git commit -m "first commit"

This commit is contained in:
2026-05-28 10:29:58 +07:00
commit 167c52aeb6
2048 changed files with 740251 additions and 0 deletions

View File

@@ -0,0 +1,52 @@
Change history
==============
1.0.6 (2017-04-04)
------------------
* Remove Python ``install_requires`` option.
* Fix minor catkin lint issues.
1.0.5 (2015-04-17)
------------------
* Alter C++ unique_id functions to work in multiple cpp files (`#7`_).
1.0.4 (2014-04-30)
------------------
1.0.3 (2013-07-24)
------------------
* Make unit tests conditional on ``CATKIN_ENABLE_TESTING``.
1.0.2 (2013-07-18)
-------------------
1.0.1 (2013-03-25)
-------------------
* Fix catkin Python install problem (`#4`_).
1.0.0 (2013-03-18)
-------------------
* Hydro release.
* Convert to catkin (`#1`_).
0.9.0 (2013-01-03)
------------------
* Initial release to Groovy.
* Add support for C++ interface using boost uuid package.
0.8.0 (2012-07-19)
------------------
* Initial release to Fuerte.
* Supports Python interface based on standard uuid package, but no
C++ API yet.
.. _`#1`: https://github.com/ros-geographic-info/unique_identifier/issues/1
.. _`#4`: https://github.com/ros-geographic-info/unique_identifier/issues/4
.. _`#7`: https://github.com/ros-geographic-info/unique_identifier/issues/7

View File

@@ -0,0 +1,19 @@
cmake_minimum_required(VERSION 2.8.3)
project(unique_id)
find_package(catkin REQUIRED COMPONENTS roscpp rospy uuid_msgs)
find_package(Boost REQUIRED)
include_directories(include ${catkin_INCLUDE_DIRS})
catkin_python_setup()
catkin_package(INCLUDE_DIRS include
CATKIN_DEPENDS uuid_msgs
DEPENDS Boost)
install(DIRECTORY include/${PROJECT_NAME}/
DESTINATION ${CATKIN_PACKAGE_INCLUDE_DESTINATION})
# unit tests
if (CATKIN_ENABLE_TESTING)
add_subdirectory(tests)
endif()

View File

@@ -0,0 +1,246 @@
# -*- coding: utf-8 -*-
#
# unique_id documentation build configuration file, created by
# sphinx-quickstart on Wed Apr 25 16:01:20 2012.
#
# This file is execfile()d with the current directory set to its containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.
import sys, os
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
#sys.path.insert(0, os.path.abspath('.'))
# -- General configuration -----------------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here.
#needs_sphinx = '1.0'
# Add any Sphinx extension module names here, as strings. They can be extensions
# coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
extensions = ['sphinx.ext.autodoc', 'sphinx.ext.intersphinx', 'sphinx.ext.todo', 'sphinx.ext.viewcode']
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# The suffix of source filenames.
source_suffix = '.rst'
# The encoding of source files.
#source_encoding = 'utf-8-sig'
# The master toctree document.
master_doc = 'index'
# General information about the project.
project = u'unique_id'
copyright = u'2012, Jack O\'Quin'
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
version = '0.9'
# The full version, including alpha/beta/rc tags.
release = '0.9.0'
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#language = None
# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
#today = ''
# Else, today_fmt is used as the format for a strftime call.
#today_fmt = '%B %d, %Y'
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
exclude_patterns = ['_build']
# The reST default role (used for this markup: `text`) to use for all documents.
#default_role = None
# If true, '()' will be appended to :func: etc. cross-reference text.
#add_function_parentheses = True
# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
#add_module_names = True
# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
#show_authors = False
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
# A list of ignored prefixes for module index sorting.
#modindex_common_prefix = []
# -- Options for HTML output ---------------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
html_theme = 'default'
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
#html_theme_options = {}
# Add any paths that contain custom themes here, relative to this directory.
#html_theme_path = []
# The name for this set of Sphinx documents. If None, it defaults to
# "<project> v<release> documentation".
#html_title = None
# A shorter title for the navigation bar. Default is the same as html_title.
#html_short_title = None
# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
#html_logo = None
# The name of an image file (within the static path) to use as favicon of the
# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
#html_favicon = None
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = []
# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
# using the given strftime format.
#html_last_updated_fmt = '%b %d, %Y'
# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
#html_use_smartypants = True
# Custom sidebar templates, maps document names to template names.
#html_sidebars = {}
# Additional templates that should be rendered to pages, maps page names to
# template names.
#html_additional_pages = {}
# If false, no module index is generated.
#html_domain_indices = True
# If false, no index is generated.
#html_use_index = True
# If true, the index is split into individual pages for each letter.
#html_split_index = False
# If true, links to the reST sources are added to the pages.
#html_show_sourcelink = True
# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
#html_show_sphinx = True
# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
#html_show_copyright = True
# If true, an OpenSearch description file will be output, and all pages will
# contain a <link> tag referring to it. The value of this option must be the
# base URL from which the finished HTML is served.
#html_use_opensearch = ''
# This is the file name suffix for HTML files (e.g. ".xhtml").
#html_file_suffix = None
# Output file base name for HTML help builder.
htmlhelp_basename = 'unique_iddoc'
# -- Options for LaTeX output --------------------------------------------------
latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
#'papersize': 'letterpaper',
# The font size ('10pt', '11pt' or '12pt').
#'pointsize': '10pt',
# Additional stuff for the LaTeX preamble.
#'preamble': '',
}
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title, author, documentclass [howto/manual]).
latex_documents = [
('index', 'unique_id.tex', u'ROS support for universally unique identifiers.',
u'Jack O\'Quin', 'manual'),
]
# The name of an image file (relative to this directory) to place at the top of
# the title page.
#latex_logo = None
# For "manual" documents, if this is true, then toplevel headings are parts,
# not chapters.
#latex_use_parts = False
# If true, show page references after internal links.
#latex_show_pagerefs = False
# If true, show URL addresses after external links.
#latex_show_urls = False
# Documents to append as an appendix to all manuals.
#latex_appendices = []
# If false, no module index is generated.
#latex_domain_indices = True
# -- Options for manual page output --------------------------------------------
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
('index', 'unique_id', u'ROS support for universally unique identifiers.',
[u'Jack O\'Quin'], 1)
]
# If true, show URL addresses after external links.
#man_show_urls = False
# -- Options for Texinfo output ------------------------------------------------
# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
('index', 'unique_id', u'unique_id Documentation',
u'Jack O\'Quin', 'unique_id', 'ROS support for universally unique identifiers.',
'Miscellaneous'),
]
# Documents to append as an appendix to all manuals.
#texinfo_appendices = []
# If false, no module index is generated.
#texinfo_domain_indices = True
# How to display URL addresses: 'footnote', 'no', or 'inline'.
#texinfo_show_urls = 'footnote'
# Example configuration for intersphinx: refer to the Python standard library.
intersphinx_mapping = {'http://docs.python.org/': None}

View File

@@ -0,0 +1,115 @@
/* -*- mode: C++ -*- */
/*********************************************************************
* Software License Agreement (BSD License)
*
* Copyright (C) 2012 Jack O'Quin
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of the author nor other contributors may be
* used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*********************************************************************/
#ifndef _IMPL_UNIQUE_ID_H_
#define _IMPL_UNIQUE_ID_H_ 1
/** @file
@brief Private implementation details for C++ unique_id interface.
@author Jack O'Quin
*/
#include <ros/ros.h>
#include <boost/uuid/uuid_generators.hpp>
namespace unique_id
{
/** @brief C++ namespace for private implementation details. */
namespace impl
{
/* Instantiate boost string UUID generator. */
static boost::uuids::string_generator genString;
/* Instantiate boost random UUID generator. */
static boost::uuids::random_generator genRandom;
/* RFC 4122 namespace for URL identifiers. */
static const std::string url_namespace =
"6ba7b811-9dad-11d1-80b4-00c04fd430c8";
/* RFC 4122 UUID for URL identifiers. */
static const boost::uuids::uuid url_namespace_uuid =
genString(url_namespace);
/* Instantiate boost URL name UUID generator. */
static boost::uuids::name_generator genURL(url_namespace_uuid);
/* Generate RFC4122 Version 1 Time-Based UUID */
static boost::uuids::uuid genTime(ros::Time uuid_time, uint64_t hw_addr)
{
// Get no. of 100 nanosecond intervals since 00:00:00 October 15, 1582
// The RFC4122 standard only requires the least significant 60 bits for timestamp
// No. of 100 ns intervals between 00:00:00 Oct 15, 1582 and 00:00:00 Jan 1, 1970
uint64_t offset = 122192928000000000;
uint64_t num_hundred_epoch = static_cast<uint64_t>(uuid_time.sec) / (1e-9 * 100) +
static_cast<uint64_t>(uuid_time.nsec) / 100;
// Note: Adding offset in the same line as the above statement may yield incorrect
// values on some systems
uint64_t num_hundred_rfc = num_hundred_epoch + offset;
uint32_t time_low = static_cast<uint32_t>(num_hundred_rfc);
uint16_t time_mid = static_cast<uint16_t>(num_hundred_rfc >> 32);
uint16_t version = 0x1000;
uint16_t time_hi_and_version = static_cast<uint16_t>(num_hundred_rfc >> (32 + 16)) | version;
// Generate Clock Sequence ID based on random number
uint16_t clock_seq_and_reserved = (rand() % (1 << 14)) | 0x8000;
boost::uuids::uuid uu = {
static_cast<uint8_t>(time_low >> 24), static_cast<uint8_t>(time_low >> 16),
static_cast<uint8_t>(time_low >> 8), static_cast<uint8_t>(time_low),
static_cast<uint8_t>(time_mid >> 8), static_cast<uint8_t>(time_mid),
static_cast<uint8_t>(time_hi_and_version >> 8),
static_cast<uint8_t>(time_hi_and_version),
static_cast<uint8_t>(clock_seq_and_reserved >> 8),
static_cast<uint8_t>(clock_seq_and_reserved),
static_cast<uint8_t>(hw_addr >> 40), static_cast<uint8_t>(hw_addr >> 32),
static_cast<uint8_t>(hw_addr >> 24), static_cast<uint8_t>(hw_addr >> 16),
static_cast<uint8_t>(hw_addr >> 8), static_cast<uint8_t>(hw_addr)
};
return uu;
}
} // end namespace impl
} // end namespace unique_id
#endif // _IMPL_UNIQUE_ID_H_

View File

@@ -0,0 +1,209 @@
/* -*- mode: C++ -*- */
/*********************************************************************
* Software License Agreement (BSD License)
*
* Copyright (C) 2012 Jack O'Quin
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of the author nor other contributors may be
* used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*********************************************************************/
#ifndef _UNIQUE_ID_H_
#define _UNIQUE_ID_H_ 1
/** @file
@brief Helper functions for universally unique identifiers and messages.
@author Jack O'Quin
*/
#include <string>
#include <boost/uuid/uuid.hpp>
#include <boost/uuid/uuid_io.hpp>
#include <ros/ros.h>
#include <uuid_msgs/UniqueID.h>
#include <unique_id/impl/unique_id.h> // private implementation details
/** @brief C++ namespace for unique_id helper functions.
*
* Various ROS components use universally unique identifiers. This
* header provides functions for working with a common
* uuid_msgs/UniqueID message, and the boost uuid class.
*
* - http://en.wikipedia.org/wiki/Uuid
* - http://tools.ietf.org/html/rfc4122.html
* - http://www.boost.org/doc/libs/1_42_0/libs/uuid/uuid.html
*
* Programmers are free to create UUID objects using any approved RFC
* 4122 method. The boost uuid interface supports them all.
*
* Functions in this namespace provide simple APIs, not requiring
* detailed knowledge of RFC 4122 or the boost uuid interface. ROS
* applications are likely to need either a random or a name-based
* UUID.
*
* - fromRandom() generates a random UUID.
* - fromURL() generates a name-based UUID from a URL string.
*/
namespace unique_id
{
/** @brief Create UUID object from UniqueID message.
*
* @param msg uuid_msgs/UniqueID message.
* @returns boost::uuids::uuid object.
*/
static inline boost::uuids::uuid fromMsg(uuid_msgs::UniqueID const &msg)
{
boost::uuids::uuid uu{};
std::copy(msg.uuid.begin(), msg.uuid.end(), uu.begin());
return uu;
}
/** @brief Generate a random UUID object.
*
* @returns type 4 boost::uuids::uuid object.
*
* Different calls to this function at any time or place will almost
* certainly generate different UUIDs. The method used is RFC 4122
* variant 4.
*/
static inline boost::uuids::uuid fromRandom(void)
{
return impl::genRandom();
}
/** @brief Generate UUID from canonical hex string.
*
* @param str string containing canonical hex representation
* @returns corresponding boost::uuids::uuid object.
*
* @note This is not a general service for generating a UUID from an
* arbitrary character string. The fromURL() function will do that
* for any Uniform Resource Identifier.
*
* The canonical hex string is a human-readable representation of a
* correctly-formatted sixteen-byte UUID. In addition to the dashes,
* it should contain exactly 32 hexadecimal digits. The @a str can
* be any accepted by the boost uuid string generator, but that is
* not well-defined. The format produced by toHexString() works
* reliably: "01234567-89ab-cdef-0123-456789abcdef".
*
* @warning Strings not accepted by boost may produce undefined
* results: perhaps throwing a @c std::runtime_error exception, or
* silently ignoring parts of the string.
*/
static inline boost::uuids::uuid fromHexString(std::string const &str)
{
return impl::genString(str);
}
/** @brief Generate UUID from Uniform Resource Identifier.
*
* @param url URL for identifier creation.
* @returns type 5 boost::uuids::uuid object.
*
* Matching @a url strings must yield the same UUID. Different @a url
* strings will almost certainly generate different UUIDs. The method
* used is RFC 4122 variant 5, computing the SHA-1 hash of the @a
* url.
*
* For any given @a url, this function returns the same UUID as the
* corresponding Python @c unique_id.fromURL() function.
*
* For example, Open Street Map identifiers are encoded like this,
* with decimal representations of the integer OSM node, way, or
* relation identifiers appended to the URL:
*
* - fromURL("http://openstreetmap.org/node/123456789")
* - fromURL("http://openstreetmap.org/way/6543210")
* - fromURL("http://openstreetmap.org/relation/999999")
*/
static inline boost::uuids::uuid fromURL(std::string const &url)
{
return impl::genURL(url);
}
/** @brief Generate a Time Based UUID object. Users are recommended to seed the random
* number generator using srand from the calling application to generate the clock_id
*
* @param timestamp The ros::Time timestamp for UUID generation
* @param hw_addr A 48-bit (6 octets) network address assigned to the 48 LSBs
* @returns type 1 boost::uuids::uuid object.
*
* Different calls to this function at any time or place will almost
* certainly generate different UUIDs. The method used is RFC 4122
* version 1.
*/
static inline boost::uuids::uuid fromTime(ros::Time timestamp, uint64_t hw_addr)
{
return impl::genTime(timestamp, hw_addr);
}
/** @brief Create a UniqueID message from a UUID object.
*
* @param uu boost::uuids::uuid object.
* @returns uuid_msgs/UniqueID message.
*/
static inline uuid_msgs::UniqueID toMsg(boost::uuids::uuid const &uu)
{
uuid_msgs::UniqueID msg;
std::copy(uu.begin(), uu.end(), msg.uuid.begin());
return msg;
}
/** @brief Get the canonical string representation for a boost UUID.
*
* @param uu boost::uuids::uuid object.
* @returns canonical UUID hex string: "01234567-89ab-cdef-0123-456789abcdef".
*
* A @c boost::uuids::uuid object yields the same representation via
* its @c << operator or @c to_string() function.
*/
static inline std::string toHexString(boost::uuids::uuid const &uu)
{
return boost::uuids::to_string(uu);
}
/** @brief Get the canonical string representation for a UniqueID message.
*
* @param msg uuid_msgs/UniqueID message.
* @returns canonical UUID hex string: "01234567-89ab-cdef-0123-456789abcdef".
*/
static inline std::string toHexString(uuid_msgs::UniqueID const &msg)
{
return boost::uuids::to_string(fromMsg(msg));
}
} // end namespace unique_id
#endif // _UNIQUE_ID_H_

View File

@@ -0,0 +1,16 @@
unique_id: ROS universally unique identifier support
====================================================
Contents:
.. toctree::
:maxdepth: 2
unique_id
CHANGELOG
Indices and tables
==================
* :ref:`genindex`
* :ref:`modindex`

View File

@@ -0,0 +1,13 @@
/**
\mainpage
\htmlinclude manifest.html
This package provides Python and C++ interfaces for managing
universally unique identifiers.
There are no ROS nodes or commands.
Note: For Time-Based UUID generation using the C++ interface
seed the random number generator through srand()
*/

View File

@@ -0,0 +1,29 @@
<?xml version="1.0"?>
<?xml-model href="http://download.ros.org/schema/package_format3.xsd" schematypens="http://www.w3.org/2001/XMLSchema"?>
<package format="3">
<name>unique_id</name>
<version>1.0.6</version>
<description>
ROS Python and C++ interfaces for universally unique identifiers.
</description>
<maintainer email="jack.oquin@gmail.com">Jack O'Quin</maintainer>
<author>Jack O'Quin</author>
<license>BSD</license>
<url>http://ros.org/wiki/unique_id</url>
<buildtool_depend>catkin</buildtool_depend>
<buildtool_depend condition="$ROS_PYTHON_VERSION == 2">python-setuptools</buildtool_depend>
<buildtool_depend condition="$ROS_PYTHON_VERSION == 3">python3-setuptools</buildtool_depend>
<depend>roscpp</depend>
<depend>rospy</depend>
<depend>uuid_msgs</depend>
<test_depend>rosunit</test_depend>
<export>
<rosdoc config="rosdoc.yaml" />
</export>
</package>

View File

@@ -0,0 +1,8 @@
- builder: doxygen
name: C++ API
output_dir: c++
file_patterns: '*.c *.cpp *.h *.cc *.hh *.dox'
- builder: sphinx
name: Python API
output_dir: python

View File

@@ -0,0 +1,11 @@
#!/usr/bin/env python
from setuptools import setup
from catkin_pkg.python_setup import generate_distutils_setup
d = generate_distutils_setup(
packages=['unique_id'],
package_dir={'': 'src'},
)
setup(**d)

View File

@@ -0,0 +1,146 @@
# Software License Agreement (BSD License)
#
# Copyright (C) 2012, Jack O'Quin
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following
# disclaimer in the documentation and/or other materials provided
# with the distribution.
# * Neither the name of the author nor of other contributors may be
# used to endorse or promote products derived from this software
# without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
"""
Python module for unique_id helper functions.
Various ROS components use universally unique identifiers
(UUID_). This module provides functions for working with a common
`uuid_msgs/UniqueID`_ message, and the standard Python
:class:`uuid.UUID` class.
Programmers are free to create UUID objects using any approved `RFC
4122`_ method. The standard Python :py:mod:`uuid` module supports them
all.
Functions in this module provide simple APIs, not requiring detailed
knowledge of `RFC 4122`_ or the :py:mod:`uuid` interface. ROS
applications are likely to need either a random or a name-based UUID.
* :func:`fromRandom` generates a random UUID.
* :func:`fromURL` generates a name-based UUID from a URL string.
.. _`uuid_msgs/UniqueID`: http://ros.org/doc/api/uuid_msgs/html/msg/UniqueID.html
.. _`RFC 4122`: http://tools.ietf.org/html/rfc4122.html
.. _UUID: http://en.wikipedia.org/wiki/Uuid
"""
# enable some python3 compatibility options:
from __future__ import absolute_import, print_function, unicode_literals
from uuid_msgs.msg import UniqueID
import uuid
def fromMsg(msg):
"""Create UUID object from UniqueID message.
:param msg: `uuid_msgs/UniqueID`_ message.
:returns: :class:`uuid.UUID` object.
"""
return uuid.UUID(bytes = msg.uuid)
def fromRandom():
"""Generate a random UUID object.
:returns: type 4 :class:`uuid.UUID` object.
Different calls to this function at any time or place will almost
certainly generate different UUIDs. The method used is `RFC 4122`_
variant 4.
"""
return uuid.uuid4()
def fromURL(url):
"""Generate UUID from Uniform Resource Locator.
:param url: URL for identifier creation.
:returns: type 5 :class:`uuid.UUID` object.
Matching *url* strings must yield the same UUID. Different *url*
strings will almost certainly generate different UUIDs. The method
used is `RFC 4122`_ variant 5, computing the SHA-1 hash of the
*url*.
For any given *url*, this function returns the same UUID as the
corresponding C++ `unique_id::fromURL()` function.
For example, Open Street Map identifiers are encoded like this,
with decimal representations of the integer OSM node, way, or
relation identifiers appended to the URL::
fromURL('http://openstreetmap.org/node/' + str(node_id))
fromURL('http://openstreetmap.org/way/' + str(way_id))
fromURL('http://openstreetmap.org/relation/' + str(rel_id))
"""
return uuid.uuid5(uuid.NAMESPACE_URL, url)
def fromTime(timestamp, hw_addr):
"""Generate a Time Based UUID object.
:param timestamp: The rospy.Time timestamp for UUID generation
:param hw_addr: A 48-bit long representing the network address
:returns: type 1 :class:`uuid.UUID` object
Different calls to this function at any time or place will almost
certainly generate different UUIDs. The method used is RFC 4122
version 1.
"""
uu = uuid.uuid1(hw_addr)
offset = 122192928000000000
nano_epoch = long(timestamp.secs / (100 * 1e-9) + timestamp.nsecs / 100)
# return nano_epoch
nano_rfc = nano_epoch + offset
data = (nano_rfc & 0x0000000FFFFFFFF, (nano_rfc >> 32) & 0x000FFFF, (nano_rfc >> 48) | 0x1000,
uu.fields[3], uu.fields[4], uu.fields[5])
return uuid.UUID(fields=data)
def toMsg(uuid_obj):
"""Create a UniqueID message from a UUID object.
:param uuid_obj: standard Python :class:`uuid.UUID` object.
:returns: `uuid_msgs/UniqueID`_ message.
"""
return UniqueID(uuid = uuid_obj.bytes)
def toHexString(msg):
"""Get the canonical hexadecimal string representation for a UniqueID message.
:param msg: `uuid_msgs/UniqueID`_ message.
:returns: UUID hex string: '01234567-89ab-cdef-0123-456789abcdef'.
A :class:`uuid.UUID` object yields the same representation via the
:py:func:`str` function.
"""
return str(fromMsg(msg))

View File

@@ -0,0 +1,15 @@
### Unit tests
#
# Only configured when CATKIN_ENABLE_TESTING is true.
# C++ gtests
catkin_add_gtest(test_${PROJECT_NAME}
test_${PROJECT_NAME}.cpp
second_test_${PROJECT_NAME}.cpp)
add_dependencies(test_${PROJECT_NAME} ${catkin_EXPORTED_TARGETS})
target_link_libraries(test_${PROJECT_NAME}
${Boost_LIBRARIES}
${catkin_LIBRARIES})
# Python nose tests
catkin_add_nosetests(test_${PROJECT_NAME}.py)

View File

@@ -0,0 +1,193 @@
//
// A second C++ unit test for unique_id interface, which must be able
// to be included in more than one source file.
//
#include <gtest/gtest.h>
#include <unique_id/unique_id.h>
using namespace unique_id;
typedef boost::uuids::uuid uuid;
typedef uuid_msgs::UniqueID UniqueID;
///////////////////////////////////////////////////////////////
// Test cases
///////////////////////////////////////////////////////////////
// Test random generator
TEST(BoostUUID2, fromRandom)
{
static const int N = 1000;
uuid uu[N];
for (int i = 0; i < N; ++i)
{
uu[i] = fromRandom();
for (int j = i-1; j >= 0; --j)
{
EXPECT_NE(uu[i], uu[j]);
}
}
}
TEST(BoostUUID2, emptyURL)
{
std::string s;
uuid x = fromURL(s);
uuid y = fromURL(s);
EXPECT_EQ(x, y);
// MUST yield same result as Python fromURL() function:
EXPECT_EQ(toHexString(x), "1b4db7eb-4057-5ddf-91e0-36dec72071f5");
}
TEST(BoostUUID2, sameURL)
{
std::string s("http://openstreetmap.org/node/1");
uuid x = fromURL(s);
uuid y = fromURL(s);
EXPECT_EQ(x, y);
// MUST yield same result as Python fromURL() function:
EXPECT_EQ(toHexString(x), "ef362ac8-9659-5481-b954-88e9b741c8f9");
}
TEST(BoostUUID2, differentOsmNamespace)
{
uuid x = fromURL("http://openstreetmap.org/node/1");
uuid y = fromURL("http://openstreetmap.org/way/1");
EXPECT_NE(x, y);
// MUST yield same result as Python fromURL() function:
EXPECT_EQ(toHexString(y), "b3180681-b125-5e41-bd04-3c8b046175b4");
}
TEST(BoostUUID2, actualOsmNode)
{
uuid x = fromURL("http://openstreetmap.org/node/1");
uuid y = fromURL("http://openstreetmap.org/node/152370223");
EXPECT_NE(x, y);
// MUST yield same result as Python fromURL() function:
EXPECT_EQ(toHexString(y), "8e0b7d8a-c433-5c42-be2e-fbd97ddff9ac");
}
TEST(BoostUUID2, fromHexString)
{
std::string s("da7c242f-2efe-5175-9961-49cc621b80b9");
std::string r = toHexString(fromHexString(s));
EXPECT_EQ(s, r);
}
TEST(BoostUUID2, fromStringNoDashes)
{
std::string s("da7c242f-2efe-5175-9961-49cc621b80b9");
std::string s_hex("da7c242f2efe5175996149cc621b80b9");
std::string r = toHexString(fromHexString(s_hex));
EXPECT_EQ(s, r);
}
TEST(BoostUUID2, fromBracesString)
{
std::string s("da7c242f-2efe-5175-9961-49cc621b80b9");
std::string s_braces = "{" + s + "}";
std::string r = toHexString(fromHexString(s_braces));
EXPECT_EQ(s, r);
}
TEST(BoostUUID2, fromUrnString)
{
// This documents boost 1.46.1 behavior, but is an undefined
// fromHexString() input, not really a valid test case.
std::string s("da7c242f-2efe-5175-9961-49cc621b80b9");
std::string s_urn = "urn:uuid:" + s;
std::string r = toHexString(fromHexString(s_urn));
EXPECT_NE(s, r);
}
TEST(BoostUUID2, fromTooLongString)
{
// This documents boost 1.46.1 behavior, but is an undefined
// fromHexString() input, not really a valid test case.
std::string s("da7c242f-2efe-5175-9961-49cc621b80b9");
std::string s_too_long = s + "-0001";
std::string r = toHexString(fromHexString(s_too_long));
EXPECT_EQ(s, r);
}
TEST(BoostUUID2, fromTooShortString)
{
// This documents boost 1.46.1 behavior, but is an undefined
// fromHexString() input, not really a valid test case.
std::string s("da7c242f-2efe-5175-9961-49cc621b80");
try
{
uuid x = fromHexString(s);
FAIL(); // expected exception not thrown
EXPECT_NE(toHexString(x), s);
}
catch (std::runtime_error &e)
{
EXPECT_EQ(e.what(), std::string("invalid uuid string"));
}
catch (...)
{
FAIL(); // unexpected exception
}
}
TEST(BoostUUID2, fromBogusString)
{
// This documents boost 1.46.1 behavior, but is an undefined
// fromHexString() input, not really a valid test case.
std::string s("Invalid UUID string");
try
{
uuid x = fromHexString(s);
FAIL(); // expected exception not thrown
EXPECT_NE(toHexString(x), s);
}
catch (std::runtime_error &e)
{
EXPECT_EQ(e.what(), std::string("invalid uuid string"));
}
catch (...)
{
FAIL(); // unexpected exception
}
}
TEST(UniqueID2, nilMessage)
{
UniqueID x;
UniqueID y = toMsg(uuid());
EXPECT_EQ(x.uuid, y.uuid);
}
TEST(UniqueID2, randomMessage)
{
UniqueID x;
UniqueID y = toMsg(fromRandom());
EXPECT_NE(x.uuid, y.uuid);
}
TEST(UniqueID2, equivalentMessages)
{
std::string s("da7c242f-2efe-5175-9961-49cc621b80b9");
UniqueID x = toMsg(fromHexString(s));
UniqueID y = toMsg(fromHexString(s));
EXPECT_EQ(x.uuid, y.uuid);
EXPECT_EQ(s, toHexString(y));
}
TEST(UniqueID2, toAndFromMessage)
{
std::string s("da7c242f-2efe-5175-9961-49cc621b80b9");
uuid x = uuid(fromHexString(s));
uuid y = fromMsg(toMsg(x));
EXPECT_EQ(x, y);
}
TEST(UniqueID2, messageToString)
{
std::string s("da7c242f-2efe-5175-9961-49cc621b80b9");
UniqueID x = toMsg(fromHexString(s));
std::string y = toHexString(x);
EXPECT_EQ(s, y);
}

View File

@@ -0,0 +1,327 @@
//
// C++ unit tests for unique_id interface.
//
#include <gtest/gtest.h>
#include <ros/ros.h>
#include <unique_id/unique_id.h>
using namespace unique_id;
typedef boost::uuids::uuid uuid;
typedef uuid_msgs::UniqueID UniqueID;
///////////////////////////////////////////////////////////////
// Test cases
///////////////////////////////////////////////////////////////
// Test random generator
TEST(BoostUUID, fromRandom)
{
static const int N = 1000;
uuid uu[N];
for (int i = 0; i < N; ++i)
{
uu[i] = fromRandom();
for (int j = i-1; j >= 0; --j)
{
EXPECT_NE(uu[i], uu[j]);
}
}
}
// Test Timebased UUID
TEST(BoostUUID, fromTime)
{
ros::Time t(1515778146, 239216089);
uint64_t hw_addr = 0xAABBCCDDEEFF;
// Generate UUID from time and hardware address
uuid uu = fromTime(t, hw_addr);
// Obtain time since epoch back from the generated uuid
std::vector<uint8_t> data(uu.size());
std::copy(uu.begin(), uu.end(), data.begin());
uint64_t timestamp = (static_cast<uint64_t>(data[0]) << 24) + (static_cast<uint64_t>(data[1]) << 16) +
(static_cast<uint64_t>(data[2]) << 8) + static_cast<uint64_t>(data[3]) +
(static_cast<uint64_t>(data[4]) << 40) + (static_cast<uint64_t>(data[5]) << 32) +
(static_cast<uint64_t>(data[6] & 0x0F) << 56) + (static_cast<uint64_t>(data[7]) << 48);
uint64_t offset = 122192928000000000; // time offset in 100 ns intervals between RFC4122 Timestamp and Epoch Time
uint64_t ns_intervals = timestamp - offset;
uint64_t uu_hw_addr = 0;
for (int8_t i=0; i < 6; i++)
{
uu_hw_addr += static_cast<uint64_t>(data[uu.size() - 1 - i]) << 8*i;
}
ros::Time uu_time;
uu_time.sec = static_cast<int32_t>(ns_intervals / 1e9 * 100);
uu_time.nsec = static_cast<int32_t>((ns_intervals - static_cast<uint64_t>(uu_time.sec) / (100 * 1e-9)) * 100);
EXPECT_EQ(t.sec, uu_time.sec);
// The UUID stores the timestamp in 100ns intervals,
// so we lose precision for the 1's and 10's value of the nanoseconds in the time given
EXPECT_EQ(t.nsec - uu_time.nsec, 89);
EXPECT_EQ(hw_addr, uu_hw_addr);
}
TEST(BoostUUID, timeWithinSameInterval)
{
ros::Time t1(1515778146, 239216020);
ros::Time t2(1515778146, 239216080);
uint64_t hw_addr = 0xAABBCCDDEEFF;
// Generate UUIDs from times and hardware address
uuid uu1 = fromTime(t1, hw_addr);
uuid uu2 = fromTime(t2, hw_addr);
// Obtain times since epoch back from uu1
std::vector<uint8_t> data(uu1.size());
std::copy(uu1.begin(), uu1.end(), data.begin());
uint64_t timestamp = (static_cast<uint64_t>(data[0]) << 24) + (static_cast<uint64_t>(data[1]) << 16) +
(static_cast<uint64_t>(data[2]) << 8) + static_cast<uint64_t>(data[3]) +
(static_cast<uint64_t>(data[4]) << 40) + (static_cast<uint64_t>(data[5]) << 32) +
(static_cast<uint64_t>(data[6] & 0x0F) << 56) + (static_cast<uint64_t>(data[7]) << 48);
uint64_t offset = 122192928000000000; // time offset in 100 ns intervals between RFC4122 Timestamp and Epoch Time
uint64_t ns_intervals = timestamp - offset;
ros::Time uu1_time;
uu1_time.sec = static_cast<int32_t>(ns_intervals / 1e9 * 100);
uu1_time.nsec = static_cast<int32_t>((ns_intervals - static_cast<uint64_t>(uu1_time.sec) / (100 * 1e-9)) * 100);
// Obtain times since epoch back from uu2
std::copy(uu2.begin(), uu2.end(), data.begin());
timestamp = (static_cast<uint64_t>(data[0]) << 24) + (static_cast<uint64_t>(data[1]) << 16) +
(static_cast<uint64_t>(data[2]) << 8) + static_cast<uint64_t>(data[3]) +
(static_cast<uint64_t>(data[4]) << 40) + (static_cast<uint64_t>(data[5]) << 32) +
(static_cast<uint64_t>(data[6] & 0x0F) << 56) + (static_cast<uint64_t>(data[7]) << 48);
ns_intervals = timestamp - offset;
ros::Time uu2_time;
uu2_time.sec = static_cast<int32_t>(ns_intervals / 1e9 * 100);
uu2_time.nsec = static_cast<int32_t>((ns_intervals - static_cast<uint64_t>(uu2_time.sec) / (100 * 1e-9)) * 100);
// Compare
// Since both timestamps were in the same 100ns interval, should get same timestamp
EXPECT_EQ(uu1_time.sec, uu2_time.sec);
EXPECT_EQ(uu1_time.nsec, uu2_time.nsec);
// While timestamps are the same, the clock_id is a randomly generated 14-bit value
// So, we should still expect the uuids generated to be different
EXPECT_NE(uu1, uu2);
}
TEST(BoostUUID, timeWithinDifferentInterval)
{
ros::Time t1(1515778146, 239216020);
ros::Time t2(1515778146, 239216120);
uint64_t hw_addr = 0xAABBCCDDEEFF;
// Generate UUIDs from times and hardware address
uuid uu1 = fromTime(t1, hw_addr);
uuid uu2 = fromTime(t2, hw_addr);
// Obtain times since epoch back from uu1
std::vector<uint8_t> data(uu1.size());
std::copy(uu1.begin(), uu1.end(), data.begin());
uint64_t timestamp = (static_cast<uint64_t>(data[0]) << 24) + (static_cast<uint64_t>(data[1]) << 16) +
(static_cast<uint64_t>(data[2]) << 8) + static_cast<uint64_t>(data[3]) +
(static_cast<uint64_t>(data[4]) << 40) + (static_cast<uint64_t>(data[5]) << 32) +
(static_cast<uint64_t>(data[6] & 0x0F) << 56) + (static_cast<uint64_t>(data[7]) << 48);
uint64_t offset = 122192928000000000; // time offset in 100 ns intervals between RFC4122 Timestamp and Epoch Time
uint64_t ns_intervals = timestamp - offset;
ros::Time uu1_time;
uu1_time.sec = static_cast<int32_t>(ns_intervals / 1e9 * 100);
uu1_time.nsec = static_cast<int32_t>((ns_intervals - static_cast<uint64_t>(uu1_time.sec) / (100 * 1e-9)) * 100);
// Obtain times since epoch back from uu2
std::copy(uu2.begin(), uu2.end(), data.begin());
timestamp = (static_cast<uint64_t>(data[0]) << 24) + (static_cast<uint64_t>(data[1]) << 16) +
(static_cast<uint64_t>(data[2]) << 8) + static_cast<uint64_t>(data[3]) +
(static_cast<uint64_t>(data[4]) << 40) + (static_cast<uint64_t>(data[5]) << 32) +
(static_cast<uint64_t>(data[6] & 0x0F) << 56) + (static_cast<uint64_t>(data[7]) << 48);
ns_intervals = timestamp - offset;
ros::Time uu2_time;
uu2_time.sec = static_cast<int32_t>(ns_intervals / 1e9 * 100);
uu2_time.nsec = static_cast<int32_t>((ns_intervals - static_cast<uint64_t>(uu2_time.sec) / (100 * 1e-9)) * 100);
// Compare
// Since both timestamps were in different 100ns intervals, should get different timestamps (at the ns level)
EXPECT_EQ(uu1_time.sec, uu2_time.sec);
EXPECT_NE(uu1_time.nsec, uu2_time.nsec);
}
TEST(BoostUUID, emptyURL)
{
std::string s;
uuid x = fromURL(s);
uuid y = fromURL(s);
EXPECT_EQ(x, y);
// MUST yield same result as Python fromURL() function:
EXPECT_EQ(toHexString(x), "1b4db7eb-4057-5ddf-91e0-36dec72071f5");
}
TEST(BoostUUID, sameURL)
{
std::string s("http://openstreetmap.org/node/1");
uuid x = fromURL(s);
uuid y = fromURL(s);
EXPECT_EQ(x, y);
// MUST yield same result as Python fromURL() function:
EXPECT_EQ(toHexString(x), "ef362ac8-9659-5481-b954-88e9b741c8f9");
}
TEST(BoostUUID, differentOsmNamespace)
{
uuid x = fromURL("http://openstreetmap.org/node/1");
uuid y = fromURL("http://openstreetmap.org/way/1");
EXPECT_NE(x, y);
// MUST yield same result as Python fromURL() function:
EXPECT_EQ(toHexString(y), "b3180681-b125-5e41-bd04-3c8b046175b4");
}
TEST(BoostUUID, actualOsmNode)
{
uuid x = fromURL("http://openstreetmap.org/node/1");
uuid y = fromURL("http://openstreetmap.org/node/152370223");
EXPECT_NE(x, y);
// MUST yield same result as Python fromURL() function:
EXPECT_EQ(toHexString(y), "8e0b7d8a-c433-5c42-be2e-fbd97ddff9ac");
}
TEST(BoostUUID, fromHexString)
{
std::string s("da7c242f-2efe-5175-9961-49cc621b80b9");
std::string r = toHexString(fromHexString(s));
EXPECT_EQ(s, r);
}
TEST(BoostUUID, fromStringNoDashes)
{
std::string s("da7c242f-2efe-5175-9961-49cc621b80b9");
std::string s_hex("da7c242f2efe5175996149cc621b80b9");
std::string r = toHexString(fromHexString(s_hex));
EXPECT_EQ(s, r);
}
TEST(BoostUUID, fromBracesString)
{
std::string s("da7c242f-2efe-5175-9961-49cc621b80b9");
std::string s_braces = "{" + s + "}";
std::string r = toHexString(fromHexString(s_braces));
EXPECT_EQ(s, r);
}
TEST(BoostUUID, fromUrnString)
{
// This documents boost 1.46.1 behavior, but is an undefined
// fromHexString() input, not really a valid test case.
std::string s("da7c242f-2efe-5175-9961-49cc621b80b9");
std::string s_urn = "urn:uuid:" + s;
std::string r = toHexString(fromHexString(s_urn));
EXPECT_NE(s, r);
}
TEST(BoostUUID, fromTooLongString)
{
// This documents boost 1.46.1 behavior, but is an undefined
// fromHexString() input, not really a valid test case.
std::string s("da7c242f-2efe-5175-9961-49cc621b80b9");
std::string s_too_long = s + "-0001";
std::string r = toHexString(fromHexString(s_too_long));
EXPECT_EQ(s, r);
}
TEST(BoostUUID, fromTooShortString)
{
// This documents boost 1.46.1 behavior, but is an undefined
// fromHexString() input, not really a valid test case.
std::string s("da7c242f-2efe-5175-9961-49cc621b80");
try
{
uuid x = fromHexString(s);
FAIL(); // expected exception not thrown
EXPECT_NE(toHexString(x), s);
}
catch (std::runtime_error &e)
{
EXPECT_EQ(e.what(), std::string("invalid uuid string"));
}
catch (...)
{
FAIL(); // unexpected exception
}
}
TEST(BoostUUID, fromBogusString)
{
// This documents boost 1.46.1 behavior, but is an undefined
// fromHexString() input, not really a valid test case.
std::string s("Invalid UUID string");
try
{
uuid x = fromHexString(s);
FAIL(); // expected exception not thrown
EXPECT_NE(toHexString(x), s);
}
catch (std::runtime_error &e)
{
EXPECT_EQ(e.what(), std::string("invalid uuid string"));
}
catch (...)
{
FAIL(); // unexpected exception
}
}
TEST(UniqueID, nilMessage)
{
UniqueID x;
UniqueID y = toMsg(uuid());
EXPECT_EQ(x.uuid, y.uuid);
}
TEST(UniqueID, randomMessage)
{
UniqueID x;
UniqueID y = toMsg(fromRandom());
EXPECT_NE(x.uuid, y.uuid);
}
TEST(UniqueID, equivalentMessages)
{
std::string s("da7c242f-2efe-5175-9961-49cc621b80b9");
UniqueID x = toMsg(fromHexString(s));
UniqueID y = toMsg(fromHexString(s));
EXPECT_EQ(x.uuid, y.uuid);
EXPECT_EQ(s, toHexString(y));
}
TEST(UniqueID, toAndFromMessage)
{
std::string s("da7c242f-2efe-5175-9961-49cc621b80b9");
uuid x = uuid(fromHexString(s));
uuid y = fromMsg(toMsg(x));
EXPECT_EQ(x, y);
}
TEST(UniqueID, messageToString)
{
std::string s("da7c242f-2efe-5175-9961-49cc621b80b9");
UniqueID x = toMsg(fromHexString(s));
std::string y = toHexString(x);
EXPECT_EQ(s, y);
}
// Run all the tests that were declared with TEST()
int main(int argc, char **argv)
{
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}

View File

@@ -0,0 +1,202 @@
#!/usr/bin/env python
# enable some python3 compatibility options:
# (unicode_literals not compatible with python2 uuid module)
from __future__ import absolute_import, print_function
import sys
import unittest
import uuid # standard Python module
import rospy
from uuid_msgs.msg import UniqueID
from unique_id import *
class TestPythonUUID(unittest.TestCase):
"""Unit tests for Python UUID generation.
"""
# random UUID generation tests
def test_random_uuids(self):
N = 1000
uu = []
for i in xrange(N):
uu.append(fromRandom())
self.assertEqual(type(uu[i]), uuid.UUID)
for j in xrange(i-1, -1, -1):
self.assertNotEqual(uu[i], uu[j])
# UUID generation from URL tests
def test_empty_url(self):
x = fromURL('')
self.assertEqual(type(x), uuid.UUID)
y = fromURL('')
self.assertEqual(type(y), uuid.UUID)
self.assertEqual(x, y)
# MUST yield same result as C++ fromURL() function:
self.assertEqual(str(x), "1b4db7eb-4057-5ddf-91e0-36dec72071f5")
def test_same_url(self):
x = fromURL('http://openstreetmap.org/node/1')
self.assertEqual(type(x), uuid.UUID)
y = fromURL('http://openstreetmap.org/node/1')
self.assertEqual(type(y), uuid.UUID)
self.assertEqual(x, y)
# MUST yield same result as C++ fromURL() function:
self.assertEqual(str(x), 'ef362ac8-9659-5481-b954-88e9b741c8f9')
def test_same_id_different_osm_namespace(self):
x = fromURL('http://openstreetmap.org/node/1')
y = fromURL('http://openstreetmap.org/way/1')
self.assertNotEqual(x, y)
# MUST yield same result as C++ fromURL() function:
self.assertEqual(str(y), 'b3180681-b125-5e41-bd04-3c8b046175b4')
def test_actual_osm_node_id(self):
x = fromURL('http://openstreetmap.org/node/1')
y = fromURL('http://openstreetmap.org/node/152370223')
self.assertNotEqual(x, y)
# MUST yield same result as C++ fromURL() function:
self.assertEqual(str(y), '8e0b7d8a-c433-5c42-be2e-fbd97ddff9ac')
def test_route_segment(self):
start = 'da7c242f-2efe-5175-9961-49cc621b80b9'
end = '812f1c08-a34b-5a21-92b9-18b2b0cf4950'
x = fromURL('http://ros.org/wiki/road_network/' + start + '/' + end)
y = fromURL('http://ros.org/wiki/road_network/' + end + '/' + start)
self.assertNotEqual(x, y)
# MUST yield same result as C++ fromURL() function:
self.assertEqual(str(x), 'acaa906e-8411-5b45-a446-ccdc2fc39f29')
# UniqueID message generation tests
def test_msg_creation(self):
msg = toMsg(fromURL('http://openstreetmap.org/node/152370223'))
self.assertEqual(toHexString(msg),
'8e0b7d8a-c433-5c42-be2e-fbd97ddff9ac')
def test_msg_same_id_different_namespace(self):
x = toMsg(fromURL('http://openstreetmap.org/node/1'))
y = toMsg(fromURL('http://openstreetmap.org/way/1'))
self.assertNotEqual(x, y)
self.assertEqual(toHexString(y),
'b3180681-b125-5e41-bd04-3c8b046175b4')
def test_msg_route_segment(self):
start = 'da7c242f-2efe-5175-9961-49cc621b80b9'
end = '812f1c08-a34b-5a21-92b9-18b2b0cf4950'
x = toMsg(fromURL('http://ros.org/wiki/road_network/'
+ start + '/' + end))
y = toMsg(fromURL('http://ros.org/wiki/road_network/'
+ end + '/' + start))
self.assertNotEqual(x, y)
self.assertEqual(toHexString(x),
'acaa906e-8411-5b45-a446-ccdc2fc39f29')
def test_nil_msg(self):
x = UniqueID()
y = toMsg(uuid.UUID(hex='00000000-0000-0000-0000-000000000000'))
self.assertEqual(x, y)
def test_random_msg(self):
x = UniqueID()
y = toMsg(fromRandom())
self.assertNotEqual(x, y)
def test_equivalent_msgs(self):
s = 'da7c242f-2efe-5175-9961-49cc621b80b9'
x = toMsg(uuid.UUID(s))
y = toMsg(uuid.UUID(s))
self.assertEqual(x, y)
self.assertEqual(s, toHexString(y))
def test_to_and_from_msg(self):
x = uuid.UUID('da7c242f-2efe-5175-9961-49cc621b80b9')
y = (fromMsg(toMsg(x)))
self.assertEqual(x, y)
self.assertEqual(type(y), uuid.UUID)
def test_msg_to_string(self):
s = 'da7c242f-2efe-5175-9961-49cc621b80b9'
x = toMsg(uuid.UUID(s))
y = toHexString(x)
self.assertEqual(s, y)
self.assertEqual(type(y), str)
# UUID Time-Based Generation
def test_time(self):
hw_addr = 0xAABBCCDDEEFF
t = rospy.Time(1515778146, 239216089)
uu = fromTime(t, hw_addr) # generate UUID
offset = 122192928000000000 # in 100ns intervals between RFC4122 timestamp and epoch time
ns_intervals_rfc = uu.fields[0] + (uu.fields[1] << 32) + ((uu.fields[2] & 0x0FFF) << 48)
ns_intervals_epoch = ns_intervals_rfc - offset
uu_time = rospy.Time()
uu_time.secs = long(ns_intervals_epoch / 1e9 * 100)
uu_time.nsecs = long(ns_intervals_epoch - uu_time.secs / (100 * 1e-9)) * 100
self.assertEqual(t.secs, uu_time.secs)
# Expect 89ns to be shaved off due to timestamp being stored in 100ns intervals
self.assertEqual(t.nsecs - uu_time.nsecs, 89)
# Should be able to retrieve the hardware id
self.assertEqual(hw_addr, uu.fields[5])
def test_time_same_interval(self):
hw_addr = 0xAABBCCDDEEFF
t1 = rospy.Time(1515778146, 239216020)
t2 = rospy.Time(1515778146, 239216080)
uu1 = fromTime(t1, hw_addr) # generate UUID for t1
uu2 = fromTime(t2, hw_addr) # generate UUID for t2
offset = 122192928000000000 # in 100ns intervals between RFC4122 timestamp and epoch time
# Get time associated with uuid uu1
ns_intervals_rfc = uu1.fields[0] + (uu1.fields[1] << 32) + ((uu1.fields[2] & 0x0FFF) << 48)
ns_intervals_epoch = ns_intervals_rfc - offset
uu1_time = rospy.Time()
uu1_time.secs = long(ns_intervals_epoch / 1e9 * 100)
uu1_time.nsecs = long(ns_intervals_epoch - uu1_time.secs / (100 * 1e-9)) * 100
# Get time associated with uuid uu2
ns_intervals_rfc = uu2.fields[0] + (uu2.fields[1] << 32) + ((uu2.fields[2] & 0x0FFF) << 48)
ns_intervals_epoch = ns_intervals_rfc - offset
uu2_time = rospy.Time()
uu2_time.secs = long(ns_intervals_epoch / 1e9 * 100)
uu2_time.nsecs = long(ns_intervals_epoch - uu2_time.secs / (100 * 1e-9)) * 100
self.assertEqual(uu1_time.secs, uu2_time.secs)
# Timestamps should be same as they were generated for timestamps in the same 100ns interval
self.assertEqual(uu1_time.nsecs, uu2_time.nsecs)
# UUIDs should be different due to different (hopefully) randomly generated 14-bit clock ids
self.assertNotEqual(uu1, uu2)
def test_time_different_interval(self):
hw_addr = 0xAABBCCDDEEFF
t1 = rospy.Time(1515778146, 239216020)
t2 = rospy.Time(1515778146, 239216120)
uu1 = fromTime(t1, hw_addr) # generate UUID for t1
uu2 = fromTime(t2, hw_addr) # generate UUID for t2
offset = 122192928000000000 # in 100ns intervals between RFC4122 timestamp and epoch time
# Get time associated with uuid uu1
ns_intervals_rfc = uu1.fields[0] + (uu1.fields[1] << 32) + ((uu1.fields[2] & 0x0FFF) << 48)
ns_intervals_epoch = ns_intervals_rfc - offset
uu1_time = rospy.Time()
uu1_time.secs = long(ns_intervals_epoch / 1e9 * 100)
uu1_time.nsecs = long(ns_intervals_epoch - uu1_time.secs / (100 * 1e-9)) * 100
# Get time associated with uuid uu2
ns_intervals_rfc = uu2.fields[0] + (uu2.fields[1] << 32) + ((uu2.fields[2] & 0x0FFF) << 48)
ns_intervals_epoch = ns_intervals_rfc - offset
uu2_time = rospy.Time()
uu2_time.secs = long(ns_intervals_epoch / 1e9 * 100)
uu2_time.nsecs = long(ns_intervals_epoch - uu2_time.secs / (100 * 1e-9)) * 100
# Timestamps were generated for the same second
self.assertEqual(uu1_time.secs, uu2_time.secs)
# Timestamps should be different as they were generated for times in different 100ns intervals
self.assertNotEqual(uu1_time.nsecs, uu2_time.nsecs)
if __name__ == '__main__':
import rosunit
rosunit.unitrun('unique_id', 'test_uuid_py', TestPythonUUID)

View File

@@ -0,0 +1,5 @@
unique_id
---------
.. automodule:: unique_id
:members: