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/roslisp/s-xml-rpc
apollo_public_repos/apollo-platform/ros/roslisp/s-xml-rpc/test/test-extensions.lisp
;;;; -*- mode: lisp -*- ;;;; ;;;; $Id: test-extensions.lisp,v 1.1 2004/06/17 19:43:11 rschlatte Exp $ ;;;; ;;;; Unit and functional tests for xml-rpc.lisp ;;;; ;;;; Copyright (C) 2004 Rudi Schlatte ;;;; ;;;; You are granted the rights to distribute and use this software ;;;; as governed by the terms of the Lisp Lesser General Public License ;;;; (http://opensource.franz.com/preamble.html), also known as the LLGPL. (in-package :s-xml-rpc) (let* ((server-port 8080) (server-process-name (start-xml-rpc-server :port server-port)) (server-args `(:port ,server-port)) (*xml-rpc-package* (make-package (gensym))) (symbols '(|system.listMethods| |system.methodSignature| |system.methodHelp| |system.multicall| |system.getCapabilities|))) (import symbols *xml-rpc-package*) (sleep 1) ; give the server some time to come up ;-) (unwind-protect (progn (assert (equal (sort (call-xml-rpc-server server-args "system.listMethods") #'string<) (sort (mapcar #'string symbols) #'string<))) (assert (every #'string= (mapcar (lambda (name) (call-xml-rpc-server server-args "system.methodHelp" name)) symbols) (mapcar (lambda (name) (or (documentation name 'function) "")) symbols))) (assert (= 2 (length (call-xml-rpc-server server-args "system.multicall" (list (xml-rpc-struct "methodName" "system.listMethods") (xml-rpc-struct "methodName" "system.methodHelp" "params" (list "system.multicall")))))))) (stop-server server-process-name) (delete-package *xml-rpc-package*))) ;;;; eof
0
apollo_public_repos/apollo-platform/ros/roslisp/s-xml-rpc
apollo_public_repos/apollo-platform/ros/roslisp/s-xml-rpc/test/test-xml-rpc.lisp
;;;; -*- mode: lisp -*- ;;;; ;;;; $Id: test-xml-rpc.lisp,v 1.1.1.1 2004/06/09 09:02:41 scaekenberghe Exp $ ;;;; ;;;; Unit and functional tests for xml-rpc.lisp ;;;; ;;;; Copyright (C) 2002, 2004 Sven Van Caekenberghe, Beta Nine BVBA. ;;;; ;;;; You are granted the rights to distribute and use this software ;;;; as governed by the terms of the Lisp Lesser General Public License ;;;; (http://opensource.franz.com/preamble.html), also known as the LLGPL. (in-package :s-xml-rpc) (assert (let ((now (get-universal-time))) (equal (iso8601->universal-time (universal-time->iso8601 now)) now))) (assert (equal (with-input-from-string (in (encode-xml-rpc-call "add" 1 2)) (decode-xml-rpc in)) '("add" 1 2))) (assert (equal (with-input-from-string (in (encode-xml-rpc-result '(1 2))) (car (decode-xml-rpc in))) '(1 2))) (let ((condition (with-input-from-string (in (encode-xml-rpc-fault "Fatal Error" 100)) (decode-xml-rpc in)))) (assert (typep condition 'xml-rpc-fault)) (assert (equal (xml-rpc-fault-string condition) "Fatal Error")) (assert (equal (xml-rpc-fault-code condition) 100))) (assert (xml-rpc-time-p (xml-rpc-call (encode-xml-rpc-call "currentTime.getCurrentTime") :host "time.xmlrpc.com"))) (assert (equal (xml-rpc-call (encode-xml-rpc-call "examples.getStateName" 41) :host "betty.userland.com") "South Dakota")) (assert (equal (call-xml-rpc-server '(:host "betty.userland.com") "examples.getStateName" 41) "South Dakota")) (assert (let ((server-process-name (start-xml-rpc-server :port 8080))) (sleep 1) ; give the server some time to come up ;-) (unwind-protect (equal (xml-rpc-call (encode-xml-rpc-call "XML-RPC-IMPLEMENTATION-VERSION") :port 8080) (xml-rpc-implementation-version)) (stop-server server-process-name)))) (assert (let* ((struct-in (xml-rpc-struct :foo 100 :bar "")) (xml (with-output-to-string (out) (encode-xml-rpc-value struct-in out))) (struct-out (with-input-from-string (in xml) (decode-xml-rpc in)))) (xml-rpc-struct-equal struct-in struct-out))) ;;;; eof
0
apollo_public_repos/apollo-platform/ros/roslisp/s-xml-rpc
apollo_public_repos/apollo-platform/ros/roslisp/s-xml-rpc/test/all-tests.lisp
;;;; -*- mode: lisp -*- ;;;; ;;;; $Id: all-tests.lisp,v 1.2 2004/06/17 19:43:11 rschlatte Exp $ ;;;; ;;;; Load and execute all unit and functional tests ;;;; ;;;; Copyright (C) 2002, 2004 Sven Van Caekenberghe, Beta Nine BVBA. ;;;; ;;;; You are granted the rights to distribute and use this software ;;;; as governed by the terms of the Lisp Lesser General Public License ;;;; (http://opensource.franz.com/preamble.html), also known as the LLGPL. (load (merge-pathnames "test-base64" *load-pathname*) :verbose t) (load (merge-pathnames "test-xml-rpc" *load-pathname*) :verbose t) (load (merge-pathnames "test-extensions" *load-pathname*) :verbose t) ;;;; eof
0
apollo_public_repos/apollo-platform/ros/roslisp/s-xml-rpc
apollo_public_repos/apollo-platform/ros/roslisp/s-xml-rpc/test/test-base64.lisp
;;;; -*- mode: lisp -*- ;;;; ;;;; $Id: test-base64.lisp,v 1.1.1.1 2004/06/09 09:02:41 scaekenberghe Exp $ ;;;; ;;;; Unit and functional tests for base64.lisp ;;;; ;;;; Copyright (C) 2002, 2004 Sven Van Caekenberghe, Beta Nine BVBA. ;;;; ;;;; You are granted the rights to distribute and use this software ;;;; as governed by the terms of the Lisp Lesser General Public License ;;;; (http://opensource.franz.com/preamble.html), also known as the LLGPL. (in-package :s-base64) (assert (equal (multiple-value-list (core-encode-base64 0 0 0)) (list #\A #\A #\A #\A))) (assert (equal (multiple-value-list (core-encode-base64 255 255 255)) (list #\/ #\/ #\/ #\/))) (assert (equal (multiple-value-list (core-encode-base64 1 2 3)) (list #\A #\Q #\I #\D))) (assert (equal (multiple-value-list (core-encode-base64 10 20 30)) (list #\C #\h #\Q #\e))) (assert (equal (multiple-value-list (core-decode-base64 #\A #\A #\A #\A)) (list 0 0 0))) (assert (equal (multiple-value-list (core-decode-base64 #\/ #\/ #\/ #\/)) (list 255 255 255))) (assert (equal (multiple-value-list (core-decode-base64 #\A #\Q #\I #\D)) (list 1 2 3))) (assert (equal (multiple-value-list (core-decode-base64 #\C #\h #\Q #\e)) (list 10 20 30))) (assert (let* ((string "Hello World!") (bytes (map 'vector #'char-code string)) encoded decoded) (setf encoded (with-output-to-string (out) (encode-base64-bytes bytes out))) (setf decoded (with-input-from-string (in encoded) (decode-base64-bytes in))) (equal string (map 'string #'code-char decoded)))) ;;; this is more of a functional test (defun same-character-file (file1 file2) (with-open-file (a file1 :direction :input) (with-open-file (b file2 :direction :input) (loop (let ((char-a (read-char a nil nil nil)) (char-b (read-char b nil nil nil))) (cond ((not (or (and (null char-a) (null char-b)) (and char-a char-b))) (return-from same-character-file nil)) ((null char-a) (return-from same-character-file t)) ((char/= char-a char-b) (return-from same-character-file nil)))))))) (defun same-binary-file (file1 file2) (with-open-file (a file1 :direction :input :element-type 'unsigned-byte) (with-open-file (b file2 :direction :input :element-type 'unsigned-byte) (loop (let ((byte-a (read-byte a nil nil)) (byte-b (read-byte b nil nil))) (cond ((not (or (and (null byte-a) (null byte-b)) (and byte-a byte-b))) (return-from same-binary-file nil)) ((null byte-a) (return-from same-binary-file t)) ((/= byte-a byte-b) (return-from same-binary-file nil)))))))) (let ((original (merge-pathnames "test.b64" *load-pathname*)) (first-gif (merge-pathnames "test.gif" *load-pathname*)) (b64 (merge-pathnames "test2.b64" *load-pathname*)) (second-gif (merge-pathnames "test2.gif" *load-pathname*))) (with-open-file (in original :direction :input) (with-open-file (out first-gif :direction :output :element-type 'unsigned-byte :if-does-not-exist :create :if-exists :supersede) (decode-base64 in out))) (with-open-file (in first-gif :direction :input :element-type 'unsigned-byte) (with-open-file (out b64 :direction :output :if-does-not-exist :create :if-exists :supersede) (encode-base64 in out nil))) (assert (same-character-file original b64)) (with-open-file (in b64 :direction :input) (with-open-file (out second-gif :direction :output :element-type 'unsigned-byte :if-does-not-exist :create :if-exists :supersede) (decode-base64 in out))) (assert (same-binary-file first-gif second-gif)) (delete-file first-gif) (delete-file b64) (delete-file second-gif)) ;;;; eof
0
apollo_public_repos/apollo-platform/ros/roslisp/s-xml-rpc
apollo_public_repos/apollo-platform/ros/roslisp/s-xml-rpc/doc/index.html
<?xml version="1.0"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <title>S-XML-RPC</title> <link rel="stylesheet" type="text/css" href="style.css"/> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"/> </head> <body> <div class="header"> <h1>S-XML-RPC</h1> </div> <p> S-XML-RPC is an implementation of <a href="http://www.xmlrpc.com">XML-RPC</a> in Common Lisp for both client and server. Originally it was written by <a href="http://homepage.mac.com/svc">Sven Van Caekenberghe</a>. It is now being maintained by <a href="http://homepage.mac.com/svc">Sven Van Caekenberghe</a>, <a href="http://constantly.at">Rudi Schlatte</a> and <a href="http://www.cs.indiana.edu/~bmastenb">Brian Mastenbrook</a>. S-XML-RPC is using <a href="http://common-lisp.net/project/s-xml">S-XML</a> as parser. </p> <p> XML-RPC is a de facto standard for making remote procedure calls between software running on disparate operating systems, running in different environments and implemented using different languages. XML-RPC is using HTTP as the transport and XML as the encoding. XML-RPC is designed to be as simple as possible, while allowing complex data structures to be transmitted, processed and returned. The protocol is described in detail on <a href="http://www.xmlrpc.com/">http://www.xmlrpc.com/</a>. Some key features (both positive and negative) of the XML-RPC protocol are: <ul> <li>It is a published protocol implemented in a variety of languages and operating systems.</li> <li>It allows communication between applications implemented in different languages.</li> <li>It allows communication over the internet and through firewalls.</li> <li>It is not intended for time-critical communications, or for the transmission of large volumes of data.</li> <li>It is an asymmetrical protocol allowing calls from the client to the server but not callbacks from the server to the client.</li> <li>It is a very simple protocol that it not defined, controlled or endorsed by a standards body.</li> <li>It works.</li> </ul> </p> <h3>Download</h3> <p> You can download the LLGPL source code and documentation as <a href="s-xml-rpc.tgz">s-xml-rpc.tgz</a> (signature: <a href="s-xml-rpc.tgz.asc">s-xml-rpc.tgz.asc</a> for which the public key can be found in the <a href="http://common-lisp.net/keyring.asc">common-lisp.net keyring</a>) (build and/or install with ASDF). There is also <a href="http://common-lisp.net/cgi-bin/viewcvs.cgi/?cvsroot=s-xml-rpc">CVS</a> access. </p> <h3>API</h3> <p> The plain API exported by the package S-XML-RPC (automatically generated by LispDoc) is available in <a href="S-XML-RPC.html">S-XML-RPC.html</a>. </p> <h2> Usage </h2> <h3> Client </h3> <p> Making an XML-RPC call is a two step process: first you encode the call, then you make the call. <pre>? (xml-rpc-call (encode-xml-rpc-call "currentTime.getCurrentTime") :host "time.xmlrpc.com") #&lt;XML-RPC-TIME 20021216T06:36:33&gt; ? (xml-rpc-call (encode-xml-rpc-call "examples.getStateName" 41) :host "betty.userland.com") "South Dakota"</pre> If you are behind an HTTP proxy, you have to pass that information along using keyword arguments. For all keyword arguments, there are default global variables (because most of the time you talk to the same host). <pre>? (xml-rpc-call (encode-xml-rpc-call "currentTime.getCurrentTime") :host "time.xmlrpc.com" :proxy-host "myproxy" :proxy-port 8080)</pre> When all goes well, an XML-RPC call returns a result that is decoded into a Common Lisp value. A number of things can go wrong: <ul> <li>There could be a problem encoding the call.</li> <li>There could be a problem in the networking, up to the HTTP server responding with a code different from 200 OK.</li> <li>The result of the call could be an XML-RPC fault: this is how the server responds to an error that occured on the server while executing the call there.</li> <li>There could be a problem decoding the call's result.</li> </ul> At the moment, all these cases are reported by the standard error mechanism. Later we could use different condition types. There are two structs, xml-rpc-time and xml-rpc-struct, that represent two XML-RPC types, iso8601.dateTime and struct respectively. Two convenience functions with the same name come in handy when creating these structs: <pre>? (xml-rpc-struct :foo 1 :bar -1) #&lt;#XML-RPC-STRUCT (:BAR . -1) (:FOO . 1)&gt; ? (xml-rpc-time 3000000000) #&lt;XML-RPC-TIME 19950125T06:20:00&gt;</pre> The function <tt>xml-rpc-aserve:xml-rpc-call-aserve</tt> does the same thing, but uses the (portable) aserve HTTP client API for the networking. </p> <p> The unit tests in the subdirectory <tt>test</tt> can serve as (executable) examples. A more complicated example is the server and client implementation of some tests in <tt>validator1.lisp</tt>. Remember that XML-RPC method (function) names are case-sensitive, as are the names of XML-RPC structure members. </p> <h3> Server </h3> <p> Only a single function call is needed to get the server up and running: <pre>? (start-xml-rpc-server :port 8080)</pre> From now on, your lisp image becomes an XML-RPC server, listening for HTTP requests on port 8080. By default the functions <tt>system.listMethods</tt>, <tt>system.methodSignature</tt>, <tt>system.methodHelp</tt> and <tt>system.multicall</tt> are available. You can export additional functions from the server by importing symbols in the package contained in <tt>*xml-rpc-package*</tt> (by default, this is the package S-XML-RPC-EXPORTS). <tt>(use-package :common-lisp :s-xml-rpc-exports)</tt> makes all of Common Lisp available via xml-rpc. </p> <p> In more detail, this is what happens: <ul> <li>The XML-RPC call arrives as XML encoded characters in the body of an HTTP POST request</li> <li>The characters received are parsed by the XML parser and decoded on the fly (using a SAX-like interface) following XML-RPC semantics into a a string method name and a possibly empty list of Lisp objects that are the arguments</li> <li>The value of <tt>*xml-rpc-call-hook*</tt> is applied on the string method name and optional argument list</li> <li>The default value of <tt>*xml-rpc-call-hook*</tt> is <tt>execute-xml-rpc-call</tt> which looks for a function with the given name in the package <tt>*xml-rpc-package*</tt> (whose default value is the XML-RPC-EXPORTS package) and applies the function bound to that name to the argument list (if any)</li> <li>The result is encoded as an XML-RPC result and returned to the client</li> <li>If anything goes wrong in any of these steps, a Lisp condition is thrown which is caught and then encoded as an XML-RPC fault and returned to the client</li> </ul> Customization points are <tt>*xml-rpc-package*</tt> and <tt>*xml-rpc-call-hook*</tt>. Setting the variable <tt>xml-rpc::*xml-rpc-debug*</tt> to <tt>t</tt> makes the server more verbose. Note that XML-RPC method names are case sensitive: for example, clients have specify "LISP-IMPLEMENTATION-TYPE" for the corresponding Lisp function; a server has to define a function named <tt>|login|</tt> if his clients look for an implementation of "login". </p> <p> AppleScript can make client-side XML-RPC calls. So provided you have your lisp XML-RPC server running and have imported + in XML-RPC-EXPORTS, you can have lisp do the math like this: <pre>tell application "http://localhost:8080/RPC2" set call_result to call xmlrpc {method name:"+", parameters:{10, 20, 30}} end tell display dialog the call_result buttons {"OK"}</pre> Calling the functions <tt>xml-rpc-aserve:start-xml-rpc</tt> and <tt>xml-rpc-aserve:publish-aserve-xml-rpc-handler</tt> does the same thing but uses the (portable) aserve server framework to handle incoming HTTP requests. </p> <h3> Type Mapping </h3> <p> This XML-RPC implementation for Common Lisp maps types as in the following table. There is a small difference between what types are accepted by the encoder and what types are returned by the decoder. </p> <p> <table border="1"> <tr> <td> XML-RPC Type </td> <td> Accepted Comon Lisp Type </td> <td> Returned Common Lisp Type </td> </tr> <tr> <tr> <td> string </td> <td> string </td> <td> string </td> </tr> <td> int, i4 </td> <td> integer </td> <td> integer </td> </tr> <tr> <td> boolean </td> <td> t or nil </td> <td> t or nil </td> </tr> <tr> <td> double </td> <td> float </td> <td> float </td> </tr> <tr> <td> base64 </td> <td> any array of 1 dimension with at least (unsigned-byte 8) as element type </td> <td> an array of 1 dimension with (unsigned-byte 8) as element type </td> </tr> <tr> <td> is08601.dateTime </td> <td> struct xml-rpc-time </td> <td> struct xml-rpc-time </td> </tr> <tr> <td> array </td> <td> list or vector </td> <td> list </td> </tr> <tr> <td> struct </td> <td> struct xml-rpc-struct </td> <td> struct xml-rpc-struct </td> </tr> </table> <p> Later, generic functions to encode and decode arbitrary CLOS instances could be added. </p> <h3> Base64 </h3> <p> The code in the package "S-BASE64" is an implementation of Base64 encoding and decoding (part of RFC 1521). Encoding takes bytes (a binary stream or a byte array) and produces characters (a character stream or a string). Decoding goes the other way. </p> <h3>Release History</h3> <ul> <li>today: project moved to common-lisp.net</li> <li>release 8, May 9, 2004: added *xml-rpc-authorization* header option (contributed by Nik Gaffney)</li> <li>release 7, March 10, 2004: reorganized code to facilitate porting (added package.lisp and sysdeps.lisp, removed run-xml-rpc-server), integrated contributions from Rudi Schlatte and Brian Mastenbrook; SBCL is now supported; fixed a bug where empty strings were turned into nil, added a test</li> <li>release 6, Januari 21, 2004: ported to LispWorks, added *xml-rpc-package*, *xml-rpc-call-hook* and execute-xml-rpc-call</li> <li>release 5, Januari 20, 2004: added ASDF support, included some contributed patches</li> <li>release 4, June 10, 2003: tracking a minor, but incompatible change in the XML parser</li> <li>release 3, May 25, 2003: the XML parser has been put in a separate package, we are using the more efficient SAX interface of the parser, improved documentation</li> <li>release 2, Januari 6, 2003: we now pass the <a href="http://validator.xmlrpc.com">XML-RPC validator tests</a>, various important bug fixes, improved documentation</li> <li>release 1, December 15, 2002: first public release of working code, not optimized, limited testing</li> </ul> <h3>Mailing Lists</h3> <ul> <li><a href="http://common-lisp.net/mailman/listinfo/s-xml-rpc-cvs">S-XML-RPC-CVS mailing list info</a></li> <li><a href="http://common-lisp.net/mailman/listinfo/s-xml-rpc-devel">S-XML-RPC-DEVEL mailing list info</a></li> <li><a href="http://common-lisp.net/mailman/listinfo/s-xml-rpc-announce">S-XML-RPC-ANNOUNCE mailing list info</a></li> </ul> <p>CVS version $Id: index.html,v 1.4 2004/07/08 19:36:53 scaekenberghe Exp $</p> <div class="footer"> <p>Back to <a href="http://common-lisp.net/">Common-lisp.net</a>.</p> </div> <div class="check"> <a href="http://validator.w3.org/check/referer">Valid XHTML 1.0 Strict</a> <a href="http://jigsaw.w3.org/css-validator/check/referer">Valid CSS</a> </div> </body> </html>
0
apollo_public_repos/apollo-platform/ros/roslisp/s-xml-rpc
apollo_public_repos/apollo-platform/ros/roslisp/s-xml-rpc/doc/style.css
.header { font-size: medium; background-color:#336699; color:#ffffff; border-style:solid; border-width: 5px; border-color:#002244; padding: 1mm 1mm 1mm 5mm; } .footer { font-size: small; font-style: italic; text-align: right; background-color:#336699; color:#ffffff; border-style:solid; border-width: 2px; border-color:#002244; padding: 1mm 1mm 1mm 1mm; } .footer a:link { font-weight:bold; color:#ffffff; text-decoration:underline; } .footer a:visited { font-weight:bold; color:#ffffff; text-decoration:underline; } .footer a:hover { font-weight:bold; color:#002244; text-decoration:underline; } .check {font-size: x-small; text-align:right;} .check a:link { font-weight:bold; color:#a0a0ff; text-decoration:underline; } .check a:visited { font-weight:bold; color:#a0a0ff; text-decoration:underline; } .check a:hover { font-weight:bold; color:#000000; text-decoration:underline; }
0
apollo_public_repos/apollo-platform/ros/roslisp/s-xml-rpc
apollo_public_repos/apollo-platform/ros/roslisp/s-xml-rpc/doc/S-XML-RPC.html
<html><head><title>S-XML-RPC</title></head><body><h3>API for package S-XML-RPC</h3> <blockquote>An implementation of the standard XML-RPC protocol for both client and server</blockquote> <p><b>*xml-rpc-agent*</b>&nbsp;&nbsp;&nbsp;<i>variable</i></p> <blockquote>String specifying the default XML-RPC agent to include in server responses</blockquote> <blockquote>Initial value: <tt>"LispWorks 4.3.7"</tt></blockquote> <p><b>*xml-rpc-authorization*</b>&nbsp;&nbsp;&nbsp;<i>variable</i></p> <blockquote>When not null, a string to be used as Authorization header</blockquote> <blockquote>Initial value: <tt>NIL</tt></blockquote> <p><b>*xml-rpc-call-hook*</b>&nbsp;&nbsp;&nbsp;<i>variable</i></p> <blockquote>A function to execute the xml-rpc call and return the result, accepting a method-name string and a optional argument list</blockquote> <blockquote>Initial value: <tt>EXECUTE-XML-RPC-CALL</tt></blockquote> <p><b>*xml-rpc-debug*</b>&nbsp;&nbsp;&nbsp;<i>variable</i></p> <blockquote>When T the XML-RPC client and server part will be more verbose about their protocol</blockquote> <blockquote>Initial value: <tt>NIL</tt></blockquote> <p><b>*xml-rpc-debug-stream*</b>&nbsp;&nbsp;&nbsp;<i>variable</i></p> <blockquote>When not nil it specifies where debugging output should be written to</blockquote> <blockquote>Initial value: <tt>NIL</tt></blockquote> <p><b>*xml-rpc-host*</b>&nbsp;&nbsp;&nbsp;<i>variable</i></p> <blockquote>String naming the default XML-RPC host to use</blockquote> <blockquote>Initial value: <tt>"localhost"</tt></blockquote> <p><b>*xml-rpc-package*</b>&nbsp;&nbsp;&nbsp;<i>variable</i></p> <blockquote>Package for XML-RPC callable functions</blockquote> <blockquote>Initial value: <tt>#<The S-XML-RPC-EXPORTS package, 29/64 internal, 0/16 external></tt></blockquote> <p><b>*xml-rpc-port*</b>&nbsp;&nbsp;&nbsp;<i>variable</i></p> <blockquote>Integer specifying the default XML-RPC port to use</blockquote> <blockquote>Initial value: <tt>80</tt></blockquote> <p><b>*xml-rpc-proxy-host*</b>&nbsp;&nbsp;&nbsp;<i>variable</i></p> <blockquote>When not null, a string naming the XML-RPC proxy host to use</blockquote> <blockquote>Initial value: <tt>NIL</tt></blockquote> <p><b>*xml-rpc-proxy-port*</b>&nbsp;&nbsp;&nbsp;<i>variable</i></p> <blockquote>When not null, an integer specifying the XML-RPC proxy port to use</blockquote> <blockquote>Initial value: <tt>NIL</tt></blockquote> <p><b>*xml-rpc-url*</b>&nbsp;&nbsp;&nbsp;<i>variable</i></p> <blockquote>String specifying the default XML-RPC URL to use</blockquote> <blockquote>Initial value: <tt>"/RPC2"</tt></blockquote> <p>(<b>call-xml-rpc-server</b> server-keywords name &rest args)&nbsp;&nbsp;&nbsp;<i>function</i></p> <blockquote>Encode and execute an XML-RPC call with name and args, using the list of server-keywords</blockquote> <p>(<b>encode-xml-rpc-call</b> name &rest args)&nbsp;&nbsp;&nbsp;<i>function</i></p> <blockquote>Encode an XML-RPC call with name and args as an XML string</blockquote> <p>(<b>execute-xml-rpc-call</b> method-name &rest arguments)&nbsp;&nbsp;&nbsp;<i>function</i></p> <blockquote>Execute method METHOD-NAME on ARGUMENTS, or raise an error if no such method exists in *XML-RPC-PACKAGE*</blockquote> <p>(<b>get-xml-rpc-struct-member</b> struct member)&nbsp;&nbsp;&nbsp;<i>function</i></p> <blockquote>Get the value of a specific member of an XML-RPC-STRUCT</blockquote> <p>(setf (<b>get-xml-rpc-struct-member</b> struct member) value)&nbsp;&nbsp;&nbsp;<i>function</i></p> <blockquote>Set the value of a specific member of an XML-RPC-STRUCT</blockquote> <p>(<b>start-xml-rpc-server</b> &key (port *xml-rpc-port*) (url *xml-rpc-url*) (agent *xml-rpc-agent*))&nbsp;&nbsp;&nbsp;<i>function</i></p> <blockquote>Start an XML-RPC server in a separate process</blockquote> <p>(<b>stop-server</b> name)&nbsp;&nbsp;&nbsp;<i>function</i></p> <blockquote>Kill a server process by name (as started by start-standard-server)</blockquote> <p>(<b>system.listmethods</b>)&nbsp;&nbsp;&nbsp;<i>function</i></p> <blockquote>List the methods that are available on this server.</blockquote> <p>(<b>system.methodhelp</b> method-name)&nbsp;&nbsp;&nbsp;<i>function</i></p> <blockquote>Returns the function documentation for the given method.</blockquote> <p>(<b>system.methodsignature</b> method-name)&nbsp;&nbsp;&nbsp;<i>function</i></p> <blockquote>Dummy system.methodSignature implementation. There's no way to get (and no concept of) required argument types in Lisp, so this function always returns nil or errors.</blockquote> <p>(<b>system.multicall</b> calls)&nbsp;&nbsp;&nbsp;<i>function</i></p> <blockquote>Implement system.multicall; see http://www.xmlrpc.com/discuss/msgReader$1208 for the specification.</blockquote> <p>(<b>xml-rpc-call</b> encoded &key (url *xml-rpc-url*) (agent *xml-rpc-agent*) (host *xml-rpc-host*) (port *xml-rpc-port*) (authorization *xml-rpc-authorization*) (proxy-host *xml-rpc-proxy-host*) (proxy-port *xml-rpc-proxy-port*))&nbsp;&nbsp;&nbsp;<i>function</i></p> <blockquote>Execute an already encoded XML-RPC call and return the decoded result</blockquote> <p><b>xml-rpc-condition</b>&nbsp;&nbsp;&nbsp;<i>condition</i></p> <blockquote>Parent condition for all conditions thrown by the XML-RPC package</blockquote> <blockquote>Class precedence list: <tt> xml-rpc-condition error serious-condition condition standard-object t</tt></blockquote> <p><b>xml-rpc-error</b>&nbsp;&nbsp;&nbsp;<i>condition</i></p> <blockquote>This condition is thrown when an XML-RPC protocol error occurs</blockquote> <blockquote>Class precedence list: <tt> xml-rpc-error xml-rpc-condition error serious-condition condition standard-object t</tt></blockquote> <blockquote>Class init args: <tt> :data :code</tt></blockquote> <p>(<b>xml-rpc-error-data</b> xml-rpc-error)&nbsp;&nbsp;&nbsp;<i>generic-function</i></p> <blockquote>Get the data from an XML-RPC error</blockquote> <p>(<b>xml-rpc-error-place</b> xml-rpc-error)&nbsp;&nbsp;&nbsp;<i>generic-function</i></p> <blockquote>Get the place from an XML-RPC error</blockquote> <p><b>xml-rpc-fault</b>&nbsp;&nbsp;&nbsp;<i>condition</i></p> <blockquote>This condition is thrown when the XML-RPC server returns a fault</blockquote> <blockquote>Class precedence list: <tt> xml-rpc-fault xml-rpc-condition error serious-condition condition standard-object t</tt></blockquote> <blockquote>Class init args: <tt> :string :code</tt></blockquote> <p>(<b>xml-rpc-fault-code</b> xml-rpc-fault)&nbsp;&nbsp;&nbsp;<i>generic-function</i></p> <blockquote>Get the code from an XML-RPC fault</blockquote> <p>(<b>xml-rpc-fault-string</b> xml-rpc-fault)&nbsp;&nbsp;&nbsp;<i>generic-function</i></p> <blockquote>Get the string from an XML-RPC fault</blockquote> <p><b>xml-rpc-struct</b>&nbsp;&nbsp;&nbsp;<i>structure</i></p> <blockquote>An XML-RPC-STRUCT is an associative map of member names and values</blockquote> <p>(<b>xml-rpc-struct</b> &rest args)&nbsp;&nbsp;&nbsp;<i>function</i></p> <blockquote>Create a new XML-RPC-STRUCT from the arguments: alternating member names and values</blockquote> <p>(<b>xml-rpc-struct-alist</b> object)&nbsp;&nbsp;&nbsp;<i>function</i></p> <blockquote>Return the alist of member names and values from an XML-RPC struct</blockquote> <p>(<b>xml-rpc-struct-equal</b> struct1 struct2)&nbsp;&nbsp;&nbsp;<i>function</i></p> <blockquote>Compare two XML-RPC-STRUCTs for equality</blockquote> <p>(<b>xml-rpc-struct-p</b> object)&nbsp;&nbsp;&nbsp;<i>function</i></p> <blockquote>Return T when the argument is an XML-RPC struct</blockquote> <p><b>xml-rpc-time</b>&nbsp;&nbsp;&nbsp;<i>structure</i></p> <blockquote>A wrapper around a Common Lisp universal time to be interpreted as an XML-RPC-TIME</blockquote> <p>(<b>xml-rpc-time</b> &optional (universal-time (get-universal-time)))&nbsp;&nbsp;&nbsp;<i>function</i></p> <blockquote>Create a new XML-RPC-TIME struct with the universal time specified, defaulting to now</blockquote> <p>(<b>xml-rpc-time-p</b> object)&nbsp;&nbsp;&nbsp;<i>function</i></p> <blockquote>Return T when the argument is an XML-RPC time</blockquote> <p>(<b>xml-rpc-time-universal-time</b> object)&nbsp;&nbsp;&nbsp;<i>function</i></p> <blockquote>Return the universal time from an XML-RPC time</blockquote> <font size=-1><p>Documentation generated by <a href="http://homepage.mac.com/svc/lispdoc/">lispdoc</a> running on LispWorks</p></font></body></html>
0
apollo_public_repos/apollo-platform/ros/roslisp/s-xml-rpc
apollo_public_repos/apollo-platform/ros/roslisp/s-xml-rpc/src/validator1-server.lisp
;;;; -*- mode: lisp -*- ;;;; ;;;; $Id: validator1-server.lisp,v 1.1 2004/06/14 20:11:55 scaekenberghe Exp $ ;;;; ;;;; This is a Common Lisp implementation of the XML-RPC 'validator1' ;;;; server test suite, as live testable from the website ;;;; http://validator.xmlrpc.com and documented on the web page ;;;; http://www.xmlrpc.com/validator1Docs ;;;; ;;;; Copyright (C) 2002, 2004 Sven Van Caekenberghe, Beta Nine BVBA. ;;;; ;;;; You are granted the rights to distribute and use this software ;;;; as governed by the terms of the Lisp Lesser General Public License ;;;; (http://opensource.franz.com/preamble.html), also known as the LLGPL. (in-package :s-xml-rpc) (defun |validator1.echoStructTest| (struct) (assert (xml-rpc-struct-p struct)) struct) (defun |validator1.easyStructTest| (struct) (assert (xml-rpc-struct-p struct)) (+ (get-xml-rpc-struct-member struct :|moe|) (get-xml-rpc-struct-member struct :|larry|) (get-xml-rpc-struct-member struct :|curly|))) (defun |validator1.countTheEntities| (string) (assert (stringp string)) (let ((left-angle-brackets (count #\< string)) (right-angle-brackets (count #\> string)) (apostrophes (count #\' string)) (quotes (count #\" string)) (ampersands (count #\& string))) (xml-rpc-struct :|ctLeftAngleBrackets| left-angle-brackets :|ctRightAngleBrackets| right-angle-brackets :|ctApostrophes| apostrophes :|ctQuotes| quotes :|ctAmpersands| ampersands))) (defun |validator1.manyTypesTest| (number boolean string double dateTime base64) (assert (and (integerp number) (or (null boolean) (eq boolean t)) (stringp string) (floatp double) (xml-rpc-time-p dateTime) (and (arrayp base64) (= (array-rank base64) 1) (subtypep (array-element-type base64) '(unsigned-byte 8))))) (list number boolean string double dateTime base64)) (defun |validator1.arrayOfStructsTest| (array) (assert (listp array)) (reduce #'+ (mapcar #'(lambda (struct) (assert (xml-rpc-struct-p struct)) (get-xml-rpc-struct-member struct :|curly|)) array) :initial-value 0)) (defun |validator1.simpleStructReturnTest| (number) (assert (integerp number)) (xml-rpc-struct :|times10| (* number 10) :|times100| (* number 100) :|times1000| (* number 1000))) (defun |validator1.moderateSizeArrayCheck| (array) (assert (listp array)) (concatenate 'string (first array) (first (last array)))) (defun |validator1.nestedStructTest| (struct) (assert (xml-rpc-struct-p struct)) (let* ((year (get-xml-rpc-struct-member struct :\2000)) (april (get-xml-rpc-struct-member year :\04)) (first (get-xml-rpc-struct-member april :\01))) (|validator1.easyStructTest| first))) (import '(|validator1.echoStructTest| |validator1.easyStructTest| |validator1.countTheEntities| |validator1.manyTypesTest| |validator1.arrayOfStructsTest| |validator1.simpleStructReturnTest| |validator1.moderateSizeArrayCheck| |validator1.nestedStructTest|) :s-xml-rpc-exports) ;;;; eof
0
apollo_public_repos/apollo-platform/ros/roslisp/s-xml-rpc
apollo_public_repos/apollo-platform/ros/roslisp/s-xml-rpc/src/package.lisp
;;;; -*- mode: lisp -*- ;;;; ;;;; $Id: package.lisp,v 1.4 2004/06/17 19:43:11 rschlatte Exp $ ;;;; ;;;; S-XML-RPC package definition ;;;; ;;;; Copyright (C) 2002, 2004 Sven Van Caekenberghe, Beta Nine BVBA. ;;;; ;;;; You are granted the rights to distribute and use this software ;;;; as governed by the terms of the Lisp Lesser GNU Public License ;;;; (http://opensource.franz.com/preamble.html), also known as the LLGPL. (defpackage s-xml-rpc (:use common-lisp #+ccl ccl #+lispworks mp #+lispworks comm s-xml s-base64) (:export #:xml-rpc-call #:encode-xml-rpc-call #:call-xml-rpc-server #:xml-rpc-condition #:xml-rpc-fault #:xml-rpc-fault-code #:xml-rpc-fault-string #:xml-rpc-error #:xml-rpc-error-place #:xml-rpc-error-data #:start-xml-rpc-server #:xml-rpc-time #:xml-rpc-time-p #:xml-rpc-time-universal-time #:xml-rpc-struct #:xml-rpc-struct-p #:xml-rpc-struct-alist #:get-xml-rpc-struct-member #:xml-rpc-struct-equal #:*xml-rpc-host* #:*xml-rpc-port* #:*xml-rpc-url* #:*xml-rpc-agent* #:*xml-rpc-proxy-host* #:*xml-rpc-proxy-port* #:*xml-rpc-authorization* #:*xml-rpc-debug* #:*xml-rpc-debug-stream* #:*xml-rpc-package* #:*xml-rpc-call-hook* #:execute-xml-rpc-call #:stop-server #:|system.listMethods| #:|system.methodSignature| #:|system.methodHelp| #:|system.multicall| #:|system.getCapabilities|) (:documentation "An implementation of the standard XML-RPC protocol for both client and server")) (defpackage s-xml-rpc-exports (:use) (:import-from :s-xml-rpc #:|system.listMethods| #:|system.methodSignature| #:|system.methodHelp| #:|system.multicall| #:|system.getCapabilities|) (:documentation "This package contains the functions callable via xml-rpc.")) ;;;; eof
0
apollo_public_repos/apollo-platform/ros/roslisp/s-xml-rpc
apollo_public_repos/apollo-platform/ros/roslisp/s-xml-rpc/src/extensions.lisp
;;;; -*- mode: lisp -*- ;;;; ;;;; $Id: extensions.lisp,v 1.1 2004/06/17 19:43:11 rschlatte Exp $ ;;;; ;;;; Extensions for xml-rpc: ;;;; ;;;; Server introspection: ;;;; http://xmlrpc.usefulinc.com/doc/reserved.html ;;;; ;;;; Multicall: ;;;; http://www.xmlrpc.com/discuss/msgReader$1208 ;;;; ;;;; Capabilities: ;;;; http://groups.yahoo.com/group/xml-rpc/message/2897 ;;;; ;;;; ;;;; Copyright (C) 2004 Rudi Schlatte ;;;; ;;;; You are granted the rights to distribute and use this software ;;;; as governed by the terms of the Lisp Lesser General Public License ;;;; (http://opensource.franz.com/preamble.html), also known as the LLGPL. (in-package :s-xml-rpc) ;;; Introspection (defun |system.listMethods| () "List the methods that are available on this server." (let ((result nil)) (do-symbols (sym *xml-rpc-package* (sort result #'string-lessp)) (when (and (fboundp sym) (valid-xml-rpc-method-name-p (symbol-name sym))) (push (symbol-name sym) result))))) (defun |system.methodSignature| (method-name) "Dummy system.methodSignature implementation. There's no way to get (and no concept of) required argument types in Lisp, so this function always returns nil or errors." (let ((method (find-xml-rpc-method method-name))) (if method ;; http://xmlrpc.usefulinc.com/doc/sysmethodsig.html says to ;; return a non-array if the signature is not available "n/a" (error "Method ~A not found." method-name)))) (defun |system.methodHelp| (method-name) "Returns the function documentation for the given method." (let ((method (find-xml-rpc-method method-name))) (if method (or (documentation method 'function) "") (error "Method ~A not found." method-name)))) ;;; system.multicall (defun do-one-multicall (call-struct) (let ((name (get-xml-rpc-struct-member call-struct :|methodName|)) (params (get-xml-rpc-struct-member call-struct :|params|))) (handler-bind ((xml-rpc-fault #'(lambda (c) (format-debug (or *xml-rpc-debug-stream* t) "Call to ~A in system.multicall failed with ~a~%" name c) (return-from do-one-multicall (xml-literal (encode-xml-rpc-fault-value (xml-rpc-fault-string c) (xml-rpc-fault-code c)))))) (error #'(lambda (c) (format-debug (or *xml-rpc-debug-stream* t) "Call to ~A in system.multicall failed with ~a~%" name c) (return-from do-one-multicall (xml-literal (encode-xml-rpc-fault-value ;; -32603 ---> server error. internal xml-rpc error (format nil "~a" c) -32603)))))) (format-debug (or *xml-rpc-debug-stream* t) "system.multicall calling ~a with ~s~%" name params) (let ((result (apply *xml-rpc-call-hook* name params))) (list result))))) (defun |system.multicall| (calls) "Implement system.multicall; see http://www.xmlrpc.com/discuss/msgReader$1208 for the specification." (mapcar #'do-one-multicall calls)) ;;; system.getCapabilities (defun |system.getCapabilities| () "Get a list of supported capabilities; see http://groups.yahoo.com/group/xml-rpc/message/2897 for the specification." (let ((capabilities '("xmlrpc" ("specUrl" "http://www.xmlrpc.com/spec" "specVersion" 1) "introspect" ("specUrl" "http://xmlrpc.usefulinc.com/doc/reserved.html" "specVersion" 1) "multicall" ("specUrl" "http://www.xmlrpc.com/discuss/msgReader$1208" "specVersion" 1) "faults_interop" ("specUrl" "http://xmlrpc-epi.sourceforge.net/specs/rfc.fault_codes.php" "specVersion" 20010516)))) (apply #'xml-rpc-struct (loop for (name description) on capabilities by #'cddr collecting name collecting (apply #'xml-rpc-struct description))))) ;;;; eof
0
apollo_public_repos/apollo-platform/ros/roslisp/s-xml-rpc
apollo_public_repos/apollo-platform/ros/roslisp/s-xml-rpc/src/aserve.lisp
;;;; -*- mode: lisp -*- ;;;; ;;;; $Id: aserve.lisp,v 1.1.1.1 2004/06/09 09:02:39 scaekenberghe Exp $ ;;;; ;;;; This file implements XML-RPC client and server networking based ;;;; on (Portable) AllegroServe (see http://opensource.franz.com/aserve/ ;;;; or http://sourceforge.net/projects/portableaserve/), which you have ;;;; to install first. ;;;; ;;;; Copyright (C) 2002, 2004 Sven Van Caekenberghe. ;;;; ;;;; You are granted the rights to distribute and use this software ;;;; as governed by the terms of the Lisp Lesser GNU Public License ;;;; (http://opensource.franz.com/preamble.html), also known as the LLGPL. (defpackage xml-rpc-aserve (:use common-lisp net.aserve.client net.aserve xml-rpc) (:export "XML-RPC-CALL" "START-XML-RPC-ASERVE" "PUBLISH-ASERVE-XML-RPC-HANDLER")) (in-package :xml-rpc-aserve) (defun xml-rpc-call-aserve (encoded &key (url *xml-rpc-url*) (agent *xml-rpc-agent*) (host *xml-rpc-host*) (port *xml-rpc-port*) (basic-autorization *xml-rpc-authorization*) (proxy)) (let ((xml (print-xml-string encoded))) (multiple-value-bind (response response-code headers uri) (do-http-request (format nil "http://~a:~d~a" host port url) :method :post :protocol :http/1.0 :user-agent agent :content-type "text/xml" :basic-authorization basic-autorization :content xml :proxy proxy) (declare (ignore headers uri)) (if (= response-code 200) (let ((result (decode-xml-rpc (make-string-input-stream response)))) (if (typep result 'xml-rpc-fault) (error result) (car result))) (error "http-error:~d" response-code))))) (defun start-xml-rpc-aserve (&key (port *xml-rpc-port*)) (process-run-function "aserve-xml-rpc" #'(lambda () (start :port port :listeners 4 :chunking nil :keep-alive nil)))) (defun publish-aserve-xml-rpc-handler (&key (url *xml-rpc-url*) (agent *xml-rpc-agent*)) (declare (ignore agent)) (publish :path url :content-type "text/xml" :function #'aserve-xml-rpc-handler)) (defun aserve-xml-rpc-handler (request entity) (with-http-response (request entity :response (if (eq :post (request-method request)) *response-ok* *response-bad-request*)) (with-http-body (request entity) (let ((body (get-request-body request)) (id (process-name *current-process*))) (with-input-from-string (in body) (let ((xml (handle-xml-rpc-call in id))) (format-debug t "~d sending ~a~%" id xml) (princ xml *html-stream*))))))) ;;;; eof
0
apollo_public_repos/apollo-platform/ros/roslisp/s-xml-rpc
apollo_public_repos/apollo-platform/ros/roslisp/s-xml-rpc/src/base64.lisp
;;;; -*- mode: lisp -*- ;;;; ;;;; $Id: base64.lisp,v 1.1.1.1 2004/06/09 09:02:39 scaekenberghe Exp $ ;;;; ;;;; This is a Common Lisp implementation of Base64 encoding and decoding. ;;;; ;;;; Copyright (C) 2002, 2004 Sven Van Caekenberghe, Beta Nine BVBA. ;;;; ;;;; You are granted the rights to distribute and use this software ;;;; as governed by the terms of the Lisp Lesser General Public License ;;;; (http://opensource.franz.com/preamble.html), also known as the LLGPL. (defpackage s-base64 (:use common-lisp) (:export "DECODE-BASE64" "ENCODE-BASE64" "DECODE-BASE64-BYTES" "ENCODE-BASE64-BYTES") (:documentation "An implementation of standard Base64 encoding and decoding")) (in-package :s-base64) (defparameter +base64-alphabet+ "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/") (defparameter +inverse-base64-alphabet+ (let ((inverse-base64-alphabet (make-array char-code-limit))) (dotimes (i char-code-limit inverse-base64-alphabet) (setf (aref inverse-base64-alphabet i) (position (code-char i) +base64-alphabet+))))) (defun core-encode-base64 (byte1 byte2 byte3) (values (char +base64-alphabet+ (ash byte1 -2)) (char +base64-alphabet+ (logior (ash (logand byte1 #B11) 4) (ash (logand byte2 #B11110000) -4))) (char +base64-alphabet+ (logior (ash (logand byte2 #B00001111) 2) (ash (logand byte3 #B11000000) -6))) (char +base64-alphabet+ (logand byte3 #B111111)))) (defun core-decode-base64 (char1 char2 char3 char4) (let ((v1 (aref +inverse-base64-alphabet+ (char-code char1))) (v2 (aref +inverse-base64-alphabet+ (char-code char2))) (v3 (aref +inverse-base64-alphabet+ (char-code char3))) (v4 (aref +inverse-base64-alphabet+ (char-code char4)))) (values (logior (ash v1 2) (ash v2 -4)) (logior (ash (logand v2 #B1111) 4) (ash v3 -2)) (logior (ash (logand v3 #B11) 6) v4)))) (defun skip-base64-whitespace (stream) (loop (let ((char (peek-char nil stream nil nil))) (cond ((null char) (return nil)) ((null (aref +inverse-base64-alphabet+ (char-code char))) (read-char stream)) (t (return char)))))) (defun decode-base64-bytes (stream) "Decode a base64 encoded character stream, returns a byte array" (let ((out (make-array 256 :element-type '(unsigned-byte 8) :adjustable t :fill-pointer 0))) (loop (skip-base64-whitespace stream) (let ((in1 (read-char stream nil nil)) (in2 (read-char stream nil nil)) (in3 (read-char stream nil nil)) (in4 (read-char stream nil nil))) (if (null in1) (return)) (if (or (null in2) (null in3) (null in4)) (error "input not aligned/padded")) (multiple-value-bind (out1 out2 out3) (core-decode-base64 in1 in2 (if (char= in3 #\=) #\A in3) (if (char= in4 #\=) #\A in4)) (vector-push-extend out1 out) (when (char/= in3 #\=) (vector-push-extend out2 out) (when (char/= in4 #\=) (vector-push-extend out3 out)))))) out)) (defun encode-base64-bytes (array stream &optional (break-lines t)) "Encode a byte array into a base64b encoded character stream" (let ((index 0) (counter 0) (len (length array))) (loop (when (>= index len) (return)) (let ((in1 (aref array index)) (in2 (if (< (+ index 1) len) (aref array (+ index 1)) nil)) (in3 (if (< (+ index 2) len) (aref array (+ index 2)) nil))) (multiple-value-bind (out1 out2 out3 out4) (core-encode-base64 in1 (if (null in2) 0 in2) (if (null in3) 0 in3)) (write-char out1 stream) (write-char out2 stream) (if (null in2) (progn (write-char #\= stream) (write-char #\= stream)) (progn (write-char out3 stream) (if (null in3) (write-char #\= stream) (write-char out4 stream)))) (incf index 3) (incf counter 4) (when (and break-lines (= counter 76)) (terpri stream) (setf counter 0))))))) (defun decode-base64 (in out) "Decode a base64 encoded character input stream into a binary output stream" (loop (skip-base64-whitespace in) (let ((in1 (read-char in nil nil)) (in2 (read-char in nil nil)) (in3 (read-char in nil nil)) (in4 (read-char in nil nil))) (if (null in1) (return)) (if (or (null in2) (null in3) (null in4)) (error "input not aligned/padded")) (multiple-value-bind (out1 out2 out3) (core-decode-base64 in1 in2 (if (char= in3 #\=) #\A in3) (if (char= in4 #\=) #\A in4)) (write-byte out1 out) (when (char/= in3 #\=) (write-byte out2 out) (when (char/= in4 #\=) (write-byte out3 out))))))) (defun encode-base64 (in out &optional (break-lines t)) "Encode a binary input stream into a base64 encoded character output stream" (let ((counter 0)) (loop (let ((in1 (read-byte in nil nil)) (in2 (read-byte in nil nil)) (in3 (read-byte in nil nil))) (if (null in1) (return)) (multiple-value-bind (out1 out2 out3 out4) (core-encode-base64 in1 (if (null in2) 0 in2) (if (null in3) 0 in3)) (write-char out1 out) (write-char out2 out) (if (null in2) (progn (write-char #\= out) (write-char #\= out)) (progn (write-char out3 out) (if (null in3) (write-char #\= out) (write-char out4 out)))) (incf counter 4) (when (and break-lines (= counter 76)) (terpri out) (setf counter 0))))))) ;;;; eof
0
apollo_public_repos/apollo-platform/ros/roslisp/s-xml-rpc
apollo_public_repos/apollo-platform/ros/roslisp/s-xml-rpc/src/xml-rpc.lisp
;;;; -*- mode: lisp -*- ;;;; ;;;; $Id: xml-rpc.lisp,v 1.4 2004/06/17 19:43:11 rschlatte Exp $ ;;;; ;;;; This is a Common Lisp implementation of the XML-RPC protocol, ;;;; as documented on the website http://www.xmlrpc.com ;;;; This implementation includes both a client and server part. ;;;; A Base64 encoder/decoder and a minimal XML parser are required. ;;;; ;;;; Copyright (C) 2002, 2004 Sven Van Caekenberghe, Beta Nine BVBA. ;;;; ;;;; You are granted the rights to distribute and use this software ;;;; as governed by the terms of the Lisp Lesser General Public License ;;;; (http://opensource.franz.com/preamble.html), also known as the LLGPL. (in-package :s-xml-rpc) ;;; conditions (define-condition xml-rpc-condition (error) () (:documentation "Parent condition for all conditions thrown by the XML-RPC package")) (define-condition xml-rpc-fault (xml-rpc-condition) ((code :initarg :code :reader xml-rpc-fault-code) (string :initarg :string :reader xml-rpc-fault-string)) (:report (lambda (condition stream) (format stream "XML-RPC fault with message '~a' and code ~d." (xml-rpc-fault-string condition) (xml-rpc-fault-code condition)))) (:documentation "This condition is thrown when the XML-RPC server returns a fault")) (setf (documentation 'xml-rpc-fault-code 'function) "Get the code from an XML-RPC fault") (setf (documentation 'xml-rpc-fault-string 'function) "Get the string from an XML-RPC fault") (define-condition xml-rpc-error (xml-rpc-condition) ((place :initarg :code :reader xml-rpc-error-place) (data :initarg :data :reader xml-rpc-error-data)) (:report (lambda (condition stream) (format stream "XML-RPC error ~a at ~a." (xml-rpc-error-data condition) (xml-rpc-error-place condition)))) (:documentation "This condition is thrown when an XML-RPC protocol error occurs")) (setf (documentation 'xml-rpc-error-place 'function) "Get the place from an XML-RPC error" (documentation 'xml-rpc-error-data 'function) "Get the data from an XML-RPC error") ;;; iso8601 support (the xml-rpc variant) (defun universal-time->iso8601 (time &optional (stream nil)) "Convert a Common Lisp universal time to a string in the XML-RPC variant of ISO8601" (multiple-value-bind (second minute hour date month year) (decode-universal-time time) (format stream "~d~2,'0d~2,'0dT~2,'0d:~2,'0d:~2,'0d" year month date hour minute second))) (defun iso8601->universal-time (string) "Convert string in the XML-RPC variant of ISO8601 to a Common Lisp universal time" (let (year month date (hour 0) (minute 0) (second 0)) (when (< (length string) 9) (error "~s is to short to represent an iso8601" string)) (setf year (parse-integer string :start 0 :end 4) month (parse-integer string :start 4 :end 6) date (parse-integer string :start 6 :end 8)) (when (and (>= (length string) 17) (char= #\T (char string 8))) (setf hour (parse-integer string :start 9 :end 11) minute (parse-integer string :start 12 :end 14) second (parse-integer string :start 15 :end 17))) (encode-universal-time second minute hour date month year))) (defstruct (xml-rpc-time (:print-function print-xml-rpc-time)) "A wrapper around a Common Lisp universal time to be interpreted as an XML-RPC-TIME" universal-time) (setf (documentation 'xml-rpc-time-p 'function) "Return T when the argument is an XML-RPC time" (documentation 'xml-rpc-time-universal-time 'function) "Return the universal time from an XML-RPC time") (defun print-xml-rpc-time (xml-rpc-time stream depth) (declare (ignore depth)) (format stream "#<XML-RPC-TIME ~a>" (universal-time->iso8601 (xml-rpc-time-universal-time xml-rpc-time)))) (defun xml-rpc-time (&optional (universal-time (get-universal-time))) "Create a new XML-RPC-TIME struct with the universal time specified, defaulting to now" (make-xml-rpc-time :universal-time universal-time)) ;;; a wrapper for literal strings, where escaping #\< and #\& is not ;;; desired (defstruct (xml-literal (:print-function print-xml-literal)) "A wrapper around a Common Lisp string that will be sent over the wire unescaped" content) (setf (documentation 'xml-literal-p 'function) "Return T when the argument is an unescaped xml string" (documentation 'xml-literal-content 'function) "Return the content of a literal xml string") (defun print-xml-literal (xml-literal stream depth) (declare (ignore depth)) (format stream "#<XML-LITERAL \"~a\" >" (xml-literal-content xml-literal))) (defun xml-literal (content) "Create a new XML-LITERAL struct with the specified content." (make-xml-literal :content content)) ;;; an extra datatype for xml-rpc structures (associative maps) (defstruct (xml-rpc-struct (:print-function print-xml-rpc-struct)) "An XML-RPC-STRUCT is an associative map of member names and values" alist) (setf (documentation 'xml-rpc-struct-p 'function) "Return T when the argument is an XML-RPC struct" (documentation 'xml-rpc-struct-alist 'function) "Return the alist of member names and values from an XML-RPC struct") (defun print-xml-rpc-struct (xml-element stream depth) (declare (ignore depth)) (format stream "#<XML-RPC-STRUCT~{ ~S~}>" (xml-rpc-struct-alist xml-element))) (defun get-xml-rpc-struct-member (struct member) "Get the value of a specific member of an XML-RPC-STRUCT" (cdr (assoc member (xml-rpc-struct-alist struct)))) (defun (setf get-xml-rpc-struct-member) (value struct member) "Set the value of a specific member of an XML-RPC-STRUCT" (let ((pair (assoc member (xml-rpc-struct-alist struct)))) (if pair (rplacd pair value) (push (cons member value) (xml-rpc-struct-alist struct))) value)) (defun xml-rpc-struct (&rest args) "Create a new XML-RPC-STRUCT from the arguments: alternating member names and values" (unless (evenp (length args)) (error "~s must contain an even number of elements" args)) (let (alist) (loop (if (null args) (return) (push (cons (pop args) (pop args)) alist))) (make-xml-rpc-struct :alist alist))) (defun xml-rpc-struct-equal (struct1 struct2) "Compare two XML-RPC-STRUCTs for equality" (if (and (xml-rpc-struct-p struct1) (xml-rpc-struct-p struct2) (= (length (xml-rpc-struct-alist struct1)) (length (xml-rpc-struct-alist struct2)))) (dolist (assoc (xml-rpc-struct-alist struct1) t) (unless (equal (get-xml-rpc-struct-member struct2 (car assoc)) (cdr assoc)) (return-from xml-rpc-struct-equal nil))) nil)) ;;; encoding support (defun encode-xml-rpc-struct (struct stream) (princ "<struct>" stream) (dolist (member (xml-rpc-struct-alist struct)) (princ "<member>" stream) (format stream "<name>~a</name>" (car member)) ; assuming name contains no special characters (encode-xml-rpc-value (cdr member) stream) (princ "</member>" stream)) (princ "</struct>" stream)) (defun encode-xml-rpc-array (sequence stream) (princ "<array><data>" stream) (map 'nil #'(lambda (element) (encode-xml-rpc-value element stream)) sequence) (princ "</data></array>" stream)) (defun encode-xml-rpc-value (arg stream) (princ "<value>" stream) (cond ((integerp arg) (format stream "<int>~d</int>" arg)) ((floatp arg) (format stream "<double>~f</double>" arg)) ((or (null arg) (eq arg t)) (princ "<boolean>" stream) (princ (if arg 1 0) stream) (princ "</boolean>" stream)) ((or (stringp arg) (symbolp arg)) (princ "<string>" stream) (print-string-xml (string arg) stream) (princ "</string>" stream)) ((and (arrayp arg) (= (array-rank arg) 1) (subtypep (array-element-type arg) '(unsigned-byte 8))) (princ "<base64>" stream) (encode-base64-bytes arg stream) (princ "</base64>" stream)) ((xml-rpc-time-p arg) (princ "<dateTime.iso8601>" stream) (universal-time->iso8601 (xml-rpc-time-universal-time arg) stream) (princ "</dateTime.iso8601>" stream)) ((xml-literal-p arg) (princ (xml-literal-content arg) stream)) ((or (listp arg) (vectorp arg)) (encode-xml-rpc-array arg stream)) ((xml-rpc-struct-p arg) (encode-xml-rpc-struct arg stream)) ;; add generic method call (t (error "cannot encode ~s" arg))) (princ "</value>" stream)) (defun encode-xml-rpc-args (args stream) (princ "<params>" stream) (dolist (arg args) (princ "<param>" stream) (encode-xml-rpc-value arg stream) (princ "</param>" stream)) (princ "</params>" stream)) (defun encode-xml-rpc-call (name &rest args) "Encode an XML-RPC call with name and args as an XML string" (with-output-to-string (stream) (princ "<methodCall>" stream) ;; Spec says: The string may only contain identifier characters, ;; upper and lower-case A-Z, the numeric characters, 0-9, ;; underscore, dot, colon and slash. (format stream "<methodName>~a</methodName>" (string name)) ; assuming name contains no special characters (when args (encode-xml-rpc-args args stream)) (princ "</methodCall>" stream))) (defun encode-xml-rpc-result (value) (with-output-to-string (stream) (princ "<methodResponse>" stream) (encode-xml-rpc-args (list value) stream) (princ "</methodResponse>" stream))) (defun encode-xml-rpc-fault-value (fault-string &optional (fault-code 0)) ;; for system.multicall (with-output-to-string (stream) (princ "<struct>" stream) (format stream "<member><name>faultCode</name><value><int>~d</int></value></member>" fault-code) (princ "<member><name>faultString</name><value><string>" stream) (print-string-xml fault-string stream) (princ "</string></value></member>" stream) (princ "</struct>" stream))) (defun encode-xml-rpc-fault (fault-string &optional (fault-code 0)) (with-output-to-string (stream) (princ "<methodResponse><fault><value>" stream) (princ (encode-xml-rpc-fault-value fault-string fault-code) stream) (princ "</value></fault></methodResponse>" stream))) ;;; decoding support (defun decode-xml-rpc-new-element (name attributes seed) (declare (ignore seed name attributes)) '()) (defun decode-xml-rpc-finish-element (name attributes parent-seed seed) (declare (ignore attributes)) (cons (case name ((:|int| :|i4|) (parse-integer seed)) (:|double| (read-from-string seed)) (:|boolean| (= 1 (parse-integer seed))) (:|string| (if (null seed) "" seed)) (:|dateTime.iso8601| (xml-rpc-time (iso8601->universal-time seed))) (:|base64| (if (null seed) (make-array 0 :element-type '(unsigned-byte 8)) (with-input-from-string (in seed) (decode-base64-bytes in)))) (:|array| (car seed)) (:|data| (nreverse seed)) (:|value| (if (stringp seed) seed (car seed))) (:|struct| (make-xml-rpc-struct :alist seed)) (:|member| (cons (cadr seed) (car seed))) (:|name| (intern seed :keyword)) (:|params| (nreverse seed)) (:|param| (car seed)) (:|fault| (make-condition 'xml-rpc-fault :string (get-xml-rpc-struct-member (car seed) :|faultString|) :code (get-xml-rpc-struct-member (car seed) :|faultCode|))) (:|methodName| seed) (:|methodCall| (let ((pair (nreverse seed))) (cons (car pair) (cadr pair)))) (:|methodResponse| (car seed))) parent-seed)) (defun decode-xml-rpc-text (string seed) (declare (ignore seed)) string) (defun decode-xml-rpc (stream) (car (start-parse-xml stream (make-instance 'xml-parser-state :new-element-hook #'decode-xml-rpc-new-element :finish-element-hook #'decode-xml-rpc-finish-element :text-hook #'decode-xml-rpc-text)))) ;;; networking basics (defparameter *xml-rpc-host* "localhost" "String naming the default XML-RPC host to use") (defparameter *xml-rpc-port* 80 "Integer specifying the default XML-RPC port to use") (defparameter *xml-rpc-url* "/RPC2" "String specifying the default XML-RPC URL to use") (defparameter *xml-rpc-agent* (concatenate 'string (lisp-implementation-type) " " (lisp-implementation-version)) "String specifying the default XML-RPC agent to include in server responses") (defvar *xml-rpc-debug* nil "When T the XML-RPC client and server part will be more verbose about their protocol") (defvar *xml-rpc-debug-stream* nil "When not nil it specifies where debugging output should be written to") (defparameter *xml-rpc-proxy-host* nil "When not null, a string naming the XML-RPC proxy host to use") (defparameter *xml-rpc-proxy-port* nil "When not null, an integer specifying the XML-RPC proxy port to use") (defparameter *xml-rpc-package* (find-package :s-xml-rpc-exports) "Package for XML-RPC callable functions") (defparameter *xml-rpc-authorization* nil "When not null, a string to be used as Authorization header") (defun format-debug (&rest args) (when *xml-rpc-debug* (apply #'format args))) (defparameter +crlf+ (make-array 2 :element-type 'character :initial-contents '(#\return #\linefeed))) (defun tokens (string &key (start 0) (separators (list #\space #\return #\linefeed #\tab))) (if (= start (length string)) '() (let ((p (position-if #'(lambda (char) (find char separators)) string :start start))) (if p (if (= p start) (tokens string :start (1+ start) :separators separators) (cons (subseq string start p) (tokens string :start (1+ p) :separators separators))) (list (subseq string start)))))) (defun format-header (stream headers) (mapc #'(lambda (header) (cond ((null (rest header)) (write-string (first header) stream) (princ +crlf+ stream)) ((second header) (apply #'format stream header) (princ +crlf+ stream)))) headers) (princ +crlf+ stream)) (defun debug-stream (in) ;; Uggh, this interacts badly with SLIME, so turning it off for now... - BMM #| (if *xml-rpc-debug* (make-echo-stream in *standard-output*) in)) |# in) ;;; client API (defun xml-rpc-call (encoded &key (url *xml-rpc-url*) (agent *xml-rpc-agent*) (host *xml-rpc-host*) (port *xml-rpc-port*) (authorization *xml-rpc-authorization*) (proxy-host *xml-rpc-proxy-host*) (proxy-port *xml-rpc-proxy-port*)) "Execute an already encoded XML-RPC call and return the decoded result" (let ((uri (if proxy-host (format nil "http://~a:~d~a" host port url) url))) (with-open-socket-stream (connection (if proxy-host proxy-host host) (if proxy-port proxy-port port)) (format-debug (or *xml-rpc-debug-stream* t) "POST ~a HTTP/1.0~%Host: ~a:~d~%" uri host port) (format-header connection `(("POST ~a HTTP/1.0" ,uri) ("User-Agent: ~a" ,agent) ("Host: ~a:~d" ,host ,port) ("Authorization: ~a" ,authorization) ("Content-Type: text/xml") ("Content-Length: ~d" ,(length encoded)))) (princ encoded connection) (finish-output connection) (format-debug (or *xml-rpc-debug-stream* t) "Sending ~a~%~%" encoded) (let ((header (read-line connection nil nil))) (when (null header) (error "no response from server")) (format-debug (or *xml-rpc-debug-stream* t) "~a~%" header) (setf header (tokens header)) (unless (and (>= (length header) 3) (string-equal (second header) "200") (string-equal (third header) "OK")) (error "http-error:~{ ~a~}" header))) (do ((line (read-line connection nil nil) (read-line connection nil nil))) ((or (null line) (= 1 (length line)))) (format-debug (or *xml-rpc-debug-stream* t) "~a~%" line)) (let ((result (decode-xml-rpc (debug-stream connection)))) (if (typep result 'xml-rpc-fault) (error result) (car result)))))) (defun call-xml-rpc-server (server-keywords name &rest args) "Encode and execute an XML-RPC call with name and args, using the list of server-keywords" (apply #'xml-rpc-call (cons (apply #'encode-xml-rpc-call (cons name args)) server-keywords))) (defun describe-server (&key (host *xml-rpc-host*) (port *xml-rpc-port*) (url *xml-rpc-url*)) "Tries to describe a remote server using system.* methods" (dolist (method (xml-rpc-call (encode-xml-rpc-call "system.listMethods") :host host :port port :url url)) (format t "Method ~a ~a~%~a~%~%" method (xml-rpc-call (encode-xml-rpc-call "system.methodSignature" method) :host host :port port :url url) (xml-rpc-call (encode-xml-rpc-call "system.methodHelp" method) :host host :port port :url url)))) ;;; server API (defvar *xml-rpc-call-hook* 'execute-xml-rpc-call "A function to execute the xml-rpc call and return the result, accepting a method-name string and a optional argument list") (defparameter +xml-rpc-method-characters+ "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_.:/") (defun valid-xml-rpc-method-name-p (method-name) (not (find-if-not (lambda (c) (find c +xml-rpc-method-characters+)) method-name))) (defun find-xml-rpc-method (method-name) "Looks for a method with the given name in *xml-rpc-package*, except that colons in the name get converted to hyphens." (let ((sym (find-symbol method-name *xml-rpc-package*))) (if (fboundp sym) sym nil))) (defun execute-xml-rpc-call (method-name &rest arguments) "Execute method METHOD-NAME on ARGUMENTS, or raise an error if no such method exists in *XML-RPC-PACKAGE*" (let ((method (find-xml-rpc-method method-name))) (if method (apply method arguments) ;; http://xmlrpc-epi.sourceforge.net/specs/rfc.fault_codes.php ;; -32601 ---> server error. requested method not found (error 'xml-rpc-fault :code -32601 :string (format nil "Method ~A not found." method-name))))) (defun handle-xml-rpc-call (in id) "Handle an actual call, reading XML from in and returning the XML-encoded result." ;; Try to conform to ;; http://xmlrpc-epi.sourceforge.net/specs/rfc.fault_codes.php (handler-bind ((s-xml:xml-parser-error #'(lambda (c) (format-debug (or *xml-rpc-debug-stream* t) "~a request parsing failed with ~a~%" id c) (return-from handle-xml-rpc-call ;; -32700 ---> parse error. not well formed (encode-xml-rpc-fault (format nil "~a" c) -32700)))) (xml-rpc-fault #'(lambda (c) (format-debug (or *xml-rpc-debug-stream* t) "~a call failed with ~a~%" id c) (return-from handle-xml-rpc-call (encode-xml-rpc-fault (xml-rpc-fault-string c) (xml-rpc-fault-code c))))) (error #'(lambda (c) (format-debug (or *xml-rpc-debug-stream* t) "~a call failed with ~a~%" id c) (return-from handle-xml-rpc-call ;; -32603 ---> server error. internal xml-rpc error (encode-xml-rpc-fault (format nil "~a" c) -32603))))) (let ((call (decode-xml-rpc (debug-stream in)))) (format-debug (or *xml-rpc-debug-stream* t) "~a received call ~s~%" id call) (let ((result (apply *xml-rpc-call-hook* (first call) (rest call)))) (format-debug (or *xml-rpc-debug-stream* t) "~a call result is ~s~%" id result) (encode-xml-rpc-result result))))) (defun xml-rpc-implementation-version () "Identify ourselves" (concatenate 'string "$Id: xml-rpc.lisp,v 1.4 2004/06/17 19:43:11 rschlatte Exp $" " " (lisp-implementation-type) " " (lisp-implementation-version))) (defun xml-rpc-server-connection-handler (connection id agent url) "Handle an incoming connection, doing both all HTTP and XML-RPC stuff" (handler-bind ((error #'(lambda (c) (format-debug (or *xml-rpc-debug-stream* t) "xml-rpc server connection handler failed with ~a~%" c) (error c)))) (let* ((header (read-line connection nil nil)) ;; (header-string header) ) (when (null header) (error "no request from client")) (setf header (tokens header)) (unless (and (>= (length header) 3) (string-equal (first header) "POST") (string-equal (second header) url)) ;; (warn "Header ~a looks malformed, but proceeding - temporary fix BMM" header-string) #|(progn (format-header connection `(("HTTP/1.0 400 Bad Request") ("Server: ~a" ,agent) ("Connection: close"))) (format-debug (or *xml-rpc-debug-stream* t) "~d got a bad request ~a~%" id header))|# ) ;; Originally this was only done if the header looked ok (progn (do ((line (read-line connection nil nil) (read-line connection nil nil))) ((or (null line) (= 1 (length line)))) (format-debug (or *xml-rpc-debug-stream* t) "~d ~a~%" id line)) (let ((xml (handle-xml-rpc-call connection id))) (format-header connection `(("HTTP/1.0 200 OK") ("Server: ~a" ,agent) ("Connection: close") ("Content-Type: text/xml") ("Content-Length: ~d" ,(length xml)))) (princ xml connection) (format-debug (or *xml-rpc-debug-stream* t) "~d sending ~a~%" id xml)))) (force-output connection) (close connection))) (defparameter *counter* 0 "Unique ID for incoming connections") (defun start-xml-rpc-server (&key (port *xml-rpc-port*) (url *xml-rpc-url*) (agent *xml-rpc-agent*)) "Start an XML-RPC server in a separate process" (start-standard-server :name (format nil "xml-rpc server ~a:~d" url port) :port port :connection-handler #'(lambda (client-stream) (let ((id (incf *counter*))) (format-debug (or *xml-rpc-debug-stream* t) "spawned connection handler ~d~%" id) (run-process (format nil "xml-rpc-server-connection-handler-~d" id) #'xml-rpc-server-connection-handler client-stream id agent url))))) ;;;; eof
0
apollo_public_repos/apollo-platform/ros/roslisp/s-xml-rpc
apollo_public_repos/apollo-platform/ros/roslisp/s-xml-rpc/src/define-xmlrpc-method.lisp
;;;; -*- mode: lisp -*- ;;;; ;;;; $Id: define-xmlrpc-method.lisp,v 1.1 2004/07/08 19:45:25 scaekenberghe Exp $ ;;;; ;;;; The code in this file adds a very handly define-xmlrpc-method macro. ;;;; ;;;; (define-xmlrpc-method get-state-name (state) ;;;; :url #u"http://betty.userland.com/RPC2" ;;;; :method "examples.getStateName") ;;;; ;;;; (define-xmlrpc-method get-time () ;;;; :url #u"http://time.xmlrpc.com/RPC2" ;;;; :method "currentTime.getCurrentTime") ;;;; ;;;; It require the PURI package. ;;;; ;;;; Copyright (C) 2004 Frederic Brunel. ;;;; ;;;; You are granted the rights to distribute and use this software ;;;; as governed by the terms of the Lisp Lesser GNU Public License ;;;; (http://opensource.franz.com/preamble.html), also known as the LLGPL. (defmacro define-xmlrpc-method (name args &key url method) `(defun ,name ,args (xml-rpc-call (encode-xml-rpc-call ,method ,@args) :url ,(puri:uri-path url) :host ,(puri:uri-host url) :port ,(cond ((puri:uri-port url)) (t 80))))) ;;;; eof
0
apollo_public_repos/apollo-platform/ros/roslisp/s-xml-rpc
apollo_public_repos/apollo-platform/ros/roslisp/s-xml-rpc/src/validator1-client.lisp
;;;; -*- mode: lisp -*- ;;;; ;;;; $Id: validator1-client.lisp,v 1.1 2004/06/14 20:11:55 scaekenberghe Exp $ ;;;; ;;;; This is a Common Lisp implementation of the XML-RPC 'validator1' ;;;; server test suite, as live testable from the website ;;;; http://validator.xmlrpc.com and documented on the web page ;;;; http://www.xmlrpc.com/validator1Docs ;;;; ;;;; Copyright (C) 2002, 2004 Sven Van Caekenberghe, Beta Nine BVBA. ;;;; ;;;; You are granted the rights to distribute and use this software ;;;; as governed by the terms of the Lisp Lesser General Public License ;;;; (http://opensource.franz.com/preamble.html), also known as the LLGPL. (in-package :s-xml-rpc) (defun random-string (&optional (length 8)) (with-output-to-string (stream) (dotimes (i (random length)) (write-char (code-char (+ 32 (random 95))) stream)))) (defun echo-struct-test () (let* ((struct (xml-rpc-struct :|foo| (random 1000000) :|bar| (random-string) :|fooBar| (list (random 100) (random 100)))) (result (xml-rpc-call (encode-xml-rpc-call :|validator1.echoStructTest| struct)))) (format t "validator1.echoStructTest(~s)=~s~%" struct result) (assert (xml-rpc-struct-equal struct result)))) (defun easy-struct-test () (let* ((moe (random 1000)) (larry (random 1000)) (curry (random 1000)) (struct (xml-rpc-struct :|moe| moe :|larry| larry :|curly| curry)) (result (xml-rpc-call (encode-xml-rpc-call :|validator1.easyStructTest| struct)))) (format t "validator1.easyStructTest(~s)=~s~%" struct result) (assert (= (+ moe larry curry) result)))) (defun count-the-entities () (let* ((string (random-string 512)) (left-angle-brackets (count #\< string)) (right-angle-brackets (count #\> string)) (apostrophes (count #\' string)) (quotes (count #\" string)) (ampersands (count #\& string)) (result (xml-rpc-call (encode-xml-rpc-call :|validator1.countTheEntities| string)))) (format t "validator1.countTheEntitities(~s)=~s~%" string result) (assert (and (xml-rpc-struct-p result) (= left-angle-brackets (get-xml-rpc-struct-member result :|ctLeftAngleBrackets|)) (= right-angle-brackets (get-xml-rpc-struct-member result :|ctRightAngleBrackets|)) (= apostrophes (get-xml-rpc-struct-member result :|ctApostrophes|)) (= quotes (get-xml-rpc-struct-member result :|ctQuotes|)) (= ampersands (get-xml-rpc-struct-member result :|ctAmpersands|)))))) (defun array-of-structs-test () (let ((array (make-array (random 32))) (sum 0)) (dotimes (i (length array)) (setf (aref array i) (xml-rpc-struct :|moe| (random 1000) :|larry| (random 1000) :|curly| (random 1000))) (incf sum (get-xml-rpc-struct-member (aref array i) :|curly|))) (let ((result (xml-rpc-call (encode-xml-rpc-call :|validator1.arrayOfStructsTest| array)))) (format t "validator1.arrayOfStructsTest(~s)=~s~%" array result) (assert (= result sum))))) (defun random-bytes (&optional (length 16)) (let ((bytes (make-array (random length) :element-type '(unsigned-byte 8)))) (dotimes (i (length bytes) bytes) (setf (aref bytes i) (random 256))))) (defun many-types-test () (let* ((integer (random 10000)) (boolean (if (zerop (random 2)) t nil)) (string (random-string)) (double (random 10000.0)) (dateTime (xml-rpc-time)) (base64 (random-bytes)) (result (xml-rpc-call (encode-xml-rpc-call :|validator1.manyTypesTest| integer boolean string double dateTime base64)))) (format t "validator1.manyTypesTest(~s,~s,~s,~s,~s,~s)=~s~%" integer boolean string double dateTime base64 result) (assert (equal integer (elt result 0))) (assert (equal boolean (elt result 1))) (assert (equal string (elt result 2))) (assert (equal double (elt result 3))) (assert (equal (xml-rpc-time-universal-time dateTime) (xml-rpc-time-universal-time (elt result 4)))) (assert (reduce #'(lambda (x y) (and x y)) (map 'list #'= base64 (elt result 5)) :initial-value t)))) (defun simple-struct-return-test () (let* ((number (random 1000)) (result (xml-rpc-call (encode-xml-rpc-call :|validator1.simpleStructReturnTest| number)))) (format t "validator1.simpleStructReturnTest(~s)=~s~%" number result) (assert (and (= (* number 10) (get-xml-rpc-struct-member result :|times10|)) (= (* number 100) (get-xml-rpc-struct-member result :|times100|)) (= (* number 1000) (get-xml-rpc-struct-member result :|times1000|)))))) (defun moderate-size-array-check () (let ((array (make-array (+ 100 (random 100)) :element-type 'string))) (dotimes (i (length array)) (setf (aref array i) (random-string))) (let ((result (xml-rpc-call (encode-xml-rpc-call :|validator1.moderateSizeArrayCheck| array)))) (format t "validator1.moderateSizeArrayCheck(~s)=~s~%" array result) (assert (equal (concatenate 'string (elt array 0) (elt array (1- (length array)))) result))))) (defun nested-struct-test () (let* ((moe (random 1000)) (larry (random 1000)) (curry (random 1000)) (struct (xml-rpc-struct :|moe| moe :|larry| larry :|curly| curry)) (first (xml-rpc-struct :\01 struct)) (april (xml-rpc-struct :\04 first)) (year (xml-rpc-struct :\2000 april)) (result (xml-rpc-call (encode-xml-rpc-call :|validator1.nestedStructTest| year)))) (format t "validator1.nestedStructTest(~s)=~s~%" year result) (assert (= (+ moe larry curry) result)))) (defun test-run (&optional (runs 1)) (dotimes (i runs t) (echo-struct-test) (easy-struct-test) (count-the-entities) (array-of-structs-test) (many-types-test) (simple-struct-return-test) (moderate-size-array-check) (nested-struct-test))) (defun timed-test-run (&optional (runs 1)) (dotimes (i runs t) (time (echo-struct-test)) (time (easy-struct-test)) (time (count-the-entities)) (time (array-of-structs-test)) (time (many-types-test)) (time (simple-struct-return-test)) (time (moderate-size-array-check)) (time (nested-struct-test)))) ;;;; eof
0
apollo_public_repos/apollo-platform/ros/roslisp/s-xml-rpc
apollo_public_repos/apollo-platform/ros/roslisp/s-xml-rpc/src/sysdeps.lisp
;;;; -*- mode: lisp -*- ;;;; ;;;; $Id: sysdeps.lisp,v 1.1.1.1 2004/06/09 09:02:39 scaekenberghe Exp $ ;;;; ;;;; These are the system dependent part of S-XML-RPC. ;;;; Ports to OpenMCL, LispWorks and SBCL are provided. ;;;; Porting to another CL requires implementating these definitions. ;;;; ;;;; Copyright (C) 2002, 2004 Sven Van Caekenberghe, Beta Nine BVBA. ;;;; SBCL port Copyright (C) 2004, Brian Mastenbrook & Rudi Schlatte. ;;;; ;;;; You are granted the rights to distribute and use this software ;;;; as governed by the terms of the Lisp Lesser General Public License ;;;; (http://opensource.franz.com/preamble.html), also known as the LLGPL. (in-package :s-xml-rpc) (defmacro with-open-socket-stream ((var host port) &body body) "Execute body with a bidirectional socket stream opened to host:port" #+openmcl `(ccl:with-open-socket (,var :remote-host ,host :remote-port ,port) ,@body) #+lispworks `(with-open-stream (,var (comm:open-tcp-stream ,host ,port)) ,@body) #+sbcl (let ((socket-object (gensym))) `(let ((,socket-object (make-instance 'sb-bsd-sockets:inet-socket :type :stream :protocol :tcp))) (sb-bsd-sockets:socket-connect ,socket-object (car (sb-bsd-sockets:host-ent-addresses (sb-bsd-sockets:get-host-by-name ,host))) ,port) (let ((,var (sb-bsd-sockets:socket-make-stream ,socket-object :element-type 'character :input t :output t :buffering :none))) (unwind-protect (progn ,@body) (close ,var)))))) (defun run-process (name function &rest arguments) "Create and run a new process with name, executing function on arguments" #+lispworks (apply #'mp:process-run-function name '(:priority 3) function arguments) #+openmcl (apply #'ccl:process-run-function name function arguments) #+sbcl (declare (ignore name)) #+sbcl (apply function arguments)) (defvar *server-processes* nil) (defun start-standard-server (&key port name connection-handler) "Start a server process with name, listening on port, delegating to connection-handler with stream as argument" #+lispworks (progn (comm:start-up-server :function #'(lambda (socket-handle) (let ((client-stream (make-instance 'comm:socket-stream :socket socket-handle :direction :io :element-type 'base-char))) (funcall connection-handler client-stream))) :service port :announce t :error t :wait t :process-name name) name) #+openmcl (progn (ccl:process-run-function name #'(lambda () (let ((server-socket (ccl:make-socket :connect :passive :local-port port :reuse-address t))) (unwind-protect (loop (let ((client-stream (ccl:accept-connection server-socket))) (funcall connection-handler client-stream))) (close server-socket))))) name) #+sbcl (let* ((socket (make-instance 'sb-bsd-sockets:inet-socket :type :stream :protocol :tcp)) (handler-fn (lambda (fd) (declare (ignore fd)) (let ((stream (sb-bsd-sockets:socket-make-stream (sb-bsd-sockets:socket-accept socket) :element-type 'character :input t :output t :buffering :none))) (funcall connection-handler stream))))) (setf (sb-bsd-sockets:sockopt-reuse-address socket) t) (sb-bsd-sockets:socket-bind socket #(0 0 0 0) port) (sb-bsd-sockets:socket-listen socket 15) (push (list name socket (sb-sys:add-fd-handler (sb-bsd-sockets:socket-file-descriptor socket) :input handler-fn)) *server-processes*) (values name socket))) (defun stop-server (name) "Kill a server process by name (as started by start-standard-server)" #+lispworks (let ((server-process (mp:find-process-from-name name))) (when server-process (mp:process-kill server-process))) #+openmcl (let ((server-process (find name (ccl:all-processes) :key #'ccl:process-name :test #'string-equal))) (when server-process (ccl:process-kill server-process))) #+sbcl (progn (destructuring-bind (name socket handler) (assoc name *server-processes* :test #'string=) (declare (ignore name)) (sb-sys:remove-fd-handler handler) (sb-bsd-sockets:socket-close socket)) (setf *server-processes* (delete name *server-processes* :key #'car :test #'string=))) name) ;;;; eof
0
apollo_public_repos/apollo-platform/ros/roslisp
apollo_public_repos/apollo-platform/ros/roslisp/src/namespace.lisp
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Software License Agreement (BSD License) ;; ;; Copyright (c) 2008, Willow Garage, Inc. ;; All rights reserved. ;; ;; Redistribution and use in source and binary forms, with ;; or without modification, are permitted provided that the ;; following conditions are met: ;; ;; * Redistributions of source code must retain the above ;; copyright notice, this list of conditions and the ;; following disclaimer. ;; * Redistributions in binary form must reproduce the ;; above copyright notice, this list of conditions and ;; the following disclaimer in the documentation and/or ;; other materials provided with the distribution. ;; * Neither the name of Willow Garage, Inc. nor the names ;; of its contributors may be used to endorse or promote ;; products derived from this software without specific ;; prior written permission. ;; ;; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND ;; CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED ;; WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED ;; WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A ;; PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE ;; COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, ;; INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR ;; CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, ;; PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ;; DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ;; CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN ;; CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE ;; OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS ;; SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH ;; DAMAGE. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (in-package :roslisp) (defun concatenate-ros-names (names) "Takes a list of strings and returns a single string with the names delimited by /'s" (declare (cons names)) (format nil "~a~{/~a~}" (first names) (rest names))) (defun fully-qualified-name (name) "Do the translation from a client-code-specified name to a fully qualified one. Handles already-fully-qualified names, tilde for private namespace, unqualified names, and remapped names." (let ((global-name (compute-global-name *namespace* *ros-node-name* name))) (if *remapped-names* (gethash global-name *remapped-names* global-name) global-name ))) (defun compute-global-name (ns node-global-name name) (case (char name 0) (#\/ name) (#\~ (concatenate 'string node-global-name "/" (subseq name 1))) (otherwise (concatenate 'string ns name)))) (defmacro with-fully-qualified-name (n &body body) (assert (symbolp n)) `(let ((,n (fully-qualified-name ,n))) ,@body))
0
apollo_public_repos/apollo-platform/ros/roslisp
apollo_public_repos/apollo-platform/ros/roslisp/src/msg.lisp
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Software License Agreement (BSD License) ;; ;; Copyright (c) 2008, Willow Garage, Inc. ;; All rights reserved. ;; ;; Redistribution and use in source and binary forms, with ;; or without modification, are permitted provided that the ;; following conditions are met: ;; ;; * Redistributions of source code must retain the above ;; copyright notice, this list of conditions and the ;; following disclaimer. ;; * Redistributions in binary form must reproduce the ;; above copyright notice, this list of conditions and ;; the following disclaimer in the documentation and/or ;; other materials provided with the distribution. ;; * Neither the name of Willow Garage, Inc. nor the names ;; of its contributors may be used to endorse or promote ;; products derived from this software without specific ;; prior written permission. ;; ;; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND ;; CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED ;; WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED ;; WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A ;; PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE ;; COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, ;; INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR ;; CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, ;; PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ;; DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ;; CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN ;; CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE ;; OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS ;; SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH ;; DAMAGE. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (in-package roslisp) (eval-when (:compile-toplevel :load-toplevel :execute) (require 'sb-cltl2)) (defmethod deserialize ((msg symbol) str) (let ((m (make-instance msg))) (deserialize m str) m)) (defmethod md5sum ((msg-type array)) (if (stringp msg-type) (md5sum (get-topic-class-name msg-type)) (progn (warn "Hmmm... unexpected topic type specifier ~a in md5sum. Passing it on anyway..." msg-type) (call-next-method)))) (defmethod ros-datatype ((msg-type array)) (if (stringp msg-type) (ros-datatype (get-topic-class-name msg-type)) (progn (warn "Hmm... unexpected topic type specifier ~a in ros-datatype. Passing it on anyway..." msg-type) (call-next-method)))) (defmethod message-definition ((msg-type array)) (if (stringp msg-type) (message-definition (get-topic-class-name msg-type)) (progn (warn "Hmm... unexpected topic type specifier ~a in message-definition. Passing it on anyway..." msg-type) (call-next-method)))) (defun make-response (service-type &rest args) (apply #'make-instance (service-response-type service-type) args)) (defmethod symbol-codes ((msg-type symbol)) nil) (defmethod symbol-codes ((m ros-message)) (symbol-codes (type-of m))) (defmethod symbol-code ((m ros-message) s) (symbol-code (type-of m) s)) (defmethod code-symbols ((msg-type symbol) code) (remove code (symbol-codes msg-type) :test-not #'= :key #'rest)) (defmethod code-symbols ((m ros-message) code) (code-symbols (type-of m) code)) (defmethod code-symbol ((msg-type symbol) code) (let ((pair (rassoc code (symbol-codes msg-type) :test #'=))) (unless pair (error "Could not get code symbol for ~a in ROS message type ~a" code msg-type)) (car pair))) (defmethod code-symbol ((m ros-message) code) (code-symbol (type-of m) code)) (defmethod symbol-code ((m symbol) s) (let ((pair (assoc s (symbol-codes m)))) (unless pair (error "Could not get symbol code for ~a for ROS message type ~a" s m)) (cdr pair))) (defmethod ros-message-to-list (msg) (check-type msg (not ros-message) "something that is not a ros-message") msg) (defmethod list-to-ros-message ((l null)) ;; Tricky case: nil should be treated as false (i.e. a primitive boolean) rather than the empty list ;; (since a ros message always has at least one element: the message type) nil) (defmethod list-to-ros-message ((l list)) (apply #'make-instance (first l) (mapcan #'(lambda (pair) (list (car pair) (list-to-ros-message (cdr pair)))) (rest l)))) ;; Either a primitive type or vector or already a ros message (should do a bit more type checking) (defmethod list-to-ros-message (msg) msg) (defun convert-to-keyword (s) (declare (symbol s)) (let ((name (string-upcase (symbol-name s)))) (when (> (length name) 4) (let ((pos (- (length name) 4))) (when (search "-VAL" name :start2 pos) (let ((new-name (subseq name 0 pos))) (signal 'compile-warning :msg (format nil "I'm assuming you're using ~a to refer to ~a (the old form), in a call to with-fields or def-service-callback. For now, converting automatically. This usage is deprecated though; switch to just using ~a (cf roslisp_examples/add-two-ints-server.lisp)." name new-name new-name)) (setq s (intern new-name 'keyword))))))) (if (keywordp s) s (intern (symbol-name s) 'keyword))) (defun extract-nested-field (m f) "extract a named field from a message. F can also be a list. E.g, if F is '(:bar :foo) that means extract field foo of field bar of the message. Calls list-to-ros-message before returning." (let ((l (ros-message-to-list m))) (list-to-ros-message (cond ((symbolp f) (get-field l f)) ((null (rest f)) (get-field l (first f))) (t (extract-nested-field (get-field l (first f)) (rest f))))))) (defun get-field (l f) (declare (list l) (symbol f)) (let ((pair (assoc f (rest l)))) (unless pair (error "Could not find field ~a in ~a" f l)) (cdr pair))) (defun set-field (l f v) (declare (list l) (symbol f)) (let ((pair (assoc f (rest l)))) (unless pair (error "Could not find field ~a in ~a" f l)) (setf (cdr pair) v))) (defun msg-slot-symbol (msg slot &optional (pkg (symbol-package (type-of msg)))) "Returns the correct symbol for `slot' that can be used to call SLOT-VALUE on `msg'. `slot' is either a string or a symbol. The return value is a symbol in `msg's package" (declare (type (or string symbol) slot)) (let ((symbol-name (etypecase slot (string (string-upcase slot)) (symbol (symbol-name slot))))) (intern symbol-name pkg))) (defun msg-slot-value (msg slot) "Like slot-value but this function ignores the package of `slot' and infers it by using the package of `msg'" (slot-value msg (msg-slot-symbol msg slot))) (define-compiler-macro msg-slot-value (&whole expr msg slot &environment env) (let ((msg-type (when (symbolp msg) (cdr (assoc 'type (nth-value 2 (sb-cltl2:variable-information msg env))))))) (if (and msg-type (subtypep msg-type 'roslisp-msg-protocol:ros-message)) (let* ((slot-symbol (msg-slot-symbol nil slot (symbol-package msg-type))) (slot-type (msg-slot-type msg-type slot-symbol))) `(the ,slot-type (slot-value ,msg ',slot-symbol))) expr))) (defun msg-slot-type (class-name slot) (let ((class (find-class class-name))) (unless (sb-mop:class-finalized-p class) (sb-mop:finalize-inheritance class)) (let* ((slot-symbol (msg-slot-symbol nil slot (symbol-package class-name))) (slot-definition (find slot-symbol (sb-mop:class-slots class) :key #'sb-mop:slot-definition-name))) (when slot-definition (sb-mop:slot-definition-type slot-definition))))) (defun make-field-reader-with-type (value-sym type field-definition) (if (and type field-definition (subtypep type 'roslisp-msg-protocol:ros-message)) (make-field-reader-with-type `(slot-value ,value-sym ',(msg-slot-symbol nil (car field-definition) (symbol-package type))) (msg-slot-type type (car field-definition)) (cdr field-definition)) value-sym)) (defun make-field-reader (value-sym field-definition) (if field-definition (make-field-reader `(msg-slot-value ,value-sym ',(car field-definition)) (cdr field-definition)) value-sym)) (defun field-reader-type (msg-type field-definition) (when msg-type (if (cdr field-definition) (field-reader-type (msg-slot-type msg-type (car field-definition)) (cdr field-definition)) (msg-slot-type msg-type (car field-definition))))) (defun make-field-definitions (defs msg-sym &optional msg-type) (flet ((make-def (name def) `(,name ,(if msg-type (make-field-reader-with-type msg-sym msg-type def) (make-field-reader msg-sym def))))) (mapcar-with-field-definition #'make-def defs))) (defun mapcar-with-field-definition (function defs) (flet ((ensure-list (x) (if (listp x) x (list x)))) (mapcar (lambda (def) (multiple-value-bind (name def) (if (listp def) (values (first def) (reverse (ensure-list (second def)))) (values def (ensure-list def))) (funcall function name def))) defs))) (defmacro with-fields (bindings msg &body body &environment env) "with-fields BINDINGS MSG &rest BODY A macro for convenient access to message fields. BINDINGS is an unevaluated list of bindings. Each binding is like a let binding (FOO BAR), where FOO is a symbol naming a variable that will be bound to the field value. BAR describes the field. In the simplest case it's just a symbol naming the field. It can also be a list, e.g. (QUX GAR). This means the field QUX of the field GAR of the message. Finally, the entire binding can be a symbol FOO, which is a shorthand for (FOO FOO). MSG evaluates to a message. BODY is the body, surrounded by an implicit progn. As an example, instead of (let ((foo (pkg:foo-val (pkg:bar-val m))) (baz (pkg:baz-val m))) (stuff)) you can use (with-fields ((foo (foo bar)) baz) (stuff)) Efficiency: since the message type of ``m'' may not be known at macroexpansion time, with-fields converts the message to a list at runtime. If, however, the message type is declared, with-fields makes use of the declaration to directly expand to the slot readers. If the message type is not declared, the macro expands to calls to MSG-SLOT-VALUE which needs to infer the correct package at runtime which causes more consing and is less performant." (let ((msg-type (when (symbolp msg) (let ((type (cdr (assoc 'type (nth-value 2 (sb-cltl2:variable-information msg env)))))) (when (symbolp type) type)))) (msg-sym (gensym "MSG"))) (declare (type (or symbol nil) msg-type)) `(let ((,msg-sym ,msg)) (declare (ignorable ,msg-sym)) (let ,(make-field-definitions bindings msg-sym (when (and msg-type (subtypep msg-type 'roslisp-msg-protocol:ros-message)) msg-type)) ,@(when msg-type (mapcar-with-field-definition (lambda (name def) (let ((inferred-msg-type (field-reader-type msg-type def))) (when inferred-msg-type `(declare (type ,inferred-msg-type ,name))))) bindings)) ,@body)))) (defun read-ros-message (stream) (list-to-ros-message (read stream))) (defun field-pair (f l) (let ((p (assoc (intern (symbol-name (car f)) :keyword) (cdr l)))) (assert p nil "Couldn't find field ~a in ~a (overall field spec was ~a)" (car f) (cdr l) f) (if (cdr f) (field-pair (cdr f) (cdr p)) p))) (defun listify-message (m nested-field) (if nested-field (dbind (f . r) nested-field (let ((m2 (ros-message-to-list m))) (set-field m2 f (listify-message (get-field m2 f) r)) m2)) m)) (defun ros-message-to-list-nested (m fields) "Return a copy of M which is sufficiently listified that all the specified fields can be accessed through lists" (dolist (f fields m) (setq m (listify-message m f)))) ;; Basic helper function that takes in a message and returns a new message with some fields updated (see below) (defun set-fields-fn (m &rest args) (let (fields vals) (while args (push (reverse (designated-list (pop args))) fields) (push (pop args) vals)) (let ((l (ros-message-to-list-nested m fields))) (loop for field in fields for val in vals do (setf (cdr (field-pair field l)) val)) (list-to-ros-message l)))) (defun make-message-fn (msg-type &rest args) "Creates a message of ros type MSG-TYPE (a string PKG/MSG), where the odd ARGS are lists of keywords that designated a nested field and the even arguments are the values. E.g., where an odd argument '(:foo :bar) means the foo field of the bar field of the corresponding even argument." (destructuring-bind (pkg-name type) (tokens (string-upcase msg-type) :separators '(#\/)) (let ((pkg (find-package (intern (concatenate 'string pkg-name "-MSG") 'keyword)))) (assert pkg nil "Can't find package ~a-MSG" pkg-name) (let ((class-name (find-symbol type pkg))) (assert class-name nil "Can't find class for ~a" msg-type) (apply #'set-fields-fn (make-instance class-name) args))))) (defun make-service-request-fn (srv-type &rest args) (destructuring-bind (pkg type) (tokens (string-upcase srv-type) :separators '(#\/)) (let ((pkg (find-package (intern (concatenate 'string pkg "-SRV") 'keyword)))) (assert pkg nil "Can't find package ~a" pkg) (let ((class-name (find-symbol (concatenate 'string type "-REQUEST") pkg))) (assert class-name nil "Can't find class ~a in package ~a" class-name pkg) (apply #'set-fields-fn (make-instance class-name) args))))) (defmacro make-request (srv-type &rest args) "make-request SRV-TYPE &rest ARGS Like make-message, but creates a service request object. SRV-TYPE can be either a string of the form package_name/message_name, or a symbol naming the service (the name is the base name of the .srv file). ARGS are as in make-message." (etypecase srv-type (string `(make-service-request-fn ,srv-type ,@(loop for i from 0 for arg in args collect (if (evenp i) `',arg arg)))) (symbol `(make-service-request ',srv-type ,@args)) (cons (assert (eql (car srv-type) 'quote)) `(make-service-request ,srv-type ,@args)))) (defun make-service-request (service-type &rest args) (apply #'make-instance (service-request-type service-type) args)) (defmacro modify-message-copy (m &rest args) "modify-message-copy MSG &rest ARGS Return a new message that is a copy of MSG with some fields modified. ARGS is a list of the form FIELD-SPEC1 VAL1 ... FIELD-SPEC_k VAL_k as in make-message." `(set-fields-fn ,m ,@(loop for i from 0 for arg in args collect (if (evenp i) `',(mapcar #'convert-to-keyword (designated-list arg)) arg)))) (defmacro setf-msg (place &rest args) "Sets PLACE to be the result of calling modify-message-copy on PLACE and ARGS" (let ((m (gensym))) `(let ((,m ,place)) (setf ,place (modify-message-copy ,m ,@args))))) (defun pairs (l) (when l (assert (rest l)) (cons (list (first l) (second l)) (pairs (nthcdr 2 l))))) (defmacro make-message (msg-type &rest args) "make-message MSG-TYPE &rest ARGS Convenience macro for creating messages easily. MSG-TYPE is a string naming a message ros datatype, i.e.., of form package_name/message_name ARGS is a list of form FIELD-SPEC1 VAL1 ... FIELD-SPECk VALk Each FIELD-SPEC (unevaluated) is a list (or a symbol, which designates a list of one element) that refers to a possibly nested field. VAL is the corresponding value. For example, if MSG-TYPE is the string robot_msgs/Pose, and ARGS are (x position) 42 (w orientation) 1 this will create a Pose with the x field of position equal to 42 and the w field of orientation equal to 1 (other fields equal their default values). For convenience, the field specifiers don't have to actually belong to the message package. E.g., they can be keywords. " `(make-message-fn ,msg-type ,@(loop for i from 0 for arg in args collect (if (evenp i) `',(mapcar #'convert-to-keyword (designated-list arg)) arg)))) (defmacro make-msg (&rest args) "Alias for make-message" `(make-message ,@args))
0
apollo_public_repos/apollo-platform/ros/roslisp
apollo_public_repos/apollo-platform/ros/roslisp/src/roslisp.lisp
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Software License Agreement (BSD License) ;; ;; Copyright (c) 2008, Willow Garage, Inc. ;; All rights reserved. ;; ;; Redistribution and use in source and binary forms, with ;; or without modification, are permitted provided that the ;; following conditions are met: ;; ;; * Redistributions of source code must retain the above ;; copyright notice, this list of conditions and the ;; following disclaimer. ;; * Redistributions in binary form must reproduce the ;; above copyright notice, this list of conditions and ;; the following disclaimer in the documentation and/or ;; other materials provided with the distribution. ;; * Neither the name of Willow Garage, Inc. nor the names ;; of its contributors may be used to endorse or promote ;; products derived from this software without specific ;; prior written permission. ;; ;; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND ;; CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED ;; WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED ;; WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A ;; PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE ;; COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, ;; INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR ;; CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, ;; PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ;; DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ;; CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN ;; CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE ;; OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS ;; SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH ;; DAMAGE. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defpackage :roslisp (:use :cl :sb-bsd-sockets :sb-sys :sb-thread :s-xml-rpc :roslisp-extended-reals :roslisp-queue :roslisp-utils :roslisp-msg-protocol :ros-load-manifest :std_srvs-srv ) (:export :msg-slot-value :with-fields :make-message :make-msg :modify-message-copy :setf-msg :ros-message :node-status :make-response :make-request :symbol-code :symbol-codes :code-symbols :code-symbol :load-if-necessary :*current-ros-package* :start-ros-node :shutdown-ros-node :with-ros-node :def-ros-node :print-status :make-response :defservice :advertise :unadvertise :subscribe :unsubscribe :register-service :register-service-fn :service-error :service-call-error :def-service-callback :call-service :wait-for-service :def-service-call :make-service-client :publish :publish-msg :make-publisher-msg :loop-at-most-every :spin-until :wait-duration :with-parallel-thread :store-message-in :load-message-types :load-service-types :get-param :set-param :has-param :delete-param :list-params :ros-time :ros-time-not-yet-received :spin-until-ros-time-valid :pprint-ros-message :read-ros-message :set-debug-level :set-debug-levels :print-debug-levels :debug-level :ros-debug :ros-warn :ros-info :ros-error :ros-fatal ;; debug topics :roslisp :top :tcp :load-msg ;; todo remove? :load-srv ;; todo remove? :*ros-node-name* :num-subscribers :fully-qualified-name :make-uri :*default-master-uri* :*master-uri* :standalone-exec-debug-hook :*running-from-command-line* :persistent-service :call-persistent-service :reconnect :close-persistent-service :persistent-service-ok)) (in-package :roslisp) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; ROS Node state ;; Stored in special variables since node is a singleton ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defvar *ros-node-name* nil "String holding node global name") (defvar *node-status* :shutdown) (defvar *event-loop-thread* nil "Handle to thread for killing") (defvar *master-uri* nil "URI of ROS master") (defvar *default-master-uri* nil "Default master URI. Is nil (intended for convenience during interactive use).") (defvar *xml-server* nil "String holding name of XML-RPC server (needed by s-xml-rpc") (defvar *xml-rpc-caller-api* nil "Holds the caller-api argument to XML RPC calls to the master.") (defvar *tcp-server* nil "Passive socket that topic-subscribers will connect to") (defvar *tcp-server-hostname* nil "Address of tcp server") (defvar *tcp-server-port* nil "Port of tcp server") (defvar *service-uri* nil "uri for service calls to this node") (defvar *publications* nil "Hashtable from topic name to list of subscriber-connections") (defvar *subscriptions* nil "Hashtable from topic name to object of type subscription") (defvar *services* nil "Hashtable from service name to object of type service") (defvar *ros-lock* (make-mutex :name "API-wide lock for all operations that affect/are affected by state of node")) (defvar *debug-stream-lock* (make-mutex :name "API-wide lock for the debugging output stream.")) (defvar *running-from-command-line* nil "True iff running ROS node script from command line (noninteractively)") (defvar *broken-socket-streams* nil "Used by TCPROS to keep track of sockets that have died and shouldn't be written to any more.") (defvar *namespace* "/" "Dynamic variable that holds the current namespace. Bound when node starts, and by in-namespace") (defvar *ros-log-location* nil "Name of file to which ros lisp debugging info is written") (defvar *ros-log-stream* nil "Output stream bound to log file during node execution") (defvar *remapped-names* nil "Hash from strings to strings containing names that have been remapped on the command line") (defvar *debug-stream* t "Stream to which to print debug messages. Defaults to standard out.") (defvar *break-on-socket-errors* nil "If true, then any error on a socket will cause a (continuable) break") (defvar *debug-level* 2 "Controls the behavior of ros-debug and others. The default value of 2 means print info and above. 1 would be everything. 4 would be warnings and above, etc.") (defvar *last-clock* nil) (defvar *use-sim-time* nil) (defvar *deserialization-threads* nil "List of threads that deserialize messages from sockets into topic queues. These have to be terminated explicitly when we shutdown (because they may be stuck in a blocking read).") ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Type defs ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; TODO is this all that goes in a URI - Should the protocol name be included? ;: Note other code assumes URI's can be tested for equality using #'equalp (defstruct (uri (:constructor create-uri)) address port) (defun make-uri (address port) (create-uri :address address :port port)) (defstruct (subscription (:conc-name nil)) sub-topic-type buffer topic-thread (callbacks nil) publisher-connections) (defstruct subscriber topic subscription callback) (defstruct (publisher-connection (:conc-name nil)) publisher-socket publisher-stream uri) (defstruct (publication (:conc-name nil)) pub-topic-type subscriber-connections is-latching last-message) (defstruct (subscriber-connection (:conc-name nil)) subscriber-socket subscriber-stream subscriber-uri) (defstruct service md5 name ros-type request-ros-type response-ros-type request-class callback) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Querying the node ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun node-status () *node-status*) (defun num-subscribers (pub) (length (subscriber-connections pub))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Debugging ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun print-status () (format t "~&Node ~a~2I~&status: ~a~&Master URI: ~a~&Publications ~/roslisp-utils:pprint-hash/~&Subscriptions ~/roslisp-utils:pprint-hash/" *ros-node-name* *node-status* *master-uri* *publications* *subscriptions*)) (define-condition compile-warning (condition) ((msg :initarg :msg)))
0
apollo_public_repos/apollo-platform/ros/roslisp
apollo_public_repos/apollo-platform/ros/roslisp/src/time.lisp
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Software License Agreement (BSD License) ;; ;; Copyright (c) 2008, Willow Garage, Inc. ;; All rights reserved. ;; ;; Redistribution and use in source and binary forms, with ;; or without modification, are permitted provided that the ;; following conditions are met: ;; ;; * Redistributions of source code must retain the above ;; copyright notice, this list of conditions and the ;; following disclaimer. ;; * Redistributions in binary form must reproduce the ;; above copyright notice, this list of conditions and ;; the following disclaimer in the documentation and/or ;; other materials provided with the distribution. ;; * Neither the name of Willow Garage, Inc. nor the names ;; of its contributors may be used to endorse or promote ;; products derived from this software without specific ;; prior written permission. ;; ;; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND ;; CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED ;; WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED ;; WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A ;; PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE ;; COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, ;; INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR ;; CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, ;; PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ;; DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ;; CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN ;; CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE ;; OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS ;; SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH ;; DAMAGE. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (in-package :roslisp) (defun ros-time () "If *use-sim-time* is true (which is set upon node startup by looking up the ROS /use_sim_time parameter), return the last received time on the /time or /clock topics, or 0.0 if no time message received yet. Otherwise, return the unix time (seconds since epoch with microsecond precision)." #+sbcl (if *use-sim-time* (if *last-clock* (rosgraph_msgs-msg:clock *last-clock*) (progn (unless (mutex-owner *debug-stream-lock*) (ros-debug (roslisp time) "Returning time of 0.0 as use_sim_time was true and no clock messages received")) 0.0)) (multiple-value-bind (secs usecs) (sb-ext:get-time-of-day) (declare (type unsigned-byte secs) (type (unsigned-byte 31) usecs)) (float (+ secs (/ usecs 1d6))))) #-sbcl (error "Only supported in SBCL.")) (defun spin-until-ros-time-valid () (spin-until (> (ros-time) 0.0) 0.05 (every-nth-time 100 (ros-warn (roslisp time) "Waiting for valid ros-time before proceeding")))) (defun wait-duration (d) "Wait until time T+D, where T is the current ros-time." (spin-until-ros-time-valid) (let ((until (+ (ros-time) d))) (spin-until (>= (ros-time) until) .01 (every-nth-time 100 (ros-debug (roslisp time) "In wait-duration spin loop; waiting until ~a" until))))) ;;; Deprecated special variables (defvar *%time-base* (unix-time) "This variable is deprecated as of roslisp 1.9.18. Holds unix time (rounded to the nearest second) when roslisp was started") (define-symbol-macro *time-base* (progn (warn "roslisp:*time-base* is deprecated as of roslisp 1.9.18.") *%time-base*)) (defvar *%internal-time-base* (get-internal-real-time) "This variable is deprecated as of roslisp 1.9.18. Holds CL's internal time when roslisp was started") (define-symbol-macro *internal-time-base* (progn (warn "roslisp:*internal-time-base* is deprecated as of roslisp 1.9.18.") *%internal-time-base))
0
apollo_public_repos/apollo-platform/ros/roslisp
apollo_public_repos/apollo-platform/ros/roslisp/src/msg-header.lisp
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Software License Agreement (BSD License) ;; ;; Copyright (c) 2008, Willow Garage, Inc. ;; All rights reserved. ;; ;; Redistribution and use in source and binary forms, with ;; or without modification, are permitted provided that the ;; following conditions are met: ;; ;; * Redistributions of source code must retain the above ;; copyright notice, this list of conditions and the ;; following disclaimer. ;; * Redistributions in binary form must reproduce the ;; above copyright notice, this list of conditions and ;; the following disclaimer in the documentation and/or ;; other materials provided with the distribution. ;; * Neither the name of Willow Garage, Inc. nor the names ;; of its contributors may be used to endorse or promote ;; products derived from this software without specific ;; prior written permission. ;; ;; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND ;; CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED ;; WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED ;; WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A ;; PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE ;; COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, ;; INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR ;; CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, ;; PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ;; DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ;; CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN ;; CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE ;; OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS ;; SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH ;; DAMAGE. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (in-package :roslisp) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Special case code for message headers ;; Not currently used ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; #| (defvar *serialize-recursion-level* 0 "Bound during calls to serialize, so we can keep track of when header time stamps need to be filled in") (defvar *seq* 0) (defvar *seq-lock* (make-mutex :name "lock on seq global variable")) ;; not currently used (defvar *set-seq* nil) ;; For now not setting seq fields as doesn't seem to be necessary for ROS (defmethod serialize :around (msg str) ;; Note that each thread has its own copy of the variable (let ((*serialize-recursion-level* (1+ *serialize-recursion-level*))) (call-next-method))) (defmethod serialize :around ((msg rosgraph_msgs-msg:<Header>) str) ;; We save the old stamp for convenience when debugging interactively and reusing the same message object (let ((old-stamp (rosgraph_msgs-msg:stamp msg))) (unwind-protect (progn (when (= *serialize-recursion-level* 1) (when *set-seq* (setf (rosgraph_msgs-msg:seq msg) (incf *seq*))) (when (= (rosgraph_msgs-msg:stamp msg) 0.0) (setf (rosgraph_msgs-msg:stamp msg) (ros-time)))) (call-next-method)) (setf (rosgraph_msgs-msg:stamp msg) old-stamp)))) |#
0
apollo_public_repos/apollo-platform/ros/roslisp
apollo_public_repos/apollo-platform/ros/roslisp/src/rosout-codegen.lisp
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Software License Agreement (BSD License) ;; ;; Copyright (c) 2008, Willow Garage, Inc. ;; All rights reserved. ;; ;; Redistribution and use in source and binary forms, with ;; or without modification, are permitted provided that the ;; following conditions are met: ;; ;; * Redistributions of source code must retain the above ;; copyright notice, this list of conditions and the ;; following disclaimer. ;; * Redistributions in binary form must reproduce the ;; above copyright notice, this list of conditions and ;; the following disclaimer in the documentation and/or ;; other materials provided with the distribution. ;; * Neither the name of Willow Garage, Inc. nor the names ;; of its contributors may be used to endorse or promote ;; products derived from this software without specific ;; prior written permission. ;; ;; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND ;; CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED ;; WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED ;; WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A ;; PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE ;; COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, ;; INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR ;; CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, ;; PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ;; DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ;; CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN ;; CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE ;; OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS ;; SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH ;; DAMAGE. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (in-package :roslisp) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; code generation for rosout ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun designated-list (x) (if (listp x) x (list x))) (defgeneric make-keyword-symbol (s) (:method ((s symbol)) (intern (string-upcase (symbol-name s)) :keyword)) (:method ((s string)) (intern (string-upcase s) :keyword))) (defun can-write-to-log () (and *ros-log-stream* (open-stream-p *ros-log-stream*))) (defun rosout-msg (name level args) (let ((code (symbol-code 'rosgraph_msgs-msg:Log level))) (when (typep (first args) 'string) (push t args)) (dbind (check str &rest format-args) args (let ((output-string (gensym))) `(when (and (>= ,code (debug-level ',(reverse (mapcar #'make-keyword-symbol (if (listp name) name (list name)))))) ,check) (let ((,output-string (format nil ,str ,@format-args))) (with-mutex (*debug-stream-lock*) (format *debug-stream* "~&[~a ~a] ~,3F: ~a~&" ',(designated-list name) ,level (ros-time) ,output-string) (when (can-write-to-log) (format *ros-log-stream* "~&[~a ~a] ~,3F: ~a~&" ',(designated-list name) ,level (ros-time) ,output-string))) (force-output *debug-stream*) (when (can-write-to-log) (force-output *ros-log-stream*)) (when (and (eq *node-status* :running) (gethash "/rosout" *publications*)) (publish "/rosout" (make-instance 'rosgraph_msgs-msg:Log :name *ros-node-name* :level ,code :msg ,output-string)))))))))
0
apollo_public_repos/apollo-platform/ros/roslisp
apollo_public_repos/apollo-platform/ros/roslisp/src/rosutils.lisp
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Software License Agreement (BSD License) ;; ;; Copyright (c) 2008, Willow Garage, Inc. ;; All rights reserved. ;; ;; Redistribution and use in source and binary forms, with ;; or without modification, are permitted provided that the ;; following conditions are met: ;; ;; * Redistributions of source code must retain the above ;; copyright notice, this list of conditions and the ;; following disclaimer. ;; * Redistributions in binary form must reproduce the ;; above copyright notice, this list of conditions and ;; the following disclaimer in the documentation and/or ;; other materials provided with the distribution. ;; * Neither the name of Willow Garage, Inc. nor the names ;; of its contributors may be used to endorse or promote ;; products derived from this software without specific ;; prior written permission. ;; ;; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND ;; CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED ;; WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED ;; WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A ;; PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE ;; COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, ;; INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR ;; CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, ;; PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ;; DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ;; CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN ;; CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE ;; OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS ;; SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH ;; DAMAGE. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (in-package roslisp) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; ROSLisp-specific utility code ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (define-condition function-timeout (error) ()) (defun with-function-timeout (expires body-fun) "throws function-timeout error when call takes longer than expires arg" (flet ((timeout-fun () (error 'function-timeout))) (let ((timer (sb-ext:make-timer #'timeout-fun))) (sb-ext:schedule-timer timer expires) (unwind-protect (funcall body-fun) (sb-ext:unschedule-timer timer))))) (defun get-ros-log-location (name) ;; Tries various possibilities in order of decreasing priority (let ((log-dir (sb-ext:posix-getenv "ROS_LOG_DIR")) (ros-home-dir (sb-ext:posix-getenv "ROS_HOME")) (home-dir (sb-ext:posix-getenv "HOME"))) (or *ros-log-location* (merge-pathnames (pathname (format nil "~a-~a.log" (if (eql (aref name 0) #\/) (subseq name 1) name) (unix-time))) (or (when log-dir (concatenate 'string log-dir "/")) (when ros-home-dir (concatenate 'string ros-home-dir "/log/")) (when home-dir (concatenate 'string home-dir "/.ros/log/")) (error "None of the possibilities for the log directory worked. Even the HOME environment variable was not set.")))))) (defun parse-uri (uri) "parse a uri struct or uri string of the form http://address:port. Return two values: address and port." (etypecase uri (string (let ((tokens (tokens uri :separators (list #\: #\/)))) (unless (and (= (length tokens) 3) (string= (first tokens) "http")) (error "Malformed URI ~a" uri)) (values (second tokens) (read-from-string (third tokens))))) (uri (values (uri-address uri) (uri-port uri))))) (defun parse-rosrpc-uri (uri) (let ((tokens (tokens uri :separators (list #\/ #\:)))) (unless (and (= (length tokens) 3) (string= (first tokens) "rosrpc")) (error "URI ~a was not of the expected form" uri)) (values (second tokens) (read-from-string (third tokens))))) (defmacro roslisp-error (str &rest args) `(progn (ros-error nil ,str ,@args) (error ,str ,@args))) (defmacro roslisp-warn (str &rest args) `(progn (ros-warn nil ,str ,@args) (warn ,str ,@args))) (defun get-ip-address (hostname) "Map from hostname into a vector of the form #(127 0 0 1)" (let ((address-vector (or (parse-string-ip-address hostname) (cond ((member hostname '("localhost" "127.0.0.1") :test #'equal) #(127 0 0 1)) ((and (typep hostname '(vector * 4)) (every #'numberp hostname)) hostname) (t (let ((address (lookup-hostname-ip-address hostname))) (etypecase address (string (let ((tokens (tokens address :separators (list #\.)))) (map 'vector #'(lambda (token) (read-from-string token)) tokens))) (vector address) (list (coerce address 'vector))))))))) (if (and (typep address-vector '(vector * 4)) (every #'(lambda (x) (typep x '(mod 256))) address-vector)) address-vector (error "Converting ~a into ip address vector resulted in ~a, which doesn't look right" hostname address-vector)))) (defun parse-string-ip-address (hostname) "If string can be parsed as 4 numbers separated by .'s return vector of those numbers, else return nil" (let ((tokens (tokens hostname :separators (list #\.)))) (when (= 4 (length tokens)) (let ((read-tokens (map 'vector #'read-from-string tokens))) (when (every #'(lambda (x) (typep x '(mod 256))) read-tokens) read-tokens))))) (defun ip-address-string (address) (etypecase address (string address) (list (format nil "~{~a~^.~}" address)) (vector (ip-address-string (coerce address 'list))))) (defun lookup-hostname-ip-address (hostname) (host-ent-address (get-host-by-name hostname))) (defun hostname () (or (sb-ext:posix-getenv "ROS_HOSTNAME") (sb-ext:posix-getenv "ROS_IP") (run-external "hostname"))) (defun get-topic-class-name (topic) "Given a topic foo with message type, say the string /std_msgs/bar, this returns the symbol named bar from the package std_msgs. The topic must be one that has already been advertised or subscribed to." (let ((sub (gethash topic *subscriptions*)) (pub (gethash topic *publications*))) (assert (or sub pub) nil "Can't get class name of topic ~a that we neither publish nor subscribe" topic) (let* ((type (if sub (sub-topic-type sub) (pub-topic-type pub))) (tokens (tokens type :separators '(#\/)))) (assert (= 2 (length tokens)) nil "topic type ~a of topic ~a was not of the form foo/bar" type topic) (let* ((class-name (concatenate 'string (string-upcase (second tokens)))) (pkg-name (string-upcase (concatenate 'string (first tokens) "-msg"))) (class-symbol (find-symbol class-name pkg-name))) (assert class-symbol nil "Could not find symbol ~a in ~a" class-name pkg-name) class-symbol)))) (defvar *message-dir-cache* (make-hash-table :test #'equal)) (defvar *service-dir-cache* (make-hash-table :test #'equal)) (defun run-external (cmd &rest args) (let ((str (make-string-output-stream))) (let ((proc (sb-ext:run-program cmd args :search t :output str :wait nil))) (sb-ext:process-wait proc) (if (zerop (sb-ext:process-exit-code proc)) (first (last (tokens (get-output-stream-string str) :separators '(#\Newline)))) (error "Received exit code ~a when running external process ~a with args ~a" (sb-ext:process-exit-code proc) cmd args))))) (defvar *loaded-files* (make-hash-table :test #'equal)) (defmacro load-if-necessary (f) "load-if-necessary FILENAME. FILENAME is a string containing a path to a file. Maintains an internal list (per Lisp session) of which ones have been already loaded, and does not reload a file twice (to avoid annoying warnings). DEPRECATED!" (declare (ignorable f)) (error "load-if-necessary deprecated!")) (defmacro load-message-types (&rest message-types) `(progn ,@(mapcar (lambda (msg-type) (let ((msg-system-name (concatenate 'string (if (symbolp msg-type) (string-downcase (symbol-name msg-type)) msg-type) "-msg"))) `(asdf:operate 'asdf:load-op ,msg-system-name))) message-types))) (defmacro load-service-types (&rest service-types) "load-service-types &rest SERVICE-TYPES Each service type is a string of form package/service. Loads the corresponding Lisp files. Makes sure to load things only once. This means that if the .lisp files are changed during the current Lisp session (which wouldn't happen in the normal scheme of things), you will have to manually reload the file rather than using this function." `(progn ,@(mapcar (lambda (msg-type) (let ((msg-system-name (concatenate 'string (if (symbolp msg-type) (string-downcase (symbol-name msg-type)) msg-type) "-srv"))) `(asdf:operate 'asdf:load-op ,msg-system-name))) service-types))) (defun standalone-exec-debug-hook (a b) (declare (ignore b)) (when (eq *node-status* :running) (invoke-restart 'shutdown-ros-node a) )) (defmacro store-message-in (place) "Macro store-message-in PLACE Used if you want a callback function for a topic that just stores the message in some variable. Expands to definition of a function that sets PLACE to equal its argument." (let ((message (gensym))) `#'(lambda (,message) (setf ,place ,message)))) (defmacro load-msg (msg-type) "Intended for interactive use. Pass it a string which is the ros name of the given message, e.g. std_msgs/String. Loads the corresponding class and calls use-package on that package." (let ((pkg-name (first (roslisp-utils:tokens msg-type :separators "/")))) `(progn (load-message-types ,msg-type) (use-package ,(intern (string-upcase (concatenate 'string pkg-name "-msg")) :keyword))))) (defmacro load-srv (msg-type) "Intended for interactive use. Pass it a string which is the ros name of the given message, e.g. std_msgs/String. Loads the corresponding class and calls use-package on that package." (let ((pkg-name (first (roslisp-utils:tokens msg-type :separators "/")))) `(progn (load-service-types ,msg-type) (use-package ,(intern (string-upcase (concatenate 'string pkg-name "-srv")) :keyword))))) (defun lookup-topic-type (type) "if it's, e.g., the string std_msgs/String just return it, if it's, e.g., 'std_msgs:<String>, return the string std_msgs/String" (etypecase type (string (ros-datatype (string-to-ros-msgtype-symbol type))) (symbol (ros-datatype type)))) (defun make-service-symbol (type-string) (let ((pkg (find-package (string-upcase (concatenate 'string (subseq type-string 0 (position #\/ type-string)) "-srv")))) (msg-name (string-upcase (subseq type-string (1+ (position #\/ type-string)))))) (assert pkg () "Service-package not found. Maybe it is not loaded?") (nth-value 0 (intern msg-name pkg))))
0
apollo_public_repos/apollo-platform/ros/roslisp
apollo_public_repos/apollo-platform/ros/roslisp/src/sockets.lisp
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Software License Agreement (BSD License) ;; ;; Copyright (c) 2008, Willow Garage, Inc. ;; All rights reserved. ;; ;; Redistribution and use in source and binary forms, with ;; or without modification, are permitted provided that the ;; following conditions are met: ;; ;; * Redistributions of source code must retain the above ;; copyright notice, this list of conditions and the ;; following disclaimer. ;; * Redistributions in binary form must reproduce the ;; above copyright notice, this list of conditions and ;; the following disclaimer in the documentation and/or ;; other materials provided with the distribution. ;; * Neither the name of Willow Garage, Inc. nor the names ;; of its contributors may be used to endorse or promote ;; products derived from this software without specific ;; prior written permission. ;; ;; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND ;; CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED ;; WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED ;; WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A ;; PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE ;; COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, ;; INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR ;; CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, ;; PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ;; DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ;; CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN ;; CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE ;; OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS ;; SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH ;; DAMAGE. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (in-package roslisp) (defun close-socket (socket) "Remove all handlers from this socket and close it" (ros-debug (roslisp tcp) "~&Closing ~a" socket) (invalidate-descriptor (socket-file-descriptor socket)) (socket-close socket)) (defun tcp-connect (hostname port) "Helper that connects over TCP to this host and port, and returns 1) The stream 2) The socket" (let ((connection (make-instance 'inet-socket :type :stream :protocol :tcp)) (ip-address (get-ip-address hostname))) (ros-debug (roslisp tcp) "~&Connecting to ~a ~a" ip-address port) (socket-connect connection ip-address port) (values (socket-make-stream connection :output t :input t :element-type '(unsigned-byte 8)) connection)))
0
apollo_public_repos/apollo-platform/ros/roslisp
apollo_public_repos/apollo-platform/ros/roslisp/src/client.lisp
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Software License Agreement (BSD License) ;; ;; Copyright (c) 2008, Willow Garage, Inc. ;; All rights reserved. ;; ;; Redistribution and use in source and binary forms, with ;; or without modification, are permitted provided that the ;; following conditions are met: ;; ;; * Redistributions of source code must retain the above ;; copyright notice, this list of conditions and the ;; following disclaimer. ;; * Redistributions in binary form must reproduce the ;; above copyright notice, this list of conditions and ;; the following disclaimer in the documentation and/or ;; other materials provided with the distribution. ;; * Neither the name of Willow Garage, Inc. nor the names ;; of its contributors may be used to endorse or promote ;; products derived from this software without specific ;; prior written permission. ;; ;; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND ;; CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED ;; WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED ;; WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A ;; PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE ;; COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, ;; INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR ;; CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, ;; PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ;; DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ;; CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN ;; CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE ;; OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS ;; SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH ;; DAMAGE. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (in-package :roslisp) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; The operations called by client code ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun advertise (topic topic-type &key (latch nil)) "TOPIC is a string naming a ros topic TOPIC-TYPE is either a string that equals the ros datatype of the topic (e.g. robot_msgs/Pose) or the symbol naming the message type in lisp (e.g. 'robot_msgs:<Pose>) LATCH (defaults to nil). If non-nil, last message sent on this topic will be sent to new subscribers upon connection. Set up things so that publish may now be called with this topic. Also, returns a publication object that can be used instead of the topic name when publishing." (declare (type (or string symbol) topic-type) (string topic)) (ensure-node-is-running) (setq topic-type (lookup-topic-type topic-type)) (with-fully-qualified-name topic (with-recursive-lock (*ros-lock*) (or (gethash topic *publications*) (let ((pub (make-publication :pub-topic-type topic-type :subscriber-connections nil :is-latching latch :last-message nil))) (setf (gethash topic *publications*) pub) (protected-call-to-master ("registerPublisher" topic topic-type *xml-rpc-caller-api*) c (remhash topic *publications*) (roslisp-error "Unable to contact master at ~a for advertising ~a: ~a" *master-uri* topic c)) (ros-debug (roslisp pub) "Advertised ~a of type ~a" topic topic-type) pub))))) (defun unadvertise (topic) (ensure-node-is-running) (with-fully-qualified-name topic (with-recursive-lock (*ros-lock*) (unless (hash-table-has-key *publications* topic) (roslisp-warn "Not publishing on ~a" topic)) (remhash topic *publications*) (protected-call-to-master ("unregisterPublisher" topic *xml-rpc-caller-api*) c (ros-warn (roslisp) "Could not contact master at ~a when unregistering as publisher of ~a during shutdown: ~a" *master-uri* topic c))))) (defmacro make-publisher-msg (pub &rest msg-args) "Convenience function to create a message that fits to a publisher. Uses the type of the publication PUB to make-msg with the MSG-ARGS." `(make-message (pub-topic-type ,pub) ,@msg-args)) (defmacro publish-msg (pub &rest msg-args) "Convenience function that first does make-msg using the type of PUB and MSG-ARGS, then publishes the resulting message on PUB" (let ((p (gensym))) `(let ((,p ,pub)) (publish ,p (make-msg (pub-topic-type ,p) ,@msg-args))))) (defgeneric publish (pub message) (:documentation "PUB is either a publication object returned by advertise, or a string naming a ros topic. MESSAGE is the message object of the appropriate type for this topic.") (:method :before (pub message) (ensure-node-is-running)) (:method ((topic string) message) (declare (type ros-message message)) (with-fully-qualified-name topic (mvbind (publication known) (gethash topic *publications*) (unless known (if (equal topic "/rosout") (error "The topic /rosout was itself unknown") (roslisp-error "Unknown topic ~a" topic))) (publish publication message)))) (:method ((publication publication) message) ;; Latch the message (when (is-latching publication) (setf (last-message publication) message)) ;; Remove closed streams (setf (subscriber-connections publication) (delete-if #'(lambda (sub) (let ((str (subscriber-stream sub))) (or (not (open-stream-p str)) (gethash str *broken-socket-streams*)))) (subscriber-connections publication))) ;; Write message to each stream (let ((num-written 0)) (dolist (sub (subscriber-connections publication) num-written) ;; TODO: TCPROS has been hardcoded in (incf num-written (tcpros-write message (subscriber-stream sub)))) ))) (defun register-service-fn (service-name function service-type) "service-name is a string, and is the ros name of the service. service type is the symbol lisp type of the service (the base name of the .srv file, e.g., 'roslisp_examples:AddTwoInts). Postcondition: the node has set up a callback for calls to this service, and registered it with the master" (declare (string service-name) (function function) (symbol service-type)) (ensure-node-is-running) (with-fully-qualified-name service-name (with-recursive-lock (*ros-lock*) (let ((info (gethash service-name *services*))) (when info (roslisp-error "Cannot create service ~a as it already exists with info ~a" service-name info))) (let ((uri *service-uri*) (req-class (service-request-type service-type))) (setf (gethash service-name *services*) (make-service :callback function :name service-name :ros-type (ros-datatype service-type) :request-ros-type (ros-datatype (service-request-type service-type)) :response-ros-type (ros-datatype (service-response-type service-type)) :request-class req-class :md5 (md5sum req-class))) (protected-call-to-master ("registerService" service-name uri *xml-rpc-caller-api*) c (remhash service-name *services*) (roslisp-error "Socket error ~a when attempting to contact master at ~a for advertising service ~a" c *master-uri* service-name)))))) (defmacro register-service (service-name service-type) "Register service with the given name SERVICE-NAME (a string) of type SERVICE-TYPE (a symbol) with the master. The callback for the service is also a function named SERVICE-TYPE. See also register-service-fn, for if you want to use a function object as the callback." (when (and (listp service-type) (eq 'quote (first service-type))) (setq service-type (second service-type))) `(register-service-fn ,service-name #',service-type ',service-type)) (defmacro def-service-callback (service (&rest args) &body body) "Define a service callback named SERVICE-FN-NAME for service of type SERVICE-TYPE-NAME (a symbol, e.g 'roslisp_examples:AddTwoInts). ARGS is a list of symbols naming particular fields of the service request object which will be available within the body. Within the body, you may also call the function make-response. This will make an instance of the response message type. E.g., to make a response object with field foo=3, (make-response :foo 3). Instead of (SERVICE-FN-NAME SERVICE-TYPE-NAME), you can just specify a symbol SERVICE-NAME, which will then be used as both." (let ((req (gensym)) (response-args (gensym)) (response-type (gensym)) service-type-name service-fn-name) (etypecase service (list (setq service-fn-name (first service) service-type-name (second service))) (symbol (setq service-fn-name service service-type-name service))) `(defun ,service-fn-name (,req) (declare (ignorable ,req)) ;; For the case when the request object is empty (let ((,response-type (service-response-type ',service-type-name))) (with-fields ,args ,req (flet ((make-response (&rest ,response-args) (apply #'make-instance ,response-type ,response-args))) ,@body)))))) (defclass service-client () ((service-client-name :reader service-client-name :initarg :service-client-name :documentation "The name of the service with the ROS master.") (service-client-type :reader service-client-type :initarg :service-client-type :documentation "Type of message sent to request the service."))) (defun make-service-client (service-name service-type) "Convenience function to create service-client object. SERVICE-NAME should be the name of the service at the ROS MASTER, and SERVICE-TYPE is the name of the service message that is send to request the service." (check-type service-name string) (check-type service-type string) (make-instance 'service-client :service-client-name service-name :service-client-type service-type)) (defgeneric call-service (service &rest rest-args)) (defmethod call-service ((service-name string) &rest rest-args) "call-service SERVICE-NAME SERVICE-TYPE &rest ARGS or call-service SERVICE-NAME SERVICE-TYPE REQUEST-OBJECT (happens iff length(ARGS) is 1) SERVICE-NAME - a string that is the ROS name of the service, e.g., my_namespace/my_srv SERVICE-TYPE - symbol or string naming the Lisp type (the basename of the .srv file), e.g. 'AddTwoInts, or the fully qualified type of the service, e.g. \"test_ros/AddTwoInts\" REQUEST-ARGS - initialization arguments that would be used when calling make-instance to create a request object. REQUEST-OBJECT - the request object itself Returns the response object from the service." (destructuring-bind (service-type &rest request-args) rest-args (declare (string service-name) ((or symbol string) service-type)) (ensure-node-is-running) (let* ((service-type (etypecase service-type (symbol service-type) (string (make-service-symbol service-type)))) (response-type (service-response-type service-type))) (with-fully-qualified-name service-name (mvbind (host port) (parse-rosrpc-uri (lookup-service service-name)) ;; No error checking: lookup service should signal an error if there are problems (let ((obj (if (= 1 (length request-args)) (first request-args) (apply #'make-service-request service-type request-args)))) (ros-debug (roslisp call-service) "Calling service at host ~a and port ~a with ~a" host port obj) (tcpros-call-service host port service-name obj response-type))))))) (defmethod call-service ((service service-client) &rest rest-args) "Convenience wrapper of call-service using a service client. Refer to the other call-service for the semantics of the function. SERVICE-CLIENT expects an object of type service-client, though." (apply #'call-service (service-client-name service) (service-client-type service) rest-args)) (defgeneric wait-for-service (service &optional timeout)) (defmethod wait-for-service ((service-name string) &optional timeout) "wait-for-service SERVICE-NAME &optional TIMEOUT Blocks until a service with this name is known to the ROS Master (unlike roscpp, doesn't currently check if the connection is actually valid), then returns true. TIMEOUT, if specified and non-nil, is the maximum (wallclock) time to wait for. If we time out, returns false." (ensure-node-is-running) (let* ((first-time t) (timed-out (nth-value 1 (spin-until (handler-case (progn (lookup-service service-name) t) (ros-rpc-error (c) (declare (ignore c)) nil)) (.1 timeout) (when first-time (setq first-time nil) (ros-debug (roslisp wait-for-service) "Waiting for service ~a" service-name)))))) (ros-debug (roslisp wait-for-service) (not timed-out) "Found service ~a" service-name) (ros-debug (roslisp wait-for-service) timed-out "Timed out waiting for service ~a" service-name) (not timed-out))) (defmethod wait-for-service ((service-client service-client) &optional timeout) "Convenience wrapper of wait-for-service using a service client. Refer to the other wait-for-service for the semantics of the function. SERVICE-CLIENT expects an object of type service-client, though." (wait-for-service (service-client-name service-client) timeout)) (defun subscribe (topic topic-type callback &key (max-queue-length 'infty)) "subscribe TOPIC TOPIC-TYPE CALLBACK &key MAX-QUEUE-LENGTH TOPIC is a string that equals the ros name of the topic TOPIC-TYPE is either a string equalling the ros datatype of the topic, or a symbol naming the lisp type of the messages (see advertise above). CALLBACK is a function of a single argument. MAX-QUEUE-LENGTH is a number. If not provided, it defaults to infinity. Set up subscription to TOPIC with given type. CALLBACK will be called on the received messages in a separate thread. MAX-QUEUE-LENGTH is the number of messages that are allowed to queue up while waiting for CALLBACK to run. Can also be called on a topic that we're already subscribed to - in this case, ignore MAX-QUEUE-LENGTH, and just add this new callback function. It will run in the existing callback thread for the topic, so that at most one callback function can be running at a time." (declare (string topic) (type (or symbol string) topic-type) (function callback)) (ensure-node-is-running) (handler-case (setq topic-type (lookup-topic-type topic-type)) (error (c) (declare (ignore c)) (warn "Couldn't lookup topic type ~a for ~a, so not subscribing." topic-type topic) (return-from subscribe))) (with-fully-qualified-name topic (with-recursive-lock (*ros-lock*) (if (hash-table-has-key *subscriptions* topic) ;; If already subscribed to topic, just add a new callback (let ((sub (gethash topic *subscriptions*))) (unless (equal topic-type (sub-topic-type sub)) (roslisp-error "Asserted topic type ~a for new subscription to ~a did not match existing type ~a" topic-type topic (sub-topic-type sub))) (push callback (callbacks sub)) (make-subscriber :topic topic :subscription sub :callback callback)) ;; Else create a new thread (let ((sub (make-subscription :buffer (make-queue :max-size max-queue-length) :publisher-connections nil :callbacks (list callback) :sub-topic-type topic-type))) (setf (gethash topic *subscriptions*) sub (topic-thread sub) (sb-thread:make-thread (subscriber-thread sub) :name (format nil "Subscriber thread for topic ~a" topic))) (handler-case (progn (update-publishers topic (protected-call-to-master ("registerSubscriber" topic topic-type *xml-rpc-caller-api*) c (roslisp-error "Could not contact master at ~a when registering as subscriber to ~a: ~a" *master-uri* topic c))) (make-subscriber :topic topic :subscription sub :callback callback)) (error (c) (warn "Received error ~a when attempting to setup subscription to ~a of type ~a, so not subscribing." c topic topic-type) (remhash topic *subscriptions*)))))))) (defun unsubscribe (subscriber) (check-type subscriber subscriber) (with-recursive-lock (*ros-lock*) (let ((sub (gethash (subscriber-topic subscriber) *subscriptions*))) (assert sub () (format nil "Subscription to topic `~a' invalid." (subscriber-topic subscriber))) (setf (callbacks sub) (delete (subscriber-callback subscriber) (callbacks sub))) (when (null (callbacks sub)) (protected-call-to-master ("unregisterSubscriber" (subscriber-topic subscriber) *xml-rpc-caller-api*) c (roslisp-error "Could not contact master at ~a when unregistering subscriber to ~a: ~a" *master-uri* (subscriber-topic subscriber) c)) (remhash (subscriber-topic subscriber) *subscriptions*)))) (values)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Internal ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (declaim (inline ensure-node-is-running)) (defun ensure-node-is-running () (unless (eq *node-status* :running) (cerror "Start a dummy node" "Node status is ~a" *node-status*) (start-ros-node "dummy"))) (defun event-loop () (loop ;; If node has stopped, end loop (unless (eq *node-status* :running) (return)) ;; Allow the tcp server to respond to any incoming connections (handler-bind ((error #'(lambda (c) (with-recursive-lock (*ros-lock*) (unless (eq *node-status* :running) (ros-info (roslisp event-loop) "Event loop received error ~a. Node-status is now ~a" c *node-status*) (return)))))) (sb-sys:serve-all-events 1))) (ros-info (roslisp event-loop) "Terminating ROS Node event loop")) (defun subscriber-thread (sub) "This is the thread that takes items off the queue and performs the callback on them (as separate from the one that puts items onto the queue from the socket)" ;; We don't acquire *ros-lock* - the assumption is that the callback is safe to interleave with the node operations defined in the roslisp package (declare (type subscription sub)) (let ((q (buffer sub))) #'(lambda () (loop (mvbind (item exists) (dequeue-wait q) (unless exists (return)) ;; We have to get this each time because there may be new callbacks (dolist (callback (callbacks sub)) (handler-case (funcall callback item) (error (e) (ros-error (roslisp service tcp) "Error during subscriber callback: '~a' for topic item: ~%~a " e item))))))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Experimental ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro def-ros-node (name params (&key spin) &body body) (let ((doc-string (if (stringp (first body)) (first body) "")) (body (if (stringp (first body)) (rest body) body))) `(defun ,name () ,doc-string (with-ros-node (,(string-downcase (symbol-name name)) ,@(when spin '(:spin t))) (let ,(mapcar #'(lambda (param) (let ((param-name (concatenate 'string "~" (string-downcase (symbol-name param))))) `(,param (get-param ,param-name)))) params) ,@body))))) (defmacro def-service-call (a service-ros-name &key return-field) "Convenience macro for calls to a service. def-service-call (FN-NAME TYPE-NAME) ROS-NAME &key RETURN-FIELD where FN-NAME and TYPE-NAME are unevaluated symbols, ROS-NAME is a string (evaluated, so doesn't have to be a literal) This means define a function FN-NAME that calls a ros service with the given ros-name, whose lisp type (which is the base name of the .srv file, but may have to be package qualified if you haven't imported it) is TYPE-NAME. The function does a calls the given service using an appropriately typed request object constructed using its arguments. The first argument can also be a symbol NAME (unevaluated), which uses NAME for both FN-NAME and TYPE-NAME If RETURN-FIELD is provided, that field of the response is returned. Otherwise, the entire response is returned." (let ((args (gensym)) (response (gensym)) name service-type) (if (listp a) (setq name (first a) service-type `',(second a)) (setq name a service-type `',a)) `(defun ,name (&rest ,args) (let ((,response (apply #'call-service ,service-ros-name ,service-type ,args))) ,(if return-field `(with-fields (,return-field) ,response ,return-field) response)))))
0
apollo_public_repos/apollo-platform/ros/roslisp
apollo_public_repos/apollo-platform/ros/roslisp/src/slave.lisp
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Software License Agreement (BSD License) ;; ;; Copyright (c) 2008, Willow Garage, Inc. ;; All rights reserved. ;; ;; Redistribution and use in source and binary forms, with ;; or without modification, are permitted provided that the ;; following conditions are met: ;; ;; * Redistributions of source code must retain the above ;; copyright notice, this list of conditions and the ;; following disclaimer. ;; * Redistributions in binary form must reproduce the ;; above copyright notice, this list of conditions and ;; the following disclaimer in the documentation and/or ;; other materials provided with the distribution. ;; * Neither the name of Willow Garage, Inc. nor the names ;; of its contributors may be used to endorse or promote ;; products derived from this software without specific ;; prior written permission. ;; ;; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND ;; CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED ;; WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED ;; WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A ;; PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE ;; COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, ;; INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR ;; CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, ;; PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ;; DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ;; CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN ;; CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE ;; OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS ;; SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH ;; DAMAGE. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (in-package roslisp) (defparameter *xmlrpc-timeout* 1.0 "How many seconds to wait until giving up") ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Slave API - implements XML-RPC calls to this node from ;; other nodes or from the master node. ;; ;; 1) XML-RPC calls have API-wide locking - only one can ;; be active at a time. ;; 2) The funny function names are because XML-RPC is ;; case sensitive and Lisp symbols are not, by default. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun |getPid| (caller-id) "getPid XML-RPC method. Takes no arguments, returns 1 upon success." (declare (ignore caller-id)) (let ((pid (sb-unix:unix-getpid))) (list 1 (format nil "PID is ~a" pid) pid))) (defun |shutdown| (caller-id) "shutdown XML-RPC method. Takes no arguments, shuts down the ROS node." ;; No need to acquire lock as shutdown acquires it (shutdown-ros-node) (list 1 (format nil "shutdown by ~a" caller-id) nil)) (defun |publisherUpdate| (caller-id topic publishers) "publisherUpdate XMl-RPC method. TOPIC : string naming the topic PUBLISHERS : list of publishers, each of which is a list (ADDRESS PORT)." (declare (ignore caller-id)) (ros-debug (roslisp topic) "Publisher update ~a ~a" topic publishers) (with-recursive-lock (*ros-lock*) (update-publishers topic publishers))) (defun |getBusInfo| (caller-id) "getBusInfo XML-RPC method Used to get info about the node's connections (e.g., for rosnode info)" (ros-debug (roslisp slave) "Received call to getBusInfo from ~a" caller-id) (with-recursive-lock (*ros-lock*) (list 1 (format nil "getBusInfo call returning") (nconc (publications-info) (subscriptions-info))))) (defun publications-info () "Helper for getBusInfo" (loop :for topic :being :each :hash-key :in *publications* :using (:hash-value pub) :append (mapcar #'(lambda (c) (publication-info topic c)) (subscriber-connections pub)))) (defun publication-info (topic conn) (list (sxhash conn) (subscriber-uri conn) "o" "TCPROS" topic)) (defun subscriptions-info () "Helper for getBusInfo" (loop :for topic :being :each :hash-key :in *subscriptions* :using (:hash-value sub) :append (mapcar #'(lambda (c) (subscription-info topic c)) (publisher-connections sub)))) (defun subscription-info (topic conn) (list (sxhash conn) (uri conn) "i" "TCPROS" topic)) (defun |requestTopic| (caller-id topic protocols) "requestTopic XML-RPC method TOPIC: string naming a topic PROTOCOLS: list of protocols, each of which is a list (PROTOCOL-NAME-STRING . PROTOCOL-INBOUND-PARAMS) If the topic is not one published by this node, return -1. If none of the protocols supported by this node return 0. Else return 1, msg, (PROTOCOL-NAME-STRING . PROTOCOL-OUTBOUND-PARAMS) Notes 1. Currently only TCPROS is supported. There are no other inbound params, and the outbound params are address, port (integers). 2. This call does not actually set up the transport over the agreed-upon protocol. In the TCP case, the subscriber must then connect to the given address and port over TCP, and send a string containing the topic name and MD5 sum." (declare (string topic) (sequence protocols)) (ros-debug (roslisp slave request-topic) "Received call `requestTopic ~a ~a ~a" caller-id topic protocols) (with-recursive-lock (*ros-lock*) (if (find "TCPROS" protocols :key #'first :test #'string=) (if (hash-table-has-key *publications* topic) ;; TCPROS-specific (list 1 (format nil "ready on ~a:~a" *tcp-server-hostname* *tcp-server-port*) (list "TCPROS" *tcp-server-hostname* *tcp-server-port*)) ;; If I don't know about this topic (list -1 (format nil "Not a publisher of ~a" topic) nil)) ;; If TCPROS is not on the protocol list (list 0 (format nil "Protocol list ~a does not contain TCPROS" protocols) nil)))) ;; Register the above operations as XML-RPC methods (import '(|getPid| |shutdown| |publisherUpdate| |requestTopic| |getBusInfo|) 's-xml-rpc-exports) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Internal ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun update-publishers (topic publishers) "Helper called by publisherUpdate and registerSubscription" ;; Sometimes this gets called with an empty string for publishers (a bug in s-xml-rpc?) ;; In that case, replace it with the empty list (when (stringp publishers) (if (= 0 (length (string-trim '(#\Space #\Tab #\Newline) publishers))) (setf publishers nil) (progn (ros-error roslisp "In update publishers, got a string ~a rather than a list of publishers. Skipping." publishers) (return-from update-publishers)))) ;; Get the current info for this topic (mvbind (subscription known) (gethash topic *subscriptions*) (cond (known ;; Remove no-longer-existing publisher connections (setf (publisher-connections subscription) (delete-if #'(lambda (conn) (not (member (uri conn) publishers :test #'equal))) (publisher-connections subscription))) ;; Add and subscribe to new ones (dolist (pub publishers (list 1 "updated" 0)) (unless (member pub (publisher-connections subscription) :test #'equal :key #'uri) ;; TCPROS-specific to assume connection consists of a socket and a stream (handler-case (mvbind (conn str) (subscribe-publisher pub topic) (push (make-publisher-connection :publisher-socket conn :publisher-stream str :uri pub) (publisher-connections subscription))) (sb-bsd-sockets:connection-refused-error (c) (ros-debug (roslisp tcp) "Socket error ~a when attempting to subscribe to ~a; skipping" c pub))) ))) ((not known) (list 0 (format nil "I'm not interested in topic ~a" topic) 0))))) (defun subscribe-publisher (uri topic) "Connect over XML-RPC to URI, negotiate a transport, and return the connection information. Right now, the transport must be TCPROS and the return value is the socket." (ros-debug (roslisp topic) "~&Subscribing to ~a at ~a" topic uri) (unless (hash-table-has-key *subscriptions* topic) (roslisp-error "I'm not subscribed to ~a" topic)) (dotimes (repeat 3 (error 'simple-error :format-control "Timeout when subscribing publisher at ~a for topic ~a, check publisher node status. Change *xmlrpc-timeout* to increase wait-time." :format-arguments (list uri topic) )) (handler-case (return (dbind (protocol address port) ;; Check if it's our publisher if that's the case don't request the topic ;; using a ros-rpc-call since it would deadlock and time out (if (equal uri *xml-rpc-caller-api*) (dbind (code msg vals) (|requestTopic| *ros-node-name* topic (list (list "TCPROS"))) (when (<= code 0) (cerror "Ignore and continue" 'ros-rpc-error :call (cons "requestTopic" (list *ros-node-name* topic (list (list "TCPROS")))) :uri uri :code code :message msg :vals vals)) vals) (with-function-timeout *xmlrpc-timeout* (lambda () (ros-rpc-call uri "requestTopic" topic (list (list "TCPROS")))))) (if (string= protocol "TCPROS") (setup-tcpros-subscription address port topic) (ros-error (roslisp tcp) "Protocol ~a did not equal TCPROS... skipping connection" protocol)))) (function-timeout () ;;just retry nil))))
0
apollo_public_repos/apollo-platform/ros/roslisp
apollo_public_repos/apollo-platform/ros/roslisp/src/node.lisp
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Software License Agreement (BSD License) ;; ;; Copyright (c) 2008, Willow Garage, Inc. ;; All rights reserved. ;; ;; Redistribution and use in source and binary forms, with ;; or without modification, are permitted provided that the ;; following conditions are met: ;; ;; * Redistributions of source code must retain the above ;; copyright notice, this list of conditions and the ;; following disclaimer. ;; * Redistributions in binary form must reproduce the ;; above copyright notice, this list of conditions and ;; the following disclaimer in the documentation and/or ;; other materials provided with the distribution. ;; * Neither the name of Willow Garage, Inc. nor the names ;; of its contributors may be used to endorse or promote ;; products derived from this software without specific ;; prior written permission. ;; ;; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND ;; CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED ;; WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED ;; WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A ;; PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE ;; COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, ;; INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR ;; CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, ;; PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ;; DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ;; CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN ;; CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE ;; OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS ;; SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH ;; DAMAGE. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (in-package :roslisp) (defun start-ros-node (name &key (xml-rpc-port 8001 xml-port-supp) (pub-server-port 7001 pub-port-supp) (master-uri (make-uri "127.0.0.1" 11311) master-supplied) (anonymous nil) (cmd-line-args (rest sb-ext:*posix-argv*)) &allow-other-keys) "Start up the ROS Node with the given name and master URI. Reset any stored state left over from previous invocations. MASTER-URI is either a string of the form http://foo:12345, or an object created using make-uri. If MASTER-URI is not provided, use *default-master-uri*, and if that's nil (which it will be unless client code sets it), use the value of environment variable ROS_MASTER_URI. ANONYMOUS, if non-nil, causes the current time to be appended to the node name (to make it unique). XML-RPC-PORT and PUB-SERVER-PORT are no longer used. CMD-LINE-ARGS is the list of command line arguments (defaults to argv minus its first element). It can also be a string of space-separated arguments." (declare (string name) (type (or string uri) master-uri)) (assert (not xml-port-supp) nil "start-ros-node no longer accepts the xml-rpc-port argument") (assert (not pub-port-supp) nil "start-ros-node no longer accepts the pub-server-port argument") (unless (eq *node-status* :shutdown) (warn "Before starting node, node-status equalled ~a instead of :shutdown. Shutting the previous node invocation down now." *node-status*) (shutdown-ros-node)) (when anonymous (mvbind (success s ms) (sb-unix:unix-gettimeofday) (declare (ignore success)) (setq name (format nil "~a_~a_~a" name ms s)))) (let ((params (handle-command-line-arguments name cmd-line-args))) (setq *ros-log-location* (get-ros-log-location name)) (ensure-directories-exist *ros-log-location* :verbose nil) (setq *ros-log-stream* (open *ros-log-location* :direction :output :if-exists :overwrite :if-does-not-exist :create)) ;; Deal with the master uri (unless master-supplied (setq master-uri (or *default-master-uri* (sb-ext:posix-getenv "ROS_MASTER_URI"))) (unless (and (stringp master-uri) (> (length master-uri) 0)) (error "Master uri needs to be supplied either as an argument to start-ros-node, or through the environment variable ROS_MASTER_URI, or by setting the lisp variable *default-master-uri*"))) (when (stringp master-uri) (mvbind (address port) (parse-uri master-uri) (setq master-uri (make-uri address port)))) (symbol-macrolet ((address (uri-address master-uri))) (unless (parse-string-ip-address address) (setf address (ip-address-string (lookup-hostname-ip-address address))))) (setq *master-uri* master-uri) ;; Set params specified at command line (dolist (p params) (set-param (car p) (cdr p))) ;; Initialize debug levels (reset-debug-levels (make-instance 'Empty-Request)) ;; Now we can finally print some debug messages (ros-debug (roslisp top) "Log location is ~a" *ros-log-location*) (command-line-args-rosout cmd-line-args params) (unless master-supplied (ros-debug (roslisp top) "Master uri was not supplied, so using default")) (ros-info (roslisp top) "master URI is ~a:~a" (uri-address master-uri) (uri-port master-uri)) ;; Done setting up master connection ;; Spawn a thread that will start up the listeners, then run the event loop (with-recursive-lock (*ros-lock*) (setf *event-loop-thread* (sb-thread:make-thread #'(lambda () (when (eq *node-status* :running) (error "Can't start node as status already equals running. Call shutdown-ros-node first.")) ;; Start publication and xml-rpc servers. (mvbind (srv sock) (start-xml-rpc-server :port 0) (setq *xml-server* srv xml-rpc-port (nth-value 1 (sb-bsd-sockets:socket-name sock)))) (ros-debug (roslisp top) "Started XML-RPC server on port ~a" xml-rpc-port) (setq *tcp-server-hostname* (hostname) *tcp-server* (ros-node-tcp-server 0) pub-server-port (nth-value 1 (sb-bsd-sockets:socket-name *tcp-server*))) (ros-debug (roslisp top) "Started tcpros server on port ~a" pub-server-port) (setq *tcp-server-port* pub-server-port *broken-socket-streams* (make-hash-table :test #'eq) *service-uri* (format nil "rosrpc://~a:~a" *tcp-server-hostname* *tcp-server-port*) *xml-rpc-caller-api* (format nil "http://~a:~a" (hostname) xml-rpc-port) *publications* (make-hash-table :test #'equal) *subscriptions* (make-hash-table :test #'equal) *services* (make-hash-table :test #'equal) *node-status* :running *deserialization-threads* nil ) (pushnew #'maybe-shutdown-ros-node sb-ext:*exit-hooks*) ;; Finally, start the serve-event loop (event-loop)) :name "ROSLisp event loop")) ;; There's no race condition - if this test and the following advertise call all happen before the event-loop starts, ;; things will just queue up (spin-until (eq *node-status* :running) 1)) ;; Advertise on global rosout topic for debugging messages (advertise "/rosout" "rosgraph_msgs/Log") ;; Subscribe to time if necessary (setq *use-sim-time* (member (get-param "/use_sim_time" nil) '("true" 1 t) :test #'equal)) (when *use-sim-time* (setq *last-clock* nil) (subscribe "/clock" "rosgraph_msgs/Clock" #'(lambda (m) (setq *last-clock* m)) :max-queue-length 5)) ;; Advertise reset-debug-levels service (register-service-fn "~reset_debug_levels" #'reset-debug-levels 'Empty) (ros-info (roslisp top) "Node startup complete"))) (defmacro with-ros-node (args &rest body) "with-ros-node ARGS &rest BODY. Call start-ros-node with argument list ARGS, then execute the body. Takes care of shutting down the ROS node if the body terminates or is interrupted. In addition to the start-ros-node arguments, ARGS may also include the boolean argument :spin. If this is true, after body is executed, the node will just spin forever. Assuming spin is not true, this call will return the return value of the final statement of body." (dbind (name &rest a &key spin &allow-other-keys) args (declare (ignorable name a)) `(let (*namespace*) ;; Set up a binding so that start-ros-node can set it and this will be seen in the body, but not by our caller (unwind-protect (restart-case (progn (start-ros-node ,@args) ,@body ,@(when spin `((spin-until nil 100)))) (shutdown-ros-node (&optional a) (ros-info (roslisp top) "About to shutdown~:[~; due to condition ~:*~a~]" a))) (shutdown-ros-node))))) (defun shutdown-ros-node () "Shutdown-ros-node. Set the status to shutdown, close all open sockets and XML-RPC servers, and unregister all publications, subscriptions, and services with master node. Finally, if *running-from-command-line* is true, exit lisp." (ros-debug (roslisp top) "Acquiring lock") (with-recursive-lock (*ros-lock*) (unless (eq *node-status* :shutdown) (ros-debug (roslisp top) "Initiating shutdown") (setf *node-status* :shutdown) (handler-case (stop-server *xml-server*) (error (c) (cerror "Continue" "Error stopping xml-rpc server: ~a" c))) (close-socket *tcp-server*) ;; Unregister from publications and subscriptions and close the sockets and kill callback and deserialization threads (do-hash (topic pub *publications*) (protected-call-to-master ("unregisterPublisher" topic *xml-rpc-caller-api*) c (ros-warn (roslisp) "Could not contact master at ~a when unregistering as publisher of ~a during shutdown: ~a" *master-uri* topic c)) (dolist (sub (subscriber-connections pub)) (handler-case (close-socket (subscriber-socket sub)) (sb-int:simple-stream-error (c) (ros-debug (roslisp top) "Received stream error ~a when attempting to close socket ~a. Skipping." c (subscriber-socket sub)))))) (do-hash (topic sub *subscriptions*) (protected-call-to-master ("unregisterSubscriber" topic *xml-rpc-caller-api*) c (ros-warn (roslisp) "Could not contact master when unsubscribing from ~a during shutdown: ~a" topic c)) (handler-case (terminate-thread (topic-thread sub)) (interrupt-thread-error (e) (declare (ignore e))))) (dolist (thread *deserialization-threads*) (ros-debug (roslisp deserialization-thread) "Killing deserialization thread") (ignore-errors (terminate-thread thread))) ;; Unregister services (do-hash (name s *services*) (let ((i (protected-call-to-master ("unregisterService" name *service-uri*) c (ros-warn roslisp "During shutdown, unable to contact master to unregister service ~a: ~a" name c) 1))) (unless (eql i 1) (ros-warn (roslisp top) "When trying to close service ~a, ~a services were closed instead of 1" name i)))) ;; Unset variables that will be used upon next startup (setq *ros-log-location* nil) ;; wait nicely for end of event loop, which was notified by setting *node-status* to shutdown (dotimes (wait-it 6) (when (sb-thread:thread-alive-p *event-loop-thread*) (sleep 0.5))) (when (sb-thread:thread-alive-p *event-loop-thread*) ;; try killing event-loop thread (may take time) (sb-thread:terminate-thread *event-loop-thread*) (dotimes (wait-it 6) (when (sb-thread:thread-alive-p *event-loop-thread*) (sleep 0.5)))) (when (sb-thread:thread-alive-p *event-loop-thread*) (error "Event-loop thread cannot be terminated")) (setf *event-loop-thread* nil) (ros-info (roslisp top) "Shutdown complete") (close *ros-log-stream*) (when *running-from-command-line* (sb-ext:exit))))) (defun maybe-shutdown-ros-node () (unless (eq *node-status* :shutdown) (shutdown-ros-node)))
0
apollo_public_repos/apollo-platform/ros/roslisp
apollo_public_repos/apollo-platform/ros/roslisp/src/tcpros.lisp
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Software License Agreement (BSD License) ;; ;; Copyright (c) 2008, Willow Garage, Inc. ;; All rights reserved. ;; ;; Redistribution and use in source and binary forms, with ;; or without modification, are permitted provided that the ;; following conditions are met: ;; ;; * Redistributions of source code must retain the above ;; copyright notice, this list of conditions and the ;; following disclaimer. ;; * Redistributions in binary form must reproduce the ;; above copyright notice, this list of conditions and ;; the following disclaimer in the documentation and/or ;; other materials provided with the distribution. ;; * Neither the name of Willow Garage, Inc. nor the names ;; of its contributors may be used to endorse or promote ;; products derived from this software without specific ;; prior written permission. ;; ;; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND ;; CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED ;; WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED ;; WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A ;; PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE ;; COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, ;; INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR ;; CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, ;; PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ;; DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ;; CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN ;; CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE ;; OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS ;; SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH ;; DAMAGE. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (in-package :roslisp) (defparameter *tcp-timeout* 5.0 "How many seconds to wait until giving up") ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Utility ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro bind-from-header (bindings header &body body) "Simplify binding a bunch of fields from a header and signaling a condition if there's a problem" (let ((h (gensym))) `(let ((,h ,header)) (let ,(mapcar #'(lambda (binding) (list (first binding) `(lookup-alist ,h ,(second binding)))) bindings) ,@body)))) (define-condition malformed-tcpros-header (error) ((msg :accessor msg :initarg :msg))) (defun tcpros-header-assert (condition str &rest args) (unless condition (error 'malformed-tcpros-header :msg (apply #'format nil str args)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; ROS Node connection server ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun ros-node-tcp-server (port) "Return a passive socket that listens for connections on the given port. The handler for incoming connections is (the function returned by) server-connection-handler." (let ((socket (make-instance 'inet-socket :type :stream :protocol :tcp)) (ip-address #(0 0 0 0))) (setf (sb-bsd-sockets:sockopt-reuse-address socket) t) (socket-bind socket ip-address port) (ros-debug (roslisp tcp) "Bound tcp listener ~a" socket) (socket-listen socket 5) (sb-sys:add-fd-handler (socket-file-descriptor socket) :input (server-connection-handler socket)) socket)) (defun server-connection-handler (socket) "Return the handler for incoming connections to this socket. The handler accepts the connection, and decides whether its a topic or service depending on whether the header has a topic field, and passes it to handle-topic-connection or handle-service connection as appropriate. If the header cannot be parsed or lacks the necessary fields, send an error header across the socket, close it, and print a warning message on this side." #'(lambda (fd) (declare (ignore fd)) (let* ((connection (socket-accept socket)) (stream (socket-make-stream connection :element-type '(unsigned-byte 8) :output t :input t :buffering :none))) (flet ((close-connection (&key (abort t)) "Closes the connection when an error occurred." ;; We first close the stream with the abort parameter ;; since SOCKET-CLOSE does not allow to specify ;; abort. This function is ment to be used in error ;; handling since SOCKET-CLOSE currently has a nasty ;; bug that prevents it from closing broken ;; connections. (close stream :abort abort) (socket-close connection))) (ros-debug (roslisp tcp) "Accepted TCP connection ~a" connection) (mvbind (header parse-error) (ignore-errors (parse-tcpros-header stream)) ;; Any errors guaranteed to be handled in the first cond clause (ros-debug (roslisp tcp) "Parsed header: ~a ~:[~;Parse error ~:*~a~]" header parse-error) (handler-case (cond ((null header) (ros-info (roslisp tcp) "Ignoring connection attempt due to error parsing header: '~a'" parse-error) (socket-close connection)) ((assoc "service" header :test #'equal) (handle-service-connection header connection stream)) ((equal (cdr (assoc "probe" header :test #'equal)) "1") (ros-warn roslisp "Unexpectedly received a tcpros connection with probe set to 1. Closing connection.") (socket-close connection)) ((assoc "topic" header :test #'equal) (handle-topic-connection header connection stream)) ) (malformed-tcpros-header (c) (send-tcpros-header stream "error" (msg c)) (warn "Connection server received error ~a when trying to parse header ~a. Ignoring this connection attempt." (msg c) header) (close-connection)) (stream-error (c) (declare (ignore c)) (ros-debug (roslisp tcp) "stream error on connection to service client (could be a probe)") (close-connection)))))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Topics ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun handle-topic-connection (header connection stream) "Handle topic connection by checking md5 sum, sending back a response header, then adding this socket to the publication list for this topic. If the connection comes from this caller no response needs to be send." (bind-from-header ((topic "topic") (md5 "md5sum") (uri "callerid")) header (let ((pub (gethash topic *publications*))) (tcpros-header-assert pub "unknown-topic") (let ((my-md5 (md5sum topic)) (caller-id (caller-id))) (tcpros-header-assert (or (equal md5 "*") (equal md5 my-md5)) "md5sums do not match for ~a: ~a vs ~a" topic md5 my-md5) ;; Send a response if you didn't subscribed to yourself (unless (equal uri caller-id) (send-tcpros-header stream "type" (ros-datatype topic) "callerid" caller-id "message_definition" (message-definition topic) "latching" (if (is-latching pub) "1" "0") "md5sum" my-md5))) ;; Add this subscription to the list for the topic (let ((sub (make-subscriber-connection :subscriber-socket connection :subscriber-stream stream :subscriber-uri uri))) (ros-debug (roslisp tcp) "~&Adding ~a to ~a for topic ~a" sub pub topic) (push sub (subscriber-connections pub)) (when (and (is-latching pub) (last-message pub)) (ros-debug (roslisp tcp) "~&Resending latched message to new subscriber") (tcpros-write (last-message pub) stream)))))) (defparameter *setup-tcpros-subscription-max-retry* 3) (defun setup-tcpros-subscription (hostname port topic) "Connect to the publisher at the given address and do the header exchange, then start a thread that will deserialize messages onto the queue for this topic." (check-type hostname string) (mvbind (stream connection) (tcp-connect hostname port) (ros-debug (roslisp tcp) "~&Successfully connected to ~a:~a for topic ~a" hostname port topic) ;; Check if we try to subscribe to our own publisher (if (and (equal hostname *tcp-server-hostname*) (equal port *tcp-server-port*)) (setup-tcpros-subscription-to-self hostname port topic connection stream) (setup-tcpros-subscription-to-strangers hostname port topic connection stream)) (values stream connection))) (defun setup-tcpros-subscription-to-self (hostname port topic connection stream) "Helper function for setting up a tcpros-subscription with a publisher that uses the same tcp-server." (mvbind (sub known) (gethash topic *subscriptions*) (assert known nil "Topic ~a unknown. This error should have been caught earlier!" topic) (send-tcpros-header stream "topic" topic "md5sum" (md5sum topic) "type" (ros-datatype topic) "callerid" (caller-id)) ;; Spawn a dedicated thread to deserialize messages off the socket onto the queue (spawn-connection-thread hostname port topic stream connection (buffer sub)))) (defun setup-tcpros-subscription-to-strangers (hostname port topic connection stream) "Helper function for setting up a tcpros-subscriptions with a publisher that doesn't uses this tcp-server." (dotimes (retry-count *setup-tcpros-subscription-max-retry* (error 'simple-error :format-control "Timeout when trying to communicate with publisher ~a:~a for topic ~a, check publisher node status. Change *tcp-timeout* to increase wait-time." :format-arguments (list hostname port topic))) (when (> retry-count 0) (ros-warn (roslisp tcpros) "Failed to communicate with publisher ~a:~a for topic ~a, retrying: ~a" hostname port topic retry-count)) (handler-case (mvbind (sub known) (gethash topic *subscriptions*) (assert known nil "Topic ~a unknown. This error should have been caught earlier!" topic) ;; Send header and receive response (send-tcpros-header stream "topic" topic "md5sum" (md5sum topic) "type" (ros-datatype topic) "callerid" (caller-id)) (let ((response (with-function-timeout *tcp-timeout* (lambda () (parse-tcpros-header stream))))) (when (assoc "error" response :test #'equal) (roslisp-error "During TCPROS handshake, publisher sent error message ~a" (cdr (assoc "error" response :test #'equal)))) ;; TODO need to do something with the response, handle AnyMsg (see tcpros.py) ;; Spawn a dedicated thread to deserialize messages off the socket onto the queue (spawn-connection-thread hostname port topic stream connection (buffer sub))) ;; If nothing failed return from dotimes (return)) (malformed-tcpros-header (c) (send-tcpros-header stream "error" (msg c)) (socket-close connection) (error c)) (function-timeout () ;;just retry nil)))) (defun spawn-connection-thread (hostname port topic stream connection buffer) "Spawns a dedicated thread to deserialize messages off the socket onto the queue and adds it to the deserialization-threads." (let ((connection-thread (sb-thread:make-thread #'(lambda () (block thread-block (unwind-protect (handler-bind ((error #'(lambda (c) (unless *break-on-socket-errors* (ros-debug (roslisp tcp) "Received error ~a when reading connection to ~a:~a on topic ~a. Connection terminated." c hostname port topic) (return-from thread-block nil))))) (loop (unless (eq *node-status* :running) (error "Node status is ~a" *node-status*)) ;; Read length (ignored) (dotimes (i 4) (read-byte stream)) (let ((msg (deserialize (get-topic-class-name topic) stream))) (let ((num-dropped (enqueue msg buffer))) (ros-debug (roslisp tcp) (> num-dropped 0) "Dropped ~a messages on topic ~a" num-dropped topic))))) ;; Always close the connection before leaving the thread (socket-close connection)))) :name (format nil "Roslisp thread for subscription to topic ~a published from ~a:~a" topic hostname port)))) (assert (eq (mutex-owner *ros-lock*) *current-thread*) nil "Code assumption violated; not holding lock in setup-tcpros-subscription") (ros-debug (roslisp deserialization-thread) "Adding deserialization thread for connection on topic ~a to ~a:~a" topic hostname port) (push connection-thread *deserialization-threads*))) (defvar *stream-error-in-progress* nil) (defun tcpros-write (msg str) (or (unless (gethash str *broken-socket-streams*) (handler-case ;; We need to serialize the data first to a string stream and ;; then send the whole string at once over the socket. We ;; also need to prevent the send operation from ;; interrupts. Otherwise, when messages do not get sent ;; completely, we run out of sync and the connection to the ;; client will be lost. (let* ((msg-size (serialization-length msg)) (data-strm (make-instance 'msg-serialization-stream :buffer-size (+ msg-size 4)))) (serialize-int msg-size data-strm) (serialize msg data-strm) (sb-sys:without-interrupts (write-sequence (serialized-message data-strm) str :end (file-position data-strm)) ;; Technically, force-output isn't supposed to be called on binary streams... (force-output str) 1 ;; Returns number of messages written )) ((or sb-bsd-sockets:socket-error stream-error) (c) (unless *stream-error-in-progress* (let ((*stream-error-in-progress* t)) (ros-debug (roslisp tcp) "Received error ~a when writing to ~a. Skipping from now on." c str))) (setf (gethash str *broken-socket-streams*) t) 0))) 0)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Services ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun handle-service-connection (header connection stream) "Handle service connection. For now, we assume a single request, which is processed immediately in this thread." (bind-from-header ((md5 "md5sum") (service-name "service")) header (let* ((service (gethash service-name *services*)) (is-probe (equal (cdr (assoc "probe" header :test #'equal)) "1"))) (tcpros-header-assert service "Unknown service") (let ((my-md5 (string-downcase (service-md5 service)))) (tcpros-header-assert (or (equal md5 "*") (equal md5 my-md5)) "md5 sums don't match for ~a: ~a vs ~a" service-name md5 my-md5) (send-tcpros-header stream "md5sum" my-md5 "callerid" (caller-id) "type" (service-ros-type service) "request_type" (service-request-ros-type service) "response_type" (service-response-ros-type service))) (unwind-protect (unless is-probe (handle-single-service-request stream (service-request-class service) (service-callback service))) (sb-thread:make-thread #'(lambda () (sleep 10.0) (ros-debug (roslisp service) "In service connection cleanup") (when (socket-open-p connection) (ros-debug (roslisp service) "Connection for call to ~a still open after 10 seconds; closing" service-name) (socket-close connection)))))))) (define-condition service-error (simple-error) ()) (defun handle-single-service-request (stream request-class-name callback) ;; Read length (dotimes (i 4) (read-byte stream)) (flet ((write-service-error (msg) (assert (stringp msg)) (write-byte 0 stream) (serialize-string msg stream) (finish-output stream))) (let ((msg (deserialize request-class-name stream))) (ros-debug (roslisp service tcp) "Deserialized service request of type ~a" request-class-name) (handler-case (let ((response (funcall callback msg))) (ros-debug (roslisp service tcp) "Callback returned") (write-byte 1 stream) (serialize-int (serialization-length response) stream) (ros-debug (roslisp service tcp) "Wrote response length ~a" (serialization-length response)) (serialize response stream) (ros-debug (roslisp service tcp) "Wrote response; flushing stream.") (finish-output stream) (ros-debug (roslisp service tcp) "Finished handling service request")) (service-error (e) (let ((msg (apply #'format nil (simple-condition-format-control e) (simple-condition-format-arguments e)))) (ros-debug (roslisp service tcp) "Service-error during request ~a:~% ~a" e msg) (write-service-error (concatenate 'string "service cannot process request: " msg)))) (error (e) (let ((msg (format nil "~a" e))) (ros-error (roslisp service tcp) "Error processing request ~a:~% ~a" e msg) (write-service-error (concatenate 'string "error processing request: " msg)))))))) (defun tcpros-establish-service-connection (hostname port service-name request-class &optional (persistent nil)) (check-type hostname string) (multiple-value-bind (stream socket) (tcp-connect hostname port) (handler-bind ((error (lambda (e) (declare (ignore e)) (socket-close socket)))) (send-tcpros-header stream "service" service-name "md5sum" (md5sum request-class) "callerid" (caller-id) "persistent" (if persistent "1" "0"))) (values stream socket (with-function-timeout *tcp-timeout* (lambda () (parse-tcpros-header stream)))))) (define-condition service-call-error (error) ((message :initarg :message :reader service-call-error-message))) (defun tcpros-do-service-request (stream request response-type) ;; Clear the input stream. In case the service call uses a ;; persistent service and the service call got interrupted after the ;; request has been sent, it can happen that the result is still in ;; the stream. Get rid of all old results before sending another ;; request. (clear-input stream) (tcpros-write request stream) (let ((ok-byte (read-byte stream nil))) (unless (eq ok-byte 1) (error 'service-call-error :message (handler-case (deserialize-string stream) ;; TODO(lorenz): don't catch all errors. (error nil)))) (let ((len (deserialize-int stream))) (declare (ignore len)) (prog1 (deserialize response-type stream) (assert (not (listen stream)) () "Still bytes in the stream. It seems like we went out of sync."))))) (defun tcpros-call-service (hostname port service-name req response-type) (check-type hostname string) (dotimes (retry-count *setup-tcpros-subscription-max-retry* (error 'simple-error :format-control "Timeout when trying to communicate with ~a:~a for service ~a, check service node status. Change *tcp-timeout* to increase wait-time." :format-arguments (list hostname port service-name))) (when (> retry-count 0) (ros-warn (roslisp tcpros) "Failed to communicate with ~a:~a for service-name ~a, retrying: ~a" hostname port service-name retry-count)) (handler-case (return (multiple-value-bind (str socket) (tcpros-establish-service-connection hostname port service-name (class-name (class-of req))) (unwind-protect (handler-case (tcpros-do-service-request str req response-type) (service-call-error (e) (if (service-call-error-message e) (roslisp-error "service-call to ~a:~a with request ~a failed with message: ~a" hostname port req (service-call-error-message e)) (roslisp-error "service-call to ~a:~a with request ~a failed." hostname port req)))) (socket-close socket)))) (function-timeout () ;;just retry nil)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Internal ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun caller-id () "The callerid field of any tcpros header used by a node" (fully-qualified-name *ros-node-name*)) (defun send-tcpros-header (str &rest args) (assert (evenp (length args)) nil "send-tcpros-header received odd number of arguments ~a" args) (let ((l args) (key-value-pairs nil) (total-length 0)) (while l (let ((next-pair (format nil "~a=~a" (pop l) (pop l)))) (incf total-length (+ 4 (length next-pair))) ;; 4 for the 4-byte length at the beginning (push next-pair key-value-pairs))) (ros-debug (roslisp tcp header) "Sending tcpros header ~a" key-value-pairs) (serialize-int total-length str) (dolist (pair key-value-pairs) (serialize-string pair str))) (force-output str)) (defun parse-tcpros-header (str) (let ((remaining-length (deserialize-int str)) (key-value-pairs nil)) (while (> remaining-length 0) (let ((field-string (deserialize-string str))) (decf remaining-length (+ 4 (length field-string))) ;; 4 for the length at the beginning (unless(>= remaining-length 0) (roslisp-error "Error parsing tcpros header: header length and field lengths didn't match")) (push (parse-header-field field-string) key-value-pairs) )) (ros-debug (roslisp tcp header) "Received tcpros header ~a" key-value-pairs) key-value-pairs)) (defun parse-header-field (field-string) (let ((first-equal-sign-pos (position #\= field-string))) (if first-equal-sign-pos (cons (subseq field-string 0 first-equal-sign-pos) (subseq field-string (1+ first-equal-sign-pos))) (roslisp-error "Error parsing tcpros header field ~a: did not contain an '='" field-string)))) (defun lookup-alist (l key) (let ((pair (assoc key l :test #'equal))) (unless pair (error 'malformed-tcpros-header :msg (format nil "Could not find key ~a in ~a" key l))) (cdr pair)))
0
apollo_public_repos/apollo-platform/ros/roslisp
apollo_public_repos/apollo-platform/ros/roslisp/src/master.lisp
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Software License Agreement (BSD License) ;; ;; Copyright (c) 2008, Willow Garage, Inc. ;; All rights reserved. ;; ;; Redistribution and use in source and binary forms, with ;; or without modification, are permitted provided that the ;; following conditions are met: ;; ;; * Redistributions of source code must retain the above ;; copyright notice, this list of conditions and the ;; following disclaimer. ;; * Redistributions in binary form must reproduce the ;; above copyright notice, this list of conditions and ;; the following disclaimer in the documentation and/or ;; other materials provided with the distribution. ;; * Neither the name of Willow Garage, Inc. nor the names ;; of its contributors may be used to endorse or promote ;; products derived from this software without specific ;; prior written permission. ;; ;; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND ;; CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED ;; WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED ;; WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A ;; PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE ;; COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, ;; INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR ;; CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, ;; PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ;; DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ;; CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN ;; CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE ;; OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS ;; SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH ;; DAMAGE. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (in-package :roslisp) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Code for talking to the master over xml rpc ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (define-condition ros-rpc-error () ;; TODO ((code :initarg :code :reader code) (message :initarg :message :reader message) (vals :initarg :vals :reader vals) (call :initarg :call :reader call) (uri :initarg :uri :reader rpc-uri)) (:report (lambda (c str) (format str "ros-rpc call ~a to ~a failed with code ~a, message ~a, values ~a" (call c) (rpc-uri c) (code c) (message c) (vals c))))) (defun lookup-service (name) (ros-rpc-call *master-uri* "lookupService" name)) (defun ros-rpc-call (uri name &rest args) "ros-rpc-call XML-RPC-SERVER-URI CALL-NAME &rest CALL-ARGS. Preprends the ros node name to the arg list and does the call. Throws a continuable error if a code <= 0 is returned. Otherwise, return the values. Requires that uri is not null (though node need not be running)." (mvbind (address port) (parse-uri uri) (dbind (code msg vals) (xml-rpc-call (apply #'encode-xml-rpc-call name (or *ros-node-name* "uninitialized-roslisp-node") args) :host address :port port) (when (<= code 0) (cerror "Ignore and continue" 'ros-rpc-error :call (cons name args) :uri uri :code code :message msg :vals vals)) vals))) (defmacro protected-call-to-master ((&rest args) &optional c &body cleanup-forms) "Wraps an xml-rpc call to the master. Calls cleanup forms if xml-rpc connection fails. Requires that the node is running, or that the *master-uri* is set." (setf c (or c (gensym))) `(handler-case (let ((args (list ,@args))) (assert *master-uri* nil "Master uri not set") (ros-debug (roslisp master) "Calling master with arguments `~a'" args) (apply #'ros-rpc-call *master-uri* args)) (sb-bsd-sockets:connection-refused-error (,c) (declare (ignorable ,c)) ,@cleanup-forms)))
0
apollo_public_repos/apollo-platform/ros/roslisp
apollo_public_repos/apollo-platform/ros/roslisp/src/pprint.lisp
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Software License Agreement (BSD License) ;; ;; Copyright (c) 2008, Willow Garage, Inc. ;; All rights reserved. ;; ;; Redistribution and use in source and binary forms, with ;; or without modification, are permitted provided that the ;; following conditions are met: ;; ;; * Redistributions of source code must retain the above ;; copyright notice, this list of conditions and the ;; following disclaimer. ;; * Redistributions in binary form must reproduce the ;; above copyright notice, this list of conditions and ;; the following disclaimer in the documentation and/or ;; other materials provided with the distribution. ;; * Neither the name of Willow Garage, Inc. nor the names ;; of its contributors may be used to endorse or promote ;; products derived from this software without specific ;; prior written permission. ;; ;; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND ;; CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED ;; WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED ;; WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A ;; PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE ;; COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, ;; INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR ;; CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, ;; PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ;; DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ;; CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN ;; CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE ;; OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS ;; SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH ;; DAMAGE. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (in-package :roslisp) (defun pprint-ros-message (&rest args &aux str m) (if (= (length args) 1) (setf str t m (first args)) (setf str (first args) m (second args))) (pprint-logical-block (str nil :prefix "[" :suffix "]") (let ((l (ros-message-to-list m))) (write (first l) :stream str) (dolist (f (rest l)) (format str "~:@_ ~a:~:@_ ~w" (car f) (ros-message-to-list (cdr f)))))) ) (set-pprint-dispatch 'ros-message #'pprint-ros-message) (defun pprint-hash (&rest args) (bind-pprint-args (s h) args (etypecase h (roslisp-utils::gen-hash-table (pprint-hash s (roslisp-utils::gen-hash-table-table h))) (hash-table (pprint-logical-block (s (roslisp-utils::hash-keys h) :prefix "[" :suffix (let ((not-shown (if *print-length* (max 0 (- (hash-table-count h) *print-length*)) 0))) (if (> not-shown 0) (format nil " and ~R other item~:*~P not shown here.]" not-shown) "]"))) (when (> (roslisp-utils::hash-table-count* h) 0) (loop (let ((k (pprint-pop))) (format s "~a : ~a" k (gethash k h)) (pprint-exit-if-list-exhausted) (pprint-newline :mandatory s))))) (values))))) (defun print-debug-levels () (let ((h (make-hash-table))) (loop for k being each hash-key in *debug-levels* do (setf (gethash k h) (string-upcase (debug-level-string (gethash k *debug-levels*))))) (pprint-hash h)))
0
apollo_public_repos/apollo-platform/ros/roslisp
apollo_public_repos/apollo-platform/ros/roslisp/src/persistent-service.lisp
;;; Copyright (c) 2012, Lorenz Moesenlechner <[email protected]> ;;; 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 Intelligent Autonomous Systems Group/ ;;; Technische Universitaet Muenchen nor the names of its contributors ;;; may be used to endorse or promote products derived from this software ;;; without specific prior written permission. ;;; ;;; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" ;;; AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ;;; IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ;;; ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE ;;; LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR ;;; CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF ;;; SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS ;;; INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN ;;; CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ;;; ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE ;;; POSSIBILITY OF SUCH DAMAGE. (in-package :roslisp) (defclass persistent-service () ((stream :reader persistent-service-stream) (socket :reader persistent-service-socket) (request-type :reader persistent-service-request-type) (response-type :reader persistent-service-response-type) (service-name :initarg :service-name) (service-type :initarg :service-type) (lock :reader persistent-service-lock :initform (sb-thread:make-mutex :name (symbol-name (gensym "PERSISTENT-SERVICE-LOCK")))))) (defgeneric call-persistent-service (service &rest request) (:method ((service persistent-service) &rest request) (with-slots (stream socket request-type response-type lock) service (block nil (loop do (restart-case (sb-thread:with-mutex (lock) (cond ((and (eql (length request) 1) (typep (car request) request-type)) (return (tcpros-do-service-request stream (car request) response-type))) (t (return (tcpros-do-service-request stream (apply #'make-instance request-type request) response-type))))) (reconnect () :report "Try reconnecting persistent service and execute the call again." (close-persistent-service service) (establish-persistent-service-connection service)))))))) (defgeneric close-persistent-service (persistent-service) (:method ((service persistent-service)) (close (persistent-service-stream service) :abort t))) (defgeneric persistent-service-ok (persistent-service) (:documentation "Returns T if the service is still ok, i.e. can be called, NIL otherwise.") (:method ((service persistent-service)) (with-slots (socket) service (and socket (socket-open-p socket))))) (defgeneric establish-persistent-service-connection (service) (:method ((service persistent-service)) (with-slots (service-name service-type stream socket request-type response-type) service (let* ((service-type (etypecase service-type (symbol service-type) (string (make-service-symbol service-type))))) (with-fully-qualified-name service-name (multiple-value-bind (host port) (parse-rosrpc-uri (lookup-service service-name)) (multiple-value-bind (service-stream service-socket) (tcpros-establish-service-connection host port service-name (service-request-type service-type) t) (setf stream service-stream) (setf socket service-socket) (setf request-type (service-request-type service-type)) (setf response-type (service-response-type service-type))))))))) (defmethod initialize-instance :after ((service persistent-service) &key) (establish-persistent-service-connection service))
0
apollo_public_repos/apollo-platform/ros/roslisp
apollo_public_repos/apollo-platform/ros/roslisp/src/debug-levels.lisp
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Software License Agreement (BSD License) ;; ;; Copyright (c) 2008, Willow Garage, Inc. ;; All rights reserved. ;; ;; Redistribution and use in source and binary forms, with ;; or without modification, are permitted provided that the ;; following conditions are met: ;; ;; * Redistributions of source code must retain the above ;; copyright notice, this list of conditions and the ;; following disclaimer. ;; * Redistributions in binary form must reproduce the ;; above copyright notice, this list of conditions and ;; the following disclaimer in the documentation and/or ;; other materials provided with the distribution. ;; * Neither the name of Willow Garage, Inc. nor the names ;; of its contributors may be used to endorse or promote ;; products derived from this software without specific ;; prior written permission. ;; ;; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND ;; CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED ;; WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED ;; WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A ;; PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE ;; COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, ;; INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR ;; CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, ;; PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ;; DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ;; CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN ;; CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE ;; OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS ;; SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH ;; DAMAGE. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (in-package :roslisp) ;; We hash from lists to numbers. Could make more efficient using a tree of hashtables instead. (defvar *debug-levels* (make-hash-table :test #'equal)) (defun debug-level-exists (l) (hash-table-has-key *debug-levels* (mapcar #'make-keyword-symbol (reverse l)))) (defun debug-level (name) (or (gethash name *debug-levels*) (if name (debug-level (cdr name)) (level-code :info)))) (defun debug-topic-param (name) (concatenate-ros-names (cons "~debug" (nconc (mapcar #'string-downcase (designated-list name)) (list "level"))))) (defgeneric debug-level-string (level) (:method ((level symbol)) (string-downcase (symbol-name level))) (:method ((level fixnum)) (debug-level-string (car (rassoc level (symbol-codes 'rosgraph_msgs-msg:<Log>)))))) (defgeneric level-code (level) (:method ((level fixnum)) level) (:method ((level symbol)) (symbol-code 'rosgraph_msgs-msg:<Log> level)) (:method ((level string)) (level-code (find-symbol level :keyword)))) (defun set-local-debug-level (topic level &optional (h *debug-levels*)) (ros-debug (roslisp rosout) "Locally setting debug level of ~a to ~a" topic level) (let ((debug-topic (mapcar #'make-keyword-symbol (reverse topic)))) (setf (gethash debug-topic h) (level-code level)))) (defun set-debug-level (name level) (set-local-debug-level (designated-list name) level *debug-levels*) (when (eq *node-status* :running) (ros-debug (roslisp rosout) "Setting ros parameter for debug level of ~a to ~a" (designated-list name) level) (set-param (debug-topic-param name) (debug-level-string level))) ) (defun set-debug-level-unless-exists (name level) (unless (debug-level-exists name) (set-debug-level name level))) (defmacro set-debug-levels (&rest args) "set-debug-level NAME1 LEVEL1 ... NAMEk LEVELk Each NAME (unevaluated) is a list, e.g. (roslisp tcp) denoting a debugger topic. LEVEL is one of the keyword symbols :debug, :info, :warn, :error, or :fatal." (labels ((helper (args) (when args `((set-debug-level ',(car args) ,(cadr args)) ,@(helper (cddr args)))))) `(progn ,@(helper args)))) (defun is-prefix (s1 s2) (when (<= (length s1) (length s2)) (search s1 s2 :end2 (length s1)))) (defun is-suffix (s1 s2) (let ((l1 (length s1)) (l2 (length s2))) (and (<= l1 l2) (search s1 s2 :start2 (- l2 l1))))) (defun is-debug-level-param (p) (and (is-prefix (fully-qualified-name "~debug") p) (is-suffix "/level" p))) (defun get-debug-topic (p) (let* ((prefix (fully-qualified-name "~debug")) (tokens (tokens p :start (length prefix) :separators '(#\/)))) (subseq tokens 0 (1- (length tokens))))) (def-service-callback (reset-debug-levels Empty) () (dolist (param (list-params "~debug")) (when (is-debug-level-param param) (let ((level (string-upcase (get-param param)))) (if (member level '("DEBUG" "INFO" "WARN" "ERROR" "FATAL") :test #'equal) (set-local-debug-level (get-debug-topic param) level) (ros-warn (roslisp rosout) "Skipping setting debug level of ~a to unknown level ~a" param level))))) (make-response))
0
apollo_public_repos/apollo-platform/ros/roslisp
apollo_public_repos/apollo-platform/ros/roslisp/src/rosout.lisp
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Software License Agreement (BSD License) ;; ;; Copyright (c) 2008, Willow Garage, Inc. ;; All rights reserved. ;; ;; Redistribution and use in source and binary forms, with ;; or without modification, are permitted provided that the ;; following conditions are met: ;; ;; * Redistributions of source code must retain the above ;; copyright notice, this list of conditions and the ;; following disclaimer. ;; * Redistributions in binary form must reproduce the ;; above copyright notice, this list of conditions and ;; the following disclaimer in the documentation and/or ;; other materials provided with the distribution. ;; * Neither the name of Willow Garage, Inc. nor the names ;; of its contributors may be used to endorse or promote ;; products derived from this software without specific ;; prior written permission. ;; ;; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND ;; CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED ;; WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED ;; WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A ;; PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE ;; COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, ;; INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR ;; CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, ;; PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ;; DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ;; CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN ;; CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE ;; OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS ;; SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH ;; DAMAGE. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (in-package :roslisp) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Called by user ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro ros-debug (name &rest args) "ros-debug NAME [CONDITION] FORMAT-STRING . ARGS When CONDITION is true, and the debug level of debug topic NAME is at least :debug, output the given format string and arguments to stdout and publish on rosout if possible. Otherwise do nothing; in particular, don't evaluate the ARGS. CONDITION can be omitted if the FORMAT-STRING is a literal string, in which case it defaults to t." (rosout-msg name :debug args)) (defmacro ros-info (name &rest args) "ros-info NAME [CONDITION] FORMAT-STRING . ARGS When CONDITION is true, and the debug level of debug topic NAME is at least :info, output the given format string and arguments to stdout and publish on rosout if possible. Otherwise do nothing; in particular, don't evaluate the ARGS. CONDITION can be omitted if the FORMAT-STRING is a literal string, in which case it defaults to t." (rosout-msg name :info args)) (defmacro ros-warn (name &rest args) "ros-warn NAME [CONDITION] FORMAT-STRING . ARGS When CONDITION is true, and the debug level of debug topic NAME is at least :warn, output the given format string and arguments to stdout and publish on rosout if possible. Otherwise do nothing; in particular, don't evaluate the ARGS. CONDITION can be omitted if the FORMAT-STRING is a literal string, in which case it defaults to t." (rosout-msg name :warn args)) (defmacro ros-error (name &rest args) "ros-error NAME [CONDITION] FORMAT-STRING . ARGS When CONDITION is true, and the debug level of debug topic NAME is at least :error, output the given format string and arguments to stdout and publish on rosout if possible. Otherwise do nothing; in particular, don't evaluate the ARGS. CONDITION can be omitted if the FORMAT-STRING is a literal string, in which case it defaults to t." (rosout-msg name :error args)) (defmacro ros-fatal (name &rest args) "ros-fatal NAME [CONDITION] FORMAT-STRING . ARGS When CONDITION is true, and the debug level of debug topic NAME is at least :fatal, output the given format string and arguments to stdout and publish on rosout if possible. Otherwise do nothing; in particular, don't evaluate the ARGS. CONDITION can be omitted if the FORMAT-STRING is a literal string, in which case it defaults to t." (rosout-msg name :fatal args)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Some standard errors that can be declared now that ;; the macros are defined ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmethod serialization-length ((msg t)) (ros-error roslisp "Hmm... unexpectedly asked for serialization length of ~w. Most likely because the aforementioned object was found some place where a (nonprimitive) ros message was expected." msg) 42)
0
apollo_public_repos/apollo-platform/ros/roslisp
apollo_public_repos/apollo-platform/ros/roslisp/src/msg-serialization-stream.lisp
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Software License Agreement (BSD License) ;; ;; Copyright (c) 2008, Willow Garage, Inc. ;; All rights reserved. ;; ;; Redistribution and use in source and binary forms, with ;; or without modification, are permitted provided that the ;; following conditions are met: ;; ;; * Redistributions of source code must retain the above ;; copyright notice, this list of conditions and the ;; following disclaimer. ;; * Redistributions in binary form must reproduce the ;; above copyright notice, this list of conditions and ;; the following disclaimer in the documentation and/or ;; other materials provided with the distribution. ;; * Neither the name of Willow Garage, Inc. nor the names ;; of its contributors may be used to endorse or promote ;; products derived from this software without specific ;; prior written permission. ;; ;; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND ;; CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED ;; WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED ;; WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A ;; PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE ;; COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, ;; INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR ;; CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, ;; PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ;; DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ;; CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN ;; CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE ;; OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS ;; SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH ;; DAMAGE. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (in-package :roslisp) (defclass msg-serialization-stream (sb-gray:fundamental-binary-output-stream) ((data-buffer :reader serialized-message) (position :initform 0))) (defmethod initialize-instance :after ((strm msg-serialization-stream) &key buffer-size) (assert buffer-size () "Parameter `buffer-size' not specified") (setf (slot-value strm 'data-buffer) (make-array buffer-size :element-type '(unsigned-byte 8)))) (defmethod stream-element-type ((strm msg-serialization-stream)) (array-element-type (serialized-message strm))) (defmethod sb-gray:stream-file-position ((strm msg-serialization-stream) &optional position) (if position (setf (slot-value strm 'position) position) (slot-value strm 'position))) (defmethod sb-gray:stream-write-byte ((strm msg-serialization-stream) integer) (declare (type (unsigned-byte 8) integer)) (with-slots (data-buffer position) strm (setf (aref data-buffer position) integer) (incf position)))
0
apollo_public_repos/apollo-platform/ros/roslisp
apollo_public_repos/apollo-platform/ros/roslisp/src/params.lisp
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Software License Agreement (BSD License) ;; ;; Copyright (c) 2008, Willow Garage, Inc. ;; All rights reserved. ;; ;; Redistribution and use in source and binary forms, with ;; or without modification, are permitted provided that the ;; following conditions are met: ;; ;; * Redistributions of source code must retain the above ;; copyright notice, this list of conditions and the ;; following disclaimer. ;; * Redistributions in binary form must reproduce the ;; above copyright notice, this list of conditions and ;; the following disclaimer in the documentation and/or ;; other materials provided with the distribution. ;; * Neither the name of Willow Garage, Inc. nor the names ;; of its contributors may be used to endorse or promote ;; products derived from this software without specific ;; prior written permission. ;; ;; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND ;; CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED ;; WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED ;; WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A ;; PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE ;; COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, ;; INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR ;; CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, ;; PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ;; DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ;; CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN ;; CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE ;; OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS ;; SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH ;; DAMAGE. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (in-package :roslisp) (defun get-param (key &optional (default nil default-supplied)) "get-param KEY &optional DEFAULT. KEY is a string naming a ros parameter. Looks up parameter on parameter server. If not found, use default if provided, and error otherwise." (declare (string key)) (with-fully-qualified-name key (if (has-param key) (protected-call-to-master ("getParam" key) c (roslisp-error "Could not contact master when getting param ~a: ~a" key c)) (if default-supplied default (roslisp-error "Param ~a does not exist, and no default supplied" key))))) (defun set-param (key val) "set-param KEY VAL KEY is a string naming a ros parameter. VAL is a string or integer. Post: parameter key set to value on the parameter server." (declare (string key)) (with-fully-qualified-name key (protected-call-to-master ("setParam" key val) c (roslisp-error "Could not contact master at ~a when setting param ~a" *master-uri* key)))) (defun has-param (key) "KEY is a string naming a ros parameter Return true iff this parameter exists on the server." (declare (string key)) (with-fully-qualified-name key (protected-call-to-master ("hasParam" key) c (roslisp-error "Could not contact master at ~a for call to hasParam ~a: ~a" *master-uri* key c)))) (defun delete-param (key) "KEY is a string naming a ros parameter Remove this key from parameter server." (declare (string key)) (with-fully-qualified-name key (protected-call-to-master ("deleteParam" key) c (roslisp-error "Could not contact master at ~a when deleting param ~a: ~a" *master-uri* key c)))) (defun get-param-names () "Return list of params on server" (protected-call-to-master ("getParamNames") c (roslisp-error "Could not contact master at ~a when getting param list: ~a" *master-uri* c))) (defun list-params (&optional namespace) "NAMESPACE is either a list of symbols (e.g. '(foo bar) refers to /foo/bar) or a string that is treated as a namespace name (possibly relative to the current one). Returns all parameters in that namespace." (declare (type (or string list) namespace)) (setq namespace (if (listp namespace) (format nil "~{/~a~}/" (mapcar #'(lambda (n) (string-downcase (symbol-name n))) namespace)) (let ((fqn (fully-qualified-name namespace))) (if (eql #\/ (char fqn (1- (length fqn)))) fqn (concatenate 'string fqn "/"))))) (filter #'(lambda (name) (search namespace name :end2 (min (length namespace) (length name)))) (get-param-names)))
0
apollo_public_repos/apollo-platform/ros/roslisp
apollo_public_repos/apollo-platform/ros/roslisp/src/command-line-args.lisp
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Software License Agreement (BSD License) ;; ;; Copyright (c) 2008, Willow Garage, Inc. ;; All rights reserved. ;; ;; Redistribution and use in source and binary forms, with ;; or without modification, are permitted provided that the ;; following conditions are met: ;; ;; * Redistributions of source code must retain the above ;; copyright notice, this list of conditions and the ;; following disclaimer. ;; * Redistributions in binary form must reproduce the ;; above copyright notice, this list of conditions and ;; the following disclaimer in the documentation and/or ;; other materials provided with the distribution. ;; * Neither the name of Willow Garage, Inc. nor the names ;; of its contributors may be used to endorse or promote ;; products derived from this software without specific ;; prior written permission. ;; ;; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND ;; CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED ;; WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED ;; WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A ;; PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE ;; COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, ;; INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR ;; CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, ;; PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ;; DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ;; CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN ;; CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE ;; OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS ;; SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH ;; DAMAGE. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (in-package :roslisp) (defun process-command-line-remappings (l base-name) "Process command line remappings, including the three special cases for remapping the node name, namespace, and setting parameters. Return alist of params to set. Note this is order dependent since setting __ns or __name affects how remappings are interpreted." (setf *remapped-names* (make-hash-table :test #'equal)) (let ((params nil)) (dolist (x l params) (dbind (lhs rhs) x (cond ((equal lhs "__ns") (setf *namespace* (postprocess-namespace rhs) *ros-node-name* (compute-node-name base-name))) ((equal lhs "__name") (setf base-name rhs *ros-node-name* (compute-node-name rhs))) ((equal lhs "__log") (setf *ros-log-location* rhs)) ((eql (char lhs 0) #\_) (push (cons (concatenate 'string "~" (subseq lhs 1)) (let ((rhs-val (read-from-string rhs))) (typecase rhs-val (symbol rhs) (otherwise rhs-val)))) params)) (t (setf (gethash (compute-global-name *namespace* *ros-node-name* lhs) *remapped-names*) (compute-global-name *namespace* *ros-node-name* rhs)))))))) (defun postprocess-namespace (ns) "Ensure that namespace begins and ends with /" (unless (eql (char ns 0) #\/) (setf ns (concatenate 'string "/" ns))) (unless (eql (char ns (1- (length ns))) #\/) (setf ns (concatenate 'string ns "/"))) ns) (defun compute-node-name (name) (concatenate 'string *namespace* (string-trim '(#\/) name))) (defun parse-remapping (string) "If string is of the form FOO:=BAR, return foo and bar, otherwise return nil." (let ((i (search ":=" string))) (when i (values (subseq string 0 i) (subseq string (+ i 2)))))) (defun handle-command-line-arguments (name args) "Postcondition: the variables *remapped-names*, *namespace*, and *ros-node-name* are set based on the argument list and the environment variable ROS_NAMESPACE as per the ros command line protocol. Also, arguments of the form _foo:=bar are interpreted by setting private parameter foo equal to bar (currently bar is just read using the lisp reader; it should eventually use yaml conventions)" (when (stringp args) (setq args (tokens args))) (setq *namespace* (postprocess-namespace (or (sb-ext:posix-getenv "ROS_NAMESPACE") "/")) *ros-node-name* (compute-node-name name)) (let ((remappings (mapcan #'(lambda (s) (mvbind (lhs rhs) (parse-remapping s) (when lhs (list (list lhs rhs))))) args))) (process-command-line-remappings remappings name))) (defun command-line-args-rosout (args params) "Separate function for debug out that's called after the debug levels are set" (ros-debug (roslisp top) "Command line arguments are ~a" args) (ros-info (roslisp top) "Node name is ~a" *ros-node-name*) (ros-info (roslisp top) "Namespace is ~a" *namespace*) (ros-info (roslisp top) "Params are ~a" params) (ros-info (roslisp top) "Remappings are:") (maphash #'(lambda (k v) (ros-info (roslisp top) " ~a = ~a" k v)) *remapped-names*))
0
apollo_public_repos/apollo-platform/ros/roslisp
apollo_public_repos/apollo-platform/ros/roslisp/src/roslisp.asd
;;;; -*- Mode: LISP -*- (in-package :asdf) (defsystem :roslisp :name "roslisp" :components ((:file "roslisp") (:file "rosutils" :depends-on ("roslisp")) (:file "master" :depends-on ("rosutils")) (:file "rosout-codegen" :depends-on ("msg" "rosutils")) (:file "rosout" :depends-on ("rosout-codegen")) (:file "time" :depends-on ("rosutils" "rosout")) (:file "namespace" :depends-on ("roslisp")) (:file "msg" :depends-on ("roslisp" "rosutils")) (:file "msg-header" :depends-on ("msg" "rosout" "time")) (:file "params" :depends-on ("namespace" "rosutils" "roslisp" "rosout" "master")) (:file "tcpros" :depends-on ("roslisp" "msg" "rosout" "msg-serialization-stream")) (:file "sockets" :depends-on ("roslisp" "rosout")) (:file "slave" :depends-on ("sockets" "tcpros" "rosout")) (:file "command-line-args" :depends-on ("roslisp" "rosout" "namespace")) (:file "client" :depends-on ("sockets" "namespace" "command-line-args" "msg" "rosout" "master")) (:file "persistent-service" :depends-on ("sockets" "namespace" "roslisp" "tcpros")) (:file "debug-levels" :depends-on ("params" "client" "rosout")) (:file "node" :depends-on ("client")) (:file "msg-serialization-stream" :depends-on ("roslisp")) (:file "pprint" :depends-on ("rosout" "msg")) ) :depends-on (:s-xml :s-xml-rpc :sb-bsd-sockets :rosgraph_msgs-msg :roslisp-msg-protocol :ros-load-manifest :roslisp-utils :std_srvs-srv)) ;;;; eof
0
apollo_public_repos/apollo-platform/ros
apollo_public_repos/apollo-platform/ros/class_loader/CMakeLists.txt
cmake_minimum_required(VERSION 2.8.3) project(class_loader) find_package(Boost REQUIRED COMPONENTS thread system) set(CATKIN_DISABLED false CACHE BOOL "Disable the catkin build, useful if catkin is present but a build outside or ros is done" ) if(NOT CATKIN_DISABLED) find_package(catkin QUIET) endif() find_package(console_bridge REQUIRED) if(${catkin_FOUND}) find_package(catkin REQUIRED COMPONENTS cmake_modules) #find_package(Poco REQUIRED COMPONENTS Foundation) set(Poco_LIBRARIES PocoFoundation) catkin_package( INCLUDE_DIRS include LIBRARIES ${PROJECT_NAME} ${Poco_LIBRARIES} DEPENDS Boost Poco console_bridge CFG_EXTRAS class_loader-extras.cmake ) else() message("-- catkin not found") set(Poco_DIR cmake) find_package(Poco REQUIRED COMPONENTS Foundation) set(CATKIN_PACKAGE_LIB_DESTINATION lib) set(CATKIN_GLOBAL_BIN_DESTINATION bin) set(CATKIN_GLOBAL_BIN_DESTINATION bin) set(CATKIN_PACKAGE_INCLUDE_DESTINATION include/class_loader) endif() include_directories(include ${console_bridge_INCLUDE_DIRS} ${Boost_INCLUDE_DIRS} ${Poco_INCLUDE_DIRS}) set(${PROJECT_NAME}_SRCS src/class_loader.cpp src/class_loader_core.cpp src/meta_object.cpp src/multi_library_class_loader.cpp ) set(${PROJECT_NAME}_HDRS include/class_loader/class_loader_core.h include/class_loader/class_loader_exceptions.h include/class_loader/class_loader.h include/class_loader/class_loader_register_macro.h include/class_loader/meta_object.h include/class_loader/multi_library_class_loader.h ) add_library(${PROJECT_NAME} ${${PROJECT_NAME}_SRCS} ${${PROJECT_NAME}_HDRS}) target_link_libraries(${PROJECT_NAME} ${Boost_LIBRARIES} ${console_bridge_LIBRARIES} ${Poco_LIBRARIES}) install(TARGETS ${PROJECT_NAME} ARCHIVE DESTINATION ${CATKIN_PACKAGE_LIB_DESTINATION} LIBRARY DESTINATION ${CATKIN_PACKAGE_LIB_DESTINATION} RUNTIME DESTINATION ${CATKIN_GLOBAL_BIN_DESTINATION}) install(DIRECTORY include/class_loader/ DESTINATION ${CATKIN_PACKAGE_INCLUDE_DESTINATION}) if(CATKIN_ENABLE_TESTING) add_subdirectory(test) endif() if(NOT catkin_FOUND) set(TARGET_NAME ${PROJECT_NAME}) set(PKGCONFIG_LIBS ${Boost_LIBRARIES} ${console_bridge_LIBRARIES} ${Poco_LIBRARIES} ) # Prepare and install necessary files to support finding of the library # using pkg-config configure_file(${CMAKE_CURRENT_SOURCE_DIR}/src/${TARGET_NAME}.pc.in ${CMAKE_CURRENT_BINARY_DIR}/${TARGET_NAME}.pc @ONLY) install(FILES ${CMAKE_BINARY_DIR}/${PROJECT_NAME}.pc DESTINATION lib/pkgconfig) endif()
0
apollo_public_repos/apollo-platform/ros
apollo_public_repos/apollo-platform/ros/class_loader/package.xml
<package> <name>class_loader</name> <version>0.3.6</version> <description> The class_loader package is a ROS-independent package for loading plugins during runtime and the foundation of the higher level ROS "pluginlib" library. class_loader utilizes the host operating system's runtime loader to open runtime libraries (e.g. .so/.dll files), introspect the library for exported plugin classes, and allows users to instantiate objects of said exported classes without the explicit declaration (i.e. header file) for those classes. </description> <maintainer email="[email protected]">Mikael Arguedas</maintainer> <author>Mirza Shah</author> <license>BSD</license> <url type="website">http://ros.org/wiki/class_loader</url> <url type="bugtracker">https://github.com/ros/class_loader/issues</url> <url type="repository">https://github.com/ros/class_loader</url> <buildtool_depend version_gte="0.5.68">catkin</buildtool_depend> <build_depend>boost</build_depend> <build_depend>libconsole-bridge-dev</build_depend> <build_depend>libpoco-dev</build_depend> <build_depend version_gte="0.3.3">cmake_modules</build_depend> <run_depend>boost</run_depend> <run_depend>libconsole-bridge-dev</run_depend> <run_depend>libpoco-dev</run_depend> </package>
0
apollo_public_repos/apollo-platform/ros
apollo_public_repos/apollo-platform/ros/class_loader/.tar
{!!python/unicode 'url': 'https://github.com/ros-gbp/class_loader-release/archive/release/indigo/class_loader/0.3.6-0.tar.gz', !!python/unicode 'version': class_loader-release-release-indigo-class_loader-0.3.6-0}
0
apollo_public_repos/apollo-platform/ros
apollo_public_repos/apollo-platform/ros/class_loader/CHANGELOG.rst
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Changelog for package class_loader ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 0.3.6 (2016-10-24) ------------------ * Made changes to two locking mechanisms inside class loader core's loadLibrary() function: 1) I added a lock to the 'addClassLoaderOwnerFor...' function to protect it against a race condition with the unloadLibrary() function. 2) I also raised the loader lock to cover the whole function. Previously the check to see if a library is already loaded and the actual loading of the library was not atomic. Multiple threads could create shared library objects, for example. * Contributors: Jonathan Meyer 0.3.5 (2016-09-20) ------------------ * Add ClassLoader::createUniqueInstance (`#38 <https://github.com/ros/class_loader/issues/38>`_) * Wrap comments on createInstance and friend. * Delegate createInstance and createUnmanagedInstance to private impl. * Add ClassLoader::createUniqueInstance. * MultiLibraryClassLoader: Factor out getClassLoaderForClass. * MultiLibraryClassLoader: Add unique_ptr API. * Add tests for unique_ptr API. * Contributors: Maarten de Vries 0.3.4 (2016-06-22) ------------------ * cleanup: don't use active_class_loaders\_[library_path] for existence test (`#35 <https://github.com/ros/class_loader/issues/35>`_) * cleanup: don't use active_class_loaders\_[library_path] for existence test - this accumulates map entries with NULL pointer - fixing it, allows some cleanup * list headers in CodeBlocks / QtCreator * explicitly list all headers * Merge pull request `#34 <https://github.com/ros/class_loader/issues/34>`_ from rhaschke/fix-on-demand-unloading fix on demand unloading * Merge pull request `#32 <https://github.com/ros/class_loader/issues/32>`_ from saarnold/fixed_unset_variable_evaluation fixed evaluation of undefined variable * fixed evaluation of undefined variable * not unloading the ClassLoaders (to avoid the SEVERE WARNING) doesn't work either * bugfix: enable on-demand loading/unloading with MultiClassLoader - enforce loading of library in loadLibrary(), otherwise we cannot know - don't unload libraries in destructor when on-demand-unloading is enabled * extra utest: MultiClassLoaderTest.lazyLoad succeeds two times in a row? * added MultiLibraryClassLoader unittest * Contributors: Mikael Arguedas, Robert Haschke, Sascha Arnold 0.3.3 (2016-03-10) ------------------ * update maintainer * Merge pull request `#26 <https://github.com/ros/class_loader/issues/26>`_ from goldhoorn/indigo-devel Added option to disable the catkin build * Added option to disable the catkin build * Contributors: Esteve Fernandez, Matthias Goldhoorn, Mikael Arguedas 0.3.2 (2015-04-22) ------------------ * Fixed wrong handling of false statement (pkg-config was not installed) * Make catkin optional again * Contributors: Esteve Fernandez, Janosch Machowinski, Matthias Goldhoorn 0.3.1 (2014-12-23) ------------------ * Depend on boost * Use FindPoco.cmake from ros/cmake_modules * Honor BUILD_SHARED_LIBS and do not force building shared libraries. * Contributors: Esteve Fernandez, Gary Servin, Scott K Logan 0.3.0 (2014-06-25) ------------------ * Use system-provided console-bridge * Contributors: Esteve Fernandez 0.2.5 (2014-03-04) ------------------ * Changed format of debug messages so that rosconsole_bridge can correctly parse the prefix * Improved debug output 0.2.4 (2014-02-12) ------------------ * fix race condition with multi threaded library loading (`#16 <https://github.com/ros/class_loader/issues/16>`_) 0.2.3 (2013-08-21) ------------------ * fix missing class name in logWarn output 0.2.2 (2013-07-14) ------------------ * check for CATKIN_ENABLE_TESTING (`#10 <https://github.com/ros/class_loader/issues/10>`_) * fix find Poco to return full lib path (`#8 <https://github.com/ros/class_loader/issues/8>`_) * add missing runtime destination for library under Windows * add Boosst component system 0.2.1 (2013-06-06) ------------------ * improve check for Poco foundation and headers (`#7 <https://github.com/ros/class_loader/issues/7>`_) 0.2.0 (2013-03-13) ------------------ * use find_package for Poco/dl instead to make it work on other platforms * update Poco cmake file to include libdl on non-windows systems * No longer CATKIN_DEPEND on console_bridge 0.1.27 (2013-01-25) ------------------- * change warning message for managed/unmanaged instance mixture in lazy loading mode 0.1.26 (2013-01-17) ------------------- * fix all instances marked as unmanaged 0.1.25 (2013-01-16) ------------------- * fix redundant destructor definition being pulled into plugin library for metaobjects instead of being contained with libclass_loader.so 0.1.24 (2013-01-14 15:27) ------------------------- * fix syntax error for logInform 0.1.23 (2013-01-14 15:23) ------------------------- * downgrade some warning messages to be info/debug 0.1.22 (2013-01-14 15:01) ------------------------- * add safety checks for mixing of managed/unmanaged mixing as well as pointer equivalency check between graveyard and newly created metaobjects 0.1.21 (2013-01-13) ------------------- * fix compile issue on OSX in dependent packages (`#3 <https://github.com/ros/class_loader/issues/3>`_) * add more debug information 0.1.20 (2012-12-21 16:04) ------------------------- * first public release for Groovy
0
apollo_public_repos/apollo-platform/ros/class_loader
apollo_public_repos/apollo-platform/ros/class_loader/test/CMakeLists.txt
cmake_minimum_required(VERSION 2.8) find_package(Boost REQUIRED COMPONENTS thread) find_package(catkin REQUIRED COMPONENTS class_loader) include_directories(${catkin_INCLUDE_DIRS}) add_library(${PROJECT_NAME}_TestPlugins1 EXCLUDE_FROM_ALL plugins1.cpp) target_link_libraries(${PROJECT_NAME}_TestPlugins1 ${PROJECT_NAME}) class_loader_hide_library_symbols(${PROJECT_NAME}_TestPlugins1) add_library(${PROJECT_NAME}_TestPlugins2 EXCLUDE_FROM_ALL plugins2.cpp) target_link_libraries(${PROJECT_NAME}_TestPlugins2 ${PROJECT_NAME}) class_loader_hide_library_symbols(${PROJECT_NAME}_TestPlugins2) catkin_add_gtest(${PROJECT_NAME}_utest utest.cpp) if(TARGET ${PROJECT_NAME}_utest) target_link_libraries(${PROJECT_NAME}_utest ${Boost_LIBRARIES} ${class_loader_LIBRARIES}) add_dependencies(${PROJECT_NAME}_utest ${PROJECT_NAME}_TestPlugins1 ${PROJECT_NAME}_TestPlugins2) endif() include(CheckCXXCompilerFlag) CHECK_CXX_COMPILER_FLAG("-std=c++11" COMPILER_SUPPORTS_CXX11) if(COMPILER_SUPPORTS_CXX11) catkin_add_gtest(${PROJECT_NAME}_unique_ptr_test unique_ptr_test.cpp) if(TARGET ${PROJECT_NAME}_unique_ptr_test) target_link_libraries(${PROJECT_NAME}_unique_ptr_test ${Boost_LIBRARIES} ${class_loader_LIBRARIES}) set_target_properties(${PROJECT_NAME}_unique_ptr_test PROPERTIES COMPILE_FLAGS -std=c++11 LINK_FLAGS -std=c++11) add_dependencies(${PROJECT_NAME}_unique_ptr_test ${PROJECT_NAME}_TestPlugins1 ${PROJECT_NAME}_TestPlugins2) endif() endif()
0
apollo_public_repos/apollo-platform/ros/class_loader
apollo_public_repos/apollo-platform/ros/class_loader/test/plugins1.cpp
#include "base.h" #include <iostream> #include <class_loader/class_loader.h> class Dog : public Base { public: virtual void saySomething(){std::cout << "Bark" << std::endl;} }; class Cat : public Base { public: virtual void saySomething(){std::cout << "Meow" << std::endl;} }; class Duck : public Base { public: virtual void saySomething(){std::cout << "Quack" << std::endl;} }; class Cow : public Base { public: virtual void saySomething(){std::cout << "Moooo" << std::endl;} }; class Sheep : public Base { public: virtual void saySomething(){std::cout << "Baaah" << std::endl;} }; CLASS_LOADER_REGISTER_CLASS(Dog, Base); CLASS_LOADER_REGISTER_CLASS(Cat, Base); CLASS_LOADER_REGISTER_CLASS(Duck, Base); CLASS_LOADER_REGISTER_CLASS(Cow, Base); CLASS_LOADER_REGISTER_CLASS(Sheep, Base);
0
apollo_public_repos/apollo-platform/ros/class_loader
apollo_public_repos/apollo-platform/ros/class_loader/test/plugins2.cpp
#include "base.h" #include <iostream> #include <class_loader/class_loader.h> class Robot : public Base { public: virtual void saySomething(){std::cout << "Beep boop" << std::endl;} }; class Alien : public Base { public: virtual void saySomething(){std::cout << "Znornoff!!!" << std::endl;} }; class Monster : public Base { public: virtual void saySomething(){std::cout << "BEAAAHHHH" << std::endl;} }; class Zombie : public Base { public: virtual void saySomething(){std::cout << "Brains!!!" << std::endl;} }; CLASS_LOADER_REGISTER_CLASS(Robot, Base); CLASS_LOADER_REGISTER_CLASS(Alien, Base); CLASS_LOADER_REGISTER_CLASS(Monster, Base); CLASS_LOADER_REGISTER_CLASS(Zombie, Base);
0
apollo_public_repos/apollo-platform/ros/class_loader
apollo_public_repos/apollo-platform/ros/class_loader/test/utest.cpp
#include <boost/thread.hpp> #include <boost/bind.hpp> #include <iostream> #include <class_loader/class_loader.h> #include <class_loader/multi_library_class_loader.h> #include "base.h" #include <gtest/gtest.h> const std::string LIBRARY_1 = "libclass_loader_TestPlugins1.so"; const std::string LIBRARY_2 = "libclass_loader_TestPlugins2.so"; /*****************************************************************************/ TEST(ClassLoaderTest, basicLoad) { try { class_loader::ClassLoader loader1(LIBRARY_1, false); loader1.createInstance<Base>("Cat")->saySomething(); //See if lazy load works } catch(class_loader::ClassLoaderException& e) { FAIL() << "ClassLoaderException: " << e.what() << "\n"; } SUCCEED(); } /*****************************************************************************/ TEST(ClassLoaderTest, correctNonLazyLoadUnload) { try { ASSERT_FALSE(class_loader::class_loader_private::isLibraryLoadedByAnybody(LIBRARY_1)); class_loader::ClassLoader loader1(LIBRARY_1, false); ASSERT_TRUE(class_loader::class_loader_private::isLibraryLoadedByAnybody(LIBRARY_1)); ASSERT_TRUE(loader1.isLibraryLoaded()); loader1.unloadLibrary(); ASSERT_FALSE(class_loader::class_loader_private::isLibraryLoadedByAnybody(LIBRARY_1)); ASSERT_FALSE(loader1.isLibraryLoaded()); return; } catch(class_loader::ClassLoaderException& e) { FAIL() << "ClassLoaderException: " << e.what() << "\n"; } catch(...) { FAIL() << "Unhandled exception"; } } /*****************************************************************************/ TEST(ClassLoaderTest, correctLazyLoadUnload) { try { ASSERT_FALSE(class_loader::class_loader_private::isLibraryLoadedByAnybody(LIBRARY_1)); class_loader::ClassLoader loader1(LIBRARY_1, true); ASSERT_FALSE(class_loader::class_loader_private::isLibraryLoadedByAnybody(LIBRARY_1)); ASSERT_FALSE(loader1.isLibraryLoaded()); { boost::shared_ptr<Base> obj = loader1.createInstance<Base>("Cat"); ASSERT_TRUE(class_loader::class_loader_private::isLibraryLoadedByAnybody(LIBRARY_1)); ASSERT_TRUE(loader1.isLibraryLoaded()); } //The library will unload automatically when the only plugin object left is destroyed ASSERT_FALSE(class_loader::class_loader_private::isLibraryLoadedByAnybody(LIBRARY_1)); return; } catch(class_loader::ClassLoaderException& e) { FAIL() << "ClassLoaderException: " << e.what() << "\n"; } catch(...) { FAIL() << "Unhandled exception"; } } /*****************************************************************************/ TEST(ClassLoaderTest, nonExistentPlugin) { class_loader::ClassLoader loader1(LIBRARY_1, false); try { boost::shared_ptr<Base> obj = loader1.createInstance<Base>("Bear"); if(obj == NULL) FAIL() << "Null object being returned instead of exception thrown."; obj->saySomething(); } catch(const class_loader::CreateClassException& e) { SUCCEED(); return; } catch(...) { FAIL() << "Unknown exception caught.\n"; } FAIL() << "Did not throw exception as expected.\n"; } /*****************************************************************************/ TEST(ClassLoaderTest, nonExistentLibrary) { try { class_loader::ClassLoader loader1("libDoesNotExist.so", false); } catch(const class_loader::LibraryLoadException& e) { SUCCEED(); return; } catch(...) { FAIL() << "Unknown exception caught.\n"; } FAIL() << "Did not throw exception as expected.\n"; } /*****************************************************************************/ class InvalidBase { }; TEST(ClassLoaderTest, invalidBase) { try { class_loader::ClassLoader loader1(LIBRARY_1, false); if(loader1.isClassAvailable<InvalidBase>("Cat")) { FAIL() << "Cat should not be available for InvalidBase"; } else if(loader1.isClassAvailable<Base>("Cat")) { SUCCEED(); return; } else FAIL() << "Class not available for correct base class."; } catch(const class_loader::LibraryLoadException& e) { FAIL() << "Unexpected exception"; } catch(...) { FAIL() << "Unexpected and unknown exception caught.\n"; } } /*****************************************************************************/ void wait(int seconds) { boost::this_thread::sleep(boost::posix_time::seconds(seconds)); } void run(class_loader::ClassLoader* loader) { std::vector<std::string> classes = loader->getAvailableClasses<Base>(); for(unsigned int c = 0; c < classes.size(); c++) { loader->createInstance<Base>(classes.at(c))->saySomething(); } } TEST(ClassLoaderTest, threadSafety) { class_loader::ClassLoader loader1(LIBRARY_1); ASSERT_TRUE(loader1.isLibraryLoaded()); //Note: Hard to test thread safety to make sure memory isn't corrupted. The hope is this test is hard enough that once in a while it'll segfault or something if there's some implementation error. try { std::vector<boost::thread*> client_threads; for(unsigned int c = 0; c < 1000; c++) client_threads.push_back(new boost::thread(boost::bind(&run, &loader1))); for(unsigned int c = 0; c < client_threads.size(); c++) client_threads.at(c)->join(); for(unsigned int c = 0; c < client_threads.size(); c++) delete(client_threads.at(c)); loader1.unloadLibrary(); ASSERT_FALSE(loader1.isLibraryLoaded()); } catch(const class_loader::ClassLoaderException& ex) { FAIL() << "Unexpected ClassLoaderException."; } catch(...) { FAIL() << "Unknown exception."; } } /*****************************************************************************/ TEST(ClassLoaderTest, loadRefCountingNonLazy) { try { class_loader::ClassLoader loader1(LIBRARY_1, false); ASSERT_TRUE(loader1.isLibraryLoaded()); loader1.loadLibrary(); loader1.loadLibrary(); ASSERT_TRUE(loader1.isLibraryLoaded()); loader1.unloadLibrary(); ASSERT_TRUE(loader1.isLibraryLoaded()); loader1.unloadLibrary(); ASSERT_TRUE(loader1.isLibraryLoaded()); loader1.unloadLibrary(); ASSERT_FALSE(loader1.isLibraryLoaded()); loader1.unloadLibrary(); ASSERT_FALSE(loader1.isLibraryLoaded()); loader1.loadLibrary(); ASSERT_TRUE(loader1.isLibraryLoaded()); return; } catch(const class_loader::ClassLoaderException& e) { FAIL() << "Unexpected exception.\n"; } catch(...) { FAIL() << "Unknown exception caught.\n"; } FAIL() << "Did not throw exception as expected.\n"; } /*****************************************************************************/ TEST(ClassLoaderTest, loadRefCountingLazy) { try { class_loader::ClassLoader loader1(LIBRARY_1, true); ASSERT_FALSE(loader1.isLibraryLoaded()); { boost::shared_ptr<Base> obj = loader1.createInstance<Base>("Dog"); ASSERT_TRUE(loader1.isLibraryLoaded()); } ASSERT_FALSE(loader1.isLibraryLoaded()); loader1.loadLibrary(); ASSERT_TRUE(loader1.isLibraryLoaded()); loader1.loadLibrary(); ASSERT_TRUE(loader1.isLibraryLoaded()); loader1.unloadLibrary(); ASSERT_TRUE(loader1.isLibraryLoaded()); loader1.unloadLibrary(); ASSERT_FALSE(loader1.isLibraryLoaded()); loader1.unloadLibrary(); ASSERT_FALSE(loader1.isLibraryLoaded()); loader1.loadLibrary(); ASSERT_TRUE(loader1.isLibraryLoaded()); return; } catch(const class_loader::ClassLoaderException& e) { FAIL() << "Unexpected exception.\n"; } catch(...) { FAIL() << "Unknown exception caught.\n"; } FAIL() << "Did not throw exception as expected.\n"; } /*****************************************************************************/ void testMultiClassLoader(bool lazy) { try { class_loader::MultiLibraryClassLoader loader(lazy); loader.loadLibrary(LIBRARY_1); loader.loadLibrary(LIBRARY_2); for (int i=0; i < 2; ++i) { loader.createInstance<Base>("Cat")->saySomething(); loader.createInstance<Base>("Dog")->saySomething(); loader.createInstance<Base>("Robot")->saySomething(); } } catch(class_loader::ClassLoaderException& e) { FAIL() << "ClassLoaderException: " << e.what() << "\n"; } SUCCEED(); } TEST(MultiClassLoaderTest, lazyLoad) { testMultiClassLoader(true); } TEST(MultiClassLoaderTest, lazyLoadSecondTime) { testMultiClassLoader(true); } TEST(MultiClassLoaderTest, nonLazyLoad) { testMultiClassLoader(false); } TEST(MultiClassLoaderTest, noWarningOnLazyLoad) { try { boost::shared_ptr<Base> cat, dog, rob; { class_loader::MultiLibraryClassLoader loader(true); loader.loadLibrary(LIBRARY_1); loader.loadLibrary(LIBRARY_2); cat = loader.createInstance<Base>("Cat"); dog = loader.createInstance<Base>("Dog"); rob = loader.createInstance<Base>("Robot"); } cat->saySomething(); dog->saySomething(); rob->saySomething(); } catch(class_loader::ClassLoaderException& e) { FAIL() << "ClassLoaderException: " << e.what() << "\n"; } SUCCEED(); } /*****************************************************************************/ // Run all the tests that were declared with TEST() int main(int argc, char **argv){ testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
0
apollo_public_repos/apollo-platform/ros/class_loader
apollo_public_repos/apollo-platform/ros/class_loader/test/unique_ptr_test.cpp
#include "base.h" #include <class_loader/class_loader.h> #include <class_loader/multi_library_class_loader.h> #include <gtest/gtest.h> #include <boost/thread.hpp> #include <functional> #include <iostream> const std::string LIBRARY_1 = "libclass_loader_TestPlugins1.so"; const std::string LIBRARY_2 = "libclass_loader_TestPlugins2.so"; using class_loader::ClassLoader; /*****************************************************************************/ TEST(ClassLoaderUniquePtrTest, basicLoad) { try { ClassLoader loader1(LIBRARY_1, false); loader1.createUniqueInstance<Base>("Cat")->saySomething(); //See if lazy load works SUCCEED(); } catch(class_loader::ClassLoaderException& e) { FAIL() << "ClassLoaderException: " << e.what() << "\n"; } } /*****************************************************************************/ TEST(ClassLoaderUniquePtrTest, correctLazyLoadUnload) { try { ASSERT_FALSE(class_loader::class_loader_private::isLibraryLoadedByAnybody(LIBRARY_1)); ClassLoader loader1(LIBRARY_1, true); ASSERT_FALSE(class_loader::class_loader_private::isLibraryLoadedByAnybody(LIBRARY_1)); ASSERT_FALSE(loader1.isLibraryLoaded()); { ClassLoader::UniquePtr<Base> obj = loader1.createUniqueInstance<Base>("Cat"); ASSERT_TRUE(class_loader::class_loader_private::isLibraryLoadedByAnybody(LIBRARY_1)); ASSERT_TRUE(loader1.isLibraryLoaded()); } //The library will unload automatically when the only plugin object left is destroyed ASSERT_FALSE(class_loader::class_loader_private::isLibraryLoadedByAnybody(LIBRARY_1)); return; } catch(class_loader::ClassLoaderException& e) { FAIL() << "ClassLoaderException: " << e.what() << "\n"; } catch(...) { FAIL() << "Unhandled exception"; } } /*****************************************************************************/ TEST(ClassLoaderUniquePtrTest, nonExistentPlugin) { ClassLoader loader1(LIBRARY_1, false); try { ClassLoader::UniquePtr<Base> obj = loader1.createUniqueInstance<Base>("Bear"); if(obj == NULL) FAIL() << "Null object being returned instead of exception thrown."; obj->saySomething(); } catch(const class_loader::CreateClassException& e) { SUCCEED(); return; } catch(...) { FAIL() << "Unknown exception caught.\n"; } FAIL() << "Did not throw exception as expected.\n"; } /*****************************************************************************/ void wait(int seconds) { boost::this_thread::sleep(boost::posix_time::seconds(seconds)); } void run(ClassLoader* loader) { std::vector<std::string> classes = loader->getAvailableClasses<Base>(); for(unsigned int c = 0; c < classes.size(); c++) { loader->createUniqueInstance<Base>(classes.at(c))->saySomething(); } } TEST(ClassLoaderUniquePtrTest, threadSafety) { ClassLoader loader1(LIBRARY_1); ASSERT_TRUE(loader1.isLibraryLoaded()); //Note: Hard to test thread safety to make sure memory isn't corrupted. //The hope is this test is hard enough that once in a while it'll segfault //or something if there's some implementation error. try { std::vector<boost::thread> client_threads; for(unsigned int c = 0; c < 1000; c++) client_threads.emplace_back(std::bind(&run, &loader1)); for(unsigned int c = 0; c < client_threads.size(); c++) client_threads.at(c).join(); loader1.unloadLibrary(); ASSERT_FALSE(loader1.isLibraryLoaded()); } catch(const class_loader::ClassLoaderException& ex) { FAIL() << "Unexpected ClassLoaderException."; } catch(...) { FAIL() << "Unknown exception."; } } /*****************************************************************************/ TEST(ClassLoaderUniquePtrTest, loadRefCountingLazy) { try { ClassLoader loader1(LIBRARY_1, true); ASSERT_FALSE(loader1.isLibraryLoaded()); { ClassLoader::UniquePtr<Base> obj = loader1.createUniqueInstance<Base>("Dog"); ASSERT_TRUE(loader1.isLibraryLoaded()); } ASSERT_FALSE(loader1.isLibraryLoaded()); loader1.loadLibrary(); ASSERT_TRUE(loader1.isLibraryLoaded()); loader1.loadLibrary(); ASSERT_TRUE(loader1.isLibraryLoaded()); loader1.unloadLibrary(); ASSERT_TRUE(loader1.isLibraryLoaded()); loader1.unloadLibrary(); ASSERT_FALSE(loader1.isLibraryLoaded()); loader1.unloadLibrary(); ASSERT_FALSE(loader1.isLibraryLoaded()); loader1.loadLibrary(); ASSERT_TRUE(loader1.isLibraryLoaded()); return; } catch(const class_loader::ClassLoaderException& e) { FAIL() << "Unexpected exception.\n"; } catch(...) { FAIL() << "Unknown exception caught.\n"; } FAIL() << "Did not throw exception as expected.\n"; } /*****************************************************************************/ void testMultiClassLoader(bool lazy) { try { class_loader::MultiLibraryClassLoader loader(lazy); loader.loadLibrary(LIBRARY_1); loader.loadLibrary(LIBRARY_2); for (int i=0; i < 2; ++i) { loader.createUniqueInstance<Base>("Cat")->saySomething(); loader.createUniqueInstance<Base>("Dog")->saySomething(); loader.createUniqueInstance<Base>("Robot")->saySomething(); } } catch(class_loader::ClassLoaderException& e) { FAIL() << "ClassLoaderException: " << e.what() << "\n"; } SUCCEED(); } TEST(MultiClassLoaderUniquePtrTest, lazyLoad) { testMultiClassLoader(true); } TEST(MultiClassLoaderUniquePtrTest, lazyLoadSecondTime) { testMultiClassLoader(true); } TEST(MultiClassLoaderUniquePtrTest, nonLazyLoad) { testMultiClassLoader(false); } TEST(MultiClassLoaderUniquePtrTest, noWarningOnLazyLoad) { try { ClassLoader::UniquePtr<Base> cat = nullptr, dog = nullptr, rob = nullptr; { class_loader::MultiLibraryClassLoader loader(true); loader.loadLibrary(LIBRARY_1); loader.loadLibrary(LIBRARY_2); cat = loader.createUniqueInstance<Base>("Cat"); dog = loader.createUniqueInstance<Base>("Dog"); rob = loader.createUniqueInstance<Base>("Robot"); } cat->saySomething(); dog->saySomething(); rob->saySomething(); } catch(class_loader::ClassLoaderException& e) { FAIL() << "ClassLoaderException: " << e.what() << "\n"; } SUCCEED(); } /*****************************************************************************/ // Run all the tests that were declared with TEST() int main(int argc, char **argv){ testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
0
apollo_public_repos/apollo-platform/ros/class_loader
apollo_public_repos/apollo-platform/ros/class_loader/test/base.h
#ifndef BASE_H #define BASE_H class Base { public: virtual void saySomething() = 0; }; #endif
0
apollo_public_repos/apollo-platform/ros/class_loader
apollo_public_repos/apollo-platform/ros/class_loader/cmake/PocoConfig.cmake
# - Find the Poco includes and libraries. # The following variables are set if Poco is found. If Poco is not # found, Poco_FOUND is set to false. # Poco_FOUND - True when the Poco include directory is found. # Poco_INCLUDE_DIRS - the path to where the poco include files are. # Poco_LIBRARY_DIR - The path to where the poco library files are. # Poco_BINARY_DIRS - The path to where the poco dlls are. # Poco_LIBRARIES - list of all libs from requested components. # ---------------------------------------------------------------------------- # If you have installed Poco in a non-standard location. # Then you have three options. # In the following comments, it is assumed that <Your Path> # points to the root directory of the include directory of Poco. e.g # If you have put poco in C:\development\Poco then <Your Path> is # "C:/development/Poco" and in this directory there will be two # directories called "include" and "lib". # 1) After CMake runs, set Poco_INCLUDE_DIR to <Your Path>/poco<-version> # 2) Use CMAKE_INCLUDE_PATH to set a path to <Your Path>/poco<-version>. This will allow FIND_PATH() # to locate Poco_INCLUDE_DIR by utilizing the PATH_SUFFIXES option. e.g. # SET(CMAKE_INCLUDE_PATH ${CMAKE_INCLUDE_PATH} "<Your Path>/include") # 3) Set an environment variable called ${POCO_ROOT} that points to the root of where you have # installed Poco, e.g. <Your Path>. It is assumed that there is at least a subdirectory called # Foundation/include/Poco in this path. # # Note: # 1) If you are just using the poco headers, then you do not need to use # Poco_LIBRARY_DIR in your CMakeLists.txt file. # 2) If Poco has not been installed, then when setting Poco_LIBRARY_DIR # the script will look for /lib first and, if this fails, then for /stage/lib. # # Usage: # In your CMakeLists.txt file do something like this: # ... # # Poco # FIND_PACKAGE(Poco COMPONENTS XML Net Data...) # ... # INCLUDE_DIRECTORIES(${Poco_INCLUDE_DIRS}) # LINK_DIRECTORIES(${Poco_LIBRARY_DIR}) # # In Windows, we make the assumption that, if the Poco files are installed, the default directory # will be C:\poco or C:\Program Files\Poco or C:\Programme\Poco. MESSAGE(STATUS "Searching for Poco library...") SET(POCO_INCLUDE_PATH_DESCRIPTION "top-level directory containing the poco include directories. E.g /usr/local/include/ or c:\\poco\\include\\poco-1.3.2") SET(POCO_INCLUDE_DIR_MESSAGE "Set the Poco_INCLUDE_DIR cmake cache entry to the ${POCO_INCLUDE_PATH_DESCRIPTION}") SET(POCO_LIBRARY_PATH_DESCRIPTION "top-level directory containing the poco libraries.") SET(POCO_LIBRARY_DIR_MESSAGE "Set the Poco_LIBRARY_DIR cmake cache entry to the ${POCO_LIBRARY_PATH_DESCRIPTION}") SET(POCO_DIR_SEARCH $ENV{POCO_ROOT}) IF(POCO_DIR_SEARCH) FILE(TO_CMAKE_PATH ${POCO_DIR_SEARCH} POCO_DIR_SEARCH) ENDIF(POCO_DIR_SEARCH) IF(WIN32) SET(POCO_DIR_SEARCH ${POCO_DIR_SEARCH} C:/poco D:/poco "C:/Program Files/poco" "C:/Programme/poco" "D:/Program Files/poco" "D:/Programme/poco" ) ENDIF(WIN32) # Add in some path suffixes. These will have to be updated whenever a new Poco version comes out. SET(SUFFIX_FOR_INCLUDE_PATH poco-1.3.2 poco-1.3.3 poco-1.3.4 poco-1.3.5 poco-1.3.6 ) SET(SUFFIX_FOR_LIBRARY_PATH poco-1.3.2/lib poco-1.3.2/lib/Linux/i686 poco-1.3.2/lib/Linux/x86_64 poco-1.3.3/lib poco-1.3.3/lib/Linux/i686 poco-1.3.3/lib/Linux/x86_64 poco-1.3.4/lib poco-1.3.4/lib/Linux/i686 poco-1.3.4/lib/Linux/x86_64 poco-1.3.5/lib poco-1.3.5/lib/Linux/i686 poco-1.3.5/lib/Linux/x86_64 poco-1.3.6/lib poco-1.3.6/lib/Linux/i686 poco-1.3.6/lib/Linux/x86_64 lib lib/Linux/i686 lib/Linux/x86_64 ) # # Look for an installation. # FIND_PATH(Poco_INCLUDE_DIR NAMES Foundation/include/Poco/SharedLibrary.h PATH_SUFFIXES ${SUFFIX_FOR_INCLUDE_PATH} PATHS # Look in other places. ${POCO_DIR_SEARCH} # Help the user find it if we cannot. DOC "The ${POCO_INCLUDE_PATH_DESCRIPTION}" ) IF(NOT Poco_INCLUDE_DIR) # Look for standard unix include paths FIND_PATH(Poco_INCLUDE_DIR Poco/Poco.h DOC "The ${POCO_INCLUDE_PATH_DESCRIPTION}") ENDIF(NOT Poco_INCLUDE_DIR) # Assume we didn't find it. SET(Poco_FOUND 0) # Now try to get the include and library path. IF(Poco_INCLUDE_DIR) IF(EXISTS "${Poco_INCLUDE_DIR}/Foundation/include/Poco/SharedLibrary.h") SET(Poco_INCLUDE_DIRS ${Poco_INCLUDE_DIR}/CppUnit/include ${Poco_INCLUDE_DIR}/Foundation/include ${Poco_INCLUDE_DIR}/Net/include ${Poco_INCLUDE_DIR}/Util/include ${Poco_INCLUDE_DIR}/XML/include ) SET(Poco_FOUND 1) ELSEIF(EXISTS "${Poco_INCLUDE_DIR}/Poco/Poco.h") SET(Poco_INCLUDE_DIRS ${Poco_INCLUDE_DIR} ) SET(Poco_FOUND 1) ENDIF() IF(NOT Poco_LIBRARY_DIR) FIND_LIBRARY(Poco_FOUNDATION_LIB NAMES PocoFoundation PocoFoundationd PATH_SUFFIXES ${SUFFIX_FOR_LIBRARY_PATH} PATHS # Look in other places. ${Poco_INCLUDE_DIR} ${POCO_DIR_SEARCH} # Help the user find it if we cannot. DOC "The ${POCO_LIBRARY_PATH_DESCRIPTION}" ) SET(Poco_LIBRARY_DIR "" CACHE PATH POCO_LIBARARY_PATH_DESCRIPTION) GET_FILENAME_COMPONENT(Poco_LIBRARY_DIR ${Poco_FOUNDATION_LIB} PATH) SET(Poco_LIBRARIES "") SET(Comp_List "") IF(Poco_LIBRARY_DIR AND Poco_FOUNDATION_LIB) # Look for the poco binary path. SET(Poco_BINARY_DIR ${Poco_INCLUDE_DIR}) IF(Poco_BINARY_DIR AND EXISTS "${Poco_BINARY_DIR}/bin") SET(Poco_BINARY_DIRS ${Poco_BINARY_DIR}/bin) ENDIF(Poco_BINARY_DIR AND EXISTS "${Poco_BINARY_DIR}/bin") ENDIF(Poco_LIBRARY_DIR AND Poco_FOUNDATION_LIB) IF(Poco_FOUNDATION_LIB) IF ("${CMAKE_BUILD_TYPE}" STREQUAL "Debug") SET(DBG "d") ELSE ("${CMAKE_BUILD_TYPE}" STREQUAL "Debug") SET(DBG "") ENDIF ("${CMAKE_BUILD_TYPE}" STREQUAL "Debug") SET(Comp_List "Foundation${DBG}") FOREACH(COMPONENT ${Poco_FIND_COMPONENTS}) FIND_LIBRARY(LIB${COMPONENT} "Poco${COMPONENT}${DBG}" Poco_LIBRARY_DIR) IF (LIB${COMPONENT}) LIST(APPEND Poco_LIBRARIES "${LIB${COMPONENT}}") LIST(APPEND Comp_List "${COMPONENT}${DBG}") ENDIF(LIB${COMPONENT}) ENDFOREACH(COMPONENT) LIST(REMOVE_DUPLICATES Comp_List) ENDIF(Poco_FOUNDATION_LIB) ENDIF(NOT Poco_LIBRARY_DIR) ENDIF(Poco_INCLUDE_DIR) IF(NOT Poco_FOUND) IF(Poco_FIND_QUIETLY) MESSAGE(STATUS "Poco was not found. ${POCO_INCLUDE_DIR_MESSAGE}") ELSE(Poco_FIND_QUIETLY) IF(Poco_FIND_REQUIRED) MESSAGE(FATAL_ERROR "Poco was not found. ${POCO_INCLUDE_DIR_MESSAGE}") ENDIF(Poco_FIND_REQUIRED) ENDIF(Poco_FIND_QUIETLY) ELSE(NOT Poco_FOUND) MESSAGE(STATUS " Found Poco!") SET(COMPONENT_STR "components found:") FOREACH(comp ${Comp_List}) SET(COMPONENT_STR "${COMPONENT_STR}, ${comp}") ENDFOREACH(comp ${Comp_List}) STRING(REPLACE ":," ":" COMPONENT_LSTR ${COMPONENT_STR}) MESSAGE(STATUS "${COMPONENT_LSTR}.") ENDIF(NOT Poco_FOUND) #I added this in to add "libdl" on non-Windows systems. Technically dl is only neded if the "Foundation" component is used, #but i doesn't hurt to add it in anyway - mas if(Poco_FOUND AND NOT WIN32) LIST(APPEND Poco_LIBRARIES "dl") endif(Poco_FOUND AND NOT WIN32)
0
apollo_public_repos/apollo-platform/ros/class_loader
apollo_public_repos/apollo-platform/ros/class_loader/cmake/class_loader-extras.cmake
# hides all symbols of a library function(class_loader_hide_library_symbols target) set(version_script "${CMAKE_CURRENT_BINARY_DIR}/class_loader_hide_library_symbols__${target}.script") file(WRITE "${version_script}" " { local: *; };" ) # checks if the linker supports version script include(TestCXXAcceptsFlag) check_cxx_accepts_flag("-Wl,--version-script,\"${version_script}\"" LD_ACCEPTS_VERSION_SCRIPT) if(LD_ACCEPTS_VERSION_SCRIPT) set_target_properties(${target} PROPERTIES LINK_FLAGS "-Wl,-version-script=\"${version_script}\"") endif() endfunction()
0
apollo_public_repos/apollo-platform/ros/class_loader/include
apollo_public_repos/apollo-platform/ros/class_loader/include/class_loader/class_loader.h
/* * 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 the 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 CLASS_LOADER_CLASS_LOADER_H_DEFINED #define CLASS_LOADER_CLASS_LOADER_H_DEFINED #include <boost/shared_ptr.hpp> #include <boost/thread/recursive_mutex.hpp> #include <boost/bind.hpp> #include <vector> #include <string> #include <console_bridge/console.h> #include "class_loader/class_loader_register_macro.h" #include "class_loader/class_loader_core.h" #if __cplusplus >= 201103L # include<memory> # include<functional> #endif namespace class_loader { /** * returns runtime library extension for native os */ std::string systemLibrarySuffix(); /** * @class ClassLoader * @brief This class allows loading and unloading of dynamically linked libraries which contain class definitions from which objects can be created/destroyed during runtime (i.e. class_loader). Libraries loaded by a ClassLoader are only accessible within scope of that ClassLoader object. */ class ClassLoader { public: #if __cplusplus >= 201103L template<typename Base> using DeleterType = std::function<void (Base *)>; template<typename Base> using UniquePtr = std::unique_ptr<Base, DeleterType<Base>>; #endif /** * @brief Constructor for ClassLoader * @param library_path - The path of the runtime library to load * @param ondemand_load_unload - Indicates if on-demand (lazy) unloading/loading of libraries occurs as plugins are created/destroyed */ ClassLoader(const std::string& library_path, bool ondemand_load_unload = false); /** * @brief Destructor for ClassLoader. All libraries opened by this ClassLoader are unloaded automatically. */ virtual ~ClassLoader(); /** * @brief Indicates which classes (i.e. class_loader) that can be loaded by this object * @return vector of strings indicating names of instantiable classes derived from <Base> */ template <class Base> std::vector<std::string> getAvailableClasses() { return(class_loader::class_loader_private::getAvailableClasses<Base>(this)); } /** * @brief Gets the full-qualified path and name of the library associated with this class loader */ std::string getLibraryPath(){return(library_path_);} /** * @brief Generates an instance of loadable classes (i.e. class_loader). * * It is not necessary for the user to call loadLibrary() as it will be invoked automatically * if the library is not yet loaded (which typically happens when in "On Demand Load/Unload" mode). * * @param derived_class_name The name of the class we want to create (@see getAvailableClasses()) * @return A boost::shared_ptr<Base> to newly created plugin object */ template <class Base> boost::shared_ptr<Base> createInstance(const std::string& derived_class_name) { return boost::shared_ptr<Base>(createRawInstance<Base>(derived_class_name, true), boost::bind(&ClassLoader::onPluginDeletion<Base>, this, _1)); } #if __cplusplus >= 201103L /** * @brief Generates an instance of loadable classes (i.e. class_loader). * * It is not necessary for the user to call loadLibrary() as it will be invoked automatically * if the library is not yet loaded (which typically happens when in "On Demand Load/Unload" mode). * * If you release the wrapped pointer you must manually call the original * deleter when you want to destroy the released pointer. * * @param derived_class_name The name of the class we want to create (@see getAvailableClasses()) * @return A std::unique_ptr<Base> to newly created plugin object */ template<class Base> UniquePtr<Base> createUniqueInstance(const std::string& derived_class_name) { Base* raw = createRawInstance<Base>(derived_class_name, true); return std::unique_ptr<Base, DeleterType<Base>>(raw, boost::bind(&ClassLoader::onPluginDeletion<Base>, this, _1)); } #endif /** * @brief Generates an instance of loadable classes (i.e. class_loader). * * It is not necessary for the user to call loadLibrary() as it will be invoked automatically * if the library is not yet loaded (which typically happens when in "On Demand Load/Unload" mode). * * Creating an unmanaged instance disables dynamically unloading libraries when * managed pointers go out of scope for all class loaders in this process. * * @param derived_class_name The name of the class we want to create (@see getAvailableClasses()) * @return An unmanaged (i.e. not a shared_ptr) Base* to newly created plugin object. */ template <class Base> Base* createUnmanagedInstance(const std::string& derived_class_name) { return createRawInstance<Base>(derived_class_name, false); } /** * @brief Indicates if a plugin class is available * @param Base - polymorphic type indicating base class * @param class_name - the name of the plugin class * @return true if yes it is available, false otherwise */ template <class Base> bool isClassAvailable(const std::string& class_name) { std::vector<std::string> available_classes = getAvailableClasses<Base>(); return(std::find(available_classes.begin(), available_classes.end(), class_name) != available_classes.end()); } /** * @brief Indicates if a library is loaded within the scope of this ClassLoader. Note that the library may already be loaded internally through another ClassLoader, but until loadLibrary() method is called, the ClassLoader cannot create objects from said library. If we want to see if the library has been opened by somebody else, @see isLibraryLoadedByAnyClassloader() * @param library_path The path to the library to load * @return true if library is loaded within this ClassLoader object's scope, otherwise false */ bool isLibraryLoaded(); /** * @brief Indicates if a library is loaded by some entity in the plugin system (another ClassLoader), but not necessarily loaded by this ClassLoader * @return true if library is loaded within the scope of the plugin system, otherwise false */ bool isLibraryLoadedByAnyClassloader(); /** * @brief Indicates if the library is to be loaded/unloaded on demand...meaning that only to load a lib when the first plugin is created and automatically shut it down when last active plugin is destroyed. */ bool isOnDemandLoadUnloadEnabled(){return(ondemand_load_unload_);} /** * @brief Attempts to load a library on behalf of the ClassLoader. If the library is already opened, this method has no effect. If the library has been already opened by some other entity (i.e. another ClassLoader or global interface), this object is given permissions to access any plugin classes loaded by that other entity. This is * @param library_path The path to the library to load */ void loadLibrary(); /** * @brief Attempts to unload a library loaded within scope of the ClassLoader. If the library is not opened, this method has no effect. If the library is opened by other another ClassLoader, the library will NOT be unloaded internally -- however this ClassLoader will no longer be able to instantiate class_loader bound to that library. If there are plugin objects that exist in memory created by this classloader, a warning message will appear and the library will not be unloaded. If loadLibrary() was called multiple times (e.g. in the case of multiple threads or purposefully in a single thread), the user is responsible for calling unloadLibrary() the same number of times. The library will not be unloaded within the context of this classloader until the number of unload calls matches the number of loads. * @return The number of times more unloadLibrary() has to be called for it to be unbound from this ClassLoader */ int unloadLibrary(); private: /** * @brief Callback method when a plugin created by this class loader is destroyed * @param obj - A pointer to the deleted object */ template <class Base> void onPluginDeletion(Base* obj) { logDebug("class_loader::ClassLoader: Calling onPluginDeletion() for obj ptr = %p.\n", obj); if(obj) { boost::recursive_mutex::scoped_lock lock(plugin_ref_count_mutex_); delete(obj); plugin_ref_count_ = plugin_ref_count_ - 1; assert(plugin_ref_count_ >= 0); if(plugin_ref_count_ == 0 && isOnDemandLoadUnloadEnabled()) { if(!ClassLoader::hasUnmanagedInstanceBeenCreated()) unloadLibraryInternal(false); else logWarn("class_loader::ClassLoader: Cannot unload library %s even though last shared pointer went out of scope. This is because createUnmanagedInstance was used within the scope of this process, perhaps by a different ClassLoader. Library will NOT be closed.", getLibraryPath().c_str()); } } } /** * @brief Generates an instance of loadable classes (i.e. class_loader). * * It is not necessary for the user to call loadLibrary() as it will be invoked automatically * if the library is not yet loaded (which typically happens when in "On Demand Load/Unload" mode). * * @param derived_class_name The name of the class we want to create (@see getAvailableClasses()) * @param managed If true, the returned pointer is assumed to be wrapped in a smart pointer by the caller. * @return A Base* to newly created plugin object */ template <class Base> Base* createRawInstance(const std::string& derived_class_name, bool managed) { if (!managed) has_unmananged_instance_been_created_ = true; if (managed && ClassLoader::hasUnmanagedInstanceBeenCreated() && isOnDemandLoadUnloadEnabled()) logInform("class_loader::ClassLoader: An attempt is being made to create a managed plugin instance (i.e. boost::shared_ptr), however an unmanaged instance was created within this process address space. This means libraries for the managed instances will not be shutdown automatically on final plugin destruction if on demand (lazy) loading/unloading mode is used."); if (!isLibraryLoaded()) loadLibrary(); Base* obj = class_loader::class_loader_private::createInstance<Base>(derived_class_name, this); assert(obj != NULL); //Unreachable assertion if createInstance() throws on failure if (managed) { boost::recursive_mutex::scoped_lock lock(plugin_ref_count_mutex_); plugin_ref_count_ = plugin_ref_count_ + 1; } return obj; } /** * @brief Getter for if an unmanaged (i.e. unsafe) instance has been created flag */ static bool hasUnmanagedInstanceBeenCreated(); /** * @brief As the library may be unloaded in "on-demand load/unload" mode, unload maybe called from createInstance(). The problem is that createInstance() locks the plugin_ref_count as does unloadLibrary(). This method is the implementation of unloadLibrary but with a parameter to decide if plugin_ref_mutex_ should be locked * @param lock_plugin_ref_count - Set to true if plugin_ref_count_mutex_ should be locked, else false * @return The number of times unloadLibraryInternal has to be called again for it to be unbound from this ClassLoader */ int unloadLibraryInternal(bool lock_plugin_ref_count); private: bool ondemand_load_unload_; std::string library_path_; int load_ref_count_; boost::recursive_mutex load_ref_count_mutex_; int plugin_ref_count_; boost::recursive_mutex plugin_ref_count_mutex_; static bool has_unmananged_instance_been_created_; }; } #endif
0
apollo_public_repos/apollo-platform/ros/class_loader/include
apollo_public_repos/apollo-platform/ros/class_loader/include/class_loader/class_loader_register_macro.h
/* * 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 the 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 CLASS_LOADER_REGISTER_MACRO_H_DEFINED #define CLASS_LOADER_REGISTER_MACRO_H_DEFINED #include "class_loader_core.h" #include <console_bridge/console.h> #define CLASS_LOADER_REGISTER_CLASS_INTERNAL_WITH_MESSAGE(Derived, Base, UniqueID, Message) \ namespace \ {\ struct ProxyExec##UniqueID \ {\ typedef Derived _derived; \ typedef Base _base; \ ProxyExec##UniqueID() \ { \ if(std::string(Message)!="")\ logInform("%s", Message);\ class_loader::class_loader_private::registerPlugin<_derived, _base>(#Derived, #Base); \ }\ };\ static ProxyExec##UniqueID g_register_plugin_##UniqueID;\ } #define CLASS_LOADER_REGISTER_CLASS_INTERNAL_HOP1_WITH_MESSAGE(Derived, Base, UniqueID, Message) CLASS_LOADER_REGISTER_CLASS_INTERNAL_WITH_MESSAGE(Derived, Base, UniqueID, Message) /** * @macro This macro is same as CLASS_LOADER_REGISTER_CLASS, but will spit out a message when the plugin is registered * at library load time */ #define CLASS_LOADER_REGISTER_CLASS_WITH_MESSAGE(Derived, Base, Message) CLASS_LOADER_REGISTER_CLASS_INTERNAL_HOP1_WITH_MESSAGE(Derived, Base, __COUNTER__, Message) /** * @macro This is the macro which must be declared within the source (.cpp) file for each class that is to be exported as plugin. * The macro utilizes a trick where a new struct is generated along with a declaration of static global variable of same type after it. The struct's constructor invokes a registration function with the plugin system. When the plugin system loads a library with registered classes in it, the initialization of static variables forces the invocation of the struct constructors, and all exported classes are automatically registerd. */ #define CLASS_LOADER_REGISTER_CLASS(Derived, Base) CLASS_LOADER_REGISTER_CLASS_WITH_MESSAGE(Derived, Base, "") #endif
0
apollo_public_repos/apollo-platform/ros/class_loader/include
apollo_public_repos/apollo-platform/ros/class_loader/include/class_loader/class_loader_core.h
/* * 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 the 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 class_loader_private_H_DEFINED #define class_loader_private_H_DEFINED #include <Poco/SharedLibrary.h> #include <boost/thread/recursive_mutex.hpp> //#include <vector> #include <map> #include <typeinfo> #include <string> #include "class_loader/meta_object.h" #include "class_loader/class_loader_exceptions.h" #include <cstdio> /** * @note This header file is the internal implementation of the plugin system which is exposed via the ClassLoader class */ namespace class_loader { class ClassLoader; //Forward declaration namespace class_loader_private { //Typedefs /*****************************************************************************/ typedef std::string LibraryPath; typedef std::string ClassName; typedef std::string BaseClassName; typedef std::map<ClassName, class_loader_private::AbstractMetaObjectBase*> FactoryMap; typedef std::map<BaseClassName, FactoryMap> BaseToFactoryMapMap; typedef std::pair<LibraryPath, Poco::SharedLibrary*> LibraryPair; typedef std::vector<LibraryPair> LibraryVector; typedef std::vector<AbstractMetaObjectBase*> MetaObjectVector; //Debug /*****************************************************************************/ void printDebugInfoToScreen(); //Global storage /*****************************************************************************/ /** * @brief Gets a handle to a global data structure that holds a map of base class names (Base class describes plugin interface) to a FactoryMap which holds the factories for the various different concrete classes that can be instantiated. Note that the Base class is NOT THE LITERAL CLASSNAME, but rather the result of typeid(Base).name() which sometimes is the literal class name (as on Windows) but is often in mangled form (as on Linux). * @return A reference to the global base to factory map */ BaseToFactoryMapMap& getGlobalPluginBaseToFactoryMapMap(); /** * @brief Gets a handle to a list of open libraries in the form of LibraryPairs which encode the library path+name and the handle to the underlying Poco::SharedLibrary * @return A reference to the global vector that tracks loaded libraries */ LibraryVector& getLoadedLibraryVector(); /** * @brief When a library is being loaded, in order for factories to know which library they are being associated with, they use this function to query which library is being loaded. * @return The currently set loading library name as a string */ std::string getCurrentlyLoadingLibraryName(); /** * @brief When a library is being loaded, in order for factories to know which library they are being associated with, this function is called to set the name of the library currently being loaded. * @param library_name - The name of library that is being loaded currently */ void setCurrentlyLoadingLibraryName(const std::string& library_name); /** * @brief Gets the ClassLoader currently in scope which used when a library is being loaded. * @return A pointer to the currently active ClassLoader. */ ClassLoader* getCurrentlyActiveClassLoader(); /** * @brief Sets the ClassLoader currently in scope which used when a library is being loaded. * @param loader - pointer to the currently active ClassLoader. */ void setCurrentlyActiveClassLoader(ClassLoader* loader); /** * @brief This function extracts a reference to the FactoryMap for appropriate base class out of the global plugin base to factory map. This function should be used by functions in this namespace that need to access the various factories so as to make sure the right key is generated to index into the global map. * @return A reference to the FactoryMap contained within the global Base-to-FactoryMap map. */ FactoryMap& getFactoryMapForBaseClass(const std::string& typeid_base_class_name); /** * @brief Same as above but uses a type parameter instead of string for more safety if info is available. * @return A reference to the FactoryMap contained within the global Base-to-FactoryMap map. */ template <typename Base> FactoryMap& getFactoryMapForBaseClass() { return(getFactoryMapForBaseClass(typeid(Base).name())); } /** * @brief To provide thread safety, all exposed plugin functions can only be run serially by multiple threads. This is implemented by using critical sections enforced by a single mutex which is locked and released with the following two functions * @return A reference to the global mutex */ boost::recursive_mutex& getLoadedLibraryVectorMutex(); boost::recursive_mutex& getPluginBaseToFactoryMapMapMutex(); /** * @brief Indicates if a library containing more than just plugins has been opened by the running process * @return True if a non-pure plugin library has been opened, otherwise false */ bool hasANonPurePluginLibraryBeenOpened(); /** * @brief Sets a flag indicating if a library containing more than just plugins has been opened by the running process * @param hasIt - The flag */ void hasANonPurePluginLibraryBeenOpened(bool hasIt); //Plugin Functions /*****************************************************************************/ /** * @brief This function is called by the CLASS_LOADER_REGISTER_CLASS macro in plugin_register_macro.h to register factories. * Classes that use that macro will cause this function to be invoked when the library is loaded. The function will create a MetaObject (i.e. factory) for the corresponding Derived class and insert it into the appropriate FactoryMap in the global Base-to-FactoryMap map. Note that the passed class_name is the literal class name and not the mangled version. * @param Derived - parameteric type indicating concrete type of plugin * @param Base - parameteric type indicating base type of plugin * @param class_name - the literal name of the class being registered (NOT MANGLED) */ template <typename Derived, typename Base> void registerPlugin(const std::string& class_name, const std::string& base_class_name) { //Note: This function will be automatically invoked when a dlopen() call //opens a library. Normally it will happen within the scope of loadLibrary(), //but that may not be guaranteed. logDebug("class_loader.class_loader_private: Registering plugin factory for class = %s, ClassLoader* = %p and library name %s.", class_name.c_str(), getCurrentlyActiveClassLoader(), getCurrentlyLoadingLibraryName().c_str()); if(getCurrentlyActiveClassLoader() == NULL) { logDebug("class_loader.class_loader_private: ALERT!!! A library containing plugins has been opened through a means other than through the class_loader or pluginlib package. This can happen if you build plugin libraries that contain more than just plugins (i.e. normal code your app links against). This inherently will trigger a dlopen() prior to main() and cause problems as class_loader is not aware of plugin factories that autoregister under the hood. The class_loader package can compensate, but you may run into namespace collision problems (e.g. if you have the same plugin class in two different libraries and you load them both at the same time). The biggest problem is that library can now no longer be safely unloaded as the ClassLoader does not know when non-plugin code is still in use. In fact, no ClassLoader instance in your application will be unable to unload any library once a non-pure one has been opened. Please refactor your code to isolate plugins into their own libraries."); hasANonPurePluginLibraryBeenOpened(true); } //Create factory class_loader_private::AbstractMetaObject<Base>* new_factory = new class_loader_private::MetaObject<Derived, Base>(class_name, base_class_name); new_factory->addOwningClassLoader(getCurrentlyActiveClassLoader()); new_factory->setAssociatedLibraryPath(getCurrentlyLoadingLibraryName()); //Add it to global factory map map getPluginBaseToFactoryMapMapMutex().lock(); FactoryMap& factoryMap = getFactoryMapForBaseClass<Base>(); if(factoryMap.find(class_name) != factoryMap.end()) logWarn("class_loader.class_loader_private: SEVERE WARNING!!! A namespace collision has occured with plugin factory for class %s. New factory will OVERWRITE existing one. This situation occurs when libraries containing plugins are directly linked against an executable (the one running right now generating this message). Please separate plugins out into their own library or just don't link against the library and use either class_loader::ClassLoader/MultiLibraryClassLoader to open.", class_name.c_str()); factoryMap[class_name] = new_factory; getPluginBaseToFactoryMapMapMutex().unlock(); logDebug("class_loader.class_loader_private: Registration of %s complete (Metaobject Address = %p)", class_name.c_str(), new_factory); } /** * @brief This function creates an instance of a plugin class given the derived name of the class and returns a pointer of the Base class type. * @param derived_class_name - The name of the derived class (unmangled) * @param loader - The ClassLoader whose scope we are within * @return A pointer to newly created plugin, note caller is responsible for object destruction */ template <typename Base> Base* createInstance(const std::string& derived_class_name, ClassLoader* loader) { AbstractMetaObject<Base>* factory = NULL; getPluginBaseToFactoryMapMapMutex().lock(); FactoryMap& factoryMap = getFactoryMapForBaseClass<Base>(); if(factoryMap.find(derived_class_name) != factoryMap.end()) factory = dynamic_cast<class_loader_private::AbstractMetaObject<Base>*>(factoryMap[derived_class_name]); else { logError("class_loader.class_loader_private: No metaobject exists for class type %s.", derived_class_name.c_str()); } getPluginBaseToFactoryMapMapMutex().unlock(); Base* obj = NULL; if(factory != NULL && factory->isOwnedBy(loader)) obj = factory->create(); if(obj == NULL) //Was never created { if(factory && factory->isOwnedBy(NULL)) { logDebug("class_loader.class_loader_private: ALERT!!! A metaobject (i.e. factory) exists for desired class, but has no owner. This implies that the library containing the class was dlopen()ed by means other than through the class_loader interface. This can happen if you build plugin libraries that contain more than just plugins (i.e. normal code your app links against) -- that intrinsically will trigger a dlopen() prior to main(). You should isolate your plugins into their own library, otherwise it will not be possible to shutdown the library!"); obj = factory->create(); } else throw(class_loader::CreateClassException("Could not create instance of type " + derived_class_name)); } logDebug("class_loader.class_loader_private: Created instance of type %s and object pointer = %p", (typeid(obj).name()), obj); return(obj); } /** * @brief This function returns all the available class_loader in the plugin system that are derived from Base and within scope of the passed ClassLoader. * @param loader - The pointer to the ClassLoader whose scope we are within, * @return A vector of strings where each string is a plugin we can create */ template <typename Base> std::vector<std::string> getAvailableClasses(ClassLoader* loader) { boost::recursive_mutex::scoped_lock lock(getPluginBaseToFactoryMapMapMutex()); FactoryMap& factory_map = getFactoryMapForBaseClass<Base>(); std::vector<std::string> classes; std::vector<std::string> classes_with_no_owner; for(FactoryMap::const_iterator itr = factory_map.begin(); itr != factory_map.end(); ++itr) { AbstractMetaObjectBase* factory = itr->second; if(factory->isOwnedBy(loader)) classes.push_back(itr->first); else if(factory->isOwnedBy(NULL)) classes_with_no_owner.push_back(itr->first); } //Added classes not associated with a class loader (Which can happen through //an unexpected dlopen() to the library) classes.insert(classes.end(), classes_with_no_owner.begin(), classes_with_no_owner.end()); return(classes); } /** * @brief This function returns the names of all libraries in use by a given class loader. * @param loader - The ClassLoader whose scope we are within * @return A vector of strings where each string is the path+name of each library that are within a ClassLoader's visible scope */ std::vector<std::string> getAllLibrariesUsedByClassLoader(const ClassLoader* loader); /** * @brief Indicates if passed library loaded within scope of a ClassLoader. The library maybe loaded in memory, but to the class loader it may not be. * @param library_path - The name of the library we wish to check is open * @param loader - The pointer to the ClassLoader whose scope we are within * @return true if the library is loaded within loader's scope, else false */ bool isLibraryLoaded(const std::string& library_path, ClassLoader* loader); /** * @brief Indicates if passed library has been loaded by ANY ClassLoader * @param library_path - The name of the library we wish to check is open * @return true if the library is loaded in memory, otherwise false */ bool isLibraryLoadedByAnybody(const std::string& library_path); /** * @brief Loads a library into memory if it has not already been done so. Attempting to load an already loaded library has no effect. * @param library_path - The name of the library to open * @param loader - The pointer to the ClassLoader whose scope we are within */ void loadLibrary(const std::string& library_path, ClassLoader* loader); /** * @brief Unloads a library if it loaded in memory and cleans up its corresponding class factories. If it is not loaded, the function has no effect * @param library_path - The name of the library to open * @param loader - The pointer to the ClassLoader whose scope we are within */ void unloadLibrary(const std::string& library_path, ClassLoader* loader); } //End namespace class_loader_private } //End namespace class_loader #endif
0
apollo_public_repos/apollo-platform/ros/class_loader/include
apollo_public_repos/apollo-platform/ros/class_loader/include/class_loader/meta_object.h
/* * 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 the 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. */ //Note: This header defines a simplication of Poco::MetaObject that allows us to tag MetaObjects with an associated library name. #ifndef PLUGINS_PRIVATE_META_OBJECT_DEFINED #define PLUGINS_PRIVATE_META_OBJECT_DEFINED #include <console_bridge/console.h> #include <vector> #include <typeinfo> namespace class_loader { class ClassLoader; //Forward declaration namespace class_loader_private { typedef std::vector<class_loader::ClassLoader*> ClassLoaderVector; /** * @class AbstractMetaObjectBase * @brief A base class for MetaObjects that excludes a polymorphic type parameter. Subclasses are class templates though. */ class AbstractMetaObjectBase { public: /** * @brief Constructor for the class */ AbstractMetaObjectBase(const std::string& class_name, const std::string& base_class_name); /** * @brief Destructor for the class. THIS MUST NOT BE VIRTUAL AND OVERRIDDEN BY * TEMPLATE SUBCLASSES, OTHERWISE THEY WILL PULL IN A REDUNDANT METAOBJECT * DESTRUCTOR OUTSIDE OF libclass_loader WITHIN THE PLUGIN LIBRARY! T */ ~AbstractMetaObjectBase(); /** * @brief Gets the literal name of the class. * @return The literal name of the class as a C-string. */ std::string className() const; /** * @brief gets the base class for the class this factory represents */ std::string baseClassName() const; /** * @brief Gets the name of the class as typeid(BASE_CLASS).name() would return it */ std::string typeidBaseClassName() const; /** * @brief Gets the path to the library associated with this factory * @return Library path as a std::string */ std::string getAssociatedLibraryPath(); /** * @brief Sets the path to the library associated with this factory */ void setAssociatedLibraryPath(std::string library_path); /** * @brief Associates a ClassLoader owner with this factory, * @param loader Handle to the owning ClassLoader. */ void addOwningClassLoader(ClassLoader* loader); /** * @brief Removes a ClassLoader that is an owner of this factory * @param loader Handle to the owning ClassLoader. */ void removeOwningClassLoader(const ClassLoader* loader); /** * @brief Indicates if the factory is within the usable scope of a ClassLoader * @param loader Handle to the owning ClassLoader. */ bool isOwnedBy(const ClassLoader* loader); /** * @brief Indicates if the factory is within the usable scope of any ClassLoader */ bool isOwnedByAnybody(); /** * A vector of class loaders that own this metaobject */ ClassLoaderVector getAssociatedClassLoaders(); protected: /** * This is needed to make base class polymorphic (i.e. have a vtable) */ virtual void dummyMethod(){} protected: ClassLoaderVector associated_class_loaders_; std::string associated_library_path_; std::string base_class_name_; std::string class_name_; std::string typeid_base_class_name_; }; /** * @class AbstractMetaObject * @brief Abstract base class for factories where polymorphic type variable indicates base class for plugin interface. * @parm B The base class interface for the plugin */ template <class B> class AbstractMetaObject : public AbstractMetaObjectBase { public: /** * @brief A constructor for this class * @param name The literal name of the class. */ AbstractMetaObject(const std::string& class_name, const std::string& base_class_name) : AbstractMetaObjectBase(class_name, base_class_name) { AbstractMetaObjectBase::typeid_base_class_name_ = std::string(typeid(B).name()); } /** * @brief Defines the factory interface that the MetaObject must implement. * @return A pointer of parametric type B to a newly created object. */ virtual B* create() const = 0; /// Create a new instance of a class. /// Cannot be used for singletons. private: AbstractMetaObject(); AbstractMetaObject(const AbstractMetaObject&); AbstractMetaObject& operator = (const AbstractMetaObject&); }; /** * @class MetaObject * @brief The actual factory. * @parm C The derived class (the actual plugin) * @parm B The base class interface for the plugin */ template <class C, class B> class MetaObject: public AbstractMetaObject<B> { public: /** * @brief Constructor for the class */ MetaObject(const std::string& class_name, const std::string& base_class_name) : AbstractMetaObject<B>(class_name, base_class_name) { } /** * @brief The factory interface to generate an object. The object has type C in reality, though a pointer of the base class type is returned. * @return A pointer to a newly created plugin with the base class type (type parameter B) */ B* create() const { return new C; } }; } // End namespace class_loader_private } // End namespace class_loader #endif
0
apollo_public_repos/apollo-platform/ros/class_loader/include
apollo_public_repos/apollo-platform/ros/class_loader/include/class_loader/multi_library_class_loader.h
/* * 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 the 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 CLASS_LOADER_MULTI_LIBRARY_CLASS_LOADER_H_DEFINED #define CLASS_LOADER_MULTI_LIBRARY_CLASS_LOADER_H_DEFINED #include "class_loader.h" #include <boost/thread.hpp> namespace class_loader { typedef std::string LibraryPath; typedef std::map<LibraryPath, class_loader::ClassLoader*> LibraryToClassLoaderMap; typedef std::vector<ClassLoader*> ClassLoaderVector; /** * @class MultiLibraryClassLoader * @brief A ClassLoader that can bind more than one runtime library */ class MultiLibraryClassLoader { public: /** * @brief Constructor for the class * @param enable_ondemand_loadunload - Flag indicates if classes are to be loaded/unloaded automatically as class_loader are created and destroyed */ MultiLibraryClassLoader(bool enable_ondemand_loadunload); /** * @brief Virtual destructor for class */ virtual ~MultiLibraryClassLoader(); /** * @brief Creates an instance of an object of given class name with ancestor class Base * This version does not look in a specific library for the factory, but rather the first open library that defines the classs * @param Base - polymorphic type indicating base class * @param class_name - the name of the concrete plugin class we want to instantiate * @return A boost::shared_ptr<Base> to newly created plugin */ template <class Base> boost::shared_ptr<Base> createInstance(const std::string& class_name) { logDebug("class_loader::MultiLibraryClassLoader: Attempting to create instance of class type %s.", class_name.c_str()); ClassLoader* loader = getClassLoaderForClass<Base>(class_name); if (loader == NULL) throw class_loader::CreateClassException("MultiLibraryClassLoader: Could not create object of class type " + class_name + " as no factory exists for it. Make sure that the library exists and was explicitly loaded through MultiLibraryClassLoader::loadLibrary()"); return loader->createInstance<Base>(class_name); } /** * @brief Creates an instance of an object of given class name with ancestor class Base * This version takes a specific library to make explicit the factory being used * @param Base - polymorphic type indicating base class * @param class_name - the name of the concrete plugin class we want to instantiate * @param library_path - the library from which we want to create the plugin * @return A boost::shared_ptr<Base> to newly created plugin */ template <class Base> boost::shared_ptr<Base> createInstance(const std::string& class_name, const std::string& library_path) { ClassLoader* loader = getClassLoaderForLibrary(library_path); if (loader == NULL) throw class_loader::NoClassLoaderExistsException("Could not create instance as there is no ClassLoader in MultiLibraryClassLoader bound to library " + library_path + " Ensure you called MultiLibraryClassLoader::loadLibrary()"); return loader->createInstance<Base>(class_name); } #if __cplusplus >= 201103L /** * @brief Creates an instance of an object of given class name with ancestor class Base * This version does not look in a specific library for the factory, but rather the first open library that defines the classs * @param Base - polymorphic type indicating base class * @param class_name - the name of the concrete plugin class we want to instantiate * @return A unique pointer to newly created plugin */ template <class Base> ClassLoader::UniquePtr<Base> createUniqueInstance(const std::string& class_name) { logDebug("class_loader::MultiLibraryClassLoader: Attempting to create instance of class type %s.", class_name.c_str()); ClassLoader* loader = getClassLoaderForClass<Base>(class_name); if (loader == nullptr) throw class_loader::CreateClassException("MultiLibraryClassLoader: Could not create object of class type " + class_name + " as no factory exists for it. Make sure that the library exists and was explicitly loaded through MultiLibraryClassLoader::loadLibrary()"); return loader->createUniqueInstance<Base>(class_name); } /** * @brief Creates an instance of an object of given class name with ancestor class Base * This version takes a specific library to make explicit the factory being used * @param Base - polymorphic type indicating base class * @param class_name - the name of the concrete plugin class we want to instantiate * @param library_path - the library from which we want to create the plugin * @return A unique pointer to newly created plugin */ template <class Base> ClassLoader::UniquePtr<Base> createUniqueInstance(const std::string& class_name, const std::string& library_path) { ClassLoader* loader = getClassLoaderForLibrary(library_path); if (loader == nullptr) throw class_loader::NoClassLoaderExistsException("Could not create instance as there is no ClassLoader in MultiLibraryClassLoader bound to library " + library_path + " Ensure you called MultiLibraryClassLoader::loadLibrary()"); return loader->createUniqueInstance<Base>(class_name); } #endif /** * @brief Creates an instance of an object of given class name with ancestor class Base * This version does not look in a specific library for the factory, but rather the first open library that defines the classs * This version should not be used as the plugin system cannot do automated safe loading/unloadings * @param Base - polymorphic type indicating base class * @param class_name - the name of the concrete plugin class we want to instantiate * @return An unmanaged Base* to newly created plugin */ template <class Base> Base* createUnmanagedInstance(const std::string& class_name) { ClassLoader* loader = getClassLoaderForClass<Base>(class_name); if (loader == NULL) throw class_loader::CreateClassException("MultiLibraryClassLoader: Could not create class of type " + class_name); return loader->createUnmanagedInstance<Base>(class_name); } /** * @brief Creates an instance of an object of given class name with ancestor class Base * This version takes a specific library to make explicit the factory being used * This version should not be used as the plugin system cannot do automated safe loading/unloadings * @param Base - polymorphic type indicating Base class * @param class_name - name of class for which we want to create instance * @param library_path - the fully qualified path to the runtime library */ template <class Base> Base* createUnmanagedInstance(const std::string& class_name, const std::string& library_path) { ClassLoader* loader = getClassLoaderForLibrary(library_path); if (loader == NULL) throw class_loader::NoClassLoaderExistsException("Could not create instance as there is no ClassLoader in MultiLibraryClassLoader bound to library " + library_path + " Ensure you called MultiLibraryClassLoader::loadLibrary()"); return loader->createUnmanagedInstance<Base>(class_name); } /** * @brief Indicates if a class has been loaded and can be instantiated * @param Base - polymorphic type indicating Base class * @param class_name - name of class that is be inquired about * @return true if loaded, false otherwise */ template <class Base> bool isClassAvailable(const std::string& class_name) { std::vector<std::string> available_classes = getAvailableClasses<Base>(); return(available_classes.end() != std::find(available_classes.begin(), available_classes.end(), class_name)); } /** * @brief Indicates if a library has been loaded into memory * @param library_path - The full qualified path to the runtime library * @return true if library is loaded, false otherwise */ bool isLibraryAvailable(const std::string& library_path); /** * @brief Gets a list of all classes that are loaded by the class loader * @param Base - polymorphic type indicating Base class * @return A vector<string> of the available classes */ template <class Base> std::vector<std::string> getAvailableClasses() { std::vector<std::string> available_classes; ClassLoaderVector loaders = getAllAvailableClassLoaders(); for(unsigned int c = 0; c < loaders.size(); c++) { ClassLoader* current = loaders.at(c); std::vector<std::string> loader_classes = current->getAvailableClasses<Base>(); available_classes.insert(available_classes.end(), loader_classes.begin(), loader_classes.end()); } return(available_classes); } /** * @brief Gets a list of all classes loaded for a particular library * @param Base - polymorphic type indicating Base class * @return A vector<string> of the available classes in the passed library */ template <class Base> std::vector<std::string> getAvailableClassesForLibrary(const std::string& library_path) { ClassLoader* loader = getClassLoaderForLibrary(library_path); std::vector<std::string> available_classes; if(loader) { available_classes = loader->getAvailableClasses<Base>(); return(available_classes); } else throw class_loader::NoClassLoaderExistsException("There is no ClassLoader in MultiLibraryClassLoader bound to library " + library_path + " Ensure you called MultiLibraryClassLoader::loadLibrary()"); } /** * @brief Gets a list of all libraries opened by this class loader @ @return A list of libraries opened by this class loader */ std::vector<std::string> getRegisteredLibraries(); /** * @brief Loads a library into memory for this class loader * @param library_path - the fully qualified path to the runtime library */ void loadLibrary(const std::string& library_path); /** * @brief Unloads a library for this class loader * @param library_path - the fully qualified path to the runtime library */ int unloadLibrary(const std::string& library_path); private: /** * @brief Indicates if on-demand (lazy) load/unload is enabled so libraries are loaded/unloaded automatically as needed */ bool isOnDemandLoadUnloadEnabled(){return(enable_ondemand_loadunload_);} /** * @brief Gets a handle to the class loader corresponding to a specific runtime library * @param library_path - the library from which we want to create the plugin * @return A pointer to the ClassLoader*, == NULL if not found */ ClassLoader* getClassLoaderForLibrary(const std::string& library_path); /** * @brief Gets a handle to the class loader corresponding to a specific class * @param class_name - name of class for which we want to create instance * @return A pointer to the ClassLoader*, == NULL if not found */ template<typename Base> ClassLoader* getClassLoaderForClass(const std::string& class_name) { ClassLoaderVector loaders = getAllAvailableClassLoaders(); for (ClassLoaderVector::iterator i = loaders.begin(); i != loaders.end(); ++i) { if (!(*i)->isLibraryLoaded()) (*i)->loadLibrary(); if ((*i)->isClassAvailable<Base>(class_name)) return *i; } return NULL; } /** * @brief Gets all class loaders loaded within scope */ ClassLoaderVector getAllAvailableClassLoaders(); /** * @brief Destroys all ClassLoaders */ void shutdownAllClassLoaders(); private: bool enable_ondemand_loadunload_; LibraryToClassLoaderMap active_class_loaders_; boost::mutex loader_mutex_; }; } #endif
0
apollo_public_repos/apollo-platform/ros/class_loader/include
apollo_public_repos/apollo-platform/ros/class_loader/include/class_loader/class_loader_exceptions.h
/* * 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 the 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 <exception> namespace class_loader { /** * @class ClassLoader sException * @brief A base class for all class_loader exceptions that inherits from std::runtime_exception */ class ClassLoaderException: public std::runtime_error { public: ClassLoaderException(const std::string error_desc) : std::runtime_error(error_desc) {} }; /** * @class LibraryLoadException * @brief An exception class thrown when class_loader is unable to load a runtime library */ class LibraryLoadException: public ClassLoaderException { public: LibraryLoadException(const std::string error_desc) : ClassLoaderException(error_desc) {} }; /** * @class LibraryUnloadException * @brief An exception class thrown when class_loader is unable to unload a runtime library */ class LibraryUnloadException: public ClassLoaderException { public: LibraryUnloadException(const std::string error_desc) : ClassLoaderException(error_desc) {} }; /** * @class CreateClassException * @brief An exception class thrown when class_loader is unable to create a plugin */ class CreateClassException: public ClassLoaderException { public: CreateClassException(const std::string error_desc) : ClassLoaderException(error_desc) {} }; /** * @class NoClassLoaderExistsException * @brief An exception class thrown when a multilibrary class loader does not have a ClassLoader bound to it */ class NoClassLoaderExistsException: public ClassLoaderException { public: NoClassLoaderExistsException(const std::string error_desc) : ClassLoaderException(error_desc) {} }; }
0
apollo_public_repos/apollo-platform/ros/class_loader
apollo_public_repos/apollo-platform/ros/class_loader/src/class_loader.cpp
/* * 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 the 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 "class_loader/class_loader.h" namespace class_loader { bool ClassLoader::has_unmananged_instance_been_created_ = false; bool ClassLoader::hasUnmanagedInstanceBeenCreated() { return ClassLoader::has_unmananged_instance_been_created_; } std::string systemLibrarySuffix() { return(Poco::SharedLibrary::suffix()); } ClassLoader::ClassLoader(const std::string& library_path, bool ondemand_load_unload) : ondemand_load_unload_(ondemand_load_unload), library_path_(library_path), load_ref_count_(0), plugin_ref_count_(0) { logDebug("class_loader.ClassLoader: Constructing new ClassLoader (%p) bound to library %s.", this, library_path.c_str()); if(!isOnDemandLoadUnloadEnabled()) loadLibrary(); } ClassLoader::~ClassLoader() { logDebug("class_loader.ClassLoader: Destroying class loader, unloading associated library...\n"); unloadLibrary(); //TODO: while(unloadLibrary() > 0){} ?? } bool ClassLoader::isLibraryLoaded() { return(class_loader::class_loader_private::isLibraryLoaded(getLibraryPath(), this)); } bool ClassLoader::isLibraryLoadedByAnyClassloader() { return(class_loader::class_loader_private::isLibraryLoadedByAnybody(getLibraryPath())); } void ClassLoader::loadLibrary() { boost::recursive_mutex::scoped_lock lock(load_ref_count_mutex_); load_ref_count_ = load_ref_count_ + 1; class_loader::class_loader_private::loadLibrary(getLibraryPath(), this); } int ClassLoader::unloadLibrary() { return(unloadLibraryInternal(true)); } int ClassLoader::unloadLibraryInternal(bool lock_plugin_ref_count) { boost::recursive_mutex::scoped_lock load_ref_lock(load_ref_count_mutex_); boost::recursive_mutex::scoped_lock plugin_ref_lock; if(lock_plugin_ref_count) plugin_ref_lock = boost::recursive_mutex::scoped_lock(plugin_ref_count_mutex_); if(plugin_ref_count_ > 0) logWarn("class_loader.ClassLoader: SEVERE WARNING!!! Attempting to unload library while objects created by this loader exist in the heap! You should delete your objects before attempting to unload the library or destroying the ClassLoader. The library will NOT be unloaded."); else { load_ref_count_ = load_ref_count_ - 1; if(load_ref_count_ == 0) class_loader::class_loader_private::unloadLibrary(getLibraryPath(), this); else if(load_ref_count_ < 0) load_ref_count_ = 0; } return(load_ref_count_); } }
0
apollo_public_repos/apollo-platform/ros/class_loader
apollo_public_repos/apollo-platform/ros/class_loader/src/multi_library_class_loader.cpp
/* * 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 the 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 "class_loader/multi_library_class_loader.h" namespace class_loader { MultiLibraryClassLoader::MultiLibraryClassLoader(bool enable_ondemand_loadunload) : enable_ondemand_loadunload_(enable_ondemand_loadunload) { } MultiLibraryClassLoader::~MultiLibraryClassLoader() { shutdownAllClassLoaders(); } std::vector<std::string> MultiLibraryClassLoader::getRegisteredLibraries() { std::vector<std::string> libraries; for(LibraryToClassLoaderMap::iterator itr = active_class_loaders_.begin(); itr != active_class_loaders_.end(); itr++) libraries.push_back(itr->first); return(libraries); } ClassLoader* MultiLibraryClassLoader::getClassLoaderForLibrary(const std::string& library_path) { LibraryToClassLoaderMap::iterator itr = active_class_loaders_.find(library_path); if (itr != active_class_loaders_.end()) return itr->second; else return NULL; } ClassLoaderVector MultiLibraryClassLoader::getAllAvailableClassLoaders() { ClassLoaderVector loaders; for(LibraryToClassLoaderMap::iterator itr = active_class_loaders_.begin(); itr != active_class_loaders_.end(); itr++) loaders.push_back(itr->second); return(loaders); } bool MultiLibraryClassLoader::isLibraryAvailable(const std::string& library_name) { return (getClassLoaderForLibrary(library_name) != NULL); } void MultiLibraryClassLoader::loadLibrary(const std::string& library_path) { if(!isLibraryAvailable(library_path)) active_class_loaders_[library_path] = new class_loader::ClassLoader(library_path, isOnDemandLoadUnloadEnabled()); } void MultiLibraryClassLoader::shutdownAllClassLoaders() { std::vector<std::string> available_libraries = getRegisteredLibraries(); for(unsigned int c = 0; c < available_libraries.size(); c++) unloadLibrary(available_libraries.at(c)); } int MultiLibraryClassLoader::unloadLibrary(const std::string& library_path) { int remaining_unloads = 0; LibraryToClassLoaderMap::iterator itr = active_class_loaders_.find(library_path); if (itr != active_class_loaders_.end()) { ClassLoader* loader = itr->second; if((remaining_unloads = loader->unloadLibrary()) == 0) { delete(loader); active_class_loaders_.erase(itr); } } return(remaining_unloads); } }
0
apollo_public_repos/apollo-platform/ros/class_loader
apollo_public_repos/apollo-platform/ros/class_loader/src/class_loader_core.cpp
/* * 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 the 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 "class_loader/class_loader_core.h" #include "class_loader/class_loader.h" #include <cassert> namespace class_loader { namespace class_loader_private { //Global data /*****************************************************************************/ /*****************************************************************************/ /*****************************************************************************/ boost::recursive_mutex& getLoadedLibraryVectorMutex() /*****************************************************************************/ { static boost::recursive_mutex m; return m; } boost::recursive_mutex& getPluginBaseToFactoryMapMapMutex() /*****************************************************************************/ { static boost::recursive_mutex m; return m; } BaseToFactoryMapMap& getGlobalPluginBaseToFactoryMapMap() /*****************************************************************************/ { static BaseToFactoryMapMap instance; return instance; } FactoryMap& getFactoryMapForBaseClass(const std::string& typeid_base_class_name) /*****************************************************************************/ { BaseToFactoryMapMap& factoryMapMap = getGlobalPluginBaseToFactoryMapMap(); std::string base_class_name = typeid_base_class_name; if(factoryMapMap.find(base_class_name) == factoryMapMap.end()) factoryMapMap[base_class_name] = FactoryMap(); return(factoryMapMap[base_class_name]); } MetaObjectVector& getMetaObjectGraveyard() /*****************************************************************************/ { static MetaObjectVector instance; return instance; } LibraryVector& getLoadedLibraryVector() /*****************************************************************************/ { static LibraryVector instance; return instance; } std::string& getCurrentlyLoadingLibraryNameReference() /*****************************************************************************/ { static std::string library_name; return library_name; } std::string getCurrentlyLoadingLibraryName() /*****************************************************************************/ { return(getCurrentlyLoadingLibraryNameReference()); } void setCurrentlyLoadingLibraryName(const std::string& library_name) /*****************************************************************************/ { std::string& library_name_ref = getCurrentlyLoadingLibraryNameReference(); library_name_ref = library_name; } ClassLoader*& getCurrentlyActiveClassLoaderReference() /*****************************************************************************/ { static ClassLoader* loader = NULL; return(loader); } ClassLoader* getCurrentlyActiveClassLoader() /*****************************************************************************/ { return(getCurrentlyActiveClassLoaderReference()); } void setCurrentlyActiveClassLoader(ClassLoader* loader) /*****************************************************************************/ { ClassLoader*& loader_ref = getCurrentlyActiveClassLoaderReference(); loader_ref = loader; } bool& hasANonPurePluginLibraryBeenOpenedReference() /*****************************************************************************/ { static bool hasANonPurePluginLibraryBeenOpenedReference = false; return hasANonPurePluginLibraryBeenOpenedReference; } bool hasANonPurePluginLibraryBeenOpened() /*****************************************************************************/ { return(hasANonPurePluginLibraryBeenOpenedReference()); } void hasANonPurePluginLibraryBeenOpened(bool hasIt) /*****************************************************************************/ { hasANonPurePluginLibraryBeenOpenedReference() = hasIt; } //MetaObject search/insert/removal/query /*****************************************************************************/ /*****************************************************************************/ /*****************************************************************************/ MetaObjectVector allMetaObjects(const FactoryMap& factories) /*****************************************************************************/ { MetaObjectVector all_meta_objs; for(FactoryMap::const_iterator factoryItr = factories.begin(); factoryItr != factories.end(); factoryItr++) all_meta_objs.push_back(factoryItr->second); return(all_meta_objs); } MetaObjectVector allMetaObjects() /*****************************************************************************/ { boost::recursive_mutex::scoped_lock lock(getPluginBaseToFactoryMapMapMutex()); MetaObjectVector all_meta_objs; BaseToFactoryMapMap& factory_map_map = getGlobalPluginBaseToFactoryMapMap(); BaseToFactoryMapMap::iterator itr; for(itr = factory_map_map.begin(); itr != factory_map_map.end(); itr++) { MetaObjectVector objs = allMetaObjects(itr->second); all_meta_objs.insert(all_meta_objs.end(), objs.begin(), objs.end()); } return(all_meta_objs); } MetaObjectVector filterAllMetaObjectsOwnedBy(const MetaObjectVector& to_filter, const ClassLoader* owner) /*****************************************************************************/ { MetaObjectVector filtered_objs; for(unsigned int c = 0; c < to_filter.size(); c++) if(to_filter.at(c)->isOwnedBy(owner)) filtered_objs.push_back(to_filter.at(c)); return(filtered_objs); } MetaObjectVector filterAllMetaObjectsAssociatedWithLibrary(const MetaObjectVector& to_filter, const std::string& library_path) /*****************************************************************************/ { MetaObjectVector filtered_objs; for(unsigned int c = 0; c < to_filter.size(); c++) if(to_filter.at(c)->getAssociatedLibraryPath()==library_path) filtered_objs.push_back(to_filter.at(c)); return(filtered_objs); } MetaObjectVector allMetaObjectsForClassLoader(const ClassLoader* owner) /*****************************************************************************/ { return(filterAllMetaObjectsOwnedBy(allMetaObjects(), owner)); } MetaObjectVector allMetaObjectsForLibrary(const std::string& library_path) /*****************************************************************************/ { return(filterAllMetaObjectsAssociatedWithLibrary(allMetaObjects(), library_path)); } MetaObjectVector allMetaObjectsForLibraryOwnedBy(const std::string& library_path, const ClassLoader* owner) /*****************************************************************************/ { return(filterAllMetaObjectsOwnedBy(allMetaObjectsForLibrary(library_path), owner)); } void insertMetaObjectIntoGraveyard(AbstractMetaObjectBase* meta_obj) /*****************************************************************************/ { logDebug("class_loader.class_loader_private: Inserting MetaObject (class = %s, base_class = %s, ptr = %p) into graveyard", meta_obj->className().c_str(), meta_obj->baseClassName().c_str(), meta_obj); getMetaObjectGraveyard().push_back(meta_obj); } void destroyMetaObjectsForLibrary(const std::string& library_path, FactoryMap& factories, const ClassLoader* loader) /*****************************************************************************/ { FactoryMap::iterator factory_itr = factories.begin(); while(factory_itr != factories.end()) { AbstractMetaObjectBase* meta_obj = factory_itr->second; if(meta_obj->getAssociatedLibraryPath() == library_path && meta_obj->isOwnedBy(loader)) { meta_obj->removeOwningClassLoader(loader); if(!meta_obj->isOwnedByAnybody()) { FactoryMap::iterator factory_itr_copy = factory_itr; factory_itr++; factories.erase(factory_itr_copy); //Note: map::erase does not return iterator like vector::erase does. Hence the ugliness of this code and a need for copy. Should be fixed in next C++ revision //Insert into graveyard //We remove the metaobject from its factory map, but we don't destroy it...instead it saved to //a "graveyard" to the side. This is due to our static global variable initialization problem //that causes factories to not be registered when a library is closed and then reopened. This is //because it's truly not closed due to the use of global symbol binding i.e. calling dlopen //with RTLD_GLOBAL instead of RTLD_LOCAL. We require using the former as the which is required to support //RTTI insertMetaObjectIntoGraveyard(meta_obj); } else factory_itr++; } else factory_itr++; } } void destroyMetaObjectsForLibrary(const std::string& library_path, const ClassLoader* loader) /*****************************************************************************/ { boost::recursive_mutex::scoped_lock lock(getPluginBaseToFactoryMapMapMutex()); logDebug("class_loader.class_loader_private: Removing MetaObjects associated with library %s and class loader %p from global plugin-to-factorymap map.\n", library_path.c_str(), loader); //We have to walk through all FactoryMaps to be sure BaseToFactoryMapMap& factory_map_map = getGlobalPluginBaseToFactoryMapMap(); BaseToFactoryMapMap::iterator itr; for(itr = factory_map_map.begin(); itr != factory_map_map.end(); itr++) destroyMetaObjectsForLibrary(library_path, itr->second, loader); logDebug("class_loader.class_loader_private: Metaobjects removed."); } bool areThereAnyExistingMetaObjectsForLibrary(const std::string& library_path) /*****************************************************************************/ { return(allMetaObjectsForLibrary(library_path).size() > 0); } //Loaded Library Vector manipulation /*****************************************************************************/ /*****************************************************************************/ /*****************************************************************************/ LibraryVector::iterator findLoadedLibrary(const std::string& library_path) /*****************************************************************************/ { LibraryVector& open_libraries = getLoadedLibraryVector(); LibraryVector::iterator itr; for(itr = open_libraries.begin(); itr != open_libraries.end(); itr++ ) { if(itr->first == library_path) break; } return(itr); } bool isLibraryLoadedByAnybody(const std::string& library_path) /*****************************************************************************/ { boost::recursive_mutex::scoped_lock lock(getLoadedLibraryVectorMutex()); LibraryVector& open_libraries = getLoadedLibraryVector(); LibraryVector::iterator itr = findLoadedLibrary(library_path); if(itr != open_libraries.end()) { assert(itr->second->isLoaded() == true); //Ensure Poco actually thinks the library is loaded return(true); } else return(false); }; bool isLibraryLoaded(const std::string& library_path, ClassLoader* loader) /*****************************************************************************/ { bool is_lib_loaded_by_anyone = isLibraryLoadedByAnybody(library_path); int num_meta_objs_for_lib = allMetaObjectsForLibrary(library_path).size(); int num_meta_objs_for_lib_bound_to_loader = allMetaObjectsForLibraryOwnedBy(library_path,loader).size(); bool are_meta_objs_bound_to_loader = (num_meta_objs_for_lib == 0) ? true : (num_meta_objs_for_lib_bound_to_loader <= num_meta_objs_for_lib); return(is_lib_loaded_by_anyone && are_meta_objs_bound_to_loader); } std::vector<std::string> getAllLibrariesUsedByClassLoader(const ClassLoader* loader) /*****************************************************************************/ { MetaObjectVector all_loader_meta_objs = allMetaObjectsForClassLoader(loader); std::vector<std::string> all_libs; for(unsigned int c = 0; c < all_loader_meta_objs.size(); c++) { std::string lib_path = all_loader_meta_objs.at(c)->getAssociatedLibraryPath(); if(std::find(all_libs.begin(), all_libs.end(), lib_path) == all_libs.end()) all_libs.push_back(lib_path); } return(all_libs); } //Implementation of Remaining Core plugin_private Functions /*****************************************************************************/ /*****************************************************************************/ /*****************************************************************************/ void addClassLoaderOwnerForAllExistingMetaObjectsForLibrary(const std::string& library_path, ClassLoader* loader) /*****************************************************************************/ { MetaObjectVector all_meta_objs = allMetaObjectsForLibrary(library_path); for(unsigned int c = 0; c < all_meta_objs.size(); c++) { AbstractMetaObjectBase* meta_obj = all_meta_objs.at(c); logDebug("class_loader.class_loader_private: Tagging existing MetaObject %p (base = %s, derived = %s) with class loader %p (library path = %s).", meta_obj, meta_obj->baseClassName().c_str(), meta_obj->className().c_str(), loader, loader ? loader->getLibraryPath().c_str() : "NULL"); all_meta_objs.at(c)->addOwningClassLoader(loader); } } void revivePreviouslyCreateMetaobjectsFromGraveyard(const std::string& library_path, ClassLoader* loader) /*****************************************************************************/ { boost::recursive_mutex::scoped_lock b2fmm_lock(getPluginBaseToFactoryMapMapMutex()); MetaObjectVector& graveyard = getMetaObjectGraveyard(); for(MetaObjectVector::iterator itr = graveyard.begin(); itr != graveyard.end(); itr++) { AbstractMetaObjectBase* obj = *itr; if(obj->getAssociatedLibraryPath() == library_path) { logDebug("class_loader.class_loader_private: Resurrected factory metaobject from graveyard, class = %s, base_class = %s ptr = %p...bound to ClassLoader %p (library path = %s)", obj->className().c_str(), obj->baseClassName().c_str(), obj, loader, loader ? loader->getLibraryPath().c_str() : "NULL"); obj->addOwningClassLoader(loader); assert(obj->typeidBaseClassName() != "UNSET"); FactoryMap& factory = getFactoryMapForBaseClass(obj->typeidBaseClassName()); factory[obj->className()] = obj; } } } void purgeGraveyardOfMetaobjects(const std::string& library_path, ClassLoader* loader, bool delete_objs) /*****************************************************************************/ { MetaObjectVector all_meta_objs = allMetaObjects(); boost::recursive_mutex::scoped_lock b2fmm_lock(getPluginBaseToFactoryMapMapMutex()); //Note: Lock must happen after call to allMetaObjects as that will lock MetaObjectVector& graveyard = getMetaObjectGraveyard(); MetaObjectVector::iterator itr = graveyard.begin(); while(itr != graveyard.end()) { AbstractMetaObjectBase* obj = *itr; if(obj->getAssociatedLibraryPath() == library_path) { logDebug("class_loader.class_loader_private: Purging factory metaobject from graveyard, class = %s, base_class = %s ptr = %p...bound to ClassLoader %p (library path = %s)", obj->className().c_str(), obj->baseClassName().c_str(), obj, loader, loader ? loader->getLibraryPath().c_str() : "NULL"); bool is_address_in_graveyard_same_as_global_factory_map = std::find(all_meta_objs.begin(), all_meta_objs.end(), *itr) != all_meta_objs.end(); itr = graveyard.erase(itr); if(delete_objs) { if(is_address_in_graveyard_same_as_global_factory_map) logDebug("class_loader.class_loader_private: Newly created metaobject factory in global factory map map has same address as one in graveyard -- metaobject has been purged from graveyard but not deleted."); else { assert(hasANonPurePluginLibraryBeenOpened() == false); logDebug("class_loader.class_loader_private: Also destroying metaobject %p (class = %s, base_class = %s, library_path = %s) in addition to purging it from graveyard.", obj, obj->className().c_str(), obj->baseClassName().c_str(), obj->getAssociatedLibraryPath().c_str()); delete(obj); //Note: This is the only place where metaobjects can be destroyed } } } else itr++; } } void loadLibrary(const std::string& library_path, ClassLoader* loader) /*****************************************************************************/ { static boost::recursive_mutex loader_mutex; logDebug("class_loader.class_loader_private: Attempting to load library %s on behalf of ClassLoader handle %p...\n", library_path.c_str(), loader); boost::recursive_mutex::scoped_lock loader_lock(loader_mutex); //If it's already open, just update existing metaobjects to have an additional owner. if(isLibraryLoadedByAnybody(library_path)) { boost::recursive_mutex::scoped_lock lock(getPluginBaseToFactoryMapMapMutex()); logDebug("class_loader.class_loader_private: Library already in memory, but binding existing MetaObjects to loader if necesesary.\n"); addClassLoaderOwnerForAllExistingMetaObjectsForLibrary(library_path, loader); return; } Poco::SharedLibrary* library_handle = NULL; { try { setCurrentlyActiveClassLoader(loader); setCurrentlyLoadingLibraryName(library_path); library_handle = new Poco::SharedLibrary(library_path); } catch(const Poco::LibraryLoadException& e) { setCurrentlyLoadingLibraryName(""); setCurrentlyActiveClassLoader(NULL); throw(class_loader::LibraryLoadException("Could not load library (Poco exception = " + std::string(e.message()) + ")")); } catch(const Poco::LibraryAlreadyLoadedException& e) { setCurrentlyLoadingLibraryName(""); setCurrentlyActiveClassLoader(NULL); throw(class_loader::LibraryLoadException("Library already loaded (Poco exception = " + std::string(e.message()) + ")")); } catch(const Poco::NotFoundException& e) { setCurrentlyLoadingLibraryName(""); setCurrentlyActiveClassLoader(NULL); throw(class_loader::LibraryLoadException("Library not found (Poco exception = " + std::string(e.message()) + ")")); } setCurrentlyLoadingLibraryName(""); setCurrentlyActiveClassLoader(NULL); } assert(library_handle != NULL); logDebug("class_loader.class_loader_private: Successfully loaded library %s into memory (Poco::SharedLibrary handle = %p).", library_path.c_str(), library_handle); //Graveyard scenario unsigned int num_lib_objs = allMetaObjectsForLibrary(library_path).size(); if(num_lib_objs == 0) { logDebug("class_loader.class_loader_private: Though the library %s was just loaded, it seems no factory metaobjects were registered. Checking factory graveyard for previously loaded metaobjects...", library_path.c_str()); revivePreviouslyCreateMetaobjectsFromGraveyard(library_path, loader); purgeGraveyardOfMetaobjects(library_path, loader, false); //Note: The 'false' indicates we don't want to invoke delete on the metaobject } else { logDebug("class_loader.class_loader_private: Library %s generated new factory metaobjects on load. Destroying graveyarded objects from previous loads...", library_path.c_str()); purgeGraveyardOfMetaobjects(library_path, loader, true); } //Insert library into global loaded library vectory boost::recursive_mutex::scoped_lock llv_lock(getLoadedLibraryVectorMutex()); LibraryVector& open_libraries = getLoadedLibraryVector(); open_libraries.push_back(LibraryPair(library_path, library_handle)); //Note: Poco::SharedLibrary automatically calls load() when library passed to constructor } void unloadLibrary(const std::string& library_path, ClassLoader* loader) /*****************************************************************************/ { if(hasANonPurePluginLibraryBeenOpened()) { logDebug("class_loader.class_loader_private: Cannot unload %s or ANY other library as a non-pure plugin library was opened. As class_loader has no idea which libraries class factories were exported from, it can safely close any library without potentially unlinking symbols that are still actively being used. You must refactor your plugin libraries to be made exclusively of plugins in order for this error to stop happening.", library_path.c_str()); } else { logDebug("class_loader.class_loader_private: Unloading library %s on behalf of ClassLoader %p...", library_path.c_str(), loader); boost::recursive_mutex::scoped_lock lock(getLoadedLibraryVectorMutex()); LibraryVector& open_libraries = getLoadedLibraryVector(); LibraryVector::iterator itr = findLoadedLibrary(library_path); if(itr != open_libraries.end()) { Poco::SharedLibrary* library = itr->second; std::string library_path = itr->first; try { destroyMetaObjectsForLibrary(library_path, loader); //Remove from loaded library list as well if no more factories associated with said library if(!areThereAnyExistingMetaObjectsForLibrary(library_path)) { logDebug("class_loader.class_loader_private: There are no more MetaObjects left for %s so unloading library and removing from loaded library vector.\n", library_path.c_str()); library->unload(); assert(library->isLoaded() == false); delete(library); itr = open_libraries.erase(itr); } else logDebug("class_loader.class_loader_private: MetaObjects still remain in memory meaning other ClassLoaders are still using library, keeping library %s open.", library_path.c_str()); return; } catch(const Poco::RuntimeException& e) { delete(library); throw(class_loader::LibraryUnloadException("Could not unload library (Poco exception = " + std::string(e.message()) + ")")); } } throw(class_loader::LibraryUnloadException("Attempt to unload library that class_loader is unaware of.")); } } //Other /*****************************************************************************/ /*****************************************************************************/ /*****************************************************************************/ void printDebugInfoToScreen() /*****************************************************************************/ { printf("*******************************************************************************\n"); printf("***** class_loader_private DEBUG INFORMATION *****\n"); printf("*******************************************************************************\n"); printf("OPEN LIBRARIES IN MEMORY:\n"); printf("--------------------------------------------------------------------------------\n"); boost::recursive_mutex::scoped_lock lock(getLoadedLibraryVectorMutex()); LibraryVector libs = getLoadedLibraryVector(); for(unsigned int c = 0; c < libs.size(); c++) printf("Open library %i = %s (Poco SharedLibrary handle = %p)\n", c, (libs.at(c)).first.c_str(), (libs.at(c)).second); printf("METAOBJECTS (i.e. FACTORIES) IN MEMORY:\n"); printf("--------------------------------------------------------------------------------\n"); MetaObjectVector meta_objs = allMetaObjects(); for(unsigned int c = 0; c < meta_objs.size(); c++) { AbstractMetaObjectBase* obj = meta_objs.at(c); printf("Metaobject %i (ptr = %p):\n TypeId = %s\n Associated Library = %s\n", c, obj, (typeid(*obj).name()), obj->getAssociatedLibraryPath().c_str()); ClassLoaderVector loaders = obj->getAssociatedClassLoaders(); for(unsigned int i = 0; i < loaders.size(); i++) printf(" Associated Loader %i = %p\n", i, loaders.at(i)); printf("--------------------------------------------------------------------------------\n"); } printf("********************************** END DEBUG **********************************\n"); printf("*******************************************************************************\n\n"); } } //End namespace class_loader_private } //End namespace class_loader
0
apollo_public_repos/apollo-platform/ros/class_loader
apollo_public_repos/apollo-platform/ros/class_loader/src/class_loader.pc.in
prefix=@CMAKE_INSTALL_PREFIX@ exec_prefix=@CMAKE_INSTALL_PREFIX@ libdir=${prefix}/lib includedir=${prefix}/include Name: @TARGET_NAME@ Description: @PROJECT_DESCRIPTION@ Version: @PROJECT_VERSION@ Requires: @PKGCONFIG_REQUIRES@ Libs: -L${libdir} -l@TARGET_NAME@ @PKGCONFIG_LIBS@ Cflags: -I${includedir} @PKGCONFIG_CFLAGS@
0
apollo_public_repos/apollo-platform/ros/class_loader
apollo_public_repos/apollo-platform/ros/class_loader/src/meta_object.cpp
/* * 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 the 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 "class_loader/meta_object.h" #include "class_loader/class_loader.h" namespace class_loader { namespace class_loader_private { AbstractMetaObjectBase::AbstractMetaObjectBase(const std::string& class_name, const std::string& base_class_name) : associated_library_path_("Unknown"), base_class_name_(base_class_name), class_name_(class_name), typeid_base_class_name_("UNSET") /*****************************************************************************/ { logDebug("class_loader.class_loader_private.AbstractMetaObjectBase: Creating MetaObject %p (base = %s, derived = %s, library path = %s)", this, baseClassName().c_str(), className().c_str(), getAssociatedLibraryPath().c_str()); } AbstractMetaObjectBase::~AbstractMetaObjectBase() /*****************************************************************************/ { logDebug("class_loader.class_loader_private.AbstractMetaObjectBase: Destroying MetaObject %p (base = %s, derived = %s, library path = %s)", this, baseClassName().c_str(), className().c_str(), getAssociatedLibraryPath().c_str()); } std::string AbstractMetaObjectBase::className() const /*****************************************************************************/ { return class_name_; } std::string AbstractMetaObjectBase::baseClassName() const /*****************************************************************************/ { return base_class_name_; } std::string AbstractMetaObjectBase::typeidBaseClassName() const /*****************************************************************************/ { return typeid_base_class_name_; } std::string AbstractMetaObjectBase::getAssociatedLibraryPath() /*****************************************************************************/ { return(associated_library_path_); } void AbstractMetaObjectBase::setAssociatedLibraryPath(std::string library_path) /*****************************************************************************/ { associated_library_path_ = library_path; } void AbstractMetaObjectBase::addOwningClassLoader(ClassLoader* loader) /*****************************************************************************/ { ClassLoaderVector& v = associated_class_loaders_; if(std::find(v.begin(), v.end(), loader) == v.end()) v.push_back(loader); } void AbstractMetaObjectBase::removeOwningClassLoader(const ClassLoader* loader) /*****************************************************************************/ { ClassLoaderVector& v = associated_class_loaders_; ClassLoaderVector::iterator itr = std::find(v.begin(), v.end(), loader); if(itr != v.end()) v.erase(itr); } bool AbstractMetaObjectBase::isOwnedBy(const ClassLoader* loader) /*****************************************************************************/ { ClassLoaderVector& v = associated_class_loaders_; ClassLoaderVector::iterator itr = std::find(v.begin(), v.end(), loader); return(itr != v.end()); } bool AbstractMetaObjectBase::isOwnedByAnybody() /*****************************************************************************/ { return(associated_class_loaders_.size() > 0); } ClassLoaderVector AbstractMetaObjectBase::getAssociatedClassLoaders() /*****************************************************************************/ { return(associated_class_loaders_); } } }
0
apollo_public_repos/apollo-platform/ros/geometry
apollo_public_repos/apollo-platform/ros/geometry/tf_conversions/index.rst
tf_conversions ============== .. toctree:: :maxdepth: 2 PoseMath -------- PoseMath is a utility that makes it easy to work with :class:`PyKDL.Frame`'s. It can work with poses from a variety of sources: :meth:`tf.Transformer.lookupTransform`, :mod:`opencv` and ROS messages. It has utility functions to convert between these types and the :class:`PyKDL.Frame` pose representation. .. doctest:: :options: -ELLIPSIS, +NORMALIZE_WHITESPACE >>> from geometry_msgs.msg import Pose >>> import tf_conversions.posemath as pm >>> import PyKDL >>> >>> msg = Pose() >>> msg.position.x = 7.0 >>> msg.orientation.w = 1.0 >>> >>> frame = PyKDL.Frame(PyKDL.Rotation.RPY(2, 0, 1), PyKDL.Vector(1,2,4)) >>> >>> res = pm.toTf(pm.fromMsg(msg) * frame) >>> print res ((8.0, 2.0, 4.0), (0.73846026260412856, 0.40342268011133486, 0.25903472399992566, 0.4741598817790379)) .. automodule:: tf_conversions.posemath :members: fromTf, fromMsg, toMsg, fromMatrix, toMatrix, fromCameraParams Indices and tables ================== * :ref:`genindex` * :ref:`modindex` * :ref:`search`
0
apollo_public_repos/apollo-platform/ros/geometry
apollo_public_repos/apollo-platform/ros/geometry/tf_conversions/CMakeLists.txt
cmake_minimum_required(VERSION 2.8) project(tf_conversions) find_package(orocos_kdl REQUIRED) find_package(catkin REQUIRED cmake_modules geometry_msgs kdl_conversions tf) find_package(Eigen REQUIRED) catkin_python_setup() catkin_package( INCLUDE_DIRS include LIBRARIES ${PROJECT_NAME} DEPENDS Eigen orocos_kdl CATKIN_DEPENDS geometry_msgs kdl_conversions tf ) include_directories(SYSTEM ${EIGEN_INCLUDE_DIRS} ${orocos_kdl_INCLUDE_DIRS}) include_directories(include ${catkin_INCLUDE_DIRS}) # Needed due to no full filename in orocos_kdl pkg-config export link_directories(${orocos_kdl_LIBRARY_DIRS}) add_library(${PROJECT_NAME} src/tf_kdl.cpp src/tf_eigen.cpp ) add_dependencies(${PROJECT_NAME} geometry_msgs_gencpp) target_link_libraries(${PROJECT_NAME} ${catkin_LIBRARIES} ${orocos_kdl_LIBRARIES}) # Tests if(CATKIN_ENABLE_TESTING) catkin_add_gtest(test_eigen_tf test/test_eigen_tf.cpp) target_link_libraries(test_eigen_tf ${PROJECT_NAME} ${orocos_kdl_LIBRARIES}) catkin_add_gtest(test_kdl_tf test/test_kdl_tf.cpp) target_link_libraries(test_kdl_tf ${PROJECT_NAME} ${orocos_kdl_LIBRARIES}) catkin_add_nosetests(test/posemath.py) endif() install(DIRECTORY include/${PROJECT_NAME}/ DESTINATION ${CATKIN_PACKAGE_INCLUDE_DESTINATION}) install(TARGETS ${PROJECT_NAME} DESTINATION ${CATKIN_PACKAGE_LIB_DESTINATION})
0
apollo_public_repos/apollo-platform/ros/geometry
apollo_public_repos/apollo-platform/ros/geometry/tf_conversions/package.xml
<package> <name>tf_conversions</name> <version>1.11.8</version> <description> This package contains a set of conversion functions to convert common tf datatypes (point, vector, pose, etc) into semantically identical datatypes used by other libraries. The conversion functions make it easier for users of the transform library (tf) to work with the datatype of their choice. Currently this package has support for the Kinematics and Dynamics Library (KDL) and the Eigen matrix library. This package is stable, and will get integrated into tf in the next major release cycle (see roadmap). </description> <author>Tully Foote</author> <maintainer email="[email protected]">Tully Foote</maintainer> <license>BSD</license> <url>http://www.ros.org/wiki/tf_conversions</url> <buildtool_depend version_gte="0.5.68">catkin</buildtool_depend> <build_depend>cmake_modules</build_depend> <build_depend>eigen</build_depend> <build_depend>geometry_msgs</build_depend> <build_depend>kdl_conversions</build_depend> <build_depend>orocos_kdl</build_depend> <build_depend>tf</build_depend> <run_depend>eigen</run_depend> <run_depend>geometry_msgs</run_depend> <run_depend>kdl_conversions</run_depend> <run_depend>orocos_kdl</run_depend> <run_depend>python_orocos_kdl</run_depend> <run_depend>tf</run_depend> <export> <rosdoc config="rosdoc.yaml" /> </export> </package>
0
apollo_public_repos/apollo-platform/ros/geometry
apollo_public_repos/apollo-platform/ros/geometry/tf_conversions/conf.py
# -*- coding: utf-8 -*- # # tf documentation build configuration file, created by # sphinx-quickstart on Mon Jun 1 14:21:53 2009. # # This file is execfile()d with the current directory set to its containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. import sys, os # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. #sys.path.append(os.path.abspath('.')) # -- General configuration ----------------------------------------------------- # Add any Sphinx extension module names here, as strings. They can be extensions # coming with Sphinx (named 'sphinx.ext.*') or your custom ones. extensions = ['sphinx.ext.autodoc', 'sphinx.ext.doctest', 'sphinx.ext.intersphinx', 'sphinx.ext.pngmath'] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix of source filenames. source_suffix = '.rst' # The encoding of source files. #source_encoding = 'utf-8' # The master toctree document. master_doc = 'index' # General information about the project. project = u'tf_conversions' copyright = u'2010, Willow Garage, Inc.' # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version. version = '0.1' # The full version, including alpha/beta/rc tags. release = '0.1.0' # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. #language = None # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: #today = '' # Else, today_fmt is used as the format for a strftime call. #today_fmt = '%B %d, %Y' # List of documents that shouldn't be included in the build. #unused_docs = [] # List of directories, relative to source directory, that shouldn't be searched # for source files. exclude_trees = ['_build'] # The reST default role (used for this markup: `text`) to use for all documents. #default_role = None # If true, '()' will be appended to :func: etc. cross-reference text. #add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). #add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. #show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # A list of ignored prefixes for module index sorting. #modindex_common_prefix = [] # -- Options for HTML output --------------------------------------------------- # The theme to use for HTML and HTML Help pages. Major themes that come with # Sphinx are currently 'default' and 'sphinxdoc'. html_theme = 'default' # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. #html_theme_options = {} # Add any paths that contain custom themes here, relative to this directory. #html_theme_path = [] # The name for this set of Sphinx documents. If None, it defaults to # "<project> v<release> documentation". #html_title = None # A shorter title for the navigation bar. Default is the same as html_title. #html_short_title = None # The name of an image file (relative to this directory) to place at the top # of the sidebar. #html_logo = None # The name of an image file (within the static path) to use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. #html_favicon = None # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ['_static'] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. #html_last_updated_fmt = '%b %d, %Y' # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. #html_use_smartypants = True # Custom sidebar templates, maps document names to template names. #html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # template names. #html_additional_pages = {} # If false, no module index is generated. #html_use_modindex = True # If false, no index is generated. #html_use_index = True # If true, the index is split into individual pages for each letter. #html_split_index = False # If true, links to the reST sources are added to the pages. #html_show_sourcelink = True # If true, an OpenSearch description file will be output, and all pages will # contain a <link> tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. #html_use_opensearch = '' # If nonempty, this is the file name suffix for HTML files (e.g. ".xhtml"). #html_file_suffix = '' # Output file base name for HTML help builder. htmlhelp_basename = 'tfdoc' # -- Options for LaTeX output -------------------------------------------------- # The paper size ('letter' or 'a4'). #latex_paper_size = 'letter' # The font size ('10pt', '11pt' or '12pt'). #latex_font_size = '10pt' # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, author, documentclass [howto/manual]). latex_documents = [ ('index', 'tf_conversions.tex', u'stereo\\_utils Documentation', u'James Bowman', 'manual'), ] # The name of an image file (relative to this directory) to place at the top of # the title page. #latex_logo = None # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. #latex_use_parts = False # Additional stuff for the LaTeX preamble. #latex_preamble = '' # Documents to append as an appendix to all manuals. #latex_appendices = [] # If false, no module index is generated. #latex_use_modindex = True # Example configuration for intersphinx: refer to the Python standard library. intersphinx_mapping = { 'http://docs.python.org/': None, 'http://docs.opencv.org/3.0-last-rst/': None, 'http://www.ros.org/doc/api/tf/html/python/' : None, 'http://docs.scipy.org/doc/numpy' : None, 'http://www.ros.org/doc/api/kdl/html/python/' : None }
0
apollo_public_repos/apollo-platform/ros/geometry
apollo_public_repos/apollo-platform/ros/geometry/tf_conversions/rosdoc.yaml
- builder: rosmake - builder: sphinx name: Python API 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/geometry
apollo_public_repos/apollo-platform/ros/geometry/tf_conversions/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=['tf_conversions'], package_dir={'': 'src'}, requires=['geometry_msgs', 'rospy', 'tf'] ) setup(**d)
0
apollo_public_repos/apollo-platform/ros/geometry
apollo_public_repos/apollo-platform/ros/geometry/tf_conversions/.tar
{!!python/unicode 'url': 'https://github.com/ros-gbp/geometry-release/archive/release/indigo/tf_conversions/1.11.8-0.tar.gz', !!python/unicode 'version': geometry-release-release-indigo-tf_conversions-1.11.8-0}
0
apollo_public_repos/apollo-platform/ros/geometry
apollo_public_repos/apollo-platform/ros/geometry/tf_conversions/CHANGELOG.rst
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Changelog for package tf_conversions ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 1.11.8 (2016-03-04) ------------------- * tf_conversions: Add conversion functions for Eigen::Isometry3d * Remove outdated manifest loading in python files * Contributors: Maarten de Vries, Michael Hwang 1.11.7 (2015-04-21) ------------------- * Fixed Vector3 documentation * Contributors: Jackie Kay 1.11.6 (2015-03-25) ------------------- 1.11.5 (2015-03-17) ------------------- 1.11.4 (2014-12-23) ------------------- * Update package.xml * Contributors: David Lu!! 1.11.3 (2014-05-07) ------------------- 1.11.2 (2014-02-25) ------------------- * fixing eigen usage in tf_conversions * Contributors: Tully Foote 1.11.1 (2014-02-23) ------------------- 1.11.0 (2014-02-14) ------------------- 1.10.8 (2014-02-01) ------------------- * add missing runtime dependency on python_orocos_kdl for the pyKDL * Contributors: Tully Foote 1.10.7 (2013-12-27) ------------------- * Fix build error in tf_conversions with orocos_kdl dependency Fixes `#45 <https://github.com/ros/geometry/issues/45>`_ * Contributors: Tessa Lau 1.10.6 (2013-08-28) ------------------- 1.10.5 (2013-07-19) ------------------- 1.10.4 (2013-07-11) ------------------- 1.10.3 (2013-07-09) ------------------- * calling out versioned catkin requirement for CATKIN_ENABLE_TESTING 1.10.2 (2013-07-09) ------------------- * adding unit test if CATKIN_ENABLE_TESTING statements for tf_conversions to make the whole repo compliant. 1.10.1 (2013-07-05) ------------------- 1.10.0 (2013-07-05) ------------------- * fixing unit tests * fixing kdl linking 1.9.31 (2013-04-18 18:16) ------------------------- 1.9.30 (2013-04-18 16:26) ------------------------- 1.9.29 (2013-01-13) ------------------- 1.9.28 (2013-01-02) ------------------- * add missing setup.py 1.9.27 (2012-12-21) ------------------- * added license headers to various files 1.9.26 (2012-12-14) ------------------- * add missing dep to catkin 1.9.25 (2012-12-13) ------------------- 1.9.24 (2012-12-11) ------------------- * Version 1.9.24 * Fixes to CMakeLists.txt's while building from source 1.9.23 (2012-11-22) ------------------- * Releaseing version 1.9.23 1.9.22 (2012-11-04 09:14) ------------------------- * more backwards compatible conversions and an include to make sure it gets into the old header location 1.9.21 (2012-11-04 01:19) ------------------------- * filling out deprecated functions for backwards compatability 1.9.20 (2012-11-02) ------------------- 1.9.19 (2012-10-31) ------------------- * Removed deprecated 'brief' attribute from <description> tags. 1.9.18 (2012-10-16) ------------------- 1.9.17 (2012-10-02) ------------------- * fix several dependency issues 1.9.16 (2012-09-29) ------------------- * adding geometry metapackage and updating to 1.9.16 1.9.15 (2012-09-30) ------------------- * fix a few dependency/catkin problems * remove old API files * comply to the new catkin API 1.9.14 (2012-09-18) ------------------- 1.9.13 (2012-09-17) ------------------- * update manifests 1.9.12 (2012-09-16) ------------------- 1.9.11 (2012-09-14 22:49) ------------------------- 1.9.10 (2012-09-14 22:30) ------------------------- 1.9.9 (2012-09-11) ------------------ * update depends * minor patches for new build system 1.9.8 (2012-09-03) ------------------ 1.9.7 (2012-08-10 12:19) ------------------------ * minor build fixes * fixed some minor errors from last commit * completed set of eigen conversions; added KDL conversions * adding additional conversion functions 1.9.6 (2012-08-02 19:59) ------------------------ 1.9.5 (2012-08-02 19:48) ------------------------ 1.9.4 (2012-08-02 18:29) ------------------------ 1.9.3 (2012-08-02 18:28) ------------------------ * forgot to install some things * also using DEPENDS 1.9.2 (2012-08-01 21:05) ------------------------ * make sure the tf target depends on the messages (and clean some include_directories too) 1.9.1 (2012-08-01 19:16) ------------------------ * install manifest.xml 1.9.0 (2012-08-01 18:52) ------------------------ * catkin build system * successfully running rosrun tf bullet_migration_sed.py and testing afterwords * eigen to rosdep from dependency * removing eigen dependency as it's now system installed * add missing empty_listener.cpp file * compiling with eigen3 * more extensive search * applying patch from sed script for eigen3 compatability * tests for tf_kdl and fixes for tf_kdl based on tests * add pykdl to example * link to kdl pages * Added VectorEigenToTF and RotationEigenToTF to tf_conversions * returning to camelCase for consistency with tf and pykdl * converting from camelCase to under_scored methods for python style * Added Ubuntu platform tags * removing pykdl finishing series of commits for `#4039 <https://github.com/ros/geometry/issues/4039>`_ * promoting pykdl index.rst * removing index.rst for replacing * posemath using kdl promoted * reverting change in test * passing test with kdl_posemath.py copied to src/posemath.py * Corrected module to tf_conversions * Improved pose comparison in test_roundtrip * `#4039 <https://github.com/ros/geometry/issues/4039>`_ original posemath now in tf_conversions * Enable posemath unit test, `#4039 <https://github.com/ros/geometry/issues/4039>`_ * Moved PoseMath from tf to tf_conversions, `#4039 <https://github.com/ros/geometry/issues/4039>`_ * PyKDL based PoseMath, `#4039 <https://github.com/ros/geometry/issues/4039>`_ * fixes for `#3915 <https://github.com/ros/geometry/issues/3915>`_ into trunk * Remove use of deprecated rosbuild macros * tf conversions is doc reviewed * api cleared * add list of supported data types * deprecate addDelta function because it is not a conversion * add api doc to tf_conversions * update documentation * migration part 1
0
apollo_public_repos/apollo-platform/ros/geometry/tf_conversions
apollo_public_repos/apollo-platform/ros/geometry/tf_conversions/test/posemath.py
import rostest import rospy import numpy import unittest import sys from tf import Transformer import tf_conversions.posemath as pm from geometry_msgs.msg import TransformStamped from PyKDL import Frame class TestPoseMath(unittest.TestCase): def setUp(self): pass def test_fromTf(self): transformer = Transformer(True, rospy.Duration(10.0)) m = TransformStamped() m.header.frame_id = 'wim' m.child_frame_id = 'james' m.transform.translation.x = 2.71828183 m.transform.rotation.w = 1.0 transformer.setTransform(m) b = pm.fromTf(transformer.lookupTransform('wim', 'james', rospy.Time(0))) def test_roundtrip(self): c = Frame() d = pm.fromMsg(pm.toMsg(c)) self.assertEqual(repr(c), repr(d)) d = pm.fromMatrix(pm.toMatrix(c)) self.assertEqual(repr(c), repr(d)) d = pm.fromTf(pm.toTf(c)) self.assertEqual(repr(c), repr(d)) if __name__ == '__main__': if len(sys.argv) == 1 or sys.argv[1].startswith('--gtest_output'): rostest.unitrun('tf', 'directed', TestPoseMath) else: suite = unittest.TestSuite() suite.addTest(TestPoseMath(sys.argv[1])) unittest.TextTestRunner(verbosity=2).run(suite)
0
apollo_public_repos/apollo-platform/ros/geometry/tf_conversions
apollo_public_repos/apollo-platform/ros/geometry/tf_conversions/test/test_kdl_tf.cpp
/* * 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, 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 <time.h> #include <tf_conversions/tf_kdl.h> #include <gtest/gtest.h> using namespace tf; double gen_rand(double min, double max) { int rand_num = rand()%100+1; double result = min + (double)((max-min)*rand_num)/101.0; return result; } TEST(TFKDLConversions, tf_kdl_vector) { tf::Vector3 t; t[0] = gen_rand(-10,10); t[1] = gen_rand(-10,10); t[2] = gen_rand(-10,10); KDL::Vector k; VectorTFToKDL(t,k); ASSERT_NEAR(t[0],k[0],1e-6); ASSERT_NEAR(t[1],k[1],1e-6); ASSERT_NEAR(t[2],k[2],1e-6); } TEST(TFKDLConversions, tf_kdl_rotation) { tf::Quaternion t; t[0] = gen_rand(-1.0,1.0); t[1] = gen_rand(-1.0,1.0); t[2] = gen_rand(-1.0,1.0); t[3] = gen_rand(-1.0,1.0); t.normalize(); KDL::Rotation k; QuaternionTFToKDL(t,k); double x,y,z,w; k.GetQuaternion(x,y,z,w); ASSERT_NEAR(fabs(t[0]),fabs(x),1e-6); ASSERT_NEAR(fabs(t[1]),fabs(y),1e-6); ASSERT_NEAR(fabs(t[2]),fabs(z),1e-6); ASSERT_NEAR(fabs(t[3]),fabs(w),1e-6); ASSERT_NEAR(t[0]*t[1]*t[2]*t[3],x*y*z*w,1e-6); } TEST(TFKDLConversions, tf_kdl_transform) { tf::Transform t; tf::Quaternion tq; tq[0] = gen_rand(-1.0,1.0); tq[1] = gen_rand(-1.0,1.0); tq[2] = gen_rand(-1.0,1.0); tq[3] = gen_rand(-1.0,1.0); tq.normalize(); t.setOrigin(tf::Vector3(gen_rand(-10,10),gen_rand(-10,10),gen_rand(-10,10))); t.setRotation(tq); //test tf->kdl KDL::Frame k; TransformTFToKDL(t,k); for(int i=0; i < 3; i++) { ASSERT_NEAR(t.getOrigin()[i],k.p[i],1e-6); for(int j=0; j < 3; j++) { ASSERT_NEAR(t.getBasis()[i][j],k.M(i,j),1e-6); } } //test kdl->tf tf::Transform r; TransformKDLToTF(k,r); for(int i=0; i< 3; i++) { ASSERT_NEAR(t.getOrigin()[i],r.getOrigin()[i],1e-6); for(int j=0; j < 3; j++) { ASSERT_NEAR(t.getBasis()[i][j],r.getBasis()[i][j],1e-6); } } } TEST(TFKDLConversions, tf_kdl_pose) { tf::Pose t; tf::Quaternion tq; tq[0] = gen_rand(-1.0,1.0); tq[1] = gen_rand(-1.0,1.0); tq[2] = gen_rand(-1.0,1.0); tq[3] = gen_rand(-1.0,1.0); tq.normalize(); t.setOrigin(tf::Vector3(gen_rand(-10,10),gen_rand(-10,10),gen_rand(-10,10))); t.setRotation(tq); //test tf->kdl KDL::Frame k; PoseTFToKDL(t,k); for(int i=0; i < 3; i++) { ASSERT_NEAR(t.getOrigin()[i],k.p[i],1e-6); for(int j=0; j < 3; j++) { ASSERT_NEAR(t.getBasis()[i][j],k.M(i,j),1e-6); } } //test kdl->tf tf::Pose r; PoseKDLToTF(k,r); for(int i=0; i< 3; i++) { ASSERT_NEAR(t.getOrigin()[i],r.getOrigin()[i],1e-6); for(int j=0; j < 3; j++) { ASSERT_NEAR(t.getBasis()[i][j],r.getBasis()[i][j],1e-6); } } } TEST(TFKDLConversions, msg_kdl_twist) { geometry_msgs::Twist m; m.linear.x = gen_rand(-10,10); m.linear.y = gen_rand(-10,10); m.linear.z = gen_rand(-10,10); m.angular.x = gen_rand(-10,10); m.angular.y = gen_rand(-10,10); m.angular.y = gen_rand(-10,10); //test msg->kdl KDL::Twist t; TwistMsgToKDL(m,t); ASSERT_NEAR(m.linear.x,t.vel[0],1e-6); ASSERT_NEAR(m.linear.y,t.vel[1],1e-6); ASSERT_NEAR(m.linear.z,t.vel[2],1e-6); ASSERT_NEAR(m.angular.x,t.rot[0],1e-6); ASSERT_NEAR(m.angular.y,t.rot[1],1e-6); ASSERT_NEAR(m.angular.z,t.rot[2],1e-6); //test msg->kdl geometry_msgs::Twist r; TwistKDLToMsg(t,r); ASSERT_NEAR(r.linear.x,t.vel[0],1e-6); ASSERT_NEAR(r.linear.y,t.vel[1],1e-6); ASSERT_NEAR(r.linear.z,t.vel[2],1e-6); ASSERT_NEAR(r.angular.x,t.rot[0],1e-6); ASSERT_NEAR(r.angular.y,t.rot[1],1e-6); ASSERT_NEAR(r.angular.z,t.rot[2],1e-6); } int main(int argc, char **argv){ /* initialize random seed: */ srand ( time(NULL) ); testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
0
apollo_public_repos/apollo-platform/ros/geometry/tf_conversions
apollo_public_repos/apollo-platform/ros/geometry/tf_conversions/test/test_eigen_tf.cpp
/* * 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, 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 <time.h> #include <tf_conversions/tf_eigen.h> #include <gtest/gtest.h> using namespace tf; double gen_rand(double min, double max) { int rand_num = rand()%100+1; double result = min + (double)((max-min)*rand_num)/101.0; return result; } TEST(TFEigenConversions, tf_eigen_vector) { tf::Vector3 t; t[0] = gen_rand(-10,10); t[1] = gen_rand(-10,10); t[2] = gen_rand(-10,10); Eigen::Vector3d k; vectorTFToEigen(t,k); ASSERT_NEAR(t[0],k[0],1e-6); ASSERT_NEAR(t[1],k[1],1e-6); ASSERT_NEAR(t[2],k[2],1e-6); } TEST(TFEigenConversions, tf_eigen_quaternion) { tf::Quaternion t; t[0] = gen_rand(-1.0,1.0); t[1] = gen_rand(-1.0,1.0); t[2] = gen_rand(-1.0,1.0); t[3] = gen_rand(-1.0,1.0); t.normalize(); Eigen::Quaterniond k; quaternionTFToEigen(t,k); ASSERT_NEAR(t[0],k.coeffs()(0),1e-6); ASSERT_NEAR(t[1],k.coeffs()(1),1e-6); ASSERT_NEAR(t[2],k.coeffs()(2),1e-6); ASSERT_NEAR(t[3],k.coeffs()(3),1e-6); ASSERT_NEAR(k.norm(),1.0,1e-10); } TEST(TFEigenConversions, tf_eigen_transform) { tf::Transform t; tf::Quaternion tq; tq[0] = gen_rand(-1.0,1.0); tq[1] = gen_rand(-1.0,1.0); tq[2] = gen_rand(-1.0,1.0); tq[3] = gen_rand(-1.0,1.0); tq.normalize(); t.setOrigin(tf::Vector3(gen_rand(-10,10),gen_rand(-10,10),gen_rand(-10,10))); t.setRotation(tq); Eigen::Affine3d affine; Eigen::Isometry3d isometry; transformTFToEigen(t, affine); transformTFToEigen(t, isometry); for(int i=0; i < 3; i++) { ASSERT_NEAR(t.getOrigin()[i],affine.matrix()(i,3),1e-6); ASSERT_NEAR(t.getOrigin()[i],isometry.matrix()(i,3),1e-6); for(int j=0; j < 3; j++) { ASSERT_NEAR(t.getBasis()[i][j],affine.matrix()(i,j),1e-6); ASSERT_NEAR(t.getBasis()[i][j],isometry.matrix()(i,j),1e-6); } } for (int col = 0 ; col < 3; col ++) { ASSERT_NEAR(affine.matrix()(3, col), 0, 1e-6); ASSERT_NEAR(isometry.matrix()(3, col), 0, 1e-6); } ASSERT_NEAR(affine.matrix()(3,3), 1, 1e-6); ASSERT_NEAR(isometry.matrix()(3,3), 1, 1e-6); } TEST(TFEigenConversions, eigen_tf_transform) { tf::Transform t1; tf::Transform t2; Eigen::Affine3d affine; Eigen::Isometry3d isometry; Eigen::Quaterniond kq; kq.coeffs()(0) = gen_rand(-1.0,1.0); kq.coeffs()(1) = gen_rand(-1.0,1.0); kq.coeffs()(2) = gen_rand(-1.0,1.0); kq.coeffs()(3) = gen_rand(-1.0,1.0); kq.normalize(); isometry.translate(Eigen::Vector3d(gen_rand(-10,10),gen_rand(-10,10),gen_rand(-10,10))); isometry.rotate(kq); affine = isometry; transformEigenToTF(affine,t1); transformEigenToTF(isometry,t2); for(int i=0; i < 3; i++) { ASSERT_NEAR(t1.getOrigin()[i],affine.matrix()(i,3),1e-6); ASSERT_NEAR(t2.getOrigin()[i],isometry.matrix()(i,3),1e-6); for(int j=0; j < 3; j++) { ASSERT_NEAR(t1.getBasis()[i][j],affine.matrix()(i,j),1e-6); ASSERT_NEAR(t2.getBasis()[i][j],isometry.matrix()(i,j),1e-6); } } } int main(int argc, char **argv){ /* initialize random seed: */ srand ( time(NULL) ); testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
0
apollo_public_repos/apollo-platform/ros/geometry/tf_conversions/include
apollo_public_repos/apollo-platform/ros/geometry/tf_conversions/include/tf_conversions/mainpage.dox
/** \mainpage @htmlinclude manifest.html The tf conversions package provide methods to convert between datatypes used by tf, and semantically identical data types of other libraries. The package now supports KDL and Eigen. The supported KDL data types are: \li Frame \li Vector \li Rotation \li Twist The supported Eigen data types are: \li Affine3d \li Vector3d \li Quaterniond For a complete list of available conversion methods, follow this link: tf */
0
apollo_public_repos/apollo-platform/ros/geometry/tf_conversions/include
apollo_public_repos/apollo-platform/ros/geometry/tf_conversions/include/tf_conversions/tf_eigen.h
/* * Copyright (c) 2009-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 the 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. */ // Author: Adam Leeper (and others) #ifndef CONVERSIONS_TF_EIGEN_H #define CONVERSIONS_TF_EIGEN_H #include "tf/transform_datatypes.h" #include "Eigen/Core" #include "Eigen/Geometry" namespace tf { /// Converts a tf Matrix3x3 into an Eigen Quaternion void matrixTFToEigen(const tf::Matrix3x3 &t, Eigen::Matrix3d &e); /// Converts an Eigen Quaternion into a tf Matrix3x3 void matrixEigenToTF(const Eigen::Matrix3d &e, tf::Matrix3x3 &t); /// Converts a tf Pose into an Eigen Affine3d void poseTFToEigen(const tf::Pose &t, Eigen::Affine3d &e); /// Converts a tf Pose into an Eigen Isometry3d void poseTFToEigen(const tf::Pose &t, Eigen::Isometry3d &e); /// Converts an Eigen Affine3d into a tf Transform void poseEigenToTF(const Eigen::Affine3d &e, tf::Pose &t); /// Converts an Eigen Isometry3d into a tf Transform void poseEigenToTF(const Eigen::Isometry3d &e, tf::Pose &t); /// Converts a tf Quaternion into an Eigen Quaternion void quaternionTFToEigen(const tf::Quaternion &t, Eigen::Quaterniond &e); /// Converts an Eigen Quaternion into a tf Quaternion void quaternionEigenToTF(const Eigen::Quaterniond &e, tf::Quaternion &t); /// Converts a tf Transform into an Eigen Affine3d void transformTFToEigen(const tf::Transform &t, Eigen::Affine3d &e); /// Converts a tf Transform into an Eigen Isometry3d void transformTFToEigen(const tf::Transform &t, Eigen::Isometry3d &e); /// Converts an Eigen Affine3d into a tf Transform void transformEigenToTF(const Eigen::Affine3d &e, tf::Transform &t); /// Converts an Eigen Isometry3d into a tf Transform void transformEigenToTF(const Eigen::Isometry3d &e, tf::Transform &t); /// Converts a tf Vector3 into an Eigen Vector3d void vectorTFToEigen(const tf::Vector3 &t, Eigen::Vector3d &e); /// Converts an Eigen Vector3d into a tf Vector3 void vectorEigenToTF(const Eigen::Vector3d &e, tf::Vector3 &t); } // namespace tf #endif
0
apollo_public_repos/apollo-platform/ros/geometry/tf_conversions/include
apollo_public_repos/apollo-platform/ros/geometry/tf_conversions/include/tf_conversions/tf_kdl.h
/* * 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, 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 CONVERSIONS_TF_KDL_H #define CONVERSIONS_TF_KDL_H #include "kdl_conversions/kdl_msg.h" //backwards compatability for deprecated methods #include "tf/transform_datatypes.h" #include "kdl/frames.hpp" #include <geometry_msgs/Pose.h> #include <geometry_msgs/Twist.h> namespace tf { /// Converts a tf Pose into a KDL Frame void poseTFToKDL(const tf::Pose &t, KDL::Frame &k); /// Converts a KDL Frame into a tf Pose void poseKDLToTF(const KDL::Frame &k, tf::Pose &t); /// Converts a tf Quaternion into a KDL Rotation void quaternionTFToKDL(const tf::Quaternion &t, KDL::Rotation &k); /// Converts a tf Quaternion into a KDL Rotation void quaternionKDLToTF(const KDL::Rotation &k, tf::Quaternion &t); /// Converts a tf Transform into a KDL Frame void transformTFToKDL(const tf::Transform &t, KDL::Frame &k); /// Converts a KDL Frame into a tf Transform void transformKDLToTF(const KDL::Frame &k, tf::Transform &t); /// Converts a tf Vector3 into a KDL Vector void vectorTFToKDL(const tf::Vector3 &t, KDL::Vector &k); /// Converts a tf Vector3 into a KDL Vector void vectorKDLToTF(const KDL::Vector &k, tf::Vector3 &t); /* DEPRECATED FUNCTIONS */ /// Starting from a Pose from A to B, apply a Twist with reference frame A and reference point B, during a time t. geometry_msgs::Pose addDelta(const geometry_msgs::Pose &pose, const geometry_msgs::Twist &twist, const double &t) __attribute__((deprecated)); /// Converts a tf Pose into a KDL Frame void PoseTFToKDL(const tf::Pose &t, KDL::Frame &k) __attribute__((deprecated)); void inline PoseTFToKDL(const tf::Pose &t, KDL::Frame &k) {poseTFToKDL(t, k);}; /// Converts a KDL Frame into a tf Pose void PoseKDLToTF(const KDL::Frame &k, tf::Pose &t) __attribute__((deprecated)); void inline PoseKDLToTF(const KDL::Frame &k, tf::Pose &t) {poseKDLToTF(k, t);}; /// Converts a tf Quaternion into a KDL Rotation void QuaternionTFToKDL(const tf::Quaternion &t, KDL::Rotation &k) __attribute__((deprecated)); void inline QuaternionTFToKDL(const tf::Quaternion &t, KDL::Rotation &k) {quaternionTFToKDL(t, k);}; /// Converts a tf Quaternion into a KDL Rotation void QuaternionKDLToTF(const KDL::Rotation &k, tf::Quaternion &t) __attribute__((deprecated)); void inline QuaternionKDLToTF(const KDL::Rotation &k, tf::Quaternion &t) {quaternionKDLToTF(k, t);}; /// Converts a tf Transform into a KDL Frame void TransformTFToKDL(const tf::Transform &t, KDL::Frame &k) __attribute__((deprecated)); void inline TransformTFToKDL(const tf::Transform &t, KDL::Frame &k) {transformTFToKDL(t, k);}; /// Converts a KDL Frame into a tf Transform void TransformKDLToTF(const KDL::Frame &k, tf::Transform &t) __attribute__((deprecated)); void inline TransformKDLToTF(const KDL::Frame &k, tf::Transform &t) {transformKDLToTF(k, t);}; /// Converts a tf Vector3 into a KDL Vector void VectorTFToKDL(const tf::Vector3 &t, KDL::Vector &k) __attribute__((deprecated)); void inline VectorTFToKDL(const tf::Vector3 &t, KDL::Vector &k) {vectorTFToKDL(t, k);}; /// Converts a tf Vector3 into a KDL Vector void VectorKDLToTF(const KDL::Vector &k, tf::Vector3 &t) __attribute__((deprecated)); void inline VectorKDLToTF(const KDL::Vector &k, tf::Vector3 &t) {vectorKDLToTF(k, t);}; } // namespace tf #endif
0
apollo_public_repos/apollo-platform/ros/geometry/tf_conversions
apollo_public_repos/apollo-platform/ros/geometry/tf_conversions/src/tf_eigen.cpp
/* * Copyright (c) 2009-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 the 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. */ // Author: Adam Leeper, Stuart Glaser #include "tf_conversions/tf_eigen.h" namespace tf { void matrixTFToEigen(const tf::Matrix3x3 &t, Eigen::Matrix3d &e) { for(int i=0; i<3; i++) for(int j=0; j<3; j++) e(i,j) = t[i][j]; } void matrixEigenToTF(const Eigen::Matrix3d &e, tf::Matrix3x3 &t) { for(int i=0; i<3; i++) for(int j=0; j<3; j++) t[i][j] = e(i,j); } void poseTFToEigen(const tf::Pose &t, Eigen::Affine3d &e) { transformTFToEigen(t, e); } void poseTFToEigen(const tf::Pose &t, Eigen::Isometry3d &e) { transformTFToEigen(t, e); } void poseEigenToTF(const Eigen::Affine3d &e, tf::Pose &t) { transformEigenToTF(e, t); } void poseEigenToTF(const Eigen::Isometry3d &e, tf::Pose &t) { transformEigenToTF(e, t); } void quaternionTFToEigen(const tf::Quaternion& t, Eigen::Quaterniond& e) { e = Eigen::Quaterniond(t[3],t[0],t[1],t[2]); } void quaternionEigenToTF(const Eigen::Quaterniond& e, tf::Quaternion& t) { t[0] = e.x(); t[1] = e.y(); t[2] = e.z(); t[3] = e.w(); } namespace { template<typename Transform> void transformTFToEigenImpl(const tf::Transform &t, Transform & e) { for(int i=0; i<3; i++) { e.matrix()(i,3) = t.getOrigin()[i]; for(int j=0; j<3; j++) { e.matrix()(i,j) = t.getBasis()[i][j]; } } // Fill in identity in last row for (int col = 0 ; col < 3; col ++) e.matrix()(3, col) = 0; e.matrix()(3,3) = 1; } template<typename T> void transformEigenToTFImpl(const T &e, tf::Transform &t) { t.setOrigin(tf::Vector3( e.matrix()(0,3), e.matrix()(1,3), e.matrix()(2,3))); t.setBasis(tf::Matrix3x3(e.matrix()(0,0), e.matrix()(0,1), e.matrix()(0,2), e.matrix()(1,0), e.matrix()(1,1), e.matrix()(1,2), e.matrix()(2,0), e.matrix()(2,1), e.matrix()(2,2))); } } void transformTFToEigen(const tf::Transform &t, Eigen::Affine3d &e) { transformTFToEigenImpl(t, e); }; void transformTFToEigen(const tf::Transform &t, Eigen::Isometry3d &e) { transformTFToEigenImpl(t, e); }; void transformEigenToTF(const Eigen::Affine3d &e, tf::Transform &t) { transformEigenToTFImpl(e, t); } void transformEigenToTF(const Eigen::Isometry3d &e, tf::Transform &t) { transformEigenToTFImpl(e, t); } void vectorTFToEigen(const tf::Vector3& t, Eigen::Vector3d& e) { e(0) = t[0]; e(1) = t[1]; e(2) = t[2]; } void vectorEigenToTF(const Eigen::Vector3d& e, tf::Vector3& t) { t[0] = e(0); t[1] = e(1); t[2] = e(2); } } // namespace tf
0
apollo_public_repos/apollo-platform/ros/geometry/tf_conversions
apollo_public_repos/apollo-platform/ros/geometry/tf_conversions/src/tf_kdl.cpp
/* * 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, 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 "tf_conversions/tf_kdl.h" #include "kdl_conversions/kdl_msg.h" namespace tf { void poseTFToKDL(const tf::Pose& t, KDL::Frame& k) { for (unsigned int i = 0; i < 3; ++i) k.p[i] = t.getOrigin()[i]; for (unsigned int i = 0; i < 9; ++i) k.M.data[i] = t.getBasis()[i/3][i%3]; } void poseKDLToTF(const KDL::Frame& k, tf::Pose& t) { t.setOrigin(tf::Vector3(k.p[0], k.p[1], k.p[2])); t.setBasis(tf::Matrix3x3(k.M.data[0], k.M.data[1], k.M.data[2], k.M.data[3], k.M.data[4], k.M.data[5], k.M.data[6], k.M.data[7], k.M.data[8])); } void quaternionTFToKDL(const tf::Quaternion& t, KDL::Rotation& k) { k = KDL::Rotation::Quaternion(t[0], t[1], t[2], t[3]); } void quaternionKDLToTF(const KDL::Rotation &k, tf::Quaternion &t) { double x, y, z, w; k.GetQuaternion(x, y, z, w); t = tf::Quaternion(x, y, z, w); } void transformTFToKDL(const tf::Transform &t, KDL::Frame &k) { for (unsigned int i = 0; i < 3; ++i) k.p[i] = t.getOrigin()[i]; for (unsigned int i = 0; i < 9; ++i) k.M.data[i] = t.getBasis()[i/3][i%3]; } void transformKDLToTF(const KDL::Frame &k, tf::Transform &t) { t.setOrigin(tf::Vector3(k.p[0], k.p[1], k.p[2])); t.setBasis(tf::Matrix3x3(k.M.data[0], k.M.data[1], k.M.data[2], k.M.data[3], k.M.data[4], k.M.data[5], k.M.data[6], k.M.data[7], k.M.data[8])); } void vectorTFToKDL(const tf::Vector3& t, KDL::Vector& k) { k[0] = t[0]; k[1] = t[1]; k[2] = t[2]; } void vectorKDLToTF(const KDL::Vector& k, tf::Vector3& t) { t[0] = k[0]; t[1] = k[1]; t[2] = k[2]; } /* DEPRECATED FUNCTIONS */ geometry_msgs::Pose addDelta(const geometry_msgs::Pose &pose, const geometry_msgs::Twist &twist, const double &t) { geometry_msgs::Pose result; KDL::Twist kdl_twist; KDL::Frame kdl_pose_id, kdl_pose; poseMsgToKDL(pose,kdl_pose); twistMsgToKDL(twist,kdl_twist); kdl_pose = KDL::addDelta(kdl_pose_id,kdl_twist,t)*kdl_pose; poseKDLToMsg(kdl_pose,result); return result; } } // namespace tf
0
apollo_public_repos/apollo-platform/ros/geometry/tf_conversions/src
apollo_public_repos/apollo-platform/ros/geometry/tf_conversions/src/tf_conversions/posemath.py
# 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 the 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 geometry_msgs.msg import Pose, Point, Quaternion from tf import transformations import tf import rospy import numpy from PyKDL import * def fromTf(tf): """ :param tf: :class:`tf.Transformer` transform :type tf: tuple (translation, quaternion) :return: New :class:`PyKDL.Frame` object Convert a pose returned by :meth:`tf.Transformer.lookupTransform` to a :class:`PyKDL.Frame`. .. doctest:: >>> import rospy >>> import tf >>> import geometry_msgs.msg >>> t = tf.Transformer(True, rospy.Duration(10.0)) >>> m = geometry_msgs.msg.TransformStamped() >>> m.header.frame_id = 'THISFRAME' >>> m.child_frame_id = 'CHILD' >>> m.transform.translation.x = 668.5 >>> m.transform.rotation.w = 1.0 >>> t.setTransform(m) >>> t.lookupTransform('THISFRAME', 'CHILD', rospy.Time(0)) ((668.5, 0.0, 0.0), (0.0, 0.0, 0.0, 1.0)) >>> import tf_conversions.posemath as pm >>> p = pm.fromTf(t.lookupTransform('THISFRAME', 'CHILD', rospy.Time(0))) >>> print pm.toMsg(p * p) position: x: 1337.0 y: 0.0 z: 0.0 orientation: x: 0.0 y: 0.0 z: 0.0 w: 1.0 """ position, quaternion = tf x, y, z = position Qx, Qy, Qz, Qw = quaternion return Frame(Rotation.Quaternion(Qx, Qy, Qz, Qw), Vector(x, y, z)) def toTf(f): """ :param f: input pose :type f: :class:`PyKDL.Frame` Return a tuple (position, quaternion) for the pose. """ return ((f.p[0], f.p[1], f.p[2]), f.M.GetQuaternion()) # to and from pose message def fromMsg(p): """ :param p: input pose :type p: :class:`geometry_msgs.msg.Pose` :return: New :class:`PyKDL.Frame` object Convert a pose represented as a ROS Pose message to a :class:`PyKDL.Frame`. """ return Frame(Rotation.Quaternion(p.orientation.x, p.orientation.y, p.orientation.z, p.orientation.w), Vector(p.position.x, p.position.y, p.position.z)) def toMsg(f): """ :param f: input pose :type f: :class:`PyKDL.Frame` Return a ROS Pose message for the Frame f. """ p = Pose() p.orientation.x, p.orientation.y, p.orientation.z, p.orientation.w = f.M.GetQuaternion() p.position.x = f.p[0] p.position.y = f.p[1] p.position.z = f.p[2] return p # to and from matrix def fromMatrix(m): """ :param m: input 4x4 matrix :type m: :func:`numpy.array` :return: New :class:`PyKDL.Frame` object Convert a pose represented as a 4x4 numpy array to a :class:`PyKDL.Frame`. """ return Frame(Rotation(m[0,0], m[0,1], m[0,2], m[1,0], m[1,1], m[1,2], m[2,0], m[2,1], m[2,2]), Vector(m[0,3], m[1, 3], m[2, 3])) def toMatrix(f): """ :param f: input pose :type f: :class:`PyKDL.Frame` Return a numpy 4x4 array for the Frame F. """ return numpy.array([[f.M[0,0], f.M[0,1], f.M[0,2], f.p[0]], [f.M[1,0], f.M[1,1], f.M[1,2], f.p[1]], [f.M[2,0], f.M[2,1], f.M[2,2], f.p[2]], [0,0,0,1]]) # from camera parameters def fromCameraParams(cv, rvec, tvec): """ :param cv: OpenCV module :param rvec: A Rodrigues rotation vector - see :func:`Rodrigues2` :type rvec: 3x1 :class:`CvMat` :param tvec: A translation vector :type tvec: 3x1 :class:`CvMat` :return: New :class:`PyKDL.Frame` object For use with :func:`FindExtrinsicCameraParams2`:: import cv import tf_conversions.posemath as pm ... rvec = cv.CreateMat(3, 1, cv.CV_32FC1) tvec = cv.CreateMat(3, 1, cv.CV_32FC1) cv.FindExtrinsicCameraParams2(model, corners, intrinsic_matrix, kc, rvec, tvec) pose = pm.fromCameraParams(cv, rvec, tvec) """ m = numpy.array([ [ 0, 0, 0, tvec[0,0] ], [ 0, 0, 0, tvec[1,0] ], [ 0, 0, 0, tvec[2,0] ], [ 0, 0, 0, 1.0 ] ], dtype = numpy.float32) cv.Rodrigues2(rvec, m[:3,:3]) return fromMatrix(m)
0
apollo_public_repos/apollo-platform/ros/geometry/tf_conversions/src
apollo_public_repos/apollo-platform/ros/geometry/tf_conversions/src/tf_conversions/__init__.py
# 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 the 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 posemath import *
0
apollo_public_repos/apollo-platform/ros/geometry
apollo_public_repos/apollo-platform/ros/geometry/eigen_conversions/CMakeLists.txt
cmake_minimum_required(VERSION 2.8) project(eigen_conversions) find_package(orocos_kdl REQUIRED) find_package(catkin REQUIRED cmake_modules geometry_msgs std_msgs) find_package(Eigen REQUIRED) include_directories(SYSTEM ${EIGEN_INCLUDE_DIRS}) include_directories(include ${catkin_INCLUDE_DIRS} ${orocos_kdl_INCLUDE_DIRS}) link_directories(${catkin_LIBRARY_DIRS}) link_directories(${orocos_kdl_LIBRARY_DIRS}) catkin_package( INCLUDE_DIRS include ${EIGEN_INCLUDE_DIRS} LIBRARIES ${PROJECT_NAME} CATKIN_DEPENDS geometry_msgs std_msgs DEPENDS orocos_kdl ) add_library(${PROJECT_NAME} src/eigen_msg.cpp src/eigen_kdl.cpp ) add_dependencies(${PROJECT_NAME} geometry_msgs_gencpp) target_link_libraries(${PROJECT_NAME} ${catkin_LIBRARIES} ${orocos_kdl_LIBRARIES}) install(DIRECTORY include/${PROJECT_NAME}/ DESTINATION ${CATKIN_PACKAGE_INCLUDE_DESTINATION}) install(TARGETS ${PROJECT_NAME} DESTINATION ${CATKIN_PACKAGE_LIB_DESTINATION})
0
apollo_public_repos/apollo-platform/ros/geometry
apollo_public_repos/apollo-platform/ros/geometry/eigen_conversions/package.xml
<package> <name>eigen_conversions</name> <version>1.11.8</version> <description> Conversion functions between: - Eigen and KDL - Eigen and geometry_msgs. </description> <author>Stuart Glaser</author> <author>Adam Leeper</author> <maintainer email="[email protected]">Tully Foote</maintainer> <license>BSD</license> <url>http://ros.org/wiki/eigen_conversions</url> <buildtool_depend>catkin</buildtool_depend> <build_depend>cmake_modules</build_depend> <build_depend>geometry_msgs</build_depend> <build_depend>eigen</build_depend> <build_depend>orocos_kdl</build_depend> <build_depend>std_msgs</build_depend> <run_depend>geometry_msgs</run_depend> <run_depend>eigen</run_depend> <run_depend>orocos_kdl</run_depend> <run_depend>std_msgs</run_depend> </package>
0
apollo_public_repos/apollo-platform/ros/geometry
apollo_public_repos/apollo-platform/ros/geometry/eigen_conversions/mainpage.dox
/** \mainpage \htmlinclude manifest.html \b eigen_conversions is ... <!-- Provide an overview of your package. --> \section codeapi Code API <!-- Provide links to specific auto-generated API documentation within your package that is of particular interest to a reader. Doxygen will document pretty much every part of your code, so do your best here to point the reader to the actual API. If your codebase is fairly large or has different sets of APIs, you should use the doxygen 'group' tag to keep these APIs together. For example, the roscpp documentation has 'libros' group. --> */
0
apollo_public_repos/apollo-platform/ros/geometry
apollo_public_repos/apollo-platform/ros/geometry/eigen_conversions/.tar
{!!python/unicode 'url': 'https://github.com/ros-gbp/geometry-release/archive/release/indigo/eigen_conversions/1.11.8-0.tar.gz', !!python/unicode 'version': geometry-release-release-indigo-eigen_conversions-1.11.8-0}
0
apollo_public_repos/apollo-platform/ros/geometry
apollo_public_repos/apollo-platform/ros/geometry/eigen_conversions/CHANGELOG.rst
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Changelog for package eigen_conversions ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 1.11.8 (2016-03-04) ------------------- * eigen_conversions: Add conversions for Eigen::Isometry3d * Contributors: Maarten de Vries 1.11.7 (2015-04-21) ------------------- 1.11.6 (2015-03-25) ------------------- 1.11.5 (2015-03-17) ------------------- 1.11.4 (2014-12-23) ------------------- 1.11.3 (2014-05-07) ------------------- 1.11.2 (2014-02-25) ------------------- * alphabetization and updating cmake to find Eigen * Contributors: Tully Foote 1.11.1 (2014-02-23) ------------------- * add dep on cmake_modules for finding eigen * Contributors: Ioan Sucan 1.11.0 (2014-02-14) ------------------- * fixed Eigen-KDL 3D Vector conversion functions * Contributors: fevb 1.10.8 (2014-02-01) ------------------- 1.10.7 (2013-12-27) ------------------- 1.10.6 (2013-08-28) ------------------- 1.10.5 (2013-07-19) ------------------- 1.10.4 (2013-07-11) ------------------- 1.10.3 (2013-07-09) ------------------- 1.10.2 (2013-07-09) ------------------- 1.10.1 (2013-07-05) ------------------- 1.10.0 (2013-07-05) ------------------- 1.9.31 (2013-04-18 18:16) ------------------------- * add link directories 1.9.30 (2013-04-18 16:26) ------------------------- * Fixes `#11 <https://github.com/ros/geometry/issues/11>`_: orocos_kdl now has cmake rules oroco-kdl update cmake to use orocos_kdl as plain cmake package instead of catkin package Signed-off-by: Ruben Smits <[email protected]> 1.9.29 (2013-01-13) ------------------- 1.9.28 (2013-01-02) ------------------- 1.9.27 (2012-12-21) ------------------- 1.9.26 (2012-12-14) ------------------- * add missing dep to catkin 1.9.25 (2012-12-13) ------------------- 1.9.24 (2012-12-11) ------------------- * Version 1.9.24 * Fixes to CMakeLists.txt's while building from source 1.9.23 (2012-11-22) ------------------- * Releaseing version 1.9.23 1.9.22 (2012-11-04 09:14) ------------------------- 1.9.21 (2012-11-04 01:19) ------------------------- 1.9.20 (2012-11-02) ------------------- 1.9.19 (2012-10-31) ------------------- * Removed deprecated 'brief' attribute from <description> tags. 1.9.18 (2012-10-16) ------------------- 1.9.17 (2012-10-02) ------------------- * fix several dependency issues 1.9.16 (2012-09-29) ------------------- * adding geometry metapackage and updating to 1.9.16 1.9.15 (2012-09-30) ------------------- * fix a few dependency/catkin problems * remove old API files * comply to the new catkin API 1.9.14 (2012-09-18) ------------------- 1.9.13 (2012-09-17) ------------------- 1.9.12 (2012-09-16) ------------------- 1.9.11 (2012-09-14 22:49) ------------------------- 1.9.10 (2012-09-14 22:30) ------------------------- 1.9.9 (2012-09-11) ------------------ * update depends * minor patches for new build system 1.9.8 (2012-09-03) ------------------ 1.9.7 (2012-08-10 12:19) ------------------------ * minor build fixes * completed set of eigen conversions; added KDL conversions * adding additional conversion functions 1.9.6 (2012-08-02 19:59) ------------------------ 1.9.5 (2012-08-02 19:48) ------------------------ 1.9.4 (2012-08-02 18:29) ------------------------ 1.9.3 (2012-08-02 18:28) ------------------------ * forgot to install some things * also using DEPENDS 1.9.2 (2012-08-01 21:05) ------------------------ 1.9.1 (2012-08-01 19:16) ------------------------ * install manifest.xml 1.9.0 (2012-08-01 18:52) ------------------------ * catkin build system * added some additional conversion routines between eigen and messages * removing dependency on eigen package * compiling with eigen3 * missed a rename * more extensive search * applying patch from sed script for eigen3 compatability * Moving eigen_conversions from sandbox.
0
apollo_public_repos/apollo-platform/ros/geometry/eigen_conversions/include
apollo_public_repos/apollo-platform/ros/geometry/eigen_conversions/include/eigen_conversions/eigen_msg.h
/* * 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, 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. */ /* * Author: Stuart Glaser */ #ifndef EIGEN_MSG_CONVERSIONS_H #define EIGEN_MSG_CONVERSIONS_H #include <std_msgs/Float64MultiArray.h> #include <geometry_msgs/Point.h> #include <geometry_msgs/Pose.h> #include <geometry_msgs/Quaternion.h> #include <geometry_msgs/Transform.h> #include <geometry_msgs/Twist.h> #include <geometry_msgs/Vector3.h> #include <geometry_msgs/Wrench.h> #include <Eigen/Core> #include <Eigen/Geometry> namespace tf { /// Converts a Point message into an Eigen Vector void pointMsgToEigen(const geometry_msgs::Point &m, Eigen::Vector3d &e); /// Converts an Eigen Vector into a Point message void pointEigenToMsg(const Eigen::Vector3d &e, geometry_msgs::Point &m); /// Converts a Pose message into an Eigen Affine3d void poseMsgToEigen(const geometry_msgs::Pose &m, Eigen::Affine3d &e); /// Converts a Pose message into an Eigen Isometry3d void poseMsgToEigen(const geometry_msgs::Pose &m, Eigen::Isometry3d &e); /// Converts an Eigen Affine3d into a Pose message void poseEigenToMsg(const Eigen::Affine3d &e, geometry_msgs::Pose &m); /// Converts an Eigen Isometry3d into a Pose message void poseEigenToMsg(const Eigen::Isometry3d &e, geometry_msgs::Pose &m); /// Converts a Quaternion message into an Eigen Quaternion void quaternionMsgToEigen(const geometry_msgs::Quaternion &m, Eigen::Quaterniond &e); /// Converts an Eigen Quaternion into a Quaternion message void quaternionEigenToMsg(const Eigen::Quaterniond &e, geometry_msgs::Quaternion &m); /// Converts a Transform message into an Eigen Affine3d void transformMsgToEigen(const geometry_msgs::Transform &m, Eigen::Affine3d &e); /// Converts a Transform message into an Eigen Isometry3d void transformMsgToEigen(const geometry_msgs::Transform &m, Eigen::Isometry3d &e); /// Converts an Eigen Affine3d into a Transform message void transformEigenToMsg(const Eigen::Affine3d &e, geometry_msgs::Transform &m); /// Converts an Eigen Isometry3d into a Transform message void transformEigenToMsg(const Eigen::Isometry3d &e, geometry_msgs::Transform &m); /// Converts a Twist message into an Eigen matrix void twistMsgToEigen(const geometry_msgs::Twist &m, Eigen::Matrix<double,6,1> &e); /// Converts an Eigen matrix into a Twist message void twistEigenToMsg(const Eigen::Matrix<double,6,1> &e, geometry_msgs::Twist &m); /// Converts a Vector message into an Eigen Vector void vectorMsgToEigen(const geometry_msgs::Vector3 &m, Eigen::Vector3d &e); /// Converts an Eigen Vector into a Vector message void vectorEigenToMsg(const Eigen::Vector3d &e, geometry_msgs::Vector3 &m); /// Converts a Wrench message into an Eigen matrix void wrenchMsgToEigen(const geometry_msgs::Wrench &m, Eigen::Matrix<double,6,1> &e); /// Converts an Eigen matrix into a Wrench message void wrenchEigenToMsg(const Eigen::Matrix<double,6,1> &e, geometry_msgs::Wrench &m); /// Converts an Eigen matrix into a Float64MultiArray message template <class Derived> void matrixEigenToMsg(const Eigen::MatrixBase<Derived> &e, std_msgs::Float64MultiArray &m) { if (m.layout.dim.size() != 2) m.layout.dim.resize(2); m.layout.dim[0].stride = e.rows() * e.cols(); m.layout.dim[0].size = e.rows(); m.layout.dim[1].stride = e.cols(); m.layout.dim[1].size = e.cols(); if ((int)m.data.size() != e.size()) m.data.resize(e.size()); int ii = 0; for (int i = 0; i < e.rows(); ++i) for (int j = 0; j < e.cols(); ++j) m.data[ii++] = e.coeff(i, j); } } // namespace #endif
0
apollo_public_repos/apollo-platform/ros/geometry/eigen_conversions/include
apollo_public_repos/apollo-platform/ros/geometry/eigen_conversions/include/eigen_conversions/eigen_kdl.h
/* * 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, 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. */ /* * Author: Adam Leeper, Stuart Glaser */ #ifndef EIGEN_KDL_CONVERSIONS_H #define EIGEN_KDL_CONVERSIONS_H #include <Eigen/Core> #include <Eigen/Geometry> #include <kdl/frames.hpp> namespace tf { /// Converts a KDL rotation into an Eigen quaternion void quaternionKDLToEigen(const KDL::Rotation &k, Eigen::Quaterniond &e); /// Converts an Eigen quaternion into a KDL rotation void quaternionEigenToKDL(const Eigen::Quaterniond &e, KDL::Rotation &k); /// Converts a KDL frame into an Eigen Affine3d void transformKDLToEigen(const KDL::Frame &k, Eigen::Affine3d &e); /// Converts a KDL frame into an Eigen Isometry3d void transformKDLToEigen(const KDL::Frame &k, Eigen::Isometry3d &e); /// Converts an Eigen Affine3d into a KDL frame void transformEigenToKDL(const Eigen::Affine3d &e, KDL::Frame &k); /// Converts an Eigen Isometry3d into a KDL frame void transformEigenToKDL(const Eigen::Isometry3d &e, KDL::Frame &k); /// Converts a KDL twist into an Eigen matrix void twistKDLToEigen(const KDL::Twist &k, Eigen::Matrix<double, 6, 1> &e); /// Converts an Eigen matrix into a KDL Twist void twistEigenToKDL(const Eigen::Matrix<double, 6, 1> &e, KDL::Twist &k); /// Converts a KDL vector into an Eigen matrix void vectorKDLToEigen(const KDL::Vector &k, Eigen::Matrix<double, 3, 1> &e); /// Converts an Eigen matrix into a KDL vector void vectorEigenToKDL(const Eigen::Matrix<double, 3, 1> &e, KDL::Vector &k); /// Converts a KDL wrench into an Eigen matrix void wrenchKDLToEigen(const KDL::Wrench &k, Eigen::Matrix<double, 6, 1> &e); /// Converts an Eigen matrix into a KDL wrench void wrenchEigenToKDL(const Eigen::Matrix<double, 6, 1> &e, KDL::Wrench &k); } // namespace #endif
0
apollo_public_repos/apollo-platform/ros/geometry/eigen_conversions
apollo_public_repos/apollo-platform/ros/geometry/eigen_conversions/src/eigen_msg.cpp
/* * 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, 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 <eigen_conversions/eigen_msg.h> namespace tf { void pointMsgToEigen(const geometry_msgs::Point &m, Eigen::Vector3d &e) { e(0) = m.x; e(1) = m.y; e(2) = m.z; } void pointEigenToMsg(const Eigen::Vector3d &e, geometry_msgs::Point &m) { m.x = e(0); m.y = e(1); m.z = e(2); } namespace { template<typename T> void poseMsgToEigenImpl(const geometry_msgs::Pose &m, T &e) { e = Eigen::Translation3d(m.position.x, m.position.y, m.position.z) * Eigen::Quaterniond(m.orientation.w, m.orientation.x, m.orientation.y, m.orientation.z); } template<typename T> void poseEigenToMsgImpl(const T &e, geometry_msgs::Pose &m) { m.position.x = e.translation()[0]; m.position.y = e.translation()[1]; m.position.z = e.translation()[2]; Eigen::Quaterniond q = (Eigen::Quaterniond)e.linear(); m.orientation.x = q.x(); m.orientation.y = q.y(); m.orientation.z = q.z(); m.orientation.w = q.w(); if (m.orientation.w < 0) { m.orientation.x *= -1; m.orientation.y *= -1; m.orientation.z *= -1; m.orientation.w *= -1; } } template<typename T> void transformMsgToEigenImpl(const geometry_msgs::Transform &m, T &e) { e = Eigen::Translation3d(m.translation.x, m.translation.y, m.translation.z) * Eigen::Quaterniond(m.rotation.w, m.rotation.x, m.rotation.y, m.rotation.z); } template<typename T> void transformEigenToMsgImpl(const T &e, geometry_msgs::Transform &m) { m.translation.x = e.translation()[0]; m.translation.y = e.translation()[1]; m.translation.z = e.translation()[2]; Eigen::Quaterniond q = (Eigen::Quaterniond)e.linear(); m.rotation.x = q.x(); m.rotation.y = q.y(); m.rotation.z = q.z(); m.rotation.w = q.w(); if (m.rotation.w < 0) { m.rotation.x *= -1; m.rotation.y *= -1; m.rotation.z *= -1; m.rotation.w *= -1; } } } void poseMsgToEigen(const geometry_msgs::Pose &m, Eigen::Affine3d &e) { poseMsgToEigenImpl(m, e); } void poseMsgToEigen(const geometry_msgs::Pose &m, Eigen::Isometry3d &e) { poseMsgToEigenImpl(m, e); } void poseEigenToMsg(const Eigen::Affine3d &e, geometry_msgs::Pose &m) { poseEigenToMsgImpl(e, m); } void poseEigenToMsg(const Eigen::Isometry3d &e, geometry_msgs::Pose &m) { poseEigenToMsgImpl(e, m); } void quaternionMsgToEigen(const geometry_msgs::Quaternion &m, Eigen::Quaterniond &e) { e = Eigen::Quaterniond(m.w, m.x, m.y, m.z); } void quaternionEigenToMsg(const Eigen::Quaterniond &e, geometry_msgs::Quaternion &m) { m.x = e.x(); m.y = e.y(); m.z = e.z(); m.w = e.w(); } void transformMsgToEigen(const geometry_msgs::Transform &m, Eigen::Affine3d &e) { transformMsgToEigenImpl(m, e); } void transformMsgToEigen(const geometry_msgs::Transform &m, Eigen::Isometry3d &e) { transformMsgToEigenImpl(m, e); } void transformEigenToMsg(const Eigen::Affine3d &e, geometry_msgs::Transform &m) { transformEigenToMsgImpl(e, m); } void transformEigenToMsg(const Eigen::Isometry3d &e, geometry_msgs::Transform &m) { transformEigenToMsgImpl(e, m); } void vectorMsgToEigen(const geometry_msgs::Vector3 &m, Eigen::Vector3d &e) { e(0) = m.x; e(1) = m.y; e(2) = m.z; } void vectorEigenToMsg(const Eigen::Vector3d &e, geometry_msgs::Vector3 &m) { m.x = e(0); m.y = e(1); m.z = e(2); } void twistMsgToEigen(const geometry_msgs::Twist &m, Eigen::Matrix<double,6,1> &e) { e[0] = m.linear.x; e[1] = m.linear.y; e[2] = m.linear.z; e[3] = m.angular.x; e[4] = m.angular.y; e[5] = m.angular.z; } void twistEigenToMsg(const Eigen::Matrix<double,6,1> &e, geometry_msgs::Twist &m) { m.linear.x = e[0]; m.linear.y = e[1]; m.linear.z = e[2]; m.angular.x = e[3]; m.angular.y = e[4]; m.angular.z = e[5]; } void wrenchMsgToEigen(const geometry_msgs::Wrench &m, Eigen::Matrix<double,6,1> &e) { e[0] = m.force.x; e[1] = m.force.y; e[2] = m.force.z; e[3] = m.torque.x; e[4] = m.torque.y; e[5] = m.torque.z; } void wrenchEigenToMsg(const Eigen::Matrix<double,6,1> &e, geometry_msgs::Wrench &m) { m.force.x = e[0]; m.force.y = e[1]; m.force.z = e[2]; m.torque.x = e[3]; m.torque.y = e[4]; m.torque.z = e[5]; } } // namespace
0
apollo_public_repos/apollo-platform/ros/geometry/eigen_conversions
apollo_public_repos/apollo-platform/ros/geometry/eigen_conversions/src/eigen_kdl.cpp
/* * 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, 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 <eigen_conversions/eigen_kdl.h> namespace tf { void quaternionKDLToEigen(const KDL::Rotation &k, Eigen::Quaterniond &e) { // // is it faster to do this? k.GetQuaternion(e.x(), e.y(), e.z(), e.w()); // or this? //double x, y, z, w; //k.GetQuaternion(x, y, z, w); //e = Eigen::Quaterniond(w, x, y, z); } void quaternionEigenToKDL(const Eigen::Quaterniond &e, KDL::Rotation &k) { k = KDL::Rotation::Quaternion(e.x(), e.y(), e.z(), e.w()); } namespace { template<typename T> void transformKDLToEigenImpl(const KDL::Frame &k, T &e) { // translation for (unsigned int i = 0; i < 3; ++i) e(i, 3) = k.p[i]; // rotation matrix for (unsigned int i = 0; i < 9; ++i) e(i/3, i%3) = k.M.data[i]; // "identity" row e(3,0) = 0.0; e(3,1) = 0.0; e(3,2) = 0.0; e(3,3) = 1.0; } template<typename T> void transformEigenToKDLImpl(const T &e, KDL::Frame &k) { for (unsigned int i = 0; i < 3; ++i) k.p[i] = e(i, 3); for (unsigned int i = 0; i < 9; ++i) k.M.data[i] = e(i/3, i%3); } } void transformKDLToEigen(const KDL::Frame &k, Eigen::Affine3d &e) { transformKDLToEigenImpl(k, e); } void transformKDLToEigen(const KDL::Frame &k, Eigen::Isometry3d &e) { transformKDLToEigenImpl(k, e); } void transformEigenToKDL(const Eigen::Affine3d &e, KDL::Frame &k) { transformEigenToKDLImpl(e, k); } void transformEigenToKDL(const Eigen::Isometry3d &e, KDL::Frame &k) { transformEigenToKDLImpl(e, k); } void twistEigenToKDL(const Eigen::Matrix<double, 6, 1> &e, KDL::Twist &k) { for(int i = 0; i < 6; ++i) k[i] = e[i]; } void twistKDLToEigen(const KDL::Twist &k, Eigen::Matrix<double, 6, 1> &e) { for(int i = 0; i < 6; ++i) e[i] = k[i]; } void vectorEigenToKDL(const Eigen::Matrix<double, 3, 1> &e, KDL::Vector &k) { for(int i = 0; i < 3; ++i) k[i] = e[i]; } void vectorKDLToEigen(const KDL::Vector &k, Eigen::Matrix<double, 3, 1> &e) { for(int i = 0; i < 3; ++i) e[i] = k[i]; } void wrenchKDLToEigen(const KDL::Wrench &k, Eigen::Matrix<double, 6, 1> &e) { for(int i = 0; i < 6; ++i) e[i] = k[i]; } void wrenchEigenToKDL(const Eigen::Matrix<double, 6, 1> &e, KDL::Wrench &k) { for(int i = 0; i < 6; ++i) k[i] = e[i]; } } // namespace
0
apollo_public_repos/apollo-platform/ros/geometry
apollo_public_repos/apollo-platform/ros/geometry/geometry/CMakeLists.txt
cmake_minimum_required(VERSION 2.8.3) project(geometry) find_package(catkin REQUIRED) catkin_metapackage()
0
apollo_public_repos/apollo-platform/ros/geometry
apollo_public_repos/apollo-platform/ros/geometry/geometry/package.xml
<package> <name>geometry</name> <version>1.11.8</version> <description>Geometry Library</description> <maintainer email="[email protected]">Tully Foote</maintainer> <license>BSD</license> <url type="website">http://www.ros.org/wiki/geometry</url> <url type="bugtracker">https://code.ros.org/trac/ros-pkg/query?component=geometry&amp;status=assigned&amp;status=new&amp;status=reopened</url> <url type="repository">https://kforge.ros.org/geometry/geometry</url> <author>Tully Foote</author> <buildtool_depend>catkin</buildtool_depend> <!-- Old stack contents --> <run_depend>angles</run_depend> <run_depend>eigen_conversions</run_depend> <run_depend>kdl_conversions</run_depend> <run_depend>tf</run_depend> <run_depend>tf_conversions</run_depend> <export> <metapackage/> </export> </package>
0
apollo_public_repos/apollo-platform/ros/geometry
apollo_public_repos/apollo-platform/ros/geometry/geometry/.tar
{!!python/unicode 'url': 'https://github.com/ros-gbp/geometry-release/archive/release/indigo/geometry/1.11.8-0.tar.gz', !!python/unicode 'version': geometry-release-release-indigo-geometry-1.11.8-0}
0
apollo_public_repos/apollo-platform/ros/geometry
apollo_public_repos/apollo-platform/ros/geometry/geometry/CHANGELOG.rst
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Changelog for package geometry ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 1.11.8 (2016-03-04) ------------------- 1.11.7 (2015-04-21) ------------------- 1.11.6 (2015-03-25) ------------------- 1.11.5 (2015-03-17) ------------------- 1.11.4 (2014-12-23) ------------------- * Update package.xml * Contributors: David Lu!! 1.11.3 (2014-05-07) ------------------- 1.11.2 (2014-02-25) ------------------- 1.11.1 (2014-02-23) ------------------- 1.11.0 (2014-02-14) ------------------- 1.10.8 (2014-02-01) ------------------- 1.10.7 (2013-12-27) ------------------- 1.10.6 (2013-08-28) ------------------- 1.10.5 (2013-07-19) ------------------- 1.10.4 (2013-07-11) ------------------- 1.10.3 (2013-07-09) ------------------- 1.10.2 (2013-07-09) ------------------- 1.10.1 (2013-07-05) ------------------- 1.10.0 (2013-07-05) ------------------- 1.9.31 (2013-04-18 18:16) ------------------------- 1.9.30 (2013-04-18 16:26) ------------------------- * add buildtool_depend * add CMakeLists.txt for metapackage 1.9.29 (2013-01-13) ------------------- 1.9.28 (2013-01-02) ------------------- 1.9.27 (2012-12-21) ------------------- 1.9.26 (2012-12-14) ------------------- 1.9.25 (2012-12-13) ------------------- 1.9.24 (2012-12-11) ------------------- * Version 1.9.24 1.9.23 (2012-11-22) ------------------- * Releaseing version 1.9.23 1.9.22 (2012-11-04 09:14) ------------------------- 1.9.21 (2012-11-04 01:19) ------------------------- 1.9.20 (2012-11-02) ------------------- * depend on angles 1.9.19 (2012-10-31) ------------------- 1.9.18 (2012-10-16) ------------------- 1.9.17 (2012-10-02) ------------------- 1.9.16 (2012-09-29) ------------------- * fixing xml syntax * adding geometry metapackage and updating to 1.9.16 1.9.15 (2012-09-30) ------------------- 1.9.14 (2012-09-18) ------------------- 1.9.13 (2012-09-17) ------------------- 1.9.12 (2012-09-16) ------------------- 1.9.11 (2012-09-14 22:49) ------------------------- 1.9.10 (2012-09-14 22:30) ------------------------- 1.9.9 (2012-09-11) ------------------ 1.9.8 (2012-09-03) ------------------ 1.9.7 (2012-08-10 12:19) ------------------------ 1.9.6 (2012-08-02 19:59) ------------------------ 1.9.5 (2012-08-02 19:48) ------------------------ 1.9.4 (2012-08-02 18:29) ------------------------ 1.9.3 (2012-08-02 18:28) ------------------------ 1.9.2 (2012-08-01 21:05) ------------------------ 1.9.1 (2012-08-01 19:16) ------------------------ 1.9.0 (2012-08-01 18:52) ------------------------
0
apollo_public_repos/apollo-platform/ros/geometry
apollo_public_repos/apollo-platform/ros/geometry/kdl_conversions/CMakeLists.txt
cmake_minimum_required(VERSION 2.8) project(kdl_conversions) find_package(catkin REQUIRED geometry_msgs) find_package(orocos_kdl REQUIRED) catkin_package( INCLUDE_DIRS include LIBRARIES ${PROJECT_NAME} CATKIN_DEPENDS geometry_msgs DEPENDS orocos_kdl ) include_directories(include ${catkin_INCLUDE_DIRS} ${orocos_kdl_INCLUDE_DIRS}) link_directories(${catkin_LIBRARY_DIRS}) link_directories(${orocos_kdl_LIBRARY_DIRS}) add_library(${PROJECT_NAME} src/kdl_msg.cpp ) add_dependencies(${PROJECT_NAME} geometry_msgs_gencpp) target_link_libraries(${PROJECT_NAME} ${catkin_LIBRARIES} ${orocos_kdl_LIBRARIES}) install(DIRECTORY include/${PROJECT_NAME}/ DESTINATION ${CATKIN_PACKAGE_INCLUDE_DESTINATION}) install(TARGETS ${PROJECT_NAME} DESTINATION ${CATKIN_PACKAGE_LIB_DESTINATION})
0
apollo_public_repos/apollo-platform/ros/geometry
apollo_public_repos/apollo-platform/ros/geometry/kdl_conversions/package.xml
<package> <name>kdl_conversions</name> <version>1.11.8</version> <description> Conversion functions between KDL and geometry_msgs types. </description> <author>Adam Leeper</author> <maintainer email="[email protected]">Tully Foote</maintainer> <license>BSD</license> <url>http://ros.org/wiki/kdl_conversions</url> <buildtool_depend>catkin</buildtool_depend> <build_depend>geometry_msgs</build_depend> <build_depend>orocos_kdl</build_depend> <run_depend>geometry_msgs</run_depend> <run_depend>orocos_kdl</run_depend> </package>
0
apollo_public_repos/apollo-platform/ros/geometry
apollo_public_repos/apollo-platform/ros/geometry/kdl_conversions/mainpage.dox
/** \mainpage \htmlinclude manifest.html \b kdl_conversions <!-- Provide an overview of your package. --> --> */
0
apollo_public_repos/apollo-platform/ros/geometry
apollo_public_repos/apollo-platform/ros/geometry/kdl_conversions/.tar
{!!python/unicode 'url': 'https://github.com/ros-gbp/geometry-release/archive/release/indigo/kdl_conversions/1.11.8-0.tar.gz', !!python/unicode 'version': geometry-release-release-indigo-kdl_conversions-1.11.8-0}
0
apollo_public_repos/apollo-platform/ros/geometry
apollo_public_repos/apollo-platform/ros/geometry/kdl_conversions/CHANGELOG.rst
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Changelog for package kdl_conversions ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 1.11.8 (2016-03-04) ------------------- 1.11.7 (2015-04-21) ------------------- 1.11.6 (2015-03-25) ------------------- 1.11.5 (2015-03-17) ------------------- 1.11.4 (2014-12-23) ------------------- * Update package.xml * Contributors: David Lu!! 1.11.3 (2014-05-07) ------------------- 1.11.2 (2014-02-25) ------------------- 1.11.1 (2014-02-23) ------------------- 1.11.0 (2014-02-14) ------------------- 1.10.8 (2014-02-01) ------------------- 1.10.7 (2013-12-27) ------------------- 1.10.6 (2013-08-28) ------------------- 1.10.5 (2013-07-19) ------------------- 1.10.4 (2013-07-11) ------------------- 1.10.3 (2013-07-09) ------------------- 1.10.2 (2013-07-09) ------------------- 1.10.1 (2013-07-05) ------------------- 1.10.0 (2013-07-05) ------------------- 1.9.31 (2013-04-18 18:16) ------------------------- * add link directories 1.9.30 (2013-04-18 16:26) ------------------------- * Fixes `#11 <https://github.com/ros/geometry/issues/11>`_: orocos_kdl now has cmake rules oroco-kdl update cmake to use orocos_kdl as plain cmake package instead of catkin package Signed-off-by: Ruben Smits <[email protected]> 1.9.29 (2013-01-13) ------------------- 1.9.28 (2013-01-02) ------------------- 1.9.27 (2012-12-21) ------------------- 1.9.26 (2012-12-14) ------------------- * add missing dep to catkin 1.9.25 (2012-12-13) ------------------- 1.9.24 (2012-12-11) ------------------- * Version 1.9.24 * Fixes to CMakeLists.txt's while building from source 1.9.23 (2012-11-22) ------------------- * Releaseing version 1.9.23 1.9.22 (2012-11-04 09:14) ------------------------- * more backwards compatible conversions and an include to make sure it gets into the old header location 1.9.21 (2012-11-04 01:19) ------------------------- 1.9.20 (2012-11-02) ------------------- 1.9.19 (2012-10-31) ------------------- * Removed deprecated 'brief' attribute from <description> tags. 1.9.18 (2012-10-16) ------------------- 1.9.17 (2012-10-02) ------------------- * fix several dependency issues 1.9.16 (2012-09-29) ------------------- * adding geometry metapackage and updating to 1.9.16 1.9.15 (2012-09-30) ------------------- * fix a few dependency/catkin problems * remove old API files * comply to the new catkin API 1.9.14 (2012-09-18) ------------------- 1.9.13 (2012-09-17) ------------------- * update manifests 1.9.12 (2012-09-16) ------------------- 1.9.11 (2012-09-14 22:49) ------------------------- 1.9.10 (2012-09-14 22:30) ------------------------- 1.9.9 (2012-09-11) ------------------ * minor patches for new build system 1.9.8 (2012-09-03) ------------------ 1.9.7 (2012-08-10 12:19) ------------------------ * minor build fixes * fixed some minor errors from last commit * completed set of eigen conversions; added KDL conversions 1.9.6 (2012-08-02 19:59) ------------------------ 1.9.5 (2012-08-02 19:48) ------------------------ 1.9.4 (2012-08-02 18:29) ------------------------ 1.9.3 (2012-08-02 18:28) ------------------------ 1.9.2 (2012-08-01 21:05) ------------------------ 1.9.1 (2012-08-01 19:16) ------------------------ 1.9.0 (2012-08-01 18:52) ------------------------
0
apollo_public_repos/apollo-platform/ros/geometry/kdl_conversions/include
apollo_public_repos/apollo-platform/ros/geometry/kdl_conversions/include/kdl_conversions/kdl_msg.h
/* * 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 the 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. * * Author: Adam Leeper */ #ifndef CONVERSIONS_KDL_MSG_H #define CONVERSIONS_KDL_MSG_H #include "kdl/frames.hpp" #include <geometry_msgs/Point.h> #include <geometry_msgs/Pose.h> #include <geometry_msgs/Quaternion.h> #include <geometry_msgs/Transform.h> #include <geometry_msgs/Twist.h> #include <geometry_msgs/Vector3.h> #include <geometry_msgs/Wrench.h> namespace tf { /// Conversion functions from/to the corresponding KDL and geometry_msgs types. /// Converts a geometry_msgs Point into a KDL Vector void pointMsgToKDL(const geometry_msgs::Point &m, KDL::Vector &k); /// Converts a KDL Vector into a geometry_msgs Vector3 void pointKDLToMsg(const KDL::Vector &k, geometry_msgs::Point &m); /// Converts a Pose message into a KDL Frame void poseMsgToKDL(const geometry_msgs::Pose &m, KDL::Frame &k); /// Converts a KDL Frame into a Pose message void poseKDLToMsg(const KDL::Frame &k, geometry_msgs::Pose &m); /// Converts a quaternion message into a KDL Rotation void quaternionMsgToKDL(const geometry_msgs::Quaternion &m, KDL::Rotation &k); /// Converts a KDL Rotation into a message quaternion void quaternionKDLToMsg(const KDL::Rotation &k, geometry_msgs::Quaternion &m); /// Converts a Transform message into a KDL Frame void transformMsgToKDL(const geometry_msgs::Transform &m, KDL::Frame &k); /// Converts a KDL Frame into a Transform message void transformKDLToMsg(const KDL::Frame &k, geometry_msgs::Transform &m); /// Converts a Twist message into a KDL Twist void twistMsgToKDL(const geometry_msgs::Twist &m, KDL::Twist &k); /// Converts a KDL Twist into a Twist message void twistKDLToMsg(const KDL::Twist &k, geometry_msgs::Twist &m); /// Converts a Vector3 message into a KDL Vector void vectorMsgToKDL(const geometry_msgs::Vector3 &m, KDL::Vector &k); /// Converts a KDL Vector into a Vector3 message void vectorKDLToMsg(const KDL::Vector &k, geometry_msgs::Vector3 &m); /// Converts a Wrench message into a KDL Wrench void wrenchMsgToKDL(const geometry_msgs::Wrench &m, KDL::Wrench &k); /// Converts a KDL Wrench into a Wrench message void wrenchKDLToMsg(const KDL::Wrench &k, geometry_msgs::Wrench &m); //Deprecated methods use above: /// Converts a Pose message into a KDL Frame void PoseMsgToKDL(const geometry_msgs::Pose &m, KDL::Frame &k)__attribute__((deprecated)); /// Converts a KDL Frame into a Pose message void PoseKDLToMsg(const KDL::Frame &k, geometry_msgs::Pose &m) __attribute__((deprecated)); /// Converts a Twist message into a KDL Twist void TwistMsgToKDL(const geometry_msgs::Twist &m, KDL::Twist &k) __attribute__((deprecated)); /// Converts a KDL Twist into a Twist message void TwistKDLToMsg(const KDL::Twist &k, geometry_msgs::Twist &m) __attribute__((deprecated)); } #endif
0
apollo_public_repos/apollo-platform/ros/geometry/kdl_conversions
apollo_public_repos/apollo-platform/ros/geometry/kdl_conversions/src/kdl_msg.cpp
/* * 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 the 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 "kdl_conversions/kdl_msg.h" namespace tf { void pointMsgToKDL(const geometry_msgs::Point &m, KDL::Vector &k) { k[0] = m.x; k[1] = m.y; k[2] = m.z; } void pointKDLToMsg(const KDL::Vector &k, geometry_msgs::Point &m) { m.x = k[0]; m.y = k[1]; m.z = k[2]; } void poseMsgToKDL(const geometry_msgs::Pose &m, KDL::Frame &k) { k.p[0] = m.position.x; k.p[1] = m.position.y; k.p[2] = m.position.z; k.M = KDL::Rotation::Quaternion( m.orientation.x, m.orientation.y, m.orientation.z, m.orientation.w); } void poseKDLToMsg(const KDL::Frame &k, geometry_msgs::Pose &m) { m.position.x = k.p[0]; m.position.y = k.p[1]; m.position.z = k.p[2]; k.M.GetQuaternion(m.orientation.x, m.orientation.y, m.orientation.z, m.orientation.w); } void quaternionMsgToKDL(const geometry_msgs::Quaternion &m, KDL::Rotation &k) { k = KDL::Rotation::Quaternion(m.x, m.y, m.z, m.w); } void quaternionKDLToMsg(const KDL::Rotation &k, geometry_msgs::Quaternion &m) { k.GetQuaternion(m.x, m.y, m.z, m.w); } void transformMsgToKDL(const geometry_msgs::Transform &m, KDL::Frame &k) { k.p[0] = m.translation.x; k.p[1] = m.translation.y; k.p[2] = m.translation.z; k.M = KDL::Rotation::Quaternion( m.rotation.x, m.rotation.y, m.rotation.z, m.rotation.w); } void transformKDLToMsg(const KDL::Frame &k, geometry_msgs::Transform &m) { m.translation.x = k.p[0]; m.translation.y = k.p[1]; m.translation.z = k.p[2]; k.M.GetQuaternion(m.rotation.x, m.rotation.y, m.rotation.z, m.rotation.w); } void twistKDLToMsg(const KDL::Twist &t, geometry_msgs::Twist &m) { m.linear.x = t.vel[0]; m.linear.y = t.vel[1]; m.linear.z = t.vel[2]; m.angular.x = t.rot[0]; m.angular.y = t.rot[1]; m.angular.z = t.rot[2]; } void twistMsgToKDL(const geometry_msgs::Twist &m, KDL::Twist &t) { t.vel[0] = m.linear.x; t.vel[1] = m.linear.y; t.vel[2] = m.linear.z; t.rot[0] = m.angular.x; t.rot[1] = m.angular.y; t.rot[2] = m.angular.z; } void vectorMsgToKDL(const geometry_msgs::Vector3 &m, KDL::Vector &k) { k[0] = m.x; k[1] = m.y; k[2] = m.z; } void vectorKDLToMsg(const KDL::Vector &k, geometry_msgs::Vector3 &m) { m.x = k[0]; m.y = k[1]; m.z = k[2]; } void wrenchMsgToKDL(const geometry_msgs::Wrench &m, KDL::Wrench &k) { k[0] = m.force.x; k[1] = m.force.y; k[2] = m.force.z; k[3] = m.torque.x; k[4] = m.torque.y; k[5] = m.torque.z; } void wrenchKDLToMsg(const KDL::Wrench &k, geometry_msgs::Wrench &m) { m.force.x = k[0]; m.force.y = k[1]; m.force.z = k[2]; m.torque.x = k[3]; m.torque.y = k[4]; m.torque.z = k[5]; } ///// Deprecated methods for backwards compatability /// Converts a Pose message into a KDL Frame void PoseMsgToKDL(const geometry_msgs::Pose &m, KDL::Frame &k) { poseMsgToKDL(m, k);} /// Converts a KDL Frame into a Pose message void PoseKDLToMsg(const KDL::Frame &k, geometry_msgs::Pose &m) { poseKDLToMsg(k, m);} /// Converts a Twist message into a KDL Twist void TwistMsgToKDL(const geometry_msgs::Twist &m, KDL::Twist &k) {twistMsgToKDL(m, k);}; /// Converts a KDL Twist into a Twist message void TwistKDLToMsg(const KDL::Twist &k, geometry_msgs::Twist &m){twistKDLToMsg(k, m);}; } // namespace tf
0
apollo_public_repos/apollo-platform/ros/geometry
apollo_public_repos/apollo-platform/ros/geometry/tf/index.rst
tf == .. toctree:: :maxdepth: 2 tf_python transformations Indices and tables ================== * :ref:`genindex` * :ref:`modindex` * :ref:`search`
0
apollo_public_repos/apollo-platform/ros/geometry
apollo_public_repos/apollo-platform/ros/geometry/tf/CMakeLists.txt
cmake_minimum_required(VERSION 2.8) project(tf) find_package(catkin REQUIRED) find_package(Boost COMPONENTS thread signals system REQUIRED) find_package(catkin COMPONENTS angles geometry_msgs message_filters message_generation rosconsole roscpp rostime sensor_msgs std_msgs tf2_ros REQUIRED) catkin_python_setup() include_directories(SYSTEM ${Boost_INCLUDE_DIR} ${catkin_INCLUDE_DIRS} ) include_directories(include) link_directories(${catkin_LIBRARY_DIRS}) add_message_files(DIRECTORY msg FILES tfMessage.msg) add_service_files(DIRECTORY srv FILES FrameGraph.srv) generate_messages(DEPENDENCIES geometry_msgs sensor_msgs std_msgs) catkin_package( INCLUDE_DIRS include LIBRARIES ${PROJECT_NAME} CATKIN_DEPENDS geometry_msgs message_filters message_runtime roscpp sensor_msgs std_msgs tf2_ros rosconsole ) add_library(${PROJECT_NAME} src/tf.cpp src/transform_listener.cpp src/cache.cpp src/transform_broadcaster.cpp) target_link_libraries(${PROJECT_NAME} ${catkin_LIBRARIES} ${Boost_LIBRARIES}) add_dependencies(${PROJECT_NAME} ${PROJECT_NAME}_gencpp) # Debug add_executable(tf_empty_listener src/empty_listener.cpp) target_link_libraries(tf_empty_listener ${PROJECT_NAME}) add_executable(tf_echo src/tf_echo.cpp) target_link_libraries(tf_echo ${PROJECT_NAME}) add_executable(tf_change_notifier src/change_notifier.cpp) target_link_libraries(tf_change_notifier ${PROJECT_NAME}) add_executable(tf_monitor src/tf_monitor.cpp) target_link_libraries(tf_monitor ${PROJECT_NAME}) add_executable(static_transform_publisher src/static_transform_publisher.cpp) target_link_libraries(static_transform_publisher ${PROJECT_NAME}) # Tests if(CATKIN_ENABLE_TESTING AND NOT ANDROID) find_package(rostest) catkin_add_gtest(tf_unittest test/tf_unittest.cpp) target_link_libraries(tf_unittest ${PROJECT_NAME}) catkin_add_gtest(tf_quaternion_unittest test/quaternion.cpp) target_link_libraries(tf_quaternion_unittest ${PROJECT_NAME}) catkin_add_gtest(test_transform_datatypes test/test_transform_datatypes.cpp) target_link_libraries(test_transform_datatypes ${PROJECT_NAME} ${Boost_LIBRARIES}) add_executable(transform_listener_unittest test/transform_listener_unittest.cpp) target_link_libraries(transform_listener_unittest ${PROJECT_NAME} ${GTEST_LIBRARIES}) add_rostest(test/transform_listener_unittest.launch) # Disabled because of changes in TransformStorage #catkin_add_gtest_future(tf_unittest_future test/tf_unittest_future.cpp) #target_link_libraries(tf_unittest_future ${PROJECT_NAME}) catkin_add_gtest(test_velocity test/velocity_test.cpp) target_link_libraries(test_velocity ${PROJECT_NAME}) #add_executable(test_transform_twist test/transform_twist_test.cpp) #target_link_libraries(test_transform_twist ${PROJECT_NAME}) #catkin_add_gtest_build_flags(test_transform_twist) #add_rostest(test/transform_twist_test.launch) catkin_add_gtest(cache_unittest test/cache_unittest.cpp) target_link_libraries(cache_unittest ${PROJECT_NAME}) add_executable(test_message_filter EXCLUDE_FROM_ALL test/test_message_filter.cpp) target_link_libraries(test_message_filter tf ${Boost_LIBRARIES} ${GTEST_LIBRARIES}) add_rostest(test/test_message_filter.xml) ### Benchmarking #catkin_add_gtest_future(tf_benchmark test/tf_benchmark.cpp) #target_link_libraries(tf_benchmark ${PROJECT_NAME}) add_executable(testListener test/testListener.cpp) target_link_libraries(testListener ${PROJECT_NAME} ${GTEST_LIBRARIES}) add_rostest(test/test_broadcaster.launch) add_executable(testBroadcaster test/testBroadcaster.cpp) target_link_libraries(testBroadcaster ${PROJECT_NAME}) endif() if(NOT ANDROID) #Python setup set(Python_ADDITIONAL_VERSIONS 2.7) find_package(PythonLibs REQUIRED) include_directories(${PYTHON_INCLUDE_PATH}) # # If on Darwin, create a symlink _foo.so -> _foo.dylib, because the # # MacPorts version of Python won't find _foo.dylib for 'import _foo' # include(CMakeDetermineSystem) # if(CMAKE_SYSTEM_NAME MATCHES "Darwin") # add_custom_command(OUTPUT ${LIBRARY_OUTPUT_PATH}/_${PROJECT_NAME}_swig.so # COMMAND cmake -E create_symlink ${LIBRARY_OUTPUT_PATH}/_${PROJECT_NAME}_swig.dylib ${LIBRARY_OUTPUT_PATH}/_${PROJECT_NAME}_swig.so # DEPENDS python_${PROJECT_NAME}) # add_custom_target(symlink_darwin_lib ALL # DEPENDS ${LIBRARY_OUTPUT_PATH}/_${PROJECT_NAME}_swig.so) # endif(CMAKE_SYSTEM_NAME MATCHES "Darwin") # Check for SSE #check_for_sse() # Dynamic linking with tf worked OK, except for exception propagation, which failed in the unit test. # so build with the objects directly instead. link_libraries(${PYTHON_LIBRARIES}) add_library(pytf_py src/pytf.cpp src/tf.cpp src/transform_listener.cpp src/cache.cpp) add_dependencies(pytf_py ${PROJECT_NAME}_gencpp) find_package(PythonLibs REQUIRED) set_target_properties(pytf_py PROPERTIES OUTPUT_NAME tf PREFIX "_" SUFFIX ".so" LIBRARY_OUTPUT_DIRECTORY ${CATKIN_DEVEL_PREFIX}/${PYTHON_INSTALL_DIR}/tf) target_link_libraries(pytf_py ${Boost_LIBRARIES} ${catkin_LIBRARIES}) endif() if(CATKIN_ENABLE_TESTING AND NOT ANDROID) catkin_add_nosetests(test/testPython.py) add_executable(tf_speed_test EXCLUDE_FROM_ALL test/speed_test.cpp) target_link_libraries(tf_speed_test ${PROJECT_NAME}) endif() install(DIRECTORY include/${PROJECT_NAME}/ DESTINATION ${CATKIN_PACKAGE_INCLUDE_DESTINATION}) install(TARGETS ${PROJECT_NAME} tf_echo tf_empty_listener tf_change_notifier tf_monitor static_transform_publisher ARCHIVE DESTINATION ${CATKIN_PACKAGE_LIB_DESTINATION} LIBRARY DESTINATION ${CATKIN_PACKAGE_LIB_DESTINATION} RUNTIME DESTINATION ${CATKIN_PACKAGE_BIN_DESTINATION}) if(NOT ANDROID) install(TARGETS pytf_py LIBRARY DESTINATION ${CMAKE_INSTALL_PREFIX}/${PYTHON_INSTALL_DIR}/tf) endif() # Install rosrun-able scripts install(PROGRAMS scripts/bullet_migration_sed.py scripts/tf_remap scripts/view_frames DESTINATION ${CATKIN_PACKAGE_BIN_DESTINATION} ) if(TARGET tests) add_dependencies(tests testBroadcaster testListener transform_listener_unittest test_message_filter ) endif()
0