file_path
stringlengths 21
207
| content
stringlengths 5
1.02M
| size
int64 5
1.02M
| lang
stringclasses 9
values | avg_line_length
float64 1.33
100
| max_line_length
int64 4
993
| alphanum_fraction
float64 0.27
0.93
|
---|---|---|---|---|---|---|
Toni-SM/skrl/docs/source/api/utils/isaacgym_utils.rst | Isaac Gym utils
===============
Utilities for ease of programming of Isaac Gym environments.
.. raw:: html
<br><hr>
Control of robotic manipulators
-------------------------------
.. raw:: html
<br>
Inverse kinematics using damped least squares method
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
This implementation attempts to unify under a single and reusable function the whole set of procedures used to calculate the inverse kinematics of a robotic manipulator shown in Isaac Gym's example: Franka IK Picking (:literal:`franka_cube_ik_osc.py`)
:math:`\Delta\theta = J^T (JJ^T + \lambda^2 I)^{-1} \, \vec{e}`
where
| :math:`\qquad \Delta\theta \;` is the change in joint angles
| :math:`\qquad J \;` is the Jacobian
| :math:`\qquad \lambda \;` is a non-zero damping constant
| :math:`\qquad \vec{e} \;` is the Cartesian pose error (position and orientation)
.. raw:: html
<br>
API
^^^
.. autofunction:: skrl.utils.isaacgym_utils.ik
.. raw:: html
<br>
Web viewer for development without X server
-------------------------------------------
This library provides an API for instantiating a lightweight web viewer useful, mostly, for designing Isaac Gym environments in remote workstations or docker containers without X server
.. raw:: html
<br>
Gestures and actions
^^^^^^^^^^^^^^^^^^^^
+---------------------------------------------------------+------------+--------------+
| Gestures / actions | Key | Mouse |
+=========================================================+============+==============+
| Orbit (rotate view around a point) | :kbd:`Alt` | Left click |
+---------------------------------------------------------+------------+--------------+
| Pan (rotate view around itself) | | Right click |
+---------------------------------------------------------+------------+--------------+
| Walk mode (move view linearly to the current alignment) | | Middle click |
+---------------------------------------------------------+------------+--------------+
| Zoom in/out | | Scroll wheel |
+---------------------------------------------------------+------------+--------------+
| Freeze view | :kbd:`V` | |
+---------------------------------------------------------+------------+--------------+
| Toggle image type (color, depth) | :kbd:`T` | |
+---------------------------------------------------------+------------+--------------+
Watch an animation of the gestures and actions in the following video
.. raw:: html
<video width="100%" controls autoplay>
<source src="https://user-images.githubusercontent.com/22400377/157323911-40729895-6175-48d2-85d7-c1b30fe0ee9c.mp4" type="video/mp4">
</video>
<br>
.. raw:: html
<br>
Requirements
^^^^^^^^^^^^
The web viewer is build on top of `Flask <https://flask.palletsprojects.com>`_ and requires the following package to be installed
.. code-block:: bash
pip install Flask
Also, to be launched in Visual Studio Code (Preview in Editor), the `Live Preview - VS Code Extension <https://marketplace.visualstudio.com/items?itemName=ms-vscode.live-server>`_ must be installed
.. raw:: html
<br>
Usage
^^^^^
.. tabs::
.. tab:: Snippet
.. literalinclude:: ../../snippets/isaacgym_utils.py
:language: python
:emphasize-lines: 4, 8, 56, 65-68
.. raw:: html
<br>
API
^^^
.. autoclass:: skrl.utils.isaacgym_utils.WebViewer
:undoc-members:
:show-inheritance:
:inherited-members:
:private-members: _route_index, _route_stream, _route_input_event, _stream
:members:
.. automethod:: __init__
| 3,868 | reStructuredText | 29.464567 | 251 | 0.478025 |
Toni-SM/skrl/docs/source/api/utils/huggingface.rst | Hugging Face integration
========================
The Hugging Face (HF) Hub is a platform for building, training, and deploying ML models, as well as accessing a variety of datasets and metrics for further analysis and validation.
.. raw:: html
<br><hr>
Integration
-----------
.. raw:: html
<br>
Download model from HF Hub
^^^^^^^^^^^^^^^^^^^^^^^^^^
Several skrl-trained models (agent checkpoints) for different environments/tasks of Gym/Gymnasium, Isaac Gym, Omniverse Isaac Gym, etc. are available in the Hugging Face Hub
These models can be used as comparison benchmarks, for collecting environment transitions in memory (for offline reinforcement learning, e.g.) or for pre-initialization of agents for performing similar tasks, among others
Visit the `skrl organization on the Hugging Face Hub <https://huggingface.co/skrl>`_ to access publicly available models!
.. raw:: html
<br>
API
---
.. autofunction:: skrl.utils.huggingface.download_model_from_huggingface
| 995 | reStructuredText | 28.294117 | 221 | 0.717588 |
Toni-SM/skrl/docs/source/api/utils/postprocessing.rst | File post-processing
====================
Utilities for processing files generated during training/evaluation.
.. raw:: html
<br><hr>
Exported memories
-----------------
This library provides an implementation for quickly loading exported memory files to inspect their contents in future post-processing steps. See the section :ref:`Library utilities (skrl.utils module) <library_utilities>` for a real use case
.. raw:: html
<br>
Usage
^^^^^
.. tabs::
.. tab:: PyTorch (.pt)
.. literalinclude:: ../../snippets/utils_postprocessing.py
:language: python
:emphasize-lines: 1, 5-6
:start-after: [start-memory_file_iterator-torch]
:end-before: [end-memory_file_iterator-torch]
.. tab:: NumPy (.npz)
.. literalinclude:: ../../snippets/utils_postprocessing.py
:language: python
:emphasize-lines: 1, 5-6
:start-after: [start-memory_file_iterator-numpy]
:end-before: [end-memory_file_iterator-numpy]
.. tab:: Comma-separated values (.csv)
.. literalinclude:: ../../snippets/utils_postprocessing.py
:language: python
:emphasize-lines: 1, 5-6
:start-after: [start-memory_file_iterator-csv]
:end-before: [end-memory_file_iterator-csv]
.. raw:: html
<br>
API
^^^
.. autoclass:: skrl.utils.postprocessing.MemoryFileIterator
:undoc-members:
:show-inheritance:
:inherited-members:
:private-members: _format_numpy, _format_torch, _format_csv
:members:
.. automethod:: __init__
.. automethod:: __iter__
.. automethod:: __next__
.. raw:: html
<br>
Tensorboard files
-----------------
This library provides an implementation for quickly loading Tensorboard files to inspect their contents in future post-processing steps. See the section :ref:`Library utilities (skrl.utils module) <library_utilities>` for a real use case
.. raw:: html
<br>
Requirements
^^^^^^^^^^^^
This utility requires the `TensorFlow <https://www.tensorflow.org/>`_ package to be installed to load and parse Tensorboard files:
.. code-block:: bash
pip install tensorflow
.. raw:: html
<br>
Usage
^^^^^
.. tabs::
.. tab:: Tensorboard (events.out.tfevents.*)
.. literalinclude:: ../../snippets/utils_postprocessing.py
:language: python
:emphasize-lines: 1, 5-7
:start-after: [start-tensorboard_file_iterator-list]
:end-before: [end-tensorboard_file_iterator-list]
.. raw:: html
<br>
API
^^^
.. autoclass:: skrl.utils.postprocessing.TensorboardFileIterator
:undoc-members:
:show-inheritance:
:inherited-members:
:members:
.. automethod:: __init__
.. automethod:: __iter__
.. automethod:: __next__
| 2,820 | reStructuredText | 22.314049 | 241 | 0.619149 |
Toni-SM/skrl/docs/source/api/utils/model_instantiators.rst | Model instantiators
===================
Utilities for quickly creating model instances.
.. raw:: html
<br><hr>
.. TODO: add snippet
.. list-table::
:header-rows: 1
* - Models
- .. centered:: |_4| |pytorch| |_4|
- .. centered:: |_4| |jax| |_4|
* - :doc:`Tabular model <../models/tabular>` (discrete domain)
- .. centered:: :math:`\square`
- .. centered:: :math:`\square`
* - :doc:`Categorical model <../models/categorical>` (discrete domain)
- .. centered:: :math:`\blacksquare`
- .. centered:: :math:`\blacksquare`
* - :doc:`Gaussian model <../models/gaussian>` (continuous domain)
- .. centered:: :math:`\blacksquare`
- .. centered:: :math:`\blacksquare`
* - :doc:`Multivariate Gaussian model <../models/multivariate_gaussian>` (continuous domain)
- .. centered:: :math:`\blacksquare`
- .. centered:: :math:`\square`
* - :doc:`Deterministic model <../models/deterministic>` (continuous domain)
- .. centered:: :math:`\blacksquare`
- .. centered:: :math:`\blacksquare`
* - :doc:`Shared model <../models/shared_model>`
- .. centered:: :math:`\blacksquare`
- .. centered:: :math:`\square`
.. raw:: html
<br>
API (PyTorch)
-------------
.. autoclass:: skrl.utils.model_instantiators.torch.Shape
.. py:property:: ONE
Flag to indicate that the model's input/output has shape (1,)
This flag is useful for the definition of critic models, where the critic's output is a scalar
.. py:property:: STATES
Flag to indicate that the model's input/output is the state (observation) space of the environment
It is an alias for :py:attr:`OBSERVATIONS`
.. py:property:: OBSERVATIONS
Flag to indicate that the model's input/output is the observation space of the environment
.. py:property:: ACTIONS
Flag to indicate that the model's input/output is the action space of the environment
.. py:property:: STATES_ACTIONS
Flag to indicate that the model's input/output is the combination (concatenation) of the state (observation) and action spaces of the environment
.. autofunction:: skrl.utils.model_instantiators.torch.categorical_model
.. autofunction:: skrl.utils.model_instantiators.torch.deterministic_model
.. autofunction:: skrl.utils.model_instantiators.torch.gaussian_model
.. autofunction:: skrl.utils.model_instantiators.torch.multivariate_gaussian_model
.. autofunction:: skrl.utils.model_instantiators.torch.shared_model
.. raw:: html
<br>
API (JAX)
---------
.. autoclass:: skrl.utils.model_instantiators.jax.Shape
.. py:property:: ONE
Flag to indicate that the model's input/output has shape (1,)
This flag is useful for the definition of critic models, where the critic's output is a scalar
.. py:property:: STATES
Flag to indicate that the model's input/output is the state (observation) space of the environment
It is an alias for :py:attr:`OBSERVATIONS`
.. py:property:: OBSERVATIONS
Flag to indicate that the model's input/output is the observation space of the environment
.. py:property:: ACTIONS
Flag to indicate that the model's input/output is the action space of the environment
.. py:property:: STATES_ACTIONS
Flag to indicate that the model's input/output is the combination (concatenation) of the state (observation) and action spaces of the environment
.. autofunction:: skrl.utils.model_instantiators.jax.categorical_model
.. autofunction:: skrl.utils.model_instantiators.jax.deterministic_model
.. autofunction:: skrl.utils.model_instantiators.jax.gaussian_model
| 3,700 | reStructuredText | 30.905172 | 153 | 0.667838 |
Toni-SM/skrl/docs/source/api/utils/omniverse_isaacgym_utils.rst | Omniverse Isaac Gym utils
=========================
Utilities for ease of programming of Omniverse Isaac Gym environments.
.. raw:: html
<br><hr>
Control of robotic manipulators
-------------------------------
.. raw:: html
<br>
Differential inverse kinematics
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
This implementation attempts to unify under a single and reusable function the whole set of procedures used to compute the inverse kinematics of a robotic manipulator, originally shown in the Isaac Orbit framework's task space controllers section, but this time for Omniverse Isaac Gym.
:math:`\Delta\theta =` :guilabel:`scale` :math:`J^\dagger \, \vec{e}`
where
| :math:`\qquad \Delta\theta \;` is the change in joint angles
| :math:`\qquad \vec{e} \;` is the Cartesian pose error (position and orientation)
| :math:`\qquad J^\dagger \;` is the pseudoinverse of the Jacobian estimated as follows:
The pseudoinverse of the Jacobian (:math:`J^\dagger`) is estimated as follows:
* Tanspose: :math:`\; J^\dagger = J^T`
* Pseduoinverse: :math:`\; J^\dagger = J^T(JJ^T)^{-1}`
* Damped least-squares: :math:`\; J^\dagger = J^T(JJ^T \, +` :guilabel:`damping`:math:`{}^2 I)^{-1}`
* Singular-vale decomposition: See `buss2004introduction <https://mathweb.ucsd.edu/~sbuss/ResearchWeb/ikmethods/iksurvey.pdf>`_ (section 6)
.. raw:: html
<br>
API
^^^
.. autofunction:: skrl.utils.omniverse_isaacgym_utils.ik
.. raw:: html
<br>
OmniIsaacGymEnvs-like environment instance
------------------------------------------
Instantiate a VecEnvBase-based object compatible with OmniIsaacGymEnvs for use outside of the OmniIsaacGymEnvs implementation.
.. raw:: html
<br>
API
^^^
.. autofunction:: skrl.utils.omniverse_isaacgym_utils.get_env_instance
| 1,764 | reStructuredText | 27.015873 | 286 | 0.665533 |
Toni-SM/skrl/docs/source/api/utils/seed.rst | Random seed
===========
Utilities for seeding the random number generators.
.. raw:: html
<br><hr>
Seed the random number generators
---------------------------------
.. raw:: html
<br>
API
^^^
.. autofunction:: skrl.utils.set_seed
| 248 | reStructuredText | 10.857142 | 51 | 0.540323 |
Toni-SM/skrl/docs/source/api/memories/random.rst | Random memory
=============
Random sampling memory
.. raw:: html
<br><hr>
Usage
-----
.. tabs::
.. group-tab:: |_4| |pytorch| |_4|
.. literalinclude:: ../../snippets/memories.py
:language: python
:emphasize-lines: 2, 5
:start-after: [start-random-torch]
:end-before: [end-random-torch]
.. group-tab:: |_4| |jax| |_4|
.. literalinclude:: ../../snippets/memories.py
:language: python
:emphasize-lines: 2, 5
:start-after: [start-random-jax]
:end-before: [end-random-jax]
.. raw:: html
<br>
API (PyTorch)
-------------
.. autoclass:: skrl.memories.torch.random.RandomMemory
:undoc-members:
:show-inheritance:
:inherited-members:
:members:
.. automethod:: __init__
.. automethod:: __len__
.. raw:: html
<br>
API (JAX)
---------
.. autoclass:: skrl.memories.jax.random.RandomMemory
:undoc-members:
:show-inheritance:
:inherited-members:
:members:
.. automethod:: __init__
.. automethod:: __len__
| 1,089 | reStructuredText | 16.580645 | 54 | 0.527089 |
Toni-SM/skrl/docs/source/intro/getting_started.rst | Getting Started
===============
In this section, you will learn how to use the various components of the **skrl** library to create reinforcement learning tasks. Whether you are a beginner or an experienced researcher, we hope this section will provide you with a solid foundation to build upon.
We recommend visiting the :doc:`Examples <examples>` to see how the components can be integrated and applied in practice. Let's get started!
.. raw:: html
<br><hr>
**Reinforcement Learning schema**
---------------------------------
**Reinforcement Learning (RL)** is a Machine Learning sub-field for decision making that allows an agent to learn from its interaction with the environment as shown in the following schema:
.. image:: ../_static/imgs/rl_schema-light.svg
:width: 100%
:align: center
:class: only-light
:alt: Reinforcement Learning schema
.. image:: ../_static/imgs/rl_schema-dark.svg
:width: 100%
:align: center
:class: only-dark
:alt: Reinforcement Learning schema
.. raw:: html
<br>
At each step (also called timestep) of interaction with the environment, the agent sees an observation :math:`o_t` of the complete description of the state :math:`s_t \in S` of the environment. Then, it decides which action :math:`a_t \in A` to take from the action space using a policy. The environment, which changes in response to the agent's action (or by itself), returns a reward signal :math:`r_t = R(s_t, a_t, s_{t+1})` as a measure of how good or bad the action was that moved it to its new state :math:`s_{t+1}`. The agent aims to maximize the cumulative reward (discounted or not by a factor :math:`\gamma \in (0,1]`) by adjusting the policy's behaviour via some optimization algorithm.
**From this schema, this section is intended to guide in the creation of a RL system using skrl**
.. raw:: html
<br>
1. Environments
^^^^^^^^^^^^^^^
The environment plays a fundamental role in the definition of the RL schema. For example, the selection of the agent depends strongly on the observation and action space nature. There are several interfaces to interact with the environments such as OpenAI Gym / Farama Gymnasium or DeepMind. However, each of them has a different API and work with non-compatible data types.
* For **single-agent** environments, skrl offers a function to **wrap environments** based on the Gym/Gymnasium, DeepMind, NVIDIA Isaac Gym, Isaac Orbit and Omniverse Isaac Gym interfaces, among others. The wrapped environments provide, to the library components, a common interface (based on Gym/Gymnasium) as shown in the following figure. Refer to the :doc:`Wrapping (single-agent) <../api/envs/wrapping>` section for more information.
* For **multi-agent** environments, skrl offers a function to **wrap environments** based on the PettingZoo and Bi-DexHands interfaces. The wrapped environments provide, to the library components, a common interface (based on PettingZoo) as shown in the following figure. Refer to the :doc:`Wrapping (multi-agents) <../api/envs/multi_agents_wrapping>` section for more information.
.. tabs::
.. group-tab:: Single-agent environments
.. image:: ../_static/imgs/wrapping-light.svg
:width: 100%
:align: center
:class: only-light
:alt: Environment wrapping
.. image:: ../_static/imgs/wrapping-dark.svg
:width: 100%
:align: center
:class: only-dark
:alt: Environment wrapping
.. group-tab:: Multi-agent environments
.. image:: ../_static/imgs/multi_agent_wrapping-light.svg
:width: 100%
:align: center
:class: only-light
:alt: Environment wrapping
.. image:: ../_static/imgs/multi_agent_wrapping-dark.svg
:width: 100%
:align: center
:class: only-dark
:alt: Environment wrapping
Among the methods and properties defined in the wrapped environment, the observation and action spaces are one of the most relevant for instantiating other library components. The following code snippets show how to load and wrap environments based on the supported interfaces:
.. tabs::
.. group-tab:: Single-agent environments
.. tabs::
.. tab:: Omniverse Isaac Gym
.. tabs::
.. tab:: Common environment
.. tabs::
.. group-tab:: |_4| |pytorch| |_4|
.. literalinclude:: ../snippets/wrapping.py
:language: python
:start-after: [pytorch-start-omniverse-isaacgym]
:end-before: [pytorch-end-omniverse-isaacgym]
.. group-tab:: |_4| |jax| |_4|
.. literalinclude:: ../snippets/wrapping.py
:language: python
:start-after: [jax-start-omniverse-isaacgym]
:end-before: [jax-end-omniverse-isaacgym]
.. tab:: Multi-threaded environment
.. tabs::
.. group-tab:: |_4| |pytorch| |_4|
.. literalinclude:: ../snippets/wrapping.py
:language: python
:start-after: [pytorch-start-omniverse-isaacgym-mt]
:end-before: [pytorch-end-omniverse-isaacgym-mt]
.. group-tab:: |_4| |jax| |_4|
.. literalinclude:: ../snippets/wrapping.py
:language: python
:start-after: [jax-start-omniverse-isaacgym-mt]
:end-before: [jax-end-omniverse-isaacgym-mt]
.. tab:: Isaac Orbit
.. tabs::
.. group-tab:: |_4| |pytorch| |_4|
.. literalinclude:: ../snippets/wrapping.py
:language: python
:start-after: [pytorch-start-isaac-orbit]
:end-before: [pytorch-end-isaac-orbit]
.. group-tab:: |_4| |jax| |_4|
.. literalinclude:: ../snippets/wrapping.py
:language: python
:start-after: [jax-start-isaac-orbit]
:end-before: [jax-end-isaac-orbit]
.. tab:: Isaac Gym
.. tabs::
.. tab:: Preview 4 (isaacgymenvs.make)
.. tabs::
.. group-tab:: |_4| |pytorch| |_4|
.. literalinclude:: ../snippets/wrapping.py
:language: python
:start-after: [pytorch-start-isaacgym-preview4-make]
:end-before: [pytorch-end-isaacgym-preview4-make]
.. group-tab:: |_4| |jax| |_4|
.. literalinclude:: ../snippets/wrapping.py
:language: python
:start-after: [jax-start-isaacgym-preview4-make]
:end-before: [jax-end-isaacgym-preview4-make]
.. tab:: Preview 4
.. tabs::
.. group-tab:: |_4| |pytorch| |_4|
.. literalinclude:: ../snippets/wrapping.py
:language: python
:start-after: [pytorch-start-isaacgym-preview4]
:end-before: [pytorch-end-isaacgym-preview4]
.. group-tab:: |_4| |jax| |_4|
.. literalinclude:: ../snippets/wrapping.py
:language: python
:start-after: [jax-start-isaacgym-preview4]
:end-before: [jax-end-isaacgym-preview4]
.. tab:: Preview 3
.. tabs::
.. group-tab:: |_4| |pytorch| |_4|
.. literalinclude:: ../snippets/wrapping.py
:language: python
:start-after: [pytorch-start-isaacgym-preview3]
:end-before: [pytorch-end-isaacgym-preview3]
.. group-tab:: |_4| |jax| |_4|
.. literalinclude:: ../snippets/wrapping.py
:language: python
:start-after: [jax-start-isaacgym-preview3]
:end-before: [jax-end-isaacgym-preview3]
.. tab:: Preview 2
.. tabs::
.. group-tab:: |_4| |pytorch| |_4|
.. literalinclude:: ../snippets/wrapping.py
:language: python
:start-after: [pytorch-start-isaacgym-preview2]
:end-before: [pytorch-end-isaacgym-preview2]
.. group-tab:: |_4| |jax| |_4|
.. literalinclude:: ../snippets/wrapping.py
:language: python
:start-after: [jax-start-isaacgym-preview2]
:end-before: [jax-end-isaacgym-preview2]
.. tab:: Gym / Gymnasium
.. tabs::
.. tab:: Gym
.. tabs::
.. tab:: Single environment
.. tabs::
.. group-tab:: |_4| |pytorch| |_4|
.. literalinclude:: ../snippets/wrapping.py
:language: python
:start-after: [pytorch-start-gym]
:end-before: [pytorch-end-gym]
.. group-tab:: |_4| |jax| |_4|
.. literalinclude:: ../snippets/wrapping.py
:language: python
:start-after: [jax-start-gym]
:end-before: [jax-end-gym]
.. tab:: Vectorized environment
Visit the Gym documentation (`Vector <https://www.gymlibrary.dev/api/vector>`__) for more information about the creation and usage of vectorized environments
.. tabs::
.. group-tab:: |_4| |pytorch| |_4|
.. literalinclude:: ../snippets/wrapping.py
:language: python
:start-after: [pytorch-start-gym-vectorized]
:end-before: [pytorch-end-gym-vectorized]
.. group-tab:: |_4| |jax| |_4|
.. literalinclude:: ../snippets/wrapping.py
:language: python
:start-after: [jax-start-gym-vectorized]
:end-before: [jax-end-gym-vectorized]
.. tab:: Gymnasium
.. tabs::
.. tab:: Single environment
.. tabs::
.. group-tab:: |_4| |pytorch| |_4|
.. literalinclude:: ../snippets/wrapping.py
:language: python
:start-after: [pytorch-start-gymnasium]
:end-before: [pytorch-end-gymnasium]
.. group-tab:: |_4| |jax| |_4|
.. literalinclude:: ../snippets/wrapping.py
:language: python
:start-after: [jax-start-gymnasium]
:end-before: [jax-end-gymnasium]
.. tab:: Vectorized environment
Visit the Gymnasium documentation (`Vector <https://gymnasium.farama.org/api/vector>`__) for more information about the creation and usage of vectorized environments
.. tabs::
.. group-tab:: |_4| |pytorch| |_4|
.. literalinclude:: ../snippets/wrapping.py
:language: python
:start-after: [pytorch-start-gymnasium-vectorized]
:end-before: [pytorch-end-gymnasium-vectorized]
.. group-tab:: |_4| |jax| |_4|
.. literalinclude:: ../snippets/wrapping.py
:language: python
:start-after: [jax-start-gymnasium-vectorized]
:end-before: [jax-end-gymnasium-vectorized]
.. tab:: DeepMind
.. tabs::
.. group-tab:: |_4| |pytorch| |_4|
.. literalinclude:: ../snippets/wrapping.py
:language: python
:start-after: [pytorch-start-deepmind]
:end-before: [pytorch-end-deepmind]
.. .. group-tab:: |_4| |jax| |_4|
.. .. literalinclude:: ../snippets/wrapping.py
.. :language: python
.. :start-after: [jax-start-deepmind]
.. :end-before: [jax-end-deepmind]
.. tab:: robosuite
.. tabs::
.. group-tab:: |_4| |pytorch| |_4|
.. literalinclude:: ../snippets/wrapping.py
:language: python
:start-after: [pytorch-start-robosuite]
:end-before: [pytorch-end-robosuite]
.. .. group-tab:: |_4| |jax| |_4|
.. .. literalinclude:: ../snippets/wrapping.py
.. :language: python
.. :start-after: [jax-start-robosuite]
.. :end-before: [jax-end-robosuite]
.. group-tab:: Multi-agent environments
.. tabs::
.. tab:: PettingZoo
.. tabs::
.. group-tab:: |_4| |pytorch| |_4|
.. literalinclude:: ../snippets/wrapping.py
:language: python
:start-after: [start-pettingzoo-torch]
:end-before: [end-pettingzoo-torch]
.. group-tab:: |_4| |jax| |_4|
.. literalinclude:: ../snippets/wrapping.py
:language: python
:start-after: [start-pettingzoo-jax]
:end-before: [end-pettingzoo-jax]
.. tab:: Bi-DexHands
.. tabs::
.. group-tab:: |_4| |pytorch| |_4|
.. literalinclude:: ../snippets/wrapping.py
:language: python
:start-after: [start-bidexhands-torch]
:end-before: [end-bidexhands-torch]
.. group-tab:: |_4| |jax| |_4|
.. literalinclude:: ../snippets/wrapping.py
:language: python
:start-after: [start-bidexhands-jax]
:end-before: [end-bidexhands-jax]
Once the environment is known (and instantiated), it is time to configure and instantiate the agent. Agents are composed, apart from the optimization algorithm, by several components, such as memories, models or noises, for example, according to their nature. The following subsections focus on those components.
.. raw:: html
<br>
2. Memories
^^^^^^^^^^^
Memories are storage components that allow agents to collect and use/reuse recent or past experiences or other types of information. These can be large in size (such as replay buffers used by off-policy algorithms like DDPG, TD3 or SAC) or small in size (such as rollout buffers used by on-policy algorithms like PPO or TRPO to store batches that are discarded after use).
skrl provides **generic memory definitions** that are not tied to the agent implementation and can be used for any role, such as rollout or replay buffers. They are empty shells when they are instantiated and the agents are in charge of defining the tensors according to their needs. The total space occupied is the product of the memory size (:literal:`memory_size`), the number of environments (:literal:`num_envs`) obtained from the wrapped environment and the data size for each defined tensor.
The following code snippets show how to instantiate a memory:
.. tabs::
.. tab:: Random memory
.. tabs::
.. group-tab:: |_4| |pytorch| |_4|
.. literalinclude:: ../snippets/memories.py
:language: python
:start-after: [start-random-torch]
:end-before: [end-random-torch]
.. group-tab:: |_4| |jax| |_4|
.. literalinclude:: ../snippets/memories.py
:language: python
:start-after: [start-random-jax]
:end-before: [end-random-jax]
Memories are passed directly to the agent constructor, if required (not all agents require memory, such as Q-learning or SARSA, for example), during its instantiation under the argument :literal:`memory` (or :literal:`memories`).
.. raw:: html
<br>
3. Models
^^^^^^^^^
Models are the agents' brains. Agents can have one or several models and their parameters are adjusted via the optimization algorithms.
In contrast to other libraries, skrl does not provide predefined models or fixed templates (this practice tends to hide and reduce the flexibility of the system, forcing developers to deeply inspect the code to make even small changes). Nevertheless, **helper mixins are provided** to create discrete and continuous (stochastic or deterministic) models with the library. In this way, the user/researcher should only be concerned with the definition of the approximation functions (tables or artificial neural networks), having all the control in his hands. The following diagrams show the concept of the provided mixins.
.. tabs::
.. tab:: Categorical
.. image:: ../_static/imgs/model_categorical-light.svg
:width: 100%
:align: center
:class: only-light
:alt: Categorical model
.. image:: ../_static/imgs/model_categorical-dark.svg
:width: 100%
:align: center
:class: only-dark
:alt: Categorical model
.. raw:: html
<br>
For snippets refer to :ref:`Categorical <models_categorical>` model section.
.. tab:: Gaussian
.. image:: ../_static/imgs/model_gaussian-light.svg
:width: 100%
:align: center
:class: only-light
:alt: Gaussian model
.. image:: ../_static/imgs/model_gaussian-dark.svg
:width: 100%
:align: center
:class: only-dark
:alt: Gaussian model
.. raw:: html
<br>
For snippets refer to :ref:`Gaussian <models_gaussian>` model section.
.. tab:: Multivariate Gaussian
.. image:: ../_static/imgs/model_multivariate_gaussian-light.svg
:width: 100%
:align: center
:class: only-light
:alt: Multivariate Gaussian model
.. image:: ../_static/imgs/model_multivariate_gaussian-dark.svg
:width: 100%
:align: center
:class: only-dark
:alt: Multivariate Gaussian model
.. raw:: html
<br>
For snippets refer to :ref:`Multivariate Gaussian <models_multivariate_gaussian>` model section.
.. tab:: Deterministic
.. image:: ../_static/imgs/model_deterministic-light.svg
:width: 60%
:align: center
:class: only-light
:alt: Deterministic model
.. image:: ../_static/imgs/model_deterministic-dark.svg
:width: 60%
:align: center
:class: only-dark
:alt: Deterministic model
.. raw:: html
<br>
For snippets refer to :ref:`Deterministic <models_deterministic>` model section.
.. tab:: Tabular
For snippets refer to :ref:`Tabular <models_tabular>` model section.
Models must be collected in a dictionary and passed to the agent constructor during its instantiation under the argument :literal:`models`. The dictionary keys are specific to each agent. Visit their respective documentation for more details (under *Spaces and models* section). For example, the PPO agent requires the policy and value models as shown below:
.. code-block:: python
models = {}
models["policy"] = Policy(env.observation_space, env.action_space, env.device)
models["value"] = Value(env.observation_space, env.action_space, env.device)
Models can be saved and loaded to and from the file system. However, the recommended practice for loading checkpoints to perform evaluations or continue an interrupted training is through the agents (they include, in addition to the models, other components and internal instances such as preprocessors or optimizers). Refer to :doc:`Saving, loading and logging <data>` (under *Checkpoints* section) for more information.
.. raw:: html
<br>
4. Noises
^^^^^^^^^
Noise plays a fundamental role in the exploration stage, especially in agents of a deterministic nature, such as DDPG or TD3, for example.
skrl provides, as part of its resources, **classes for instantiating noises** as shown in the following code snippets. Refer to :doc:`Noises <../api/resources/noises>` documentation for more information. Noise instances are passed to the agents in their respective configuration dictionaries.
.. tabs::
.. tab:: Gaussian noise
.. tabs::
.. group-tab:: |_4| |pytorch| |_4|
.. literalinclude:: ../snippets/noises.py
:language: python
:start-after: [torch-start-gaussian]
:end-before: [torch-end-gaussian]
.. group-tab:: |_4| |jax| |_4|
.. literalinclude:: ../snippets/noises.py
:language: python
:start-after: [jax-start-gaussian]
:end-before: [jax-end-gaussian]
.. tab:: Ornstein-Uhlenbeck noise
.. tabs::
.. group-tab:: |_4| |pytorch| |_4|
.. literalinclude:: ../snippets/noises.py
:language: python
:start-after: [torch-start-ornstein-uhlenbeck]
:end-before: [torch-end-ornstein-uhlenbeck]
.. group-tab:: |_4| |jax| |_4|
.. literalinclude:: ../snippets/noises.py
:language: python
:start-after: [jax-start-ornstein-uhlenbeck]
:end-before: [jax-end-ornstein-uhlenbeck]
.. raw:: html
<br>
5. Learning rate schedulers
^^^^^^^^^^^^^^^^^^^^^^^^^^^
Learning rate schedulers help RL system converge faster and improve accuracy.
skrl **supports all PyTorch and JAX (Optax) learning rate schedulers** and provides, as part of its resources, **additional schedulers**. Refer to :doc:`Learning rate schedulers <../api/resources/schedulers>` documentation for more information.
Learning rate schedulers classes and their respective arguments (except the :literal:`optimizer` argument) are passed to the agents in their respective configuration dictionaries. For example, for the PPO agent, one of the schedulers can be configured as shown below:
.. tabs::
.. group-tab:: |_4| |pytorch| |_4|
.. code-block:: python
from skrl.agents.torch.ppo import PPO, PPO_DEFAULT_CONFIG
from skrl.resources.schedulers.torch import KLAdaptiveRL
agent_cfg = PPO_DEFAULT_CONFIG.copy()
agent_cfg["learning_rate_scheduler"] = KLAdaptiveRL
agent_cfg["learning_rate_scheduler_kwargs"] = {"kl_threshold": 0.008}
.. group-tab:: |_4| |jax| |_4|
.. code-block:: python
from skrl.agents.jax.ppo import PPO, PPO_DEFAULT_CONFIG
from skrl.resources.schedulers.jax import KLAdaptiveRL
agent_cfg = PPO_DEFAULT_CONFIG.copy()
agent_cfg["learning_rate_scheduler"] = KLAdaptiveRL
agent_cfg["learning_rate_scheduler_kwargs"] = {"kl_threshold": 0.008}
.. raw:: html
<br>
6. Preprocessors
^^^^^^^^^^^^^^^^
Data preprocessing can help increase the accuracy and efficiency of training by cleaning or making data suitable for machine learning models.
skrl provides, as part of its resources, **preprocessors** classes. Refer to :doc:`Preprocessors <../api/resources/preprocessors>` documentation for more information.
Preprocessors classes and their respective arguments are passed to the agents in their respective configuration dictionaries. For example, for the PPO agent, one of the preprocessors can be configured as shown below:
.. tabs::
.. group-tab:: |_4| |pytorch| |_4|
.. code-block:: python
from skrl.agents.torch.ppo import PPO, PPO_DEFAULT_CONFIG
from skrl.resources.preprocessors.torch import RunningStandardScaler
agent_cfg["state_preprocessor"] = RunningStandardScaler
agent_cfg["state_preprocessor_kwargs"] = {"size": env.observation_space, "device": env.device}
agent_cfg["value_preprocessor"] = RunningStandardScaler
agent_cfg["value_preprocessor_kwargs"] = {"size": 1, "device": env.device}
.. group-tab:: |_4| |jax| |_4|
.. code-block:: python
from skrl.agents.jax.ppo import PPO, PPO_DEFAULT_CONFIG
from skrl.resources.preprocessors.jax import RunningStandardScaler
agent_cfg["state_preprocessor"] = RunningStandardScaler
agent_cfg["state_preprocessor_kwargs"] = {"size": env.observation_space, "device": env.device}
agent_cfg["value_preprocessor"] = RunningStandardScaler
agent_cfg["value_preprocessor_kwargs"] = {"size": 1, "device": env.device}
.. raw:: html
<br>
7. Agents
^^^^^^^^^
Agents are the components in charge of decision making. They are much more than models (neural networks, for example) and include the optimization algorithms that compute the optimal policy
skrl provides **state-of-the-art agents**. Their implementations are focused on readability, simplicity and code transparency. Each agent is implemented independently even when two or more agents may contain code in common. Refer to each agent documentation for more information about the models and spaces they support, their respective configurations, algorithm details and more.
.. tabs::
.. group-tab:: (Single) agents
* :doc:`Advantage Actor Critic <../api/agents/a2c>` (**A2C**)
* :doc:`Adversarial Motion Priors <../api/agents/amp>` (**AMP**)
* :doc:`Cross-Entropy Method <../api/agents/cem>` (**CEM**)
* :doc:`Deep Deterministic Policy Gradient <../api/agents/ddpg>` (**DDPG**)
* :doc:`Double Deep Q-Network <../api/agents/ddqn>` (**DDQN**)
* :doc:`Deep Q-Network <../api/agents/dqn>` (**DQN**)
* :doc:`Proximal Policy Optimization <../api/agents/ppo>` (**PPO**)
* :doc:`Q-learning <../api/agents/q_learning>` (**Q-learning**)
* :doc:`Robust Policy Optimization <../api/agents/rpo>` (**RPO**)
* :doc:`Soft Actor-Critic <../api/agents/sac>` (**SAC**)
* :doc:`State Action Reward State Action <../api/agents/sarsa>` (**SARSA**)
* :doc:`Twin-Delayed DDPG <../api/agents/td3>` (**TD3**)
* :doc:`Trust Region Policy Optimization <../api/agents/trpo>` (**TRPO**)
.. group-tab:: Multi-agents
* :doc:`Independent Proximal Policy Optimization <../api/multi_agents/ippo>` (**IPPO**)
* :doc:`Multi-Agent Proximal Policy Optimization <../api/multi_agents/mappo>` (**MAPPO**)
Agents generally expect, as arguments, the following components: models and memories, as well as the following variables: observation and action spaces, the device where their logic is executed and a configuration dictionary with hyperparameters and other values. The remaining components, mentioned above, are collected through the configuration dictionary. For example, the PPO agent can be instantiated as follows:
.. tabs::
.. group-tab:: |_4| |pytorch| |_4|
.. code-block:: python
from skrl.agents.torch.ppo import PPO
agent = PPO(models=models, # models dict
memory=memory, # memory instance, or None if not required
cfg=agent_cfg, # configuration dict (preprocessors, learning rate schedulers, etc.)
observation_space=env.observation_space,
action_space=env.action_space,
device=env.device)
.. group-tab:: |_4| |jax| |_4|
.. code-block:: python
from skrl.agents.jax.ppo import PPO
agent = PPO(models=models, # models dict
memory=memory, # memory instance, or None if not required
cfg=agent_cfg, # configuration dict (preprocessors, learning rate schedulers, etc.)
observation_space=env.observation_space,
action_space=env.action_space,
device=env.device)
Agents can be saved and loaded to and from the file system. This is the **recommended practice** for loading checkpoints to perform evaluations or to continue interrupted training (since they include, in addition to models, other internal components and instances such as preprocessors or optimizers). Refer to :doc:`Saving, loading and logging <data>` (under *Checkpoints* section) for more information.
.. raw:: html
<br>
8. Trainers
^^^^^^^^^^^
Now that both actors, the environment and the agent, are instantiated, it is time to put the RL system in motion.
skrl offers classes (called :doc:`Trainers <../api/trainers>`) that manage the interaction cycle between the environment and the agent(s) for both: training and evaluation. These classes also enable the simultaneous training and evaluation of several agents by scope (subsets of environments among all available environments), which may or may not share resources, in the same run.
The following code snippets show how to train/evaluate RL systems using the available trainers:
.. tabs::
.. tab:: Sequential trainer
.. tabs::
.. group-tab:: |_4| |pytorch| |_4|
.. literalinclude:: ../snippets/trainer.py
:language: python
:start-after: [pytorch-start-sequential]
:end-before: [pytorch-end-sequential]
.. group-tab:: |_4| |jax| |_4|
.. literalinclude:: ../snippets/trainer.py
:language: python
:start-after: [jax-start-sequential]
:end-before: [jax-end-sequential]
.. tab:: Parallel trainer
.. tabs::
.. group-tab:: |_4| |pytorch| |_4|
.. literalinclude:: ../snippets/trainer.py
:language: python
:start-after: [pytorch-start-parallel]
:end-before: [pytorch-end-parallel]
.. tab:: Step trainer
.. tabs::
.. group-tab:: |_4| |pytorch| |_4|
.. literalinclude:: ../snippets/trainer.py
:language: python
:start-after: [pytorch-start-step]
:end-before: [pytorch-end-step]
.. group-tab:: |_4| |jax| |_4|
.. literalinclude:: ../snippets/trainer.py
:language: python
:start-after: [jax-start-step]
:end-before: [jax-end-step]
.. raw:: html
<br><hr>
**What's next?**
Visit the :doc:`Examples <examples>` section for training and evaluation demonstrations with different environment interfaces and highlighted practices, among others.
| 33,642 | reStructuredText | 41.586076 | 697 | 0.539891 |
Toni-SM/skrl/docs/source/intro/installation.rst | Installation
============
In this section, you will find the steps to install the library, troubleshoot known issues, review changes between versions, and more.
.. raw:: html
<br><hr>
**Dependencies**
----------------
**skrl** requires Python 3.6 or higher and the following libraries (they will be installed automatically):
* `gym <https://www.gymlibrary.dev>`_ / `gymnasium <https://gymnasium.farama.org/>`_
* `tqdm <https://tqdm.github.io>`_
* `packaging <https://packaging.pypa.io>`_
* `tensorboard <https://www.tensorflow.org/tensorboard>`_
Machine learning (ML) framework
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
According to the specific ML frameworks, the following libraries are required:
PyTorch
"""""""
* `torch <https://pytorch.org>`_ 1.9.0 or higher
JAX
"""
* `jax <https://jax.readthedocs.io>`_ / `jaxlib <https://jax.readthedocs.io>`_ 0.4.3 or higher
* `flax <https://flax.readthedocs.io>`_
* `optax <https://optax.readthedocs.io>`_
.. raw:: html
<br><hr>
**Library Installation**
------------------------
.. raw:: html
<br>
Python Package Index (PyPI)
^^^^^^^^^^^^^^^^^^^^^^^^^^^
To install **skrl** with pip, execute:
.. tabs::
.. group-tab:: |_4| |pytorch| |_4|
.. code-block:: bash
pip install skrl["torch"]
.. group-tab:: |_4| |jax| |_4|
.. warning::
JAX installs its CPU version if not specified. For GPU/TPU versions visit the JAX
`installation <https://github.com/google/jax#installation>`_ page before proceeding with the steps described below.
.. code-block:: bash
pip install skrl["jax"]
.. group-tab:: All ML frameworks
.. code-block:: bash
pip install skrl["all"]
.. group-tab:: No ML framework
.. code-block:: bash
pip install skrl
.. raw:: html
<br>
GitHub repository
^^^^^^^^^^^^^^^^^
Clone or download the library from its GitHub repository (https://github.com/Toni-SM/skrl)
.. code-block:: bash
git clone https://github.com/Toni-SM/skrl.git
cd skrl
* **Install in editable/development mode** (links the package to its original location allowing any modifications to be reflected directly in its Python environment)
.. tabs::
.. group-tab:: |_4| |pytorch| |_4|
.. code-block:: bash
pip install -e .["torch"]
.. group-tab:: |_4| |jax| |_4|
.. warning::
JAX installs its CPU version if not specified. For GPU/TPU versions visit the JAX
`installation <https://github.com/google/jax#installation>`_ page before proceeding with the steps described below.
.. code-block:: bash
pip install -e .["jax"]
.. group-tab:: All ML frameworks
.. code-block:: bash
pip install -e .["all"]
.. group-tab:: No ML framework
.. code-block:: bash
pip install -e .
* **Install in the current Python site-packages directory** (modifications to the code downloaded from GitHub will not be reflected in your Python environment)
.. tabs::
.. group-tab:: |_4| |pytorch| |_4|
.. code-block:: bash
pip install .["torch"]
.. group-tab:: |_4| |jax| |_4|
.. warning::
JAX installs its CPU version if not specified. For GPU/TPU versions visit the JAX
`installation <https://github.com/google/jax#installation>`_ page before proceeding with the steps described below.
.. code-block:: bash
pip install .["jax"]
.. group-tab:: All ML frameworks
.. code-block:: bash
pip install .["all"]
.. group-tab:: No ML framework
.. code-block:: bash
pip install .
.. raw:: html
<br><hr>
**Discussions and issues**
--------------------------
To ask questions or discuss about the library visit skrl's GitHub discussions
.. centered:: https://github.com/Toni-SM/skrl/discussions
Bug detection and/or correction, feature requests and everything else are more than welcome. Come on, open a new issue!
.. centered:: https://github.com/Toni-SM/skrl/issues
.. raw:: html
<br><hr>
**Known issues and troubleshooting**
------------------------------------
1. When using the parallel trainer with PyTorch 1.12.
See PyTorch issue `#80831 <https://github.com/pytorch/pytorch/issues/80831>`_
.. code-block:: text
AttributeError: 'Adam' object has no attribute '_warned_capturable_if_run_uncaptured'
2. When installing the JAX version in Python 3.7 (e.g. OmniIsaacGymEnvs or Isaac Orbit on Isaac Sim 2022.2.1 and earlier).
.. code-block:: text
ERROR: Ignored the following versions that require a different python version: 0.4.0 Requires-Python >=3.8; ...
ERROR: Could not find a version that satisfies the requirement jax>=0.4.3; extra == "jax" (from skrl[jax]) (from versions: 0.0, ..., 0.3.25)
ERROR: No matching distribution found for jax>=0.4.3; extra == "jax"
JAX support for Python 3.7 is up to version 0.3.25, while skrl requires ``jax>=0.4.3``.
Furthermore, ``jaxlib<=0.3.25`` builds are only available up to NVIDIA CUDA 11 and cuDNN 8.2 versions.
However, it is possible to use **skrl** under these circumstances, subject to the following points:
* Install JAX, Flax and Optax manually using ``pip install jax flax optax`` and ignore the installation errors for skrl.
* The ``jax.Device = jax.xla.Device`` statement is required by skrl to support ``jax<0.4.3``.
* Overload models ``__hash__`` method to avoid :literal:`"TypeError: Failed to hash Flax Module"`.
3. When training/evaluating using JAX in Python 3.7 (e.g. OmniIsaacGymEnvs or Isaac Orbit on Isaac Sim 2022.2.1 and earlier).
.. code-block:: text
TypeError: Failed to hash Flax Module. The module probably contains unhashable attributes
Overload the ``__hash__`` method for each defined model to avoid this issue:
.. code-block:: python
def __hash__(self):
return id(self)
4. When training/evaluating using JAX with the NVIDIA Isaac Gym Preview, Isaac Orbit or Omniverse Isaac Gym environments.
.. code-block:: text
PxgCudaDeviceMemoryAllocator fail to allocate memory XXXXXX bytes!! Result = 2
RuntimeError: CUDA error: an illegal memory access was encountered
NVIDIA environments use PyTorch as a backend, and both PyTorch (for CUDA kernels, among others) and JAX preallocate GPU memory,
which can lead to out-of-memory (OOM) problems. Reduce or disable GPU memory preallocation as indicated in JAX
`GPU memory allocation <https://jax.readthedocs.io/en/latest/gpu_memory_allocation.html>`_ to avoid this issue. For example:
.. code-block:: bash
export XLA_PYTHON_CLIENT_MEM_FRACTION=.50 # lowering preallocated GPU memory to 50%
.. raw:: html
<br><hr>
**Changelog**
-------------
.. literalinclude:: ../../../CHANGELOG.md
:language: markdown
| 7,135 | reStructuredText | 27.544 | 165 | 0.61808 |
Toni-SM/skrl/docs/source/intro/examples.rst | Examples
========
In this section, you will find a variety of examples that demonstrate how to use this library to solve reinforcement learning tasks. With the knowledge and skills you gain from trying these examples, you will be well on your way to using this library to solve your reinforcement learning problems.
.. note::
It is recommended to use the table of contents in the right sidebar for better navigation.
.. raw:: html
<br><hr>
**Gymnasium / Gym**
-------------------
.. raw:: html
<br>
Gymnasium / Gym environments
^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Training/evaluation of an agent in `Gymnasium <https://gymnasium.farama.org/>`_ / `Gym <https://www.gymlibrary.dev/>`_ environments (**one agent, one environment**)
.. image:: ../_static/imgs/example_gym.png
:width: 100%
:align: center
:alt: Gymnasium / Gym environments
.. raw:: html
<br>
**Benchmark results** are listed in `Benchmark results #32 (Gymnasium/Gym) <https://github.com/Toni-SM/skrl/discussions/32#discussioncomment-4308370>`_
.. tabs::
.. group-tab:: Gymnasium
.. tabs::
.. group-tab:: |_4| |pytorch| |_4|
.. list-table::
:align: left
:header-rows: 1
:stub-columns: 1
:class: nowrap
* - Environment
- Script
- Checkpoint (Hugging Face)
* - CartPole
- :download:`torch_gymnasium_cartpole_cem.py <../examples/gymnasium/torch_gymnasium_cartpole_cem.py>`
|br| :download:`torch_gymnasium_cartpole_dqn.py <../examples/gymnasium/torch_gymnasium_cartpole_dqn.py>`
-
* - FrozenLake
- :download:`torch_gymnasium_frozen_lake_q_learning.py <../examples/gymnasium/torch_gymnasium_frozen_lake_q_learning.py>`
-
* - Pendulum
- :download:`torch_gymnasium_pendulum_ddpg.py <../examples/gymnasium/torch_gymnasium_pendulum_ddpg.py>`
|br| :download:`torch_gymnasium_pendulum_ppo.py <../examples/gymnasium/torch_gymnasium_pendulum_ppo.py>`
|br| :download:`torch_gymnasium_pendulum_sac.py <../examples/gymnasium/torch_gymnasium_pendulum_sac.py>`
|br| :download:`torch_gymnasium_pendulum_td3.py <../examples/gymnasium/torch_gymnasium_pendulum_td3.py>`
-
* - PendulumNoVel*
|br| (RNN / GRU / LSTM)
- :download:`torch_gymnasium_pendulumnovel_ddpg_rnn.py <../examples/gymnasium/torch_gymnasium_pendulumnovel_ddpg_rnn.py>`
|br| :download:`torch_gymnasium_pendulumnovel_ddpg_gru.py <../examples/gymnasium/torch_gymnasium_pendulumnovel_ddpg_gru.py>`
|br| :download:`torch_gymnasium_pendulumnovel_ddpg_lstm.py <../examples/gymnasium/torch_gymnasium_pendulumnovel_ddpg_lstm.py>`
|br| :download:`torch_gymnasium_pendulumnovel_ppo_rnn.py <../examples/gymnasium/torch_gymnasium_pendulumnovel_ppo_rnn.py>`
|br| :download:`torch_gymnasium_pendulumnovel_ppo_gru.py <../examples/gymnasium/torch_gymnasium_pendulumnovel_ppo_gru.py>`
|br| :download:`torch_gymnasium_pendulumnovel_ppo_lstm.py <../examples/gymnasium/torch_gymnasium_pendulumnovel_ppo_lstm.py>`
|br| :download:`torch_gymnasium_pendulumnovel_sac_rnn.py <../examples/gymnasium/torch_gymnasium_pendulumnovel_sac_rnn.py>`
|br| :download:`torch_gymnasium_pendulumnovel_sac_gru.py <../examples/gymnasium/torch_gymnasium_pendulumnovel_sac_gru.py>`
|br| :download:`torch_gymnasium_pendulumnovel_sac_lstm.py <../examples/gymnasium/torch_gymnasium_pendulumnovel_sac_lstm.py>`
|br| :download:`torch_gymnasium_pendulumnovel_td3_rnn.py <../examples/gymnasium/torch_gymnasium_pendulumnovel_td3_rnn.py>`
|br| :download:`torch_gymnasium_pendulumnovel_td3_gru.py <../examples/gymnasium/torch_gymnasium_pendulumnovel_td3_gru.py>`
|br| :download:`torch_gymnasium_pendulumnovel_td3_lstm.py <../examples/gymnasium/torch_gymnasium_pendulumnovel_td3_lstm.py>`
-
* - Taxi
- :download:`torch_gymnasium_taxi_sarsa.py <../examples/gymnasium/torch_gymnasium_taxi_sarsa.py>`
-
.. group-tab:: |_4| |jax| |_4|
.. list-table::
:align: left
:header-rows: 1
:stub-columns: 1
:class: nowrap
* - Environment
- Script
- Checkpoint (Hugging Face)
* - CartPole
- :download:`jax_gymnasium_cartpole_cem.py <../examples/gymnasium/jax_gymnasium_cartpole_cem.py>`
|br| :download:`jax_gymnasium_cartpole_dqn.py <../examples/gymnasium/jax_gymnasium_cartpole_dqn.py>`
-
* - FrozenLake
-
-
* - Pendulum
- :download:`jax_gymnasium_pendulum_ddpg.py <../examples/gymnasium/jax_gymnasium_pendulum_ddpg.py>`
|br| :download:`jax_gymnasium_pendulum_ppo.py <../examples/gymnasium/jax_gymnasium_pendulum_ppo.py>`
|br| :download:`jax_gymnasium_pendulum_sac.py <../examples/gymnasium/jax_gymnasium_pendulum_sac.py>`
|br| :download:`jax_gymnasium_pendulum_td3.py <../examples/gymnasium/jax_gymnasium_pendulum_td3.py>`
-
* - PendulumNoVel*
|br| (RNN / GRU / LSTM)
- |br|
|br|
|br|
|br|
|br|
|br|
|br|
|br|
|br|
|br|
|br|
|br|
-
* - Taxi
-
-
.. note::
(*) The examples use a wrapper around the original environment to mask the velocity in the observation. The intention is to make the MDP partially observable and to show the capabilities of recurrent neural networks
.. group-tab:: Gym
.. tabs::
.. group-tab:: |_4| |pytorch| |_4|
.. list-table::
:align: left
:header-rows: 1
:stub-columns: 1
:class: nowrap
* - Environment
- Script
- Checkpoint (Hugging Face)
* - CartPole
- :download:`torch_gym_cartpole_cem.py <../examples/gym/torch_gym_cartpole_cem.py>`
|br| :download:`torch_gym_cartpole_dqn.py <../examples/gym/torch_gym_cartpole_dqn.py>`
-
* - FrozenLake
- :download:`torch_gym_frozen_lake_q_learning.py <../examples/gym/torch_gym_frozen_lake_q_learning.py>`
-
* - Pendulum
- :download:`torch_gym_pendulum_ddpg.py <../examples/gym/torch_gym_pendulum_ddpg.py>`
|br| :download:`torch_gym_pendulum_ppo.py <../examples/gym/torch_gym_pendulum_ppo.py>`
|br| :download:`torch_gym_pendulum_sac.py <../examples/gym/torch_gym_pendulum_sac.py>`
|br| :download:`torch_gym_pendulum_td3.py <../examples/gym/torch_gym_pendulum_td3.py>`
-
* - PendulumNoVel*
|br| (RNN / GRU / LSTM)
- :download:`torch_gym_pendulumnovel_ddpg_rnn.py <../examples/gym/torch_gym_pendulumnovel_ddpg_rnn.py>`
|br| :download:`torch_gym_pendulumnovel_ddpg_gru.py <../examples/gym/torch_gym_pendulumnovel_ddpg_gru.py>`
|br| :download:`torch_gym_pendulumnovel_ddpg_lstm.py <../examples/gym/torch_gym_pendulumnovel_ddpg_lstm.py>`
|br| :download:`torch_gym_pendulumnovel_ppo_rnn.py <../examples/gym/torch_gym_pendulumnovel_ppo_rnn.py>`
|br| :download:`torch_gym_pendulumnovel_ppo_gru.py <../examples/gym/torch_gym_pendulumnovel_ppo_gru.py>`
|br| :download:`torch_gym_pendulumnovel_ppo_lstm.py <../examples/gym/torch_gym_pendulumnovel_ppo_lstm.py>`
|br| :download:`torch_gym_pendulumnovel_sac_rnn.py <../examples/gym/torch_gym_pendulumnovel_sac_rnn.py>`
|br| :download:`torch_gym_pendulumnovel_sac_gru.py <../examples/gym/torch_gym_pendulumnovel_sac_gru.py>`
|br| :download:`torch_gym_pendulumnovel_sac_lstm.py <../examples/gym/torch_gym_pendulumnovel_sac_lstm.py>`
|br| :download:`torch_gym_pendulumnovel_td3_rnn.py <../examples/gym/torch_gym_pendulumnovel_td3_rnn.py>`
|br| :download:`torch_gym_pendulumnovel_td3_gru.py <../examples/gym/torch_gym_pendulumnovel_td3_gru.py>`
|br| :download:`torch_gym_pendulumnovel_td3_lstm.py <../examples/gym/torch_gym_pendulumnovel_td3_lstm.py>`
-
* - Taxi
- :download:`torch_gym_taxi_sarsa.py <../examples/gym/torch_gym_taxi_sarsa.py>`
-
.. group-tab:: |_4| |jax| |_4|
.. list-table::
:align: left
:header-rows: 1
:stub-columns: 1
:class: nowrap
* - Environment
- Script
- Checkpoint (Hugging Face)
* - CartPole
- :download:`jax_gym_cartpole_cem.py <../examples/gym/jax_gym_cartpole_cem.py>`
|br| :download:`jax_gym_cartpole_dqn.py <../examples/gym/jax_gym_cartpole_dqn.py>`
-
* - FrozenLake
-
-
* - Pendulum
- :download:`jax_gym_pendulum_ddpg.py <../examples/gym/jax_gym_pendulum_ddpg.py>`
|br| :download:`jax_gym_pendulum_ppo.py <../examples/gym/jax_gym_pendulum_ppo.py>`
|br| :download:`jax_gym_pendulum_sac.py <../examples/gym/jax_gym_pendulum_sac.py>`
|br| :download:`jax_gym_pendulum_td3.py <../examples/gym/jax_gym_pendulum_td3.py>`
-
* - PendulumNoVel*
|br| (RNN / GRU / LSTM)
- |br|
|br|
|br|
|br|
|br|
|br|
|br|
|br|
|br|
|br|
|br|
|br|
-
* - Taxi
-
-
.. note::
(*) The examples use a wrapper around the original environment to mask the velocity in the observation. The intention is to make the MDP partially observable and to show the capabilities of recurrent neural networks
.. raw:: html
<br>
Gymnasium / Gym vectorized environments
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Training/evaluation of an agent in `Gymnasium <https://gymnasium.farama.org/>`_ / `Gym <https://www.gymlibrary.dev/>`_ vectorized environments (**one agent, multiple independent copies of the same environment in parallel**)
.. tabs::
.. group-tab:: Gymnasium
.. tabs::
.. group-tab:: |_4| |pytorch| |_4|
.. list-table::
:align: left
:header-rows: 1
:stub-columns: 1
:class: nowrap
* - Environment
- Script
- Checkpoint (Hugging Face)
* - CartPole
- :download:`torch_gymnasium_cartpole_vector_dqn.py <../examples/gymnasium/torch_gymnasium_cartpole_vector_dqn.py>`
-
* - FrozenLake
- :download:`torch_gymnasium_frozen_lake_vector_q_learning.py <../examples/gymnasium/torch_gymnasium_frozen_lake_vector_q_learning.py>`
-
* - Pendulum
- :download:`torch_gymnasium_pendulum_vector_ddpg.py <../examples/gymnasium/torch_gymnasium_pendulum_vector_ddpg.py>`
-
* - Taxi
- :download:`torch_gymnasium_taxi_vector_sarsa.py <../examples/gymnasium/torch_gymnasium_taxi_vector_sarsa.py>`
-
.. group-tab:: |_4| |jax| |_4|
.. list-table::
:align: left
:header-rows: 1
:stub-columns: 1
:class: nowrap
* - Environment
- Script
- Checkpoint (Hugging Face)
* - CartPole
- :download:`jax_gymnasium_cartpole_vector_dqn.py <../examples/gymnasium/jax_gymnasium_cartpole_vector_dqn.py>`
-
* - FrozenLake
-
-
* - Pendulum
- :download:`jax_gymnasium_pendulum_vector_ddpg.py <../examples/gymnasium/jax_gymnasium_pendulum_vector_ddpg.py>`
-
* - Taxi
-
-
.. group-tab:: Gym
.. tabs::
.. group-tab:: |_4| |pytorch| |_4|
.. list-table::
:align: left
:header-rows: 1
:stub-columns: 1
:class: nowrap
* - Environment
- Script
- Checkpoint (Hugging Face)
* - CartPole
- :download:`torch_gym_cartpole_vector_dqn.py <../examples/gym/torch_gym_cartpole_vector_dqn.py>`
-
* - FrozenLake
- :download:`torch_gym_frozen_lake_vector_q_learning.py <../examples/gym/torch_gym_frozen_lake_vector_q_learning.py>`
-
* - Pendulum
- :download:`torch_gym_pendulum_vector_ddpg.py <../examples/gym/torch_gym_pendulum_vector_ddpg.py>`
-
* - Taxi
- :download:`torch_gym_taxi_vector_sarsa.py <../examples/gym/torch_gym_taxi_vector_sarsa.py>`
-
.. group-tab:: |_4| |jax| |_4|
.. list-table::
:align: left
:header-rows: 1
:stub-columns: 1
:class: nowrap
* - Environment
- Script
- Checkpoint (Hugging Face)
* - CartPole
- :download:`jax_gym_cartpole_vector_dqn.py <../examples/gym/jax_gym_cartpole_vector_dqn.py>`
-
* - FrozenLake
-
-
* - Pendulum
- :download:`jax_gym_pendulum_vector_ddpg.py <../examples/gym/jax_gym_pendulum_vector_ddpg.py>`
-
* - Taxi
-
-
.. raw:: html
<br>
Shimmy (API conversion)
^^^^^^^^^^^^^^^^^^^^^^^
The following examples show the training in several popular environments (Atari, DeepMind Control and OpenAI Gym) that have been converted to the Gymnasium API using the `Shimmy <https://github.com/Farama-Foundation/Shimmy>`_ (API conversion tool) package
.. image:: ../_static/imgs/example_shimmy.png
:width: 100%
:align: center
:alt: Shimmy (API conversion)
.. note::
From **skrl**, no extra implementation is necessary, since it fully supports Gymnasium API
.. note::
Because the Gymnasium API requires that the rendering mode be specified during the initialization of the environment, it is not enough to set the :literal:`headless` option in the trainer configuration to render the environment. In this case, it is necessary to call the :literal:`gymnasium.make` function using :literal:`render_mode="human"` or any other supported option
.. tabs::
.. group-tab:: |_4| |pytorch| |_4|
.. list-table::
:align: left
:header-rows: 1
:stub-columns: 1
:class: nowrap
* - Environment
- Script
- Checkpoint (Hugging Face)
* - Atari: Pong
- :download:`torch_shimmy_atari_pong_dqn.py <../examples/shimmy/torch_shimmy_atari_pong_dqn.py>`
-
* - DeepMind: Acrobot
- :download:`torch_shimmy_dm_control_acrobot_swingup_sparse_sac.py <../examples/shimmy/torch_shimmy_dm_control_acrobot_swingup_sparse_sac.py>`
-
* - Gym-v21 compatibility
- :download:`torch_shimmy_openai_gym_compatibility_pendulum_ddpg.py <../examples/shimmy/torch_shimmy_openai_gym_compatibility_pendulum_ddpg.py>`
-
.. group-tab:: |_4| |jax| |_4|
.. list-table::
:align: left
:header-rows: 1
:stub-columns: 1
:class: nowrap
* - Environment
- Script
- Checkpoint (Hugging Face)
* - Atari: Pong
- :download:`jax_shimmy_atari_pong_dqn.py <../examples/shimmy/jax_shimmy_atari_pong_dqn.py>`
-
* - DeepMind: Acrobot
- :download:`jax_shimmy_dm_control_acrobot_swingup_sparse_sac.py <../examples/shimmy/jax_shimmy_dm_control_acrobot_swingup_sparse_sac.py>`
-
* - Gym-v21 compatibility
- :download:`jax_shimmy_openai_gym_compatibility_pendulum_ddpg.py <../examples/shimmy/jax_shimmy_openai_gym_compatibility_pendulum_ddpg.py>`
-
.. raw:: html
<br><hr>
**Other supported APIs**
------------------------
.. raw:: html
<br>
DeepMind environments
^^^^^^^^^^^^^^^^^^^^^
These examples perform the training of one agent in a DeepMind environment (**one agent, one environment**)
.. image:: ../_static/imgs/example_deepmind.png
:width: 100%
:align: center
:alt: DeepMind environments
.. raw:: html
<br>
.. tabs::
.. group-tab:: |_4| |pytorch| |_4|
.. list-table::
:align: left
:header-rows: 1
:stub-columns: 1
:class: nowrap
* - Environment
- Script
- Checkpoint (Hugging Face)
* - Control: Cartpole SwingUp
- :download:`dm_suite_cartpole_swingup_ddpg.py <../examples/deepmind/dm_suite_cartpole_swingup_ddpg.py>`
-
* - Manipulation: Reach Site Vision
- :download:`dm_manipulation_stack_sac.py <../examples/deepmind/dm_manipulation_stack_sac.py>`
-
.. raw:: html
<br>
Robosuite environments
^^^^^^^^^^^^^^^^^^^^^^
These examples perform the training of one agent in a robosuite environment (**one agent, one environment**)
.. image:: ../_static/imgs/example_robosuite.png
:width: 50%
:align: center
:alt: robosuite environments
.. raw:: html
<br>
.. tabs::
.. group-tab:: |_4| |pytorch| |_4|
.. list-table::
:align: left
:header-rows: 1
:stub-columns: 1
:class: nowrap
* - Environment
- Script
- Checkpoint (Hugging Face)
* - TwoArmLift
- :download:`td3_robosuite_two_arm_lift.py <../examples/robosuite/td3_robosuite_two_arm_lift.py>`
-
.. raw:: html
<br>
Bi-DexHands environments
^^^^^^^^^^^^^^^^^^^^^^^^
Multi-agent training/evaluation in a `Bi-DexHands <https://github.com/PKU-MARL/DexterousHands>`_ environment
.. image:: ../_static/imgs/example_bidexhands.png
:width: 75%
:align: center
:alt: bidexhands environments
.. raw:: html
<br>
.. tabs::
.. group-tab:: |_4| |pytorch| |_4|
.. list-table::
:align: left
:header-rows: 1
:stub-columns: 1
:class: nowrap
* - Environment
- Script
- Checkpoint (Hugging Face)
* - ShadowHandOver
- :download:`torch_bidexhands_shadow_hand_over_ippo.py <../examples/bidexhands/torch_bidexhands_shadow_hand_over_ippo.py>`
|br| :download:`torch_bidexhands_shadow_hand_over_mappo.py <../examples/bidexhands/torch_bidexhands_shadow_hand_over_mappo.py>`
-
.. group-tab:: |_4| |jax| |_4|
.. list-table::
:align: left
:header-rows: 1
:stub-columns: 1
:class: nowrap
* - Environment
- Script
- Checkpoint (Hugging Face)
* - ShadowHandOver
- :download:`jax_bidexhands_shadow_hand_over_ippo.py <../examples/bidexhands/jax_bidexhands_shadow_hand_over_ippo.py>`
|br| :download:`jax_bidexhands_shadow_hand_over_mappo.py <../examples/bidexhands/jax_bidexhands_shadow_hand_over_mappo.py>`
-
.. raw:: html
<br><hr>
**NVIDIA Isaac Gym preview**
----------------------------
.. raw:: html
<br>
Isaac Gym environments
^^^^^^^^^^^^^^^^^^^^^^
Training/evaluation of an agent in `Isaac Gym environments <https://github.com/NVIDIA-Omniverse/IsaacGymEnvs>`_ (**one agent, multiple environments**)
.. image:: ../_static/imgs/example_isaacgym.png
:width: 100%
:align: center
:alt: Isaac Gym environments
.. raw:: html
<br>
The agent configuration is mapped, as far as possible, from the `IsaacGymEnvs configuration <https://github.com/NVIDIA-Omniverse/IsaacGymEnvs/tree/main/isaacgymenvs/cfg/train>`_ for rl_games. Shared models or separated models are used depending on the value of the :literal:`network.separate` variable. The following list shows the mapping between the two configurations:
.. tabs::
.. tab:: PPO
.. code-block:: bash
# memory
memory_size = horizon_length
# agent
rollouts = horizon_length
learning_epochs = mini_epochs
mini_batches = horizon_length * num_actors / minibatch_size
discount_factor = gamma
lambda = tau
learning_rate = learning_rate
learning_rate_scheduler = skrl.resources.schedulers.torch.KLAdaptiveLR
learning_rate_scheduler_kwargs = {"kl_threshold": kl_threshold}
random_timesteps = 0
learning_starts = 0
grad_norm_clip = grad_norm # if truncate_grads else 0
ratio_clip = e_clip
value_clip = e_clip
clip_predicted_values = clip_value
entropy_loss_scale = entropy_coef
value_loss_scale = 0.5 * critic_coef
kl_threshold = 0
rewards_shaper = lambda rewards, timestep, timesteps: rewards * scale_value
# trainer
timesteps = horizon_length * max_epochs
.. tab:: DDPG / TD3 / SAC
.. code-block:: bash
# memory
memory_size = replay_buffer_size / num_envs
# agent
gradient_steps = 1
batch_size = batch_size
discount_factor = gamma
polyak = critic_tau
actor_learning_rate = actor_lr
critic_learning_rate = critic_lr
random_timesteps = num_warmup_steps * num_steps_per_episode
learning_starts = num_warmup_steps * num_steps_per_episode
grad_norm_clip = 0
learn_entropy = learnable_temperature
entropy_learning_rate = alpha_lr
initial_entropy_value = init_alpha
target_entropy = None
rewards_shaper = lambda rewards, timestep, timesteps: rewards * scale_value
# trainer
timesteps = num_steps_per_episode * max_epochs
**Benchmark results** are listed in `Benchmark results #32 (NVIDIA Isaac Gym) <https://github.com/Toni-SM/skrl/discussions/32#discussioncomment-3774815>`_
.. note::
Isaac Gym environments implement a functionality to get their configuration from the command line. Because of this feature, setting the :literal:`headless` option from the trainer configuration will not work. In this case, it is necessary to invoke the scripts as follows: :literal:`python script.py headless=True` for Isaac Gym environments (preview 3 and preview 4) or :literal:`python script.py --headless` for Isaac Gym environments (preview 2)
.. tabs::
.. group-tab:: |_4| |pytorch| |_4|
.. list-table::
:align: left
:header-rows: 1
:stub-columns: 1
:class: nowrap
* - Environment
- Script
- Checkpoint (Hugging Face)
* - AllegroHand
- :download:`torch_allegro_hand_ppo.py <../examples/isaacgym/torch_allegro_hand_ppo.py>`
-
* - Ant
- :download:`torch_ant_ppo.py <../examples/isaacgym/torch_ant_ppo.py>`
|br| :download:`torch_ant_ddpg.py <../examples/isaacgym/torch_ant_ddpg.py>`
|br| :download:`torch_ant_td3.py <../examples/isaacgym/torch_ant_td3.py>`
|br| :download:`torch_ant_sac.py <../examples/isaacgym/torch_ant_sac.py>`
- `IsaacGymEnvs-Ant-PPO <https://huggingface.co/skrl/IsaacGymEnvs-Ant-PPO>`_
|br|
|br|
|br|
* - Anymal
- :download:`torch_anymal_ppo.py <../examples/isaacgym/torch_anymal_ppo.py>`
- `IsaacGymEnvs-Anymal-PPO <https://huggingface.co/skrl/IsaacGymEnvs-Anymal-PPO>`_
* - AnymalTerrain
- :download:`torch_anymal_terrain_ppo.py <../examples/isaacgym/torch_anymal_terrain_ppo.py>`
- `IsaacGymEnvs-AnymalTerrain-PPO <https://huggingface.co/skrl/IsaacGymEnvs-AnymalTerrain-PPO>`_
* - BallBalance
- :download:`torch_ball_balance_ppo.py <../examples/isaacgym/torch_ball_balance_ppo.py>`
- `IsaacGymEnvs-BallBalance-PPO <https://huggingface.co/skrl/IsaacGymEnvs-BallBalance-PPO>`_
* - Cartpole
- :download:`torch_cartpole_ppo.py <../examples/isaacgym/torch_cartpole_ppo.py>`
- `IsaacGymEnvs-Cartpole-PPO <https://huggingface.co/skrl/IsaacGymEnvs-Cartpole-PPO>`_
* - FactoryTaskNutBoltPick
- :download:`torch_factory_task_nut_bolt_pick_ppo.py <../examples/isaacgym/torch_factory_task_nut_bolt_pick_ppo.py>`
- `IsaacGymEnvs-FactoryTaskNutBoltPick-PPO <https://huggingface.co/skrl/IsaacGymEnvs-FactoryTaskNutBoltPick-PPO>`_
* - FactoryTaskNutBoltPlace
- :download:`torch_factory_task_nut_bolt_place_ppo.py <../examples/isaacgym/torch_factory_task_nut_bolt_place_ppo.py>`
- `IsaacGymEnvs-FactoryTaskNutBoltPlace-PPO <https://huggingface.co/skrl/IsaacGymEnvs-FactoryTaskNutBoltPlace-PPO>`_
* - FactoryTaskNutBoltScrew
- :download:`torch_factory_task_nut_bolt_screw_ppo.py <../examples/isaacgym/torch_factory_task_nut_bolt_screw_ppo.py>`
- `IsaacGymEnvs-FactoryTaskNutBoltScrew-PPO <https://huggingface.co/skrl/IsaacGymEnvs-FactoryTaskNutBoltScrew-PPO>`_
* - FrankaCabinet
- :download:`torch_franka_cabinet_ppo.py <../examples/isaacgym/torch_franka_cabinet_ppo.py>`
- `IsaacGymEnvs-FrankaCabinet-PPO <https://huggingface.co/skrl/IsaacGymEnvs-FrankaCabinet-PPO>`_
* - FrankaCubeStack
- :download:`torch_franka_cube_stack_ppo.py <../examples/isaacgym/torch_franka_cube_stack_ppo.py>`
-
* - Humanoid
- :download:`torch_humanoid_ppo.py <../examples/isaacgym/torch_humanoid_ppo.py>`
- `IsaacGymEnvs-Humanoid-PPO <https://huggingface.co/skrl/IsaacGymEnvs-Humanoid-PPO>`_
* - Humanoid-AMP
- :download:`torch_humanoid_amp.py <../examples/isaacgym/torch_humanoid_amp.py>`
-
* - Ingenuity
- :download:`torch_ingenuity_ppo.py <../examples/isaacgym/torch_ingenuity_ppo.py>`
- `IsaacGymEnvs-Ingenuity-PPO <https://huggingface.co/skrl/IsaacGymEnvs-Ingenuity-PPO>`_
* - Quadcopter
- :download:`torch_quadcopter_ppo.py <../examples/isaacgym/torch_quadcopter_ppo.py>`
- `IsaacGymEnvs-Quadcopter-PPO <https://huggingface.co/skrl/IsaacGymEnvs-Quadcopter-PPO>`_
* - ShadowHand
- :download:`torch_shadow_hand_ppo.py <../examples/isaacgym/torch_shadow_hand_ppo.py>`
-
* - Trifinger
- :download:`torch_trifinger_ppo.py <../examples/isaacgym/torch_trifinger_ppo.py>`
-
.. group-tab:: |_4| |jax| |_4|
.. list-table::
:align: left
:header-rows: 1
:stub-columns: 1
:class: nowrap
* - Environment
- Script
- Checkpoint (Hugging Face)
* - AllegroHand
- :download:`jax_allegro_hand_ppo.py <../examples/isaacgym/jax_allegro_hand_ppo.py>`
-
* - Ant
- :download:`jax_ant_ppo.py <../examples/isaacgym/jax_ant_ppo.py>`
|br| :download:`jax_ant_ddpg.py <../examples/isaacgym/jax_ant_ddpg.py>`
|br| :download:`jax_ant_td3.py <../examples/isaacgym/jax_ant_sac.py>`
|br| :download:`jax_ant_sac.py <../examples/isaacgym/jax_ant_td3.py>`
- `IsaacGymEnvs-Ant-PPO <https://huggingface.co/skrl/IsaacGymEnvs-Ant-PPO>`_
|br|
|br|
|br|
* - Anymal
- :download:`jax_anymal_ppo.py <../examples/isaacgym/jax_anymal_ppo.py>`
- `IsaacGymEnvs-Anymal-PPO <https://huggingface.co/skrl/IsaacGymEnvs-Anymal-PPO>`_
* - AnymalTerrain
- :download:`jax_anymal_terrain_ppo.py <../examples/isaacgym/jax_anymal_terrain_ppo.py>`
- `IsaacGymEnvs-AnymalTerrain-PPO <https://huggingface.co/skrl/IsaacGymEnvs-AnymalTerrain-PPO>`_
* - BallBalance
- :download:`jax_ball_balance_ppo.py <../examples/isaacgym/jax_ball_balance_ppo.py>`
- `IsaacGymEnvs-BallBalance-PPO <https://huggingface.co/skrl/IsaacGymEnvs-BallBalance-PPO>`_
* - Cartpole
- :download:`jax_cartpole_ppo.py <../examples/isaacgym/jax_cartpole_ppo.py>`
- `IsaacGymEnvs-Cartpole-PPO <https://huggingface.co/skrl/IsaacGymEnvs-Cartpole-PPO>`_
* - FactoryTaskNutBoltPick
- :download:`jax_factory_task_nut_bolt_pick_ppo.py <../examples/isaacgym/jax_factory_task_nut_bolt_pick_ppo.py>`
- `IsaacGymEnvs-FactoryTaskNutBoltPick-PPO <https://huggingface.co/skrl/IsaacGymEnvs-FactoryTaskNutBoltPick-PPO>`_
* - FactoryTaskNutBoltPlace
- :download:`jax_factory_task_nut_bolt_place_ppo.py <../examples/isaacgym/jax_factory_task_nut_bolt_place_ppo.py>`
- `IsaacGymEnvs-FactoryTaskNutBoltPlace-PPO <https://huggingface.co/skrl/IsaacGymEnvs-FactoryTaskNutBoltPlace-PPO>`_
* - FactoryTaskNutBoltScrew
- :download:`jax_factory_task_nut_bolt_screw_ppo.py <../examples/isaacgym/jax_factory_task_nut_bolt_screw_ppo.py>`
- `IsaacGymEnvs-FactoryTaskNutBoltScrew-PPO <https://huggingface.co/skrl/IsaacGymEnvs-FactoryTaskNutBoltScrew-PPO>`_
* - FrankaCabinet
- :download:`jax_franka_cabinet_ppo.py <../examples/isaacgym/jax_franka_cabinet_ppo.py>`
- `IsaacGymEnvs-FrankaCabinet-PPO <https://huggingface.co/skrl/IsaacGymEnvs-FrankaCabinet-PPO>`_
* - FrankaCubeStack
- :download:`jax_franka_cube_stack_ppo.py <../examples/isaacgym/jax_franka_cube_stack_ppo.py>`
-
* - Humanoid
- :download:`jax_humanoid_ppo.py <../examples/isaacgym/jax_humanoid_ppo.py>`
- `IsaacGymEnvs-Humanoid-PPO <https://huggingface.co/skrl/IsaacGymEnvs-Humanoid-PPO>`_
* - Humanoid-AMP
-
-
* - Ingenuity
- :download:`jax_ingenuity_ppo.py <../examples/isaacgym/jax_ingenuity_ppo.py>`
- `IsaacGymEnvs-Ingenuity-PPO <https://huggingface.co/skrl/IsaacGymEnvs-Ingenuity-PPO>`_
* - Quadcopter
- :download:`jax_quadcopter_ppo.py <../examples/isaacgym/jax_quadcopter_ppo.py>`
- `IsaacGymEnvs-Quadcopter-PPO <https://huggingface.co/skrl/IsaacGymEnvs-Quadcopter-PPO>`_
* - ShadowHand
- :download:`jax_shadow_hand_ppo.py <../examples/isaacgym/jax_shadow_hand_ppo.py>`
-
* - Trifinger
- :download:`jax_trifinger_ppo.py <../examples/isaacgym/jax_trifinger_ppo.py>`
-
.. raw:: html
<br><hr>
**NVIDIA Isaac Orbit**
----------------------
.. raw:: html
<br>
Isaac Orbit environments
^^^^^^^^^^^^^^^^^^^^^^^^
Training/evaluation of an agent in `Isaac Orbit environments <https://isaac-orbit.github.io/orbit/index.html>`_ (**one agent, multiple environments**)
.. image:: ../_static/imgs/example_isaac_orbit.png
:width: 100%
:align: center
:alt: Isaac Orbit environments
.. raw:: html
<br>
The agent configuration is mapped, as far as possible, from the `Isaac Orbit configuration <https://github.com/NVIDIA-Omniverse/Orbit/tree/main/source/extensions/omni.isaac.orbit_envs/data/rl_games>`_ for rl_games. Shared models or separated models are used depending on the value of the :literal:`network.separate` variable. The following list shows the mapping between the two configurations:
.. tabs::
.. tab:: PPO
.. code-block:: bash
# memory
memory_size = horizon_length
# agent
rollouts = horizon_length
learning_epochs = mini_epochs
mini_batches = horizon_length * num_actors / minibatch_size
discount_factor = gamma
lambda = tau
learning_rate = learning_rate
learning_rate_scheduler = skrl.resources.schedulers.torch.KLAdaptiveLR
learning_rate_scheduler_kwargs = {"kl_threshold": kl_threshold}
random_timesteps = 0
learning_starts = 0
grad_norm_clip = grad_norm # if truncate_grads else 0
ratio_clip = e_clip
value_clip = e_clip
clip_predicted_values = clip_value
entropy_loss_scale = entropy_coef
value_loss_scale = 0.5 * critic_coef
kl_threshold = 0
rewards_shaper = lambda rewards, timestep, timesteps: rewards * scale_value
# trainer
timesteps = horizon_length * max_epochs
.. tab:: DDPG / TD3 / SAC
.. code-block:: bash
# memory
memory_size = replay_buffer_size / num_envs
# agent
gradient_steps = 1
batch_size = batch_size
discount_factor = gamma
polyak = critic_tau
actor_learning_rate = actor_lr
critic_learning_rate = critic_lr
random_timesteps = num_warmup_steps * num_steps_per_episode
learning_starts = num_warmup_steps * num_steps_per_episode
grad_norm_clip = 0
learn_entropy = learnable_temperature
entropy_learning_rate = alpha_lr
initial_entropy_value = init_alpha
target_entropy = None
rewards_shaper = lambda rewards, timestep, timesteps: rewards * scale_value
# trainer
timesteps = num_steps_per_episode * max_epochs
**Benchmark results** are listed in `Benchmark results #32 (NVIDIA Isaac Orbit) <https://github.com/Toni-SM/skrl/discussions/32#discussioncomment-4744446>`_
.. note::
Isaac Orbit environments implement a functionality to get their configuration from the command line. Because of this feature, setting the :literal:`headless` option from the trainer configuration will not work. In this case, it is necessary to invoke the scripts as follows: :literal:`orbit -p script.py --headless`
.. tabs::
.. group-tab:: |_4| |pytorch| |_4|
.. list-table::
:align: left
:header-rows: 1
:stub-columns: 1
:class: nowrap
* - Environment
- Script
- Checkpoint (Hugging Face)
* - Isaac-Ant-v0
- :download:`torch_ant_ppo.py <../examples/isaacorbit/torch_ant_ppo.py>`
|br| :download:`torch_ant_ddpg.py <../examples/isaacorbit/torch_ant_ddpg.py>`
|br| :download:`torch_ant_td3.py <../examples/isaacorbit/torch_ant_td3.py>`
|br| :download:`torch_ant_sac.py <../examples/isaacorbit/torch_ant_sac.py>`
- `IsaacOrbit-Isaac-Ant-v0-PPO <https://huggingface.co/skrl/IsaacOrbit-Isaac-Ant-v0-PPO>`_
|br|
|br|
|br|
* - Isaac-Cartpole-v0
- :download:`torch_cartpole_ppo.py <../examples/isaacorbit/torch_cartpole_ppo.py>`
- `IsaacOrbit-Isaac-Cartpole-v0-PPO <https://huggingface.co/skrl/IsaacOrbit-Isaac-Cartpole-v0-PPO>`_
* - Isaac-Humanoid-v0
- :download:`torch_humanoid_ppo.py <../examples/isaacorbit/torch_humanoid_ppo.py>`
- `IsaacOrbit-Isaac-Humanoid-v0-PPO <https://huggingface.co/skrl/IsaacOrbit-Isaac-Humanoid-v0-PPO>`_
* - Isaac-Lift-Franka-v0
- :download:`torch_lift_franka_ppo.py <../examples/isaacorbit/torch_lift_franka_ppo.py>`
- `IsaacOrbit-Isaac-Lift-Franka-v0-PPO <https://huggingface.co/skrl/IsaacOrbit-Isaac-Lift-Franka-v0-PPO>`_
* - Isaac-Reach-Franka-v0
- :download:`torch_reach_franka_ppo.py <../examples/isaacorbit/torch_reach_franka_ppo.py>`
- `IsaacOrbit-Isaac-Reach-Franka-v0-PPO <https://huggingface.co/skrl/IsaacOrbit-Isaac-Reach-Franka-v0-PPO>`_
* - Isaac-Velocity-Anymal-C-v0
- :download:`torch_velocity_anymal_c_ppo.py <../examples/isaacorbit/torch_velocity_anymal_c_ppo.py>`
-
.. group-tab:: |_4| |jax| |_4|
.. list-table::
:align: left
:header-rows: 1
:stub-columns: 1
:class: nowrap
* - Environment
- Script
- Checkpoint (Hugging Face)
* - Isaac-Ant-v0
- :download:`jax_ant_ppo.py <../examples/isaacorbit/jax_ant_ppo.py>`
|br| :download:`jax_ant_ddpg.py <../examples/isaacorbit/jax_ant_ddpg.py>`
|br| :download:`jax_ant_td3.py <../examples/isaacorbit/jax_ant_td3.py>`
|br| :download:`jax_ant_sac.py <../examples/isaacorbit/jax_ant_sac.py>`
- `IsaacOrbit-Isaac-Ant-v0-PPO <https://huggingface.co/skrl/IsaacOrbit-Isaac-Ant-v0-PPO>`_
|br|
|br|
|br|
* - Isaac-Cartpole-v0
- :download:`jax_cartpole_ppo.py <../examples/isaacorbit/jax_cartpole_ppo.py>`
- `IsaacOrbit-Isaac-Cartpole-v0-PPO <https://huggingface.co/skrl/IsaacOrbit-Isaac-Cartpole-v0-PPO>`_
* - Isaac-Humanoid-v0
- :download:`jax_humanoid_ppo.py <../examples/isaacorbit/jax_humanoid_ppo.py>`
- `IsaacOrbit-Isaac-Humanoid-v0-PPO <https://huggingface.co/skrl/IsaacOrbit-Isaac-Humanoid-v0-PPO>`_
* - Isaac-Lift-Franka-v0
- :download:`jax_lift_franka_ppo.py <../examples/isaacorbit/jax_lift_franka_ppo.py>`
- `IsaacOrbit-Isaac-Lift-Franka-v0-PPO <https://huggingface.co/skrl/IsaacOrbit-Isaac-Lift-Franka-v0-PPO>`_
* - Isaac-Reach-Franka-v0
- :download:`jax_reach_franka_ppo.py <../examples/isaacorbit/jax_reach_franka_ppo.py>`
- `IsaacOrbit-Isaac-Reach-Franka-v0-PPO <https://huggingface.co/skrl/IsaacOrbit-Isaac-Reach-Franka-v0-PPO>`_
* - Isaac-Velocity-Anymal-C-v0
- :download:`jax_velocity_anymal_c_ppo.py <../examples/isaacorbit/jax_velocity_anymal_c_ppo.py>`
-
.. raw:: html
<br><hr>
**NVIDIA Omniverse Isaac Gym**
------------------------------
.. raw:: html
<br>
Omniverse Isaac Gym environments (OIGE)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Training/evaluation of an agent in `Omniverse Isaac Gym environments (OIGE) <https://github.com/NVIDIA-Omniverse/OmniIsaacGymEnvs>`_ (**one agent, multiple environments**)
.. image:: ../_static/imgs/example_omniverse_isaacgym.png
:width: 100%
:align: center
:alt: Isaac Gym environments
.. raw:: html
<br>
The agent configuration is mapped, as far as possible, from the `OmniIsaacGymEnvs configuration <https://github.com/NVIDIA-Omniverse/OmniIsaacGymEnvs/tree/main/omniisaacgymenvs/cfg/train>`_ for rl_games. Shared models or separated models are used depending on the value of the :literal:`network.separate` variable. The following list shows the mapping between the two configurations:
.. tabs::
.. tab:: PPO
.. code-block:: bash
# memory
memory_size = horizon_length
# agent
rollouts = horizon_length
learning_epochs = mini_epochs
mini_batches = horizon_length * num_actors / minibatch_size
discount_factor = gamma
lambda = tau
learning_rate = learning_rate
learning_rate_scheduler = skrl.resources.schedulers.torch.KLAdaptiveLR
learning_rate_scheduler_kwargs = {"kl_threshold": kl_threshold}
random_timesteps = 0
learning_starts = 0
grad_norm_clip = grad_norm # if truncate_grads else 0
ratio_clip = e_clip
value_clip = e_clip
clip_predicted_values = clip_value
entropy_loss_scale = entropy_coef
value_loss_scale = 0.5 * critic_coef
kl_threshold = 0
rewards_shaper = lambda rewards, timestep, timesteps: rewards * scale_value
# trainer
timesteps = horizon_length * max_epochs
.. tab:: DDPG / TD3 / SAC
.. code-block:: bash
# memory
memory_size = replay_buffer_size / num_envs
# agent
gradient_steps = 1
batch_size = batch_size
discount_factor = gamma
polyak = critic_tau
actor_learning_rate = actor_lr
critic_learning_rate = critic_lr
random_timesteps = num_warmup_steps * num_steps_per_episode
learning_starts = num_warmup_steps * num_steps_per_episode
grad_norm_clip = 0
learn_entropy = learnable_temperature
entropy_learning_rate = alpha_lr
initial_entropy_value = init_alpha
target_entropy = None
rewards_shaper = lambda rewards, timestep, timesteps: rewards * scale_value
# trainer
timesteps = num_steps_per_episode * max_epochs
**Benchmark results** are listed in `Benchmark results #32 (NVIDIA Omniverse Isaac Gym) <https://github.com/Toni-SM/skrl/discussions/32#discussioncomment-3774894>`_
.. note::
Omniverse Isaac Gym environments implement a functionality to get their configuration from the command line. Because of this feature, setting the :literal:`headless` option from the trainer configuration will not work. In this case, it is necessary to invoke the scripts as follows: :literal:`python script.py headless=True`
.. tabs::
.. group-tab:: |_4| |pytorch| |_4|
.. list-table::
:align: left
:header-rows: 1
:stub-columns: 1
:class: nowrap
* - Environment
- Script
- Checkpoint (Hugging Face)
* - AllegroHand
- :download:`torch_allegro_hand_ppo.py <../examples/omniisaacgym/torch_allegro_hand_ppo.py>`
- `OmniIsaacGymEnvs-AllegroHand-PPO <https://huggingface.co/skrl/OmniIsaacGymEnvs-AllegroHand-PPO>`_
* - Ant
- :download:`torch_ant_ppo.py <../examples/omniisaacgym/torch_ant_ppo.py>`
|br| :download:`torch_ant_ddpg.py <../examples/omniisaacgym/torch_ant_ddpg.py>`
|br| :download:`torch_ant_td3.py <../examples/omniisaacgym/torch_ant_td3.py>`
|br| :download:`torch_ant_sac.py <../examples/omniisaacgym/torch_ant_sac.py>`
- `OmniIsaacGymEnvs-Ant-PPO <https://huggingface.co/skrl/OmniIsaacGymEnvs-Ant-PPO>`_
|br|
|br|
|br|
* - Ant (multi-threaded)
- :download:`torch_ant_mt_ppo.py <../examples/omniisaacgym/torch_ant_mt_ppo.py>`
- `OmniIsaacGymEnvs-Ant-PPO <https://huggingface.co/skrl/OmniIsaacGymEnvs-Ant-PPO>`_
* - Anymal
- :download:`torch_anymal_ppo.py <../examples/omniisaacgym/torch_anymal_ppo.py>`
-
* - AnymalTerrain
- :download:`torch_anymal_terrain_ppo.py <../examples/omniisaacgym/torch_anymal_terrain_ppo.py>`
-
* - BallBalance
- :download:`torch_ball_balance_ppo.py <../examples/omniisaacgym/torch_ball_balance_ppo.py>`
- `OmniIsaacGymEnvs-BallBalance-PPO <https://huggingface.co/skrl/OmniIsaacGymEnvs-BallBalance-PPO>`_
* - Cartpole
- :download:`torch_cartpole_ppo.py <../examples/omniisaacgym/torch_cartpole_ppo.py>`
- `OmniIsaacGymEnvs-Cartpole-PPO <https://huggingface.co/skrl/OmniIsaacGymEnvs-Cartpole-PPO>`_
* - Cartpole (multi-threaded)
- :download:`torch_cartpole_mt_ppo.py <../examples/omniisaacgym/torch_cartpole_mt_ppo.py>`
- `OmniIsaacGymEnvs-Cartpole-PPO <https://huggingface.co/skrl/OmniIsaacGymEnvs-Cartpole-PPO>`_
* - Crazyflie
- :download:`torch_crazyflie_ppo.py <../examples/omniisaacgym/torch_crazyflie_ppo.py>`
- `OmniIsaacGymEnvs-Crazyflie-PPO <https://huggingface.co/skrl/OmniIsaacGymEnvs-Crazyflie-PPO>`_
* - FactoryTaskNutBoltPick
- :download:`torch_factory_task_nut_bolt_pick_ppo.py <../examples/omniisaacgym/torch_factory_task_nut_bolt_pick_ppo.py>`
-
* - FrankaCabinet
- :download:`torch_franka_cabinet_ppo.py <../examples/omniisaacgym/torch_franka_cabinet_ppo.py>`
- `OmniIsaacGymEnvs-FrankaCabinet-PPO <https://huggingface.co/skrl/OmniIsaacGymEnvs-FrankaCabinet-PPO>`_
* - Humanoid
- :download:`torch_humanoid_ppo.py <../examples/omniisaacgym/torch_humanoid_ppo.py>`
- `OmniIsaacGymEnvs-Humanoid-PPO <https://huggingface.co/skrl/OmniIsaacGymEnvs-Humanoid-PPO>`_
* - Ingenuity
- :download:`torch_ingenuity_ppo.py <../examples/omniisaacgym/torch_ingenuity_ppo.py>`
- `OmniIsaacGymEnvs-Ingenuity-PPO <https://huggingface.co/skrl/OmniIsaacGymEnvs-Ingenuity-PPO>`_
* - Quadcopter
- :download:`torch_quadcopter_ppo.py <../examples/omniisaacgym/torch_quadcopter_ppo.py>`
- `OmniIsaacGymEnvs-Quadcopter-PPO <https://huggingface.co/skrl/OmniIsaacGymEnvs-Quadcopter-PPO>`_
* - ShadowHand
- :download:`torch_shadow_hand_ppo.py <../examples/omniisaacgym/torch_shadow_hand_ppo.py>`
- `OmniIsaacGymEnvs-ShadowHand-PPO <https://huggingface.co/skrl/OmniIsaacGymEnvs-ShadowHand-PPO>`_
.. group-tab:: |_4| |jax| |_4|
.. list-table::
:align: left
:header-rows: 1
:stub-columns: 1
:class: nowrap
* - Environment
- Script
- Checkpoint (Hugging Face)
* - AllegroHand
- :download:`jax_allegro_hand_ppo.py <../examples/omniisaacgym/jax_allegro_hand_ppo.py>`
-
* - Ant
- :download:`jax_ant_ppo.py <../examples/omniisaacgym/jax_ant_ppo.py>`
|br| :download:`jax_ant_ddpg.py <../examples/omniisaacgym/jax_ant_ddpg.py>`
|br| :download:`jax_ant_td3.py <../examples/omniisaacgym/jax_ant_sac.py>`
|br| :download:`jax_ant_sac.py <../examples/omniisaacgym/jax_ant_td3.py>`
- |br|
|br|
|br|
|br|
* - Ant (multi-threaded)
- :download:`jax_ant_mt_ppo.py <../examples/omniisaacgym/jax_ant_mt_ppo.py>`
-
* - Anymal
- :download:`jax_anymal_ppo.py <../examples/omniisaacgym/jax_anymal_ppo.py>`
-
* - AnymalTerrain
- :download:`jax_anymal_terrain_ppo.py <../examples/omniisaacgym/jax_anymal_terrain_ppo.py>`
-
* - BallBalance
- :download:`jax_ball_balance_ppo.py <../examples/omniisaacgym/jax_ball_balance_ppo.py>`
-
* - Cartpole
- :download:`jax_cartpole_ppo.py <../examples/omniisaacgym/jax_cartpole_ppo.py>`
-
* - Cartpole (multi-threaded)
- :download:`jax_cartpole_mt_ppo.py <../examples/omniisaacgym/jax_cartpole_mt_ppo.py>`
-
* - Crazyflie
- :download:`jax_crazyflie_ppo.py <../examples/omniisaacgym/jax_crazyflie_ppo.py>`
-
* - FactoryTaskNutBoltPick
- :download:`jax_factory_task_nut_bolt_pick_ppo.py <../examples/omniisaacgym/jax_factory_task_nut_bolt_pick_ppo.py>`
-
* - FrankaCabinet
- :download:`jax_franka_cabinet_ppo.py <../examples/omniisaacgym/jax_franka_cabinet_ppo.py>`
-
* - Humanoid
- :download:`jax_humanoid_ppo.py <../examples/omniisaacgym/jax_humanoid_ppo.py>`
-
* - Ingenuity
- :download:`jax_ingenuity_ppo.py <../examples/omniisaacgym/jax_ingenuity_ppo.py>`
-
* - Quadcopter
- :download:`jax_quadcopter_ppo.py <../examples/omniisaacgym/jax_quadcopter_ppo.py>`
-
* - ShadowHand
- :download:`jax_shadow_hand_ppo.py <../examples/omniisaacgym/jax_shadow_hand_ppo.py>`
-
.. raw:: html
<br>
Omniverse Isaac Gym environments (simultaneous learning by scope)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Simultaneous training/evaluation by scopes (subsets of environments among all available environments) of several agents in the same run in `OIGE <https://github.com/NVIDIA-Omniverse/OmniIsaacGymEnvs>`_'s Ant environment (**multiple agents and environments**)
.. image:: ../_static/imgs/example_parallel.jpg
:width: 100%
:align: center
:alt: Simultaneous training
.. raw:: html
<br>
Three cases are presented:
* Simultaneous (**sequential**) training of agents that **share the same memory** and whose scopes are automatically selected to be as equal as possible.
* Simultaneous (**sequential**) training of agents **without sharing memory** and whose scopes are specified manually.
* Simultaneous (**parallel**) training of agents **without sharing memory** and whose scopes are specified manually.
.. note::
Omniverse Isaac Gym environments implement a functionality to get their configuration from the command line. Because of this feature, setting the :literal:`headless` option from the trainer configuration will not work. In this case, it is necessary to invoke the scripts as follows: :literal:`python script.py headless=True`
.. tabs::
.. group-tab:: |_4| |pytorch| |_4|
.. list-table::
:align: left
:header-rows: 1
:stub-columns: 1
:class: nowrap
* - Type
- Script
* - Sequential training (shared memory)
- :download:`torch_ant_ddpg_td3_sac_sequential_shared_memory.py <../examples/omniisaacgym/torch_ant_ddpg_td3_sac_sequential_shared_memory.py>`
* - Sequential training (unshared memory)
- :download:`torch_ant_ddpg_td3_sac_sequential_unshared_memory.py <../examples/omniisaacgym/torch_ant_ddpg_td3_sac_sequential_unshared_memory.py>`
* - Parallel training (unshared memory)
- :download:`torch_ant_ddpg_td3_sac_parallel_unshared_memory.py <../examples/omniisaacgym/torch_ant_ddpg_td3_sac_parallel_unshared_memory.py>`
.. raw:: html
<br>
Omniverse Isaac Sim (single environment)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Training/evaluation of an agent in Omniverse Isaac Sim environment implemented using the Gym interface (**one agent, one environment**)
.. tabs::
.. tab:: Isaac Sim 2022.X.X (Cartpole)
This example performs the training of an agent in the Isaac Sim's Cartpole environment described in the `Creating New RL Environment <https://docs.omniverse.nvidia.com/isaacsim/latest/tutorial_gym_new_rl_example.html>`_ tutorial
Use the steps described below to setup and launch the experiment after follow the tutorial
.. code-block:: bash
# download the sample code from GitHub in the directory containing the cartpole_task.py script
wget https://raw.githubusercontent.com/Toni-SM/skrl/main/docs/source/examples/isaacsim/torch_isaacsim_cartpole_ppo.py
# run the experiment
PYTHON_PATH torch_isaacsim_cartpole_ppo.py
.. raw:: html
<br>
.. tabs::
.. group-tab:: |_4| |pytorch| |_4|
.. list-table::
:align: left
:header-rows: 1
:stub-columns: 1
:class: nowrap
* - Environment
- Script
- Checkpoint (Hugging Face)
* - Cartpole
- :download:`torch_isaacsim_cartpole_ppo.py <../examples/isaacsim/torch_isaacsim_cartpole_ppo.py>`
-
.. tab:: Isaac Sim 2021.2.1 (JetBot)
This example performs the training of an agent in the Isaac Sim's JetBot environment. The following components or practices are exemplified (highlighted):
- Define and instantiate Convolutional Neural Networks (CNN) to learn from 128 X 128 RGB images
Use the steps described below (for a local workstation or a remote container) to setup and launch the experiment
.. tabs::
.. tab:: Local workstation (setup)
.. code-block:: bash
# create a working directory and change to it
mkdir ~/.local/share/ov/pkg/isaac_sim-2021.2.1/standalone_examples/api/omni.isaac.jetbot/skrl_example
cd ~/.local/share/ov/pkg/isaac_sim-2021.2.1/standalone_examples/api/omni.isaac.jetbot/skrl_example
# install the skrl library in editable mode from the working directory
~/.local/share/ov/pkg/isaac_sim-2021.2.1/python.sh -m pip install -e git+https://github.com/Toni-SM/skrl.git#egg=skrl
# download the sample code from GitHub
wget https://raw.githubusercontent.com/Toni-SM/skrl/main/docs/source/examples/isaacsim/torch_isaacsim_jetbot_ppo.py
# copy the Isaac Sim sample environment (JetBotEnv) to the working directory
cp ../stable_baselines_example/env.py .
# run the experiment
~/.local/share/ov/pkg/isaac_sim-2021.2.1/python.sh torch_isaacsim_jetbot_ppo.py
.. tab:: Remote container (setup)
.. code-block:: bash
# create a working directory and change to it
mkdir /isaac-sim/standalone_examples/api/omni.isaac.jetbot/skrl_example
cd /isaac-sim/standalone_examples/api/omni.isaac.jetbot/skrl_example
# install the skrl library in editable mode from the working directory
/isaac-sim/kit/python/bin/python3 -m pip install -e git+https://github.com/Toni-SM/skrl.git#egg=skrl
# download the sample code from GitHub
wget https://raw.githubusercontent.com/Toni-SM/skrl/main/docs/source/examples/isaacsim/torch_isaacsim_jetbot_ppo.py
# copy the Isaac Sim sample environment (JetBotEnv) to the working directory
cp ../stable_baselines_example/env.py .
# run the experiment
/isaac-sim/python.sh torch_isaacsim_jetbot_ppo.py
.. raw:: html
<br>
.. tabs::
.. group-tab:: |_4| |pytorch| |_4|
.. list-table::
:align: left
:header-rows: 1
:stub-columns: 1
:class: nowrap
* - Environment
- Script
- Checkpoint (Hugging Face)
* - JetBot
- :download:`torch_isaacsim_jetbot_ppo.py <../examples/isaacsim/torch_isaacsim_jetbot_ppo.py>`
-
.. raw:: html
<br><hr>
**Real-world examples**
-----------------------
These examples show basic real-world and sim2real use cases to guide and support advanced RL implementations
.. raw:: html
<br>
.. tabs::
.. tab:: Franka Emika Panda
**3D reaching task (Franka's gripper must reach a certain target point in space)**. The training was done in Omniverse Isaac Gym. The real robot control is performed through the Python API of a modified version of *frankx* (see `frankx's pull request #44 <https://github.com/pantor/frankx/pull/44>`_), a high-level motion library around *libfranka*. Training and evaluation is performed for both Cartesian and joint control space
.. raw:: html
<br>
**Implementation** (see details in the table below):
* The observation space is composed of the episode's normalized progress, the robot joints' normalized positions (:math:`q`) in the interval -1 to 1, the robot joints' velocities (:math:`\dot{q}`) affected by a random uniform scale for generalization, and the target's position in space (:math:`target_{_{XYZ}}`) with respect to the robot's base
* The action space, bounded in the range -1 to 1, consists of the following. For the joint control it's robot joints' position scaled change. For the Cartesian control it's the end-effector's position (:math:`ee_{_{XYZ}}`) scaled change. The end-effector position frame corresponds to the point where the left finger connects to the gripper base in simulation, whereas in the real world it corresponds to the end of the fingers. The gripper fingers remain closed all the time in both cases
* The instantaneous reward is the negative value of the Euclidean distance (:math:`\text{d}`) between the robot end-effector and the target point position. The episode terminates when this distance is less than 0.035 meters in simulation (0.075 meters in real-world) or when the defined maximum timestep is reached
* The target position lies within a rectangular cuboid of dimensions 0.5 x 0.5 x 0.2 meters centered at (0.5, 0.0, 0.2) meters with respect to the robot's base. The robot joints' positions are drawn from an initial configuration [0º, -45º, 0º, -135º, 0º, 90º, 45º] modified with uniform random values between -7º and 7º approximately
.. list-table::
:header-rows: 1
* - Variable
- Formula / value
- Size
* - Observation space
- :math:`\dfrac{t}{t_{max}},\; 2 \dfrac{q - q_{min}}{q_{max} - q_{min}} - 1,\; 0.1\,\dot{q}\,U(0.5,1.5),\; target_{_{XYZ}}`
- 18
* - Action space (joint)
- :math:`\dfrac{2.5}{120} \, \Delta q`
- 7
* - Action space (Cartesian)
- :math:`\dfrac{1}{100} \, \Delta ee_{_{XYZ}}`
- 3
* - Reward
- :math:`-\text{d}(ee_{_{XYZ}},\; target_{_{XYZ}})`
-
* - Episode termination
- :math:`\text{d}(ee_{_{XYZ}},\; target_{_{XYZ}}) \le 0.035 \quad` or :math:`\quad t \ge t_{max} - 1`
-
* - Maximum timesteps (:math:`t_{max}`)
- 100
-
.. raw:: html
<br>
**Workflows:**
.. tabs::
.. tab:: Real-world
.. warning::
Make sure you have the e-stop on hand in case something goes wrong in the run. **Control via RL can be dangerous and unsafe for both the operator and the robot**
.. raw:: html
<video width="100%" controls autoplay>
<source src="https://user-images.githubusercontent.com/22400377/190899202-6b80c48d-fc49-48e9-b277-24814d0adab1.mp4" type="video/mp4">
</video>
<strong>Target position entered via the command prompt or generated randomly</strong>
<br><br>
<video width="100%" controls autoplay>
<source src="https://user-images.githubusercontent.com/22400377/190899205-752f654e-9310-4696-a6b2-bfa57d5325f2.mp4" type="video/mp4">
</video>
<strong>Target position in X and Y obtained with a USB-camera (position in Z fixed at 0.2 m)</strong>
|
**Prerequisites:**
A physical Franka Emika Panda robot with `Franka Control Interface (FCI) <https://frankaemika.github.io/docs/index.html>`_ is required. Additionally, the *frankx* library must be available in the python environment (see `frankx's pull request #44 <https://github.com/pantor/frankx/pull/44>`_ for the RL-compatible version installation)
**Files**
* Environment: :download:`reaching_franka_real_env.py <../examples/real_world/franka_emika_panda/reaching_franka_real_env.py>`
* Evaluation script: :download:`reaching_franka_real_skrl_eval.py <../examples/real_world/franka_emika_panda/reaching_franka_real_skrl_eval.py>`
* Checkpoints (:literal:`agent_joint.pt`, :literal:`agent_cartesian.pt`): :download:`trained_checkpoints.zip <https://github.com/Toni-SM/skrl/files/9595293/trained_checkpoints.zip>`
**Evaluation:**
.. code-block:: bash
python3 reaching_franka_real_skrl_eval.py
**Main environment configuration:**
.. note::
In the joint control space the final control of the robot is performed through the Cartesian pose (forward kinematics from specified values for the joints)
The control space (Cartesian or joint), the robot motion type (waypoint or impedance) and the target position acquisition (command prompt / automatically generated or USB-camera) can be specified in the environment class constructor (from :literal:`reaching_franka_real_skrl_eval.py`) as follow:
.. code-block:: python
control_space = "joint" # joint or cartesian
motion_type = "waypoint" # waypoint or impedance
camera_tracking = False # True for USB-camera tracking
.. tab:: Simulation (Omniverse Isaac Gym)
.. raw:: html
<video width="100%" controls autoplay>
<source src="https://user-images.githubusercontent.com/22400377/211668430-7cd4668b-e79a-46a9-bdbc-3212388b6b6d.mp4" type="video/mp4">
</video>
.. raw:: html
<img width="100%" src="https://user-images.githubusercontent.com/22400377/190921341-6feb255a-04d4-4e51-bc7a-f939116dd02d.png">
|
**Prerequisites:**
All installation steps described in Omniverse Isaac Gym's `Overview & Getting Started <https://docs.omniverse.nvidia.com/isaacsim/latest/tutorial_gym_isaac_gym.html>`_ section must be fulfilled (especially the subsection 1.3. Installing Examples Repository)
**Files** (the implementation is self-contained so no specific location is required):
* Environment: :download:`reaching_franka_omniverse_isaacgym_env.py <../examples/real_world/franka_emika_panda/reaching_franka_omniverse_isaacgym_env.py>`
* Training script: :download:`reaching_franka_omniverse_isaacgym_skrl_train.py <../examples/real_world/franka_emika_panda/reaching_franka_omniverse_isaacgym_skrl_train.py>`
* Evaluation script: :download:`reaching_franka_omniverse_isaacgym_skrl_eval.py <../examples/real_world/franka_emika_panda/reaching_franka_omniverse_isaacgym_skrl_eval.py>`
* Checkpoints (:literal:`agent_joint.pt`, :literal:`agent_cartesian.pt`): :download:`trained_checkpoints.zip <https://github.com/Toni-SM/skrl/files/9595293/trained_checkpoints.zip>`
**Training and evaluation:**
.. code-block:: bash
# training (local workstation)
~/.local/share/ov/pkg/isaac_sim-*/python.sh reaching_franka_omniverse_isaacgym_skrl_train.py
# training (docker container)
/isaac-sim/python.sh reaching_franka_omniverse_isaacgym_skrl_train.py
.. code-block:: bash
# evaluation (local workstation)
~/.local/share/ov/pkg/isaac_sim-*/python.sh reaching_franka_omniverse_isaacgym_skrl_eval.py
# evaluation (docker container)
/isaac-sim/python.sh reaching_franka_omniverse_isaacgym_skrl_eval.py
**Main environment configuration:**
The control space (Cartesian or joint) can be specified in the task configuration dictionary (from :literal:`reaching_franka_omniverse_isaacgym_skrl_train.py`) as follow:
.. code-block:: python
TASK_CFG["task"]["env"]["controlSpace"] = "joint" # "joint" or "cartesian"
.. tab:: Simulation (Isaac Gym)
.. raw:: html
<video width="100%" controls autoplay>
<source src="https://user-images.githubusercontent.com/22400377/193537523-e0f0f8ad-2295-410c-ba9a-2a16c827a498.mp4" type="video/mp4">
</video>
.. raw:: html
<img width="100%" src="https://user-images.githubusercontent.com/22400377/193546966-bcf966e6-98d8-4b41-bc15-bd7364a79381.png">
|
**Prerequisites:**
All installation steps described in Isaac Gym's `Installation <https://github.com/NVIDIA-Omniverse/IsaacGymEnvs#installation>`_ section must be fulfilled
**Files** (the implementation is self-contained so no specific location is required):
* Environment: :download:`reaching_franka_isaacgym_env.py <../examples/real_world/franka_emika_panda/reaching_franka_isaacgym_env.py>`
* Training script: :download:`reaching_franka_isaacgym_skrl_train.py <../examples/real_world/franka_emika_panda/reaching_franka_isaacgym_skrl_train.py>`
* Evaluation script: :download:`reaching_franka_isaacgym_skrl_eval.py <../examples/real_world/franka_emika_panda/reaching_franka_isaacgym_skrl_eval.py>`
**Training and evaluation:**
.. note::
The checkpoints obtained in Isaac Gym were not evaluated with the real robot. However, they were evaluated in Omniverse Isaac Gym showing successful performance
.. code-block:: bash
# training (with the Python virtual environment active)
python reaching_franka_isaacgym_skrl_train.py
.. code-block:: bash
# evaluation (with the Python virtual environment active)
python reaching_franka_isaacgym_skrl_eval.py
**Main environment configuration:**
The control space (Cartesian or joint) can be specified in the task configuration dictionary (from :literal:`reaching_franka_isaacgym_skrl_train.py`) as follow:
.. code-block:: python
TASK_CFG["env"]["controlSpace"] = "joint" # "joint" or "cartesian"
.. tab:: Kuka LBR iiwa
**3D reaching task (iiwa's end-effector must reach a certain target point in space)**. The training was done in Omniverse Isaac Gym. The real robot control is performed through the Python, ROS and ROS2 APIs of `libiiwa <https://libiiwa.readthedocs.io>`_, a scalable multi-control framework for the KUKA LBR Iiwa robots. Training and evaluation is performed for both Cartesian and joint control space
.. raw:: html
<br>
**Implementation** (see details in the table below):
* The observation space is composed of the episode's normalized progress, the robot joints' normalized positions (:math:`q`) in the interval -1 to 1, the robot joints' velocities (:math:`\dot{q}`) affected by a random uniform scale for generalization, and the target's position in space (:math:`target_{_{XYZ}}`) with respect to the robot's base
* The action space, bounded in the range -1 to 1, consists of the following. For the joint control it's robot joints' position scaled change. For the Cartesian control it's the end-effector's position (:math:`ee_{_{XYZ}}`) scaled change
* The instantaneous reward is the negative value of the Euclidean distance (:math:`\text{d}`) between the robot end-effector and the target point position. The episode terminates when this distance is less than 0.035 meters in simulation (0.075 meters in real-world) or when the defined maximum timestep is reached
* The target position lies within a rectangular cuboid of dimensions 0.2 x 0.4 x 0.4 meters centered at (0.6, 0.0, 0.4) meters with respect to the robot's base. The robot joints' positions are drawn from an initial configuration [0º, 0º, 0º, -90º, 0º, 90º, 0º] modified with uniform random values between -7º and 7º approximately
.. list-table::
:header-rows: 1
* - Variable
- Formula / value
- Size
* - Observation space
- :math:`\dfrac{t}{t_{max}},\; 2 \dfrac{q - q_{min}}{q_{max} - q_{min}} - 1,\; 0.1\,\dot{q}\,U(0.5,1.5),\; target_{_{XYZ}}`
- 18
* - Action space (joint)
- :math:`\dfrac{2.5}{120} \, \Delta q`
- 7
* - Action space (Cartesian)
- :math:`\dfrac{1}{100} \, \Delta ee_{_{XYZ}}`
- 3
* - Reward
- :math:`-\text{d}(ee_{_{XYZ}},\; target_{_{XYZ}})`
-
* - Episode termination
- :math:`\text{d}(ee_{_{XYZ}},\; target_{_{XYZ}}) \le 0.035 \quad` or :math:`\quad t \ge t_{max} - 1`
-
* - Maximum timesteps (:math:`t_{max}`)
- 100
-
.. raw:: html
<br>
**Workflows:**
.. tabs::
.. tab:: Real-world
.. warning::
Make sure you have the smartHMI on hand in case something goes wrong in the run. **Control via RL can be dangerous and unsafe for both the operator and the robot**
.. raw:: html
<video width="100%" controls autoplay>
<source src="https://user-images.githubusercontent.com/22400377/212192766-9698bfba-af27-41b8-8a11-17ed3d22c020.mp4" type="video/mp4">
</video>
**Prerequisites:**
A physical Kuka LBR iiwa robot is required. Additionally, the *libiiwa* library must be installed (visit the `libiiwa <https://libiiwa.readthedocs.io>`_ documentation for installation details)
**Files**
* Environment: :download:`reaching_iiwa_real_env.py <../examples/real_world/kuka_lbr_iiwa/reaching_iiwa_real_env.py>`
* Evaluation script: :download:`reaching_iiwa_real_skrl_eval.py <../examples/real_world/kuka_lbr_iiwa/reaching_iiwa_real_skrl_eval.py>`
* Checkpoints (:literal:`agent_joint.pt`, :literal:`agent_cartesian.pt`): :download:`trained_checkpoints.zip <https://github.com/Toni-SM/skrl/files/10406561/trained_checkpoints.zip>`
**Evaluation:**
.. code-block:: bash
python3 reaching_iiwa_real_skrl_eval.py
**Main environment configuration:**
The control space (Cartesian or joint) can be specified in the environment class constructor (from :literal:`reaching_iiwa_real_skrl_eval.py`) as follow:
.. code-block:: python
control_space = "joint" # joint or cartesian
.. tab:: Real-world (ROS/ROS2)
.. warning::
Make sure you have the smartHMI on hand in case something goes wrong in the run. **Control via RL can be dangerous and unsafe for both the operator and the robot**
.. raw:: html
<video width="100%" controls autoplay>
<source src="https://user-images.githubusercontent.com/22400377/212192817-12115478-e6a8-4502-b33f-b072664b1959.mp4" type="video/mp4">
</video>
**Prerequisites:**
A physical Kuka LBR iiwa robot is required. Additionally, the *libiiwa* library must be installed (visit the `libiiwa <https://libiiwa.readthedocs.io>`_ documentation for installation details) and a Robot Operating System (ROS or ROS2) distribution must be available
**Files**
* Environment (ROS): :download:`reaching_iiwa_real_ros_env.py <../examples/real_world/kuka_lbr_iiwa/reaching_iiwa_real_ros_env.py>`
* Environment (ROS2): :download:`reaching_iiwa_real_ros2_env.py <../examples/real_world/kuka_lbr_iiwa/reaching_iiwa_real_ros2_env.py>`
* Evaluation script: :download:`reaching_iiwa_real_ros_ros2_skrl_eval.py <../examples/real_world/kuka_lbr_iiwa/reaching_iiwa_real_ros_ros2_skrl_eval.py>`
* Checkpoints (:literal:`agent_joint.pt`, :literal:`agent_cartesian.pt`): :download:`trained_checkpoints.zip <https://github.com/Toni-SM/skrl/files/10406561/trained_checkpoints.zip>`
.. note::
Source the ROS/ROS2 distribution and the ROS/ROS workspace containing the libiiwa packages before executing the scripts
**Evaluation:**
.. note::
The environment (:literal:`reaching_iiwa_real_ros_env.py` or :literal:`reaching_iiwa_real_ros2_env.py`) to be loaded will be automatically selected based on the sourced ROS distribution (ROS or ROS2) at script execution
.. code-block:: bash
python3 reaching_iiwa_real_ros_ros2_skrl_eval.py
**Main environment configuration:**
The control space (Cartesian or joint) can be specified in the environment class constructor (from :literal:`reaching_iiwa_real_ros_ros2_skrl_eval.py`) as follow:
.. code-block:: python
control_space = "joint" # joint or cartesian
.. tab:: Simulation (Omniverse Isaac Gym)
.. raw:: html
<video width="100%" controls autoplay>
<source src="https://user-images.githubusercontent.com/22400377/211668313-7bcbcd41-cde5-441e-abb4-82fff7616f06.mp4" type="video/mp4">
</video>
.. raw:: html
<img width="100%" src="https://user-images.githubusercontent.com/22400377/212194442-f6588b98-38af-4f29-92a3-3c853a7e31f4.png">
|
**Prerequisites:**
All installation steps described in Omniverse Isaac Gym's `Overview & Getting Started <https://docs.omniverse.nvidia.com/isaacsim/latest/tutorial_gym_isaac_gym.html>`_ section must be fulfilled (especially the subsection 1.3. Installing Examples Repository)
**Files** (the implementation is self-contained so no specific location is required):
* Environment: :download:`reaching_iiwa_omniverse_isaacgym_env.py <../examples/real_world/kuka_lbr_iiwa/reaching_iiwa_omniverse_isaacgym_env.py>`
* Training script: :download:`reaching_iiwa_omniverse_isaacgym_skrl_train.py <../examples/real_world/kuka_lbr_iiwa/reaching_iiwa_omniverse_isaacgym_skrl_train.py>`
* Evaluation script: :download:`reaching_iiwa_omniverse_isaacgym_skrl_eval.py <../examples/real_world/kuka_lbr_iiwa/reaching_iiwa_omniverse_isaacgym_skrl_eval.py>`
* Checkpoints (:literal:`agent_joint.pt`, :literal:`agent_cartesian.pt`): :download:`trained_checkpoints.zip <https://github.com/Toni-SM/skrl/files/10406561/trained_checkpoints.zip>`
* Simulation files: (.usd assets and robot class): :download:`simulation_files.zip <https://github.com/Toni-SM/skrl/files/10409551/simulation_files.zip>`
Simulation files must be structured as follows:
.. code-block::
<some_folder>
├── agent_cartesian.pt
├── agent_joint.pt
├── assets
│ ├── iiwa14_instanceable_meshes.usd
│ └── iiwa14.usd
├── reaching_iiwa_omniverse_isaacgym_env.py
├── reaching_iiwa_omniverse_isaacgym_skrl_eval.py
├── reaching_iiwa_omniverse_isaacgym_skrl_train.py
├── robots
│ ├── iiwa14.py
│ └── __init__.py
**Training and evaluation:**
.. code-block:: bash
# training (local workstation)
~/.local/share/ov/pkg/isaac_sim-*/python.sh reaching_iiwa_omniverse_isaacgym_skrl_train.py
# training (docker container)
/isaac-sim/python.sh reaching_iiwa_omniverse_isaacgym_skrl_train.py
.. code-block:: bash
# evaluation (local workstation)
~/.local/share/ov/pkg/isaac_sim-*/python.sh reaching_iiwa_omniverse_isaacgym_skrl_eval.py
# evaluation (docker container)
/isaac-sim/python.sh reaching_iiwa_omniverse_isaacgym_skrl_eval.py
**Main environment configuration:**
The control space (Cartesian or joint) can be specified in the task configuration dictionary (from :literal:`reaching_iiwa_omniverse_isaacgym_skrl_train.py`) as follow:
.. code-block:: python
TASK_CFG["task"]["env"]["controlSpace"] = "joint" # "joint" or "cartesian"
.. raw:: html
<br><hr>
.. _library_utilities:
**Library utilities (skrl.utils module)**
-----------------------------------------
This example shows how to use the library utilities to carry out the post-processing of files and data generated by the experiments
.. raw:: html
<br>
.. tabs::
.. tab:: Tensorboard files
.. image:: ../_static/imgs/utils_tensorboard_file_iterator.svg
:width: 100%
:alt: Tensorboard file iterator
.. raw:: html
<br><br>
Example of a figure, generated by the code, showing the total reward (left) and the mean and standard deviation (right) of all experiments located in the runs folder
:download:`tensorboard_file_iterator.py <../examples/utils/tensorboard_file_iterator.py>`
**Note:** The code will load all the Tensorboard files of the experiments located in the :literal:`runs` folder. It is necessary to adjust the iterator's parameters for other paths
.. literalinclude:: ../examples/utils/tensorboard_file_iterator.py
:language: python
:emphasize-lines: 4, 11-13
| 81,480 | reStructuredText | 44.982506 | 497 | 0.571809 |
Toni-SM/skrl/docs/source/intro/data.rst | Saving, loading and logging
===========================
In this section, you will find the information you need to log data with TensorBoard or Weights & Biases and to save and load checkpoints and memories to and from persistent storage.
.. raw:: html
<br><hr>
**TensorBoard integration**
---------------------------
`TensorBoard <https://www.tensorflow.org/tensorboard>`_ is used for tracking and visualizing metrics and scalars (coefficients, losses, etc.). The tracking and writing of metrics and scalars is the responsibility of the agents (**can be customized independently for each agent using its configuration dictionary**).
.. .. admonition:: |jax|
.. note::
A standalone JAX installation does not include any package for writing events to Tensorboard. In this case it is necessary to install (if not installed) one of the following frameworks/packages:
* `PyTorch <https://pytorch.org/get-started/locally>`_
* `TensorFlow <https://www.tensorflow.org/install>`_
* `TensorboardX <https://github.com/lanpa/tensorboardX#install>`_
.. raw:: html
<br>
Configuration
^^^^^^^^^^^^^
Each agent offers the following parameters under the :literal:`"experiment"` key:
.. literalinclude:: ../snippets/data.py
:language: python
:emphasize-lines: 5-7
:start-after: [start-tensorboard-configuration]
:end-before: [end-tensorboard-configuration]
* **directory**: directory path where the data generated by the experiments (a subdirectory) are stored. If no value is set, the :literal:`runs` folder (inside the current working directory) will be used (and created if it does not exist).
* **experiment_name**: name of the experiment (subdirectory). If no value is set, it will be the current date and time and the agent's name (e.g. :literal:`22-01-09_22-48-49-816281_DDPG`).
* **write_interval**: interval for writing metrics and values to TensorBoard (default is 250 timesteps). A value equal to or less than 0 disables tracking and writing to TensorBoard.
.. raw:: html
<br>
Tracked metrics/scales visualization
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
To visualize the tracked metrics/scales, during or after the training, TensorBoard can be launched using the following command in a terminal:
.. code-block:: bash
tensorboard --logdir=PATH_TO_RUNS_DIRECTORY
.. image:: ../_static/imgs/data_tensorboard.jpg
:width: 100%
:align: center
:alt: TensorBoard panel
|
The following table shows the metrics/scales tracked by each agent ([**+**] all the time, [**-**] only when such a function is enabled in the agent's configuration):
+-----------+--------------------+------------------+------------------+------------------+------------------+------------------+------------------+------------------+-------------------------+------------------+--------------------+------------------+------------------+
|Tag |Metric / Scalar |.. centered:: A2C |.. centered:: AMP |.. centered:: CEM |.. centered:: DDPG|.. centered:: DDQN|.. centered:: DQN |.. centered:: PPO |.. centered:: Q-learning |.. centered:: SAC |.. centered:: SARSA |.. centered:: TD3 |.. centered:: TRPO|
+===========+====================+==================+==================+==================+==================+==================+==================+==================+=========================+==================+====================+==================+==================+
|Coefficient|Entropy coefficient | | | | | | | | |.. centered:: + | | | |
+ +--------------------+------------------+------------------+------------------+------------------+------------------+------------------+------------------+-------------------------+------------------+--------------------+------------------+------------------+
| |Return threshold | | |.. centered:: + | | | | | | | | | |
+ +--------------------+------------------+------------------+------------------+------------------+------------------+------------------+------------------+-------------------------+------------------+--------------------+------------------+------------------+
| |Mean disc. returns | | |.. centered:: + | | | | | | | | | |
+-----------+--------------------+------------------+------------------+------------------+------------------+------------------+------------------+------------------+-------------------------+------------------+--------------------+------------------+------------------+
|Episode |Total timesteps |.. centered:: + |.. centered:: + |.. centered:: + |.. centered:: + |.. centered:: + |.. centered:: + |.. centered:: + |.. centered:: + |.. centered:: + |.. centered:: + |.. centered:: + |.. centered:: + |
+-----------+--------------------+------------------+------------------+------------------+------------------+------------------+------------------+------------------+-------------------------+------------------+--------------------+------------------+------------------+
|Exploration|Exploration noise | | | |.. centered:: + | | | | | | |.. centered:: + | |
+ +--------------------+------------------+------------------+------------------+------------------+------------------+------------------+------------------+-------------------------+------------------+--------------------+------------------+------------------+
| |Exploration epsilon | | | | |.. centered:: + |.. centered:: + | | | | | | |
+-----------+--------------------+------------------+------------------+------------------+------------------+------------------+------------------+------------------+-------------------------+------------------+--------------------+------------------+------------------+
|Learning |Learning rate |.. centered:: + |.. centered:: + |.. centered:: -- | |.. centered:: -- |.. centered:: -- |.. centered:: -- | | | | | |
+ +--------------------+------------------+------------------+------------------+------------------+------------------+------------------+------------------+-------------------------+------------------+--------------------+------------------+------------------+
| |Policy learning rate| | | |.. centered:: -- | | | | |.. centered:: -- | |.. centered:: -- | |
+ +--------------------+------------------+------------------+------------------+------------------+------------------+------------------+------------------+-------------------------+------------------+--------------------+------------------+------------------+
| |Critic learning rate| | | |.. centered:: -- | | | | |.. centered:: -- | |.. centered:: -- | |
+ +--------------------+------------------+------------------+------------------+------------------+------------------+------------------+------------------+-------------------------+------------------+--------------------+------------------+------------------+
| |Return threshold | | | | | | | | | | | |.. centered:: -- |
+-----------+--------------------+------------------+------------------+------------------+------------------+------------------+------------------+------------------+-------------------------+------------------+--------------------+------------------+------------------+
|Loss |Critic loss | | | |.. centered:: + | | | | |.. centered:: + | |.. centered:: + | |
+ +--------------------+------------------+------------------+------------------+------------------+------------------+------------------+------------------+-------------------------+------------------+--------------------+------------------+------------------+
| |Entropy loss |.. centered:: -- |.. centered:: -- | | | | |.. centered:: -- | |.. centered:: -- | | | |
+ +--------------------+------------------+------------------+------------------+------------------+------------------+------------------+------------------+-------------------------+------------------+--------------------+------------------+------------------+
| |Discriminator loss | |.. centered:: + | | | | | | | | | | |
+ +--------------------+------------------+------------------+------------------+------------------+------------------+------------------+------------------+-------------------------+------------------+--------------------+------------------+------------------+
| |Policy loss |.. centered:: + |.. centered:: + |.. centered:: + |.. centered:: + | | |.. centered:: + | |.. centered:: + | |.. centered:: + |.. centered:: + |
+ +--------------------+------------------+------------------+------------------+------------------+------------------+------------------+------------------+-------------------------+------------------+--------------------+------------------+------------------+
| |Q-network loss | | | | |.. centered:: + |.. centered:: + | | | | | | |
+ +--------------------+------------------+------------------+------------------+------------------+------------------+------------------+------------------+-------------------------+------------------+--------------------+------------------+------------------+
| |Value loss |.. centered:: + |.. centered:: + | | | | |.. centered:: + | | | | |.. centered:: + |
+-----------+--------------------+------------------+------------------+------------------+------------------+------------------+------------------+------------------+-------------------------+------------------+--------------------+------------------+------------------+
|Policy |Standard deviation |.. centered:: + |.. centered:: + | | | | |.. centered:: + | | | | |.. centered:: + |
+-----------+--------------------+------------------+------------------+------------------+------------------+------------------+------------------+------------------+-------------------------+------------------+--------------------+------------------+------------------+
|Q-network |Q1 | | | |.. centered:: + | | | | |.. centered:: + | |.. centered:: + | |
+ +--------------------+------------------+------------------+------------------+------------------+------------------+------------------+------------------+-------------------------+------------------+--------------------+------------------+------------------+
| |Q2 | | | | | | | | |.. centered:: + | |.. centered:: + | |
+-----------+--------------------+------------------+------------------+------------------+------------------+------------------+------------------+------------------+-------------------------+------------------+--------------------+------------------+------------------+
|Reward |Instantaneous reward|.. centered:: + |.. centered:: + |.. centered:: + |.. centered:: + |.. centered:: + |.. centered:: + |.. centered:: + |.. centered:: + |.. centered:: + |.. centered:: + |.. centered:: + |.. centered:: + |
+ +--------------------+------------------+------------------+------------------+------------------+------------------+------------------+------------------+-------------------------+------------------+--------------------+------------------+------------------+
| |Total reward |.. centered:: + |.. centered:: + |.. centered:: + |.. centered:: + |.. centered:: + |.. centered:: + |.. centered:: + |.. centered:: + |.. centered:: + |.. centered:: + |.. centered:: + |.. centered:: + |
+-----------+--------------------+------------------+------------------+------------------+------------------+------------------+------------------+------------------+-------------------------+------------------+--------------------+------------------+------------------+
|Target |Target | | | |.. centered:: + |.. centered:: + |.. centered:: + | | |.. centered:: + | |.. centered:: + | |
+-----------+--------------------+------------------+------------------+------------------+------------------+------------------+------------------+------------------+-------------------------+------------------+--------------------+------------------+------------------+
.. raw:: html
<br>
Tracking custom metrics/scales
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
* **Tracking custom data attached to the agent's control and timing logic (recommended)**
Although the TensorBoard's writing control and timing logic is controlled by the base class Agent, it is possible to track custom data. The :literal:`track_data` method can be used (see :doc:`Agent <../api/agents>` class for more details), passing as arguments the data identification (tag) and the scalar value to be recorded.
For example, to track the current CPU usage, the following code can be used:
.. code-block:: python
# assuming agent is an instance of an Agent subclass
agent.track_data("Resource / CPU usage", psutil.cpu_percent())
* **Tracking custom data directly to Tensorboard**
It is also feasible to access directly to the `SummaryWriter <https://pytorch.org/docs/stable/tensorboard.html#torch.utils.tensorboard.writer.SummaryWriter>`_ instance through the :literal:`writer` property if it is desired to write directly to Tensorboard, avoiding the base class's control and timing logic.
For example, to write directly to TensorBoard:
.. code-block:: python
# assuming agent is an instance of an Agent subclass
agent.writer.add_scalar("Resource / CPU usage", psutil.cpu_percent(), global_step=1000)
.. raw:: html
<br><hr>
**Weights & Biases integration**
--------------------------------
`Weights & Biases (wandb) <https://wandb.ai>`_ is also supported for tracking and visualizing metrics and scalars. Its configuration is responsibility of the agents (**can be customized independently for each agent using its configuration dictionary**).
Follow the steps described in Weights & Biases documentation (`Set up wandb <https://docs.wandb.ai/quickstart#1.-set-up-wandb>`_) to login to the :literal:`wandb` library on the current machine.
.. note::
The :literal:`wandb` library is not installed by default. Install it in a Python 3 environment using pip as follows:
.. code-block:: bash
pip install wandb
.. raw:: html
<br>
Configuration
^^^^^^^^^^^^^
Each agent offers the following parameters under the :literal:`"experiment"` key. Visit the Weights & Biases documentation for more details about the configuration parameters.
.. literalinclude:: ../snippets/data.py
:language: python
:emphasize-lines: 12-13
:start-after: [start-wandb-configuration]
:end-before: [end-wandb-configuration]
* **wandb**: whether to enable support for Weights & Biases.
* **wandb_kwargs**: keyword argument dictionary used to parameterize the `wandb.init <https://docs.wandb.ai/ref/python/init>`_ function. If no values are provided for the following parameters, the following values will be set for them:
* :literal:`"name"`: will be set to the name of the experiment directory.
* :literal:`"sync_tensorboard"`: will be set to :literal:`True`.
* :literal:`"config"`: will be updated with the configuration dictionaries of both the agent (and its models) and the trainer. The update will be done even if a value has been set for the parameter.
.. raw:: html
<br><hr>
**Checkpoints**
---------------
.. raw:: html
<br>
Saving checkpoints
^^^^^^^^^^^^^^^^^^
The checkpoints are saved in the :literal:`checkpoints` subdirectory of the experiment's directory (its path can be customized using the options described in the previous subsection). The checkpoint name is the key referring to the agent (or models, optimizers and preprocessors) and the current timestep (e.g. :literal:`runs/22-01-09_22-48-49-816281_DDPG/checkpoints/agent_2500.pt`).
The checkpoint management, as in the previous case, is the responsibility of the agents (**can be customized independently for each agent using its configuration dictionary**).
.. literalinclude:: ../snippets/data.py
:language: python
:emphasize-lines: 9,10
:start-after: [start-checkpoint-configuration]
:end-before: [end-checkpoint-configuration]
* **checkpoint_interval**: interval for checkpoints (default is 1000 timesteps). A value equal to or less than 0 disables the checkpoint creation.
* **store_separately**: if set to :literal:`True`, all the modules that an agent contains (models, optimizers, preprocessors, etc.) will be saved each one in a separate file. By default (:literal:`False`) the modules are grouped in a dictionary and stored in the same file.
**Checkpointing the best models**
The best models, attending the mean total reward, will be saved in the :literal:`checkpoints` subdirectory of the experiment's directory. The checkpoint name is the word :literal:`best` and the key referring to the model (e.g. :literal:`runs/22-01-09_22-48-49-816281_DDPG/checkpoints/best_agent.pt`).
The best models are updated internally on each TensorBoard writing interval :literal:`"write_interval"` and they are saved on each checkpoint interval :literal:`"checkpoint_interval"`. The :literal:`"store_separately"` key specifies whether the best modules are grouped and stored together or separately.
.. raw:: html
<br>
Loading checkpoints
^^^^^^^^^^^^^^^^^^^
Checkpoints can be loaded (e.g. to resume or continue training) for each of the instantiated agents (or models) independently via the :literal:`.load(...)` method (`Agent.load <../modules/skrl.agents.base_class.html#skrl.agents.torch.base.Agent.load>`_ or `Model.load <../modules/skrl.models.base_class.html#skrl.models.torch.base.Model.load>`_). It accepts the path (relative or absolute) of the checkpoint to load as the only argument. The checkpoint will be dynamically mapped to the device specified as argument in the class constructor (internally the torch load's :literal:`map_location` method is used during loading).
.. note::
The agents or models instances must have the same architecture/structure as the one used to save the checkpoint. The current implementation load the model's state-dict directly.
.. note::
Warnings such as :literal:`[skrl:WARNING] Cannot load the <module> module. The agent doesn't have such an instance` can be ignored without problems during evaluation. The reason for this is that during the evaluation not all components, such as optimizers or other models apart from the policy, may be defined.
The following code snippets show how to load the checkpoints through the instantiated agent (recommended) or models. See the :doc:`Examples <examples>` section for showcases about how to checkpoints and use them to continue the training or evaluate experiments.
.. tabs::
.. tab:: Agent (recommended)
.. tabs::
.. group-tab:: |_4| |pytorch| |_4|
.. literalinclude:: ../snippets/data.py
:language: python
:emphasize-lines: 12
:start-after: [start-checkpoint-load-agent-torch]
:end-before: [end-checkpoint-load-agent-torch]
.. group-tab:: |_4| |jax| |_4|
.. literalinclude:: ../snippets/data.py
:language: python
:emphasize-lines: 12
:start-after: [start-checkpoint-load-agent-jax]
:end-before: [end-checkpoint-load-agent-jax]
.. tab:: Model
.. tabs::
.. group-tab:: |_4| |pytorch| |_4|
.. literalinclude:: ../snippets/data.py
:language: python
:emphasize-lines: 22
:start-after: [start-checkpoint-load-model-torch]
:end-before: [end-checkpoint-load-model-torch]
.. group-tab:: |_4| |jax| |_4|
.. literalinclude:: ../snippets/data.py
:language: python
:emphasize-lines: 22
:start-after: [start-checkpoint-load-model-jax]
:end-before: [end-checkpoint-load-model-jax]
In addition, it is possible to load, through the library utilities, trained agent checkpoints from the Hugging Face Hub (`huggingface.co/skrl <https://huggingface.co/skrl>`_). See the :doc:`Hugging Face integration <../api/utils/huggingface>` for more information.
.. tabs::
.. tab:: Agent (from Hugging Face Hub)
.. tabs::
.. group-tab:: |_4| |pytorch| |_4|
.. literalinclude:: ../snippets/data.py
:language: python
:emphasize-lines: 2, 13-14
:start-after: [start-checkpoint-load-huggingface-torch]
:end-before: [end-checkpoint-load-huggingface-torch]
.. group-tab:: |_4| |jax| |_4|
.. literalinclude:: ../snippets/data.py
:language: python
:emphasize-lines: 2, 13-14
:start-after: [start-checkpoint-load-huggingface-jax]
:end-before: [end-checkpoint-load-huggingface-jax]
.. raw:: html
<br>
Migrating external checkpoints
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
It is possible to load checkpoints generated with external reinforcement learning libraries into skrl agents (or models) via the :literal:`.migrate(...)` method (`Agent.migrate <../modules/skrl.agents.base_class.html#skrl.agents.torch.base.Agent.migrate>`_ or `Model.migrate <../modules/skrl.models.base_class.html#skrl.models.torch.base.Model.migrate>`_).
.. note::
In some cases it will be necessary to specify a parameter mapping, especially in ambiguous models (where 2 or more parameters, for source or current model, have equal shape). Refer to the respective method documentation for more details in these cases.
The following code snippets show how to migrate checkpoints from other libraries to the agents or models implemented in skrl:
.. tabs::
.. tab:: Agent
.. tabs::
.. group-tab:: |_4| |pytorch| |_4|
.. literalinclude:: ../snippets/data.py
:language: python
:emphasize-lines: 12
:start-after: [start-checkpoint-migrate-agent-torch]
:end-before: [end-checkpoint-migrate-agent-torch]
.. tab:: Model
.. tabs::
.. group-tab:: |_4| |pytorch| |_4|
.. literalinclude:: ../snippets/data.py
:language: python
:emphasize-lines: 22, 25, 28-29
:start-after: [start-checkpoint-migrate-model-torch]
:end-before: [end-checkpoint-migrate-model-torch]
.. raw:: html
<br><hr>
**Memory export/import**
------------------------
.. raw:: html
<br>
Exporting memories
^^^^^^^^^^^^^^^^^^
Memories can be automatically exported to files at each filling cycle (before data overwriting is performed). Its activation, the output files' format and their path can be modified through the constructor parameters when an instance is created.
.. tabs::
.. group-tab:: |_4| |pytorch| |_4|
.. literalinclude:: ../snippets/data.py
:language: python
:emphasize-lines: 7-9
:start-after: [start-export-memory-torch]
:end-before: [end-export-memory-torch]
.. group-tab:: |_4| |jax| |_4|
.. literalinclude:: ../snippets/data.py
:language: python
:emphasize-lines: 7-9
:start-after: [start-export-memory-jax]
:end-before: [end-export-memory-jax]
* **export**: enable or disable the memory export (default is disabled).
* **export_format**: the format of the exported memory (default is :literal:`"pt"`). Supported formats are PyTorch (:literal:`"pt"`), NumPy (:literal:`"np"`) and Comma-separated values (:literal:`"csv"`).
* **export_directory**: the directory where the memory will be exported (default is :literal:`"memory"`).
.. raw:: html
<br>
Importing memories
^^^^^^^^^^^^^^^^^^
TODO :red:`(coming soon)`
| 27,308 | reStructuredText | 67.962121 | 625 | 0.399773 |
Toni-SM/semu.misc.jupyter_notebook/README.md | ## Embedded Jupyter Notebook for NVIDIA Omniverse
> This extension can be described as the [Jupyter](https://jupyter.org/) notebook version of Omniverse's [Script Editor](https://docs.omniverse.nvidia.com/extensions/latest/ext_script-editor.html). It allows to open a Jupyter Notebook embedded in the current NVIDIA Omniverse application scope.
<br>
**Target applications:** Any NVIDIA Omniverse app
**Supported OS:** Windows and Linux
**Changelog:** [CHANGELOG.md](exts/semu.misc.jupyter_notebook/docs/CHANGELOG.md)
**Table of Contents:**
- [Extension setup](#setup)
- [Troubleshooting](#setup-troubleshooting)
- [Extension usage](#usage)
- [Code autocompletion](#usage-autocompletion)
- [Code introspection](#usage-introspection)
- [Configuring the extension](#config)
- [Implementation details](#implementation)
<br>

<hr>
<a name="setup"></a>
### Extension setup
1. Add the extension using the [Extension Manager](https://docs.omniverse.nvidia.com/extensions/latest/ext_extension-manager.html) or by following the steps in [Extension Search Paths](https://docs.omniverse.nvidia.com/kit/docs/kit-manual/latest/guide/extensions_advanced.html#git-url-paths)
* Git url (git+https) as extension search path
```
git+https://github.com/Toni-SM/semu.misc.jupyter_notebook.git?branch=main&dir=exts
```
* Compressed (.zip) file for import
[semu.misc.jupyter_notebook.zip](https://github.com/Toni-SM/semu.misc.jupyter_notebook/releases)
2. Enable the extension using the [Extension Manager](https://docs.omniverse.nvidia.com/extensions/latest/ext_extension-manager.html) or by following the steps in [Extension Enabling/Disabling](https://docs.omniverse.nvidia.com/kit/docs/kit-manual/latest/guide/extensions_advanced.html#extension-enabling-disabling)
<a name="setup-troubleshooting"></a>
#### Troubleshooting
* Failed installation (particularly in Kit 105 based applications - Python 3.10)
**Issues/Errors:**
```ini
[Warning] [omni.kit.pipapi.pipapi] 'jupyterlab' failed to install.
[Warning] [omni.kit.pipapi.pipapi] 'notebook' failed to install.
```
**Solution:**
Upgrade `pip` to the latest version and install required libraries manually. Replace `<USER>`, `<OMNIVERSE_APP>`, `<APP_NAME>`, and `<APP_VERSION>` according to your system configuration. Example:
- `<USER>`: toni
- `<OMNIVERSE_APP>`: create-2023.1.1
- `<APP_NAME>`: USD.Composer
- `<APP_VERSION>`: 2023.1
<br>
Linux
```xml
/home/<USER>/.local/share/ov/pkg/<OMNIVERSE_APP>/kit/python/bin/python3 -m pip install --upgrade pip
/home/<USER>/.local/share/ov/pkg/<OMNIVERSE_APP>/kit/python/bin/python3 -m pip --isolated install --upgrade --target=/home/<USER>/.local/share/ov/data/Kit/<APP_NAME>/<APP_VERSION>/pip3-envs/default jupyterlab notebook jedi
```
Windows
```xml
C:\Users\<USER>\AppData\Local\ov\pkg\<OMNIVERSE_APP>\kit\python\python.exe -m pip install --upgrade pip
C:\Users\<USER>\AppData\Local\ov\pkg\<OMNIVERSE_APP>\kit\python\python.exe -m pip --isolated install --upgrade --target=C:\Users\<USER>\AppData\Local\ov\data\Kit\<APP_NAME>\<APP_VERSION>\pip3-envs\default jupyterlab notebook jedi
```
<hr>
<a name="usage"></a>
### Extension usage
#### Omniverse app
Enabling the extension launches the Jupyter Notebook server ([JupyterLab](https://jupyterlab.readthedocs.io/en/stable/) or [Jupyter Notebook](https://jupyter-notebook.readthedocs.io/en/latest/)) in the background. The notebook can then be opened in the browser via its URL (`http://WORKSTATION_IP:PORT/`), which is also indicated inside the Omniverse application in the *Windows > Embedded Jupyter Notebook* menu.
> **Note:** The Jupyter Notebook URL port may change if the configured port is already in use.
<br>
<p align="center">
<img src="exts/semu.misc.jupyter_notebook/data/preview1.png" width="75%">
</p>
Disabling the extension shutdowns the Jupyter Notebook server and the openened kernels.
#### Jupyter Notebook
To execute Python code in the current NVIDIA Omniverse application scope use the following kernel:
<br>
<table align="center" class="table table-striped table-bordered">
<thead>
</thead>
<tbody>
<tr>
<td>Embedded Omniverse (Python 3)</td>
<td><p align="center" style="margin: 0"><img src="exts/semu.misc.jupyter_notebook/data/kernels/embedded_omniverse_python3_socket/logo-64x64.png" width="50px"></p></td>
</tr>
</tbody>
</table>
<a name="usage-autocompletion"></a>
##### Code autocompletion
Use the <kbd>Tab</kbd> key for code autocompletion.
<a name="usage-introspection"></a>
##### Code introspection
Use the <kbd>Ctrl</kbd> + <kbd>i</kbd> keys for code introspection (display *docstring* if available).
<hr>
<a name="config"></a>
### Configuring the extension
The extension can be configured by editing the [config.toml](exts/semu.misc.jupyter_notebook/config/extension.toml) file under `[settings]` section. The following parameters are available:
<br>
**Extension settings**
<table class="table table-striped table-bordered">
<thead>
<tr>
<th>Parameter</th>
<th>Value</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td>socket_port</td>
<td>8224</td>
<td>The port on which the Jupyter Notebook server will be listening for connections</td>
</tr>
<tr>
<td>classic_notebook_interface</td>
<td>false</td>
<td>Whether the Jupyter Notebook server will use the JupyterLab interface (default interface) or the classic Jupyter Notebook interface</td>
</tr>
<tr>
<td>kill_processes_with_port_in_use</td>
<td>true</td>
<td>Whether to kill applications/processes that use the same ports (8224 and 8225 by default) before activating the extension. Disable this option if you want to launch multiple applications that have this extension active</td>
</tr>
</tbody>
</table>
<br>
**Jupyter Notebook server settings**
<table class="table table-striped table-bordered">
<thead>
<tr>
<th>Parameter</th>
<th>Value</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td>notebook_ip</td>
<td>"0.0.0.0"</td>
<td>The IP address on which the Jupyter Notebook server will be launched</td>
</tr>
<tr>
<td>notebook_port</td>
<td>8225</td>
<td>The port on which the Jupyter Notebook server will be launched. If the port is already in use, the server will be launched on a different incrementing port</td>
</tr>
<tr>
<td>token</td>
<td>""</td>
<td>The Jupyter Notebook server token. If empty, the default configuration, the server will be launched without authentication</td>
</tr>
<tr>
<td>notebook_dir</td>
<td>""</td>
<td>The Jupyter Notebook server directory</td>
</tr>
<tr>
<td>command_line_options</td>
<td>"--allow-root --no-browser"</td>
<td>The Jupyter Notebook server command line options excluding the previously mentioned parameters</td>
</tr>
</tbody>
</table>
<hr>
<a name="implementation"></a>
### Implementation details
Both the Jupyter Notebook server and the IPython kernels are designed to be launched as independent processes (or subprocesses). Due to this specification, the Jupyter Notebook server and the IPython kernels are launched in separate (sub)processes.
<br>
<table class="table table-striped table-bordered">
<thead>
<tr>
<th></th>
<th>Jupyter Notebook as (sub)process</th>
</tr>
</thead>
<tbody>
<tr>
<td>Kernel (display name)</td>
<td>Embedded Omniverse (Python 3)</td>
</tr>
<tr>
<td>Kernel (logo)</td>
<td><p align="center"><img src="exts/semu.misc.jupyter_notebook/data/kernels/embedded_omniverse_python3_socket/logo-64x64.png" width="50px"></p></td>
</tr>
<tr>
<td>Kernel (raw name)</td>
<td>embedded_omniverse_python3_socket</td>
</tr>
<tr>
<td>Instanceable kernels</td>
<td>Unlimited</td>
</tr>
<tr>
<td>Python backend</td>
<td>Omniverse Kit embedded Python</td>
</tr>
<tr>
<td>Code execution</td>
<td>Intercept Jupyter-IPython communication, forward and execute code in Omniverse Kit and send back the results to the published by the notebook</td>
</tr>
<tr>
<td>Main limitations</td>
<td>
<ul>
<li>IPython magic commands are not available</li>
<li>Printing, inside callbacks, is not displayed in the notebook but in the Omniverse terminal</li>
<li>Matplotlib plotting is not available in notebooks</li>
</ul>
</td>
</tr>
</tbody>
</table>
| 8,763 | Markdown | 32.968992 | 413 | 0.684126 |
Toni-SM/semu.misc.jupyter_notebook/exts/semu.misc.jupyter_notebook/semu/misc/jupyter_notebook/__init__.py | from .scripts.extension import * | 32 | Python | 31.999968 | 32 | 0.8125 |
Toni-SM/semu.misc.jupyter_notebook/exts/semu.misc.jupyter_notebook/semu/misc/jupyter_notebook/scripts/extension.py | import __future__
import os
import sys
import jedi
import json
import glob
import socket
import asyncio
import traceback
import subprocess
import contextlib
from io import StringIO
from dis import COMPILER_FLAG_NAMES
try:
from ast import PyCF_ALLOW_TOP_LEVEL_AWAIT
except ImportError:
PyCF_ALLOW_TOP_LEVEL_AWAIT = 0
import carb
import omni.ext
def _get_coroutine_flag() -> int:
"""Get the coroutine flag for the current Python version
"""
for k, v in COMPILER_FLAG_NAMES.items():
if v == "COROUTINE":
return k
return -1
COROUTINE_FLAG = _get_coroutine_flag()
def _has_coroutine_flag(code) -> bool:
"""Check if the code has the coroutine flag set
"""
if COROUTINE_FLAG == -1:
return False
return bool(code.co_flags & COROUTINE_FLAG)
def _get_compiler_flags() -> int:
"""Get the compiler flags for the current Python version
"""
flags = 0
for value in globals().values():
try:
if isinstance(value, __future__._Feature):
f = value.compiler_flag
flags |= f
except BaseException:
pass
flags = flags | PyCF_ALLOW_TOP_LEVEL_AWAIT
return flags
def _get_event_loop() -> asyncio.AbstractEventLoop:
"""Backward compatible function for getting the event loop
"""
try:
if sys.version_info >= (3, 7):
return asyncio.get_running_loop()
else:
return asyncio.get_event_loop()
except RuntimeError:
return asyncio.get_event_loop_policy().get_event_loop()
class Extension(omni.ext.IExt):
WINDOW_NAME = "Embedded Jupyter Notebook"
MENU_PATH = f"Window/{WINDOW_NAME}"
def on_startup(self, ext_id):
self._globals = {**globals()}
self._locals = self._globals
self._server = None
self._process = None
self._settings = carb.settings.get_settings()
self._extension_path = omni.kit.app.get_app().get_extension_manager().get_extension_path(ext_id)
sys.path.append(os.path.join(self._extension_path, "data", "provisioners"))
# get extension settings
self._token = self._settings.get("/exts/semu.misc.jupyter_notebook/token")
self._notebook_ip = self._settings.get("/exts/semu.misc.jupyter_notebook/notebook_ip")
self._notebook_port = self._settings.get("/exts/semu.misc.jupyter_notebook/notebook_port")
self._notebook_dir = self._settings.get("/exts/semu.misc.jupyter_notebook/notebook_dir")
self._command_line_options = self._settings.get("/exts/semu.misc.jupyter_notebook/command_line_options")
self._classic_notebook_interface = self._settings.get("/exts/semu.misc.jupyter_notebook/classic_notebook_interface")
self._socket_port = self._settings.get("/exts/semu.misc.jupyter_notebook/socket_port")
kill_processes_with_port_in_use = self._settings.get("/exts/semu.misc.jupyter_notebook/kill_processes_with_port_in_use")
# menu item
self._editor_menu = omni.kit.ui.get_editor_menu()
if self._editor_menu:
self._menu = self._editor_menu.add_item(Extension.MENU_PATH, self._show_notification, toggle=False, value=False)
# shutdown stream
self.shutdown_stream_event = omni.kit.app.get_app().get_shutdown_event_stream() \
.create_subscription_to_pop(self._on_shutdown_event, name="semu.misc.jupyter_notebook", order=0)
# ensure port is free
if kill_processes_with_port_in_use:
# windows
if sys.platform == "win32":
pids = []
cmd = ["netstat", "-ano"]
p = subprocess.Popen(cmd, stdout=subprocess.PIPE)
for line in p.stdout:
if f":{self._socket_port}".encode() in line or f":{self._notebook_port}".encode() in line:
if "listening".encode() in line.lower():
carb.log_info(f"Open port: {line.strip().decode()}")
pids.append(line.strip().split(b" ")[-1].decode())
p.wait()
for pid in pids:
if not pid.isnumeric():
continue
carb.log_warn(f"Forced process shutdown with PID {pid}")
cmd = ["taskkill", "/PID", pid, "/F"]
subprocess.Popen(cmd).wait()
# linux
elif sys.platform == "linux":
pids = []
cmd = ["netstat", "-ltnup"]
try:
p = subprocess.Popen(cmd, stdout=subprocess.PIPE)
for line in p.stdout:
if f":{self._socket_port}".encode() in line or f":{self._notebook_port}".encode() in line:
carb.log_info(f"Open port: {line.strip().decode()}")
pids.append([chunk for chunk in line.strip().split(b" ") if b'/' in chunk][-1].decode().split("/")[0])
p.wait()
except FileNotFoundError as e:
carb.log_warn(f"Command (netstat) not available. Install it using `apt install net-tools`")
for pid in pids:
if not pid.isnumeric():
continue
carb.log_warn(f"Forced process shutdown with PID {pid}")
cmd = ["kill", "-9", pid]
subprocess.Popen(cmd).wait()
# create socket
self._create_socket()
# run jupyter notebook in a separate process
self._launch_jupyter_process()
# jedi (autocompletion)
# application root path
app_folder = carb.settings.get_settings().get_as_string("/app/folder")
if not app_folder:
app_folder = carb.tokens.get_tokens_interface().resolve("${app}")
path = os.path.normpath(os.path.join(app_folder, os.pardir))
# get extension paths
folders = [
"exts",
"extscache",
os.path.join("kit", "extensions"),
os.path.join("kit", "exts"),
os.path.join("kit", "extsPhysics"),
os.path.join("kit", "extscore"),
]
added_sys_path = []
for folder in folders:
sys_paths = glob.glob(os.path.join(path, folder, "*"))
for sys_path in sys_paths:
if os.path.isdir(sys_path):
added_sys_path.append(sys_path)
# python environment
python_exe = "python.exe" if sys.platform == "win32" else "bin/python3"
environment_path = os.path.join(path, "kit", "python", python_exe)
# jedi project
carb.log_info("Autocompletion: jedi.Project")
carb.log_info(f" |-- path: {path}")
carb.log_info(f" |-- added_sys_path: {len(added_sys_path)} items")
carb.log_info(f" |-- environment_path: {environment_path}")
self._jedi_project = jedi.Project(path=path,
environment_path=environment_path,
added_sys_path=added_sys_path,
load_unsafe_extensions=False)
def on_shutdown(self):
# clean extension paths from sys.path
if self._extension_path is not None:
sys.path.remove(os.path.join(self._extension_path, "data", "provisioners"))
self._extension_path = None
# clean up menu item
if self._menu is not None:
self._editor_menu.remove_item(self._menu)
self._menu = None
# close the socket
if self._server:
self._server.close()
_get_event_loop().run_until_complete(self._server.wait_closed())
# close the jupyter notebook (external process)
if self._process is not None:
process_pid = self._process.pid
try:
self._process.terminate() # .kill()
except OSError as e:
if sys.platform == 'win32':
if e.winerror != 5:
raise
else:
from errno import ESRCH
if not isinstance(e, ProcessLookupError) or e.errno != ESRCH:
raise
# make sure the process is not running anymore in Windows
if sys.platform == 'win32':
subprocess.call(['taskkill', '/F', '/T', '/PID', str(process_pid)])
# wait for the process to terminate
self._process.wait()
self._process = None
# extension ui methods
def _on_shutdown_event(self, event):
if event.type == omni.kit.app.POST_QUIT_EVENT_TYPE:
self.on_shutdown()
def _show_notification(self, *args, **kwargs) -> None:
"""Show a Jupyter Notebook URL in the notification area
"""
display_url = ""
if self._process is not None:
notebook_txt = os.path.join(self._extension_path, "data", "launchers", "notebook.txt")
if os.path.exists(notebook_txt):
with open(notebook_txt, "r") as f:
display_url = f.read()
if display_url:
notification = "Jupyter Notebook is running at:\n\n - " + display_url.replace(" or ", " - ")
status=omni.kit.notification_manager.NotificationStatus.INFO
else:
notification = "Unable to identify Jupyter Notebook URL"
status=omni.kit.notification_manager.NotificationStatus.WARNING
ok_button = omni.kit.notification_manager.NotificationButtonInfo("OK", on_complete=None)
omni.kit.notification_manager.post_notification(notification,
hide_after_timeout=False,
duration=0,
status=status,
button_infos=[ok_button])
print(notification)
carb.log_info(notification)
# internal socket methods
def _create_socket(self) -> None:
"""Create a socket server to listen for incoming connections from the IPython kernel
"""
socket_txt = os.path.join(self._extension_path, "data", "launchers", "socket.txt")
# delete socket.txt file
if os.path.exists(socket_txt):
os.remove(socket_txt)
class ServerProtocol(asyncio.Protocol):
def __init__(self, parent) -> None:
super().__init__()
self._parent = parent
def connection_made(self, transport):
peername = transport.get_extra_info('peername')
carb.log_info('Connection from {}'.format(peername))
self.transport = transport
def data_received(self, data):
code = data.decode()
# completion
if code[:3] == "%!c":
code = code[3:]
asyncio.run_coroutine_threadsafe(self._parent._complete_code_async(code, self.transport), _get_event_loop())
# introspection
elif code[:3] == "%!i":
code = code[3:]
pos = code.find('%')
line, column = [int(i) for i in code[:pos].split(':')]
code = code[pos + 1:]
asyncio.run_coroutine_threadsafe(self._parent._introspect_code_async(code, line, column, self.transport), _get_event_loop())
# execution
else:
asyncio.run_coroutine_threadsafe(self._parent._exec_code_async(code, self.transport), _get_event_loop())
async def server_task():
self._server = await _get_event_loop().create_server(protocol_factory=lambda: ServerProtocol(self),
host="127.0.0.1",
port=self._socket_port,
family=socket.AF_INET,
reuse_port=None if sys.platform == 'win32' else True)
await self._server.start_serving()
task = _get_event_loop().create_task(server_task())
# write the socket port to socket.txt file
carb.log_info("Internal socket server is running at port {}".format(self._socket_port))
with open(socket_txt, "w") as f:
f.write(str(self._socket_port))
async def _complete_code_async(self, statement: str, transport: asyncio.Transport) -> None:
"""Complete objects under the cursor and send the result to the IPython kernel
:param statement: statement to complete
:type statement: str
:param transport: transport to send the result to the IPython kernel
:type transport: asyncio.Transport
:return: reply dictionary
:rtype: dict
"""
# generate completions
script = jedi.Script(statement, project=self._jedi_project)
completions = script.complete()
delta = completions[0].get_completion_prefix_length() if completions else 0
reply = {"matches": [c.name for c in completions], "delta": delta}
# send the reply to the IPython kernel
reply = json.dumps(reply)
transport.write(reply.encode())
# close the connection
transport.close()
async def _introspect_code_async(self, statement: str, line: int, column: int, transport: asyncio.Transport) -> None:
"""Introspect code under the cursor and send the result to the IPython kernel
:param statement: statement to introspect
:type statement: str
:param line: the line where the definition occurs
:type line: int
:param column: the column where the definition occurs
:type column: int
:param transport: transport to send the result to the IPython kernel
:type transport: asyncio.Transport
:return: reply dictionary
:rtype: dict
"""
# generate introspection
script = jedi.Script(statement, project=self._jedi_project)
definitions = script.infer(line=line, column=column)
reply = {"found": False, "data": "TODO"}
if len(definitions):
reply["found"] = True
reply["data"] = definitions[0].docstring()
# send the reply to the IPython kernel
reply = json.dumps(reply)
transport.write(reply.encode())
# close the connection
transport.close()
async def _exec_code_async(self, statement: str, transport: asyncio.Transport) -> None:
"""Execute the statement in the Omniverse scope and send the result to the IPython kernel
:param statement: statement to execute
:type statement: str
:param transport: transport to send the result to the IPython kernel
:type transport: asyncio.Transport
:return: reply dictionary
:rtype: dict
"""
_stdout = StringIO()
try:
with contextlib.redirect_stdout(_stdout):
should_exec_code = True
# try 'eval' first
try:
code = compile(statement, "<string>", "eval", flags= _get_compiler_flags(), dont_inherit=True)
except SyntaxError:
pass
else:
result = eval(code, self._globals, self._locals)
should_exec_code = False
# if 'eval' fails, try 'exec'
if should_exec_code:
code = compile(statement, "<string>", "exec", flags= _get_compiler_flags(), dont_inherit=True)
result = eval(code, self._globals, self._locals)
# await the result if it is a coroutine
if _has_coroutine_flag(code):
result = await result
except Exception as e:
# clean traceback
_traceback = traceback.format_exc()
_i = _traceback.find('\n File "<string>"')
if _i != -1:
_traceback = _traceback[_i + 20:]
_traceback = _traceback.replace(", in <module>\n", "\n")
# build reply dictionary
reply = {"status": "error",
"traceback": [_traceback],
"ename": str(type(e).__name__),
"evalue": str(e)}
else:
reply = {"status": "ok"}
# add output to reply dictionary for printing
reply["output"] = _stdout.getvalue()
# send the reply to the IPython kernel
reply = json.dumps(reply)
transport.write(reply.encode())
# close the connection
transport.close()
# launch Jupyter Notebook methods
def _launch_jupyter_process(self) -> None:
"""Launch the Jupyter notebook in a separate process
"""
# get packages path
paths = [p for p in sys.path if "pip3-envs" in p]
packages_txt = os.path.join(self._extension_path, "data", "launchers", "packages.txt")
with open(packages_txt, "w") as f:
f.write("\n".join(paths))
if sys.platform == 'win32':
executable_path = os.path.abspath(os.path.join(os.path.dirname(os.__file__), "..", "python.exe"))
else:
executable_path = os.path.abspath(os.path.join(os.path.dirname(os.__file__), "..", "..", "bin", "python3"))
cmd = [executable_path,
os.path.join(self._extension_path, "data", "launchers", "jupyter_launcher.py"),
self._notebook_ip,
str(self._notebook_port),
self._token,
str(self._classic_notebook_interface),
self._notebook_dir,
self._command_line_options]
carb.log_info("Starting Jupyter server in separate process")
carb.log_info(" |-- command: " + " ".join(cmd))
try:
self._process = subprocess.Popen(cmd, cwd=os.path.join(self._extension_path, "data", "launchers"))
except Exception as e:
carb.log_error("Error starting Jupyter server: {}".format(e))
self._process = None
| 18,476 | Python | 40.521348 | 144 | 0.546872 |
Toni-SM/semu.misc.jupyter_notebook/exts/semu.misc.jupyter_notebook/config/extension.toml | [core]
reloadable = true
order = 0
[package]
version = "0.1.1"
category = "Utility"
feature = false
app = false
title = "Embedded Jupyter Notebook"
description = "Jupyter Notebook version of Omniverse's script editor"
authors = ["Toni-SM"]
repository = "https://github.com/Toni-SM/semu.misc.jupyter_notebook"
keywords = ["jupyter", "notebook", "ipython", "editor"]
changelog = "docs/CHANGELOG.md"
readme = "docs/README.md"
preview_image = "data/preview.png"
icon = "data/icon.png"
[package.target]
config = ["release"]
platform = ["linux-*", "windows-*"]
python = ["*"]
[dependencies]
"omni.kit.test" = {}
"omni.kit.uiapp" = {}
"omni.kit.notification_manager" = {}
[[python.module]]
name = "semu.misc.jupyter_notebook"
[python.pipapi]
requirements = ["jupyterlab", "notebook", "jedi"]
use_online_index = true
[settings]
# extension settings
exts."semu.misc.jupyter_notebook".socket_port = 8224
exts."semu.misc.jupyter_notebook".classic_notebook_interface = false
exts."semu.misc.jupyter_notebook".kill_processes_with_port_in_use = true
# jupyter notebook settings
exts."semu.misc.jupyter_notebook".notebook_ip = "0.0.0.0"
exts."semu.misc.jupyter_notebook".notebook_port = 8225
exts."semu.misc.jupyter_notebook".token = ""
exts."semu.misc.jupyter_notebook".notebook_dir = ""
# jupyter notebook's command line options other than: '--ip', '--port', '--token', '--notebook-dir'
exts."semu.misc.jupyter_notebook".command_line_options = "--allow-root --no-browser --JupyterApp.answer_yes=True"
| 1,494 | TOML | 29.510203 | 113 | 0.715529 |
Toni-SM/semu.misc.jupyter_notebook/exts/semu.misc.jupyter_notebook/docs/CHANGELOG.md | # Changelog
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).
## [0.1.1] - 2023-08-08
### Added
- Code autocompletion (<kbd>Tab</kbd>)
- Code introspection (<kbd>Ctrl</kbd> + <kbd>i</kbd>)
### Changed
- Implement embedded kernel on `ipykernel.kernelbase.Kernel`
- Update links in resource notebooks
### Removed
- Threaded kernel implementation
## [0.1.0] - 2023-08-07
The release was yanked
## [0.0.3-beta] - 2022-12-31
### Added
- Add `kill_processes_with_port_in_use` to extension settings
- Add Omniverse documentation and developer resource to notebooks
### Fixed
- Fix port in use when starting up and shutting down
## [0.0.2-beta] - 2022-08-14
### Added
- Jupyter Lab
- Launch Jupyter in separate (sub)process
- Embedded kernel using socket
## [0.0.1-beta] - 2022-08-08
### Added
- Jupyter Notebook
| 845 | Markdown | 21.864864 | 80 | 0.698225 |
Toni-SM/semu.misc.jupyter_notebook/exts/semu.misc.jupyter_notebook/docs/README.md | # semu.misc.jupyter_notebook
This extension can be described as the Jupyter notebook version of Omniverse's script editor. It allows to open a Jupyter Notebook embedded in the current NVIDIA Omniverse application scope
Visit https://github.com/Toni-SM/semu.misc.jupyter_notebook to read more about its use
| 309 | Markdown | 43.285708 | 189 | 0.812298 |
Toni-SM/semu.misc.jupyter_notebook/exts/semu.misc.jupyter_notebook/data/launchers/jupyter_launcher.py | from typing import List
import os
import sys
PACKAGES_PATH = []
SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
# add packages to sys.path
with open(os.path.join(SCRIPT_DIR, "packages.txt"), "r") as f:
for p in f.readlines():
p = p.strip()
if p:
PACKAGES_PATH.append(p)
if p not in sys.path:
print("Adding package to sys.path: {}".format(p))
sys.path.append(p)
# add provisioners to sys.path
sys.path.append(os.path.abspath(os.path.join(SCRIPT_DIR, "..", "provisioners")))
from jupyter_client.kernelspec import KernelSpecManager as _KernelSpecManager
class KernelSpecManager(_KernelSpecManager):
def __init__(self, *args, **kwargs):
"""Custom kernel spec manager to allow for loading of custom kernels
"""
super().__init__(*args, **kwargs)
kernel_dir = os.path.abspath(os.path.join(SCRIPT_DIR, "..", "kernels"))
if kernel_dir not in self.kernel_dirs:
self.kernel_dirs.append(kernel_dir)
def main(ip: str = "0.0.0.0", port: int = 8225, argv: List[str] = [], classic_notebook_interface: bool = False) -> None:
"""Entry point for launching Juptyter Notebook/Lab
:param ip: Notebook server IP address (default: "0.0.0.0")
:type code: str, optional
:param port: Notebook server port number (default: 8225)
:type code: int, optional
:param argv: Command line arguments to pass to Jupyter Notebook/Lab (default: [])
:type code: List of strings, optional
:param classic_notebook_interface: Whether to use the classic notebook interface (default: False)
If false, the Juptyter Lab interface will be used
:type code: bool, optional
"""
# jupyter notebook
if classic_notebook_interface:
from notebook.notebookapp import NotebookApp
app = NotebookApp(ip=ip,
port=port,
kernel_spec_manager_class=KernelSpecManager)
app.initialize(argv=argv)
# jupyter lab
else:
from jupyterlab.labapp import LabApp
from jupyter_server.serverapp import ServerApp
jpserver_extensions = {LabApp.get_extension_package(): True}
find_extensions = LabApp.load_other_extensions
if "jpserver_extensions" in LabApp.serverapp_config:
jpserver_extensions.update(LabApp.serverapp_config["jpserver_extensions"])
LabApp.serverapp_config["jpserver_extensions"] = jpserver_extensions
find_extensions = False
app = ServerApp.instance(ip=ip,
port=port,
kernel_spec_manager_class=KernelSpecManager,
jpserver_extensions=jpserver_extensions)
app.aliases.update(LabApp.aliases)
app.initialize(argv=argv,
starter_extension=LabApp.name,
find_extensions=find_extensions)
# write url to file in script directory
with open(os.path.join(SCRIPT_DIR, "notebook.txt"), "w") as f:
f.write(app.display_url)
app.start()
if __name__ == "__main__":
argv = sys.argv[1:]
# testing the launcher
if not len(argv):
print("Testing the launcher")
argv = ['0.0.0.0', # ip
'8888', # port
'', # token
'False', # classic_notebook_interface
'', # notebook_dir
'--allow-root --no-browser'] # extra arguments
# get function arguments
ip = argv[0]
port = int(argv[1])
token = argv[2]
classic_notebook_interface = argv[3] == "True"
# buld notebook_dir
if not argv[4]:
notebook_dir = os.path.abspath(os.path.join(SCRIPT_DIR, "..", "notebooks"))
notebook_dir = "--notebook-dir={}".format(notebook_dir)
# build token
if classic_notebook_interface:
token = "--NotebookApp.token={}".format(token)
else:
token = "--ServerApp.token={}".format(token)
# assets path
app_dir = []
if not classic_notebook_interface:
for p in PACKAGES_PATH:
print("Checking package to app_dir: {}".format(p))
if os.path.exists(os.path.join(p, "share", "jupyter", "lab")):
app_dir = ["--app-dir={}".format(os.path.join(p, "share", "jupyter", "lab"))]
if os.path.exists(os.path.join(p, "jupyterlab", "static")):
app_dir = ["--app-dir={}".format(os.path.join(p, "jupyterlab"))]
if app_dir:
break
print("app_dir: {}".format(app_dir))
# clean up the argv
argv = app_dir + [token] + [notebook_dir] + argv[5].split(" ")
# run the launcher
print("Starting Jupyter {} at {}:{}".format("Notebook" if classic_notebook_interface else "Lab", ip, port))
print(" with argv: {}".format(" ".join(argv)))
main(ip=ip, port=port, argv=argv, classic_notebook_interface=classic_notebook_interface)
# delete notebook.txt
try:
os.remove(os.path.join(SCRIPT_DIR, "notebook.txt"))
except:
pass
| 5,168 | Python | 33.925675 | 120 | 0.585526 |
Toni-SM/semu.misc.jupyter_notebook/exts/semu.misc.jupyter_notebook/data/launchers/ipykernel_launcher.py | import os
import sys
import json
import socket
import asyncio
SOCKET_HOST = "127.0.0.1"
SOCKET_PORT = 8224
PACKAGES_PATH = []
SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
# add packages to sys.path
with open(os.path.join(SCRIPT_DIR, "packages.txt"), "r") as f:
for p in f.readlines():
p = p.strip()
if p:
PACKAGES_PATH.append(p)
if p not in sys.path:
print("Adding package to sys.path: {}".format(p))
sys.path.append(p)
from ipykernel.kernelbase import Kernel
from ipykernel.kernelapp import IPKernelApp
async def _send_and_recv(message):
reader, writer = await asyncio.open_connection(host=SOCKET_HOST,
port=SOCKET_PORT,
family=socket.AF_INET)
writer.write(message.encode())
await writer.drain()
data = await reader.read()
writer.close()
await writer.wait_closed()
return data.decode()
def _get_line_column(code, cursor_pos):
line = code.count('\n', 0, cursor_pos) + 1
last_newline_pos = code.rfind('\n', 0, cursor_pos)
column = cursor_pos - last_newline_pos - 1
return line, column
class EmbeddedKernel(Kernel):
"""Omniverse Kit Python wrapper kernels
It re-use the IPython's kernel machinery
https://jupyter-client.readthedocs.io/en/latest/wrapperkernels.html
"""
# kernel info: https://jupyter-client.readthedocs.io/en/latest/messaging.html#kernel-info
implementation = "Omniverse Kit (Python 3)"
implementation_version = "0.1.0"
language_info = {
"name": "python",
"version": "3.7", # TODO: get from Omniverse Kit
"mimetype": "text/x-python",
"file_extension": ".py",
}
banner = "Embedded Omniverse (Python 3)"
help_links = [{"text": "semu.misc.jupyter_notebook", "url": "https://github.com/Toni-SM/semu.misc.jupyter_notebook"}]
async def do_execute(self, code, silent, store_history=True, user_expressions=None, allow_stdin=False):
"""Execute user code
"""
# https://jupyter-client.readthedocs.io/en/latest/messaging.html#execute
execute_reply = {"status": "ok",
"execution_count": self.execution_count,
"payload": [],
"user_expressions": {}}
# no code
if not code.strip():
return execute_reply
# magic commands
if code.startswith('%'):
# TODO: process magic commands
pass
# python code
try:
data = await _send_and_recv(code)
reply_content = json.loads(data)
except Exception as e:
# show network error in client
print("\x1b[0;31m==================================================\x1b[0m")
print("\x1b[0;31mKernel error at port {}\x1b[0m".format(SOCKET_PORT))
print(e)
print("\x1b[0;31m==================================================\x1b[0m")
reply_content = {"status": "error", "output": "", "traceback": [], "ename": str(type(e).__name__), "evalue": str(e)}
# code execution stdout: {"status": str, "output": str}
if not silent:
if reply_content["output"]:
stream_content = {"name": "stdout", "text": reply_content["output"]}
self.send_response(self.iopub_socket, "stream", stream_content)
reply_content.pop("output", None)
# code execution error: {"status": str("error"), "output": str, "traceback": list(str), "ename": str, "evalue": str}
if reply_content["status"] == "error":
self.send_response(self.iopub_socket, "error", reply_content)
# update reply
execute_reply["status"] = reply_content["status"]
execute_reply["execution_count"] = self.execution_count, # the base class increments the execution count
return execute_reply
def do_debug_request(self, msg):
return {}
async def do_complete(self, code, cursor_pos):
"""Code completation
"""
# https://jupyter-client.readthedocs.io/en/latest/messaging.html#msging-completion
complete_reply = {"status": "ok",
"matches": [],
"cursor_start": 0,
"cursor_end": cursor_pos,
"metadata": {}}
# parse code
code = code[:cursor_pos]
if not code or code[-1] in [' ', '=', ':', '(', ')']:
return complete_reply
# generate completions
try:
data = await _send_and_recv("%!c" + code)
reply_content = json.loads(data)
except Exception as e:
# show network error in client
print("\x1b[0;31m==================================================\x1b[0m")
print("\x1b[0;31mKernel error at port {}\x1b[0m".format(SOCKET_PORT))
print(e)
print("\x1b[0;31m==================================================\x1b[0m")
reply_content = {"matches": [], "delta": cursor_pos}
# update replay: {"matches": list(str), "delta": int}
complete_reply["matches"] = reply_content["matches"]
complete_reply["cursor_start"] = cursor_pos - reply_content["delta"]
return complete_reply
async def do_inspect(self, code, cursor_pos, detail_level=0, omit_sections=()):
"""Object introspection
"""
# https://jupyter-client.readthedocs.io/en/latest/messaging.html#msging-inspection
inspect_reply = {"status": "ok",
"found": False,
"data": {},
"metadata": {}}
line, column = _get_line_column(code, cursor_pos)
# generate introspection
try:
data = await _send_and_recv(f"%!i{line}:{column}%" + code)
reply_content = json.loads(data)
except Exception as e:
# show network error in client
print("\x1b[0;31m==================================================\x1b[0m")
print("\x1b[0;31mKernel error at port {}\x1b[0m".format(SOCKET_PORT))
print(e)
print("\x1b[0;31m==================================================\x1b[0m")
reply_content = {"found": False, "data": cursor_pos}
# update replay: {"found": bool, "data": str}
if reply_content["found"]:
inspect_reply["found"] = reply_content["found"]
inspect_reply["data"] = {"text/plain": reply_content["data"]}
return inspect_reply
if __name__ == "__main__":
if sys.path[0] == "":
del sys.path[0]
# read socket port from file
if os.path.exists(os.path.join(SCRIPT_DIR, "socket.txt")):
with open(os.path.join(SCRIPT_DIR, "socket.txt"), "r") as f:
SOCKET_PORT = int(f.read())
IPKernelApp.launch_instance(kernel_class=EmbeddedKernel)
| 7,057 | Python | 36.743315 | 128 | 0.530679 |
Toni-SM/semu.misc.jupyter_notebook/exts/semu.misc.jupyter_notebook/data/provisioners/embedded_omniverse_python3/provisioner_socket.py | from typing import Any, List
import os
import sys
from jupyter_client.provisioning import LocalProvisioner
from jupyter_client.connect import KernelConnectionInfo
from jupyter_client.launcher import launch_kernel
class Provisioner(LocalProvisioner):
async def launch_kernel(self, cmd: List[str], **kwargs: Any) -> KernelConnectionInfo:
# set paths
if sys.platform == 'win32':
cmd[0] = os.path.abspath(os.path.join(os.path.dirname(os.__file__), "..", "python.exe"))
else:
cmd[0] = os.path.abspath(os.path.join(os.path.dirname(os.__file__), "..", "..", "bin", "python3"))
cmd[1] = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "..", "launchers", "ipykernel_launcher.py"))
self.log.info("Launching kernel: %s", " ".join(cmd))
scrubbed_kwargs = LocalProvisioner._scrub_kwargs(kwargs)
self.process = launch_kernel(cmd, **scrubbed_kwargs)
pgid = None
if hasattr(os, "getpgid"):
try:
pgid = os.getpgid(self.process.pid)
except OSError:
pass
self.pid = self.process.pid
self.pgid = pgid
return self.connection_info
| 1,210 | Python | 34.617646 | 123 | 0.61405 |
Toni-SM/semu.data.visualizer/README.md | ## Data visualizer for NVIDIA Omniverse apps
This extension allows to switch [Matplotlib](https://matplotlib.org/) and [OpenCV](https://docs.opencv.org/) backend to display graphics and images inside NVIDIA Omniverse apps without modifying the code logic
<br>
**Target applications:** Any NVIDIA Omniverse app
**Supported OS:** Windows and Linux
**Changelog:** [CHANGELOG.md](src/semu.data.visualizer/docs/CHANGELOG.md)
**Table of Contents:**
- [Extension setup](#setup)
- [Extension usage](#usage)
<br>

<hr>
<a name="setup"></a>
### Extension setup
1. Add the extension using the [Extension Manager](https://docs.omniverse.nvidia.com/prod_extensions/prod_extensions/ext_extension-manager.html) or by following the steps in [Extension Search Paths](https://docs.omniverse.nvidia.com/py/kit/docs/guide/extensions.html#extension-search-paths)
* Git url (git+https) as extension search path
```
git+https://github.com/Toni-SM/semu.data.visualizer.git?branch=main&dir=exts
```
To install the source code version use the following url
```
git+https://github.com/Toni-SM/semu.data.visualizer.git?branch=main&dir=src
```
* Compressed (.zip) file for import
[semu.data.visualizer.zip](https://github.com/Toni-SM/semu.data.visualizer/releases)
2. Enable the extension using the [Extension Manager](https://docs.omniverse.nvidia.com/prod_extensions/prod_extensions/ext_extension-manager.html) or by following the steps in [Extension Enabling/Disabling](https://docs.omniverse.nvidia.com/py/kit/docs/guide/extensions.html#extension-enabling-disabling)
<hr>
<a name="usage"></a>
### Extension usage
**Enabling the extension** switches the Matplotlib and OpenCV backends **to display graphics and images in the Omniverse app**
Disabling the extension reverts the changes: graphics and images will be displayed in their respective windows by default, outside the Omniverse app
> **Note:** The current implementation does not support interaction with the displayed graphics or images
| 2,185 | Markdown | 37.350877 | 305 | 0.743707 |
Toni-SM/semu.data.visualizer/src/semu.data.visualizer/BUILD.md | ## Building form source
### Linux
```bash
cd src/semu.data.visualizer
bash compile_extension.bash
```
### Windows (Microsoft Visual C++ (MSVC))
We don't do that here!
### Windows (MinGW64)
#### Build extension
```batch
cd src\semu.data.visualizer
compile_extension.bat
```
#### Troubleshooting
* **Cannot find -lvcruntime140: No such file or directory**
```
cannot find -lvcruntime140: No such file or directory
```
Find and copy `vcruntime140.dll` to `...mingw64\lib\`
* **Error: enumerator value for '__pyx_check_sizeof_voidp' is not an integer constant**
```
error: enumerator value for '__pyx_check_sizeof_voidp' is not an integer constant
```
Add -DMS_WIN64 to the build command (Cython issue [#2670](https://github.com/cython/cython/issues/2670#issuecomment-432212671))
* **ValueError: Unknown MS Compiler version XXXX**
```
ValueError: Unknown MS Compiler version XXXX
```
Apply this [path](https://bugs.python.org/file40608/patch.diff) or just return `return ['vcruntime140']` in `...distutils\cygwinccompiler.py`
## Removing old compiled files
Get a fresh clone of the repository and follow the next steps
```bash
# remove compiled files _visualizer.cpython-37m-x86_64-linux-gnu.so
git filter-repo --invert-paths --path exts/semu.data.visualizer/semu/data/visualizer/_visualizer.cpython-37m-x86_64-linux-gnu.so
git filter-repo --invert-paths --path exts/semu.data.visualizer/semu/data/visualizer/_visualizer.cp37-win_amd64.pyd
# add origin
git remote add origin [email protected]:Toni-SM/semu.data.visualizer.git
# push changes
git push origin --force --all
git push origin --force --tags
```
## Packaging the extension
```bash
cd src/semu.data.visualizer
bash package_extension.bash
``` | 1,769 | Markdown | 23.929577 | 145 | 0.714528 |
Toni-SM/semu.data.visualizer/src/semu.data.visualizer/compile_extension.py | import os
import sys
from distutils.core import setup
from distutils.extension import Extension
from Cython.Distutils import build_ext
# OV python (kit\python\include)
if sys.platform == 'win32':
python_library_dir = os.path.join(os.path.dirname(sys.executable), "include")
elif sys.platform == 'linux':
python_library_dir = os.path.join(os.path.dirname(sys.executable), "..", "include")
if not os.path.exists(python_library_dir):
raise Exception("OV Python library directory not found: {}".format(python_library_dir))
ext_modules = [
Extension("_visualizer",
[os.path.join("semu", "data", "visualizer", "visualizer.py")],
library_dirs=[python_library_dir]),
]
setup(
name = 'semu.data.visualizer',
cmdclass = {'build_ext': build_ext},
ext_modules = ext_modules
)
| 825 | Python | 28.499999 | 91 | 0.682424 |
Toni-SM/semu.data.visualizer/src/semu.data.visualizer/semu/data/visualizer/__init__.py | from .scripts.extension import *
| 33 | Python | 15.999992 | 32 | 0.787879 |
Toni-SM/semu.data.visualizer/src/semu.data.visualizer/semu/data/visualizer/visualizer.py | import os
import sys
import carb
import omni
import omni.ui as ui
try:
import numpy as np
except ImportError:
print("numpy not found. Attempting to install...")
omni.kit.pipapi.install("numpy")
import numpy as np
try:
import matplotlib
except ImportError:
print("matplotlib not found. Attempting to install...")
omni.kit.pipapi.install("matplotlib")
import matplotlib
try:
import cv2
except ImportError:
print("opencv-python not found. Attempting to install...")
omni.kit.pipapi.install("opencv-python")
import cv2
from matplotlib.figure import Figure
from matplotlib.backend_bases import FigureManagerBase
from matplotlib.backends.backend_agg import FigureCanvasAgg
from matplotlib._pylab_helpers import Gcf
def acquire_visualizer_interface(ext_id: str = "") -> dict:
"""Acquire the visualizer interface
:param ext_id: The extension id
:type ext_id: str
:returns: The interface
:rtype: dict
"""
global _opencv_windows
# add current path to sys.path to import the backend
path = os.path.dirname(__file__)
if path not in sys.path:
sys.path.append(path)
# get matplotlib backend
matplotlib_backend = matplotlib.get_backend()
if type(matplotlib_backend) is str:
if matplotlib_backend.lower() == "agg":
matplotlib_backend = carb.settings.get_settings().get("/exts/semu.data.visualizer/default_matplotlib_backend_if_agg")
else:
matplotlib_backend = carb.settings.get_settings().get("/exts/semu.data.visualizer/default_matplotlib_backend_if_agg")
interface = {"matplotlib_backend": matplotlib_backend,
"opencv_imshow": cv2.imshow,
"opencv_waitKey": cv2.waitKey}
# set custom matplotlib backend
if os.path.basename(__file__).startswith("_visualizer"):
matplotlib.use("module://_visualizer")
else:
print(">>>> [DEVELOPMENT] module://visualizer")
matplotlib.use("module://visualizer")
# set custom opencv methods
_opencv_windows = {}
cv2.imshow = _imshow
cv2.waitKey = _waitKey
return interface
def release_visualizer_interface(interface: dict) -> None:
"""Release the visualizer interface
:param interface: The interface to release
:type interface: dict
"""
# restore default matplotlib backend
try:
matplotlib.use(interface.get("matplotlib_backend", \
carb.settings.get_settings().get("/exts/semu.data.visualizer/default_matplotlib_backend_if_agg")))
except Exception as e:
matplotlib.use("Agg")
matplotlib.rcdefaults()
# restore default opencv imshow
try:
cv2.imshow = interface.get("opencv_imshow", None)
cv2.waitKey = interface.get("opencv_waitKey", None)
except Exception as e:
pass
# destroy all opencv windows
for window in _opencv_windows.values():
window.destroy()
_opencv_windows.clear()
# remove current path from sys.path
path = os.path.dirname(__file__)
if path in sys.path:
sys.path.remove(path)
# opencv backend
_opencv_windows = {}
def _imshow(winname: str, mat: np.ndarray) -> None:
"""Show the image
:param winname: The window name
:type winname: str
:param mat: The image
:type mat: np.ndarray
"""
if winname not in _opencv_windows:
_opencv_windows[winname] = FigureManager(None, winname)
_opencv_windows[winname].render_image(mat)
def _waitKey(delay: int = 0) -> int:
"""Wait for a key press on the canvas
:param delay: The delay in milliseconds
:type delay: int
:returns: The key code
:rtype: int
"""
return -1
# matplotlib backend
def draw_if_interactive():
"""
For image backends - is not required.
For GUI backends - this should be overridden if drawing should be done in
interactive python mode.
"""
pass
def show(*, block: bool = None) -> None:
"""Show all figures and enter the main loop
For image backends - is not required.
For GUI backends - show() is usually the last line of a pyplot script and
tells the backend that it is time to draw. In interactive mode, this should do nothing
:param block: If not None, the call will block until the figure is closed
:type block: bool
"""
for manager in Gcf.get_all_fig_managers():
manager.show(block=block)
def new_figure_manager(num: int, *args, FigureClass: type = Figure, **kwargs) -> 'FigureManagerOmniUi':
"""Create a new figure manager instance
:param num: The figure number
:type num: int
:param args: The arguments to be passed to the Figure constructor
:type args: tuple
:param FigureClass: The class to use for creating the figure
:type FigureClass: type
:param kwargs: The keyword arguments to be passed to the Figure constructor
:type kwargs: dict
:returns: The figure manager instance
:rtype: FigureManagerOmniUi
"""
return new_figure_manager_given_figure(num, FigureClass(*args, **kwargs))
def new_figure_manager_given_figure(num: int, figure: 'Figure') -> 'FigureManagerOmniUi':
"""Create a new figure manager instance for the given figure.
:param num: The figure number
:type num: int
:param figure: The figure
:type figure: Figure
:returns: The figure manager instance
:rtype: FigureManagerOmniUi
"""
canvas = FigureCanvasAgg(figure)
manager = FigureManagerOmniUi(canvas, num)
return manager
class FigureManagerOmniUi(FigureManagerBase):
def __init__(self, canvas: 'FigureCanvasBase', num: int) -> None:
"""Figure manager for the Omni UI backend
:param canvas: The canvas
:type canvas: FigureCanvasBase
:param num: The figure number
:type num: int
"""
if canvas is not None:
super().__init__(canvas, num)
self._window_title = "Figure {}".format(num) if type(num) is int else num
self._byte_provider = None
self._window = None
def destroy(self) -> None:
"""Destroy the figure window"""
try:
self._byte_provider = None
self._window = None
except:
pass
def set_window_title(self, title: str) -> None:
"""Set the window title
:param title: The title
:type title: str
"""
self._window_title = title
try:
self._window.title = title
except:
pass
def get_window_title(self) -> str:
"""Get the window title
:returns: The window title
:rtype: str
"""
return self._window_title
def resize(self, w: int, h: int) -> None:
"""Resize the window
:param w: The width
:type w: int
:param h: The height
:type h: int
"""
print("[WARNING] resize() is not implemented")
def show(self, *, block: bool = None) -> None:
"""Show the figure window
:param block: If not None, the call will block until the figure is closed
:type block: bool
"""
# draw canvas and get figure
self.canvas.draw()
image = np.asarray(self.canvas.buffer_rgba())
# show figure
self.render_image(image=image,
figsize=(self.canvas.figure.get_figwidth(), self.canvas.figure.get_figheight()),
dpi=self.canvas.figure.get_dpi())
def render_image(self, image: np.ndarray, figsize: tuple = (6.4, 4.8), dpi: int = 100) -> None:
"""Set and display the image in the window (inner function)
:param image: The image
:type image: np.ndarray
:param figsize: The figure size
:type figsize: tuple
:param dpi: The dpi
:type dpi: int
"""
height, width = image.shape[:2]
# convert image to 4-channel RGBA
if image.ndim == 2:
image = np.dstack((image, image, image, np.full((height, width, 1), 255, dtype=np.uint8)))
elif image.ndim == 3:
if image.shape[2] == 3:
image = np.dstack((image, np.full((height, width, 1), 255, dtype=np.uint8)))
# enable the window visibility
if self._window is not None and not self._window.visible:
self._window.visible = True
# create the byte provider
if self._byte_provider is None:
self._byte_provider = ui.ByteImageProvider()
self._byte_provider.set_bytes_data(image.flatten().data, [width, height])
# update the byte provider
else:
self._byte_provider.set_bytes_data(image.flatten().data, [width, height])
# create the window
if self._window is None:
self._window = ui.Window(self._window_title,
width=int(figsize[0] * dpi),
height=int(figsize[1] * dpi),
visible=True)
with self._window.frame:
with ui.VStack():
ui.ImageWithProvider(self._byte_provider)
# provide the standard names that backend.__init__ is expecting
FigureCanvas = FigureCanvasAgg
FigureManager = FigureManagerOmniUi
| 9,315 | Python | 29.544262 | 129 | 0.619431 |
Toni-SM/semu.data.visualizer/src/semu.data.visualizer/semu/data/visualizer/scripts/extension.py | import omni.ext
try:
from .. import _visualizer
except:
print(">>>> [DEVELOPMENT] import visualizer")
from .. import visualizer as _visualizer
class Extension(omni.ext.IExt):
def on_startup(self, ext_id):
self._interface = _visualizer.acquire_visualizer_interface(ext_id)
def on_shutdown(self):
_visualizer.release_visualizer_interface(self._interface)
| 393 | Python | 23.624999 | 74 | 0.692112 |
Toni-SM/semu.data.visualizer/src/semu.data.visualizer/semu/data/visualizer/tests/test_visualizer.py | import omni.kit.test
class TestExtension(omni.kit.test.AsyncTestCaseFailOnLogError):
async def setUp(self) -> None:
pass
async def tearDown(self) -> None:
pass
async def test_extension(self):
pass | 235 | Python | 20.454544 | 63 | 0.659574 |
Toni-SM/semu.data.visualizer/src/semu.data.visualizer/semu/data/visualizer/tests/__init__.py | from .test_visualizer import *
| 31 | Python | 14.999993 | 30 | 0.774194 |
Toni-SM/semu.data.visualizer/src/semu.data.visualizer/config/extension.toml | [core]
reloadable = true
order = 0
[package]
version = "0.2.0"
category = "Other"
feature = false
app = false
title = "Data Visualizer (Plots and Images)"
description = "Switch Matplotlib and OpenCV backend to display graphics and images inside NVIDIA Omniverse apps"
authors = ["Toni-SM"]
repository = "https://github.com/Toni-SM/semu.data.visualizer"
keywords = ["data", "image", "plot"]
changelog = "docs/CHANGELOG.md"
readme = "docs/README.md"
preview_image = "data/preview.png"
icon = "data/icon.png"
[package.target]
config = ["release"]
platform = ["linux-*", "windows-*"]
python = ["*"]
[dependencies]
"omni.ui" = {}
"omni.kit.uiapp" = {}
"omni.kit.pipapi" = {}
[python.pipapi]
requirements = ["numpy", "matplotlib", "opencv-python"]
[[python.module]]
name = "semu.data.visualizer"
[[python.module]]
name = "semu.data.visualizer.tests"
[settings]
exts."semu.data.visualizer".default_matplotlib_backend_if_agg = "Agg"
| 932 | TOML | 21.756097 | 112 | 0.694206 |
Toni-SM/semu.data.visualizer/src/semu.data.visualizer/docs/CHANGELOG.md | # Changelog
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).
## [0.2.0] - 2022-05-21
### Changed
- Rename the extension to `semu.data.visualizer`
## [0.1.0] - 2022-03-28
### Added
- Source code (src folder)
- Availability for Windows operating system
### Changed
- Rewrite the extension to implement a mechanism to change the Matplotlib
and OpenCV backend to display graphics and images inside NVIDIA Omniverse apps
- Improve the display process performance
### Removed
- Omniverse native plots
## [0.0.1] - 2021-06-18
### Added
- Update extension to Isaac Sim 2021.1.0 extension format
| 629 | Markdown | 23.230768 | 80 | 0.72337 |
Toni-SM/semu.data.visualizer/src/semu.data.visualizer/docs/README.md | # semu.data.visualizer
This extension allows to switch Matplotlib and OpenCV backend to display graphics and images inside NVIDIA Omniverse apps without modifying the code logic
Visit https://github.com/Toni-SM/semu.data.visualizer to read more about its use
| 262 | Markdown | 36.571423 | 154 | 0.816794 |
Toni-SM/semu.data.visualizer/exts/semu.data.visualizer/semu/data/visualizer/__init__.py | from .scripts.extension import *
| 33 | Python | 15.999992 | 32 | 0.787879 |
Toni-SM/semu.data.visualizer/exts/semu.data.visualizer/semu/data/visualizer/scripts/extension.py | import omni.ext
try:
from .. import _visualizer
except:
print(">>>> [DEVELOPMENT] import visualizer")
from .. import visualizer as _visualizer
class Extension(omni.ext.IExt):
def on_startup(self, ext_id):
self._interface = _visualizer.acquire_visualizer_interface(ext_id)
def on_shutdown(self):
_visualizer.release_visualizer_interface(self._interface)
| 393 | Python | 23.624999 | 74 | 0.692112 |
Toni-SM/semu.data.visualizer/exts/semu.data.visualizer/semu/data/visualizer/tests/test_visualizer.py | import omni.kit.test
class TestExtension(omni.kit.test.AsyncTestCaseFailOnLogError):
async def setUp(self) -> None:
pass
async def tearDown(self) -> None:
pass
async def test_extension(self):
pass | 235 | Python | 20.454544 | 63 | 0.659574 |
Toni-SM/semu.data.visualizer/exts/semu.data.visualizer/semu/data/visualizer/tests/__init__.py | from .test_visualizer import *
| 31 | Python | 14.999993 | 30 | 0.774194 |
Toni-SM/semu.data.visualizer/exts/semu.data.visualizer/config/extension.toml | [core]
reloadable = true
order = 0
[package]
version = "0.2.0"
category = "Other"
feature = false
app = false
title = "Data Visualizer (Plots and Images)"
description = "Switch Matplotlib and OpenCV backend to display graphics and images inside NVIDIA Omniverse apps"
authors = ["Toni-SM"]
repository = "https://github.com/Toni-SM/semu.data.visualizer"
keywords = ["data", "image", "plot"]
changelog = "docs/CHANGELOG.md"
readme = "docs/README.md"
preview_image = "data/preview.png"
icon = "data/icon.png"
[package.target]
config = ["release"]
platform = ["linux-*", "windows-*"]
python = ["*"]
[dependencies]
"omni.ui" = {}
"omni.kit.uiapp" = {}
"omni.kit.pipapi" = {}
[python.pipapi]
requirements = ["numpy", "matplotlib", "opencv-python"]
[[python.module]]
name = "semu.data.visualizer"
[[python.module]]
name = "semu.data.visualizer.tests"
[settings]
exts."semu.data.visualizer".default_matplotlib_backend_if_agg = "Agg"
| 932 | TOML | 21.756097 | 112 | 0.694206 |
Toni-SM/semu.data.visualizer/exts/semu.data.visualizer/docs/CHANGELOG.md | # Changelog
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).
## [0.2.0] - 2022-05-21
### Changed
- Rename the extension to `semu.data.visualizer`
## [0.1.0] - 2022-03-28
### Added
- Source code (src folder)
- Availability for Windows operating system
### Changed
- Rewrite the extension to implement a mechanism to change the Matplotlib
and OpenCV backend to display graphics and images inside NVIDIA Omniverse apps
- Improve the display process performance
### Removed
- Omniverse native plots
## [0.0.1] - 2021-06-18
### Added
- Update extension to Isaac Sim 2021.1.0 extension format
| 629 | Markdown | 23.230768 | 80 | 0.72337 |
Toni-SM/semu.data.visualizer/exts/semu.data.visualizer/docs/README.md | # semu.data.visualizer
This extension allows to switch Matplotlib and OpenCV backend to display graphics and images inside NVIDIA Omniverse apps without modifying the code logic
Visit https://github.com/Toni-SM/semu.data.visualizer to read more about its use
| 262 | Markdown | 36.571423 | 154 | 0.816794 |
Toni-SM/omni.add_on.ros_control_bridge/README.md | ## ROS Control Bridge (add-on) for NVIDIA Omniverse Isaac Sim
<br>
<hr>
<br>
:warning: :warning: :warning:
**This repository has been integrated into `semu.robotics.ros_bridge`, in which its source code has been released.**
**Visit [semu.robotics.ros_bridge](https://github.com/Toni-SM/semu.robotics.ros_bridge)**
:warning: :warning: :warning:
<br>
<hr>
<br>
> This extension enables the **ROS action interfaces used for controlling robots**. Particularly those used by [MoveIt](https://moveit.ros.org/) to talk with the controllers on the robot (**FollowJointTrajectory** and **GripperCommand**)
<br>
### Table of Contents
- [Prerequisites](#prerequisites)
- [Add the extension to an NVIDIA Omniverse app and enable it](#extension)
- [Control your robot using MoveIt](#control)
- [Configure a FollowJointTrajectory action](#follow_joint_trajectory)
- [Configure a GripperCommand action](#gripper_command)
<br>
<a name="prerequisites"></a>
### Prerequisites
All prerequisites described in [ROS & ROS2 Bridge](https://docs.omniverse.nvidia.com/app_isaacsim/app_isaacsim/ext_omni_isaac_ros_bridge.html) must be fulfilled before running this extension. In addition, this extension requires the following extensions to be present in Isaac Sim:
- [omni.usd.schema.add_on](https://github.com/Toni-SM/omni.usd.schema.add_on): USD add-on schemas
- [omni.add_on.ros_bridge_ui](https://github.com/Toni-SM/omni.add_on.ros_bridge_ui): Menu and commands
<br>
<a name="extension"></a>
### Add the extension to an NVIDIA Omniverse app and enable it
1. Add the the extension by following the steps described in [Extension Search Paths](https://docs.omniverse.nvidia.com/py/kit/docs/guide/extensions.html#extension-search-paths) or simply download and unzip the latest [release](https://github.com/Toni-SM/omni.add_on.ros_control_bridge/releases) in one of the extension folders such as ```PATH_TO_OMNIVERSE_APP/exts```
Git url (git+https) as extension search path:
```
git+https://github.com/Toni-SM/omni.add_on.ros_control_bridge.git?branch=main&dir=exts
```
2. Enable the extension by following the steps described in [Extension Enabling/Disabling](https://docs.omniverse.nvidia.com/py/kit/docs/guide/extensions.html#extension-enabling-disabling)
<br>
<a name="control"></a>
### Control your robot using MoveIt
#### Concepts
MoveIt's *move_group* talks to the robot through ROS topics and actions. Three interfaces are required to control the robot. Go to the [MoveIt](https://moveit.ros.org/) website to read more about the [concepts](https://moveit.ros.org/documentation/concepts/) behind it
- **Joint State information:** the ```/joint_states``` topic (publisher) is used to determining the current state information
- **Transform information:** the ROS TF library is used to monitor the transform information
- **Controller Interface:** *move_group* talks to the controllers on the robot using the *FollowJointTrajectory* action interface. However, it is possible to use other controller interfaces to control the robot
#### Configuration
**Isaac Sim side**
1. Import your robot from an URDF file using the [URDF Importer](https://docs.omniverse.nvidia.com/app_isaacsim/app_isaacsim/ext_omni_isaac_urdf.html) extension. Go to [ROS Wiki: Using Xacro](http://wiki.ros.org/urdf/Tutorials/Using%20Xacro%20to%20Clean%20Up%20a%20URDF%20File#Using_Xacro) to convert your robot description form ```.xacro``` to ```.urdf```
2. Add a *Joint State* topic using the menu (*Create > Isaac > ROS > Joint State*) according to the [ROS Bridge](https://docs.omniverse.nvidia.com/app_isaacsim/app_isaacsim/ext_omni_isaac_ros_bridge.html) extension
3. Add a *TF topic* using the menu (*Create > Isaac > ROS > Pose Tree*) according to the [ROS Bridge](https://docs.omniverse.nvidia.com/app_isaacsim/app_isaacsim/ext_omni_isaac_ros_bridge.html) extension
4. Add the corresponding ROS control actions implemented by this extension (**see the sections below**) according to your robotic application's requirements
**Note:** At that point, it is recommendable to setup the MoveIt YAML configuration file first to know the controllers' names and the action namespaces
5. Play the editor to activate the respective topics and actions. Remember the editor must be playing before launching the *move_group*
**MoveIt side**
1. Launch the [MoveIt Setup Assistant](http://docs.ros.org/en/melodic/api/moveit_tutorials/html/doc/setup_assistant/setup_assistant_tutorial.html) and generate a new configuration package loading the same ```.xacro``` or ```.urdf``` used in Isaac Sim. Also, select the same ROS controller interfaces inside the step *ROS Control*
```bash
roslaunch moveit_setup_assistant setup_assistant.launch
```
2. Launch the *move_group* using the configured controllers
For example, you can use the next launch file (sample.launch) which is configured to support the *FollowJointTrajectory* and *GripperCommand* controllers (panda_gripper_controllers.yaml) by replacing the ```panda_moveit_config``` with the generated folder's name and ```/panda/joint_state``` with the Isaac Sim joint state topic name
```bash
roslaunch moveit_config sample.launch
```
panda_gripper_controllers.yaml
```yaml
controller_list:
- name: panda_arm_controller
action_ns: follow_joint_trajectory
type: FollowJointTrajectory
default: true
joints:
- panda_joint1
- panda_joint2
- panda_joint3
- panda_joint4
- panda_joint5
- panda_joint6
- panda_joint7
- name: panda_gripper
action_ns: gripper_command
type: GripperCommand
default: true
joints:
- panda_finger_joint1
- panda_finger_joint2
```
sample.launch
```xml
<launch>
<!-- Load the URDF, SRDF and other .yaml configuration files on the param server -->
<include file="$(find panda_moveit_config)/launch/planning_context.launch">
<arg name="load_robot_description" value="true"/>
</include>
<!-- Publish joint states -->
<node name="joint_state_publisher" pkg="joint_state_publisher" type="joint_state_publisher">
<rosparam param="/source_list">["/panda/joint_state"]</rosparam>
</node>
<node name="joint_state_desired_publisher" pkg="topic_tools" type="relay" args="joint_states joint_states_desired"/>
<!-- Given the published joint states, publish tf for the robot links -->
<node name="robot_state_publisher" pkg="robot_state_publisher" type="robot_state_publisher" respawn="true" output="screen" />
<!-- Run the main MoveIt executable -->
<include file="$(find panda_moveit_config)/launch/move_group.launch">
<arg name="allow_trajectory_execution" value="true"/>
<arg name="info" value="true"/>
<arg name="debug" value="false"/>
</include>
<!-- Run Rviz (optional) -->
<include file="$(find panda_moveit_config)/launch/moveit_rviz.launch">
<arg name="debug" value="false"/>
</include>
</launch>
```
Also, you can modify the ```demo.launch``` file and disable the fake controller execution inside the main MoveIt executable
```xml
<arg name="fake_execution" value="false"/>
```
3. Use the Move Group [C++](http://docs.ros.org/en/melodic/api/moveit_tutorials/html/doc/move_group_interface/move_group_interface_tutorial.html) or [Python](http://docs.ros.org/en/melodic/api/moveit_tutorials/html/doc/move_group_python_interface/move_group_python_interface_tutorial.html) interfaces to control the robot
<br>
<a name="follow_joint_trajectory"></a>
### Configure a FollowJointTrajectory action
To add a ```FollowJointTrajectory``` action go to menu *Create > Isaac > ROS Control* and select *Follow Joint Trajectory*
To connect the schema with the robot of your choice, select the root of the articulation tree by pressing the *Add Target(s)* button under the ```articulationPrim``` field. Press the play button in the editor, and the topics related to this action will be activated for use
The communication shall take place in the namespace defined by the following fields:
```python
rosNodePrefix + controllerName + actionNamespace
```
<br>
The following figure shows a *FollowJointTrajectory* schema configured to match the ```panda_gripper_controllers.yaml``` described above

<br>
<a name="gripper_command"></a>
### Configure a GripperCommand action
To add a ```GripperCommand``` action go to menu *Create > Isaac > ROS Control* and select *Gripper Command*
To connect the schematic to the end-effector of your choice, first select the root of the articulation tree and then select each of the end-effector's articulations to control following this strict order. This can be done by pressing the *Add Target(s)* button repeatedly under the ```articulationPrim``` field. Press the play button in the editor, and the topics related to this action will be activated for use
The communication shall take place in the namespace defined by the following fields:
```python
rosNodePrefix + controllerName + actionNamespace
```
The ```GripperCommand``` action definition doesn't specify which joints will be controlled. The value manage by this action will affect all the specified joints equally
<br>
The following figure shows a *GripperCommand* schema configured to match the ```panda_gripper_controllers.yaml``` described above

| 9,798 | Markdown | 45.661905 | 412 | 0.726067 |
Toni-SM/semu.robotics.ros_bridge/README.md | ## ROS Bridge (external extension) for NVIDIA Omniverse Isaac Sim
> This extension enables the ROS action server interfaces for controlling robots (particularly those used by MoveIt to talk to robot controllers: [FollowJointTrajectory](http://docs.ros.org/en/api/control_msgs/html/action/FollowJointTrajectory.html) and [GripperCommand](http://docs.ros.org/en/api/control_msgs/html/action/GripperCommand.html)) and enables services for agile prototyping of robotic applications in [ROS](https://www.ros.org/)
<br>
**Target applications:** NVIDIA Omniverse Isaac Sim
**Supported OS:** Linux
**Changelog:** [CHANGELOG.md](exts/semu.robotics.ros_bridge/docs/CHANGELOG.md)
**Table of Contents:**
- [Prerequisites](#prerequisites)
- [Extension setup](#setup)
- [Extension usage](#usage)
- [Supported components](#components)
- [Attribute](#ros-attribute)
- [FollowJointTrajectory](#ros-follow-joint-trajectory)
- [GripperCommand](#ros-gripper-command)
<br>

<hr>
<a name="prerequisites"></a>
### Prerequisites
All prerequisites described in [ROS & ROS2 Bridge](https://docs.omniverse.nvidia.com/isaacsim/latest/features/external_communication/ext_omni_isaac_ros_bridge.html) must be fulfilled before running this extension
<hr>
<a name="setup"></a>
### Extension setup
1. Add the extension using the [Extension Manager](https://docs.omniverse.nvidia.com/prod_extensions/prod_extensions/ext_extension-manager.html) or by following the steps in [Extension Search Paths](https://docs.omniverse.nvidia.com/py/kit/docs/guide/extensions.html#extension-search-paths)
* Git url (git+https) as extension search path
:warning: *There seems to be a bug when installing extensions using the git url (git+https) as extension search path in Isaac Sim 2022.1.0. In this case, it is recommended to install the extension by importing the .zip file*
```
git+https://github.com/Toni-SM/semu.robotics.ros_bridge.git?branch=main&dir=exts
```
* Compressed (.zip) file for import
[semu.robotics.ros_bridge.zip](https://github.com/Toni-SM/semu.robotics.ros_bridge/releases)
2. Enable the extension using the [Extension Manager](https://docs.omniverse.nvidia.com/prod_extensions/prod_extensions/ext_extension-manager.html) or by following the steps in [Extension Enabling/Disabling](https://docs.omniverse.nvidia.com/py/kit/docs/guide/extensions.html#extension-enabling-disabling)
<hr>
<a name="usage"></a>
### Extension usage
Enabling the extension initializes a ROS node named `/SemuRosBridge` (configurable in the `extension.toml` file). This node will enable, when the simulation starts, the ROS topics, services and actions protocols according to the ROS prims (and their configurations) existing in the current stage
Disabling the extension shutdowns the ROS node and its respective active communication protocols
> **Note:** The current implementation only implements position control (velocity or effort control is not yet supported) for the FollowJointTrajectory and GripperCommand actions
<hr>
<a name="components"></a>
### Supported components

<br>
The following components are supported:
<a name="ros-attribute"></a>
* **Attribute (ROS service):** enables the services for getting and setting the attributes of a prim according to the service definitions described bellow
To add an Attribute service action search for ActionGraph nodes and select ***ROS1 Attribute Service***
The ROS package [add_on_msgs](https://github.com/Toni-SM/semu.robotics.ros_bridge/releases) contains the definition of the messages (download and add it to a ROS workspace). A sample code of a [python client application](https://github.com/Toni-SM/semu.robotics.ros_bridge/releases) is also provided
Prim attributes are retrieved and modified as JSON (applied directly to the data, without keys). Arrays, vectors, matrixes and other numeric classes (```pxr.Gf.Vec3f```, ```pxr.Gf.Matrix4d```, ```pxr.Gf.Quatf```, ```pxr.Vt.Vec2fArray```, etc.) are interpreted as a list of numbers (row first)
* **add_on_msgs.srv.GetPrims**: Get all prim path under the specified path
```yaml
string path # get prims at path
---
string[] paths # list of prim paths
string[] types # prim type names
bool success # indicate a successful execution of the service
string message # informational, e.g. for error messages
```
* **add_on_msgs.srv.GetPrimAttributes**: Get prim attribute names and their types
```yaml
string path # prim path
---
string[] names # list of attribute base names (name used to Get or Set an attribute)
string[] displays # list of attribute display names (name displayed in Property tab)
string[] types # list of attribute data types
bool success # indicate a successful execution of the service
string message # informational, e.g. for error messages
```
* **add_on_msgs.srv.GetPrimAttribute**: Get prim attribute
```yaml
string path # prim path
string attribute # attribute name
---
string value # attribute value (as JSON)
string type # attribute type
bool success # indicate a successful execution of the service
string message # informational, e.g. for error messages
```
* **add_on_msgs.srv.SetPrimAttribute**: Set prim attribute
```yaml
string path # prim path
string attribute # attribute name
string value # attribute value (as JSON)
---
bool success # indicate a successful execution of the service
string message # informational, e.g. for error messages
```
<a name="ros-follow-joint-trajectory"></a>
* **FollowJointTrajectory (ROS action):** enables the actions for a robot to follow a given trajectory
To add a FollowJointTrajectory action search for ActionGraph nodes and select ***ROS1 FollowJointTrajectory Action***
Select, by clicking the **Add Target(s)** button under the `inputs:targetPrims` field, the root of the robot's articulation tree to control and edit the fields that define the namespace of the communication. The communication will take place in the namespace defined by the following fields:
```
controllerName + actionNamespace
```
<a name="ros-gripper-command"></a>
* **GripperCommand (ROS action):** enables the actions to control a gripper
To add a GripperCommand action search for ActionGraph nodes and select ***ROS1 GripperCommand Action***
Select, by clicking the **Add Target(s)** button under the `inputs:targetPrims` field, the root of the robot's articulation tree to which the end-effector belongs and add the joints (of the gripper) to control using the `inputs:targetGripperJoints` field
Also, edit the fields that define the namespace of the communication. The communication will take place in the namespace defined by the following fields:
```
controllerName + actionNamespace
```
> **Note:** The GripperCommand action definition doesn't specify which joints will be controlled. The value manage by this action will affect all the specified joints equally
| 7,615 | Markdown | 47.509554 | 442 | 0.70151 |
Toni-SM/semu.robotics.ros_bridge/exts/semu.robotics.ros_bridge/semu/robotics/ros_bridge/ros_bridge.py | import omni
import carb
import rospy
import rosgraph
_ROS_NODE_RUNNING = False
def acquire_ros_bridge_interface(ext_id: str = "") -> 'RosBridge':
"""Acquire the RosBridge interface
:param ext_id: The extension id
:type ext_id: str
:returns: The RosBridge interface
:rtype: RosBridge
"""
return RosBridge()
def release_ros_bridge_interface(bridge: 'RosBridge') -> None:
"""Release the RosBridge interface
:param bridge: The RosBridge interface
:type bridge: RosBridge
"""
bridge.shutdown()
def is_ros_master_running() -> bool:
"""Check if the ROS master is running
:returns: True if the ROS master is running, False otherwise
:rtype: bool
"""
# check ROS master
try:
rosgraph.Master("/rostopic").getPid()
except:
return False
return True
def is_ros_node_running() -> bool:
"""Check if the ROS node is running
:returns: True if the ROS node is running, False otherwise
:rtype: bool
"""
return _ROS_NODE_RUNNING
class RosBridge:
def __init__(self) -> None:
"""Initialize the RosBridge interface
"""
self._node_name = carb.settings.get_settings().get("/exts/semu.robotics.ros_bridge/nodeName")
# omni objects and interfaces
self._timeline = omni.timeline.get_timeline_interface()
# events
self._timeline_event = self._timeline.get_timeline_event_stream().create_subscription_to_pop(self._on_timeline_event)
# ROS node
if is_ros_master_running():
self._init_ros_node()
def shutdown(self) -> None:
"""Shutdown the RosBridge interface
"""
self._timeline_event = None
rospy.signal_shutdown("semu.robotics.ros_bridge shutdown")
def _init_ros_node(self) -> None:
global _ROS_NODE_RUNNING
"""Initialize the ROS node
"""
try:
rospy.init_node(self._node_name, disable_signals=False)
_ROS_NODE_RUNNING = True
print("[Info][semu.robotics.ros_bridge] {} node started".format(self._node_name))
except rospy.ROSException as e:
print("[Error][semu.robotics.ros_bridge] {}: {}".format(self._node_name, e))
def _on_timeline_event(self, event: 'carb.events._events.IEvent') -> None:
"""Handle the timeline event
:param event: Event
:type event: carb.events._events.IEvent
"""
if event.type == int(omni.timeline.TimelineEventType.PLAY):
if is_ros_master_running():
self._init_ros_node()
elif event.type == int(omni.timeline.TimelineEventType.PAUSE):
pass
elif event.type == int(omni.timeline.TimelineEventType.STOP):
pass
| 2,777 | Python | 27.639175 | 125 | 0.613972 |
Toni-SM/semu.robotics.ros_bridge/exts/semu.robotics.ros_bridge/semu/robotics/ros_bridge/__init__.py | from .scripts.extension import *
| 33 | Python | 15.999992 | 32 | 0.787879 |
Toni-SM/semu.robotics.ros_bridge/exts/semu.robotics.ros_bridge/semu/robotics/ros_bridge/ogn/nodes/OgnROS1ActionGripperCommand.py | import omni
from pxr import PhysxSchema
from omni.isaac.dynamic_control import _dynamic_control
from omni.isaac.core.utils.stage import get_stage_units
import rospy
import actionlib
import control_msgs.msg
try:
from ... import _ros_bridge
except:
from ... import ros_bridge as _ros_bridge
class InternalState:
def __init__(self):
"""Internal state for the ROS1 GripperCommand node
"""
self.initialized = False
self.dci = None
self.usd_context = None
self.timeline_event = None
self.action_server = None
self.articulation_path = ""
self.gripper_joints_paths = []
self._articulation = _dynamic_control.INVALID_HANDLE
self._joints = {}
self._action_goal = None
self._action_goal_handle = None
self._action_start_time = None
# TODO: add to schema?
self._action_timeout = 10.0
self._action_position_threshold = 0.001
self._action_previous_position_sum = float("inf")
# feedback / result
self._action_result_message = control_msgs.msg.GripperCommandResult()
self._action_feedback_message = control_msgs.msg.GripperCommandFeedback()
def on_timeline_event(self, event: 'carb.events._events.IEvent') -> None:
"""Handle the timeline event
:param event: Event
:type event: carb.events._events.IEvent
"""
if event.type == int(omni.timeline.TimelineEventType.PLAY):
pass
elif event.type == int(omni.timeline.TimelineEventType.PAUSE):
pass
elif event.type == int(omni.timeline.TimelineEventType.STOP):
self.initialized = False
self.shutdown_action_server()
self._articulation = _dynamic_control.INVALID_HANDLE
self._joints = {}
self._action_goal = None
self._action_goal_handle = None
self._action_start_time = None
def shutdown_action_server(self) -> None:
"""Shutdown the action server
"""
# omni.isaac.ros_bridge/noetic/lib/python3/dist-packages/actionlib/action_server.py
print("[Info][semu.robotics.ros_bridge] ROS1 GripperCommand: destroying action server")
if self.action_server:
if self.action_server.started:
self.action_server.started = False
self.action_server.status_pub.unregister()
self.action_server.result_pub.unregister()
self.action_server.feedback_pub.unregister()
self.action_server.goal_sub.unregister()
self.action_server.cancel_sub.unregister()
del self.action_server
self.action_server = None
def _init_articulation(self) -> None:
"""Initialize the articulation and register joints
"""
# get articulation
path = self.articulation_path
self._articulation = self.dci.get_articulation(path)
if self._articulation == _dynamic_control.INVALID_HANDLE:
print("[Warning][semu.robotics.ros_bridge] ROS1 GripperCommand: {} is not an articulation".format(path))
return
dof_props = self.dci.get_articulation_dof_properties(self._articulation)
if dof_props is None:
return
upper_limits = dof_props["upper"]
lower_limits = dof_props["lower"]
has_limits = dof_props["hasLimits"]
# get joints
for i in range(self.dci.get_articulation_dof_count(self._articulation)):
dof_ptr = self.dci.get_articulation_dof(self._articulation, i)
if dof_ptr != _dynamic_control.DofType.DOF_NONE:
# add only required joints
if self.dci.get_dof_path(dof_ptr) in self.gripper_joints_paths:
dof_name = self.dci.get_dof_name(dof_ptr)
if dof_name not in self._joints:
_joint = self.dci.find_articulation_joint(self._articulation, dof_name)
self._joints[dof_name] = {"joint": _joint,
"type": self.dci.get_joint_type(_joint),
"dof": self.dci.find_articulation_dof(self._articulation, dof_name),
"lower": lower_limits[i],
"upper": upper_limits[i],
"has_limits": has_limits[i]}
if not self._joints:
print("[Warning][semu.robotics.ros_bridge] ROS1 GripperCommand: no joints found in {}".format(path))
self.initialized = False
def _set_joint_position(self, name: str, target_position: float) -> None:
"""Set the target position of a joint in the articulation
:param name: The joint name
:type name: str
:param target_position: The target position
:type target_position: float
"""
# clip target position
if self._joints[name]["has_limits"]:
target_position = min(max(target_position, self._joints[name]["lower"]), self._joints[name]["upper"])
# scale target position for prismatic joints
if self._joints[name]["type"] == _dynamic_control.JOINT_PRISMATIC:
target_position /= get_stage_units()
# set target position
self.dci.set_dof_position_target(self._joints[name]["dof"], target_position)
def _get_joint_position(self, name: str) -> float:
"""Get the current position of a joint in the articulation
:param name: The joint name
:type name: str
:return: The current position of the joint
:rtype: float
"""
position = self.dci.get_dof_state(self._joints[name]["dof"], _dynamic_control.STATE_POS).pos
if self._joints[name]["type"] == _dynamic_control.JOINT_PRISMATIC:
return position * get_stage_units()
return position
def on_goal(self, goal_handle: 'actionlib.ServerGoalHandle') -> None:
"""Callback function for handling new goal requests
:param goal_handle: The goal handle
:type goal_handle: actionlib.ServerGoalHandle
"""
goal = goal_handle.get_goal()
# reject if there is an active goal
if self._action_goal is not None:
print("[Warning][semu.robotics.ros_bridge] ROS1 GripperCommand: multiple goals not supported")
goal_handle.set_rejected()
return
# store goal data
self._action_goal = goal
self._action_goal_handle = goal_handle
self._action_start_time = rospy.get_time()
self._action_previous_position_sum = float("inf")
goal_handle.set_accepted()
def on_cancel(self, goal_handle: 'actionlib.ServerGoalHandle') -> None:
"""Callback function for handling cancel requests
:param goal_handle: The goal handle
:type goal_handle: actionlib.ServerGoalHandle
"""
if self._action_goal is None:
goal_handle.set_rejected()
return
self._action_goal = None
self._action_goal_handle = None
self._action_start_time = None
self._action_previous_position_sum = float("inf")
goal_handle.set_canceled()
def step(self, dt: float) -> None:
"""Update step
:param dt: Delta time
:type dt: float
"""
if not self.initialized:
return
# init articulation
if not self._joints:
self._init_articulation()
return
# update articulation
if self._action_goal is not None and self._action_goal_handle is not None:
target_position = self._action_goal.command.position
# set target
self.dci.wake_up_articulation(self._articulation)
for name in self._joints:
self._set_joint_position(name, target_position)
# end (position reached)
position = 0
current_position_sum = 0
position_reached = True
for name in self._joints:
position = self._get_joint_position(name)
current_position_sum += position
if abs(position - target_position) > self._action_position_threshold:
position_reached = False
break
if position_reached:
self._action_goal = None
self._action_result_message.position = position
self._action_result_message.stalled = False
self._action_result_message.reached_goal = True
if self._action_goal_handle is not None:
self._action_goal_handle.set_succeeded(self._action_result_message)
self._action_goal_handle = None
return
# end (stalled)
if abs(current_position_sum - self._action_previous_position_sum) < 1e-6:
self._action_goal = None
self._action_result_message.position = position
self._action_result_message.stalled = True
self._action_result_message.reached_goal = False
if self._action_goal_handle is not None:
self._action_goal_handle.set_succeeded(self._action_result_message)
self._action_goal_handle = None
return
self._action_previous_position_sum = current_position_sum
# end (timeout)
time_passed = rospy.get_time() - self._action_start_time
if time_passed >= self._action_timeout:
self._action_goal = None
if self._action_goal_handle is not None:
self._action_goal_handle.set_aborted()
self._action_goal_handle = None
# TODO: send feedback
# self._action_goal_handle.publish_feedback(self._action_feedback_message)
class OgnROS1ActionGripperCommand:
"""This node provides the services to list, read and write prim's attributes
"""
@staticmethod
def initialize(graph_context, node):
pass
@staticmethod
def internal_state() -> InternalState:
return InternalState()
@staticmethod
def compute(db) -> bool:
if not _ros_bridge.is_ros_node_running():
return False
if db.internal_state.initialized:
db.internal_state.step(0)
else:
try:
db.internal_state.usd_context = omni.usd.get_context()
db.internal_state.dci = _dynamic_control.acquire_dynamic_control_interface()
if db.internal_state.timeline_event is None:
timeline = omni.timeline.get_timeline_interface()
db.internal_state.timeline_event = timeline.get_timeline_event_stream() \
.create_subscription_to_pop(db.internal_state.on_timeline_event)
def get_action_name(namespace, controller_name, action_namespace):
controller_name = controller_name if controller_name.startswith("/") else "/" + controller_name
action_namespace = action_namespace if action_namespace.startswith("/") else "/" + action_namespace
return namespace if namespace else "" + controller_name + action_namespace
def get_relationships(node, usd_context, attribute):
stage = usd_context.get_stage()
prim = stage.GetPrimAtPath(node.get_prim_path())
return prim.GetRelationship(attribute).GetTargets()
# check for articulation
path = db.inputs.targetPrim.path
if not len(path):
print("[Warning][semu.robotics.ros_bridge] ROS1 GripperCommand: targetPrim not set")
return
# check for articulation API
stage = db.internal_state.usd_context.get_stage()
if not stage.GetPrimAtPath(path).HasAPI(PhysxSchema.PhysxArticulationAPI):
print("[Warning][semu.robotics.ros_bridge] ROS1 GripperCommand: {} doesn't have PhysxArticulationAPI".format(path))
return
db.internal_state.articulation_path = path
# check for gripper joints
relationships = get_relationships(db.node, db.internal_state.usd_context, "inputs:targetGripperJoints")
paths = [relationship.GetPrimPath().pathString for relationship in relationships]
if not paths:
print("[Warning][semu.robotics.ros_bridge] ROS1 GripperCommand: targetGripperJoints not set")
return
db.internal_state.gripper_joints_paths = paths
# create action server
db.internal_state.shutdown_action_server()
action_name = get_action_name(db.inputs.nodeNamespace, db.inputs.controllerName, db.inputs.actionNamespace)
db.internal_state.action_server = actionlib.ActionServer(action_name,
control_msgs.msg.GripperCommandAction,
goal_cb=db.internal_state.on_goal,
cancel_cb=db.internal_state.on_cancel,
auto_start=False)
db.internal_state.action_server.start()
print("[Info][semu.robotics.ros_bridge] ROS1 GripperCommand: register action {}".format(action_name))
except ConnectionRefusedError as error:
print("[Error][semu.robotics.ros_bridge] ROS1 GripperCommand: action server {} not started".format(action_name))
db.log_error(str(error))
db.internal_state.initialized = False
return False
except Exception as error:
print("[Error][semu.robotics.ros_bridge] ROS1 GripperCommand: error: {}".format(error))
db.log_error(str(error))
db.internal_state.initialized = False
return False
db.internal_state.initialized = True
return True
| 14,448 | Python | 41.875371 | 135 | 0.576412 |
Toni-SM/semu.robotics.ros_bridge/exts/semu.robotics.ros_bridge/semu/robotics/ros_bridge/ogn/nodes/OgnROS1ServiceAttribute.py | from typing import Any
import json
import asyncio
import threading
import omni
import carb
from pxr import Usd, Gf
from omni.isaac.dynamic_control import _dynamic_control
import rospy
try:
from ... import _ros_bridge
except:
from ... import ros_bridge as _ros_bridge
class InternalState:
def __init__(self):
"""Internal state for the ROS1 Attribute node
"""
self.initialized = False
self.dci = None
self.usd_context = None
self.timeline_event = None
self.GetPrims = None
self.GetPrimAttributes = None
self.GetPrimAttribute = None
self.SetPrimAttribute = None
self.srv_prims = None
self.srv_attributes = None
self.srv_getter = None
self.srv_setter = None
self._event = threading.Event()
self._event.set()
self.__event_timeout = carb.settings.get_settings().get("/exts/semu.robotics.ros_bridge/eventTimeout")
self.__set_attribute_using_asyncio = \
carb.settings.get_settings().get("/exts/semu.robotics.ros_bridge/setAttributeUsingAsyncio")
print("[Info][semu.robotics.ros_bridge] ROS1 Attribute: asyncio: {}".format(self.__set_attribute_using_asyncio))
print("[Info][semu.robotics.ros_bridge] ROS1 Attribute: event timeout: {}".format(self.__event_timeout))
def on_timeline_event(self, event: 'carb.events._events.IEvent') -> None:
"""Handle the timeline event
:param event: Event
:type event: carb.events._events.IEvent
"""
if event.type == int(omni.timeline.TimelineEventType.PLAY):
pass
elif event.type == int(omni.timeline.TimelineEventType.PAUSE):
pass
elif event.type == int(omni.timeline.TimelineEventType.STOP):
self.initialized = False
self.shutdown_services()
def shutdown_services(self) -> None:
"""Shutdown the services
"""
if self.srv_prims is not None:
print("[Info][semu.robotics.ros_bridge] RosAttribute: unregister srv: {}".format(self.srv_prims.resolved_name))
self.srv_prims.shutdown()
self.srv_prims = None
if self.srv_getter is not None:
print("[Info][semu.robotics.ros_bridge] RosAttribute: unregister srv: {}".format(self.srv_getter.resolved_name))
self.srv_getter.shutdown()
self.srv_getter = None
if self.srv_attributes is not None:
print("[Info][semu.robotics.ros_bridge] RosAttribute: unregister srv: {}".format(self.srv_attributes.resolved_name))
self.srv_attributes.shutdown()
self.srv_attributes = None
if self.srv_setter is not None:
print("[Info][semu.robotics.ros_bridge] RosAttribute: unregister srv: {}".format(self.srv_setter.resolved_name))
self.srv_setter.shutdown()
self.srv_setter = None
async def _set_attribute(self, attribute: 'pxr.Usd.Attribute', attribute_value: Any) -> None:
"""Set the attribute value using asyncio
:param attribute: The prim's attribute to set
:type attribute: pxr.Usd.Attribute
:param attribute_value: The attribute value
:type attribute_value: Any
"""
ret = attribute.Set(attribute_value)
def process_setter_request(self, request: 'SetPrimAttribute.SetPrimAttributeRequest') -> 'SetPrimAttribute.SetPrimAttributeResponse':
"""Process the setter request
:param request: The service request
:type request: SetPrimAttribute.SetPrimAttributeRequest
:return: The service response
:rtype: SetPrimAttribute.SetPrimAttributeResponse
"""
response = self.SetPrimAttribute.SetPrimAttributeResponse()
response.success = False
stage = self.usd_context.get_stage()
# get prim
if stage.GetPrimAtPath(request.path).IsValid():
prim = stage.GetPrimAtPath(request.path)
if request.attribute and prim.HasAttribute(request.attribute):
# attribute
attribute = prim.GetAttribute(request.attribute)
attribute_type = type(attribute.Get()).__name__
# value
try:
value = json.loads(request.value)
attribute_value = None
except json.JSONDecodeError:
print("[Error][semu.robotics.ros_bridge] ROS1 Attribute: invalid value: {}".format(request.value))
response.success = False
response.message = "Invalid value '{}'".format(request.value)
return response
# parse data
try:
if attribute_type in ['Vec2d', 'Vec2f', 'Vec2h', 'Vec2i']:
attribute_value = type(attribute.Get())(value)
elif attribute_type in ['Vec3d', 'Vec3f', 'Vec3h', 'Vec3i']:
attribute_value = type(attribute.Get())(value)
elif attribute_type in ['Vec4d', 'Vec4f', 'Vec4h', 'Vec4i']:
attribute_value = type(attribute.Get())(value)
elif attribute_type in ['Quatd', 'Quatf', 'Quath']:
attribute_value = type(attribute.Get())(*value)
elif attribute_type in ['Matrix4d', 'Matrix4f']:
attribute_value = type(attribute.Get())(value)
elif attribute_type.startswith('Vec') and attribute_type.endswith('Array'):
attribute_value = type(attribute.Get())(value)
elif attribute_type.startswith('Matrix') and attribute_type.endswith('Array'):
if attribute_type.endswith("dArray"):
attribute_value = type(attribute.Get())([Gf.Matrix2d(v) for v in value])
elif attribute_type.endswith("fArray"):
attribute_value = type(attribute.Get())([Gf.Matrix2f(v) for v in value])
elif attribute_type.startswith('Quat') and attribute_type.endswith('Array'):
if attribute_type.endswith("dArray"):
attribute_value = type(attribute.Get())([Gf.Quatd(*v) for v in value])
elif attribute_type.endswith("fArray"):
attribute_value = type(attribute.Get())([Gf.Quatf(*v) for v in value])
elif attribute_type.endswith("hArray"):
attribute_value = type(attribute.Get())([Gf.Quath(*v) for v in value])
elif attribute_type.endswith('Array'):
attribute_value = type(attribute.Get())(value)
elif attribute_type in ['AssetPath']:
attribute_value = type(attribute.Get())(value)
elif attribute_type in ['NoneType']:
pass
else:
attribute_value = type(attribute.Get())(value)
# set attribute
if attribute_value is not None:
# set attribute usign asyncio
if self.__set_attribute_using_asyncio:
try:
loop = asyncio.get_event_loop()
except:
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
future = asyncio.ensure_future(self._set_attribute(attribute, attribute_value))
loop.run_until_complete(future)
response.success = True
# set attribute in the physics event
else:
self._attribute = attribute
self._value = attribute_value
self._event.clear()
response.success = self._event.wait(self.__event_timeout)
if not response.success:
response.message = "The timeout ({} s) for setting the attribute value has been reached" \
.format(self.__event_timeout)
except Exception as e:
print("[Error][semu.robotics.ros_bridge] ROS1 Attribute: srv {} request for {} ({}: {}): {}" \
.format(self.srv_setter.resolved_name, request.path, request.attribute, value, e))
response.success = False
response.message = str(e)
else:
response.message = "Prim has not attribute {}".format(request.attribute)
else:
response.message = "Invalid prim ({})".format(request.path)
return response
def process_getter_request(self, request: 'GetPrimAttribute.GetPrimAttributeRequest') -> 'GetPrimAttribute.GetPrimAttributeResponse':
"""Process the getter request
:param request: The service request
:type request: GetPrimAttribute.GetPrimAttributeRequest
:return: The service response
:rtype: GetPrimAttribute.GetPrimAttributeResponse
"""
response = self.GetPrimAttribute.GetPrimAttributeResponse()
response.success = False
stage = self.usd_context.get_stage()
# get prim
if stage.GetPrimAtPath(request.path).IsValid():
prim = stage.GetPrimAtPath(request.path)
if request.attribute and prim.HasAttribute(request.attribute):
attribute = prim.GetAttribute(request.attribute)
response.type = type(attribute.Get()).__name__
# parse data
response.success = True
if response.type in ['Vec2d', 'Vec2f', 'Vec2h', 'Vec2i']:
data = attribute.Get()
response.value = json.dumps([data[i] for i in range(2)])
elif response.type in ['Vec3d', 'Vec3f', 'Vec3h', 'Vec3i']:
data = attribute.Get()
response.value = json.dumps([data[i] for i in range(3)])
elif response.type in ['Vec4d', 'Vec4f', 'Vec4h', 'Vec4i']:
data = attribute.Get()
response.value = json.dumps([data[i] for i in range(4)])
elif response.type in ['Quatd', 'Quatf', 'Quath']:
data = attribute.Get()
response.value = json.dumps([data.real, data.imaginary[0], data.imaginary[1], data.imaginary[2]])
elif response.type in ['Matrix4d', 'Matrix4f']:
data = attribute.Get()
response.value = json.dumps([[data.GetRow(i)[j] for j in range(data.dimension[1])] \
for i in range(data.dimension[0])])
elif response.type.startswith('Vec') and response.type.endswith('Array'):
data = attribute.Get()
response.value = json.dumps([[d[i] for i in range(len(d))] for d in data])
elif response.type.startswith('Matrix') and response.type.endswith('Array'):
data = attribute.Get()
response.value = json.dumps([[[d.GetRow(i)[j] for j in range(d.dimension[1])] \
for i in range(d.dimension[0])] for d in data])
elif response.type.startswith('Quat') and response.type.endswith('Array'):
data = attribute.Get()
response.value = json.dumps([[d.real, d.imaginary[0], d.imaginary[1], d.imaginary[2]] for d in data])
elif response.type.endswith('Array'):
try:
response.value = json.dumps(list(attribute.Get()))
except Exception as e:
print("[Warning][semu.robotics.ros_bridge] ROS1 Attribute: Unknow attribute type {}" \
.format(type(attribute.Get())))
print(" |-- Please, report a new issue (https://github.com/Toni-SM/semu.robotics.ros_bridge/issues)")
response.success = False
response.message = "Unknow type {}".format(type(attribute.Get()))
elif response.type in ['AssetPath']:
response.value = json.dumps(str(attribute.Get().path))
else:
try:
response.value = json.dumps(attribute.Get())
except Exception as e:
print("[Warning][semu.robotics.ros_bridge] ROS1 Attribute: Unknow {}: {}" \
.format(type(attribute.Get()), attribute.Get()))
print(" |-- Please, report a new issue (https://github.com/Toni-SM/semu.robotics.ros_bridge/issues)")
response.success = False
response.message = "Unknow type {}".format(type(attribute.Get()))
else:
response.message = "Prim has not attribute {}".format(request.attribute)
else:
response.message = "Invalid prim ({})".format(request.path)
return response
def process_attributes_request(self, request: 'GetPrimAttributes.GetPrimAttributesRequest') -> 'GetPrimAttributes.GetPrimAttributesResponse':
"""Process the 'get all attributes' request
:param request: The service request
:type request: GetPrimAttributes.GetPrimAttributesRequest
:return: The service response
:rtype: GetPrimAttributes.GetPrimAttributesResponse
"""
response = self.GetPrimAttributes.GetPrimAttributesResponse()
response.success = False
stage = self.usd_context.get_stage()
# get prim
if stage.GetPrimAtPath(request.path).IsValid():
prim = stage.GetPrimAtPath(request.path)
for attribute in prim.GetAttributes():
if attribute.GetNamespace():
response.names.append("{}:{}".format(attribute.GetNamespace(), attribute.GetBaseName()))
else:
response.names.append(attribute.GetBaseName())
response.displays.append(attribute.GetDisplayName())
response.types.append(type(attribute.Get()).__name__)
response.success = True
else:
response.message = "Invalid prim ({})".format(request.path)
return response
def process_prims_request(self, request: 'GetPrims.GetPrimsRequest') -> 'GetPrims.GetPrimsResponse':
"""Process the 'get all prims' request
:param request: The service request
:type request: GetPrims.GetPrimsRequest
:return: The service response
:rtype: GetPrims.GetPrimsResponse
"""
response = self.GetPrims.GetPrimsResponse()
response.success = False
stage = self.usd_context.get_stage()
# get prims
if not request.path or stage.GetPrimAtPath(request.path).IsValid():
path = request.path if request.path else "/"
for prim in Usd.PrimRange.AllPrims(stage.GetPrimAtPath(path)):
response.paths.append(str(prim.GetPath()))
response.types.append(prim.GetTypeName())
response.success = True
else:
response.message = "Invalid search path ({})".format(request.path)
return response
def step(self, dt: float) -> None:
"""Update step
:param dt: Delta time
:type dt: float
"""
if not self.initialized:
return
if self.__set_attribute_using_asyncio:
return
if self.dci.is_simulating():
if not self._event.is_set():
if self._attribute is not None:
ret = self._attribute.Set(self._value)
self._event.set()
class OgnROS1ServiceAttribute:
"""This node provides the services to list, read and write prim's attributes
"""
@staticmethod
def initialize(graph_context, node):
pass
@staticmethod
def internal_state() -> InternalState:
return InternalState()
@staticmethod
def compute(db) -> bool:
if not _ros_bridge.is_ros_node_running():
return False
if db.internal_state.initialized:
db.internal_state.step(0)
else:
try:
db.internal_state.usd_context = omni.usd.get_context()
db.internal_state.dci = _dynamic_control.acquire_dynamic_control_interface()
if db.internal_state.timeline_event is None:
timeline = omni.timeline.get_timeline_interface()
db.internal_state.timeline_event = timeline.get_timeline_event_stream() \
.create_subscription_to_pop(db.internal_state.on_timeline_event)
def get_service_name(namespace, name):
service_namespace = namespace if namespace.startswith("/") else "/" + namespace
service_name = name if name.startswith("/") else "/" + name
return service_namespace if namespace else "" + service_name
# load service definitions
from add_on_msgs.srv import _GetPrims
from add_on_msgs.srv import _GetPrimAttributes
from add_on_msgs.srv import _GetPrimAttribute
from add_on_msgs.srv import _SetPrimAttribute
db.internal_state.GetPrims = _GetPrims
db.internal_state.GetPrimAttributes = _GetPrimAttributes
db.internal_state.GetPrimAttribute = _GetPrimAttribute
db.internal_state.SetPrimAttribute = _SetPrimAttribute
# create services
db.internal_state.shutdown_services()
service_name = get_service_name(db.inputs.nodeNamespace, db.inputs.primsServiceName)
db.internal_state.srv_prims = rospy.Service(service_name,
db.internal_state.GetPrims.GetPrims,
db.internal_state.process_prims_request)
print("[Info][semu.robotics.ros_bridge] ROS1 Attribute: register srv: {}".format(db.internal_state.srv_prims.resolved_name))
service_name = get_service_name(db.inputs.nodeNamespace, db.inputs.getAttributesServiceName)
db.internal_state.srv_attributes = rospy.Service(service_name,
db.internal_state.GetPrimAttributes.GetPrimAttributes,
db.internal_state.process_attributes_request)
print("[Info][semu.robotics.ros_bridge] ROS1 Attribute: register srv: {}".format(db.internal_state.srv_attributes.resolved_name))
service_name = get_service_name(db.inputs.nodeNamespace, db.inputs.getAttributeServiceName)
db.internal_state.srv_getter = rospy.Service(service_name,
db.internal_state.GetPrimAttribute.GetPrimAttribute,
db.internal_state.process_getter_request)
print("[Info][semu.robotics.ros_bridge] ROS1 Attribute: register srv: {}".format(db.internal_state.srv_getter.resolved_name))
service_name = get_service_name(db.inputs.nodeNamespace, db.inputs.setAttributeServiceName)
db.internal_state.srv_setter = rospy.Service(service_name,
db.internal_state.SetPrimAttribute.SetPrimAttribute,
db.internal_state.process_setter_request)
print("[Info][semu.robotics.ros_bridge] ROS1 Attribute: register srv: {}".format(db.internal_state.srv_setter.resolved_name))
except Exception as error:
print("[Error][semu.robotics.ros_bridge] ROS1 Attribute: error: {}".format(error))
db.log_error(str(error))
db.internal_state.initialized = False
return False
db.internal_state.initialized = True
return True
| 20,602 | Python | 49.497549 | 145 | 0.557713 |
Toni-SM/semu.robotics.ros_bridge/exts/semu.robotics.ros_bridge/semu/robotics/ros_bridge/ogn/nodes/OgnROS1ActionFollowJointTrajectory.py | import omni
from pxr import PhysxSchema
from omni.isaac.dynamic_control import _dynamic_control
from omni.isaac.core.utils.stage import get_stage_units
import rospy
import actionlib
import control_msgs.msg
from trajectory_msgs.msg import JointTrajectoryPoint
try:
from ... import _ros_bridge
except:
from ... import ros_bridge as _ros_bridge
class InternalState:
def __init__(self):
"""Internal state for the ROS1 FollowJointTrajectory node
"""
self.initialized = False
self.dci = None
self.usd_context = None
self.timeline_event = None
self.action_server = None
self.articulation_path = ""
self._articulation = _dynamic_control.INVALID_HANDLE
self._joints = {}
self._action_goal = None
self._action_goal_handle = None
self._action_start_time = None
self._action_point_index = 1
# feedback / result
self._action_result_message = control_msgs.msg.FollowJointTrajectoryResult()
self._action_feedback_message = control_msgs.msg.FollowJointTrajectoryFeedback()
def on_timeline_event(self, event: 'carb.events._events.IEvent') -> None:
"""Handle the timeline event
:param event: Event
:type event: carb.events._events.IEvent
"""
if event.type == int(omni.timeline.TimelineEventType.PLAY):
pass
elif event.type == int(omni.timeline.TimelineEventType.PAUSE):
pass
elif event.type == int(omni.timeline.TimelineEventType.STOP):
self.initialized = False
self.shutdown_action_server()
self._articulation = _dynamic_control.INVALID_HANDLE
self._joints = {}
self._action_goal = None
self._action_goal_handle = None
self._action_start_time = None
self._action_point_index = 1
def shutdown_action_server(self) -> None:
"""Shutdown the action server
"""
# noetic/lib/python3/dist-packages/actionlib/action_server.py
print("[Info][semu.robotics.ros_bridge] ROS1 FollowJointTrajectory: destroying action server")
if self.action_server:
if self.action_server.started:
self.action_server.started = False
self.action_server.status_pub.unregister()
self.action_server.result_pub.unregister()
self.action_server.feedback_pub.unregister()
self.action_server.goal_sub.unregister()
self.action_server.cancel_sub.unregister()
del self.action_server
self.action_server = None
def _init_articulation(self) -> None:
"""Initialize the articulation and register joints
"""
# get articulation
path = self.articulation_path
self._articulation = self.dci.get_articulation(path)
if self._articulation == _dynamic_control.INVALID_HANDLE:
print("[Warning][semu.robotics.ros_bridge] ROS1 FollowJointTrajectory: {} is not an articulation".format(path))
return
dof_props = self.dci.get_articulation_dof_properties(self._articulation)
if dof_props is None:
return
upper_limits = dof_props["upper"]
lower_limits = dof_props["lower"]
has_limits = dof_props["hasLimits"]
# get joints
for i in range(self.dci.get_articulation_dof_count(self._articulation)):
dof_ptr = self.dci.get_articulation_dof(self._articulation, i)
if dof_ptr != _dynamic_control.DofType.DOF_NONE:
dof_name = self.dci.get_dof_name(dof_ptr)
if dof_name not in self._joints:
_joint = self.dci.find_articulation_joint(self._articulation, dof_name)
self._joints[dof_name] = {"joint": _joint,
"type": self.dci.get_joint_type(_joint),
"dof": self.dci.find_articulation_dof(self._articulation, dof_name),
"lower": lower_limits[i],
"upper": upper_limits[i],
"has_limits": has_limits[i]}
if not self._joints:
print("[Warning][semu.robotics.ros_bridge] ROS1 FollowJointTrajectory: no joints found in {}".format(path))
self.initialized = False
def _set_joint_position(self, name: str, target_position: float) -> None:
"""Set the target position of a joint in the articulation
:param name: The joint name
:type name: str
:param target_position: The target position
:type target_position: float
"""
# clip target position
if self._joints[name]["has_limits"]:
target_position = min(max(target_position, self._joints[name]["lower"]), self._joints[name]["upper"])
# scale target position for prismatic joints
if self._joints[name]["type"] == _dynamic_control.JOINT_PRISMATIC:
target_position /= get_stage_units()
# set target position
self.dci.set_dof_position_target(self._joints[name]["dof"], target_position)
def _get_joint_position(self, name: str) -> float:
"""Get the current position of a joint in the articulation
:param name: The joint name
:type name: str
:return: The current position of the joint
:rtype: float
"""
position = self.dci.get_dof_state(self._joints[name]["dof"], _dynamic_control.STATE_POS).pos
if self._joints[name]["type"] == _dynamic_control.JOINT_PRISMATIC:
return position * get_stage_units()
return position
def on_goal(self, goal_handle: 'actionlib.ServerGoalHandle') -> None:
"""Callback function for handling new goal requests
:param goal_handle: The goal handle
:type goal_handle: actionlib.ServerGoalHandle
"""
goal = goal_handle.get_goal()
# reject if joints don't match
for name in goal.trajectory.joint_names:
if name not in self._joints:
print("[Warning][semu.robotics.ros_bridge] ROS1 FollowJointTrajectory: joints don't match ({} not in {})" \
.format(name, list(self._joints.keys())))
self._action_result_message.error_code = self._action_result_message.INVALID_JOINTS
goal_handle.set_rejected(self._action_result_message, "")
return
# reject if there is an active goal
if self._action_goal is not None:
print("[Warning][semu.robotics.ros_bridge] ROS1 FollowJointTrajectory: multiple goals not supported")
self._action_result_message.error_code = self._action_result_message.INVALID_GOAL
goal_handle.set_rejected(self._action_result_message, "")
return
# check initial position
if goal.trajectory.points[0].time_from_start.to_sec():
initial_point = JointTrajectoryPoint(positions=[self._get_joint_position(name) for name in goal.trajectory.joint_names],
time_from_start=rospy.Duration())
goal.trajectory.points.insert(0, initial_point)
# store goal data
self._action_goal = goal
self._action_goal_handle = goal_handle
self._action_point_index = 1
self._action_start_time = rospy.get_time()
self._action_feedback_message.joint_names = list(goal.trajectory.joint_names)
goal_handle.set_accepted()
def on_cancel(self, goal_handle: 'actionlib.ServerGoalHandle') -> None:
"""Callback function for handling cancel requests
:param goal_handle: The goal handle
:type goal_handle: actionlib.ServerGoalHandle
"""
if self._action_goal is None:
goal_handle.set_rejected()
return
self._action_goal = None
self._action_goal_handle = None
self._action_start_time = None
goal_handle.set_canceled()
def step(self, dt: float) -> None:
"""Update step
:param dt: Delta time
:type dt: float
"""
if not self.initialized:
return
# init articulation
if not self._joints:
self._init_articulation()
return
# update articulation
if self._action_goal is not None and self._action_goal_handle is not None:
# end of trajectory
if self._action_point_index >= len(self._action_goal.trajectory.points):
self._action_goal = None
self._action_result_message.error_code = self._action_result_message.SUCCESSFUL
if self._action_goal_handle is not None:
self._action_goal_handle.set_succeeded(self._action_result_message)
self._action_goal_handle = None
return
previous_point = self._action_goal.trajectory.points[self._action_point_index - 1]
current_point = self._action_goal.trajectory.points[self._action_point_index]
time_passed = rospy.get_time() - self._action_start_time
# set target using linear interpolation
if time_passed <= current_point.time_from_start.to_sec():
ratio = (time_passed - previous_point.time_from_start.to_sec()) \
/ (current_point.time_from_start.to_sec() - previous_point.time_from_start.to_sec())
self.dci.wake_up_articulation(self._articulation)
for i, name in enumerate(self._action_goal.trajectory.joint_names):
side = -1 if current_point.positions[i] < previous_point.positions[i] else 1
target_position = previous_point.positions[i] \
+ side * ratio * abs(current_point.positions[i] - previous_point.positions[i])
self._set_joint_position(name, target_position)
# send feedback
else:
self._action_point_index += 1
self._action_feedback_message.actual.positions = [self._get_joint_position(name) \
for name in self._action_goal.trajectory.joint_names]
self._action_feedback_message.actual.time_from_start = rospy.Duration.from_sec(time_passed)
if self._action_goal_handle is not None:
self._action_goal_handle.publish_feedback(self._action_feedback_message)
class OgnROS1ActionFollowJointTrajectory:
"""This node provides the services to list, read and write prim's attributes
"""
@staticmethod
def initialize(graph_context, node):
pass
@staticmethod
def internal_state() -> InternalState:
return InternalState()
@staticmethod
def compute(db) -> bool:
if not _ros_bridge.is_ros_node_running():
return False
if db.internal_state.initialized:
db.internal_state.step(0)
else:
try:
db.internal_state.usd_context = omni.usd.get_context()
db.internal_state.dci = _dynamic_control.acquire_dynamic_control_interface()
if db.internal_state.timeline_event is None:
timeline = omni.timeline.get_timeline_interface()
db.internal_state.timeline_event = timeline.get_timeline_event_stream() \
.create_subscription_to_pop(db.internal_state.on_timeline_event)
def get_action_name(namespace, controller_name, action_namespace):
controller_name = controller_name if controller_name.startswith("/") else "/" + controller_name
action_namespace = action_namespace if action_namespace.startswith("/") else "/" + action_namespace
return namespace if namespace else "" + controller_name + action_namespace
# check for articulation
path = db.inputs.targetPrim.path
if not len(path):
print("[Warning][semu.robotics.ros_bridge] ROS1 FollowJointTrajectory: empty targetPrim")
return
# check for articulation API
stage = db.internal_state.usd_context.get_stage()
if not stage.GetPrimAtPath(path).HasAPI(PhysxSchema.PhysxArticulationAPI):
print("[Warning][semu.robotics.ros_bridge] ROS1 FollowJointTrajectory: {} doesn't have PhysxArticulationAPI".format(path))
return
db.internal_state.articulation_path = path
# create action server
db.internal_state.shutdown_action_server()
action_name = get_action_name(db.inputs.nodeNamespace, db.inputs.controllerName, db.inputs.actionNamespace)
db.internal_state.action_server = actionlib.ActionServer(action_name,
control_msgs.msg.FollowJointTrajectoryAction,
goal_cb=db.internal_state.on_goal,
cancel_cb=db.internal_state.on_cancel,
auto_start=False)
db.internal_state.action_server.start()
print("[Info][semu.robotics.ros_bridge] ROS1 FollowJointTrajectory: register action {}".format(action_name))
except ConnectionRefusedError as error:
print("[Error][semu.robotics.ros_bridge] ROS1 FollowJointTrajectory: action server {} not started".format(action_name))
db.log_error(str(error))
db.internal_state.initialized = False
return False
except Exception as error:
print("[Error][semu.robotics.ros_bridge] ROS1 FollowJointTrajectory: error: {}".format(error))
db.log_error(str(error))
db.internal_state.initialized = False
return False
db.internal_state.initialized = True
return True
| 14,361 | Python | 43.602484 | 142 | 0.587285 |
Toni-SM/semu.robotics.ros_bridge/exts/semu.robotics.ros_bridge/semu/robotics/ros_bridge/scripts/extension.py | import os
import sys
import carb
import omni.ext
import omni.graph.core as og
try:
from .. import _ros_bridge
except:
from .. import ros_bridge as _ros_bridge
class Extension(omni.ext.IExt):
def on_startup(self, ext_id):
self._rosbridge = None
self._extension_path = None
ext_manager = omni.kit.app.get_app().get_extension_manager()
if ext_manager.is_extension_enabled("omni.isaac.ros2_bridge"):
carb.log_error("ROS Bridge external extension cannot be enabled if ROS 2 Bridge is enabled")
ext_manager.set_extension_enabled("semu.robotics.ros_bridge", False)
return
self._extension_path = ext_manager.get_extension_path(ext_id)
sys.path.append(os.path.join(self._extension_path, "semu", "robotics", "ros_bridge", "packages"))
self._rosbridge = _ros_bridge.acquire_ros_bridge_interface(ext_id)
og.register_ogn_nodes(__file__, "semu.robotics.ros_bridge")
def on_shutdown(self):
if self._extension_path is not None:
sys.path.remove(os.path.join(self._extension_path, "semu", "robotics", "ros_bridge", "packages"))
self._extension_path = None
if self._rosbridge is not None:
_ros_bridge.release_ros_bridge_interface(self._rosbridge)
self._rosbridge = None
| 1,345 | Python | 36.388888 | 109 | 0.646097 |
Toni-SM/semu.robotics.ros_bridge/exts/semu.robotics.ros_bridge/semu/robotics/ros_bridge/packages/add_on_msgs/srv/_SetPrimAttribute.py | # This Python file uses the following encoding: utf-8
"""autogenerated by genpy from add_on_msgs/SetPrimAttributeRequest.msg. Do not edit."""
import codecs
import sys
python3 = True if sys.hexversion > 0x03000000 else False
import genpy
import struct
class SetPrimAttributeRequest(genpy.Message):
_md5sum = "c72cd1009a2d47b7e1ab3f88d1ff98e3"
_type = "add_on_msgs/SetPrimAttributeRequest"
_has_header = False # flag to mark the presence of a Header object
_full_text = """string path # prim path
string attribute # attribute name
string value # attribute value (as JSON)
"""
__slots__ = ['path','attribute','value']
_slot_types = ['string','string','string']
def __init__(self, *args, **kwds):
"""
Constructor. Any message fields that are implicitly/explicitly
set to None will be assigned a default value. The recommend
use is keyword arguments as this is more robust to future message
changes. You cannot mix in-order arguments and keyword arguments.
The available fields are:
path,attribute,value
:param args: complete set of field values, in .msg order
:param kwds: use keyword arguments corresponding to message field names
to set specific fields.
"""
if args or kwds:
super(SetPrimAttributeRequest, self).__init__(*args, **kwds)
# message fields cannot be None, assign default values for those that are
if self.path is None:
self.path = ''
if self.attribute is None:
self.attribute = ''
if self.value is None:
self.value = ''
else:
self.path = ''
self.attribute = ''
self.value = ''
def _get_types(self):
"""
internal API method
"""
return self._slot_types
def serialize(self, buff):
"""
serialize message into buffer
:param buff: buffer, ``StringIO``
"""
try:
_x = self.path
length = len(_x)
if python3 or type(_x) == unicode:
_x = _x.encode('utf-8')
length = len(_x)
buff.write(struct.Struct('<I%ss'%length).pack(length, _x))
_x = self.attribute
length = len(_x)
if python3 or type(_x) == unicode:
_x = _x.encode('utf-8')
length = len(_x)
buff.write(struct.Struct('<I%ss'%length).pack(length, _x))
_x = self.value
length = len(_x)
if python3 or type(_x) == unicode:
_x = _x.encode('utf-8')
length = len(_x)
buff.write(struct.Struct('<I%ss'%length).pack(length, _x))
except struct.error as se: self._check_types(struct.error("%s: '%s' when writing '%s'" % (type(se), str(se), str(locals().get('_x', self)))))
except TypeError as te: self._check_types(ValueError("%s: '%s' when writing '%s'" % (type(te), str(te), str(locals().get('_x', self)))))
def deserialize(self, str):
"""
unpack serialized message in str into this message instance
:param str: byte array of serialized message, ``str``
"""
if python3:
codecs.lookup_error("rosmsg").msg_type = self._type
try:
end = 0
start = end
end += 4
(length,) = _struct_I.unpack(str[start:end])
start = end
end += length
if python3:
self.path = str[start:end].decode('utf-8', 'rosmsg')
else:
self.path = str[start:end]
start = end
end += 4
(length,) = _struct_I.unpack(str[start:end])
start = end
end += length
if python3:
self.attribute = str[start:end].decode('utf-8', 'rosmsg')
else:
self.attribute = str[start:end]
start = end
end += 4
(length,) = _struct_I.unpack(str[start:end])
start = end
end += length
if python3:
self.value = str[start:end].decode('utf-8', 'rosmsg')
else:
self.value = str[start:end]
return self
except struct.error as e:
raise genpy.DeserializationError(e) # most likely buffer underfill
def serialize_numpy(self, buff, numpy):
"""
serialize message with numpy array types into buffer
:param buff: buffer, ``StringIO``
:param numpy: numpy python module
"""
try:
_x = self.path
length = len(_x)
if python3 or type(_x) == unicode:
_x = _x.encode('utf-8')
length = len(_x)
buff.write(struct.Struct('<I%ss'%length).pack(length, _x))
_x = self.attribute
length = len(_x)
if python3 or type(_x) == unicode:
_x = _x.encode('utf-8')
length = len(_x)
buff.write(struct.Struct('<I%ss'%length).pack(length, _x))
_x = self.value
length = len(_x)
if python3 or type(_x) == unicode:
_x = _x.encode('utf-8')
length = len(_x)
buff.write(struct.Struct('<I%ss'%length).pack(length, _x))
except struct.error as se: self._check_types(struct.error("%s: '%s' when writing '%s'" % (type(se), str(se), str(locals().get('_x', self)))))
except TypeError as te: self._check_types(ValueError("%s: '%s' when writing '%s'" % (type(te), str(te), str(locals().get('_x', self)))))
def deserialize_numpy(self, str, numpy):
"""
unpack serialized message in str into this message instance using numpy for array types
:param str: byte array of serialized message, ``str``
:param numpy: numpy python module
"""
if python3:
codecs.lookup_error("rosmsg").msg_type = self._type
try:
end = 0
start = end
end += 4
(length,) = _struct_I.unpack(str[start:end])
start = end
end += length
if python3:
self.path = str[start:end].decode('utf-8', 'rosmsg')
else:
self.path = str[start:end]
start = end
end += 4
(length,) = _struct_I.unpack(str[start:end])
start = end
end += length
if python3:
self.attribute = str[start:end].decode('utf-8', 'rosmsg')
else:
self.attribute = str[start:end]
start = end
end += 4
(length,) = _struct_I.unpack(str[start:end])
start = end
end += length
if python3:
self.value = str[start:end].decode('utf-8', 'rosmsg')
else:
self.value = str[start:end]
return self
except struct.error as e:
raise genpy.DeserializationError(e) # most likely buffer underfill
_struct_I = genpy.struct_I
def _get_struct_I():
global _struct_I
return _struct_I
# This Python file uses the following encoding: utf-8
"""autogenerated by genpy from add_on_msgs/SetPrimAttributeResponse.msg. Do not edit."""
import codecs
import sys
python3 = True if sys.hexversion > 0x03000000 else False
import genpy
import struct
class SetPrimAttributeResponse(genpy.Message):
_md5sum = "937c9679a518e3a18d831e57125ea522"
_type = "add_on_msgs/SetPrimAttributeResponse"
_has_header = False # flag to mark the presence of a Header object
_full_text = """bool success # indicate a successful execution of the service
string message # informational, e.g. for error messages
"""
__slots__ = ['success','message']
_slot_types = ['bool','string']
def __init__(self, *args, **kwds):
"""
Constructor. Any message fields that are implicitly/explicitly
set to None will be assigned a default value. The recommend
use is keyword arguments as this is more robust to future message
changes. You cannot mix in-order arguments and keyword arguments.
The available fields are:
success,message
:param args: complete set of field values, in .msg order
:param kwds: use keyword arguments corresponding to message field names
to set specific fields.
"""
if args or kwds:
super(SetPrimAttributeResponse, self).__init__(*args, **kwds)
# message fields cannot be None, assign default values for those that are
if self.success is None:
self.success = False
if self.message is None:
self.message = ''
else:
self.success = False
self.message = ''
def _get_types(self):
"""
internal API method
"""
return self._slot_types
def serialize(self, buff):
"""
serialize message into buffer
:param buff: buffer, ``StringIO``
"""
try:
_x = self.success
buff.write(_get_struct_B().pack(_x))
_x = self.message
length = len(_x)
if python3 or type(_x) == unicode:
_x = _x.encode('utf-8')
length = len(_x)
buff.write(struct.Struct('<I%ss'%length).pack(length, _x))
except struct.error as se: self._check_types(struct.error("%s: '%s' when writing '%s'" % (type(se), str(se), str(locals().get('_x', self)))))
except TypeError as te: self._check_types(ValueError("%s: '%s' when writing '%s'" % (type(te), str(te), str(locals().get('_x', self)))))
def deserialize(self, str):
"""
unpack serialized message in str into this message instance
:param str: byte array of serialized message, ``str``
"""
if python3:
codecs.lookup_error("rosmsg").msg_type = self._type
try:
end = 0
start = end
end += 1
(self.success,) = _get_struct_B().unpack(str[start:end])
self.success = bool(self.success)
start = end
end += 4
(length,) = _struct_I.unpack(str[start:end])
start = end
end += length
if python3:
self.message = str[start:end].decode('utf-8', 'rosmsg')
else:
self.message = str[start:end]
return self
except struct.error as e:
raise genpy.DeserializationError(e) # most likely buffer underfill
def serialize_numpy(self, buff, numpy):
"""
serialize message with numpy array types into buffer
:param buff: buffer, ``StringIO``
:param numpy: numpy python module
"""
try:
_x = self.success
buff.write(_get_struct_B().pack(_x))
_x = self.message
length = len(_x)
if python3 or type(_x) == unicode:
_x = _x.encode('utf-8')
length = len(_x)
buff.write(struct.Struct('<I%ss'%length).pack(length, _x))
except struct.error as se: self._check_types(struct.error("%s: '%s' when writing '%s'" % (type(se), str(se), str(locals().get('_x', self)))))
except TypeError as te: self._check_types(ValueError("%s: '%s' when writing '%s'" % (type(te), str(te), str(locals().get('_x', self)))))
def deserialize_numpy(self, str, numpy):
"""
unpack serialized message in str into this message instance using numpy for array types
:param str: byte array of serialized message, ``str``
:param numpy: numpy python module
"""
if python3:
codecs.lookup_error("rosmsg").msg_type = self._type
try:
end = 0
start = end
end += 1
(self.success,) = _get_struct_B().unpack(str[start:end])
self.success = bool(self.success)
start = end
end += 4
(length,) = _struct_I.unpack(str[start:end])
start = end
end += length
if python3:
self.message = str[start:end].decode('utf-8', 'rosmsg')
else:
self.message = str[start:end]
return self
except struct.error as e:
raise genpy.DeserializationError(e) # most likely buffer underfill
_struct_I = genpy.struct_I
def _get_struct_I():
global _struct_I
return _struct_I
_struct_B = None
def _get_struct_B():
global _struct_B
if _struct_B is None:
_struct_B = struct.Struct("<B")
return _struct_B
class SetPrimAttribute(object):
_type = 'add_on_msgs/SetPrimAttribute'
_md5sum = 'd15a408481ab068b790f599b3a64ee47'
_request_class = SetPrimAttributeRequest
_response_class = SetPrimAttributeResponse
| 11,604 | Python | 32.157143 | 145 | 0.606429 |
Toni-SM/semu.robotics.ros_bridge/exts/semu.robotics.ros_bridge/semu/robotics/ros_bridge/packages/add_on_msgs/srv/_GetPrimAttributes.py | # This Python file uses the following encoding: utf-8
"""autogenerated by genpy from add_on_msgs/GetPrimAttributesRequest.msg. Do not edit."""
import codecs
import sys
python3 = True if sys.hexversion > 0x03000000 else False
import genpy
import struct
class GetPrimAttributesRequest(genpy.Message):
_md5sum = "1d00cd540af97efeb6b1589112fab63e"
_type = "add_on_msgs/GetPrimAttributesRequest"
_has_header = False # flag to mark the presence of a Header object
_full_text = """string path # prim path
"""
__slots__ = ['path']
_slot_types = ['string']
def __init__(self, *args, **kwds):
"""
Constructor. Any message fields that are implicitly/explicitly
set to None will be assigned a default value. The recommend
use is keyword arguments as this is more robust to future message
changes. You cannot mix in-order arguments and keyword arguments.
The available fields are:
path
:param args: complete set of field values, in .msg order
:param kwds: use keyword arguments corresponding to message field names
to set specific fields.
"""
if args or kwds:
super(GetPrimAttributesRequest, self).__init__(*args, **kwds)
# message fields cannot be None, assign default values for those that are
if self.path is None:
self.path = ''
else:
self.path = ''
def _get_types(self):
"""
internal API method
"""
return self._slot_types
def serialize(self, buff):
"""
serialize message into buffer
:param buff: buffer, ``StringIO``
"""
try:
_x = self.path
length = len(_x)
if python3 or type(_x) == unicode:
_x = _x.encode('utf-8')
length = len(_x)
buff.write(struct.Struct('<I%ss'%length).pack(length, _x))
except struct.error as se: self._check_types(struct.error("%s: '%s' when writing '%s'" % (type(se), str(se), str(locals().get('_x', self)))))
except TypeError as te: self._check_types(ValueError("%s: '%s' when writing '%s'" % (type(te), str(te), str(locals().get('_x', self)))))
def deserialize(self, str):
"""
unpack serialized message in str into this message instance
:param str: byte array of serialized message, ``str``
"""
if python3:
codecs.lookup_error("rosmsg").msg_type = self._type
try:
end = 0
start = end
end += 4
(length,) = _struct_I.unpack(str[start:end])
start = end
end += length
if python3:
self.path = str[start:end].decode('utf-8', 'rosmsg')
else:
self.path = str[start:end]
return self
except struct.error as e:
raise genpy.DeserializationError(e) # most likely buffer underfill
def serialize_numpy(self, buff, numpy):
"""
serialize message with numpy array types into buffer
:param buff: buffer, ``StringIO``
:param numpy: numpy python module
"""
try:
_x = self.path
length = len(_x)
if python3 or type(_x) == unicode:
_x = _x.encode('utf-8')
length = len(_x)
buff.write(struct.Struct('<I%ss'%length).pack(length, _x))
except struct.error as se: self._check_types(struct.error("%s: '%s' when writing '%s'" % (type(se), str(se), str(locals().get('_x', self)))))
except TypeError as te: self._check_types(ValueError("%s: '%s' when writing '%s'" % (type(te), str(te), str(locals().get('_x', self)))))
def deserialize_numpy(self, str, numpy):
"""
unpack serialized message in str into this message instance using numpy for array types
:param str: byte array of serialized message, ``str``
:param numpy: numpy python module
"""
if python3:
codecs.lookup_error("rosmsg").msg_type = self._type
try:
end = 0
start = end
end += 4
(length,) = _struct_I.unpack(str[start:end])
start = end
end += length
if python3:
self.path = str[start:end].decode('utf-8', 'rosmsg')
else:
self.path = str[start:end]
return self
except struct.error as e:
raise genpy.DeserializationError(e) # most likely buffer underfill
_struct_I = genpy.struct_I
def _get_struct_I():
global _struct_I
return _struct_I
# This Python file uses the following encoding: utf-8
"""autogenerated by genpy from add_on_msgs/GetPrimAttributesResponse.msg. Do not edit."""
import codecs
import sys
python3 = True if sys.hexversion > 0x03000000 else False
import genpy
import struct
class GetPrimAttributesResponse(genpy.Message):
_md5sum = "0c128a464ca5b41e4dd660a9d06a2cfb"
_type = "add_on_msgs/GetPrimAttributesResponse"
_has_header = False # flag to mark the presence of a Header object
_full_text = """string[] names # list of attribute base names (name used to Get or Set an attribute)
string[] displays # list of attribute display names (name displayed in Property tab)
string[] types # list of attribute data types
bool success # indicate a successful execution of the service
string message # informational, e.g. for error messages
"""
__slots__ = ['names','displays','types','success','message']
_slot_types = ['string[]','string[]','string[]','bool','string']
def __init__(self, *args, **kwds):
"""
Constructor. Any message fields that are implicitly/explicitly
set to None will be assigned a default value. The recommend
use is keyword arguments as this is more robust to future message
changes. You cannot mix in-order arguments and keyword arguments.
The available fields are:
names,displays,types,success,message
:param args: complete set of field values, in .msg order
:param kwds: use keyword arguments corresponding to message field names
to set specific fields.
"""
if args or kwds:
super(GetPrimAttributesResponse, self).__init__(*args, **kwds)
# message fields cannot be None, assign default values for those that are
if self.names is None:
self.names = []
if self.displays is None:
self.displays = []
if self.types is None:
self.types = []
if self.success is None:
self.success = False
if self.message is None:
self.message = ''
else:
self.names = []
self.displays = []
self.types = []
self.success = False
self.message = ''
def _get_types(self):
"""
internal API method
"""
return self._slot_types
def serialize(self, buff):
"""
serialize message into buffer
:param buff: buffer, ``StringIO``
"""
try:
length = len(self.names)
buff.write(_struct_I.pack(length))
for val1 in self.names:
length = len(val1)
if python3 or type(val1) == unicode:
val1 = val1.encode('utf-8')
length = len(val1)
buff.write(struct.Struct('<I%ss'%length).pack(length, val1))
length = len(self.displays)
buff.write(_struct_I.pack(length))
for val1 in self.displays:
length = len(val1)
if python3 or type(val1) == unicode:
val1 = val1.encode('utf-8')
length = len(val1)
buff.write(struct.Struct('<I%ss'%length).pack(length, val1))
length = len(self.types)
buff.write(_struct_I.pack(length))
for val1 in self.types:
length = len(val1)
if python3 or type(val1) == unicode:
val1 = val1.encode('utf-8')
length = len(val1)
buff.write(struct.Struct('<I%ss'%length).pack(length, val1))
_x = self.success
buff.write(_get_struct_B().pack(_x))
_x = self.message
length = len(_x)
if python3 or type(_x) == unicode:
_x = _x.encode('utf-8')
length = len(_x)
buff.write(struct.Struct('<I%ss'%length).pack(length, _x))
except struct.error as se: self._check_types(struct.error("%s: '%s' when writing '%s'" % (type(se), str(se), str(locals().get('_x', self)))))
except TypeError as te: self._check_types(ValueError("%s: '%s' when writing '%s'" % (type(te), str(te), str(locals().get('_x', self)))))
def deserialize(self, str):
"""
unpack serialized message in str into this message instance
:param str: byte array of serialized message, ``str``
"""
if python3:
codecs.lookup_error("rosmsg").msg_type = self._type
try:
end = 0
start = end
end += 4
(length,) = _struct_I.unpack(str[start:end])
self.names = []
for i in range(0, length):
start = end
end += 4
(length,) = _struct_I.unpack(str[start:end])
start = end
end += length
if python3:
val1 = str[start:end].decode('utf-8', 'rosmsg')
else:
val1 = str[start:end]
self.names.append(val1)
start = end
end += 4
(length,) = _struct_I.unpack(str[start:end])
self.displays = []
for i in range(0, length):
start = end
end += 4
(length,) = _struct_I.unpack(str[start:end])
start = end
end += length
if python3:
val1 = str[start:end].decode('utf-8', 'rosmsg')
else:
val1 = str[start:end]
self.displays.append(val1)
start = end
end += 4
(length,) = _struct_I.unpack(str[start:end])
self.types = []
for i in range(0, length):
start = end
end += 4
(length,) = _struct_I.unpack(str[start:end])
start = end
end += length
if python3:
val1 = str[start:end].decode('utf-8', 'rosmsg')
else:
val1 = str[start:end]
self.types.append(val1)
start = end
end += 1
(self.success,) = _get_struct_B().unpack(str[start:end])
self.success = bool(self.success)
start = end
end += 4
(length,) = _struct_I.unpack(str[start:end])
start = end
end += length
if python3:
self.message = str[start:end].decode('utf-8', 'rosmsg')
else:
self.message = str[start:end]
return self
except struct.error as e:
raise genpy.DeserializationError(e) # most likely buffer underfill
def serialize_numpy(self, buff, numpy):
"""
serialize message with numpy array types into buffer
:param buff: buffer, ``StringIO``
:param numpy: numpy python module
"""
try:
length = len(self.names)
buff.write(_struct_I.pack(length))
for val1 in self.names:
length = len(val1)
if python3 or type(val1) == unicode:
val1 = val1.encode('utf-8')
length = len(val1)
buff.write(struct.Struct('<I%ss'%length).pack(length, val1))
length = len(self.displays)
buff.write(_struct_I.pack(length))
for val1 in self.displays:
length = len(val1)
if python3 or type(val1) == unicode:
val1 = val1.encode('utf-8')
length = len(val1)
buff.write(struct.Struct('<I%ss'%length).pack(length, val1))
length = len(self.types)
buff.write(_struct_I.pack(length))
for val1 in self.types:
length = len(val1)
if python3 or type(val1) == unicode:
val1 = val1.encode('utf-8')
length = len(val1)
buff.write(struct.Struct('<I%ss'%length).pack(length, val1))
_x = self.success
buff.write(_get_struct_B().pack(_x))
_x = self.message
length = len(_x)
if python3 or type(_x) == unicode:
_x = _x.encode('utf-8')
length = len(_x)
buff.write(struct.Struct('<I%ss'%length).pack(length, _x))
except struct.error as se: self._check_types(struct.error("%s: '%s' when writing '%s'" % (type(se), str(se), str(locals().get('_x', self)))))
except TypeError as te: self._check_types(ValueError("%s: '%s' when writing '%s'" % (type(te), str(te), str(locals().get('_x', self)))))
def deserialize_numpy(self, str, numpy):
"""
unpack serialized message in str into this message instance using numpy for array types
:param str: byte array of serialized message, ``str``
:param numpy: numpy python module
"""
if python3:
codecs.lookup_error("rosmsg").msg_type = self._type
try:
end = 0
start = end
end += 4
(length,) = _struct_I.unpack(str[start:end])
self.names = []
for i in range(0, length):
start = end
end += 4
(length,) = _struct_I.unpack(str[start:end])
start = end
end += length
if python3:
val1 = str[start:end].decode('utf-8', 'rosmsg')
else:
val1 = str[start:end]
self.names.append(val1)
start = end
end += 4
(length,) = _struct_I.unpack(str[start:end])
self.displays = []
for i in range(0, length):
start = end
end += 4
(length,) = _struct_I.unpack(str[start:end])
start = end
end += length
if python3:
val1 = str[start:end].decode('utf-8', 'rosmsg')
else:
val1 = str[start:end]
self.displays.append(val1)
start = end
end += 4
(length,) = _struct_I.unpack(str[start:end])
self.types = []
for i in range(0, length):
start = end
end += 4
(length,) = _struct_I.unpack(str[start:end])
start = end
end += length
if python3:
val1 = str[start:end].decode('utf-8', 'rosmsg')
else:
val1 = str[start:end]
self.types.append(val1)
start = end
end += 1
(self.success,) = _get_struct_B().unpack(str[start:end])
self.success = bool(self.success)
start = end
end += 4
(length,) = _struct_I.unpack(str[start:end])
start = end
end += length
if python3:
self.message = str[start:end].decode('utf-8', 'rosmsg')
else:
self.message = str[start:end]
return self
except struct.error as e:
raise genpy.DeserializationError(e) # most likely buffer underfill
_struct_I = genpy.struct_I
def _get_struct_I():
global _struct_I
return _struct_I
_struct_B = None
def _get_struct_B():
global _struct_B
if _struct_B is None:
_struct_B = struct.Struct("<B")
return _struct_B
class GetPrimAttributes(object):
_type = 'add_on_msgs/GetPrimAttributes'
_md5sum = 'c58d65c0fb14e3af9f2c6842bf315d01'
_request_class = GetPrimAttributesRequest
_response_class = GetPrimAttributesResponse
| 14,453 | Python | 32.381062 | 145 | 0.592126 |
Toni-SM/semu.robotics.ros_bridge/exts/semu.robotics.ros_bridge/semu/robotics/ros_bridge/packages/add_on_msgs/srv/__init__.py | from ._GetPrimAttribute import *
from ._GetPrimAttributes import *
from ._GetPrims import *
from ._SetPrimAttribute import *
| 125 | Python | 24.199995 | 33 | 0.776 |
Toni-SM/semu.robotics.ros_bridge/exts/semu.robotics.ros_bridge/semu/robotics/ros_bridge/packages/add_on_msgs/srv/_GetPrims.py | # This Python file uses the following encoding: utf-8
"""autogenerated by genpy from add_on_msgs/GetPrimsRequest.msg. Do not edit."""
import codecs
import sys
python3 = True if sys.hexversion > 0x03000000 else False
import genpy
import struct
class GetPrimsRequest(genpy.Message):
_md5sum = "1d00cd540af97efeb6b1589112fab63e"
_type = "add_on_msgs/GetPrimsRequest"
_has_header = False # flag to mark the presence of a Header object
_full_text = """string path # get prims at path
"""
__slots__ = ['path']
_slot_types = ['string']
def __init__(self, *args, **kwds):
"""
Constructor. Any message fields that are implicitly/explicitly
set to None will be assigned a default value. The recommend
use is keyword arguments as this is more robust to future message
changes. You cannot mix in-order arguments and keyword arguments.
The available fields are:
path
:param args: complete set of field values, in .msg order
:param kwds: use keyword arguments corresponding to message field names
to set specific fields.
"""
if args or kwds:
super(GetPrimsRequest, self).__init__(*args, **kwds)
# message fields cannot be None, assign default values for those that are
if self.path is None:
self.path = ''
else:
self.path = ''
def _get_types(self):
"""
internal API method
"""
return self._slot_types
def serialize(self, buff):
"""
serialize message into buffer
:param buff: buffer, ``StringIO``
"""
try:
_x = self.path
length = len(_x)
if python3 or type(_x) == unicode:
_x = _x.encode('utf-8')
length = len(_x)
buff.write(struct.Struct('<I%ss'%length).pack(length, _x))
except struct.error as se: self._check_types(struct.error("%s: '%s' when writing '%s'" % (type(se), str(se), str(locals().get('_x', self)))))
except TypeError as te: self._check_types(ValueError("%s: '%s' when writing '%s'" % (type(te), str(te), str(locals().get('_x', self)))))
def deserialize(self, str):
"""
unpack serialized message in str into this message instance
:param str: byte array of serialized message, ``str``
"""
if python3:
codecs.lookup_error("rosmsg").msg_type = self._type
try:
end = 0
start = end
end += 4
(length,) = _struct_I.unpack(str[start:end])
start = end
end += length
if python3:
self.path = str[start:end].decode('utf-8', 'rosmsg')
else:
self.path = str[start:end]
return self
except struct.error as e:
raise genpy.DeserializationError(e) # most likely buffer underfill
def serialize_numpy(self, buff, numpy):
"""
serialize message with numpy array types into buffer
:param buff: buffer, ``StringIO``
:param numpy: numpy python module
"""
try:
_x = self.path
length = len(_x)
if python3 or type(_x) == unicode:
_x = _x.encode('utf-8')
length = len(_x)
buff.write(struct.Struct('<I%ss'%length).pack(length, _x))
except struct.error as se: self._check_types(struct.error("%s: '%s' when writing '%s'" % (type(se), str(se), str(locals().get('_x', self)))))
except TypeError as te: self._check_types(ValueError("%s: '%s' when writing '%s'" % (type(te), str(te), str(locals().get('_x', self)))))
def deserialize_numpy(self, str, numpy):
"""
unpack serialized message in str into this message instance using numpy for array types
:param str: byte array of serialized message, ``str``
:param numpy: numpy python module
"""
if python3:
codecs.lookup_error("rosmsg").msg_type = self._type
try:
end = 0
start = end
end += 4
(length,) = _struct_I.unpack(str[start:end])
start = end
end += length
if python3:
self.path = str[start:end].decode('utf-8', 'rosmsg')
else:
self.path = str[start:end]
return self
except struct.error as e:
raise genpy.DeserializationError(e) # most likely buffer underfill
_struct_I = genpy.struct_I
def _get_struct_I():
global _struct_I
return _struct_I
# This Python file uses the following encoding: utf-8
"""autogenerated by genpy from add_on_msgs/GetPrimsResponse.msg. Do not edit."""
import codecs
import sys
python3 = True if sys.hexversion > 0x03000000 else False
import genpy
import struct
class GetPrimsResponse(genpy.Message):
_md5sum = "f072514d01cc913f074f0eaf8eb9d8b1"
_type = "add_on_msgs/GetPrimsResponse"
_has_header = False # flag to mark the presence of a Header object
_full_text = """string[] paths # list of prim paths
string[] types # prim type names
bool success # indicate a successful execution of the service
string message # informational, e.g. for error messages
"""
__slots__ = ['paths','types','success','message']
_slot_types = ['string[]','string[]','bool','string']
def __init__(self, *args, **kwds):
"""
Constructor. Any message fields that are implicitly/explicitly
set to None will be assigned a default value. The recommend
use is keyword arguments as this is more robust to future message
changes. You cannot mix in-order arguments and keyword arguments.
The available fields are:
paths,types,success,message
:param args: complete set of field values, in .msg order
:param kwds: use keyword arguments corresponding to message field names
to set specific fields.
"""
if args or kwds:
super(GetPrimsResponse, self).__init__(*args, **kwds)
# message fields cannot be None, assign default values for those that are
if self.paths is None:
self.paths = []
if self.types is None:
self.types = []
if self.success is None:
self.success = False
if self.message is None:
self.message = ''
else:
self.paths = []
self.types = []
self.success = False
self.message = ''
def _get_types(self):
"""
internal API method
"""
return self._slot_types
def serialize(self, buff):
"""
serialize message into buffer
:param buff: buffer, ``StringIO``
"""
try:
length = len(self.paths)
buff.write(_struct_I.pack(length))
for val1 in self.paths:
length = len(val1)
if python3 or type(val1) == unicode:
val1 = val1.encode('utf-8')
length = len(val1)
buff.write(struct.Struct('<I%ss'%length).pack(length, val1))
length = len(self.types)
buff.write(_struct_I.pack(length))
for val1 in self.types:
length = len(val1)
if python3 or type(val1) == unicode:
val1 = val1.encode('utf-8')
length = len(val1)
buff.write(struct.Struct('<I%ss'%length).pack(length, val1))
_x = self.success
buff.write(_get_struct_B().pack(_x))
_x = self.message
length = len(_x)
if python3 or type(_x) == unicode:
_x = _x.encode('utf-8')
length = len(_x)
buff.write(struct.Struct('<I%ss'%length).pack(length, _x))
except struct.error as se: self._check_types(struct.error("%s: '%s' when writing '%s'" % (type(se), str(se), str(locals().get('_x', self)))))
except TypeError as te: self._check_types(ValueError("%s: '%s' when writing '%s'" % (type(te), str(te), str(locals().get('_x', self)))))
def deserialize(self, str):
"""
unpack serialized message in str into this message instance
:param str: byte array of serialized message, ``str``
"""
if python3:
codecs.lookup_error("rosmsg").msg_type = self._type
try:
end = 0
start = end
end += 4
(length,) = _struct_I.unpack(str[start:end])
self.paths = []
for i in range(0, length):
start = end
end += 4
(length,) = _struct_I.unpack(str[start:end])
start = end
end += length
if python3:
val1 = str[start:end].decode('utf-8', 'rosmsg')
else:
val1 = str[start:end]
self.paths.append(val1)
start = end
end += 4
(length,) = _struct_I.unpack(str[start:end])
self.types = []
for i in range(0, length):
start = end
end += 4
(length,) = _struct_I.unpack(str[start:end])
start = end
end += length
if python3:
val1 = str[start:end].decode('utf-8', 'rosmsg')
else:
val1 = str[start:end]
self.types.append(val1)
start = end
end += 1
(self.success,) = _get_struct_B().unpack(str[start:end])
self.success = bool(self.success)
start = end
end += 4
(length,) = _struct_I.unpack(str[start:end])
start = end
end += length
if python3:
self.message = str[start:end].decode('utf-8', 'rosmsg')
else:
self.message = str[start:end]
return self
except struct.error as e:
raise genpy.DeserializationError(e) # most likely buffer underfill
def serialize_numpy(self, buff, numpy):
"""
serialize message with numpy array types into buffer
:param buff: buffer, ``StringIO``
:param numpy: numpy python module
"""
try:
length = len(self.paths)
buff.write(_struct_I.pack(length))
for val1 in self.paths:
length = len(val1)
if python3 or type(val1) == unicode:
val1 = val1.encode('utf-8')
length = len(val1)
buff.write(struct.Struct('<I%ss'%length).pack(length, val1))
length = len(self.types)
buff.write(_struct_I.pack(length))
for val1 in self.types:
length = len(val1)
if python3 or type(val1) == unicode:
val1 = val1.encode('utf-8')
length = len(val1)
buff.write(struct.Struct('<I%ss'%length).pack(length, val1))
_x = self.success
buff.write(_get_struct_B().pack(_x))
_x = self.message
length = len(_x)
if python3 or type(_x) == unicode:
_x = _x.encode('utf-8')
length = len(_x)
buff.write(struct.Struct('<I%ss'%length).pack(length, _x))
except struct.error as se: self._check_types(struct.error("%s: '%s' when writing '%s'" % (type(se), str(se), str(locals().get('_x', self)))))
except TypeError as te: self._check_types(ValueError("%s: '%s' when writing '%s'" % (type(te), str(te), str(locals().get('_x', self)))))
def deserialize_numpy(self, str, numpy):
"""
unpack serialized message in str into this message instance using numpy for array types
:param str: byte array of serialized message, ``str``
:param numpy: numpy python module
"""
if python3:
codecs.lookup_error("rosmsg").msg_type = self._type
try:
end = 0
start = end
end += 4
(length,) = _struct_I.unpack(str[start:end])
self.paths = []
for i in range(0, length):
start = end
end += 4
(length,) = _struct_I.unpack(str[start:end])
start = end
end += length
if python3:
val1 = str[start:end].decode('utf-8', 'rosmsg')
else:
val1 = str[start:end]
self.paths.append(val1)
start = end
end += 4
(length,) = _struct_I.unpack(str[start:end])
self.types = []
for i in range(0, length):
start = end
end += 4
(length,) = _struct_I.unpack(str[start:end])
start = end
end += length
if python3:
val1 = str[start:end].decode('utf-8', 'rosmsg')
else:
val1 = str[start:end]
self.types.append(val1)
start = end
end += 1
(self.success,) = _get_struct_B().unpack(str[start:end])
self.success = bool(self.success)
start = end
end += 4
(length,) = _struct_I.unpack(str[start:end])
start = end
end += length
if python3:
self.message = str[start:end].decode('utf-8', 'rosmsg')
else:
self.message = str[start:end]
return self
except struct.error as e:
raise genpy.DeserializationError(e) # most likely buffer underfill
_struct_I = genpy.struct_I
def _get_struct_I():
global _struct_I
return _struct_I
_struct_B = None
def _get_struct_B():
global _struct_B
if _struct_B is None:
_struct_B = struct.Struct("<B")
return _struct_B
class GetPrims(object):
_type = 'add_on_msgs/GetPrims'
_md5sum = '0e294bdd37240dbb5e18c218e5029ba0'
_request_class = GetPrimsRequest
_response_class = GetPrimsResponse
| 12,587 | Python | 31.866841 | 145 | 0.594741 |
Toni-SM/semu.robotics.ros_bridge/exts/semu.robotics.ros_bridge/semu/robotics/ros_bridge/packages/add_on_msgs/srv/_GetPrimAttribute.py | # This Python file uses the following encoding: utf-8
"""autogenerated by genpy from add_on_msgs/GetPrimAttributeRequest.msg. Do not edit."""
import codecs
import sys
python3 = True if sys.hexversion > 0x03000000 else False
import genpy
import struct
class GetPrimAttributeRequest(genpy.Message):
_md5sum = "c9201df12943eb9aa031dc2dfa5b1f49"
_type = "add_on_msgs/GetPrimAttributeRequest"
_has_header = False # flag to mark the presence of a Header object
_full_text = """string path # prim path
string attribute # attribute name
"""
__slots__ = ['path','attribute']
_slot_types = ['string','string']
def __init__(self, *args, **kwds):
"""
Constructor. Any message fields that are implicitly/explicitly
set to None will be assigned a default value. The recommend
use is keyword arguments as this is more robust to future message
changes. You cannot mix in-order arguments and keyword arguments.
The available fields are:
path,attribute
:param args: complete set of field values, in .msg order
:param kwds: use keyword arguments corresponding to message field names
to set specific fields.
"""
if args or kwds:
super(GetPrimAttributeRequest, self).__init__(*args, **kwds)
# message fields cannot be None, assign default values for those that are
if self.path is None:
self.path = ''
if self.attribute is None:
self.attribute = ''
else:
self.path = ''
self.attribute = ''
def _get_types(self):
"""
internal API method
"""
return self._slot_types
def serialize(self, buff):
"""
serialize message into buffer
:param buff: buffer, ``StringIO``
"""
try:
_x = self.path
length = len(_x)
if python3 or type(_x) == unicode:
_x = _x.encode('utf-8')
length = len(_x)
buff.write(struct.Struct('<I%ss'%length).pack(length, _x))
_x = self.attribute
length = len(_x)
if python3 or type(_x) == unicode:
_x = _x.encode('utf-8')
length = len(_x)
buff.write(struct.Struct('<I%ss'%length).pack(length, _x))
except struct.error as se: self._check_types(struct.error("%s: '%s' when writing '%s'" % (type(se), str(se), str(locals().get('_x', self)))))
except TypeError as te: self._check_types(ValueError("%s: '%s' when writing '%s'" % (type(te), str(te), str(locals().get('_x', self)))))
def deserialize(self, str):
"""
unpack serialized message in str into this message instance
:param str: byte array of serialized message, ``str``
"""
if python3:
codecs.lookup_error("rosmsg").msg_type = self._type
try:
end = 0
start = end
end += 4
(length,) = _struct_I.unpack(str[start:end])
start = end
end += length
if python3:
self.path = str[start:end].decode('utf-8', 'rosmsg')
else:
self.path = str[start:end]
start = end
end += 4
(length,) = _struct_I.unpack(str[start:end])
start = end
end += length
if python3:
self.attribute = str[start:end].decode('utf-8', 'rosmsg')
else:
self.attribute = str[start:end]
return self
except struct.error as e:
raise genpy.DeserializationError(e) # most likely buffer underfill
def serialize_numpy(self, buff, numpy):
"""
serialize message with numpy array types into buffer
:param buff: buffer, ``StringIO``
:param numpy: numpy python module
"""
try:
_x = self.path
length = len(_x)
if python3 or type(_x) == unicode:
_x = _x.encode('utf-8')
length = len(_x)
buff.write(struct.Struct('<I%ss'%length).pack(length, _x))
_x = self.attribute
length = len(_x)
if python3 or type(_x) == unicode:
_x = _x.encode('utf-8')
length = len(_x)
buff.write(struct.Struct('<I%ss'%length).pack(length, _x))
except struct.error as se: self._check_types(struct.error("%s: '%s' when writing '%s'" % (type(se), str(se), str(locals().get('_x', self)))))
except TypeError as te: self._check_types(ValueError("%s: '%s' when writing '%s'" % (type(te), str(te), str(locals().get('_x', self)))))
def deserialize_numpy(self, str, numpy):
"""
unpack serialized message in str into this message instance using numpy for array types
:param str: byte array of serialized message, ``str``
:param numpy: numpy python module
"""
if python3:
codecs.lookup_error("rosmsg").msg_type = self._type
try:
end = 0
start = end
end += 4
(length,) = _struct_I.unpack(str[start:end])
start = end
end += length
if python3:
self.path = str[start:end].decode('utf-8', 'rosmsg')
else:
self.path = str[start:end]
start = end
end += 4
(length,) = _struct_I.unpack(str[start:end])
start = end
end += length
if python3:
self.attribute = str[start:end].decode('utf-8', 'rosmsg')
else:
self.attribute = str[start:end]
return self
except struct.error as e:
raise genpy.DeserializationError(e) # most likely buffer underfill
_struct_I = genpy.struct_I
def _get_struct_I():
global _struct_I
return _struct_I
# This Python file uses the following encoding: utf-8
"""autogenerated by genpy from add_on_msgs/GetPrimAttributeResponse.msg. Do not edit."""
import codecs
import sys
python3 = True if sys.hexversion > 0x03000000 else False
import genpy
import struct
class GetPrimAttributeResponse(genpy.Message):
_md5sum = "098d36ccd3206edc9561c3e2d9eb07f9"
_type = "add_on_msgs/GetPrimAttributeResponse"
_has_header = False # flag to mark the presence of a Header object
_full_text = """string value # attribute value (as JSON)
string type # attribute type
bool success # indicate a successful execution of the service
string message # informational, e.g. for error messages
"""
__slots__ = ['value','type','success','message']
_slot_types = ['string','string','bool','string']
def __init__(self, *args, **kwds):
"""
Constructor. Any message fields that are implicitly/explicitly
set to None will be assigned a default value. The recommend
use is keyword arguments as this is more robust to future message
changes. You cannot mix in-order arguments and keyword arguments.
The available fields are:
value,type,success,message
:param args: complete set of field values, in .msg order
:param kwds: use keyword arguments corresponding to message field names
to set specific fields.
"""
if args or kwds:
super(GetPrimAttributeResponse, self).__init__(*args, **kwds)
# message fields cannot be None, assign default values for those that are
if self.value is None:
self.value = ''
if self.type is None:
self.type = ''
if self.success is None:
self.success = False
if self.message is None:
self.message = ''
else:
self.value = ''
self.type = ''
self.success = False
self.message = ''
def _get_types(self):
"""
internal API method
"""
return self._slot_types
def serialize(self, buff):
"""
serialize message into buffer
:param buff: buffer, ``StringIO``
"""
try:
_x = self.value
length = len(_x)
if python3 or type(_x) == unicode:
_x = _x.encode('utf-8')
length = len(_x)
buff.write(struct.Struct('<I%ss'%length).pack(length, _x))
_x = self.type
length = len(_x)
if python3 or type(_x) == unicode:
_x = _x.encode('utf-8')
length = len(_x)
buff.write(struct.Struct('<I%ss'%length).pack(length, _x))
_x = self.success
buff.write(_get_struct_B().pack(_x))
_x = self.message
length = len(_x)
if python3 or type(_x) == unicode:
_x = _x.encode('utf-8')
length = len(_x)
buff.write(struct.Struct('<I%ss'%length).pack(length, _x))
except struct.error as se: self._check_types(struct.error("%s: '%s' when writing '%s'" % (type(se), str(se), str(locals().get('_x', self)))))
except TypeError as te: self._check_types(ValueError("%s: '%s' when writing '%s'" % (type(te), str(te), str(locals().get('_x', self)))))
def deserialize(self, str):
"""
unpack serialized message in str into this message instance
:param str: byte array of serialized message, ``str``
"""
if python3:
codecs.lookup_error("rosmsg").msg_type = self._type
try:
end = 0
start = end
end += 4
(length,) = _struct_I.unpack(str[start:end])
start = end
end += length
if python3:
self.value = str[start:end].decode('utf-8', 'rosmsg')
else:
self.value = str[start:end]
start = end
end += 4
(length,) = _struct_I.unpack(str[start:end])
start = end
end += length
if python3:
self.type = str[start:end].decode('utf-8', 'rosmsg')
else:
self.type = str[start:end]
start = end
end += 1
(self.success,) = _get_struct_B().unpack(str[start:end])
self.success = bool(self.success)
start = end
end += 4
(length,) = _struct_I.unpack(str[start:end])
start = end
end += length
if python3:
self.message = str[start:end].decode('utf-8', 'rosmsg')
else:
self.message = str[start:end]
return self
except struct.error as e:
raise genpy.DeserializationError(e) # most likely buffer underfill
def serialize_numpy(self, buff, numpy):
"""
serialize message with numpy array types into buffer
:param buff: buffer, ``StringIO``
:param numpy: numpy python module
"""
try:
_x = self.value
length = len(_x)
if python3 or type(_x) == unicode:
_x = _x.encode('utf-8')
length = len(_x)
buff.write(struct.Struct('<I%ss'%length).pack(length, _x))
_x = self.type
length = len(_x)
if python3 or type(_x) == unicode:
_x = _x.encode('utf-8')
length = len(_x)
buff.write(struct.Struct('<I%ss'%length).pack(length, _x))
_x = self.success
buff.write(_get_struct_B().pack(_x))
_x = self.message
length = len(_x)
if python3 or type(_x) == unicode:
_x = _x.encode('utf-8')
length = len(_x)
buff.write(struct.Struct('<I%ss'%length).pack(length, _x))
except struct.error as se: self._check_types(struct.error("%s: '%s' when writing '%s'" % (type(se), str(se), str(locals().get('_x', self)))))
except TypeError as te: self._check_types(ValueError("%s: '%s' when writing '%s'" % (type(te), str(te), str(locals().get('_x', self)))))
def deserialize_numpy(self, str, numpy):
"""
unpack serialized message in str into this message instance using numpy for array types
:param str: byte array of serialized message, ``str``
:param numpy: numpy python module
"""
if python3:
codecs.lookup_error("rosmsg").msg_type = self._type
try:
end = 0
start = end
end += 4
(length,) = _struct_I.unpack(str[start:end])
start = end
end += length
if python3:
self.value = str[start:end].decode('utf-8', 'rosmsg')
else:
self.value = str[start:end]
start = end
end += 4
(length,) = _struct_I.unpack(str[start:end])
start = end
end += length
if python3:
self.type = str[start:end].decode('utf-8', 'rosmsg')
else:
self.type = str[start:end]
start = end
end += 1
(self.success,) = _get_struct_B().unpack(str[start:end])
self.success = bool(self.success)
start = end
end += 4
(length,) = _struct_I.unpack(str[start:end])
start = end
end += length
if python3:
self.message = str[start:end].decode('utf-8', 'rosmsg')
else:
self.message = str[start:end]
return self
except struct.error as e:
raise genpy.DeserializationError(e) # most likely buffer underfill
_struct_I = genpy.struct_I
def _get_struct_I():
global _struct_I
return _struct_I
_struct_B = None
def _get_struct_B():
global _struct_B
if _struct_B is None:
_struct_B = struct.Struct("<B")
return _struct_B
class GetPrimAttribute(object):
_type = 'add_on_msgs/GetPrimAttribute'
_md5sum = '703eb9b34a0933a564035819a2278c14'
_request_class = GetPrimAttributeRequest
_response_class = GetPrimAttributeResponse
| 12,649 | Python | 31.857143 | 145 | 0.598308 |
Toni-SM/semu.robotics.ros_bridge/exts/semu.robotics.ros_bridge/semu/robotics/ros_bridge/tests/__init__.py | from .test_ros_bridge import *
| 31 | Python | 14.999993 | 30 | 0.741935 |
Toni-SM/semu.robotics.ros_bridge/exts/semu.robotics.ros_bridge/semu/robotics/ros_bridge/tests/test_ros_bridge.py | # NOTE:
# omni.kit.test - std python's unittest module with additional wrapping to add suport for async/await tests
# For most things refer to unittest docs: https://docs.python.org/3/library/unittest.html
import omni.kit.test
# Import extension python module we are testing with absolute import path, as if we are external user (other extension)
import semu.robotics.ros_bridge
# Having a test class dervived from omni.kit.test.AsyncTestCase declared on the root of module will make it auto-discoverable by omni.kit.test
class TestROSBridge(omni.kit.test.AsyncTestCaseFailOnLogError):
# Before running each test
async def setUp(self):
pass
# After running each test
async def tearDown(self):
pass
# Actual test, notice it is "async" function, so "await" can be used if needed
async def test_ros_bridge(self):
print("test_ros_bridge - TODO")
pass
| 919 | Python | 38.999998 | 142 | 0.724701 |
Toni-SM/semu.robotics.ros_bridge/exts/semu.robotics.ros_bridge/config/extension.toml | [core]
reloadable = true
order = 0
[package]
version = "1.0.0"
category = "Simulation"
feature = false
app = false
title = "ROS Bridge (semu namespace)"
description = "ROS interfaces (semu namespace)"
authors = ["Toni-SM"]
repository = "https://github.com/Toni-SM/semu.robotics.ros_bridge"
keywords = ["ROS", "control"]
changelog = "docs/CHANGELOG.md"
readme = "docs/README.md"
preview_image = "data/preview.png"
icon = "data/icon.png"
[package.target]
config = ["release"]
platform = ["linux-*"]
python = ["*"]
[dependencies]
"omni.kit.uiapp" = {}
"omni.kit.test" = {}
"omni.graph" = {}
"omni.isaac.dynamic_control" = {}
[[python.module]]
name = "semu.robotics.ros_bridge"
[[python.module]]
name = "semu.robotics.ros_bridge.tests"
[fswatcher.patterns]
include = ["*.ogn", "*.py"]
exclude = ["Ogn*Database.py"]
[settings]
exts."semu.robotics.ros_bridge".nodeName = "SemuRosBridge"
exts."semu.robotics.ros_bridge".eventTimeout = 5.0
exts."semu.robotics.ros_bridge".setAttributeUsingAsyncio = false
| 1,004 | TOML | 21.333333 | 66 | 0.692231 |
Toni-SM/semu.robotics.ros_bridge/exts/semu.robotics.ros_bridge/docs/CHANGELOG.md | # Changelog
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).
## [1.0.0] - 2022-06-15
### Changed
- Switch to OmniGraph
## [0.1.1] - 2022-05-28
### Changed
- Rename the extension to `semu.robotics.ros_bridge`
## [0.1.0] - 2022-04-14
### Added
- Source code (src folder)
- `control_msgs/FollowJointTrajectory` action server
- `control_msgs/GripperCommand` action server
### Changed
- Improve the extension implementation
### Removed
- `sensor_msgs/CompressedImage` topic
## [0.0.2] - 2021-10-29
### Added
- `add_on_msgs/RosAttribute` services
## [0.0.1] - 2021-06-22
### Added
- Update extension to Isaac Sim 2021.1.0 extension format
| 673 | Markdown | 20.062499 | 80 | 0.686478 |
Toni-SM/semu.robotics.ros_bridge/exts/semu.robotics.ros_bridge/docs/README.md | # semu.robotics.ros_bridge
This extension enables the ROS action server interfaces for controlling robots (particularly those used by MoveIt to talk to robot controllers: FollowJointTrajectory and GripperCommand) and enables services for agile prototyping of robotic applications in ROS
Visit https://github.com/Toni-SM/semu.robotics.ros_bridge to read more about its use
| 375 | Markdown | 52.714278 | 259 | 0.826667 |
Toni-SM/semu.robotics.ros2_bridge/README.md | ## ROS2 Bridge (external extension) for NVIDIA Omniverse Isaac Sim
> This extension enables the ROS2 action server interfaces for controlling robots (particularly those used by MoveIt to talk to robot controllers: [FollowJointTrajectory](http://docs.ros.org/en/api/control_msgs/html/action/FollowJointTrajectory.html) and [GripperCommand](http://docs.ros.org/en/api/control_msgs/html/action/GripperCommand.html)) and enables services for agile prototyping of robotic applications in [ROS2](https://docs.ros.org/)
<br>
**Target applications:** NVIDIA Omniverse Isaac Sim
**Supported OS:** Linux
**Changelog:** [CHANGELOG.md](src/semu.robotics.ros2_bridge/docs/CHANGELOG.md)
**Table of Contents:**
- [Prerequisites](#prerequisites)
- [Extension setup](#setup)
- [Extension usage](#usage)
- [Supported components](#components)
- [Attribute](#ros-attribute)
- [FollowJointTrajectory](#ros-follow-joint-trajectory)
- [GripperCommand](#ros-gripper-command)
<br>
<hr>
<a name="prerequisites"></a>
### Prerequisites
All prerequisites described in [ROS & ROS2 Bridge](https://docs.omniverse.nvidia.com/app_isaacsim/app_isaacsim/ext_omni_isaac_ros_bridge.html) must be fulfilled before running this extension. In addition, this extension requires the following extensions to be present in Isaac Sim:
- [semu.usd.schemas](https://github.com/Toni-SM/semu.usd.schemas): USD schemas
- [semu.robotics.ros_bridge_ui](https://github.com/Toni-SM/semu.robotics.ros_bridge_ui): Menu and commands
<hr>
<a name="setup"></a>
### Extension setup
1. Add the extension using the [Extension Manager](https://docs.omniverse.nvidia.com/prod_extensions/prod_extensions/ext_extension-manager.html) or by following the steps in [Extension Search Paths](https://docs.omniverse.nvidia.com/py/kit/docs/guide/extensions.html#extension-search-paths)
* Git url (git+https) as extension search path
```
git+https://github.com/Toni-SM/semu.robotics.ros2_bridge.git?branch=main&dir=exts
```
To install the source code version use the following url
```
git+https://github.com/Toni-SM/semu.robotics.ros2_bridge.git?branch=main&dir=src
```
* Compressed (.zip) file for import
[semu.robotics.ros2_bridge.zip](https://github.com/Toni-SM/semu.robotics.ros2_bridge/releases)
2. Enable the extension using the [Extension Manager](https://docs.omniverse.nvidia.com/prod_extensions/prod_extensions/ext_extension-manager.html) or by following the steps in [Extension Enabling/Disabling](https://docs.omniverse.nvidia.com/py/kit/docs/guide/extensions.html#extension-enabling-disabling)
<hr>
<a name="usage"></a>
### Extension usage
Enabling the extension initializes a ROS node named `/SemuRos2Bridge` (configurable in the `extension.toml` file). This node will enable, when the simulation starts, the ROS topics, services and actions protocols according to the ROS prims (and their configurations) existing in the current stage
Disabling the extension shutdowns the ROS node and its respective active communication protocols
> **Note:** The current implementation only implements position control (velocity or effort control is not yet supported) for the FollowJointTrajectory and GripperCommand actions
<hr>
<a name="components"></a>
### Supported components
The following components are supported:
<a name="ros-attribute"></a>
* **Attribute (ROS2 service):** enables the ervices for getting and setting the attributes of a prim according to the service definitions described bellow
The ROS2 package [add_on_msgs](https://github.com/Toni-SM/semu.robotics.ros2_bridge/releases) contains the definition of the messages (download and add it to a ROS2 workspace). A sample code of a [python client application](https://github.com/Toni-SM/semu.robotics.ros2_bridge/releases) is also provided
Prim attributes are retrieved and modified as JSON (applied directly to the data, without keys). Arrays, vectors, matrixes and other numeric classes (```pxr.Gf.Vec3f```, ```pxr.Gf.Matrix4d```, ```pxr.Gf.Quatf```, ```pxr.Vt.Vec2fArray```, etc.) are interpreted as a list of numbers (row first)
* **add_on_msgs.srv.GetPrims**: Get all prim path under the specified path
```yaml
string path # get prims at path
---
string[] paths # list of prim paths
string[] types # prim type names
bool success # indicate a successful execution of the service
string message # informational, e.g. for error messages
```
* **add_on_msgs.srv.GetPrimAttributes**: Get prim attribute names and their types
```yaml
string path # prim path
---
string[] names # list of attribute base names (name used to Get or Set an attribute)
string[] displays # list of attribute display names (name displayed in Property tab)
string[] types # list of attribute data types
bool success # indicate a successful execution of the service
string message # informational, e.g. for error messages
```
* **add_on_msgs.srv.GetPrimAttribute**: Get prim attribute
```yaml
string path # prim path
string attribute # attribute name
---
string value # attribute value (as JSON)
string type # attribute type
bool success # indicate a successful execution of the service
string message # informational, e.g. for error messages
```
* **add_on_msgs.srv.SetPrimAttribute**: Set prim attribute
```yaml
string path # prim path
string attribute # attribute name
string value # attribute value (as JSON)
---
bool success # indicate a successful execution of the service
string message # informational, e.g. for error messages
```
<a name="ros-follow-joint-trajectory"></a>
* **FollowJointTrajectory (ROS2 action):** enables the actions for a robot to follow a given trajectory
To add a FollowJointTrajectory action go to the ***Create > Isaac > ROS Control*** menu and select ***Follow Joint Trajectory***
Select, by clicking the **Add Target(s)** button under the `articulationPrim` field, the root of the robot's articulation tree to control and edit the fields that define the namespace of the communication. The communication will take place in the namespace defined by the following fields:
```
controllerName + actionNamespace
```
<a name="ros-gripper-command"></a>
* **GripperCommand (ROS2 action):** enables the actions to control a gripper
To add a GripperCommand action go to the ***Create > Isaac > ROS Control*** menu and select ***Gripper Command***
Select, by clicking the **Add Target(s)** button under the `articulationPrim` field, the root of the robot's articulation tree to which the end-effector belongs and then add the joints (of the gripper) to control
Also, edit the fields that define the namespace of the communication. The communication will take place in the namespace defined by the following fields:
```
controllerName + actionNamespace
```
> **Note:** The GripperCommand action definition doesn't specify which joints will be controlled. The value manage by this action will affect all the specified joints equally | 7,567 | Markdown | 48.142857 | 445 | 0.695388 |
Toni-SM/semu.robotics.ros2_bridge/src/semu.robotics.ros2_bridge/BUILD.md | ## Building form source
### Linux
```bash
cd src/semu.robotics.ros2_bridge
bash compile_extension.bash
```
## Removing old compiled files
Get a fresh clone of the repository and follow the next steps
```bash
# remove compiled files _ros2_bridge.cpython-37m-x86_64-linux-gnu.so
git filter-repo --invert-paths --path exts/semu.robotics.ros2_bridge/semu/robotics/ros2_bridge/_ros2_bridge.cpython-37m-x86_64-linux-gnu.so
# add origin
git remote add origin [email protected]:Toni-SM/semu.robotics.ros2_bridge.git
# push changes
git push origin --force --all
git push origin --force --tags
```
## Packaging the extension
```bash
cd src/semu.robotics.ros2_bridge
bash package_extension.bash
``` | 694 | Markdown | 21.419354 | 139 | 0.75072 |
Toni-SM/semu.robotics.ros2_bridge/src/semu.robotics.ros2_bridge/compile_extension.py | import os
import sys
from distutils.core import setup
from distutils.extension import Extension
from Cython.Distutils import build_ext
# OV python (kit\python\include)
if sys.platform == 'win32':
raise Exception('Windows is not supported')
exit(1)
elif sys.platform == 'linux':
python_library_dir = os.path.join(os.path.dirname(sys.executable), "..", "include")
if not os.path.exists(python_library_dir):
raise Exception("OV Python library directory not found: {}".format(python_library_dir))
ext_modules = [
Extension("_ros2_bridge",
[os.path.join("semu", "robotics", "ros2_bridge", "ros2_bridge.py")],
library_dirs=[python_library_dir]),
]
setup(
name = 'semu.robotics.ros2_bridge',
cmdclass = {'build_ext': build_ext},
ext_modules = ext_modules
)
| 815 | Python | 27.13793 | 91 | 0.677301 |
Toni-SM/semu.robotics.ros2_bridge/src/semu.robotics.ros2_bridge/semu/robotics/ros2_bridge/ros2_bridge.py | from typing import List, Any
import time
import json
import asyncio
import threading
import omni
import carb
import omni.kit
from pxr import Usd, Gf, PhysxSchema
from omni.isaac.dynamic_control import _dynamic_control
from omni.isaac.core.utils.stage import get_stage_units
import rclpy
from rclpy.node import Node
from rclpy.duration import Duration
from rclpy.action import ActionServer, CancelResponse, GoalResponse
from trajectory_msgs.msg import JointTrajectoryPoint
import semu.usd.schemas.RosBridgeSchema as ROSSchema
import semu.usd.schemas.RosControlBridgeSchema as ROSControlSchema
# message types
GetPrims = None
GetPrimAttributes = None
GetPrimAttribute = None
SetPrimAttribute = None
FollowJointTrajectory = None
GripperCommand = None
def acquire_ros2_bridge_interface(ext_id: str = "") -> 'Ros2Bridge':
"""
Acquire the Ros2Bridge interface
:param ext_id: The extension id
:type ext_id: str
:returns: The Ros2Bridge interface
:rtype: Ros2Bridge
"""
global GetPrims, GetPrimAttributes, GetPrimAttribute, SetPrimAttribute, FollowJointTrajectory, GripperCommand
from add_on_msgs.srv import GetPrims as get_prims_srv
from add_on_msgs.srv import GetPrimAttributes as get_prim_attributes_srv
from add_on_msgs.srv import GetPrimAttribute as get_prim_attribute_srv
from add_on_msgs.srv import SetPrimAttribute as set_prim_attribute_srv
from control_msgs.action import FollowJointTrajectory as follow_joint_trajectory_action
from control_msgs.action import GripperCommand as gripper_command_action
GetPrims = get_prims_srv
GetPrimAttributes = get_prim_attributes_srv
GetPrimAttribute = get_prim_attribute_srv
SetPrimAttribute = set_prim_attribute_srv
FollowJointTrajectory = follow_joint_trajectory_action
GripperCommand = gripper_command_action
rclpy.init()
bridge = Ros2Bridge()
executor = rclpy.executors.MultiThreadedExecutor()
executor.add_node(bridge)
threading.Thread(target=executor.spin).start()
return bridge
def release_ros2_bridge_interface(bridge: 'Ros2Bridge') -> None:
"""
Release the Ros2Bridge interface
:param bridge: The Ros2Bridge interface
:type bridge: Ros2Bridge
"""
bridge.shutdown()
class Ros2Bridge(Node):
def __init__(self) -> None:
"""Initialize the Ros2Bridge interface
"""
self._components = []
self._node_name = carb.settings.get_settings().get("/exts/semu.robotics.ros2_bridge/nodeName")
super().__init__(self._node_name)
# omni objects and interfaces
self._usd_context = omni.usd.get_context()
self._timeline = omni.timeline.get_timeline_interface()
self._physx_interface = omni.physx.acquire_physx_interface()
self._dci = _dynamic_control.acquire_dynamic_control_interface()
# events
self._update_event = omni.kit.app.get_app().get_update_event_stream().create_subscription_to_pop(self._on_update_event)
self._timeline_event = self._timeline.get_timeline_event_stream().create_subscription_to_pop(self._on_timeline_event)
self._stage_event = self._usd_context.get_stage_event_stream().create_subscription_to_pop(self._on_stage_event)
self._physx_event = self._physx_interface.subscribe_physics_step_events(self._on_physics_event)
def shutdown(self) -> None:
"""Shutdown the Ros2Bridge interface
"""
self._update_event = None
self._timeline_event = None
self._stage_event = None
self._stop_components()
self.destroy_node()
rclpy.shutdown()
def _get_ros_bridge_schemas(self) -> List['ROSSchema.RosBridgeComponent']:
"""Get the ROS bridge schemas in the current stage
:returns: The ROS bridge schemas
:rtype: list of RosBridgeComponent
"""
schemas = []
stage = self._usd_context.get_stage()
for prim in Usd.PrimRange.AllPrims(stage.GetPrimAtPath("/")):
if prim.GetTypeName() == "RosAttribute":
schemas.append(ROSSchema.RosAttribute(prim))
elif prim.GetTypeName() == "RosControlFollowJointTrajectory":
schemas.append(ROSControlSchema.RosControlFollowJointTrajectory(prim))
elif prim.GetTypeName() == "RosControlGripperCommand":
schemas.append(ROSControlSchema.RosControlGripperCommand(prim))
return schemas
def _stop_components(self) -> None:
"""Stop all components
"""
for component in self._components:
component.stop()
def _reload_components(self) -> None:
"""Reload all components
"""
# stop components
self._stop_components()
# load components
self._components = []
self._skip_update_step = True
for schema in self._get_ros_bridge_schemas():
if schema.__class__.__name__ == "RosAttribute":
self._components.append(RosAttribute(self, self._usd_context, schema, self._dci))
elif schema.__class__.__name__ == "RosControlFollowJointTrajectory":
self._components.append(RosControlFollowJointTrajectory(self, self._usd_context, schema, self._dci))
elif schema.__class__.__name__ == "RosControlGripperCommand":
self._components.append(RosControllerGripperCommand(self, self._usd_context, schema, self._dci))
def _on_update_event(self, event: 'carb.events._events.IEvent') -> None:
"""Handle the kit update event
:param event: Event
:type event: carb.events._events.IEvent
"""
if self._timeline.is_playing():
for component in self._components:
if self._skip_update_step:
self._skip_update_step = False
return
# start components
if not component.started:
component.start()
return
# step
component.update_step(event.payload["dt"])
def _on_timeline_event(self, event: 'carb.events._events.IEvent') -> None:
"""Handle the timeline event
:param event: Event
:type event: carb.events._events.IEvent
"""
# reload components
if event.type == int(omni.timeline.TimelineEventType.PLAY):
self._reload_components()
print("[Info][semu.robotics.ros2_bridge] RosControlBridge: components reloaded")
# stop components
elif event.type == int(omni.timeline.TimelineEventType.STOP) or event.type == int(omni.timeline.TimelineEventType.PAUSE):
self._stop_components()
print("[Info][semu.robotics.ros2_bridge] RosControlBridge: components stopped")
def _on_stage_event(self, event: 'carb.events._events.IEvent') -> None:
"""Handle the stage event
:param event: The stage event
:type event: carb.events._events.IEvent
"""
pass
def _on_physics_event(self, step: float) -> None:
"""Handle the physics event
:param step: The physics step
:type step: float
"""
for component in self._components:
component.physics_step(step)
class RosController:
def __init__(self, node: Node, usd_context: 'omni.usd._usd.UsdContext', schema: 'ROSSchema.RosBridgeComponent') -> None:
"""Base class for RosController
:param node: ROS2 node
:type node: Node
:param usd_context: USD context
:type usd_context: omni.usd._usd.UsdContext
:param schema: The ROS bridge schema
:type schema: ROSSchema.RosBridgeComponent
"""
self._node = node
self._usd_context = usd_context
self._schema = schema
self.started = False
def start(self) -> None:
"""Start the component
"""
raise NotImplementedError
def stop(self) -> None:
"""Stop the component
"""
print("[Info][semu.robotics.ros2_bridge] RosController: stopping {}".format(self._schema.__class__.__name__))
self.started = False
def update_step(self, dt: float) -> None:
"""Kit update step
:param dt: The delta time
:type dt: float
"""
raise NotImplementedError
def physics_step(self, dt: float) -> None:
"""Physics update step
:param dt: The physics delta time
:type dt: float
"""
raise NotImplementedError
class RosAttribute(RosController):
def __init__(self,
node: Node,
usd_context: 'omni.usd._usd.UsdContext',
schema: 'ROSSchema.RosBridgeComponent',
dci: 'omni.isaac.dynamic_control.DynamicControl') -> None:
"""RosAttribute interface
:param node: The ROS node
:type node: rclpy.node.Node
:param usd_context: USD context
:type usd_context: omni.usd._usd.UsdContext
:param schema: The ROS bridge schema
:type schema: ROSSchema.RosAttribute
:param dci: The dynamic control interface
:type dci: omni.isaac.dynamic_control.DynamicControl
"""
super().__init__(node, usd_context, schema)
self._dci = dci
self._srv_prims = None
self._srv_attributes = None
self._srv_getter = None
self._srv_setter = None
self._value = None
self._attribute = None
self._event = threading.Event()
self._event.set()
self.__event_timeout = carb.settings.get_settings().get("/exts/semu.robotics.ros2_bridge/eventTimeout")
self.__set_attribute_using_asyncio = \
carb.settings.get_settings().get("/exts/semu.robotics.ros2_bridge/setAttributeUsingAsyncio")
print("[Info][semu.robotics.ros2_bridge] RosAttribute: asyncio: {}".format(self.__set_attribute_using_asyncio))
print("[Info][semu.robotics.ros2_bridge] RosAttribute: event timeout: {}".format(self.__event_timeout))
async def _set_attribute(self, attribute: 'pxr.Usd.Attribute', attribute_value: Any) -> None:
"""Set the attribute value using asyncio
:param attribute: The prim's attribute to set
:type attribute: pxr.Usd.Attribute
:param attribute_value: The attribute value
:type attribute_value: Any
"""
ret = attribute.Set(attribute_value)
def _process_setter_request(self,
request: 'SetPrimAttribute.Request',
response: 'SetPrimAttribute.Response') -> 'SetPrimAttribute.Response':
"""Process the setter request
:param request: The service request
:type request: SetPrimAttribute.Request
:param response: The service response
:type response: SetPrimAttribute.Response
:return: The service response
:rtype: SetPrimAttribute.Response
"""
response.success = False
if self._schema.GetEnabledAttr().Get():
stage = self._usd_context.get_stage()
# get prim
if stage.GetPrimAtPath(request.path).IsValid():
prim = stage.GetPrimAtPath(request.path)
if request.attribute and prim.HasAttribute(request.attribute):
# attribute
attribute = prim.GetAttribute(request.attribute)
attribute_type = type(attribute.Get()).__name__
# value
try:
value = json.loads(request.value)
attribute_value = None
except json.JSONDecodeError:
print("[Error][semu.robotics.ros2_bridge] RosAttribute: invalid value: {}".format(request.value))
response.success = False
response.message = "Invalid value '{}'".format(request.value)
return response
# parse data
try:
if attribute_type in ['Vec2d', 'Vec2f', 'Vec2h', 'Vec2i']:
attribute_value = type(attribute.Get())(value)
elif attribute_type in ['Vec3d', 'Vec3f', 'Vec3h', 'Vec3i']:
attribute_value = type(attribute.Get())(value)
elif attribute_type in ['Vec4d', 'Vec4f', 'Vec4h', 'Vec4i']:
attribute_value = type(attribute.Get())(value)
elif attribute_type in ['Quatd', 'Quatf', 'Quath']:
attribute_value = type(attribute.Get())(*value)
elif attribute_type in ['Matrix4d', 'Matrix4f']:
attribute_value = type(attribute.Get())(value)
elif attribute_type.startswith('Vec') and attribute_type.endswith('Array'):
attribute_value = type(attribute.Get())(value)
elif attribute_type.startswith('Matrix') and attribute_type.endswith('Array'):
if attribute_type.endswith("dArray"):
attribute_value = type(attribute.Get())([Gf.Matrix2d(v) for v in value])
elif attribute_type.endswith("fArray"):
attribute_value = type(attribute.Get())([Gf.Matrix2f(v) for v in value])
elif attribute_type.startswith('Quat') and attribute_type.endswith('Array'):
if attribute_type.endswith("dArray"):
attribute_value = type(attribute.Get())([Gf.Quatd(*v) for v in value])
elif attribute_type.endswith("fArray"):
attribute_value = type(attribute.Get())([Gf.Quatf(*v) for v in value])
elif attribute_type.endswith("hArray"):
attribute_value = type(attribute.Get())([Gf.Quath(*v) for v in value])
elif attribute_type.endswith('Array'):
attribute_value = type(attribute.Get())(value)
elif attribute_type in ['AssetPath']:
attribute_value = type(attribute.Get())(value)
elif attribute_type in ['NoneType']:
pass
else:
attribute_value = type(attribute.Get())(value)
# set attribute
if attribute_value is not None:
# set attribute usign asyncio
if self.__set_attribute_using_asyncio:
try:
loop = asyncio.get_event_loop()
except:
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
future = asyncio.ensure_future(self._set_attribute(attribute, attribute_value))
loop.run_until_complete(future)
response.success = True
# set attribute in the physics event
else:
self._attribute = attribute
self._value = attribute_value
self._event.clear()
response.success = self._event.wait(self.__event_timeout)
if not response.success:
response.message = "The timeout ({} s) for setting the attribute value has been reached" \
.format(self.__event_timeout)
except Exception as e:
print("[Error][semu.robotics.ros2_bridge] RosAttribute: srv {} request for {} ({}: {}): {}" \
.format(self._srv_setter.resolved_name, request.path, request.attribute, value, e))
response.success = False
response.message = str(e)
else:
response.message = "Prim has not attribute {}".format(request.attribute)
else:
response.message = "Invalid prim ({})".format(request.path)
else:
response.message = "RosAttribute prim is not enabled"
return response
def _process_getter_request(self,
request: 'GetPrimAttribute.Request',
response: 'GetPrimAttribute.Response') -> 'GetPrimAttribute.Response':
"""Process the getter request
:param request: The service request
:type request: GetPrimAttribute.Request
:param response: The service response
:type response: GetPrimAttribute.Response
:return: The service response
:rtype: GetPrimAttribute.Response
"""
response.success = False
if self._schema.GetEnabledAttr().Get():
stage = self._usd_context.get_stage()
# get prim
if stage.GetPrimAtPath(request.path).IsValid():
prim = stage.GetPrimAtPath(request.path)
if request.attribute and prim.HasAttribute(request.attribute):
attribute = prim.GetAttribute(request.attribute)
response.type = type(attribute.Get()).__name__
# parse data
response.success = True
if response.type in ['Vec2d', 'Vec2f', 'Vec2h', 'Vec2i']:
data = attribute.Get()
response.value = json.dumps([data[i] for i in range(2)])
elif response.type in ['Vec3d', 'Vec3f', 'Vec3h', 'Vec3i']:
data = attribute.Get()
response.value = json.dumps([data[i] for i in range(3)])
elif response.type in ['Vec4d', 'Vec4f', 'Vec4h', 'Vec4i']:
data = attribute.Get()
response.value = json.dumps([data[i] for i in range(4)])
elif response.type in ['Quatd', 'Quatf', 'Quath']:
data = attribute.Get()
response.value = json.dumps([data.real, data.imaginary[0], data.imaginary[1], data.imaginary[2]])
elif response.type in ['Matrix4d', 'Matrix4f']:
data = attribute.Get()
response.value = json.dumps([[data.GetRow(i)[j] for j in range(data.dimension[1])] \
for i in range(data.dimension[0])])
elif response.type.startswith('Vec') and response.type.endswith('Array'):
data = attribute.Get()
response.value = json.dumps([[d[i] for i in range(len(d))] for d in data])
elif response.type.startswith('Matrix') and response.type.endswith('Array'):
data = attribute.Get()
response.value = json.dumps([[[d.GetRow(i)[j] for j in range(d.dimension[1])] \
for i in range(d.dimension[0])] for d in data])
elif response.type.startswith('Quat') and response.type.endswith('Array'):
data = attribute.Get()
response.value = json.dumps([[d.real, d.imaginary[0], d.imaginary[1], d.imaginary[2]] for d in data])
elif response.type.endswith('Array'):
try:
response.value = json.dumps(list(attribute.Get()))
except Exception as e:
print("[Warning][semu.robotics.ros2_bridge] RosAttribute: Unknow attribute type {}" \
.format(type(attribute.Get())))
print(" |-- Please, report a new issue (https://github.com/Toni-SM/semu.robotics.ros2_bridge/issues)")
response.success = False
response.message = "Unknow type {}".format(type(attribute.Get()))
elif response.type in ['AssetPath']:
response.value = json.dumps(str(attribute.Get().path))
else:
try:
response.value = json.dumps(attribute.Get())
except Exception as e:
print("[Warning][semu.robotics.ros2_bridge] RosAttribute: Unknow {}: {}" \
.format(type(attribute.Get()), attribute.Get()))
print(" |-- Please, report a new issue (https://github.com/Toni-SM/semu.robotics.ros2_bridge/issues)")
response.success = False
response.message = "Unknow type {}".format(type(attribute.Get()))
else:
response.message = "Prim has not attribute {}".format(request.attribute)
else:
response.message = "Invalid prim ({})".format(request.path)
else:
response.message = "RosAttribute prim is not enabled"
return response
def _process_attributes_request(self,
request: 'GetPrimAttributes.Request',
response: 'GetPrimAttributes.Response') -> 'GetPrimAttributes.Response':
"""Process the 'get all attributes' request
:param request: The service request
:type request: GetPrimAttributes.Request
:param response: The service response
:type response: GetPrimAttributes.Response
:return: The service response
:rtype: GetPrimAttributes.Response
"""
response.success = False
if self._schema.GetEnabledAttr().Get():
stage = self._usd_context.get_stage()
# get prim
if stage.GetPrimAtPath(request.path).IsValid():
prim = stage.GetPrimAtPath(request.path)
for attribute in prim.GetAttributes():
if attribute.GetNamespace():
response.names.append("{}:{}".format(attribute.GetNamespace(), attribute.GetBaseName()))
else:
response.names.append(attribute.GetBaseName())
response.displays.append(attribute.GetDisplayName())
response.types.append(type(attribute.Get()).__name__)
response.success = True
else:
response.message = "Invalid prim ({})".format(request.path)
else:
response.message = "RosAttribute prim is not enabled"
return response
def _process_prims_request(self, request: 'GetPrims.Request', response: 'GetPrims.Response') -> 'GetPrims.Response':
"""Process the 'get all prims' request
:param request: The service request
:type request: GetPrims.Request
:param response: The service response
:type response: GetPrims.Response
:return: The service response
:rtype: GetPrims.Response
"""
response.success = False
if self._schema.GetEnabledAttr().Get():
stage = self._usd_context.get_stage()
# get prims
if not request.path or stage.GetPrimAtPath(request.path).IsValid():
path = request.path if request.path else "/"
for prim in Usd.PrimRange.AllPrims(stage.GetPrimAtPath(path)):
response.paths.append(str(prim.GetPath()))
response.types.append(prim.GetTypeName())
response.success = True
else:
response.message = "Invalid search path ({})".format(request.path)
else:
response.message = "RosAttribute prim is not enabled"
return response
def start(self) -> None:
"""Start the services
"""
print("[Info][semu.robotics.ros2_bridge] RosAttribute: starting {}".format(self._schema.__class__.__name__))
service_name = self._schema.GetPrimsSrvTopicAttr().Get()
self._srv_prims = self._node.create_service(GetPrims, service_name, self._process_prims_request)
print("[Info][semu.robotics.ros2_bridge] RosAttribute: register srv: {}".format(self._srv_prims.srv_name))
service_name = self._schema.GetGetAttrSrvTopicAttr().Get()
self._srv_getter = self._node.create_service(GetPrimAttribute, service_name, self._process_getter_request)
print("[Info][semu.robotics.ros2_bridge] RosAttribute: register srv: {}".format(self._srv_getter.srv_name))
service_name = self._schema.GetAttributesSrvTopicAttr().Get()
self._srv_attributes = self._node.create_service(GetPrimAttributes, service_name, self._process_attributes_request)
print("[Info][semu.robotics.ros2_bridge] RosAttribute: register srv: {}".format(self._srv_attributes.srv_name))
service_name = self._schema.GetSetAttrSrvTopicAttr().Get()
self._srv_setter = self._node.create_service(SetPrimAttribute, service_name, self._process_setter_request)
print("[Info][semu.robotics.ros2_bridge] RosAttribute: register srv: {}".format(self._srv_setter.srv_name))
self.started = True
def stop(self) -> None:
"""Stop the services
"""
if self._srv_prims is not None:
print("[Info][semu.robotics.ros2_bridge] RosAttribute: unregister srv: {}".format(self._srv_prims.srv_name))
self._node.destroy_service(self._srv_prims)
self._srv_prims = None
if self._srv_getter is not None:
print("[Info][semu.robotics.ros2_bridge] RosAttribute: unregister srv: {}".format(self._srv_getter.srv_name))
self._node.destroy_service(self._srv_getter)
self._srv_getter = None
if self._srv_attributes is not None:
print("[Info][semu.robotics.ros2_bridge] RosAttribute: unregister srv: {}".format(self._srv_attributes.srv_name))
self._node.destroy_service(self._srv_attributes)
self._srv_attributes = None
if self._srv_setter is not None:
print("[Info][semu.robotics.ros2_bridge] RosAttribute: unregister srv: {}".format(self._srv_setter.srv_name))
self._node.destroy_service(self._srv_setter)
self._srv_setter = None
super().stop()
def update_step(self, dt: float) -> None:
"""Kit update step
:param dt: The delta time
:type dt: float
"""
pass
def physics_step(self, dt: float) -> None:
"""Physics update step
:param dt: The physics delta time
:type dt: float
"""
if not self.started:
return
if self.__set_attribute_using_asyncio:
return
if self._dci.is_simulating():
if not self._event.is_set():
if self._attribute is not None:
ret = self._attribute.Set(self._value)
self._event.set()
class RosControlFollowJointTrajectory(RosController):
def __init__(self,
node: Node,
usd_context: 'omni.usd._usd.UsdContext',
schema: 'ROSSchema.RosBridgeComponent',
dci: 'omni.isaac.dynamic_control.DynamicControl') -> None:
"""FollowJointTrajectory interface
:param node: The ROS node
:type node: rclpy.node.Node
:param usd_context: The USD context
:type usd_context: omni.usd._usd.UsdContext
:param schema: The schema
:type schema: ROSSchema.RosBridgeComponent
:param dci: The dynamic control interface
:type dci: omni.isaac.dynamic_control.DynamicControl
"""
super().__init__(node, usd_context, schema)
self._dci = dci
self._articulation = _dynamic_control.INVALID_HANDLE
self._joints = {}
self._action_server = None
self._action_dt = 0.05
self._action_goal = None
self._action_goal_handle = None
self._action_start_time = None
self._action_point_index = 1
# feedback / result
self._action_result_message = None
self._action_feedback_message = FollowJointTrajectory.Feedback()
def start(self) -> None:
"""Start the action server
"""
print("[Info][semu.robotics.ros2_bridge] RosControlFollowJointTrajectory: starting {}" \
.format(self._schema.__class__.__name__))
# get attributes and relationships
action_namespace = self._schema.GetActionNamespaceAttr().Get()
controller_name = self._schema.GetControllerNameAttr().Get()
relationships = self._schema.GetArticulationPrimRel().GetTargets()
if not len(relationships):
print("[Warning][semu.robotics.ros2_bridge] RosControlFollowJointTrajectory: empty relationships")
return
# check for articulation API
stage = self._usd_context.get_stage()
path = relationships[0].GetPrimPath().pathString
if not stage.GetPrimAtPath(path).HasAPI(PhysxSchema.PhysxArticulationAPI):
print("[Warning][semu.robotics.ros2_bridge] RosControlFollowJointTrajectory: {} doesn't have PhysxArticulationAPI".format(path))
return
# start action server
self._action_server = ActionServer(self._node,
FollowJointTrajectory,
controller_name + action_namespace,
execute_callback=self._on_execute,
goal_callback=self._on_goal,
cancel_callback=self._on_cancel,
handle_accepted_callback=self._on_handle_accepted)
print("[Info][semu.robotics.ros2_bridge] RosControlFollowJointTrajectory: register action {}" \
.format(controller_name + action_namespace))
self.started = True
def stop(self) -> None:
"""Stop the action server
"""
super().stop()
self._articulation = _dynamic_control.INVALID_HANDLE
# destroy action server
if self._action_server is not None:
print("[Info][semu.robotics.ros2_bridge] RosControlFollowJointTrajectory: destroy action server: {}" \
.format(self._schema.GetPrim().GetPath()))
# self._action_server.destroy()
self._action_server = None
self._action_goal_handle = None
self._action_goal = None
def _duration_to_seconds(self, duration: Duration) -> float:
"""Convert a ROS2 Duration to seconds
:param duration: The ROS2 Duration
:type duration: Duration
:return: The duration in seconds
:rtype: float
"""
return Duration.from_msg(duration).nanoseconds / 1e9
def _init_articulation(self) -> None:
"""Initialize the articulation and register joints
"""
# get articulation
relationships = self._schema.GetArticulationPrimRel().GetTargets()
path = relationships[0].GetPrimPath().pathString
self._articulation = self._dci.get_articulation(path)
if self._articulation == _dynamic_control.INVALID_HANDLE:
print("[Warning][semu.robotics.ros2_bridge] RosControlFollowJointTrajectory: {} is not an articulation".format(path))
return
dof_props = self._dci.get_articulation_dof_properties(self._articulation)
if dof_props is None:
return
upper_limits = dof_props["upper"]
lower_limits = dof_props["lower"]
has_limits = dof_props["hasLimits"]
# get joints
for i in range(self._dci.get_articulation_dof_count(self._articulation)):
dof_ptr = self._dci.get_articulation_dof(self._articulation, i)
if dof_ptr != _dynamic_control.DofType.DOF_NONE:
dof_name = self._dci.get_dof_name(dof_ptr)
if dof_name not in self._joints:
_joint = self._dci.find_articulation_joint(self._articulation, dof_name)
self._joints[dof_name] = {"joint": _joint,
"type": self._dci.get_joint_type(_joint),
"dof": self._dci.find_articulation_dof(self._articulation, dof_name),
"lower": lower_limits[i],
"upper": upper_limits[i],
"has_limits": has_limits[i]}
if not self._joints:
print("[Warning][semu.robotics.ros2_bridge] RosControlFollowJointTrajectory: no joints found in {}".format(path))
self.started = False
def _set_joint_position(self, name: str, target_position: float) -> None:
"""Set the target position of a joint in the articulation
:param name: The joint name
:type name: str
:param target_position: The target position
:type target_position: float
"""
# clip target position
if self._joints[name]["has_limits"]:
target_position = min(max(target_position, self._joints[name]["lower"]), self._joints[name]["upper"])
# scale target position for prismatic joints
if self._joints[name]["type"] == _dynamic_control.JOINT_PRISMATIC:
target_position /= get_stage_units()
# set target position
self._dci.set_dof_position_target(self._joints[name]["dof"], target_position)
def _get_joint_position(self, name: str) -> float:
"""Get the current position of a joint in the articulation
:param name: The joint name
:type name: str
:return: The current position of the joint
:rtype: float
"""
position = self._dci.get_dof_state(self._joints[name]["dof"], _dynamic_control.STATE_POS).pos
if self._joints[name]["type"] == _dynamic_control.JOINT_PRISMATIC:
return position * get_stage_units()
return position
def _on_handle_accepted(self, goal_handle: 'rclpy.action.server.ServerGoalHandle') -> None:
"""Callback function for handling newly accepted goals
:param goal_handle: The goal handle
:type goal_handle: rclpy.action.server.ServerGoalHandle
"""
goal_handle.execute()
def _on_goal(self, goal: 'FollowJointTrajectory.Goal') -> 'rclpy.action.server.GoalResponse':
"""Callback function for handling new goal requests
:param goal: The goal
:type goal: FollowJointTrajectory.Goal
:return: Whether the goal was accepted
:rtype: rclpy.action.server.GoalResponse
"""
# reject if joints don't match
for name in goal.trajectory.joint_names:
if name not in self._joints:
print("[Warning][semu.robotics.ros2_bridge] RosControlFollowJointTrajectory: joints don't match ({} not in {})" \
.format(name, list(self._joints.keys())))
return GoalResponse.REJECT
# reject if there is an active goal
if self._action_goal is not None:
print("[Warning][semu.robotics.ros2_bridge] RosControlFollowJointTrajectory: multiple goals not supported")
return GoalResponse.REJECT
# check initial position
if goal.trajectory.points[0].time_from_start:
initial_point = JointTrajectoryPoint(positions=[self._get_joint_position(name) for name in goal.trajectory.joint_names],
time_from_start=Duration().to_msg())
goal.trajectory.points.insert(0, initial_point)
# reset internal data
self._action_goal_handle = None
self._action_start_time = None
self._action_result_message = None
# store goal data
self._action_goal = goal
return GoalResponse.ACCEPT
def _on_cancel(self, goal_handle: 'rclpy.action.server.ServerGoalHandle') -> 'rclpy.action.server.CancelResponse':
"""Callback function for handling cancel requests
:param goal_handle: The goal handle
:type goal_handle: rclpy.action.server.ServerGoalHandle
:return: Whether the goal was canceled
:rtype: rclpy.action.server.CancelResponse
"""
if self._action_goal is None:
return CancelResponse.REJECT
# reset internal data
self._action_goal = None
self._action_goal_handle = None
self._action_start_time = None
self._action_result_message = None
goal_handle.destroy()
return CancelResponse.ACCEPT
def _on_execute(self, goal_handle: 'rclpy.action.server.ServerGoalHandle') -> 'FollowJointTrajectory.Result':
"""Callback function for processing accepted goals
:param goal_handle: The goal handle
:type goal_handle: rclpy.action.server.ServerGoalHandle
:return: The result of the goal execution
:rtype: FollowJointTrajectory.Result
"""
# reset internal data
self._action_start_time = self._node.get_clock().now().nanoseconds / 1e9
self._action_result_message = None
# set goal
self._action_goal_handle = goal_handle
# wait for the goal to be executed
while self._action_result_message is None:
if self._action_goal is None:
result = FollowJointTrajectory.Result()
result.error_code = result.INVALID_GOAL
return result
time.sleep(self._action_dt)
self._action_goal = None
self._action_goal_handle = None
return self._action_result_message
def update_step(self, dt: float) -> None:
"""Kit update step
:param dt: The delta time
:type dt: float
"""
pass
def physics_step(self, dt: float) -> None:
"""Physics update step
:param dt: The physics delta time
:type dt: float
"""
if not self.started:
return
# init articulation
if not self._joints:
self._init_articulation()
return
# update articulation
if self._action_goal is not None and self._action_goal_handle is not None:
self._action_dt = dt
# end of trajectory
if self._action_point_index >= len(self._action_goal.trajectory.points):
self._action_goal = None
self._action_result_message = FollowJointTrajectory.Result()
self._action_result_message.error_code = self._action_result_message.SUCCESSFUL
if self._action_goal_handle is not None:
self._action_goal_handle.succeed()
self._action_goal_handle = None
return
previous_point = self._action_goal.trajectory.points[self._action_point_index - 1]
current_point = self._action_goal.trajectory.points[self._action_point_index]
time_passed = self._node.get_clock().now().nanoseconds / 1e9 - self._action_start_time
# set target using linear interpolation
if time_passed <= self._duration_to_seconds(current_point.time_from_start):
ratio = (time_passed - self._duration_to_seconds(previous_point.time_from_start)) \
/ (self._duration_to_seconds(current_point.time_from_start) \
- self._duration_to_seconds(previous_point.time_from_start))
self._dci.wake_up_articulation(self._articulation)
for i, name in enumerate(self._action_goal.trajectory.joint_names):
side = -1 if current_point.positions[i] < previous_point.positions[i] else 1
target_position = previous_point.positions[i] \
+ side * ratio * abs(current_point.positions[i] - previous_point.positions[i])
self._set_joint_position(name, target_position)
# send feedback
else:
self._action_point_index += 1
self._action_feedback_message.joint_names = list(self._action_goal.trajectory.joint_names)
self._action_feedback_message.actual.positions = [self._get_joint_position(name) \
for name in self._action_goal.trajectory.joint_names]
self._action_feedback_message.actual.time_from_start = Duration(seconds=time_passed).to_msg()
if self._action_goal_handle is not None:
self._action_goal_handle.publish_feedback(self._action_feedback_message)
class RosControllerGripperCommand(RosController):
def __init__(self,
node: Node,
usd_context: 'omni.usd._usd.UsdContext',
schema: 'ROSSchema.RosBridgeComponent',
dci: 'omni.isaac.dynamic_control.DynamicControl') -> None:
"""GripperCommand interface
:param node: The ROS node
:type node: rclpy.node.Node
:param usd_context: The USD context
:type usd_context: omni.usd._usd.UsdContext
:param schema: The ROS bridge schema
:type schema: ROSSchema.RosBridgeComponent
:param dci: The dynamic control interface
:type dci: omni.isaac.dynamic_control.DynamicControl
"""
super().__init__(node, usd_context, schema)
self._dci = dci
self._articulation = _dynamic_control.INVALID_HANDLE
self._joints = {}
self._action_server = None
self._action_dt = 0.05
self._action_goal = None
self._action_goal_handle = None
self._action_start_time = None
# TODO: add to schema?
self._action_timeout = 10.0
self._action_position_threshold = 0.001
self._action_previous_position_sum = float("inf")
# feedback / result
self._action_result_message = None
self._action_feedback_message = GripperCommand.Feedback()
def start(self) -> None:
"""Start the action server
"""
print("[Info][semu.robotics.ros2_bridge] RosControllerGripperCommand: starting {}" \
.format(self._schema.__class__.__name__))
# get attributes and relationships
action_namespace = self._schema.GetActionNamespaceAttr().Get()
controller_name = self._schema.GetControllerNameAttr().Get()
relationships = self._schema.GetArticulationPrimRel().GetTargets()
if not len(relationships):
print("[Warning][semu.robotics.ros2_bridge] RosControllerGripperCommand: empty relationships")
return
elif len(relationships) == 1:
print("[Warning][semu.robotics.ros2_bridge] RosControllerGripperCommand: relationship is not a group")
return
# check for articulation API
stage = self._usd_context.get_stage()
path = relationships[0].GetPrimPath().pathString
if not stage.GetPrimAtPath(path).HasAPI(PhysxSchema.PhysxArticulationAPI):
print("[Warning][semu.robotics.ros2_bridge] RosControllerGripperCommand: {} doesn't have PhysxArticulationAPI".format(path))
return
# start action server
self._action_server = ActionServer(self._node,
GripperCommand,
controller_name + action_namespace,
execute_callback=self._on_execute,
goal_callback=self._on_goal,
cancel_callback=self._on_cancel,
handle_accepted_callback=self._on_handle_accepted)
print("[Info][semu.robotics.ros2_bridge] RosControllerGripperCommand: register action {}" \
.format(controller_name + action_namespace))
self.started = True
def stop(self) -> None:
"""Stop the action server
"""
super().stop()
self._articulation = _dynamic_control.INVALID_HANDLE
# destroy action server
if self._action_server is not None:
print("[Info][semu.robotics.ros2_bridge] RosControllerGripperCommand: destroy action server: {}" \
.format(self._schema.GetPrim().GetPath()))
# self._action_server.destroy()
self._action_server = None
self._action_goal_handle = None
self._action_goal = None
def _duration_to_seconds(self, duration: Duration) -> float:
"""Convert a ROS2 Duration to seconds
:param duration: The ROS2 Duration
:type duration: Duration
:return: The duration in seconds
:rtype: float
"""
return Duration.from_msg(duration).nanoseconds / 1e9
def _init_articulation(self) -> None:
"""Initialize the articulation and register joints
"""
# get articulation
relationships = self._schema.GetArticulationPrimRel().GetTargets()
path = relationships[0].GetPrimPath().pathString
self._articulation = self._dci.get_articulation(path)
if self._articulation == _dynamic_control.INVALID_HANDLE:
print("[Warning][semu.robotics.ros2_bridge] RosControllerGripperCommand: {} is not an articulation".format(path))
return
dof_props = self._dci.get_articulation_dof_properties(self._articulation)
if dof_props is None:
return
upper_limits = dof_props["upper"]
lower_limits = dof_props["lower"]
has_limits = dof_props["hasLimits"]
# get joints
# TODO: move to another relationship in the schema
paths = [relationship.GetPrimPath().pathString for relationship in relationships[1:]]
for i in range(self._dci.get_articulation_dof_count(self._articulation)):
dof_ptr = self._dci.get_articulation_dof(self._articulation, i)
if dof_ptr != _dynamic_control.DofType.DOF_NONE:
# add only required joints
if self._dci.get_dof_path(dof_ptr) in paths:
dof_name = self._dci.get_dof_name(dof_ptr)
if dof_name not in self._joints:
_joint = self._dci.find_articulation_joint(self._articulation, dof_name)
self._joints[dof_name] = {"joint": _joint,
"type": self._dci.get_joint_type(_joint),
"dof": self._dci.find_articulation_dof(self._articulation, dof_name),
"lower": lower_limits[i],
"upper": upper_limits[i],
"has_limits": has_limits[i]}
if not self._joints:
print("[Warning][semu.robotics.ros2_bridge] RosControllerGripperCommand: no joints found in {}".format(path))
self.started = False
def _set_joint_position(self, name: str, target_position: float) -> None:
"""Set the target position of a joint in the articulation
:param name: The joint name
:type name: str
:param target_position: The target position
:type target_position: float
"""
# clip target position
if self._joints[name]["has_limits"]:
target_position = min(max(target_position, self._joints[name]["lower"]), self._joints[name]["upper"])
# scale target position for prismatic joints
if self._joints[name]["type"] == _dynamic_control.JOINT_PRISMATIC:
target_position /= get_stage_units()
# set target position
self._dci.set_dof_position_target(self._joints[name]["dof"], target_position)
def _get_joint_position(self, name: str) -> float:
"""Get the current position of a joint in the articulation
:param name: The joint name
:type name: str
:return: The current position of the joint
:rtype: float
"""
position = self._dci.get_dof_state(self._joints[name]["dof"], _dynamic_control.STATE_POS).pos
if self._joints[name]["type"] == _dynamic_control.JOINT_PRISMATIC:
return position * get_stage_units()
return position
def _on_handle_accepted(self, goal_handle: 'rclpy.action.server.ServerGoalHandle') -> None:
"""Callback function for handling newly accepted goals
:param goal_handle: The goal handle
:type goal_handle: rclpy.action.server.ServerGoalHandle
"""
goal_handle.execute()
def _on_goal(self, goal: 'GripperCommand.Goal') -> 'rclpy.action.server.GoalResponse':
"""Callback function for handling new goal requests
:param goal: The goal
:type goal: GripperCommand.Goal
:return: Whether the goal was accepted
:rtype: rclpy.action.server.GoalResponse
"""
# reject if there is an active goal
if self._action_goal is not None:
print("[Warning][semu.robotics.ros2_bridge] RosControllerGripperCommand: multiple goals not supported")
return GoalResponse.REJECT
# reset internal data
self._action_goal = None
self._action_goal_handle = None
self._action_start_time = None
self._action_result_message = None
self._action_previous_position_sum = float("inf")
return GoalResponse.ACCEPT
def _on_cancel(self, goal_handle: 'rclpy.action.server.ServerGoalHandle') -> 'rclpy.action.server.CancelResponse':
"""Callback function for handling cancel requests
:param goal_handle: The goal handle
:type goal_handle: rclpy.action.server.ServerGoalHandle
:return: Whether the goal was canceled
:rtype: rclpy.action.server.CancelResponse
"""
if self._action_goal is None:
return CancelResponse.REJECT
# reset internal data
self._action_goal = None
self._action_goal_handle = None
self._action_start_time = None
self._action_result_message = None
self._action_previous_position_sum = float("inf")
goal_handle.destroy()
return CancelResponse.ACCEPT
def _on_execute(self, goal_handle: 'rclpy.action.server.ServerGoalHandle') -> 'GripperCommand.Result':
"""Callback function for processing accepted goals
:param goal_handle: The goal handle
:type goal_handle: rclpy.action.server.ServerGoalHandle
:return: The result of the goal execution
:rtype: GripperCommand.Result
"""
# reset internal data
self._action_start_time = self._node.get_clock().now().nanoseconds / 1e9
self._action_result_message = None
self._action_previous_position_sum = float("inf")
# set goal
self._action_goal_handle = goal_handle
self._action_goal = goal_handle.request
# wait for the goal to be executed
while self._action_result_message is None:
if self._action_goal is None:
return GripperCommand.Result()
time.sleep(self._action_dt)
self._action_goal = None
self._action_goal_handle = None
return self._action_result_message
def update_step(self, dt: float) -> None:
"""Kit update step
:param dt: The delta time
:type dt: float
"""
pass
def physics_step(self, dt: float) -> None:
"""Physics update step
:param dt: The physics delta time
:type dt: float
"""
if not self.started:
return
# init articulation
if not self._joints:
self._init_articulation()
return
# update articulation
if self._action_goal is not None and self._action_goal_handle is not None:
self._action_dt = dt
target_position = self._action_goal.command.position
# set target
self._dci.wake_up_articulation(self._articulation)
for name in self._joints:
self._set_joint_position(name, target_position)
# end (position reached)
position = 0
current_position_sum = 0
position_reached = True
for name in self._joints:
position = self._get_joint_position(name)
current_position_sum += position
if abs(position - target_position) > self._action_position_threshold:
position_reached = False
break
if position_reached:
self._action_result_message = GripperCommand.Result()
self._action_result_message.position = position
self._action_result_message.stalled = False
self._action_result_message.reached_goal = True
if self._action_goal_handle is not None:
self._action_goal_handle.succeed()
self._action_goal_handle = None
return
# end (stalled)
if abs(current_position_sum - self._action_previous_position_sum) < 1e-6:
self._action_result_message = GripperCommand.Result()
self._action_result_message.position = position
self._action_result_message.stalled = True
self._action_result_message.reached_goal = False
if self._action_goal_handle is not None:
self._action_goal_handle.succeed()
self._action_goal_handle = None
return
self._action_previous_position_sum = current_position_sum
# end (timeout)
time_passed = self._node.get_clock().now().nanoseconds / 1e9 - self._action_start_time
if time_passed >= self._action_timeout:
self._action_result_message = GripperCommand.Result()
if self._action_goal_handle is not None:
self._action_goal_handle.abort()
self._action_goal_handle = None
# TODO: send feedback
# self._action_goal_handle.publish_feedback(self._action_feedback_message)
| 55,059 | Python | 43.619125 | 141 | 0.576945 |
Toni-SM/semu.robotics.ros2_bridge/src/semu.robotics.ros2_bridge/semu/robotics/ros2_bridge/__init__.py | from .scripts.extension import *
| 33 | Python | 15.999992 | 32 | 0.787879 |
Toni-SM/semu.robotics.ros2_bridge/src/semu.robotics.ros2_bridge/semu/robotics/ros2_bridge/scripts/extension.py | import os
import sys
import carb
import omni.ext
try:
from .. import _ros2_bridge
except:
print(">>>> [DEVELOPMENT] import ros2_bridge")
from .. import ros2_bridge as _ros2_bridge
class Extension(omni.ext.IExt):
def on_startup(self, ext_id):
self._ros2bridge = None
self._extension_path = None
ext_manager = omni.kit.app.get_app().get_extension_manager()
if ext_manager.is_extension_enabled("omni.isaac.ros_bridge"):
carb.log_error("ROS 2 Bridge external extension cannot be enabled if ROS Bridge is enabled")
ext_manager.set_extension_enabled("semu.robotics.ros2_bridge", False)
return
self._extension_path = ext_manager.get_extension_path(ext_id)
sys.path.append(os.path.join(self._extension_path, "semu", "robotics", "ros2_bridge", "packages"))
if os.environ.get("LD_LIBRARY_PATH"):
os.environ["LD_LIBRARY_PATH"] = os.environ.get("LD_LIBRARY_PATH") + ":{}/bin".format(self._extension_path)
else:
os.environ["LD_LIBRARY_PATH"] = "{}/bin".format(self._extension_path)
self._ros2bridge = _ros2_bridge.acquire_ros2_bridge_interface(ext_id)
def on_shutdown(self):
if self._extension_path is not None:
sys.path.remove(os.path.join(self._extension_path, "semu", "robotics", "ros2_bridge", "packages"))
self._extension_path = None
if self._ros2bridge is not None:
_ros2_bridge.release_ros2_bridge_interface(self._ros2bridge)
self._ros2bridge = None
| 1,574 | Python | 39.384614 | 118 | 0.635959 |
Toni-SM/semu.robotics.ros2_bridge/src/semu.robotics.ros2_bridge/semu/robotics/ros2_bridge/packages/control_msgs/srv/_query_trajectory_state_s.c | // generated from rosidl_generator_py/resource/_idl_support.c.em
// with input from control_msgs:srv/QueryTrajectoryState.idl
// generated code does not contain a copyright notice
#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION
#include <Python.h>
#include <stdbool.h>
#ifndef _WIN32
# pragma GCC diagnostic push
# pragma GCC diagnostic ignored "-Wunused-function"
#endif
#include "numpy/ndarrayobject.h"
#ifndef _WIN32
# pragma GCC diagnostic pop
#endif
#include "rosidl_runtime_c/visibility_control.h"
#include "control_msgs/srv/detail/query_trajectory_state__struct.h"
#include "control_msgs/srv/detail/query_trajectory_state__functions.h"
ROSIDL_GENERATOR_C_IMPORT
bool builtin_interfaces__msg__time__convert_from_py(PyObject * _pymsg, void * _ros_message);
ROSIDL_GENERATOR_C_IMPORT
PyObject * builtin_interfaces__msg__time__convert_to_py(void * raw_ros_message);
ROSIDL_GENERATOR_C_EXPORT
bool control_msgs__srv__query_trajectory_state__request__convert_from_py(PyObject * _pymsg, void * _ros_message)
{
// check that the passed message is of the expected Python class
{
char full_classname_dest[70];
{
char * class_name = NULL;
char * module_name = NULL;
{
PyObject * class_attr = PyObject_GetAttrString(_pymsg, "__class__");
if (class_attr) {
PyObject * name_attr = PyObject_GetAttrString(class_attr, "__name__");
if (name_attr) {
class_name = (char *)PyUnicode_1BYTE_DATA(name_attr);
Py_DECREF(name_attr);
}
PyObject * module_attr = PyObject_GetAttrString(class_attr, "__module__");
if (module_attr) {
module_name = (char *)PyUnicode_1BYTE_DATA(module_attr);
Py_DECREF(module_attr);
}
Py_DECREF(class_attr);
}
}
if (!class_name || !module_name) {
return false;
}
snprintf(full_classname_dest, sizeof(full_classname_dest), "%s.%s", module_name, class_name);
}
assert(strncmp("control_msgs.srv._query_trajectory_state.QueryTrajectoryState_Request", full_classname_dest, 69) == 0);
}
control_msgs__srv__QueryTrajectoryState_Request * ros_message = _ros_message;
{ // time
PyObject * field = PyObject_GetAttrString(_pymsg, "time");
if (!field) {
return false;
}
if (!builtin_interfaces__msg__time__convert_from_py(field, &ros_message->time)) {
Py_DECREF(field);
return false;
}
Py_DECREF(field);
}
return true;
}
ROSIDL_GENERATOR_C_EXPORT
PyObject * control_msgs__srv__query_trajectory_state__request__convert_to_py(void * raw_ros_message)
{
/* NOTE(esteve): Call constructor of QueryTrajectoryState_Request */
PyObject * _pymessage = NULL;
{
PyObject * pymessage_module = PyImport_ImportModule("control_msgs.srv._query_trajectory_state");
assert(pymessage_module);
PyObject * pymessage_class = PyObject_GetAttrString(pymessage_module, "QueryTrajectoryState_Request");
assert(pymessage_class);
Py_DECREF(pymessage_module);
_pymessage = PyObject_CallObject(pymessage_class, NULL);
Py_DECREF(pymessage_class);
if (!_pymessage) {
return NULL;
}
}
control_msgs__srv__QueryTrajectoryState_Request * ros_message = (control_msgs__srv__QueryTrajectoryState_Request *)raw_ros_message;
{ // time
PyObject * field = NULL;
field = builtin_interfaces__msg__time__convert_to_py(&ros_message->time);
if (!field) {
return NULL;
}
{
int rc = PyObject_SetAttrString(_pymessage, "time", field);
Py_DECREF(field);
if (rc) {
return NULL;
}
}
}
// ownership of _pymessage is transferred to the caller
return _pymessage;
}
#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION
// already included above
// #include <Python.h>
// already included above
// #include <stdbool.h>
// already included above
// #include "numpy/ndarrayobject.h"
// already included above
// #include "rosidl_runtime_c/visibility_control.h"
// already included above
// #include "control_msgs/srv/detail/query_trajectory_state__struct.h"
// already included above
// #include "control_msgs/srv/detail/query_trajectory_state__functions.h"
#include "rosidl_runtime_c/string.h"
#include "rosidl_runtime_c/string_functions.h"
#include "rosidl_runtime_c/primitives_sequence.h"
#include "rosidl_runtime_c/primitives_sequence_functions.h"
ROSIDL_GENERATOR_C_EXPORT
bool control_msgs__srv__query_trajectory_state__response__convert_from_py(PyObject * _pymsg, void * _ros_message)
{
// check that the passed message is of the expected Python class
{
char full_classname_dest[71];
{
char * class_name = NULL;
char * module_name = NULL;
{
PyObject * class_attr = PyObject_GetAttrString(_pymsg, "__class__");
if (class_attr) {
PyObject * name_attr = PyObject_GetAttrString(class_attr, "__name__");
if (name_attr) {
class_name = (char *)PyUnicode_1BYTE_DATA(name_attr);
Py_DECREF(name_attr);
}
PyObject * module_attr = PyObject_GetAttrString(class_attr, "__module__");
if (module_attr) {
module_name = (char *)PyUnicode_1BYTE_DATA(module_attr);
Py_DECREF(module_attr);
}
Py_DECREF(class_attr);
}
}
if (!class_name || !module_name) {
return false;
}
snprintf(full_classname_dest, sizeof(full_classname_dest), "%s.%s", module_name, class_name);
}
assert(strncmp("control_msgs.srv._query_trajectory_state.QueryTrajectoryState_Response", full_classname_dest, 70) == 0);
}
control_msgs__srv__QueryTrajectoryState_Response * ros_message = _ros_message;
{ // success
PyObject * field = PyObject_GetAttrString(_pymsg, "success");
if (!field) {
return false;
}
assert(PyBool_Check(field));
ros_message->success = (Py_True == field);
Py_DECREF(field);
}
{ // message
PyObject * field = PyObject_GetAttrString(_pymsg, "message");
if (!field) {
return false;
}
assert(PyUnicode_Check(field));
PyObject * encoded_field = PyUnicode_AsUTF8String(field);
if (!encoded_field) {
Py_DECREF(field);
return false;
}
rosidl_runtime_c__String__assign(&ros_message->message, PyBytes_AS_STRING(encoded_field));
Py_DECREF(encoded_field);
Py_DECREF(field);
}
{ // name
PyObject * field = PyObject_GetAttrString(_pymsg, "name");
if (!field) {
return false;
}
PyObject * seq_field = PySequence_Fast(field, "expected a sequence in 'name'");
if (!seq_field) {
Py_DECREF(field);
return false;
}
Py_ssize_t size = PySequence_Size(field);
if (-1 == size) {
Py_DECREF(seq_field);
Py_DECREF(field);
return false;
}
if (!rosidl_runtime_c__String__Sequence__init(&(ros_message->name), size)) {
PyErr_SetString(PyExc_RuntimeError, "unable to create String__Sequence ros_message");
Py_DECREF(seq_field);
Py_DECREF(field);
return false;
}
rosidl_runtime_c__String * dest = ros_message->name.data;
for (Py_ssize_t i = 0; i < size; ++i) {
PyObject * item = PySequence_Fast_GET_ITEM(seq_field, i);
if (!item) {
Py_DECREF(seq_field);
Py_DECREF(field);
return false;
}
assert(PyUnicode_Check(item));
PyObject * encoded_item = PyUnicode_AsUTF8String(item);
if (!encoded_item) {
Py_DECREF(seq_field);
Py_DECREF(field);
return false;
}
rosidl_runtime_c__String__assign(&dest[i], PyBytes_AS_STRING(encoded_item));
Py_DECREF(encoded_item);
}
Py_DECREF(seq_field);
Py_DECREF(field);
}
{ // position
PyObject * field = PyObject_GetAttrString(_pymsg, "position");
if (!field) {
return false;
}
PyObject * seq_field = PySequence_Fast(field, "expected a sequence in 'position'");
if (!seq_field) {
Py_DECREF(field);
return false;
}
Py_ssize_t size = PySequence_Size(field);
if (-1 == size) {
Py_DECREF(seq_field);
Py_DECREF(field);
return false;
}
if (!rosidl_runtime_c__double__Sequence__init(&(ros_message->position), size)) {
PyErr_SetString(PyExc_RuntimeError, "unable to create double__Sequence ros_message");
Py_DECREF(seq_field);
Py_DECREF(field);
return false;
}
double * dest = ros_message->position.data;
for (Py_ssize_t i = 0; i < size; ++i) {
PyObject * item = PySequence_Fast_GET_ITEM(seq_field, i);
if (!item) {
Py_DECREF(seq_field);
Py_DECREF(field);
return false;
}
assert(PyFloat_Check(item));
double tmp = PyFloat_AS_DOUBLE(item);
memcpy(&dest[i], &tmp, sizeof(double));
}
Py_DECREF(seq_field);
Py_DECREF(field);
}
{ // velocity
PyObject * field = PyObject_GetAttrString(_pymsg, "velocity");
if (!field) {
return false;
}
PyObject * seq_field = PySequence_Fast(field, "expected a sequence in 'velocity'");
if (!seq_field) {
Py_DECREF(field);
return false;
}
Py_ssize_t size = PySequence_Size(field);
if (-1 == size) {
Py_DECREF(seq_field);
Py_DECREF(field);
return false;
}
if (!rosidl_runtime_c__double__Sequence__init(&(ros_message->velocity), size)) {
PyErr_SetString(PyExc_RuntimeError, "unable to create double__Sequence ros_message");
Py_DECREF(seq_field);
Py_DECREF(field);
return false;
}
double * dest = ros_message->velocity.data;
for (Py_ssize_t i = 0; i < size; ++i) {
PyObject * item = PySequence_Fast_GET_ITEM(seq_field, i);
if (!item) {
Py_DECREF(seq_field);
Py_DECREF(field);
return false;
}
assert(PyFloat_Check(item));
double tmp = PyFloat_AS_DOUBLE(item);
memcpy(&dest[i], &tmp, sizeof(double));
}
Py_DECREF(seq_field);
Py_DECREF(field);
}
{ // acceleration
PyObject * field = PyObject_GetAttrString(_pymsg, "acceleration");
if (!field) {
return false;
}
PyObject * seq_field = PySequence_Fast(field, "expected a sequence in 'acceleration'");
if (!seq_field) {
Py_DECREF(field);
return false;
}
Py_ssize_t size = PySequence_Size(field);
if (-1 == size) {
Py_DECREF(seq_field);
Py_DECREF(field);
return false;
}
if (!rosidl_runtime_c__double__Sequence__init(&(ros_message->acceleration), size)) {
PyErr_SetString(PyExc_RuntimeError, "unable to create double__Sequence ros_message");
Py_DECREF(seq_field);
Py_DECREF(field);
return false;
}
double * dest = ros_message->acceleration.data;
for (Py_ssize_t i = 0; i < size; ++i) {
PyObject * item = PySequence_Fast_GET_ITEM(seq_field, i);
if (!item) {
Py_DECREF(seq_field);
Py_DECREF(field);
return false;
}
assert(PyFloat_Check(item));
double tmp = PyFloat_AS_DOUBLE(item);
memcpy(&dest[i], &tmp, sizeof(double));
}
Py_DECREF(seq_field);
Py_DECREF(field);
}
return true;
}
ROSIDL_GENERATOR_C_EXPORT
PyObject * control_msgs__srv__query_trajectory_state__response__convert_to_py(void * raw_ros_message)
{
/* NOTE(esteve): Call constructor of QueryTrajectoryState_Response */
PyObject * _pymessage = NULL;
{
PyObject * pymessage_module = PyImport_ImportModule("control_msgs.srv._query_trajectory_state");
assert(pymessage_module);
PyObject * pymessage_class = PyObject_GetAttrString(pymessage_module, "QueryTrajectoryState_Response");
assert(pymessage_class);
Py_DECREF(pymessage_module);
_pymessage = PyObject_CallObject(pymessage_class, NULL);
Py_DECREF(pymessage_class);
if (!_pymessage) {
return NULL;
}
}
control_msgs__srv__QueryTrajectoryState_Response * ros_message = (control_msgs__srv__QueryTrajectoryState_Response *)raw_ros_message;
{ // success
PyObject * field = NULL;
field = PyBool_FromLong(ros_message->success ? 1 : 0);
{
int rc = PyObject_SetAttrString(_pymessage, "success", field);
Py_DECREF(field);
if (rc) {
return NULL;
}
}
}
{ // message
PyObject * field = NULL;
field = PyUnicode_DecodeUTF8(
ros_message->message.data,
strlen(ros_message->message.data),
"strict");
if (!field) {
return NULL;
}
{
int rc = PyObject_SetAttrString(_pymessage, "message", field);
Py_DECREF(field);
if (rc) {
return NULL;
}
}
}
{ // name
PyObject * field = NULL;
size_t size = ros_message->name.size;
rosidl_runtime_c__String * src = ros_message->name.data;
field = PyList_New(size);
if (!field) {
return NULL;
}
for (size_t i = 0; i < size; ++i) {
PyObject * decoded_item = PyUnicode_DecodeUTF8(src[i].data, strlen(src[i].data), "strict");
if (!decoded_item) {
return NULL;
}
int rc = PyList_SetItem(field, i, decoded_item);
(void)rc;
assert(rc == 0);
}
assert(PySequence_Check(field));
{
int rc = PyObject_SetAttrString(_pymessage, "name", field);
Py_DECREF(field);
if (rc) {
return NULL;
}
}
}
{ // position
PyObject * field = NULL;
field = PyObject_GetAttrString(_pymessage, "position");
if (!field) {
return NULL;
}
assert(field->ob_type != NULL);
assert(field->ob_type->tp_name != NULL);
assert(strcmp(field->ob_type->tp_name, "array.array") == 0);
// ensure that itemsize matches the sizeof of the ROS message field
PyObject * itemsize_attr = PyObject_GetAttrString(field, "itemsize");
assert(itemsize_attr != NULL);
size_t itemsize = PyLong_AsSize_t(itemsize_attr);
Py_DECREF(itemsize_attr);
if (itemsize != sizeof(double)) {
PyErr_SetString(PyExc_RuntimeError, "itemsize doesn't match expectation");
Py_DECREF(field);
return NULL;
}
// clear the array, poor approach to remove potential default values
Py_ssize_t length = PyObject_Length(field);
if (-1 == length) {
Py_DECREF(field);
return NULL;
}
if (length > 0) {
PyObject * pop = PyObject_GetAttrString(field, "pop");
assert(pop != NULL);
for (Py_ssize_t i = 0; i < length; ++i) {
PyObject * ret = PyObject_CallFunctionObjArgs(pop, NULL);
if (!ret) {
Py_DECREF(pop);
Py_DECREF(field);
return NULL;
}
Py_DECREF(ret);
}
Py_DECREF(pop);
}
if (ros_message->position.size > 0) {
// populating the array.array using the frombytes method
PyObject * frombytes = PyObject_GetAttrString(field, "frombytes");
assert(frombytes != NULL);
double * src = &(ros_message->position.data[0]);
PyObject * data = PyBytes_FromStringAndSize((const char *)src, ros_message->position.size * sizeof(double));
assert(data != NULL);
PyObject * ret = PyObject_CallFunctionObjArgs(frombytes, data, NULL);
Py_DECREF(data);
Py_DECREF(frombytes);
if (!ret) {
Py_DECREF(field);
return NULL;
}
Py_DECREF(ret);
}
Py_DECREF(field);
}
{ // velocity
PyObject * field = NULL;
field = PyObject_GetAttrString(_pymessage, "velocity");
if (!field) {
return NULL;
}
assert(field->ob_type != NULL);
assert(field->ob_type->tp_name != NULL);
assert(strcmp(field->ob_type->tp_name, "array.array") == 0);
// ensure that itemsize matches the sizeof of the ROS message field
PyObject * itemsize_attr = PyObject_GetAttrString(field, "itemsize");
assert(itemsize_attr != NULL);
size_t itemsize = PyLong_AsSize_t(itemsize_attr);
Py_DECREF(itemsize_attr);
if (itemsize != sizeof(double)) {
PyErr_SetString(PyExc_RuntimeError, "itemsize doesn't match expectation");
Py_DECREF(field);
return NULL;
}
// clear the array, poor approach to remove potential default values
Py_ssize_t length = PyObject_Length(field);
if (-1 == length) {
Py_DECREF(field);
return NULL;
}
if (length > 0) {
PyObject * pop = PyObject_GetAttrString(field, "pop");
assert(pop != NULL);
for (Py_ssize_t i = 0; i < length; ++i) {
PyObject * ret = PyObject_CallFunctionObjArgs(pop, NULL);
if (!ret) {
Py_DECREF(pop);
Py_DECREF(field);
return NULL;
}
Py_DECREF(ret);
}
Py_DECREF(pop);
}
if (ros_message->velocity.size > 0) {
// populating the array.array using the frombytes method
PyObject * frombytes = PyObject_GetAttrString(field, "frombytes");
assert(frombytes != NULL);
double * src = &(ros_message->velocity.data[0]);
PyObject * data = PyBytes_FromStringAndSize((const char *)src, ros_message->velocity.size * sizeof(double));
assert(data != NULL);
PyObject * ret = PyObject_CallFunctionObjArgs(frombytes, data, NULL);
Py_DECREF(data);
Py_DECREF(frombytes);
if (!ret) {
Py_DECREF(field);
return NULL;
}
Py_DECREF(ret);
}
Py_DECREF(field);
}
{ // acceleration
PyObject * field = NULL;
field = PyObject_GetAttrString(_pymessage, "acceleration");
if (!field) {
return NULL;
}
assert(field->ob_type != NULL);
assert(field->ob_type->tp_name != NULL);
assert(strcmp(field->ob_type->tp_name, "array.array") == 0);
// ensure that itemsize matches the sizeof of the ROS message field
PyObject * itemsize_attr = PyObject_GetAttrString(field, "itemsize");
assert(itemsize_attr != NULL);
size_t itemsize = PyLong_AsSize_t(itemsize_attr);
Py_DECREF(itemsize_attr);
if (itemsize != sizeof(double)) {
PyErr_SetString(PyExc_RuntimeError, "itemsize doesn't match expectation");
Py_DECREF(field);
return NULL;
}
// clear the array, poor approach to remove potential default values
Py_ssize_t length = PyObject_Length(field);
if (-1 == length) {
Py_DECREF(field);
return NULL;
}
if (length > 0) {
PyObject * pop = PyObject_GetAttrString(field, "pop");
assert(pop != NULL);
for (Py_ssize_t i = 0; i < length; ++i) {
PyObject * ret = PyObject_CallFunctionObjArgs(pop, NULL);
if (!ret) {
Py_DECREF(pop);
Py_DECREF(field);
return NULL;
}
Py_DECREF(ret);
}
Py_DECREF(pop);
}
if (ros_message->acceleration.size > 0) {
// populating the array.array using the frombytes method
PyObject * frombytes = PyObject_GetAttrString(field, "frombytes");
assert(frombytes != NULL);
double * src = &(ros_message->acceleration.data[0]);
PyObject * data = PyBytes_FromStringAndSize((const char *)src, ros_message->acceleration.size * sizeof(double));
assert(data != NULL);
PyObject * ret = PyObject_CallFunctionObjArgs(frombytes, data, NULL);
Py_DECREF(data);
Py_DECREF(frombytes);
if (!ret) {
Py_DECREF(field);
return NULL;
}
Py_DECREF(ret);
}
Py_DECREF(field);
}
// ownership of _pymessage is transferred to the caller
return _pymessage;
}
| 19,331 | C | 31.655405 | 135 | 0.61435 |
Toni-SM/semu.robotics.ros2_bridge/src/semu.robotics.ros2_bridge/semu/robotics/ros2_bridge/packages/control_msgs/srv/_query_calibration_state.py | # generated from rosidl_generator_py/resource/_idl.py.em
# with input from control_msgs:srv/QueryCalibrationState.idl
# generated code does not contain a copyright notice
# Import statements for member types
import rosidl_parser.definition # noqa: E402, I100
class Metaclass_QueryCalibrationState_Request(type):
"""Metaclass of message 'QueryCalibrationState_Request'."""
_CREATE_ROS_MESSAGE = None
_CONVERT_FROM_PY = None
_CONVERT_TO_PY = None
_DESTROY_ROS_MESSAGE = None
_TYPE_SUPPORT = None
__constants = {
}
@classmethod
def __import_type_support__(cls):
try:
from rosidl_generator_py import import_type_support
module = import_type_support('control_msgs')
except ImportError:
import logging
import traceback
logger = logging.getLogger(
'control_msgs.srv.QueryCalibrationState_Request')
logger.debug(
'Failed to import needed modules for type support:\n' +
traceback.format_exc())
else:
cls._CREATE_ROS_MESSAGE = module.create_ros_message_msg__srv__query_calibration_state__request
cls._CONVERT_FROM_PY = module.convert_from_py_msg__srv__query_calibration_state__request
cls._CONVERT_TO_PY = module.convert_to_py_msg__srv__query_calibration_state__request
cls._TYPE_SUPPORT = module.type_support_msg__srv__query_calibration_state__request
cls._DESTROY_ROS_MESSAGE = module.destroy_ros_message_msg__srv__query_calibration_state__request
@classmethod
def __prepare__(cls, name, bases, **kwargs):
# list constant names here so that they appear in the help text of
# the message class under "Data and other attributes defined here:"
# as well as populate each message instance
return {
}
class QueryCalibrationState_Request(metaclass=Metaclass_QueryCalibrationState_Request):
"""Message class 'QueryCalibrationState_Request'."""
__slots__ = [
]
_fields_and_field_types = {
}
SLOT_TYPES = (
)
def __init__(self, **kwargs):
assert all('_' + key in self.__slots__ for key in kwargs.keys()), \
'Invalid arguments passed to constructor: %s' % \
', '.join(sorted(k for k in kwargs.keys() if '_' + k not in self.__slots__))
def __repr__(self):
typename = self.__class__.__module__.split('.')
typename.pop()
typename.append(self.__class__.__name__)
args = []
for s, t in zip(self.__slots__, self.SLOT_TYPES):
field = getattr(self, s)
fieldstr = repr(field)
# We use Python array type for fields that can be directly stored
# in them, and "normal" sequences for everything else. If it is
# a type that we store in an array, strip off the 'array' portion.
if (
isinstance(t, rosidl_parser.definition.AbstractSequence) and
isinstance(t.value_type, rosidl_parser.definition.BasicType) and
t.value_type.typename in ['float', 'double', 'int8', 'uint8', 'int16', 'uint16', 'int32', 'uint32', 'int64', 'uint64']
):
if len(field) == 0:
fieldstr = '[]'
else:
assert fieldstr.startswith('array(')
prefix = "array('X', "
suffix = ')'
fieldstr = fieldstr[len(prefix):-len(suffix)]
args.append(s[1:] + '=' + fieldstr)
return '%s(%s)' % ('.'.join(typename), ', '.join(args))
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
return True
@classmethod
def get_fields_and_field_types(cls):
from copy import copy
return copy(cls._fields_and_field_types)
# Import statements for member types
# already imported above
# import rosidl_parser.definition
class Metaclass_QueryCalibrationState_Response(type):
"""Metaclass of message 'QueryCalibrationState_Response'."""
_CREATE_ROS_MESSAGE = None
_CONVERT_FROM_PY = None
_CONVERT_TO_PY = None
_DESTROY_ROS_MESSAGE = None
_TYPE_SUPPORT = None
__constants = {
}
@classmethod
def __import_type_support__(cls):
try:
from rosidl_generator_py import import_type_support
module = import_type_support('control_msgs')
except ImportError:
import logging
import traceback
logger = logging.getLogger(
'control_msgs.srv.QueryCalibrationState_Response')
logger.debug(
'Failed to import needed modules for type support:\n' +
traceback.format_exc())
else:
cls._CREATE_ROS_MESSAGE = module.create_ros_message_msg__srv__query_calibration_state__response
cls._CONVERT_FROM_PY = module.convert_from_py_msg__srv__query_calibration_state__response
cls._CONVERT_TO_PY = module.convert_to_py_msg__srv__query_calibration_state__response
cls._TYPE_SUPPORT = module.type_support_msg__srv__query_calibration_state__response
cls._DESTROY_ROS_MESSAGE = module.destroy_ros_message_msg__srv__query_calibration_state__response
@classmethod
def __prepare__(cls, name, bases, **kwargs):
# list constant names here so that they appear in the help text of
# the message class under "Data and other attributes defined here:"
# as well as populate each message instance
return {
}
class QueryCalibrationState_Response(metaclass=Metaclass_QueryCalibrationState_Response):
"""Message class 'QueryCalibrationState_Response'."""
__slots__ = [
'_is_calibrated',
]
_fields_and_field_types = {
'is_calibrated': 'boolean',
}
SLOT_TYPES = (
rosidl_parser.definition.BasicType('boolean'), # noqa: E501
)
def __init__(self, **kwargs):
assert all('_' + key in self.__slots__ for key in kwargs.keys()), \
'Invalid arguments passed to constructor: %s' % \
', '.join(sorted(k for k in kwargs.keys() if '_' + k not in self.__slots__))
self.is_calibrated = kwargs.get('is_calibrated', bool())
def __repr__(self):
typename = self.__class__.__module__.split('.')
typename.pop()
typename.append(self.__class__.__name__)
args = []
for s, t in zip(self.__slots__, self.SLOT_TYPES):
field = getattr(self, s)
fieldstr = repr(field)
# We use Python array type for fields that can be directly stored
# in them, and "normal" sequences for everything else. If it is
# a type that we store in an array, strip off the 'array' portion.
if (
isinstance(t, rosidl_parser.definition.AbstractSequence) and
isinstance(t.value_type, rosidl_parser.definition.BasicType) and
t.value_type.typename in ['float', 'double', 'int8', 'uint8', 'int16', 'uint16', 'int32', 'uint32', 'int64', 'uint64']
):
if len(field) == 0:
fieldstr = '[]'
else:
assert fieldstr.startswith('array(')
prefix = "array('X', "
suffix = ')'
fieldstr = fieldstr[len(prefix):-len(suffix)]
args.append(s[1:] + '=' + fieldstr)
return '%s(%s)' % ('.'.join(typename), ', '.join(args))
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
if self.is_calibrated != other.is_calibrated:
return False
return True
@classmethod
def get_fields_and_field_types(cls):
from copy import copy
return copy(cls._fields_and_field_types)
@property
def is_calibrated(self):
"""Message field 'is_calibrated'."""
return self._is_calibrated
@is_calibrated.setter
def is_calibrated(self, value):
if __debug__:
assert \
isinstance(value, bool), \
"The 'is_calibrated' field must be of type 'bool'"
self._is_calibrated = value
class Metaclass_QueryCalibrationState(type):
"""Metaclass of service 'QueryCalibrationState'."""
_TYPE_SUPPORT = None
@classmethod
def __import_type_support__(cls):
try:
from rosidl_generator_py import import_type_support
module = import_type_support('control_msgs')
except ImportError:
import logging
import traceback
logger = logging.getLogger(
'control_msgs.srv.QueryCalibrationState')
logger.debug(
'Failed to import needed modules for type support:\n' +
traceback.format_exc())
else:
cls._TYPE_SUPPORT = module.type_support_srv__srv__query_calibration_state
from control_msgs.srv import _query_calibration_state
if _query_calibration_state.Metaclass_QueryCalibrationState_Request._TYPE_SUPPORT is None:
_query_calibration_state.Metaclass_QueryCalibrationState_Request.__import_type_support__()
if _query_calibration_state.Metaclass_QueryCalibrationState_Response._TYPE_SUPPORT is None:
_query_calibration_state.Metaclass_QueryCalibrationState_Response.__import_type_support__()
class QueryCalibrationState(metaclass=Metaclass_QueryCalibrationState):
from control_msgs.srv._query_calibration_state import QueryCalibrationState_Request as Request
from control_msgs.srv._query_calibration_state import QueryCalibrationState_Response as Response
def __init__(self):
raise NotImplementedError('Service classes can not be instantiated')
| 9,936 | Python | 37.219231 | 134 | 0.598631 |
Toni-SM/semu.robotics.ros2_bridge/src/semu.robotics.ros2_bridge/semu/robotics/ros2_bridge/packages/control_msgs/srv/__init__.py | from control_msgs.srv._query_calibration_state import QueryCalibrationState # noqa: F401
from control_msgs.srv._query_trajectory_state import QueryTrajectoryState # noqa: F401
| 178 | Python | 58.666647 | 89 | 0.820225 |
Toni-SM/semu.robotics.ros2_bridge/src/semu.robotics.ros2_bridge/semu/robotics/ros2_bridge/packages/control_msgs/srv/_query_trajectory_state.py | # generated from rosidl_generator_py/resource/_idl.py.em
# with input from control_msgs:srv/QueryTrajectoryState.idl
# generated code does not contain a copyright notice
# Import statements for member types
import rosidl_parser.definition # noqa: E402, I100
class Metaclass_QueryTrajectoryState_Request(type):
"""Metaclass of message 'QueryTrajectoryState_Request'."""
_CREATE_ROS_MESSAGE = None
_CONVERT_FROM_PY = None
_CONVERT_TO_PY = None
_DESTROY_ROS_MESSAGE = None
_TYPE_SUPPORT = None
__constants = {
}
@classmethod
def __import_type_support__(cls):
try:
from rosidl_generator_py import import_type_support
module = import_type_support('control_msgs')
except ImportError:
import logging
import traceback
logger = logging.getLogger(
'control_msgs.srv.QueryTrajectoryState_Request')
logger.debug(
'Failed to import needed modules for type support:\n' +
traceback.format_exc())
else:
cls._CREATE_ROS_MESSAGE = module.create_ros_message_msg__srv__query_trajectory_state__request
cls._CONVERT_FROM_PY = module.convert_from_py_msg__srv__query_trajectory_state__request
cls._CONVERT_TO_PY = module.convert_to_py_msg__srv__query_trajectory_state__request
cls._TYPE_SUPPORT = module.type_support_msg__srv__query_trajectory_state__request
cls._DESTROY_ROS_MESSAGE = module.destroy_ros_message_msg__srv__query_trajectory_state__request
from builtin_interfaces.msg import Time
if Time.__class__._TYPE_SUPPORT is None:
Time.__class__.__import_type_support__()
@classmethod
def __prepare__(cls, name, bases, **kwargs):
# list constant names here so that they appear in the help text of
# the message class under "Data and other attributes defined here:"
# as well as populate each message instance
return {
}
class QueryTrajectoryState_Request(metaclass=Metaclass_QueryTrajectoryState_Request):
"""Message class 'QueryTrajectoryState_Request'."""
__slots__ = [
'_time',
]
_fields_and_field_types = {
'time': 'builtin_interfaces/Time',
}
SLOT_TYPES = (
rosidl_parser.definition.NamespacedType(['builtin_interfaces', 'msg'], 'Time'), # noqa: E501
)
def __init__(self, **kwargs):
assert all('_' + key in self.__slots__ for key in kwargs.keys()), \
'Invalid arguments passed to constructor: %s' % \
', '.join(sorted(k for k in kwargs.keys() if '_' + k not in self.__slots__))
from builtin_interfaces.msg import Time
self.time = kwargs.get('time', Time())
def __repr__(self):
typename = self.__class__.__module__.split('.')
typename.pop()
typename.append(self.__class__.__name__)
args = []
for s, t in zip(self.__slots__, self.SLOT_TYPES):
field = getattr(self, s)
fieldstr = repr(field)
# We use Python array type for fields that can be directly stored
# in them, and "normal" sequences for everything else. If it is
# a type that we store in an array, strip off the 'array' portion.
if (
isinstance(t, rosidl_parser.definition.AbstractSequence) and
isinstance(t.value_type, rosidl_parser.definition.BasicType) and
t.value_type.typename in ['float', 'double', 'int8', 'uint8', 'int16', 'uint16', 'int32', 'uint32', 'int64', 'uint64']
):
if len(field) == 0:
fieldstr = '[]'
else:
assert fieldstr.startswith('array(')
prefix = "array('X', "
suffix = ')'
fieldstr = fieldstr[len(prefix):-len(suffix)]
args.append(s[1:] + '=' + fieldstr)
return '%s(%s)' % ('.'.join(typename), ', '.join(args))
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
if self.time != other.time:
return False
return True
@classmethod
def get_fields_and_field_types(cls):
from copy import copy
return copy(cls._fields_and_field_types)
@property
def time(self):
"""Message field 'time'."""
return self._time
@time.setter
def time(self, value):
if __debug__:
from builtin_interfaces.msg import Time
assert \
isinstance(value, Time), \
"The 'time' field must be a sub message of type 'Time'"
self._time = value
# Import statements for member types
# Member 'position'
# Member 'velocity'
# Member 'acceleration'
import array # noqa: E402, I100
# already imported above
# import rosidl_parser.definition
class Metaclass_QueryTrajectoryState_Response(type):
"""Metaclass of message 'QueryTrajectoryState_Response'."""
_CREATE_ROS_MESSAGE = None
_CONVERT_FROM_PY = None
_CONVERT_TO_PY = None
_DESTROY_ROS_MESSAGE = None
_TYPE_SUPPORT = None
__constants = {
}
@classmethod
def __import_type_support__(cls):
try:
from rosidl_generator_py import import_type_support
module = import_type_support('control_msgs')
except ImportError:
import logging
import traceback
logger = logging.getLogger(
'control_msgs.srv.QueryTrajectoryState_Response')
logger.debug(
'Failed to import needed modules for type support:\n' +
traceback.format_exc())
else:
cls._CREATE_ROS_MESSAGE = module.create_ros_message_msg__srv__query_trajectory_state__response
cls._CONVERT_FROM_PY = module.convert_from_py_msg__srv__query_trajectory_state__response
cls._CONVERT_TO_PY = module.convert_to_py_msg__srv__query_trajectory_state__response
cls._TYPE_SUPPORT = module.type_support_msg__srv__query_trajectory_state__response
cls._DESTROY_ROS_MESSAGE = module.destroy_ros_message_msg__srv__query_trajectory_state__response
@classmethod
def __prepare__(cls, name, bases, **kwargs):
# list constant names here so that they appear in the help text of
# the message class under "Data and other attributes defined here:"
# as well as populate each message instance
return {
}
class QueryTrajectoryState_Response(metaclass=Metaclass_QueryTrajectoryState_Response):
"""Message class 'QueryTrajectoryState_Response'."""
__slots__ = [
'_success',
'_message',
'_name',
'_position',
'_velocity',
'_acceleration',
]
_fields_and_field_types = {
'success': 'boolean',
'message': 'string',
'name': 'sequence<string>',
'position': 'sequence<double>',
'velocity': 'sequence<double>',
'acceleration': 'sequence<double>',
}
SLOT_TYPES = (
rosidl_parser.definition.BasicType('boolean'), # noqa: E501
rosidl_parser.definition.UnboundedString(), # noqa: E501
rosidl_parser.definition.UnboundedSequence(rosidl_parser.definition.UnboundedString()), # noqa: E501
rosidl_parser.definition.UnboundedSequence(rosidl_parser.definition.BasicType('double')), # noqa: E501
rosidl_parser.definition.UnboundedSequence(rosidl_parser.definition.BasicType('double')), # noqa: E501
rosidl_parser.definition.UnboundedSequence(rosidl_parser.definition.BasicType('double')), # noqa: E501
)
def __init__(self, **kwargs):
assert all('_' + key in self.__slots__ for key in kwargs.keys()), \
'Invalid arguments passed to constructor: %s' % \
', '.join(sorted(k for k in kwargs.keys() if '_' + k not in self.__slots__))
self.success = kwargs.get('success', bool())
self.message = kwargs.get('message', str())
self.name = kwargs.get('name', [])
self.position = array.array('d', kwargs.get('position', []))
self.velocity = array.array('d', kwargs.get('velocity', []))
self.acceleration = array.array('d', kwargs.get('acceleration', []))
def __repr__(self):
typename = self.__class__.__module__.split('.')
typename.pop()
typename.append(self.__class__.__name__)
args = []
for s, t in zip(self.__slots__, self.SLOT_TYPES):
field = getattr(self, s)
fieldstr = repr(field)
# We use Python array type for fields that can be directly stored
# in them, and "normal" sequences for everything else. If it is
# a type that we store in an array, strip off the 'array' portion.
if (
isinstance(t, rosidl_parser.definition.AbstractSequence) and
isinstance(t.value_type, rosidl_parser.definition.BasicType) and
t.value_type.typename in ['float', 'double', 'int8', 'uint8', 'int16', 'uint16', 'int32', 'uint32', 'int64', 'uint64']
):
if len(field) == 0:
fieldstr = '[]'
else:
assert fieldstr.startswith('array(')
prefix = "array('X', "
suffix = ')'
fieldstr = fieldstr[len(prefix):-len(suffix)]
args.append(s[1:] + '=' + fieldstr)
return '%s(%s)' % ('.'.join(typename), ', '.join(args))
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
if self.success != other.success:
return False
if self.message != other.message:
return False
if self.name != other.name:
return False
if self.position != other.position:
return False
if self.velocity != other.velocity:
return False
if self.acceleration != other.acceleration:
return False
return True
@classmethod
def get_fields_and_field_types(cls):
from copy import copy
return copy(cls._fields_and_field_types)
@property
def success(self):
"""Message field 'success'."""
return self._success
@success.setter
def success(self, value):
if __debug__:
assert \
isinstance(value, bool), \
"The 'success' field must be of type 'bool'"
self._success = value
@property
def message(self):
"""Message field 'message'."""
return self._message
@message.setter
def message(self, value):
if __debug__:
assert \
isinstance(value, str), \
"The 'message' field must be of type 'str'"
self._message = value
@property
def name(self):
"""Message field 'name'."""
return self._name
@name.setter
def name(self, value):
if __debug__:
from collections.abc import Sequence
from collections.abc import Set
from collections import UserList
from collections import UserString
assert \
((isinstance(value, Sequence) or
isinstance(value, Set) or
isinstance(value, UserList)) and
not isinstance(value, str) and
not isinstance(value, UserString) and
all(isinstance(v, str) for v in value) and
True), \
"The 'name' field must be a set or sequence and each value of type 'str'"
self._name = value
@property
def position(self):
"""Message field 'position'."""
return self._position
@position.setter
def position(self, value):
if isinstance(value, array.array):
assert value.typecode == 'd', \
"The 'position' array.array() must have the type code of 'd'"
self._position = value
return
if __debug__:
from collections.abc import Sequence
from collections.abc import Set
from collections import UserList
from collections import UserString
assert \
((isinstance(value, Sequence) or
isinstance(value, Set) or
isinstance(value, UserList)) and
not isinstance(value, str) and
not isinstance(value, UserString) and
all(isinstance(v, float) for v in value) and
True), \
"The 'position' field must be a set or sequence and each value of type 'float'"
self._position = array.array('d', value)
@property
def velocity(self):
"""Message field 'velocity'."""
return self._velocity
@velocity.setter
def velocity(self, value):
if isinstance(value, array.array):
assert value.typecode == 'd', \
"The 'velocity' array.array() must have the type code of 'd'"
self._velocity = value
return
if __debug__:
from collections.abc import Sequence
from collections.abc import Set
from collections import UserList
from collections import UserString
assert \
((isinstance(value, Sequence) or
isinstance(value, Set) or
isinstance(value, UserList)) and
not isinstance(value, str) and
not isinstance(value, UserString) and
all(isinstance(v, float) for v in value) and
True), \
"The 'velocity' field must be a set or sequence and each value of type 'float'"
self._velocity = array.array('d', value)
@property
def acceleration(self):
"""Message field 'acceleration'."""
return self._acceleration
@acceleration.setter
def acceleration(self, value):
if isinstance(value, array.array):
assert value.typecode == 'd', \
"The 'acceleration' array.array() must have the type code of 'd'"
self._acceleration = value
return
if __debug__:
from collections.abc import Sequence
from collections.abc import Set
from collections import UserList
from collections import UserString
assert \
((isinstance(value, Sequence) or
isinstance(value, Set) or
isinstance(value, UserList)) and
not isinstance(value, str) and
not isinstance(value, UserString) and
all(isinstance(v, float) for v in value) and
True), \
"The 'acceleration' field must be a set or sequence and each value of type 'float'"
self._acceleration = array.array('d', value)
class Metaclass_QueryTrajectoryState(type):
"""Metaclass of service 'QueryTrajectoryState'."""
_TYPE_SUPPORT = None
@classmethod
def __import_type_support__(cls):
try:
from rosidl_generator_py import import_type_support
module = import_type_support('control_msgs')
except ImportError:
import logging
import traceback
logger = logging.getLogger(
'control_msgs.srv.QueryTrajectoryState')
logger.debug(
'Failed to import needed modules for type support:\n' +
traceback.format_exc())
else:
cls._TYPE_SUPPORT = module.type_support_srv__srv__query_trajectory_state
from control_msgs.srv import _query_trajectory_state
if _query_trajectory_state.Metaclass_QueryTrajectoryState_Request._TYPE_SUPPORT is None:
_query_trajectory_state.Metaclass_QueryTrajectoryState_Request.__import_type_support__()
if _query_trajectory_state.Metaclass_QueryTrajectoryState_Response._TYPE_SUPPORT is None:
_query_trajectory_state.Metaclass_QueryTrajectoryState_Response.__import_type_support__()
class QueryTrajectoryState(metaclass=Metaclass_QueryTrajectoryState):
from control_msgs.srv._query_trajectory_state import QueryTrajectoryState_Request as Request
from control_msgs.srv._query_trajectory_state import QueryTrajectoryState_Response as Response
def __init__(self):
raise NotImplementedError('Service classes can not be instantiated')
| 16,687 | Python | 36.927273 | 134 | 0.579613 |
Toni-SM/semu.robotics.ros2_bridge/src/semu.robotics.ros2_bridge/semu/robotics/ros2_bridge/packages/control_msgs/srv/_query_calibration_state_s.c | // generated from rosidl_generator_py/resource/_idl_support.c.em
// with input from control_msgs:srv/QueryCalibrationState.idl
// generated code does not contain a copyright notice
#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION
#include <Python.h>
#include <stdbool.h>
#ifndef _WIN32
# pragma GCC diagnostic push
# pragma GCC diagnostic ignored "-Wunused-function"
#endif
#include "numpy/ndarrayobject.h"
#ifndef _WIN32
# pragma GCC diagnostic pop
#endif
#include "rosidl_runtime_c/visibility_control.h"
#include "control_msgs/srv/detail/query_calibration_state__struct.h"
#include "control_msgs/srv/detail/query_calibration_state__functions.h"
ROSIDL_GENERATOR_C_EXPORT
bool control_msgs__srv__query_calibration_state__request__convert_from_py(PyObject * _pymsg, void * _ros_message)
{
// check that the passed message is of the expected Python class
{
char full_classname_dest[72];
{
char * class_name = NULL;
char * module_name = NULL;
{
PyObject * class_attr = PyObject_GetAttrString(_pymsg, "__class__");
if (class_attr) {
PyObject * name_attr = PyObject_GetAttrString(class_attr, "__name__");
if (name_attr) {
class_name = (char *)PyUnicode_1BYTE_DATA(name_attr);
Py_DECREF(name_attr);
}
PyObject * module_attr = PyObject_GetAttrString(class_attr, "__module__");
if (module_attr) {
module_name = (char *)PyUnicode_1BYTE_DATA(module_attr);
Py_DECREF(module_attr);
}
Py_DECREF(class_attr);
}
}
if (!class_name || !module_name) {
return false;
}
snprintf(full_classname_dest, sizeof(full_classname_dest), "%s.%s", module_name, class_name);
}
assert(strncmp("control_msgs.srv._query_calibration_state.QueryCalibrationState_Request", full_classname_dest, 71) == 0);
}
control_msgs__srv__QueryCalibrationState_Request * ros_message = _ros_message;
ros_message->structure_needs_at_least_one_member = 0;
return true;
}
ROSIDL_GENERATOR_C_EXPORT
PyObject * control_msgs__srv__query_calibration_state__request__convert_to_py(void * raw_ros_message)
{
/* NOTE(esteve): Call constructor of QueryCalibrationState_Request */
PyObject * _pymessage = NULL;
{
PyObject * pymessage_module = PyImport_ImportModule("control_msgs.srv._query_calibration_state");
assert(pymessage_module);
PyObject * pymessage_class = PyObject_GetAttrString(pymessage_module, "QueryCalibrationState_Request");
assert(pymessage_class);
Py_DECREF(pymessage_module);
_pymessage = PyObject_CallObject(pymessage_class, NULL);
Py_DECREF(pymessage_class);
if (!_pymessage) {
return NULL;
}
}
(void)raw_ros_message;
// ownership of _pymessage is transferred to the caller
return _pymessage;
}
#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION
// already included above
// #include <Python.h>
// already included above
// #include <stdbool.h>
// already included above
// #include "numpy/ndarrayobject.h"
// already included above
// #include "rosidl_runtime_c/visibility_control.h"
// already included above
// #include "control_msgs/srv/detail/query_calibration_state__struct.h"
// already included above
// #include "control_msgs/srv/detail/query_calibration_state__functions.h"
ROSIDL_GENERATOR_C_EXPORT
bool control_msgs__srv__query_calibration_state__response__convert_from_py(PyObject * _pymsg, void * _ros_message)
{
// check that the passed message is of the expected Python class
{
char full_classname_dest[73];
{
char * class_name = NULL;
char * module_name = NULL;
{
PyObject * class_attr = PyObject_GetAttrString(_pymsg, "__class__");
if (class_attr) {
PyObject * name_attr = PyObject_GetAttrString(class_attr, "__name__");
if (name_attr) {
class_name = (char *)PyUnicode_1BYTE_DATA(name_attr);
Py_DECREF(name_attr);
}
PyObject * module_attr = PyObject_GetAttrString(class_attr, "__module__");
if (module_attr) {
module_name = (char *)PyUnicode_1BYTE_DATA(module_attr);
Py_DECREF(module_attr);
}
Py_DECREF(class_attr);
}
}
if (!class_name || !module_name) {
return false;
}
snprintf(full_classname_dest, sizeof(full_classname_dest), "%s.%s", module_name, class_name);
}
assert(strncmp("control_msgs.srv._query_calibration_state.QueryCalibrationState_Response", full_classname_dest, 72) == 0);
}
control_msgs__srv__QueryCalibrationState_Response * ros_message = _ros_message;
{ // is_calibrated
PyObject * field = PyObject_GetAttrString(_pymsg, "is_calibrated");
if (!field) {
return false;
}
assert(PyBool_Check(field));
ros_message->is_calibrated = (Py_True == field);
Py_DECREF(field);
}
return true;
}
ROSIDL_GENERATOR_C_EXPORT
PyObject * control_msgs__srv__query_calibration_state__response__convert_to_py(void * raw_ros_message)
{
/* NOTE(esteve): Call constructor of QueryCalibrationState_Response */
PyObject * _pymessage = NULL;
{
PyObject * pymessage_module = PyImport_ImportModule("control_msgs.srv._query_calibration_state");
assert(pymessage_module);
PyObject * pymessage_class = PyObject_GetAttrString(pymessage_module, "QueryCalibrationState_Response");
assert(pymessage_class);
Py_DECREF(pymessage_module);
_pymessage = PyObject_CallObject(pymessage_class, NULL);
Py_DECREF(pymessage_class);
if (!_pymessage) {
return NULL;
}
}
control_msgs__srv__QueryCalibrationState_Response * ros_message = (control_msgs__srv__QueryCalibrationState_Response *)raw_ros_message;
{ // is_calibrated
PyObject * field = NULL;
field = PyBool_FromLong(ros_message->is_calibrated ? 1 : 0);
{
int rc = PyObject_SetAttrString(_pymessage, "is_calibrated", field);
Py_DECREF(field);
if (rc) {
return NULL;
}
}
}
// ownership of _pymessage is transferred to the caller
return _pymessage;
}
| 6,102 | C | 33.874286 | 137 | 0.6647 |
Toni-SM/semu.robotics.ros2_bridge/src/semu.robotics.ros2_bridge/semu/robotics/ros2_bridge/packages/control_msgs/action/_joint_trajectory_s.c | // generated from rosidl_generator_py/resource/_idl_support.c.em
// with input from control_msgs:action/JointTrajectory.idl
// generated code does not contain a copyright notice
#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION
#include <Python.h>
#include <stdbool.h>
#ifndef _WIN32
# pragma GCC diagnostic push
# pragma GCC diagnostic ignored "-Wunused-function"
#endif
#include "numpy/ndarrayobject.h"
#ifndef _WIN32
# pragma GCC diagnostic pop
#endif
#include "rosidl_runtime_c/visibility_control.h"
#include "control_msgs/action/detail/joint_trajectory__struct.h"
#include "control_msgs/action/detail/joint_trajectory__functions.h"
ROSIDL_GENERATOR_C_IMPORT
bool trajectory_msgs__msg__joint_trajectory__convert_from_py(PyObject * _pymsg, void * _ros_message);
ROSIDL_GENERATOR_C_IMPORT
PyObject * trajectory_msgs__msg__joint_trajectory__convert_to_py(void * raw_ros_message);
ROSIDL_GENERATOR_C_EXPORT
bool control_msgs__action__joint_trajectory__goal__convert_from_py(PyObject * _pymsg, void * _ros_message)
{
// check that the passed message is of the expected Python class
{
char full_classname_dest[59];
{
char * class_name = NULL;
char * module_name = NULL;
{
PyObject * class_attr = PyObject_GetAttrString(_pymsg, "__class__");
if (class_attr) {
PyObject * name_attr = PyObject_GetAttrString(class_attr, "__name__");
if (name_attr) {
class_name = (char *)PyUnicode_1BYTE_DATA(name_attr);
Py_DECREF(name_attr);
}
PyObject * module_attr = PyObject_GetAttrString(class_attr, "__module__");
if (module_attr) {
module_name = (char *)PyUnicode_1BYTE_DATA(module_attr);
Py_DECREF(module_attr);
}
Py_DECREF(class_attr);
}
}
if (!class_name || !module_name) {
return false;
}
snprintf(full_classname_dest, sizeof(full_classname_dest), "%s.%s", module_name, class_name);
}
assert(strncmp("control_msgs.action._joint_trajectory.JointTrajectory_Goal", full_classname_dest, 58) == 0);
}
control_msgs__action__JointTrajectory_Goal * ros_message = _ros_message;
{ // trajectory
PyObject * field = PyObject_GetAttrString(_pymsg, "trajectory");
if (!field) {
return false;
}
if (!trajectory_msgs__msg__joint_trajectory__convert_from_py(field, &ros_message->trajectory)) {
Py_DECREF(field);
return false;
}
Py_DECREF(field);
}
return true;
}
ROSIDL_GENERATOR_C_EXPORT
PyObject * control_msgs__action__joint_trajectory__goal__convert_to_py(void * raw_ros_message)
{
/* NOTE(esteve): Call constructor of JointTrajectory_Goal */
PyObject * _pymessage = NULL;
{
PyObject * pymessage_module = PyImport_ImportModule("control_msgs.action._joint_trajectory");
assert(pymessage_module);
PyObject * pymessage_class = PyObject_GetAttrString(pymessage_module, "JointTrajectory_Goal");
assert(pymessage_class);
Py_DECREF(pymessage_module);
_pymessage = PyObject_CallObject(pymessage_class, NULL);
Py_DECREF(pymessage_class);
if (!_pymessage) {
return NULL;
}
}
control_msgs__action__JointTrajectory_Goal * ros_message = (control_msgs__action__JointTrajectory_Goal *)raw_ros_message;
{ // trajectory
PyObject * field = NULL;
field = trajectory_msgs__msg__joint_trajectory__convert_to_py(&ros_message->trajectory);
if (!field) {
return NULL;
}
{
int rc = PyObject_SetAttrString(_pymessage, "trajectory", field);
Py_DECREF(field);
if (rc) {
return NULL;
}
}
}
// ownership of _pymessage is transferred to the caller
return _pymessage;
}
#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION
// already included above
// #include <Python.h>
// already included above
// #include <stdbool.h>
// already included above
// #include "numpy/ndarrayobject.h"
// already included above
// #include "rosidl_runtime_c/visibility_control.h"
// already included above
// #include "control_msgs/action/detail/joint_trajectory__struct.h"
// already included above
// #include "control_msgs/action/detail/joint_trajectory__functions.h"
ROSIDL_GENERATOR_C_EXPORT
bool control_msgs__action__joint_trajectory__result__convert_from_py(PyObject * _pymsg, void * _ros_message)
{
// check that the passed message is of the expected Python class
{
char full_classname_dest[61];
{
char * class_name = NULL;
char * module_name = NULL;
{
PyObject * class_attr = PyObject_GetAttrString(_pymsg, "__class__");
if (class_attr) {
PyObject * name_attr = PyObject_GetAttrString(class_attr, "__name__");
if (name_attr) {
class_name = (char *)PyUnicode_1BYTE_DATA(name_attr);
Py_DECREF(name_attr);
}
PyObject * module_attr = PyObject_GetAttrString(class_attr, "__module__");
if (module_attr) {
module_name = (char *)PyUnicode_1BYTE_DATA(module_attr);
Py_DECREF(module_attr);
}
Py_DECREF(class_attr);
}
}
if (!class_name || !module_name) {
return false;
}
snprintf(full_classname_dest, sizeof(full_classname_dest), "%s.%s", module_name, class_name);
}
assert(strncmp("control_msgs.action._joint_trajectory.JointTrajectory_Result", full_classname_dest, 60) == 0);
}
control_msgs__action__JointTrajectory_Result * ros_message = _ros_message;
ros_message->structure_needs_at_least_one_member = 0;
return true;
}
ROSIDL_GENERATOR_C_EXPORT
PyObject * control_msgs__action__joint_trajectory__result__convert_to_py(void * raw_ros_message)
{
/* NOTE(esteve): Call constructor of JointTrajectory_Result */
PyObject * _pymessage = NULL;
{
PyObject * pymessage_module = PyImport_ImportModule("control_msgs.action._joint_trajectory");
assert(pymessage_module);
PyObject * pymessage_class = PyObject_GetAttrString(pymessage_module, "JointTrajectory_Result");
assert(pymessage_class);
Py_DECREF(pymessage_module);
_pymessage = PyObject_CallObject(pymessage_class, NULL);
Py_DECREF(pymessage_class);
if (!_pymessage) {
return NULL;
}
}
(void)raw_ros_message;
// ownership of _pymessage is transferred to the caller
return _pymessage;
}
#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION
// already included above
// #include <Python.h>
// already included above
// #include <stdbool.h>
// already included above
// #include "numpy/ndarrayobject.h"
// already included above
// #include "rosidl_runtime_c/visibility_control.h"
// already included above
// #include "control_msgs/action/detail/joint_trajectory__struct.h"
// already included above
// #include "control_msgs/action/detail/joint_trajectory__functions.h"
ROSIDL_GENERATOR_C_EXPORT
bool control_msgs__action__joint_trajectory__feedback__convert_from_py(PyObject * _pymsg, void * _ros_message)
{
// check that the passed message is of the expected Python class
{
char full_classname_dest[63];
{
char * class_name = NULL;
char * module_name = NULL;
{
PyObject * class_attr = PyObject_GetAttrString(_pymsg, "__class__");
if (class_attr) {
PyObject * name_attr = PyObject_GetAttrString(class_attr, "__name__");
if (name_attr) {
class_name = (char *)PyUnicode_1BYTE_DATA(name_attr);
Py_DECREF(name_attr);
}
PyObject * module_attr = PyObject_GetAttrString(class_attr, "__module__");
if (module_attr) {
module_name = (char *)PyUnicode_1BYTE_DATA(module_attr);
Py_DECREF(module_attr);
}
Py_DECREF(class_attr);
}
}
if (!class_name || !module_name) {
return false;
}
snprintf(full_classname_dest, sizeof(full_classname_dest), "%s.%s", module_name, class_name);
}
assert(strncmp("control_msgs.action._joint_trajectory.JointTrajectory_Feedback", full_classname_dest, 62) == 0);
}
control_msgs__action__JointTrajectory_Feedback * ros_message = _ros_message;
ros_message->structure_needs_at_least_one_member = 0;
return true;
}
ROSIDL_GENERATOR_C_EXPORT
PyObject * control_msgs__action__joint_trajectory__feedback__convert_to_py(void * raw_ros_message)
{
/* NOTE(esteve): Call constructor of JointTrajectory_Feedback */
PyObject * _pymessage = NULL;
{
PyObject * pymessage_module = PyImport_ImportModule("control_msgs.action._joint_trajectory");
assert(pymessage_module);
PyObject * pymessage_class = PyObject_GetAttrString(pymessage_module, "JointTrajectory_Feedback");
assert(pymessage_class);
Py_DECREF(pymessage_module);
_pymessage = PyObject_CallObject(pymessage_class, NULL);
Py_DECREF(pymessage_class);
if (!_pymessage) {
return NULL;
}
}
(void)raw_ros_message;
// ownership of _pymessage is transferred to the caller
return _pymessage;
}
#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION
// already included above
// #include <Python.h>
// already included above
// #include <stdbool.h>
// already included above
// #include "numpy/ndarrayobject.h"
// already included above
// #include "rosidl_runtime_c/visibility_control.h"
// already included above
// #include "control_msgs/action/detail/joint_trajectory__struct.h"
// already included above
// #include "control_msgs/action/detail/joint_trajectory__functions.h"
ROSIDL_GENERATOR_C_IMPORT
bool unique_identifier_msgs__msg__uuid__convert_from_py(PyObject * _pymsg, void * _ros_message);
ROSIDL_GENERATOR_C_IMPORT
PyObject * unique_identifier_msgs__msg__uuid__convert_to_py(void * raw_ros_message);
bool control_msgs__action__joint_trajectory__goal__convert_from_py(PyObject * _pymsg, void * _ros_message);
PyObject * control_msgs__action__joint_trajectory__goal__convert_to_py(void * raw_ros_message);
ROSIDL_GENERATOR_C_EXPORT
bool control_msgs__action__joint_trajectory__send_goal__request__convert_from_py(PyObject * _pymsg, void * _ros_message)
{
// check that the passed message is of the expected Python class
{
char full_classname_dest[71];
{
char * class_name = NULL;
char * module_name = NULL;
{
PyObject * class_attr = PyObject_GetAttrString(_pymsg, "__class__");
if (class_attr) {
PyObject * name_attr = PyObject_GetAttrString(class_attr, "__name__");
if (name_attr) {
class_name = (char *)PyUnicode_1BYTE_DATA(name_attr);
Py_DECREF(name_attr);
}
PyObject * module_attr = PyObject_GetAttrString(class_attr, "__module__");
if (module_attr) {
module_name = (char *)PyUnicode_1BYTE_DATA(module_attr);
Py_DECREF(module_attr);
}
Py_DECREF(class_attr);
}
}
if (!class_name || !module_name) {
return false;
}
snprintf(full_classname_dest, sizeof(full_classname_dest), "%s.%s", module_name, class_name);
}
assert(strncmp("control_msgs.action._joint_trajectory.JointTrajectory_SendGoal_Request", full_classname_dest, 70) == 0);
}
control_msgs__action__JointTrajectory_SendGoal_Request * ros_message = _ros_message;
{ // goal_id
PyObject * field = PyObject_GetAttrString(_pymsg, "goal_id");
if (!field) {
return false;
}
if (!unique_identifier_msgs__msg__uuid__convert_from_py(field, &ros_message->goal_id)) {
Py_DECREF(field);
return false;
}
Py_DECREF(field);
}
{ // goal
PyObject * field = PyObject_GetAttrString(_pymsg, "goal");
if (!field) {
return false;
}
if (!control_msgs__action__joint_trajectory__goal__convert_from_py(field, &ros_message->goal)) {
Py_DECREF(field);
return false;
}
Py_DECREF(field);
}
return true;
}
ROSIDL_GENERATOR_C_EXPORT
PyObject * control_msgs__action__joint_trajectory__send_goal__request__convert_to_py(void * raw_ros_message)
{
/* NOTE(esteve): Call constructor of JointTrajectory_SendGoal_Request */
PyObject * _pymessage = NULL;
{
PyObject * pymessage_module = PyImport_ImportModule("control_msgs.action._joint_trajectory");
assert(pymessage_module);
PyObject * pymessage_class = PyObject_GetAttrString(pymessage_module, "JointTrajectory_SendGoal_Request");
assert(pymessage_class);
Py_DECREF(pymessage_module);
_pymessage = PyObject_CallObject(pymessage_class, NULL);
Py_DECREF(pymessage_class);
if (!_pymessage) {
return NULL;
}
}
control_msgs__action__JointTrajectory_SendGoal_Request * ros_message = (control_msgs__action__JointTrajectory_SendGoal_Request *)raw_ros_message;
{ // goal_id
PyObject * field = NULL;
field = unique_identifier_msgs__msg__uuid__convert_to_py(&ros_message->goal_id);
if (!field) {
return NULL;
}
{
int rc = PyObject_SetAttrString(_pymessage, "goal_id", field);
Py_DECREF(field);
if (rc) {
return NULL;
}
}
}
{ // goal
PyObject * field = NULL;
field = control_msgs__action__joint_trajectory__goal__convert_to_py(&ros_message->goal);
if (!field) {
return NULL;
}
{
int rc = PyObject_SetAttrString(_pymessage, "goal", field);
Py_DECREF(field);
if (rc) {
return NULL;
}
}
}
// ownership of _pymessage is transferred to the caller
return _pymessage;
}
#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION
// already included above
// #include <Python.h>
// already included above
// #include <stdbool.h>
// already included above
// #include "numpy/ndarrayobject.h"
// already included above
// #include "rosidl_runtime_c/visibility_control.h"
// already included above
// #include "control_msgs/action/detail/joint_trajectory__struct.h"
// already included above
// #include "control_msgs/action/detail/joint_trajectory__functions.h"
ROSIDL_GENERATOR_C_IMPORT
bool builtin_interfaces__msg__time__convert_from_py(PyObject * _pymsg, void * _ros_message);
ROSIDL_GENERATOR_C_IMPORT
PyObject * builtin_interfaces__msg__time__convert_to_py(void * raw_ros_message);
ROSIDL_GENERATOR_C_EXPORT
bool control_msgs__action__joint_trajectory__send_goal__response__convert_from_py(PyObject * _pymsg, void * _ros_message)
{
// check that the passed message is of the expected Python class
{
char full_classname_dest[72];
{
char * class_name = NULL;
char * module_name = NULL;
{
PyObject * class_attr = PyObject_GetAttrString(_pymsg, "__class__");
if (class_attr) {
PyObject * name_attr = PyObject_GetAttrString(class_attr, "__name__");
if (name_attr) {
class_name = (char *)PyUnicode_1BYTE_DATA(name_attr);
Py_DECREF(name_attr);
}
PyObject * module_attr = PyObject_GetAttrString(class_attr, "__module__");
if (module_attr) {
module_name = (char *)PyUnicode_1BYTE_DATA(module_attr);
Py_DECREF(module_attr);
}
Py_DECREF(class_attr);
}
}
if (!class_name || !module_name) {
return false;
}
snprintf(full_classname_dest, sizeof(full_classname_dest), "%s.%s", module_name, class_name);
}
assert(strncmp("control_msgs.action._joint_trajectory.JointTrajectory_SendGoal_Response", full_classname_dest, 71) == 0);
}
control_msgs__action__JointTrajectory_SendGoal_Response * ros_message = _ros_message;
{ // accepted
PyObject * field = PyObject_GetAttrString(_pymsg, "accepted");
if (!field) {
return false;
}
assert(PyBool_Check(field));
ros_message->accepted = (Py_True == field);
Py_DECREF(field);
}
{ // stamp
PyObject * field = PyObject_GetAttrString(_pymsg, "stamp");
if (!field) {
return false;
}
if (!builtin_interfaces__msg__time__convert_from_py(field, &ros_message->stamp)) {
Py_DECREF(field);
return false;
}
Py_DECREF(field);
}
return true;
}
ROSIDL_GENERATOR_C_EXPORT
PyObject * control_msgs__action__joint_trajectory__send_goal__response__convert_to_py(void * raw_ros_message)
{
/* NOTE(esteve): Call constructor of JointTrajectory_SendGoal_Response */
PyObject * _pymessage = NULL;
{
PyObject * pymessage_module = PyImport_ImportModule("control_msgs.action._joint_trajectory");
assert(pymessage_module);
PyObject * pymessage_class = PyObject_GetAttrString(pymessage_module, "JointTrajectory_SendGoal_Response");
assert(pymessage_class);
Py_DECREF(pymessage_module);
_pymessage = PyObject_CallObject(pymessage_class, NULL);
Py_DECREF(pymessage_class);
if (!_pymessage) {
return NULL;
}
}
control_msgs__action__JointTrajectory_SendGoal_Response * ros_message = (control_msgs__action__JointTrajectory_SendGoal_Response *)raw_ros_message;
{ // accepted
PyObject * field = NULL;
field = PyBool_FromLong(ros_message->accepted ? 1 : 0);
{
int rc = PyObject_SetAttrString(_pymessage, "accepted", field);
Py_DECREF(field);
if (rc) {
return NULL;
}
}
}
{ // stamp
PyObject * field = NULL;
field = builtin_interfaces__msg__time__convert_to_py(&ros_message->stamp);
if (!field) {
return NULL;
}
{
int rc = PyObject_SetAttrString(_pymessage, "stamp", field);
Py_DECREF(field);
if (rc) {
return NULL;
}
}
}
// ownership of _pymessage is transferred to the caller
return _pymessage;
}
#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION
// already included above
// #include <Python.h>
// already included above
// #include <stdbool.h>
// already included above
// #include "numpy/ndarrayobject.h"
// already included above
// #include "rosidl_runtime_c/visibility_control.h"
// already included above
// #include "control_msgs/action/detail/joint_trajectory__struct.h"
// already included above
// #include "control_msgs/action/detail/joint_trajectory__functions.h"
ROSIDL_GENERATOR_C_IMPORT
bool unique_identifier_msgs__msg__uuid__convert_from_py(PyObject * _pymsg, void * _ros_message);
ROSIDL_GENERATOR_C_IMPORT
PyObject * unique_identifier_msgs__msg__uuid__convert_to_py(void * raw_ros_message);
ROSIDL_GENERATOR_C_EXPORT
bool control_msgs__action__joint_trajectory__get_result__request__convert_from_py(PyObject * _pymsg, void * _ros_message)
{
// check that the passed message is of the expected Python class
{
char full_classname_dest[72];
{
char * class_name = NULL;
char * module_name = NULL;
{
PyObject * class_attr = PyObject_GetAttrString(_pymsg, "__class__");
if (class_attr) {
PyObject * name_attr = PyObject_GetAttrString(class_attr, "__name__");
if (name_attr) {
class_name = (char *)PyUnicode_1BYTE_DATA(name_attr);
Py_DECREF(name_attr);
}
PyObject * module_attr = PyObject_GetAttrString(class_attr, "__module__");
if (module_attr) {
module_name = (char *)PyUnicode_1BYTE_DATA(module_attr);
Py_DECREF(module_attr);
}
Py_DECREF(class_attr);
}
}
if (!class_name || !module_name) {
return false;
}
snprintf(full_classname_dest, sizeof(full_classname_dest), "%s.%s", module_name, class_name);
}
assert(strncmp("control_msgs.action._joint_trajectory.JointTrajectory_GetResult_Request", full_classname_dest, 71) == 0);
}
control_msgs__action__JointTrajectory_GetResult_Request * ros_message = _ros_message;
{ // goal_id
PyObject * field = PyObject_GetAttrString(_pymsg, "goal_id");
if (!field) {
return false;
}
if (!unique_identifier_msgs__msg__uuid__convert_from_py(field, &ros_message->goal_id)) {
Py_DECREF(field);
return false;
}
Py_DECREF(field);
}
return true;
}
ROSIDL_GENERATOR_C_EXPORT
PyObject * control_msgs__action__joint_trajectory__get_result__request__convert_to_py(void * raw_ros_message)
{
/* NOTE(esteve): Call constructor of JointTrajectory_GetResult_Request */
PyObject * _pymessage = NULL;
{
PyObject * pymessage_module = PyImport_ImportModule("control_msgs.action._joint_trajectory");
assert(pymessage_module);
PyObject * pymessage_class = PyObject_GetAttrString(pymessage_module, "JointTrajectory_GetResult_Request");
assert(pymessage_class);
Py_DECREF(pymessage_module);
_pymessage = PyObject_CallObject(pymessage_class, NULL);
Py_DECREF(pymessage_class);
if (!_pymessage) {
return NULL;
}
}
control_msgs__action__JointTrajectory_GetResult_Request * ros_message = (control_msgs__action__JointTrajectory_GetResult_Request *)raw_ros_message;
{ // goal_id
PyObject * field = NULL;
field = unique_identifier_msgs__msg__uuid__convert_to_py(&ros_message->goal_id);
if (!field) {
return NULL;
}
{
int rc = PyObject_SetAttrString(_pymessage, "goal_id", field);
Py_DECREF(field);
if (rc) {
return NULL;
}
}
}
// ownership of _pymessage is transferred to the caller
return _pymessage;
}
#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION
// already included above
// #include <Python.h>
// already included above
// #include <stdbool.h>
// already included above
// #include "numpy/ndarrayobject.h"
// already included above
// #include "rosidl_runtime_c/visibility_control.h"
// already included above
// #include "control_msgs/action/detail/joint_trajectory__struct.h"
// already included above
// #include "control_msgs/action/detail/joint_trajectory__functions.h"
bool control_msgs__action__joint_trajectory__result__convert_from_py(PyObject * _pymsg, void * _ros_message);
PyObject * control_msgs__action__joint_trajectory__result__convert_to_py(void * raw_ros_message);
ROSIDL_GENERATOR_C_EXPORT
bool control_msgs__action__joint_trajectory__get_result__response__convert_from_py(PyObject * _pymsg, void * _ros_message)
{
// check that the passed message is of the expected Python class
{
char full_classname_dest[73];
{
char * class_name = NULL;
char * module_name = NULL;
{
PyObject * class_attr = PyObject_GetAttrString(_pymsg, "__class__");
if (class_attr) {
PyObject * name_attr = PyObject_GetAttrString(class_attr, "__name__");
if (name_attr) {
class_name = (char *)PyUnicode_1BYTE_DATA(name_attr);
Py_DECREF(name_attr);
}
PyObject * module_attr = PyObject_GetAttrString(class_attr, "__module__");
if (module_attr) {
module_name = (char *)PyUnicode_1BYTE_DATA(module_attr);
Py_DECREF(module_attr);
}
Py_DECREF(class_attr);
}
}
if (!class_name || !module_name) {
return false;
}
snprintf(full_classname_dest, sizeof(full_classname_dest), "%s.%s", module_name, class_name);
}
assert(strncmp("control_msgs.action._joint_trajectory.JointTrajectory_GetResult_Response", full_classname_dest, 72) == 0);
}
control_msgs__action__JointTrajectory_GetResult_Response * ros_message = _ros_message;
{ // status
PyObject * field = PyObject_GetAttrString(_pymsg, "status");
if (!field) {
return false;
}
assert(PyLong_Check(field));
ros_message->status = (int8_t)PyLong_AsLong(field);
Py_DECREF(field);
}
{ // result
PyObject * field = PyObject_GetAttrString(_pymsg, "result");
if (!field) {
return false;
}
if (!control_msgs__action__joint_trajectory__result__convert_from_py(field, &ros_message->result)) {
Py_DECREF(field);
return false;
}
Py_DECREF(field);
}
return true;
}
ROSIDL_GENERATOR_C_EXPORT
PyObject * control_msgs__action__joint_trajectory__get_result__response__convert_to_py(void * raw_ros_message)
{
/* NOTE(esteve): Call constructor of JointTrajectory_GetResult_Response */
PyObject * _pymessage = NULL;
{
PyObject * pymessage_module = PyImport_ImportModule("control_msgs.action._joint_trajectory");
assert(pymessage_module);
PyObject * pymessage_class = PyObject_GetAttrString(pymessage_module, "JointTrajectory_GetResult_Response");
assert(pymessage_class);
Py_DECREF(pymessage_module);
_pymessage = PyObject_CallObject(pymessage_class, NULL);
Py_DECREF(pymessage_class);
if (!_pymessage) {
return NULL;
}
}
control_msgs__action__JointTrajectory_GetResult_Response * ros_message = (control_msgs__action__JointTrajectory_GetResult_Response *)raw_ros_message;
{ // status
PyObject * field = NULL;
field = PyLong_FromLong(ros_message->status);
{
int rc = PyObject_SetAttrString(_pymessage, "status", field);
Py_DECREF(field);
if (rc) {
return NULL;
}
}
}
{ // result
PyObject * field = NULL;
field = control_msgs__action__joint_trajectory__result__convert_to_py(&ros_message->result);
if (!field) {
return NULL;
}
{
int rc = PyObject_SetAttrString(_pymessage, "result", field);
Py_DECREF(field);
if (rc) {
return NULL;
}
}
}
// ownership of _pymessage is transferred to the caller
return _pymessage;
}
#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION
// already included above
// #include <Python.h>
// already included above
// #include <stdbool.h>
// already included above
// #include "numpy/ndarrayobject.h"
// already included above
// #include "rosidl_runtime_c/visibility_control.h"
// already included above
// #include "control_msgs/action/detail/joint_trajectory__struct.h"
// already included above
// #include "control_msgs/action/detail/joint_trajectory__functions.h"
ROSIDL_GENERATOR_C_IMPORT
bool unique_identifier_msgs__msg__uuid__convert_from_py(PyObject * _pymsg, void * _ros_message);
ROSIDL_GENERATOR_C_IMPORT
PyObject * unique_identifier_msgs__msg__uuid__convert_to_py(void * raw_ros_message);
bool control_msgs__action__joint_trajectory__feedback__convert_from_py(PyObject * _pymsg, void * _ros_message);
PyObject * control_msgs__action__joint_trajectory__feedback__convert_to_py(void * raw_ros_message);
ROSIDL_GENERATOR_C_EXPORT
bool control_msgs__action__joint_trajectory__feedback_message__convert_from_py(PyObject * _pymsg, void * _ros_message)
{
// check that the passed message is of the expected Python class
{
char full_classname_dest[70];
{
char * class_name = NULL;
char * module_name = NULL;
{
PyObject * class_attr = PyObject_GetAttrString(_pymsg, "__class__");
if (class_attr) {
PyObject * name_attr = PyObject_GetAttrString(class_attr, "__name__");
if (name_attr) {
class_name = (char *)PyUnicode_1BYTE_DATA(name_attr);
Py_DECREF(name_attr);
}
PyObject * module_attr = PyObject_GetAttrString(class_attr, "__module__");
if (module_attr) {
module_name = (char *)PyUnicode_1BYTE_DATA(module_attr);
Py_DECREF(module_attr);
}
Py_DECREF(class_attr);
}
}
if (!class_name || !module_name) {
return false;
}
snprintf(full_classname_dest, sizeof(full_classname_dest), "%s.%s", module_name, class_name);
}
assert(strncmp("control_msgs.action._joint_trajectory.JointTrajectory_FeedbackMessage", full_classname_dest, 69) == 0);
}
control_msgs__action__JointTrajectory_FeedbackMessage * ros_message = _ros_message;
{ // goal_id
PyObject * field = PyObject_GetAttrString(_pymsg, "goal_id");
if (!field) {
return false;
}
if (!unique_identifier_msgs__msg__uuid__convert_from_py(field, &ros_message->goal_id)) {
Py_DECREF(field);
return false;
}
Py_DECREF(field);
}
{ // feedback
PyObject * field = PyObject_GetAttrString(_pymsg, "feedback");
if (!field) {
return false;
}
if (!control_msgs__action__joint_trajectory__feedback__convert_from_py(field, &ros_message->feedback)) {
Py_DECREF(field);
return false;
}
Py_DECREF(field);
}
return true;
}
ROSIDL_GENERATOR_C_EXPORT
PyObject * control_msgs__action__joint_trajectory__feedback_message__convert_to_py(void * raw_ros_message)
{
/* NOTE(esteve): Call constructor of JointTrajectory_FeedbackMessage */
PyObject * _pymessage = NULL;
{
PyObject * pymessage_module = PyImport_ImportModule("control_msgs.action._joint_trajectory");
assert(pymessage_module);
PyObject * pymessage_class = PyObject_GetAttrString(pymessage_module, "JointTrajectory_FeedbackMessage");
assert(pymessage_class);
Py_DECREF(pymessage_module);
_pymessage = PyObject_CallObject(pymessage_class, NULL);
Py_DECREF(pymessage_class);
if (!_pymessage) {
return NULL;
}
}
control_msgs__action__JointTrajectory_FeedbackMessage * ros_message = (control_msgs__action__JointTrajectory_FeedbackMessage *)raw_ros_message;
{ // goal_id
PyObject * field = NULL;
field = unique_identifier_msgs__msg__uuid__convert_to_py(&ros_message->goal_id);
if (!field) {
return NULL;
}
{
int rc = PyObject_SetAttrString(_pymessage, "goal_id", field);
Py_DECREF(field);
if (rc) {
return NULL;
}
}
}
{ // feedback
PyObject * field = NULL;
field = control_msgs__action__joint_trajectory__feedback__convert_to_py(&ros_message->feedback);
if (!field) {
return NULL;
}
{
int rc = PyObject_SetAttrString(_pymessage, "feedback", field);
Py_DECREF(field);
if (rc) {
return NULL;
}
}
}
// ownership of _pymessage is transferred to the caller
return _pymessage;
}
| 29,706 | C | 33.067661 | 151 | 0.651889 |
Toni-SM/semu.robotics.ros2_bridge/src/semu.robotics.ros2_bridge/semu/robotics/ros2_bridge/packages/control_msgs/action/_joint_trajectory.py | # generated from rosidl_generator_py/resource/_idl.py.em
# with input from control_msgs:action/JointTrajectory.idl
# generated code does not contain a copyright notice
# Import statements for member types
import rosidl_parser.definition # noqa: E402, I100
class Metaclass_JointTrajectory_Goal(type):
"""Metaclass of message 'JointTrajectory_Goal'."""
_CREATE_ROS_MESSAGE = None
_CONVERT_FROM_PY = None
_CONVERT_TO_PY = None
_DESTROY_ROS_MESSAGE = None
_TYPE_SUPPORT = None
__constants = {
}
@classmethod
def __import_type_support__(cls):
try:
from rosidl_generator_py import import_type_support
module = import_type_support('control_msgs')
except ImportError:
import logging
import traceback
logger = logging.getLogger(
'control_msgs.action.JointTrajectory_Goal')
logger.debug(
'Failed to import needed modules for type support:\n' +
traceback.format_exc())
else:
cls._CREATE_ROS_MESSAGE = module.create_ros_message_msg__action__joint_trajectory__goal
cls._CONVERT_FROM_PY = module.convert_from_py_msg__action__joint_trajectory__goal
cls._CONVERT_TO_PY = module.convert_to_py_msg__action__joint_trajectory__goal
cls._TYPE_SUPPORT = module.type_support_msg__action__joint_trajectory__goal
cls._DESTROY_ROS_MESSAGE = module.destroy_ros_message_msg__action__joint_trajectory__goal
from trajectory_msgs.msg import JointTrajectory
if JointTrajectory.__class__._TYPE_SUPPORT is None:
JointTrajectory.__class__.__import_type_support__()
@classmethod
def __prepare__(cls, name, bases, **kwargs):
# list constant names here so that they appear in the help text of
# the message class under "Data and other attributes defined here:"
# as well as populate each message instance
return {
}
class JointTrajectory_Goal(metaclass=Metaclass_JointTrajectory_Goal):
"""Message class 'JointTrajectory_Goal'."""
__slots__ = [
'_trajectory',
]
_fields_and_field_types = {
'trajectory': 'trajectory_msgs/JointTrajectory',
}
SLOT_TYPES = (
rosidl_parser.definition.NamespacedType(['trajectory_msgs', 'msg'], 'JointTrajectory'), # noqa: E501
)
def __init__(self, **kwargs):
assert all('_' + key in self.__slots__ for key in kwargs.keys()), \
'Invalid arguments passed to constructor: %s' % \
', '.join(sorted(k for k in kwargs.keys() if '_' + k not in self.__slots__))
from trajectory_msgs.msg import JointTrajectory
self.trajectory = kwargs.get('trajectory', JointTrajectory())
def __repr__(self):
typename = self.__class__.__module__.split('.')
typename.pop()
typename.append(self.__class__.__name__)
args = []
for s, t in zip(self.__slots__, self.SLOT_TYPES):
field = getattr(self, s)
fieldstr = repr(field)
# We use Python array type for fields that can be directly stored
# in them, and "normal" sequences for everything else. If it is
# a type that we store in an array, strip off the 'array' portion.
if (
isinstance(t, rosidl_parser.definition.AbstractSequence) and
isinstance(t.value_type, rosidl_parser.definition.BasicType) and
t.value_type.typename in ['float', 'double', 'int8', 'uint8', 'int16', 'uint16', 'int32', 'uint32', 'int64', 'uint64']
):
if len(field) == 0:
fieldstr = '[]'
else:
assert fieldstr.startswith('array(')
prefix = "array('X', "
suffix = ')'
fieldstr = fieldstr[len(prefix):-len(suffix)]
args.append(s[1:] + '=' + fieldstr)
return '%s(%s)' % ('.'.join(typename), ', '.join(args))
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
if self.trajectory != other.trajectory:
return False
return True
@classmethod
def get_fields_and_field_types(cls):
from copy import copy
return copy(cls._fields_and_field_types)
@property
def trajectory(self):
"""Message field 'trajectory'."""
return self._trajectory
@trajectory.setter
def trajectory(self, value):
if __debug__:
from trajectory_msgs.msg import JointTrajectory
assert \
isinstance(value, JointTrajectory), \
"The 'trajectory' field must be a sub message of type 'JointTrajectory'"
self._trajectory = value
# Import statements for member types
# already imported above
# import rosidl_parser.definition
class Metaclass_JointTrajectory_Result(type):
"""Metaclass of message 'JointTrajectory_Result'."""
_CREATE_ROS_MESSAGE = None
_CONVERT_FROM_PY = None
_CONVERT_TO_PY = None
_DESTROY_ROS_MESSAGE = None
_TYPE_SUPPORT = None
__constants = {
}
@classmethod
def __import_type_support__(cls):
try:
from rosidl_generator_py import import_type_support
module = import_type_support('control_msgs')
except ImportError:
import logging
import traceback
logger = logging.getLogger(
'control_msgs.action.JointTrajectory_Result')
logger.debug(
'Failed to import needed modules for type support:\n' +
traceback.format_exc())
else:
cls._CREATE_ROS_MESSAGE = module.create_ros_message_msg__action__joint_trajectory__result
cls._CONVERT_FROM_PY = module.convert_from_py_msg__action__joint_trajectory__result
cls._CONVERT_TO_PY = module.convert_to_py_msg__action__joint_trajectory__result
cls._TYPE_SUPPORT = module.type_support_msg__action__joint_trajectory__result
cls._DESTROY_ROS_MESSAGE = module.destroy_ros_message_msg__action__joint_trajectory__result
@classmethod
def __prepare__(cls, name, bases, **kwargs):
# list constant names here so that they appear in the help text of
# the message class under "Data and other attributes defined here:"
# as well as populate each message instance
return {
}
class JointTrajectory_Result(metaclass=Metaclass_JointTrajectory_Result):
"""Message class 'JointTrajectory_Result'."""
__slots__ = [
]
_fields_and_field_types = {
}
SLOT_TYPES = (
)
def __init__(self, **kwargs):
assert all('_' + key in self.__slots__ for key in kwargs.keys()), \
'Invalid arguments passed to constructor: %s' % \
', '.join(sorted(k for k in kwargs.keys() if '_' + k not in self.__slots__))
def __repr__(self):
typename = self.__class__.__module__.split('.')
typename.pop()
typename.append(self.__class__.__name__)
args = []
for s, t in zip(self.__slots__, self.SLOT_TYPES):
field = getattr(self, s)
fieldstr = repr(field)
# We use Python array type for fields that can be directly stored
# in them, and "normal" sequences for everything else. If it is
# a type that we store in an array, strip off the 'array' portion.
if (
isinstance(t, rosidl_parser.definition.AbstractSequence) and
isinstance(t.value_type, rosidl_parser.definition.BasicType) and
t.value_type.typename in ['float', 'double', 'int8', 'uint8', 'int16', 'uint16', 'int32', 'uint32', 'int64', 'uint64']
):
if len(field) == 0:
fieldstr = '[]'
else:
assert fieldstr.startswith('array(')
prefix = "array('X', "
suffix = ')'
fieldstr = fieldstr[len(prefix):-len(suffix)]
args.append(s[1:] + '=' + fieldstr)
return '%s(%s)' % ('.'.join(typename), ', '.join(args))
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
return True
@classmethod
def get_fields_and_field_types(cls):
from copy import copy
return copy(cls._fields_and_field_types)
# Import statements for member types
# already imported above
# import rosidl_parser.definition
class Metaclass_JointTrajectory_Feedback(type):
"""Metaclass of message 'JointTrajectory_Feedback'."""
_CREATE_ROS_MESSAGE = None
_CONVERT_FROM_PY = None
_CONVERT_TO_PY = None
_DESTROY_ROS_MESSAGE = None
_TYPE_SUPPORT = None
__constants = {
}
@classmethod
def __import_type_support__(cls):
try:
from rosidl_generator_py import import_type_support
module = import_type_support('control_msgs')
except ImportError:
import logging
import traceback
logger = logging.getLogger(
'control_msgs.action.JointTrajectory_Feedback')
logger.debug(
'Failed to import needed modules for type support:\n' +
traceback.format_exc())
else:
cls._CREATE_ROS_MESSAGE = module.create_ros_message_msg__action__joint_trajectory__feedback
cls._CONVERT_FROM_PY = module.convert_from_py_msg__action__joint_trajectory__feedback
cls._CONVERT_TO_PY = module.convert_to_py_msg__action__joint_trajectory__feedback
cls._TYPE_SUPPORT = module.type_support_msg__action__joint_trajectory__feedback
cls._DESTROY_ROS_MESSAGE = module.destroy_ros_message_msg__action__joint_trajectory__feedback
@classmethod
def __prepare__(cls, name, bases, **kwargs):
# list constant names here so that they appear in the help text of
# the message class under "Data and other attributes defined here:"
# as well as populate each message instance
return {
}
class JointTrajectory_Feedback(metaclass=Metaclass_JointTrajectory_Feedback):
"""Message class 'JointTrajectory_Feedback'."""
__slots__ = [
]
_fields_and_field_types = {
}
SLOT_TYPES = (
)
def __init__(self, **kwargs):
assert all('_' + key in self.__slots__ for key in kwargs.keys()), \
'Invalid arguments passed to constructor: %s' % \
', '.join(sorted(k for k in kwargs.keys() if '_' + k not in self.__slots__))
def __repr__(self):
typename = self.__class__.__module__.split('.')
typename.pop()
typename.append(self.__class__.__name__)
args = []
for s, t in zip(self.__slots__, self.SLOT_TYPES):
field = getattr(self, s)
fieldstr = repr(field)
# We use Python array type for fields that can be directly stored
# in them, and "normal" sequences for everything else. If it is
# a type that we store in an array, strip off the 'array' portion.
if (
isinstance(t, rosidl_parser.definition.AbstractSequence) and
isinstance(t.value_type, rosidl_parser.definition.BasicType) and
t.value_type.typename in ['float', 'double', 'int8', 'uint8', 'int16', 'uint16', 'int32', 'uint32', 'int64', 'uint64']
):
if len(field) == 0:
fieldstr = '[]'
else:
assert fieldstr.startswith('array(')
prefix = "array('X', "
suffix = ')'
fieldstr = fieldstr[len(prefix):-len(suffix)]
args.append(s[1:] + '=' + fieldstr)
return '%s(%s)' % ('.'.join(typename), ', '.join(args))
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
return True
@classmethod
def get_fields_and_field_types(cls):
from copy import copy
return copy(cls._fields_and_field_types)
# Import statements for member types
# already imported above
# import rosidl_parser.definition
class Metaclass_JointTrajectory_SendGoal_Request(type):
"""Metaclass of message 'JointTrajectory_SendGoal_Request'."""
_CREATE_ROS_MESSAGE = None
_CONVERT_FROM_PY = None
_CONVERT_TO_PY = None
_DESTROY_ROS_MESSAGE = None
_TYPE_SUPPORT = None
__constants = {
}
@classmethod
def __import_type_support__(cls):
try:
from rosidl_generator_py import import_type_support
module = import_type_support('control_msgs')
except ImportError:
import logging
import traceback
logger = logging.getLogger(
'control_msgs.action.JointTrajectory_SendGoal_Request')
logger.debug(
'Failed to import needed modules for type support:\n' +
traceback.format_exc())
else:
cls._CREATE_ROS_MESSAGE = module.create_ros_message_msg__action__joint_trajectory__send_goal__request
cls._CONVERT_FROM_PY = module.convert_from_py_msg__action__joint_trajectory__send_goal__request
cls._CONVERT_TO_PY = module.convert_to_py_msg__action__joint_trajectory__send_goal__request
cls._TYPE_SUPPORT = module.type_support_msg__action__joint_trajectory__send_goal__request
cls._DESTROY_ROS_MESSAGE = module.destroy_ros_message_msg__action__joint_trajectory__send_goal__request
from control_msgs.action import JointTrajectory
if JointTrajectory.Goal.__class__._TYPE_SUPPORT is None:
JointTrajectory.Goal.__class__.__import_type_support__()
from unique_identifier_msgs.msg import UUID
if UUID.__class__._TYPE_SUPPORT is None:
UUID.__class__.__import_type_support__()
@classmethod
def __prepare__(cls, name, bases, **kwargs):
# list constant names here so that they appear in the help text of
# the message class under "Data and other attributes defined here:"
# as well as populate each message instance
return {
}
class JointTrajectory_SendGoal_Request(metaclass=Metaclass_JointTrajectory_SendGoal_Request):
"""Message class 'JointTrajectory_SendGoal_Request'."""
__slots__ = [
'_goal_id',
'_goal',
]
_fields_and_field_types = {
'goal_id': 'unique_identifier_msgs/UUID',
'goal': 'control_msgs/JointTrajectory_Goal',
}
SLOT_TYPES = (
rosidl_parser.definition.NamespacedType(['unique_identifier_msgs', 'msg'], 'UUID'), # noqa: E501
rosidl_parser.definition.NamespacedType(['control_msgs', 'action'], 'JointTrajectory_Goal'), # noqa: E501
)
def __init__(self, **kwargs):
assert all('_' + key in self.__slots__ for key in kwargs.keys()), \
'Invalid arguments passed to constructor: %s' % \
', '.join(sorted(k for k in kwargs.keys() if '_' + k not in self.__slots__))
from unique_identifier_msgs.msg import UUID
self.goal_id = kwargs.get('goal_id', UUID())
from control_msgs.action._joint_trajectory import JointTrajectory_Goal
self.goal = kwargs.get('goal', JointTrajectory_Goal())
def __repr__(self):
typename = self.__class__.__module__.split('.')
typename.pop()
typename.append(self.__class__.__name__)
args = []
for s, t in zip(self.__slots__, self.SLOT_TYPES):
field = getattr(self, s)
fieldstr = repr(field)
# We use Python array type for fields that can be directly stored
# in them, and "normal" sequences for everything else. If it is
# a type that we store in an array, strip off the 'array' portion.
if (
isinstance(t, rosidl_parser.definition.AbstractSequence) and
isinstance(t.value_type, rosidl_parser.definition.BasicType) and
t.value_type.typename in ['float', 'double', 'int8', 'uint8', 'int16', 'uint16', 'int32', 'uint32', 'int64', 'uint64']
):
if len(field) == 0:
fieldstr = '[]'
else:
assert fieldstr.startswith('array(')
prefix = "array('X', "
suffix = ')'
fieldstr = fieldstr[len(prefix):-len(suffix)]
args.append(s[1:] + '=' + fieldstr)
return '%s(%s)' % ('.'.join(typename), ', '.join(args))
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
if self.goal_id != other.goal_id:
return False
if self.goal != other.goal:
return False
return True
@classmethod
def get_fields_and_field_types(cls):
from copy import copy
return copy(cls._fields_and_field_types)
@property
def goal_id(self):
"""Message field 'goal_id'."""
return self._goal_id
@goal_id.setter
def goal_id(self, value):
if __debug__:
from unique_identifier_msgs.msg import UUID
assert \
isinstance(value, UUID), \
"The 'goal_id' field must be a sub message of type 'UUID'"
self._goal_id = value
@property
def goal(self):
"""Message field 'goal'."""
return self._goal
@goal.setter
def goal(self, value):
if __debug__:
from control_msgs.action._joint_trajectory import JointTrajectory_Goal
assert \
isinstance(value, JointTrajectory_Goal), \
"The 'goal' field must be a sub message of type 'JointTrajectory_Goal'"
self._goal = value
# Import statements for member types
# already imported above
# import rosidl_parser.definition
class Metaclass_JointTrajectory_SendGoal_Response(type):
"""Metaclass of message 'JointTrajectory_SendGoal_Response'."""
_CREATE_ROS_MESSAGE = None
_CONVERT_FROM_PY = None
_CONVERT_TO_PY = None
_DESTROY_ROS_MESSAGE = None
_TYPE_SUPPORT = None
__constants = {
}
@classmethod
def __import_type_support__(cls):
try:
from rosidl_generator_py import import_type_support
module = import_type_support('control_msgs')
except ImportError:
import logging
import traceback
logger = logging.getLogger(
'control_msgs.action.JointTrajectory_SendGoal_Response')
logger.debug(
'Failed to import needed modules for type support:\n' +
traceback.format_exc())
else:
cls._CREATE_ROS_MESSAGE = module.create_ros_message_msg__action__joint_trajectory__send_goal__response
cls._CONVERT_FROM_PY = module.convert_from_py_msg__action__joint_trajectory__send_goal__response
cls._CONVERT_TO_PY = module.convert_to_py_msg__action__joint_trajectory__send_goal__response
cls._TYPE_SUPPORT = module.type_support_msg__action__joint_trajectory__send_goal__response
cls._DESTROY_ROS_MESSAGE = module.destroy_ros_message_msg__action__joint_trajectory__send_goal__response
from builtin_interfaces.msg import Time
if Time.__class__._TYPE_SUPPORT is None:
Time.__class__.__import_type_support__()
@classmethod
def __prepare__(cls, name, bases, **kwargs):
# list constant names here so that they appear in the help text of
# the message class under "Data and other attributes defined here:"
# as well as populate each message instance
return {
}
class JointTrajectory_SendGoal_Response(metaclass=Metaclass_JointTrajectory_SendGoal_Response):
"""Message class 'JointTrajectory_SendGoal_Response'."""
__slots__ = [
'_accepted',
'_stamp',
]
_fields_and_field_types = {
'accepted': 'boolean',
'stamp': 'builtin_interfaces/Time',
}
SLOT_TYPES = (
rosidl_parser.definition.BasicType('boolean'), # noqa: E501
rosidl_parser.definition.NamespacedType(['builtin_interfaces', 'msg'], 'Time'), # noqa: E501
)
def __init__(self, **kwargs):
assert all('_' + key in self.__slots__ for key in kwargs.keys()), \
'Invalid arguments passed to constructor: %s' % \
', '.join(sorted(k for k in kwargs.keys() if '_' + k not in self.__slots__))
self.accepted = kwargs.get('accepted', bool())
from builtin_interfaces.msg import Time
self.stamp = kwargs.get('stamp', Time())
def __repr__(self):
typename = self.__class__.__module__.split('.')
typename.pop()
typename.append(self.__class__.__name__)
args = []
for s, t in zip(self.__slots__, self.SLOT_TYPES):
field = getattr(self, s)
fieldstr = repr(field)
# We use Python array type for fields that can be directly stored
# in them, and "normal" sequences for everything else. If it is
# a type that we store in an array, strip off the 'array' portion.
if (
isinstance(t, rosidl_parser.definition.AbstractSequence) and
isinstance(t.value_type, rosidl_parser.definition.BasicType) and
t.value_type.typename in ['float', 'double', 'int8', 'uint8', 'int16', 'uint16', 'int32', 'uint32', 'int64', 'uint64']
):
if len(field) == 0:
fieldstr = '[]'
else:
assert fieldstr.startswith('array(')
prefix = "array('X', "
suffix = ')'
fieldstr = fieldstr[len(prefix):-len(suffix)]
args.append(s[1:] + '=' + fieldstr)
return '%s(%s)' % ('.'.join(typename), ', '.join(args))
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
if self.accepted != other.accepted:
return False
if self.stamp != other.stamp:
return False
return True
@classmethod
def get_fields_and_field_types(cls):
from copy import copy
return copy(cls._fields_and_field_types)
@property
def accepted(self):
"""Message field 'accepted'."""
return self._accepted
@accepted.setter
def accepted(self, value):
if __debug__:
assert \
isinstance(value, bool), \
"The 'accepted' field must be of type 'bool'"
self._accepted = value
@property
def stamp(self):
"""Message field 'stamp'."""
return self._stamp
@stamp.setter
def stamp(self, value):
if __debug__:
from builtin_interfaces.msg import Time
assert \
isinstance(value, Time), \
"The 'stamp' field must be a sub message of type 'Time'"
self._stamp = value
class Metaclass_JointTrajectory_SendGoal(type):
"""Metaclass of service 'JointTrajectory_SendGoal'."""
_TYPE_SUPPORT = None
@classmethod
def __import_type_support__(cls):
try:
from rosidl_generator_py import import_type_support
module = import_type_support('control_msgs')
except ImportError:
import logging
import traceback
logger = logging.getLogger(
'control_msgs.action.JointTrajectory_SendGoal')
logger.debug(
'Failed to import needed modules for type support:\n' +
traceback.format_exc())
else:
cls._TYPE_SUPPORT = module.type_support_srv__action__joint_trajectory__send_goal
from control_msgs.action import _joint_trajectory
if _joint_trajectory.Metaclass_JointTrajectory_SendGoal_Request._TYPE_SUPPORT is None:
_joint_trajectory.Metaclass_JointTrajectory_SendGoal_Request.__import_type_support__()
if _joint_trajectory.Metaclass_JointTrajectory_SendGoal_Response._TYPE_SUPPORT is None:
_joint_trajectory.Metaclass_JointTrajectory_SendGoal_Response.__import_type_support__()
class JointTrajectory_SendGoal(metaclass=Metaclass_JointTrajectory_SendGoal):
from control_msgs.action._joint_trajectory import JointTrajectory_SendGoal_Request as Request
from control_msgs.action._joint_trajectory import JointTrajectory_SendGoal_Response as Response
def __init__(self):
raise NotImplementedError('Service classes can not be instantiated')
# Import statements for member types
# already imported above
# import rosidl_parser.definition
class Metaclass_JointTrajectory_GetResult_Request(type):
"""Metaclass of message 'JointTrajectory_GetResult_Request'."""
_CREATE_ROS_MESSAGE = None
_CONVERT_FROM_PY = None
_CONVERT_TO_PY = None
_DESTROY_ROS_MESSAGE = None
_TYPE_SUPPORT = None
__constants = {
}
@classmethod
def __import_type_support__(cls):
try:
from rosidl_generator_py import import_type_support
module = import_type_support('control_msgs')
except ImportError:
import logging
import traceback
logger = logging.getLogger(
'control_msgs.action.JointTrajectory_GetResult_Request')
logger.debug(
'Failed to import needed modules for type support:\n' +
traceback.format_exc())
else:
cls._CREATE_ROS_MESSAGE = module.create_ros_message_msg__action__joint_trajectory__get_result__request
cls._CONVERT_FROM_PY = module.convert_from_py_msg__action__joint_trajectory__get_result__request
cls._CONVERT_TO_PY = module.convert_to_py_msg__action__joint_trajectory__get_result__request
cls._TYPE_SUPPORT = module.type_support_msg__action__joint_trajectory__get_result__request
cls._DESTROY_ROS_MESSAGE = module.destroy_ros_message_msg__action__joint_trajectory__get_result__request
from unique_identifier_msgs.msg import UUID
if UUID.__class__._TYPE_SUPPORT is None:
UUID.__class__.__import_type_support__()
@classmethod
def __prepare__(cls, name, bases, **kwargs):
# list constant names here so that they appear in the help text of
# the message class under "Data and other attributes defined here:"
# as well as populate each message instance
return {
}
class JointTrajectory_GetResult_Request(metaclass=Metaclass_JointTrajectory_GetResult_Request):
"""Message class 'JointTrajectory_GetResult_Request'."""
__slots__ = [
'_goal_id',
]
_fields_and_field_types = {
'goal_id': 'unique_identifier_msgs/UUID',
}
SLOT_TYPES = (
rosidl_parser.definition.NamespacedType(['unique_identifier_msgs', 'msg'], 'UUID'), # noqa: E501
)
def __init__(self, **kwargs):
assert all('_' + key in self.__slots__ for key in kwargs.keys()), \
'Invalid arguments passed to constructor: %s' % \
', '.join(sorted(k for k in kwargs.keys() if '_' + k not in self.__slots__))
from unique_identifier_msgs.msg import UUID
self.goal_id = kwargs.get('goal_id', UUID())
def __repr__(self):
typename = self.__class__.__module__.split('.')
typename.pop()
typename.append(self.__class__.__name__)
args = []
for s, t in zip(self.__slots__, self.SLOT_TYPES):
field = getattr(self, s)
fieldstr = repr(field)
# We use Python array type for fields that can be directly stored
# in them, and "normal" sequences for everything else. If it is
# a type that we store in an array, strip off the 'array' portion.
if (
isinstance(t, rosidl_parser.definition.AbstractSequence) and
isinstance(t.value_type, rosidl_parser.definition.BasicType) and
t.value_type.typename in ['float', 'double', 'int8', 'uint8', 'int16', 'uint16', 'int32', 'uint32', 'int64', 'uint64']
):
if len(field) == 0:
fieldstr = '[]'
else:
assert fieldstr.startswith('array(')
prefix = "array('X', "
suffix = ')'
fieldstr = fieldstr[len(prefix):-len(suffix)]
args.append(s[1:] + '=' + fieldstr)
return '%s(%s)' % ('.'.join(typename), ', '.join(args))
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
if self.goal_id != other.goal_id:
return False
return True
@classmethod
def get_fields_and_field_types(cls):
from copy import copy
return copy(cls._fields_and_field_types)
@property
def goal_id(self):
"""Message field 'goal_id'."""
return self._goal_id
@goal_id.setter
def goal_id(self, value):
if __debug__:
from unique_identifier_msgs.msg import UUID
assert \
isinstance(value, UUID), \
"The 'goal_id' field must be a sub message of type 'UUID'"
self._goal_id = value
# Import statements for member types
# already imported above
# import rosidl_parser.definition
class Metaclass_JointTrajectory_GetResult_Response(type):
"""Metaclass of message 'JointTrajectory_GetResult_Response'."""
_CREATE_ROS_MESSAGE = None
_CONVERT_FROM_PY = None
_CONVERT_TO_PY = None
_DESTROY_ROS_MESSAGE = None
_TYPE_SUPPORT = None
__constants = {
}
@classmethod
def __import_type_support__(cls):
try:
from rosidl_generator_py import import_type_support
module = import_type_support('control_msgs')
except ImportError:
import logging
import traceback
logger = logging.getLogger(
'control_msgs.action.JointTrajectory_GetResult_Response')
logger.debug(
'Failed to import needed modules for type support:\n' +
traceback.format_exc())
else:
cls._CREATE_ROS_MESSAGE = module.create_ros_message_msg__action__joint_trajectory__get_result__response
cls._CONVERT_FROM_PY = module.convert_from_py_msg__action__joint_trajectory__get_result__response
cls._CONVERT_TO_PY = module.convert_to_py_msg__action__joint_trajectory__get_result__response
cls._TYPE_SUPPORT = module.type_support_msg__action__joint_trajectory__get_result__response
cls._DESTROY_ROS_MESSAGE = module.destroy_ros_message_msg__action__joint_trajectory__get_result__response
from control_msgs.action import JointTrajectory
if JointTrajectory.Result.__class__._TYPE_SUPPORT is None:
JointTrajectory.Result.__class__.__import_type_support__()
@classmethod
def __prepare__(cls, name, bases, **kwargs):
# list constant names here so that they appear in the help text of
# the message class under "Data and other attributes defined here:"
# as well as populate each message instance
return {
}
class JointTrajectory_GetResult_Response(metaclass=Metaclass_JointTrajectory_GetResult_Response):
"""Message class 'JointTrajectory_GetResult_Response'."""
__slots__ = [
'_status',
'_result',
]
_fields_and_field_types = {
'status': 'int8',
'result': 'control_msgs/JointTrajectory_Result',
}
SLOT_TYPES = (
rosidl_parser.definition.BasicType('int8'), # noqa: E501
rosidl_parser.definition.NamespacedType(['control_msgs', 'action'], 'JointTrajectory_Result'), # noqa: E501
)
def __init__(self, **kwargs):
assert all('_' + key in self.__slots__ for key in kwargs.keys()), \
'Invalid arguments passed to constructor: %s' % \
', '.join(sorted(k for k in kwargs.keys() if '_' + k not in self.__slots__))
self.status = kwargs.get('status', int())
from control_msgs.action._joint_trajectory import JointTrajectory_Result
self.result = kwargs.get('result', JointTrajectory_Result())
def __repr__(self):
typename = self.__class__.__module__.split('.')
typename.pop()
typename.append(self.__class__.__name__)
args = []
for s, t in zip(self.__slots__, self.SLOT_TYPES):
field = getattr(self, s)
fieldstr = repr(field)
# We use Python array type for fields that can be directly stored
# in them, and "normal" sequences for everything else. If it is
# a type that we store in an array, strip off the 'array' portion.
if (
isinstance(t, rosidl_parser.definition.AbstractSequence) and
isinstance(t.value_type, rosidl_parser.definition.BasicType) and
t.value_type.typename in ['float', 'double', 'int8', 'uint8', 'int16', 'uint16', 'int32', 'uint32', 'int64', 'uint64']
):
if len(field) == 0:
fieldstr = '[]'
else:
assert fieldstr.startswith('array(')
prefix = "array('X', "
suffix = ')'
fieldstr = fieldstr[len(prefix):-len(suffix)]
args.append(s[1:] + '=' + fieldstr)
return '%s(%s)' % ('.'.join(typename), ', '.join(args))
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
if self.status != other.status:
return False
if self.result != other.result:
return False
return True
@classmethod
def get_fields_and_field_types(cls):
from copy import copy
return copy(cls._fields_and_field_types)
@property
def status(self):
"""Message field 'status'."""
return self._status
@status.setter
def status(self, value):
if __debug__:
assert \
isinstance(value, int), \
"The 'status' field must be of type 'int'"
assert value >= -128 and value < 128, \
"The 'status' field must be an integer in [-128, 127]"
self._status = value
@property
def result(self):
"""Message field 'result'."""
return self._result
@result.setter
def result(self, value):
if __debug__:
from control_msgs.action._joint_trajectory import JointTrajectory_Result
assert \
isinstance(value, JointTrajectory_Result), \
"The 'result' field must be a sub message of type 'JointTrajectory_Result'"
self._result = value
class Metaclass_JointTrajectory_GetResult(type):
"""Metaclass of service 'JointTrajectory_GetResult'."""
_TYPE_SUPPORT = None
@classmethod
def __import_type_support__(cls):
try:
from rosidl_generator_py import import_type_support
module = import_type_support('control_msgs')
except ImportError:
import logging
import traceback
logger = logging.getLogger(
'control_msgs.action.JointTrajectory_GetResult')
logger.debug(
'Failed to import needed modules for type support:\n' +
traceback.format_exc())
else:
cls._TYPE_SUPPORT = module.type_support_srv__action__joint_trajectory__get_result
from control_msgs.action import _joint_trajectory
if _joint_trajectory.Metaclass_JointTrajectory_GetResult_Request._TYPE_SUPPORT is None:
_joint_trajectory.Metaclass_JointTrajectory_GetResult_Request.__import_type_support__()
if _joint_trajectory.Metaclass_JointTrajectory_GetResult_Response._TYPE_SUPPORT is None:
_joint_trajectory.Metaclass_JointTrajectory_GetResult_Response.__import_type_support__()
class JointTrajectory_GetResult(metaclass=Metaclass_JointTrajectory_GetResult):
from control_msgs.action._joint_trajectory import JointTrajectory_GetResult_Request as Request
from control_msgs.action._joint_trajectory import JointTrajectory_GetResult_Response as Response
def __init__(self):
raise NotImplementedError('Service classes can not be instantiated')
# Import statements for member types
# already imported above
# import rosidl_parser.definition
class Metaclass_JointTrajectory_FeedbackMessage(type):
"""Metaclass of message 'JointTrajectory_FeedbackMessage'."""
_CREATE_ROS_MESSAGE = None
_CONVERT_FROM_PY = None
_CONVERT_TO_PY = None
_DESTROY_ROS_MESSAGE = None
_TYPE_SUPPORT = None
__constants = {
}
@classmethod
def __import_type_support__(cls):
try:
from rosidl_generator_py import import_type_support
module = import_type_support('control_msgs')
except ImportError:
import logging
import traceback
logger = logging.getLogger(
'control_msgs.action.JointTrajectory_FeedbackMessage')
logger.debug(
'Failed to import needed modules for type support:\n' +
traceback.format_exc())
else:
cls._CREATE_ROS_MESSAGE = module.create_ros_message_msg__action__joint_trajectory__feedback_message
cls._CONVERT_FROM_PY = module.convert_from_py_msg__action__joint_trajectory__feedback_message
cls._CONVERT_TO_PY = module.convert_to_py_msg__action__joint_trajectory__feedback_message
cls._TYPE_SUPPORT = module.type_support_msg__action__joint_trajectory__feedback_message
cls._DESTROY_ROS_MESSAGE = module.destroy_ros_message_msg__action__joint_trajectory__feedback_message
from control_msgs.action import JointTrajectory
if JointTrajectory.Feedback.__class__._TYPE_SUPPORT is None:
JointTrajectory.Feedback.__class__.__import_type_support__()
from unique_identifier_msgs.msg import UUID
if UUID.__class__._TYPE_SUPPORT is None:
UUID.__class__.__import_type_support__()
@classmethod
def __prepare__(cls, name, bases, **kwargs):
# list constant names here so that they appear in the help text of
# the message class under "Data and other attributes defined here:"
# as well as populate each message instance
return {
}
class JointTrajectory_FeedbackMessage(metaclass=Metaclass_JointTrajectory_FeedbackMessage):
"""Message class 'JointTrajectory_FeedbackMessage'."""
__slots__ = [
'_goal_id',
'_feedback',
]
_fields_and_field_types = {
'goal_id': 'unique_identifier_msgs/UUID',
'feedback': 'control_msgs/JointTrajectory_Feedback',
}
SLOT_TYPES = (
rosidl_parser.definition.NamespacedType(['unique_identifier_msgs', 'msg'], 'UUID'), # noqa: E501
rosidl_parser.definition.NamespacedType(['control_msgs', 'action'], 'JointTrajectory_Feedback'), # noqa: E501
)
def __init__(self, **kwargs):
assert all('_' + key in self.__slots__ for key in kwargs.keys()), \
'Invalid arguments passed to constructor: %s' % \
', '.join(sorted(k for k in kwargs.keys() if '_' + k not in self.__slots__))
from unique_identifier_msgs.msg import UUID
self.goal_id = kwargs.get('goal_id', UUID())
from control_msgs.action._joint_trajectory import JointTrajectory_Feedback
self.feedback = kwargs.get('feedback', JointTrajectory_Feedback())
def __repr__(self):
typename = self.__class__.__module__.split('.')
typename.pop()
typename.append(self.__class__.__name__)
args = []
for s, t in zip(self.__slots__, self.SLOT_TYPES):
field = getattr(self, s)
fieldstr = repr(field)
# We use Python array type for fields that can be directly stored
# in them, and "normal" sequences for everything else. If it is
# a type that we store in an array, strip off the 'array' portion.
if (
isinstance(t, rosidl_parser.definition.AbstractSequence) and
isinstance(t.value_type, rosidl_parser.definition.BasicType) and
t.value_type.typename in ['float', 'double', 'int8', 'uint8', 'int16', 'uint16', 'int32', 'uint32', 'int64', 'uint64']
):
if len(field) == 0:
fieldstr = '[]'
else:
assert fieldstr.startswith('array(')
prefix = "array('X', "
suffix = ')'
fieldstr = fieldstr[len(prefix):-len(suffix)]
args.append(s[1:] + '=' + fieldstr)
return '%s(%s)' % ('.'.join(typename), ', '.join(args))
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
if self.goal_id != other.goal_id:
return False
if self.feedback != other.feedback:
return False
return True
@classmethod
def get_fields_and_field_types(cls):
from copy import copy
return copy(cls._fields_and_field_types)
@property
def goal_id(self):
"""Message field 'goal_id'."""
return self._goal_id
@goal_id.setter
def goal_id(self, value):
if __debug__:
from unique_identifier_msgs.msg import UUID
assert \
isinstance(value, UUID), \
"The 'goal_id' field must be a sub message of type 'UUID'"
self._goal_id = value
@property
def feedback(self):
"""Message field 'feedback'."""
return self._feedback
@feedback.setter
def feedback(self, value):
if __debug__:
from control_msgs.action._joint_trajectory import JointTrajectory_Feedback
assert \
isinstance(value, JointTrajectory_Feedback), \
"The 'feedback' field must be a sub message of type 'JointTrajectory_Feedback'"
self._feedback = value
class Metaclass_JointTrajectory(type):
"""Metaclass of action 'JointTrajectory'."""
_TYPE_SUPPORT = None
@classmethod
def __import_type_support__(cls):
try:
from rosidl_generator_py import import_type_support
module = import_type_support('control_msgs')
except ImportError:
import logging
import traceback
logger = logging.getLogger(
'control_msgs.action.JointTrajectory')
logger.debug(
'Failed to import needed modules for type support:\n' +
traceback.format_exc())
else:
cls._TYPE_SUPPORT = module.type_support_action__action__joint_trajectory
from action_msgs.msg import _goal_status_array
if _goal_status_array.Metaclass_GoalStatusArray._TYPE_SUPPORT is None:
_goal_status_array.Metaclass_GoalStatusArray.__import_type_support__()
from action_msgs.srv import _cancel_goal
if _cancel_goal.Metaclass_CancelGoal._TYPE_SUPPORT is None:
_cancel_goal.Metaclass_CancelGoal.__import_type_support__()
from control_msgs.action import _joint_trajectory
if _joint_trajectory.Metaclass_JointTrajectory_SendGoal._TYPE_SUPPORT is None:
_joint_trajectory.Metaclass_JointTrajectory_SendGoal.__import_type_support__()
if _joint_trajectory.Metaclass_JointTrajectory_GetResult._TYPE_SUPPORT is None:
_joint_trajectory.Metaclass_JointTrajectory_GetResult.__import_type_support__()
if _joint_trajectory.Metaclass_JointTrajectory_FeedbackMessage._TYPE_SUPPORT is None:
_joint_trajectory.Metaclass_JointTrajectory_FeedbackMessage.__import_type_support__()
class JointTrajectory(metaclass=Metaclass_JointTrajectory):
# The goal message defined in the action definition.
from control_msgs.action._joint_trajectory import JointTrajectory_Goal as Goal
# The result message defined in the action definition.
from control_msgs.action._joint_trajectory import JointTrajectory_Result as Result
# The feedback message defined in the action definition.
from control_msgs.action._joint_trajectory import JointTrajectory_Feedback as Feedback
class Impl:
# The send_goal service using a wrapped version of the goal message as a request.
from control_msgs.action._joint_trajectory import JointTrajectory_SendGoal as SendGoalService
# The get_result service using a wrapped version of the result message as a response.
from control_msgs.action._joint_trajectory import JointTrajectory_GetResult as GetResultService
# The feedback message with generic fields which wraps the feedback message.
from control_msgs.action._joint_trajectory import JointTrajectory_FeedbackMessage as FeedbackMessage
# The generic service to cancel a goal.
from action_msgs.srv._cancel_goal import CancelGoal as CancelGoalService
# The generic message for get the status of a goal.
from action_msgs.msg._goal_status_array import GoalStatusArray as GoalStatusMessage
def __init__(self):
raise NotImplementedError('Action classes can not be instantiated')
| 45,957 | Python | 37.717776 | 134 | 0.595274 |
Toni-SM/semu.robotics.ros2_bridge/src/semu.robotics.ros2_bridge/semu/robotics/ros2_bridge/packages/control_msgs/action/_point_head_s.c | // generated from rosidl_generator_py/resource/_idl_support.c.em
// with input from control_msgs:action/PointHead.idl
// generated code does not contain a copyright notice
#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION
#include <Python.h>
#include <stdbool.h>
#ifndef _WIN32
# pragma GCC diagnostic push
# pragma GCC diagnostic ignored "-Wunused-function"
#endif
#include "numpy/ndarrayobject.h"
#ifndef _WIN32
# pragma GCC diagnostic pop
#endif
#include "rosidl_runtime_c/visibility_control.h"
#include "control_msgs/action/detail/point_head__struct.h"
#include "control_msgs/action/detail/point_head__functions.h"
#include "rosidl_runtime_c/string.h"
#include "rosidl_runtime_c/string_functions.h"
ROSIDL_GENERATOR_C_IMPORT
bool geometry_msgs__msg__point_stamped__convert_from_py(PyObject * _pymsg, void * _ros_message);
ROSIDL_GENERATOR_C_IMPORT
PyObject * geometry_msgs__msg__point_stamped__convert_to_py(void * raw_ros_message);
ROSIDL_GENERATOR_C_IMPORT
bool geometry_msgs__msg__vector3__convert_from_py(PyObject * _pymsg, void * _ros_message);
ROSIDL_GENERATOR_C_IMPORT
PyObject * geometry_msgs__msg__vector3__convert_to_py(void * raw_ros_message);
ROSIDL_GENERATOR_C_IMPORT
bool builtin_interfaces__msg__duration__convert_from_py(PyObject * _pymsg, void * _ros_message);
ROSIDL_GENERATOR_C_IMPORT
PyObject * builtin_interfaces__msg__duration__convert_to_py(void * raw_ros_message);
ROSIDL_GENERATOR_C_EXPORT
bool control_msgs__action__point_head__goal__convert_from_py(PyObject * _pymsg, void * _ros_message)
{
// check that the passed message is of the expected Python class
{
char full_classname_dest[47];
{
char * class_name = NULL;
char * module_name = NULL;
{
PyObject * class_attr = PyObject_GetAttrString(_pymsg, "__class__");
if (class_attr) {
PyObject * name_attr = PyObject_GetAttrString(class_attr, "__name__");
if (name_attr) {
class_name = (char *)PyUnicode_1BYTE_DATA(name_attr);
Py_DECREF(name_attr);
}
PyObject * module_attr = PyObject_GetAttrString(class_attr, "__module__");
if (module_attr) {
module_name = (char *)PyUnicode_1BYTE_DATA(module_attr);
Py_DECREF(module_attr);
}
Py_DECREF(class_attr);
}
}
if (!class_name || !module_name) {
return false;
}
snprintf(full_classname_dest, sizeof(full_classname_dest), "%s.%s", module_name, class_name);
}
assert(strncmp("control_msgs.action._point_head.PointHead_Goal", full_classname_dest, 46) == 0);
}
control_msgs__action__PointHead_Goal * ros_message = _ros_message;
{ // target
PyObject * field = PyObject_GetAttrString(_pymsg, "target");
if (!field) {
return false;
}
if (!geometry_msgs__msg__point_stamped__convert_from_py(field, &ros_message->target)) {
Py_DECREF(field);
return false;
}
Py_DECREF(field);
}
{ // pointing_axis
PyObject * field = PyObject_GetAttrString(_pymsg, "pointing_axis");
if (!field) {
return false;
}
if (!geometry_msgs__msg__vector3__convert_from_py(field, &ros_message->pointing_axis)) {
Py_DECREF(field);
return false;
}
Py_DECREF(field);
}
{ // pointing_frame
PyObject * field = PyObject_GetAttrString(_pymsg, "pointing_frame");
if (!field) {
return false;
}
assert(PyUnicode_Check(field));
PyObject * encoded_field = PyUnicode_AsUTF8String(field);
if (!encoded_field) {
Py_DECREF(field);
return false;
}
rosidl_runtime_c__String__assign(&ros_message->pointing_frame, PyBytes_AS_STRING(encoded_field));
Py_DECREF(encoded_field);
Py_DECREF(field);
}
{ // min_duration
PyObject * field = PyObject_GetAttrString(_pymsg, "min_duration");
if (!field) {
return false;
}
if (!builtin_interfaces__msg__duration__convert_from_py(field, &ros_message->min_duration)) {
Py_DECREF(field);
return false;
}
Py_DECREF(field);
}
{ // max_velocity
PyObject * field = PyObject_GetAttrString(_pymsg, "max_velocity");
if (!field) {
return false;
}
assert(PyFloat_Check(field));
ros_message->max_velocity = PyFloat_AS_DOUBLE(field);
Py_DECREF(field);
}
return true;
}
ROSIDL_GENERATOR_C_EXPORT
PyObject * control_msgs__action__point_head__goal__convert_to_py(void * raw_ros_message)
{
/* NOTE(esteve): Call constructor of PointHead_Goal */
PyObject * _pymessage = NULL;
{
PyObject * pymessage_module = PyImport_ImportModule("control_msgs.action._point_head");
assert(pymessage_module);
PyObject * pymessage_class = PyObject_GetAttrString(pymessage_module, "PointHead_Goal");
assert(pymessage_class);
Py_DECREF(pymessage_module);
_pymessage = PyObject_CallObject(pymessage_class, NULL);
Py_DECREF(pymessage_class);
if (!_pymessage) {
return NULL;
}
}
control_msgs__action__PointHead_Goal * ros_message = (control_msgs__action__PointHead_Goal *)raw_ros_message;
{ // target
PyObject * field = NULL;
field = geometry_msgs__msg__point_stamped__convert_to_py(&ros_message->target);
if (!field) {
return NULL;
}
{
int rc = PyObject_SetAttrString(_pymessage, "target", field);
Py_DECREF(field);
if (rc) {
return NULL;
}
}
}
{ // pointing_axis
PyObject * field = NULL;
field = geometry_msgs__msg__vector3__convert_to_py(&ros_message->pointing_axis);
if (!field) {
return NULL;
}
{
int rc = PyObject_SetAttrString(_pymessage, "pointing_axis", field);
Py_DECREF(field);
if (rc) {
return NULL;
}
}
}
{ // pointing_frame
PyObject * field = NULL;
field = PyUnicode_DecodeUTF8(
ros_message->pointing_frame.data,
strlen(ros_message->pointing_frame.data),
"strict");
if (!field) {
return NULL;
}
{
int rc = PyObject_SetAttrString(_pymessage, "pointing_frame", field);
Py_DECREF(field);
if (rc) {
return NULL;
}
}
}
{ // min_duration
PyObject * field = NULL;
field = builtin_interfaces__msg__duration__convert_to_py(&ros_message->min_duration);
if (!field) {
return NULL;
}
{
int rc = PyObject_SetAttrString(_pymessage, "min_duration", field);
Py_DECREF(field);
if (rc) {
return NULL;
}
}
}
{ // max_velocity
PyObject * field = NULL;
field = PyFloat_FromDouble(ros_message->max_velocity);
{
int rc = PyObject_SetAttrString(_pymessage, "max_velocity", field);
Py_DECREF(field);
if (rc) {
return NULL;
}
}
}
// ownership of _pymessage is transferred to the caller
return _pymessage;
}
#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION
// already included above
// #include <Python.h>
// already included above
// #include <stdbool.h>
// already included above
// #include "numpy/ndarrayobject.h"
// already included above
// #include "rosidl_runtime_c/visibility_control.h"
// already included above
// #include "control_msgs/action/detail/point_head__struct.h"
// already included above
// #include "control_msgs/action/detail/point_head__functions.h"
ROSIDL_GENERATOR_C_EXPORT
bool control_msgs__action__point_head__result__convert_from_py(PyObject * _pymsg, void * _ros_message)
{
// check that the passed message is of the expected Python class
{
char full_classname_dest[49];
{
char * class_name = NULL;
char * module_name = NULL;
{
PyObject * class_attr = PyObject_GetAttrString(_pymsg, "__class__");
if (class_attr) {
PyObject * name_attr = PyObject_GetAttrString(class_attr, "__name__");
if (name_attr) {
class_name = (char *)PyUnicode_1BYTE_DATA(name_attr);
Py_DECREF(name_attr);
}
PyObject * module_attr = PyObject_GetAttrString(class_attr, "__module__");
if (module_attr) {
module_name = (char *)PyUnicode_1BYTE_DATA(module_attr);
Py_DECREF(module_attr);
}
Py_DECREF(class_attr);
}
}
if (!class_name || !module_name) {
return false;
}
snprintf(full_classname_dest, sizeof(full_classname_dest), "%s.%s", module_name, class_name);
}
assert(strncmp("control_msgs.action._point_head.PointHead_Result", full_classname_dest, 48) == 0);
}
control_msgs__action__PointHead_Result * ros_message = _ros_message;
ros_message->structure_needs_at_least_one_member = 0;
return true;
}
ROSIDL_GENERATOR_C_EXPORT
PyObject * control_msgs__action__point_head__result__convert_to_py(void * raw_ros_message)
{
/* NOTE(esteve): Call constructor of PointHead_Result */
PyObject * _pymessage = NULL;
{
PyObject * pymessage_module = PyImport_ImportModule("control_msgs.action._point_head");
assert(pymessage_module);
PyObject * pymessage_class = PyObject_GetAttrString(pymessage_module, "PointHead_Result");
assert(pymessage_class);
Py_DECREF(pymessage_module);
_pymessage = PyObject_CallObject(pymessage_class, NULL);
Py_DECREF(pymessage_class);
if (!_pymessage) {
return NULL;
}
}
(void)raw_ros_message;
// ownership of _pymessage is transferred to the caller
return _pymessage;
}
#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION
// already included above
// #include <Python.h>
// already included above
// #include <stdbool.h>
// already included above
// #include "numpy/ndarrayobject.h"
// already included above
// #include "rosidl_runtime_c/visibility_control.h"
// already included above
// #include "control_msgs/action/detail/point_head__struct.h"
// already included above
// #include "control_msgs/action/detail/point_head__functions.h"
ROSIDL_GENERATOR_C_EXPORT
bool control_msgs__action__point_head__feedback__convert_from_py(PyObject * _pymsg, void * _ros_message)
{
// check that the passed message is of the expected Python class
{
char full_classname_dest[51];
{
char * class_name = NULL;
char * module_name = NULL;
{
PyObject * class_attr = PyObject_GetAttrString(_pymsg, "__class__");
if (class_attr) {
PyObject * name_attr = PyObject_GetAttrString(class_attr, "__name__");
if (name_attr) {
class_name = (char *)PyUnicode_1BYTE_DATA(name_attr);
Py_DECREF(name_attr);
}
PyObject * module_attr = PyObject_GetAttrString(class_attr, "__module__");
if (module_attr) {
module_name = (char *)PyUnicode_1BYTE_DATA(module_attr);
Py_DECREF(module_attr);
}
Py_DECREF(class_attr);
}
}
if (!class_name || !module_name) {
return false;
}
snprintf(full_classname_dest, sizeof(full_classname_dest), "%s.%s", module_name, class_name);
}
assert(strncmp("control_msgs.action._point_head.PointHead_Feedback", full_classname_dest, 50) == 0);
}
control_msgs__action__PointHead_Feedback * ros_message = _ros_message;
{ // pointing_angle_error
PyObject * field = PyObject_GetAttrString(_pymsg, "pointing_angle_error");
if (!field) {
return false;
}
assert(PyFloat_Check(field));
ros_message->pointing_angle_error = PyFloat_AS_DOUBLE(field);
Py_DECREF(field);
}
return true;
}
ROSIDL_GENERATOR_C_EXPORT
PyObject * control_msgs__action__point_head__feedback__convert_to_py(void * raw_ros_message)
{
/* NOTE(esteve): Call constructor of PointHead_Feedback */
PyObject * _pymessage = NULL;
{
PyObject * pymessage_module = PyImport_ImportModule("control_msgs.action._point_head");
assert(pymessage_module);
PyObject * pymessage_class = PyObject_GetAttrString(pymessage_module, "PointHead_Feedback");
assert(pymessage_class);
Py_DECREF(pymessage_module);
_pymessage = PyObject_CallObject(pymessage_class, NULL);
Py_DECREF(pymessage_class);
if (!_pymessage) {
return NULL;
}
}
control_msgs__action__PointHead_Feedback * ros_message = (control_msgs__action__PointHead_Feedback *)raw_ros_message;
{ // pointing_angle_error
PyObject * field = NULL;
field = PyFloat_FromDouble(ros_message->pointing_angle_error);
{
int rc = PyObject_SetAttrString(_pymessage, "pointing_angle_error", field);
Py_DECREF(field);
if (rc) {
return NULL;
}
}
}
// ownership of _pymessage is transferred to the caller
return _pymessage;
}
#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION
// already included above
// #include <Python.h>
// already included above
// #include <stdbool.h>
// already included above
// #include "numpy/ndarrayobject.h"
// already included above
// #include "rosidl_runtime_c/visibility_control.h"
// already included above
// #include "control_msgs/action/detail/point_head__struct.h"
// already included above
// #include "control_msgs/action/detail/point_head__functions.h"
ROSIDL_GENERATOR_C_IMPORT
bool unique_identifier_msgs__msg__uuid__convert_from_py(PyObject * _pymsg, void * _ros_message);
ROSIDL_GENERATOR_C_IMPORT
PyObject * unique_identifier_msgs__msg__uuid__convert_to_py(void * raw_ros_message);
bool control_msgs__action__point_head__goal__convert_from_py(PyObject * _pymsg, void * _ros_message);
PyObject * control_msgs__action__point_head__goal__convert_to_py(void * raw_ros_message);
ROSIDL_GENERATOR_C_EXPORT
bool control_msgs__action__point_head__send_goal__request__convert_from_py(PyObject * _pymsg, void * _ros_message)
{
// check that the passed message is of the expected Python class
{
char full_classname_dest[59];
{
char * class_name = NULL;
char * module_name = NULL;
{
PyObject * class_attr = PyObject_GetAttrString(_pymsg, "__class__");
if (class_attr) {
PyObject * name_attr = PyObject_GetAttrString(class_attr, "__name__");
if (name_attr) {
class_name = (char *)PyUnicode_1BYTE_DATA(name_attr);
Py_DECREF(name_attr);
}
PyObject * module_attr = PyObject_GetAttrString(class_attr, "__module__");
if (module_attr) {
module_name = (char *)PyUnicode_1BYTE_DATA(module_attr);
Py_DECREF(module_attr);
}
Py_DECREF(class_attr);
}
}
if (!class_name || !module_name) {
return false;
}
snprintf(full_classname_dest, sizeof(full_classname_dest), "%s.%s", module_name, class_name);
}
assert(strncmp("control_msgs.action._point_head.PointHead_SendGoal_Request", full_classname_dest, 58) == 0);
}
control_msgs__action__PointHead_SendGoal_Request * ros_message = _ros_message;
{ // goal_id
PyObject * field = PyObject_GetAttrString(_pymsg, "goal_id");
if (!field) {
return false;
}
if (!unique_identifier_msgs__msg__uuid__convert_from_py(field, &ros_message->goal_id)) {
Py_DECREF(field);
return false;
}
Py_DECREF(field);
}
{ // goal
PyObject * field = PyObject_GetAttrString(_pymsg, "goal");
if (!field) {
return false;
}
if (!control_msgs__action__point_head__goal__convert_from_py(field, &ros_message->goal)) {
Py_DECREF(field);
return false;
}
Py_DECREF(field);
}
return true;
}
ROSIDL_GENERATOR_C_EXPORT
PyObject * control_msgs__action__point_head__send_goal__request__convert_to_py(void * raw_ros_message)
{
/* NOTE(esteve): Call constructor of PointHead_SendGoal_Request */
PyObject * _pymessage = NULL;
{
PyObject * pymessage_module = PyImport_ImportModule("control_msgs.action._point_head");
assert(pymessage_module);
PyObject * pymessage_class = PyObject_GetAttrString(pymessage_module, "PointHead_SendGoal_Request");
assert(pymessage_class);
Py_DECREF(pymessage_module);
_pymessage = PyObject_CallObject(pymessage_class, NULL);
Py_DECREF(pymessage_class);
if (!_pymessage) {
return NULL;
}
}
control_msgs__action__PointHead_SendGoal_Request * ros_message = (control_msgs__action__PointHead_SendGoal_Request *)raw_ros_message;
{ // goal_id
PyObject * field = NULL;
field = unique_identifier_msgs__msg__uuid__convert_to_py(&ros_message->goal_id);
if (!field) {
return NULL;
}
{
int rc = PyObject_SetAttrString(_pymessage, "goal_id", field);
Py_DECREF(field);
if (rc) {
return NULL;
}
}
}
{ // goal
PyObject * field = NULL;
field = control_msgs__action__point_head__goal__convert_to_py(&ros_message->goal);
if (!field) {
return NULL;
}
{
int rc = PyObject_SetAttrString(_pymessage, "goal", field);
Py_DECREF(field);
if (rc) {
return NULL;
}
}
}
// ownership of _pymessage is transferred to the caller
return _pymessage;
}
#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION
// already included above
// #include <Python.h>
// already included above
// #include <stdbool.h>
// already included above
// #include "numpy/ndarrayobject.h"
// already included above
// #include "rosidl_runtime_c/visibility_control.h"
// already included above
// #include "control_msgs/action/detail/point_head__struct.h"
// already included above
// #include "control_msgs/action/detail/point_head__functions.h"
ROSIDL_GENERATOR_C_IMPORT
bool builtin_interfaces__msg__time__convert_from_py(PyObject * _pymsg, void * _ros_message);
ROSIDL_GENERATOR_C_IMPORT
PyObject * builtin_interfaces__msg__time__convert_to_py(void * raw_ros_message);
ROSIDL_GENERATOR_C_EXPORT
bool control_msgs__action__point_head__send_goal__response__convert_from_py(PyObject * _pymsg, void * _ros_message)
{
// check that the passed message is of the expected Python class
{
char full_classname_dest[60];
{
char * class_name = NULL;
char * module_name = NULL;
{
PyObject * class_attr = PyObject_GetAttrString(_pymsg, "__class__");
if (class_attr) {
PyObject * name_attr = PyObject_GetAttrString(class_attr, "__name__");
if (name_attr) {
class_name = (char *)PyUnicode_1BYTE_DATA(name_attr);
Py_DECREF(name_attr);
}
PyObject * module_attr = PyObject_GetAttrString(class_attr, "__module__");
if (module_attr) {
module_name = (char *)PyUnicode_1BYTE_DATA(module_attr);
Py_DECREF(module_attr);
}
Py_DECREF(class_attr);
}
}
if (!class_name || !module_name) {
return false;
}
snprintf(full_classname_dest, sizeof(full_classname_dest), "%s.%s", module_name, class_name);
}
assert(strncmp("control_msgs.action._point_head.PointHead_SendGoal_Response", full_classname_dest, 59) == 0);
}
control_msgs__action__PointHead_SendGoal_Response * ros_message = _ros_message;
{ // accepted
PyObject * field = PyObject_GetAttrString(_pymsg, "accepted");
if (!field) {
return false;
}
assert(PyBool_Check(field));
ros_message->accepted = (Py_True == field);
Py_DECREF(field);
}
{ // stamp
PyObject * field = PyObject_GetAttrString(_pymsg, "stamp");
if (!field) {
return false;
}
if (!builtin_interfaces__msg__time__convert_from_py(field, &ros_message->stamp)) {
Py_DECREF(field);
return false;
}
Py_DECREF(field);
}
return true;
}
ROSIDL_GENERATOR_C_EXPORT
PyObject * control_msgs__action__point_head__send_goal__response__convert_to_py(void * raw_ros_message)
{
/* NOTE(esteve): Call constructor of PointHead_SendGoal_Response */
PyObject * _pymessage = NULL;
{
PyObject * pymessage_module = PyImport_ImportModule("control_msgs.action._point_head");
assert(pymessage_module);
PyObject * pymessage_class = PyObject_GetAttrString(pymessage_module, "PointHead_SendGoal_Response");
assert(pymessage_class);
Py_DECREF(pymessage_module);
_pymessage = PyObject_CallObject(pymessage_class, NULL);
Py_DECREF(pymessage_class);
if (!_pymessage) {
return NULL;
}
}
control_msgs__action__PointHead_SendGoal_Response * ros_message = (control_msgs__action__PointHead_SendGoal_Response *)raw_ros_message;
{ // accepted
PyObject * field = NULL;
field = PyBool_FromLong(ros_message->accepted ? 1 : 0);
{
int rc = PyObject_SetAttrString(_pymessage, "accepted", field);
Py_DECREF(field);
if (rc) {
return NULL;
}
}
}
{ // stamp
PyObject * field = NULL;
field = builtin_interfaces__msg__time__convert_to_py(&ros_message->stamp);
if (!field) {
return NULL;
}
{
int rc = PyObject_SetAttrString(_pymessage, "stamp", field);
Py_DECREF(field);
if (rc) {
return NULL;
}
}
}
// ownership of _pymessage is transferred to the caller
return _pymessage;
}
#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION
// already included above
// #include <Python.h>
// already included above
// #include <stdbool.h>
// already included above
// #include "numpy/ndarrayobject.h"
// already included above
// #include "rosidl_runtime_c/visibility_control.h"
// already included above
// #include "control_msgs/action/detail/point_head__struct.h"
// already included above
// #include "control_msgs/action/detail/point_head__functions.h"
ROSIDL_GENERATOR_C_IMPORT
bool unique_identifier_msgs__msg__uuid__convert_from_py(PyObject * _pymsg, void * _ros_message);
ROSIDL_GENERATOR_C_IMPORT
PyObject * unique_identifier_msgs__msg__uuid__convert_to_py(void * raw_ros_message);
ROSIDL_GENERATOR_C_EXPORT
bool control_msgs__action__point_head__get_result__request__convert_from_py(PyObject * _pymsg, void * _ros_message)
{
// check that the passed message is of the expected Python class
{
char full_classname_dest[60];
{
char * class_name = NULL;
char * module_name = NULL;
{
PyObject * class_attr = PyObject_GetAttrString(_pymsg, "__class__");
if (class_attr) {
PyObject * name_attr = PyObject_GetAttrString(class_attr, "__name__");
if (name_attr) {
class_name = (char *)PyUnicode_1BYTE_DATA(name_attr);
Py_DECREF(name_attr);
}
PyObject * module_attr = PyObject_GetAttrString(class_attr, "__module__");
if (module_attr) {
module_name = (char *)PyUnicode_1BYTE_DATA(module_attr);
Py_DECREF(module_attr);
}
Py_DECREF(class_attr);
}
}
if (!class_name || !module_name) {
return false;
}
snprintf(full_classname_dest, sizeof(full_classname_dest), "%s.%s", module_name, class_name);
}
assert(strncmp("control_msgs.action._point_head.PointHead_GetResult_Request", full_classname_dest, 59) == 0);
}
control_msgs__action__PointHead_GetResult_Request * ros_message = _ros_message;
{ // goal_id
PyObject * field = PyObject_GetAttrString(_pymsg, "goal_id");
if (!field) {
return false;
}
if (!unique_identifier_msgs__msg__uuid__convert_from_py(field, &ros_message->goal_id)) {
Py_DECREF(field);
return false;
}
Py_DECREF(field);
}
return true;
}
ROSIDL_GENERATOR_C_EXPORT
PyObject * control_msgs__action__point_head__get_result__request__convert_to_py(void * raw_ros_message)
{
/* NOTE(esteve): Call constructor of PointHead_GetResult_Request */
PyObject * _pymessage = NULL;
{
PyObject * pymessage_module = PyImport_ImportModule("control_msgs.action._point_head");
assert(pymessage_module);
PyObject * pymessage_class = PyObject_GetAttrString(pymessage_module, "PointHead_GetResult_Request");
assert(pymessage_class);
Py_DECREF(pymessage_module);
_pymessage = PyObject_CallObject(pymessage_class, NULL);
Py_DECREF(pymessage_class);
if (!_pymessage) {
return NULL;
}
}
control_msgs__action__PointHead_GetResult_Request * ros_message = (control_msgs__action__PointHead_GetResult_Request *)raw_ros_message;
{ // goal_id
PyObject * field = NULL;
field = unique_identifier_msgs__msg__uuid__convert_to_py(&ros_message->goal_id);
if (!field) {
return NULL;
}
{
int rc = PyObject_SetAttrString(_pymessage, "goal_id", field);
Py_DECREF(field);
if (rc) {
return NULL;
}
}
}
// ownership of _pymessage is transferred to the caller
return _pymessage;
}
#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION
// already included above
// #include <Python.h>
// already included above
// #include <stdbool.h>
// already included above
// #include "numpy/ndarrayobject.h"
// already included above
// #include "rosidl_runtime_c/visibility_control.h"
// already included above
// #include "control_msgs/action/detail/point_head__struct.h"
// already included above
// #include "control_msgs/action/detail/point_head__functions.h"
bool control_msgs__action__point_head__result__convert_from_py(PyObject * _pymsg, void * _ros_message);
PyObject * control_msgs__action__point_head__result__convert_to_py(void * raw_ros_message);
ROSIDL_GENERATOR_C_EXPORT
bool control_msgs__action__point_head__get_result__response__convert_from_py(PyObject * _pymsg, void * _ros_message)
{
// check that the passed message is of the expected Python class
{
char full_classname_dest[61];
{
char * class_name = NULL;
char * module_name = NULL;
{
PyObject * class_attr = PyObject_GetAttrString(_pymsg, "__class__");
if (class_attr) {
PyObject * name_attr = PyObject_GetAttrString(class_attr, "__name__");
if (name_attr) {
class_name = (char *)PyUnicode_1BYTE_DATA(name_attr);
Py_DECREF(name_attr);
}
PyObject * module_attr = PyObject_GetAttrString(class_attr, "__module__");
if (module_attr) {
module_name = (char *)PyUnicode_1BYTE_DATA(module_attr);
Py_DECREF(module_attr);
}
Py_DECREF(class_attr);
}
}
if (!class_name || !module_name) {
return false;
}
snprintf(full_classname_dest, sizeof(full_classname_dest), "%s.%s", module_name, class_name);
}
assert(strncmp("control_msgs.action._point_head.PointHead_GetResult_Response", full_classname_dest, 60) == 0);
}
control_msgs__action__PointHead_GetResult_Response * ros_message = _ros_message;
{ // status
PyObject * field = PyObject_GetAttrString(_pymsg, "status");
if (!field) {
return false;
}
assert(PyLong_Check(field));
ros_message->status = (int8_t)PyLong_AsLong(field);
Py_DECREF(field);
}
{ // result
PyObject * field = PyObject_GetAttrString(_pymsg, "result");
if (!field) {
return false;
}
if (!control_msgs__action__point_head__result__convert_from_py(field, &ros_message->result)) {
Py_DECREF(field);
return false;
}
Py_DECREF(field);
}
return true;
}
ROSIDL_GENERATOR_C_EXPORT
PyObject * control_msgs__action__point_head__get_result__response__convert_to_py(void * raw_ros_message)
{
/* NOTE(esteve): Call constructor of PointHead_GetResult_Response */
PyObject * _pymessage = NULL;
{
PyObject * pymessage_module = PyImport_ImportModule("control_msgs.action._point_head");
assert(pymessage_module);
PyObject * pymessage_class = PyObject_GetAttrString(pymessage_module, "PointHead_GetResult_Response");
assert(pymessage_class);
Py_DECREF(pymessage_module);
_pymessage = PyObject_CallObject(pymessage_class, NULL);
Py_DECREF(pymessage_class);
if (!_pymessage) {
return NULL;
}
}
control_msgs__action__PointHead_GetResult_Response * ros_message = (control_msgs__action__PointHead_GetResult_Response *)raw_ros_message;
{ // status
PyObject * field = NULL;
field = PyLong_FromLong(ros_message->status);
{
int rc = PyObject_SetAttrString(_pymessage, "status", field);
Py_DECREF(field);
if (rc) {
return NULL;
}
}
}
{ // result
PyObject * field = NULL;
field = control_msgs__action__point_head__result__convert_to_py(&ros_message->result);
if (!field) {
return NULL;
}
{
int rc = PyObject_SetAttrString(_pymessage, "result", field);
Py_DECREF(field);
if (rc) {
return NULL;
}
}
}
// ownership of _pymessage is transferred to the caller
return _pymessage;
}
#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION
// already included above
// #include <Python.h>
// already included above
// #include <stdbool.h>
// already included above
// #include "numpy/ndarrayobject.h"
// already included above
// #include "rosidl_runtime_c/visibility_control.h"
// already included above
// #include "control_msgs/action/detail/point_head__struct.h"
// already included above
// #include "control_msgs/action/detail/point_head__functions.h"
ROSIDL_GENERATOR_C_IMPORT
bool unique_identifier_msgs__msg__uuid__convert_from_py(PyObject * _pymsg, void * _ros_message);
ROSIDL_GENERATOR_C_IMPORT
PyObject * unique_identifier_msgs__msg__uuid__convert_to_py(void * raw_ros_message);
bool control_msgs__action__point_head__feedback__convert_from_py(PyObject * _pymsg, void * _ros_message);
PyObject * control_msgs__action__point_head__feedback__convert_to_py(void * raw_ros_message);
ROSIDL_GENERATOR_C_EXPORT
bool control_msgs__action__point_head__feedback_message__convert_from_py(PyObject * _pymsg, void * _ros_message)
{
// check that the passed message is of the expected Python class
{
char full_classname_dest[58];
{
char * class_name = NULL;
char * module_name = NULL;
{
PyObject * class_attr = PyObject_GetAttrString(_pymsg, "__class__");
if (class_attr) {
PyObject * name_attr = PyObject_GetAttrString(class_attr, "__name__");
if (name_attr) {
class_name = (char *)PyUnicode_1BYTE_DATA(name_attr);
Py_DECREF(name_attr);
}
PyObject * module_attr = PyObject_GetAttrString(class_attr, "__module__");
if (module_attr) {
module_name = (char *)PyUnicode_1BYTE_DATA(module_attr);
Py_DECREF(module_attr);
}
Py_DECREF(class_attr);
}
}
if (!class_name || !module_name) {
return false;
}
snprintf(full_classname_dest, sizeof(full_classname_dest), "%s.%s", module_name, class_name);
}
assert(strncmp("control_msgs.action._point_head.PointHead_FeedbackMessage", full_classname_dest, 57) == 0);
}
control_msgs__action__PointHead_FeedbackMessage * ros_message = _ros_message;
{ // goal_id
PyObject * field = PyObject_GetAttrString(_pymsg, "goal_id");
if (!field) {
return false;
}
if (!unique_identifier_msgs__msg__uuid__convert_from_py(field, &ros_message->goal_id)) {
Py_DECREF(field);
return false;
}
Py_DECREF(field);
}
{ // feedback
PyObject * field = PyObject_GetAttrString(_pymsg, "feedback");
if (!field) {
return false;
}
if (!control_msgs__action__point_head__feedback__convert_from_py(field, &ros_message->feedback)) {
Py_DECREF(field);
return false;
}
Py_DECREF(field);
}
return true;
}
ROSIDL_GENERATOR_C_EXPORT
PyObject * control_msgs__action__point_head__feedback_message__convert_to_py(void * raw_ros_message)
{
/* NOTE(esteve): Call constructor of PointHead_FeedbackMessage */
PyObject * _pymessage = NULL;
{
PyObject * pymessage_module = PyImport_ImportModule("control_msgs.action._point_head");
assert(pymessage_module);
PyObject * pymessage_class = PyObject_GetAttrString(pymessage_module, "PointHead_FeedbackMessage");
assert(pymessage_class);
Py_DECREF(pymessage_module);
_pymessage = PyObject_CallObject(pymessage_class, NULL);
Py_DECREF(pymessage_class);
if (!_pymessage) {
return NULL;
}
}
control_msgs__action__PointHead_FeedbackMessage * ros_message = (control_msgs__action__PointHead_FeedbackMessage *)raw_ros_message;
{ // goal_id
PyObject * field = NULL;
field = unique_identifier_msgs__msg__uuid__convert_to_py(&ros_message->goal_id);
if (!field) {
return NULL;
}
{
int rc = PyObject_SetAttrString(_pymessage, "goal_id", field);
Py_DECREF(field);
if (rc) {
return NULL;
}
}
}
{ // feedback
PyObject * field = NULL;
field = control_msgs__action__point_head__feedback__convert_to_py(&ros_message->feedback);
if (!field) {
return NULL;
}
{
int rc = PyObject_SetAttrString(_pymessage, "feedback", field);
Py_DECREF(field);
if (rc) {
return NULL;
}
}
}
// ownership of _pymessage is transferred to the caller
return _pymessage;
}
| 32,869 | C | 31.739044 | 139 | 0.64033 |
Toni-SM/semu.robotics.ros2_bridge/src/semu.robotics.ros2_bridge/semu/robotics/ros2_bridge/packages/control_msgs/action/__init__.py | from control_msgs.action._follow_joint_trajectory import FollowJointTrajectory # noqa: F401
from control_msgs.action._gripper_command import GripperCommand # noqa: F401
from control_msgs.action._joint_trajectory import JointTrajectory # noqa: F401
from control_msgs.action._point_head import PointHead # noqa: F401
from control_msgs.action._single_joint_position import SingleJointPosition # noqa: F401
| 408 | Python | 67.166655 | 92 | 0.811275 |
Toni-SM/semu.robotics.ros2_bridge/src/semu.robotics.ros2_bridge/semu/robotics/ros2_bridge/packages/control_msgs/action/_gripper_command_s.c | // generated from rosidl_generator_py/resource/_idl_support.c.em
// with input from control_msgs:action/GripperCommand.idl
// generated code does not contain a copyright notice
#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION
#include <Python.h>
#include <stdbool.h>
#ifndef _WIN32
# pragma GCC diagnostic push
# pragma GCC diagnostic ignored "-Wunused-function"
#endif
#include "numpy/ndarrayobject.h"
#ifndef _WIN32
# pragma GCC diagnostic pop
#endif
#include "rosidl_runtime_c/visibility_control.h"
#include "control_msgs/action/detail/gripper_command__struct.h"
#include "control_msgs/action/detail/gripper_command__functions.h"
bool control_msgs__msg__gripper_command__convert_from_py(PyObject * _pymsg, void * _ros_message);
PyObject * control_msgs__msg__gripper_command__convert_to_py(void * raw_ros_message);
ROSIDL_GENERATOR_C_EXPORT
bool control_msgs__action__gripper_command__goal__convert_from_py(PyObject * _pymsg, void * _ros_message)
{
// check that the passed message is of the expected Python class
{
char full_classname_dest[57];
{
char * class_name = NULL;
char * module_name = NULL;
{
PyObject * class_attr = PyObject_GetAttrString(_pymsg, "__class__");
if (class_attr) {
PyObject * name_attr = PyObject_GetAttrString(class_attr, "__name__");
if (name_attr) {
class_name = (char *)PyUnicode_1BYTE_DATA(name_attr);
Py_DECREF(name_attr);
}
PyObject * module_attr = PyObject_GetAttrString(class_attr, "__module__");
if (module_attr) {
module_name = (char *)PyUnicode_1BYTE_DATA(module_attr);
Py_DECREF(module_attr);
}
Py_DECREF(class_attr);
}
}
if (!class_name || !module_name) {
return false;
}
snprintf(full_classname_dest, sizeof(full_classname_dest), "%s.%s", module_name, class_name);
}
assert(strncmp("control_msgs.action._gripper_command.GripperCommand_Goal", full_classname_dest, 56) == 0);
}
control_msgs__action__GripperCommand_Goal * ros_message = _ros_message;
{ // command
PyObject * field = PyObject_GetAttrString(_pymsg, "command");
if (!field) {
return false;
}
if (!control_msgs__msg__gripper_command__convert_from_py(field, &ros_message->command)) {
Py_DECREF(field);
return false;
}
Py_DECREF(field);
}
return true;
}
ROSIDL_GENERATOR_C_EXPORT
PyObject * control_msgs__action__gripper_command__goal__convert_to_py(void * raw_ros_message)
{
/* NOTE(esteve): Call constructor of GripperCommand_Goal */
PyObject * _pymessage = NULL;
{
PyObject * pymessage_module = PyImport_ImportModule("control_msgs.action._gripper_command");
assert(pymessage_module);
PyObject * pymessage_class = PyObject_GetAttrString(pymessage_module, "GripperCommand_Goal");
assert(pymessage_class);
Py_DECREF(pymessage_module);
_pymessage = PyObject_CallObject(pymessage_class, NULL);
Py_DECREF(pymessage_class);
if (!_pymessage) {
return NULL;
}
}
control_msgs__action__GripperCommand_Goal * ros_message = (control_msgs__action__GripperCommand_Goal *)raw_ros_message;
{ // command
PyObject * field = NULL;
field = control_msgs__msg__gripper_command__convert_to_py(&ros_message->command);
if (!field) {
return NULL;
}
{
int rc = PyObject_SetAttrString(_pymessage, "command", field);
Py_DECREF(field);
if (rc) {
return NULL;
}
}
}
// ownership of _pymessage is transferred to the caller
return _pymessage;
}
#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION
// already included above
// #include <Python.h>
// already included above
// #include <stdbool.h>
// already included above
// #include "numpy/ndarrayobject.h"
// already included above
// #include "rosidl_runtime_c/visibility_control.h"
// already included above
// #include "control_msgs/action/detail/gripper_command__struct.h"
// already included above
// #include "control_msgs/action/detail/gripper_command__functions.h"
ROSIDL_GENERATOR_C_EXPORT
bool control_msgs__action__gripper_command__result__convert_from_py(PyObject * _pymsg, void * _ros_message)
{
// check that the passed message is of the expected Python class
{
char full_classname_dest[59];
{
char * class_name = NULL;
char * module_name = NULL;
{
PyObject * class_attr = PyObject_GetAttrString(_pymsg, "__class__");
if (class_attr) {
PyObject * name_attr = PyObject_GetAttrString(class_attr, "__name__");
if (name_attr) {
class_name = (char *)PyUnicode_1BYTE_DATA(name_attr);
Py_DECREF(name_attr);
}
PyObject * module_attr = PyObject_GetAttrString(class_attr, "__module__");
if (module_attr) {
module_name = (char *)PyUnicode_1BYTE_DATA(module_attr);
Py_DECREF(module_attr);
}
Py_DECREF(class_attr);
}
}
if (!class_name || !module_name) {
return false;
}
snprintf(full_classname_dest, sizeof(full_classname_dest), "%s.%s", module_name, class_name);
}
assert(strncmp("control_msgs.action._gripper_command.GripperCommand_Result", full_classname_dest, 58) == 0);
}
control_msgs__action__GripperCommand_Result * ros_message = _ros_message;
{ // position
PyObject * field = PyObject_GetAttrString(_pymsg, "position");
if (!field) {
return false;
}
assert(PyFloat_Check(field));
ros_message->position = PyFloat_AS_DOUBLE(field);
Py_DECREF(field);
}
{ // effort
PyObject * field = PyObject_GetAttrString(_pymsg, "effort");
if (!field) {
return false;
}
assert(PyFloat_Check(field));
ros_message->effort = PyFloat_AS_DOUBLE(field);
Py_DECREF(field);
}
{ // stalled
PyObject * field = PyObject_GetAttrString(_pymsg, "stalled");
if (!field) {
return false;
}
assert(PyBool_Check(field));
ros_message->stalled = (Py_True == field);
Py_DECREF(field);
}
{ // reached_goal
PyObject * field = PyObject_GetAttrString(_pymsg, "reached_goal");
if (!field) {
return false;
}
assert(PyBool_Check(field));
ros_message->reached_goal = (Py_True == field);
Py_DECREF(field);
}
return true;
}
ROSIDL_GENERATOR_C_EXPORT
PyObject * control_msgs__action__gripper_command__result__convert_to_py(void * raw_ros_message)
{
/* NOTE(esteve): Call constructor of GripperCommand_Result */
PyObject * _pymessage = NULL;
{
PyObject * pymessage_module = PyImport_ImportModule("control_msgs.action._gripper_command");
assert(pymessage_module);
PyObject * pymessage_class = PyObject_GetAttrString(pymessage_module, "GripperCommand_Result");
assert(pymessage_class);
Py_DECREF(pymessage_module);
_pymessage = PyObject_CallObject(pymessage_class, NULL);
Py_DECREF(pymessage_class);
if (!_pymessage) {
return NULL;
}
}
control_msgs__action__GripperCommand_Result * ros_message = (control_msgs__action__GripperCommand_Result *)raw_ros_message;
{ // position
PyObject * field = NULL;
field = PyFloat_FromDouble(ros_message->position);
{
int rc = PyObject_SetAttrString(_pymessage, "position", field);
Py_DECREF(field);
if (rc) {
return NULL;
}
}
}
{ // effort
PyObject * field = NULL;
field = PyFloat_FromDouble(ros_message->effort);
{
int rc = PyObject_SetAttrString(_pymessage, "effort", field);
Py_DECREF(field);
if (rc) {
return NULL;
}
}
}
{ // stalled
PyObject * field = NULL;
field = PyBool_FromLong(ros_message->stalled ? 1 : 0);
{
int rc = PyObject_SetAttrString(_pymessage, "stalled", field);
Py_DECREF(field);
if (rc) {
return NULL;
}
}
}
{ // reached_goal
PyObject * field = NULL;
field = PyBool_FromLong(ros_message->reached_goal ? 1 : 0);
{
int rc = PyObject_SetAttrString(_pymessage, "reached_goal", field);
Py_DECREF(field);
if (rc) {
return NULL;
}
}
}
// ownership of _pymessage is transferred to the caller
return _pymessage;
}
#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION
// already included above
// #include <Python.h>
// already included above
// #include <stdbool.h>
// already included above
// #include "numpy/ndarrayobject.h"
// already included above
// #include "rosidl_runtime_c/visibility_control.h"
// already included above
// #include "control_msgs/action/detail/gripper_command__struct.h"
// already included above
// #include "control_msgs/action/detail/gripper_command__functions.h"
ROSIDL_GENERATOR_C_EXPORT
bool control_msgs__action__gripper_command__feedback__convert_from_py(PyObject * _pymsg, void * _ros_message)
{
// check that the passed message is of the expected Python class
{
char full_classname_dest[61];
{
char * class_name = NULL;
char * module_name = NULL;
{
PyObject * class_attr = PyObject_GetAttrString(_pymsg, "__class__");
if (class_attr) {
PyObject * name_attr = PyObject_GetAttrString(class_attr, "__name__");
if (name_attr) {
class_name = (char *)PyUnicode_1BYTE_DATA(name_attr);
Py_DECREF(name_attr);
}
PyObject * module_attr = PyObject_GetAttrString(class_attr, "__module__");
if (module_attr) {
module_name = (char *)PyUnicode_1BYTE_DATA(module_attr);
Py_DECREF(module_attr);
}
Py_DECREF(class_attr);
}
}
if (!class_name || !module_name) {
return false;
}
snprintf(full_classname_dest, sizeof(full_classname_dest), "%s.%s", module_name, class_name);
}
assert(strncmp("control_msgs.action._gripper_command.GripperCommand_Feedback", full_classname_dest, 60) == 0);
}
control_msgs__action__GripperCommand_Feedback * ros_message = _ros_message;
{ // position
PyObject * field = PyObject_GetAttrString(_pymsg, "position");
if (!field) {
return false;
}
assert(PyFloat_Check(field));
ros_message->position = PyFloat_AS_DOUBLE(field);
Py_DECREF(field);
}
{ // effort
PyObject * field = PyObject_GetAttrString(_pymsg, "effort");
if (!field) {
return false;
}
assert(PyFloat_Check(field));
ros_message->effort = PyFloat_AS_DOUBLE(field);
Py_DECREF(field);
}
{ // stalled
PyObject * field = PyObject_GetAttrString(_pymsg, "stalled");
if (!field) {
return false;
}
assert(PyBool_Check(field));
ros_message->stalled = (Py_True == field);
Py_DECREF(field);
}
{ // reached_goal
PyObject * field = PyObject_GetAttrString(_pymsg, "reached_goal");
if (!field) {
return false;
}
assert(PyBool_Check(field));
ros_message->reached_goal = (Py_True == field);
Py_DECREF(field);
}
return true;
}
ROSIDL_GENERATOR_C_EXPORT
PyObject * control_msgs__action__gripper_command__feedback__convert_to_py(void * raw_ros_message)
{
/* NOTE(esteve): Call constructor of GripperCommand_Feedback */
PyObject * _pymessage = NULL;
{
PyObject * pymessage_module = PyImport_ImportModule("control_msgs.action._gripper_command");
assert(pymessage_module);
PyObject * pymessage_class = PyObject_GetAttrString(pymessage_module, "GripperCommand_Feedback");
assert(pymessage_class);
Py_DECREF(pymessage_module);
_pymessage = PyObject_CallObject(pymessage_class, NULL);
Py_DECREF(pymessage_class);
if (!_pymessage) {
return NULL;
}
}
control_msgs__action__GripperCommand_Feedback * ros_message = (control_msgs__action__GripperCommand_Feedback *)raw_ros_message;
{ // position
PyObject * field = NULL;
field = PyFloat_FromDouble(ros_message->position);
{
int rc = PyObject_SetAttrString(_pymessage, "position", field);
Py_DECREF(field);
if (rc) {
return NULL;
}
}
}
{ // effort
PyObject * field = NULL;
field = PyFloat_FromDouble(ros_message->effort);
{
int rc = PyObject_SetAttrString(_pymessage, "effort", field);
Py_DECREF(field);
if (rc) {
return NULL;
}
}
}
{ // stalled
PyObject * field = NULL;
field = PyBool_FromLong(ros_message->stalled ? 1 : 0);
{
int rc = PyObject_SetAttrString(_pymessage, "stalled", field);
Py_DECREF(field);
if (rc) {
return NULL;
}
}
}
{ // reached_goal
PyObject * field = NULL;
field = PyBool_FromLong(ros_message->reached_goal ? 1 : 0);
{
int rc = PyObject_SetAttrString(_pymessage, "reached_goal", field);
Py_DECREF(field);
if (rc) {
return NULL;
}
}
}
// ownership of _pymessage is transferred to the caller
return _pymessage;
}
#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION
// already included above
// #include <Python.h>
// already included above
// #include <stdbool.h>
// already included above
// #include "numpy/ndarrayobject.h"
// already included above
// #include "rosidl_runtime_c/visibility_control.h"
// already included above
// #include "control_msgs/action/detail/gripper_command__struct.h"
// already included above
// #include "control_msgs/action/detail/gripper_command__functions.h"
ROSIDL_GENERATOR_C_IMPORT
bool unique_identifier_msgs__msg__uuid__convert_from_py(PyObject * _pymsg, void * _ros_message);
ROSIDL_GENERATOR_C_IMPORT
PyObject * unique_identifier_msgs__msg__uuid__convert_to_py(void * raw_ros_message);
bool control_msgs__action__gripper_command__goal__convert_from_py(PyObject * _pymsg, void * _ros_message);
PyObject * control_msgs__action__gripper_command__goal__convert_to_py(void * raw_ros_message);
ROSIDL_GENERATOR_C_EXPORT
bool control_msgs__action__gripper_command__send_goal__request__convert_from_py(PyObject * _pymsg, void * _ros_message)
{
// check that the passed message is of the expected Python class
{
char full_classname_dest[69];
{
char * class_name = NULL;
char * module_name = NULL;
{
PyObject * class_attr = PyObject_GetAttrString(_pymsg, "__class__");
if (class_attr) {
PyObject * name_attr = PyObject_GetAttrString(class_attr, "__name__");
if (name_attr) {
class_name = (char *)PyUnicode_1BYTE_DATA(name_attr);
Py_DECREF(name_attr);
}
PyObject * module_attr = PyObject_GetAttrString(class_attr, "__module__");
if (module_attr) {
module_name = (char *)PyUnicode_1BYTE_DATA(module_attr);
Py_DECREF(module_attr);
}
Py_DECREF(class_attr);
}
}
if (!class_name || !module_name) {
return false;
}
snprintf(full_classname_dest, sizeof(full_classname_dest), "%s.%s", module_name, class_name);
}
assert(strncmp("control_msgs.action._gripper_command.GripperCommand_SendGoal_Request", full_classname_dest, 68) == 0);
}
control_msgs__action__GripperCommand_SendGoal_Request * ros_message = _ros_message;
{ // goal_id
PyObject * field = PyObject_GetAttrString(_pymsg, "goal_id");
if (!field) {
return false;
}
if (!unique_identifier_msgs__msg__uuid__convert_from_py(field, &ros_message->goal_id)) {
Py_DECREF(field);
return false;
}
Py_DECREF(field);
}
{ // goal
PyObject * field = PyObject_GetAttrString(_pymsg, "goal");
if (!field) {
return false;
}
if (!control_msgs__action__gripper_command__goal__convert_from_py(field, &ros_message->goal)) {
Py_DECREF(field);
return false;
}
Py_DECREF(field);
}
return true;
}
ROSIDL_GENERATOR_C_EXPORT
PyObject * control_msgs__action__gripper_command__send_goal__request__convert_to_py(void * raw_ros_message)
{
/* NOTE(esteve): Call constructor of GripperCommand_SendGoal_Request */
PyObject * _pymessage = NULL;
{
PyObject * pymessage_module = PyImport_ImportModule("control_msgs.action._gripper_command");
assert(pymessage_module);
PyObject * pymessage_class = PyObject_GetAttrString(pymessage_module, "GripperCommand_SendGoal_Request");
assert(pymessage_class);
Py_DECREF(pymessage_module);
_pymessage = PyObject_CallObject(pymessage_class, NULL);
Py_DECREF(pymessage_class);
if (!_pymessage) {
return NULL;
}
}
control_msgs__action__GripperCommand_SendGoal_Request * ros_message = (control_msgs__action__GripperCommand_SendGoal_Request *)raw_ros_message;
{ // goal_id
PyObject * field = NULL;
field = unique_identifier_msgs__msg__uuid__convert_to_py(&ros_message->goal_id);
if (!field) {
return NULL;
}
{
int rc = PyObject_SetAttrString(_pymessage, "goal_id", field);
Py_DECREF(field);
if (rc) {
return NULL;
}
}
}
{ // goal
PyObject * field = NULL;
field = control_msgs__action__gripper_command__goal__convert_to_py(&ros_message->goal);
if (!field) {
return NULL;
}
{
int rc = PyObject_SetAttrString(_pymessage, "goal", field);
Py_DECREF(field);
if (rc) {
return NULL;
}
}
}
// ownership of _pymessage is transferred to the caller
return _pymessage;
}
#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION
// already included above
// #include <Python.h>
// already included above
// #include <stdbool.h>
// already included above
// #include "numpy/ndarrayobject.h"
// already included above
// #include "rosidl_runtime_c/visibility_control.h"
// already included above
// #include "control_msgs/action/detail/gripper_command__struct.h"
// already included above
// #include "control_msgs/action/detail/gripper_command__functions.h"
ROSIDL_GENERATOR_C_IMPORT
bool builtin_interfaces__msg__time__convert_from_py(PyObject * _pymsg, void * _ros_message);
ROSIDL_GENERATOR_C_IMPORT
PyObject * builtin_interfaces__msg__time__convert_to_py(void * raw_ros_message);
ROSIDL_GENERATOR_C_EXPORT
bool control_msgs__action__gripper_command__send_goal__response__convert_from_py(PyObject * _pymsg, void * _ros_message)
{
// check that the passed message is of the expected Python class
{
char full_classname_dest[70];
{
char * class_name = NULL;
char * module_name = NULL;
{
PyObject * class_attr = PyObject_GetAttrString(_pymsg, "__class__");
if (class_attr) {
PyObject * name_attr = PyObject_GetAttrString(class_attr, "__name__");
if (name_attr) {
class_name = (char *)PyUnicode_1BYTE_DATA(name_attr);
Py_DECREF(name_attr);
}
PyObject * module_attr = PyObject_GetAttrString(class_attr, "__module__");
if (module_attr) {
module_name = (char *)PyUnicode_1BYTE_DATA(module_attr);
Py_DECREF(module_attr);
}
Py_DECREF(class_attr);
}
}
if (!class_name || !module_name) {
return false;
}
snprintf(full_classname_dest, sizeof(full_classname_dest), "%s.%s", module_name, class_name);
}
assert(strncmp("control_msgs.action._gripper_command.GripperCommand_SendGoal_Response", full_classname_dest, 69) == 0);
}
control_msgs__action__GripperCommand_SendGoal_Response * ros_message = _ros_message;
{ // accepted
PyObject * field = PyObject_GetAttrString(_pymsg, "accepted");
if (!field) {
return false;
}
assert(PyBool_Check(field));
ros_message->accepted = (Py_True == field);
Py_DECREF(field);
}
{ // stamp
PyObject * field = PyObject_GetAttrString(_pymsg, "stamp");
if (!field) {
return false;
}
if (!builtin_interfaces__msg__time__convert_from_py(field, &ros_message->stamp)) {
Py_DECREF(field);
return false;
}
Py_DECREF(field);
}
return true;
}
ROSIDL_GENERATOR_C_EXPORT
PyObject * control_msgs__action__gripper_command__send_goal__response__convert_to_py(void * raw_ros_message)
{
/* NOTE(esteve): Call constructor of GripperCommand_SendGoal_Response */
PyObject * _pymessage = NULL;
{
PyObject * pymessage_module = PyImport_ImportModule("control_msgs.action._gripper_command");
assert(pymessage_module);
PyObject * pymessage_class = PyObject_GetAttrString(pymessage_module, "GripperCommand_SendGoal_Response");
assert(pymessage_class);
Py_DECREF(pymessage_module);
_pymessage = PyObject_CallObject(pymessage_class, NULL);
Py_DECREF(pymessage_class);
if (!_pymessage) {
return NULL;
}
}
control_msgs__action__GripperCommand_SendGoal_Response * ros_message = (control_msgs__action__GripperCommand_SendGoal_Response *)raw_ros_message;
{ // accepted
PyObject * field = NULL;
field = PyBool_FromLong(ros_message->accepted ? 1 : 0);
{
int rc = PyObject_SetAttrString(_pymessage, "accepted", field);
Py_DECREF(field);
if (rc) {
return NULL;
}
}
}
{ // stamp
PyObject * field = NULL;
field = builtin_interfaces__msg__time__convert_to_py(&ros_message->stamp);
if (!field) {
return NULL;
}
{
int rc = PyObject_SetAttrString(_pymessage, "stamp", field);
Py_DECREF(field);
if (rc) {
return NULL;
}
}
}
// ownership of _pymessage is transferred to the caller
return _pymessage;
}
#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION
// already included above
// #include <Python.h>
// already included above
// #include <stdbool.h>
// already included above
// #include "numpy/ndarrayobject.h"
// already included above
// #include "rosidl_runtime_c/visibility_control.h"
// already included above
// #include "control_msgs/action/detail/gripper_command__struct.h"
// already included above
// #include "control_msgs/action/detail/gripper_command__functions.h"
ROSIDL_GENERATOR_C_IMPORT
bool unique_identifier_msgs__msg__uuid__convert_from_py(PyObject * _pymsg, void * _ros_message);
ROSIDL_GENERATOR_C_IMPORT
PyObject * unique_identifier_msgs__msg__uuid__convert_to_py(void * raw_ros_message);
ROSIDL_GENERATOR_C_EXPORT
bool control_msgs__action__gripper_command__get_result__request__convert_from_py(PyObject * _pymsg, void * _ros_message)
{
// check that the passed message is of the expected Python class
{
char full_classname_dest[70];
{
char * class_name = NULL;
char * module_name = NULL;
{
PyObject * class_attr = PyObject_GetAttrString(_pymsg, "__class__");
if (class_attr) {
PyObject * name_attr = PyObject_GetAttrString(class_attr, "__name__");
if (name_attr) {
class_name = (char *)PyUnicode_1BYTE_DATA(name_attr);
Py_DECREF(name_attr);
}
PyObject * module_attr = PyObject_GetAttrString(class_attr, "__module__");
if (module_attr) {
module_name = (char *)PyUnicode_1BYTE_DATA(module_attr);
Py_DECREF(module_attr);
}
Py_DECREF(class_attr);
}
}
if (!class_name || !module_name) {
return false;
}
snprintf(full_classname_dest, sizeof(full_classname_dest), "%s.%s", module_name, class_name);
}
assert(strncmp("control_msgs.action._gripper_command.GripperCommand_GetResult_Request", full_classname_dest, 69) == 0);
}
control_msgs__action__GripperCommand_GetResult_Request * ros_message = _ros_message;
{ // goal_id
PyObject * field = PyObject_GetAttrString(_pymsg, "goal_id");
if (!field) {
return false;
}
if (!unique_identifier_msgs__msg__uuid__convert_from_py(field, &ros_message->goal_id)) {
Py_DECREF(field);
return false;
}
Py_DECREF(field);
}
return true;
}
ROSIDL_GENERATOR_C_EXPORT
PyObject * control_msgs__action__gripper_command__get_result__request__convert_to_py(void * raw_ros_message)
{
/* NOTE(esteve): Call constructor of GripperCommand_GetResult_Request */
PyObject * _pymessage = NULL;
{
PyObject * pymessage_module = PyImport_ImportModule("control_msgs.action._gripper_command");
assert(pymessage_module);
PyObject * pymessage_class = PyObject_GetAttrString(pymessage_module, "GripperCommand_GetResult_Request");
assert(pymessage_class);
Py_DECREF(pymessage_module);
_pymessage = PyObject_CallObject(pymessage_class, NULL);
Py_DECREF(pymessage_class);
if (!_pymessage) {
return NULL;
}
}
control_msgs__action__GripperCommand_GetResult_Request * ros_message = (control_msgs__action__GripperCommand_GetResult_Request *)raw_ros_message;
{ // goal_id
PyObject * field = NULL;
field = unique_identifier_msgs__msg__uuid__convert_to_py(&ros_message->goal_id);
if (!field) {
return NULL;
}
{
int rc = PyObject_SetAttrString(_pymessage, "goal_id", field);
Py_DECREF(field);
if (rc) {
return NULL;
}
}
}
// ownership of _pymessage is transferred to the caller
return _pymessage;
}
#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION
// already included above
// #include <Python.h>
// already included above
// #include <stdbool.h>
// already included above
// #include "numpy/ndarrayobject.h"
// already included above
// #include "rosidl_runtime_c/visibility_control.h"
// already included above
// #include "control_msgs/action/detail/gripper_command__struct.h"
// already included above
// #include "control_msgs/action/detail/gripper_command__functions.h"
bool control_msgs__action__gripper_command__result__convert_from_py(PyObject * _pymsg, void * _ros_message);
PyObject * control_msgs__action__gripper_command__result__convert_to_py(void * raw_ros_message);
ROSIDL_GENERATOR_C_EXPORT
bool control_msgs__action__gripper_command__get_result__response__convert_from_py(PyObject * _pymsg, void * _ros_message)
{
// check that the passed message is of the expected Python class
{
char full_classname_dest[71];
{
char * class_name = NULL;
char * module_name = NULL;
{
PyObject * class_attr = PyObject_GetAttrString(_pymsg, "__class__");
if (class_attr) {
PyObject * name_attr = PyObject_GetAttrString(class_attr, "__name__");
if (name_attr) {
class_name = (char *)PyUnicode_1BYTE_DATA(name_attr);
Py_DECREF(name_attr);
}
PyObject * module_attr = PyObject_GetAttrString(class_attr, "__module__");
if (module_attr) {
module_name = (char *)PyUnicode_1BYTE_DATA(module_attr);
Py_DECREF(module_attr);
}
Py_DECREF(class_attr);
}
}
if (!class_name || !module_name) {
return false;
}
snprintf(full_classname_dest, sizeof(full_classname_dest), "%s.%s", module_name, class_name);
}
assert(strncmp("control_msgs.action._gripper_command.GripperCommand_GetResult_Response", full_classname_dest, 70) == 0);
}
control_msgs__action__GripperCommand_GetResult_Response * ros_message = _ros_message;
{ // status
PyObject * field = PyObject_GetAttrString(_pymsg, "status");
if (!field) {
return false;
}
assert(PyLong_Check(field));
ros_message->status = (int8_t)PyLong_AsLong(field);
Py_DECREF(field);
}
{ // result
PyObject * field = PyObject_GetAttrString(_pymsg, "result");
if (!field) {
return false;
}
if (!control_msgs__action__gripper_command__result__convert_from_py(field, &ros_message->result)) {
Py_DECREF(field);
return false;
}
Py_DECREF(field);
}
return true;
}
ROSIDL_GENERATOR_C_EXPORT
PyObject * control_msgs__action__gripper_command__get_result__response__convert_to_py(void * raw_ros_message)
{
/* NOTE(esteve): Call constructor of GripperCommand_GetResult_Response */
PyObject * _pymessage = NULL;
{
PyObject * pymessage_module = PyImport_ImportModule("control_msgs.action._gripper_command");
assert(pymessage_module);
PyObject * pymessage_class = PyObject_GetAttrString(pymessage_module, "GripperCommand_GetResult_Response");
assert(pymessage_class);
Py_DECREF(pymessage_module);
_pymessage = PyObject_CallObject(pymessage_class, NULL);
Py_DECREF(pymessage_class);
if (!_pymessage) {
return NULL;
}
}
control_msgs__action__GripperCommand_GetResult_Response * ros_message = (control_msgs__action__GripperCommand_GetResult_Response *)raw_ros_message;
{ // status
PyObject * field = NULL;
field = PyLong_FromLong(ros_message->status);
{
int rc = PyObject_SetAttrString(_pymessage, "status", field);
Py_DECREF(field);
if (rc) {
return NULL;
}
}
}
{ // result
PyObject * field = NULL;
field = control_msgs__action__gripper_command__result__convert_to_py(&ros_message->result);
if (!field) {
return NULL;
}
{
int rc = PyObject_SetAttrString(_pymessage, "result", field);
Py_DECREF(field);
if (rc) {
return NULL;
}
}
}
// ownership of _pymessage is transferred to the caller
return _pymessage;
}
#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION
// already included above
// #include <Python.h>
// already included above
// #include <stdbool.h>
// already included above
// #include "numpy/ndarrayobject.h"
// already included above
// #include "rosidl_runtime_c/visibility_control.h"
// already included above
// #include "control_msgs/action/detail/gripper_command__struct.h"
// already included above
// #include "control_msgs/action/detail/gripper_command__functions.h"
ROSIDL_GENERATOR_C_IMPORT
bool unique_identifier_msgs__msg__uuid__convert_from_py(PyObject * _pymsg, void * _ros_message);
ROSIDL_GENERATOR_C_IMPORT
PyObject * unique_identifier_msgs__msg__uuid__convert_to_py(void * raw_ros_message);
bool control_msgs__action__gripper_command__feedback__convert_from_py(PyObject * _pymsg, void * _ros_message);
PyObject * control_msgs__action__gripper_command__feedback__convert_to_py(void * raw_ros_message);
ROSIDL_GENERATOR_C_EXPORT
bool control_msgs__action__gripper_command__feedback_message__convert_from_py(PyObject * _pymsg, void * _ros_message)
{
// check that the passed message is of the expected Python class
{
char full_classname_dest[68];
{
char * class_name = NULL;
char * module_name = NULL;
{
PyObject * class_attr = PyObject_GetAttrString(_pymsg, "__class__");
if (class_attr) {
PyObject * name_attr = PyObject_GetAttrString(class_attr, "__name__");
if (name_attr) {
class_name = (char *)PyUnicode_1BYTE_DATA(name_attr);
Py_DECREF(name_attr);
}
PyObject * module_attr = PyObject_GetAttrString(class_attr, "__module__");
if (module_attr) {
module_name = (char *)PyUnicode_1BYTE_DATA(module_attr);
Py_DECREF(module_attr);
}
Py_DECREF(class_attr);
}
}
if (!class_name || !module_name) {
return false;
}
snprintf(full_classname_dest, sizeof(full_classname_dest), "%s.%s", module_name, class_name);
}
assert(strncmp("control_msgs.action._gripper_command.GripperCommand_FeedbackMessage", full_classname_dest, 67) == 0);
}
control_msgs__action__GripperCommand_FeedbackMessage * ros_message = _ros_message;
{ // goal_id
PyObject * field = PyObject_GetAttrString(_pymsg, "goal_id");
if (!field) {
return false;
}
if (!unique_identifier_msgs__msg__uuid__convert_from_py(field, &ros_message->goal_id)) {
Py_DECREF(field);
return false;
}
Py_DECREF(field);
}
{ // feedback
PyObject * field = PyObject_GetAttrString(_pymsg, "feedback");
if (!field) {
return false;
}
if (!control_msgs__action__gripper_command__feedback__convert_from_py(field, &ros_message->feedback)) {
Py_DECREF(field);
return false;
}
Py_DECREF(field);
}
return true;
}
ROSIDL_GENERATOR_C_EXPORT
PyObject * control_msgs__action__gripper_command__feedback_message__convert_to_py(void * raw_ros_message)
{
/* NOTE(esteve): Call constructor of GripperCommand_FeedbackMessage */
PyObject * _pymessage = NULL;
{
PyObject * pymessage_module = PyImport_ImportModule("control_msgs.action._gripper_command");
assert(pymessage_module);
PyObject * pymessage_class = PyObject_GetAttrString(pymessage_module, "GripperCommand_FeedbackMessage");
assert(pymessage_class);
Py_DECREF(pymessage_module);
_pymessage = PyObject_CallObject(pymessage_class, NULL);
Py_DECREF(pymessage_class);
if (!_pymessage) {
return NULL;
}
}
control_msgs__action__GripperCommand_FeedbackMessage * ros_message = (control_msgs__action__GripperCommand_FeedbackMessage *)raw_ros_message;
{ // goal_id
PyObject * field = NULL;
field = unique_identifier_msgs__msg__uuid__convert_to_py(&ros_message->goal_id);
if (!field) {
return NULL;
}
{
int rc = PyObject_SetAttrString(_pymessage, "goal_id", field);
Py_DECREF(field);
if (rc) {
return NULL;
}
}
}
{ // feedback
PyObject * field = NULL;
field = control_msgs__action__gripper_command__feedback__convert_to_py(&ros_message->feedback);
if (!field) {
return NULL;
}
{
int rc = PyObject_SetAttrString(_pymessage, "feedback", field);
Py_DECREF(field);
if (rc) {
return NULL;
}
}
}
// ownership of _pymessage is transferred to the caller
return _pymessage;
}
| 33,597 | C | 31.682879 | 149 | 0.640414 |
Toni-SM/semu.robotics.ros2_bridge/src/semu.robotics.ros2_bridge/semu/robotics/ros2_bridge/packages/control_msgs/action/_gripper_command.py | # generated from rosidl_generator_py/resource/_idl.py.em
# with input from control_msgs:action/GripperCommand.idl
# generated code does not contain a copyright notice
# Import statements for member types
import rosidl_parser.definition # noqa: E402, I100
class Metaclass_GripperCommand_Goal(type):
"""Metaclass of message 'GripperCommand_Goal'."""
_CREATE_ROS_MESSAGE = None
_CONVERT_FROM_PY = None
_CONVERT_TO_PY = None
_DESTROY_ROS_MESSAGE = None
_TYPE_SUPPORT = None
__constants = {
}
@classmethod
def __import_type_support__(cls):
try:
from rosidl_generator_py import import_type_support
module = import_type_support('control_msgs')
except ImportError:
import logging
import traceback
logger = logging.getLogger(
'control_msgs.action.GripperCommand_Goal')
logger.debug(
'Failed to import needed modules for type support:\n' +
traceback.format_exc())
else:
cls._CREATE_ROS_MESSAGE = module.create_ros_message_msg__action__gripper_command__goal
cls._CONVERT_FROM_PY = module.convert_from_py_msg__action__gripper_command__goal
cls._CONVERT_TO_PY = module.convert_to_py_msg__action__gripper_command__goal
cls._TYPE_SUPPORT = module.type_support_msg__action__gripper_command__goal
cls._DESTROY_ROS_MESSAGE = module.destroy_ros_message_msg__action__gripper_command__goal
from control_msgs.msg import GripperCommand
if GripperCommand.__class__._TYPE_SUPPORT is None:
GripperCommand.__class__.__import_type_support__()
@classmethod
def __prepare__(cls, name, bases, **kwargs):
# list constant names here so that they appear in the help text of
# the message class under "Data and other attributes defined here:"
# as well as populate each message instance
return {
}
class GripperCommand_Goal(metaclass=Metaclass_GripperCommand_Goal):
"""Message class 'GripperCommand_Goal'."""
__slots__ = [
'_command',
]
_fields_and_field_types = {
'command': 'control_msgs/GripperCommand',
}
SLOT_TYPES = (
rosidl_parser.definition.NamespacedType(['control_msgs', 'msg'], 'GripperCommand'), # noqa: E501
)
def __init__(self, **kwargs):
assert all('_' + key in self.__slots__ for key in kwargs.keys()), \
'Invalid arguments passed to constructor: %s' % \
', '.join(sorted(k for k in kwargs.keys() if '_' + k not in self.__slots__))
from control_msgs.msg import GripperCommand
self.command = kwargs.get('command', GripperCommand())
def __repr__(self):
typename = self.__class__.__module__.split('.')
typename.pop()
typename.append(self.__class__.__name__)
args = []
for s, t in zip(self.__slots__, self.SLOT_TYPES):
field = getattr(self, s)
fieldstr = repr(field)
# We use Python array type for fields that can be directly stored
# in them, and "normal" sequences for everything else. If it is
# a type that we store in an array, strip off the 'array' portion.
if (
isinstance(t, rosidl_parser.definition.AbstractSequence) and
isinstance(t.value_type, rosidl_parser.definition.BasicType) and
t.value_type.typename in ['float', 'double', 'int8', 'uint8', 'int16', 'uint16', 'int32', 'uint32', 'int64', 'uint64']
):
if len(field) == 0:
fieldstr = '[]'
else:
assert fieldstr.startswith('array(')
prefix = "array('X', "
suffix = ')'
fieldstr = fieldstr[len(prefix):-len(suffix)]
args.append(s[1:] + '=' + fieldstr)
return '%s(%s)' % ('.'.join(typename), ', '.join(args))
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
if self.command != other.command:
return False
return True
@classmethod
def get_fields_and_field_types(cls):
from copy import copy
return copy(cls._fields_and_field_types)
@property
def command(self):
"""Message field 'command'."""
return self._command
@command.setter
def command(self, value):
if __debug__:
from control_msgs.msg import GripperCommand
assert \
isinstance(value, GripperCommand), \
"The 'command' field must be a sub message of type 'GripperCommand'"
self._command = value
# Import statements for member types
# already imported above
# import rosidl_parser.definition
class Metaclass_GripperCommand_Result(type):
"""Metaclass of message 'GripperCommand_Result'."""
_CREATE_ROS_MESSAGE = None
_CONVERT_FROM_PY = None
_CONVERT_TO_PY = None
_DESTROY_ROS_MESSAGE = None
_TYPE_SUPPORT = None
__constants = {
}
@classmethod
def __import_type_support__(cls):
try:
from rosidl_generator_py import import_type_support
module = import_type_support('control_msgs')
except ImportError:
import logging
import traceback
logger = logging.getLogger(
'control_msgs.action.GripperCommand_Result')
logger.debug(
'Failed to import needed modules for type support:\n' +
traceback.format_exc())
else:
cls._CREATE_ROS_MESSAGE = module.create_ros_message_msg__action__gripper_command__result
cls._CONVERT_FROM_PY = module.convert_from_py_msg__action__gripper_command__result
cls._CONVERT_TO_PY = module.convert_to_py_msg__action__gripper_command__result
cls._TYPE_SUPPORT = module.type_support_msg__action__gripper_command__result
cls._DESTROY_ROS_MESSAGE = module.destroy_ros_message_msg__action__gripper_command__result
@classmethod
def __prepare__(cls, name, bases, **kwargs):
# list constant names here so that they appear in the help text of
# the message class under "Data and other attributes defined here:"
# as well as populate each message instance
return {
}
class GripperCommand_Result(metaclass=Metaclass_GripperCommand_Result):
"""Message class 'GripperCommand_Result'."""
__slots__ = [
'_position',
'_effort',
'_stalled',
'_reached_goal',
]
_fields_and_field_types = {
'position': 'double',
'effort': 'double',
'stalled': 'boolean',
'reached_goal': 'boolean',
}
SLOT_TYPES = (
rosidl_parser.definition.BasicType('double'), # noqa: E501
rosidl_parser.definition.BasicType('double'), # noqa: E501
rosidl_parser.definition.BasicType('boolean'), # noqa: E501
rosidl_parser.definition.BasicType('boolean'), # noqa: E501
)
def __init__(self, **kwargs):
assert all('_' + key in self.__slots__ for key in kwargs.keys()), \
'Invalid arguments passed to constructor: %s' % \
', '.join(sorted(k for k in kwargs.keys() if '_' + k not in self.__slots__))
self.position = kwargs.get('position', float())
self.effort = kwargs.get('effort', float())
self.stalled = kwargs.get('stalled', bool())
self.reached_goal = kwargs.get('reached_goal', bool())
def __repr__(self):
typename = self.__class__.__module__.split('.')
typename.pop()
typename.append(self.__class__.__name__)
args = []
for s, t in zip(self.__slots__, self.SLOT_TYPES):
field = getattr(self, s)
fieldstr = repr(field)
# We use Python array type for fields that can be directly stored
# in them, and "normal" sequences for everything else. If it is
# a type that we store in an array, strip off the 'array' portion.
if (
isinstance(t, rosidl_parser.definition.AbstractSequence) and
isinstance(t.value_type, rosidl_parser.definition.BasicType) and
t.value_type.typename in ['float', 'double', 'int8', 'uint8', 'int16', 'uint16', 'int32', 'uint32', 'int64', 'uint64']
):
if len(field) == 0:
fieldstr = '[]'
else:
assert fieldstr.startswith('array(')
prefix = "array('X', "
suffix = ')'
fieldstr = fieldstr[len(prefix):-len(suffix)]
args.append(s[1:] + '=' + fieldstr)
return '%s(%s)' % ('.'.join(typename), ', '.join(args))
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
if self.position != other.position:
return False
if self.effort != other.effort:
return False
if self.stalled != other.stalled:
return False
if self.reached_goal != other.reached_goal:
return False
return True
@classmethod
def get_fields_and_field_types(cls):
from copy import copy
return copy(cls._fields_and_field_types)
@property
def position(self):
"""Message field 'position'."""
return self._position
@position.setter
def position(self, value):
if __debug__:
assert \
isinstance(value, float), \
"The 'position' field must be of type 'float'"
self._position = value
@property
def effort(self):
"""Message field 'effort'."""
return self._effort
@effort.setter
def effort(self, value):
if __debug__:
assert \
isinstance(value, float), \
"The 'effort' field must be of type 'float'"
self._effort = value
@property
def stalled(self):
"""Message field 'stalled'."""
return self._stalled
@stalled.setter
def stalled(self, value):
if __debug__:
assert \
isinstance(value, bool), \
"The 'stalled' field must be of type 'bool'"
self._stalled = value
@property
def reached_goal(self):
"""Message field 'reached_goal'."""
return self._reached_goal
@reached_goal.setter
def reached_goal(self, value):
if __debug__:
assert \
isinstance(value, bool), \
"The 'reached_goal' field must be of type 'bool'"
self._reached_goal = value
# Import statements for member types
# already imported above
# import rosidl_parser.definition
class Metaclass_GripperCommand_Feedback(type):
"""Metaclass of message 'GripperCommand_Feedback'."""
_CREATE_ROS_MESSAGE = None
_CONVERT_FROM_PY = None
_CONVERT_TO_PY = None
_DESTROY_ROS_MESSAGE = None
_TYPE_SUPPORT = None
__constants = {
}
@classmethod
def __import_type_support__(cls):
try:
from rosidl_generator_py import import_type_support
module = import_type_support('control_msgs')
except ImportError:
import logging
import traceback
logger = logging.getLogger(
'control_msgs.action.GripperCommand_Feedback')
logger.debug(
'Failed to import needed modules for type support:\n' +
traceback.format_exc())
else:
cls._CREATE_ROS_MESSAGE = module.create_ros_message_msg__action__gripper_command__feedback
cls._CONVERT_FROM_PY = module.convert_from_py_msg__action__gripper_command__feedback
cls._CONVERT_TO_PY = module.convert_to_py_msg__action__gripper_command__feedback
cls._TYPE_SUPPORT = module.type_support_msg__action__gripper_command__feedback
cls._DESTROY_ROS_MESSAGE = module.destroy_ros_message_msg__action__gripper_command__feedback
@classmethod
def __prepare__(cls, name, bases, **kwargs):
# list constant names here so that they appear in the help text of
# the message class under "Data and other attributes defined here:"
# as well as populate each message instance
return {
}
class GripperCommand_Feedback(metaclass=Metaclass_GripperCommand_Feedback):
"""Message class 'GripperCommand_Feedback'."""
__slots__ = [
'_position',
'_effort',
'_stalled',
'_reached_goal',
]
_fields_and_field_types = {
'position': 'double',
'effort': 'double',
'stalled': 'boolean',
'reached_goal': 'boolean',
}
SLOT_TYPES = (
rosidl_parser.definition.BasicType('double'), # noqa: E501
rosidl_parser.definition.BasicType('double'), # noqa: E501
rosidl_parser.definition.BasicType('boolean'), # noqa: E501
rosidl_parser.definition.BasicType('boolean'), # noqa: E501
)
def __init__(self, **kwargs):
assert all('_' + key in self.__slots__ for key in kwargs.keys()), \
'Invalid arguments passed to constructor: %s' % \
', '.join(sorted(k for k in kwargs.keys() if '_' + k not in self.__slots__))
self.position = kwargs.get('position', float())
self.effort = kwargs.get('effort', float())
self.stalled = kwargs.get('stalled', bool())
self.reached_goal = kwargs.get('reached_goal', bool())
def __repr__(self):
typename = self.__class__.__module__.split('.')
typename.pop()
typename.append(self.__class__.__name__)
args = []
for s, t in zip(self.__slots__, self.SLOT_TYPES):
field = getattr(self, s)
fieldstr = repr(field)
# We use Python array type for fields that can be directly stored
# in them, and "normal" sequences for everything else. If it is
# a type that we store in an array, strip off the 'array' portion.
if (
isinstance(t, rosidl_parser.definition.AbstractSequence) and
isinstance(t.value_type, rosidl_parser.definition.BasicType) and
t.value_type.typename in ['float', 'double', 'int8', 'uint8', 'int16', 'uint16', 'int32', 'uint32', 'int64', 'uint64']
):
if len(field) == 0:
fieldstr = '[]'
else:
assert fieldstr.startswith('array(')
prefix = "array('X', "
suffix = ')'
fieldstr = fieldstr[len(prefix):-len(suffix)]
args.append(s[1:] + '=' + fieldstr)
return '%s(%s)' % ('.'.join(typename), ', '.join(args))
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
if self.position != other.position:
return False
if self.effort != other.effort:
return False
if self.stalled != other.stalled:
return False
if self.reached_goal != other.reached_goal:
return False
return True
@classmethod
def get_fields_and_field_types(cls):
from copy import copy
return copy(cls._fields_and_field_types)
@property
def position(self):
"""Message field 'position'."""
return self._position
@position.setter
def position(self, value):
if __debug__:
assert \
isinstance(value, float), \
"The 'position' field must be of type 'float'"
self._position = value
@property
def effort(self):
"""Message field 'effort'."""
return self._effort
@effort.setter
def effort(self, value):
if __debug__:
assert \
isinstance(value, float), \
"The 'effort' field must be of type 'float'"
self._effort = value
@property
def stalled(self):
"""Message field 'stalled'."""
return self._stalled
@stalled.setter
def stalled(self, value):
if __debug__:
assert \
isinstance(value, bool), \
"The 'stalled' field must be of type 'bool'"
self._stalled = value
@property
def reached_goal(self):
"""Message field 'reached_goal'."""
return self._reached_goal
@reached_goal.setter
def reached_goal(self, value):
if __debug__:
assert \
isinstance(value, bool), \
"The 'reached_goal' field must be of type 'bool'"
self._reached_goal = value
# Import statements for member types
# already imported above
# import rosidl_parser.definition
class Metaclass_GripperCommand_SendGoal_Request(type):
"""Metaclass of message 'GripperCommand_SendGoal_Request'."""
_CREATE_ROS_MESSAGE = None
_CONVERT_FROM_PY = None
_CONVERT_TO_PY = None
_DESTROY_ROS_MESSAGE = None
_TYPE_SUPPORT = None
__constants = {
}
@classmethod
def __import_type_support__(cls):
try:
from rosidl_generator_py import import_type_support
module = import_type_support('control_msgs')
except ImportError:
import logging
import traceback
logger = logging.getLogger(
'control_msgs.action.GripperCommand_SendGoal_Request')
logger.debug(
'Failed to import needed modules for type support:\n' +
traceback.format_exc())
else:
cls._CREATE_ROS_MESSAGE = module.create_ros_message_msg__action__gripper_command__send_goal__request
cls._CONVERT_FROM_PY = module.convert_from_py_msg__action__gripper_command__send_goal__request
cls._CONVERT_TO_PY = module.convert_to_py_msg__action__gripper_command__send_goal__request
cls._TYPE_SUPPORT = module.type_support_msg__action__gripper_command__send_goal__request
cls._DESTROY_ROS_MESSAGE = module.destroy_ros_message_msg__action__gripper_command__send_goal__request
from control_msgs.action import GripperCommand
if GripperCommand.Goal.__class__._TYPE_SUPPORT is None:
GripperCommand.Goal.__class__.__import_type_support__()
from unique_identifier_msgs.msg import UUID
if UUID.__class__._TYPE_SUPPORT is None:
UUID.__class__.__import_type_support__()
@classmethod
def __prepare__(cls, name, bases, **kwargs):
# list constant names here so that they appear in the help text of
# the message class under "Data and other attributes defined here:"
# as well as populate each message instance
return {
}
class GripperCommand_SendGoal_Request(metaclass=Metaclass_GripperCommand_SendGoal_Request):
"""Message class 'GripperCommand_SendGoal_Request'."""
__slots__ = [
'_goal_id',
'_goal',
]
_fields_and_field_types = {
'goal_id': 'unique_identifier_msgs/UUID',
'goal': 'control_msgs/GripperCommand_Goal',
}
SLOT_TYPES = (
rosidl_parser.definition.NamespacedType(['unique_identifier_msgs', 'msg'], 'UUID'), # noqa: E501
rosidl_parser.definition.NamespacedType(['control_msgs', 'action'], 'GripperCommand_Goal'), # noqa: E501
)
def __init__(self, **kwargs):
assert all('_' + key in self.__slots__ for key in kwargs.keys()), \
'Invalid arguments passed to constructor: %s' % \
', '.join(sorted(k for k in kwargs.keys() if '_' + k not in self.__slots__))
from unique_identifier_msgs.msg import UUID
self.goal_id = kwargs.get('goal_id', UUID())
from control_msgs.action._gripper_command import GripperCommand_Goal
self.goal = kwargs.get('goal', GripperCommand_Goal())
def __repr__(self):
typename = self.__class__.__module__.split('.')
typename.pop()
typename.append(self.__class__.__name__)
args = []
for s, t in zip(self.__slots__, self.SLOT_TYPES):
field = getattr(self, s)
fieldstr = repr(field)
# We use Python array type for fields that can be directly stored
# in them, and "normal" sequences for everything else. If it is
# a type that we store in an array, strip off the 'array' portion.
if (
isinstance(t, rosidl_parser.definition.AbstractSequence) and
isinstance(t.value_type, rosidl_parser.definition.BasicType) and
t.value_type.typename in ['float', 'double', 'int8', 'uint8', 'int16', 'uint16', 'int32', 'uint32', 'int64', 'uint64']
):
if len(field) == 0:
fieldstr = '[]'
else:
assert fieldstr.startswith('array(')
prefix = "array('X', "
suffix = ')'
fieldstr = fieldstr[len(prefix):-len(suffix)]
args.append(s[1:] + '=' + fieldstr)
return '%s(%s)' % ('.'.join(typename), ', '.join(args))
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
if self.goal_id != other.goal_id:
return False
if self.goal != other.goal:
return False
return True
@classmethod
def get_fields_and_field_types(cls):
from copy import copy
return copy(cls._fields_and_field_types)
@property
def goal_id(self):
"""Message field 'goal_id'."""
return self._goal_id
@goal_id.setter
def goal_id(self, value):
if __debug__:
from unique_identifier_msgs.msg import UUID
assert \
isinstance(value, UUID), \
"The 'goal_id' field must be a sub message of type 'UUID'"
self._goal_id = value
@property
def goal(self):
"""Message field 'goal'."""
return self._goal
@goal.setter
def goal(self, value):
if __debug__:
from control_msgs.action._gripper_command import GripperCommand_Goal
assert \
isinstance(value, GripperCommand_Goal), \
"The 'goal' field must be a sub message of type 'GripperCommand_Goal'"
self._goal = value
# Import statements for member types
# already imported above
# import rosidl_parser.definition
class Metaclass_GripperCommand_SendGoal_Response(type):
"""Metaclass of message 'GripperCommand_SendGoal_Response'."""
_CREATE_ROS_MESSAGE = None
_CONVERT_FROM_PY = None
_CONVERT_TO_PY = None
_DESTROY_ROS_MESSAGE = None
_TYPE_SUPPORT = None
__constants = {
}
@classmethod
def __import_type_support__(cls):
try:
from rosidl_generator_py import import_type_support
module = import_type_support('control_msgs')
except ImportError:
import logging
import traceback
logger = logging.getLogger(
'control_msgs.action.GripperCommand_SendGoal_Response')
logger.debug(
'Failed to import needed modules for type support:\n' +
traceback.format_exc())
else:
cls._CREATE_ROS_MESSAGE = module.create_ros_message_msg__action__gripper_command__send_goal__response
cls._CONVERT_FROM_PY = module.convert_from_py_msg__action__gripper_command__send_goal__response
cls._CONVERT_TO_PY = module.convert_to_py_msg__action__gripper_command__send_goal__response
cls._TYPE_SUPPORT = module.type_support_msg__action__gripper_command__send_goal__response
cls._DESTROY_ROS_MESSAGE = module.destroy_ros_message_msg__action__gripper_command__send_goal__response
from builtin_interfaces.msg import Time
if Time.__class__._TYPE_SUPPORT is None:
Time.__class__.__import_type_support__()
@classmethod
def __prepare__(cls, name, bases, **kwargs):
# list constant names here so that they appear in the help text of
# the message class under "Data and other attributes defined here:"
# as well as populate each message instance
return {
}
class GripperCommand_SendGoal_Response(metaclass=Metaclass_GripperCommand_SendGoal_Response):
"""Message class 'GripperCommand_SendGoal_Response'."""
__slots__ = [
'_accepted',
'_stamp',
]
_fields_and_field_types = {
'accepted': 'boolean',
'stamp': 'builtin_interfaces/Time',
}
SLOT_TYPES = (
rosidl_parser.definition.BasicType('boolean'), # noqa: E501
rosidl_parser.definition.NamespacedType(['builtin_interfaces', 'msg'], 'Time'), # noqa: E501
)
def __init__(self, **kwargs):
assert all('_' + key in self.__slots__ for key in kwargs.keys()), \
'Invalid arguments passed to constructor: %s' % \
', '.join(sorted(k for k in kwargs.keys() if '_' + k not in self.__slots__))
self.accepted = kwargs.get('accepted', bool())
from builtin_interfaces.msg import Time
self.stamp = kwargs.get('stamp', Time())
def __repr__(self):
typename = self.__class__.__module__.split('.')
typename.pop()
typename.append(self.__class__.__name__)
args = []
for s, t in zip(self.__slots__, self.SLOT_TYPES):
field = getattr(self, s)
fieldstr = repr(field)
# We use Python array type for fields that can be directly stored
# in them, and "normal" sequences for everything else. If it is
# a type that we store in an array, strip off the 'array' portion.
if (
isinstance(t, rosidl_parser.definition.AbstractSequence) and
isinstance(t.value_type, rosidl_parser.definition.BasicType) and
t.value_type.typename in ['float', 'double', 'int8', 'uint8', 'int16', 'uint16', 'int32', 'uint32', 'int64', 'uint64']
):
if len(field) == 0:
fieldstr = '[]'
else:
assert fieldstr.startswith('array(')
prefix = "array('X', "
suffix = ')'
fieldstr = fieldstr[len(prefix):-len(suffix)]
args.append(s[1:] + '=' + fieldstr)
return '%s(%s)' % ('.'.join(typename), ', '.join(args))
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
if self.accepted != other.accepted:
return False
if self.stamp != other.stamp:
return False
return True
@classmethod
def get_fields_and_field_types(cls):
from copy import copy
return copy(cls._fields_and_field_types)
@property
def accepted(self):
"""Message field 'accepted'."""
return self._accepted
@accepted.setter
def accepted(self, value):
if __debug__:
assert \
isinstance(value, bool), \
"The 'accepted' field must be of type 'bool'"
self._accepted = value
@property
def stamp(self):
"""Message field 'stamp'."""
return self._stamp
@stamp.setter
def stamp(self, value):
if __debug__:
from builtin_interfaces.msg import Time
assert \
isinstance(value, Time), \
"The 'stamp' field must be a sub message of type 'Time'"
self._stamp = value
class Metaclass_GripperCommand_SendGoal(type):
"""Metaclass of service 'GripperCommand_SendGoal'."""
_TYPE_SUPPORT = None
@classmethod
def __import_type_support__(cls):
try:
from rosidl_generator_py import import_type_support
module = import_type_support('control_msgs')
except ImportError:
import logging
import traceback
logger = logging.getLogger(
'control_msgs.action.GripperCommand_SendGoal')
logger.debug(
'Failed to import needed modules for type support:\n' +
traceback.format_exc())
else:
cls._TYPE_SUPPORT = module.type_support_srv__action__gripper_command__send_goal
from control_msgs.action import _gripper_command
if _gripper_command.Metaclass_GripperCommand_SendGoal_Request._TYPE_SUPPORT is None:
_gripper_command.Metaclass_GripperCommand_SendGoal_Request.__import_type_support__()
if _gripper_command.Metaclass_GripperCommand_SendGoal_Response._TYPE_SUPPORT is None:
_gripper_command.Metaclass_GripperCommand_SendGoal_Response.__import_type_support__()
class GripperCommand_SendGoal(metaclass=Metaclass_GripperCommand_SendGoal):
from control_msgs.action._gripper_command import GripperCommand_SendGoal_Request as Request
from control_msgs.action._gripper_command import GripperCommand_SendGoal_Response as Response
def __init__(self):
raise NotImplementedError('Service classes can not be instantiated')
# Import statements for member types
# already imported above
# import rosidl_parser.definition
class Metaclass_GripperCommand_GetResult_Request(type):
"""Metaclass of message 'GripperCommand_GetResult_Request'."""
_CREATE_ROS_MESSAGE = None
_CONVERT_FROM_PY = None
_CONVERT_TO_PY = None
_DESTROY_ROS_MESSAGE = None
_TYPE_SUPPORT = None
__constants = {
}
@classmethod
def __import_type_support__(cls):
try:
from rosidl_generator_py import import_type_support
module = import_type_support('control_msgs')
except ImportError:
import logging
import traceback
logger = logging.getLogger(
'control_msgs.action.GripperCommand_GetResult_Request')
logger.debug(
'Failed to import needed modules for type support:\n' +
traceback.format_exc())
else:
cls._CREATE_ROS_MESSAGE = module.create_ros_message_msg__action__gripper_command__get_result__request
cls._CONVERT_FROM_PY = module.convert_from_py_msg__action__gripper_command__get_result__request
cls._CONVERT_TO_PY = module.convert_to_py_msg__action__gripper_command__get_result__request
cls._TYPE_SUPPORT = module.type_support_msg__action__gripper_command__get_result__request
cls._DESTROY_ROS_MESSAGE = module.destroy_ros_message_msg__action__gripper_command__get_result__request
from unique_identifier_msgs.msg import UUID
if UUID.__class__._TYPE_SUPPORT is None:
UUID.__class__.__import_type_support__()
@classmethod
def __prepare__(cls, name, bases, **kwargs):
# list constant names here so that they appear in the help text of
# the message class under "Data and other attributes defined here:"
# as well as populate each message instance
return {
}
class GripperCommand_GetResult_Request(metaclass=Metaclass_GripperCommand_GetResult_Request):
"""Message class 'GripperCommand_GetResult_Request'."""
__slots__ = [
'_goal_id',
]
_fields_and_field_types = {
'goal_id': 'unique_identifier_msgs/UUID',
}
SLOT_TYPES = (
rosidl_parser.definition.NamespacedType(['unique_identifier_msgs', 'msg'], 'UUID'), # noqa: E501
)
def __init__(self, **kwargs):
assert all('_' + key in self.__slots__ for key in kwargs.keys()), \
'Invalid arguments passed to constructor: %s' % \
', '.join(sorted(k for k in kwargs.keys() if '_' + k not in self.__slots__))
from unique_identifier_msgs.msg import UUID
self.goal_id = kwargs.get('goal_id', UUID())
def __repr__(self):
typename = self.__class__.__module__.split('.')
typename.pop()
typename.append(self.__class__.__name__)
args = []
for s, t in zip(self.__slots__, self.SLOT_TYPES):
field = getattr(self, s)
fieldstr = repr(field)
# We use Python array type for fields that can be directly stored
# in them, and "normal" sequences for everything else. If it is
# a type that we store in an array, strip off the 'array' portion.
if (
isinstance(t, rosidl_parser.definition.AbstractSequence) and
isinstance(t.value_type, rosidl_parser.definition.BasicType) and
t.value_type.typename in ['float', 'double', 'int8', 'uint8', 'int16', 'uint16', 'int32', 'uint32', 'int64', 'uint64']
):
if len(field) == 0:
fieldstr = '[]'
else:
assert fieldstr.startswith('array(')
prefix = "array('X', "
suffix = ')'
fieldstr = fieldstr[len(prefix):-len(suffix)]
args.append(s[1:] + '=' + fieldstr)
return '%s(%s)' % ('.'.join(typename), ', '.join(args))
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
if self.goal_id != other.goal_id:
return False
return True
@classmethod
def get_fields_and_field_types(cls):
from copy import copy
return copy(cls._fields_and_field_types)
@property
def goal_id(self):
"""Message field 'goal_id'."""
return self._goal_id
@goal_id.setter
def goal_id(self, value):
if __debug__:
from unique_identifier_msgs.msg import UUID
assert \
isinstance(value, UUID), \
"The 'goal_id' field must be a sub message of type 'UUID'"
self._goal_id = value
# Import statements for member types
# already imported above
# import rosidl_parser.definition
class Metaclass_GripperCommand_GetResult_Response(type):
"""Metaclass of message 'GripperCommand_GetResult_Response'."""
_CREATE_ROS_MESSAGE = None
_CONVERT_FROM_PY = None
_CONVERT_TO_PY = None
_DESTROY_ROS_MESSAGE = None
_TYPE_SUPPORT = None
__constants = {
}
@classmethod
def __import_type_support__(cls):
try:
from rosidl_generator_py import import_type_support
module = import_type_support('control_msgs')
except ImportError:
import logging
import traceback
logger = logging.getLogger(
'control_msgs.action.GripperCommand_GetResult_Response')
logger.debug(
'Failed to import needed modules for type support:\n' +
traceback.format_exc())
else:
cls._CREATE_ROS_MESSAGE = module.create_ros_message_msg__action__gripper_command__get_result__response
cls._CONVERT_FROM_PY = module.convert_from_py_msg__action__gripper_command__get_result__response
cls._CONVERT_TO_PY = module.convert_to_py_msg__action__gripper_command__get_result__response
cls._TYPE_SUPPORT = module.type_support_msg__action__gripper_command__get_result__response
cls._DESTROY_ROS_MESSAGE = module.destroy_ros_message_msg__action__gripper_command__get_result__response
from control_msgs.action import GripperCommand
if GripperCommand.Result.__class__._TYPE_SUPPORT is None:
GripperCommand.Result.__class__.__import_type_support__()
@classmethod
def __prepare__(cls, name, bases, **kwargs):
# list constant names here so that they appear in the help text of
# the message class under "Data and other attributes defined here:"
# as well as populate each message instance
return {
}
class GripperCommand_GetResult_Response(metaclass=Metaclass_GripperCommand_GetResult_Response):
"""Message class 'GripperCommand_GetResult_Response'."""
__slots__ = [
'_status',
'_result',
]
_fields_and_field_types = {
'status': 'int8',
'result': 'control_msgs/GripperCommand_Result',
}
SLOT_TYPES = (
rosidl_parser.definition.BasicType('int8'), # noqa: E501
rosidl_parser.definition.NamespacedType(['control_msgs', 'action'], 'GripperCommand_Result'), # noqa: E501
)
def __init__(self, **kwargs):
assert all('_' + key in self.__slots__ for key in kwargs.keys()), \
'Invalid arguments passed to constructor: %s' % \
', '.join(sorted(k for k in kwargs.keys() if '_' + k not in self.__slots__))
self.status = kwargs.get('status', int())
from control_msgs.action._gripper_command import GripperCommand_Result
self.result = kwargs.get('result', GripperCommand_Result())
def __repr__(self):
typename = self.__class__.__module__.split('.')
typename.pop()
typename.append(self.__class__.__name__)
args = []
for s, t in zip(self.__slots__, self.SLOT_TYPES):
field = getattr(self, s)
fieldstr = repr(field)
# We use Python array type for fields that can be directly stored
# in them, and "normal" sequences for everything else. If it is
# a type that we store in an array, strip off the 'array' portion.
if (
isinstance(t, rosidl_parser.definition.AbstractSequence) and
isinstance(t.value_type, rosidl_parser.definition.BasicType) and
t.value_type.typename in ['float', 'double', 'int8', 'uint8', 'int16', 'uint16', 'int32', 'uint32', 'int64', 'uint64']
):
if len(field) == 0:
fieldstr = '[]'
else:
assert fieldstr.startswith('array(')
prefix = "array('X', "
suffix = ')'
fieldstr = fieldstr[len(prefix):-len(suffix)]
args.append(s[1:] + '=' + fieldstr)
return '%s(%s)' % ('.'.join(typename), ', '.join(args))
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
if self.status != other.status:
return False
if self.result != other.result:
return False
return True
@classmethod
def get_fields_and_field_types(cls):
from copy import copy
return copy(cls._fields_and_field_types)
@property
def status(self):
"""Message field 'status'."""
return self._status
@status.setter
def status(self, value):
if __debug__:
assert \
isinstance(value, int), \
"The 'status' field must be of type 'int'"
assert value >= -128 and value < 128, \
"The 'status' field must be an integer in [-128, 127]"
self._status = value
@property
def result(self):
"""Message field 'result'."""
return self._result
@result.setter
def result(self, value):
if __debug__:
from control_msgs.action._gripper_command import GripperCommand_Result
assert \
isinstance(value, GripperCommand_Result), \
"The 'result' field must be a sub message of type 'GripperCommand_Result'"
self._result = value
class Metaclass_GripperCommand_GetResult(type):
"""Metaclass of service 'GripperCommand_GetResult'."""
_TYPE_SUPPORT = None
@classmethod
def __import_type_support__(cls):
try:
from rosidl_generator_py import import_type_support
module = import_type_support('control_msgs')
except ImportError:
import logging
import traceback
logger = logging.getLogger(
'control_msgs.action.GripperCommand_GetResult')
logger.debug(
'Failed to import needed modules for type support:\n' +
traceback.format_exc())
else:
cls._TYPE_SUPPORT = module.type_support_srv__action__gripper_command__get_result
from control_msgs.action import _gripper_command
if _gripper_command.Metaclass_GripperCommand_GetResult_Request._TYPE_SUPPORT is None:
_gripper_command.Metaclass_GripperCommand_GetResult_Request.__import_type_support__()
if _gripper_command.Metaclass_GripperCommand_GetResult_Response._TYPE_SUPPORT is None:
_gripper_command.Metaclass_GripperCommand_GetResult_Response.__import_type_support__()
class GripperCommand_GetResult(metaclass=Metaclass_GripperCommand_GetResult):
from control_msgs.action._gripper_command import GripperCommand_GetResult_Request as Request
from control_msgs.action._gripper_command import GripperCommand_GetResult_Response as Response
def __init__(self):
raise NotImplementedError('Service classes can not be instantiated')
# Import statements for member types
# already imported above
# import rosidl_parser.definition
class Metaclass_GripperCommand_FeedbackMessage(type):
"""Metaclass of message 'GripperCommand_FeedbackMessage'."""
_CREATE_ROS_MESSAGE = None
_CONVERT_FROM_PY = None
_CONVERT_TO_PY = None
_DESTROY_ROS_MESSAGE = None
_TYPE_SUPPORT = None
__constants = {
}
@classmethod
def __import_type_support__(cls):
try:
from rosidl_generator_py import import_type_support
module = import_type_support('control_msgs')
except ImportError:
import logging
import traceback
logger = logging.getLogger(
'control_msgs.action.GripperCommand_FeedbackMessage')
logger.debug(
'Failed to import needed modules for type support:\n' +
traceback.format_exc())
else:
cls._CREATE_ROS_MESSAGE = module.create_ros_message_msg__action__gripper_command__feedback_message
cls._CONVERT_FROM_PY = module.convert_from_py_msg__action__gripper_command__feedback_message
cls._CONVERT_TO_PY = module.convert_to_py_msg__action__gripper_command__feedback_message
cls._TYPE_SUPPORT = module.type_support_msg__action__gripper_command__feedback_message
cls._DESTROY_ROS_MESSAGE = module.destroy_ros_message_msg__action__gripper_command__feedback_message
from control_msgs.action import GripperCommand
if GripperCommand.Feedback.__class__._TYPE_SUPPORT is None:
GripperCommand.Feedback.__class__.__import_type_support__()
from unique_identifier_msgs.msg import UUID
if UUID.__class__._TYPE_SUPPORT is None:
UUID.__class__.__import_type_support__()
@classmethod
def __prepare__(cls, name, bases, **kwargs):
# list constant names here so that they appear in the help text of
# the message class under "Data and other attributes defined here:"
# as well as populate each message instance
return {
}
class GripperCommand_FeedbackMessage(metaclass=Metaclass_GripperCommand_FeedbackMessage):
"""Message class 'GripperCommand_FeedbackMessage'."""
__slots__ = [
'_goal_id',
'_feedback',
]
_fields_and_field_types = {
'goal_id': 'unique_identifier_msgs/UUID',
'feedback': 'control_msgs/GripperCommand_Feedback',
}
SLOT_TYPES = (
rosidl_parser.definition.NamespacedType(['unique_identifier_msgs', 'msg'], 'UUID'), # noqa: E501
rosidl_parser.definition.NamespacedType(['control_msgs', 'action'], 'GripperCommand_Feedback'), # noqa: E501
)
def __init__(self, **kwargs):
assert all('_' + key in self.__slots__ for key in kwargs.keys()), \
'Invalid arguments passed to constructor: %s' % \
', '.join(sorted(k for k in kwargs.keys() if '_' + k not in self.__slots__))
from unique_identifier_msgs.msg import UUID
self.goal_id = kwargs.get('goal_id', UUID())
from control_msgs.action._gripper_command import GripperCommand_Feedback
self.feedback = kwargs.get('feedback', GripperCommand_Feedback())
def __repr__(self):
typename = self.__class__.__module__.split('.')
typename.pop()
typename.append(self.__class__.__name__)
args = []
for s, t in zip(self.__slots__, self.SLOT_TYPES):
field = getattr(self, s)
fieldstr = repr(field)
# We use Python array type for fields that can be directly stored
# in them, and "normal" sequences for everything else. If it is
# a type that we store in an array, strip off the 'array' portion.
if (
isinstance(t, rosidl_parser.definition.AbstractSequence) and
isinstance(t.value_type, rosidl_parser.definition.BasicType) and
t.value_type.typename in ['float', 'double', 'int8', 'uint8', 'int16', 'uint16', 'int32', 'uint32', 'int64', 'uint64']
):
if len(field) == 0:
fieldstr = '[]'
else:
assert fieldstr.startswith('array(')
prefix = "array('X', "
suffix = ')'
fieldstr = fieldstr[len(prefix):-len(suffix)]
args.append(s[1:] + '=' + fieldstr)
return '%s(%s)' % ('.'.join(typename), ', '.join(args))
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
if self.goal_id != other.goal_id:
return False
if self.feedback != other.feedback:
return False
return True
@classmethod
def get_fields_and_field_types(cls):
from copy import copy
return copy(cls._fields_and_field_types)
@property
def goal_id(self):
"""Message field 'goal_id'."""
return self._goal_id
@goal_id.setter
def goal_id(self, value):
if __debug__:
from unique_identifier_msgs.msg import UUID
assert \
isinstance(value, UUID), \
"The 'goal_id' field must be a sub message of type 'UUID'"
self._goal_id = value
@property
def feedback(self):
"""Message field 'feedback'."""
return self._feedback
@feedback.setter
def feedback(self, value):
if __debug__:
from control_msgs.action._gripper_command import GripperCommand_Feedback
assert \
isinstance(value, GripperCommand_Feedback), \
"The 'feedback' field must be a sub message of type 'GripperCommand_Feedback'"
self._feedback = value
class Metaclass_GripperCommand(type):
"""Metaclass of action 'GripperCommand'."""
_TYPE_SUPPORT = None
@classmethod
def __import_type_support__(cls):
try:
from rosidl_generator_py import import_type_support
module = import_type_support('control_msgs')
except ImportError:
import logging
import traceback
logger = logging.getLogger(
'control_msgs.action.GripperCommand')
logger.debug(
'Failed to import needed modules for type support:\n' +
traceback.format_exc())
else:
cls._TYPE_SUPPORT = module.type_support_action__action__gripper_command
from action_msgs.msg import _goal_status_array
if _goal_status_array.Metaclass_GoalStatusArray._TYPE_SUPPORT is None:
_goal_status_array.Metaclass_GoalStatusArray.__import_type_support__()
from action_msgs.srv import _cancel_goal
if _cancel_goal.Metaclass_CancelGoal._TYPE_SUPPORT is None:
_cancel_goal.Metaclass_CancelGoal.__import_type_support__()
from control_msgs.action import _gripper_command
if _gripper_command.Metaclass_GripperCommand_SendGoal._TYPE_SUPPORT is None:
_gripper_command.Metaclass_GripperCommand_SendGoal.__import_type_support__()
if _gripper_command.Metaclass_GripperCommand_GetResult._TYPE_SUPPORT is None:
_gripper_command.Metaclass_GripperCommand_GetResult.__import_type_support__()
if _gripper_command.Metaclass_GripperCommand_FeedbackMessage._TYPE_SUPPORT is None:
_gripper_command.Metaclass_GripperCommand_FeedbackMessage.__import_type_support__()
class GripperCommand(metaclass=Metaclass_GripperCommand):
# The goal message defined in the action definition.
from control_msgs.action._gripper_command import GripperCommand_Goal as Goal
# The result message defined in the action definition.
from control_msgs.action._gripper_command import GripperCommand_Result as Result
# The feedback message defined in the action definition.
from control_msgs.action._gripper_command import GripperCommand_Feedback as Feedback
class Impl:
# The send_goal service using a wrapped version of the goal message as a request.
from control_msgs.action._gripper_command import GripperCommand_SendGoal as SendGoalService
# The get_result service using a wrapped version of the result message as a response.
from control_msgs.action._gripper_command import GripperCommand_GetResult as GetResultService
# The feedback message with generic fields which wraps the feedback message.
from control_msgs.action._gripper_command import GripperCommand_FeedbackMessage as FeedbackMessage
# The generic service to cancel a goal.
from action_msgs.srv._cancel_goal import CancelGoal as CancelGoalService
# The generic message for get the status of a goal.
from action_msgs.msg._goal_status_array import GoalStatusArray as GoalStatusMessage
def __init__(self):
raise NotImplementedError('Action classes can not be instantiated')
| 50,417 | Python | 36.653473 | 134 | 0.587718 |
Toni-SM/semu.robotics.ros2_bridge/src/semu.robotics.ros2_bridge/semu/robotics/ros2_bridge/packages/control_msgs/action/_single_joint_position.py | # generated from rosidl_generator_py/resource/_idl.py.em
# with input from control_msgs:action/SingleJointPosition.idl
# generated code does not contain a copyright notice
# Import statements for member types
import rosidl_parser.definition # noqa: E402, I100
class Metaclass_SingleJointPosition_Goal(type):
"""Metaclass of message 'SingleJointPosition_Goal'."""
_CREATE_ROS_MESSAGE = None
_CONVERT_FROM_PY = None
_CONVERT_TO_PY = None
_DESTROY_ROS_MESSAGE = None
_TYPE_SUPPORT = None
__constants = {
}
@classmethod
def __import_type_support__(cls):
try:
from rosidl_generator_py import import_type_support
module = import_type_support('control_msgs')
except ImportError:
import logging
import traceback
logger = logging.getLogger(
'control_msgs.action.SingleJointPosition_Goal')
logger.debug(
'Failed to import needed modules for type support:\n' +
traceback.format_exc())
else:
cls._CREATE_ROS_MESSAGE = module.create_ros_message_msg__action__single_joint_position__goal
cls._CONVERT_FROM_PY = module.convert_from_py_msg__action__single_joint_position__goal
cls._CONVERT_TO_PY = module.convert_to_py_msg__action__single_joint_position__goal
cls._TYPE_SUPPORT = module.type_support_msg__action__single_joint_position__goal
cls._DESTROY_ROS_MESSAGE = module.destroy_ros_message_msg__action__single_joint_position__goal
from builtin_interfaces.msg import Duration
if Duration.__class__._TYPE_SUPPORT is None:
Duration.__class__.__import_type_support__()
@classmethod
def __prepare__(cls, name, bases, **kwargs):
# list constant names here so that they appear in the help text of
# the message class under "Data and other attributes defined here:"
# as well as populate each message instance
return {
}
class SingleJointPosition_Goal(metaclass=Metaclass_SingleJointPosition_Goal):
"""Message class 'SingleJointPosition_Goal'."""
__slots__ = [
'_position',
'_min_duration',
'_max_velocity',
]
_fields_and_field_types = {
'position': 'double',
'min_duration': 'builtin_interfaces/Duration',
'max_velocity': 'double',
}
SLOT_TYPES = (
rosidl_parser.definition.BasicType('double'), # noqa: E501
rosidl_parser.definition.NamespacedType(['builtin_interfaces', 'msg'], 'Duration'), # noqa: E501
rosidl_parser.definition.BasicType('double'), # noqa: E501
)
def __init__(self, **kwargs):
assert all('_' + key in self.__slots__ for key in kwargs.keys()), \
'Invalid arguments passed to constructor: %s' % \
', '.join(sorted(k for k in kwargs.keys() if '_' + k not in self.__slots__))
self.position = kwargs.get('position', float())
from builtin_interfaces.msg import Duration
self.min_duration = kwargs.get('min_duration', Duration())
self.max_velocity = kwargs.get('max_velocity', float())
def __repr__(self):
typename = self.__class__.__module__.split('.')
typename.pop()
typename.append(self.__class__.__name__)
args = []
for s, t in zip(self.__slots__, self.SLOT_TYPES):
field = getattr(self, s)
fieldstr = repr(field)
# We use Python array type for fields that can be directly stored
# in them, and "normal" sequences for everything else. If it is
# a type that we store in an array, strip off the 'array' portion.
if (
isinstance(t, rosidl_parser.definition.AbstractSequence) and
isinstance(t.value_type, rosidl_parser.definition.BasicType) and
t.value_type.typename in ['float', 'double', 'int8', 'uint8', 'int16', 'uint16', 'int32', 'uint32', 'int64', 'uint64']
):
if len(field) == 0:
fieldstr = '[]'
else:
assert fieldstr.startswith('array(')
prefix = "array('X', "
suffix = ')'
fieldstr = fieldstr[len(prefix):-len(suffix)]
args.append(s[1:] + '=' + fieldstr)
return '%s(%s)' % ('.'.join(typename), ', '.join(args))
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
if self.position != other.position:
return False
if self.min_duration != other.min_duration:
return False
if self.max_velocity != other.max_velocity:
return False
return True
@classmethod
def get_fields_and_field_types(cls):
from copy import copy
return copy(cls._fields_and_field_types)
@property
def position(self):
"""Message field 'position'."""
return self._position
@position.setter
def position(self, value):
if __debug__:
assert \
isinstance(value, float), \
"The 'position' field must be of type 'float'"
self._position = value
@property
def min_duration(self):
"""Message field 'min_duration'."""
return self._min_duration
@min_duration.setter
def min_duration(self, value):
if __debug__:
from builtin_interfaces.msg import Duration
assert \
isinstance(value, Duration), \
"The 'min_duration' field must be a sub message of type 'Duration'"
self._min_duration = value
@property
def max_velocity(self):
"""Message field 'max_velocity'."""
return self._max_velocity
@max_velocity.setter
def max_velocity(self, value):
if __debug__:
assert \
isinstance(value, float), \
"The 'max_velocity' field must be of type 'float'"
self._max_velocity = value
# Import statements for member types
# already imported above
# import rosidl_parser.definition
class Metaclass_SingleJointPosition_Result(type):
"""Metaclass of message 'SingleJointPosition_Result'."""
_CREATE_ROS_MESSAGE = None
_CONVERT_FROM_PY = None
_CONVERT_TO_PY = None
_DESTROY_ROS_MESSAGE = None
_TYPE_SUPPORT = None
__constants = {
}
@classmethod
def __import_type_support__(cls):
try:
from rosidl_generator_py import import_type_support
module = import_type_support('control_msgs')
except ImportError:
import logging
import traceback
logger = logging.getLogger(
'control_msgs.action.SingleJointPosition_Result')
logger.debug(
'Failed to import needed modules for type support:\n' +
traceback.format_exc())
else:
cls._CREATE_ROS_MESSAGE = module.create_ros_message_msg__action__single_joint_position__result
cls._CONVERT_FROM_PY = module.convert_from_py_msg__action__single_joint_position__result
cls._CONVERT_TO_PY = module.convert_to_py_msg__action__single_joint_position__result
cls._TYPE_SUPPORT = module.type_support_msg__action__single_joint_position__result
cls._DESTROY_ROS_MESSAGE = module.destroy_ros_message_msg__action__single_joint_position__result
@classmethod
def __prepare__(cls, name, bases, **kwargs):
# list constant names here so that they appear in the help text of
# the message class under "Data and other attributes defined here:"
# as well as populate each message instance
return {
}
class SingleJointPosition_Result(metaclass=Metaclass_SingleJointPosition_Result):
"""Message class 'SingleJointPosition_Result'."""
__slots__ = [
]
_fields_and_field_types = {
}
SLOT_TYPES = (
)
def __init__(self, **kwargs):
assert all('_' + key in self.__slots__ for key in kwargs.keys()), \
'Invalid arguments passed to constructor: %s' % \
', '.join(sorted(k for k in kwargs.keys() if '_' + k not in self.__slots__))
def __repr__(self):
typename = self.__class__.__module__.split('.')
typename.pop()
typename.append(self.__class__.__name__)
args = []
for s, t in zip(self.__slots__, self.SLOT_TYPES):
field = getattr(self, s)
fieldstr = repr(field)
# We use Python array type for fields that can be directly stored
# in them, and "normal" sequences for everything else. If it is
# a type that we store in an array, strip off the 'array' portion.
if (
isinstance(t, rosidl_parser.definition.AbstractSequence) and
isinstance(t.value_type, rosidl_parser.definition.BasicType) and
t.value_type.typename in ['float', 'double', 'int8', 'uint8', 'int16', 'uint16', 'int32', 'uint32', 'int64', 'uint64']
):
if len(field) == 0:
fieldstr = '[]'
else:
assert fieldstr.startswith('array(')
prefix = "array('X', "
suffix = ')'
fieldstr = fieldstr[len(prefix):-len(suffix)]
args.append(s[1:] + '=' + fieldstr)
return '%s(%s)' % ('.'.join(typename), ', '.join(args))
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
return True
@classmethod
def get_fields_and_field_types(cls):
from copy import copy
return copy(cls._fields_and_field_types)
# Import statements for member types
# already imported above
# import rosidl_parser.definition
class Metaclass_SingleJointPosition_Feedback(type):
"""Metaclass of message 'SingleJointPosition_Feedback'."""
_CREATE_ROS_MESSAGE = None
_CONVERT_FROM_PY = None
_CONVERT_TO_PY = None
_DESTROY_ROS_MESSAGE = None
_TYPE_SUPPORT = None
__constants = {
}
@classmethod
def __import_type_support__(cls):
try:
from rosidl_generator_py import import_type_support
module = import_type_support('control_msgs')
except ImportError:
import logging
import traceback
logger = logging.getLogger(
'control_msgs.action.SingleJointPosition_Feedback')
logger.debug(
'Failed to import needed modules for type support:\n' +
traceback.format_exc())
else:
cls._CREATE_ROS_MESSAGE = module.create_ros_message_msg__action__single_joint_position__feedback
cls._CONVERT_FROM_PY = module.convert_from_py_msg__action__single_joint_position__feedback
cls._CONVERT_TO_PY = module.convert_to_py_msg__action__single_joint_position__feedback
cls._TYPE_SUPPORT = module.type_support_msg__action__single_joint_position__feedback
cls._DESTROY_ROS_MESSAGE = module.destroy_ros_message_msg__action__single_joint_position__feedback
from std_msgs.msg import Header
if Header.__class__._TYPE_SUPPORT is None:
Header.__class__.__import_type_support__()
@classmethod
def __prepare__(cls, name, bases, **kwargs):
# list constant names here so that they appear in the help text of
# the message class under "Data and other attributes defined here:"
# as well as populate each message instance
return {
}
class SingleJointPosition_Feedback(metaclass=Metaclass_SingleJointPosition_Feedback):
"""Message class 'SingleJointPosition_Feedback'."""
__slots__ = [
'_header',
'_position',
'_velocity',
'_error',
]
_fields_and_field_types = {
'header': 'std_msgs/Header',
'position': 'double',
'velocity': 'double',
'error': 'double',
}
SLOT_TYPES = (
rosidl_parser.definition.NamespacedType(['std_msgs', 'msg'], 'Header'), # noqa: E501
rosidl_parser.definition.BasicType('double'), # noqa: E501
rosidl_parser.definition.BasicType('double'), # noqa: E501
rosidl_parser.definition.BasicType('double'), # noqa: E501
)
def __init__(self, **kwargs):
assert all('_' + key in self.__slots__ for key in kwargs.keys()), \
'Invalid arguments passed to constructor: %s' % \
', '.join(sorted(k for k in kwargs.keys() if '_' + k not in self.__slots__))
from std_msgs.msg import Header
self.header = kwargs.get('header', Header())
self.position = kwargs.get('position', float())
self.velocity = kwargs.get('velocity', float())
self.error = kwargs.get('error', float())
def __repr__(self):
typename = self.__class__.__module__.split('.')
typename.pop()
typename.append(self.__class__.__name__)
args = []
for s, t in zip(self.__slots__, self.SLOT_TYPES):
field = getattr(self, s)
fieldstr = repr(field)
# We use Python array type for fields that can be directly stored
# in them, and "normal" sequences for everything else. If it is
# a type that we store in an array, strip off the 'array' portion.
if (
isinstance(t, rosidl_parser.definition.AbstractSequence) and
isinstance(t.value_type, rosidl_parser.definition.BasicType) and
t.value_type.typename in ['float', 'double', 'int8', 'uint8', 'int16', 'uint16', 'int32', 'uint32', 'int64', 'uint64']
):
if len(field) == 0:
fieldstr = '[]'
else:
assert fieldstr.startswith('array(')
prefix = "array('X', "
suffix = ')'
fieldstr = fieldstr[len(prefix):-len(suffix)]
args.append(s[1:] + '=' + fieldstr)
return '%s(%s)' % ('.'.join(typename), ', '.join(args))
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
if self.header != other.header:
return False
if self.position != other.position:
return False
if self.velocity != other.velocity:
return False
if self.error != other.error:
return False
return True
@classmethod
def get_fields_and_field_types(cls):
from copy import copy
return copy(cls._fields_and_field_types)
@property
def header(self):
"""Message field 'header'."""
return self._header
@header.setter
def header(self, value):
if __debug__:
from std_msgs.msg import Header
assert \
isinstance(value, Header), \
"The 'header' field must be a sub message of type 'Header'"
self._header = value
@property
def position(self):
"""Message field 'position'."""
return self._position
@position.setter
def position(self, value):
if __debug__:
assert \
isinstance(value, float), \
"The 'position' field must be of type 'float'"
self._position = value
@property
def velocity(self):
"""Message field 'velocity'."""
return self._velocity
@velocity.setter
def velocity(self, value):
if __debug__:
assert \
isinstance(value, float), \
"The 'velocity' field must be of type 'float'"
self._velocity = value
@property
def error(self):
"""Message field 'error'."""
return self._error
@error.setter
def error(self, value):
if __debug__:
assert \
isinstance(value, float), \
"The 'error' field must be of type 'float'"
self._error = value
# Import statements for member types
# already imported above
# import rosidl_parser.definition
class Metaclass_SingleJointPosition_SendGoal_Request(type):
"""Metaclass of message 'SingleJointPosition_SendGoal_Request'."""
_CREATE_ROS_MESSAGE = None
_CONVERT_FROM_PY = None
_CONVERT_TO_PY = None
_DESTROY_ROS_MESSAGE = None
_TYPE_SUPPORT = None
__constants = {
}
@classmethod
def __import_type_support__(cls):
try:
from rosidl_generator_py import import_type_support
module = import_type_support('control_msgs')
except ImportError:
import logging
import traceback
logger = logging.getLogger(
'control_msgs.action.SingleJointPosition_SendGoal_Request')
logger.debug(
'Failed to import needed modules for type support:\n' +
traceback.format_exc())
else:
cls._CREATE_ROS_MESSAGE = module.create_ros_message_msg__action__single_joint_position__send_goal__request
cls._CONVERT_FROM_PY = module.convert_from_py_msg__action__single_joint_position__send_goal__request
cls._CONVERT_TO_PY = module.convert_to_py_msg__action__single_joint_position__send_goal__request
cls._TYPE_SUPPORT = module.type_support_msg__action__single_joint_position__send_goal__request
cls._DESTROY_ROS_MESSAGE = module.destroy_ros_message_msg__action__single_joint_position__send_goal__request
from control_msgs.action import SingleJointPosition
if SingleJointPosition.Goal.__class__._TYPE_SUPPORT is None:
SingleJointPosition.Goal.__class__.__import_type_support__()
from unique_identifier_msgs.msg import UUID
if UUID.__class__._TYPE_SUPPORT is None:
UUID.__class__.__import_type_support__()
@classmethod
def __prepare__(cls, name, bases, **kwargs):
# list constant names here so that they appear in the help text of
# the message class under "Data and other attributes defined here:"
# as well as populate each message instance
return {
}
class SingleJointPosition_SendGoal_Request(metaclass=Metaclass_SingleJointPosition_SendGoal_Request):
"""Message class 'SingleJointPosition_SendGoal_Request'."""
__slots__ = [
'_goal_id',
'_goal',
]
_fields_and_field_types = {
'goal_id': 'unique_identifier_msgs/UUID',
'goal': 'control_msgs/SingleJointPosition_Goal',
}
SLOT_TYPES = (
rosidl_parser.definition.NamespacedType(['unique_identifier_msgs', 'msg'], 'UUID'), # noqa: E501
rosidl_parser.definition.NamespacedType(['control_msgs', 'action'], 'SingleJointPosition_Goal'), # noqa: E501
)
def __init__(self, **kwargs):
assert all('_' + key in self.__slots__ for key in kwargs.keys()), \
'Invalid arguments passed to constructor: %s' % \
', '.join(sorted(k for k in kwargs.keys() if '_' + k not in self.__slots__))
from unique_identifier_msgs.msg import UUID
self.goal_id = kwargs.get('goal_id', UUID())
from control_msgs.action._single_joint_position import SingleJointPosition_Goal
self.goal = kwargs.get('goal', SingleJointPosition_Goal())
def __repr__(self):
typename = self.__class__.__module__.split('.')
typename.pop()
typename.append(self.__class__.__name__)
args = []
for s, t in zip(self.__slots__, self.SLOT_TYPES):
field = getattr(self, s)
fieldstr = repr(field)
# We use Python array type for fields that can be directly stored
# in them, and "normal" sequences for everything else. If it is
# a type that we store in an array, strip off the 'array' portion.
if (
isinstance(t, rosidl_parser.definition.AbstractSequence) and
isinstance(t.value_type, rosidl_parser.definition.BasicType) and
t.value_type.typename in ['float', 'double', 'int8', 'uint8', 'int16', 'uint16', 'int32', 'uint32', 'int64', 'uint64']
):
if len(field) == 0:
fieldstr = '[]'
else:
assert fieldstr.startswith('array(')
prefix = "array('X', "
suffix = ')'
fieldstr = fieldstr[len(prefix):-len(suffix)]
args.append(s[1:] + '=' + fieldstr)
return '%s(%s)' % ('.'.join(typename), ', '.join(args))
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
if self.goal_id != other.goal_id:
return False
if self.goal != other.goal:
return False
return True
@classmethod
def get_fields_and_field_types(cls):
from copy import copy
return copy(cls._fields_and_field_types)
@property
def goal_id(self):
"""Message field 'goal_id'."""
return self._goal_id
@goal_id.setter
def goal_id(self, value):
if __debug__:
from unique_identifier_msgs.msg import UUID
assert \
isinstance(value, UUID), \
"The 'goal_id' field must be a sub message of type 'UUID'"
self._goal_id = value
@property
def goal(self):
"""Message field 'goal'."""
return self._goal
@goal.setter
def goal(self, value):
if __debug__:
from control_msgs.action._single_joint_position import SingleJointPosition_Goal
assert \
isinstance(value, SingleJointPosition_Goal), \
"The 'goal' field must be a sub message of type 'SingleJointPosition_Goal'"
self._goal = value
# Import statements for member types
# already imported above
# import rosidl_parser.definition
class Metaclass_SingleJointPosition_SendGoal_Response(type):
"""Metaclass of message 'SingleJointPosition_SendGoal_Response'."""
_CREATE_ROS_MESSAGE = None
_CONVERT_FROM_PY = None
_CONVERT_TO_PY = None
_DESTROY_ROS_MESSAGE = None
_TYPE_SUPPORT = None
__constants = {
}
@classmethod
def __import_type_support__(cls):
try:
from rosidl_generator_py import import_type_support
module = import_type_support('control_msgs')
except ImportError:
import logging
import traceback
logger = logging.getLogger(
'control_msgs.action.SingleJointPosition_SendGoal_Response')
logger.debug(
'Failed to import needed modules for type support:\n' +
traceback.format_exc())
else:
cls._CREATE_ROS_MESSAGE = module.create_ros_message_msg__action__single_joint_position__send_goal__response
cls._CONVERT_FROM_PY = module.convert_from_py_msg__action__single_joint_position__send_goal__response
cls._CONVERT_TO_PY = module.convert_to_py_msg__action__single_joint_position__send_goal__response
cls._TYPE_SUPPORT = module.type_support_msg__action__single_joint_position__send_goal__response
cls._DESTROY_ROS_MESSAGE = module.destroy_ros_message_msg__action__single_joint_position__send_goal__response
from builtin_interfaces.msg import Time
if Time.__class__._TYPE_SUPPORT is None:
Time.__class__.__import_type_support__()
@classmethod
def __prepare__(cls, name, bases, **kwargs):
# list constant names here so that they appear in the help text of
# the message class under "Data and other attributes defined here:"
# as well as populate each message instance
return {
}
class SingleJointPosition_SendGoal_Response(metaclass=Metaclass_SingleJointPosition_SendGoal_Response):
"""Message class 'SingleJointPosition_SendGoal_Response'."""
__slots__ = [
'_accepted',
'_stamp',
]
_fields_and_field_types = {
'accepted': 'boolean',
'stamp': 'builtin_interfaces/Time',
}
SLOT_TYPES = (
rosidl_parser.definition.BasicType('boolean'), # noqa: E501
rosidl_parser.definition.NamespacedType(['builtin_interfaces', 'msg'], 'Time'), # noqa: E501
)
def __init__(self, **kwargs):
assert all('_' + key in self.__slots__ for key in kwargs.keys()), \
'Invalid arguments passed to constructor: %s' % \
', '.join(sorted(k for k in kwargs.keys() if '_' + k not in self.__slots__))
self.accepted = kwargs.get('accepted', bool())
from builtin_interfaces.msg import Time
self.stamp = kwargs.get('stamp', Time())
def __repr__(self):
typename = self.__class__.__module__.split('.')
typename.pop()
typename.append(self.__class__.__name__)
args = []
for s, t in zip(self.__slots__, self.SLOT_TYPES):
field = getattr(self, s)
fieldstr = repr(field)
# We use Python array type for fields that can be directly stored
# in them, and "normal" sequences for everything else. If it is
# a type that we store in an array, strip off the 'array' portion.
if (
isinstance(t, rosidl_parser.definition.AbstractSequence) and
isinstance(t.value_type, rosidl_parser.definition.BasicType) and
t.value_type.typename in ['float', 'double', 'int8', 'uint8', 'int16', 'uint16', 'int32', 'uint32', 'int64', 'uint64']
):
if len(field) == 0:
fieldstr = '[]'
else:
assert fieldstr.startswith('array(')
prefix = "array('X', "
suffix = ')'
fieldstr = fieldstr[len(prefix):-len(suffix)]
args.append(s[1:] + '=' + fieldstr)
return '%s(%s)' % ('.'.join(typename), ', '.join(args))
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
if self.accepted != other.accepted:
return False
if self.stamp != other.stamp:
return False
return True
@classmethod
def get_fields_and_field_types(cls):
from copy import copy
return copy(cls._fields_and_field_types)
@property
def accepted(self):
"""Message field 'accepted'."""
return self._accepted
@accepted.setter
def accepted(self, value):
if __debug__:
assert \
isinstance(value, bool), \
"The 'accepted' field must be of type 'bool'"
self._accepted = value
@property
def stamp(self):
"""Message field 'stamp'."""
return self._stamp
@stamp.setter
def stamp(self, value):
if __debug__:
from builtin_interfaces.msg import Time
assert \
isinstance(value, Time), \
"The 'stamp' field must be a sub message of type 'Time'"
self._stamp = value
class Metaclass_SingleJointPosition_SendGoal(type):
"""Metaclass of service 'SingleJointPosition_SendGoal'."""
_TYPE_SUPPORT = None
@classmethod
def __import_type_support__(cls):
try:
from rosidl_generator_py import import_type_support
module = import_type_support('control_msgs')
except ImportError:
import logging
import traceback
logger = logging.getLogger(
'control_msgs.action.SingleJointPosition_SendGoal')
logger.debug(
'Failed to import needed modules for type support:\n' +
traceback.format_exc())
else:
cls._TYPE_SUPPORT = module.type_support_srv__action__single_joint_position__send_goal
from control_msgs.action import _single_joint_position
if _single_joint_position.Metaclass_SingleJointPosition_SendGoal_Request._TYPE_SUPPORT is None:
_single_joint_position.Metaclass_SingleJointPosition_SendGoal_Request.__import_type_support__()
if _single_joint_position.Metaclass_SingleJointPosition_SendGoal_Response._TYPE_SUPPORT is None:
_single_joint_position.Metaclass_SingleJointPosition_SendGoal_Response.__import_type_support__()
class SingleJointPosition_SendGoal(metaclass=Metaclass_SingleJointPosition_SendGoal):
from control_msgs.action._single_joint_position import SingleJointPosition_SendGoal_Request as Request
from control_msgs.action._single_joint_position import SingleJointPosition_SendGoal_Response as Response
def __init__(self):
raise NotImplementedError('Service classes can not be instantiated')
# Import statements for member types
# already imported above
# import rosidl_parser.definition
class Metaclass_SingleJointPosition_GetResult_Request(type):
"""Metaclass of message 'SingleJointPosition_GetResult_Request'."""
_CREATE_ROS_MESSAGE = None
_CONVERT_FROM_PY = None
_CONVERT_TO_PY = None
_DESTROY_ROS_MESSAGE = None
_TYPE_SUPPORT = None
__constants = {
}
@classmethod
def __import_type_support__(cls):
try:
from rosidl_generator_py import import_type_support
module = import_type_support('control_msgs')
except ImportError:
import logging
import traceback
logger = logging.getLogger(
'control_msgs.action.SingleJointPosition_GetResult_Request')
logger.debug(
'Failed to import needed modules for type support:\n' +
traceback.format_exc())
else:
cls._CREATE_ROS_MESSAGE = module.create_ros_message_msg__action__single_joint_position__get_result__request
cls._CONVERT_FROM_PY = module.convert_from_py_msg__action__single_joint_position__get_result__request
cls._CONVERT_TO_PY = module.convert_to_py_msg__action__single_joint_position__get_result__request
cls._TYPE_SUPPORT = module.type_support_msg__action__single_joint_position__get_result__request
cls._DESTROY_ROS_MESSAGE = module.destroy_ros_message_msg__action__single_joint_position__get_result__request
from unique_identifier_msgs.msg import UUID
if UUID.__class__._TYPE_SUPPORT is None:
UUID.__class__.__import_type_support__()
@classmethod
def __prepare__(cls, name, bases, **kwargs):
# list constant names here so that they appear in the help text of
# the message class under "Data and other attributes defined here:"
# as well as populate each message instance
return {
}
class SingleJointPosition_GetResult_Request(metaclass=Metaclass_SingleJointPosition_GetResult_Request):
"""Message class 'SingleJointPosition_GetResult_Request'."""
__slots__ = [
'_goal_id',
]
_fields_and_field_types = {
'goal_id': 'unique_identifier_msgs/UUID',
}
SLOT_TYPES = (
rosidl_parser.definition.NamespacedType(['unique_identifier_msgs', 'msg'], 'UUID'), # noqa: E501
)
def __init__(self, **kwargs):
assert all('_' + key in self.__slots__ for key in kwargs.keys()), \
'Invalid arguments passed to constructor: %s' % \
', '.join(sorted(k for k in kwargs.keys() if '_' + k not in self.__slots__))
from unique_identifier_msgs.msg import UUID
self.goal_id = kwargs.get('goal_id', UUID())
def __repr__(self):
typename = self.__class__.__module__.split('.')
typename.pop()
typename.append(self.__class__.__name__)
args = []
for s, t in zip(self.__slots__, self.SLOT_TYPES):
field = getattr(self, s)
fieldstr = repr(field)
# We use Python array type for fields that can be directly stored
# in them, and "normal" sequences for everything else. If it is
# a type that we store in an array, strip off the 'array' portion.
if (
isinstance(t, rosidl_parser.definition.AbstractSequence) and
isinstance(t.value_type, rosidl_parser.definition.BasicType) and
t.value_type.typename in ['float', 'double', 'int8', 'uint8', 'int16', 'uint16', 'int32', 'uint32', 'int64', 'uint64']
):
if len(field) == 0:
fieldstr = '[]'
else:
assert fieldstr.startswith('array(')
prefix = "array('X', "
suffix = ')'
fieldstr = fieldstr[len(prefix):-len(suffix)]
args.append(s[1:] + '=' + fieldstr)
return '%s(%s)' % ('.'.join(typename), ', '.join(args))
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
if self.goal_id != other.goal_id:
return False
return True
@classmethod
def get_fields_and_field_types(cls):
from copy import copy
return copy(cls._fields_and_field_types)
@property
def goal_id(self):
"""Message field 'goal_id'."""
return self._goal_id
@goal_id.setter
def goal_id(self, value):
if __debug__:
from unique_identifier_msgs.msg import UUID
assert \
isinstance(value, UUID), \
"The 'goal_id' field must be a sub message of type 'UUID'"
self._goal_id = value
# Import statements for member types
# already imported above
# import rosidl_parser.definition
class Metaclass_SingleJointPosition_GetResult_Response(type):
"""Metaclass of message 'SingleJointPosition_GetResult_Response'."""
_CREATE_ROS_MESSAGE = None
_CONVERT_FROM_PY = None
_CONVERT_TO_PY = None
_DESTROY_ROS_MESSAGE = None
_TYPE_SUPPORT = None
__constants = {
}
@classmethod
def __import_type_support__(cls):
try:
from rosidl_generator_py import import_type_support
module = import_type_support('control_msgs')
except ImportError:
import logging
import traceback
logger = logging.getLogger(
'control_msgs.action.SingleJointPosition_GetResult_Response')
logger.debug(
'Failed to import needed modules for type support:\n' +
traceback.format_exc())
else:
cls._CREATE_ROS_MESSAGE = module.create_ros_message_msg__action__single_joint_position__get_result__response
cls._CONVERT_FROM_PY = module.convert_from_py_msg__action__single_joint_position__get_result__response
cls._CONVERT_TO_PY = module.convert_to_py_msg__action__single_joint_position__get_result__response
cls._TYPE_SUPPORT = module.type_support_msg__action__single_joint_position__get_result__response
cls._DESTROY_ROS_MESSAGE = module.destroy_ros_message_msg__action__single_joint_position__get_result__response
from control_msgs.action import SingleJointPosition
if SingleJointPosition.Result.__class__._TYPE_SUPPORT is None:
SingleJointPosition.Result.__class__.__import_type_support__()
@classmethod
def __prepare__(cls, name, bases, **kwargs):
# list constant names here so that they appear in the help text of
# the message class under "Data and other attributes defined here:"
# as well as populate each message instance
return {
}
class SingleJointPosition_GetResult_Response(metaclass=Metaclass_SingleJointPosition_GetResult_Response):
"""Message class 'SingleJointPosition_GetResult_Response'."""
__slots__ = [
'_status',
'_result',
]
_fields_and_field_types = {
'status': 'int8',
'result': 'control_msgs/SingleJointPosition_Result',
}
SLOT_TYPES = (
rosidl_parser.definition.BasicType('int8'), # noqa: E501
rosidl_parser.definition.NamespacedType(['control_msgs', 'action'], 'SingleJointPosition_Result'), # noqa: E501
)
def __init__(self, **kwargs):
assert all('_' + key in self.__slots__ for key in kwargs.keys()), \
'Invalid arguments passed to constructor: %s' % \
', '.join(sorted(k for k in kwargs.keys() if '_' + k not in self.__slots__))
self.status = kwargs.get('status', int())
from control_msgs.action._single_joint_position import SingleJointPosition_Result
self.result = kwargs.get('result', SingleJointPosition_Result())
def __repr__(self):
typename = self.__class__.__module__.split('.')
typename.pop()
typename.append(self.__class__.__name__)
args = []
for s, t in zip(self.__slots__, self.SLOT_TYPES):
field = getattr(self, s)
fieldstr = repr(field)
# We use Python array type for fields that can be directly stored
# in them, and "normal" sequences for everything else. If it is
# a type that we store in an array, strip off the 'array' portion.
if (
isinstance(t, rosidl_parser.definition.AbstractSequence) and
isinstance(t.value_type, rosidl_parser.definition.BasicType) and
t.value_type.typename in ['float', 'double', 'int8', 'uint8', 'int16', 'uint16', 'int32', 'uint32', 'int64', 'uint64']
):
if len(field) == 0:
fieldstr = '[]'
else:
assert fieldstr.startswith('array(')
prefix = "array('X', "
suffix = ')'
fieldstr = fieldstr[len(prefix):-len(suffix)]
args.append(s[1:] + '=' + fieldstr)
return '%s(%s)' % ('.'.join(typename), ', '.join(args))
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
if self.status != other.status:
return False
if self.result != other.result:
return False
return True
@classmethod
def get_fields_and_field_types(cls):
from copy import copy
return copy(cls._fields_and_field_types)
@property
def status(self):
"""Message field 'status'."""
return self._status
@status.setter
def status(self, value):
if __debug__:
assert \
isinstance(value, int), \
"The 'status' field must be of type 'int'"
assert value >= -128 and value < 128, \
"The 'status' field must be an integer in [-128, 127]"
self._status = value
@property
def result(self):
"""Message field 'result'."""
return self._result
@result.setter
def result(self, value):
if __debug__:
from control_msgs.action._single_joint_position import SingleJointPosition_Result
assert \
isinstance(value, SingleJointPosition_Result), \
"The 'result' field must be a sub message of type 'SingleJointPosition_Result'"
self._result = value
class Metaclass_SingleJointPosition_GetResult(type):
"""Metaclass of service 'SingleJointPosition_GetResult'."""
_TYPE_SUPPORT = None
@classmethod
def __import_type_support__(cls):
try:
from rosidl_generator_py import import_type_support
module = import_type_support('control_msgs')
except ImportError:
import logging
import traceback
logger = logging.getLogger(
'control_msgs.action.SingleJointPosition_GetResult')
logger.debug(
'Failed to import needed modules for type support:\n' +
traceback.format_exc())
else:
cls._TYPE_SUPPORT = module.type_support_srv__action__single_joint_position__get_result
from control_msgs.action import _single_joint_position
if _single_joint_position.Metaclass_SingleJointPosition_GetResult_Request._TYPE_SUPPORT is None:
_single_joint_position.Metaclass_SingleJointPosition_GetResult_Request.__import_type_support__()
if _single_joint_position.Metaclass_SingleJointPosition_GetResult_Response._TYPE_SUPPORT is None:
_single_joint_position.Metaclass_SingleJointPosition_GetResult_Response.__import_type_support__()
class SingleJointPosition_GetResult(metaclass=Metaclass_SingleJointPosition_GetResult):
from control_msgs.action._single_joint_position import SingleJointPosition_GetResult_Request as Request
from control_msgs.action._single_joint_position import SingleJointPosition_GetResult_Response as Response
def __init__(self):
raise NotImplementedError('Service classes can not be instantiated')
# Import statements for member types
# already imported above
# import rosidl_parser.definition
class Metaclass_SingleJointPosition_FeedbackMessage(type):
"""Metaclass of message 'SingleJointPosition_FeedbackMessage'."""
_CREATE_ROS_MESSAGE = None
_CONVERT_FROM_PY = None
_CONVERT_TO_PY = None
_DESTROY_ROS_MESSAGE = None
_TYPE_SUPPORT = None
__constants = {
}
@classmethod
def __import_type_support__(cls):
try:
from rosidl_generator_py import import_type_support
module = import_type_support('control_msgs')
except ImportError:
import logging
import traceback
logger = logging.getLogger(
'control_msgs.action.SingleJointPosition_FeedbackMessage')
logger.debug(
'Failed to import needed modules for type support:\n' +
traceback.format_exc())
else:
cls._CREATE_ROS_MESSAGE = module.create_ros_message_msg__action__single_joint_position__feedback_message
cls._CONVERT_FROM_PY = module.convert_from_py_msg__action__single_joint_position__feedback_message
cls._CONVERT_TO_PY = module.convert_to_py_msg__action__single_joint_position__feedback_message
cls._TYPE_SUPPORT = module.type_support_msg__action__single_joint_position__feedback_message
cls._DESTROY_ROS_MESSAGE = module.destroy_ros_message_msg__action__single_joint_position__feedback_message
from control_msgs.action import SingleJointPosition
if SingleJointPosition.Feedback.__class__._TYPE_SUPPORT is None:
SingleJointPosition.Feedback.__class__.__import_type_support__()
from unique_identifier_msgs.msg import UUID
if UUID.__class__._TYPE_SUPPORT is None:
UUID.__class__.__import_type_support__()
@classmethod
def __prepare__(cls, name, bases, **kwargs):
# list constant names here so that they appear in the help text of
# the message class under "Data and other attributes defined here:"
# as well as populate each message instance
return {
}
class SingleJointPosition_FeedbackMessage(metaclass=Metaclass_SingleJointPosition_FeedbackMessage):
"""Message class 'SingleJointPosition_FeedbackMessage'."""
__slots__ = [
'_goal_id',
'_feedback',
]
_fields_and_field_types = {
'goal_id': 'unique_identifier_msgs/UUID',
'feedback': 'control_msgs/SingleJointPosition_Feedback',
}
SLOT_TYPES = (
rosidl_parser.definition.NamespacedType(['unique_identifier_msgs', 'msg'], 'UUID'), # noqa: E501
rosidl_parser.definition.NamespacedType(['control_msgs', 'action'], 'SingleJointPosition_Feedback'), # noqa: E501
)
def __init__(self, **kwargs):
assert all('_' + key in self.__slots__ for key in kwargs.keys()), \
'Invalid arguments passed to constructor: %s' % \
', '.join(sorted(k for k in kwargs.keys() if '_' + k not in self.__slots__))
from unique_identifier_msgs.msg import UUID
self.goal_id = kwargs.get('goal_id', UUID())
from control_msgs.action._single_joint_position import SingleJointPosition_Feedback
self.feedback = kwargs.get('feedback', SingleJointPosition_Feedback())
def __repr__(self):
typename = self.__class__.__module__.split('.')
typename.pop()
typename.append(self.__class__.__name__)
args = []
for s, t in zip(self.__slots__, self.SLOT_TYPES):
field = getattr(self, s)
fieldstr = repr(field)
# We use Python array type for fields that can be directly stored
# in them, and "normal" sequences for everything else. If it is
# a type that we store in an array, strip off the 'array' portion.
if (
isinstance(t, rosidl_parser.definition.AbstractSequence) and
isinstance(t.value_type, rosidl_parser.definition.BasicType) and
t.value_type.typename in ['float', 'double', 'int8', 'uint8', 'int16', 'uint16', 'int32', 'uint32', 'int64', 'uint64']
):
if len(field) == 0:
fieldstr = '[]'
else:
assert fieldstr.startswith('array(')
prefix = "array('X', "
suffix = ')'
fieldstr = fieldstr[len(prefix):-len(suffix)]
args.append(s[1:] + '=' + fieldstr)
return '%s(%s)' % ('.'.join(typename), ', '.join(args))
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
if self.goal_id != other.goal_id:
return False
if self.feedback != other.feedback:
return False
return True
@classmethod
def get_fields_and_field_types(cls):
from copy import copy
return copy(cls._fields_and_field_types)
@property
def goal_id(self):
"""Message field 'goal_id'."""
return self._goal_id
@goal_id.setter
def goal_id(self, value):
if __debug__:
from unique_identifier_msgs.msg import UUID
assert \
isinstance(value, UUID), \
"The 'goal_id' field must be a sub message of type 'UUID'"
self._goal_id = value
@property
def feedback(self):
"""Message field 'feedback'."""
return self._feedback
@feedback.setter
def feedback(self, value):
if __debug__:
from control_msgs.action._single_joint_position import SingleJointPosition_Feedback
assert \
isinstance(value, SingleJointPosition_Feedback), \
"The 'feedback' field must be a sub message of type 'SingleJointPosition_Feedback'"
self._feedback = value
class Metaclass_SingleJointPosition(type):
"""Metaclass of action 'SingleJointPosition'."""
_TYPE_SUPPORT = None
@classmethod
def __import_type_support__(cls):
try:
from rosidl_generator_py import import_type_support
module = import_type_support('control_msgs')
except ImportError:
import logging
import traceback
logger = logging.getLogger(
'control_msgs.action.SingleJointPosition')
logger.debug(
'Failed to import needed modules for type support:\n' +
traceback.format_exc())
else:
cls._TYPE_SUPPORT = module.type_support_action__action__single_joint_position
from action_msgs.msg import _goal_status_array
if _goal_status_array.Metaclass_GoalStatusArray._TYPE_SUPPORT is None:
_goal_status_array.Metaclass_GoalStatusArray.__import_type_support__()
from action_msgs.srv import _cancel_goal
if _cancel_goal.Metaclass_CancelGoal._TYPE_SUPPORT is None:
_cancel_goal.Metaclass_CancelGoal.__import_type_support__()
from control_msgs.action import _single_joint_position
if _single_joint_position.Metaclass_SingleJointPosition_SendGoal._TYPE_SUPPORT is None:
_single_joint_position.Metaclass_SingleJointPosition_SendGoal.__import_type_support__()
if _single_joint_position.Metaclass_SingleJointPosition_GetResult._TYPE_SUPPORT is None:
_single_joint_position.Metaclass_SingleJointPosition_GetResult.__import_type_support__()
if _single_joint_position.Metaclass_SingleJointPosition_FeedbackMessage._TYPE_SUPPORT is None:
_single_joint_position.Metaclass_SingleJointPosition_FeedbackMessage.__import_type_support__()
class SingleJointPosition(metaclass=Metaclass_SingleJointPosition):
# The goal message defined in the action definition.
from control_msgs.action._single_joint_position import SingleJointPosition_Goal as Goal
# The result message defined in the action definition.
from control_msgs.action._single_joint_position import SingleJointPosition_Result as Result
# The feedback message defined in the action definition.
from control_msgs.action._single_joint_position import SingleJointPosition_Feedback as Feedback
class Impl:
# The send_goal service using a wrapped version of the goal message as a request.
from control_msgs.action._single_joint_position import SingleJointPosition_SendGoal as SendGoalService
# The get_result service using a wrapped version of the result message as a response.
from control_msgs.action._single_joint_position import SingleJointPosition_GetResult as GetResultService
# The feedback message with generic fields which wraps the feedback message.
from control_msgs.action._single_joint_position import SingleJointPosition_FeedbackMessage as FeedbackMessage
# The generic service to cancel a goal.
from action_msgs.srv._cancel_goal import CancelGoal as CancelGoalService
# The generic message for get the status of a goal.
from action_msgs.msg._goal_status_array import GoalStatusArray as GoalStatusMessage
def __init__(self):
raise NotImplementedError('Action classes can not be instantiated')
| 50,584 | Python | 37.703137 | 134 | 0.595821 |
Toni-SM/semu.robotics.ros2_bridge/src/semu.robotics.ros2_bridge/semu/robotics/ros2_bridge/packages/control_msgs/action/_follow_joint_trajectory.py | # generated from rosidl_generator_py/resource/_idl.py.em
# with input from control_msgs:action/FollowJointTrajectory.idl
# generated code does not contain a copyright notice
# Import statements for member types
import rosidl_parser.definition # noqa: E402, I100
class Metaclass_FollowJointTrajectory_Goal(type):
"""Metaclass of message 'FollowJointTrajectory_Goal'."""
_CREATE_ROS_MESSAGE = None
_CONVERT_FROM_PY = None
_CONVERT_TO_PY = None
_DESTROY_ROS_MESSAGE = None
_TYPE_SUPPORT = None
__constants = {
}
@classmethod
def __import_type_support__(cls):
try:
from rosidl_generator_py import import_type_support
module = import_type_support('control_msgs')
except ImportError:
import logging
import traceback
logger = logging.getLogger(
'control_msgs.action.FollowJointTrajectory_Goal')
logger.debug(
'Failed to import needed modules for type support:\n' +
traceback.format_exc())
else:
cls._CREATE_ROS_MESSAGE = module.create_ros_message_msg__action__follow_joint_trajectory__goal
cls._CONVERT_FROM_PY = module.convert_from_py_msg__action__follow_joint_trajectory__goal
cls._CONVERT_TO_PY = module.convert_to_py_msg__action__follow_joint_trajectory__goal
cls._TYPE_SUPPORT = module.type_support_msg__action__follow_joint_trajectory__goal
cls._DESTROY_ROS_MESSAGE = module.destroy_ros_message_msg__action__follow_joint_trajectory__goal
from builtin_interfaces.msg import Duration
if Duration.__class__._TYPE_SUPPORT is None:
Duration.__class__.__import_type_support__()
from control_msgs.msg import JointTolerance
if JointTolerance.__class__._TYPE_SUPPORT is None:
JointTolerance.__class__.__import_type_support__()
from trajectory_msgs.msg import JointTrajectory
if JointTrajectory.__class__._TYPE_SUPPORT is None:
JointTrajectory.__class__.__import_type_support__()
@classmethod
def __prepare__(cls, name, bases, **kwargs):
# list constant names here so that they appear in the help text of
# the message class under "Data and other attributes defined here:"
# as well as populate each message instance
return {
}
class FollowJointTrajectory_Goal(metaclass=Metaclass_FollowJointTrajectory_Goal):
"""Message class 'FollowJointTrajectory_Goal'."""
__slots__ = [
'_trajectory',
'_path_tolerance',
'_goal_tolerance',
'_goal_time_tolerance',
]
_fields_and_field_types = {
'trajectory': 'trajectory_msgs/JointTrajectory',
'path_tolerance': 'sequence<control_msgs/JointTolerance>',
'goal_tolerance': 'sequence<control_msgs/JointTolerance>',
'goal_time_tolerance': 'builtin_interfaces/Duration',
}
SLOT_TYPES = (
rosidl_parser.definition.NamespacedType(['trajectory_msgs', 'msg'], 'JointTrajectory'), # noqa: E501
rosidl_parser.definition.UnboundedSequence(rosidl_parser.definition.NamespacedType(['control_msgs', 'msg'], 'JointTolerance')), # noqa: E501
rosidl_parser.definition.UnboundedSequence(rosidl_parser.definition.NamespacedType(['control_msgs', 'msg'], 'JointTolerance')), # noqa: E501
rosidl_parser.definition.NamespacedType(['builtin_interfaces', 'msg'], 'Duration'), # noqa: E501
)
def __init__(self, **kwargs):
assert all('_' + key in self.__slots__ for key in kwargs.keys()), \
'Invalid arguments passed to constructor: %s' % \
', '.join(sorted(k for k in kwargs.keys() if '_' + k not in self.__slots__))
from trajectory_msgs.msg import JointTrajectory
self.trajectory = kwargs.get('trajectory', JointTrajectory())
self.path_tolerance = kwargs.get('path_tolerance', [])
self.goal_tolerance = kwargs.get('goal_tolerance', [])
from builtin_interfaces.msg import Duration
self.goal_time_tolerance = kwargs.get('goal_time_tolerance', Duration())
def __repr__(self):
typename = self.__class__.__module__.split('.')
typename.pop()
typename.append(self.__class__.__name__)
args = []
for s, t in zip(self.__slots__, self.SLOT_TYPES):
field = getattr(self, s)
fieldstr = repr(field)
# We use Python array type for fields that can be directly stored
# in them, and "normal" sequences for everything else. If it is
# a type that we store in an array, strip off the 'array' portion.
if (
isinstance(t, rosidl_parser.definition.AbstractSequence) and
isinstance(t.value_type, rosidl_parser.definition.BasicType) and
t.value_type.typename in ['float', 'double', 'int8', 'uint8', 'int16', 'uint16', 'int32', 'uint32', 'int64', 'uint64']
):
if len(field) == 0:
fieldstr = '[]'
else:
assert fieldstr.startswith('array(')
prefix = "array('X', "
suffix = ')'
fieldstr = fieldstr[len(prefix):-len(suffix)]
args.append(s[1:] + '=' + fieldstr)
return '%s(%s)' % ('.'.join(typename), ', '.join(args))
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
if self.trajectory != other.trajectory:
return False
if self.path_tolerance != other.path_tolerance:
return False
if self.goal_tolerance != other.goal_tolerance:
return False
if self.goal_time_tolerance != other.goal_time_tolerance:
return False
return True
@classmethod
def get_fields_and_field_types(cls):
from copy import copy
return copy(cls._fields_and_field_types)
@property
def trajectory(self):
"""Message field 'trajectory'."""
return self._trajectory
@trajectory.setter
def trajectory(self, value):
if __debug__:
from trajectory_msgs.msg import JointTrajectory
assert \
isinstance(value, JointTrajectory), \
"The 'trajectory' field must be a sub message of type 'JointTrajectory'"
self._trajectory = value
@property
def path_tolerance(self):
"""Message field 'path_tolerance'."""
return self._path_tolerance
@path_tolerance.setter
def path_tolerance(self, value):
if __debug__:
from control_msgs.msg import JointTolerance
from collections.abc import Sequence
from collections.abc import Set
from collections import UserList
from collections import UserString
assert \
((isinstance(value, Sequence) or
isinstance(value, Set) or
isinstance(value, UserList)) and
not isinstance(value, str) and
not isinstance(value, UserString) and
all(isinstance(v, JointTolerance) for v in value) and
True), \
"The 'path_tolerance' field must be a set or sequence and each value of type 'JointTolerance'"
self._path_tolerance = value
@property
def goal_tolerance(self):
"""Message field 'goal_tolerance'."""
return self._goal_tolerance
@goal_tolerance.setter
def goal_tolerance(self, value):
if __debug__:
from control_msgs.msg import JointTolerance
from collections.abc import Sequence
from collections.abc import Set
from collections import UserList
from collections import UserString
assert \
((isinstance(value, Sequence) or
isinstance(value, Set) or
isinstance(value, UserList)) and
not isinstance(value, str) and
not isinstance(value, UserString) and
all(isinstance(v, JointTolerance) for v in value) and
True), \
"The 'goal_tolerance' field must be a set or sequence and each value of type 'JointTolerance'"
self._goal_tolerance = value
@property
def goal_time_tolerance(self):
"""Message field 'goal_time_tolerance'."""
return self._goal_time_tolerance
@goal_time_tolerance.setter
def goal_time_tolerance(self, value):
if __debug__:
from builtin_interfaces.msg import Duration
assert \
isinstance(value, Duration), \
"The 'goal_time_tolerance' field must be a sub message of type 'Duration'"
self._goal_time_tolerance = value
# Import statements for member types
# already imported above
# import rosidl_parser.definition
class Metaclass_FollowJointTrajectory_Result(type):
"""Metaclass of message 'FollowJointTrajectory_Result'."""
_CREATE_ROS_MESSAGE = None
_CONVERT_FROM_PY = None
_CONVERT_TO_PY = None
_DESTROY_ROS_MESSAGE = None
_TYPE_SUPPORT = None
__constants = {
'SUCCESSFUL': 0,
'INVALID_GOAL': -1,
'INVALID_JOINTS': -2,
'OLD_HEADER_TIMESTAMP': -3,
'PATH_TOLERANCE_VIOLATED': -4,
'GOAL_TOLERANCE_VIOLATED': -5,
}
@classmethod
def __import_type_support__(cls):
try:
from rosidl_generator_py import import_type_support
module = import_type_support('control_msgs')
except ImportError:
import logging
import traceback
logger = logging.getLogger(
'control_msgs.action.FollowJointTrajectory_Result')
logger.debug(
'Failed to import needed modules for type support:\n' +
traceback.format_exc())
else:
cls._CREATE_ROS_MESSAGE = module.create_ros_message_msg__action__follow_joint_trajectory__result
cls._CONVERT_FROM_PY = module.convert_from_py_msg__action__follow_joint_trajectory__result
cls._CONVERT_TO_PY = module.convert_to_py_msg__action__follow_joint_trajectory__result
cls._TYPE_SUPPORT = module.type_support_msg__action__follow_joint_trajectory__result
cls._DESTROY_ROS_MESSAGE = module.destroy_ros_message_msg__action__follow_joint_trajectory__result
@classmethod
def __prepare__(cls, name, bases, **kwargs):
# list constant names here so that they appear in the help text of
# the message class under "Data and other attributes defined here:"
# as well as populate each message instance
return {
'SUCCESSFUL': cls.__constants['SUCCESSFUL'],
'INVALID_GOAL': cls.__constants['INVALID_GOAL'],
'INVALID_JOINTS': cls.__constants['INVALID_JOINTS'],
'OLD_HEADER_TIMESTAMP': cls.__constants['OLD_HEADER_TIMESTAMP'],
'PATH_TOLERANCE_VIOLATED': cls.__constants['PATH_TOLERANCE_VIOLATED'],
'GOAL_TOLERANCE_VIOLATED': cls.__constants['GOAL_TOLERANCE_VIOLATED'],
}
@property
def SUCCESSFUL(self):
"""Message constant 'SUCCESSFUL'."""
return Metaclass_FollowJointTrajectory_Result.__constants['SUCCESSFUL']
@property
def INVALID_GOAL(self):
"""Message constant 'INVALID_GOAL'."""
return Metaclass_FollowJointTrajectory_Result.__constants['INVALID_GOAL']
@property
def INVALID_JOINTS(self):
"""Message constant 'INVALID_JOINTS'."""
return Metaclass_FollowJointTrajectory_Result.__constants['INVALID_JOINTS']
@property
def OLD_HEADER_TIMESTAMP(self):
"""Message constant 'OLD_HEADER_TIMESTAMP'."""
return Metaclass_FollowJointTrajectory_Result.__constants['OLD_HEADER_TIMESTAMP']
@property
def PATH_TOLERANCE_VIOLATED(self):
"""Message constant 'PATH_TOLERANCE_VIOLATED'."""
return Metaclass_FollowJointTrajectory_Result.__constants['PATH_TOLERANCE_VIOLATED']
@property
def GOAL_TOLERANCE_VIOLATED(self):
"""Message constant 'GOAL_TOLERANCE_VIOLATED'."""
return Metaclass_FollowJointTrajectory_Result.__constants['GOAL_TOLERANCE_VIOLATED']
class FollowJointTrajectory_Result(metaclass=Metaclass_FollowJointTrajectory_Result):
"""
Message class 'FollowJointTrajectory_Result'.
Constants:
SUCCESSFUL
INVALID_GOAL
INVALID_JOINTS
OLD_HEADER_TIMESTAMP
PATH_TOLERANCE_VIOLATED
GOAL_TOLERANCE_VIOLATED
"""
__slots__ = [
'_error_code',
'_error_string',
]
_fields_and_field_types = {
'error_code': 'int32',
'error_string': 'string',
}
SLOT_TYPES = (
rosidl_parser.definition.BasicType('int32'), # noqa: E501
rosidl_parser.definition.UnboundedString(), # noqa: E501
)
def __init__(self, **kwargs):
assert all('_' + key in self.__slots__ for key in kwargs.keys()), \
'Invalid arguments passed to constructor: %s' % \
', '.join(sorted(k for k in kwargs.keys() if '_' + k not in self.__slots__))
self.error_code = kwargs.get('error_code', int())
self.error_string = kwargs.get('error_string', str())
def __repr__(self):
typename = self.__class__.__module__.split('.')
typename.pop()
typename.append(self.__class__.__name__)
args = []
for s, t in zip(self.__slots__, self.SLOT_TYPES):
field = getattr(self, s)
fieldstr = repr(field)
# We use Python array type for fields that can be directly stored
# in them, and "normal" sequences for everything else. If it is
# a type that we store in an array, strip off the 'array' portion.
if (
isinstance(t, rosidl_parser.definition.AbstractSequence) and
isinstance(t.value_type, rosidl_parser.definition.BasicType) and
t.value_type.typename in ['float', 'double', 'int8', 'uint8', 'int16', 'uint16', 'int32', 'uint32', 'int64', 'uint64']
):
if len(field) == 0:
fieldstr = '[]'
else:
assert fieldstr.startswith('array(')
prefix = "array('X', "
suffix = ')'
fieldstr = fieldstr[len(prefix):-len(suffix)]
args.append(s[1:] + '=' + fieldstr)
return '%s(%s)' % ('.'.join(typename), ', '.join(args))
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
if self.error_code != other.error_code:
return False
if self.error_string != other.error_string:
return False
return True
@classmethod
def get_fields_and_field_types(cls):
from copy import copy
return copy(cls._fields_and_field_types)
@property
def error_code(self):
"""Message field 'error_code'."""
return self._error_code
@error_code.setter
def error_code(self, value):
if __debug__:
assert \
isinstance(value, int), \
"The 'error_code' field must be of type 'int'"
assert value >= -2147483648 and value < 2147483648, \
"The 'error_code' field must be an integer in [-2147483648, 2147483647]"
self._error_code = value
@property
def error_string(self):
"""Message field 'error_string'."""
return self._error_string
@error_string.setter
def error_string(self, value):
if __debug__:
assert \
isinstance(value, str), \
"The 'error_string' field must be of type 'str'"
self._error_string = value
# Import statements for member types
# already imported above
# import rosidl_parser.definition
class Metaclass_FollowJointTrajectory_Feedback(type):
"""Metaclass of message 'FollowJointTrajectory_Feedback'."""
_CREATE_ROS_MESSAGE = None
_CONVERT_FROM_PY = None
_CONVERT_TO_PY = None
_DESTROY_ROS_MESSAGE = None
_TYPE_SUPPORT = None
__constants = {
}
@classmethod
def __import_type_support__(cls):
try:
from rosidl_generator_py import import_type_support
module = import_type_support('control_msgs')
except ImportError:
import logging
import traceback
logger = logging.getLogger(
'control_msgs.action.FollowJointTrajectory_Feedback')
logger.debug(
'Failed to import needed modules for type support:\n' +
traceback.format_exc())
else:
cls._CREATE_ROS_MESSAGE = module.create_ros_message_msg__action__follow_joint_trajectory__feedback
cls._CONVERT_FROM_PY = module.convert_from_py_msg__action__follow_joint_trajectory__feedback
cls._CONVERT_TO_PY = module.convert_to_py_msg__action__follow_joint_trajectory__feedback
cls._TYPE_SUPPORT = module.type_support_msg__action__follow_joint_trajectory__feedback
cls._DESTROY_ROS_MESSAGE = module.destroy_ros_message_msg__action__follow_joint_trajectory__feedback
from std_msgs.msg import Header
if Header.__class__._TYPE_SUPPORT is None:
Header.__class__.__import_type_support__()
from trajectory_msgs.msg import JointTrajectoryPoint
if JointTrajectoryPoint.__class__._TYPE_SUPPORT is None:
JointTrajectoryPoint.__class__.__import_type_support__()
@classmethod
def __prepare__(cls, name, bases, **kwargs):
# list constant names here so that they appear in the help text of
# the message class under "Data and other attributes defined here:"
# as well as populate each message instance
return {
}
class FollowJointTrajectory_Feedback(metaclass=Metaclass_FollowJointTrajectory_Feedback):
"""Message class 'FollowJointTrajectory_Feedback'."""
__slots__ = [
'_header',
'_joint_names',
'_desired',
'_actual',
'_error',
]
_fields_and_field_types = {
'header': 'std_msgs/Header',
'joint_names': 'sequence<string>',
'desired': 'trajectory_msgs/JointTrajectoryPoint',
'actual': 'trajectory_msgs/JointTrajectoryPoint',
'error': 'trajectory_msgs/JointTrajectoryPoint',
}
SLOT_TYPES = (
rosidl_parser.definition.NamespacedType(['std_msgs', 'msg'], 'Header'), # noqa: E501
rosidl_parser.definition.UnboundedSequence(rosidl_parser.definition.UnboundedString()), # noqa: E501
rosidl_parser.definition.NamespacedType(['trajectory_msgs', 'msg'], 'JointTrajectoryPoint'), # noqa: E501
rosidl_parser.definition.NamespacedType(['trajectory_msgs', 'msg'], 'JointTrajectoryPoint'), # noqa: E501
rosidl_parser.definition.NamespacedType(['trajectory_msgs', 'msg'], 'JointTrajectoryPoint'), # noqa: E501
)
def __init__(self, **kwargs):
assert all('_' + key in self.__slots__ for key in kwargs.keys()), \
'Invalid arguments passed to constructor: %s' % \
', '.join(sorted(k for k in kwargs.keys() if '_' + k not in self.__slots__))
from std_msgs.msg import Header
self.header = kwargs.get('header', Header())
self.joint_names = kwargs.get('joint_names', [])
from trajectory_msgs.msg import JointTrajectoryPoint
self.desired = kwargs.get('desired', JointTrajectoryPoint())
from trajectory_msgs.msg import JointTrajectoryPoint
self.actual = kwargs.get('actual', JointTrajectoryPoint())
from trajectory_msgs.msg import JointTrajectoryPoint
self.error = kwargs.get('error', JointTrajectoryPoint())
def __repr__(self):
typename = self.__class__.__module__.split('.')
typename.pop()
typename.append(self.__class__.__name__)
args = []
for s, t in zip(self.__slots__, self.SLOT_TYPES):
field = getattr(self, s)
fieldstr = repr(field)
# We use Python array type for fields that can be directly stored
# in them, and "normal" sequences for everything else. If it is
# a type that we store in an array, strip off the 'array' portion.
if (
isinstance(t, rosidl_parser.definition.AbstractSequence) and
isinstance(t.value_type, rosidl_parser.definition.BasicType) and
t.value_type.typename in ['float', 'double', 'int8', 'uint8', 'int16', 'uint16', 'int32', 'uint32', 'int64', 'uint64']
):
if len(field) == 0:
fieldstr = '[]'
else:
assert fieldstr.startswith('array(')
prefix = "array('X', "
suffix = ')'
fieldstr = fieldstr[len(prefix):-len(suffix)]
args.append(s[1:] + '=' + fieldstr)
return '%s(%s)' % ('.'.join(typename), ', '.join(args))
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
if self.header != other.header:
return False
if self.joint_names != other.joint_names:
return False
if self.desired != other.desired:
return False
if self.actual != other.actual:
return False
if self.error != other.error:
return False
return True
@classmethod
def get_fields_and_field_types(cls):
from copy import copy
return copy(cls._fields_and_field_types)
@property
def header(self):
"""Message field 'header'."""
return self._header
@header.setter
def header(self, value):
if __debug__:
from std_msgs.msg import Header
assert \
isinstance(value, Header), \
"The 'header' field must be a sub message of type 'Header'"
self._header = value
@property
def joint_names(self):
"""Message field 'joint_names'."""
return self._joint_names
@joint_names.setter
def joint_names(self, value):
if __debug__:
from collections.abc import Sequence
from collections.abc import Set
from collections import UserList
from collections import UserString
assert \
((isinstance(value, Sequence) or
isinstance(value, Set) or
isinstance(value, UserList)) and
not isinstance(value, str) and
not isinstance(value, UserString) and
all(isinstance(v, str) for v in value) and
True), \
"The 'joint_names' field must be a set or sequence and each value of type 'str'"
self._joint_names = value
@property
def desired(self):
"""Message field 'desired'."""
return self._desired
@desired.setter
def desired(self, value):
if __debug__:
from trajectory_msgs.msg import JointTrajectoryPoint
assert \
isinstance(value, JointTrajectoryPoint), \
"The 'desired' field must be a sub message of type 'JointTrajectoryPoint'"
self._desired = value
@property
def actual(self):
"""Message field 'actual'."""
return self._actual
@actual.setter
def actual(self, value):
if __debug__:
from trajectory_msgs.msg import JointTrajectoryPoint
assert \
isinstance(value, JointTrajectoryPoint), \
"The 'actual' field must be a sub message of type 'JointTrajectoryPoint'"
self._actual = value
@property
def error(self):
"""Message field 'error'."""
return self._error
@error.setter
def error(self, value):
if __debug__:
from trajectory_msgs.msg import JointTrajectoryPoint
assert \
isinstance(value, JointTrajectoryPoint), \
"The 'error' field must be a sub message of type 'JointTrajectoryPoint'"
self._error = value
# Import statements for member types
# already imported above
# import rosidl_parser.definition
class Metaclass_FollowJointTrajectory_SendGoal_Request(type):
"""Metaclass of message 'FollowJointTrajectory_SendGoal_Request'."""
_CREATE_ROS_MESSAGE = None
_CONVERT_FROM_PY = None
_CONVERT_TO_PY = None
_DESTROY_ROS_MESSAGE = None
_TYPE_SUPPORT = None
__constants = {
}
@classmethod
def __import_type_support__(cls):
try:
from rosidl_generator_py import import_type_support
module = import_type_support('control_msgs')
except ImportError:
import logging
import traceback
logger = logging.getLogger(
'control_msgs.action.FollowJointTrajectory_SendGoal_Request')
logger.debug(
'Failed to import needed modules for type support:\n' +
traceback.format_exc())
else:
cls._CREATE_ROS_MESSAGE = module.create_ros_message_msg__action__follow_joint_trajectory__send_goal__request
cls._CONVERT_FROM_PY = module.convert_from_py_msg__action__follow_joint_trajectory__send_goal__request
cls._CONVERT_TO_PY = module.convert_to_py_msg__action__follow_joint_trajectory__send_goal__request
cls._TYPE_SUPPORT = module.type_support_msg__action__follow_joint_trajectory__send_goal__request
cls._DESTROY_ROS_MESSAGE = module.destroy_ros_message_msg__action__follow_joint_trajectory__send_goal__request
from control_msgs.action import FollowJointTrajectory
if FollowJointTrajectory.Goal.__class__._TYPE_SUPPORT is None:
FollowJointTrajectory.Goal.__class__.__import_type_support__()
from unique_identifier_msgs.msg import UUID
if UUID.__class__._TYPE_SUPPORT is None:
UUID.__class__.__import_type_support__()
@classmethod
def __prepare__(cls, name, bases, **kwargs):
# list constant names here so that they appear in the help text of
# the message class under "Data and other attributes defined here:"
# as well as populate each message instance
return {
}
class FollowJointTrajectory_SendGoal_Request(metaclass=Metaclass_FollowJointTrajectory_SendGoal_Request):
"""Message class 'FollowJointTrajectory_SendGoal_Request'."""
__slots__ = [
'_goal_id',
'_goal',
]
_fields_and_field_types = {
'goal_id': 'unique_identifier_msgs/UUID',
'goal': 'control_msgs/FollowJointTrajectory_Goal',
}
SLOT_TYPES = (
rosidl_parser.definition.NamespacedType(['unique_identifier_msgs', 'msg'], 'UUID'), # noqa: E501
rosidl_parser.definition.NamespacedType(['control_msgs', 'action'], 'FollowJointTrajectory_Goal'), # noqa: E501
)
def __init__(self, **kwargs):
assert all('_' + key in self.__slots__ for key in kwargs.keys()), \
'Invalid arguments passed to constructor: %s' % \
', '.join(sorted(k for k in kwargs.keys() if '_' + k not in self.__slots__))
from unique_identifier_msgs.msg import UUID
self.goal_id = kwargs.get('goal_id', UUID())
from control_msgs.action._follow_joint_trajectory import FollowJointTrajectory_Goal
self.goal = kwargs.get('goal', FollowJointTrajectory_Goal())
def __repr__(self):
typename = self.__class__.__module__.split('.')
typename.pop()
typename.append(self.__class__.__name__)
args = []
for s, t in zip(self.__slots__, self.SLOT_TYPES):
field = getattr(self, s)
fieldstr = repr(field)
# We use Python array type for fields that can be directly stored
# in them, and "normal" sequences for everything else. If it is
# a type that we store in an array, strip off the 'array' portion.
if (
isinstance(t, rosidl_parser.definition.AbstractSequence) and
isinstance(t.value_type, rosidl_parser.definition.BasicType) and
t.value_type.typename in ['float', 'double', 'int8', 'uint8', 'int16', 'uint16', 'int32', 'uint32', 'int64', 'uint64']
):
if len(field) == 0:
fieldstr = '[]'
else:
assert fieldstr.startswith('array(')
prefix = "array('X', "
suffix = ')'
fieldstr = fieldstr[len(prefix):-len(suffix)]
args.append(s[1:] + '=' + fieldstr)
return '%s(%s)' % ('.'.join(typename), ', '.join(args))
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
if self.goal_id != other.goal_id:
return False
if self.goal != other.goal:
return False
return True
@classmethod
def get_fields_and_field_types(cls):
from copy import copy
return copy(cls._fields_and_field_types)
@property
def goal_id(self):
"""Message field 'goal_id'."""
return self._goal_id
@goal_id.setter
def goal_id(self, value):
if __debug__:
from unique_identifier_msgs.msg import UUID
assert \
isinstance(value, UUID), \
"The 'goal_id' field must be a sub message of type 'UUID'"
self._goal_id = value
@property
def goal(self):
"""Message field 'goal'."""
return self._goal
@goal.setter
def goal(self, value):
if __debug__:
from control_msgs.action._follow_joint_trajectory import FollowJointTrajectory_Goal
assert \
isinstance(value, FollowJointTrajectory_Goal), \
"The 'goal' field must be a sub message of type 'FollowJointTrajectory_Goal'"
self._goal = value
# Import statements for member types
# already imported above
# import rosidl_parser.definition
class Metaclass_FollowJointTrajectory_SendGoal_Response(type):
"""Metaclass of message 'FollowJointTrajectory_SendGoal_Response'."""
_CREATE_ROS_MESSAGE = None
_CONVERT_FROM_PY = None
_CONVERT_TO_PY = None
_DESTROY_ROS_MESSAGE = None
_TYPE_SUPPORT = None
__constants = {
}
@classmethod
def __import_type_support__(cls):
try:
from rosidl_generator_py import import_type_support
module = import_type_support('control_msgs')
except ImportError:
import logging
import traceback
logger = logging.getLogger(
'control_msgs.action.FollowJointTrajectory_SendGoal_Response')
logger.debug(
'Failed to import needed modules for type support:\n' +
traceback.format_exc())
else:
cls._CREATE_ROS_MESSAGE = module.create_ros_message_msg__action__follow_joint_trajectory__send_goal__response
cls._CONVERT_FROM_PY = module.convert_from_py_msg__action__follow_joint_trajectory__send_goal__response
cls._CONVERT_TO_PY = module.convert_to_py_msg__action__follow_joint_trajectory__send_goal__response
cls._TYPE_SUPPORT = module.type_support_msg__action__follow_joint_trajectory__send_goal__response
cls._DESTROY_ROS_MESSAGE = module.destroy_ros_message_msg__action__follow_joint_trajectory__send_goal__response
from builtin_interfaces.msg import Time
if Time.__class__._TYPE_SUPPORT is None:
Time.__class__.__import_type_support__()
@classmethod
def __prepare__(cls, name, bases, **kwargs):
# list constant names here so that they appear in the help text of
# the message class under "Data and other attributes defined here:"
# as well as populate each message instance
return {
}
class FollowJointTrajectory_SendGoal_Response(metaclass=Metaclass_FollowJointTrajectory_SendGoal_Response):
"""Message class 'FollowJointTrajectory_SendGoal_Response'."""
__slots__ = [
'_accepted',
'_stamp',
]
_fields_and_field_types = {
'accepted': 'boolean',
'stamp': 'builtin_interfaces/Time',
}
SLOT_TYPES = (
rosidl_parser.definition.BasicType('boolean'), # noqa: E501
rosidl_parser.definition.NamespacedType(['builtin_interfaces', 'msg'], 'Time'), # noqa: E501
)
def __init__(self, **kwargs):
assert all('_' + key in self.__slots__ for key in kwargs.keys()), \
'Invalid arguments passed to constructor: %s' % \
', '.join(sorted(k for k in kwargs.keys() if '_' + k not in self.__slots__))
self.accepted = kwargs.get('accepted', bool())
from builtin_interfaces.msg import Time
self.stamp = kwargs.get('stamp', Time())
def __repr__(self):
typename = self.__class__.__module__.split('.')
typename.pop()
typename.append(self.__class__.__name__)
args = []
for s, t in zip(self.__slots__, self.SLOT_TYPES):
field = getattr(self, s)
fieldstr = repr(field)
# We use Python array type for fields that can be directly stored
# in them, and "normal" sequences for everything else. If it is
# a type that we store in an array, strip off the 'array' portion.
if (
isinstance(t, rosidl_parser.definition.AbstractSequence) and
isinstance(t.value_type, rosidl_parser.definition.BasicType) and
t.value_type.typename in ['float', 'double', 'int8', 'uint8', 'int16', 'uint16', 'int32', 'uint32', 'int64', 'uint64']
):
if len(field) == 0:
fieldstr = '[]'
else:
assert fieldstr.startswith('array(')
prefix = "array('X', "
suffix = ')'
fieldstr = fieldstr[len(prefix):-len(suffix)]
args.append(s[1:] + '=' + fieldstr)
return '%s(%s)' % ('.'.join(typename), ', '.join(args))
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
if self.accepted != other.accepted:
return False
if self.stamp != other.stamp:
return False
return True
@classmethod
def get_fields_and_field_types(cls):
from copy import copy
return copy(cls._fields_and_field_types)
@property
def accepted(self):
"""Message field 'accepted'."""
return self._accepted
@accepted.setter
def accepted(self, value):
if __debug__:
assert \
isinstance(value, bool), \
"The 'accepted' field must be of type 'bool'"
self._accepted = value
@property
def stamp(self):
"""Message field 'stamp'."""
return self._stamp
@stamp.setter
def stamp(self, value):
if __debug__:
from builtin_interfaces.msg import Time
assert \
isinstance(value, Time), \
"The 'stamp' field must be a sub message of type 'Time'"
self._stamp = value
class Metaclass_FollowJointTrajectory_SendGoal(type):
"""Metaclass of service 'FollowJointTrajectory_SendGoal'."""
_TYPE_SUPPORT = None
@classmethod
def __import_type_support__(cls):
try:
from rosidl_generator_py import import_type_support
module = import_type_support('control_msgs')
except ImportError:
import logging
import traceback
logger = logging.getLogger(
'control_msgs.action.FollowJointTrajectory_SendGoal')
logger.debug(
'Failed to import needed modules for type support:\n' +
traceback.format_exc())
else:
cls._TYPE_SUPPORT = module.type_support_srv__action__follow_joint_trajectory__send_goal
from control_msgs.action import _follow_joint_trajectory
if _follow_joint_trajectory.Metaclass_FollowJointTrajectory_SendGoal_Request._TYPE_SUPPORT is None:
_follow_joint_trajectory.Metaclass_FollowJointTrajectory_SendGoal_Request.__import_type_support__()
if _follow_joint_trajectory.Metaclass_FollowJointTrajectory_SendGoal_Response._TYPE_SUPPORT is None:
_follow_joint_trajectory.Metaclass_FollowJointTrajectory_SendGoal_Response.__import_type_support__()
class FollowJointTrajectory_SendGoal(metaclass=Metaclass_FollowJointTrajectory_SendGoal):
from control_msgs.action._follow_joint_trajectory import FollowJointTrajectory_SendGoal_Request as Request
from control_msgs.action._follow_joint_trajectory import FollowJointTrajectory_SendGoal_Response as Response
def __init__(self):
raise NotImplementedError('Service classes can not be instantiated')
# Import statements for member types
# already imported above
# import rosidl_parser.definition
class Metaclass_FollowJointTrajectory_GetResult_Request(type):
"""Metaclass of message 'FollowJointTrajectory_GetResult_Request'."""
_CREATE_ROS_MESSAGE = None
_CONVERT_FROM_PY = None
_CONVERT_TO_PY = None
_DESTROY_ROS_MESSAGE = None
_TYPE_SUPPORT = None
__constants = {
}
@classmethod
def __import_type_support__(cls):
try:
from rosidl_generator_py import import_type_support
module = import_type_support('control_msgs')
except ImportError:
import logging
import traceback
logger = logging.getLogger(
'control_msgs.action.FollowJointTrajectory_GetResult_Request')
logger.debug(
'Failed to import needed modules for type support:\n' +
traceback.format_exc())
else:
cls._CREATE_ROS_MESSAGE = module.create_ros_message_msg__action__follow_joint_trajectory__get_result__request
cls._CONVERT_FROM_PY = module.convert_from_py_msg__action__follow_joint_trajectory__get_result__request
cls._CONVERT_TO_PY = module.convert_to_py_msg__action__follow_joint_trajectory__get_result__request
cls._TYPE_SUPPORT = module.type_support_msg__action__follow_joint_trajectory__get_result__request
cls._DESTROY_ROS_MESSAGE = module.destroy_ros_message_msg__action__follow_joint_trajectory__get_result__request
from unique_identifier_msgs.msg import UUID
if UUID.__class__._TYPE_SUPPORT is None:
UUID.__class__.__import_type_support__()
@classmethod
def __prepare__(cls, name, bases, **kwargs):
# list constant names here so that they appear in the help text of
# the message class under "Data and other attributes defined here:"
# as well as populate each message instance
return {
}
class FollowJointTrajectory_GetResult_Request(metaclass=Metaclass_FollowJointTrajectory_GetResult_Request):
"""Message class 'FollowJointTrajectory_GetResult_Request'."""
__slots__ = [
'_goal_id',
]
_fields_and_field_types = {
'goal_id': 'unique_identifier_msgs/UUID',
}
SLOT_TYPES = (
rosidl_parser.definition.NamespacedType(['unique_identifier_msgs', 'msg'], 'UUID'), # noqa: E501
)
def __init__(self, **kwargs):
assert all('_' + key in self.__slots__ for key in kwargs.keys()), \
'Invalid arguments passed to constructor: %s' % \
', '.join(sorted(k for k in kwargs.keys() if '_' + k not in self.__slots__))
from unique_identifier_msgs.msg import UUID
self.goal_id = kwargs.get('goal_id', UUID())
def __repr__(self):
typename = self.__class__.__module__.split('.')
typename.pop()
typename.append(self.__class__.__name__)
args = []
for s, t in zip(self.__slots__, self.SLOT_TYPES):
field = getattr(self, s)
fieldstr = repr(field)
# We use Python array type for fields that can be directly stored
# in them, and "normal" sequences for everything else. If it is
# a type that we store in an array, strip off the 'array' portion.
if (
isinstance(t, rosidl_parser.definition.AbstractSequence) and
isinstance(t.value_type, rosidl_parser.definition.BasicType) and
t.value_type.typename in ['float', 'double', 'int8', 'uint8', 'int16', 'uint16', 'int32', 'uint32', 'int64', 'uint64']
):
if len(field) == 0:
fieldstr = '[]'
else:
assert fieldstr.startswith('array(')
prefix = "array('X', "
suffix = ')'
fieldstr = fieldstr[len(prefix):-len(suffix)]
args.append(s[1:] + '=' + fieldstr)
return '%s(%s)' % ('.'.join(typename), ', '.join(args))
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
if self.goal_id != other.goal_id:
return False
return True
@classmethod
def get_fields_and_field_types(cls):
from copy import copy
return copy(cls._fields_and_field_types)
@property
def goal_id(self):
"""Message field 'goal_id'."""
return self._goal_id
@goal_id.setter
def goal_id(self, value):
if __debug__:
from unique_identifier_msgs.msg import UUID
assert \
isinstance(value, UUID), \
"The 'goal_id' field must be a sub message of type 'UUID'"
self._goal_id = value
# Import statements for member types
# already imported above
# import rosidl_parser.definition
class Metaclass_FollowJointTrajectory_GetResult_Response(type):
"""Metaclass of message 'FollowJointTrajectory_GetResult_Response'."""
_CREATE_ROS_MESSAGE = None
_CONVERT_FROM_PY = None
_CONVERT_TO_PY = None
_DESTROY_ROS_MESSAGE = None
_TYPE_SUPPORT = None
__constants = {
}
@classmethod
def __import_type_support__(cls):
try:
from rosidl_generator_py import import_type_support
module = import_type_support('control_msgs')
except ImportError:
import logging
import traceback
logger = logging.getLogger(
'control_msgs.action.FollowJointTrajectory_GetResult_Response')
logger.debug(
'Failed to import needed modules for type support:\n' +
traceback.format_exc())
else:
cls._CREATE_ROS_MESSAGE = module.create_ros_message_msg__action__follow_joint_trajectory__get_result__response
cls._CONVERT_FROM_PY = module.convert_from_py_msg__action__follow_joint_trajectory__get_result__response
cls._CONVERT_TO_PY = module.convert_to_py_msg__action__follow_joint_trajectory__get_result__response
cls._TYPE_SUPPORT = module.type_support_msg__action__follow_joint_trajectory__get_result__response
cls._DESTROY_ROS_MESSAGE = module.destroy_ros_message_msg__action__follow_joint_trajectory__get_result__response
from control_msgs.action import FollowJointTrajectory
if FollowJointTrajectory.Result.__class__._TYPE_SUPPORT is None:
FollowJointTrajectory.Result.__class__.__import_type_support__()
@classmethod
def __prepare__(cls, name, bases, **kwargs):
# list constant names here so that they appear in the help text of
# the message class under "Data and other attributes defined here:"
# as well as populate each message instance
return {
}
class FollowJointTrajectory_GetResult_Response(metaclass=Metaclass_FollowJointTrajectory_GetResult_Response):
"""Message class 'FollowJointTrajectory_GetResult_Response'."""
__slots__ = [
'_status',
'_result',
]
_fields_and_field_types = {
'status': 'int8',
'result': 'control_msgs/FollowJointTrajectory_Result',
}
SLOT_TYPES = (
rosidl_parser.definition.BasicType('int8'), # noqa: E501
rosidl_parser.definition.NamespacedType(['control_msgs', 'action'], 'FollowJointTrajectory_Result'), # noqa: E501
)
def __init__(self, **kwargs):
assert all('_' + key in self.__slots__ for key in kwargs.keys()), \
'Invalid arguments passed to constructor: %s' % \
', '.join(sorted(k for k in kwargs.keys() if '_' + k not in self.__slots__))
self.status = kwargs.get('status', int())
from control_msgs.action._follow_joint_trajectory import FollowJointTrajectory_Result
self.result = kwargs.get('result', FollowJointTrajectory_Result())
def __repr__(self):
typename = self.__class__.__module__.split('.')
typename.pop()
typename.append(self.__class__.__name__)
args = []
for s, t in zip(self.__slots__, self.SLOT_TYPES):
field = getattr(self, s)
fieldstr = repr(field)
# We use Python array type for fields that can be directly stored
# in them, and "normal" sequences for everything else. If it is
# a type that we store in an array, strip off the 'array' portion.
if (
isinstance(t, rosidl_parser.definition.AbstractSequence) and
isinstance(t.value_type, rosidl_parser.definition.BasicType) and
t.value_type.typename in ['float', 'double', 'int8', 'uint8', 'int16', 'uint16', 'int32', 'uint32', 'int64', 'uint64']
):
if len(field) == 0:
fieldstr = '[]'
else:
assert fieldstr.startswith('array(')
prefix = "array('X', "
suffix = ')'
fieldstr = fieldstr[len(prefix):-len(suffix)]
args.append(s[1:] + '=' + fieldstr)
return '%s(%s)' % ('.'.join(typename), ', '.join(args))
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
if self.status != other.status:
return False
if self.result != other.result:
return False
return True
@classmethod
def get_fields_and_field_types(cls):
from copy import copy
return copy(cls._fields_and_field_types)
@property
def status(self):
"""Message field 'status'."""
return self._status
@status.setter
def status(self, value):
if __debug__:
assert \
isinstance(value, int), \
"The 'status' field must be of type 'int'"
assert value >= -128 and value < 128, \
"The 'status' field must be an integer in [-128, 127]"
self._status = value
@property
def result(self):
"""Message field 'result'."""
return self._result
@result.setter
def result(self, value):
if __debug__:
from control_msgs.action._follow_joint_trajectory import FollowJointTrajectory_Result
assert \
isinstance(value, FollowJointTrajectory_Result), \
"The 'result' field must be a sub message of type 'FollowJointTrajectory_Result'"
self._result = value
class Metaclass_FollowJointTrajectory_GetResult(type):
"""Metaclass of service 'FollowJointTrajectory_GetResult'."""
_TYPE_SUPPORT = None
@classmethod
def __import_type_support__(cls):
try:
from rosidl_generator_py import import_type_support
module = import_type_support('control_msgs')
except ImportError:
import logging
import traceback
logger = logging.getLogger(
'control_msgs.action.FollowJointTrajectory_GetResult')
logger.debug(
'Failed to import needed modules for type support:\n' +
traceback.format_exc())
else:
cls._TYPE_SUPPORT = module.type_support_srv__action__follow_joint_trajectory__get_result
from control_msgs.action import _follow_joint_trajectory
if _follow_joint_trajectory.Metaclass_FollowJointTrajectory_GetResult_Request._TYPE_SUPPORT is None:
_follow_joint_trajectory.Metaclass_FollowJointTrajectory_GetResult_Request.__import_type_support__()
if _follow_joint_trajectory.Metaclass_FollowJointTrajectory_GetResult_Response._TYPE_SUPPORT is None:
_follow_joint_trajectory.Metaclass_FollowJointTrajectory_GetResult_Response.__import_type_support__()
class FollowJointTrajectory_GetResult(metaclass=Metaclass_FollowJointTrajectory_GetResult):
from control_msgs.action._follow_joint_trajectory import FollowJointTrajectory_GetResult_Request as Request
from control_msgs.action._follow_joint_trajectory import FollowJointTrajectory_GetResult_Response as Response
def __init__(self):
raise NotImplementedError('Service classes can not be instantiated')
# Import statements for member types
# already imported above
# import rosidl_parser.definition
class Metaclass_FollowJointTrajectory_FeedbackMessage(type):
"""Metaclass of message 'FollowJointTrajectory_FeedbackMessage'."""
_CREATE_ROS_MESSAGE = None
_CONVERT_FROM_PY = None
_CONVERT_TO_PY = None
_DESTROY_ROS_MESSAGE = None
_TYPE_SUPPORT = None
__constants = {
}
@classmethod
def __import_type_support__(cls):
try:
from rosidl_generator_py import import_type_support
module = import_type_support('control_msgs')
except ImportError:
import logging
import traceback
logger = logging.getLogger(
'control_msgs.action.FollowJointTrajectory_FeedbackMessage')
logger.debug(
'Failed to import needed modules for type support:\n' +
traceback.format_exc())
else:
cls._CREATE_ROS_MESSAGE = module.create_ros_message_msg__action__follow_joint_trajectory__feedback_message
cls._CONVERT_FROM_PY = module.convert_from_py_msg__action__follow_joint_trajectory__feedback_message
cls._CONVERT_TO_PY = module.convert_to_py_msg__action__follow_joint_trajectory__feedback_message
cls._TYPE_SUPPORT = module.type_support_msg__action__follow_joint_trajectory__feedback_message
cls._DESTROY_ROS_MESSAGE = module.destroy_ros_message_msg__action__follow_joint_trajectory__feedback_message
from control_msgs.action import FollowJointTrajectory
if FollowJointTrajectory.Feedback.__class__._TYPE_SUPPORT is None:
FollowJointTrajectory.Feedback.__class__.__import_type_support__()
from unique_identifier_msgs.msg import UUID
if UUID.__class__._TYPE_SUPPORT is None:
UUID.__class__.__import_type_support__()
@classmethod
def __prepare__(cls, name, bases, **kwargs):
# list constant names here so that they appear in the help text of
# the message class under "Data and other attributes defined here:"
# as well as populate each message instance
return {
}
class FollowJointTrajectory_FeedbackMessage(metaclass=Metaclass_FollowJointTrajectory_FeedbackMessage):
"""Message class 'FollowJointTrajectory_FeedbackMessage'."""
__slots__ = [
'_goal_id',
'_feedback',
]
_fields_and_field_types = {
'goal_id': 'unique_identifier_msgs/UUID',
'feedback': 'control_msgs/FollowJointTrajectory_Feedback',
}
SLOT_TYPES = (
rosidl_parser.definition.NamespacedType(['unique_identifier_msgs', 'msg'], 'UUID'), # noqa: E501
rosidl_parser.definition.NamespacedType(['control_msgs', 'action'], 'FollowJointTrajectory_Feedback'), # noqa: E501
)
def __init__(self, **kwargs):
assert all('_' + key in self.__slots__ for key in kwargs.keys()), \
'Invalid arguments passed to constructor: %s' % \
', '.join(sorted(k for k in kwargs.keys() if '_' + k not in self.__slots__))
from unique_identifier_msgs.msg import UUID
self.goal_id = kwargs.get('goal_id', UUID())
from control_msgs.action._follow_joint_trajectory import FollowJointTrajectory_Feedback
self.feedback = kwargs.get('feedback', FollowJointTrajectory_Feedback())
def __repr__(self):
typename = self.__class__.__module__.split('.')
typename.pop()
typename.append(self.__class__.__name__)
args = []
for s, t in zip(self.__slots__, self.SLOT_TYPES):
field = getattr(self, s)
fieldstr = repr(field)
# We use Python array type for fields that can be directly stored
# in them, and "normal" sequences for everything else. If it is
# a type that we store in an array, strip off the 'array' portion.
if (
isinstance(t, rosidl_parser.definition.AbstractSequence) and
isinstance(t.value_type, rosidl_parser.definition.BasicType) and
t.value_type.typename in ['float', 'double', 'int8', 'uint8', 'int16', 'uint16', 'int32', 'uint32', 'int64', 'uint64']
):
if len(field) == 0:
fieldstr = '[]'
else:
assert fieldstr.startswith('array(')
prefix = "array('X', "
suffix = ')'
fieldstr = fieldstr[len(prefix):-len(suffix)]
args.append(s[1:] + '=' + fieldstr)
return '%s(%s)' % ('.'.join(typename), ', '.join(args))
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
if self.goal_id != other.goal_id:
return False
if self.feedback != other.feedback:
return False
return True
@classmethod
def get_fields_and_field_types(cls):
from copy import copy
return copy(cls._fields_and_field_types)
@property
def goal_id(self):
"""Message field 'goal_id'."""
return self._goal_id
@goal_id.setter
def goal_id(self, value):
if __debug__:
from unique_identifier_msgs.msg import UUID
assert \
isinstance(value, UUID), \
"The 'goal_id' field must be a sub message of type 'UUID'"
self._goal_id = value
@property
def feedback(self):
"""Message field 'feedback'."""
return self._feedback
@feedback.setter
def feedback(self, value):
if __debug__:
from control_msgs.action._follow_joint_trajectory import FollowJointTrajectory_Feedback
assert \
isinstance(value, FollowJointTrajectory_Feedback), \
"The 'feedback' field must be a sub message of type 'FollowJointTrajectory_Feedback'"
self._feedback = value
class Metaclass_FollowJointTrajectory(type):
"""Metaclass of action 'FollowJointTrajectory'."""
_TYPE_SUPPORT = None
@classmethod
def __import_type_support__(cls):
try:
from rosidl_generator_py import import_type_support
module = import_type_support('control_msgs')
except ImportError:
import logging
import traceback
logger = logging.getLogger(
'control_msgs.action.FollowJointTrajectory')
logger.debug(
'Failed to import needed modules for type support:\n' +
traceback.format_exc())
else:
cls._TYPE_SUPPORT = module.type_support_action__action__follow_joint_trajectory
from action_msgs.msg import _goal_status_array
if _goal_status_array.Metaclass_GoalStatusArray._TYPE_SUPPORT is None:
_goal_status_array.Metaclass_GoalStatusArray.__import_type_support__()
from action_msgs.srv import _cancel_goal
if _cancel_goal.Metaclass_CancelGoal._TYPE_SUPPORT is None:
_cancel_goal.Metaclass_CancelGoal.__import_type_support__()
from control_msgs.action import _follow_joint_trajectory
if _follow_joint_trajectory.Metaclass_FollowJointTrajectory_SendGoal._TYPE_SUPPORT is None:
_follow_joint_trajectory.Metaclass_FollowJointTrajectory_SendGoal.__import_type_support__()
if _follow_joint_trajectory.Metaclass_FollowJointTrajectory_GetResult._TYPE_SUPPORT is None:
_follow_joint_trajectory.Metaclass_FollowJointTrajectory_GetResult.__import_type_support__()
if _follow_joint_trajectory.Metaclass_FollowJointTrajectory_FeedbackMessage._TYPE_SUPPORT is None:
_follow_joint_trajectory.Metaclass_FollowJointTrajectory_FeedbackMessage.__import_type_support__()
class FollowJointTrajectory(metaclass=Metaclass_FollowJointTrajectory):
# The goal message defined in the action definition.
from control_msgs.action._follow_joint_trajectory import FollowJointTrajectory_Goal as Goal
# The result message defined in the action definition.
from control_msgs.action._follow_joint_trajectory import FollowJointTrajectory_Result as Result
# The feedback message defined in the action definition.
from control_msgs.action._follow_joint_trajectory import FollowJointTrajectory_Feedback as Feedback
class Impl:
# The send_goal service using a wrapped version of the goal message as a request.
from control_msgs.action._follow_joint_trajectory import FollowJointTrajectory_SendGoal as SendGoalService
# The get_result service using a wrapped version of the result message as a response.
from control_msgs.action._follow_joint_trajectory import FollowJointTrajectory_GetResult as GetResultService
# The feedback message with generic fields which wraps the feedback message.
from control_msgs.action._follow_joint_trajectory import FollowJointTrajectory_FeedbackMessage as FeedbackMessage
# The generic service to cancel a goal.
from action_msgs.srv._cancel_goal import CancelGoal as CancelGoalService
# The generic message for get the status of a goal.
from action_msgs.msg._goal_status_array import GoalStatusArray as GoalStatusMessage
def __init__(self):
raise NotImplementedError('Action classes can not be instantiated')
| 59,208 | Python | 38.764271 | 149 | 0.603179 |
Toni-SM/semu.robotics.ros2_bridge/src/semu.robotics.ros2_bridge/semu/robotics/ros2_bridge/packages/control_msgs/action/_point_head.py | # generated from rosidl_generator_py/resource/_idl.py.em
# with input from control_msgs:action/PointHead.idl
# generated code does not contain a copyright notice
# Import statements for member types
import rosidl_parser.definition # noqa: E402, I100
class Metaclass_PointHead_Goal(type):
"""Metaclass of message 'PointHead_Goal'."""
_CREATE_ROS_MESSAGE = None
_CONVERT_FROM_PY = None
_CONVERT_TO_PY = None
_DESTROY_ROS_MESSAGE = None
_TYPE_SUPPORT = None
__constants = {
}
@classmethod
def __import_type_support__(cls):
try:
from rosidl_generator_py import import_type_support
module = import_type_support('control_msgs')
except ImportError:
import logging
import traceback
logger = logging.getLogger(
'control_msgs.action.PointHead_Goal')
logger.debug(
'Failed to import needed modules for type support:\n' +
traceback.format_exc())
else:
cls._CREATE_ROS_MESSAGE = module.create_ros_message_msg__action__point_head__goal
cls._CONVERT_FROM_PY = module.convert_from_py_msg__action__point_head__goal
cls._CONVERT_TO_PY = module.convert_to_py_msg__action__point_head__goal
cls._TYPE_SUPPORT = module.type_support_msg__action__point_head__goal
cls._DESTROY_ROS_MESSAGE = module.destroy_ros_message_msg__action__point_head__goal
from builtin_interfaces.msg import Duration
if Duration.__class__._TYPE_SUPPORT is None:
Duration.__class__.__import_type_support__()
from geometry_msgs.msg import PointStamped
if PointStamped.__class__._TYPE_SUPPORT is None:
PointStamped.__class__.__import_type_support__()
from geometry_msgs.msg import Vector3
if Vector3.__class__._TYPE_SUPPORT is None:
Vector3.__class__.__import_type_support__()
@classmethod
def __prepare__(cls, name, bases, **kwargs):
# list constant names here so that they appear in the help text of
# the message class under "Data and other attributes defined here:"
# as well as populate each message instance
return {
}
class PointHead_Goal(metaclass=Metaclass_PointHead_Goal):
"""Message class 'PointHead_Goal'."""
__slots__ = [
'_target',
'_pointing_axis',
'_pointing_frame',
'_min_duration',
'_max_velocity',
]
_fields_and_field_types = {
'target': 'geometry_msgs/PointStamped',
'pointing_axis': 'geometry_msgs/Vector3',
'pointing_frame': 'string',
'min_duration': 'builtin_interfaces/Duration',
'max_velocity': 'double',
}
SLOT_TYPES = (
rosidl_parser.definition.NamespacedType(['geometry_msgs', 'msg'], 'PointStamped'), # noqa: E501
rosidl_parser.definition.NamespacedType(['geometry_msgs', 'msg'], 'Vector3'), # noqa: E501
rosidl_parser.definition.UnboundedString(), # noqa: E501
rosidl_parser.definition.NamespacedType(['builtin_interfaces', 'msg'], 'Duration'), # noqa: E501
rosidl_parser.definition.BasicType('double'), # noqa: E501
)
def __init__(self, **kwargs):
assert all('_' + key in self.__slots__ for key in kwargs.keys()), \
'Invalid arguments passed to constructor: %s' % \
', '.join(sorted(k for k in kwargs.keys() if '_' + k not in self.__slots__))
from geometry_msgs.msg import PointStamped
self.target = kwargs.get('target', PointStamped())
from geometry_msgs.msg import Vector3
self.pointing_axis = kwargs.get('pointing_axis', Vector3())
self.pointing_frame = kwargs.get('pointing_frame', str())
from builtin_interfaces.msg import Duration
self.min_duration = kwargs.get('min_duration', Duration())
self.max_velocity = kwargs.get('max_velocity', float())
def __repr__(self):
typename = self.__class__.__module__.split('.')
typename.pop()
typename.append(self.__class__.__name__)
args = []
for s, t in zip(self.__slots__, self.SLOT_TYPES):
field = getattr(self, s)
fieldstr = repr(field)
# We use Python array type for fields that can be directly stored
# in them, and "normal" sequences for everything else. If it is
# a type that we store in an array, strip off the 'array' portion.
if (
isinstance(t, rosidl_parser.definition.AbstractSequence) and
isinstance(t.value_type, rosidl_parser.definition.BasicType) and
t.value_type.typename in ['float', 'double', 'int8', 'uint8', 'int16', 'uint16', 'int32', 'uint32', 'int64', 'uint64']
):
if len(field) == 0:
fieldstr = '[]'
else:
assert fieldstr.startswith('array(')
prefix = "array('X', "
suffix = ')'
fieldstr = fieldstr[len(prefix):-len(suffix)]
args.append(s[1:] + '=' + fieldstr)
return '%s(%s)' % ('.'.join(typename), ', '.join(args))
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
if self.target != other.target:
return False
if self.pointing_axis != other.pointing_axis:
return False
if self.pointing_frame != other.pointing_frame:
return False
if self.min_duration != other.min_duration:
return False
if self.max_velocity != other.max_velocity:
return False
return True
@classmethod
def get_fields_and_field_types(cls):
from copy import copy
return copy(cls._fields_and_field_types)
@property
def target(self):
"""Message field 'target'."""
return self._target
@target.setter
def target(self, value):
if __debug__:
from geometry_msgs.msg import PointStamped
assert \
isinstance(value, PointStamped), \
"The 'target' field must be a sub message of type 'PointStamped'"
self._target = value
@property
def pointing_axis(self):
"""Message field 'pointing_axis'."""
return self._pointing_axis
@pointing_axis.setter
def pointing_axis(self, value):
if __debug__:
from geometry_msgs.msg import Vector3
assert \
isinstance(value, Vector3), \
"The 'pointing_axis' field must be a sub message of type 'Vector3'"
self._pointing_axis = value
@property
def pointing_frame(self):
"""Message field 'pointing_frame'."""
return self._pointing_frame
@pointing_frame.setter
def pointing_frame(self, value):
if __debug__:
assert \
isinstance(value, str), \
"The 'pointing_frame' field must be of type 'str'"
self._pointing_frame = value
@property
def min_duration(self):
"""Message field 'min_duration'."""
return self._min_duration
@min_duration.setter
def min_duration(self, value):
if __debug__:
from builtin_interfaces.msg import Duration
assert \
isinstance(value, Duration), \
"The 'min_duration' field must be a sub message of type 'Duration'"
self._min_duration = value
@property
def max_velocity(self):
"""Message field 'max_velocity'."""
return self._max_velocity
@max_velocity.setter
def max_velocity(self, value):
if __debug__:
assert \
isinstance(value, float), \
"The 'max_velocity' field must be of type 'float'"
self._max_velocity = value
# Import statements for member types
# already imported above
# import rosidl_parser.definition
class Metaclass_PointHead_Result(type):
"""Metaclass of message 'PointHead_Result'."""
_CREATE_ROS_MESSAGE = None
_CONVERT_FROM_PY = None
_CONVERT_TO_PY = None
_DESTROY_ROS_MESSAGE = None
_TYPE_SUPPORT = None
__constants = {
}
@classmethod
def __import_type_support__(cls):
try:
from rosidl_generator_py import import_type_support
module = import_type_support('control_msgs')
except ImportError:
import logging
import traceback
logger = logging.getLogger(
'control_msgs.action.PointHead_Result')
logger.debug(
'Failed to import needed modules for type support:\n' +
traceback.format_exc())
else:
cls._CREATE_ROS_MESSAGE = module.create_ros_message_msg__action__point_head__result
cls._CONVERT_FROM_PY = module.convert_from_py_msg__action__point_head__result
cls._CONVERT_TO_PY = module.convert_to_py_msg__action__point_head__result
cls._TYPE_SUPPORT = module.type_support_msg__action__point_head__result
cls._DESTROY_ROS_MESSAGE = module.destroy_ros_message_msg__action__point_head__result
@classmethod
def __prepare__(cls, name, bases, **kwargs):
# list constant names here so that they appear in the help text of
# the message class under "Data and other attributes defined here:"
# as well as populate each message instance
return {
}
class PointHead_Result(metaclass=Metaclass_PointHead_Result):
"""Message class 'PointHead_Result'."""
__slots__ = [
]
_fields_and_field_types = {
}
SLOT_TYPES = (
)
def __init__(self, **kwargs):
assert all('_' + key in self.__slots__ for key in kwargs.keys()), \
'Invalid arguments passed to constructor: %s' % \
', '.join(sorted(k for k in kwargs.keys() if '_' + k not in self.__slots__))
def __repr__(self):
typename = self.__class__.__module__.split('.')
typename.pop()
typename.append(self.__class__.__name__)
args = []
for s, t in zip(self.__slots__, self.SLOT_TYPES):
field = getattr(self, s)
fieldstr = repr(field)
# We use Python array type for fields that can be directly stored
# in them, and "normal" sequences for everything else. If it is
# a type that we store in an array, strip off the 'array' portion.
if (
isinstance(t, rosidl_parser.definition.AbstractSequence) and
isinstance(t.value_type, rosidl_parser.definition.BasicType) and
t.value_type.typename in ['float', 'double', 'int8', 'uint8', 'int16', 'uint16', 'int32', 'uint32', 'int64', 'uint64']
):
if len(field) == 0:
fieldstr = '[]'
else:
assert fieldstr.startswith('array(')
prefix = "array('X', "
suffix = ')'
fieldstr = fieldstr[len(prefix):-len(suffix)]
args.append(s[1:] + '=' + fieldstr)
return '%s(%s)' % ('.'.join(typename), ', '.join(args))
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
return True
@classmethod
def get_fields_and_field_types(cls):
from copy import copy
return copy(cls._fields_and_field_types)
# Import statements for member types
# already imported above
# import rosidl_parser.definition
class Metaclass_PointHead_Feedback(type):
"""Metaclass of message 'PointHead_Feedback'."""
_CREATE_ROS_MESSAGE = None
_CONVERT_FROM_PY = None
_CONVERT_TO_PY = None
_DESTROY_ROS_MESSAGE = None
_TYPE_SUPPORT = None
__constants = {
}
@classmethod
def __import_type_support__(cls):
try:
from rosidl_generator_py import import_type_support
module = import_type_support('control_msgs')
except ImportError:
import logging
import traceback
logger = logging.getLogger(
'control_msgs.action.PointHead_Feedback')
logger.debug(
'Failed to import needed modules for type support:\n' +
traceback.format_exc())
else:
cls._CREATE_ROS_MESSAGE = module.create_ros_message_msg__action__point_head__feedback
cls._CONVERT_FROM_PY = module.convert_from_py_msg__action__point_head__feedback
cls._CONVERT_TO_PY = module.convert_to_py_msg__action__point_head__feedback
cls._TYPE_SUPPORT = module.type_support_msg__action__point_head__feedback
cls._DESTROY_ROS_MESSAGE = module.destroy_ros_message_msg__action__point_head__feedback
@classmethod
def __prepare__(cls, name, bases, **kwargs):
# list constant names here so that they appear in the help text of
# the message class under "Data and other attributes defined here:"
# as well as populate each message instance
return {
}
class PointHead_Feedback(metaclass=Metaclass_PointHead_Feedback):
"""Message class 'PointHead_Feedback'."""
__slots__ = [
'_pointing_angle_error',
]
_fields_and_field_types = {
'pointing_angle_error': 'double',
}
SLOT_TYPES = (
rosidl_parser.definition.BasicType('double'), # noqa: E501
)
def __init__(self, **kwargs):
assert all('_' + key in self.__slots__ for key in kwargs.keys()), \
'Invalid arguments passed to constructor: %s' % \
', '.join(sorted(k for k in kwargs.keys() if '_' + k not in self.__slots__))
self.pointing_angle_error = kwargs.get('pointing_angle_error', float())
def __repr__(self):
typename = self.__class__.__module__.split('.')
typename.pop()
typename.append(self.__class__.__name__)
args = []
for s, t in zip(self.__slots__, self.SLOT_TYPES):
field = getattr(self, s)
fieldstr = repr(field)
# We use Python array type for fields that can be directly stored
# in them, and "normal" sequences for everything else. If it is
# a type that we store in an array, strip off the 'array' portion.
if (
isinstance(t, rosidl_parser.definition.AbstractSequence) and
isinstance(t.value_type, rosidl_parser.definition.BasicType) and
t.value_type.typename in ['float', 'double', 'int8', 'uint8', 'int16', 'uint16', 'int32', 'uint32', 'int64', 'uint64']
):
if len(field) == 0:
fieldstr = '[]'
else:
assert fieldstr.startswith('array(')
prefix = "array('X', "
suffix = ')'
fieldstr = fieldstr[len(prefix):-len(suffix)]
args.append(s[1:] + '=' + fieldstr)
return '%s(%s)' % ('.'.join(typename), ', '.join(args))
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
if self.pointing_angle_error != other.pointing_angle_error:
return False
return True
@classmethod
def get_fields_and_field_types(cls):
from copy import copy
return copy(cls._fields_and_field_types)
@property
def pointing_angle_error(self):
"""Message field 'pointing_angle_error'."""
return self._pointing_angle_error
@pointing_angle_error.setter
def pointing_angle_error(self, value):
if __debug__:
assert \
isinstance(value, float), \
"The 'pointing_angle_error' field must be of type 'float'"
self._pointing_angle_error = value
# Import statements for member types
# already imported above
# import rosidl_parser.definition
class Metaclass_PointHead_SendGoal_Request(type):
"""Metaclass of message 'PointHead_SendGoal_Request'."""
_CREATE_ROS_MESSAGE = None
_CONVERT_FROM_PY = None
_CONVERT_TO_PY = None
_DESTROY_ROS_MESSAGE = None
_TYPE_SUPPORT = None
__constants = {
}
@classmethod
def __import_type_support__(cls):
try:
from rosidl_generator_py import import_type_support
module = import_type_support('control_msgs')
except ImportError:
import logging
import traceback
logger = logging.getLogger(
'control_msgs.action.PointHead_SendGoal_Request')
logger.debug(
'Failed to import needed modules for type support:\n' +
traceback.format_exc())
else:
cls._CREATE_ROS_MESSAGE = module.create_ros_message_msg__action__point_head__send_goal__request
cls._CONVERT_FROM_PY = module.convert_from_py_msg__action__point_head__send_goal__request
cls._CONVERT_TO_PY = module.convert_to_py_msg__action__point_head__send_goal__request
cls._TYPE_SUPPORT = module.type_support_msg__action__point_head__send_goal__request
cls._DESTROY_ROS_MESSAGE = module.destroy_ros_message_msg__action__point_head__send_goal__request
from control_msgs.action import PointHead
if PointHead.Goal.__class__._TYPE_SUPPORT is None:
PointHead.Goal.__class__.__import_type_support__()
from unique_identifier_msgs.msg import UUID
if UUID.__class__._TYPE_SUPPORT is None:
UUID.__class__.__import_type_support__()
@classmethod
def __prepare__(cls, name, bases, **kwargs):
# list constant names here so that they appear in the help text of
# the message class under "Data and other attributes defined here:"
# as well as populate each message instance
return {
}
class PointHead_SendGoal_Request(metaclass=Metaclass_PointHead_SendGoal_Request):
"""Message class 'PointHead_SendGoal_Request'."""
__slots__ = [
'_goal_id',
'_goal',
]
_fields_and_field_types = {
'goal_id': 'unique_identifier_msgs/UUID',
'goal': 'control_msgs/PointHead_Goal',
}
SLOT_TYPES = (
rosidl_parser.definition.NamespacedType(['unique_identifier_msgs', 'msg'], 'UUID'), # noqa: E501
rosidl_parser.definition.NamespacedType(['control_msgs', 'action'], 'PointHead_Goal'), # noqa: E501
)
def __init__(self, **kwargs):
assert all('_' + key in self.__slots__ for key in kwargs.keys()), \
'Invalid arguments passed to constructor: %s' % \
', '.join(sorted(k for k in kwargs.keys() if '_' + k not in self.__slots__))
from unique_identifier_msgs.msg import UUID
self.goal_id = kwargs.get('goal_id', UUID())
from control_msgs.action._point_head import PointHead_Goal
self.goal = kwargs.get('goal', PointHead_Goal())
def __repr__(self):
typename = self.__class__.__module__.split('.')
typename.pop()
typename.append(self.__class__.__name__)
args = []
for s, t in zip(self.__slots__, self.SLOT_TYPES):
field = getattr(self, s)
fieldstr = repr(field)
# We use Python array type for fields that can be directly stored
# in them, and "normal" sequences for everything else. If it is
# a type that we store in an array, strip off the 'array' portion.
if (
isinstance(t, rosidl_parser.definition.AbstractSequence) and
isinstance(t.value_type, rosidl_parser.definition.BasicType) and
t.value_type.typename in ['float', 'double', 'int8', 'uint8', 'int16', 'uint16', 'int32', 'uint32', 'int64', 'uint64']
):
if len(field) == 0:
fieldstr = '[]'
else:
assert fieldstr.startswith('array(')
prefix = "array('X', "
suffix = ')'
fieldstr = fieldstr[len(prefix):-len(suffix)]
args.append(s[1:] + '=' + fieldstr)
return '%s(%s)' % ('.'.join(typename), ', '.join(args))
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
if self.goal_id != other.goal_id:
return False
if self.goal != other.goal:
return False
return True
@classmethod
def get_fields_and_field_types(cls):
from copy import copy
return copy(cls._fields_and_field_types)
@property
def goal_id(self):
"""Message field 'goal_id'."""
return self._goal_id
@goal_id.setter
def goal_id(self, value):
if __debug__:
from unique_identifier_msgs.msg import UUID
assert \
isinstance(value, UUID), \
"The 'goal_id' field must be a sub message of type 'UUID'"
self._goal_id = value
@property
def goal(self):
"""Message field 'goal'."""
return self._goal
@goal.setter
def goal(self, value):
if __debug__:
from control_msgs.action._point_head import PointHead_Goal
assert \
isinstance(value, PointHead_Goal), \
"The 'goal' field must be a sub message of type 'PointHead_Goal'"
self._goal = value
# Import statements for member types
# already imported above
# import rosidl_parser.definition
class Metaclass_PointHead_SendGoal_Response(type):
"""Metaclass of message 'PointHead_SendGoal_Response'."""
_CREATE_ROS_MESSAGE = None
_CONVERT_FROM_PY = None
_CONVERT_TO_PY = None
_DESTROY_ROS_MESSAGE = None
_TYPE_SUPPORT = None
__constants = {
}
@classmethod
def __import_type_support__(cls):
try:
from rosidl_generator_py import import_type_support
module = import_type_support('control_msgs')
except ImportError:
import logging
import traceback
logger = logging.getLogger(
'control_msgs.action.PointHead_SendGoal_Response')
logger.debug(
'Failed to import needed modules for type support:\n' +
traceback.format_exc())
else:
cls._CREATE_ROS_MESSAGE = module.create_ros_message_msg__action__point_head__send_goal__response
cls._CONVERT_FROM_PY = module.convert_from_py_msg__action__point_head__send_goal__response
cls._CONVERT_TO_PY = module.convert_to_py_msg__action__point_head__send_goal__response
cls._TYPE_SUPPORT = module.type_support_msg__action__point_head__send_goal__response
cls._DESTROY_ROS_MESSAGE = module.destroy_ros_message_msg__action__point_head__send_goal__response
from builtin_interfaces.msg import Time
if Time.__class__._TYPE_SUPPORT is None:
Time.__class__.__import_type_support__()
@classmethod
def __prepare__(cls, name, bases, **kwargs):
# list constant names here so that they appear in the help text of
# the message class under "Data and other attributes defined here:"
# as well as populate each message instance
return {
}
class PointHead_SendGoal_Response(metaclass=Metaclass_PointHead_SendGoal_Response):
"""Message class 'PointHead_SendGoal_Response'."""
__slots__ = [
'_accepted',
'_stamp',
]
_fields_and_field_types = {
'accepted': 'boolean',
'stamp': 'builtin_interfaces/Time',
}
SLOT_TYPES = (
rosidl_parser.definition.BasicType('boolean'), # noqa: E501
rosidl_parser.definition.NamespacedType(['builtin_interfaces', 'msg'], 'Time'), # noqa: E501
)
def __init__(self, **kwargs):
assert all('_' + key in self.__slots__ for key in kwargs.keys()), \
'Invalid arguments passed to constructor: %s' % \
', '.join(sorted(k for k in kwargs.keys() if '_' + k not in self.__slots__))
self.accepted = kwargs.get('accepted', bool())
from builtin_interfaces.msg import Time
self.stamp = kwargs.get('stamp', Time())
def __repr__(self):
typename = self.__class__.__module__.split('.')
typename.pop()
typename.append(self.__class__.__name__)
args = []
for s, t in zip(self.__slots__, self.SLOT_TYPES):
field = getattr(self, s)
fieldstr = repr(field)
# We use Python array type for fields that can be directly stored
# in them, and "normal" sequences for everything else. If it is
# a type that we store in an array, strip off the 'array' portion.
if (
isinstance(t, rosidl_parser.definition.AbstractSequence) and
isinstance(t.value_type, rosidl_parser.definition.BasicType) and
t.value_type.typename in ['float', 'double', 'int8', 'uint8', 'int16', 'uint16', 'int32', 'uint32', 'int64', 'uint64']
):
if len(field) == 0:
fieldstr = '[]'
else:
assert fieldstr.startswith('array(')
prefix = "array('X', "
suffix = ')'
fieldstr = fieldstr[len(prefix):-len(suffix)]
args.append(s[1:] + '=' + fieldstr)
return '%s(%s)' % ('.'.join(typename), ', '.join(args))
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
if self.accepted != other.accepted:
return False
if self.stamp != other.stamp:
return False
return True
@classmethod
def get_fields_and_field_types(cls):
from copy import copy
return copy(cls._fields_and_field_types)
@property
def accepted(self):
"""Message field 'accepted'."""
return self._accepted
@accepted.setter
def accepted(self, value):
if __debug__:
assert \
isinstance(value, bool), \
"The 'accepted' field must be of type 'bool'"
self._accepted = value
@property
def stamp(self):
"""Message field 'stamp'."""
return self._stamp
@stamp.setter
def stamp(self, value):
if __debug__:
from builtin_interfaces.msg import Time
assert \
isinstance(value, Time), \
"The 'stamp' field must be a sub message of type 'Time'"
self._stamp = value
class Metaclass_PointHead_SendGoal(type):
"""Metaclass of service 'PointHead_SendGoal'."""
_TYPE_SUPPORT = None
@classmethod
def __import_type_support__(cls):
try:
from rosidl_generator_py import import_type_support
module = import_type_support('control_msgs')
except ImportError:
import logging
import traceback
logger = logging.getLogger(
'control_msgs.action.PointHead_SendGoal')
logger.debug(
'Failed to import needed modules for type support:\n' +
traceback.format_exc())
else:
cls._TYPE_SUPPORT = module.type_support_srv__action__point_head__send_goal
from control_msgs.action import _point_head
if _point_head.Metaclass_PointHead_SendGoal_Request._TYPE_SUPPORT is None:
_point_head.Metaclass_PointHead_SendGoal_Request.__import_type_support__()
if _point_head.Metaclass_PointHead_SendGoal_Response._TYPE_SUPPORT is None:
_point_head.Metaclass_PointHead_SendGoal_Response.__import_type_support__()
class PointHead_SendGoal(metaclass=Metaclass_PointHead_SendGoal):
from control_msgs.action._point_head import PointHead_SendGoal_Request as Request
from control_msgs.action._point_head import PointHead_SendGoal_Response as Response
def __init__(self):
raise NotImplementedError('Service classes can not be instantiated')
# Import statements for member types
# already imported above
# import rosidl_parser.definition
class Metaclass_PointHead_GetResult_Request(type):
"""Metaclass of message 'PointHead_GetResult_Request'."""
_CREATE_ROS_MESSAGE = None
_CONVERT_FROM_PY = None
_CONVERT_TO_PY = None
_DESTROY_ROS_MESSAGE = None
_TYPE_SUPPORT = None
__constants = {
}
@classmethod
def __import_type_support__(cls):
try:
from rosidl_generator_py import import_type_support
module = import_type_support('control_msgs')
except ImportError:
import logging
import traceback
logger = logging.getLogger(
'control_msgs.action.PointHead_GetResult_Request')
logger.debug(
'Failed to import needed modules for type support:\n' +
traceback.format_exc())
else:
cls._CREATE_ROS_MESSAGE = module.create_ros_message_msg__action__point_head__get_result__request
cls._CONVERT_FROM_PY = module.convert_from_py_msg__action__point_head__get_result__request
cls._CONVERT_TO_PY = module.convert_to_py_msg__action__point_head__get_result__request
cls._TYPE_SUPPORT = module.type_support_msg__action__point_head__get_result__request
cls._DESTROY_ROS_MESSAGE = module.destroy_ros_message_msg__action__point_head__get_result__request
from unique_identifier_msgs.msg import UUID
if UUID.__class__._TYPE_SUPPORT is None:
UUID.__class__.__import_type_support__()
@classmethod
def __prepare__(cls, name, bases, **kwargs):
# list constant names here so that they appear in the help text of
# the message class under "Data and other attributes defined here:"
# as well as populate each message instance
return {
}
class PointHead_GetResult_Request(metaclass=Metaclass_PointHead_GetResult_Request):
"""Message class 'PointHead_GetResult_Request'."""
__slots__ = [
'_goal_id',
]
_fields_and_field_types = {
'goal_id': 'unique_identifier_msgs/UUID',
}
SLOT_TYPES = (
rosidl_parser.definition.NamespacedType(['unique_identifier_msgs', 'msg'], 'UUID'), # noqa: E501
)
def __init__(self, **kwargs):
assert all('_' + key in self.__slots__ for key in kwargs.keys()), \
'Invalid arguments passed to constructor: %s' % \
', '.join(sorted(k for k in kwargs.keys() if '_' + k not in self.__slots__))
from unique_identifier_msgs.msg import UUID
self.goal_id = kwargs.get('goal_id', UUID())
def __repr__(self):
typename = self.__class__.__module__.split('.')
typename.pop()
typename.append(self.__class__.__name__)
args = []
for s, t in zip(self.__slots__, self.SLOT_TYPES):
field = getattr(self, s)
fieldstr = repr(field)
# We use Python array type for fields that can be directly stored
# in them, and "normal" sequences for everything else. If it is
# a type that we store in an array, strip off the 'array' portion.
if (
isinstance(t, rosidl_parser.definition.AbstractSequence) and
isinstance(t.value_type, rosidl_parser.definition.BasicType) and
t.value_type.typename in ['float', 'double', 'int8', 'uint8', 'int16', 'uint16', 'int32', 'uint32', 'int64', 'uint64']
):
if len(field) == 0:
fieldstr = '[]'
else:
assert fieldstr.startswith('array(')
prefix = "array('X', "
suffix = ')'
fieldstr = fieldstr[len(prefix):-len(suffix)]
args.append(s[1:] + '=' + fieldstr)
return '%s(%s)' % ('.'.join(typename), ', '.join(args))
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
if self.goal_id != other.goal_id:
return False
return True
@classmethod
def get_fields_and_field_types(cls):
from copy import copy
return copy(cls._fields_and_field_types)
@property
def goal_id(self):
"""Message field 'goal_id'."""
return self._goal_id
@goal_id.setter
def goal_id(self, value):
if __debug__:
from unique_identifier_msgs.msg import UUID
assert \
isinstance(value, UUID), \
"The 'goal_id' field must be a sub message of type 'UUID'"
self._goal_id = value
# Import statements for member types
# already imported above
# import rosidl_parser.definition
class Metaclass_PointHead_GetResult_Response(type):
"""Metaclass of message 'PointHead_GetResult_Response'."""
_CREATE_ROS_MESSAGE = None
_CONVERT_FROM_PY = None
_CONVERT_TO_PY = None
_DESTROY_ROS_MESSAGE = None
_TYPE_SUPPORT = None
__constants = {
}
@classmethod
def __import_type_support__(cls):
try:
from rosidl_generator_py import import_type_support
module = import_type_support('control_msgs')
except ImportError:
import logging
import traceback
logger = logging.getLogger(
'control_msgs.action.PointHead_GetResult_Response')
logger.debug(
'Failed to import needed modules for type support:\n' +
traceback.format_exc())
else:
cls._CREATE_ROS_MESSAGE = module.create_ros_message_msg__action__point_head__get_result__response
cls._CONVERT_FROM_PY = module.convert_from_py_msg__action__point_head__get_result__response
cls._CONVERT_TO_PY = module.convert_to_py_msg__action__point_head__get_result__response
cls._TYPE_SUPPORT = module.type_support_msg__action__point_head__get_result__response
cls._DESTROY_ROS_MESSAGE = module.destroy_ros_message_msg__action__point_head__get_result__response
from control_msgs.action import PointHead
if PointHead.Result.__class__._TYPE_SUPPORT is None:
PointHead.Result.__class__.__import_type_support__()
@classmethod
def __prepare__(cls, name, bases, **kwargs):
# list constant names here so that they appear in the help text of
# the message class under "Data and other attributes defined here:"
# as well as populate each message instance
return {
}
class PointHead_GetResult_Response(metaclass=Metaclass_PointHead_GetResult_Response):
"""Message class 'PointHead_GetResult_Response'."""
__slots__ = [
'_status',
'_result',
]
_fields_and_field_types = {
'status': 'int8',
'result': 'control_msgs/PointHead_Result',
}
SLOT_TYPES = (
rosidl_parser.definition.BasicType('int8'), # noqa: E501
rosidl_parser.definition.NamespacedType(['control_msgs', 'action'], 'PointHead_Result'), # noqa: E501
)
def __init__(self, **kwargs):
assert all('_' + key in self.__slots__ for key in kwargs.keys()), \
'Invalid arguments passed to constructor: %s' % \
', '.join(sorted(k for k in kwargs.keys() if '_' + k not in self.__slots__))
self.status = kwargs.get('status', int())
from control_msgs.action._point_head import PointHead_Result
self.result = kwargs.get('result', PointHead_Result())
def __repr__(self):
typename = self.__class__.__module__.split('.')
typename.pop()
typename.append(self.__class__.__name__)
args = []
for s, t in zip(self.__slots__, self.SLOT_TYPES):
field = getattr(self, s)
fieldstr = repr(field)
# We use Python array type for fields that can be directly stored
# in them, and "normal" sequences for everything else. If it is
# a type that we store in an array, strip off the 'array' portion.
if (
isinstance(t, rosidl_parser.definition.AbstractSequence) and
isinstance(t.value_type, rosidl_parser.definition.BasicType) and
t.value_type.typename in ['float', 'double', 'int8', 'uint8', 'int16', 'uint16', 'int32', 'uint32', 'int64', 'uint64']
):
if len(field) == 0:
fieldstr = '[]'
else:
assert fieldstr.startswith('array(')
prefix = "array('X', "
suffix = ')'
fieldstr = fieldstr[len(prefix):-len(suffix)]
args.append(s[1:] + '=' + fieldstr)
return '%s(%s)' % ('.'.join(typename), ', '.join(args))
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
if self.status != other.status:
return False
if self.result != other.result:
return False
return True
@classmethod
def get_fields_and_field_types(cls):
from copy import copy
return copy(cls._fields_and_field_types)
@property
def status(self):
"""Message field 'status'."""
return self._status
@status.setter
def status(self, value):
if __debug__:
assert \
isinstance(value, int), \
"The 'status' field must be of type 'int'"
assert value >= -128 and value < 128, \
"The 'status' field must be an integer in [-128, 127]"
self._status = value
@property
def result(self):
"""Message field 'result'."""
return self._result
@result.setter
def result(self, value):
if __debug__:
from control_msgs.action._point_head import PointHead_Result
assert \
isinstance(value, PointHead_Result), \
"The 'result' field must be a sub message of type 'PointHead_Result'"
self._result = value
class Metaclass_PointHead_GetResult(type):
"""Metaclass of service 'PointHead_GetResult'."""
_TYPE_SUPPORT = None
@classmethod
def __import_type_support__(cls):
try:
from rosidl_generator_py import import_type_support
module = import_type_support('control_msgs')
except ImportError:
import logging
import traceback
logger = logging.getLogger(
'control_msgs.action.PointHead_GetResult')
logger.debug(
'Failed to import needed modules for type support:\n' +
traceback.format_exc())
else:
cls._TYPE_SUPPORT = module.type_support_srv__action__point_head__get_result
from control_msgs.action import _point_head
if _point_head.Metaclass_PointHead_GetResult_Request._TYPE_SUPPORT is None:
_point_head.Metaclass_PointHead_GetResult_Request.__import_type_support__()
if _point_head.Metaclass_PointHead_GetResult_Response._TYPE_SUPPORT is None:
_point_head.Metaclass_PointHead_GetResult_Response.__import_type_support__()
class PointHead_GetResult(metaclass=Metaclass_PointHead_GetResult):
from control_msgs.action._point_head import PointHead_GetResult_Request as Request
from control_msgs.action._point_head import PointHead_GetResult_Response as Response
def __init__(self):
raise NotImplementedError('Service classes can not be instantiated')
# Import statements for member types
# already imported above
# import rosidl_parser.definition
class Metaclass_PointHead_FeedbackMessage(type):
"""Metaclass of message 'PointHead_FeedbackMessage'."""
_CREATE_ROS_MESSAGE = None
_CONVERT_FROM_PY = None
_CONVERT_TO_PY = None
_DESTROY_ROS_MESSAGE = None
_TYPE_SUPPORT = None
__constants = {
}
@classmethod
def __import_type_support__(cls):
try:
from rosidl_generator_py import import_type_support
module = import_type_support('control_msgs')
except ImportError:
import logging
import traceback
logger = logging.getLogger(
'control_msgs.action.PointHead_FeedbackMessage')
logger.debug(
'Failed to import needed modules for type support:\n' +
traceback.format_exc())
else:
cls._CREATE_ROS_MESSAGE = module.create_ros_message_msg__action__point_head__feedback_message
cls._CONVERT_FROM_PY = module.convert_from_py_msg__action__point_head__feedback_message
cls._CONVERT_TO_PY = module.convert_to_py_msg__action__point_head__feedback_message
cls._TYPE_SUPPORT = module.type_support_msg__action__point_head__feedback_message
cls._DESTROY_ROS_MESSAGE = module.destroy_ros_message_msg__action__point_head__feedback_message
from control_msgs.action import PointHead
if PointHead.Feedback.__class__._TYPE_SUPPORT is None:
PointHead.Feedback.__class__.__import_type_support__()
from unique_identifier_msgs.msg import UUID
if UUID.__class__._TYPE_SUPPORT is None:
UUID.__class__.__import_type_support__()
@classmethod
def __prepare__(cls, name, bases, **kwargs):
# list constant names here so that they appear in the help text of
# the message class under "Data and other attributes defined here:"
# as well as populate each message instance
return {
}
class PointHead_FeedbackMessage(metaclass=Metaclass_PointHead_FeedbackMessage):
"""Message class 'PointHead_FeedbackMessage'."""
__slots__ = [
'_goal_id',
'_feedback',
]
_fields_and_field_types = {
'goal_id': 'unique_identifier_msgs/UUID',
'feedback': 'control_msgs/PointHead_Feedback',
}
SLOT_TYPES = (
rosidl_parser.definition.NamespacedType(['unique_identifier_msgs', 'msg'], 'UUID'), # noqa: E501
rosidl_parser.definition.NamespacedType(['control_msgs', 'action'], 'PointHead_Feedback'), # noqa: E501
)
def __init__(self, **kwargs):
assert all('_' + key in self.__slots__ for key in kwargs.keys()), \
'Invalid arguments passed to constructor: %s' % \
', '.join(sorted(k for k in kwargs.keys() if '_' + k not in self.__slots__))
from unique_identifier_msgs.msg import UUID
self.goal_id = kwargs.get('goal_id', UUID())
from control_msgs.action._point_head import PointHead_Feedback
self.feedback = kwargs.get('feedback', PointHead_Feedback())
def __repr__(self):
typename = self.__class__.__module__.split('.')
typename.pop()
typename.append(self.__class__.__name__)
args = []
for s, t in zip(self.__slots__, self.SLOT_TYPES):
field = getattr(self, s)
fieldstr = repr(field)
# We use Python array type for fields that can be directly stored
# in them, and "normal" sequences for everything else. If it is
# a type that we store in an array, strip off the 'array' portion.
if (
isinstance(t, rosidl_parser.definition.AbstractSequence) and
isinstance(t.value_type, rosidl_parser.definition.BasicType) and
t.value_type.typename in ['float', 'double', 'int8', 'uint8', 'int16', 'uint16', 'int32', 'uint32', 'int64', 'uint64']
):
if len(field) == 0:
fieldstr = '[]'
else:
assert fieldstr.startswith('array(')
prefix = "array('X', "
suffix = ')'
fieldstr = fieldstr[len(prefix):-len(suffix)]
args.append(s[1:] + '=' + fieldstr)
return '%s(%s)' % ('.'.join(typename), ', '.join(args))
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
if self.goal_id != other.goal_id:
return False
if self.feedback != other.feedback:
return False
return True
@classmethod
def get_fields_and_field_types(cls):
from copy import copy
return copy(cls._fields_and_field_types)
@property
def goal_id(self):
"""Message field 'goal_id'."""
return self._goal_id
@goal_id.setter
def goal_id(self, value):
if __debug__:
from unique_identifier_msgs.msg import UUID
assert \
isinstance(value, UUID), \
"The 'goal_id' field must be a sub message of type 'UUID'"
self._goal_id = value
@property
def feedback(self):
"""Message field 'feedback'."""
return self._feedback
@feedback.setter
def feedback(self, value):
if __debug__:
from control_msgs.action._point_head import PointHead_Feedback
assert \
isinstance(value, PointHead_Feedback), \
"The 'feedback' field must be a sub message of type 'PointHead_Feedback'"
self._feedback = value
class Metaclass_PointHead(type):
"""Metaclass of action 'PointHead'."""
_TYPE_SUPPORT = None
@classmethod
def __import_type_support__(cls):
try:
from rosidl_generator_py import import_type_support
module = import_type_support('control_msgs')
except ImportError:
import logging
import traceback
logger = logging.getLogger(
'control_msgs.action.PointHead')
logger.debug(
'Failed to import needed modules for type support:\n' +
traceback.format_exc())
else:
cls._TYPE_SUPPORT = module.type_support_action__action__point_head
from action_msgs.msg import _goal_status_array
if _goal_status_array.Metaclass_GoalStatusArray._TYPE_SUPPORT is None:
_goal_status_array.Metaclass_GoalStatusArray.__import_type_support__()
from action_msgs.srv import _cancel_goal
if _cancel_goal.Metaclass_CancelGoal._TYPE_SUPPORT is None:
_cancel_goal.Metaclass_CancelGoal.__import_type_support__()
from control_msgs.action import _point_head
if _point_head.Metaclass_PointHead_SendGoal._TYPE_SUPPORT is None:
_point_head.Metaclass_PointHead_SendGoal.__import_type_support__()
if _point_head.Metaclass_PointHead_GetResult._TYPE_SUPPORT is None:
_point_head.Metaclass_PointHead_GetResult.__import_type_support__()
if _point_head.Metaclass_PointHead_FeedbackMessage._TYPE_SUPPORT is None:
_point_head.Metaclass_PointHead_FeedbackMessage.__import_type_support__()
class PointHead(metaclass=Metaclass_PointHead):
# The goal message defined in the action definition.
from control_msgs.action._point_head import PointHead_Goal as Goal
# The result message defined in the action definition.
from control_msgs.action._point_head import PointHead_Result as Result
# The feedback message defined in the action definition.
from control_msgs.action._point_head import PointHead_Feedback as Feedback
class Impl:
# The send_goal service using a wrapped version of the goal message as a request.
from control_msgs.action._point_head import PointHead_SendGoal as SendGoalService
# The get_result service using a wrapped version of the result message as a response.
from control_msgs.action._point_head import PointHead_GetResult as GetResultService
# The feedback message with generic fields which wraps the feedback message.
from control_msgs.action._point_head import PointHead_FeedbackMessage as FeedbackMessage
# The generic service to cancel a goal.
from action_msgs.srv._cancel_goal import CancelGoal as CancelGoalService
# The generic message for get the status of a goal.
from action_msgs.msg._goal_status_array import GoalStatusArray as GoalStatusMessage
def __init__(self):
raise NotImplementedError('Action classes can not be instantiated')
| 48,726 | Python | 36.656105 | 134 | 0.583959 |
Toni-SM/semu.robotics.ros2_bridge/src/semu.robotics.ros2_bridge/semu/robotics/ros2_bridge/packages/control_msgs/action/_follow_joint_trajectory_s.c | // generated from rosidl_generator_py/resource/_idl_support.c.em
// with input from control_msgs:action/FollowJointTrajectory.idl
// generated code does not contain a copyright notice
#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION
#include <Python.h>
#include <stdbool.h>
#ifndef _WIN32
# pragma GCC diagnostic push
# pragma GCC diagnostic ignored "-Wunused-function"
#endif
#include "numpy/ndarrayobject.h"
#ifndef _WIN32
# pragma GCC diagnostic pop
#endif
#include "rosidl_runtime_c/visibility_control.h"
#include "control_msgs/action/detail/follow_joint_trajectory__struct.h"
#include "control_msgs/action/detail/follow_joint_trajectory__functions.h"
#include "rosidl_runtime_c/primitives_sequence.h"
#include "rosidl_runtime_c/primitives_sequence_functions.h"
// Nested array functions includes
#include "control_msgs/msg/detail/joint_tolerance__functions.h"
// end nested array functions include
ROSIDL_GENERATOR_C_IMPORT
bool trajectory_msgs__msg__joint_trajectory__convert_from_py(PyObject * _pymsg, void * _ros_message);
ROSIDL_GENERATOR_C_IMPORT
PyObject * trajectory_msgs__msg__joint_trajectory__convert_to_py(void * raw_ros_message);
bool control_msgs__msg__joint_tolerance__convert_from_py(PyObject * _pymsg, void * _ros_message);
PyObject * control_msgs__msg__joint_tolerance__convert_to_py(void * raw_ros_message);
bool control_msgs__msg__joint_tolerance__convert_from_py(PyObject * _pymsg, void * _ros_message);
PyObject * control_msgs__msg__joint_tolerance__convert_to_py(void * raw_ros_message);
ROSIDL_GENERATOR_C_IMPORT
bool builtin_interfaces__msg__duration__convert_from_py(PyObject * _pymsg, void * _ros_message);
ROSIDL_GENERATOR_C_IMPORT
PyObject * builtin_interfaces__msg__duration__convert_to_py(void * raw_ros_message);
ROSIDL_GENERATOR_C_EXPORT
bool control_msgs__action__follow_joint_trajectory__goal__convert_from_py(PyObject * _pymsg, void * _ros_message)
{
// check that the passed message is of the expected Python class
{
char full_classname_dest[72];
{
char * class_name = NULL;
char * module_name = NULL;
{
PyObject * class_attr = PyObject_GetAttrString(_pymsg, "__class__");
if (class_attr) {
PyObject * name_attr = PyObject_GetAttrString(class_attr, "__name__");
if (name_attr) {
class_name = (char *)PyUnicode_1BYTE_DATA(name_attr);
Py_DECREF(name_attr);
}
PyObject * module_attr = PyObject_GetAttrString(class_attr, "__module__");
if (module_attr) {
module_name = (char *)PyUnicode_1BYTE_DATA(module_attr);
Py_DECREF(module_attr);
}
Py_DECREF(class_attr);
}
}
if (!class_name || !module_name) {
return false;
}
snprintf(full_classname_dest, sizeof(full_classname_dest), "%s.%s", module_name, class_name);
}
assert(strncmp("control_msgs.action._follow_joint_trajectory.FollowJointTrajectory_Goal", full_classname_dest, 71) == 0);
}
control_msgs__action__FollowJointTrajectory_Goal * ros_message = _ros_message;
{ // trajectory
PyObject * field = PyObject_GetAttrString(_pymsg, "trajectory");
if (!field) {
return false;
}
if (!trajectory_msgs__msg__joint_trajectory__convert_from_py(field, &ros_message->trajectory)) {
Py_DECREF(field);
return false;
}
Py_DECREF(field);
}
{ // path_tolerance
PyObject * field = PyObject_GetAttrString(_pymsg, "path_tolerance");
if (!field) {
return false;
}
PyObject * seq_field = PySequence_Fast(field, "expected a sequence in 'path_tolerance'");
if (!seq_field) {
Py_DECREF(field);
return false;
}
Py_ssize_t size = PySequence_Size(field);
if (-1 == size) {
Py_DECREF(seq_field);
Py_DECREF(field);
return false;
}
if (!control_msgs__msg__JointTolerance__Sequence__init(&(ros_message->path_tolerance), size)) {
PyErr_SetString(PyExc_RuntimeError, "unable to create control_msgs__msg__JointTolerance__Sequence ros_message");
Py_DECREF(seq_field);
Py_DECREF(field);
return false;
}
control_msgs__msg__JointTolerance * dest = ros_message->path_tolerance.data;
for (Py_ssize_t i = 0; i < size; ++i) {
if (!control_msgs__msg__joint_tolerance__convert_from_py(PySequence_Fast_GET_ITEM(seq_field, i), &dest[i])) {
Py_DECREF(seq_field);
Py_DECREF(field);
return false;
}
}
Py_DECREF(seq_field);
Py_DECREF(field);
}
{ // goal_tolerance
PyObject * field = PyObject_GetAttrString(_pymsg, "goal_tolerance");
if (!field) {
return false;
}
PyObject * seq_field = PySequence_Fast(field, "expected a sequence in 'goal_tolerance'");
if (!seq_field) {
Py_DECREF(field);
return false;
}
Py_ssize_t size = PySequence_Size(field);
if (-1 == size) {
Py_DECREF(seq_field);
Py_DECREF(field);
return false;
}
if (!control_msgs__msg__JointTolerance__Sequence__init(&(ros_message->goal_tolerance), size)) {
PyErr_SetString(PyExc_RuntimeError, "unable to create control_msgs__msg__JointTolerance__Sequence ros_message");
Py_DECREF(seq_field);
Py_DECREF(field);
return false;
}
control_msgs__msg__JointTolerance * dest = ros_message->goal_tolerance.data;
for (Py_ssize_t i = 0; i < size; ++i) {
if (!control_msgs__msg__joint_tolerance__convert_from_py(PySequence_Fast_GET_ITEM(seq_field, i), &dest[i])) {
Py_DECREF(seq_field);
Py_DECREF(field);
return false;
}
}
Py_DECREF(seq_field);
Py_DECREF(field);
}
{ // goal_time_tolerance
PyObject * field = PyObject_GetAttrString(_pymsg, "goal_time_tolerance");
if (!field) {
return false;
}
if (!builtin_interfaces__msg__duration__convert_from_py(field, &ros_message->goal_time_tolerance)) {
Py_DECREF(field);
return false;
}
Py_DECREF(field);
}
return true;
}
ROSIDL_GENERATOR_C_EXPORT
PyObject * control_msgs__action__follow_joint_trajectory__goal__convert_to_py(void * raw_ros_message)
{
/* NOTE(esteve): Call constructor of FollowJointTrajectory_Goal */
PyObject * _pymessage = NULL;
{
PyObject * pymessage_module = PyImport_ImportModule("control_msgs.action._follow_joint_trajectory");
assert(pymessage_module);
PyObject * pymessage_class = PyObject_GetAttrString(pymessage_module, "FollowJointTrajectory_Goal");
assert(pymessage_class);
Py_DECREF(pymessage_module);
_pymessage = PyObject_CallObject(pymessage_class, NULL);
Py_DECREF(pymessage_class);
if (!_pymessage) {
return NULL;
}
}
control_msgs__action__FollowJointTrajectory_Goal * ros_message = (control_msgs__action__FollowJointTrajectory_Goal *)raw_ros_message;
{ // trajectory
PyObject * field = NULL;
field = trajectory_msgs__msg__joint_trajectory__convert_to_py(&ros_message->trajectory);
if (!field) {
return NULL;
}
{
int rc = PyObject_SetAttrString(_pymessage, "trajectory", field);
Py_DECREF(field);
if (rc) {
return NULL;
}
}
}
{ // path_tolerance
PyObject * field = NULL;
size_t size = ros_message->path_tolerance.size;
field = PyList_New(size);
if (!field) {
return NULL;
}
control_msgs__msg__JointTolerance * item;
for (size_t i = 0; i < size; ++i) {
item = &(ros_message->path_tolerance.data[i]);
PyObject * pyitem = control_msgs__msg__joint_tolerance__convert_to_py(item);
if (!pyitem) {
Py_DECREF(field);
return NULL;
}
int rc = PyList_SetItem(field, i, pyitem);
(void)rc;
assert(rc == 0);
}
assert(PySequence_Check(field));
{
int rc = PyObject_SetAttrString(_pymessage, "path_tolerance", field);
Py_DECREF(field);
if (rc) {
return NULL;
}
}
}
{ // goal_tolerance
PyObject * field = NULL;
size_t size = ros_message->goal_tolerance.size;
field = PyList_New(size);
if (!field) {
return NULL;
}
control_msgs__msg__JointTolerance * item;
for (size_t i = 0; i < size; ++i) {
item = &(ros_message->goal_tolerance.data[i]);
PyObject * pyitem = control_msgs__msg__joint_tolerance__convert_to_py(item);
if (!pyitem) {
Py_DECREF(field);
return NULL;
}
int rc = PyList_SetItem(field, i, pyitem);
(void)rc;
assert(rc == 0);
}
assert(PySequence_Check(field));
{
int rc = PyObject_SetAttrString(_pymessage, "goal_tolerance", field);
Py_DECREF(field);
if (rc) {
return NULL;
}
}
}
{ // goal_time_tolerance
PyObject * field = NULL;
field = builtin_interfaces__msg__duration__convert_to_py(&ros_message->goal_time_tolerance);
if (!field) {
return NULL;
}
{
int rc = PyObject_SetAttrString(_pymessage, "goal_time_tolerance", field);
Py_DECREF(field);
if (rc) {
return NULL;
}
}
}
// ownership of _pymessage is transferred to the caller
return _pymessage;
}
#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION
// already included above
// #include <Python.h>
// already included above
// #include <stdbool.h>
// already included above
// #include "numpy/ndarrayobject.h"
// already included above
// #include "rosidl_runtime_c/visibility_control.h"
// already included above
// #include "control_msgs/action/detail/follow_joint_trajectory__struct.h"
// already included above
// #include "control_msgs/action/detail/follow_joint_trajectory__functions.h"
#include "rosidl_runtime_c/string.h"
#include "rosidl_runtime_c/string_functions.h"
ROSIDL_GENERATOR_C_EXPORT
bool control_msgs__action__follow_joint_trajectory__result__convert_from_py(PyObject * _pymsg, void * _ros_message)
{
// check that the passed message is of the expected Python class
{
char full_classname_dest[74];
{
char * class_name = NULL;
char * module_name = NULL;
{
PyObject * class_attr = PyObject_GetAttrString(_pymsg, "__class__");
if (class_attr) {
PyObject * name_attr = PyObject_GetAttrString(class_attr, "__name__");
if (name_attr) {
class_name = (char *)PyUnicode_1BYTE_DATA(name_attr);
Py_DECREF(name_attr);
}
PyObject * module_attr = PyObject_GetAttrString(class_attr, "__module__");
if (module_attr) {
module_name = (char *)PyUnicode_1BYTE_DATA(module_attr);
Py_DECREF(module_attr);
}
Py_DECREF(class_attr);
}
}
if (!class_name || !module_name) {
return false;
}
snprintf(full_classname_dest, sizeof(full_classname_dest), "%s.%s", module_name, class_name);
}
assert(strncmp("control_msgs.action._follow_joint_trajectory.FollowJointTrajectory_Result", full_classname_dest, 73) == 0);
}
control_msgs__action__FollowJointTrajectory_Result * ros_message = _ros_message;
{ // error_code
PyObject * field = PyObject_GetAttrString(_pymsg, "error_code");
if (!field) {
return false;
}
assert(PyLong_Check(field));
ros_message->error_code = (int32_t)PyLong_AsLong(field);
Py_DECREF(field);
}
{ // error_string
PyObject * field = PyObject_GetAttrString(_pymsg, "error_string");
if (!field) {
return false;
}
assert(PyUnicode_Check(field));
PyObject * encoded_field = PyUnicode_AsUTF8String(field);
if (!encoded_field) {
Py_DECREF(field);
return false;
}
rosidl_runtime_c__String__assign(&ros_message->error_string, PyBytes_AS_STRING(encoded_field));
Py_DECREF(encoded_field);
Py_DECREF(field);
}
return true;
}
ROSIDL_GENERATOR_C_EXPORT
PyObject * control_msgs__action__follow_joint_trajectory__result__convert_to_py(void * raw_ros_message)
{
/* NOTE(esteve): Call constructor of FollowJointTrajectory_Result */
PyObject * _pymessage = NULL;
{
PyObject * pymessage_module = PyImport_ImportModule("control_msgs.action._follow_joint_trajectory");
assert(pymessage_module);
PyObject * pymessage_class = PyObject_GetAttrString(pymessage_module, "FollowJointTrajectory_Result");
assert(pymessage_class);
Py_DECREF(pymessage_module);
_pymessage = PyObject_CallObject(pymessage_class, NULL);
Py_DECREF(pymessage_class);
if (!_pymessage) {
return NULL;
}
}
control_msgs__action__FollowJointTrajectory_Result * ros_message = (control_msgs__action__FollowJointTrajectory_Result *)raw_ros_message;
{ // error_code
PyObject * field = NULL;
field = PyLong_FromLong(ros_message->error_code);
{
int rc = PyObject_SetAttrString(_pymessage, "error_code", field);
Py_DECREF(field);
if (rc) {
return NULL;
}
}
}
{ // error_string
PyObject * field = NULL;
field = PyUnicode_DecodeUTF8(
ros_message->error_string.data,
strlen(ros_message->error_string.data),
"strict");
if (!field) {
return NULL;
}
{
int rc = PyObject_SetAttrString(_pymessage, "error_string", field);
Py_DECREF(field);
if (rc) {
return NULL;
}
}
}
// ownership of _pymessage is transferred to the caller
return _pymessage;
}
#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION
// already included above
// #include <Python.h>
// already included above
// #include <stdbool.h>
// already included above
// #include "numpy/ndarrayobject.h"
// already included above
// #include "rosidl_runtime_c/visibility_control.h"
// already included above
// #include "control_msgs/action/detail/follow_joint_trajectory__struct.h"
// already included above
// #include "control_msgs/action/detail/follow_joint_trajectory__functions.h"
// already included above
// #include "rosidl_runtime_c/primitives_sequence.h"
// already included above
// #include "rosidl_runtime_c/primitives_sequence_functions.h"
// already included above
// #include "rosidl_runtime_c/string.h"
// already included above
// #include "rosidl_runtime_c/string_functions.h"
ROSIDL_GENERATOR_C_IMPORT
bool std_msgs__msg__header__convert_from_py(PyObject * _pymsg, void * _ros_message);
ROSIDL_GENERATOR_C_IMPORT
PyObject * std_msgs__msg__header__convert_to_py(void * raw_ros_message);
ROSIDL_GENERATOR_C_IMPORT
bool trajectory_msgs__msg__joint_trajectory_point__convert_from_py(PyObject * _pymsg, void * _ros_message);
ROSIDL_GENERATOR_C_IMPORT
PyObject * trajectory_msgs__msg__joint_trajectory_point__convert_to_py(void * raw_ros_message);
ROSIDL_GENERATOR_C_IMPORT
bool trajectory_msgs__msg__joint_trajectory_point__convert_from_py(PyObject * _pymsg, void * _ros_message);
ROSIDL_GENERATOR_C_IMPORT
PyObject * trajectory_msgs__msg__joint_trajectory_point__convert_to_py(void * raw_ros_message);
ROSIDL_GENERATOR_C_IMPORT
bool trajectory_msgs__msg__joint_trajectory_point__convert_from_py(PyObject * _pymsg, void * _ros_message);
ROSIDL_GENERATOR_C_IMPORT
PyObject * trajectory_msgs__msg__joint_trajectory_point__convert_to_py(void * raw_ros_message);
ROSIDL_GENERATOR_C_EXPORT
bool control_msgs__action__follow_joint_trajectory__feedback__convert_from_py(PyObject * _pymsg, void * _ros_message)
{
// check that the passed message is of the expected Python class
{
char full_classname_dest[76];
{
char * class_name = NULL;
char * module_name = NULL;
{
PyObject * class_attr = PyObject_GetAttrString(_pymsg, "__class__");
if (class_attr) {
PyObject * name_attr = PyObject_GetAttrString(class_attr, "__name__");
if (name_attr) {
class_name = (char *)PyUnicode_1BYTE_DATA(name_attr);
Py_DECREF(name_attr);
}
PyObject * module_attr = PyObject_GetAttrString(class_attr, "__module__");
if (module_attr) {
module_name = (char *)PyUnicode_1BYTE_DATA(module_attr);
Py_DECREF(module_attr);
}
Py_DECREF(class_attr);
}
}
if (!class_name || !module_name) {
return false;
}
snprintf(full_classname_dest, sizeof(full_classname_dest), "%s.%s", module_name, class_name);
}
assert(strncmp("control_msgs.action._follow_joint_trajectory.FollowJointTrajectory_Feedback", full_classname_dest, 75) == 0);
}
control_msgs__action__FollowJointTrajectory_Feedback * ros_message = _ros_message;
{ // header
PyObject * field = PyObject_GetAttrString(_pymsg, "header");
if (!field) {
return false;
}
if (!std_msgs__msg__header__convert_from_py(field, &ros_message->header)) {
Py_DECREF(field);
return false;
}
Py_DECREF(field);
}
{ // joint_names
PyObject * field = PyObject_GetAttrString(_pymsg, "joint_names");
if (!field) {
return false;
}
PyObject * seq_field = PySequence_Fast(field, "expected a sequence in 'joint_names'");
if (!seq_field) {
Py_DECREF(field);
return false;
}
Py_ssize_t size = PySequence_Size(field);
if (-1 == size) {
Py_DECREF(seq_field);
Py_DECREF(field);
return false;
}
if (!rosidl_runtime_c__String__Sequence__init(&(ros_message->joint_names), size)) {
PyErr_SetString(PyExc_RuntimeError, "unable to create String__Sequence ros_message");
Py_DECREF(seq_field);
Py_DECREF(field);
return false;
}
rosidl_runtime_c__String * dest = ros_message->joint_names.data;
for (Py_ssize_t i = 0; i < size; ++i) {
PyObject * item = PySequence_Fast_GET_ITEM(seq_field, i);
if (!item) {
Py_DECREF(seq_field);
Py_DECREF(field);
return false;
}
assert(PyUnicode_Check(item));
PyObject * encoded_item = PyUnicode_AsUTF8String(item);
if (!encoded_item) {
Py_DECREF(seq_field);
Py_DECREF(field);
return false;
}
rosidl_runtime_c__String__assign(&dest[i], PyBytes_AS_STRING(encoded_item));
Py_DECREF(encoded_item);
}
Py_DECREF(seq_field);
Py_DECREF(field);
}
{ // desired
PyObject * field = PyObject_GetAttrString(_pymsg, "desired");
if (!field) {
return false;
}
if (!trajectory_msgs__msg__joint_trajectory_point__convert_from_py(field, &ros_message->desired)) {
Py_DECREF(field);
return false;
}
Py_DECREF(field);
}
{ // actual
PyObject * field = PyObject_GetAttrString(_pymsg, "actual");
if (!field) {
return false;
}
if (!trajectory_msgs__msg__joint_trajectory_point__convert_from_py(field, &ros_message->actual)) {
Py_DECREF(field);
return false;
}
Py_DECREF(field);
}
{ // error
PyObject * field = PyObject_GetAttrString(_pymsg, "error");
if (!field) {
return false;
}
if (!trajectory_msgs__msg__joint_trajectory_point__convert_from_py(field, &ros_message->error)) {
Py_DECREF(field);
return false;
}
Py_DECREF(field);
}
return true;
}
ROSIDL_GENERATOR_C_EXPORT
PyObject * control_msgs__action__follow_joint_trajectory__feedback__convert_to_py(void * raw_ros_message)
{
/* NOTE(esteve): Call constructor of FollowJointTrajectory_Feedback */
PyObject * _pymessage = NULL;
{
PyObject * pymessage_module = PyImport_ImportModule("control_msgs.action._follow_joint_trajectory");
assert(pymessage_module);
PyObject * pymessage_class = PyObject_GetAttrString(pymessage_module, "FollowJointTrajectory_Feedback");
assert(pymessage_class);
Py_DECREF(pymessage_module);
_pymessage = PyObject_CallObject(pymessage_class, NULL);
Py_DECREF(pymessage_class);
if (!_pymessage) {
return NULL;
}
}
control_msgs__action__FollowJointTrajectory_Feedback * ros_message = (control_msgs__action__FollowJointTrajectory_Feedback *)raw_ros_message;
{ // header
PyObject * field = NULL;
field = std_msgs__msg__header__convert_to_py(&ros_message->header);
if (!field) {
return NULL;
}
{
int rc = PyObject_SetAttrString(_pymessage, "header", field);
Py_DECREF(field);
if (rc) {
return NULL;
}
}
}
{ // joint_names
PyObject * field = NULL;
size_t size = ros_message->joint_names.size;
rosidl_runtime_c__String * src = ros_message->joint_names.data;
field = PyList_New(size);
if (!field) {
return NULL;
}
for (size_t i = 0; i < size; ++i) {
PyObject * decoded_item = PyUnicode_DecodeUTF8(src[i].data, strlen(src[i].data), "strict");
if (!decoded_item) {
return NULL;
}
int rc = PyList_SetItem(field, i, decoded_item);
(void)rc;
assert(rc == 0);
}
assert(PySequence_Check(field));
{
int rc = PyObject_SetAttrString(_pymessage, "joint_names", field);
Py_DECREF(field);
if (rc) {
return NULL;
}
}
}
{ // desired
PyObject * field = NULL;
field = trajectory_msgs__msg__joint_trajectory_point__convert_to_py(&ros_message->desired);
if (!field) {
return NULL;
}
{
int rc = PyObject_SetAttrString(_pymessage, "desired", field);
Py_DECREF(field);
if (rc) {
return NULL;
}
}
}
{ // actual
PyObject * field = NULL;
field = trajectory_msgs__msg__joint_trajectory_point__convert_to_py(&ros_message->actual);
if (!field) {
return NULL;
}
{
int rc = PyObject_SetAttrString(_pymessage, "actual", field);
Py_DECREF(field);
if (rc) {
return NULL;
}
}
}
{ // error
PyObject * field = NULL;
field = trajectory_msgs__msg__joint_trajectory_point__convert_to_py(&ros_message->error);
if (!field) {
return NULL;
}
{
int rc = PyObject_SetAttrString(_pymessage, "error", field);
Py_DECREF(field);
if (rc) {
return NULL;
}
}
}
// ownership of _pymessage is transferred to the caller
return _pymessage;
}
#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION
// already included above
// #include <Python.h>
// already included above
// #include <stdbool.h>
// already included above
// #include "numpy/ndarrayobject.h"
// already included above
// #include "rosidl_runtime_c/visibility_control.h"
// already included above
// #include "control_msgs/action/detail/follow_joint_trajectory__struct.h"
// already included above
// #include "control_msgs/action/detail/follow_joint_trajectory__functions.h"
ROSIDL_GENERATOR_C_IMPORT
bool unique_identifier_msgs__msg__uuid__convert_from_py(PyObject * _pymsg, void * _ros_message);
ROSIDL_GENERATOR_C_IMPORT
PyObject * unique_identifier_msgs__msg__uuid__convert_to_py(void * raw_ros_message);
bool control_msgs__action__follow_joint_trajectory__goal__convert_from_py(PyObject * _pymsg, void * _ros_message);
PyObject * control_msgs__action__follow_joint_trajectory__goal__convert_to_py(void * raw_ros_message);
ROSIDL_GENERATOR_C_EXPORT
bool control_msgs__action__follow_joint_trajectory__send_goal__request__convert_from_py(PyObject * _pymsg, void * _ros_message)
{
// check that the passed message is of the expected Python class
{
char full_classname_dest[84];
{
char * class_name = NULL;
char * module_name = NULL;
{
PyObject * class_attr = PyObject_GetAttrString(_pymsg, "__class__");
if (class_attr) {
PyObject * name_attr = PyObject_GetAttrString(class_attr, "__name__");
if (name_attr) {
class_name = (char *)PyUnicode_1BYTE_DATA(name_attr);
Py_DECREF(name_attr);
}
PyObject * module_attr = PyObject_GetAttrString(class_attr, "__module__");
if (module_attr) {
module_name = (char *)PyUnicode_1BYTE_DATA(module_attr);
Py_DECREF(module_attr);
}
Py_DECREF(class_attr);
}
}
if (!class_name || !module_name) {
return false;
}
snprintf(full_classname_dest, sizeof(full_classname_dest), "%s.%s", module_name, class_name);
}
assert(strncmp("control_msgs.action._follow_joint_trajectory.FollowJointTrajectory_SendGoal_Request", full_classname_dest, 83) == 0);
}
control_msgs__action__FollowJointTrajectory_SendGoal_Request * ros_message = _ros_message;
{ // goal_id
PyObject * field = PyObject_GetAttrString(_pymsg, "goal_id");
if (!field) {
return false;
}
if (!unique_identifier_msgs__msg__uuid__convert_from_py(field, &ros_message->goal_id)) {
Py_DECREF(field);
return false;
}
Py_DECREF(field);
}
{ // goal
PyObject * field = PyObject_GetAttrString(_pymsg, "goal");
if (!field) {
return false;
}
if (!control_msgs__action__follow_joint_trajectory__goal__convert_from_py(field, &ros_message->goal)) {
Py_DECREF(field);
return false;
}
Py_DECREF(field);
}
return true;
}
ROSIDL_GENERATOR_C_EXPORT
PyObject * control_msgs__action__follow_joint_trajectory__send_goal__request__convert_to_py(void * raw_ros_message)
{
/* NOTE(esteve): Call constructor of FollowJointTrajectory_SendGoal_Request */
PyObject * _pymessage = NULL;
{
PyObject * pymessage_module = PyImport_ImportModule("control_msgs.action._follow_joint_trajectory");
assert(pymessage_module);
PyObject * pymessage_class = PyObject_GetAttrString(pymessage_module, "FollowJointTrajectory_SendGoal_Request");
assert(pymessage_class);
Py_DECREF(pymessage_module);
_pymessage = PyObject_CallObject(pymessage_class, NULL);
Py_DECREF(pymessage_class);
if (!_pymessage) {
return NULL;
}
}
control_msgs__action__FollowJointTrajectory_SendGoal_Request * ros_message = (control_msgs__action__FollowJointTrajectory_SendGoal_Request *)raw_ros_message;
{ // goal_id
PyObject * field = NULL;
field = unique_identifier_msgs__msg__uuid__convert_to_py(&ros_message->goal_id);
if (!field) {
return NULL;
}
{
int rc = PyObject_SetAttrString(_pymessage, "goal_id", field);
Py_DECREF(field);
if (rc) {
return NULL;
}
}
}
{ // goal
PyObject * field = NULL;
field = control_msgs__action__follow_joint_trajectory__goal__convert_to_py(&ros_message->goal);
if (!field) {
return NULL;
}
{
int rc = PyObject_SetAttrString(_pymessage, "goal", field);
Py_DECREF(field);
if (rc) {
return NULL;
}
}
}
// ownership of _pymessage is transferred to the caller
return _pymessage;
}
#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION
// already included above
// #include <Python.h>
// already included above
// #include <stdbool.h>
// already included above
// #include "numpy/ndarrayobject.h"
// already included above
// #include "rosidl_runtime_c/visibility_control.h"
// already included above
// #include "control_msgs/action/detail/follow_joint_trajectory__struct.h"
// already included above
// #include "control_msgs/action/detail/follow_joint_trajectory__functions.h"
ROSIDL_GENERATOR_C_IMPORT
bool builtin_interfaces__msg__time__convert_from_py(PyObject * _pymsg, void * _ros_message);
ROSIDL_GENERATOR_C_IMPORT
PyObject * builtin_interfaces__msg__time__convert_to_py(void * raw_ros_message);
ROSIDL_GENERATOR_C_EXPORT
bool control_msgs__action__follow_joint_trajectory__send_goal__response__convert_from_py(PyObject * _pymsg, void * _ros_message)
{
// check that the passed message is of the expected Python class
{
char full_classname_dest[85];
{
char * class_name = NULL;
char * module_name = NULL;
{
PyObject * class_attr = PyObject_GetAttrString(_pymsg, "__class__");
if (class_attr) {
PyObject * name_attr = PyObject_GetAttrString(class_attr, "__name__");
if (name_attr) {
class_name = (char *)PyUnicode_1BYTE_DATA(name_attr);
Py_DECREF(name_attr);
}
PyObject * module_attr = PyObject_GetAttrString(class_attr, "__module__");
if (module_attr) {
module_name = (char *)PyUnicode_1BYTE_DATA(module_attr);
Py_DECREF(module_attr);
}
Py_DECREF(class_attr);
}
}
if (!class_name || !module_name) {
return false;
}
snprintf(full_classname_dest, sizeof(full_classname_dest), "%s.%s", module_name, class_name);
}
assert(strncmp("control_msgs.action._follow_joint_trajectory.FollowJointTrajectory_SendGoal_Response", full_classname_dest, 84) == 0);
}
control_msgs__action__FollowJointTrajectory_SendGoal_Response * ros_message = _ros_message;
{ // accepted
PyObject * field = PyObject_GetAttrString(_pymsg, "accepted");
if (!field) {
return false;
}
assert(PyBool_Check(field));
ros_message->accepted = (Py_True == field);
Py_DECREF(field);
}
{ // stamp
PyObject * field = PyObject_GetAttrString(_pymsg, "stamp");
if (!field) {
return false;
}
if (!builtin_interfaces__msg__time__convert_from_py(field, &ros_message->stamp)) {
Py_DECREF(field);
return false;
}
Py_DECREF(field);
}
return true;
}
ROSIDL_GENERATOR_C_EXPORT
PyObject * control_msgs__action__follow_joint_trajectory__send_goal__response__convert_to_py(void * raw_ros_message)
{
/* NOTE(esteve): Call constructor of FollowJointTrajectory_SendGoal_Response */
PyObject * _pymessage = NULL;
{
PyObject * pymessage_module = PyImport_ImportModule("control_msgs.action._follow_joint_trajectory");
assert(pymessage_module);
PyObject * pymessage_class = PyObject_GetAttrString(pymessage_module, "FollowJointTrajectory_SendGoal_Response");
assert(pymessage_class);
Py_DECREF(pymessage_module);
_pymessage = PyObject_CallObject(pymessage_class, NULL);
Py_DECREF(pymessage_class);
if (!_pymessage) {
return NULL;
}
}
control_msgs__action__FollowJointTrajectory_SendGoal_Response * ros_message = (control_msgs__action__FollowJointTrajectory_SendGoal_Response *)raw_ros_message;
{ // accepted
PyObject * field = NULL;
field = PyBool_FromLong(ros_message->accepted ? 1 : 0);
{
int rc = PyObject_SetAttrString(_pymessage, "accepted", field);
Py_DECREF(field);
if (rc) {
return NULL;
}
}
}
{ // stamp
PyObject * field = NULL;
field = builtin_interfaces__msg__time__convert_to_py(&ros_message->stamp);
if (!field) {
return NULL;
}
{
int rc = PyObject_SetAttrString(_pymessage, "stamp", field);
Py_DECREF(field);
if (rc) {
return NULL;
}
}
}
// ownership of _pymessage is transferred to the caller
return _pymessage;
}
#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION
// already included above
// #include <Python.h>
// already included above
// #include <stdbool.h>
// already included above
// #include "numpy/ndarrayobject.h"
// already included above
// #include "rosidl_runtime_c/visibility_control.h"
// already included above
// #include "control_msgs/action/detail/follow_joint_trajectory__struct.h"
// already included above
// #include "control_msgs/action/detail/follow_joint_trajectory__functions.h"
ROSIDL_GENERATOR_C_IMPORT
bool unique_identifier_msgs__msg__uuid__convert_from_py(PyObject * _pymsg, void * _ros_message);
ROSIDL_GENERATOR_C_IMPORT
PyObject * unique_identifier_msgs__msg__uuid__convert_to_py(void * raw_ros_message);
ROSIDL_GENERATOR_C_EXPORT
bool control_msgs__action__follow_joint_trajectory__get_result__request__convert_from_py(PyObject * _pymsg, void * _ros_message)
{
// check that the passed message is of the expected Python class
{
char full_classname_dest[85];
{
char * class_name = NULL;
char * module_name = NULL;
{
PyObject * class_attr = PyObject_GetAttrString(_pymsg, "__class__");
if (class_attr) {
PyObject * name_attr = PyObject_GetAttrString(class_attr, "__name__");
if (name_attr) {
class_name = (char *)PyUnicode_1BYTE_DATA(name_attr);
Py_DECREF(name_attr);
}
PyObject * module_attr = PyObject_GetAttrString(class_attr, "__module__");
if (module_attr) {
module_name = (char *)PyUnicode_1BYTE_DATA(module_attr);
Py_DECREF(module_attr);
}
Py_DECREF(class_attr);
}
}
if (!class_name || !module_name) {
return false;
}
snprintf(full_classname_dest, sizeof(full_classname_dest), "%s.%s", module_name, class_name);
}
assert(strncmp("control_msgs.action._follow_joint_trajectory.FollowJointTrajectory_GetResult_Request", full_classname_dest, 84) == 0);
}
control_msgs__action__FollowJointTrajectory_GetResult_Request * ros_message = _ros_message;
{ // goal_id
PyObject * field = PyObject_GetAttrString(_pymsg, "goal_id");
if (!field) {
return false;
}
if (!unique_identifier_msgs__msg__uuid__convert_from_py(field, &ros_message->goal_id)) {
Py_DECREF(field);
return false;
}
Py_DECREF(field);
}
return true;
}
ROSIDL_GENERATOR_C_EXPORT
PyObject * control_msgs__action__follow_joint_trajectory__get_result__request__convert_to_py(void * raw_ros_message)
{
/* NOTE(esteve): Call constructor of FollowJointTrajectory_GetResult_Request */
PyObject * _pymessage = NULL;
{
PyObject * pymessage_module = PyImport_ImportModule("control_msgs.action._follow_joint_trajectory");
assert(pymessage_module);
PyObject * pymessage_class = PyObject_GetAttrString(pymessage_module, "FollowJointTrajectory_GetResult_Request");
assert(pymessage_class);
Py_DECREF(pymessage_module);
_pymessage = PyObject_CallObject(pymessage_class, NULL);
Py_DECREF(pymessage_class);
if (!_pymessage) {
return NULL;
}
}
control_msgs__action__FollowJointTrajectory_GetResult_Request * ros_message = (control_msgs__action__FollowJointTrajectory_GetResult_Request *)raw_ros_message;
{ // goal_id
PyObject * field = NULL;
field = unique_identifier_msgs__msg__uuid__convert_to_py(&ros_message->goal_id);
if (!field) {
return NULL;
}
{
int rc = PyObject_SetAttrString(_pymessage, "goal_id", field);
Py_DECREF(field);
if (rc) {
return NULL;
}
}
}
// ownership of _pymessage is transferred to the caller
return _pymessage;
}
#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION
// already included above
// #include <Python.h>
// already included above
// #include <stdbool.h>
// already included above
// #include "numpy/ndarrayobject.h"
// already included above
// #include "rosidl_runtime_c/visibility_control.h"
// already included above
// #include "control_msgs/action/detail/follow_joint_trajectory__struct.h"
// already included above
// #include "control_msgs/action/detail/follow_joint_trajectory__functions.h"
bool control_msgs__action__follow_joint_trajectory__result__convert_from_py(PyObject * _pymsg, void * _ros_message);
PyObject * control_msgs__action__follow_joint_trajectory__result__convert_to_py(void * raw_ros_message);
ROSIDL_GENERATOR_C_EXPORT
bool control_msgs__action__follow_joint_trajectory__get_result__response__convert_from_py(PyObject * _pymsg, void * _ros_message)
{
// check that the passed message is of the expected Python class
{
char full_classname_dest[86];
{
char * class_name = NULL;
char * module_name = NULL;
{
PyObject * class_attr = PyObject_GetAttrString(_pymsg, "__class__");
if (class_attr) {
PyObject * name_attr = PyObject_GetAttrString(class_attr, "__name__");
if (name_attr) {
class_name = (char *)PyUnicode_1BYTE_DATA(name_attr);
Py_DECREF(name_attr);
}
PyObject * module_attr = PyObject_GetAttrString(class_attr, "__module__");
if (module_attr) {
module_name = (char *)PyUnicode_1BYTE_DATA(module_attr);
Py_DECREF(module_attr);
}
Py_DECREF(class_attr);
}
}
if (!class_name || !module_name) {
return false;
}
snprintf(full_classname_dest, sizeof(full_classname_dest), "%s.%s", module_name, class_name);
}
assert(strncmp("control_msgs.action._follow_joint_trajectory.FollowJointTrajectory_GetResult_Response", full_classname_dest, 85) == 0);
}
control_msgs__action__FollowJointTrajectory_GetResult_Response * ros_message = _ros_message;
{ // status
PyObject * field = PyObject_GetAttrString(_pymsg, "status");
if (!field) {
return false;
}
assert(PyLong_Check(field));
ros_message->status = (int8_t)PyLong_AsLong(field);
Py_DECREF(field);
}
{ // result
PyObject * field = PyObject_GetAttrString(_pymsg, "result");
if (!field) {
return false;
}
if (!control_msgs__action__follow_joint_trajectory__result__convert_from_py(field, &ros_message->result)) {
Py_DECREF(field);
return false;
}
Py_DECREF(field);
}
return true;
}
ROSIDL_GENERATOR_C_EXPORT
PyObject * control_msgs__action__follow_joint_trajectory__get_result__response__convert_to_py(void * raw_ros_message)
{
/* NOTE(esteve): Call constructor of FollowJointTrajectory_GetResult_Response */
PyObject * _pymessage = NULL;
{
PyObject * pymessage_module = PyImport_ImportModule("control_msgs.action._follow_joint_trajectory");
assert(pymessage_module);
PyObject * pymessage_class = PyObject_GetAttrString(pymessage_module, "FollowJointTrajectory_GetResult_Response");
assert(pymessage_class);
Py_DECREF(pymessage_module);
_pymessage = PyObject_CallObject(pymessage_class, NULL);
Py_DECREF(pymessage_class);
if (!_pymessage) {
return NULL;
}
}
control_msgs__action__FollowJointTrajectory_GetResult_Response * ros_message = (control_msgs__action__FollowJointTrajectory_GetResult_Response *)raw_ros_message;
{ // status
PyObject * field = NULL;
field = PyLong_FromLong(ros_message->status);
{
int rc = PyObject_SetAttrString(_pymessage, "status", field);
Py_DECREF(field);
if (rc) {
return NULL;
}
}
}
{ // result
PyObject * field = NULL;
field = control_msgs__action__follow_joint_trajectory__result__convert_to_py(&ros_message->result);
if (!field) {
return NULL;
}
{
int rc = PyObject_SetAttrString(_pymessage, "result", field);
Py_DECREF(field);
if (rc) {
return NULL;
}
}
}
// ownership of _pymessage is transferred to the caller
return _pymessage;
}
#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION
// already included above
// #include <Python.h>
// already included above
// #include <stdbool.h>
// already included above
// #include "numpy/ndarrayobject.h"
// already included above
// #include "rosidl_runtime_c/visibility_control.h"
// already included above
// #include "control_msgs/action/detail/follow_joint_trajectory__struct.h"
// already included above
// #include "control_msgs/action/detail/follow_joint_trajectory__functions.h"
ROSIDL_GENERATOR_C_IMPORT
bool unique_identifier_msgs__msg__uuid__convert_from_py(PyObject * _pymsg, void * _ros_message);
ROSIDL_GENERATOR_C_IMPORT
PyObject * unique_identifier_msgs__msg__uuid__convert_to_py(void * raw_ros_message);
bool control_msgs__action__follow_joint_trajectory__feedback__convert_from_py(PyObject * _pymsg, void * _ros_message);
PyObject * control_msgs__action__follow_joint_trajectory__feedback__convert_to_py(void * raw_ros_message);
ROSIDL_GENERATOR_C_EXPORT
bool control_msgs__action__follow_joint_trajectory__feedback_message__convert_from_py(PyObject * _pymsg, void * _ros_message)
{
// check that the passed message is of the expected Python class
{
char full_classname_dest[83];
{
char * class_name = NULL;
char * module_name = NULL;
{
PyObject * class_attr = PyObject_GetAttrString(_pymsg, "__class__");
if (class_attr) {
PyObject * name_attr = PyObject_GetAttrString(class_attr, "__name__");
if (name_attr) {
class_name = (char *)PyUnicode_1BYTE_DATA(name_attr);
Py_DECREF(name_attr);
}
PyObject * module_attr = PyObject_GetAttrString(class_attr, "__module__");
if (module_attr) {
module_name = (char *)PyUnicode_1BYTE_DATA(module_attr);
Py_DECREF(module_attr);
}
Py_DECREF(class_attr);
}
}
if (!class_name || !module_name) {
return false;
}
snprintf(full_classname_dest, sizeof(full_classname_dest), "%s.%s", module_name, class_name);
}
assert(strncmp("control_msgs.action._follow_joint_trajectory.FollowJointTrajectory_FeedbackMessage", full_classname_dest, 82) == 0);
}
control_msgs__action__FollowJointTrajectory_FeedbackMessage * ros_message = _ros_message;
{ // goal_id
PyObject * field = PyObject_GetAttrString(_pymsg, "goal_id");
if (!field) {
return false;
}
if (!unique_identifier_msgs__msg__uuid__convert_from_py(field, &ros_message->goal_id)) {
Py_DECREF(field);
return false;
}
Py_DECREF(field);
}
{ // feedback
PyObject * field = PyObject_GetAttrString(_pymsg, "feedback");
if (!field) {
return false;
}
if (!control_msgs__action__follow_joint_trajectory__feedback__convert_from_py(field, &ros_message->feedback)) {
Py_DECREF(field);
return false;
}
Py_DECREF(field);
}
return true;
}
ROSIDL_GENERATOR_C_EXPORT
PyObject * control_msgs__action__follow_joint_trajectory__feedback_message__convert_to_py(void * raw_ros_message)
{
/* NOTE(esteve): Call constructor of FollowJointTrajectory_FeedbackMessage */
PyObject * _pymessage = NULL;
{
PyObject * pymessage_module = PyImport_ImportModule("control_msgs.action._follow_joint_trajectory");
assert(pymessage_module);
PyObject * pymessage_class = PyObject_GetAttrString(pymessage_module, "FollowJointTrajectory_FeedbackMessage");
assert(pymessage_class);
Py_DECREF(pymessage_module);
_pymessage = PyObject_CallObject(pymessage_class, NULL);
Py_DECREF(pymessage_class);
if (!_pymessage) {
return NULL;
}
}
control_msgs__action__FollowJointTrajectory_FeedbackMessage * ros_message = (control_msgs__action__FollowJointTrajectory_FeedbackMessage *)raw_ros_message;
{ // goal_id
PyObject * field = NULL;
field = unique_identifier_msgs__msg__uuid__convert_to_py(&ros_message->goal_id);
if (!field) {
return NULL;
}
{
int rc = PyObject_SetAttrString(_pymessage, "goal_id", field);
Py_DECREF(field);
if (rc) {
return NULL;
}
}
}
{ // feedback
PyObject * field = NULL;
field = control_msgs__action__follow_joint_trajectory__feedback__convert_to_py(&ros_message->feedback);
if (!field) {
return NULL;
}
{
int rc = PyObject_SetAttrString(_pymessage, "feedback", field);
Py_DECREF(field);
if (rc) {
return NULL;
}
}
}
// ownership of _pymessage is transferred to the caller
return _pymessage;
}
| 43,203 | C | 32.753125 | 163 | 0.644076 |
Toni-SM/semu.robotics.ros2_bridge/src/semu.robotics.ros2_bridge/semu/robotics/ros2_bridge/packages/control_msgs/action/_single_joint_position_s.c | // generated from rosidl_generator_py/resource/_idl_support.c.em
// with input from control_msgs:action/SingleJointPosition.idl
// generated code does not contain a copyright notice
#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION
#include <Python.h>
#include <stdbool.h>
#ifndef _WIN32
# pragma GCC diagnostic push
# pragma GCC diagnostic ignored "-Wunused-function"
#endif
#include "numpy/ndarrayobject.h"
#ifndef _WIN32
# pragma GCC diagnostic pop
#endif
#include "rosidl_runtime_c/visibility_control.h"
#include "control_msgs/action/detail/single_joint_position__struct.h"
#include "control_msgs/action/detail/single_joint_position__functions.h"
ROSIDL_GENERATOR_C_IMPORT
bool builtin_interfaces__msg__duration__convert_from_py(PyObject * _pymsg, void * _ros_message);
ROSIDL_GENERATOR_C_IMPORT
PyObject * builtin_interfaces__msg__duration__convert_to_py(void * raw_ros_message);
ROSIDL_GENERATOR_C_EXPORT
bool control_msgs__action__single_joint_position__goal__convert_from_py(PyObject * _pymsg, void * _ros_message)
{
// check that the passed message is of the expected Python class
{
char full_classname_dest[68];
{
char * class_name = NULL;
char * module_name = NULL;
{
PyObject * class_attr = PyObject_GetAttrString(_pymsg, "__class__");
if (class_attr) {
PyObject * name_attr = PyObject_GetAttrString(class_attr, "__name__");
if (name_attr) {
class_name = (char *)PyUnicode_1BYTE_DATA(name_attr);
Py_DECREF(name_attr);
}
PyObject * module_attr = PyObject_GetAttrString(class_attr, "__module__");
if (module_attr) {
module_name = (char *)PyUnicode_1BYTE_DATA(module_attr);
Py_DECREF(module_attr);
}
Py_DECREF(class_attr);
}
}
if (!class_name || !module_name) {
return false;
}
snprintf(full_classname_dest, sizeof(full_classname_dest), "%s.%s", module_name, class_name);
}
assert(strncmp("control_msgs.action._single_joint_position.SingleJointPosition_Goal", full_classname_dest, 67) == 0);
}
control_msgs__action__SingleJointPosition_Goal * ros_message = _ros_message;
{ // position
PyObject * field = PyObject_GetAttrString(_pymsg, "position");
if (!field) {
return false;
}
assert(PyFloat_Check(field));
ros_message->position = PyFloat_AS_DOUBLE(field);
Py_DECREF(field);
}
{ // min_duration
PyObject * field = PyObject_GetAttrString(_pymsg, "min_duration");
if (!field) {
return false;
}
if (!builtin_interfaces__msg__duration__convert_from_py(field, &ros_message->min_duration)) {
Py_DECREF(field);
return false;
}
Py_DECREF(field);
}
{ // max_velocity
PyObject * field = PyObject_GetAttrString(_pymsg, "max_velocity");
if (!field) {
return false;
}
assert(PyFloat_Check(field));
ros_message->max_velocity = PyFloat_AS_DOUBLE(field);
Py_DECREF(field);
}
return true;
}
ROSIDL_GENERATOR_C_EXPORT
PyObject * control_msgs__action__single_joint_position__goal__convert_to_py(void * raw_ros_message)
{
/* NOTE(esteve): Call constructor of SingleJointPosition_Goal */
PyObject * _pymessage = NULL;
{
PyObject * pymessage_module = PyImport_ImportModule("control_msgs.action._single_joint_position");
assert(pymessage_module);
PyObject * pymessage_class = PyObject_GetAttrString(pymessage_module, "SingleJointPosition_Goal");
assert(pymessage_class);
Py_DECREF(pymessage_module);
_pymessage = PyObject_CallObject(pymessage_class, NULL);
Py_DECREF(pymessage_class);
if (!_pymessage) {
return NULL;
}
}
control_msgs__action__SingleJointPosition_Goal * ros_message = (control_msgs__action__SingleJointPosition_Goal *)raw_ros_message;
{ // position
PyObject * field = NULL;
field = PyFloat_FromDouble(ros_message->position);
{
int rc = PyObject_SetAttrString(_pymessage, "position", field);
Py_DECREF(field);
if (rc) {
return NULL;
}
}
}
{ // min_duration
PyObject * field = NULL;
field = builtin_interfaces__msg__duration__convert_to_py(&ros_message->min_duration);
if (!field) {
return NULL;
}
{
int rc = PyObject_SetAttrString(_pymessage, "min_duration", field);
Py_DECREF(field);
if (rc) {
return NULL;
}
}
}
{ // max_velocity
PyObject * field = NULL;
field = PyFloat_FromDouble(ros_message->max_velocity);
{
int rc = PyObject_SetAttrString(_pymessage, "max_velocity", field);
Py_DECREF(field);
if (rc) {
return NULL;
}
}
}
// ownership of _pymessage is transferred to the caller
return _pymessage;
}
#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION
// already included above
// #include <Python.h>
// already included above
// #include <stdbool.h>
// already included above
// #include "numpy/ndarrayobject.h"
// already included above
// #include "rosidl_runtime_c/visibility_control.h"
// already included above
// #include "control_msgs/action/detail/single_joint_position__struct.h"
// already included above
// #include "control_msgs/action/detail/single_joint_position__functions.h"
ROSIDL_GENERATOR_C_EXPORT
bool control_msgs__action__single_joint_position__result__convert_from_py(PyObject * _pymsg, void * _ros_message)
{
// check that the passed message is of the expected Python class
{
char full_classname_dest[70];
{
char * class_name = NULL;
char * module_name = NULL;
{
PyObject * class_attr = PyObject_GetAttrString(_pymsg, "__class__");
if (class_attr) {
PyObject * name_attr = PyObject_GetAttrString(class_attr, "__name__");
if (name_attr) {
class_name = (char *)PyUnicode_1BYTE_DATA(name_attr);
Py_DECREF(name_attr);
}
PyObject * module_attr = PyObject_GetAttrString(class_attr, "__module__");
if (module_attr) {
module_name = (char *)PyUnicode_1BYTE_DATA(module_attr);
Py_DECREF(module_attr);
}
Py_DECREF(class_attr);
}
}
if (!class_name || !module_name) {
return false;
}
snprintf(full_classname_dest, sizeof(full_classname_dest), "%s.%s", module_name, class_name);
}
assert(strncmp("control_msgs.action._single_joint_position.SingleJointPosition_Result", full_classname_dest, 69) == 0);
}
control_msgs__action__SingleJointPosition_Result * ros_message = _ros_message;
ros_message->structure_needs_at_least_one_member = 0;
return true;
}
ROSIDL_GENERATOR_C_EXPORT
PyObject * control_msgs__action__single_joint_position__result__convert_to_py(void * raw_ros_message)
{
/* NOTE(esteve): Call constructor of SingleJointPosition_Result */
PyObject * _pymessage = NULL;
{
PyObject * pymessage_module = PyImport_ImportModule("control_msgs.action._single_joint_position");
assert(pymessage_module);
PyObject * pymessage_class = PyObject_GetAttrString(pymessage_module, "SingleJointPosition_Result");
assert(pymessage_class);
Py_DECREF(pymessage_module);
_pymessage = PyObject_CallObject(pymessage_class, NULL);
Py_DECREF(pymessage_class);
if (!_pymessage) {
return NULL;
}
}
(void)raw_ros_message;
// ownership of _pymessage is transferred to the caller
return _pymessage;
}
#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION
// already included above
// #include <Python.h>
// already included above
// #include <stdbool.h>
// already included above
// #include "numpy/ndarrayobject.h"
// already included above
// #include "rosidl_runtime_c/visibility_control.h"
// already included above
// #include "control_msgs/action/detail/single_joint_position__struct.h"
// already included above
// #include "control_msgs/action/detail/single_joint_position__functions.h"
ROSIDL_GENERATOR_C_IMPORT
bool std_msgs__msg__header__convert_from_py(PyObject * _pymsg, void * _ros_message);
ROSIDL_GENERATOR_C_IMPORT
PyObject * std_msgs__msg__header__convert_to_py(void * raw_ros_message);
ROSIDL_GENERATOR_C_EXPORT
bool control_msgs__action__single_joint_position__feedback__convert_from_py(PyObject * _pymsg, void * _ros_message)
{
// check that the passed message is of the expected Python class
{
char full_classname_dest[72];
{
char * class_name = NULL;
char * module_name = NULL;
{
PyObject * class_attr = PyObject_GetAttrString(_pymsg, "__class__");
if (class_attr) {
PyObject * name_attr = PyObject_GetAttrString(class_attr, "__name__");
if (name_attr) {
class_name = (char *)PyUnicode_1BYTE_DATA(name_attr);
Py_DECREF(name_attr);
}
PyObject * module_attr = PyObject_GetAttrString(class_attr, "__module__");
if (module_attr) {
module_name = (char *)PyUnicode_1BYTE_DATA(module_attr);
Py_DECREF(module_attr);
}
Py_DECREF(class_attr);
}
}
if (!class_name || !module_name) {
return false;
}
snprintf(full_classname_dest, sizeof(full_classname_dest), "%s.%s", module_name, class_name);
}
assert(strncmp("control_msgs.action._single_joint_position.SingleJointPosition_Feedback", full_classname_dest, 71) == 0);
}
control_msgs__action__SingleJointPosition_Feedback * ros_message = _ros_message;
{ // header
PyObject * field = PyObject_GetAttrString(_pymsg, "header");
if (!field) {
return false;
}
if (!std_msgs__msg__header__convert_from_py(field, &ros_message->header)) {
Py_DECREF(field);
return false;
}
Py_DECREF(field);
}
{ // position
PyObject * field = PyObject_GetAttrString(_pymsg, "position");
if (!field) {
return false;
}
assert(PyFloat_Check(field));
ros_message->position = PyFloat_AS_DOUBLE(field);
Py_DECREF(field);
}
{ // velocity
PyObject * field = PyObject_GetAttrString(_pymsg, "velocity");
if (!field) {
return false;
}
assert(PyFloat_Check(field));
ros_message->velocity = PyFloat_AS_DOUBLE(field);
Py_DECREF(field);
}
{ // error
PyObject * field = PyObject_GetAttrString(_pymsg, "error");
if (!field) {
return false;
}
assert(PyFloat_Check(field));
ros_message->error = PyFloat_AS_DOUBLE(field);
Py_DECREF(field);
}
return true;
}
ROSIDL_GENERATOR_C_EXPORT
PyObject * control_msgs__action__single_joint_position__feedback__convert_to_py(void * raw_ros_message)
{
/* NOTE(esteve): Call constructor of SingleJointPosition_Feedback */
PyObject * _pymessage = NULL;
{
PyObject * pymessage_module = PyImport_ImportModule("control_msgs.action._single_joint_position");
assert(pymessage_module);
PyObject * pymessage_class = PyObject_GetAttrString(pymessage_module, "SingleJointPosition_Feedback");
assert(pymessage_class);
Py_DECREF(pymessage_module);
_pymessage = PyObject_CallObject(pymessage_class, NULL);
Py_DECREF(pymessage_class);
if (!_pymessage) {
return NULL;
}
}
control_msgs__action__SingleJointPosition_Feedback * ros_message = (control_msgs__action__SingleJointPosition_Feedback *)raw_ros_message;
{ // header
PyObject * field = NULL;
field = std_msgs__msg__header__convert_to_py(&ros_message->header);
if (!field) {
return NULL;
}
{
int rc = PyObject_SetAttrString(_pymessage, "header", field);
Py_DECREF(field);
if (rc) {
return NULL;
}
}
}
{ // position
PyObject * field = NULL;
field = PyFloat_FromDouble(ros_message->position);
{
int rc = PyObject_SetAttrString(_pymessage, "position", field);
Py_DECREF(field);
if (rc) {
return NULL;
}
}
}
{ // velocity
PyObject * field = NULL;
field = PyFloat_FromDouble(ros_message->velocity);
{
int rc = PyObject_SetAttrString(_pymessage, "velocity", field);
Py_DECREF(field);
if (rc) {
return NULL;
}
}
}
{ // error
PyObject * field = NULL;
field = PyFloat_FromDouble(ros_message->error);
{
int rc = PyObject_SetAttrString(_pymessage, "error", field);
Py_DECREF(field);
if (rc) {
return NULL;
}
}
}
// ownership of _pymessage is transferred to the caller
return _pymessage;
}
#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION
// already included above
// #include <Python.h>
// already included above
// #include <stdbool.h>
// already included above
// #include "numpy/ndarrayobject.h"
// already included above
// #include "rosidl_runtime_c/visibility_control.h"
// already included above
// #include "control_msgs/action/detail/single_joint_position__struct.h"
// already included above
// #include "control_msgs/action/detail/single_joint_position__functions.h"
ROSIDL_GENERATOR_C_IMPORT
bool unique_identifier_msgs__msg__uuid__convert_from_py(PyObject * _pymsg, void * _ros_message);
ROSIDL_GENERATOR_C_IMPORT
PyObject * unique_identifier_msgs__msg__uuid__convert_to_py(void * raw_ros_message);
bool control_msgs__action__single_joint_position__goal__convert_from_py(PyObject * _pymsg, void * _ros_message);
PyObject * control_msgs__action__single_joint_position__goal__convert_to_py(void * raw_ros_message);
ROSIDL_GENERATOR_C_EXPORT
bool control_msgs__action__single_joint_position__send_goal__request__convert_from_py(PyObject * _pymsg, void * _ros_message)
{
// check that the passed message is of the expected Python class
{
char full_classname_dest[80];
{
char * class_name = NULL;
char * module_name = NULL;
{
PyObject * class_attr = PyObject_GetAttrString(_pymsg, "__class__");
if (class_attr) {
PyObject * name_attr = PyObject_GetAttrString(class_attr, "__name__");
if (name_attr) {
class_name = (char *)PyUnicode_1BYTE_DATA(name_attr);
Py_DECREF(name_attr);
}
PyObject * module_attr = PyObject_GetAttrString(class_attr, "__module__");
if (module_attr) {
module_name = (char *)PyUnicode_1BYTE_DATA(module_attr);
Py_DECREF(module_attr);
}
Py_DECREF(class_attr);
}
}
if (!class_name || !module_name) {
return false;
}
snprintf(full_classname_dest, sizeof(full_classname_dest), "%s.%s", module_name, class_name);
}
assert(strncmp("control_msgs.action._single_joint_position.SingleJointPosition_SendGoal_Request", full_classname_dest, 79) == 0);
}
control_msgs__action__SingleJointPosition_SendGoal_Request * ros_message = _ros_message;
{ // goal_id
PyObject * field = PyObject_GetAttrString(_pymsg, "goal_id");
if (!field) {
return false;
}
if (!unique_identifier_msgs__msg__uuid__convert_from_py(field, &ros_message->goal_id)) {
Py_DECREF(field);
return false;
}
Py_DECREF(field);
}
{ // goal
PyObject * field = PyObject_GetAttrString(_pymsg, "goal");
if (!field) {
return false;
}
if (!control_msgs__action__single_joint_position__goal__convert_from_py(field, &ros_message->goal)) {
Py_DECREF(field);
return false;
}
Py_DECREF(field);
}
return true;
}
ROSIDL_GENERATOR_C_EXPORT
PyObject * control_msgs__action__single_joint_position__send_goal__request__convert_to_py(void * raw_ros_message)
{
/* NOTE(esteve): Call constructor of SingleJointPosition_SendGoal_Request */
PyObject * _pymessage = NULL;
{
PyObject * pymessage_module = PyImport_ImportModule("control_msgs.action._single_joint_position");
assert(pymessage_module);
PyObject * pymessage_class = PyObject_GetAttrString(pymessage_module, "SingleJointPosition_SendGoal_Request");
assert(pymessage_class);
Py_DECREF(pymessage_module);
_pymessage = PyObject_CallObject(pymessage_class, NULL);
Py_DECREF(pymessage_class);
if (!_pymessage) {
return NULL;
}
}
control_msgs__action__SingleJointPosition_SendGoal_Request * ros_message = (control_msgs__action__SingleJointPosition_SendGoal_Request *)raw_ros_message;
{ // goal_id
PyObject * field = NULL;
field = unique_identifier_msgs__msg__uuid__convert_to_py(&ros_message->goal_id);
if (!field) {
return NULL;
}
{
int rc = PyObject_SetAttrString(_pymessage, "goal_id", field);
Py_DECREF(field);
if (rc) {
return NULL;
}
}
}
{ // goal
PyObject * field = NULL;
field = control_msgs__action__single_joint_position__goal__convert_to_py(&ros_message->goal);
if (!field) {
return NULL;
}
{
int rc = PyObject_SetAttrString(_pymessage, "goal", field);
Py_DECREF(field);
if (rc) {
return NULL;
}
}
}
// ownership of _pymessage is transferred to the caller
return _pymessage;
}
#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION
// already included above
// #include <Python.h>
// already included above
// #include <stdbool.h>
// already included above
// #include "numpy/ndarrayobject.h"
// already included above
// #include "rosidl_runtime_c/visibility_control.h"
// already included above
// #include "control_msgs/action/detail/single_joint_position__struct.h"
// already included above
// #include "control_msgs/action/detail/single_joint_position__functions.h"
ROSIDL_GENERATOR_C_IMPORT
bool builtin_interfaces__msg__time__convert_from_py(PyObject * _pymsg, void * _ros_message);
ROSIDL_GENERATOR_C_IMPORT
PyObject * builtin_interfaces__msg__time__convert_to_py(void * raw_ros_message);
ROSIDL_GENERATOR_C_EXPORT
bool control_msgs__action__single_joint_position__send_goal__response__convert_from_py(PyObject * _pymsg, void * _ros_message)
{
// check that the passed message is of the expected Python class
{
char full_classname_dest[81];
{
char * class_name = NULL;
char * module_name = NULL;
{
PyObject * class_attr = PyObject_GetAttrString(_pymsg, "__class__");
if (class_attr) {
PyObject * name_attr = PyObject_GetAttrString(class_attr, "__name__");
if (name_attr) {
class_name = (char *)PyUnicode_1BYTE_DATA(name_attr);
Py_DECREF(name_attr);
}
PyObject * module_attr = PyObject_GetAttrString(class_attr, "__module__");
if (module_attr) {
module_name = (char *)PyUnicode_1BYTE_DATA(module_attr);
Py_DECREF(module_attr);
}
Py_DECREF(class_attr);
}
}
if (!class_name || !module_name) {
return false;
}
snprintf(full_classname_dest, sizeof(full_classname_dest), "%s.%s", module_name, class_name);
}
assert(strncmp("control_msgs.action._single_joint_position.SingleJointPosition_SendGoal_Response", full_classname_dest, 80) == 0);
}
control_msgs__action__SingleJointPosition_SendGoal_Response * ros_message = _ros_message;
{ // accepted
PyObject * field = PyObject_GetAttrString(_pymsg, "accepted");
if (!field) {
return false;
}
assert(PyBool_Check(field));
ros_message->accepted = (Py_True == field);
Py_DECREF(field);
}
{ // stamp
PyObject * field = PyObject_GetAttrString(_pymsg, "stamp");
if (!field) {
return false;
}
if (!builtin_interfaces__msg__time__convert_from_py(field, &ros_message->stamp)) {
Py_DECREF(field);
return false;
}
Py_DECREF(field);
}
return true;
}
ROSIDL_GENERATOR_C_EXPORT
PyObject * control_msgs__action__single_joint_position__send_goal__response__convert_to_py(void * raw_ros_message)
{
/* NOTE(esteve): Call constructor of SingleJointPosition_SendGoal_Response */
PyObject * _pymessage = NULL;
{
PyObject * pymessage_module = PyImport_ImportModule("control_msgs.action._single_joint_position");
assert(pymessage_module);
PyObject * pymessage_class = PyObject_GetAttrString(pymessage_module, "SingleJointPosition_SendGoal_Response");
assert(pymessage_class);
Py_DECREF(pymessage_module);
_pymessage = PyObject_CallObject(pymessage_class, NULL);
Py_DECREF(pymessage_class);
if (!_pymessage) {
return NULL;
}
}
control_msgs__action__SingleJointPosition_SendGoal_Response * ros_message = (control_msgs__action__SingleJointPosition_SendGoal_Response *)raw_ros_message;
{ // accepted
PyObject * field = NULL;
field = PyBool_FromLong(ros_message->accepted ? 1 : 0);
{
int rc = PyObject_SetAttrString(_pymessage, "accepted", field);
Py_DECREF(field);
if (rc) {
return NULL;
}
}
}
{ // stamp
PyObject * field = NULL;
field = builtin_interfaces__msg__time__convert_to_py(&ros_message->stamp);
if (!field) {
return NULL;
}
{
int rc = PyObject_SetAttrString(_pymessage, "stamp", field);
Py_DECREF(field);
if (rc) {
return NULL;
}
}
}
// ownership of _pymessage is transferred to the caller
return _pymessage;
}
#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION
// already included above
// #include <Python.h>
// already included above
// #include <stdbool.h>
// already included above
// #include "numpy/ndarrayobject.h"
// already included above
// #include "rosidl_runtime_c/visibility_control.h"
// already included above
// #include "control_msgs/action/detail/single_joint_position__struct.h"
// already included above
// #include "control_msgs/action/detail/single_joint_position__functions.h"
ROSIDL_GENERATOR_C_IMPORT
bool unique_identifier_msgs__msg__uuid__convert_from_py(PyObject * _pymsg, void * _ros_message);
ROSIDL_GENERATOR_C_IMPORT
PyObject * unique_identifier_msgs__msg__uuid__convert_to_py(void * raw_ros_message);
ROSIDL_GENERATOR_C_EXPORT
bool control_msgs__action__single_joint_position__get_result__request__convert_from_py(PyObject * _pymsg, void * _ros_message)
{
// check that the passed message is of the expected Python class
{
char full_classname_dest[81];
{
char * class_name = NULL;
char * module_name = NULL;
{
PyObject * class_attr = PyObject_GetAttrString(_pymsg, "__class__");
if (class_attr) {
PyObject * name_attr = PyObject_GetAttrString(class_attr, "__name__");
if (name_attr) {
class_name = (char *)PyUnicode_1BYTE_DATA(name_attr);
Py_DECREF(name_attr);
}
PyObject * module_attr = PyObject_GetAttrString(class_attr, "__module__");
if (module_attr) {
module_name = (char *)PyUnicode_1BYTE_DATA(module_attr);
Py_DECREF(module_attr);
}
Py_DECREF(class_attr);
}
}
if (!class_name || !module_name) {
return false;
}
snprintf(full_classname_dest, sizeof(full_classname_dest), "%s.%s", module_name, class_name);
}
assert(strncmp("control_msgs.action._single_joint_position.SingleJointPosition_GetResult_Request", full_classname_dest, 80) == 0);
}
control_msgs__action__SingleJointPosition_GetResult_Request * ros_message = _ros_message;
{ // goal_id
PyObject * field = PyObject_GetAttrString(_pymsg, "goal_id");
if (!field) {
return false;
}
if (!unique_identifier_msgs__msg__uuid__convert_from_py(field, &ros_message->goal_id)) {
Py_DECREF(field);
return false;
}
Py_DECREF(field);
}
return true;
}
ROSIDL_GENERATOR_C_EXPORT
PyObject * control_msgs__action__single_joint_position__get_result__request__convert_to_py(void * raw_ros_message)
{
/* NOTE(esteve): Call constructor of SingleJointPosition_GetResult_Request */
PyObject * _pymessage = NULL;
{
PyObject * pymessage_module = PyImport_ImportModule("control_msgs.action._single_joint_position");
assert(pymessage_module);
PyObject * pymessage_class = PyObject_GetAttrString(pymessage_module, "SingleJointPosition_GetResult_Request");
assert(pymessage_class);
Py_DECREF(pymessage_module);
_pymessage = PyObject_CallObject(pymessage_class, NULL);
Py_DECREF(pymessage_class);
if (!_pymessage) {
return NULL;
}
}
control_msgs__action__SingleJointPosition_GetResult_Request * ros_message = (control_msgs__action__SingleJointPosition_GetResult_Request *)raw_ros_message;
{ // goal_id
PyObject * field = NULL;
field = unique_identifier_msgs__msg__uuid__convert_to_py(&ros_message->goal_id);
if (!field) {
return NULL;
}
{
int rc = PyObject_SetAttrString(_pymessage, "goal_id", field);
Py_DECREF(field);
if (rc) {
return NULL;
}
}
}
// ownership of _pymessage is transferred to the caller
return _pymessage;
}
#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION
// already included above
// #include <Python.h>
// already included above
// #include <stdbool.h>
// already included above
// #include "numpy/ndarrayobject.h"
// already included above
// #include "rosidl_runtime_c/visibility_control.h"
// already included above
// #include "control_msgs/action/detail/single_joint_position__struct.h"
// already included above
// #include "control_msgs/action/detail/single_joint_position__functions.h"
bool control_msgs__action__single_joint_position__result__convert_from_py(PyObject * _pymsg, void * _ros_message);
PyObject * control_msgs__action__single_joint_position__result__convert_to_py(void * raw_ros_message);
ROSIDL_GENERATOR_C_EXPORT
bool control_msgs__action__single_joint_position__get_result__response__convert_from_py(PyObject * _pymsg, void * _ros_message)
{
// check that the passed message is of the expected Python class
{
char full_classname_dest[82];
{
char * class_name = NULL;
char * module_name = NULL;
{
PyObject * class_attr = PyObject_GetAttrString(_pymsg, "__class__");
if (class_attr) {
PyObject * name_attr = PyObject_GetAttrString(class_attr, "__name__");
if (name_attr) {
class_name = (char *)PyUnicode_1BYTE_DATA(name_attr);
Py_DECREF(name_attr);
}
PyObject * module_attr = PyObject_GetAttrString(class_attr, "__module__");
if (module_attr) {
module_name = (char *)PyUnicode_1BYTE_DATA(module_attr);
Py_DECREF(module_attr);
}
Py_DECREF(class_attr);
}
}
if (!class_name || !module_name) {
return false;
}
snprintf(full_classname_dest, sizeof(full_classname_dest), "%s.%s", module_name, class_name);
}
assert(strncmp("control_msgs.action._single_joint_position.SingleJointPosition_GetResult_Response", full_classname_dest, 81) == 0);
}
control_msgs__action__SingleJointPosition_GetResult_Response * ros_message = _ros_message;
{ // status
PyObject * field = PyObject_GetAttrString(_pymsg, "status");
if (!field) {
return false;
}
assert(PyLong_Check(field));
ros_message->status = (int8_t)PyLong_AsLong(field);
Py_DECREF(field);
}
{ // result
PyObject * field = PyObject_GetAttrString(_pymsg, "result");
if (!field) {
return false;
}
if (!control_msgs__action__single_joint_position__result__convert_from_py(field, &ros_message->result)) {
Py_DECREF(field);
return false;
}
Py_DECREF(field);
}
return true;
}
ROSIDL_GENERATOR_C_EXPORT
PyObject * control_msgs__action__single_joint_position__get_result__response__convert_to_py(void * raw_ros_message)
{
/* NOTE(esteve): Call constructor of SingleJointPosition_GetResult_Response */
PyObject * _pymessage = NULL;
{
PyObject * pymessage_module = PyImport_ImportModule("control_msgs.action._single_joint_position");
assert(pymessage_module);
PyObject * pymessage_class = PyObject_GetAttrString(pymessage_module, "SingleJointPosition_GetResult_Response");
assert(pymessage_class);
Py_DECREF(pymessage_module);
_pymessage = PyObject_CallObject(pymessage_class, NULL);
Py_DECREF(pymessage_class);
if (!_pymessage) {
return NULL;
}
}
control_msgs__action__SingleJointPosition_GetResult_Response * ros_message = (control_msgs__action__SingleJointPosition_GetResult_Response *)raw_ros_message;
{ // status
PyObject * field = NULL;
field = PyLong_FromLong(ros_message->status);
{
int rc = PyObject_SetAttrString(_pymessage, "status", field);
Py_DECREF(field);
if (rc) {
return NULL;
}
}
}
{ // result
PyObject * field = NULL;
field = control_msgs__action__single_joint_position__result__convert_to_py(&ros_message->result);
if (!field) {
return NULL;
}
{
int rc = PyObject_SetAttrString(_pymessage, "result", field);
Py_DECREF(field);
if (rc) {
return NULL;
}
}
}
// ownership of _pymessage is transferred to the caller
return _pymessage;
}
#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION
// already included above
// #include <Python.h>
// already included above
// #include <stdbool.h>
// already included above
// #include "numpy/ndarrayobject.h"
// already included above
// #include "rosidl_runtime_c/visibility_control.h"
// already included above
// #include "control_msgs/action/detail/single_joint_position__struct.h"
// already included above
// #include "control_msgs/action/detail/single_joint_position__functions.h"
ROSIDL_GENERATOR_C_IMPORT
bool unique_identifier_msgs__msg__uuid__convert_from_py(PyObject * _pymsg, void * _ros_message);
ROSIDL_GENERATOR_C_IMPORT
PyObject * unique_identifier_msgs__msg__uuid__convert_to_py(void * raw_ros_message);
bool control_msgs__action__single_joint_position__feedback__convert_from_py(PyObject * _pymsg, void * _ros_message);
PyObject * control_msgs__action__single_joint_position__feedback__convert_to_py(void * raw_ros_message);
ROSIDL_GENERATOR_C_EXPORT
bool control_msgs__action__single_joint_position__feedback_message__convert_from_py(PyObject * _pymsg, void * _ros_message)
{
// check that the passed message is of the expected Python class
{
char full_classname_dest[79];
{
char * class_name = NULL;
char * module_name = NULL;
{
PyObject * class_attr = PyObject_GetAttrString(_pymsg, "__class__");
if (class_attr) {
PyObject * name_attr = PyObject_GetAttrString(class_attr, "__name__");
if (name_attr) {
class_name = (char *)PyUnicode_1BYTE_DATA(name_attr);
Py_DECREF(name_attr);
}
PyObject * module_attr = PyObject_GetAttrString(class_attr, "__module__");
if (module_attr) {
module_name = (char *)PyUnicode_1BYTE_DATA(module_attr);
Py_DECREF(module_attr);
}
Py_DECREF(class_attr);
}
}
if (!class_name || !module_name) {
return false;
}
snprintf(full_classname_dest, sizeof(full_classname_dest), "%s.%s", module_name, class_name);
}
assert(strncmp("control_msgs.action._single_joint_position.SingleJointPosition_FeedbackMessage", full_classname_dest, 78) == 0);
}
control_msgs__action__SingleJointPosition_FeedbackMessage * ros_message = _ros_message;
{ // goal_id
PyObject * field = PyObject_GetAttrString(_pymsg, "goal_id");
if (!field) {
return false;
}
if (!unique_identifier_msgs__msg__uuid__convert_from_py(field, &ros_message->goal_id)) {
Py_DECREF(field);
return false;
}
Py_DECREF(field);
}
{ // feedback
PyObject * field = PyObject_GetAttrString(_pymsg, "feedback");
if (!field) {
return false;
}
if (!control_msgs__action__single_joint_position__feedback__convert_from_py(field, &ros_message->feedback)) {
Py_DECREF(field);
return false;
}
Py_DECREF(field);
}
return true;
}
ROSIDL_GENERATOR_C_EXPORT
PyObject * control_msgs__action__single_joint_position__feedback_message__convert_to_py(void * raw_ros_message)
{
/* NOTE(esteve): Call constructor of SingleJointPosition_FeedbackMessage */
PyObject * _pymessage = NULL;
{
PyObject * pymessage_module = PyImport_ImportModule("control_msgs.action._single_joint_position");
assert(pymessage_module);
PyObject * pymessage_class = PyObject_GetAttrString(pymessage_module, "SingleJointPosition_FeedbackMessage");
assert(pymessage_class);
Py_DECREF(pymessage_module);
_pymessage = PyObject_CallObject(pymessage_class, NULL);
Py_DECREF(pymessage_class);
if (!_pymessage) {
return NULL;
}
}
control_msgs__action__SingleJointPosition_FeedbackMessage * ros_message = (control_msgs__action__SingleJointPosition_FeedbackMessage *)raw_ros_message;
{ // goal_id
PyObject * field = NULL;
field = unique_identifier_msgs__msg__uuid__convert_to_py(&ros_message->goal_id);
if (!field) {
return NULL;
}
{
int rc = PyObject_SetAttrString(_pymessage, "goal_id", field);
Py_DECREF(field);
if (rc) {
return NULL;
}
}
}
{ // feedback
PyObject * field = NULL;
field = control_msgs__action__single_joint_position__feedback__convert_to_py(&ros_message->feedback);
if (!field) {
return NULL;
}
{
int rc = PyObject_SetAttrString(_pymessage, "feedback", field);
Py_DECREF(field);
if (rc) {
return NULL;
}
}
}
// ownership of _pymessage is transferred to the caller
return _pymessage;
}
| 33,535 | C | 32.536 | 159 | 0.648218 |
Toni-SM/semu.robotics.ros2_bridge/src/semu.robotics.ros2_bridge/semu/robotics/ros2_bridge/packages/control_msgs/msg/_joint_tolerance_s.c | // generated from rosidl_generator_py/resource/_idl_support.c.em
// with input from control_msgs:msg/JointTolerance.idl
// generated code does not contain a copyright notice
#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION
#include <Python.h>
#include <stdbool.h>
#ifndef _WIN32
# pragma GCC diagnostic push
# pragma GCC diagnostic ignored "-Wunused-function"
#endif
#include "numpy/ndarrayobject.h"
#ifndef _WIN32
# pragma GCC diagnostic pop
#endif
#include "rosidl_runtime_c/visibility_control.h"
#include "control_msgs/msg/detail/joint_tolerance__struct.h"
#include "control_msgs/msg/detail/joint_tolerance__functions.h"
#include "rosidl_runtime_c/string.h"
#include "rosidl_runtime_c/string_functions.h"
ROSIDL_GENERATOR_C_EXPORT
bool control_msgs__msg__joint_tolerance__convert_from_py(PyObject * _pymsg, void * _ros_message)
{
// check that the passed message is of the expected Python class
{
char full_classname_dest[49];
{
char * class_name = NULL;
char * module_name = NULL;
{
PyObject * class_attr = PyObject_GetAttrString(_pymsg, "__class__");
if (class_attr) {
PyObject * name_attr = PyObject_GetAttrString(class_attr, "__name__");
if (name_attr) {
class_name = (char *)PyUnicode_1BYTE_DATA(name_attr);
Py_DECREF(name_attr);
}
PyObject * module_attr = PyObject_GetAttrString(class_attr, "__module__");
if (module_attr) {
module_name = (char *)PyUnicode_1BYTE_DATA(module_attr);
Py_DECREF(module_attr);
}
Py_DECREF(class_attr);
}
}
if (!class_name || !module_name) {
return false;
}
snprintf(full_classname_dest, sizeof(full_classname_dest), "%s.%s", module_name, class_name);
}
assert(strncmp("control_msgs.msg._joint_tolerance.JointTolerance", full_classname_dest, 48) == 0);
}
control_msgs__msg__JointTolerance * ros_message = _ros_message;
{ // name
PyObject * field = PyObject_GetAttrString(_pymsg, "name");
if (!field) {
return false;
}
assert(PyUnicode_Check(field));
PyObject * encoded_field = PyUnicode_AsUTF8String(field);
if (!encoded_field) {
Py_DECREF(field);
return false;
}
rosidl_runtime_c__String__assign(&ros_message->name, PyBytes_AS_STRING(encoded_field));
Py_DECREF(encoded_field);
Py_DECREF(field);
}
{ // position
PyObject * field = PyObject_GetAttrString(_pymsg, "position");
if (!field) {
return false;
}
assert(PyFloat_Check(field));
ros_message->position = PyFloat_AS_DOUBLE(field);
Py_DECREF(field);
}
{ // velocity
PyObject * field = PyObject_GetAttrString(_pymsg, "velocity");
if (!field) {
return false;
}
assert(PyFloat_Check(field));
ros_message->velocity = PyFloat_AS_DOUBLE(field);
Py_DECREF(field);
}
{ // acceleration
PyObject * field = PyObject_GetAttrString(_pymsg, "acceleration");
if (!field) {
return false;
}
assert(PyFloat_Check(field));
ros_message->acceleration = PyFloat_AS_DOUBLE(field);
Py_DECREF(field);
}
return true;
}
ROSIDL_GENERATOR_C_EXPORT
PyObject * control_msgs__msg__joint_tolerance__convert_to_py(void * raw_ros_message)
{
/* NOTE(esteve): Call constructor of JointTolerance */
PyObject * _pymessage = NULL;
{
PyObject * pymessage_module = PyImport_ImportModule("control_msgs.msg._joint_tolerance");
assert(pymessage_module);
PyObject * pymessage_class = PyObject_GetAttrString(pymessage_module, "JointTolerance");
assert(pymessage_class);
Py_DECREF(pymessage_module);
_pymessage = PyObject_CallObject(pymessage_class, NULL);
Py_DECREF(pymessage_class);
if (!_pymessage) {
return NULL;
}
}
control_msgs__msg__JointTolerance * ros_message = (control_msgs__msg__JointTolerance *)raw_ros_message;
{ // name
PyObject * field = NULL;
field = PyUnicode_DecodeUTF8(
ros_message->name.data,
strlen(ros_message->name.data),
"strict");
if (!field) {
return NULL;
}
{
int rc = PyObject_SetAttrString(_pymessage, "name", field);
Py_DECREF(field);
if (rc) {
return NULL;
}
}
}
{ // position
PyObject * field = NULL;
field = PyFloat_FromDouble(ros_message->position);
{
int rc = PyObject_SetAttrString(_pymessage, "position", field);
Py_DECREF(field);
if (rc) {
return NULL;
}
}
}
{ // velocity
PyObject * field = NULL;
field = PyFloat_FromDouble(ros_message->velocity);
{
int rc = PyObject_SetAttrString(_pymessage, "velocity", field);
Py_DECREF(field);
if (rc) {
return NULL;
}
}
}
{ // acceleration
PyObject * field = NULL;
field = PyFloat_FromDouble(ros_message->acceleration);
{
int rc = PyObject_SetAttrString(_pymessage, "acceleration", field);
Py_DECREF(field);
if (rc) {
return NULL;
}
}
}
// ownership of _pymessage is transferred to the caller
return _pymessage;
}
| 5,128 | C | 28.477011 | 105 | 0.629485 |
Toni-SM/semu.robotics.ros2_bridge/src/semu.robotics.ros2_bridge/semu/robotics/ros2_bridge/packages/control_msgs/msg/_interface_value.py | # generated from rosidl_generator_py/resource/_idl.py.em
# with input from control_msgs:msg/InterfaceValue.idl
# generated code does not contain a copyright notice
# Import statements for member types
# Member 'values'
import array # noqa: E402, I100
import rosidl_parser.definition # noqa: E402, I100
class Metaclass_InterfaceValue(type):
"""Metaclass of message 'InterfaceValue'."""
_CREATE_ROS_MESSAGE = None
_CONVERT_FROM_PY = None
_CONVERT_TO_PY = None
_DESTROY_ROS_MESSAGE = None
_TYPE_SUPPORT = None
__constants = {
}
@classmethod
def __import_type_support__(cls):
try:
from rosidl_generator_py import import_type_support
module = import_type_support('control_msgs')
except ImportError:
import logging
import traceback
logger = logging.getLogger(
'control_msgs.msg.InterfaceValue')
logger.debug(
'Failed to import needed modules for type support:\n' +
traceback.format_exc())
else:
cls._CREATE_ROS_MESSAGE = module.create_ros_message_msg__msg__interface_value
cls._CONVERT_FROM_PY = module.convert_from_py_msg__msg__interface_value
cls._CONVERT_TO_PY = module.convert_to_py_msg__msg__interface_value
cls._TYPE_SUPPORT = module.type_support_msg__msg__interface_value
cls._DESTROY_ROS_MESSAGE = module.destroy_ros_message_msg__msg__interface_value
@classmethod
def __prepare__(cls, name, bases, **kwargs):
# list constant names here so that they appear in the help text of
# the message class under "Data and other attributes defined here:"
# as well as populate each message instance
return {
}
class InterfaceValue(metaclass=Metaclass_InterfaceValue):
"""Message class 'InterfaceValue'."""
__slots__ = [
'_interface_names',
'_values',
]
_fields_and_field_types = {
'interface_names': 'sequence<string>',
'values': 'sequence<double>',
}
SLOT_TYPES = (
rosidl_parser.definition.UnboundedSequence(rosidl_parser.definition.UnboundedString()), # noqa: E501
rosidl_parser.definition.UnboundedSequence(rosidl_parser.definition.BasicType('double')), # noqa: E501
)
def __init__(self, **kwargs):
assert all('_' + key in self.__slots__ for key in kwargs.keys()), \
'Invalid arguments passed to constructor: %s' % \
', '.join(sorted(k for k in kwargs.keys() if '_' + k not in self.__slots__))
self.interface_names = kwargs.get('interface_names', [])
self.values = array.array('d', kwargs.get('values', []))
def __repr__(self):
typename = self.__class__.__module__.split('.')
typename.pop()
typename.append(self.__class__.__name__)
args = []
for s, t in zip(self.__slots__, self.SLOT_TYPES):
field = getattr(self, s)
fieldstr = repr(field)
# We use Python array type for fields that can be directly stored
# in them, and "normal" sequences for everything else. If it is
# a type that we store in an array, strip off the 'array' portion.
if (
isinstance(t, rosidl_parser.definition.AbstractSequence) and
isinstance(t.value_type, rosidl_parser.definition.BasicType) and
t.value_type.typename in ['float', 'double', 'int8', 'uint8', 'int16', 'uint16', 'int32', 'uint32', 'int64', 'uint64']
):
if len(field) == 0:
fieldstr = '[]'
else:
assert fieldstr.startswith('array(')
prefix = "array('X', "
suffix = ')'
fieldstr = fieldstr[len(prefix):-len(suffix)]
args.append(s[1:] + '=' + fieldstr)
return '%s(%s)' % ('.'.join(typename), ', '.join(args))
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
if self.interface_names != other.interface_names:
return False
if self.values != other.values:
return False
return True
@classmethod
def get_fields_and_field_types(cls):
from copy import copy
return copy(cls._fields_and_field_types)
@property
def interface_names(self):
"""Message field 'interface_names'."""
return self._interface_names
@interface_names.setter
def interface_names(self, value):
if __debug__:
from collections.abc import Sequence
from collections.abc import Set
from collections import UserList
from collections import UserString
assert \
((isinstance(value, Sequence) or
isinstance(value, Set) or
isinstance(value, UserList)) and
not isinstance(value, str) and
not isinstance(value, UserString) and
all(isinstance(v, str) for v in value) and
True), \
"The 'interface_names' field must be a set or sequence and each value of type 'str'"
self._interface_names = value
@property
def values(self):
"""Message field 'values'."""
return self._values
@values.setter
def values(self, value):
if isinstance(value, array.array):
assert value.typecode == 'd', \
"The 'values' array.array() must have the type code of 'd'"
self._values = value
return
if __debug__:
from collections.abc import Sequence
from collections.abc import Set
from collections import UserList
from collections import UserString
assert \
((isinstance(value, Sequence) or
isinstance(value, Set) or
isinstance(value, UserList)) and
not isinstance(value, str) and
not isinstance(value, UserString) and
all(isinstance(v, float) for v in value) and
True), \
"The 'values' field must be a set or sequence and each value of type 'float'"
self._values = array.array('d', value)
| 6,387 | Python | 36.57647 | 134 | 0.571473 |
Toni-SM/semu.robotics.ros2_bridge/src/semu.robotics.ros2_bridge/semu/robotics/ros2_bridge/packages/control_msgs/msg/_joint_trajectory_controller_state.py | # generated from rosidl_generator_py/resource/_idl.py.em
# with input from control_msgs:msg/JointTrajectoryControllerState.idl
# generated code does not contain a copyright notice
# Import statements for member types
import rosidl_parser.definition # noqa: E402, I100
class Metaclass_JointTrajectoryControllerState(type):
"""Metaclass of message 'JointTrajectoryControllerState'."""
_CREATE_ROS_MESSAGE = None
_CONVERT_FROM_PY = None
_CONVERT_TO_PY = None
_DESTROY_ROS_MESSAGE = None
_TYPE_SUPPORT = None
__constants = {
}
@classmethod
def __import_type_support__(cls):
try:
from rosidl_generator_py import import_type_support
module = import_type_support('control_msgs')
except ImportError:
import logging
import traceback
logger = logging.getLogger(
'control_msgs.msg.JointTrajectoryControllerState')
logger.debug(
'Failed to import needed modules for type support:\n' +
traceback.format_exc())
else:
cls._CREATE_ROS_MESSAGE = module.create_ros_message_msg__msg__joint_trajectory_controller_state
cls._CONVERT_FROM_PY = module.convert_from_py_msg__msg__joint_trajectory_controller_state
cls._CONVERT_TO_PY = module.convert_to_py_msg__msg__joint_trajectory_controller_state
cls._TYPE_SUPPORT = module.type_support_msg__msg__joint_trajectory_controller_state
cls._DESTROY_ROS_MESSAGE = module.destroy_ros_message_msg__msg__joint_trajectory_controller_state
from std_msgs.msg import Header
if Header.__class__._TYPE_SUPPORT is None:
Header.__class__.__import_type_support__()
from trajectory_msgs.msg import JointTrajectoryPoint
if JointTrajectoryPoint.__class__._TYPE_SUPPORT is None:
JointTrajectoryPoint.__class__.__import_type_support__()
@classmethod
def __prepare__(cls, name, bases, **kwargs):
# list constant names here so that they appear in the help text of
# the message class under "Data and other attributes defined here:"
# as well as populate each message instance
return {
}
class JointTrajectoryControllerState(metaclass=Metaclass_JointTrajectoryControllerState):
"""Message class 'JointTrajectoryControllerState'."""
__slots__ = [
'_header',
'_joint_names',
'_desired',
'_actual',
'_error',
]
_fields_and_field_types = {
'header': 'std_msgs/Header',
'joint_names': 'sequence<string>',
'desired': 'trajectory_msgs/JointTrajectoryPoint',
'actual': 'trajectory_msgs/JointTrajectoryPoint',
'error': 'trajectory_msgs/JointTrajectoryPoint',
}
SLOT_TYPES = (
rosidl_parser.definition.NamespacedType(['std_msgs', 'msg'], 'Header'), # noqa: E501
rosidl_parser.definition.UnboundedSequence(rosidl_parser.definition.UnboundedString()), # noqa: E501
rosidl_parser.definition.NamespacedType(['trajectory_msgs', 'msg'], 'JointTrajectoryPoint'), # noqa: E501
rosidl_parser.definition.NamespacedType(['trajectory_msgs', 'msg'], 'JointTrajectoryPoint'), # noqa: E501
rosidl_parser.definition.NamespacedType(['trajectory_msgs', 'msg'], 'JointTrajectoryPoint'), # noqa: E501
)
def __init__(self, **kwargs):
assert all('_' + key in self.__slots__ for key in kwargs.keys()), \
'Invalid arguments passed to constructor: %s' % \
', '.join(sorted(k for k in kwargs.keys() if '_' + k not in self.__slots__))
from std_msgs.msg import Header
self.header = kwargs.get('header', Header())
self.joint_names = kwargs.get('joint_names', [])
from trajectory_msgs.msg import JointTrajectoryPoint
self.desired = kwargs.get('desired', JointTrajectoryPoint())
from trajectory_msgs.msg import JointTrajectoryPoint
self.actual = kwargs.get('actual', JointTrajectoryPoint())
from trajectory_msgs.msg import JointTrajectoryPoint
self.error = kwargs.get('error', JointTrajectoryPoint())
def __repr__(self):
typename = self.__class__.__module__.split('.')
typename.pop()
typename.append(self.__class__.__name__)
args = []
for s, t in zip(self.__slots__, self.SLOT_TYPES):
field = getattr(self, s)
fieldstr = repr(field)
# We use Python array type for fields that can be directly stored
# in them, and "normal" sequences for everything else. If it is
# a type that we store in an array, strip off the 'array' portion.
if (
isinstance(t, rosidl_parser.definition.AbstractSequence) and
isinstance(t.value_type, rosidl_parser.definition.BasicType) and
t.value_type.typename in ['float', 'double', 'int8', 'uint8', 'int16', 'uint16', 'int32', 'uint32', 'int64', 'uint64']
):
if len(field) == 0:
fieldstr = '[]'
else:
assert fieldstr.startswith('array(')
prefix = "array('X', "
suffix = ')'
fieldstr = fieldstr[len(prefix):-len(suffix)]
args.append(s[1:] + '=' + fieldstr)
return '%s(%s)' % ('.'.join(typename), ', '.join(args))
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
if self.header != other.header:
return False
if self.joint_names != other.joint_names:
return False
if self.desired != other.desired:
return False
if self.actual != other.actual:
return False
if self.error != other.error:
return False
return True
@classmethod
def get_fields_and_field_types(cls):
from copy import copy
return copy(cls._fields_and_field_types)
@property
def header(self):
"""Message field 'header'."""
return self._header
@header.setter
def header(self, value):
if __debug__:
from std_msgs.msg import Header
assert \
isinstance(value, Header), \
"The 'header' field must be a sub message of type 'Header'"
self._header = value
@property
def joint_names(self):
"""Message field 'joint_names'."""
return self._joint_names
@joint_names.setter
def joint_names(self, value):
if __debug__:
from collections.abc import Sequence
from collections.abc import Set
from collections import UserList
from collections import UserString
assert \
((isinstance(value, Sequence) or
isinstance(value, Set) or
isinstance(value, UserList)) and
not isinstance(value, str) and
not isinstance(value, UserString) and
all(isinstance(v, str) for v in value) and
True), \
"The 'joint_names' field must be a set or sequence and each value of type 'str'"
self._joint_names = value
@property
def desired(self):
"""Message field 'desired'."""
return self._desired
@desired.setter
def desired(self, value):
if __debug__:
from trajectory_msgs.msg import JointTrajectoryPoint
assert \
isinstance(value, JointTrajectoryPoint), \
"The 'desired' field must be a sub message of type 'JointTrajectoryPoint'"
self._desired = value
@property
def actual(self):
"""Message field 'actual'."""
return self._actual
@actual.setter
def actual(self, value):
if __debug__:
from trajectory_msgs.msg import JointTrajectoryPoint
assert \
isinstance(value, JointTrajectoryPoint), \
"The 'actual' field must be a sub message of type 'JointTrajectoryPoint'"
self._actual = value
@property
def error(self):
"""Message field 'error'."""
return self._error
@error.setter
def error(self, value):
if __debug__:
from trajectory_msgs.msg import JointTrajectoryPoint
assert \
isinstance(value, JointTrajectoryPoint), \
"The 'error' field must be a sub message of type 'JointTrajectoryPoint'"
self._error = value
| 8,648 | Python | 37.44 | 134 | 0.591351 |
Toni-SM/semu.robotics.ros2_bridge/src/semu.robotics.ros2_bridge/semu/robotics/ros2_bridge/packages/control_msgs/msg/_interface_value_s.c | // generated from rosidl_generator_py/resource/_idl_support.c.em
// with input from control_msgs:msg/InterfaceValue.idl
// generated code does not contain a copyright notice
#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION
#include <Python.h>
#include <stdbool.h>
#ifndef _WIN32
# pragma GCC diagnostic push
# pragma GCC diagnostic ignored "-Wunused-function"
#endif
#include "numpy/ndarrayobject.h"
#ifndef _WIN32
# pragma GCC diagnostic pop
#endif
#include "rosidl_runtime_c/visibility_control.h"
#include "control_msgs/msg/detail/interface_value__struct.h"
#include "control_msgs/msg/detail/interface_value__functions.h"
#include "rosidl_runtime_c/primitives_sequence.h"
#include "rosidl_runtime_c/primitives_sequence_functions.h"
#include "rosidl_runtime_c/string.h"
#include "rosidl_runtime_c/string_functions.h"
ROSIDL_GENERATOR_C_EXPORT
bool control_msgs__msg__interface_value__convert_from_py(PyObject * _pymsg, void * _ros_message)
{
// check that the passed message is of the expected Python class
{
char full_classname_dest[49];
{
char * class_name = NULL;
char * module_name = NULL;
{
PyObject * class_attr = PyObject_GetAttrString(_pymsg, "__class__");
if (class_attr) {
PyObject * name_attr = PyObject_GetAttrString(class_attr, "__name__");
if (name_attr) {
class_name = (char *)PyUnicode_1BYTE_DATA(name_attr);
Py_DECREF(name_attr);
}
PyObject * module_attr = PyObject_GetAttrString(class_attr, "__module__");
if (module_attr) {
module_name = (char *)PyUnicode_1BYTE_DATA(module_attr);
Py_DECREF(module_attr);
}
Py_DECREF(class_attr);
}
}
if (!class_name || !module_name) {
return false;
}
snprintf(full_classname_dest, sizeof(full_classname_dest), "%s.%s", module_name, class_name);
}
assert(strncmp("control_msgs.msg._interface_value.InterfaceValue", full_classname_dest, 48) == 0);
}
control_msgs__msg__InterfaceValue * ros_message = _ros_message;
{ // interface_names
PyObject * field = PyObject_GetAttrString(_pymsg, "interface_names");
if (!field) {
return false;
}
PyObject * seq_field = PySequence_Fast(field, "expected a sequence in 'interface_names'");
if (!seq_field) {
Py_DECREF(field);
return false;
}
Py_ssize_t size = PySequence_Size(field);
if (-1 == size) {
Py_DECREF(seq_field);
Py_DECREF(field);
return false;
}
if (!rosidl_runtime_c__String__Sequence__init(&(ros_message->interface_names), size)) {
PyErr_SetString(PyExc_RuntimeError, "unable to create String__Sequence ros_message");
Py_DECREF(seq_field);
Py_DECREF(field);
return false;
}
rosidl_runtime_c__String * dest = ros_message->interface_names.data;
for (Py_ssize_t i = 0; i < size; ++i) {
PyObject * item = PySequence_Fast_GET_ITEM(seq_field, i);
if (!item) {
Py_DECREF(seq_field);
Py_DECREF(field);
return false;
}
assert(PyUnicode_Check(item));
PyObject * encoded_item = PyUnicode_AsUTF8String(item);
if (!encoded_item) {
Py_DECREF(seq_field);
Py_DECREF(field);
return false;
}
rosidl_runtime_c__String__assign(&dest[i], PyBytes_AS_STRING(encoded_item));
Py_DECREF(encoded_item);
}
Py_DECREF(seq_field);
Py_DECREF(field);
}
{ // values
PyObject * field = PyObject_GetAttrString(_pymsg, "values");
if (!field) {
return false;
}
PyObject * seq_field = PySequence_Fast(field, "expected a sequence in 'values'");
if (!seq_field) {
Py_DECREF(field);
return false;
}
Py_ssize_t size = PySequence_Size(field);
if (-1 == size) {
Py_DECREF(seq_field);
Py_DECREF(field);
return false;
}
if (!rosidl_runtime_c__double__Sequence__init(&(ros_message->values), size)) {
PyErr_SetString(PyExc_RuntimeError, "unable to create double__Sequence ros_message");
Py_DECREF(seq_field);
Py_DECREF(field);
return false;
}
double * dest = ros_message->values.data;
for (Py_ssize_t i = 0; i < size; ++i) {
PyObject * item = PySequence_Fast_GET_ITEM(seq_field, i);
if (!item) {
Py_DECREF(seq_field);
Py_DECREF(field);
return false;
}
assert(PyFloat_Check(item));
double tmp = PyFloat_AS_DOUBLE(item);
memcpy(&dest[i], &tmp, sizeof(double));
}
Py_DECREF(seq_field);
Py_DECREF(field);
}
return true;
}
ROSIDL_GENERATOR_C_EXPORT
PyObject * control_msgs__msg__interface_value__convert_to_py(void * raw_ros_message)
{
/* NOTE(esteve): Call constructor of InterfaceValue */
PyObject * _pymessage = NULL;
{
PyObject * pymessage_module = PyImport_ImportModule("control_msgs.msg._interface_value");
assert(pymessage_module);
PyObject * pymessage_class = PyObject_GetAttrString(pymessage_module, "InterfaceValue");
assert(pymessage_class);
Py_DECREF(pymessage_module);
_pymessage = PyObject_CallObject(pymessage_class, NULL);
Py_DECREF(pymessage_class);
if (!_pymessage) {
return NULL;
}
}
control_msgs__msg__InterfaceValue * ros_message = (control_msgs__msg__InterfaceValue *)raw_ros_message;
{ // interface_names
PyObject * field = NULL;
size_t size = ros_message->interface_names.size;
rosidl_runtime_c__String * src = ros_message->interface_names.data;
field = PyList_New(size);
if (!field) {
return NULL;
}
for (size_t i = 0; i < size; ++i) {
PyObject * decoded_item = PyUnicode_DecodeUTF8(src[i].data, strlen(src[i].data), "strict");
if (!decoded_item) {
return NULL;
}
int rc = PyList_SetItem(field, i, decoded_item);
(void)rc;
assert(rc == 0);
}
assert(PySequence_Check(field));
{
int rc = PyObject_SetAttrString(_pymessage, "interface_names", field);
Py_DECREF(field);
if (rc) {
return NULL;
}
}
}
{ // values
PyObject * field = NULL;
field = PyObject_GetAttrString(_pymessage, "values");
if (!field) {
return NULL;
}
assert(field->ob_type != NULL);
assert(field->ob_type->tp_name != NULL);
assert(strcmp(field->ob_type->tp_name, "array.array") == 0);
// ensure that itemsize matches the sizeof of the ROS message field
PyObject * itemsize_attr = PyObject_GetAttrString(field, "itemsize");
assert(itemsize_attr != NULL);
size_t itemsize = PyLong_AsSize_t(itemsize_attr);
Py_DECREF(itemsize_attr);
if (itemsize != sizeof(double)) {
PyErr_SetString(PyExc_RuntimeError, "itemsize doesn't match expectation");
Py_DECREF(field);
return NULL;
}
// clear the array, poor approach to remove potential default values
Py_ssize_t length = PyObject_Length(field);
if (-1 == length) {
Py_DECREF(field);
return NULL;
}
if (length > 0) {
PyObject * pop = PyObject_GetAttrString(field, "pop");
assert(pop != NULL);
for (Py_ssize_t i = 0; i < length; ++i) {
PyObject * ret = PyObject_CallFunctionObjArgs(pop, NULL);
if (!ret) {
Py_DECREF(pop);
Py_DECREF(field);
return NULL;
}
Py_DECREF(ret);
}
Py_DECREF(pop);
}
if (ros_message->values.size > 0) {
// populating the array.array using the frombytes method
PyObject * frombytes = PyObject_GetAttrString(field, "frombytes");
assert(frombytes != NULL);
double * src = &(ros_message->values.data[0]);
PyObject * data = PyBytes_FromStringAndSize((const char *)src, ros_message->values.size * sizeof(double));
assert(data != NULL);
PyObject * ret = PyObject_CallFunctionObjArgs(frombytes, data, NULL);
Py_DECREF(data);
Py_DECREF(frombytes);
if (!ret) {
Py_DECREF(field);
return NULL;
}
Py_DECREF(ret);
}
Py_DECREF(field);
}
// ownership of _pymessage is transferred to the caller
return _pymessage;
}
| 8,143 | C | 31.97166 | 112 | 0.617954 |
Toni-SM/semu.robotics.ros2_bridge/src/semu.robotics.ros2_bridge/semu/robotics/ros2_bridge/packages/control_msgs/msg/_pid_state_s.c | // generated from rosidl_generator_py/resource/_idl_support.c.em
// with input from control_msgs:msg/PidState.idl
// generated code does not contain a copyright notice
#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION
#include <Python.h>
#include <stdbool.h>
#ifndef _WIN32
# pragma GCC diagnostic push
# pragma GCC diagnostic ignored "-Wunused-function"
#endif
#include "numpy/ndarrayobject.h"
#ifndef _WIN32
# pragma GCC diagnostic pop
#endif
#include "rosidl_runtime_c/visibility_control.h"
#include "control_msgs/msg/detail/pid_state__struct.h"
#include "control_msgs/msg/detail/pid_state__functions.h"
ROSIDL_GENERATOR_C_IMPORT
bool std_msgs__msg__header__convert_from_py(PyObject * _pymsg, void * _ros_message);
ROSIDL_GENERATOR_C_IMPORT
PyObject * std_msgs__msg__header__convert_to_py(void * raw_ros_message);
ROSIDL_GENERATOR_C_IMPORT
bool builtin_interfaces__msg__duration__convert_from_py(PyObject * _pymsg, void * _ros_message);
ROSIDL_GENERATOR_C_IMPORT
PyObject * builtin_interfaces__msg__duration__convert_to_py(void * raw_ros_message);
ROSIDL_GENERATOR_C_EXPORT
bool control_msgs__msg__pid_state__convert_from_py(PyObject * _pymsg, void * _ros_message)
{
// check that the passed message is of the expected Python class
{
char full_classname_dest[37];
{
char * class_name = NULL;
char * module_name = NULL;
{
PyObject * class_attr = PyObject_GetAttrString(_pymsg, "__class__");
if (class_attr) {
PyObject * name_attr = PyObject_GetAttrString(class_attr, "__name__");
if (name_attr) {
class_name = (char *)PyUnicode_1BYTE_DATA(name_attr);
Py_DECREF(name_attr);
}
PyObject * module_attr = PyObject_GetAttrString(class_attr, "__module__");
if (module_attr) {
module_name = (char *)PyUnicode_1BYTE_DATA(module_attr);
Py_DECREF(module_attr);
}
Py_DECREF(class_attr);
}
}
if (!class_name || !module_name) {
return false;
}
snprintf(full_classname_dest, sizeof(full_classname_dest), "%s.%s", module_name, class_name);
}
assert(strncmp("control_msgs.msg._pid_state.PidState", full_classname_dest, 36) == 0);
}
control_msgs__msg__PidState * ros_message = _ros_message;
{ // header
PyObject * field = PyObject_GetAttrString(_pymsg, "header");
if (!field) {
return false;
}
if (!std_msgs__msg__header__convert_from_py(field, &ros_message->header)) {
Py_DECREF(field);
return false;
}
Py_DECREF(field);
}
{ // timestep
PyObject * field = PyObject_GetAttrString(_pymsg, "timestep");
if (!field) {
return false;
}
if (!builtin_interfaces__msg__duration__convert_from_py(field, &ros_message->timestep)) {
Py_DECREF(field);
return false;
}
Py_DECREF(field);
}
{ // error
PyObject * field = PyObject_GetAttrString(_pymsg, "error");
if (!field) {
return false;
}
assert(PyFloat_Check(field));
ros_message->error = PyFloat_AS_DOUBLE(field);
Py_DECREF(field);
}
{ // error_dot
PyObject * field = PyObject_GetAttrString(_pymsg, "error_dot");
if (!field) {
return false;
}
assert(PyFloat_Check(field));
ros_message->error_dot = PyFloat_AS_DOUBLE(field);
Py_DECREF(field);
}
{ // p_error
PyObject * field = PyObject_GetAttrString(_pymsg, "p_error");
if (!field) {
return false;
}
assert(PyFloat_Check(field));
ros_message->p_error = PyFloat_AS_DOUBLE(field);
Py_DECREF(field);
}
{ // i_error
PyObject * field = PyObject_GetAttrString(_pymsg, "i_error");
if (!field) {
return false;
}
assert(PyFloat_Check(field));
ros_message->i_error = PyFloat_AS_DOUBLE(field);
Py_DECREF(field);
}
{ // d_error
PyObject * field = PyObject_GetAttrString(_pymsg, "d_error");
if (!field) {
return false;
}
assert(PyFloat_Check(field));
ros_message->d_error = PyFloat_AS_DOUBLE(field);
Py_DECREF(field);
}
{ // p_term
PyObject * field = PyObject_GetAttrString(_pymsg, "p_term");
if (!field) {
return false;
}
assert(PyFloat_Check(field));
ros_message->p_term = PyFloat_AS_DOUBLE(field);
Py_DECREF(field);
}
{ // i_term
PyObject * field = PyObject_GetAttrString(_pymsg, "i_term");
if (!field) {
return false;
}
assert(PyFloat_Check(field));
ros_message->i_term = PyFloat_AS_DOUBLE(field);
Py_DECREF(field);
}
{ // d_term
PyObject * field = PyObject_GetAttrString(_pymsg, "d_term");
if (!field) {
return false;
}
assert(PyFloat_Check(field));
ros_message->d_term = PyFloat_AS_DOUBLE(field);
Py_DECREF(field);
}
{ // i_max
PyObject * field = PyObject_GetAttrString(_pymsg, "i_max");
if (!field) {
return false;
}
assert(PyFloat_Check(field));
ros_message->i_max = PyFloat_AS_DOUBLE(field);
Py_DECREF(field);
}
{ // i_min
PyObject * field = PyObject_GetAttrString(_pymsg, "i_min");
if (!field) {
return false;
}
assert(PyFloat_Check(field));
ros_message->i_min = PyFloat_AS_DOUBLE(field);
Py_DECREF(field);
}
{ // output
PyObject * field = PyObject_GetAttrString(_pymsg, "output");
if (!field) {
return false;
}
assert(PyFloat_Check(field));
ros_message->output = PyFloat_AS_DOUBLE(field);
Py_DECREF(field);
}
return true;
}
ROSIDL_GENERATOR_C_EXPORT
PyObject * control_msgs__msg__pid_state__convert_to_py(void * raw_ros_message)
{
/* NOTE(esteve): Call constructor of PidState */
PyObject * _pymessage = NULL;
{
PyObject * pymessage_module = PyImport_ImportModule("control_msgs.msg._pid_state");
assert(pymessage_module);
PyObject * pymessage_class = PyObject_GetAttrString(pymessage_module, "PidState");
assert(pymessage_class);
Py_DECREF(pymessage_module);
_pymessage = PyObject_CallObject(pymessage_class, NULL);
Py_DECREF(pymessage_class);
if (!_pymessage) {
return NULL;
}
}
control_msgs__msg__PidState * ros_message = (control_msgs__msg__PidState *)raw_ros_message;
{ // header
PyObject * field = NULL;
field = std_msgs__msg__header__convert_to_py(&ros_message->header);
if (!field) {
return NULL;
}
{
int rc = PyObject_SetAttrString(_pymessage, "header", field);
Py_DECREF(field);
if (rc) {
return NULL;
}
}
}
{ // timestep
PyObject * field = NULL;
field = builtin_interfaces__msg__duration__convert_to_py(&ros_message->timestep);
if (!field) {
return NULL;
}
{
int rc = PyObject_SetAttrString(_pymessage, "timestep", field);
Py_DECREF(field);
if (rc) {
return NULL;
}
}
}
{ // error
PyObject * field = NULL;
field = PyFloat_FromDouble(ros_message->error);
{
int rc = PyObject_SetAttrString(_pymessage, "error", field);
Py_DECREF(field);
if (rc) {
return NULL;
}
}
}
{ // error_dot
PyObject * field = NULL;
field = PyFloat_FromDouble(ros_message->error_dot);
{
int rc = PyObject_SetAttrString(_pymessage, "error_dot", field);
Py_DECREF(field);
if (rc) {
return NULL;
}
}
}
{ // p_error
PyObject * field = NULL;
field = PyFloat_FromDouble(ros_message->p_error);
{
int rc = PyObject_SetAttrString(_pymessage, "p_error", field);
Py_DECREF(field);
if (rc) {
return NULL;
}
}
}
{ // i_error
PyObject * field = NULL;
field = PyFloat_FromDouble(ros_message->i_error);
{
int rc = PyObject_SetAttrString(_pymessage, "i_error", field);
Py_DECREF(field);
if (rc) {
return NULL;
}
}
}
{ // d_error
PyObject * field = NULL;
field = PyFloat_FromDouble(ros_message->d_error);
{
int rc = PyObject_SetAttrString(_pymessage, "d_error", field);
Py_DECREF(field);
if (rc) {
return NULL;
}
}
}
{ // p_term
PyObject * field = NULL;
field = PyFloat_FromDouble(ros_message->p_term);
{
int rc = PyObject_SetAttrString(_pymessage, "p_term", field);
Py_DECREF(field);
if (rc) {
return NULL;
}
}
}
{ // i_term
PyObject * field = NULL;
field = PyFloat_FromDouble(ros_message->i_term);
{
int rc = PyObject_SetAttrString(_pymessage, "i_term", field);
Py_DECREF(field);
if (rc) {
return NULL;
}
}
}
{ // d_term
PyObject * field = NULL;
field = PyFloat_FromDouble(ros_message->d_term);
{
int rc = PyObject_SetAttrString(_pymessage, "d_term", field);
Py_DECREF(field);
if (rc) {
return NULL;
}
}
}
{ // i_max
PyObject * field = NULL;
field = PyFloat_FromDouble(ros_message->i_max);
{
int rc = PyObject_SetAttrString(_pymessage, "i_max", field);
Py_DECREF(field);
if (rc) {
return NULL;
}
}
}
{ // i_min
PyObject * field = NULL;
field = PyFloat_FromDouble(ros_message->i_min);
{
int rc = PyObject_SetAttrString(_pymessage, "i_min", field);
Py_DECREF(field);
if (rc) {
return NULL;
}
}
}
{ // output
PyObject * field = NULL;
field = PyFloat_FromDouble(ros_message->output);
{
int rc = PyObject_SetAttrString(_pymessage, "output", field);
Py_DECREF(field);
if (rc) {
return NULL;
}
}
}
// ownership of _pymessage is transferred to the caller
return _pymessage;
}
| 9,678 | C | 26.112045 | 99 | 0.593511 |
Toni-SM/semu.robotics.ros2_bridge/src/semu.robotics.ros2_bridge/semu/robotics/ros2_bridge/packages/control_msgs/msg/_joint_tolerance.py | # generated from rosidl_generator_py/resource/_idl.py.em
# with input from control_msgs:msg/JointTolerance.idl
# generated code does not contain a copyright notice
# Import statements for member types
import rosidl_parser.definition # noqa: E402, I100
class Metaclass_JointTolerance(type):
"""Metaclass of message 'JointTolerance'."""
_CREATE_ROS_MESSAGE = None
_CONVERT_FROM_PY = None
_CONVERT_TO_PY = None
_DESTROY_ROS_MESSAGE = None
_TYPE_SUPPORT = None
__constants = {
}
@classmethod
def __import_type_support__(cls):
try:
from rosidl_generator_py import import_type_support
module = import_type_support('control_msgs')
except ImportError:
import logging
import traceback
logger = logging.getLogger(
'control_msgs.msg.JointTolerance')
logger.debug(
'Failed to import needed modules for type support:\n' +
traceback.format_exc())
else:
cls._CREATE_ROS_MESSAGE = module.create_ros_message_msg__msg__joint_tolerance
cls._CONVERT_FROM_PY = module.convert_from_py_msg__msg__joint_tolerance
cls._CONVERT_TO_PY = module.convert_to_py_msg__msg__joint_tolerance
cls._TYPE_SUPPORT = module.type_support_msg__msg__joint_tolerance
cls._DESTROY_ROS_MESSAGE = module.destroy_ros_message_msg__msg__joint_tolerance
@classmethod
def __prepare__(cls, name, bases, **kwargs):
# list constant names here so that they appear in the help text of
# the message class under "Data and other attributes defined here:"
# as well as populate each message instance
return {
}
class JointTolerance(metaclass=Metaclass_JointTolerance):
"""Message class 'JointTolerance'."""
__slots__ = [
'_name',
'_position',
'_velocity',
'_acceleration',
]
_fields_and_field_types = {
'name': 'string',
'position': 'double',
'velocity': 'double',
'acceleration': 'double',
}
SLOT_TYPES = (
rosidl_parser.definition.UnboundedString(), # noqa: E501
rosidl_parser.definition.BasicType('double'), # noqa: E501
rosidl_parser.definition.BasicType('double'), # noqa: E501
rosidl_parser.definition.BasicType('double'), # noqa: E501
)
def __init__(self, **kwargs):
assert all('_' + key in self.__slots__ for key in kwargs.keys()), \
'Invalid arguments passed to constructor: %s' % \
', '.join(sorted(k for k in kwargs.keys() if '_' + k not in self.__slots__))
self.name = kwargs.get('name', str())
self.position = kwargs.get('position', float())
self.velocity = kwargs.get('velocity', float())
self.acceleration = kwargs.get('acceleration', float())
def __repr__(self):
typename = self.__class__.__module__.split('.')
typename.pop()
typename.append(self.__class__.__name__)
args = []
for s, t in zip(self.__slots__, self.SLOT_TYPES):
field = getattr(self, s)
fieldstr = repr(field)
# We use Python array type for fields that can be directly stored
# in them, and "normal" sequences for everything else. If it is
# a type that we store in an array, strip off the 'array' portion.
if (
isinstance(t, rosidl_parser.definition.AbstractSequence) and
isinstance(t.value_type, rosidl_parser.definition.BasicType) and
t.value_type.typename in ['float', 'double', 'int8', 'uint8', 'int16', 'uint16', 'int32', 'uint32', 'int64', 'uint64']
):
if len(field) == 0:
fieldstr = '[]'
else:
assert fieldstr.startswith('array(')
prefix = "array('X', "
suffix = ')'
fieldstr = fieldstr[len(prefix):-len(suffix)]
args.append(s[1:] + '=' + fieldstr)
return '%s(%s)' % ('.'.join(typename), ', '.join(args))
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
if self.name != other.name:
return False
if self.position != other.position:
return False
if self.velocity != other.velocity:
return False
if self.acceleration != other.acceleration:
return False
return True
@classmethod
def get_fields_and_field_types(cls):
from copy import copy
return copy(cls._fields_and_field_types)
@property
def name(self):
"""Message field 'name'."""
return self._name
@name.setter
def name(self, value):
if __debug__:
assert \
isinstance(value, str), \
"The 'name' field must be of type 'str'"
self._name = value
@property
def position(self):
"""Message field 'position'."""
return self._position
@position.setter
def position(self, value):
if __debug__:
assert \
isinstance(value, float), \
"The 'position' field must be of type 'float'"
self._position = value
@property
def velocity(self):
"""Message field 'velocity'."""
return self._velocity
@velocity.setter
def velocity(self, value):
if __debug__:
assert \
isinstance(value, float), \
"The 'velocity' field must be of type 'float'"
self._velocity = value
@property
def acceleration(self):
"""Message field 'acceleration'."""
return self._acceleration
@acceleration.setter
def acceleration(self, value):
if __debug__:
assert \
isinstance(value, float), \
"The 'acceleration' field must be of type 'float'"
self._acceleration = value
| 6,075 | Python | 32.755555 | 134 | 0.560329 |
Toni-SM/semu.robotics.ros2_bridge/src/semu.robotics.ros2_bridge/semu/robotics/ros2_bridge/packages/control_msgs/msg/_dynamic_joint_state_s.c | // generated from rosidl_generator_py/resource/_idl_support.c.em
// with input from control_msgs:msg/DynamicJointState.idl
// generated code does not contain a copyright notice
#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION
#include <Python.h>
#include <stdbool.h>
#ifndef _WIN32
# pragma GCC diagnostic push
# pragma GCC diagnostic ignored "-Wunused-function"
#endif
#include "numpy/ndarrayobject.h"
#ifndef _WIN32
# pragma GCC diagnostic pop
#endif
#include "rosidl_runtime_c/visibility_control.h"
#include "control_msgs/msg/detail/dynamic_joint_state__struct.h"
#include "control_msgs/msg/detail/dynamic_joint_state__functions.h"
#include "rosidl_runtime_c/primitives_sequence.h"
#include "rosidl_runtime_c/primitives_sequence_functions.h"
#include "rosidl_runtime_c/string.h"
#include "rosidl_runtime_c/string_functions.h"
// Nested array functions includes
#include "control_msgs/msg/detail/interface_value__functions.h"
// end nested array functions include
ROSIDL_GENERATOR_C_IMPORT
bool std_msgs__msg__header__convert_from_py(PyObject * _pymsg, void * _ros_message);
ROSIDL_GENERATOR_C_IMPORT
PyObject * std_msgs__msg__header__convert_to_py(void * raw_ros_message);
bool control_msgs__msg__interface_value__convert_from_py(PyObject * _pymsg, void * _ros_message);
PyObject * control_msgs__msg__interface_value__convert_to_py(void * raw_ros_message);
ROSIDL_GENERATOR_C_EXPORT
bool control_msgs__msg__dynamic_joint_state__convert_from_py(PyObject * _pymsg, void * _ros_message)
{
// check that the passed message is of the expected Python class
{
char full_classname_dest[56];
{
char * class_name = NULL;
char * module_name = NULL;
{
PyObject * class_attr = PyObject_GetAttrString(_pymsg, "__class__");
if (class_attr) {
PyObject * name_attr = PyObject_GetAttrString(class_attr, "__name__");
if (name_attr) {
class_name = (char *)PyUnicode_1BYTE_DATA(name_attr);
Py_DECREF(name_attr);
}
PyObject * module_attr = PyObject_GetAttrString(class_attr, "__module__");
if (module_attr) {
module_name = (char *)PyUnicode_1BYTE_DATA(module_attr);
Py_DECREF(module_attr);
}
Py_DECREF(class_attr);
}
}
if (!class_name || !module_name) {
return false;
}
snprintf(full_classname_dest, sizeof(full_classname_dest), "%s.%s", module_name, class_name);
}
assert(strncmp("control_msgs.msg._dynamic_joint_state.DynamicJointState", full_classname_dest, 55) == 0);
}
control_msgs__msg__DynamicJointState * ros_message = _ros_message;
{ // header
PyObject * field = PyObject_GetAttrString(_pymsg, "header");
if (!field) {
return false;
}
if (!std_msgs__msg__header__convert_from_py(field, &ros_message->header)) {
Py_DECREF(field);
return false;
}
Py_DECREF(field);
}
{ // joint_names
PyObject * field = PyObject_GetAttrString(_pymsg, "joint_names");
if (!field) {
return false;
}
PyObject * seq_field = PySequence_Fast(field, "expected a sequence in 'joint_names'");
if (!seq_field) {
Py_DECREF(field);
return false;
}
Py_ssize_t size = PySequence_Size(field);
if (-1 == size) {
Py_DECREF(seq_field);
Py_DECREF(field);
return false;
}
if (!rosidl_runtime_c__String__Sequence__init(&(ros_message->joint_names), size)) {
PyErr_SetString(PyExc_RuntimeError, "unable to create String__Sequence ros_message");
Py_DECREF(seq_field);
Py_DECREF(field);
return false;
}
rosidl_runtime_c__String * dest = ros_message->joint_names.data;
for (Py_ssize_t i = 0; i < size; ++i) {
PyObject * item = PySequence_Fast_GET_ITEM(seq_field, i);
if (!item) {
Py_DECREF(seq_field);
Py_DECREF(field);
return false;
}
assert(PyUnicode_Check(item));
PyObject * encoded_item = PyUnicode_AsUTF8String(item);
if (!encoded_item) {
Py_DECREF(seq_field);
Py_DECREF(field);
return false;
}
rosidl_runtime_c__String__assign(&dest[i], PyBytes_AS_STRING(encoded_item));
Py_DECREF(encoded_item);
}
Py_DECREF(seq_field);
Py_DECREF(field);
}
{ // interface_values
PyObject * field = PyObject_GetAttrString(_pymsg, "interface_values");
if (!field) {
return false;
}
PyObject * seq_field = PySequence_Fast(field, "expected a sequence in 'interface_values'");
if (!seq_field) {
Py_DECREF(field);
return false;
}
Py_ssize_t size = PySequence_Size(field);
if (-1 == size) {
Py_DECREF(seq_field);
Py_DECREF(field);
return false;
}
if (!control_msgs__msg__InterfaceValue__Sequence__init(&(ros_message->interface_values), size)) {
PyErr_SetString(PyExc_RuntimeError, "unable to create control_msgs__msg__InterfaceValue__Sequence ros_message");
Py_DECREF(seq_field);
Py_DECREF(field);
return false;
}
control_msgs__msg__InterfaceValue * dest = ros_message->interface_values.data;
for (Py_ssize_t i = 0; i < size; ++i) {
if (!control_msgs__msg__interface_value__convert_from_py(PySequence_Fast_GET_ITEM(seq_field, i), &dest[i])) {
Py_DECREF(seq_field);
Py_DECREF(field);
return false;
}
}
Py_DECREF(seq_field);
Py_DECREF(field);
}
return true;
}
ROSIDL_GENERATOR_C_EXPORT
PyObject * control_msgs__msg__dynamic_joint_state__convert_to_py(void * raw_ros_message)
{
/* NOTE(esteve): Call constructor of DynamicJointState */
PyObject * _pymessage = NULL;
{
PyObject * pymessage_module = PyImport_ImportModule("control_msgs.msg._dynamic_joint_state");
assert(pymessage_module);
PyObject * pymessage_class = PyObject_GetAttrString(pymessage_module, "DynamicJointState");
assert(pymessage_class);
Py_DECREF(pymessage_module);
_pymessage = PyObject_CallObject(pymessage_class, NULL);
Py_DECREF(pymessage_class);
if (!_pymessage) {
return NULL;
}
}
control_msgs__msg__DynamicJointState * ros_message = (control_msgs__msg__DynamicJointState *)raw_ros_message;
{ // header
PyObject * field = NULL;
field = std_msgs__msg__header__convert_to_py(&ros_message->header);
if (!field) {
return NULL;
}
{
int rc = PyObject_SetAttrString(_pymessage, "header", field);
Py_DECREF(field);
if (rc) {
return NULL;
}
}
}
{ // joint_names
PyObject * field = NULL;
size_t size = ros_message->joint_names.size;
rosidl_runtime_c__String * src = ros_message->joint_names.data;
field = PyList_New(size);
if (!field) {
return NULL;
}
for (size_t i = 0; i < size; ++i) {
PyObject * decoded_item = PyUnicode_DecodeUTF8(src[i].data, strlen(src[i].data), "strict");
if (!decoded_item) {
return NULL;
}
int rc = PyList_SetItem(field, i, decoded_item);
(void)rc;
assert(rc == 0);
}
assert(PySequence_Check(field));
{
int rc = PyObject_SetAttrString(_pymessage, "joint_names", field);
Py_DECREF(field);
if (rc) {
return NULL;
}
}
}
{ // interface_values
PyObject * field = NULL;
size_t size = ros_message->interface_values.size;
field = PyList_New(size);
if (!field) {
return NULL;
}
control_msgs__msg__InterfaceValue * item;
for (size_t i = 0; i < size; ++i) {
item = &(ros_message->interface_values.data[i]);
PyObject * pyitem = control_msgs__msg__interface_value__convert_to_py(item);
if (!pyitem) {
Py_DECREF(field);
return NULL;
}
int rc = PyList_SetItem(field, i, pyitem);
(void)rc;
assert(rc == 0);
}
assert(PySequence_Check(field));
{
int rc = PyObject_SetAttrString(_pymessage, "interface_values", field);
Py_DECREF(field);
if (rc) {
return NULL;
}
}
}
// ownership of _pymessage is transferred to the caller
return _pymessage;
}
| 8,105 | C | 31.685484 | 118 | 0.624553 |
Toni-SM/semu.robotics.ros2_bridge/src/semu.robotics.ros2_bridge/semu/robotics/ros2_bridge/packages/control_msgs/msg/_joint_controller_state_s.c | // generated from rosidl_generator_py/resource/_idl_support.c.em
// with input from control_msgs:msg/JointControllerState.idl
// generated code does not contain a copyright notice
#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION
#include <Python.h>
#include <stdbool.h>
#ifndef _WIN32
# pragma GCC diagnostic push
# pragma GCC diagnostic ignored "-Wunused-function"
#endif
#include "numpy/ndarrayobject.h"
#ifndef _WIN32
# pragma GCC diagnostic pop
#endif
#include "rosidl_runtime_c/visibility_control.h"
#include "control_msgs/msg/detail/joint_controller_state__struct.h"
#include "control_msgs/msg/detail/joint_controller_state__functions.h"
ROSIDL_GENERATOR_C_IMPORT
bool std_msgs__msg__header__convert_from_py(PyObject * _pymsg, void * _ros_message);
ROSIDL_GENERATOR_C_IMPORT
PyObject * std_msgs__msg__header__convert_to_py(void * raw_ros_message);
ROSIDL_GENERATOR_C_EXPORT
bool control_msgs__msg__joint_controller_state__convert_from_py(PyObject * _pymsg, void * _ros_message)
{
// check that the passed message is of the expected Python class
{
char full_classname_dest[62];
{
char * class_name = NULL;
char * module_name = NULL;
{
PyObject * class_attr = PyObject_GetAttrString(_pymsg, "__class__");
if (class_attr) {
PyObject * name_attr = PyObject_GetAttrString(class_attr, "__name__");
if (name_attr) {
class_name = (char *)PyUnicode_1BYTE_DATA(name_attr);
Py_DECREF(name_attr);
}
PyObject * module_attr = PyObject_GetAttrString(class_attr, "__module__");
if (module_attr) {
module_name = (char *)PyUnicode_1BYTE_DATA(module_attr);
Py_DECREF(module_attr);
}
Py_DECREF(class_attr);
}
}
if (!class_name || !module_name) {
return false;
}
snprintf(full_classname_dest, sizeof(full_classname_dest), "%s.%s", module_name, class_name);
}
assert(strncmp("control_msgs.msg._joint_controller_state.JointControllerState", full_classname_dest, 61) == 0);
}
control_msgs__msg__JointControllerState * ros_message = _ros_message;
{ // header
PyObject * field = PyObject_GetAttrString(_pymsg, "header");
if (!field) {
return false;
}
if (!std_msgs__msg__header__convert_from_py(field, &ros_message->header)) {
Py_DECREF(field);
return false;
}
Py_DECREF(field);
}
{ // set_point
PyObject * field = PyObject_GetAttrString(_pymsg, "set_point");
if (!field) {
return false;
}
assert(PyFloat_Check(field));
ros_message->set_point = PyFloat_AS_DOUBLE(field);
Py_DECREF(field);
}
{ // process_value
PyObject * field = PyObject_GetAttrString(_pymsg, "process_value");
if (!field) {
return false;
}
assert(PyFloat_Check(field));
ros_message->process_value = PyFloat_AS_DOUBLE(field);
Py_DECREF(field);
}
{ // process_value_dot
PyObject * field = PyObject_GetAttrString(_pymsg, "process_value_dot");
if (!field) {
return false;
}
assert(PyFloat_Check(field));
ros_message->process_value_dot = PyFloat_AS_DOUBLE(field);
Py_DECREF(field);
}
{ // error
PyObject * field = PyObject_GetAttrString(_pymsg, "error");
if (!field) {
return false;
}
assert(PyFloat_Check(field));
ros_message->error = PyFloat_AS_DOUBLE(field);
Py_DECREF(field);
}
{ // time_step
PyObject * field = PyObject_GetAttrString(_pymsg, "time_step");
if (!field) {
return false;
}
assert(PyFloat_Check(field));
ros_message->time_step = PyFloat_AS_DOUBLE(field);
Py_DECREF(field);
}
{ // command
PyObject * field = PyObject_GetAttrString(_pymsg, "command");
if (!field) {
return false;
}
assert(PyFloat_Check(field));
ros_message->command = PyFloat_AS_DOUBLE(field);
Py_DECREF(field);
}
{ // p
PyObject * field = PyObject_GetAttrString(_pymsg, "p");
if (!field) {
return false;
}
assert(PyFloat_Check(field));
ros_message->p = PyFloat_AS_DOUBLE(field);
Py_DECREF(field);
}
{ // i
PyObject * field = PyObject_GetAttrString(_pymsg, "i");
if (!field) {
return false;
}
assert(PyFloat_Check(field));
ros_message->i = PyFloat_AS_DOUBLE(field);
Py_DECREF(field);
}
{ // d
PyObject * field = PyObject_GetAttrString(_pymsg, "d");
if (!field) {
return false;
}
assert(PyFloat_Check(field));
ros_message->d = PyFloat_AS_DOUBLE(field);
Py_DECREF(field);
}
{ // i_clamp
PyObject * field = PyObject_GetAttrString(_pymsg, "i_clamp");
if (!field) {
return false;
}
assert(PyFloat_Check(field));
ros_message->i_clamp = PyFloat_AS_DOUBLE(field);
Py_DECREF(field);
}
{ // antiwindup
PyObject * field = PyObject_GetAttrString(_pymsg, "antiwindup");
if (!field) {
return false;
}
assert(PyBool_Check(field));
ros_message->antiwindup = (Py_True == field);
Py_DECREF(field);
}
return true;
}
ROSIDL_GENERATOR_C_EXPORT
PyObject * control_msgs__msg__joint_controller_state__convert_to_py(void * raw_ros_message)
{
/* NOTE(esteve): Call constructor of JointControllerState */
PyObject * _pymessage = NULL;
{
PyObject * pymessage_module = PyImport_ImportModule("control_msgs.msg._joint_controller_state");
assert(pymessage_module);
PyObject * pymessage_class = PyObject_GetAttrString(pymessage_module, "JointControllerState");
assert(pymessage_class);
Py_DECREF(pymessage_module);
_pymessage = PyObject_CallObject(pymessage_class, NULL);
Py_DECREF(pymessage_class);
if (!_pymessage) {
return NULL;
}
}
control_msgs__msg__JointControllerState * ros_message = (control_msgs__msg__JointControllerState *)raw_ros_message;
{ // header
PyObject * field = NULL;
field = std_msgs__msg__header__convert_to_py(&ros_message->header);
if (!field) {
return NULL;
}
{
int rc = PyObject_SetAttrString(_pymessage, "header", field);
Py_DECREF(field);
if (rc) {
return NULL;
}
}
}
{ // set_point
PyObject * field = NULL;
field = PyFloat_FromDouble(ros_message->set_point);
{
int rc = PyObject_SetAttrString(_pymessage, "set_point", field);
Py_DECREF(field);
if (rc) {
return NULL;
}
}
}
{ // process_value
PyObject * field = NULL;
field = PyFloat_FromDouble(ros_message->process_value);
{
int rc = PyObject_SetAttrString(_pymessage, "process_value", field);
Py_DECREF(field);
if (rc) {
return NULL;
}
}
}
{ // process_value_dot
PyObject * field = NULL;
field = PyFloat_FromDouble(ros_message->process_value_dot);
{
int rc = PyObject_SetAttrString(_pymessage, "process_value_dot", field);
Py_DECREF(field);
if (rc) {
return NULL;
}
}
}
{ // error
PyObject * field = NULL;
field = PyFloat_FromDouble(ros_message->error);
{
int rc = PyObject_SetAttrString(_pymessage, "error", field);
Py_DECREF(field);
if (rc) {
return NULL;
}
}
}
{ // time_step
PyObject * field = NULL;
field = PyFloat_FromDouble(ros_message->time_step);
{
int rc = PyObject_SetAttrString(_pymessage, "time_step", field);
Py_DECREF(field);
if (rc) {
return NULL;
}
}
}
{ // command
PyObject * field = NULL;
field = PyFloat_FromDouble(ros_message->command);
{
int rc = PyObject_SetAttrString(_pymessage, "command", field);
Py_DECREF(field);
if (rc) {
return NULL;
}
}
}
{ // p
PyObject * field = NULL;
field = PyFloat_FromDouble(ros_message->p);
{
int rc = PyObject_SetAttrString(_pymessage, "p", field);
Py_DECREF(field);
if (rc) {
return NULL;
}
}
}
{ // i
PyObject * field = NULL;
field = PyFloat_FromDouble(ros_message->i);
{
int rc = PyObject_SetAttrString(_pymessage, "i", field);
Py_DECREF(field);
if (rc) {
return NULL;
}
}
}
{ // d
PyObject * field = NULL;
field = PyFloat_FromDouble(ros_message->d);
{
int rc = PyObject_SetAttrString(_pymessage, "d", field);
Py_DECREF(field);
if (rc) {
return NULL;
}
}
}
{ // i_clamp
PyObject * field = NULL;
field = PyFloat_FromDouble(ros_message->i_clamp);
{
int rc = PyObject_SetAttrString(_pymessage, "i_clamp", field);
Py_DECREF(field);
if (rc) {
return NULL;
}
}
}
{ // antiwindup
PyObject * field = NULL;
field = PyBool_FromLong(ros_message->antiwindup ? 1 : 0);
{
int rc = PyObject_SetAttrString(_pymessage, "antiwindup", field);
Py_DECREF(field);
if (rc) {
return NULL;
}
}
}
// ownership of _pymessage is transferred to the caller
return _pymessage;
}
| 9,042 | C | 26.570122 | 117 | 0.601416 |
Toni-SM/semu.robotics.ros2_bridge/src/semu.robotics.ros2_bridge/semu/robotics/ros2_bridge/packages/control_msgs/msg/_pid_state.py | # generated from rosidl_generator_py/resource/_idl.py.em
# with input from control_msgs:msg/PidState.idl
# generated code does not contain a copyright notice
# Import statements for member types
import rosidl_parser.definition # noqa: E402, I100
class Metaclass_PidState(type):
"""Metaclass of message 'PidState'."""
_CREATE_ROS_MESSAGE = None
_CONVERT_FROM_PY = None
_CONVERT_TO_PY = None
_DESTROY_ROS_MESSAGE = None
_TYPE_SUPPORT = None
__constants = {
}
@classmethod
def __import_type_support__(cls):
try:
from rosidl_generator_py import import_type_support
module = import_type_support('control_msgs')
except ImportError:
import logging
import traceback
logger = logging.getLogger(
'control_msgs.msg.PidState')
logger.debug(
'Failed to import needed modules for type support:\n' +
traceback.format_exc())
else:
cls._CREATE_ROS_MESSAGE = module.create_ros_message_msg__msg__pid_state
cls._CONVERT_FROM_PY = module.convert_from_py_msg__msg__pid_state
cls._CONVERT_TO_PY = module.convert_to_py_msg__msg__pid_state
cls._TYPE_SUPPORT = module.type_support_msg__msg__pid_state
cls._DESTROY_ROS_MESSAGE = module.destroy_ros_message_msg__msg__pid_state
from builtin_interfaces.msg import Duration
if Duration.__class__._TYPE_SUPPORT is None:
Duration.__class__.__import_type_support__()
from std_msgs.msg import Header
if Header.__class__._TYPE_SUPPORT is None:
Header.__class__.__import_type_support__()
@classmethod
def __prepare__(cls, name, bases, **kwargs):
# list constant names here so that they appear in the help text of
# the message class under "Data and other attributes defined here:"
# as well as populate each message instance
return {
}
class PidState(metaclass=Metaclass_PidState):
"""Message class 'PidState'."""
__slots__ = [
'_header',
'_timestep',
'_error',
'_error_dot',
'_p_error',
'_i_error',
'_d_error',
'_p_term',
'_i_term',
'_d_term',
'_i_max',
'_i_min',
'_output',
]
_fields_and_field_types = {
'header': 'std_msgs/Header',
'timestep': 'builtin_interfaces/Duration',
'error': 'double',
'error_dot': 'double',
'p_error': 'double',
'i_error': 'double',
'd_error': 'double',
'p_term': 'double',
'i_term': 'double',
'd_term': 'double',
'i_max': 'double',
'i_min': 'double',
'output': 'double',
}
SLOT_TYPES = (
rosidl_parser.definition.NamespacedType(['std_msgs', 'msg'], 'Header'), # noqa: E501
rosidl_parser.definition.NamespacedType(['builtin_interfaces', 'msg'], 'Duration'), # noqa: E501
rosidl_parser.definition.BasicType('double'), # noqa: E501
rosidl_parser.definition.BasicType('double'), # noqa: E501
rosidl_parser.definition.BasicType('double'), # noqa: E501
rosidl_parser.definition.BasicType('double'), # noqa: E501
rosidl_parser.definition.BasicType('double'), # noqa: E501
rosidl_parser.definition.BasicType('double'), # noqa: E501
rosidl_parser.definition.BasicType('double'), # noqa: E501
rosidl_parser.definition.BasicType('double'), # noqa: E501
rosidl_parser.definition.BasicType('double'), # noqa: E501
rosidl_parser.definition.BasicType('double'), # noqa: E501
rosidl_parser.definition.BasicType('double'), # noqa: E501
)
def __init__(self, **kwargs):
assert all('_' + key in self.__slots__ for key in kwargs.keys()), \
'Invalid arguments passed to constructor: %s' % \
', '.join(sorted(k for k in kwargs.keys() if '_' + k not in self.__slots__))
from std_msgs.msg import Header
self.header = kwargs.get('header', Header())
from builtin_interfaces.msg import Duration
self.timestep = kwargs.get('timestep', Duration())
self.error = kwargs.get('error', float())
self.error_dot = kwargs.get('error_dot', float())
self.p_error = kwargs.get('p_error', float())
self.i_error = kwargs.get('i_error', float())
self.d_error = kwargs.get('d_error', float())
self.p_term = kwargs.get('p_term', float())
self.i_term = kwargs.get('i_term', float())
self.d_term = kwargs.get('d_term', float())
self.i_max = kwargs.get('i_max', float())
self.i_min = kwargs.get('i_min', float())
self.output = kwargs.get('output', float())
def __repr__(self):
typename = self.__class__.__module__.split('.')
typename.pop()
typename.append(self.__class__.__name__)
args = []
for s, t in zip(self.__slots__, self.SLOT_TYPES):
field = getattr(self, s)
fieldstr = repr(field)
# We use Python array type for fields that can be directly stored
# in them, and "normal" sequences for everything else. If it is
# a type that we store in an array, strip off the 'array' portion.
if (
isinstance(t, rosidl_parser.definition.AbstractSequence) and
isinstance(t.value_type, rosidl_parser.definition.BasicType) and
t.value_type.typename in ['float', 'double', 'int8', 'uint8', 'int16', 'uint16', 'int32', 'uint32', 'int64', 'uint64']
):
if len(field) == 0:
fieldstr = '[]'
else:
assert fieldstr.startswith('array(')
prefix = "array('X', "
suffix = ')'
fieldstr = fieldstr[len(prefix):-len(suffix)]
args.append(s[1:] + '=' + fieldstr)
return '%s(%s)' % ('.'.join(typename), ', '.join(args))
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
if self.header != other.header:
return False
if self.timestep != other.timestep:
return False
if self.error != other.error:
return False
if self.error_dot != other.error_dot:
return False
if self.p_error != other.p_error:
return False
if self.i_error != other.i_error:
return False
if self.d_error != other.d_error:
return False
if self.p_term != other.p_term:
return False
if self.i_term != other.i_term:
return False
if self.d_term != other.d_term:
return False
if self.i_max != other.i_max:
return False
if self.i_min != other.i_min:
return False
if self.output != other.output:
return False
return True
@classmethod
def get_fields_and_field_types(cls):
from copy import copy
return copy(cls._fields_and_field_types)
@property
def header(self):
"""Message field 'header'."""
return self._header
@header.setter
def header(self, value):
if __debug__:
from std_msgs.msg import Header
assert \
isinstance(value, Header), \
"The 'header' field must be a sub message of type 'Header'"
self._header = value
@property
def timestep(self):
"""Message field 'timestep'."""
return self._timestep
@timestep.setter
def timestep(self, value):
if __debug__:
from builtin_interfaces.msg import Duration
assert \
isinstance(value, Duration), \
"The 'timestep' field must be a sub message of type 'Duration'"
self._timestep = value
@property
def error(self):
"""Message field 'error'."""
return self._error
@error.setter
def error(self, value):
if __debug__:
assert \
isinstance(value, float), \
"The 'error' field must be of type 'float'"
self._error = value
@property
def error_dot(self):
"""Message field 'error_dot'."""
return self._error_dot
@error_dot.setter
def error_dot(self, value):
if __debug__:
assert \
isinstance(value, float), \
"The 'error_dot' field must be of type 'float'"
self._error_dot = value
@property
def p_error(self):
"""Message field 'p_error'."""
return self._p_error
@p_error.setter
def p_error(self, value):
if __debug__:
assert \
isinstance(value, float), \
"The 'p_error' field must be of type 'float'"
self._p_error = value
@property
def i_error(self):
"""Message field 'i_error'."""
return self._i_error
@i_error.setter
def i_error(self, value):
if __debug__:
assert \
isinstance(value, float), \
"The 'i_error' field must be of type 'float'"
self._i_error = value
@property
def d_error(self):
"""Message field 'd_error'."""
return self._d_error
@d_error.setter
def d_error(self, value):
if __debug__:
assert \
isinstance(value, float), \
"The 'd_error' field must be of type 'float'"
self._d_error = value
@property
def p_term(self):
"""Message field 'p_term'."""
return self._p_term
@p_term.setter
def p_term(self, value):
if __debug__:
assert \
isinstance(value, float), \
"The 'p_term' field must be of type 'float'"
self._p_term = value
@property
def i_term(self):
"""Message field 'i_term'."""
return self._i_term
@i_term.setter
def i_term(self, value):
if __debug__:
assert \
isinstance(value, float), \
"The 'i_term' field must be of type 'float'"
self._i_term = value
@property
def d_term(self):
"""Message field 'd_term'."""
return self._d_term
@d_term.setter
def d_term(self, value):
if __debug__:
assert \
isinstance(value, float), \
"The 'd_term' field must be of type 'float'"
self._d_term = value
@property
def i_max(self):
"""Message field 'i_max'."""
return self._i_max
@i_max.setter
def i_max(self, value):
if __debug__:
assert \
isinstance(value, float), \
"The 'i_max' field must be of type 'float'"
self._i_max = value
@property
def i_min(self):
"""Message field 'i_min'."""
return self._i_min
@i_min.setter
def i_min(self, value):
if __debug__:
assert \
isinstance(value, float), \
"The 'i_min' field must be of type 'float'"
self._i_min = value
@property
def output(self):
"""Message field 'output'."""
return self._output
@output.setter
def output(self, value):
if __debug__:
assert \
isinstance(value, float), \
"The 'output' field must be of type 'float'"
self._output = value
| 11,681 | Python | 31.181818 | 134 | 0.532061 |
Toni-SM/semu.robotics.ros2_bridge/src/semu.robotics.ros2_bridge/semu/robotics/ros2_bridge/packages/control_msgs/msg/_joint_controller_state.py | # generated from rosidl_generator_py/resource/_idl.py.em
# with input from control_msgs:msg/JointControllerState.idl
# generated code does not contain a copyright notice
# Import statements for member types
import rosidl_parser.definition # noqa: E402, I100
class Metaclass_JointControllerState(type):
"""Metaclass of message 'JointControllerState'."""
_CREATE_ROS_MESSAGE = None
_CONVERT_FROM_PY = None
_CONVERT_TO_PY = None
_DESTROY_ROS_MESSAGE = None
_TYPE_SUPPORT = None
__constants = {
}
@classmethod
def __import_type_support__(cls):
try:
from rosidl_generator_py import import_type_support
module = import_type_support('control_msgs')
except ImportError:
import logging
import traceback
logger = logging.getLogger(
'control_msgs.msg.JointControllerState')
logger.debug(
'Failed to import needed modules for type support:\n' +
traceback.format_exc())
else:
cls._CREATE_ROS_MESSAGE = module.create_ros_message_msg__msg__joint_controller_state
cls._CONVERT_FROM_PY = module.convert_from_py_msg__msg__joint_controller_state
cls._CONVERT_TO_PY = module.convert_to_py_msg__msg__joint_controller_state
cls._TYPE_SUPPORT = module.type_support_msg__msg__joint_controller_state
cls._DESTROY_ROS_MESSAGE = module.destroy_ros_message_msg__msg__joint_controller_state
from std_msgs.msg import Header
if Header.__class__._TYPE_SUPPORT is None:
Header.__class__.__import_type_support__()
@classmethod
def __prepare__(cls, name, bases, **kwargs):
# list constant names here so that they appear in the help text of
# the message class under "Data and other attributes defined here:"
# as well as populate each message instance
return {
}
class JointControllerState(metaclass=Metaclass_JointControllerState):
"""Message class 'JointControllerState'."""
__slots__ = [
'_header',
'_set_point',
'_process_value',
'_process_value_dot',
'_error',
'_time_step',
'_command',
'_p',
'_i',
'_d',
'_i_clamp',
'_antiwindup',
]
_fields_and_field_types = {
'header': 'std_msgs/Header',
'set_point': 'double',
'process_value': 'double',
'process_value_dot': 'double',
'error': 'double',
'time_step': 'double',
'command': 'double',
'p': 'double',
'i': 'double',
'd': 'double',
'i_clamp': 'double',
'antiwindup': 'boolean',
}
SLOT_TYPES = (
rosidl_parser.definition.NamespacedType(['std_msgs', 'msg'], 'Header'), # noqa: E501
rosidl_parser.definition.BasicType('double'), # noqa: E501
rosidl_parser.definition.BasicType('double'), # noqa: E501
rosidl_parser.definition.BasicType('double'), # noqa: E501
rosidl_parser.definition.BasicType('double'), # noqa: E501
rosidl_parser.definition.BasicType('double'), # noqa: E501
rosidl_parser.definition.BasicType('double'), # noqa: E501
rosidl_parser.definition.BasicType('double'), # noqa: E501
rosidl_parser.definition.BasicType('double'), # noqa: E501
rosidl_parser.definition.BasicType('double'), # noqa: E501
rosidl_parser.definition.BasicType('double'), # noqa: E501
rosidl_parser.definition.BasicType('boolean'), # noqa: E501
)
def __init__(self, **kwargs):
assert all('_' + key in self.__slots__ for key in kwargs.keys()), \
'Invalid arguments passed to constructor: %s' % \
', '.join(sorted(k for k in kwargs.keys() if '_' + k not in self.__slots__))
from std_msgs.msg import Header
self.header = kwargs.get('header', Header())
self.set_point = kwargs.get('set_point', float())
self.process_value = kwargs.get('process_value', float())
self.process_value_dot = kwargs.get('process_value_dot', float())
self.error = kwargs.get('error', float())
self.time_step = kwargs.get('time_step', float())
self.command = kwargs.get('command', float())
self.p = kwargs.get('p', float())
self.i = kwargs.get('i', float())
self.d = kwargs.get('d', float())
self.i_clamp = kwargs.get('i_clamp', float())
self.antiwindup = kwargs.get('antiwindup', bool())
def __repr__(self):
typename = self.__class__.__module__.split('.')
typename.pop()
typename.append(self.__class__.__name__)
args = []
for s, t in zip(self.__slots__, self.SLOT_TYPES):
field = getattr(self, s)
fieldstr = repr(field)
# We use Python array type for fields that can be directly stored
# in them, and "normal" sequences for everything else. If it is
# a type that we store in an array, strip off the 'array' portion.
if (
isinstance(t, rosidl_parser.definition.AbstractSequence) and
isinstance(t.value_type, rosidl_parser.definition.BasicType) and
t.value_type.typename in ['float', 'double', 'int8', 'uint8', 'int16', 'uint16', 'int32', 'uint32', 'int64', 'uint64']
):
if len(field) == 0:
fieldstr = '[]'
else:
assert fieldstr.startswith('array(')
prefix = "array('X', "
suffix = ')'
fieldstr = fieldstr[len(prefix):-len(suffix)]
args.append(s[1:] + '=' + fieldstr)
return '%s(%s)' % ('.'.join(typename), ', '.join(args))
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
if self.header != other.header:
return False
if self.set_point != other.set_point:
return False
if self.process_value != other.process_value:
return False
if self.process_value_dot != other.process_value_dot:
return False
if self.error != other.error:
return False
if self.time_step != other.time_step:
return False
if self.command != other.command:
return False
if self.p != other.p:
return False
if self.i != other.i:
return False
if self.d != other.d:
return False
if self.i_clamp != other.i_clamp:
return False
if self.antiwindup != other.antiwindup:
return False
return True
@classmethod
def get_fields_and_field_types(cls):
from copy import copy
return copy(cls._fields_and_field_types)
@property
def header(self):
"""Message field 'header'."""
return self._header
@header.setter
def header(self, value):
if __debug__:
from std_msgs.msg import Header
assert \
isinstance(value, Header), \
"The 'header' field must be a sub message of type 'Header'"
self._header = value
@property
def set_point(self):
"""Message field 'set_point'."""
return self._set_point
@set_point.setter
def set_point(self, value):
if __debug__:
assert \
isinstance(value, float), \
"The 'set_point' field must be of type 'float'"
self._set_point = value
@property
def process_value(self):
"""Message field 'process_value'."""
return self._process_value
@process_value.setter
def process_value(self, value):
if __debug__:
assert \
isinstance(value, float), \
"The 'process_value' field must be of type 'float'"
self._process_value = value
@property
def process_value_dot(self):
"""Message field 'process_value_dot'."""
return self._process_value_dot
@process_value_dot.setter
def process_value_dot(self, value):
if __debug__:
assert \
isinstance(value, float), \
"The 'process_value_dot' field must be of type 'float'"
self._process_value_dot = value
@property
def error(self):
"""Message field 'error'."""
return self._error
@error.setter
def error(self, value):
if __debug__:
assert \
isinstance(value, float), \
"The 'error' field must be of type 'float'"
self._error = value
@property
def time_step(self):
"""Message field 'time_step'."""
return self._time_step
@time_step.setter
def time_step(self, value):
if __debug__:
assert \
isinstance(value, float), \
"The 'time_step' field must be of type 'float'"
self._time_step = value
@property
def command(self):
"""Message field 'command'."""
return self._command
@command.setter
def command(self, value):
if __debug__:
assert \
isinstance(value, float), \
"The 'command' field must be of type 'float'"
self._command = value
@property
def p(self):
"""Message field 'p'."""
return self._p
@p.setter
def p(self, value):
if __debug__:
assert \
isinstance(value, float), \
"The 'p' field must be of type 'float'"
self._p = value
@property
def i(self):
"""Message field 'i'."""
return self._i
@i.setter
def i(self, value):
if __debug__:
assert \
isinstance(value, float), \
"The 'i' field must be of type 'float'"
self._i = value
@property
def d(self):
"""Message field 'd'."""
return self._d
@d.setter
def d(self, value):
if __debug__:
assert \
isinstance(value, float), \
"The 'd' field must be of type 'float'"
self._d = value
@property
def i_clamp(self):
"""Message field 'i_clamp'."""
return self._i_clamp
@i_clamp.setter
def i_clamp(self, value):
if __debug__:
assert \
isinstance(value, float), \
"The 'i_clamp' field must be of type 'float'"
self._i_clamp = value
@property
def antiwindup(self):
"""Message field 'antiwindup'."""
return self._antiwindup
@antiwindup.setter
def antiwindup(self, value):
if __debug__:
assert \
isinstance(value, bool), \
"The 'antiwindup' field must be of type 'bool'"
self._antiwindup = value
| 11,020 | Python | 31.606509 | 134 | 0.54274 |
Toni-SM/semu.robotics.ros2_bridge/src/semu.robotics.ros2_bridge/semu/robotics/ros2_bridge/packages/control_msgs/msg/__init__.py | from control_msgs.msg._dynamic_joint_state import DynamicJointState # noqa: F401
from control_msgs.msg._gripper_command import GripperCommand # noqa: F401
from control_msgs.msg._interface_value import InterfaceValue # noqa: F401
from control_msgs.msg._joint_controller_state import JointControllerState # noqa: F401
from control_msgs.msg._joint_jog import JointJog # noqa: F401
from control_msgs.msg._joint_tolerance import JointTolerance # noqa: F401
from control_msgs.msg._joint_trajectory_controller_state import JointTrajectoryControllerState # noqa: F401
from control_msgs.msg._pid_state import PidState # noqa: F401
| 630 | Python | 69.111103 | 108 | 0.803175 |
Toni-SM/semu.robotics.ros2_bridge/src/semu.robotics.ros2_bridge/semu/robotics/ros2_bridge/packages/control_msgs/msg/_gripper_command_s.c | // generated from rosidl_generator_py/resource/_idl_support.c.em
// with input from control_msgs:msg/GripperCommand.idl
// generated code does not contain a copyright notice
#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION
#include <Python.h>
#include <stdbool.h>
#ifndef _WIN32
# pragma GCC diagnostic push
# pragma GCC diagnostic ignored "-Wunused-function"
#endif
#include "numpy/ndarrayobject.h"
#ifndef _WIN32
# pragma GCC diagnostic pop
#endif
#include "rosidl_runtime_c/visibility_control.h"
#include "control_msgs/msg/detail/gripper_command__struct.h"
#include "control_msgs/msg/detail/gripper_command__functions.h"
ROSIDL_GENERATOR_C_EXPORT
bool control_msgs__msg__gripper_command__convert_from_py(PyObject * _pymsg, void * _ros_message)
{
// check that the passed message is of the expected Python class
{
char full_classname_dest[49];
{
char * class_name = NULL;
char * module_name = NULL;
{
PyObject * class_attr = PyObject_GetAttrString(_pymsg, "__class__");
if (class_attr) {
PyObject * name_attr = PyObject_GetAttrString(class_attr, "__name__");
if (name_attr) {
class_name = (char *)PyUnicode_1BYTE_DATA(name_attr);
Py_DECREF(name_attr);
}
PyObject * module_attr = PyObject_GetAttrString(class_attr, "__module__");
if (module_attr) {
module_name = (char *)PyUnicode_1BYTE_DATA(module_attr);
Py_DECREF(module_attr);
}
Py_DECREF(class_attr);
}
}
if (!class_name || !module_name) {
return false;
}
snprintf(full_classname_dest, sizeof(full_classname_dest), "%s.%s", module_name, class_name);
}
assert(strncmp("control_msgs.msg._gripper_command.GripperCommand", full_classname_dest, 48) == 0);
}
control_msgs__msg__GripperCommand * ros_message = _ros_message;
{ // position
PyObject * field = PyObject_GetAttrString(_pymsg, "position");
if (!field) {
return false;
}
assert(PyFloat_Check(field));
ros_message->position = PyFloat_AS_DOUBLE(field);
Py_DECREF(field);
}
{ // max_effort
PyObject * field = PyObject_GetAttrString(_pymsg, "max_effort");
if (!field) {
return false;
}
assert(PyFloat_Check(field));
ros_message->max_effort = PyFloat_AS_DOUBLE(field);
Py_DECREF(field);
}
return true;
}
ROSIDL_GENERATOR_C_EXPORT
PyObject * control_msgs__msg__gripper_command__convert_to_py(void * raw_ros_message)
{
/* NOTE(esteve): Call constructor of GripperCommand */
PyObject * _pymessage = NULL;
{
PyObject * pymessage_module = PyImport_ImportModule("control_msgs.msg._gripper_command");
assert(pymessage_module);
PyObject * pymessage_class = PyObject_GetAttrString(pymessage_module, "GripperCommand");
assert(pymessage_class);
Py_DECREF(pymessage_module);
_pymessage = PyObject_CallObject(pymessage_class, NULL);
Py_DECREF(pymessage_class);
if (!_pymessage) {
return NULL;
}
}
control_msgs__msg__GripperCommand * ros_message = (control_msgs__msg__GripperCommand *)raw_ros_message;
{ // position
PyObject * field = NULL;
field = PyFloat_FromDouble(ros_message->position);
{
int rc = PyObject_SetAttrString(_pymessage, "position", field);
Py_DECREF(field);
if (rc) {
return NULL;
}
}
}
{ // max_effort
PyObject * field = NULL;
field = PyFloat_FromDouble(ros_message->max_effort);
{
int rc = PyObject_SetAttrString(_pymessage, "max_effort", field);
Py_DECREF(field);
if (rc) {
return NULL;
}
}
}
// ownership of _pymessage is transferred to the caller
return _pymessage;
}
| 3,736 | C | 30.403361 | 105 | 0.643201 |
Toni-SM/semu.robotics.ros2_bridge/src/semu.robotics.ros2_bridge/semu/robotics/ros2_bridge/packages/control_msgs/msg/_gripper_command.py | # generated from rosidl_generator_py/resource/_idl.py.em
# with input from control_msgs:msg/GripperCommand.idl
# generated code does not contain a copyright notice
# Import statements for member types
import rosidl_parser.definition # noqa: E402, I100
class Metaclass_GripperCommand(type):
"""Metaclass of message 'GripperCommand'."""
_CREATE_ROS_MESSAGE = None
_CONVERT_FROM_PY = None
_CONVERT_TO_PY = None
_DESTROY_ROS_MESSAGE = None
_TYPE_SUPPORT = None
__constants = {
}
@classmethod
def __import_type_support__(cls):
try:
from rosidl_generator_py import import_type_support
module = import_type_support('control_msgs')
except ImportError:
import logging
import traceback
logger = logging.getLogger(
'control_msgs.msg.GripperCommand')
logger.debug(
'Failed to import needed modules for type support:\n' +
traceback.format_exc())
else:
cls._CREATE_ROS_MESSAGE = module.create_ros_message_msg__msg__gripper_command
cls._CONVERT_FROM_PY = module.convert_from_py_msg__msg__gripper_command
cls._CONVERT_TO_PY = module.convert_to_py_msg__msg__gripper_command
cls._TYPE_SUPPORT = module.type_support_msg__msg__gripper_command
cls._DESTROY_ROS_MESSAGE = module.destroy_ros_message_msg__msg__gripper_command
@classmethod
def __prepare__(cls, name, bases, **kwargs):
# list constant names here so that they appear in the help text of
# the message class under "Data and other attributes defined here:"
# as well as populate each message instance
return {
}
class GripperCommand(metaclass=Metaclass_GripperCommand):
"""Message class 'GripperCommand'."""
__slots__ = [
'_position',
'_max_effort',
]
_fields_and_field_types = {
'position': 'double',
'max_effort': 'double',
}
SLOT_TYPES = (
rosidl_parser.definition.BasicType('double'), # noqa: E501
rosidl_parser.definition.BasicType('double'), # noqa: E501
)
def __init__(self, **kwargs):
assert all('_' + key in self.__slots__ for key in kwargs.keys()), \
'Invalid arguments passed to constructor: %s' % \
', '.join(sorted(k for k in kwargs.keys() if '_' + k not in self.__slots__))
self.position = kwargs.get('position', float())
self.max_effort = kwargs.get('max_effort', float())
def __repr__(self):
typename = self.__class__.__module__.split('.')
typename.pop()
typename.append(self.__class__.__name__)
args = []
for s, t in zip(self.__slots__, self.SLOT_TYPES):
field = getattr(self, s)
fieldstr = repr(field)
# We use Python array type for fields that can be directly stored
# in them, and "normal" sequences for everything else. If it is
# a type that we store in an array, strip off the 'array' portion.
if (
isinstance(t, rosidl_parser.definition.AbstractSequence) and
isinstance(t.value_type, rosidl_parser.definition.BasicType) and
t.value_type.typename in ['float', 'double', 'int8', 'uint8', 'int16', 'uint16', 'int32', 'uint32', 'int64', 'uint64']
):
if len(field) == 0:
fieldstr = '[]'
else:
assert fieldstr.startswith('array(')
prefix = "array('X', "
suffix = ')'
fieldstr = fieldstr[len(prefix):-len(suffix)]
args.append(s[1:] + '=' + fieldstr)
return '%s(%s)' % ('.'.join(typename), ', '.join(args))
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
if self.position != other.position:
return False
if self.max_effort != other.max_effort:
return False
return True
@classmethod
def get_fields_and_field_types(cls):
from copy import copy
return copy(cls._fields_and_field_types)
@property
def position(self):
"""Message field 'position'."""
return self._position
@position.setter
def position(self, value):
if __debug__:
assert \
isinstance(value, float), \
"The 'position' field must be of type 'float'"
self._position = value
@property
def max_effort(self):
"""Message field 'max_effort'."""
return self._max_effort
@max_effort.setter
def max_effort(self, value):
if __debug__:
assert \
isinstance(value, float), \
"The 'max_effort' field must be of type 'float'"
self._max_effort = value
| 4,935 | Python | 33.760563 | 134 | 0.565147 |
Toni-SM/semu.robotics.ros2_bridge/src/semu.robotics.ros2_bridge/semu/robotics/ros2_bridge/packages/control_msgs/msg/_joint_trajectory_controller_state_s.c | // generated from rosidl_generator_py/resource/_idl_support.c.em
// with input from control_msgs:msg/JointTrajectoryControllerState.idl
// generated code does not contain a copyright notice
#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION
#include <Python.h>
#include <stdbool.h>
#ifndef _WIN32
# pragma GCC diagnostic push
# pragma GCC diagnostic ignored "-Wunused-function"
#endif
#include "numpy/ndarrayobject.h"
#ifndef _WIN32
# pragma GCC diagnostic pop
#endif
#include "rosidl_runtime_c/visibility_control.h"
#include "control_msgs/msg/detail/joint_trajectory_controller_state__struct.h"
#include "control_msgs/msg/detail/joint_trajectory_controller_state__functions.h"
#include "rosidl_runtime_c/primitives_sequence.h"
#include "rosidl_runtime_c/primitives_sequence_functions.h"
#include "rosidl_runtime_c/string.h"
#include "rosidl_runtime_c/string_functions.h"
ROSIDL_GENERATOR_C_IMPORT
bool std_msgs__msg__header__convert_from_py(PyObject * _pymsg, void * _ros_message);
ROSIDL_GENERATOR_C_IMPORT
PyObject * std_msgs__msg__header__convert_to_py(void * raw_ros_message);
ROSIDL_GENERATOR_C_IMPORT
bool trajectory_msgs__msg__joint_trajectory_point__convert_from_py(PyObject * _pymsg, void * _ros_message);
ROSIDL_GENERATOR_C_IMPORT
PyObject * trajectory_msgs__msg__joint_trajectory_point__convert_to_py(void * raw_ros_message);
ROSIDL_GENERATOR_C_IMPORT
bool trajectory_msgs__msg__joint_trajectory_point__convert_from_py(PyObject * _pymsg, void * _ros_message);
ROSIDL_GENERATOR_C_IMPORT
PyObject * trajectory_msgs__msg__joint_trajectory_point__convert_to_py(void * raw_ros_message);
ROSIDL_GENERATOR_C_IMPORT
bool trajectory_msgs__msg__joint_trajectory_point__convert_from_py(PyObject * _pymsg, void * _ros_message);
ROSIDL_GENERATOR_C_IMPORT
PyObject * trajectory_msgs__msg__joint_trajectory_point__convert_to_py(void * raw_ros_message);
ROSIDL_GENERATOR_C_EXPORT
bool control_msgs__msg__joint_trajectory_controller_state__convert_from_py(PyObject * _pymsg, void * _ros_message)
{
// check that the passed message is of the expected Python class
{
char full_classname_dest[83];
{
char * class_name = NULL;
char * module_name = NULL;
{
PyObject * class_attr = PyObject_GetAttrString(_pymsg, "__class__");
if (class_attr) {
PyObject * name_attr = PyObject_GetAttrString(class_attr, "__name__");
if (name_attr) {
class_name = (char *)PyUnicode_1BYTE_DATA(name_attr);
Py_DECREF(name_attr);
}
PyObject * module_attr = PyObject_GetAttrString(class_attr, "__module__");
if (module_attr) {
module_name = (char *)PyUnicode_1BYTE_DATA(module_attr);
Py_DECREF(module_attr);
}
Py_DECREF(class_attr);
}
}
if (!class_name || !module_name) {
return false;
}
snprintf(full_classname_dest, sizeof(full_classname_dest), "%s.%s", module_name, class_name);
}
assert(strncmp("control_msgs.msg._joint_trajectory_controller_state.JointTrajectoryControllerState", full_classname_dest, 82) == 0);
}
control_msgs__msg__JointTrajectoryControllerState * ros_message = _ros_message;
{ // header
PyObject * field = PyObject_GetAttrString(_pymsg, "header");
if (!field) {
return false;
}
if (!std_msgs__msg__header__convert_from_py(field, &ros_message->header)) {
Py_DECREF(field);
return false;
}
Py_DECREF(field);
}
{ // joint_names
PyObject * field = PyObject_GetAttrString(_pymsg, "joint_names");
if (!field) {
return false;
}
PyObject * seq_field = PySequence_Fast(field, "expected a sequence in 'joint_names'");
if (!seq_field) {
Py_DECREF(field);
return false;
}
Py_ssize_t size = PySequence_Size(field);
if (-1 == size) {
Py_DECREF(seq_field);
Py_DECREF(field);
return false;
}
if (!rosidl_runtime_c__String__Sequence__init(&(ros_message->joint_names), size)) {
PyErr_SetString(PyExc_RuntimeError, "unable to create String__Sequence ros_message");
Py_DECREF(seq_field);
Py_DECREF(field);
return false;
}
rosidl_runtime_c__String * dest = ros_message->joint_names.data;
for (Py_ssize_t i = 0; i < size; ++i) {
PyObject * item = PySequence_Fast_GET_ITEM(seq_field, i);
if (!item) {
Py_DECREF(seq_field);
Py_DECREF(field);
return false;
}
assert(PyUnicode_Check(item));
PyObject * encoded_item = PyUnicode_AsUTF8String(item);
if (!encoded_item) {
Py_DECREF(seq_field);
Py_DECREF(field);
return false;
}
rosidl_runtime_c__String__assign(&dest[i], PyBytes_AS_STRING(encoded_item));
Py_DECREF(encoded_item);
}
Py_DECREF(seq_field);
Py_DECREF(field);
}
{ // desired
PyObject * field = PyObject_GetAttrString(_pymsg, "desired");
if (!field) {
return false;
}
if (!trajectory_msgs__msg__joint_trajectory_point__convert_from_py(field, &ros_message->desired)) {
Py_DECREF(field);
return false;
}
Py_DECREF(field);
}
{ // actual
PyObject * field = PyObject_GetAttrString(_pymsg, "actual");
if (!field) {
return false;
}
if (!trajectory_msgs__msg__joint_trajectory_point__convert_from_py(field, &ros_message->actual)) {
Py_DECREF(field);
return false;
}
Py_DECREF(field);
}
{ // error
PyObject * field = PyObject_GetAttrString(_pymsg, "error");
if (!field) {
return false;
}
if (!trajectory_msgs__msg__joint_trajectory_point__convert_from_py(field, &ros_message->error)) {
Py_DECREF(field);
return false;
}
Py_DECREF(field);
}
return true;
}
ROSIDL_GENERATOR_C_EXPORT
PyObject * control_msgs__msg__joint_trajectory_controller_state__convert_to_py(void * raw_ros_message)
{
/* NOTE(esteve): Call constructor of JointTrajectoryControllerState */
PyObject * _pymessage = NULL;
{
PyObject * pymessage_module = PyImport_ImportModule("control_msgs.msg._joint_trajectory_controller_state");
assert(pymessage_module);
PyObject * pymessage_class = PyObject_GetAttrString(pymessage_module, "JointTrajectoryControllerState");
assert(pymessage_class);
Py_DECREF(pymessage_module);
_pymessage = PyObject_CallObject(pymessage_class, NULL);
Py_DECREF(pymessage_class);
if (!_pymessage) {
return NULL;
}
}
control_msgs__msg__JointTrajectoryControllerState * ros_message = (control_msgs__msg__JointTrajectoryControllerState *)raw_ros_message;
{ // header
PyObject * field = NULL;
field = std_msgs__msg__header__convert_to_py(&ros_message->header);
if (!field) {
return NULL;
}
{
int rc = PyObject_SetAttrString(_pymessage, "header", field);
Py_DECREF(field);
if (rc) {
return NULL;
}
}
}
{ // joint_names
PyObject * field = NULL;
size_t size = ros_message->joint_names.size;
rosidl_runtime_c__String * src = ros_message->joint_names.data;
field = PyList_New(size);
if (!field) {
return NULL;
}
for (size_t i = 0; i < size; ++i) {
PyObject * decoded_item = PyUnicode_DecodeUTF8(src[i].data, strlen(src[i].data), "strict");
if (!decoded_item) {
return NULL;
}
int rc = PyList_SetItem(field, i, decoded_item);
(void)rc;
assert(rc == 0);
}
assert(PySequence_Check(field));
{
int rc = PyObject_SetAttrString(_pymessage, "joint_names", field);
Py_DECREF(field);
if (rc) {
return NULL;
}
}
}
{ // desired
PyObject * field = NULL;
field = trajectory_msgs__msg__joint_trajectory_point__convert_to_py(&ros_message->desired);
if (!field) {
return NULL;
}
{
int rc = PyObject_SetAttrString(_pymessage, "desired", field);
Py_DECREF(field);
if (rc) {
return NULL;
}
}
}
{ // actual
PyObject * field = NULL;
field = trajectory_msgs__msg__joint_trajectory_point__convert_to_py(&ros_message->actual);
if (!field) {
return NULL;
}
{
int rc = PyObject_SetAttrString(_pymessage, "actual", field);
Py_DECREF(field);
if (rc) {
return NULL;
}
}
}
{ // error
PyObject * field = NULL;
field = trajectory_msgs__msg__joint_trajectory_point__convert_to_py(&ros_message->error);
if (!field) {
return NULL;
}
{
int rc = PyObject_SetAttrString(_pymessage, "error", field);
Py_DECREF(field);
if (rc) {
return NULL;
}
}
}
// ownership of _pymessage is transferred to the caller
return _pymessage;
}
| 8,722 | C | 31.427509 | 137 | 0.634946 |
Toni-SM/semu.robotics.ros2_bridge/src/semu.robotics.ros2_bridge/semu/robotics/ros2_bridge/packages/control_msgs/msg/_dynamic_joint_state.py | # generated from rosidl_generator_py/resource/_idl.py.em
# with input from control_msgs:msg/DynamicJointState.idl
# generated code does not contain a copyright notice
# Import statements for member types
import rosidl_parser.definition # noqa: E402, I100
class Metaclass_DynamicJointState(type):
"""Metaclass of message 'DynamicJointState'."""
_CREATE_ROS_MESSAGE = None
_CONVERT_FROM_PY = None
_CONVERT_TO_PY = None
_DESTROY_ROS_MESSAGE = None
_TYPE_SUPPORT = None
__constants = {
}
@classmethod
def __import_type_support__(cls):
try:
from rosidl_generator_py import import_type_support
module = import_type_support('control_msgs')
except ImportError:
import logging
import traceback
logger = logging.getLogger(
'control_msgs.msg.DynamicJointState')
logger.debug(
'Failed to import needed modules for type support:\n' +
traceback.format_exc())
else:
cls._CREATE_ROS_MESSAGE = module.create_ros_message_msg__msg__dynamic_joint_state
cls._CONVERT_FROM_PY = module.convert_from_py_msg__msg__dynamic_joint_state
cls._CONVERT_TO_PY = module.convert_to_py_msg__msg__dynamic_joint_state
cls._TYPE_SUPPORT = module.type_support_msg__msg__dynamic_joint_state
cls._DESTROY_ROS_MESSAGE = module.destroy_ros_message_msg__msg__dynamic_joint_state
from control_msgs.msg import InterfaceValue
if InterfaceValue.__class__._TYPE_SUPPORT is None:
InterfaceValue.__class__.__import_type_support__()
from std_msgs.msg import Header
if Header.__class__._TYPE_SUPPORT is None:
Header.__class__.__import_type_support__()
@classmethod
def __prepare__(cls, name, bases, **kwargs):
# list constant names here so that they appear in the help text of
# the message class under "Data and other attributes defined here:"
# as well as populate each message instance
return {
}
class DynamicJointState(metaclass=Metaclass_DynamicJointState):
"""Message class 'DynamicJointState'."""
__slots__ = [
'_header',
'_joint_names',
'_interface_values',
]
_fields_and_field_types = {
'header': 'std_msgs/Header',
'joint_names': 'sequence<string>',
'interface_values': 'sequence<control_msgs/InterfaceValue>',
}
SLOT_TYPES = (
rosidl_parser.definition.NamespacedType(['std_msgs', 'msg'], 'Header'), # noqa: E501
rosidl_parser.definition.UnboundedSequence(rosidl_parser.definition.UnboundedString()), # noqa: E501
rosidl_parser.definition.UnboundedSequence(rosidl_parser.definition.NamespacedType(['control_msgs', 'msg'], 'InterfaceValue')), # noqa: E501
)
def __init__(self, **kwargs):
assert all('_' + key in self.__slots__ for key in kwargs.keys()), \
'Invalid arguments passed to constructor: %s' % \
', '.join(sorted(k for k in kwargs.keys() if '_' + k not in self.__slots__))
from std_msgs.msg import Header
self.header = kwargs.get('header', Header())
self.joint_names = kwargs.get('joint_names', [])
self.interface_values = kwargs.get('interface_values', [])
def __repr__(self):
typename = self.__class__.__module__.split('.')
typename.pop()
typename.append(self.__class__.__name__)
args = []
for s, t in zip(self.__slots__, self.SLOT_TYPES):
field = getattr(self, s)
fieldstr = repr(field)
# We use Python array type for fields that can be directly stored
# in them, and "normal" sequences for everything else. If it is
# a type that we store in an array, strip off the 'array' portion.
if (
isinstance(t, rosidl_parser.definition.AbstractSequence) and
isinstance(t.value_type, rosidl_parser.definition.BasicType) and
t.value_type.typename in ['float', 'double', 'int8', 'uint8', 'int16', 'uint16', 'int32', 'uint32', 'int64', 'uint64']
):
if len(field) == 0:
fieldstr = '[]'
else:
assert fieldstr.startswith('array(')
prefix = "array('X', "
suffix = ')'
fieldstr = fieldstr[len(prefix):-len(suffix)]
args.append(s[1:] + '=' + fieldstr)
return '%s(%s)' % ('.'.join(typename), ', '.join(args))
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
if self.header != other.header:
return False
if self.joint_names != other.joint_names:
return False
if self.interface_values != other.interface_values:
return False
return True
@classmethod
def get_fields_and_field_types(cls):
from copy import copy
return copy(cls._fields_and_field_types)
@property
def header(self):
"""Message field 'header'."""
return self._header
@header.setter
def header(self, value):
if __debug__:
from std_msgs.msg import Header
assert \
isinstance(value, Header), \
"The 'header' field must be a sub message of type 'Header'"
self._header = value
@property
def joint_names(self):
"""Message field 'joint_names'."""
return self._joint_names
@joint_names.setter
def joint_names(self, value):
if __debug__:
from collections.abc import Sequence
from collections.abc import Set
from collections import UserList
from collections import UserString
assert \
((isinstance(value, Sequence) or
isinstance(value, Set) or
isinstance(value, UserList)) and
not isinstance(value, str) and
not isinstance(value, UserString) and
all(isinstance(v, str) for v in value) and
True), \
"The 'joint_names' field must be a set or sequence and each value of type 'str'"
self._joint_names = value
@property
def interface_values(self):
"""Message field 'interface_values'."""
return self._interface_values
@interface_values.setter
def interface_values(self, value):
if __debug__:
from control_msgs.msg import InterfaceValue
from collections.abc import Sequence
from collections.abc import Set
from collections import UserList
from collections import UserString
assert \
((isinstance(value, Sequence) or
isinstance(value, Set) or
isinstance(value, UserList)) and
not isinstance(value, str) and
not isinstance(value, UserString) and
all(isinstance(v, InterfaceValue) for v in value) and
True), \
"The 'interface_values' field must be a set or sequence and each value of type 'InterfaceValue'"
self._interface_values = value
| 7,379 | Python | 37.4375 | 149 | 0.577585 |
Toni-SM/semu.robotics.ros2_bridge/src/semu.robotics.ros2_bridge/semu/robotics/ros2_bridge/packages/control_msgs/msg/_joint_jog_s.c | // generated from rosidl_generator_py/resource/_idl_support.c.em
// with input from control_msgs:msg/JointJog.idl
// generated code does not contain a copyright notice
#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION
#include <Python.h>
#include <stdbool.h>
#ifndef _WIN32
# pragma GCC diagnostic push
# pragma GCC diagnostic ignored "-Wunused-function"
#endif
#include "numpy/ndarrayobject.h"
#ifndef _WIN32
# pragma GCC diagnostic pop
#endif
#include "rosidl_runtime_c/visibility_control.h"
#include "control_msgs/msg/detail/joint_jog__struct.h"
#include "control_msgs/msg/detail/joint_jog__functions.h"
#include "rosidl_runtime_c/primitives_sequence.h"
#include "rosidl_runtime_c/primitives_sequence_functions.h"
#include "rosidl_runtime_c/string.h"
#include "rosidl_runtime_c/string_functions.h"
ROSIDL_GENERATOR_C_IMPORT
bool std_msgs__msg__header__convert_from_py(PyObject * _pymsg, void * _ros_message);
ROSIDL_GENERATOR_C_IMPORT
PyObject * std_msgs__msg__header__convert_to_py(void * raw_ros_message);
ROSIDL_GENERATOR_C_EXPORT
bool control_msgs__msg__joint_jog__convert_from_py(PyObject * _pymsg, void * _ros_message)
{
// check that the passed message is of the expected Python class
{
char full_classname_dest[37];
{
char * class_name = NULL;
char * module_name = NULL;
{
PyObject * class_attr = PyObject_GetAttrString(_pymsg, "__class__");
if (class_attr) {
PyObject * name_attr = PyObject_GetAttrString(class_attr, "__name__");
if (name_attr) {
class_name = (char *)PyUnicode_1BYTE_DATA(name_attr);
Py_DECREF(name_attr);
}
PyObject * module_attr = PyObject_GetAttrString(class_attr, "__module__");
if (module_attr) {
module_name = (char *)PyUnicode_1BYTE_DATA(module_attr);
Py_DECREF(module_attr);
}
Py_DECREF(class_attr);
}
}
if (!class_name || !module_name) {
return false;
}
snprintf(full_classname_dest, sizeof(full_classname_dest), "%s.%s", module_name, class_name);
}
assert(strncmp("control_msgs.msg._joint_jog.JointJog", full_classname_dest, 36) == 0);
}
control_msgs__msg__JointJog * ros_message = _ros_message;
{ // header
PyObject * field = PyObject_GetAttrString(_pymsg, "header");
if (!field) {
return false;
}
if (!std_msgs__msg__header__convert_from_py(field, &ros_message->header)) {
Py_DECREF(field);
return false;
}
Py_DECREF(field);
}
{ // joint_names
PyObject * field = PyObject_GetAttrString(_pymsg, "joint_names");
if (!field) {
return false;
}
PyObject * seq_field = PySequence_Fast(field, "expected a sequence in 'joint_names'");
if (!seq_field) {
Py_DECREF(field);
return false;
}
Py_ssize_t size = PySequence_Size(field);
if (-1 == size) {
Py_DECREF(seq_field);
Py_DECREF(field);
return false;
}
if (!rosidl_runtime_c__String__Sequence__init(&(ros_message->joint_names), size)) {
PyErr_SetString(PyExc_RuntimeError, "unable to create String__Sequence ros_message");
Py_DECREF(seq_field);
Py_DECREF(field);
return false;
}
rosidl_runtime_c__String * dest = ros_message->joint_names.data;
for (Py_ssize_t i = 0; i < size; ++i) {
PyObject * item = PySequence_Fast_GET_ITEM(seq_field, i);
if (!item) {
Py_DECREF(seq_field);
Py_DECREF(field);
return false;
}
assert(PyUnicode_Check(item));
PyObject * encoded_item = PyUnicode_AsUTF8String(item);
if (!encoded_item) {
Py_DECREF(seq_field);
Py_DECREF(field);
return false;
}
rosidl_runtime_c__String__assign(&dest[i], PyBytes_AS_STRING(encoded_item));
Py_DECREF(encoded_item);
}
Py_DECREF(seq_field);
Py_DECREF(field);
}
{ // displacements
PyObject * field = PyObject_GetAttrString(_pymsg, "displacements");
if (!field) {
return false;
}
PyObject * seq_field = PySequence_Fast(field, "expected a sequence in 'displacements'");
if (!seq_field) {
Py_DECREF(field);
return false;
}
Py_ssize_t size = PySequence_Size(field);
if (-1 == size) {
Py_DECREF(seq_field);
Py_DECREF(field);
return false;
}
if (!rosidl_runtime_c__double__Sequence__init(&(ros_message->displacements), size)) {
PyErr_SetString(PyExc_RuntimeError, "unable to create double__Sequence ros_message");
Py_DECREF(seq_field);
Py_DECREF(field);
return false;
}
double * dest = ros_message->displacements.data;
for (Py_ssize_t i = 0; i < size; ++i) {
PyObject * item = PySequence_Fast_GET_ITEM(seq_field, i);
if (!item) {
Py_DECREF(seq_field);
Py_DECREF(field);
return false;
}
assert(PyFloat_Check(item));
double tmp = PyFloat_AS_DOUBLE(item);
memcpy(&dest[i], &tmp, sizeof(double));
}
Py_DECREF(seq_field);
Py_DECREF(field);
}
{ // velocities
PyObject * field = PyObject_GetAttrString(_pymsg, "velocities");
if (!field) {
return false;
}
PyObject * seq_field = PySequence_Fast(field, "expected a sequence in 'velocities'");
if (!seq_field) {
Py_DECREF(field);
return false;
}
Py_ssize_t size = PySequence_Size(field);
if (-1 == size) {
Py_DECREF(seq_field);
Py_DECREF(field);
return false;
}
if (!rosidl_runtime_c__double__Sequence__init(&(ros_message->velocities), size)) {
PyErr_SetString(PyExc_RuntimeError, "unable to create double__Sequence ros_message");
Py_DECREF(seq_field);
Py_DECREF(field);
return false;
}
double * dest = ros_message->velocities.data;
for (Py_ssize_t i = 0; i < size; ++i) {
PyObject * item = PySequence_Fast_GET_ITEM(seq_field, i);
if (!item) {
Py_DECREF(seq_field);
Py_DECREF(field);
return false;
}
assert(PyFloat_Check(item));
double tmp = PyFloat_AS_DOUBLE(item);
memcpy(&dest[i], &tmp, sizeof(double));
}
Py_DECREF(seq_field);
Py_DECREF(field);
}
{ // duration
PyObject * field = PyObject_GetAttrString(_pymsg, "duration");
if (!field) {
return false;
}
assert(PyFloat_Check(field));
ros_message->duration = PyFloat_AS_DOUBLE(field);
Py_DECREF(field);
}
return true;
}
ROSIDL_GENERATOR_C_EXPORT
PyObject * control_msgs__msg__joint_jog__convert_to_py(void * raw_ros_message)
{
/* NOTE(esteve): Call constructor of JointJog */
PyObject * _pymessage = NULL;
{
PyObject * pymessage_module = PyImport_ImportModule("control_msgs.msg._joint_jog");
assert(pymessage_module);
PyObject * pymessage_class = PyObject_GetAttrString(pymessage_module, "JointJog");
assert(pymessage_class);
Py_DECREF(pymessage_module);
_pymessage = PyObject_CallObject(pymessage_class, NULL);
Py_DECREF(pymessage_class);
if (!_pymessage) {
return NULL;
}
}
control_msgs__msg__JointJog * ros_message = (control_msgs__msg__JointJog *)raw_ros_message;
{ // header
PyObject * field = NULL;
field = std_msgs__msg__header__convert_to_py(&ros_message->header);
if (!field) {
return NULL;
}
{
int rc = PyObject_SetAttrString(_pymessage, "header", field);
Py_DECREF(field);
if (rc) {
return NULL;
}
}
}
{ // joint_names
PyObject * field = NULL;
size_t size = ros_message->joint_names.size;
rosidl_runtime_c__String * src = ros_message->joint_names.data;
field = PyList_New(size);
if (!field) {
return NULL;
}
for (size_t i = 0; i < size; ++i) {
PyObject * decoded_item = PyUnicode_DecodeUTF8(src[i].data, strlen(src[i].data), "strict");
if (!decoded_item) {
return NULL;
}
int rc = PyList_SetItem(field, i, decoded_item);
(void)rc;
assert(rc == 0);
}
assert(PySequence_Check(field));
{
int rc = PyObject_SetAttrString(_pymessage, "joint_names", field);
Py_DECREF(field);
if (rc) {
return NULL;
}
}
}
{ // displacements
PyObject * field = NULL;
field = PyObject_GetAttrString(_pymessage, "displacements");
if (!field) {
return NULL;
}
assert(field->ob_type != NULL);
assert(field->ob_type->tp_name != NULL);
assert(strcmp(field->ob_type->tp_name, "array.array") == 0);
// ensure that itemsize matches the sizeof of the ROS message field
PyObject * itemsize_attr = PyObject_GetAttrString(field, "itemsize");
assert(itemsize_attr != NULL);
size_t itemsize = PyLong_AsSize_t(itemsize_attr);
Py_DECREF(itemsize_attr);
if (itemsize != sizeof(double)) {
PyErr_SetString(PyExc_RuntimeError, "itemsize doesn't match expectation");
Py_DECREF(field);
return NULL;
}
// clear the array, poor approach to remove potential default values
Py_ssize_t length = PyObject_Length(field);
if (-1 == length) {
Py_DECREF(field);
return NULL;
}
if (length > 0) {
PyObject * pop = PyObject_GetAttrString(field, "pop");
assert(pop != NULL);
for (Py_ssize_t i = 0; i < length; ++i) {
PyObject * ret = PyObject_CallFunctionObjArgs(pop, NULL);
if (!ret) {
Py_DECREF(pop);
Py_DECREF(field);
return NULL;
}
Py_DECREF(ret);
}
Py_DECREF(pop);
}
if (ros_message->displacements.size > 0) {
// populating the array.array using the frombytes method
PyObject * frombytes = PyObject_GetAttrString(field, "frombytes");
assert(frombytes != NULL);
double * src = &(ros_message->displacements.data[0]);
PyObject * data = PyBytes_FromStringAndSize((const char *)src, ros_message->displacements.size * sizeof(double));
assert(data != NULL);
PyObject * ret = PyObject_CallFunctionObjArgs(frombytes, data, NULL);
Py_DECREF(data);
Py_DECREF(frombytes);
if (!ret) {
Py_DECREF(field);
return NULL;
}
Py_DECREF(ret);
}
Py_DECREF(field);
}
{ // velocities
PyObject * field = NULL;
field = PyObject_GetAttrString(_pymessage, "velocities");
if (!field) {
return NULL;
}
assert(field->ob_type != NULL);
assert(field->ob_type->tp_name != NULL);
assert(strcmp(field->ob_type->tp_name, "array.array") == 0);
// ensure that itemsize matches the sizeof of the ROS message field
PyObject * itemsize_attr = PyObject_GetAttrString(field, "itemsize");
assert(itemsize_attr != NULL);
size_t itemsize = PyLong_AsSize_t(itemsize_attr);
Py_DECREF(itemsize_attr);
if (itemsize != sizeof(double)) {
PyErr_SetString(PyExc_RuntimeError, "itemsize doesn't match expectation");
Py_DECREF(field);
return NULL;
}
// clear the array, poor approach to remove potential default values
Py_ssize_t length = PyObject_Length(field);
if (-1 == length) {
Py_DECREF(field);
return NULL;
}
if (length > 0) {
PyObject * pop = PyObject_GetAttrString(field, "pop");
assert(pop != NULL);
for (Py_ssize_t i = 0; i < length; ++i) {
PyObject * ret = PyObject_CallFunctionObjArgs(pop, NULL);
if (!ret) {
Py_DECREF(pop);
Py_DECREF(field);
return NULL;
}
Py_DECREF(ret);
}
Py_DECREF(pop);
}
if (ros_message->velocities.size > 0) {
// populating the array.array using the frombytes method
PyObject * frombytes = PyObject_GetAttrString(field, "frombytes");
assert(frombytes != NULL);
double * src = &(ros_message->velocities.data[0]);
PyObject * data = PyBytes_FromStringAndSize((const char *)src, ros_message->velocities.size * sizeof(double));
assert(data != NULL);
PyObject * ret = PyObject_CallFunctionObjArgs(frombytes, data, NULL);
Py_DECREF(data);
Py_DECREF(frombytes);
if (!ret) {
Py_DECREF(field);
return NULL;
}
Py_DECREF(ret);
}
Py_DECREF(field);
}
{ // duration
PyObject * field = NULL;
field = PyFloat_FromDouble(ros_message->duration);
{
int rc = PyObject_SetAttrString(_pymessage, "duration", field);
Py_DECREF(field);
if (rc) {
return NULL;
}
}
}
// ownership of _pymessage is transferred to the caller
return _pymessage;
}
| 12,528 | C | 31.125641 | 119 | 0.60728 |
Toni-SM/semu.robotics.ros2_bridge/src/semu.robotics.ros2_bridge/semu/robotics/ros2_bridge/packages/control_msgs/msg/_joint_jog.py | # generated from rosidl_generator_py/resource/_idl.py.em
# with input from control_msgs:msg/JointJog.idl
# generated code does not contain a copyright notice
# Import statements for member types
# Member 'displacements'
# Member 'velocities'
import array # noqa: E402, I100
import rosidl_parser.definition # noqa: E402, I100
class Metaclass_JointJog(type):
"""Metaclass of message 'JointJog'."""
_CREATE_ROS_MESSAGE = None
_CONVERT_FROM_PY = None
_CONVERT_TO_PY = None
_DESTROY_ROS_MESSAGE = None
_TYPE_SUPPORT = None
__constants = {
}
@classmethod
def __import_type_support__(cls):
try:
from rosidl_generator_py import import_type_support
module = import_type_support('control_msgs')
except ImportError:
import logging
import traceback
logger = logging.getLogger(
'control_msgs.msg.JointJog')
logger.debug(
'Failed to import needed modules for type support:\n' +
traceback.format_exc())
else:
cls._CREATE_ROS_MESSAGE = module.create_ros_message_msg__msg__joint_jog
cls._CONVERT_FROM_PY = module.convert_from_py_msg__msg__joint_jog
cls._CONVERT_TO_PY = module.convert_to_py_msg__msg__joint_jog
cls._TYPE_SUPPORT = module.type_support_msg__msg__joint_jog
cls._DESTROY_ROS_MESSAGE = module.destroy_ros_message_msg__msg__joint_jog
from std_msgs.msg import Header
if Header.__class__._TYPE_SUPPORT is None:
Header.__class__.__import_type_support__()
@classmethod
def __prepare__(cls, name, bases, **kwargs):
# list constant names here so that they appear in the help text of
# the message class under "Data and other attributes defined here:"
# as well as populate each message instance
return {
}
class JointJog(metaclass=Metaclass_JointJog):
"""Message class 'JointJog'."""
__slots__ = [
'_header',
'_joint_names',
'_displacements',
'_velocities',
'_duration',
]
_fields_and_field_types = {
'header': 'std_msgs/Header',
'joint_names': 'sequence<string>',
'displacements': 'sequence<double>',
'velocities': 'sequence<double>',
'duration': 'double',
}
SLOT_TYPES = (
rosidl_parser.definition.NamespacedType(['std_msgs', 'msg'], 'Header'), # noqa: E501
rosidl_parser.definition.UnboundedSequence(rosidl_parser.definition.UnboundedString()), # noqa: E501
rosidl_parser.definition.UnboundedSequence(rosidl_parser.definition.BasicType('double')), # noqa: E501
rosidl_parser.definition.UnboundedSequence(rosidl_parser.definition.BasicType('double')), # noqa: E501
rosidl_parser.definition.BasicType('double'), # noqa: E501
)
def __init__(self, **kwargs):
assert all('_' + key in self.__slots__ for key in kwargs.keys()), \
'Invalid arguments passed to constructor: %s' % \
', '.join(sorted(k for k in kwargs.keys() if '_' + k not in self.__slots__))
from std_msgs.msg import Header
self.header = kwargs.get('header', Header())
self.joint_names = kwargs.get('joint_names', [])
self.displacements = array.array('d', kwargs.get('displacements', []))
self.velocities = array.array('d', kwargs.get('velocities', []))
self.duration = kwargs.get('duration', float())
def __repr__(self):
typename = self.__class__.__module__.split('.')
typename.pop()
typename.append(self.__class__.__name__)
args = []
for s, t in zip(self.__slots__, self.SLOT_TYPES):
field = getattr(self, s)
fieldstr = repr(field)
# We use Python array type for fields that can be directly stored
# in them, and "normal" sequences for everything else. If it is
# a type that we store in an array, strip off the 'array' portion.
if (
isinstance(t, rosidl_parser.definition.AbstractSequence) and
isinstance(t.value_type, rosidl_parser.definition.BasicType) and
t.value_type.typename in ['float', 'double', 'int8', 'uint8', 'int16', 'uint16', 'int32', 'uint32', 'int64', 'uint64']
):
if len(field) == 0:
fieldstr = '[]'
else:
assert fieldstr.startswith('array(')
prefix = "array('X', "
suffix = ')'
fieldstr = fieldstr[len(prefix):-len(suffix)]
args.append(s[1:] + '=' + fieldstr)
return '%s(%s)' % ('.'.join(typename), ', '.join(args))
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
if self.header != other.header:
return False
if self.joint_names != other.joint_names:
return False
if self.displacements != other.displacements:
return False
if self.velocities != other.velocities:
return False
if self.duration != other.duration:
return False
return True
@classmethod
def get_fields_and_field_types(cls):
from copy import copy
return copy(cls._fields_and_field_types)
@property
def header(self):
"""Message field 'header'."""
return self._header
@header.setter
def header(self, value):
if __debug__:
from std_msgs.msg import Header
assert \
isinstance(value, Header), \
"The 'header' field must be a sub message of type 'Header'"
self._header = value
@property
def joint_names(self):
"""Message field 'joint_names'."""
return self._joint_names
@joint_names.setter
def joint_names(self, value):
if __debug__:
from collections.abc import Sequence
from collections.abc import Set
from collections import UserList
from collections import UserString
assert \
((isinstance(value, Sequence) or
isinstance(value, Set) or
isinstance(value, UserList)) and
not isinstance(value, str) and
not isinstance(value, UserString) and
all(isinstance(v, str) for v in value) and
True), \
"The 'joint_names' field must be a set or sequence and each value of type 'str'"
self._joint_names = value
@property
def displacements(self):
"""Message field 'displacements'."""
return self._displacements
@displacements.setter
def displacements(self, value):
if isinstance(value, array.array):
assert value.typecode == 'd', \
"The 'displacements' array.array() must have the type code of 'd'"
self._displacements = value
return
if __debug__:
from collections.abc import Sequence
from collections.abc import Set
from collections import UserList
from collections import UserString
assert \
((isinstance(value, Sequence) or
isinstance(value, Set) or
isinstance(value, UserList)) and
not isinstance(value, str) and
not isinstance(value, UserString) and
all(isinstance(v, float) for v in value) and
True), \
"The 'displacements' field must be a set or sequence and each value of type 'float'"
self._displacements = array.array('d', value)
@property
def velocities(self):
"""Message field 'velocities'."""
return self._velocities
@velocities.setter
def velocities(self, value):
if isinstance(value, array.array):
assert value.typecode == 'd', \
"The 'velocities' array.array() must have the type code of 'd'"
self._velocities = value
return
if __debug__:
from collections.abc import Sequence
from collections.abc import Set
from collections import UserList
from collections import UserString
assert \
((isinstance(value, Sequence) or
isinstance(value, Set) or
isinstance(value, UserList)) and
not isinstance(value, str) and
not isinstance(value, UserString) and
all(isinstance(v, float) for v in value) and
True), \
"The 'velocities' field must be a set or sequence and each value of type 'float'"
self._velocities = array.array('d', value)
@property
def duration(self):
"""Message field 'duration'."""
return self._duration
@duration.setter
def duration(self, value):
if __debug__:
assert \
isinstance(value, float), \
"The 'duration' field must be of type 'float'"
self._duration = value
| 9,270 | Python | 36.232932 | 134 | 0.565912 |
Toni-SM/semu.robotics.ros2_bridge/src/semu.robotics.ros2_bridge/semu/robotics/ros2_bridge/packages/add_on_msgs/srv/_set_prim_attribute.py | # generated from rosidl_generator_py/resource/_idl.py.em
# with input from add_on_msgs:srv/SetPrimAttribute.idl
# generated code does not contain a copyright notice
# Import statements for member types
import rosidl_parser.definition # noqa: E402, I100
class Metaclass_SetPrimAttribute_Request(type):
"""Metaclass of message 'SetPrimAttribute_Request'."""
_CREATE_ROS_MESSAGE = None
_CONVERT_FROM_PY = None
_CONVERT_TO_PY = None
_DESTROY_ROS_MESSAGE = None
_TYPE_SUPPORT = None
__constants = {
}
@classmethod
def __import_type_support__(cls):
try:
from rosidl_generator_py import import_type_support
module = import_type_support('add_on_msgs')
except ImportError:
import logging
import traceback
logger = logging.getLogger(
'add_on_msgs.srv.SetPrimAttribute_Request')
logger.debug(
'Failed to import needed modules for type support:\n' +
traceback.format_exc())
else:
cls._CREATE_ROS_MESSAGE = module.create_ros_message_msg__srv__set_prim_attribute__request
cls._CONVERT_FROM_PY = module.convert_from_py_msg__srv__set_prim_attribute__request
cls._CONVERT_TO_PY = module.convert_to_py_msg__srv__set_prim_attribute__request
cls._TYPE_SUPPORT = module.type_support_msg__srv__set_prim_attribute__request
cls._DESTROY_ROS_MESSAGE = module.destroy_ros_message_msg__srv__set_prim_attribute__request
@classmethod
def __prepare__(cls, name, bases, **kwargs):
# list constant names here so that they appear in the help text of
# the message class under "Data and other attributes defined here:"
# as well as populate each message instance
return {
}
class SetPrimAttribute_Request(metaclass=Metaclass_SetPrimAttribute_Request):
"""Message class 'SetPrimAttribute_Request'."""
__slots__ = [
'_path',
'_attribute',
'_value',
]
_fields_and_field_types = {
'path': 'string',
'attribute': 'string',
'value': 'string',
}
SLOT_TYPES = (
rosidl_parser.definition.UnboundedString(), # noqa: E501
rosidl_parser.definition.UnboundedString(), # noqa: E501
rosidl_parser.definition.UnboundedString(), # noqa: E501
)
def __init__(self, **kwargs):
assert all('_' + key in self.__slots__ for key in kwargs.keys()), \
'Invalid arguments passed to constructor: %s' % \
', '.join(sorted(k for k in kwargs.keys() if '_' + k not in self.__slots__))
self.path = kwargs.get('path', str())
self.attribute = kwargs.get('attribute', str())
self.value = kwargs.get('value', str())
def __repr__(self):
typename = self.__class__.__module__.split('.')
typename.pop()
typename.append(self.__class__.__name__)
args = []
for s, t in zip(self.__slots__, self.SLOT_TYPES):
field = getattr(self, s)
fieldstr = repr(field)
# We use Python array type for fields that can be directly stored
# in them, and "normal" sequences for everything else. If it is
# a type that we store in an array, strip off the 'array' portion.
if (
isinstance(t, rosidl_parser.definition.AbstractSequence) and
isinstance(t.value_type, rosidl_parser.definition.BasicType) and
t.value_type.typename in ['float', 'double', 'int8', 'uint8', 'int16', 'uint16', 'int32', 'uint32', 'int64', 'uint64']
):
if len(field) == 0:
fieldstr = '[]'
else:
assert fieldstr.startswith('array(')
prefix = "array('X', "
suffix = ')'
fieldstr = fieldstr[len(prefix):-len(suffix)]
args.append(s[1:] + '=' + fieldstr)
return '%s(%s)' % ('.'.join(typename), ', '.join(args))
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
if self.path != other.path:
return False
if self.attribute != other.attribute:
return False
if self.value != other.value:
return False
return True
@classmethod
def get_fields_and_field_types(cls):
from copy import copy
return copy(cls._fields_and_field_types)
@property
def path(self):
"""Message field 'path'."""
return self._path
@path.setter
def path(self, value):
if __debug__:
assert \
isinstance(value, str), \
"The 'path' field must be of type 'str'"
self._path = value
@property
def attribute(self):
"""Message field 'attribute'."""
return self._attribute
@attribute.setter
def attribute(self, value):
if __debug__:
assert \
isinstance(value, str), \
"The 'attribute' field must be of type 'str'"
self._attribute = value
@property
def value(self):
"""Message field 'value'."""
return self._value
@value.setter
def value(self, value):
if __debug__:
assert \
isinstance(value, str), \
"The 'value' field must be of type 'str'"
self._value = value
# Import statements for member types
# already imported above
# import rosidl_parser.definition
class Metaclass_SetPrimAttribute_Response(type):
"""Metaclass of message 'SetPrimAttribute_Response'."""
_CREATE_ROS_MESSAGE = None
_CONVERT_FROM_PY = None
_CONVERT_TO_PY = None
_DESTROY_ROS_MESSAGE = None
_TYPE_SUPPORT = None
__constants = {
}
@classmethod
def __import_type_support__(cls):
try:
from rosidl_generator_py import import_type_support
module = import_type_support('add_on_msgs')
except ImportError:
import logging
import traceback
logger = logging.getLogger(
'add_on_msgs.srv.SetPrimAttribute_Response')
logger.debug(
'Failed to import needed modules for type support:\n' +
traceback.format_exc())
else:
cls._CREATE_ROS_MESSAGE = module.create_ros_message_msg__srv__set_prim_attribute__response
cls._CONVERT_FROM_PY = module.convert_from_py_msg__srv__set_prim_attribute__response
cls._CONVERT_TO_PY = module.convert_to_py_msg__srv__set_prim_attribute__response
cls._TYPE_SUPPORT = module.type_support_msg__srv__set_prim_attribute__response
cls._DESTROY_ROS_MESSAGE = module.destroy_ros_message_msg__srv__set_prim_attribute__response
@classmethod
def __prepare__(cls, name, bases, **kwargs):
# list constant names here so that they appear in the help text of
# the message class under "Data and other attributes defined here:"
# as well as populate each message instance
return {
}
class SetPrimAttribute_Response(metaclass=Metaclass_SetPrimAttribute_Response):
"""Message class 'SetPrimAttribute_Response'."""
__slots__ = [
'_success',
'_message',
]
_fields_and_field_types = {
'success': 'boolean',
'message': 'string',
}
SLOT_TYPES = (
rosidl_parser.definition.BasicType('boolean'), # noqa: E501
rosidl_parser.definition.UnboundedString(), # noqa: E501
)
def __init__(self, **kwargs):
assert all('_' + key in self.__slots__ for key in kwargs.keys()), \
'Invalid arguments passed to constructor: %s' % \
', '.join(sorted(k for k in kwargs.keys() if '_' + k not in self.__slots__))
self.success = kwargs.get('success', bool())
self.message = kwargs.get('message', str())
def __repr__(self):
typename = self.__class__.__module__.split('.')
typename.pop()
typename.append(self.__class__.__name__)
args = []
for s, t in zip(self.__slots__, self.SLOT_TYPES):
field = getattr(self, s)
fieldstr = repr(field)
# We use Python array type for fields that can be directly stored
# in them, and "normal" sequences for everything else. If it is
# a type that we store in an array, strip off the 'array' portion.
if (
isinstance(t, rosidl_parser.definition.AbstractSequence) and
isinstance(t.value_type, rosidl_parser.definition.BasicType) and
t.value_type.typename in ['float', 'double', 'int8', 'uint8', 'int16', 'uint16', 'int32', 'uint32', 'int64', 'uint64']
):
if len(field) == 0:
fieldstr = '[]'
else:
assert fieldstr.startswith('array(')
prefix = "array('X', "
suffix = ')'
fieldstr = fieldstr[len(prefix):-len(suffix)]
args.append(s[1:] + '=' + fieldstr)
return '%s(%s)' % ('.'.join(typename), ', '.join(args))
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
if self.success != other.success:
return False
if self.message != other.message:
return False
return True
@classmethod
def get_fields_and_field_types(cls):
from copy import copy
return copy(cls._fields_and_field_types)
@property
def success(self):
"""Message field 'success'."""
return self._success
@success.setter
def success(self, value):
if __debug__:
assert \
isinstance(value, bool), \
"The 'success' field must be of type 'bool'"
self._success = value
@property
def message(self):
"""Message field 'message'."""
return self._message
@message.setter
def message(self, value):
if __debug__:
assert \
isinstance(value, str), \
"The 'message' field must be of type 'str'"
self._message = value
class Metaclass_SetPrimAttribute(type):
"""Metaclass of service 'SetPrimAttribute'."""
_TYPE_SUPPORT = None
@classmethod
def __import_type_support__(cls):
try:
from rosidl_generator_py import import_type_support
module = import_type_support('add_on_msgs')
except ImportError:
import logging
import traceback
logger = logging.getLogger(
'add_on_msgs.srv.SetPrimAttribute')
logger.debug(
'Failed to import needed modules for type support:\n' +
traceback.format_exc())
else:
cls._TYPE_SUPPORT = module.type_support_srv__srv__set_prim_attribute
from add_on_msgs.srv import _set_prim_attribute
if _set_prim_attribute.Metaclass_SetPrimAttribute_Request._TYPE_SUPPORT is None:
_set_prim_attribute.Metaclass_SetPrimAttribute_Request.__import_type_support__()
if _set_prim_attribute.Metaclass_SetPrimAttribute_Response._TYPE_SUPPORT is None:
_set_prim_attribute.Metaclass_SetPrimAttribute_Response.__import_type_support__()
class SetPrimAttribute(metaclass=Metaclass_SetPrimAttribute):
from add_on_msgs.srv._set_prim_attribute import SetPrimAttribute_Request as Request
from add_on_msgs.srv._set_prim_attribute import SetPrimAttribute_Response as Response
def __init__(self):
raise NotImplementedError('Service classes can not be instantiated')
| 11,863 | Python | 34.309524 | 134 | 0.573717 |
Toni-SM/semu.robotics.ros2_bridge/src/semu.robotics.ros2_bridge/semu/robotics/ros2_bridge/packages/add_on_msgs/srv/_get_prim_attributes_s.c | // generated from rosidl_generator_py/resource/_idl_support.c.em
// with input from add_on_msgs:srv/GetPrimAttributes.idl
// generated code does not contain a copyright notice
#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION
#include <Python.h>
#include <stdbool.h>
#ifndef _WIN32
# pragma GCC diagnostic push
# pragma GCC diagnostic ignored "-Wunused-function"
#endif
#include "numpy/ndarrayobject.h"
#ifndef _WIN32
# pragma GCC diagnostic pop
#endif
#include "rosidl_runtime_c/visibility_control.h"
#include "add_on_msgs/srv/detail/get_prim_attributes__struct.h"
#include "add_on_msgs/srv/detail/get_prim_attributes__functions.h"
#include "rosidl_runtime_c/string.h"
#include "rosidl_runtime_c/string_functions.h"
ROSIDL_GENERATOR_C_EXPORT
bool add_on_msgs__srv__get_prim_attributes__request__convert_from_py(PyObject * _pymsg, void * _ros_message)
{
// check that the passed message is of the expected Python class
{
char full_classname_dest[63];
{
char * class_name = NULL;
char * module_name = NULL;
{
PyObject * class_attr = PyObject_GetAttrString(_pymsg, "__class__");
if (class_attr) {
PyObject * name_attr = PyObject_GetAttrString(class_attr, "__name__");
if (name_attr) {
class_name = (char *)PyUnicode_1BYTE_DATA(name_attr);
Py_DECREF(name_attr);
}
PyObject * module_attr = PyObject_GetAttrString(class_attr, "__module__");
if (module_attr) {
module_name = (char *)PyUnicode_1BYTE_DATA(module_attr);
Py_DECREF(module_attr);
}
Py_DECREF(class_attr);
}
}
if (!class_name || !module_name) {
return false;
}
snprintf(full_classname_dest, sizeof(full_classname_dest), "%s.%s", module_name, class_name);
}
assert(strncmp("add_on_msgs.srv._get_prim_attributes.GetPrimAttributes_Request", full_classname_dest, 62) == 0);
}
add_on_msgs__srv__GetPrimAttributes_Request * ros_message = _ros_message;
{ // path
PyObject * field = PyObject_GetAttrString(_pymsg, "path");
if (!field) {
return false;
}
assert(PyUnicode_Check(field));
PyObject * encoded_field = PyUnicode_AsUTF8String(field);
if (!encoded_field) {
Py_DECREF(field);
return false;
}
rosidl_runtime_c__String__assign(&ros_message->path, PyBytes_AS_STRING(encoded_field));
Py_DECREF(encoded_field);
Py_DECREF(field);
}
return true;
}
ROSIDL_GENERATOR_C_EXPORT
PyObject * add_on_msgs__srv__get_prim_attributes__request__convert_to_py(void * raw_ros_message)
{
/* NOTE(esteve): Call constructor of GetPrimAttributes_Request */
PyObject * _pymessage = NULL;
{
PyObject * pymessage_module = PyImport_ImportModule("add_on_msgs.srv._get_prim_attributes");
assert(pymessage_module);
PyObject * pymessage_class = PyObject_GetAttrString(pymessage_module, "GetPrimAttributes_Request");
assert(pymessage_class);
Py_DECREF(pymessage_module);
_pymessage = PyObject_CallObject(pymessage_class, NULL);
Py_DECREF(pymessage_class);
if (!_pymessage) {
return NULL;
}
}
add_on_msgs__srv__GetPrimAttributes_Request * ros_message = (add_on_msgs__srv__GetPrimAttributes_Request *)raw_ros_message;
{ // path
PyObject * field = NULL;
field = PyUnicode_DecodeUTF8(
ros_message->path.data,
strlen(ros_message->path.data),
"strict");
if (!field) {
return NULL;
}
{
int rc = PyObject_SetAttrString(_pymessage, "path", field);
Py_DECREF(field);
if (rc) {
return NULL;
}
}
}
// ownership of _pymessage is transferred to the caller
return _pymessage;
}
#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION
// already included above
// #include <Python.h>
// already included above
// #include <stdbool.h>
// already included above
// #include "numpy/ndarrayobject.h"
// already included above
// #include "rosidl_runtime_c/visibility_control.h"
// already included above
// #include "add_on_msgs/srv/detail/get_prim_attributes__struct.h"
// already included above
// #include "add_on_msgs/srv/detail/get_prim_attributes__functions.h"
#include "rosidl_runtime_c/primitives_sequence.h"
#include "rosidl_runtime_c/primitives_sequence_functions.h"
// already included above
// #include "rosidl_runtime_c/string.h"
// already included above
// #include "rosidl_runtime_c/string_functions.h"
ROSIDL_GENERATOR_C_EXPORT
bool add_on_msgs__srv__get_prim_attributes__response__convert_from_py(PyObject * _pymsg, void * _ros_message)
{
// check that the passed message is of the expected Python class
{
char full_classname_dest[64];
{
char * class_name = NULL;
char * module_name = NULL;
{
PyObject * class_attr = PyObject_GetAttrString(_pymsg, "__class__");
if (class_attr) {
PyObject * name_attr = PyObject_GetAttrString(class_attr, "__name__");
if (name_attr) {
class_name = (char *)PyUnicode_1BYTE_DATA(name_attr);
Py_DECREF(name_attr);
}
PyObject * module_attr = PyObject_GetAttrString(class_attr, "__module__");
if (module_attr) {
module_name = (char *)PyUnicode_1BYTE_DATA(module_attr);
Py_DECREF(module_attr);
}
Py_DECREF(class_attr);
}
}
if (!class_name || !module_name) {
return false;
}
snprintf(full_classname_dest, sizeof(full_classname_dest), "%s.%s", module_name, class_name);
}
assert(strncmp("add_on_msgs.srv._get_prim_attributes.GetPrimAttributes_Response", full_classname_dest, 63) == 0);
}
add_on_msgs__srv__GetPrimAttributes_Response * ros_message = _ros_message;
{ // names
PyObject * field = PyObject_GetAttrString(_pymsg, "names");
if (!field) {
return false;
}
PyObject * seq_field = PySequence_Fast(field, "expected a sequence in 'names'");
if (!seq_field) {
Py_DECREF(field);
return false;
}
Py_ssize_t size = PySequence_Size(field);
if (-1 == size) {
Py_DECREF(seq_field);
Py_DECREF(field);
return false;
}
if (!rosidl_runtime_c__String__Sequence__init(&(ros_message->names), size)) {
PyErr_SetString(PyExc_RuntimeError, "unable to create String__Sequence ros_message");
Py_DECREF(seq_field);
Py_DECREF(field);
return false;
}
rosidl_runtime_c__String * dest = ros_message->names.data;
for (Py_ssize_t i = 0; i < size; ++i) {
PyObject * item = PySequence_Fast_GET_ITEM(seq_field, i);
if (!item) {
Py_DECREF(seq_field);
Py_DECREF(field);
return false;
}
assert(PyUnicode_Check(item));
PyObject * encoded_item = PyUnicode_AsUTF8String(item);
if (!encoded_item) {
Py_DECREF(seq_field);
Py_DECREF(field);
return false;
}
rosidl_runtime_c__String__assign(&dest[i], PyBytes_AS_STRING(encoded_item));
Py_DECREF(encoded_item);
}
Py_DECREF(seq_field);
Py_DECREF(field);
}
{ // displays
PyObject * field = PyObject_GetAttrString(_pymsg, "displays");
if (!field) {
return false;
}
PyObject * seq_field = PySequence_Fast(field, "expected a sequence in 'displays'");
if (!seq_field) {
Py_DECREF(field);
return false;
}
Py_ssize_t size = PySequence_Size(field);
if (-1 == size) {
Py_DECREF(seq_field);
Py_DECREF(field);
return false;
}
if (!rosidl_runtime_c__String__Sequence__init(&(ros_message->displays), size)) {
PyErr_SetString(PyExc_RuntimeError, "unable to create String__Sequence ros_message");
Py_DECREF(seq_field);
Py_DECREF(field);
return false;
}
rosidl_runtime_c__String * dest = ros_message->displays.data;
for (Py_ssize_t i = 0; i < size; ++i) {
PyObject * item = PySequence_Fast_GET_ITEM(seq_field, i);
if (!item) {
Py_DECREF(seq_field);
Py_DECREF(field);
return false;
}
assert(PyUnicode_Check(item));
PyObject * encoded_item = PyUnicode_AsUTF8String(item);
if (!encoded_item) {
Py_DECREF(seq_field);
Py_DECREF(field);
return false;
}
rosidl_runtime_c__String__assign(&dest[i], PyBytes_AS_STRING(encoded_item));
Py_DECREF(encoded_item);
}
Py_DECREF(seq_field);
Py_DECREF(field);
}
{ // types
PyObject * field = PyObject_GetAttrString(_pymsg, "types");
if (!field) {
return false;
}
PyObject * seq_field = PySequence_Fast(field, "expected a sequence in 'types'");
if (!seq_field) {
Py_DECREF(field);
return false;
}
Py_ssize_t size = PySequence_Size(field);
if (-1 == size) {
Py_DECREF(seq_field);
Py_DECREF(field);
return false;
}
if (!rosidl_runtime_c__String__Sequence__init(&(ros_message->types), size)) {
PyErr_SetString(PyExc_RuntimeError, "unable to create String__Sequence ros_message");
Py_DECREF(seq_field);
Py_DECREF(field);
return false;
}
rosidl_runtime_c__String * dest = ros_message->types.data;
for (Py_ssize_t i = 0; i < size; ++i) {
PyObject * item = PySequence_Fast_GET_ITEM(seq_field, i);
if (!item) {
Py_DECREF(seq_field);
Py_DECREF(field);
return false;
}
assert(PyUnicode_Check(item));
PyObject * encoded_item = PyUnicode_AsUTF8String(item);
if (!encoded_item) {
Py_DECREF(seq_field);
Py_DECREF(field);
return false;
}
rosidl_runtime_c__String__assign(&dest[i], PyBytes_AS_STRING(encoded_item));
Py_DECREF(encoded_item);
}
Py_DECREF(seq_field);
Py_DECREF(field);
}
{ // success
PyObject * field = PyObject_GetAttrString(_pymsg, "success");
if (!field) {
return false;
}
assert(PyBool_Check(field));
ros_message->success = (Py_True == field);
Py_DECREF(field);
}
{ // message
PyObject * field = PyObject_GetAttrString(_pymsg, "message");
if (!field) {
return false;
}
assert(PyUnicode_Check(field));
PyObject * encoded_field = PyUnicode_AsUTF8String(field);
if (!encoded_field) {
Py_DECREF(field);
return false;
}
rosidl_runtime_c__String__assign(&ros_message->message, PyBytes_AS_STRING(encoded_field));
Py_DECREF(encoded_field);
Py_DECREF(field);
}
return true;
}
ROSIDL_GENERATOR_C_EXPORT
PyObject * add_on_msgs__srv__get_prim_attributes__response__convert_to_py(void * raw_ros_message)
{
/* NOTE(esteve): Call constructor of GetPrimAttributes_Response */
PyObject * _pymessage = NULL;
{
PyObject * pymessage_module = PyImport_ImportModule("add_on_msgs.srv._get_prim_attributes");
assert(pymessage_module);
PyObject * pymessage_class = PyObject_GetAttrString(pymessage_module, "GetPrimAttributes_Response");
assert(pymessage_class);
Py_DECREF(pymessage_module);
_pymessage = PyObject_CallObject(pymessage_class, NULL);
Py_DECREF(pymessage_class);
if (!_pymessage) {
return NULL;
}
}
add_on_msgs__srv__GetPrimAttributes_Response * ros_message = (add_on_msgs__srv__GetPrimAttributes_Response *)raw_ros_message;
{ // names
PyObject * field = NULL;
size_t size = ros_message->names.size;
rosidl_runtime_c__String * src = ros_message->names.data;
field = PyList_New(size);
if (!field) {
return NULL;
}
for (size_t i = 0; i < size; ++i) {
PyObject * decoded_item = PyUnicode_DecodeUTF8(src[i].data, strlen(src[i].data), "strict");
if (!decoded_item) {
return NULL;
}
int rc = PyList_SetItem(field, i, decoded_item);
(void)rc;
assert(rc == 0);
}
assert(PySequence_Check(field));
{
int rc = PyObject_SetAttrString(_pymessage, "names", field);
Py_DECREF(field);
if (rc) {
return NULL;
}
}
}
{ // displays
PyObject * field = NULL;
size_t size = ros_message->displays.size;
rosidl_runtime_c__String * src = ros_message->displays.data;
field = PyList_New(size);
if (!field) {
return NULL;
}
for (size_t i = 0; i < size; ++i) {
PyObject * decoded_item = PyUnicode_DecodeUTF8(src[i].data, strlen(src[i].data), "strict");
if (!decoded_item) {
return NULL;
}
int rc = PyList_SetItem(field, i, decoded_item);
(void)rc;
assert(rc == 0);
}
assert(PySequence_Check(field));
{
int rc = PyObject_SetAttrString(_pymessage, "displays", field);
Py_DECREF(field);
if (rc) {
return NULL;
}
}
}
{ // types
PyObject * field = NULL;
size_t size = ros_message->types.size;
rosidl_runtime_c__String * src = ros_message->types.data;
field = PyList_New(size);
if (!field) {
return NULL;
}
for (size_t i = 0; i < size; ++i) {
PyObject * decoded_item = PyUnicode_DecodeUTF8(src[i].data, strlen(src[i].data), "strict");
if (!decoded_item) {
return NULL;
}
int rc = PyList_SetItem(field, i, decoded_item);
(void)rc;
assert(rc == 0);
}
assert(PySequence_Check(field));
{
int rc = PyObject_SetAttrString(_pymessage, "types", field);
Py_DECREF(field);
if (rc) {
return NULL;
}
}
}
{ // success
PyObject * field = NULL;
field = PyBool_FromLong(ros_message->success ? 1 : 0);
{
int rc = PyObject_SetAttrString(_pymessage, "success", field);
Py_DECREF(field);
if (rc) {
return NULL;
}
}
}
{ // message
PyObject * field = NULL;
field = PyUnicode_DecodeUTF8(
ros_message->message.data,
strlen(ros_message->message.data),
"strict");
if (!field) {
return NULL;
}
{
int rc = PyObject_SetAttrString(_pymessage, "message", field);
Py_DECREF(field);
if (rc) {
return NULL;
}
}
}
// ownership of _pymessage is transferred to the caller
return _pymessage;
}
| 14,105 | C | 30.002198 | 127 | 0.611273 |
Toni-SM/semu.robotics.ros2_bridge/src/semu.robotics.ros2_bridge/semu/robotics/ros2_bridge/packages/add_on_msgs/srv/_get_prim_attribute_s.c | // generated from rosidl_generator_py/resource/_idl_support.c.em
// with input from add_on_msgs:srv/GetPrimAttribute.idl
// generated code does not contain a copyright notice
#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION
#include <Python.h>
#include <stdbool.h>
#ifndef _WIN32
# pragma GCC diagnostic push
# pragma GCC diagnostic ignored "-Wunused-function"
#endif
#include "numpy/ndarrayobject.h"
#ifndef _WIN32
# pragma GCC diagnostic pop
#endif
#include "rosidl_runtime_c/visibility_control.h"
#include "add_on_msgs/srv/detail/get_prim_attribute__struct.h"
#include "add_on_msgs/srv/detail/get_prim_attribute__functions.h"
#include "rosidl_runtime_c/string.h"
#include "rosidl_runtime_c/string_functions.h"
ROSIDL_GENERATOR_C_EXPORT
bool add_on_msgs__srv__get_prim_attribute__request__convert_from_py(PyObject * _pymsg, void * _ros_message)
{
// check that the passed message is of the expected Python class
{
char full_classname_dest[61];
{
char * class_name = NULL;
char * module_name = NULL;
{
PyObject * class_attr = PyObject_GetAttrString(_pymsg, "__class__");
if (class_attr) {
PyObject * name_attr = PyObject_GetAttrString(class_attr, "__name__");
if (name_attr) {
class_name = (char *)PyUnicode_1BYTE_DATA(name_attr);
Py_DECREF(name_attr);
}
PyObject * module_attr = PyObject_GetAttrString(class_attr, "__module__");
if (module_attr) {
module_name = (char *)PyUnicode_1BYTE_DATA(module_attr);
Py_DECREF(module_attr);
}
Py_DECREF(class_attr);
}
}
if (!class_name || !module_name) {
return false;
}
snprintf(full_classname_dest, sizeof(full_classname_dest), "%s.%s", module_name, class_name);
}
assert(strncmp("add_on_msgs.srv._get_prim_attribute.GetPrimAttribute_Request", full_classname_dest, 60) == 0);
}
add_on_msgs__srv__GetPrimAttribute_Request * ros_message = _ros_message;
{ // path
PyObject * field = PyObject_GetAttrString(_pymsg, "path");
if (!field) {
return false;
}
assert(PyUnicode_Check(field));
PyObject * encoded_field = PyUnicode_AsUTF8String(field);
if (!encoded_field) {
Py_DECREF(field);
return false;
}
rosidl_runtime_c__String__assign(&ros_message->path, PyBytes_AS_STRING(encoded_field));
Py_DECREF(encoded_field);
Py_DECREF(field);
}
{ // attribute
PyObject * field = PyObject_GetAttrString(_pymsg, "attribute");
if (!field) {
return false;
}
assert(PyUnicode_Check(field));
PyObject * encoded_field = PyUnicode_AsUTF8String(field);
if (!encoded_field) {
Py_DECREF(field);
return false;
}
rosidl_runtime_c__String__assign(&ros_message->attribute, PyBytes_AS_STRING(encoded_field));
Py_DECREF(encoded_field);
Py_DECREF(field);
}
return true;
}
ROSIDL_GENERATOR_C_EXPORT
PyObject * add_on_msgs__srv__get_prim_attribute__request__convert_to_py(void * raw_ros_message)
{
/* NOTE(esteve): Call constructor of GetPrimAttribute_Request */
PyObject * _pymessage = NULL;
{
PyObject * pymessage_module = PyImport_ImportModule("add_on_msgs.srv._get_prim_attribute");
assert(pymessage_module);
PyObject * pymessage_class = PyObject_GetAttrString(pymessage_module, "GetPrimAttribute_Request");
assert(pymessage_class);
Py_DECREF(pymessage_module);
_pymessage = PyObject_CallObject(pymessage_class, NULL);
Py_DECREF(pymessage_class);
if (!_pymessage) {
return NULL;
}
}
add_on_msgs__srv__GetPrimAttribute_Request * ros_message = (add_on_msgs__srv__GetPrimAttribute_Request *)raw_ros_message;
{ // path
PyObject * field = NULL;
field = PyUnicode_DecodeUTF8(
ros_message->path.data,
strlen(ros_message->path.data),
"strict");
if (!field) {
return NULL;
}
{
int rc = PyObject_SetAttrString(_pymessage, "path", field);
Py_DECREF(field);
if (rc) {
return NULL;
}
}
}
{ // attribute
PyObject * field = NULL;
field = PyUnicode_DecodeUTF8(
ros_message->attribute.data,
strlen(ros_message->attribute.data),
"strict");
if (!field) {
return NULL;
}
{
int rc = PyObject_SetAttrString(_pymessage, "attribute", field);
Py_DECREF(field);
if (rc) {
return NULL;
}
}
}
// ownership of _pymessage is transferred to the caller
return _pymessage;
}
#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION
// already included above
// #include <Python.h>
// already included above
// #include <stdbool.h>
// already included above
// #include "numpy/ndarrayobject.h"
// already included above
// #include "rosidl_runtime_c/visibility_control.h"
// already included above
// #include "add_on_msgs/srv/detail/get_prim_attribute__struct.h"
// already included above
// #include "add_on_msgs/srv/detail/get_prim_attribute__functions.h"
// already included above
// #include "rosidl_runtime_c/string.h"
// already included above
// #include "rosidl_runtime_c/string_functions.h"
ROSIDL_GENERATOR_C_EXPORT
bool add_on_msgs__srv__get_prim_attribute__response__convert_from_py(PyObject * _pymsg, void * _ros_message)
{
// check that the passed message is of the expected Python class
{
char full_classname_dest[62];
{
char * class_name = NULL;
char * module_name = NULL;
{
PyObject * class_attr = PyObject_GetAttrString(_pymsg, "__class__");
if (class_attr) {
PyObject * name_attr = PyObject_GetAttrString(class_attr, "__name__");
if (name_attr) {
class_name = (char *)PyUnicode_1BYTE_DATA(name_attr);
Py_DECREF(name_attr);
}
PyObject * module_attr = PyObject_GetAttrString(class_attr, "__module__");
if (module_attr) {
module_name = (char *)PyUnicode_1BYTE_DATA(module_attr);
Py_DECREF(module_attr);
}
Py_DECREF(class_attr);
}
}
if (!class_name || !module_name) {
return false;
}
snprintf(full_classname_dest, sizeof(full_classname_dest), "%s.%s", module_name, class_name);
}
assert(strncmp("add_on_msgs.srv._get_prim_attribute.GetPrimAttribute_Response", full_classname_dest, 61) == 0);
}
add_on_msgs__srv__GetPrimAttribute_Response * ros_message = _ros_message;
{ // value
PyObject * field = PyObject_GetAttrString(_pymsg, "value");
if (!field) {
return false;
}
assert(PyUnicode_Check(field));
PyObject * encoded_field = PyUnicode_AsUTF8String(field);
if (!encoded_field) {
Py_DECREF(field);
return false;
}
rosidl_runtime_c__String__assign(&ros_message->value, PyBytes_AS_STRING(encoded_field));
Py_DECREF(encoded_field);
Py_DECREF(field);
}
{ // type
PyObject * field = PyObject_GetAttrString(_pymsg, "type");
if (!field) {
return false;
}
assert(PyUnicode_Check(field));
PyObject * encoded_field = PyUnicode_AsUTF8String(field);
if (!encoded_field) {
Py_DECREF(field);
return false;
}
rosidl_runtime_c__String__assign(&ros_message->type, PyBytes_AS_STRING(encoded_field));
Py_DECREF(encoded_field);
Py_DECREF(field);
}
{ // success
PyObject * field = PyObject_GetAttrString(_pymsg, "success");
if (!field) {
return false;
}
assert(PyBool_Check(field));
ros_message->success = (Py_True == field);
Py_DECREF(field);
}
{ // message
PyObject * field = PyObject_GetAttrString(_pymsg, "message");
if (!field) {
return false;
}
assert(PyUnicode_Check(field));
PyObject * encoded_field = PyUnicode_AsUTF8String(field);
if (!encoded_field) {
Py_DECREF(field);
return false;
}
rosidl_runtime_c__String__assign(&ros_message->message, PyBytes_AS_STRING(encoded_field));
Py_DECREF(encoded_field);
Py_DECREF(field);
}
return true;
}
ROSIDL_GENERATOR_C_EXPORT
PyObject * add_on_msgs__srv__get_prim_attribute__response__convert_to_py(void * raw_ros_message)
{
/* NOTE(esteve): Call constructor of GetPrimAttribute_Response */
PyObject * _pymessage = NULL;
{
PyObject * pymessage_module = PyImport_ImportModule("add_on_msgs.srv._get_prim_attribute");
assert(pymessage_module);
PyObject * pymessage_class = PyObject_GetAttrString(pymessage_module, "GetPrimAttribute_Response");
assert(pymessage_class);
Py_DECREF(pymessage_module);
_pymessage = PyObject_CallObject(pymessage_class, NULL);
Py_DECREF(pymessage_class);
if (!_pymessage) {
return NULL;
}
}
add_on_msgs__srv__GetPrimAttribute_Response * ros_message = (add_on_msgs__srv__GetPrimAttribute_Response *)raw_ros_message;
{ // value
PyObject * field = NULL;
field = PyUnicode_DecodeUTF8(
ros_message->value.data,
strlen(ros_message->value.data),
"strict");
if (!field) {
return NULL;
}
{
int rc = PyObject_SetAttrString(_pymessage, "value", field);
Py_DECREF(field);
if (rc) {
return NULL;
}
}
}
{ // type
PyObject * field = NULL;
field = PyUnicode_DecodeUTF8(
ros_message->type.data,
strlen(ros_message->type.data),
"strict");
if (!field) {
return NULL;
}
{
int rc = PyObject_SetAttrString(_pymessage, "type", field);
Py_DECREF(field);
if (rc) {
return NULL;
}
}
}
{ // success
PyObject * field = NULL;
field = PyBool_FromLong(ros_message->success ? 1 : 0);
{
int rc = PyObject_SetAttrString(_pymessage, "success", field);
Py_DECREF(field);
if (rc) {
return NULL;
}
}
}
{ // message
PyObject * field = NULL;
field = PyUnicode_DecodeUTF8(
ros_message->message.data,
strlen(ros_message->message.data),
"strict");
if (!field) {
return NULL;
}
{
int rc = PyObject_SetAttrString(_pymessage, "message", field);
Py_DECREF(field);
if (rc) {
return NULL;
}
}
}
// ownership of _pymessage is transferred to the caller
return _pymessage;
}
| 10,253 | C | 28.982456 | 125 | 0.626158 |
Toni-SM/semu.robotics.ros2_bridge/src/semu.robotics.ros2_bridge/semu/robotics/ros2_bridge/packages/add_on_msgs/srv/_set_prim_attribute_s.c | // generated from rosidl_generator_py/resource/_idl_support.c.em
// with input from add_on_msgs:srv/SetPrimAttribute.idl
// generated code does not contain a copyright notice
#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION
#include <Python.h>
#include <stdbool.h>
#ifndef _WIN32
# pragma GCC diagnostic push
# pragma GCC diagnostic ignored "-Wunused-function"
#endif
#include "numpy/ndarrayobject.h"
#ifndef _WIN32
# pragma GCC diagnostic pop
#endif
#include "rosidl_runtime_c/visibility_control.h"
#include "add_on_msgs/srv/detail/set_prim_attribute__struct.h"
#include "add_on_msgs/srv/detail/set_prim_attribute__functions.h"
#include "rosidl_runtime_c/string.h"
#include "rosidl_runtime_c/string_functions.h"
ROSIDL_GENERATOR_C_EXPORT
bool add_on_msgs__srv__set_prim_attribute__request__convert_from_py(PyObject * _pymsg, void * _ros_message)
{
// check that the passed message is of the expected Python class
{
char full_classname_dest[61];
{
char * class_name = NULL;
char * module_name = NULL;
{
PyObject * class_attr = PyObject_GetAttrString(_pymsg, "__class__");
if (class_attr) {
PyObject * name_attr = PyObject_GetAttrString(class_attr, "__name__");
if (name_attr) {
class_name = (char *)PyUnicode_1BYTE_DATA(name_attr);
Py_DECREF(name_attr);
}
PyObject * module_attr = PyObject_GetAttrString(class_attr, "__module__");
if (module_attr) {
module_name = (char *)PyUnicode_1BYTE_DATA(module_attr);
Py_DECREF(module_attr);
}
Py_DECREF(class_attr);
}
}
if (!class_name || !module_name) {
return false;
}
snprintf(full_classname_dest, sizeof(full_classname_dest), "%s.%s", module_name, class_name);
}
assert(strncmp("add_on_msgs.srv._set_prim_attribute.SetPrimAttribute_Request", full_classname_dest, 60) == 0);
}
add_on_msgs__srv__SetPrimAttribute_Request * ros_message = _ros_message;
{ // path
PyObject * field = PyObject_GetAttrString(_pymsg, "path");
if (!field) {
return false;
}
assert(PyUnicode_Check(field));
PyObject * encoded_field = PyUnicode_AsUTF8String(field);
if (!encoded_field) {
Py_DECREF(field);
return false;
}
rosidl_runtime_c__String__assign(&ros_message->path, PyBytes_AS_STRING(encoded_field));
Py_DECREF(encoded_field);
Py_DECREF(field);
}
{ // attribute
PyObject * field = PyObject_GetAttrString(_pymsg, "attribute");
if (!field) {
return false;
}
assert(PyUnicode_Check(field));
PyObject * encoded_field = PyUnicode_AsUTF8String(field);
if (!encoded_field) {
Py_DECREF(field);
return false;
}
rosidl_runtime_c__String__assign(&ros_message->attribute, PyBytes_AS_STRING(encoded_field));
Py_DECREF(encoded_field);
Py_DECREF(field);
}
{ // value
PyObject * field = PyObject_GetAttrString(_pymsg, "value");
if (!field) {
return false;
}
assert(PyUnicode_Check(field));
PyObject * encoded_field = PyUnicode_AsUTF8String(field);
if (!encoded_field) {
Py_DECREF(field);
return false;
}
rosidl_runtime_c__String__assign(&ros_message->value, PyBytes_AS_STRING(encoded_field));
Py_DECREF(encoded_field);
Py_DECREF(field);
}
return true;
}
ROSIDL_GENERATOR_C_EXPORT
PyObject * add_on_msgs__srv__set_prim_attribute__request__convert_to_py(void * raw_ros_message)
{
/* NOTE(esteve): Call constructor of SetPrimAttribute_Request */
PyObject * _pymessage = NULL;
{
PyObject * pymessage_module = PyImport_ImportModule("add_on_msgs.srv._set_prim_attribute");
assert(pymessage_module);
PyObject * pymessage_class = PyObject_GetAttrString(pymessage_module, "SetPrimAttribute_Request");
assert(pymessage_class);
Py_DECREF(pymessage_module);
_pymessage = PyObject_CallObject(pymessage_class, NULL);
Py_DECREF(pymessage_class);
if (!_pymessage) {
return NULL;
}
}
add_on_msgs__srv__SetPrimAttribute_Request * ros_message = (add_on_msgs__srv__SetPrimAttribute_Request *)raw_ros_message;
{ // path
PyObject * field = NULL;
field = PyUnicode_DecodeUTF8(
ros_message->path.data,
strlen(ros_message->path.data),
"strict");
if (!field) {
return NULL;
}
{
int rc = PyObject_SetAttrString(_pymessage, "path", field);
Py_DECREF(field);
if (rc) {
return NULL;
}
}
}
{ // attribute
PyObject * field = NULL;
field = PyUnicode_DecodeUTF8(
ros_message->attribute.data,
strlen(ros_message->attribute.data),
"strict");
if (!field) {
return NULL;
}
{
int rc = PyObject_SetAttrString(_pymessage, "attribute", field);
Py_DECREF(field);
if (rc) {
return NULL;
}
}
}
{ // value
PyObject * field = NULL;
field = PyUnicode_DecodeUTF8(
ros_message->value.data,
strlen(ros_message->value.data),
"strict");
if (!field) {
return NULL;
}
{
int rc = PyObject_SetAttrString(_pymessage, "value", field);
Py_DECREF(field);
if (rc) {
return NULL;
}
}
}
// ownership of _pymessage is transferred to the caller
return _pymessage;
}
#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION
// already included above
// #include <Python.h>
// already included above
// #include <stdbool.h>
// already included above
// #include "numpy/ndarrayobject.h"
// already included above
// #include "rosidl_runtime_c/visibility_control.h"
// already included above
// #include "add_on_msgs/srv/detail/set_prim_attribute__struct.h"
// already included above
// #include "add_on_msgs/srv/detail/set_prim_attribute__functions.h"
// already included above
// #include "rosidl_runtime_c/string.h"
// already included above
// #include "rosidl_runtime_c/string_functions.h"
ROSIDL_GENERATOR_C_EXPORT
bool add_on_msgs__srv__set_prim_attribute__response__convert_from_py(PyObject * _pymsg, void * _ros_message)
{
// check that the passed message is of the expected Python class
{
char full_classname_dest[62];
{
char * class_name = NULL;
char * module_name = NULL;
{
PyObject * class_attr = PyObject_GetAttrString(_pymsg, "__class__");
if (class_attr) {
PyObject * name_attr = PyObject_GetAttrString(class_attr, "__name__");
if (name_attr) {
class_name = (char *)PyUnicode_1BYTE_DATA(name_attr);
Py_DECREF(name_attr);
}
PyObject * module_attr = PyObject_GetAttrString(class_attr, "__module__");
if (module_attr) {
module_name = (char *)PyUnicode_1BYTE_DATA(module_attr);
Py_DECREF(module_attr);
}
Py_DECREF(class_attr);
}
}
if (!class_name || !module_name) {
return false;
}
snprintf(full_classname_dest, sizeof(full_classname_dest), "%s.%s", module_name, class_name);
}
assert(strncmp("add_on_msgs.srv._set_prim_attribute.SetPrimAttribute_Response", full_classname_dest, 61) == 0);
}
add_on_msgs__srv__SetPrimAttribute_Response * ros_message = _ros_message;
{ // success
PyObject * field = PyObject_GetAttrString(_pymsg, "success");
if (!field) {
return false;
}
assert(PyBool_Check(field));
ros_message->success = (Py_True == field);
Py_DECREF(field);
}
{ // message
PyObject * field = PyObject_GetAttrString(_pymsg, "message");
if (!field) {
return false;
}
assert(PyUnicode_Check(field));
PyObject * encoded_field = PyUnicode_AsUTF8String(field);
if (!encoded_field) {
Py_DECREF(field);
return false;
}
rosidl_runtime_c__String__assign(&ros_message->message, PyBytes_AS_STRING(encoded_field));
Py_DECREF(encoded_field);
Py_DECREF(field);
}
return true;
}
ROSIDL_GENERATOR_C_EXPORT
PyObject * add_on_msgs__srv__set_prim_attribute__response__convert_to_py(void * raw_ros_message)
{
/* NOTE(esteve): Call constructor of SetPrimAttribute_Response */
PyObject * _pymessage = NULL;
{
PyObject * pymessage_module = PyImport_ImportModule("add_on_msgs.srv._set_prim_attribute");
assert(pymessage_module);
PyObject * pymessage_class = PyObject_GetAttrString(pymessage_module, "SetPrimAttribute_Response");
assert(pymessage_class);
Py_DECREF(pymessage_module);
_pymessage = PyObject_CallObject(pymessage_class, NULL);
Py_DECREF(pymessage_class);
if (!_pymessage) {
return NULL;
}
}
add_on_msgs__srv__SetPrimAttribute_Response * ros_message = (add_on_msgs__srv__SetPrimAttribute_Response *)raw_ros_message;
{ // success
PyObject * field = NULL;
field = PyBool_FromLong(ros_message->success ? 1 : 0);
{
int rc = PyObject_SetAttrString(_pymessage, "success", field);
Py_DECREF(field);
if (rc) {
return NULL;
}
}
}
{ // message
PyObject * field = NULL;
field = PyUnicode_DecodeUTF8(
ros_message->message.data,
strlen(ros_message->message.data),
"strict");
if (!field) {
return NULL;
}
{
int rc = PyObject_SetAttrString(_pymessage, "message", field);
Py_DECREF(field);
if (rc) {
return NULL;
}
}
}
// ownership of _pymessage is transferred to the caller
return _pymessage;
}
| 9,456 | C | 29.506452 | 125 | 0.630816 |
Toni-SM/semu.robotics.ros2_bridge/src/semu.robotics.ros2_bridge/semu/robotics/ros2_bridge/packages/add_on_msgs/srv/__init__.py | from add_on_msgs.srv._get_prim_attribute import GetPrimAttribute # noqa: F401
from add_on_msgs.srv._get_prim_attributes import GetPrimAttributes # noqa: F401
from add_on_msgs.srv._get_prims import GetPrims # noqa: F401
from add_on_msgs.srv._set_prim_attribute import SetPrimAttribute # noqa: F401
| 301 | Python | 59.399988 | 80 | 0.777409 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.