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/ros_comm
apollo_public_repos/apollo-platform/ros/ros_comm/xmlrpcpp/package.xml
<package> <name>xmlrpcpp</name> <version>1.11.21</version> <description> XmlRpc++ is a C++ implementation of the XML-RPC protocol. This version is heavily modified from the package available on SourceForge in order to support roscpp's threading model. As such, we are maintaining our own fork. </description> <maintainer email="dthomas@osrfoundation.org">Dirk Thomas</maintainer> <license>LGPL-2.1</license> <url>http://xmlrpcpp.sourceforge.net</url> <author>Chris Morley</author> <author>Konstantin Pilipchuk</author> <author>Morgan Quigley</author> <buildtool_depend>catkin</buildtool_depend> <build_depend>cpp_common</build_depend> <run_depend>cpp_common</run_depend> <export> <rosdoc external="http://xmlrpcpp.sourceforge.net/doc/hierarchy.html"/> </export> </package>
0
apollo_public_repos/apollo-platform/ros/ros_comm
apollo_public_repos/apollo-platform/ros/ros_comm/xmlrpcpp/COPYING
GNU LESSER GENERAL PUBLIC LICENSE Version 2.1, February 1999 Copyright (C) 1991, 1999 Free Software Foundation, Inc. 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. [This is the first released version of the Lesser GPL. It also counts as the successor of the GNU Library Public License, version 2, hence the version number 2.1.] Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public Licenses are intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This license, the Lesser General Public License, applies to some specially designated software packages--typically libraries--of the Free Software Foundation and other authors who decide to use it. You can use it too, but we suggest you first think carefully about whether this license or the ordinary General Public License is the better strategy to use in any particular case, based on the explanations below. When we speak of free software, we are referring to freedom of use, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish); that you receive source code or can get it if you want it; that you can change the software and use pieces of it in new free programs; and that you are informed that you can do these things. To protect your rights, we need to make restrictions that forbid distributors to deny you these rights or to ask you to surrender these rights. These restrictions translate to certain responsibilities for you if you distribute copies of the library or if you modify it. For example, if you distribute copies of the library, whether gratis or for a fee, you must give the recipients all the rights that we gave you. You must make sure that they, too, receive or can get the source code. If you link other code with the library, you must provide complete object files to the recipients, so that they can relink them with the library after making changes to the library and recompiling it. And you must show them these terms so they know their rights. We protect your rights with a two-step method: (1) we copyright the library, and (2) we offer you this license, which gives you legal permission to copy, distribute and/or modify the library. To protect each distributor, we want to make it very clear that there is no warranty for the free library. Also, if the library is modified by someone else and passed on, the recipients should know that what they have is not the original version, so that the original author's reputation will not be affected by problems that might be introduced by others. Finally, software patents pose a constant threat to the existence of any free program. We wish to make sure that a company cannot effectively restrict the users of a free program by obtaining a restrictive license from a patent holder. Therefore, we insist that any patent license obtained for a version of the library must be consistent with the full freedom of use specified in this license. Most GNU software, including some libraries, is covered by the ordinary GNU General Public License. This license, the GNU Lesser General Public License, applies to certain designated libraries, and is quite different from the ordinary General Public License. We use this license for certain libraries in order to permit linking those libraries into non-free programs. When a program is linked with a library, whether statically or using a shared library, the combination of the two is legally speaking a combined work, a derivative of the original library. The ordinary General Public License therefore permits such linking only if the entire combination fits its criteria of freedom. The Lesser General Public License permits more lax criteria for linking other code with the library. We call this license the "Lesser" General Public License because it does Less to protect the user's freedom than the ordinary General Public License. It also provides other free software developers Less of an advantage over competing non-free programs. These disadvantages are the reason we use the ordinary General Public License for many libraries. However, the Lesser license provides advantages in certain special circumstances. For example, on rare occasions, there may be a special need to encourage the widest possible use of a certain library, so that it becomes a de-facto standard. To achieve this, non-free programs must be allowed to use the library. A more frequent case is that a free library does the same job as widely used non-free libraries. In this case, there is little to gain by limiting the free library to free software only, so we use the Lesser General Public License. In other cases, permission to use a particular library in non-free programs enables a greater number of people to use a large body of free software. For example, permission to use the GNU C Library in non-free programs enables many more people to use the whole GNU operating system, as well as its variant, the GNU/Linux operating system. Although the Lesser General Public License is Less protective of the users' freedom, it does ensure that the user of a program that is linked with the Library has the freedom and the wherewithal to run that program using a modified version of the Library. The precise terms and conditions for copying, distribution and modification follow. Pay close attention to the difference between a "work based on the library" and a "work that uses the library". The former contains code derived from the library, whereas the latter must be combined with the library in order to run. GNU LESSER GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License Agreement applies to any software library or other program which contains a notice placed by the copyright holder or other authorized party saying it may be distributed under the terms of this Lesser General Public License (also called "this License"). Each licensee is addressed as "you". A "library" means a collection of software functions and/or data prepared so as to be conveniently linked with application programs (which use some of those functions and data) to form executables. The "Library", below, refers to any such software library or work which has been distributed under these terms. A "work based on the Library" means either the Library or any derivative work under copyright law: that is to say, a work containing the Library or a portion of it, either verbatim or with modifications and/or translated straightforwardly into another language. (Hereinafter, translation is included without limitation in the term "modification".) "Source code" for a work means the preferred form of the work for making modifications to it. For a library, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the library. Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running a program using the Library is not restricted, and output from such a program is covered only if its contents constitute a work based on the Library (independent of the use of the Library in a tool for writing it). Whether that is true depends on what the Library does and what the program that uses the Library does. 1. You may copy and distribute verbatim copies of the Library's complete source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and distribute a copy of this License along with the Library. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Library or any portion of it, thus forming a work based on the Library, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) The modified work must itself be a software library. b) You must cause the files modified to carry prominent notices stating that you changed the files and the date of any change. c) You must cause the whole of the work to be licensed at no charge to all third parties under the terms of this License. d) If a facility in the modified Library refers to a function or a table of data to be supplied by an application program that uses the facility, other than as an argument passed when the facility is invoked, then you must make a good faith effort to ensure that, in the event an application does not supply such function or table, the facility still operates, and performs whatever part of its purpose remains meaningful. (For example, a function in a library to compute square roots has a purpose that is entirely well-defined independent of the application. Therefore, Subsection 2d requires that any application-supplied function or table used by this function must be optional: if the application does not supply it, the square root function must still compute square roots.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Library, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Library, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Library. In addition, mere aggregation of another work not based on the Library with the Library (or with a work based on the Library) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may opt to apply the terms of the ordinary GNU General Public License instead of this License to a given copy of the Library. To do this, you must alter all the notices that refer to this License, so that they refer to the ordinary GNU General Public License, version 2, instead of to this License. (If a newer version than version 2 of the ordinary GNU General Public License has appeared, then you can specify that version instead if you wish.) Do not make any other change in these notices. Once this change is made in a given copy, it is irreversible for that copy, so the ordinary GNU General Public License applies to all subsequent copies and derivative works made from that copy. This option is useful when you wish to copy part of the code of the Library into a program that is not a library. 4. You may copy and distribute the Library (or a portion or derivative of it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange. If distribution of object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place satisfies the requirement to distribute the source code, even though third parties are not compelled to copy the source along with the object code. 5. A program that contains no derivative of any portion of the Library, but is designed to work with the Library by being compiled or linked with it, is called a "work that uses the Library". Such a work, in isolation, is not a derivative work of the Library, and therefore falls outside the scope of this License. However, linking a "work that uses the Library" with the Library creates an executable that is a derivative of the Library (because it contains portions of the Library), rather than a "work that uses the library". The executable is therefore covered by this License. Section 6 states terms for distribution of such executables. When a "work that uses the Library" uses material from a header file that is part of the Library, the object code for the work may be a derivative work of the Library even though the source code is not. Whether this is true is especially significant if the work can be linked without the Library, or if the work is itself a library. The threshold for this to be true is not precisely defined by law. If such an object file uses only numerical parameters, data structure layouts and accessors, and small macros and small inline functions (ten lines or less in length), then the use of the object file is unrestricted, regardless of whether it is legally a derivative work. (Executables containing this object code plus portions of the Library will still fall under Section 6.) Otherwise, if the work is a derivative of the Library, you may distribute the object code for the work under the terms of Section 6. Any executables containing that work also fall under Section 6, whether or not they are linked directly with the Library itself. 6. As an exception to the Sections above, you may also combine or link a "work that uses the Library" with the Library to produce a work containing portions of the Library, and distribute that work under terms of your choice, provided that the terms permit modification of the work for the customer's own use and reverse engineering for debugging such modifications. You must give prominent notice with each copy of the work that the Library is used in it and that the Library and its use are covered by this License. You must supply a copy of this License. If the work during execution displays copyright notices, you must include the copyright notice for the Library among them, as well as a reference directing the user to the copy of this License. Also, you must do one of these things: a) Accompany the work with the complete corresponding machine-readable source code for the Library including whatever changes were used in the work (which must be distributed under Sections 1 and 2 above); and, if the work is an executable linked with the Library, with the complete machine-readable "work that uses the Library", as object code and/or source code, so that the user can modify the Library and then relink to produce a modified executable containing the modified Library. (It is understood that the user who changes the contents of definitions files in the Library will not necessarily be able to recompile the application to use the modified definitions.) b) Use a suitable shared library mechanism for linking with the Library. A suitable mechanism is one that (1) uses at run time a copy of the library already present on the user's computer system, rather than copying library functions into the executable, and (2) will operate properly with a modified version of the library, if the user installs one, as long as the modified version is interface-compatible with the version that the work was made with. c) Accompany the work with a written offer, valid for at least three years, to give the same user the materials specified in Subsection 6a, above, for a charge no more than the cost of performing this distribution. d) If distribution of the work is made by offering access to copy from a designated place, offer equivalent access to copy the above specified materials from the same place. e) Verify that the user has already received a copy of these materials or that you have already sent this user a copy. For an executable, the required form of the "work that uses the Library" must include any data and utility programs needed for reproducing the executable from it. However, as a special exception, the materials to be distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. It may happen that this requirement contradicts the license restrictions of other proprietary libraries that do not normally accompany the operating system. Such a contradiction means you cannot use both them and the Library together in an executable that you distribute. 7. You may place library facilities that are a work based on the Library side-by-side in a single library together with other library facilities not covered by this License, and distribute such a combined library, provided that the separate distribution of the work based on the Library and of the other library facilities is otherwise permitted, and provided that you do these two things: a) Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities. This must be distributed under the terms of the Sections above. b) Give prominent notice with the combined library of the fact that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work. 8. You may not copy, modify, sublicense, link with, or distribute the Library except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense, link with, or distribute the Library is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 9. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Library or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Library (or any work based on the Library), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Library or works based on it. 10. Each time you redistribute the Library (or any work based on the Library), the recipient automatically receives a license from the original licensor to copy, distribute, link with or modify the Library subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties with this License. 11. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Library at all. For example, if a patent license would not permit royalty-free redistribution of the Library by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Library. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply, and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 12. If the distribution and/or use of the Library is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Library under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 13. The Free Software Foundation may publish revised and/or new versions of the Lesser General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Library specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Library does not specify a license version number, you may choose any version ever published by the Free Software Foundation. 14. If you wish to incorporate parts of the Library into other free programs whose distribution conditions are incompatible with these, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Libraries If you develop a new library, and you want it to be of the greatest possible use to the public, we recommend making it free software that everyone can redistribute and change. You can do so by permitting redistribution under these terms (or, alternatively, under the terms of the ordinary General Public License). To apply these terms, attach the following notices to the library. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. <one line to give the library's name and a brief idea of what it does.> Copyright (C) <year> <name of author> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Also add information on how to contact you by electronic and paper mail. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the library, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the library `Frob' (a library for tweaking knobs) written by James Random Hacker. <signature of Ty Coon>, 1 April 1990 Ty Coon, President of Vice That's all there is to it!
0
apollo_public_repos/apollo-platform/ros/ros_comm
apollo_public_repos/apollo-platform/ros/ros_comm/xmlrpcpp/.tar
{!!python/unicode 'url': 'https://github.com/ros-gbp/ros_comm-release/archive/release/indigo/xmlrpcpp/1.11.21-0.tar.gz', !!python/unicode 'version': ros_comm-release-release-indigo-xmlrpcpp-1.11.21-0}
0
apollo_public_repos/apollo-platform/ros/ros_comm
apollo_public_repos/apollo-platform/ros/ros_comm/xmlrpcpp/CHANGELOG.rst
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Changelog for package xmlrpcpp ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 1.11.21 (2017-03-06) -------------------- 1.11.20 (2016-06-27) -------------------- 1.11.19 (2016-04-18) -------------------- * use directory specific compiler flags (`#785 <https://github.com/ros/ros_comm/pull/785>`_) 1.11.18 (2016-03-17) -------------------- 1.11.17 (2016-03-11) -------------------- 1.11.16 (2015-11-09) -------------------- 1.11.15 (2015-10-13) -------------------- 1.11.14 (2015-09-19) -------------------- 1.11.13 (2015-04-28) -------------------- 1.11.12 (2015-04-27) -------------------- 1.11.11 (2015-04-16) -------------------- 1.11.10 (2014-12-22) -------------------- * improve Android support (`#537 <https://github.com/ros/ros_comm/pull/537>`_) * fix various defects reported by coverity 1.11.9 (2014-08-18) ------------------- 1.11.8 (2014-08-04) ------------------- 1.11.7 (2014-07-18) ------------------- 1.11.6 (2014-07-10) ------------------- 1.11.5 (2014-06-24) ------------------- 1.11.4 (2014-06-16) ------------------- 1.11.3 (2014-05-21) ------------------- 1.11.2 (2014-05-08) ------------------- 1.11.1 (2014-05-07) ------------------- * fix day comparison for rpc value of type timestamp (`#395 <https://github.com/ros/ros_comm/issues/395>`_) 1.11.0 (2014-03-04) ------------------- * output error message when hostname lookup fails (`#364 <https://github.com/ros/ros_comm/issues/364>`_) 1.10.0 (2014-02-11) ------------------- 1.9.54 (2014-01-27) ------------------- 1.9.53 (2014-01-14) ------------------- 1.9.52 (2014-01-08) ------------------- 1.9.51 (2014-01-07) ------------------- * fix compilation and warnings with clang (`#291 <https://github.com/ros/ros_comm/issues/291>`_) 1.9.50 (2013-10-04) ------------------- 1.9.49 (2013-09-16) ------------------- 1.9.48 (2013-08-21) ------------------- 1.9.47 (2013-07-03) ------------------- 1.9.46 (2013-06-18) ------------------- 1.9.45 (2013-06-06) ------------------- 1.9.44 (2013-03-21) ------------------- * fix install destination for dll's under Windows 1.9.43 (2013-03-13) ------------------- 1.9.42 (2013-03-08) ------------------- * refine license description to LGPL-2.1 1.9.41 (2013-01-24) ------------------- 1.9.40 (2013-01-13) ------------------- 1.9.39 (2012-12-29) ------------------- * first public release for Groovy
0
apollo_public_repos/apollo-platform/ros/ros_comm/xmlrpcpp
apollo_public_repos/apollo-platform/ros/ros_comm/xmlrpcpp/test/TestValues.vcproj
<?xml version="1.0" encoding = "Windows-1252"?> <VisualStudioProject ProjectType="Visual C++" Version="7.00" Name="TestValues" ProjectGUID="{6181BBE3-DA50-4EEE-8D52-1F4245A1D603}" SccProjectName="" SccLocalPath=""> <Platforms> <Platform Name="Win32"/> </Platforms> <Configurations> <Configuration Name="Release|Win32" OutputDirectory=".\Release" IntermediateDirectory=".\Release" ConfigurationType="1" UseOfMFC="0" ATLMinimizesCRunTimeLibraryUsage="FALSE" CharacterSet="2"> <Tool Name="VCCLCompilerTool" InlineFunctionExpansion="1" PreprocessorDefinitions="WIN32,NDEBUG,_CONSOLE" StringPooling="TRUE" RuntimeLibrary="2" EnableFunctionLevelLinking="TRUE" UsePrecompiledHeader="2" PrecompiledHeaderFile=".\Release/TestValues.pch" AssemblerListingLocation=".\Release/" ObjectFile=".\Release/" ProgramDataBaseFileName=".\Release/" WarningLevel="3" SuppressStartupBanner="TRUE"> <IntelOptions Optimization="2" InlineFuncExpansion="1" OmitFramePtrs="1" StringPooling="1" RuntimeLibrary="2" BufferSecurityCheck="1" FunctionLevelLinking="1" AllOptions="/c /nologo /W3 /O2 /Ob1 /Oy /D &quot;WIN32&quot; /D &quot;NDEBUG&quot; /D &quot;_CONSOLE&quot; /D &quot;_MBCS&quot; /GF /FD /EHsc /MD /GS /Gy /YX&quot;StdAfx.h&quot; /Fp&quot;.\Release/TestValues.pch&quot; /Fo&quot;.\Release/&quot; /Fd&quot;.\Release/&quot; /Gd /TP"/> </Tool> <Tool Name="VCCustomBuildTool"/> <Tool Name="VCLinkerTool" AdditionalOptions="/MACHINE:I386" AdditionalDependencies="odbc32.lib odbccp32.lib" OutputFile=".\Release/TestValues.exe" LinkIncremental="1" SuppressStartupBanner="TRUE" ProgramDatabaseFile=".\Release/TestValues.pdb" SubSystem="1"> <IntelOptions AllOptions="/NOLOGO /OUT:&quot;.\Release/TestValues.exe&quot; /INCREMENTAL:NO odbc32.lib odbccp32.lib /PDB:&quot;.\Release/TestValues.pdb&quot; /SUBSYSTEM:CONSOLE /TLBID:1 /MACHINE:I386 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib"/> </Tool> <Tool Name="VCMIDLTool" TypeLibraryName=".\Release/TestValues.tlb"/> <Tool Name="VCPostBuildEventTool"/> <Tool Name="VCPreBuildEventTool"/> <Tool Name="VCPreLinkEventTool"/> <Tool Name="VCResourceCompilerTool" PreprocessorDefinitions="NDEBUG" Culture="1033"/> <Tool Name="VCWebServiceProxyGeneratorTool"/> <Tool Name="VCWebDeploymentTool"/> <IntelOptions CompilerName="1"/> </Configuration> <Configuration Name="Debug|Win32" OutputDirectory=".\Debug" IntermediateDirectory=".\Debug" ConfigurationType="1" UseOfMFC="0" ATLMinimizesCRunTimeLibraryUsage="FALSE" CharacterSet="2"> <Tool Name="VCCLCompilerTool" Optimization="0" AdditionalIncludeDirectories="..\src" PreprocessorDefinitions="WIN32,_DEBUG,_CONSOLE,_WINDOWS" BasicRuntimeChecks="3" RuntimeLibrary="3" PrecompiledHeaderFile=".\Debug/TestValues.pch" AssemblerListingLocation=".\Debug/" ObjectFile=".\Debug/" ProgramDataBaseFileName=".\Debug/" WarningLevel="3" SuppressStartupBanner="TRUE" DebugInformationFormat="4" CompileAs="0"> <IntelOptions Optimization="0" MinimalRebuild="1" BasicRuntimeChecks="3" RuntimeLibrary="3" AllOptions="/c /I &quot;..\src&quot; /ZI /nologo /W3 /Od /D &quot;WIN32&quot; /D &quot;_DEBUG&quot; /D &quot;_CONSOLE&quot; /D &quot;_WINDOWS&quot; /D &quot;_MBCS&quot; /Gm /EHsc /RTC1 /MDd /Fp&quot;.\Debug/TestValues.pch&quot; /Fo&quot;.\Debug/&quot; /Fd&quot;.\Debug/&quot; /Gd"/> </Tool> <Tool Name="VCCustomBuildTool"/> <Tool Name="VCLinkerTool" AdditionalOptions="/MACHINE:I386" AdditionalDependencies="xmlrpc.lib odbc32.lib odbccp32.lib" OutputFile=".\Debug/TestValues.exe" LinkIncremental="2" SuppressStartupBanner="TRUE" AdditionalLibraryDirectories="..\Debug" GenerateDebugInformation="TRUE" ProgramDatabaseFile=".\Debug/TestValues.pdb" SubSystem="1"> <IntelOptions AllOptions="/NOLOGO /OUT:&quot;.\Debug/TestValues.exe&quot; /INCREMENTAL /LIBPATH:&quot;..\Debug&quot; xmlrpc.lib odbc32.lib odbccp32.lib /DEBUG /PDB:&quot;.\Debug/TestValues.pdb&quot; /SUBSYSTEM:CONSOLE /TLBID:1 /MACHINE:I386 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib"/> </Tool> <Tool Name="VCMIDLTool" TypeLibraryName=".\Debug/TestValues.tlb"/> <Tool Name="VCPostBuildEventTool"/> <Tool Name="VCPreBuildEventTool"/> <Tool Name="VCPreLinkEventTool"/> <Tool Name="VCResourceCompilerTool" PreprocessorDefinitions="_DEBUG" Culture="1033"/> <Tool Name="VCWebServiceProxyGeneratorTool"/> <Tool Name="VCWebDeploymentTool"/> <IntelOptions CompilerName="1"/> </Configuration> </Configurations> <Files> <Filter Name="Source Files" Filter="cpp;c;cxx;rc;def;r;odl;idl;hpj;bat"> <File RelativePath=".\TestValues.cpp"/> </Filter> </Files> <Globals/> </VisualStudioProject>
0
apollo_public_repos/apollo-platform/ros/ros_comm/xmlrpcpp
apollo_public_repos/apollo-platform/ros/ros_comm/xmlrpcpp/test/FileClient.cpp
// FileClient.cpp : A simple xmlrpc client. Usage: FileClient serverHost serverPort xmlfile // Reads an xmlrpc request from the specified xmlfile and calls the method on the server. // // Link against xmlrpc lib and whatever socket libs your system needs (ws2_32.lib on windows) #include "XmlRpc.h" #include <iostream> #include <fstream> #include <stdlib.h> using namespace XmlRpc; std::string parseRequest(std::string const& xml, XmlRpcValue& params); int main(int argc, char* argv[]) { if (argc != 4) { std::cerr << "Usage: FileClient serverHost serverPort requestXmlFile\n"; return -1; } int port = atoi(argv[2]); XmlRpc::setVerbosity(5); XmlRpcClient c(argv[1], port); // std::ifstream infile(argv[3]); if (infile.fail()) { std::cerr << "Could not open file '" << argv[3] << "'.\n"; return -1; } // Suck in the file. This is a one-liner in good compilers (which vc++ 6 is not)... infile.seekg(0L, std::ios::end); long nb = infile.tellg(); infile.clear(); infile.seekg(0L); char* b = new char[nb+1]; infile.read(b, nb); b[nb] = 0; std::cout << "Read file.\n"; // Find the methodName and parse the params std::string s(b); XmlRpcValue params; std::string name = parseRequest(s, params); if (name.empty()) { std::cerr << "Could not parse file\n"; return -1; } for (;;) { XmlRpcValue result; std::cout << "Calling " << name << std::endl; if (c.execute(name.c_str(), params, result)) std::cout << result << "\n\n"; else std::cout << "Error calling '" << name << "'\n\n"; std::cout << "Again? [y]: "; std::string ans; std::cin >> ans; if (ans != "" && ans != "y") break; } return 0; } // std::string parseRequest(std::string const& xml, XmlRpcValue& params) { const char METHODNAME_TAG[] = "<methodName>"; const char PARAMS_TAG[] = "<params>"; const char PARAMS_ETAG[] = "</params>"; const char PARAM_TAG[] = "<param>"; const char PARAM_ETAG[] = "</param>"; int offset = 0; // Number of chars parsed from the request std::string methodName = XmlRpcUtil::parseTag(METHODNAME_TAG, xml, &offset); XmlRpcUtil::log(3, "XmlRpcServerConnection::parseRequest: parsed methodName %s.", methodName.c_str()); if (! methodName.empty() && XmlRpcUtil::findTag(PARAMS_TAG, xml, &offset)) { int nArgs = 0; while (XmlRpcUtil::nextTagIs(PARAM_TAG, xml, &offset)) { std::cout << "Parsing arg " << nArgs+1 << std::endl; XmlRpcValue arg(xml, &offset); if ( ! arg.valid()) { std::cerr << "Invalid argument\n"; return std::string(); } std::cout << "Adding arg " << nArgs+1 << " to params array." << std::endl; params[nArgs++] = arg; (void) XmlRpcUtil::nextTagIs(PARAM_ETAG, xml, &offset); } XmlRpcUtil::log(3, "XmlRpcServerConnection::parseRequest: parsed %d params.", nArgs); (void) XmlRpcUtil::nextTagIs(PARAMS_ETAG, xml, &offset); } return methodName; }
0
apollo_public_repos/apollo-platform/ros/ros_comm/xmlrpcpp
apollo_public_repos/apollo-platform/ros/ros_comm/xmlrpcpp/test/Validator.vcproj
<?xml version="1.0" encoding = "Windows-1252"?> <VisualStudioProject ProjectType="Visual C++" Version="7.00" Name="Validator" ProjectGUID="{E68AB694-4805-43EA-A96E-21B8FE285DE4}" SccProjectName="" SccLocalPath=""> <Platforms> <Platform Name="Win32"/> </Platforms> <Configurations> <Configuration Name="Release|Win32" OutputDirectory=".\Release" IntermediateDirectory=".\Release" ConfigurationType="1" UseOfMFC="0" ATLMinimizesCRunTimeLibraryUsage="FALSE" CharacterSet="2"> <Tool Name="VCCLCompilerTool" InlineFunctionExpansion="1" PreprocessorDefinitions="WIN32,NDEBUG,_CONSOLE,_WINDOWS" StringPooling="TRUE" RuntimeLibrary="2" EnableFunctionLevelLinking="TRUE" UsePrecompiledHeader="3" PrecompiledHeaderThrough="stdafx.h" PrecompiledHeaderFile=".\Release/Validator.pch" AssemblerListingLocation=".\Release/" ObjectFile=".\Release/" ProgramDataBaseFileName=".\Release/" WarningLevel="3" SuppressStartupBanner="TRUE"> <IntelOptions Optimization="2" InlineFuncExpansion="1" OmitFramePtrs="1" StringPooling="1" RuntimeLibrary="2" BufferSecurityCheck="1" FunctionLevelLinking="1" AllOptions="/c /nologo /W3 /O2 /Ob1 /Oy /D &quot;WIN32&quot; /D &quot;NDEBUG&quot; /D &quot;_CONSOLE&quot; /D &quot;_WINDOWS&quot; /D &quot;_MBCS&quot; /GF /FD /EHsc /MD /GS /Gy /Yu&quot;stdafx.h&quot; /Fp&quot;.\Release/Validator.pch&quot; /Fo&quot;.\Release/&quot; /Fd&quot;.\Release/&quot; /Gd /TP"/> </Tool> <Tool Name="VCCustomBuildTool"/> <Tool Name="VCLinkerTool" AdditionalOptions="/MACHINE:I386" AdditionalDependencies="odbc32.lib odbccp32.lib" OutputFile=".\Release/Validator.exe" LinkIncremental="1" SuppressStartupBanner="TRUE" ProgramDatabaseFile=".\Release/Validator.pdb" SubSystem="1"> <IntelOptions AllOptions="/NOLOGO /OUT:&quot;.\Release/Validator.exe&quot; /INCREMENTAL:NO odbc32.lib odbccp32.lib /PDB:&quot;.\Release/Validator.pdb&quot; /SUBSYSTEM:CONSOLE /TLBID:1 /MACHINE:I386 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib"/> </Tool> <Tool Name="VCMIDLTool" TypeLibraryName=".\Release/Validator.tlb"/> <Tool Name="VCPostBuildEventTool"/> <Tool Name="VCPreBuildEventTool"/> <Tool Name="VCPreLinkEventTool"/> <Tool Name="VCResourceCompilerTool" PreprocessorDefinitions="NDEBUG" Culture="1033"/> <Tool Name="VCWebServiceProxyGeneratorTool"/> <Tool Name="VCWebDeploymentTool"/> <IntelOptions CompilerName="1"/> </Configuration> <Configuration Name="Debug|Win32" OutputDirectory=".\Debug" IntermediateDirectory=".\Debug" ConfigurationType="1" UseOfMFC="0" ATLMinimizesCRunTimeLibraryUsage="FALSE" CharacterSet="2"> <Tool Name="VCCLCompilerTool" Optimization="0" AdditionalIncludeDirectories="..\src" PreprocessorDefinitions="WIN32,_DEBUG,_CONSOLE,_WINDOWS" BasicRuntimeChecks="3" RuntimeLibrary="3" PrecompiledHeaderFile=".\Debug/Validator.pch" AssemblerListingLocation=".\Debug/" ObjectFile=".\Debug/" ProgramDataBaseFileName=".\Debug/" WarningLevel="3" SuppressStartupBanner="TRUE" DebugInformationFormat="4" CompileAs="0"> <IntelOptions Optimization="0" MinimalRebuild="1" BasicRuntimeChecks="3" RuntimeLibrary="3" AllOptions="/c /I &quot;..\src&quot; /ZI /nologo /W3 /Od /D &quot;WIN32&quot; /D &quot;_DEBUG&quot; /D &quot;_CONSOLE&quot; /D &quot;_WINDOWS&quot; /D &quot;_MBCS&quot; /Gm /EHsc /RTC1 /MDd /Fp&quot;.\Debug/Validator.pch&quot; /Fo&quot;.\Debug/&quot; /Fd&quot;.\Debug/&quot; /Gd"/> </Tool> <Tool Name="VCCustomBuildTool"/> <Tool Name="VCLinkerTool" AdditionalOptions="/MACHINE:I386" AdditionalDependencies="xmlrpc.lib WS2_32.lib odbc32.lib odbccp32.lib" OutputFile=".\Debug/Validator.exe" LinkIncremental="2" SuppressStartupBanner="TRUE" AdditionalLibraryDirectories="..\debug" GenerateDebugInformation="TRUE" ProgramDatabaseFile=".\Debug/Validator.pdb" SubSystem="1"> <IntelOptions AllOptions="/NOLOGO /OUT:&quot;.\Debug/Validator.exe&quot; /INCREMENTAL /LIBPATH:&quot;..\debug&quot; xmlrpc.lib WS2_32.lib odbc32.lib odbccp32.lib /DEBUG /PDB:&quot;.\Debug/Validator.pdb&quot; /SUBSYSTEM:CONSOLE /TLBID:1 /MACHINE:I386 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib"/> </Tool> <Tool Name="VCMIDLTool" TypeLibraryName=".\Debug/Validator.tlb"/> <Tool Name="VCPostBuildEventTool"/> <Tool Name="VCPreBuildEventTool"/> <Tool Name="VCPreLinkEventTool"/> <Tool Name="VCResourceCompilerTool" PreprocessorDefinitions="_DEBUG" Culture="1033"/> <Tool Name="VCWebServiceProxyGeneratorTool"/> <Tool Name="VCWebDeploymentTool"/> <IntelOptions CompilerName="1"/> </Configuration> </Configurations> <Files> <Filter Name="Source Files" Filter="cpp;c;cxx;rc;def;r;odl;idl;hpj;bat"> <File RelativePath=".\Validator.cpp"/> </Filter> </Files> <Globals/> </VisualStudioProject>
0
apollo_public_repos/apollo-platform/ros/ros_comm/xmlrpcpp
apollo_public_repos/apollo-platform/ros/ros_comm/xmlrpcpp/test/HelloServer.dsp
# Microsoft Developer Studio Project File - Name="HelloServer" - Package Owner=<4> # Microsoft Developer Studio Generated Build File, Format Version 6.00 # ** DO NOT EDIT ** # TARGTYPE "Win32 (x86) Console Application" 0x0103 CFG=HelloServer - Win32 Debug !MESSAGE This is not a valid makefile. To build this project using NMAKE, !MESSAGE use the Export Makefile command and run !MESSAGE !MESSAGE NMAKE /f "HelloServer.mak". !MESSAGE !MESSAGE You can specify a configuration when running NMAKE !MESSAGE by defining the macro CFG on the command line. For example: !MESSAGE !MESSAGE NMAKE /f "HelloServer.mak" CFG="HelloServer - Win32 Debug" !MESSAGE !MESSAGE Possible choices for configuration are: !MESSAGE !MESSAGE "HelloServer - Win32 Release" (based on "Win32 (x86) Console Application") !MESSAGE "HelloServer - Win32 Debug" (based on "Win32 (x86) Console Application") !MESSAGE # Begin Project # PROP AllowPerConfigDependencies 0 # PROP Scc_ProjName "" # PROP Scc_LocalPath "" CPP=cl.exe RSC=rc.exe !IF "$(CFG)" == "HelloServer - Win32 Release" # PROP BASE Use_MFC 0 # PROP BASE Use_Debug_Libraries 0 # PROP BASE Output_Dir "Release" # PROP BASE Intermediate_Dir "Release" # PROP BASE Target_Dir "" # PROP Use_MFC 0 # PROP Use_Debug_Libraries 0 # PROP Output_Dir "Release" # PROP Intermediate_Dir "Release" # PROP Ignore_Export_Lib 0 # PROP Target_Dir "" # ADD BASE CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_CONSOLE" /D "_MBCS" /Yu"stdafx.h" /FD /c # ADD CPP /nologo /MD /W3 /GX /O2 /I "..\src" /D "WIN32" /D "NDEBUG" /D "_CONSOLE" /D "_MBCS" /D "_WINDOWS" /FD /c # SUBTRACT CPP /YX /Yc /Yu # ADD BASE RSC /l 0x409 /d "NDEBUG" # ADD RSC /l 0x409 /d "NDEBUG" BSC32=bscmake.exe # ADD BASE BSC32 /nologo # ADD BSC32 /nologo LINK32=link.exe # ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /machine:I386 # ADD LINK32 xmlrpc.lib Ws2_32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /machine:I386 /libpath:"..\release" !ELSEIF "$(CFG)" == "HelloServer - Win32 Debug" # PROP BASE Use_MFC 0 # PROP BASE Use_Debug_Libraries 1 # PROP BASE Output_Dir "Debug" # PROP BASE Intermediate_Dir "Debug" # PROP BASE Target_Dir "" # PROP Use_MFC 0 # PROP Use_Debug_Libraries 1 # PROP Output_Dir "Debug" # PROP Intermediate_Dir "Debug" # PROP Ignore_Export_Lib 0 # PROP Target_Dir "" # ADD BASE CPP /nologo /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_CONSOLE" /D "_MBCS" /Yu"stdafx.h" /FD /GZ /c # ADD CPP /nologo /MDd /W3 /Gm /GX /ZI /Od /I "..\src" /D "WIN32" /D "_DEBUG" /D "_CONSOLE" /D "_MBCS" /D "_WINDOWS" /FD /GZ /c # SUBTRACT CPP /YX /Yc /Yu # ADD BASE RSC /l 0x409 /d "_DEBUG" # ADD RSC /l 0x409 /d "_DEBUG" BSC32=bscmake.exe # ADD BASE BSC32 /nologo # ADD BSC32 /nologo LINK32=link.exe # ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /debug /machine:I386 /pdbtype:sept # ADD LINK32 xmlrpc.lib Ws2_32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /debug /machine:I386 /pdbtype:sept /libpath:"..\Debug" !ENDIF # Begin Target # Name "HelloServer - Win32 Release" # Name "HelloServer - Win32 Debug" # Begin Group "Source Files" # PROP Default_Filter "cpp;c;cxx;rc;def;r;odl;idl;hpj;bat" # Begin Source File SOURCE=.\HelloServer.cpp # End Source File # End Group # End Target # End Project
0
apollo_public_repos/apollo-platform/ros/ros_comm/xmlrpcpp
apollo_public_repos/apollo-platform/ros/ros_comm/xmlrpcpp/test/TestBase64Server.cpp
// TestBase64Server.cpp : Simple XMLRPC server example. Usage: TestBase64Server serverPort // #if defined(_MSC_VER) # pragma warning(disable:4786) // identifier was truncated in debug info #endif #include <iostream> #include <fstream> #include <algorithm> #include <stdlib.h> #include "XmlRpc.h" using namespace XmlRpc; // The server XmlRpcServer s; // No arguments, result is Base64-encoded pngnow.png data. class TestBase64 : public XmlRpcServerMethod { public: TestBase64(XmlRpcServer* s) : XmlRpcServerMethod("TestBase64", s) {} void execute(XmlRpcValue& params, XmlRpcValue& result) { std::ifstream infile("pngnow.png", std::ios::binary); if (infile.fail()) infile.open("../pngnow.png", std::ios::binary); if (infile.fail()) result = "Could not open file pngnow.png"; else { XmlRpcValue::BinaryData& data = result; int n = 0; for (;; ++n) { char c = infile.get(); if (infile.eof()) break; data.push_back(c); } std::cerr << "Read " << n << " bytes from pngnow.png\n"; } } } TestBase64(&s); // This constructor registers the method with the server int main(int argc, char* argv[]) { if (argc != 2) { std::cerr << "Usage: TestBase64Server serverPort\n"; return -1; } int port = atoi(argv[1]); //XmlRpc::setVerbosity(5); // Create the server socket on the specified port s.bindAndListen(port); // Wait for requests indefinitely s.work(-1.0); return 0; }
0
apollo_public_repos/apollo-platform/ros/ros_comm/xmlrpcpp
apollo_public_repos/apollo-platform/ros/ros_comm/xmlrpcpp/test/TestValuesWin32.cpp
// TestValues.cpp : Test XML encoding and decoding of XmlRpcValues. #define _CRTDBG_MAP_ALLOC #include <stdlib.h> #include <crtdbg.h> #include "XmlRpcValue.h" #include <assert.h> #include <iostream> using namespace XmlRpc; void testBoolean() { XmlRpcValue booleanFalse(false); XmlRpcValue booleanTrue(true); int offset = 0; XmlRpcValue booleanFalseXml("<value><boolean>0</boolean></value>", &offset); offset = 0; XmlRpcValue booleanTrueXml("<value><boolean>1</boolean></value>", &offset); assert(booleanFalse != booleanTrue); assert(booleanFalse == booleanFalseXml); assert(booleanFalse == booleanFalseXml); if (booleanFalse) assert(false); if (booleanTrue) assert( ! false); else assert(false); } // Int void testInt() { XmlRpcValue int0(0); XmlRpcValue int1(1); XmlRpcValue int10(10); XmlRpcValue int_1(-1); int offset = 0; XmlRpcValue int0Xml("<value><int>0</int></value>", &offset); offset = 0; XmlRpcValue int9Xml("<value><i4>9</i4></value>", &offset); assert(int0 == int0Xml); assert(int(int10) - int(int1) == int(int9Xml)); assert(9 == int(int9Xml)); assert(int(int10) + int(int_1) == int(int9Xml)); } void testDouble() { // Double XmlRpcValue d(43.7); int offset = 0; XmlRpcValue dXml("<value><double>56.3</double></value>", &offset); assert(double(d) + double(dXml) == 100.0); // questionable practice... } void testString() { // String XmlRpcValue s("Now is the time <&"); char csxml[] = "<value><string>Now is the time &lt;&amp;</string></value>"; std::string ssxml = csxml; int offset = 0; XmlRpcValue vscXml(csxml, &offset); offset = 0; XmlRpcValue vssXml(ssxml, &offset); assert(s == vscXml); assert(s == vssXml); offset = 0; XmlRpcValue fromXml(vssXml.toXml(), &offset); assert(s == fromXml); // Empty or blank strings with no <string> tags std::string emptyStringXml("<value></value>"); offset = 0; XmlRpcValue emptyStringVal1(emptyStringXml, &offset); XmlRpcValue emptyStringVal2(""); assert(emptyStringVal1 == emptyStringVal2); emptyStringXml = "<value> </value>"; offset = 0; XmlRpcValue blankStringVal(emptyStringXml, &offset); assert(std::string(blankStringVal) == " "); } void testDateTime() { // DateTime int offset = 0; XmlRpcValue dateTime("<value><dateTime.iso8601>19040101T03:12:35</dateTime.iso8601></value>", &offset); struct tm &t = dateTime; assert(t.tm_year == 1904 && t.tm_min == 12); } void testArray(XmlRpcValue const& d) { // Array XmlRpcValue a; a.setSize(4); a[0] = 1; a[1] = std::string("two"); a[2] = 43.7; a[3] = "four"; assert(int(a[0]) == 1); assert(a[2] == d); char csaXml[] = "<value><array>\n" " <data>\n" " <value><i4>1</i4></value> \n" " <value> <string>two</string></value>\n" " <value><double>43.7</double></value>\n" " <value>four</value>\n" " </data>\n" "</array></value>"; int offset = 0; XmlRpcValue aXml(csaXml, &offset); assert(a == aXml); } void testStruct() { // Struct XmlRpcValue struct1; struct1["i4"] = 1; struct1["str"] = "two"; struct1["d"] = 43.7; XmlRpcValue a; a.setSize(4); a[0] = 1; a[1] = std::string("two"); a[2] = 43.7; a[3] = "four"; assert(struct1["d"] == a[2]); char csStructXml[] = "<value><struct>\n" " <member>\n" " <name>i4</name> \n" " <value><i4>1</i4></value> \n" " </member>\n" " <member>\n" " <name>d</name> \n" " <value><double>43.7</double></value>\n" " </member>\n" " <member>\n" " <name>str</name> \n" " <value> <string>two</string></value>\n" " </member>\n" "</struct></value>"; int offset = 0; XmlRpcValue structXml(csStructXml, &offset); assert(struct1 == structXml); XmlRpcValue astruct; astruct["array"] = a; assert(astruct["array"][2] == struct1["d"]); for (int i=0; i<10; i++) { XmlRpcValue Event; Event["Name"] = "string"; Event.clear(); const int NELMTS = 100; int ii; for (ii=0; ii< NELMTS; ++ii) { char buf[40]; sprintf(buf,"%d", ii); Event[buf] = buf; } Event.clear(); for (ii=0; ii< NELMTS; ++ii) { char buf[40]; sprintf(buf,"%d", ii); if (ii != NELMTS/2) Event[buf] = ii; else for (int jj=0; jj< NELMTS; ++jj) { char bufj[40]; sprintf(bufj,"%d", jj); Event[buf][bufj] = bufj; } } for (ii=0; ii< NELMTS; ++ii) { char buf[40]; sprintf(buf,"%d", ii); if (ii != NELMTS/2) assert(Event[buf] == XmlRpcValue(ii)); else assert(Event[buf].size() == NELMTS); } } } int main(int argc, char* argv[]) { _CrtDumpMemoryLeaks(); _CrtCheckMemory( ); testBoolean(); _CrtDumpMemoryLeaks(); _CrtCheckMemory( ); testInt(); _CrtDumpMemoryLeaks(); _CrtCheckMemory( ); testDouble(); _CrtDumpMemoryLeaks(); _CrtCheckMemory( ); testString(); _CrtDumpMemoryLeaks(); _CrtCheckMemory( ); testDateTime(); _CrtDumpMemoryLeaks(); _CrtCheckMemory( ); testArray(43.7); _CrtDumpMemoryLeaks(); _CrtCheckMemory( ); testStruct(); _CrtDumpMemoryLeaks(); _CrtCheckMemory( ); return 0; }
0
apollo_public_repos/apollo-platform/ros/ros_comm/xmlrpcpp
apollo_public_repos/apollo-platform/ros/ros_comm/xmlrpcpp/test/echoStructTest.xml
<?xml version="1.0"?> <methodCall> <methodName>validator1.echoStructTest</methodName> <params> <param> <value><struct> <member> <name>substruct0</name> <value> <struct> <member> <name>curly</name> <value> <i4>-76</i4> </value> </member> <member> <name>larry</name> <value> <i4>31</i4> </value> </member> <member> <name>moe</name> <value> <i4>44</i4> </value> </member> </struct> </value> </member> <member> <name>substruct1</name> <value> <struct> <member> <name>curly</name> <value> <i4>-9</i4> </value> </member> <member> <name>larry</name> <value> <i4>42</i4> </value> </member> <member> <name>moe</name> <value> <i4>57</i4> </value> </member> </struct> </value> </member> <member> <name>substruct2</name> <value> <struct> <member> <name>curly</name> <value> <i4>-15</i4> </value> </member> <member> <name>larry</name> <value> <i4>69</i4> </value> </member> <member> <name>moe</name> <value> <i4>78</i4> </value> </member> </struct> </value> </member> <member> <name>substruct3</name> <value> <struct> <member> <name>curly</name> <value> <i4>-91</i4> </value> </member> <member> <name>larry</name> <value> <i4>66</i4> </value> </member> <member> <name>moe</name> <value> <i4>4</i4> </value> </member> </struct> </value> </member> <member> <name>substruct4</name> <value> <struct> <member> <name>curly</name> <value> <i4>-47</i4> </value> </member> <member> <name>larry</name> <value> <i4>66</i4> </value> </member> <member> <name>moe</name> <value> <i4>8</i4> </value> </member> </struct> </value> </member> <member> <name>substruct5</name> <value> <struct> <member> <name>curly</name> <value> <i4>-68</i4> </value> </member> <member> <name>larry</name> <value> <i4>26</i4> </value> </member> <member> <name>moe</name> <value> <i4>87</i4> </value> </member> </struct> </value> </member> <member> <name>substruct6</name> <value> <struct> <member> <name>curly</name> <value> <i4>-59</i4> </value> </member> <member> <name>larry</name> <value> <i4>20</i4> </value> </member> <member> <name>moe</name> <value> <i4>74</i4> </value> </member> </struct> </value> </member> <member> <name>substruct7</name> <value> <struct> <member> <name>curly</name> <value> <i4>-57</i4> </value> </member> <member> <name>larry</name> <value> <i4>30</i4> </value> </member> <member> <name>moe</name> <value> <i4>75</i4> </value> </member> </struct> </value> </member> <member> <name>substruct8</name> <value> <struct> <member> <name>curly</name> <value> <i4>-34</i4> </value> </member> <member> <name>larry</name> <value> <i4>33</i4> </value> </member> <member> <name>moe</name> <value> <i4>30</i4> </value> </member> </struct> </value> </member> <member> <name>substruct9</name> <value> <struct> <member> <name>curly</name> <value> <i4>-64</i4> </value> </member> <member> <name>larry</name> <value> <i4>98</i4> </value> </member> <member> <name>moe</name> <value> <i4>17</i4> </value> </member> </struct> </value> </member> </struct></value> </param> </params> </methodCall>
0
apollo_public_repos/apollo-platform/ros/ros_comm/xmlrpcpp
apollo_public_repos/apollo-platform/ros/ros_comm/xmlrpcpp/test/TestBase64Client.vcproj
<?xml version="1.0" encoding = "Windows-1252"?> <VisualStudioProject ProjectType="Visual C++" Version="7.00" Name="TestBase64Client" ProjectGUID="{1E8B725B-E898-494C-84C6-DB77EF38E6CB}" SccProjectName="" SccLocalPath=""> <Platforms> <Platform Name="Win32"/> </Platforms> <Configurations> <Configuration Name="Debug|Win32" OutputDirectory=".\Debug" IntermediateDirectory=".\Debug" ConfigurationType="1" UseOfMFC="0" ATLMinimizesCRunTimeLibraryUsage="FALSE" CharacterSet="2"> <Tool Name="VCCLCompilerTool" Optimization="0" AdditionalIncludeDirectories="..\src" PreprocessorDefinitions="WIN32,_DEBUG,_CONSOLE,_WINDOWS" BasicRuntimeChecks="3" RuntimeLibrary="3" PrecompiledHeaderFile=".\Debug/TestBase64Client.pch" AssemblerListingLocation=".\Debug/" ObjectFile=".\Debug/" ProgramDataBaseFileName=".\Debug/" WarningLevel="3" SuppressStartupBanner="TRUE" DebugInformationFormat="4" CompileAs="0"> <IntelOptions Optimization="0" MinimalRebuild="1" BasicRuntimeChecks="3" RuntimeLibrary="3" AllOptions="/c /I &quot;..\src&quot; /ZI /nologo /W3 /Od /D &quot;WIN32&quot; /D &quot;_DEBUG&quot; /D &quot;_CONSOLE&quot; /D &quot;_WINDOWS&quot; /D &quot;_MBCS&quot; /Gm /EHsc /RTC1 /MDd /Fp&quot;.\Debug/TestBase64Client.pch&quot; /Fo&quot;.\Debug/&quot; /Fd&quot;.\Debug/&quot; /Gd"/> </Tool> <Tool Name="VCCustomBuildTool"/> <Tool Name="VCLinkerTool" AdditionalOptions="/MACHINE:I386" AdditionalDependencies="xmlrpc.lib Ws2_32.lib odbc32.lib odbccp32.lib" OutputFile=".\Debug/TestBase64Client.exe" LinkIncremental="2" SuppressStartupBanner="TRUE" AdditionalLibraryDirectories="..\Debug" GenerateDebugInformation="TRUE" ProgramDatabaseFile=".\Debug/TestBase64Client.pdb" SubSystem="1"> <IntelOptions AllOptions="/NOLOGO /OUT:&quot;.\Debug/TestBase64Client.exe&quot; /INCREMENTAL /LIBPATH:&quot;..\Debug&quot; xmlrpc.lib Ws2_32.lib odbc32.lib odbccp32.lib /DEBUG /PDB:&quot;.\Debug/TestBase64Client.pdb&quot; /SUBSYSTEM:CONSOLE /TLBID:1 /MACHINE:I386 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib"/> </Tool> <Tool Name="VCMIDLTool" TypeLibraryName=".\Debug/TestBase64Client.tlb"/> <Tool Name="VCPostBuildEventTool"/> <Tool Name="VCPreBuildEventTool"/> <Tool Name="VCPreLinkEventTool"/> <Tool Name="VCResourceCompilerTool" PreprocessorDefinitions="_DEBUG" Culture="1033"/> <Tool Name="VCWebServiceProxyGeneratorTool"/> <Tool Name="VCWebDeploymentTool"/> <IntelOptions CompilerName="1"/> </Configuration> <Configuration Name="Release|Win32" OutputDirectory=".\Release" IntermediateDirectory=".\Release" ConfigurationType="1" UseOfMFC="0" ATLMinimizesCRunTimeLibraryUsage="FALSE" CharacterSet="2"> <Tool Name="VCCLCompilerTool" InlineFunctionExpansion="1" AdditionalIncludeDirectories="..\src" PreprocessorDefinitions="WIN32,NDEBUG,_CONSOLE,_WINDOWS" StringPooling="TRUE" RuntimeLibrary="2" EnableFunctionLevelLinking="TRUE" PrecompiledHeaderFile=".\Release/TestBase64Client.pch" AssemblerListingLocation=".\Release/" ObjectFile=".\Release/" ProgramDataBaseFileName=".\Release/" WarningLevel="3" SuppressStartupBanner="TRUE" CompileAs="0"> <IntelOptions Optimization="2" InlineFuncExpansion="1" OmitFramePtrs="1" StringPooling="1" RuntimeLibrary="2" BufferSecurityCheck="1" FunctionLevelLinking="1" AllOptions="/c /I &quot;..\src&quot; /nologo /W3 /O2 /Ob1 /Oy /D &quot;WIN32&quot; /D &quot;NDEBUG&quot; /D &quot;_CONSOLE&quot; /D &quot;_WINDOWS&quot; /D &quot;_MBCS&quot; /GF /FD /EHsc /MD /GS /Gy /Fp&quot;.\Release/TestBase64Client.pch&quot; /Fo&quot;.\Release/&quot; /Fd&quot;.\Release/&quot; /Gd"/> </Tool> <Tool Name="VCCustomBuildTool"/> <Tool Name="VCLinkerTool" AdditionalOptions="/MACHINE:I386" AdditionalDependencies="xmlrpc.lib Ws2_32.lib odbc32.lib odbccp32.lib" OutputFile=".\Release/TestBase64Client.exe" LinkIncremental="1" SuppressStartupBanner="TRUE" AdditionalLibraryDirectories="..\release" ProgramDatabaseFile=".\Release/TestBase64Client.pdb" SubSystem="1"> <IntelOptions AllOptions="/NOLOGO /OUT:&quot;.\Release/TestBase64Client.exe&quot; /INCREMENTAL:NO /LIBPATH:&quot;..\release&quot; xmlrpc.lib Ws2_32.lib odbc32.lib odbccp32.lib /PDB:&quot;.\Release/TestBase64Client.pdb&quot; /SUBSYSTEM:CONSOLE /TLBID:1 /MACHINE:I386 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib"/> </Tool> <Tool Name="VCMIDLTool" TypeLibraryName=".\Release/TestBase64Client.tlb"/> <Tool Name="VCPostBuildEventTool"/> <Tool Name="VCPreBuildEventTool"/> <Tool Name="VCPreLinkEventTool"/> <Tool Name="VCResourceCompilerTool" PreprocessorDefinitions="NDEBUG" Culture="1033"/> <Tool Name="VCWebServiceProxyGeneratorTool"/> <Tool Name="VCWebDeploymentTool"/> <IntelOptions CompilerName="1"/> </Configuration> </Configurations> <Files> <Filter Name="Source Files" Filter="cpp;c;cxx;rc;def;r;odl;idl;hpj;bat"> <File RelativePath=".\TestBase64Client.cpp"/> </Filter> </Files> <Globals/> </VisualStudioProject>
0
apollo_public_repos/apollo-platform/ros/ros_comm/xmlrpcpp
apollo_public_repos/apollo-platform/ros/ros_comm/xmlrpcpp/test/TestXml.cpp
// TestXml.cpp : Test XML encoding and decoding. // The characters <>&'" are illegal in xml and must be encoded. #define WIN32_LEAN_AND_MEAN // Exclude rarely-used stuff from Windows headers #include <iostream> // If you are using MSVC++6, you should update <string> to fix // BUG: getline Template Function Reads Extra Character #include <string> #include <assert.h> #include <stdlib.h> #include "XmlRpcUtil.h" using namespace XmlRpc; int main(int argc, char* argv[]) { // Basic tests std::string empty; assert(empty == XmlRpcUtil::xmlEncode(empty)); assert(empty == XmlRpcUtil::xmlDecode(empty)); assert(empty == XmlRpcUtil::xmlEncode("")); assert(empty == XmlRpcUtil::xmlDecode("")); std::string raw("<>&'\""); assert(XmlRpcUtil::xmlDecode(XmlRpcUtil::xmlEncode(raw)) == raw); std::cout << "Basic tests passed.\n"; // Interactive tests std::string s; for (;;) { std::cout << "\nEnter line of raw text to encode:\n"; std::getline(std::cin, s); if (s.empty()) break; std::cout << XmlRpcUtil::xmlEncode(s) << std::endl; } for (;;) { std::cout << "\nEnter line of xml-encoded text to decode:\n"; std::getline(std::cin, s); if (s.empty()) break; std::cout << XmlRpcUtil::xmlDecode(s) << std::endl; } return 0; }
0
apollo_public_repos/apollo-platform/ros/ros_comm/xmlrpcpp
apollo_public_repos/apollo-platform/ros/ros_comm/xmlrpcpp/test/arrayOfStructsTest.xml
<?xml version="1.0"?> <methodCall> <methodName>validator1.arrayOfStructsTest</methodName> <params> <param> <value><array> <data> <value> <struct> <member> <name>curly</name> <value> <i4>-84</i4> </value> </member> <member> <name>larry</name> <value> <i4>87</i4> </value> </member> <member> <name>moe</name> <value> <i4>77</i4> </value> </member> </struct> </value> <value> <struct> <member> <name>curly</name> <value> <i4>-46</i4> </value> </member> <member> <name>larry</name> <value> <i4>27</i4> </value> </member> <member> <name>moe</name> <value> <i4>33</i4> </value> </member> </struct> </value> <value> <struct> <member> <name>curly</name> <value> <i4>-70</i4> </value> </member> <member> <name>larry</name> <value> <i4>89</i4> </value> </member> <member> <name>moe</name> <value> <i4>30</i4> </value> </member> </struct> </value> <value> <struct> <member> <name>curly</name> <value> <i4>-90</i4> </value> </member> <member> <name>larry</name> <value> <i4>42</i4> </value> </member> <member> <name>moe</name> <value> <i4>6</i4> </value> </member> </struct> </value> <value> <struct> <member> <name>curly</name> <value> <i4>-28</i4> </value> </member> <member> <name>larry</name> <value> <i4>96</i4> </value> </member> <member> <name>moe</name> <value> <i4>92</i4> </value> </member> </struct> </value> <value> <struct> <member> <name>curly</name> <value> <i4>-31</i4> </value> </member> <member> <name>larry</name> <value> <i4>81</i4> </value> </member> <member> <name>moe</name> <value> <i4>85</i4> </value> </member> </struct> </value> <value> <struct> <member> <name>curly</name> <value> <i4>-18</i4> </value> </member> <member> <name>larry</name> <value> <i4>62</i4> </value> </member> <member> <name>moe</name> <value> <i4>9</i4> </value> </member> </struct> </value> <value> <struct> <member> <name>curly</name> <value> <i4>-98</i4> </value> </member> <member> <name>larry</name> <value> <i4>79</i4> </value> </member> <member> <name>moe</name> <value> <i4>66</i4> </value> </member> </struct> </value> <value> <struct> <member> <name>curly</name> <value> <i4>-3</i4> </value> </member> <member> <name>larry</name> <value> <i4>59</i4> </value> </member> <member> <name>moe</name> <value> <i4>80</i4> </value> </member> </struct> </value> <value> <struct> <member> <name>curly</name> <value> <i4>-83</i4> </value> </member> <member> <name>larry</name> <value> <i4>27</i4> </value> </member> <member> <name>moe</name> <value> <i4>19</i4> </value> </member> </struct> </value> <value> <struct> <member> <name>curly</name> <value> <i4>-85</i4> </value> </member> <member> <name>larry</name> <value> <i4>4</i4> </value> </member> <member> <name>moe</name> <value> <i4>16</i4> </value> </member> </struct> </value> </data> </array></value> </param> </params> </methodCall>
0
apollo_public_repos/apollo-platform/ros/ros_comm/xmlrpcpp
apollo_public_repos/apollo-platform/ros/ros_comm/xmlrpcpp/test/easyStructTest.xml
<?xml version="1.0"?> <methodCall> <methodName>validator1.easyStructTest</methodName> <params> <param> <value><struct> <member> <name>curly</name> <value> <i4>-78</i4> </value> </member> <member> <name>larry</name> <value> <i4>23</i4> </value> </member> <member> <name>moe</name> <value> <i4>38</i4> </value> </member> </struct></value> </param> </params> </methodCall>
0
apollo_public_repos/apollo-platform/ros/ros_comm/xmlrpcpp
apollo_public_repos/apollo-platform/ros/ros_comm/xmlrpcpp/test/countTheEntities.xml
<?xml version="1.0"?> <methodCall> <methodName>validator1.countTheEntities</methodName> <params> <param> <value>&'<p"dgt"&>'<&"'<s>>ehv<j><>iu'<<<y"'>qo>"z"f<l&'"akn<&r'c'wbm&&x''</value> </param> </params> </methodCall>
0
apollo_public_repos/apollo-platform/ros/ros_comm/xmlrpcpp
apollo_public_repos/apollo-platform/ros/ros_comm/xmlrpcpp/test/Makefile
# makefile written for gnu make CXX = g++ SRC = ../src CPPFLAGS = -I$(SRC) DEBUG = -g #OPTIMIZE = -O2 GCCWARN = -Wall CXXFLAGS = $(DEBUG) $(GCCWARN) $(OPTIMIZE) $(INCLUDES) LIB = ../libXmlRpc.a # Add your system-dependent network libs here # Solaris: -lsocket -lnsl SYSTEMLIBS = LDLIBS = $(SYSTEMLIBS) $(LIB) TESTS = HelloClient HelloServer TestBase64Client TestBase64Server TestValues TestXml Validator port_zero_server bool_test all: $(TESTS) $(TESTS): $(LIB) clean: rm -f *.o rm -f $(TESTS)
0
apollo_public_repos/apollo-platform/ros/ros_comm/xmlrpcpp
apollo_public_repos/apollo-platform/ros/ros_comm/xmlrpcpp/test/bool_test.cpp
// bool_test.cpp : make sure bool variables copy around ok #include "XmlRpc.h" #include <iostream> #include <stdlib.h> using namespace XmlRpc; using namespace std; int main(int argc, char* argv[]) { XmlRpcValue v(bool(false)); cout << v.toXml() << endl; XmlRpcValue v2; v2[0] = int(1); v2[1] = string(); v2[2] = XmlRpcValue(false); cout << v2.toXml() << endl; return 0; }
0
apollo_public_repos/apollo-platform/ros/ros_comm/xmlrpcpp
apollo_public_repos/apollo-platform/ros/ros_comm/xmlrpcpp/test/TestBase64Server.vcproj
<?xml version="1.0" encoding = "Windows-1252"?> <VisualStudioProject ProjectType="Visual C++" Version="7.00" Name="TestBase64Server" ProjectGUID="{D3107CC6-6300-47DE-B183-255B75CFE85A}" SccProjectName="" SccLocalPath=""> <Platforms> <Platform Name="Win32"/> </Platforms> <Configurations> <Configuration Name="Release|Win32" OutputDirectory=".\Release" IntermediateDirectory=".\Release" ConfigurationType="1" UseOfMFC="0" ATLMinimizesCRunTimeLibraryUsage="FALSE" CharacterSet="2"> <Tool Name="VCCLCompilerTool" InlineFunctionExpansion="1" AdditionalIncludeDirectories="..\src" PreprocessorDefinitions="WIN32,NDEBUG,_CONSOLE,_WINDOWS" StringPooling="TRUE" RuntimeLibrary="2" EnableFunctionLevelLinking="TRUE" PrecompiledHeaderFile=".\Release/TestBase64Server.pch" AssemblerListingLocation=".\Release/" ObjectFile=".\Release/" ProgramDataBaseFileName=".\Release/" WarningLevel="3" SuppressStartupBanner="TRUE" CompileAs="0"> <IntelOptions Optimization="2" InlineFuncExpansion="1" OmitFramePtrs="1" StringPooling="1" RuntimeLibrary="2" BufferSecurityCheck="1" FunctionLevelLinking="1" AllOptions="/c /I &quot;..\src&quot; /nologo /W3 /O2 /Ob1 /Oy /D &quot;WIN32&quot; /D &quot;NDEBUG&quot; /D &quot;_CONSOLE&quot; /D &quot;_WINDOWS&quot; /D &quot;_MBCS&quot; /GF /FD /EHsc /MD /GS /Gy /Fp&quot;.\Release/TestBase64Server.pch&quot; /Fo&quot;.\Release/&quot; /Fd&quot;.\Release/&quot; /Gd"/> </Tool> <Tool Name="VCCustomBuildTool"/> <Tool Name="VCLinkerTool" AdditionalOptions="/MACHINE:I386" AdditionalDependencies="xmlrpc.lib Ws2_32.lib odbc32.lib odbccp32.lib" OutputFile=".\Release/TestBase64Server.exe" LinkIncremental="1" SuppressStartupBanner="TRUE" AdditionalLibraryDirectories="..\release" ProgramDatabaseFile=".\Release/TestBase64Server.pdb" SubSystem="1"> <IntelOptions AllOptions="/NOLOGO /OUT:&quot;.\Release/TestBase64Server.exe&quot; /INCREMENTAL:NO /LIBPATH:&quot;..\release&quot; xmlrpc.lib Ws2_32.lib odbc32.lib odbccp32.lib /PDB:&quot;.\Release/TestBase64Server.pdb&quot; /SUBSYSTEM:CONSOLE /TLBID:1 /MACHINE:I386 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib"/> </Tool> <Tool Name="VCMIDLTool" TypeLibraryName=".\Release/TestBase64Server.tlb"/> <Tool Name="VCPostBuildEventTool"/> <Tool Name="VCPreBuildEventTool"/> <Tool Name="VCPreLinkEventTool"/> <Tool Name="VCResourceCompilerTool" PreprocessorDefinitions="NDEBUG" Culture="1033"/> <Tool Name="VCWebServiceProxyGeneratorTool"/> <Tool Name="VCWebDeploymentTool"/> <IntelOptions CompilerName="1"/> </Configuration> <Configuration Name="Debug|Win32" OutputDirectory=".\Debug" IntermediateDirectory=".\Debug" ConfigurationType="1" UseOfMFC="0" ATLMinimizesCRunTimeLibraryUsage="FALSE" CharacterSet="2"> <Tool Name="VCCLCompilerTool" Optimization="0" AdditionalIncludeDirectories="..\src" PreprocessorDefinitions="WIN32,_DEBUG,_CONSOLE,_WINDOWS" BasicRuntimeChecks="3" RuntimeLibrary="3" PrecompiledHeaderFile=".\Debug/TestBase64Server.pch" AssemblerListingLocation=".\Debug/" ObjectFile=".\Debug/" ProgramDataBaseFileName=".\Debug/" WarningLevel="3" SuppressStartupBanner="TRUE" DebugInformationFormat="4" CompileAs="0"> <IntelOptions Optimization="0" MinimalRebuild="1" BasicRuntimeChecks="3" RuntimeLibrary="3" AllOptions="/c /I &quot;..\src&quot; /ZI /nologo /W3 /Od /D &quot;WIN32&quot; /D &quot;_DEBUG&quot; /D &quot;_CONSOLE&quot; /D &quot;_WINDOWS&quot; /D &quot;_MBCS&quot; /Gm /EHsc /RTC1 /MDd /Fp&quot;.\Debug/TestBase64Server.pch&quot; /Fo&quot;.\Debug/&quot; /Fd&quot;.\Debug/&quot; /Gd"/> </Tool> <Tool Name="VCCustomBuildTool"/> <Tool Name="VCLinkerTool" AdditionalOptions="/MACHINE:I386" AdditionalDependencies="xmlrpc.lib Ws2_32.lib odbc32.lib odbccp32.lib" OutputFile=".\Debug/TestBase64Server.exe" LinkIncremental="2" SuppressStartupBanner="TRUE" AdditionalLibraryDirectories="..\Debug" GenerateDebugInformation="TRUE" ProgramDatabaseFile=".\Debug/TestBase64Server.pdb" SubSystem="1"> <IntelOptions AllOptions="/NOLOGO /OUT:&quot;.\Debug/TestBase64Server.exe&quot; /INCREMENTAL /LIBPATH:&quot;..\Debug&quot; xmlrpc.lib Ws2_32.lib odbc32.lib odbccp32.lib /DEBUG /PDB:&quot;.\Debug/TestBase64Server.pdb&quot; /SUBSYSTEM:CONSOLE /TLBID:1 /MACHINE:I386 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib"/> </Tool> <Tool Name="VCMIDLTool" TypeLibraryName=".\Debug/TestBase64Server.tlb"/> <Tool Name="VCPostBuildEventTool"/> <Tool Name="VCPreBuildEventTool"/> <Tool Name="VCPreLinkEventTool"/> <Tool Name="VCResourceCompilerTool" PreprocessorDefinitions="_DEBUG" Culture="1033"/> <Tool Name="VCWebServiceProxyGeneratorTool"/> <Tool Name="VCWebDeploymentTool"/> <IntelOptions CompilerName="1"/> </Configuration> </Configurations> <Files> <Filter Name="Source Files" Filter="cpp;c;cxx;rc;def;r;odl;idl;hpj;bat"> <File RelativePath=".\TestBase64Server.cpp"/> </Filter> </Files> <Globals/> </VisualStudioProject>
0
apollo_public_repos/apollo-platform/ros/ros_comm/xmlrpcpp
apollo_public_repos/apollo-platform/ros/ros_comm/xmlrpcpp/test/FileClient.dsp
# Microsoft Developer Studio Project File - Name="FileClient" - Package Owner=<4> # Microsoft Developer Studio Generated Build File, Format Version 6.00 # ** DO NOT EDIT ** # TARGTYPE "Win32 (x86) Console Application" 0x0103 CFG=FileClient - Win32 Debug !MESSAGE This is not a valid makefile. To build this project using NMAKE, !MESSAGE use the Export Makefile command and run !MESSAGE !MESSAGE NMAKE /f "FileClient.mak". !MESSAGE !MESSAGE You can specify a configuration when running NMAKE !MESSAGE by defining the macro CFG on the command line. For example: !MESSAGE !MESSAGE NMAKE /f "FileClient.mak" CFG="FileClient - Win32 Debug" !MESSAGE !MESSAGE Possible choices for configuration are: !MESSAGE !MESSAGE "FileClient - Win32 Release" (based on "Win32 (x86) Console Application") !MESSAGE "FileClient - Win32 Debug" (based on "Win32 (x86) Console Application") !MESSAGE # Begin Project # PROP AllowPerConfigDependencies 0 # PROP Scc_ProjName "" # PROP Scc_LocalPath "" CPP=cl.exe RSC=rc.exe !IF "$(CFG)" == "FileClient - Win32 Release" # PROP BASE Use_MFC 0 # PROP BASE Use_Debug_Libraries 0 # PROP BASE Output_Dir "Release" # PROP BASE Intermediate_Dir "Release" # PROP BASE Target_Dir "" # PROP Use_MFC 0 # PROP Use_Debug_Libraries 0 # PROP Output_Dir "Release" # PROP Intermediate_Dir "Release" # PROP Ignore_Export_Lib 0 # PROP Target_Dir "" # ADD BASE CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_CONSOLE" /D "_MBCS" /Yu"stdafx.h" /FD /c # ADD CPP /nologo /MD /W3 /GX /O2 /I "..\src" /D "WIN32" /D "NDEBUG" /D "_CONSOLE" /D "_MBCS" /D "_WINDOWS" /FD /c # SUBTRACT CPP /YX /Yc /Yu # ADD BASE RSC /l 0x409 /d "NDEBUG" # ADD RSC /l 0x409 /d "NDEBUG" BSC32=bscmake.exe # ADD BASE BSC32 /nologo # ADD BSC32 /nologo LINK32=link.exe # ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /machine:I386 # ADD LINK32 xmlrpc.lib Ws2_32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /machine:I386 /libpath:"..\release" !ELSEIF "$(CFG)" == "FileClient - Win32 Debug" # PROP BASE Use_MFC 0 # PROP BASE Use_Debug_Libraries 1 # PROP BASE Output_Dir "Debug" # PROP BASE Intermediate_Dir "Debug" # PROP BASE Target_Dir "" # PROP Use_MFC 0 # PROP Use_Debug_Libraries 1 # PROP Output_Dir "Debug" # PROP Intermediate_Dir "Debug" # PROP Ignore_Export_Lib 0 # PROP Target_Dir "" # ADD BASE CPP /nologo /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_CONSOLE" /D "_MBCS" /Yu"stdafx.h" /FD /GZ /c # ADD CPP /nologo /MDd /W3 /Gm /GX /ZI /Od /I "..\src" /D "WIN32" /D "_DEBUG" /D "_CONSOLE" /D "_MBCS" /D "_WINDOWS" /FD /GZ /c # SUBTRACT CPP /YX /Yc /Yu # ADD BASE RSC /l 0x409 /d "_DEBUG" # ADD RSC /l 0x409 /d "_DEBUG" BSC32=bscmake.exe # ADD BASE BSC32 /nologo # ADD BSC32 /nologo LINK32=link.exe # ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /debug /machine:I386 /pdbtype:sept # ADD LINK32 xmlrpc.lib Ws2_32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /debug /machine:I386 /pdbtype:sept /libpath:"..\Debug" !ENDIF # Begin Target # Name "FileClient - Win32 Release" # Name "FileClient - Win32 Debug" # Begin Group "Source Files" # PROP Default_Filter "cpp;c;cxx;rc;def;r;odl;idl;hpj;bat" # Begin Source File SOURCE=.\FileClient.cpp # End Source File # End Group # End Target # End Project
0
apollo_public_repos/apollo-platform/ros/ros_comm/xmlrpcpp
apollo_public_repos/apollo-platform/ros/ros_comm/xmlrpcpp/test/HelloServer.cpp
// HelloServer.cpp : Simple XMLRPC server example. Usage: HelloServer serverPort // #include "XmlRpc.h" #include <iostream> #include <stdlib.h> using namespace XmlRpc; // The server XmlRpcServer s; // No arguments, result is "Hello". class Hello : public XmlRpcServerMethod { public: Hello(XmlRpcServer* s) : XmlRpcServerMethod("Hello", s) {} void execute(XmlRpcValue& params, XmlRpcValue& result) { result = "Hello"; } std::string help() { return std::string("Say hello"); } } hello(&s); // This constructor registers the method with the server // One argument is passed, result is "Hello, " + arg. class HelloName : public XmlRpcServerMethod { public: HelloName(XmlRpcServer* s) : XmlRpcServerMethod("HelloName", s) {} void execute(XmlRpcValue& params, XmlRpcValue& result) { std::string resultString = "Hello, "; resultString += std::string(params[0]); result = resultString; } } helloName(&s); // A variable number of arguments are passed, all doubles, result is their sum. class Sum : public XmlRpcServerMethod { public: Sum(XmlRpcServer* s) : XmlRpcServerMethod("Sum", s) {} void execute(XmlRpcValue& params, XmlRpcValue& result) { int nArgs = params.size(); double sum = 0.0; for (int i=0; i<nArgs; ++i) sum += double(params[i]); result = sum; } } sum(&s); int main(int argc, char* argv[]) { if (argc != 2) { std::cerr << "Usage: HelloServer serverPort\n"; return -1; } int port = atoi(argv[1]); XmlRpc::setVerbosity(5); // Create the server socket on the specified port s.bindAndListen(port); // Enable introspection s.enableIntrospection(true); // Wait for requests indefinitely s.work(-1.0); return 0; }
0
apollo_public_repos/apollo-platform/ros/ros_comm/xmlrpcpp
apollo_public_repos/apollo-platform/ros/ros_comm/xmlrpcpp/test/TestBase64Server.dsp
# Microsoft Developer Studio Project File - Name="TestBase64Server" - Package Owner=<4> # Microsoft Developer Studio Generated Build File, Format Version 6.00 # ** DO NOT EDIT ** # TARGTYPE "Win32 (x86) Console Application" 0x0103 CFG=TestBase64Server - Win32 Debug !MESSAGE This is not a valid makefile. To build this project using NMAKE, !MESSAGE use the Export Makefile command and run !MESSAGE !MESSAGE NMAKE /f "TestBase64Server.mak". !MESSAGE !MESSAGE You can specify a configuration when running NMAKE !MESSAGE by defining the macro CFG on the command line. For example: !MESSAGE !MESSAGE NMAKE /f "TestBase64Server.mak" CFG="TestBase64Server - Win32 Debug" !MESSAGE !MESSAGE Possible choices for configuration are: !MESSAGE !MESSAGE "TestBase64Server - Win32 Release" (based on "Win32 (x86) Console Application") !MESSAGE "TestBase64Server - Win32 Debug" (based on "Win32 (x86) Console Application") !MESSAGE # Begin Project # PROP AllowPerConfigDependencies 0 # PROP Scc_ProjName "" # PROP Scc_LocalPath "" CPP=cl.exe RSC=rc.exe !IF "$(CFG)" == "TestBase64Server - Win32 Release" # PROP BASE Use_MFC 0 # PROP BASE Use_Debug_Libraries 0 # PROP BASE Output_Dir "Release" # PROP BASE Intermediate_Dir "Release" # PROP BASE Target_Dir "" # PROP Use_MFC 0 # PROP Use_Debug_Libraries 0 # PROP Output_Dir "Release" # PROP Intermediate_Dir "Release" # PROP Ignore_Export_Lib 0 # PROP Target_Dir "" # ADD BASE CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_CONSOLE" /D "_MBCS" /Yu"stdafx.h" /FD /c # ADD CPP /nologo /MD /W3 /GX /O2 /I "..\src" /D "WIN32" /D "NDEBUG" /D "_CONSOLE" /D "_MBCS" /D "_WINDOWS" /FD /c # SUBTRACT CPP /Fr /YX /Yc /Yu # ADD BASE RSC /l 0x409 /d "NDEBUG" # ADD RSC /l 0x409 /d "NDEBUG" BSC32=bscmake.exe # ADD BASE BSC32 /nologo # ADD BSC32 /nologo LINK32=link.exe # ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /machine:I386 # ADD LINK32 xmlrpc.lib Ws2_32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /machine:I386 /libpath:"..\release" !ELSEIF "$(CFG)" == "TestBase64Server - Win32 Debug" # PROP BASE Use_MFC 0 # PROP BASE Use_Debug_Libraries 1 # PROP BASE Output_Dir "Debug" # PROP BASE Intermediate_Dir "Debug" # PROP BASE Target_Dir "" # PROP Use_MFC 0 # PROP Use_Debug_Libraries 1 # PROP Output_Dir "Debug" # PROP Intermediate_Dir "Debug" # PROP Ignore_Export_Lib 0 # PROP Target_Dir "" # ADD BASE CPP /nologo /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_CONSOLE" /D "_MBCS" /Yu"stdafx.h" /FD /GZ /c # ADD CPP /nologo /MDd /W3 /Gm /GX /ZI /Od /I "..\src" /D "WIN32" /D "_DEBUG" /D "_CONSOLE" /D "_MBCS" /D "_WINDOWS" /FD /GZ /c # SUBTRACT CPP /YX /Yc /Yu # ADD BASE RSC /l 0x409 /d "_DEBUG" # ADD RSC /l 0x409 /d "_DEBUG" BSC32=bscmake.exe # ADD BASE BSC32 /nologo # ADD BSC32 /nologo LINK32=link.exe # ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /debug /machine:I386 /pdbtype:sept # ADD LINK32 xmlrpc.lib Ws2_32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /debug /machine:I386 /pdbtype:sept /libpath:"..\Debug" !ENDIF # Begin Target # Name "TestBase64Server - Win32 Release" # Name "TestBase64Server - Win32 Debug" # Begin Group "Source Files" # PROP Default_Filter "cpp;c;cxx;rc;def;r;odl;idl;hpj;bat" # Begin Source File SOURCE=.\TestBase64Server.cpp # End Source File # End Group # End Target # End Project
0
apollo_public_repos/apollo-platform/ros/ros_comm/xmlrpcpp
apollo_public_repos/apollo-platform/ros/ros_comm/xmlrpcpp/test/TestXml.vcproj
<?xml version="1.0" encoding = "Windows-1252"?> <VisualStudioProject ProjectType="Visual C++" Version="7.00" Name="TestXml" ProjectGUID="{6F0C2ADA-0341-4183-8FAA-576668F1788A}" SccProjectName="" SccLocalPath=""> <Platforms> <Platform Name="Win32"/> </Platforms> <Configurations> <Configuration Name="Release|Win32" OutputDirectory=".\Release" IntermediateDirectory=".\Release" ConfigurationType="1" UseOfMFC="0" ATLMinimizesCRunTimeLibraryUsage="FALSE" CharacterSet="2"> <Tool Name="VCCLCompilerTool" InlineFunctionExpansion="1" AdditionalIncludeDirectories="..\src" PreprocessorDefinitions="WIN32,NDEBUG,_CONSOLE" StringPooling="TRUE" RuntimeLibrary="2" EnableFunctionLevelLinking="TRUE" PrecompiledHeaderFile=".\Release/TestXml.pch" AssemblerListingLocation=".\Release/" ObjectFile=".\Release/" ProgramDataBaseFileName=".\Release/" WarningLevel="3" SuppressStartupBanner="TRUE" CompileAs="0"> <IntelOptions Optimization="2" InlineFuncExpansion="1" OmitFramePtrs="1" StringPooling="1" RuntimeLibrary="2" BufferSecurityCheck="1" FunctionLevelLinking="1" AllOptions="/c /I &quot;..\src&quot; /nologo /W3 /O2 /Ob1 /Oy /D &quot;WIN32&quot; /D &quot;NDEBUG&quot; /D &quot;_CONSOLE&quot; /D &quot;_MBCS&quot; /GF /FD /EHsc /MD /GS /Gy /Fp&quot;.\Release/TestXml.pch&quot; /Fo&quot;.\Release/&quot; /Fd&quot;.\Release/&quot; /Gd"/> </Tool> <Tool Name="VCCustomBuildTool"/> <Tool Name="VCLinkerTool" AdditionalOptions="/MACHINE:I386" AdditionalDependencies="xmlrpc.lib odbc32.lib odbccp32.lib" OutputFile=".\Release/TestXml.exe" LinkIncremental="1" SuppressStartupBanner="TRUE" AdditionalLibraryDirectories="..\release" ProgramDatabaseFile=".\Release/TestXml.pdb" SubSystem="1"> <IntelOptions AllOptions="/NOLOGO /OUT:&quot;.\Release/TestXml.exe&quot; /INCREMENTAL:NO /LIBPATH:&quot;..\release&quot; xmlrpc.lib odbc32.lib odbccp32.lib /PDB:&quot;.\Release/TestXml.pdb&quot; /SUBSYSTEM:CONSOLE /TLBID:1 /MACHINE:I386 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib"/> </Tool> <Tool Name="VCMIDLTool" TypeLibraryName=".\Release/TestXml.tlb"/> <Tool Name="VCPostBuildEventTool"/> <Tool Name="VCPreBuildEventTool"/> <Tool Name="VCPreLinkEventTool"/> <Tool Name="VCResourceCompilerTool" PreprocessorDefinitions="NDEBUG" Culture="1033"/> <Tool Name="VCWebServiceProxyGeneratorTool"/> <Tool Name="VCWebDeploymentTool"/> <IntelOptions CompilerName="1"/> </Configuration> <Configuration Name="Debug|Win32" OutputDirectory=".\Debug" IntermediateDirectory=".\Debug" ConfigurationType="1" UseOfMFC="0" ATLMinimizesCRunTimeLibraryUsage="FALSE" CharacterSet="2"> <Tool Name="VCCLCompilerTool" Optimization="0" AdditionalIncludeDirectories="..\src" PreprocessorDefinitions="WIN32,_DEBUG,_CONSOLE" BasicRuntimeChecks="3" RuntimeLibrary="3" PrecompiledHeaderFile=".\Debug/TestXml.pch" AssemblerListingLocation=".\Debug/" ObjectFile=".\Debug/" ProgramDataBaseFileName=".\Debug/" WarningLevel="3" SuppressStartupBanner="TRUE" DebugInformationFormat="4" CompileAs="0"> <IntelOptions Optimization="0" MinimalRebuild="1" BasicRuntimeChecks="3" RuntimeLibrary="3" AllOptions="/c /I &quot;..\src&quot; /ZI /nologo /W3 /Od /D &quot;WIN32&quot; /D &quot;_DEBUG&quot; /D &quot;_CONSOLE&quot; /D &quot;_MBCS&quot; /Gm /EHsc /RTC1 /MDd /Fp&quot;.\Debug/TestXml.pch&quot; /Fo&quot;.\Debug/&quot; /Fd&quot;.\Debug/&quot; /Gd"/> </Tool> <Tool Name="VCCustomBuildTool"/> <Tool Name="VCLinkerTool" AdditionalOptions="/MACHINE:I386" AdditionalDependencies="xmlrpc.lib odbc32.lib odbccp32.lib" OutputFile=".\Debug/TestXml.exe" LinkIncremental="2" SuppressStartupBanner="TRUE" AdditionalLibraryDirectories="..\Debug" GenerateDebugInformation="TRUE" ProgramDatabaseFile=".\Debug/TestXml.pdb" SubSystem="1"> <IntelOptions AllOptions="/NOLOGO /OUT:&quot;.\Debug/TestXml.exe&quot; /INCREMENTAL /LIBPATH:&quot;..\Debug&quot; xmlrpc.lib odbc32.lib odbccp32.lib /DEBUG /PDB:&quot;.\Debug/TestXml.pdb&quot; /SUBSYSTEM:CONSOLE /TLBID:1 /MACHINE:I386 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib"/> </Tool> <Tool Name="VCMIDLTool" TypeLibraryName=".\Debug/TestXml.tlb"/> <Tool Name="VCPostBuildEventTool"/> <Tool Name="VCPreBuildEventTool"/> <Tool Name="VCPreLinkEventTool"/> <Tool Name="VCResourceCompilerTool" PreprocessorDefinitions="_DEBUG" Culture="1033"/> <Tool Name="VCWebServiceProxyGeneratorTool"/> <Tool Name="VCWebDeploymentTool"/> <IntelOptions CompilerName="1"/> </Configuration> </Configurations> <Files> <Filter Name="Source Files" Filter="cpp;c;cxx;rc;def;r;odl;idl;hpj;bat"> <File RelativePath=".\TestXml.cpp"/> </Filter> </Files> <Globals/> </VisualStudioProject>
0
apollo_public_repos/apollo-platform/ros/ros_comm/xmlrpcpp
apollo_public_repos/apollo-platform/ros/ros_comm/xmlrpcpp/test/TestXml.dsp
# Microsoft Developer Studio Project File - Name="TestXml" - Package Owner=<4> # Microsoft Developer Studio Generated Build File, Format Version 6.00 # ** DO NOT EDIT ** # TARGTYPE "Win32 (x86) Console Application" 0x0103 CFG=TestXml - Win32 Debug !MESSAGE This is not a valid makefile. To build this project using NMAKE, !MESSAGE use the Export Makefile command and run !MESSAGE !MESSAGE NMAKE /f "TestXml.mak". !MESSAGE !MESSAGE You can specify a configuration when running NMAKE !MESSAGE by defining the macro CFG on the command line. For example: !MESSAGE !MESSAGE NMAKE /f "TestXml.mak" CFG="TestXml - Win32 Debug" !MESSAGE !MESSAGE Possible choices for configuration are: !MESSAGE !MESSAGE "TestXml - Win32 Release" (based on "Win32 (x86) Console Application") !MESSAGE "TestXml - Win32 Debug" (based on "Win32 (x86) Console Application") !MESSAGE # Begin Project # PROP AllowPerConfigDependencies 0 # PROP Scc_ProjName "" # PROP Scc_LocalPath "" CPP=cl.exe RSC=rc.exe !IF "$(CFG)" == "TestXml - Win32 Release" # PROP BASE Use_MFC 0 # PROP BASE Use_Debug_Libraries 0 # PROP BASE Output_Dir "Release" # PROP BASE Intermediate_Dir "Release" # PROP BASE Target_Dir "" # PROP Use_MFC 0 # PROP Use_Debug_Libraries 0 # PROP Output_Dir "Release" # PROP Intermediate_Dir "Release" # PROP Ignore_Export_Lib 0 # PROP Target_Dir "" # ADD BASE CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_CONSOLE" /D "_MBCS" /Yu"stdafx.h" /FD /c # ADD CPP /nologo /MD /W3 /GX /O2 /I "..\src" /D "WIN32" /D "NDEBUG" /D "_CONSOLE" /D "_MBCS" /FD /c # SUBTRACT CPP /YX /Yc /Yu # ADD BASE RSC /l 0x409 /d "NDEBUG" # ADD RSC /l 0x409 /d "NDEBUG" BSC32=bscmake.exe # ADD BASE BSC32 /nologo # ADD BSC32 /nologo LINK32=link.exe # ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /machine:I386 # ADD LINK32 xmlrpc.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /machine:I386 /libpath:"..\release" !ELSEIF "$(CFG)" == "TestXml - Win32 Debug" # PROP BASE Use_MFC 0 # PROP BASE Use_Debug_Libraries 1 # PROP BASE Output_Dir "Debug" # PROP BASE Intermediate_Dir "Debug" # PROP BASE Target_Dir "" # PROP Use_MFC 0 # PROP Use_Debug_Libraries 1 # PROP Output_Dir "Debug" # PROP Intermediate_Dir "Debug" # PROP Ignore_Export_Lib 0 # PROP Target_Dir "" # ADD BASE CPP /nologo /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_CONSOLE" /D "_MBCS" /Yu"stdafx.h" /FD /GZ /c # ADD CPP /nologo /MDd /W3 /Gm /GX /ZI /Od /I "..\src" /D "WIN32" /D "_DEBUG" /D "_CONSOLE" /D "_MBCS" /FD /GZ /c # SUBTRACT CPP /YX /Yc /Yu # ADD BASE RSC /l 0x409 /d "_DEBUG" # ADD RSC /l 0x409 /d "_DEBUG" BSC32=bscmake.exe # ADD BASE BSC32 /nologo # ADD BSC32 /nologo LINK32=link.exe # ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /debug /machine:I386 /pdbtype:sept # ADD LINK32 xmlrpc.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /debug /machine:I386 /pdbtype:sept /libpath:"..\Debug" !ENDIF # Begin Target # Name "TestXml - Win32 Release" # Name "TestXml - Win32 Debug" # Begin Group "Source Files" # PROP Default_Filter "cpp;c;cxx;rc;def;r;odl;idl;hpj;bat" # Begin Source File SOURCE=.\TestXml.cpp # End Source File # End Group # End Target # End Project
0
apollo_public_repos/apollo-platform/ros/ros_comm/xmlrpcpp
apollo_public_repos/apollo-platform/ros/ros_comm/xmlrpcpp/test/echo.xml
<?xml version="1.0"?> <methodCall> <methodName>echo</methodName> <params> <param><value><string>Hello Chris</string></value></param> <param><value><i4>123</i4></value></param> </params> </methodCall>
0
apollo_public_repos/apollo-platform/ros/ros_comm/xmlrpcpp
apollo_public_repos/apollo-platform/ros/ros_comm/xmlrpcpp/test/FileClient.vcproj
<?xml version="1.0" encoding = "Windows-1252"?> <VisualStudioProject ProjectType="Visual C++" Version="7.00" Name="FileClient" ProjectGUID="{C3B49855-CD45-448E-991E-3E4C9B02F465}" SccProjectName="" SccLocalPath=""> <Platforms> <Platform Name="Win32"/> </Platforms> <Configurations> <Configuration Name="Release|Win32" OutputDirectory=".\Release" IntermediateDirectory=".\Release" ConfigurationType="1" UseOfMFC="0" ATLMinimizesCRunTimeLibraryUsage="FALSE" CharacterSet="2"> <Tool Name="VCCLCompilerTool" InlineFunctionExpansion="1" AdditionalIncludeDirectories="..\src" PreprocessorDefinitions="WIN32,NDEBUG,_CONSOLE,_WINDOWS" StringPooling="TRUE" RuntimeLibrary="2" EnableFunctionLevelLinking="TRUE" PrecompiledHeaderFile=".\Release/FileClient.pch" AssemblerListingLocation=".\Release/" ObjectFile=".\Release/" ProgramDataBaseFileName=".\Release/" WarningLevel="3" SuppressStartupBanner="TRUE" CompileAs="0"> <IntelOptions Optimization="2" InlineFuncExpansion="1" OmitFramePtrs="1" StringPooling="1" RuntimeLibrary="2" BufferSecurityCheck="1" FunctionLevelLinking="1" AllOptions="/c /I &quot;..\src&quot; /nologo /W3 /O2 /Ob1 /Oy /D &quot;WIN32&quot; /D &quot;NDEBUG&quot; /D &quot;_CONSOLE&quot; /D &quot;_WINDOWS&quot; /D &quot;_MBCS&quot; /GF /FD /EHsc /MD /GS /Gy /Fp&quot;.\Release/FileClient.pch&quot; /Fo&quot;.\Release/&quot; /Fd&quot;.\Release/&quot; /Gd"/> </Tool> <Tool Name="VCCustomBuildTool"/> <Tool Name="VCLinkerTool" AdditionalOptions="/MACHINE:I386" AdditionalDependencies="xmlrpc.lib Ws2_32.lib odbc32.lib odbccp32.lib" OutputFile=".\Release/FileClient.exe" LinkIncremental="1" SuppressStartupBanner="TRUE" AdditionalLibraryDirectories="..\release" ProgramDatabaseFile=".\Release/FileClient.pdb" SubSystem="1"> <IntelOptions AllOptions="/NOLOGO /OUT:&quot;.\Release/FileClient.exe&quot; /INCREMENTAL:NO /LIBPATH:&quot;..\release&quot; xmlrpc.lib Ws2_32.lib odbc32.lib odbccp32.lib /PDB:&quot;.\Release/FileClient.pdb&quot; /SUBSYSTEM:CONSOLE /TLBID:1 /MACHINE:I386 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib"/> </Tool> <Tool Name="VCMIDLTool" TypeLibraryName=".\Release/FileClient.tlb"/> <Tool Name="VCPostBuildEventTool"/> <Tool Name="VCPreBuildEventTool"/> <Tool Name="VCPreLinkEventTool"/> <Tool Name="VCResourceCompilerTool" PreprocessorDefinitions="NDEBUG" Culture="1033"/> <Tool Name="VCWebServiceProxyGeneratorTool"/> <Tool Name="VCWebDeploymentTool"/> <IntelOptions CompilerName="1"/> </Configuration> <Configuration Name="Debug|Win32" OutputDirectory=".\Debug" IntermediateDirectory=".\Debug" ConfigurationType="1" UseOfMFC="0" ATLMinimizesCRunTimeLibraryUsage="FALSE" CharacterSet="2"> <Tool Name="VCCLCompilerTool" Optimization="0" AdditionalIncludeDirectories="..\src" PreprocessorDefinitions="WIN32,_DEBUG,_CONSOLE,_WINDOWS" BasicRuntimeChecks="3" RuntimeLibrary="3" PrecompiledHeaderFile=".\Debug/FileClient.pch" AssemblerListingLocation=".\Debug/" ObjectFile=".\Debug/" ProgramDataBaseFileName=".\Debug/" WarningLevel="3" SuppressStartupBanner="TRUE" DebugInformationFormat="4" CompileAs="0"> <IntelOptions Optimization="0" MinimalRebuild="1" BasicRuntimeChecks="3" RuntimeLibrary="3" AllOptions="/c /I &quot;..\src&quot; /ZI /nologo /W3 /Od /D &quot;WIN32&quot; /D &quot;_DEBUG&quot; /D &quot;_CONSOLE&quot; /D &quot;_WINDOWS&quot; /D &quot;_MBCS&quot; /Gm /EHsc /RTC1 /MDd /Fp&quot;.\Debug/FileClient.pch&quot; /Fo&quot;.\Debug/&quot; /Fd&quot;.\Debug/&quot; /Gd"/> </Tool> <Tool Name="VCCustomBuildTool"/> <Tool Name="VCLinkerTool" AdditionalOptions="/MACHINE:I386" AdditionalDependencies="xmlrpc.lib Ws2_32.lib odbc32.lib odbccp32.lib" OutputFile=".\Debug/FileClient.exe" LinkIncremental="2" SuppressStartupBanner="TRUE" AdditionalLibraryDirectories="..\Debug" GenerateDebugInformation="TRUE" ProgramDatabaseFile=".\Debug/FileClient.pdb" SubSystem="1"> <IntelOptions AllOptions="/NOLOGO /OUT:&quot;.\Debug/FileClient.exe&quot; /INCREMENTAL /LIBPATH:&quot;..\Debug&quot; xmlrpc.lib Ws2_32.lib odbc32.lib odbccp32.lib /DEBUG /PDB:&quot;.\Debug/FileClient.pdb&quot; /SUBSYSTEM:CONSOLE /TLBID:1 /MACHINE:I386 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib"/> </Tool> <Tool Name="VCMIDLTool" TypeLibraryName=".\Debug/FileClient.tlb"/> <Tool Name="VCPostBuildEventTool"/> <Tool Name="VCPreBuildEventTool"/> <Tool Name="VCPreLinkEventTool"/> <Tool Name="VCResourceCompilerTool" PreprocessorDefinitions="_DEBUG" Culture="1033"/> <Tool Name="VCWebServiceProxyGeneratorTool"/> <Tool Name="VCWebDeploymentTool"/> <IntelOptions CompilerName="1"/> </Configuration> </Configurations> <Files> <Filter Name="Source Files" Filter="cpp;c;cxx;rc;def;r;odl;idl;hpj;bat"> <File RelativePath=".\FileClient.cpp"/> </Filter> </Files> <Globals/> </VisualStudioProject>
0
apollo_public_repos/apollo-platform/ros/ros_comm/xmlrpcpp
apollo_public_repos/apollo-platform/ros/ros_comm/xmlrpcpp/test/port_zero_server.cpp
// HelloServer.cpp : Simple XMLRPC server example. Usage: HelloServer serverPort // #include "XmlRpc.h" #include <iostream> #include <stdlib.h> using namespace XmlRpc; // The server XmlRpcServer s; // No arguments, result is "Hello". class Hello : public XmlRpcServerMethod { public: Hello(XmlRpcServer* s) : XmlRpcServerMethod("Hello", s) {} void execute(XmlRpcValue& params, XmlRpcValue& result) { result = "Hello"; } std::string help() { return std::string("Say hello"); } } hello(&s); // This constructor registers the method with the server // One argument is passed, result is "Hello, " + arg. class HelloName : public XmlRpcServerMethod { public: HelloName(XmlRpcServer* s) : XmlRpcServerMethod("HelloName", s) {} void execute(XmlRpcValue& params, XmlRpcValue& result) { std::string resultString = "Hello, "; resultString += std::string(params[0]); result = resultString; } } helloName(&s); // A variable number of arguments are passed, all doubles, result is their sum. class Sum : public XmlRpcServerMethod { public: Sum(XmlRpcServer* s) : XmlRpcServerMethod("Sum", s) {} void execute(XmlRpcValue& params, XmlRpcValue& result) { int nArgs = params.size(); double sum = 0.0; for (int i=0; i<nArgs; ++i) sum += double(params[i]); result = sum; } } sum(&s); int main(int argc, char* argv[]) { XmlRpc::setVerbosity(5); // Create the server socket on the specified port s.bindAndListen(0); // Enable introspection s.enableIntrospection(true); // Wait for requests indefinitely s.work(-1.0); return 0; }
0
apollo_public_repos/apollo-platform/ros/ros_comm/xmlrpcpp
apollo_public_repos/apollo-platform/ros/ros_comm/xmlrpcpp/test/TestValues.cpp
// TestValues.cpp : Test XML encoding and decoding of XmlRpcValues. #include <stdlib.h> #include "XmlRpcValue.h" #include <assert.h> #include <iostream> using namespace XmlRpc; void testBoolean() { XmlRpcValue booleanFalse(false); XmlRpcValue booleanTrue(true); int offset = 0; XmlRpcValue booleanFalseXml("<value><boolean>0</boolean></value>", &offset); offset = 0; XmlRpcValue booleanTrueXml("<value><boolean>1</boolean></value>", &offset); assert(booleanFalse != booleanTrue); assert(booleanFalse == booleanFalseXml); assert(booleanFalse != booleanTrueXml); if (bool(booleanFalse)) assert(false); if ( ! bool(booleanTrue)) assert(false); } // Int void testInt() { XmlRpcValue int0(0); XmlRpcValue int1(1); XmlRpcValue int10(10); XmlRpcValue int_1(-1); int offset = 0; XmlRpcValue int0Xml("<value><int>0</int></value>", &offset); offset = 0; XmlRpcValue int9Xml("<value><i4>9</i4></value>", &offset); assert(int0 == int0Xml); assert(int(int10) - int(int1) == int(int9Xml)); assert(9 == int(int9Xml)); assert(int(int10) + int(int_1) == int(int9Xml)); } void testDouble() { // Double XmlRpcValue d(43.7); int offset = 0; XmlRpcValue dXml("<value><double>56.3</double></value>", &offset); assert(double(d) + double(dXml) == 100.0); // questionable practice... } void testString() { // String XmlRpcValue s("Now is the time <&"); char csxml[] = "<value><string>Now is the time &lt;&amp;</string></value>"; std::string ssxml = csxml; int offset = 0; XmlRpcValue vscXml(csxml, &offset); offset = 0; XmlRpcValue vssXml(ssxml, &offset); assert(s == vscXml); assert(s == vssXml); offset = 0; XmlRpcValue fromXml(vssXml.toXml(), &offset); assert(s == fromXml); // Empty or blank strings with no <string> tags std::string emptyStringXml("<value></value>"); offset = 0; XmlRpcValue emptyStringVal1(emptyStringXml, &offset); XmlRpcValue emptyStringVal2(""); assert(emptyStringVal1 == emptyStringVal2); emptyStringXml = "<value> </value>"; offset = 0; XmlRpcValue blankStringVal(emptyStringXml, &offset); assert(std::string(blankStringVal) == " "); } void testDateTime() { // DateTime int offset = 0; XmlRpcValue dateTime("<value><dateTime.iso8601>19040101T03:12:35</dateTime.iso8601></value>", &offset); struct tm &t = dateTime; assert(t.tm_year == 1904 && t.tm_min == 12); } void testArray(XmlRpcValue const& d) { // Array XmlRpcValue a; a.setSize(4); a[0] = 1; a[1] = std::string("two"); a[2] = 43.7; a[3] = "four"; assert(int(a[0]) == 1); assert(a[2] == d); char csaXml[] = "<value><array>\n" " <data>\n" " <value><i4>1</i4></value> \n" " <value> <string>two</string></value>\n" " <value><double>43.7</double></value>\n" " <value>four</value>\n" " </data>\n" "</array></value>"; int offset = 0; XmlRpcValue aXml(csaXml, &offset); assert(a == aXml); } void testStruct() { // Struct XmlRpcValue struct1; struct1["i4"] = 1; struct1["str"] = "two"; struct1["d"] = 43.7; XmlRpcValue a; a.setSize(4); a[0] = 1; a[1] = std::string("two"); a[2] = 43.7; a[3] = "four"; assert(struct1["d"] == a[2]); char csStructXml[] = "<value><struct>\n" " <member>\n" " <name>i4</name> \n" " <value><i4>1</i4></value> \n" " </member>\n" " <member>\n" " <name>d</name> \n" " <value><double>43.7</double></value>\n" " </member>\n" " <member>\n" " <name>str</name> \n" " <value> <string>two</string></value>\n" " </member>\n" "</struct></value>"; int offset = 0; XmlRpcValue structXml(csStructXml, &offset); assert(struct1 == structXml); XmlRpcValue astruct; astruct["array"] = a; assert(astruct["array"][2] == struct1["d"]); for (int i=0; i<10; i++) { XmlRpcValue Event; Event["Name"] = "string"; Event.clear(); const int NELMTS = 100; int ii; for (ii=0; ii< NELMTS; ++ii) { char buf[40]; sprintf(buf,"%d", ii); Event[std::string(buf)] = buf; } Event.clear(); for (ii=0; ii< NELMTS; ++ii) { char buf[40]; sprintf(buf,"%d", ii); if (ii != NELMTS/2) Event[std::string(buf)] = ii; else for (int jj=0; jj< NELMTS; ++jj) { char bufj[40]; sprintf(bufj,"%d", jj); Event[std::string(buf)][std::string(bufj)] = bufj; } } for (ii=0; ii< NELMTS; ++ii) { char buf[40]; sprintf(buf,"%d", ii); if (ii != NELMTS/2) assert(Event[std::string(buf)] == XmlRpcValue(ii)); else assert(Event[std::string(buf)].size() == NELMTS); } } } int main(int argc, char* argv[]) { testBoolean(); testInt(); testDouble(); testString(); testDateTime(); testArray(43.7); testStruct(); return 0; }
0
apollo_public_repos/apollo-platform/ros/ros_comm/xmlrpcpp
apollo_public_repos/apollo-platform/ros/ros_comm/xmlrpcpp/test/HelloServer.vcproj
<?xml version="1.0" encoding = "Windows-1252"?> <VisualStudioProject ProjectType="Visual C++" Version="7.00" Name="HelloServer" ProjectGUID="{08C4FFA8-A9E5-4EEA-9703-53C293C2F724}" SccProjectName="" SccLocalPath=""> <Platforms> <Platform Name="Win32"/> </Platforms> <Configurations> <Configuration Name="Release|Win32" OutputDirectory=".\Release" IntermediateDirectory=".\Release" ConfigurationType="1" UseOfMFC="0" ATLMinimizesCRunTimeLibraryUsage="FALSE" CharacterSet="2"> <Tool Name="VCCLCompilerTool" InlineFunctionExpansion="1" AdditionalIncludeDirectories="..\src" PreprocessorDefinitions="WIN32,NDEBUG,_CONSOLE" StringPooling="TRUE" RuntimeLibrary="2" EnableFunctionLevelLinking="TRUE" PrecompiledHeaderFile=".\Release/HelloServer.pch" AssemblerListingLocation=".\Release/" ObjectFile=".\Release/" ProgramDataBaseFileName=".\Release/" WarningLevel="3" SuppressStartupBanner="TRUE" CompileAs="0"> <IntelOptions Optimization="2" InlineFuncExpansion="1" OmitFramePtrs="1" StringPooling="1" RuntimeLibrary="2" BufferSecurityCheck="1" FunctionLevelLinking="1" AllOptions="/c /I &quot;..\src&quot; /nologo /W3 /O2 /Ob1 /Oy /D &quot;WIN32&quot; /D &quot;NDEBUG&quot; /D &quot;_CONSOLE&quot; /D &quot;_MBCS&quot; /GF /FD /EHsc /MD /GS /Gy /Fp&quot;.\Release/HelloServer.pch&quot; /Fo&quot;.\Release/&quot; /Fd&quot;.\Release/&quot; /Gd"/> </Tool> <Tool Name="VCCustomBuildTool"/> <Tool Name="VCLinkerTool" AdditionalOptions="/MACHINE:I386" AdditionalDependencies="xmlrpc.lib Ws2_32.lib odbc32.lib odbccp32.lib" OutputFile=".\Release/HelloServer.exe" LinkIncremental="1" SuppressStartupBanner="TRUE" AdditionalLibraryDirectories="..\release" ProgramDatabaseFile=".\Release/HelloServer.pdb" SubSystem="1"> <IntelOptions AllOptions="/NOLOGO /OUT:&quot;.\Release/HelloServer.exe&quot; /INCREMENTAL:NO /LIBPATH:&quot;..\release&quot; xmlrpc.lib Ws2_32.lib odbc32.lib odbccp32.lib /PDB:&quot;.\Release/HelloServer.pdb&quot; /SUBSYSTEM:CONSOLE /TLBID:1 /MACHINE:I386 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib"/> </Tool> <Tool Name="VCMIDLTool" TypeLibraryName=".\Release/HelloServer.tlb"/> <Tool Name="VCPostBuildEventTool"/> <Tool Name="VCPreBuildEventTool"/> <Tool Name="VCPreLinkEventTool"/> <Tool Name="VCResourceCompilerTool" PreprocessorDefinitions="NDEBUG" Culture="1033"/> <Tool Name="VCWebServiceProxyGeneratorTool"/> <Tool Name="VCWebDeploymentTool"/> <IntelOptions CompilerName="1"/> </Configuration> <Configuration Name="Debug|Win32" OutputDirectory=".\Debug" IntermediateDirectory=".\Debug" ConfigurationType="1" UseOfMFC="0" ATLMinimizesCRunTimeLibraryUsage="FALSE" CharacterSet="2"> <Tool Name="VCCLCompilerTool" Optimization="0" AdditionalIncludeDirectories="..\src" PreprocessorDefinitions="WIN32,_DEBUG,_CONSOLE" BasicRuntimeChecks="3" RuntimeLibrary="3" PrecompiledHeaderFile=".\Debug/HelloServer.pch" AssemblerListingLocation=".\Debug/" ObjectFile=".\Debug/" ProgramDataBaseFileName=".\Debug/" WarningLevel="3" SuppressStartupBanner="TRUE" DebugInformationFormat="4" CompileAs="0"> <IntelOptions Optimization="0" MinimalRebuild="1" BasicRuntimeChecks="3" RuntimeLibrary="3" AllOptions="/c /I &quot;..\src&quot; /ZI /nologo /W3 /Od /D &quot;WIN32&quot; /D &quot;_DEBUG&quot; /D &quot;_CONSOLE&quot; /D &quot;_MBCS&quot; /Gm /EHsc /RTC1 /MDd /Fp&quot;.\Debug/HelloServer.pch&quot; /Fo&quot;.\Debug/&quot; /Fd&quot;.\Debug/&quot; /Gd"/> </Tool> <Tool Name="VCCustomBuildTool"/> <Tool Name="VCLinkerTool" AdditionalOptions="/MACHINE:I386" AdditionalDependencies="xmlrpc.lib Ws2_32.lib odbc32.lib odbccp32.lib" OutputFile=".\Debug/HelloServer.exe" LinkIncremental="2" SuppressStartupBanner="TRUE" AdditionalLibraryDirectories="..\Debug" GenerateDebugInformation="TRUE" ProgramDatabaseFile=".\Debug/HelloServer.pdb" SubSystem="1"> <IntelOptions AllOptions="/NOLOGO /OUT:&quot;.\Debug/HelloServer.exe&quot; /INCREMENTAL /LIBPATH:&quot;..\Debug&quot; xmlrpc.lib Ws2_32.lib odbc32.lib odbccp32.lib /DEBUG /PDB:&quot;.\Debug/HelloServer.pdb&quot; /SUBSYSTEM:CONSOLE /TLBID:1 /MACHINE:I386 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib"/> </Tool> <Tool Name="VCMIDLTool" TypeLibraryName=".\Debug/HelloServer.tlb"/> <Tool Name="VCPostBuildEventTool"/> <Tool Name="VCPreBuildEventTool"/> <Tool Name="VCPreLinkEventTool"/> <Tool Name="VCResourceCompilerTool" PreprocessorDefinitions="_DEBUG" Culture="1033"/> <Tool Name="VCWebServiceProxyGeneratorTool"/> <Tool Name="VCWebDeploymentTool"/> <IntelOptions CompilerName="1"/> </Configuration> </Configurations> <Files> <Filter Name="Source Files" Filter="cpp;c;cxx;rc;def;r;odl;idl;hpj;bat"> <File RelativePath=".\HelloServer.cpp"/> </Filter> </Files> <Globals/> </VisualStudioProject>
0
apollo_public_repos/apollo-platform/ros/ros_comm/xmlrpcpp
apollo_public_repos/apollo-platform/ros/ros_comm/xmlrpcpp/test/Validator.dsp
# Microsoft Developer Studio Project File - Name="Validator" - Package Owner=<4> # Microsoft Developer Studio Generated Build File, Format Version 6.00 # ** DO NOT EDIT ** # TARGTYPE "Win32 (x86) Console Application" 0x0103 CFG=Validator - Win32 Debug !MESSAGE This is not a valid makefile. To build this project using NMAKE, !MESSAGE use the Export Makefile command and run !MESSAGE !MESSAGE NMAKE /f "Validator.mak". !MESSAGE !MESSAGE You can specify a configuration when running NMAKE !MESSAGE by defining the macro CFG on the command line. For example: !MESSAGE !MESSAGE NMAKE /f "Validator.mak" CFG="Validator - Win32 Debug" !MESSAGE !MESSAGE Possible choices for configuration are: !MESSAGE !MESSAGE "Validator - Win32 Release" (based on "Win32 (x86) Console Application") !MESSAGE "Validator - Win32 Debug" (based on "Win32 (x86) Console Application") !MESSAGE # Begin Project # PROP AllowPerConfigDependencies 0 # PROP Scc_ProjName "" # PROP Scc_LocalPath "" CPP=cl.exe RSC=rc.exe !IF "$(CFG)" == "Validator - Win32 Release" # PROP BASE Use_MFC 0 # PROP BASE Use_Debug_Libraries 0 # PROP BASE Output_Dir "Release" # PROP BASE Intermediate_Dir "Release" # PROP BASE Target_Dir "" # PROP Use_MFC 0 # PROP Use_Debug_Libraries 0 # PROP Output_Dir "Release" # PROP Intermediate_Dir "Release" # PROP Target_Dir "" # ADD BASE CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_CONSOLE" /D "_MBCS" /Yu"stdafx.h" /FD /c # ADD CPP /nologo /MD /W3 /GX /Zd /O2 /I "..\src" /D "WIN32" /D "NDEBUG" /D "_CONSOLE" /D "_MBCS" /D "_WINDOWS" /FD /c # SUBTRACT CPP /YX /Yc /Yu # ADD BASE RSC /l 0x409 /d "NDEBUG" # ADD RSC /l 0x409 /d "NDEBUG" BSC32=bscmake.exe # ADD BASE BSC32 /nologo # ADD BSC32 /nologo LINK32=link.exe # ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /machine:I386 # ADD LINK32 xmlrpc.lib ws2_32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /machine:I386 /libpath:"..\release" !ELSEIF "$(CFG)" == "Validator - Win32 Debug" # PROP BASE Use_MFC 0 # PROP BASE Use_Debug_Libraries 1 # PROP BASE Output_Dir "Debug" # PROP BASE Intermediate_Dir "Debug" # PROP BASE Target_Dir "" # PROP Use_MFC 0 # PROP Use_Debug_Libraries 1 # PROP Output_Dir "Debug" # PROP Intermediate_Dir "Debug" # PROP Ignore_Export_Lib 0 # PROP Target_Dir "" # ADD BASE CPP /nologo /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_CONSOLE" /D "_MBCS" /Yu"stdafx.h" /FD /GZ /c # ADD CPP /nologo /MDd /W3 /Gm /GX /ZI /Od /I "..\src" /D "WIN32" /D "_DEBUG" /D "_CONSOLE" /D "_MBCS" /D "_WINDOWS" /FD /GZ /c # SUBTRACT CPP /YX /Yc /Yu # ADD BASE RSC /l 0x409 /d "_DEBUG" # ADD RSC /l 0x409 /d "_DEBUG" BSC32=bscmake.exe # ADD BASE BSC32 /nologo # ADD BSC32 /nologo LINK32=link.exe # ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /debug /machine:I386 /pdbtype:sept # ADD LINK32 xmlrpc.lib WS2_32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /debug /machine:I386 /pdbtype:sept /libpath:"..\debug" !ENDIF # Begin Target # Name "Validator - Win32 Release" # Name "Validator - Win32 Debug" # Begin Group "Source Files" # PROP Default_Filter "cpp;c;cxx;rc;def;r;odl;idl;hpj;bat" # Begin Source File SOURCE=.\Validator.cpp # End Source File # End Group # End Target # End Project
0
apollo_public_repos/apollo-platform/ros/ros_comm/xmlrpcpp
apollo_public_repos/apollo-platform/ros/ros_comm/xmlrpcpp/test/HelloClient.cpp
// HelloClient.cpp : A simple xmlrpc client. Usage: HelloClient serverHost serverPort // Link against xmlrpc lib and whatever socket libs your system needs (ws2_32.lib // on windows) #include "XmlRpc.h" #include <iostream> using namespace XmlRpc; int main(int argc, char* argv[]) { if (argc != 3) { std::cerr << "Usage: HelloClient serverHost serverPort\n"; return -1; } int port = atoi(argv[2]); //XmlRpc::setVerbosity(5); // Use introspection API to look up the supported methods XmlRpcClient c(argv[1], port); XmlRpcValue noArgs, result; for (int i = 0; i < 2000; i++) { if (c.execute("system.listMethods", noArgs, result)) std::cout << "\nMethods:\n " << result << "\n\n"; else std::cout << "Error calling 'listMethods'\n\n"; } // Use introspection API to get the help string for the Hello method XmlRpcValue oneArg; oneArg[0] = "Hello"; if (c.execute("system.methodHelp", oneArg, result)) std::cout << "Help for 'Hello' method: " << result << "\n\n"; else std::cout << "Error calling 'methodHelp'\n\n"; // Call the Hello method if (c.execute("Hello", noArgs, result)) std::cout << result << "\n\n"; else std::cout << "Error calling 'Hello'\n\n"; // Call the HelloName method oneArg[0] = "Chris"; if (c.execute("HelloName", oneArg, result)) std::cout << result << "\n\n"; else std::cout << "Error calling 'HelloName'\n\n"; // Add up an array of numbers XmlRpcValue numbers; numbers[0] = 33.33; numbers[1] = 112.57; numbers[2] = 76.1; std::cout << "numbers.size() is " << numbers.size() << std::endl; if (c.execute("Sum", numbers, result)) std::cout << "Sum = " << double(result) << "\n\n"; else std::cout << "Error calling 'Sum'\n\n"; // Test the "no such method" fault if (c.execute("NoSuchMethod", numbers, result)) std::cout << "NoSuchMethod call: fault: " << c.isFault() << ", result = " << result << std::endl; else std::cout << "Error calling 'Sum'\n"; // Test the multicall method. It accepts one arg, an array of structs XmlRpcValue multicall; multicall[0][0]["methodName"] = "Sum"; multicall[0][0]["params"][0] = 5.0; multicall[0][0]["params"][1] = 9.0; multicall[0][1]["methodName"] = "NoSuchMethod"; multicall[0][1]["params"][0] = ""; multicall[0][2]["methodName"] = "Sum"; // Missing params multicall[0][3]["methodName"] = "Sum"; multicall[0][3]["params"][0] = 10.5; multicall[0][3]["params"][1] = 12.5; if (c.execute("system.multicall", multicall, result)) std::cout << "\nmulticall result = " << result << std::endl; else std::cout << "\nError calling 'system.multicall'\n"; return 0; }
0
apollo_public_repos/apollo-platform/ros/ros_comm/xmlrpcpp
apollo_public_repos/apollo-platform/ros/ros_comm/xmlrpcpp/test/TestBase64Client.dsp
# Microsoft Developer Studio Project File - Name="TestBase64Client" - Package Owner=<4> # Microsoft Developer Studio Generated Build File, Format Version 6.00 # ** DO NOT EDIT ** # TARGTYPE "Win32 (x86) Console Application" 0x0103 CFG=TestBase64Client - Win32 Debug !MESSAGE This is not a valid makefile. To build this project using NMAKE, !MESSAGE use the Export Makefile command and run !MESSAGE !MESSAGE NMAKE /f "TestBase64Client.mak". !MESSAGE !MESSAGE You can specify a configuration when running NMAKE !MESSAGE by defining the macro CFG on the command line. For example: !MESSAGE !MESSAGE NMAKE /f "TestBase64Client.mak" CFG="TestBase64Client - Win32 Debug" !MESSAGE !MESSAGE Possible choices for configuration are: !MESSAGE !MESSAGE "TestBase64Client - Win32 Release" (based on "Win32 (x86) Console Application") !MESSAGE "TestBase64Client - Win32 Debug" (based on "Win32 (x86) Console Application") !MESSAGE # Begin Project # PROP AllowPerConfigDependencies 0 # PROP Scc_ProjName "" # PROP Scc_LocalPath "" CPP=cl.exe RSC=rc.exe !IF "$(CFG)" == "TestBase64Client - Win32 Release" # PROP BASE Use_MFC 0 # PROP BASE Use_Debug_Libraries 0 # PROP BASE Output_Dir "Release" # PROP BASE Intermediate_Dir "Release" # PROP BASE Target_Dir "" # PROP Use_MFC 0 # PROP Use_Debug_Libraries 0 # PROP Output_Dir "Release" # PROP Intermediate_Dir "Release" # PROP Ignore_Export_Lib 0 # PROP Target_Dir "" # ADD BASE CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_CONSOLE" /D "_MBCS" /Yu"stdafx.h" /FD /c # ADD CPP /nologo /MD /W3 /GX /O2 /I "..\src" /D "WIN32" /D "NDEBUG" /D "_CONSOLE" /D "_MBCS" /D "_WINDOWS" /FD /c # SUBTRACT CPP /YX /Yc /Yu # ADD BASE RSC /l 0x409 /d "NDEBUG" # ADD RSC /l 0x409 /d "NDEBUG" BSC32=bscmake.exe # ADD BASE BSC32 /nologo # ADD BSC32 /nologo LINK32=link.exe # ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /machine:I386 # ADD LINK32 xmlrpc.lib Ws2_32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /machine:I386 /libpath:"..\release" !ELSEIF "$(CFG)" == "TestBase64Client - Win32 Debug" # PROP BASE Use_MFC 0 # PROP BASE Use_Debug_Libraries 1 # PROP BASE Output_Dir "Debug" # PROP BASE Intermediate_Dir "Debug" # PROP BASE Target_Dir "" # PROP Use_MFC 0 # PROP Use_Debug_Libraries 1 # PROP Output_Dir "Debug" # PROP Intermediate_Dir "Debug" # PROP Ignore_Export_Lib 0 # PROP Target_Dir "" # ADD BASE CPP /nologo /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_CONSOLE" /D "_MBCS" /Yu"stdafx.h" /FD /GZ /c # ADD CPP /nologo /MDd /W3 /Gm /GX /ZI /Od /I "..\src" /D "WIN32" /D "_DEBUG" /D "_CONSOLE" /D "_MBCS" /D "_WINDOWS" /FD /GZ /c # SUBTRACT CPP /YX /Yc /Yu # ADD BASE RSC /l 0x409 /d "_DEBUG" # ADD RSC /l 0x409 /d "_DEBUG" BSC32=bscmake.exe # ADD BASE BSC32 /nologo # ADD BSC32 /nologo LINK32=link.exe # ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /debug /machine:I386 /pdbtype:sept # ADD LINK32 xmlrpc.lib Ws2_32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /debug /machine:I386 /pdbtype:sept /libpath:"..\Debug" !ENDIF # Begin Target # Name "TestBase64Client - Win32 Release" # Name "TestBase64Client - Win32 Debug" # Begin Group "Source Files" # PROP Default_Filter "cpp;c;cxx;rc;def;r;odl;idl;hpj;bat" # Begin Source File SOURCE=.\TestBase64Client.cpp # End Source File # End Group # End Target # End Project
0
apollo_public_repos/apollo-platform/ros/ros_comm/xmlrpcpp
apollo_public_repos/apollo-platform/ros/ros_comm/xmlrpcpp/test/TestValues.dsp
# Microsoft Developer Studio Project File - Name="TestValues" - Package Owner=<4> # Microsoft Developer Studio Generated Build File, Format Version 6.00 # ** DO NOT EDIT ** # TARGTYPE "Win32 (x86) Console Application" 0x0103 CFG=TestValues - Win32 Debug !MESSAGE This is not a valid makefile. To build this project using NMAKE, !MESSAGE use the Export Makefile command and run !MESSAGE !MESSAGE NMAKE /f "TestValues.mak". !MESSAGE !MESSAGE You can specify a configuration when running NMAKE !MESSAGE by defining the macro CFG on the command line. For example: !MESSAGE !MESSAGE NMAKE /f "TestValues.mak" CFG="TestValues - Win32 Debug" !MESSAGE !MESSAGE Possible choices for configuration are: !MESSAGE !MESSAGE "TestValues - Win32 Release" (based on "Win32 (x86) Console Application") !MESSAGE "TestValues - Win32 Debug" (based on "Win32 (x86) Console Application") !MESSAGE # Begin Project # PROP AllowPerConfigDependencies 0 # PROP Scc_ProjName "" # PROP Scc_LocalPath "" CPP=cl.exe RSC=rc.exe !IF "$(CFG)" == "TestValues - Win32 Release" # PROP BASE Use_MFC 0 # PROP BASE Use_Debug_Libraries 0 # PROP BASE Output_Dir "Release" # PROP BASE Intermediate_Dir "Release" # PROP BASE Target_Dir "" # PROP Use_MFC 0 # PROP Use_Debug_Libraries 0 # PROP Output_Dir "Release" # PROP Intermediate_Dir "Release" # PROP Ignore_Export_Lib 0 # PROP Target_Dir "" # ADD BASE CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /c # ADD CPP /nologo /MD /W3 /GX /O2 /I "..\src" /D "WIN32" /D "NDEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /c # ADD BASE RSC /l 0x409 /d "NDEBUG" # ADD RSC /l 0x409 /d "NDEBUG" BSC32=bscmake.exe # ADD BASE BSC32 /nologo # ADD BSC32 /nologo LINK32=link.exe # ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /machine:I386 # ADD LINK32 xmlrpc.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /machine:I386 /libpath:"..\Release" !ELSEIF "$(CFG)" == "TestValues - Win32 Debug" # PROP BASE Use_MFC 0 # PROP BASE Use_Debug_Libraries 1 # PROP BASE Output_Dir "Debug" # PROP BASE Intermediate_Dir "Debug" # PROP BASE Target_Dir "" # PROP Use_MFC 0 # PROP Use_Debug_Libraries 1 # PROP Output_Dir "Debug" # PROP Intermediate_Dir "Debug" # PROP Ignore_Export_Lib 0 # PROP Target_Dir "" # ADD BASE CPP /nologo /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /GZ /c # ADD CPP /MDd /W3 /GX /Zi /Od /I "..\src" /D "WIN32" /D "_DEBUG" /D "_CONSOLE" /D "_MBCS" /D "_WINDOWS" /FR /FD /c # SUBTRACT CPP /nologo # ADD BASE RSC /l 0x409 /d "_DEBUG" # ADD RSC /l 0x409 /d "_DEBUG" BSC32=bscmake.exe # ADD BASE BSC32 /nologo # ADD BSC32 /nologo LINK32=link.exe # ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /debug /machine:I386 /pdbtype:sept # ADD LINK32 xmlrpc.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /debug /machine:I386 /pdbtype:sept /libpath:"..\Debug" !ENDIF # Begin Target # Name "TestValues - Win32 Release" # Name "TestValues - Win32 Debug" # Begin Group "Source Files" # PROP Default_Filter "cpp;c;cxx;rc;def;r;odl;idl;hpj;bat" # Begin Source File SOURCE=.\TestValuesWin32.cpp # End Source File # End Group # End Target # End Project
0
apollo_public_repos/apollo-platform/ros/ros_comm/xmlrpcpp
apollo_public_repos/apollo-platform/ros/ros_comm/xmlrpcpp/test/Validator.cpp
// Validator.cpp : XMLRPC server based on the compliancy test at validator.xmlrpc.com. // #include "XmlRpc.h" using namespace XmlRpc; #include <iostream> XmlRpcServer s; // One argument is passed, an array of structs, each with a member named curly with // an integer value. Return the sum of those values. class ArrayOfStructsTest : public XmlRpcServerMethod { public: ArrayOfStructsTest(XmlRpcServer* s) : XmlRpcServerMethod("validator1.arrayOfStructsTest", s) {} void execute(XmlRpcValue& params, XmlRpcValue& result) { std::cerr << "ArrayOfStructsTest\n"; XmlRpcValue& arg1 = params[0]; int n = arg1.size(), sum = 0; for (int i=0; i<n; ++i) sum += int(arg1[i]["curly"]); result = sum; } } arrayOfStructsTest(&s); // This handler takes a single parameter, a string, that contains any number of predefined // entities, namely <, >, &, ' and ". // The handler must return a struct that contains five fields, all numbers: ctLeftAngleBrackets, // ctRightAngleBrackets, ctAmpersands, ctApostrophes, ctQuotes. // To validate, the numbers must be correct. class CountTheEntities : public XmlRpcServerMethod { public: CountTheEntities(XmlRpcServer* s) : XmlRpcServerMethod("validator1.countTheEntities", s) {} void execute(XmlRpcValue& params, XmlRpcValue& result) { std::cerr << "CountTheEntities\n"; std::string& arg = params[0]; int ctLeftAngleBrackets = 0; int ctRightAngleBrackets = 0; int ctAmpersands = 0; int ctApostrophes = 0; int ctQuotes = 0; int n = int(arg.length()); for (int i=0; i<n; ++i) switch (arg[i]) { case '<': ++ctLeftAngleBrackets; break; case '>': ++ctRightAngleBrackets; break; case '&': ++ctAmpersands; break; case '\'': ++ctApostrophes; break; case '\"': ++ctQuotes; break; } result["ctLeftAngleBrackets"] = ctLeftAngleBrackets; result["ctRightAngleBrackets"] = ctRightAngleBrackets; result["ctAmpersands"] = ctAmpersands; result["ctApostrophes"] = ctApostrophes; result["ctQuotes"] = ctQuotes; } } countTheEntities(&s); // This handler takes a single parameter, a struct, containing at least three elements // named moe, larry and curly, all <i4>s. Your handler must add the three numbers and // return the result. class EasyStructTest : public XmlRpcServerMethod { public: EasyStructTest(XmlRpcServer* s) : XmlRpcServerMethod("validator1.easyStructTest", s) {} void execute(XmlRpcValue& params, XmlRpcValue& result) { std::cerr << "EasyStructTest\n"; XmlRpcValue& arg1 = params[0]; int sum = int(arg1["moe"]) + int(arg1["larry"]) + int(arg1["curly"]); result = sum; } } easyStructTest(&s); // This handler takes a single parameter, a struct. Your handler must return the struct. class EchoStructTest : public XmlRpcServerMethod { public: EchoStructTest(XmlRpcServer* s) : XmlRpcServerMethod("validator1.echoStructTest", s) {} void execute(XmlRpcValue& params, XmlRpcValue& result) { std::cerr << "EchoStructTest\n"; result = params[0]; } } echoStructTest(&s); // This handler takes six parameters, and returns an array containing all the parameters. class ManyTypesTest : public XmlRpcServerMethod { public: ManyTypesTest(XmlRpcServer* s) : XmlRpcServerMethod("validator1.manyTypesTest", s) {} void execute(XmlRpcValue& params, XmlRpcValue& result) { std::cerr << "ManyTypesTest\n"; result = params; } } manyTypesTest(&s); // This handler takes a single parameter, which is an array containing between 100 and // 200 elements. Each of the items is a string, your handler must return a string // containing the concatenated text of the first and last elements. class ModerateSizeArrayCheck : public XmlRpcServerMethod { public: ModerateSizeArrayCheck(XmlRpcServer* s) : XmlRpcServerMethod("validator1.moderateSizeArrayCheck", s) {} void execute(XmlRpcValue& params, XmlRpcValue& result) { std::cerr << "ModerateSizeArrayCheck\n"; std::string s = params[0][0]; s += std::string(params[0][params[0].size()-1]); result = s; } } moderateSizeArrayCheck(&s); // This handler takes a single parameter, a struct, that models a daily calendar. // At the top level, there is one struct for each year. Each year is broken down // into months, and months into days. Most of the days are empty in the struct // you receive, but the entry for April 1, 2000 contains a least three elements // named moe, larry and curly, all <i4>s. Your handler must add the three numbers // and return the result. class NestedStructTest : public XmlRpcServerMethod { public: NestedStructTest(XmlRpcServer* s) : XmlRpcServerMethod("validator1.nestedStructTest", s) {} void execute(XmlRpcValue& params, XmlRpcValue& result) { std::cerr << "NestedStructTest\n"; XmlRpcValue& dayStruct = params[0]["2000"]["04"]["01"]; int sum = int(dayStruct["moe"]) + int(dayStruct["larry"]) + int(dayStruct["curly"]); result = sum; } } nestedStructTest(&s); // This handler takes one parameter, and returns a struct containing three elements, // times10, times100 and times1000, the result of multiplying the number by 10, 100 and 1000. class SimpleStructReturnTest : public XmlRpcServerMethod { public: SimpleStructReturnTest(XmlRpcServer* s) : XmlRpcServerMethod("validator1.simpleStructReturnTest", s) {} void execute(XmlRpcValue& params, XmlRpcValue& result) { std::cerr << "SimpleStructReturnTest\n"; int n = params[0]; result["times10"] = n * 10; result["times100"] = n * 100; result["times1000"] = n * 1000; } } simpleStructReturnTest(&s); int main(int argc, char* argv[]) { if (argc != 2) { std::cerr << "Usage: Validator port\n"; return -1; } int port = atoi(argv[1]); XmlRpc::setVerbosity(5); // Create the server socket on the specified port s.bindAndListen(port); // Wait for requests indefinitely s.work(-1.0); return 0; }
0
apollo_public_repos/apollo-platform/ros/ros_comm/xmlrpcpp
apollo_public_repos/apollo-platform/ros/ros_comm/xmlrpcpp/test/.cvsignore
Debug Release doc *.ncb *.opt *.plg *.suo
0
apollo_public_repos/apollo-platform/ros/ros_comm/xmlrpcpp
apollo_public_repos/apollo-platform/ros/ros_comm/xmlrpcpp/test/HelloClient.vcproj
<?xml version="1.0" encoding = "Windows-1252"?> <VisualStudioProject ProjectType="Visual C++" Version="7.00" Name="HelloClient" ProjectGUID="{F6860B2F-0F3B-445E-92F2-6DF3D36C90F0}" SccProjectName="" SccLocalPath=""> <Platforms> <Platform Name="Win32"/> </Platforms> <Configurations> <Configuration Name="Release|Win32" OutputDirectory=".\Release" IntermediateDirectory=".\Release" ConfigurationType="1" UseOfMFC="0" ATLMinimizesCRunTimeLibraryUsage="FALSE" CharacterSet="2"> <Tool Name="VCCLCompilerTool" InlineFunctionExpansion="1" AdditionalIncludeDirectories="..\src" PreprocessorDefinitions="WIN32,NDEBUG,_CONSOLE" StringPooling="TRUE" RuntimeLibrary="2" EnableFunctionLevelLinking="TRUE" PrecompiledHeaderFile=".\Release/HelloClient.pch" AssemblerListingLocation=".\Release/" ObjectFile=".\Release/" ProgramDataBaseFileName=".\Release/" WarningLevel="3" SuppressStartupBanner="TRUE" CompileAs="0"> <IntelOptions Optimization="2" InlineFuncExpansion="1" OmitFramePtrs="1" StringPooling="1" RuntimeLibrary="2" BufferSecurityCheck="1" FunctionLevelLinking="1" AllOptions="/c /I &quot;..\src&quot; /nologo /W3 /O2 /Ob1 /Oy /D &quot;WIN32&quot; /D &quot;NDEBUG&quot; /D &quot;_CONSOLE&quot; /D &quot;_MBCS&quot; /GF /FD /EHsc /MD /GS /Gy /Fp&quot;.\Release/HelloClient.pch&quot; /Fo&quot;.\Release/&quot; /Fd&quot;.\Release/&quot; /Gd"/> </Tool> <Tool Name="VCCustomBuildTool"/> <Tool Name="VCLinkerTool" AdditionalOptions="/MACHINE:I386" AdditionalDependencies="xmlrpc.lib Ws2_32.lib odbc32.lib odbccp32.lib" OutputFile=".\Release/HelloClient.exe" LinkIncremental="1" SuppressStartupBanner="TRUE" AdditionalLibraryDirectories="..\release" ProgramDatabaseFile=".\Release/HelloClient.pdb" SubSystem="1"> <IntelOptions AllOptions="/NOLOGO /OUT:&quot;.\Release/HelloClient.exe&quot; /INCREMENTAL:NO /LIBPATH:&quot;..\release&quot; xmlrpc.lib Ws2_32.lib odbc32.lib odbccp32.lib /PDB:&quot;.\Release/HelloClient.pdb&quot; /SUBSYSTEM:CONSOLE /TLBID:1 /MACHINE:I386 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib"/> </Tool> <Tool Name="VCMIDLTool" TypeLibraryName=".\Release/HelloClient.tlb"/> <Tool Name="VCPostBuildEventTool"/> <Tool Name="VCPreBuildEventTool"/> <Tool Name="VCPreLinkEventTool"/> <Tool Name="VCResourceCompilerTool" PreprocessorDefinitions="NDEBUG" Culture="1033"/> <Tool Name="VCWebServiceProxyGeneratorTool"/> <Tool Name="VCWebDeploymentTool"/> <IntelOptions CompilerName="1"/> </Configuration> <Configuration Name="Debug|Win32" OutputDirectory=".\Debug" IntermediateDirectory=".\Debug" ConfigurationType="1" UseOfMFC="0" ATLMinimizesCRunTimeLibraryUsage="FALSE" CharacterSet="2"> <Tool Name="VCCLCompilerTool" Optimization="0" AdditionalIncludeDirectories="..\src" PreprocessorDefinitions="WIN32,_DEBUG,_CONSOLE" BasicRuntimeChecks="3" RuntimeLibrary="3" PrecompiledHeaderFile=".\Debug/HelloClient.pch" AssemblerListingLocation=".\Debug/" ObjectFile=".\Debug/" ProgramDataBaseFileName=".\Debug/" WarningLevel="3" SuppressStartupBanner="TRUE" DebugInformationFormat="4" CompileAs="0"> <IntelOptions Optimization="0" MinimalRebuild="1" BasicRuntimeChecks="3" RuntimeLibrary="3" AllOptions="/c /I &quot;..\src&quot; /ZI /nologo /W3 /Od /D &quot;WIN32&quot; /D &quot;_DEBUG&quot; /D &quot;_CONSOLE&quot; /D &quot;_MBCS&quot; /Gm /EHsc /RTC1 /MDd /Fp&quot;.\Debug/HelloClient.pch&quot; /Fo&quot;.\Debug/&quot; /Fd&quot;.\Debug/&quot; /Gd"/> </Tool> <Tool Name="VCCustomBuildTool"/> <Tool Name="VCLinkerTool" AdditionalOptions="/MACHINE:I386 &quot;c:\home\cmm\dev\sourceforge\xmlrpc++\Debug\xmlrpc.lib&quot;" AdditionalDependencies="xmlrpc.lib Ws2_32.lib odbc32.lib odbccp32.lib" OutputFile=".\Debug/HelloClient.exe" LinkIncremental="2" SuppressStartupBanner="TRUE" AdditionalLibraryDirectories="..\Debug" GenerateDebugInformation="TRUE" ProgramDatabaseFile=".\Debug/HelloClient.pdb" SubSystem="1"> <IntelOptions AllOptions="/NOLOGO /OUT:&quot;.\Debug/HelloClient.exe&quot; /INCREMENTAL /LIBPATH:&quot;..\Debug&quot; xmlrpc.lib Ws2_32.lib odbc32.lib odbccp32.lib /DEBUG /PDB:&quot;.\Debug/HelloClient.pdb&quot; /SUBSYSTEM:CONSOLE /TLBID:1 /MACHINE:I386 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib"/> </Tool> <Tool Name="VCMIDLTool" TypeLibraryName=".\Debug/HelloClient.tlb"/> <Tool Name="VCPostBuildEventTool"/> <Tool Name="VCPreBuildEventTool"/> <Tool Name="VCPreLinkEventTool"/> <Tool Name="VCResourceCompilerTool" PreprocessorDefinitions="_DEBUG" Culture="1033"/> <Tool Name="VCWebServiceProxyGeneratorTool"/> <Tool Name="VCWebDeploymentTool"/> <IntelOptions CompilerName="1"/> </Configuration> </Configurations> <Files> <Filter Name="Source Files" Filter="cpp;c;cxx;rc;def;r;odl;idl;hpj;bat"> <File RelativePath=".\HelloClient.cpp"/> </Filter> </Files> <Globals/> </VisualStudioProject>
0
apollo_public_repos/apollo-platform/ros/ros_comm/xmlrpcpp
apollo_public_repos/apollo-platform/ros/ros_comm/xmlrpcpp/test/HelloClient.dsp
# Microsoft Developer Studio Project File - Name="HelloClient" - Package Owner=<4> # Microsoft Developer Studio Generated Build File, Format Version 6.00 # ** DO NOT EDIT ** # TARGTYPE "Win32 (x86) Console Application" 0x0103 CFG=HelloClient - Win32 Debug !MESSAGE This is not a valid makefile. To build this project using NMAKE, !MESSAGE use the Export Makefile command and run !MESSAGE !MESSAGE NMAKE /f "HelloClient.mak". !MESSAGE !MESSAGE You can specify a configuration when running NMAKE !MESSAGE by defining the macro CFG on the command line. For example: !MESSAGE !MESSAGE NMAKE /f "HelloClient.mak" CFG="HelloClient - Win32 Debug" !MESSAGE !MESSAGE Possible choices for configuration are: !MESSAGE !MESSAGE "HelloClient - Win32 Release" (based on "Win32 (x86) Console Application") !MESSAGE "HelloClient - Win32 Debug" (based on "Win32 (x86) Console Application") !MESSAGE # Begin Project # PROP AllowPerConfigDependencies 0 # PROP Scc_ProjName "" # PROP Scc_LocalPath "" CPP=cl.exe RSC=rc.exe !IF "$(CFG)" == "HelloClient - Win32 Release" # PROP BASE Use_MFC 0 # PROP BASE Use_Debug_Libraries 0 # PROP BASE Output_Dir "Release" # PROP BASE Intermediate_Dir "Release" # PROP BASE Target_Dir "" # PROP Use_MFC 0 # PROP Use_Debug_Libraries 0 # PROP Output_Dir "Release" # PROP Intermediate_Dir "Release" # PROP Ignore_Export_Lib 0 # PROP Target_Dir "" # ADD BASE CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_CONSOLE" /D "_MBCS" /Yu"stdafx.h" /FD /c # ADD CPP /nologo /MD /W3 /GX /O2 /I "..\src" /D "WIN32" /D "NDEBUG" /D "_CONSOLE" /D "_MBCS" /D "_WINDOWS" /FD /c # SUBTRACT CPP /YX /Yc /Yu # ADD BASE RSC /l 0x409 /d "NDEBUG" # ADD RSC /l 0x409 /d "NDEBUG" BSC32=bscmake.exe # ADD BASE BSC32 /nologo # ADD BSC32 /nologo LINK32=link.exe # ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /machine:I386 # ADD LINK32 xmlrpc.lib Ws2_32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /machine:I386 /libpath:"..\release" !ELSEIF "$(CFG)" == "HelloClient - Win32 Debug" # PROP BASE Use_MFC 0 # PROP BASE Use_Debug_Libraries 1 # PROP BASE Output_Dir "Debug" # PROP BASE Intermediate_Dir "Debug" # PROP BASE Target_Dir "" # PROP Use_MFC 0 # PROP Use_Debug_Libraries 1 # PROP Output_Dir "Debug" # PROP Intermediate_Dir "Debug" # PROP Ignore_Export_Lib 0 # PROP Target_Dir "" # ADD BASE CPP /nologo /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_CONSOLE" /D "_MBCS" /Yu"stdafx.h" /FD /GZ /c # ADD CPP /nologo /MDd /W3 /Gm /GX /ZI /Od /I "..\src" /D "WIN32" /D "_DEBUG" /D "_CONSOLE" /D "_MBCS" /D "_WINDOWS" /FD /GZ /c # SUBTRACT CPP /YX /Yc /Yu # ADD BASE RSC /l 0x409 /d "_DEBUG" # ADD RSC /l 0x409 /d "_DEBUG" BSC32=bscmake.exe # ADD BASE BSC32 /nologo # ADD BSC32 /nologo LINK32=link.exe # ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /debug /machine:I386 /pdbtype:sept # ADD LINK32 xmlrpc.lib Ws2_32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /debug /machine:I386 /pdbtype:sept /libpath:"..\Debug" !ENDIF # Begin Target # Name "HelloClient - Win32 Release" # Name "HelloClient - Win32 Debug" # Begin Group "Source Files" # PROP Default_Filter "cpp;c;cxx;rc;def;r;odl;idl;hpj;bat" # Begin Source File SOURCE=.\HelloClient.cpp # End Source File # End Group # End Target # End Project
0
apollo_public_repos/apollo-platform/ros/ros_comm/xmlrpcpp
apollo_public_repos/apollo-platform/ros/ros_comm/xmlrpcpp/test/TestBase64Client.cpp
// TestBase64Client.cpp : A simple xmlrpc client that returns a png file // encoded as base64 data to the client. // // Usage: TestBase64Client serverHost serverPort outputfile // Requests a png file from the specified server and saves it in outputfile. // Link against xmlrpc lib and whatever socket libs your system needs (ws2_32.lib on windows) #include "XmlRpc.h" #include <iostream> #include <fstream> #include <stdlib.h> using namespace XmlRpc; int main(int argc, char* argv[]) { if (argc != 4) { std::cerr << "Usage: TestBase64Client serverHost serverPort outputFile\n"; return -1; } int port = atoi(argv[2]); //XmlRpc::setVerbosity(5); XmlRpcClient c(argv[1], port); XmlRpcValue noArgs, result; if (c.execute("TestBase64", noArgs, result)) { const XmlRpcValue::BinaryData& data = result; std::ofstream outfile(argv[3], std::ios::binary | std::ios::trunc); if (outfile.fail()) std::cerr << "Error opening " << argv[3] << " for output.\n"; else { int n = int(data.size()); for (int i=0; i<n; ++i) outfile << data[i]; } } else std::cout << "Error calling 'TestBase64'\n\n"; return 0; }
0
apollo_public_repos/apollo-platform/ros/ros_comm/xmlrpcpp
apollo_public_repos/apollo-platform/ros/ros_comm/xmlrpcpp/include/XmlRpcServer.h
// this file modified by Morgan Quigley on 22 Apr 2008. // added features: server can be opened on port 0 and you can read back // what port the OS gave you #ifndef _XMLRPCSERVER_H_ #define _XMLRPCSERVER_H_ // // XmlRpc++ Copyright (c) 2002-2003 by Chris Morley // #if defined(_MSC_VER) # pragma warning(disable:4786) // identifier was truncated in debug info #endif #ifndef MAKEDEPEND # include <map> # include <string> #endif #include "XmlRpcDispatch.h" #include "XmlRpcSource.h" #include "XmlRpcDecl.h" namespace XmlRpc { // An abstract class supporting XML RPC methods class XmlRpcServerMethod; // Class representing connections to specific clients class XmlRpcServerConnection; // Class representing argument and result values class XmlRpcValue; //! A class to handle XML RPC requests class XMLRPCPP_DECL XmlRpcServer : public XmlRpcSource { public: //! Create a server object. XmlRpcServer(); //! Destructor. virtual ~XmlRpcServer(); //! Specify whether introspection is enabled or not. Default is not enabled. void enableIntrospection(bool enabled=true); //! Add a command to the RPC server void addMethod(XmlRpcServerMethod* method); //! Remove a command from the RPC server void removeMethod(XmlRpcServerMethod* method); //! Remove a command from the RPC server by name void removeMethod(const std::string& methodName); //! Look up a method by name XmlRpcServerMethod* findMethod(const std::string& name) const; //! Create a socket, bind to the specified port, and //! set it in listen mode to make it available for clients. bool bindAndListen(int port, int backlog = 5); //! Process client requests for the specified time void work(double msTime); //! Temporarily stop processing client requests and exit the work() method. void exit(); //! Close all connections with clients and the socket file descriptor void shutdown(); //! Introspection support void listMethods(XmlRpcValue& result); // XmlRpcSource interface implementation //! Handle client connection requests virtual unsigned handleEvent(unsigned eventType); //! Remove a connection from the dispatcher virtual void removeConnection(XmlRpcServerConnection*); inline int get_port() { return _port; } XmlRpcDispatch *get_dispatch() { return &_disp; } protected: //! Accept a client connection request virtual void acceptConnection(); //! Create a new connection object for processing requests from a specific client. virtual XmlRpcServerConnection* createConnection(int socket); // Whether the introspection API is supported by this server bool _introspectionEnabled; // Event dispatcher XmlRpcDispatch _disp; // Collection of methods. This could be a set keyed on method name if we wanted... typedef std::map< std::string, XmlRpcServerMethod* > MethodMap; MethodMap _methods; // system methods XmlRpcServerMethod* _listMethods; XmlRpcServerMethod* _methodHelp; int _port; }; } // namespace XmlRpc #endif //_XMLRPCSERVER_H_
0
apollo_public_repos/apollo-platform/ros/ros_comm/xmlrpcpp
apollo_public_repos/apollo-platform/ros/ros_comm/xmlrpcpp/include/XmlRpcSocket.h
// this file modified by Morgan Quigley on 22 Apr 2008. // added features: server can be opened on port 0 and you can read back // what port the OS gave you #ifndef _XMLRPCSOCKET_H_ #define _XMLRPCSOCKET_H_ // // XmlRpc++ Copyright (c) 2002-2003 by Chris Morley // #if defined(_MSC_VER) # pragma warning(disable:4786) // identifier was truncated in debug info #endif #ifndef MAKEDEPEND # include <string> #endif #include "XmlRpcDecl.h" namespace XmlRpc { //! A platform-independent socket API. class XMLRPCPP_DECL XmlRpcSocket { public: static bool s_use_ipv6_; //! Creates a stream (TCP) socket. Returns -1 on failure. static int socket(); //! Closes a socket. static void close(int socket); //! Sets a stream (TCP) socket to perform non-blocking IO. Returns false on failure. static bool setNonBlocking(int socket); //! Read text from the specified socket. Returns false on error. static bool nbRead(int socket, std::string& s, bool *eof); //! Write text to the specified socket. Returns false on error. static bool nbWrite(int socket, std::string& s, int *bytesSoFar); // The next four methods are appropriate for servers. //! Allow the port the specified socket is bound to to be re-bound immediately so //! server re-starts are not delayed. Returns false on failure. static bool setReuseAddr(int socket); //! Bind to a specified port static bool bind(int socket, int port); static int get_port(int socket); //! Set socket in listen mode static bool listen(int socket, int backlog); //! Accept a client connection request static int accept(int socket); //! Connect a socket to a server (from a client) static bool connect(int socket, std::string& host, int port); //! Returns last errno static int getError(); //! Returns message corresponding to last error static std::string getErrorMsg(); //! Returns message corresponding to error static std::string getErrorMsg(int error); }; } // namespace XmlRpc #endif
0
apollo_public_repos/apollo-platform/ros/ros_comm/xmlrpcpp
apollo_public_repos/apollo-platform/ros/ros_comm/xmlrpcpp/include/XmlRpcUtil.h
#ifndef _XMLRPCUTIL_H_ #define _XMLRPCUTIL_H_ // // XmlRpc++ Copyright (c) 2002-2003 by Chris Morley // #if defined(_MSC_VER) # pragma warning(disable:4786) // identifier was truncated in debug info #endif #ifndef MAKEDEPEND # include <string> #endif #include "XmlRpcDecl.h" #if defined(_MSC_VER) # define snprintf _snprintf_s # define vsnprintf _vsnprintf_s # define strcasecmp _stricmp # define strncasecmp _strnicmp #elif defined(__BORLANDC__) # define strcasecmp stricmp # define strncasecmp strnicmp #endif namespace XmlRpc { //! Utilities for XML parsing, encoding, and decoding and message handlers. class XMLRPCPP_DECL XmlRpcUtil { public: // hokey xml parsing //! Returns contents between <tag> and </tag>, updates offset to char after </tag> static std::string parseTag(const char* tag, std::string const& xml, int* offset); //! Returns true if the tag is found and updates offset to the char after the tag static bool findTag(const char* tag, std::string const& xml, int* offset); //! Returns the next tag and updates offset to the char after the tag, or empty string //! if the next non-whitespace character is not '<' static std::string getNextTag(std::string const& xml, int* offset); //! Returns true if the tag is found at the specified offset (modulo any whitespace) //! and updates offset to the char after the tag static bool nextTagIs(const char* tag, std::string const& xml, int* offset); //! Convert raw text to encoded xml. static std::string xmlEncode(const std::string& raw); //! Convert encoded xml to raw text static std::string xmlDecode(const std::string& encoded); //! Dump messages somewhere static void log(int level, const char* fmt, ...); //! Dump error messages somewhere static void error(const char* fmt, ...); }; } // namespace XmlRpc #endif // _XMLRPCUTIL_H_
0
apollo_public_repos/apollo-platform/ros/ros_comm/xmlrpcpp
apollo_public_repos/apollo-platform/ros/ros_comm/xmlrpcpp/include/XmlRpcDispatch.h
#ifndef _XMLRPCDISPATCH_H_ #define _XMLRPCDISPATCH_H_ // // XmlRpc++ Copyright (c) 2002-2003 by Chris Morley // #if defined(_MSC_VER) # pragma warning(disable:4786) // identifier was truncated in debug info #endif #include "XmlRpcDecl.h" #ifndef MAKEDEPEND # include <list> #endif namespace XmlRpc { // An RPC source represents a file descriptor to monitor class XmlRpcSource; //! An object which monitors file descriptors for events and performs //! callbacks when interesting events happen. class XMLRPCPP_DECL XmlRpcDispatch { public: //! Constructor XmlRpcDispatch(); ~XmlRpcDispatch(); //! Values indicating the type of events a source is interested in enum EventType { ReadableEvent = 1, //!< data available to read WritableEvent = 2, //!< connected/data can be written without blocking Exception = 4 //!< uh oh }; //! Monitor this source for the event types specified by the event mask //! and call its event handler when any of the events occur. //! @param source The source to monitor //! @param eventMask Which event types to watch for. \see EventType void addSource(XmlRpcSource* source, unsigned eventMask); //! Stop monitoring this source. //! @param source The source to stop monitoring void removeSource(XmlRpcSource* source); //! Modify the types of events to watch for on this source void setSourceEvents(XmlRpcSource* source, unsigned eventMask); //! Watch current set of sources and process events for the specified //! duration (in ms, -1 implies wait forever, or until exit is called) void work(double msTime); //! Exit from work routine void exit(); //! Clear all sources from the monitored sources list. Sources are closed. void clear(); // helper double getTime(); // A source to monitor and what to monitor it for struct MonitoredSource { MonitoredSource(XmlRpcSource* src, unsigned mask) : _src(src), _mask(mask) {} XmlRpcSource* getSource() const { return _src; } unsigned& getMask() { return _mask; } XmlRpcSource* _src; unsigned _mask; }; // A list of sources to monitor typedef std::list< MonitoredSource > SourceList; // Sources being monitored SourceList _sources; protected: // When work should stop (-1 implies wait forever, or until exit is called) double _endTime; bool _doClear; bool _inWork; }; } // namespace XmlRpc #endif // _XMLRPCDISPATCH_H_
0
apollo_public_repos/apollo-platform/ros/ros_comm/xmlrpcpp
apollo_public_repos/apollo-platform/ros/ros_comm/xmlrpcpp/include/base64.h
// base64.hpp // Autor Konstantin Pilipchuk // mailto:lostd@ukr.net // // #if !defined(__BASE64_H_INCLUDED__) #define __BASE64_H_INCLUDED__ 1 #ifndef MAKEDEPEND # include <iterator> #endif #include <ios> static int _base64Chars[]= {'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z', 'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z', '0','1','2','3','4','5','6','7','8','9', '+','/' }; #define _0000_0011 0x03 #define _1111_1100 0xFC #define _1111_0000 0xF0 #define _0011_0000 0x30 #define _0011_1100 0x3C #define _0000_1111 0x0F #define _1100_0000 0xC0 #define _0011_1111 0x3F #define _EQUAL_CHAR (-1) #define _UNKNOWN_CHAR (-2) #define _IOS_FAILBIT std::ios_base::failbit #define _IOS_EOFBIT std::ios_base::eofbit #define _IOS_BADBIT std::ios_base::badbit #define _IOS_GOODBIT std::ios_base::goodbit // TEMPLATE CLASS base64_put template<class _E = char, class _Tr = std::char_traits<_E> > class base64 { public: typedef unsigned char byte_t; typedef _E char_type; typedef _Tr traits_type; // base64 requires max line length <= 72 characters // you can fill end of line // it may be crlf, crlfsp, noline or other class like it struct crlf { template<class _OI> _OI operator()(_OI _To) const{ *_To = _Tr::to_char_type('\r'); ++_To; *_To = _Tr::to_char_type('\n'); ++_To; return (_To); } }; struct crlfsp { template<class _OI> _OI operator()(_OI _To) const{ *_To = _Tr::to_char_type('\r'); ++_To; *_To = _Tr::to_char_type('\n'); ++_To; *_To = _Tr::to_char_type(' '); ++_To; return (_To); } }; struct noline { template<class _OI> _OI operator()(_OI _To) const{ return (_To); } }; struct three2four { void zero() { _data[0] = 0; _data[1] = 0; _data[2] = 0; } byte_t get_0() const { return _data[0]; } byte_t get_1() const { return _data[1]; } byte_t get_2() const { return _data[2]; } void set_0(byte_t _ch) { _data[0] = _ch; } void set_1(byte_t _ch) { _data[1] = _ch; } void set_2(byte_t _ch) { _data[2] = _ch; } // 0000 0000 1111 1111 2222 2222 // xxxx xxxx xxxx xxxx xxxx xxxx // 0000 0011 1111 2222 2233 3333 int b64_0() const {return (_data[0] & _1111_1100) >> 2;} int b64_1() const {return ((_data[0] & _0000_0011) << 4) + ((_data[1] & _1111_0000)>>4);} int b64_2() const {return ((_data[1] & _0000_1111) << 2) + ((_data[2] & _1100_0000)>>6);} int b64_3() const {return (_data[2] & _0011_1111);} void b64_0(int _ch) {_data[0] = ((_ch & _0011_1111) << 2) | (_0000_0011 & _data[0]);} void b64_1(int _ch) { _data[0] = ((_ch & _0011_0000) >> 4) | (_1111_1100 & _data[0]); _data[1] = ((_ch & _0000_1111) << 4) | (_0000_1111 & _data[1]); } void b64_2(int _ch) { _data[1] = ((_ch & _0011_1100) >> 2) | (_1111_0000 & _data[1]); _data[2] = ((_ch & _0000_0011) << 6) | (_0011_1111 & _data[2]); } void b64_3(int _ch){ _data[2] = (_ch & _0011_1111) | (_1100_0000 & _data[2]);} private: byte_t _data[3]; }; template<class _II, class _OI, class _State, class _Endline> _II put(_II _First, _II _Last, _OI _To, _State&, _Endline) const { three2four _3to4; int line_octets = 0; while(_First != _Last) { _3to4.zero(); _3to4.set_0(*_First); _First++; if(_First == _Last) { *_To = _Tr::to_char_type(_base64Chars[_3to4.b64_0()]); ++_To; *_To = _Tr::to_char_type(_base64Chars[_3to4.b64_1()]); ++_To; *_To = _Tr::to_char_type('='); ++_To; *_To = _Tr::to_char_type('='); ++_To; goto __end; } _3to4.set_1(*_First); _First++; if(_First == _Last) { *_To = _Tr::to_char_type(_base64Chars[_3to4.b64_0()]); ++_To; *_To = _Tr::to_char_type(_base64Chars[_3to4.b64_1()]); ++_To; *_To = _Tr::to_char_type(_base64Chars[_3to4.b64_2()]); ++_To; *_To = _Tr::to_char_type('='); ++_To; goto __end; } _3to4.set_2(*_First); _First++; *_To = _Tr::to_char_type(_base64Chars[_3to4.b64_0()]); ++_To; *_To = _Tr::to_char_type(_base64Chars[_3to4.b64_1()]); ++_To; *_To = _Tr::to_char_type(_base64Chars[_3to4.b64_2()]); ++_To; *_To = _Tr::to_char_type(_base64Chars[_3to4.b64_3()]); ++_To; if(line_octets == 17) { //_To = _Endl(_To); *_To = '\n'; ++_To; line_octets = 0; } else ++line_octets; } __end: ; return (_First); } template<class _II, class _OI, class _State> _II get(_II _First, _II _Last, _OI _To, _State& _St) const { three2four _3to4; int _Char; while(_First != _Last) { // Take octet _3to4.zero(); // -- 0 -- // Search next valid char... while((_Char = _getCharType(*_First)) < 0 && _Char == _UNKNOWN_CHAR) { if(++_First == _Last) { _St |= _IOS_FAILBIT|_IOS_EOFBIT; return _First; // unexpected EOF } } if(_Char == _EQUAL_CHAR){ // Error! First character in octet can't be '=' _St |= _IOS_FAILBIT; return _First; } else _3to4.b64_0(_Char); // -- 1 -- // Search next valid char... while(++_First != _Last) if((_Char = _getCharType(*_First)) != _UNKNOWN_CHAR) break; if(_First == _Last) { _St |= _IOS_FAILBIT|_IOS_EOFBIT; // unexpected EOF return _First; } if(_Char == _EQUAL_CHAR){ // Error! Second character in octet can't be '=' _St |= _IOS_FAILBIT; return _First; } else _3to4.b64_1(_Char); // -- 2 -- // Search next valid char... while(++_First != _Last) if((_Char = _getCharType(*_First)) != _UNKNOWN_CHAR) break; if(_First == _Last) { // Error! Unexpected EOF. Must be '=' or base64 character _St |= _IOS_FAILBIT|_IOS_EOFBIT; return _First; } if(_Char == _EQUAL_CHAR){ // OK! _3to4.b64_2(0); _3to4.b64_3(0); // chek for EOF if(++_First == _Last) { // Error! Unexpected EOF. Must be '='. Ignore it. //_St |= _IOS_BADBIT|_IOS_EOFBIT; _St |= _IOS_EOFBIT; } else if(_getCharType(*_First) != _EQUAL_CHAR) { // Error! Must be '='. Ignore it. //_St |= _IOS_BADBIT; } else ++_First; // Skip '=' // write 1 std::uint8_t to output *_To = (byte_t) _3to4.get_0(); return _First; } else _3to4.b64_2(_Char); // -- 3 -- // Search next valid char... while(++_First != _Last) if((_Char = _getCharType(*_First)) != _UNKNOWN_CHAR) break; if(_First == _Last) { // Unexpected EOF. It's error. But ignore it. //_St |= _IOS_FAILBIT|_IOS_EOFBIT; _St |= _IOS_EOFBIT; return _First; } if(_Char == _EQUAL_CHAR) { // OK! _3to4.b64_3(0); // write to output 2 bytes *_To = (byte_t) _3to4.get_0(); *_To = (byte_t) _3to4.get_1(); ++_First; // set position to next character return _First; } else _3to4.b64_3(_Char); // write to output 3 bytes *_To = (byte_t) _3to4.get_0(); *_To = (byte_t) _3to4.get_1(); *_To = (byte_t) _3to4.get_2(); ++_First; } // while(_First != _Last) return (_First); } protected: int _getCharType(int _Ch) const { if(_base64Chars[62] == _Ch) return 62; if(_base64Chars[63] == _Ch) return 63; if((_base64Chars[0] <= _Ch) && (_base64Chars[25] >= _Ch)) return _Ch - _base64Chars[0]; if((_base64Chars[26] <= _Ch) && (_base64Chars[51] >= _Ch)) return _Ch - _base64Chars[26] + 26; if((_base64Chars[52] <= _Ch) && (_base64Chars[61] >= _Ch)) return _Ch - _base64Chars[52] + 52; if(_Ch == _Tr::to_int_type('=')) return _EQUAL_CHAR; return _UNKNOWN_CHAR; } }; #endif
0
apollo_public_repos/apollo-platform/ros/ros_comm/xmlrpcpp
apollo_public_repos/apollo-platform/ros/ros_comm/xmlrpcpp/include/XmlRpcServerMethod.h
#ifndef _XMLRPCSERVERMETHOD_H_ #define _XMLRPCSERVERMETHOD_H_ // // XmlRpc++ Copyright (c) 2002-2003 by Chris Morley // #if defined(_MSC_VER) # pragma warning(disable:4786) // identifier was truncated in debug info #endif #include "XmlRpcDecl.h" #ifndef MAKEDEPEND # include <string> #endif namespace XmlRpc { // Representation of a parameter or result value class XmlRpcValue; // The XmlRpcServer processes client requests to call RPCs class XmlRpcServer; //! Abstract class representing a single RPC method class XMLRPCPP_DECL XmlRpcServerMethod { public: //! Constructor XmlRpcServerMethod(std::string const& name, XmlRpcServer* server = 0); //! Destructor virtual ~XmlRpcServerMethod(); //! Returns the name of the method std::string& name() { return _name; } //! Execute the method. Subclasses must provide a definition for this method. virtual void execute(XmlRpcValue& params, XmlRpcValue& result) = 0; //! Returns a help string for the method. //! Subclasses should define this method if introspection is being used. virtual std::string help() { return std::string(); } protected: std::string _name; XmlRpcServer* _server; }; } // namespace XmlRpc #endif // _XMLRPCSERVERMETHOD_H_
0
apollo_public_repos/apollo-platform/ros/ros_comm/xmlrpcpp
apollo_public_repos/apollo-platform/ros/ros_comm/xmlrpcpp/include/XmlRpcException.h
#ifndef _XMLRPCEXCEPTION_H_ #define _XMLRPCEXCEPTION_H_ // // XmlRpc++ Copyright (c) 2002-2003 by Chris Morley // #if defined(_MSC_VER) # pragma warning(disable:4786) // identifier was truncated in debug info #endif #ifndef MAKEDEPEND # include <string> #endif #include "XmlRpcDecl.h" namespace XmlRpc { //! A class representing an error. //! If server methods throw this exception, a fault response is returned //! to the client. class XMLRPCPP_DECL XmlRpcException { public: //! Constructor //! @param message A descriptive error message //! @param code An integer error code XmlRpcException(const std::string& message, int code=-1) : _message(message), _code(code) {} //! Return the error message. const std::string& getMessage() const { return _message; } //! Return the error code. int getCode() const { return _code; } private: std::string _message; int _code; }; } #endif // _XMLRPCEXCEPTION_H_
0
apollo_public_repos/apollo-platform/ros/ros_comm/xmlrpcpp
apollo_public_repos/apollo-platform/ros/ros_comm/xmlrpcpp/include/XmlRpcValue.h
#ifndef _XMLRPCVALUE_H_ #define _XMLRPCVALUE_H_ // // XmlRpc++ Copyright (c) 2002-2003 by Chris Morley // #if defined(_MSC_VER) # pragma warning(disable:4786) // identifier was truncated in debug info #endif #include "XmlRpcDecl.h" #ifndef MAKEDEPEND # include <map> # include <string> # include <vector> # include <time.h> #endif namespace XmlRpc { //! RPC method arguments and results are represented by Values // should probably refcount them... class XMLRPCPP_DECL XmlRpcValue { public: enum Type { TypeInvalid, TypeBoolean, TypeInt, TypeDouble, TypeString, TypeDateTime, TypeBase64, TypeArray, TypeStruct }; // Non-primitive types typedef std::vector<char> BinaryData; typedef std::vector<XmlRpcValue> ValueArray; typedef std::map<std::string, XmlRpcValue> ValueStruct; typedef ValueStruct::iterator iterator; //! Constructors XmlRpcValue() : _type(TypeInvalid) { _value.asBinary = 0; } XmlRpcValue(bool value) : _type(TypeBoolean) { _value.asBool = value; } XmlRpcValue(int value) : _type(TypeInt) { _value.asInt = value; } XmlRpcValue(double value) : _type(TypeDouble) { _value.asDouble = value; } XmlRpcValue(std::string const& value) : _type(TypeString) { _value.asString = new std::string(value); } XmlRpcValue(const char* value) : _type(TypeString) { _value.asString = new std::string(value); } XmlRpcValue(struct tm* value) : _type(TypeDateTime) { _value.asTime = new struct tm(*value); } XmlRpcValue(void* value, int nBytes) : _type(TypeBase64) { _value.asBinary = new BinaryData((char*)value, ((char*)value)+nBytes); } //! Construct from xml, beginning at *offset chars into the string, updates offset XmlRpcValue(std::string const& xml, int* offset) : _type(TypeInvalid) { if ( ! fromXml(xml,offset)) _type = TypeInvalid; } //! Copy XmlRpcValue(XmlRpcValue const& rhs) : _type(TypeInvalid) { *this = rhs; } //! Destructor (make virtual if you want to subclass) /*virtual*/ ~XmlRpcValue() { invalidate(); } //! Erase the current value void clear() { invalidate(); } // Operators XmlRpcValue& operator=(XmlRpcValue const& rhs); XmlRpcValue& operator=(int const& rhs) { return operator=(XmlRpcValue(rhs)); } XmlRpcValue& operator=(double const& rhs) { return operator=(XmlRpcValue(rhs)); } XmlRpcValue& operator=(const char* rhs) { return operator=(XmlRpcValue(std::string(rhs))); } bool operator==(XmlRpcValue const& other) const; bool operator!=(XmlRpcValue const& other) const; operator bool&() { assertTypeOrInvalid(TypeBoolean); return _value.asBool; } operator int&() { assertTypeOrInvalid(TypeInt); return _value.asInt; } operator double&() { assertTypeOrInvalid(TypeDouble); return _value.asDouble; } operator std::string&() { assertTypeOrInvalid(TypeString); return *_value.asString; } operator BinaryData&() { assertTypeOrInvalid(TypeBase64); return *_value.asBinary; } operator struct tm&() { assertTypeOrInvalid(TypeDateTime); return *_value.asTime; } XmlRpcValue const& operator[](int i) const { assertArray(i+1); return _value.asArray->at(i); } XmlRpcValue& operator[](int i) { assertArray(i+1); return _value.asArray->at(i); } XmlRpcValue& operator[](std::string const& k) { assertStruct(); return (*_value.asStruct)[k]; } XmlRpcValue& operator[](const char* k) { assertStruct(); std::string s(k); return (*_value.asStruct)[s]; } iterator begin() {assertStruct(); return (*_value.asStruct).begin(); } iterator end() {assertStruct(); return (*_value.asStruct).end(); } // Accessors //! Return true if the value has been set to something. bool valid() const { return _type != TypeInvalid; } //! Return the type of the value stored. \see Type. Type const &getType() const { return _type; } //! Return the size for string, base64, array, and struct values. int size() const; //! Specify the size for array values. Array values will grow beyond this size if needed. void setSize(int size) { assertArray(size); } //! Check for the existence of a struct member by name. bool hasMember(const std::string& name) const; //! Decode xml. Destroys any existing value. bool fromXml(std::string const& valueXml, int* offset); //! Encode the Value in xml std::string toXml() const; //! Write the value (no xml encoding) std::ostream& write(std::ostream& os) const; // Formatting //! Return the format used to write double values. static std::string const& getDoubleFormat() { return _doubleFormat; } //! Specify the format used to write double values. static void setDoubleFormat(const char* f) { _doubleFormat = f; } protected: // Clean up void invalidate(); // Type checking void assertTypeOrInvalid(Type t); void assertArray(int size) const; void assertArray(int size); void assertStruct(); // XML decoding bool boolFromXml(std::string const& valueXml, int* offset); bool intFromXml(std::string const& valueXml, int* offset); bool doubleFromXml(std::string const& valueXml, int* offset); bool stringFromXml(std::string const& valueXml, int* offset); bool timeFromXml(std::string const& valueXml, int* offset); bool binaryFromXml(std::string const& valueXml, int* offset); bool arrayFromXml(std::string const& valueXml, int* offset); bool structFromXml(std::string const& valueXml, int* offset); // XML encoding std::string boolToXml() const; std::string intToXml() const; std::string doubleToXml() const; std::string stringToXml() const; std::string timeToXml() const; std::string binaryToXml() const; std::string arrayToXml() const; std::string structToXml() const; // Format strings static std::string _doubleFormat; // Type tag and values Type _type; // At some point I will split off Arrays and Structs into // separate ref-counted objects for more efficient copying. union { bool asBool; int asInt; double asDouble; struct tm* asTime; std::string* asString; BinaryData* asBinary; ValueArray* asArray; ValueStruct* asStruct; } _value; }; } // namespace XmlRpc std::ostream& operator<<(std::ostream& os, XmlRpc::XmlRpcValue& v); #endif // _XMLRPCVALUE_H_
0
apollo_public_repos/apollo-platform/ros/ros_comm/xmlrpcpp
apollo_public_repos/apollo-platform/ros/ros_comm/xmlrpcpp/include/XmlRpc.h
// this file modified by Morgan Quigley on 22 April 2008 to add // a std::exception-derived class #ifndef _XMLRPC_H_ #define _XMLRPC_H_ // // XmlRpc++ Copyright (c) 2002-2003 by Chris Morley // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 // #if defined(_MSC_VER) # pragma warning(disable:4786) // identifier was truncated in debug info #endif #ifndef MAKEDEPEND # include <string> #endif #include "XmlRpcClient.h" #include "XmlRpcException.h" #include "XmlRpcServer.h" #include "XmlRpcServerMethod.h" #include "XmlRpcValue.h" #include "XmlRpcUtil.h" #include <stdexcept> namespace XmlRpc { //! An interface allowing custom handling of error message reporting. class XmlRpcErrorHandler { public: virtual ~XmlRpcErrorHandler() { } //! Returns a pointer to the currently installed error handling object. static XmlRpcErrorHandler* getErrorHandler() { return _errorHandler; } //! Specifies the error handler. static void setErrorHandler(XmlRpcErrorHandler* eh) { _errorHandler = eh; } //! Report an error. Custom error handlers should define this method. virtual void error(const char* msg) = 0; protected: static XmlRpcErrorHandler* _errorHandler; }; //! An interface allowing custom handling of informational message reporting. class XmlRpcLogHandler { public: virtual ~XmlRpcLogHandler() { } //! Returns a pointer to the currently installed message reporting object. static XmlRpcLogHandler* getLogHandler() { return _logHandler; } //! Specifies the message handler. static void setLogHandler(XmlRpcLogHandler* lh) { _logHandler = lh; } //! Returns the level of verbosity of informational messages. 0 is no output, 5 is very verbose. static int getVerbosity() { return _verbosity; } //! Specify the level of verbosity of informational messages. 0 is no output, 5 is very verbose. static void setVerbosity(int v) { _verbosity = v; } //! Output a message. Custom error handlers should define this method. virtual void log(int level, const char* msg) = 0; protected: static XmlRpcLogHandler* _logHandler; static int _verbosity; }; //! Returns log message verbosity. This is short for XmlRpcLogHandler::getVerbosity() int getVerbosity(); //! Sets log message verbosity. This is short for XmlRpcLogHandler::setVerbosity(level) void setVerbosity(int level); //! Version identifier extern const char XMLRPC_VERSION[]; } // namespace XmlRpc #endif // _XMLRPC_H_
0
apollo_public_repos/apollo-platform/ros/ros_comm/xmlrpcpp
apollo_public_repos/apollo-platform/ros/ros_comm/xmlrpcpp/include/XmlRpcSource.h
#ifndef _XMLRPCSOURCE_H_ #define _XMLRPCSOURCE_H_ // // XmlRpc++ Copyright (c) 2002-2003 by Chris Morley // #if defined(_MSC_VER) # pragma warning(disable:4786) // identifier was truncated in debug info #endif #include "XmlRpcDecl.h" namespace XmlRpc { //! An RPC source represents a file descriptor to monitor class XMLRPCPP_DECL XmlRpcSource { public: //! Constructor //! @param fd The socket file descriptor to monitor. //! @param deleteOnClose If true, the object deletes itself when close is called. XmlRpcSource(int fd = -1, bool deleteOnClose = false); //! Destructor virtual ~XmlRpcSource(); //! Return the file descriptor being monitored. int getfd() const { return _fd; } //! Specify the file descriptor to monitor. void setfd(int fd) { _fd = fd; } //! Return whether the file descriptor should be kept open if it is no longer monitored. bool getKeepOpen() const { return _keepOpen; } //! Specify whether the file descriptor should be kept open if it is no longer monitored. void setKeepOpen(bool b=true) { _keepOpen = b; } //! Close the owned fd. If deleteOnClose was specified at construction, the object is deleted. virtual void close(); //! Return true to continue monitoring this source virtual unsigned handleEvent(unsigned eventType) = 0; private: // Socket. This should really be a SOCKET (an alias for unsigned int*) on windows... int _fd; // In the server, a new source (XmlRpcServerConnection) is created // for each connected client. When each connection is closed, the // corresponding source object is deleted. bool _deleteOnClose; // In the client, keep connections open if you intend to make multiple calls. bool _keepOpen; }; } // namespace XmlRpc #endif //_XMLRPCSOURCE_H_
0
apollo_public_repos/apollo-platform/ros/ros_comm/xmlrpcpp
apollo_public_repos/apollo-platform/ros/ros_comm/xmlrpcpp/include/XmlRpcDecl.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. * *********************************************************************/ /* * Cross platform macros. * */ #ifndef XMLRPCPP_DECL_H_INCLUDED #define XMLRPCPP_DECL_H_INCLUDED #include <ros/macros.h> #ifdef ROS_BUILD_SHARED_LIBS // ros is being built around shared libraries #ifdef xmlrpcpp_EXPORTS // we are building a shared lib/dll #define XMLRPCPP_DECL ROS_HELPER_EXPORT #else // we are using shared lib/dll #define XMLRPCPP_DECL ROS_HELPER_IMPORT #endif #else // ros is being built around static libraries #define XMLRPCPP_DECL #endif #endif /* XMLRPCPP_DECL_H_INCLUDED */
0
apollo_public_repos/apollo-platform/ros/ros_comm/xmlrpcpp
apollo_public_repos/apollo-platform/ros/ros_comm/xmlrpcpp/include/XmlRpcClient.h
#ifndef _XMLRPCCLIENT_H_ #define _XMLRPCCLIENT_H_ // // XmlRpc++ Copyright (c) 2002-2003 by Chris Morley // #if defined(_MSC_VER) # pragma warning(disable:4786) // identifier was truncated in debug info #endif #ifndef MAKEDEPEND # include <string> #endif #include "XmlRpcDispatch.h" #include "XmlRpcSource.h" #include "XmlRpcDecl.h" namespace XmlRpc { // Arguments and results are represented by XmlRpcValues class XmlRpcValue; //! A class to send XML RPC requests to a server and return the results. class XMLRPCPP_DECL XmlRpcClient : public XmlRpcSource { public: // Static data static const char REQUEST_BEGIN[]; static const char REQUEST_END_METHODNAME[]; static const char PARAMS_TAG[]; static const char PARAMS_ETAG[]; static const char PARAM_TAG[]; static const char PARAM_ETAG[]; static const char REQUEST_END[]; // Result tags static const char METHODRESPONSE_TAG[]; static const char FAULT_TAG[]; //! Construct a client to connect to the server at the specified host:port address //! @param host The name of the remote machine hosting the server //! @param port The port on the remote machine where the server is listening //! @param uri An optional string to be sent as the URI in the HTTP GET header XmlRpcClient(const char* host, int port, const char* uri=0); //! Destructor virtual ~XmlRpcClient(); //! Execute the named procedure on the remote server. //! @param method The name of the remote procedure to execute //! @param params An array of the arguments for the method //! @param result The result value to be returned to the client //! @return true if the request was sent and a result received //! (although the result might be a fault). //! //! Currently this is a synchronous (blocking) implementation (execute //! does not return until it receives a response or an error). Use isFault() //! to determine whether the result is a fault response. bool execute(const char* method, XmlRpcValue const& params, XmlRpcValue& result); bool executeNonBlock(const char* method, XmlRpcValue const& params); bool executeCheckDone(XmlRpcValue& result); //! Returns true if the result of the last execute() was a fault response. bool isFault() const { return _isFault; } // XmlRpcSource interface implementation //! Close the connection virtual void close(); //! Handle server responses. Called by the event dispatcher during execute. //! @param eventType The type of event that occurred. //! @see XmlRpcDispatch::EventType virtual unsigned handleEvent(unsigned eventType); protected: // Execution processing helpers virtual bool doConnect(); virtual bool setupConnection(); virtual bool generateRequest(const char* method, XmlRpcValue const& params); virtual std::string generateHeader(std::string const& body); virtual bool writeRequest(); virtual bool readHeader(); virtual bool readResponse(); virtual bool parseResponse(XmlRpcValue& result); // Possible IO states for the connection enum ClientConnectionState { NO_CONNECTION, CONNECTING, WRITE_REQUEST, READ_HEADER, READ_RESPONSE, IDLE }; ClientConnectionState _connectionState; // Server location std::string _host; std::string _uri; int _port; public: const std::string &getHost() { return _host; } const std::string &getUri() { return _uri; } int getPort() const { return _port; } // The xml-encoded request, http header of response, and response xml std::string _request; std::string _header; std::string _response; // Number of times the client has attempted to send the request int _sendAttempts; // Number of bytes of the request that have been written to the socket so far int _bytesWritten; // True if we are currently executing a request. If you want to multithread, // each thread should have its own client. bool _executing; // True if the server closed the connection bool _eof; // True if a fault response was returned by the server bool _isFault; // Number of bytes expected in the response body (parsed from response header) int _contentLength; // Event dispatcher XmlRpcDispatch _disp; }; // class XmlRpcClient } // namespace XmlRpc #endif // _XMLRPCCLIENT_H_
0
apollo_public_repos/apollo-platform/ros/ros_comm/xmlrpcpp
apollo_public_repos/apollo-platform/ros/ros_comm/xmlrpcpp/include/XmlRpcServerConnection.h
#ifndef _XMLRPCSERVERCONNECTION_H_ #define _XMLRPCSERVERCONNECTION_H_ // // XmlRpc++ Copyright (c) 2002-2003 by Chris Morley // #if defined(_MSC_VER) # pragma warning(disable:4786) // identifier was truncated in debug info #endif #ifndef MAKEDEPEND # include <string> #endif #include "XmlRpcValue.h" #include "XmlRpcSource.h" #include "XmlRpcDecl.h" namespace XmlRpc { // The server waits for client connections and provides methods class XmlRpcServer; class XmlRpcServerMethod; //! A class to handle XML RPC requests from a particular client class XMLRPCPP_DECL XmlRpcServerConnection : public XmlRpcSource { public: // Static data static const char METHODNAME_TAG[]; static const char PARAMS_TAG[]; static const char PARAMS_ETAG[]; static const char PARAM_TAG[]; static const char PARAM_ETAG[]; static const std::string SYSTEM_MULTICALL; static const std::string METHODNAME; static const std::string PARAMS; static const std::string FAULTCODE; static const std::string FAULTSTRING; //! Constructor XmlRpcServerConnection(int fd, XmlRpcServer* server, bool deleteOnClose = false); //! Destructor virtual ~XmlRpcServerConnection(); // XmlRpcSource interface implementation //! Handle IO on the client connection socket. //! @param eventType Type of IO event that occurred. @see XmlRpcDispatch::EventType. virtual unsigned handleEvent(unsigned eventType); protected: bool readHeader(); bool readRequest(); bool writeResponse(); // Parses the request, runs the method, generates the response xml. virtual void executeRequest(); // Parse the methodName and parameters from the request. std::string parseRequest(XmlRpcValue& params); // Execute a named method with the specified params. bool executeMethod(const std::string& methodName, XmlRpcValue& params, XmlRpcValue& result); // Execute multiple calls and return the results in an array. bool executeMulticall(const std::string& methodName, XmlRpcValue& params, XmlRpcValue& result); // Construct a response from the result XML. void generateResponse(std::string const& resultXml); void generateFaultResponse(std::string const& msg, int errorCode = -1); std::string generateHeader(std::string const& body); // The XmlRpc server that accepted this connection XmlRpcServer* _server; // Possible IO states for the connection enum ServerConnectionState { READ_HEADER, READ_REQUEST, WRITE_RESPONSE }; ServerConnectionState _connectionState; // Request headers std::string _header; // Number of bytes expected in the request body (parsed from header) int _contentLength; // Request body std::string _request; // Response std::string _response; // Number of bytes of the response written so far int _bytesWritten; // Whether to keep the current client connection open for further requests bool _keepAlive; }; } // namespace XmlRpc #endif // _XMLRPCSERVERCONNECTION_H_
0
apollo_public_repos/apollo-platform/ros/ros_comm/xmlrpcpp
apollo_public_repos/apollo-platform/ros/ros_comm/xmlrpcpp/src/XmlRpcDispatch.cpp
#include "XmlRpcDispatch.h" #include "XmlRpcSource.h" #include "XmlRpcUtil.h" #include <math.h> #include <errno.h> #include <sys/timeb.h> #if defined (__ANDROID__) #include <sys/select.h> #endif #if defined(_WINDOWS) # include <winsock2.h> # define USE_FTIME # if defined(_MSC_VER) # define timeb _timeb # define ftime _ftime_s # endif #else # include <sys/time.h> #endif // _WINDOWS using namespace XmlRpc; XmlRpcDispatch::XmlRpcDispatch() { _endTime = -1.0; _doClear = false; _inWork = false; } XmlRpcDispatch::~XmlRpcDispatch() { } // Monitor this source for the specified events and call its event handler // when the event occurs void XmlRpcDispatch::addSource(XmlRpcSource* source, unsigned mask) { _sources.push_back(MonitoredSource(source, mask)); } // Stop monitoring this source. Does not close the source. void XmlRpcDispatch::removeSource(XmlRpcSource* source) { for (SourceList::iterator it=_sources.begin(); it!=_sources.end(); ++it) if (it->getSource() == source) { _sources.erase(it); break; } } // Modify the types of events to watch for on this source void XmlRpcDispatch::setSourceEvents(XmlRpcSource* source, unsigned eventMask) { for (SourceList::iterator it=_sources.begin(); it!=_sources.end(); ++it) if (it->getSource() == source) { it->getMask() = eventMask; break; } } // Watch current set of sources and process events void XmlRpcDispatch::work(double timeout) { // Compute end time _endTime = (timeout < 0.0) ? -1.0 : (getTime() + timeout); _doClear = false; _inWork = true; // Only work while there is something to monitor while (_sources.size() > 0) { // Construct the sets of descriptors we are interested in fd_set inFd, outFd, excFd; FD_ZERO(&inFd); FD_ZERO(&outFd); FD_ZERO(&excFd); int maxFd = -1; // Not used on windows SourceList::iterator it; for (it=_sources.begin(); it!=_sources.end(); ++it) { int fd = it->getSource()->getfd(); if (it->getMask() & ReadableEvent) FD_SET(fd, &inFd); if (it->getMask() & WritableEvent) FD_SET(fd, &outFd); if (it->getMask() & Exception) FD_SET(fd, &excFd); if (it->getMask() && fd > maxFd) maxFd = fd; } // Check for events int nEvents; if (timeout < 0.0) nEvents = select(maxFd+1, &inFd, &outFd, &excFd, NULL); else { struct timeval tv; tv.tv_sec = (int)floor(timeout); tv.tv_usec = ((int)floor(1000000.0 * (timeout-floor(timeout)))) % 1000000; nEvents = select(maxFd+1, &inFd, &outFd, &excFd, &tv); } if (nEvents < 0) { if(errno != EINTR) XmlRpcUtil::error("Error in XmlRpcDispatch::work: error in select (%d).", nEvents); _inWork = false; return; } // Process events for (it=_sources.begin(); it != _sources.end(); ) { SourceList::iterator thisIt = it++; XmlRpcSource* src = thisIt->getSource(); int fd = src->getfd(); unsigned newMask = (unsigned) -1; if (fd <= maxFd) { // If you select on multiple event types this could be ambiguous if (FD_ISSET(fd, &inFd)) newMask &= src->handleEvent(ReadableEvent); if (FD_ISSET(fd, &outFd)) newMask &= src->handleEvent(WritableEvent); if (FD_ISSET(fd, &excFd)) newMask &= src->handleEvent(Exception); // Find the source again. It may have moved as a result of the way // that sources are removed and added in the call stack starting // from the handleEvent() calls above. for (thisIt=_sources.begin(); thisIt != _sources.end(); thisIt++) { if(thisIt->getSource() == src) break; } if(thisIt == _sources.end()) { XmlRpcUtil::error("Error in XmlRpcDispatch::work: couldn't find source iterator"); continue; } if ( ! newMask) { _sources.erase(thisIt); // Stop monitoring this one if ( ! src->getKeepOpen()) src->close(); } else if (newMask != (unsigned) -1) { thisIt->getMask() = newMask; } } } // Check whether to clear all sources if (_doClear) { SourceList closeList = _sources; _sources.clear(); for (SourceList::iterator it=closeList.begin(); it!=closeList.end(); ++it) { XmlRpcSource *src = it->getSource(); src->close(); } _doClear = false; } // Check whether end time has passed if (0 <= _endTime && getTime() > _endTime) break; } _inWork = false; } // Exit from work routine. Presumably this will be called from // one of the source event handlers. void XmlRpcDispatch::exit() { _endTime = 0.0; // Return from work asap } // Clear all sources from the monitored sources list void XmlRpcDispatch::clear() { if (_inWork) _doClear = true; // Finish reporting current events before clearing else { SourceList closeList = _sources; _sources.clear(); for (SourceList::iterator it=closeList.begin(); it!=closeList.end(); ++it) it->getSource()->close(); } } double XmlRpcDispatch::getTime() { #ifdef USE_FTIME struct timeb tbuff; ftime(&tbuff); return ((double) tbuff.time + ((double)tbuff.millitm / 1000.0) + ((double) tbuff.timezone * 60)); #else struct timeval tv; struct timezone tz; gettimeofday(&tv, &tz); return (tv.tv_sec + tv.tv_usec / 1000000.0); #endif /* USE_FTIME */ }
0
apollo_public_repos/apollo-platform/ros/ros_comm/xmlrpcpp
apollo_public_repos/apollo-platform/ros/ros_comm/xmlrpcpp/src/XmlRpcServerConnection.cpp
#include "XmlRpcServerConnection.h" #include "XmlRpcSocket.h" #include "XmlRpc.h" #ifndef MAKEDEPEND # include <stdio.h> # include <stdlib.h> #ifndef _WINDOWS # include <strings.h> #endif # include <string.h> #endif using namespace XmlRpc; // Static data const char XmlRpcServerConnection::METHODNAME_TAG[] = "<methodName>"; const char XmlRpcServerConnection::PARAMS_TAG[] = "<params>"; const char XmlRpcServerConnection::PARAMS_ETAG[] = "</params>"; const char XmlRpcServerConnection::PARAM_TAG[] = "<param>"; const char XmlRpcServerConnection::PARAM_ETAG[] = "</param>"; const std::string XmlRpcServerConnection::SYSTEM_MULTICALL = "system.multicall"; const std::string XmlRpcServerConnection::METHODNAME = "methodName"; const std::string XmlRpcServerConnection::PARAMS = "params"; const std::string XmlRpcServerConnection::FAULTCODE = "faultCode"; const std::string XmlRpcServerConnection::FAULTSTRING = "faultString"; // The server delegates handling client requests to a serverConnection object. XmlRpcServerConnection::XmlRpcServerConnection(int fd, XmlRpcServer* server, bool deleteOnClose /*= false*/) : XmlRpcSource(fd, deleteOnClose) { XmlRpcUtil::log(2,"XmlRpcServerConnection: new socket %d.", fd); _server = server; _connectionState = READ_HEADER; _contentLength = 0; _bytesWritten = 0; _keepAlive = true; } XmlRpcServerConnection::~XmlRpcServerConnection() { XmlRpcUtil::log(4,"XmlRpcServerConnection dtor."); _server->removeConnection(this); } // Handle input on the server socket by accepting the connection // and reading the rpc request. Return true to continue to monitor // the socket for events, false to remove it from the dispatcher. unsigned XmlRpcServerConnection::handleEvent(unsigned /*eventType*/) { if (_connectionState == READ_HEADER) if ( ! readHeader()) return 0; if (_connectionState == READ_REQUEST) if ( ! readRequest()) return 0; if (_connectionState == WRITE_RESPONSE) if ( ! writeResponse()) return 0; return (_connectionState == WRITE_RESPONSE) ? XmlRpcDispatch::WritableEvent : XmlRpcDispatch::ReadableEvent; } bool XmlRpcServerConnection::readHeader() { // Read available data bool eof; if ( ! XmlRpcSocket::nbRead(this->getfd(), _header, &eof)) { // Its only an error if we already have read some data if (_header.length() > 0) XmlRpcUtil::error("XmlRpcServerConnection::readHeader: error while reading header (%s).",XmlRpcSocket::getErrorMsg().c_str()); return false; } XmlRpcUtil::log(4, "XmlRpcServerConnection::readHeader: read %d bytes.", _header.length()); char *hp = (char*)_header.c_str(); // Start of header char *ep = hp + _header.length(); // End of string char *bp = 0; // Start of body char *lp = 0; // Start of content-length value char *kp = 0; // Start of connection value for (char *cp = hp; (bp == 0) && (cp < ep); ++cp) { if ((ep - cp > 16) && (strncasecmp(cp, "Content-length: ", 16) == 0)) lp = cp + 16; else if ((ep - cp > 12) && (strncasecmp(cp, "Connection: ", 12) == 0)) kp = cp + 12; else if ((ep - cp > 4) && (strncmp(cp, "\r\n\r\n", 4) == 0)) bp = cp + 4; else if ((ep - cp > 2) && (strncmp(cp, "\n\n", 2) == 0)) bp = cp + 2; } // If we haven't gotten the entire header yet, return (keep reading) if (bp == 0) { // EOF in the middle of a request is an error, otherwise its ok if (eof) { XmlRpcUtil::log(4, "XmlRpcServerConnection::readHeader: EOF"); if (_header.length() > 0) XmlRpcUtil::error("XmlRpcServerConnection::readHeader: EOF while reading header"); return false; // Either way we close the connection } return true; // Keep reading } // Decode content length if (lp == 0) { XmlRpcUtil::error("XmlRpcServerConnection::readHeader: No Content-length specified"); return false; // We could try to figure it out by parsing as we read, but for now... } _contentLength = atoi(lp); if (_contentLength <= 0) { XmlRpcUtil::error("XmlRpcServerConnection::readHeader: Invalid Content-length specified (%d).", _contentLength); return false; } XmlRpcUtil::log(3, "XmlRpcServerConnection::readHeader: specified content length is %d.", _contentLength); // Otherwise copy non-header data to request buffer and set state to read request. _request = bp; // Parse out any interesting bits from the header (HTTP version, connection) _keepAlive = true; if (_header.find("HTTP/1.0") != std::string::npos) { if (kp == 0 || strncasecmp(kp, "keep-alive", 10) != 0) _keepAlive = false; // Default for HTTP 1.0 is to close the connection } else { if (kp != 0 && strncasecmp(kp, "close", 5) == 0) _keepAlive = false; } XmlRpcUtil::log(3, "KeepAlive: %d", _keepAlive); _header = ""; _connectionState = READ_REQUEST; return true; // Continue monitoring this source } bool XmlRpcServerConnection::readRequest() { // If we dont have the entire request yet, read available data if (int(_request.length()) < _contentLength) { bool eof; if ( ! XmlRpcSocket::nbRead(this->getfd(), _request, &eof)) { XmlRpcUtil::error("XmlRpcServerConnection::readRequest: read error (%s).",XmlRpcSocket::getErrorMsg().c_str()); return false; } // If we haven't gotten the entire request yet, return (keep reading) if (int(_request.length()) < _contentLength) { if (eof) { XmlRpcUtil::error("XmlRpcServerConnection::readRequest: EOF while reading request"); return false; // Either way we close the connection } return true; } } // Otherwise, parse and dispatch the request XmlRpcUtil::log(3, "XmlRpcServerConnection::readRequest read %d bytes.", _request.length()); //XmlRpcUtil::log(5, "XmlRpcServerConnection::readRequest:\n%s\n", _request.c_str()); _connectionState = WRITE_RESPONSE; return true; // Continue monitoring this source } bool XmlRpcServerConnection::writeResponse() { if (_response.length() == 0) { executeRequest(); _bytesWritten = 0; if (_response.length() == 0) { XmlRpcUtil::error("XmlRpcServerConnection::writeResponse: empty response."); return false; } } // Try to write the response if ( ! XmlRpcSocket::nbWrite(this->getfd(), _response, &_bytesWritten)) { XmlRpcUtil::error("XmlRpcServerConnection::writeResponse: write error (%s).",XmlRpcSocket::getErrorMsg().c_str()); return false; } XmlRpcUtil::log(3, "XmlRpcServerConnection::writeResponse: wrote %d of %d bytes.", _bytesWritten, _response.length()); // Prepare to read the next request if (_bytesWritten == int(_response.length())) { _header = ""; _request = ""; _response = ""; _connectionState = READ_HEADER; } return _keepAlive; // Continue monitoring this source if true } // Run the method, generate _response string void XmlRpcServerConnection::executeRequest() { XmlRpcValue params, resultValue; std::string methodName = parseRequest(params); XmlRpcUtil::log(2, "XmlRpcServerConnection::executeRequest: server calling method '%s'", methodName.c_str()); try { if ( ! executeMethod(methodName, params, resultValue) && ! executeMulticall(methodName, params, resultValue)) generateFaultResponse(methodName + ": unknown method name"); else generateResponse(resultValue.toXml()); } catch (const XmlRpcException& fault) { XmlRpcUtil::log(2, "XmlRpcServerConnection::executeRequest: fault %s.", fault.getMessage().c_str()); generateFaultResponse(fault.getMessage(), fault.getCode()); } } // Parse the method name and the argument values from the request. std::string XmlRpcServerConnection::parseRequest(XmlRpcValue& params) { int offset = 0; // Number of chars parsed from the request std::string methodName = XmlRpcUtil::parseTag(METHODNAME_TAG, _request, &offset); if (methodName.size() > 0 && XmlRpcUtil::findTag(PARAMS_TAG, _request, &offset)) { int nArgs = 0; while (XmlRpcUtil::nextTagIs(PARAM_TAG, _request, &offset)) { params[nArgs++] = XmlRpcValue(_request, &offset); (void) XmlRpcUtil::nextTagIs(PARAM_ETAG, _request, &offset); } (void) XmlRpcUtil::nextTagIs(PARAMS_ETAG, _request, &offset); } return methodName; } // Execute a named method with the specified params. bool XmlRpcServerConnection::executeMethod(const std::string& methodName, XmlRpcValue& params, XmlRpcValue& result) { XmlRpcServerMethod* method = _server->findMethod(methodName); if ( ! method) return false; method->execute(params, result); // Ensure a valid result value if ( ! result.valid()) result = std::string(); return true; } // Execute multiple calls and return the results in an array. bool XmlRpcServerConnection::executeMulticall(const std::string& methodName, XmlRpcValue& params, XmlRpcValue& result) { if (methodName != SYSTEM_MULTICALL) return false; // There ought to be 1 parameter, an array of structs if (params.size() != 1 || params[0].getType() != XmlRpcValue::TypeArray) throw XmlRpcException(SYSTEM_MULTICALL + ": Invalid argument (expected an array)"); int nc = params[0].size(); result.setSize(nc); for (int i=0; i<nc; ++i) { if ( ! params[0][i].hasMember(METHODNAME) || ! params[0][i].hasMember(PARAMS)) { result[i][FAULTCODE] = -1; result[i][FAULTSTRING] = SYSTEM_MULTICALL + ": Invalid argument (expected a struct with members methodName and params)"; continue; } const std::string& methodName = params[0][i][METHODNAME]; XmlRpcValue& methodParams = params[0][i][PARAMS]; XmlRpcValue resultValue; resultValue.setSize(1); try { if ( ! executeMethod(methodName, methodParams, resultValue[0]) && ! executeMulticall(methodName, params, resultValue[0])) { result[i][FAULTCODE] = -1; result[i][FAULTSTRING] = methodName + ": unknown method name"; } else result[i] = resultValue; } catch (const XmlRpcException& fault) { result[i][FAULTCODE] = fault.getCode(); result[i][FAULTSTRING] = fault.getMessage(); } } return true; } // Create a response from results xml void XmlRpcServerConnection::generateResponse(std::string const& resultXml) { const char RESPONSE_1[] = "<?xml version=\"1.0\"?>\r\n" "<methodResponse><params><param>\r\n\t"; const char RESPONSE_2[] = "\r\n</param></params></methodResponse>\r\n"; std::string body = RESPONSE_1 + resultXml + RESPONSE_2; std::string header = generateHeader(body); _response = header + body; XmlRpcUtil::log(5, "XmlRpcServerConnection::generateResponse:\n%s\n", _response.c_str()); } // Prepend http headers std::string XmlRpcServerConnection::generateHeader(std::string const& body) { std::string header = "HTTP/1.1 200 OK\r\n" "Server: "; header += XMLRPC_VERSION; header += "\r\n" "Content-Type: text/xml\r\n" "Content-length: "; char buffLen[40]; #ifdef _MSC_VER sprintf_s(buffLen,40,"%d\r\n\r\n", (int)body.size()); #else sprintf(buffLen,"%d\r\n\r\n", (int)body.size()); #endif return header + buffLen; } void XmlRpcServerConnection::generateFaultResponse(std::string const& errorMsg, int errorCode) { const char RESPONSE_1[] = "<?xml version=\"1.0\"?>\r\n" "<methodResponse><fault>\r\n\t"; const char RESPONSE_2[] = "\r\n</fault></methodResponse>\r\n"; XmlRpcValue faultStruct; faultStruct[FAULTCODE] = errorCode; faultStruct[FAULTSTRING] = errorMsg; std::string body = RESPONSE_1 + faultStruct.toXml() + RESPONSE_2; std::string header = generateHeader(body); _response = header + body; }
0
apollo_public_repos/apollo-platform/ros/ros_comm/xmlrpcpp
apollo_public_repos/apollo-platform/ros/ros_comm/xmlrpcpp/src/XmlRpcValue.cpp
#include "XmlRpcValue.h" #include "XmlRpcException.h" #include "XmlRpcUtil.h" #include "base64.h" #ifndef MAKEDEPEND # include <iostream> # include <ostream> # include <stdlib.h> # include <stdio.h> #endif #include <sstream> namespace XmlRpc { static const char VALUE_TAG[] = "<value>"; static const char VALUE_ETAG[] = "</value>"; static const char BOOLEAN_TAG[] = "<boolean>"; static const char BOOLEAN_ETAG[] = "</boolean>"; static const char DOUBLE_TAG[] = "<double>"; static const char DOUBLE_ETAG[] = "</double>"; static const char INT_TAG[] = "<int>"; static const char I4_TAG[] = "<i4>"; static const char I4_ETAG[] = "</i4>"; static const char STRING_TAG[] = "<string>"; static const char DATETIME_TAG[] = "<dateTime.iso8601>"; static const char DATETIME_ETAG[] = "</dateTime.iso8601>"; static const char BASE64_TAG[] = "<base64>"; static const char BASE64_ETAG[] = "</base64>"; static const char ARRAY_TAG[] = "<array>"; static const char DATA_TAG[] = "<data>"; static const char DATA_ETAG[] = "</data>"; static const char ARRAY_ETAG[] = "</array>"; static const char STRUCT_TAG[] = "<struct>"; static const char MEMBER_TAG[] = "<member>"; static const char NAME_TAG[] = "<name>"; static const char NAME_ETAG[] = "</name>"; static const char MEMBER_ETAG[] = "</member>"; static const char STRUCT_ETAG[] = "</struct>"; // Format strings std::string XmlRpcValue::_doubleFormat("%.16g"); // Clean up void XmlRpcValue::invalidate() { switch (_type) { case TypeString: delete _value.asString; break; case TypeDateTime: delete _value.asTime; break; case TypeBase64: delete _value.asBinary; break; case TypeArray: delete _value.asArray; break; case TypeStruct: delete _value.asStruct; break; default: break; } _type = TypeInvalid; _value.asBinary = 0; } // Type checking void XmlRpcValue::assertTypeOrInvalid(Type t) { if (_type == TypeInvalid) { _type = t; switch (_type) { // Ensure there is a valid value for the type case TypeString: _value.asString = new std::string(); break; case TypeDateTime: _value.asTime = new struct tm(); break; case TypeBase64: _value.asBinary = new BinaryData(); break; case TypeArray: _value.asArray = new ValueArray(); break; case TypeStruct: _value.asStruct = new ValueStruct(); break; default: _value.asBinary = 0; break; } } else if (_type != t) throw XmlRpcException("type error"); } void XmlRpcValue::assertArray(int size) const { if (_type != TypeArray) throw XmlRpcException("type error: expected an array"); else if (int(_value.asArray->size()) < size) throw XmlRpcException("range error: array index too large"); } void XmlRpcValue::assertArray(int size) { if (_type == TypeInvalid) { _type = TypeArray; _value.asArray = new ValueArray(size); } else if (_type == TypeArray) { if (int(_value.asArray->size()) < size) _value.asArray->resize(size); } else throw XmlRpcException("type error: expected an array"); } void XmlRpcValue::assertStruct() { if (_type == TypeInvalid) { _type = TypeStruct; _value.asStruct = new ValueStruct(); } else if (_type != TypeStruct) throw XmlRpcException("type error: expected a struct"); } // Operators XmlRpcValue& XmlRpcValue::operator=(XmlRpcValue const& rhs) { if (this != &rhs) { invalidate(); _type = rhs._type; switch (_type) { case TypeBoolean: _value.asBool = rhs._value.asBool; break; case TypeInt: _value.asInt = rhs._value.asInt; break; case TypeDouble: _value.asDouble = rhs._value.asDouble; break; case TypeDateTime: _value.asTime = new struct tm(*rhs._value.asTime); break; case TypeString: _value.asString = new std::string(*rhs._value.asString); break; case TypeBase64: _value.asBinary = new BinaryData(*rhs._value.asBinary); break; case TypeArray: _value.asArray = new ValueArray(*rhs._value.asArray); break; case TypeStruct: _value.asStruct = new ValueStruct(*rhs._value.asStruct); break; default: _value.asBinary = 0; break; } } return *this; } // Predicate for tm equality static bool tmEq(struct tm const& t1, struct tm const& t2) { return t1.tm_sec == t2.tm_sec && t1.tm_min == t2.tm_min && t1.tm_hour == t2.tm_hour && t1.tm_mday == t2.tm_mday && t1.tm_mon == t2.tm_mon && t1.tm_year == t2.tm_year; } bool XmlRpcValue::operator==(XmlRpcValue const& other) const { if (_type != other._type) return false; switch (_type) { case TypeBoolean: return ( !_value.asBool && !other._value.asBool) || ( _value.asBool && other._value.asBool); case TypeInt: return _value.asInt == other._value.asInt; case TypeDouble: return _value.asDouble == other._value.asDouble; case TypeDateTime: return tmEq(*_value.asTime, *other._value.asTime); case TypeString: return *_value.asString == *other._value.asString; case TypeBase64: return *_value.asBinary == *other._value.asBinary; case TypeArray: return *_value.asArray == *other._value.asArray; // The map<>::operator== requires the definition of value< for kcc case TypeStruct: //return *_value.asStruct == *other._value.asStruct; { if (_value.asStruct->size() != other._value.asStruct->size()) return false; ValueStruct::const_iterator it1=_value.asStruct->begin(); ValueStruct::const_iterator it2=other._value.asStruct->begin(); while (it1 != _value.asStruct->end()) { const XmlRpcValue& v1 = it1->second; const XmlRpcValue& v2 = it2->second; if ( ! (v1 == v2)) return false; it1++; it2++; } return true; } default: break; } return true; // Both invalid values ... } bool XmlRpcValue::operator!=(XmlRpcValue const& other) const { return !(*this == other); } // Works for strings, binary data, arrays, and structs. int XmlRpcValue::size() const { switch (_type) { case TypeString: return int(_value.asString->size()); case TypeBase64: return int(_value.asBinary->size()); case TypeArray: return int(_value.asArray->size()); case TypeStruct: return int(_value.asStruct->size()); default: break; } throw XmlRpcException("type error"); } // Checks for existence of struct member bool XmlRpcValue::hasMember(const std::string& name) const { return _type == TypeStruct && _value.asStruct->find(name) != _value.asStruct->end(); } // Set the value from xml. The chars at *offset into valueXml // should be the start of a <value> tag. Destroys any existing value. bool XmlRpcValue::fromXml(std::string const& valueXml, int* offset) { int savedOffset = *offset; invalidate(); if ( ! XmlRpcUtil::nextTagIs(VALUE_TAG, valueXml, offset)) return false; // Not a value, offset not updated int afterValueOffset = *offset; std::string typeTag = XmlRpcUtil::getNextTag(valueXml, offset); bool result = false; if (typeTag == BOOLEAN_TAG) result = boolFromXml(valueXml, offset); else if (typeTag == I4_TAG || typeTag == INT_TAG) result = intFromXml(valueXml, offset); else if (typeTag == DOUBLE_TAG) result = doubleFromXml(valueXml, offset); else if (typeTag.empty() || typeTag == STRING_TAG) result = stringFromXml(valueXml, offset); else if (typeTag == DATETIME_TAG) result = timeFromXml(valueXml, offset); else if (typeTag == BASE64_TAG) result = binaryFromXml(valueXml, offset); else if (typeTag == ARRAY_TAG) result = arrayFromXml(valueXml, offset); else if (typeTag == STRUCT_TAG) result = structFromXml(valueXml, offset); // Watch for empty/blank strings with no <string>tag else if (typeTag == VALUE_ETAG) { *offset = afterValueOffset; // back up & try again result = stringFromXml(valueXml, offset); } if (result) // Skip over the </value> tag XmlRpcUtil::findTag(VALUE_ETAG, valueXml, offset); else // Unrecognized tag after <value> *offset = savedOffset; return result; } // Encode the Value in xml std::string XmlRpcValue::toXml() const { switch (_type) { case TypeBoolean: return boolToXml(); case TypeInt: return intToXml(); case TypeDouble: return doubleToXml(); case TypeString: return stringToXml(); case TypeDateTime: return timeToXml(); case TypeBase64: return binaryToXml(); case TypeArray: return arrayToXml(); case TypeStruct: return structToXml(); default: break; } return std::string(); // Invalid value } // Boolean bool XmlRpcValue::boolFromXml(std::string const& valueXml, int* offset) { const char* valueStart = valueXml.c_str() + *offset; char* valueEnd; long ivalue = strtol(valueStart, &valueEnd, 10); if (valueEnd == valueStart || (ivalue != 0 && ivalue != 1)) return false; _type = TypeBoolean; _value.asBool = (ivalue == 1); *offset += int(valueEnd - valueStart); return true; } std::string XmlRpcValue::boolToXml() const { std::string xml = VALUE_TAG; xml += BOOLEAN_TAG; xml += (_value.asBool ? "1" : "0"); xml += BOOLEAN_ETAG; xml += VALUE_ETAG; return xml; } // Int bool XmlRpcValue::intFromXml(std::string const& valueXml, int* offset) { const char* valueStart = valueXml.c_str() + *offset; char* valueEnd; long ivalue = strtol(valueStart, &valueEnd, 10); if (valueEnd == valueStart) return false; _type = TypeInt; _value.asInt = int(ivalue); *offset += int(valueEnd - valueStart); return true; } std::string XmlRpcValue::intToXml() const { char buf[256]; snprintf(buf, sizeof(buf)-1, "%d", _value.asInt); buf[sizeof(buf)-1] = 0; std::string xml = VALUE_TAG; xml += I4_TAG; xml += buf; xml += I4_ETAG; xml += VALUE_ETAG; return xml; } // Double bool XmlRpcValue::doubleFromXml(std::string const& valueXml, int* offset) { const char* valueStart = valueXml.c_str() + *offset; char* valueEnd; // ticket #2438 // push/pop the locale here. Value 123.45 can get read by strtod // as '123', if the locale expects a comma instead of dot. // if there are locale problems, silently continue. std::string tmplocale; char* locale_cstr = setlocale(LC_NUMERIC, 0); if (locale_cstr) { tmplocale = locale_cstr; setlocale(LC_NUMERIC, "POSIX"); } double dvalue = strtod(valueStart, &valueEnd); if (tmplocale.size() > 0) { setlocale(LC_NUMERIC, tmplocale.c_str()); } if (valueEnd == valueStart) return false; _type = TypeDouble; _value.asDouble = dvalue; *offset += int(valueEnd - valueStart); return true; } std::string XmlRpcValue::doubleToXml() const { // ticket #2438 std::stringstream ss; ss.imbue(std::locale::classic()); // ensure we're using "C" locale for formatting floating-point (1.4 vs. 1,4, etc.) ss.precision(17); ss << _value.asDouble; std::string xml = VALUE_TAG; xml += DOUBLE_TAG; xml += ss.str(); xml += DOUBLE_ETAG; xml += VALUE_ETAG; return xml; } // String bool XmlRpcValue::stringFromXml(std::string const& valueXml, int* offset) { size_t valueEnd = valueXml.find('<', *offset); if (valueEnd == std::string::npos) return false; // No end tag; _type = TypeString; _value.asString = new std::string(XmlRpcUtil::xmlDecode(valueXml.substr(*offset, valueEnd-*offset))); *offset += int(_value.asString->length()); return true; } std::string XmlRpcValue::stringToXml() const { std::string xml = VALUE_TAG; //xml += STRING_TAG; optional xml += XmlRpcUtil::xmlEncode(*_value.asString); //xml += STRING_ETAG; xml += VALUE_ETAG; return xml; } // DateTime (stored as a struct tm) bool XmlRpcValue::timeFromXml(std::string const& valueXml, int* offset) { size_t valueEnd = valueXml.find('<', *offset); if (valueEnd == std::string::npos) return false; // No end tag; std::string stime = valueXml.substr(*offset, valueEnd-*offset); struct tm t; #ifdef _MSC_VER if (sscanf_s(stime.c_str(),"%4d%2d%2dT%2d:%2d:%2d",&t.tm_year,&t.tm_mon,&t.tm_mday,&t.tm_hour,&t.tm_min,&t.tm_sec) != 6) #else if (sscanf(stime.c_str(),"%4d%2d%2dT%2d:%2d:%2d",&t.tm_year,&t.tm_mon,&t.tm_mday,&t.tm_hour,&t.tm_min,&t.tm_sec) != 6) #endif return false; t.tm_isdst = -1; _type = TypeDateTime; _value.asTime = new struct tm(t); *offset += int(stime.length()); return true; } std::string XmlRpcValue::timeToXml() const { struct tm* t = _value.asTime; char buf[20]; snprintf(buf, sizeof(buf)-1, "%4d%02d%02dT%02d:%02d:%02d", t->tm_year,t->tm_mon,t->tm_mday,t->tm_hour,t->tm_min,t->tm_sec); buf[sizeof(buf)-1] = 0; std::string xml = VALUE_TAG; xml += DATETIME_TAG; xml += buf; xml += DATETIME_ETAG; xml += VALUE_ETAG; return xml; } // Base64 bool XmlRpcValue::binaryFromXml(std::string const& valueXml, int* offset) { size_t valueEnd = valueXml.find('<', *offset); if (valueEnd == std::string::npos) return false; // No end tag; _type = TypeBase64; std::string asString = valueXml.substr(*offset, valueEnd-*offset); _value.asBinary = new BinaryData(); // check whether base64 encodings can contain chars xml encodes... // convert from base64 to binary int iostatus = 0; base64<char> decoder; std::back_insert_iterator<BinaryData> ins = std::back_inserter(*(_value.asBinary)); decoder.get(asString.begin(), asString.end(), ins, iostatus); *offset += int(asString.length()); return true; } std::string XmlRpcValue::binaryToXml() const { // convert to base64 std::vector<char> base64data; int iostatus = 0; base64<char> encoder; std::back_insert_iterator<std::vector<char> > ins = std::back_inserter(base64data); encoder.put(_value.asBinary->begin(), _value.asBinary->end(), ins, iostatus, base64<>::crlf()); // Wrap with xml std::string xml = VALUE_TAG; xml += BASE64_TAG; xml.append(base64data.begin(), base64data.end()); xml += BASE64_ETAG; xml += VALUE_ETAG; return xml; } // Array bool XmlRpcValue::arrayFromXml(std::string const& valueXml, int* offset) { if ( ! XmlRpcUtil::nextTagIs(DATA_TAG, valueXml, offset)) return false; _type = TypeArray; _value.asArray = new ValueArray; XmlRpcValue v; while (v.fromXml(valueXml, offset)) _value.asArray->push_back(v); // copy... // Skip the trailing </data> (void) XmlRpcUtil::nextTagIs(DATA_ETAG, valueXml, offset); return true; } // In general, its preferable to generate the xml of each element of the // array as it is needed rather than glomming up one big string. std::string XmlRpcValue::arrayToXml() const { std::string xml = VALUE_TAG; xml += ARRAY_TAG; xml += DATA_TAG; int s = int(_value.asArray->size()); for (int i=0; i<s; ++i) xml += _value.asArray->at(i).toXml(); xml += DATA_ETAG; xml += ARRAY_ETAG; xml += VALUE_ETAG; return xml; } // Struct bool XmlRpcValue::structFromXml(std::string const& valueXml, int* offset) { _type = TypeStruct; _value.asStruct = new ValueStruct; while (XmlRpcUtil::nextTagIs(MEMBER_TAG, valueXml, offset)) { // name const std::string name = XmlRpcUtil::parseTag(NAME_TAG, valueXml, offset); // value XmlRpcValue val(valueXml, offset); if ( ! val.valid()) { invalidate(); return false; } const std::pair<const std::string, XmlRpcValue> p(name, val); _value.asStruct->insert(p); (void) XmlRpcUtil::nextTagIs(MEMBER_ETAG, valueXml, offset); } return true; } // In general, its preferable to generate the xml of each element // as it is needed rather than glomming up one big string. std::string XmlRpcValue::structToXml() const { std::string xml = VALUE_TAG; xml += STRUCT_TAG; ValueStruct::const_iterator it; for (it=_value.asStruct->begin(); it!=_value.asStruct->end(); ++it) { xml += MEMBER_TAG; xml += NAME_TAG; xml += XmlRpcUtil::xmlEncode(it->first); xml += NAME_ETAG; xml += it->second.toXml(); xml += MEMBER_ETAG; } xml += STRUCT_ETAG; xml += VALUE_ETAG; return xml; } // Write the value without xml encoding it std::ostream& XmlRpcValue::write(std::ostream& os) const { switch (_type) { default: break; case TypeBoolean: os << _value.asBool; break; case TypeInt: os << _value.asInt; break; case TypeDouble: os << _value.asDouble; break; case TypeString: os << *_value.asString; break; case TypeDateTime: { struct tm* t = _value.asTime; char buf[20]; snprintf(buf, sizeof(buf)-1, "%4d%02d%02dT%02d:%02d:%02d", t->tm_year,t->tm_mon,t->tm_mday,t->tm_hour,t->tm_min,t->tm_sec); buf[sizeof(buf)-1] = 0; os << buf; break; } case TypeBase64: { int iostatus = 0; std::ostreambuf_iterator<char> out(os); base64<char> encoder; encoder.put(_value.asBinary->begin(), _value.asBinary->end(), out, iostatus, base64<>::crlf()); break; } case TypeArray: { int s = int(_value.asArray->size()); os << '{'; for (int i=0; i<s; ++i) { if (i > 0) os << ','; _value.asArray->at(i).write(os); } os << '}'; break; } case TypeStruct: { os << '['; ValueStruct::const_iterator it; for (it=_value.asStruct->begin(); it!=_value.asStruct->end(); ++it) { if (it!=_value.asStruct->begin()) os << ','; os << it->first << ':'; it->second.write(os); } os << ']'; break; } } return os; } } // namespace XmlRpc // ostream std::ostream& operator<<(std::ostream& os, XmlRpc::XmlRpcValue& v) { // If you want to output in xml format: //return os << v.toXml(); return v.write(os); }
0
apollo_public_repos/apollo-platform/ros/ros_comm/xmlrpcpp
apollo_public_repos/apollo-platform/ros/ros_comm/xmlrpcpp/src/XmlRpcServerMethod.cpp
#include "XmlRpcServerMethod.h" #include "XmlRpcServer.h" namespace XmlRpc { XmlRpcServerMethod::XmlRpcServerMethod(std::string const& name, XmlRpcServer* server) { _name = name; _server = server; if (_server) _server->addMethod(this); } XmlRpcServerMethod::~XmlRpcServerMethod() { if (_server) _server->removeMethod(this); } } // namespace XmlRpc
0
apollo_public_repos/apollo-platform/ros/ros_comm/xmlrpcpp
apollo_public_repos/apollo-platform/ros/ros_comm/xmlrpcpp/src/XmlRpcServer.cpp
// this file modified by Morgan Quigley on 22 Apr 2008. // added features: server can be opened on port 0 and you can read back // what port the OS gave you #include "XmlRpcServer.h" #include "XmlRpcServerConnection.h" #include "XmlRpcServerMethod.h" #include "XmlRpcSocket.h" #include "XmlRpcUtil.h" #include "XmlRpcException.h" using namespace XmlRpc; XmlRpcServer::XmlRpcServer() { _introspectionEnabled = false; _listMethods = 0; _methodHelp = 0; _port = 0; } XmlRpcServer::~XmlRpcServer() { this->shutdown(); _methods.clear(); delete _listMethods; delete _methodHelp; } // Add a command to the RPC server void XmlRpcServer::addMethod(XmlRpcServerMethod* method) { _methods[method->name()] = method; } // Remove a command from the RPC server void XmlRpcServer::removeMethod(XmlRpcServerMethod* method) { MethodMap::iterator i = _methods.find(method->name()); if (i != _methods.end()) _methods.erase(i); } // Remove a command from the RPC server by name void XmlRpcServer::removeMethod(const std::string& methodName) { MethodMap::iterator i = _methods.find(methodName); if (i != _methods.end()) _methods.erase(i); } // Look up a method by name XmlRpcServerMethod* XmlRpcServer::findMethod(const std::string& name) const { MethodMap::const_iterator i = _methods.find(name); if (i == _methods.end()) return 0; return i->second; } // Create a socket, bind to the specified port, and // set it in listen mode to make it available for clients. bool XmlRpcServer::bindAndListen(int port, int backlog /*= 5*/) { int fd = XmlRpcSocket::socket(); if (fd < 0) { XmlRpcUtil::error("XmlRpcServer::bindAndListen: Could not create socket (%s).", XmlRpcSocket::getErrorMsg().c_str()); return false; } this->setfd(fd); // Don't block on reads/writes if ( ! XmlRpcSocket::setNonBlocking(fd)) { this->close(); XmlRpcUtil::error("XmlRpcServer::bindAndListen: Could not set socket to non-blocking input mode (%s).", XmlRpcSocket::getErrorMsg().c_str()); return false; } // Allow this port to be re-bound immediately so server re-starts are not delayed if ( ! XmlRpcSocket::setReuseAddr(fd)) { this->close(); XmlRpcUtil::error("XmlRpcServer::bindAndListen: Could not set SO_REUSEADDR socket option (%s).", XmlRpcSocket::getErrorMsg().c_str()); return false; } // Bind to the specified port on the default interface if ( ! XmlRpcSocket::bind(fd, port)) { this->close(); XmlRpcUtil::error("XmlRpcServer::bindAndListen: Could not bind to specified port (%s).", XmlRpcSocket::getErrorMsg().c_str()); return false; } // Set in listening mode if ( ! XmlRpcSocket::listen(fd, backlog)) { this->close(); XmlRpcUtil::error("XmlRpcServer::bindAndListen: Could not set socket in listening mode (%s).", XmlRpcSocket::getErrorMsg().c_str()); return false; } _port = XmlRpcSocket::get_port(fd); XmlRpcUtil::log(2, "XmlRpcServer::bindAndListen: server listening on port %d fd %d", _port, fd); // Notify the dispatcher to listen on this source when we are in work() _disp.addSource(this, XmlRpcDispatch::ReadableEvent); return true; } // Process client requests for the specified time void XmlRpcServer::work(double msTime) { XmlRpcUtil::log(2, "XmlRpcServer::work: waiting for a connection"); _disp.work(msTime); } // Handle input on the server socket by accepting the connection // and reading the rpc request. unsigned XmlRpcServer::handleEvent(unsigned) { acceptConnection(); return XmlRpcDispatch::ReadableEvent; // Continue to monitor this fd } // Accept a client connection request and create a connection to // handle method calls from the client. void XmlRpcServer::acceptConnection() { int s = XmlRpcSocket::accept(this->getfd()); XmlRpcUtil::log(2, "XmlRpcServer::acceptConnection: socket %d", s); if (s < 0) { //this->close(); XmlRpcUtil::error("XmlRpcServer::acceptConnection: Could not accept connection (%s).", XmlRpcSocket::getErrorMsg().c_str()); } else if ( ! XmlRpcSocket::setNonBlocking(s)) { XmlRpcSocket::close(s); XmlRpcUtil::error("XmlRpcServer::acceptConnection: Could not set socket to non-blocking input mode (%s).", XmlRpcSocket::getErrorMsg().c_str()); } else // Notify the dispatcher to listen for input on this source when we are in work() { XmlRpcUtil::log(2, "XmlRpcServer::acceptConnection: creating a connection"); _disp.addSource(this->createConnection(s), XmlRpcDispatch::ReadableEvent); } } // Create a new connection object for processing requests from a specific client. XmlRpcServerConnection* XmlRpcServer::createConnection(int s) { // Specify that the connection object be deleted when it is closed return new XmlRpcServerConnection(s, this, true); } void XmlRpcServer::removeConnection(XmlRpcServerConnection* sc) { _disp.removeSource(sc); } // Stop processing client requests void XmlRpcServer::exit() { _disp.exit(); } // Close the server socket file descriptor and stop monitoring connections void XmlRpcServer::shutdown() { // This closes and destroys all connections as well as closing this socket _disp.clear(); } // Introspection support static const std::string LIST_METHODS("system.listMethods"); static const std::string METHOD_HELP("system.methodHelp"); static const std::string MULTICALL("system.multicall"); // List all methods available on a server class ListMethods : public XmlRpcServerMethod { public: ListMethods(XmlRpcServer* s) : XmlRpcServerMethod(LIST_METHODS, s) {} void execute(XmlRpcValue&, XmlRpcValue& result) { _server->listMethods(result); } std::string help() { return std::string("List all methods available on a server as an array of strings"); } }; // Retrieve the help string for a named method class MethodHelp : public XmlRpcServerMethod { public: MethodHelp(XmlRpcServer* s) : XmlRpcServerMethod(METHOD_HELP, s) {} void execute(XmlRpcValue& params, XmlRpcValue& result) { if (params[0].getType() != XmlRpcValue::TypeString) throw XmlRpcException(METHOD_HELP + ": Invalid argument type"); XmlRpcServerMethod* m = _server->findMethod(params[0]); if ( ! m) throw XmlRpcException(METHOD_HELP + ": Unknown method name"); result = m->help(); } std::string help() { return std::string("Retrieve the help string for a named method"); } }; // Specify whether introspection is enabled or not. Default is enabled. void XmlRpcServer::enableIntrospection(bool enabled) { if (_introspectionEnabled == enabled) return; _introspectionEnabled = enabled; if (enabled) { if ( ! _listMethods) { _listMethods = new ListMethods(this); _methodHelp = new MethodHelp(this); } else { addMethod(_listMethods); addMethod(_methodHelp); } } else { removeMethod(LIST_METHODS); removeMethod(METHOD_HELP); } } void XmlRpcServer::listMethods(XmlRpcValue& result) { int i = 0; result.setSize(_methods.size()+1); for (MethodMap::iterator it=_methods.begin(); it != _methods.end(); ++it) result[i++] = it->first; // Multicall support is built into XmlRpcServerConnection result[i] = MULTICALL; }
0
apollo_public_repos/apollo-platform/ros/ros_comm/xmlrpcpp
apollo_public_repos/apollo-platform/ros/ros_comm/xmlrpcpp/src/XmlRpcSource.cpp
#include "XmlRpcSource.h" #include "XmlRpcSocket.h" #include "XmlRpcUtil.h" namespace XmlRpc { XmlRpcSource::XmlRpcSource(int fd /*= -1*/, bool deleteOnClose /*= false*/) : _fd(fd), _deleteOnClose(deleteOnClose), _keepOpen(false) { } XmlRpcSource::~XmlRpcSource() { } void XmlRpcSource::close() { if (_fd != -1) { XmlRpcUtil::log(2,"XmlRpcSource::close: closing socket %d.", _fd); XmlRpcSocket::close(_fd); XmlRpcUtil::log(2,"XmlRpcSource::close: done closing socket %d.", _fd); _fd = -1; } if (_deleteOnClose) { XmlRpcUtil::log(2,"XmlRpcSource::close: deleting this"); _deleteOnClose = false; delete this; } } } // namespace XmlRpc
0
apollo_public_repos/apollo-platform/ros/ros_comm/xmlrpcpp
apollo_public_repos/apollo-platform/ros/ros_comm/xmlrpcpp/src/XmlRpcClient.cpp
#include "XmlRpcClient.h" #include "XmlRpcSocket.h" #include "XmlRpc.h" #include <stdio.h> #include <stdlib.h> #ifndef _WINDOWS # include <strings.h> #endif #include <string.h> using namespace XmlRpc; // Static data const char XmlRpcClient::REQUEST_BEGIN[] = "<?xml version=\"1.0\"?>\r\n" "<methodCall><methodName>"; const char XmlRpcClient::REQUEST_END_METHODNAME[] = "</methodName>\r\n"; const char XmlRpcClient::PARAMS_TAG[] = "<params>"; const char XmlRpcClient::PARAMS_ETAG[] = "</params>"; const char XmlRpcClient::PARAM_TAG[] = "<param>"; const char XmlRpcClient::PARAM_ETAG[] = "</param>"; const char XmlRpcClient::REQUEST_END[] = "</methodCall>\r\n"; const char XmlRpcClient::METHODRESPONSE_TAG[] = "<methodResponse>"; const char XmlRpcClient::FAULT_TAG[] = "<fault>"; XmlRpcClient::XmlRpcClient(const char* host, int port, const char* uri/*=0*/) { XmlRpcUtil::log(1, "XmlRpcClient new client: host %s, port %d.", host, port); _host = host; _port = port; if (uri) _uri = uri; else _uri = "/RPC2"; _connectionState = NO_CONNECTION; _executing = false; _eof = false; // Default to keeping the connection open until an explicit close is done setKeepOpen(); } XmlRpcClient::~XmlRpcClient() { this->close(); } // Close the owned fd void XmlRpcClient::close() { XmlRpcUtil::log(4, "XmlRpcClient::close: fd %d.", getfd()); _connectionState = NO_CONNECTION; _disp.exit(); _disp.removeSource(this); XmlRpcSource::close(); } // Clear the referenced flag even if exceptions or errors occur. struct ClearFlagOnExit { ClearFlagOnExit(bool& flag) : _flag(flag) {} ~ClearFlagOnExit() { _flag = false; } bool& _flag; }; // Execute the named procedure on the remote server. // Params should be an array of the arguments for the method. // Returns true if the request was sent and a result received (although the result // might be a fault). bool XmlRpcClient::execute(const char* method, XmlRpcValue const& params, XmlRpcValue& result) { XmlRpcUtil::log(1, "XmlRpcClient::execute: method %s (_connectionState %d).", method, _connectionState); // This is not a thread-safe operation, if you want to do multithreading, use separate // clients for each thread. If you want to protect yourself from multiple threads // accessing the same client, replace this code with a real mutex. if (_executing) return false; _executing = true; ClearFlagOnExit cf(_executing); _sendAttempts = 0; _isFault = false; if ( ! setupConnection()) return false; if ( ! generateRequest(method, params)) return false; result.clear(); double msTime = -1.0; // Process until exit is called _disp.work(msTime); if (_connectionState != IDLE || ! parseResponse(result)) return false; XmlRpcUtil::log(1, "XmlRpcClient::execute: method %s completed.", method); _response = ""; return true; } // Execute the named procedure on the remote server, non-blocking. // Params should be an array of the arguments for the method. // Returns true if the request was sent and a result received (although the result // might be a fault). bool XmlRpcClient::executeNonBlock(const char* method, XmlRpcValue const& params) { XmlRpcUtil::log(1, "XmlRpcClient::execute: method %s (_connectionState %d).", method, _connectionState); // This is not a thread-safe operation, if you want to do multithreading, use separate // clients for each thread. If you want to protect yourself from multiple threads // accessing the same client, replace this code with a real mutex. if (_executing) return false; _executing = true; ClearFlagOnExit cf(_executing); _sendAttempts = 0; _isFault = false; if ( ! setupConnection()) return false; if ( ! generateRequest(method, params)) return false; return true; } bool XmlRpcClient::executeCheckDone(XmlRpcValue& result) { result.clear(); // Are we done yet? if (_connectionState != IDLE) return false; if (! parseResponse(result)) { // Hopefully the caller can determine that parsing failed. } //XmlRpcUtil::log(1, "XmlRpcClient::execute: method %s completed.", method); _response = ""; return true; } // XmlRpcSource interface implementation // Handle server responses. Called by the event dispatcher during execute. unsigned XmlRpcClient::handleEvent(unsigned eventType) { if (eventType == XmlRpcDispatch::Exception) { if (_connectionState == WRITE_REQUEST && _bytesWritten == 0) XmlRpcUtil::error("Error in XmlRpcClient::handleEvent: could not connect to server (%s).", XmlRpcSocket::getErrorMsg().c_str()); else XmlRpcUtil::error("Error in XmlRpcClient::handleEvent (state %d): %s.", _connectionState, XmlRpcSocket::getErrorMsg().c_str()); return 0; } if (_connectionState == WRITE_REQUEST) if ( ! writeRequest()) return 0; if (_connectionState == READ_HEADER) if ( ! readHeader()) return 0; if (_connectionState == READ_RESPONSE) if ( ! readResponse()) return 0; // This should probably always ask for Exception events too return (_connectionState == WRITE_REQUEST) ? XmlRpcDispatch::WritableEvent : XmlRpcDispatch::ReadableEvent; } // Create the socket connection to the server if necessary bool XmlRpcClient::setupConnection() { // If an error occurred last time through, or if the server closed the connection, close our end if ((_connectionState != NO_CONNECTION && _connectionState != IDLE) || _eof) close(); _eof = false; if (_connectionState == NO_CONNECTION) if (! doConnect()) return false; // Prepare to write the request _connectionState = WRITE_REQUEST; _bytesWritten = 0; // Notify the dispatcher to listen on this source (calls handleEvent when the socket is writable) _disp.removeSource(this); // Make sure nothing is left over _disp.addSource(this, XmlRpcDispatch::WritableEvent | XmlRpcDispatch::Exception); return true; } // Connect to the xmlrpc server bool XmlRpcClient::doConnect() { int fd = XmlRpcSocket::socket(); if (fd < 0) { XmlRpcUtil::error("Error in XmlRpcClient::doConnect: Could not create socket (%s).", XmlRpcSocket::getErrorMsg().c_str()); return false; } XmlRpcUtil::log(3, "XmlRpcClient::doConnect: fd %d.", fd); this->setfd(fd); // Don't block on connect/reads/writes if ( ! XmlRpcSocket::setNonBlocking(fd)) { this->close(); XmlRpcUtil::error("Error in XmlRpcClient::doConnect: Could not set socket to non-blocking IO mode (%s).", XmlRpcSocket::getErrorMsg().c_str()); return false; } if ( ! XmlRpcSocket::connect(fd, _host, _port)) { this->close(); XmlRpcUtil::error("Error in XmlRpcClient::doConnect: Could not connect to server (%s).", XmlRpcSocket::getErrorMsg().c_str()); return false; } return true; } // Encode the request to call the specified method with the specified parameters into xml bool XmlRpcClient::generateRequest(const char* methodName, XmlRpcValue const& params) { std::string body = REQUEST_BEGIN; body += methodName; body += REQUEST_END_METHODNAME; // If params is an array, each element is a separate parameter if (params.valid()) { body += PARAMS_TAG; if (params.getType() == XmlRpcValue::TypeArray) { for (int i=0; i<params.size(); ++i) { body += PARAM_TAG; body += params[i].toXml(); body += PARAM_ETAG; } } else { body += PARAM_TAG; body += params.toXml(); body += PARAM_ETAG; } body += PARAMS_ETAG; } body += REQUEST_END; std::string header = generateHeader(body); XmlRpcUtil::log(4, "XmlRpcClient::generateRequest: header is %d bytes, content-length is %d.", header.length(), body.length()); _request = header + body; return true; } // Prepend http headers std::string XmlRpcClient::generateHeader(std::string const& body) { std::string header = "POST " + _uri + " HTTP/1.1\r\n" "User-Agent: "; header += XMLRPC_VERSION; header += "\r\nHost: "; header += _host; char buff[40]; #ifdef _MSC_VER sprintf_s(buff,40,":%d\r\n", _port); #else sprintf(buff,":%d\r\n", _port); #endif header += buff; header += "Content-Type: text/xml\r\nContent-length: "; #ifdef _MSC_VER sprintf_s(buff,40,"%d\r\n\r\n", (int)body.size()); #else sprintf(buff,"%d\r\n\r\n", (int)body.size()); #endif return header + buff; } bool XmlRpcClient::writeRequest() { if (_bytesWritten == 0) XmlRpcUtil::log(5, "XmlRpcClient::writeRequest (attempt %d):\n%s\n", _sendAttempts+1, _request.c_str()); // Try to write the request if ( ! XmlRpcSocket::nbWrite(this->getfd(), _request, &_bytesWritten)) { XmlRpcUtil::error("Error in XmlRpcClient::writeRequest: write error (%s).",XmlRpcSocket::getErrorMsg().c_str()); return false; } XmlRpcUtil::log(3, "XmlRpcClient::writeRequest: wrote %d of %d bytes.", _bytesWritten, _request.length()); // Wait for the result if (_bytesWritten == int(_request.length())) { _header = ""; _response = ""; _connectionState = READ_HEADER; } return true; } // Read the header from the response bool XmlRpcClient::readHeader() { // Read available data if ( ! XmlRpcSocket::nbRead(this->getfd(), _header, &_eof) || (_eof && _header.length() == 0)) { // If we haven't read any data yet and this is a keep-alive connection, the server may // have timed out, so we try one more time. if (getKeepOpen() && _header.length() == 0 && _sendAttempts++ == 0) { XmlRpcUtil::log(4, "XmlRpcClient::readHeader: re-trying connection"); XmlRpcSource::close(); _connectionState = NO_CONNECTION; _eof = false; return setupConnection(); } XmlRpcUtil::error("Error in XmlRpcClient::readHeader: error while reading header (%s) on fd %d.", XmlRpcSocket::getErrorMsg().c_str(), getfd()); return false; } XmlRpcUtil::log(4, "XmlRpcClient::readHeader: client has read %d bytes", _header.length()); char *hp = (char*)_header.c_str(); // Start of header char *ep = hp + _header.length(); // End of string char *bp = 0; // Start of body char *lp = 0; // Start of content-length value for (char *cp = hp; (bp == 0) && (cp < ep); ++cp) { if ((ep - cp > 16) && (strncasecmp(cp, "Content-length: ", 16) == 0)) lp = cp + 16; else if ((ep - cp > 4) && (strncmp(cp, "\r\n\r\n", 4) == 0)) bp = cp + 4; else if ((ep - cp > 2) && (strncmp(cp, "\n\n", 2) == 0)) bp = cp + 2; } // If we haven't gotten the entire header yet, return (keep reading) if (bp == 0) { if (_eof) // EOF in the middle of a response is an error { XmlRpcUtil::error("Error in XmlRpcClient::readHeader: EOF while reading header"); return false; // Close the connection } return true; // Keep reading } // Decode content length if (lp == 0) { XmlRpcUtil::error("Error XmlRpcClient::readHeader: No Content-length specified"); return false; // We could try to figure it out by parsing as we read, but for now... } _contentLength = atoi(lp); if (_contentLength <= 0) { XmlRpcUtil::error("Error in XmlRpcClient::readHeader: Invalid Content-length specified (%d).", _contentLength); return false; } XmlRpcUtil::log(4, "client read content length: %d", _contentLength); // Otherwise copy non-header data to response buffer and set state to read response. _response = bp; _header = ""; // should parse out any interesting bits from the header (connection, etc)... _connectionState = READ_RESPONSE; return true; // Continue monitoring this source } bool XmlRpcClient::readResponse() { // If we dont have the entire response yet, read available data if (int(_response.length()) < _contentLength) { if ( ! XmlRpcSocket::nbRead(this->getfd(), _response, &_eof)) { XmlRpcUtil::error("Error in XmlRpcClient::readResponse: read error (%s).",XmlRpcSocket::getErrorMsg().c_str()); return false; } // If we haven't gotten the entire _response yet, return (keep reading) if (int(_response.length()) < _contentLength) { if (_eof) { XmlRpcUtil::error("Error in XmlRpcClient::readResponse: EOF while reading response"); return false; } return true; } } // Otherwise, parse and return the result XmlRpcUtil::log(3, "XmlRpcClient::readResponse (read %d bytes)", _response.length()); XmlRpcUtil::log(5, "response:\n%s", _response.c_str()); _connectionState = IDLE; return false; // Stop monitoring this source (causes return from work) } // Convert the response xml into a result value bool XmlRpcClient::parseResponse(XmlRpcValue& result) { // Parse response xml into result int offset = 0; if ( ! XmlRpcUtil::findTag(METHODRESPONSE_TAG,_response,&offset)) { XmlRpcUtil::error("Error in XmlRpcClient::parseResponse: Invalid response - no methodResponse. Response:\n%s", _response.c_str()); return false; } // Expect either <params><param>... or <fault>... if ((XmlRpcUtil::nextTagIs(PARAMS_TAG,_response,&offset) && XmlRpcUtil::nextTagIs(PARAM_TAG,_response,&offset)) || (XmlRpcUtil::nextTagIs(FAULT_TAG,_response,&offset) && (_isFault = true))) { if ( ! result.fromXml(_response, &offset)) { XmlRpcUtil::error("Error in XmlRpcClient::parseResponse: Invalid response value. Response:\n%s", _response.c_str()); _response = ""; return false; } } else { XmlRpcUtil::error("Error in XmlRpcClient::parseResponse: Invalid response - no param or fault tag. Response:\n%s", _response.c_str()); _response = ""; return false; } _response = ""; return result.valid(); }
0
apollo_public_repos/apollo-platform/ros/ros_comm/xmlrpcpp
apollo_public_repos/apollo-platform/ros/ros_comm/xmlrpcpp/src/XmlRpcSocket.cpp
// this file modified by Morgan Quigley on 22 Apr 2008. // added features: server can be opened on port 0 and you can read back // what port the OS gave you #include "XmlRpcSocket.h" #include "XmlRpcUtil.h" #ifndef MAKEDEPEND #if defined(_WINDOWS) # include <stdio.h> # include <winsock2.h> # include <ws2tcpip.h> //# pragma lib(WS2_32.lib) // MS VS10 actually has these definitions (as opposed to earlier versions), // so if present, temporarily disable them and reset to WSA codes for this file only. #ifdef EAGAIN #undef EAGAIN #endif #ifdef EINTR #undef EINTR #endif #ifdef EINPROGRESS #undef EINPROGRESS #endif #ifdef EWOULDBLOCK #undef EWOULDBLOCK #endif #ifdef ETIMEDOUT #undef ETIMEDOUT #endif # define EAGAIN WSATRY_AGAIN # define EINTR WSAEINTR # define EINPROGRESS WSAEINPROGRESS # define EWOULDBLOCK WSAEWOULDBLOCK # define ETIMEDOUT WSAETIMEDOUT #else extern "C" { # include <unistd.h> # include <stdio.h> # include <sys/types.h> # include <sys/socket.h> # include <netinet/in.h> # include <netdb.h> # include <errno.h> # include <fcntl.h> # include <string.h> # include <stdlib.h> # include <arpa/inet.h> } #endif // _WINDOWS #endif // MAKEDEPEND // MSG_NOSIGNAL does not exists on OS X #if defined(__APPLE__) || defined(__MACH__) # ifndef MSG_NOSIGNAL # define MSG_NOSIGNAL SO_NOSIGPIPE # endif #endif using namespace XmlRpc; bool XmlRpcSocket::s_use_ipv6_ = false; #if defined(_WINDOWS) static void initWinSock() { static bool wsInit = false; if (! wsInit) { WORD wVersionRequested = MAKEWORD( 2, 0 ); WSADATA wsaData; WSAStartup(wVersionRequested, &wsaData); wsInit = true; } } #else #define initWinSock() #endif // _WINDOWS // These errors are not considered fatal for an IO operation; the operation will be re-tried. static inline bool nonFatalError() { int err = XmlRpcSocket::getError(); return (err == EINPROGRESS || err == EAGAIN || err == EWOULDBLOCK || err == EINTR); } int XmlRpcSocket::socket() { initWinSock(); return (int) ::socket(s_use_ipv6_ ? AF_INET6 : AF_INET, SOCK_STREAM, 0); } void XmlRpcSocket::close(int fd) { XmlRpcUtil::log(4, "XmlRpcSocket::close: fd %d.", fd); #if defined(_WINDOWS) closesocket(fd); #else ::close(fd); #endif // _WINDOWS } bool XmlRpcSocket::setNonBlocking(int fd) { #if defined(_WINDOWS) unsigned long flag = 1; return (ioctlsocket((SOCKET)fd, FIONBIO, &flag) == 0); #else return (fcntl(fd, F_SETFL, O_NONBLOCK) == 0); #endif // _WINDOWS } bool XmlRpcSocket::setReuseAddr(int fd) { // Allow this port to be re-bound immediately so server re-starts are not delayed int sflag = 1; return (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&sflag, sizeof(sflag)) == 0); } // Bind to a specified port bool XmlRpcSocket::bind(int fd, int port) { sockaddr_storage ss; socklen_t ss_len; memset(&ss, 0, sizeof(ss)); if (s_use_ipv6_) { sockaddr_in6 *address = (sockaddr_in6 *)&ss; ss_len = sizeof(sockaddr_in6); address->sin6_family = AF_INET6; address->sin6_addr = in6addr_any; address->sin6_port = htons((u_short) port); } else { sockaddr_in *address = (sockaddr_in *)&ss; ss_len = sizeof(sockaddr_in); address->sin_family = AF_INET; address->sin_addr.s_addr = htonl(INADDR_ANY); address->sin_port = htons((u_short) port); } return (::bind(fd, (sockaddr*)&ss, ss_len) == 0); } // Set socket in listen mode bool XmlRpcSocket::listen(int fd, int backlog) { return (::listen(fd, backlog) == 0); } int XmlRpcSocket::accept(int fd) { struct sockaddr_in addr; #if defined(_WINDOWS) int #else socklen_t #endif addrlen = sizeof(addr); // accept will truncate the address if the buffer is too small. // As we are not using it, no special case for IPv6 // has to be made. return (int) ::accept(fd, (struct sockaddr*)&addr, &addrlen); } // Connect a socket to a server (from a client) bool XmlRpcSocket::connect(int fd, std::string& host, int port) { sockaddr_storage ss; socklen_t ss_len; memset(&ss, 0, sizeof(ss)); struct addrinfo* addr; struct addrinfo hints; memset(&hints, 0, sizeof(hints)); hints.ai_family = AF_UNSPEC; if (getaddrinfo(host.c_str(), NULL, &hints, &addr) != 0) { fprintf(stderr, "Couldn't find an %s address for [%s]\n", s_use_ipv6_ ? "AF_INET6" : "AF_INET", host.c_str()); return false; } bool found = false; struct addrinfo* it = addr; for (; it; it = it->ai_next) { if (!s_use_ipv6_ && it->ai_family == AF_INET) { sockaddr_in *address = (sockaddr_in *)&ss; ss_len = sizeof(sockaddr_in); memcpy(address, it->ai_addr, it->ai_addrlen); address->sin_family = it->ai_family; address->sin_port = htons((u_short) port); XmlRpcUtil::log(5, "found host as %s\n", inet_ntoa(address->sin_addr)); found = true; break; } if (s_use_ipv6_ && it->ai_family == AF_INET6) { sockaddr_in6 *address = (sockaddr_in6 *)&ss; ss_len = sizeof(sockaddr_in6); memcpy(address, it->ai_addr, it->ai_addrlen); address->sin6_family = it->ai_family; address->sin6_port = htons((u_short) port); char buf[128]; // TODO IPV6: check if this also works under Windows XmlRpcUtil::log(5, "found ipv6 host as %s\n", inet_ntop(AF_INET6, (void*)&(address->sin6_addr), buf, sizeof(buf))); found = true; break; } } if (!found) { printf("Couldn't find an %s address for [%s]\n", s_use_ipv6_ ? "AF_INET6" : "AF_INET", host.c_str()); freeaddrinfo(addr); return false; } // For asynch operation, this will return EWOULDBLOCK (windows) or // EINPROGRESS (linux) and we just need to wait for the socket to be writable... int result = ::connect(fd, (sockaddr*)&ss, ss_len); if (result != 0 ) { int error = getError(); if ( (error != EINPROGRESS) && error != EWOULDBLOCK) { // actually, should probably do a platform check here, EWOULDBLOCK on WIN32 and EINPROGRESS otherwise printf("::connect error = %d\n", getError()); } } freeaddrinfo(addr); return result == 0 || nonFatalError(); } // Read available text from the specified socket. Returns false on error. bool XmlRpcSocket::nbRead(int fd, std::string& s, bool *eof) { const int READ_SIZE = 4096; // Number of bytes to attempt to read at a time char readBuf[READ_SIZE]; bool wouldBlock = false; *eof = false; while ( ! wouldBlock && ! *eof) { #if defined(_WINDOWS) int n = recv(fd, readBuf, READ_SIZE-1, 0); #else int n = read(fd, readBuf, READ_SIZE-1); #endif XmlRpcUtil::log(5, "XmlRpcSocket::nbRead: read/recv returned %d.", n); if (n > 0) { readBuf[n] = 0; s.append(readBuf, n); } else if (n == 0) { *eof = true; } else if (nonFatalError()) { wouldBlock = true; } else { return false; // Error } } return true; } // Write text to the specified socket. Returns false on error. bool XmlRpcSocket::nbWrite(int fd, std::string& s, int *bytesSoFar) { int nToWrite = int(s.length()) - *bytesSoFar; char *sp = const_cast<char*>(s.c_str()) + *bytesSoFar; bool wouldBlock = false; while ( nToWrite > 0 && ! wouldBlock ) { #if defined(_WINDOWS) int n = send(fd, sp, nToWrite, 0); #else int n = write(fd, sp, nToWrite); #endif XmlRpcUtil::log(5, "XmlRpcSocket::nbWrite: send/write returned %d.", n); if (n > 0) { sp += n; *bytesSoFar += n; nToWrite -= n; } else if (nonFatalError()) { wouldBlock = true; } else { return false; // Error } } return true; } // Returns last errno int XmlRpcSocket::getError() { #if defined(_WINDOWS) return WSAGetLastError(); #else return errno; #endif } // Returns message corresponding to last errno std::string XmlRpcSocket::getErrorMsg() { return getErrorMsg(getError()); } // Returns message corresponding to errno... well, it should anyway std::string XmlRpcSocket::getErrorMsg(int error) { char err[60]; #ifdef _MSC_VER strerror_s(err,60,error); #else snprintf(err,sizeof(err),"%s",strerror(error)); #endif return std::string(err); } int XmlRpcSocket::get_port(int socket) { sockaddr_storage ss; socklen_t ss_len = sizeof(ss); getsockname(socket, (sockaddr *)&ss, &ss_len); sockaddr_in *sin = (sockaddr_in *)&ss; sockaddr_in6 *sin6 = (sockaddr_in6 *)&ss; switch (ss.ss_family) { case AF_INET: return ntohs(sin->sin_port); case AF_INET6: return ntohs(sin6->sin6_port); } return 0; }
0
apollo_public_repos/apollo-platform/ros/ros_comm/xmlrpcpp
apollo_public_repos/apollo-platform/ros/ros_comm/xmlrpcpp/src/Doxyfile
# Doxyfile 1.3-rc3 # This file describes the settings to be used by the documentation system # doxygen (www.doxygen.org) for a project # # All text after a hash (#) is considered a comment and will be ignored # The format is: # TAG = value [value, ...] # For lists items can also be appended using: # TAG += value [value, ...] # Values that contain spaces should be placed between quotes (" ") #--------------------------------------------------------------------------- # General configuration options #--------------------------------------------------------------------------- # The PROJECT_NAME tag is a single word (or a sequence of words surrounded # by quotes) that should identify the project. PROJECT_NAME = XmlRpc++ # The PROJECT_NUMBER tag can be used to enter a project or revision number. # This could be handy for archiving the generated documentation or # if some version control system is used. PROJECT_NUMBER = 0.7 # The OUTPUT_DIRECTORY tag is used to specify the (relative or absolute) # base path where the generated documentation will be put. # If a relative path is entered, it will be relative to the location # where doxygen was started. If left blank the current directory will be used. OUTPUT_DIRECTORY = ../doc # The OUTPUT_LANGUAGE tag is used to specify the language in which all # documentation generated by doxygen is written. Doxygen will use this # information to generate all constant output in the proper language. # The default language is English, other supported languages are: # Brazilian, Catalan, Chinese, Chinese-Traditional, Croatian, Czech, Danish, Dutch, # Finnish, French, German, Greek, Hungarian, Italian, Japanese, Japanese-en # (Japanese with english messages), Korean, Norwegian, Polish, Portuguese, # Romanian, Russian, Serbian, Slovak, Slovene, Spanish, Swedish and Ukrainian. OUTPUT_LANGUAGE = English # If the EXTRACT_ALL tag is set to YES doxygen will assume all entities in # documentation are documented, even if no documentation was available. # Private class members and static file members will be hidden unless # the EXTRACT_PRIVATE and EXTRACT_STATIC tags are set to YES EXTRACT_ALL = NO # If the EXTRACT_PRIVATE tag is set to YES all private members of a class # will be included in the documentation. EXTRACT_PRIVATE = NO # If the EXTRACT_STATIC tag is set to YES all static members of a file # will be included in the documentation. EXTRACT_STATIC = NO # If the EXTRACT_LOCAL_CLASSES tag is set to YES classes (and structs) # defined locally in source files will be included in the documentation. # If set to NO only classes defined in header files are included. EXTRACT_LOCAL_CLASSES = YES # If the HIDE_UNDOC_MEMBERS tag is set to YES, Doxygen will hide all # undocumented members of documented classes, files or namespaces. # If set to NO (the default) these members will be included in the # various overviews, but no documentation section is generated. # This option has no effect if EXTRACT_ALL is enabled. HIDE_UNDOC_MEMBERS = NO # If the HIDE_UNDOC_CLASSES tag is set to YES, Doxygen will hide all # undocumented classes that are normally visible in the class hierarchy. # If set to NO (the default) these class will be included in the various # overviews. This option has no effect if EXTRACT_ALL is enabled. HIDE_UNDOC_CLASSES = YES # If the HIDE_FRIEND_COMPOUNDS tag is set to YES, Doxygen will hide all # friend (class|struct|union) declarations. # If set to NO (the default) these declarations will be included in the # documentation. HIDE_FRIEND_COMPOUNDS = NO # If the HIDE_IN_BODY_DOCS tag is set to YES, Doxygen will hide any # documentation blocks found inside the body of a function. # If set to NO (the default) these blocks will be appended to the # function's detailed documentation block. HIDE_IN_BODY_DOCS = NO # If the BRIEF_MEMBER_DESC tag is set to YES (the default) Doxygen will # include brief member descriptions after the members that are listed in # the file and class documentation (similar to JavaDoc). # Set to NO to disable this. BRIEF_MEMBER_DESC = YES # If the REPEAT_BRIEF tag is set to YES (the default) Doxygen will prepend # the brief description of a member or function before the detailed description. # Note: if both HIDE_UNDOC_MEMBERS and BRIEF_MEMBER_DESC are set to NO, the # brief descriptions will be completely suppressed. REPEAT_BRIEF = YES # If the ALWAYS_DETAILED_SEC and REPEAT_BRIEF tags are both set to YES then # Doxygen will generate a detailed section even if there is only a brief # description. ALWAYS_DETAILED_SEC = NO # If the INLINE_INHERITED_MEMB tag is set to YES, doxygen will show all inherited # members of a class in the documentation of that class as if those members were # ordinary class members. Constructors, destructors and assignment operators of # the base classes will not be shown. INLINE_INHERITED_MEMB = NO # If the FULL_PATH_NAMES tag is set to YES then Doxygen will prepend the full # path before files name in the file list and in the header files. If set # to NO the shortest path that makes the file name unique will be used. FULL_PATH_NAMES = NO # If the FULL_PATH_NAMES tag is set to YES then the STRIP_FROM_PATH tag # can be used to strip a user defined part of the path. Stripping is # only done if one of the specified strings matches the left-hand part of # the path. It is allowed to use relative paths in the argument list. STRIP_FROM_PATH = # The INTERNAL_DOCS tag determines if documentation # that is typed after a \internal command is included. If the tag is set # to NO (the default) then the documentation will be excluded. # Set it to YES to include the internal documentation. INTERNAL_DOCS = NO # If the CASE_SENSE_NAMES tag is set to NO then Doxygen will only generate # file names in lower case letters. If set to YES upper case letters are also # allowed. This is useful if you have classes or files whose names only differ # in case and if your file system supports case sensitive file names. Windows # users are adviced to set this option to NO. CASE_SENSE_NAMES = YES # If the SHORT_NAMES tag is set to YES, doxygen will generate much shorter # (but less readable) file names. This can be useful is your file systems # doesn't support long names like on DOS, Mac, or CD-ROM. SHORT_NAMES = NO # If the HIDE_SCOPE_NAMES tag is set to NO (the default) then Doxygen # will show members with their full class and namespace scopes in the # documentation. If set to YES the scope will be hidden. HIDE_SCOPE_NAMES = NO # If the VERBATIM_HEADERS tag is set to YES (the default) then Doxygen # will generate a verbatim copy of the header file for each class for # which an include is specified. Set to NO to disable this. VERBATIM_HEADERS = YES # If the SHOW_INCLUDE_FILES tag is set to YES (the default) then Doxygen # will put list of the files that are included by a file in the documentation # of that file. SHOW_INCLUDE_FILES = YES # If the JAVADOC_AUTOBRIEF tag is set to YES then Doxygen # will interpret the first line (until the first dot) of a JavaDoc-style # comment as the brief description. If set to NO, the JavaDoc # comments will behave just like the Qt-style comments (thus requiring an # explict @brief command for a brief description. JAVADOC_AUTOBRIEF = YES # The MULTILINE_CPP_IS_BRIEF tag can be set to YES to make Doxygen # treat a multi-line C++ special comment block (i.e. a block of //! or /// # comments) as a brief description. This used to be the default behaviour. # The new default is to treat a multi-line C++ comment block as a detailed # description. Set this tag to YES if you prefer the old behaviour instead. MULTILINE_CPP_IS_BRIEF = NO # If the DETAILS_AT_TOP tag is set to YES then Doxygen # will output the detailed description near the top, like JavaDoc. # If set to NO, the detailed description appears after the member # documentation. DETAILS_AT_TOP = NO # If the INHERIT_DOCS tag is set to YES (the default) then an undocumented # member inherits the documentation from any documented member that it # reimplements. INHERIT_DOCS = YES # If the INLINE_INFO tag is set to YES (the default) then a tag [inline] # is inserted in the documentation for inline members. INLINE_INFO = YES # If the SORT_MEMBER_DOCS tag is set to YES (the default) then doxygen # will sort the (detailed) documentation of file and class members # alphabetically by member name. If set to NO the members will appear in # declaration order. SORT_MEMBER_DOCS = YES # If member grouping is used in the documentation and the DISTRIBUTE_GROUP_DOC # tag is set to YES, then doxygen will reuse the documentation of the first # member in the group (if any) for the other members of the group. By default # all members of a group must be documented explicitly. DISTRIBUTE_GROUP_DOC = NO # The TAB_SIZE tag can be used to set the number of spaces in a tab. # Doxygen uses this value to replace tabs by spaces in code fragments. TAB_SIZE = 8 # The GENERATE_TODOLIST tag can be used to enable (YES) or # disable (NO) the todo list. This list is created by putting \todo # commands in the documentation. GENERATE_TODOLIST = YES # The GENERATE_TESTLIST tag can be used to enable (YES) or # disable (NO) the test list. This list is created by putting \test # commands in the documentation. GENERATE_TESTLIST = YES # The GENERATE_BUGLIST tag can be used to enable (YES) or # disable (NO) the bug list. This list is created by putting \bug # commands in the documentation. GENERATE_BUGLIST = YES # The GENERATE_DEPRECATEDLIST tag can be used to enable (YES) or # disable (NO) the deprecated list. This list is created by putting # \deprecated commands in the documentation. GENERATE_DEPRECATEDLIST= YES # This tag can be used to specify a number of aliases that acts # as commands in the documentation. An alias has the form "name=value". # For example adding "sideeffect=\par Side Effects:\n" will allow you to # put the command \sideeffect (or @sideeffect) in the documentation, which # will result in a user defined paragraph with heading "Side Effects:". # You can put \n's in the value part of an alias to insert newlines. ALIASES = # The ENABLED_SECTIONS tag can be used to enable conditional # documentation sections, marked by \if sectionname ... \endif. ENABLED_SECTIONS = # The MAX_INITIALIZER_LINES tag determines the maximum number of lines # the initial value of a variable or define consist of for it to appear in # the documentation. If the initializer consists of more lines than specified # here it will be hidden. Use a value of 0 to hide initializers completely. # The appearance of the initializer of individual variables and defines in the # documentation can be controlled using \showinitializer or \hideinitializer # command in the documentation regardless of this setting. MAX_INITIALIZER_LINES = 30 # Set the OPTIMIZE_OUTPUT_FOR_C tag to YES if your project consists of C sources # only. Doxygen will then generate output that is more tailored for C. # For instance some of the names that are used will be different. The list # of all members will be omitted, etc. OPTIMIZE_OUTPUT_FOR_C = NO # Set the OPTIMIZE_OUTPUT_JAVA tag to YES if your project consists of Java sources # only. Doxygen will then generate output that is more tailored for Java. # For instance namespaces will be presented as packages, qualified scopes # will look different, etc. OPTIMIZE_OUTPUT_JAVA = NO # Set the SHOW_USED_FILES tag to NO to disable the list of files generated # at the bottom of the documentation of classes and structs. If set to YES the # list will mention the files that were used to generate the documentation. SHOW_USED_FILES = YES #--------------------------------------------------------------------------- # configuration options related to warning and progress messages #--------------------------------------------------------------------------- # The QUIET tag can be used to turn on/off the messages that are generated # by doxygen. Possible values are YES and NO. If left blank NO is used. QUIET = NO # The WARNINGS tag can be used to turn on/off the warning messages that are # generated by doxygen. Possible values are YES and NO. If left blank # NO is used. WARNINGS = YES # If WARN_IF_UNDOCUMENTED is set to YES, then doxygen will generate warnings # for undocumented members. If EXTRACT_ALL is set to YES then this flag will # automatically be disabled. WARN_IF_UNDOCUMENTED = YES # If WARN_IF_DOC_ERROR is set to YES, doxygen will generate warnings for # potential errors in the documentation, such as not documenting some # parameters in a documented function, or documenting parameters that # don't exist or using markup commands wrongly. WARN_IF_DOC_ERROR = YES # The WARN_FORMAT tag determines the format of the warning messages that # doxygen can produce. The string should contain the $file, $line, and $text # tags, which will be replaced by the file and line number from which the # warning originated and the warning text. WARN_FORMAT = "$file:$line: $text" # The WARN_LOGFILE tag can be used to specify a file to which warning # and error messages should be written. If left blank the output is written # to stderr. WARN_LOGFILE = #--------------------------------------------------------------------------- # configuration options related to the input files #--------------------------------------------------------------------------- # The INPUT tag can be used to specify the files and/or directories that contain # documented source files. You may enter file names like "myfile.cpp" or # directories like "/usr/src/myproject". Separate the files or directories # with spaces. INPUT = # If the value of the INPUT tag contains directories, you can use the # FILE_PATTERNS tag to specify one or more wildcard pattern (like *.cpp # and *.h) to filter out the source-files in the directories. If left # blank the following patterns are tested: # *.c *.cc *.cxx *.cpp *.c++ *.java *.ii *.ixx *.ipp *.i++ *.inl *.h *.hh *.hxx *.hpp # *.h++ *.idl *.odl FILE_PATTERNS = # The RECURSIVE tag can be used to turn specify whether or not subdirectories # should be searched for input files as well. Possible values are YES and NO. # If left blank NO is used. RECURSIVE = NO # The EXCLUDE tag can be used to specify files and/or directories that should # excluded from the INPUT source files. This way you can easily exclude a # subdirectory from a directory tree whose root is specified with the INPUT tag. EXCLUDE = base64.h # The EXCLUDE_SYMLINKS tag can be used select whether or not files or directories # that are symbolic links (a Unix filesystem feature) are excluded from the input. EXCLUDE_SYMLINKS = NO # If the value of the INPUT tag contains directories, you can use the # EXCLUDE_PATTERNS tag to specify one or more wildcard patterns to exclude # certain files from those directories. EXCLUDE_PATTERNS = # The EXAMPLE_PATH tag can be used to specify one or more files or # directories that contain example code fragments that are included (see # the \include command). EXAMPLE_PATH = # If the value of the EXAMPLE_PATH tag contains directories, you can use the # EXAMPLE_PATTERNS tag to specify one or more wildcard pattern (like *.cpp # and *.h) to filter out the source-files in the directories. If left # blank all files are included. EXAMPLE_PATTERNS = # If the EXAMPLE_RECURSIVE tag is set to YES then subdirectories will be # searched for input files to be used with the \include or \dontinclude # commands irrespective of the value of the RECURSIVE tag. # Possible values are YES and NO. If left blank NO is used. EXAMPLE_RECURSIVE = NO # The IMAGE_PATH tag can be used to specify one or more files or # directories that contain image that are included in the documentation (see # the \image command). IMAGE_PATH = # The INPUT_FILTER tag can be used to specify a program that doxygen should # invoke to filter for each input file. Doxygen will invoke the filter program # by executing (via popen()) the command <filter> <input-file>, where <filter> # is the value of the INPUT_FILTER tag, and <input-file> is the name of an # input file. Doxygen will then use the output that the filter program writes # to standard output. INPUT_FILTER = # If the FILTER_SOURCE_FILES tag is set to YES, the input filter (if set using # INPUT_FILTER) will be used to filter the input files when producing source # files to browse (i.e. when SOURCE_BROWSER is set to YES). FILTER_SOURCE_FILES = NO #--------------------------------------------------------------------------- # configuration options related to source browsing #--------------------------------------------------------------------------- # If the SOURCE_BROWSER tag is set to YES then a list of source files will # be generated. Documented entities will be cross-referenced with these sources. SOURCE_BROWSER = NO # Setting the INLINE_SOURCES tag to YES will include the body # of functions and classes directly in the documentation. INLINE_SOURCES = NO # Setting the STRIP_CODE_COMMENTS tag to YES (the default) will instruct # doxygen to hide any special comment blocks from generated source code # fragments. Normal C and C++ comments will always remain visible. STRIP_CODE_COMMENTS = YES # If the REFERENCED_BY_RELATION tag is set to YES (the default) # then for each documented function all documented # functions referencing it will be listed. REFERENCED_BY_RELATION = YES # If the REFERENCES_RELATION tag is set to YES (the default) # then for each documented function all documented entities # called/used by that function will be listed. REFERENCES_RELATION = YES #--------------------------------------------------------------------------- # configuration options related to the alphabetical class index #--------------------------------------------------------------------------- # If the ALPHABETICAL_INDEX tag is set to YES, an alphabetical index # of all compounds will be generated. Enable this if the project # contains a lot of classes, structs, unions or interfaces. ALPHABETICAL_INDEX = NO # If the alphabetical index is enabled (see ALPHABETICAL_INDEX) then # the COLS_IN_ALPHA_INDEX tag can be used to specify the number of columns # in which this list will be split (can be a number in the range [1..20]) COLS_IN_ALPHA_INDEX = 5 # In case all classes in a project start with a common prefix, all # classes will be put under the same header in the alphabetical index. # The IGNORE_PREFIX tag can be used to specify one or more prefixes that # should be ignored while generating the index headers. IGNORE_PREFIX = #--------------------------------------------------------------------------- # configuration options related to the HTML output #--------------------------------------------------------------------------- # If the GENERATE_HTML tag is set to YES (the default) Doxygen will # generate HTML output. GENERATE_HTML = YES # The HTML_OUTPUT tag is used to specify where the HTML docs will be put. # If a relative path is entered the value of OUTPUT_DIRECTORY will be # put in front of it. If left blank `html' will be used as the default path. HTML_OUTPUT = html # The HTML_FILE_EXTENSION tag can be used to specify the file extension for # each generated HTML page (for example: .htm,.php,.asp). If it is left blank # doxygen will generate files with .html extension. HTML_FILE_EXTENSION = .html # The HTML_HEADER tag can be used to specify a personal HTML header for # each generated HTML page. If it is left blank doxygen will generate a # standard header. HTML_HEADER = # The HTML_FOOTER tag can be used to specify a personal HTML footer for # each generated HTML page. If it is left blank doxygen will generate a # standard footer. HTML_FOOTER = # The HTML_STYLESHEET tag can be used to specify a user defined cascading # style sheet that is used by each HTML page. It can be used to # fine-tune the look of the HTML output. If the tag is left blank doxygen # will generate a default style sheet HTML_STYLESHEET = # If the HTML_ALIGN_MEMBERS tag is set to YES, the members of classes, # files or namespaces will be aligned in HTML using tables. If set to # NO a bullet list will be used. HTML_ALIGN_MEMBERS = YES # If the GENERATE_HTMLHELP tag is set to YES, additional index files # will be generated that can be used as input for tools like the # Microsoft HTML help workshop to generate a compressed HTML help file (.chm) # of the generated HTML documentation. GENERATE_HTMLHELP = NO # If the GENERATE_HTMLHELP tag is set to YES, the CHM_FILE tag can # be used to specify the file name of the resulting .chm file. You # can add a path in front of the file if the result should not be # written to the html output dir. CHM_FILE = # If the GENERATE_HTMLHELP tag is set to YES, the HHC_LOCATION tag can # be used to specify the location (absolute path including file name) of # the HTML help compiler (hhc.exe). If non empty doxygen will try to run # the html help compiler on the generated index.hhp. HHC_LOCATION = # If the GENERATE_HTMLHELP tag is set to YES, the GENERATE_CHI flag # controls if a separate .chi index file is generated (YES) or that # it should be included in the master .chm file (NO). GENERATE_CHI = NO # If the GENERATE_HTMLHELP tag is set to YES, the BINARY_TOC flag # controls whether a binary table of contents is generated (YES) or a # normal table of contents (NO) in the .chm file. BINARY_TOC = NO # The TOC_EXPAND flag can be set to YES to add extra items for group members # to the contents of the Html help documentation and to the tree view. TOC_EXPAND = NO # The DISABLE_INDEX tag can be used to turn on/off the condensed index at # top of each HTML page. The value NO (the default) enables the index and # the value YES disables it. DISABLE_INDEX = NO # This tag can be used to set the number of enum values (range [1..20]) # that doxygen will group on one line in the generated HTML documentation. ENUM_VALUES_PER_LINE = 4 # If the GENERATE_TREEVIEW tag is set to YES, a side panel will be # generated containing a tree-like index structure (just like the one that # is generated for HTML Help). For this to work a browser that supports # JavaScript, DHTML, CSS and frames is required (for instance Mozilla, # Netscape 6.0+, Internet explorer 5.0+, or Konqueror). Windows users are # probably better off using the HTML help feature. GENERATE_TREEVIEW = NO # If the treeview is enabled (see GENERATE_TREEVIEW) then this tag can be # used to set the initial width (in pixels) of the frame in which the tree # is shown. TREEVIEW_WIDTH = 250 #--------------------------------------------------------------------------- # configuration options related to the LaTeX output #--------------------------------------------------------------------------- # If the GENERATE_LATEX tag is set to YES (the default) Doxygen will # generate Latex output. GENERATE_LATEX = NO # The LATEX_OUTPUT tag is used to specify where the LaTeX docs will be put. # If a relative path is entered the value of OUTPUT_DIRECTORY will be # put in front of it. If left blank `latex' will be used as the default path. LATEX_OUTPUT = latex # The LATEX_CMD_NAME tag can be used to specify the LaTeX command name to be # invoked. If left blank `latex' will be used as the default command name. LATEX_CMD_NAME = latex # The MAKEINDEX_CMD_NAME tag can be used to specify the command name to # generate index for LaTeX. If left blank `makeindex' will be used as the # default command name. MAKEINDEX_CMD_NAME = makeindex # If the COMPACT_LATEX tag is set to YES Doxygen generates more compact # LaTeX documents. This may be useful for small projects and may help to # save some trees in general. COMPACT_LATEX = NO # The PAPER_TYPE tag can be used to set the paper type that is used # by the printer. Possible values are: a4, a4wide, letter, legal and # executive. If left blank a4wide will be used. PAPER_TYPE = a4wide # The EXTRA_PACKAGES tag can be to specify one or more names of LaTeX # packages that should be included in the LaTeX output. EXTRA_PACKAGES = # The LATEX_HEADER tag can be used to specify a personal LaTeX header for # the generated latex document. The header should contain everything until # the first chapter. If it is left blank doxygen will generate a # standard header. Notice: only use this tag if you know what you are doing! LATEX_HEADER = # If the PDF_HYPERLINKS tag is set to YES, the LaTeX that is generated # is prepared for conversion to pdf (using ps2pdf). The pdf file will # contain links (just like the HTML output) instead of page references # This makes the output suitable for online browsing using a pdf viewer. PDF_HYPERLINKS = NO # If the USE_PDFLATEX tag is set to YES, pdflatex will be used instead of # plain latex in the generated Makefile. Set this option to YES to get a # higher quality PDF documentation. USE_PDFLATEX = NO # If the LATEX_BATCHMODE tag is set to YES, doxygen will add the \\batchmode. # command to the generated LaTeX files. This will instruct LaTeX to keep # running if errors occur, instead of asking the user for help. # This option is also used when generating formulas in HTML. LATEX_BATCHMODE = NO #--------------------------------------------------------------------------- # configuration options related to the RTF output #--------------------------------------------------------------------------- # If the GENERATE_RTF tag is set to YES Doxygen will generate RTF output # The RTF output is optimised for Word 97 and may not look very pretty with # other RTF readers or editors. GENERATE_RTF = NO # The RTF_OUTPUT tag is used to specify where the RTF docs will be put. # If a relative path is entered the value of OUTPUT_DIRECTORY will be # put in front of it. If left blank `rtf' will be used as the default path. RTF_OUTPUT = rtf # If the COMPACT_RTF tag is set to YES Doxygen generates more compact # RTF documents. This may be useful for small projects and may help to # save some trees in general. COMPACT_RTF = NO # If the RTF_HYPERLINKS tag is set to YES, the RTF that is generated # will contain hyperlink fields. The RTF file will # contain links (just like the HTML output) instead of page references. # This makes the output suitable for online browsing using WORD or other # programs which support those fields. # Note: wordpad (write) and others do not support links. RTF_HYPERLINKS = NO # Load stylesheet definitions from file. Syntax is similar to doxygen's # config file, i.e. a series of assigments. You only have to provide # replacements, missing definitions are set to their default value. RTF_STYLESHEET_FILE = # Set optional variables used in the generation of an rtf document. # Syntax is similar to doxygen's config file. RTF_EXTENSIONS_FILE = #--------------------------------------------------------------------------- # configuration options related to the man page output #--------------------------------------------------------------------------- # If the GENERATE_MAN tag is set to YES (the default) Doxygen will # generate man pages GENERATE_MAN = NO # The MAN_OUTPUT tag is used to specify where the man pages will be put. # If a relative path is entered the value of OUTPUT_DIRECTORY will be # put in front of it. If left blank `man' will be used as the default path. MAN_OUTPUT = man # The MAN_EXTENSION tag determines the extension that is added to # the generated man pages (default is the subroutine's section .3) MAN_EXTENSION = .3 # If the MAN_LINKS tag is set to YES and Doxygen generates man output, # then it will generate one additional man file for each entity # documented in the real man page(s). These additional files # only source the real man page, but without them the man command # would be unable to find the correct page. The default is NO. MAN_LINKS = NO #--------------------------------------------------------------------------- # configuration options related to the XML output #--------------------------------------------------------------------------- # If the GENERATE_XML tag is set to YES Doxygen will # generate an XML file that captures the structure of # the code including all documentation. Note that this # feature is still experimental and incomplete at the # moment. GENERATE_XML = NO # The XML_SCHEMA tag can be used to specify an XML schema, # which can be used by a validating XML parser to check the # syntax of the XML files. XML_SCHEMA = # The XML_DTD tag can be used to specify an XML DTD, # which can be used by a validating XML parser to check the # syntax of the XML files. XML_DTD = #--------------------------------------------------------------------------- # configuration options for the AutoGen Definitions output #--------------------------------------------------------------------------- # If the GENERATE_AUTOGEN_DEF tag is set to YES Doxygen will # generate an AutoGen Definitions (see autogen.sf.net) file # that captures the structure of the code including all # documentation. Note that this feature is still experimental # and incomplete at the moment. GENERATE_AUTOGEN_DEF = NO #--------------------------------------------------------------------------- # configuration options related to the Perl module output #--------------------------------------------------------------------------- # If the GENERATE_PERLMOD tag is set to YES Doxygen will # generate a Perl module file that captures the structure of # the code including all documentation. Note that this # feature is still experimental and incomplete at the # moment. GENERATE_PERLMOD = NO # If the PERLMOD_LATEX tag is set to YES Doxygen will generate # the necessary Makefile rules, Perl scripts and LaTeX code to be able # to generate PDF and DVI output from the Perl module output. PERLMOD_LATEX = NO # If the PERLMOD_PRETTY tag is set to YES the Perl module output will be # nicely formatted so it can be parsed by a human reader. This is useful # if you want to understand what is going on. On the other hand, if this # tag is set to NO the size of the Perl module output will be much smaller # and Perl will parse it just the same. PERLMOD_PRETTY = YES # The names of the make variables in the generated doxyrules.make file # are prefixed with the string contained in PERLMOD_MAKEVAR_PREFIX. # This is useful so different doxyrules.make files included by the same # Makefile don't overwrite each other's variables. PERLMOD_MAKEVAR_PREFIX = #--------------------------------------------------------------------------- # Configuration options related to the preprocessor #--------------------------------------------------------------------------- # If the ENABLE_PREPROCESSING tag is set to YES (the default) Doxygen will # evaluate all C-preprocessor directives found in the sources and include # files. ENABLE_PREPROCESSING = YES # If the MACRO_EXPANSION tag is set to YES Doxygen will expand all macro # names in the source code. If set to NO (the default) only conditional # compilation will be performed. Macro expansion can be done in a controlled # way by setting EXPAND_ONLY_PREDEF to YES. MACRO_EXPANSION = NO # If the EXPAND_ONLY_PREDEF and MACRO_EXPANSION tags are both set to YES # then the macro expansion is limited to the macros specified with the # PREDEFINED and EXPAND_AS_PREDEFINED tags. EXPAND_ONLY_PREDEF = NO # If the SEARCH_INCLUDES tag is set to YES (the default) the includes files # in the INCLUDE_PATH (see below) will be search if a #include is found. SEARCH_INCLUDES = YES # The INCLUDE_PATH tag can be used to specify one or more directories that # contain include files that are not input files but should be processed by # the preprocessor. INCLUDE_PATH = # You can use the INCLUDE_FILE_PATTERNS tag to specify one or more wildcard # patterns (like *.h and *.hpp) to filter out the header-files in the # directories. If left blank, the patterns specified with FILE_PATTERNS will # be used. INCLUDE_FILE_PATTERNS = # The PREDEFINED tag can be used to specify one or more macro names that # are defined before the preprocessor is started (similar to the -D option of # gcc). The argument of the tag is a list of macros of the form: name # or name=definition (no spaces). If the definition and the = are # omitted =1 is assumed. PREDEFINED = # If the MACRO_EXPANSION and EXPAND_ONLY_PREDEF tags are set to YES then # this tag can be used to specify a list of macro names that should be expanded. # The macro definition that is found in the sources will be used. # Use the PREDEFINED tag if you want to use a different macro definition. EXPAND_AS_DEFINED = # If the SKIP_FUNCTION_MACROS tag is set to YES (the default) then # doxygen's preprocessor will remove all function-like macros that are alone # on a line, have an all uppercase name, and do not end with a semicolon. Such # function macros are typically used for boiler-plate code, and will confuse the # parser if not removed. SKIP_FUNCTION_MACROS = YES #--------------------------------------------------------------------------- # Configuration::addtions related to external references #--------------------------------------------------------------------------- # The TAGFILES tag can be used to specify one or more tagfiles. TAGFILES = # When a file name is specified after GENERATE_TAGFILE, doxygen will create # a tag file that is based on the input files it reads. GENERATE_TAGFILE = # If the ALLEXTERNALS tag is set to YES all external classes will be listed # in the class index. If set to NO only the inherited external classes # will be listed. ALLEXTERNALS = NO # If the EXTERNAL_GROUPS tag is set to YES all external groups will be listed # in the modules index. If set to NO, only the current project's groups will # be listed. EXTERNAL_GROUPS = YES # The PERL_PATH should be the absolute path and name of the perl script # interpreter (i.e. the result of `which perl'). PERL_PATH = /usr/bin/perl #--------------------------------------------------------------------------- # Configuration options related to the dot tool #--------------------------------------------------------------------------- # If the CLASS_DIAGRAMS tag is set to YES (the default) Doxygen will # generate a inheritance diagram (in Html, RTF and LaTeX) for classes with base or # super classes. Setting the tag to NO turns the diagrams off. Note that this # option is superceded by the HAVE_DOT option below. This is only a fallback. It is # recommended to install and use dot, since it yield more powerful graphs. CLASS_DIAGRAMS = YES # If set to YES, the inheritance and collaboration graphs will hide # inheritance and usage relations if the target is undocumented # or is not a class. HIDE_UNDOC_RELATIONS = YES # If you set the HAVE_DOT tag to YES then doxygen will assume the dot tool is # available from the path. This tool is part of Graphviz, a graph visualization # toolkit from AT&T and Lucent Bell Labs. The other options in this section # have no effect if this option is set to NO (the default) HAVE_DOT = NO # If the CLASS_GRAPH and HAVE_DOT tags are set to YES then doxygen # will generate a graph for each documented class showing the direct and # indirect inheritance relations. Setting this tag to YES will force the # the CLASS_DIAGRAMS tag to NO. CLASS_GRAPH = YES # If the COLLABORATION_GRAPH and HAVE_DOT tags are set to YES then doxygen # will generate a graph for each documented class showing the direct and # indirect implementation dependencies (inheritance, containment, and # class references variables) of the class with other documented classes. COLLABORATION_GRAPH = YES # If set to YES, the inheritance and collaboration graphs will show the # relations between templates and their instances. TEMPLATE_RELATIONS = YES # If the ENABLE_PREPROCESSING, SEARCH_INCLUDES, INCLUDE_GRAPH, and HAVE_DOT # tags are set to YES then doxygen will generate a graph for each documented # file showing the direct and indirect include dependencies of the file with # other documented files. INCLUDE_GRAPH = YES # If the ENABLE_PREPROCESSING, SEARCH_INCLUDES, INCLUDED_BY_GRAPH, and # HAVE_DOT tags are set to YES then doxygen will generate a graph for each # documented header file showing the documented files that directly or # indirectly include this file. INCLUDED_BY_GRAPH = YES # If the GRAPHICAL_HIERARCHY and HAVE_DOT tags are set to YES then doxygen # will graphical hierarchy of all classes instead of a textual one. GRAPHICAL_HIERARCHY = YES # The DOT_IMAGE_FORMAT tag can be used to set the image format of the images # generated by dot. Possible values are png, jpg, or gif # If left blank png will be used. DOT_IMAGE_FORMAT = png # The tag DOT_PATH can be used to specify the path where the dot tool can be # found. If left blank, it is assumed the dot tool can be found on the path. DOT_PATH = # The DOTFILE_DIRS tag can be used to specify one or more directories that # contain dot files that are included in the documentation (see the # \dotfile command). DOTFILE_DIRS = # The MAX_DOT_GRAPH_WIDTH tag can be used to set the maximum allowed width # (in pixels) of the graphs generated by dot. If a graph becomes larger than # this value, doxygen will try to truncate the graph, so that it fits within # the specified constraint. Beware that most browsers cannot cope with very # large images. MAX_DOT_GRAPH_WIDTH = 1024 # The MAX_DOT_GRAPH_HEIGHT tag can be used to set the maximum allows height # (in pixels) of the graphs generated by dot. If a graph becomes larger than # this value, doxygen will try to truncate the graph, so that it fits within # the specified constraint. Beware that most browsers cannot cope with very # large images. MAX_DOT_GRAPH_HEIGHT = 1024 # If the GENERATE_LEGEND tag is set to YES (the default) Doxygen will # generate a legend page explaining the meaning of the various boxes and # arrows in the dot generated graphs. GENERATE_LEGEND = YES # If the DOT_CLEANUP tag is set to YES (the default) Doxygen will # remove the intermedate dot files that are used to generate # the various graphs. DOT_CLEANUP = YES #--------------------------------------------------------------------------- # Configuration::addtions related to the search engine #--------------------------------------------------------------------------- # The SEARCHENGINE tag specifies whether or not a search engine should be # used. If set to NO the values of all tags below this one will be ignored. SEARCHENGINE = NO # The CGI_NAME tag should be the name of the CGI script that # starts the search engine (doxysearch) with the correct parameters. # A script with this name will be generated by doxygen. CGI_NAME = search.cgi # The CGI_URL tag should be the absolute URL to the directory where the # cgi binaries are located. See the documentation of your http daemon for # details. CGI_URL = # The DOC_URL tag should be the absolute URL to the directory where the # documentation is located. If left blank the absolute path to the # documentation, with file:// prepended to it, will be used. DOC_URL = # The DOC_ABSPATH tag should be the absolute path to the directory where the # documentation is located. If left blank the directory on the local machine # will be used. DOC_ABSPATH = # The BIN_ABSPATH tag must point to the directory where the doxysearch binary # is installed. BIN_ABSPATH = /usr/local/bin/ # The EXT_DOC_PATHS tag can be used to specify one or more paths to # documentation generated for other projects. This allows doxysearch to search # the documentation for these projects as well. EXT_DOC_PATHS =
0
apollo_public_repos/apollo-platform/ros/ros_comm/xmlrpcpp
apollo_public_repos/apollo-platform/ros/ros_comm/xmlrpcpp/src/XmlRpcUtil.cpp
#include "XmlRpcUtil.h" #ifndef MAKEDEPEND # include <ctype.h> # include <iostream> # include <stdarg.h> # include <stdio.h> # include <string.h> #endif #include "XmlRpc.h" using namespace XmlRpc; //#define USE_WINDOWS_DEBUG // To make the error and log messages go to VC++ debug output #ifdef USE_WINDOWS_DEBUG #define WIN32_LEAN_AND_MEAN #include <windows.h> #endif // Version id const char XmlRpc::XMLRPC_VERSION[] = "XMLRPC++ 0.7"; // Default log verbosity: 0 for no messages through 5 (writes everything) int XmlRpcLogHandler::_verbosity = 0; // Default log handler static class DefaultLogHandler : public XmlRpcLogHandler { public: void log(int level, const char* msg) { #ifdef USE_WINDOWS_DEBUG if (level <= _verbosity) { OutputDebugString(msg); OutputDebugString("\n"); } #else if (level <= _verbosity) std::cout << msg << std::endl; #endif } } defaultLogHandler; // Message log singleton XmlRpcLogHandler* XmlRpcLogHandler::_logHandler = &defaultLogHandler; // Default error handler static class DefaultErrorHandler : public XmlRpcErrorHandler { public: #ifdef USE_WINDOWS_DEBUG void error(const char* msg) { OutputDebugString(msg); OutputDebugString("\n"); #else void error(const char*) { #endif // As far as I can tell, throwing an exception here is a bug, unless // the intention is that the program should exit. Throughout the code, // calls to error() are followed by cleanup code that does things like // closing a failed socket. Thus it would seem that it should be // possible to continue execution. But if the user just catches the // exception that's thrown here, the library ends up in a bogus state. // So I'm commenting out the throw. - BPG // //throw std::runtime_error(msg); } } defaultErrorHandler; // Error handler singleton XmlRpcErrorHandler* XmlRpcErrorHandler::_errorHandler = &defaultErrorHandler; // Easy API for log verbosity int XmlRpc::getVerbosity() { return XmlRpcLogHandler::getVerbosity(); } void XmlRpc::setVerbosity(int level) { XmlRpcLogHandler::setVerbosity(level); } void XmlRpcUtil::log(int level, const char* fmt, ...) { if (level <= XmlRpcLogHandler::getVerbosity()) { va_list va; char buf[1024]; va_start( va, fmt); vsnprintf(buf,sizeof(buf)-1,fmt,va); va_end(va); buf[sizeof(buf)-1] = 0; XmlRpcLogHandler::getLogHandler()->log(level, buf); } } void XmlRpcUtil::error(const char* fmt, ...) { va_list va; va_start(va, fmt); char buf[1024]; vsnprintf(buf,sizeof(buf)-1,fmt,va); va_end(va); buf[sizeof(buf)-1] = 0; XmlRpcErrorHandler::getErrorHandler()->error(buf); } // Returns contents between <tag> and </tag>, updates offset to char after </tag> std::string XmlRpcUtil::parseTag(const char* tag, std::string const& xml, int* offset) { if (*offset >= int(xml.length())) return std::string(); size_t istart = xml.find(tag, *offset); if (istart == std::string::npos) return std::string(); istart += strlen(tag); std::string etag = "</"; etag += tag + 1; size_t iend = xml.find(etag, istart); if (iend == std::string::npos) return std::string(); *offset = int(iend + etag.length()); return xml.substr(istart, iend-istart); } // Returns true if the tag is found and updates offset to the char after the tag bool XmlRpcUtil::findTag(const char* tag, std::string const& xml, int* offset) { if (*offset >= int(xml.length())) return false; size_t istart = xml.find(tag, *offset); if (istart == std::string::npos) return false; *offset = int(istart + strlen(tag)); return true; } // Returns true if the tag is found at the specified offset (modulo any whitespace) // and updates offset to the char after the tag bool XmlRpcUtil::nextTagIs(const char* tag, std::string const& xml, int* offset) { if (*offset >= int(xml.length())) return false; const char* cp = xml.c_str() + *offset; int nc = 0; while (*cp && isspace(*cp)) { ++cp; ++nc; } int len = int(strlen(tag)); if (*cp && (strncmp(cp, tag, len) == 0)) { *offset += nc + len; return true; } return false; } // Returns the next tag and updates offset to the char after the tag, or empty string // if the next non-whitespace character is not '<' std::string XmlRpcUtil::getNextTag(std::string const& xml, int* offset) { if (*offset >= int(xml.length())) return std::string(); size_t pos = *offset; const char* cp = xml.c_str() + pos; while (*cp && isspace(*cp)) { ++cp; ++pos; } if (*cp != '<') return std::string(); std::string s; do { s += *cp; ++pos; } while (*cp++ != '>' && *cp != 0); *offset = int(pos); return s; } // xml encodings (xml-encoded entities are preceded with '&') static const char AMP = '&'; static const char rawEntity[] = { '<', '>', '&', '\'', '\"', 0 }; static const char* xmlEntity[] = { "lt;", "gt;", "amp;", "apos;", "quot;", 0 }; static const int xmlEntLen[] = { 3, 3, 4, 5, 5 }; // Replace xml-encoded entities with the raw text equivalents. std::string XmlRpcUtil::xmlDecode(const std::string& encoded) { std::string::size_type iAmp = encoded.find(AMP); if (iAmp == std::string::npos) return encoded; std::string decoded(encoded, 0, iAmp); std::string::size_type iSize = encoded.size(); decoded.reserve(iSize); const char* ens = encoded.c_str(); while (iAmp != iSize) { if (encoded[iAmp] == AMP && iAmp+1 < iSize) { int iEntity; for (iEntity=0; xmlEntity[iEntity] != 0; ++iEntity) //if (encoded.compare(iAmp+1, xmlEntLen[iEntity], xmlEntity[iEntity]) == 0) if (strncmp(ens+iAmp+1, xmlEntity[iEntity], xmlEntLen[iEntity]) == 0) { decoded += rawEntity[iEntity]; iAmp += xmlEntLen[iEntity]+1; break; } if (xmlEntity[iEntity] == 0) // unrecognized sequence decoded += encoded[iAmp++]; } else { decoded += encoded[iAmp++]; } } return decoded; } // Replace raw text with xml-encoded entities. std::string XmlRpcUtil::xmlEncode(const std::string& raw) { std::string::size_type iRep = raw.find_first_of(rawEntity); if (iRep == std::string::npos) return raw; std::string encoded(raw, 0, iRep); std::string::size_type iSize = raw.size(); while (iRep != iSize) { int iEntity; for (iEntity=0; rawEntity[iEntity] != 0; ++iEntity) if (raw[iRep] == rawEntity[iEntity]) { encoded += AMP; encoded += xmlEntity[iEntity]; break; } if (rawEntity[iEntity] == 0) encoded += raw[iRep]; ++iRep; } return encoded; }
0
apollo_public_repos/apollo-platform/ros/ros_comm
apollo_public_repos/apollo-platform/ros/ros_comm/rosbag/CMakeLists.txt
cmake_minimum_required(VERSION 2.8.3) project(rosbag) if(NOT WIN32) set_directory_properties(PROPERTIES COMPILE_OPTIONS "-Wall;-Wextra") endif() set(CMAKE_CXX_FLAGS "-std=c++11 ${CMAKE_CXX_FLAGS}") find_package(catkin REQUIRED COMPONENTS rosbag_storage rosconsole roscpp topic_tools xmlrpcpp) find_package(Boost REQUIRED COMPONENTS date_time regex program_options filesystem) find_package(BZip2 REQUIRED) catkin_python_setup() # Support large bags (>2GB) on 32-bit systems add_definitions(-D_FILE_OFFSET_BITS=64) include_directories(include ${catkin_INCLUDE_DIRS} ${Boost_INCLUDE_DIRS}) set(FASTRTPS_INCLUDE_DIR "${FASTRTPS_PATH}/include") set(FASTRTPS_LIBRARY_DIR "${FASTRTPS_PATH}/lib") set(FASTRTPS_GEN "${FASTRTPS_PATH}/bin/fastrtpsgen") include_directories(include ${FASTRTPS_INCLUDE_DIR}) catkin_package( LIBRARIES rosbag INCLUDE_DIRS include CATKIN_DEPENDS rosbag_storage rosconsole roscpp topic_tools xmlrpcpp) add_library(rosbag src/player.cpp src/recorder.cpp src/time_translator.cpp) target_link_libraries(rosbag ${catkin_LIBRARIES} ${Boost_LIBRARIES}) add_executable(record src/record.cpp) target_link_libraries(record rosbag) add_executable(play src/play.cpp) target_link_libraries(play rosbag) install(DIRECTORY include/${PROJECT_NAME}/ DESTINATION ${CATKIN_PACKAGE_INCLUDE_DESTINATION} FILES_MATCHING PATTERN "*.h") install(TARGETS rosbag ARCHIVE DESTINATION ${CATKIN_PACKAGE_LIB_DESTINATION} LIBRARY DESTINATION ${CATKIN_PACKAGE_LIB_DESTINATION} RUNTIME DESTINATION ${CATKIN_GLOBAL_BIN_DESTINATION}) install(TARGETS record play ARCHIVE DESTINATION ${CATKIN_PACKAGE_LIB_DESTINATION} LIBRARY DESTINATION ${CATKIN_PACKAGE_LIB_DESTINATION} RUNTIME DESTINATION ${CATKIN_PACKAGE_BIN_DESTINATION}) catkin_install_python(PROGRAMS scripts/bag2png.py scripts/bagsort.py scripts/fastrebag.py scripts/fixbag.py scripts/fixbag_batch.py scripts/fix_md5sums.py scripts/fix_moved_messages.py scripts/fix_msg_defs.py scripts/makerule.py scripts/savemsg.py scripts/topic_renamer.py DESTINATION ${CATKIN_PACKAGE_BIN_DESTINATION})
0
apollo_public_repos/apollo-platform/ros/ros_comm
apollo_public_repos/apollo-platform/ros/ros_comm/rosbag/FORMATS
Version 0: ------------- topic_name md5sum datatype <repeating N> time.sec time.nsec length MSGDATA ------------- Version 1.0: ------------- #ROSLOG V1.0 quantity <repeating quantity> topic_name md5sum datatype <repeating N> topic_name time.sec time.nsec length MSGDATA ------------- Version 1.1: ------------- #ROSLOG V1.1 <repeating N> topic_name md5sum datatype time.sec time.nsec length MSGDATA ------------- Alternative Version 1.1: ------------- #ROSRECORD V1.1 <repeating N> topic_name md5sum datatype time.sec time.nsec length MSGDATA ------------- Version 1.2: ------------- #ROSRECORD V1.2 file header op=2 index_pos=index_1.pos --- <empty> (padded with ' ' to 4KB) msg_def_1 msg_1 msg_2 ... msg_N index_1 ver=0 topic=topic count=count --- timestamp_1, uncompressed_byte_offset_1 timestamp_2, uncompressed_byte_offset_2 ... timestamp_N, uncompressed_byte_offset_N index_2 ... Version 2.0: ------------- #ROSBAG V2.0 file_header op=3 index_pos=msg_def_1.pos # position of index conn_count=conn_count # total number of distinct connections in the bag chunk_count=chunk_count # total number of chunks in the bag --- <empty> (padded with ' ' to 4KB) chunk_1 op=5 compression=bz2 # type of compression (optional) size=<uncompressed bytes> # size of data when uncompressed (optional) --- conn_1i op=7 topic=topic id=0 --- topic=topic message_definition= type= md5sum= latching=1 callerid=caller1234 msg_1 op=2 topic=... time=... conn=... --- <serialized msg> msg_2 op=2 topic=... time=... conn=... --- <serialized msg> ... msg_N chunk_index_1.0 op=4 ver=1 conn=conn count=count --- timestamp_1, uncompressed_byte_offset_1 timestamp_2, uncompressed_byte_offset_2 ... timestamp_N, uncompressed_byte_offset_N chunk_index_1.1 op=4 ver=1 conn=conn count=count --- ... chunk_2 op=5 compression=bz2 size=<uncompressed bytes> --- msg_N+1 msg_N+2 ... msg_N+M chunk_index_2.0 op=4 ver=1 conn=conn count=count --- timestamp_N+1, uncompressed_byte_offset_1 timestamp_N+2, uncompressed_byte_offset_2 ... timestamp_N+M, uncompressed_byte_offset_N+M ... conn_1 op=7 id=0 --- latching=1 callerid=caller1234 msg_def_1 op=1 topic= type= md5sum= def= --- <empty> msg_def_2 op=1 topic= type= md5sum= def= --- <empty> ... chunk_info_1 op=6 ver=1 chunk_pos=chunk_1.pos start=start_stamp_1 end=end_stamp_1 count=K --- conn_1, count_1 conn_2, count_2 ... conn_K, count_K chunk_info_2 ... ... <eof>
0
apollo_public_repos/apollo-platform/ros/ros_comm
apollo_public_repos/apollo-platform/ros/ros_comm/rosbag/package.xml
<package> <name>rosbag</name> <version>1.11.21</version> <description> This is a set of tools for recording from and playing back to ROS topics. It is intended to be high performance and avoids deserialization and reserialization of the messages. </description> <maintainer email="dthomas@osrfoundation.org">Dirk Thomas</maintainer> <license>BSD</license> <url>http://ros.org/wiki/rosbag</url> <author>Tim Field</author> <author>Jeremy Leibs</author> <author>James Bowman</author> <buildtool_depend version_gte="0.5.78">catkin</buildtool_depend> <build_depend>boost</build_depend> <build_depend>cpp_common</build_depend> <build_depend>python-imaging</build_depend> <build_depend>rosbag_storage</build_depend> <build_depend>rosconsole</build_depend> <build_depend>roscpp</build_depend> <build_depend>roscpp_serialization</build_depend> <build_depend>topic_tools</build_depend> <build_depend>xmlrpcpp</build_depend> <run_depend>boost</run_depend> <run_depend>genmsg</run_depend> <run_depend>genpy</run_depend> <run_depend>python-rospkg</run_depend> <run_depend>rosbag_storage</run_depend> <run_depend>rosconsole</run_depend> <run_depend>roscpp</run_depend> <run_depend>roslib</run_depend> <run_depend>rospy</run_depend> <run_depend>topic_tools</run_depend> <run_depend>xmlrpcpp</run_depend> <export> <rosdoc config="${prefix}/rosdoc.yaml"/> </export> </package>
0
apollo_public_repos/apollo-platform/ros/ros_comm
apollo_public_repos/apollo-platform/ros/ros_comm/rosbag/mainpage.dox
/** \mainpage \htmlinclude manifest.html \b rosbag is a set of tools and API's for recording/writing messages to bag files and playing/reading them back. Most code (not relying on the ROS client library) has been moved to the <a href="../../../rosbag_storage/html/c++/">rosbag_storage</a> package. */
0
apollo_public_repos/apollo-platform/ros/ros_comm
apollo_public_repos/apollo-platform/ros/ros_comm/rosbag/rosdoc.yaml
- builder: epydoc output_dir: python - builder: doxygen name: C++ API output_dir: c++ file_patterns: '*.c *.cpp *.h *.cc *.hh *.dox'
0
apollo_public_repos/apollo-platform/ros/ros_comm
apollo_public_repos/apollo-platform/ros/ros_comm/rosbag/setup.py
#!/usr/bin/env python from distutils.core import setup from catkin_pkg.python_setup import generate_distutils_setup d = generate_distutils_setup( packages=['rosbag'], package_dir={'': 'src'}, scripts=['scripts/rosbag'], requires=['genmsg', 'genpy', 'roslib', 'rospkg'] ) setup(**d)
0
apollo_public_repos/apollo-platform/ros/ros_comm
apollo_public_repos/apollo-platform/ros/ros_comm/rosbag/.tar
{!!python/unicode 'url': 'https://github.com/ros-gbp/ros_comm-release/archive/release/indigo/rosbag/1.11.21-0.tar.gz', !!python/unicode 'version': ros_comm-release-release-indigo-rosbag-1.11.21-0}
0
apollo_public_repos/apollo-platform/ros/ros_comm
apollo_public_repos/apollo-platform/ros/ros_comm/rosbag/CHANGELOG.rst
^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Changelog for package rosbag ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 1.11.21 (2017-03-06) -------------------- * throw exception instead of accessing invalid memory (`#971 <https://github.com/ros/ros_comm/pull/971>`_) * terminate underlying rosbag play, record on SIGTERM (`#951 <https://github.com/ros/ros_comm/issues/951>`_) * fix BagMigrationException in migrate_raw (`#917 <https://github.com/ros/ros_comm/issues/917>`_) * set default values for min_space and min_space_str (`#883 <https://github.com/ros/ros_comm/issues/883>`_) * update rosbag filter progress meter to use raw uncompressed input size (`#857 <https://github.com/ros/ros_comm/issues/857>`_) 1.11.20 (2016-06-27) -------------------- 1.11.19 (2016-04-18) -------------------- * promote the result of read_messages to a namedtuple (`#777 <https://github.com/ros/ros_comm/pull/777>`_) * use directory specific compiler flags (`#785 <https://github.com/ros/ros_comm/pull/785>`_) 1.11.18 (2016-03-17) -------------------- 1.11.17 (2016-03-11) -------------------- * use boost::make_shared instead of new for constructing boost::shared_ptr (`#740 <https://github.com/ros/ros_comm/issues/740>`_) 1.11.16 (2015-11-09) -------------------- * show size unit for --size of rosbag record in help string (`#697 <https://github.com/ros/ros_comm/pull/697>`_) 1.11.15 (2015-10-13) -------------------- * add option --prefix for prefixing output topics (`#626 <https://github.com/ros/ros_comm/pull/626>`_) 1.11.14 (2015-09-19) -------------------- * reduce memory usage by using slots for IndexEntry types (`#613 <https://github.com/ros/ros_comm/pull/613>`_) * remove duplicate topics (`#647 <https://github.com/ros/ros_comm/issues/647>`_) * better exception when calling get_start_time / get_end_time on empty bags (`#657 <https://github.com/ros/ros_comm/pull/657>`_) * make support for lz4 in rosbag optional (`#642 <https://github.com/ros/ros_comm/pull/642>`_) * fix handling of "play --topics" (`#620 <https://github.com/ros/ros_comm/issues/620>`_) 1.11.13 (2015-04-28) -------------------- 1.11.12 (2015-04-27) -------------------- 1.11.11 (2015-04-16) -------------------- * add support for pausing when specified topics are about to be published (`#569 <https://github.com/ros/ros_comm/pull/569>`_) 1.11.10 (2014-12-22) -------------------- * add option to specify the minimum disk space at which recording is stopped (`#500 <https://github.com/ros/ros_comm/pull/500>`_) * add convenience API to Python rosbag (`#508 <https://github.com/ros/ros_comm/issues/508>`_) * fix delay on detecting a running rosmaster with use_sim_time set (`#532 <https://github.com/ros/ros_comm/pull/532>`_) 1.11.9 (2014-08-18) ------------------- 1.11.8 (2014-08-04) ------------------- 1.11.7 (2014-07-18) ------------------- 1.11.6 (2014-07-10) ------------------- * fix rosbag record prefix (`#449 <https://github.com/ros/ros_comm/issues/449>`_) 1.11.5 (2014-06-24) ------------------- * Fix typo in rosbag usage 1.11.4 (2014-06-16) ------------------- * Python 3 compatibility (`#426 <https://github.com/ros/ros_comm/issues/426>`_, `#430 <https://github.com/ros/ros_comm/issues/430>`_) 1.11.3 (2014-05-21) ------------------- 1.11.2 (2014-05-08) ------------------- 1.11.1 (2014-05-07) ------------------- * add lz4 compression to rosbag (Python and C++) (`#356 <https://github.com/ros/ros_comm/issues/356>`_) * fix rosbag record --node (`#357 <https://github.com/ros/ros_comm/issues/357>`_) * move rosbag dox to rosbag_storage (`#389 <https://github.com/ros/ros_comm/issues/389>`_) 1.11.0 (2014-03-04) ------------------- * use catkin_install_python() to install Python scripts (`#361 <https://github.com/ros/ros_comm/issues/361>`_) 1.10.0 (2014-02-11) ------------------- * remove use of __connection header 1.9.54 (2014-01-27) ------------------- * readd missing declaration of rosbag::createAdvertiseOptions (`#338 <https://github.com/ros/ros_comm/issues/338>`_) 1.9.53 (2014-01-14) ------------------- 1.9.52 (2014-01-08) ------------------- 1.9.51 (2014-01-07) ------------------- * move several client library independent parts from ros_comm into roscpp_core, split rosbag storage specific stuff from client library usage (`#299 <https://github.com/ros/ros_comm/issues/299>`_) * fix return value on platforms where char is unsigned. * fix usage of boost include directories 1.9.50 (2013-10-04) ------------------- * add chunksize option to rosbag record 1.9.49 (2013-09-16) ------------------- 1.9.48 (2013-08-21) ------------------- * search for exported rosbag migration rules based on new package rosbag_migration_rule 1.9.47 (2013-07-03) ------------------- 1.9.46 (2013-06-18) ------------------- * fix crash in bag migration (`#239 <https://github.com/ros/ros_comm/issues/239>`_) 1.9.45 (2013-06-06) ------------------- * added option '--duration' to 'rosbag play' (`#121 <https://github.com/ros/ros_comm/issues/121>`_) * fix missing newlines in rosbag error messages (`#237 <https://github.com/ros/ros_comm/issues/237>`_) * fix flushing for tools like 'rosbag compress' (`#237 <https://github.com/ros/ros_comm/issues/237>`_) 1.9.44 (2013-03-21) ------------------- * fix various issues on Windows (`#189 <https://github.com/ros/ros_comm/issues/189>`_) 1.9.43 (2013-03-13) ------------------- 1.9.42 (2013-03-08) ------------------- * added option '--duration' to 'rosrun rosbag play' (`#121 <https://github.com/ros/ros_comm/issues/121>`_) * add error message to rosbag when using same in and out file (`#171 <https://github.com/ros/ros_comm/issues/171>`_) 1.9.41 (2013-01-24) ------------------- 1.9.40 (2013-01-13) ------------------- * fix bagsort script (`#42 <https://github.com/ros/ros_comm/issues/42>`_) 1.9.39 (2012-12-29) ------------------- * first public release for Groovy
0
apollo_public_repos/apollo-platform/ros/ros_comm/rosbag/include
apollo_public_repos/apollo-platform/ros/ros_comm/rosbag/include/rosbag/time_translator.h
/********************************************************************* * Software License Agreement (BSD License) * * Copyright (c) 2010, 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. *********************************************************************/ #ifndef ROSBAG_TIME_TRANSLATOR_H #define ROSBAG_TIME_TRANSLATOR_H #include "ros/time.h" #include "rosbag/macros.h" namespace rosbag { //! Helper class for translating between two times /*! * The time translator can be configured with a Real start time, a * Translated start time, and a time scale. * * It will convert a time from a series starting at realStartTime to a * comparable time series instead starting at translatedStartTime. * All durations in the time-sequence as scaled by 1/(timeScale). * * That is, a time-sequence with time-scale 2 will finish twice as * quickly. */ class ROSBAG_DECL TimeTranslator { public: TimeTranslator(); void setTimeScale(double const& s); void setRealStartTime(ros::Time const& t); void setTranslatedStartTime(ros::Time const& t); //!< Increments the translated start time by shift. Useful for pausing. void shift(ros::Duration const& d); //!< Increments the translated start time by shift. Useful for pausing. ros::Time translate(ros::Time const& t); private: double time_scale_; ros::Time real_start_; ros::Time translated_start_; }; } // namespace rosbag #endif
0
apollo_public_repos/apollo-platform/ros/ros_comm/rosbag/include
apollo_public_repos/apollo-platform/ros/ros_comm/rosbag/include/rosbag/player.h
/********************************************************************* * 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. ********************************************************************/ #ifndef ROSBAG_PLAYER_H #define ROSBAG_PLAYER_H #include <sys/stat.h> #if !defined(_MSC_VER) #include <termios.h> #include <unistd.h> #endif #include <time.h> #include <queue> #include <string> #include <ros/ros.h> #include <ros/time.h> #include "rosbag/bag.h" #include "rosbag/time_translator.h" #include "rosbag/macros.h" namespace rosbag { //! Helper function to create AdvertiseOptions from a MessageInstance /*! * param msg The Message instance for which to generate adveritse options * param queue_size The size of the outgoing queue */ ros::AdvertiseOptions createAdvertiseOptions(MessageInstance const& msg, uint32_t queue_size); ROSBAG_DECL ros::AdvertiseOptions createAdvertiseOptions(const ConnectionInfo* c, uint32_t queue_size); struct ROSBAG_DECL PlayerOptions { PlayerOptions(); void check(); std::string prefix; bool quiet; bool start_paused; bool at_once; bool bag_time; double bag_time_frequency; double time_scale; int queue_size; ros::WallDuration advertise_sleep; bool try_future; bool has_time; bool loop; float time; bool has_duration; float duration; bool keep_alive; ros::Duration skip_empty; std::vector<std::string> bags; std::vector<std::string> topics; std::vector<std::string> pause_topics; }; //! PRIVATE. A helper class to track relevant state for publishing time class ROSBAG_DECL TimePublisher { public: /*! Create a time publisher * A publish_frequency of < 0 indicates that time shouldn't actually be published */ TimePublisher(); void setPublishFrequency(double publish_frequency); void setTimeScale(double time_scale); /*! Set the horizon that the clock will run to */ void setHorizon(const ros::Time& horizon); /*! Set the horizon that the clock will run to */ void setWCHorizon(const ros::WallTime& horizon); /*! Set the current time */ void setTime(const ros::Time& time); /*! Get the current time */ ros::Time const& getTime() const; /*! Run the clock for AT MOST duration * * If horizon has been reached this function returns immediately */ void runClock(const ros::WallDuration& duration); //! Sleep as necessary, but don't let the click run void runStalledClock(const ros::WallDuration& duration); //! Step the clock to the horizon void stepClock(); bool horizonReached(); private: bool do_publish_; double publish_frequency_; double time_scale_; ros::NodeHandle node_handle_; ros::Publisher time_pub_; ros::WallDuration wall_step_; ros::WallTime next_pub_; ros::WallTime wc_horizon_; ros::Time horizon_; ros::Time current_; }; //! PRIVATE. Player class to abstract the interface to the player /*! * This API is currently considered private, but will be released in the * future after view. */ class ROSBAG_DECL Player { public: Player(PlayerOptions const& options); ~Player(); void publish(); private: int readCharFromStdin(); void setupTerminal(); void restoreTerminal(); void doPublish(rosbag::MessageInstance const& m); void doKeepAlive(); void printTime(); private: PlayerOptions options_; ros::NodeHandle node_handle_; bool paused_; bool pause_for_topics_; ros::WallTime paused_time_; std::vector<boost::shared_ptr<Bag> > bags_; std::map<std::string, ros::Publisher> publishers_; // Terminal bool terminal_modified_; #if defined(_MSC_VER) HANDLE input_handle; DWORD stdin_set; #else termios orig_flags_; fd_set stdin_fdset_; #endif int maxfd_; TimeTranslator time_translator_; TimePublisher time_publisher_; ros::Time start_time_; ros::Duration bag_length_; }; } // namespace rosbag #endif
0
apollo_public_repos/apollo-platform/ros/ros_comm/rosbag/include
apollo_public_repos/apollo-platform/ros/ros_comm/rosbag/include/rosbag/recorder.h
/********************************************************************* * 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. ********************************************************************/ #ifndef ROSBAG_RECORDER_H #define ROSBAG_RECORDER_H #include <sys/stat.h> #if !defined(_MSC_VER) #include <termios.h> #include <unistd.h> #endif #include <time.h> #include <queue> #include <string> #include <vector> #include <boost/thread/condition.hpp> #include <boost/thread/mutex.hpp> #include <boost/regex.hpp> #include <ros/ros.h> #include <ros/time.h> #include <std_msgs/Empty.h> #include <topic_tools/shape_shifter.h> #include "rosbag/bag.h" #include "rosbag/stream.h" #include "rosbag/macros.h" namespace rosbag { class ROSBAG_DECL OutgoingMessage { public: OutgoingMessage(std::string const& _topic, topic_tools::ShapeShifter::ConstPtr _msg, boost::shared_ptr<ros::M_string> _connection_header, ros::Time _time); std::string topic; topic_tools::ShapeShifter::ConstPtr msg; boost::shared_ptr<ros::M_string> connection_header; ros::Time time; }; class ROSBAG_DECL OutgoingQueue { public: OutgoingQueue(std::string const& _filename, std::queue<OutgoingMessage>* _queue, ros::Time _time); std::string filename; std::queue<OutgoingMessage>* queue; ros::Time time; }; struct ROSBAG_DECL RecorderOptions { RecorderOptions(); bool trigger; bool record_all; bool regex; bool do_exclude; bool quiet; bool append_date; bool snapshot; bool verbose; CompressionType compression; std::string prefix; std::string name; boost::regex exclude_regex; uint32_t buffer_size; uint32_t chunk_size; uint32_t limit; bool split; uint32_t max_size; ros::Duration max_duration; std::string node; unsigned long long min_space; std::string min_space_str; std::vector<std::string> topics; }; struct ROSBAG_DECL envItem { std::string datatype; std::string md5sum; std::string msg_def; }; class ROSBAG_DECL Recorder { public: Recorder(RecorderOptions const& options); void doTrigger(); bool isSubscribed(std::string const& topic) const; boost::shared_ptr<ros::Subscriber> subscribe(std::string const& topic); int run(); private: void printUsage(); void updateFilenames(); void startWriting(); void stopWriting(); bool checkLogging(); bool scheduledCheckDisk(); bool checkDisk(); void snapshotTrigger(std_msgs::Empty::ConstPtr trigger); // void doQueue(topic_tools::ShapeShifter::ConstPtr msg, std::string const& topic, boost::shared_ptr<ros::Subscriber> subscriber, boost::shared_ptr<int> count); void doQueue(const ros::MessageEvent<topic_tools::ShapeShifter const>& msg_event, std::string const& topic, boost::shared_ptr<ros::Subscriber> subscriber, boost::shared_ptr<int> count); void doRecord(); bool checkSize(); bool checkDuration(const ros::Time&); void doRecordSnapshotter(); void doCheckMaster(ros::TimerEvent const& e, ros::NodeHandle& node_handle); bool shouldSubscribeToTopic(std::string const& topic, bool from_node = false); template<class T> static std::string timeToStr(T ros_t); private: RecorderOptions options_; Bag bag_; std::string target_filename_; std::string write_filename_; std::set<std::string> currently_recording_; //!< set of currenly recording topics int num_subscribers_; //!< used for book-keeping of our number of subscribers int exit_code_; //!< eventual exit code boost::condition_variable_any queue_condition_; //!< conditional variable for queue boost::mutex queue_mutex_; //!< mutex for queue std::queue<OutgoingMessage>* queue_; //!< queue for storing uint64_t queue_size_; //!< queue size uint64_t max_queue_size_; //!< max queue size uint64_t split_count_; //!< split count std::queue<OutgoingQueue> queue_queue_; //!< queue of queues to be used by the snapshot recorders ros::Time last_buffer_warn_; ros::Time start_time_; bool writing_enabled_; boost::mutex check_disk_mutex_; ros::WallTime check_disk_next_; ros::WallTime warn_next_; std::map<std::string, envItem> env_info_; }; } // namespace rosbag #endif
0
apollo_public_repos/apollo-platform/ros/ros_comm/rosbag
apollo_public_repos/apollo-platform/ros/ros_comm/rosbag/examples/write.cpp
// Copyright (c) 2010, 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. #include "rosbag/bag.h" #include "std_msgs/String.h" #include "std_msgs/Int32.h" int main() { // %Tag(WRITE)% rosbag::Bag bag; bag.open("test.bag", rosbag::bagmode::Write); std_msgs::String str; str.data = std::string("foo"); std_msgs::Int32 i; i.data = 42; bag.write("chatter", ros::Time::now(), str); bag.write("numbers", ros::Time::now(), i); bag.close(); // %EndTag(WRITE)% }
0
apollo_public_repos/apollo-platform/ros/ros_comm/rosbag
apollo_public_repos/apollo-platform/ros/ros_comm/rosbag/examples/write.py
# Software License Agreement (BSD License) # # Copyright (c) 2012, 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. # %Tag(WRITE_PY)% import rosbag from std_msgs.msg import Int32, String bag = rosbag.Bag('test.bag', 'w') str = String() str.data = 'foo' i = Int32() i.data = 42 bag.write('chatter', str); bag.write('numbers', i); bag.close(); # %EndTag(WRITE_PY)%
0
apollo_public_repos/apollo-platform/ros/ros_comm/rosbag
apollo_public_repos/apollo-platform/ros/ros_comm/rosbag/scripts/bagsort.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. from __future__ import print_function import rospy import rosbag def sortbags(inbag, outbag): rebag = rosbag.Bag(outbag, 'w') try: schedule = [(t, i) for i, (topic, msg, t) in enumerate(rosbag.Bag(inbag).read_messages(raw=True))] schedule = [i for (t, i) in sorted(schedule)] print(schedule) stage = {} for i, (topic, msg, t) in enumerate(rosbag.Bag(inbag).read_messages(raw=True)): stage[i] = (topic, msg, t) while (len(schedule) > 0) and (schedule[0] in stage): (topic, msg, t) = stage[schedule[0]] rebag.write(topic, msg, t, raw=True) del stage[schedule[0]] schedule = schedule[1:] assert schedule == [] assert stage == {} finally: rebag.close() if __name__ == '__main__': import sys if len(sys.argv) == 3: sortbags(sys.argv[1], sys.argv[2]) else: print("usage: bagsort.py <inbag> <outbag>")
0
apollo_public_repos/apollo-platform/ros/ros_comm/rosbag
apollo_public_repos/apollo-platform/ros/ros_comm/rosbag/scripts/savemsg.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. from __future__ import print_function import optparse import sys import roslib.message import rosbag if __name__ == '__main__': parser = optparse.OptionParser(usage='usage: savemsg.py [-b <bagfile] type') parser.add_option('-b', '--bagfiles', action='store', dest='bagfile', default=None, help='Save message from a bagfile rather than system definition') (options, args) = parser.parse_args() if len(args) < 1: parser.error('Message type not specified.') if options.bagfile is None: sys_class = roslib.message.get_message_class(args[0]) if sys_class is None: print('Could not find message %s.' % args[0], file=sys.stderr) else: print('[%s]:' % args[0]) print(sys_class._full_text) else: for topic, msg, t in rosbag.Bag(options.bagfile).read_messages(raw=True): if msg[0] == args[0]: print('[%s]:' % args[0]) print(msg[4]._full_text) exit(0) print('Could not find message %s in bag %s.' % (args[0], options.bagfile), file=sys.stderr)
0
apollo_public_repos/apollo-platform/ros/ros_comm/rosbag
apollo_public_repos/apollo-platform/ros/ros_comm/rosbag/scripts/fastrebag.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. from __future__ import print_function import rosbag def fastrebag(inbag, outbag): rebag = rosbag.Bag(outbag, 'w') for i, (topic, msg, t) in enumerate(rosbag.Bag(inbag).read_messages(raw=True)): rebag.write(topic, msg, t, raw=True) rebag.close() if __name__ == '__main__': import sys if len(sys.argv) == 3: fastrebag(sys.argv[1], sys.argv[2]) else: print('usage: fastrebag.py <inbag> <outbag>')
0
apollo_public_repos/apollo-platform/ros/ros_comm/rosbag
apollo_public_repos/apollo-platform/ros/ros_comm/rosbag/scripts/topic_renamer.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. from __future__ import print_function import rospy import rosbag def rename_topic(intopic, inbag, outtopic, outbag): rebag = rosbag.Bag(outbag, 'w') for topic, msg, t in rosbag.Bag(inbag).read_messages(raw=True): rebag.write(outtopic if topic == intopic else topic, msg, t, raw=True) rebag.close() if __name__ == '__main__': import sys if len(sys.argv) == 5: rename_topic(sys.argv[1], sys.argv[2], sys.argv[3], sys.argv[4]) else: print("usage: topic_renamer.py <intopic> <inbag> <outtopic> <outbag>")
0
apollo_public_repos/apollo-platform/ros/ros_comm/rosbag
apollo_public_repos/apollo-platform/ros/ros_comm/rosbag/scripts/rosbag
#!/usr/bin/env python # 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. import rosbag rosbag.rosbagmain()
0
apollo_public_repos/apollo-platform/ros/ros_comm/rosbag
apollo_public_repos/apollo-platform/ros/ros_comm/rosbag/scripts/fixbag.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. from __future__ import print_function import sys import rosbag.migration if __name__ == '__main__': if len(sys.argv) < 3: print('usage: fixbag.py <inbag> <outbag> [rulefile1, rulefile2, ...]') exit(2) if sys.argv[2].split('.')[-1] == 'bmr': print('Second argument should be a bag, not a rule file.', file=sys.stderr) exit(2) mm = rosbag.migration.MessageMigrator(sys.argv[3:]) if not rosbag.migration.fixbag(mm, sys.argv[1], sys.argv[2]): print('Bag could not be migrated.') exit(1) print('Bag migrated successfully.') exit(0)
0
apollo_public_repos/apollo-platform/ros/ros_comm/rosbag
apollo_public_repos/apollo-platform/ros/ros_comm/rosbag/scripts/bag2png.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. import sys import array import Image import rospy import rosbag def int16_str(d): return array.array('B', [ min(x, 255) for x in d ]).tostring() #return array.array('f', [ float(x) for x in d ]).tostring() def msg2im(msg): """Take an sensor_msgs/Image and return a PIL image""" if len(msg.uint8_data.data) == 0 and len(msg.int16_data.data) == 0: return None if msg.depth == 'uint8': ma, image_data = msg.uint8_data, ma.data else: ma, image_data = msg.int16_data, int16_str(ma.data) dim = dict([(d.label, d.size) for d in ma.layout.dim]) mode = { ('uint8',1) : "L", ('uint8',3) : "RGB", ('int16',1) : "L" }[msg.depth, dim['channel']] (w, h) = (dim['width'], dim['height']) return Image.fromstring(mode, (w, h), image_data) counter = 0 for topic, msg, t in rosbag.Bag(sys.argv[1]).read_messages(): if topic.endswith('stereo/raw_stereo'): for (mi, c) in [ (msg.left_image, 'L'), (msg.right_image, 'R'), (msg.disparity_image, 'D')]: im = msg2im(mi) if im: ext = { 'L':'png', 'RGB':'png', 'F':'tiff' }[im.mode] im.save('%06d%s.%s' % (counter, c, ext)) counter += 1
0
apollo_public_repos/apollo-platform/ros/ros_comm/rosbag
apollo_public_repos/apollo-platform/ros/ros_comm/rosbag/scripts/fixbag_batch.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. from __future__ import print_function import os import sys import rosbag.migration def fixbag_batch(inbags): mm = rosbag.migration.MessageMigrator() for b in inbags: print('Trying to migrate: %s' % b) outbag = b + '.tmp' if not rosbag.migration.fixbag(mm, b, outbag): os.remove(outbag) print(' Migration failed.') continue oldnamebase = b + '.old' oldname = oldnamebase i = 1 while os.path.isfile(oldname): i += 1 oldname = oldnamebase + str(i) os.rename(b, oldname) os.rename(outbag, b) print(' Migration successful. Original stored as: %s' % oldname) if __name__ == '__main__': import sys if len(sys.argv) >= 2: fixbag_batch(sys.argv[1:]) else: print('usage: fixbag_batch.py bag1 [bag2 bag3 ...]') exit(2)
0
apollo_public_repos/apollo-platform/ros/ros_comm/rosbag
apollo_public_repos/apollo-platform/ros/ros_comm/rosbag/scripts/makerule.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. from __future__ import print_function import optparse import os import re import sys import rosbag.migration import genpy.message import genpy.dynamic def print_trans(old, new, indent): from_txt = '%s [%s]' % (old._type, old._md5sum) if new is not None: to_txt= '%s [%s]' % (new._type, new._md5sum) else: to_txt = 'Unknown' print(' ' * indent + ' * From: %s' % from_txt) print(' ' * indent + ' To: %s' % to_txt) if __name__ == '__main__': parser = optparse.OptionParser(usage='usage: makerule.py msg.saved [-a] output_rulefile [rulefile1, rulefile2, ...] [-n]') parser.add_option('-a', '--append', action='store_true', dest='append', default=False) parser.add_option('-n', '--noplugins', action='store_true', dest='noplugins', default=False) (options, args) = parser.parse_args() if len(args) < 2: parser.error("Incorrect number of arguments") rulefile = args[1] if os.path.isfile(rulefile) and not options.append: print("The file %s already exists. Include -a if you intend to append." % rulefile, file=sys.stderr) exit(1) if not os.path.isfile(rulefile) and options.append: print("The file %s does not exist, and so -a is invalid." % rulefile, file=sys.stderr) exit(1) if options.append: append_rule = [rulefile] else: append_rule = [] f = open(args[0]) if f is None: print('Could not open message full definition: %s', file=sys.stderr) sys.exit() type_line = f.readline() pat = re.compile(r"\[(.*)]:") type_match = pat.match(type_line) if type_match is None: print("Full definition file malformed. First line should be: '[my_package/my_msg]:'", file=sys.stderr) sys.exit() old_type = type_match.groups()[0] old_full_text = f.read() f.close() old_class = genpy.dynamic.generate_dynamic(old_type,old_full_text)[old_type] if old_class is None: print('Could not generate class from full definition file.', file=sys.stderr) sys.exit() mm = rosbag.migration.MessageMigrator(args[2:]+append_rule,not options.noplugins) migrations = rosbag.migration.checkmessages(mm, [old_class]) if migrations == []: print('Saved definition is up to date.') exit(0) print('The following migrations need to occur:') all_rules = [] for m in migrations: all_rules.extend(m[1]) print_trans(m[0][0].old_class, m[0][-1].new_class, 0) if len(m[1]) > 0: print(" %d rules missing:" % len(m[1])) for r in m[1]: print_trans(r.old_class, r.new_class, 1) if rulefile is None: print("rulefile not specified") else: output = '' rules_left = mm.filter_rules_unique(all_rules) if rules_left == []: print("\nNo additional rule files needed to be generated. %s not created." % rulefile) exit(0) while rules_left != []: extra_rules = [] for r in rules_left: if r.new_class is None: print("The message type %s appears to have moved. Please enter the type to migrate it to." % r.old_class._type) new_type = raw_input('>') new_class = genpy.message.get_message_class(new_type) while new_class is None: print("\'%s\' could not be found in your system. Please make sure it is built." % new_type) new_type = raw_input('>') new_class = genpy.message.get_message_class(new_type) new_rule = mm.make_update_rule(r.old_class, new_class) R = new_rule(mm, 'GENERATED.' + new_rule.__name__) R.find_sub_paths() new_rules = [r for r in mm.expand_rules(R.sub_rules) if r.valid == False] extra_rules.extend(new_rules) print('Creating the migration rule for %s requires additional missing rules:' % new_type) for nr in new_rules: print_trans(nr.old_class, nr.new_class,1) output += R.get_class_def() else: output += r.get_class_def() rules_left = mm.filter_rules_unique(extra_rules) f = open(rulefile, 'a') f.write(output) f.close() print("\nThe necessary rule files have been written to: %s" % rulefile)
0
apollo_public_repos/apollo-platform/ros/ros_comm/rosbag
apollo_public_repos/apollo-platform/ros/ros_comm/rosbag/scripts/fix_msg_defs.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. from __future__ import print_function import sys import rosbag.migration if __name__ == '__main__': if len(sys.argv) != 3: print('usage: fix_msg_defs.py <inbag> <outbag>') exit(2) mm = rosbag.migration.MessageMigrator() checked = set() migrations = [] inbag = rosbag.Bag(sys.argv[1], 'r') outbag = rosbag.Bag(sys.argv[2], 'w') lookup_cache = {} #msg is: datatype, data, pytype._md5sum, bag_pos, pytype for topic, msg, t in inbag.read_messages(raw=True): if msg[4]._md5sum != msg[2]: k = (msg[0], msg[2]) if k in lookup_cache: real_msg_type = lookup_cache[k] else: real_msg_type = mm.lookup_type(k) if real_msg_type != None: print("FOUND: %s [%s] was defined in migration system\n"%(msg[0], msg[2]), file=sys.stderr) else: systype = roslib.message.get_message_class(msg[0]) if systype != None and systype._md5sum == msg[2]: real_msg_type = systype print("FOUND: %s [%s] was defined on your package path\n"%(msg[0], msg[2]), file=sys.stderr) if real_msg_type == None: real_msg_type = msg[4] print("WARNING: Type [%s] with md5sum [%s] has an unknown definition.\n"%(msg[0], msg[2]), file=sys.stderr) lookup_cache[k] = real_msg_type outbag.write(topic, (msg[0], msg[1], msg[2], msg[3], real_msg_type), t, raw=True) else: outbag.write(topic, msg, t, raw=True) inbag.close() outbag.close() exit(0)
0
apollo_public_repos/apollo-platform/ros/ros_comm/rosbag
apollo_public_repos/apollo-platform/ros/ros_comm/rosbag/scripts/fix_md5sums.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. from __future__ import print_function import os import rospy import rosbag def fix_md5sums(inbags): for b in inbags: print('Trying to migrating file: %s' % b) outbag = b + '.tmp' rebag = rosbag.Bag(outbag, 'w') try: for i,(topic, msg, t) in enumerate(rosbag.Bag(b).read_messages(raw=True)): rebag.write(topic, msg, t, raw=True) rebag.close() except rosbag.ROSBagException as e: print(' Migration failed: %s' % str(e)) os.remove(outbag) continue oldnamebase = b + '.old' oldname = oldnamebase i = 1 while os.path.isfile(oldname): i += 1 oldname = oldnamebase + str(i) os.rename(b, oldname) os.rename(outbag, b) print(' Migration successful. Original stored as: %s' % oldname) if __name__ == '__main__': import sys if len(sys.argv) >= 2: fix_md5sums(sys.argv[1:]) else: print("usage: fix_md5sums.py bag1 [bag2 bag3 ...]")
0
apollo_public_repos/apollo-platform/ros/ros_comm/rosbag
apollo_public_repos/apollo-platform/ros/ros_comm/rosbag/scripts/fix_moved_messages.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. from __future__ import print_function import rospy import rosbag import fileinput def fixbags(md5file, inbag, outbag): d = {} for line in fileinput.input(md5file): sp = line.split() d[sp[1]] = [sp[0], sp[2], sp[3]] rebag = rosbag.Bag(outbag, 'w') for topic, msg, t in rosbag.Bag(inbag).read_messages(raw=True): type, bytes, md5 = msg[0], msg[1], msg[2] if md5 in d: if type != d[md5][0]: print('WARNING: found matching md5, but non-matching name') continue msg = (d[md5][1], msg[1], d[md5][2]) rebag.write(topic, msg, t, raw=True) rebag.close() if __name__ == '__main__': import sys if len(sys.argv) == 4: fixbags(sys.argv[1], sys.argv[2], sys.argv[3]) else: print('usage: fix_moved_messages.py <name_md5_file> <inbag> <outbag>') exit(2)
0
apollo_public_repos/apollo-platform/ros/ros_comm/rosbag
apollo_public_repos/apollo-platform/ros/ros_comm/rosbag/src/time_translator.cpp
/********************************************************************* * Software License Agreement (BSD License) * * Copyright (c) 2010, 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. *********************************************************************/ #include "rosbag/time_translator.h" namespace rosbag { TimeTranslator::TimeTranslator() : time_scale_(1.0), real_start_(ros::TIME_MIN), translated_start_(ros::TIME_MIN) { } void TimeTranslator::setTimeScale(double const& s) { time_scale_ = s; } void TimeTranslator::setRealStartTime(ros::Time const& t) { real_start_ = t; } void TimeTranslator::setTranslatedStartTime(ros::Time const& t) { translated_start_ = t; } void TimeTranslator::shift(ros::Duration const& d) { translated_start_ += d; } ros::Time TimeTranslator::translate(ros::Time const& t) { return translated_start_ + (t - real_start_) * (1.0 / time_scale_); } } // namespace rosbag
0
apollo_public_repos/apollo-platform/ros/ros_comm/rosbag
apollo_public_repos/apollo-platform/ros/ros_comm/rosbag/src/player.cpp
/********************************************************************* * 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. ********************************************************************/ #include "rosbag/player.h" #include "rosbag/message_instance.h" #include "rosbag/view.h" #if !defined(_MSC_VER) #include <sys/select.h> #endif #include <boost/foreach.hpp> #include <boost/format.hpp> #include "rosgraph_msgs/Clock.h" #define foreach BOOST_FOREACH using std::map; using std::pair; using std::string; using std::vector; using boost::shared_ptr; using ros::Exception; namespace rosbag { ros::AdvertiseOptions createAdvertiseOptions(const ConnectionInfo* c, uint32_t queue_size, const std::string& prefix) { ros::AdvertiseOptions opts(prefix + c->topic, queue_size, c->md5sum, c->datatype, c->msg_def); ros::M_string::const_iterator header_iter = c->header->find("latching"); opts.latch = (header_iter != c->header->end() && header_iter->second == "1"); return opts; } ros::AdvertiseOptions createAdvertiseOptions(MessageInstance const& m, uint32_t queue_size, const std::string& prefix) { return ros::AdvertiseOptions(prefix + m.getTopic(), queue_size, m.getMD5Sum(), m.getDataType(), m.getMessageDefinition()); } // PlayerOptions PlayerOptions::PlayerOptions() : prefix(""), quiet(false), start_paused(false), at_once(false), bag_time(false), bag_time_frequency(0.0), time_scale(1.0), queue_size(0), advertise_sleep(0.2), try_future(false), has_time(false), loop(false), time(0.0f), has_duration(false), duration(0.0f), keep_alive(false), skip_empty(ros::DURATION_MAX) { } void PlayerOptions::check() { if (bags.size() == 0) throw Exception("You must specify at least one bag file to play from"); if (has_duration && duration <= 0.0) throw Exception("Invalid duration, must be > 0.0"); } // Player Player::Player(PlayerOptions const& options) : options_(options), paused_(false), // If we were given a list of topics to pause on, then go into that mode // by default (it can be toggled later via 't' from the keyboard). pause_for_topics_(options_.pause_topics.size() > 0), terminal_modified_(false) { } Player::~Player() { foreach(shared_ptr<Bag> bag, bags_) bag->close(); restoreTerminal(); } void Player::publish() { options_.check(); // Open all the bag files foreach(string const& filename, options_.bags) { ROS_INFO("Opening %s", filename.c_str()); try { shared_ptr<Bag> bag(boost::make_shared<Bag>()); bag->open(filename, bagmode::Read); bags_.push_back(bag); } catch (BagUnindexedException ex) { std::cerr << "Bag file " << filename << " is unindexed. Run rosbag reindex." << std::endl; return; } } setupTerminal(); if (!node_handle_.ok()) return; if (!options_.prefix.empty()) { ROS_INFO_STREAM("Using prefix '" << options_.prefix << "'' for topics "); } if (!options_.quiet) puts(""); // Publish all messages in the bags View full_view; foreach(shared_ptr<Bag> bag, bags_) full_view.addQuery(*bag); ros::Time initial_time = full_view.getBeginTime(); initial_time += ros::Duration(options_.time); ros::Time finish_time = ros::TIME_MAX; if (options_.has_duration) { finish_time = initial_time + ros::Duration(options_.duration); } View view; TopicQuery topics(options_.topics); if (options_.topics.empty()) { foreach(shared_ptr<Bag> bag, bags_) view.addQuery(*bag, initial_time, finish_time); } else { foreach(shared_ptr<Bag> bag, bags_) view.addQuery(*bag, topics, initial_time, finish_time); } if (view.size() == 0) { std::cerr << "No messages to play on specified topics. Exiting." << std::endl; ros::shutdown(); return; } // Advertise all of our messages foreach(const ConnectionInfo* c, view.getConnections()) { ros::M_string::const_iterator header_iter = c->header->find("callerid"); std::string callerid = (header_iter != c->header->end() ? header_iter->second : string("")); string callerid_topic = callerid + c->topic; map<string, ros::Publisher>::iterator pub_iter = publishers_.find(callerid_topic); if (pub_iter == publishers_.end()) { ros::AdvertiseOptions opts = createAdvertiseOptions(c, options_.queue_size, options_.prefix); ros::Publisher pub = node_handle_.advertise(opts); publishers_.insert(publishers_.begin(), pair<string, ros::Publisher>(callerid_topic, pub)); pub_iter = publishers_.find(callerid_topic); } } std::cout << "Waiting " << options_.advertise_sleep.toSec() << " seconds after advertising topics..." << std::flush; options_.advertise_sleep.sleep(); std::cout << " done." << std::endl; std::cout << std::endl << "Hit space to toggle paused, or 's' to step." << std::endl; paused_ = options_.start_paused; while (true) { // Set up our time_translator and publishers time_translator_.setTimeScale(options_.time_scale); start_time_ = view.begin()->getTime(); time_translator_.setRealStartTime(start_time_); bag_length_ = view.getEndTime() - view.getBeginTime(); time_publisher_.setTime(start_time_); ros::WallTime now_wt = ros::WallTime::now(); time_translator_.setTranslatedStartTime(ros::Time(now_wt.sec, now_wt.nsec)); time_publisher_.setTimeScale(options_.time_scale); if (options_.bag_time) time_publisher_.setPublishFrequency(options_.bag_time_frequency); else time_publisher_.setPublishFrequency(-1.0); paused_time_ = now_wt; // Call do-publish for each message foreach(MessageInstance m, view) { if (!node_handle_.ok()) break; doPublish(m); } if (options_.keep_alive) while (node_handle_.ok()) doKeepAlive(); if (!node_handle_.ok()) { std::cout << std::endl; break; } if (!options_.loop) { std::cout << std::endl << "Done." << std::endl; break; } } ros::shutdown(); } void Player::printTime() { if (!options_.quiet) { ros::Time current_time = time_publisher_.getTime(); ros::Duration d = current_time - start_time_; if (paused_) { printf("\r [PAUSED] Bag Time: %13.6f Duration: %.6f / %.6f \r", time_publisher_.getTime().toSec(), d.toSec(), bag_length_.toSec()); } else { printf("\r [RUNNING] Bag Time: %13.6f Duration: %.6f / %.6f \r", time_publisher_.getTime().toSec(), d.toSec(), bag_length_.toSec()); } fflush(stdout); } } void Player::doPublish(MessageInstance const& m) { string const& topic = m.getTopic(); ros::Time const& time = m.getTime(); string callerid = m.getCallerId(); ros::Time translated = time_translator_.translate(time); ros::WallTime horizon = ros::WallTime(translated.sec, translated.nsec); time_publisher_.setHorizon(time); time_publisher_.setWCHorizon(horizon); string callerid_topic = callerid + topic; map<string, ros::Publisher>::iterator pub_iter = publishers_.find(callerid_topic); ROS_ASSERT(pub_iter != publishers_.end()); // If immediate specified, play immediately if (options_.at_once) { time_publisher_.stepClock(); pub_iter->second.publish(m); printTime(); return; } // If skip_empty is specified, skip this region and shift. if (time - time_publisher_.getTime() > options_.skip_empty) { time_publisher_.stepClock(); ros::WallDuration shift = ros::WallTime::now() - horizon ; time_translator_.shift(ros::Duration(shift.sec, shift.nsec)); horizon += shift; time_publisher_.setWCHorizon(horizon); (pub_iter->second).publish(m); printTime(); return; } if (pause_for_topics_) { for (std::vector<std::string>::iterator i = options_.pause_topics.begin(); i != options_.pause_topics.end(); ++i) { if (topic == *i) { paused_ = true; paused_time_ = ros::WallTime::now(); } } } while ((paused_ || !time_publisher_.horizonReached()) && node_handle_.ok()) { bool charsleftorpaused = true; while (charsleftorpaused && node_handle_.ok()) { switch (readCharFromStdin()){ case ' ': paused_ = !paused_; if (paused_) { paused_time_ = ros::WallTime::now(); } else { ros::WallDuration shift = ros::WallTime::now() - paused_time_; paused_time_ = ros::WallTime::now(); time_translator_.shift(ros::Duration(shift.sec, shift.nsec)); horizon += shift; time_publisher_.setWCHorizon(horizon); } break; case 's': if (paused_) { time_publisher_.stepClock(); ros::WallDuration shift = ros::WallTime::now() - horizon ; paused_time_ = ros::WallTime::now(); time_translator_.shift(ros::Duration(shift.sec, shift.nsec)); horizon += shift; time_publisher_.setWCHorizon(horizon); (pub_iter->second).publish(m); printTime(); return; } break; case 't': pause_for_topics_ = !pause_for_topics_; break; case EOF: if (paused_) { printTime(); time_publisher_.runStalledClock(ros::WallDuration(.1)); } else charsleftorpaused = false; } } printTime(); time_publisher_.runClock(ros::WallDuration(.1)); } pub_iter->second.publish(m); } void Player::doKeepAlive() { //Keep pushing ourself out in 10-sec increments (avoids fancy math dealing with the end of time) ros::Time const& time = time_publisher_.getTime() + ros::Duration(10.0); ros::Time translated = time_translator_.translate(time); ros::WallTime horizon = ros::WallTime(translated.sec, translated.nsec); time_publisher_.setHorizon(time); time_publisher_.setWCHorizon(horizon); if (options_.at_once) { return; } while ((paused_ || !time_publisher_.horizonReached()) && node_handle_.ok()) { bool charsleftorpaused = true; while (charsleftorpaused && node_handle_.ok()) { switch (readCharFromStdin()){ case ' ': paused_ = !paused_; if (paused_) { paused_time_ = ros::WallTime::now(); } else { ros::WallDuration shift = ros::WallTime::now() - paused_time_; paused_time_ = ros::WallTime::now(); time_translator_.shift(ros::Duration(shift.sec, shift.nsec)); horizon += shift; time_publisher_.setWCHorizon(horizon); } break; case EOF: if (paused_) { printTime(); time_publisher_.runStalledClock(ros::WallDuration(.1)); } else charsleftorpaused = false; } } printTime(); time_publisher_.runClock(ros::WallDuration(.1)); } } void Player::setupTerminal() { if (terminal_modified_) return; #if defined(_MSC_VER) input_handle = GetStdHandle(STD_INPUT_HANDLE); if (input_handle == INVALID_HANDLE_VALUE) { std::cout << "Failed to set up standard input handle." << std::endl; return; } if (! GetConsoleMode(input_handle, &stdin_set) ) { std::cout << "Failed to save the console mode." << std::endl; return; } // don't actually need anything but the default, alternatively try this //DWORD event_mode = ENABLE_WINDOW_INPUT | ENABLE_MOUSE_INPUT; //if (! SetConsoleMode(input_handle, event_mode) ) //{ // std::cout << "Failed to set the console mode." << std::endl; // return; //} terminal_modified_ = true; #else const int fd = fileno(stdin); termios flags; tcgetattr(fd, &orig_flags_); flags = orig_flags_; flags.c_lflag &= ~ICANON; // set raw (unset canonical modes) flags.c_cc[VMIN] = 0; // i.e. min 1 char for blocking, 0 chars for non-blocking flags.c_cc[VTIME] = 0; // block if waiting for char tcsetattr(fd, TCSANOW, &flags); FD_ZERO(&stdin_fdset_); FD_SET(fd, &stdin_fdset_); maxfd_ = fd + 1; terminal_modified_ = true; #endif } void Player::restoreTerminal() { if (!terminal_modified_) return; #if defined(_MSC_VER) SetConsoleMode(input_handle, stdin_set); #else const int fd = fileno(stdin); tcsetattr(fd, TCSANOW, &orig_flags_); #endif terminal_modified_ = false; } int Player::readCharFromStdin() { #ifdef __APPLE__ fd_set testfd; FD_COPY(&stdin_fdset_, &testfd); #elif !defined(_MSC_VER) fd_set testfd = stdin_fdset_; #endif #if defined(_MSC_VER) DWORD events = 0; INPUT_RECORD input_record[1]; DWORD input_size = 1; BOOL b = GetNumberOfConsoleInputEvents(input_handle, &events); if (b && events > 0) { b = ReadConsoleInput(input_handle, input_record, input_size, &events); if (b) { for (unsigned int i = 0; i < events; ++i) { if (input_record[i].EventType & KEY_EVENT & input_record[i].Event.KeyEvent.bKeyDown) { CHAR ch = input_record[i].Event.KeyEvent.uChar.AsciiChar; return ch; } } } } return EOF; #else timeval tv; tv.tv_sec = 0; tv.tv_usec = 0; if (select(maxfd_, &testfd, NULL, NULL, &tv) <= 0) return EOF; return getc(stdin); #endif } TimePublisher::TimePublisher() : time_scale_(1.0) { setPublishFrequency(-1.0); time_pub_ = node_handle_.advertise<rosgraph_msgs::Clock>("clock",1); } void TimePublisher::setPublishFrequency(double publish_frequency) { publish_frequency_ = publish_frequency; do_publish_ = (publish_frequency > 0.0); wall_step_.fromSec(1.0 / publish_frequency); } void TimePublisher::setTimeScale(double time_scale) { time_scale_ = time_scale; } void TimePublisher::setHorizon(const ros::Time& horizon) { horizon_ = horizon; } void TimePublisher::setWCHorizon(const ros::WallTime& horizon) { wc_horizon_ = horizon; } void TimePublisher::setTime(const ros::Time& time) { current_ = time; } ros::Time const& TimePublisher::getTime() const { return current_; } void TimePublisher::runClock(const ros::WallDuration& duration) { if (do_publish_) { rosgraph_msgs::Clock pub_msg; ros::WallTime t = ros::WallTime::now(); ros::WallTime done = t + duration; while (t < done && t < wc_horizon_) { ros::WallDuration leftHorizonWC = wc_horizon_ - t; ros::Duration d(leftHorizonWC.sec, leftHorizonWC.nsec); d *= time_scale_; current_ = horizon_ - d; if (current_ >= horizon_) current_ = horizon_; if (t >= next_pub_) { pub_msg.clock = current_; time_pub_.publish(pub_msg); next_pub_ = t + wall_step_; } ros::WallTime target = done; if (target > wc_horizon_) target = wc_horizon_; if (target > next_pub_) target = next_pub_; ros::WallTime::sleepUntil(target); t = ros::WallTime::now(); } } else { ros::WallTime t = ros::WallTime::now(); ros::WallDuration leftHorizonWC = wc_horizon_ - t; ros::Duration d(leftHorizonWC.sec, leftHorizonWC.nsec); d *= time_scale_; current_ = horizon_ - d; if (current_ >= horizon_) current_ = horizon_; ros::WallTime target = ros::WallTime::now() + duration; if (target > wc_horizon_) target = wc_horizon_; ros::WallTime::sleepUntil(target); } } void TimePublisher::stepClock() { if (do_publish_) { current_ = horizon_; rosgraph_msgs::Clock pub_msg; pub_msg.clock = current_; time_pub_.publish(pub_msg); ros::WallTime t = ros::WallTime::now(); next_pub_ = t + wall_step_; } else { current_ = horizon_; } } void TimePublisher::runStalledClock(const ros::WallDuration& duration) { if (do_publish_) { rosgraph_msgs::Clock pub_msg; ros::WallTime t = ros::WallTime::now(); ros::WallTime done = t + duration; while ( t < done ) { if (t > next_pub_) { pub_msg.clock = current_; time_pub_.publish(pub_msg); next_pub_ = t + wall_step_; } ros::WallTime target = done; if (target > next_pub_) target = next_pub_; ros::WallTime::sleepUntil(target); t = ros::WallTime::now(); } } else { duration.sleep(); } } bool TimePublisher::horizonReached() { return ros::WallTime::now() > wc_horizon_; } } // namespace rosbag
0
apollo_public_repos/apollo-platform/ros/ros_comm/rosbag
apollo_public_repos/apollo-platform/ros/ros_comm/rosbag/src/play.cpp
/********************************************************************* * 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. ********************************************************************/ #include "rosbag/player.h" #include "boost/program_options.hpp" namespace po = boost::program_options; rosbag::PlayerOptions parseOptions(int argc, char** argv) { rosbag::PlayerOptions opts; po::options_description desc("Allowed options"); desc.add_options() ("help,h", "produce help message") ("prefix,p", po::value<std::string>()->default_value(""), "prefixes all output topics in replay") ("quiet,q", "suppress console output") ("immediate,i", "play back all messages without waiting") ("pause", "start in paused mode") ("queue", po::value<int>()->default_value(100), "use an outgoing queue of size SIZE") ("clock", "publish the clock time") ("hz", po::value<float>()->default_value(100.0f), "use a frequency of HZ when publishing clock time") ("delay,d", po::value<float>()->default_value(0.2f), "sleep SEC seconds after every advertise call (to allow subscribers to connect)") ("rate,r", po::value<float>()->default_value(1.0f), "multiply the publish rate by FACTOR") ("start,s", po::value<float>()->default_value(0.0f), "start SEC seconds into the bag files") ("duration,u", po::value<float>(), "play only SEC seconds from the bag files") ("skip-empty", po::value<float>(), "skip regions in the bag with no messages for more than SEC seconds") ("loop,l", "loop playback") ("keep-alive,k", "keep alive past end of bag (useful for publishing latched topics)") ("try-future-version", "still try to open a bag file, even if the version is not known to the player") ("topics", po::value< std::vector<std::string> >()->multitoken(), "topics to play back") ("pause-topics", po::value< std::vector<std::string> >()->multitoken(), "topics to pause playback on") ("bags", po::value< std::vector<std::string> >(), "bag files to play back from"); po::positional_options_description p; p.add("bags", -1); po::variables_map vm; try { po::store(po::command_line_parser(argc, argv).options(desc).positional(p).run(), vm); } catch (boost::program_options::invalid_command_line_syntax& e) { throw ros::Exception(e.what()); } catch (boost::program_options::unknown_option& e) { throw ros::Exception(e.what()); } if (vm.count("help")) { std::cout << desc << std::endl; exit(0); } if (vm.count("prefix")) opts.prefix = vm["prefix"].as<std::string>(); if (vm.count("quiet")) opts.quiet = true; if (vm.count("immediate")) opts.at_once = true; if (vm.count("pause")) opts.start_paused = true; if (vm.count("queue")) opts.queue_size = vm["queue"].as<int>(); if (vm.count("hz")) opts.bag_time_frequency = vm["hz"].as<float>(); if (vm.count("clock")) opts.bag_time = true; if (vm.count("delay")) opts.advertise_sleep = ros::WallDuration(vm["delay"].as<float>()); if (vm.count("rate")) opts.time_scale = vm["rate"].as<float>(); if (vm.count("start")) { opts.time = vm["start"].as<float>(); opts.has_time = true; } if (vm.count("duration")) { opts.duration = vm["duration"].as<float>(); opts.has_duration = true; } if (vm.count("skip-empty")) opts.skip_empty = ros::Duration(vm["skip-empty"].as<float>()); if (vm.count("loop")) opts.loop = true; if (vm.count("keep-alive")) opts.keep_alive = true; if (vm.count("topics")) { std::vector<std::string> topics = vm["topics"].as< std::vector<std::string> >(); for (std::vector<std::string>::iterator i = topics.begin(); i != topics.end(); i++) opts.topics.push_back(*i); } if (vm.count("pause-topics")) { std::vector<std::string> pause_topics = vm["pause-topics"].as< std::vector<std::string> >(); for (std::vector<std::string>::iterator i = pause_topics.begin(); i != pause_topics.end(); i++) opts.pause_topics.push_back(*i); } if (vm.count("bags")) { std::vector<std::string> bags = vm["bags"].as< std::vector<std::string> >(); for (std::vector<std::string>::iterator i = bags.begin(); i != bags.end(); i++) opts.bags.push_back(*i); } else { if (vm.count("topics") || vm.count("pause-topics")) throw ros::Exception("When using --topics or --pause-topics, --bags " "should be specified to list bags."); throw ros::Exception("You must specify at least one bag to play back."); } return opts; } int main(int argc, char** argv) { ros::init(argc, argv, "play", ros::init_options::AnonymousName); // Parse the command-line options rosbag::PlayerOptions opts; try { opts = parseOptions(argc, argv); } catch (ros::Exception const& ex) { ROS_ERROR("Error reading options: %s", ex.what()); return 1; } rosbag::Player player(opts); try { player.publish(); } catch (std::runtime_error& e) { ROS_FATAL("%s", e.what()); return 1; } return 0; }
0
apollo_public_repos/apollo-platform/ros/ros_comm/rosbag
apollo_public_repos/apollo-platform/ros/ros_comm/rosbag/src/record.cpp
/********************************************************************* * 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. ********************************************************************/ #include "rosbag/recorder.h" #include "rosbag/exceptions.h" #include "boost/program_options.hpp" #include <string> #include <sstream> namespace po = boost::program_options; //! Parse the command-line arguments for recorder options rosbag::RecorderOptions parseOptions(int argc, char** argv) { rosbag::RecorderOptions opts; po::options_description desc("Allowed options"); desc.add_options() ("help,h", "produce help message") ("all,a", "record all topics") ("regex,e", "match topics using regular expressions") ("exclude,x", po::value<std::string>(), "exclude topics matching regular expressions") ("quiet,q", "suppress console output") ("output-prefix,o", po::value<std::string>(), "prepend PREFIX to beginning of bag name") ("output-name,O", po::value<std::string>(), "record bagnamed NAME.bag") ("buffsize,b", po::value<int>()->default_value(256), "Use an internal buffer of SIZE MB (Default: 256)") ("chunksize", po::value<int>()->default_value(768), "Set chunk size of message data, in KB (Default: 768. Advanced)") ("limit,l", po::value<int>()->default_value(0), "Only record NUM messages on each topic") ("min-space,L", po::value<std::string>()->default_value("1G"), "Minimum allowed space on recording device (use G,M,k multipliers)") ("bz2,j", "use BZ2 compression") ("lz4", "use LZ4 compression") ("split", po::value<int>()->implicit_value(0), "Split the bag file and continue recording when maximum size or maximum duration reached.") ("topic", po::value< std::vector<std::string> >(), "topic to record") ("size", po::value<int>(), "The maximum size of the bag to record in MB.") ("duration", po::value<std::string>(), "Record a bag of maximum duration in seconds, unless 'm', or 'h' is appended.") ("node", po::value<std::string>(), "Record all topics subscribed to by a specific node."); po::positional_options_description p; p.add("topic", -1); po::variables_map vm; try { po::store(po::command_line_parser(argc, argv).options(desc).positional(p).run(), vm); } catch (boost::program_options::invalid_command_line_syntax& e) { throw ros::Exception(e.what()); } catch (boost::program_options::unknown_option& e) { throw ros::Exception(e.what()); } if (vm.count("help")) { std::cout << desc << std::endl; exit(0); } if (vm.count("all")) opts.record_all = true; if (vm.count("regex")) opts.regex = true; if (vm.count("exclude")) { opts.do_exclude = true; opts.exclude_regex = vm["exclude"].as<std::string>(); } if (vm.count("quiet")) opts.quiet = true; if (vm.count("output-prefix")) { opts.prefix = vm["output-prefix"].as<std::string>(); opts.append_date = true; } if (vm.count("output-name")) { opts.prefix = vm["output-name"].as<std::string>(); opts.append_date = false; } if (vm.count("split")) { opts.split = true; int S = vm["split"].as<int>(); if (S != 0) { ROS_WARN("Use of \"--split <MAX_SIZE>\" has been deprecated. Please use --split --size <MAX_SIZE> or --split --duration <MAX_DURATION>"); if (S < 0) throw ros::Exception("Split size must be 0 or positive"); opts.max_size = 1048576 * S; } } if (vm.count("buffsize")) { int m = vm["buffsize"].as<int>(); if (m < 0) throw ros::Exception("Buffer size must be 0 or positive"); opts.buffer_size = 1048576 * m; } if (vm.count("chunksize")) { int chnk_sz = vm["chunksize"].as<int>(); if (chnk_sz < 0) throw ros::Exception("Chunk size must be 0 or positive"); opts.chunk_size = 1024 * chnk_sz; } if (vm.count("limit")) { opts.limit = vm["limit"].as<int>(); } if (vm.count("min-space")) { std::string ms = vm["min-space"].as<std::string>(); long long int value = 1073741824ull; char mul = 0; // Sane default values, just in case opts.min_space_str = "1G"; opts.min_space = value; if (sscanf(ms.c_str(), " %lld%c", &value, &mul) > 0) { opts.min_space_str = ms; switch (mul) { case 'G': case 'g': opts.min_space = value * 1073741824ull; break; case 'M': case 'm': opts.min_space = value * 1048576ull; break; case 'K': case 'k': opts.min_space = value * 1024ull; break; default: opts.min_space = value; break; } } ROS_DEBUG("Rosbag using minimum space of %lld bytes, or %s", opts.min_space, opts.min_space_str.c_str()); } if (vm.count("bz2") && vm.count("lz4")) { throw ros::Exception("Can only use one type of compression"); } if (vm.count("bz2")) { opts.compression = rosbag::compression::BZ2; } if (vm.count("lz4")) { opts.compression = rosbag::compression::LZ4; } if (vm.count("duration")) { std::string duration_str = vm["duration"].as<std::string>(); double duration; double multiplier = 1.0; std::string unit(""); std::istringstream iss(duration_str); if ((iss >> duration).fail()) throw ros::Exception("Duration must start with a floating point number."); if ( (!iss.eof() && ((iss >> unit).fail())) ) { throw ros::Exception("Duration unit must be s, m, or h"); } if (unit == std::string("")) multiplier = 1.0; else if (unit == std::string("s")) multiplier = 1.0; else if (unit == std::string("m")) multiplier = 60.0; else if (unit == std::string("h")) multiplier = 3600.0; else throw ros::Exception("Duration unit must be s, m, or h"); opts.max_duration = ros::Duration(duration * multiplier); if (opts.max_duration <= ros::Duration(0)) throw ros::Exception("Duration must be positive."); } if (vm.count("size")) { opts.max_size = vm["size"].as<int>() * 1048576; if (opts.max_size <= 0) throw ros::Exception("Split size must be 0 or positive"); } if (vm.count("node")) { opts.node = vm["node"].as<std::string>(); std::cout << "Recording from: " << opts.node << std::endl; } // Every non-option argument is assumed to be a topic if (vm.count("topic")) { std::vector<std::string> bags = vm["topic"].as< std::vector<std::string> >(); std::sort(bags.begin(), bags.end()); bags.erase(std::unique(bags.begin(), bags.end()), bags.end()); for (std::vector<std::string>::iterator i = bags.begin(); i != bags.end(); i++) opts.topics.push_back(*i); } // check that argument combinations make sense if(opts.exclude_regex.size() > 0 && !(opts.record_all || opts.regex)) { fprintf(stderr, "Warning: Exclusion regex given, but no topics to subscribe to.\n" "Adding implicit 'record all'."); opts.record_all = true; } return opts; } int main(int argc, char** argv) { ros::init(argc, argv, "record", ros::init_options::AnonymousName); // Parse the command-line options rosbag::RecorderOptions opts; try { opts = parseOptions(argc, argv); } catch (ros::Exception const& ex) { ROS_ERROR("Error reading options: %s", ex.what()); return 1; } catch(boost::regex_error const& ex) { ROS_ERROR("Error reading options: %s\n", ex.what()); return 1; } // Run the recorder rosbag::Recorder recorder(opts); int result = recorder.run(); return result; }
0
apollo_public_repos/apollo-platform/ros/ros_comm/rosbag
apollo_public_repos/apollo-platform/ros/ros_comm/rosbag/src/recorder.cpp
/********************************************************************* * 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. ********************************************************************/ #include "rosbag/recorder.h" #include <sys/stat.h> #include <boost/filesystem.hpp> // Boost filesystem v3 is default in 1.46.0 and above // Fallback to original posix code (*nix only) if this is not true #if BOOST_FILESYSTEM_VERSION < 3 #include <sys/statvfs.h> #endif #include <time.h> #include <queue> #include <set> #include <sstream> #include <string> #include <boost/foreach.hpp> #include <boost/lexical_cast.hpp> #include <boost/regex.hpp> #include <boost/thread.hpp> #include <boost/thread/xtime.hpp> #include <boost/date_time/local_time/local_time.hpp> #include <ros/ros.h> #include <topic_tools/shape_shifter.h> #include "ros/network.h" #include "ros/broadcast_manager.h" #include "ros/xmlrpc_manager.h" #include "XmlRpc.h" #define foreach BOOST_FOREACH using std::cout; using std::endl; using std::set; using std::string; using std::vector; using boost::shared_ptr; using ros::Time; namespace rosbag { // OutgoingMessage OutgoingMessage::OutgoingMessage(string const& _topic, topic_tools::ShapeShifter::ConstPtr _msg, boost::shared_ptr<ros::M_string> _connection_header, Time _time) : topic(_topic), msg(_msg), connection_header(_connection_header), time(_time) { } // OutgoingQueue OutgoingQueue::OutgoingQueue(string const& _filename, std::queue<OutgoingMessage>* _queue, Time _time) : filename(_filename), queue(_queue), time(_time) { } // RecorderOptions RecorderOptions::RecorderOptions() : trigger(false), record_all(false), regex(false), do_exclude(false), quiet(false), append_date(true), snapshot(false), verbose(false), compression(compression::Uncompressed), prefix(""), name(""), exclude_regex(), buffer_size(1048576 * 256), chunk_size(1024 * 768), limit(0), split(false), max_size(0), max_duration(-1.0), node(""), min_space(1024 * 1024 * 1024), min_space_str("1G") { } // Recorder Recorder::Recorder(RecorderOptions const& options) : options_(options), num_subscribers_(0), exit_code_(0), queue_size_(0), split_count_(0), writing_enabled_(true) { } int Recorder::run() { if (options_.trigger) { doTrigger(); return 0; } if (options_.topics.size() == 0) { // Make sure limit is not specified with automatic topic subscription if (options_.limit > 0) { fprintf(stderr, "Specifing a count is not valid with automatic topic subscription.\n"); return 1; } // Make sure topics are specified if (!options_.record_all && (options_.node == std::string(""))) { fprintf(stderr, "No topics specified.\n"); return 1; } } ros::NodeHandle nh; if (!nh.ok()) return 0; last_buffer_warn_ = Time(); queue_ = new std::queue<OutgoingMessage>; // Subscribe to each topic if (!options_.regex) { foreach(string const& topic, options_.topics) subscribe(topic); } if (!ros::Time::waitForValid(ros::WallDuration(2.0))) ROS_WARN("/use_sim_time set to true and no clock published. Still waiting for valid time..."); ros::Time::waitForValid(); start_time_ = ros::Time::now(); // Don't bother doing anything if we never got a valid time if (!nh.ok()) return 0; ros::Subscriber trigger_sub; // Spin up a thread for writing to the file boost::thread record_thread; if (options_.snapshot) { record_thread = boost::thread(boost::bind(&Recorder::doRecordSnapshotter, this)); // Subscribe to the snapshot trigger trigger_sub = nh.subscribe<std_msgs::Empty>("snapshot_trigger", 100, boost::bind(&Recorder::snapshotTrigger, this, _1)); } else record_thread = boost::thread(boost::bind(&Recorder::doRecord, this)); ros::Timer check_master_timer; if (options_.record_all || options_.regex || (options_.node != std::string(""))) { // check for master first doCheckMaster(ros::TimerEvent(), nh); check_master_timer = nh.createTimer(ros::Duration(1.0), boost::bind(&Recorder::doCheckMaster, this, _1, boost::ref(nh))); } ros::MultiThreadedSpinner s(10); ros::spin(s); queue_condition_.notify_all(); record_thread.join(); delete queue_; return exit_code_; } shared_ptr<ros::Subscriber> Recorder::subscribe(string const& topic) { ROS_INFO("Subscribing to %s", topic.c_str()); ros::NodeHandle nh; shared_ptr<int> count(boost::make_shared<int>(options_.limit)); shared_ptr<ros::Subscriber> sub(boost::make_shared<ros::Subscriber>()); ros::SubscribeOptions ops; ops.topic = topic; ops.queue_size = 100; ops.md5sum = ros::message_traits::md5sum<topic_tools::ShapeShifter>(); ops.datatype = ros::message_traits::datatype<topic_tools::ShapeShifter>(); ops.helper = boost::make_shared<ros::SubscriptionCallbackHelperT< const ros::MessageEvent<topic_tools::ShapeShifter const> &> >( boost::bind(&Recorder::doQueue, this, _1, topic, sub, count)); *sub = nh.subscribe(ops); currently_recording_.insert(topic); num_subscribers_++; return sub; } bool Recorder::isSubscribed(string const& topic) const { return currently_recording_.find(topic) != currently_recording_.end(); } bool Recorder::shouldSubscribeToTopic(std::string const& topic, bool from_node) { // ignore already known topics if (isSubscribed(topic)) { return false; } // subtract exclusion regex, if any if(options_.do_exclude && boost::regex_match(topic, options_.exclude_regex)) { return false; } if(options_.record_all || from_node) { return true; } if (options_.regex) { // Treat the topics as regular expressions foreach(string const& regex_str, options_.topics) { boost::regex e(regex_str); boost::smatch what; if (boost::regex_match(topic, what, e, boost::match_extra)) return true; } } else { foreach(string const& t, options_.topics) if (t == topic) return true; } return false; } template<class T> std::string Recorder::timeToStr(T ros_t) { (void)ros_t; std::stringstream msg; const boost::posix_time::ptime now= boost::posix_time::second_clock::local_time(); boost::posix_time::time_facet *const f= new boost::posix_time::time_facet("%Y-%m-%d-%H-%M-%S"); msg.imbue(std::locale(msg.getloc(),f)); msg << now; return msg.str(); } //! Callback to be invoked to save messages into a queue void Recorder::doQueue(const ros::MessageEvent<topic_tools::ShapeShifter const>& msg_event, string const& topic, shared_ptr<ros::Subscriber> subscriber, shared_ptr<int> count) { //void Recorder::doQueue(topic_tools::ShapeShifter::ConstPtr msg, string const& topic, shared_ptr<ros::Subscriber> subscriber, shared_ptr<int> count) { Time rectime = Time::now(); if (options_.verbose) cout << "Received message on topic " << subscriber->getTopic() << endl; OutgoingMessage out(topic, msg_event.getMessage(), msg_event.getConnectionHeaderPtr(), rectime); { boost::mutex::scoped_lock lock(queue_mutex_); queue_->push(out); queue_size_ += out.msg->size(); // Check to see if buffer has been exceeded while (options_.buffer_size > 0 && queue_size_ > options_.buffer_size) { OutgoingMessage drop = queue_->front(); queue_->pop(); queue_size_ -= drop.msg->size(); if (!options_.snapshot) { Time now = Time::now(); if (now > last_buffer_warn_ + ros::Duration(5.0)) { ROS_WARN("rosbag record buffer exceeded. Dropping oldest queued message."); last_buffer_warn_ = now; } } } } if (!options_.snapshot) queue_condition_.notify_all(); // If we are book-keeping count, decrement and possibly shutdown if ((*count) > 0) { (*count)--; if ((*count) == 0) { subscriber->shutdown(); num_subscribers_--; if (num_subscribers_ == 0) ros::shutdown(); } } } void Recorder::updateFilenames() { vector<string> parts; std::string prefix = options_.prefix; size_t ind = prefix.rfind(".bag"); if (ind != std::string::npos && ind == prefix.size() - 4) { prefix.erase(ind); } if (prefix.length() > 0) parts.push_back(prefix); if (options_.append_date) parts.push_back(timeToStr(ros::WallTime::now())); if (options_.split) parts.push_back(boost::lexical_cast<string>(split_count_)); if (parts.size() == 0) { throw BagException("Bag filename is empty (neither of these was specified: prefix, append_date, split)"); } target_filename_ = parts[0]; for (unsigned int i = 1; i < parts.size(); i++) target_filename_ += string("_") + parts[i]; target_filename_ += string(".bag"); write_filename_ = target_filename_ + string(".active"); } //! Callback to be invoked to actually do the recording void Recorder::snapshotTrigger(std_msgs::Empty::ConstPtr trigger) { (void)trigger; updateFilenames(); ROS_INFO("Triggered snapshot recording with name %s.", target_filename_.c_str()); { boost::mutex::scoped_lock lock(queue_mutex_); queue_queue_.push(OutgoingQueue(target_filename_, queue_, Time::now())); queue_ = new std::queue<OutgoingMessage>; queue_size_ = 0; } queue_condition_.notify_all(); } void Recorder::startWriting() { bag_.setCompression(options_.compression); bag_.setChunkThreshold(options_.chunk_size); updateFilenames(); try { bag_.open(write_filename_, bagmode::Write); } catch (rosbag::BagException e) { ROS_ERROR("Error writing: %s", e.what()); exit_code_ = 1; ros::shutdown(); } ROS_INFO("Recording to %s.", target_filename_.c_str()); } void Recorder::stopWriting() { ROS_INFO("Closing %s.", target_filename_.c_str()); bag_.close(); rename(write_filename_.c_str(), target_filename_.c_str()); } bool Recorder::checkSize() { if (options_.max_size > 0) { if (bag_.getSize() > options_.max_size) { if (options_.split) { stopWriting(); split_count_++; startWriting(); } else { ros::shutdown(); return true; } } } return false; } bool Recorder::checkDuration(const ros::Time& t) { if (options_.max_duration > ros::Duration(0)) { if (t - start_time_ > options_.max_duration) { if (options_.split) { while (start_time_ + options_.max_duration < t) { stopWriting(); split_count_++; start_time_ += options_.max_duration; startWriting(); } } else { ros::shutdown(); return true; } } } return false; } //! Thread that actually does writing to file. void Recorder::doRecord() { // Open bag file for writing startWriting(); // Schedule the disk space check warn_next_ = ros::WallTime(); checkDisk(); check_disk_next_ = ros::WallTime::now() + ros::WallDuration().fromSec(20.0); // Technically the queue_mutex_ should be locked while checking empty. // Except it should only get checked if the node is not ok, and thus // it shouldn't be in contention. ros::NodeHandle nh; while (nh.ok() || !queue_->empty()) { boost::unique_lock<boost::mutex> lock(queue_mutex_); bool finished = false; while (queue_->empty()) { if (!nh.ok()) { lock.release()->unlock(); finished = true; break; } boost::xtime xt; #if BOOST_VERSION >= 105000 boost::xtime_get(&xt, boost::TIME_UTC_); #else boost::xtime_get(&xt, boost::TIME_UTC); #endif xt.nsec += 250000000; queue_condition_.timed_wait(lock, xt); if (checkDuration(ros::Time::now())) { finished = true; break; } } if (finished) break; OutgoingMessage out = queue_->front(); queue_->pop(); queue_size_ -= out.msg->size(); lock.release()->unlock(); if (checkSize()) break; if (checkDuration(out.time)) break; if (scheduledCheckDisk() && checkLogging()) { if (std::string(ros::message_traits::datatype(*out.msg)) == "*") { std::map<std::string, envItem>::iterator i = env_info_.find(out.topic); if (i != env_info_.end()) { bag_.write(out.topic, out.time, *out.msg, out.connection_header, i->second.datatype, i->second.md5sum, i->second.msg_def); continue; } else { boost::shared_ptr<sharedmem_transport::SharedMemoryUtil> util(new sharedmem_transport::SharedMemoryUtil()); boost::interprocess::managed_shared_memory* segment = util->get_segment(out.topic.c_str()); if (segment != NULL) { envItem env_item; env_item.datatype = util->get_datatype(segment); env_item.md5sum = util->get_md5sum(segment); env_item.msg_def = util->get_msg_def(segment); env_info_.insert(make_pair(out.topic, env_item)); bag_.write(out.topic, out.time, *out.msg, out.connection_header, env_item.datatype, env_item.md5sum, env_item.msg_def); continue; } } } bag_.write(out.topic, out.time, *out.msg, out.connection_header); } } stopWriting(); } void Recorder::doRecordSnapshotter() { ros::NodeHandle nh; while (nh.ok() || !queue_queue_.empty()) { boost::unique_lock<boost::mutex> lock(queue_mutex_); while (queue_queue_.empty()) { if (!nh.ok()) return; queue_condition_.wait(lock); } OutgoingQueue out_queue = queue_queue_.front(); queue_queue_.pop(); lock.release()->unlock(); string target_filename = out_queue.filename; string write_filename = target_filename + string(".active"); try { bag_.open(write_filename, bagmode::Write); } catch (rosbag::BagException ex) { ROS_ERROR("Error writing: %s", ex.what()); return; } while (!out_queue.queue->empty()) { OutgoingMessage out = out_queue.queue->front(); out_queue.queue->pop(); bag_.write(out.topic, out.time, *out.msg); } stopWriting(); } } void Recorder::doCheckMaster(ros::TimerEvent const& e, ros::NodeHandle& node_handle) { (void)e; (void)node_handle; ros::master::V_TopicInfo topics; ros::BroadcastManager::instance()->getTopics(topics); foreach(ros::master::TopicInfo const& t, topics) { if (shouldSubscribeToTopic(t.name)) { subscribe(t.name); } } if (options_.node != std::string("")) { XmlRpc::XmlRpcValue req; req[0] = ros::this_node::getName(); req[1] = options_.node; XmlRpc::XmlRpcValue resp; XmlRpc::XmlRpcValue payload; if (ros::master::execute("lookupNode", req, resp, payload, true)) { std::string peer_host; uint32_t peer_port; if (!ros::network::splitURI(static_cast<std::string>(resp[2]), peer_host, peer_port)) { ROS_ERROR("Bad xml-rpc URI trying to inspect node at: [%s]", static_cast<std::string>(resp[2]).c_str()); } else { XmlRpc::XmlRpcClient c(peer_host.c_str(), peer_port, "/"); XmlRpc::XmlRpcValue req2; XmlRpc::XmlRpcValue resp2; req2[0] = ros::this_node::getName(); c.execute("getSubscriptions", req2, resp2); if (!c.isFault() && resp2.valid() && resp2.size() > 0 && static_cast<int>(resp2[0]) == 1) { for(int i = 0; i < resp2[2].size(); i++) { if (shouldSubscribeToTopic(resp2[2][i][0], true)) subscribe(resp2[2][i][0]); } } else { ROS_ERROR("Node at: [%s] failed to return subscriptions.", static_cast<std::string>(resp[2]).c_str()); } } } } } void Recorder::doTrigger() { ros::NodeHandle nh; ros::Publisher pub = nh.advertise<std_msgs::Empty>("snapshot_trigger", 1, true); pub.publish(std_msgs::Empty()); ros::Timer terminate_timer = nh.createTimer(ros::Duration(1.0), boost::bind(&ros::shutdown)); ros::spin(); } bool Recorder::scheduledCheckDisk() { boost::mutex::scoped_lock lock(check_disk_mutex_); if (ros::WallTime::now() < check_disk_next_) return true; check_disk_next_ += ros::WallDuration().fromSec(20.0); return checkDisk(); } bool Recorder::checkDisk() { #if BOOST_FILESYSTEM_VERSION < 3 struct statvfs fiData; if ((statvfs(bag_.getFileName().c_str(), &fiData)) < 0) { ROS_WARN("Failed to check filesystem stats."); return true; } unsigned long long free_space = 0; free_space = (unsigned long long) (fiData.f_bsize) * (unsigned long long) (fiData.f_bavail); if (free_space < options_.min_space) { ROS_ERROR("Less than %s of space free on disk with %s. Disabling recording.", options_.min_space_str.c_str(), bag_.getFileName().c_str()); writing_enabled_ = false; return false; } else if (free_space < 5 * options_.min_space) { ROS_WARN("Less than 5 x %s of space free on disk with %s.", options_.min_space_str.c_str(), bag_.getFileName().c_str()); } else { writing_enabled_ = true; } #else boost::filesystem::path p(boost::filesystem::system_complete(bag_.getFileName().c_str())); p = p.parent_path(); boost::filesystem::space_info info; try { info = boost::filesystem::space(p); } catch (boost::filesystem::filesystem_error &e) { ROS_WARN("Failed to check filesystem stats [%s].", e.what()); writing_enabled_ = false; return false; } if ( info.available < options_.min_space) { ROS_ERROR("Less than %s of space free on disk with %s. Disabling recording.", options_.min_space_str.c_str(), bag_.getFileName().c_str()); writing_enabled_ = false; return false; } else if (info.available < 5 * options_.min_space) { ROS_WARN("Less than 5 x %s of space free on disk with %s.", options_.min_space_str.c_str(), bag_.getFileName().c_str()); writing_enabled_ = true; } else { writing_enabled_ = true; } #endif return true; } bool Recorder::checkLogging() { if (writing_enabled_) return true; ros::WallTime now = ros::WallTime::now(); if (now >= warn_next_) { warn_next_ = now + ros::WallDuration().fromSec(5.0); ROS_WARN("Not logging message because logging disabled. Most likely cause is a full disk."); } return false; } } // namespace rosbag
0
apollo_public_repos/apollo-platform/ros/ros_comm/rosbag/src
apollo_public_repos/apollo-platform/ros/ros_comm/rosbag/src/rosbag/rosbag_main.py
# Software License Agreement (BSD License) # # Copyright (c) 2010, 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. from __future__ import print_function import optparse import os import shutil import signal import subprocess import sys import time try: from UserDict import UserDict # Python 2.x except ImportError: from collections import UserDict # Python 3.x import roslib.message import roslib.packages from .bag import Bag, Compression, ROSBagException, ROSBagFormatException, ROSBagUnindexedException from .migration import MessageMigrator, fixbag2, checkbag def print_trans(old, new, indent): from_txt = '%s [%s]' % (old._type, old._md5sum) if new is not None: to_txt= '%s [%s]' % (new._type, new._md5sum) else: to_txt = 'Unknown' print(' ' * indent + ' * From: %s' % from_txt) print(' ' * indent + ' To: %s' % to_txt) def handle_split(option, opt_str, value, parser): parser.values.split = True if len(parser.rargs) > 0 and parser.rargs[0].isdigit(): print("Use of \"--split <MAX_SIZE>\" has been deprecated. Please use --split --size <MAX_SIZE> or --split --duration <MAX_DURATION>", file=sys.stderr) parser.values.size = int(parser.rargs.pop(0)) def _stop_process(signum, frame, old_handler, process): process.terminate() if old_handler: old_handler(signum, frame) def record_cmd(argv): parser = optparse.OptionParser(usage="rosbag record TOPIC1 [TOPIC2 TOPIC3 ...]", description="Record a bag file with the contents of specified topics.", formatter=optparse.IndentedHelpFormatter()) parser.add_option("-a", "--all", dest="all", default=False, action="store_true", help="record all topics") parser.add_option("-e", "--regex", dest="regex", default=False, action="store_true", help="match topics using regular expressions") parser.add_option("-x", "--exclude", dest="exclude_regex", default="", action="store", help="exclude topics matching the follow regular expression (subtracts from -a or regex)") parser.add_option("-q", "--quiet", dest="quiet", default=False, action="store_true", help="suppress console output") parser.add_option("-o", "--output-prefix", dest="prefix", default=None, action="store", help="prepend PREFIX to beginning of bag name (name will always end with date stamp)") parser.add_option("-O", "--output-name", dest="name", default=None, action="store", help="record to bag with name NAME.bag") parser.add_option( "--split", dest="split", default=False, callback=handle_split, action="callback", help="split the bag when maximum size or duration is reached") parser.add_option( "--size", dest="size", type='int', action="store", help="record a bag of maximum size SIZE MB. (Default: infinite)", metavar="SIZE") parser.add_option( "--duration", dest="duration", type='string',action="store", help="record a bag of maximum duration DURATION in seconds, unless 'm', or 'h' is appended.", metavar="DURATION") parser.add_option("-b", "--buffsize", dest="buffsize", default=256, type='int', action="store", help="use an internal buffer of SIZE MB (Default: %default, 0 = infinite)", metavar="SIZE") parser.add_option("--chunksize", dest="chunksize", default=768, type='int', action="store", help="Advanced. Record to chunks of SIZE KB (Default: %default)", metavar="SIZE") parser.add_option("-l", "--limit", dest="num", default=0, type='int', action="store", help="only record NUM messages on each topic") parser.add_option( "--node", dest="node", default=None, type='string',action="store", help="record all topics subscribed to by a specific node") parser.add_option("-j", "--bz2", dest="compression", default=None, action="store_const", const='bz2', help="use BZ2 compression") parser.add_option("--lz4", dest="compression", action="store_const", const='lz4', help="use LZ4 compression") (options, args) = parser.parse_args(argv) if len(args) == 0 and not options.all and not options.node: parser.error("You must specify a topic name or else use the '-a' option.") if options.prefix is not None and options.name is not None: parser.error("Can't set both prefix and name.") recordpath = roslib.packages.find_node('rosbag', 'record') if not recordpath: parser.error("Cannot find rosbag/record executable") cmd = [recordpath[0]] cmd.extend(['--buffsize', str(options.buffsize)]) cmd.extend(['--chunksize', str(options.chunksize)]) if options.num != 0: cmd.extend(['--limit', str(options.num)]) if options.quiet: cmd.extend(["--quiet"]) if options.prefix: cmd.extend(["-o", options.prefix]) if options.name: cmd.extend(["-O", options.name]) if options.exclude_regex: cmd.extend(["--exclude", options.exclude_regex]) if options.all: cmd.extend(["--all"]) if options.regex: cmd.extend(["--regex"]) if options.compression: cmd.extend(["--%s" % options.compression]) if options.split: if not options.duration and not options.size: parser.error("Split specified without giving a maximum duration or size") cmd.extend(["--split"]) if options.duration: cmd.extend(["--duration", options.duration]) if options.size: cmd.extend(["--size", str(options.size)]) if options.node: cmd.extend(["--node", options.node]) cmd.extend(args) old_handler = signal.signal( signal.SIGTERM, lambda signum, frame: _stop_process(signum, frame, old_handler, process) ) # Better way of handling it than os.execv # This makes sure stdin handles are passed to the process. process = subprocess.Popen(cmd) process.wait() def info_cmd(argv): parser = optparse.OptionParser(usage='rosbag info [options] BAGFILE1 [BAGFILE2 BAGFILE3 ...]', description='Summarize the contents of one or more bag files.') parser.add_option('-y', '--yaml', dest='yaml', default=False, action='store_true', help='print information in YAML format') parser.add_option('-k', '--key', dest='key', default=None, action='store', help='print information on the given key') parser.add_option( '--freq', dest='freq', default=False, action='store_true', help='display topic message frequency statistics') (options, args) = parser.parse_args(argv) if len(args) == 0: parser.error('You must specify at least 1 bag file.') if options.key and not options.yaml: parser.error('You can only specify key when printing in YAML format.') for i, arg in enumerate(args): try: b = Bag(arg, 'r', skip_index=not options.freq) if options.yaml: info = b._get_yaml_info(key=options.key) if info is not None: print(info) else: print(b) b.close() if i < len(args) - 1: print('---') except ROSBagUnindexedException as ex: print('ERROR bag unindexed: %s. Run rosbag reindex.' % arg, file=sys.stderr) except ROSBagException as ex: print('ERROR reading %s: %s' % (arg, str(ex)), file=sys.stderr) except IOError as ex: print('ERROR reading %s: %s' % (arg, str(ex)), file=sys.stderr) def handle_topics(option, opt_str, value, parser): topics = [] for arg in parser.rargs: if arg[:2] == "--" and len(arg) > 2: break if arg[:1] == "-" and len(arg) > 1: break topics.append(arg) parser.values.topics.extend(topics) del parser.rargs[:len(topics)] def handle_pause_topics(option, opt_str, value, parser): pause_topics = [] for arg in parser.rargs: if arg[:2] == "--" and len(arg) > 2: break if arg[:1] == "-" and len(arg) > 1: break pause_topics.append(arg) parser.values.pause_topics.extend(pause_topics) del parser.rargs[:len(pause_topics)] def play_cmd(argv): parser = optparse.OptionParser(usage="rosbag play BAGFILE1 [BAGFILE2 BAGFILE3 ...]", description="Play back the contents of one or more bag files in a time-synchronized fashion.") parser.add_option("-p", "--prefix", dest="prefix", default='', type='str', help="prefix all output topics") parser.add_option("-q", "--quiet", dest="quiet", default=False, action="store_true", help="suppress console output") parser.add_option("-i", "--immediate", dest="immediate", default=False, action="store_true", help="play back all messages without waiting") parser.add_option("--pause", dest="pause", default=False, action="store_true", help="start in paused mode") parser.add_option("--queue", dest="queue", default=100, type='int', action="store", help="use an outgoing queue of size SIZE (defaults to %default)", metavar="SIZE") parser.add_option("--clock", dest="clock", default=False, action="store_true", help="publish the clock time") parser.add_option("--hz", dest="freq", default=100, type='float', action="store", help="use a frequency of HZ when publishing clock time (default: %default)", metavar="HZ") parser.add_option("-d", "--delay", dest="delay", default=0.2, type='float', action="store", help="sleep SEC seconds after every advertise call (to allow subscribers to connect)", metavar="SEC") parser.add_option("-r", "--rate", dest="rate", default=1.0, type='float', action="store", help="multiply the publish rate by FACTOR", metavar="FACTOR") parser.add_option("-s", "--start", dest="start", default=0.0, type='float', action="store", help="start SEC seconds into the bag files", metavar="SEC") parser.add_option("-u", "--duration", dest="duration", default=None, type='float', action="store", help="play only SEC seconds from the bag files", metavar="SEC") parser.add_option("--skip-empty", dest="skip_empty", default=None, type='float', action="store", help="skip regions in the bag with no messages for more than SEC seconds", metavar="SEC") parser.add_option("-l", "--loop", dest="loop", default=False, action="store_true", help="loop playback") parser.add_option("-k", "--keep-alive", dest="keep_alive", default=False, action="store_true", help="keep alive past end of bag (useful for publishing latched topics)") parser.add_option("--try-future-version", dest="try_future", default=False, action="store_true", help="still try to open a bag file, even if the version number is not known to the player") parser.add_option("--topics", dest="topics", default=[], callback=handle_topics, action="callback", help="topics to play back") parser.add_option("--pause-topics", dest="pause_topics", default=[], callback=handle_pause_topics, action="callback", help="topics to pause on during playback") parser.add_option("--bags", help="bags files to play back from") (options, args) = parser.parse_args(argv) if options.bags: args.append(options.bags) if len(args) == 0: parser.error('You must specify at least 1 bag file to play back.') playpath = roslib.packages.find_node('rosbag', 'play') if not playpath: parser.error("Cannot find rosbag/play executable") cmd = [playpath[0]] if options.prefix: cmd.extend(["--prefix", str(options.prefix)]) if options.quiet: cmd.extend(["--quiet"]) if options.pause: cmd.extend(["--pause"]) if options.immediate: cmd.extend(["--immediate"]) if options.loop: cmd.extend(["--loop"]) if options.keep_alive: cmd.extend(["--keep-alive"]) if options.try_future: cmd.extend(["--try-future-version"]) if options.clock: cmd.extend(["--clock", "--hz", str(options.freq)]) cmd.extend(['--queue', str(options.queue)]) cmd.extend(['--rate', str(options.rate)]) cmd.extend(['--delay', str(options.delay)]) cmd.extend(['--start', str(options.start)]) if options.duration: cmd.extend(['--duration', str(options.duration)]) if options.skip_empty: cmd.extend(['--skip-empty', str(options.skip_empty)]) if options.topics: cmd.extend(['--topics'] + options.topics) if options.pause_topics: cmd.extend(['--pause-topics'] + options.pause_topics) # prevent bag files to be passed as --topics or --pause-topics if options.topics or options.pause_topics: cmd.extend(['--bags']) cmd.extend(args) old_handler = signal.signal( signal.SIGTERM, lambda signum, frame: _stop_process(signum, frame, old_handler, process) ) # Better way of handling it than os.execv # This makes sure stdin handles are passed to the process. process = subprocess.Popen(cmd) process.wait() def filter_cmd(argv): def expr_eval(expr): def eval_fn(topic, m, t): return eval(expr) return eval_fn parser = optparse.OptionParser(usage="""rosbag filter [options] INBAG OUTBAG EXPRESSION EXPRESSION can be any Python-legal expression. The following variables are available: * topic: name of topic * m: message * t: time of message (t.secs, t.nsecs)""", description='Filter the contents of the bag.') parser.add_option('-p', '--print', action='store', dest='verbose_pattern', default=None, metavar='PRINT-EXPRESSION', help='Python expression to print for verbose debugging. Uses same variables as filter-expression') options, args = parser.parse_args(argv) if len(args) == 0: parser.error('You must specify an in bag, an out bag, and an expression.') if len(args) == 1: parser.error('You must specify an out bag and an expression.') if len(args) == 2: parser.error("You must specify an expression.") if len(args) > 3: parser.error("Too many arguments.") inbag_filename, outbag_filename, expr = args if not os.path.isfile(inbag_filename): print('Cannot locate input bag file [%s]' % inbag_filename, file=sys.stderr) sys.exit(2) if os.path.realpath(inbag_filename) == os.path.realpath(outbag_filename): print('Cannot use same file as input and output [%s]' % inbag_filename, file=sys.stderr) sys.exit(3) filter_fn = expr_eval(expr) outbag = Bag(outbag_filename, 'w') try: inbag = Bag(inbag_filename) except ROSBagUnindexedException as ex: print('ERROR bag unindexed: %s. Run rosbag reindex.' % inbag_filename, file=sys.stderr) return try: meter = ProgressMeter(outbag_filename, inbag._uncompressed_size) total_bytes = 0 if options.verbose_pattern: verbose_pattern = expr_eval(options.verbose_pattern) for topic, raw_msg, t in inbag.read_messages(raw=True): msg_type, serialized_bytes, md5sum, pos, pytype = raw_msg msg = pytype() msg.deserialize(serialized_bytes) if filter_fn(topic, msg, t): print('MATCH', verbose_pattern(topic, msg, t)) outbag.write(topic, msg, t) else: print('NO MATCH', verbose_pattern(topic, msg, t)) total_bytes += len(serialized_bytes) meter.step(total_bytes) else: for topic, raw_msg, t in inbag.read_messages(raw=True): msg_type, serialized_bytes, md5sum, pos, pytype = raw_msg msg = pytype() msg.deserialize(serialized_bytes) if filter_fn(topic, msg, t): outbag.write(topic, msg, t) total_bytes += len(serialized_bytes) meter.step(total_bytes) meter.finish() finally: inbag.close() outbag.close() def fix_cmd(argv): parser = optparse.OptionParser(usage='rosbag fix INBAG OUTBAG [EXTRARULES1 EXTRARULES2 ...]', description='Repair the messages in a bag file so that it can be played in the current system.') parser.add_option('-n', '--noplugins', action='store_true', dest='noplugins', help='do not load rulefiles via plugins') parser.add_option('--force', action='store_true', dest='force', help='proceed with migrations, even if not all rules defined') (options, args) = parser.parse_args(argv) if len(args) < 1: parser.error('You must pass input and output bag files.') if len(args) < 2: parser.error('You must pass an output bag file.') inbag_filename = args[0] outbag_filename = args[1] rules = args[2:] ext = os.path.splitext(outbag_filename)[1] if ext == '.bmr': parser.error('Input file should be a bag file, not a rule file.') if ext != '.bag': parser.error('Output file must be a bag file.') outname = outbag_filename + '.tmp' if os.path.exists(outbag_filename): if not os.access(outbag_filename, os.W_OK): print('Don\'t have permissions to access %s' % outbag_filename, file=sys.stderr) sys.exit(1) else: try: file = open(outbag_filename, 'w') file.close() except IOError as e: print('Cannot open %s for writing' % outbag_filename, file=sys.stderr) sys.exit(1) if os.path.exists(outname): if not os.access(outname, os.W_OK): print('Don\'t have permissions to access %s' % outname, file=sys.stderr) sys.exit(1) else: try: file = open(outname, 'w') file.close() except IOError as e: print('Cannot open %s for writing' % outname, file=sys.stderr) sys.exit(1) if options.noplugins is None: options.noplugins = False migrator = MessageMigrator(rules, plugins=not options.noplugins) try: migrations = fixbag2(migrator, inbag_filename, outname, options.force) except ROSBagUnindexedException as ex: print('ERROR bag unindexed: %s. Run rosbag reindex.' % inbag_filename, file=sys.stderr) return if len(migrations) == 0: os.rename(outname, outbag_filename) print('Bag migrated successfully.') else: print('Bag could not be migrated. The following migrations could not be performed:') for m in migrations: print_trans(m[0][0].old_class, m[0][-1].new_class, 0) if len(m[1]) > 0: print(' %d rules missing:' % len(m[1])) for r in m[1]: print_trans(r.old_class, r.new_class,1) print('Try running \'rosbag check\' to create the necessary rule files or run \'rosbag fix\' with the \'--force\' option.') os.remove(outname) def check_cmd(argv): parser = optparse.OptionParser(usage='rosbag check BAG [-g RULEFILE] [EXTRARULES1 EXTRARULES2 ...]', description='Determine whether a bag is playable in the current system, or if it can be migrated.') parser.add_option('-g', '--genrules', action='store', dest='rulefile', default=None, help='generate a rulefile named RULEFILE') parser.add_option('-a', '--append', action='store_true', dest='append', help='append to the end of an existing rulefile after loading it') parser.add_option('-n', '--noplugins', action='store_true', dest='noplugins', help='do not load rulefiles via plugins') (options, args) = parser.parse_args(argv) if len(args) == 0: parser.error('You must specify a bag file to check.') if options.append and options.rulefile is None: parser.error('Cannot specify -a without also specifying -g.') if options.rulefile is not None: rulefile_exists = os.path.isfile(options.rulefile) if rulefile_exists and not options.append: parser.error('The file %s already exists. Include -a if you intend to append.' % options.rulefile) if not rulefile_exists and options.append: parser.error('The file %s does not exist, and so -a is invalid.' % options.rulefile) if options.append: append_rule = [options.rulefile] else: append_rule = [] # First check that the bag is not unindexed try: Bag(args[0]) except ROSBagUnindexedException as ex: print('ERROR bag unindexed: %s. Run rosbag reindex.' % args[0], file=sys.stderr) return mm = MessageMigrator(args[1:] + append_rule, not options.noplugins) migrations = checkbag(mm, args[0]) if len(migrations) == 0: print('Bag file is up to date.') exit(0) print('The following migrations need to occur:') all_rules = [] for m in migrations: all_rules.extend(m[1]) print_trans(m[0][0].old_class, m[0][-1].new_class, 0) if len(m[1]) > 0: print(" %d rules missing:" % len(m[1])) for r in m[1]: print_trans(r.old_class, r.new_class, 1) if options.rulefile is None: if all_rules == []: print("\nAll rules defined. Bag is ready to be migrated") else: print("\nTo generate rules, please run with -g <rulefile>") exit(0) output = '' rules_left = mm.filter_rules_unique(all_rules) if rules_left == []: print("\nNo additional rule files needed to be generated. %s not created."%(options.rulefile)) exit(0) while len(rules_left) > 0: extra_rules = [] for r in rules_left: if r.new_class is None: print('The message type %s appears to have moved. Please enter the type to migrate it to.' % r.old_class._type) new_type = raw_input('>') new_class = roslib.message.get_message_class(new_type) while new_class is None: print("\'%s\' could not be found in your system. Please make sure it is built." % new_type) new_type = raw_input('>') new_class = roslib.message.get_message_class(new_type) new_rule = mm.make_update_rule(r.old_class, new_class) R = new_rule(mm, 'GENERATED.' + new_rule.__name__) R.find_sub_paths() new_rules = [r for r in mm.expand_rules(R.sub_rules) if r.valid == False] extra_rules.extend(new_rules) print('Creating the migration rule for %s requires additional missing rules:' % new_type) for nr in new_rules: print_trans(nr.old_class, nr.new_class,1) output += R.get_class_def() else: output += r.get_class_def() rules_left = mm.filter_rules_unique(extra_rules) f = open(options.rulefile, 'a') f.write(output) f.close() print('\nThe necessary rule files have been written to: %s' % options.rulefile) def compress_cmd(argv): parser = optparse.OptionParser(usage='rosbag compress [options] BAGFILE1 [BAGFILE2 ...]', description='Compress one or more bag files.') parser.add_option( '--output-dir', action='store', dest='output_dir', help='write to directory DIR', metavar='DIR') parser.add_option('-f', '--force', action='store_true', dest='force', help='force overwriting of backup file if it exists') parser.add_option('-q', '--quiet', action='store_true', dest='quiet', help='suppress noncritical messages') parser.add_option('-j', '--bz2', action='store_const', dest='compression', help='use BZ2 compression', const=Compression.BZ2, default=Compression.BZ2) parser.add_option( '--lz4', action='store_const', dest='compression', help='use lz4 compression', const=Compression.LZ4) (options, args) = parser.parse_args(argv) if len(args) < 1: parser.error('You must specify at least one bag file.') op = lambda inbag, outbag, quiet: change_compression_op(inbag, outbag, options.compression, options.quiet) bag_op(args, False, lambda b: False, op, options.output_dir, options.force, options.quiet) def decompress_cmd(argv): parser = optparse.OptionParser(usage='rosbag decompress [options] BAGFILE1 [BAGFILE2 ...]', description='Decompress one or more bag files.') parser.add_option( '--output-dir', action='store', dest='output_dir', help='write to directory DIR', metavar='DIR') parser.add_option('-f', '--force', action='store_true', dest='force', help='force overwriting of backup file if it exists') parser.add_option('-q', '--quiet', action='store_true', dest='quiet', help='suppress noncritical messages') (options, args) = parser.parse_args(argv) if len(args) < 1: parser.error('You must specify at least one bag file.') op = lambda inbag, outbag, quiet: change_compression_op(inbag, outbag, Compression.NONE, options.quiet) bag_op(args, False, lambda b: False, op, options.output_dir, options.force, options.quiet) def reindex_cmd(argv): parser = optparse.OptionParser(usage='rosbag reindex [options] BAGFILE1 [BAGFILE2 ...]', description='Reindexes one or more bag files.') parser.add_option( '--output-dir', action='store', dest='output_dir', help='write to directory DIR', metavar='DIR') parser.add_option('-f', '--force', action='store_true', dest='force', help='force overwriting of backup file if it exists') parser.add_option('-q', '--quiet', action='store_true', dest='quiet', help='suppress noncritical messages') (options, args) = parser.parse_args(argv) if len(args) < 1: parser.error('You must specify at least one bag file.') op = lambda inbag, outbag, quiet: reindex_op(inbag, outbag, options.quiet) bag_op(args, True, lambda b: b.version > 102, op, options.output_dir, options.force, options.quiet) def bag_op(inbag_filenames, allow_unindexed, copy_fn, op, output_dir=None, force=False, quiet=False): for inbag_filename in inbag_filenames: # Check we can read the file try: inbag = Bag(inbag_filename, 'r', allow_unindexed=allow_unindexed) except ROSBagUnindexedException: print('ERROR bag unindexed: %s. Run rosbag reindex.' % inbag_filename, file=sys.stderr) continue except (ROSBagException, IOError) as ex: print('ERROR reading %s: %s' % (inbag_filename, str(ex)), file=sys.stderr) continue # Determine whether we should copy the bag copy = copy_fn(inbag) inbag.close() # Determine filename for output bag if output_dir is None: outbag_filename = inbag_filename else: outbag_filename = os.path.join(output_dir, os.path.split(inbag_filename)[1]) backup_filename = None if outbag_filename == inbag_filename: # Rename the input bag to ###.orig.###, and open for reading backup_filename = '%s.orig%s' % os.path.splitext(inbag_filename) if not force and os.path.exists(backup_filename): if not quiet: print('Skipping %s. Backup path %s already exists.' % (inbag_filename, backup_filename), file=sys.stderr) continue try: if copy: shutil.copy(inbag_filename, backup_filename) else: os.rename(inbag_filename, backup_filename) except OSError as ex: print('ERROR %s %s to %s: %s' % ('copying' if copy else 'moving', inbag_filename, backup_filename, str(ex)), file=sys.stderr) continue source_filename = backup_filename else: if copy: shutil.copy(inbag_filename, outbag_filename) source_filename = outbag_filename else: source_filename = inbag_filename try: inbag = Bag(source_filename, 'r', allow_unindexed=allow_unindexed) # Open the output bag file for writing try: if copy: outbag = Bag(outbag_filename, 'a', allow_unindexed=allow_unindexed) else: outbag = Bag(outbag_filename, 'w') except (ROSBagException, IOError) as ex: print('ERROR writing to %s: %s' % (outbag_filename, str(ex)), file=sys.stderr) inbag.close() continue # Perform the operation try: op(inbag, outbag, quiet=quiet) except ROSBagException as ex: print('\nERROR operating on %s: %s' % (source_filename, str(ex)), file=sys.stderr) inbag.close() outbag.close() continue outbag.close() inbag.close() except KeyboardInterrupt: if backup_filename is not None: try: if copy: os.remove(backup_filename) else: os.rename(backup_filename, inbag_filename) except OSError as ex: print('ERROR %s %s to %s: %s', ('removing' if copy else 'moving', backup_filename, inbag_filename, str(ex)), file=sys.stderr) break except (ROSBagException, IOError) as ex: print('ERROR operating on %s: %s' % (inbag_filename, str(ex)), file=sys.stderr) def change_compression_op(inbag, outbag, compression, quiet): outbag.compression = compression if quiet: for topic, msg, t in inbag.read_messages(raw=True): outbag.write(topic, msg, t, raw=True) else: meter = ProgressMeter(outbag.filename, inbag._uncompressed_size) total_bytes = 0 for topic, msg, t in inbag.read_messages(raw=True): msg_type, serialized_bytes, md5sum, pos, pytype = msg outbag.write(topic, msg, t, raw=True) total_bytes += len(serialized_bytes) meter.step(total_bytes) meter.finish() def reindex_op(inbag, outbag, quiet): if inbag.version == 102: if quiet: try: for offset in inbag.reindex(): pass except: pass for (topic, msg, t) in inbag.read_messages(): outbag.write(topic, msg, t) else: meter = ProgressMeter(outbag.filename, inbag.size) try: for offset in inbag.reindex(): meter.step(offset) except: pass meter.finish() meter = ProgressMeter(outbag.filename, inbag.size) for (topic, msg, t) in inbag.read_messages(): outbag.write(topic, msg, t) meter.step(inbag._file.tell()) meter.finish() else: if quiet: try: for offset in outbag.reindex(): pass except: pass else: meter = ProgressMeter(outbag.filename, outbag.size) try: for offset in outbag.reindex(): meter.step(offset) except: pass meter.finish() class RosbagCmds(UserDict): def __init__(self): UserDict.__init__(self) self._description = {} self['help'] = self.help_cmd def add_cmd(self, name, function, description): self[name] = function self._description[name] = description def get_valid_cmds(self): str = "Available subcommands:\n" for k in sorted(self.keys()): str += " %s " % k if k in self._description.keys(): str +="\t%s" % self._description[k] str += "\n" return str def help_cmd(self,argv): argv = [a for a in argv if a != '-h' and a != '--help'] if len(argv) == 0: print('Usage: rosbag <subcommand> [options] [args]') print() print("A bag is a file format in ROS for storing ROS message data. The rosbag command can record, replay and manipulate bags.") print() print(self.get_valid_cmds()) print('For additional information, see http://wiki.ros.org/rosbag') print() return cmd = argv[0] if cmd in self: self[cmd](['-h']) else: print("Unknown command: '%s'" % cmd, file=sys.stderr) print(self.get_valid_cmds(), file=sys.stderr) class ProgressMeter(object): def __init__(self, path, bytes_total, refresh_rate=1.0): self.path = path self.bytes_total = bytes_total self.refresh_rate = refresh_rate self.elapsed = 0.0 self.update_elapsed = 0.0 self.bytes_read = 0.0 self.start_time = time.time() self._update_progress() def step(self, bytes_read, force_update=False): self.bytes_read = bytes_read self.elapsed = time.time() - self.start_time if force_update or self.elapsed - self.update_elapsed > self.refresh_rate: self._update_progress() self.update_elapsed = self.elapsed def _update_progress(self): max_path_len = self.terminal_width() - 37 path = self.path if len(path) > max_path_len: path = '...' + self.path[-max_path_len + 3:] bytes_read_str = self._human_readable_size(float(self.bytes_read)) bytes_total_str = self._human_readable_size(float(self.bytes_total)) if self.bytes_read < self.bytes_total: complete_fraction = float(self.bytes_read) / self.bytes_total pct_complete = int(100.0 * complete_fraction) if complete_fraction > 0.0: eta = self.elapsed * (1.0 / complete_fraction - 1.0) eta_min, eta_sec = eta / 60, eta % 60 if eta_min > 99: eta_str = '--:--' else: eta_str = '%02d:%02d' % (eta_min, eta_sec) else: eta_str = '--:--' progress = '%-*s %3d%% %8s / %8s %s ETA' % (max_path_len, path, pct_complete, bytes_read_str, bytes_total_str, eta_str) else: progress = '%-*s 100%% %19s %02d:%02d ' % (max_path_len, path, bytes_total_str, self.elapsed / 60, self.elapsed % 60) print('\r', progress, end='') sys.stdout.flush() def _human_readable_size(self, size): multiple = 1024.0 for suffix in ['KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']: size /= multiple if size < multiple: return '%.1f %s' % (size, suffix) raise ValueError('number too large') def finish(self): self.step(self.bytes_total, force_update=True) print() @staticmethod def terminal_width(): """Estimate the width of the terminal""" width = 0 try: import struct, fcntl, termios s = struct.pack('HHHH', 0, 0, 0, 0) x = fcntl.ioctl(1, termios.TIOCGWINSZ, s) width = struct.unpack('HHHH', x)[1] except (IOError, ImportError): pass if width <= 0: try: width = int(os.environ['COLUMNS']) except: pass if width <= 0: width = 80 return width def rosbagmain(argv=None): cmds = RosbagCmds() cmds.add_cmd('record', record_cmd, "Record a bag file with the contents of specified topics.") cmds.add_cmd('info', info_cmd, 'Summarize the contents of one or more bag files.') cmds.add_cmd('play', play_cmd, "Play back the contents of one or more bag files in a time-synchronized fashion.") cmds.add_cmd('check', check_cmd, 'Determine whether a bag is playable in the current system, or if it can be migrated.') cmds.add_cmd('fix', fix_cmd, 'Repair the messages in a bag file so that it can be played in the current system.') cmds.add_cmd('filter', filter_cmd, 'Filter the contents of the bag.') cmds.add_cmd('compress', compress_cmd, 'Compress one or more bag files.') cmds.add_cmd('decompress', decompress_cmd, 'Decompress one or more bag files.') cmds.add_cmd('reindex', reindex_cmd, 'Reindexes one or more bag files.') if argv is None: argv = sys.argv if '-h' in argv or '--help' in argv: argv = [a for a in argv if a != '-h' and a != '--help'] argv.insert(1, 'help') if len(argv) > 1: cmd = argv[1] else: cmd = 'help' try: if cmd in cmds: cmds[cmd](argv[2:]) else: cmds['help']([cmd]) except KeyboardInterrupt: pass
0
apollo_public_repos/apollo-platform/ros/ros_comm/rosbag/src
apollo_public_repos/apollo-platform/ros/ros_comm/rosbag/src/rosbag/bag.py
# Software License Agreement (BSD License) # # Copyright (c) 2010, 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. """ The rosbag Python API. Provides serialization of bag files. """ from __future__ import print_function import bisect import bz2 import collections import heapq import os import re import struct import sys import threading import time import yaml import google.protobuf try: from cStringIO import StringIO # Python 2.x except ImportError: from io import BytesIO as StringIO # Python 3.x import genmsg import genpy import genpy.dynamic import genpy.message import roslib.names # still needed for roslib.names.canonicalize_name() import roslib.message import rospy try: import roslz4 found_lz4 = True except ImportError: rospy.logwarn( 'Failed to load Python extension for LZ4 support. ' 'LZ4 compression will not be available.') found_lz4 = False class ROSBagException(Exception): """ Base class for exceptions in rosbag. """ def __init__(self, value): self.value = value def __str__(self): return self.value class ROSBagFormatException(ROSBagException): """ Exceptions for errors relating to the bag file format. """ def __init__(self, value): ROSBagException.__init__(self, value) class ROSBagUnindexedException(ROSBagException): """ Exception for unindexed bags. """ def __init__(self): ROSBagException.__init__(self, 'Unindexed bag') class Compression: """ Allowable compression types """ NONE = 'none' BZ2 = 'bz2' LZ4 = 'lz4' BagMessage = collections.namedtuple('BagMessage', 'topic message timestamp') class Bag(object): """ Bag serialize messages to and from a single file on disk using the bag format. """ def __init__(self, f, mode='r', compression=Compression.NONE, chunk_threshold=768 * 1024, allow_unindexed=False, options=None, skip_index=False): """ Open a bag file. The mode can be 'r', 'w', or 'a' for reading (default), writing or appending. The file will be created if it doesn't exist when opened for writing or appending; it will be truncated when opened for writing. Simultaneous reading and writing is allowed when in writing or appending mode. @param f: filename of bag to open or a stream to read from @type f: str or file @param mode: mode, either 'r', 'w', or 'a' @type mode: str @param compression: compression mode, see U{rosbag.Compression} for valid modes @type compression: str @param chunk_threshold: minimum number of uncompressed bytes per chunk @type chunk_threshold: int @param allow_unindexed: if True, allow opening unindexed bags @type allow_unindexed: bool @param options: the bag options (currently: compression and chunk_threshold) @type options: dict @param skip_index: if True, don't read the connection index records on open [2.0+] @type skip_index: bool @raise ValueError: if any argument is invalid @raise ROSBagException: if an error occurs opening file @raise ROSBagFormatException: if bag format is corrupted """ if options is not None: if type(options) is not dict: raise ValueError('options must be of type dict') if 'compression' in options: compression = options['compression'] if 'chunk_threshold' in options: chunk_threshold = options['chunk_threshold'] self._file = None self._filename = None self._version = None allowed_compressions = [Compression.NONE, Compression.BZ2] if found_lz4: allowed_compressions.append(Compression.LZ4) if compression not in allowed_compressions: raise ValueError('compression must be one of: %s' % ', '.join(allowed_compressions)) self._compression = compression if chunk_threshold < 0: raise ValueError('chunk_threshold must be greater than or equal to zero') self._chunk_threshold = chunk_threshold self._skip_index = skip_index self._reader = None self._file_header_pos = None self._index_data_pos = 0 # (1.2+) self._clear_index() self._buffer = StringIO() self._curr_compression = Compression.NONE self._open(f, mode, allow_unindexed) self._output_file = self._file def __iter__(self): return self.read_messages() def __enter__(self): return self def __exit__(self, exc_type, exc_value, traceback): self.close() @property def options(self): """Get the options.""" return { 'compression' : self._compression, 'chunk_threshold' : self._chunk_threshold } @property def filename(self): """Get the filename.""" return self._filename @property def version(self): """Get the version.""" return self._version @property def mode(self): """Get the mode.""" return self._mode @property def size(self): """Get the size in bytes.""" if not self._file: raise ValueError('I/O operation on closed bag') pos = self._file.tell() self._file.seek(0, os.SEEK_END) size = self._file.tell() self._file.seek(pos) return size # compression def _get_compression(self): """Get the compression method to use for writing.""" return self._compression def _set_compression(self, compression): """Set the compression method to use for writing.""" allowed_compressions = [Compression.NONE, Compression.BZ2] if found_lz4: allowed_compressions.append(Compression.LZ4) if compression not in allowed_compressions: raise ValueError('compression must be one of: %s' % ', '.join(allowed_compressions)) self.flush() self._compression = compression compression = property(_get_compression, _set_compression) # chunk_threshold def _get_chunk_threshold(self): """Get the chunk threshold to use for writing.""" return self._chunk_threshold def _set_chunk_threshold(self, chunk_threshold): """Set the chunk threshold to use for writing.""" if chunk_threshold < 0: raise ValueError('chunk_threshold must be greater than or equal to zero') self.flush() self._chunk_threshold = chunk_threshold chunk_threshold = property(_get_chunk_threshold, _set_chunk_threshold) def read_messages(self, topics=None, start_time=None, end_time=None, connection_filter=None, raw=False): """ Read messages from the bag, optionally filtered by topic, timestamp and connection details. @param topics: list of topics or a single topic. if an empty list is given all topics will be read [optional] @type topics: list(str) or str @param start_time: earliest timestamp of message to return [optional] @type start_time: U{genpy.Time} @param end_time: latest timestamp of message to return [optional] @type end_time: U{genpy.Time} @param connection_filter: function to filter connections to include [optional] @type connection_filter: function taking (topic, datatype, md5sum, msg_def, header) and returning bool @param raw: if True, then generate tuples of (datatype, (data, md5sum, position), pytype) @type raw: bool @return: generator of BagMessage(topic, message, timestamp) namedtuples for each message in the bag file @rtype: generator of tuples of (str, U{genpy.Message}, U{genpy.Time}) [not raw] or (str, (str, str, str, tuple, class), U{genpy.Time}) [raw] """ self.flush() if topics and type(topics) is str: topics = [topics] return self._reader.read_messages(topics, start_time, end_time, connection_filter, raw) def flush(self): """ Write the open chunk to disk so subsequent reads will read all messages. @raise ValueError: if bag is closed """ if not self._file: raise ValueError('I/O operation on closed bag') if self._chunk_open: self._stop_writing_chunk() def write(self, topic, msg, t=None, raw=False): """ Write a message to the bag. @param topic: name of topic @type topic: str @param msg: message to add to bag, or tuple (if raw) @type msg: Message or tuple of raw message data @param t: ROS time of message publication, if None specifed, use current time [optional] @type t: U{genpy.Time} @param raw: if True, msg is in raw format, i.e. (msg_type, serialized_bytes, md5sum, pytype) @type raw: bool @raise ValueError: if arguments are invalid or bag is closed """ if not self._file: raise ValueError('I/O operation on closed bag') if not topic: raise ValueError('topic is invalid') if not msg: raise ValueError('msg is invalid') if t is None: t = genpy.Time.from_sec(time.time()) # Seek to end (in case previous operation was a read) self._file.seek(0, os.SEEK_END) # Open a chunk, if needed if not self._chunk_open: self._start_writing_chunk(t) # Unpack raw if raw: if len(msg) == 5: msg_type, serialized_bytes, md5sum, pos, pytype = msg elif len(msg) == 4: msg_type, serialized_bytes, md5sum, pytype = msg else: raise ValueError('msg must be of length 4 or 5') # Write connection record, if necessary (currently using a connection per topic; ignoring message connection header) if topic in self._topic_connections: connection_info = self._topic_connections[topic] conn_id = connection_info.id else: conn_id = len(self._connections) if raw: if pytype is None: try: pytype = genpy.message.get_message_class(msg_type) except Exception: pytype = None if pytype is None: raise ROSBagException('cannot locate message class and no message class provided for [%s]' % msg_type) if pytype._md5sum != md5sum: print('WARNING: md5sum of loaded type [%s] does not match that specified' % msg_type, file=sys.stderr) #raise ROSBagException('md5sum of loaded type does not match that of data being recorded') header = { 'topic' : topic, 'type' : msg_type, 'md5sum' : md5sum, 'message_definition' : pytype._full_text } else: if issubclass(msg.__class__, google.protobuf.message.Message): roslib.message.add_rosmsg_interface_for_protobuf(msg.__class__) header = { 'topic' : topic, 'type' : msg.__class__._type, 'md5sum' : msg.__class__._md5sum, 'message_definition' : 'protobuf' } else: header = { 'topic' : topic, 'type' : msg.__class__._type, 'md5sum' : msg.__class__._md5sum, 'message_definition' : msg._full_text } connection_info = _ConnectionInfo(conn_id, topic, header) self._write_connection_record(connection_info) self._connections[conn_id] = connection_info self._topic_connections[topic] = connection_info # Create an index entry index_entry = _IndexEntry200(t, self._curr_chunk_info.pos, self._get_chunk_offset()) # Update the indexes and current chunk info if conn_id not in self._curr_chunk_connection_indexes: # This is the first message on this connection in the chunk self._curr_chunk_connection_indexes[conn_id] = [index_entry] self._curr_chunk_info.connection_counts[conn_id] = 1 else: curr_chunk_connection_index = self._curr_chunk_connection_indexes[conn_id] if index_entry >= curr_chunk_connection_index[-1]: # Test if we're writing chronologically. Can skip binary search if so. curr_chunk_connection_index.append(index_entry) else: bisect.insort_right(curr_chunk_connection_index, index_entry) self._curr_chunk_info.connection_counts[conn_id] += 1 if conn_id not in self._connection_indexes: self._connection_indexes[conn_id] = [index_entry] else: bisect.insort_right(self._connection_indexes[conn_id], index_entry) # Update the chunk start/end times if t > self._curr_chunk_info.end_time: self._curr_chunk_info.end_time = t elif t < self._curr_chunk_info.start_time: self._curr_chunk_info.start_time = t if not raw: # Serialize the message to the buffer self._buffer.seek(0) self._buffer.truncate(0) msg.serialize(self._buffer) serialized_bytes = self._buffer.getvalue() # Write message data record self._write_message_data_record(conn_id, t, serialized_bytes) # Check if we want to stop this chunk chunk_size = self._get_chunk_offset() if chunk_size > self._chunk_threshold: self._stop_writing_chunk() def reindex(self): """ Reindexes the bag file. Yields position of each chunk for progress. """ self._clear_index() return self._reader.reindex() def close(self): """ Close the bag file. Closing an already closed bag does nothing. """ if self._file: if self._mode in 'wa': self._stop_writing() self._close_file() def get_compression_info(self): """ Returns information about the compression of the bag @return: generator of CompressionTuple(compression, uncompressed, compressed) describing the type of compression used, size of the uncompressed data in Bytes, size of the compressed data in Bytes. If no compression is used then uncompressed and compressed data will be equal. @rtype: generator of CompressionTuple of (str, int, int) """ compression = self.compression uncompressed = 0 compressed = 0 if self._chunk_headers: compression_counts = {} compression_uncompressed = {} compression_compressed = {} # the rest of this is determine which compression algorithm is dominant and # to add up the uncompressed and compressed Bytes for chunk_header in self._chunk_headers.values(): if chunk_header.compression not in compression_counts: compression_counts[chunk_header.compression] = 0 if chunk_header.compression not in compression_uncompressed: compression_uncompressed[chunk_header.compression] = 0 if chunk_header.compression not in compression_compressed: compression_compressed[chunk_header.compression] = 0 compression_counts[chunk_header.compression] += 1 compression_uncompressed[chunk_header.compression] += chunk_header.uncompressed_size uncompressed += chunk_header.uncompressed_size compression_compressed[chunk_header.compression] += chunk_header.compressed_size compressed += chunk_header.compressed_size chunk_count = len(self._chunk_headers) main_compression_count, main_compression = sorted([(v, k) for k, v in compression_counts.items()], reverse=True)[0] compression = str(main_compression) return collections.namedtuple("CompressionTuple", ["compression", "uncompressed", "compressed"])(compression=compression, uncompressed=uncompressed, compressed=compressed) def get_message_count(self, topic_filters=None): """ Returns the number of messages in the bag. Can be filtered by Topic @param topic_filters: One or more topics to filter by @type topic_filters: Could be either a single str or a list of str. @return: The number of messages in the bag, optionally filtered by topic @rtype: int """ num_messages = 0 if topic_filters is not None: info = self.get_type_and_topic_info(topic_filters=topic_filters) for topic in info.topics.values(): num_messages += topic.message_count else: if self._chunks: for c in self._chunks: for counts in c.connection_counts.values(): num_messages += counts else: num_messages = sum([len(index) for index in self._connection_indexes.values()]) return num_messages def get_start_time(self): """ Returns the start time of the bag. @return: a timestamp of the start of the bag @rtype: float, timestamp in seconds, includes fractions of a second """ if self._chunks: start_stamp = self._chunks[0].start_time.to_sec() else: if not self._connection_indexes: raise ROSBagException('Bag contains no message') start_stamp = min([index[0].time.to_sec() for index in self._connection_indexes.values()]) return start_stamp def get_end_time(self): """ Returns the end time of the bag. @return: a timestamp of the end of the bag @rtype: float, timestamp in seconds, includes fractions of a second """ if self._chunks: end_stamp = self._chunks[-1].end_time.to_sec() else: if not self._connection_indexes: raise ROSBagException('Bag contains no message') end_stamp = max([index[-1].time.to_sec() for index in self._connection_indexes.values()]) return end_stamp def get_type_and_topic_info(self, topic_filters=None): """ Coallates info about the type and topics in the bag. Note, it would be nice to filter by type as well, but there appear to be some limitations in the current architecture that prevent that from working when more than one message type is written on the same topic. @param topic_filters: specify one or more topic to filter by. @type topic_filters: either a single str or a list of str. @return: generator of TypesAndTopicsTuple(types{key:type name, val: md5hash}, topics{type: msg type (Ex. "std_msgs/String"), message_count: the number of messages of the particular type, connections: the number of connections, frequency: the data frequency, key: type name, val: md5hash}) describing the types of messages present and information about the topics @rtype: TypesAndTopicsTuple(dict(str, str), TopicTuple(str, int, int, float, str, str)) """ datatypes = set() datatype_infos = [] for connection in self._connections.values(): if connection.datatype in datatypes: continue datatype_infos.append((connection.datatype, connection.md5sum, connection.msg_def)) datatypes.add(connection.datatype) topics = [] # load our list of topics and optionally filter if topic_filters is not None: if not isinstance(topic_filters, list): topic_filters = [topic_filters] topics = topic_filters else: topics = [c.topic for c in self._get_connections()] topics = sorted(set(topics)) topic_datatypes = {} topic_conn_counts = {} topic_msg_counts = {} topic_freqs_median = {} for topic in topics: connections = list(self._get_connections(topic)) if not connections: continue topic_datatypes[topic] = connections[0].datatype topic_conn_counts[topic] = len(connections) msg_count = 0 for connection in connections: for chunk in self._chunks: msg_count += chunk.connection_counts.get(connection.id, 0) topic_msg_counts[topic] = msg_count if self._connection_indexes_read: stamps = [entry.time.to_sec() for entry in self._get_entries(connections)] if len(stamps) > 1: periods = [s1 - s0 for s1, s0 in zip(stamps[1:], stamps[:-1])] med_period = _median(periods) if med_period > 0.0: topic_freqs_median[topic] = 1.0 / med_period # process datatypes types = {} for datatype, md5sum, msg_def in sorted(datatype_infos): types[datatype] = md5sum # process topics topics_t = {} TopicTuple = collections.namedtuple("TopicTuple", ["msg_type", "message_count", "connections", "frequency"]) for topic in sorted(topic_datatypes.keys()): topic_msg_count = topic_msg_counts[topic] frequency = topic_freqs_median[topic] if topic in topic_freqs_median else None topics_t[topic] = TopicTuple(msg_type=topic_datatypes[topic], message_count=topic_msg_count, connections=topic_conn_counts[topic], frequency=frequency) return collections.namedtuple("TypesAndTopicsTuple", ["msg_types", "topics"])(msg_types=types, topics=topics_t) def __str__(self): rows = [] try: if self._filename: rows.append(('path', self._filename)) if self._version == 102 and type(self._reader) == _BagReader102_Unindexed: rows.append(('version', '1.2 (unindexed)')) else: rows.append(('version', '%d.%d' % (int(self._version / 100), self._version % 100))) if not self._connection_indexes and not self._chunks: rows.append(('size', _human_readable_size(self.size))) else: if self._chunks: start_stamp = self._chunks[ 0].start_time.to_sec() end_stamp = self._chunks[-1].end_time.to_sec() else: start_stamp = min([index[ 0].time.to_sec() for index in self._connection_indexes.values()]) end_stamp = max([index[-1].time.to_sec() for index in self._connection_indexes.values()]) # Show duration duration = end_stamp - start_stamp dur_secs = duration % 60 dur_mins = int(duration / 60) dur_hrs = int(dur_mins / 60) if dur_hrs > 0: dur_mins = dur_mins % 60 duration_str = '%dhr %d:%02ds (%ds)' % (dur_hrs, dur_mins, dur_secs, duration) elif dur_mins > 0: duration_str = '%d:%02ds (%ds)' % (dur_mins, dur_secs, duration) else: duration_str = '%.1fs' % duration rows.append(('duration', duration_str)) # Show start and end times rows.append(('start', '%s (%.2f)' % (_time_to_str(start_stamp), start_stamp))) rows.append(('end', '%s (%.2f)' % (_time_to_str(end_stamp), end_stamp))) rows.append(('size', _human_readable_size(self.size))) if self._chunks: num_messages = 0 for c in self._chunks: for counts in c.connection_counts.values(): num_messages += counts else: num_messages = sum([len(index) for index in self._connection_indexes.values()]) rows.append(('messages', str(num_messages))) # Show compression information if len(self._chunk_headers) == 0: rows.append(('compression', 'none')) else: compression_counts = {} compression_uncompressed = {} compression_compressed = {} for chunk_header in self._chunk_headers.values(): if chunk_header.compression not in compression_counts: compression_counts[chunk_header.compression] = 1 compression_uncompressed[chunk_header.compression] = chunk_header.uncompressed_size compression_compressed[chunk_header.compression] = chunk_header.compressed_size else: compression_counts[chunk_header.compression] += 1 compression_uncompressed[chunk_header.compression] += chunk_header.uncompressed_size compression_compressed[chunk_header.compression] += chunk_header.compressed_size chunk_count = len(self._chunk_headers) compressions = [] for count, compression in reversed(sorted([(v, k) for k, v in compression_counts.items()])): if compression != Compression.NONE: fraction = (100.0 * compression_compressed[compression]) / compression_uncompressed[compression] compressions.append('%s [%d/%d chunks; %.2f%%]' % (compression, count, chunk_count, fraction)) else: compressions.append('%s [%d/%d chunks]' % (compression, count, chunk_count)) rows.append(('compression', ', '.join(compressions))) all_uncompressed = (sum([count for c, count in compression_counts.items() if c != Compression.NONE]) == 0) if not all_uncompressed: total_uncompressed_size = sum((h.uncompressed_size for h in self._chunk_headers.values())) total_compressed_size = sum((h.compressed_size for h in self._chunk_headers.values())) total_uncompressed_size_str = _human_readable_size(total_uncompressed_size) total_compressed_size_str = _human_readable_size(total_compressed_size) total_size_str_length = max([len(total_uncompressed_size_str), len(total_compressed_size_str)]) if duration > 0: uncompressed_rate_str = _human_readable_size(total_uncompressed_size / duration) compressed_rate_str = _human_readable_size(total_compressed_size / duration) rate_str_length = max([len(uncompressed_rate_str), len(compressed_rate_str)]) rows.append(('uncompressed', '%*s @ %*s/s' % (total_size_str_length, total_uncompressed_size_str, rate_str_length, uncompressed_rate_str))) rows.append(('compressed', '%*s @ %*s/s (%.2f%%)' % (total_size_str_length, total_compressed_size_str, rate_str_length, compressed_rate_str, (100.0 * total_compressed_size) / total_uncompressed_size))) else: rows.append(('uncompressed', '%*s' % (total_size_str_length, total_uncompressed_size_str))) rows.append(('compressed', '%*s' % (total_size_str_length, total_compressed_size_str))) datatypes = set() datatype_infos = [] for connection in self._connections.values(): if connection.datatype in datatypes: continue datatype_infos.append((connection.datatype, connection.md5sum, connection.msg_def)) datatypes.add(connection.datatype) topics = sorted(set([c.topic for c in self._get_connections()])) topic_datatypes = {} topic_conn_counts = {} topic_msg_counts = {} topic_freqs_median = {} for topic in topics: connections = list(self._get_connections(topic)) topic_datatypes[topic] = connections[0].datatype topic_conn_counts[topic] = len(connections) msg_count = 0 for connection in connections: for chunk in self._chunks: msg_count += chunk.connection_counts.get(connection.id, 0) topic_msg_counts[topic] = msg_count if self._connection_indexes_read: stamps = [entry.time.to_sec() for entry in self._get_entries(connections)] if len(stamps) > 1: periods = [s1 - s0 for s1, s0 in zip(stamps[1:], stamps[:-1])] med_period = _median(periods) if med_period > 0.0: topic_freqs_median[topic] = 1.0 / med_period topics = sorted(topic_datatypes.keys()) max_topic_len = max([len(topic) for topic in topics]) max_datatype_len = max([len(datatype) for datatype in datatypes]) max_msg_count_len = max([len('%d' % msg_count) for msg_count in topic_msg_counts.values()]) max_freq_median_len = max([len(_human_readable_frequency(freq)) for freq in topic_freqs_median.values()]) if len(topic_freqs_median) > 0 else 0 # Show datatypes for i, (datatype, md5sum, msg_def) in enumerate(sorted(datatype_infos)): s = '%-*s [%s]' % (max_datatype_len, datatype, md5sum) if i == 0: rows.append(('types', s)) else: rows.append(('', s)) # Show topics for i, topic in enumerate(topics): topic_msg_count = topic_msg_counts[topic] s = '%-*s %*d %s' % (max_topic_len, topic, max_msg_count_len, topic_msg_count, 'msgs' if topic_msg_count > 1 else 'msg ') if topic in topic_freqs_median: s += ' @ %*s' % (max_freq_median_len, _human_readable_frequency(topic_freqs_median[topic])) else: s += ' %*s' % (max_freq_median_len, '') s += ' : %-*s' % (max_datatype_len, topic_datatypes[topic]) if topic_conn_counts[topic] > 1: s += ' (%d connections)' % topic_conn_counts[topic] if i == 0: rows.append(('topics', s)) else: rows.append(('', s)) except Exception as ex: raise first_column_width = max([len(field) for field, _ in rows]) + 1 s = '' for (field, value) in rows: if field: s += '%-*s %s\n' % (first_column_width, field + ':', value) else: s += '%-*s %s\n' % (first_column_width, '', value) return s.rstrip() def _get_yaml_info(self, key=None): s = '' try: if self._filename: s += 'path: %s\n' % self._filename if self._version == 102 and type(self._reader) == _BagReader102_Unindexed: s += 'version: 1.2 (unindexed)\n' else: s += 'version: %d.%d\n' % (int(self._version / 100), self._version % 100) if not self._connection_indexes and not self._chunks: s += 'size: %d\n' % self.size s += 'indexed: False\n' else: if self._chunks: start_stamp = self._chunks[ 0].start_time.to_sec() end_stamp = self._chunks[-1].end_time.to_sec() else: start_stamp = min([index[ 0].time.to_sec() for index in self._connection_indexes.values()]) end_stamp = max([index[-1].time.to_sec() for index in self._connection_indexes.values()]) duration = end_stamp - start_stamp s += 'duration: %.6f\n' % duration s += 'start: %.6f\n' % start_stamp s += 'end: %.6f\n' % end_stamp s += 'size: %d\n' % self.size if self._chunks: num_messages = 0 for c in self._chunks: for counts in c.connection_counts.values(): num_messages += counts else: num_messages = sum([len(index) for index in self._connection_indexes.values()]) s += 'messages: %d\n' % num_messages s += 'indexed: True\n' # Show compression information if len(self._chunk_headers) == 0: s += 'compression: none\n' else: compression_counts = {} compression_uncompressed = {} compression_compressed = {} for chunk_header in self._chunk_headers.values(): if chunk_header.compression not in compression_counts: compression_counts[chunk_header.compression] = 1 compression_uncompressed[chunk_header.compression] = chunk_header.uncompressed_size compression_compressed[chunk_header.compression] = chunk_header.compressed_size else: compression_counts[chunk_header.compression] += 1 compression_uncompressed[chunk_header.compression] += chunk_header.uncompressed_size compression_compressed[chunk_header.compression] += chunk_header.compressed_size chunk_count = len(self._chunk_headers) main_compression_count, main_compression = list(reversed(sorted([(v, k) for k, v in compression_counts.items()])))[0] s += 'compression: %s\n' % str(main_compression) all_uncompressed = (sum([count for c, count in compression_counts.items() if c != Compression.NONE]) == 0) if not all_uncompressed: s += 'uncompressed: %d\n' % sum((h.uncompressed_size for h in self._chunk_headers.values())) s += 'compressed: %d\n' % sum((h.compressed_size for h in self._chunk_headers.values())) datatypes = set() datatype_infos = [] for connection in self._connections.values(): if connection.datatype in datatypes: continue datatype_infos.append((connection.datatype, connection.md5sum, connection.msg_def)) datatypes.add(connection.datatype) topics = sorted(set([c.topic for c in self._get_connections()])) topic_datatypes = {} topic_conn_counts = {} topic_msg_counts = {} topic_freqs_median = {} for topic in topics: connections = list(self._get_connections(topic)) topic_datatypes[topic] = connections[0].datatype topic_conn_counts[topic] = len(connections) msg_count = 0 for connection in connections: for chunk in self._chunks: msg_count += chunk.connection_counts.get(connection.id, 0) topic_msg_counts[topic] = msg_count if self._connection_indexes_read: stamps = [entry.time.to_sec() for entry in self._get_entries(connections)] if len(stamps) > 1: periods = [s1 - s0 for s1, s0 in zip(stamps[1:], stamps[:-1])] med_period = _median(periods) if med_period > 0.0: topic_freqs_median[topic] = 1.0 / med_period topics = sorted(topic_datatypes.keys()) max_topic_len = max([len(topic) for topic in topics]) max_datatype_len = max([len(datatype) for datatype in datatypes]) max_msg_count_len = max([len('%d' % msg_count) for msg_count in topic_msg_counts.values()]) max_freq_median_len = max([len(_human_readable_frequency(freq)) for freq in topic_freqs_median.values()]) if len(topic_freqs_median) > 0 else 0 # Show datatypes s += 'types:\n' for i, (datatype, md5sum, msg_def) in enumerate(sorted(datatype_infos)): s += ' - type: %s\n' % datatype s += ' md5: %s\n' % md5sum # Show topics s += 'topics:\n' for i, topic in enumerate(topics): topic_msg_count = topic_msg_counts[topic] s += ' - topic: %s\n' % topic s += ' type: %s\n' % topic_datatypes[topic] s += ' messages: %d\n' % topic_msg_count if topic_conn_counts[topic] > 1: s += ' connections: %d\n' % topic_conn_counts[topic] if topic in topic_freqs_median: s += ' frequency: %.4f\n' % topic_freqs_median[topic] if not key: return s class DictObject(object): def __init__(self, d): for a, b in d.items(): if isinstance(b, (list, tuple)): setattr(self, a, [DictObject(x) if isinstance(x, dict) else x for x in b]) else: setattr(self, a, DictObject(b) if isinstance(b, dict) else b) obj = DictObject(yaml.load(s)) try: val = eval('obj.' + key) except Exception as ex: print('Error getting key "%s"' % key, file=sys.stderr) return None def print_yaml(val, indent=0): indent_str = ' ' * indent if type(val) is list: s = '' for item in val: s += '%s- %s\n' % (indent_str, print_yaml(item, indent + 1)) return s elif type(val) is DictObject: s = '' for i, (k, v) in enumerate(val.__dict__.items()): if i != 0: s += indent_str s += '%s: %s' % (k, str(v)) if i < len(val.__dict__) - 1: s += '\n' return s else: return indent_str + str(val) return print_yaml(val) except Exception as ex: raise ### Internal API ### @property def _has_compressed_chunks(self): if not self._chunk_headers: return False return any((h.compression != Compression.NONE for h in self._chunk_headers.values())) @property def _uncompressed_size(self): if not self._chunk_headers: return self.size return sum((h.uncompressed_size for h in self._chunk_headers.values())) def _read_message(self, position, raw=False): """ Read the message from the given position in the file. """ self.flush() return self._reader.seek_and_read_message_data_record(position, raw) # Index accessing def _get_connections(self, topics=None, connection_filter=None): """ Yield the connections, optionally filtering by topic and/or connection information. """ if topics: if type(topics) is str: topics = set([roslib.names.canonicalize_name(topics)]) else: topics = set([roslib.names.canonicalize_name(t) for t in topics]) for c in self._connections.values(): if topics and c.topic not in topics and roslib.names.canonicalize_name(c.topic) not in topics: continue if connection_filter and not connection_filter(c.topic, c.datatype, c.md5sum, c.msg_def, c.header): continue yield c def _get_entries(self, connections=None, start_time=None, end_time=None): """ Yield index entries on the given connections in the given time range. """ for entry, _ in _mergesort(self._get_indexes(connections), key=lambda entry: entry.time): if start_time and entry.time < start_time: continue if end_time and entry.time > end_time: return yield entry def _get_entries_reverse(self, connections=None, start_time=None, end_time=None): """ Yield index entries on the given connections in the given time range in reverse order. """ for entry, _ in _mergesort((reversed(index) for index in self._get_indexes(connections)), key=lambda entry: -entry.time.to_sec()): if end_time and entry.time > end_time: continue if start_time and entry.time < start_time: return yield entry def _get_entry(self, t, connections=None): """ Return the first index entry on/before the given time on the given connections """ indexes = self._get_indexes(connections) entry = _IndexEntry(t) first_entry = None for index in indexes: i = bisect.bisect_right(index, entry) - 1 if i >= 0: index_entry = index[i] if first_entry is None or index_entry > first_entry: first_entry = index_entry return first_entry def _get_entry_after(self, t, connections=None): """ Return the first index entry after the given time on the given connections """ indexes = self._get_indexes(connections) entry = _IndexEntry(t) first_entry = None for index in indexes: i = bisect.bisect_right(index, entry) if i <= len(index) - 1: index_entry = index[i] if first_entry is None or index_entry < first_entry: first_entry = index_entry return first_entry def _get_indexes(self, connections): """ Get the indexes for the given connections. """ if not self._connection_indexes_read: self._reader._read_connection_index_records() if connections is None: return self._connection_indexes.values() else: return (self._connection_indexes[c.id] for c in connections) ### Implementation ### def _clear_index(self): self._connection_indexes_read = False self._connection_indexes = {} # id -> IndexEntry[] (1.2+) self._topic_connections = {} # topic -> connection_id self._connections = {} # id -> ConnectionInfo self._connection_count = 0 # (2.0) self._chunk_count = 0 # (2.0) self._chunks = [] # ChunkInfo[] (2.0) self._chunk_headers = {} # chunk_pos -> ChunkHeader (2.0) self._chunk_open = False self._curr_chunk_info = None self._curr_chunk_data_pos = None self._curr_chunk_connection_indexes = {} def _open(self, f, mode, allow_unindexed): if not f: raise ValueError('filename (or stream) is invalid') try: if mode == 'r': self._open_read(f, allow_unindexed) elif mode == 'w': self._open_write(f) elif mode == 'a': self._open_append(f, allow_unindexed) else: raise ValueError('mode "%s" is invalid' % mode) if 'b' not in self._file.mode and not isinstance('', bytes): raise ROSBagException('In Python 3 the bag file must be opened in binary mode') except struct.error: raise ROSBagFormatException('error with bag') def _is_file(self, f): try: return isinstance(f, file) # Python 2 except NameError: import io return isinstance(f, io.IOBase) # Python 3...this will return false in Python 2 always def _open_read(self, f, allow_unindexed): if self._is_file(f): self._file = f self._filename = None else: self._file = open(f, 'rb') self._filename = f self._mode = 'r' try: self._version = self._read_version() except: self._version = None self._close_file() raise try: self._create_reader() self._reader.start_reading() except ROSBagUnindexedException as ex: if not allow_unindexed: self._close_file() raise except: self._close_file() raise def _open_write(self, f): if self._is_file(f): self._file = f self._filename = None else: self._file = open(f, 'w+b') self._filename = f self._mode = 'w' self._version = 200 try: self._create_reader() self._start_writing() except: self._close_file() raise def _open_append(self, f, allow_unindexed): if self._is_file(f): self._file = f self._filename = None else: try: # Test if the file already exists open(f, 'r').close() # File exists: open in read with update mode self._file = open(f, 'r+b') except IOError: # File doesn't exist: open in write mode self._file = open(f, 'w+b') self._filename = f self._mode = 'a' try: self._version = self._read_version() except: self._version = None self._close_file() raise if self._version != 200: self._file.close() raise ROSBagException('bag version %d is unsupported for appending' % self._version) try: self._start_appending() except ROSBagUnindexedException: if not allow_unindexed: self._close_file() raise except: self._close_file() raise def _close_file(self): self._file.close() self._file = None def _create_reader(self): """ @raise ROSBagException: if the bag version is unsupported """ major_version, minor_version = int(self._version / 100), self._version % 100 if major_version == 2: self._reader = _BagReader200(self) elif major_version == 1: if minor_version == 1: raise ROSBagException('unsupported bag version %d. Please convert bag to newer format.' % self._version) else: # Get the op code of the first record. If it's FILE_HEADER, then we have an indexed 1.2 bag. first_record_pos = self._file.tell() header = _read_header(self._file) op = _read_uint8_field(header, 'op') self._file.seek(first_record_pos) if op == _OP_FILE_HEADER: self._reader = _BagReader102_Indexed(self) else: self._reader = _BagReader102_Unindexed(self) else: raise ROSBagException('unknown bag version %d' % self._version) def _read_version(self): """ @raise ROSBagException: if the file is empty, or the version line can't be parsed """ version_line = self._file.readline().rstrip().decode() if len(version_line) == 0: raise ROSBagException('empty file') matches = re.match("#ROS(.*) V(\d).(\d)", version_line) if matches is None or len(matches.groups()) != 3: raise ROSBagException('This does not appear to be a bag file') version_type, major_version_str, minor_version_str = matches.groups() version = int(major_version_str) * 100 + int(minor_version_str) return version def _start_writing(self): version = _VERSION + '\n' version = version.encode() self._file.write(version) self._file_header_pos = self._file.tell() self._write_file_header_record(0, 0, 0) def _stop_writing(self): # Write the open chunk (if any) to file self.flush() # Remember this location as the start of the index self._index_data_pos = self._file.tell() # Write connection infos for connection_info in self._connections.values(): self._write_connection_record(connection_info) # Write chunk infos for chunk_info in self._chunks: self._write_chunk_info_record(chunk_info) # Re-write the file header self._file.seek(self._file_header_pos) self._write_file_header_record(self._index_data_pos, len(self._connections), len(self._chunks)) def _start_appending(self): self._file_header_pos = self._file.tell() self._create_reader() self._reader.start_reading() # Truncate the file to chop off the index self._file.truncate(self._index_data_pos) self._reader.index_data_pos = 0 # Rewrite the file header, clearing the index position (so we know if the index is invalid) self._file.seek(self._file_header_pos); self._write_file_header_record(0, 0, 0) # Seek to the end of the file self._file.seek(0, os.SEEK_END) def _start_writing_chunk(self, t): self._curr_chunk_info = _ChunkInfo(self._file.tell(), t, t) self._write_chunk_header(_ChunkHeader(self._compression, 0, 0)) self._curr_chunk_data_pos = self._file.tell() self._set_compression_mode(self._compression) self._chunk_open = True def _get_chunk_offset(self): if self._compression == Compression.NONE: return self._file.tell() - self._curr_chunk_data_pos else: return self._output_file.compressed_bytes_in def _stop_writing_chunk(self): # Add this chunk to the index self._chunks.append(self._curr_chunk_info) # Get the uncompressed and compressed sizes uncompressed_size = self._get_chunk_offset() self._set_compression_mode(Compression.NONE) compressed_size = self._file.tell() - self._curr_chunk_data_pos # Rewrite the chunk header with the size of the chunk (remembering current offset) end_of_chunk_pos = self._file.tell() self._file.seek(self._curr_chunk_info.pos) chunk_header = _ChunkHeader(self._compression, compressed_size, uncompressed_size, self._curr_chunk_data_pos) self._write_chunk_header(chunk_header) self._chunk_headers[self._curr_chunk_info.pos] = chunk_header # Write out the connection indexes and clear them self._file.seek(end_of_chunk_pos) for connection_id, entries in self._curr_chunk_connection_indexes.items(): self._write_connection_index_record(connection_id, entries) self._curr_chunk_connection_indexes.clear() # Flag that we're starting a new chunk self._chunk_open = False def _set_compression_mode(self, compression): # Flush the compressor, if needed if self._curr_compression != Compression.NONE: self._output_file.flush() # Create the compressor if compression == Compression.BZ2: self._output_file = _CompressorFileFacade(self._file, bz2.BZ2Compressor()) elif compression == Compression.LZ4 and found_lz4: self._output_file = _CompressorFileFacade(self._file, roslz4.LZ4Compressor()) elif compression == Compression.NONE: self._output_file = self._file else: raise ROSBagException('unsupported compression type: %s' % compression) self._curr_compression = compression def _write_file_header_record(self, index_pos, connection_count, chunk_count): header = { 'op': _pack_uint8(_OP_FILE_HEADER), 'index_pos': _pack_uint64(index_pos), 'conn_count': _pack_uint32(connection_count), 'chunk_count': _pack_uint32(chunk_count) } _write_record(self._file, header, padded_size=_FILE_HEADER_LENGTH) def _write_connection_record(self, connection_info): header = { 'op': _pack_uint8(_OP_CONNECTION), 'topic': connection_info.topic, 'conn': _pack_uint32(connection_info.id) } _write_header(self._output_file, header) _write_header(self._output_file, connection_info.header) def _write_message_data_record(self, connection_id, t, serialized_bytes): header = { 'op': _pack_uint8(_OP_MSG_DATA), 'conn': _pack_uint32(connection_id), 'time': _pack_time(t) } _write_record(self._output_file, header, serialized_bytes) def _write_chunk_header(self, chunk_header): header = { 'op': _pack_uint8(_OP_CHUNK), 'compression': chunk_header.compression, 'size': _pack_uint32(chunk_header.uncompressed_size) } _write_header(self._file, header) self._file.write(_pack_uint32(chunk_header.compressed_size)) def _write_connection_index_record(self, connection_id, entries): header = { 'op': _pack_uint8(_OP_INDEX_DATA), 'conn': _pack_uint32(connection_id), 'ver': _pack_uint32(_INDEX_VERSION), 'count': _pack_uint32(len(entries)) } buffer = self._buffer buffer.seek(0) buffer.truncate(0) for entry in entries: buffer.write(_pack_time (entry.time)) buffer.write(_pack_uint32(entry.offset)) _write_record(self._file, header, buffer.getvalue()) def _write_chunk_info_record(self, chunk_info): header = { 'op': _pack_uint8 (_OP_CHUNK_INFO), 'ver': _pack_uint32(_CHUNK_INDEX_VERSION), 'chunk_pos': _pack_uint64(chunk_info.pos), 'start_time': _pack_time(chunk_info.start_time), 'end_time': _pack_time(chunk_info.end_time), 'count': _pack_uint32(len(chunk_info.connection_counts)) } buffer = self._buffer buffer.seek(0) buffer.truncate(0) for connection_id, count in chunk_info.connection_counts.items(): buffer.write(_pack_uint32(connection_id)) buffer.write(_pack_uint32(count)) _write_record(self._file, header, buffer.getvalue()) ### Implementation ### _message_types = {} # md5sum -> type _OP_MSG_DEF = 0x01 _OP_MSG_DATA = 0x02 _OP_FILE_HEADER = 0x03 _OP_INDEX_DATA = 0x04 _OP_CHUNK = 0x05 _OP_CHUNK_INFO = 0x06 _OP_CONNECTION = 0x07 _OP_CODES = { _OP_MSG_DEF: 'MSG_DEF', _OP_MSG_DATA: 'MSG_DATA', _OP_FILE_HEADER: 'FILE_HEADER', _OP_INDEX_DATA: 'INDEX_DATA', _OP_CHUNK: 'CHUNK', _OP_CHUNK_INFO: 'CHUNK_INFO', _OP_CONNECTION: 'CONNECTION' } _VERSION = '#ROSBAG V2.0' _FILE_HEADER_LENGTH = 4096 _INDEX_VERSION = 1 _CHUNK_INDEX_VERSION = 1 class _ConnectionInfo(object): def __init__(self, id, topic, header): try: datatype = _read_str_field(header, 'type') md5sum = _read_str_field(header, 'md5sum') msg_def = _read_str_field(header, 'message_definition') except KeyError as ex: raise ROSBagFormatException('connection header field %s not found' % str(ex)) self.id = id self.topic = topic self.datatype = datatype self.md5sum = md5sum self.msg_def = msg_def self.header = header def __str__(self): return '%d on %s: %s' % (self.id, self.topic, str(self.header)) class _ChunkInfo(object): def __init__(self, pos, start_time, end_time): self.pos = pos self.start_time = start_time self.end_time = end_time self.connection_counts = {} def __str__(self): s = 'chunk_pos: %d\n' % self.pos s += 'start_time: %s\n' % str(self.start_time) s += 'end_time: %s\n' % str(self.end_time) s += 'connections: %d\n' % len(self.connection_counts) s += '\n'.join([' - [%4d] %d' % (connection_id, count) for connection_id, count in self.connection_counts.items()]) return s class _ChunkHeader(object): def __init__(self, compression, compressed_size, uncompressed_size, data_pos=0): self.compression = compression self.compressed_size = compressed_size self.uncompressed_size = uncompressed_size self.data_pos = data_pos def __str__(self): if self.uncompressed_size > 0: ratio = 100 * (float(self.compressed_size) / self.uncompressed_size) return 'compression: %s, size: %d, uncompressed: %d (%.2f%%)' % (self.compression, self.compressed_size, self.uncompressed_size, ratio) else: return 'compression: %s, size: %d, uncompressed: %d' % (self.compression, self.compressed_size, self.uncompressed_size) class ComparableMixin(object): __slots__ = [] def _compare(self, other, method): try: return method(self._cmpkey(), other._cmpkey()) except (AttributeError, TypeError): # _cmpkey not implemented or return different type # so can not compare with other return NotImplemented def __lt__(self, other): return self._compare(other, lambda s, o: s < o) def __le__(self, other): return self._compare(other, lambda s, o: s <= o) def __eq__(self, other): return self._compare(other, lambda s, o: s == o) def __ge__(self, other): return self._compare(other, lambda s, o: s >= o) def __gt__(self, other): return self._compare(other, lambda s, o: s > o) def __ne__(self, other): return self._compare(other, lambda s, o: s != o) class _IndexEntry(ComparableMixin): __slots__ = ['time'] def __init__(self, time): self.time = time def _cmpkey(self): return self.time class _IndexEntry102(_IndexEntry): __slots__ = ['offset'] def __init__(self, time, offset): self.time = time self.offset = offset @property def position(self): return self.offset def __str__(self): return '%d.%d: %d' % (self.time.secs, self.time.nsecs, self.offset) class _IndexEntry200(_IndexEntry): __slots__ = ['chunk_pos', 'offset'] def __init__(self, time, chunk_pos, offset): self.time = time self.chunk_pos = chunk_pos self.offset = offset @property def position(self): return (self.chunk_pos, self.offset) def __str__(self): return '%d.%d: %d+%d' % (self.time.secs, self.time.nsecs, self.chunk_pos, self.offset) def _get_message_type(info): message_type = _message_types.get(info.md5sum) if message_type is None: try: if info.msg_def == 'protobuf': obj = __import__('pb_msgs.msg') message_type = getattr(obj.msg, info.datatype.split('/')[1]) roslib.message.add_rosmsg_interface_for_protobuf(message_type) else: message_type = genpy.dynamic.generate_dynamic(info.datatype, info.msg_def)[info.datatype] if (message_type._md5sum != info.md5sum): print('WARNING: For type [%s] stored md5sum [%s] does not match message definition [%s].\n Try: "rosrun rosbag fix_msg_defs.py old_bag new_bag."'%(info.datatype, info.md5sum, message_type._md5sum), file=sys.stderr) except genmsg.InvalidMsgSpec: message_type = genpy.dynamic.generate_dynamic(info.datatype, "")[info.datatype] print('WARNING: For type [%s] stored md5sum [%s] has invalid message definition."'%(info.datatype, info.md5sum), file=sys.stderr) except genmsg.MsgGenerationException as ex: raise ROSBagException('Error generating datatype %s: %s' % (info.datatype, str(ex))) _message_types[info.md5sum] = message_type return message_type def _read_uint8 (f): return _unpack_uint8 (f.read(1)) def _read_uint32(f): return _unpack_uint32(f.read(4)) def _read_uint64(f): return _unpack_uint64(f.read(8)) def _read_time (f): return _unpack_time (f.read(8)) def _unpack_uint8(v): return struct.unpack('<B', v)[0] def _unpack_uint32(v): return struct.unpack('<L', v)[0] def _unpack_uint64(v): return struct.unpack('<Q', v)[0] def _unpack_time(v): return rospy.Time(*struct.unpack('<LL', v)) def _pack_uint8(v): return struct.pack('<B', v) def _pack_uint32(v): return struct.pack('<L', v) def _pack_uint64(v): return struct.pack('<Q', v) def _pack_time(v): return _pack_uint32(v.secs) + _pack_uint32(v.nsecs) def _read(f, size): data = f.read(size) if len(data) != size: raise ROSBagException('expecting %d bytes, read %d' % (size, len(data))) return data def _skip_record(f): _skip_sized(f) # skip header _skip_sized(f) # skip data def _skip_sized(f): size = _read_uint32(f) f.seek(size, os.SEEK_CUR) def _read_sized(f): try: size = _read_uint32(f) except struct.error as ex: raise ROSBagFormatException('error unpacking uint32: %s' % str(ex)) return _read(f, size) def _write_sized(f, v): if not isinstance(v, bytes): v = v.encode() f.write(_pack_uint32(len(v))) f.write(v) def _read_field(header, field, unpack_fn): if field not in header: raise ROSBagFormatException('expected "%s" field in record' % field) try: value = unpack_fn(header[field]) except Exception as ex: raise ROSBagFormatException('error reading field "%s": %s' % (field, str(ex))) return value def _read_str_field (header, field): return _read_field(header, field, lambda v: v) def _read_uint8_field (header, field): return _read_field(header, field, _unpack_uint8) def _read_uint32_field(header, field): return _read_field(header, field, _unpack_uint32) def _read_uint64_field(header, field): return _read_field(header, field, _unpack_uint64) def _read_time_field (header, field): return _read_field(header, field, _unpack_time) def _write_record(f, header, data='', padded_size=None): header_str = _write_header(f, header) if padded_size is not None: header_len = len(header_str) if header_len < padded_size: data = ' ' * (padded_size - header_len) else: data = '' _write_sized(f, data) def _write_header(f, header): header_str = b'' equal = b'=' for k, v in header.items(): if not isinstance(k, bytes): k = k.encode() if not isinstance(v, bytes): v = v.encode() header_str += _pack_uint32(len(k) + 1 + len(v)) + k + equal + v _write_sized(f, header_str) return header_str def _read_header(f, req_op=None): bag_pos = f.tell() # Read header try: header = _read_sized(f) except ROSBagException as ex: raise ROSBagFormatException('Error reading header: %s' % str(ex)) # Parse header into a dict header_dict = {} while header != b'': # Read size if len(header) < 4: raise ROSBagFormatException('Error reading header field') (size,) = struct.unpack('<L', header[:4]) # @todo reindex: catch struct.error header = header[4:] # Read bytes if len(header) < size: raise ROSBagFormatException('Error reading header field: expected %d bytes, read %d' % (size, len(header))) (name, sep, value) = header[:size].partition(b'=') if sep == b'': raise ROSBagFormatException('Error reading header field') name = name.decode() header_dict[name] = value # @todo reindex: raise exception on empty name header = header[size:] # Check the op code of the header, if supplied if req_op is not None: op = _read_uint8_field(header_dict, 'op') if req_op != op: raise ROSBagFormatException('Expected op code: %s, got %s' % (_OP_CODES[req_op], _OP_CODES[op])) return header_dict def _peek_next_header_op(f): pos = f.tell() header = _read_header(f) op = _read_uint8_field(header, 'op') f.seek(pos) return op def _read_record_data(f): try: record_data = _read_sized(f) except ROSBagException as ex: raise ROSBagFormatException('Error reading record data: %s' % str(ex)) return record_data class _BagReader(object): def __init__(self, bag): self.bag = bag def start_reading(self): raise NotImplementedError() def read_messages(self, topics, start_time, end_time, connection_filter, raw): raise NotImplementedError() def reindex(self): raise NotImplementedError() class _BagReader102_Unindexed(_BagReader): """ Support class for reading unindexed v1.2 bag files. """ def __init__(self, bag): _BagReader.__init__(self, bag) def start_reading(self): self.bag._file_header_pos = self.bag._file.tell() def reindex(self): """Generates all bag index information by rereading the message records.""" f = self.bag._file total_bytes = self.bag.size # Re-read the file header to get to the start of the first message self.bag._file.seek(self.bag._file_header_pos) offset = f.tell() # Read message definition and data records while offset < total_bytes: yield offset op = _peek_next_header_op(f) if op == _OP_MSG_DEF: connection_info = self.read_message_definition_record() if connection_info.topic not in self.bag._topic_connections: self.bag._topic_connections[connection_info.topic] = connection_info.id self.bag._connections[connection_info.id] = connection_info self.bag._connection_indexes[connection_info.id] = [] elif op == _OP_MSG_DATA: # Read the topic and timestamp from the header header = _read_header(f) topic = _read_str_field(header, 'topic') secs = _read_uint32_field(header, 'sec') nsecs = _read_uint32_field(header, 'nsec') t = genpy.Time(secs, nsecs) if topic not in self.bag._topic_connections: datatype = _read_str_field(header, 'type') self._create_connection_info_for_datatype(topic, datatype) connection_id = self.bag._topic_connections[topic] info = self.bag._connections[connection_id] # Skip over the message content _skip_sized(f) # Insert the message entry (in order) into the connection index bisect.insort_right(self.bag._connection_indexes[connection_id], _IndexEntry102(t, offset)) offset = f.tell() def read_messages(self, topics, start_time, end_time, topic_filter, raw): f = self.bag._file f.seek(self.bag._file_header_pos) while True: # Read MSG_DEF records while True: position = f.tell() try: header = _read_header(f) except Exception: return op = _read_uint8_field(header, 'op') if op != _OP_MSG_DEF: break connection_info = self.read_message_definition_record(header) if connection_info.topic not in self.bag._topic_connections: self.bag._topic_connections[connection_info.topic] = connection_info.id self.bag._connections[connection_info.id] = connection_info # Check that we have a MSG_DATA record if op != _OP_MSG_DATA: raise ROSBagFormatException('Expecting OP_MSG_DATA, got %d' % op) topic = _read_str_field(header, 'topic') if topic not in self.bag._topic_connections: datatype = _read_str_field(header, 'type') self._create_connection_info_for_datatype(topic, datatype) connection_id = self.bag._topic_connections[topic] info = self.bag._connections[connection_id] # Get the message type try: msg_type = _get_message_type(info) except KeyError: raise ROSBagException('Cannot deserialize messages of type [%s]. Message was not preceeded in bagfile by definition' % info.datatype) # Get the timestamp secs = _read_uint32_field(header, 'sec') nsecs = _read_uint32_field(header, 'nsec') t = genpy.Time(secs, nsecs) # Read the message content data = _read_record_data(f) if raw: msg = (info.datatype, data, info.md5sum, position, msg_type) else: # Deserialize the message msg = msg_type() msg.deserialize(data) yield BagMessage(topic, msg, t) self.bag._connection_indexes_read = True def _create_connection_info_for_datatype(self, topic, datatype): for c in self.bag._connections.values(): if c.datatype == datatype: connection_id = len(self.bag._connections) connection_header = { 'topic' : topic, 'type' : c.header['type'], 'md5sum' : c.header['md5sum'], 'message_definition' : c.header['message_definition'] } connection_info = _ConnectionInfo(connection_id, topic, connection_header) self.bag._topic_connections[topic] = connection_id self.bag._connections[connection_id] = connection_info self.bag._connection_indexes[connection_id] = [] return raise ROSBagFormatException('Topic %s of datatype %s not preceded by message definition' % (topic, datatype)) def read_message_definition_record(self, header=None): if not header: header = _read_header(self.bag._file, _OP_MSG_DEF) topic = _read_str_field(header, 'topic') datatype = _read_str_field(header, 'type') md5sum = _read_str_field(header, 'md5') msg_def = _read_str_field(header, 'def') _skip_sized(self.bag._file) # skip the record data connection_header = { 'topic' : topic, 'type' : datatype, 'md5sum' : md5sum, 'message_definition' : msg_def } id = len(self.bag._connections) return _ConnectionInfo(id, topic, connection_header) class _BagReader102_Indexed(_BagReader102_Unindexed): """ Support class for reading indexed v1.2 bag files. """ def __init__(self, bag): _BagReader.__init__(self, bag) def read_messages(self, topics, start_time, end_time, connection_filter, raw): connections = self.bag._get_connections(topics, connection_filter) for entry in self.bag._get_entries(connections, start_time, end_time): yield self.seek_and_read_message_data_record(entry.offset, raw) def reindex(self): """Generates all bag index information by rereading the message records.""" f = self.bag._file total_bytes = self.bag.size # Re-read the file header to get to the start of the first message self.bag._file.seek(self.bag._file_header_pos) self.read_file_header_record() offset = f.tell() # Read message definition and data records while offset < total_bytes: yield offset op = _peek_next_header_op(f) if op == _OP_MSG_DEF: connection_info = self.read_message_definition_record() if connection_info.topic not in self.bag._topic_connections: self.bag._topic_connections[connection_info.topic] = connection_info.id self.bag._connections[connection_info.id] = connection_info self.bag._connection_indexes[connection_info.id] = [] elif op == _OP_MSG_DATA: # Read the topic and timestamp from the header header = _read_header(f) topic = _read_str_field(header, 'topic') secs = _read_uint32_field(header, 'sec') nsecs = _read_uint32_field(header, 'nsec') t = genpy.Time(secs, nsecs) if topic not in self.bag._topic_connections: datatype = _read_str_field(header, 'type') self._create_connection_info_for_datatype(topic, datatype) connection_id = self.bag._topic_connections[topic] info = self.bag._connections[connection_id] # Skip over the message content _skip_sized(f) # Insert the message entry (in order) into the connection index bisect.insort_right(self.bag._connection_indexes[connection_id], _IndexEntry102(t, offset)) elif op == _OP_INDEX_DATA: _skip_record(f) offset = f.tell() def start_reading(self): try: # Read the file header self.read_file_header_record() total_bytes = self.bag.size # Check if the index position has been written, i.e. the bag was closed successfully if self.bag._index_data_pos == 0: raise ROSBagUnindexedException() # Seek to the beginning of the topic index records self.bag._file.seek(self.bag._index_data_pos) # Read the topic indexes topic_indexes = {} while True: pos = self.bag._file.tell() if pos >= total_bytes: break topic, index = self.read_topic_index_record() topic_indexes[topic] = index # Read the message definition records (one for each topic) for topic, index in topic_indexes.items(): self.bag._file.seek(index[0].offset) connection_info = self.read_message_definition_record() if connection_info.topic not in self.bag._topic_connections: self.bag._topic_connections[connection_info.topic] = connection_info.id self.bag._connections[connection_info.id] = connection_info self.bag._connection_indexes[connection_info.id] = index self.bag._connection_indexes_read = True except Exception as ex: raise ROSBagUnindexedException() def read_file_header_record(self): self.bag._file_header_pos = self.bag._file.tell() header = _read_header(self.bag._file, _OP_FILE_HEADER) self.bag._index_data_pos = _read_uint64_field(header, 'index_pos') _skip_sized(self.bag._file) # skip the record data, i.e. padding def read_topic_index_record(self): f = self.bag._file header = _read_header(f, _OP_INDEX_DATA) index_version = _read_uint32_field(header, 'ver') topic = _read_str_field (header, 'topic') count = _read_uint32_field(header, 'count') if index_version != 0: raise ROSBagFormatException('expecting index version 0, got %d' % index_version) _read_uint32(f) # skip the record data size topic_index = [] for i in range(count): time = _read_time (f) offset = _read_uint64(f) topic_index.append(_IndexEntry102(time, offset)) return (topic, topic_index) def seek_and_read_message_data_record(self, position, raw): f = self.bag._file # Seek to the message position f.seek(position) # Skip any MSG_DEF records while True: header = _read_header(f) op = _read_uint8_field(header, 'op') if op != _OP_MSG_DEF: break _skip_sized(f) # Check that we have a MSG_DATA record if op != _OP_MSG_DATA: raise ROSBagFormatException('Expecting OP_MSG_DATA, got %d' % op) topic = _read_str_field(header, 'topic') connection_id = self.bag._topic_connections[topic] info = self.bag._connections[connection_id] # Get the message type try: msg_type = _get_message_type(info) except KeyError: raise ROSBagException('Cannot deserialize messages of type [%s]. Message was not preceeded in bagfile by definition' % info.datatype) # Get the timestamp secs = _read_uint32_field(header, 'sec') nsecs = _read_uint32_field(header, 'nsec') t = genpy.Time(secs, nsecs) # Read the message content data = _read_record_data(f) if raw: msg = info.datatype, data, info.md5sum, position, msg_type else: # Deserialize the message msg = msg_type() msg.deserialize(data) return BagMessage(topic, msg, t) class _BagReader200(_BagReader): """ Support class for reading v2.0 bag files. """ def __init__(self, bag): _BagReader.__init__(self, bag) self.decompressed_chunk_pos = None self.decompressed_chunk = None self.decompressed_chunk_io = None def reindex(self): """ Generates all bag index information by rereading the chunks. Assumes the file header has been read. """ f = self.bag._file f.seek(0, os.SEEK_END) total_bytes = f.tell() # Read any connection records from after the chunk section. # This is to workaround a bug in rosbag record --split (fixed in r10390) # where connection records weren't always being written inside the chunk. self._read_terminal_connection_records() # Re-read the file header to get to the start of the first chunk self.bag._file.seek(self.bag._file_header_pos) self.read_file_header_record() trunc_pos = None while True: chunk_pos = f.tell() if chunk_pos >= total_bytes: break yield chunk_pos try: self._reindex_read_chunk(f, chunk_pos, total_bytes) except Exception as ex: break trunc_pos = f.tell() if trunc_pos and trunc_pos < total_bytes: f.truncate(trunc_pos) def _reindex_read_chunk(self, f, chunk_pos, total_bytes): # Read the chunk header chunk_header = self.read_chunk_header() # If the chunk header size is 0, then the chunk wasn't correctly terminated - we're done if chunk_header.compressed_size == 0: raise ROSBagException('unterminated chunk at %d' % chunk_pos) if chunk_header.compression == Compression.NONE: chunk_file = f else: # Read the compressed chunk compressed_chunk = _read(f, chunk_header.compressed_size) # Decompress it if chunk_header.compression == Compression.BZ2: self.decompressed_chunk = bz2.decompress(compressed_chunk) elif chunk_header.compression == Compression.LZ4 and found_lz4: self.decompressed_chunk = roslz4.decompress(compressed_chunk) else: raise ROSBagException('unsupported compression type: %s' % chunk_header.compression) if self.decompressed_chunk_io: self.decompressed_chunk_io.close() self.decompressed_chunk_io = StringIO(self.decompressed_chunk) chunk_file = self.decompressed_chunk_io # Read chunk connection and message records self.bag._curr_chunk_info = None if chunk_header.compression == Compression.NONE: offset = chunk_file.tell() - chunk_pos else: offset = chunk_file.tell() expected_index_length = 0 while offset < chunk_header.uncompressed_size: op = _peek_next_header_op(chunk_file) if op == _OP_CONNECTION: connection_info = self.read_connection_record(chunk_file) if connection_info.id not in self.bag._connections: self.bag._connections[connection_info.id] = connection_info if connection_info.id not in self.bag._connection_indexes: self.bag._connection_indexes[connection_info.id] = [] elif op == _OP_MSG_DATA: # Read the connection id and timestamp from the header header = _read_header(chunk_file) connection_id = _read_uint32_field(header, 'conn') t = _read_time_field (header, 'time') # Update the chunk info with this timestamp if not self.bag._curr_chunk_info: self.bag._curr_chunk_info = _ChunkInfo(chunk_pos, t, t) else: if t > self.bag._curr_chunk_info.end_time: self.bag._curr_chunk_info.end_time = t elif t < self.bag._curr_chunk_info.start_time: self.bag._curr_chunk_info.start_time = t if connection_id in self.bag._curr_chunk_info.connection_counts: self.bag._curr_chunk_info.connection_counts[connection_id] += 1 else: self.bag._curr_chunk_info.connection_counts[connection_id] = 1 # Skip over the message content _skip_sized(chunk_file) # Insert the message entry (in order) into the connection index if connection_id not in self.bag._connection_indexes: raise ROSBagException('connection id (id=%d) in chunk at position %d not preceded by connection record' % (connection_id, chunk_pos)) bisect.insort_right(self.bag._connection_indexes[connection_id], _IndexEntry200(t, chunk_pos, offset)) expected_index_length += 1 else: # Unknown record type so skip _skip_record(chunk_file) if chunk_header.compression == Compression.NONE: offset = chunk_file.tell() - chunk_pos else: offset = chunk_file.tell() # Skip over index records, connection records and chunk info records next_op = _peek_next_header_op(f) total_index_length = 0 while next_op != _OP_CHUNK: if next_op == _OP_INDEX_DATA: # Bug workaround: C Turtle bags (pre-1.1.15) were written with an incorrect data length _, index = self.read_connection_index_record() total_index_length += len(index) else: _skip_record(f) if f.tell() >= total_bytes: if total_index_length != expected_index_length: raise ROSBagException('index shorter than expected (%d vs %d)' % (total_index_length, expected_index_length)) break next_op = _peek_next_header_op(f) # Chunk was read correctly - store info self.bag._chunk_headers[chunk_pos] = chunk_header self.bag._chunks.append(self.bag._curr_chunk_info) def _read_terminal_connection_records(self): b, f, r = self.bag, self.bag._file, self.bag._reader # Seek to the first record after FILE_HEADER f.seek(b._file_header_pos) r.read_file_header_record() # Advance to the first CONNECTION if self._advance_to_next_record(_OP_CONNECTION): # Read the CONNECTION records while True: connection_info = r.read_connection_record(f) b._connections[connection_info.id] = connection_info b._connection_indexes[connection_info.id] = [] next_op = _peek_next_header_op(f) if next_op != _OP_CONNECTION: break def _advance_to_next_record(self, op): b, f = self.bag, self.bag._file try: while True: next_op = _peek_next_header_op(f) if next_op == op: break if next_op == _OP_INDEX_DATA: # Workaround the possible invalid data length in INDEX_DATA records # read_connection_index_record() requires _curr_chunk_info is set if b._curr_chunk_info is None: b._curr_chunk_info = _ChunkInfo(0, rospy.Time(0, 1), rospy.Time(0, 1)) b._reader.read_connection_index_record() else: _skip_record(f) return True except Exception as ex: return False def start_reading(self): try: # Read the file header self.read_file_header_record() # Check if the index position has been written, i.e. the bag was closed successfully if self.bag._index_data_pos == 0: raise ROSBagUnindexedException() # Seek to the end of the chunks self.bag._file.seek(self.bag._index_data_pos) # Read the connection records self.bag._connection_indexes = {} for i in range(self.bag._connection_count): connection_info = self.read_connection_record(self.bag._file) self.bag._connections[connection_info.id] = connection_info self.bag._connection_indexes[connection_info.id] = [] # Read the chunk info records self.bag._chunks = [self.read_chunk_info_record() for i in range(self.bag._chunk_count)] # Read the chunk headers self.bag._chunk_headers = {} for chunk_info in self.bag._chunks: self.bag._file.seek(chunk_info.pos) self.bag._chunk_headers[chunk_info.pos] = self.read_chunk_header() if not self.bag._skip_index: self._read_connection_index_records() except Exception as ex: raise ROSBagUnindexedException() def _read_connection_index_records(self): for chunk_info in self.bag._chunks: self.bag._file.seek(chunk_info.pos) _skip_record(self.bag._file) self.bag._curr_chunk_info = chunk_info for i in range(len(chunk_info.connection_counts)): connection_id, index = self.read_connection_index_record() self.bag._connection_indexes[connection_id].extend(index) # Remove any connections with no entries # This is a workaround for a bug where connection records were being written for # connections which had no messages in the bag orphan_connection_ids = [id for id, index in self.bag._connection_indexes.items() if not index] for id in orphan_connection_ids: del self.bag._connections[id] del self.bag._connection_indexes[id] self.bag._connection_indexes_read = True def read_messages(self, topics, start_time, end_time, connection_filter, raw): connections = self.bag._get_connections(topics, connection_filter) for entry in self.bag._get_entries(connections, start_time, end_time): yield self.seek_and_read_message_data_record((entry.chunk_pos, entry.offset), raw) ### def read_file_header_record(self): self.bag._file_header_pos = self.bag._file.tell() header = _read_header(self.bag._file, _OP_FILE_HEADER) self.bag._index_data_pos = _read_uint64_field(header, 'index_pos') self.bag._chunk_count = _read_uint32_field(header, 'chunk_count') self.bag._connection_count = _read_uint32_field(header, 'conn_count') _skip_sized(self.bag._file) # skip over the record data, i.e. padding def read_connection_record(self, f): header = _read_header(f, _OP_CONNECTION) conn_id = _read_uint32_field(header, 'conn') topic = _read_str_field (header, 'topic') connection_header = _read_header(f) return _ConnectionInfo(conn_id, topic, connection_header) def read_chunk_info_record(self): f = self.bag._file header = _read_header(f, _OP_CHUNK_INFO) chunk_info_version = _read_uint32_field(header, 'ver') if chunk_info_version == 1: chunk_pos = _read_uint64_field(header, 'chunk_pos') start_time = _read_time_field (header, 'start_time') end_time = _read_time_field (header, 'end_time') connection_count = _read_uint32_field(header, 'count') chunk_info = _ChunkInfo(chunk_pos, start_time, end_time) _read_uint32(f) # skip the record data size for i in range(connection_count): connection_id = _read_uint32(f) count = _read_uint32(f) chunk_info.connection_counts[connection_id] = count return chunk_info else: raise ROSBagFormatException('Unknown chunk info record version: %d' % chunk_info_version) def read_chunk_header(self): header = _read_header(self.bag._file, _OP_CHUNK) compression = _read_str_field (header, 'compression') uncompressed_size = _read_uint32_field(header, 'size') compressed_size = _read_uint32(self.bag._file) # read the record data size data_pos = self.bag._file.tell() return _ChunkHeader(compression, compressed_size, uncompressed_size, data_pos) def read_connection_index_record(self): f = self.bag._file header = _read_header(f, _OP_INDEX_DATA) index_version = _read_uint32_field(header, 'ver') connection_id = _read_uint32_field(header, 'conn') count = _read_uint32_field(header, 'count') if index_version != 1: raise ROSBagFormatException('expecting index version 1, got %d' % index_version) record_size = _read_uint32(f) # skip the record data size index = [] for i in range(count): time = _read_time (f) offset = _read_uint32(f) index.append(_IndexEntry200(time, self.bag._curr_chunk_info.pos, offset)) return (connection_id, index) def seek_and_read_message_data_record(self, position, raw): chunk_pos, offset = position chunk_header = self.bag._chunk_headers.get(chunk_pos) if chunk_header is None: raise ROSBagException('no chunk at position %d' % chunk_pos) if chunk_header.compression == Compression.NONE: f = self.bag._file f.seek(chunk_header.data_pos + offset) else: if self.decompressed_chunk_pos != chunk_pos: # Seek to the chunk data, read and decompress self.bag._file.seek(chunk_header.data_pos) compressed_chunk = _read(self.bag._file, chunk_header.compressed_size) if chunk_header.compression == Compression.BZ2: self.decompressed_chunk = bz2.decompress(compressed_chunk) elif chunk_header.compression == Compression.LZ4 and found_lz4: self.decompressed_chunk = roslz4.decompress(compressed_chunk) else: raise ROSBagException('unsupported compression type: %s' % chunk_header.compression) self.decompressed_chunk_pos = chunk_pos if self.decompressed_chunk_io: self.decompressed_chunk_io.close() self.decompressed_chunk_io = StringIO(self.decompressed_chunk) f = self.decompressed_chunk_io f.seek(offset) # Skip any CONNECTION records while True: header = _read_header(f) op = _read_uint8_field(header, 'op') if op != _OP_CONNECTION: break _skip_sized(f) # Check that we have a MSG_DATA record if op != _OP_MSG_DATA: raise ROSBagFormatException('Expecting OP_MSG_DATA, got %d' % op) connection_id = _read_uint32_field(header, 'conn') t = _read_time_field (header, 'time') # Get the message type connection_info = self.bag._connections[connection_id] try: msg_type = _get_message_type(connection_info) except KeyError: raise ROSBagException('Cannot deserialize messages of type [%s]. Message was not preceded in bag by definition' % connection_info.datatype) # Read the message content data = _read_record_data(f) # Deserialize the message if raw: msg = connection_info.datatype, data, connection_info.md5sum, (chunk_pos, offset), msg_type else: msg = msg_type() msg.deserialize(data) return BagMessage(connection_info.topic, msg, t) def _time_to_str(secs): secs_frac = secs - int(secs) secs_frac_str = ('%.2f' % secs_frac)[1:] return time.strftime('%b %d %Y %H:%M:%S', time.localtime(secs)) + secs_frac_str def _human_readable_size(size): multiple = 1024.0 for suffix in ['KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']: size /= multiple if size < multiple: return '%.1f %s' % (size, suffix) return '-' def _human_readable_frequency(freq): multiple = 1000.0 for suffix in ['Hz', 'kHz', 'MHz', 'GHz', 'THz', 'PHz', 'EHz', 'ZHz', 'YHz']: if freq < multiple: return '%.1f %s' % (freq, suffix) freq /= multiple return '-' ## See http://code.activestate.com/recipes/511509 def _mergesort(list_of_lists, key=None): """ Perform an N-way merge operation on sorted lists. @param list_of_lists: (really iterable of iterable) of sorted elements (either by naturally or by C{key}) @param key: specify sort key function (like C{sort()}, C{sorted()}) @param iterfun: function that returns an iterator. Yields tuples of the form C{(item, iterator)}, where the iterator is the built-in list iterator or something you pass in, if you pre-generate the iterators. This is a stable merge; complexity O(N lg N) Examples:: print list(x[0] for x in mergesort([[1,2,3,4], [2,3.5,3.7,4.5,6,7], [2.6,3.6,6.6,9]])) [1, 2, 2, 2.6, 3, 3.5, 3.6, 3.7, 4, 4.5, 6, 6.6, 7, 9] # note stability print list(x[0] for x in mergesort([[1,2,3,4], [2,3.5,3.7,4.5,6,7], [2.6,3.6,6.6,9]], key=int)) [1, 2, 2, 2.6, 3, 3.5, 3.6, 3.7, 4, 4.5, 6, 6.6, 7, 9] print list(x[0] for x in mergesort([[4,3,2,1], [7,6.5,4,3.7,3.3,1.9], [9,8.6,7.6,6.6,5.5,4.4,3.3]], key=lambda x: -x)) [9, 8.6, 7.6, 7, 6.6, 6.5, 5.5, 4.4, 4, 4, 3.7, 3.3, 3.3, 3, 2, 1.9, 1] """ heap = [] for i, itr in enumerate(iter(pl) for pl in list_of_lists): try: item = next(itr) toadd = (key(item), i, item, itr) if key else (item, i, itr) heap.append(toadd) except StopIteration: pass heapq.heapify(heap) if key: while heap: _, idx, item, itr = heap[0] yield item, itr try: item = next(itr) heapq.heapreplace(heap, (key(item), idx, item, itr) ) except StopIteration: heapq.heappop(heap) else: while heap: item, idx, itr = heap[0] yield item, itr try: heapq.heapreplace(heap, (next(itr), idx, itr)) except StopIteration: heapq.heappop(heap) class _CompressorFileFacade(object): """ A file facade for sequential compressors (e.g., bz2.BZ2Compressor). """ def __init__(self, file, compressor): self.file = file self.compressor = compressor self.compressed_bytes_in = 0 def write(self, data): compressed = self.compressor.compress(data) if len(compressed) > 0: self.file.write(compressed) self.compressed_bytes_in += len(data) def flush(self): compressed = self.compressor.flush() if len(compressed) > 0: self.file.write(compressed) def _median(values): values_len = len(values) if values_len == 0: return float('nan') sorted_values = sorted(values) if values_len % 2 == 1: return sorted_values[int(values_len / 2)] lower = sorted_values[int(values_len / 2) - 1] upper = sorted_values[int(values_len / 2)] return float(lower + upper) / 2
0
apollo_public_repos/apollo-platform/ros/ros_comm/rosbag/src
apollo_public_repos/apollo-platform/ros/ros_comm/rosbag/src/rosbag/__init__.py
# 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. from .bag import Bag, Compression, ROSBagException, ROSBagFormatException, ROSBagUnindexedException # Import rosbag main to be used by the rosbag executable from .rosbag_main import rosbagmain
0
apollo_public_repos/apollo-platform/ros/ros_comm/rosbag/src
apollo_public_repos/apollo-platform/ros/ros_comm/rosbag/src/rosbag/migration.py
# 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. from __future__ import print_function import collections import copy try: from cStringIO import StringIO # Python 2.x except ImportError: from io import BytesIO as StringIO # Python 3.x import inspect import itertools import os import string import sys import genmsg.msgs import genpy import genpy.dynamic import rospkg import rosbag # Anything outside the scope of these primitives is a submessage #_PRIMITIVES = ['bool', 'byte','int8','int16','int32','int64','char','uint8','uint16','uint32','uint64','float32','float64','string','time'] class BagMigrationException(Exception): pass def checkbag(migrator, inbag): """ Check whether a bag file can be played in the current system. @param migrator: message migrator to use @param inbag name of the bag to be checked. @returns A list of tuples for each type in the bag file. The first element of each tuple is the full migration path for the type. The second element of the tuple is the expanded list of invalid rules for that particular path. """ checked = set() migrations = [] bag = rosbag.Bag(inbag, 'r') for topic, msg, t in bag.read_messages(raw=True): key = get_message_key(msg[4]) if key not in checked: target = migrator.find_target(msg[4]) # Even in the case of a zero-length path (matching md5sums), we still want # to migrate in the event of a type change (message move). path = migrator.find_path(msg[4], target) if len(path) > 0: migrations.append((path, [r for r in migrator.expand_rules([sn.rule for sn in path]) if r.valid == False])) checked.add(key) bag.close() return migrations def checkmessages(migrator, messages): """ Check whether a bag file can be played in the current system. @param migrator The message migrator to use @param message_list A list of message classes. @returns A list of tuples for each type in the bag file. The first element of each tuple is the full migration path for the type. The second element of the tuple is the expanded list of invalid rules for that particular path. """ checked = set() migrations = [] for msg in messages: key = get_message_key(msg) if key not in checked: target = migrator.find_target(msg) # Even in the case of a zero-length path (matching md5sums), we still want # to migrate in the event of a type change (message move). path = migrator.find_path(msg, target) if len(path) > 0: migrations.append((path, [r for r in migrator.expand_rules([sn.rule for sn in path]) if r.valid == False])) checked.add(key) return migrations ## Fix a bag so that it can be played in the current system # # @param migrator The message migrator to use # @param inbag Name of the bag to be fixed. # @param outbag Name of the bag to be saved. # @returns True if migration was successful. def fixbag(migrator, inbag, outbag): # This checks/builds up rules for the given migrator res = checkbag(migrator, inbag) # Deserializing all messages is inefficient, but we can speed this up later if not False in [m[1] == [] for m in res]: bag = rosbag.Bag(inbag, 'r') rebag = rosbag.Bag(outbag, 'w', options=bag.options) for topic, msg, t in bag.read_messages(raw=True): new_msg_type = migrator.find_target(msg[4]) mig_msg = migrator.migrate_raw(msg, (new_msg_type._type, None, new_msg_type._md5sum, None, new_msg_type)) rebag.write(topic, mig_msg, t, raw=True) rebag.close() bag.close() return True else: return False ## Fix a bag so that it can be played in the current system # # @param migrator The message migrator to use # @param inbag Name of the bag to be fixed. # @param outbag Name of the bag to be saved. # @returns [] if bag could be migrated, otherwise, it returns the list of necessary migration paths def fixbag2(migrator, inbag, outbag, force=False): # This checks/builds up rules for the given migrator res = checkbag(migrator, inbag) migrations = [m for m in res if len(m[1]) > 0] # Deserializing all messages is inefficient, but we can speed this up later if len(migrations) == 0 or force: bag = rosbag.Bag(inbag, 'r') rebag = rosbag.Bag(outbag, 'w', options=bag.options) for topic, msg, t in bag.read_messages(raw=True): new_msg_type = migrator.find_target(msg[4]) if new_msg_type != None: mig_msg = migrator.migrate_raw(msg, (new_msg_type._type, None, new_msg_type._md5sum, None, new_msg_type)) rebag.write(topic, mig_msg, t, raw=True) else: rebag.write(topic, msg, t, raw=True) rebag.close() bag.close() if force: return [] else: return migrations ## Helper function to strip out roslib and package name from name usages. # # There is some inconsistency in whether a fully-qualified path is # used for sub-messages within a given message. This function is # useful for stripping out the package name in a fully qualified # sub-message. # # @param name The name to clean. # @param top_name The name of the top-level type # @returns The cleaned version of the name. def clean_name(name, top_name): name_split = name.split('/') try: name_split.remove('std_msgs') except ValueError: pass try: name_split.remove(top_name.split('/')[0]) except ValueError: pass new_name = '/'.join(name_split) return new_name ## Helper function to ensure we end up with a qualified name # # There is some inconsistency in whether a fully-qualified path is # used for sub-messages within a given message. This function is # useful for ensuring that a name is fully qualified correctly. # # @param name The name to quailfy # @param top_name The name of the top-level type # @returns The qualified version of the name. def qualified_name(name, top_name): # First clean the name, to make everyting else more deterministic tmp_name = clean_name(name, top_name) if len(tmp_name.split('/')) == 2 or (genmsg.msgs.is_builtin(tmp_name)): return tmp_name elif tmp_name == 'Header': return 'std_msgs/Header' else: return top_name.split('/')[0] + '/' + tmp_name ## Helper function to return a key from a given class # # For now, we choose the tuple (type,md5sum) as a unique key for the # class. However, this is subject to change and assumptions about keys # should not be made other than their uniqueness. # # @param c The message class or instance to get a key for # @returns The unique key def get_message_key(c): try: return (c._type, c._md5sum) except: return None ## Helper function to return a key for a given path # # For now, we choose the tuple ((type1,md5sum1),(type2,md5sum2)) as a # unique key for the path. However, this is subject to change and # assumptions about keys should not be made other than their # uniqueness. # # @param c1 The start point of the path # @param c1 The stop point of the path # @returns The unique key def get_path_key(c1, c2): try: return (get_message_key(c1), get_message_key(c2)) except: return None ## Base class for all message update rules class MessageUpdateRule(object): old_type = '' old_full_text = '' new_type = '' new_full_text = '' migrated_types = [] order = -1 valid = False ## Initialize class def __init__(self, migrator, location): # Every rule needs to hang onto the migrator so we can potentially use it self.migrator = migrator self.location = location if (self.old_type != self.new_type): self.rename_rule = True else: self.rename_rule = False # Instantiate types dynamically based on definition try: if self.old_type == "": raise Exception self.old_types = genpy.dynamic.generate_dynamic(self.old_type, self.old_full_text) self.old_class = self.old_types[self.old_type] self.old_md5sum = self.old_class._md5sum except: self.old_types = [] self.old_class = None self.old_md5sum = "" try: if self.new_type == "": raise Exception self.new_types = genpy.dynamic.generate_dynamic(self.new_type, self.new_full_text) self.new_class = self.new_types[self.new_type] self.new_md5sum = self.new_class._md5sum except: self.new_types = [] self.new_class = None self.new_md5sum = "" # We have not populated our sub rules (and ideally should # wait until the full scaffold exists before doing this) self.sub_rules_done = False self.sub_rules_valid = False self.sub_rules = [] ## Find all of the sub paths # # For any migrated type the user might want to use, we must make # sure the migrator had found a path for it. To facilitated this # check we require that all migrated types must be listed as pairs # in the migrated_types field. # # It would be nice not to need these through performing some kind # of other inspection of the update rule itself. def find_sub_paths(self): self.sub_rules_valid = True for (t1, t2) in self.migrated_types: try: tmp_old_class = self.get_old_class(t1) except KeyError: print("WARNING: Within rule [%s], specified migrated type [%s] not found in old message types" % (self.location, t1), file=sys.stderr) self.sub_rules_valid = False continue try: tmp_new_class = self.get_new_class(t2) except KeyError: print("WARNING: Within rule [%s], specified migrated type [%s] not found in new message types" % (self.location, t2), file=sys.stderr) self.sub_rules_valid = False continue # If a rule instantiates itself as a subrule (because the # author knows the md5sums match), we don't Want to end up # with an infinite recursion. if (get_message_key(tmp_old_class) != get_message_key(self.old_class)) or (get_message_key(tmp_new_class) != get_message_key(self.new_class)): path = self.migrator.find_path(tmp_old_class, tmp_new_class) rules = [sn.rule for sn in path] self.sub_rules.extend(rules) if False in [r.valid for r in self.sub_rules]: print("WARNING: Within rule [%s] cannot migrate from subtype [%s] to [%s].." % (self.location, t1, t2), file=sys.stderr) self.sub_rules_valid = False continue self.sub_rules = self.migrator.filter_rules_unique(self.sub_rules) self.sub_rules_done = True ## Helper function to get the class of a submsg for the new type # # This function should be used inside of update to access new classes. # # @param t The subtype to return the class of # @returns The class of the new sub type def get_new_class(self,t): try: try: return self.new_types[t] except KeyError: return self.new_types['std_msgs/' + t] except KeyError: return self.new_types[self.new_type.split('/')[0] + '/' + t] ## Helper function to get the class of a submsg for the old type # # This function should be used inside of update to access old classes. # # @param t The subtype to return the class of # @returns The class of the old sub type def get_old_class(self,t): try: try: return self.old_types[t] except KeyError: return self.old_types['std_msgs/' + t] except KeyError: return self.old_types[self.old_type.split('/')[0] + '/' + t] ## Actually migrate one sub_type to another # # This function should be used inside of update to migrate sub msgs. # # @param msg_from A message instance of the old message type # @param msg_to A message instance of a new message type to be populated def migrate(self, msg_from, msg_to): tmp_msg_from = clean_name(msg_from._type, self.old_type) tmp_msg_to = clean_name(msg_to._type, self.new_type) if (tmp_msg_from, tmp_msg_to) not in self.migrated_types: raise BagMigrationException("Rule [%s] tried to perform a migration from old [%s] to new [%s] not listed in migrated_types"%(self.location, tmp_msg_from, tmp_msg_to)) self.migrator.migrate(msg_from, msg_to) ## Helper function to migrate a whole array of messages # # This function should be used inside of update to migrate arrays of sub msgs. # # @param msg_from_array An array of messages of the old message type # @param msg_to_array An array of messages of the new message type (this will be emptied if not already) # @param msg_to_class The name of the new message type since msg_to_array may be an empty array. def migrate_array(self, msg_from_array, msg_to_array, msg_to_name): msg_to_class = self.get_new_class(msg_to_name) while len(msg_to_array) > 0: msg_to_array.pop() if (len(msg_from_array) == 0): return tmp_msg_from = clean_name(msg_from_array[0]._type, self.old_type) tmp_msg_to = clean_name(msg_to_class._type, self.new_type) if (tmp_msg_from, tmp_msg_to) not in self.migrated_types: raise BagMigrationException("Rule [%s] tried to perform a migration from old [%s] to new [%s] not listed in migrated_types"%(self.location, tmp_msg_from, tmp_msg_to)) msg_to_array.extend( [msg_to_class() for i in range(len(msg_from_array))] ) self.migrator.migrate_array(msg_from_array, msg_to_array) ## A helper function to print out the definiton of autogenerated messages. def get_class_def(self): pass ## The function actually called by the message migrator # # @param old_msg An instance of the old message type. # @returns An instance of a new message type def apply(self, old_msg): if not self.valid: raise BagMigrationException("Attempted to apply an invalid rule") if not self.sub_rules_done: raise BagMigrationException("Attempted to apply a rule without building up its sub rules") if not self.sub_rules_valid: raise BagMigrationException("Attempted to apply a rule without valid sub-rules") if (get_message_key(old_msg) != get_message_key(self.old_class)): raise BagMigrationException("Attempted to apply rule to incorrect class %s %s."%(get_message_key(old_msg),get_message_key(self.old_class))) # Apply update rule new_msg = self.new_class() self.update(old_msg, new_msg) return new_msg ## The function which a user overrides to actually perform the message update # # @param msg_from A message instance of the old message type # @param msg_to A message instance of a new message type to be populated def update(self, old_msg, new_msg): raise BagMigrationException("Tried to use rule without update overidden") ## A class for book-keeping about rule-chains. # # Rule chains define the ordered set of update rules, indexed by # typename, terminated by a rename rule. This class is only used # temporarily to help us get the ordering right, until all explicit # rules have been loaded (possibly out of order) and the proper # scaffold can be built. class RuleChain(object): def __init__(self): self.chain = [] self.order_keys = set() self.rename = None ## A class for arranging the ordered rules # # They provide a scaffolding (essentially a linked list) over which we # assume we can migrate messages forward. This allows us to verify a # path exists before actually creating all of the necessary implicit # rules (mostly migration of sub-messages) that such a path # necessitates. class ScaffoldNode(object): def __init__(self, old_class, new_class, rule): self.old_class = old_class self.new_class = new_class self.rule = rule self.next = None ## A class to actually migrate messages # # This is the big class that actually handles all of the fancy # migration work. Better documentation to come later. class MessageMigrator(object): def __init__(self, input_rule_files=[], plugins=True): # We use the rulechains to scaffold our initial creation of # implicit rules. Each RuleChain is keyed off of a type and # consists of an ordered set of update rules followed by an # optional rename rule. For the system rule definitions to be # valid, all members of a rulechains must be connectable via # implicit rules and all rulechains must terminate in a known # system type which is also reachable by an implicit rule. self.rulechains = collections.defaultdict(RuleChain) # The list of all nodes that we can iterate through in the # future when making sure all rules have been constructed. self.base_nodes = [] # The list of extra (non-scaffolded) nodes that we can use # when determining if all rules are valid and printing invalid # rules. self.extra_nodes = [] # A map from typename to the first node of a particular type self.first_type = {} # A map from a typename to all other typenames for which # rename rules exist. This is necessary to determine whether # an appropriate implicit rule can actually be constructed. self.rename_map = {} # The cached set of all found paths, keyed by: # ((old_type, old_md5), (new_type, new_md5)) self.found_paths = {} self.found_targets = {} # Temporary list of the terminal nodes terminal_nodes = [] # Temporary list of rule modules we are loading rule_dicts = [] self.false_rule_loaded = False # To make debugging easy we can pass in a list of local # rulefiles. for r in input_rule_files: try: scratch_locals = {'MessageUpdateRule':MessageUpdateRule} with open(r, 'r') as f: exec(f.read(), scratch_locals) rule_dicts.append((scratch_locals, r)) except: print("Cannot load rule file [%s] in local package" % r, file=sys.stderr) # Alternatively the preferred method is to load definitions # from the migration ruleset export flag. if plugins: rospack = rospkg.RosPack() for dep,export in [('rosbagmigration','rule_file'),('rosbag','migration_rule_file'),('rosbag_migration_rule','rule_file')]: for pkg in rospack.get_depends_on(dep, implicit=False): m = rospack.get_manifest(pkg) p_rules = m.get_export(dep,export) pkg_dir = rospack.get_path(pkg) for r in p_rules: if dep == 'rosbagmigration': print("""WARNING: The package: [%s] is using a deprecated rosbagmigration export. The export in the manifest should be changed to: <rosbag migration_rule_file="%s"/> """ % (pkg, r), file=sys.stderr) try: scratch_locals = {'MessageUpdateRule':MessageUpdateRule} exec(open(pkg_dir + "/" + r).read(), scratch_locals) rule_dicts.append((scratch_locals, r)) except ImportError: print("Cannot load rule file [%s] in package [%s]" % (r, pkg), file=sys.stderr) for (rule_dict, location_base) in rule_dicts: for (n,c) in rule_dict.items(): if inspect.isclass(c): if (not c == MessageUpdateRule) and issubclass(c, MessageUpdateRule): self.add_update_rule(c(self, location_base + ':' + n)) if self.false_rule_loaded: raise BagMigrationException("Cannot instantiate MessageMigrator with invalid rules") # Now, go through and build up a better scaffolded # representation, deferring implicit rule generation until # complete, since the implicit rule generation and sub-rule # population makes use of the scaffold. # First we each particular type chain (now including implicit # rules). Additionally, we build up our name remapping lists. # For Each rulechain for (type,rulechain) in self.rulechains.items(): first = True sn = None prev_sn = None # Find name remapping list rename_set = set([type]) tmp = rulechain.rename while tmp: rename_set.add(tmp.new_type) if tmp.new_type in self.rulechains: tmp = self.rulechains[tmp.new_type].rename else: break self.rename_map[type] = rename_set # For each element in the rulechain chain, for r in rulechain.chain: # Create a scaffoldnode sn = ScaffoldNode(r.old_class, r.new_class, r) self.base_nodes.append(sn) # If it's the first one, stick it in our first_type map if first: self.first_type[type] = sn first = False # If there was a previous node, link them if keys # match, or else create an implicit SN if prev_sn: if get_message_key(prev_sn.new_class) == get_message_key(sn.old_class): prev_sn.next = sn else: implicit_sn = ScaffoldNode(prev_sn.new_class, sn.old_class, None) self.base_nodes.append(implicit_sn) prev_sn.next = implicit_sn implicit_sn.next = sn # The just-created node now becomes the previous prev_sn = sn # If there is a rename rule if rulechain.rename: # Create a scaffoldnode sn = ScaffoldNode(rulechain.rename.old_class, rulechain.rename.new_class, rulechain.rename) self.base_nodes.append(sn) # Same rules apply here as when we created each node # from chain. Link if possible, otherwise create # implicit if first: self.first_type[type] = sn first = False if prev_sn: if get_message_key(prev_sn.new_class) == get_message_key(sn.old_class): prev_sn.next = sn else: implicit_sn = ScaffoldNode(prev_sn.new_class, sn.old_class, None) self.base_nodes.append(implicit_sn) prev_sn.next = implicit_sn implicit_sn.next = sn prev_sn = sn terminal_nodes.append(sn) # If there was not a rename rule, this must be a terminal node else: if prev_sn: terminal_nodes.append(prev_sn) # Between our partial scaffold and name remapping list, we can # now GENERATE rules, though we cannot yet populate the # subrules. for sn in terminal_nodes: key = get_message_key(sn.new_class) renamed = (sn.old_class._type != sn.new_class._type) sys_class = genpy.message.get_message_class(sn.new_class._type) # If we map directly to a system-defined class we're done if sys_class: new_rule = self.make_update_rule(sn.new_class, sys_class) R = new_rule(self, 'GENERATED.' + new_rule.__name__) if R.valid: sn.next = ScaffoldNode(sn.new_class, sys_class, R) self.base_nodes.append(sn.next) if renamed: tmp_sns = self.scaffold_range(sn.new_class._type, sn.new_class._type) # If we don't map to a scaffold range, we appear to be done if tmp_sns == []: if sys_class is not None: sn.next = ScaffoldNode(sn.new_class, sys_class, None) self.base_nodes.append(sn.next) continue # Otherwise look for trivial bridges for tmp_sn in reversed(tmp_sns): tmp_key = get_message_key(tmp_sn.old_class) if (key == tmp_key): sn.next = tmp_sn break # If we did not find a trivial bridge, we instead need # to create the right implicit rule ourselves. This # is based on the ability to create a valid implicit # rule as LATE in the chain as possible. We do this # to avoid extra conversions in some boundary # circumstances. if (sn.next is None): for tmp_sn in reversed(tmp_sns): new_rule = self.make_update_rule(sn.new_class, tmp_sn.old_class) R = new_rule(self, 'GENERATED.' + new_rule.__name__) if R.valid: sn.next = ScaffoldNode(sn.new_class, tmp_sn.old_class, R) self.base_nodes.append(sn.next) break # If we have still failed we need to create a placeholder. if (sn.next is None): if sys_class: new_rule = self.make_update_rule(sn.new_class, sys_class) else: new_rule = self.make_old_half_rule(sn.new_class) R = new_rule(self, 'GENERATED.' + new_rule.__name__) sn.next = ScaffoldNode(sn.new_class, None, R) self.base_nodes.append(sn.next) # Now that our scaffolding is actually complete, we iterate # through all of our rules and generate the rules for which we # have scaffoldnodes, but no rule yet for sn in self.base_nodes: if (sn.rule is None): new_rule = self.make_update_rule(sn.old_class, sn.new_class) sn.rule = new_rule(self, 'GENERATED.' + new_rule.__name__) # Finally, we go through and try to find sub_paths for every # rule in the system so far for sn in self.base_nodes: sn.rule.find_sub_paths() # Construction should be done, we can now use the system in # the event that we don't have invalid update rules. self.class_dict = {} for sn in self.base_nodes + self.extra_nodes: self.class_dict[get_message_key(sn.old_class)] = sn.old_class self.class_dict[get_message_key(sn.new_class)] = sn.new_class def lookup_type(self, key): if key in self.class_dict: return self.class_dict[key] else: return None # Add an update rule to our set of rule chains def add_update_rule(self, r): if r.valid == False: print("ERROR: Update rule [%s] has valid set to False." % (r.location), file=sys.stderr) self.false_rule_loaded = True return rulechain = self.rulechains[r.old_type] if r.rename_rule: if (rulechain.rename != None): print("WARNING: Update rules [%s] and [%s] both attempting to rename type [%s]. Ignoring [%s]" % (rulechain.rename.location, r.location, r.old_type, r.location), file=sys.stderr) return # Search forward to make sure we havn't created a cycle cycle = [] tmp = r while tmp: cycle.append(tmp) if (tmp.new_type == r.old_type): print("WARNING: Update rules %s introduce a renaming cycle. Ignoring [%s]" % ([x.location for x in cycle], r.location), file=sys.stderr) return if tmp.new_type in self.rulechains: tmp = self.rulechains[tmp.new_type].rename else: break if rulechain.chain and (r.order <= rulechain.chain[-1].order): print("WARNING: Update rule [%s] which performs rename does not have largest order number. Ignoring" % r.location, file=sys.stderr) return rulechain.rename = r else: if r.order in rulechain.order_keys: otherind = [x.order for x in rulechain.chain].index(r.order) print("WARNING: Update rules [%s] and [%s] for type [%s] have the same order number. Ignoring [%s]" % (rulechain.chain[otherind].location, r.location, r.old_type, r.location), file=sys.stderr) return else: if rulechain.rename and (r.order >= rulechain.rename.order): print("WARNING: Update rule [%s] has order number larger than rename rule [%s]. Ignoring" % (r.location, rulechain.rename.location), file=sys.stderr) return # Insert the rule into a rule chain rulechain.order_keys.add(r.order) rulechain.chain.append(r) rulechain.chain.sort(key=lambda x: x.order) # Helper function to determine if all rules are valid def all_rules_valid(self): base_valid = not False in [sn.rule.valid for sn in self.base_nodes] extra_valid = not False in [sn.rule.valid for sn in self.extra_nodes] return base_valid and extra_valid # Helper function to print out the definitions for all invalid rules (which include definitions) def get_invalid_rules(self): invalid_rules = [] invalid_rule_cache = [] for sn in self.base_nodes: if not sn.rule.valid: path_key = get_path_key(sn.old_class, sn.new_class) if (path_key not in invalid_rule_cache): invalid_rules.append(sn.rule) invalid_rule_cache.append(path_key) for sn in self.extra_nodes: if not sn.rule.valid: path_key = get_path_key(sn.old_class, sn.new_class) if (path_key not in invalid_rule_cache): invalid_rules.append(sn.rule) invalid_rule_cache.append(path_key) return invalid_rules # Helper function to remove non-unique rules def filter_rules_unique(self, rules): rule_cache = [] new_rules = [] for r in rules: path_key = get_path_key(r.old_class, r.new_class) if (path_key not in rule_cache): new_rules.append(r) return new_rules # Helper function to expand a list of rules to include subrules def expand_rules(self, rules): filtered = self.filter_rules_unique(rules) expanded = [] for r in filtered: expanded.append(r) #print "For rule %s --> %s"%(r.old_class._type, r.new_class._type) expanded.extend(self.expand_rules(r.sub_rules)) filtered = self.filter_rules_unique(expanded) return filtered def scaffold_range(self, old_type, new_type): try: first_sn = self.first_type[old_type] sn_range = [first_sn] found_new_type = False tmp_sn = first_sn while (tmp_sn.next is not None and tmp_sn.next.new_class is not None): # print sn_range tmp_sn = tmp_sn.next if (tmp_sn != first_sn): sn_range.append(tmp_sn) if (tmp_sn.new_class._type == new_type): found_new_type == True if (found_new_type and tmp_sn.new_class._type != new_type): break return sn_range except KeyError: return [] def find_target(self, old_class): key = get_message_key(old_class) last_class = old_class try: return self.found_targets[key] except KeyError: sys_class = genpy.message.get_message_class(old_class._type) if sys_class is not None: self.found_targets[key] = sys_class return sys_class try: tmp_sn = self.first_type[old_class._type] if tmp_sn.new_class is not None: last_class = tmp_sn.new_class while tmp_sn.next is not None: tmp_sn = tmp_sn.next if tmp_sn.new_class is not None: last_class = tmp_sn.new_class sys_class = genpy.message.get_message_class(tmp_sn.new_class._type) else: sys_class = None if sys_class is not None: self.found_targets[key] = sys_class return sys_class except KeyError: pass self.found_targets[key] = None return None # This function determines the set of rules which must be created # to get from the old type to the new type. def find_path(self, old_class, new_class): key = get_path_key(old_class, new_class) # Return any path already found in the cache try: return self.found_paths[key] except KeyError: pass # If the new_class is none, e.g., a message has been moved and # we are lacking a proper rename rule, such that find-target # failed, the best we can do is create a half-rule from the # end-point if new_class is None: sn_range = self.scaffold_range(old_class._type, "") found_start = False for (ind, tmp_sn) in reversed(list(zip(range(len(sn_range)), sn_range))): # Skip until we find the class we're trying to match if (tmp_sn.old_class._type != old_class._type): continue if get_message_key(tmp_sn.old_class) == get_message_key(old_class): sn_range = sn_range[ind:] found_start = True break # Next see if we can create a valid rule if not found_start: for (ind, tmp_sn) in reversed(list(zip(range(len(sn_range)), sn_range))): if (tmp_sn.old_class._type != old_class._type): continue new_rule = self.make_update_rule(old_class, tmp_sn.old_class) R = new_rule(self, 'GENERATED.' + new_rule.__name__) if R.valid: R.find_sub_paths() sn = ScaffoldNode(old_class, tmp_sn.old_class, R) self.extra_nodes.append(sn) sn_range = sn_range[ind:] sn_range.insert(0,sn) found_start = True break if sn_range == []: tmp_class = old_class else: tmp_class = sn_range[-1].new_class new_rule = self.make_old_half_rule(tmp_class) R = new_rule(self, 'GENERATED.' + new_rule.__name__) sn = ScaffoldNode(tmp_class, None, R) sn_range.append(sn) self.extra_nodes.append(sn) self.found_paths[key] = sn_range return sn_range # If the messages are the same, there is no actually path if (old_class._type == new_class._type and old_class._full_text.strip() == new_class._full_text.strip()): self.found_paths[key] = [] return [] sn_range = self.scaffold_range(old_class._type, new_class._type) # If we have no scaffolding, we just try to create the one path if sn_range == []: new_rule = self.make_update_rule(old_class, new_class) R = new_rule(self, 'GENERATED.' + new_rule.__name__) R.find_sub_paths() sn = ScaffoldNode(old_class, new_class, R) self.extra_nodes.append(sn) self.found_paths[key] = [sn] return [sn] # Search for the stop point in the scaffold found_stop = False # First look for a trivial match for (ind, tmp_sn) in reversed(list(zip(range(len(sn_range)), sn_range))): # Stop looking early if the classes don't match if (tmp_sn.new_class._type != new_class._type): break if get_message_key(tmp_sn.new_class) == get_message_key(new_class): sn_range = sn_range[:ind+1] found_stop = True break # Next see if we can create a valid rule if not found_stop: for (ind, tmp_sn) in reversed(list(zip(range(len(sn_range)), sn_range))): if (tmp_sn.new_class._type != new_class._type): break new_rule = self.make_update_rule(tmp_sn.new_class, new_class) R = new_rule(self, 'GENERATED.' + new_rule.__name__) if R.valid: R.find_sub_paths() sn = ScaffoldNode(tmp_sn.new_class, new_class, R) self.extra_nodes.append(sn) sn_range = sn_range[:ind+1] sn_range.append(sn) found_stop = True break # If there were no valid implicit rules, we suggest a new one from to the end if not found_stop: new_rule = self.make_update_rule(sn_range[-1].new_class, new_class) R = new_rule(self, 'GENERATED.' + new_rule.__name__) R.find_sub_paths() sn = ScaffoldNode(sn_range[-1].new_class, new_class, R) self.extra_nodes.append(sn) sn_range.append(sn) # Search for the start point in the scaffold found_start = False # First look for a trivial match for (ind, tmp_sn) in reversed(list(zip(range(len(sn_range)), sn_range))): # Skip until we find the class we're trying to match if (tmp_sn.old_class._type != old_class._type): continue if get_message_key(tmp_sn.old_class) == get_message_key(old_class): sn_range = sn_range[ind:] found_start = True break # Next see if we can create a valid rule if not found_start: for (ind, tmp_sn) in reversed(list(zip(range(len(sn_range)), sn_range))): if (tmp_sn.old_class._type != old_class._type): continue new_rule = self.make_update_rule(old_class, tmp_sn.old_class) R = new_rule(self, 'GENERATED.' + new_rule.__name__) if R.valid: R.find_sub_paths() sn = ScaffoldNode(old_class, tmp_sn.old_class, R) self.extra_nodes.append(sn) sn_range = sn_range[ind:] sn_range.insert(0,sn) found_start = True break # If there were no valid implicit rules, we suggest a new one from the beginning if not found_start: new_rule = self.make_update_rule(old_class, sn_range[0].old_class) R = new_rule(self, 'GENERATED.' + new_rule.__name__) R.find_sub_paths() sn = ScaffoldNode(old_class, sn_range[0].old_class, R) self.extra_nodes.append(sn) sn_range.insert(0,sn) self.found_paths[key] = sn_range return sn_range def migrate_raw(self, msg_from, msg_to): path = self.find_path(msg_from[4], msg_to[4]) if False in [sn.rule.valid for sn in path]: raise BagMigrationException("Migrate called, but no valid migration path from [%s] to [%s]"%(msg_from[0], msg_to[0])) # Short cut to speed up case of matching md5sum: if path == [] or msg_from[2] == msg_to[2]: return (msg_to[0], msg_from[1], msg_to[2], msg_to[3], msg_to[4]) tmp_msg = path[0].old_class() tmp_msg.deserialize(msg_from[1]) for sn in path: tmp_msg = sn.rule.apply(tmp_msg) buff = StringIO() tmp_msg.serialize(buff) return (msg_to[0], buff.getvalue(), msg_to[2], msg_to[3], msg_to[4]) def migrate(self, msg_from, msg_to): path = self.find_path(msg_from.__class__, msg_to.__class__) if False in [sn.rule.valid for sn in path]: raise BagMigrationException("Migrate called, but no valid migration path from [%s] to [%s]"%(msg_from._type, msg_to._type)) # Short cut to speed up case of matching md5sum: if path == [] or msg_from._md5sum == msg_to._md5sum: buff = StringIO() msg_from.serialize(buff) msg_to.deserialize(buff.getvalue()) return if len(path) > 0: buff = StringIO() msg_from.serialize(buff) tmp_msg = path[0].old_class() tmp_msg.deserialize(buff.getvalue()) for sn in path: tmp_msg = sn.rule.apply(tmp_msg) else: tmp_msg = msg_from buff = StringIO() tmp_msg.serialize(buff) msg_to.deserialize(buff.getvalue()) def migrate_array(self, msg_from_array, msg_to_array): if len(msg_from_array) != len(msg_to_array): raise BagMigrationException("Migrate array called on on arrays of unequal length.") if len(msg_from_array) == 0: return path = self.find_path(msg_from_array[0].__class__, msg_to_array[0].__class__) if path is None: raise BagMigrationException("Migrate called, but no migration path from [%s] to [%s]"%(msg_from._type, msg_to._type)) # Short cut to speed up case of matching md5sum: if path == []: for i in range(len(msg_from_array)): buff = StringIO() msg_from_array[i].serialize(buff) msg_to_array[i].deserialize(buff.getvalue()) return for i in range(len(msg_from_array)): buff = StringIO() tmp_msg = path[0].old_class() msg_from_array[i].serialize(buff) tmp_msg.deserialize(buff.getvalue()) for sn in path: tmp_msg = sn.rule.apply(tmp_msg) buff = StringIO() tmp_msg.serialize(buff) msg_to_array[i].deserialize(buff.getvalue()) def make_update_rule(self, old_class, new_class): name = "update_%s_%s"%(old_class._type.replace("/","_"), old_class._md5sum) # We assemble the class as a string and then exec it to end up with a class # that can essentially print its own definition. classdef = "class %s(MessageUpdateRule):\n"%name classdef += "\told_type = \"%s\"\n"%old_class._type classdef += "\told_full_text = \"\"\"\n%s\n\"\"\"\n\n"%old_class._full_text.strip() classdef += "\tnew_type = \"%s\"\n"%new_class._type classdef += "\tnew_full_text = \"\"\"\n%s\n\"\"\"\n"%new_class._full_text.strip() classdef += "\n" classdef += "\torder = 0" classdef += "\n" validdef = "\tvalid = True\n" migratedefs = "\tmigrated_types = [" updatedef = "\tdef update(self, old_msg, new_msg):\n" old_consts = constants_from_def(old_class._type, old_class._full_text) new_consts = constants_from_def(new_class._type, new_class._full_text) if (not new_consts >= old_consts): validdef = "\tvalid = False\n" for c in (old_consts - new_consts): updatedef += "\t\t#Constant '%s' has changed\n"%(c[0],) old_slots = [] old_slots.extend(old_class.__slots__) migrations_seen = [] # Assign across primitives, self.migrate or self.migrate_array non-primitives for (s,t) in zip(new_class.__slots__, new_class._slot_types): warn_msg = None new_base_type, new_is_array, new_array_len = genmsg.msgs.parse_type(t) try: ind = old_class.__slots__.index(s) old_slots.remove(s) old_base_type, old_is_array, old_array_len = genmsg.msgs.parse_type(old_class._slot_types[ind]) if new_is_array != old_is_array: warn_msg = "Could not match array with nonarray" elif new_array_len != old_array_len: if old_array_len is None: warn_msg = "Converted from variable length array to fixed array of length %d"%(new_array_len) elif new_array_len is None: warn_msg = "Converted from fixed array of length %d to variable length"%(old_array_len) else: warn_msg = "Fixed length array converted from %d to %d"%(old_array_len,new_array_len) elif genmsg.msgs.is_builtin(new_base_type): if new_base_type != old_base_type: warn_msg = "Primitive type changed" else: updatedef += "\t\tnew_msg.%s = old_msg.%s\n"%(s,s) else: tmp_old_type = clean_name(old_base_type, old_class._type) tmp_new_type = clean_name(new_base_type, new_class._type) tmp_qualified_old_type = qualified_name(old_base_type, old_class._type) tmp_qualified_new_type = qualified_name(new_base_type, new_class._type) # Verify the type can theoretically be migrated if (tmp_qualified_old_type == tmp_qualified_new_type) or \ (tmp_qualified_old_type in self.rename_map and tmp_qualified_new_type in self.rename_map[tmp_qualified_old_type]): if (tmp_old_type, tmp_new_type) not in migrations_seen: migratedefs += "\n\t\t(\"%s\",\"%s\"),"%(tmp_old_type, tmp_new_type) migrations_seen.append((tmp_old_type, tmp_new_type)) if not new_is_array: updatedef += "\t\tself.migrate(old_msg.%s, new_msg.%s)\n"%(s,s) else: updatedef += "\t\tself.migrate_array(old_msg.%s, new_msg.%s, \"%s\")\n"%(s,s,new_base_type) else: warn_msg = "No migration path between [%s] and [%s]"%(tmp_old_type, tmp_new_type) except ValueError: warn_msg = "No matching field name in old message" if warn_msg is not None: validdef = "\tvalid = False\n" updatedef += "\t\t#%s\n"%warn_msg updatedef += "\t\tnew_msg.%s = %s\n"%(s,migration_default_value(t)) migratedefs += "]\n" if old_slots: validdef = "\tvalid = False\n" for s in old_slots: updatedef += "\t\t#No field to match field %s from old message\n"%(s) classdef += migratedefs + '\n' + validdef + '\n' + updatedef printclassdef = classdef + "\tdef get_class_def(self):\n\t\treturn \'\'\'%s\'\'\'\n"%classdef # This is probably a TERRIBLE idea? exec(printclassdef) return locals()[name] def make_old_half_rule(self, old_class): name = "update__%s__%s"%(old_class._type.replace("/","_"), old_class._md5sum) # We assemble the class as a string and then exec it to end up with a class # that can essentially print its own definition. classdef = "class %s(MessageUpdateRule):\n"%name classdef += "\told_type = \"%s\"\n"%old_class._type classdef += "\told_full_text = \"\"\"\n%s\n\"\"\"\n\n"%old_class._full_text.strip() classdef += "\tnew_type = \"\"\n" classdef += "\tnew_full_text = \"\"\"\n\n\"\"\"\n" classdef += "\n" classdef += "\torder = 0" classdef += "\n" validdef = "\tvalid = False\n" migratedefs = "\tmigrated_types = []\n" updatedef = "\tdef update(self, old_msg, new_msg):\n" updatedef += "\t\tpass\n" classdef += migratedefs + '\n' + validdef + '\n' + updatedef printclassdef = classdef + "\tdef get_class_def(self):\n\t\treturn \'\'\'%s\'\'\'\n"%classdef # This is probably a TERRIBLE idea? exec(printclassdef) return locals()[name] def make_new_half_rule(self, new_class): name = "update_to_%s_%s"%(new_class._type.replace("/","_"), new_class._md5sum) # We assemble the class as a string and then exec it to end up with a class # that can essentially print its own definition. classdef = "class %s(MessageUpdateRule):\n"%name classdef += "\told_type = \"\"\n" classdef += "\told_full_text = \"\"\"\n\n\"\"\"\n\n" classdef += "\tnew_type = \"%s\"\n"%new_class._type classdef += "\tnew_full_text = \"\"\"\n%s\n\"\"\"\n"%new_class._full_text.strip() classdef += "\n" classdef += "\torder = 0" classdef += "\n" validdef = "\tvalid = False\n" migratedefs = "\tmigrated_types = []\n" updatedef = "\tdef update(self, old_msg, new_msg):\n" updatedef += "\t\tpass\n" classdef += migratedefs + '\n' + validdef + '\n' + updatedef printclassdef = classdef + "\tdef get_class_def(self):\n\t\treturn \'\'\'%s\'\'\'\n"%classdef # This is probably a TERRIBLE idea? exec(printclassdef) return locals()[name] def migration_default_value(field_type): if field_type in ['bool', 'byte', 'int8', 'int16', 'int32', 'int64',\ 'char', 'uint8', 'uint16', 'uint32', 'uint64']: return '0' elif field_type in ['float32', 'float64']: return '0.' elif field_type == 'string': # strings, byte[], and uint8s are all optimized to be strings return "''" elif field_type.endswith(']'): # array type base_type, is_array, array_len = genmsg.msgs.parse_type(field_type) if base_type in ['byte', 'uint8']: # strings, byte[], and uint8s are all optimized to be strings if array_len is not None: return "chr(0)*%s"%array_len else: return "''" elif array_len is None: #var-length return '[]' else: # fixed-length, fill values def_val = migration_default_value(base_type) return '[' + ','.join(itertools.repeat(def_val, array_len)) + ']' else: return "self.get_new_class('%s')()"%field_type def constants_from_def(core_type, msg_def): core_pkg, core_base_type = genmsg.package_resource_name(core_type) splits = msg_def.split('\n' + '=' * 80 + '\n') core_msg = splits[0] deps_msgs = splits[1:] # create MsgSpec representations of .msg text from genmsg import MsgContext context = MsgContext.create_default() specs = { core_type: genmsg.msg_loader.load_msg_from_string(context, core_msg, core_pkg) } # - dependencies # for dep_msg in deps_msgs: # # dependencies require more handling to determine type name # dep_type, dep_spec = _generate_dynamic_specs(specs, dep_msg) # specs[dep_type] = dep_spec return set([(x.name, x.val, x.type) for x in specs[core_type].constants])
0
apollo_public_repos/apollo-platform/ros/ros_comm
apollo_public_repos/apollo-platform/ros/ros_comm/rosout/CMakeLists.txt
cmake_minimum_required(VERSION 2.8.3) project(rosout) if(NOT WIN32) set_directory_properties(PROPERTIES COMPILE_OPTIONS "-Wall;-Wextra") endif() find_package(catkin REQUIRED COMPONENTS roscpp rosgraph_msgs) catkin_package() include_directories(${catkin_INCLUDE_DIRS}) add_executable(rosout rosout.cpp) target_link_libraries(rosout ${catkin_LIBRARIES}) install(TARGETS rosout RUNTIME DESTINATION ${CATKIN_PACKAGE_BIN_DESTINATION})
0
apollo_public_repos/apollo-platform/ros/ros_comm
apollo_public_repos/apollo-platform/ros/ros_comm/rosout/package.xml
<package> <name>rosout</name> <version>1.11.21</version> <description> System-wide logging mechanism for messages sent to the /rosout topic. </description> <maintainer email="dthomas@osrfoundation.org">Dirk Thomas</maintainer> <license>BSD</license> <url>http://ros.org/wiki/rosout</url> <author>Josh Faust</author> <buildtool_depend>catkin</buildtool_depend> <build_depend>roscpp</build_depend> <build_depend>rosgraph_msgs</build_depend> <run_depend>roscpp</run_depend> <run_depend>rosgraph_msgs</run_depend> </package>
0
apollo_public_repos/apollo-platform/ros/ros_comm
apollo_public_repos/apollo-platform/ros/ros_comm/rosout/rosout.cpp
/* * 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. */ #include <cstring> #include <cstdlib> #include "ros/ros.h" #include "ros/file_log.h" #ifdef WIN32 #ifdef ERROR // ach, windows.h polluting everything again, // clashes with autogenerated rosgraph_msgs/Log.h #undef ERROR #endif #endif #include "rosgraph_msgs/Log.h" /** * @mainpage * * @htmlinclude manifest.html * * @b rosout logs messages sent to the /rosout topic, * which is a system-wide string logging mechanism. */ /** * the rosout node subscribes to /rosout, logs the messages to file, and re-broadcasts the messages to /rosout_agg */ class Rosout { public: std::string log_file_name_; FILE* handle_; size_t max_file_size_; size_t current_file_size_; size_t max_backup_index_; size_t current_backup_index_; ros::NodeHandle node_; ros::Subscriber rosout_sub_; ros::Publisher agg_pub_; Rosout() { init(); } void init() { max_file_size_ = 100*1024*1024; current_file_size_ = 0; max_backup_index_ = 10; current_backup_index_ = 0; log_file_name_ = ros::file_log::getLogDirectory() + "/rosout.log"; handle_ = fopen(log_file_name_.c_str(), "w"); if (handle_ == 0) { std::cerr << "Error opening rosout log file '" << log_file_name_.c_str() << "': " << strerror(errno); } else { std::cout << "logging to " << log_file_name_.c_str() << std::endl; std::stringstream ss; ss << "\n\n" << ros::Time::now() << " Node Startup\n"; int written = fprintf(handle_, "%s", ss.str().c_str()); if (written < 0) { std::cerr << "Error writting to rosout log file '" << log_file_name_.c_str() << "': " << strerror(ferror(handle_)) << std::endl; } else if (written > 0) { current_file_size_ += written; if (fflush(handle_)) { std::cerr << "Error flushing rosout log file '" << log_file_name_.c_str() << "': " << strerror(ferror(handle_)); } } } agg_pub_ = node_.advertise<rosgraph_msgs::Log>("/rosout_agg", 0); std::cout << "re-publishing aggregated messages to /rosout_agg" << std::endl; rosout_sub_ = node_.subscribe("/rosout", 0, &Rosout::rosoutCallback, this); std::cout << "subscribed to /rosout" << std::endl; } void rosoutCallback(const rosgraph_msgs::Log::ConstPtr& msg) { agg_pub_.publish(msg); std::stringstream ss; ss << msg->header.stamp << " "; switch (msg->level) { case rosgraph_msgs::Log::FATAL: ss << "FATAL "; break; case rosgraph_msgs::Log::ERROR: ss << "ERROR "; break; case rosgraph_msgs::Log::WARN: ss << "WARN "; break; case rosgraph_msgs::Log::DEBUG: ss << "DEBUG "; break; case rosgraph_msgs::Log::INFO: ss << "INFO "; break; default: ss << msg->level << " "; } ss << "[" << msg->file << ":" << msg->line << "(" << msg->function << ") "; ss << "[topics: "; std::vector<std::string>::const_iterator it = msg->topics.begin(); std::vector<std::string>::const_iterator end = msg->topics.end(); for ( ; it != end; ++it ) { const std::string& topic = *it; if ( it != msg->topics.begin() ) { ss << ", "; } ss << topic; } ss << "] "; ss << msg->msg; ss << "\n"; int written = fprintf(handle_, "%s", ss.str().c_str()); if (written < 0) { std::cerr << "Error writting to rosout log file '" << log_file_name_.c_str() << "': " << strerror(ferror(handle_)) << std::endl; } else if (written > 0) { current_file_size_ += written; if (fflush(handle_)) { std::cerr << "Error flushing rosout log file '" << log_file_name_.c_str() << "': " << strerror(ferror(handle_)); } // check for rolling if (current_file_size_ > max_file_size_) { if (fclose(handle_)) { std::cerr << "Error closing rosout log file '" << log_file_name_.c_str() << "': " << strerror(ferror(handle_)) << std::endl; } current_backup_index_++; if (current_backup_index_ <= max_backup_index_) { std::stringstream backup_file_name; backup_file_name << log_file_name_ << "." << current_backup_index_; int rc = rename(log_file_name_.c_str(), backup_file_name.str().c_str()); if (rc != 0) { rc = remove(backup_file_name.str().c_str()); if (rc == 0) { rc = rename(log_file_name_.c_str(), backup_file_name.str().c_str()); if (rc) { std::cerr << "Error rotating rosout log file '" << log_file_name_.c_str() << "' to '" << backup_file_name.str().c_str() << "': " << strerror(errno); } } } if (rc) { std::cerr << "Error rotating rosout log file '" << log_file_name_.c_str() << "'' to '" << backup_file_name.str().c_str() << "'" << std::endl; } else { std::cout << "rosout log file " << log_file_name_.c_str() << " reached max size, back up data to " << backup_file_name.str().c_str() << std::endl; } if (current_backup_index_ == max_backup_index_) { current_backup_index_ = 0; } } handle_ = fopen(log_file_name_.c_str(), "w"); if (handle_ == 0) { std::cerr << "Error opening rosout log file '" << log_file_name_.c_str() << "': " << strerror(errno); } current_file_size_ = 0; } } } }; int main(int argc, char **argv) { ros::init(argc, argv, "rosout", ros::init_options::NoRosout); ros::NodeHandle n; Rosout r; ros::spin(); return 0; }
0
apollo_public_repos/apollo-platform/ros/ros_comm
apollo_public_repos/apollo-platform/ros/ros_comm/rosout/.tar
{!!python/unicode 'url': 'https://github.com/ros-gbp/ros_comm-release/archive/release/indigo/rosout/1.11.21-0.tar.gz', !!python/unicode 'version': ros_comm-release-release-indigo-rosout-1.11.21-0}
0
apollo_public_repos/apollo-platform/ros/ros_comm
apollo_public_repos/apollo-platform/ros/ros_comm/rosout/CHANGELOG.rst
^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Changelog for package rosout ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 1.11.21 (2017-03-06) -------------------- 1.11.20 (2016-06-27) -------------------- 1.11.19 (2016-04-18) -------------------- * use directory specific compiler flags (`#785 <https://github.com/ros/ros_comm/pull/785>`_) 1.11.18 (2016-03-17) -------------------- 1.11.17 (2016-03-11) -------------------- 1.11.16 (2015-11-09) -------------------- 1.11.15 (2015-10-13) -------------------- 1.11.14 (2015-09-19) -------------------- 1.11.13 (2015-04-28) -------------------- 1.11.12 (2015-04-27) -------------------- 1.11.11 (2015-04-16) -------------------- 1.11.10 (2014-12-22) -------------------- 1.11.9 (2014-08-18) ------------------- 1.11.8 (2014-08-04) ------------------- 1.11.7 (2014-07-18) ------------------- 1.11.6 (2014-07-10) ------------------- 1.11.5 (2014-06-24) ------------------- 1.11.4 (2014-06-16) ------------------- 1.11.3 (2014-05-21) ------------------- 1.11.2 (2014-05-08) ------------------- 1.11.1 (2014-05-07) ------------------- 1.11.0 (2014-03-04) ------------------- 1.10.0 (2014-02-11) ------------------- 1.9.54 (2014-01-27) ------------------- 1.9.53 (2014-01-14) ------------------- 1.9.52 (2014-01-08) ------------------- 1.9.51 (2014-01-07) ------------------- * remove log4cxx dependency from rosout, implementing custom rolling log file 1.9.50 (2013-10-04) ------------------- 1.9.49 (2013-09-16) ------------------- 1.9.48 (2013-08-21) ------------------- 1.9.47 (2013-07-03) ------------------- 1.9.46 (2013-06-18) ------------------- 1.9.45 (2013-06-06) ------------------- 1.9.44 (2013-03-21) ------------------- 1.9.43 (2013-03-13) ------------------- 1.9.42 (2013-03-08) ------------------- 1.9.41 (2013-01-24) ------------------- 1.9.40 (2013-01-13) ------------------- 1.9.39 (2012-12-29) ------------------- * first public release for Groovy
0