repo_id
stringlengths 19
138
| file_path
stringlengths 32
200
| content
stringlengths 1
12.9M
| __index_level_0__
int64 0
0
|
---|---|---|---|
apollo_public_repos/apollo-platform/ros/image_common | apollo_public_repos/apollo-platform/ros/image_common/camera_info_manager/package.xml | <package>
<name>camera_info_manager</name>
<version>1.11.12</version>
<description>
This package provides a C++ interface for camera calibration
information. It provides CameraInfo, and handles SetCameraInfo
service requests, saving and restoring the camera calibration
data.
</description>
<author>Jack O'Quin</author>
<maintainer email="[email protected]">Jack O'Quin</maintainer>
<maintainer email="[email protected]">Vincent Rabaud</maintainer>
<license>BSD</license>
<url type="website">http://ros.org/wiki/camera_info_manager</url>
<url type="bugtracker">https://github.com/ros-perception/image_common/issues</url>
<url type="repository">https://github.com/ros-perception/image_common</url>
<buildtool_depend version_gte="0.5.68">catkin</buildtool_depend>
<build_depend>boost</build_depend>
<build_depend>camera_calibration_parsers</build_depend>
<build_depend>image_transport</build_depend>
<build_depend>roscpp</build_depend>
<build_depend>roslib</build_depend>
<build_depend>rostest</build_depend>
<build_depend>sensor_msgs</build_depend>
<run_depend>boost</run_depend>
<run_depend>camera_calibration_parsers</run_depend>
<run_depend>image_transport</run_depend>
<run_depend>roscpp</run_depend>
<run_depend>roslib</run_depend>
<run_depend>sensor_msgs</run_depend>
<test_depend>gtest</test_depend>
</package>
| 0 |
apollo_public_repos/apollo-platform/ros/image_common | apollo_public_repos/apollo-platform/ros/image_common/camera_info_manager/mainpage.dox | /**
\mainpage
\htmlinclude manifest.html
\section codeapi C++ API
See: <camera_info_manager/camera_info_manager.h>.
*/
| 0 |
apollo_public_repos/apollo-platform/ros/image_common | apollo_public_repos/apollo-platform/ros/image_common/camera_info_manager/CHANGELOG.rst | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Changelog for package camera_info_manager
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1.11.12 (2017-01-29)
--------------------
* 1.11.11
* update changelogs
* Return empty CameraInfo when !ros::ok()
* Contributors: Enrique Fernandez, Vincent Rabaud
1.11.11 (2016-09-24)
--------------------
* Return empty CameraInfo when !ros::ok()
* Contributors: Enrique Fernandez
1.11.10 (2016-01-19)
--------------------
1.11.9 (2016-01-17)
-------------------
1.11.8 (2015-11-29)
-------------------
* fix compilation on Fedora, fixes `#42 <https://github.com/ros-perception/image_common/issues/42>`_
* Contributors: Vincent Rabaud
1.11.7 (2015-07-28)
-------------------
1.11.6 (2015-07-16)
-------------------
* simplify target_link_libraries
That should fix `#35 <https://github.com/ros-perception/image_common/issues/35>`_
* Contributors: Vincent Rabaud
1.11.5 (2015-05-14)
-------------------
1.11.4 (2014-09-21)
-------------------
1.11.3 (2014-05-19)
-------------------
* Add public member function to manually set camera info (`#19
<https://github.com/ros-perception/image_common/issues/19>`_)
* make rostest in CMakeLists optional (`ros/rosdistro#3010
<https://github.com/ros/rosdistro/issues/3010>`_)
* Contributors: Jack O'Quin, Jonathan Bohren, Lukas Bulwahn
1.11.2 (2014-02-13)
-------------------
1.11.1 (2014-01-26 02:33)
-------------------------
* check for CATKIN_ENABLE_TESTING
* Contributors: Lukas Bulwahn
1.11.0 (2013-07-20 12:23)
-------------------------
1.10.5 (2014-01-26 02:34)
-------------------------
1.10.4 (2013-07-20 11:42)
-------------------------
* add Jack as maintainer
* Contributors: Vincent Rabaud
1.10.3 (2013-02-21 05:33)
-------------------------
* add gtest libraries linkage
* Contributors: Vincent Rabaud
1.10.2 (2013-02-21 04:48)
-------------------------
* fix the rostest dependency
* Contributors: Vincent Rabaud
1.10.1 (2013-02-21 04:16)
-------------------------
* fix catkin gtest and rostest problem
* fix unit test dependencies
* Removed duplicated test dependancy
Test dependencies should never duplicate build or run dependencies.
* Contributors: Aaron Blasdel, Jack O'Quin
1.10.0 (2013-01-13)
-------------------
* fix the urls
* Contributors: Vincent Rabaud
1.9.22 (2012-12-16)
-------------------
1.9.21 (2012-12-14)
-------------------
* Updated package.xml file(s) to handle new catkin buildtool_depend
requirement
* Contributors: mirzashah
1.9.20 (2012-12-04)
-------------------
1.9.19 (2012-11-08)
-------------------
1.9.18 (2012-11-06)
-------------------
* remove the brief attribute
* Contributors: Vincent Rabaud
1.9.17 (2012-10-30 19:32)
-------------------------
1.9.16 (2012-10-30 09:10)
-------------------------
1.9.15 (2012-10-13 08:43)
-------------------------
* fix bad folder/libraries
* Contributors: Vincent Rabaud
1.9.14 (2012-10-13 01:07)
-------------------------
1.9.13 (2012-10-06)
-------------------
1.9.12 (2012-10-04)
-------------------
1.9.11 (2012-10-02 02:56)
-------------------------
* add missing rostest dependency
* Contributors: Vincent Rabaud
1.9.10 (2012-10-02 02:42)
-------------------------
* fix bad dependency
* Contributors: Vincent Rabaud
1.9.9 (2012-10-01)
------------------
* fix dependencies
* Contributors: Vincent Rabaud
1.9.8 (2012-09-30)
------------------
* add catkin as a dependency
* comply to the catkin API
* Contributors: Vincent Rabaud
1.9.7 (2012-09-18 11:39)
------------------------
* add missing linkage
* Contributors: Vincent Rabaud
1.9.6 (2012-09-18 11:07)
------------------------
1.9.5 (2012-09-13)
------------------
* install the include directories
* Contributors: Vincent Rabaud
1.9.4 (2012-09-12 23:37)
------------------------
1.9.3 (2012-09-12 20:44)
------------------------
1.9.2 (2012-09-10)
------------------
* fix build issues
* Contributors: Vincent Rabaud
1.9.1 (2012-09-07 15:33)
------------------------
* make the libraries public
* Contributors: Vincent Rabaud
1.9.0 (2012-09-07 13:03)
------------------------
* API documentation review update
* suppress misleading camera_info_manager error messages [`#5273
<https://github.com/ros-perception/image_common/issues/5273>`_]
* remove deprecated global CameraInfoManager symbol for Fuerte (`#4971
<https://github.com/ros-perception/image_common/issues/4971>`_)
* Revert to using boost::mutex, not boost::recursive_mutex.
* Hack saveCalibrationFile() to stat() the containing directory and
attempt to create it if necessary. Test for this case.
* Reload camera info when camera name changes.
* Implement most new Electric API changes, with test cases.
* Add ${ROS_HOME} expansion, with unit test cases.
Do not use "$$" for a single '$', look for "${" instead.
* Use case-insensitive comparisons for parsing URL tags (`#4761
<https://github.com/ros-perception/image_common/issues/4761>`_).
Add unit test cases to cover this. Add unit test case for camera
name containing video mode.
* add test for resolving an empty URL
* Deprecate use of global CameraInfoManager symbol in E-turtle (`#4786
<https://github.com/ros-perception/image_common/issues/4786>`_).
Modify unit tests accordingly.
* provide camera_info_manager namespace, fixes `#4760
<https://github.com/ros-perception/image_common/issues/4760>`_
* Add support for "package://" URLs.
* Fixed tests to work with new CameraInfo.
* Moved image_common from camera_drivers.
* Contributors: Vincent Rabaud, blaise, Jack O'Quin, mihelich
| 0 |
apollo_public_repos/apollo-platform/ros/image_common/camera_info_manager/include | apollo_public_repos/apollo-platform/ros/image_common/camera_info_manager/include/camera_info_manager/camera_info_manager.h | /* -*- mode: C++ -*- */
/* $Id$ */
/*********************************************************************
* Software License Agreement (BSD License)
*
* Copyright (c) 2010-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 _CAMERA_INFO_MANAGER_H_
#define _CAMERA_INFO_MANAGER_H_
#include <ros/ros.h>
#include <boost/thread/mutex.hpp>
#include <sensor_msgs/CameraInfo.h>
#include <sensor_msgs/SetCameraInfo.h>
/** @file
@brief CameraInfo Manager interface
@author Jack O'Quin
*/
namespace camera_info_manager
{
/** @brief CameraInfo Manager class
Provides CameraInfo, handles the sensor_msgs/SetCameraInfo service
requests, saves and restores sensor_msgs/CameraInfo data.
@par ROS Service
- @b set_camera_info (sensor_msgs/SetCameraInfo) stores
calibration information
Typically, these service requests are made by a calibration
package, such as:
- http://www.ros.org/wiki/camera_calibration
The calling node @em must invoke ros::spin() or ros::spinOnce() in
some thread, so CameraInfoManager can handle arriving service
requests.
@par Camera Name
The device driver sets a camera name via the
CameraInfoManager::CameraInfoManager constructor or the
setCameraName() method. This name is written when CameraInfo is
saved, and checked when data are loaded, with a warning logged if
the name read does not match.
Syntax: a camera name contains any combination of alphabetic,
numeric and '_' characters. Case is significant.
Camera drivers may use any syntactically valid name they please.
Where possible, it is best for the name to be unique to the
device, such as a GUID, or the make, model and serial number. Any
parameters that affect calibration, such as resolution, focus,
zoom, etc., may also be included in the name, uniquely identifying
each CameraInfo file.
Beginning with Electric Emys, the camera name can be resolved as
part of the URL, allowing direct access to device-specific
calibration information.
@par Uniform Resource Locator
The location for getting and saving calibration data is expressed
by Uniform Resource Locator. The driver defines a URL via the
CameraInfoManager::CameraInfoManager constructor or the
loadCameraInfo() method. Many drivers provide a @c
~camera_info_url parameter so users may customize this URL, but
that is handled outside this class.
Typically, cameras store calibration information in a file, which
can be in any format supported by @c camera_calibration_parsers.
Currently, that includes YAML and Videre INI files, identified by
their .yaml or .ini extensions as shown in the examples. These
file formats are described here:
- http://www.ros.org/wiki/camera_calibration_parsers#File_formats
Example URL syntax:
- file:///full/path/to/local/file.yaml
- file:///full/path/to/videre/file.ini
- package://camera_info_manager/tests/test_calibration.yaml
- package://ros_package_name/calibrations/camera3.yaml
The @c file: URL specifies a full path name in the local system.
The @c package: URL is handled the same as @c file:, except the
path name is resolved relative to the location of the named ROS
package, which @em must be reachable via @c $ROS_PACKAGE_PATH.
Beginning with Electric Emys, the URL may contain substitution
variables delimited by <tt>${...}</tt>, including:
- @c ${NAME} resolved to the current camera name defined by the
device driver.
- @c ${ROS_HOME} resolved to the @c $ROS_HOME environment variable
if defined, <tt>~/.ros</tt> if not.
Resolution is done in a single pass through the URL string.
Variable values containing substitutable strings are not resolved
recursively. Unrecognized variable names are treated literally
with no substitution, but an error is logged.
Examples with variable substitution:
- package://my_cameras/calibrations/${NAME}.yaml
- file://${ROS_HOME}/camera_info/left_front_camera.yaml
In C-turtle and Diamondback, if the URL was empty, no calibration
data were loaded, and any data provided via `set_camera_info`
would be stored in:
- file:///tmp/calibration_${NAME}.yaml
Beginning in Electric, the default URL changed to:
- file://${ROS_HOME}/camera_info/${NAME}.yaml.
If that file exists, its contents are used. Any new calibration
will be stored there, missing parent directories being created if
necessary and possible.
@par Loading Calibration Data
Prior to Fuerte, calibration information was loaded in the
constructor, and again each time the URL or camera name was
updated. This frequently caused logging of confusing and
misleading error messages.
Beginning in Fuerte, camera_info_manager loads nothing until the
@c loadCameraInfo(), @c isCalibrated() or @c getCameraInfo()
method is called. That suppresses bogus error messages, but allows
(valid) load errors to occur during the first @c getCameraInfo(),
or @c isCalibrated(). To avoid that, do an explicit @c
loadCameraInfo() first.
*/
class CameraInfoManager
{
public:
CameraInfoManager(ros::NodeHandle nh,
const std::string &cname="camera",
const std::string &url="");
sensor_msgs::CameraInfo getCameraInfo(void);
bool isCalibrated(void);
bool loadCameraInfo(const std::string &url);
std::string resolveURL(const std::string &url,
const std::string &cname);
bool setCameraName(const std::string &cname);
bool setCameraInfo(const sensor_msgs::CameraInfo &camera_info);
bool validateURL(const std::string &url);
private:
// recognized URL types
typedef enum
{
// supported URLs
URL_empty = 0, // empty string
URL_file, // file:
URL_package, // package:
// URLs not supported
URL_invalid, // anything >= is invalid
URL_flash, // flash:
} url_type_t;
// private methods
std::string getPackageFileName(const std::string &url);
bool loadCalibration(const std::string &url,
const std::string &cname);
bool loadCalibrationFile(const std::string &filename,
const std::string &cname);
url_type_t parseURL(const std::string &url);
bool saveCalibration(const sensor_msgs::CameraInfo &new_info,
const std::string &url,
const std::string &cname);
bool saveCalibrationFile(const sensor_msgs::CameraInfo &new_info,
const std::string &filename,
const std::string &cname);
bool setCameraInfoService(sensor_msgs::SetCameraInfo::Request &req,
sensor_msgs::SetCameraInfo::Response &rsp);
/** @brief mutual exclusion lock for private data
*
* This non-recursive mutex is only held for a short time while
* accessing or changing private class variables. To avoid
* deadlocks and contention, it is never held during I/O or while
* invoking a callback. Most private methods operate on copies of
* class variables, keeping the mutex hold time short.
*/
boost::mutex mutex_;
// private data
ros::NodeHandle nh_; ///< node handle for service
ros::ServiceServer info_service_; ///< set_camera_info service
std::string camera_name_; ///< camera name
std::string url_; ///< URL for calibration data
sensor_msgs::CameraInfo cam_info_; ///< current CameraInfo
bool loaded_cam_info_; ///< cam_info_ load attempted
}; // class CameraInfoManager
}; // namespace camera_info_manager
#endif // _CAMERA_INFO_MANAGER_H_
| 0 |
apollo_public_repos/apollo-platform/ros/image_common/camera_info_manager | apollo_public_repos/apollo-platform/ros/image_common/camera_info_manager/tests/test_calibration.yaml | image_width: 640
image_height: 480
camera_name: 08144361026320a0
camera_matrix:
rows: 3
cols: 3
data: [1168.68, 0, 295.015, 0, 1169.01, 252.247, 0, 0, 1]
distortion_model: plumb_bob
distortion_coefficients:
rows: 1
cols: 5
data: [-1.04482, 1.59252, -0.0196308, 0.0287906, 0]
rectification_matrix:
rows: 3
cols: 3
data: [1, 0, 0, 0, 1, 0, 0, 0, 1]
projection_matrix:
rows: 3
cols: 4
data: [1168.68, 0, 295.015, 0, 0, 1169.01, 252.247, 0, 0, 0, 1, 0] | 0 |
apollo_public_repos/apollo-platform/ros/image_common/camera_info_manager | apollo_public_repos/apollo-platform/ros/image_common/camera_info_manager/tests/unit_test.test | <!-- -*- mode: XML -*- -->
<!-- rostest launch file for camera_info_manager
This unit test uses rostest, because the camera_info_manager
constructor requires a node handle. Apart from needing a ROS
environment, it is completely self-contained.
$Id$
-->
<launch>
<!-- start unit-test node -->
<test pkg="camera_info_manager" type="unit_test" name="unit_test"
test-name="unit_test" time-limit="2.0" />
</launch>
| 0 |
apollo_public_repos/apollo-platform/ros/image_common/camera_info_manager | apollo_public_repos/apollo-platform/ros/image_common/camera_info_manager/tests/unit_test.cpp | /* $Id$ */
/*********************************************************************
* Software License Agreement (BSD License)
*
* Copyright (c) 2010 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.
*********************************************************************/
#include <unistd.h>
#include <stdlib.h>
#include <ros/ros.h>
#include <ros/package.h>
#include "camera_info_manager/camera_info_manager.h"
#include <sensor_msgs/distortion_models.h>
#include <string>
#include <gtest/gtest.h>
///////////////////////////////////////////////////////////////
// global test data
///////////////////////////////////////////////////////////////
namespace
{
const std::string g_package_name("camera_info_manager");
const std::string g_test_name("test_calibration");
const std::string g_package_filename("/tests/" + g_test_name +".yaml");
const std::string g_package_url("package://" + g_package_name
+ g_package_filename);
const std::string g_package_name_url("package://" + g_package_name
+ "/tests/${NAME}.yaml");
const std::string g_default_url("file://${ROS_HOME}/camera_info/${NAME}.yaml");
const std::string g_camera_name("08144361026320a0");
}
///////////////////////////////////////////////////////////////
// utility functions
///////////////////////////////////////////////////////////////
// compare CameraInfo fields that are saved and loaded for calibration
void compare_calibration(const sensor_msgs::CameraInfo &exp,
const sensor_msgs::CameraInfo &ci)
{
// check image size
EXPECT_EQ(exp.width, ci.width);
EXPECT_EQ(exp.height, ci.height);
// check distortion coefficients
EXPECT_EQ(exp.distortion_model, ci.distortion_model);
EXPECT_EQ(exp.D.size(), ci.D.size());
for (unsigned i = 0; i < ci.D.size(); ++i)
{
EXPECT_EQ(exp.D[i], ci.D[i]);
}
// check camera matrix
for (unsigned i = 0; i < ci.K.size(); ++i)
{
EXPECT_EQ(exp.K[i], ci.K[i]);
}
// check rectification matrix
for (unsigned i = 0; i < ci.R.size(); ++i)
{
EXPECT_EQ(exp.R[i], ci.R[i]);
}
// check projection matrix
for (unsigned i = 0; i < ci.P.size(); ++i)
{
EXPECT_EQ(exp.P[i], ci.P[i]);
}
}
// make sure this file does not exist
void delete_file(std::string filename)
{
int rc = unlink(filename.c_str());
if (rc != 0)
{
if (errno != ENOENT)
ROS_INFO_STREAM("unexpected unlink() error: " << errno);
}
}
void delete_default_file(void)
{
std::string ros_home("/tmp");
setenv("ROS_HOME", ros_home.c_str(), true);
std::string tmpFile(ros_home + "/camera_info/camera.yaml");
delete_file(tmpFile);
}
void do_system(const std::string &command)
{
int rc = system(command.c_str());
if (rc)
std::cout << command << " returns " << rc;
}
void delete_tmp_camera_info_directory(void)
{
do_system(std::string("rm -rf /tmp/camera_info"));
}
void make_tmp_camera_info_directory(void)
{
do_system(std::string("mkdir -p /tmp/camera_info"));
}
// These data must match the contents of test_calibration.yaml.
sensor_msgs::CameraInfo expected_calibration(void)
{
sensor_msgs::CameraInfo ci;
ci.width = 640u;
ci.height = 480u;
// set distortion coefficients
ci.distortion_model = sensor_msgs::distortion_models::PLUMB_BOB;
ci.D.resize(5);
ci.D[0] = -1.04482;
ci.D[1] = 1.59252;
ci.D[2] = -0.0196308;
ci.D[3] = 0.0287906;
ci.D[4] = 0.0;
// set camera matrix
ci.K[0] = 1168.68;
ci.K[1] = 0.0;
ci.K[2] = 295.015;
ci.K[3] = 0.0;
ci.K[4] = 1169.01;
ci.K[5] = 252.247;
ci.K[6] = 0.0;
ci.K[7] = 0.0;
ci.K[8] = 1.0;
// set rectification matrix
ci.R[0] = 1.0;
ci.R[1] = 0.0;
ci.R[2] = 0.0;
ci.R[3] = 0.0;
ci.R[4] = 1.0;
ci.R[5] = 0.0;
ci.R[6] = 0.0;
ci.R[7] = 0.0;
ci.R[8] = 1.0;
// set projection matrix
ci.P[0] = ci.K[0];
ci.P[1] = ci.K[1];
ci.P[2] = ci.K[2];
ci.P[3] = 0.0;
ci.P[4] = ci.K[3];
ci.P[5] = ci.K[4];
ci.P[6] = ci.K[5];
ci.P[7] = 0.0;
ci.P[8] = ci.K[6];
ci.P[9] = ci.K[7];
ci.P[10] = ci.K[8];
ci.P[11] = 0.0;
return ci;
}
// issue SetCameraInfo service request
bool set_calibration(ros::NodeHandle node,
const sensor_msgs::CameraInfo &calib)
{
ros::ServiceClient client =
node.serviceClient<sensor_msgs::SetCameraInfo>("set_camera_info");
sensor_msgs::SetCameraInfo set_camera_info;
set_camera_info.request.camera_info = calib;
bool success;
EXPECT_TRUE((success = client.call(set_camera_info)));
return success;
}
// resolve URL string, result should be as expected
void check_url_substitution(ros::NodeHandle node,
const std::string &url,
const std::string &exp_url,
const std::string &camera_name)
{
camera_info_manager::CameraInfoManager cinfo(node, camera_name, url);
std::string sub_url = cinfo.resolveURL(url, camera_name);
EXPECT_EQ(sub_url, exp_url);
}
///////////////////////////////////////////////////////////////
// Test cases
///////////////////////////////////////////////////////////////
// Test that valid camera names are accepted
TEST(CameraName, validNames)
{
ros::NodeHandle node;
camera_info_manager::CameraInfoManager cinfo(node);
EXPECT_TRUE(cinfo.setCameraName(std::string("a")));
EXPECT_TRUE(cinfo.setCameraName(std::string("1")));
EXPECT_TRUE(cinfo.setCameraName(std::string("_")));
EXPECT_TRUE(cinfo.setCameraName(std::string("abcdefghijklmnopqrstuvwxyz")));
EXPECT_TRUE(cinfo.setCameraName(std::string("ABCDEFGHIJKLMNOPQRSTUVWXYZ")));
EXPECT_TRUE(cinfo.setCameraName(std::string("0123456789")));
EXPECT_TRUE(cinfo.setCameraName(std::string("0123456789abcdef")));
EXPECT_TRUE(cinfo.setCameraName(std::string("A1")));
EXPECT_TRUE(cinfo.setCameraName(std::string("9z")));
EXPECT_TRUE(cinfo.setCameraName(std::string("08144361026320a0_640x480_mono8")));
}
// Test that invalid camera names are rejected
TEST(CameraName, invalidNames)
{
ros::NodeHandle node;
camera_info_manager::CameraInfoManager cinfo(node);
EXPECT_FALSE(cinfo.setCameraName(std::string("")));
EXPECT_FALSE(cinfo.setCameraName(std::string("-21")));
EXPECT_FALSE(cinfo.setCameraName(std::string("C++")));
EXPECT_FALSE(cinfo.setCameraName(std::string("file:///tmp/url.yaml")));
EXPECT_FALSE(cinfo.setCameraName(std::string("file://${INVALID}/xxx.yaml")));
}
// Test that valid URLs are accepted
TEST(UrlValidation, validURLs)
{
ros::NodeHandle node;
camera_info_manager::CameraInfoManager cinfo(node);
EXPECT_TRUE(cinfo.validateURL(std::string("")));
EXPECT_TRUE(cinfo.validateURL(std::string("file:///")));
EXPECT_TRUE(cinfo.validateURL(std::string("file:///tmp/url.yaml")));
EXPECT_TRUE(cinfo.validateURL(std::string("File:///tmp/url.ini")));
EXPECT_TRUE(cinfo.validateURL(std::string("FILE:///tmp/url.yaml")));
EXPECT_TRUE(cinfo.validateURL(g_default_url));
EXPECT_TRUE(cinfo.validateURL(g_package_url));
EXPECT_TRUE(cinfo.validateURL(std::string("package://no_such_package/calibration.yaml")));
EXPECT_TRUE(cinfo.validateURL(std::string("packAge://camera_info_manager/x")));
}
// Test that invalid URLs are rejected
TEST(UrlValidation, invalidURLs)
{
ros::NodeHandle node;
camera_info_manager::CameraInfoManager cinfo(node);
EXPECT_FALSE(cinfo.validateURL(std::string("file://")));
EXPECT_FALSE(cinfo.validateURL(std::string("flash:///")));
EXPECT_FALSE(cinfo.validateURL(std::string("html://ros.org/wiki/camera_info_manager")));
EXPECT_FALSE(cinfo.validateURL(std::string("package://")));
EXPECT_FALSE(cinfo.validateURL(std::string("package:///")));
EXPECT_FALSE(cinfo.validateURL(std::string("package://calibration.yaml")));
EXPECT_FALSE(cinfo.validateURL(std::string("package://camera_info_manager/")));
}
// Test ability to provide uncalibrated CameraInfo
TEST(GetInfo, uncalibrated)
{
ros::NodeHandle node;
delete_default_file();
camera_info_manager::CameraInfoManager cinfo(node);
EXPECT_FALSE(cinfo.isCalibrated());
sensor_msgs::CameraInfo ci(cinfo.getCameraInfo());
sensor_msgs::CameraInfo exp;
compare_calibration(exp, ci);
}
// Test ability to load calibrated CameraInfo
TEST(GetInfo, calibrated)
{
ros::NodeHandle node;
delete_default_file();
camera_info_manager::CameraInfoManager cinfo(node);
EXPECT_FALSE(cinfo.isCalibrated());
std::string pkgPath(ros::package::getPath(g_package_name));
std::string url("file://" + pkgPath + "/tests/test_calibration.yaml");
EXPECT_TRUE(cinfo.loadCameraInfo(url));
EXPECT_TRUE(cinfo.isCalibrated());
sensor_msgs::CameraInfo ci(cinfo.getCameraInfo());
sensor_msgs::CameraInfo exp(expected_calibration());
compare_calibration(exp, ci);
}
// Test ability to load calibrated CameraInfo from package
TEST(GetInfo, fromPackage)
{
ros::NodeHandle node;
camera_info_manager::CameraInfoManager cinfo(node);
EXPECT_TRUE(cinfo.loadCameraInfo(g_package_url));
EXPECT_TRUE(cinfo.isCalibrated());
sensor_msgs::CameraInfo ci(cinfo.getCameraInfo());
sensor_msgs::CameraInfo exp(expected_calibration());
compare_calibration(exp, ci);
}
// Test ability to access named calibrated CameraInfo from package
TEST(GetInfo, fromPackageWithName)
{
ros::NodeHandle node;
camera_info_manager::CameraInfoManager cinfo(node, g_test_name,
g_package_name_url);
EXPECT_TRUE(cinfo.isCalibrated());
sensor_msgs::CameraInfo ci(cinfo.getCameraInfo());
sensor_msgs::CameraInfo exp(expected_calibration());
compare_calibration(exp, ci);
}
// Test load of unresolved "package:" URL files
TEST(GetInfo, unresolvedLoads)
{
ros::NodeHandle node;
camera_info_manager::CameraInfoManager cinfo(node);
EXPECT_FALSE(cinfo.loadCameraInfo(std::string("package://")));
EXPECT_FALSE(cinfo.isCalibrated());
EXPECT_FALSE(cinfo.loadCameraInfo(std::string("package:///calibration.yaml")));
EXPECT_FALSE(cinfo.isCalibrated());
EXPECT_FALSE(cinfo.loadCameraInfo(std::string("package://no_such_package/calibration.yaml")));
EXPECT_FALSE(cinfo.isCalibrated());
EXPECT_FALSE(cinfo.loadCameraInfo(std::string("package://camera_info_manager/no_such_file.yaml")));
EXPECT_FALSE(cinfo.isCalibrated());
}
// Test load of "package:" URL after changing name
TEST(GetInfo, nameChange)
{
ros::NodeHandle node;
const std::string missing_file("no_such_file");
// first declare using non-existent camera name
camera_info_manager::CameraInfoManager cinfo(node, missing_file,
g_package_name_url);
EXPECT_FALSE(cinfo.isCalibrated());
// set name so it resolves to a test file that does exist
EXPECT_TRUE(cinfo.setCameraName(g_test_name));
EXPECT_TRUE(cinfo.isCalibrated());
sensor_msgs::CameraInfo ci(cinfo.getCameraInfo());
sensor_msgs::CameraInfo exp(expected_calibration());
compare_calibration(exp, ci);
}
// Test load of invalid CameraInfo URLs
TEST(GetInfo, invalidLoads)
{
ros::NodeHandle node;
camera_info_manager::CameraInfoManager cinfo(node);
EXPECT_FALSE(cinfo.loadCameraInfo(std::string("flash:///")));
EXPECT_FALSE(cinfo.isCalibrated());
EXPECT_FALSE(cinfo.loadCameraInfo(std::string("html://ros.org/wiki/camera_info_manager")));
EXPECT_FALSE(cinfo.isCalibrated());
sensor_msgs::CameraInfo ci(cinfo.getCameraInfo());
sensor_msgs::CameraInfo exp;
compare_calibration(exp, ci);
}
// Test ability to set CameraInfo directly
TEST(SetInfo, setCameraInfo)
{
ros::NodeHandle node;
camera_info_manager::CameraInfoManager cinfo(node);
// issue calibration service request
sensor_msgs::CameraInfo exp(expected_calibration());
bool success = cinfo.setCameraInfo(exp);
EXPECT_TRUE(success);
// only check results if the service succeeded, avoiding confusing
// and redundant failure messages
if (success)
{
// check that it worked
EXPECT_TRUE(cinfo.isCalibrated());
sensor_msgs::CameraInfo ci = cinfo.getCameraInfo();
compare_calibration(exp, ci);
}
}
// Test ability to set calibrated CameraInfo
TEST(SetInfo, setCalibration)
{
ros::NodeHandle node;
camera_info_manager::CameraInfoManager cinfo(node);
// issue calibration service request
sensor_msgs::CameraInfo exp(expected_calibration());
bool success = set_calibration(node, exp);
// only check results if the service succeeded, avoiding confusing
// and redundant failure messages
if (success)
{
// check that it worked
EXPECT_TRUE(cinfo.isCalibrated());
sensor_msgs::CameraInfo ci = cinfo.getCameraInfo();
compare_calibration(exp, ci);
}
}
// Test ability to save calibrated CameraInfo in default URL
TEST(SetInfo, saveCalibrationDefault)
{
ros::NodeHandle node;
sensor_msgs::CameraInfo exp(expected_calibration());
bool success;
// Set ${ROS_HOME} to /tmp, then delete the /tmp/camera_info
// directory and everything in it.
setenv("ROS_HOME", "/tmp", true);
delete_tmp_camera_info_directory();
{
// create instance to save calibrated data
camera_info_manager::CameraInfoManager cinfo(node);
EXPECT_FALSE(cinfo.isCalibrated());
// issue calibration service request
success = set_calibration(node, exp);
EXPECT_TRUE(cinfo.isCalibrated());
}
// only check results if the service succeeded, avoiding confusing
// and redundant failure messages
if (success)
{
// create a new instance to load saved calibration
camera_info_manager::CameraInfoManager cinfo2(node);
EXPECT_TRUE(cinfo2.isCalibrated());
if (cinfo2.isCalibrated())
{
sensor_msgs::CameraInfo ci(cinfo2.getCameraInfo());
compare_calibration(exp, ci);
}
}
}
// Test ability to save calibrated CameraInfo to default location with
// explicit camera name
TEST(SetInfo, saveCalibrationCameraName)
{
ros::NodeHandle node;
sensor_msgs::CameraInfo exp(expected_calibration());
bool success;
// set ${ROS_HOME} to /tmp, delete the calibration file
std::string ros_home("/tmp");
setenv("ROS_HOME", ros_home.c_str(), true);
std::string tmpFile(ros_home + "/camera_info/" + g_camera_name + ".yaml");
delete_file(tmpFile);
{
// create instance to save calibrated data
camera_info_manager::CameraInfoManager cinfo(node, g_camera_name);
success = set_calibration(node, exp);
EXPECT_TRUE(cinfo.isCalibrated());
}
// only check results if the service succeeded, avoiding confusing
// and redundant failure messages
if (success)
{
// create a new instance to load saved calibration
camera_info_manager::CameraInfoManager cinfo2(node);
std::string url = "file://" + tmpFile;
cinfo2.loadCameraInfo(std::string(url));
EXPECT_TRUE(cinfo2.isCalibrated());
if (cinfo2.isCalibrated())
{
sensor_msgs::CameraInfo ci(cinfo2.getCameraInfo());
compare_calibration(exp, ci);
}
}
}
// Test ability to save calibrated CameraInfo in a file
TEST(SetInfo, saveCalibrationFile)
{
return;
ros::NodeHandle node;
sensor_msgs::CameraInfo exp(expected_calibration());
std::string cname("camera");
std::string tmpFile("/tmp/camera_info_manager_calibration_test.yaml");
std::string url = "file://" + tmpFile;
bool success;
// first, delete the file
delete_file(tmpFile);
{
// create instance to save calibrated data
camera_info_manager::CameraInfoManager cinfo(node, cname, url);
success = set_calibration(node, exp);
EXPECT_TRUE(cinfo.isCalibrated());
}
// only check results if the service succeeded, avoiding confusing
// and redundant failure messages
if (success)
{
// create a new instance to load saved calibration
camera_info_manager::CameraInfoManager cinfo2(node, cname, url);
EXPECT_TRUE(cinfo2.isCalibrated());
if (cinfo2.isCalibrated())
{
sensor_msgs::CameraInfo ci(cinfo2.getCameraInfo());
compare_calibration(exp, ci);
}
}
}
// Test ability to save calibrated CameraInfo in a package
// (needs write access).
TEST(SetInfo, saveCalibrationPackage)
{
ros::NodeHandle node;
sensor_msgs::CameraInfo exp(expected_calibration());
std::string pkgPath(ros::package::getPath(g_package_name));
std::string filename(pkgPath + g_package_filename);
bool success;
// first, delete the file
delete_file(filename);
{
// create instance to save calibrated data
camera_info_manager::CameraInfoManager cinfo(node, g_camera_name,
g_package_url);
success = set_calibration(node, exp);
EXPECT_TRUE(cinfo.isCalibrated());
}
// only check results if the service succeeded, avoiding confusing
// and redundant failure messages
if (success)
{
// create a new instance to load saved calibration
camera_info_manager::CameraInfoManager cinfo2(node, g_camera_name,
g_package_url);
EXPECT_TRUE(cinfo2.isCalibrated());
if (cinfo2.isCalibrated())
{
sensor_msgs::CameraInfo ci(cinfo2.getCameraInfo());
compare_calibration(exp, ci);
}
}
}
TEST(UrlSubstitution, cameraName)
{
ros::NodeHandle node;
std::string name_url;
std::string exp_url;
// resolve a GUID camera name
name_url = "package://" + g_package_name + "/tests/${NAME}.yaml";
exp_url = "package://" + g_package_name + "/tests/" + g_camera_name + ".yaml";
check_url_substitution(node, name_url, exp_url, g_camera_name);
// substitute camera name "test"
name_url = "package://" + g_package_name + "/tests/${NAME}_calibration.yaml";
std::string test_name("test");
exp_url = "package://" + g_package_name + "/tests/" + test_name
+ "_calibration.yaml";
check_url_substitution(node, name_url, exp_url, test_name);
// with an '_' in the name
test_name = "camera_1024x768";
exp_url = "package://" + g_package_name + "/tests/" + test_name
+ "_calibration.yaml";
check_url_substitution(node, name_url, exp_url, test_name);
// substitute empty camera name
name_url = "package://" + g_package_name + "/tests/${NAME}_calibration.yaml";
std::string empty_name("");
exp_url = "package://" + g_package_name + "/tests/" + empty_name
+ "_calibration.yaml";
check_url_substitution(node, name_url, exp_url, empty_name);
// substitute test camera calibration from this package
check_url_substitution(node, g_package_name_url, g_package_url, g_test_name);
}
TEST(UrlSubstitution, rosHome)
{
ros::NodeHandle node;
std::string name_url;
std::string exp_url;
char *home_env = getenv("HOME");
std::string home(home_env);
// resolve ${ROS_HOME} with environment variable undefined
unsetenv("ROS_HOME");
name_url = "file://${ROS_HOME}/camera_info/test_camera.yaml";
exp_url = "file://" + home + "/.ros/camera_info/test_camera.yaml";
check_url_substitution(node, name_url, exp_url, g_camera_name);
// resolve ${ROS_HOME} with environment variable defined
setenv("ROS_HOME", "/my/ros/home", true);
name_url = "file://${ROS_HOME}/camera_info/test_camera.yaml";
exp_url = "file:///my/ros/home/camera_info/test_camera.yaml";
check_url_substitution(node, name_url, exp_url, g_camera_name);
}
TEST(UrlSubstitution, unmatchedDollarSigns)
{
ros::NodeHandle node;
// test for "$$" in the URL (NAME should be resolved)
std::string name_url("file:///tmp/$${NAME}.yaml");
std::string exp_url("file:///tmp/$" + g_camera_name + ".yaml");
check_url_substitution(node, name_url, exp_url, g_camera_name);
// test for "$" in middle of string
name_url = "file:///$whatever.yaml";
check_url_substitution(node, name_url, name_url, g_camera_name);
// test for "$$" in middle of string
name_url = "file:///something$$whatever.yaml";
check_url_substitution(node, name_url, name_url, g_camera_name);
// test for "$$" at end of string
name_url = "file:///$$";
check_url_substitution(node, name_url, name_url, g_camera_name);
}
TEST(UrlSubstitution, emptyURL)
{
// test that empty URL is handled correctly
ros::NodeHandle node;
std::string empty_url("");
check_url_substitution(node, empty_url, empty_url, g_camera_name);
}
TEST(UrlSubstitution, invalidVariables)
{
ros::NodeHandle node;
std::string name_url;
// missing "{...}"
name_url = "file:///tmp/$NAME.yaml";
check_url_substitution(node, name_url, name_url, g_camera_name);
// invalid substitution variable name
name_url = "file:///tmp/${INVALID}/calibration.yaml";
check_url_substitution(node, name_url, name_url, g_camera_name);
// truncated substitution variable
name_url = "file:///tmp/${NAME";
check_url_substitution(node, name_url, name_url, g_camera_name);
// missing substitution variable
name_url = "file:///tmp/${}";
check_url_substitution(node, name_url, name_url, g_camera_name);
// no exception thrown for single "$" at end of string
name_url = "file:///$";
check_url_substitution(node, name_url, name_url, g_camera_name);
}
// Run all the tests that were declared with TEST()
int main(int argc, char **argv)
{
ros::init(argc, argv, "camera_info_manager_unit_test");
testing::InitGoogleTest(&argc, argv);
// create asynchronous thread for handling service requests
ros::AsyncSpinner spinner(1);
spinner.start();
// run the tests in this thread
return RUN_ALL_TESTS();
}
| 0 |
apollo_public_repos/apollo-platform/ros/image_common/camera_info_manager | apollo_public_repos/apollo-platform/ros/image_common/camera_info_manager/src/camera_info_manager.cpp | /* $Id$ */
/*********************************************************************
* Software License Agreement (BSD License)
*
* Copyright (c) 2010-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.
*********************************************************************/
#include <string>
#include <locale>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <ros/ros.h>
#include <ros/package.h>
#include <boost/algorithm/string.hpp>
#include <camera_calibration_parsers/parse.h>
#include "camera_info_manager/camera_info_manager.h"
/** @file
@brief CameraInfo Manager implementation
Provides CameraInfo, handles the SetCameraInfo service requests,
saves and restores sensor_msgs/CameraInfo data.
@author Jack O'Quin
*/
namespace camera_info_manager
{
using namespace camera_calibration_parsers;
/** URL to use when no other is defined. */
const std::string
default_camera_info_url = "file://${ROS_HOME}/camera_info/${NAME}.yaml";
/** Constructor
*
* @param nh node handle, normally for the driver's streaming name
* space ("camera"). The service name is relative to this
* handle. Nodes supporting multiple cameras may use
* subordinate names, like "left/camera" and "right/camera".
* @param cname default camera name
* @param url default Uniform Resource Locator for loading and saving data.
*/
CameraInfoManager::CameraInfoManager(ros::NodeHandle nh,
const std::string &cname,
const std::string &url):
nh_(nh),
camera_name_(cname),
url_(url),
loaded_cam_info_(false)
{
// register callback for camera calibration service request
info_service_ = nh_.advertiseService("set_camera_info",
&CameraInfoManager::setCameraInfoService, this);
}
/** Get the current CameraInfo data.
*
* If CameraInfo has not yet been loaded, an attempt must be made
* here. To avoid that, ensure that loadCameraInfo() ran previously.
* If the load is attempted but fails, an empty CameraInfo will be
* supplied.
*
* The matrices are all zeros if no calibration is available. The
* image pipeline handles that as uncalibrated data.
*
* @warning The caller @em must fill in the message Header of the
* CameraInfo returned. The time stamp and frame_id should
* normally be the same as the corresponding Image message
* Header fields.
*/
sensor_msgs::CameraInfo CameraInfoManager::getCameraInfo(void)
{
while (ros::ok())
{
std::string cname;
std::string url;
{
boost::mutex::scoped_lock lock_(mutex_);
if (loaded_cam_info_)
{
return cam_info_; // all done
}
// load being attempted now
loaded_cam_info_ = true;
// copy the name and URL strings
url = url_;
cname = camera_name_;
} // release the lock
// attempt load without the lock, it is not recursive
loadCalibration(url, cname);
}
return sensor_msgs::CameraInfo();
}
/** Get file name corresponding to a @c package: URL.
*
* @param url a copy of the Uniform Resource Locator
* @return file name if package found, "" otherwise
*/
std::string CameraInfoManager::getPackageFileName(const std::string &url)
{
ROS_DEBUG_STREAM("camera calibration URL: " << url);
// Scan URL from after "package://" until next '/' and extract
// package name. The parseURL() already checked that it's present.
size_t prefix_len = std::string("package://").length();
size_t rest = url.find('/', prefix_len);
std::string package(url.substr(prefix_len, rest - prefix_len));
// Look up the ROS package path name.
std::string pkgPath(ros::package::getPath(package));
if (pkgPath.empty()) // package not found?
{
ROS_WARN_STREAM("unknown package: " << package << " (ignored)");
return pkgPath;
}
else
{
// Construct file name from package location and remainder of URL.
return pkgPath + url.substr(rest);
}
}
/** Is the current CameraInfo calibrated?
*
* If CameraInfo has not yet been loaded, an attempt must be made
* here. To avoid that, ensure that loadCameraInfo() ran previously.
* If the load failed, CameraInfo will be empty and this predicate
* will return false.
*
* @return true if the current CameraInfo is calibrated.
*/
bool CameraInfoManager::isCalibrated(void)
{
while (true)
{
std::string cname;
std::string url;
{
boost::mutex::scoped_lock lock_(mutex_);
if (loaded_cam_info_)
{
return (cam_info_.K[0] != 0.0);
}
// load being attempted now
loaded_cam_info_ = true;
// copy the name and URL strings
url = url_;
cname = camera_name_;
} // release the lock
// attempt load without the lock, it is not recursive
loadCalibration(url, cname);
}
}
/** Load CameraInfo calibration data (if any).
*
* @pre mutex_ unlocked
*
* @param url a copy of the Uniform Resource Locator
* @param cname is a copy of the camera_name_
* @return true if URL contains calibration data.
*
* sets cam_info_, if successful
*/
bool CameraInfoManager::loadCalibration(const std::string &url,
const std::string &cname)
{
bool success = false; // return value
const std::string resURL(resolveURL(url, cname));
url_type_t url_type = parseURL(resURL);
if (url_type != URL_empty)
{
ROS_INFO_STREAM("camera calibration URL: " << resURL);
}
switch (url_type)
{
case URL_empty:
{
ROS_INFO("using default calibration URL");
success = loadCalibration(default_camera_info_url, cname);
break;
}
case URL_file:
{
success = loadCalibrationFile(resURL.substr(7), cname);
break;
}
case URL_flash:
{
ROS_WARN("[CameraInfoManager] reading from flash not implemented yet");
break;
}
case URL_package:
{
std::string filename(getPackageFileName(resURL));
if (!filename.empty())
success = loadCalibrationFile(filename, cname);
break;
}
default:
{
ROS_ERROR_STREAM("Invalid camera calibration URL: " << resURL);
break;
}
}
return success;
}
/** Load CameraInfo calibration data from a file.
*
* @pre mutex_ unlocked
*
* @param filename containing CameraInfo to read
* @param cname is a copy of the camera_name_
* @return true if URL contains calibration data.
*
* Sets cam_info_, if successful
*/
bool CameraInfoManager::loadCalibrationFile(const std::string &filename,
const std::string &cname)
{
bool success = false;
ROS_DEBUG_STREAM("reading camera calibration from " << filename);
std::string cam_name;
sensor_msgs::CameraInfo cam_info;
if (readCalibration(filename, cam_name, cam_info))
{
if (cname != cam_name)
{
ROS_WARN_STREAM("[" << cname << "] does not match name "
<< cam_name << " in file " << filename);
}
success = true;
{
// lock only while updating cam_info_
boost::mutex::scoped_lock lock(mutex_);
cam_info_ = cam_info;
}
}
else
{
ROS_WARN_STREAM("Camera calibration file " << filename << " not found.");
}
return success;
}
/** Set a new URL and load its calibration data (if any).
*
* If multiple threads call this method simultaneously with different
* URLs, there is no guarantee which will prevail.
*
* @param url new Uniform Resource Locator for CameraInfo.
* @return true if new URL contains calibration data.
*
* @post @c loaded_cam_info_ true (meaning a load was attempted, even
* if it failed); @c cam_info_ updated, if successful.
*/
bool CameraInfoManager::loadCameraInfo(const std::string &url)
{
std::string cname;
{
boost::mutex::scoped_lock lock(mutex_);
url_ = url;
cname = camera_name_;
loaded_cam_info_ = true;
}
// load using copies of the parameters, no need to hold the lock
return loadCalibration(url, cname);
}
/** Resolve Uniform Resource Locator string.
*
* @param url a copy of the Uniform Resource Locator, which may
* include <tt>${...}</tt> substitution variables.
* @param cname is a copy of the camera_name_
*
* @return a copy of the URL with any variable information resolved.
*/
std::string CameraInfoManager::resolveURL(const std::string &url,
const std::string &cname)
{
std::string resolved;
size_t rest = 0;
while (true)
{
// find the next '$' in the URL string
size_t dollar = url.find('$', rest);
if (dollar >= url.length())
{
// no more variables left in the URL
resolved += url.substr(rest);
break;
}
// copy characters up to the next '$'
resolved += url.substr(rest, dollar-rest);
if (url.substr(dollar+1, 1) != "{")
{
// no '{' follows, so keep the '$'
resolved += "$";
}
else if (url.substr(dollar+1, 6) == "{NAME}")
{
// substitute camera name
resolved += cname;
dollar += 6;
}
else if (url.substr(dollar+1, 10) == "{ROS_HOME}")
{
// substitute $ROS_HOME
std::string ros_home;
char *ros_home_env;
if ((ros_home_env = getenv("ROS_HOME")))
{
// use environment variable
ros_home = ros_home_env;
}
else if ((ros_home_env = getenv("HOME")))
{
// use "$HOME/.ros"
ros_home = ros_home_env;
ros_home += "/.ros";
}
resolved += ros_home;
dollar += 10;
}
else
{
// not a valid substitution variable
ROS_ERROR_STREAM("[CameraInfoManager]"
" invalid URL substitution (not resolved): "
<< url);
resolved += "$"; // keep the bogus '$'
}
// look for next '$'
rest = dollar + 1;
}
return resolved;
}
/** Parse calibration Uniform Resource Locator.
*
* @param url string to parse
* @return URL type
*
* @note Recognized but unsupported URL types have enum values >= URL_invalid.
*/
CameraInfoManager::url_type_t CameraInfoManager::parseURL(const std::string &url)
{
if (url == "")
{
return URL_empty;
}
if (boost::iequals(url.substr(0, 8), "file:///"))
{
return URL_file;
}
if (boost::iequals(url.substr(0, 9), "flash:///"))
{
return URL_flash;
}
if (boost::iequals(url.substr(0, 10), "package://"))
{
// look for a '/' following the package name, make sure it is
// there, the name is not empty, and something follows it
size_t rest = url.find('/', 10);
if (rest < url.length()-1 && rest > 10)
return URL_package;
}
return URL_invalid;
}
/** Save CameraInfo calibration data.
*
* @pre mutex_ unlocked
*
* @param new_info contains CameraInfo to save
* @param url is a copy of the URL storage location (if empty, use
* @c file://${ROS_HOME}/camera_info/${NAME}.yaml)
* @param cname is a copy of the camera_name_
* @return true, if successful
*/
bool
CameraInfoManager::saveCalibration(const sensor_msgs::CameraInfo &new_info,
const std::string &url,
const std::string &cname)
{
bool success = false;
const std::string resURL(resolveURL(url, cname));
switch (parseURL(resURL))
{
case URL_empty:
{
// store using default file name
success = saveCalibration(new_info, default_camera_info_url, cname);
break;
}
case URL_file:
{
success = saveCalibrationFile(new_info, resURL.substr(7), cname);
break;
}
case URL_package:
{
std::string filename(getPackageFileName(resURL));
if (!filename.empty())
success = saveCalibrationFile(new_info, filename, cname);
break;
}
default:
{
// invalid URL, save to default location
ROS_ERROR_STREAM("invalid url: " << resURL << " (ignored)");
success = saveCalibration(new_info, default_camera_info_url, cname);
break;
}
}
return success;
}
/** Save CameraInfo calibration data to a file.
*
* @pre mutex_ unlocked
*
* @param new_info contains CameraInfo to save
* @param filename is local file to store data
* @param cname is a copy of the camera_name_
* @return true, if successful
*/
bool
CameraInfoManager::saveCalibrationFile(const sensor_msgs::CameraInfo &new_info,
const std::string &filename,
const std::string &cname)
{
ROS_INFO_STREAM("writing calibration data to " << filename);
// isolate the name of the containing directory
size_t last_slash = filename.rfind('/');
if (last_slash >= filename.length())
{
// No slash in the name. This should never happen, the URL
// parser ensures there is at least one '/' at the beginning.
ROS_ERROR_STREAM("filename [" << filename << "] has no '/'");
return false; // not a valid URL
}
// make sure the directory exists and is writable
std::string dirname(filename.substr(0, last_slash+1));
struct stat stat_data;
int rc = stat(dirname.c_str(), &stat_data);
if (rc != 0)
{
if (errno == ENOENT)
{
// directory does not exist, try to create it and its parents
std::string command("mkdir -p " + dirname);
rc = system(command.c_str());
if (rc != 0)
{
// mkdir failed
ROS_ERROR_STREAM("unable to create path to directory ["
<< dirname << "]");
return false;
}
}
else
{
// not accessible, or something screwy
ROS_ERROR_STREAM("directory [" << dirname << "] not accessible");
return false;
}
}
else if (!S_ISDIR(stat_data.st_mode))
{
// dirname exists but is not a directory
ROS_ERROR_STREAM("[" << dirname << "] is not a directory");
return false;
}
// Directory exists and is accessible. Permissions might still be bad.
// Currently, writeCalibration() always returns true no matter what
// (ros-pkg ticket #5010).
return writeCalibration(filename, cname, new_info);
}
/** Callback for SetCameraInfo request.
*
* Always updates cam_info_ class variable, even if save fails.
*
* @param req SetCameraInfo request message
* @param rsp SetCameraInfo response message
* @return true if message handled
*/
bool
CameraInfoManager::setCameraInfoService(sensor_msgs::SetCameraInfo::Request &req,
sensor_msgs::SetCameraInfo::Response &rsp)
{
// copies of class variables needed for saving calibration
std::string url_copy;
std::string cname;
{
boost::mutex::scoped_lock lock(mutex_);
cam_info_ = req.camera_info;
url_copy = url_;
cname = camera_name_;
loaded_cam_info_ = true;
}
if (!nh_.ok())
{
ROS_ERROR("set_camera_info service called, but driver not running.");
rsp.status_message = "Camera driver not running.";
rsp.success = false;
return false;
}
rsp.success = saveCalibration(req.camera_info, url_copy, cname);
if (!rsp.success)
rsp.status_message = "Error storing camera calibration.";
return true;
}
/** Set a new camera name.
*
* @param cname new camera name to use for saving calibration data
*
* @return true if new name has valid syntax; valid names contain only
* alphabetic, numeric, or '_' characters.
*
* @post @c cam_name_ updated, if valid; since it may affect the URL,
* @c cam_info_ will be reloaded before being used again.
*/
bool CameraInfoManager::setCameraName(const std::string &cname)
{
// the camera name may not be empty
if (cname.empty())
return false;
// validate the camera name characters
for (unsigned i = 0; i < cname.size(); ++i)
{
if (!isalnum(cname[i]) && cname[i] != '_')
return false;
}
// The name is valid, so update our private copy. Since the new
// name might cause the existing URL to resolve somewhere else,
// force @c cam_info_ to be reloaded before being used again.
{
boost::mutex::scoped_lock lock(mutex_);
camera_name_ = cname;
loaded_cam_info_ = false;
}
return true;
}
/** Set the camera info manually
*
* @param camera_info new camera calibration data
*
* @return true if new camera info is set
*
* @post @c cam_info_ updated, if valid;
*/
bool CameraInfoManager::setCameraInfo(const sensor_msgs::CameraInfo &camera_info)
{
boost::mutex::scoped_lock lock(mutex_);
cam_info_ = camera_info;
loaded_cam_info_ = true;
return true;
}
/** Validate URL syntax.
*
* @param url Uniform Resource Locator to check
*
* @return true if URL syntax is supported by CameraInfoManager
* (although the resource need not actually exist)
*/
bool CameraInfoManager::validateURL(const std::string &url)
{
std::string cname; // copy of camera name
{
boost::mutex::scoped_lock lock(mutex_);
cname = camera_name_;
} // release the lock
url_type_t url_type = parseURL(resolveURL(url, cname));
return (url_type < URL_invalid);
}
} // namespace camera_info_manager
| 0 |
apollo_public_repos/apollo-platform/ros/image_common | apollo_public_repos/apollo-platform/ros/image_common/camera_calibration_parsers/CMakeLists.txt | cmake_minimum_required(VERSION 2.8)
project(camera_calibration_parsers)
find_package(catkin REQUIRED sensor_msgs rosconsole roscpp roscpp_serialization)
find_package(PythonLibs REQUIRED)
if(PYTHONLIBS_VERSION_STRING VERSION_LESS 3)
find_package(Boost REQUIRED COMPONENTS filesystem python)
else()
find_package(Boost REQUIRED COMPONENTS filesystem python3)
endif()
include_directories(include ${catkin_INCLUDE_DIRS} ${Boost_INCLUDE_DIRS} ${PYTHON_INCLUDE_DIRS})
catkin_python_setup()
catkin_package(
INCLUDE_DIRS include
LIBRARIES ${PROJECT_NAME}
CATKIN_DEPENDS sensor_msgs
)
find_package(PkgConfig)
if (ANDROID)
find_package(yaml-cpp)
add_definitions(-DHAVE_NEW_YAMLCPP)
else()
pkg_check_modules(YAML_CPP yaml-cpp)
if(${YAML_CPP_VERSION} VERSION_GREATER 0.5)
add_definitions(-DHAVE_NEW_YAMLCPP)
endif()
link_directories(${YAML_CPP_LIBRARY_DIRS})
endif()
include_directories(${YAML_CPP_INCLUDE_DIRS})
# define the library
add_library(${PROJECT_NAME}
src/parse.cpp
src/parse_ini.cpp
src/parse_yml.cpp
)
add_library(${PROJECT_NAME}_wrapper
src/parse_wrapper.cpp)
target_link_libraries(${PROJECT_NAME} ${catkin_LIBRARIES} ${YAML_CPP_LIBRARIES} ${Boost_FILESYSTEM_LIBRARY})
target_link_libraries(${PROJECT_NAME}_wrapper ${PROJECT_NAME} ${catkin_LIBRARIES} ${Boost_LIBRARIES} ${PYTHON_LIBRARIES})
# Don't prepend wrapper library name with lib and add to Python libs.
set_target_properties(${PROJECT_NAME}_wrapper PROPERTIES
PREFIX ""
LIBRARY_OUTPUT_DIRECTORY ${CATKIN_DEVEL_PREFIX}/${CATKIN_PACKAGE_PYTHON_DESTINATION}
)
add_dependencies(${PROJECT_NAME} ${catkin_EXPORTED_TARGETS})
install(
TARGETS ${PROJECT_NAME}
DESTINATION ${CATKIN_PACKAGE_LIB_DESTINATION}
COMPONENT main
)
install(
DIRECTORY include/${PROJECT_NAME}/
DESTINATION ${CATKIN_PACKAGE_INCLUDE_DESTINATION}
)
# define the exe to convert
add_executable(convert src/convert.cpp)
target_link_libraries(convert ${PROJECT_NAME} ${rosconsole_LIBRARIES})
install(
TARGETS convert
DESTINATION ${CATKIN_PACKAGE_BIN_DESTINATION}
)
install(TARGETS ${PROJECT_NAME}_wrapper
DESTINATION ${CATKIN_PACKAGE_PYTHON_DESTINATION}
)
if(CATKIN_ENABLE_TESTING)
add_subdirectory(test)
endif()
| 0 |
apollo_public_repos/apollo-platform/ros/image_common | apollo_public_repos/apollo-platform/ros/image_common/camera_calibration_parsers/package.xml | <package>
<name>camera_calibration_parsers</name>
<version>1.11.12</version>
<description>
camera_calibration_parsers contains routines for reading and writing camera calibration parameters.
</description>
<author>Patrick Mihelich</author>
<maintainer email="[email protected]">Jack O'Quin</maintainer>
<maintainer email="[email protected]">Vincent Rabaud</maintainer>
<license>BSD</license>
<url type="website">http://ros.org/wiki/camera_calibration_parsers</url>
<url type="bugtracker">https://github.com/ros-perception/image_common/issues</url>
<url type="repository">https://github.com/ros-perception/image_common</url>
<buildtool_depend>catkin</buildtool_depend>
<build_depend>boost</build_depend>
<build_depend>pkg-config</build_depend>
<build_depend>rosconsole</build_depend>
<build_depend>sensor_msgs</build_depend>
<build_depend>yaml-cpp</build_depend>
<build_depend>roscpp</build_depend>
<build_depend>roscpp_serialization</build_depend>
<run_depend>boost</run_depend>
<run_depend>sensor_msgs</run_depend>
<run_depend>yaml-cpp</run_depend>
<run_depend>roscpp</run_depend>
<run_depend>roscpp_serialization</run_depend>
<test_depend>rosbash</test_depend>
<test_depend>rosunit</test_depend>
</package>
| 0 |
apollo_public_repos/apollo-platform/ros/image_common | apollo_public_repos/apollo-platform/ros/image_common/camera_calibration_parsers/mainpage.dox | /**
\mainpage
\htmlinclude manifest.html
\b camera_calibration_parsers contains routines for reading and writing
camera calibration parameters. Two human-readable file formats are
supported: YAML and the Videre INI format.
\section codeapi Code API
- camera_calibration_parsers::writeCalibration - Write parameters to a file
- camera_calibration_parsers::readCalibration - Read parameters from a file
- camera_calibration_parsers::parseCalibration - Read parameters from an in-memory buffer
*/
| 0 |
apollo_public_repos/apollo-platform/ros/image_common | apollo_public_repos/apollo-platform/ros/image_common/camera_calibration_parsers/setup.py | # ! DO NOT MANUALLY INVOKE THIS setup.py, USE CATKIN INSTEAD
from distutils.core import setup
from catkin_pkg.python_setup import generate_distutils_setup
# fetch values from package.xml
setup_args = generate_distutils_setup(
packages=['camera_calibration_parsers'],
package_dir={'': 'src'})
setup(**setup_args)
| 0 |
apollo_public_repos/apollo-platform/ros/image_common | apollo_public_repos/apollo-platform/ros/image_common/camera_calibration_parsers/CHANGELOG.rst | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Changelog for package camera_calibration_parsers
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1.11.12 (2017-01-29)
--------------------
* Properly detect Boost Python 2 or 3
This fixes `#59 <https://github.com/ros-perception/image_common/issues/59>`_
* 1.11.11
* update changelogs
* Contributors: Vincent Rabaud
1.11.11 (2016-09-24)
--------------------
1.11.10 (2016-01-19)
--------------------
* Add install target for python wrapper library
* Only link against needed Boost libraries
9829b02 introduced a python dependency into find_package(Boost..) which
results in ${Boost_LIBRARIES} containing boost_python and such a
dependency to libpython at link time. With this patch we only link
against the needed libraries.
* Contributors: Jochen Sprickerhof, Vincent Rabaud
1.11.9 (2016-01-17)
-------------------
* Add python wrapper for readCalibration.
Reads .ini or .yaml calibration file and returns camera name and sensor_msgs/cameraInfo.
* Use $catkin_EXPORTED_TARGETS
* Contributors: Jochen Sprickerhof, Markus Roth
1.11.8 (2015-11-29)
-------------------
* Remove no-longer-neccessary flags to allow OS X to use 0.3 and 0.5 of yaml-cpp.
* remove buggy CMake message
* Contributors: Helen Oleynikova, Vincent Rabaud
1.11.7 (2015-07-28)
-------------------
* fix `#39 <https://github.com/ros-perception/image_common/issues/39>`_
* make sure test does not fail
* Contributors: Vincent Rabaud
1.11.6 (2015-07-16)
-------------------
* [camera_calibration_parsers] Better error message when calib file can't be written
* add rosbash as a test dependency
* add a test dependency now that we have tests
* parse distortion of arbitraty length in INI
This fixes `#33 <https://github.com/ros-perception/image_common/issues/33>`_
* add a test to parse INI calibration files with 5 or 8 D param
* Add yaml-cpp case for building on Android
* Contributors: Gary Servin, Isaac IY Saito, Vincent Rabaud
1.11.5 (2015-05-14)
-------------------
* Fix catkin_make failure (due to yaml-cpp deps) for mac os
* Contributors: Yifei Zhang
1.11.4 (2014-09-21)
-------------------
* fix bad yaml-cpp usage in certain conditions
fixes `#24 <https://github.com/ros-perception/image_common/issues/24>`_
* Contributors: Vincent Rabaud
1.11.3 (2014-05-19)
-------------------
1.11.2 (2014-02-13 08:32:06 +0100)
-----------------------------------
* add a dependency on pkg-config to have it work on Indigo
1.11.1 (2014-01-26 02:32:06 +0100)
-----------------------------------
* fix YAML CPP 0.5.x compatibility
| 0 |
apollo_public_repos/apollo-platform/ros/image_common/camera_calibration_parsers | apollo_public_repos/apollo-platform/ros/image_common/camera_calibration_parsers/test/CMakeLists.txt | file(COPY calib5.ini calib8.ini DESTINATION ${CATKIN_DEVEL_PREFIX}/${CATKIN_PACKAGE_SHARE_DESTINATION}/test)
catkin_add_nosetests(parser.py)
| 0 |
apollo_public_repos/apollo-platform/ros/image_common/camera_calibration_parsers | apollo_public_repos/apollo-platform/ros/image_common/camera_calibration_parsers/test/calib8.ini | [image]
width
640
height
480
[mono_left]
camera matrix
369.344588 0.000000 320.739078
0.000000 367.154330 203.592450
0.000000 0.000000 1.000000
distortion
0.189544 -0.018229 -0.000630 0.000054 -0.000212 0.543582 -0.027892 0.000000
rectification
1.000000 0.000000 0.000000
0.000000 1.000000 0.000000
0.000000 0.000000 1.000000
projection
262.927429 0.000000 320.984481 0.000000
0.000000 302.056213 188.592437 0.000000
0.000000 0.000000 1.000000 0.000000
| 0 |
apollo_public_repos/apollo-platform/ros/image_common/camera_calibration_parsers | apollo_public_repos/apollo-platform/ros/image_common/camera_calibration_parsers/test/parser.py | #!/usr/bin/env python
#
# Software License Agreement (BSD License)
#
# Copyright (c) 2009, Willow Garage, Inc.
# 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 Willow Garage nor the names of its
# 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.
import rosunit
import subprocess
import unittest
import os
from camera_calibration_parsers import readCalibration
class TestParser(unittest.TestCase):
def test_ini(self):
for files in [('calib5.ini', 'calib5.yaml'), ('calib8.ini', 'calib8.yaml')]:
for dir in [ '', './']:
p = subprocess.Popen('rosrun camera_calibration_parsers convert $(rospack find camera_calibration_parsers)/test/%s %s%s' % (files[0], dir, files[1]), shell=True, stderr=subprocess.PIPE)
out, err = p.communicate()
self.assertEqual(err, '')
def test_readCalibration(self):
script_dir = os.path.dirname(os.path.realpath(__file__))
camera_name, camera_info = readCalibration(os.path.join(script_dir, 'calib5.ini'))
self.assertEqual(camera_name, 'mono_left')
self.assertEqual(camera_info.height, 480)
self.assertEqual(camera_info.width, 640)
self.assertEqual(camera_info.P[0], 262.927429)
camera_name, camera_info = readCalibration(os.path.join(script_dir, 'calib8.ini'))
self.assertEqual(camera_info.distortion_model, 'rational_polynomial')
if __name__ == '__main__':
rosunit.unitrun('camera_calibration_parsers', 'parser', TestParser)
| 0 |
apollo_public_repos/apollo-platform/ros/image_common/camera_calibration_parsers | apollo_public_repos/apollo-platform/ros/image_common/camera_calibration_parsers/test/calib5.ini | [image]
width
640
height
480
[mono_left]
camera matrix
369.344588 0.000000 320.739078
0.000000 367.154330 203.592450
0.000000 0.000000 1.000000
distortion
0.189544 -0.018229 -0.000630 0.000054 -0.000212
rectification
1.000000 0.000000 0.000000
0.000000 1.000000 0.000000
0.000000 0.000000 1.000000
projection
262.927429 0.000000 320.984481 0.000000
0.000000 302.056213 188.592437 0.000000
0.000000 0.000000 1.000000 0.000000
| 0 |
apollo_public_repos/apollo-platform/ros/image_common/camera_calibration_parsers/include | apollo_public_repos/apollo-platform/ros/image_common/camera_calibration_parsers/include/camera_calibration_parsers/parse.h | /*********************************************************************
* Software License Agreement (BSD License)
*
* Copyright (c) 2009, Willow Garage, Inc.
* 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 Willow Garage nor the names of its
* 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 CAMERA_CALIBRATION_PARSERS_PARSE_H
#define CAMERA_CALIBRATION_PARSERS_PARSE_H
#include <string>
#include <sensor_msgs/CameraInfo.h>
/// @todo: use stream-based API, so no read/parse distinction
namespace camera_calibration_parsers {
/**
* \brief Write calibration parameters to a file.
*
* The file name extension (.yml, .yaml, or .ini) determines the output format.
*
* \param file_name File to write
* \param camera_name Name of the camera
* \param cam_info Camera parameters
*/
bool writeCalibration(const std::string& file_name, const std::string& camera_name,
const sensor_msgs::CameraInfo& cam_info);
/**
* \brief Read calibration parameters from a file.
*
* The file may be YAML or INI format.
*
* \param file_name File to read
* \param[out] camera_name Name of the camera
* \param[out] cam_info Camera parameters
*/
bool readCalibration(const std::string& file_name, std::string& camera_name,
sensor_msgs::CameraInfo& cam_info);
/**
* \brief Parse calibration parameters from a string in memory.
*
* \param buffer Calibration string
* \param format Format of calibration string, "yml" or "ini"
* \param[out] camera_name Name of the camera
* \param[out] cam_info Camera parameters
*/
bool parseCalibration(const std::string& buffer, const std::string& format,
std::string& camera_name, sensor_msgs::CameraInfo& cam_info);
} //namespace camera_calibration_parsers
#endif
| 0 |
apollo_public_repos/apollo-platform/ros/image_common/camera_calibration_parsers/include | apollo_public_repos/apollo-platform/ros/image_common/camera_calibration_parsers/include/camera_calibration_parsers/parse_ini.h | /*********************************************************************
* Software License Agreement (BSD License)
*
* Copyright (c) 2009, Willow Garage, Inc.
* 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 Willow Garage nor the names of its
* 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 CAMERA_CALIBRATION_PARSERS_PARSE_INI_H
#define CAMERA_CALIBRATION_PARSERS_PARSE_INI_H
#include <string>
#include <sensor_msgs/CameraInfo.h>
namespace camera_calibration_parsers {
/**
* \brief Write calibration parameters to a file in INI format.
*
* \param out Output stream to write to
* \param camera_name Name of the camera
* \param cam_info Camera parameters
*/
bool writeCalibrationIni(std::ostream& out, const std::string& camera_name,
const sensor_msgs::CameraInfo& cam_info);
/**
* \brief Read calibration parameters from an INI file.
*
* \param in Input stream to read from
* \param[out] camera_name Name of the camera
* \param[out] cam_info Camera parameters
*/
bool readCalibrationIni(std::istream& in, std::string& camera_name, sensor_msgs::CameraInfo& cam_info);
/**
* \brief Write calibration parameters to a file in INI format.
*
* \param file_name File to write
* \param camera_name Name of the camera
* \param cam_info Camera parameters
*/
bool writeCalibrationIni(const std::string& file_name, const std::string& camera_name,
const sensor_msgs::CameraInfo& cam_info);
/**
* \brief Read calibration parameters from an INI file.
*
* \param file_name File to read
* \param[out] camera_name Name of the camera
* \param[out] cam_info Camera parameters
*/
bool readCalibrationIni(const std::string& file_name, std::string& camera_name,
sensor_msgs::CameraInfo& cam_info);
/**
* \brief Parse calibration parameters from a string in memory of INI format.
*
* \param buffer Calibration string
* \param[out] camera_name Name of the camera
* \param[out] cam_info Camera parameters
*/
bool parseCalibrationIni(const std::string& buffer, std::string& camera_name,
sensor_msgs::CameraInfo& cam_info);
//bool readCalibrationIni
} //namespace camera_calibration_parsers
#endif
| 0 |
apollo_public_repos/apollo-platform/ros/image_common/camera_calibration_parsers/include | apollo_public_repos/apollo-platform/ros/image_common/camera_calibration_parsers/include/camera_calibration_parsers/parse_yml.h | /*********************************************************************
* Software License Agreement (BSD License)
*
* Copyright (c) 2009, Willow Garage, Inc.
* 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 Willow Garage nor the names of its
* 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 CAMERA_CALIBRATION_PARSERS_PARSE_YML_H
#define CAMERA_CALIBRATION_PARSERS_PARSE_YML_H
#include <string>
#include <istream>
#include <ostream>
#include <sensor_msgs/CameraInfo.h>
namespace camera_calibration_parsers {
/**
* \brief Write calibration parameters to a file in YAML format.
*
* \param out Output stream to write to
* \param camera_name Name of the camera
* \param cam_info Camera parameters
*/
bool writeCalibrationYml(std::ostream& out, const std::string& camera_name,
const sensor_msgs::CameraInfo& cam_info);
/**
* \brief Read calibration parameters from a YAML file.
*
* \param in Input stream to read from
* \param[out] camera_name Name of the camera
* \param[out] cam_info Camera parameters
*/
bool readCalibrationYml(std::istream& in, std::string& camera_name, sensor_msgs::CameraInfo& cam_info);
/**
* \brief Write calibration parameters to a file in YAML format.
*
* \param file_name File to write
* \param camera_name Name of the camera
* \param cam_info Camera parameters
*/
bool writeCalibrationYml(const std::string& file_name, const std::string& camera_name,
const sensor_msgs::CameraInfo& cam_info);
/**
* \brief Read calibration parameters from a YAML file.
*
* \param file_name File to read
* \param[out] camera_name Name of the camera
* \param[out] cam_info Camera parameters
*/
bool readCalibrationYml(const std::string& file_name, std::string& camera_name,
sensor_msgs::CameraInfo& cam_info);
} //namespace camera_calibration_parsers
#endif
| 0 |
apollo_public_repos/apollo-platform/ros/image_common/camera_calibration_parsers/include | apollo_public_repos/apollo-platform/ros/image_common/camera_calibration_parsers/include/camera_calibration_parsers/parse_wrapper.h | /*********************************************************************
* Software License Agreement (BSD License)
*
* 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 Willow Garage nor the names of its
* 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 CAMERA_CALIBRATION_PARSERS_PARSE_WRAPPER_H
#define CAMERA_CALIBRATION_PARSERS_PARSE_WRAPPER_H
#include <string>
#include <boost/python.hpp>
namespace camera_calibration_parsers {
boost::python::tuple readCalibrationWrapper(const std::string& file_name);
} //namespace camera_calibration_parsers
#endif
| 0 |
apollo_public_repos/apollo-platform/ros/image_common/camera_calibration_parsers | apollo_public_repos/apollo-platform/ros/image_common/camera_calibration_parsers/src/parse_wrapper.cpp | /*********************************************************************
* Software License Agreement (BSD License)
*
* 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 Willow Garage nor the names of its
* 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.
*********************************************************************/
#include "camera_calibration_parsers/parse.h"
#include "camera_calibration_parsers/parse_wrapper.h"
#include <boost/python.hpp>
#include <ros/serialization.h>
namespace camera_calibration_parsers {
/* Write a ROS message into a serialized string.
* @from https://github.com/galou/python_bindings_tutorial/blob/master/src/add_two_ints_wrapper.cpp#L27
*/
template <typename M>
std::string to_python(const M& msg)
{
size_t serial_size = ros::serialization::serializationLength(msg);
boost::shared_array<uint8_t> buffer(new uint8_t[serial_size]);
ros::serialization::OStream stream(buffer.get(), serial_size);
ros::serialization::serialize(stream, msg);
std::string str_msg;
str_msg.reserve(serial_size);
for (size_t i = 0; i < serial_size; ++i)
{
str_msg.push_back(buffer[i]);
}
return str_msg;
}
// Wrapper for readCalibration()
boost::python::tuple readCalibrationWrapper(const std::string& file_name)
{
std::string camera_name;
sensor_msgs::CameraInfo camera_info;
bool result = readCalibration(file_name, camera_name, camera_info);
std::string cam_info = to_python(camera_info);
return boost::python::make_tuple(result, camera_name, cam_info);
}
BOOST_PYTHON_MODULE(camera_calibration_parsers_wrapper)
{
boost::python::def("__readCalibrationWrapper", readCalibrationWrapper, boost::python::args("file_name"), "");
}
} //namespace camera_calibration_parsers
| 0 |
apollo_public_repos/apollo-platform/ros/image_common/camera_calibration_parsers | apollo_public_repos/apollo-platform/ros/image_common/camera_calibration_parsers/src/parse.cpp | /*********************************************************************
* Software License Agreement (BSD License)
*
* Copyright (c) 2009, Willow Garage, Inc.
* 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 Willow Garage nor the names of its
* 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.
*********************************************************************/
#include "camera_calibration_parsers/parse.h"
#include "camera_calibration_parsers/parse_ini.h"
#include "camera_calibration_parsers/parse_yml.h"
#include <boost/algorithm/string/predicate.hpp>
namespace camera_calibration_parsers {
bool writeCalibration(const std::string& file_name, const std::string& camera_name,
const sensor_msgs::CameraInfo& cam_info)
{
if (boost::iends_with(file_name, ".ini"))
return writeCalibrationIni(file_name, camera_name, cam_info);
if (boost::iends_with(file_name, ".yml") || boost::iends_with(file_name, ".yaml"))
return writeCalibrationYml(file_name, camera_name, cam_info);
return false;
}
bool readCalibration(const std::string& file_name, std::string& camera_name,
sensor_msgs::CameraInfo& cam_info)
{
if (boost::iends_with(file_name, ".ini"))
return readCalibrationIni(file_name, camera_name, cam_info);
if (boost::iends_with(file_name, ".yml") || boost::iends_with(file_name, ".yaml"))
return readCalibrationYml(file_name, camera_name, cam_info);
return false;
}
bool parseCalibration(const std::string& buffer, const std::string& format,
std::string& camera_name, sensor_msgs::CameraInfo& cam_info)
{
if (format != "ini")
return false;
return parseCalibrationIni(buffer, camera_name, cam_info);
}
} //namespace camera_calibration_parsers
| 0 |
apollo_public_repos/apollo-platform/ros/image_common/camera_calibration_parsers | apollo_public_repos/apollo-platform/ros/image_common/camera_calibration_parsers/src/convert.cpp | /*********************************************************************
* Software License Agreement (BSD License)
*
* Copyright (c) 2009, Willow Garage, Inc.
* 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 Willow Garage nor the names of its
* 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.
*********************************************************************/
#include "camera_calibration_parsers/parse.h"
#include <ros/console.h>
#include <cstdio>
using namespace camera_calibration_parsers;
int main(int argc, char** argv)
{
if (argc < 3) {
printf("Usage: %s input.yml output.ini\n"
" %s input.ini output.yml\n", argv[0], argv[0]);
return 0;
}
std::string name;
sensor_msgs::CameraInfo cam_info;
if (!readCalibration(argv[1], name, cam_info)) {
ROS_ERROR("Failed to load camera model from file %s", argv[1]);
return -1;
}
if (!writeCalibration(argv[2], name, cam_info)) {
ROS_ERROR("Failed to save camera model to file %s", argv[2]);
return -1;
}
ROS_INFO("Saved %s", argv[2]);
return 0;
}
| 0 |
apollo_public_repos/apollo-platform/ros/image_common/camera_calibration_parsers | apollo_public_repos/apollo-platform/ros/image_common/camera_calibration_parsers/src/parse_ini.cpp | /*********************************************************************
* Software License Agreement (BSD License)
*
* Copyright (c) 2009, Willow Garage, Inc.
* 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 Willow Garage nor the names of its
* 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.
*********************************************************************/
#include "camera_calibration_parsers/parse_ini.h"
#include <sensor_msgs/distortion_models.h>
#include <ros/console.h>
#include <boost/spirit/include/phoenix_stl.hpp>
#include <boost/spirit/include/qi.hpp>
#include <boost/spirit/include/classic_core.hpp>
#include <boost/spirit/include/classic_file_iterator.hpp>
#include <boost/spirit/include/classic_confix.hpp>
#include <boost/spirit/include/classic_loops.hpp>
#include <boost/typeof/typeof.hpp>
#include <boost/filesystem.hpp>
#include <iterator>
#include <fstream>
namespace camera_calibration_parsers {
/// @todo Move to new spirit
using namespace BOOST_SPIRIT_CLASSIC_NS;
/// \cond
struct SimpleMatrix
{
int rows;
int cols;
const double* data;
SimpleMatrix(int rows, int cols, const double* data)
: rows(rows), cols(cols), data(data)
{}
};
std::ostream& operator << (std::ostream& out, const SimpleMatrix& m)
{
for (int i = 0; i < m.rows; ++i) {
for (int j = 0; j < m.cols; ++j) {
out << m.data[m.cols*i+j] << " ";
}
out << std::endl;
}
return out;
}
/// \endcond
bool writeCalibrationIni(std::ostream& out, const std::string& camera_name,
const sensor_msgs::CameraInfo& cam_info)
{
// Videre INI format is legacy, only supports plumb bob distortion model.
if (cam_info.distortion_model != sensor_msgs::distortion_models::PLUMB_BOB ||
cam_info.D.size() != 5) {
ROS_ERROR("Videre INI format can only save calibrations using the plumb bob distortion model. "
"Use the YAML format instead.\n"
"\tdistortion_model = '%s', expected '%s'\n"
"\tD.size() = %d, expected 5", cam_info.distortion_model.c_str(),
sensor_msgs::distortion_models::PLUMB_BOB.c_str(), (int)cam_info.D.size());
return false;
}
out.precision(5);
out << std::fixed;
out << "# Camera intrinsics\n\n";
/// @todo time?
out << "[image]\n\n";
out << "width\n" << cam_info.width << "\n\n";
out << "height\n" << cam_info.height << "\n\n";
out << "[" << camera_name << "]\n\n";
out << "camera matrix\n" << SimpleMatrix(3, 3, &cam_info.K[0]);
out << "\ndistortion\n" << SimpleMatrix(1, 5, &cam_info.D[0]);
out << "\n\nrectification\n" << SimpleMatrix(3, 3, &cam_info.R[0]);
out << "\nprojection\n" << SimpleMatrix(3, 4, &cam_info.P[0]);
return true;
}
bool writeCalibrationIni(const std::string& file_name, const std::string& camera_name,
const sensor_msgs::CameraInfo& cam_info)
{
boost::filesystem::path dir(boost::filesystem::path(file_name).parent_path());
if (!dir.empty() && !boost::filesystem::exists(dir) &&
!boost::filesystem::create_directories(dir)){
ROS_ERROR("Unable to create directory for camera calibration file [%s]", dir.c_str());
}
std::ofstream out(file_name.c_str());
if (!out.is_open())
{
ROS_ERROR("Unable to open camera calibration file [%s] for writing", file_name.c_str());
return false;
}
return writeCalibrationIni(out, camera_name, cam_info);
}
/// \cond
// Semantic action to store a sequence of values in an array
template <typename T>
struct ArrayAssignActor
{
ArrayAssignActor(T* start)
: ptr_(start)
{}
void operator()(T val) const
{
*ptr_++ = val;
}
mutable T* ptr_;
};
// Semantic action generator
template <typename T>
ArrayAssignActor<T> array_assign_a(T* start)
{
return ArrayAssignActor<T>(start);
}
template <typename Iterator>
bool parseCalibrationIniRange(Iterator first, Iterator last,
std::string& camera_name, sensor_msgs::CameraInfo& cam_info)
{
cam_info.D.clear();
// We don't actually use the [externals] info, but it's part of the format
bool have_externals = false;
double trans[3], rot[3];
/// @todo separate grammar out into separate function
// Image section (width, height)
BOOST_AUTO(image,
str_p("[image]")
>> "width"
>> uint_p[assign_a(cam_info.width)]
>> "height"
>> uint_p[assign_a(cam_info.height)]
);
// Optional externals section
BOOST_AUTO(externals,
str_p("[externals]")
>> "translation"
>> repeat_p(3)[real_p[array_assign_a(trans)]]
>> "rotation"
>> repeat_p(3)[real_p[array_assign_a(rot)]]
);
// Parser to save name of camera section
BOOST_AUTO(name, confix_p('[', (*anychar_p)[assign_a(camera_name)], ']'));
// Camera section (intrinsics)
BOOST_AUTO(camera,
name
>> "camera matrix"
>> repeat_p(9)[real_p[array_assign_a(&cam_info.K[0])]]
>> "distortion"
>> *(real_p[push_back_a(cam_info.D)])
>> "rectification"
>> repeat_p(9)[real_p[array_assign_a(&cam_info.R[0])]]
>> "projection"
>> repeat_p(12)[real_p[array_assign_a(&cam_info.P[0])]]
);
// Full grammar
BOOST_AUTO(ini_grammar,
image
>> !externals[assign_a(have_externals, true)]
>> camera);
// Skip whitespace and line comments
BOOST_AUTO(skip, space_p | comment_p('#'));
parse_info<Iterator> info = parse(first, last, ini_grammar, skip);
// Figure out the distortion model
if (cam_info.D.size() == 5)
cam_info.distortion_model = sensor_msgs::distortion_models::PLUMB_BOB;
else if (cam_info.D.size() == 8)
cam_info.distortion_model = sensor_msgs::distortion_models::RATIONAL_POLYNOMIAL;
return info.hit;
}
/// \endcond
bool readCalibrationIni(std::istream& in, std::string& camera_name, sensor_msgs::CameraInfo& cam_info)
{
std::istream_iterator<char> first(in), last;
return parseCalibrationIniRange(first, last, camera_name, cam_info);
}
bool readCalibrationIni(const std::string& file_name, std::string& camera_name,
sensor_msgs::CameraInfo& cam_info)
{
typedef file_iterator<char> Iterator;
Iterator first(file_name);
if (!first) {
ROS_INFO("Unable to open camera calibration file [%s]", file_name.c_str());
return false;
}
Iterator last = first.make_end();
return parseCalibrationIniRange(first, last, camera_name, cam_info);
}
bool parseCalibrationIni(const std::string& buffer, std::string& camera_name,
sensor_msgs::CameraInfo& cam_info)
{
return parseCalibrationIniRange(buffer.begin(), buffer.end(), camera_name, cam_info);
}
} //namespace camera_calibration_parsers
| 0 |
apollo_public_repos/apollo-platform/ros/image_common/camera_calibration_parsers | apollo_public_repos/apollo-platform/ros/image_common/camera_calibration_parsers/src/parse_yml.cpp | /*********************************************************************
* Software License Agreement (BSD License)
*
* Copyright (c) 2009, Willow Garage, Inc.
* 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 Willow Garage nor the names of its
* 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.
*********************************************************************/
#include "camera_calibration_parsers/parse_yml.h"
#include <sensor_msgs/distortion_models.h>
#include <boost/filesystem.hpp>
#include <yaml-cpp/yaml.h>
#include <fstream>
#include <ctime>
#include <cassert>
#include <cstring>
#include <ros/console.h>
namespace camera_calibration_parsers {
/// \cond
static const char CAM_YML_NAME[] = "camera_name";
static const char WIDTH_YML_NAME[] = "image_width";
static const char HEIGHT_YML_NAME[] = "image_height";
static const char K_YML_NAME[] = "camera_matrix";
static const char D_YML_NAME[] = "distortion_coefficients";
static const char R_YML_NAME[] = "rectification_matrix";
static const char P_YML_NAME[] = "projection_matrix";
static const char DMODEL_YML_NAME[] = "distortion_model";
struct SimpleMatrix
{
int rows;
int cols;
double* data;
SimpleMatrix(int rows, int cols, double* data)
: rows(rows), cols(cols), data(data)
{}
};
YAML::Emitter& operator << (YAML::Emitter& out, const SimpleMatrix& m)
{
out << YAML::BeginMap;
out << YAML::Key << "rows" << YAML::Value << m.rows;
out << YAML::Key << "cols" << YAML::Value << m.cols;
//out << YAML::Key << "dt" << YAML::Value << "d"; // OpenCV data type specifier
out << YAML::Key << "data" << YAML::Value;
out << YAML::Flow;
out << YAML::BeginSeq;
for (int i = 0; i < m.rows*m.cols; ++i)
out << m.data[i];
out << YAML::EndSeq;
out << YAML::EndMap;
return out;
}
#ifdef HAVE_NEW_YAMLCPP
template<typename T>
void operator >> (const YAML::Node& node, T& i)
{
i = node.as<T>();
}
#endif
void operator >> (const YAML::Node& node, SimpleMatrix& m)
{
int rows, cols;
node["rows"] >> rows;
assert(rows == m.rows);
node["cols"] >> cols;
assert(cols == m.cols);
const YAML::Node& data = node["data"];
for (int i = 0; i < rows*cols; ++i)
data[i] >> m.data[i];
}
/// \endcond
bool writeCalibrationYml(std::ostream& out, const std::string& camera_name,
const sensor_msgs::CameraInfo& cam_info)
{
YAML::Emitter emitter;
emitter << YAML::BeginMap;
#if 0
// Calibration time
/// @todo Emitting the time breaks yaml-cpp on reading for some reason
time_t raw_time;
time( &raw_time );
emitter << YAML::Key << "calibration_time";
emitter << YAML::Value << asctime(localtime(&raw_time));
#endif
// Image dimensions
emitter << YAML::Key << WIDTH_YML_NAME << YAML::Value << (int)cam_info.width;
emitter << YAML::Key << HEIGHT_YML_NAME << YAML::Value << (int)cam_info.height;
// Camera name and intrinsics
emitter << YAML::Key << CAM_YML_NAME << YAML::Value << camera_name;
emitter << YAML::Key << K_YML_NAME << YAML::Value << SimpleMatrix(3, 3, const_cast<double*>(&cam_info.K[0]));
emitter << YAML::Key << DMODEL_YML_NAME << YAML::Value << cam_info.distortion_model;
emitter << YAML::Key << D_YML_NAME << YAML::Value << SimpleMatrix(1, cam_info.D.size(),
const_cast<double*>(&cam_info.D[0]));
emitter << YAML::Key << R_YML_NAME << YAML::Value << SimpleMatrix(3, 3, const_cast<double*>(&cam_info.R[0]));
emitter << YAML::Key << P_YML_NAME << YAML::Value << SimpleMatrix(3, 4, const_cast<double*>(&cam_info.P[0]));
emitter << YAML::EndMap;
out << emitter.c_str();
return true;
}
bool writeCalibrationYml(const std::string& file_name, const std::string& camera_name,
const sensor_msgs::CameraInfo& cam_info)
{
boost::filesystem::path dir(boost::filesystem::path(file_name).parent_path());
if (!dir.empty() && !boost::filesystem::exists(dir) &&
!boost::filesystem::create_directories(dir)){
ROS_ERROR("Unable to create directory for camera calibration file [%s]", dir.c_str());
}
std::ofstream out(file_name.c_str());
if (!out.is_open())
{
ROS_ERROR("Unable to open camera calibration file [%s] for writing", file_name.c_str());
return false;
}
return writeCalibrationYml(out, camera_name, cam_info);
}
bool readCalibrationYml(std::istream& in, std::string& camera_name, sensor_msgs::CameraInfo& cam_info)
{
try {
#ifdef HAVE_NEW_YAMLCPP
YAML::Node doc = YAML::Load(in);
if (doc[CAM_YML_NAME])
doc[CAM_YML_NAME] >> camera_name;
else
camera_name = "unknown";
#else
YAML::Parser parser(in);
if (!parser) {
ROS_ERROR("Unable to create YAML parser for camera calibration");
return false;
}
YAML::Node doc;
parser.GetNextDocument(doc);
if (const YAML::Node* name_node = doc.FindValue(CAM_YML_NAME))
*name_node >> camera_name;
else
camera_name = "unknown";
#endif
doc[WIDTH_YML_NAME] >> cam_info.width;
doc[HEIGHT_YML_NAME] >> cam_info.height;
// Read in fixed-size matrices
SimpleMatrix K_(3, 3, &cam_info.K[0]);
doc[K_YML_NAME] >> K_;
SimpleMatrix R_(3, 3, &cam_info.R[0]);
doc[R_YML_NAME] >> R_;
SimpleMatrix P_(3, 4, &cam_info.P[0]);
doc[P_YML_NAME] >> P_;
// Different distortion models may have different numbers of parameters
#ifdef HAVE_NEW_YAMLCPP
if (doc[DMODEL_YML_NAME]) {
doc[DMODEL_YML_NAME] >> cam_info.distortion_model;
}
#else
if (const YAML::Node* model_node = doc.FindValue(DMODEL_YML_NAME)) {
*model_node >> cam_info.distortion_model;
}
#endif
else {
// Assume plumb bob for backwards compatibility
cam_info.distortion_model = sensor_msgs::distortion_models::PLUMB_BOB;
ROS_WARN("Camera calibration file did not specify distortion model, assuming plumb bob");
}
const YAML::Node& D_node = doc[D_YML_NAME];
int D_rows, D_cols;
D_node["rows"] >> D_rows;
D_node["cols"] >> D_cols;
const YAML::Node& D_data = D_node["data"];
cam_info.D.resize(D_rows*D_cols);
for (int i = 0; i < D_rows*D_cols; ++i)
D_data[i] >> cam_info.D[i];
return true;
}
catch (YAML::Exception& e) {
ROS_ERROR("Exception parsing YAML camera calibration:\n%s", e.what());
return false;
}
}
bool readCalibrationYml(const std::string& file_name, std::string& camera_name,
sensor_msgs::CameraInfo& cam_info)
{
std::ifstream fin(file_name.c_str());
if (!fin.good()) {
ROS_INFO("Unable to open camera calibration file [%s]", file_name.c_str());
return false;
}
bool success = readCalibrationYml(fin, camera_name, cam_info);
if (!success)
ROS_ERROR("Failed to parse camera calibration from file [%s]", file_name.c_str());
return success;
}
} //namespace camera_calibration_parsers
| 0 |
apollo_public_repos/apollo-platform/ros/image_common/camera_calibration_parsers/src | apollo_public_repos/apollo-platform/ros/image_common/camera_calibration_parsers/src/camera_calibration_parsers/__init__.py | from camera_calibration_parsers.camera_calibration_parsers_wrapper import __readCalibrationWrapper
from sensor_msgs.msg import CameraInfo
def readCalibration(file_name):
"""Read .ini or .yaml calibration file and return (camera name and cameraInfo message).
@param file_name: camera calibration file name
@type file_name: str
@return: (camera name, cameraInfo message) or None on Error
@rtype: tuple(str, sensor_msgs.msg.CameraInfo | None
"""
ret, cn, ci = __readCalibrationWrapper(file_name)
if not ret:
return None
c = CameraInfo()
c.deserialize(ci)
return cn, c
| 0 |
apollo_public_repos/apollo-platform/ros/image_common | apollo_public_repos/apollo-platform/ros/image_common/polled_camera/CMakeLists.txt | cmake_minimum_required(VERSION 2.8)
project(polled_camera)
# generate the server
find_package(catkin REQUIRED COMPONENTS image_transport message_generation roscpp sensor_msgs std_msgs)
add_service_files(DIRECTORY srv FILES GetPolledImage.srv)
generate_messages(DEPENDENCIES sensor_msgs std_msgs)
# define the project
catkin_package(CATKIN_DEPENDS image_transport message_runtime roscpp sensor_msgs std_msgs
INCLUDE_DIRS include
LIBRARIES ${PROJECT_NAME}
)
# create some library and exe
include_directories(include
${catkin_INCLUDE_DIRS}
${CATKIN_DEVEL_PREFIX}/${CATKIN_GLOBAL_INCLUDE_DESTINATION}
)
add_library(${PROJECT_NAME} src/publication_server.cpp)
add_dependencies(${PROJECT_NAME} ${catkin_EXPORTED_TARGETS} ${${PROJECT_NAME}_EXPORTED_TARGETS})
target_link_libraries(${PROJECT_NAME} ${catkin_LIBRARIES})
install(TARGETS ${PROJECT_NAME}
DESTINATION ${CATKIN_PACKAGE_LIB_DESTINATION}
)
install(DIRECTORY include/${PROJECT_NAME}/
DESTINATION ${CATKIN_PACKAGE_INCLUDE_DESTINATION}
)
add_executable(poller src/poller.cpp)
add_dependencies(poller ${catkin_EXPORTED_TARGETS} ${${PROJECT_NAME}_EXPORTED_TARGETS})
target_link_libraries(poller ${PROJECT_NAME}
${catkin_LIBRARIES}
)
install(TARGETS poller
DESTINATION ${CATKIN_PACKAGE_BIN_DESTINATION}
)
| 0 |
apollo_public_repos/apollo-platform/ros/image_common | apollo_public_repos/apollo-platform/ros/image_common/polled_camera/package.xml | <package>
<name>polled_camera</name>
<version>1.11.12</version>
<description>
polled_camera contains a service and C++ helper classes for implementing a polled
camera driver node and requesting images from it. The package is currently for
internal use as the API is still under development.
</description>
<author>Patrick Mihelich</author>
<maintainer email="[email protected]">Jack O'Quin</maintainer>
<maintainer email="[email protected]">Vincent Rabaud</maintainer>
<license>BSD</license>
<url type="website">http://ros.org/wiki/polled_camera</url>
<url type="bugtracker">https://github.com/ros-perception/image_common/issues</url>
<url type="repository">https://github.com/ros-perception/image_common</url>
<buildtool_depend>catkin</buildtool_depend>
<build_depend>image_transport</build_depend>
<build_depend>message_generation</build_depend>
<build_depend>roscpp</build_depend>
<build_depend>sensor_msgs</build_depend>
<build_depend>std_msgs</build_depend>
<run_depend>image_transport</run_depend>
<run_depend>message_runtime</run_depend>
<run_depend>roscpp</run_depend>
<run_depend>sensor_msgs</run_depend>
<run_depend>std_msgs</run_depend>
</package>
| 0 |
apollo_public_repos/apollo-platform/ros/image_common | apollo_public_repos/apollo-platform/ros/image_common/polled_camera/mainpage.dox | /**
\mainpage
\htmlinclude manifest.html
NOTE: This package's API is not yet released. It may change from its current form.
\b polled_camera contains a service definition for requesting polled images,
as well as a C++ server class to simplify publishing polled images to clients.
The protocol for polling images from a camera driver node that supports it is as
follows:
- The camera driver advertises a service call \c \<camera\>/request_image.
- The client calls the service, specifying an output namespace in the request.
- On receiving a request, the driver captures an image and returns its time stamp
in the service response.
- The \c Image and \c CameraInfo are published to \c \<response_namespace\>/image_raw
and \c \<response_namespace\>/camera_info, latched.
- Clients subscribe to the response topics just like any other camera image stream.
\section codeapi Code API
Use polled_camera::PublicationServer in camera driver nodes (or similar) to
track client connections and respond to image requests.
There is not currently a matching client class, but receiving polled images
is identical to subscribing to any other image topic. The only additional
step is using a ros::ServiceClient to make explicit requests:
\code
#include <ros/ros.h>
#include <image_transport/image_transport.h>
#include <polled_camera/GetPolledImage.h>
void callback(const sensor_msgs::ImageConstPtr& image, const sensor_msgs::CameraInfoConstPtr& info);
ros::NodeHandle nh;
image_transport::ImageTransport it(nh);
image_transport::CameraSubscriber sub = it.subscribeCamera("output_ns/image_raw", 1, callback);
ros::ServiceClient client = nh.serviceClient<polled_camera::GetPolledImage>("my_camera/request_image");
polled_camera::GetPolledImage srv;
srv.request.response_namespace = "output_ns";
if (client.call(srv))
{
ROS_INFO_STREAM("Image captured with timestamp " << srv.response.stamp);
}
\endcode
*/
| 0 |
apollo_public_repos/apollo-platform/ros/image_common | apollo_public_repos/apollo-platform/ros/image_common/polled_camera/CHANGELOG.rst | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Changelog for package polled_camera
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1.11.12 (2017-01-29)
--------------------
* Fix CMake of image_transport/tutorial and polled_camera
Fix loads of problems with the CMakeLists.
* 1.11.11
* update changelogs
* address gcc6 build error in polled_camera
With gcc6, compiling fails with `stdlib.h: No such file or directory`,
as including '-isystem /usr/include' breaks with gcc6, cf.,
https://gcc.gnu.org/bugzilla/show_bug.cgi?id=70129.
This commit addresses this issue for this package in the same way
it was addressed in various other ROS packages. A list of related
commits and pull requests is at:
https://github.com/ros/rosdistro/issues/12783
Signed-off-by: Lukas Bulwahn <[email protected]>
* Contributors: Lukas Bulwahn, Martin Guenther, Vincent Rabaud
1.11.11 (2016-09-24)
--------------------
* address gcc6 build error in polled_camera
With gcc6, compiling fails with `stdlib.h: No such file or directory`,
as including '-isystem /usr/include' breaks with gcc6, cf.,
https://gcc.gnu.org/bugzilla/show_bug.cgi?id=70129.
This commit addresses this issue for this package in the same way
it was addressed in various other ROS packages. A list of related
commits and pull requests is at:
https://github.com/ros/rosdistro/issues/12783
Signed-off-by: Lukas Bulwahn <[email protected]>
* Contributors: Lukas Bulwahn
1.11.10 (2016-01-19)
--------------------
1.11.9 (2016-01-17)
-------------------
1.11.8 (2015-11-29)
-------------------
1.11.7 (2015-07-28)
-------------------
1.11.6 (2015-07-16)
-------------------
1.11.5 (2015-05-14)
-------------------
1.11.4 (2014-09-21)
-------------------
1.11.3 (2014-05-19)
-------------------
1.11.2 (2014-02-13)
-------------------
1.11.1 (2014-01-26 02:33)
-------------------------
1.11.0 (2013-07-20 12:23)
-------------------------
1.10.5 (2014-01-26 02:34)
-------------------------
1.10.4 (2013-07-20 11:42)
-------------------------
* add Jack as maintainer
* Contributors: Vincent Rabaud
1.10.3 (2013-02-21 05:33)
-------------------------
1.10.2 (2013-02-21 04:48)
-------------------------
1.10.1 (2013-02-21 04:16)
-------------------------
1.10.0 (2013-01-13)
-------------------
* use CATKIN_DEVEL_PREFIX instead of obsolete CATKIN_BUILD_PREFIX
* fix the urls
* Missing link flags exposed on OS X
* added license headers to various cpp and h files
* Contributors: Aaron Blasdel, Dirk Thomas, Vincent Rabaud, William Woodall
1.9.22 (2012-12-16)
-------------------
* replace genmsg by message_generation
* Contributors: Vincent Rabaud
1.9.21 (2012-12-14)
-------------------
* Updated package.xml file(s) to handle new catkin buildtool_depend requirement
* Contributors: mirzashah
1.9.20 (2012-12-04)
-------------------
1.9.19 (2012-11-08)
-------------------
1.9.18 (2012-11-06)
-------------------
* remove the brief attribute
* Contributors: Vincent Rabaud
1.9.17 (2012-10-30 19:32)
-------------------------
* comlpy to the new catkin API
* Contributors: Vincent Rabaud
1.9.16 (2012-10-30 09:10)
-------------------------
1.9.15 (2012-10-13 08:43)
-------------------------
* fix bad folder/libraries
* Contributors: Vincent Rabaud
1.9.14 (2012-10-13 01:07)
-------------------------
* fix typo that resulted in bad installation of include folder
* Contributors: Vincent Rabaud
1.9.13 (2012-10-06)
-------------------
1.9.12 (2012-10-04)
-------------------
1.9.11 (2012-10-02 02:56)
-------------------------
1.9.10 (2012-10-02 02:42)
-------------------------
1.9.9 (2012-10-01)
------------------
* fix dependencies
* Contributors: Vincent Rabaud
1.9.8 (2012-09-30)
------------------
* add catkin as a dependency
* comply to the catkin API
* Contributors: Vincent Rabaud
1.9.7 (2012-09-18 11:39)
------------------------
1.9.6 (2012-09-18 11:07)
------------------------
1.9.5 (2012-09-13)
------------------
* install the include directories
* Contributors: Vincent Rabaud
1.9.4 (2012-09-12 23:37)
------------------------
* make sure we depend on the server
* Contributors: Vincent Rabaud
1.9.3 (2012-09-12 20:44)
------------------------
1.9.2 (2012-09-10)
------------------
1.9.1 (2012-09-07 15:33)
------------------------
1.9.0 (2012-09-07 13:03)
------------------------
* catkinize for Groovy
* polled_camera (rep0104): Changed callback to allow filling
status_message field.
* polled_camera (rep0104): Applied changes to GetPolledImage service.
* Contributors: Vincent Rabaud, eitan, gerkey, kwc, mihelich
| 0 |
apollo_public_repos/apollo-platform/ros/image_common/polled_camera/include | apollo_public_repos/apollo-platform/ros/image_common/polled_camera/include/polled_camera/publication_server.h | /*********************************************************************
* Software License Agreement (BSD License)
*
* Copyright (c) 2009, Willow Garage, Inc.
* 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 Willow Garage nor the names of its
* 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 POLLED_CAMERA_PUBLICATION_SERVER_H
#define POLLED_CAMERA_PUBLICATION_SERVER_H
#include <ros/ros.h>
#include <sensor_msgs/Image.h>
#include <sensor_msgs/CameraInfo.h>
#include "polled_camera/GetPolledImage.h"
namespace polled_camera {
/**
* \brief Manage image requests from one or more clients.
*
* Instances of polled_camera::PublicationServer should be created using one of
* the overloads of polled_camera::advertise(). You must specify a driver
* callback that populates the requested data:
\code
void callback(polled_camera::GetPolledImage::Request& req,
polled_camera::GetPolledImage::Response& rsp,
sensor_msgs::Image& image, sensor_msgs::CameraInfo& info)
{
// Capture an image and fill in the Image and CameraInfo messages here.
// On success, set rsp.success = true. rsp.timestamp will be filled in
// automatically.
// On failure, set rsp.success = false and fill rsp.status_message with an
// informative error message.
}
\endcode
*/
class PublicationServer
{
public:
typedef boost::function<void (polled_camera::GetPolledImage::Request&,
polled_camera::GetPolledImage::Response&,
sensor_msgs::Image&,
sensor_msgs::CameraInfo&)> DriverCallback;
PublicationServer() {}
/**
* \brief Unadvertise the request service and shut down all published topics.
*/
void shutdown();
std::string getService() const;
operator void*() const;
bool operator< (const PublicationServer& rhs) const { return impl_ < rhs.impl_; }
bool operator==(const PublicationServer& rhs) const { return impl_ == rhs.impl_; }
bool operator!=(const PublicationServer& rhs) const { return impl_ != rhs.impl_; }
private:
PublicationServer(const std::string& service, ros::NodeHandle& nh,
const DriverCallback& cb, const ros::VoidPtr& tracked_object);
class Impl;
boost::shared_ptr<Impl> impl_;
friend
PublicationServer advertise(ros::NodeHandle&, const std::string&, const DriverCallback&,
const ros::VoidPtr&);
};
/**
* \brief Advertise a polled image service, version for arbitrary boost::function object.
*/
PublicationServer advertise(ros::NodeHandle& nh, const std::string& service,
const PublicationServer::DriverCallback& cb,
const ros::VoidPtr& tracked_object = ros::VoidPtr());
/**
* \brief Advertise a polled image service, version for class member function with bare pointer.
*/
template<class T>
PublicationServer advertise(ros::NodeHandle& nh, const std::string& service,
void(T::*fp)(polled_camera::GetPolledImage::Request&,
polled_camera::GetPolledImage::Response&,
sensor_msgs::Image&, sensor_msgs::CameraInfo&),
T* obj)
{
return advertise(nh, service, boost::bind(fp, obj, _1, _2, _3, _4));
}
/**
* \brief Advertise a polled image service, version for class member function with bare pointer.
*/
template<class T>
PublicationServer advertise(ros::NodeHandle& nh, const std::string& service,
void(T::*fp)(polled_camera::GetPolledImage::Request&,
polled_camera::GetPolledImage::Response&,
sensor_msgs::Image&, sensor_msgs::CameraInfo&),
const boost::shared_ptr<T>& obj)
{
return advertise(nh, service, boost::bind(fp, obj.get(), _1, _2, _3, _4), obj);
}
} //namespace polled_camera
#endif
| 0 |
apollo_public_repos/apollo-platform/ros/image_common/polled_camera | apollo_public_repos/apollo-platform/ros/image_common/polled_camera/srv/GetPolledImage.srv | # Namespace to publish response topics in. A polled camera driver node
# should publish:
# <response_namespace>/image_raw
# <response_namespace>/camera_info
string response_namespace
# Timeout for attempting to capture data from the device. This does not
# include latency from ROS communication, post-processing of raw camera
# data, etc. A zero duration indicates no time limit.
duration timeout
# Binning settings, if supported by the camera.
uint32 binning_x
uint32 binning_y
# Region of interest, if supported by the camera.
sensor_msgs/RegionOfInterest roi
---
bool success # Could the image be captured?
string status_message # Error message in case of failure
time stamp # Timestamp of the captured image. Can be matched
# against incoming sensor_msgs/Image header.
| 0 |
apollo_public_repos/apollo-platform/ros/image_common/polled_camera | apollo_public_repos/apollo-platform/ros/image_common/polled_camera/src/poller.cpp | /*********************************************************************
* Software License Agreement (BSD License)
*
* Copyright (c) 2009, Willow Garage, Inc.
* 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 Willow Garage nor the names of its
* 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.
*********************************************************************/
#include <cstdio>
#include <ros/ros.h>
#include <boost/lexical_cast.hpp>
#include "polled_camera/GetPolledImage.h"
int main(int argc, char** argv)
{
ros::init(argc, argv, "poller", ros::init_options::AnonymousName);
if (argc < 2) {
printf("Usage: %s <Hz> camera:=<namespace> output:=<namespace>\n", argv[0]);
return 0;
}
double hz = boost::lexical_cast<double>(argv[1]);
ros::NodeHandle nh;
std::string service_name = nh.resolveName("camera") + "/request_image";
ros::ServiceClient client = nh.serviceClient<polled_camera::GetPolledImage>(service_name);
polled_camera::GetPolledImage::Request req;
polled_camera::GetPolledImage::Response rsp;
req.response_namespace = nh.resolveName("output");
ros::Rate loop_rate(hz);
while (nh.ok()) {
if (client.call(req, rsp)) {
std::cout << "Timestamp: " << rsp.stamp << std::endl;
loop_rate.sleep();
}
else {
ROS_ERROR("Service call failed");
client.waitForExistence();
}
}
}
| 0 |
apollo_public_repos/apollo-platform/ros/image_common/polled_camera | apollo_public_repos/apollo-platform/ros/image_common/polled_camera/src/publication_server.cpp | /*********************************************************************
* Software License Agreement (BSD License)
*
* Copyright (c) 2009, Willow Garage, Inc.
* 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 Willow Garage nor the names of its
* 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.
*********************************************************************/
#include "polled_camera/publication_server.h"
#include <image_transport/image_transport.h>
namespace polled_camera {
/// \cond
class PublicationServer::Impl
{
public:
ros::ServiceServer srv_server_;
DriverCallback driver_cb_;
ros::VoidPtr tracked_object_;
image_transport::ImageTransport it_;
std::map<std::string, image_transport::CameraPublisher> client_map_;
bool unadvertised_;
double constructed_;
Impl(const ros::NodeHandle& nh)
: it_(nh),
unadvertised_(false),
constructed_(ros::WallTime::now().toSec())
{
}
~Impl()
{
if (ros::WallTime::now().toSec() - constructed_ < 0.001)
ROS_WARN("PublicationServer destroyed immediately after creation. Did you forget to store the handle?");
unadvertise();
}
bool isValid() const
{
return !unadvertised_;
}
void unadvertise()
{
if (!unadvertised_) {
unadvertised_ = true;
srv_server_.shutdown();
client_map_.clear();
}
}
bool requestCallback(polled_camera::GetPolledImage::Request& req,
polled_camera::GetPolledImage::Response& rsp)
{
std::string image_topic = req.response_namespace + "/image_raw";
image_transport::CameraPublisher& pub = client_map_[image_topic];
if (!pub) {
// Create a latching camera publisher.
pub = it_.advertiseCamera(image_topic, 1, image_transport::SubscriberStatusCallback(),
boost::bind(&Impl::disconnectCallback, this, _1),
ros::SubscriberStatusCallback(), ros::SubscriberStatusCallback(),
ros::VoidPtr(), true /*latch*/);
ROS_INFO("Advertising %s", pub.getTopic().c_str());
}
// Correct zero binning values to one for convenience
req.binning_x = std::max(req.binning_x, (uint32_t)1);
req.binning_y = std::max(req.binning_y, (uint32_t)1);
/// @todo Use pointers in prep for nodelet drivers?
sensor_msgs::Image image;
sensor_msgs::CameraInfo info;
driver_cb_(req, rsp, image, info);
if (rsp.success) {
assert(image.header.stamp == info.header.stamp);
rsp.stamp = image.header.stamp;
pub.publish(image, info);
}
else {
ROS_ERROR("Failed to capture requested image, status message: '%s'",
rsp.status_message.c_str());
}
return true; // Success/failure indicated by rsp.success
}
void disconnectCallback(const image_transport::SingleSubscriberPublisher& ssp)
{
// Shut down the publication when the subscription count drops to zero.
if (ssp.getNumSubscribers() == 0) {
ROS_INFO("Shutting down %s", ssp.getTopic().c_str());
client_map_.erase(ssp.getTopic());
}
}
};
/// \endcond
PublicationServer::PublicationServer(const std::string& service, ros::NodeHandle& nh,
const DriverCallback& cb, const ros::VoidPtr& tracked_object)
: impl_(new Impl(nh))
{
impl_->driver_cb_ = cb;
impl_->tracked_object_ = tracked_object;
impl_->srv_server_ = nh.advertiseService<>(service, &Impl::requestCallback, impl_);
}
void PublicationServer::shutdown()
{
if (impl_) impl_->unadvertise();
}
std::string PublicationServer::getService() const
{
if (impl_) return impl_->srv_server_.getService();
return std::string();
}
PublicationServer::operator void*() const
{
return (impl_ && impl_->isValid()) ? (void*)1 : (void*)0;
}
PublicationServer advertise(ros::NodeHandle& nh, const std::string& service,
const PublicationServer::DriverCallback& cb,
const ros::VoidPtr& tracked_object)
{
return PublicationServer(service, nh, cb, tracked_object);
}
} //namespace polled_camera
| 0 |
apollo_public_repos/apollo-platform/ros/image_common | apollo_public_repos/apollo-platform/ros/image_common/image_common/CMakeLists.txt | cmake_minimum_required(VERSION 2.8.3)
project(image_common)
find_package(catkin REQUIRED)
catkin_metapackage()
| 0 |
apollo_public_repos/apollo-platform/ros/image_common | apollo_public_repos/apollo-platform/ros/image_common/image_common/package.xml | <package>
<name>image_common</name>
<version>1.11.12</version>
<description>Common code for working with images in ROS.</description>
<author>Patrick Mihelich</author>
<author>James Bowman</author>
<maintainer email="[email protected]">Jack O'Quin</maintainer>
<maintainer email="[email protected]">Vincent Rabaud</maintainer>
<license>BSD</license>
<url type="website">http://www.ros.org/wiki/image_common</url>
<url type="bugtracker">https://github.com/ros-perception/image_common/issues</url>
<url type="repository">https://github.com/ros-perception/image_common</url>
<buildtool_depend>catkin</buildtool_depend>
<!-- Old stack contents -->
<run_depend>camera_calibration_parsers</run_depend>
<run_depend>camera_info_manager</run_depend>
<run_depend>image_transport</run_depend>
<run_depend>polled_camera</run_depend>
<export>
<metapackage/>
</export>
</package>
| 0 |
apollo_public_repos/apollo-platform/ros/image_common | apollo_public_repos/apollo-platform/ros/image_common/image_common/CHANGELOG.rst | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Changelog for package image_common
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1.11.12 (2017-01-29)
--------------------
* 1.11.11
* update changelogs
* Contributors: Vincent Rabaud
1.11.11 (2016-09-24)
--------------------
1.11.10 (2016-01-19)
--------------------
1.11.9 (2016-01-17)
-------------------
1.11.8 (2015-11-29)
-------------------
1.11.7 (2015-07-28)
-------------------
1.11.6 (2015-07-16)
-------------------
1.11.5 (2015-05-14)
-------------------
1.11.4 (2014-09-21)
-------------------
1.11.3 (2014-05-19)
-------------------
1.11.2 (2014-02-13)
-------------------
1.11.1 (2014-01-26 02:33)
-------------------------
1.11.0 (2013-07-20 12:23)
-------------------------
1.10.5 (2014-01-26 02:34)
-------------------------
1.10.4 (2013-07-20 11:42)
-------------------------
* add Jack as maintainer
* comply to REP 0127
* Contributors: Vincent Rabaud
1.10.3 (2013-02-21 05:33)
-------------------------
1.10.2 (2013-02-21 04:48)
-------------------------
1.10.1 (2013-02-21 04:16)
-------------------------
1.10.0 (2013-01-13)
-------------------
1.9.22 (2012-12-16)
-------------------
1.9.21 (2012-12-14)
-------------------
1.9.20 (2012-12-04)
-------------------
1.9.19 (2012-11-08)
-------------------
1.9.18 (2012-11-06)
-------------------
1.9.17 (2012-10-30 19:32)
-------------------------
1.9.16 (2012-10-30 09:10)
-------------------------
1.9.15 (2012-10-13 08:43)
-------------------------
1.9.14 (2012-10-13 01:07)
-------------------------
1.9.13 (2012-10-06)
-------------------
* add missing description
* Contributors: Vincent Rabaud
1.9.12 (2012-10-04)
-------------------
* define metapackage
* Contributors: Vincent Rabaud
1.9.11 (2012-10-02 02:56)
-------------------------
1.9.10 (2012-10-02 02:42)
-------------------------
1.9.9 (2012-10-01)
------------------
1.9.8 (2012-09-30)
------------------
1.9.7 (2012-09-18 11:39)
------------------------
1.9.6 (2012-09-18 11:07)
------------------------
1.9.5 (2012-09-13)
------------------
1.9.4 (2012-09-12 23:37)
------------------------
1.9.3 (2012-09-12 20:44)
------------------------
1.9.2 (2012-09-10)
------------------
1.9.1 (2012-09-07 15:33)
------------------------
1.9.0 (2012-09-07 13:03)
------------------------
| 0 |
apollo_public_repos/apollo-platform/ros | apollo_public_repos/apollo-platform/ros/roslisp/CMakeLists.txt | cmake_minimum_required(VERSION 2.8.3)
project(roslisp)
find_package(catkin REQUIRED)
catkin_package(CFG_EXTRAS roslisp-extras.cmake)
add_subdirectory(env-hooks)
foreach(dir
load-manifest
rosbuild
roslisp-msg-protocol
src
s-xml
s-xml-rpc
utils)
install(DIRECTORY ${dir}
DESTINATION share/${PROJECT_NAME}
PATTERN ".svn" EXCLUDE
PATTERN "genmsg_lisp.py" EXCLUDE)
endforeach()
# install legacy infrastructure needed by rosbuild
install(FILES manifest.xml
DESTINATION ${CATKIN_PACKAGE_SHARE_DESTINATION})
install(DIRECTORY scripts
DESTINATION ${CATKIN_PACKAGE_SHARE_DESTINATION}
USE_SOURCE_PERMISSIONS
PATTERN ".svn" EXCLUDE
PATTERN "genmsg_lisp.py" EXCLUDE)
install(FILES rosbuild/roslisp.cmake
DESTINATION ${CATKIN_PACKAGE_SHARE_DESTINATION}/rosbuild)
install(PROGRAMS
rosbuild/scripts/genmsg_lisp.py
DESTINATION ${CATKIN_PACKAGE_SHARE_DESTINATION}/rosbuild/scripts)
| 0 |
apollo_public_repos/apollo-platform/ros | apollo_public_repos/apollo-platform/ros/roslisp/.svnignore | *.fasl
*~
.build_version
bin
build
lib
src
msg
| 0 |
apollo_public_repos/apollo-platform/ros | apollo_public_repos/apollo-platform/ros/roslisp/package.xml | <package>
<name>roslisp</name>
<version>1.9.20</version>
<description>Lisp client library for ROS, the Robot Operating System.</description>
<maintainer email="[email protected]">Georg Bartels</maintainer>
<maintainer email="[email protected]">Lorenz Moesenlechner</maintainer>
<license>BSD</license>
<author>Bhaskara Marthi</author>
<author>Brian Gerkey</author>
<author email="[email protected]">Lorenz Moesenlechner</author>
<author>Thibault Kruse</author>
<url>http://ros.org/wiki/roslisp</url>
<buildtool_depend>catkin</buildtool_depend>
<run_depend>roslang</run_depend>
<run_depend>sbcl</run_depend>
<run_depend>rospack</run_depend>
<run_depend>rosgraph_msgs</run_depend>
<run_depend>std_srvs</run_depend>
<export>
<roslang cmake="${prefix}/rosbuild/roslisp.cmake"/>
</export>
</package>
| 0 |
apollo_public_repos/apollo-platform/ros | apollo_public_repos/apollo-platform/ros/roslisp/roslisp.dox | /**
\mainpage
\htmlinclude manifest.html
\section Overview
\b roslisp is a library for writing ROS nodes in ANSI Common Lisp. See the tutorial at for how to set up roslisp for standalone compilation of lisp source files and/or interactive use. This page lists the functions available in the client library and other miscellaneous information. Detailed documentation about the functions is available within the Lisp environment using the documentation feature.
\section build Integration with build system
Roslisp is integrated with the asdf build system. When using roslisp nodes from within a lisp environment, add the following lines to your .sbclrc:
\verbatim
(push #P"/path/to/roslisp/asdf/" asdf:*central-registry*)
(asdf:operate 'asdf:load-op :ros-load-manifest)
\endverbatim
This extends asdf to use two additional rospack-based search methods to finding .asd files.
- Given a system name foo, if the variable ros-load:*current-ros-package* is a nonempty string, it will look for a system named foo defined in asdf/foo.asd of the package or one of its ros dependencies. The file asdf/foo.asd will usually be a symbolic link to a file in whatever directory the actual source files are in. To dynamically bind the variable ros-load:*current-ros-package* and perform the load operation, the function ros-load:load-system can be used. It takes the name of the ros package as first parameter and an optional second parameter for the name of the system to load, which defaults to the ros package name.
- Given a system of the form foo-msg, if there's a ros package called foo, the messages from this package will be loaded, and likewise for foo-srv and services.
You can also build standalone nodes in the CMakeLists.txt file. For example, roslisp_examples/CMakeLists.txt contains
\verbatim
rospack_add_lisp_executable(bin/talker roslisp-examples roslisp-talker:main)
\endverbatim
This produces the executable roslisp_examples/bin/talker when built. When run from the command line, the executable does not load your standard .sbclrc init file. Rather, it loads ~/.sbclrc-roslisp (if it exists). It then sets *current-ros-package* to roslisp_examples, and loads the asdf system roslisp-examples into memory (using rospack). Next, it loads the files bin/roslisp-init.lisp and bin/roslisp-talker:main.init.lisp (if they exist). These are the places where you can put global, package-specific, and node-specific runtime customizations (customizing debug levels, setting optimization flags, modifying constants) respectively. Finally, it calls the function roslisp-talker:main. Also, when running standalone, the keyword :roslisp-standalone-executable is pushed on to the *features* list, in case you want to make use of this information in some way. Finally, setting the ROSLISP_BACKTRACE_ON_ERRORS environment variable before running the node will print debugging info if it dies.
\section emacs Integration into emacs
The current trunk version of the rosemacs package contains a slime contrib that adds a slime repl shortcut to load systems in ros packages. Please see the rosemacs documentation for more information.
\section debug Debugging output
Roslisp provides a hierarchical, customizable-at-runtime, logging scheme, similar to rosconsole for roscpp. Debug topics are lists, e.g. (roslisp top). For such a topic, the debug level of (roslisp top) would be looked up. If this is not present (roslisp) is looked up. If this is not present, () is looked up (and this is always present in the topic list). The level at runtime then determines whether the message is evaluated and outputted (to stdout and rosout).
To set debug levels, from within Lisp use set-debug-levels. To produce debugging output, use ros-{debug|info|warn|error|fatal}. Additionally, debug levels correspond to ros parameters, e.g., topic (foo bar) corresponds to the private parameter ~debug/foo/bar/level. Upon node initialization, these are read from the parameter server, and must be one of the five strings debug, info, warn, error, or fatal. If they are changed after node startup, call the node's ~reset-debug-levels service to update. A more permanent way to update debug levels is to call set-debug-levels in an initialization file.
Roslisp itself uses debugging levels starting with :roslisp, with subtopics such as :top, :tcp, and :rosout. For example, if debugging roslisp_examples/bin/talker, add the following line to roslisp_examples/bin/roslisp-init.lisp:
\verbatim
(roslisp:set-debug-levels roslisp :debug)
\endverbatim
To reduce the number of connection-related debugging messages, also add the line
\verbatim
(roslisp:set-debug-levels (roslisp tcp) :info)
\endverbatim
\section Packages
The functions in the client API below belong to the Lisp package (namespace) named :roslisp, with the exception of the constructors and field accessors for ROS message data types, which belong to a Lisp package with the same name as the message's ROS package concatenated with "-msg" (and likewise for services, with the suffix "-srv").
\section Names
Names (of topics, services, and parameters) are handled according to standard ROS conventions. Command-line arguments to the executable, of the form foo:=bar, where foo does not begin with '_', are known as command line remappings. Given such a remapping, any topic, parameter, or service referred to as foo in the node's code would then be replaced by bar. The node name is given by the argument to start-ros-node or with-ros-node. It can, however, be overridden by including a command-line argument of the form __name=foo. The namespace is set as follows: if there is a command-line argument __ns:=foo, the namespace is foo. If not, and if the environment variable ROS_NAMESPACE is set to bar, the namespace is bar. If not, the namespace is /. All commands below that take a name of a topic, service, or parameter can be given an absolute (/foo/bar/baz), relative (baz/qux), or private (~qux) name.
\section startstop Starting and stopping a node
See documentation for functions start-ros-node, shutdown-ros-node, and with-ros-node.
\section topic Topics
See functions advertise, subscribe, publish, publish-msg.
\section services Services
See functions call-service, def-service-callback, register-service, register-service-fn, wait-for-service, make-request.
\section params Parameters
See functions get-param, set-param, has-param, delete-param.
\section node Node information
See function node-status.
\section misc Miscellaneous functions
See make-uri, fully-qualified-name, loop-at-most-every, ros-time,
\section types Message data types
Each ROS message type has a corresponding Lisp class and operations on it. A message type foo in ROS package bar corresponds to a Lisp class named <foo> in the bar-msg Lisp package. If your code will create or operate on objects of this type, it should contain the form (roslisp:load-message-types "bar/foo"). Operations in the message's package:
- An object of type <foo> in package bar-msg, with initial value of field baz equal to 3, is created using (make-instance 'bar-msg:<foo> :baz 3).
- Given a field named baz in an object m of the above message type, it can be read using (bar-msg:baz-val m).
However, it is recommended that you use the list operations below such as with-fields, unless this is slowing your code down.
The roslisp Lisp package contains some additional generic operations that work on any message:
- symbol-code M S. M is either a message or the name of a message class. S is a keyword symbol naming a constant declaration in the .msg file. Returns the value of the constant. For example, to get the value of the DEBUG constant in roslib/Log.msg, use (symbol-code 'roslib-msg:<Log> :debug) or (symbol-code m :debug) where m is an instance of '<Log>.
- ros-message-to-list MSG
- list-to-ros-message L
- pprint-ros-message STREAM MSG prints the message to the given stream in human-readable format. This is also set as the default dispatch function for ROS messages in Lisp's pretty printer. So if you have pretty printing turned on, and call a function from the prompt that returns a ROS message, that return value will be printed human-readably using pprint-ros-message. Similarly, if your code contains something like (format t "The message is ~a" m), that will DTRT.
There are a few additional operations that use the list representation of ros messages, and are therefore less efficient, but more readable and convenient for interactive use. See with-fields, make-message, modify-message-copy, and setf-msg.
IMPORTANT: message objects are assumed to be immutable; this assumption may be used in future to cache various things. In other words, if m is a variable that refers to some message object, don't do something like (setf (slot-value m 'my-field) 42). Instead, in this situation, do something like (setf-msg m 'my-field 42) (of course, it's always legal to do something like (setq m (function-that-returns-new-message-object)) since that just changes what m refers to rather than modifying the pointed-to object). When constructing messages, either use the form (make-instance '<Foo> :field1 42 :field24) or (make-msg "my_package/Foo" :field1 42 :field2 24). Don't use the C++-inspired way of first creating the object then setting its fields.
\section servicetypes Service Data Types
Given a ROS service type qux in the bar ROS package, there are corresponding message types <qux-request> and <qux-response> in the bar-srv Lisp package. The request and response messages can be operated on like any other message.
*/
| 0 |
apollo_public_repos/apollo-platform/ros | apollo_public_repos/apollo-platform/ros/roslisp/manifest.xml | <package>
<description brief="A Lisp client library for ROS">
This package is a Lisp client library for ROS, the Robot Operating
System.
</description>
<author>Bhaskara Marthi, Brian Gerkey, Lorenz Mösenlechner, Thibault Kruse</author>
<license>BSD</license>
<review status="experimental" notes="" />
<depend package="roslang" />
<depend package="rosgraph_msgs" />
<depend package="std_srvs" />
<depend package="rospack" />
<export>
<roslang cmake="${prefix}/rosbuild/roslisp.cmake" />
</export>
<rosdep name="sbcl" />
<url>http://ros.org/wiki/roslisp</url>
</package>
| 0 |
apollo_public_repos/apollo-platform/ros | apollo_public_repos/apollo-platform/ros/roslisp/.tar | {!!python/unicode 'url': 'https://github.com/ros-gbp/roslisp-release/archive/release/indigo/roslisp/1.9.20-0.tar.gz',
!!python/unicode 'version': roslisp-release-release-indigo-roslisp-1.9.20-0}
| 0 |
apollo_public_repos/apollo-platform/ros | apollo_public_repos/apollo-platform/ros/roslisp/README.rst | roslisp
========
Common Lisp library for interaction with ROS (Robot operating system).
See http://www.ros.org/wiki/roslisp
Tested using SBCL.
| 0 |
apollo_public_repos/apollo-platform/ros | apollo_public_repos/apollo-platform/ros/roslisp/CHANGELOG.rst | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Changelog for package roslisp
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1.9.20 (2016-04-14)
-------------------
* Merge pull request `#28 <https://github.com/ros/roslisp/issues/28>`_ from gaya-/master
In ADD_LISP_EXECUTABLE added a check for slashes in first argument
* in cmake script minor nicification
* [cmake] in ADD_LISP_EXECUTABLE added a check for slashes in first argument
* Contributors: Gayane Kazhoyan, Georg Bartels
1.9.19 (2015-08-14)
-----------
* Merge pull request `#25 <https://github.com/ros/roslisp/issues/25>`_ from airballking/symbol-codes
roslisp-msg-protocol: looking up symbols from constants
* Followed Gaya's suggestion of throwing an error if no symbol-code with the requested code can be found in (code-symbol ...).
* Merge pull request `#26 <https://github.com/ros/roslisp/issues/26>`_ from gaya-/deprecated-quit
Replaced deprecated SB-EXT:QUIT with SB-EXT:EXIT
* Merge pull request `#19 <https://github.com/ros/roslisp/issues/19>`_ from gaya-/master
Fixed the outdated executables generation pipeline
* Replaced deprecated SB-EXT:QUIT with SB-EXT:EXIT
* Contributors: Dirk Thomas, Gayane Kazhoyan, Georg Bartels
1.9.17 (2014-10-02)
-------------------
* Merge pull request `#20 <https://github.com/ros/roslisp/issues/20>`_ from daewok/use_sim_time
use_sim_time parameter should be absolute.
* Merge pull request `#18 <https://github.com/ros/roslisp/issues/18>`_ from airballking/fix-issue17
fix for ASDF3 compatibility
* Merge pull request `#16 <https://github.com/ros/roslisp/issues/16>`_ from jannikb/master
Fixed Issue `ros/roslisp#12 <https://github.com/ros/roslisp/issues/12>`_
* Merge pull request `#15 <https://github.com/ros/roslisp/issues/15>`_ from jannikb/master
Start fixing issue `ros/roslisp#12 <https://github.com/ros/roslisp/issues/12>`_
* Contributors: Eric Timmons, Georg Bartels, Jannik Buckelo, Lorenz Mösenlechner
1.9.16 (2014-04-22)
-------------------
* Added Georg Bartels as maintainer in package.xml.
* Bug-fix: Export SERVICE-CALL-ERROR symbol.
* Bug-fix: Don't throw END-OF-FILE condition in TCPROS-DO-SERVICE-REQUEST.
* Bug-fix: Corrected typo 'close-persistent-service'.
* Contributors: Gayane Kazhoyan, Georg Bartels
1.9.15 (2013-12-03)
-------------------
* Bug-fix: Make sure 'asdf-paths-to-add' does not contain any 'nil' pathnames.
* Contributors: Georg Bartels
1.9.14 (2013-11-21)
-------------------
* Merge pull request (`#10 <https://github.com/ros/roslisp/issues/10>`_) from ros/relocatable
resolve roslisp path in installspace at runtime (`#490 <https://github.com/ros/catkin/issues/490>`_)
* resolve roslisp path in installspace at runtime (`#490 <https://github.com/ros/catkin/issues/490>`_)
* Contributors: Dirk Thomas, Georg Bartels, Lorenz Moesenlechner
1.9.13 (2013-06-24)
-------------------
* Merge pull request (`#9 <https://github.com/ros/roslisp/issues/9>`_) from ros/fix_env_hook
fix environment hook to set ROSLISP_PACKAGE_DIRECTORIES in devel space
* fix environment hook to set ROSLISP_PACKAGE_DIRECTORIES to all devel spaces
* Contributors: Dirk Thomas, Georg Bartels
1.9.12 (2013-06-18)
-------------------
* Merge pull request (`#3 <https://github.com/ros/roslisp/issues/3>`_) from airballking/master
Convenience function create messages for publication object AND convenience service-client interface.
* added buildtool_depend catkin to package.xml
* Added a convenience function to create message for topics that uses publication to get the message type.
* Contributors: Aaron Blasdel, Georg Bartels, Lorenz Moesenlechner
1.9.11 (2012-11-28)
-------------------
* Improved wrapper script generation to not require the ROS package sbcl.
* Throw an error if *LOAD-TRUENAME* is unbound in roslisp-sbcl-init.
* Contributors: Lorenz Moesenlechner
1.9.10 (2012-11-20)
-------------------
* Removed directory `asdf` form install target.
* Don't use rospack or the asdf subdirectory to find system load-manifest.
Instead, we use the directory of the initfile directly, assuming that
it's always in the roslisp directory.
* Got rid of asdf subdirectory and symbolic links.
As of asdf2, the symbolic links to asd files are not required anymore.
They even screw up the deb build proces. Deleting them.
* Contributors: Lorenz Moesenlechner
1.9.9 (2012-11-09)
------------------
* Added find_package for catkin in CMakeLists.txt.
* Contributors: Lorenz Moesenlechner
1.9.8 (2012-10-26)
------------------
* Check for unambiguous type declaration in with-fields macro.
If the user declares the type using OR, we cannot use it for optimizing
the macro expansion since it is ambiguous. Fixes (`#1 <https://github.com/ros/roslisp/issues/1>`_).
* Updated dependencies in manifest.xml file.
* Updated run-dependencies in package.xml.
* Updated CMakeLists for new catkin.
* Got rid of call of catkin_stack.
* Contributors: Lorenz Moesenlechner
1.9.7 (2012-09-27)
------------------
* Change of maintainer to Lorenz Moesenlechner
* Various catkin fixes
* Contributors: Dave Hershberger, Dirk Thomas, Lorenz Moesenlechner
1.9.0 (2012-08-30)
------------------
* Begin Catkinization
* Initial development
* Contributors: Dirk Thomas, Lorenz Moesenlechner, Thibault Kruse, bhaskara, dirk-thomas, gerkey, kruset, kwc, lorenz, mkjaergaard, tfoote
| 0 |
apollo_public_repos/apollo-platform/ros/roslisp | apollo_public_repos/apollo-platform/ros/roslisp/s-xml/ChangeLog | 2005-11-20 Sven Van Caekenberghe <[email protected]>
* added xml prefix namespace as per REC-xml-names-19990114 (by Rudi Schlatte)
2005-11-06 Sven Van Caekenberghe <[email protected]>
* removed Debian packaging directory (on Luca's request)
* added CDATA support (patch contributed by Peter Van Eynde [email protected])
2005-08-30 Sven Van Caekenberghe <[email protected]>
* added Debian packaging directory (contributed by Luca Capello [email protected])
* added experimental XML namespace support
2005-02-03 Sven Van Caekenberghe <[email protected]>
* release 5 (cvs tag RELEASE_5)
* added :start and :end keywords to print-string-xml
* fixed a bug: in a tag containing whitespace, like <foo> </foo> the parser collapsed
and ingnored all whitespace and considered the tag to be empty!
this is now fixed and a unit test has been added
* cleaned up xml character escaping a bit: single quotes and all normal whitespace
(newline, return and tab) is preserved a unit test for this has been added
* IE doesn't understand the ' XML entity, so I've commented that out for now.
Also, using actual newlines for newlines is probably better than using #xA,
which won't get any end of line conversion by the server or user agent.
June 2004 Sven Van Caekenberghe <[email protected]>
* release 4
* project moved to common-lisp.net, renamed to s-xml,
* added examples counter, tracer and remove-markup, improved documentation
13 Jan 2004 Sven Van Caekenberghe <[email protected]>
* release 3
* added ASDF systems
* optimized print-string-xml
10 Jun 2003 Sven Van Caekenberghe <[email protected]>
* release 2
* added echo-xml function: we are no longer taking the car when
the last seed is returned from start-parse-xml
25 May 2003 Sven Van Caekenberghe <[email protected]>
* release 1
* first public release of working code
* tested on OpenMCL
* rewritten to be event-based, to improve efficiency and
to optionally use different DOM representations
* more documentation
end of 2002 Sven Van Caekenberghe <[email protected]>
* release 0
* as part of an XML-RPC implementation
$Id: ChangeLog,v 1.5 2005/11/20 14:24:33 scaekenberghe Exp $
| 0 |
apollo_public_repos/apollo-platform/ros/roslisp | apollo_public_repos/apollo-platform/ros/roslisp/s-xml/Makefile | # $Id: Makefile,v 1.3 2004/07/08 19:31:22 scaekenberghe Exp $
default:
@echo Possible targets:
@echo clean-openmcl --- remove all '*.dfsl' recursively
@echo clean-lw --- remove all '*.nfasl' recursively
@echo clean-emacs --- remove all '*~' recursively
@echo clean --- all of the above
clean-openmcl:
find . -name "*.dfsl" | xargs rm
clean-lw:
find . -name "*.nfasl" | xargs rm
clean-emacs:
find . -name "*~" | xargs rm
clean: clean-openmcl clean-lw clean-emacs
#
# This can obviously only be done by a specific person in a very specific context ;-)
#
PRJ=s-xml
ACCOUNT=scaekenberghe
CVSRT=:ext:$(ACCOUNT)@common-lisp.net:/project/$(PRJ)/cvsroot
release:
rm -rf /tmp/$(PRJ) /tmp/public_html /tmp/$(PRJ).tgz /tmp/$(PRJ).tgz.asc
cd /tmp; cvs -d$(CVSRT) export -r HEAD $(PRJ); cvs -d$(CVSRT) export -r HEAD public_html
mv /tmp/public_html /tmp/$(PRJ)/doc
cd /tmp; gnutar cvfz $(PRJ).tgz $(PRJ); gpg -a -b $(PRJ).tgz
scp /tmp/$(PRJ).tgz $(ACCOUNT)@common-lisp.net:/project/$(PRJ)/public_html
scp /tmp/$(PRJ).tgz.asc $(ACCOUNT)@common-lisp.net:/project/$(PRJ)/public_html
| 0 |
apollo_public_repos/apollo-platform/ros/roslisp | apollo_public_repos/apollo-platform/ros/roslisp/s-xml/s-xml.asd | ;;;; -*- Mode: LISP -*-
;;;;
;;;; $Id: s-xml.asd,v 1.2 2005/12/14 21:49:04 scaekenberghe Exp $
;;;;
;;;; The S-XML ASDF system definition
;;;;
;;;; Copyright (C) 2002, 2004 Sven Van Caekenberghe, Beta Nine BVBA.
;;;;
;;;; You are granted the rights to distribute and use this software
;;;; as governed by the terms of the Lisp Lesser General Public License
;;;; (http://opensource.franz.com/preamble.html), also known as the LLGPL.
(in-package :asdf)
(defsystem :s-xml
:name "S-XML"
:author "Sven Van Caekenberghe <[email protected]>"
:version "3"
:maintainer "Sven Van Caekenberghe <[email protected]>, Brian Mastenbrook <>, Rudi Schlatte <>"
:licence "Lisp Lesser General Public License (LLGPL)"
:description "Simple Common Lisp XML Parser"
:long-description "S-XML is a Common Lisp implementation of a simple XML parser, with a SAX-like and DOM interface"
:components
((:module
:src
:components ((:file "package")
(:file "xml" :depends-on ("package"))
(:file "dom" :depends-on ("package" "xml"))
(:file "lxml-dom" :depends-on ("dom"))
(:file "sxml-dom" :depends-on ("dom"))
(:file "xml-struct-dom" :depends-on ("dom"))))))
;;;; eof
| 0 |
apollo_public_repos/apollo-platform/ros/roslisp/s-xml | apollo_public_repos/apollo-platform/ros/roslisp/s-xml/test/test-lxml-dom.lisp | ;;;; -*- mode: lisp -*-
;;;;
;;;; $Id: test-lxml-dom.lisp,v 1.2 2005/11/06 12:44:48 scaekenberghe Exp $
;;;;
;;;; Unit and functional tests for lxml-dom.lisp
;;;;
;;;; Copyright (C) 2002, 2004 Sven Van Caekenberghe, Beta Nine BVBA.
;;;;
;;;; You are granted the rights to distribute and use this software
;;;; as governed by the terms of the Lisp Lesser General Public License
;;;; (http://opensource.franz.com/preamble.html), also known as the LLGPL.
(in-package :s-xml)
(assert
(equal (with-input-from-string (stream " <foo/>")
(parse-xml stream :output-type :lxml))
:|foo|))
(assert
(equal (parse-xml-string "<tag1><tag2 att1='one'/>this is some text</tag1>"
:output-type :lxml)
'(:|tag1|
((:|tag2| :|att1| "one"))
"this is some text")))
(assert
(equal (parse-xml-string "<TAG><foo></TAG>"
:output-type :lxml)
'(:TAG "<foo>")))
(assert
(equal (parse-xml-string
"<P><INDEX ITEM='one'/> This is some <B>bold</B> text, with a leading & trailing space </P>"
:output-type :lxml)
'(:p
((:index :item "one"))
" This is some "
(:b "bold")
" text, with a leading & trailing space ")))
(assert
(consp (parse-xml-file (merge-pathnames "xhtml-page.xml" *load-pathname*)
:output-type :lxml)))
(assert
(consp (parse-xml-file (merge-pathnames "ant-build-file.xml" *load-pathname*)
:output-type :lxml)))
(assert
(consp (parse-xml-file (merge-pathnames "plist.xml" *load-pathname*)
:output-type :lxml)))
(assert
(string-equal (print-xml-string :|foo| :input-type :lxml)
"<foo/>"))
(assert
(string-equal (print-xml-string '((:|foo| :|bar| "1")) :input-type :lxml)
"<foo bar=\"1\"/>"))
(assert
(string-equal (print-xml-string '(:foo "some text") :input-type :lxml)
"<FOO>some text</FOO>"))
(assert
(string-equal (print-xml-string '(:|foo| :|bar|) :input-type :lxml)
"<foo><bar/></foo>"))
(assert (string-equal (second
(with-input-from-string (stream "<foo><![CDATA[<greeting>Hello, world!</greeting>]]></foo>")
(parse-xml stream :output-type :lxml)))
"<greeting>Hello, world!</greeting>"))
(assert (string-equal (second
(with-input-from-string (stream "<foo><![CDATA[<greeting>Hello, < world!</greeting>]]></foo>")
(parse-xml stream :output-type :lxml)))
"<greeting>Hello, < world!</greeting>"))
;;;; eof | 0 |
apollo_public_repos/apollo-platform/ros/roslisp/s-xml | apollo_public_repos/apollo-platform/ros/roslisp/s-xml/test/test-sxml-dom.lisp | ;;;; -*- mode: lisp -*-
;;;;
;;;; $Id: test-sxml-dom.lisp,v 1.1.1.1 2004/06/07 18:49:59 scaekenberghe Exp $
;;;;
;;;; Unit and functional tests for sxml-dom.lisp
;;;;
;;;; Copyright (C) 2002, 2004 Sven Van Caekenberghe, Beta Nine BVBA.
;;;;
;;;; You are granted the rights to distribute and use this software
;;;; as governed by the terms of the Lisp Lesser General Public License
;;;; (http://opensource.franz.com/preamble.html), also known as the LLGPL.
(in-package :s-xml)
(assert
(equal (with-input-from-string (stream " <foo/>")
(parse-xml stream :output-type :sxml))
'(:|foo|)))
(assert
(equal (parse-xml-string "<tag1><tag2 att1='one'/>this is some text</tag1>"
:output-type :sxml)
'(:|tag1|
(:|tag2| (:@ (:|att1| "one")))
"this is some text")))
(assert
(equal (parse-xml-string "<TAG><foo></TAG>"
:output-type :sxml)
'(:TAG "<foo>")))
(assert
(equal (parse-xml-string
"<P><INDEX ITEM='one'/> This is some <B>bold</B> text, with a leading & trailing space </P>"
:output-type :sxml)
'(:p
(:index (:@ (:item "one")))
" This is some "
(:b "bold")
" text, with a leading & trailing space ")))
(assert
(consp (parse-xml-file (merge-pathnames "xhtml-page.xml" *load-pathname*)
:output-type :sxml)))
(assert
(consp (parse-xml-file (merge-pathnames "ant-build-file.xml" *load-pathname*)
:output-type :sxml)))
(assert
(consp (parse-xml-file (merge-pathnames "plist.xml" *load-pathname*)
:output-type :sxml)))
(assert
(string-equal (print-xml-string '(:|foo|) :input-type :sxml)
"<foo/>"))
(assert
(string-equal (print-xml-string '(:|foo| (:@ (:|bar| "1"))) :input-type :sxml)
"<foo bar=\"1\"/>"))
(assert
(string-equal (print-xml-string '(:foo "some text") :input-type :sxml)
"<FOO>some text</FOO>"))
(assert
(string-equal (print-xml-string '(:|foo| (:|bar|)) :input-type :sxml)
"<foo><bar/></foo>"))
;;;; eof | 0 |
apollo_public_repos/apollo-platform/ros/roslisp/s-xml | apollo_public_repos/apollo-platform/ros/roslisp/s-xml/test/remove-markup.lisp | ;;;; -*- mode: lisp -*-
;;;;
;;;; $Id: remove-markup.lisp,v 1.1 2004/06/11 11:14:43 scaekenberghe Exp $
;;;;
;;;; Remove markup from an XML document using the SSAX interface
;;;;
;;;; Copyright (C) 2004 Sven Van Caekenberghe, Beta Nine BVBA.
;;;;
;;;; You are granted the rights to distribute and use this software
;;;; as governed by the terms of the Lisp Lesser General Public License
;;;; (http://opensource.franz.com/preamble.html), also known as the LLGPL.
(in-package :s-xml)
(defun remove-xml-markup (in)
(let* ((state (make-instance 'xml-parser-state
:text-hook #'(lambda (string seed) (cons string seed))))
(result (start-parse-xml in state)))
(apply #'concatenate 'string (nreverse result))))
;;;; eof | 0 |
apollo_public_repos/apollo-platform/ros/roslisp/s-xml | apollo_public_repos/apollo-platform/ros/roslisp/s-xml/test/tracer.lisp | ;;;; -*- mode: lisp -*-
;;;;
;;;; $Id: tracer.lisp,v 1.2 2004/06/11 11:14:43 scaekenberghe Exp $
;;;;
;;;; A simple SSAX tracer example that can be used to understand how the hooks are called
;;;;
;;;; Copyright (C) 2004 Sven Van Caekenberghe, Beta Nine BVBA.
;;;;
;;;; You are granted the rights to distribute and use this software
;;;; as governed by the terms of the Lisp Lesser General Public License
;;;; (http://opensource.franz.com/preamble.html), also known as the LLGPL.
(in-package :s-xml)
(defun trace-xml-log (level msg &rest args)
(indent *standard-output* level)
(apply #'format *standard-output* msg args)
(terpri *standard-output*))
(defun trace-xml-new-element-hook (name attributes seed)
(let ((new-seed (cons (1+ (car seed)) (1+ (cdr seed)))))
(trace-xml-log (car seed)
"(new-element :name ~s :attributes ~:[()~;~:*~s~] :seed ~s) => ~s"
name attributes seed new-seed)
new-seed))
(defun trace-xml-finish-element-hook (name attributes parent-seed seed)
(let ((new-seed (cons (1- (car seed)) (1+ (cdr seed)))))
(trace-xml-log (car parent-seed)
"(finish-element :name ~s :attributes ~:[()~;~:*~s~] :parent-seed ~s :seed ~s) => ~s"
name attributes parent-seed seed new-seed)
new-seed))
(defun trace-xml-text-hook (string seed)
(let ((new-seed (cons (car seed) (1+ (cdr seed)))))
(trace-xml-log (car seed)
"(text :string ~s :seed ~s) => ~s"
string seed new-seed)
new-seed))
(defun trace-xml (in)
"Parse and trace a toplevel XML element from stream in"
(start-parse-xml in
(make-instance 'xml-parser-state
:seed (cons 0 0)
;; seed car is xml element nesting level
;; seed cdr is ever increasing from element to element
:new-element-hook #'trace-xml-new-element-hook
:finish-element-hook #'trace-xml-finish-element-hook
:text-hook #'trace-xml-text-hook)))
(defun trace-xml-file (pathname)
"Parse and trace XMl from the file at pathname"
(with-open-file (in pathname)
(trace-xml in)))
;;;; eof
| 0 |
apollo_public_repos/apollo-platform/ros/roslisp/s-xml | apollo_public_repos/apollo-platform/ros/roslisp/s-xml/test/plist.xml | <?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>AppleDockIconEnabled</key>
<true/>
<key>AppleNavServices:GetFile:0:Path</key>
<string>file://localhost/Users/sven/Pictures/</string>
<key>AppleNavServices:GetFile:0:Position</key>
<data>
AOUBXw==
</data>
<key>AppleNavServices:GetFile:0:Size</key>
<data>
AAAAAAFeAcI=
</data>
<key>AppleNavServices:PutFile:0:Disclosure</key>
<data>
AQ==
</data>
<key>AppleNavServices:PutFile:0:Path</key>
<string>file://localhost/Users/sven/Desktop/</string>
<key>AppleNavServices:PutFile:0:Position</key>
<data>
AUIBVQ==
</data>
<key>AppleNavServices:PutFile:0:Size</key>
<data>
AAAAAACkAdY=
</data>
<key>AppleSavePanelExpanded</key>
<string>YES</string>
<key>NSDefaultOpenDirectory</key>
<string>~/Desktop</string>
<key>NSNoBigString</key>
<true/>
</dict>
</plist>
| 0 |
apollo_public_repos/apollo-platform/ros/roslisp/s-xml | apollo_public_repos/apollo-platform/ros/roslisp/s-xml/test/xhtml-page.xml | <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<title>XHTML Tutorial</title>
<meta http-equiv="Content-Type" content="text/html; charset=windows-1252" />
<meta name="Keywords" content="XML,tutorial,HTML,DHTML,CSS,XSL,XHTML,JavaScript,ASP,ADO,VBScript,DOM,authoring,programming,learning,beginner's guide,primer,lessons,school,howto,reference,examples,samples,source code,demos,tips,links,FAQ,tag list,forms,frames,color table,W3C,Cascading Style Sheets,Active Server Pages,Dynamic HTML,Internet database development,Webbuilder,Sitebuilder,Webmaster,HTMLGuide,SiteExpert" />
<meta name="Description" content="HTML,CSS,JavaScript,DHTML,XML,XHTML,ASP,ADO and VBScript tutorial from W3Schools." />
<meta http-equiv="pragma" content="no-cache" />
<meta http-equiv="cache-control" content="no-cache" />
<link rel="stylesheet" type="text/css" href="../stdtheme.css" />
</head>
<body>
<table border="0" cellpadding="0" cellspacing="0" width="775">
<tr>
<td width="140" class="content" valign="top">
<br />
<a class="left" href="../default.asp" target="_top"><b>HOME</b></a><br />
<br />
<b>XHTML Tutorial</b><br />
<a class="left" target="_top" href="default.asp" style='font-weight:bold;color:#000000;background-color:transparent;'>XHTML HOME</a><br />
<a class="left" target="_top" href="xhtml_intro.asp" >XHTML Introduction</a><br />
<a class="left" target="_top" href="xhtml_why.asp" >XHTML Why</a><br />
<a class="left" target="_top" href="xhtml_html.asp" >XHTML v HTML</a><br />
<a class="left" target="_top" href="xhtml_syntax.asp" >XHTML Syntax</a><br />
<a class="left" target="_top" href="xhtml_dtd.asp" >XHTML DTD</a><br />
<a class="left" target="_top" href="xhtml_howto.asp" >XHTML HowTo</a><br />
<a class="left" target="_top" href="xhtml_validate.asp" >XHTML Validation</a><br />
<br />
<b>Quiz</b>
<br />
<a class="left" target="_top" href="xhtml_quiz.asp" >XHTML Quiz</a><br />
<br />
<b>References</b>
<br />
<a class="left" target="_top" href="xhtml_reference.asp" >XHTML Tag List</a><br />
<a class="left" target="_top" href="xhtml_standardattributes.asp" >XHTML Attributes</a><br />
<a class="left" target="_top" href="xhtml_eventattributes.asp" >XHTML Events</a><br />
</td>
<td width="490" valign="top">
<table width="100%" bgcolor="#FFFFFF" border="1" cellpadding="7" cellspacing="0">
<tr>
<td>
<center>
<a href="http://ad.doubleclick.net/jump/N1951.w3schools/B1097963;sz=468x60;ord=[timestamp]?" target="_new">
<img src="http://ad.doubleclick.net/ad/N1951.w3schools/B1097963;sz=468x60;ord=[timestamp]?"
border="0" width="468" height="60" alt="Corel XMetal 3" /></a>
<br />Please Visit Our Sponsors !
</center>
<h1>XHTML Tutorial</h1>
<a href="../default.asp"><img border="0" src="../images/btn_previous.gif" alt="Previous" /></a>
<a href="xhtml_intro.asp"><img border="0" src="../images/btn_next.gif" width="100" height="20" alt="Next" /></a>
<hr />
<h2>XHTML Tutorial</h2>
<p>XHTML is the next generation of HTML! In our XHTML tutorial you will learn the difference between HTML and XHTML, and how to use XHTML in your future
applications. You will also see how we converted this Web site into XHTML. <a href="xhtml_intro.asp">Start Learning
XHTML!</a></p>
<h2>XHTML Quiz Test</h2>
<p>Test your XHTML skills at W3Schools! <a href="xhtml_quiz.asp">Start XHTML
Quiz!</a> </p>
<h2>XHTML References</h2>
<p>At W3Schools you will find complete XHTML references about tags, attributes
and events. <a href="xhtml_reference.asp">XHTML 1.0 References</a>.</p>
<hr />
<h2>Table of Contents</h2>
<p><a href="xhtml_intro.asp">Introduction to XHTML</a><br />
This chapter gives a brief introduction to XHTML and explains what XHTML is.</p>
<p><a href="xhtml_why.asp">XHTML - Why?</a><br />
This chapter explains why we needed a new language like XHTML.</p>
<p><a href="xhtml_html.asp">Differences between XHTML and HTML</a><br />
This chapter explains the main differences in syntax between XHTML and HTML.</p>
<p><a href="xhtml_syntax.asp">XHTML Syntax</a> <br />
This chapter explains the basic syntax of XHTML.</p>
<p><a href="xhtml_dtd.asp">XHTML DTD</a> <br />
This chapter explains the three different XHTML Document Type Definitions.</p>
<p><a href="xhtml_howto.asp">XHTML HowTo</a><br />
This chapter explains how this web site was converted from HTML to XHTML.</p>
<p><a href="xhtml_validate.asp">XHTML Validation</a><br />
This chapter explains how to validate XHTML documents.</p>
<hr />
<h2>XHTML References</h2>
<p><a href="xhtml_reference.asp">XHTML 1.0 Reference<br />
</a>Our complete XHTML 1.0 reference is an alphabetical list of all XHTML tags
with lots of examples and tips.</p>
<p><a href="xhtml_standardattributes.asp">XHTML 1.0 Standard Attributes<br />
</a>All the tags have attributes. The attributes for each tag are listed in the
examples in the "XHTML 1.0 Reference" page. The attributes listed here
are the core and language attributes all the tags has as standard (with
few exceptions). This reference describes the attributes, and shows possible
values for each.</p>
<p><a href="xhtml_eventattributes.asp">XHTML 1.0 Event Attributes<br />
</a>All the standard event attributes of the tags. This reference describes the attributes, and shows possible
values for each.</p>
<hr />
<a href="../default.asp"><img border="0" src="../images/btn_previous.gif" width="100" height="20" alt="Previous" /></a>
<a href="xhtml_intro.asp"><img border="0" src="../images/btn_next.gif" width="100" height="20" alt="Next" /></a>
<hr />
<p>
Jump to: <a href="#top" target="_top"><b>Top of Page</b></a>
or <a href="/" target="_top"><b>HOME</b></a> or
<a href='/xhtml/default.asp?output=print' target="_blank">
<img src="../images/print.gif" alt="Printer Friendly" border="0" />
<b>Printer friendly page</b></a>
</p>
<hr />
<h2>Search W3Schools:</h2>
<form method="get" name="searchform" action="http://www.google.com/search" target="_blank">
<input type="hidden" name="as_sitesearch" value="www.w3schools.com" />
<input type="text" size="30" name="as_q" />
<input type="submit" value=" Go! " />
</form>
<hr />
<h2>What Others Say About Us</h2>
<p>Does the world know about us? Check out these places:</p>
<p>
<a href="http://search.dogpile.com/texis/search?q=W3schools" target="_blank">Dogpile</a>
<a href="http://www.altavista.com/cgi-bin/query?q=W3Schools" target="_blank">Alta Vista</a>
<a href="http://search.msn.com/results.asp?q=W3Schools" target="_blank">MSN</a>
<a href="http://www.google.com/search?q=W3Schools" target="_blank">Google</a>
<a href="http://search.excite.com/search.gw?search=W3Schools" target="_blank">Excite</a>
<a href="http://search.lycos.com/main/?query=W3Schools" target="_blank">Lycos</a>
<a href="http://search.yahoo.com/search?p=w3schools" target="_blank">Yahoo</a>
<a href="http://www.ask.com/main/askJeeves.asp?ask=W3Schools" target="_blank">Ask Jeeves</a>
</p>
<hr />
<h2>We Help You For Free. You Can Help Us!</h2>
<ul>
<li><a href="../tellyourgroup.htm" target="blank">Tell your newsgroup or mailing list</a></li>
<li><a href="../about/about_linking.asp">Link to us from your pages</a></li>
<li><a href="../about/about_helpers.asp">Help us correct errors and broken links</a></li>
<li><a href="../about/about_helpers.asp">Help us with spelling and grammar</a></li>
<li><a href="http://validator.w3.org/check/referer" target="_blank">Validate the XHTML code of this page</a></li>
</ul>
<hr />
<p>
W3Schools is for training only. We do not warrant its correctness or its fitness for use.
The risk of using it remains entirely with the user. While using this site, you agree to have read and accepted our
<a href="../about/about_copyright.asp">terms of use</a> and
<a href="../about/about_privacy.asp">privacy policy</a>.</p>
<p>
<a href="../about/about_copyright.asp">Copyright 1999-2002</a> by Refsnes Data. All Rights Reserved</p>
<hr />
<table border="0" width="100%" cellspacing="0" cellpadding="0"><tr>
<td width="25%" align="left">
<a href="http://validator.w3.org/check/referer" target="_blank">
<img src="../images/vxhtml.gif" alt="Validate" width="88" height="31" border="0" /></a>
</td>
<td width="50%" align="center">
<a href="../xhtml/" target="_top">How we converted to XHTML</a>
</td>
<td width="25%" align="right">
<a href="http://jigsaw.w3.org/css-validator/check/referer" target="_blank">
<img src="../images/vcss.gif" alt="Validate" width="88" height="31" border="0" /></a>
</td>
</tr></table>
</td>
</tr>
</table>
</td>
<td width="144" align="center" valign="top">
<table border="1" width="100%" bgcolor="#ffffff" cellpadding="0" cellspacing="0"><tr>
<td align="center" class="right"><br />
<a href="http://www.dotnetcharting.com" target="_blank"><img src="../images/dnc-icon.gif" alt="Web charting" border="0" /></a>
<br />
<a class="right" href="http://www.dotnetcharting.com" target="_blank">Web based charting<br />for ASP.NET</a>
<br /><br />
</td></tr></table>
<table border="1" width="100%" bgcolor="#ffffff" cellpadding="0" cellspacing="0"><tr>
<td align="center" class="right">
<br />
<a href="../hosting/default.asp">
Your own Web Site?<br />
<br />Read W3Schools
<br />Hosting Tutorial</a>
<br />
<br />
</td></tr></table>
<table border="1" width="100%" bgcolor="#ffffff" cellpadding="0" cellspacing="0"><tr>
<td align="center" class="right">
<br />
<a class="red" href="http://www.dotdnr.com" target="_blank">$15 Domain Name<br />Registration<br />Save $20 / year!</a>
<br />
<br />
</td></tr></table>
<table border="1" width="100%" bgcolor="#ffffff" cellpadding="0" cellspacing="0">
<tr><td align="center" class="right">
<br />
<b>SELECTED LINKS</b>
<br /><br />
<a class="right" href="http://opogee.com/clk/dangtingcentiaonie" target="_blank">University Online<br />
Master Degree<br />Bachelor Degree</a>
<br /><br />
<a class="right" href="../software/default.asp" target="_top">Web Software</a>
<br /><br />
<a class="right" href="../appml/default.asp" target="_top">The Future of<br />Web Development</a>
<br /><br />
<a class="right" href="../careers/default.asp" target="_top">Jobs and Careers</a>
<br /><br />
<a class="right" href="../site/site_security.asp" target="_top">Web Security</a>
<br />
<a class="right" href="../browsers/browsers_stats.asp" target="_top">Web Statistics</a>
<br />
<a class="right" href="../w3c" target="_top">Web Standards</a>
<br /><br />
</td></tr></table>
<table border="1" width="100%" bgcolor="#ffffff" cellpadding="0" cellspacing="0"><tr>
<td align="center" class="right">
<br />
<b>Recommended<br />
Reading:</b><br /><br />
<a class="right" target="_blank"
href="http://www.amazon.com/exec/obidos/ASIN/059600026X/w3schools03">
<img src="../images/book_amazon_xhtml.jpg" border="0" alt="HTML XHTML" /></a>
<br /><br /></td>
</tr></table>
<table border="1" width="100%" bgcolor="#ffffff" cellpadding="0" cellspacing="0"><tr>
<td align="center" class="right">
<br />
<b>PARTNERS</b><br />
<br />
<a class="right" href="http://www.W3Schools.com" target="_blank">W3Schools</a><br />
<a class="right" href="http://www.topxml.com" target="_blank">TopXML</a><br />
<a class="right" href="http://www.visualbuilder.com" target="_blank">VisualBuilder</a><br />
<a class="right" href="http://www.xmlpitstop.com" target="_blank">XMLPitstop</a><br />
<a class="right" href="http://www.developersdex.com" target="_blank">DevelopersDex</a><br />
<a class="right" href="http://www.devguru.com" target="_blank">DevGuru</a><br />
<a class="right" href="http://www.programmersheaven.com/" target="_blank">Programmers Heaven</a><br />
<a class="right" href="http://www.codeproject.com" target="_blank">The Code Project</a><br />
<a class="right" href="http://www.tek-tips.com" target="_blank">Tek Tips Forum</a><br />
<a class="right" href="http://www.zvon.ORG/" target="_blank">ZVON.ORG</a><br />
<a class="right" href="http://www.topxml.com/search.asp" target="_blank">TopXML Search</a><br />
<br />
</td>
</tr></table>
</td></tr></table>
</body>
</html>
| 0 |
apollo_public_repos/apollo-platform/ros/roslisp/s-xml | apollo_public_repos/apollo-platform/ros/roslisp/s-xml/test/test-xml-struct-dom.lisp | ;;;; -*- mode: lisp -*-
;;;;
;;;; $Id: test-xml-struct-dom.lisp,v 1.2 2005/08/29 15:01:49 scaekenberghe Exp $
;;;;
;;;; Unit and functional tests for xml-struct-dom.lisp
;;;;
;;;; Copyright (C) 2002, 2004 Sven Van Caekenberghe, Beta Nine BVBA.
;;;;
;;;; You are granted the rights to distribute and use this software
;;;; as governed by the terms of the Lisp Lesser General Public License
;;;; (http://opensource.franz.com/preamble.html), also known as the LLGPL.
(in-package :s-xml)
(assert
(xml-equal (with-input-from-string (stream " <foo/>")
(parse-xml stream :output-type :xml-struct))
(make-xml-element :name :|foo|)))
(assert
(xml-equal (parse-xml-string "<tag1><tag2 att1='one'/>this is some text</tag1>"
:output-type :xml-struct)
(make-xml-element :name :|tag1|
:children (list (make-xml-element :name :|tag2|
:attributes '((:|att1| . "one")))
"this is some text"))))
(assert
(xml-equal (parse-xml-string "<tag><foo></tag>"
:output-type :xml-struct)
(make-xml-element :name :|tag|
:children (list "<foo>"))))
(assert
(xml-equal (parse-xml-string
"<P><INDEX ITEM='one'/> This is some <B>bold</B> text, with a leading & trailing space </P>"
:output-type :xml-struct)
(make-xml-element :name :p
:children (list (make-xml-element :name :index
:attributes '((:item . "one")))
" This is some "
(make-xml-element :name :b
:children (list "bold"))
" text, with a leading & trailing space "))))
(assert
(xml-element-p (parse-xml-file (merge-pathnames "xhtml-page.xml" *load-pathname*)
:output-type :xml-struct)))
(assert
(xml-element-p (parse-xml-file (merge-pathnames "ant-build-file.xml" *load-pathname*)
:output-type :xml-struct)))
(assert
(xml-element-p (parse-xml-file (merge-pathnames "plist.xml" *load-pathname*)
:output-type :xml-struct)))
(assert
(string-equal (print-xml-string (make-xml-element :name "foo")
:input-type :xml-struct)
"<foo/>"))
(assert
(string-equal (print-xml-string (make-xml-element :name "foo" :attributes '((:|bar| . "1")))
:input-type :xml-struct)
"<foo bar=\"1\"/>"))
(assert
(string-equal (print-xml-string (make-xml-element :name "foo" :children (list "some text"))
:input-type :xml-struct)
"<foo>some text</foo>"))
(assert
(string-equal (print-xml-string (make-xml-element :name "foo" :children (list (make-xml-element :name "bar")))
:input-type :xml-struct)
"<foo><bar/></foo>"))
;;;; eof | 0 |
apollo_public_repos/apollo-platform/ros/roslisp/s-xml | apollo_public_repos/apollo-platform/ros/roslisp/s-xml/test/ant-build-file.xml | <!-- $Id: ant-build-file.xml,v 1.1.1.1 2004/06/07 18:49:59 scaekenberghe Exp $ -->
<!-- Ant 1.2 build file -->
<project name="Libretto" default="compile" basedir=".">
<!-- set global properties for this build -->
<property name="src" value="${basedir}/src" />
<property name="rsrc" value="${basedir}/rsrc" />
<property name="build" value="${basedir}/bin" />
<property name="api" value="${basedir}/api" />
<property name="lib" value="${basedir}/lib" />
<property name="junit" value="${basedir}/junit" />
<property name="rsrc" value="${basedir}/rsrc" />
<target name="prepare">
<!-- Create the time stamp -->
<tstamp/>
<!-- Create the build directory structure used by compile -->
<mkdir dir="${build}" />
<mkdir dir="${api}" />
<mkdir dir="${junit}" />
<copy file="${rsrc}/build/build.version" tofile="${build}/build.properties"/>
<replace file="${build}/build.properties" token="@@@BUILD_ID@@@" value="${DSTAMP}-${TSTAMP}"/>
</target>
<target name="compile" depends="copy-rsrc">
<!-- Compile the java code from ${src} into ${build} -->
<javac srcdir="${src}" destdir="${build}" debug="on">
<classpath>
<fileset dir="${lib}">
<include name="log4j-core.jar" />
<include name="jaxp.jar" />
<include name="crimson.jar" />
<include name="jdom.jar" />
<include name="beanshell.jar" />
</fileset>
</classpath>
</javac>
</target>
<target name="compile-junit" depends="copy-rsrc">
<!-- Compile the java code from ${src} into ${build} -->
<javac srcdir="${junit}" destdir="${build}" debug="on">
<classpath>
<fileset dir="${lib}">
<include name="*.jar" />
</fileset>
</classpath>
</javac>
</target>
<target name="copy-rsrc" depends="prepare">
<!-- Copy various resource files into ${build} -->
<copy todir="${build}">
<fileset
dir="${basedir}"
includes="images/*.gif, images/*.jpg" />
</copy>
<copy todir="${build}">
<fileset
dir="${src}"
includes="be/beta9/libretto/data/*.txt" />
</copy>
<copy todir="${build}">
<fileset
dir="${rsrc}/log4j"
includes="log4j.properties" />
</copy>
</target>
<target name="c-header" depends="compile">
<javah destdir="${rsrc}/VC_source" class="be.beta9.libretto.io.ParallelPort">
<classpath>
<pathelement location="${build}" />
</classpath>
</javah>
</target>
<target name="test-parport" depends="compile">
<java
classname="be.beta9.libretto.io.ParallelPortWriter"
fork="yes">
<classpath>
<pathelement location="${build}" />
<fileset dir="${lib}">
<include name="*.jar" />
</fileset>
</classpath>
</java>
</target>
<target name="jar-simple" depends="compile">
<!-- Put everything in ${build} into the a jar file -->
<jar
jarfile="${basedir}/libretto.jar"
basedir="${build}"
manifest="${rsrc}/manifest/libretto.mf"/>
</target>
<target name="jar" depends="compile">
<!-- Put everything in ${build} into the a jar file including all dependecies -->
<unjar src="${lib}/jaxp.jar" dest="${build}" />
<unjar src="${lib}/crimson.jar" dest="${build}" />
<unjar src="${lib}/jdom.jar" dest="${build}" />
<unjar src="${lib}/log4j-core.jar" dest="${build}" />
<jar
jarfile="${basedir}/libretto.jar"
basedir="${build}"
manifest="${rsrc}/manifest/libretto.mf"/>
</target>
<target name="client-jar" depends="background-jar">
<!-- Put everything in ${build} into the a jar file including all dependecies -->
<unjar src="${lib}/log4j-core.jar" dest="${build}" />
<jar jarfile="${basedir}/libretto-client.jar" manifest="${rsrc}/manifest/libretto-client.mf">
<fileset dir="${build}">
<include name="build.properties"/>
<include name="log4j.properties"/>
<include name="be/beta9/libretto/io/*.class"/>
<include name="be/beta9/libretto/application/Build.class"/>
<include name="be/beta9/libretto/net/LibrettoTextClient*.class"/>
<include name="be/beta9/libretto/net/TestClientMessage.class"/>
<include name="be/beta9/libretto/net/ClientStatusMessageResult.class"/>
<include name="be/beta9/libretto/net/Client*.class"/>
<include name="be/beta9/libretto/net/Constants.class"/>
<include name="be/beta9/libretto/net/TextMessage.class"/>
<include name="be/beta9/libretto/net/MessageResult.class"/>
<include name="be/beta9/libretto/net/MessageException.class"/>
<include name="be/beta9/libretto/net/SingleTextMessage.class"/>
<include name="be/beta9/libretto/net/Message.class"/>
<include name="be/beta9/libretto/net/Util.class"/>
<include name="be/beta9/libretto/gui/ShowSingleTextFrame*.class"/>
<include name="be/beta9/libretto/gui/AWTTextView*.class"/>
<include name="be/beta9/libretto/model/AttributedString*.class"/>
<include name="be/beta9/libretto/model/AWTTextStyle.class"/>
<include name="be/beta9/libretto/model/LTextStyle.class"/>
<include name="be/beta9/libretto/model/AWTCharacterAttributes.class"/>
<include name="be/beta9/libretto/model/Java2DTextStyle.class"/>
<include name="be/beta9/libretto/model/LCharacterAttributes.class"/>
<include name="be/beta9/libretto/model/Java2DCharacterAttributes.class"/>
<include name="be/beta9/libretto/util/TextStyleManager.class"/>
<include name="be/beta9/libretto/util/Bean.class"/>
<include name="be/beta9/libretto/util/LibrettoSaxReader.class"/>
<include name="be/beta9/libretto/util/Preferences.class"/>
<include name="be/beta9/libretto/util/Utilities.class"/>
<include name="org/apache/log4j/**"/>
</fileset>
</jar>
</target>
<target name="background-jar" depends="compile">
<!-- Put everything in ${build} into the a jar file including all dependecies -->
<jar jarfile="${basedir}/background.jar" manifest="${rsrc}/manifest/background-black-window.mf">
<fileset dir="${build}">
<include name="be/beta9/libretto/gui/BackgroundBlackWindow.class"/>
</fileset>
</jar>
</target>
<target name="run" depends="compile">
<!-- Execute the main application -->
<java
classname="be.beta9.libretto.application.Libretto"
fork="yes">
<classpath>
<pathelement location="${build}" />
<fileset dir="${lib}">
<include name="log4j-core.jar" />
<include name="jaxp.jar" />
<include name="crimson.jar" />
<include name="jdom.jar" />
</fileset>
</classpath>
</java>
</target>
<target name="debug" depends="compile">
<!-- Execute the main application in debug mode -->
<java
classname="be.beta9.libretto.application.LibrettoDebug"
fork="yes">
<classpath>
<pathelement location="${build}" />
<fileset dir="${lib}">
<include name="*.jar" />
</fileset>
</classpath>
</java>
</target>
<target name="junit" depends="compile-junit">
<!-- Execute all junit tests -->
<java
classname="be.beta9.libretto.AllTests"
fork="yes">
<classpath>
<pathelement location="${build}" />
<fileset dir="${lib}">
<include name="*.jar" />
</fileset>
</classpath>
</java>
</target>
<target name="clean">
<!-- Delete the ${build} directory trees -->
<delete dir="${build}" />
<delete dir="${api}" />
</target>
<target name="api" depends="prepare">
<!-- Generate javadoc -->
<javadoc
packagenames="be.beta9.libretto.*"
sourcepath="${src}"
destdir="${api}"
windowtitle="Libretto"
author="true"
version="true"
use="true"/>
</target>
<target name="zip-all" depends="jar, client-jar">
<zip zipfile="libretto.zip">
<fileset dir="${basedir}">
<include name="libretto.jar"/>
<include name="libretto-client.jar"/>
</fileset>
</zip>
</target>
<target name="upload" depends="clean, zip-all">
<ftp
server="users.pandora.be"
userid="a002458"
password="bast0s"
remotedir="libretto"
verbose="true"
passive="true">
<fileset dir="${basedir}">
<include name="libretto.jar" />
<include name="libretto-client.jar" />
<include name="libretto.zip" />
</fileset>
</ftp>
</target>
</project>
| 0 |
apollo_public_repos/apollo-platform/ros/roslisp/s-xml | apollo_public_repos/apollo-platform/ros/roslisp/s-xml/test/simple.xml | <?xml version="1.0"?>
<!-- This is a very simple XML document -->
<root id="123">
<text>Hello World!</text>
</root>
| 0 |
apollo_public_repos/apollo-platform/ros/roslisp/s-xml | apollo_public_repos/apollo-platform/ros/roslisp/s-xml/test/test-xml.lisp | ;;;; -*- mode: lisp -*-
;;;;
;;;; $Id: test-xml.lisp,v 1.3 2005/11/06 12:44:48 scaekenberghe Exp $
;;;;
;;;; Unit and functional tests for xml.lisp
;;;;
;;;; Copyright (C) 2002, 2004 Sven Van Caekenberghe, Beta Nine BVBA.
;;;;
;;;; You are granted the rights to distribute and use this software
;;;; as governed by the terms of the Lisp Lesser General Public License
;;;; (http://opensource.franz.com/preamble.html), also known as the LLGPL.
(in-package :s-xml)
(assert
(whitespace-char-p (character " ")))
(assert
(whitespace-char-p (character " ")))
(assert
(whitespace-char-p (code-char 10)))
(assert
(whitespace-char-p (code-char 13)))
(assert
(not (whitespace-char-p #\A)))
(assert
(char= (with-input-from-string (stream " ABC")
(skip-whitespace stream))
#\A))
(assert
(char= (with-input-from-string (stream "ABC")
(skip-whitespace stream))
#\A))
(assert
(string-equal (with-output-to-string (stream) (print-string-xml "<foo>" stream))
"<foo>"))
(assert
(string-equal (with-output-to-string (stream) (print-string-xml "' '" stream))
"' '"))
(assert
(let ((string (map 'string #'identity '(#\return #\tab #\newline))))
(string-equal (with-output-to-string (stream) (print-string-xml string stream))
string)))
(defun simple-echo-xml (in out)
(start-parse-xml
in
(make-instance 'xml-parser-state
:new-element-hook #'(lambda (name attributes seed)
(declare (ignore seed))
(format out "<~a~:{ ~a='~a'~}>"
name
(mapcar #'(lambda (p) (list (car p) (cdr p)))
(reverse attributes))))
:finish-element-hook #'(lambda (name attributes parent-seed seed)
(declare (ignore attributes parent-seed seed))
(format out "</~a>" name))
:text-hook #'(lambda (string seed)
(declare (ignore seed))
(princ string out)))))
(defun simple-echo-xml-string (string)
(with-input-from-string (in string)
(with-output-to-string (out)
(simple-echo-xml in out))))
(assert
(let ((xml "<FOO ATT1='1' ATT2='2'><B>Text</B><EMPTY></EMPTY>More text!<SUB><SUB></SUB></SUB></FOO>"))
(equal (simple-echo-xml-string xml)
xml)))
(assert
(let ((xml "<p> </p>"))
(equal (simple-echo-xml-string xml)
xml)))
;;;; eof | 0 |
apollo_public_repos/apollo-platform/ros/roslisp/s-xml | apollo_public_repos/apollo-platform/ros/roslisp/s-xml/test/echo.lisp | ;;;; -*- mode: lisp -*-
;;;;
;;;; $Id: echo.lisp,v 1.1 2005/08/17 13:44:30 scaekenberghe Exp $
;;;;
;;;; A simple example as well as a useful tool: parse, echo and pretty print XML
;;;;
;;;; Copyright (C) 2002, 2004 Sven Van Caekenberghe, Beta Nine BVBA.
;;;;
;;;; You are granted the rights to distribute and use this software
;;;; as governed by the terms of the Lisp Lesser General Public License
;;;; (http://opensource.franz.com/preamble.html), also known as the LLGPL.
(in-package :s-xml)
(defun indent (stream count)
(loop :repeat (* count 2) :do (write-char #\space stream)))
(defclass echo-xml-seed ()
((stream :initarg :stream)
(level :initarg :level :initform 0)))
#+NIL
(defmethod print-object ((seed echo-xml-seed) stream)
(with-slots (stream level) seed
(print-unreadable-object (seed stream :type t)
(format stream "level=~d" level))))
(defun echo-xml-new-element-hook (name attributes seed)
(with-slots (stream level) seed
(indent stream level)
(format stream "<~a" name)
(dolist (attribute (reverse attributes))
(format stream " ~a=\'" (car attribute))
(print-string-xml (cdr attribute) stream)
(write-char #\' stream))
(format stream ">~%")
(incf level)
seed))
(defun echo-xml-finish-element-hook (name attributes parent-seed seed)
(declare (ignore attributes parent-seed))
(with-slots (stream level) seed
(decf level)
(indent stream level)
(format stream "</~a>~%" name)
seed))
(defun echo-xml-text-hook (string seed)
(with-slots (stream level) seed
(indent stream level)
(print-string-xml string stream)
(terpri stream)
seed))
(defun echo-xml (in out)
"Parse a toplevel XML element from stream in, echoing and pretty printing the result to stream out"
(start-parse-xml in
(make-instance 'xml-parser-state
:seed (make-instance 'echo-xml-seed :stream out)
:new-element-hook #'echo-xml-new-element-hook
:finish-element-hook #'echo-xml-finish-element-hook
:text-hook #'echo-xml-text-hook)))
;;;; eof
| 0 |
apollo_public_repos/apollo-platform/ros/roslisp/s-xml | apollo_public_repos/apollo-platform/ros/roslisp/s-xml/test/counter.lisp | ;;;; -*- mode: lisp -*-
;;;;
;;;; $Id: counter.lisp,v 1.2 2004/06/11 11:14:43 scaekenberghe Exp $
;;;;
;;;; A simple SSAX counter example that can be used as a performance test
;;;;
;;;; Copyright (C) 2004 Sven Van Caekenberghe, Beta Nine BVBA.
;;;;
;;;; You are granted the rights to distribute and use this software
;;;; as governed by the terms of the Lisp Lesser General Public License
;;;; (http://opensource.franz.com/preamble.html), also known as the LLGPL.
(in-package :s-xml)
(defclass count-xml-seed ()
((elements :initform 0)
(attributes :initform 0)
(characters :initform 0)))
(defun count-xml-new-element-hook (name attributes seed)
(declare (ignore name))
(incf (slot-value seed 'elements))
(incf (slot-value seed 'attributes) (length attributes))
seed)
(defun count-xml-text-hook (string seed)
(incf (slot-value seed 'characters) (length string))
seed)
(defun count-xml (in)
"Parse a toplevel XML element from stream in, counting elements, attributes and characters"
(start-parse-xml in
(make-instance 'xml-parser-state
:seed (make-instance 'count-xml-seed)
:new-element-hook #'count-xml-new-element-hook
:text-hook #'count-xml-text-hook)))
(defun count-xml-file (pathname)
"Parse XMl from the file at pathname, counting elements, attributes and characters"
(with-open-file (in pathname)
(let ((result (count-xml in)))
(with-slots (elements attributes characters) result
(format t
"~a contains ~d XML elements, ~d attributes and ~d characters.~%"
pathname elements attributes characters)))))
;;;; eof
| 0 |
apollo_public_repos/apollo-platform/ros/roslisp/s-xml | apollo_public_repos/apollo-platform/ros/roslisp/s-xml/test/all-tests.lisp | ;;;; -*- mode: lisp -*-
;;;;
;;;; $Id: all-tests.lisp,v 1.1.1.1 2004/06/07 18:49:58 scaekenberghe Exp $
;;;;
;;;; Load and execute all unit and functional tests
;;;;
;;;; Copyright (C) 2002, 2004 Sven Van Caekenberghe, Beta Nine BVBA.
;;;;
;;;; You are granted the rights to distribute and use this software
;;;; as governed by the terms of the Lisp Lesser General Public License
;;;; (http://opensource.franz.com/preamble.html), also known as the LLGPL.
(load (merge-pathnames "test-xml" *load-pathname*) :verbose t)
(load (merge-pathnames "test-xml-struct-dom" *load-pathname*) :verbose t)
(load (merge-pathnames "test-lxml-dom" *load-pathname*) :verbose t)
(load (merge-pathnames "test-sxml-dom" *load-pathname*) :verbose t)
;;;; eof | 0 |
apollo_public_repos/apollo-platform/ros/roslisp/s-xml | apollo_public_repos/apollo-platform/ros/roslisp/s-xml/doc/index.html | <?xml version="1.0"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>S-XML</title>
<link rel="stylesheet" type="text/css" href="style.css"/>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"/>
</head>
<body>
<div class="header">
<h1>S-XML</h1>
</div>
<p>
S-XML is a simple XML parser implemented in Common Lisp.
Originally it was written by <a href="http://homepage.mac.com/svc">Sven Van Caekenberghe</a>.
It is now being maintained by <a href="http://homepage.mac.com/svc">Sven Van Caekenberghe</a>,
<a href="http://constantly.at">Rudi Schlatte</a> and <a href="http://www.cs.indiana.edu/~bmastenb">Brian Mastenbrook</a>.
S-XML is used by <a href="http://common-lisp.net/project/s-xml-rpc">S-XML-RPC</a> and
<a href="http://common-lisp.net/project/cl-prevalence">CL-PREVALENCE</a>.
</p>
<p>
This XML parser implementation has the following features:
</p>
<ul>
<li>It works (handling many common XML usages).</li>
<li>It is very small (the core is about 400 lines of code, including comments and whitespace).</li>
<li>It has a core API that is simple, efficient and pure functional, much like that from <a href="http://pobox.com/~oleg/ftp/Scheme/xml.html">SSAX</a> (see also <a href="http://ssax.sourceforge.net">http://ssax.sourceforge.net</a>).</li>
<li>It supports different DOM models: an <a href="http://pobox.com/~oleg/ftp/Scheme/SXML.html">XSML</a>-based one, an <a href="http://opensource.franz.com/xmlutils/xmlutils-dist/pxml.htm">LXML</a>-based one and a classic xml-element struct based one.</li>
<li>It is reasonably time and space efficient (internally avoiding garbage generatation as much as possible).</li>
</ul>
<p>
This XML parser implementation has the following limitations:
</p>
<ul>
<li>It does not support CDATA.</li>
<li>Only supports simple character sets.</li>
<li>It does not support name spaces</li>
<li>It does not support any special tags (like processing instructions).</li>
<li>It is not validating, even skips DTD's all together.</li>
</ul>
<h3>Download</h3>
<p>
You can download the LLGPL source code and documentation as <a href="s-xml.tgz">s-xml.tgz</a>
(signature: <a href="s-xml.tgz.asc">s-xml.tgz.asc</a> for which the public key can be found
in the <a href="http://common-lisp.net/keyring.asc">common-lisp.net keyring</a>)
(build and/or install with ASDF).
</p>
<p>
You can view the <a href="http://common-lisp.net/cgi-bin/viewcvs.cgi/?cvsroot=s-xml">CVS Repository</a> or
get anonymous CVS access as follows:
<pre>$ cvs -d:pserver:[email protected]:/project/s-xml/cvsroot login
(Logging in to [email protected])
CVS password: anonymous
$ cvs -d:pserver:[email protected]:/project/s-xml/cvsroot co s-xml</pre>
</p>
<h3>API</h3>
<p>
The plain API exported by the package S-XML (automatically generated by LispDoc)
is available in <a href="S-XML.html">S-XML.html</a>.
</p>
<h3>XML Parser</h3>
<p>
Using a DOM parser is easier, but usually less efficient: see the next sections. To use the event-based API of the parser, you call the function start-parse-xml on a stream, specifying 3 hook functions:
</p>
<ul>
<li><b>new-element-hook</b> <tt>(name attributes seed) => seed</tt><br/>
Called when the parser enters a new element.
The name of the element (tag) and the attributes (an unordered dotted pair list of attribute names as keywords
and attribute values as strings) of the element are passed in,
as well as the seed from the previous element (either the last encountered sibling or the parent).
The hook must return a seed value to be passed to the first child element
or directly to finish-element-hook (when there are no children).</li>
<li><b>finish-element-hook</b> <tt>(name attributes parent-seed seed) => seed</tt><br/>
Called when the parser leaves an element.
The name of the element (tag) and the attributes (an unordered dotted pair list of attribute names as keywords
and attribute values as strings) of the element are passed in,
as well as the parent-seed, the seed passed to us when this element started,
i.e. passed to our corresponding new-element-hook,
as well as the seed from the previous element (either the last encountered sibling or the parent).
The hook must return the final seed value for this element
to be passed to the next sibling or to the parent (when there are no more children).</li>
<li><b>text-hook</b> <tt>(string seed) => seed</tt><br/>
Called when the parser finds text as contents.
The string of the text encountered is passed in, as well as the seed from the previous element
(either the last encountered sibling or the parent).
The hook must return the final seed value for this element
to be passed to the next sibling or to the parent (when there are no more children).</li>
</ul>
<p>
As an example, consider the following tracer that shows how the different hooks are called:
</p>
<pre>(defun trace-xml-new-element-hook (name attributes seed)
(let ((new-seed (cons (1+ (car seed)) (1+ (cdr seed)))))
(trace-xml-log (car seed)
"(new-element :name ~s :attributes ~:[()~;~:*~s~] :seed ~s) => ~s"
name attributes seed new-seed)
new-seed))
(defun trace-xml-finish-element-hook (name attributes parent-seed seed)
(let ((new-seed (cons (1- (car seed)) (1+ (cdr seed)))))
(trace-xml-log (car parent-seed)
"(finish-element :name ~s :attributes ~:[()~;~:*~s~] :parent-seed ~s :seed ~s) => ~s"
name attributes parent-seed seed new-seed)
new-seed))
(defun trace-xml-text-hook (string seed)
(let ((new-seed (cons (car seed) (1+ (cdr seed)))))
(trace-xml-log (car seed)
"(text :string ~s :seed ~s) => ~s"
string seed new-seed)
new-seed))
(defun trace-xml (in)
"Parse and trace a toplevel XML element from stream in"
(start-parse-xml in
(make-instance 'xml-parser-state
:seed (cons 0 0)
;; seed car is xml element nesting level
;; seed cdr is ever increasing from element to element
:new-element-hook #'trace-xml-new-element-hook
:finish-element-hook #'trace-xml-finish-element-hook
:text-hook #'trace-xml-text-hook)))</pre>
<p>
This is the output of the tracer on two small XML documents, the seed is a CONS that keeps track of the nesting level in its CAR and of its flow through the hooks with an ever increasing number is its CDR:
</p>
<pre>S-XML 31 > (with-input-from-string (in "<FOO X='10' Y='20'><P>Text</P><BAR/><H1><H2></H2></H1></FOO>") (trace-xml in))
(new-element :name :FOO :attributes ((:Y . "20") (:X . "10")) :seed (0 . 0)) => (1 . 1)
(new-element :name :P :attributes () :seed (1 . 1)) => (2 . 2)
(text :string "Text" :seed (2 . 2)) => (2 . 3)
(finish-element :name :P :attributes () :parent-seed (1 . 1) :seed (2 . 3)) => (1 . 4)
(new-element :name :BAR :attributes () :seed (1 . 4)) => (2 . 5)
(finish-element :name :BAR :attributes () :parent-seed (1 . 4) :seed (2 . 5)) => (1 . 6)
(new-element :name :H1 :attributes () :seed (1 . 6)) => (2 . 7)
(new-element :name :H2 :attributes () :seed (2 . 7)) => (3 . 8)
(finish-element :name :H2 :attributes () :parent-seed (2 . 7) :seed (3 . 8)) => (2 . 9)
(finish-element :name :H1 :attributes () :parent-seed (1 . 6) :seed (2 . 9)) => (1 . 10)
(finish-element :name :FOO :attributes ((:Y . "20") (:X . "10")) :parent-seed (0 . 0) :seed (1 . 10)) => (0 . 11)
(0 . 11)
S-XML 32 > (with-input-from-string (in "<FOO><UL><LI>1</LI><LI>2</LI><LI>3</LI></UL></FOO>") (trace-xml in))
(new-element :name :FOO :attributes () :seed (0 . 0)) => (1 . 1)
(new-element :name :UL :attributes () :seed (1 . 1)) => (2 . 2)
(new-element :name :LI :attributes () :seed (2 . 2)) => (3 . 3)
(text :string "1" :seed (3 . 3)) => (3 . 4)
(finish-element :name :LI :attributes () :parent-seed (2 . 2) :seed (3 . 4)) => (2 . 5)
(new-element :name :LI :attributes () :seed (2 . 5)) => (3 . 6)
(text :string "2" :seed (3 . 6)) => (3 . 7)
(finish-element :name :LI :attributes () :parent-seed (2 . 5) :seed (3 . 7)) => (2 . 8)
(new-element :name :LI :attributes () :seed (2 . 8)) => (3 . 9)
(text :string "3" :seed (3 . 9)) => (3 . 10)
(finish-element :name :LI :attributes () :parent-seed (2 . 8) :seed (3 . 10)) => (2 . 11)
(finish-element :name :UL :attributes () :parent-seed (1 . 1) :seed (2 . 11)) => (1 . 12)
(finish-element :name :FOO :attributes () :parent-seed (0 . 0) :seed (1 . 12)) => (0 . 13)
(0 . 13)</pre>
<p>
The following example counts tags, attributes and characters:
</p>
<pre>(defclass count-xml-seed ()
((elements :initform 0)
(attributes :initform 0)
(characters :initform 0)))
(defun count-xml-new-element-hook (name attributes seed)
(declare (ignore name))
(incf (slot-value seed 'elements))
(incf (slot-value seed 'attributes) (length attributes))
seed)
(defun count-xml-text-hook (string seed)
(incf (slot-value seed 'characters) (length string))
seed)
(defun count-xml (in)
"Parse a toplevel XML element from stream in, counting elements, attributes and characters"
(start-parse-xml in
(make-instance 'xml-parser-state
:seed (make-instance 'count-xml-seed)
:new-element-hook #'count-xml-new-element-hook
:text-hook #'count-xml-text-hook)))
(defun count-xml-file (pathname)
"Parse XMl from the file at pathname, counting elements, attributes and characters"
(with-open-file (in pathname)
(let ((result (count-xml in)))
(with-slots (elements attributes characters) result
(format t
"~a contains ~d XML elements, ~d attributes and ~d characters.~%"
pathname elements attributes characters)))))</pre>
<p>
This example removes XML markup:
</p>
<pre>(defun remove-xml-markup (in)
(let* ((state (make-instance 'xml-parser-state
:text-hook #'(lambda (string seed) (cons string seed))))
(result (start-parse-xml in state)))
(apply #'concatenate 'string (nreverse result))))</pre>
<p>
The next example is from the xml-element struct DOM implementation, where the SSAX parser hook functions are building the actual DOM:
</p>
<pre>(defun standard-new-element-hook (name attributes seed)
(declare (ignore name attributes seed))
'())
(defun standard-finish-element-hook (name attributes parent-seed seed)
(let ((xml-element (make-xml-element :name name
:attributes attributes
:children (nreverse seed))))
(cons xml-element parent-seed)))
(defun standard-text-hook (string seed)
(cons string seed))
(defmethod parse-xml-dom (stream (output-type (eql :xml-struct)))
(car (start-parse-xml stream
(make-instance 'xml-parser-state
:new-element-hook #'standard-new-element-hook
:finish-element-hook #'standard-finish-element-hook
:text-hook #'standard-text-hook))))
</pre>
<p>
The parse state can be used to specify the initial seed value (nil by default), and the set of known entities (the 5 standard entities (lt, gt, amp, qout, apos) and nbps by default).
</p>
<h3>DOM</h3>
<p>
Using a DOM parser is easier, but usually less efficient. Currently three different DOM's are supported:
</p>
<ul>
<li>The DOM type <tt>:sxml</tt> is an <a href="http://pobox.com/~oleg/ftp/Scheme/SXML.html">XSML</a>-based one</li>
<li>The DOM type <tt>:lxml</tt> is an <a href="http://opensource.franz.com/xmlutils/xmlutils-dist/pxml.htm">LXML</a>-based one</li>
<li>The DOM type <tt>:xml-struct</tt> is a classic xml-element struct based one</li>
</ul>
<p>
There is a generic API that is identical for each type of DOM, with an extra parameter <tt>input-type</tt> or <tt>output-type</tt> used to specify the type of DOM. The default DOM type is <tt>:lxml</tt>. Here are some examples:
</p>
<pre>? (in-package :s-xml)
#<Package "S-XML">
? (setf xml-string "<foo id='top'><bar>text</bar></foo>")
"<foo id='top'><bar>text</bar></foo>"
? (parse-xml-string xml-string)
((:|foo| :|id| "top") (:|bar| "text"))
? (parse-xml-string xml-string :output-type :sxml)
(:|foo| (:@ (:|id| "top")) (:|bar| "text"))
? (parse-xml-string xml-string :output-type :xml-struct)
#S(XML-ELEMENT :NAME :|foo| :ATTRIBUTES ((:|id| . "top"))
:CHILDREN (#S(XML-ELEMENT :NAME :|bar|
:ATTRIBUTES NIL
:CHILDREN ("text"))))
? (print-xml * :pretty t :input-type :xml-struct)
<foo id="top">
<bar>text</bar>
</foo>
NIL
? (print-xml '(p "Interesting stuff at " ((a href "http://slashdot.org") "SlashDot")))
<P>Interesting stuff at <A HREF="http://slashdot.org">SlashDot</A></P>
NIL</pre>
<p>
Tag and attribute names are converted to keywords. Note that XML is case-sensitive, hence the fact that Common Lisp has to resort to the special literal symbol syntax.
</p>
<h3>Release History and ChangeLog</h3>
<pre>
2005-02-03 Sven Van Caekenberghe <[email protected]>
* release 5 (cvs tag RELEASE_5)
* added :start and :end keywords to print-string-xml
* fixed a bug: in a tag containing whitespace, like <foo> </foo> the parser collapsed
and ingnored all whitespace and considered the tag to be empty!
this is now fixed and a unit test has been added
* cleaned up xml character escaping a bit: single quotes and all normal whitespace
(newline, return and tab) is preserved a unit test for this has been added
* IE doesn't understand the ' XML entity, so I've commented that out for now.
Also, using actual newlines for newlines is probably better than using #xA,
which won't get any end of line conversion by the server or user agent.
June 2004 Sven Van Caekenberghe <[email protected]>
* release 4
* project moved to common-lisp.net, renamed to s-xml,
* added examples counter, tracer and remove-markup, improved documentation
13 Jan 2004 Sven Van Caekenberghe <[email protected]>
* release 3
* added ASDF systems
* optimized print-string-xml
10 Jun 2003 Sven Van Caekenberghe <[email protected]>
* release 2
* added echo-xml function: we are no longer taking the car when
the last seed is returned from start-parse-xml
25 May 2003 Sven Van Caekenberghe <[email protected]>
* release 1
* first public release of working code
* tested on OpenMCL
* rewritten to be event-based, to improve efficiency and
to optionally use different DOM representations
* more documentation
end of 2002 Sven Van Caekenberghe <[email protected]>
* release 0
* as part of an XML-RPC implementation
</pre>
<h3>Todo</h3>
<ul>
<li>Some should find some time to add CDATA support (both in the parser and as a print function) - this shouldn't be too hard, and it would be really useful!</li>
</ul>
<h3>Mailing Lists</h3>
<ul>
<li><a href="http://common-lisp.net/mailman/listinfo/s-xml-cvs">S-XML-CVS mailing list info</a></li>
<li><a href="http://common-lisp.net/mailman/listinfo/s-xml-devel">S-XML-DEVEL mailing list info</a></li>
<li><a href="http://common-lisp.net/mailman/listinfo/s-xml-announce">S-XML-ANNOUNCE mailing list info</a></li>
</ul>
<p>CVS version $Id: index.html,v 1.10 2005/02/03 08:36:05 scaekenberghe Exp $</p>
<div class="footer">
<p>Back to <a href="http://common-lisp.net/">Common-lisp.net</a>.</p>
</div>
<div class="check">
<a href="http://validator.w3.org/check/referer">Valid XHTML 1.0 Strict</a>
<a href="http://jigsaw.w3.org/css-validator/check/referer">Valid CSS</a>
</div>
</body>
</html>
| 0 |
apollo_public_repos/apollo-platform/ros/roslisp/s-xml | apollo_public_repos/apollo-platform/ros/roslisp/s-xml/doc/style.css |
.header {
font-size: medium;
background-color:#336699;
color:#ffffff;
border-style:solid;
border-width: 5px;
border-color:#002244;
padding: 1mm 1mm 1mm 5mm;
}
.footer {
font-size: small;
font-style: italic;
text-align: right;
background-color:#336699;
color:#ffffff;
border-style:solid;
border-width: 2px;
border-color:#002244;
padding: 1mm 1mm 1mm 1mm;
}
.footer a:link {
font-weight:bold;
color:#ffffff;
text-decoration:underline;
}
.footer a:visited {
font-weight:bold;
color:#ffffff;
text-decoration:underline;
}
.footer a:hover {
font-weight:bold;
color:#002244;
text-decoration:underline; }
.check {font-size: x-small;
text-align:right;}
.check a:link { font-weight:bold;
color:#a0a0ff;
text-decoration:underline; }
.check a:visited { font-weight:bold;
color:#a0a0ff;
text-decoration:underline; }
.check a:hover { font-weight:bold;
color:#000000;
text-decoration:underline; }
| 0 |
apollo_public_repos/apollo-platform/ros/roslisp/s-xml | apollo_public_repos/apollo-platform/ros/roslisp/s-xml/doc/S-XML.html | <html><head><title>S-XML</title></head><body><h3>API for package S-XML</h3>
<blockquote>A simple XML parser with an efficient, purely functional, event-based interface as well as a DOM interface</blockquote>
<p>(<b>echo-xml</b> in out) <i>function</i></p>
<blockquote>Parse a toplevel XML element from stream in, echoing and pretty printing the result to stream out</blockquote>
<p>(<b>first-xml-element-child</b> xml-element) <i>function</i></p>
<blockquote>Get the first child of an xml-element</blockquote>
<p>(<b>get-entities</b> xml-parser-state) <i>generic-function</i></p>
<blockquote>Get the entities hashtable of an XML parser state</blockquote>
<p>(setf (<b>get-entities</b> xml-parser-state) value) <i>generic-function</i></p>
<blockquote>Set the entities hashtable of an XML parser state</blockquote>
<p>(<b>get-finish-element-hook</b> xml-parser-state) <i>generic-function</i></p>
<blockquote>Get the finish element hook of an XML parser state</blockquote>
<p>(setf (<b>get-finish-element-hook</b> xml-parser-state) value) <i>generic-function</i></p>
<blockquote>Set the finish element hook of an XML parser state</blockquote>
<p>(<b>get-new-element-hook</b> xml-parser-state) <i>generic-function</i></p>
<blockquote>Get the new element hook of an XML parser state</blockquote>
<p>(setf (<b>get-new-element-hook</b> xml-parser-state) value) <i>generic-function</i></p>
<blockquote>Set the new element hook of an XML parser state</blockquote>
<p>(<b>get-seed</b> xml-parser-state) <i>generic-function</i></p>
<blockquote>Get the initial user seed of an XML parser state</blockquote>
<p>(setf (<b>get-seed</b> xml-parser-state) value) <i>generic-function</i></p>
<blockquote>Set the initial user seed of an XML parser state</blockquote>
<p>(<b>get-text-hook</b> xml-parser-state) <i>generic-function</i></p>
<blockquote>Get the text hook of an XML parser state</blockquote>
<p>(setf (<b>get-text-hook</b> xml-parser-state) value) <i>generic-function</i></p>
<blockquote>Set the text hook of an XML parser state</blockquote>
<p>(<b>make-xml-element</b> &key name attributes children) <i>function</i></p>
<blockquote>Make and return a new xml-element struct</blockquote>
<p>(<b>new-xml-element</b> name &rest children) <i>function</i></p>
<blockquote>Make a new xml-element with name and children</blockquote>
<p>(<b>parse-xml</b> stream &key (output-type :lxml)) <i>function</i></p>
<blockquote>Parse a character stream as XML and generate a DOM of output-type, defaulting to :lxml</blockquote>
<p>(<b>parse-xml-dom</b> stream output-type) <i>generic-function</i></p>
<blockquote>Parse a character stream as XML and generate a DOM of output-type</blockquote>
<p>(<b>parse-xml-file</b> filename &key (output-type :lxml)) <i>function</i></p>
<blockquote>Parse a character file as XML and generate a DOM of output-type, defaulting to :lxml</blockquote>
<p>(<b>parse-xml-string</b> string &key (output-type :lxml)) <i>function</i></p>
<blockquote>Parse a string as XML and generate a DOM of output-type, defaulting to :lxml</blockquote>
<p>(<b>print-string-xml</b> string stream) <i>function</i></p>
<blockquote>Write the characters of string to stream using basic XML conventions</blockquote>
<p>(<b>print-xml</b> dom &key (stream t) pretty (input-type :lxml) (header)) <i>function</i></p>
<blockquote>Generate XML output on a character stream (t by default) from a DOM of input-type (:lxml by default), optionally pretty printing (off by default), or adding a header (none by default)</blockquote>
<p>(<b>print-xml-dom</b> dom input-type stream pretty level) <i>generic-function</i></p>
<blockquote>Generate XML output on a character stream from a DOM of input-type, optionally pretty printing using level</blockquote>
<p>(<b>print-xml-string</b> dom &key pretty (input-type :lxml)) <i>function</i></p>
<blockquote>Generate XML output to a string from a DOM of input-type (:lxml by default), optionally pretty printing (off by default)</blockquote>
<p>(<b>start-parse-xml</b> stream &optional (state (make-instance (quote xml-parser-state)))) <i>function</i></p>
<blockquote>Parse and return a toplevel XML element from stream, using parser state</blockquote>
<p>(<b>xml-element-attribute</b> xml-element key) <i>function</i></p>
<blockquote>Return the string value of the attribute with name the keyword :key
of xml-element if any, return null if not found</blockquote>
<p>(setf (<b>xml-element-attribute</b> xml-element key) value) <i>function</i></p>
<blockquote>Set the string value of the attribute with name the keyword :key of
xml-element, creating a new attribute if necessary or overwriting an
existing one, returning the value</blockquote>
<p>(<b>xml-element-attributes</b> object) <i>function</i></p>
<blockquote>Return the alist of attribute names and values dotted pairs from an xml-element struct</blockquote>
<p>(<b>xml-element-children</b> object) <i>function</i></p>
<blockquote>Return the list of children from an xml-element struct</blockquote>
<p>(<b>xml-element-name</b> object) <i>function</i></p>
<blockquote>Return the name from an xml-element struct</blockquote>
<p>(<b>xml-element-p</b> object) <i>function</i></p>
<blockquote>Return T when the argument is an xml-element struct</blockquote>
<p><b>xml-parser-error</b> <i>condition</i></p>
<blockquote>Thrown by the XML parser to indicate errorneous input</blockquote>
<blockquote>Class precedence list: <tt> xml-parser-error error serious-condition condition standard-object t</tt></blockquote>
<blockquote>Class init args: <tt> :stream :args :message</tt></blockquote>
<p>(<b>xml-parser-error-args</b> xml-parser-error) <i>generic-function</i></p>
<blockquote>Get the error arguments from an XML parser error</blockquote>
<p>(<b>xml-parser-error-message</b> xml-parser-error) <i>generic-function</i></p>
<blockquote>Get the message from an XML parser error</blockquote>
<p>(<b>xml-parser-error-stream</b> xml-parser-error) <i>generic-function</i></p>
<blockquote>Get the stream from an XML parser error</blockquote>
<p><b>xml-parser-state</b> <i>class</i></p>
<blockquote>The XML parser state passed along all code making up the parser</blockquote>
<blockquote>Class precedence list: <tt> xml-parser-state standard-object t</tt></blockquote>
<blockquote>Class init args: <tt> :text-hook :finish-element-hook :new-element-hook :seed :entities</tt></blockquote>
<font size=-1><p>Documentation generated by <a href="http://homepage.mac.com/svc/lispdoc/">lispdoc</a> running on LispWorks</p></font></body></html>
| 0 |
apollo_public_repos/apollo-platform/ros/roslisp/s-xml | apollo_public_repos/apollo-platform/ros/roslisp/s-xml/src/package.lisp | ;;;; -*- mode: lisp -*-
;;;;
;;;; $Id: package.lisp,v 1.6 2005/11/20 14:24:34 scaekenberghe Exp $
;;;;
;;;; This is a Common Lisp implementation of a very basic XML parser.
;;;; The parser is non-validating.
;;;; The API into the parser is pure functional parser hook model that comes from SSAX,
;;;; see also http://pobox.com/~oleg/ftp/Scheme/xml.html or http://ssax.sourceforge.net
;;;; Different DOM models are provided, an XSML, an LXML and a xml-element struct based one.
;;;;
;;;; Copyright (C) 2002, 2003, 2004, 2005 Sven Van Caekenberghe, Beta Nine BVBA.
;;;;
;;;; You are granted the rights to distribute and use this software
;;;; as governed by the terms of the Lisp Lesser General Public License
;;;; (http://opensource.franz.com/preamble.html), also known as the LLGPL.
(defpackage s-xml
(:use common-lisp)
(:export
;; main parser interface
#:start-parse-xml
#:print-string-xml
#:xml-parser-error #:xml-parser-error-message #:xml-parser-error-args #:xml-parser-error-stream
#:xml-parser-state #:get-entities #:get-seed
#:get-new-element-hook #:get-finish-element-hook #:get-text-hook
;; dom parser and printer
#:parse-xml-dom #:parse-xml #:parse-xml-string #:parse-xml-file
#:print-xml-dom #:print-xml #:print-xml-string
;; xml-element structure
#:make-xml-element #:xml-element-children #:xml-element-name
#:xml-element-attribute #:xml-element-attributes
#:xml-element-p #:new-xml-element #:first-xml-element-child
;; namespaces
#:*ignore-namespaces* #:*local-namespace* #:*namespaces*
#:*require-existing-symbols* #:*auto-export-symbols* #:*auto-create-namespace-packages*
#:find-namespace #:register-namespace #:get-prefix #:get-uri #:get-package
#:resolve-identifier #:extend-namespaces #:print-identifier #:split-identifier)
(:documentation
"A simple XML parser with an efficient, purely functional, event-based interface as well as a DOM interface"))
;;;; eof
| 0 |
apollo_public_repos/apollo-platform/ros/roslisp/s-xml | apollo_public_repos/apollo-platform/ros/roslisp/s-xml/src/xml-struct-dom.lisp | ;;;; -*- mode: lisp -*-
;;;;
;;;; $Id: xml-struct-dom.lisp,v 1.3 2005/09/20 09:57:48 scaekenberghe Exp $
;;;;
;;;; XML-STRUCT implementation of the generic DOM parser and printer.
;;;;
;;;; Copyright (C) 2002, 2004 Sven Van Caekenberghe, Beta Nine BVBA.
;;;;
;;;; You are granted the rights to distribute and use this software
;;;; as governed by the terms of the Lisp Lesser General Public License
;;;; (http://opensource.franz.com/preamble.html), also known as the LLGPL.
(in-package :s-xml)
;;; xml-element struct datastructure and API
(defstruct xml-element
name ; :tag-name
attributes ; a assoc list of (:attribute-name . "attribute-value")
children ; a list of children/content either text strings or xml-elements
)
(setf (documentation 'xml-element-p 'function)
"Return T when the argument is an xml-element struct"
(documentation 'xml-element-attributes 'function)
"Return the alist of attribute names and values dotted pairs from an xml-element struct"
(documentation 'xml-element-children 'function)
"Return the list of children from an xml-element struct"
(documentation 'xml-element-name 'function)
"Return the name from an xml-element struct"
(documentation 'make-xml-element 'function)
"Make and return a new xml-element struct")
(defun xml-element-attribute (xml-element key)
"Return the string value of the attribute with name the keyword :key
of xml-element if any, return null if not found"
(let ((pair (assoc key (xml-element-attributes xml-element) :test #'eq)))
(when pair (cdr pair))))
(defun (setf xml-element-attribute) (value xml-element key)
"Set the string value of the attribute with name the keyword :key of
xml-element, creating a new attribute if necessary or overwriting an
existing one, returning the value"
(let ((attributes (xml-element-attributes xml-element)))
(if (null attributes)
(push (cons key value) (xml-element-attributes xml-element))
(let ((pair (assoc key attributes :test #'eq)))
(if pair
(setf (cdr pair) value)
(push (cons key value) (xml-element-attributes xml-element)))))
value))
(defun new-xml-element (name &rest children)
"Make a new xml-element with name and children"
(make-xml-element :name name :children children))
(defun first-xml-element-child (xml-element)
"Get the first child of an xml-element"
(first (xml-element-children xml-element)))
(defun xml-equal (xml-1 xml-2)
(and (xml-element-p xml-1)
(xml-element-p xml-2)
(eq (xml-element-name xml-1)
(xml-element-name xml-2))
(equal (xml-element-attributes xml-1)
(xml-element-attributes xml-2))
(reduce #'(lambda (&optional (x t) (y t)) (and x y))
(mapcar #'(lambda (x y)
(or (and (stringp x) (stringp y) (string= x y))
(xml-equal x y)))
(xml-element-children xml-1)
(xml-element-children xml-2)))))
;;; printing xml structures
(defmethod print-xml-dom (xml-element (input-type (eql :xml-struct)) stream pretty level)
(declare (special *namespaces*))
(let ((*namespaces* (extend-namespaces (xml-element-attributes xml-element)
*namespaces*)))
(write-char #\< stream)
(print-identifier (xml-element-name xml-element) stream)
(loop :for (name . value) :in (xml-element-attributes xml-element)
:do (print-attribute name value stream))
(let ((children (xml-element-children xml-element)))
(if children
(progn
(write-char #\> stream)
(if (and (= (length children) 1) (stringp (first children)))
(print-string-xml (first children) stream)
(progn
(dolist (child children)
(when pretty (print-spaces (* 2 level) stream))
(if (stringp child)
(print-string-xml child stream)
(print-xml-dom child input-type stream pretty (1+ level))))
(when pretty (print-spaces (* 2 (1- level)) stream))))
(print-closing-tag (xml-element-name xml-element) stream))
(write-string "/>" stream)))))
;;; the standard hooks to generate xml-element structs
(defun standard-new-element-hook (name attributes seed)
(declare (ignore name attributes seed))
'())
(defun standard-finish-element-hook (name attributes parent-seed seed)
(let ((xml-element (make-xml-element :name name
:attributes attributes
:children (nreverse seed))))
(cons xml-element parent-seed)))
(defun standard-text-hook (string seed)
(cons string seed))
;;; top level standard parser interfaces
(defmethod parse-xml-dom (stream (output-type (eql :xml-struct)))
(car (start-parse-xml stream
(make-instance 'xml-parser-state
:new-element-hook #'standard-new-element-hook
:finish-element-hook #'standard-finish-element-hook
:text-hook #'standard-text-hook))))
;;;; eof
| 0 |
apollo_public_repos/apollo-platform/ros/roslisp/s-xml | apollo_public_repos/apollo-platform/ros/roslisp/s-xml/src/xml.lisp | ;;;; -*- mode: lisp -*-
;;;;
;;;; $Id: xml.lisp,v 1.14 2005/11/20 14:24:34 scaekenberghe Exp $
;;;;
;;;; This is a Common Lisp implementation of a basic but usable XML parser.
;;;; The parser is non-validating and not complete (no CDATA).
;;;; Namespace and entities are handled.
;;;; The API into the parser is a pure functional parser hook model that comes from SSAX,
;;;; see also http://pobox.com/~oleg/ftp/Scheme/xml.html or http://ssax.sourceforge.net
;;;; Different DOM models are provided, an XSML, an LXML and a xml-element struct based one.
;;;;
;;;; Copyright (C) 2002, 2003, 2004, 2005 Sven Van Caekenberghe, Beta Nine BVBA.
;;;;
;;;; You are granted the rights to distribute and use this software
;;;; as governed by the terms of the Lisp Lesser General Public License
;;;; (http://opensource.franz.com/preamble.html), also known as the LLGPL.
(in-package :s-xml)
;;; error reporting
(define-condition xml-parser-error (error)
((message :initarg :message :reader xml-parser-error-message)
(args :initarg :args :reader xml-parser-error-args)
(stream :initarg :stream :reader xml-parser-error-stream :initform nil))
(:report (lambda (condition stream)
(format stream
"XML parser ~?~@[ near stream position ~d~]."
(xml-parser-error-message condition)
(xml-parser-error-args condition)
(and (xml-parser-error-stream condition)
(file-position (xml-parser-error-stream condition))))))
(:documentation "Thrown by the XML parser to indicate errorneous input"))
(setf (documentation 'xml-parser-error-message 'function)
"Get the message from an XML parser error"
(documentation 'xml-parser-error-args 'function)
"Get the error arguments from an XML parser error"
(documentation 'xml-parser-error-stream 'function)
"Get the stream from an XML parser error")
(defun parser-error (message &optional args stream)
(make-condition 'xml-parser-error
:message message
:args args
:stream stream))
;;; utilities
(defun whitespace-char-p (char)
"Is char an XML whitespace character ?"
(or (char= char #\space)
(char= char #\tab)
(char= char #\return)
(char= char #\linefeed)))
(defun identifier-char-p (char)
"Is char an XML identifier character ?"
(or (and (char<= #\A char) (char<= char #\Z))
(and (char<= #\a char) (char<= char #\z))
(and (char<= #\0 char) (char<= char #\9))
(char= char #\-)
(char= char #\_)
(char= char #\.)
(char= char #\:)))
(defun skip-whitespace (stream)
"Skip over XML whitespace in stream, return first non-whitespace
character which was peeked but not read, return nil on eof"
(loop
(let ((char (peek-char nil stream nil nil)))
(if (and char (whitespace-char-p char))
(read-char stream)
(return char)))))
(defun make-extendable-string (&optional (size 10))
"Make an extendable string which is a one-dimensional character
array which is adjustable and has a fill pointer"
(make-array size
:element-type 'character
:adjustable t
:fill-pointer 0))
(defun print-string-xml (string stream &key (start 0) end)
"Write the characters of string to stream using basic XML conventions"
(loop for offset upfrom start below (or end (length string))
for char = (char string offset)
do (case char
(#\& (write-string "&" stream))
(#\< (write-string "<" stream))
(#\> (write-string ">" stream))
(#\" (write-string """ stream))
((#\newline #\return #\tab) (write-char char stream))
(t (if (and (<= 32 (char-code char))
(<= (char-code char) 126))
(write-char char stream)
(progn
(write-string "&#x" stream)
(write (char-code char) :stream stream :base 16)
(write-char #\; stream)))))))
(defun make-standard-entities ()
"A hashtable mapping XML entity names to their replacement strings,
filled with the standard set"
(let ((entities (make-hash-table :test #'equal)))
(setf (gethash "amp" entities) (string #\&)
(gethash "quot" entities) (string #\")
(gethash "apos" entities) (string #\')
(gethash "lt" entities) (string #\<)
(gethash "gt" entities) (string #\>)
(gethash "nbsp" entities) (string #\space))
entities))
(defun resolve-entity (stream extendable-string entities &optional (entity (make-extendable-string)))
"Read and resolve an XML entity from stream, positioned after the '&' entity marker,
accepting &name; &#DEC; and &#xHEX; formats,
destructively modifying string, which is also returned,
destructively modifying entity, incorrect entity formats result in errors"
(loop
(let ((char (read-char stream nil nil)))
(cond ((null char) (error (parser-error "encountered eof before end of entity")))
((char= #\; char) (return))
(t (vector-push-extend char entity)))))
(if (char= (char entity 0) #\#)
(let ((code (if (char= (char entity 1) #\x)
(parse-integer entity :start 2 :radix 16 :junk-allowed t)
(parse-integer entity :start 1 :radix 10 :junk-allowed t))))
(when (null code)
(error (parser-error "encountered incorrect entity &~s;" (list entity) stream)))
(vector-push-extend (code-char code) extendable-string))
(let ((value (gethash entity entities)))
(if value
(loop :for char :across value
:do (vector-push-extend char extendable-string))
(error (parser-error "encountered unknown entity &~s;" (list entity) stream)))))
extendable-string)
;;; namespace support
(defvar *ignore-namespaces* nil
"When t, namespaces are ignored like in the old version of S-XML")
(defclass xml-namespace ()
((uri :documentation "The URI used to identify this namespace"
:accessor get-uri
:initarg :uri)
(prefix :documentation "The preferred prefix assigned to this namespace"
:accessor get-prefix
:initarg :prefix
:initform nil)
(package :documentation "The Common Lisp package where this namespace's symbols are interned"
:accessor get-package
:initarg :package
:initform nil))
(:documentation "Describes an XML namespace and how it is handled"))
(defmethod print-object ((object xml-namespace) stream)
(print-unreadable-object (object stream :type t :identity t)
(format stream "~A - ~A" (get-prefix object) (get-uri object))))
(defvar *local-namespace* (make-instance 'xml-namespace
:uri "local"
:prefix ""
:package (find-package :keyword))
"The local (global default) XML namespace")
(defvar *xml-namespace* (make-instance 'xml-namespace
:uri "http://www.w3.org/XML/1998/namespace"
:prefix "xml"
:package (or (find-package :xml)
(make-package :xml :nicknames '("XML"))))
"REC-xml-names-19990114 says the prefix xml is bound to the namespace http://www.w3.org/XML/1998/namespace.")
(defvar *known-namespaces* (list *local-namespace* *xml-namespace*)
"The list of known/defined namespaces")
(defvar *namespaces* `(("xml" . ,*xml-namespace*) ("" . ,*local-namespace*))
"Ordered list of (prefix . XML-namespace) bindings currently in effect - special variable")
(defun find-namespace (uri)
"Find a registered XML namespace identified by uri"
(find uri *known-namespaces* :key #'get-uri :test #'string-equal))
(defun register-namespace (uri prefix package)
"Register a new or redefine an existing XML namespace defined by uri with prefix and package"
(let ((namespace (find-namespace uri)))
(if namespace
(setf (get-prefix namespace) prefix
(get-package namespace) (find-package package))
(push (setf namespace (make-instance 'xml-namespace
:uri uri
:prefix prefix
:package (find-package package)))
*known-namespaces*))
namespace))
(defun find-namespace-binding (prefix namespaces)
"Find the XML namespace currently bound to prefix in the namespaces bindings"
(cdr (assoc prefix namespaces :test #'string-equal)))
(defun split-identifier (identifier)
"Split an identifier 'prefix:name' and return (values prefix name)"
(when (symbolp identifier)
(setf identifier (symbol-name identifier)))
(let ((colon-position (position #\: identifier :test #'char=)))
(if colon-position
(values (subseq identifier 0 colon-position)
(subseq identifier (1+ colon-position)))
(values nil identifier))))
(defvar *require-existing-symbols* nil
"If t, each XML identifier must exist as symbol already")
(defvar *auto-export-symbols* t
"If t, export newly interned symbols form their packages")
(defun resolve-identifier (identifier namespaces &optional as-attribute)
"Resolve the string identifier in the list of namespace bindings"
(if *ignore-namespaces*
(intern identifier :keyword)
(flet ((intern-symbol (string package) ; intern string as a symbol in package
(if *require-existing-symbols*
(let ((symbol (find-symbol string package)))
(or symbol
(error "Symbol ~s does not exist in ~s" string package)))
(let ((symbol (intern string package)))
(when (and *auto-export-symbols*
(not (eql package (find-package :keyword))))
(export symbol package))
symbol))))
(multiple-value-bind (prefix name)
(split-identifier identifier)
(if (or (null prefix) (string= prefix "xmlns"))
(if as-attribute
(intern (if (string= prefix "xmlns") identifier name) (get-package *local-namespace*))
(let ((default-namespace (find-namespace-binding "" namespaces)))
(intern-symbol name (get-package default-namespace))))
(let ((namespace (find-namespace-binding prefix namespaces)))
(if namespace
(intern-symbol name (get-package namespace))
(error "namespace not found for prefix ~s" prefix))))))))
(defvar *auto-create-namespace-packages* t
"If t, new packages will be created for namespaces, if needed, named by the prefix")
(defun new-namespace (uri &optional prefix)
"Register a new namespace for uri and prefix, creating a package if necessary"
(if prefix
(register-namespace uri
prefix
(or (find-package prefix)
(if *auto-create-namespace-packages*
(make-package prefix :nicknames `(,(string-upcase prefix)))
(error "Cannot find or create package ~s" prefix))))
(let ((unique-name (loop :for i :upfrom 0
:do (let ((name (format nil "ns-~d" i)))
(when (not (find-package name))
(return name))))))
(register-namespace uri
unique-name
(if *auto-create-namespace-packages*
(make-package (string-upcase unique-name) :nicknames `(,unique-name))
(error "Cannot create package ~s" unique-name))))))
(defun extend-namespaces (attributes namespaces)
"Given possible 'xmlns[:prefix]' attributes, extend the namespaces bindings"
(unless *ignore-namespaces*
(let (default-namespace-uri)
(loop :for (key . value) :in attributes
:do (if (string= key "xmlns")
(setf default-namespace-uri value)
(multiple-value-bind (prefix name)
(split-identifier key)
(when (string= prefix "xmlns")
(let* ((uri value)
(prefix name)
(namespace (find-namespace uri)))
(unless namespace
(setf namespace (new-namespace uri prefix)))
(push `(,prefix . ,namespace) namespaces))))))
(when default-namespace-uri
(let ((namespace (find-namespace default-namespace-uri)))
(unless namespace
(setf namespace (new-namespace default-namespace-uri)))
(push `("" . ,namespace) namespaces)))))
namespaces)
(defun print-identifier (identifier stream &optional as-attribute)
"Print identifier on stream using namespace conventions"
(declare (ignore as-attribute) (special *namespaces*))
(if *ignore-namespaces*
(princ identifier stream)
(if (symbolp identifier)
(let ((package (symbol-package identifier))
(name (symbol-name identifier)))
(let* ((namespace (find package *known-namespaces* :key #'get-package))
(prefix (or (car (find namespace *namespaces* :key #'cdr))
(get-prefix namespace))))
(if (string= prefix "")
(princ name stream)
(format stream "~a:~a" prefix name))))
(princ identifier stream))))
;;; the parser state
(defclass xml-parser-state ()
((entities :documentation "A hashtable mapping XML entity names to their replacement stings"
:accessor get-entities
:initarg :entities
:initform (make-standard-entities))
(seed :documentation "The user seed object"
:accessor get-seed
:initarg :seed
:initform nil)
(buffer :documentation "The main reusable character buffer"
:accessor get-buffer
:initform (make-extendable-string))
(mini-buffer :documentation "The secondary, smaller reusable character buffer"
:accessor get-mini-buffer
:initform (make-extendable-string))
(new-element-hook :documentation "Called when new element starts"
;; Handle the start of a new xml element with name and attributes,
;; receiving seed from previous element (sibling or parent)
;; return seed to be used for first child (content)
;; or directly to finish-element-hook
:accessor get-new-element-hook
:initarg :new-element-hook
:initform #'(lambda (name attributes seed)
(declare (ignore name attributes))
seed))
(finish-element-hook :documentation "Called when element ends"
;; Handle the end of an xml element with name and attributes,
;; receiving parent-seed, the seed passed to us when this element started,
;; i.e. passed to our corresponding new-element-hook
;; and receiving seed from last child (content)
;; or directly from new-element-hook
;; return final seed for this element to next element (sibling or parent)
:accessor get-finish-element-hook
:initarg :finish-element-hook
:initform #'(lambda (name attributes parent-seed seed)
(declare (ignore name attributes parent-seed))
seed))
(text-hook :documentation "Called when text is found"
;; Handle text in string, found as contents,
;; receiving seed from previous element (sibling or parent),
;; return final seed for this element to next element (sibling or parent)
:accessor get-text-hook
:initarg :text-hook
:initform #'(lambda (string seed)
(declare (ignore string))
seed)))
(:documentation "The XML parser state passed along all code making up the parser"))
(setf (documentation 'get-seed 'function)
"Get the initial user seed of an XML parser state"
(documentation 'get-entities 'function)
"Get the entities hashtable of an XML parser state"
(documentation 'get-new-element-hook 'function)
"Get the new element hook of an XML parser state"
(documentation 'get-finish-element-hook 'function)
"Get the finish element hook of an XML parser state"
(documentation 'get-text-hook 'function)
"Get the text hook of an XML parser state")
#-allegro
(setf (documentation '(setf get-seed) 'function)
"Set the initial user seed of an XML parser state"
(documentation '(setf get-entities) 'function)
"Set the entities hashtable of an XML parser state"
(documentation '(setf get-new-element-hook) 'function)
"Set the new element hook of an XML parser state"
(documentation '(setf get-finish-element-hook) 'function)
"Set the finish element hook of an XML parser state"
(documentation '(setf get-text-hook) 'function)
"Set the text hook of an XML parser state")
(defmethod get-mini-buffer :after ((state xml-parser-state))
"Reset and return the reusable mini buffer"
(with-slots (mini-buffer) state
(setf (fill-pointer mini-buffer) 0)))
(defmethod get-buffer :after ((state xml-parser-state))
"Reset and return the main reusable buffer"
(with-slots (buffer) state
(setf (fill-pointer buffer) 0)))
;;; parser support
(defun parse-whitespace (stream extendable-string)
"Read and collect XML whitespace from stream in string which is
destructively modified, return first non-whitespace character which
was peeked but not read, return nil on eof"
(loop
(let ((char (peek-char nil stream nil nil)))
(if (and char (whitespace-char-p char))
(vector-push-extend (read-char stream) extendable-string)
(return char)))))
(defun parse-string (stream state &optional (string (make-extendable-string)))
"Read and return an XML string from stream, delimited by either
single or double quotes, the stream is expected to be on the opening
delimiter, at the end the closing delimiter is also read, entities
are resolved, eof before end of string is an error"
(let ((delimiter (read-char stream nil nil))
(char))
(when (or (null delimiter) (not (or (char= delimiter #\') (char= delimiter #\"))))
(error (parser-error "expected string delimiter" nil stream)))
(loop
(setf char (read-char stream nil nil))
(cond ((null char) (error (parser-error "encountered eof before end of string")))
((char= char delimiter) (return))
((char= char #\&) (resolve-entity stream string (get-entities state) (get-mini-buffer state)))
(t (vector-push-extend char string))))
string))
(defun parse-text (stream state extendable-string)
"Read and collect XML text from stream in string which is
destructively modified, the text ends with a '<', which is peeked and
returned, entities are resolved, eof is considered an error"
(let (char)
(loop
(setf char (peek-char nil stream nil nil))
(when (null char) (error (parser-error "encountered unexpected eof in text")))
(when (char= char #\<) (return))
(read-char stream)
(if (char= char #\&)
(resolve-entity stream extendable-string (get-entities state) (get-mini-buffer state))
(vector-push-extend char extendable-string)))
char))
(defun parse-identifier (stream &optional (identifier (make-extendable-string)))
"Read and returns an XML identifier from stream, positioned at the
start of the identifier, ending with the first non-identifier
character, which is peeked, the identifier is written destructively
into identifier which is also returned"
(loop
(let ((char (peek-char nil stream nil nil)))
(cond ((and char (identifier-char-p char))
(read-char stream)
(vector-push-extend char identifier))
(t
(return identifier))))))
(defun skip-comment (stream)
"Skip an XML comment in stream, positioned after the opening '<!--',
consumes the closing '-->' sequence, unexpected eof or a malformed
closing sequence result in a error"
(let ((dashes-to-read 2))
(loop
(if (zerop dashes-to-read) (return))
(let ((char (read-char stream nil nil)))
(if (null char)
(error (parser-error "encountered unexpected eof for comment")))
(if (char= char #\-)
(decf dashes-to-read)
(setf dashes-to-read 2)))))
(if (char/= (read-char stream nil nil) #\>)
(error (parser-error "expected > ending comment" nil stream))))
(defun read-cdata (stream state &optional (string (make-extendable-string)))
"Reads in the CDATA and calls the callback for CDATA if it exists"
;; we already read the <![CDATA[ stuff
;; continue to read until we hit ]]>
(let ((char #\space)
(last-3-characters (list #\[ #\A #\T))
(pattern (list #\> #\] #\])))
(loop
(setf char (read-char stream nil nil))
(when (null char) (error (parser-error "encountered unexpected eof in text")))
(push char last-3-characters)
(setf (cdddr last-3-characters) nil)
(cond
((equal last-3-characters
pattern)
(setf (fill-pointer string)
(- (fill-pointer string) 2))
(setf (get-seed state)
(funcall (get-text-hook state)
(copy-seq string)
(get-seed state)))
(return-from read-cdata))
(t
(vector-push-extend char string))))))
(defun skip-special-tag (stream state)
"Skip an XML special tag (comments and processing instructions) in
stream, positioned after the opening '<', unexpected eof is an error"
;; opening < has been read, consume ? or !
(read-char stream)
(let ((char (read-char stream nil nil)))
;; see if we are dealing with a comment
(when (char= char #\-)
(setf char (read-char stream nil nil))
(when (char= char #\-)
(skip-comment stream)
(return-from skip-special-tag)))
;; maybe we are dealing with CDATA?
(when (and (char= char #\[)
(loop :for pattern :across "CDATA["
:for char = (read-char stream nil nil)
:when (null char) :do
(error (parser-error "encountered unexpected eof in cdata"))
:always (char= char pattern)))
(read-cdata stream state (get-buffer state))
(return-from skip-special-tag))
;; loop over chars, dealing with strings (skipping their content)
;; and counting opening and closing < and > chars
(let ((taglevel 1)
(string-delimiter))
(loop
(when (zerop taglevel) (return))
(setf char (read-char stream nil nil))
(when (null char)
(error (parser-error "encountered unexpected eof for special (! or ?) tag" nil stream)))
(if string-delimiter
;; inside a string we only look for a closing string delimiter
(when (char= char string-delimiter)
(setf string-delimiter nil))
;; outside a string we count < and > and watch out for strings
(cond ((or (char= char #\') (char= char #\")) (setf string-delimiter char))
((char= char #\<) (incf taglevel))
((char= char #\>) (decf taglevel))))))))
;;; the XML parser proper
(defun parse-xml-element-attributes (stream state)
"Parse XML element attributes from stream positioned after the tag
identifier, returning the attributes as an assoc list, ending at
either a '>' or a '/' which is peeked and also returned"
(declare (special *namespaces*))
(let (char attributes)
(loop
;; skip whitespace separating items
(setf char (skip-whitespace stream))
;; start tag attributes ends with > or />
(when (and char (or (char= char #\>) (char= char #\/))) (return))
;; read the attribute key
(let ((key (copy-seq (parse-identifier stream (get-mini-buffer state)))))
;; skip separating whitespace
(setf char (skip-whitespace stream))
;; require = sign (and consume it if present)
(if (and char (char= char #\=))
(read-char stream)
(error (parser-error "expected =" nil stream)))
;; skip separating whitespace
(skip-whitespace stream)
;; read the attribute value as a string
(push (cons key (copy-seq (parse-string stream state (get-buffer state))))
attributes)))
;; return attributes peek char ending loop
(values attributes char)))
(defun parse-xml-element (stream state)
"Parse and return an XML element from stream, positioned after the opening '<'"
(declare (special *namespaces*))
;; opening < has been read
(when (char= (peek-char nil stream nil nil) #\!)
(skip-special-tag stream state)
(return-from parse-xml-element))
(let (char buffer open-tag parent-seed has-children)
(setf parent-seed (get-seed state))
;; read tag name (no whitespace between < and name ?)
(setf open-tag (copy-seq (parse-identifier stream (get-mini-buffer state))))
;; tag has been read, read attributes if any
(multiple-value-bind (attributes peeked-char)
(parse-xml-element-attributes stream state)
(let ((*namespaces* (extend-namespaces attributes *namespaces*)))
(setf open-tag (resolve-identifier open-tag *namespaces*)
attributes (loop :for (key . value) :in attributes
:collect (cons (resolve-identifier key *namespaces* t) value)))
(setf (get-seed state) (funcall (get-new-element-hook state)
open-tag attributes (get-seed state)))
(setf char peeked-char)
(when (char= char #\/)
;; handle solitary tag of the form <tag .. />
(read-char stream)
(setf char (read-char stream nil nil))
(if (char= #\> char)
(progn
(setf (get-seed state) (funcall (get-finish-element-hook state)
open-tag attributes parent-seed (get-seed state)))
(return-from parse-xml-element))
(error (parser-error "expected >" nil stream))))
;; consume >
(read-char stream)
(loop
(setf buffer (get-buffer state))
;; read whitespace into buffer
(setf char (parse-whitespace stream buffer))
;; see what ended the whitespace scan
(cond ((null char) (error (parser-error "encountered unexpected eof handling ~a" (list open-tag))))
((char= char #\<)
;; consume the <
(read-char stream)
(if (char= (peek-char nil stream nil nil) #\/)
(progn
;; handle the matching closing tag </tag> and done
;; if we read whitespace as this (leaf) element's contents, it is significant
(when (and (not has-children) (plusp (length buffer)))
(setf (get-seed state) (funcall (get-text-hook state)
(copy-seq buffer) (get-seed state))))
(read-char stream)
(let ((close-tag (resolve-identifier (parse-identifier stream (get-mini-buffer state))
*namespaces*)))
(unless (eq open-tag close-tag)
(error (parser-error "found <~a> not matched by </~a> but by <~a>"
(list open-tag open-tag close-tag) stream)))
(unless (char= (read-char stream nil nil) #\>)
(error (parser-error "expected >" nil stream)))
(setf (get-seed state) (funcall (get-finish-element-hook state)
open-tag attributes parent-seed (get-seed state))))
(return))
;; handle child tag and loop, no hooks to call here
;; whitespace between child elements is skipped
(progn
(setf has-children t)
(parse-xml-element stream state))))
(t
;; no child tag, concatenate text to whitespace in buffer
;; handle text content and loop
(setf char (parse-text stream state buffer))
(setf (get-seed state) (funcall (get-text-hook state)
(copy-seq buffer) (get-seed state))))))))))
(defun start-parse-xml (stream &optional (state (make-instance 'xml-parser-state)))
"Parse and return a toplevel XML element from stream, using parser state"
(loop
(let ((char (skip-whitespace stream)))
(when (null char) (return-from start-parse-xml))
;; skip whitespace until start tag
(unless (char= char #\<)
(error (parser-error "expected <" nil stream)))
(read-char stream) ; consume peeked char
(setf char (peek-char nil stream nil nil))
(if (or (char= char #\!) (char= char #\?))
;; deal with special tags
(skip-special-tag stream state)
(progn
;; read the main element
(parse-xml-element stream state)
(return-from start-parse-xml (get-seed state)))))))
;;;; eof
| 0 |
apollo_public_repos/apollo-platform/ros/roslisp/s-xml | apollo_public_repos/apollo-platform/ros/roslisp/s-xml/src/lxml-dom.lisp | ;;;; -*- mode: lisp -*-
;;;;
;;;; $Id: lxml-dom.lisp,v 1.6 2005/11/20 14:34:15 scaekenberghe Exp $
;;;;
;;;; LXML implementation of the generic DOM parser and printer.
;;;;
;;;; Copyright (C) 2002, 2004 Sven Van Caekenberghe, Beta Nine BVBA.
;;;;
;;;; You are granted the rights to distribute and use this software
;;;; as governed by the terms of the Lisp Lesser General Public License
;;;; (http://opensource.franz.com/preamble.html), also known as the LLGPL.
(in-package :s-xml)
;;; the lxml hooks to generate lxml
(defun lxml-new-element-hook (name attributes seed)
(declare (ignore name attributes seed))
'())
(defun lxml-finish-element-hook (name attributes parent-seed seed)
(let ((xml-element
(cond ((and (null seed) (null attributes))
name)
(attributes
`((,name ,@(let (list)
(dolist (attribute attributes list)
(push (cdr attribute) list)
(push (car attribute) list))))
,@(nreverse seed)))
(t
`(,name ,@(nreverse seed))))))
(cons xml-element parent-seed)))
(defun lxml-text-hook (string seed)
(cons string seed))
;;; standard DOM interfaces
(defmethod parse-xml-dom (stream (output-type (eql :lxml)))
(car (start-parse-xml stream
(make-instance 'xml-parser-state
:new-element-hook #'lxml-new-element-hook
:finish-element-hook #'lxml-finish-element-hook
:text-hook #'lxml-text-hook))))
(defun plist->alist (plist)
(when plist
(cons (cons (first plist) (second plist))
(plist->alist (rest (rest plist))))))
(defmethod print-xml-dom (dom (input-type (eql :lxml)) stream pretty level)
(declare (special *namespaces*))
(cond ((symbolp dom) (print-solitary-tag dom stream))
((stringp dom) (print-string-xml dom stream))
((consp dom)
(let (tag attributes)
(cond ((symbolp (first dom)) (setf tag (first dom)))
((consp (first dom)) (setf tag (first (first dom))
attributes (plist->alist (rest (first dom)))))
(t (error "Input not recognized as LXML ~s" dom)))
(let ((*namespaces* (extend-namespaces attributes *namespaces*)))
(write-char #\< stream)
(print-identifier tag stream)
(loop :for (name . value) :in attributes
:do (print-attribute name value stream))
(if (rest dom)
(let ((children (rest dom)))
(write-char #\> stream)
(if (and (= (length children) 1) (stringp (first children)))
(print-string-xml (first children) stream)
(progn
(dolist (child children)
(when pretty (print-spaces (* 2 level) stream))
(if (stringp child)
(print-string-xml child stream)
(print-xml-dom child input-type stream pretty (1+ level))))
(when pretty (print-spaces (* 2 (1- level)) stream))))
(print-closing-tag tag stream))
(write-string "/>" stream)))))
(t (error "Input not recognized as LXML ~s" dom))))
;;;; eof | 0 |
apollo_public_repos/apollo-platform/ros/roslisp/s-xml | apollo_public_repos/apollo-platform/ros/roslisp/s-xml/src/sxml-dom.lisp | ;;;; -*- mode: lisp -*-
;;;;
;;;; $Id: sxml-dom.lisp,v 1.5 2005/11/20 14:34:15 scaekenberghe Exp $
;;;;
;;;; LXML implementation of the generic DOM parser and printer.
;;;;
;;;; Copyright (C) 2003, 2004 Sven Van Caekenberghe, Beta Nine BVBA.
;;;;
;;;; You are granted the rights to distribute and use this software
;;;; as governed by the terms of the Lisp Lesser General Public License
;;;; (http://opensource.franz.com/preamble.html), also known as the LLGPL.
(in-package :s-xml)
;;; the sxml hooks to generate sxml
(defun sxml-new-element-hook (name attributes seed)
(declare (ignore name attributes seed))
'())
(defun sxml-finish-element-hook (name attributes parent-seed seed)
(let ((xml-element (append (list name)
(when attributes
(list (let (list)
(dolist (attribute attributes (cons :@ list))
(push (list (car attribute) (cdr attribute)) list)))))
(nreverse seed))))
(cons xml-element parent-seed)))
(defun sxml-text-hook (string seed)
(cons string seed))
;;; the standard DOM interfaces
(defmethod parse-xml-dom (stream (output-type (eql :sxml)))
(car (start-parse-xml stream
(make-instance 'xml-parser-state
:new-element-hook #'sxml-new-element-hook
:finish-element-hook #'sxml-finish-element-hook
:text-hook #'sxml-text-hook))))
(defmethod print-xml-dom (dom (input-type (eql :sxml)) stream pretty level)
(declare (special *namespaces*))
(cond ((stringp dom) (print-string-xml dom stream))
((consp dom)
(let ((tag (first dom))
attributes
children)
(if (and (consp (second dom)) (eq (first (second dom)) :@))
(setf attributes (rest (second dom))
children (rest (rest dom)))
(setf children (rest dom)))
(let ((*namespaces* (extend-namespaces (loop :for (name value) :in attributes
:collect (cons name value))
*namespaces*)))
(write-char #\< stream)
(print-identifier tag stream)
(loop :for (name value) :in attributes
:do (print-attribute name value stream))
(if children
(progn
(write-char #\> stream)
(if (and (= (length children) 1) (stringp (first children)))
(print-string-xml (first children) stream)
(progn
(dolist (child children)
(when pretty (print-spaces (* 2 level) stream))
(if (stringp child)
(print-string-xml child stream)
(print-xml-dom child input-type stream pretty (1+ level))))
(when pretty (print-spaces (* 2 (1- level)) stream))))
(print-closing-tag tag stream))
(write-string "/>" stream)))))
(t (error "Input not recognized as SXML ~s" dom))))
;;;; eof
| 0 |
apollo_public_repos/apollo-platform/ros/roslisp/s-xml | apollo_public_repos/apollo-platform/ros/roslisp/s-xml/src/dom.lisp | ;;;; -*- mode: lisp -*-
;;;;
;;;; $Id: dom.lisp,v 1.2 2005/08/29 15:01:47 scaekenberghe Exp $
;;;;
;;;; This is the generic simple DOM parser and printer interface.
;;;;
;;;; Copyright (C) 2002, 2004 Sven Van Caekenberghe, Beta Nine BVBA.
;;;;
;;;; You are granted the rights to distribute and use this software
;;;; as governed by the terms of the Lisp Lesser General Public License
;;;; (http://opensource.franz.com/preamble.html), also known as the LLGPL.
(in-package :s-xml)
;;; top level DOM parser interface
(defgeneric parse-xml-dom (stream output-type)
(:documentation "Parse a character stream as XML and generate a DOM of output-type"))
(defun parse-xml (stream &key (output-type :lxml))
"Parse a character stream as XML and generate a DOM of output-type, defaulting to :lxml"
(parse-xml-dom stream output-type))
(defun parse-xml-string (string &key (output-type :lxml))
"Parse a string as XML and generate a DOM of output-type, defaulting to :lxml"
(with-input-from-string (stream string)
(parse-xml-dom stream output-type)))
(defun parse-xml-file (filename &key (output-type :lxml))
"Parse a character file as XML and generate a DOM of output-type, defaulting to :lxml"
(with-open-file (in filename :direction :input)
(parse-xml-dom in output-type)))
;;; top level DOM printer interface
(defgeneric print-xml-dom (dom input-type stream pretty level)
(:documentation "Generate XML output on a character stream from a DOM of input-type, optionally pretty printing using level"))
(defun print-xml (dom &key (stream t) (pretty nil) (input-type :lxml) (header))
"Generate XML output on a character stream (t by default) from a DOM of input-type (:lxml by default), optionally pretty printing (off by default), or adding a header (none by default)"
(when header (format stream header))
(when pretty (terpri stream))
(print-xml-dom dom input-type stream pretty 1))
(defun print-xml-string (dom &key (pretty nil) (input-type :lxml))
"Generate XML output to a string from a DOM of input-type (:lxml by default), optionally pretty printing (off by default)"
(with-output-to-string (stream)
(print-xml dom :stream stream :pretty pretty :input-type input-type)))
;;; shared/common support functions
(defun print-spaces (n stream &optional (preceding-newline t))
(when preceding-newline
(terpri stream))
(loop :repeat n
:do (write-char #\Space stream)))
(defun print-solitary-tag (tag stream)
(write-char #\< stream)
(print-identifier tag stream)
(write-string "/>" stream))
(defun print-closing-tag (tag stream)
(write-string "</" stream)
(print-identifier tag stream)
(write-char #\> stream))
(defun print-attribute (name value stream)
(write-char #\space stream)
(print-identifier name stream t)
(write-string "=\"" stream)
(print-string-xml value stream)
(write-char #\" stream))
;;;; eof
| 0 |
apollo_public_repos/apollo-platform/ros/roslisp | apollo_public_repos/apollo-platform/ros/roslisp/rosbuild/roslisp.cmake | rosbuild_find_ros_package(roslisp)
# Message-generation support.
macro(genmsg_lisp)
rosbuild_get_msgs(_msglist)
set(_autogen "")
foreach(_msg ${_msglist})
# Construct the path to the .msg file
set(_input ${PROJECT_SOURCE_DIR}/msg/${_msg})
rosbuild_gendeps(${PROJECT_NAME} ${_msg})
set(genmsg_lisp_exe ${roslisp_PACKAGE_PATH}/rosbuild/scripts/genmsg_lisp.py)
set(_output_lisp ${PROJECT_SOURCE_DIR}/msg_gen/lisp/${_msg})
set(_output_lisp_package ${PROJECT_SOURCE_DIR}/msg_gen/lisp/_package.lisp)
set(_output_lisp_export ${PROJECT_SOURCE_DIR}/msg_gen/lisp/_package_${_msg})
string(REPLACE ".msg" ".lisp" _output_lisp ${_output_lisp})
string(REPLACE ".msg" ".lisp" _output_lisp_export ${_output_lisp_export})
# Add the rule to build the .h and .py from the .msg
add_custom_command(OUTPUT ${_output_lisp} ${_output_lisp_package} ${_output_lisp_export}
COMMAND ${genmsg_lisp_exe} ${_input}
DEPENDS ${_input} ${genmsg_lisp_exe} ${gendeps_exe} ${${PROJECT_NAME}_${_msg}_GENDEPS} ${ROS_MANIFEST_LIST})
list(APPEND _autogen ${_output_lisp} ${_output_lisp_package} ${_output_lisp_export})
endforeach(_msg)
# Create a target that depends on the union of all the autogenerated
# files
add_custom_target(ROSBUILD_genmsg_lisp DEPENDS ${_autogen})
# Make our target depend on rosbuild_premsgsrvgen, to allow any
# pre-msg/srv generation steps to be done first.
add_dependencies(ROSBUILD_genmsg_lisp rosbuild_premsgsrvgen)
# Add our target to the top-level genmsg target, which will be fired if
# the user calls genmsg()
add_dependencies(rospack_genmsg ROSBUILD_genmsg_lisp)
if(_autogen)
# Also set up to clean the msg_gen directory
get_directory_property(_old_clean_files ADDITIONAL_MAKE_CLEAN_FILES)
list(APPEND _old_clean_files ${PROJECT_SOURCE_DIR}/msg_gen)
set_directory_properties(PROPERTIES ADDITIONAL_MAKE_CLEAN_FILES "${_old_clean_files}")
endif(_autogen)
endmacro(genmsg_lisp)
# Call the macro we just defined.
genmsg_lisp()
# Service-generation support.
macro(gensrv_lisp)
rosbuild_get_srvs(_srvlist)
set(_autogen "")
foreach(_srv ${_srvlist})
# Construct the path to the .srv file
set(_input ${PROJECT_SOURCE_DIR}/srv/${_srv})
rosbuild_gendeps(${PROJECT_NAME} ${_srv})
set(gensrv_lisp_exe ${roslisp_PACKAGE_PATH}/rosbuild/scripts/genmsg_lisp.py)
set(_output_lisp ${PROJECT_SOURCE_DIR}/srv_gen/lisp/${_srv})
set(_output_lisp_package ${PROJECT_SOURCE_DIR}/srv_gen/lisp/_package.lisp)
set(_output_lisp_export ${PROJECT_SOURCE_DIR}/srv_gen/lisp/_package_${_srv})
string(REPLACE ".srv" ".lisp" _output_lisp ${_output_lisp})
string(REPLACE ".srv" ".lisp" _output_lisp_export ${_output_lisp_export})
# Add the rule to build the .h and .py from the .srv
add_custom_command(OUTPUT ${_output_lisp} ${_output_lisp_package} ${_output_lisp_export}
COMMAND ${gensrv_lisp_exe} ${_input}
DEPENDS ${_input} ${gensrv_lisp_exe} ${gendeps_exe} ${${PROJECT_NAME}_${_srv}_GENDEPS} ${ROS_MANIFEST_LIST})
list(APPEND _autogen ${_output_lisp} ${_output_lisp_package} ${_output_lisp_export})
endforeach(_srv)
# Create a target that depends on the union of all the autogenerated
# files
add_custom_target(ROSBUILD_gensrv_lisp DEPENDS ${_autogen})
# Make our target depend on rosbuild_premsgsrvgen, to allow any
# pre-msg/srv generation steps to be done first.
add_dependencies(ROSBUILD_gensrv_lisp rosbuild_premsgsrvgen)
# Add our target to the top-level gensrv target, which will be fired if
# the user calls gensrv()
add_dependencies(rospack_gensrv ROSBUILD_gensrv_lisp)
if(_autogen)
# Also set up to clean the srv_gen directory
get_directory_property(_old_clean_files ADDITIONAL_MAKE_CLEAN_FILES)
list(APPEND _old_clean_files ${PROJECT_SOURCE_DIR}/srv_gen)
set_directory_properties(PROPERTIES ADDITIONAL_MAKE_CLEAN_FILES "${_old_clean_files}")
endif(_autogen)
endmacro(gensrv_lisp)
# Call the macro we just defined.
gensrv_lisp()
# Old rospack_add_lisp_executable.
#macro(rospack_add_lisp_executable exe lispfile)
# add_custom_command(OUTPUT ${CMAKE_CURRENT_SOURCE_DIR}/${exe}
# COMMAND ${roslisp_make_node_exe} ${CMAKE_CURRENT_SOURCE_DIR}/${lispfile} ${roslisp_image_file} ${CMAKE_CURRENT_SOURCE_DIR}/${exe}
# DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/${lispfile} ${roslisp_image_file})
# set(_targetname _roslisp_${exe})
# string(REPLACE "/" "_" _targetname ${_targetname})
# add_custom_target(${_targetname} ALL
# DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/${exe})
# add_dependencies(${_targetname} _rospack_genmsg)
# add_dependencies(${_targetname} _rospack_gensrv)
#endmacro(rospack_add_lisp_executable)
# New rospack_add_lisp_executable (#1102)
rosbuild_find_ros_package(roslisp)
set(roslisp_make_node_exe ${roslisp_PACKAGE_PATH}/scripts/make_node_exec)
# Build up a list of executables, in order to make them depend on each
# other, to avoid building them in parallel, because it's not safe to do
# that.
set(roslisp_executables)
macro(rosbuild_add_lisp_executable _output _system_name _entry_point)
set(_targetname _roslisp_${_output})
string(REPLACE "/" "_" _targetname ${_targetname})
# Add dummy custom command to get make clean behavior right.
add_custom_command(OUTPUT ${CMAKE_CURRENT_SOURCE_DIR}/${_output} ${CMAKE_CURRENT_SOURCE_DIR}/${_output}.lisp
COMMAND echo -n)
add_custom_target(${_targetname} ALL
DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/${_output} ${CMAKE_CURRENT_SOURCE_DIR}/${_output}.lisp
COMMAND ${roslisp_make_node_exe} ${PROJECT_NAME} ${_system_name} ${_entry_point} ${CMAKE_CURRENT_SOURCE_DIR}/${_output})
# Make this executable depend on all previously declared executables, to
# serialize them.
add_dependencies(${_targetname} rosbuild_precompile ${roslisp_executables})
# Add this executable to the list of executables on which all future
# executables will depend.
list(APPEND roslisp_executables ${_targetname})
endmacro(rosbuild_add_lisp_executable)
macro(rospack_add_lisp_executable _output _system_name _entry_point)
_rosbuild_warn_deprecate_rospack_prefix(rospack_add_lisp_executable)
rosbuild_add_lisp_executable(${_output} ${_system_name} ${_entry_point})
endmacro(rospack_add_lisp_executable)
| 0 |
apollo_public_repos/apollo-platform/ros/roslisp/rosbuild | apollo_public_repos/apollo-platform/ros/roslisp/rosbuild/scripts/genmsg_lisp.py | #!/usr/bin/env python
# Software License Agreement (BSD License)
#
# Copyright (c) 2009, Willow Garage, Inc.
# 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 Willow Garage, Inc. nor the names of its
# 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.
#
## ROS message source code generation for Lisp
##
## Converts ROS .msg and .srv files in a package into Lisp source code
## t0: needed for script to work
## t1: for reference; remove once running
## t2: can be changed once we remove strict diff-compatibility requirement with old version of genmsg_lisp
import sys
import os
import traceback
import re
import roslib.msgs
import roslib.srvs
import roslib.packages
import roslib.gentools
from roslib.msgs import MsgSpec
from roslib.srvs import SrvSpec
try:
from cStringIO import StringIO #Python 2.x
except ImportError:
from io import StringIO #Python 3.x
############################################################
# Built in types
############################################################
def is_fixnum(t):
return t in ['int8', 'uint8', 'int16', 'uint16']
def is_integer(t):
return is_fixnum(t) or t in ['byte', 'char', 'int32', 'uint32', 'int64', 'uint64'] #t2 byte, char can be fixnum
def is_signed_int(t):
return t in ['int8', 'int16', 'int32', 'int64']
def is_unsigned_int(t):
return t in ['uint8', 'uint16', 'uint32', 'uint64']
def is_bool(t):
return t == 'bool'
def is_string(t):
return t == 'string'
def is_float(t):
return t in ['float16', 'float32', 'float64']
def is_time(t):
return t in ['time', 'duration']
def field_type(f):
if f.is_builtin:
elt_type = lisp_type(f.base_type)
else:
elt_type = msg_type(f)
if f.is_array:
return '(cl:vector %s)'%elt_type
else:
return elt_type
def parse_msg_type(f):
if f.base_type == 'Header':
return ('std_msgs', 'Header')
else:
return f.base_type.split('/')
# t2 no need for is_array
def msg_type(f):
(pkg, msg) = parse_msg_type(f)
return '%s-msg:%s'%(pkg, msg)
def lisp_type(t):
if is_fixnum(t):
return 'cl:fixnum'
elif is_integer(t):
return 'cl:integer'
elif is_bool(t):
return 'cl:boolean'
elif is_float(t):
return 'cl:float'
elif is_time(t):
return 'cl:real'
elif is_string(t):
return 'cl:string'
else:
raise ValueError('%s is not a recognized primitive type'%t)
def field_initform(f):
if f.is_builtin:
initform = lisp_initform(f.base_type)
elt_type = lisp_type(f.base_type)
else:
initform = '(cl:make-instance \'%s)'%msg_type(f)
elt_type = msg_type(f)
if f.is_array:
len = f.array_len or 0
return '(cl:make-array %s :element-type \'%s :initial-element %s)'%(len, elt_type, initform)
else:
return initform
def lisp_initform(t):
if is_integer(t):
return '0'
elif is_bool(t):
return 'cl:nil'
elif is_float(t):
return '0.0'
elif is_time(t):
return 0
elif is_string(t):
return '\"\"'
else:
raise ValueError('%s is not a recognized primitive type'%t)
NUM_BYTES = {'int8': 1, 'int16': 2, 'int32': 4, 'int64': 8,
'uint8': 1, 'uint16': 2, 'uint32': 4, 'uint64': 8}
############################################################
# Indented writer
############################################################
class IndentedWriter():
def __init__(self, s):
self.str = s
self.indentation = 0
self.block_indent = False
def write(self, s, indent=True, newline=True):
if not indent:
newline = False
if self.block_indent:
self.block_indent = False
else:
if newline:
self.str.write('\n')
if indent:
for i in range(self.indentation):
self.str.write(' ')
self.str.write(s)
def newline(self):
self.str.write('\n')
def inc_indent(self, inc=2):
self.indentation += inc
def dec_indent(self, dec=2):
self.indentation -= dec
def reset_indent(self):
self.indentation = 0
def block_next_indent(self):
self.block_indent = True
class Indent():
def __init__(self, w, inc=2, indent_first=True):
self.writer = w
self.inc = inc
self.indent_first = indent_first
def __enter__(self):
self.writer.inc_indent(self.inc)
if not self.indent_first:
self.writer.block_next_indent()
def __exit__(self, type, val, traceback):
self.writer.dec_indent(self.inc)
def write_begin(s, spec, path, is_service=False):
"Writes the beginning of the file: a comment saying it's auto-generated and the in-package form"
s.write('; Auto-generated. Do not edit!\n\n\n', newline=False)
suffix = 'srv' if is_service else 'msg'
s.write('(cl:in-package %s-%s)\n\n\n'%(spec.package, suffix), newline=False)
def write_html_include(s, spec, is_srv=False):
s.write(';//! \\htmlinclude %s.msg.html\n'%spec.actual_name, newline=False) # t2
def write_slot_definition(s, field):
"Write the definition of a slot corresponding to a single message field"
s.write('(%s'%field.name)
with Indent(s, 1):
s.write(':reader %s'%field.name)
s.write(':initarg :%s'%field.name)
s.write(':type %s'%field_type(field))
i = 0 if field.is_array else 1 # t2
with Indent(s, i):
s.write(':initform %s)'%field_initform(field))
def write_deprecated_readers(s, spec):
suffix = 'srv' if spec.component_type == 'service' else 'msg'
for field in spec.parsed_fields():
s.newline()
s.write('(cl:ensure-generic-function \'%s-val :lambda-list \'(m))' % field.name)
s.write('(cl:defmethod %s-val ((m %s))'%(field.name, message_class(spec)))
with Indent(s):
s.write('(roslisp-msg-protocol:msg-deprecation-warning "Using old-style slot reader %s-%s:%s-val is deprecated. Use %s-%s:%s instead.")'%(spec.package, suffix, field.name, spec.package, suffix, field.name))
s.write('(%s m))'%field.name)
def write_defclass(s, spec):
"Writes the defclass that defines the message type"
cl = message_class(spec)
new_cl = new_message_class(spec)
suffix = 'srv' if spec.component_type == 'service' else 'msg'
s.write('(cl:defclass %s (roslisp-msg-protocol:ros-message)'%cl)
with Indent(s):
s.write('(')
with Indent(s, inc=1, indent_first=False):
for field in spec.parsed_fields():
write_slot_definition(s, field)
s.write(')', indent=False)
s.write(')')
s.newline()
s.write('(cl:defclass %s (%s)'%(new_cl, cl))
with Indent(s):
s.write('())')
s.newline()
s.write('(cl:defmethod cl:initialize-instance :after ((m %s) cl:&rest args)'%cl)
with Indent(s):
s.write('(cl:declare (cl:ignorable args))')
s.write('(cl:unless (cl:typep m \'%s)'%new_cl)
with Indent(s):
s.write('(roslisp-msg-protocol:msg-deprecation-warning "using old message class name %s-%s:%s is deprecated: use %s-%s:%s instead.")))'%(spec.package, suffix, cl, spec.package, suffix, new_cl))
def message_class(spec):
"""
Return the CLOS class name for this message type
"""
return '<%s>'%spec.actual_name
def new_message_class(spec):
return spec.actual_name
def write_serialize_length(s, v, is_array=False):
#t2
var = '__ros_arr_len' if is_array else '__ros_str_len'
s.write('(cl:let ((%s (cl:length %s)))'%(var, v))
with Indent(s):
for x in range(0, 32, 8):
s.write('(cl:write-byte (cl:ldb (cl:byte 8 %s) %s) ostream)'%(x, var))
s.write(')', indent=False)
def write_serialize_bits(s, v, num_bytes):
for x in range(0, num_bytes*8, 8):
s.write('(cl:write-byte (cl:ldb (cl:byte 8 %s) %s) ostream)'%(x, v))
def write_serialize_bits_signed(s, v, num_bytes):
num_bits = num_bytes*8
s.write('(cl:let* ((signed %s) (unsigned (cl:if (cl:< signed 0) (cl:+ signed %s) signed)))'%(v, 2**num_bits))
with Indent(s):
write_serialize_bits(s, 'unsigned', num_bytes)
s.write(')')
# t2: can get rid of this lookup_slot stuff
def write_serialize_builtin(s, f, var='msg', lookup_slot=True):
v = '(cl:slot-value %s \'%s)'%(var, f.name) if lookup_slot else var
if f.base_type == 'string':
write_serialize_length(s, v)
s.write('(cl:map cl:nil #\'(cl:lambda (c) (cl:write-byte (cl:char-code c) ostream)) %s)'%v)
elif f.base_type == 'float32':
s.write('(cl:let ((bits %s))'%'(roslisp-utils:encode-single-float-bits %s)'%v)
with Indent(s):
write_serialize_bits(s, 'bits', 4)
s.write(')', False)
elif f.base_type == 'float64':
s.write('(cl:let ((bits %s))'%'(roslisp-utils:encode-double-float-bits %s)'%v)
with Indent(s):
write_serialize_bits(s, 'bits', 8)
s.write(')', False)
elif f.base_type == 'bool':
s.write('(cl:write-byte (cl:ldb (cl:byte 8 0) (cl:if %s 1 0)) ostream)'%v)
elif f.base_type in ['byte', 'char']:
s.write('(cl:write-byte (cl:ldb (cl:byte 8 0) %s) ostream)'%v)
elif f.base_type in ['duration', 'time']:
s.write('(cl:let ((__sec (cl:floor %s))'%v)
s.write(' (__nsec (cl:round (cl:* 1e9 (cl:- %s (cl:floor %s))))))'%(v,v))
with Indent(s):
write_serialize_bits(s, '__sec', 4)
write_serialize_bits(s, '__nsec', 4)
s.write(')', False)
elif is_signed_int(f.base_type):
write_serialize_bits_signed(s, v, NUM_BYTES[f.base_type])
elif is_unsigned_int(f.base_type):
write_serialize_bits(s, v, NUM_BYTES[f.base_type])
else:
raise ValueError('Unknown type: %s', f.base_type)
def write_serialize_field(s, f):
slot = '(cl:slot-value msg \'%s)'%f.name
if f.is_array:
if not f.array_len:
write_serialize_length(s, slot, True)
s.write('(cl:map cl:nil #\'(cl:lambda (ele) ')
var = 'ele'
s.block_next_indent()
lookup_slot = False
else:
var='msg'
lookup_slot = True
if f.is_builtin:
write_serialize_builtin(s, f, var, lookup_slot=lookup_slot)
else:
to_write = slot if lookup_slot else var #t2
s.write('(roslisp-msg-protocol:serialize %s ostream)'%to_write)
if f.is_array:
s.write(')', False)
s.write(' %s)'%slot)
def write_serialize(s, spec):
"""
Write the serialize method
"""
s.write('(cl:defmethod roslisp-msg-protocol:serialize ((msg %s) ostream)'%message_class(spec))
with Indent(s):
s.write('"Serializes a message object of type \'%s"'%message_class(spec))
for f in spec.parsed_fields():
write_serialize_field(s, f)
s.write(')')
# t2 can get rid of is_array
def write_deserialize_length(s, is_array=False):
var = '__ros_arr_len' if is_array else '__ros_str_len'
s.write('(cl:let ((%s 0))'%var)
with Indent(s):
for x in range(0, 32, 8):
s.write('(cl:setf (cl:ldb (cl:byte 8 %s) %s) (cl:read-byte istream))'%(x, var))
def write_deserialize_bits(s, v, num_bytes):
for x in range(0, num_bytes*8, 8):
s.write('(cl:setf (cl:ldb (cl:byte 8 %s) %s) (cl:read-byte istream))'%(x, v))
def write_deserialize_bits_signed(s, v, num_bytes):
s.write('(cl:let ((unsigned 0))')
num_bits = 8*num_bytes
with Indent(s):
write_deserialize_bits(s, 'unsigned', num_bytes)
s.write('(cl:setf %s (cl:if (cl:< unsigned %s) unsigned (cl:- unsigned %s))))'%(v, 2**(num_bits-1), 2**num_bits))
def write_deserialize_builtin(s, f, v):
if f.base_type == 'string':
write_deserialize_length(s)
with Indent(s):
s.write('(cl:setf %s (cl:make-string __ros_str_len))'%v)
s.write('(cl:dotimes (__ros_str_idx __ros_str_len msg)')
with Indent(s):
s.write('(cl:setf (cl:char %s __ros_str_idx) (cl:code-char (cl:read-byte istream)))))'%v)
elif f.base_type == 'float32':
s.write('(cl:let ((bits 0))')
with Indent(s):
write_deserialize_bits(s, 'bits', 4)
s.write('(cl:setf %s (roslisp-utils:decode-single-float-bits bits)))'%v)
elif f.base_type == 'float64':
s.write('(cl:let ((bits 0))')
with Indent(s):
write_deserialize_bits(s, 'bits', 8)
s.write('(cl:setf %s (roslisp-utils:decode-double-float-bits bits)))'%v)
elif f.base_type == 'bool':
s.write('(cl:setf %s (cl:not (cl:zerop (cl:read-byte istream))))'%v)
elif f.base_type in ['byte', 'char']:
s.write('(cl:setf (cl:ldb (cl:byte 8 0) %s) (cl:read-byte istream))'%v)
elif f.base_type in ['duration', 'time']:
s.write('(cl:let ((__sec 0) (__nsec 0))')
with Indent(s):
write_deserialize_bits(s, '__sec', 4)
write_deserialize_bits(s, '__nsec', 4)
s.write('(cl:setf %s (cl:+ (cl:coerce __sec \'cl:double-float) (cl:/ __nsec 1e9))))'%v)
elif is_signed_int(f.base_type):
write_deserialize_bits_signed(s, v, NUM_BYTES[f.base_type])
elif is_unsigned_int(f.base_type):
write_deserialize_bits(s, v, NUM_BYTES[f.base_type])
else:
raise ValueError('%s unknown'%f.base_type)
def write_deserialize_field(s, f, pkg):
slot = '(cl:slot-value msg \'%s)'%f.name
var = slot
if f.is_array:
if not f.array_len:
write_deserialize_length(s, True)
length = '__ros_arr_len'
else:
length = '%s'%f.array_len
s.write('(cl:setf %s (cl:make-array %s))'%(slot, length))
s.write('(cl:let ((vals %s))'%slot) # t2
var = '(cl:aref vals i)'
with Indent(s):
s.write('(cl:dotimes (i %s)'%length)
if f.is_builtin:
with Indent(s):
write_deserialize_builtin(s, f, var)
else:
if f.is_array:
with Indent(s):
s.write('(cl:setf %s (cl:make-instance \'%s))'%(var, msg_type(f)))
s.write('(roslisp-msg-protocol:deserialize %s istream)'%var)
if f.is_array:
s.write('))', False)
if not f.array_len:
s.write(')', False)
def write_deserialize(s, spec):
"""
Write the deserialize method
"""
s.write('(cl:defmethod roslisp-msg-protocol:deserialize ((msg %s) istream)'%message_class(spec))
with Indent(s):
s.write('"Deserializes a message object of type \'%s"'%message_class(spec))
for f in spec.parsed_fields():
write_deserialize_field(s, f, spec.package)
s.write('msg')
s.write(')')
def write_class_exports(s, pkg):
"Write the _package.lisp file"
s.write('(cl:defpackage %s-msg'%pkg, False)
with Indent(s):
s.write('(:use )')
s.write('(:export')
with Indent(s, inc=1):
for spec in roslib.msgs.get_pkg_msg_specs(pkg)[0]:
(p, msg_type) = spec[0].split('/')
msg_class = '<%s>'%msg_type
s.write('"%s"'%msg_class.upper())
s.write('"%s"'%msg_type.upper())
s.write('))\n\n')
def write_srv_exports(s, pkg):
"Write the _package.lisp file for a service directory"
s.write('(cl:defpackage %s-srv'%pkg, False)
with Indent(s):
s.write('(:use )')
s.write('(:export')
with Indent(s, inc=1):
for spec in roslib.srvs.get_pkg_srv_specs(pkg)[0]:
(_, srv_type) = spec[0].split('/')
s.write('"%s"'%srv_type.upper())
s.write('"<%s-REQUEST>"'%srv_type.upper())
s.write('"%s-REQUEST"'%srv_type.upper())
s.write('"<%s-RESPONSE>"'%srv_type.upper())
s.write('"%s-RESPONSE"'%srv_type.upper())
s.write('))\n\n')
def write_asd_deps(s, deps, msgs):
with Indent(s):
s.write(':depends-on (:roslisp-msg-protocol :roslisp-utils ')
with Indent(s, inc=13, indent_first=False):
for d in sorted(deps):
s.write(':%s-msg'%d)
s.write(')') #t2 indentation
with Indent(s):
s.write(':components ((:file "_package")')
with Indent(s):
for (full_name, _) in msgs:
(_, name) = full_name.split('/')
s.write('(:file "%s" :depends-on ("_package_%s"))'%(name, name))
s.write('(:file "_package_%s" :depends-on ("_package"))'%name)
s.write('))')
def write_srv_asd(s, pkg):
s.write('(cl:in-package :asdf)')
s.newline()
s.write('(defsystem "%s-srv"'%pkg)
services = roslib.srvs.get_pkg_srv_specs(pkg)[0]
# Figure out set of depended-upon ros packages
deps = set()
for (_, spec) in services:
for f in spec.request.parsed_fields():
if not f.is_builtin:
(p, _) = parse_msg_type(f)
deps.add(p)
for f in spec.response.parsed_fields():
if not f.is_builtin:
(p, _) = parse_msg_type(f)
deps.add(p)
write_asd_deps(s, deps, services)
def write_asd(s, pkg):
s.write('(cl:in-package :asdf)')
s.newline()
s.write('(defsystem "%s-msg"'%pkg)
msgs = roslib.msgs.get_pkg_msg_specs(pkg)[0]
# Figure out set of depended-upon ros packages
deps = set()
for (_, spec) in msgs:
for f in spec.parsed_fields():
if not f.is_builtin:
(p, _) = parse_msg_type(f)
deps.add(p)
if pkg in deps:
deps.remove(pkg)
write_asd_deps(s, deps, msgs)
def write_accessor_exports(s, spec):
"Write the package exports for this message/service"
is_srv = isinstance(spec, SrvSpec)
suffix = 'srv' if is_srv else 'msg'
s.write('(cl:in-package %s-%s)'%(spec.package, suffix), indent=False)
s.write('(cl:export \'(')
if is_srv:
fields = spec.request.parsed_fields()[:]
fields.extend(spec.response.parsed_fields())
else:
fields = spec.parsed_fields()
with Indent(s, inc=10, indent_first=False):
for f in fields:
accessor = '%s-val'%f.name
s.write('%s'%accessor.upper())
s.write('%s'%f.name.upper())
s.write('))')
def write_ros_datatype(s, spec):
for c in (message_class(spec), new_message_class(spec)):
s.write('(cl:defmethod roslisp-msg-protocol:ros-datatype ((msg (cl:eql \'%s)))'%c)
with Indent(s):
s.write('"Returns string type for a %s object of type \'%s"'%(spec.component_type, c))
s.write('"%s")'%spec.full_name)
def write_md5sum(s, spec, parent=None):
if parent is None:
parent = spec
gendeps_dict = roslib.gentools.get_dependencies(parent, spec.package,
compute_files=False)
md5sum = roslib.gentools.compute_md5(gendeps_dict)
for c in (message_class(spec), new_message_class(spec)):
s.write('(cl:defmethod roslisp-msg-protocol:md5sum ((type (cl:eql \'%s)))'%c)
with Indent(s):
# t2 this should print 'service' instead of 'message' if it's a service request or response
s.write('"Returns md5sum for a message object of type \'%s"'%c)
s.write('"%s")'%md5sum)
def write_message_definition(s, spec):
for c in (message_class(spec), new_message_class(spec)):
s.write('(cl:defmethod roslisp-msg-protocol:message-definition ((type (cl:eql \'%s)))'%c)
with Indent(s):
s.write('"Returns full string definition for message of type \'%s"'%c)
s.write('(cl:format cl:nil "')
gendeps_dict = roslib.gentools.get_dependencies(spec, spec.package, compute_files=False)
definition = roslib.gentools.compute_full_text(gendeps_dict)
lines = definition.split('\n')
for line in lines:
l = line.replace('\\', '\\\\')
l = l.replace('"', '\\"')
s.write('%s~%%'%l, indent=False)
s.write('~%', indent=False)
s.write('"))', indent=False)
def write_builtin_length(s, f, var='msg'):
if f.base_type in ['int8', 'uint8']:
s.write('1')
elif f.base_type in ['int16', 'uint16']:
s.write('2')
elif f.base_type in ['int32', 'uint32', 'float32']:
s.write('4')
elif f.base_type in ['int64', 'uint64', 'float64', 'duration', 'time']:
s.write('8')
elif f.base_type == 'string':
s.write('4 (cl:length %s)'%var)
elif f.base_type in ['bool', 'byte', 'char']:
s.write('1')
else:
raise ValueError('Unknown: %s', f.base_type)
def write_serialization_length(s, spec):
c = message_class(spec)
s.write('(cl:defmethod roslisp-msg-protocol:serialization-length ((msg %s))'%c)
with Indent(s):
s.write('(cl:+ 0')
with Indent(s, 3):
for field in spec.parsed_fields():
slot = '(cl:slot-value msg \'%s)'%field.name
if field.is_array:
l = '0' if field.array_len else '4'
s.write('%s (cl:reduce #\'cl:+ %s :key #\'(cl:lambda (ele) (cl:declare (cl:ignorable ele)) (cl:+ '%(l, slot))
var = 'ele'
s.block_next_indent()
else:
var = slot
if field.is_builtin:
write_builtin_length(s, field, var)
else:
s.write('(roslisp-msg-protocol:serialization-length %s)'%var)
if field.is_array:
s.write(')))', False)
s.write('))')
def write_list_converter(s, spec):
c = message_class(spec)
s.write('(cl:defmethod roslisp-msg-protocol:ros-message-to-list ((msg %s))'%c)
with Indent(s):
s.write('"Converts a ROS message object to a list"')
s.write('(cl:list \'%s'%new_message_class(spec))
with Indent(s):
for f in spec.parsed_fields():
s.write('(cl:cons \':%s (%s msg))'%(f.name, f.name))
s.write('))')
def write_constants(s, spec):
if spec.constants:
for cls in (message_class(spec), new_message_class(spec)):
s.write('(cl:defmethod roslisp-msg-protocol:symbol-codes ((msg-type (cl:eql \'%s)))'%cls)
with Indent(s):
s.write(' "Constants for message type \'%s"'%cls)
s.write('\'(')
with Indent(s, indent_first=False):
for c in spec.constants:
s.write('(:%s . %s)'%(c.name.upper(), c.val))
s.write(')', False)
s.write(')')
def write_srv_component(s, spec, parent):
spec.component_type='service'
write_html_include(s, spec)
write_defclass(s, spec)
write_deprecated_readers(s, spec)
write_constants(s, spec)
write_serialize(s, spec)
write_deserialize(s, spec)
write_ros_datatype(s, spec)
write_md5sum(s, spec, parent)
write_message_definition(s, spec)
write_serialization_length(s, spec)
write_list_converter(s, spec)
def write_service_specific_methods(s, spec):
spec.actual_name=spec.short_name
s.write('(cl:defmethod roslisp-msg-protocol:service-request-type ((msg (cl:eql \'%s)))'%spec.short_name)
with Indent(s):
s.write('\'%s)'%new_message_class(spec.request))
s.write('(cl:defmethod roslisp-msg-protocol:service-response-type ((msg (cl:eql \'%s)))'%spec.short_name)
with Indent(s):
s.write('\'%s)'%new_message_class(spec.response))
s.write('(cl:defmethod roslisp-msg-protocol:ros-datatype ((msg (cl:eql \'%s)))'%spec.short_name)
with Indent(s):
s.write('"Returns string type for a service object of type \'%s"'%message_class(spec))
s.write('"%s")'%spec.full_name)
def generate_msg(msg_path):
"""
Generate a message
@param msg_path: The path to the .msg file
@type msg_path: str
"""
(package_dir, package) = roslib.packages.get_dir_pkg(msg_path)
(_, spec) = roslib.msgs.load_from_file(msg_path, package)
spec.actual_name=spec.short_name
spec.component_type='message'
########################################
# 1. Write the .lisp file
########################################
io = StringIO()
s = IndentedWriter(io)
write_begin(s, spec, msg_path)
write_html_include(s, spec)
write_defclass(s, spec)
write_deprecated_readers(s, spec)
write_constants(s, spec)
write_serialize(s, spec)
write_deserialize(s, spec)
write_ros_datatype(s, spec)
write_md5sum(s, spec)
write_message_definition(s, spec)
write_serialization_length(s, spec)
write_list_converter(s, spec)
output_dir = '%s/msg_gen/lisp'%package_dir
if (not os.path.exists(output_dir)):
# if we're being run concurrently, the above test can report false but os.makedirs can still fail if
# another copy just created the directory
try:
os.makedirs(output_dir)
except OSError as e:
pass
with open('%s/%s.lisp'%(output_dir, spec.short_name), 'w') as f:
f.write(io.getvalue() + "\n")
io.close()
########################################
# 2. Write the _package file
# for this message
########################################
io = StringIO()
s = IndentedWriter(io)
write_accessor_exports(s, spec)
with open('%s/_package_%s.lisp'%(output_dir, spec.short_name), 'w') as f:
f.write(io.getvalue())
io.close()
########################################
# 3. Write the _package.lisp file
# This is being rewritten once per msg
# file, which is inefficient
########################################
io = StringIO()
s = IndentedWriter(io)
write_class_exports(s, package)
with open('%s/_package.lisp'%output_dir, 'w') as f:
f.write(io.getvalue())
io.close()
########################################
# 4. Write the .asd file
# This is being written once per msg
# file, which is inefficient
########################################
io = StringIO()
s = IndentedWriter(io)
write_asd(s, package)
with open('%s/%s-msg.asd'%(output_dir, package), 'w') as f:
f.write(io.getvalue())
io.close()
# t0 most of this could probably be refactored into being shared with messages
def generate_srv(srv_path):
"Generate code from .srv file"
(pkg_dir, pkg) = roslib.packages.get_dir_pkg(srv_path)
(_, spec) = roslib.srvs.load_from_file(srv_path, pkg)
output_dir = '%s/srv_gen/lisp'%pkg_dir
if (not os.path.exists(output_dir)):
# if we're being run concurrently, the above test can report false but os.makedirs can still fail if
# another copy just created the directory
try:
os.makedirs(output_dir)
except OSError as e:
pass
########################################
# 1. Write the .lisp file
########################################
io = StringIO()
s = IndentedWriter(io)
write_begin(s, spec, srv_path, True)
spec.request.actual_name='%s-request'%spec.short_name
spec.response.actual_name='%s-response'%spec.short_name
write_srv_component(s, spec.request, spec)
s.newline()
write_srv_component(s, spec.response, spec)
write_service_specific_methods(s, spec)
with open('%s/%s.lisp'%(output_dir, spec.short_name), 'w') as f:
f.write(io.getvalue())
io.close()
########################################
# 2. Write the _package file
# for this service
########################################
io = StringIO()
s = IndentedWriter(io)
write_accessor_exports(s, spec)
with open('%s/_package_%s.lisp'%(output_dir, spec.short_name), 'w') as f:
f.write(io.getvalue())
io.close()
########################################
# 3. Write the _package.lisp file
########################################
io = StringIO()
s = IndentedWriter(io)
write_srv_exports(s, pkg)
with open('%s/_package.lisp'%output_dir, 'w') as f:
f.write(io.getvalue())
io.close()
########################################
# 4. Write the .asd file
########################################
io = StringIO()
s = IndentedWriter(io)
write_srv_asd(s, pkg)
with open('%s/%s-srv.asd'%(output_dir, pkg), 'w') as f:
f.write(io.getvalue())
io.close()
if __name__ == "__main__":
roslib.msgs.set_verbose(False)
if sys.argv[1].endswith('.msg'):
generate_msg(sys.argv[1])
elif sys.argv[1].endswith('.srv'):
generate_srv(sys.argv[1])
else:
raise ValueError('Invalid filename %s'%sys.argv[1])
| 0 |
apollo_public_repos/apollo-platform/ros/roslisp | apollo_public_repos/apollo-platform/ros/roslisp/cmake/roslisp-extras.cmake.em | #
# Generated from roslisp/cmake/roslisp-extras.cmake.in
#
@[if DEVELSPACE]@
# location of script in develspace
set(ROSLISP_MAKE_NODE_BIN "@(CMAKE_CURRENT_SOURCE_DIR)/scripts/make_node_exec")
set(ROSLISP_COMPILE_MANIFEST_BIN "@(CMAKE_CURRENT_SOURCE_DIR)/scripts/compile_load_manifest")
set(ROSLISP_EXE_SCRIPT "@(CMAKE_CURRENT_SOURCE_DIR)/scripts/make_exe_script")
@[else]@
# location of script in installspace
set(ROSLISP_MAKE_NODE_BIN "${roslisp_DIR}/../scripts/make_node_exec")
set(ROSLISP_COMPILE_MANIFEST_BIN "${roslisp_DIR}/../scripts/compile_load_manifest")
set(ROSLISP_EXE_SCRIPT "${roslisp_DIR}/../scripts/make_exe_script")
@[end if]@
# Build up a list of executables, in order to make them depend on each
# other, to avoid building them in parallel, because it's not safe to do
# that.
# The first entry in this list will be a target to compile ros-load-manifest
# as all the executables depend on it.
if(NOT TARGET _roslisp_load_manifest)
add_custom_target(_roslisp_load_manifest ALL COMMAND ${ROSLISP_COMPILE_MANIFEST_BIN})
endif()
set(ROSLISP_EXECUTABLES _roslisp_load_manifest)
# example usage:
# add_compiled_lisp_executable(my_script my-system my-system:my-func [my_targetname])
function(add_compiled_lisp_executable output system_name entry_point)
if(${ARGC} LESS 3 OR ${ARGC} GREATER 4)
message(SEND_ERROR "[roslisp] add_compiled_lisp_executable can only have 3 or 4 arguments")
elseif(${ARGC} LESS 4)
set(targetname _roslisp_${output})
else()
set(extra_macro_args ${ARGN})
list(GET extra_macro_args 0 targetname)
endif()
string(REPLACE "/" "_" targetname ${targetname})
set(targetdir ${CATKIN_DEVEL_PREFIX}/${CATKIN_PACKAGE_BIN_DESTINATION})
# Add dummy custom command to get make clean behavior right.
add_custom_command(OUTPUT ${targetdir}/${output} ${targetdir}/${output}.lisp
COMMAND echo -n)
add_custom_target(${targetname} ALL
DEPENDS ${targetdir}/${output} ${targetdir}/${output}.lisp
COMMAND ${ROSLISP_MAKE_NODE_BIN} ${PROJECT_NAME} ${system_name} ${entry_point} ${targetdir}/${output})
# Make this executable depend on all previously declared executables, to serialize them.
if(ROSLISP_EXECUTABLES)
add_dependencies(${targetname} ${ROSLISP_EXECUTABLES})
endif()
# Add this executable to the list of executables on which all future
# executables will depend.
list(APPEND ROSLISP_EXECUTABLES ${targetname})
set(ROSLISP_EXECUTABLES "${ROSLISP_EXECUTABLES}" PARENT_SCOPE)
# mark the generated executables for installation
install(PROGRAMS ${targetdir}/${output}
DESTINATION ${CATKIN_PACKAGE_BIN_DESTINATION})
install(FILES ${targetdir}/${output}.lisp
DESTINATION ${CATKIN_PACKAGE_BIN_DESTINATION})
endfunction(add_compiled_lisp_executable)
# example usage:
# add_lisp_executable(my_script my-system my-package:my-func)
function(add_lisp_executable output system_name entry_point)
if(NOT ${ARGC} EQUAL 3)
message(SEND_ERROR "[roslisp] add_lisp_executable can only have 3 arguments")
endif()
if(output MATCHES "/")
message(WARNING "First argument of ADD_LISP_EXECUTABLE (${output}) cannot contain slashes! Ignoring.")
string(REPLACE "/" "_" output ${output})
endif()
set(targetdir ${CATKIN_DEVEL_PREFIX}/${CATKIN_PACKAGE_BIN_DESTINATION})
set(targetname _roslisp_${output})
# create directory if it does not exist
file(MAKE_DIRECTORY ${targetdir})
# generate script
add_custom_command(OUTPUT ${targetdir}/${output}
COMMAND ${ROSLISP_EXE_SCRIPT} ${PROJECT_NAME} ${system_name} ${entry_point}
${targetdir}/${output}
DEPENDS ${ROSLISP_EXE_SCRIPT}
COMMENT "Generating lisp exe script ${targetdir}/${output}"
VERBATIM)
add_custom_target(${targetname} ALL DEPENDS ${targetdir}/${output})
# mark the generated executables for installation
install(PROGRAMS ${targetdir}/${output}
DESTINATION ${CATKIN_PACKAGE_BIN_DESTINATION})
endfunction(add_lisp_executable)
| 0 |
apollo_public_repos/apollo-platform/ros/roslisp | apollo_public_repos/apollo-platform/ros/roslisp/load-manifest/ros-load-manifest.asd | ;;;; -*- Mode: LISP -*-
(defsystem :ros-load-manifest
:name "ros-load-manifest"
:components ((:file "load-manifest"))
:depends-on (:sb-posix))
| 0 |
apollo_public_repos/apollo-platform/ros/roslisp | apollo_public_repos/apollo-platform/ros/roslisp/load-manifest/load-manifest.lisp | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Software License Agreement (BSD License)
;;
;; Copyright (c) 2008, Willow Garage, Inc.
;; 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 Willow Garage, Inc. nor the names
;; of its 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.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defpackage :ros-load-manifest
(:nicknames :ros-load)
(:export :load-manifest :load-system :asdf-paths-to-add :*current-ros-package*
:asdf-ros-search :asdf-ros-pkg-search :ros-package-path :ros-home :rospack)
(:use :cl))
(in-package :ros-load-manifest)
(defvar *current-ros-package* nil
"A string naming the current package. This is used in the asdf-ros-search search method.")
(defvar *ros-asdf-output-cache* (make-hash-table :test 'eq))
(defvar *ros-asdf-paths-cache* (make-hash-table :test 'equal)
"Cache of asdf directories returned by ASDF-PATHS-TO-ADD to reduce rospack calls.")
(defvar *ros-package-path-cache* (make-hash-table :test 'equal)
"Cache for ros package paths.")
(defvar *ros-asdf-use-ros-home* nil)
(defconstant +marker-file-timeout+ 60.0)
(defun asdf-system-of-component (component)
"Returns the system of a component."
(typecase component
(asdf:system component)
(asdf:component (asdf-system-of-component (asdf:component-parent component)))))
(defun path-ros-package (path &optional traversed)
"Traverses the `path' upwards until it finds a manifest.
Returns two values, the name of the ros package and the relative
part of path inside the package. Returns nil if no manifest could
be found."
(let ((manifest (probe-file (merge-pathnames "manifest.xml" path)))
(marker-file (probe-file (merge-pathnames "roslisp_ignore" path))))
(cond (marker-file nil)
(manifest
(values (truename path) traversed))
((not (cdr (pathname-directory path)))
nil)
(t
(path-ros-package (make-pathname :directory (butlast (pathname-directory path)))
(cons (car (last (pathname-directory path)))
traversed))))))
(defun asdf-system-ros-name (system)
"Returns the ros package name of a system."
(multiple-value-bind (package-path rel-path)
(path-ros-package (asdf:component-pathname system))
(assert (eq (car (pathname-directory package-path)) :absolute))
(values (car (last (pathname-directory package-path))) rel-path)))
(defun pathname-rel-subdir (p1 p2)
"returns the relative path of `p2' in `p1'."
(loop with result = (pathname-directory (truename p2))
for d1 in (pathname-directory (truename p1))
do (setf result (cdr result))
finally (return result)))
(defun roslisp-home-output-files (component)
"Returns the output filename of an asdf component inside ROS_HOME (or ~/.ros)."
(let ((system (asdf-system-of-component component))
(component-path (asdf:component-pathname component)))
(destructuring-bind (package-name rel-path)
(or (gethash system *ros-asdf-output-cache*)
(setf (gethash system *ros-asdf-output-cache*)
(multiple-value-list (asdf-system-ros-name system))))
(list
(asdf::compile-file-pathname
(merge-pathnames (make-pathname :name (pathname-name component-path)
:type (pathname-type component-path)
:directory `(:relative ,@(pathname-rel-subdir
(asdf:component-pathname system)
component-path)))
(merge-pathnames
(make-pathname :directory `(:relative "roslisp" ,package-name ,@rel-path))
(ros-home))))))))
;; Use lock file to prevent from parallel compilation of the same
;; system
(defun wait-for-file-deleted (file msg &optional delete-timeout)
"Waits for `file' to be removed or, when `timeout' is set and
expires, deletes the file."
(let ((timer (sb-ext:make-timer
(lambda () (delete-file file)))))
(when delete-timeout
(sb-ext:schedule-timer timer delete-timeout))
(unwind-protect
(let ((print-msg t))
(loop while (probe-file file) do
(when print-msg
(warn 'simple-warning :format-control msg)
(setf print-msg nil))
(sleep 0.5)))
(when delete-timeout
(sb-ext:unschedule-timer timer)))))
(defun compilation-marker-file-path (component)
(merge-pathnames (make-pathname
:name (concatenate 'string
".roslisp-compile-"
(asdf:component-name component)))
(ros-home)))
(defmethod asdf:perform :around ((op asdf:compile-op) component)
(unless (typep component 'asdf:cl-source-file)
(call-next-method)
(return-from asdf:perform))
(let ((marker-file-path (compilation-marker-file-path component)))
(unwind-protect
(tagbody
retry
(handler-bind
((file-error (lambda (e)
(declare (ignore e))
(wait-for-file-deleted
marker-file-path
(format nil
"System `~a' is compiled by a different process. Waiting for compilation of blocking file to finish. Will proceed in at most ~a seconds."
(asdf:component-name (asdf-system-of-component component))
+marker-file-timeout+)
+marker-file-timeout+)
(go retry))))
(close
(open marker-file-path
:if-exists :error
:if-does-not-exist :create
:direction :output)))
(call-next-method))
(when (probe-file marker-file-path)
(delete-file marker-file-path)))))
(defmethod asdf:perform :around ((op asdf:load-op) component)
(unless (typep component 'asdf:cl-source-file)
(call-next-method)
(return-from asdf:perform))
(let ((marker-file-path (compilation-marker-file-path component)))
(wait-for-file-deleted marker-file-path
(format nil
"System `~a' is compiled by a different process. Waiting for compilation of blocking file to finish."
(asdf:component-name (asdf-system-of-component component))))
(call-next-method)))
(defun ros-home ()
(or (sb-ext:posix-getenv "ROS_HOME")
(merge-pathnames (make-pathname :directory '(:relative ".ros"))
(user-homedir-pathname))))
(defun rospack (&rest cmd-args)
(labels ((split-str (seq &optional (separator #\Newline))
(labels ((doit (start-pos)
(let ((split-pos (position separator seq :start start-pos)))
(when split-pos
(cons (subseq seq start-pos split-pos)
(doit (1+ split-pos)))))))
(doit 0))))
(let* ((str (make-string-output-stream))
(error-str (make-string-output-stream))
(proc (sb-ext:run-program "rospack" cmd-args :search t :output str :error error-str))
(exit-code (sb-ext:process-exit-code proc)))
(if (zerop exit-code)
(split-str (get-output-stream-string str))
(error "rospack ~{~a~^ ~} returned ~a with stderr '~a'"
cmd-args exit-code (get-output-stream-string error-str))))))
(defun asdf-paths-to-add (package)
"Given a package name, calls rospack to find out the dependencies. Adds all the /asdf directories that it finds to a list and return it."
(let ((asdf-dir-list
(cons (get-asdf-directory (ros-package-path package))
(loop for pkg in (or (gethash package *ros-asdf-paths-cache*)
(setf (gethash package *ros-asdf-paths-cache*)
(rospack "depends" package)))
for asdf-dir = (get-asdf-directory (ros-package-path pkg))
when asdf-dir collecting asdf-dir))))
(remove nil asdf-dir-list)))
(defun normalize (str)
(let* ((pos (position #\Newline str))
(stripped (if pos
(subseq str 0 pos)
str)))
(if (eq #\/ (char stripped (1- (length stripped))))
stripped
(concatenate 'string stripped "/"))))
(defun ros-package-path (p)
(or (gethash p *ros-package-path-cache*)
(setf (gethash p *ros-package-path-cache*)
(pathname (normalize (first (rospack "find" p)))))))
(defun get-asdf-directory (path)
(let ((asdf-path (merge-pathnames "asdf/" path)))
(when (probe-file asdf-path) asdf-path)))
(defun asdf-ros-search (def &aux (debug-print (sb-ext:posix-getenv "ROSLISP_LOAD_DEBUG")))
"An ASDF search method for ros packages. When *current-ros-package*
is a nonempty string, it uses rospack to generate the list of
depended-upon packages, with the current one at the front. It then
searches the asdf/ subdirectory of each package root in turn for the
package."
(if (and (stringp *current-ros-package*) (> (length *current-ros-package*) 0))
(let ((paths (asdf-paths-to-add *current-ros-package*)))
(when debug-print (format t "~&Current ros package is ~a. Searching for asdf system ~a in directories:~& ~a" *current-ros-package* def paths))
(dolist (p paths)
(let ((filename (merge-pathnames (make-pathname :name def :type "asd") p)))
(when (probe-file filename)
(when debug-print (format t "~& Found ~a" filename))
(return-from asdf-ros-search filename))))
(when debug-print (format t "~& Not found")))
(when debug-print (format t "~&asdf-ros-search not invoked since *current-ros-package* is ~a" *current-ros-package*))))
(asdf:initialize-source-registry
(let ((roslisp-package-directories (sb-posix:getenv "ROSLISP_PACKAGE_DIRECTORIES"))
(ros-package-path (sb-posix:getenv "ROS_PACKAGE_PATH"))
;; during the transition from asdf2 to asdf3 the utility function
;; 'split-string' moved from package 'asdf' to package 'uiop'.
;; Hence, the version-dependent function-call
(split-string-symbol
(if (asdf:version-satisfies (asdf:asdf-version) "3.0")
(intern "SPLIT-STRING" :uiop)
(intern "SPLIT-STRING" :asdf))))
`(:source-registry
,@(when roslisp-package-directories
(mapcan (lambda (path)
(when (and path (> (length path) 0))
`((:tree ,path))))
(funcall split-string-symbol roslisp-package-directories :separator '(#\:))))
,@(when ros-package-path
(mapcan (lambda (path)
(when (and path (> (length path) 0))
`((:tree ,path))))
(funcall split-string-symbol ros-package-path :separator '(#\:))))
;; NOTE(lorenz): this looks to me as sort of an ugly hack but we
;; should not break the user's source registry
;; configuration. Instead, we inherit the user's configuration if
;; it exists and just add our entries at the beginning.
,@(if (and (boundp 'asdf:*source-registry-parameter*)
(eq (car asdf:*source-registry-parameter*)
:source-registry))
(cdr asdf:*source-registry-parameter*)
(list :inherit-configuration)))))
(setq asdf:*system-definition-search-functions*
(append asdf:*system-definition-search-functions*
'(asdf-ros-search)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; top level
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defun load-manifest (package)
"Walks down the tree of dependencies of this ros package. Backtracks when it reaches a leaf or a package with no asdf/ subdirectory. Adds all the asdf directories it finds to the asdf:*central-registry*."
(cerror "continue" "Load manifest deprecated!")
(dolist (p (asdf-paths-to-add package))
(pushnew p asdf:*central-registry* :test #'equal)))
(defun load-system (package &optional (asdf-name package) force)
"Sets *CURRENT-ROS-PACKAGE* and performs an asdf load operation on `package'"
(let ((*current-ros-package* package))
(asdf:operate 'asdf:load-op asdf-name :force force)))
| 0 |
apollo_public_repos/apollo-platform/ros/roslisp | apollo_public_repos/apollo-platform/ros/roslisp/utils/queue.lisp | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Software License Agreement (BSD License)
;;
;; Copyright (c) 2008, Willow Garage, Inc.
;; 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 Willow Garage, Inc. nor the names
;; of its 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.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defpackage :roslisp-queue
(:documentation "A threadsafe implementation of queues")
(:export
:queue
:make-queue
:queue-empty
:enqueue
:queue-size
:dequeue
:dequeue-wait
:wakeup
:peek-front)
(:use :cl
:roslisp-utils
:roslisp-extended-reals
:sb-thread))
(in-package :roslisp-queue)
(defstruct (queue (:conc-name nil) (:constructor create-queue))
lock
read-cv
max-size
queue-size
head
tail)
(defun make-queue (&key (sequence nil) (max-size 'infty))
"make-queue &key (SEQUENCE nil) (MAX-SIZE 'infty)
Makes a queue out of SEQUENCE as if enqueueing the elements in sequence."
(assert (or (eql max-size 'infty) (< (length sequence) max-size)))
(let* ((head (etypecase sequence (list (copy-list sequence)) (vector (map 'list #'identity sequence))))
(tail (last head))
(queue
(create-queue :head head
:tail tail
:lock (make-mutex :name "queue lock")
:max-size max-size
:queue-size (length head)
:read-cv (make-waitqueue :name "queue reader waitqueue"))))
queue))
(defun queue-empty (queue)
"queue-empty QUEUE. Return t iff the queue has no elements."
(null (head queue)))
(defun enqueue (item q)
"enqueue ITEM QUEUE. Add ITEM to the end of the QUEUE. If any dequeue-wait calls are waiting, one of them will wake up. If MAX-SIZE is exceeded, dequeue until not. Return the number of dropped items."
(with-recursive-lock ((lock q))
(incf (queue-size q))
(let ((new-pair (list item))
(num-dropped 0))
(cond
((queue-empty q)
(setf (head q) (setf (tail q) new-pair))
(condition-notify (read-cv q) 1))
(t
(setf (tail q)
(setf (cdr (tail q))
new-pair))
(repeat (extmax 0 (ext- (queue-size q) (max-size q)))
(dequeue q)
(incf num-dropped))))
num-dropped)))
(defun dequeue (q)
"dequeue QUEUE. Return 1) the first item on the queue if it exists (in this case the item is removed from the queue) 2) t if the queue was nonempty, nil otherwise. See also dequeue-wait."
(with-recursive-lock ((lock q))
(decf (queue-size q))
(if (queue-empty q)
(values nil nil)
(multiple-value-prog1
(values (car (head q)) t)
(setf (head q) (cdr (head q)))))))
(defun dequeue-wait (q &key (allow-wakeup nil))
"dequeue-wait QUEUE &key (ALLOW-WAKEUP t). Sleep till QUEUE is nonempty, then return the first item and t, or wakeup is called on the queue, in which case return nil and nil. If there are multiple threads doing this, there is no guarantee about which enqueuing this one will wake up upon. However, the overall ordering of dequeued items will be FIFO. If wakeup is called when ALLOW-WAKEUP is nil, then an assert happens."
;; TODO wakeup isn't working
(with-recursive-lock ((lock q))
(loop
(if (queue-empty q)
(condition-wait (read-cv q) (lock q))
(multiple-value-bind (item exists) (dequeue q)
(if exists
(return (values item t))
(unless allow-wakeup
(assert nil nil "Thread woken up in call to dequeue-wait with allow-wakeup set to false"))))))))
(defun wakeup (q)
"Wakeup all dequeuers and tell them they aren't getting anything."
;; TODO wakeup isn't working
(with-recursive-lock ((lock q))
(condition-broadcast (read-cv q))))
(defun peek-front (q)
"peek-front QUEUE. Has the same return values as dequeue, but does not modify the queue."
(with-recursive-lock ((lock q))
(if (queue-empty q)
(values nil nil)
(car (head q)))))
(defmethod print-object ((q queue) str)
(with-recursive-lock ((lock q))
(print-unreadable-object (q str :type t :identity nil)
(format str "with elements ~a" (head q))))) | 0 |
apollo_public_repos/apollo-platform/ros/roslisp | apollo_public_repos/apollo-platform/ros/roslisp/utils/utils.lisp | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Software License Agreement (BSD License)
;;
;; Copyright (c) 2008, Willow Garage, Inc.
;; 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 Willow Garage, Inc. nor the names
;; of its 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.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defpackage roslisp-utils
(:use :cl :sb-thread)
(:export
:mvbind
:dbind
:bind-pprint-args
:force-format
:until
:while
:repeat
:unix-time
:loop-at-most-every
:spin-until
:with-parallel-thread
:every-nth-time
:hash-table-has-key
:pprint-hash
:do-hash
:tokens
:serialize-int
:deserialize-int
:serialize-string
:deserialize-string
:filter
:intern-compound-symbol
:encode-single-float-bits
:encode-double-float-bits
:decode-single-float-bits
:decode-double-float-bits))
(in-package :roslisp-utils)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Macros
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defmacro aif (test-form then-form &optional else-form)
`(let ((it ,test-form))
(if it ,then-form ,else-form)))
(defmacro dbind (pattern object &body body)
"abbreviation for destructuring-bind"
`(destructuring-bind ,pattern ,object ,@body))
(defmacro mvbind (vars form &body body)
"abbreviation for multiple-value-bind"
`(multiple-value-bind ,vars ,form ,@body))
(defmacro until (test &body body)
`(loop
(when ,test (return))
,@body))
(defmacro while (test &body body)
`(loop
(unless ,test (return))
,@body))
(defmacro bind-pprint-args ((str obj) args &body body)
"bind-pprint-args (STR OBJ) ARGS &rest BODY
STR, OBJ : unevaluated symbols
ARGS : a list (evaluated)
If ARGS has length 1, bind STR to t, OBJ to (FIRST ARGS). Otherwise, bind STR to (first args) and OBJ to (second args) ARGS. Then evaluate BDOY in this lexical context."
(let ((x (gensym)))
`(let ((,x ,args))
(condlet
(((= 1 (length ,x)) (,str t) (,obj (first ,x)))
(t (,str (first ,x)) (,obj (second ,x))))
,@body))))
(defmacro repeat (n &body body)
(let ((v (gensym)))
`(dotimes (,v ,n)
(declare (ignorable ,v))
,@body)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; condlet
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defmacro condlet (clauses &body body)
"condlet CLAUSES &rest BODY. CLAUSES is a list of which each member is a conditional binding or otherwise clause. There can be at most one otherwise clause and it must be the last clause. Each conditional binding is a list where the first element is a test and the remaining elements are the bindings to be made if the test succeeds. Each clause must bind the same set of variables. If one of the tests succeeds, the corresponding bindings are made, and the body evaluated. If none of the tests suceeds, the otherwise clause, if any, is evaluated instead of the body."
(labels ((condlet-clause (vars cl bodfn)
`(,(car cl) (let ,(condlet-binds vars cl)
(,bodfn ,@(mapcar #'cdr vars)))))
(condlet-binds (vars cl)
(mapcar #'(lambda (bindform)
(if (consp bindform)
(cons (cdr (assoc (car bindform) vars))
(cdr bindform))))
(cdr cl))))
(let* ((var-names (mapcar #'car (cdr (first clauses))))
(otherwise-clause? (eql (caar (last clauses)) 'otherwise))
(actual-clauses (if otherwise-clause? (butlast clauses) clauses)))
(assert (every (lambda (cl) (equal var-names (mapcar #'car (cdr cl))))
actual-clauses)
nil "All non-otherwise-clauses in condlet must have same variables.")
(let ((bodfn (gensym))
(vars (mapcar (lambda (v) (cons v (gensym)))
var-names)))
`(labels ((,bodfn ,(mapcar #'car vars)
,@body))
(cond
,@(mapcar (lambda (cl) (condlet-clause vars cl bodfn))
actual-clauses)
,@(when otherwise-clause? `((t (progn ,@(cdar (last clauses))))))))))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Symbols
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defun build-symbol-name (&rest args)
"build-symbol-name S1 ... Sn. Each Si is a string or symbol. Concatenate them into a single long string (which can then be turned into a symbol using intern or find-symbol."
(apply #'concatenate 'string (mapcar (lambda (x) (if (symbolp x) (symbol-name x) x)) args)))
(defun intern-compound-symbol (&rest args)
"intern-compound-symbol S1 ... Sn. Interns the result of build-symbol-name applied to the S."
(intern (apply #'build-symbol-name args)))
(defmacro with-struct ((name . fields) s &body body)
"with-struct (CONC-NAME . FIELDS) S &rest BODY
Example:
with-struct (foo- bar baz) s ...
is equivalent to
let ((bar (foo-bar s)) (baz (foo-baz s)))...
Note that despite the name, this is not like with-accessors or with-slots in that setf-ing bar above would not change the value of the corresponding slot in s."
(let ((gs (gensym)))
`(let ((,gs ,s))
(let ,(mapcar #'(lambda (f)
`(,f (,(intern-compound-symbol name f) ,gs)))
fields)
,@body))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Strings
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defun tokens (string &key (start 0) (separators (list #\space #\return #\linefeed #\tab)))
(if (= start (length string))
'()
(let ((p (position-if #'(lambda (char) (find char separators)) string :start start)))
(if p
(if (= p start)
(tokens string :start (1+ start) :separators separators)
(cons (subseq string start p)
(tokens string :start (1+ p) :separators separators)))
(list (subseq string start))))))
(defun deserialize-int (istream)
(let ((int 0))
(setf (ldb (byte 8 0) int) (read-byte istream))
(setf (ldb (byte 8 8) int) (read-byte istream))
(setf (ldb (byte 8 16) int) (read-byte istream))
(setf (ldb (byte 8 24) int) (read-byte istream))
int))
(defun deserialize-string (istream)
(let* ((__ros_str_len (deserialize-int istream))
(str (make-string __ros_str_len)))
(dotimes (i (length str) str)
do (setf (char str i) (code-char (read-byte istream))))))
(defun serialize-int (int ostream)
(write-byte (ldb (byte 8 0) int) ostream)
(write-byte (ldb (byte 8 8) int) ostream)
(write-byte (ldb (byte 8 16) int) ostream)
(write-byte (ldb (byte 8 24) int) ostream))
(defun serialize-string (string ostream)
(serialize-int (length string) ostream)
(map nil #'(lambda (c) (write-byte (char-code c) ostream)) string))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Time, event loops
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defun unix-time ()
"seconds since 00:00:00, January 1, 1970"
(- (get-universal-time) 2208988800))
(defun set-next-real-time-to-run (l time)
(setf (car l) time))
(defun time-to-run (l)
(car l))
(defun wait-until-ready (l)
;; Sbcl's sleep does not respect deadlines which causes severe
;; problems with CRAM. We don't use it directly. We explicitly take
;; into account deadlines.
(let* ((current-time (get-internal-real-time))
(time-to-run (time-to-run l))
(deadline-seconds sb-impl::*deadline-seconds*)
(stop-time (- time-to-run current-time)))
(when (< current-time time-to-run)
(tagbody
:retry
(cond ((or (not deadline-seconds)
(> deadline-seconds time-to-run))
(sleep (/ stop-time internal-time-units-per-second)))
(t
(sleep deadline-seconds)
(sb-sys:signal-deadline)
(setq deadline-seconds sb-impl::*deadline-seconds*)
(setf time-to-run (/ (float (- stop-time (get-internal-real-time)) 0.0d0)
(float internal-time-units-per-second 0.0d0)))
(when (plusp time-to-run)
(go :retry))))))))
(defun run-and-increment-delay (l d)
(let ((next-time (+ (time-to-run l) (* d internal-time-units-per-second))))
(wait-until-ready l)
(set-next-real-time-to-run l next-time)))
(defmacro loop-at-most-every (d &body body)
"Like loop, except ensures that BODY is executed at most once every D seconds (though possibly arbitrarily slower, if it takes a long time)"
(let ((delay (gensym))
(inc (gensym)))
`(let ((,delay (list (get-internal-real-time)))
(,inc ,d))
(loop
(run-and-increment-delay ,delay ,inc)
,@body))))
(defmacro spin-until (test inc &body body)
"Macro spin-until TEST INC &body BODY
or
spin-until TEST (INC TIMEOUT) &body BODY
Every INC seconds, evaluate the form TEST, and return its value it becomes true.
In the case with TIMEOUT specified, return two values: the first is the return value of TEST, and the second is T iff a timeout occurred (in which case the first value is meaningless)."
(condlet (((listp inc) (actual-inc (first inc)) (timeout (second inc)))
(t (actual-inc inc) (timeout nil)))
(let ((init-time (gensym)) (test-var (gensym)))
`(let ((,init-time (get-internal-real-time)))
(declare (ignorable ,init-time))
(loop-at-most-every ,actual-inc
(let ((,test-var ,test))
(when ,test-var (return ,test-var))
,(when timeout `(when (and ,timeout
(> (get-internal-real-time)
(+ ,init-time (* ,timeout ,internal-time-units-per-second))))
(return (values nil t))))
,@body))))))
(defmacro with-parallel-thread ((fn &optional name) &body body)
"with-parallel-thread (FN NAME) &body BODY
Start a thread that executes FN, named NAME (which defaults to the symbol FN). Then, in the current thread, execute BODY. After BODY exits, terminate the newly started thread as well (typically BODY will be a long-running loop).
If FN is a symbol, it's replaced by (function FN).
"
(unless name
(assert (symbolp fn) nil "If name is not provided to with-parallel-thread, the (unevaluated) fn argument should be a symbol")
(setq name `',fn))
(let ((thread (gensym))
(fn (if (symbolp fn) `#',fn fn)))
`(let ((,thread (sb-thread:make-thread ,fn :name ,name)))
(unwind-protect
(progn ,@body)
(sb-thread:terminate-thread ,thread)))))
(defvar *do-every-nth-table* (make-hash-table))
(defvar *do-every-nth-lock* (make-mutex :name "do-every-nth"))
(defun counter-value (id)
(with-mutex (*do-every-nth-lock*)
(let ((v (gethash id *do-every-nth-table*)))
(setf (gethash id *do-every-nth-table*) (if v (1+ v) 1)))))
(defmacro every-nth-time (n &body body)
(let ((id (gensym)))
`(when (zerop (mod (counter-value ',id) ,n))
,@body)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Miscellaneous
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defun force-format (str &rest args)
"force-format STREAM &rest ARGS. Like format, except flushes output on the stream."
(apply #'format str args)
(finish-output str))
(defparameter *standard-equality-tests* (list #'eq #'equal #'eql #'equalp 'eq 'eql 'equal 'equalp))
(defun is-standard-equality-test (f)
(member f *standard-equality-tests*))
(defun filter (f l)
(loop for x in l when (funcall f x) collect x)) | 0 |
apollo_public_repos/apollo-platform/ros/roslisp | apollo_public_repos/apollo-platform/ros/roslisp/utils/extended-reals.lisp | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Software License Agreement (BSD License)
;;
;; Copyright (c) 2008, Willow Garage, Inc.
;; 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 Willow Garage, Inc. nor the names
;; of its 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.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defpackage :roslisp-extended-reals
(:use :cl)
(:export
:infty :-infty
:ext+ :ext- :extmax))
(in-package :roslisp-extended-reals)
;(declaim (inline ext+ ext- ext>))
(defun ext+ (&rest args)
(reduce 'add-ext args))
(defun ext- (a &rest args)
(if args
(reduce 'subtract (cons a args))
(negate a)))
(defun extmax (&rest args)
(when args
(let ((m '-infty))
(dolist (x args m)
(when (ext> x m)
(setf m x))))))
(defun ext> (a b)
(cond
((eql a 'infty) (not (eql b 'infty)))
((eql b '-infty) (not (eql a '-infty)))
((and (numberp a) (numberp b)) (> a b))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Internal
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;(declaim (inline subtract negate))
(defun add-ext (a b)
(cond ((symbolp a)
(cond ((numberp b) a)
((eq a b) a)
(t (assert nil nil "Can't add infty and -infty"))))
((symbolp b) b)
(t (+ a b))))
(defun subtract (a b)
(cond ((symbolp a)
(cond ((numberp b) a)
((eq a b) (assert nil nil "Can't subtract infty or -infty from themselves."))
(t a)))
((eql b 'infty) '-infty)
((eql b '-infty) 'infty)
(t (- a b))))
(defun negate (a)
(case a
(infty '-infty)
(-infty 'infty)
(otherwise (- a))))
| 0 |
apollo_public_repos/apollo-platform/ros/roslisp | apollo_public_repos/apollo-platform/ros/roslisp/utils/hash-utils.lisp | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Software License Agreement (BSD License)
;;
;; Copyright (c) 2008, Willow Garage, Inc.
;; 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 Willow Garage, Inc. nor the names
;; of its 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.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(in-package roslisp-utils)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Hash tables with general hash functions
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defstruct gen-hash-table
table
hash-fn)
(defun make-hash-table* (&rest args &key (hash-fn #'identity hsupp) (test #'eql t-supp))
"make-hash-table* &rest ARGS
Portable version of hash tables with nonstandard hash functions
ARGS are the arguments to hash table, with two additional keywords.
HASH-FN : a function of one argument that returns an object. Defaults to #'identity.
TEST: a function of two arguments that must be one of #'equal, #'equalp, #'eql, or #'eq. Defaults to #'eql.
The assumption will be that given two objects X and Y that are 'the same', their images under HASH-FN are equal w.r.t TEST."
(assert (and args (is-standard-equality-test test)))
(flet ((remove-if-necessary (args supp key)
(if supp
(aif (position key args)
(if (zerop it)
(cddr args)
(progn (setf (cdr (nthcdr (1- it) args)) (nthcdr (+ it 2) args)) args))
args)
args)))
(let ((actual-args (copy-list args)))
(setf actual-args (remove-if-necessary actual-args hsupp ':hash-fn)
actual-args (remove-if-necessary actual-args t-supp ':test))
(make-gen-hash-table :table (apply #'make-hash-table :test test actual-args) :hash-fn hash-fn))))
(defgeneric gethash* (key ht)
(:documentation "gethash* KEY TABLE
To be used with tables created with make-hash-table*. Also works for regular hash tables.")
(:method (key (ht hash-table)) (gethash key ht))
(:method (key (ht gen-hash-table))
(with-struct (gen-hash-table- table hash-fn) ht
(let ((p (gethash (funcall hash-fn key) table)))
(if p
(values (cdr p) t)
(values nil nil))))))
(defgeneric sethash* (key ht val)
(:method (key (ht hash-table) val)
(setf (gethash key ht) val))
(:method (key (ht gen-hash-table) val)
(with-struct (gen-hash-table- table hash-fn) ht
(let* ((k (funcall hash-fn key))
(p (gethash k table)))
(if p
(setf (cdr p) val)
(setf (gethash k table) (cons key val)))
val))))
(defgeneric hash-table-test* (ht)
(:documentation "hash-table-test* GEN-HASH-TABLE. Works for generalized hash tables. Also, unlike hash-table-test, returns a function rather than a symbol.")
(:method ((ht hash-table)) (symbol-function (hash-table-test ht)))
(:method ((ht gen-hash-table)) (with-struct (gen-hash-table- table hash-fn) ht
(let ((test (symbol-function (hash-table-test table))))
#'(lambda (x y) (funcall test (funcall hash-fn x) (funcall hash-fn y)))))))
(defgeneric hash-table-count* (ht)
(:method ((ht hash-table))
(hash-table-count ht))
(:method ((ht gen-hash-table))
(hash-table-count (gen-hash-table-table ht))))
(defgeneric remhash* (key ht)
(:method (key (ht hash-table))
(remhash key ht))
(:method (key (ht gen-hash-table))
(with-struct (gen-hash-table- table hash-fn) ht
(remhash (funcall hash-fn key) table))))
(defgeneric hash-table-has-key (h k)
(:documentation "hash-table-has-key HASHTABLE X. Does the HASHTABLE contain (an item that satisfies the table's test together with) X? Works with generalized hash tables also.")
(:method ((h hash-table) x)
(mvbind (y pres)
(gethash x h)
(declare (ignore y))
pres))
(:method ((h gen-hash-table) x)
(hash-table-has-key (gen-hash-table-table h) (funcall (gen-hash-table-hash-fn h) x))))
(defsetf gethash* sethash*)
(defgeneric hash-keys (h)
(:documentation "hash-keys HASHTABLE. Return list of keys in some order. Works for generalized hash tables.")
(:method ((h hash-table))
(loop for k being each hash-key in h collecting k))
(:method ((h gen-hash-table))
(loop for v being each hash-value in (gen-hash-table-table h)
collect (car v))))
(defgeneric maphash* (fn h)
(:documentation "maphash* FN H. Like maphash* but works for generalized hash tables.")
(:method (fn (h hash-table))
(maphash fn h))
(:method (fn (h gen-hash-table))
(loop
for v being each hash-value in (gen-hash-table-table h)
do (funcall fn (car v) (cdr v)))))
(defmacro do-hash ((k v h) &rest body)
`(maphash* #'(lambda (,k ,v) (declare (ignorable ,k ,v)) ,@body) ,h))
| 0 |
apollo_public_repos/apollo-platform/ros/roslisp | apollo_public_repos/apollo-platform/ros/roslisp/utils/float-bytes.lisp | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Software License Agreement (BSD License)
;;
;; Copyright (c) 2008, Willow Garage, Inc.
;; 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 Willow Garage, Inc. nor the names
;; of its 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.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(in-package roslisp-utils)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Conversion functions for going to and from single and
;; double precision floating point values, assuming the
;; IEEE format (which one?).
;;
;; Code taken Peter Seibel's post to comp.lang.lisp:
;; http://groups.google.com/group/comp.lang.lisp/msg/11d500ef6e31a4ba
;; which presumably is in the public domain.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defun encode-float-bits (float sign-byte exponent-byte mantissa-byte bias)
(multiple-value-bind (original-mantissa original-exponent sign)
(integer-decode-float (float float 0d0))
(multiple-value-bind (mantissa exponent) (scale original-mantissa
original-exponent (1+ (byte-size mantissa-byte)))
(incf exponent (byte-size mantissa-byte))
(when (zerop mantissa)
(setf exponent (- bias)))
(when (<= exponent (- bias))
(setf (values mantissa exponent) (denormalize original-mantissa
original-exponent bias mantissa-byte)))
(incf exponent bias)
(when (> (integer-length exponent) (byte-size exponent-byte))
(setf mantissa 0 exponent (ldb (byte (byte-size exponent-byte) 0)
(lognot 0))))
(let ((result 0))
(setf (ldb sign-byte result) (if (plusp sign) 0 1))
(setf (ldb exponent-byte result) exponent)
(setf (ldb mantissa-byte result) mantissa)
result))))
(defun decode-float-bits (bits sign-byte exponent-byte mantissa-byte bias)
(let ((sign (if (zerop (ldb sign-byte bits)) 1 -1))
(exponent (ldb exponent-byte bits))
(mantissa (ldb mantissa-byte bits)))
(if (= (logcount (ldb exponent-byte bits)) (byte-size exponent-byte))
(if (zerop mantissa)
(if (plusp sign) 'positive-infinity 'negative-infinity)
'not-a-number)
(progn
(when (plusp exponent)
(incf mantissa (expt 2 (byte-size mantissa-byte))))
(if (zerop exponent)
(setf exponent (- 1 bias (byte-size mantissa-byte)))
(setf exponent (- (- exponent (byte-size mantissa-byte))
bias)))
(float (* sign (* mantissa (expt 2 exponent))) 0d0)))))
(defun scale-integer (value bits)
"Scale an integer value so it fits in the given number of bits."
(if (zerop value)
(values 0 0)
(let ((scale (- bits (integer-length value))))
(values (round (* value (expt 2 scale))) scale))))
(defun scale (mantissa exponent mantissa-bits)
"Scale an integer value so it fits in the given number of bits."
(multiple-value-bind (mantissa scale) (scale-integer mantissa
mantissa-bits)
(values mantissa (- exponent scale))))
(defun denormalize (mantissa exponent bias mantissa-byte)
(multiple-value-bind (mantissa exponent) (scale mantissa exponent
(byte-size mantissa-byte))
(incf exponent (byte-size mantissa-byte))
(values (ash mantissa (- exponent (1+ (- bias)))) (- bias))))
(defun encode-single-float-bits (float)
(let ((float (float float 0.0)))
(encode-float-bits float (byte 1 31) (byte 8 23) (byte 23 0) 127)))
(defun encode-double-float-bits (float)
(let ((float (float float 0.0d0)))
(encode-float-bits float (byte 1 63) (byte 11 52) (byte 52 0) 1023)))
(defun decode-single-float-bits (bits)
(decode-float-bits bits (byte 1 31) (byte 8 23) (byte 23 0) 127))
(defun decode-double-float-bits (bits)
(decode-float-bits bits (byte 1 63) (byte 11 52) (byte 52 0) 1023))
| 0 |
apollo_public_repos/apollo-platform/ros/roslisp | apollo_public_repos/apollo-platform/ros/roslisp/utils/roslisp-utils.asd |
(defsystem :roslisp-utils
:name "roslisp-utils"
:components
((:file "utils")
(:file "float-bytes" :depends-on ("utils"))
(:file "extended-reals")
(:file "queue" :depends-on ("utils" "extended-reals"))
(:file "hash-utils" :depends-on ("utils"))))
| 0 |
apollo_public_repos/apollo-platform/ros/roslisp | apollo_public_repos/apollo-platform/ros/roslisp/env-hooks/CMakeLists.txt | catkin_add_env_hooks(99.roslisp SHELLS sh DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR})
| 0 |
apollo_public_repos/apollo-platform/ros/roslisp | apollo_public_repos/apollo-platform/ros/roslisp/env-hooks/99.roslisp.sh | # generated from roslisp/env-hooks/99.roslisp.sh.in
# python function to generate ROSLISP package directories containing all devel spaces based on all workspaces
PYTHON_CODE_BUILD_ROSLISP_PACKAGE_DIRECTORIES=$(cat <<EOF
from __future__ import print_function
import os
env_name = 'CMAKE_PREFIX_PATH'
paths = [path for path in os.environ[env_name].split(os.pathsep)] if env_name in os.environ and os.environ[env_name] != '' else []
workspaces = [path for path in paths if os.path.exists(os.path.join(path, '.catkin'))]
paths = []
for workspace in workspaces:
filename = os.path.join(workspace, '.catkin')
data = ''
with open(filename) as f:
data = f.read()
if data:
paths.append(os.path.join(workspace, 'share', 'common-lisp'))
print(os.pathsep.join(paths))
EOF
)
export ROSLISP_PACKAGE_DIRECTORIES="`python -c \"$PYTHON_CODE_BUILD_ROSLISP_PACKAGE_DIRECTORIES\"`"
| 0 |
apollo_public_repos/apollo-platform/ros/roslisp | apollo_public_repos/apollo-platform/ros/roslisp/roslisp-msg-protocol/package.lisp | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Software License Agreement (BSD License)
;;
;; Copyright (c) 2008, Willow Garage, Inc.
;; 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 Willow Garage, Inc. nor the names
;; of its 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.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defpackage :roslisp-msg-protocol
(:use :cl)
(:export :ros-message
:serialize
:deserialize
:serialization-length
:md5sum
:ros-datatype
:message-definition
:service-request-type
:service-response-type
:symbol-codes
:symbol-code
:code-symbols
:code-symbol
:string-to-ros-msgtype-symbol
:ros-message-to-list
:list-to-ros-message
:msg-deprecation-warning))
| 0 |
apollo_public_repos/apollo-platform/ros/roslisp | apollo_public_repos/apollo-platform/ros/roslisp/roslisp-msg-protocol/roslisp-msg-protocol.asd |
(in-package :asdf)
(defsystem :roslisp-msg-protocol
:name "roslisp-msg"
:serial t
:components
((:file "package")
(:file "msg-protocol")))
| 0 |
apollo_public_repos/apollo-platform/ros/roslisp | apollo_public_repos/apollo-platform/ros/roslisp/roslisp-msg-protocol/msg-protocol.lisp | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Software License Agreement (BSD License)
;;
;; Copyright (c) 2008, Willow Garage, Inc.
;; 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 Willow Garage, Inc. nor the names
;; of its 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.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(in-package roslisp-msg-protocol)
(defclass ros-message () ())
(defgeneric serialize (msg str)
(:documentation "Serialize message object MSG onto stream STR."))
(defgeneric deserialize (msg str)
(:documentation "Deserialize from stream STR into message object MSG and also returns MSG. MSG may also be a symbol naming a message type, in which case a new object of that type is created and returned."))
(defgeneric serialization-length (msg)
(:documentation "Length of this message"))
(defgeneric md5sum (msg-type)
(:documentation "Return the md5 sum of this message type."))
(defgeneric ros-datatype (msg-type)
(:documentation "Return the datatype given a message type, service type, service request or response type, or topic name"))
(defgeneric message-definition (msg-type)
(:documentation "Return the definition of this message type"))
(defgeneric service-request-type (srv))
(defgeneric service-response-type (srv))
(defgeneric symbol-codes (msg-type)
(:documentation "Return an association list from symbols to numbers (the const declarations in the .msg file). `msg-type' is either a symbol naming the message class or an instance of the class."))
(defgeneric symbol-code (msg-type symbol)
(:documentation "symbol-code MSG-TYPE SYMBOL. Gets the value of a message-specific constant declared in a msg file. The first argument is either a symbol naming the message class, or an instance of the class, and the second argument is the keyword symbol corresponding to the constant name.
For example, to get the value of the DEBUG constant from Log.msg, use (symbol-code '<Log> :debug)."))
(defgeneric code-symbols (msg-type code)
(:documentation "Retrieves the list of symbol-code associations which contain
`code' within `msg-type'. `msg-type' is a either a symbol naming the message class
or an instance of that class. `code' is an integer.
For example, if my_msgs/Log.msg has defined the constants DEBUG=1, WARN=2, ERROR=1,
you can get all code-symbol associations with constant code 1 with:
ROSLISP-MSG-PROTOCOL> (code-symbols 'my_msgs-msg:log 1)
((:DEBUG . 1) (:ERROR . 1))"))
(defgeneric code-symbol (msg-type code)
(:documentation "Retrieves the first symbol associated with the constant `code'
in the symbol codes of `msg-type'. If no such association exists, it returns NIL.
`msg-type' is a either a symbol naming the message class or an instance of that
class. `code' is an integer.
For example, if my_msgs/Log.msg has defined the constants DEBUG=1, WARN=2, ERROR=1, you
can get the first symbol associated with the constant code 1 with:
ROSLISP-MSG-PROTOCOL> (code-symbol 'my_msgs-msg:log 1)
:DEBUG"))
(defgeneric ros-message-to-list (msg)
(:documentation "Return a structured list representation of the message. For example, say message type foo has a float field x equal to 42, and a field y which is itself a message of type bar, which has a single field z=24. This function would then return the structured list '(foo (:x . 42.0) (:y . (bar (:z . 24)))).
The return value can be passed to list-to-ros-message to retrieve an equivalent message to the original.
As a base case, non-ros messages just return themselves."))
(defgeneric list-to-ros-message (l))
(defvar *print-deprecation-warnings* t)
(defvar *warnings-table* (make-hash-table :test 'eq))
(defmacro msg-deprecation-warning (str &rest args)
(let ((x (gensym)))
`(unless (gethash ',x *warnings-table*)
(when *print-deprecation-warnings* (warn ,str ,@args))
(setf (gethash ',x *warnings-table*) t)
)
))
;; datatype functions for string arguments
(defun string-to-ros-msgtype-symbol (msg-type)
"returns the symbol of a know ros messagetype if the string matches the the name case sensitively, else throws error"
(assert (= 1 (count #\/ msg-type)) () "Too few or too many slashes in \"~a\"" msg-type)
(let* ((slashpos (position #\/ msg-type))
(type-symbol (find-symbol (string-upcase (subseq msg-type (1+ slashpos) (length msg-type)))
(string-upcase (concatenate 'string (subseq msg-type 0 slashpos) "-MSG"))))
(truename (unless (null type-symbol) (ros-datatype type-symbol))))
(when (null type-symbol) (error "No datatype ~a known" msg-type))
(unless (string= truename msg-type) (error "Case mismatch for message type ~a, did you mean ~a?" msg-type truename))
type-symbol)) | 0 |
apollo_public_repos/apollo-platform/ros/roslisp | apollo_public_repos/apollo-platform/ros/roslisp/scripts/make-roslisp-exec.lisp | (require :asdf)
(in-package :cl-user)
(flet ((failure-quit (&key exit-code)
(if (find-symbol "EXIT" 'sb-ext)
(funcall (intern "EXIT" 'sb-ext) :code exit-code)
(funcall (intern "QUIT" 'sb-ext) :unix-status exit-code))))
(let ((p (sb-ext:posix-getenv "ROS_ROOT")))
(unless p (error "ROS_ROOT not set"))
(let ((roslisp-path (merge-pathnames (make-pathname :directory '(:relative "asdf"))
(ros-load:ros-package-path "roslisp")))
(output-filename (pathname (fifth sb-ext:*posix-argv*))))
(unless (sb-ext:posix-getenv "ROS_DEBBUILD")
(handler-case
(let ((ros-load:*current-ros-package* (second sb-ext:*posix-argv*)))
(asdf:operate 'asdf:compile-op (third sb-ext:*posix-argv*)))
(error (e)
(format *error-output* "Compilation failed due to condition: ~a~&" e)
(failure-quit :exit-code 1))))
(with-open-file (strm (ensure-directories-exist output-filename)
:if-exists :supersede :direction :output)
(let ((*standard-output* strm))
(pprint '(require :asdf))
(pprint '(defmethod asdf:perform :around ((o asdf:load-op)
(c asdf:cl-source-file))
(handler-case (call-next-method o c)
;; If a fasl was stale, try to recompile and load (once).
(sb-ext:invalid-fasl ()
(asdf:perform (make-instance 'asdf:compile-op) c)
(call-next-method)))))
(pprint '(push :roslisp-standalone-executable *features*))
(pprint '(declaim (sb-ext:muffle-conditions sb-ext:compiler-note)))
(pprint `(push ,roslisp-path asdf:*central-registry*))
(pprint '(defun roslisp-debugger-hook (condition me)
(declare (ignore me))
(flet ((failure-quit (&key abort-p)
(if (find-symbol "EXIT" 'sb-ext)
(funcall (intern "EXIT" 'sb-ext)
:code 1 :abort abort-p)
(funcall (intern "QUIT" 'sb-ext)
:unix-status 1 :recklessly-p abort-p))))
(handler-case
(progn
(format *error-output*
"~&Roslisp exiting due to condition: ~a~&" condition)
(finish-output *error-output*)
(failure-quit))
(condition ()
(failure-quit :abort-p t))))))
(pprint '(unless (let ((v (sb-ext:posix-getenv "ROSLISP_BACKTRACE_ON_ERRORS")))
(and (stringp v) (> (length v) 0)))
(setq sb-ext:*invoke-debugger-hook* #'roslisp-debugger-hook)))
(pprint `(handler-bind ((style-warning #'muffle-warning)
(warning #'print))
(asdf:operate 'asdf:load-op :ros-load-manifest :verbose nil)
(setf (symbol-value (intern "*CURRENT-ROS-PACKAGE*" :ros-load))
,(second sb-ext:*posix-argv*))
(let ((*standard-output* (make-broadcast-stream))
(sys ,(third sb-ext:*posix-argv*)))
(handler-case (asdf:operate 'asdf:load-op sys :verbose nil)
(asdf:missing-component (c)
(error "Couldn't find asdf system (filename ~a.asd and system name ~a) or some dependency. Original condition was ~a."
sys sys c))))
(load (merge-pathnames
(make-pathname :name ,(format nil "~a-init.lisp"
(pathname-name output-filename))
:directory '(:relative "roslisp"
,(second sb-ext:*posix-argv*)))
(funcall (symbol-function (intern "ROS-HOME" :ros-load))))
:if-does-not-exist nil)
(funcall (symbol-function (read-from-string ,(fourth sb-ext:*posix-argv*))))
(if (find-symbol "EXIT" 'sb-ext)
(funcall (intern "EXIT" 'sb-ext))
(funcall (intern "QUIT" 'sb-ext))))))))
(failure-quit :exit-code 0)))
| 0 |
apollo_public_repos/apollo-platform/ros/roslisp | apollo_public_repos/apollo-platform/ros/roslisp/scripts/run-roslisp-script.sh | #!/usr/bin/env sh
"true";exec /usr/bin/env /usr/bin/sbcl --noinform --end-runtime-options --noprint --no-userinit --disable-debugger --script "$0" "$@"
;; This LISP script can be used to launch LISP scripts that depend on ros functinoality.
;; To use it make the following the first two lines of your script:
;;
;; #!/usr/bin/env sh
;; "true";exec /usr/bin/env rosrun roslisp run-roslisp-script.sh --script "$0" "$@"
;;
;; You can then load asdf systems from ROS (like roslisp) using:
;; (ros-load:load-system "roslisp" "roslisp")
;;
;; This script initializes ros lookup of packages, and wraps SBCL to suppress unwanted output for scripts
(REQUIRE :ASDF)
(labels ((get-roslisp-path ()
;; calls rospack to find path to roslisp
(let ((rospack-process
(run-program "rospack" '("find" "roslisp")
:search t
:output :stream)))
(when rospack-process
(unwind-protect
(with-open-stream (o (process-output rospack-process))
(concatenate 'string (car (loop
for line := (read-line o nil nil)
while line
collect line)) "/load-manifest/"))
(process-close rospack-process)))))
(load-ros-lookup ()
;; make sure roslisp is in asdf central registry
(PUSH (get-roslisp-path) ASDF:*CENTRAL-REGISTRY*)
;; load ros-load-manifest, defining e.g. "ros-load:load-system"
(ASDF:OPERATE 'ASDF:LOAD-OP :ROS-LOAD-MANIFEST :VERBOSE NIL)))
(load-ros-lookup))
(PUSH :ROSLISP-STANDALONE-EXECUTABLE *FEATURES*)
;; handle conditions
(LABELS ((ROSLISP-DEBUGGER-HOOK (CONDITION ME)
(DECLARE (IGNORE ME))
(FLET ((FAILURE-QUIT (&KEY RECKLESSLY-P)
(QUIT :UNIX-STATUS 1 :RECKLESSLY-P RECKLESSLY-P)))
(HANDLER-CASE
(PROGN
(FORMAT *ERROR-OUTPUT* "~&Roslisp exiting due to condition: ~a~&"
CONDITION)
(FINISH-OUTPUT *ERROR-OUTPUT*)
(FAILURE-QUIT))
(CONDITION NIL (FAILURE-QUIT :RECKLESSLY-P T))))))
(UNLESS
(LET ((V (POSIX-GETENV "ROSLISP_BACKTRACE_ON_ERRORS")))
(AND (STRINGP V) (> (LENGTH V) 0)))
(SETQ *INVOKE-DEBUGGER-HOOK* #'ROSLISP-DEBUGGER-HOOK)))
;; load file
(let ((filename (third sb-ext:*posix-argv*)))
(let ((stream (open filename :direction :input))
;; remove artificial arguments
(sb-ext::*posix-argv* (cddr sb-ext::*posix-argv*)))
(unwind-protect
(progn
;; ignore shebang line
(read-line stream)
(load stream))
(close stream))))
| 0 |
apollo_public_repos/apollo-platform/ros/roslisp | apollo_public_repos/apollo-platform/ros/roslisp/scripts/test-genmsg-lisp | #!/usr/bin/env bash
set -e
if (( $# == 2 ))
then
PKG=`rospack find $1`
FILENAME=$PKG/msg/$2.msg
rosrun genmsg_cpp genmsg_lisp $FILENAME
rosrun roslisp genmsg_lisp.py $FILENAME
NAME="$2.lisp"
echo " $NAME"
diff -w $PKG/msg/lisp/$1/$NAME $PKG/msg_gen/lisp/$NAME | head -n 50
NAME="_package_$2.lisp"
echo " $NAME"
diff -w $PKG/msg/lisp/$1/$NAME $PKG/msg_gen/lisp/$NAME | head -n 50
elif (( $# == 1 ))
then
for p in `rosmsg package $1`
do args=`echo $p | tr "/" " "`
echo "$p"
$0 $args
echo "--------------------------------------"
done
PKG=`rospack find $1`
echo "_package.lisp"
diff -w $PKG/msg/lisp/$1/_package.lisp $PKG/msg_gen/lisp/_package.lisp | head -n 50
NAME="$1-msg.asd"
echo "$NAME"
diff -w $PKG/msg/lisp/$1/$NAME $PKG/msg_gen/lisp/$NAME | head -n 50
else
echo "Usage: test-genmsg-lisp PKG MSG or test-genmsg-lisp PKG"
exit 1
fi
| 0 |
apollo_public_repos/apollo-platform/ros/roslisp | apollo_public_repos/apollo-platform/ros/roslisp/scripts/roslisp-sbcl-init | ;; Initialization for sbcl when compiling roslisp
(require :asdf)
;;; Handle recompilation of fasls with wrong version.
(defmethod asdf:perform :around ((o asdf:load-op)
(c asdf:cl-source-file))
(handler-case (call-next-method o c)
;; If a fasl was stale, try to recompile and load (once).
(sb-ext:invalid-fasl ()
(asdf:perform (make-instance 'asdf:compile-op) c)
(call-next-method))))
;;; Add appropriate paths for asdf to look for ros-load-manifest. We
;;; use the path of this file as base.
(unless (asdf:find-system :ros-load-manifest nil)
(unless *load-truename*
(error 'simple-error
:format-control "*LOAD-TRUENAME* not bound. This script needs to be loaded with the --load parameter."))
(let ((load-manifest-directory (parse-namestring
(concatenate 'string
(directory-namestring *load-truename*)
"../load-manifest/"))))
(push load-manifest-directory asdf:*central-registry*)))
(asdf:operate 'asdf:load-op :ros-load-manifest)
| 0 |
apollo_public_repos/apollo-platform/ros/roslisp | apollo_public_repos/apollo-platform/ros/roslisp/scripts/compile_load_manifest | #!/usr/bin/env sh
SBCL_CMD="/usr/bin/env sbcl"
ROSLISP_PATH=`rospack find roslisp`
if [ -z "$ROSLISP_PATH" ]; then
echo "roslisp not found"
exit 1
fi
$SBCL_CMD --noinform --end-runtime-options --noprint --non-interactive \
--load $ROSLISP_PATH/scripts/roslisp-sbcl-init
| 0 |
apollo_public_repos/apollo-platform/ros/roslisp | apollo_public_repos/apollo-platform/ros/roslisp/scripts/make_exe_script | #!/usr/bin/env sh
ROSLISP_PATH=`rospack find roslisp`
if [ -z "$ROSLISP_PATH" ]; then
echo "roslisp not found"
exit 1
fi
if [ $# = 4 ]; then
pkg=$1
system=$2
entry=$3
output=$4
cat > $output <<EOF
#!/usr/bin/env sh
"true"; exec /usr/bin/env sbcl --noinform --load $ROSLISP_PATH/scripts/roslisp-sbcl-init --script "\$0" "\$@"
(ros-load:load-system "${pkg}" "${system}")
(${entry})
EOF
chmod a+x $output
else
echo "Usage: make_node_exec <pkg> <system> <entry> <output>"
exit 1
fi
| 0 |
apollo_public_repos/apollo-platform/ros/roslisp | apollo_public_repos/apollo-platform/ros/roslisp/scripts/make_roslisp_image | #!/bin/bash
# make-roslisp-image IMAGE_NAME
# Creates or overwrites a file IMAGE_NAME containing the Lisp image that includes Roslisp
# Will be used as an intermediate file when making individual executables for ROS nodes
if [[ $# == 1 ]]; then
# Force certain files to be recompiled
touch `rospack find roslisp`/msg.lisp
touch `rospack find roslisp`/utils/hash-utils.lisp
sbcl --noinform --userinit "`rospack find roslisp`/scripts/roslisp-sbcl-init" --eval "(setf sb-ext:*invoke-debugger-hook* #'(lambda (a b) (declare (ignore b)) (format t \"Roslisp compilation dying due to error ~a\" a) (sb-ext:quit :unix-status 70)))" --eval "(handler-bind ((warning #'(lambda (c) (format t \"~&Ignoring warning ~a\" c) (muffle-warning)))) (asdf:operate 'asdf:load-op ':roslisp))" --eval "(setf sb-ext:*invoke-debugger-hook* #'roslisp:standalone-exec-debug-hook roslisp:*running-from-command-line* t)" --eval "(sb-ext:save-lisp-and-die \"$1\")"
touch `rospack find roslisp`/msg.lisp
touch `rospack find roslisp`/utils/hash-utils.lisp
else
echo "Usage: make-roslisp-image IMAGE_NAME"
fi | 0 |
apollo_public_repos/apollo-platform/ros/roslisp | apollo_public_repos/apollo-platform/ros/roslisp/scripts/test-gensrv-lisp | #!/usr/bin/env bash
set -e
if (( $# == 2 ))
then
PKG=`rospack find $1`
FILENAME=$PKG/srv/$2.srv
rosrun genmsg_cpp gensrv_lisp $FILENAME
rosrun roslisp genmsg_lisp.py $FILENAME
NAME="$2.lisp"
echo " $NAME"
diff -w $PKG/srv/lisp/$1/$NAME $PKG/srv_gen/lisp/$NAME | head -n 50
NAME="_package_$2.lisp"
echo " $NAME"
diff -w $PKG/srv/lisp/$1/$NAME $PKG/srv_gen/lisp/$NAME | head -n 50
elif (( $# == 1 ))
then
for p in `rossrv package $1`
do args=`echo $p | tr "/" " "`
echo "$p"
$0 $args
echo "--------------------------------------"
done
PKG=`rospack find $1`
echo "_package.lisp"
diff -w $PKG/srv/lisp/$1/_package.lisp $PKG/srv_gen/lisp/_package.lisp | head -n 50
NAME="$1-srv.asd"
echo "$NAME"
diff -w $PKG/srv/lisp/$1/$NAME $PKG/srv_gen/lisp/$NAME | head -n 50
else
echo "Usage: test-gensrv-lisp PKG SRV or test-gensrv-lisp PKG"
exit 1
fi
| 0 |
apollo_public_repos/apollo-platform/ros/roslisp | apollo_public_repos/apollo-platform/ros/roslisp/scripts/make_node_exec | #!/usr/bin/env sh
SBCL_CMD="/usr/bin/env sbcl"
ROSLISP_PATH=`rospack find roslisp`
if [ -z "$ROSLISP_PATH" ]; then
echo "roslisp not found"
exit 1
fi
if [ $# = 4 ]; then
pkg=$1
system=$2
entry=$3
output=$4
echo "Generating Lisp executable."
$SBCL_CMD --noinform --end-runtime-options --noprint --non-interactive \
--load $ROSLISP_PATH/scripts/roslisp-sbcl-init \
--load $ROSLISP_PATH/scripts/make-roslisp-exec.lisp \
$pkg $system $entry $output.lisp \
--script \
|| exit $?
cat > $output <<EOF
#!/usr/bin/env sh
SBCL_CMD="/usr/bin/env sbcl"
ROSLISP_PATH=\`rospack find roslisp\`
if [ -z "\$ROSLISP_PATH" ]; then
echo "roslisp not found"
exit 1
fi
ROSLISP_CURRENT_PACKAGE=$pkg
$SBCL_CMD --noinform --end-runtime-options --noprint --no-userinit --disable-debugger --load \$ROSLISP_PATH/scripts/roslisp-sbcl-init --load $output.lisp --end-toplevel-options \$*
EOF
chmod a+x $output
else
echo "Usage: make_node_exec <pkg> <system> <entry> <output>"
exit 1
fi
| 0 |
apollo_public_repos/apollo-platform/ros/roslisp | apollo_public_repos/apollo-platform/ros/roslisp/s-xml-rpc/ChangeLog | 2004-06-17 Rudi Schlatte <[email protected]>
* src/package.lisp: Add system.getCapabilities.
* src/extensions.lisp: Create, move server extensions from
xml-rpc.lisp here.
(do-one-multicall): Raise standard fault codes.
(|system.getCapabilities|): Implement.
* src/xml-rpc.lisp: Remove server extensions.
(encode-xml-rpc-value): Encode symbols as strings
(execute-xml-rpc-call, handle-xml-rpc-call): Raise standard fault
codes.
2004-06-13 Rudi Schlatte <[email protected]>
* src/xml-rpc.lisp (xml-literal): new datatype for unescaped
strings (used by system.multicall to pass back encoded fault structs)
(encode-xml-rpc-value): handle it.
(encode-xml-rpc-fault-value, encode-xml-rpc-fault): separate
encoding of fault and methodResponse for system.multicall
(do-one-multicall, |system.multicall|): Implement system.multicall.
* src/package.lisp (s-xml-rpc-exports): New package -- don't
export the whole common-lisp package by default ;)
* src/xml-rpc.lisp (*xml-rpc-package*): ... use it.
* src/xml-rpc.lisp (|system.listMethods|)
(|system.methodSignature|, |system.methodHelp|): Added
introspection methods, to be imported in *xml-rpc-package*.
* src/package.lisp (s-xml-rpc): ... export them, and also
|system.multicall|
* src/xml-rpc.lisp: Some indentation frobs.
| 0 |
apollo_public_repos/apollo-platform/ros/roslisp | apollo_public_repos/apollo-platform/ros/roslisp/s-xml-rpc/Makefile | default:
@echo Possible targets:
@echo clean-openmcl --- remove all '*.dfsl' recursively
@echo clean-lw --- remove all '*.nfasl' recursively
@echo clean-emacs --- remove all '*~' recursively
@echo clean --- all of the above
clean-openmcl:
find . -name "*.dfsl" | xargs rm
clean-lw:
find . -name "*.nfasl" | xargs rm
clean-emacs:
find . -name "*~" | xargs rm
clean: clean-openmcl clean-lw clean-emacs
#
# This can obviously only be done by a specific person in a very specific context ;-)
#
PRJ=s-xml-rpc
ACCOUNT=scaekenberghe
CVSRT=:ext:$(ACCOUNT)@common-lisp.net:/project/$(PRJ)/cvsroot
release:
rm -rf /tmp/$(PRJ) /tmp/public_html /tmp/$(PRJ).tgz /tmp/$(PRJ).tgz.asc
cd /tmp; cvs -d$(CVSRT) export -r HEAD $(PRJ); cvs -d$(CVSRT) export -r HEAD public_html
mv /tmp/public_html /tmp/$(PRJ)/doc
cd /tmp; gnutar cvfz $(PRJ).tgz $(PRJ); gpg -a -b $(PRJ).tgz
scp /tmp/$(PRJ).tgz $(ACCOUNT)@common-lisp.net:/project/$(PRJ)/public_html
scp /tmp/$(PRJ).tgz.asc $(ACCOUNT)@common-lisp.net:/project/$(PRJ)/public_html
| 0 |
apollo_public_repos/apollo-platform/ros/roslisp | apollo_public_repos/apollo-platform/ros/roslisp/s-xml-rpc/s-xml-rpc.asd | ;;;; -*- Mode: LISP -*-
;;;;
;;;; $Id: s-xml-rpc.asd,v 1.2 2004/06/17 19:43:11 rschlatte Exp $
;;;;
;;;; The S-XML-RPC ASDF system definition
;;;;
;;;; Copyright (C) 2002, 2004 Sven Van Caekenberghe, Beta Nine BVBA.
;;;;
;;;; You are granted the rights to distribute and use this software
;;;; as governed by the terms of the Lisp Lesser General Public License
;;;; (http://opensource.franz.com/preamble.html), also known as the LLGPL.
(in-package :asdf)
(defsystem :s-xml-rpc
:name "S-XML-RPC"
:author "Sven Van Caekenberghe <[email protected]>"
:version "7"
:maintainer "Sven Van Caekenberghe <[email protected]>, Brian Mastenbrook <>, Rudi Schlatte <>"
:licence "Lesser Lisp General Public License (LLGPL)"
:description "Common Lisp XML-RPC Package"
:long-description "s-xml-rpc is a Common Lisp implementation of the XML-RPC procotol for both client and server"
:components
((:module
:src
:components ((:file "base64")
(:file "package" :depends-on ("base64"))
(:file "sysdeps" :depends-on ("package"))
(:file "xml-rpc" :depends-on ("package" "sysdeps" "base64"))
(:file "extensions" :depends-on ("package" "xml-rpc")))))
:depends-on (:s-xml #+sbcl :sb-bsd-sockets))
;;;; eof
| 0 |
apollo_public_repos/apollo-platform/ros/roslisp/s-xml-rpc | apollo_public_repos/apollo-platform/ros/roslisp/s-xml-rpc/test/test.b64 | R0lGODlhNABYAMQAAP////vi5etreuM0SN8ZL+dOYPCIk+56hPi/xPGapPjP1N4EGvHr9PSstMzI6riw4IY+kHsie3lvyVtMu0Y4tN3b8Y+CzX1ast2ftskNNNBdfqGb2so0WeHL4E8spLA0aiH5BAAAAAAALAAAAAA0AFgAQAX/ICCOZGmeaKqeBUEc5WAATbECQnCfyiAWsFIBgfMJFoTOYcAQERYN0SK4KxEUp4FPC/ABXN/oKOCtmh0OxGPj+UAgHmKhIZiZHJLJhMKXNKsMFQAMFnp6EogWFxEWOAsCgw4VfyN5IhKNABMPZhAUe3yhoYiYFmsWiISYlCoMeaJ8ehR5hoektLCjEhCcJGgQqSkKC1BmxscBxEQkBAlOxSMDCzY/ZQAICyPEOwnbCgXgcyQCBeQFWCIHVDXhJN/hkMc0DR0iA80oPXbyI+Vd6CO+RdOxjAWVYz367bPXzciVHjKwGCAwg4AOfiUOEBgg4ICAe08WYCFgQ0aKBtaM/xWSEMuQKA+1WHrIhYpCJgB4KDzYA4BPFQejLAgdSvSB0QoOHgCT4GAEKqSfUuT8ZIHVCAYbWOaaQErSiqoYw4oVkWxBwRETt41RW2KBNWluq5QteCAbiQJxSRATQIDVRisLnJmQ5sLi2MNhP24cUIDxRcRjCAsG0HgHnbEaFRAwAURExxsJHh8jB2CJiQZBOALokHIEgXiqjQks3frcFyRdcKfzonGBaGMDxFzTIgDBMBd4GVN7sQSdAWpiuZQIsJHkCwNQqKOgCBmF2wZu5xj4XUL4MUJcMTlowmANhAgXhGoIIMA5NUKwQIWCcANNIkEMMPDBAWgUmAEGIgwDQ/97u2ByCQVNTdCIBRTssEEfVpUWjwgMpIHKTQCg0oQnguhhBgObPCBBLys4gIoEJVTA0gSCGIPUegBolV8tomwSVgUTiEBhehZsgMB6AZ4Q4JJLcjhIh1ntAeMITamw0ycSbDDJHx0aRdSLuPSIyQM1rnAEMcRc0R0/c7EADUppLgRAAoRtuE0ABvBF3lpmlTCMI9A5shkz1vB1G0AqtNkPEoWx9cwMGllRWEitmTCMSAlCw4ymAFxaz6KWOuqmnGuWaqqpHQTw6almbmSAAqoG8M0AB3XXA0mC/bWCbYjxNQ0JdHY6WQoJZDgaYymhJEICgaKQg1hXgDMYOuKooMD/hvJQx4BmlsYT7GyWGoZRcJRhm44z3HaaFzOD4mXeDglRVitlWMjgghYgJaCZuE8gWkW86ZJgxCOA0iBtp1royk8Zmi1UGAAT4WmSZwREYUClZhzQ7MX3MDqFri4kIK7BY12cxRW+4dNCuSaQNpYW74KHhALgbXawpQP4ixGzWoiD3UZ9HkAqCUKfysA9zx1AJznvrlkBmCuu10AGCFSgDg5Y0CFaIbLAAuIJF86CyAZGbWDKAxwcoEACFbzhgZEWwHEBV0H5oSNLX5eAipSkcDWBB3MjsocHeUhwwQdEoFgmABX4ZCJLrSylCwQfoFHB5RpwIAJ4BehIwQY49tTI/wMVArDTDu1JKRSL2GBBXdMkFNIE5JpMeQOKNYl9i+CFk9KLJIQ0gUpTURmTR+67J5/IA2iQQEhOthvjgH5crT7UUrZsMMIDNa04Vt9i75Ee+KNUiRF6sTDFIfU8toTIWUqm0PgmE5i/QpLyXGh/Ja/4AQHUsciFAGExEzGBhUOIMEF7JDfAUMykgFv5RB/CZ4sHGAsFeABFTJSXvCKFjlUgnA5cMBbCUPXpBBtCQB3yNCwa1OFqIkAADK5lgAOsygQdUMYJiPGWX5mgLo/BRmACooIcnpAZvjLPE2rVjVUxoGKiSoER4beysrQFU2TBohNgUBcSkmCK7piCAS62LlR12QUAC1hIC8aIHU6hAIzaGNYThtWNzbwGWGc04w0uVRAwhDGPufFhplqYnBUIMQB4WiKiREYMG2pjUJ0607A60MaJneBnJayCbjK5HR5y8pNiCQEAOw== | 0 |