diff --git a/.github/CODE_OF_CONDUCT.md b/.github/CODE_OF_CONDUCT.md new file mode 100644 index 00000000..3f355bbe --- /dev/null +++ b/.github/CODE_OF_CONDUCT.md @@ -0,0 +1,42 @@ +## Our Pledge + +In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation. + +## Our Standards + +Examples of behavior that contributes to creating a positive environment include: + +- Using welcoming and inclusive language +- Being respectful of differing viewpoints and experiences +- Gracefully accepting constructive criticism +- Focusing on what is best for the community +- Showing empathy towards other community members + +Examples of unacceptable behavior by participants include: + +- The use of sexualized language or imagery and unwelcome sexual attention or advances +- Trolling, insulting/derogatory comments, and personal or political attacks +- Public or private harassment +- Publishing others’ private information, such as a physical or electronic address, without explicit permission +- Other conduct which could reasonably be considered inappropriate in a professional setting + + +## Our Responsibilities + +Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior. + +Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful. + +## Scope + +This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers. + +## Enforcement + +Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at n-ando@aist.go.jp . All complaints will be reviewed and investigated and will result in a response that is deemed necessary and appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately. + +Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project’s leadership. + +## Attribution + +This Code of Conduct is adapted from the Contributor Covenant, version 1.4, available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md new file mode 100644 index 00000000..595f40d0 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/bug_report.md @@ -0,0 +1,52 @@ +--- +name: Bug report +about: Create a report to help us improve (Note! This is Python repository) +title: '' +labels: bug +assignees: '' + +--- + + + + + +**Describe the bug** +A clear and concise description of what the bug is. + +**To Reproduce** +Steps to reproduce the behavior: +1. Go to '...' +2. Click on '....' +3. Scroll down to '....' +4. See error + +**Reproducibility** +Ran XXX times, occurred YYY times. + +**Expected behavior** +A clear and concise description of what you expected to happen. + +**Screenshots or Logs** +If applicable, add screenshots or logs to help explain your problem. + +**Environment** + - OS: [e.g. Ubuntu 16.04 32bits] + - OpenRTM-aist Version [e.g. 1.2.1] + - ... + +**Additional context** +Add any other context about the problem here. diff --git a/.github/ISSUE_TEMPLATE/feature_request.md b/.github/ISSUE_TEMPLATE/feature_request.md new file mode 100644 index 00000000..c609950c --- /dev/null +++ b/.github/ISSUE_TEMPLATE/feature_request.md @@ -0,0 +1,37 @@ +--- +name: Feature request +about: Suggest an idea for this project (Note! This is Python repository) +title: '' +labels: enhancement +assignees: '' + +--- + + + + + +**Is your feature request related to a problem? Please describe.** +A clear and concise description of what the problem is. + +**Describe the solution you'd like** +A clear and concise description of what you want to happen. + +**Describe alternatives you've considered** +A clear and concise description of any alternative solutions or features you've considered. + +**Additional context** +Add any other context or screenshots about the feature request here. diff --git a/.github/ISSUE_TEMPLATE/question.md b/.github/ISSUE_TEMPLATE/question.md new file mode 100644 index 00000000..3df737da --- /dev/null +++ b/.github/ISSUE_TEMPLATE/question.md @@ -0,0 +1,25 @@ +--- +name: Question +about: Questions about this project (Note! This is Python repository) +title: '' +labels: question +assignees: '' + +--- + + + + diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md new file mode 100644 index 00000000..9522be98 --- /dev/null +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -0,0 +1,28 @@ + + +## Identify the Bug + +Link to the issue describing the bug that you're fixing. +If there is not yet an issue for your bug, please open a new issue and then link to that issue in your pull request. + + +## Description of the Change + +We must be able to understand the design of your change from this description. + + +## Verification + + + +- [ ] Did you succeed the build? +- [ ] No warnings for the build? +- [ ] Have you passed the unit tests? diff --git a/COPYING.LIB b/COPYING.LIB new file mode 100644 index 00000000..65c5ca88 --- /dev/null +++ b/COPYING.LIB @@ -0,0 +1,165 @@ + GNU LESSER GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + + This version of the GNU Lesser General Public License incorporates +the terms and conditions of version 3 of the GNU General Public +License, supplemented by the additional permissions listed below. + + 0. Additional Definitions. + + As used herein, "this License" refers to version 3 of the GNU Lesser +General Public License, and the "GNU GPL" refers to version 3 of the GNU +General Public License. + + "The Library" refers to a covered work governed by this License, +other than an Application or a Combined Work as defined below. + + An "Application" is any work that makes use of an interface provided +by the Library, but which is not otherwise based on the Library. +Defining a subclass of a class defined by the Library is deemed a mode +of using an interface provided by the Library. + + A "Combined Work" is a work produced by combining or linking an +Application with the Library. The particular version of the Library +with which the Combined Work was made is also called the "Linked +Version". + + The "Minimal Corresponding Source" for a Combined Work means the +Corresponding Source for the Combined Work, excluding any source code +for portions of the Combined Work that, considered in isolation, are +based on the Application, and not on the Linked Version. + + The "Corresponding Application Code" for a Combined Work means the +object code and/or source code for the Application, including any data +and utility programs needed for reproducing the Combined Work from the +Application, but excluding the System Libraries of the Combined Work. + + 1. Exception to Section 3 of the GNU GPL. + + You may convey a covered work under sections 3 and 4 of this License +without being bound by section 3 of the GNU GPL. + + 2. Conveying Modified Versions. + + If you modify a copy of the Library, and, in your modifications, a +facility refers to a function or data to be supplied by an Application +that uses the facility (other than as an argument passed when the +facility is invoked), then you may convey a copy of the modified +version: + + a) under this License, provided that you make a good faith effort to + ensure that, in the event an Application does not supply the + function or data, the facility still operates, and performs + whatever part of its purpose remains meaningful, or + + b) under the GNU GPL, with none of the additional permissions of + this License applicable to that copy. + + 3. Object Code Incorporating Material from Library Header Files. + + The object code form of an Application may incorporate material from +a header file that is part of the Library. You may convey such object +code under terms of your choice, provided that, if the incorporated +material is not limited to numerical parameters, data structure +layouts and accessors, or small macros, inline functions and templates +(ten or fewer lines in length), you do both of the following: + + a) Give prominent notice with each copy of the object code that the + Library is used in it and that the Library and its use are + covered by this License. + + b) Accompany the object code with a copy of the GNU GPL and this license + document. + + 4. Combined Works. + + You may convey a Combined Work under terms of your choice that, +taken together, effectively do not restrict modification of the +portions of the Library contained in the Combined Work and reverse +engineering for debugging such modifications, if you also do each of +the following: + + a) Give prominent notice with each copy of the Combined Work that + the Library is used in it and that the Library and its use are + covered by this License. + + b) Accompany the Combined Work with a copy of the GNU GPL and this license + document. + + c) For a Combined Work that displays copyright notices during + execution, include the copyright notice for the Library among + these notices, as well as a reference directing the user to the + copies of the GNU GPL and this license document. + + d) Do one of the following: + + 0) Convey the Minimal Corresponding Source under the terms of this + License, and the Corresponding Application Code in a form + suitable for, and under terms that permit, the user to + recombine or relink the Application with a modified version of + the Linked Version to produce a modified Combined Work, in the + manner specified by section 6 of the GNU GPL for conveying + Corresponding Source. + + 1) Use a suitable shared library mechanism for linking with the + Library. A suitable mechanism is one that (a) uses at run time + a copy of the Library already present on the user's computer + system, and (b) will operate properly with a modified version + of the Library that is interface-compatible with the Linked + Version. + + e) Provide Installation Information, but only if you would otherwise + be required to provide such information under section 6 of the + GNU GPL, and only to the extent that such information is + necessary to install and execute a modified version of the + Combined Work produced by recombining or relinking the + Application with a modified version of the Linked Version. (If + you use option 4d0, the Installation Information must accompany + the Minimal Corresponding Source and Corresponding Application + Code. If you use option 4d1, you must provide the Installation + Information in the manner specified by section 6 of the GNU GPL + for conveying Corresponding Source.) + + 5. Combined Libraries. + + You may place library facilities that are a work based on the +Library side by side in a single library together with other library +facilities that are not Applications and are not covered by this +License, and convey such a combined library under terms of your +choice, if you do both of the following: + + a) Accompany the combined library with a copy of the same work based + on the Library, uncombined with any other library facilities, + conveyed under the terms of this License. + + b) Give prominent notice with the combined library that part of it + is a work based on the Library, and explaining where to find the + accompanying uncombined form of the same work. + + 6. Revised Versions of the GNU Lesser General Public License. + + The Free Software Foundation may publish revised and/or new versions +of the GNU Lesser General Public License from time to time. Such new +versions will be similar in spirit to the present version, but may +differ in detail to address new problems or concerns. + + Each version is given a distinguishing version number. If the +Library as you received it specifies that a certain numbered version +of the GNU Lesser General Public License "or any later version" +applies to it, you have the option of following the terms and +conditions either of that published version or of any later version +published by the Free Software Foundation. If the Library as you +received it does not specify a version number of the GNU Lesser +General Public License, you may choose any version of the GNU Lesser +General Public License ever published by the Free Software Foundation. + + If the Library as you received it specifies that a proxy can decide +whether future versions of the GNU Lesser General Public License shall +apply, that proxy's public statement of acceptance of any version is +permanent authorization for you to choose that version for the +Library. diff --git a/COPYRIGHT b/COPYRIGHT new file mode 100755 index 00000000..3ef692be --- /dev/null +++ b/COPYRIGHT @@ -0,0 +1,79 @@ + +Copyright (C) 2003-2018 + Noriaki Ando and the OpenRTM-aist Project team + Intelligent Systems Research Institute, + National Institute of Advanced Industrial Science and Technology (AIST), + Tsukuba, Japan, All rights reserved. + + +NOTICE +------ +THIS IS A LEGAL CONTRACT BETWEEN YOU AND THE COPYRIGHT HOLDER. YOU +SHOULD CAREFULLY READ AND ACCEPT ALL THE TERMS AND CONDITIONS SET +FORTH IN THIS DOCUMENT BEFORE USING ALL OR ANY PORTION OF THIS +SOFTWARE. BY USING THE SOFTWARE, YOU ARE AGREEING TO BE BOUND BY ALL +OF THE TERMS AND CONDITION OF THIS LICENSE AND ALSO AGREE THAT THIS +AGREEMENT IS ENFORCEABLE LIKE ANY WRITTEN NEGOTIATED AGREEMENT SIGNED +BY YOU. + + +LICENSE +------- +The OpenRTM-aist (H22PRO-1089) is the dual-licensed open source +software. You can use, copy, distribute and/or modify this library +under the terms and conditions of either of the licenses below. + +1) LGPL (GNU LESSER GENERAL PUBLIC LICENSE) +See COPYING.LIB. + +2) Individual Licnese +You can purchase license from AIST and/or AIST's TLO to copy, +distribute, modify and/or sublicense the library without any +limitation in the terms of LGPL. The individual license should be +concluded with a negotiated agreement between you and AIST and/or AIST +TLO. To conclude individual license, contact the person responsible of +AIST. + + +SUBMISSIONS +----------- +The OpenRTM-aist is maintained by the National Institute of Advanced +Industrial Science and Technology (AIST), Tsukuba, Japan for the +development of open-source software as part of the open-source +software community. By submitting comments, suggestions, code, code +snippets, techniques (including that of usage) and algorithms +(collectively ``Submissions''), submitters acknowledge that they have +the right to do so, that any such Submissions are given freely and +unreservedly, and that they waive any claims to copyright or +ownership. In addition, submitters acknowledge that any such +Submission might become part of the copyright maintained on the +overall body of code that comprises the OpenRTM-aist. By making a +Submission, submitter agree to these terms. Moreover, submitters +acknowledge that the incorporation or modification of such Submissions +is entirely at the discretion of the moderators of the open-source +software projects or their designees. + + +DISCLAIMER +---------- +THIS SOFTWARE IS PROVIDED BY AUTHOR 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 AUTHOR 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. + + +CONTACT INFORMATION +------------------- +Noriaki Ando +National Institute of Advanced Industrial Science and Technology +Intelligent Systems Research Institute +Tsukuba Central 2, 1-1-1 Umezono, Tsukuba, Ibaraki 305-8568 JAPAN. +TEL: +81-29-861-5981 FAX: +81-29-861-6631 + diff --git a/INSTALL.jp b/INSTALL.jp new file mode 100644 index 00000000..9328ea95 --- /dev/null +++ b/INSTALL.jp @@ -0,0 +1,9 @@ +============================================================ + OpenRTM-aist-Python-2.0.0 のソースからのインストール +============================================================ + +OpenRTM-aist-Python-2.0.0 をソースからビルドしインストールする手順については、 +下記サイトの手順に従って行ってください。 + + * Official Site + http://openrtm.org \ No newline at end of file diff --git a/MANIFEST.in b/MANIFEST.in index 774be978..75b1d422 100644 --- a/MANIFEST.in +++ b/MANIFEST.in @@ -4,7 +4,7 @@ include setup.py include README recursive-include packages Makefile recursive-include packages/deb *.sh copyright changelog rules README* compat control control.* files -recursive-include packages/rpm *.sh openrtm-aist.spec.in openrtm-aist_fc19.spec.in +recursive-include packages/rpm *.sh openrtm-aist.spec.in openrtm-aist_py3.spec.in recursive-include OpenRTM_aist *.conf *.exe *.idl *.py *.pth *.sh recursive-include OpenRTM_aist *.bat *.exe *.sample README recursive-include OpenRTM_aist/docs *.css *.gif *.png *.html *.hhc *.hhk *.hhp Doxyfile_en.in Doxyfile_jp.in diff --git a/OpenRTM_aist/Async.py b/OpenRTM_aist/Async.py index c4a8d90e..6c648380 100644 --- a/OpenRTM_aist/Async.py +++ b/OpenRTM_aist/Async.py @@ -1,5 +1,5 @@ #!/usr/bin/env python -# -*- coding: euc-jp -*- +# -*- coding: utf-8 -*- ## # @file Async.py @@ -24,80 +24,75 @@ class Async_t(OpenRTM_aist.Task): - def __init__(self, obj, func, *args): - OpenRTM_aist.Task.__init__(self) - self._obj = obj - self._func = func - self._finished = False - self._args = args - self._mutex = threading.RLock() + def __init__(self, obj, func, *args): + OpenRTM_aist.Task.__init__(self) + self._obj = obj + self._func = func + self._finished = False + self._args = args + self._mutex = threading.RLock() - def invoke(self): - self.activate() + def invoke(self): + self.activate() + def finished(self): + guard = OpenRTM_aist.ScopedLock(self._mutex) + return self._finished - def finished(self): - guard = OpenRTM_aist.ScopedLock(self._mutex) - return self._finished + def svc(self): + if self._args: + self._func(self._obj, *self._args) + else: + self._func(self._obj) - - def svc(self): - if len(self._args) > 0: - self._func(self._obj, *self._args) - else: - self._func(self._obj) - - guard = OpenRTM_aist.ScopedLock(self._mutex) - self._finished = True - return 0 + guard = OpenRTM_aist.ScopedLock(self._mutex) + self._finished = True + return 0 class Async_ref_t(OpenRTM_aist.Task): - def __init__(self, obj, func, *args): - OpenRTM_aist.Task.__init__(self) - self._obj = obj - self._func = func - self._args = args - self._finished = False - + def __init__(self, obj, func, *args): + OpenRTM_aist.Task.__init__(self) + self._obj = obj + self._func = func + self._args = args + self._finished = False + + def invoke(self): + self.activate() - def invoke(self): - self.activate() + def finished(self): + return self._finished + def svc(self): + if self._args: + self._func(self._obj, *self._args) + else: + self._func(self._obj) - def finished(self): - return self._finished - + self._finished = True + return 0 - def svc(self): - if len(self._args) > 0: - self._func(self._obj, *self._args) - else: - self._func(self._obj) - self._finished = True - return 0 - - ## # @if jp -# @brief ƱСؿƤӽФإѡؿ +# @brief 非同期メンバー関数呼び出しヘルパー関数 # -# СؿƱ˸Ƥ֤Υإѡؿ -# +# メンバー関数を非同期に呼ぶためのヘルパー関数 +# 例 # # class A # { # public: -# // ֤Τؿ +# // 時間のかかる関数 # void hoge() { # for (int i(0); i < 5; ++i) { # std::cout << "hoge" << std::endl; # sleep(1); # } # } -# // ֤Τؿ +# // 時間のかかる関数 # void munya(const char* msg) { # for (int i(0); i < 10; ++i) { # std::cout << "message is: " << msg << std::endl; @@ -108,22 +103,22 @@ def svc(self): # return val + 1; # } # }; -# ͤʥ饹Υ֥ȤФơ +# この様なクラスのオブジェクトに対して、 # # A a; # Async* invoker0(AsyncInvoker(&a, # std::mem_fun(&A::hoge))); # Async* invoker1(AsyncInvoker(&a, # std::bind2nd(std::mem_fun(&A::munya), -# "ۤ"))); -# invoker0->invoke(); // -# invoker1->invoke(); // +# "ほげ"))); +# invoker0->invoke(); // すぐに戻る +# invoker1->invoke(); // すぐに戻る # -# delete invoker0; // ɬ뤳 -# delete invoker1; // ɬ뤳 +# delete invoker0; // 必ず削除すること +# delete invoker1; // 必ず削除すること # -# Τ褦ƱθƤӽФǤ롣 -# ƤӽФͤϡδؿ֥ȤѰդ롣 +# のように非同期の呼び出しができる。 +# 呼び出しの戻り値を取得したい場合は、自前の関数オブジェクトを用意する。 # # class add_one_functor # { @@ -138,7 +133,7 @@ def svc(self): # } # }; # -# 嵭δؿ֥ȤΥ󥹥󥹤Υݥ󥿤Ϥ +# 上記の関数オブジェクトのインスタンスを作成し、そのポインタを渡す。 # # add_one_functor aof(100); # Async* invoker2(AsyncInvoker(&a, &aof)); @@ -147,24 +142,24 @@ def svc(self): # std::cout << "result: " << aof.get_ret() << std::endl; # delete invoker2; # -# ̾AsyncInvoker ֤֥ȤŪ˺ʤ -# ʤʤ軰 true ϤȤǡƱ¹ԤλƱ -# ưŪ˥󥹥󥹤롣 +# 通常、AsyncInvoker が返すオブジェクトは明示的に削除しなければ +# ならないが、第三引数に true を渡すことで、非同期実行が終了すると同時に +# 自動的にインスタンスが削除される。 # -# // invoker3 Ϻ (delete invoker3) ƤϤʤ +# // invoker3 は削除 (delete invoker3) してはいけない # Async* invoker3(AsyncInvoker(&a, std::mem_fun(&A::hoge), true)); # -# // 󥹥Ʊ˼¹Ԥ뤳ȤǤ롣 +# // インスタンス生成と同時に実行することもできる。 # AsyncInvoker(&a, std::mem_fun(&A::hoge))->invoke(); # # @else # # @endif # -#def Async_tInvoker(func, auto_delete = False): +# def Async_tInvoker(func, auto_delete = False): def Async_tInvoker(obj, func, *args): - return Async_t(obj, func, *args) + return Async_t(obj, func, *args) def Async_ref_tInvoker(obj, func, *args): - return Async_ref_t(obj, func, *args) + return Async_ref_t(obj, func, *args) diff --git a/OpenRTM_aist/BufferBase.py b/OpenRTM_aist/BufferBase.py index 38fcf193..be7940cb 100644 --- a/OpenRTM_aist/BufferBase.py +++ b/OpenRTM_aist/BufferBase.py @@ -1,5 +1,5 @@ #!/usr/bin/env python -# -*- coding: euc-jp -*- +# -*- coding: utf-8 -*- ## # @file BufferBase.py @@ -20,637 +20,640 @@ ## # @if jp # @class BufferBase -# @brief BufferBase ݥ饹 -# -# ΥХåեΤݥ󥿡ե饹 -# ݥХåե饹ϡʲδؿμ󶡤ʤФʤʤ -# -# public󥿡եȤưʲΤΤ󶡤롣 -# - write(): Хåե˽񤭹 -# - read(): Хåեɤ߽Ф -# - length(): ХåեĹ֤ -# - isFull(): ХåեդǤ -# - isEmpty(): ХåեǤ -# -# protected󥿡եȤưʲΤΤ󶡤롣 -# - put(): Хåե˥ǡ񤭹 -# - get(): Хåեǡɤ߽Ф -# +# @brief BufferBase 抽象クラス +# +# 種々のバッファのための抽象インターフェースクラス。 +# 具象バッファクラスは、以下の関数の実装を提供しなければならない。 +# +# publicインターフェースとして以下のものを提供する。 +# - write(): バッファに書き込む +# - read(): バッファから読み出す +# - length(): バッファ長を返す +# - isFull(): バッファが満杯である +# - isEmpty(): バッファが空である +# +# protectedインターフェースとして以下のものを提供する。 +# - put(): バッファにデータを書き込む +# - get(): バッファからデータを読み出す +# # @since 0.4.0 -# +# # @else -# +# # @class BufferBase # @brief BufferBase abstract class -# +# # This is the abstract interface class for various Buffer. -# +# # @since 0.4.0 -# +# # @endif -class BufferBase(OpenRTM_aist.BufferStatus): - """ - """ - - - ## - # @if jp - # @brief Хåե - # - # Properties Ϳץѥƥˤꡢ - # Хåե롣 - # ѤǤ륪ץỌ̇̄ϰʲ̤ - # - # - buffer.length: - # ХåեĹʳοͤꤵƤ̵뤵롣 - # Ǥ˥ХåեѾ֤Ǥ⡢Ĺꤵ줿Τ٤Ƥ - # ݥ󥿤롣 - # - # - buffer.write.full_policy: - # 񤭤뤫ɤΥݥꥷ - # overwrite (), do_nothing (⤷ʤ), block (֥å) - # block ꤷ硢 timeout ͤꤹСָ - # 񤭹ԲǽǤХॢȤ롣 - # ǥեȤ overwrite () - # - # - buffer.write.timeout: - # ॢȻ֤ [sec] ǻꤹ롣ǥեȤ 1.0 [sec] - # 1 sec -> 1.0, 1 ms -> 0.001, ॢȤʤ -> 0.0 - # - # - buffer.read.empty_policy: - # ХåեΤȤɤ߽Фݥꥷ - # readback (Ǹ), do_nothing (⤷ʤ), block (֥å) - # block ꤷ硢 timeout ͤꤹСָ - # ɤ߽ФԲǽǤХॢȤ롣 - # ǥեȤ readback (Ǹ) - # - # - buffer.read.timeout: - # ॢȻ [sec] ǻꤹ롣ǥեȤ 1.0 [sec] - # 1sec -> 1.0, 1ms -> 0.001, ॢȤʤ -> 0.0 - # - # @else - # - # @endif - def init(self, prop): - pass - - - ## - # @if jp - # - # @brief ХåեĹ(֥饹) - # - # ХåեĹ
- # ֥饹Ǥμ - # - # @param self - # - # @return ХåեĹ - # - # @else - # - # @brief Get the buffer length - # - # @return buffer length - # - # @endif - def length(self): - pass - - - ## - # @if jp - # - # @brief Хåեξ֤ꥻåȤ - # - # Хåեɤ߽Фݥ󥿤Ƚ񤭹ߥݥ󥿤ΰ֤ꥻåȤ롣 - # - # @return BUFFER_OK: ェλ - # NOT_SUPPORTED: ХåեĹѹԲ - # BUFFER_ERROR: ۾ェλ - # - # @else - # - # @brief Get the buffer length - # - # Pure virtual function to get the buffer length. - # - # @return buffer length - # - # @endif - # - def reset(self): - pass - - - ## - # @if jp - # - # @brief ХåեθߤνǤΥݥ - # - # ХåեθߤνǤΥݥ󥿤ޤϡnΥݥ󥿤֤ - # - # @param n ߥݥ + n ΰ֤Υݥ - # @return ֤߰Υݥ - # - # @else - # - # @brief Get the buffer length - # - # Pure virtual function to get the buffer length. - # - # @return buffer length - # - # @endif - def wptr(self, n=0): - pass - - - ## - # @if jp - # - # @brief ߥݥ󥿤ʤ - # - # ߤν񤭹֤߰Υݥ󥿤 n Ŀʤ롣 - # - # @param n ߥݥ + n ΰ֤Υݥ - # @param unlock_enable Trueξ˥ХåեץƥΥ֥å - # @return BUFFER_OK: ェλ - # BUFFER_ERROR: ۾ェλ - # - # @else - # - # @brief Get the buffer length - # - # Pure virtual function to get the buffer length. - # - # @return buffer length - # - # @endif - def advanceWptr(self, n = 1, unlock_enable=True): - pass - - - ## - # @if jp - # - # @brief Хåե˥ǡǼ(֥饹) - # - # ХåեؤΥǡǼѴؿ
- # ֥饹Ǥμ - # - # @param self - # @param data оݥǡ - # - # @else - # - # @brief Write data into the buffer - # - # @endif - def put(self, data): - pass - - - ## - # @if jp - # - # @brief Хåե˥ǡ񤭹(֥饹) - # - # Хåե˥ǡ񤭹
- # ֥饹Ǥμ - # - # @param self - # @param value 񤭹оݥǡ - # - # @return ǡ񤭹߷(true:񤭹false:񤭹߼) - # - # @else - # - # @brief Write data into the buffer - # - # @endif - def write(self, value, sec=-1, nsec=-1): - pass - - - ## - # @if jp - # - # @brief Хåե˽߲ǽǿ - # - # Хåե˽߲ǽǿ֤ - # - # @return 񤭹߲ǽǿ - # - # @return BUFFER_OK: ェλ - # BUFFER_ERROR: ۾ェλ - # - # @else - # - # @brief Write data into the buffer - # - # Pure virtual function to write data into the buffer. - # - # @param value Target data to write. - # - # @return Result of having written in data (true:Successful, false:Failed) - # - # @endif - def writable(self): - pass - - - ## - # @if jp - # - # @brief Хåեfullå - # - # Хåեfullåѽ貾۴ؿ - # - # @return fullå(true:Хåեfullfalse:Хåե) - # - # @else - # - # @brief Check on whether the buffer is full. - # - # Pure virtual function to check on whether the buffer is full. - # - # @return True if the buffer is full, else false. - # - # @endif - def full(self): - pass - - - ## - # @if jp - # - # @brief Хåեθߤɤ߽ФǤΥݥ - # - # Хåեθߤɤ߽ФǤΥݥ󥿤ޤϡnΥݥ󥿤֤ - # - # @param n ɤ߽Фݥ + n ΰ֤Υݥ - # @return ɤ߽Ф֤Υݥ - # - # @else - # - # @brief Get the buffer length - # - # Pure virtual function to get the buffer length. - # - # @return buffer length - # - # @endif - def rptr(self, n = 0): - pass - - ## - # @if jp - # - # @brief ɤ߽Фݥ󥿤ʤ - # - # ߤɤ߽Ф֤Υݥ󥿤 n Ŀʤ롣 - # - # @param n ɤ߽Фݥ + n ΰ֤Υݥ - # @param unlock_enable Trueξ˥ХåեեΥ֥å - # @return BUFFER_OK: ェλ - # BUFFER_ERROR: ۾ェλ - # - # @else - # - # @brief Get the buffer length - # - # Pure virtual function to get the buffer length. - # - # @return buffer length - # - # @endif - def advanceRptr(self, n = 1, unlock_enable=True): - pass - - - ## - # @if jp - # - # @brief Хåեǡ(֥饹) - # - # Хåե˳Ǽ줿ǡѴؿ
- # ֥饹Ǥμ - # - # @param self - # - # @return ǡ - # - # @else - # - # @brief Get data from the buffer - # - # @endif - def get(self): - pass - - - ## - # @if jp - # - # @brief Хåեǡɤ߽Ф(֥饹) - # - # Хåեǡɤ߽Ф
- # ֥饹Ǥμ - # - # @param self - # @param value ɤ߽Фǡ - # - # @return ǡɤ߽Ф(true:ɤ߽Фfalse:ɤ߽Ф) - # - # @else - # - # @brief Read data from the buffer - # - # @endif - def read(self, value, sec = -1, nsec = -1): - pass - - - ## - # @if jp - # - # @brief Хåեɤ߽Фǽǿ - # - # Хåեɤ߽Фǽǿ֤ - # - # @return ɤ߽Фǽǿ - # - # @return BUFFER_OK: ェλ - # BUFFER_ERROR: ۾ェλ - # - # @else - # - # @brief Write data into the buffer - # - # Pure virtual function to write data into the buffer. - # - # @param value Target data to write. - # - # @return Result of having written in data (true:Successful, false:Failed) - # - # @endif - def readable(self): - pass - - - ## - # @if jp - # - # @brief Хåեemptyå - # - # Хåեemptyåѽ貾۴ؿ - # - # @return emptyå(true:Хåեemptyfalse:Хåեǡ) - # - # @else - # - # @brief Check on whether the buffer is empty. - # - # Pure virtual function to check on whether the buffer is empty. - # - # @return True if the buffer is empty, else false. - # - # @endif - def empty(self): - pass +class BufferBase(OpenRTM_aist.BufferStatus): + """ + """ + + ## + # @if jp + # @brief バッファの設定 + # + # Properties で与えられるプロパティにより、 + # バッファの設定を初期化する。 + # 使用できるオプションと意味は以下の通り + # + # - buffer.length: + # バッファの長さ。自然数以外の数値が指定されても無視される。す + # でにバッファが使用状態でも、長さが再設定されたのち、すべての + # ポインタが初期化される。 + # + # - buffer.write.full_policy: + # 上書きするかどうかのポリシー。 + # overwrite (上書き), do_nothing (何もしない), block (ブロックする) + # block を指定した場合、次の timeout 値を指定すれば、指定時間後 + # 書き込み不可能であればタイムアウトする。 + # デフォルトは overwrite (上書き)。 + # + # - buffer.write.timeout: + # タイムアウト時間を [sec] で指定する。デフォルトは 1.0 [sec]。 + # 1 sec -> 1.0, 1 ms -> 0.001, タイムアウトしない -> 0.0 + # + # - buffer.read.empty_policy: + # バッファが空のときの読み出しポリシー。 + # readback (最後の要素), do_nothing (何もしない), block (ブロックする) + # block を指定した場合、次の timeout 値を指定すれば、指定時間後 + # 読み出し不可能であればタイムアウトする。 + # デフォルトは readback (最後の要素)。 + # + # - buffer.read.timeout: + # タイムアウト時間 [sec] で指定する。デフォルトは 1.0 [sec]。 + # 1sec -> 1.0, 1ms -> 0.001, タイムアウトしない -> 0.0 + # + # @else + # + # @endif + def init(self, prop): + pass + + ## + # @if jp + # + # @brief バッファの長さを取得する(サブクラス実装用) + # + # バッファ長を取得する
+ # ※サブクラスでの実装参照用 + # + # @param self + # + # @return バッファ長 + # + # @else + # + # @brief Get the buffer length + # + # @return buffer length + # + # @endif + + def length(self): + pass + + ## + # @if jp + # + # @brief バッファの状態をリセットする + # + # バッファの読み出しポインタと書き込みポインタの位置をリセットする。 + # + # @return BUFFER_OK: 正常終了 + # NOT_SUPPORTED: バッファ長変更不可 + # BUFFER_ERROR: 異常終了 + # + # @else + # + # @brief Get the buffer length + # + # Pure virtual function to get the buffer length. + # + # @return buffer length + # + # @endif + # + + def reset(self): + pass + + ## + # @if jp + # + # @brief バッファの現在の書込み要素のポインタ + # + # バッファの現在の書込み要素のポインタまたは、n個先のポインタを返す + # + # @param n 書込みポインタ + n の位置のポインタ + # @return 書込み位置のポインタ + # + # @else + # + # @brief Get the buffer length + # + # Pure virtual function to get the buffer length. + # + # @return buffer length + # + # @endif + + def wptr(self, n=0): + pass + + ## + # @if jp + # + # @brief 書込みポインタを進める + # + # 現在の書き込み位置のポインタを n 個進める。 + # + # @param n 書込みポインタ + n の位置のポインタ + # @param unlock_enable Trueの場合にバッファエンプティのブロックを解除する + # @return BUFFER_OK: 正常終了 + # BUFFER_ERROR: 異常終了 + # + # @else + # + # @brief Get the buffer length + # + # Pure virtual function to get the buffer length. + # + # @return buffer length + # + # @endif + + def advanceWptr(self, n=1, unlock_enable=True): + pass + + ## + # @if jp + # + # @brief バッファにデータを格納する(サブクラス実装用) + # + # バッファへのデータ格納用関数
+ # ※サブクラスでの実装参照用 + # + # @param self + # @param data 対象データ + # + # @else + # + # @brief Write data into the buffer + # + # @endif + + def put(self, data): + pass + + ## + # @if jp + # + # @brief バッファにデータを書き込む(サブクラス実装用) + # + # バッファにデータを書き込む
+ # ※サブクラスでの実装参照用 + # + # @param self + # @param value 書き込み対象データ + # + # @return データ書き込み結果(true:書き込み成功,false:書き込み失敗) + # + # @else + # + # @brief Write data into the buffer + # + # @endif + + def write(self, value, sec=-1, nsec=-1): + pass + + ## + # @if jp + # + # @brief バッファに書込み可能な要素数 + # + # バッファに書込み可能な要素数を返す。 + # + # @return 書き込み可能な要素数 + # + # @return BUFFER_OK: 正常終了 + # BUFFER_ERROR: 異常終了 + # + # @else + # + # @brief Write data into the buffer + # + # Pure virtual function to write data into the buffer. + # + # @param value Target data to write. + # + # @return Result of having written in data (true:Successful, false:Failed) + # + # @endif + + def writable(self): + pass + + ## + # @if jp + # + # @brief バッファfullチェック + # + # バッファfullチェック用純粋仮想関数 + # + # @return fullチェック結果(true:バッファfull,false:バッファ空きあり) + # + # @else + # + # @brief Check on whether the buffer is full. + # + # Pure virtual function to check on whether the buffer is full. + # + # @return True if the buffer is full, else false. + # + # @endif + + def full(self): + pass + + ## + # @if jp + # + # @brief バッファの現在の読み出し要素のポインタ + # + # バッファの現在の読み出し要素のポインタまたは、n個先のポインタを返す + # + # @param n 読み出しポインタ + n の位置のポインタ + # @return 読み出し位置のポインタ + # + # @else + # + # @brief Get the buffer length + # + # Pure virtual function to get the buffer length. + # + # @return buffer length + # + # @endif + + def rptr(self, n=0): + pass + + ## + # @if jp + # + # @brief 読み出しポインタを進める + # + # 現在の読み出し位置のポインタを n 個進める。 + # + # @param n 読み出しポインタ + n の位置のポインタ + # @param unlock_enable Trueの場合にバッファフルのブロックを解除する + # @return BUFFER_OK: 正常終了 + # BUFFER_ERROR: 異常終了 + # + # @else + # + # @brief Get the buffer length + # + # Pure virtual function to get the buffer length. + # + # @return buffer length + # + # @endif + def advanceRptr(self, n=1, unlock_enable=True): + pass + + ## + # @if jp + # + # @brief バッファからデータを取得する(サブクラス実装用) + # + # バッファに格納されたデータ取得用関数
+ # ※サブクラスでの実装参照用 + # + # @param self + # + # @return 取得データ + # + # @else + # + # @brief Get data from the buffer + # + # @endif + + def get(self): + pass + + ## + # @if jp + # + # @brief バッファからデータを読み出す(サブクラス実装用) + # + # バッファからデータを読み出す
+ # ※サブクラスでの実装参照用 + # + # @param self + # + # @return ret, data + # ret : データ読み出し結果(true:読み出し成功,false:読み出し失敗) + # value : 読み出しデータ + # + # @else + # + # @brief Read data from the buffer + # + # @endif + + def read(self, sec=-1, nsec=-1): + pass + + ## + # @if jp + # + # @brief バッファから読み出し可能な要素数 + # + # バッファから読み出し可能な要素数を返す。 + # + # @return 読み出し可能な要素数 + # + # @return BUFFER_OK: 正常終了 + # BUFFER_ERROR: 異常終了 + # + # @else + # + # @brief Write data into the buffer + # + # Pure virtual function to write data into the buffer. + # + # @param value Target data to write. + # + # @return Result of having written in data (true:Successful, false:Failed) + # + # @endif + + def readable(self): + pass + + ## + # @if jp + # + # @brief バッファemptyチェック + # + # バッファemptyチェック用純粋仮想関数 + # + # @return emptyチェック結果(true:バッファempty,false:バッファデータあり) + # + # @else + # + # @brief Check on whether the buffer is empty. + # + # Pure virtual function to check on whether the buffer is empty. + # + # @return True if the buffer is empty, else false. + # + # @endif + + def empty(self): + pass + ## # @if jp # @class NullBuffer -# @brief ߡХåե饹 -# -# ХåեĹΥߡХåե饹 -# -# @param DataType Хåե˳Ǽǡ -# +# @brief ダミーバッファ実装クラス +# +# バッファ長が1固定のダミーバッファ実装クラス。 +# +# @param DataType バッファに格納するデータ型 +# # @since 0.4.0 -# +# # @else -# +# # @endif class NullBuffer(BufferBase): - """ - """ - - - - ## - # @if jp - # - # @brief 󥹥ȥ饯 - # - # 󥹥ȥ饯 - # ХåեĹ()ǽ롣 - # - # @param self - # @param size ХåեĹ(ǥե:None̵) - # - # @else - # - # @endif - def __init__(self, size=None): - self._length = 1 - self._data = None - self._is_new = False - self._inited = False - - - ## - # @if jp - # - # @brief ХåեĹ() - # - # ХåեĹ롣(ˣ֤) - # - # @param self - # - # @return ХåեĹ() - # - # @else - # - # @brief Get the buffer length - # - # @return buffer length(always 1) - # - # @endif - def length(self): - return 1 - - - ## - # @if jp - # - # @brief Хåե˥ǡ񤭹 - # - # Ϳ줿ǡХåե˽񤭹ࡣ - # - # @param self - # @param value 񤭹оݥǡ - # - # @return ǡ񤭹߷(true:񤭹false:񤭹߼) - # - # @else - # - # @brief Write data into the buffer - # - # @endif - def write(self, value, sec=-1, nsec=-1): - self.put(value) - return True - - - ## - # @if jp - # - # @brief Хåեǡɤ߽Ф - # - # Хåե˳Ǽ줿ǡɤ߽Ф - # - # @param self - # @param value ɤ߽Фǡ - # - # @return ǡɤ߽Ф(true:ɤ߽Фfalse:ɤ߽Ф) - # - # @else - # - # @brief Read data from the buffer - # - # @endif - def read(self, value): - if not self._inited: - return False - value[0] = self.get() - return True - - - ## - # @if jp - # - # @brief Хåեfullå - # - # Хåեfullå롣(false֤) - # - # @param self - # - # @return fullå(false) - # - # @else - # - # @brief Always false. - # - # @endif - def isFull(self): - return False - - - ## - # @if jp - # - # @brief Хåեemptyå - # - # Хåեemptyå롣(false֤) - # ׳ǧ - # - # @param self - # - # @return emptyå(false) - # - # @else - # - # @brief Always false. - # - # @endif - def isEmpty(self): - return False - - - ## - # @if jp - # - # @brief ǿǡǧ - # - # ߤΥХåե֤˳ǼƤǡǿǡǧ롣 - # - # @param self - # - # @return ǿǡǧ - # ( true:ǿǡǡϤޤɤ߽ФƤʤ - # false:Υǡǡϴɤ߽ФƤ) - # - # @else - # - # @endif - def isNew(self): - return self._is_new - - - ## - # @if jp - # - # @brief Хåե˥ǡǼ - # - # Ϳ줿ǡХåե˳Ǽ롣 - # - # @param self - # @param data оݥǡ - # - # @else - # - # @brief Write data into the buffer - # - # @endif - def put(self, data): - self._data = data - self._is_new = True - self._inited = True - - - ## - # @if jp - # - # @brief Хåեǡ - # - # Хåե˳Ǽ줿ǡ롣 - # - # @param self - # - # @return ǡ - # - # @else - # - # @brief Get data from the buffer - # - # @endif - def get(self): - self._is_new = False - return self._data - - - ## - # @if jp - # - # @brief ˽񤭹ХåեؤλȤ - # - # 񤭹ߥХåեؤλȤ롣 - # ܥХåեǤϥХåեĹϸǣǤ뤿ᡤ - # Ʊ֤ؤλȤ֤ - # - # @param self - # - # @return ν񤭹оݥХåեؤλ() - # - # @else - # - # @brief Get the buffer's reference to be written the next - # - # @endif - def getRef(self): - return self._data + """ + """ + + ## + # @if jp + # + # @brief コンストラクタ + # + # コンストラクタ + # バッファ長を1(固定)で初期化する。 + # + # @param self + # @param size バッファ長(デフォルト値:None,ただし無効) + # + # @else + # + # @endif + def __init__(self, size=None): + self._length = 1 + self._data = None + self._is_new = False + self._inited = False + + ## + # @if jp + # + # @brief バッファ長(1固定)を取得する + # + # バッファ長を取得する。(常に1を返す。) + # + # @param self + # + # @return バッファ長(1固定) + # + # @else + # + # @brief Get the buffer length + # + # @return buffer length(always 1) + # + # @endif + + def length(self): + return 1 + + ## + # @if jp + # + # @brief バッファにデータを書き込む + # + # 引数で与えられたデータをバッファに書き込む。 + # + # @param self + # @param value 書き込み対象データ + # + # @return データ書き込み結果(true:書き込み成功,false:書き込み失敗) + # + # @else + # + # @brief Write data into the buffer + # + # @endif + + def write(self, value, sec=-1, nsec=-1): + self.put(value) + return True + + ## + # @if jp + # + # @brief バッファからデータを読み出す + # + # バッファに格納されたデータを読み出す。 + # + # @param self + # + # @return ret, data + # ret : データ読み出し結果(true:読み出し成功,false:読み出し失敗) + # data 読み出したデータ + # + # @else + # + # @brief Read data from the buffer + # + # @endif + + def read(self): + if not self._inited: + return False, None + _, value = self.get() + return True, value + + ## + # @if jp + # + # @brief バッファfullチェック + # + # バッファfullをチェックする。(常にfalseを返す。) + # + # @param self + # + # @return fullチェック結果(常にfalse) + # + # @else + # + # @brief Always false. + # + # @endif + + def isFull(self): + return False + + ## + # @if jp + # + # @brief バッファemptyチェック + # + # バッファemptyをチェックする。(常にfalseを返す。) + # ※要確認 + # + # @param self + # + # @return emptyチェック結果(常にfalse) + # + # @else + # + # @brief Always false. + # + # @endif + + def isEmpty(self): + return False + + ## + # @if jp + # + # @brief 最新データか確認する + # + # 現在のバッファ位置に格納されているデータが最新データか確認する。 + # + # @param self + # + # @return 最新データ確認結果 + # ( true:最新データ.データはまだ読み出されていない + # false:過去のデータ.データは既に読み出されている) + # + # @else + # + # @endif + + def isNew(self): + return self._is_new + + ## + # @if jp + # + # @brief バッファにデータを格納 + # + # 引数で与えられたデータをバッファに格納する。 + # + # @param self + # @param data 対象データ + # + # @else + # + # @brief Write data into the buffer + # + # @endif + + def put(self, data): + self._data = data + self._is_new = True + self._inited = True + + ## + # @if jp + # + # @brief バッファからデータを取得する + # + # バッファに格納されたデータを取得する。 + # + # @param self + # + # @return ret, value + # ret : BUFFER_OK: 正常終了 + # BUFFER_ERROR: 異常終了 + # value : 読み出しデータ + # + # @else + # + # @brief Get data from the buffer + # + # @endif + + def get(self): + self._is_new = False + return OpenRTM_aist.BufferStatus.BUFFER_OK, self._data + + ## + # @if jp + # + # @brief 次に書き込むバッファへの参照を取得する + # + # 書き込みバッファへの参照を取得する。 + # 本バッファ実装ではバッファ長は固定で1であるため, + # 常に同じ位置への参照を返す。 + # + # @param self + # + # @return 次の書き込み対象バッファへの参照(固定) + # + # @else + # + # @brief Get the buffer's reference to be written the next + # + # @endif + + def getRef(self): + return self._data diff --git a/OpenRTM_aist/BufferStatus.py b/OpenRTM_aist/BufferStatus.py index 18633b84..4482f48a 100644 --- a/OpenRTM_aist/BufferStatus.py +++ b/OpenRTM_aist/BufferStatus.py @@ -1,5 +1,5 @@ #!/usr/bin/env python -# -*- coding: euc-jp -*- +# -*- coding: utf-8 -*- ## # @@ -19,23 +19,25 @@ class BufferStatus: - """ - """ + """ + """ - BUFFER_OK = 0 - BUFFER_ERROR = 1 - BUFFER_FULL = 2 - BUFFER_EMPTY = 3 - NOT_SUPPORTED = 4 - TIMEOUT = 5 - PRECONDITION_NOT_MET = 6 + BUFFER_OK = 0 + BUFFER_ERROR = 1 + BUFFER_FULL = 2 + BUFFER_EMPTY = 3 + NOT_SUPPORTED = 4 + TIMEOUT = 5 + PRECONDITION_NOT_MET = 6 - def toString(self, status): - str = ["BUFFER_OK", - "BUFFER_ERROR", - "BUFFER_FULL", - "BUFFER_EMPTY", - "NOT_SUPPORTED", - "TIMEOUT", - "PRECONDITION_NOT_MET"] - return str[status] + def toString(self, status): + typeString = ["BUFFER_OK", + "BUFFER_ERROR", + "BUFFER_FULL", + "BUFFER_EMPTY", + "NOT_SUPPORTED", + "TIMEOUT", + "PRECONDITION_NOT_MET"] + if status < len(typeString): + return typeString[status] + return "" diff --git a/OpenRTM_aist/ByteDataStreamBase.py b/OpenRTM_aist/ByteDataStreamBase.py new file mode 100644 index 00000000..bc902cac --- /dev/null +++ b/OpenRTM_aist/ByteDataStreamBase.py @@ -0,0 +1,396 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- + +## +# @file ByteDataStreamBase.py +# @brief ByteData Stream Base class +# @date $Date$ +# @author Nobuhiko Miyamoto +# +# Copyright (C) 2019 +# Noriaki Ando +# Robot Innovation Research Center, +# National Institute of +# Advanced Industrial Science and Technology (AIST), Japan +# All rights reserved. +# +# $Id$ +# + +import OpenRTM_aist + + +## +# @if jp +# @class ByteDataStreamBase +# +# @brief シリアライザの基底クラス +# +# @else +# @class ByteDataStreamBase +# +# @brief +# +# @endif +class ByteDataStreamBase: + """ + """ + SERIALIZE_OK = 0 + SERIALIZE_ERROR = 1 + SERIALIZE_NOTFOUND = 2 + SERIALIZE_NOT_SUPPORT_ENDIAN = 3 + + ## + # @if jp + # @brief 設定初期化 + # + # + # @param prop 設定情報 + # + # @else + # + # @brief Initializing configuration + # + # + # @param prop Configuration information + # + # @endif + # virtual ReturnCode init(coil::Properties& prop) = 0; + + def init(self, prop): + pass + + ## + # @if jp + # @brief エンディアンの設定 + # + # + # @param little_endian リトルエンディアン(True)、ビッグエンディアン(False) + # + # @else + # + # @brief + # + # + # @param little_endian + # + # @endif + # virtual void isLittleEndian(bool little_endian) = 0; + + def isLittleEndian(self, little_endian): + pass + + ## + # @if jp + # @brief データの符号化 + # + # + # @param data 符号化前のデータ + # @return SERIALIZE_OK:成功、SERIALIZE_ERROR:失敗、SERIALIZE_NOTFOUND:指定のシリアライザがない + # + # @else + # + # @brief + # + # + # @param data + # @return + # + # @endif + # virtual bool serialize(const DataType& data) = 0; + + def serialize(self, data): + return ByteDataStreamBase.SERIALIZE_NOTFOUND, "" + + ## + # @if jp + # @brief データの復号化 + # + # @param cdr バイト列 + # @param data_type データ型 + # @return ret、value + # ret:SERIALIZE_OK:成功、SERIALIZE_ERROR:失敗、SERIALIZE_NOTFOUND:指定のシリアライザがない + # value:復号化後のデータ + # + # @else + # + # @brief + # + # @param cdr + # @param data_type + # @return + # + # @endif + # virtual bool deserialize(DataType& data) = 0; + + def deserialize(self, cdr, data_type): + return ByteDataStreamBase.SERIALIZE_NOTFOUND, data_type + + +serializerfactories = None +globalserializerfactories = None + +## +# @if jp +# @class SerializerFactory +# +# @brief シリアライザを生成するファクトリ +# +# @else +# @class SerializerFactory +# +# @brief +# +# @endif + + +class SerializerFactory(OpenRTM_aist.Factory, ByteDataStreamBase): + + ## + # @if jp + # @brief コンストラクタ + # + # コンストラクタ + # + # @param self + # + # @else + # @brief Constructor + # + # @param self + # + # @endif + def __init__(self): + OpenRTM_aist.Factory.__init__(self) + pass + + ## + # @if jp + # @brief デストラクタ + # + # + # @param self + # + # @else + # + # @brief self + # + # @endif + def __del__(self): + pass + +## +# @if jp +# @class SerializerFactories +# +# @brief シリアライザ生成ファクトリの一覧を操作するクラス +# +# @else +# @class SerializerFactories +# +# @brief +# +# @endif + + +class SerializerFactories: + ## + # @if jp + # @brief コンストラクタ + # + # コンストラクタ + # + # @param self + # + # @else + # @brief Constructor + # + # @param self + # + # @endif + def __init__(self): + self._factories = {} + + ## + # @if jp + # @brief デストラクタ + # + # + # @param self + # + # @else + # + # @brief self + # + # @endif + def __del__(self): + pass + + ## + # @if jp + # @brief シリアライザの登録(データ型ごと) + # + # @param self + # @param marshalingtype シリアライザの種類(文字列) + # @param serializer シリアライザを定義したクラス + # @param datatype 対象のデータ型のインスタンス、もしくはクラス + # + # + # @param self + # + # @else + # + # @param self + # @param marshalingtype + # @param serializer + # @param datatype + # + # @endif + def addSerializer(self, marshalingtype, serializer, datatype): + mtype = OpenRTM_aist.toTypename(datatype) + if not (mtype in self._factories): + self._factories[mtype] = SerializerFactory() + self._factories[mtype].addFactory(marshalingtype, + serializer) + + ## + # @if jp + # @brief シリアライザの登録(グローバル) + # 基本的にシリアライザはデータ型ごとに追加するが、 + # CORBA CDR形式のシリアライザのように全てのデータ型で共通の + # 処理を行う場合はグローバルにシリアライザを登録できる。 + # 特定のデータ型から特定のROSメッセージ型への変換が必要などという + # 場合はデータ型ごとの登録が必要である。 + # + # + # + # @param self + # @param marshalingtype シリアライザの種類(文字列) + # @param serializer シリアライザを定義したクラス + # + # + # @param self + # + # @else + # + # @param self + # @param marshalingtype + # @param serializer + # + # @endif + def addSerializerGlobal(self, marshalingtype, serializer): + globalserializerfactories.addFactory(marshalingtype, + serializer) + ## + # @if jp + # @brief シリアライザの登録解除(データ型ごと) + # + # @param self + # @param marshalingtype シリアライザの種類(文字列) + # @param datatype 対象のデータ型のインスタンス、もしくはクラス + # + # + # @param self + # + # @else + # + # @param self + # @param marshalingtype + # @param datatype + # + # @endif + + def removeSerializer(self, marshalingtype, datatype): + mtype = OpenRTM_aist.toTypename(datatype) + if mtype in self._factories: + self._factories[mtype].removeFactory(marshalingtype) + + ## + # @if jp + # @brief シリアライザの登録解除(グローバル) + # + # @param self + # @param marshalingtype シリアライザの種類(文字列) + # + # + # @param self + # + # @else + # + # @param self + # @param marshalingtype + # + # @endif + def removeSerializerGlobal(self, marshalingtype): + globalserializerfactories.removeFactory(marshalingtype) + + ## + # @if jp + # @brief シリアライザの生成 + # + # @param self + # @param marshalingtype シリアライザの種類(文字列) + # @param datatype 対象のデータ型のインスタンス、もしくはクラス + # + # + # @param self + # + # @else + # + # @param self + # @param marshalingtype + # @param datatype + # + # @endif + def createSerializer(self, marshalingtype, datatype=None): + if datatype is not None: + mtype = OpenRTM_aist.toTypename(datatype) + if mtype in self._factories: + obj = self._factories[mtype].createObject(marshalingtype) + if obj is not None: + return obj + obj = globalserializerfactories.createObject(marshalingtype) + if obj is not None: + return obj + return None + + ## + # @if jp + # @brief 使用可能なシリアライザ一覧の取得 + # + # @param self + # @param datatype 対象のデータ型のインスタンス、もしくはクラス + # + # + # @param self + # + # @else + # + # @param self + # @param datatype + # + # @endif + def getSerializerList(self, datatype): + if datatype is not None: + available_types = [] + mtype = OpenRTM_aist.toTypename(datatype) + if mtype in self._factories: + factory = self._factories[mtype] + available_types.extend(factory.getIdentifiers()) + + available_types.extend(globalserializerfactories.getIdentifiers()) + + return available_types + + def instance(): + global serializerfactories + global globalserializerfactories + + if serializerfactories is None: + serializerfactories = SerializerFactories() + if globalserializerfactories is None: + globalserializerfactories = SerializerFactory() + + return serializerfactories + + instance = staticmethod(instance) diff --git a/OpenRTM_aist/CORBA_CdrMemoryStream.py b/OpenRTM_aist/CORBA_CdrMemoryStream.py new file mode 100644 index 00000000..d23e18a8 --- /dev/null +++ b/OpenRTM_aist/CORBA_CdrMemoryStream.py @@ -0,0 +1,188 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- + +## +# @file CORBA_CdrMemoryStream.py +# @brief CORBA Cdr Memory Stream class +# @date $Date$ +# @author Nobuhiko Miyamoto +# +# Copyright (C) 2019 +# Noriaki Ando +# Robot Innovation Research Center, +# National Institute of +# Advanced Industrial Science and Technology (AIST), Japan +# All rights reserved. +# +# $Id$ +# + +import sys +import OpenRTM_aist +from omniORB import cdrMarshal +from omniORB import cdrUnmarshal +from omniORB import any + +## +# @if jp +# @class CORBA_CdrMemoryStream +# +# @brief CORBAのCDR形式シリアライザ、デシリアライザを定義 +# +# @else +# @class CORBA_CdrMemoryStream +# +# @brief +# +# @endif + + +class CORBA_CdrMemoryStream(OpenRTM_aist.ByteDataStreamBase): + """ + """ + + ## + # @if jp + # @brief コンストラクタ + # + # コンストラクタ + # + # @param self + # + # @else + # @brief Constructor + # + # @param self + # + # @endif + def __init__(self): + self._endian = None + + ## + # @if jp + # @brief デストラクタ + # + # + # @param self + # + # @else + # + # @brief self + # + # @endif + def __del__(self): + pass + + ## + # @if jp + # @brief 設定初期化 + # + # + # @param prop 設定情報 + # + # @else + # + # @brief Initializing configuration + # + # + # @param prop Configuration information + # + # @endif + # virtual ReturnCode init(coil::Properties& prop) = 0; + def init(self, prop): + pass + + ## + # @if jp + # @brief エンディアンの設定 + # + # + # @param little_endian リトルエンディアン(True)、ビッグエンディアン(False) + # + # @else + # + # @brief + # + # + # @param little_endian + # + # @endif + # virtual void isLittleEndian(bool little_endian) = 0; + def isLittleEndian(self, little_endian): + self._endian = little_endian + + ## + # @if jp + # @brief データの符号化 + # + # + # @param data 符号化前のデータ + # @return ret、value + # ret:SERIALIZE_OK:成功、SERIALIZE_ERROR:失敗、SERIALIZE_NOTFOUND:指定のシリアライザがない + # cdr:バイト列 + # + # @else + # + # @brief + # + # + # @param data + # @return + # + # @endif + # virtual bool serialize(const DataType& data) = 0; + + def serialize(self, data): + if self._endian is not None: + try: + cdr = cdrMarshal( + any.to_any(data).typecode(), data, self._endian) + return OpenRTM_aist.ByteDataStreamBase.SERIALIZE_OK, cdr + except BaseException: + if sys.version_info[0] == 3: + return OpenRTM_aist.ByteDataStreamBase.SERIALIZE_ERROR, b"" + else: + return OpenRTM_aist.ByteDataStreamBase.SERIALIZE_ERROR, "" + else: + if sys.version_info[0] == 3: + return OpenRTM_aist.ByteDataStreamBase.SERIALIZE_NOT_SUPPORT_ENDIAN, b"" + else: + return OpenRTM_aist.ByteDataStreamBase.SERIALIZE_NOT_SUPPORT_ENDIAN, "" + + ## + # @if jp + # @brief データの復号化 + # + # @param cdr バイト列 + # @param data_type データ型 + # @return ret、value + # ret:SERIALIZE_OK:成功、SERIALIZE_ERROR:失敗、SERIALIZE_NOTFOUND:指定のシリアライザがない + # value:復号化後のデータ + # + # @else + # + # @brief + # + # @param cdr + # @param data_type + # @return + # + # @endif + # virtual bool deserialize(DataType& data) = 0; + + def deserialize(self, cdr, data_type): + if self._endian is not None: + try: + data = cdrUnmarshal( + any.to_any(data_type).typecode(), cdr, self._endian) + return OpenRTM_aist.ByteDataStreamBase.SERIALIZE_OK, data + except BaseException: + return OpenRTM_aist.ByteDataStreamBase.SERIALIZE_ERROR, data_type + else: + return OpenRTM_aist.ByteDataStreamBase.SERIALIZE_NOT_SUPPORT_ENDIAN, data_type + + +def CORBA_CdrMemoryStreamInit(): + OpenRTM_aist.SerializerFactories.instance().addSerializerGlobal("cdr", + CORBA_CdrMemoryStream) + diff --git a/OpenRTM_aist/CORBA_IORUtil.py b/OpenRTM_aist/CORBA_IORUtil.py index f2b6b972..ac66c78d 100755 --- a/OpenRTM_aist/CORBA_IORUtil.py +++ b/OpenRTM_aist/CORBA_IORUtil.py @@ -1,12 +1,12 @@ #!/usr/bin/env python -# -*- coding: euc-jp -*- +# -*- coding: utf-8 -*- ## # @file CORBA_IORUtil.py # @brief CORBA IOR utility # @date $Date$ # @author Noriaki Ando -# +# from omniORB import CORBA from omniORB import * @@ -14,294 +14,396 @@ from IORProfile_idl import * from IORProfile_idl import _0__GlobalIDL endian = True + + class IOP: - TAG_INTERNET_IOP = 0; - TAG_MULTIPLE_COMPONENTS = 1; - TAG_SCCP_IOP = 2; - DEFAULT_CORBALOC_PORT = 2809; - - ProfileID = { TAG_INTERNET_IOP: "TAG_INTERNET_IOP", - TAG_MULTIPLE_COMPONENTS: "TAG_MULTIPLE_COMPONENTS", - TAG_SCCP_IOP: "TAG_SCCP_IOP", - DEFAULT_CORBALOC_PORT: "DEFAULT_CORBALOC_PORT" + TAG_INTERNET_IOP = 0 + TAG_MULTIPLE_COMPONENTS = 1 + TAG_SCCP_IOP = 2 + DEFAULT_CORBALOC_PORT = 2809 + + ProfileID = {TAG_INTERNET_IOP: "TAG_INTERNET_IOP", + TAG_MULTIPLE_COMPONENTS: "TAG_MULTIPLE_COMPONENTS", + TAG_SCCP_IOP: "TAG_SCCP_IOP", + DEFAULT_CORBALOC_PORT: "DEFAULT_CORBALOC_PORT" + } + # ComponentId + TAG_ORB_TYPE = 0 + TAG_CODE_SETS = 1 + TAG_POLICIES = 2 + TAG_ALTERNATE_IIOP_ADDRESS = 3 + TAG_COMPLETE_OBJECT_KEY = 5 + TAG_ENDPOINT_ID_POSITION = 6 + TAG_LOCATION_POLICY = 12 + TAG_ASSOCIATION_OPTIONS = 13 + TAG_SEC_NAME = 14 + TAG_SPKM_1_SEC_MECH = 15 + TAG_SPKM_2_SEC_MECH = 16 + TAG_KERBEROSV5_SEC_MECH = 17 + TAG_CSI_ECMA_SECRET_SEC_MECH = 18 + TAG_CSI_ECMA_HYBRID_SEC_MECH = 19 + TAG_SSL_SEC_TRANS = 20 + TAG_CSI_ECMA_PUBLIC_SEC_MECH = 21 + TAG_GENERIC_SEC_MECH = 22 + TAG_FIREWALL_TRANS = 23 + TAG_SCCP_CONTACT_INFO = 24 + TAG_JAVA_CODEBASE = 25 + TAG_CSI_SEC_MECH_LIST = 33 + TAG_NULL_TAG = 34 + TAG_TLS_SEC_TRANS = 36 + TAG_DCE_STRING_BINDING = 100 + TAG_DCE_BINDING_NAME = 101 + TAG_DCE_NO_PIPES = 102 + TAG_DCE_SEC_MECH = 103 + TAG_INET_SEC_TRANS = 123 + TAG_GROUP = 90001 # XXX NEED THE REAL CONSTANT !! + TAG_PRIMARY = 90002 # XXX NEED THE REAL CONSTANT! + TAG_HEARTBEAT_ENABLED = 90003 # XXX NEED THE REAL CONSTANT ! + # omniORB specific IDs + TAG_OMNIORB_BIDIR = 0x41545401 + TAG_OMNIORB_UNIX_TRANS = 0x41545402 + TAG_OMNIORB_PERSISTENT_ID = 0x41545403 + TAG_OMNIORB_RESTRICTED_CONNECTION = 0x41545404 + ComponentID = {TAG_ORB_TYPE: "TAG_ORB_TYPE", + TAG_CODE_SETS: "TAG_CODE_SETS", + TAG_POLICIES: "TAG_POLICIES", + TAG_ALTERNATE_IIOP_ADDRESS: "TAG_ALTERNATE_IIOP_ADDRESS", + TAG_COMPLETE_OBJECT_KEY: "TAG_COMPLETE_OBJECT_KEY", + TAG_ENDPOINT_ID_POSITION: "TAG_ENDPOINT_ID_POSITION", + TAG_LOCATION_POLICY: "TAG_LOCATION_POLICY", + TAG_ASSOCIATION_OPTIONS: "TAG_ASSOCIATION_OPTIONS", + TAG_SEC_NAME: "TAG_SEC_NAME", + TAG_SPKM_1_SEC_MECH: "TAG_SPKM_1_SEC_MECH", + TAG_SPKM_2_SEC_MECH: "TAG_SPKM_2_SEC_MECH", + TAG_KERBEROSV5_SEC_MECH: "TAG_KERBEROSV5_SEC_MECH", + TAG_CSI_ECMA_SECRET_SEC_MECH: "TAG_CSI_ECMA_SECRET_SEC_MECH", + TAG_CSI_ECMA_HYBRID_SEC_MECH: "TAG_CSI_ECMA_HYBRID_SEC_MECH", + TAG_SSL_SEC_TRANS: "TAG_SSL_SEC_TRANS", + TAG_CSI_ECMA_PUBLIC_SEC_MECH: "TAG_CSI_ECMA_PUBLIC_SEC_MECH", + TAG_GENERIC_SEC_MECH: "TAG_GENERIC_SEC_MECH", + TAG_FIREWALL_TRANS: "TAG_FIREWALL_TRANS", + TAG_SCCP_CONTACT_INFO: "TAG_SCCP_CONTACT_INFO", + TAG_JAVA_CODEBASE: "TAG_JAVA_CODEBASE", + TAG_CSI_SEC_MECH_LIST: "TAG_CSI_SEC_MECH_LIST", + TAG_NULL_TAG: "TAG_NULL_TAG", + TAG_TLS_SEC_TRANS: "TAG_TLS_SEC_TRANS", + TAG_DCE_STRING_BINDING: "TAG_DCE_STRING_BINDING", + TAG_DCE_BINDING_NAME: "TAG_DCE_BINDING_NAME", + TAG_DCE_NO_PIPES: "TAG_DCE_NO_PIPES", + TAG_DCE_SEC_MECH: "TAG_DCE_SEC_MECH", + TAG_INET_SEC_TRANS: "TAG_INET_SEC_TRANS", + TAG_GROUP: "TAG_GROUP", + TAG_PRIMARY: "TAG_PRIMARY", + TAG_HEARTBEAT_ENABLED: "TAG_HEARTBEAT_ENABLED", + TAG_OMNIORB_BIDIR: "TAG_OMNIORB_BIDIR", + TAG_OMNIORB_UNIX_TRANS: "TAG_OMNIORB_UNIX_TRANS", + TAG_OMNIORB_PERSISTENT_ID: "TAG_OMNIORB_PERSISTENT_ID", + TAG_OMNIORB_RESTRICTED_CONNECTION: "TAG_OMNIORB_RESTRICTED_CONNECTION", + } + + codesets = {0x00010001: "ISO-8859-1", + 0x00010002: "ISO-8859-2", + 0x00010003: "ISO-8859-3", + 0x00010004: "ISO-8859-4", + 0x00010005: "ISO-8859-5", + 0x00010006: "ISO-8859-6", + 0x00010007: "ISO-8859-7", + 0x00010008: "ISO-8859-8", + 0x00010009: "ISO-8859-9", + 0x0001000a: "ISO-8859-10", + 0x0001000b: "ISO-8859-11", + 0x0001000d: "ISO-8859-13", + 0x0001000e: "ISO-8859-14", + 0x0001000f: "ISO-8859-15", + 0x00010010: "ISO-8859-16", + 0x00010020: "ISO-646", + 0x00010100: "UCS-2-level-1", + 0x00010101: "UCS-2-level-2", + 0x00010102: "UCS-2-level-3", + 0x00010106: "UCS-4", + 0x05010001: "UTF-8", + 0x00010109: "UTF-16", + 0x100204e2: "windows-1250", + 0x100204e3: "windows-1251", + 0x100204e4: "windows-1252", + 0x100204e5: "windows-1253", + 0x100204e6: "windows-1254", + 0x100204e7: "windows-1255", + 0x100204e8: "windows-1256", + 0x100204e9: "windows-1257", + 0x100204ea: "windows-1258", + 0x10020025: "IBM-037", + 0x100201f8: "IBM-500", + 0x10040366: "SNI-EDF-4", + 0x10020567: "GBK" + } + orb_type = {0x41545400: "omniORB", + 0x48500000: "HP", + 0x4e534400: "HP", + 0x49424d00: "IBM", + 0x53554e00: "Sun", + 0x4f424200: "BEA", + 0x42454100: "BEA", + 0x574C5300: "BEA", + 0x494c5500: "Xerox", + 0x58505300: "PrismTech", + 0x50544300: "PrismTech", + 0x49534900: "AdNovum Informatik", + 0x56495300: "Borland", + 0x4f495300: "Object Interface Systems", + 0x46420000: "FloorBoard Software", + 0x4e4e4e00: "Rogue Wave", + 0x4e550000: "Nihon Unisys", + 0x4a424b00: "SilverStream Software", + 0x54414f00: "TAO", + 0x4c434200: "2AB", + 0x41505800: "Univ. of Erlangen-Nuernberg", + 0x4f425400: "ORBit", + 0x47534900: "GemStone Systems", + 0x464a0000: "Fujitsu", + 0x4f425f00: "TIBCO", + 0x4f414b00: "Camros Corporation", + 0x4f4f4300: "IONA (Orbacus)", + 0x49545f00: "IONA (Orbix)", + 0x4e454300: "NEC", + 0x424c5500: "Berry Software", + 0x56495400: "Vitria", + 0x444f4700: "Exoffice Technologies", + 0xcb0e0000: "Chicago Board of Exchange", + 0x4a414300: "JacORB", + 0x58545200: "Xtradyne Technologies", + 0x54475800: "Top Graph'X", + 0x41646100: "AdaOS Project", + 0x4e4f4b00: "Nokia", + 0x45524900: "Ericsson", + 0x52415900: "RayORB", + 0x53414e00: "Sankhya Technologies", + 0x414e4400: "Androsoft", + 0x42424300: "Bionic Buffalo", + 0x522e4300: "Remoting.Corba", + 0x504f0000: "PolyORB", + 0x54494400: "Telefonica", } - # ComponentId - TAG_ORB_TYPE = 0; - TAG_CODE_SETS = 1; - TAG_POLICIES = 2; - TAG_ALTERNATE_IIOP_ADDRESS = 3; - TAG_COMPLETE_OBJECT_KEY = 5; - TAG_ENDPOINT_ID_POSITION = 6; - TAG_LOCATION_POLICY = 12; - TAG_ASSOCIATION_OPTIONS = 13; - TAG_SEC_NAME = 14; - TAG_SPKM_1_SEC_MECH = 15; - TAG_SPKM_2_SEC_MECH = 16; - TAG_KERBEROSV5_SEC_MECH = 17; - TAG_CSI_ECMA_SECRET_SEC_MECH = 18; - TAG_CSI_ECMA_HYBRID_SEC_MECH = 19; - TAG_SSL_SEC_TRANS = 20; - TAG_CSI_ECMA_PUBLIC_SEC_MECH = 21; - TAG_GENERIC_SEC_MECH = 22; - TAG_FIREWALL_TRANS = 23; - TAG_SCCP_CONTACT_INFO = 24; - TAG_JAVA_CODEBASE = 25; - TAG_CSI_SEC_MECH_LIST = 33; - TAG_NULL_TAG = 34; - TAG_TLS_SEC_TRANS = 36; - TAG_DCE_STRING_BINDING = 100; - TAG_DCE_BINDING_NAME = 101; - TAG_DCE_NO_PIPES = 102; - TAG_DCE_SEC_MECH = 103; - TAG_INET_SEC_TRANS = 123; - TAG_GROUP = 90001; # XXX NEED THE REAL CONSTANT !! - TAG_PRIMARY = 90002; # XXX NEED THE REAL CONSTANT! - TAG_HEARTBEAT_ENABLED = 90003; # XXX NEED THE REAL CONSTANT ! - # omniORB specific IDs - TAG_OMNIORB_BIDIR = 0x41545401; - TAG_OMNIORB_UNIX_TRANS = 0x41545402; - TAG_OMNIORB_PERSISTENT_ID = 0x41545403; - TAG_OMNIORB_RESTRICTED_CONNECTION = 0x41545404; - ComponentID = { TAG_ORB_TYPE: "TAG_ORB_TYPE", - TAG_CODE_SETS: "TAG_CODE_SETS", - TAG_POLICIES: "TAG_POLICIES", - TAG_ALTERNATE_IIOP_ADDRESS: "TAG_ALTERNATE_IIOP_ADDRESS", - TAG_COMPLETE_OBJECT_KEY: "TAG_COMPLETE_OBJECT_KEY", - TAG_ENDPOINT_ID_POSITION: "TAG_ENDPOINT_ID_POSITION", - TAG_LOCATION_POLICY: "TAG_LOCATION_POLICY", - TAG_ASSOCIATION_OPTIONS: "TAG_ASSOCIATION_OPTIONS", - TAG_SEC_NAME: "TAG_SEC_NAME", - TAG_SPKM_1_SEC_MECH: "TAG_SPKM_1_SEC_MECH", - TAG_SPKM_2_SEC_MECH: "TAG_SPKM_2_SEC_MECH", - TAG_KERBEROSV5_SEC_MECH: "TAG_KERBEROSV5_SEC_MECH", - TAG_CSI_ECMA_SECRET_SEC_MECH: "TAG_CSI_ECMA_SECRET_SEC_MECH", - TAG_CSI_ECMA_HYBRID_SEC_MECH: "TAG_CSI_ECMA_HYBRID_SEC_MECH", - TAG_SSL_SEC_TRANS: "TAG_SSL_SEC_TRANS", - TAG_CSI_ECMA_PUBLIC_SEC_MECH: "TAG_CSI_ECMA_PUBLIC_SEC_MECH", - TAG_GENERIC_SEC_MECH: "TAG_GENERIC_SEC_MECH", - TAG_FIREWALL_TRANS: "TAG_FIREWALL_TRANS", - TAG_SCCP_CONTACT_INFO: "TAG_SCCP_CONTACT_INFO", - TAG_JAVA_CODEBASE: "TAG_JAVA_CODEBASE", - TAG_CSI_SEC_MECH_LIST: "TAG_CSI_SEC_MECH_LIST", - TAG_NULL_TAG: "TAG_NULL_TAG", - TAG_TLS_SEC_TRANS: "TAG_TLS_SEC_TRANS", - TAG_DCE_STRING_BINDING: "TAG_DCE_STRING_BINDING", - TAG_DCE_BINDING_NAME: "TAG_DCE_BINDING_NAME", - TAG_DCE_NO_PIPES: "TAG_DCE_NO_PIPES", - TAG_DCE_SEC_MECH: "TAG_DCE_SEC_MECH", - TAG_INET_SEC_TRANS: "TAG_INET_SEC_TRANS", - TAG_GROUP: "TAG_GROUP", - TAG_PRIMARY: "TAG_PRIMARY", - TAG_HEARTBEAT_ENABLED: "TAG_HEARTBEAT_ENABLED", - TAG_OMNIORB_BIDIR: "TAG_OMNIORB_BIDIR", - TAG_OMNIORB_UNIX_TRANS: "TAG_OMNIORB_UNIX_TRANS", - TAG_OMNIORB_PERSISTENT_ID: "TAG_OMNIORB_PERSISTENT_ID", - TAG_OMNIORB_RESTRICTED_CONNECTION: "TAG_OMNIORB_RESTRICTED_CONNECTION", - } - - codesets = { 0x00010001: "ISO-8859-1", - 0x00010002: "ISO-8859-2", - 0x00010003: "ISO-8859-3", - 0x00010004: "ISO-8859-4", - 0x00010005: "ISO-8859-5", - 0x00010006: "ISO-8859-6", - 0x00010007: "ISO-8859-7", - 0x00010008: "ISO-8859-8", - 0x00010009: "ISO-8859-9", - 0x0001000a: "ISO-8859-10", - 0x0001000b: "ISO-8859-11", - 0x0001000d: "ISO-8859-13", - 0x0001000e: "ISO-8859-14", - 0x0001000f: "ISO-8859-15", - 0x00010010: "ISO-8859-16", - 0x00010020: "ISO-646", - 0x00010100: "UCS-2-level-1", - 0x00010101: "UCS-2-level-2", - 0x00010102: "UCS-2-level-3", - 0x00010106: "UCS-4", - 0x05010001: "UTF-8", - 0x00010109: "UTF-16", - 0x100204e2: "windows-1250", - 0x100204e3: "windows-1251", - 0x100204e4: "windows-1252", - 0x100204e5: "windows-1253", - 0x100204e6: "windows-1254", - 0x100204e7: "windows-1255", - 0x100204e8: "windows-1256", - 0x100204e9: "windows-1257", - 0x100204ea: "windows-1258", - 0x10020025: "IBM-037", - 0x100201f8: "IBM-500", - 0x10040366: "SNI-EDF-4", - 0x10020567: "GBK" - } - orb_type = { 0x41545400: "omniORB", - 0x48500000: "HP", - 0x4e534400: "HP", - 0x49424d00: "IBM", - 0x53554e00: "Sun", - 0x4f424200: "BEA", - 0x42454100: "BEA", - 0x574C5300: "BEA", - 0x494c5500: "Xerox", - 0x58505300: "PrismTech", - 0x50544300: "PrismTech", - 0x49534900: "AdNovum Informatik", - 0x56495300: "Borland", - 0x4f495300: "Object Interface Systems", - 0x46420000: "FloorBoard Software", - 0x4e4e4e00: "Rogue Wave", - 0x4e550000: "Nihon Unisys", - 0x4a424b00: "SilverStream Software", - 0x54414f00: "TAO", - 0x4c434200: "2AB", - 0x41505800: "Univ. of Erlangen-Nuernberg", - 0x4f425400: "ORBit", - 0x47534900: "GemStone Systems", - 0x464a0000: "Fujitsu", - 0x4f425f00: "TIBCO", - 0x4f414b00: "Camros Corporation", - 0x4f4f4300: "IONA (Orbacus)", - 0x49545f00: "IONA (Orbix)", - 0x4e454300: "NEC", - 0x424c5500: "Berry Software", - 0x56495400: "Vitria", - 0x444f4700: "Exoffice Technologies", - 0xcb0e0000: "Chicago Board of Exchange", - 0x4a414300: "JacORB", - 0x58545200: "Xtradyne Technologies", - 0x54475800: "Top Graph'X", - 0x41646100: "AdaOS Project", - 0x4e4f4b00: "Nokia", - 0x45524900: "Ericsson", - 0x52415900: "RayORB", - 0x53414e00: "Sankhya Technologies", - 0x414e4400: "Androsoft", - 0x42424300: "Bionic Buffalo", - 0x522e4300: "Remoting.Corba", - 0x504f0000: "PolyORB", - 0x54494400: "Telefonica", - } ## # @if jp # -# @brief ݡͥȤΥץѥƥ +# @brief コンポーネントのプロパティ取得 # -# -# @param rtc RTݡͥ -# @return ݡͥȤΥץѥƥ +# +# @param rtc RTコンポーネント +# @return コンポーネントのプロパティ # # @else # -# @brief +# @brief # @param rtc -# @return +# @return # # @endif # coil::Properties get_component_profile(const RTC::RTObject_ptr rtc) + + class cdrStream: - def __init__(self, cdrdata): - self.pos = 0 - self.cdrdata = cdrdata - return - def data(self, length): - return self.iordata[self.pos:self.pos+length] - def pos(self): - return self.pos - def rewind(self): - self.pos = 0 - def incr(self, count = 1): - self.pos += count + def __init__(self, cdrdata): + self.pos = 0 + self.cdrdata = cdrdata + return + + def data(self, length): + return self.iordata[self.pos:self.pos + length] + + def pos(self): + return self.pos + + def rewind(self): + self.pos = 0 + + def incr(self, count=1): + self.pos += count + def unmarshalBoolean(cdr): - cdrUnmarshal(CORBA.TC_boolean, "".join(cdr.data(2))) - -TAGS=("IOP::TAG_INTERNET_IOP", - "IOP::TAG_MULTIPLE_COMPONENTS", - "IOP::TAG_SCCP_IOP") + cdrUnmarshal(CORBA.TC_boolean, "".join(cdr.data(2))) + + +TAGS = ("IOP::TAG_INTERNET_IOP", + "IOP::TAG_MULTIPLE_COMPONENTS", + "IOP::TAG_SCCP_IOP") + + +def toString(ior): + global endian + + data = cdrMarshal(any.to_any(ior).typecode(), ior, endian) + result = [0] * (12 + len(data) * 2) + result[0] = "I" + result[1] = "O" + result[2] = "R" + result[3] = ":" + + result[4] = "0" + if endian: + result[5] = "1" + else: + result[5] = "0" + result[6] = "0" + result[7] = "0" + result[8] = "0" + result[9] = "0" + result[10] = "0" + result[11] = "0" + + for i,datai in enumerate(data): + d = ord(datai) + j = 12 + i * 2 + v = (d & 0xf0) + v = v >> 4 + if v < 10: + result[j] = chr(ord('0') + v) + else: + result[j] = chr(ord('a') + (v - 10)) + v = ((d & 0xf)) + if v < 10: + result[j + 1] = chr(ord('0') + v) + else: + result[j + 1] = chr(ord('a') + (v - 10)) + + iorstr = "".join(result) + return iorstr def toIOR(iorstr): - global endian - if len(iorstr) < 4: return - if iorstr[0:4] != 'IOR:': return - - pos = len("IOR:") - if sys.version_info[0] == 2: - iorvalue = [chr(int(i + j, 16)) - for (i, j) in zip(iorstr[pos::2], iorstr[(pos + 1)::2])] - else: - iorvalue = [int(i + j, 16) - for (i, j) in zip(iorstr[pos::2], iorstr[(pos + 1)::2])] - # Endian flag - pos = 0 - endian = (iorvalue[pos] != 0) - pos += 4 - if sys.version_info[0] == 2: - ior = cdrUnmarshal(_0__GlobalIDL._tc_IOR, - "".join(iorvalue[pos:]), endian) - else: - ior = cdrUnmarshal(_0__GlobalIDL._tc_IOR, - bytes(iorvalue[pos:]), endian) - return ior + global endian + if len(iorstr) < 4: + return + if iorstr[0:4] != 'IOR:': + return -def getEndpoints(ior): - global endian - addr = [] - for p in ior.profiles: - # TAG_INTERNET_IOP - if p.tag == IOP.TAG_INTERNET_IOP: - if sys.version_info[0] == 2: - pbody = cdrUnmarshal(_0__GlobalIDL._tc_ProfileBody, - "".join(p.profile_data), endian) - else: - pbody = cdrUnmarshal(_0__GlobalIDL._tc_ProfileBody, - p.profile_data, endian) - addr.append(pbody.address_) - addr += extractAddrs(pbody.components) - - # TAG_MULTIPLE_COMPONENTS - elif p.tag == IOP.TAG_MULTIPLE_COMPONENTS: - if sys.version_info[0] == 2: - profiles = cdrUnmarshal(_0__GlobalIDL._tc_MultipleComponentProfile, - "".join(p.profile_data), endian) - else: - profiles = cdrUnmarshal(_0__GlobalIDL._tc_MultipleComponentProfile, - p.profile_data, endian) - addr += extractAddrs(profiles) + pos = len("IOR:") + if sys.version_info[0] == 2: + iorvalue = [chr(int(i + j, 16)) + for (i, j) in zip(iorstr[pos::2], iorstr[(pos + 1)::2])] else: - print("Other Profile") - return addr + iorvalue = [int(i + j, 16) + for (i, j) in zip(iorstr[pos::2], iorstr[(pos + 1)::2])] + # Endian flag + pos = 0 + endian = (iorvalue[pos] != 0) + pos += 4 + if sys.version_info[0] == 2: + ior = cdrUnmarshal(_0__GlobalIDL._tc_IOR, + "".join(iorvalue[pos:]), endian) + else: + ior = cdrUnmarshal(_0__GlobalIDL._tc_IOR, + bytes(iorvalue[pos:]), endian) + return ior + + +def getEndpoints(ior): + global endian + addr = [] + for p in ior.profiles: + # TAG_INTERNET_IOP + if p.tag == IOP.TAG_INTERNET_IOP: + if sys.version_info[0] == 2: + pbody = cdrUnmarshal(_0__GlobalIDL._tc_ProfileBody, + "".join(p.profile_data), endian) + else: + pbody = cdrUnmarshal(_0__GlobalIDL._tc_ProfileBody, + p.profile_data, endian) + addr.append(pbody.address_) + addr += extractAddrs(pbody.components) + + # TAG_MULTIPLE_COMPONENTS + elif p.tag == IOP.TAG_MULTIPLE_COMPONENTS: + if sys.version_info[0] == 2: + profiles = cdrUnmarshal(_0__GlobalIDL._tc_MultipleComponentProfile, + "".join(p.profile_data), endian) + else: + profiles = cdrUnmarshal(_0__GlobalIDL._tc_MultipleComponentProfile, + p.profile_data, endian) + addr += extractAddrs(profiles) + else: + print("Other Profile") + return addr + def extractAddrs(comps): - global endian - addr = [] - for c in comps: - # print("TAG component type: ", IOP.ComponentID[c.tag]) - if c.tag == IOP.TAG_ALTERNATE_IIOP_ADDRESS: - if sys.version_info[0] == 2: - size = cdrUnmarshal(CORBA.TC_ulong, - "".join(c.component_data[0:4]), endian) - address = cdrUnmarshal(_0__GlobalIDL._tc_Address, - "".join(c.component_data[4:]), endian) - else: - size = cdrUnmarshal(CORBA.TC_ulong, - c.component_data[0:4], endian) - address = cdrUnmarshal(_0__GlobalIDL._tc_Address, - c.component_data[4:], endian) - addr.append(address) - elif c.tag == IOP.TAG_ORB_TYPE: - if sys.version_info[0] == 2: - size = cdrUnmarshal(CORBA.TC_ulong, - "".join(c.component_data[0:4]), endian) - orb_type = cdrUnmarshal(CORBA.TC_ulong, - "".join(c.component_data[4:8]), endian) - else: - size = cdrUnmarshal(CORBA.TC_ulong, - c.component_data[0:4], endian) - orb_type = cdrUnmarshal(CORBA.TC_ulong, - c.component_data[4:8], endian) - return addr + global endian + addr = [] + for c in comps: + # print("TAG component type: ", IOP.ComponentID[c.tag]) + if c.tag == IOP.TAG_ALTERNATE_IIOP_ADDRESS: + if sys.version_info[0] == 2: + size = cdrUnmarshal(CORBA.TC_ulong, + "".join(c.component_data[0:4]), endian) + address = cdrUnmarshal(_0__GlobalIDL._tc_Address, + "".join(c.component_data[4:]), endian) + else: + size = cdrUnmarshal(CORBA.TC_ulong, + c.component_data[0:4], endian) + address = cdrUnmarshal(_0__GlobalIDL._tc_Address, + c.component_data[4:], endian) + addr.append(address) + elif c.tag == IOP.TAG_ORB_TYPE: + if sys.version_info[0] == 2: + size = cdrUnmarshal(CORBA.TC_ulong, + "".join(c.component_data[0:4]), endian) + orb_type = cdrUnmarshal(CORBA.TC_ulong, + "".join(c.component_data[4:8]), endian) + else: + size = cdrUnmarshal(CORBA.TC_ulong, + c.component_data[0:4], endian) + orb_type = cdrUnmarshal(CORBA.TC_ulong, + c.component_data[4:8], endian) + return addr + +## +# @if jp +# +# @brief IROのエンドポイント置き換え +# +# +# @param iorstr IOR文字列 +# @param endpoint エンドポイント +# @return 置き換え後の文字列 +# +# @else +# +# @brief +# +# @param iorstr +# @param endpoint +# @return +# +# @endif + + +def replaceEndpoint(iorstr, endpoint): + global endian + ior = toIOR(iorstr) + for p in ior.profiles: + # TAG_INTERNET_IOP + if p.tag == IOP.TAG_INTERNET_IOP: + if sys.version_info[0] == 2: + pbody = cdrUnmarshal(_0__GlobalIDL._tc_ProfileBody, + "".join(p.profile_data), endian) + else: + pbody = cdrUnmarshal(_0__GlobalIDL._tc_ProfileBody, + p.profile_data, endian) + + pbody.address_.host = endpoint + p.profile_data = cdrMarshal( + any.to_any(pbody).typecode(), pbody, endian) + + # TAG_MULTIPLE_COMPONENTS + elif p.tag == IOP.TAG_MULTIPLE_COMPONENTS: + pass + else: + print("Other Profile") + iorstr = toString(ior) + return iorstr + iorstr = "IOR:000000000000003549444c3a6f70656e72746d2e616973742e676f2e6a702f4f70656e52544d2f44617461466c6f77436f6d706f6e656e743a312e3000000000000000010000000000000064000102000000000d31302e3231312e35352e31350000ffa90000000efed593815800002090000000000100000000000200000000000000080000000041545400000000010000001c00000000000100010000000105010001000101090000000100010109" diff --git a/OpenRTM_aist/CORBA_RTCUtil.py b/OpenRTM_aist/CORBA_RTCUtil.py index dbb2e52b..a1062b63 100644 --- a/OpenRTM_aist/CORBA_RTCUtil.py +++ b/OpenRTM_aist/CORBA_RTCUtil.py @@ -1,12 +1,12 @@ #!/usr/bin/env python -# -*- coding: euc-jp -*- +# -*- coding: utf-8 -*- ## # @file CORBA_RTCUtil.py # @brief CORBA RTC utility # @date $Date: 2016/01/08 $ # @author Nobuhiko Miyamoto -# +# import OpenRTM_aist import OpenRTM_aist.RTObject @@ -17,717 +17,729 @@ ## # @if jp # -# @brief ݡͥȤΥץѥƥ +# @brief コンポーネントのプロパティ取得 +# # -# -# @param rtc RTݡͥ -# @return ݡͥȤΥץѥƥ +# @param rtc RTコンポーネント +# @return コンポーネントのプロパティ # # @else # -# @brief +# @brief # @param rtc -# @return +# @return # # @endif # coil::Properties get_component_profile(const RTC::RTObject_ptr rtc) def get_component_profile(rtc): - prop = OpenRTM_aist.Properties() - if CORBA.is_nil(rtc): + prop = OpenRTM_aist.Properties() + if CORBA.is_nil(rtc): + return prop + prof = rtc.get_component_profile() + OpenRTM_aist.NVUtil.copyToProperties(prop, prof.properties) return prop - prof = rtc.get_component_profile() - OpenRTM_aist.NVUtil.copyToProperties(prop, prof.properties) - return prop - - ## # @if jp # -# @brief ݡͥȤΥ֥ȥե󥹤¸ߤƤ뤫Ƚ +# @brief コンポーネントのオブジェクトリファレンスが存在しているかを判定 +# # -# -# @param rtc RTݡͥ -# @return True:¸False:λѤ +# @param rtc RTコンポーネント +# @return True:生存、False:終了済み # # @else # -# @brief -# @param rtc RTݡͥ -# @return +# @brief +# @param rtc RTコンポーネント +# @return # # @endif def is_existing(rtc): - try: - if rtc._non_existent(): - return False - return True - except CORBA.SystemException: - return False + try: + if rtc._non_existent(): + return False + return True + except CORBA.SystemException: + return False ## # @if jp # -# @brief RTCǥեȤμ¹ԥƥȤalive֤Ƚꤹ +# @brief RTCがデフォルトの実行コンテキストでalive状態かを判定する +# +# @param rtc RTコンポーネント +# @return True:alive状態 # -# @param rtc RTݡͥ -# @return True:alive -# -# @param +# @param # # @else # -# @brief -# @param +# @brief +# @param # # @endif def is_alive_in_default_ec(rtc): - ec = get_actual_ec(rtc) - if CORBA.is_nil(ec): - return False - return rtc.is_alive(ec) + ec = get_actual_ec(rtc) + if CORBA.is_nil(ec): + return False + return rtc.is_alive(ec) ## # @if jp # -# @brief RTݡͥȤ˴Ϣդ¹ԥƥȤꤷIDμ¹ԥƥȤ +# @brief RTコンポーネントに関連付けした実行コンテキストから指定したIDの実行コンテキストを取得 +# # -# -# @param rtc оݤRTݡͥ -# @param ec_id ¹ԥƥȤID -# @return ¹ԥƥȤΥ֥ȥե +# @param rtc 対象のRTコンポーネント +# @param ec_id 実行コンテキストのID +# @return 実行コンテキストのオブジェクトリファレンス # # @else # -# @brief +# @brief # @param rtc # @param ec_id # @return # # @endif -# RTC::ExecutionContext_var get_actual_ec(const RTC::RTObject_ptr rtc,RTC::UniqueId ec_id = 0) +# RTC::ExecutionContext_var get_actual_ec(const RTC::RTObject_ptr +# rtc,RTC::UniqueId ec_id = 0) def get_actual_ec(rtc, ec_id=0): - if ec_id < 0: - return RTC.ExecutionContext._nil - if CORBA.is_nil(rtc): - return RTC.ExecutionContext._nil - if ec_id < OpenRTM_aist.RTObject.ECOTHER_OFFSET: - eclist = rtc.get_owned_contexts() - if ec_id >= len(eclist): - return RTC.ExecutionContext._nil - - if CORBA.is_nil(eclist[ec_id]): - return RTC.ExecutionContext._nil - return eclist[ec_id] - elif ec_id >= OpenRTM_aist.RTObject.ECOTHER_OFFSET: - pec_id = ec_id - OpenRTM_aist.RTObject.ECOTHER_OFFSET - eclist = rtc.get_participating_contexts() - if pec_id >= len(eclist): - return RTC.ExecutionContext._nil - if CORBA.is_nil(eclist[pec_id]): - return RTC.ExecutionContext._nil - return eclist[pec_id] - - + if ec_id < 0: + return RTC.ExecutionContext._nil + if CORBA.is_nil(rtc): + return RTC.ExecutionContext._nil + if ec_id < OpenRTM_aist.RTObject.ECOTHER_OFFSET: + eclist = rtc.get_owned_contexts() + if ec_id >= len(eclist): + return RTC.ExecutionContext._nil + + if CORBA.is_nil(eclist[ec_id]): + return RTC.ExecutionContext._nil + return eclist[ec_id] + elif ec_id >= OpenRTM_aist.RTObject.ECOTHER_OFFSET: + pec_id = ec_id - OpenRTM_aist.RTObject.ECOTHER_OFFSET + eclist = rtc.get_participating_contexts() + if pec_id >= len(eclist): + return RTC.ExecutionContext._nil + if CORBA.is_nil(eclist[pec_id]): + return RTC.ExecutionContext._nil + return eclist[pec_id] ## # @if jp # -# @brief оݤRTݡͥȤꤷ¹ԥƥȤID +# @brief 対象のRTコンポーネントから指定した実行コンテキストのIDを取得する +# # -# -# @param rtc оݤRTݡͥ -# @param ec ¹ԥƥ -# @return ¹ԥƥȤID -# ꤷ¹ԥƥȤRTݡͥȤ˴ϢդƤʤä-1֤ +# @param rtc 対象のRTコンポーネント +# @param ec 実行コンテキスト +# @return 実行コンテキストのID +# 指定した実行コンテキストがRTコンポーネントに関連付けられていなかった場合は-1を返す # # @else # -# @brief -# @param +# @brief +# @param # # @endif def get_ec_id(rtc, ec): - if CORBA.is_nil(rtc): - return -1 - if CORBA.is_nil(ec): + if CORBA.is_nil(rtc): + return -1 + if CORBA.is_nil(ec): + return -1 + + eclist_own = rtc.get_owned_contexts() + + count = 0 + for e in eclist_own: + if not CORBA.is_nil(e): + if e._is_equivalent(ec): + return count + count += 1 + eclist_pec = rtc.get_participating_contexts() + count = 0 + for e in eclist_pec: + if not CORBA.is_nil(e): + if e._is_equivalent(ec): + return count + OpenRTM_aist.RTObject.ECOTHER_OFFSET + count += 1 return -1 - - eclist_own = rtc.get_owned_contexts() - - count = 0 - for e in eclist_own: - if not CORBA.is_nil(e): - if e._is_equivalent(ec): - return count - count += 1 - eclist_pec = rtc.get_participating_contexts() - count = 0 - for e in eclist_pec: - if not CORBA.is_nil(e): - if e._is_equivalent(ec): - return count+OpenRTM_aist.RTObject.ECOTHER_OFFSET - count += 1 - return -1 - ## # @if jp # -# @brief RTCꤷ¹ԥƥȤǥƥ١󤹤 +# @brief RTCを指定した実行コンテキストでアクティベーションする +# # -# -# @param rtc оݤRTݡͥ -# @param ec_id ¹ԥƥȤID -# @return RTCECΥ֥ȥե󥹤nilξBAD_PARAMETER֤ -# nilǤϤʤactivate_componentؿ֤ͤRTC_OKξϥƥ١ +# @param rtc 対象のRTコンポーネント +# @param ec_id 実行コンテキストのID +# @return RTC、ECのオブジェクトリファレンスがnilの場合はBAD_PARAMETERを返す +# nilではない場合はactivate_component関数の戻り値を返す。RTC_OKの場合はアクティベーションが成功 # # @else # -# @brief +# @brief # @param rtc # @param ec_id -# @return +# @return # # @endif # RTC::ReturnCode_t activate(RTC::RTObject_ptr rtc, RTC::UniqueId ec_id = 0) def activate(rtc, ec_id=0): - if CORBA.is_nil(rtc): - return RTC.BAD_PARAMETER - ec = get_actual_ec(rtc, ec_id) - if CORBA.is_nil(ec): - return RTC.BAD_PARAMETER - return ec.activate_component(rtc) - + if CORBA.is_nil(rtc): + return RTC.BAD_PARAMETER + ec = get_actual_ec(rtc, ec_id) + if CORBA.is_nil(ec): + return RTC.BAD_PARAMETER + return ec.activate_component(rtc) + ## # @if jp # -# @brief RTCꤷ¹ԥƥȤ󥢥ƥ١󤹤 +# @brief RTCを指定した実行コンテキストで非アクティベーションする +# # -# -# @param rtc оݤRTݡͥ -# @param ec_id ¹ԥƥȤID -# @return RTCECΥ֥ȥե󥹤nilξBAD_PARAMETER֤ -# nilǤϤʤdeactivate_componentؿ֤ͤRTC_OKξ󥢥ƥ١ +# @param rtc 対象のRTコンポーネント +# @param ec_id 実行コンテキストのID +# @return RTC、ECのオブジェクトリファレンスがnilの場合はBAD_PARAMETERを返す +# nilではない場合はdeactivate_component関数の戻り値を返す。RTC_OKの場合は非アクティベーションが成功 # # @else # -# @brief +# @brief # @param rtc # @param ec_id -# @return +# @return # # @endif # RTC::ReturnCode_t deactivate(RTC::RTObject_ptr rtc, RTC::UniqueId ec_id = 0) def deactivate(rtc, ec_id=0): - if CORBA.is_nil(rtc): - return RTC.BAD_PARAMETER - ec = get_actual_ec(rtc, ec_id) - if CORBA.is_nil(ec): - return RTC.BAD_PARAMETER - return ec.deactivate_component(rtc) + if CORBA.is_nil(rtc): + return RTC.BAD_PARAMETER + ec = get_actual_ec(rtc, ec_id) + if CORBA.is_nil(ec): + return RTC.BAD_PARAMETER + return ec.deactivate_component(rtc) ## # @if jp # -# @brief RTCꤷ¹ԥƥȤǥꥻåȤ +# @brief RTCを指定した実行コンテキストでリセットする +# # -# -# @param rtc оݤRTݡͥ -# @param ec_id ¹ԥƥȤID -# @return RTCECΥ֥ȥե󥹤nilξBAD_PARAMETER֤ -# nilǤϤʤreset_componentؿ֤ͤRTC_OKξϥꥻåȤ +# @param rtc 対象のRTコンポーネント +# @param ec_id 実行コンテキストのID +# @return RTC、ECのオブジェクトリファレンスがnilの場合はBAD_PARAMETERを返す +# nilではない場合はreset_component関数の戻り値を返す。RTC_OKの場合はリセットが成功 # # @else # -# @brief +# @brief # @param rtc # @param ec_id -# @return +# @return # # @endif # RTC::ReturnCode_t reset(RTC::RTObject_ptr rtc, RTC::UniqueId ec_id = 0) + + def reset(rtc, ec_id=0): - if CORBA.is_nil(rtc): - return RTC.BAD_PARAMETER - ec = get_actual_ec(rtc, ec_id) - if CORBA.is_nil(ec): - return RTC.BAD_PARAMETER - return ec.reset_component(rtc) + if CORBA.is_nil(rtc): + return RTC.BAD_PARAMETER + ec = get_actual_ec(rtc, ec_id) + if CORBA.is_nil(ec): + return RTC.BAD_PARAMETER + return ec.reset_component(rtc) ## # @if jp # -# @brief оݤRTݡͥȤλꤷ¹ԥƥȤǤξ֤ +# @brief 対象のRTコンポーネントの指定した実行コンテキストでの状態を取得 +# # +# @param rtc 対象のRTコンポーネント +# @param ec_id 実行コンテキストのID +# @return 1番目の戻り値としてrtc、ecがnilの場合はFalseを返し、それ以外の場合はTrueを返す。 +# 2番目の戻り値として状態を返す。 # -# @param rtc оݤRTݡͥ -# @param ec_id ¹ԥƥȤID -# @return 1ܤͤȤrtcecnilξFalse֤ʳξTrue֤ -# 2ܤͤȤƾ֤֤ -# # # @else # # @brief # @param rtc # @param ec_id -# @return +# @return # # @endif + + def get_state(rtc, ec_id=0): - if CORBA.is_nil(rtc): - return False, RTC.CREATED_STATE - ec = get_actual_ec(rtc, ec_id) - if CORBA.is_nil(ec): - return False, RTC.CREATED_STATE - state = ec.get_component_state(rtc) - return True, state + if CORBA.is_nil(rtc): + return False, RTC.CREATED_STATE + ec = get_actual_ec(rtc, ec_id) + if CORBA.is_nil(ec): + return False, RTC.CREATED_STATE + state = ec.get_component_state(rtc) + return True, state ## # @if jp # -# @brief оݤRTݡͥȤλꤷ¹ԥƥȤINACTIVE֤ɤȽ +# @brief 対象のRTコンポーネントの指定した実行コンテキストでINACTIVE状態かどうか判定 # -# -# @param rtc оݤRTݡͥ -# @param ec_id ¹ԥƥȤID -# @return INACTIVE֤λTrueʳFalse -# rtcecnilξFalse֤ +# +# @param rtc 対象のRTコンポーネント +# @param ec_id 実行コンテキストのID +# @return INACTIVE状態の時はTrue、それ以外はFalse +# rtc、ecがnilの場合もFalseを返す # # @else # -# @brief -# @param rtc +# @brief +# @param rtc # @param ec_id -# @return +# @return # # @endif + + def is_in_inactive(rtc, ec_id=0): - ret, state = get_state(rtc, ec_id) - if ret: - if state == RTC.INACTIVE_STATE: - return True - return False + ret, state = get_state(rtc, ec_id) + if ret: + if state == RTC.INACTIVE_STATE: + return True + return False ## # @if jp # -# @brief оݤRTݡͥȤλꤷ¹ԥƥȤACTIVE֤ɤȽ +# @brief 対象のRTコンポーネントの指定した実行コンテキストでACTIVE状態かどうか判定 # -# -# @param rtc оݤRTݡͥ -# @param ec_id ¹ԥƥȤID -# @return ACTIVE֤λTrueʳFalse -# rtcecnilξFalse֤ +# +# @param rtc 対象のRTコンポーネント +# @param ec_id 実行コンテキストのID +# @return ACTIVE状態の時はTrue、それ以外はFalse +# rtc、ecがnilの場合もFalseを返す # # @else # -# @brief -# @param rtc +# @brief +# @param rtc # @param ec_id -# @return +# @return # # @endif + + def is_in_active(rtc, ec_id=0): - ret, state = get_state(rtc, ec_id) - if ret: - if state == RTC.ACTIVE_STATE: - return True - return False + ret, state = get_state(rtc, ec_id) + if ret: + if state == RTC.ACTIVE_STATE: + return True + return False ## # @if jp # -# @brief оݤRTݡͥȤλꤷ¹ԥƥȤERROR֤ɤȽ +# @brief 対象のRTコンポーネントの指定した実行コンテキストでERROR状態かどうか判定 # -# -# @param rtc оݤRTݡͥ -# @param ec_id ¹ԥƥȤID -# @return ERROR֤λTrueʳFalse -# rtcecnilξFalse֤ +# +# @param rtc 対象のRTコンポーネント +# @param ec_id 実行コンテキストのID +# @return ERROR状態の時はTrue、それ以外はFalse +# rtc、ecがnilの場合もFalseを返す # # @else # -# @brief -# @param rtc +# @brief +# @param rtc # @param ec_id -# @return +# @return # # @endif -def is_in_error(rtc, ec_id=0): - ret, state = get_state(rtc, ec_id) - if ret: - if state == RTC.ERROR_STATE: - return True - return False +def is_in_error(rtc, ec_id=0): + ret, state = get_state(rtc, ec_id) + if ret: + if state == RTC.ERROR_STATE: + return True + return False + ## # @if jp # -# @brief RTCΥǥեȤμ¹ԥƥȤμ¹Լ +# @brief RTCのデフォルトの実行コンテキストの実行周期を取得する +# # -# -# @param rtc RTݡͥ -# @return ¹Լ +# @param rtc RTコンポーネント +# @return 実行周期 # # @else # -# @brief -# @param ec +# @brief +# @param ec # @return # # @endif def get_default_rate(rtc): - ec = get_actual_ec(rtc) - return ec.get_rate() + ec = get_actual_ec(rtc) + if CORBA.is_nil(ec): + return RTC.BAD_PARAMETER + return ec.get_rate() ## # @if jp # -# @brief RTCΥǥեȤμ¹ԥƥȤμ¹Լꤹ +# @brief RTCのデフォルトの実行コンテキストの実行周期を設定する # -# -# @param rtc RTݡͥ -# @param rate ¹Լ -# @return set_rateؿ֤ͤ -# RTC_OK꤬ +# +# @param rtc RTコンポーネント +# @param rate 実行周期 +# @return set_rate関数の戻り値を返す。 +# RTC_OKで設定が成功 # # @else # -# @brief +# @brief # @param ec # # @endif def set_default_rate(rtc, rate): - ec = get_actual_ec(rtc) - return ec.set_rate(rate) + ec = get_actual_ec(rtc) + if CORBA.is_nil(ec): + return RTC.BAD_PARAMETER + return ec.set_rate(rate) ## # @if jp # -# @brief RTCλIDμ¹ԥƥȤμ +# @brief RTCの指定IDの実行コンテキストの周期を取得 +# # -# -# @param rtc оݤRTݡͥ -# @param ec_id μ¹ԥƥȤID -# @return ¹Լ +# @param rtc 対象のRTコンポーネント +# @param ec_id 指定の実行コンテキストのID +# @return 実行周期 # # @else # -# @brief +# @brief # @param ec # @return # # @endif def get_current_rate(rtc, ec_id): - ec = get_actual_ec(rtc, ec_id) - return ec.get_rate() + ec = get_actual_ec(rtc, ec_id) + if CORBA.is_nil(ec): + return RTC.BAD_PARAMETER + return ec.get_rate() ## # @if jp # -# @brief RTCλIDμ¹ԥƥȤμ +# @brief RTCの指定IDの実行コンテキストの周期を設定 +# # -# -# @param rtc оݤRTݡͥ -# @param ec_id μ¹ԥƥȤID -# @param rate ¹Լ -# @return set_rateؿ֤ͤ -# RTC_OK꤬ +# @param rtc 対象のRTコンポーネント +# @param ec_id 指定の実行コンテキストのID +# @param rate 実行周期 +# @return set_rate関数の戻り値を返す。 +# RTC_OKで設定が成功 # # @else # -# @brief -# @param +# @brief +# @param # # @endif def set_current_rate(rtc, ec_id, rate): - ec = get_actual_ec(rtc, ec_id) - return ec.set_rate(rate) + ec = get_actual_ec(rtc, ec_id) + if CORBA.is_nil(ec): + return RTC.BAD_PARAMETER + return ec.set_rate(rate) ## # @if jp # -# @brief оݤRTCΥǥեȤμ¹ԥƥȤ˻RTCϢդ +# @brief 対象のRTCのデフォルトの実行コンテキストに指定のRTCを関連付ける +# # -# -# @param localcomp оݤRTݡͥ -# @param othercomp ¹ԥƥȤ˴ϢդRTݡͥ -# @return ecμ˼ԤBAD_PARAMETER֤ -# ǤʤaddComponentؿ֤ͤRTC_OK³ +# @param localcomp 対象のRTコンポーネント +# @param othercomp 実行コンテキストに関連付けるRTコンポーネント +# @return ecの取得に失敗した場合はBAD_PARAMETERを返す +# そうでない場合はaddComponent関数の戻り値を返す。RTC_OKで接続成功。 # # @else # -# @brief -# @param +# @brief +# @param # # @endif def add_rtc_to_default_ec(localcomp, othercomp): - if CORBA.is_nil(othercomp): - return RTC.BAD_PARAMETER - ec = get_actual_ec(localcomp) - if CORBA.is_nil(ec): - return RTC.BAD_PARAMETER - return ec.add_component(othercomp) + if CORBA.is_nil(othercomp): + return RTC.BAD_PARAMETER + ec = get_actual_ec(localcomp) + if CORBA.is_nil(ec): + return RTC.BAD_PARAMETER + return ec.add_component(othercomp) ## # @if jp # -# @brief оݤRTCΥǥեȤμ¹ԥƥȤλRTCؤδϢդ +# @brief 対象のRTCのデフォルトの実行コンテキストの指定のRTCへの関連付けを解除する # -# -# @param localcomp оݤRTݡͥ -# @param othercomp ¹ԥƥȤȤδϢդRTݡͥ -# @return ecμ˼ԤBAD_PARAMETER֤ -# ǤʤremoveComponentؿ֤ͤRTC_OKDz +# +# @param localcomp 対象のRTコンポーネント +# @param othercomp 実行コンテキストとの関連付けを解除するRTコンポーネント +# @return ecの取得に失敗した場合はBAD_PARAMETERを返す +# そうでない場合はremoveComponent関数の戻り値を返す。RTC_OKで解除成功。 # # @else # -# @brief -# @param +# @brief +# @param # # @endif def remove_rtc_to_default_ec(localcomp, othercomp): - if CORBA.is_nil(othercomp): - return RTC.BAD_PARAMETER - ec = get_actual_ec(localcomp) - if CORBA.is_nil(ec): - return RTC.BAD_PARAMETER - return ec.remove_component(othercomp) + if CORBA.is_nil(othercomp): + return RTC.BAD_PARAMETER + ec = get_actual_ec(localcomp) + if CORBA.is_nil(ec): + return RTC.BAD_PARAMETER + return ec.remove_component(othercomp) ## # @if jp # -# @brief RTCΥǥեȤμ¹ԥƥȤ˻äƤRTCΥꥹȤ -# ¹ԥƥȤnilξ϶ΥꥹȤ֤ +# @brief RTCのデフォルトの実行コンテキストに参加しているRTCのリストを取得する +# 実行コンテキストがnilの場合は空のリストを返す # -# -# @param rtc RTݡͥ -# @return RTCΥꥹ +# +# @param rtc RTコンポーネント +# @return RTCのリスト # # @else # -# @brief +# @brief # @param ec -# @return +# @return # # @endif def get_participants_rtc(rtc): - ec = get_actual_ec(rtc) - if CORBA.is_nil(ec): - return [] - profile = ec.get_profile() - return profile.participants + ec = get_actual_ec(rtc) + if CORBA.is_nil(ec): + return [] + profile = ec.get_profile() + return profile.participants ## # @if jp # -# @brief ꤷRTCݻݡȤ̾ +# @brief 指定したRTCの保持するポートの名前を取得 # -# -# @param rtc оݤRTݡͥ -# @return ݡ̾Υꥹ +# +# @param rtc 対象のRTコンポーネント +# @return ポート名のリスト # # @else # -# @brief +# @brief # @param rtc # @return # # @endif def get_port_names(rtc): - names = [] - if CORBA.is_nil(rtc): + names = [] + if CORBA.is_nil(rtc): + return names + ports = rtc.get_ports() + for p in ports: + pp = p.get_port_profile() + s = pp.name + names.append(s) return names - ports = rtc.get_ports() - for p in ports: - pp = p.get_port_profile() - s = pp.name - names.append(s) - return names ## # @if jp # -# @brief ꤷRTCݻ륤ݡȤ̾ +# @brief 指定したRTCの保持するインポートの名前を取得 +# # -# -# @param rtc оݤRTݡͥ -# @return ݡ̾Υꥹ +# @param rtc 対象のRTコンポーネント +# @return ポート名のリスト # # @else # -# @brief +# @brief # @param rtc # @return # # @endif def get_inport_names(rtc): - names = [] - if CORBA.is_nil(rtc): + names = [] + if CORBA.is_nil(rtc): + return names + + ports = rtc.get_ports() + for p in ports: + pp = p.get_port_profile() + prop = OpenRTM_aist.Properties() + OpenRTM_aist.NVUtil.copyToProperties(prop, pp.properties) + if prop.getProperty("port.port_type") == "DataInPort": + s = pp.name + names.append(s) return names - - ports = rtc.get_ports() - for p in ports: - pp = p.get_port_profile() - prop = OpenRTM_aist.Properties() - OpenRTM_aist.NVUtil.copyToProperties(prop, pp.properties) - if prop.getProperty("port.port_type") == "DataInPort": - s = pp.name - names.append(s) - return names ## # @if jp # -# @brief ꤷRTCݻ륢ȥݡȤ̾ +# @brief 指定したRTCの保持するアウトポートの名前を取得 +# # -# -# @param rtc оݤRTݡͥ -# @return ݡ̾Υꥹ +# @param rtc 対象のRTコンポーネント +# @return ポート名のリスト # # @else # -# @brief +# @brief # @param rtc # @return # # @endif def get_outport_names(rtc): - names = [] - if CORBA.is_nil(rtc): - return names - - ports = rtc.get_ports() - for p in ports: - pp = p.get_port_profile() - prop = OpenRTM_aist.Properties() - OpenRTM_aist.NVUtil.copyToProperties(prop, pp.properties) - if prop.getProperty("port.port_type") == "DataOutPort": - s = pp.name - names.append(s) - return names + names = [] + if CORBA.is_nil(rtc): + return names + ports = rtc.get_ports() + for p in ports: + pp = p.get_port_profile() + prop = OpenRTM_aist.Properties() + OpenRTM_aist.NVUtil.copyToProperties(prop, pp.properties) + if prop.getProperty("port.port_type") == "DataOutPort": + s = pp.name + names.append(s) + return names ## # @if jp # -# @brief ꤷRTCݻ륵ӥݡȤ̾ +# @brief 指定したRTCの保持するサービスポートの名前を取得 # -# -# @param rtc оݤRTݡͥ -# @return ݡ̾Υꥹ +# +# @param rtc 対象のRTコンポーネント +# @return ポート名のリスト # # @else # -# @brief +# @brief # @param rtc # @return # # @endif def get_svcport_names(rtc): - names = [] - if CORBA.is_nil(rtc): + names = [] + if CORBA.is_nil(rtc): + return names + + ports = rtc.get_ports() + for p in ports: + pp = p.get_port_profile() + prop = OpenRTM_aist.Properties() + OpenRTM_aist.NVUtil.copyToProperties(prop, pp.properties) + if prop.getProperty("port.port_type") == "CorbaPort": + s = pp.name + names.append(s) return names - - ports = rtc.get_ports() - for p in ports: - pp = p.get_port_profile() - prop = OpenRTM_aist.Properties() - OpenRTM_aist.NVUtil.copyToProperties(prop, pp.properties) - if prop.getProperty("port.port_type") == "CorbaPort": - s = pp.name - names.append(s) - return names ## # @if jp # -# @brief оݤRTCꤷ̾ΥݡȤ +# @brief 対象のRTCから指定した名前のポートを取得 +# # -# -# @param rtc RTݡͥ -# @param port_name ݡ̾ -# @return ݡ +# @param rtc RTコンポーネント +# @param port_name ポート名 +# @return ポート # # @else # -# @brief -# @param rtc +# @brief +# @param rtc # @param port_name -# @return +# @return # # @endif # -# RTC::PortService_var get_port_by_name(const RTC::RTObject_ptr rtc, std::string port_name) +# RTC::PortService_var get_port_by_name(const RTC::RTObject_ptr rtc, +# std::string port_name) def get_port_by_name(rtc, port_name): - if CORBA.is_nil(rtc): - return RTC.PortService._nil - ports = rtc.get_ports() - for p in ports: - pp = p.get_port_profile() - s = pp.name - - if port_name == s: - return p + if CORBA.is_nil(rtc): + return RTC.PortService._nil + ports = rtc.get_ports() + for p in ports: + pp = p.get_port_profile() + s = pp.name - return RTC.PortService._nil + if port_name == s: + return p + return RTC.PortService._nil ## # @if jp # -# @brief ꤷݡȤݻƤ륳ͥ̾ΥꥹȤ +# @brief 指定したポートの保持しているコネクタの名前のリストを取得 +# # -# -# @param port оݤΥݡ -# @return ͥ̾Υꥹ +# @param port 対象のポート +# @return コネクタ名のリスト # # @else # -# @brief +# @brief # @param port # @return # # @endif def get_connector_names_by_portref(port): - names = [] - if CORBA.is_nil(port): + names = [] + if CORBA.is_nil(port): + return names + conprof = port.get_connector_profiles() + for c in conprof: + names.append(c.name) return names - conprof = port.get_connector_profiles() - for c in conprof: - names.append(c.name) - return names ## # @if jp # -# @brief оݤRTCλꤷݡȤΥͥ̾ΥꥹȤ +# @brief 対象のRTCの指定したポートのコネクタの名前のリストを取得 # -# @param rtc RTݡͥ -# @param port_name ݡ̾ -# @return ͥ̾Υꥹ +# @param rtc RTコンポーネント +# @param port_name ポート名 +# @return コネクタ名のリスト # # @else # @@ -737,91 +749,88 @@ def get_connector_names_by_portref(port): # @return # # @endif -def get_connector_names(rtc, port_name): - names = [] - port = get_port_by_name(rtc, port_name) - if CORBA.is_nil(port): - return names - conprof = port.get_connector_profiles() - for c in conprof: - names.append(c.name) - return names - +def get_connector_names(rtc, port_name): + names = [] + port = get_port_by_name(rtc, port_name) + if CORBA.is_nil(port): + return names + conprof = port.get_connector_profiles() + for c in conprof: + names.append(c.name) + return names ## # @if jp # -# @brief ꤷݡȤݻƤ륳ͥIDΥꥹȤ +# @brief 指定したポートの保持しているコネクタのIDのリストを取得 # -# -# @param port оݤΥݡ -# @return ͥIDΥꥹ +# +# @param port 対象のポート +# @return コネクタのIDのリスト # # @else # -# @brief +# @brief # @param port # @return # # @endif def get_connector_ids_by_portref(port): - ids = [] - if CORBA.is_nil(port): + ids = [] + if CORBA.is_nil(port): + return ids + conprof = port.get_connector_profiles() + for c in conprof: + ids.append(c.connector_id) return ids - conprof = port.get_connector_profiles() - for c in conprof: - ids.append(c.connector_id) - return ids - - ## # @if jp # -# @brief оݤRTCλꤷݡȤΥͥIDΥꥹȤ +# @brief 対象のRTCの指定したポートのコネクタのIDのリストを取得 +# # -# -# @param rtc RTݡͥ -# @param port_name ݡ̾ -# @return ͥIDΥꥹ +# @param rtc RTコンポーネント +# @param port_name ポート名 +# @return コネクタのIDのリスト # # @else # -# @brief +# @brief # @param rtc # @param port_name # @return # # @endif def get_connector_ids(rtc, port_name): - ids = [] - port = get_port_by_name(rtc, port_name) - if CORBA.is_nil(port): + ids = [] + port = get_port_by_name(rtc, port_name) + if CORBA.is_nil(port): + return ids + conprof = port.get_connector_profiles() + for c in conprof: + ids.append(c.connector_id) return ids - conprof = port.get_connector_profiles() - for c in conprof: - ids.append(c.connector_id) - return ids ## # @if jp # -# @brief ꤷݡȤ³뤿Υͥץե +# @brief 指定したポートを接続するためのコネクタプロファイルを取得 +# # -# -# @param name ͥ̾ -# @param prop_arg -# @param port0 оݤΥݡ1 -# @param port1 оݤΥݡ2 -# @return ͥץե +# @param name コネクタ名 +# @param prop_arg 設定 +# @param port0 対象のポート1 +# @param port1 対象のポート2 +# @return コネクタプロファイル # # @else # -# @brief +# @brief # @param name # @param prop_arg # @param port0 @@ -829,47 +838,43 @@ def get_connector_ids(rtc, port_name): # @return # # @endif -# RTC::ConnectorProfile_var create_connector(const std::string name,const coil::Properties prop_arg,const RTC::PortService_ptr port0,const RTC::PortService_ptr port1) -def create_connector(name, prop_arg, port0, port1): - prop = prop_arg - if CORBA.is_nil(port1): - conn_prof = RTC.ConnectorProfile(name, "", [port0],[]) - else: - conn_prof = RTC.ConnectorProfile(name, "", [port0, port1],[]) - +# RTC::ConnectorProfile_var create_connector(const std::string name,const +# coil::Properties prop_arg,const RTC::PortService_ptr port0,const +# RTC::PortService_ptr port1) - if not str(prop.getProperty("dataport.dataflow_type")): - prop.setProperty("dataport.dataflow_type","push") +def create_connector(name, prop_arg, port0, port1): + prop = prop_arg + if CORBA.is_nil(port1): + conn_prof = RTC.ConnectorProfile(name, "", [port0], []) + else: + conn_prof = RTC.ConnectorProfile(name, "", [port0, port1], []) - + if not str(prop.getProperty("dataport.dataflow_type")): + prop.setProperty("dataport.dataflow_type", "push") - if not str(prop.getProperty("dataport.interface_type")): - prop.setProperty("dataport.interface_type","corba_cdr") + if not str(prop.getProperty("dataport.interface_type")): + prop.setProperty("dataport.interface_type", "corba_cdr") + conn_prof.properties = [] + OpenRTM_aist.NVUtil.copyFromProperties(conn_prof.properties, prop) - conn_prof.properties = [] - OpenRTM_aist.NVUtil.copyFromProperties(conn_prof.properties, prop) - - return conn_prof - + return conn_prof - - ## # @if jp # -# @brief ꤷݡƱΤ³Ƥ뤫Ƚ +# @brief 指定したポート同士が接続されているかを判定 +# # -# -# @param localport оݤΥݡ1 -# @param otherport оݤΥݡ2 -# @return True: ³ѤߡFalse: ̤³ +# @param localport 対象のポート1 +# @param otherport 対象のポート2 +# @return True: 接続済み、False: 未接続 # # @else # -# @brief +# @brief # @param name # @param prop_arg # @param port0 @@ -879,485 +884,495 @@ def create_connector(name, prop_arg, port0, port1): # @endif def already_connected(localport, otherport): - conprof = localport.get_connector_profiles() - for c in conprof: - for p in c.ports: - if p._is_equivalent(otherport): - return True + if localport._is_equivalent(otherport): + return False + conprof = localport.get_connector_profiles() + for c in conprof: + for p in c.ports: + if p._is_equivalent(otherport): + return True - return False + return False ## # @if jp # -# @brief ꤷݡȤ³ +# @brief 指定したポートを接続する +# # -# -# @param name ͥ̾ -# @param prop -# @param port0 оݤΥݡ1 -# @param port1 оݤΥݡ2 -# @return ݡȤΥ֥ȥե󥹤nilξBAD_PARAMETER֤ -# nilǤϤʤport0.connectؿ֤ͤRTC_OKξ³ +# @param name コネクタ名 +# @param prop 設定 +# @param port0 対象のポート1 +# @param port1 対象のポート2 +# @return ポートのオブジェクトリファレンスがnilの場合はBAD_PARAMETERを返す +# nilではない場合はport0.connect関数の戻り値を返す。RTC_OKの場合は接続が成功 # # @else # -# @brief +# @brief # @param name # @param prop # @param port0 # @param port1 -# @return +# @return # # @endif -# RTC::ReturnCode_t connect(const std::string name,const coil::Properties prop,const RTC::PortService_ptr port0,const RTC::PortService_ptr port1) +# RTC::ReturnCode_t connect(const std::string name,const coil::Properties +# prop,const RTC::PortService_ptr port0,const RTC::PortService_ptr port1) def connect(name, prop, port0, port1): - if CORBA.is_nil(port0): - return RTC.BAD_PARAMETER - #if CORBA.is_nil(port1): - # return RTC.BAD_PARAMETER - if not CORBA.is_nil(port1): - if port0._is_equivalent(port1): - return RTC.BAD_PARAMETER - cprof = create_connector(name, prop, port0, port1) - return port0.connect(cprof)[0] - + if CORBA.is_nil(port0): + return RTC.BAD_PARAMETER + # if CORBA.is_nil(port1): + # return RTC.BAD_PARAMETER + if not CORBA.is_nil(port1): + if port0._is_equivalent(port1): + return RTC.BAD_PARAMETER + cprof = create_connector(name, prop, port0, port1) + return port0.connect(cprof)[0] ## # @if jp # -# @brief ꤷݡȤȻꤷꥹΥݡƤ³ +# @brief 指定したポートと指定したリスト内のポート全てと接続する +# # -# -# @param name ͥ̾ -# @param prop -# @param port оݤΥݡ -# @param target_ports оݤΥݡȤΥꥹ -# @return Ƥ³RTC_OK֤ -# connectؿRTC_OKʳ֤BAD_PARAMETER֤ +# @param name コネクタ名 +# @param prop 設定 +# @param port 対象のポート +# @param target_ports 対象のポートのリスト +# @return 全ての接続が成功した場合はRTC_OKを返す。 +# connect関数がRTC_OK以外を返した場合はBAD_PARAMETERを返す。 # # # @else # -# @brief +# @brief # @param name # @param prop # @param port0 # @param port1 -# @return +# @return # # @endif -# RTC::ReturnCode_t connect_multi(const std::string name,const coil::Properties prop,const RTC::PortService_ptr port,RTC::PortServiceList_var& target_ports) +# RTC::ReturnCode_t connect_multi(const std::string name,const +# coil::Properties prop,const RTC::PortService_ptr +# port,RTC::PortServiceList_var& target_ports) def connect_multi(name, prop, port, target_ports): - ret = RTC.RTC_OK - if CORBA.is_nil(port): - return RTC.BAD_PARAMETER - for p in target_ports: - if CORBA.is_nil(p): - ret = RTC.BAD_PARAMETER - continue - if p._is_equivalent(port): - ret = RTC.BAD_PARAMETER - continue - if already_connected(port, p): - ret = RTC.BAD_PARAMETER - continue - if RTC.RTC_OK != connect(name, prop, port, p): - ret = RTC.BAD_PARAMETER - - return ret + ret = RTC.RTC_OK + if CORBA.is_nil(port): + return RTC.BAD_PARAMETER + for p in target_ports: + if CORBA.is_nil(p): + ret = RTC.BAD_PARAMETER + continue + if p._is_equivalent(port): + ret = RTC.BAD_PARAMETER + continue + if already_connected(port, p): + ret = RTC.BAD_PARAMETER + continue + if RTC.RTC_OK != connect(name, prop, port, p): + ret = RTC.BAD_PARAMETER + + return ret ## # @if jp # @class find_port -# @brief ݡȤ̾鸡 +# @brief ポートを名前から検索 # # @else # @class find_port -# @brief +# @brief # # @endif # class find_port: - ## - # @if jp - # - # @brief 󥹥ȥ饯 - # ݡ̾ꤹ - # - # - # @param self - # @param name ݡ̾ - # - # @else - # - # @brief - # @param self - # @param name - # - # @endif - # find_port(const std::string name) - def __init__(self, name): - self._name = name - ## - # @if jp - # - # @brief оݤΥݡȤ̾Ȼꤷݡ̾פ뤫Ƚ - # - # - # @param self - # @param p оݤΥݡ - # @return True: ̾סFalse:̾԰ - # - # @else - # - # @brief - # @param self - # @param p - # @return - # - # @endif - # bool operator()(RTC::PortService_var p) - def __call__(self, p): - prof = p.get_port_profile() - c = prof.name - - return (self._name == c) - + ## + # @if jp + # + # @brief コンストラクタ + # 検索するポート名を指定する + # + # + # @param self + # @param name ポート名 + # + # @else + # + # @brief + # @param self + # @param name + # + # @endif + # find_port(const std::string name) + def __init__(self, name): + self._name = name + ## + # @if jp + # + # @brief 対象のポートの名前と指定したポート名が一致するか判定 + # + # + # @param self + # @param p 対象のポート + # @return True: 名前が一致、False: 名前が不一致 + # + # @else + # + # @brief + # @param self + # @param p + # @return + # + # @endif + # bool operator()(RTC::PortService_var p) + + def __call__(self, p): + prof = p.get_port_profile() + c = prof.name + + return (self._name == c) + ## # @if jp # -# @brief оݤRTCλꤷ̾ΥݡȤ³ +# @brief 対象のRTCの指定した名前のポートを接続する # -# -# @param name ͥ̾ -# @param prop -# @param rtc0 оݤRTCݡͥ1 -# @param portName0 оݤΥݡ̾1 -# @param rtc1 оݤRTCݡͥ2 -# @param portName1 оݤRTCݡͥ2 -# @return RTCݡȤnilξBAD_PARAMETER֤ -# nilǤϤʤport0.connectؿ֤ͤRTC_OKξ³ +# +# @param name コネクタ名 +# @param prop 設定 +# @param rtc0 対象のRTCコンポーネント1 +# @param portName0 対象のポート名1 +# @param rtc1 対象のRTCコンポーネント2 +# @param portName1 対象のRTCコンポーネント2 +# @return RTC、ポートがnilの場合はBAD_PARAMETERを返す。 +# nilではない場合はport0.connect関数の戻り値を返す。RTC_OKの場合は接続が成功 # # @else # -# @brief +# @brief # @param name # @param prop_arg # @param port0 -# @param port1 +# @param port1 # # @endif # -# RTC::ReturnCode_t connect_by_name(std::string name, coil::Properties prop,RTC::RTObject_ptr rtc0,const std::string port_name0,RTC::RTObject_ptr rtc1,const std::string port_name1) +# RTC::ReturnCode_t connect_by_name(std::string name, coil::Properties +# prop,RTC::RTObject_ptr rtc0,const std::string +# port_name0,RTC::RTObject_ptr rtc1,const std::string port_name1) + + def connect_by_name(name, prop, rtc0, port_name0, rtc1, port_name1): - if CORBA.is_nil(rtc0): - return RTC.BAD_PARAMETER - if CORBA.is_nil(rtc1): - return RTC.BAD_PARAMETER + if CORBA.is_nil(rtc0): + return RTC.BAD_PARAMETER + if CORBA.is_nil(rtc1): + return RTC.BAD_PARAMETER - port0 = get_port_by_name(rtc0, port_name0) - if CORBA.is_nil(port0): - return RTC.BAD_PARAMETER + port0 = get_port_by_name(rtc0, port_name0) + if CORBA.is_nil(port0): + return RTC.BAD_PARAMETER - port1 = get_port_by_name(rtc1, port_name1) - if CORBA.is_nil(port1): - return RTC.BAD_PARAMETER + port1 = get_port_by_name(rtc1, port_name1) + if CORBA.is_nil(port1): + return RTC.BAD_PARAMETER - return connect(name, prop, port0, port1) + return connect(name, prop, port0, port1) ## # @if jp # -# @brief ΥͥǤ +# @brief 指定のコネクタを切断する # -# -# @param connector_prof ͥץե -# @return ͥץեݻƤݡȤΥ֥ȥե󥹤nilξBAD_PARAMETER֤ -# nilǤϤʤports[0].disconnectؿ֤ͤRTC_OKξǤ +# +# @param connector_prof コネクタプロファイル +# @return コネクタプロファイルで保持しているポートのオブジェクトリファレンスがnilの場合はBAD_PARAMETERを返す +# nilではない場合はports[0].disconnect関数の戻り値を返す。RTC_OKの場合は切断が成功 # # @else # -# @brief +# @brief # @param connector_prof # @return # # @endif def disconnect(connector_prof): - ports = connector_prof.ports - return disconnect_by_portref_connector_id(ports[0], connector_prof.connector_id) - - + ports = connector_prof.ports + return disconnect_by_portref_connector_id( + ports[0], connector_prof.connector_id) + ## # @if jp # -# @brief оݤΥݡȤǻꤷ̾Υͥ +# @brief 対象のポートで指定した名前のコネクタを切断 # -# -# @param port_ref оݤΥݡ -# @param conn_name ͥ̾ -# @return portnilξBAD_PARAMETER֤ -# nilǤϤʤdisconnectؿ֤ͤRTC_OKξǤ +# +# @param port_ref 対象のポート +# @param conn_name コネクタ名 +# @return portがnilの場合はBAD_PARAMETERを返す +# nilではない場合はdisconnect関数の戻り値を返す。RTC_OKの場合は切断が成功 # # @else # -# @brief -# @param port_ref -# @param conn_name -# @return +# @brief +# @param port_ref +# @param conn_name +# @return # # @endif def disconnect_by_portref_connector_name(port_ref, conn_name): - if CORBA.is_nil(port_ref): + if CORBA.is_nil(port_ref): + return RTC.BAD_PARAMETER + conprof = port_ref.get_connector_profiles() + for c in conprof: + if c.name == conn_name: + return disconnect(c) return RTC.BAD_PARAMETER - conprof = port_ref.get_connector_profiles() - for c in conprof: - if c.name == conn_name: - return disconnect(c) - return RTC.BAD_PARAMETER - ## # @if jp # -# @brief оݤ̾ΥݡȤǻꤷ̾Υͥ +# @brief 対象の名前のポートで指定した名前のコネクタを切断 # -# -# @param port_name оݤΥݡ̾ -# @param conn_name ͥ̾ -# @return port¸ߤʤBAD_PARAMETER֤ -# nilǤϤʤdisconnectؿ֤ͤRTC_OKξǤ +# +# @param port_name 対象のポート名 +# @param conn_name コネクタ名 +# @return portが存在しない場合はBAD_PARAMETERを返す +# nilではない場合はdisconnect関数の戻り値を返す。RTC_OKの場合は切断が成功 # # @else # -# @brief -# @param +# @brief +# @param # # @endif def disconnect_by_portname_connector_name(port_name, conn_name): - port_ref = get_port_by_url(port_name) - if CORBA.is_nil(port_ref): + port_ref = get_port_by_url(port_name) + if CORBA.is_nil(port_ref): + return RTC.BAD_PARAMETER + + conprof = port_ref.get_connector_profiles() + for c in conprof: + if c.name == conn_name: + return disconnect(c) + return RTC.BAD_PARAMETER - - conprof = port_ref.get_connector_profiles() - for c in conprof: - if c.name == conn_name: - return disconnect(c) - - return RTC.BAD_PARAMETER ## # @if jp # -# @brief оݤΥݡȤǻꤷIDΥͥ +# @brief 対象のポートで指定したIDのコネクタを切断 +# # -# -# @param port оݤΥݡ -# @param name ͥID -# @return portnilξBAD_PARAMETER֤ -# nilǤϤʤdisconnectؿ֤ͤRTC_OKξǤ +# @param port 対象のポート +# @param name コネクタID +# @return portがnilの場合はBAD_PARAMETERを返す +# nilではない場合はdisconnect関数の戻り値を返す。RTC_OKの場合は切断が成功 # # @else # -# @brief -# @param +# @brief +# @param # # @endif def disconnect_by_portref_connector_id(port_ref, conn_id): - if CORBA.is_nil(port_ref): - return RTC.BAD_PARAMETER - return port_ref.disconnect(conn_id) + if CORBA.is_nil(port_ref): + return RTC.BAD_PARAMETER + return port_ref.disconnect(conn_id) ## # @if jp # -# @brief оݤ̾ΥݡȤǻꤷIDΥͥ +# @brief 対象の名前のポートで指定したIDのコネクタを切断 # -# -# @param port_name оݤΥݡ̾ -# @param name ͥID -# @return port¸ߤʤBAD_PARAMETER֤ -# nilǤϤʤdisconnectؿ֤ͤRTC_OKξǤ +# +# @param port_name 対象のポート名 +# @param name コネクタID +# @return portが存在しない場合はBAD_PARAMETERを返す +# nilではない場合はdisconnect関数の戻り値を返す。RTC_OKの場合は切断が成功 # # @else # -# @brief -# @param port_name -# @param name -# @return +# @brief +# @param port_name +# @param name +# @return # # @endif def disconnect_by_portname_connector_id(port_name, conn_id): - port_ref = get_port_by_url(port_name) - if port_ref == RTC.PortService._nil: - return RTC.BAD_PARAMETER - - return port_ref.disconnect(conn_id) - + port_ref = get_port_by_url(port_name) + if port_ref == RTC.PortService._nil: + return RTC.BAD_PARAMETER + + return port_ref.disconnect(conn_id) + ## # @if jp # -# @brief оݤΥݡȤΥͥ +# @brief 対象のポートのコネクタを全て切断 +# # -# -# @param port_ref ݡȤΥ֥ȥե -# @return portnilξBAD_PARAMETER֤ -# ǤǤRTC_OK֤ +# @param port_ref ポートのオブジェクトリファレンス +# @return portがnilの場合はBAD_PARAMETERを返す +# 切断できた場合はRTC_OKを返す # # @else # -# @brief +# @brief # @param port -# @return +# @return # # @endif def disconnect_all_by_ref(port_ref): - if CORBA.is_nil(port_ref): - return RTC.BAD_PARAMETER - return port_ref.disconnect_all() + if CORBA.is_nil(port_ref): + return RTC.BAD_PARAMETER + return port_ref.disconnect_all() ## # @if jp # -# @brief ݡ̾ΥݡȤΥͥ +# @brief 指定ポート名のポートのコネクタを全て切断 # -# -# @param port_name ݡ̾ -# @return port¸ߤʤBAD_PARAMETER֤ -# ǤǤRTC_OK֤ +# +# @param port_name ポート名 +# @return portが存在しない場合はBAD_PARAMETERを返す +# 切断できた場合はRTC_OKを返す # # @else # -# @brief +# @brief # @param port -# @return +# @return # # @endif def disconnect_all_by_name(port_name): - port_ref = get_port_by_url(port_name) - if port_ref == RTC.PortService._nil: - return RTC.BAD_PARAMETER - return port_ref.disconnect_all() + port_ref = get_port_by_url(port_name) + if port_ref == RTC.PortService._nil: + return RTC.BAD_PARAMETER + return port_ref.disconnect_all() ## # @if jp # -# @brief ꤷ̾ΥݡȤ +# @brief 指定した名前のポートを取得 +# # -# -# @param port_name ݡ̾ -# @return ݡȤΥ֥ȥե -# port¸ߤʤnil֤ +# @param port_name ポート名 +# @return ポートのオブジェクトリファレンス +# portが存在しない場合はnilを返す # # @else # -# @brief +# @brief # @param port_name -# @return +# @return # # @endif def get_port_by_url(port_name): - mgr = OpenRTM_aist.Manager.instance() - nm = mgr.getNaming() - p = port_name.split(".") - if len(p) < 2: - return RTC.PortService._nil - - rtcs = nm.string_to_component(port_name.rstrip("."+p[-1])) - - if len(rtcs) < 1: - return RTC.PortService._nil - pn = port_name.split("/") - - return get_port_by_name(rtcs[0],pn[-1]) + mgr = OpenRTM_aist.Manager.instance() + nm = mgr.getNaming() + p = port_name.split(".") + if len(p) < 2: + return RTC.PortService._nil + + rtcs = nm.string_to_component(port_name.rstrip("." + p[-1])) + + if not rtcs: + return RTC.PortService._nil + pn = port_name.split("/") + + return get_port_by_name(rtcs[0], pn[-1]) ## # @if jp # -# @brief оݥݡȤ³ƤݡȤǻꤷݡ̾Ȱפ +# @brief 対象ポートと接続しているポートで指定したポート名と一致した場合に切断 # -# -# @param localport оݤΥݡ -# @param othername ³Ƥݡ̾ -# @return ݡȤnilξ硢localport̾othernameפ硢³ƤݡȤ̾othernameȰפΤʤBAD_PARAMETER֤ -# 嵭ξƤϤޤʤdisconnectؿ֤ͤRTC_OKξǤ +# +# @param localport 対象のポート +# @param othername 接続しているポート名 +# @return ポートがnilの場合、localportの名前とothernameが一致する場合、接続しているポートの名前でothernameと一致するものがない場合にBAD_PARAMETERを返す +# 上記の条件に当てはまらない場合はdisconnect関数の戻り値を返す。RTC_OKの場合は切断が成功 # # @else # -# @brief -# @param +# @brief +# @param # # @endif + + def disconnect_by_port_name(localport, othername): - if CORBA.is_nil(localport): + if CORBA.is_nil(localport): + return RTC.BAD_PARAMETER + prof = localport.get_port_profile() + if prof.name == othername: + return RTC.BAD_PARAMETER + + conprof = localport.get_connector_profiles() + for c in conprof: + for p in c.ports: + if not CORBA.is_nil(p): + pp = p.get_port_profile() + if pp.name == othername: + return disconnect(c) return RTC.BAD_PARAMETER - prof = localport.get_port_profile() - if prof.name == othername: - return RTC.BAD_PARAMETER - - conprof = localport.get_connector_profiles() - for c in conprof: - for p in c.ports: - if not CORBA.is_nil(p): - pp = p.get_port_profile() - if pp.name == othername: - return disconnect(c) - return RTC.BAD_PARAMETER ## # @if jp # -# @brief оݤRTݡͥȤλꤷ̾Υե졼󥻥åȤkey-valueǼ +# @brief 対象のRTコンポーネントの指定した名前のコンフィギュレーションセットをkey-valueで取得 +# # -# -# @param rtc оݤRTݡͥ -# @param conf_name ե졼󥻥å̾ -# @return ե졼󥻥å +# @param rtc 対象のRTコンポーネント +# @param conf_name コンフィギュレーションセット名 +# @return コンフィギュレーションセット # # @else # -# @brief -# @param rtc -# @param conf_name -# @return +# @brief +# @param rtc +# @param conf_name +# @return # # @endif def get_configuration(rtc, conf_name): - conf = rtc.get_configuration() - - confset = conf.get_configuration_set(conf_name) - confData = confset.configuration_data - prop = OpenRTM_aist.Properties() - OpenRTM_aist.NVUtil.copyToProperties(prop, confData) - return prop + conf = rtc.get_configuration() + + confset = conf.get_configuration_set(conf_name) + confData = confset.configuration_data + prop = OpenRTM_aist.Properties() + OpenRTM_aist.NVUtil.copyToProperties(prop, confData) + return prop ## # @if jp # -# @brief ꤷե졼󥻥å̾ѥ᡼̾Υե졼ѥ᡼ +# @brief 指定したコンフィギュレーションセット名、パラメータ名のコンフィギュレーションパラメータを取得 +# # -# -# @param rtc RTݡͥ -# @param confset_name ե졼󥻥å̾ -# @param value_name ѥ᡼̾ -# @return ѥ᡼ +# @param rtc RTコンポーネント +# @param confset_name コンフィギュレーションセット名 +# @param value_name パラメータ名 +# @return パラメータ # # @else # -# @brief +# @brief # @param rtc # @param confset_name # @param value_name @@ -1366,81 +1381,77 @@ def get_configuration(rtc, conf_name): # # @endif def get_parameter_by_key(rtc, confset_name, value_name): - conf = rtc.get_configuration() - - - confset = conf.get_configuration_set(confset_name) - confData = confset.configuration_data - prop = OpenRTM_aist.Properties() - OpenRTM_aist.NVUtil.copyToProperties(prop, confData) - return prop.getProperty(value_name) - - + conf = rtc.get_configuration() + + confset = conf.get_configuration_set(confset_name) + confData = confset.configuration_data + prop = OpenRTM_aist.Properties() + OpenRTM_aist.NVUtil.copyToProperties(prop, confData) + return prop.getProperty(value_name) ## # @if jp # -# @brief оݤRTCΥƥ֤ʥե졼󥻥å̾ +# @brief 対象のRTCのアクティブなコンフィギュレーションセット名を取得する +# +# @param rtc RTコンポーネント +# @return コンフィギュレーションセット名 +# コンフィギュレーションの取得に失敗した場合は空の文字列を返す # -# @param rtc RTݡͥ -# @return ե졼󥻥å̾ -# ե졼μ˼Ԥ϶ʸ֤ -# -# @param +# @param # # @else # -# @brief +# @brief # @param rtc -# @return +# @return # # @endif def get_active_configuration_name(rtc): - conf = rtc.get_configuration() - confset = conf.get_active_configuration_set() - return confset.id + conf = rtc.get_configuration() + confset = conf.get_active_configuration_set() + return confset.id ## # @if jp # -# @brief ƥ֤ʥե졼󥻥åȤkey-valueǼ +# @brief アクティブなコンフィギュレーションセットをkey-valueで取得する +# # -# -# @param rtc оݤRTݡͥ -# @return ƥ֤ʥե졼󥻥å +# @param rtc 対象のRTコンポーネント +# @return アクティブなコンフィギュレーションセット # # @else # -# @brief +# @brief # @param rtc # @return # # @endif -def get_active_configuration(rtc): - conf = rtc.get_configuration() - confset = conf.get_active_configuration_set() - confData = confset.configuration_data - prop = OpenRTM_aist.Properties() - OpenRTM_aist.NVUtil.copyToProperties(prop, confData) - return prop - +def get_active_configuration(rtc): + conf = rtc.get_configuration() + confset = conf.get_active_configuration_set() + confData = confset.configuration_data + prop = OpenRTM_aist.Properties() + OpenRTM_aist.NVUtil.copyToProperties(prop, confData) + return prop ## # @if jp # -# @brief ե졼ѥ᡼ +# @brief コンフィギュレーションパラメータを設定 # # -# @param rtc оݤRTݡͥ -# @param confset_name ե졼󥻥å̾ -# @param value_name ѥ᡼̾ -# @param value ѥ᡼ -# @return True:False:˼ +# @param rtc 対象のRTコンポーネント +# @param confset_name コンフィギュレーションセット名 +# @param value_name パラメータ名 +# @param value パラメータ +# @return True:設定に成功、False:設定に失敗 # # @else # @@ -1453,31 +1464,31 @@ def get_active_configuration(rtc): # # @endif def set_configuration(rtc, confset_name, value_name, value): - conf = rtc.get_configuration() - - confset = conf.get_configuration_set(confset_name) + conf = rtc.get_configuration() + + confset = conf.get_configuration_set(confset_name) + + set_configuration_parameter(conf, confset, value_name, value) - set_configuration_parameter(conf, confset, value_name, value) - - conf.activate_configuration_set(confset_name) - return True + conf.activate_configuration_set(confset_name) + return True ## # @if jp # -# @brief ƥ֤ʥե졼󥻥åȤΥѥ᡼ +# @brief アクティブなコンフィギュレーションセットのパラメータを設定 # # -# @param rtc оݤRTݡͥ -# @param value_name ѥ᡼̾ -# @param value ѥ᡼ -# @return True:False:˼ +# @param rtc 対象のRTコンポーネント +# @param value_name パラメータ名 +# @param value パラメータ +# @return True:設定に成功、False:設定に失敗 # # @else # # @brief -# @param rtc +# @param rtc # @param confset_name # @param value_name # @param value @@ -1485,26 +1496,26 @@ def set_configuration(rtc, confset_name, value_name, value): # # @endif def set_active_configuration(rtc, value_name, value): - conf = rtc.get_configuration() - - confset = conf.get_active_configuration_set() - set_configuration_parameter(conf, confset, value_name, value) - - conf.activate_configuration_set(confset.id) - return True + conf = rtc.get_configuration() + + confset = conf.get_active_configuration_set() + set_configuration_parameter(conf, confset, value_name, value) + + conf.activate_configuration_set(confset.id) + return True ## # @if jp # -# @brief ե졼ѥ᡼ +# @brief コンフィギュレーションパラメータの設定 # # -# @param conf ե졼 -# @param confset ե졼󥻥å -# @param value_name ѥ᡼̾ -# @param value ѥ᡼ -# @return True:False:˼ +# @param conf コンフィギュレーション +# @param confset コンフィギュレーションセット +# @param value_name パラメータ名 +# @param value パラメータ +# @return True:設定に成功、False:設定に失敗 # # @else # @@ -1517,12 +1528,11 @@ def set_active_configuration(rtc, value_name, value): # # @endif def set_configuration_parameter(conf, confset, value_name, value): - confData = confset.configuration_data - prop = OpenRTM_aist.Properties() - OpenRTM_aist.NVUtil.copyToProperties(prop, confData) - prop.setProperty(value_name,value) - OpenRTM_aist.NVUtil.copyFromProperties(confData,prop) - confset.configuration_data = confData - conf.set_configuration_set_values(confset) - return True - \ No newline at end of file + confData = confset.configuration_data + prop = OpenRTM_aist.Properties() + OpenRTM_aist.NVUtil.copyToProperties(prop, confData) + prop.setProperty(value_name, value) + OpenRTM_aist.NVUtil.copyFromProperties(confData, prop) + confset.configuration_data = confData + conf.set_configuration_set_values(confset) + return True diff --git a/OpenRTM_aist/CORBA_SeqUtil.py b/OpenRTM_aist/CORBA_SeqUtil.py index 3bc5c0de..dacdcc7d 100644 --- a/OpenRTM_aist/CORBA_SeqUtil.py +++ b/OpenRTM_aist/CORBA_SeqUtil.py @@ -1,12 +1,12 @@ #!/usr/bin/env python -# -*- coding: euc-jp -*- +# -*- coding: utf-8 -*- ## # @file CORBA_SeqUtil.py # @brief CORBA sequence utility template functions # @date $Date: 2007/09/03 $ # @author Noriaki Ando and Shinji Kurihara -# +# # Copyright (C) 2006-2008 # Task-intelligence Research Group, # Intelligent Systems Research Institute, @@ -18,276 +18,278 @@ ## # @if jp -# -# @brief CORBA sequence Ф functor ŬѤ -# -# CORBA sequence ƤǤФơͿ줿 functor ŬѤ롣 -# functor void functor(CORBA sequence ) ηȤɬפ롣 -# -# @param seq Functor ŬѤ CORBA sequence -# @param f CORBA sequence Ǥ Functor -# -# @return ƤǤ Functor -# +# +# @brief CORBA sequence に対して functor を適用する +# +# CORBA sequence 全ての要素に対して、与えられた functor を適用する。 +# functor は void functor(CORBA sequence の要素) の形式をとる必要がある。 +# +# @param seq Functor を適用する CORBA sequence +# @param f CORBA sequence の要素を処理する Functor +# +# @return 全ての要素を処理した Functor +# # @since 0.4.0 -# +# # @else -# +# # @brief Apply the functor to all CORBA sequence elements -# +# # Apply the given functor to the given CORBA sequence. # functor should be void functor(CORBA sequence element). -# +# # @param seq CORBA sequence to be applied the functor # @param functor A functor to process CORBA sequence elements -# +# # @return Functor that processed all CORBA sequence elements -# +# # @endif + + def for_each(seq, f): - len_ = len(seq) - for i in range(len_): - f(seq[i]) - return f + for s in seq: + f(s) + return f ## # @if jp -# @brief CORBA sequence 椫 functor Ŭ礹ǤΥǥå֤ -# -# CORBA sequence ƤǤФơͿ줿 functor ŬѤ -# functor true ֤褦Υǥå֤ -# functor bool functor(const CORBA sequence ) ηȤꡢ -# Ŭ礹ǤФ true ֤ɬפ롣 -# -# @param seq Functor ŬѤ CORBA sequence -# @param f CORBA sequence Ǥ򸫤Ĥ Functor -# -# @return Functor Ŭ礹ǤΥǥåĤʤȤ -1 ֤ -# +# @brief CORBA sequence の中から functor に適合する要素のインデックスを返す +# +# CORBA sequence 全ての要素に対して、与えられた functor を適用し、 +# functor が true を返すようそのインデックスを返す。 +# functor は bool functor(const CORBA sequence の要素) の形式をとり、 +# 適合する要素に対して true を返す必要がある。 +# +# @param seq Functor を適用する CORBA sequence +# @param f CORBA sequence から要素を見つける Functor +# +# @return Functor に適合する要素のインデックス。見つからないときは -1 を返す。 +# # @else -# -# @brief Return the index of CORBA sequence element that functor matches -# +# +# @brief Return the index of CORBA sequence element that functor matches +# # This operation applies the given functor to the given CORBA sequence, # and returns the index of the sequence element that the functor matches. # The functor should be bool functor(const CORBA sequence element) type, # and it would return true, if the element matched the functor. -# +# # @param seq CORBA sequence to be applied the functor # @param functor A functor to process CORBA sequence elements -# +# # @return The index of the element that functor matches. # If no element found, it would return -1. -# +# # @endif def find(seq, f): - len_ = len(seq) - for i in range(len_): - if f(seq[i]): - return i - return -1 + len_ = len(seq) + for i,s in enumerate(seq): + if f(s): + return i + return -1 ## # @if jp -# @brief CORBA sequence κǸǤɲä -# -# CORBA sequence κǸͿ줿Ǥɲä롣 -# CORBA sequence ĹϼưŪ˳ĥ롣 -# -# @param seq Ǥɲä CORBA sequence -# @param elem ɲä -# +# @brief CORBA sequence の最後に要素を追加する +# +# CORBA sequence の最後に与えられた要素を追加する。 +# CORBA sequence の長さは自動的に拡張される。 +# +# @param seq 要素を追加する CORBA sequence +# @param elem 追加する要素 +# # @else -# +# # @brief Push the new element back to the CORBA sequence -# +# # Add the given element to the last of CORBA sequence. # The length of the CORBA sequence will be expanded automatically. -# +# # @param seq CORBA sequence to be added a new element # @param elem The new element to be added to the CORBA sequence -# +# # @endif def push_back(seq, elem): - seq.append(elem) + seq.append(elem) ## # @if jp -# @brief CORBA sequence ޡ -# -# Ϳ줿 CORBA sequence ޡ롣 -# -# @param seq1 ޡ CORBA sequence -# @param seq2 ޡ CORBA sequence -# +# @brief CORBA sequence をマージする +# +# 与えられた CORBA sequence をマージする。 +# +# @param seq1 マージされる CORBA sequence +# @param seq2 マージされる CORBA sequence +# # @else -# +# # @endif def push_back_list(seq1, seq2): - for elem in seq2: - seq1.append(elem) + for elem in seq2: + seq1.append(elem) ## # @if jp -# @brief CORBA sequence Ǥ -# -# CORBA sequence index ΰ֤Ǥä롣 -# index Ϳ줿CORBA sequence κ index 礭 -# ǸǤȤƲä롣 -# CORBA sequence ĹϼưŪ˳ĥ롣 -# -# @param seq Ǥɲä CORBA sequence -# @param elem ɲä -# @param index Ǥɲä -# +# @brief CORBA sequence に要素を挿入する +# +# CORBA sequence の index の位置に要素を加える。 +# index が 与えられた CORBA sequence の最大の index より大きい場合 +# 最後の要素として加えられる。 +# CORBA sequence の長さは自動的に拡張される。 +# +# @param seq 要素を追加する CORBA sequence +# @param elem 追加する要素 +# @param index 要素を追加する位置 +# # @else -# +# # @brief Insert the element to the CORBA sequence -# +# # Insert a new element in the given position to the CORBA sequence. # If the given index is greater than the length of the sequence, # the given element is pushed back to the last of the sequence. # The length of the CORBA sequence will be expanded automatically. -# +# # @param seq The CORBA sequence to be inserted a new element # @param elem The new element to be inserted the sequence # @param index The inserting position -# +# # @endif def insert(seq, elem, index): - len_ = len(seq) - if index > len_: - seq.append(elem) - return - seq.insert(index, elem) + len_ = len(seq) + if index > len_: + seq.append(elem) + return + seq.insert(index, elem) ## # @if jp -# @brief CORBA sequence ƬǤ -# -# CORBA sequence ƬǤ롣 -# seq[0] Ʊ -# -# @param seq Ǥ CORBA sequence -# -# @return -# +# @brief CORBA sequence の先頭要素を取得する +# +# CORBA sequence の先頭要素を取得する。 +# seq[0] と同じ。 +# +# @param seq 要素を取得する CORBA sequence +# +# @return 取得した要素 +# # @else -# +# # @brief Get the front element of the CORBA sequence -# +# # This operation returns seq[0]. -# +# # @param seq The CORBA sequence to be get the element -# +# # @endif def front(seq): - return seq[0] + return seq[0] ## # @if jp -# @brief CORBA sequence Ǥ -# -# CORBA sequence Ǥ롣 -# seq[seq.length() - 1] Ʊ -# -# @param seq Ǥ CORBA sequence -# -# @return -# +# @brief CORBA sequence の末尾要素を取得する +# +# CORBA sequence の末尾要素を取得する。 +# seq[seq.length() - 1] と同じ。 +# +# @param seq 要素を取得する CORBA sequence +# +# @return 取得した要素 +# # @else -# +# # @brief Get the last element of the CORBA sequence -# +# # This operation returns seq[seq.length() - 1]. -# +# # @param seq The CORBA sequence to be get the element -# +# # @endif def back(seq): - if len(seq) > 0: - return seq[-1] + if seq: + return seq[-1] ## # @if jp -# @brief CORBA sequence λꤵ줿֤Ǥ -# -# ꤵ줿ǥåǤ롣 -# 줿Ǥϵͤ졢sequence Ĺ1롣 -# -# @param seq Ǥ CORBA sequence -# @param index ǤΥǥå -# +# @brief CORBA sequence の指定された位置の要素を削除する +# +# 指定されたインデックスの要素を削除する。 +# 削除された要素は詰められ、sequence の長さは1減る。 +# +# @param seq 要素を削除する CORBA sequence +# @param index 削除する要素のインデックス +# # @else -# +# # @brief Erase the element of the specified index -# +# # This operation removes the element of the given index. # The other elements are closed up around the hole. -# +# # @param seq The CORBA sequence to be get the element # @param index The index of the element to be removed -# +# # @endif def erase(seq, index): - if index > len(seq): - return + if index > len(seq): + return - del seq[index] + del seq[index] ## # @if jp -# -# @brief 󥹤ǤҸˤäƺ -# -# Υڥ졼ϽҸȤͿ줿ؿ֥Ȥ -# 郎ΤȤΥ󥹤Ǥ롣 -# -# @param seq Ǹоݤ CORBA sequence -# @param f 륷󥹤ꤹѸ -# +# +# @brief シーケンスの要素を述語にしたがって削除する +# +# このオペレーションは述語として与えられた関数オブジェクトの +# 条件が真のとき、そのシーケンスの要素を削除する。 +# +# @param seq 要素検索対象の CORBA sequence +# @param f 削除するシーケンスを決定する術語 +# # @else -# +# # @endif + + def erase_if(seq, f): - index = find(seq, f) - if index < 0: - return - del seq[index] + index = find(seq, f) + if index < 0: + return + del seq[index] ## # @if jp -# @brief CORBA sequence Ǥ -# -# CORBA sequence Ǥ롣 -# seq.length(0) Ʊ -# +# @brief CORBA sequence の全要素を削除 +# +# CORBA sequence の全要素を削除する。 +# seq.length(0) と同じ。 +# # @else -# +# # @brief Erase all the elements of the CORBA sequence -# +# # same as seq.length(0). -# +# # @endif def clear(seq): - del seq[0:] + del seq[0:] -## coil::vstring refToVstring(const CorbaRefSequence& objlist) +# coil::vstring refToVstring(const CorbaRefSequence& objlist) def refToVstring(objlist): - iorlist = [] - orb = OpenRTM_aist.Manager.instance().getORB() - - for obj in objlist: - iorlist.append(orb.object_to_string(obj)) + iorlist = [] + orb = OpenRTM_aist.Manager.instance().getORB() - return iorlist + for obj in objlist: + iorlist.append(orb.object_to_string(obj)) + return iorlist diff --git a/OpenRTM_aist/CPUAffinity.py b/OpenRTM_aist/CPUAffinity.py index a9692fc3..1357838a 100644 --- a/OpenRTM_aist/CPUAffinity.py +++ b/OpenRTM_aist/CPUAffinity.py @@ -1,9 +1,9 @@ #!/usr/bin/env python -# -*- coding: euc-jp -*- +# -*- coding: utf-8 -*- ## # @file CPUAffinity.py -# @brief +# @brief # @date $Date$ # @author Nobuhiko Miyamoto # @@ -15,146 +15,146 @@ ## # @if jp -# @brief CPUֹꥹȤѴ +# @brief CPUの番号リストを変換 # -# @param cpu_num_list CPUֹꥹ -# @return +# @param cpu_num_list CPUの番号リスト +# @return 数値 # # @else -# @brief +# @brief # # @param cpu_num_list -# @return +# @return # # @endif # def listToCUPNUM(cpu_num_list): - cpu_num = 0 - try: - for num in cpu_num_list: - p = 0x01 << (int(num)) - cpu_num += p - except ValueError: - pass - return cpu_num - - + cpu_num = 0 + try: + for num in cpu_num_list: + p = 0x01 << (int(num)) + cpu_num += p + except ValueError: + pass + return cpu_num + + ## # @if jp -# @brief ץCPUե˥ƥ +# @brief プロセスのCPUアフィニティを設定 # -# @param cpu_num_list CPUֹꥹ -# @return TrueԤFalse +# @param cpu_num_list CPUの番号リスト +# @return 成功でTrue、失敗でFalse # # @else -# @brief +# @brief # # @param cpu_num_list -# @return +# @return # # @endif # def setProcessAffinity(cpu_num_list): - cpu_num = listToCUPNUM(cpu_num_list) - if cpu_num == 0: - return False - pid = os.getpid() - - if os.name == "nt": - - PROCESS_QUERY_INFORMATION = 0x0400 - PROCESS_SET_INFORMATION = 0x0200 - - - - flag = PROCESS_QUERY_INFORMATION | PROCESS_SET_INFORMATION - ctypes.windll.kernel32.OpenProcess(flag, 0, pid) - - - result = ctypes.windll.kernel32.SetProcessAffinityMask(ctypes.windll.kernel32.GetCurrentProcess(), cpu_num) - processMask = ctypes.c_long() - systemMask = ctypes.c_long() - result = ctypes.windll.kernel32.GetProcessAffinityMask(ctypes.windll.kernel32.GetCurrentProcess(),ctypes.byref(processMask),ctypes.byref(systemMask)) - - if processMask.value != cpu_num: - return False - else: - return True - - else: - from ctypes.util import find_library - pthread = find_library("pthread") - if pthread is None: - return False - pthread = ctypes.CDLL(pthread) - - mask = ctypes.c_long() - mask.value = cpu_num - result = pthread.sched_setaffinity(pid, ctypes.sizeof(mask), ctypes.byref(mask)) - if result != 0: - return False - mask = ctypes.c_long() - result = pthread.sched_getaffinity(pid, ctypes.sizeof(mask), ctypes.byref(mask)) - if mask.value != cpu_num: - return False + cpu_num = listToCUPNUM(cpu_num_list) + if cpu_num == 0: + return False + pid = os.getpid() + + if os.name == "nt": + + PROCESS_QUERY_INFORMATION = 0x0400 + PROCESS_SET_INFORMATION = 0x0200 + + flag = PROCESS_QUERY_INFORMATION | PROCESS_SET_INFORMATION + ctypes.windll.kernel32.OpenProcess(flag, 0, pid) + + result = ctypes.windll.kernel32.SetProcessAffinityMask( + ctypes.windll.kernel32.GetCurrentProcess(), cpu_num) + processMask = ctypes.c_long() + systemMask = ctypes.c_long() + result = ctypes.windll.kernel32.GetProcessAffinityMask( + ctypes.windll.kernel32.GetCurrentProcess(), + ctypes.byref(processMask), + ctypes.byref(systemMask)) + + if processMask.value != cpu_num: + return False + else: + return True + else: - return True + from ctypes.util import find_library + pthread = find_library("pthread") + if pthread is None: + return False + pthread = ctypes.CDLL(pthread) + + mask = ctypes.c_long() + mask.value = cpu_num + result = pthread.sched_setaffinity( + pid, ctypes.sizeof(mask), ctypes.byref(mask)) + if result != 0: + return False + mask = ctypes.c_long() + result = pthread.sched_getaffinity( + pid, ctypes.sizeof(mask), ctypes.byref(mask)) + if mask.value != cpu_num: + return False + else: + return True ## # @if jp -# @brief åɤCPUե˥ƥ +# @brief スレッドのCPUアフィニティを設定 # -# @param cpu_num_list CPUֹꥹ -# @return TrueԤFalse +# @param cpu_num_list CPUの番号リスト +# @return 成功でTrue、失敗でFalse # # @else -# @brief +# @brief # # @param cpu_num_list -# @return +# @return # # @endif # def setThreadAffinity(cpu_num_list): - cpu_num = listToCUPNUM(cpu_num_list) - if cpu_num == 0: - return False - - - if os.name == "nt": - - - - h = ctypes.windll.kernel32.GetCurrentThread() - - result = ctypes.windll.kernel32.SetThreadAffinityMask(h, cpu_num) - - - if result != cpu_num: - return False - - return True - - else: - from ctypes.util import find_library - pthread = find_library("pthread") - if pthread is None: - return False - pthread = ctypes.CDLL(pthread) - libc = find_library("libc") - libc = ctypes.CDLL(libc) - - mask = ctypes.c_long() - mask.value = cpu_num - tid = libc.syscall(186) - result = pthread.sched_setaffinity(tid, ctypes.sizeof(mask), ctypes.byref(mask)) - if result != 0: - return False - mask = ctypes.c_long() - result = pthread.sched_getaffinity(tid, ctypes.sizeof(mask), ctypes.byref(mask)) - if mask.value != cpu_num: - return False + cpu_num = listToCUPNUM(cpu_num_list) + if cpu_num == 0: + return False + + if os.name == "nt": + + h = ctypes.windll.kernel32.GetCurrentThread() + + result = ctypes.windll.kernel32.SetThreadAffinityMask(h, cpu_num) + + if result != cpu_num: + return False + + return True + else: - return True + from ctypes.util import find_library + pthread = find_library("pthread") + if pthread is None: + return False + pthread = ctypes.CDLL(pthread) + libc = find_library("libc") + libc = ctypes.CDLL(libc) + mask = ctypes.c_long() + mask.value = cpu_num + tid = libc.syscall(186) + result = pthread.sched_setaffinity( + tid, ctypes.sizeof(mask), ctypes.byref(mask)) + if result != 0: + return False + mask = ctypes.c_long() + result = pthread.sched_getaffinity( + tid, ctypes.sizeof(mask), ctypes.byref(mask)) + if mask.value != cpu_num: + return False + else: + return True diff --git a/OpenRTM_aist/CSPEventPort.py b/OpenRTM_aist/CSPEventPort.py new file mode 100644 index 00000000..7cbf6740 --- /dev/null +++ b/OpenRTM_aist/CSPEventPort.py @@ -0,0 +1,1439 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- + +## +# @file CSPEventPort.py +# @brief CSPEventPort template class +# @date $Date: $ +# @author Nobuhiko Miyamoto +# +# Copyright (C) 2019 +# Intelligent Systems Research Institute, +# National Institute of +# Advanced Industrial Science and Technology (AIST), Japan +# All rights reserved. + +import OpenRTM_aist +import OpenRTM_aist.EventPort +import copy +import threading + + +## +# @if jp +# +# @class CSPEventPort +# +# @brief CSPEventPort テンプレートクラス +# +# +# @since 2.0.0 +# +# @else +# +# @class CSPEventPort +# +# @brief CSPEventPort template class +# +# +# @since 2.0.0 +# +# @endif +# +class CSPEventPort(OpenRTM_aist.InPortBase): + SUCCESSFUL_GET_DATA = 0 + FAILED_DESERIALIZE = 1 + FAILED_TIMEOUT = 2 + FAILED_EMPTY = 3 + FAILED_GET_DATA = 4 + ## + # @if jp + # + # @brief コンストラクタ + # + # コンストラクタ。 + # パラメータとして与えられる T 型の変数にバインドされる。 + # + # @param self + # @param name EventInPort 名。EventInPortBase:name() により参照される。 + # @param fsm FSM + # + # @else + # + # @brief A constructor. + # + # constructor. + # This is bound to type-T variable given as a parameter. + # + # @param self + # @param name A name of the EventInPort. This name is referred by + # EventInPortBase::name(). + # @param value type-T variable that is bound to this EventInPort. + # @param fsm + # + # @endif + # + + def __init__(self, name, fsm=None, manager=None): + super(CSPEventPort, self).__init__(name, "any") + self._ctrl = CSPEventPort.WorkerThreadCtrl() + self._name = name + self._value = None + + self._OnRead = None + + self._singlebuffer = True + self._eventbuffer = None + + self._channeltimeout = 10 + self._bufferzeromode = False + self._fsm = fsm + + self._manager = manager + if manager: + self._manager.addInPort(self) + self._writingConnector = None + self._syncmode = False + + ## + # @if jp + # + # @brief デストラクタ + # + # デストラクタ。 + # + # @param self + # + # @else + # + # @brief Destructor + # + # Destructor + # + # @param self + # + # @endif + # + + def __del__(self): + super(CSPEventPort, self).__del__() + + ## + # @if jp + # + # @brief ポート名称を取得する。 + # + # ポート名称を取得する。 + # + # @param self + # @return ポート名称 + # + # @else + # + # @brief Get port name + # + # Get port name. + # + # @param self + # @return The port name + # + # @endif + # + + def name(self): + return self._name + + ## + # @if jp + # + # @brief 引数なしのイベントハンドラを登録する + # + # @param self + # @param name イベント名 + # @param handler イベントハンドラ + # コネクタ接続時にfsm_event_nameという要素を設定する。 + # fsm_event_nameとイベント名が一致するとイベントが実行される。 + # イベントハンドラにはMacho等で定義したイベントを入力する + # + # + # @else + # + # @param self + # @param name + # @param handler + # + # @endif + # + + def bindEvent0(self, name, handler): + self.addConnectorDataListener(OpenRTM_aist.ConnectorDataListenerType.ON_RECEIVED, + OpenRTM_aist.EventPort.EventBinder0(self._fsm, name, handler, self._eventbuffer)) + + ## + # @if jp + # + # @brief 引数ありのイベントハンドラを登録する + # + # @param self + # @param name イベント名 + # @param handler イベントハンドラ + # @param data_type 入力データ + # + # @else + # + # @brief + # + # @param self + # @param name + # @param handler + # @param data_type + # + # @endif + # + def bindEvent1(self, name, handler, data_type): + self.addConnectorDataListener(OpenRTM_aist.ConnectorDataListenerType.ON_RECEIVED, + OpenRTM_aist.EventPort.EventBinder1(self._fsm, name, handler, data_type, self._eventbuffer)) + + ## + # @if jp + # + # @brief 初期化関数 + # + # @param self + # @param prop コネクタのプロパティ + # buffer(dataport.buffer)要素でバッファ長さ等を設定 + # channel_timeout(dataport.channel_timeout)要素で、 + # 送信可能なアウトポートが存在しない場合のブロックのタイムアウトを設定 + # + # @return ポート名称 + # + # @else + # + # @brief Get port name + # + # @param self + # @param prop + # + # @endif + # + def init(self, prop): + super(CSPEventPort, self).init(prop) + + num = 10 + ret, num = OpenRTM_aist.stringTo( + num, self._properties.getProperty( + "channel_timeout", "10")) + if ret: + self._channeltimeout = num + + buff_prop = prop.getNode("buffer") + length = 8 + _, length = OpenRTM_aist.stringTo( + length, buff_prop.getProperty("length", "8")) + + if length == 0: + buff_prop.setProperty("length", "1") + self._bufferzeromode = True + + self._eventbuffer = OpenRTM_aist.CdrBufferFactory.instance().createObject("ring_buffer") + if self._eventbuffer is None: + self._rtcout.RTC_ERROR("default buffer creation failed") + self._eventbuffer.init(buff_prop) + + self._syncmode = OpenRTM_aist.toBool( + prop.getProperty("csp.sync_wait"), "YES", "NO", False) + + if not self._bufferzeromode: + self._writable_listener = CSPEventPort.IsWritableListener( + self._eventbuffer, self._ctrl, self._channeltimeout, self, self._manager) + self._write_listener = CSPEventPort.WriteListener(self._ctrl) + else: + self._writable_listener = CSPEventPort.IsWritableZeroModeListener( + self._ctrl, self._channeltimeout, self, self._manager) + self._write_listener = CSPEventPort.WriteZeroModeListener( + self._ctrl) + + ## + # @if jp + # + # @brief CSPManagerの設定 + # + # @param self + # @param manager CSPManager + # + # @else + # + # @brief + # + # @param self + # @param manager + # + # @endif + # + def setManager(self, manager): + self._writable_listener.setManager(manager) + self._manager = manager + if manager: + self._manager.addInPort(self) + + ## + # @if jp + # + # @brief CSPManagerの設定解除 + # + # @param self + # + # @else + # + # @brief + # + # @param self + # + # @endif + # + def releaseManager(self): + self._writable_listener.releaseManager() + self._manager = None + + ## + # @if jp + # + # @brief 書き込み処理を開始したコネクタを登録 + # + # @param self + # @param con InPortConnector + # + # + # @else + # + # @brief + # + # @param self + # @param con + # + # @endif + # + + def setWritingConnector(self, con): + self._writingConnector = con + + ## + # @if jp + # + # @brief 接続先のOutPortに入力可能であることを通知 + # バッファがフルになる、もしくは待機中のOutPortがなくなるまで、接続先のコネクタのデータを読み込む + # バッファからデータを読み込んだ場合は、この関数を呼び出す必要がある + # + # @param self + # + # + # @else + # + # @brief + # + # @param self + # + # @endif + # + def notify(self): + for con in self._connectors: + guard_ctrl = None + if not self._syncmode: + guard_ctrl = OpenRTM_aist.ScopedLock(self._ctrl._cond) + if self._ctrl._writing: + self._ctrl._cond.wait(self._channeltimeout) + if not self._eventbuffer.full(): + if con.isReadable(False): + ret, _ = con.readBuff() + if ret == OpenRTM_aist.DataPortStatus.PORT_OK: + pass + else: + self._rtcout.RTC_ERROR( + "read error:%s", (OpenRTM_aist.DataPortStatus.toString(ret))) + + ## + # @if jp + # + # @brief コネクタ接続関数 + # InPortBaseの接続処理のほかに、コネクタに書き込み確認時、書き込み時のコールバック関数を設定する + # + # @param self + # @param connector_profile コネクタプロファイル + # @return ret, prof + # ret:リターンコード + # prof:コネクタプロファイル + # + # @return ポート名称 + # + # @else + # + # @brief Get port name + # + # @param self + # @param connector_profile + # @return ret, prof + # + # @endif + # + def notify_connect(self, connector_profile): + ret, prof = super(CSPEventPort, self).notify_connect(connector_profile) + guard_con = OpenRTM_aist.ScopedLock(self._connector_mutex) + for con in self._connectors: + con.setIsWritableListener(self._writable_listener) + con.setWriteListener(self._write_listener) + return (ret, prof) + + ## + # @if jp + # + # @brief リングバッファ使用モード時に指定コネクタの読み込み確認、データの読み込みを行う + # + # @param self + # @param con コネクタ + # @param retry True:再検索、False:通常の書き込み確認 + # @return ret, data + # ret:SUCCESSFUL_GET_DATA:データ取得成功、FAILED_DESERIALIZE:復号失敗、FAILED_TIMEOUT:タイムアウトにより失敗、FAILED_EMPTY:空のデータを取得、FAILED_GET_DATA:データの読み込み可能なコネクタが存在しない + # prof:読み込んだデータ + # + # @return ポート名称 + # + # @else + # + # @brief + # + # @param self + # @param con + # @param retry + # @return ret, data + # + # @endif + # + def getDataBufferMode(self, con, retry): + guard_ctrl = None + if not self._syncmode: + guard_ctrl = OpenRTM_aist.ScopedLock(self._ctrl._cond) + + if not self._eventbuffer.empty(): + _, value = self._eventbuffer.read() + if guard_ctrl is not None: + del guard_ctrl + self.notify() + return CSPEventPort.SUCCESSFUL_GET_DATA, value + elif self._ctrl._writing: + self._ctrl._cond.wait(self._channeltimeout) + if not self._eventbuffer.empty(): + _, value = self._eventbuffer.read() + if guard_ctrl is not None: + del guard_ctrl + self.notify() + return CSPEventPort.SUCCESSFUL_GET_DATA, value + else: + self._rtcout.RTC_ERROR("read timeout") + return CSPEventPort.FAILED_TIMEOUT, None + else: + readable = con.isReadable(retry) + if readable: + ret, _ = con.readBuff() + _, value = self._eventbuffer.read() + if ret == OpenRTM_aist.DataPortStatus.PORT_OK: + return CSPEventPort.SUCCESSFUL_GET_DATA, value + else: + self._rtcout.RTC_ERROR( + "read error:%s", (OpenRTM_aist.DataPortStatus.toString(ret))) + return CSPEventPort.FAILED_DESERIALIZE, None + return CSPEventPort.FAILED_GET_DATA, None + ## + # @if jp + # + # @brief リングバッファ使用モード時のデータ読み込み処理 + # バッファがemptyではない場合はバッファから読み込む + # コネクタの中に読み込み可能なものがある場合は、そのコネクタから読み込む + # ただし、書き込み中の場合は書き込み終了までブロックする + # + # @param self + # @param connector_profile コネクタプロファイル + # @return ret, prof + # ret:True:読み込み成功、False:バッファがemptyでかつ読み込み可能なコネクタが存在しない + # data:データ + # + # + # @else + # + # @brief + # + # @param self + # @return ret, data + # + # @endif + # + + def dataPullBufferMode(self): + guard_ctrl = None + if not self._syncmode: + guard_ctrl = OpenRTM_aist.ScopedLock(self._ctrl._cond) + + self._ctrl._connectors = [] + self._ctrl._searched_connectors = [] + + del guard_ctrl + + guard_con = OpenRTM_aist.ScopedLock(self._connector_mutex) + if not self._connectors: + self._rtcout.RTC_DEBUG("no connectors") + return False, None + + if self._eventbuffer.empty(): + for con in self._connectors: + ret, value = self.getDataBufferMode(con, False) + if ret == CSPEventPort.SUCCESSFUL_GET_DATA: + self._ctrl._searched_connectors = [] + return True, value + elif ret != CSPEventPort.FAILED_GET_DATA: + return False, value + else: + self._ctrl._searched_connectors.append(con) + + else: + if not self._syncmode: + guard_ctrl = OpenRTM_aist.ScopedLock(self._ctrl._cond) + if not self._eventbuffer.empty(): + _, value = self._eventbuffer.read() + del guard_ctrl + self.notify() + return True, value + else: + self._rtcout.RTC_ERROR( + "read error:%s", + (OpenRTM_aist.BufferStatus.toString(ret))) + del guard_ctrl + self.notify() + return False, None + return False, None + + ## + # @if jp + # + # @brief リングバッファ使用モード時にデータの再受信を行う + # データの送受信時は片方がコネクタ選択時にスレッドをロックするロックモード、 + # もう片方がスレッドをロックしない非ロックモードに設定する必要がある。 + # 非ロックモードの場合はデータ選択時にis_writable、is_readable関数が呼ばれた場合、 + # 再検索するコネクタのリストに追加して後で再検索する。 + # + # @param self + # @return ret, data + # ret:True:読み込み成功、False:バッファがemptyでかつ読み込み可能なコネクタが存在しない + # data:データ + # + # + # @else + # + # @brief + # + # @param self + # @return ret, data + # + # @endif + # + def dataPullBufferModeRetry(self): + if self._thebuffer.empty(): + cons = self._ctrl._connectors[:] + for con in cons: + ret, value = self.getDataBufferMode(con, True) + if ret == CSPEventPort.SUCCESSFUL_GET_DATA: + self._ctrl._connectors = [] + self._ctrl._searched_connectors = [] + return True, value + elif ret != CSPEventPort.FAILED_GET_DATA: + return False, value + self._ctrl._connectors = [] + self._ctrl._searched_connectors = [] + + else: + if not self._syncmode: + guard_ctrl = OpenRTM_aist.ScopedLock(self._ctrl._cond) + if not self._eventbuffer.empty(): + _, value = self._eventbuffer.read() + del guard_ctrl + self.notify() + return True, value + else: + self._rtcout.RTC_ERROR( + "read error:%s", + (OpenRTM_aist.BufferStatus.toString(ret))) + del guard_ctrl + self.notify() + return False, None + return False, None + + ## + # @if jp + # + # @brief 非リングバッファ使用モード時に指定コネクタの読み込み確認、データの読み込みを行う + # + # @param self + # @param con コネクタ + # @param retry True:再検索、False:通常の書き込み確認 + # @return ret, data + # ret:SUCCESSFUL_GET_DATA:データ取得成功、FAILED_DESERIALIZE:復号失敗、FAILED_GET_DATA:データの読み込み可能なコネクタが存在しない + # prof:読み込んだデータ + # + # + # @else + # + # @brief + # + # @param self + # @param con + # @param retry + # @return ret, data + # + # @endif + # + def getDataZeroMode(self, con, retry): + ret = con.isReadable(retry) + if ret: + guard_ctrl = None + if not self._syncmode: + guard_ctrl = OpenRTM_aist.ScopedLock(self._ctrl._cond) + ret, _ = con.readBuff() + _, value = self._eventbuffer.read() + if ret == OpenRTM_aist.DataPortStatus.PORT_OK: + return CSPEventPort.SUCCESSFUL_GET_DATA, value + else: + self._rtcout.RTC_ERROR( + "read error:%s", (OpenRTM_aist.DataPortStatus.toString(ret))) + return CSPEventPort.FAILED_DESERIALIZE, None + return CSPEventPort.FAILED_GET_DATA, None + + ## + # @if jp + # + # @brief 非リングバッファ使用モード時のデータ読み込み処理 + # データ読み込み可能なコネクタが存在する場合は、そのコネクタからデータを読み込む + # + # + # @param self + # @param connector_profile コネクタプロファイル + # @return ret, data + # ret:True:読み込み成功、False:データ読み込み可能なコネクタが存在しない + # data:データ(読み込み失敗の場合はNone) + # + # + # @else + # + # @brief + # + # @param self + # @return ret, data + # + # @endif + # + def dataPullZeroMode(self): + + guard_con = OpenRTM_aist.ScopedLock(self._connector_mutex) + for con in self._connectors: + ret, value = self.getDataZeroMode(con, False) + + if ret == CSPEventPort.SUCCESSFUL_GET_DATA: + self._ctrl._searched_connectors = [] + return True, value + elif ret != CSPEventPort.FAILED_GET_DATA: + return False, value + else: + self._ctrl._searched_connectors.append(con) + + self._ctrl._connectors = [] + self._ctrl._searched_connectors = [] + + return False, None + + ## + # @if jp + # + # @brief 非リングバッファ使用モード時にデータの再受信を行う + # + # @param self + # @return ret, data + # ret:True:読み込み成功、False:バッファがemptyでかつ読み込み可能なコネクタが存在しない + # data:データ + # + # + # @else + # + # @brief + # + # @param self + # @return ret, data + # + # @endif + # + def dataPullZeroModeRetry(self): + cons = self._ctrl._connectors[:] + self._rtcout.RTC_TRACE("reselect %d connectors", (len(cons))) + for con in cons: + ret, value = self.getDataZeroMode(con, True) + if ret == CSPEventPort.SUCCESSFUL_GET_DATA: + self._ctrl._connectors = [] + self._ctrl._searched_connectors = [] + return True, value + elif ret != CSPEventPort.FAILED_GET_DATA: + return False, value + self._ctrl._connectors = [] + self._ctrl._searched_connectors = [] + return False, None + + ## + # @if jp + # + # @brief データ読み込み可能なコネクタを選択し、 + # self._valueに読み込んだデータを格納する + # + # + # @param self + # @return True:読み込み成功、False:読み込み不可 + # + # + # @else + # + # @brief + # + # @param self + # @return + # + # @endif + # + def select(self): + self._rtcout.RTC_TRACE("select()") + guard = OpenRTM_aist.ScopedLock(self._ctrl._cond) + + self._ctrl._connectors = [] + self._ctrl._searched_connectors = [] + + if not self._syncmode: + del guard + guard = None + + if not self._bufferzeromode: + ret, value = self.dataPullBufferMode() + else: + ret, value = self.dataPullZeroMode() + + if not self._syncmode: + guard = OpenRTM_aist.ScopedLock(self._ctrl._cond) + if ret: + self._value = value + return ret + + ## + # @if jp + # + # @brief 再検索リストのコネクタからデータ読み込み可能なコネクタを選択し、 + # self._valueに読み込んだデータを格納する + # + # + # @param self + # @return True:読み込み成功、False:読み込み不可 + # + # + # @else + # + # @brief + # + # @param self + # @return + # + # @endif + # + def reselect(self): + self._rtcout.RTC_TRACE("reselect()") + guard = None + if self._syncmode: + guard = OpenRTM_aist.ScopedLock(self._ctrl._cond) + + if not self._bufferzeromode: + ret, value = self.dataPullBufferModeRetry() + else: + ret, value = self.dataPullZeroModeRetry() + + if not self._syncmode: + guard = OpenRTM_aist.ScopedLock(self._ctrl._cond) + if ret: + self._value = value + return ret + + ## + # @if jp + # + # @brief ロックモード、非ロックモードの設定 + # データの送受信時は片方がコネクタ選択時にスレッドをロックするロックモード、 + # もう片方がスレッドをロックしない非ロックモードに設定する必要がある。 + # 非ロックモードの場合はデータ選択時にis_writable、is_readable関数が呼ばれた場合、 + # 再検索するコネクタのリストに追加して後で再検索する。 + # + # + # @param self + # @param mode True:ロックモード、False:非ロックモード + # + # + # @else + # + # @brief + # + # @param self + # @param mode + # + # @endif + # + def setSyncMode(self, mode): + self._syncmode = mode + + ## + # @if jp + # + # @brief ロックモード、非ロックモードの取得 + # + # + # @param self + # @return True:ロックモード、False:非ロックモード + # + # + # @else + # + # @brief + # + # @param self + # @return + # + # @endif + # + def getSyncMode(self): + return self._syncmode + + ## + # @if jp + # + # @brief select関数で格納したデータの取得 + # + # + # @param self + # @return データ + # + # + # @else + # + # @brief + # + # @param self + # @return + # + # @endif + # + def readData(self): + guard = OpenRTM_aist.ScopedLock(self._ctrl._cond) + self._rtcout.RTC_TRACE("readData()") + if self._OnRead is not None: + self._OnRead() + self._rtcout.RTC_TRACE("OnRead called") + + if self._ctrl._writing: + self._ctrl._cond.wait(self._channeltimeout) + + if not self._eventbuffer.empty(): + _, value = self._eventbuffer.read() + return value + + return self._value + + ## + # @if jp + # + # @brief データを読み込み可能なコネクタを選択しデータを取得する + # 読み込み可能なコネクタが存在しない場合は待機する + # + # + # @param self + # @return データ(タイムアウトした場合はNone) + # + # + # @else + # + # @brief + # + # @param self + # @return + # + # @endif + # + def read(self): + self._rtcout.RTC_TRACE("DataType read()") + if self._OnRead is not None: + self._OnRead() + self._rtcout.RTC_TRACE("OnRead called") + + if not self._connectors: + self._rtcout.RTC_DEBUG("no connectors") + return None + + if not self._bufferzeromode: + return self.readBufferMode() + else: + return self.readZeroMode() + + ## + # @if jp + # + # @brief リングバッファ使用モード時のデータ読み込み処理 + # 読み込み可能なコネクタが存在しない場合は待機する + # + # + # @param self + # @return データ(タイムアウトした場合はNone) + # + # + # @else + # + # @brief + # + # @param self + # @return + # + # @endif + # + + def readBufferMode(self): + guard = OpenRTM_aist.ScopedLock(self._ctrl._cond) + self._ctrl._connectors = [] + self._ctrl._searched_connectors = [] + if not self._syncmode: + del guard + guard = None + + ret, data = self.dataPullBufferMode() + if ret: + return data + else: + if not self._syncmode: + guard = OpenRTM_aist.ScopedLock(self._ctrl._cond) + ret, data = self.dataPullBufferModeRetry() + if ret: + return data + if self._ctrl._writing or self._eventbuffer.empty(): + self._ctrl._cond.wait(self._channeltimeout) + if not self._eventbuffer.empty(): + _, value = self._eventbuffer.read() + + return value + else: + self._rtcout.RTC_ERROR("read timeout") + return None + + ## + # @if jp + # + # @brief 非リングバッファ使用モード時のデータ読み込み処理 + # 読み込み可能なコネクタが存在しない場合は待機する + # + # + # @param self + # @return データ(タイムアウトした場合はNone) + # + # + # @else + # + # @brief + # + # @param self + # @return + # + # @endif + # + def readZeroMode(self): + guard = OpenRTM_aist.ScopedLock(self._ctrl._cond) + self._ctrl._connectors = [] + self._ctrl._searched_connectors = [] + if not self._syncmode: + del guard + guard = None + + ret, data = self.dataPullZeroMode() + if ret: + return data + else: + if not self._syncmode: + guard = OpenRTM_aist.ScopedLock(self._ctrl._cond) + ret, data = self.dataPullZeroModeRetry() + if ret: + return data + self._ctrl._waiting = True + self._ctrl._cond.wait(self._channeltimeout) + self._ctrl._waiting = False + if not self._eventbuffer.empty(): + _, value = self._eventbuffer.read() + return value + else: + self._rtcout.RTC_ERROR("read timeout") + return None + + def setOnRead(self, on_read): + self._OnRead = on_read + + ## + # @if jp + # + # @class IsWritableListener + # + # @brief データ書き込み時の確認リスナ基底クラス(リングバッファ使用モード) + # + # + # @since 2.0.0 + # + # @else + # + # @class IsWritableListener + # + # @brief + # + # + # @since 2.0.0 + # + # @endif + # + + class IsWritableListener(OpenRTM_aist.IsWritableListenerBase): + ## + # @if jp + # + # @brief コンストラクタ + # + # + # @param self + # @param buff リングバッファ + # @param control WorkerThreadCtrlオブジェクト + # @param timeout 書き込み待機のタイムアウト + # @param manager CSPチャネル管理マネージャ + # managerを指定した場合は、managerが待機中の場合にロック解除の通知を行う + # + # + # + # @else + # + # @brief + # + # @param self + # @param buff + # @param control + # @param timeout + # @param manager + # + # @endif + # + def __init__(self, buff, control, timeout, port, manager=None): + self._ctrl = control + self._buffer = buff + self._channeltimeout = timeout + self._manager = manager + self._port = port + self._mutex = threading.RLock() + ## + # @if jp + # + # @brief 書き込み確認時のコールバック関数 + # 他のコネクタがデータ書き込み中の場合は完了まで待機する + # バッファがフルではない場合は書き込み状態に移行する + # このため、書き込み可能な場合は必ずデータを書き込む必要がある + # + # + # @param self + # @param con InPortConnector + # @param retry True:再検索、False:通常の書き込み確認 + # @return True:書き込み可能、False:書き込み不可 + # + # + # + # @else + # + # @brief + # + # @param self + # @param con + # @param retry + # @return + # + # @endif + # + + def __call__(self, con, retry=False): + guard_manager = OpenRTM_aist.Guard.ScopedLock(self._mutex) + + if retry: + if con not in self._ctrl._searched_connectors: + return False + + if self._manager: + if self._manager.notify(inport=self._port): + return True + del guard_manager + guard = OpenRTM_aist.ScopedLock(self._ctrl._cond) + if self._ctrl._writing: + self._ctrl._cond.wait(self._channeltimeout) + if not self._buffer.full(): + self._ctrl._writing = True + return True + else: + self._ctrl._writing = False + self._ctrl._connectors.append(con) + return False + + ## + # @if jp + # + # @brief CSPManagerの設定 + # + # @param self + # @param manager CSPManager + # + # + # + # @else + # + # @brief + # + # @param self + # @param manager + # + # @endif + # + def setManager(self, manager): + guard_manager = OpenRTM_aist.Guard.ScopedLock(self._mutex) + self._manager = manager + + ## + # @if jp + # + # @brief CSPManagerの解除 + # + # @param self + # + # + # + # @else + # + # @brief + # + # @param self + # + # @endif + # + def releaseManager(self): + guard_manager = OpenRTM_aist.Guard.ScopedLock(self._mutex) + self._manager = None + + ## + # @if jp + # + # @class WriteListener + # + # @brief データ書き込み時のリスナ基底クラス(リングバッファ使用モード) + # + # + # @since 2.0.0 + # + # @else + # + # @class WriteListener + # + # @brief + # + # + # @since 2.0.0 + # + # @endif + # + class WriteListener(OpenRTM_aist.WriteListenerBase): + ## + # @if jp + # + # @brief コンストラクタ + # + # + # @param self + # @param control WorkerThreadCtrlオブジェクト + # + # + # + # @else + # + # @brief + # + # @param self + # @param control + # + # @endif + # + def __init__(self, control): + self._ctrl = control + ## + # @if jp + # + # @brief 書き込み時のコールバック関数 + # CSPEventPortではバッファへの書き込みはON_RECEIVEDコールバックで実行するため、 + # 書き込み状態の解除のみを行う。 + # + # + # @param self + # @param data データ + # @return リターンコード + # BUFFER_OK:正常完了 + # + # + # + # @else + # + # @brief + # + # @param self + # @param data + # @return + # + # @endif + # + + def __call__(self, data): + guard = OpenRTM_aist.ScopedLock(self._ctrl._cond) + self._ctrl._writing = False + self._ctrl._cond.notify() + return OpenRTM_aist.BufferStatus.BUFFER_OK + + ## + # @if jp + # + # @class IsWritableZeroModeListener + # + # @brief データ書き込み確認リスナ基底クラス(非リングバッファ使用モード) + # + # + # @since 2.0.0 + # + # @else + # + # @class IsWritableZeroModeListener + # + # @brief + # + # + # @since 2.0.0 + # + # @endif + # + class IsWritableZeroModeListener(OpenRTM_aist.IsWritableListenerBase): + ## + # @if jp + # + # @brief コンストラクタ + # + # + # @param self + # @param buff リングバッファ + # @param control WorkerThreadCtrlオブジェクト + # @param timeout 書き込み待機のタイムアウト + # @param manager CSPチャネル管理マネージャ + # managerを指定した場合は、managerが待機中の場合にロック解除の通知を行う + # + # + # + # @else + # + # @brief + # + # @param self + # @param buff + # @param control + # @param timeout + # @param manager + # + # @endif + # + def __init__(self, control, timeout, port, manager=None): + self._ctrl = control + self._channeltimeout = timeout + self._manager = manager + self._port = port + self._mutex = threading.RLock() + ## + # @if jp + # + # @brief 書き込み確認時のコールバック関数 + # 他のコネクタがデータ書き込み中の場合は完了まで待機する + # バッファがフルではない場合は書き込み状態に移行する + # このため、書き込み可能な場合は必ずデータを書き込む必要がある + # + # + # @param self + # @param con InPortConnector + # @param retry True:再検索、False:通常の書き込み確認 + # @return True:書き込み可能、False:書き込み不可 + # + # + # + # @else + # + # @brief + # + # @param self + # @param con + # @param retry + # @return + # + # @endif + # + + def __call__(self, con, retry=False): + guard_manager = OpenRTM_aist.Guard.ScopedLock(self._mutex) + + if retry: + if con not in self._ctrl._searched_connectors: + return False + + if self._manager: + if self._manager.notify(inport=self._port): + return True + del guard_manager + guard = OpenRTM_aist.ScopedLock(self._ctrl._cond) + if self._ctrl._waiting and self._ctrl._writing: + self._ctrl._cond.wait(self._channeltimeout) + if self._ctrl._waiting: + self._ctrl._writing = True + return True + else: + self._ctrl._writing = False + self._ctrl._connectors.append(con) + return False + + ## + # @if jp + # + # @brief CSPManagerの設定 + # + # @param self + # @param manager CSPManager + # + # + # + # @else + # + # @brief + # + # @param self + # @param manager + # + # @endif + # + def setManager(self, manager): + guard_manager = OpenRTM_aist.Guard.ScopedLock(self._mutex) + self._manager = manager + + ## + # @if jp + # + # @brief CSPManagerの解除 + # + # @param self + # + # + # + # @else + # + # @brief + # + # @param self + # + # @endif + # + def releaseManager(self): + guard_manager = OpenRTM_aist.Guard.ScopedLock(self._mutex) + self._manager = None + + ## + # @if jp + # + # @class WriteZeroModeListener + # + # @brief データ書き込み時のリスナ基底クラス(非リングバッファ使用モード) + # + # + # @since 2.0.0 + # + # @else + # + # @class WriteZeroModeListener + # + # @brief + # + # + # @since 2.0.0 + # + # @endif + # + class WriteZeroModeListener(OpenRTM_aist.WriteListenerBase): + ## + # @if jp + # + # @brief コンストラクタ + # + # + # @param self + # @param control WorkerThreadCtrlオブジェクト + # + # + # + # @else + # + # @brief + # + # @param self + # @param control + # + # @endif + # + def __init__(self, control): + self._ctrl = control + ## + # @if jp + # + # @brief 書き込み時のコールバック関数 + # CSPEventPortではバッファへの書き込みはON_RECEIVEDコールバックで実行するため、 + # 書き込み状態の解除のみを行う。 + # + # + # @param self + # @param data データ + # @return リターンコード + # BUFFER_OK:正常完了 + # + # + # + # @else + # + # @brief + # + # @param self + # @param data + # @return + # + # @endif + # + + def __call__(self, data): + guard = OpenRTM_aist.ScopedLock(self._ctrl._cond) + self._ctrl._writing = False + self._ctrl._cond.notify() + return OpenRTM_aist.BufferStatus.BUFFER_OK + + class WorkerThreadCtrl: + def __init__(self): + self._mutex = threading.RLock() + self._cond = threading.Condition(self._mutex) + self._writing = False + self._waiting = False + self._connectors = [] + self._searched_connectors = [] diff --git a/OpenRTM_aist/CSPInPort.py b/OpenRTM_aist/CSPInPort.py new file mode 100644 index 00000000..8a988c94 --- /dev/null +++ b/OpenRTM_aist/CSPInPort.py @@ -0,0 +1,1402 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- + +## +# @file CSPInPort.py +# @brief CSPInPort template class +# @date $Date: $ +# @author Nobuhiko Miyamoto +# +# Copyright (C) 2019 +# Intelligent Systems Research Institute, +# National Institute of +# Advanced Industrial Science and Technology (AIST), Japan +# All rights reserved. + +import OpenRTM_aist +import copy +import threading + + +## +# @if jp +# +# @class CSPInPort +# +# @brief CSPInPort テンプレートクラス +# +# +# @since 2.0.0 +# +# @else +# +# @class CSPInPort +# +# @brief CSPInPort template class +# +# +# @since 2.0.0 +# +# @endif +# +class CSPInPort(OpenRTM_aist.InPortBase): + SUCCESSFUL_GET_DATA = 0 + FAILED_DESERIALIZE = 1 + FAILED_TIMEOUT = 2 + FAILED_EMPTY = 3 + FAILED_GET_DATA = 4 + + ## + # @if jp + # + # @brief コンストラクタ + # + # コンストラクタ。 + # パラメータとして与えられる T 型の変数にバインドされる。 + # + # @param name EventInPort 名。EventInPortBase:name() により参照される。 + # @param value この EventInPort にバインドされる T 型の変数 + # + # @else + # + # @brief A constructor. + # + # constructor. + # This is bound to type-T variable given as a parameter. + # + # @param name A name of the EventInPort. This name is referred by + # EventInPortBase::name(). + # @param value type-T variable that is bound to this EventInPort. + # @param bufsize Buffer length of internal ring buffer of EventInPort + # (The default value:64) + # + # @endif + # + def __init__(self, name, value, manager=None): + super(CSPInPort, self).__init__(name, "any") + self._ctrl = OpenRTM_aist.CSPInPort.WorkerThreadCtrl() + self._name = name + self._value = value + + self._OnRead = None + self._OnReadConvert = None + + self._singlebuffer = True + + self._channeltimeout = 10 + self._bufferzeromode = False + self._manager = manager + if manager: + manager.addInPort(self) + self._writingConnector = None + self._syncmode = False + + ## + # @if jp + # + # @brief デストラクタ + # + # デストラクタ。 + # + # @else + # + # @brief Destructor + # + # Destructor + # + # @endif + # + + def __del__(self): + super(CSPInPort, self).__del__() + + ## + # @if jp + # + # @brief ポート名称を取得する。 + # + # ポート名称を取得する。 + # + # @param self + # @return ポート名称 + # + # @else + # + # @brief Get port name + # + # Get port name. + # + # @param self + # @return The port name + # + # @endif + # + def name(self): + return self._name + + ## + # @if jp + # + # @brief 初期化関数 + # + # @param self + # @param prop 設定情報 + # channel_timeout:データ書き込み、読み込み時のタイムアウト + # buffer.lengthが0の場合は非リングバッファモードに設定 + # データ読み込み待機状態に移行していないとデータを書き込むことができない + # buffer.lengthが1以上の場合はリングバッファモードに設定 + # バッファに空きがある場合はデータの書き込みができる + # + # @else + # + # @brief + # + # @param self + # @param prop + # + # @endif + # + def init(self, prop): + super(CSPInPort, self).init(prop) + + num = 10 + ret, num = OpenRTM_aist.stringTo( + num, self._properties.getProperty("channel_timeout", "10")) + if ret: + self._channeltimeout = num + + buff_prop = prop.getNode("buffer") + length = 8 + ret, length = OpenRTM_aist.stringTo( + length, buff_prop.getProperty("length", "8")) + + if length == 0: + buff_prop.setProperty("length", "1") + self._bufferzeromode = True + + self._thebuffer.init(buff_prop) + + self._syncmode = OpenRTM_aist.toBool( + prop.getProperty("csp.sync_wait"), "YES", "NO", False) + + if not self._bufferzeromode: + self._writable_listener = OpenRTM_aist.CSPInPort.IsWritableListener( + self._thebuffer, self._ctrl, self._channeltimeout, self, self._manager) + self._write_listener = OpenRTM_aist.CSPInPort.WriteListener( + self._thebuffer, self._ctrl) + else: + self._writable_listener = OpenRTM_aist.CSPInPort.IsWritableZeroModeListener( + self._thebuffer, self._ctrl, self._channeltimeout, self, self._manager) + self._write_listener = OpenRTM_aist.CSPInPort.WriteZeroModeListener( + self._thebuffer, self._ctrl) + + ## + # @if jp + # + # @brief CSPManagerの設定 + # + # @param self + # @param manager CSPManager + # + # @else + # + # @brief + # + # @param self + # @param manager + # + # @endif + # + def setManager(self, manager): + self._writable_listener.setManager(manager) + self._manager = manager + if manager: + self._manager.addInPort(self) + + ## + # @if jp + # + # @brief CSPManagerの設定解除 + # + # @param self + # + # @else + # + # @brief + # + # @param self + # + # @endif + # + def releaseManager(self): + self._writable_listener.releaseManager() + self._manager = None + + ## + # @if jp + # + # @brief 書き込み処理を開始したコネクタを登録 + # + # @param self + # @param con InPortConnector + # + # + # @else + # + # @brief + # + # @param self + # @param con + # + # @endif + # + def setWritingConnector(self, con): + self._writingConnector = con + + ## + # @if jp + # + # @brief 接続先のOutPortに入力可能であることを通知 + # バッファがフルになる、もしくは待機中のOutPortがなくなるまで、接続先のコネクタのデータを読み込む + # バッファからデータを読み込んだ場合は、この関数を呼び出す必要がある + # + # @param self + # + # + # @else + # + # @brief + # + # @param self + # + # @endif + # + def notify(self): + for con in self._connectors: + guard_ctrl = None + if not self._syncmode: + guard_ctrl = OpenRTM_aist.ScopedLock(self._ctrl._cond) + if self._ctrl._writing: + self._ctrl._cond.wait(self._channeltimeout) + if not self._thebuffer.full(): + if con.isReadable(False): + ret, cdr = con.readBuff() + if ret == OpenRTM_aist.DataPortStatus.PORT_OK: + self._thebuffer.write(cdr) + else: + self._rtcout.RTC_ERROR( + "notify read error:%s", (OpenRTM_aist.DataPortStatus.toString(ret))) + + ## + # @if jp + # + # @brief コネクタ接続関数 + # InPortBaseの接続処理のほかに、コネクタに書き込み確認時、書き込み時のコールバック関数を設定する + # + # @param self + # @param connector_profile コネクタプロファイル + # @return ret, prof + # ret:リターンコード + # prof:コネクタプロファイル + # + # @return ポート名称 + # + # @else + # + # @brief + # + # @param self + # @param connector_profile + # @return ret, prof + # + # @endif + # + def notify_connect(self, connector_profile): + ret, prof = super(CSPInPort, self).notify_connect(connector_profile) + guard_con = OpenRTM_aist.ScopedLock(self._connector_mutex) + for con in self._connectors: + con.setIsWritableListener(self._writable_listener) + con.setWriteListener(self._write_listener) + return (ret, prof) + + ## + # @if jp + # + # @brief リングバッファ使用モード時に指定コネクタの読み込み確認、データの読み込みを行う + # + # @param self + # @param con コネクタ + # @param retry True:再検索、False:通常の書き込み確認 + # @return ret, data + # ret:SUCCESSFUL_GET_DATA:データ取得成功、FAILED_DESERIALIZE:復号失敗、FAILED_TIMEOUT:タイムアウトにより失敗、FAILED_EMPTY:空のデータを取得、FAILED_GET_DATA:データの読み込み可能なコネクタが存在しない + # prof:読み込んだデータ + # + # @return ポート名称 + # + # @else + # + # @brief + # + # @param self + # @param con + # @param retry + # @return ret, data + # + # @endif + # + def getDataBufferMode(self, con, retry): + guard_ctrl = None + if not self._syncmode: + guard_ctrl = OpenRTM_aist.ScopedLock(self._ctrl._cond) + if not self._thebuffer.empty(): + _, value = self._thebuffer.read(value) + if guard_ctrl is not None: + del guard_ctrl + self.notify() + ret, data = con.deserializeData(value) + if ret == OpenRTM_aist.DataPortStatus.PORT_OK: + return CSPInPort.SUCCESSFUL_GET_DATA, data + else: + self._rtcout.RTC_ERROR("deserialize error") + elif self._ctrl._writing: + self._ctrl._cond.wait(self._channeltimeout) + if not self._thebuffer.empty(): + _, value = self._thebuffer.read() + if guard_ctrl is not None: + del guard_ctrl + self.notify() + ret, data = con.deserializeData(value[0]) + if ret == OpenRTM_aist.DataPortStatus.PORT_OK: + return CSPInPort.SUCCESSFUL_GET_DATA, data + else: + self._rtcout.RTC_ERROR("deserialize error") + return CSPInPort.FAILED_DESERIALIZE, None + else: + self._rtcout.RTC_ERROR("read timeout") + return CSPInPort.FAILED_TIMEOUT, None + else: + if guard_ctrl is not None: + del guard_ctrl + readable = con.isReadable(retry) + guard_ctrl = OpenRTM_aist.ScopedLock(self._ctrl._cond) + if readable: + ret, value = con.read() + if ret == OpenRTM_aist.DataPortStatus.PORT_OK: + return CSPInPort.SUCCESSFUL_GET_DATA, value + else: + self._rtcout.RTC_ERROR("empty read error:%s", + (OpenRTM_aist.DataPortStatus.toString(ret))) + return CSPInPort.FAILED_EMPTY, None + return CSPInPort.FAILED_GET_DATA, None + + ## + # @if jp + # + # @brief リングバッファ使用モード時にデータの受信を行う + # + # @param self + # @return ret, data + # ret:True:読み込み成功、False:バッファがemptyでかつ読み込み可能なコネクタが存在しない + # data:データ + # + # + # @else + # + # @brief + # + # @param self + # @return ret, data + # + # @endif + # + def dataPullBufferMode(self): + + guard_ctrl = None + + guard_con = OpenRTM_aist.ScopedLock(self._connector_mutex) + if not self._connectors: + self._rtcout.RTC_DEBUG("no connectors") + return False, None + + if self._thebuffer.empty(): + for con in self._connectors: + ret, value = self.getDataBufferMode(con, False) + if ret == CSPInPort.SUCCESSFUL_GET_DATA: + self._ctrl._connectors = [] + self._ctrl._searched_connectors = [] + return True, value + elif ret != CSPInPort.FAILED_GET_DATA: + return False, value + else: + self._ctrl._searched_connectors.append(con) + + else: + if not self._syncmode: + guard_ctrl = OpenRTM_aist.ScopedLock(self._ctrl._cond) + + if not self._thebuffer.empty(): + _, value = self._thebuffer.read() + del guard_ctrl + self.notify() + ret, data = self._connectors[0].deserializeData(value) + if ret == OpenRTM_aist.DataPortStatus.PORT_OK: + return True, data + else: + self._rtcout.RTC_ERROR("deserialize error") + return False, None + else: + self._rtcout.RTC_ERROR("value read error:%s", + (OpenRTM_aist.BufferStatus.toString(ret))) + del guard_ctrl + self.notify() + return False, None + return False, None + + ## + # @if jp + # + # @brief リングバッファ使用モード時にデータの再受信を行う + # データの送受信時は片方がコネクタ選択時にスレッドをロックするロックモード、 + # もう片方がスレッドをロックしない非ロックモードに設定する必要がある。 + # 非ロックモードの場合はデータ選択時にis_writable、is_readable関数が呼ばれた場合、 + # 再検索するコネクタのリストに追加して後で再検索する。 + # + # @param self + # @return ret, data + # ret:True:読み込み成功、False:バッファがemptyでかつ読み込み可能なコネクタが存在しない + # data:データ + # + # + # @else + # + # @brief + # + # @param self + # @return ret, data + # + # @endif + # + def dataPullBufferModeRetry(self): + if self._thebuffer.empty(): + cons = self._ctrl._connectors[:] + for con in cons: + ret, value = self.getDataBufferMode(con, True) + if ret == CSPInPort.SUCCESSFUL_GET_DATA: + self._ctrl._connectors = [] + self._ctrl._searched_connectors = [] + return True, value + elif ret != CSPInPort.FAILED_GET_DATA: + return False, value + self._ctrl._connectors = [] + self._ctrl._searched_connectors = [] + + else: + if not self._thebuffer.empty(): + _, value = self._thebuffer.read() + self.notify() + ret, data = self._connectors[0].deserializeData(value) + if ret == OpenRTM_aist.DataPortStatus.PORT_OK: + return True, data + else: + self._rtcout.RTC_ERROR("deserialize error") + return False, None + else: + self._rtcout.RTC_ERROR("value read error:%s", + (OpenRTM_aist.BufferStatus.toString(ret))) + self.notify() + return False, None + return False, None + + ## + # @if jp + # + # @brief 非リングバッファ使用モード時に指定コネクタの読み込み確認、データの読み込みを行う + # + # @param self + # @param con コネクタ + # @param retry True:再検索、False:通常の書き込み確認 + # @return ret, data + # ret:SUCCESSFUL_GET_DATA:データ取得成功、FAILED_DESERIALIZE:復号失敗、FAILED_GET_DATA:データの読み込み可能なコネクタが存在しない + # prof:読み込んだデータ + # + # + # @else + # + # @brief + # + # @param self + # @param con + # @param retry + # @return ret, data + # + # @endif + # + def getDataZeroMode(self, con, retry): + if con.isReadable(retry): + if not self._syncmode: + guard_ctrl = OpenRTM_aist.ScopedLock(self._ctrl._cond) + ret, value = con.read() + if ret == OpenRTM_aist.DataPortStatus.PORT_OK: + return CSPInPort.SUCCESSFUL_GET_DATA, value + else: + self._rtcout.RTC_ERROR( + "read error:%s", (OpenRTM_aist.DataPortStatus.toString(ret))) + return CSPInPort.FAILED_DESERIALIZE, None + return CSPInPort.FAILED_GET_DATA, None + + ## + # @if jp + # + # @brief 非リングバッファ使用モード時にデータの受信を行う + # + # @param self + # @return ret, data + # ret:True:読み込み成功、False:読み込み可能なコネクタが存在しない + # data:データ + # + # + # @else + # + # @brief + # + # @param self + # @return ret, data + # + # @endif + # + def dataPullZeroMode(self): + guard_con = OpenRTM_aist.ScopedLock(self._connector_mutex) + for con in self._connectors: + ret, value = self.getDataZeroMode(con, False) + if ret == CSPInPort.SUCCESSFUL_GET_DATA: + self._ctrl._connectors = [] + self._ctrl._searched_connectors = [] + return True, value + elif ret != CSPInPort.FAILED_GET_DATA: + return False, value + else: + self._ctrl._searched_connectors.append(con) + + return False, None + + ## + # @if jp + # + # @brief 非リングバッファ使用モード時にデータの再受信確認を行う + # + # @param self + # @return ret, data + # ret:True:読み込み成功、False:バッファがemptyでかつ読み込み可能なコネクタが存在しない + # data:データ + # + # + # @else + # + # @brief + # + # @param self + # @return ret, data + # + # @endif + # + def dataPullZeroModeRetry(self): + cons = self._ctrl._connectors[:] + self._rtcout.RTC_TRACE("reselect %d connectors", (len(cons))) + for con in cons: + ret, value = self.getDataZeroMode(con, True) + if ret == CSPInPort.SUCCESSFUL_GET_DATA: + self._ctrl._connectors = [] + self._ctrl._searched_connectors = [] + return True, value + elif ret != CSPInPort.FAILED_GET_DATA: + self._ctrl._connectors = [] + self._ctrl._searched_connectors = [] + return False, value + self._ctrl._connectors = [] + self._ctrl._searched_connectors = [] + return False, None + + ## + # @if jp + # + # @brief データ読み込み可能なコネクタを選択し、 + # self._valueに読み込んだデータを格納する + # + # + # @param self + # @return True:読み込み成功、False:読み込み不可 + # + # + # @else + # + # @brief + # + # @param self + # @return + # + # @endif + # + + def select(self): + self._rtcout.RTC_TRACE("select()") + guard = OpenRTM_aist.ScopedLock(self._ctrl._cond) + + self._ctrl._connectors = [] + self._ctrl._searched_connectors = [] + + if not self._syncmode: + del guard + guard = None + + if not self._bufferzeromode: + ret, value = self.dataPullBufferMode() + else: + ret, value = self.dataPullZeroMode() + if not self._syncmode: + guard = OpenRTM_aist.ScopedLock(self._ctrl._cond) + if ret: + self._value = value + return ret + + ## + # @if jp + # + # @brief 再検索リストのコネクタからデータ読み込み可能なコネクタを選択し、 + # self._valueに読み込んだデータを格納する + # + # + # @param self + # @return True:読み込み成功、False:読み込み不可 + # + # + # @else + # + # @brief + # + # @param self + # @return + # + # @endif + # + def reselect(self): + self._rtcout.RTC_TRACE("reselect()") + guard = None + if self._syncmode: + guard = OpenRTM_aist.ScopedLock(self._ctrl._cond) + + if not self._bufferzeromode: + ret, value = self.dataPullBufferModeRetry() + else: + ret, value = self.dataPullZeroModeRetry() + if not self._syncmode: + guard = OpenRTM_aist.ScopedLock(self._ctrl._cond) + if ret: + self._value = value + return ret + + ## + # @if jp + # + # @brief ロックモード、非ロックモードの設定 + # データの送受信時は片方がコネクタ選択時にスレッドをロックするロックモード、 + # もう片方がスレッドをロックしない非ロックモードに設定する必要がある。 + # 非ロックモードの場合はデータ選択時にis_writable、is_readable関数が呼ばれた場合、 + # 再検索するコネクタのリストに追加して後で再検索する。 + # + # + # @param self + # @param mode True:ロックモード、False:非ロックモード + # + # + # @else + # + # @brief + # + # @param self + # @param mode + # + # @endif + # + def setSyncMode(self, mode): + self._syncmode = mode + + ## + # @if jp + # + # @brief ロックモード、非ロックモードの取得 + # + # + # @param self + # @return True:ロックモード、False:非ロックモード + # + # + # @else + # + # @brief + # + # @param self + # @return + # + # @endif + # + def getSyncMode(self): + return self._syncmode + + ## + # @if jp + # + # @brief select関数で格納したデータの取得 + # + # + # @param self + # @return データ + # + # + # @else + # + # @brief + # + # @param self + # @return + # + # @endif + # + + def readData(self): + guard = OpenRTM_aist.ScopedLock(self._ctrl._cond) + self._rtcout.RTC_TRACE("readData()") + if self._OnRead is not None: + self._OnRead() + self._rtcout.RTC_TRACE("OnRead called") + + if self._ctrl._writing: + self._ctrl._cond.wait(self._channeltimeout) + + if self._writingConnector: + self._writingConnector = None + if not self._thebuffer.empty(): + _, value = self._thebuffer.read() + ret, data = self._connectors[0].deserializeData(value) + if ret == OpenRTM_aist.DataPortStatus.PORT_OK: + return data + + return self._value + + ## + # @if jp + # + # @brief データを読み込み可能なコネクタを選択しデータを取得する + # 読み込み可能なコネクタが存在しない場合は待機する + # + # + # @param self + # @return データ(タイムアウトした場合はNone) + # + # + # @else + # + # @brief + # + # @param self + # @return + # + # @endif + # + def read(self): + self._rtcout.RTC_TRACE("DataType read()") + if self._OnRead is not None: + self._OnRead() + self._rtcout.RTC_TRACE("OnRead called") + + if not self._connectors: + self._rtcout.RTC_DEBUG("no connectors") + return None + + if not self._bufferzeromode: + return self.readBufferMode() + else: + return self.readZeroMode() + + ## + # @if jp + # + # @brief リングバッファ使用モード時のデータ読み込み処理 + # 読み込み可能なコネクタが存在しない場合は待機する + # + # + # @param self + # @return データ(タイムアウトした場合はNone) + # + # + # @else + # + # @brief + # + # @param self + # @return + # + # @endif + # + + def readBufferMode(self): + guard = OpenRTM_aist.ScopedLock(self._ctrl._cond) + self._ctrl._connectors = [] + self._ctrl._searched_connectors = [] + if not self._syncmode: + del guard + guard = None + + ret, data = self.dataPullBufferMode() + if ret: + return data + else: + if not self._syncmode: + guard = OpenRTM_aist.ScopedLock(self._ctrl._cond) + ret, data = self.dataPullBufferModeRetry() + if ret: + return data + if self._ctrl._writing or self._thebuffer.empty(): + self._ctrl._cond.wait(self._channeltimeout) + if not self._thebuffer.empty(): + _, value = self._thebuffer.read() + + ret, data = self._connectors[0].deserializeData(value) + if ret == OpenRTM_aist.DataPortStatus.PORT_OK: + return data + else: + self._rtcout.RTC_ERROR("deserialize error") + return None + else: + self._rtcout.RTC_ERROR("read timeout") + return None + + ## + # @if jp + # + # @brief 非リングバッファ使用モード時のデータ読み込み処理 + # 読み込み可能なコネクタが存在しない場合は待機する + # + # + # @param self + # @return データ(タイムアウトした場合はNone) + # + # + # @else + # + # @brief + # + # @param self + # @return + # + # @endif + # + def readZeroMode(self): + guard = OpenRTM_aist.ScopedLock(self._ctrl._cond) + self._ctrl._connectors = [] + self._ctrl._searched_connectors = [] + if not self._syncmode: + del guard + guard = None + + ret, data = self.dataPullZeroMode() + if ret: + return data + else: + if not self._syncmode: + guard = OpenRTM_aist.ScopedLock(self._ctrl._cond) + + ret, data = self.dataPullZeroModeRetry() + if ret: + return data + self._ctrl._waiting = True + self._ctrl._cond.wait(self._channeltimeout) + self._ctrl._waiting = False + if not self._thebuffer.empty(): + _, value = self._thebuffer.read() + ret, data = self._connectors[0].deserializeData(value) + if ret == OpenRTM_aist.DataPortStatus.PORT_OK: + return data + else: + self._rtcout.RTC_ERROR("deserialize error") + return None + else: + self._rtcout.RTC_ERROR("read timeout") + return None + + def setOnRead(self, on_read): + self._OnRead = on_read + + def setOnReadConvert(self, on_rconvert): + self._OnReadConvert = on_rconvert + + ## + # @if jp + # + # @class IsWritableListener + # + # @brief データ書き込み確認リスナ基底クラス(リングバッファ使用モード) + # + # + # @since 2.0.0 + # + # @else + # + # @class IsWritableListener + # + # @brief + # + # + # @since 2.0.0 + # + # @endif + # + + class IsWritableListener(OpenRTM_aist.IsWritableListenerBase): + ## + # @if jp + # + # @brief コンストラクタ + # + # + # @param self + # @param buff リングバッファ + # @param control WorkerThreadCtrlオブジェクト + # @param timeout 書き込み待機のタイムアウト時間 + # @param manager CSPチャネル管理マネージャ + # managerを指定した場合は、managerが待機中の場合にロック解除の通知を行う + # + # + # + # @else + # + # @brief + # + # @param self + # @param buff + # @param control + # @param timeout + # @param manager + # + # @endif + # + def __init__(self, buff, control, timeout, port, manager=None): + self._ctrl = control + self._buffer = buff + self._channeltimeout = timeout + self._manager = manager + self._port = port + self._mutex = threading.RLock() + ## + # @if jp + # + # @brief 書き込み確認時のコールバック関数 + # 他のコネクタがデータ書き込み中の場合は完了まで待機する + # バッファがフルではない場合は書き込み状態に移行する + # このため、書き込み可能な場合は必ずデータを書き込む必要がある + # + # + # @param self + # @param con InPortConnector + # @param retry True:再検索、False:通常の書き込み確認 + # @return True:書き込み可能、False:書き込み不可 + # + # + # + # @else + # + # @brief + # + # @param self + # @param con + # @param retry + # @return + # + # @endif + # + + def __call__(self, con, retry=False): + guard_manager = OpenRTM_aist.Guard.ScopedLock(self._mutex) + + if retry: + if con not in self._ctrl._searched_connectors: + return False + + if self._manager: + if self._manager.notify(inport=self._port): + guard = OpenRTM_aist.ScopedLock(self._ctrl._cond) + self._ctrl._writing = True + self._port.setWritingConnector(con) + return True + del guard_manager + guard = OpenRTM_aist.ScopedLock(self._ctrl._cond) + if self._ctrl._writing: + self._ctrl._cond.wait(self._channeltimeout) + if not self._buffer.full(): + self._ctrl._writing = True + return True + else: + self._ctrl._writing = False + self._ctrl._connectors.append(con) + return False + + ## + # @if jp + # + # @brief CSPManagerの設定 + # + # @param self + # @param manager CSPManager + # + # + # + # @else + # + # @brief + # + # @param self + # @param manager + # + # @endif + # + def setManager(self, manager): + guard_manager = OpenRTM_aist.Guard.ScopedLock(self._mutex) + self._manager = manager + + ## + # @if jp + # + # @brief CSPManagerの解除 + # + # @param self + # + # + # + # @else + # + # @brief + # + # @param self + # + # @endif + # + def releaseManager(self): + guard_manager = OpenRTM_aist.Guard.ScopedLock(self._mutex) + self._manager = None + + ## + # @if jp + # + # @class WriteListener + # + # @brief データ書き込み時のリスナ基底クラス(リングバッファ使用モード) + # + # + # @since 2.0.0 + # + # @else + # + # @class WriteListener + # + # @brief + # + # + # @since 2.0.0 + # + # @endif + # + class WriteListener(OpenRTM_aist.WriteListenerBase): + ## + # @if jp + # + # @brief コンストラクタ + # + # + # @param self + # @param buff リングバッファ + # @param control WorkerThreadCtrlオブジェクト + # + # + # + # @else + # + # @brief + # + # @param self + # @param buff + # @param control + # + # @endif + # + def __init__(self, buff, control): + self._ctrl = control + self._buffer = buff + ## + # @if jp + # + # @brief 書き込み時のコールバック関数 + # データをバッファに追加し、書き込み状態を解除する + # + # + # @param self + # @param data データ + # @return リターンコード + # BUFFER_OK:正常完了 + # + # + # + # @else + # + # @brief + # + # @param self + # @param data + # @return + # + # @endif + # + + def __call__(self, data): + guard = OpenRTM_aist.ScopedLock(self._ctrl._cond) + self._buffer.write(data) + self._ctrl._writing = False + self._ctrl._cond.notify() + return OpenRTM_aist.BufferStatus.BUFFER_OK + + ## + # @if jp + # + # @class IsWritableZeroModeListener + # + # @brief データ書き込み確認リスナ基底クラス(非リングバッファ使用モード) + # + # + # @since 2.0.0 + # + # @else + # + # @class IsWritableZeroModeListener + # + # @brief + # + # + # @since 2.0.0 + # + # @endif + # + class IsWritableZeroModeListener(OpenRTM_aist.IsWritableListenerBase): + ## + # @if jp + # + # @brief コンストラクタ + # + # + # @param self + # @param buff リングバッファ + # @param control WorkerThreadCtrlオブジェクト + # @param timeout 書き込み待機のタイムアウト時間 + # @param manager CSPチャネル管理マネージャ + # managerを指定した場合は、managerが待機中の場合にロック解除の通知を行う + # + # + # + # @else + # + # @brief + # + # @param self + # @param buff + # @param control + # @param timeout + # @param manager + # + # @endif + # + def __init__(self, buff, control, timeout, port, manager=None): + self._ctrl = control + self._buffer = buff + self._channeltimeout = timeout + self._port = port + self._manager = manager + self._mutex = threading.RLock() + ## + # @if jp + # + # @brief 書き込み確認時のコールバック関数 + # 他のコネクタがデータ書き込み中の場合は完了まで待機する + # バッファがフルではない場合は書き込み状態に移行する + # このため、書き込み可能な場合は必ずデータを書き込む必要がある + # + # + # @param self + # @param con InPortConnector + # @param retry True:再検索、False:通常の書き込み確認 + # @return True:書き込み可能、False:書き込み不可 + # + # + # + # @else + # + # @brief + # + # @param self + # @param con + # @param retry + # @return + # + # @endif + # + + def __call__(self, con, retry=False): + guard_manager = OpenRTM_aist.Guard.ScopedLock(self._mutex) + if retry: + if con not in self._ctrl._searched_connectors: + return False + if self._manager: + if self._manager.notify(inport=self._port): + guard = OpenRTM_aist.ScopedLock(self._ctrl._cond) + self._ctrl._writing = True + self._port.setWritingConnector(con) + return True + del guard_manager + guard = OpenRTM_aist.ScopedLock(self._ctrl._cond) + if self._ctrl._waiting and self._ctrl._writing: + self._ctrl._cond.wait(self._channeltimeout) + if self._ctrl._waiting: + self._ctrl._writing = True + return True + else: + self._ctrl._writing = False + self._ctrl._connectors.append(con) + return False + + ## + # @if jp + # + # @brief CSPManagerの設定 + # + # @param self + # @param manager CSPManager + # + # + # + # @else + # + # @brief + # + # @param self + # @param manager + # + # @endif + # + def setManager(self, manager): + guard_manager = OpenRTM_aist.Guard.ScopedLock(self._mutex) + self._manager = manager + + ## + # @if jp + # + # @brief CSPManagerの解除 + # + # @param self + # + # + # + # @else + # + # @brief + # + # @param self + # + # @endif + # + def releaseManager(self): + guard_manager = OpenRTM_aist.Guard.ScopedLock(self._mutex) + self._manager = None + + ## + # @if jp + # + # @class WriteZeroModeListener + # + # @brief データ書き込み時のリスナ基底クラス(非リングバッファ使用モード) + # + # + # @since 2.0.0 + # + # @else + # + # @class WriteZeroModeListener + # + # @brief + # + # + # @since 2.0.0 + # + # @endif + # + class WriteZeroModeListener(OpenRTM_aist.WriteListenerBase): + ## + # @if jp + # + # @brief コンストラクタ + # + # + # @param self + # @param buff リングバッファ + # @param control WorkerThreadCtrlオブジェクト + # + # + # + # @else + # + # @brief + # + # @param self + # @param buff + # @param control + # + # @endif + # + def __init__(self, buff, control): + self._ctrl = control + self._buffer = buff + ## + # @if jp + # + # @brief 書き込み時のコールバック関数 + # 書き込み状態を解除しバッファにデータを追加する。 + # + # + # @param self + # @param data データ + # @return リターンコード + # BUFFER_OK:正常完了 + # + # + # + # @else + # + # @brief + # + # @param self + # @param data + # @return + # + # @endif + # + + def __call__(self, data): + guard = OpenRTM_aist.ScopedLock(self._ctrl._cond) + self._ctrl._writing = False + self._buffer.write(data) + self._ctrl._cond.notify() + return OpenRTM_aist.BufferStatus.BUFFER_OK + + class WorkerThreadCtrl: + def __init__(self): + self._mutex = threading.RLock() + self._cond = threading.Condition(self._mutex) + self._writing = False + self._waiting = False + self._connectors = [] + self._searched_connectors = [] diff --git a/OpenRTM_aist/CSPMachine.py b/OpenRTM_aist/CSPMachine.py new file mode 100644 index 00000000..7e58858b --- /dev/null +++ b/OpenRTM_aist/CSPMachine.py @@ -0,0 +1,141 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- + +## +# @file StaticFSM.py +# @brief Static FSM framework based on Macho +# @date $Date: $ +# @author Nobuhiko Miyamoto +# +# Copyright (C) 2017 +# Intelligent Systems Research Institute, +# National Institute of +# Advanced Industrial Science and Technology (AIST), Japan +# All rights reserved. + +import OpenRTM_aist +import OpenRTM_aist.Macho +import OpenRTM_aist.StaticFSM +import RTC + + +## +# @if jp +# +# @class CSPMachine +# +# @brief 有限状態機械、CSPOutPort、CSPInPortを管理するクラス +# +# +# @since 2.0.0 +# +# @else +# +# @class CSPMachine +# +# @brief +# +# +# @since 2.0.0 +# +# @endif +# +class CSPMachine(OpenRTM_aist.StaticFSM.Machine): + ## + # @if jp + # + # @brief コンストラクタ + # + # @param self + # + # @else + # + # @brief A constructor. + # + # @param self + # + # @endif + # + def __init__(self, TOP, comp, cspmgr): + OpenRTM_aist.StaticFSM.Machine.__init__(self, TOP, comp) + self._manager = cspmgr + #self._ctrl = OpenRTM_aist.CSPManager.CSPThreadCtrl() + + ## + # @if jp + # + # @brief デストラクタ + # + # @param self + # + # @else + # + # @brief Destructor + # + # @param self + # + # @endif + # + def __del__(self): + pass + + def init_other(self, other): + pass + + def equal(self, snapshot): + pass + ## + # @if jp + # + # @brief RTC取得 + # + # @param self + # @return RTC + # + # @else + # + # @brief + # + # @param self + # @return + # + # @endif + # + + def getComp(self): + return self._rtComponent + + ## + # @if jp + # + # @brief FSMのイベントを実行する + # 受信済みのイベント、送信可能なInPortを選択してイベントを実行する + # OutPortを登録している場合はデータを送信する。 + # イベント実行可能なポートがない場合はタイムアウトまで待機する + # この時、送信するデータは事前に設定しておく必要がある + # + # @param self + # @param timeout タイムアウトまでの時間 + # @return イベント実行したポート。イベントを実行できなかった場合はNoneを返す。 + # + # @else + # + # @brief + # + # @param self + # @param timeout + # @return + # + # @endif + # + def run_event(self, timeout=10): + ret, outport, inport = self._manager.select(timeout) + if ret: + if inport: + event = inport.readData() + event() + return inport + elif outport: + outport.write() + return outport + return None diff --git a/OpenRTM_aist/CSPManager.py b/OpenRTM_aist/CSPManager.py new file mode 100644 index 00000000..cc844c61 --- /dev/null +++ b/OpenRTM_aist/CSPManager.py @@ -0,0 +1,438 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- + +## +# @file CSPManager.py +# @brief CSP Manager class +# @date $Date: $ +# @author Nobuhiko Miyamoto +# +# Copyright (C) 2019 +# Intelligent Systems Research Institute, +# National Institute of +# Advanced Industrial Science and Technology (AIST), Japan +# All rights reserved. + +import OpenRTM_aist +import OpenRTM_aist.CSPEventPort +import copy +import threading + + +## +# @if jp +# +# @class CSPManager +# +# @brief CSPOutPort、CSPInPortを管理するクラス +# +# +# @since 2.0.0 +# +# @else +# +# @class CSPManager +# +# @brief +# +# +# @since 2.0.0 +# +# @endif +# +class CSPManager(object): + ## + # @if jp + # + # @brief コンストラクタ + # + # @param self + # + # @else + # + # @brief A constructor. + # + # @param self + # + # @endif + # + def __init__(self): + self._outports = [] + self._inports = [] + self._ctrl = CSPManager.CSPThreadCtrl() + self._writableOutPort = None + self._readableInPort = None + + ## + # @if jp + # + # @brief デストラクタ + # + # デストラクタ。 + # + # @else + # + # @brief Destructor + # + # Destructor + # + # @endif + # + + def __del__(self): + pass + + ## + # @if jp + # + # @brief CSPポートに設定したCSPManagerとの関連付けを解除 + # + # @param self + # + # @else + # + # @brief + # + # @param self + # + # @endif + # + def reset(self): + for port in self._outports: + port.releaseManager() + for port in self._inports: + port.releaseManager() + self._outports = [] + self._inports = [] + + ## + # @if jp + # + # @brief 書き込み可能なOutPortを選択する + # + # @param self + # @return ret, port + # ret:True(書き込み可能なOutPortが存在する)、False(存在しない) + # port:書き込み可能なOutPort。選択できなかった場合はNone + # + # @else + # + # @brief + # + # @param self + # @return + # + # @endif + # + def selectOutPort(self): + for port in self._outports: + if port.select(): + return True, port + return False, None + + ## + # @if jp + # + # @brief 読み込み可能なInPortを選択する + # + # @param self + # @return ret, port + # ret:True(読み込み可能なInPortが存在する)、False(存在しない) + # port:読み込み可能なInPort。選択できなかった場合はNone + # + # @else + # + # @brief + # + # @param self + # @return + # + # @endif + # + def selectInPort(self): + for port in self._inports: + if port.select(): + return True, port + return False, None + + ## + # @if jp + # + # @brief ポートをロックモードと非ロックモードに仕分けする + # + # @param self + # @return ports1, ports2 + # ports1:ロックモードのポート + # ports2:非ロックモードのポート + # + # @else + # + # @brief + # + # @param self + # @return + # + # @endif + # + def getPorts(self): + ports1 = [] + ports2 = [] + for port in self._inports: + if port.getSyncMode(): + ports1.append(port) + else: + ports2.append(port) + + for port in self._outports: + if port.getSyncMode(): + ports1.append(port) + else: + ports2.append(port) + return ports1, ports2 + + ## + # @if jp + # + # @brief ポート一覧から通信可能なポートを自動選択する + # + # @param self + # @param ports 選択対象のポート一覧 + # @return ret, outport, inport + # ret:True:選択成功、False:選択失敗 + # outport:選択したOutPort。OutPortを選択しなかった場合はNone + # inport:選択したInPort。InPortを選択しなかった場合はNone + # + # @else + # + # @brief + # + # @param self + # @param ports + # @return + # + # @endif + # + def selectPort(self, ports): + for port in ports: + ret = port.select() + if ret: + if port in self._inports: + return True, None, port + elif port in self._outports: + return True, port, None + return False, None, None + + ## + # @if jp + # + # @brief ポート一覧から通信可能なポートを再選択する + # + # @param self + # @param ports 選択対象のポート一覧 + # @return ret, outport, inport + # ret:True:選択成功、False:選択失敗 + # outport:選択したOutPort。OutPortを選択しなかった場合はNone + # inport:選択したInPort。InPortを選択しなかった場合はNone + # + # @else + # + # @brief + # + # @param self + # @param ports + # @return + # + # @endif + # + def reselectPort(self, ports): + for port in ports: + ret = port.reselect() + if ret: + if isinstance(port, OpenRTM_aist.CSPInPort): + return True, None, port + elif isinstance(port, OpenRTM_aist.CSPEventPort.CSPEventPort): + return True, None, port + elif isinstance(port, OpenRTM_aist.CSPOutPort): + return True, port, None + return False, None, None + + ## + # @if jp + # + # @brief 読み込み可能なInPort、もしくは書き込み可能なOutPortを選択する + # 読み込み可能なInPort、書き込み可能なOutPortが存在しない場合はタイムアウトまで待機する + # 待機解除後、読み込み可能なInPort、もしくは書き込み可能なOutPortを再度選択する + # + # @param self + # @param timeout 待機のタイムアウト時間 + # @return ret, outport, inport + # ret:Ture(書き込み、読み込み可能なポートが存在)、False(タイムアウト) + # outport:OutPortを選択した場合に、書き込み可能なOutPortを格納 + # inport:InPortを選択した場合に、読み込み可能なInortを格納 + # + # @else + # + # @brief + # + # @param self + # @param timeout + # @return + # + # @endif + # + def select(self, timeout): + ports1, ports2 = self.getPorts() + + ret, outport, inport = self.selectPort(ports2) + + if ret: + return ret, outport, inport + + guard = OpenRTM_aist.ScopedLock(self._ctrl._cond) + + ret, outport, inport = self.reselectPort(ports2) + + if ret: + return ret, outport, inport + + ret, outport, inport = self.selectPort(ports1) + + if ret: + return ret, outport, inport + + if timeout >= 0: + self._ctrl._waiting = True + self._ctrl._timeout = True + self._ctrl._cond.wait(timeout) + self._ctrl._waiting = False + del guard + if self._ctrl._timeout: + return False, None, None + else: + if self._writableOutPort or self._readableInPort: + inport = self._readableInPort + outport = self._writableOutPort + self._writableOutPort = None + self._readableInPort = None + return True, outport, inport + return False, None, None + + ## + # @if jp + # + # @brief 待機状態解除を通知 + # select関数で待機している場合に、待機を解除する + # + # @param self + # @return True:待機状態を解除、False:待機状態ではない + # + # @else + # + # @brief + # + # @param self + # @return + # + # @endif + # + + def notify(self, outport=None, inport=None): + guard = OpenRTM_aist.ScopedLock(self._ctrl._cond) + if self._ctrl._waiting: + self._ctrl._timeout = False + if outport: + self._writableOutPort = outport + elif inport: + self._readableInPort = inport + self._ctrl._cond.notify() + return True + else: + return False + + ## + # @if jp + # + # @brief InPortを追加 + # + # @param self + # @param port InPort + # + # @else + # + # @brief + # + # @param self + # @param port + # + # @endif + # + def addInPort(self, port): + self._inports.append(port) + + ## + # @if jp + # + # @brief OutPortを追加 + # + # @param self + # @param port OutPort + # + # @else + # + # @brief + # + # @param self + # @param port + # + # @endif + # + def addOutPort(self, port): + self._outports.append(port) + + ## + # @if jp + # + # @brief InPortを削除 + # + # @param self + # @param port InPort + # + # @else + # + # @brief + # + # @param self + # @param port + # + # @endif + # + def removeInPort(self, port): + self._inports.remove(port) + + ## + # @if jp + # + # @brief Outortを削除 + # + # @param self + # @param port OutPort + # + # @else + # + # @brief + # + # @param self + # @param port + # + # @endif + # + def removeOutPort(self, port): + self._outports.remove(port) + + class CSPThreadCtrl: + def __init__(self): + self._mutex = threading.RLock() + self._cond = threading.Condition(self._mutex) + self._port = None + self._waiting = False + self._timeout = True diff --git a/OpenRTM_aist/CSPOutPort.py b/OpenRTM_aist/CSPOutPort.py new file mode 100644 index 00000000..e971063f --- /dev/null +++ b/OpenRTM_aist/CSPOutPort.py @@ -0,0 +1,814 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- + +## +# @file CSPOutPort.py +# @brief CSPOutPort template class +# @date $Date: $ +# @author Nobuhiko Miyamoto +# +# Copyright (C) 2019 +# Intelligent Systems Research Institute, +# National Institute of +# Advanced Industrial Science and Technology (AIST), Japan +# All rights reserved. + +import OpenRTM_aist +import copy +import threading + + +## +# @if jp +# +# @class EventInPort +# +# @brief EventInPort テンプレートクラス +# +# +# @since 2.0.0 +# +# @else +# +# @class EventInPort +# +# @brief EventInPort template class +# +# +# @since 2.0.0 +# +# @endif +# +class CSPOutPort(OpenRTM_aist.OutPortBase): + ## + # @if jp + # + # @brief コンストラクタ + # + # コンストラクタ。 + # パラメータとして与えられる T 型の変数にバインドされる。 + # + # @param name EventInPort 名。EventInPortBase:name() により参照される。 + # @param value この EventInPort にバインドされる T 型の変数 + # + # @else + # + # @brief A constructor. + # + # constructor. + # This is bound to type-T variable given as a parameter. + # + # @param name A name of the EventInPort. This name is referred by + # EventInPortBase::name(). + # @param value type-T variable that is bound to this EventInPort. + # + # @endif + # + def __init__(self, name, value, manager=None): + super(CSPOutPort, self).__init__(name, OpenRTM_aist.toTypename(value)) + self._value = value + self._ctrl = OpenRTM_aist.CSPOutPort.WorkerThreadCtrl() + self._name = name + self._OnWrite = None + self._OnWriteConvert = None + self._buffdata = [None] + + self._channeltimeout = 10 + self._writableConnector = None + self._manager = manager + if manager: + manager.addOutPort(self) + self._syncmode = True + + ## + # @if jp + # + # @brief デストラクタ + # + # デストラクタ。 + # + # @else + # + # @brief Destructor + # + # Destructor + # + # @endif + # + + def __del__(self): + super(CSPOutPort, self).__del__() + + ## + # @if jp + # + # @brief ポート名称を取得する。 + # + # ポート名称を取得する。 + # + # @param self + # @return ポート名称 + # + # @else + # + # @brief Get port name + # + # Get port name. + # + # @param self + # @return The port name + # + # @endif + # + def name(self): + return self._name + + ## + # @if jp + # + # @brief 初期化関数 + # + # @param self + # @param prop 設定情報 + # channel_timeout:データ書き込み、読み込み時のタイムアウト + # + # @else + # + # @brief + # + # @param self + # @param prop + # + # @endif + # + def init(self, prop): + super(CSPOutPort, self).init(prop) + num = 10 + ret, num = OpenRTM_aist.stringTo( + num, self._properties.getProperty("channel_timeout", "10")) + if ret: + self._channeltimeout = num + + self._syncmode = OpenRTM_aist.toBool( + prop.getProperty("csp.sync_wait"), "YES", "NO", True) + + self._readable_listener = OpenRTM_aist.CSPOutPort.IsReadableListener( + self._buffdata, self._ctrl, self._channeltimeout, self, self._manager) + self._read_listener = OpenRTM_aist.CSPOutPort.ReadListener( + self._buffdata, self._ctrl, self._channeltimeout) + + ## + # @if jp + # + # @brief CSPManagerの設定 + # + # @param self + # @param manager CSPManager + # + # @else + # + # @brief + # + # @param self + # @param manager + # + # @endif + # + def setManager(self, manager): + self._readable_listener.setManager(manager) + self._manager = manager + if manager: + self._manager.addOutPort(self) + + ## + # @if jp + # + # @brief CSPManagerの設定解除 + # + # @param self + # + # @else + # + # @brief + # + # @param self + # + # @endif + # + def releaseManager(self): + self._readable_listener.releaseManager() + self._manager = None + + ## + # @if jp + # + # @brief コネクタ接続関数 + # OutPortBaseの接続処理のほかに、コネクタに読み込み確認時、読み込み時のコールバック関数を設定する + # + # @param self + # @param connector_profile コネクタプロファイル + # @return ret, prof + # ret:リターンコード + # prof:コネクタプロファイル + # + # @return ポート名称 + # + # @else + # + # @brief + # + # @param self + # @param connector_profile + # @return ret, prof + # + # @endif + # + def notify_connect(self, connector_profile): + ret, prof = super(CSPOutPort, self).notify_connect(connector_profile) + guard_con = OpenRTM_aist.ScopedLock(self._connector_mutex) + for con in self._connectors: + con.setIsReadableListener(self._readable_listener) + con.setReadListener(self._read_listener) + return (ret, prof) + + ## + # @if jp + # + # @brief データが書き込み可能かを確認 + # + # @param self + # @return ret, con + # ret:True(書き込み可能)、False(書き込み不可) + # con:書き込み可能なコネクタ。書き込み不可の場合はNone + # + # @else + # + # @brief + # + # @param self + # @return + # + # @endif + # + def dataWritable(self): + guard = OpenRTM_aist.ScopedLock(self._connector_mutex) + for con in self._connectors: + if con.isWritable(False): + self._ctrl._searched_connectors = [] + return True, con + else: + self._ctrl._searched_connectors.append(con) + + return False, None + + ## + # @if jp + # + # @brief データの再送信確認を行う + # + # @param self + # @return ret, con + # ret:True(書き込み可能)、False(書き込み不可) + # con:書き込み可能なコネクタ。書き込み不可の場合はNone + # + # + # @else + # + # @brief + # + # @param self + # @return ret, con + # + # @endif + # + def dataWritableRetry(self): + cons = self._ctrl._connectors[:] + for con in cons: + if con.isWritable(True): + self._ctrl._connectors = [] + self._ctrl._searched_connectors = [] + return True, con + self._ctrl._connectors = [] + self._ctrl._searched_connectors = [] + return False, None + + ## + # @if jp + # + # @brief 書き込み可能なコネクタを選択してself._writableConnectorに格納する + # + # @param self + # @return True:書き込み可能、False:書き込み不可 + # + # @else + # + # @brief + # + # @param self + # @return + # + # @endif + # + + def select(self): + self._rtcout.RTC_TRACE("select()") + guard = OpenRTM_aist.ScopedLock(self._ctrl._cond) + + self._ctrl._connectors = [] + self._ctrl._searched_connectors = [] + + if self._ctrl._waiting: + return True + if self._ctrl._reading: + self._ctrl._cond.wait(self._channeltimeout) + + if not self._syncmode: + del guard + guard = None + + ret, self._writableConnector = self.dataWritable() + return ret + + ## + # @if jp + # + # @brief 再検索リストのコネクタからデータ書き込み可能なコネクタを選択し、 + # self._writableConnectorに格納する + # + # + # @param self + # @return True:書き込み可能、False:書き込み不可 + # + # + # @else + # + # @brief + # + # @param self + # @return + # + # @endif + # + def reselect(self): + self._rtcout.RTC_TRACE("reselect()") + guard = OpenRTM_aist.ScopedLock(self._ctrl._cond) + + if self._ctrl._waiting: + return True + if self._ctrl._reading: + self._ctrl._cond.wait(self._channeltimeout) + + if not self._syncmode: + del guard + + ret, self._writableConnector = self.dataWritableRetry() + return ret + + ## + # @if jp + # + # @brief ロックモード、非ロックモードの設定 + # データの送受信時は片方がコネクタ選択時にスレッドをロックするロックモード、 + # もう片方がスレッドをロックしない非ロックモードに設定する必要がある。 + # 非ロックモードの場合はデータ選択時にis_writable、is_readable関数が呼ばれた場合、 + # 再検索するコネクタのリストに追加して後で再検索する。 + # + # + # @param self + # @param mode True:ロックモード、False:非ロックモード + # + # + # @else + # + # @brief + # + # @param self + # @param mode + # + # @endif + # + def setSyncMode(self, mode): + self._syncmode = mode + + ## + # @if jp + # + # @brief ロックモード、非ロックモードの取得 + # + # + # @param self + # @return True:ロックモード、False:非ロックモード + # + # + # @else + # + # @brief + # + # @param self + # @return + # + # @endif + # + def getSyncMode(self): + return self._syncmode + + ## + # @if jp + # + # @brief self._writableConnectorに格納したコネクタにデータを書き込む + # このため、事前にselect関数を実行する必要がある + # + # @param self + # @param value データ + # + # @else + # + # @brief + # + # @param self + # @param value + # + # @endif + # + def writeData(self, value=None): + self._rtcout.RTC_TRACE("writeData()") + if not value: + value = self._value + if self._OnWrite: + self._OnWrite(value) + + if self._OnWriteConvert: + value = self._OnWriteConvert(value) + + guard_con = OpenRTM_aist.ScopedLock(self._ctrl._cond) + if self._ctrl._waiting: + ret, cdr_data = self._connectors[0].serializeData(value) + if ret == OpenRTM_aist.DataPortStatus.PORT_OK: + self.setData(cdr_data) + self._ctrl._waiting = False + self._ctrl._cond.notify() + return True + + if self._writableConnector: + del guard_con + self._writableConnector.write(value) + + ## + # @if jp + # + # @brief 待機状態時に移行した場合にデータを一時的に変数に格納する + # + # @param self + # @param data データ + # + # @else + # + # @brief + # + # @param self + # @param data + # + # @endif + # + def setData(self, data): + self._buffdata[0] = data + + ## + # @if jp + # + # @brief データを書き込む + # 書き込み可能なコネクタが存在する場合は、データを書き込んで処理を終了する + # 書き込み可能なコネクタが存在しない場合は、InPort側からデータを読み込むまで待機する + # + # @param self + # @param value データ + # @return True:正常完了、False:エラー + # データのマーシャリング、書き込みのタイムアウトでエラーが発生する + # + # @else + # + # @brief + # + # @param self + # @param value + # @return + # + # @endif + # + def write(self, value=None): + guard = OpenRTM_aist.ScopedLock(self._ctrl._cond) + + self._ctrl._connectors = [] + self._ctrl._searched_connectors = [] + + if not self._syncmode: + del guard + guard = None + + if not value: + value = self._value + if self._OnWrite: + self._OnWrite(value) + + if not self._connectors: + return False + + if self._OnWriteConvert: + value = self._OnWriteConvert(value) + + if not self._ctrl._waiting: + ret, con = self.dataWritable() + if ret: + retcon = con.write(value) + if retcon == OpenRTM_aist.DataPortStatus.PORT_OK: + return True + else: + self._rtcout.RTC_ERROR("write error %d", (retcon)) + return False + + if not self._syncmode: + guard_con = OpenRTM_aist.ScopedLock(self._ctrl._cond) + + ret, con = self.dataWritableRetry() + if ret: + retcon = con.write(value) + if retcon == OpenRTM_aist.DataPortStatus.PORT_OK: + return True + else: + self._rtcout.RTC_ERROR("write error %d", (retcon)) + return False + + ret, cdr_data = self._connectors[0].serializeData(value) + if ret == OpenRTM_aist.DataPortStatus.PORT_OK: + self.setData(cdr_data) + if self._ctrl._waiting: + self._ctrl._waiting = False + self._ctrl._cond.notify() + return True + self._ctrl._readable = True + self._ctrl._cond.wait(self._channeltimeout) + + if self._ctrl._readable: + self._rtcout.RTC_ERROR("write timeout") + self._ctrl._readable = False + return False + return True + else: + self._rtcout.RTC_ERROR("serialize error") + return False + + def setOnWrite(self, on_write): + self._OnWrite = on_write + + def setOnWriteConvert(self, on_wconvert): + self._OnWriteConvert = on_wconvert + + ## + # @if jp + # + # @class IsReadableListener + # + # @brief データ読み込み確認リスナ基底クラス + # + # + # @since 2.0.0 + # + # @else + # + # @class IsReadableListener + # + # @brief + # + # + # @since 2.0.0 + # + # @endif + # + class IsReadableListener(OpenRTM_aist.IsReadableListenerBase): + ## + # @if jp + # + # @brief コンストラクタ + # + # + # @param self + # @param control WorkerThreadCtrlオブジェクト + # @param timeout 読み込み待機のタイムアウト時間 + # @param manager CSPチャネル管理マネージャ + # managerを指定した場合は、managerが待機中の場合にロック解除の通知を行う + # + # + # + # @else + # + # @brief + # + # @param self + # @param control + # @param timeout + # @param manager + # + # @endif + # + def __init__(self, data, control, timeout, port, manager=None): + self._ctrl = control + self._data = data + self._channeltimeout = timeout + self._port = port + self._manager = manager + self._mutex = threading.RLock() + ## + # @if jp + # + # @brief 読み込み確認時のコールバック関数 + # 他のコネクタがデータ読み込み中の場合は完了まで待機する + # データ書き込みで待機しているの場合は読み込み状態に移行する + # このため、読み込み可能な場合は必ずデータを読み込み必要がある + # + # + # @param self + # @param con OutPortConnector + # @param retry True:再検索、False:通常の読み込み確認 + # @return True:読み込み可能、False:読み込み不可 + # + # + # + # @else + # + # @brief + # + # @param self + # @param con + # @param retry + # @return + # + # @endif + # + + def __call__(self, con, retry=False): + guard_manager = OpenRTM_aist.Guard.ScopedLock(self._mutex) + + if retry: + if con not in self._ctrl._searched_connectors: + return False + + if self._manager: + if self._manager.notify(outport=self._port): + guard = OpenRTM_aist.ScopedLock(self._ctrl._cond) + self._ctrl._reading = True + return True + del guard_manager + guard = OpenRTM_aist.ScopedLock(self._ctrl._cond) + if self._ctrl._reading: + self._ctrl._cond.wait(self._channeltimeout) + if not self._ctrl._readable: + self._ctrl._reading = False + self._ctrl._connectors.append(con) + return False + else: + self._ctrl._reading = True + return True + + ## + # @if jp + # + # @brief CSPManagerの設定 + # + # @param self + # @param manager CSPManager + # + # + # + # @else + # + # @brief + # + # @param self + # @param manager + # + # @endif + # + def setManager(self, manager): + guard_manager = OpenRTM_aist.Guard.ScopedLock(self._mutex) + self._manager = manager + + ## + # @if jp + # + # @brief CSPManagerの解除 + # + # @param self + # + # + # + # @else + # + # @brief + # + # @param self + # + # @endif + # + def releaseManager(self): + guard_manager = OpenRTM_aist.Guard.ScopedLock(self._mutex) + self._manager = None + + ## + # @if jp + # + # @class ReadListener + # + # @brief データ読み込み時のリスナ基底クラス + # + # + # @since 2.0.0 + # + # @else + # + # @class ReadListener + # + # @brief + # + # + # @since 2.0.0 + # + # @endif + # + class ReadListener(OpenRTM_aist.ReadListenerBase): + ## + # @if jp + # + # @brief コンストラクタ + # + # + # @param self + # @param data データを格納する変数 + # @param control WorkerThreadCtrlオブジェクト + # + # + # + # @else + # + # @brief + # + # @param self + # @param data + # @param control + # + # @endif + # + def __init__(self, data, control, timeout): + self._ctrl = control + self._data = data + self._channeltimeout = timeout + ## + # @if jp + # + # @brief 読み込み時のコールバック関数 + # データを変数から取り出し、読み込み状態を解除する + # + # + # @param self + # @return ret, data + # ret:リターンコード + # BUFFER_OK:正常完了 + # BUFFER_ERROR:データが格納されていない + # data:データ + # + # + # + # @else + # + # @brief + # + # @param self + # @return + # + # @endif + # + + def __call__(self): + guard = OpenRTM_aist.ScopedLock(self._ctrl._cond) + if self._data[0] is None: + self._ctrl._waiting = True + self._ctrl._cond.wait(self._channeltimeout) + + self._ctrl._reading = False + data = self._data[0] + self._data[0] = None + self._ctrl._readable = False + self._ctrl._cond.notify() + if data is None: + return OpenRTM_aist.BufferStatus.BUFFER_ERROR, data + else: + return OpenRTM_aist.BufferStatus.BUFFER_OK, data + + class WorkerThreadCtrl: + def __init__(self): + self._mutex = threading.RLock() + self._cond = threading.Condition(self._mutex) + self._reading = False + self._readable = False + self._waiting = False + self._connectors = [] + self._searched_connectors = [] diff --git a/OpenRTM_aist/CdrBufferBase.py b/OpenRTM_aist/CdrBufferBase.py index b1b28daa..bca68529 100644 --- a/OpenRTM_aist/CdrBufferBase.py +++ b/OpenRTM_aist/CdrBufferBase.py @@ -1,5 +1,5 @@ #!/usr/bin/env python -# -*- coding: euc-jp -*- +# -*- coding: utf-8 -*- ## # @file CdrBufferBase.py @@ -32,10 +32,9 @@ def __init__(self): OpenRTM_aist.Factory.__init__(self) pass - def instance(): global cdrbufferfactory - + if cdrbufferfactory is None: cdrbufferfactory = CdrBufferFactory() diff --git a/OpenRTM_aist/CdrRingBuffer.py b/OpenRTM_aist/CdrRingBuffer.py index fa147365..99e46f0f 100644 --- a/OpenRTM_aist/CdrRingBuffer.py +++ b/OpenRTM_aist/CdrRingBuffer.py @@ -1,5 +1,5 @@ #!/usr/bin/env python -# -*- coding: euc-jp -*- +# -*- coding: utf-8 -*- ## # @file CdrRingBuffer.py @@ -20,14 +20,14 @@ class CdrRingBuffer(OpenRTM_aist.RingBuffer): - """ - """ - def __init__(self): - OpenRTM_aist.RingBuffer.__init__(self) - pass + """ + """ + + def __init__(self): + OpenRTM_aist.RingBuffer.__init__(self) + pass def CdrRingBufferInit(): - OpenRTM_aist.CdrBufferFactory.instance().addFactory("ring_buffer", - OpenRTM_aist.CdrRingBuffer, - OpenRTM_aist.Delete) + OpenRTM_aist.CdrBufferFactory.instance().addFactory("ring_buffer", + OpenRTM_aist.CdrRingBuffer) diff --git a/OpenRTM_aist/ClockManager.py b/OpenRTM_aist/ClockManager.py index 2cc8c902..8ff1fc6d 100644 --- a/OpenRTM_aist/ClockManager.py +++ b/OpenRTM_aist/ClockManager.py @@ -1,5 +1,5 @@ #!/usr/bin/env python -# -*- coding: euc-jp -*- +# -*- coding: utf-8 -*- ## # @file ClockManager.py @@ -23,14 +23,14 @@ ## # @if jp -# @class ꡦ֥ȤΥ󥿡ե +# @class 時刻設定・取得オブジェクトのインターフェース # -# Υ饹 ClockManager ˤäƴ륯å֥Ȥ -# Υ󥿡եǤ롣ClockManager ʣΥå֥ -# Ȥɬפ˱Ŭڤʥå֥Ȥ IClock -# եĥ֥ȤȤ֤å֥Ȥñ -# ˥ƥ֤Τ䡢ȼĥå֥ -# ͤ롣 +# このクラスは ClockManager によって管理されるクロックオブジェクトの +# ためのインターフェースである。ClockManager は複数のクロックオブジェ +# クトを管理し、必要に応じて適切なクロックオブジェクトを IClock イン +# ターフェースをもつオブジェクトとして返す。クロックオブジェクトは単 +# にシステム時刻を返すものや、独自の論理時刻を持つクロックオブジェク +# ト等が考えられる。 # # @else # @brief An interface to set and get time @@ -43,40 +43,40 @@ # # @endif class IClock: - """ - """ - - ## - # @if jp - # @brief - # @return ߤλ - # @else - # @brief Getting time - # @return Current time - # @endif - # virtual coil::TimeValue gettime() const = 0; - def gettime(self): - pass - - - ## - # @if jp - # @brief ꤹ - # @param clocktime ߤλ - # @else - # @brief Setting time - # @param clocktime Current time - # @endif - # virtual bool settime(coil::TimeValue clocktime) = 0; - def settime(self, clocktime): - pass + """ + """ + + ## + # @if jp + # @brief 時刻を取得する + # @return 現在の時刻 + # @else + # @brief Getting time + # @return Current time + # @endif + # virtual coil::TimeValue gettime() const = 0; + def gettime(self): + pass + + ## + # @if jp + # @brief 時刻を設定する + # @param clocktime 現在の時刻 + # @else + # @brief Setting time + # @param clocktime Current time + # @endif + # virtual bool settime(coil::TimeValue clocktime) = 0; + + def settime(self, clocktime): + pass ## # @if jp -# @class ƥ򰷤å֥ +# @class システム時刻を扱うクロックオブジェクト # -# Υ饹ϥƥ९åޤϼ륯饹Ǥ롣 +# このクラスはシステムクロックを設定または取得するクラスである。 # # @else # @brief clock object to handle system clock @@ -85,24 +85,24 @@ def settime(self, clocktime): # # @endif class SystemClock(IClock): - """ - """ + """ + """ - # virtual coil::TimeValue gettime() const; - def gettime(self): - return OpenRTM_aist.Time().getTime() + # virtual coil::TimeValue gettime() const; + def gettime(self): + return OpenRTM_aist.Time().getTime() - # virtual bool settime(coil::TimeValue clocktime); - def settime(self, clocktime): - return OpenRTM_aist.Time().settimeofday(clocktime, 0) + # virtual bool settime(coil::TimeValue clocktime); + def settime(self, clocktime): + return OpenRTM_aist.Time().settimeofday(clocktime, 0) ## # @if jp -# @class ֤򰷤å֥ +# @class 論理時間を扱うクロックオブジェクト # -# Υ饹֤ޤϼ륯饹Ǥ롣 -# ñ settime() ˤäꤵ줿 gettime() ˤäƼ롣 +# このクラスは論理時間を設定または取得するクラスである。 +# 単純に settime() によって設定された時刻を gettime() によって取得する。 # # @else # @brief Clock object to handle logical clock @@ -112,32 +112,32 @@ def settime(self, clocktime): # # @endif class LogicalClock(IClock): - """ - """ - - def __init__(self): - self._currentTime = OpenRTM_aist.TimeValue(0.0) - self._currentTimeMutex = threading.RLock() - return - - # virtual coil::TimeValue gettime() const; - def gettime(self): - guard = OpenRTM_aist.ScopedLock(self._currentTimeMutex) - return self._currentTime - - # virtual bool settime(coil::TimeValue clocktime); - def settime(self, clocktime): - guard = OpenRTM_aist.ScopedLock(self._currentTimeMutex) - self._currentTime = clocktime - return True - + """ + """ + + def __init__(self): + self._currentTime = OpenRTM_aist.TimeValue(0.0) + self._currentTimeMutex = threading.RLock() + return + + # virtual coil::TimeValue gettime() const; + def gettime(self): + guard = OpenRTM_aist.ScopedLock(self._currentTimeMutex) + return self._currentTime + + # virtual bool settime(coil::TimeValue clocktime); + def settime(self, clocktime): + guard = OpenRTM_aist.ScopedLock(self._currentTimeMutex) + self._currentTime = clocktime + return True + ## # @if jp -# @class ĴѤ߻򰷤å֥ +# @class 調整済み時刻を扱うクロックオブジェクト # -# settime() ƤӽФ˸߻Ȥκ򥪥եåȤȤݻ -# gettime() ˤäƥեåĴѤߤλ֤ +# settime() 呼び出し時に現在時刻との差をオフセットとして保持し、 +# gettime() によってオフセット調整済みの時刻を返す。 # # @else # @brief Clock object to handle adjusted clock @@ -147,37 +147,38 @@ def settime(self, clocktime): # # @endif class AdjustedClock(IClock): - """ - """ - - def __init__(self): - self._offset = OpenRTM_aist.TimeValue(0.0) - self._offsetMutex = threading.RLock() - return - - - # virtual coil::TimeValue gettime() const; - def gettime(self): - guard = OpenRTM_aist.ScopedLock(self._offsetMutex) - return OpenRTM_aist.Time().getTime() - self._offset - - # virtual bool settime(coil::TimeValue clocktime); - def settime(self, clocktime): - guard = OpenRTM_aist.ScopedLock(self._offsetMutex) - self._offset = OpenRTM_aist.Time().getTime() - clocktime - return True + """ + """ + + def __init__(self): + self._offset = OpenRTM_aist.TimeValue(0.0) + self._offsetMutex = threading.RLock() + return + + # virtual coil::TimeValue gettime() const; + + def gettime(self): + guard = OpenRTM_aist.ScopedLock(self._offsetMutex) + return OpenRTM_aist.Time().getTime() - self._offset + + # virtual bool settime(coil::TimeValue clocktime); + def settime(self, clocktime): + guard = OpenRTM_aist.ScopedLock(self._offsetMutex) + self._offset = OpenRTM_aist.Time().getTime() - clocktime + return True + clockmgr = None clockmgr_mutex = threading.RLock() ## # @if jp -# @class Хʥå饹 +# @class グローバルなクロック管理クラス。 # -# Υ饹ϥХ˥å֥Ȥ󶡤륷󥰥ȥ -# 饹Ǥ롣getClocK(å̾) ˤ IClock Υå -# Ȥ֤Ѳǽʥå "system", "logical" -# "adjusted" ΣǤ롣 +# このクラスはグローバルにクロックオブジェクトを提供するシングルトン +# クラスである。getClocK(クロック名) により IClock 型のクロックオブ +# ジェクトを返す。利用可能なクロックは "system", "logical" および +# "adjusted" の3種類である。 # # @else # @brief A global clock management class @@ -188,34 +189,35 @@ def settime(self, clocktime): # available. # # @endif -class ClockManager: - """ - """ - - def __init__(self): - self._systemClock = SystemClock() - self._logicalClock = LogicalClock() - self._adjustedClock = AdjustedClock() - return - - def getClock(self, clocktype): - if clocktype == "logical": - return self._logicalClock - elif clocktype == "adjusted": - return self._adjustedClock - elif clocktype == "system": - return self._systemClock - - return self._systemClock - - def instance(): - global clockmgr - global clockmgr_mutex - - if not clockmgr: - guard = OpenRTM_aist.ScopedLock(clockmgr_mutex) - clockmgr = ClockManager() - - return clockmgr - instance = staticmethod(instance) + +class ClockManager: + """ + """ + + def __init__(self): + self._systemClock = SystemClock() + self._logicalClock = LogicalClock() + self._adjustedClock = AdjustedClock() + return + + def getClock(self, clocktype): + if clocktype == "logical": + return self._logicalClock + elif clocktype == "adjusted": + return self._adjustedClock + elif clocktype == "system": + return self._systemClock + + return self._systemClock + + def instance(): + global clockmgr + global clockmgr_mutex + + if not clockmgr: + guard = OpenRTM_aist.ScopedLock(clockmgr_mutex) + clockmgr = ClockManager() + + return clockmgr + instance = staticmethod(instance) diff --git a/OpenRTM_aist/ComponentActionListener.py b/OpenRTM_aist/ComponentActionListener.py index 02d19d43..007c83c0 100644 --- a/OpenRTM_aist/ComponentActionListener.py +++ b/OpenRTM_aist/ComponentActionListener.py @@ -1,5 +1,5 @@ #!/usr/bin/env python -# -*- coding: euc-jp -*- +# -*- coding: utf-8 -*- ## # @file ComponentActionListener.py @@ -14,58 +14,58 @@ # All rights reserved. -#============================================================ +# ============================================================ ## # @if jp -# @brief PreComponentActionListener Υ +# @brief PreComponentActionListener のタイプ # -# - PRE_ON_INITIALIZE: onInitialize ľ -# - PRE_ON_FINALIZE: onFinalize ľ -# - PRE_ON_STARTUP: onStartup ľ -# - PRE_ON_SHUTDOWN: onShutdown ľ -# - PRE_ON_ACTIVATED: onActivated ľ -# - PRE_ON_DEACTIVATED: onDeactivated ľ -# - PRE_ON_ABORTING: onAborted ľ -# - PRE_ON_ERROR: onError ľ -# - PRE_ON_RESET: onReset ľ -# - PRE_ON_EXECUTE: onExecute ľ -# - PRE_ON_STATE_UPDATE: onStateUpdate ľ -# - PRE_ON_RATE_CHANGED: onRateChanged ľ +# - PRE_ON_INITIALIZE: onInitialize 直前 +# - PRE_ON_FINALIZE: onFinalize 直前 +# - PRE_ON_STARTUP: onStartup 直前 +# - PRE_ON_SHUTDOWN: onShutdown 直前 +# - PRE_ON_ACTIVATED: onActivated 直前 +# - PRE_ON_DEACTIVATED: onDeactivated 直前 +# - PRE_ON_ABORTING: onAborted 直前 +# - PRE_ON_ERROR: onError 直前 +# - PRE_ON_RESET: onReset 直前 +# - PRE_ON_EXECUTE: onExecute 直前 +# - PRE_ON_STATE_UPDATE: onStateUpdate 直前 +# - PRE_ON_RATE_CHANGED: onRateChanged 直前 # # @else -# @brief The types of ConnectorDataListener -# +# @brief The types of PreComponentActionListenerType +# # @endif class PreComponentActionListenerType: - """ - """ - - def __init__(self): - pass - - PRE_ON_INITIALIZE = 0 - PRE_ON_FINALIZE = 1 - PRE_ON_STARTUP = 2 - PRE_ON_SHUTDOWN = 3 - PRE_ON_ACTIVATED = 4 - PRE_ON_DEACTIVATED = 5 - PRE_ON_ABORTING = 6 - PRE_ON_ERROR = 7 - PRE_ON_RESET = 8 - PRE_ON_EXECUTE = 9 - PRE_ON_STATE_UPDATE = 10 - PRE_ON_RATE_CHANGED = 11 - PRE_COMPONENT_ACTION_LISTENER_NUM = 12 + """ + """ + + def __init__(self): + pass + + PRE_ON_INITIALIZE = 0 + PRE_ON_FINALIZE = 1 + PRE_ON_STARTUP = 2 + PRE_ON_SHUTDOWN = 3 + PRE_ON_ACTIVATED = 4 + PRE_ON_DEACTIVATED = 5 + PRE_ON_ABORTING = 6 + PRE_ON_ERROR = 7 + PRE_ON_RESET = 8 + PRE_ON_EXECUTE = 9 + PRE_ON_STATE_UPDATE = 10 + PRE_ON_RATE_CHANGED = 11 + PRE_COMPONENT_ACTION_LISTENER_NUM = 12 ## # @if jp -# @class PreComponentActionListener 饹 -# @brief PreComponentActionListener 饹 +# @class PreComponentActionListener クラス +# @brief PreComponentActionListener クラス # -# OMG RTCͤƤʲΥݡͥȥȤˤĤ -# ơ +# OMG RTC仕様で定義されている以下のコンポーネントアクショントについ +# て、 # # - on_initialize() # - on_finalize() @@ -80,8 +80,8 @@ def __init__(self): # - on_state_update() # - on_rate_changed() # -# ƥб桼ɤƤФľΥߥ -# ǥ뤵ꥹʥ饹δ쥯饹 +# 各アクションに対応するユーザーコードが呼ばれる直前のタイミング +# でコールされるリスナクラスの基底クラス。 # # - PRE_ON_INITIALIZE: # - PRE_ON_FINALIZE: @@ -105,88 +105,87 @@ def __init__(self): # # @endif class PreComponentActionListener: - """ - """ - - def __init__(self): - pass - - ## - # @if jp - # - # @brief PreComponentActionListenerType ʸѴ - # - # PreComponentActionListenerType ʸѴ - # - # @param type Ѵо PreComponentActionListenerType - # - # @return ʸѴ - # - # @else - # - # @brief Convert PreComponentActionListenerType into the string. - # - # Convert PreComponentActionListenerType into the string. - # - # @param type The target PreComponentActionListenerType for transformation - # - # @return Trnasformation result of string representation - # - # @endif - # static const char* toString(PreComponentActionListenerType type) - def toString(type): - typeString = ["PRE_ON_INITIALIZE", - "PRE_ON_FINALIZE", - "PRE_ON_STARTUP", - "PRE_ON_SHUTDOWN", - "PRE_ON_ACTIVATED", - "PRE_ON_DEACTIVATED", - "PRE_ON_ABORTING", - "PRE_ON_ERROR", - "PRE_ON_RESET", - "PRE_ON_EXECUTE", - "PRE_ON_STATE_UPDATE", - "PRE_ON_RATE_CHANGED", - "PRE_COMPONENT_ACTION_LISTENER_NUM"] - if type < PreComponentActionListenerType.PRE_COMPONENT_ACTION_LISTENER_NUM: - return typeString[type] - - return "" - toString = staticmethod(toString) - - ## - # @if jp - # @brief ǥȥ饯 - # @else - # @brief Destructor - # @endif - def __del__(self): - pass - - ## - # @if jp - # - # @brief ۥХåؿ - # - # PreComponentActionListener ΥХåؿ - # - # @else - # - # @brief Virtual Callback function - # - # This is a the Callback function for PreComponentActionListener. - # - # @endif - # virtual void operator()(UniqueId ec_id) = 0; - def __call__(self, ec_id): - pass - - -#============================================================ + """ + """ + + def __init__(self): + pass + + ## + # @if jp + # + # @brief PreComponentActionListenerType を文字列に変換 + # + # PreComponentActionListenerType を文字列に変換する + # + # @param type 変換対象 PreComponentActionListenerType + # + # @return 文字列変換結果 + # + # @else + # + # @brief Convert PreComponentActionListenerType into the string. + # + # Convert PreComponentActionListenerType into the string. + # + # @param type The target PreComponentActionListenerType for transformation + # + # @return Trnasformation result of string representation + # + # @endif + # static const char* toString(PreComponentActionListenerType type) + def toString(status): + typeString = ["PRE_ON_INITIALIZE", + "PRE_ON_FINALIZE", + "PRE_ON_STARTUP", + "PRE_ON_SHUTDOWN", + "PRE_ON_ACTIVATED", + "PRE_ON_DEACTIVATED", + "PRE_ON_ABORTING", + "PRE_ON_ERROR", + "PRE_ON_RESET", + "PRE_ON_EXECUTE", + "PRE_ON_STATE_UPDATE", + "PRE_ON_RATE_CHANGED"] + if status < len(typeString): + return typeString[status] + + return "" + toString = staticmethod(toString) + + ## + # @if jp + # @brief デストラクタ + # @else + # @brief Destructor + # @endif + def __del__(self): + pass + + ## + # @if jp + # + # @brief 仮想コールバック関数 + # + # PreComponentActionListener のコールバック関数 + # + # @else + # + # @brief Virtual Callback function + # + # This is a the Callback function for PreComponentActionListener. + # + # @endif + # virtual void operator()(UniqueId ec_id) = 0; + def __call__(self, ec_id): + pass + + +# ============================================================ ## # @if jp -# @brief PostCompoenntActionListener Υ +# @brief PostCompoenntActionListener のタイプ # # - POST_ON_INITIALIZE: # - POST_ON_FINALIZE: @@ -202,38 +201,38 @@ def __call__(self, ec_id): # - POST_ON_RATE_CHANGED: # # @else -# @brief The types of ConnectorDataListener -# +# @brief The types of PostComponentActionListenerType +# # @endif class PostComponentActionListenerType: - """ - """ - def __init__(self): - pass - - POST_ON_INITIALIZE = 0 - POST_ON_FINALIZE = 1 - POST_ON_STARTUP = 2 - POST_ON_SHUTDOWN = 3 - POST_ON_ACTIVATED = 4 - POST_ON_DEACTIVATED = 5 - POST_ON_ABORTING = 6 - POST_ON_ERROR = 7 - POST_ON_RESET = 8 - POST_ON_EXECUTE = 9 - POST_ON_STATE_UPDATE = 10 - POST_ON_RATE_CHANGED = 11 - POST_COMPONENT_ACTION_LISTENER_NUM = 12 - + """ + """ + + def __init__(self): + pass + + POST_ON_INITIALIZE = 0 + POST_ON_FINALIZE = 1 + POST_ON_STARTUP = 2 + POST_ON_SHUTDOWN = 3 + POST_ON_ACTIVATED = 4 + POST_ON_DEACTIVATED = 5 + POST_ON_ABORTING = 6 + POST_ON_ERROR = 7 + POST_ON_RESET = 8 + POST_ON_EXECUTE = 9 + POST_ON_STATE_UPDATE = 10 + POST_ON_RATE_CHANGED = 11 + POST_COMPONENT_ACTION_LISTENER_NUM = 12 ## # @if jp -# @class PostComponentActionListener 饹 -# @brief PostComponentActionListener 饹 +# @class PostComponentActionListener クラス +# @brief PostComponentActionListener クラス # -# OMG RTCͤƤʲΥݡͥȥȤˤĤ -# ơ +# OMG RTC仕様で定義されている以下のコンポーネントアクショントについ +# て、 # # - on_initialize() # - on_finalize() @@ -248,8 +247,8 @@ def __init__(self): # - on_state_update() # - on_rate_changed() # -# ƥб桼ɤƤФľΥߥ -# ǥ뤵ꥹʥ饹δ쥯饹 +# 各アクションに対応するユーザーコードが呼ばれる直前のタイミング +# でコールされるリスなクラスの基底クラス。 # # - POST_ON_INITIALIZE: # - POST_ON_FINALIZE: @@ -273,117 +272,114 @@ def __init__(self): # # @endif class PostComponentActionListener: - """ - """ - - def __init__(self): - pass - - ## - # @if jp - # - # @brief PostComponentActionListenerType ʸѴ - # - # PostComponentActionListenerType ʸѴ - # - # @param type Ѵо PostComponentActionListenerType - # - # @return ʸѴ - # - # @else - # - # @brief Convert PostComponentActionListenerType into the string. - # - # Convert PostComponentActionListenerType into the string. - # - # @param type The target PostComponentActionListenerType for transformation - # - # @return Trnasformation result of string representation - # - # @endif - # static const char* toString(PostComponentActionListenerType type) - def toString(type): - typeString = ["POST_ON_INITIALIZE", - "POST_ON_FINALIZE", - "POST_ON_STARTUP", - "POST_ON_SHUTDOWN", - "POST_ON_ACTIVATED", - "POST_ON_DEACTIVATED", - "POST_ON_ABORTING", - "POST_ON_ERROR", - "POST_ON_RESET", - "POST_ON_EXECUTE", - "POST_ON_STATE_UPDATE", - "POST_ON_RATE_CHANGED", - "POST_COMPONENT_ACTION_LISTENER_NUM"] - if type < PostComponentActionListenerType.POST_COMPONENT_ACTION_LISTENER_NUM: - return typeString[type] - return ""; - - toString = staticmethod(toString) - - ## - # @if jp - # @brief ǥȥ饯 - # @else - # @brief Destructor - # @endif - def __del__(self): - pass - - ## - # @if jp - # - # @brief ۥХåؿ - # - # PostComponentActionListener ΥХåؿ - # - # @else - # - # @brief Virtual Callback function - # - # This is a the Callback function for PostComponentActionListener. - # - # @endif - #virtual void operator()(UniqueId ec_id, - # ReturnCode_t ret) = 0; - def __call__(self, ec_id, ret): - pass - - - -#============================================================ + """ + """ + + def __init__(self): + pass + + ## + # @if jp + # + # @brief PostComponentActionListenerType を文字列に変換 + # + # PostComponentActionListenerType を文字列に変換する + # + # @param type 変換対象 PostComponentActionListenerType + # + # @return 文字列変換結果 + # + # @else + # + # @brief Convert PostComponentActionListenerType into the string. + # + # Convert PostComponentActionListenerType into the string. + # + # @param type The target PostComponentActionListenerType for transformation + # + # @return Trnasformation result of string representation + # + # @endif + # static const char* toString(PostComponentActionListenerType type) + def toString(status): + typeString = ["POST_ON_INITIALIZE", + "POST_ON_FINALIZE", + "POST_ON_STARTUP", + "POST_ON_SHUTDOWN", + "POST_ON_ACTIVATED", + "POST_ON_DEACTIVATED", + "POST_ON_ABORTING", + "POST_ON_ERROR", + "POST_ON_RESET", + "POST_ON_EXECUTE", + "POST_ON_STATE_UPDATE", + "POST_ON_RATE_CHANGED"] + if status < len(typeString): + return typeString[status] + return "" + + toString = staticmethod(toString) + + ## + # @if jp + # @brief デストラクタ + # @else + # @brief Destructor + # @endif + def __del__(self): + pass + + ## + # @if jp + # + # @brief 仮想コールバック関数 + # + # PostComponentActionListener のコールバック関数 + # + # @else + # + # @brief Virtual Callback function + # + # This is a the Callback function for PostComponentActionListener. + # + # @endif + # virtual void operator()(UniqueId ec_id, + # ReturnCode_t ret) = 0; + def __call__(self, ec_id, ret): + pass + + +# ============================================================ ## # @if jp -# @brief PortActionListener Υ +# @brief PortActionListener のタイプ # -# - ADD_PORT: Port ɲû -# - REMOVE_PORT: Port +# - ADD_PORT: Port 追加時 +# - REMOVE_PORT: Port 削除時 # # @else # @brief The types of PortActionListener -# +# # @endif class PortActionListenerType: - """ - """ - - def __init__(self): - pass + """ + """ - ADD_PORT = 0 - REMOVE_PORT = 1 - PORT_ACTION_LISTENER_NUM = 2 + def __init__(self): + pass + ADD_PORT = 0 + REMOVE_PORT = 1 + PORT_ACTION_LISTENER_NUM = 2 ## # @if jp -# @class PortActionListener 饹 -# @brief PortActionListener 饹 +# @class PortActionListener クラス +# @brief PortActionListener クラス # -# ƥб桼ɤƤФľΥߥ -# ǥ뤵ꥹʥ饹δ쥯饹 +# 各アクションに対応するユーザーコードが呼ばれる直前のタイミング +# でコールされるリスなクラスの基底クラス。 # # - ADD_PORT: # - REMOVE_PORT: @@ -397,103 +393,103 @@ def __init__(self): # # @endif class PortActionListener: - """ - """ - - def __init__(self): - pass - - ## - # @if jp - # - # @brief PortActionListenerType ʸѴ - # - # PortActionListenerType ʸѴ - # - # @param type Ѵо PortActionListenerType - # - # @return ʸѴ - # - # @else - # - # @brief Convert PortActionListenerType into the string. - # - # Convert PortActionListenerType into the string. - # - # @param type The target PortActionListenerType for transformation - # - # @return Trnasformation result of string representation - # - # @endif - #static const char* toString(PortActionListenerType type) - def toString(type): - typeString = ["ADD_PORT", - "REMOVE_PORT", - "PORT_ACTION_LISTENER_NUM"] - if type < PortActionListenerType.PORT_ACTION_LISTENER_NUM: - return typeString[type] - return "" - - toString = staticmethod(toString) - - ## - # @if jp - # @brief ǥȥ饯 - # @else - # @brief Destructor - # @endif - #virtual ~PortActionListener(); - def __del__(self): - pass - - ## - # @if jp - # - # @brief ۥХåؿ - # - # PortActionListener ΥХåؿ - # - # @else - # - # @brief Virtual Callback function - # - # This is a the Callback function for PortActionListener - # - # @endif - #virtual void operator()(const ::RTC::PortProfile& pprof) = 0; - def __call__(self, pprof): - pass - - -#============================================================ + """ + """ + + def __init__(self): + pass + + ## + # @if jp + # + # @brief PortActionListenerType を文字列に変換 + # + # PortActionListenerType を文字列に変換する + # + # @param type 変換対象 PortActionListenerType + # + # @return 文字列変換結果 + # + # @else + # + # @brief Convert PortActionListenerType into the string. + # + # Convert PortActionListenerType into the string. + # + # @param type The target PortActionListenerType for transformation + # + # @return Trnasformation result of string representation + # + # @endif + # static const char* toString(PortActionListenerType type) + def toString(status): + typeString = ["ADD_PORT", + "REMOVE_PORT"] + if status < len(typeString): + return typeString[status] + return "" + + toString = staticmethod(toString) + + ## + # @if jp + # @brief デストラクタ + # @else + # @brief Destructor + # @endif + # virtual ~PortActionListener(); + def __del__(self): + pass + + ## + # @if jp + # + # @brief 仮想コールバック関数 + # + # PortActionListener のコールバック関数 + # + # @else + # + # @brief Virtual Callback function + # + # This is a the Callback function for PortActionListener + # + # @endif + # virtual void operator()(const ::RTC::PortProfile& pprof) = 0; + def __call__(self, pprof): + pass + + +# ============================================================ ## # @if jp -# @brief ExecutionContextActionListener Υ +# @brief ExecutionContextActionListener のタイプ # -# - EC_ATTACHED: ExecutionContext ɲû -# - EC_DETACHED: ExecutionContext +# - EC_ATTACHED: ExecutionContext 追加時 +# - EC_DETACHED: ExecutionContext 削除時 # # @else # @brief The types of ExecutionContextActionListener -# +# # @endif class ExecutionContextActionListenerType: - """ - """ - def __init__(self): - pass + """ + """ + + def __init__(self): + pass - EC_ATTACHED = 0 - EC_DETACHED = 1 - EC_ACTION_LISTENER_NUM = 2 + EC_ATTACHED = 0 + EC_DETACHED = 1 + EC_ACTION_LISTENER_NUM = 2 ## # @if jp -# @class ExecutionContextActionListener 饹 -# @brief ExecutionContextActionListener 饹 +# @class ExecutionContextActionListener クラス +# @brief ExecutionContextActionListener クラス # -# ƥб桼ɤƤФľΥߥ -# ǥ뤵ꥹʥ饹δ쥯饹 +# 各アクションに対応するユーザーコードが呼ばれる直前のタイミング +# でコールされるリスなクラスの基底クラス。 # # - ADD_PORT: # - REMOVE_PORT: @@ -506,90 +502,84 @@ def __init__(self): # provides callbacks for various events in rtobject. # # @endif + + class ExecutionContextActionListener: - """ - """ - - def __init__(self): - pass - - - ## - # @if jp - # - # @brief ExecutionContextActionListenerType ʸѴ - # - # ExecutionContextActionListenerType ʸѴ - # - # @param type Ѵо ExecutionContextActionListenerType - # - # @return ʸѴ - # - # @else - # - # @brief Convert ExecutionContextActionListenerType into the string. - # - # Convert ExecutionContextActionListenerType into the string. - # - # @param type The target ExecutionContextActionListenerType for transformation - # - # @return Trnasformation result of string representation - # - # @endif - #static const char* toString(ExecutionContextActionListenerType type) - def toString(type): - typeString = ["ATTACH_EC", - "DETACH_EC", - "EC_ACTION_LISTENER_NUM"] - if type < ExecutionContextActionListenerType.EC_ACTION_LISTENER_NUM: - return typeString[type] - return "" - - toString = staticmethod(toString) - - - ## - # @if jp - # @brief ǥȥ饯 - # @else - # @brief Destructor - # @endif - def __del__(self): - pass - - ## - # @if jp - # - # @brief ۥХåؿ - # - # ExecutionContextActionListener ΥХåؿ - # - # @else - # - # @brief Virtual Callback function - # - # This is a the Callback function for ExecutionContextActionListener - # - # @endif - #virtual void operator()(UniqueId ec_id) = 0; - def __call__(self, ec_id): - pass - - -class Entry: - def __init__(self,listener, autoclean): - self.listener = listener - self.autoclean = autoclean - return - - -#============================================================ + """ + """ + + def __init__(self): + pass + + ## + # @if jp + # + # @brief ExecutionContextActionListenerType を文字列に変換 + # + # ExecutionContextActionListenerType を文字列に変換する + # + # @param type 変換対象 ExecutionContextActionListenerType + # + # @return 文字列変換結果 + # + # @else + # + # @brief Convert ExecutionContextActionListenerType into the string. + # + # Convert ExecutionContextActionListenerType into the string. + # + # @param type The target ExecutionContextActionListenerType for transformation + # + # @return Trnasformation result of string representation + # + # @endif + # static const char* toString(ExecutionContextActionListenerType type) + + def toString(status): + typeString = ["ATTACH_EC", + "DETACH_EC"] + if status < len(typeString): + return typeString[status] + return "" + + toString = staticmethod(toString) + + ## + # @if jp + # @brief デストラクタ + # @else + # @brief Destructor + # @endif + + def __del__(self): + pass + + ## + # @if jp + # + # @brief 仮想コールバック関数 + # + # ExecutionContextActionListener のコールバック関数 + # + # @else + # + # @brief Virtual Callback function + # + # This is a the Callback function for ExecutionContextActionListener + # + # @endif + # virtual void operator()(UniqueId ec_id) = 0; + def __call__(self, ec_id): + pass + + +# ============================================================ ## # @if jp -# @class PreComponentActionListenerHolder -# @brief PreComponentActionListener ۥ饹 +# @class PreComponentActionListenerHolder +# @brief PreComponentActionListener ホルダクラス # -# ʣ PreComponentActionListener ݻ륯饹 +# 複数の PreComponentActionListener を保持し管理するクラス。 # # @else # @class PreComponentActionListenerHolder @@ -600,115 +590,105 @@ def __init__(self,listener, autoclean): # # @endif class PreComponentActionListenerHolder: - """ - """ - - ## - # @if jp - # @brief 󥹥ȥ饯 - # @else - # @brief Constructor - # @endif - def __init__(self): - self._listeners = [] - return - - - ## - # @if jp - # @brief ǥȥ饯 - # @else - # @brief Destructor - # @endif - def __del__(self): - for (idx, listener) in enumerate(self._listeners): - if listener.autoclean: - self._listeners[idx] = None - return - - ## - # @if jp - # - # @brief ꥹʡɲ - # - # ꥹʡɲä롣 - # - # @param listener ɲäꥹ - # @param autoclean true:ǥȥ饯Ǻ, - # false:ǥȥ饯Ǻʤ - # @else - # - # @brief Add the listener. - # - # This method adds the listener. - # - # @param listener Added listener - # @param autoclean true:The listener is deleted at the destructor., - # false:The listener is not deleted at the destructor. - # @endif - #void addListener(PreComponentActionListener* listener, bool autoclean); - def addListener(self, listener, autoclean): - self._listeners.append(Entry(listener, autoclean)) - return - - ## - # @if jp - # - # @brief ꥹʡκ - # - # ꥹʤ롣 - # - # @param listener ꥹ - # @else - # - # @brief Remove the listener. - # - # This method removes the listener. - # - # @param listener Removed listener - # @endif - #void removeListener(PreComponentActionListener* listener); - def removeListener(self, listener): - len_ = len(self._listeners) - for i in range(len_): - idx = (len_ - 1) - i - if self._listeners[idx].listener == listener: - if self._listeners[idx].autoclean: - self._listeners[idx].listener = None - del self._listeners[idx] - return - return - - ## - # @if jp - # - # @brief ꥹʡΤ - # - # ϿƤꥹʤΥХå᥽åɤƤӽФ - # - # @param info ConnectorInfo - # @else - # - # @brief Notify listeners. - # - # This calls the Callback method of the registered listener. - # - # @param info ConnectorInfo - # @endif - #void notify(UniqueId ec_id); - def notify(self, ec_id): - for listener in self._listeners: - listener.listener(ec_id) - return - - + """ + """ + + ## + # @if jp + # @brief コンストラクタ + # @else + # @brief Constructor + # @endif + def __init__(self): + self._listeners = [] + return + + ## + # @if jp + # @brief デストラクタ + # @else + # @brief Destructor + # @endif + + def __del__(self): + pass + + ## + # @if jp + # + # @brief リスナーの追加 + # + # リスナーを追加する。 + # + # @param listener 追加するリスナ + # @else + # + # @brief Add the listener. + # + # This method adds the listener. + # + # @param listener Added listener + # @endif + # void addListener(PreComponentActionListener* listener); + def addListener(self, listener): + self._listeners.append(listener) + return + + ## + # @if jp + # + # @brief リスナーの削除 + # + # リスナを削除する。 + # + # @param listener 削除するリスナ + # @else + # + # @brief Remove the listener. + # + # This method removes the listener. + # + # @param listener Removed listener + # @endif + # void removeListener(PreComponentActionListener* listener); + def removeListener(self, listener): + len_ = len(self._listeners) + for i in range(len_): + idx = (len_ - 1) - i + if self._listeners[idx] == listener: + del self._listeners[idx] + return + return + + ## + # @if jp + # + # @brief リスナーへ通知する + # + # 登録されているリスナのコールバックメソッドを呼び出す。 + # + # @param info ConnectorInfo + # @else + # + # @brief Notify listeners. + # + # This calls the Callback method of the registered listener. + # + # @param info ConnectorInfo + # @endif + # void notify(UniqueId ec_id); + def notify(self, ec_id): + for listener in self._listeners: + listener(ec_id) + return + ## # @if jp # @class PostComponentActionListenerHolder -# @brief PostComponentActionListener ۥ饹 +# @brief PostComponentActionListener ホルダクラス # -# ʣ PostComponentActionListener ݻ륯饹 +# 複数の PostComponentActionListener を保持し管理するクラス。 # # @else # @class PostComponentActionListenerHolder @@ -719,119 +699,109 @@ def notify(self, ec_id): # # @endif class PostComponentActionListenerHolder: - """ - """ - - ## - # @if jp - # @brief 󥹥ȥ饯 - # @else - # @brief Constructor - # @endif - def __init__(self): - self._listeners = [] - return - - - ## - # @if jp - # @brief ǥȥ饯 - # @else - # @brief Destructor - # @endif - def __del__(self): - for (idx, listener) in enumerate(self._listeners): - if listener.autoclean: - self._listeners[idx] = None - return - - ## - # @if jp - # - # @brief ꥹʡɲ - # - # ꥹʡɲä롣 - # - # @param listener ɲäꥹ - # @param autoclean true:ǥȥ饯Ǻ, - # false:ǥȥ饯Ǻʤ - # @else - # - # @brief Add the listener. - # - # This method adds the listener. - # - # @param listener Added listener - # @param autoclean true:The listener is deleted at the destructor., - # false:The listener is not deleted at the destructor. - # @endif - #void addListener(PostComponentActionListener* listener, bool autoclean); - def addListener(self, listener, autoclean): - self._listeners.append(Entry(listener, autoclean)) - return - - ## - # @if jp - # - # @brief ꥹʡκ - # - # ꥹʤ롣 - # - # @param listener ꥹ - # @else - # - # @brief Remove the listener. - # - # This method removes the listener. - # - # @param listener Removed listener - # @endif - #void removeListener(PostComponentActionListener* listener); - def removeListener(self, listener): - len_ = len(self._listeners) - for i in range(len_): - idx = (len_ - 1) - i - if self._listeners[idx].listener == listener: - if self._listeners[idx].autoclean: - self._listeners[idx].listener = None - del self._listeners[idx] - return - return - - - ## - # @if jp - # - # @brief ꥹʡΤ - # - # ϿƤꥹʤΥХå᥽åɤƤӽФ - # - # @param info ConnectorInfo - # @param cdrdata ǡ - # @else - # - # @brief Notify listeners. - # - # This calls the Callback method of the registered listener. - # - # @param info ConnectorInfo - # @param cdrdata Data - # @endif - #void notify(UniqueId ec_id, ReturnCode_t ret); - def notify(self, ec_id, ret): - for listener in self._listeners: - listener.listener(ec_id, ret) - return - - - -#============================================================ + """ + """ + + ## + # @if jp + # @brief コンストラクタ + # @else + # @brief Constructor + # @endif + def __init__(self): + self._listeners = [] + return + + ## + # @if jp + # @brief デストラクタ + # @else + # @brief Destructor + # @endif + + def __del__(self): + return + + ## + # @if jp + # + # @brief リスナーの追加 + # + # リスナーを追加する。 + # + # @param listener 追加するリスナ + # @else + # + # @brief Add the listener. + # + # This method adds the listener. + # + # @param listener Added listener + # @endif + # void addListener(PostComponentActionListener* listener); + def addListener(self, listener): + self._listeners.append(listener) + return + + ## + # @if jp + # + # @brief リスナーの削除 + # + # リスナを削除する。 + # + # @param listener 削除するリスナ + # @else + # + # @brief Remove the listener. + # + # This method removes the listener. + # + # @param listener Removed listener + # @endif + # void removeListener(PostComponentActionListener* listener); + def removeListener(self, listener): + len_ = len(self._listeners) + for i in range(len_): + idx = (len_ - 1) - i + if self._listeners[idx] == listener: + del self._listeners[idx] + return + return + + ## + # @if jp + # + # @brief リスナーへ通知する + # + # 登録されているリスナのコールバックメソッドを呼び出す。 + # + # @param info ConnectorInfo + # @param cdrdata データ + # @else + # + # @brief Notify listeners. + # + # This calls the Callback method of the registered listener. + # + # @param info ConnectorInfo + # @param cdrdata Data + # @endif + # void notify(UniqueId ec_id, ReturnCode_t ret); + + def notify(self, ec_id, ret): + for listener in self._listeners: + listener(ec_id, ret) + return + + +# ============================================================ ## # @if jp # @class PortActionListenerHolder -# @brief PortActionListener ۥ饹 +# @brief PortActionListener ホルダクラス # -# ʣ PortActionListener ݻ륯饹 +# 複数の PortActionListener を保持し管理するクラス。 # # @else # @class PortActionListenerHolder @@ -842,118 +812,108 @@ def notify(self, ec_id, ret): # # @endif class PortActionListenerHolder: - """ - """ - - ## - # @if jp - # @brief 󥹥ȥ饯 - # @else - # @brief Constructor - # @endif - def __init__(self): - self._listeners = [] - return - - - ## - # @if jp - # @brief ǥȥ饯 - # @else - # @brief Destructor - # @endif - def __del__(self): - for (idx, listener) in enumerate(self._listeners): - if listener.autoclean: - self._listeners[idx] = None - pass - - ## - # @if jp - # - # @brief ꥹʡɲ - # - # ꥹʡɲä롣 - # - # @param listener ɲäꥹ - # @param autoclean true:ǥȥ饯Ǻ, - # false:ǥȥ饯Ǻʤ - # @else - # - # @brief Add the listener. - # - # This method adds the listener. - # - # @param listener Added listener - # @param autoclean true:The listener is deleted at the destructor., - # false:The listener is not deleted at the destructor. - # @endif - #void addListener(PortActionListener* listener, bool autoclean); - def addListener(self, listener, autoclean): - self._listeners.append(Entry(listener, autoclean)) - return - - - ## - # @if jp - # - # @brief ꥹʡκ - # - # ꥹʤ롣 - # - # @param listener ꥹ - # @else - # - # @brief Remove the listener. - # - # This method removes the listener. - # - # @param listener Removed listener - # @endif - #void removeListener(PortActionListener* listener); - def removeListener(self, listener): - len_ = len(self._listeners) - for i in range(len_): - idx = (len_ - 1) - i - if self._listeners[idx].listener == listener: - if self._listeners[idx].autoclean: - self._listeners[idx].listener = None - del self._listeners[idx] - return - return - - ## - # @if jp - # - # @brief ꥹʡΤ - # - # ϿƤꥹʤΥХå᥽åɤƤӽФ - # - # @param info ConnectorInfo - # @param cdrdata ǡ - # @else - # - # @brief Notify listeners. - # - # This calls the Callback method of the registered listener. - # - # @param info ConnectorInfo - # @param cdrdata Data - # @endif - #void notify(const RTC::PortProfile& pprofile); - def notify(self, pprofile): - for listener in self._listeners: - listener.listener(pprofile) - return - - + """ + """ + + ## + # @if jp + # @brief コンストラクタ + # @else + # @brief Constructor + # @endif + def __init__(self): + self._listeners = [] + return + + ## + # @if jp + # @brief デストラクタ + # @else + # @brief Destructor + # @endif + + def __del__(self): + pass + + ## + # @if jp + # + # @brief リスナーの追加 + # + # リスナーを追加する。 + # + # @param listener 追加するリスナ + # @else + # + # @brief Add the listener. + # + # This method adds the listener. + # + # @param listener Added listener + # @endif + # void addListener(PortActionListener* listener); + def addListener(self, listener): + self._listeners.append(listener) + return + + ## + # @if jp + # + # @brief リスナーの削除 + # + # リスナを削除する。 + # + # @param listener 削除するリスナ + # @else + # + # @brief Remove the listener. + # + # This method removes the listener. + # + # @param listener Removed listener + # @endif + # void removeListener(PortActionListener* listener); + + def removeListener(self, listener): + len_ = len(self._listeners) + for i in range(len_): + idx = (len_ - 1) - i + if self._listeners[idx] == listener: + del self._listeners[idx] + return + return + + ## + # @if jp + # + # @brief リスナーへ通知する + # + # 登録されているリスナのコールバックメソッドを呼び出す。 + # + # @param info ConnectorInfo + # @param cdrdata データ + # @else + # + # @brief Notify listeners. + # + # This calls the Callback method of the registered listener. + # + # @param info ConnectorInfo + # @param cdrdata Data + # @endif + # void notify(const RTC::PortProfile& pprofile); + def notify(self, pprofile): + for listener in self._listeners: + listener(pprofile) + return + ## # @if jp # @class ExecutionContextActionListenerHolder -# @brief ExecutionContextActionListener ۥ饹 +# @brief ExecutionContextActionListener ホルダクラス # -# ʣ ExecutionContextActionListener ݻ륯饹 +# 複数の ExecutionContextActionListener を保持し管理するクラス。 # # @else # @class ExecutionContextActionListenerHolder @@ -964,118 +924,108 @@ def notify(self, pprofile): # # @endif class ExecutionContextActionListenerHolder: - """ - """ - - ## - # @if jp - # @brief 󥹥ȥ饯 - # @else - # @brief Constructor - # @endif - def __init__(self): - self._listeners = [] - return - - - ## - # @if jp - # @brief ǥȥ饯 - # @else - # @brief Destructor - # @endif - def __del__(self): - for (idx, listener) in enumerate(self._listeners): - if listener.autoclean: - self._listeners[idx] = None - pass - - - ## - # @if jp - # - # @brief ꥹʡɲ - # - # ꥹʡɲä롣 - # - # @param listener ɲäꥹ - # @param autoclean true:ǥȥ饯Ǻ, - # false:ǥȥ饯Ǻʤ - # @else - # - # @brief Add the listener. - # - # This method adds the listener. - # - # @param listener Added listener - # @param autoclean true:The listener is deleted at the destructor., - # false:The listener is not deleted at the destructor. - # @endif - #void addListener(ExecutionContextActionListener* listener, bool autoclean); - def addListener(self, listener, autoclean): - self._listeners.append(Entry(listener, autoclean)) - return - - - ## - # @if jp - # - # @brief ꥹʡκ - # - # ꥹʤ롣 - # - # @param listener ꥹ - # @else - # - # @brief Remove the listener. - # - # This method removes the listener. - # - # @param listener Removed listener - # @endif - #void removeListener(ExecutionContextActionListener* listener); - def removeListener(self, listener): - len_ = len(self._listeners) - for i in range(len_): - idx = (len_ - 1) - i - if self._listeners[idx].listener == listener: - if self._listeners[idx].autoclean: - self._listeners[idx].listener = None - del self._listeners[idx] - return - return - - - ## - # @if jp - # - # @brief ꥹʡΤ - # - # ϿƤꥹʤΥХå᥽åɤƤӽФ - # - # @param info ConnectorInfo - # @param cdrdata ǡ - # @else - # - # @brief Notify listeners. - # - # This calls the Callback method of the registered listener. - # - # @param info ConnectorInfo - # @param cdrdata Data - # @endif - #void notify(UniqueId ec_id); - def notify(self, ec_id): - for listener in self._listeners: - listener.listener(ec_id) - return + """ + """ + ## + # @if jp + # @brief コンストラクタ + # @else + # @brief Constructor + # @endif + def __init__(self): + self._listeners = [] + return + + ## + # @if jp + # @brief デストラクタ + # @else + # @brief Destructor + # @endif + + def __del__(self): + pass + + ## + # @if jp + # + # @brief リスナーの追加 + # + # リスナーを追加する。 + # + # @param listener 追加するリスナ + # @else + # + # @brief Add the listener. + # + # This method adds the listener. + # + # @param listener Added listener + # @endif + # void addListener(ExecutionContextActionListener* listener); + + def addListener(self, listener): + self._listeners.append(listener) + return + + ## + # @if jp + # + # @brief リスナーの削除 + # + # リスナを削除する。 + # + # @param listener 削除するリスナ + # @else + # + # @brief Remove the listener. + # + # This method removes the listener. + # + # @param listener Removed listener + # @endif + # void removeListener(ExecutionContextActionListener* listener); + + def removeListener(self, listener): + len_ = len(self._listeners) + for i in range(len_): + idx = (len_ - 1) - i + if self._listeners[idx] == listener: + del self._listeners[idx] + return + return + + ## + # @if jp + # + # @brief リスナーへ通知する + # + # 登録されているリスナのコールバックメソッドを呼び出す。 + # + # @param info ConnectorInfo + # @param cdrdata データ + # @else + # + # @brief Notify listeners. + # + # This calls the Callback method of the registered listener. + # + # @param info ConnectorInfo + # @param cdrdata Data + # @endif + # void notify(UniqueId ec_id); + + def notify(self, ec_id): + for listener in self._listeners: + listener(ec_id) + return ## # @if jp # @class ComponentActionListeners -# @brief ComponentActionListeners 饹 +# @brief ComponentActionListeners クラス # # # @else @@ -1085,55 +1035,353 @@ def notify(self, ec_id): # # @endif class ComponentActionListeners: - """ - """ + """ + """ + ## + # @if jp + # @brief コンストラクタ + # + # + # @param self + # + # @else + # + # @param self + # + # @endif + + def __init__(self): + + ## + # @if jp + # @brief PreComponentActionListenerTypeリスナ配列 + # PreComponentActionListenerTypeリスナを格納 + # @else + # @brief PreComponentActionListenerType listener array + # The PreComponentActionListenerType listener is stored. + # @endif + self.preaction_num = PreComponentActionListenerType.PRE_COMPONENT_ACTION_LISTENER_NUM + self.preaction_ = [PreComponentActionListenerHolder() + for i in range(self.preaction_num)] + + ## + # @if jp + # @brief PostComponentActionListenerTypeリスナ配列 + # PostComponentActionListenerTypeリスナを格納 + # @else + # @brief PostComponentActionListenerType listener array + # The PostComponentActionListenerType listener is stored. + # @endif + self.postaction_num = PostComponentActionListenerType.POST_COMPONENT_ACTION_LISTENER_NUM + self.postaction_ = [PostComponentActionListenerHolder() + for i in range(self.postaction_num)] + + ## + # @if jp + # @brief PortActionListenerTypeリスナ配列 + # PortActionListenerTypeリスナを格納 + # @else + # @brief PortActionListenerType listener array + # The PortActionListenerType listener is stored. + # @endif + self.portaction_num = PortActionListenerType.PORT_ACTION_LISTENER_NUM + self.portaction_ = [PortActionListenerHolder() + for i in range(self.portaction_num)] + + ## + # @if jp + # @brief ExecutionContextActionListenerTypeリスナ配列 + # ExecutionContextActionListenerTypeリスナを格納 + # @else + # @brief ExecutionContextActionListenerType listener array + # The ExecutionContextActionListenerType listener is stored. + # @endif + self.ecaction_num = ExecutionContextActionListenerType.EC_ACTION_LISTENER_NUM + self.ecaction_ = [ExecutionContextActionListenerHolder() + for i in range(self.ecaction_num)] + + ## + # @if jp + # @brief リスナーの追加 + # + # 指定の種類のPreComponentActionListenerを追加する。 + # + # @param self + # @param ltype リスナの種類 + # @param listener 追加するリスナ + # @return False:指定の種類のリスナが存在しない + # + # @else + # + # @param self + # @param ltype + # @param listener + # @return + # + # @endif + def addPreActionListener(self, ltype, listener): + if ltype < len(self.preaction_): + self.preaction_[ltype].addListener(listener) + return True + return False + + ## + # @if jp + # @brief リスナーの追加 + # + # 指定の種類のPostComponentActionListenerを追加する。 + # + # @param self + # @param ltype リスナの種類 + # @param listener 追加するリスナ + # @return False:指定の種類のリスナが存在しない + # + # @else + # + # @param self + # @param ltype + # @param listener + # @return + # + # @endif + def addPostActionListener(self, ltype, listener): + if ltype < len(self.postaction_): + self.postaction_[ltype].addListener(listener) + return True + return False - def __init__(self): + ## + # @if jp + # @brief リスナーの追加 + # + # 指定の種類のPortActionListenerを追加する。 + # + # @param self + # @param ltype リスナの種類 + # @param listener 追加するリスナ + # @return False:指定の種類のリスナが存在しない + # + # @else + # + # @param self + # @param ltype + # @param listener + # @return + # + # @endif + def addPortActionListener(self, ltype, listener): + if ltype < len(self.portaction_): + self.portaction_[ltype].addListener(listener) + return True + return False + + ## + # @if jp + # @brief リスナーの追加 + # + # 指定の種類のExecutionContextActionListenerを追加する。 + # + # @param self + # @param ltype リスナの種類 + # @param listener 追加するリスナ + # @return False:指定の種類のリスナが存在しない + # + # @else + # + # @param self + # @param ltype + # @param listener + # @return + # + # @endif + def addECActionListener(self, ltype, listener): + if ltype < len(self.ecaction_): + self.ecaction_[ltype].addListener(listener) + return True + return False + + ## + # @if jp + # @brief リスナーの削除 + # + # 指定の種類のPreComponentActionListenerを削除する。 + # + # @param self + # @param ltype リスナの種類 + # @param listener 削除するリスナ + # @return False:指定の種類のリスナが存在しない + # + # @else + # + # @param self + # @param ltype + # @param listener + # @return + # + # @endif + def removePreActionListener(self, ltype, listener): + if ltype < len(self.preaction_): + self.preaction_[ltype].removeListener(listener) + return True + return False + + ## + # @if jp + # @brief リスナーの削除 + # + # 指定の種類のPostComponentActionListenerを削除する。 + # + # @param self + # @param ltype リスナの種類 + # @param listener 削除するリスナ + # @return False:指定の種類のリスナが存在しない + # + # @else + # + # @param self + # @param ltype + # @param listener + # @return + # + # @endif + def removePostActionListener(self, ltype, listener): + if ltype < len(self.postaction_): + self.postaction_[ltype].removeListener(listener) + return True + return False ## # @if jp - # @brief PreComponentActionListenerTypeꥹ - # PreComponentActionListenerTypeꥹʤǼ + # @brief リスナーの削除 + # + # 指定の種類のPortActionListenerを削除する。 + # + # @param self + # @param ltype リスナの種類 + # @param listener 削除するリスナ + # @return False:指定の種類のリスナが存在しない + # # @else - # @brief PreComponentActionListenerType listener array - # The PreComponentActionListenerType listener is stored. + # + # @param self + # @param ltype + # @param listener + # @return + # # @endif - self.preaction_num = PreComponentActionListenerType.PRE_COMPONENT_ACTION_LISTENER_NUM - self.preaction_ = [PreComponentActionListenerHolder() - for i in range(self.preaction_num)] + def removePortActionListener(self, ltype, listener): + if ltype < len(self.portaction_): + self.portaction_[ltype].removeListener(listener) + return True + return False ## # @if jp - # @brief PostComponentActionListenerTypeꥹ - # PostComponentActionListenerTypeꥹʤǼ + # @brief リスナーの削除 + # + # 指定の種類のExecutionContextActionListenerを削除する。 + # + # @param self + # @param ltype リスナの種類 + # @param listener 削除するリスナ + # @return False:指定の種類のリスナが存在しない + # # @else - # @brief PostComponentActionListenerType listener array - # The PostComponentActionListenerType listener is stored. + # + # @param self + # @param ltype + # @param listener + # @return + # # @endif - self.postaction_num = PostComponentActionListenerType.POST_COMPONENT_ACTION_LISTENER_NUM - self.postaction_ = [PostComponentActionListenerHolder() - for i in range(self.postaction_num)] + def removeECActionListener(self, ltype, listener): + if ltype < len(self.ecaction_): + self.ecaction_[ltype].removeListener(listener) + return True + return False ## # @if jp - # @brief PortActionListenerTypeꥹ - # PortActionListenerTypeꥹʤǼ + # @brief リスナーへ通知する + # + # 指定の種類のPreComponentActionListenerのコールバック関数を呼び出す。 + # + # @param self + # @param ltype リスナの種類 + # @param ec_id 実行コンテキストのID + # # @else - # @brief PortActionListenerType listener array - # The PortActionListenerType listener is stored. + # + # @param self + # @param ltype + # @param ec_id + # # @endif - self.portaction_num = PortActionListenerType.PORT_ACTION_LISTENER_NUM - self.portaction_ = [PortActionListenerHolder() - for i in range(self.portaction_num)] - + def notifyPreAction(self, ltype, ec_id): + if ltype < len(self.preaction_): + self.preaction_[ltype].notify(ec_id) + + ## + # @if jp + # @brief リスナーへ通知する + # + # 指定の種類のPostComponentActionListenerのコールバック関数を呼び出す。 + # + # @param self + # @param ltype リスナの種類 + # @param ec_id 実行コンテキストのID + # @param ret リターンコード + # + # @else + # + # @param self + # @param ltype + # @param ec_id + # @param ret + # + # @endif + def notifyPostAction(self, ltype, ec_id, ret): + if ltype < len(self.postaction_): + self.postaction_[ltype].notify(ec_id, ret) + + ## + # @if jp + # @brief リスナーへ通知する + # + # 指定の種類のPortActionListenerのコールバック関数を呼び出す。 + # + # @param self + # @param ltype リスナの種類 + # @param pprofile ポートプロファイル + # + # @else + # + # @param self + # @param ltype + # @param pprofile + # + # @endif + def notifyPortAction(self, ltype, pprofile): + if ltype < len(self.portaction_): + self.portaction_[ltype].notify(pprofile) + ## # @if jp - # @brief ExecutionContextActionListenerTypeꥹ - # ExecutionContextActionListenerTypeꥹʤǼ + # @brief リスナーへ通知する + # + # 指定の種類のExecutionContextActionListenerのコールバック関数を呼び出す。 + # + # @param self + # @param ltype リスナの種類 + # @param ec_id 実行コンテキストのID + # # @else - # @brief ExecutionContextActionListenerType listener array - # The ExecutionContextActionListenerType listener is stored. + # + # @param self + # @param ltype + # @param ec_id + # # @endif - self.ecaction_num = ExecutionContextActionListenerType.EC_ACTION_LISTENER_NUM - self.ecaction_ = [ExecutionContextActionListenerHolder() - for i in range(self.ecaction_num)] + def notifyECAction(self, ltype, ec_id): + if ltype < len(self.ecaction_): + self.ecaction_[ltype].notify(ec_id) diff --git a/OpenRTM_aist/ConfigAdmin.py b/OpenRTM_aist/ConfigAdmin.py index e0750f9a..4ee14d6d 100644 --- a/OpenRTM_aist/ConfigAdmin.py +++ b/OpenRTM_aist/ConfigAdmin.py @@ -1,12 +1,12 @@ #!/usr/bin/env python -# -*- coding: euc-jp -*- +# -*- coding: utf-8 -*- ## # @file ConfigAdmin.py # @brief Configuration Administration classes # @date $Date: 2007/09/04$ # @author Noriaki Ando and Shinji Kurihara -# +# # Copyright (C) 2007-2008 # Task-intelligence Research Group, # Intelligent Systems Research Institute, @@ -15,254 +15,241 @@ # All rights reserved. - - import OpenRTM_aist class OnUpdateCallback: - def __init__(self): - pass - - - def __call__(self, config_set): - pass + def __init__(self): + pass + def __call__(self, config_set): + pass class OnUpdateParamCallback: - def __init__(self): - pass - - - def __call__(self, config_set, config_param): - pass + def __init__(self): + pass + def __call__(self, config_set, config_param): + pass class OnSetConfigurationSetCallback: - def __init__(self): - pass - - - def __call__(self, config_set): - pass + def __init__(self): + pass + def __call__(self, config_set): + pass class OnAddConfigurationAddCallback: - def __init__(self): - pass - - - def __call__(self, config_set): - pass + def __init__(self): + pass + def __call__(self, config_set): + pass class OnRemoveConfigurationSetCallback: - def __init__(self): - pass - - - def __call__(self, config_set): - pass + def __init__(self): + pass + def __call__(self, config_set): + pass class OnActivateSetCallback: - def __init__(self): - pass - - - def __call__(self, config_id): - pass + def __init__(self): + pass + def __call__(self, config_id): + pass ## # @if jp # @class Config -# @brief Config 饹 -# -# ե졼ѥ᡼ξݻ륯饹 +# @brief Config クラス +# +# コンフィギュレーションパラメータの情報を保持するクラス。 # # @since 0.4.0 # # @else # @class Config # @brief Config class -# +# # Class to hold the configuration parameter information. # # @since 0.4.0 # # @endif class Config: - """ - """ - - ## - # @if jp - # - # @brief 󥹥ȥ饯 - # - # 󥹥ȥ饯 - # - # @param self - # @param name ե졼ѥ᡼̾ - # @param var ե졼ѥ᡼Ǽѿ - # @param def_val ʸΥǥե - # @param trans ʸѴؿ(ǥե:None) - # - # @else - # - # @brief Constructor - # - # Constructor - # - # @param self - # @param name Configuration parameter name - # @param var Configuration parameter variable - # @param def_val Default value in string format - # @param trans Function to transform into string format - # - # @endif - def __init__(self, name, var, def_val, trans=None): - self.name = name - self.default_value = def_val - self.string_value = "" - self.callback = None - self._var = var - if trans: - self._trans = trans - else: - self._trans = OpenRTM_aist.stringTo - return - - - ## - # @if jp - # - # @brief ХåΥå - # - # ѿѹ˥뤵륳Хåؿ򥻥åȤ. - # - # @else - # - # @brief Setting callback - # - # This member function sets callback function which is called - # when variable is changed. - # - # @endif - # - # void setCallback(CallbackFunc cbf); - def setCallback(self, cbf): - self.callback = cbf - - return - - - ## - # @if jp - # - # @brief ѿѹΤ餻륪֥дؿ - # - # ѿѹΤ餻륪֥дؿ. - # - # @else - # - # @brief Observer function to notify variable changed - # - # This function notifies variable has been changed. - # - # @endif - # - # void notifyUpdate(const char* key, const char* val); - def notifyUpdate(self, key, val): - self.callback(key, val) - return - - - ## - # @if jp - # - # @brief Хɥѥ᡼ͤ򹹿 - # - # ե졼ͤǥե졼ѥ᡼򹹿 - # - # @param self - # @param val ѥ᡼ͤʸɽ - # - # @return (:true:false) - # - # @else - # - # @brief Update a bind parameter value - # - # Update configuration paramater by the configuration value. - # - # @param self - # @param val The parameter values converted into character string format - # - # @return Update result (Successful:true, Failed:false) - # - # @endif - # virtual bool update(const char* val) - def update(self, val): - if self.string_value == val: - return True - self.string_value = val - # value changed - if self._trans(self._var, val): - self.notifyUpdate(self.name, val) - return True - self._trans(self._var, self.default_value) - self.notifyUpdate(self.name, val) - return False + """ + """ + + ## + # @if jp + # + # @brief コンストラクタ + # + # コンストラクタ + # + # @param self + # @param name コンフィギュレーションパラメータ名 + # @param var コンフィギュレーションパラメータ格納用変数 + # @param def_val 文字列形式のデフォルト値 + # @param trans 文字列形式変換関数(デフォルト値:None) + # + # @else + # + # @brief Constructor + # + # Constructor + # + # @param self + # @param name Configuration parameter name + # @param var Configuration parameter variable + # @param def_val Default value in string format + # @param trans Function to transform into string format + # + # @endif + def __init__(self, name, var, def_val, trans=None): + self.name = name + self.default_value = def_val + self.string_value = "" + self.callback = None + self._var = var + if trans: + self._trans = trans + else: + self._trans = OpenRTM_aist.stringTo + return + + ## + # @if jp + # + # @brief コールバックのセット + # + # 変数変更時にコールされるコールバック関数をセットする. + # + # @else + # + # @brief Setting callback + # + # This member function sets callback function which is called + # when variable is changed. + # + # @endif + # + # void setCallback(CallbackFunc cbf); + + def setCallback(self, cbf): + self.callback = cbf + + return + + ## + # @if jp + # + # @brief 変数変更を知らせるオブザーバ関数 + # + # 変数変更を知らせるオブザーバ関数. + # + # @else + # + # @brief Observer function to notify variable changed + # + # This function notifies variable has been changed. + # + # @endif + # + # void notifyUpdate(const char* key, const char* val); + + def notifyUpdate(self, key, val): + self.callback(key, val) + return + + ## + # @if jp + # + # @brief バインドパラメータ値を更新 + # + # コンフィギュレーション設定値でコンフィギュレーションパラメータを更新する + # + # @param self + # @param val パラメータ値の文字列表現 + # + # @return 更新処理結果(更新成功:true,更新失敗:false) + # + # @else + # + # @brief Update a bind parameter value + # + # Update configuration paramater by the configuration value. + # + # @param self + # @param val The parameter values converted into character string format + # + # @return Update result (Successful:true, Failed:false) + # + # @endif + # virtual bool update(const char* val) + + def update(self, val): + if self.string_value == val: + return True + self.string_value = val + # value changed + ret, self._var[0] = self._trans(self._var[0], val) + if ret: + self.notifyUpdate(self.name, val) + return True + ret, self._var[0] = self._trans(self._var[0], self.default_value) + self.notifyUpdate(self.name, val) + return False ## # @if jp # @class ConfigAdmin -# @brief ConfigAdmin 饹 -# -# Ƽ拾ե졼륯饹 -# ѸʲΤ褦롣 +# @brief ConfigAdmin クラス # -# - ե졼: ݡͥȤ +# 各種コンフィギュレーション情報を管理するクラス。 +# 用語を以下のように定義する。 # -# - (ե졼)ѥ᡼ key-value ʤ -# coil::Properties ѿȤư졢keyvalue ʸȤ -# 롣key 򥳥ե졼ѥ᡼̾value 򥳥 -# ե졼ѥ᡼ͤȸƤ֡ +# - コンフィギュレーション: コンポーネントの設定情報。 # -# - ե졼󥻥åȡ ե졼ѥ᡼ -# ΥꥹȤǡ̾ (ID) ˤäƶ̤롣ID򥳥ե졼 -# 󥻥åIDȸƤ֡ +# - (コンフィギュレーション)パラメータ: key-value からなる設定情報。 +# coil::Properties 変数として扱われ、key、value 共に文字列として保 +# 持される。key をコンフィギュレーションパラメータ名、value をコン +# フィギュレーションパラメータ値と呼ぶ。 # -# - (ե졼)ѥ᡼ѿե졼 -# ᡼RTCΥƥӥƥǼºݤѤݤ˻Ȥ -# ѥ᡼Ȥ˸ͭηġ +# - コンフィギュレーションセット: コンフィギュレーションパラメータ +# のリストで、名前 (ID) によって区別される。IDをコンフィギュレーショ +# ンセットIDと呼ぶ。 # -# - ƥ(ե졼)åȡͭʥե -# 졼󥻥åȤΤȤǤꡢͣ¸ߤ롣§Ȥơƥ -# ֥ե졼󥻥åȤΥѥ᡼ե졼 -# ѥ᡼ѿȿǤ롣 +# - (コンフィギュレーション)パラメータ変数:コンフィギュレーションパ +# ラメータをRTCのアクティビティ内で実際に利用する際に参照される変 +# 数。パラメータごとに固有の型を持つ。 # -# Υ饹Ǥϡե졼Τΰʲ2Ĥξ -# Ƥ롣 +# - アクティブ(コンフィギュレーション)セット:現在有効なコンフィギュ +# レーションセットのことであり、唯一つ存在する。原則として、アクティ +# ブコンフィギュレーションセットのパラメータがコンフィギュレーショ +# ンパラメータ変数に反映される。 # -# -# ե졼󥻥åȤΥꥹ -# -# ѥ᡼ѿΥꥹ +# このクラスでは、コンフィギュレーションのための以下の2つの情報を保 +# 持している。 # -# Ūˤϡ(1) Υե졼󥻥åȤΥꥹȤΤĤ -# (2) Υѥ᡼ѿȿǤ롢Τܥ饹ŪǤ롣̾ -# ѥ᡼ѿѹϡե졼󥻥åȤѹȥ -# ᡼ѿؤȿǤ2ʳǹԤ롣 +# -# コンフィギュレーションセットのリスト +# -# パラメータ変数のリスト # -# ե졼󥻥åȤΥꥹȤˤϡʲδؿѤ롣 +# 基本的には、(1) のコンフィギュレーションセットのリストのうち一つを、 +# (2) のパラメータ変数へ反映させる、のが本クラスの目的である。通常、 +# パラメータ変数の変更操作は、コンフィギュレーションセットの変更とパ +# ラメータ変数への反映の2段階で行われる。 +# +# コンフィギュレーションセットのリストの操作には、以下の関数を用いる。 # # - getConfigurationSets() # - getConfigurationSet() @@ -272,31 +259,31 @@ def update(self, val): # - removeConfigurationSet() # - activateConfigurationSet() # -# δؿˤꡢե졼󥻥åȤѹɲá -# ƥֲԤˤѹ줿ե -# 졼󥻥åȤRTCΥƥӥƥѤѥ᡼ѿ -# ȿǤˤϡʲ update() ؿѤ롣 +# これらの関数により、コンフィギュレーションセットの変更、追加、削除、 +# 取得、アクティブ化を行う。これらの操作により変更されたコンフィギュ +# レーションセットを、RTCのアクティビティから使用するパラメータ変数 +# に反映させるには、以下の update() 関数を用いる。 # # - update(void) # - update(const char* config_set) # - update(const char* config_set, const char* config_param) # -# ե졼եå뤿˥Хåե󥯥 -# Ϳ뤳ȤǤ롣եåǤϰʲ̤ꡣ +# コンフィギュレーション操作をフックするためにコールバックファンクタ +# を与えることができる。フックできる操作は以下の通り。 # -# - ON_UPDATE : update() -# - ON_UPDATE_PARAM : update(param) -# - ON_SET_CONFIGURATIONSET : setConfigurationSet() -# - ON_ADD_CONFIGURATIONSET : addConfigurationSet() -# - ON_REMOVE_CONFIGURATIONSET : removeConfigurationSet() -# - ON_ACTIVATE_CONFIGURATIONSET: activateConfigurationSet() +# - ON_UPDATE : update() コール時 +# - ON_UPDATE_PARAM : update(param) コール時 +# - ON_SET_CONFIGURATIONSET : setConfigurationSet() コール時 +# - ON_ADD_CONFIGURATIONSET : addConfigurationSet() コール時 +# - ON_REMOVE_CONFIGURATIONSET : removeConfigurationSet() コール時 +# - ON_ACTIVATE_CONFIGURATIONSET: activateConfigurationSet() コール時 # # @since 0.4.0 # # @else # @class ConfigAdmin # @brief ConfigAdmin class -# +# # Class to manage various configuration information. # Now terms for this class are defined as follows. # @@ -368,1351 +355,1352 @@ def update(self, val): # # @endif class ConfigAdmin: - """ - """ - - ## - # @if jp - # - # @brief 󥹥ȥ饯 - # - # 󥹥ȥ饯 - # - # @param self - # @param configsets оݥץѥƥ̾ - # - # @else - # - # Constructor - # - # @param self - # @param prop The target property name for setup - # - # @endif - # ConfigAdmin(coil::Properties& prop); - def __init__(self, configsets): - self._configsets = configsets - self._activeId = "default" - self._active = True - self._changed = False - self._params = [] - self._emptyconf = OpenRTM_aist.Properties() - self._newConfig = [] - self._listeners = OpenRTM_aist.ConfigurationListeners() - self._changedParam = [] - - ## - # @if jp - # - # @brief ǥȥ饯 - # - # ǥȥ饯 - # ꤵƤѥ᡼롣 - # - # @param self - # - # @else - # - # @brief Destructor - # - # @param self - # - # @endif - def __del__(self): - del self._params - - - ## - # @if jp - # - # @brief ե졼ѥ᡼ - # - # ե졼ѥ᡼ѿХɤ - # ꤷ̾ΤΥե졼ѥ᡼¸ߤ - # false֤ - # - # @param self - # @param param_name ե졼ѥ᡼̾ - # @param var ե졼ѥ᡼Ǽѿ - # @param def_val ե졼ѥ᡼ǥե - # @param trans ե졼ѥ᡼ʸѴѴؿ - # (ǥե:None) - # - # @return (:true꼺:false) - # - # @else - # - # @brief Setup for configuration parameters - # - # Bind configuration parameter to its variable. - # Return false, if configuration parameter of specified name has already - # existed. - # - # @param self - # @param param_name Configuration parameter name - # @param var Configuration parameter variable - # @param def_val Default value of configuration parameter - # @param trans Function to transform configuration parameter type into - # string format - # - # @return Setup result (Successful:true, Failed:false) - # - # - # @endif - #template - # bool bindParameter(const char* param_name, VarType& var, - # const char* def_val, - # bool (*trans)(VarType&, const char*) = coil::stringTo) - def bindParameter(self, param_name, var, def_val, trans=None): - if trans is None: - trans = OpenRTM_aist.stringTo - - if not param_name or not def_val: - return False - - if self.isExist(param_name): - return False - - if not trans(var, def_val): - return False - conf_ = Config(param_name, var, def_val, trans) - self._params.append(conf_) - conf_.setCallback(self.onUpdateParam) - self.update(self.getActiveId(), param_name) - - return True - - - ## - # @if jp - # - # @brief ե졼ѥ᡼β - # - # ե졼ѥ᡼ѿΥХɤ롣 - # ꤷ̾ΤΥե졼ѥ᡼¸ߤʤ - # false֤ - # - # @param param_name ե졼ѥ᡼̾ - # @return (:true꼺:false) - # - # @else - # - # @brief Unbinding configuration parameters - # - # Unbind configuration parameter from its variable. It returns - # false, if configuration parameter of specified name has already - # existed. - # - # @param param_name Configuration parameter name - # @return Setup result (Successful:true, Failed:false) - # - # @endif - # - # bool unbindParameter(const char* param_name); - def unbindParameter(self, param_name): - find_idx = -1 - for (find_idx,param) in enumerate(self._params): - if param.name == param_name: - break - if find_idx == -1: - return False - - del self._params[find_idx] - - # configsets - leaf = self._configsets.getLeaf() - for i in range(len(leaf)): - if leaf[i].hasKey(param_name): - leaf[i].removeNode(param_name) - - return True - - - ## - # void update(void); - # - # @if jp - # - # @brief ե졼ѥ᡼ι - # (ƥ֥ե졼󥻥å) - # - # ե졼󥻥åȤƤˡߥƥ - # ֤ˤʤäƤ륳ե졼ꤷͤǡե - # 졼ѥ᡼ͤ򹹿롣νǤιϡƥ - # ֤ȤʤäƤ륳ե졼󥻥åȤ¸ߤƤ硢 - # ι饳ե졼󥻥åȤƤƤ - # Τ߼¹Ԥ롣 - # - # @else - # - # @brief Update the values of configuration parameters - # (Active configuration set) - # - # When configuration set is updated, update the configuration - # parameter value to the value that is set to the current active - # configuration. This update will be executed, only when an - # active configuration set exists and the content of the - # configuration set has been updated from the last update. - # - # @endif - # - # void update(const char* config_set); - # - # @if jp - # - # @brief ե졼ѥ᡼ι(ID) - # - # ե졼ѿͤ򡢻ꤷIDĥե졼 - # 󥻥åȤͤǹ롣ˤꡢƥ֤ʥե - # 졼󥻥åȤѹʤäơƥ֥ե - # 졼󥻥åȤȥѥ᡼ѿδ̷֤⤬ȯǽ - # ΤդɬפǤ롣 - # - # ꤷIDΥե졼󥻥åȤ¸ߤʤϡ - # ˽λ롣 - # - # @param config_set оݤΥե졼󥻥åID - # - # @else - # - # @brief Update configuration parameter (By ID) - # - # This operation updates configuration variables by the - # configuration-set with specified ID. This operation does not - # change current active configuration-set. Since this operation - # causes inconsistency between current active configuration set - # and actual values of configuration variables, user should - # carefully use it. - # - # This operation ends without doing anything, if the - # configuration-set does not exist. - # - # @param config_set The target configuration set's ID to setup - # - # @endif - # - # void update(const char* config_set, const char* config_param); - # - # @if jp - # - # @brief ե졼ѥ᡼ι(̾λ) - # - # Υե졼ѿͤ򡢻ꤷIDĥե - # 졼󥻥åȤͤǹ롣ˤꡢƥ֤ʥ - # ե졼󥻥åȤѹʤäơƥ֥ - # ե졼󥻥åȤȥѥ᡼ѿδ̷֤⤬ȯ - # ǽΤդɬפǤ롣 - # - # ꤷIDΥե졼󥻥åȤ䡢ꤷ̾ΤΥѥ᡼ - # ¸ߤʤϡ⤻˽λ롣 - # - # @param config_set ե졼ID - # @param config_param ե졼ѥ᡼̾ - # - # @else - # - # @brief Update the values of configuration parameters (By name) - # - # This operation updates a configuration variable by the - # specified configuration parameter in the - # configuration-set. This operation does not change current - # active configuration-set. Since this operation causes - # inconsistency between current active configuration set and - # actual values of configuration variables, user should carefully - # use it. - # - # This operation ends without doing anything, if the - # configuration-set or the configuration parameter do not exist. - # - # @param config_set configuration-set ID. - # @param config_param configuration parameter name. - # - # @endif - # - def update(self, config_set=None, config_param=None): - # update(const char* config_set) - - if config_set and config_param is None: - if self._configsets.hasKey(config_set) is None: - return - self._changedParam = [] - prop = self._configsets.getNode(config_set) - for i in range(len(self._params)): - if prop.hasKey(self._params[i].name): - # self._changedParam is updated here - self._params[i].update(prop.getProperty(self._params[i].name)) - self.onUpdate(config_set) - - # update(const char* config_set, const char* config_param) - if config_set and config_param: - self._changedParam = [] - key = config_set - key = key+"."+config_param - for conf in self._params: - if conf.name == config_param: - conf.update(self._configsets.getProperty(key)) - #self.onUpdateParam(config_set, config_param) - return - - # update() - if config_set is None and config_param is None: - self._changedParam = [] - if self._changed and self._active: - self.update(self._activeId) + """ + """ + + ## + # @if jp + # + # @brief コンストラクタ + # + # コンストラクタ + # + # @param self + # @param configsets 設定対象プロパティ名 + # + # @else + # + # Constructor + # + # @param self + # @param prop The target property name for setup + # + # @endif + # ConfigAdmin(coil::Properties& prop); + def __init__(self, configsets): + self._configsets = configsets + self._activeId = "default" + self._active = True self._changed = False - return - - - ## - # @if jp - # - # @brief ե졼ѥ᡼¸߳ǧ - # - # ꤷ̾Τĥե졼ѥ᡼¸ߤ뤫ǧ롣 - # - # @param self - # @param param_name ե졼ѥ᡼̾Ρ - # - # @return ¸߳ǧ(ѥ᡼:trueѥ᡼ʤ:false) - # - # @else - # - # @brief Check the existence of configuration parameters - # - # Check the existence of configuration parameters of specified name. - # - # @param self - # @param name Configuration parameter name - # - # @return Result of existance confirmation - # (Parameters exist:true, else:false) - # - # @endif - # bool isExist(const char* name); - def isExist(self, param_name): - if not self._params: - return False - - for conf in self._params: - if conf.name == param_name: + self._params = [] + self._emptyconf = OpenRTM_aist.Properties() + self._newConfig = [] + self._listeners = OpenRTM_aist.ConfigurationListeners() + self._changedParam = [] + + ## + # @if jp + # + # @brief デストラクタ + # + # デストラクタ。 + # 設定されているパラメータを削除する。 + # + # @param self + # + # @else + # + # @brief Destructor + # + # @param self + # + # @endif + def __del__(self): + del self._params + + ## + # @if jp + # + # @brief コンフィギュレーションパラメータの設定 + # + # コンフィギュレーションパラメータと変数をバインドする + # 指定した名称のコンフィギュレーションパラメータが既に存在する場合は + # falseを返す。 + # + # @param self + # @param param_name コンフィギュレーションパラメータ名 + # @param var コンフィギュレーションパラメータ格納用変数 + # @param def_val コンフィギュレーションパラメータデフォルト値 + # @param trans コンフィギュレーションパラメータ文字列変換用関数 + # (デフォルト値:None) + # + # @return 設定結果(設定成功:true,設定失敗:false) + # + # @else + # + # @brief Setup for configuration parameters + # + # Bind configuration parameter to its variable. + # Return false, if configuration parameter of specified name has already + # existed. + # + # @param self + # @param param_name Configuration parameter name + # @param var Configuration parameter variable + # @param def_val Default value of configuration parameter + # @param trans Function to transform configuration parameter type into + # string format + # + # @return Setup result (Successful:true, Failed:false) + # + # + # @endif + # template + # bool bindParameter(const char* param_name, VarType& var, + # const char* def_val, + # bool (*trans)(VarType&, const char*) = coil::stringTo) + + def bindParameter(self, param_name, var, def_val, trans=None): + if trans is None: + trans = OpenRTM_aist.stringTo + + if not param_name or not def_val: + return False + + if self.isExist(param_name): + return False + ret, var[0] = trans(var[0], def_val) + if not ret: + return False + conf_ = Config(param_name, var, def_val, trans) + self._params.append(conf_) + conf_.setCallback(self.onUpdateParam) + self.update(self.getActiveId(), param_name) + + return True + + ## + # @if jp + # + # @brief コンフィギュレーションパラメータの解除 + # + # コンフィギュレーションパラメータと変数のバインドを解除する。 + # 指定した名称のコンフィギュレーションパラメータが存在しない場合は + # falseを返す。 + # + # @param param_name コンフィギュレーションパラメータ名 + # @return 設定結果(設定成功:true,設定失敗:false) + # + # @else + # + # @brief Unbinding configuration parameters + # + # Unbind configuration parameter from its variable. It returns + # false, if configuration parameter of specified name has already + # existed. + # + # @param param_name Configuration parameter name + # @return Setup result (Successful:true, Failed:false) + # + # @endif + # + # bool unbindParameter(const char* param_name); + + def unbindParameter(self, param_name): + find_idx = -1 + for (find_idx, param) in enumerate(self._params): + if param.name == param_name: + break + if find_idx == -1: + return False + + del self._params[find_idx] + + # configsets + leaf = self._configsets.getLeaf() + for l in leaf: + if l.hasKey(param_name): + l.removeNode(param_name) + return True - return False - - - ## - # @if jp - # - # @brief ե졼ѥ᡼ѹǧ - # - # ե졼ѥ᡼ѹ줿ǧ롣 - # - # @param self - # - # @return ѹǧ(ѹ:trueѹʤ:false) - # - # @else - # - # @brief Confirm to change configuration parameters - # - # Confirm that configuration parameters have changed. - # - # @param self - # - # @return Result of change confirmation - # (There is a change:trueNo change:false) - # - # @endif - # bool isChanged(void) {return m_changed;} - def isChanged(self): - return self._changed - - - ## - # @if jp - # - # @brief ѹ줿ѥ᡼Υꥹ - # - # ե졼ѥ᡼Τѹ줿ΤΥꥹȤ֤ - # - # @return ѹ줿ѥ᡼̾ꥹ - # - # @else - # - # @brief Changed parameters list - # - # This operation returns parameter list which are changed. - # - # @return Changed parameters list - # - # @endif - # - # coil::vstring& changedParameters() { return m_changedParam; } - def changedParameters(self): - return self._changedParam - - ## - # @if jp - # - # @brief ƥ֡ե졼󥻥åIDμ - # - # ߥƥ֤ʥե졼󥻥åȤID롣 - # - # @param self - # - # @return ƥ֡ե졼󥻥åID - # - # @else - # - # @brief Get ID of active configuration set - # - # Get ID of the current active configuration set. - # - # @param self - # - # @return The active configuration set ID - # - # @endif - # const char* getActiveId(void); - def getActiveId(self): - return self._activeId - - - ## - # @if jp - # - # @brief ե졼󥻥åȤ¸߳ǧ - # - # ꤷե졼󥻥åȤ¸ߤ뤫ǧ롣 - # - # @param self - # @param config_id ǧоݥե졼󥻥åID - # - # @return ¸߳ǧ(ꤷConfigSet:trueʤ:false) - # - # @else - # - # @brief Check the existence of configuration set - # - # Check the existence of specified configuration set. - # - # @param self - # @param config_id ID of target configuration set for confirmation - # @return Result of existence confirmation - # (Specified ConfigSet exists:true, else:false) - # @endif - # bool haveConfig(const char* config_id); - def haveConfig(self, config_id): - if self._configsets.hasKey(config_id) is None: - return False - else: - return True - - - ## - # @if jp - # - # @brief ե졼󥻥åȤΥƥֲǧ - # - # ե졼󥻥åȤƥֲƤ뤫ǧ롣 - # - # @param self - # - # @return ֳǧ(ƥ־:true󥢥ƥ־:false) - # - # @else - # - # @brief Confirm to activate configuration set - # - # Confirm that configuration set has been activated. - # - # @param self - # - # @return Result of state confirmation - # (Active state:true, Inactive state:false) - # - # @endif - # bool isActive(void); - def isActive(self): - return self._active - - - ## - # @if jp - # - # @brief ե졼󥻥åȤμ - # - # ꤵƤե졼󥻥åȤ롣 - # - # @param self - # - # @return ե졼󥻥å - # - # @else - # - # @brief Get all configuration sets - # - # Get all specified configuration sets - # - # @param self - # - # @return All configuration sets - # - # @endif - # const std::vector& getConfigurationSets(void); - def getConfigurationSets(self): - return self._configsets.getLeaf() - - - ## - # @if jp - # - # @brief ꤷIDΥե졼󥻥åȤμ - # - # IDǻꤷե졼󥻥åȤ롣 - # ꤷե졼󥻥åȤ¸ߤʤϡ - # Υե졼󥻥åȤ֤ - # - # @param self - # @param config_id оݥե졼󥻥åȤID - # - # @return ե졼󥻥å - # - # @else - # - # @brief Get a configuration set by specified ID - # - # Get a configuration set that was specified by ID - # Return empty configuration set, if a configuration set of - # specified ID doesn't exist. - # - # @param self - # @param config_id ID of the target configuration set for getting - # - # @return The configuration set - # - # @endif - # const coil::Properties& getConfigurationSet(const char* config_id); - def getConfigurationSet(self, config_id): - - prop = self._configsets.findNode(config_id) - if prop is None: - return self._emptyconf - return prop - - - ## - # @if jp - # - # @brief ꤷץѥƥΥե졼󥻥åȤؤɲ - # - # ꤷץѥƥ򥳥ե졼󥻥åȤɲä롣 - # - # @param self - # @param config_set ɲäץѥƥ - # - # @return ɲý¹Է(ɲ:trueɲü:false) - # - # @else - # - # @brief Add to configuration set from specified property - # - # Add specified property to configuration set. - # - # @param self - # @param configuration_set Property to add - # - # @return Add result (Successful:true, Failed:false) - # - # @endif - # bool setConfigurationSetValues(const coil::Properties& config_set) - def setConfigurationSetValues(self, config_set): - node_ = config_set.getName() - if node_ == "" or node_ is None: - return False - - if not self._configsets.hasKey(node_): - return False - - p = self._configsets.getNode(node_) - #if p is None: - # return False - - p.mergeProperties(config_set) - self._changed = True - self._active = False - self.onSetConfigurationSet(config_set) - return True - - - ## - # @if jp - # - # @brief ƥ֡ե졼󥻥åȤ - # - # ߥƥ֤ȤʤäƤ륳ե졼󥻥åȤ롣 - # ƥ֤ȤʤäƤ륳ե졼󥻥åȤ¸ߤʤϡ - # Υե졼󥻥å ֤ - # - # @param self - # - # @return ƥ֡ե졼󥻥å - # - # @else - # - # @brief Get the active configuration set - # - # Get the current active configuration set. - # Return empty configuration set, if an active configuration set - # doesn't exist. - # - # @param self - # @return The active configuration set - # - # @endif - # const coil::Properties& getActiveConfigurationSet(void); - def getActiveConfigurationSet(self): - p = self._configsets.getNode(self._activeId) - #if p is None: - # return self._emptyconf - - return p - - - ## - # @if jp - # - # @brief ե졼󥻥åȤͤɲ - # - # ե졼󥻥åȤͤɲä롣 - # - # @param self - # @param configset ɲäץѥƥ - # - # @return ɲý(ɲ:trueɲü:false) - # - # @else - # - # @brief Add the configuration value to configuration set - # - # Add the configuration value to configuration set - # - # @param self - # @param configuration_set Property to add - # - # @return Add Result (Successful:true, Failed:false) - # - # @endif - # bool addConfigurationSet(const coil::Properties& configuration_set); - def addConfigurationSet(self, configset): - if self._configsets.hasKey(configset.getName()): - return False - node = configset.getName() - - # Create node - self._configsets.createNode(node) - - p = self._configsets.getNode(node) - #if p is None: - # return False - - p.mergeProperties(configset) - self._newConfig.append(node) - - self._changed = True - self._active = False - self.onAddConfigurationSet(configset) - return True - - - ## - # @if jp - # - # @brief ե졼󥻥åȤκ - # - # ꤷIDΥե졼󥻥åȤ롣 - # - # ꤷIDΥե졼󥻥åȤ¸ߤʤϡ - # false֤ǽʥե졼󥻥åȤϡ - # addConfigruationSet() ˤäɲäե졼󥻥 - # ȤΤߤǤꡢǥեȥե졼󥻥åȡݡ - # ȵư˥ե뤫ɤ߹ޤ륳ե졼󥻥å - # Ϻ뤳ȤǤʤ - # - # ޤꤷե졼󥻥åȤߥƥ֤Ǥ - # ˤϡʤ륳ե졼󥻥åȤǤǤʤ - # - # δؿˤºݤ˥ե졼󥻥åȤ줿硢 - # setOnRemoveConfigurationSet() ǥåȤ줿Хåؿ - # ӽФ롣 - # - # @param self - # @param config_id оݥե졼󥻥åȤID - # - # @return (:true:false) - # - # @else - # - # @brief Remove the configuration set - # - # Remove the configuration set of specified ID Return empty - # configuration set, if a configuration set of specified ID - # doesn't exist. - # - # The configuration-sets that can be removed by this function are - # only configuration-sets newly added by the - # addConfigurationSet() function. The configuration that can be - # removed by this function is only newly added configuration-set - # by addConfigurationSet() function. The "default" - # configuration-set and configurationi-sets that is loaded from - # configuration file cannot be removed. - # - # If the specified configuration is active currently, any - # configurations are not deleted. - # - # Callback functions that are set by - # addOnRemovedConfigurationSet() will be called if a - # configuration-set is deleted actually by this function. - # - # @param self - # @param config_id ID of the target configuration set for remove - # - # @return Remove result (Successful:true, Failed:false) - # - # @endif - # - # bool removeConfigurationSet(const char* config_id); - def removeConfigurationSet(self, config_id): - if config_id == "default": - return False - if self._activeId == config_id: - return False - - find_flg = False - # removeable config-set is only config-sets newly added - for (idx,conf) in enumerate(self._newConfig): - if conf == config_id: - find_flg = True - break - - - if not find_flg: - return False - - p = self._configsets.getNode(config_id) - if p: - p.getRoot().removeNode(config_id) - del p - - del self._newConfig[idx] - - self._changed = True - self._active = False - self.onRemoveConfigurationSet(config_id) - return True - - - ## - # @if jp - # - # @brief ե졼󥻥åȤΥƥֲ - # - # ꤷIDΥե졼󥻥åȤ򥢥ƥֲ롣 - # ꤷIDΥե졼󥻥åȤ¸ߤʤϡ - # false֤ - # - # @param self - # @param config_id оݥե졼󥻥åȤID - # - # @return ƥֽ(:true:false) - # - # @else - # - # @brief Activate the configuration set - # - # Activate the configuration set of specified ID - # Return empty configuration set, if a configuration set of - # specified ID doesn't exist. - # - # @param self - # @param config_id ID of the target configuration set for remove - # - # @return Activate result (Remove success:trueRemove failure:false) - # - # @endif - # bool activateConfigurationSet(const char* config_id); - def activateConfigurationSet(self, config_id): - if config_id == "" or config_id is None: - return False - - # '_' is special configuration set name - if config_id[0] == '_': - return False - - if not self._configsets.hasKey(config_id): - return False - self._activeId = config_id - self._active = True - self._changed = True - self.onActivateSet(config_id) - return True - - - #------------------------------------------------------------ - # obsolete functions - # - - ## - # @if jp - # - # @brief OnUpdate ΥХå - # - # OnUpdate ǸƤФ륳ХåΥ֥Ȥꤹ롣 - # - # @param self - # @param cb OnUpdateCallbackΥ֥ - # - # @else - # - # @brief Set callback that is called by OnUpdate. - # - # @param self - # @param cb OnUpdateCallback type object - # - # @endif - # - # void setOnUpdate(OnUpdateCallback* cb); - def setOnUpdate(self, cb): - print("setOnUpdate function is obsolete.") - print("Use addConfigurationSetNameListener instead.") - self._listeners.configsetname_[OpenRTM_aist.ConfigurationSetNameListenerType.ON_UPDATE_CONFIG_SET].addListener(cb, False) - return - - - ## - # @if jp - # - # @brief OnUpdateParam ΥХå - # - # OnUpdateParam ǸƤФ륳ХåΥ֥Ȥꤹ롣 - # - # @param self - # @param cb OnUpdateParamCallbackΥ֥ - # - # @else - # - # @brief Set callback that is called by OnUpdateParam. - # - # @param self - # @param cb OnUpdateParamCallback type object - # - # @endif - # - # void setOnUpdateParam(OnUpdateParamCallback* cb); - def setOnUpdateParam(self, cb): - print("setOnUpdateParam function is obsolete.") - print("Use addConfigurationParamListener instead.") - self._listeners.configparam_[OpenRTM_aist.ConfigurationParamListenerType.ON_UPDATE_CONFIG_PARAM].addListener(cb, False) - return - - - ## - # @if jp - # - # @brief OnSetConfigurationSet ΥХå - # - # OnSetConfigurationSet ǸƤФ륳ХåΥ֥Ȥꤹ롣 - # - # @param self - # @param cb OnSetConfigurationSetCallbackΥ֥ - # - # @else - # - # @brief Set callback that is called by OnSetConfiguration. - # - # @param self - # @param cb OnSetConfigurationSetCallback type object - # - # @endif - # - # void setOnSetConfigurationSet(OnSetConfigurationSetCallback* cb); - def setOnSetConfigurationSet(self, cb): - print("setOnSetConfigurationSet function is obsolete.") - print("Use addConfigurationSetListener instead.") - self._listeners.configset_[OpenRTM_aist.ConfigurationSetListenerType.ON_SET_CONFIG_SET].addListener(cb, False) - return - - - ## - # @if jp - # - # @brief OnAddConfigurationSet ΥХå - # - # OnAddConfigurationSet ǸƤФ륳ХåΥ֥Ȥꤹ롣 - # - # @param self - # @param cb OnAddConfigurationAddCallbackΥ֥ - # - # @else - # - # @brief Set callback that is called by OnSetConfiguration. - # - # @param self - # @param cb OnSetConfigurationSetCallback type object - # - # @endif - # - # void setOnAddConfigurationSet(OnAddConfigurationAddCallback* cb); - def setOnAddConfigurationSet(self, cb): - print("setOnAddConfigurationSet function is obsolete.") - print("Use addConfigurationSetListener instead.") - self._listeners.configset_[OpenRTM_aist.ConfigurationSetListenerType.ON_ADD_CONFIG_SET].addListener(cb, False) - return - - - ## - # @if jp - # - # @brief OnRemoveConfigurationSet ΥХå - # - # OnRemoveConfiguration ǸƤФ륳ХåΥ֥Ȥꤹ롣 - # - # @param self - # @param cb OnRemoveConfigurationSetCallbackΥ֥ - # - # @else - # - # @brief Set callback that is called by OnRemoveConfigurationSet. - # - # @param self - # @param cb OnRemoveConfigurationSetCallback type object - # - # @endif - # - # void setOnRemoveConfigurationSet(OnRemoveConfigurationSetCallback* cb); - def setOnRemoveConfigurationSet(self, cb): - print("setOnRemoveConfigurationSet function is obsolete.") - print("Use addConfigurationSetNameListener instead.") - self._listeners.configsetname_[OpenRTM_aist.ConfigurationSetNameListenerType.ON_REMOVE_CONFIG_SET].addListener(cb, False) - return - - - ## - # @if jp - # - # @brief OnActivateSet ΥХå - # - # OnActivateSet ǸƤФ륳ХåΥ֥Ȥꤹ롣 - # - # @param self - # @param cb OnActivateSetCallbackΥ֥ - # - # @else - # - # @brief Set callback that is called by OnActivateSet. - # - # @param self - # @param cb OnActivateSetCallback type object - # - # @endif - # - # void setOnActivateSet(OnActivateSetCallback* cb); - def setOnActivateSet(self, cb): - print("setOnActivateSet function is obsolete.") - print("Use addConfigurationSetNameListener instead.") - self._listeners.configsetname_[OpenRTM_aist.ConfigurationSetNameListenerType.ON_ACTIVATE_CONFIG_SET].addListener(cb, False) - return - - # - # end of obsolete functions - #------------------------------------------------------------ - - ## - # @if jp - # - # @brief ConfigurationParamListener ɲä - # - # update(const char* config_set, const char* config_param) ƤФ줿ݤ - # 뤵ꥹ ConfigurationParamListener ɲä롣 - # type ˤϸߤΤȤ ON_UPDATE_CONFIG_PARAM Τߤ롣 - # - # @param type ConfigurationParamListenerType͡ - # ON_UPDATE_CONFIG_PARAM 롣 - # - # @param listener ConfigurationParamListener Υꥹʥ֥ȡ - # @param autoclean ꥹʥ֥ȤưǺ뤫ɤΥե饰 - # - # @else - # - # @brief Adding ConfigurationParamListener - # - # This function adds a listener object which is called when - # update(const char* config_set, const char* config_param) is - # called. In the type argument, currently only - # ON_UPDATE_CONFIG_PARAM is allowed. - # - # @param type ConfigurationParamListenerType value - # ON_UPDATE_CONFIG_PARAM is only allowed. - # - # @param listener ConfigurationParamListener listener object. - # @param autoclean a flag whether if the listener object autocleaned. - # - # @endif - # - # void addConfigurationParamListener(ConfigurationParamListenerType type, - # ConfigurationParamListener* listener, - # bool autoclean = true); - def addConfigurationParamListener(self, type, listener, autoclean = True): - self._listeners.configparam_[type].addListener(listener, autoclean) - return - - - ## - # @if jp - # - # @brief ConfigurationParamListener - # - # addConfigurationParamListener ɲä줿ꥹʥ֥Ȥ롣 - # - # @param type ConfigurationParamListenerType͡ - # ON_UPDATE_CONFIG_PARAM 롣 - # @param listener Ϳꥹʥ֥ȤؤΥݥ - # - # @else - # - # @brief Removing ConfigurationParamListener - # - # This function removes a listener object which is added by - # addConfigurationParamListener() function. - # - # @param type ConfigurationParamListenerType value - # ON_UPDATE_CONFIG_PARAM is only allowed. - # @param listener a pointer to ConfigurationParamListener listener object. - # - # @endif - # - # void removeConfigurationParamListener(ConfigurationParamListenerType type, - # ConfigurationParamListener* listener); - def removeConfigurationParamListener(self, type, listener): - self._listeners.configparam_[type].removeListener(listener) - return - - - ## - # @if jp - # - # @brief ConfigurationSetListener ɲä - # - # ConfigurationSet 줿Ȥʤɤ˸ƤФꥹ - # ConfigurationSetListener ɲä롣ǽʥ٥Ȥϰʲ - # 2ब롣 - # - # - ON_SET_CONFIG_SET: setConfigurationSetValues() - # ConfigurationSet ͤꤵ줿硣 - # - ON_ADD_CONFIG_SET: addConfigurationSet() ǿ - # ConfigurationSet ɲä줿硣 - # - # @param type ConfigurationSetListenerType͡ - # @param listener ConfigurationSetListener Υꥹʥ֥ȡ - # @param autoclean ꥹʥ֥ȤưǺ뤫ɤΥե饰 - # - # @else - # - # @brief Adding ConfigurationSetListener - # - # This function add a listener object which is called when - # ConfigurationSet is updated. Available events are the followings. - # - # @param type ConfigurationSetListenerType value - # @param listener ConfigurationSetListener listener object. - # @param autoclean a flag whether if the listener object autocleaned. - # - # @endif - # - # void addConfigurationSetListener(ConfigurationSetListenerType type, - # ConfigurationSetListener* listener, - # bool autoclean = true); - def addConfigurationSetListener(self, type, listener, autoclean = True): - self._listeners.configset_[type].addListener(listener, autoclean) - return - - - ## - # @if jp - # - # @brief ConfigurationSetListener - # - # addConfigurationSetListener ɲä줿ꥹʥ֥Ȥ롣 - # - # @param type ConfigurationSetListenerType͡ - # @param listener Ϳꥹʥ֥ȤؤΥݥ - # - # @else - # - # @brief Removing ConfigurationSetListener - # - # This function removes a listener object which is added by - # addConfigurationSetListener() function. - # - # @param type ConfigurationSetListenerType value - # @param listener a pointer to ConfigurationSetListener listener object. - # - # @endif - # void removeConfigurationSetListener(ConfigurationSetListenerType type, - # ConfigurationSetListener* listener); - def removeConfigurationSetListener(self, type, listener): - self._listeners.configset_[type].removeListener(listener) - return - - - ## - # @if jp - # - # @brief ConfigurationSetNameListener ɲä - # - # ConfigurationSetName 줿Ȥʤɤ˸ƤФꥹ - # ConfigurationSetNameListener ɲä롣ǽʥ٥Ȥϰʲ - # 3ब롣 - # - # - ON_UPDATE_CONFIG_SET: ConfigurationSet åץǡȤ줿 - # - ON_REMOVE_CONFIG_SET: ConfigurationSet 줿 - # - ON_ACTIVATE_CONFIG_SET: ConfigurationSet ƥֲ줿 - # - # @param type ConfigurationSetNameListenerType͡ - # @param listener ConfigurationSetNameListener Υꥹʥ֥ȡ - # @param autoclean ꥹʥ֥ȤưǺ뤫ɤΥե饰 - # - # @else - # - # @brief Adding ConfigurationSetNameListener - # - # This function add a listener object which is called when - # ConfigurationSetName is updated. Available events are the followings. - # - # - ON_UPDATE_CONFIG_SET: A ConfigurationSet has been updated. - # - ON_REMOVE_CONFIG_SET: A ConfigurationSet has been deleted. - # - ON_ACTIVATE_CONFIG_SET: A ConfigurationSet has been activated. - # - # @param type ConfigurationSetNameListenerType value - # @param listener ConfigurationSetNameListener listener object. - # @param autoclean a flag whether if the listener object autocleaned. - # - # @endif - # void - # addConfigurationSetNameListener(ConfigurationSetNameListenerType type, - # ConfigurationSetNameListener* listener, - # bool autoclean = true); - def addConfigurationSetNameListener(self, type, listener, autoclean = True): - self._listeners.configsetname_[type].addListener(listener, autoclean) - return - - - ## - # @if jp - # - # @brief ConfigurationSetNameListener - # - # addConfigurationSetNameListener ɲä줿ꥹʥ֥Ȥ - # 롣 - # - # @param type ConfigurationSetNameListenerType͡ - # ON_UPDATE_CONFIG_PARAM 롣 - # @param listener Ϳꥹʥ֥ȤؤΥݥ - # - # @else - # - # @brief Removing ConfigurationSetNameListener - # - # This function removes a listener object which is added by - # addConfigurationSetNameListener() function. - # - # @param type ConfigurationSetNameListenerType value - # ON_UPDATE_CONFIG_PARAM is only allowed. - # @param listener a pointer to ConfigurationSetNameListener - # listener object. - # - # @endif - # void - # removeConfigurationSetNameListener(ConfigurationSetNameListenerType type, - # ConfigurationSetNameListener* listener); - def removeConfigurationSetNameListener(self, type, listener): - self._listeners.configsetname_[type].removeListener(listener) - return - - - ## - # @if jp - # - # @brief ե졼ѥ᡼ι(ID)˥뤵 - # - # ꤵƤ륳Хå֥ȤƤӽФ - # - # @param self - # @param config_set оݤΥե졼󥻥åID - # - # @else - # - # @brief When the configuration parameter is updated, it is called. - # - # Call the set callback object. - # - # @param self - # @param config_set The target configuration set's ID to setup - # - # @endif - # - # void onUpdate(const char* config_set); - def onUpdate(self, config_set): - self._listeners.configsetname_[OpenRTM_aist.ConfigurationSetNameListenerType.ON_UPDATE_CONFIG_SET].notify(config_set) - return - - - ## - # @if jp - # - # @brief ե졼ѥ᡼ι(̾λ)˥뤵 - # - # ꤵƤ륳Хå֥ȤƤӽФ - # - # @param self - # @param config_param ե졼ѥ᡼̾ - # @param config_value ե졼 - # - # @else - # - # @brief When the configuration parameter is updated, it is called. - # - # Call the set callback object. - # - # @param self - # @param config_param configuration parameter name. - # @param config_value configuration value. - # - # @endif - # - # void onUpdateParam(const char* config_param, const char* config_value); - def onUpdateParam(self, config_param, config_value): - self._changedParam.append(config_param) - self._listeners.configparam_[OpenRTM_aist.ConfigurationParamListenerType.ON_UPDATE_CONFIG_PARAM].notify(config_param, - config_value) - return - - - ## - # @if jp - # - # @brief ե졼󥻥åȤؤɲû˥뤵 - # - # ꤵƤ륳Хå֥ȤƤӽФ - # - # @param self - # @param configuration_set ץѥƥ - # - # @else - # - # @brief Called when the property is added to the configuration set - # - # Call the set callback object. - # - # @param self - # @param configuration_set property - # - # @endif - # - # void onSetConfigurationSet(const coil::Properties& config_set); - def onSetConfigurationSet(self, config_set): - self._listeners.configset_[OpenRTM_aist.ConfigurationSetListenerType.ON_SET_CONFIG_SET].notify(config_set) - return - - - ## - # @if jp - # - # @brief ͤɲä줿Ȥ˥뤵롣 - # - # ꤵƤ륳Хå֥ȤƤӽФ - # - # @param self - # @param configuration_set ץѥƥ - # - # @else - # - # @brief Called when a set value is added to the configuration set - # - # Call the set callback object. - # - # @param self - # @param configuration_set property - # - # @endif - # - # void onAddConfigurationSet(const coil::Properties& config_set); - def onAddConfigurationSet(self, config_set): - self._listeners.configset_[OpenRTM_aist.ConfigurationSetListenerType.ON_ADD_CONFIG_SET].notify(config_set) - return - - - ## - # @if jp - # - # @brief åȤƤȤ˥뤵롣 - # - # ꤵƤ륳Хå֥ȤƤӽФ - # - # @param self - # @param config_id ץѥƥ - # - # @else - # - # @brief Called when the configuration set has been deleted - # - # Call the set callback object. - # - # @param self - # @param config_id property - # - # @endif - # - # void onRemoveConfigurationSet(const char* config_id); - def onRemoveConfigurationSet(self, config_id): - self._listeners.configsetname_[OpenRTM_aist.ConfigurationSetNameListenerType.ON_REMOVE_CONFIG_SET].notify(config_id) - return - - - ## - # @if jp - # - # @brief åȤƥֲ줿Ȥ˥뤵롣 - # - # ꤵƤ륳Хå֥ȤƤӽФ - # - # @param self - # @param config_id ץѥƥ - # - # @else - # - # @brief Called when the configuration set is made active - # - # Call the set callback object. - # - # @param self - # @param config_id property - # - # @endif - # - # void onActivateSet(const char* config_id); - def onActivateSet(self, config_id): - self._listeners.configsetname_[OpenRTM_aist.ConfigurationSetNameListenerType.ON_ACTIVATE_CONFIG_SET].notify(config_id) - return - - - class find_conf: - def __init__(self, name): - self._name = name - return - - def __call__(self, conf): - if conf is None or conf is 0: + ## + # void update(void); + # + # @if jp + # + # @brief コンフィギュレーションパラメータの更新 + # (アクティブコンフィギュレーションセット) + # + # コンフィギュレーションセットが更新されている場合に、現在アクティ + # ブになっているコンフィギュレーションに設定した値で、コンフィギュ + # レーションパラメータの値を更新する。この処理での更新は、アクティ + # ブとなっているコンフィギュレーションセットが存在している場合、前 + # 回の更新からコンフィギュレーションセットの内容が更新されている場 + # 合のみ実行される。 + # + # @else + # + # @brief Update the values of configuration parameters + # (Active configuration set) + # + # When configuration set is updated, update the configuration + # parameter value to the value that is set to the current active + # configuration. This update will be executed, only when an + # active configuration set exists and the content of the + # configuration set has been updated from the last update. + # + # @endif + # + # void update(const char* config_set); + # + # @if jp + # + # @brief コンフィギュレーションパラメータの更新(ID指定) + # + # コンフィギュレーション変数の値を、指定したIDを持つコンフィギュレー + # ションセットの値で更新する。これにより、アクティブなコンフィギュ + # レーションセットは変更されない。したがって、アクティブコンフィギュ + # レーションセットとパラメータ変数の間に矛盾が発生する可能性がある + # ので注意が必要である。 + # + # 指定したIDのコンフィギュレーションセットが存在しない場合は、何も + # せずに終了する。 + # + # @param config_set 設定対象のコンフィギュレーションセットID + # + # @else + # + # @brief Update configuration parameter (By ID) + # + # This operation updates configuration variables by the + # configuration-set with specified ID. This operation does not + # change current active configuration-set. Since this operation + # causes inconsistency between current active configuration set + # and actual values of configuration variables, user should + # carefully use it. + # + # This operation ends without doing anything, if the + # configuration-set does not exist. + # + # @param config_set The target configuration set's ID to setup + # + # @endif + # + # void update(const char* config_set, const char* config_param); + # + # @if jp + # + # @brief コンフィギュレーションパラメータの更新(名称指定) + # + # 特定のコンフィギュレーション変数の値を、指定したIDを持つコンフィ + # ギュレーションセットの値で更新する。これにより、アクティブなコン + # フィギュレーションセットは変更されない。したがって、アクティブコ + # ンフィギュレーションセットとパラメータ変数の間に矛盾が発生する可 + # 能性があるので注意が必要である。 + # + # 指定したIDのコンフィギュレーションセットや、指定した名称のパラメー + # タが存在しない場合は、何もせずに終了する。 + # + # @param config_set コンフィギュレーションID + # @param config_param コンフィギュレーションパラメータ名 + # + # @else + # + # @brief Update the values of configuration parameters (By name) + # + # This operation updates a configuration variable by the + # specified configuration parameter in the + # configuration-set. This operation does not change current + # active configuration-set. Since this operation causes + # inconsistency between current active configuration set and + # actual values of configuration variables, user should carefully + # use it. + # + # This operation ends without doing anything, if the + # configuration-set or the configuration parameter do not exist. + # + # @param config_set configuration-set ID. + # @param config_param configuration parameter name. + # + # @endif + # + + def update(self, config_set=None, config_param=None): + # update(const char* config_set) + + if config_set and config_param is None: + if self._configsets.hasKey(config_set) is None: + return + self._changedParam = [] + prop = self._configsets.getNode(config_set) + for param in self._params: + if prop.hasKey(param.name): + # self._changedParam is updated here + param.update( + prop.getProperty( + param.name)) + self.onUpdate(config_set) + + # update(const char* config_set, const char* config_param) + if config_set and config_param: + self._changedParam = [] + key = config_set + key = key + "." + config_param + for conf in self._params: + if conf.name == config_param: + conf.update(self._configsets.getProperty(key)) + #self.onUpdateParam(config_set, config_param) + return + + # update() + if config_set is None and config_param is None: + self._changedParam = [] + if self._changed and self._active: + self.update(self._activeId) + self._changed = False + return + + ## + # @if jp + # + # @brief コンフィギュレーションパラメータの存在確認 + # + # 指定した名称を持つコンフィギュレーションパラメータが存在するか確認する。 + # + # @param self + # @param param_name コンフィギュレーションパラメータ名称。 + # + # @return 存在確認結果(パラメータあり:true,パラメータなし:false) + # + # @else + # + # @brief Check the existence of configuration parameters + # + # Check the existence of configuration parameters of specified name. + # + # @param self + # @param name Configuration parameter name + # + # @return Result of existance confirmation + # (Parameters exist:true, else:false) + # + # @endif + # bool isExist(const char* name); + + def isExist(self, param_name): + if not self._params: + return False + + for conf in self._params: + if conf.name == param_name: + return True + return False - return self._name == conf.name + ## + # @if jp + # + # @brief コンフィギュレーションパラメータの変更確認 + # + # コンフィギュレーションパラメータが変更されたか確認する。 + # + # @param self + # + # @return 変更確認結果(変更あり:true、変更なし:false) + # + # @else + # + # @brief Confirm to change configuration parameters + # + # Confirm that configuration parameters have changed. + # + # @param self + # + # @return Result of change confirmation + # (There is a change:true、No change:false) + # + # @endif + # bool isChanged(void) {return m_changed;} + + def isChanged(self): + return self._changed + + ## + # @if jp + # + # @brief 変更されたパラメータのリスト + # + # コンフィギュレーションパラメータのうち変更されたもののリストを返す。 + # + # @return 変更されたパラメータ名リスト + # + # @else + # + # @brief Changed parameters list + # + # This operation returns parameter list which are changed. + # + # @return Changed parameters list + # + # @endif + # + # coil::vstring& changedParameters() { return m_changedParam; } + + def changedParameters(self): + return self._changedParam + + ## + # @if jp + # + # @brief アクティブ・コンフィギュレーションセットIDの取得 + # + # 現在アクティブなコンフィギュレーションセットのIDを取得する。 + # + # @param self + # + # @return アクティブ・コンフィギュレーションセットID + # + # @else + # + # @brief Get ID of active configuration set + # + # Get ID of the current active configuration set. + # + # @param self + # + # @return The active configuration set ID + # + # @endif + # const char* getActiveId(void); + def getActiveId(self): + return self._activeId + + ## + # @if jp + # + # @brief コンフィギュレーションセットの存在確認 + # + # 指定したコンフィギュレーションセットが存在するか確認する。 + # + # @param self + # @param config_id 確認対象コンフィギュレーションセットID + # + # @return 存在確認結果(指定したConfigSetあり:true、なし:false) + # + # @else + # + # @brief Check the existence of configuration set + # + # Check the existence of specified configuration set. + # + # @param self + # @param config_id ID of target configuration set for confirmation + # @return Result of existence confirmation + # (Specified ConfigSet exists:true, else:false) + # @endif + # bool haveConfig(const char* config_id); + + def haveConfig(self, config_id): + if self._configsets.hasKey(config_id) is None: + return False + else: + return True + + ## + # @if jp + # + # @brief コンフィギュレーションセットのアクティブ化確認 + # + # コンフィギュレーションセットがアクティブ化されているか確認する。 + # + # @param self + # + # @return 状態確認結果(アクティブ状態:true、非アクティブ状態:false) + # + # @else + # + # @brief Confirm to activate configuration set + # + # Confirm that configuration set has been activated. + # + # @param self + # + # @return Result of state confirmation + # (Active state:true, Inactive state:false) + # + # @endif + # bool isActive(void); + + def isActive(self): + return self._active + + ## + # @if jp + # + # @brief 全コンフィギュレーションセットの取得 + # + # 設定されている全コンフィギュレーションセットを取得する。 + # + # @param self + # + # @return 全コンフィギュレーションセット + # + # @else + # + # @brief Get all configuration sets + # + # Get all specified configuration sets + # + # @param self + # + # @return All configuration sets + # + # @endif + # const std::vector& getConfigurationSets(void); + + def getConfigurationSets(self): + return self._configsets.getLeaf() + + ## + # @if jp + # + # @brief 指定したIDのコンフィギュレーションセットの取得 + # + # IDで指定したコンフィギュレーションセットを取得する。 + # 指定したコンフィギュレーションセットが存在しない場合は、 + # 空のコンフィギュレーションセットを返す。 + # + # @param self + # @param config_id 取得対象コンフィギュレーションセットのID + # + # @return コンフィギュレーションセット + # + # @else + # + # @brief Get a configuration set by specified ID + # + # Get a configuration set that was specified by ID + # Return empty configuration set, if a configuration set of + # specified ID doesn't exist. + # + # @param self + # @param config_id ID of the target configuration set for getting + # + # @return The configuration set + # + # @endif + # const coil::Properties& getConfigurationSet(const char* config_id); + def getConfigurationSet(self, config_id): + + prop = self._configsets.findNode(config_id) + if prop is None: + return self._emptyconf + return prop + + ## + # @if jp + # + # @brief 指定したプロパティのコンフィギュレーションセットへの追加 + # + # 指定したプロパティをコンフィギュレーションセットへ追加する。 + # + # @param self + # @param config_set 追加するプロパティ + # + # @return 追加処理実行結果(追加成功:true、追加失敗:false) + # + # @else + # + # @brief Add to configuration set from specified property + # + # Add specified property to configuration set. + # + # @param self + # @param configuration_set Property to add + # + # @return Add result (Successful:true, Failed:false) + # + # @endif + # bool setConfigurationSetValues(const coil::Properties& config_set) + + def setConfigurationSetValues(self, config_set): + node_ = config_set.getName() + if node_ == "" or node_ is None: + return False + + if not self._configsets.hasKey(node_): + return False + + p = self._configsets.getNode(node_) + # if p is None: + # return False + + p.mergeProperties(config_set) + self._changed = True + self._active = False + self.onSetConfigurationSet(config_set) + return True + + ## + # @if jp + # + # @brief アクティブ・コンフィギュレーションセットを取得 + # + # 現在アクティブとなっているコンフィギュレーションセットを取得する。 + # アクティブとなっているコンフィギュレーションセットが存在しない場合は、 + # 空のコンフィギュレーションセット を返す。 + # + # @param self + # + # @return アクティブ・コンフィギュレーションセット + # + # @else + # + # @brief Get the active configuration set + # + # Get the current active configuration set. + # Return empty configuration set, if an active configuration set + # doesn't exist. + # + # @param self + # @return The active configuration set + # + # @endif + # const coil::Properties& getActiveConfigurationSet(void); + + def getActiveConfigurationSet(self): + p = self._configsets.getNode(self._activeId) + # if p is None: + # return self._emptyconf + + return p + + ## + # @if jp + # + # @brief コンフィギュレーションセットに設定値を追加 + # + # コンフィギュレーションセットに設定値を追加する。 + # + # @param self + # @param configset 追加するプロパティ + # + # @return 追加処理結果(追加成功:true、追加失敗:false) + # + # @else + # + # @brief Add the configuration value to configuration set + # + # Add the configuration value to configuration set + # + # @param self + # @param configuration_set Property to add + # + # @return Add Result (Successful:true, Failed:false) + # + # @endif + # bool addConfigurationSet(const coil::Properties& configuration_set); + + def addConfigurationSet(self, configset): + if self._configsets.hasKey(configset.getName()): + return False + node = configset.getName() + + # Create node + self._configsets.createNode(node) + + p = self._configsets.getNode(node) + # if p is None: + # return False + + p.mergeProperties(configset) + self._newConfig.append(node) + + self._changed = True + self._active = False + self.onAddConfigurationSet(configset) + return True + + ## + # @if jp + # + # @brief コンフィギュレーションセットの削除 + # + # 指定したIDのコンフィギュレーションセットを削除する。 + # + # 指定したIDのコンフィギュレーションセットが存在しない場合は、 + # falseを返す。削除可能なコンフィギュレーションセットは、 + # addConfigruationSet() によって追加したコンフィギュレーションセッ + # トのみであり、デフォルトコンフィギュレーションセット、コンポーネ + # ント起動時にファイルから読み込まれるコンフィギュレーションセット + # は削除することができない。 + # + # また、指定したコンフィギュレーションセットが現在アクティブである + # 場合には、いかなるコンフィギュレーションセットでも削除できない。 + # + # この関数により実際にコンフィギュレーションセットが削除された場合、 + # setOnRemoveConfigurationSet() でセットされたコールバック関数が呼 + # び出される。 + # + # @param self + # @param config_id 削除対象コンフィギュレーションセットのID + # + # @return 削除処理結果(削除成功:true、削除失敗:false) + # + # @else + # + # @brief Remove the configuration set + # + # Remove the configuration set of specified ID Return empty + # configuration set, if a configuration set of specified ID + # doesn't exist. + # + # The configuration-sets that can be removed by this function are + # only configuration-sets newly added by the + # addConfigurationSet() function. The configuration that can be + # removed by this function is only newly added configuration-set + # by addConfigurationSet() function. The "default" + # configuration-set and configurationi-sets that is loaded from + # configuration file cannot be removed. + # + # If the specified configuration is active currently, any + # configurations are not deleted. + # + # Callback functions that are set by + # addOnRemovedConfigurationSet() will be called if a + # configuration-set is deleted actually by this function. + # + # @param self + # @param config_id ID of the target configuration set for remove + # + # @return Remove result (Successful:true, Failed:false) + # + # @endif + # + # bool removeConfigurationSet(const char* config_id); + + def removeConfigurationSet(self, config_id): + if config_id == "default": + return False + if self._activeId == config_id: + return False + + find_flg = False + # removeable config-set is only config-sets newly added + for (idx, conf) in enumerate(self._newConfig): + if conf == config_id: + find_flg = True + break + + if not find_flg: + return False + + p = self._configsets.getNode(config_id) + if p: + p.getRoot().removeNode(config_id) + del p + + del self._newConfig[idx] + + self._changed = True + self._active = False + self.onRemoveConfigurationSet(config_id) + return True + + ## + # @if jp + # + # @brief コンフィギュレーションセットのアクティブ化 + # + # 指定したIDのコンフィギュレーションセットをアクティブ化する。 + # 指定したIDのコンフィギュレーションセットが存在しない場合は、 + # falseを返す。 + # + # @param self + # @param config_id 削除対象コンフィギュレーションセットのID + # + # @return アクティブ処理結果(成功:true、失敗:false) + # + # @else + # + # @brief Activate the configuration set + # + # Activate the configuration set of specified ID + # Return empty configuration set, if a configuration set of + # specified ID doesn't exist. + # + # @param self + # @param config_id ID of the target configuration set for remove + # + # @return Activate result (Remove success:true、Remove failure:false) + # + # @endif + # bool activateConfigurationSet(const char* config_id); + + def activateConfigurationSet(self, config_id): + if config_id == "" or config_id is None: + return False + + # '_' is special configuration set name + if config_id[0] == '_': + return False + + if not self._configsets.hasKey(config_id): + return False + self._activeId = config_id + self._active = True + self._changed = True + self.onActivateSet(config_id) + return True + + # ------------------------------------------------------------ + # obsolete functions + # + + ## + # @if jp + # + # @brief OnUpdate のコールバックの設定 + # + # OnUpdate で呼ばれるコールバックのオブジェクトを設定する。 + # + # @param self + # @param cb OnUpdateCallback型のオブジェクト + # + # @else + # + # @brief Set callback that is called by OnUpdate. + # + # @param self + # @param cb OnUpdateCallback type object + # + # @endif + # + # void setOnUpdate(OnUpdateCallback* cb); + + def setOnUpdate(self, cb): + print("setOnUpdate function is obsolete.") + print("Use addConfigurationSetNameListener instead.") + self._listeners.addConfigurationSetNameListener( + OpenRTM_aist.ConfigurationSetNameListenerType.ON_UPDATE_CONFIG_SET, cb) + return + + ## + # @if jp + # + # @brief OnUpdateParam のコールバックの設定 + # + # OnUpdateParam で呼ばれるコールバックのオブジェクトを設定する。 + # + # @param self + # @param cb OnUpdateParamCallback型のオブジェクト + # + # @else + # + # @brief Set callback that is called by OnUpdateParam. + # + # @param self + # @param cb OnUpdateParamCallback type object + # + # @endif + # + # void setOnUpdateParam(OnUpdateParamCallback* cb); + + def setOnUpdateParam(self, cb): + print("setOnUpdateParam function is obsolete.") + print("Use addConfigurationParamListener instead.") + self._listeners.addConfigParamListener( + OpenRTM_aist.ConfigurationParamListenerType.ON_UPDATE_CONFIG_PARAM, cb) + return + + ## + # @if jp + # + # @brief OnSetConfigurationSet のコールバックの設定 + # + # OnSetConfigurationSet で呼ばれるコールバックのオブジェクトを設定する。 + # + # @param self + # @param cb OnSetConfigurationSetCallback型のオブジェクト + # + # @else + # + # @brief Set callback that is called by OnSetConfiguration. + # + # @param self + # @param cb OnSetConfigurationSetCallback type object + # + # @endif + # + # void setOnSetConfigurationSet(OnSetConfigurationSetCallback* cb); + + def setOnSetConfigurationSet(self, cb): + print("setOnSetConfigurationSet function is obsolete.") + print("Use addConfigurationSetListener instead.") + self._listeners.addConfigurationSetListener( + OpenRTM_aist.ConfigurationSetListenerType.ON_SET_CONFIG_SET, cb) + return + + ## + # @if jp + # + # @brief OnAddConfigurationSet のコールバックの設定 + # + # OnAddConfigurationSet で呼ばれるコールバックのオブジェクトを設定する。 + # + # @param self + # @param cb OnAddConfigurationAddCallback型のオブジェクト + # + # @else + # + # @brief Set callback that is called by OnSetConfiguration. + # + # @param self + # @param cb OnSetConfigurationSetCallback type object + # + # @endif + # + # void setOnAddConfigurationSet(OnAddConfigurationAddCallback* cb); + + def setOnAddConfigurationSet(self, cb): + print("setOnAddConfigurationSet function is obsolete.") + print("Use addConfigurationSetListener instead.") + self._listeners.addConfigurationSetListener( + OpenRTM_aist.ConfigurationSetListenerType.ON_ADD_CONFIG_SET, cb) + return + + ## + # @if jp + # + # @brief OnRemoveConfigurationSet のコールバックの設定 + # + # OnRemoveConfiguration で呼ばれるコールバックのオブジェクトを設定する。 + # + # @param self + # @param cb OnRemoveConfigurationSetCallback型のオブジェクト + # + # @else + # + # @brief Set callback that is called by OnRemoveConfigurationSet. + # + # @param self + # @param cb OnRemoveConfigurationSetCallback type object + # + # @endif + # + # void setOnRemoveConfigurationSet(OnRemoveConfigurationSetCallback* cb); + + def setOnRemoveConfigurationSet(self, cb): + print("setOnRemoveConfigurationSet function is obsolete.") + print("Use addConfigurationSetNameListener instead.") + self._listeners.addConfigurationSetNameListener( + OpenRTM_aist.ConfigurationSetNameListenerType.ON_REMOVE_CONFIG_SET, cb) + return + + ## + # @if jp + # + # @brief OnActivateSet のコールバックの設定 + # + # OnActivateSet で呼ばれるコールバックのオブジェクトを設定する。 + # + # @param self + # @param cb OnActivateSetCallback型のオブジェクト + # + # @else + # + # @brief Set callback that is called by OnActivateSet. + # + # @param self + # @param cb OnActivateSetCallback type object + # + # @endif + # + # void setOnActivateSet(OnActivateSetCallback* cb); + + def setOnActivateSet(self, cb): + print("setOnActivateSet function is obsolete.") + print("Use addConfigurationSetNameListener instead.") + self._listeners.addConfigurationSetNameListener( + OpenRTM_aist.ConfigurationSetNameListenerType.ON_ACTIVATE_CONFIG_SET, cb) + return + + # + # end of obsolete functions + # ------------------------------------------------------------ + + ## + # @if jp + # + # @brief ConfigurationParamListener を追加する + # + # update(const char* config_set, const char* config_param) が呼ばれた際に + # コールされるリスナ ConfigurationParamListener を追加する。 + # type には現在のところ ON_UPDATE_CONFIG_PARAM のみが入る。 + # + # @param type ConfigurationParamListenerType型の値。 + # ON_UPDATE_CONFIG_PARAM がある。 + # + # @param listener ConfigurationParamListener 型のリスナオブジェクト。 + # + # @else + # + # @brief Adding ConfigurationParamListener + # + # This function adds a listener object which is called when + # update(const char* config_set, const char* config_param) is + # called. In the type argument, currently only + # ON_UPDATE_CONFIG_PARAM is allowed. + # + # @param type ConfigurationParamListenerType value + # ON_UPDATE_CONFIG_PARAM is only allowed. + # + # @param listener ConfigurationParamListener listener object. + # + # @endif + # + # void addConfigurationParamListener(ConfigurationParamListenerType type, + # ConfigurationParamListener* listener); + def addConfigurationParamListener(self, type, listener): + self._listeners.addConfigParamListener(type, listener) + return + + ## + # @if jp + # + # @brief ConfigurationParamListener を削除する + # + # addConfigurationParamListener で追加されたリスナオブジェクトを削除する。 + # + # @param type ConfigurationParamListenerType型の値。 + # ON_UPDATE_CONFIG_PARAM がある。 + # @param listener 与えたリスナオブジェクトへのポインタ + # + # @else + # + # @brief Removing ConfigurationParamListener + # + # This function removes a listener object which is added by + # addConfigurationParamListener() function. + # + # @param type ConfigurationParamListenerType value + # ON_UPDATE_CONFIG_PARAM is only allowed. + # @param listener a pointer to ConfigurationParamListener listener object. + # + # @endif + # + # void removeConfigurationParamListener(ConfigurationParamListenerType type, + # ConfigurationParamListener* listener); + + def removeConfigurationParamListener(self, type, listener): + self._listeners.removeConfigParamListener(type, listener) + return + + ## + # @if jp + # + # @brief ConfigurationSetListener を追加する + # + # ConfigurationSet が更新されたときなどに呼ばれるリスナ + # ConfigurationSetListener を追加する。設定可能なイベントは以下の + # 2種類がある。 + # + # - ON_SET_CONFIG_SET: setConfigurationSetValues() で + # ConfigurationSet に値が設定された場合。 + # - ON_ADD_CONFIG_SET: addConfigurationSet() で新しい + # ConfigurationSet が追加された場合。 + # + # @param type ConfigurationSetListenerType型の値。 + # @param listener ConfigurationSetListener 型のリスナオブジェクト。 + # + # @else + # + # @brief Adding ConfigurationSetListener + # + # This function add a listener object which is called when + # ConfigurationSet is updated. Available events are the followings. + # + # @param type ConfigurationSetListenerType value + # @param listener ConfigurationSetListener listener object. + # + # @endif + # + # void addConfigurationSetListener(ConfigurationSetListenerType type, + # ConfigurationSetListener* listener); + + def addConfigurationSetListener(self, type, listener): + self._listeners.addConfigurationSetListener(type, listener) + return + + ## + # @if jp + # + # @brief ConfigurationSetListener を削除する + # + # addConfigurationSetListener で追加されたリスナオブジェクトを削除する。 + # + # @param type ConfigurationSetListenerType型の値。 + # @param listener 与えたリスナオブジェクトへのポインタ + # + # @else + # + # @brief Removing ConfigurationSetListener + # + # This function removes a listener object which is added by + # addConfigurationSetListener() function. + # + # @param type ConfigurationSetListenerType value + # @param listener a pointer to ConfigurationSetListener listener object. + # + # @endif + # void removeConfigurationSetListener(ConfigurationSetListenerType type, + # ConfigurationSetListener* listener); + + def removeConfigurationSetListener(self, type, listener): + self._listeners.removeConfigurationSetListener(type, listener) + return + + ## + # @if jp + # + # @brief ConfigurationSetNameListener を追加する + # + # ConfigurationSetName が更新されたときなどに呼ばれるリスナ + # ConfigurationSetNameListener を追加する。設定可能なイベントは以下の + # 3種類がある。 + # + # - ON_UPDATE_CONFIG_SET: ある ConfigurationSet がアップデートされた + # - ON_REMOVE_CONFIG_SET: ある ConfigurationSet が削除された + # - ON_ACTIVATE_CONFIG_SET: ある ConfigurationSet がアクティブ化された + # + # @param type ConfigurationSetNameListenerType型の値。 + # @param listener ConfigurationSetNameListener 型のリスナオブジェクト。 + # + # @else + # + # @brief Adding ConfigurationSetNameListener + # + # This function add a listener object which is called when + # ConfigurationSetName is updated. Available events are the followings. + # + # - ON_UPDATE_CONFIG_SET: A ConfigurationSet has been updated. + # - ON_REMOVE_CONFIG_SET: A ConfigurationSet has been deleted. + # - ON_ACTIVATE_CONFIG_SET: A ConfigurationSet has been activated. + # + # @param type ConfigurationSetNameListenerType value + # @param listener ConfigurationSetNameListener listener object. + # + # @endif + # void + # addConfigurationSetNameListener(ConfigurationSetNameListenerType type, + # ConfigurationSetNameListener* listener); + + def addConfigurationSetNameListener(self, type, listener): + self._listeners.addConfigurationSetNameListener(type, listener) + return + + ## + # @if jp + # + # @brief ConfigurationSetNameListener を削除する + # + # addConfigurationSetNameListener で追加されたリスナオブジェクトを + # 削除する。 + # + # @param type ConfigurationSetNameListenerType型の値。 + # ON_UPDATE_CONFIG_PARAM がある。 + # @param listener 与えたリスナオブジェクトへのポインタ + # + # @else + # + # @brief Removing ConfigurationSetNameListener + # + # This function removes a listener object which is added by + # addConfigurationSetNameListener() function. + # + # @param type ConfigurationSetNameListenerType value + # ON_UPDATE_CONFIG_PARAM is only allowed. + # @param listener a pointer to ConfigurationSetNameListener + # listener object. + # + # @endif + # void + # removeConfigurationSetNameListener(ConfigurationSetNameListenerType type, + # ConfigurationSetNameListener* listener); + + def removeConfigurationSetNameListener(self, type, listener): + self._listeners.removeConfigurationSetNameListener(type, listener) + return + + ## + # @if jp + # + # @brief コンフィギュレーションパラメータの更新(ID指定)時にコールされる + # + # 設定されてるコールバックオブジェクトを呼び出す。 + # + # @param self + # @param config_set 設定対象のコンフィギュレーションセットID + # + # @else + # + # @brief When the configuration parameter is updated, it is called. + # + # Call the set callback object. + # + # @param self + # @param config_set The target configuration set's ID to setup + # + # @endif + # + # void onUpdate(const char* config_set); + + def onUpdate(self, config_set): + self._listeners.notifyConfigurationSetName( + OpenRTM_aist.ConfigurationSetNameListenerType.ON_UPDATE_CONFIG_SET, config_set) + return + + ## + # @if jp + # + # @brief コンフィギュレーションパラメータの更新(名称指定)時にコールされる + # + # 設定されてるコールバックオブジェクトを呼び出す。 + # + # @param self + # @param config_param コンフィギュレーションパラメータ名 + # @param config_value コンフィギュレーション値 + # + # @else + # + # @brief When the configuration parameter is updated, it is called. + # + # Call the set callback object. + # + # @param self + # @param config_param configuration parameter name. + # @param config_value configuration value. + # + # @endif + # + # void onUpdateParam(const char* config_param, const char* config_value); + + def onUpdateParam(self, config_param, config_value): + self._changedParam.append(config_param) + self._listeners.notifyConfigParam(OpenRTM_aist.ConfigurationParamListenerType.ON_UPDATE_CONFIG_PARAM, config_param, + config_value) + return + + ## + # @if jp + # + # @brief コンフィギュレーションセットへの追加時にコールされる + # + # 設定されてるコールバックオブジェクトを呼び出す。 + # + # @param self + # @param configuration_set プロパティ + # + # @else + # + # @brief Called when the property is added to the configuration set + # + # Call the set callback object. + # + # @param self + # @param configuration_set property + # + # @endif + # + # void onSetConfigurationSet(const coil::Properties& config_set); + + def onSetConfigurationSet(self, config_set): + self._listeners.notifyConfigurationSet( + OpenRTM_aist.ConfigurationSetListenerType.ON_SET_CONFIG_SET, config_set) + return + + ## + # @if jp + # + # @brief 設定値が追加されたときにコールされる。 + # + # 設定されてるコールバックオブジェクトを呼び出す。 + # + # @param self + # @param configuration_set プロパティ + # + # @else + # + # @brief Called when a set value is added to the configuration set + # + # Call the set callback object. + # + # @param self + # @param configuration_set property + # + # @endif + # + # void onAddConfigurationSet(const coil::Properties& config_set); + + def onAddConfigurationSet(self, config_set): + self._listeners.notifyConfigurationSet( + OpenRTM_aist.ConfigurationSetListenerType.ON_ADD_CONFIG_SET, config_set) + return + + ## + # @if jp + # + # @brief セットが削除されてるときにコールされる。 + # + # 設定されてるコールバックオブジェクトを呼び出す。 + # + # @param self + # @param config_id プロパティ + # + # @else + # + # @brief Called when the configuration set has been deleted + # + # Call the set callback object. + # + # @param self + # @param config_id property + # + # @endif + # + # void onRemoveConfigurationSet(const char* config_id); + + def onRemoveConfigurationSet(self, config_id): + self._listeners.notifyConfigurationSetName( + OpenRTM_aist.ConfigurationSetNameListenerType.ON_REMOVE_CONFIG_SET, config_id) + return + + ## + # @if jp + # + # @brief セットがアクティブ化されたときにコールされる。 + # + # 設定されてるコールバックオブジェクトを呼び出す。 + # + # @param self + # @param config_id プロパティ + # + # @else + # + # @brief Called when the configuration set is made active + # + # Call the set callback object. + # + # @param self + # @param config_id property + # + # @endif + # + # void onActivateSet(const char* config_id); + + def onActivateSet(self, config_id): + self._listeners.notifyConfigurationSetName( + OpenRTM_aist.ConfigurationSetNameListenerType.ON_ACTIVATE_CONFIG_SET, config_id) + return + + class find_conf: + def __init__(self, name): + self._name = name + return + + def __call__(self, conf): + if conf is None: + return False + + return self._name == conf.name diff --git a/OpenRTM_aist/ConfigurationListener.py b/OpenRTM_aist/ConfigurationListener.py index b75d1b57..567418a5 100644 --- a/OpenRTM_aist/ConfigurationListener.py +++ b/OpenRTM_aist/ConfigurationListener.py @@ -1,5 +1,5 @@ #!/usr/bin/env python -# -*- coding: euc-jp -*- +# -*- coding: utf-8 -*- ## # @file ConfigurationListener.py @@ -14,41 +14,39 @@ # All rights reserved. - ## # @if jp -# @brief ConfigurationParamListener Υ +# @brief ConfigurationParamListener のタイプ # # - ON_UPDATE_CONFIG_PARAM, # # @else -# @brief The types of ConnectorDataListener -# +# @brief The types of ConfigurationParamListenerType +# # - ON_UPDATE_CONFIG_PARAM, # # @endif # class ConfigurationParamListenerType: - """ - """ + """ + """ - def __init__(self): - pass - - ON_UPDATE_CONFIG_PARAM = 0 - CONFIG_PARAM_LISTENER_NUM = 1 + def __init__(self): + pass + ON_UPDATE_CONFIG_PARAM = 0 + CONFIG_PARAM_LISTENER_NUM = 1 ## # @if jp -# @class ConfigurationParamListener 饹 -# @brief ConfigurationParamListener 饹 +# @class ConfigurationParamListener クラス +# @brief ConfigurationParamListener クラス # -# Configuration ѥ᡼ѹ˴ؤꥹʥ饹 -# ʲΥ٥ȤФƥХå롣 +# Configuration パラメータの変更に関するリスナクラス。 +# 以下のイベントに対してコールバックされる。 # -# - ON_UPDATE_CONFIG_PARAM: ѥ᡼ѹ줿 +# - ON_UPDATE_CONFIG_PARAM: パラメータが変更された # # @else # @class ConfigurationParamListener class @@ -62,116 +60,113 @@ def __init__(self): # # @endif class ConfigurationParamListener: - """ - """ - - def __init__(self): - pass - - ## - # @if jp - # - # @brief ConfigurationParamListenerType ʸѴ - # - # ConfigurationParamListenerType ʸѴ - # - # @param type Ѵо ConfigurationParamListenerType - # - # @return ʸѴ - # - # @else - # - # @brief Convert ConfigurationParamListenerType into the string. - # - # Convert ConfigurationParamListenerType into the string. - # - # @param type The target ConfigurationParamListenerType for transformation - # - # @return Trnasformation result of string representation - # - # @endif - # static const char* toString(ConfigurationParamListenerType type) - def toString(type): - typeString = ["ON_UPDATE_CONFIG_PARAM", - "CONFIG_PARAM_LISTENER_NUM"] - - if type < ConfigurationParamListenerType.CONFIG_PARAM_LISTENER_NUM: - return typeString[type] - - return ""; - - toString = staticmethod(toString) - - - ## - # @if jp - # @brief ǥȥ饯 - # @else - # @brief Destructor - # @endif - def __del__(self): - pass - - - ## - # @if jp - # - # @brief ۥХåؿ - # - # ConfigurationParamListener ΥХåؿ - # - # @else - # - # @brief Virtual Callback function - # - # This is a the Callback function for ConfigurationParamListener. - # - # @endif - # virtual void operator()(const char* config_set_name, - # const char* config_param_name) = 0; - def __call__(self, config_set_name, config_param_name): - pass - - - -#============================================================ + """ + """ + + def __init__(self): + pass + + ## + # @if jp + # + # @brief ConfigurationParamListenerType を文字列に変換 + # + # ConfigurationParamListenerType を文字列に変換する + # + # @param type 変換対象 ConfigurationParamListenerType + # + # @return 文字列変換結果 + # + # @else + # + # @brief Convert ConfigurationParamListenerType into the string. + # + # Convert ConfigurationParamListenerType into the string. + # + # @param type The target ConfigurationParamListenerType for transformation + # + # @return Trnasformation result of string representation + # + # @endif + # static const char* toString(ConfigurationParamListenerType type) + def toString(status): + typeString = ["ON_UPDATE_CONFIG_PARAM"] + + if status < len(typeString): + return typeString[status] + + return "" + + toString = staticmethod(toString) + + ## + # @if jp + # @brief デストラクタ + # @else + # @brief Destructor + # @endif + + def __del__(self): + pass + + ## + # @if jp + # + # @brief 仮想コールバック関数 + # + # ConfigurationParamListener のコールバック関数 + # + # @else + # + # @brief Virtual Callback function + # + # This is a the Callback function for ConfigurationParamListener. + # + # @endif + # virtual void operator()(const char* config_set_name, + # const char* config_param_name) = 0; + + def __call__(self, config_set_name, config_param_name): + pass + + +# ============================================================ ## # @if jp -# @brief ConfigurationSetListener Υ +# @brief ConfigurationSetListener のタイプ # -# - ON_SET_CONFIG_SET: ConfigurationSet ñ̤ͤåȤ줿 -# - ON_ADD_CONFIG_SET: ConfigurationSet ɲä줿 +# - ON_SET_CONFIG_SET: ConfigurationSet 単位で値がセットされた +# - ON_ADD_CONFIG_SET: ConfigurationSet が追加された # # @else # @brief The types of ConfigurationSetListener -# -# - ON_SET_CONFIG_SET: Value list has been set as a configuration set +# +# - ON_SET_CONFIG_SET: Value list has been set as a configuration set # - ON_ADD_CONFIG_SET: A new configuration set has been added # # @endif class ConfigurationSetListenerType: - """ - """ - - def __init__(self): - pass + """ + """ - ON_SET_CONFIG_SET = 0 - ON_ADD_CONFIG_SET = 1 - CONFIG_SET_LISTENER_NUM = 2 + def __init__(self): + pass + ON_SET_CONFIG_SET = 0 + ON_ADD_CONFIG_SET = 1 + CONFIG_SET_LISTENER_NUM = 2 ## # @if jp -# @class ConfigurationSetListener 饹 -# @brief ConfigurationSetListener 饹 +# @class ConfigurationSetListener クラス +# @brief ConfigurationSetListener クラス # -# ConfigurationåȤѹ줿ɲä줿˸ƤӽФꥹʥ饹 -# ʲConfigurationåȤ˴Ϣ륤٥ȤФꥹʡ +# Configurationセットが変更されたり追加された場合に呼び出されるリスナクラス。 +# 以下のConfigurationセットに関連するイベントに対するリスナ。 # -# - ON_SET_CONFIG_SET: ConfigurationSet ñ̤ͤåȤ줿 -# - ON_ADD_CONFIG_SET: ConfigurationSet ɲä줿 +# - ON_SET_CONFIG_SET: ConfigurationSet 単位で値がセットされた +# - ON_ADD_CONFIG_SET: ConfigurationSet が追加された # # @else # @class ConfigurationSetListener class @@ -180,113 +175,110 @@ def __init__(self): # This class is abstract base class for listener classes that # provides callbacks for configuration set's related events. # -# - ON_SET_CONFIG_SET: Value list has been set as a configuration set +# - ON_SET_CONFIG_SET: Value list has been set as a configuration set # - ON_ADD_CONFIG_SET: A new configuration set has been added # # @endif class ConfigurationSetListener: - """ - """ - - def __init__(self): - pass - - - ## - # @if jp - # - # @brief ConfigurationSetListenerType ʸѴ - # - # ConfigurationSetListenerType ʸѴ - # - # @param type Ѵо ConfigurationSetListenerType - # - # @return ʸѴ - # - # @else - # - # @brief Convert ConfigurationSetListenerType into the string. - # - # Convert ConfigurationSetListenerType into the string. - # - # @param type The target ConfigurationSetListenerType for - # transformation - # - # @return Trnasformation result of string representation - # - # @endif - # static const char* toString(ConfigurationSetListenerType type) - def toString(type): - typeString = ["ON_SET_CONFIG_SET", - "ON_ADD_CONFIG_SET", - "CONFIG_SET_LISTENER_NUM"] - if type < ConfigurationSetListenerType.CONFIG_SET_LISTENER_NUM: - return typeString[type] - - return ""; - - toString = staticmethod(toString) - - - ## - # @if jp - # @brief ǥȥ饯 - # @else - # @brief Destructor - # @endif - def __del__(self): - pass - - - ## - # @if jp - # - # @brief ۥХåؿ - # - # ConfigurationSetListener ΥХåؿ - # - # @else - # - # @brief Virtual Callback function - # - # This is a the Callback function for ConfigurationSetListener - # - # @endif - # virtual void operator()(const coil::Properties& config_set) = 0; - def __call__(self, config_set): - pass - - - -#============================================================ + """ + """ + + def __init__(self): + pass + + ## + # @if jp + # + # @brief ConfigurationSetListenerType を文字列に変換 + # + # ConfigurationSetListenerType を文字列に変換する + # + # @param type 変換対象 ConfigurationSetListenerType + # + # @return 文字列変換結果 + # + # @else + # + # @brief Convert ConfigurationSetListenerType into the string. + # + # Convert ConfigurationSetListenerType into the string. + # + # @param type The target ConfigurationSetListenerType for + # transformation + # + # @return Trnasformation result of string representation + # + # @endif + # static const char* toString(ConfigurationSetListenerType type) + + def toString(status): + typeString = ["ON_SET_CONFIG_SET", + "ON_ADD_CONFIG_SET"] + if status < len(typeString): + return typeString[status] + + return "" + + toString = staticmethod(toString) + + ## + # @if jp + # @brief デストラクタ + # @else + # @brief Destructor + # @endif + + def __del__(self): + pass + + ## + # @if jp + # + # @brief 仮想コールバック関数 + # + # ConfigurationSetListener のコールバック関数 + # + # @else + # + # @brief Virtual Callback function + # + # This is a the Callback function for ConfigurationSetListener + # + # @endif + # virtual void operator()(const coil::Properties& config_set) = 0; + + def __call__(self, config_set): + pass + + +# ============================================================ ## # @if jp # @brief ConfigurationSetNameListenerType # # @else # @brief The types of ConfigurationSetNameListener -# +# # @endif class ConfigurationSetNameListenerType: - """ - """ + """ + """ - def __init__(self): - pass - - ON_UPDATE_CONFIG_SET = 0 - ON_REMOVE_CONFIG_SET = 1 - ON_ACTIVATE_CONFIG_SET = 2 - CONFIG_SET_NAME_LISTENER_NUM = 3 + def __init__(self): + pass + ON_UPDATE_CONFIG_SET = 0 + ON_REMOVE_CONFIG_SET = 1 + ON_ACTIVATE_CONFIG_SET = 2 + CONFIG_SET_NAME_LISTENER_NUM = 3 ## # @if jp -# @class ConfigurationSetNameListener 饹 -# @brief ConfigurationSetNameListener 饹 +# @class ConfigurationSetNameListener クラス +# @brief ConfigurationSetNameListener クラス # -# ConfigurationSet˴ؤ륤٥Ȥ˴ؤꥹʡ饹 +# ConfigurationSetに関するイベントに関するリスナークラス。 # # - ON_UPDATE_CONFIG_SET: # - ON_REMOVE_CONFIG_SET: @@ -305,111 +297,84 @@ def __init__(self): # # @endif class ConfigurationSetNameListener: - """ - """ - - def __init__(self): - pass - - - ## - # @if jp - # - # @brief ConfigurationSetNameListenerType ʸѴ - # - # ConfigurationSetNameListenerType ʸѴ - # - # @param type Ѵо ConfigurationSetNameListenerType - # - # @return ʸѴ - # - # @else - # - # @brief Convert ConfigurationSetNameListenerType into the string. - # - # Convert ConfigurationSetNameListenerType into the string. - # - # @param type The target ConfigurationSetNameListenerType for - # transformation - # - # @return Trnasformation result of string representation - # - # @endif - # static const char* toString(ConfigurationSetNameListenerType type) - def toString(type): - typeString = ["ON_UPDATE_CONFIG_SET", - "ON_REMOVE_CONFIG_SET", - "ON_ACTIVATE_CONFIG_SET", - "CONFIG_SET_NAME_LISTENER_NUM"] - if type < ConfigurationSetNameListenerType.CONFIG_SET_NAME_LISTENER_NUM: - return typeString[type] - - return ""; - - toString = staticmethod(toString) - - - ## - # @if jp - # @brief ǥȥ饯 - # @else - # @brief Destructor - # @endif - def __del__(self): - pass - - - ## - # @if jp - # - # @brief ۥХåؿ - # - # ConfigurationSetNameListener ΥХåؿ - # - # @else - # - # @brief Virtual Callback function - # - # This is a the Callback function for ConfigurationSetNameListener. - # - # @endif - # virtual void operator()(const char* config_set_name) = 0; - def __call__(self, config_set_name): - pass + """ + """ + def __init__(self): + pass + ## + # @if jp + # + # @brief ConfigurationSetNameListenerType を文字列に変換 + # + # ConfigurationSetNameListenerType を文字列に変換する + # + # @param type 変換対象 ConfigurationSetNameListenerType + # + # @return 文字列変換結果 + # + # @else + # + # @brief Convert ConfigurationSetNameListenerType into the string. + # + # Convert ConfigurationSetNameListenerType into the string. + # + # @param type The target ConfigurationSetNameListenerType for + # transformation + # + # @return Trnasformation result of string representation + # + # @endif + # static const char* toString(ConfigurationSetNameListenerType type) -## -# @if jp -# -# @class Entry -# @brief ꥹʡȼưե饰ǼѤѥ饹 -# -# ꥹʡ֥ȤȼưΤΥե饰Ǽ뤿ѥ饹 -# -# @else -# -# @class Entry -# @brief Listner and autoclean-flag holder class -# -# A general-purpose class to store away a listener object and -# a flag for automatic deletion -# -# @endif -class Entry: - def __init__(self,listener,autoclean): - self.listener = listener - self.autoclean = autoclean - return + def toString(status): + typeString = ["ON_UPDATE_CONFIG_SET", + "ON_REMOVE_CONFIG_SET", + "ON_ACTIVATE_CONFIG_SET"] + if status < len(typeString): + return typeString[status] + + return "" + + toString = staticmethod(toString) + + ## + # @if jp + # @brief デストラクタ + # @else + # @brief Destructor + # @endif + + def __del__(self): + pass + + ## + # @if jp + # + # @brief 仮想コールバック関数 + # + # ConfigurationSetNameListener のコールバック関数 + # + # @else + # + # @brief Virtual Callback function + # + # This is a the Callback function for ConfigurationSetNameListener. + # + # @endif + # virtual void operator()(const char* config_set_name) = 0; + def __call__(self, config_set_name): + pass ## # @if jp # @class ConfigurationParamListenerHolder -# @brief ConfigurationParamListener ۥ饹 +# @brief ConfigurationParamListener ホルダクラス # -# ʣ ConfigurationParamListener ݻ륯饹 +# 複数の ConfigurationParamListener を保持し管理するクラス。 # # @else # @class ConfigurationParamListenerHolder @@ -420,123 +385,114 @@ def __init__(self,listener,autoclean): # # @endif class ConfigurationParamListenerHolder: - """ - """ - - ## - # @if jp - # @brief 󥹥ȥ饯 - # @else - # @brief Constructor - # @endif - # ConfigurationParamListenerHolder(); - def __init__(self): - self._listeners = [] - pass - - - ## - # @if jp - # @brief ǥȥ饯 - # @else - # @brief Destructor - # @endif - def __del__(self): - for (idx, listener) in enumerate(self._listeners): - if listener.autoclean: - del self._listeners[idx] - #self._listeners[idx] = None - return - - - ## - # @if jp - # - # @brief ꥹʡɲ - # - # ꥹʡɲä롣 - # - # @param listener ɲäꥹ - # @param autoclean true:ǥȥ饯Ǻ, - # false:ǥȥ饯Ǻʤ - # @else - # - # @brief Add the listener. - # - # This method adds the listener. - # - # @param listener Added listener - # @param autoclean true:The listener is deleted at the destructor., - # false:The listener is not deleted at the destructor. - # @endif - # void addListener(ConfigurationParamListener* listener, bool autoclean); - def addListener(self, listener, autoclean): - self._listeners.append(Entry(listener, autoclean)) - return - - - ## - # @if jp - # - # @brief ꥹʡκ - # - # ꥹʤ롣 - # - # @param listener ꥹ - # @else - # - # @brief Remove the listener. - # - # This method removes the listener. - # - # @param listener Removed listener - # @endif - # void removeListener(ConfigurationParamListener* listener); - def removeListener(self, listener): - len_ = len(self._listeners) - for i in range(len_): - idx = (len_ - 1) - i - if self._listeners[idx].listener == listener: - if self._listeners[idx].autoclean: - self._listeners[idx].listener = None - del self._listeners[idx] - return - return - - - ## - # @if jp - # - # @brief ꥹʡΤ - # - # ϿƤꥹʤΥХå᥽åɤƤӽФ - # - # @param info ConnectorInfo - # @param cdrdata ǡ - # @else - # - # @brief Notify listeners. - # - # This calls the Callback method of the registered listener. - # - # @param info ConnectorInfo - # @param cdrdata Data - # @endif - # void notify(const char* config_set_name, const char* config_param_name); - def notify(self, config_set_name, config_param_name): - for listener in self._listeners: - listener.listener(config_set_name, config_param_name) - return - - - -#============================================================ + """ + """ + + ## + # @if jp + # @brief コンストラクタ + # @else + # @brief Constructor + # @endif + # ConfigurationParamListenerHolder(); + def __init__(self): + self._listeners = [] + pass + + ## + # @if jp + # @brief デストラクタ + # @else + # @brief Destructor + # @endif + + def __del__(self): + for (idx, listener) in enumerate(self._listeners): + del self._listeners[idx] + return + + ## + # @if jp + # + # @brief リスナーの追加 + # + # リスナーを追加する。 + # + # @param listener 追加するリスナ + # @else + # + # @brief Add the listener. + # + # This method adds the listener. + # + # @param listener Added listener + # @endif + # void addListener(ConfigurationParamListener* listener); + + def addListener(self, listener): + self._listeners.append(listener) + return + + ## + # @if jp + # + # @brief リスナーの削除 + # + # リスナを削除する。 + # + # @param listener 削除するリスナ + # @else + # + # @brief Remove the listener. + # + # This method removes the listener. + # + # @param listener Removed listener + # @endif + # void removeListener(ConfigurationParamListener* listener); + + def removeListener(self, listener): + len_ = len(self._listeners) + for i in range(len_): + idx = (len_ - 1) - i + if self._listeners[idx] == listener: + del self._listeners[idx] + return + return + + ## + # @if jp + # + # @brief リスナーへ通知する + # + # 登録されているリスナのコールバックメソッドを呼び出す。 + # + # @param info ConnectorInfo + # @param cdrdata データ + # @else + # + # @brief Notify listeners. + # + # This calls the Callback method of the registered listener. + # + # @param info ConnectorInfo + # @param cdrdata Data + # @endif + # void notify(const char* config_set_name, const char* config_param_name); + + def notify(self, config_set_name, config_param_name): + for listener in self._listeners: + listener(config_set_name, config_param_name) + return + + +# ============================================================ ## # @if jp # @class ConfigurationSetListenerHolder -# @brief ConfigurationSetListener ۥ饹 +# @brief ConfigurationSetListener ホルダクラス # -# ʣ ConfigurationSetListener ݻ륯饹 +# 複数の ConfigurationSetListener を保持し管理するクラス。 # # @else # @class ConfigurationSetListenerHolder @@ -547,123 +503,112 @@ def notify(self, config_set_name, config_param_name): # # @endif class ConfigurationSetListenerHolder: - """ - """ - - ## - # @if jp - # @brief 󥹥ȥ饯 - # @else - # @brief Constructor - # @endif - # ConfigurationSetListenerHolder(); - def __init__(self): - self._listeners = [] - pass - - - ## - # @if jp - # @brief ǥȥ饯 - # @else - # @brief Destructor - # @endif - def __del__(self): - for (idx, listener) in enumerate(self._listeners): - if listener.autoclean: - del self._listeners[idx] - #self._listeners[idx] = None - return - - - ## - # @if jp - # - # @brief ꥹʡɲ - # - # ꥹʡɲä롣 - # - # @param listener ɲäꥹ - # @param autoclean true:ǥȥ饯Ǻ, - # false:ǥȥ饯Ǻʤ - # @else - # - # @brief Add the listener. - # - # This method adds the listener. - # - # @param listener Added listener - # @param autoclean true:The listener is deleted at the destructor., - # false:The listener is not deleted at the destructor. - # @endif - # void addListener(ConfigurationSetListener* listener, bool autoclean); - def addListener(self, listener, autoclean): - self._listeners.append(Entry(listener, autoclean)) - return - - - ## - # @if jp - # - # @brief ꥹʡκ - # - # ꥹʤ롣 - # - # @param listener ꥹ - # @else - # - # @brief Remove the listener. - # - # This method removes the listener. - # - # @param listener Removed listener - # @endif - # void removeListener(ConfigurationSetListener* listener); - def removeListener(self, listener): - len_ = len(self._listeners) - for i in range(len_): - idx = (len_ - 1) - i - if self._listeners[idx].listener == listener: - if self._listeners[idx].autoclean: - self._listeners[idx].listener = None - del self._listeners[idx] - return - return - - - ## - # @if jp - # - # @brief ꥹʡΤ - # - # ϿƤꥹʤΥХå᥽åɤƤӽФ - # - # @param info ConnectorInfo - # @param cdrdata ǡ - # @else - # - # @brief Notify listeners. - # - # This calls the Callback method of the registered listener. - # - # @param info ConnectorInfo - # @param cdrdata Data - # @endif - # void notify(const coil::Properties& config_set); - def notify(self, config_set): - for listener in self._listeners: - listener.listener(config_set) - return - - - -#============================================================ + """ + """ + + ## + # @if jp + # @brief コンストラクタ + # @else + # @brief Constructor + # @endif + # ConfigurationSetListenerHolder(); + def __init__(self): + self._listeners = [] + pass + + ## + # @if jp + # @brief デストラクタ + # @else + # @brief Destructor + # @endif + + def __del__(self): + return + + ## + # @if jp + # + # @brief リスナーの追加 + # + # リスナーを追加する。 + # + # @param listener 追加するリスナ + # @else + # + # @brief Add the listener. + # + # This method adds the listener. + # + # @param listener Added listener + # @endif + # void addListener(ConfigurationSetListener* listener); + + def addListener(self, listener): + self._listeners.append(listener) + return + + ## + # @if jp + # + # @brief リスナーの削除 + # + # リスナを削除する。 + # + # @param listener 削除するリスナ + # @else + # + # @brief Remove the listener. + # + # This method removes the listener. + # + # @param listener Removed listener + # @endif + # void removeListener(ConfigurationSetListener* listener); + + def removeListener(self, listener): + len_ = len(self._listeners) + for i in range(len_): + idx = (len_ - 1) - i + if self._listeners[idx] == listener: + del self._listeners[idx] + return + return + + ## + # @if jp + # + # @brief リスナーへ通知する + # + # 登録されているリスナのコールバックメソッドを呼び出す。 + # + # @param info ConnectorInfo + # @param cdrdata データ + # @else + # + # @brief Notify listeners. + # + # This calls the Callback method of the registered listener. + # + # @param info ConnectorInfo + # @param cdrdata Data + # @endif + # void notify(const coil::Properties& config_set); + + def notify(self, config_set): + for listener in self._listeners: + listener(config_set) + return + + +# ============================================================ ## # @if jp -# @class ConfigurationSetNameListenerHolder -# @brief ConfigurationSetNameListener ۥ饹 +# @class ConfigurationSetNameListenerHolder +# @brief ConfigurationSetNameListener ホルダクラス # -# ʣ ConfigurationSetNameListener ݻ륯饹 +# 複数の ConfigurationSetNameListener を保持し管理するクラス。 # # @else # @class ConfigurationSetNameListenerHolder @@ -674,119 +619,108 @@ def notify(self, config_set): # # @endif class ConfigurationSetNameListenerHolder: - """ - """ - - ## - # @if jp - # @brief 󥹥ȥ饯 - # @else - # @brief Constructor - # @endif - # ConfigurationSetNameListenerHolder(); - def __init__(self): - self._listeners = [] - pass - - - ## - # @if jp - # @brief ǥȥ饯 - # @else - # @brief Destructor - # @endif - def __del__(self): - for (idx, listener) in enumerate(self._listeners): - if listener.autoclean: - del self._listeners[idx] - #self._listeners[idx] = None - return - - - ## - # @if jp - # - # @brief ꥹʡɲ - # - # ꥹʡɲä롣 - # - # @param listener ɲäꥹ - # @param autoclean true:ǥȥ饯Ǻ, - # false:ǥȥ饯Ǻʤ - # @else - # - # @brief Add the listener. - # - # This method adds the listener. - # - # @param listener Added listener - # @param autoclean true:The listener is deleted at the destructor., - # false:The listener is not deleted at the destructor. - # @endif - # void addListener(ConfigurationSetNameListener* listener, bool autoclean); - def addListener(self, listener, autoclean): - self._listeners.append(Entry(listener, autoclean)) - return - - - ## - # @if jp - # - # @brief ꥹʡκ - # - # ꥹʤ롣 - # - # @param listener ꥹ - # @else - # - # @brief Remove the listener. - # - # This method removes the listener. - # - # @param listener Removed listener - # @endif - # void removeListener(ConfigurationSetNameListener* listener); - def removeListener(self, listener): - len_ = len(self._listeners) - for i in range(len_): - idx = (len_ - 1) - i - if self._listeners[idx].listener == listener: - if self._listeners[idx].autoclean: - self._listeners[idx].listener = None - del self._listeners[idx] - return - return - - - ## - # @if jp - # - # @brief ꥹʡΤ - # - # ϿƤꥹʤΥХå᥽åɤƤӽФ - # - # @param info ConnectorInfo - # @else - # - # @brief Notify listeners. - # - # This calls the Callback method of the registered listener. - # - # @param info ConnectorInfo - # @endif - # void notify(const char* config_set_name); - def notify(self, config_set_name): - for listener in self._listeners: - listener.listener(config_set_name) - return - - - -#------------------------------------------------------------ + """ + """ + + ## + # @if jp + # @brief コンストラクタ + # @else + # @brief Constructor + # @endif + # ConfigurationSetNameListenerHolder(); + def __init__(self): + self._listeners = [] + pass + + ## + # @if jp + # @brief デストラクタ + # @else + # @brief Destructor + # @endif + + def __del__(self): + return + + ## + # @if jp + # + # @brief リスナーの追加 + # + # リスナーを追加する。 + # + # @param listener 追加するリスナ + # @else + # + # @brief Add the listener. + # + # This method adds the listener. + # + # @param listener Added listener + # @endif + # void addListener(ConfigurationSetNameListener* listener); + + def addListener(self, listener): + self._listeners.append(listener) + return + + ## + # @if jp + # + # @brief リスナーの削除 + # + # リスナを削除する。 + # + # @param listener 削除するリスナ + # @else + # + # @brief Remove the listener. + # + # This method removes the listener. + # + # @param listener Removed listener + # @endif + # void removeListener(ConfigurationSetNameListener* listener); + + def removeListener(self, listener): + len_ = len(self._listeners) + for i in range(len_): + idx = (len_ - 1) - i + if self._listeners[idx] == listener: + del self._listeners[idx] + return + return + + ## + # @if jp + # + # @brief リスナーへ通知する + # + # 登録されているリスナのコールバックメソッドを呼び出す。 + # + # @param info ConnectorInfo + # @else + # + # @brief Notify listeners. + # + # This calls the Callback method of the registered listener. + # + # @param info ConnectorInfo + # @endif + # void notify(const char* config_set_name); + + def notify(self, config_set_name): + for listener in self._listeners: + listener(config_set_name) + return + + +# ------------------------------------------------------------ ## # @if jp # @class ConfigurationActionListeners -# @brief ConfigurationActionListeners 饹 +# @brief ConfigurationActionListeners クラス # # # @else @@ -796,42 +730,271 @@ def notify(self, config_set_name): # # @endif class ConfigurationListeners: - """ - """ + """ + """ + ## + # @if jp + # @brief コンストラクタ + # + # + # @param self + # + # @else + # + # @param self + # + # @endif + def __init__(self): + ## + # @if jp + # @brief ConfigurationParamListenerTypeリスナ配列 + # ConfigurationParamTypeリスナを格納 + # @else + # @brief ConfigurationParamListenerType listener array + # The ConfigurationParamListenerType listener is stored. + # @endif + self.configparam_num = ConfigurationParamListenerType.CONFIG_PARAM_LISTENER_NUM + self.configparam_ = [ConfigurationParamListenerHolder() + for i in range(self.configparam_num)] + + ## + # @if jp + # @brief ConfigurationSetListenerTypeリスナ配列 + # ConfigurationSetListenerTypeリスナを格納 + # @else + # @brief ConfigurationSetListenerType listener array + # The ConfigurationSetListenerType listener is stored. + # @endif + self.configset_num = ConfigurationSetListenerType.CONFIG_SET_LISTENER_NUM + self.configset_ = [ConfigurationSetListenerHolder() + for i in range(self.configset_num)] + + ## + # @if jp + # @brief ConfigurationSetNameListenerTypeリスナ配列 + # ConfigurationSetNameListenerTypeリスナを格納 + # @else + # @brief ConfigurationSetNameListenerType listener array + # The ConfigurationSetNameListenerType listener is stored. + # @endif + self.configsetname_num = ConfigurationSetNameListenerType.CONFIG_SET_NAME_LISTENER_NUM + self.configsetname_ = [ConfigurationSetNameListenerHolder() + for i in range(self.configsetname_num)] + + ## + # @if jp + # @brief リスナーの追加 + # + # 指定の種類のConfigurationParamListenerを追加する。 + # + # @param self + # @param ltype リスナの種類 + # @param listener 追加するリスナ + # @return False:指定の種類のリスナが存在しない + # + # @else + # + # @param self + # @param ltype + # @param listener + # @return + # + # @endif + def addConfigParamListener(self, ltype, listener): + if ltype < len(self.configparam_): + self.configparam_[ltype].addListener(listener) + return True + return False + + ## + # @if jp + # @brief リスナーの追加 + # + # 指定の種類のConfigurationSetListenerを追加する。 + # + # @param self + # @param ltype リスナの種類 + # @param listener 追加するリスナ + # @return False:指定の種類のリスナが存在しない + # + # @else + # + # @param self + # @param ltype + # @param listener + # @return + # + # @endif + def addConfigurationSetListener(self, ltype, listener): + if ltype < len(self.configset_): + self.configset_[ltype].addListener(listener) + return True + return False + + ## + # @if jp + # @brief リスナーの追加 + # + # 指定の種類のConfigurationSetNameListenerを追加する。 + # + # @param self + # @param ltype リスナの種類 + # @param listener 追加するリスナ + # @return False:指定の種類のリスナが存在しない + # + # @else + # + # @param self + # @param ltype + # @param listener + # @return + # + # @endif + def addConfigurationSetNameListener(self, ltype, listener): + if ltype < len(self.configsetname_): + self.configsetname_[ltype].addListener(listener) + return True + return False + + ## + # @if jp + # @brief リスナーの削除 + # + # 指定の種類のConfigParamListenerを削除する。 + # + # @param self + # @param ltype リスナの種類 + # @param listener 削除するリスナ + # @return False:指定の種類のリスナが存在しない + # + # @else + # + # @param self + # @param ltype + # @param listener + # @return + # + # @endif + def removeConfigParamListener(self, ltype, listener): + if ltype < len(self.configparam_): + self.configparam_[ltype].removeListener(listener) + return True + return False + + ## + # @if jp + # @brief リスナーの削除 + # + # 指定の種類のConfigurationSetListenerを削除する。 + # + # @param self + # @param ltype リスナの種類 + # @param listener 削除するリスナ + # @return False:指定の種類のリスナが存在しない + # + # @else + # + # @param self + # @param ltype + # @param listener + # @return + # + # @endif + def removeConfigurationSetListener(self, ltype, listener): + if ltype < len(self.configset_): + self.configset_[ltype].removeListener(listener) + return True + return False + + ## + # @if jp + # @brief リスナーの削除 + # + # 指定の種類のConfigurationSetNameListenerを削除する。 + # + # @param self + # @param ltype リスナの種類 + # @param listener 削除するリスナ + # @return False:指定の種類のリスナが存在しない + # + # @else + # + # @param self + # @param ltype + # @param listener + # @return + # + # @endif + def removeConfigurationSetNameListener(self, ltype, listener): + if ltype < len(self.configsetname_): + self.configsetname_[ltype].removeListener(listener) + return True + return False - def __init__(self): ## # @if jp - # @brief ConfigurationParamListenerTypeꥹ - # ConfigurationParamTypeꥹʤǼ + # @brief リスナーへ通知する + # + # 指定の種類のConfigurationParamListenerのコールバック関数を呼び出す。 + # + # @param self + # @param ltype リスナの種類 + # @param config_set_name コンフィギュレーションセット名 + # @param config_param_name コンフィギュレーションパラメータ名 + # # @else - # @brief ConfigurationParamListenerType listener array - # The ConfigurationParamListenerType listener is stored. + # + # @param self + # @param ltype + # @param config_set_name + # @param config_param_name + # @return + # # @endif - self.configparam_num = ConfigurationParamListenerType.CONFIG_PARAM_LISTENER_NUM - self.configparam_ = [ConfigurationParamListenerHolder() - for i in range(self.configparam_num)] + def notifyConfigParam(self, ltype, config_set_name, config_param_name): + if ltype < len(self.configparam_): + self.configparam_[ltype].notify(config_set_name, config_param_name) ## # @if jp - # @brief ConfigurationSetListenerTypeꥹ - # ConfigurationSetListenerTypeꥹʤǼ + # @brief リスナーへ通知する + # + # 指定の種類のConfigurationSetListenerのコールバック関数を呼び出す。 + # + # @param self + # @param ltype リスナの種類 + # @param config_set コンフィギュレーションセット + # # @else - # @brief ConfigurationSetListenerType listener array - # The ConfigurationSetListenerType listener is stored. + # + # @param self + # @param ltype + # @param config_set + # @return + # # @endif - self.configset_num = ConfigurationSetListenerType.CONFIG_SET_LISTENER_NUM - self.configset_ = [ConfigurationSetListenerHolder() - for i in range(self.configset_num)] + def notifyConfigurationSet(self, ltype, config_set): + if ltype < len(self.configset_): + self.configset_[ltype].notify(config_set) ## # @if jp - # @brief ConfigurationSetNameListenerTypeꥹ - # ConfigurationSetNameListenerTypeꥹʤǼ + # @brief リスナーへ通知する + # + # 指定の種類のConfigurationSetNameListenerのコールバック関数を呼び出す。 + # + # @param self + # @param ltype リスナの種類 + # @param config_set_name コンフィギュレーションセット名 + # # @else - # @brief ConfigurationSetNameListenerType listener array - # The ConfigurationSetNameListenerType listener is stored. + # + # @param self + # @param ltype + # @param config_set_name + # @return + # # @endif - self.configsetname_num = ConfigurationSetNameListenerType.CONFIG_SET_NAME_LISTENER_NUM - self.configsetname_ = [ConfigurationSetNameListenerHolder() - for i in range(self.configsetname_num)] + def notifyConfigurationSetName(self, ltype, config_set_name): + if ltype < len(self.configsetname_): + self.configsetname_[ltype].notify(config_set_name) diff --git a/OpenRTM_aist/ConnectorBase.py b/OpenRTM_aist/ConnectorBase.py index 045fdcb2..c48c85e7 100644 --- a/OpenRTM_aist/ConnectorBase.py +++ b/OpenRTM_aist/ConnectorBase.py @@ -1,5 +1,5 @@ #!/usr/bin/env python -# -*- coding: euc-jp -*- +# -*- coding: utf-8 -*- ## # @file ConnectorBase.py @@ -20,8 +20,8 @@ ## # @if jp -# @class ConnectorInfo 饹 -# @brief ConnectorInfo 饹 +# @class ConnectorInfo クラス +# @brief ConnectorInfo クラス # # @class ConnectorInfo class # @brief ConnectorInfo class @@ -29,47 +29,48 @@ # @endif # class ConnectorInfo: - """ - """ - ## - # @if jp - # - # @brief 󥹥ȥ饯 - # - # 󥹥ȥ饯 - # - # @param name_ ³̾ - # @param id_ ³ID - # @param ports_ ³ݡIOR - # @param properties_ ץѥƥ - # - # @else - # - # @brief Constructor - # - # Constructor - # - # @param name_ connection name - # @param id_ connection ID - # @param ports_ connection Ports - # @param properties_ connection properties - # - # @endif - # ConnectorInfo(const char* name_, const char* id_, - # coil::vstring ports_, coil::Properties properties_) - def __init__(self, name_, id_, ports_, properties_): - self.name = name_ # str - self.id = id_ # str - self.ports = ports_ # [str,...] - self.properties = properties_ # OpenRTM_aist.Properties + """ + """ + ## + # @if jp + # + # @brief コンストラクタ + # + # コンストラクタ + # + # @param name_ 接続名前 + # @param id_ 接続ID + # @param ports_ 接続ポートIOR + # @param properties_ プロパティ + # + # @else + # + # @brief Constructor + # + # Constructor + # + # @param name_ connection name + # @param id_ connection ID + # @param ports_ connection Ports + # @param properties_ connection properties + # + # @endif + # ConnectorInfo(const char* name_, const char* id_, + # coil::vstring ports_, coil::Properties properties_) + + def __init__(self, name_, id_, ports_, properties_): + self.name = name_ # str + self.id = id_ # str + self.ports = ports_ # [str,...] + self.properties = properties_ # OpenRTM_aist.Properties #! # @if jp # @class ConnectorBase -# @brief Connector 쥯饹 +# @brief Connector 基底クラス # -# InPort/OutPort, Push/Pull Ƽ Connector 뤿 -# 쥯饹 +# InPort/OutPort, Push/Pull 各種 Connector を派生させるための +# 基底クラス。 # # @since 1.0.0 # @@ -83,154 +84,156 @@ def __init__(self, name_, id_, ports_, properties_): # @since 1.0.0 # # @endif + + class ConnectorBase(OpenRTM_aist.DataPortStatus): - """ - """ - - ## - # @if jp - # @class Profile - # @brief Connector profile 빽¤ - # - # ConnectorBase Ӥ饹ǰ ConnectorProfile ¤Ρ - # - # @since 1.0.0 - # - # @else - # @class Profile - # @brief local representation of Connector profile - # - # ConnectorProfile struct for ConnectorBase and its subclasses. - # - # @since 1.0.0 - # - # @endif - - ## - # @if jp - # @brief ǥȥ饯 - # @else - # @brief Destructor - # @endif - def __del__(self): - pass - - - ## - # @if jp - # @brief Profile - # - # Connector Profile - # - # @else - # @brief Getting Profile - # - # This operation returns Connector Profile - # - # @endif - # virtual const ConnectorInfo& profile() = 0; - def profile(self): - pass - - ## - # @if jp - # @brief Connector ID - # - # Connector ID - # - # @else - # @brief Getting Connector ID - # - # This operation returns Connector ID - # - # @endif - # virtual const char* id() = 0; - def id(self): - pass - - - ## - # @if jp - # @brief Connector ̾ - # - # Connector ̾ - # - # @else - # @brief Getting Connector name - # - # This operation returns Connector name - # - # @endif - # virtual const char* name() = 0; - def name(self): - pass - - - ## - # @if jp - # @brief ³ؿ - # - # Connector ݻƤ³ - # - # @else - # @brief Disconnect connection - # - # This operation disconnect this connection - # - # @endif - # virtual ReturnCode disconnect() = 0; - def disconnect(self): - pass - - - ## - # @if jp - # @brief Buffer - # - # Connector ݻƤ Buffer ֤ - # - # @else - # @brief Getting Buffer - # - # This operation returns this connector's buffer - # - # @endif - # virtual CdrBufferBase* getBuffer() = 0; - def getBuffer(self): - pass - - - ## - # @if jp - # @brief ƥֲ - # - # Υͥ򥢥ƥֲ - # - # @else - # - # @brief Connector activation - # - # This operation activates this connector - # - # @endif - # virtual void activate() = 0; - def activate(self): - pass - - - ## - # @if jp - # @brief 󥢥ƥֲ - # - # Υͥ󥢥ƥֲ - # - # @else - # - # @brief Connector deactivation - # - # This operation deactivates this connector - # - # @endif - # virtual void deactivate() = 0; - def deactivate(self): - pass + """ + """ + + ## + # @if jp + # @class Profile + # @brief Connector profile ローカル構造体 + # + # ConnectorBase およびその派生クラスで扱う ConnectorProfile 構造体。 + # + # @since 1.0.0 + # + # @else + # @class Profile + # @brief local representation of Connector profile + # + # ConnectorProfile struct for ConnectorBase and its subclasses. + # + # @since 1.0.0 + # + # @endif + + ## + # @if jp + # @brief デストラクタ + # @else + # @brief Destructor + # @endif + def __del__(self): + pass + + ## + # @if jp + # @brief Profile 取得 + # + # Connector Profile を取得する + # + # @else + # @brief Getting Profile + # + # This operation returns Connector Profile + # + # @endif + # virtual const ConnectorInfo& profile() = 0; + + def profile(self): + pass + + ## + # @if jp + # @brief Connector ID 取得 + # + # Connector ID を取得する + # + # @else + # @brief Getting Connector ID + # + # This operation returns Connector ID + # + # @endif + # virtual const char* id() = 0; + def id(self): + pass + + ## + # @if jp + # @brief Connector 名取得 + # + # Connector 名を取得する + # + # @else + # @brief Getting Connector name + # + # This operation returns Connector name + # + # @endif + # virtual const char* name() = 0; + + def name(self): + pass + + ## + # @if jp + # @brief 接続解除関数 + # + # Connector が保持している接続を解除する + # + # @else + # @brief Disconnect connection + # + # This operation disconnect this connection + # + # @endif + # virtual ReturnCode disconnect() = 0; + + def disconnect(self): + pass + + ## + # @if jp + # @brief Buffer を取得する + # + # Connector が保持している Buffer を返す + # + # @else + # @brief Getting Buffer + # + # This operation returns this connector's buffer + # + # @endif + # virtual CdrBufferBase* getBuffer() = 0; + + def getBuffer(self): + pass + + ## + # @if jp + # @brief アクティブ化 + # + # このコネクタをアクティブ化する + # + # @else + # + # @brief Connector activation + # + # This operation activates this connector + # + # @endif + # virtual void activate() = 0; + + def activate(self): + pass + + ## + # @if jp + # @brief 非アクティブ化 + # + # このコネクタを非アクティブ化する + # + # @else + # + # @brief Connector deactivation + # + # This operation deactivates this connector + # + # @endif + # virtual void deactivate() = 0; + + def deactivate(self): + pass diff --git a/OpenRTM_aist/ConnectorListener.py b/OpenRTM_aist/ConnectorListener.py index c0ed75f4..9d783785 100644 --- a/OpenRTM_aist/ConnectorListener.py +++ b/OpenRTM_aist/ConnectorListener.py @@ -1,5 +1,5 @@ #!/usr/bin/env python -# -*- coding: euc-jp -*- +# -*- coding: utf-8 -*- ## # @file ConnectorListener.py @@ -15,8 +15,6 @@ # Advanced Industrial Science and Technology (AIST), Japan # All rights reserved. -from omniORB import cdrUnmarshal -from omniORB import any import OpenRTM_aist import OpenRTM_aist.Guard @@ -26,16 +24,16 @@ ## # @if jp # @class ConnectorListenerStatus mixin class -# @brief ConnectorListenerStatus mixin 饹 +# @brief ConnectorListenerStatus mixin クラス # -# Υ饹ϡenum줿꥿󥳡ɤConnectorListener -# ϢΥ֥饹ǶѤ뤿 mixin 饹Ǥ롣Υ꥿ -# 󥳡ɤѤ륯饹ǤϡConnectorListenerStatus 饹 -# public Ѿdefine Ƥ CONNLISTENER_STATUS_ENUM 򥯥 -# ˵Ҥ뤳ȤѲǽȤʤ롣ˤꡢenum -# ReturnCode Ȥ typedef ʸ ReturnCode ѤǤ褦 -# ȤȤˡ֤̾ enum 줿Ƽ̻Ҥ饹̾ -# Ƴ롣 +# このクラスは、enum定義されたリターンコードを、ConnectorListener関 +# 連のサブクラスで共通利用するための mixin クラスである。このリター +# ンコードを使用するクラスでは、ConnectorListenerStatus クラスを +# public 継承し、下にdefine してある CONNLISTENER_STATUS_ENUM をクラ +# ス内に記述することで利用可能となる。これにより、enum を +# ReturnCode 型として typedef し、以後 ReturnCode を利用できるように +# するとともに、名前空間に enum 定義された各識別子を当該クラス名前空 +# 間内に導入する。 # # @else # @class DataPortStatus mixin class @@ -52,30 +50,34 @@ # @endif # class ConnectorListenerStatus: - NO_CHANGE = 0 - INFO_CHANGED = 1 << 0 - DATA_CHANGED = 1 << 1 - BOTH_CHANGED = INFO_CHANGED | DATA_CHANGED + NO_CHANGE = 0 + INFO_CHANGED = 1 << 0 + DATA_CHANGED = 1 << 1 + BOTH_CHANGED = INFO_CHANGED | DATA_CHANGED +class PortType: + OutPortType = 0 + InPortType = 1 + ## # @if jp -# @brief ConnectorDataListener Υ -# -# - ON_BUFFER_WRITE: Хåե񤭹߻ -# - ON_BUFFER_FULL: Хåեե -# - ON_BUFFER_WRITE_TIMEOUT: Хåե񤭹ߥॢȻ -# - ON_BUFFER_OVERWRITE: Хåե񤭻 -# - ON_BUFFER_READ: Хåեɤ߽Ф -# - ON_SEND: InProtؤ -# - ON_RECEIVED: InProtؤλ -# - ON_RECEIVER_FULL: InProt¦Хåեե -# - ON_RECEIVER_TIMEOUT: InProt¦ХåեॢȻ -# - ON_RECEIVER_ERROR: InProt¦顼 +# @brief ConnectorDataListener のタイプ +# +# - ON_BUFFER_WRITE: バッファ書き込み時 +# - ON_BUFFER_FULL: バッファフル時 +# - ON_BUFFER_WRITE_TIMEOUT: バッファ書き込みタイムアウト時 +# - ON_BUFFER_OVERWRITE: バッファ上書き時 +# - ON_BUFFER_READ: バッファ読み出し時 +# - ON_SEND: InProtへの送信時 +# - ON_RECEIVED: InProtへの送信完了時 +# - ON_RECEIVER_FULL: InProt側バッファフル時 +# - ON_RECEIVER_TIMEOUT: InProt側バッファタイムアウト時 +# - ON_RECEIVER_ERROR: InProt側エラー時 # # @else # @brief The types of ConnectorDataListener -# +# # - ON_BUFFER_WRITE: At the time of buffer write # - ON_BUFFER_FULL: At the time of buffer full # - ON_BUFFER_WRITE_TIMEOUT: At the time of buffer write timeout @@ -89,51 +91,52 @@ class ConnectorListenerStatus: # # @endif # -class ConnectorDataListenerType: - def __init__(self): - pass - ON_BUFFER_WRITE = 0 - ON_BUFFER_FULL = 1 - ON_BUFFER_WRITE_TIMEOUT = 2 - ON_BUFFER_OVERWRITE = 3 - ON_BUFFER_READ = 4 - ON_SEND = 5 - ON_RECEIVED = 6 - ON_RECEIVER_FULL = 7 - ON_RECEIVER_TIMEOUT = 8 - ON_RECEIVER_ERROR = 9 - CONNECTOR_DATA_LISTENER_NUM = 10 +class ConnectorDataListenerType: + def __init__(self): + pass + + ON_BUFFER_WRITE = 0 + ON_BUFFER_FULL = 1 + ON_BUFFER_WRITE_TIMEOUT = 2 + ON_BUFFER_OVERWRITE = 3 + ON_BUFFER_READ = 4 + ON_SEND = 5 + ON_RECEIVED = 6 + ON_RECEIVER_FULL = 7 + ON_RECEIVER_TIMEOUT = 8 + ON_RECEIVER_ERROR = 9 + CONNECTOR_DATA_LISTENER_NUM = 10 ## # @if jp -# @class ConnectorDataListener 饹 -# -# ǡݡȤ Connector ˤȯƼ磻٥ȤФ륳 -# Хå¸ꥹʥ饹δ쥯饹 -# -# åOutPortФƥǡ񤭹ߡInPort¦ǥǡ -# ޤǤδ֤ȯƼ磻٥Ȥեå륳Хå -# ꤹ뤳ȤǤ롣ʤꥹʡ饹2¸ߤХåե -# ΥХåǡλͭʥǡե󥯥ΰ -# ȤƼ ConnectorDataListener Ǥꡢ⤦ϥǡ -# ץƥХåեɤ߹߻ΥॢȤʤɥǡǤʤ -# ʤɤ˥뤵ե󥯥ΰ˲Ȥʤ餤 -# ConnecotorListener 롣 -# -# ǡݡȤˤϡ³˥ǡˡˤĤƥǡե -# ֥ץꤹ뤳ȤǤ롣 -# ConnectorDaataListener/ConnectorListener ϤȤˡ͡ʥ٥ -# Ф륳Хåꤹ뤳ȤǤ뤬ǡե -# ӥ֥ץ󷿤˱ơѲǽʤԲǽ -# ʤΤ䡢ƤӽФ륿ߥ󥰤ۤʤ롣 -# ʲˡ󥿡եCORBA CDRξΥХå򼨤 -# +# @class ConnectorDataListener クラス +# +# データポートの Connector において発生する各種イベントに対するコー +# ルバックを実現するリスナクラスの基底クラス。 +# +# コアロジックがOutPortに対してデータ書き込み、InPort側でデータが取 +# 得されるまでの間で発生する各種イベントをフックするコールバックを設 +# 定することができる。なお、リスナークラスは2種類存在し、バッファフ +# ルや送信時のコールバックで、その時点で有効なデータをファンクタの引 +# 数として受け取る ConnectorDataListener であり、もう一方はデータエ +# ンプティやバッファ読み込み時のタイムアウトなどデータが取得できない +# 場合などにコールされるファンクタの引数に何もとらならい +# ConnecotorListener がある。 +# +# データポートには、接続時にデータの送受信方法についてデータフロー型、 +# サブスクリプション型等を設定することができる。 +# ConnectorDaataListener/ConnectorListener はともに、様々なイベント +# に対するコールバックを設定することができるが、これらデータフロー型 +# およびサブスクリプション型の設定に応じて、利用可能なもの利用不可能 +# なものや、呼び出されるタイミングが異なる。 +# 以下に、インターフェースがCORBA CDR型の場合のコールバック一覧を示す。 +# # OutPort: -# - Push: Subscription Typeˤꤵ˥٥Ȥμबʬ롣 -# - Flush: FlushˤϥХåեʤ ON_BUFFER ϤΥ٥Ȥȯʤ +# - Push型: Subscription Typeによりさらにイベントの種類が分かれる。 +# - Flush: Flush型にはバッファがないため ON_BUFFER 系のイベントは発生しない # - ON_SEND # - ON_RECEIVED # - ON_RECEIVER_FULL @@ -142,7 +145,7 @@ def __init__(self): # - ON_CONNECT # - ON_DISCONNECT # . -# - New +# - New型 # - ON_BUFFER_WRITE # - ON_BUFFER_FULL # - ON_BUFFER_WRITE_TIMEOUT @@ -157,7 +160,7 @@ def __init__(self): # - ON_CONNECT # - ON_DISCONNECT # . -# - Periodic +# - Periodic型 # - ON_BUFFER_WRITE # - ON_BUFFER_FULL # - ON_BUFFER_WRITE_TIMEOUT @@ -174,7 +177,7 @@ def __init__(self): # - ON_DISCONNECT # . # . -# - Pull +# - Pull型 # - ON_BUFFER_READ # - ON_SEND # - ON_BUFFER_EMPTY @@ -184,9 +187,9 @@ def __init__(self): # - ON_SENDER_ERROR # - ON_CONNECT # - ON_DISCONNECT -# +# # InPort: -# - Push: +# - Push型: # - ON_BUFFER_WRITE # - ON_BUFFER_FULL # - ON_BUFFER_WRITE_TIMEOUT @@ -198,7 +201,7 @@ def __init__(self): # - ON_CONNECT # - ON_DISCONNECT # . -# - Pull +# - Pull型 # - ON_CONNECT # - ON_DISCONNECT # @else @@ -210,72 +213,72 @@ def __init__(self): # # @endif # -class ConnectorDataListener: - """ - """ - - def __del__(self): - pass - - # virtual ReturnCode operator()(const ConnectorInfo& info, - # const cdrMemoryStream& data) = 0; - def __call__(self, info, data): - pass - - ## - # @if jp - # - # @brief ConnectorDataListenerType ʸѴ - # - # ConnectorDataListenerType ʸѴ - # - # @param type Ѵо ConnectorDataListenerType - # - # @return ʸѴ - # - # @else - # - # @brief Convert ConnectorDataListenerType into the string. - # - # Convert ConnectorDataListenerType into the string. - # - # @param type The target ConnectorDataListenerType for transformation - # - # @return Trnasformation result of string representation - # - # @endif - # - def toString(type): - typeString = ["ON_BUFFER_WRITE", - "ON_BUFFER_FULL", - "ON_BUFFER_WRITE_TIMEOUT", - "ON_BUFFER_OVERWRITE", - "ON_BUFFER_READ", - "ON_SEND", - "ON_RECEIVED", - "ON_RECEIVER_FULL", - "ON_RECEIVER_TIMEOUT", - "ON_RECEIVER_ERROR", - "CONNECTOR_DATA_LISTENER_NUM"] - - if type < ConnectorDataListenerType.CONNECTOR_DATA_LISTENER_NUM: - return typeString[type] - - return "" - - toString = staticmethod(toString) +# TODO: The "object" class inheritance must be removed in Python3 +class ConnectorDataListener(object): + """ + """ + + def __del__(self): + pass + + # virtual ReturnCode operator()(const ConnectorInfo& info, + # const cdrMemoryStream& data) = 0; + def __call__(self, info, data): + pass + + ## + # @if jp + # + # @brief ConnectorDataListenerType を文字列に変換 + # + # ConnectorDataListenerType を文字列に変換する + # + # @param type 変換対象 ConnectorDataListenerType + # + # @return 文字列変換結果 + # + # @else + # + # @brief Convert ConnectorDataListenerType into the string. + # + # Convert ConnectorDataListenerType into the string. + # + # @param type The target ConnectorDataListenerType for transformation + # + # @return Trnasformation result of string representation + # + # @endif + # + def toString(status): + typeString = ["ON_BUFFER_WRITE", + "ON_BUFFER_FULL", + "ON_BUFFER_WRITE_TIMEOUT", + "ON_BUFFER_OVERWRITE", + "ON_BUFFER_READ", + "ON_SEND", + "ON_RECEIVED", + "ON_RECEIVER_FULL", + "ON_RECEIVER_TIMEOUT", + "ON_RECEIVER_ERROR"] + + if status < len(typeString): + return typeString[status] + + return "" + + toString = staticmethod(toString) ## # @if jp -# @class ConnectorDataListenerT 饹 +# @class ConnectorDataListenerT クラス # -# ǡݡȤ Connector ˤȯƼ磻٥ȤФ륳 -# Хå¸ꥹʥ饹δ쥯饹 -# -# Υ饹ϡoperator()() 2 cdrMemoryStream ǤϤʤ -# ºݤ˥ǡݡȤǻѤѿƥץ졼ȰȤ -# ϤȤǤ롣 +# データポートの Connector において発生する各種イベントに対するコー +# ルバックを実現するリスナクラスの基底クラス。 +# +# このクラスは、operator()() の第2引数に cdrMemoryStream 型ではなく、 +# 実際にデータポートで使用される変数型をテンプレート引数として +# 渡すことができる。 # # @else # @class ConnectorDataListenerT class @@ -291,71 +294,92 @@ def toString(type): # @endif # class ConnectorDataListenerT(ConnectorDataListener): - """ - """ - - def __del__(self): - pass - - - ## - # @if jp - # - # @brief Хå᥽å - # - # ǡǡݡȤǻѤѿѴ ConnectorDataListenerT - # ΥХå᥽åɤƤӽФ - # - # @param info ConnectorInfo - # @param cdrdata cdrMemoryStreamΥǡ - # - # @else - # - # @brief Callback method - # - # This method invokes the callback method of ConnectorDataListenerT. - # Data is converted into the variable type used in DataPort. - # - # @param info ConnectorInfo - # @param cdrdata Data of cdrMemoryStream type - # - # @endif - # - # virtual ReturnCode operator()(const ConnectorInfo& info, - # const cdrMemoryStream& cdrdata) - def __call__(self, info, cdrdata, data): - endian = info.properties.getProperty("serializer.cdr.endian","little") - if endian is not "little" and endian is not None: - endian = OpenRTM_aist.split(endian, ",") # Maybe endian is ["little","big"] - endian = OpenRTM_aist.normalize(endian) # Maybe self._endian is "little" or "big" - - if endian == "little": - endian = True - elif endian == "big": - endian = False - else: - endian = True - - _data = cdrUnmarshal(any.to_any(data).typecode(), cdrdata, endian) - return _data + """ + """ + + def __del__(self): + pass + ## + # @if jp + # + # @brief コールバックメソッド + # + # データをデータポートで使用される変数型に変換して ConnectorDataListenerT + # のコールバックメソッドを呼び出す。 + # + # @param info ConnectorInfo + # @param cdrdata cdrMemoryStream型のデータ + # @param data 元のデータ型 + # @param porttype ポートの種類 + # + # @else + # + # @brief Callback method + # + # This method invokes the callback method of ConnectorDataListenerT. + # Data is converted into the variable type used in DataPort. + # + # @param info ConnectorInfo + # @param cdrdata Data of cdrMemoryStream type + # @param data + # @param porttype + # + # @endif + # + # virtual ReturnCode operator()(const ConnectorInfo& info, + # const cdrMemoryStream& cdrdata) + + def __call__(self, info, cdrdata, data, porttype=PortType.OutPortType): + endian = info.properties.getProperty("serializer.cdr.endian", "little") + if endian != "little" and endian is not None: + # Maybe endian is ["little","big"] + endian = OpenRTM_aist.split(endian, ",") + # Maybe self._endian is "little" or "big" + endian = OpenRTM_aist.normalize(endian[0]) + + if endian == "little": + endian = True + elif endian == "big": + endian = False + else: + endian = True + + marshaling_type = info.properties.getProperty( + "marshaling_type", "cdr") + if porttype == PortType.OutPortType: + marshaling_type = info.properties.getProperty( + "outport.marshaling_type", marshaling_type) + elif porttype == PortType.InPortType: + marshaling_type = info.properties.getProperty( + "inport.marshaling_type", marshaling_type) + marshaling_type = marshaling_type.strip() + + serializer = OpenRTM_aist.SerializerFactories.instance( + ).createSerializer(marshaling_type, data) + if serializer is not None: + serializer.isLittleEndian(endian) + ret, data = serializer.deserialize(cdrdata, data) + + return data + return data ## # @if jp -# @brief ConnectorListener Υ -# -# - ON_BUFFER_EMPTY: Хåեξ -# - ON_BUFFER_READTIMEOUT: ХåեǥॢȤ -# - ON_SENDER_EMPTY: OutPort¦Хåե -# - ON_SENDER_TIMEOUT: OutPort¦ॢȻ -# - ON_SENDER_ERROR: OutPort¦顼 -# - ON_CONNECT: ³Ω -# - ON_DISCONNECT: ³ǻ +# @brief ConnectorListener のタイプ +# +# - ON_BUFFER_EMPTY: バッファが空の場合 +# - ON_BUFFER_READTIMEOUT: バッファが空でタイムアウトした場合 +# - ON_SENDER_EMPTY: OutPort側バッファが空 +# - ON_SENDER_TIMEOUT: OutPort側タイムアウト時 +# - ON_SENDER_ERROR: OutPort側エラー時 +# - ON_CONNECT: 接続確立時 +# - ON_DISCONNECT: 接続切断時 # # @else # @brief The types of ConnectorListener -# +# # - ON_BUFFER_EMPTY: At the time of buffer empty # - ON_BUFFER_READTIMEOUT: At the time of buffer read timeout # - ON_BUFFER_EMPTY: At the time of empty of OutPort @@ -369,41 +393,40 @@ def __call__(self, info, cdrdata, data): # enum ConnectorListenerType class ConnectorListenerType: - def __init__(self): - pass - - ON_BUFFER_EMPTY = 0 - ON_BUFFER_READ_TIMEOUT = 1 - ON_SENDER_EMPTY = 2 - ON_SENDER_TIMEOUT = 3 - ON_SENDER_ERROR = 4 - ON_CONNECT = 5 - ON_DISCONNECT = 6 - CONNECTOR_LISTENER_NUM = 7 + def __init__(self): + pass + ON_BUFFER_EMPTY = 0 + ON_BUFFER_READ_TIMEOUT = 1 + ON_SENDER_EMPTY = 2 + ON_SENDER_TIMEOUT = 3 + ON_SENDER_ERROR = 4 + ON_CONNECT = 5 + ON_DISCONNECT = 6 + CONNECTOR_LISTENER_NUM = 7 ## # @if jp -# @class ConnectorListener 饹 -# @brief ConnectorListener 饹 -# -# ǡݡȤ Connector ˤȯƼ磻٥ȤФ륳 -# Хå¸ꥹʥ饹δ쥯饹 -# -# åOutPortФƥǡ񤭹ߡInPort¦ǥǡ -# ޤǤδ֤ȯƼ磻٥Ȥեå륳Хå -# ꤹ뤳ȤǤ롣ʤꥹʡ饹2¸ߤХåե -# ΥХåǡλͭʥǡե󥯥ΰ -# ȤƼ ConnectorDataListener Ǥꡢ⤦ϥǡ -# ץƥХåեɤ߹߻ΥॢȤʤɥǡǤʤ -# ʤɤ˥뤵ե󥯥ΰ˲Ȥʤ餤 -# ConnecotorListener 롣 -# -# ConnectorListener 饹ˤäƴϢưեå硢 -# Τ褦ˡΥ饹Ѿͥξ˼ʲ -# Τ褦ʥХå֥ȤǡݡȤŬڤʥ -# Хåؿ饳Хå֥Ȥ򥻥åȤɬפ롣 +# @class ConnectorListener クラス +# @brief ConnectorListener クラス +# +# データポートの Connector において発生する各種イベントに対するコー +# ルバックを実現するリスナクラスの基底クラス。 +# +# コアロジックがOutPortに対してデータ書き込み、InPort側でデータが取 +# 得されるまでの間で発生する各種イベントをフックするコールバックを設 +# 定することができる。なお、リスナークラスは2種類存在し、バッファフ +# ルや送信時のコールバックで、その時点で有効なデータをファンクタの引 +# 数として受け取る ConnectorDataListener であり、もう一方はデータエ +# ンプティやバッファ読み込み時のタイムアウトなどデータが取得できない +# 場合などにコールされるファンクタの引数に何もとらならい +# ConnecotorListener がある。 +# +# ConnectorListener クラスによって関連する動作をフックしたい場合、以 +# 下の例のように、このクラスを継承し、コネクタの情報を引数に取る以下 +# のようなコールバックオブジェクトを定義し、データポートの適切なコー +# ルバック設定関数からコールバックオブジェクトをセットする必要がある。 # #
 # class MyListener
@@ -424,8 +447,8 @@ def __init__(self):
 # };
 # 
# -# Τ褦ˤ줿ꥹʥ饹ϡʲΤ褦˥ǡݡȤ -# ФơʲΤ褦˥åȤ롣 +# このようにして定義されたリスナクラスは、以下のようにデータポートに +# 対して、以下のようにセットされる。 # #
 # RTC::ReturnCode_t ConsoleIn::onInitialize()
@@ -436,24 +459,24 @@ def __init__(self):
 #    :
 # 
# -# 1 "ON_BUFFER_EMPTY" ϡХåեåݥȤ -# ꡢʲ󤹤ͤ뤳ȤǽǤ롣ǡݡȤˤϡ -# ³˥ǡˡˤĤơ󥿡եǡե -# ֥ץꤹ뤳ȤǤ뤬 -# եåݥȤϰۤʤ롣ʲˡ󥿡եCORBA -# CDRξΥХå򼨤 +# 第1引数の "ON_BUFFER_EMPTY" は、コールバックをフックするポイントで +# あり、以下に列挙する値を取ることが可能である。データポートには、接 +# 続時にデータの送受信方法について、インターフェース型、データフロー +# 型、サブスクリプション型等を設定することができるが、これらの設定に +# よりフックされるポイントは異なる。以下に、インターフェースがCORBA +# CDR型の場合のコールバック一覧を示す。 # # OutPort: -# - Push: Subscription Typeˤꤵ˥٥Ȥμबʬ롣 -# - Flush: FlushˤϥХåեʤ ON_BUFFER ϤΥ٥Ȥȯʤ +# - Push型: Subscription Typeによりさらにイベントの種類が分かれる。 +# - Flush: Flush型にはバッファがないため ON_BUFFER 系のイベントは発生しない # - ON_CONNECT # - ON_DISCONNECT # . -# - New +# - New型 # - ON_CONNECT # - ON_DISCONNECT # . -# - Periodic +# - Periodic型 # - ON_BUFFER_EMPTY # - ON_BUFFER_READ_TIMEOUT # - ON_SENDER_EMPTY @@ -462,7 +485,7 @@ def __init__(self): # - ON_DISCONNECT # . # . -# - Pull +# - Pull型 # - ON_BUFFER_EMPTY # - ON_BUFFER_READ_TIMEOUT # - ON_SENDER_EMPTY @@ -472,13 +495,13 @@ def __init__(self): # - ON_DISCONNECT # . # InPort: -# - Push: +# - Push型: # - ON_BUFFER_EMPTY # - ON_BUFFER_READ_TIMEOUT # - ON_CONNECT # - ON_DISCONNECT # . -# - Pull +# - Pull型 # - ON_CONNECT # - ON_DISCONNECT # @@ -585,62 +608,61 @@ def __init__(self): # @endif # class ConnectorListener: - """ - """ - - def __del__(self): - pass - - # virtual void operator()(const ConnectorInfo& info) = 0; - def __call__(self, info): - pass - - ## - # @if jp - # - # @brief ConnectorListenerType ʸѴ - # - # ConnectorListenerType ʸѴ - # - # @param type Ѵо ConnectorListenerType - # - # @return ʸѴ - # - # @else - # - # @brief Convert ConnectorListenerType into the string. - # - # Convert ConnectorListenerType into the string. - # - # @param type The target ConnectorListenerType for transformation - # - # @return Trnasformation result of string representation - # - # @endif - # - def toString(type): - typeString = ["ON_BUFFER_EMPTY", - "ON_BUFFER_READ_TIMEOUT", - "ON_SENDER_EMPTY", - "ON_SENDER_TIMEOUT", - "ON_SENDER_ERROR", - "ON_CONNECT", - "ON_DISCONNECT", - "CONNECTOR_LISTENER_NUM"] - - if type < ConnectorListenerType.CONNECTOR_LISTENER_NUM: - return typeString[type] - - return "" - - toString = staticmethod(toString) + """ + """ + + def __del__(self): + pass + + # virtual void operator()(const ConnectorInfo& info) = 0; + def __call__(self, info): + pass + + ## + # @if jp + # + # @brief ConnectorListenerType を文字列に変換 + # + # ConnectorListenerType を文字列に変換する + # + # @param type 変換対象 ConnectorListenerType + # + # @return 文字列変換結果 + # + # @else + # + # @brief Convert ConnectorListenerType into the string. + # + # Convert ConnectorListenerType into the string. + # + # @param type The target ConnectorListenerType for transformation + # + # @return Trnasformation result of string representation + # + # @endif + # + def toString(status): + typeString = ["ON_BUFFER_EMPTY", + "ON_BUFFER_READ_TIMEOUT", + "ON_SENDER_EMPTY", + "ON_SENDER_TIMEOUT", + "ON_SENDER_ERROR", + "ON_CONNECT", + "ON_DISCONNECT"] + + if status < len(typeString): + return typeString[status] + + return "" + + toString = staticmethod(toString) ## # @if jp -# @class ConnectorDataListener ۥ饹 +# @class ConnectorDataListener ホルダクラス # -# ʣ ConnectorDataListener ݻ륯饹 +# 複数の ConnectorDataListener を保持し管理するクラス。 # # @else # @class ConnectorDataListener holder class @@ -650,133 +672,190 @@ def toString(type): # @endif # class ConnectorDataListenerHolder: - """ - """ - - ## - # @if jp - # @brief 󥹥ȥ饯 - # @else - # @brief Constructor - # @endif - # - def __init__(self): - self._listeners = [] - self._mutex = threading.RLock() - return - - - ## - # @if jp - # @brief ǥȥ饯 - # @else - # @brief Destructor - # @endif - # - def __del__(self): - #guard = OpenRTM_aist.Guard.ScopedLock(self._mutex) - #for listener in self._listeners: - # for (k,v) in listener.items(): - # if v: - # del k - return - - - ## - # @if jp - # - # @brief ꥹʡɲ - # - # ꥹʡɲä롣 - # - # @param self - # @param listener ɲäꥹ - # @param autoclean true:ǥȥ饯Ǻ, - # false:ǥȥ饯Ǻʤ - # @else - # - # @brief Add the listener. - # - # This method adds the listener. - # - # @param self - # @param listener Added listener - # @param autoclean true:The listener is deleted at the destructor., - # false:The listener is not deleted at the destructor. - # @endif - # - # void addListener(ConnectorDataListener* listener, bool autoclean); - def addListener(self, listener, autoclean): - guard = OpenRTM_aist.Guard.ScopedLock(self._mutex) - self._listeners.append({listener:autoclean}) - return - - - ## - # @if jp - # - # @brief ꥹʡκ - # - # ꥹʤ롣 - # - # @param self - # @param listener ꥹ - # @else - # - # @brief Remove the listener. - # - # This method removes the listener. - # - # @param self - # @param listener Removed listener - # @endif - # - # void removeListener(ConnectorDataListener* listener); - def removeListener(self, listener): - guard = OpenRTM_aist.Guard.ScopedLock(self._mutex) - for (i, _listener) in enumerate(self._listeners): - if listener in _listener: - del self._listeners[i][listener] + """ + """ + + ## + # @if jp + # @brief コンストラクタ + # @else + # @brief Constructor + # @endif + # + def __init__(self): + self._listeners = [] + self._mutex = threading.RLock() + self._data = None + self._portType = PortType.OutPortType + return + + ## + # @if jp + # @brief デストラクタ + # @else + # @brief Destructor + # @endif + # + + def __del__(self): + return + + ## + # @if jp + # + # @brief リスナーの追加 + # + # リスナーを追加する。 + # + # @param self + # @param listener 追加するリスナ + # @else + # + # @brief Add the listener. + # + # This method adds the listener. + # + # @param self + # @param listener Added listener + # @endif + # + # void addListener(ConnectorDataListener* listener); + + def addListener(self, listener): + guard = OpenRTM_aist.Guard.ScopedLock(self._mutex) + self._listeners.append(listener) return - - ## - # @if jp - # - # @brief ꥹʡΤ - # - # ϿƤꥹʤΥХå᥽åɤƤӽФ - # - # @param self - # @param info ConnectorInfo - # @param cdrdata ǡ - # @else - # - # @brief Notify listeners. - # - # This calls the Callback method of the registered listener. - # - # @param self - # @param info ConnectorInfo - # @param cdrdata Data - # @endif - # - # ReturnCode notify(const ConnectorInfo& info, - # const cdrMemoryStream& cdrdata); - def notify(self, info, cdrdata): - guard = OpenRTM_aist.Guard.ScopedLock(self._mutex) - ret = ConnectorListenerStatus.NO_CHANGE - for listener in self._listeners: - for (k,v) in listener.items(): - ret = ret | k(info, cdrdata) - return ret + ## + # @if jp + # + # @brief リスナーの削除 + # + # リスナを削除する。 + # + # @param self + # @param listener 削除するリスナ + # @else + # + # @brief Remove the listener. + # + # This method removes the listener. + # + # @param self + # @param listener Removed listener + # @endif + # + # void removeListener(ConnectorDataListener* listener); + + def removeListener(self, listener): + guard = OpenRTM_aist.Guard.ScopedLock(self._mutex) + for (i, _listener) in enumerate(self._listeners): + if self._listeners[i] == listener: + del self._listeners[i] + return + + ## + # @if jp + # + # @brief リスナーへ通知する + # + # 登録されているリスナのコールバックメソッドを呼び出す。 + # + # @param self + # @param info ConnectorInfo + # @param cdrdata データ + # @else + # + # @brief Notify listeners. + # + # This calls the Callback method of the registered listener. + # + # @param self + # @param info ConnectorInfo + # @param cdrdata Data + # @endif + # + # ReturnCode notify(const ConnectorInfo& info, + # const cdrMemoryStream& cdrdata); + + def notify(self, info, cdrdata): + guard = OpenRTM_aist.Guard.ScopedLock(self._mutex) + ret = ConnectorListenerStatus.NO_CHANGE + + endian = info.properties.getProperty( + "serializer.cdr.endian", "little") + if endian is not "little" and endian is not None: + # Maybe endian is ["little","big"] + endian = OpenRTM_aist.split(endian, ",") + # Maybe self._endian is "little" or "big" + endian = OpenRTM_aist.normalize(endian[0]) + + if endian == "little": + endian = True + elif endian == "big": + endian = False + else: + endian = True + marshaling_type = info.properties.getProperty( + "marshaling_type", "cdr") + if self._portType == PortType.OutPortType: + marshaling_type = info.properties.getProperty( + "outport.marshaling_type", marshaling_type) + elif self._portType == PortType.InPortType: + marshaling_type = info.properties.getProperty( + "inport.marshaling_type", marshaling_type) + marshaling_type = marshaling_type.strip() + + serializer = OpenRTM_aist.SerializerFactories.instance( + ).createSerializer(marshaling_type, self._data) + + data = self._data + if serializer is not None: + serializer.isLittleEndian(endian) + if data: + deserialize_ret, _data = serializer.deserialize( + cdrdata, self._data) + if deserialize_ret == OpenRTM_aist.ByteDataStreamBase.SERIALIZE_OK: + data = _data + + for listener in self._listeners: + if issubclass(type(listener), ConnectorDataListenerT): + if data: + if deserialize_ret == OpenRTM_aist.ByteDataStreamBase.SERIALIZE_OK: + listener_ret, _data = listener(info, data) + if listener_ret == ConnectorListenerStatus.DATA_CHANGED or listener_ret == ConnectorListenerStatus.BOTH_CHANGED: + data = _data + serializer.isLittleEndian(endian) + serialize_ret, _cdrdata = serializer.serialize( + data) + if deserialize_ret == OpenRTM_aist.ByteDataStreamBase.SERIALIZE_OK: + cdrdata = _cdrdata + ret = ret | listener_ret + else: + listener_ret, _cdrdata = listener(info, cdrdata) + if listener_ret == ConnectorListenerStatus.DATA_CHANGED or listener_ret == ConnectorListenerStatus.BOTH_CHANGED: + cdrdata = _cdrdata + if serializer is not None: + serializer.isLittleEndian(endian) + deserialize_ret, _data = serializer.deserialize( + cdrdata, data) + if deserialize_ret == OpenRTM_aist.ByteDataStreamBase.SERIALIZE_OK: + data = _data + ret = ret | listener_ret + return ret, cdrdata + + def setDataType(self, dataType): + self._data = dataType + + def setPortType(self, portType): + self._portType = portType ## # @if jp -# @class ConnectorListener ۥ饹 +# @class ConnectorListener ホルダクラス # -# ʣ ConnectorListener ݻ륯饹 +# 複数の ConnectorListener を保持し管理するクラス。 # # @else # @class ConnectorListener holder class @@ -785,131 +864,330 @@ def notify(self, info, cdrdata): # # @endif # + + class ConnectorListenerHolder: - """ - """ - - ## - # @if jp - # @brief 󥹥ȥ饯 - # @else - # @brief Constructor - # @endif - # - def __init__(self): - self._listeners = [] - self._mutex = threading.RLock() - return - - - ## - # @if jp - # @brief ǥȥ饯 - # @else - # @brief Destructor - # @endif - # - def __del__(self): - #guard = OpenRTM_aist.Guard.ScopedLock(self._mutex) - #for listener in self._listeners: - # for (k,v) in listener.items(): - # if v: - # del k - return - - - ## - # @if jp - # - # @brief ꥹʡɲ - # - # ꥹʡɲä롣 - # - # @param self - # @param listener ɲäꥹ - # @param autoclean true:ǥȥ饯Ǻ, - # false:ǥȥ饯Ǻʤ - # @else - # - # @brief Add the listener. - # - # This method adds the listener. - # - # @param self - # @param listener Added listener - # @param autoclean true:The listener is deleted at the destructor., - # false:The listener is not deleted at the destructor. - # @endif - # - # void addListener(ConnectorListener* listener, bool autoclean); - def addListener(self, listener, autoclean): - guard = OpenRTM_aist.Guard.ScopedLock(self._mutex) - self._listeners.append({listener:autoclean}) - return - - - ## - # @if jp - # - # @brief ꥹʡκ - # - # ꥹʤ롣 - # - # @param self - # @param listener ꥹ - # @else - # - # @brief Remove the listener. - # - # This method removes the listener. - # - # @param self - # @param listener Removed listener - # @endif - # - # void removeListener(ConnectorListener* listener); - def removeListener(self, listener): - guard = OpenRTM_aist.Guard.ScopedLock(self._mutex) - for (i, _listener) in enumerate(self._listeners): - if listener in _listener: - del self._listeners[i][listener] + """ + """ + + ## + # @if jp + # @brief コンストラクタ + # @else + # @brief Constructor + # @endif + # + def __init__(self): + self._listeners = [] + self._mutex = threading.RLock() return + ## + # @if jp + # @brief デストラクタ + # @else + # @brief Destructor + # @endif + # + + def __del__(self): + return + + ## + # @if jp + # + # @brief リスナーの追加 + # + # リスナーを追加する。 + # + # @param self + # @param listener 追加するリスナ + # @else + # + # @brief Add the listener. + # + # This method adds the listener. + # + # @param self + # @param listener Added listener + # @endif + # + # void addListener(ConnectorListener* listener); + + def addListener(self, listener): + guard = OpenRTM_aist.Guard.ScopedLock(self._mutex) + self._listeners.append(listener) + return + + ## + # @if jp + # + # @brief リスナーの削除 + # + # リスナを削除する。 + # + # @param self + # @param listener 削除するリスナ + # @else + # + # @brief Remove the listener. + # + # This method removes the listener. + # + # @param self + # @param listener Removed listener + # @endif + # + # void removeListener(ConnectorListener* listener); + + def removeListener(self, listener): + guard = OpenRTM_aist.Guard.ScopedLock(self._mutex) + for (i, _listener) in enumerate(self._listeners): + if self._listeners[i] == listener: + del self._listeners[i] + return + + ## + # @if jp + # + # @brief リスナーへ通知する + # + # 登録されているリスナのコールバックメソッドを呼び出す。 + # + # @param self + # @param info ConnectorInfo + # @return ReturnCode + # @else + # + # @brief Notify listeners. + # + # This calls the Callback method of the registered listener. + # + # @param self + # @param info ConnectorInfo + # @return ReturnCode + # @endif + # + # void notify(const ConnectorInfo& info); + + def notify(self, info): + guard = OpenRTM_aist.Guard.ScopedLock(self._mutex) + ret = ConnectorListenerStatus.NO_CHANGE + for listener in self._listeners: + ret = ret | listener(info) + return ret + - ## - # @if jp - # - # @brief ꥹʡΤ - # - # ϿƤꥹʤΥХå᥽åɤƤӽФ - # - # @param self - # @param info ConnectorInfo - # @return ReturnCode - # @else - # - # @brief Notify listeners. - # - # This calls the Callback method of the registered listener. - # - # @param self - # @param info ConnectorInfo - # @return ReturnCode - # @endif - # - # void notify(const ConnectorInfo& info); - def notify(self, info): - guard = OpenRTM_aist.Guard.ScopedLock(self._mutex) - ret = ConnectorListenerStatus.NO_CHANGE - for listener in self._listeners: - for (k,v) in listener.items(): - ret = ret | k(info) - return ret - - - class ConnectorListeners: - def __init__(self): - self.connectorData_ = [ OpenRTM_aist.ConnectorDataListenerHolder() for i in range(OpenRTM_aist.ConnectorDataListenerType.CONNECTOR_DATA_LISTENER_NUM) ] - self.connector_ = [ OpenRTM_aist.ConnectorListenerHolder() for i in range(OpenRTM_aist.ConnectorListenerType.CONNECTOR_LISTENER_NUM) ] - return + ## + # @if jp + # @brief コンストラクタ + # + # + # @param self + # + # @else + # + # @param self + # + # @endif + def __init__(self): + self.connectorData_ = [OpenRTM_aist.ConnectorDataListenerHolder() for i in range( + OpenRTM_aist.ConnectorDataListenerType.CONNECTOR_DATA_LISTENER_NUM)] + self.connector_ = [OpenRTM_aist.ConnectorListenerHolder() for i in range( + OpenRTM_aist.ConnectorListenerType.CONNECTOR_LISTENER_NUM)] + return + ## + # @if jp + # @brief データ型の設定 + # + # OutPort、InPortで初期化する際にデータ型を指定すると、 + # ConnectorDataListenerTを継承したリスナでコールバック関数に + # 指定データ型にデシリアライズしたデータを入力する。 + # データ型を指定しない場合はコールバック関数で明示的にデシリアライズする必要がある。 + # + # @param self + # @param dataType データ型 + # + # @else + # + # @param self + # @param dataType + # + # @endif + + def setDataType(self, dataType): + for holder in self.connectorData_: + holder.setDataType(dataType) + + ## + # @if jp + # @brief ポート型の指定 + # + # OutPortの場合はPortType.OutPortType、InPortの場合はPortType.InPortTypeを指定する + # + # @param self + # @param porttype ポート型 + # + # @else + # + # @param self + # @param porttype + # + # @endif + def setPortType(self, porttype): + for holder in self.connectorData_: + holder.setPortType(porttype) + + ## + # @if jp + # @brief リスナーの追加 + # + # 指定の種類のConnectorListenerを追加する。 + # + # @param self + # @param ltype リスナの種類 + # @param listener 追加するリスナ + # @return False:指定の種類のリスナが存在しない + # + # @else + # + # @param self + # @param ltype + # @param listener + # @return + # + # @endif + def addListener(self, ltype, listener): + if ltype < len(self.connector_): + self.connector_[ltype].addListener(listener) + return True + return False + + ## + # @if jp + # @brief リスナーの追加 + # + # 指定の種類のConnectorDataListenerを追加する。 + # + # @param self + # @param ltype リスナの種類 + # @param listener 追加するリスナ + # @return False:指定の種類のリスナが存在しない + # + # @else + # + # @param self + # @param ltype + # @param listener + # @return + # + # @endif + def addDataListener(self, ltype, listener): + if ltype < len(self.connectorData_): + self.connectorData_[ltype].addListener(listener) + return True + return False + + ## + # @if jp + # @brief リスナーの削除 + # + # 指定の種類のConnectorListenerを削除する。 + # + # @param self + # @param ltype リスナの種類 + # @param listener 削除するリスナ + # @return False:指定の種類のリスナが存在しない + # + # @else + # + # @param self + # @param ltype + # @param listener + # @return + # + # @endif + def removeListener(self, ltype, listener): + if ltype < len(self.connector_): + self.connector_[ltype].removeListener(listener) + return True + return False + + ## + # @if jp + # @brief リスナーの削除 + # + # 指定の種類のConnectorDataListenerを削除する。 + # + # @param self + # @param ltype リスナの種類 + # @param listener 削除するリスナ + # @return False:指定の種類のリスナが存在しない + # + # @else + # + # @param self + # @param ltype + # @param listener + # @return + # + # @endif + def removeDataListener(self, ltype, listener): + if ltype < len(self.connectorData_): + self.connectorData_[ltype].removeListener(listener) + return True + return False + + ## + # @if jp + # @brief リスナーへ通知する + # + # 指定の種類のConnectorDataListenerのコールバック関数を呼び出す。 + # + # @param self + # @param ltype リスナの種類 + # @param info ConnectorInfo + # @param cdrdata バイト列のデータ + # @return ret, data + # ret:ConnectorListenerStatus + # data:バイト列のデータ。リスナで変更する場合がある。 + # + # @else + # + # @param self + # @param ltype + # @param info + # @param cdrdata + # @return + # + # @endif + def notifyData(self, ltype, info, cdrdata): + if ltype < len(self.connectorData_): + return self.connectorData_[ltype].notify(info, cdrdata) + return ConnectorListenerStatus.NO_CHANGE, None + + ## + # @if jp + # @brief リスナーへ通知する + # + # 指定の種類のConnectorListenerのコールバック関数を呼び出す。 + # + # @param self + # @param ltype リスナの種類 + # @param info ConnectorInfo + # @return ret:ConnectorListenerStatus + # + # + # @else + # + # @param self + # @param ltype + # @param info + # @return + # + # @endif + def notify(self, ltype, info): + if ltype < len(self.connector_): + return self.connector_[ltype].notify(info) + return ConnectorListenerStatus.NO_CHANGE diff --git a/OpenRTM_aist/CorbaConsumer.py b/OpenRTM_aist/CorbaConsumer.py index 2636a1a1..180477f9 100644 --- a/OpenRTM_aist/CorbaConsumer.py +++ b/OpenRTM_aist/CorbaConsumer.py @@ -1,5 +1,5 @@ #!/usr/bin/env python -# -*- coding: euc-jp -*- +# -*- coding: utf-8 -*- ## @@ -8,7 +8,7 @@ # @brief CORBA Consumer class # @date $Date: 2007/09/20 $ # @author Noriaki Ando and Shinji Kurihara -# +# # Copyright (C) 2006-2008 # Noriaki Ando # Task-intelligence Research Group, @@ -25,9 +25,9 @@ # @if jp # @class CorbaConsumerBase # -# @brief ֥ȥե󥹤ݻץ졼ۥ쥯饹 +# @brief オブジェクトリファレンスを保持するプレースホルダ基底クラス # -# ̿ʤȤ CORBA 򤷤Υ󥷥塼޼Τδ쥯饹 +# 通信手段として CORBA を選択した場合のコンシューマ実装のための基底クラス # # @since 0.4.0 # @@ -35,142 +35,141 @@ # @class ConsumerBase # @brief Placeholder base class to hold remote object reference. # @endif -class CorbaConsumerBase: - """ - """ - - - - ## - # @if jp - # - # @brief 󥹥ȥ饯 - # - # @param self - # @param consumer ԡCorbaConsumerBase֥ - # - # @else - # - # @brief Consructor - # - # @param self - # - # @endif - def __init__(self, consumer=None): - if consumer: - self._objref = consumer._objref - else: - self._objref = CORBA.Object._nil - - - ## - # @if jp - # - # @brief 黻 - # - # @param self - # @param consumer - # - # @return - # - # @else - # - # @brief Assignment operator - # - # @param self - # @param consumer Copy source. - # - # @endif - def equal(self, consumer): - self._objref = consumer._objref - return self - - - ## - # @if jp - # - # @brief CORBA֥Ȥ򥻥åȤ - # - # Ϳ줿֥ȥե󥹤ϡConsumerBase ֥ - # CORBA::Object_var Ȥݻ롣 - # - # @param self - # @param obj CORBA ֥ȤΥե - # - # @return obj nil ե󥹤ξ false ֤ - # - # @else - # - # @brief Set CORBA Object - # - # The given CORBA Object is held as CORBA::Object_var type - # - # @param self - # @param obj Object reference of CORBA object - # - # @return If obj is nil reference, it returns false. - # - # @endif - def setObject(self, obj): - if CORBA.is_nil(obj): - return False - - self._objref = obj - return True - - - ## - # @if jp - # - # @brief CORBA֥Ȥ - # - # ConsumerBase ֥ CORBA::Object_var ȤݻƤ - # ֥ȥե󥹤롣 - # - # @param self - # - # @return obj CORBA ֥ȤΥե - # - # @else - # - # @brief Get CORBA Object - # - # @param self - # - # @return Object reference of CORBA object - # - # @endif - def getObject(self): - return self._objref - - - ## - # @if jp - # - # @brief CORBA֥Ȥ򥯥ꥢ - # - # ꤵƤ CORBA ֥Ȥ򥯥ꥢ롣 - # CORBA֥ȤΤΤФƤϲʤ - # - # @param self - # - # @else - # - # @endif - def releaseObject(self): - self._objref = CORBA.Object._nil +class CorbaConsumerBase: + """ + """ + + ## + # @if jp + # + # @brief コンストラクタ + # + # @param self + # @param consumer コピー元のCorbaConsumerBaseオブジェクト + # + # @else + # + # @brief Consructor + # + # @param self + # + # @endif + def __init__(self, consumer=None): + if consumer: + self._objref = consumer._objref + else: + self._objref = CORBA.Object._nil + + ## + # @if jp + # + # @brief 代入演算子 + # + # @param self + # @param consumer 代入元 + # + # @return 代入結果 + # + # @else + # + # @brief Assignment operator + # + # @param self + # @param consumer Copy source. + # + # @endif + + def equal(self, consumer): + self._objref = consumer._objref + return self + + ## + # @if jp + # + # @brief CORBAオブジェクトをセットする + # + # 与えられたオブジェクトリファレンスは、ConsumerBase オブジェクト内に + # CORBA::Object_var 型として保持される。 + # + # @param self + # @param obj CORBA オブジェクトのリファレンス + # + # @return obj が nil リファレンスの場合 false を返す。 + # + # @else + # + # @brief Set CORBA Object + # + # The given CORBA Object is held as CORBA::Object_var type + # + # @param self + # @param obj Object reference of CORBA object + # + # @return If obj is nil reference, it returns false. + # + # @endif + + def setObject(self, obj): + if CORBA.is_nil(obj): + return False + + self._objref = obj + return True + + ## + # @if jp + # + # @brief CORBAオブジェクトを取得する + # + # ConsumerBase オブジェクト内に CORBA::Object_var 型として保持されている + # オブジェクトリファレンスを取得する。 + # + # @param self + # + # @return obj CORBA オブジェクトのリファレンス + # + # @else + # + # @brief Get CORBA Object + # + # @param self + # + # @return Object reference of CORBA object + # + # @endif + + def getObject(self): + return self._objref + + ## + # @if jp + # + # @brief CORBAオブジェクトの設定をクリアする + # + # 設定されている CORBA オブジェクトをクリアする。 + # CORBAオブジェクトそのものに対しては何も操作しない。 + # + # @param self + # + # @else + # + # @endif + + def releaseObject(self): + self._objref = CORBA.Object._nil + ## # @if jp # # @class CorbaConsumer -# @brief ֥ȥե󥹤ݻץ졼ۥ饹 -# -# Ϳ줿CORBA֥Ȥݻ롣 -# ֥ȤåȤ줿ȤˡͿ줿 narrow Τǡ -# _ptr() Ǽե󥹤ϡnarrow ѤߤΥե󥹤Ǥ롣 +# @brief オブジェクトリファレンスを保持するプレースホルダクラス +# +# 引数で与えられた型のCORBAオブジェクトを保持する。 +# オブジェクトがセットされたときに、与えられた型で narrow されるので、 +# _ptr() で取得するリファレンスは、narrow 済みのリファレンスである。 # # @since 0.4.0 # @@ -186,172 +185,164 @@ def releaseObject(self): # # @endif class CorbaConsumer(CorbaConsumerBase): - """ - """ - - - - ## - # @if jp - # - # @brief 󥹥ȥ饯 - # - # @param self - # @param interfaceType Υۥݻ륪֥Ȥη - # (ǥե;None) - # @param consumer Υۥݻ륪֥(ǥե;None) - # - # @else - # - # @brief Consructor - # - # @endif - def __init__(self, interfaceType=None, consumer=None): - if interfaceType: - self._interfaceType = interfaceType - else: - self._interfaceType = None - - if consumer: - CorbaConsumerBase.__init__(self, consumer) - self._var = consumer._var - else: - CorbaConsumerBase.__init__(self) - self._var = None - - self._sev = None - - - ## - # @if jp - # - # @brief 黻 - # - # @param self - # @param consumer - # - # @return - # - # @else - # - # @brief Assignment operator - # - # @param self - # @param consumer Copy source. - # - # @endif - def equal(self, consumer): - self._var = consumer._var - - - def __del__(self): - pass - #self.releaseObject() - - - - - ## - # @if jp - # @brief ֥Ȥ򥻥åȤ - # - # ConsumerBase ΥС饤ɡCORBA::Object_var ˥֥Ȥ򥻥å - # ȤȤˡѥ᡼η narrow ֥Ȥݻ롣 - # - # @param self - # @param obj CORBA Objecct - # - # @return ֥ - # оݥ֥Ȥ null ξ false ֤äƤ - # - # @else - # @brief Set Object - # - # Override function of ConsumerBase. This operation set an Object to - # CORBA:Object_var in the class, and this object is narrowed to - # given parameter and stored in. - # - # @param self - # @param obj CORBA Objecct - # - # @endif - def setObject(self, obj): - if not CorbaConsumerBase.setObject(self, obj): - self.releaseObject() - return False - - if self._interfaceType: - - self._var = obj._narrow(self._interfaceType) - if self._var is None: - self.releaseObject() - return False - - else: - self._var = self._objref - - - return True - #if not CORBA.is_nil(self._var): - # return True - - #self.releaseObject() - #return False - - - ## - # @if jp - # @brief ObjectType Υ֥ȤΥե󥹤 - # - # ObjectType narrowѤߤΥ֥ȤΥե󥹤롣 - # ֥ȥե󥹤ѤˤϡsetObject() ǥåȺѤߤ - # ʤФʤʤ - # ֥ȤåȤƤʤСnil ֥ȥե󥹤 - # ֤롣 - # - # @param self - # - # @return ObjectType narrow ѤߤΥ֥ȤΥե - # - # @else - # @brief Get Object reference narrowed as ObjectType - # - # This operation returns object reference narrowed as ObjectType. - # To use the returned object reference, reference have to be set by - # setObject(). - # If object is not set, this operation returns nil object reference. - # - # @return The object reference narrowed as ObjectType - # - # @endif - def _ptr(self, get_ref=False): - if get_ref: - return self._var - if self._sev is not None: - return self._sev - try: - mgr = OpenRTM_aist.Manager.instance() - self._sev = mgr._poa.reference_to_servant(self._var) - return self._sev - except: - return self._var - - - - ## - # @if jp - # - # @brief CORBA֥Ȥ򥯥ꥢ - # - # ꤵƤ CORBA ֥Ȥ򥯥ꥢ롣 - # CORBA֥ȤΤΤФƤϲʤ - # - # @param self - # - # @else - # - # @endif - def releaseObject(self): - CorbaConsumerBase.releaseObject(self) - self._var = CORBA.Object._nil - self._sev = None + """ + """ + + ## + # @if jp + # + # @brief コンストラクタ + # + # @param self + # @param interfaceType このホルダが保持するオブジェクトの型 + # (デフォルト値;None) + # @param consumer このホルダが保持するオブジェクト(デフォルト値;None) + # + # @else + # + # @brief Consructor + # + # @endif + def __init__(self, interfaceType=None, consumer=None): + if interfaceType: + self._interfaceType = interfaceType + else: + self._interfaceType = None + + if consumer: + CorbaConsumerBase.__init__(self, consumer) + self._var = consumer._var + else: + CorbaConsumerBase.__init__(self) + self._var = None + + self._sev = None + + ## + # @if jp + # + # @brief 代入演算子 + # + # @param self + # @param consumer 代入元 + # + # @return 代入結果 + # + # @else + # + # @brief Assignment operator + # + # @param self + # @param consumer Copy source. + # + # @endif + + def equal(self, consumer): + self._var = consumer._var + + def __del__(self): + pass + + ## + # @if jp + # @brief オブジェクトをセットする + # + # ConsumerBase のオーバーライド。CORBA::Object_var にオブジェクトをセット + # するとともに、パラメータの型で narrow したオブジェクトを保持する。 + # + # @param self + # @param obj CORBA Objecct + # + # @return オブジェクト設定結果 + # 設定対象オブジェクトが null の場合は false が返ってくる + # + # @else + # @brief Set Object + # + # Override function of ConsumerBase. This operation set an Object to + # CORBA:Object_var in the class, and this object is narrowed to + # given parameter and stored in. + # + # @param self + # @param obj CORBA Objecct + # + # @endif + + def setObject(self, obj): + if not CorbaConsumerBase.setObject(self, obj): + self.releaseObject() + return False + + if self._interfaceType: + + self._var = obj._narrow(self._interfaceType) + if self._var is None: + self.releaseObject() + return False + + else: + self._var = self._objref + + return True + # if not CORBA.is_nil(self._var): + # return True + + # self.releaseObject() + # return False + + ## + # @if jp + # @brief ObjectType 型のオブジェクトのリファレンスを取得 + # + # ObjectType に narrow済みのオブジェクトのリファレンスを取得する。 + # オブジェクトリファレンスを使用するには、setObject() でセット済みで + # なければならない。 + # オブジェクトがセットされていなければ nil オブジェクトリファレンスが + # 返される。 + # + # @param self + # + # @return ObjectType に narrow 済みのオブジェクトのリファレンス + # + # @else + # @brief Get Object reference narrowed as ObjectType + # + # This operation returns object reference narrowed as ObjectType. + # To use the returned object reference, reference have to be set by + # setObject(). + # If object is not set, this operation returns nil object reference. + # + # @return The object reference narrowed as ObjectType + # + # @endif + + def _ptr(self, get_ref=False): + if get_ref: + return self._var + if self._sev is not None: + return self._sev + try: + mgr = OpenRTM_aist.Manager.instance() + self._sev = mgr._poa.reference_to_servant(self._var) + return self._sev + except BaseException: + return self._var + + ## + # @if jp + # + # @brief CORBAオブジェクトの設定をクリアする + # + # 設定されている CORBA オブジェクトをクリアする。 + # CORBAオブジェクトそのものに対しては何も操作しない。 + # + # @param self + # + # @else + # + # @endif + + def releaseObject(self): + CorbaConsumerBase.releaseObject(self) + self._var = CORBA.Object._nil + self._sev = None diff --git a/OpenRTM_aist/CorbaNaming.py b/OpenRTM_aist/CorbaNaming.py index 5cff0a8a..527c349c 100644 --- a/OpenRTM_aist/CorbaNaming.py +++ b/OpenRTM_aist/CorbaNaming.py @@ -1,5 +1,5 @@ #!/usr/bin/env python -# -*- coding: euc-jp -*- +# -*- coding: utf-8 -*- ## @@ -24,19 +24,19 @@ ## # @if jp # @class CorbaNaming -# @brief CORBA Naming Service إѡ饹 +# @brief CORBA Naming Service ヘルパークラス # -# Υ饹ϡCosNaming::NamingContext Фåѡ饹Ǥ롣 -# CosNaming::NamingContext ĥڥ졼ȤۤƱǽ -# ڥ졼󶡤ȤȤˡ͡ॳݡͥ CosNaming::Name -# ʸˤ̾ɽդ륪ڥ졼󶡤롣 +# このクラスは、CosNaming::NamingContext に対するラッパークラスである。 +# CosNaming::NamingContext が持つオペレーションとほぼ同じ機能の +# オペレーションを提供するとともに、ネームコンポーネント CosNaming::Name +# の代わりに文字列による名前表現を受け付けるオペレーションも提供する。 # -# ֥Ȥ뤤ľ CORBA ͡ॵФ³ -# ʸ塢Υ͡ॵФΥ롼ȥƥȤФƼΥڥ졼 -# 롣 -# ؤΥ͡ߥ󥰥ƥȤκ䥪֥ȤΥХɤˤơ -# ΥƥȤ¸ߤʤǤ⡢Ū˥ƥȤХ -# ŪΥƥȤ䥪֥ȤΥХɤԤȤǤ롣 +# オブジェクトは生成時、あるいは生成直後に CORBA ネームサーバに接続し +# 以後、このネームサーバのルートコンテキストに対して種々のオペレーション +# を処理する。 +# 深い階層のネーミングコンテキストの作成やオブジェクトのバインドにおいて、 +# 途中のコンテキストが存在しない場合でも、強制的にコンテキストをバインド +# し目的のコンテキストやオブジェクトのバインドを行うこともできる。 # # @since 0.4.0 # @@ -58,1267 +58,1264 @@ # @since 0.4.0 # # @endif + + class CorbaNaming: - """ - """ - - - - ## - # @if jp - # - # @brief 󥹥ȥ饯 - # - # @param self - # @param orb ORB - # @param name_server ͡ॵФ̾(ǥե:None) - # - # @else - # - # @brief Consructor - # - # @endif - def __init__(self, orb, name_server=None): - self._orb = orb - self._nameServer = "" - self._rootContext = CosNaming.NamingContext._nil - self._blLength = 100 - - if name_server: - self._nameServer = "corbaloc::" + name_server + "/NameService" - try: - obj = orb.string_to_object(self._nameServer) + """ + """ + + ## + # @if jp + # + # @brief コンストラクタ + # + # @param self + # @param orb ORB + # @param name_server ネームサーバの名称(デフォルト値:None) + # + # @else + # + # @brief Consructor + # + # @endif + def __init__(self, orb, name_server=None): + self._orb = orb + self._nameServer = "" + self._rootContext = CosNaming.NamingContext._nil + self._blLength = 100 + + if name_server: + self._nameServer = "corbaloc::" + name_server + "/NameService" + try: + obj = orb.string_to_object(self._nameServer) + self._rootContext = obj._narrow(CosNaming.NamingContext) + if CORBA.is_nil(self._rootContext): + print("CorbaNaming: Failed to narrow the root naming context.") + + except CORBA.ORB.InvalidName: + self.__print_exception() + print("Service required is invalid [does not exist].") + + return + + ## + # @if jp + # + # @brief デストラクタ + # + # @param self + # + # @else + # + # @brief destructor + # + # @endif + + def __del__(self): + return + + ## + # @if jp + # + # @brief ネーミングサービスの初期化 + # + # 指定されたネームサーバ上のネーミングサービスを初期化します。 + # + # @param self + # @param name_server ネームサーバの名称 + # + # @else + # + # @endif + + def init(self, name_server): + self._nameServer = "corbaloc::" + name_server + "/NameService" + obj = self._orb.string_to_object(self._nameServer) self._rootContext = obj._narrow(CosNaming.NamingContext) if CORBA.is_nil(self._rootContext): - print("CorbaNaming: Failed to narrow the root naming context.") - - except CORBA.ORB.InvalidName: - self.__print_exception() - print("Service required is invalid [does not exist].") - - return - - - ## - # @if jp - # - # @brief ǥȥ饯 - # - # @param self - # - # @else - # - # @brief destructor - # - # @endif - def __del__(self): - return - - - ## - # @if jp - # - # @brief ͡ߥ󥰥ӥν - # - # ꤵ줿͡ॵоΥ͡ߥ󥰥ӥޤ - # - # @param self - # @param name_server ͡ॵФ̾ - # - # @else - # - # @endif - def init(self, name_server): - self._nameServer = "corbaloc::" + name_server + "/NameService" - obj = self._orb.string_to_object(self._nameServer) - self._rootContext = obj._narrow(CosNaming.NamingContext) - if CORBA.is_nil(self._rootContext): - raise MemoryError - - return - - - ## - # @if jp - # - # @brief 롼ȥƥȤ¸Ƥ뤫֤ - # - # 롼ȥƥȤ¸Ƥ뤫ΥåԤ - # - # @param self - # @else - # @brief Check on whether the root context is alive. - # Check on whether the root context is alive. - # @param self - # @endif - # bool CorbaNaming::isAlive() - def isAlive(self): - try: - if self._rootContext._non_existent(): - return False - return True - except: - self.__print_exception() - return False - - - - - ## - # @if jp - # - # @brief Object bind - # - # CosNaming::bind() ȤۤƱƯ򤹤뤬Ϳ줿͡ॵФ - # 롼ȥƥȤФbind()ƤӽФۤʤ롣 - # - # Name Object NamingContext ˥Хɤ롣 - # c_n n ܤ NameComponent 򤢤魯Ȥȡ - # name n Ĥ NameComponent ȤʲΤ褦˰롣 - # - # cxt->bind(, obj) ϰʲƱǤ롣 - # cxt->resolve()->bind(, obj) - # - # ʤ1ܤn-1ܤΥƥȤ褷n-1ܤΥƥ - # name Ȥơobj bind 롣 - # ̾˻ä NemingContext ϡ - # bindContext() rebindContext() Ǵ˥ХɺѤߤǤʤФʤʤ - # ⤷ NamingContext ¸ߤʤˤϡ - # NotFound 㳰ȯ롣 - # - # Хɥե饰 force true λϡ - # ¸ߤʤˤ⡢ƵŪ˥ƥȤХɤʤ顢 - # ǽŪ obj ̾ name ˥Хɤ롣 - # - # ξǤ⡢n-1ܤΥƥȾ name Υ֥ - # (Object 뤤 ƥ) ХɤƤ - # AlreadyBound 㳰ȯ롣 - # - # @param self - # @param name_list ֥Ȥդ̾ NameComponent - # @param obj Ϣդ Object - # @param force trueξ硢ΥƥȤŪ˥Хɤ - # (ǥե:None) - # - # @exception NotFound ¸ߤʤ - # @exception CannotProceed 餫ͳǽ³Ǥʤ - # @exception InvalidName name_list ̾ - # @exception AlreadyBound name Object Ǥ˥ХɤƤ롣 - # - # @else - # - # @brief - # - # @endif - def bind(self, name_list, obj, force=None): - if force is None : - force = True - - try: - self._rootContext.bind(name_list, obj) - except CosNaming.NamingContext.NotFound: - if force: - self.bindRecursive(self._rootContext, name_list, obj) - else: - raise - except CosNaming.NamingContext.CannotProceed as err: - if force: - self.bindRecursive(err.cxt, err.rest_of_name, obj) - else: - raise - except CosNaming.NamingContext.AlreadyBound: - self._rootContext.rebind(name_list, obj) - - - ## - # @if jp - # - # @brief Object bind - # - # Object bind ݤͿ̾ʸɽǤ뤳Ȱʳϡbind() - # ƱǤ롣bind(toName(string_name), obj) - # - # @param self - # @param string_name ֥Ȥդ̾ʸɽ - # @param obj Ϣդ륪֥ - # @param force trueξ硢ΥƥȤŪ˥Хɤ - # (ǥե:true) - # - # @exception NotFound ¸ߤʤ - # @exception CannotProceed 餫ͳǽ³Ǥʤ - # @exception InvalidName string_name ̾ - # @exception AlreadyBound name Object Ǥ˥ХɤƤ롣 - # - # @else - # - # @brief - # - # @endif - def bindByString(self, string_name, obj, force=True): - self.bind(self.toName(string_name), obj, force) - - - ## - # @if jp - # - # @brief ΥƥȤ bind ʤ Object bind - # - # context Ϳ줿 NamingContext Фơname ǻꤵ줿 - # ͡ॳݡͥ NamingContext Ȥ - # 褷ʤ顢̾ Ф obj bind 롣 - # ⤷ б NamingContext ʤˤ - # NamingContext Хɤ롣 - # - # ǽŪ б NamingContext - # ޤϲ褵줿ǡCosNaming::bind(, object) ƤӽФ롣 - # ΤȤǤ˥Хǥ󥰤¸ߤ AlreadyBound㳰ȯ롣 - # - # ΥƥȤ褹ǡ褷褦Ȥ륳ƥȤ - # Ʊ̾ NamingContext ǤϤʤ Binding ¸ߤ硢 - # CannotProceed 㳰ȯߤ롣 - # - # @param self - # @param context bind 򳫻Ϥ롡NamingContext - # @param name_list ֥Ȥդ̾Υ͡ॳݡͥ - # @param obj Ϣդ륪֥ - # - # @exception CannotProceed б NamingContext - # ΤҤȤĤǤ NamingContext ʳ object ˥Х - # Ƥꡢ³Ǥʤ - # @exception InvalidName ̾ name_list - # @exception AlreadyBound name ˤǤ˲餫 object Х - # Ƥ롣 - # @else - # - # @brief - # - # @endif - def bindRecursive(self, context, name_list, obj): - length = len(name_list) - cxt = context - for i in range(length): - if i == length -1: + raise MemoryError + + return + + ## + # @if jp + # + # @brief ルートコンテキストが生存しているかを返す。 + # + # ルートコンテキストが生存しているかのチェックを行う。 + # + # @param self + # @else + # @brief Check on whether the root context is alive. + # Check on whether the root context is alive. + # @param self + # @endif + # bool CorbaNaming::isAlive() + + def isAlive(self): try: - cxt.bind(self.subName(name_list, i, i), obj) + if self._rootContext._non_existent(): + return False + return True + except BaseException: + self.__print_exception() + return False + + ## + # @if jp + # + # @brief Object を bind する + # + # CosNaming::bind() とほぼ同等の働きをするが、常に与えられたネームサーバの + # ルートコンテキストに対してbind()が呼び出される点が異なる。 + # + # Name と Object を当該 NamingContext 上にバインドする。 + # c_n が n 番目の NameComponent をあらわすとすると、 + # name が n 個の NameComponent から成るとき、以下のように扱われる。 + # + # cxt->bind(, obj) は以下の操作と同等である。 + # cxt->resolve()->bind(, obj) + # + # すなわち、1番目からn-1番目のコンテキストを解決し、n-1番目のコンテキスト + # 上に name として obj を bind する。 + # 名前解決に参加する の NemingContext は、 + # bindContext() や rebindContext() で既にバインド済みでなければならない。 + # もし の NamingContext が存在しない場合には、 + # NotFound 例外が発生する。 + # + # ただし、強制バインドフラグ force が true の時は、 + # が存在しない場合にも、再帰的にコンテキストをバインドしながら、 + # 最終的に obj を名前 name にバインドする。 + # + # いずれの場合でも、n-1番目のコンテキスト上に name のオブジェクト + # (Object あるいは コンテキスト) がバインドされていれば + # AlreadyBound 例外が発生する。 + # + # @param self + # @param name_list オブジェクトに付ける名前の NameComponent + # @param obj 関連付けられる Object + # @param force trueの場合、途中のコンテキストを強制的にバインドする + # (デフォルト値:None) + # + # @exception NotFound 途中の が存在しない。 + # @exception CannotProceed 何らかの理由で処理を継続できない。 + # @exception InvalidName 引数 name_list の名前が不正。 + # @exception AlreadyBound name の Object がすでにバインドされている。 + # + # @else + # + # @brief + # + # @endif + + def bind(self, name_list, obj, force=None): + if force is None: + force = True + + try: + self._rootContext.bind(name_list, obj) + except CosNaming.NamingContext.NotFound: + if force: + self.bindRecursive(self._rootContext, name_list, obj) + else: + raise + except CosNaming.NamingContext.CannotProceed as err: + if force: + self.bindRecursive(err.cxt, err.rest_of_name, obj) + else: + raise except CosNaming.NamingContext.AlreadyBound: - cxt.rebind(self.subName(name_list, i, i), obj) + self._rootContext.rebind(name_list, obj) + + ## + # @if jp + # + # @brief Object を bind する + # + # Object を bind する際に与える名前が文字列表現であること以外は、bind() + # と同じである。bind(toName(string_name), obj) と等価。 + # + # @param self + # @param string_name オブジェクトに付ける名前の文字列表現 + # @param obj 関連付けられるオブジェクト + # @param force trueの場合、途中のコンテキストを強制的にバインドする + # (デフォルト値:true) + # + # @exception NotFound 途中の が存在しない。 + # @exception CannotProceed 何らかの理由で処理を継続できない。 + # @exception InvalidName 引数 string_name の名前が不正。 + # @exception AlreadyBound name の Object がすでにバインドされている。 + # + # @else + # + # @brief + # + # @endif + + def bindByString(self, string_name, obj, force=True): + self.bind(self.toName(string_name), obj, force) + + ## + # @if jp + # + # @brief 途中のコンテキストを bind しながら Object を bind する + # + # context で与えられた NamingContext に対して、name で指定された + # ネームコンポーネント を NamingContext として + # 解決しながら、名前 に対して obj を bind する。 + # もし、 に対応する NamingContext がない場合には + # 新たな NamingContext をバインドする。 + # + # 最終的に に対応する NamingContext が生成 + # または解決された上で、CosNaming::bind(, object) が呼び出される。 + # このとき、すでにバインディングが存在すれば AlreadyBound例外が発生する。 + # + # 途中のコンテキストを解決する過程で、解決しようとするコンテキストと + # 同じ名前の NamingContext ではない Binding が存在する場合、 + # CannotProceed 例外が発生し処理を中止する。 + # + # @param self + # @param context bind を開始する NamingContext + # @param name_list オブジェクトに付ける名前のネームコンポーネント + # @param obj 関連付けられるオブジェクト + # + # @exception CannotProceed に対応する NamingContext + # のうちひとつが、すでに NamingContext 以外の object にバインド + # されており、処理を継続できない。 + # @exception InvalidName 名前 name_list が不正 + # @exception AlreadyBound name にすでに何らかの object がバインド + # されている。 + # @else + # + # @brief + # + # @endif + + def bindRecursive(self, context, name_list, obj): + length = len(name_list) + cxt = context + for i in range(length): + if i == length - 1: + try: + cxt.bind(self.subName(name_list, i, i), obj) + except CosNaming.NamingContext.AlreadyBound: + cxt.rebind(self.subName(name_list, i, i), obj) + return + else: + if self.objIsNamingContext(cxt): + cxt = self.bindOrResolveContext( + cxt, self.subName(name_list, i, i)) + else: + raise CosNaming.NamingContext.CannotProceed( + cxt, self.subName(name_list, i)) return - else: - if self.objIsNamingContext(cxt): - cxt = self.bindOrResolveContext(cxt,self.subName(name_list, i, i)) + + ## + # @if jp + # + # @brief Object を rebind する + # + # name_list で指定された Binding がすでに存在する場合を除いて bind() と同じ + # である。バインディングがすでに存在する場合には、新しいバインディングに + # 置き換えられる。 + # + # @param self + # @param name_list オブジェクトに付ける名前の NameComponent + # @param obj 関連付けられるオブジェクト + # @param force trueの場合、途中のコンテキストを強制的にバインドする + # (デフォルト値:true) + # + # @exception NotFound 途中の が存在しない。 + # @exception CannotProceed 何らかの理由で処理を継続できない。 + # @exception InvalidName 名前 name_list が不正 + # + # @else + # + # @brief + # + # @endif + + def rebind(self, name_list, obj, force=True): + # if force is None: + # force = True + + try: + self._rootContext.rebind(name_list, obj) + + except CosNaming.NamingContext.NotFound: + if force: + self.rebindRecursive(self._rootContext, name_list, obj) + else: + self.__print_exception() + raise + + except CosNaming.NamingContext.CannotProceed as err: + if force: + self.rebindRecursive(err.cxt, err.rest_of_name, obj) + else: + self.__print_exception() + raise + + ## + # @if jp + # + # @brief Object を rebind する + # + # Object を rebind する際に与える名前が文字列表現であること以外は rebind() + # と同じである。rebind(toName(string_name), obj) と等価。 + # + # @param self + # @param string_name オブジェクトに付ける名前の文字列表現 + # @param obj 関連付けられるオブジェクト + # @param force trueの場合、途中のコンテキストを強制的にバインドする + # (デフォルト値:true) + # + # @exception NotFound 途中の が存在しない。 + # @exception CannotProceed 何らかの理由で処理を継続できない。 + # @exception InvalidName 引数 string_name の名前が不正。 + # + # @else + # + # @brief + # + # @endif + + def rebindByString(self, string_name, obj, force=True): + self.rebind(self.toName(string_name), obj, force) + + return + + ## + # @if jp + # + # @brief 途中のコンテキストを bind しながら Object を rebind する + # + # name_list で指定された NamingContext もしくは Object がすでに存在する + # 場合を除いて bindRecursive() と同じである。 + # + # name_list で指定されたバインディングがすでに存在する場合には、 + # 新しいバインディングに置き換えられる。 + # + # @param self + # @param context bind を開始する NamingContext + # @param name_list オブジェクトに付ける名前の NameComponent + # @param obj 関連付けられるオブジェクト + # + # @exception CannotProceed 途中のコンテキストが解決できない。 + # @exception InvalidName 与えられた name_list が不正。 + # + # @else + # + # @brief + # + # @endif + + def rebindRecursive(self, context, name_list, obj): + length = len(name_list) + for i in range(length): + if i == length - 1: + context.rebind(self.subName(name_list, i, i), obj) + return + else: + if self.objIsNamingContext(context): + try: + context = context.bind_new_context( + self.subName(name_list, i, i)) + except CosNaming.NamingContext.AlreadyBound: + obj_ = context.resolve(self.subName(name_list, i, i)) + context = obj_._narrow(CosNaming.NamingContext) + else: + raise CosNaming.NamingContext.CannotProceed( + context, self.subName(name_list, i)) + + ## + # @if jp + # + # @brief NamingContext を bind する + # + # bind 対象として指定された引数 name が文字列の場合は bindByString() と、 + # それ以外の場合は bind() と同じである。 + # + # @param self + # @param name オブジェクトに付ける名前 + # @param name_cxt 関連付けられる NamingContext + # @param force trueの場合、途中のコンテキストを強制的にバインドする + # (デフォルト値:True) + # + # @exception NotFound 途中の が存在しない。 + # @exception CannotProceed 何らかの理由で処理を継続できない。 + # @exception InvalidName 引数 name の名前が不正。 + # @exception AlreadyBound name の Object がすでにバインドされている。 + # + # @else + # + # @brief + # + # @endif + + def bindContext(self, name, name_cxt, force=True): + if isinstance(name, str): + self.bind(self.toName(name), name_cxt, force) else: - raise CosNaming.NamingContext.CannotProceed(cxt, self.subName(name_list, i)) - return - - - ## - # @if jp - # - # @brief Object rebind - # - # name_list ǻꤵ줿 Binding Ǥ¸ߤ bind() Ʊ - # Ǥ롣Хǥ󥰤Ǥ¸ߤˤϡХǥ󥰤 - # ֤롣 - # - # @param self - # @param name_list ֥Ȥդ̾ NameComponent - # @param obj Ϣդ륪֥ - # @param force trueξ硢ΥƥȤŪ˥Хɤ - # (ǥե:true) - # - # @exception NotFound ¸ߤʤ - # @exception CannotProceed 餫ͳǽ³Ǥʤ - # @exception InvalidName ̾ name_list - # - # @else - # - # @brief - # - # @endif - def rebind(self, name_list, obj, force=True): - #if force is None: - # force = True - - try: - self._rootContext.rebind(name_list, obj) - - except CosNaming.NamingContext.NotFound: - if force: - self.rebindRecursive(self._rootContext, name_list, obj) - else: - self.__print_exception() - raise - - except CosNaming.NamingContext.CannotProceed as err: - if force: - self.rebindRecursive(err.cxt, err.rest_of_name, obj) - else: - self.__print_exception() - raise - - - - ## - # @if jp - # - # @brief Object rebind - # - # Object rebind ݤͿ̾ʸɽǤ뤳Ȱʳ rebind() - # ƱǤ롣rebind(toName(string_name), obj) - # - # @param self - # @param string_name ֥Ȥդ̾ʸɽ - # @param obj Ϣդ륪֥ - # @param force trueξ硢ΥƥȤŪ˥Хɤ - # (ǥե:true) - # - # @exception NotFound ¸ߤʤ - # @exception CannotProceed 餫ͳǽ³Ǥʤ - # @exception InvalidName string_name ̾ - # - # @else - # - # @brief - # - # @endif - def rebindByString(self, string_name, obj, force=True): - self.rebind(self.toName(string_name), obj, force) - - return - - - ## - # @if jp - # - # @brief ΥƥȤ bind ʤ Object rebind - # - # name_list ǻꤵ줿 NamingContext ⤷ Object Ǥ¸ߤ - # bindRecursive() ƱǤ롣 - # - # name_list ǻꤵ줿Хǥ󥰤Ǥ¸ߤˤϡ - # Хǥ󥰤֤롣 - # - # @param self - # @param context bind 򳫻Ϥ롡NamingContext - # @param name_list ֥Ȥդ̾ NameComponent - # @param obj Ϣդ륪֥ - # - # @exception CannotProceed ΥƥȤǤʤ - # @exception InvalidName Ϳ줿 name_list - # - # @else - # - # @brief - # - # @endif - def rebindRecursive(self, context, name_list, obj): - length = len(name_list) - for i in range(length): - if i == length - 1: - context.rebind(self.subName(name_list, i, i), obj) + self.bind(name, name_cxt, force) + return + + ## + # @if jp + # + # @brief NamingContext を bind する + # + # bind されるオブジェクトが NamingContext であることを除いて + # bindRecursive() と同じである。 + # + # @param self + # @param context bind を開始する NamingContext + # @param name_list オブジェクトに付ける名前のネームコンポーネント + # @param name_cxt 関連付けられる NamingContext + # + # @else + # + # @brief + # + # @endif + + def bindContextRecursive(self, context, name_list, name_cxt): + self.bindRecursive(context, name_list, name_cxt) return - else: - if self.objIsNamingContext(context): - try: - context = context.bind_new_context(self.subName(name_list, i, i)) - except CosNaming.NamingContext.AlreadyBound: - obj_ = context.resolve(self.subName(name_list, i, i)) - context = obj_._narrow(CosNaming.NamingContext) + + ## + # @if jp + # + # @brief NamingContext を rebind する + # + # bind 対象として指定された引数 name が文字列の場合は rebindByString() と、 + # それ以外の場合は rebind() と同じである。 + # どちらの場合もバインディングがすでに存在する場合には、 + # 新しいバインディングに置き換えられる。 + # + # @param self + # @param name オブジェクトに付ける名前のネームコンポーネント + # @param name_cxt 関連付けられる NamingContext + # @param force trueの場合、途中のコンテキストを強制的にバインドする + # (デフォルト値:true) + # + # @exception NotFound 途中の が存在しない。 + # @exception CannotProceed 何らかの理由で処理を継続できない。 + # @exception InvalidName 引数 name の名前が不正。 + # + # @else + # + # @endif + + def rebindContext(self, name, name_cxt, force=True): + if isinstance(name, str): + self.rebind(self.toName(name), name_cxt, force) else: - raise CosNaming.NamingContext.CannotProceed(context, self.subName(name_list, i)) - - - - ## - # @if jp - # - # @brief NamingContext bind - # - # bind оݤȤƻꤵ줿 name ʸξ bindByString() ȡ - # ʳξ bind() ƱǤ롣 - # - # @param self - # @param name ֥Ȥդ̾ - # @param name_cxt Ϣդ NamingContext - # @param force trueξ硢ΥƥȤŪ˥Хɤ - # (ǥե:True) - # - # @exception NotFound ¸ߤʤ - # @exception CannotProceed 餫ͳǽ³Ǥʤ - # @exception InvalidName name ̾ - # @exception AlreadyBound name Object Ǥ˥ХɤƤ롣 - # - # @else - # - # @brief - # - # @endif - def bindContext(self, name, name_cxt, force=True): - if isinstance(name, str): - self.bind(self.toName(name), name_cxt, force) - else: - self.bind(name, name_cxt, force) - return - - - ## - # @if jp - # - # @brief NamingContext bind - # - # bind 륪֥Ȥ NamingContext Ǥ뤳Ȥ - # bindRecursive() ƱǤ롣 - # - # @param self - # @param context bind 򳫻Ϥ롡NamingContext - # @param name_list ֥Ȥդ̾Υ͡ॳݡͥ - # @param name_cxt Ϣդ NamingContext - # - # @else - # - # @brief - # - # @endif - def bindContextRecursive(self, context, name_list, name_cxt): - self.bindRecursive(context, name_list, name_cxt) - return - - - ## - # @if jp - # - # @brief NamingContext rebind - # - # bind оݤȤƻꤵ줿 name ʸξ rebindByString() ȡ - # ʳξ rebind() ƱǤ롣 - # ɤξХǥ󥰤Ǥ¸ߤˤϡ - # Хǥ󥰤֤롣 - # - # @param self - # @param name ֥Ȥդ̾Υ͡ॳݡͥ - # @param name_cxt Ϣդ NamingContext - # @param force trueξ硢ΥƥȤŪ˥Хɤ - # (ǥե:true) - # - # @exception NotFound ¸ߤʤ - # @exception CannotProceed 餫ͳǽ³Ǥʤ - # @exception InvalidName name ̾ - # - # @else - # - # @endif - def rebindContext(self, name, name_cxt, force=True): - if isinstance(name, str): - self.rebind(self.toName(name), name_cxt, force) - else: - self.rebind(name, name_cxt, force) - return - - - ## - # @if jp - # - # @brief ΥƥȤƵŪ rebind NamingContext rebind # - # bind 륪֥Ȥ NamingContext Ǥ뤳Ȥ - # rebindRecursive() ƱǤ롣 - # - # @param self - # @param context bind 򳫻Ϥ롡NamingContext - # @param name_list ֥Ȥդ̾ NameComponent - # @param name_cxt Ϣդ NamingContext - # - # @else - # - # @brief - # - # @endif - def rebindContextRecursive(self, context, name_list, name_cxt): - self.rebindRecursive(context, name_list, name_cxt) - return - - - ## - # @if jp - # - # @brief Object name 褹 - # - # name bind Ƥ륪֥ȻȤ֤ - # ͡ॳݡͥ ϺƵŪ˲褵롣 - # - # name Ϳ줿ͤʸξˤϤޤǽ toName() ˤä - # NameComponent Ѵ롣 - # - # CosNaming::resolve() ȤۤƱƯ򤹤뤬Ϳ줿 - # ͡ॵФΥ롼ȥƥȤФ resolve() ƤӽФ - # ۤʤ롣 - # - # @param self - # @param name 褹٤֥Ȥ̾Υ͡ॳݡͥ - # - # @return 褵줿֥Ȼ - # - # @exception NotFound ¸ߤʤ - # @exception CannotProceed 餫ͳǽ³Ǥʤ - # @exception InvalidName name ̾ - # - # @else - # - # @endif - def resolve(self, name): - if isinstance(name, str): - name_ = self.toName(name) - else: - name_ = name - - try: - obj = self._rootContext.resolve(name_) - return obj - except CosNaming.NamingContext.NotFound: - self.__print_exception() - return None - - - ## - # @if jp - # - # @brief ꤵ줿̾Υ֥Ȥ bind - # - # name bind Ƥ륪֥ȻȤ롣 - # ͡ॳݡͥ ϺƵŪ˲褵롣 - # - # name Ϳ줿ͤʸξˤϤޤǽ toName() ˤä - # NameComponent Ѵ롣 - # - # CosNaming::unbind() ȤۤƱƯ򤹤뤬Ϳ줿 - # ͡ॵФΥ롼ȥƥȤФ unbind() ƤӽФ - # ۤʤ롣 - # - # @param self - # @param name 륪֥ȤΥ͡ॳݡͥ - # - # @exception NotFound ¸ߤʤ - # @exception CannotProceed 餫ͳǽ³Ǥʤ - # @exception InvalidName name ̾ - # - # @else - # - # @endif - # void unbind(const CosNaming::Name& name) - # throw(NotFound, CannotProceed, InvalidName); - def unbind(self, name): - if isinstance(name, str): - name_ = self.toName(name) - else: - name_ = name - - try: - self._rootContext.unbind(name_) - except: - self.__print_exception() - - return - - - ## - # @if jp - # - # @brief ƥȤ - # - # Ϳ줿͡ॵо줿 NamingContext ֤ - # ֤줿 NamingContext bind Ƥʤ - # - # @param self - # - # @return 줿 NamingContext - # - # @else - # - # @endif - def newContext(self): - return self._rootContext.new_context() - - - ## - # @if jp - # - # @brief ƥȤ bind - # - # Ϳ줿 name ФƿƥȤХɤ롣 - # 줿NamingContext ϥ͡ॵо줿ΤǤ롣 - # - # name Ϳ줿ͤʸξˤϤޤǽ toName() ˤä - # NameComponent Ѵ롣 - # - # @param self - # @param name NamingContextդ̾Υ͡ॳݡͥ - # @param force trueξ硢ΥƥȤŪ˥Хɤ - # (ǥե:true) - # - # @return 줿 NamingContext - # - # @exception NotFound ¸ߤʤ - # @exception CannotProceed 餫ͳǽ³Ǥʤ - # @exception InvalidName name ̾ - # @exception AlreadyBound name Object Ǥ˥ХɤƤ롣 - # - # @else - # - # @endif - def bindNewContext(self, name, force=True): - #if force is None: - # force = True - - if isinstance(name, str): - name_ = self.toName(name) - else: - name_ = name - - try: - return self._rootContext.bind_new_context(name_) - except CosNaming.NamingContext.NotFound: - if force: - self.bindRecursive(self._rootContext, name_, self.newContext()) - else: - self.__print_exception() - raise - except CosNaming.NamingContext.CannotProceed as err: - if force: - self.bindRecursive(err.cxt, err.rest_of_name, self.newContext()) - else: - self.__print_exception() - raise - return None - - - ## - # @if jp - # - # @brief NamingContext 󥢥ƥֲ - # - # context ǻꤵ줿 NamingContext 󥢥ƥֲ롣 - # context ¾ΥƥȤХɤƤ NotEmpty 㳰 - # ȯ롣 - # - # @param self - # @param context 󥢥ƥֲ NamingContext - # - # @exception NotEmpty оcontext ¾ΥƥȤХɤƤ롣 - # - # @else - # - # @else - # - # @brief Destroy the naming context - # - # Delete the specified naming context. - # any bindings should be in which the given context is bound to - # some names before invoking operation on it. - # - # @param context NamingContext which is destroied. - # - # @exception NotEmpty - # - # @else - # - # @endif - def destroy(self, context): - context.destroy() - - - ## - # @if jp - # @brief NamingContext ƵŪ˲ä󥢥ƥֲ - # - # context Ϳ줿 NamingContext Фơname ǻꤵ줿 - # ͡ॳݡͥ NamingContext Ȥ - # 褷ʤ顢̾ Ф 󥢥ƥֲԤ - # - # @param self - # @param context 󥢥ƥֲ NamingContext - # - # @exception NotEmpty оcontext ¾ΥƥȤХɤƤ롣 - # @exception NotFound ¸ߤʤ - # @exception CannotProceed 餫ͳǽ³Ǥʤ - # @exception InvalidName name ̾ - # - # @else - # @brief Destroy the naming context recursively - # @endif - def destroyRecursive(self, context): - cont = True - bl = [] - bi = 0 - bl, bi = context.list(self._blLength) - while cont: - for i in range(len(bl)): - if bl[i].binding_type == CosNaming.ncontext: - obj = context.resolve(bl[i].binding_name) - next_context = obj._narrow(CosNaming.NamingContext) - - self.destroyRecursive(next_context) - context.unbind(bl[i].binding_name) - next_context.destroy() - elif bl[i].binding_type == CosNaming.nobject: - context.unbind(bl[i].binding_name) - - if CORBA.is_nil(bi): - cont = False - else: - bi.next_n(self._blLength) - - #if not (CORBA.is_nil(bi)): - # bi.destroy() - return - - - ## - # @if jp - # @brief ٤Ƥ Binding - # - # ϿƤƤBinding 롣 - # - # @param self - # - # @else - # @brief Destroy all binding - # @endif - def clearAll(self): - self.destroyRecursive(self._rootContext) - return - - - ## - # @if jp - # @brief Ϳ줿 NamingContext Binding - # - # ꤵ줿 NamingContext Binding 롣 - # - # @param self - # @param name_cxt Binding о NamingContext - # @param how_many Binding 볬ؤο - # @param rbl Binding ݻۥ - # @param rbi Binding 򤿤ɤ뤿Υƥ졼 - # - # @else - # @endif - def list(self, name_cxt, how_many, rbl, rbi): - bl, bi = name_cxt.list(how_many) - - for i in bl: - rbl.append(bl) - - rbi.append(bi) - - - #============================================================ - # interface of NamingContext - #============================================================ - - ## - # @if jp - # @brief Ϳ줿 NameComponent ʸɽ֤ - # - # ꤵ줿 NameComponent ʸѴ롣 - # - # @param self - # @param name_list Ѵо NameComponent - # - # @return ʸѴ - # - # @exception InvalidName name_list ̾ - # - # @else - # @brief Get string representation of given NameComponent - # @endif - def toString(self, name_list): - if len(name_list) == 0: - raise CosNaming.NamingContext.InvalidName - - slen = self.getNameLength(name_list) - string_name = [""] - self.nameToString(name_list, string_name, slen) - - return string_name[0] - - - ## - # @if jp - # @brief Ϳ줿ʸɽ NameComponent ʬ򤹤 - # - # ꤵ줿ʸ NameComponent Ѵ롣 - # - # @param self - # @param sname Ѵоʸ - # - # @return NameComponent Ѵ - # - # @exception InvalidName sname - # - # @else - # @brief Get NameComponent from gien string name representation - # @endif - def toName(self, sname): - if not sname: - raise CosNaming.NamingContext.InvalidName - - string_name = sname - name_comps = [] - - - nc_length = self.split(string_name, "/", name_comps) - - #if not (nc_length > 0): - # raise CosNaming.NamingContext.InvalidName - - name_list = [CosNaming.NameComponent("","") for i in range(nc_length)] - - for i in range(nc_length): - pos = str.rfind(name_comps[i][0:],".") - if pos == -1: - name_list[i].id = name_comps[i] - name_list[i].kind = "" - else: - name_list[i].id = name_comps[i][0:pos] - name_list[i].kind = name_comps[i][(pos+1):] - - return name_list - - - ## - # @if jp - # @brief Ϳ줿 addr string_name URLɽ - # - # ꤵ줿ɥ쥹̾ΤURLѴ롣 - # - # @param self - # @param addr Ѵоݥɥ쥹 - # @param string_name Ѵо̾ - # - # @return URL Ѵ - # - # @exception InvalidAddress addr - # @exception InvalidName string_name - # - # @else - # @brief Get URL representation from given addr and string_name - # @endif - def toUrl(self, addr, string_name): - return self._rootContext.to_url(addr, string_name) - - - ## - # @if jp - # @brief Ϳ줿ʸɽ resolve ֥Ȥ֤ - # - # ꤵ줿ʸɽresolve֥Ȥ롣 - # - # @param self - # @param string_name оݥ֥ʸɽ - # - # @return 褵줿֥ - # - # @exception NotFound ¸ߤʤ - # @exception CannotProceed 餫ͳǽ³Ǥʤ - # @exception InvalidName name ̾ - # @exception AlreadyBound name Object Ǥ˥ХɤƤ롣 - # - # @else - # @brief Resolve from name of string representation and get object - # @endif - def resolveStr(self, string_name): - return self.resolve(self.toName(string_name)) - - - #============================================================ - # Find functions - #============================================================ - - ## - # @if jp - # - # @brief ֥Ȥ̾Хɤޤϲ褹 - # - # ꤵ줿ƥȤФƥ֥Ȥ NameComponent ǻꤵ줿 - # ֤˥Хɤ롣 - # Ʊս˴¾ǤХɺѤߤξϡ¸ΥХɺѤǤ - # 롣 - # - # @param self - # @param context bind ⤷ resole оݥƥ - # @param name_list ֥Ȥդ̾ NameComponent - # @param obj Ϣդ Object - # - # @return NameComponent ǻꤵ줿֤˥ХɤƤ륪֥ - # - # @else - # @brief Bind of resolve the given name component - # @endif - def bindOrResolve(self, context, name_list, obj): - try: - context.bind_context(name_list, obj) - return obj - except CosNaming.NamingContext.AlreadyBound: - obj = context.resolve(name_list) - return obj - - - - ## - # @if jp - # - # @brief ƥȤ̾Хɤޤϲ褹 - # - # ꤵ줿ƥȤФ Context NameComponent ǻꤵ줿֤ - # Хɤ롣 - # Context ξϿƥȤƥХɤ롣 - # Ʊս˴¾ǤХɺѤߤξϡ¸ΥХɺѤǤ - # 롣 - # - # @param self - # @param context bind ⤷ resole оݥƥ - # @param name_list ƥȤդ̾ NameComponent - # @param new_context Ϣդ Context(ǥե:None) - # - # @return NameComponent ǻꤵ줿֤˥ХɤƤContext - # - # @else - # @brief Bind of resolve the given name component - # @endif - def bindOrResolveContext(self, context, name_list, new_context=None): - if new_context is None: - new_cxt = self.newContext() - else: - new_cxt = new_context - - obj = self.bindOrResolve(context, name_list, new_cxt) - return obj._narrow(CosNaming.NamingContext) - - - ## - # @if jp - # @brief ͡ॵФ̾ - # - # ꤷ͡ॵФ̾롣 - # - # @param self - # - # @return ͡ॵФ̾ - # - # @else - # @brief Get the name of naming server - # @endif - def getNameServer(self): - return self._nameServer - - - ## - # @if jp - # @brief 롼ȥƥȤ - # - # ꤷ͡ॵФΥ롼ȥƥȤ롣 - # - # @param self - # - # @return ͡ॵФΥ롼ȥƥ - # - # @else - # @brief Get the root context - # @endif - def getRootContext(self): - return self._rootContext - - - ## - # @if jp - # @brief ֥Ȥ͡ߥ󥰥ƥȤȽ̤ - # - # ꤷǤ͡ߥ󥰥ƥȤȽ̤ - # - # @param self - # @param obj Ƚо - # - # @return Ƚ̷(͡ߥ󥰥ƥ:trueʳ:false) - # - # @else - # @brief Whether the object is NamingContext - # @endif - def objIsNamingContext(self, obj): - nc = obj._narrow(CosNaming.NamingContext) - if CORBA.is_nil(nc): - return False - else: - return True - - - ## - # @if jp - # @brief Ϳ줿̾͡ߥ󥰥ƥȤɤȽ̤ - # - # NameComponent ⤷ʸǻꤷǤ͡ߥ󥰥ƥȤ - # Ƚ̤ - # - # @param self - # @param name_list Ƚо - # - # @return Ƚ̷(͡ߥ󥰥ƥ:trueʳ:false) - # - # @else - # @brief Whether the given name component is NamingContext - # @endif - def nameIsNamingContext(self, name_list): - return self.objIsNamingContext(self.resolve(name_list)) - - - ## - # @if jp - # @brief ͡ॳݡͥȤʬ֤ - # - # ꤵ줿ϰϤΥ͡ॳݡͥȤ롣 - # λ֤ꤵƤʤϡǸǤ͡ॳݡͥ - # ֤ - # - # @param self - # @param name_list оNameComponent - # @param begin ϰϳϰ - # @param end ϰϽλ(ǥե:None) - # - # @return NameComponent - # - # @else - # @brief Get subset of given name component - # @endif - def subName(self, name_list, begin, end = None): - if end is None or end < 0: - end = len(name_list) - 1 - - sub_len = end - (begin -1) - #objId = "" - #kind = "" - - sub_name = [] - for i in range(sub_len): - sub_name.append(name_list[begin + i]) - - return sub_name - - - ## - # @if jp - # @brief ͡ॳݡͥȤʸɽ - # - # ꤷϰϤΥ͡ॳݡͥȤʸɽ롣 - # ʸɽϡNameComponentι{Nc[0],Nc[1],Nc[2]}ξ硢 - # Nc[0]id.Nc[0].kind/Nc[1]id.Nc[1].kind/Nc[2].id/Nc[2].kind - # ȤǼǤ롣 - # ʸĹꤷĹʾξϡ - # ꤷĹڤΤƤ롣 - # - # @param self - # @param name_list оNameComponent - # @param string_name ʸ - # @param slen оʸ - # - # @else - # @brief Get string representation of name component - # @endif - def nameToString(self, name_list, string_name, slen): - for i in range(len(name_list)): - for id_ in name_list[i].id: - if id_ == "/" or id_ == "." or id_ == "\\": - string_name[0] += "\\" - string_name[0] += id_ - - if name_list[i].id == "" or name_list[i].kind != "": - string_name[0] += "." - - for kind_ in name_list[i].kind: - if kind_ == "/" or kind_ == "." or kind_ == "\\": - string_name[0] += "\\" - string_name[0] += kind_ - - string_name[0] += "/" - - - ## - # @if jp - # @brief ͡ॳݡͥȤʸɽʸĹ - # - # ꤷ͡ॳݡͥȤʸɽĹ롣 - # ʸɽϡNameComponentι{Nc[0],Nc[1],Nc[2]}ξ硢 - # Nc[0]id.Nc[0].kind/Nc[1]id.Nc[1].kind/Nc[2].id/Nc[2].kind - # ȤǼǤ롣 - # - # @param self - # @param name_list оNameComponent - # - # @return ꤷ͡ॳݡͥȤʸĹ - # - # @else - # @brief Get string length of the name component's string representation - # @endif - def getNameLength(self, name_list): - slen = 0 - - for i in range(len(name_list)): - for id_ in name_list[i].id: - if id_ == "/" or id_ == "." or id_ == "\\": - slen += 1 - slen += 1 - if name_list[i].id == "" or name_list[i].kind == "": - slen += 1 - - for kind_ in name_list[i].kind: - if kind_ == "/" or kind_ == "." or kind_ == "\\": - slen += 1 - slen += 1 - - slen += 1 - - return slen - - - ## - # @if jp - # @brief ʸʬ - # - # ʸꤷǥߥʬ䤹롣 - # - # @param self - # @param input ʬоʸ - # @param delimiter ʬѥǥߥ - # @param results ʬ - # - # @return ʬ䤷ʸǿ - # - # @else - # @brief Split of string - # @endif - def split(self, input, delimiter, results): - delim_size = len(delimiter) - found_pos = 0 - begin_pos = 0 - pre_pos = 0 - substr_size = 0 - - if input[0:delim_size] == delimiter: - begin_pos = delim_size - pre_pos = delim_size - - while 1: - found_pos = str.find(input[begin_pos:],delimiter) - if found_pos == -1: - results.append(input[pre_pos:]) - break - - if found_pos > 0 and input[found_pos + begin_pos - 1] == "\\": - begin_pos += found_pos + delim_size - else: - substr_size = found_pos + (begin_pos - pre_pos) - if substr_size > 0: - results.append(input[pre_pos:(pre_pos+substr_size)]) - begin_pos += found_pos + delim_size - pre_pos = begin_pos - - return len(results) - - - ## - # @if jp - # - # @brief 㳰 - # 㳰Ϥ롣 - # - # @else - # - # @brief Print exception information - # Print exception information - # @endif - def __print_exception(self): - if sys.version_info[0:3] >= (2, 4, 0): - print(traceback.format_exc()) - else: - _exc_list = traceback.format_exception(*sys.exc_info()) - _exc_str = "".join(_exc_list) - print(_exc_str) - - return - - ## - # @if jp - # @brief Ϳ줿ѥʲλꤵ줿kindΥХǥ󥰤 - # @param self - # @param string_name ѥ - # @param string_kind kind - # @return Хǥ󥰤Υꥹ - # @else - # - # @brief Get all the binding with specified kind under given naming path - # @param self - # @param string_name path - # @param string_kind kind - # @return - # @endif - # BindingList_var listByKind(const char* string_name,const char* string_kind) - def listByKind(self, string_name, string_kind): - if not string_name: - return [] - if not string_kind: - return [] - kind = string_kind - tmp_bl = self.listBinding(string_name) - bl = [] - #tmp_len = len(tmp_bl) - #list_len = 0 - for b in tmp_bl: - if b.binding_type == CosNaming.nobject: - last_index = len(b.binding_name)-1 - tmp = b.binding_name[last_index].kind - if kind != tmp: - continue - bl.append(b) - - return bl - - ## - # @if jp - # @brief Ϳ줿 Naming ѥʲΤ٤ƤΥХǥ󥰤 - # @param self - # @param string_name Namingѥ - # @return Хǥ󥰤Υꥹ - # @else - # - # @brief Get all the binding under given naming path - # @param self - # @param string_name - # @return - # @endif - # BindingList_var list(const char* string_name) - def listBinding(self, string_name): - if not string_name: - return - obj = self.resolveStr(string_name) - #obj = self.getRootContext() - if CORBA.is_nil(obj): - return [] - #nc = obj._narrow(obj) - #if CORBA.is_nil(nc): - # return [] - max_list_size = 65536 - - bl, bi = obj.list(max_list_size) - - - max_remaining = max_list_size - len(bl) - more_bindings = not CORBA.is_nil(bi) - - - if more_bindings: - while more_bindings and (max_remaining > 0): - - (tmp_bl, more_bindings) = bi.next_n(max_remaining) - for i in tmp_bl: - bl.append(i) - - max_remaining = max_list_size - len(tmp_bl) - - return bl \ No newline at end of file + self.rebind(name, name_cxt, force) + return + + ## + # @if jp + # + # @brief 途中のコンテキストを再帰的に rebind し NamingContext を rebind する # + # bind されるオブジェクトが NamingContext であることを除いて + # rebindRecursive() と同じである。 + # + # @param self + # @param context bind を開始する NamingContext + # @param name_list オブジェクトに付ける名前の NameComponent + # @param name_cxt 関連付けられる NamingContext + # + # @else + # + # @brief + # + # @endif + + def rebindContextRecursive(self, context, name_list, name_cxt): + self.rebindRecursive(context, name_list, name_cxt) + return + + ## + # @if jp + # + # @brief Object を name から解決する + # + # name に bind されているオブジェクト参照を返す。 + # ネームコンポーネント は再帰的に解決される。 + # + # 引数 name に与えられた値が文字列の場合にはまず最初に toName() によって + # NameComponent に変換される。 + # + # CosNaming::resolve() とほぼ同等の働きをするが、常に与えられた + # ネームサーバのルートコンテキストに対して resolve() が呼び出される点が + # 異なる。 + # + # @param self + # @param name 解決すべきオブジェクトの名前のネームコンポーネント + # + # @return 解決されたオブジェクト参照 + # + # @exception NotFound 途中の が存在しない。 + # @exception CannotProceed 何らかの理由で処理を継続できない。 + # @exception InvalidName 引数 name の名前が不正。 + # + # @else + # + # @endif + + def resolve(self, name): + if isinstance(name, str): + name_ = self.toName(name) + else: + name_ = name + + try: + obj = self._rootContext.resolve(name_) + return obj + except CosNaming.NamingContext.NotFound: + self.__print_exception() + return None + + ## + # @if jp + # + # @brief 指定された名前のオブジェクトの bind を解除する + # + # name に bind されているオブジェクト参照を解除する。 + # ネームコンポーネント は再帰的に解決される。 + # + # 引数 name に与えられた値が文字列の場合にはまず最初に toName() によって + # NameComponent に変換される。 + # + # CosNaming::unbind() とほぼ同等の働きをするが、常に与えられた + # ネームサーバのルートコンテキストに対して unbind() が呼び出される点が + # 異なる。 + # + # @param self + # @param name 削除するオブジェクトのネームコンポーネント + # + # @exception NotFound 途中の が存在しない。 + # @exception CannotProceed 何らかの理由で処理を継続できない。 + # @exception InvalidName 引数 name の名前が不正。 + # + # @else + # + # @endif + # void unbind(const CosNaming::Name& name) + # throw(NotFound, CannotProceed, InvalidName); + + def unbind(self, name): + if isinstance(name, str): + name_ = self.toName(name) + else: + name_ = name + + try: + self._rootContext.unbind(name_) + except BaseException: + self.__print_exception() + + return + + ## + # @if jp + # + # @brief 新しいコンテキストを生成する + # + # 与えられたネームサーバ上で生成された NamingContext を返す。 + # 返された NamingContext は bind されていない。 + # + # @param self + # + # @return 生成された新しい NamingContext + # + # @else + # + # @endif + + def newContext(self): + return self._rootContext.new_context() + + ## + # @if jp + # + # @brief 新しいコンテキストを bind する + # + # 与えられた name に対して新しいコンテキストをバインドする。 + # 生成された NamingContext はネームサーバ上で生成されたものである。 + # + # 引数 name に与えられた値が文字列の場合にはまず最初に toName() によって + # NameComponent に変換される。 + # + # @param self + # @param name NamingContextに付ける名前のネームコンポーネント + # @param force trueの場合、途中のコンテキストを強制的にバインドする + # (デフォルト値:true) + # + # @return 生成された新しい NamingContext + # + # @exception NotFound 途中の が存在しない。 + # @exception CannotProceed 何らかの理由で処理を継続できない。 + # @exception InvalidName 引数 name の名前が不正。 + # @exception AlreadyBound name の Object がすでにバインドされている。 + # + # @else + # + # @endif + + def bindNewContext(self, name, force=True): + # if force is None: + # force = True + + if isinstance(name, str): + name_ = self.toName(name) + else: + name_ = name + + try: + return self._rootContext.bind_new_context(name_) + except CosNaming.NamingContext.NotFound: + if force: + self.bindRecursive(self._rootContext, name_, self.newContext()) + else: + self.__print_exception() + raise + except CosNaming.NamingContext.CannotProceed as err: + if force: + self.bindRecursive( + err.cxt, err.rest_of_name, self.newContext()) + else: + self.__print_exception() + raise + return None + + ## + # @if jp + # + # @brief NamingContext を非アクティブ化する + # + # context で指定された NamingContext を非アクティブ化する。 + # context に他のコンテキストがバインドされている場合は NotEmpty 例外が + # 発生する。 + # + # @param self + # @param context 非アクティブ化する NamingContext + # + # @exception NotEmpty 対象context に他のコンテキストがバインドされている。 + # + # @else + # + # @else + # + # @brief Destroy the naming context + # + # Delete the specified naming context. + # any bindings should be in which the given context is bound to + # some names before invoking operation on it. + # + # @param context NamingContext which is destroied. + # + # @exception NotEmpty + # + # @else + # + # @endif + + def destroy(self, context): + context.destroy() + + ## + # @if jp + # @brief NamingContext を再帰的に下って非アクティブ化する + # + # context で与えられた NamingContext に対して、name で指定された + # ネームコンポーネント を NamingContext として + # 解決しながら、名前 に対して 非アクティブ化を行う。 + # + # @param self + # @param context 非アクティブ化する NamingContext + # + # @exception NotEmpty 対象context に他のコンテキストがバインドされている。 + # @exception NotFound 途中の が存在しない。 + # @exception CannotProceed 何らかの理由で処理を継続できない。 + # @exception InvalidName 引数 name の名前が不正。 + # + # @else + # @brief Destroy the naming context recursively + # @endif + + def destroyRecursive(self, context): + cont = True + bl = [] + bi = None + bl, bi = context.list(self._blLength) + while cont: + for bli in bl: + if bli.binding_type == CosNaming.ncontext: + obj = context.resolve(bli.binding_name) + next_context = obj._narrow(CosNaming.NamingContext) + + self.destroyRecursive(next_context) + context.unbind(bli.binding_name) + next_context.destroy() + elif bli.binding_type == CosNaming.nobject: + context.unbind(bli.binding_name) + + if CORBA.is_nil(bi): + cont = False + else: + bi.next_n(self._blLength) + + # if not (CORBA.is_nil(bi)): + # bi.destroy() + return + + ## + # @if jp + # @brief すべての Binding を削除する + # + # 登録されている全てのBinding を削除する。 + # + # @param self + # + # @else + # @brief Destroy all binding + # @endif + + def clearAll(self): + self.destroyRecursive(self._rootContext) + return + + ## + # @if jp + # @brief 与えられた NamingContext の Binding を取得する + # + # 指定された NamingContext の Binding を取得する。 + # + # @param self + # @param name_cxt Binding 取得対象 NamingContext + # @param how_many Binding を取得する階層の深さ + # @param rbl 取得した Binding を保持するホルダ + # @param rbi 取得した Binding をたどるためのイテレータ + # + # @else + # @endif + + def list(self, name_cxt, how_many, rbl, rbi): + bl, bi = name_cxt.list(how_many) + + for i in bl: + rbl.append(bl) + + rbi.append(bi) + + # ============================================================ + # interface of NamingContext + # ============================================================ + + ## + # @if jp + # @brief 与えられた NameComponent の文字列表現を返す + # + # 指定された NameComponent を文字に変換する。 + # + # @param self + # @param name_list 変換対象 NameComponent + # + # @return 文字列変換結果 + # + # @exception InvalidName 引数 name_list の名前が不正。 + # + # @else + # @brief Get string representation of given NameComponent + # @endif + + def toString(self, name_list): + if not name_list: + raise CosNaming.NamingContext.InvalidName + + slen = self.getNameLength(name_list) + string_name = "" + string_name = self.nameToString(name_list, string_name, slen) + + return string_name + + ## + # @if jp + # @brief 与えられた文字列表現を NameComponent に分解する + # + # 指定された文字列を NameComponent に変換する。 + # + # @param self + # @param sname 変換対象文字列 + # + # @return NameComponent 変換結果 + # + # @exception InvalidName 引数 sname が不正。 + # + # @else + # @brief Get NameComponent from gien string name representation + # @endif + + def toName(self, sname): + if not sname: + raise CosNaming.NamingContext.InvalidName + + string_name = sname + name_comps = [] + + nc_length = self.split(string_name, "/", name_comps) + + # if not (nc_length > 0): + # raise CosNaming.NamingContext.InvalidName + + name_list = [CosNaming.NameComponent("", "") for i in range(nc_length)] + + for i in range(nc_length): + pos = str.rfind(name_comps[i][0:], ".") + if pos == -1: + name_list[i].id = name_comps[i] + name_list[i].kind = "" + else: + name_list[i].id = name_comps[i][0:pos] + name_list[i].kind = name_comps[i][(pos + 1):] + + return name_list + + ## + # @if jp + # @brief 与えられた addr と string_name から URL表現を取得する + # + # 指定されたアドレスと名称をURLに変換する。 + # + # @param self + # @param addr 変換対象アドレス + # @param string_name 変換対象名称 + # + # @return URL 変換結果 + # + # @exception InvalidAddress 引数 addr が不正。 + # @exception InvalidName 引数 string_name が不正。 + # + # @else + # @brief Get URL representation from given addr and string_name + # @endif + + def toUrl(self, addr, string_name): + return self._rootContext.to_url(addr, string_name) + + ## + # @if jp + # @brief 与えられた文字列表現を resolve しオブジェクトを返す + # + # 指定された文字列表現をresolveし,オブジェクトを取得する。 + # + # @param self + # @param string_name 取得対象オブジェクト文字列表現 + # + # @return 解決されたオブジェクト + # + # @exception NotFound 途中の が存在しない。 + # @exception CannotProceed 何らかの理由で処理を継続できない。 + # @exception InvalidName 引数 name の名前が不正。 + # @exception AlreadyBound name の Object がすでにバインドされている。 + # + # @else + # @brief Resolve from name of string representation and get object + # @endif + + def resolveStr(self, string_name): + return self.resolve(self.toName(string_name)) + + # ============================================================ + # Find functions + # ============================================================ + + ## + # @if jp + # + # @brief オブジェクトの名前をバインドまたは解決する + # + # 指定されたコンテキストに対してオブジェクトを NameComponent で指定された + # 位置にバインドする。 + # 同一箇所に既に他の要素がバインド済みの場合は、既存のバインド済み要素を + # 取得する。 + # + # @param self + # @param context bind もしくは resole 対象コンテキスト + # @param name_list オブジェクトに付ける名前の NameComponent + # @param obj 関連付けられる Object + # + # @return NameComponent で指定された位置にバインドされているオブジェクト + # + # @else + # @brief Bind of resolve the given name component + # @endif + + def bindOrResolve(self, context, name_list, obj): + try: + context.bind_context(name_list, obj) + return obj + except CosNaming.NamingContext.AlreadyBound: + obj = context.resolve(name_list) + return obj + + ## + # @if jp + # + # @brief コンテキストの名前をバインドまたは解決する + # + # 指定されたコンテキストに対して Contextを NameComponent で指定された位置に + # バインドする。 + # Context が空の場合は新規コンテキストを生成してバインドする。 + # 同一箇所に既に他の要素がバインド済みの場合は、既存のバインド済み要素を + # 取得する。 + # + # @param self + # @param context bind もしくは resole 対象コンテキスト + # @param name_list コンテキストに付ける名前の NameComponent + # @param new_context 関連付けられる Context(デフォルト値:None) + # + # @return NameComponent で指定された位置にバインドされているContext + # + # @else + # @brief Bind of resolve the given name component + # @endif + + def bindOrResolveContext(self, context, name_list, new_context=None): + if new_context is None: + new_cxt = self.newContext() + else: + new_cxt = new_context + + obj = self.bindOrResolve(context, name_list, new_cxt) + return obj._narrow(CosNaming.NamingContext) + + ## + # @if jp + # @brief ネームサーバの名前を取得する + # + # 設定したネームサーバの名前を取得する。 + # + # @param self + # + # @return ネームサーバの名前 + # + # @else + # @brief Get the name of naming server + # @endif + + def getNameServer(self): + return self._nameServer + + ## + # @if jp + # @brief ルートコンテキストを取得する + # + # 設定したネームサーバのルートコンテキストを取得する。 + # + # @param self + # + # @return ネームサーバのルートコンテキスト + # + # @else + # @brief Get the root context + # @endif + + def getRootContext(self): + return self._rootContext + + ## + # @if jp + # @brief オブジェクトがネーミングコンテキストか判別する + # + # 指定した要素がネーミングコンテキストか判別する + # + # @param self + # @param obj 判別対象要素 + # + # @return 判別結果(ネーミングコンテキスト:true、それ以外:false) + # + # @else + # @brief Whether the object is NamingContext + # @endif + + def objIsNamingContext(self, obj): + nc = obj._narrow(CosNaming.NamingContext) + if CORBA.is_nil(nc): + return False + else: + return True + + ## + # @if jp + # @brief 与えられた名前がネーミングコンテキストかどうか判別する + # + # NameComponent もしくは文字列で指定した要素がネーミングコンテキストか + # 判別する + # + # @param self + # @param name_list 判別対象 + # + # @return 判別結果(ネーミングコンテキスト:true、それ以外:false) + # + # @else + # @brief Whether the given name component is NamingContext + # @endif + + def nameIsNamingContext(self, name_list): + return self.objIsNamingContext(self.resolve(name_list)) + + ## + # @if jp + # @brief ネームコンポーネントの部分を返す + # + # 指定された範囲のネームコンポーネントを取得する。 + # 終了位置が指定されていない場合は、最後の要素を除いたネームコンポーネント + # を返す。 + # + # @param self + # @param name_list 検索対象NameComponent + # @param begin 取得範囲開始位置 + # @param end 取得範囲終了位置(デフォルト値:None) + # + # @return NameComponent 取得結果 + # + # @else + # @brief Get subset of given name component + # @endif + + def subName(self, name_list, begin, end=None): + if end is None or end < 0: + end = len(name_list) - 1 + + sub_len = end - (begin - 1) + #objId = "" + #kind = "" + + sub_name = [] + for i in range(sub_len): + sub_name.append(name_list[begin + i]) + + return sub_name + + ## + # @if jp + # @brief ネームコンポーネントの文字列表現を取得する + # + # 指定した範囲のネームコンポーネントの文字列表現を取得する。 + # 文字列表現は、NameComponentの構成が{Nc[0],Nc[1],Nc[2]・・・}の場合、 + # Nc[0]id.Nc[0].kind/Nc[1]id.Nc[1].kind/Nc[2].id/Nc[2].kind・・・ + # という形式で取得できる。 + # 取得した文字列の長さが指定した長さ以上の場合は、 + # 指定した長さで切り捨てられる。 + # + # @param self + # @param name_list 取得対象NameComponent + # @param string_name 取得結果文字列 + # @param slen 取得対象文字列最大値 + # + # @else + # @brief Get string representation of name component + # @endif + + def nameToString(self, name_list, string_name, slen): + for n in name_list: + for id_ in n.id: + if id_ == "/" or id_ == "." or id_ == "\\": + string_name += "\\" + string_name += id_ + + if n.id == "" or n.kind != "": + string_name += "." + + for kind_ in n.kind: + if kind_ == "/" or kind_ == "." or kind_ == "\\": + string_name += "\\" + string_name += kind_ + + string_name += "/" + return string_name + + ## + # @if jp + # @brief ネームコンポーネントの文字列表現時の文字長を取得する + # + # 指定したネームコンポーネントを文字列で表現した場合の長さを取得する。 + # 文字列表現は、NameComponentの構成が{Nc[0],Nc[1],Nc[2]・・・}の場合、 + # Nc[0]id.Nc[0].kind/Nc[1]id.Nc[1].kind/Nc[2].id/Nc[2].kind・・・ + # という形式で取得できる。 + # + # @param self + # @param name_list 取得対象NameComponent + # + # @return 指定したネームコンポーネントの文字列長さ + # + # @else + # @brief Get string length of the name component's string representation + # @endif + + def getNameLength(self, name_list): + slen = 0 + + for n in name_list: + for id_ in n.id: + if id_ == "/" or id_ == "." or id_ == "\\": + slen += 1 + slen += 1 + if n.id == "" or n.kind == "": + slen += 1 + + for kind_ in n.kind: + if kind_ == "/" or kind_ == "." or kind_ == "\\": + slen += 1 + slen += 1 + + slen += 1 + + return slen + + ## + # @if jp + # @brief 文字列の分割 + # + # 文字列を指定したデリミタで分割する。 + # + # @param self + # @param input 分割対象文字列 + # @param delimiter 分割用デリミタ + # @param results 分割結果 + # + # @return 分割した文字列の要素数 + # + # @else + # @brief Split of string + # @endif + + def split(self, input, delimiter, results): + delim_size = len(delimiter) + found_pos = 0 + begin_pos = 0 + pre_pos = 0 + substr_size = 0 + + if input[0:delim_size] == delimiter: + begin_pos = delim_size + pre_pos = delim_size + + while True: + found_pos = str.find(input[begin_pos:], delimiter) + if found_pos == -1: + results.append(input[pre_pos:]) + break + + if found_pos > 0 and input[found_pos + begin_pos - 1] == "\\": + begin_pos += found_pos + delim_size + else: + substr_size = found_pos + (begin_pos - pre_pos) + if substr_size > 0: + results.append(input[pre_pos:(pre_pos + substr_size)]) + begin_pos += found_pos + delim_size + pre_pos = begin_pos + + return len(results) + + ## + # @if jp + # + # @brief 例外情報出力 + # 例外情報を出力する。 + # + # @else + # + # @brief Print exception information + # Print exception information + # @endif + + def __print_exception(self): + if sys.version_info[0:3] >= (2, 4, 0): + print(traceback.format_exc()) + else: + _exc_list = traceback.format_exception(*sys.exc_info()) + _exc_str = "".join(_exc_list) + print(_exc_str) + + return + + ## + # @if jp + # @brief 与えられたパス以下の指定されたkindのバインディングを取得する + # @param self + # @param string_name パス + # @param string_kind kind + # @return バインディングのリスト + # @else + # + # @brief Get all the binding with specified kind under given naming path + # @param self + # @param string_name path + # @param string_kind kind + # @return + # @endif + # BindingList_var listByKind(const char* string_name,const char* + # string_kind) + def listByKind(self, string_name, string_kind): + if not string_name: + return [] + if not string_kind: + return [] + kind = string_kind + tmp_bl = self.listBinding(string_name) + bl = [] + + for b in tmp_bl: + if b.binding_type == CosNaming.nobject: + tmp = b.binding_name[-1].kind + if kind != tmp: + continue + bl.append(b) + + return bl + + ## + # @if jp + # @brief 与えられた Naming パス以下のすべてのバインディングを取得する + # @param self + # @param string_name Namingパス + # @return バインディングのリスト + # @else + # + # @brief Get all the binding under given naming path + # @param self + # @param string_name + # @return + # @endif + # BindingList_var list(const char* string_name) + def listBinding(self, string_name): + if not string_name: + return + obj = self.resolveStr(string_name) + #obj = self.getRootContext() + if CORBA.is_nil(obj): + return [] + #nc = obj._narrow(obj) + # if CORBA.is_nil(nc): + # return [] + max_list_size = 65536 + + bl, bi = obj.list(max_list_size) + + max_remaining = max_list_size - len(bl) + more_bindings = not CORBA.is_nil(bi) + + if more_bindings: + while more_bindings and (max_remaining > 0): + + (tmp_bl, more_bindings) = bi.next_n(max_remaining) + for i in tmp_bl: + bl.append(i) + + max_remaining = max_list_size - len(tmp_bl) + + return bl diff --git a/OpenRTM_aist/CorbaPort.py b/OpenRTM_aist/CorbaPort.py index 9be3cb76..3fad5037 100644 --- a/OpenRTM_aist/CorbaPort.py +++ b/OpenRTM_aist/CorbaPort.py @@ -1,12 +1,12 @@ #!/usr/bin/env python -# -*- coding: euc-jp -*- +# -*- coding: utf-8 -*- ## # \file CorbaPort.py # \brief CorbaPort class # \date $Date: 2007/09/26 $ # \author Noriaki Ando and Shinji Kurihara -# +# # Copyright (C) 2006-2008 # Noriaki Ando # Task-intelligence Research Group, @@ -19,94 +19,92 @@ from omniORB import any - import OpenRTM_aist import RTC - ## # @if jp # @class CorbaPort -# @brief RT ݡͥ CORBA provider/consumer Port +# @brief RT コンポーネント CORBA provider/consumer 用 Port # -# CorbaPort RT ݡͥȤˤơ桼 CORBA ֥ -# ȥӥӥ󥷥塼ޤ󶡤 Port Ǥ롣 +# CorbaPort は RT コンポーネントにおいて、ユーザ定義の CORBA オブジェ +# クトサービスおよびコンシューマを提供する Port 実装である。 # -# RT ݡͥȤϡPort 𤷤ƥ桼 CORBA ӥ -# 󶡤뤳ȤǤ RT Service (Provider) ȸƤ֡ޤ -# ¾ RT ݡͥȤΥӥѤ뤿 CORBA ֥ -# ȤΥץ졼ۥ󶡤뤳ȤǤ RT Service -# Consumer ȸƤ֡ -# CorbaPort Ǥդο Provider Consumer 뤳Ȥ -# Port ƱΤ³ݤб Provider Consumer Ŭڤ -# Ϣդ뤳ȤǤ롣 -# CorbaPort ̾ʲΤ褦Ѥ롣 +# RT コンポーネントは、Port を介してユーザが定義した CORBA サービス +# を提供することができ、これを RT Service (Provider) と呼ぶ。また、 +# 他の RT コンポーネントのサービスを利用するための CORBA オブジェク +# トのプレースホルダを提供することができ、これを RT Service +# Consumer と呼ぶ。 +# CorbaPort は任意の数の Provider および Consumer を管理することがで +# き、Port 同士を接続する際に対応する Provider と Consumer を適切に +# 関連付けることができる。 +# CorbaPort は通常以下のように利用される。 # #
-# RTC::CorbaPort m_port0; // Port 
+# RTC::CorbaPort m_port0; // Port の宣言
 #
-# MyService_impl m_mysvc0; //  Port 󶡤 Serivce Provider
-# RTC::CorbaConsumer m_cons0; //  Port  Consumer
+# MyService_impl m_mysvc0; // この Port が提供する Serivce Provider
+# RTC::CorbaConsumer m_cons0; // この Port の Consumer
 #
-# // Service Provider  Port Ͽ
+# // Service Provider を Port に登録
 # m_port0.registerProvider("MyService0", "Generic", m_mysvc0);
-# // Service Consumer  Port Ͽ
+# // Service Consumer を Port に登録
 # m_port0.registerConsumer("YourService0", "Generic", m_cons0 );
 #
-# // connect Ԥ줿
+# // connect が行われた後
 #
-# m_cons0->your_service_function(); // YourService δؿ򥳡
+# m_cons0->your_service_function(); // YourService の関数をコール
 #
-# // connect 줿 ̤ΥݡͥȤˤ
-# m_cons1->my_service_function(); // MyService δؿ򥳡
+# // connect された 別のコンポーネントにおいて
+# m_cons1->my_service_function(); // MyService の関数をコール
 # 
# -# Τ褦ˡ󶡤 Service Provider registerProvider() -# Ͽ뤳Ȥˤꡢ¾ΥݡͥȤѲǽˤ¾Ѥ -# Service Consumer registerConsumer() Ͽ뤳Ȥˤ¾ -# ΥݡͥȤ Service 򥳥ݡͥѲǽˤ뤳 -# Ǥ롣 -# -# PortInterfaceProfile Port ˽°ץХ⤷ϥ󥷥塼 -# ޥ󥿡եˤĤƤξ򵭽Ҥ뤿ΥץեǤ롣 -# ³Ԥġϡξ˴Ť ConnectorProfile Ŭ -# ³ Port ΤǤդΰĤФư -# ConnectorProfile Ϳ Port::connect() ƤӽФɬפ롣 -# -# ʤPortInterfaceProfile Υ󥹥̾ "#" üʥ󥹥 -# ɽ -# -# PROVIDEDʤץХΥ󥹥̾ "#" ξϡ³ -# ϻǤϥ󥹥󥹤¸ߤ󥷥塼ޤ׵˱ưŪ -# 󥹥󥹤륿פΥץХǤ뤳Ȥɽ -# ơ³ϻǤϥ󥹥̾¸ߤʤ³ -# Υ󥿡եץˤơץХ -# 󥹥󥹤бһҤ ConnectorProfile Ŭꤹ -# ΤȤ롣(̤) -# -# REQUIREDʤ󥷥塼ޤΥ󥹥̾ "#" ξϡ -# Υ󥷥塼ޤʣΥץХ³ǽʥפΥ󥷥塼ޤ -# 뤳Ȥ򼨤(̤) -# -# ʲϡPort֤Υ󥿡ե³뤿 ConnectorProfile -# ޥåԥ󥰤򵭽Ҥ뤿Υ롼򼨤 -# -# Port°륤󥿡եλҤΥեޥåȤʲΤ褦 -# 롣󥿡ե˴ؤץѥƥʲξ -# -# - RTC󥹥̾: rtc_iname -# - ݡ̾: port_name -# - 󥿡ե: if_polarity -# - 󥿡ե̾: if_tname -# - 󥿡ե󥹥̾: if_iname -# -# 󥿡եλҤʲʸ̾ΤǻꤹΤȤ롣 +# このように、提供したい Service Provider を registerProvider() で登 +# 録することにより、他のコンポーネントから利用可能にし、他方、利用し +# たい Service Consumer を registerConsumer() で登録することにより他 +# のコンポーネントの Service をコンポーネント内で利用可能にすること +# ができる。 +# +# PortInterfaceProfile は Port に所属するプロバイダもしくはコンシュー +# マインターフェースについての情報を記述するためのプロファイルである。 +# 接続を行うツール等は、これらの情報に基づき ConnectorProfile を適切 +# に生成し、接続を構成する Port のうち任意の一つに対して引数に +# ConnectorProfile を与えて Port::connect() を呼び出す必要がある。 +# +# なお、PortInterfaceProfile のインスタンス名 "#" は特殊なインスタン +# スを表す。 +# +# PROVIDEDすなわちプロバイダのインスタンス名が "#" の場合は、接続開 +# 始時点ではインスタンスが存在せず、コンシューマの要求に応じて動的に +# インスタンスを生成するタイプのプロバイダであることを表す。したがっ +# て、接続開始時点ではインスタンス名は存在しないが、接続シーケンス中 +# のインターフェースを公開するプロセスにおいて、プロバイダは生成した +# インスタンスに対応した記述子を ConnectorProfile に適正に設定するも +# のとする。(未実装) +# +# REQUIREDすなわちコンシューマのインスタンス名が "#" の場合は、一つ +# のコンシューマが複数のプロバイダと接続可能なタイプのコンシューマで +# あることを示す。(未実装) +# +# 以下は、Port間のインターフェースを接続するために ConnectorProfile に +# マッピングを記述するためのルールを示す。 +# +# Portに付属するインターフェースの指定子のフォーマットを以下のように +# 定める。インターフェースに関するプロパティが以下の場合 +# +# - RTCインスタンス名: rtc_iname +# - ポート名: port_name +# - インターフェース極性: if_polarity +# - インターフェース型名: if_tname +# - インターフェースインスタンス名: if_iname +# +# インターフェースの指定子を以下の文字列名称で指定するものとする。 # # .port.... # -# PROVIDED()ʤץХΥ󥿥եΥץѥƥ -# ξ硢 +# PROVIDED(提供)型すなわちプロバイダのインタフェースのプロパティが以 +# 下の場合、 # # - rtc_iname = MyComp0 # - port_name = myservice @@ -114,12 +112,12 @@ # - if_tname = echo_interface # - if_iname = echo_interface2 # -# 󥿡եҤ +# インターフェース指定子は # # MyComp0.port.myservice.provided.echo_interface.echo_interface2 # -# Τ褦˵Ҥ롣ޤƱͤREQUIRED(׵)ʤ󥷥塼 -# ޤΥ󥿡եΥץѥƥʲξ硢 +# のように記述される。また、同様にREQUIRED(要求)型すなわちコンシュー +# マのインターフェースのプロパティが以下の場合、 # # - rtc_iname = YourComp0 # - port_name = yourservice @@ -127,40 +125,40 @@ # - if_tname = hoge_interface # - if_iname = hoge_interface1 # -# 󥿡եҤϡ -# +# インターフェース指定子は、 +# # YourComp0.port.myservice.required.hoge_interface.hoge_inteface1 # -# Τ褦˵Ҥ뤳ȤǤ롣 -# -# ʤưŪ󥿡եΥ󥹥󥹤Τüʥ -# פΥ󥹥̾һ +# のように記述することができる。 +# +# なお、ここで動的生成インターフェースのインスタンスのための特殊なタ +# イプのインスタンス名記述子 # -# - *: ưŪ󥹥̾һ -# - +: 󥯥󥿥󥹥̾һ +# - *: 動的生成型インスタンス名記述子 +# - +: インクリメンタル生成型インスタンス名記述子 # -# 롣ưŪ󥿡եȤϡ³˥󥹥󥹤 -# 륿פΥ󥿡եǤ롣(̤) +# を定義する。動的生成インターフェースとは、接続時にインスタンスが生 +# 成されるタイプのインターフェースである。(未実装) # -# 󥷥塼ޤ׵᤹ץХ󥿡եһҤưŪ -# 󥹥̾һ "#" ꤵ줿硢ץХ -# 󥹥󥹤1Ŀ롣"#" εһҤˤץ -# ׵᤹ n ĤΥ󥷥塼ޤ¸ߤ硢餫׵ -# (ڥ졼󥳡)1 ĤΥץХˤطۤ -# () +# コンシューマが要求するプロバイダインターフェース記述子に動的生成型 +# インスタンス名記述子 "#" が指定された場合、プロバイダは +# インスタンスを1つ新規に生成する。"#" の記述子によりプロバ +# イダを要求する n 個のコンシューマが存在する場合、これらからの要求 +# (オペレーションコール)を1 つのプロバイダにより処理する関係を構築す +# る(下図)。 # #
 # consumer0 ]---<
 # consumer1 ]---<  O----[ provider0
 # consumer2 ]---<
 # 
-# -# Ф󥷥塼ޤ׵᤹ץХ󥿡եһ -# ˥󥯥󥿥󥹥̾һ "+" -# 줿硢һ "+" οץХΥ󥹥 -# ưŪ롣ʤ"+" εһҤˤץ -# ׵᤹ n ĤΥ󥷥塼ޤ¸ߤ硢n ĤΥץХ -# 줾׵ʲΤ褦ʴطۤ롣 +# +# これに対し、コンシューマが要求するプロバイダインターフェース記述子 +# にインクリメンタル生成型インスタンス名記述子 "+" が指定 +# された場合、記述子 "+" の数だけプロバイダのインスタン +# スが動的に生成される。すなわち、"+" の記述子によりプロバ +# イダを要求する n 個のコンシューマが存在する場合、n 個のプロバイダ +# がそれぞれの要求を処理する以下のような関係が構築される。 # #
 # consumer0 ]---<  O----[ provider0
@@ -169,19 +167,19 @@
 # 
# # -# ³˺ݤơġ ConnectorProfile::properties Ŭڤʥ -# 󥿡եޥåԥ󥰻򵭽Ҥ뤳ȤǡߤΥץХ/ -# 󥷥塼ޥ󥿡եͳ³뤳ȤǤ롣 -# ³˴ؤ RTC ˡۤʤ륤󥹥󥹤Ǥʤ顢ƱΥ -# ̾¸ߤ硢󥿡եһҤΰݾڤǤ -# Τǡˡˤ³ݾڤʤ +# 接続に際して、ツール等から ConnectorProfile::properties に適切なイ +# ンターフェースマッピング指定を記述することで、相互のプロバイダ/コ +# ンシューマインターフェースを自由に接続することができる。ただし、接 +# 続に関わる RTC の中に、異なるインスタンスでありながら、同一のインス +# タンス名が存在する場合、インターフェース記述子の一意性が保証できな +# いので、この方法による接続性は保証されない。 # -# ǥ󥿡եһҤñΤ , -# , ... Ȥ롣ޤConnectorProfile::properties -# NVList key value key: value Τ褦˵ҤΤȤ롣 +# ここでインターフェース記述子を簡単のために , +# , ... とする。また、ConnectorProfile::properties の +# NVListの key と value を key: value のように記述するものとする。 # -# ޡ2ĤΥݡͥȤΥӥݡȤ³ͤ롣 -# 줾ΥݡͥȤΥӥݡȤʲξ硢 +# いま、2つのコンポーネントのサービスポートを接続する場合を考える。 +# それぞれのコンポーネントのサービスポートが以下の場合、 # # - rtc_iname: MyComp0
# port_name: mycomp_service
@@ -213,97 +211,97 @@ # | | # # -# MyComp0 echo0 (ץХ) YourComp0 echo9 (󥷥塼) -# MyComp0 add0 (󥷥塼) YourComp0 add9 (ץХ) -# 򤽤줾Фˤ³ΤȲꤹ롣ξ硢 -# ConnectorProfile ϰʲΤ褦ꤹ롣 -# +# MyComp0 の echo0 (プロバイダ) と YourComp0 の echo9 (コンシューマ)、 +# MyComp0 の add0 (コンシューマ) と YourComp0 の add9 (プロバイダ) +# をそれぞれ対にして接続させるものと仮定する。この場合、 +# ConnectorProfile は以下のように設定する。 +# #
 # ConnectorProfile:
-#   name: ǤդΥͥ̾
-#   connector_id: ʸ
-#   ports[]: mycomp_service λ, yourcomp_service λ
+#   name: 任意のコネクタ名
+#   connector_id: 空文字
+#   ports[]: mycomp_service の参照, yourcomp_service の参照
 #   properties:
 #     : 
 #     : 
 # 
# -# 줾 -# +# ただし、それぞれ +# #
-#   MyComp0.port.mycomp_service.required.add.add0
-#   YourComp0.port.yourcomp_service.provided.add.add9
-#   MyComp0.port.mycomp_service.provided.echo.echo0
-#   YourComp0.port.yourcomp_service.required.echo.echo9
+#  は MyComp0.port.mycomp_service.required.add.add0
+#  は YourComp0.port.yourcomp_service.provided.add.add9
+#  は MyComp0.port.mycomp_service.provided.echo.echo0
+#  は YourComp0.port.yourcomp_service.required.echo.echo9
 # 
# -# Ǥ롣³ץˤơƥݡȤΥץХӥ󥷥塼 -# ޤϡ줾ʲκȤCorbaPort::publishInterfaces(), -# CorbaPort::subscribeInterfaces() ۴ؿˤƹԤ -# -# ץХϡpublishInterfaces() ؿˤơʬΥ󥿡ե -# һҤ򥭡ȤͤIORʸɽΤ -# ConnectorProfile::properties ꤹ롣ȤơΥ󥿡 -# եһҤϺԤȤƤ륳ͥˤƤϰդǤ뤿ᡢ -# Ʊ1Ĥ¸ߤƤϤʤ -# -# [ʬεҤ̤εǽ] ʤưŪ󥿡եˤ -# Ƥϡʲμ³˽뤳ȤȤʤ롣publishInterface() -# ؿˤơưŪ󥹥̾һ "*" ޤϡ -# 󥯥󥿥󥹥̾һ "+" ¸ߤ -# 뤫ɤ롣ưŪ󥹥̾һ "*" -# ¸ߤ硢ץХΥ󥹥󥹤1Υ󥿡 -# եҤ key ˡIORʸ value ꤹȤȤˡư -# Ū󥹥̾һ "*" value ˴ޤह٤Ƥ -# value Υ󥿡եҤ򡢤󥿡ե -# Ҥ֤롣 -# -# 󥯥󥿥󥹥̾һ"+" ¸ߤ -# 硢󥹥̾һҤοץХΥ󥹥󥹤 -# 줾Υ󥿡եҤkey ˡIORʸ value -# ꤹȤȤˡ󥯥󥿥󥹥̾һ -# "+" value ޤह٤Ƥ value Υ󥿡ե -# ҤФƽˡ줾Υ󥿡եҤ -# ֤롣 -# -# ץХ subscribeInterfaces() ǤäϹԤʤ -# -# 󥷥塼ޤϡ publishInterfaces() ˤƤäԤʤ -# -# subscribeInterfaces() ǤϡʬεһҤ key Ȥ -# key-value ڥ ¸ߤ뤫ɤĴ١⤷¸ߤС value -# ꤵ줿ץХΥ󥿡եҤǻꤵ뻲Ȥ -# ConnectorProfile::properties õ򥳥󥷥塼ޤ -# ³Ȥꤹ롣ʤտŪ˥󥷥塼ޤ˥ץХλ -# ꤷʤϡͽʸ "nil" ޤ "null" ꤹ -# Ȥ롣 -# -# 󥷥塼ޤϡ⤷ʬεһҤ¸ߤʤ硢ޤϥץХ -# λȤ Connector::properties ¸ߤʤ硢󥷥塼ޤϡ -# ʬΥ󥹥̾ӷ̾ƱΥץХõλȤ -# ʬȤꤹ롣ϡOpenRTM-aist-0.4 Ȥθߴݻ -# Υ롼Ǥꡢ1.0ʹߤǤϿ侩ʤ -# -# ץХХ󥷥塼ޤбϰаǤɬפϤʤץХ -# 1 Фơ󥷥塼 nޤϥ󥷥塼 1 ФƥץХ -# n Υ롣ץХ 1 Фơ󥷥塼 n -# ǤϡץХλҤʣΥ󥷥塼ޤФơ -# 嵭ˡǻꤵ뤳Ȥˤꡢ¸롣󥷥塼 -# 1 ФƥץХ n ΥǤϡ󥷥塼޻Ҥ key -# ơʣΥץХλҤ޶ڤ󤵤Ȥʤ -# ΤȤ롣 -# -# ʤ󥿡եбطθ̩ꤹ륪ץȤơ -# ʲΥץꤹ뤳ȤǤ롣 -# -# port.connection.strictness: strict, best_effort -# -# strict: ٤ƤΥ󥷥塼ޤ˻ꤷȤ¸ߤĥʥ -# ˤ󥷥塼ޤŬڤ˥åȤǤˤΤ Port -# ֤³Ω롣 -# -# best_effort: ʥ˼ԤǤ⡢顼֤Ȥ -# Port ֤³Ω롣 +# である。接続プロセスにおいて、各ポートのプロバイダおよびコンシュー +# マは、それぞれ以下の作業を、CorbaPort::publishInterfaces(), +# CorbaPort::subscribeInterfaces() 仮想関数において行う。 +# +# プロバイダは、publishInterfaces() 関数において、自分のインターフェー +# ス記述子をキーとし、値にIORの文字列表記したものを +# ConnectorProfile::properties に設定する。前提として、このインター +# フェース記述子は今行おうとしているコネクタにおいては一意であるため、 +# 同じキーは1つしか存在してはいけない。 +# +# [この部分の記述は未実装の機能] なお、動的生成インターフェースにつ +# いては、以下の手続きに従い処理することとなる。publishInterface() +# 関数において、動的生成インスタンス名記述子 "*" または、 +# インクリメンタル生成型インスタンス名記述子 "+" が存在す +# るかどうかを走査する。動的生成インスタンス名記述子 "*" +# が存在する場合、プロバイダのインスタンスを1つ生成し、そのインター +# フェース指定子を key に、IOR文字列を value に設定するとともに、動 +# 的生成インスタンス名記述子 "*" を value に含むすべての +# value 上のインターフェース指定子を、ここで生成したインターフェース +# 指定子に置き換える。 +# +# インクリメンタル生成型インスタンス名記述子"+" が存在す +# る場合、インスタンス名記述子の数だけプロバイダのインスタンスを生成 +# し、それぞれのインターフェース指定子をkey に、IOR文字列を value に +# 設定するとともに、インクリメンタル生成型インスタンス名記述子 +# "+" を value 含むすべての value 上のインターフェース指 +# 定子に対して順に、ここで生成したそれぞれのインターフェース指定子に +# 置き換える。 +# +# プロバイダは subscribeInterfaces() では特に操作は行わない。 +# +# コンシューマは、 publishInterfaces() においては特に操作を行わない。 +# +# 一方、 subscribeInterfaces() では、自分の記述子を key とする +# key-value ペア が存在するかどうか調べ、もし存在すれば、その value +# に設定されたプロバイダのインターフェース指定子で指定される参照を、 +# さらに ConnectorProfile::properties から探し、それをコンシューマの +# 接続先として設定する。なお、意図的にコンシューマにプロバイダの参照 +# を設定しない場合は、予約文字列 "nil" または "null" を設定するもの +# とする。 +# +# コンシューマは、もし自分の記述子が存在しない場合、またはプロバイダ +# の参照が Connector::properties に存在しない場合、コンシューマは、 +# 自分のインスタンス名および型名と同一のプロバイダを探し、その参照を +# 自分自身に設定する。これは、OpenRTM-aist-0.4 との互換性を保持する +# ためのルールであり、1.0以降では推奨されない。 +# +# プロバイダ対コンシューマの対応は一対一である必要はなく、プロバイダ +# 1 に対して、コンシューマ n、またはコンシューマ 1 に対してプロバイ +# ダ n のケースも許される。プロバイダ 1 に対して、コンシューマ n の +# ケースでは、あるプロバイダの指定子が、複数のコンシューマに対して、 +# 上記の方法で指定されることにより、実現される。一方、コンシューマ +# 1 に対してプロバイダ n のケースでは、コンシューマ指定子の key に対 +# して、複数のプロバイダの指定子がカンマ区切りで列挙される形式となる +# ものとする。 +# +# なお、インターフェースの対応関係の厳密さを指定するオプションとして、 +# 以下のオプションを指定することができる。 +# +# port.connection.strictness: strict, best_effort +# +# strict: すべてのコンシューマに指定した参照が存在し、かつナローイン +# グにも成功しコンシューマに適切にセットできた場合にのみ Port +# 間の接続を確立する。 +# +# best_effort: ナローイング等に失敗した場合でも、エラーを返すことな +# く Port 間の接続を確立する。 # # @since 0.4.0 # @@ -369,7 +367,7 @@ # If REQUIRED interface name that is Consumer interface name is # "*", it shows that one Consumer interface is able to connect with # multiple Provider interfaces. (This feature is not implemented.) -# +# # The following describes the rules that specify interface # connection between ports. # @@ -407,7 +405,7 @@ # - if_tname = hoge_interface # - if_iname = hoge_interface1 # -# interface descriptor is as follows. +# interface descriptor is as follows. # # YourComp0.port.myservice.required.hoge_interface.hoge_inteface1 # @@ -429,7 +427,7 @@ # consumer1 ]---< O----[ provider0 # consumer2 ]---< # -# +# # On the other hand, when incremental generated type instance name # descriptor "+" is specified as the provider interface # descriptor whom consumers demand, provider's instances are @@ -461,7 +459,7 @@ # Now the case where the service ports of two components are # connected is considered. When the service port of each component # is the following, -# +# # - rtc_iname: MyComp0
# port_name: mycomp_service
# interfaces: @@ -492,7 +490,7 @@ # ~T~ ~T~ # | | # -# +# # # # Assume that connection between echo0 (provider) of MyComp0 @@ -500,7 +498,7 @@ # (consumer) of MyComp0 and add0 (provider) of YourComp0 is # established. In this case, ConnectorProfile is set up as # follows. -# +# #
 # ConnectorProfile:
 #   name: any connector name
@@ -512,7 +510,7 @@
 # 
# # Please note that , , and are the following. -# +# #
 #  is MyComp0.port.mycomp_service.required.add.add0
 #  is YourComp0.port.yourcomp_service.provided.add.add9
@@ -524,7 +522,7 @@
 # port carries out the following process respectively in the
 # virtual functions such as CorbaPort::publishInterfaces() and
 # CorbaPort::subscribeInerfaces().
-# 
+#
 # A provider sets its IOR string as a value and its interface
 # descriptor as a key in the ConnectorProfile::properties in a
 # publishInterfaces() function. Since this interface descriptor's
@@ -591,7 +589,7 @@
 #
 # strict: The connection is established, if only all the specified
 #         consumers are set appropriate references and narrowed
-#         successfully.  
+#         successfully.
 #
 # best_effort: The connection is established without any errors,
 #         even if appropriate reference does not exist or reference
@@ -602,957 +600,960 @@
 # @endif
 #
 class CorbaPort(OpenRTM_aist.PortBase):
-  """
-  """
-
-  ##
-  # @if jp
-  # @brief 󥹥ȥ饯
-  #
-  # @param self
-  # @param name Port ̾
-  #
-  # @else
-  #
-  # @brief Constructor
-  #
-  # @param name The name of Port 
-  #
-  # @endif
-  def __init__(self, name):
-    OpenRTM_aist.PortBase.__init__(self, name)
-    self.addProperty("port.port_type", "CorbaPort")
-    self._properties = OpenRTM_aist.Properties()
-    self._providers = []
-    self._consumers = []
-    return
-
-
-  def __del__(self, PortBase=OpenRTM_aist.PortBase):
-    PortBase.__del__(self)
-
-
-  ##
-  # @if jp
-  # @brief ץѥƥν
-  #
-  # OutPortΥץѥƥ롣ΥݡȤؤ³ꤹ
-  # ץѥƥ "connection_limit" ޤޤ졢ŬڤʿͤꤵƤ
-  # 硢³ȤƤοͤꤵ롣ץѥƥꤵ
-  # Ƥʤ硢⤷ŬڤͤꤵƤʤˤϡ
-  # ³̵¤Ȥʤ롣
-  #
-  # @param prop CorbaPort Υץѥƥ
-  #
-  # @else
-  #
-  # @brief Initializing properties
-  #
-  # This operation initializes outport's properties. If a property
-  # "connection_limit" is set and appropriate value is set to this
-  # property value, the number of maximum connection is set as this
-  # value. If the property does not exist or invalid value is set
-  # to this property, the maximum number of connection will be set
-  # unlimited.
-  #
-  # @param prop properties of the CorbaPort
-  #
-  # @endif
-  #
-  # void init(coil::Properties& prop);
-  def init(self, prop):
-    self._rtcout.RTC_TRACE("init()")
-
-    self._properties.mergeProperties(prop)
-
-    num = [-1]
-    if not OpenRTM_aist.stringTo([num], 
-                                 self._properties.getProperty("connection_limit","-1")):
-      self._rtcout.RTC_ERROR("invalid connection_limit value: %s", 
-                             self._properties.getProperty("connection_limit"))
-
-    self.setConnectionLimit(num[0])
-
-
-  ##
-  # @if jp
-  #
-  # @brief Provider Ͽ
-  #
-  #  Port ˤ󶡤ХȤ򤳤 Port ФϿ
-  # 롣ХȤϡͿ instance_name, type_name 
-  # ХȼȤΥ󥹥̾ӥ̾ȤơХȤ
-  # Ϣդ롣δؿˤꡢХȤ CorbaPort 
-  # ȤȤˡPortInterfaceProfile RTC::PROVIDED 󥿡
-  # եȤϿ롣
-  #
-  # @param instance_name ХȤΥ󥹥̾
-  # @param type_name ХȤΥ̾
-  # @param provider CORBA Х
-  #
-  # @return Ʊ̾ instance_name ϿƤ false ֤
-  #
-  # @else
-  #
-  # @brief Register the provider
-  #
-  # This operation registers a servant, which is provided in this
-  # Port, to the Port. The servant is associated with
-  # "instance_name" and "type_name" as the instance name of the
-  # servant and as the type name of the servant. A given servant
-  # will be stored in the CorbaPort, and this is registered as
-  # RTC::PROVIDED interface into the PortInterfaceProfile.
-  #
-  # @param instance_name Instance name of servant
-  # @param type_name Type name of the servant
-  # @param provider CORBA servant
-  #
-  # @return Return false if the same name of instance_name is already 
-  #         registered.
-  #
-  # @endif
-  #
-  # bool registerProvider(const char* instance_name, const char* type_name,
-  #                       PortableServer::RefCountServantBase& provider);
-  def registerProvider(self, instance_name, type_name, provider):
-    self._rtcout.RTC_TRACE("registerProvider(instance=%s, type_name=%s)",
-                           (instance_name, type_name))
-
-    try:
-      self._providers.append(self.CorbaProviderHolder(type_name,
-                                                      instance_name,
-                                                      provider))
-    except:
-      self._rtcout.RTC_ERROR("appending provider interface failed")
-      self._rtcout.RTC_ERROR(OpenRTM_aist.Logger.print_exception())
-      return False
-
-    
-    if not self.appendInterface(instance_name, type_name, RTC.PROVIDED):
-      return False
-
-    return True
-
-
-  ##
-  # @if jp
-  #
-  # @brief Consumer Ͽ
-  #
-  #  Port ׵᤹륵ӥΥץ졼ۥǤ륳󥷥塼
-  # (Consumer) Ͽ롣Consumer Ϣդ륵ӥΥ
-  # ̾ӥ̾Ȥơ instance_name, type_name 
-  #  Consumer ȤͿ뤳ȤˤꡢǤ餬Ϣդ
-  # 롣Port ֤³ (connect)  ˤϡsubscribeInterfaces() ǽ
-  # ٤Ƥ롼˴ŤProvider Interface λȤưŪ
-  # Consumer ˥åȤ롣
-  #
-  # @param instance_name Consumer ׵᤹륵ӥΥ󥹥̾
-  # @param type_name Consumer ׵᤹륵ӥΥ̾
-  # @param consumer CORBA ӥ󥷥塼
-  #
-  # @return Ʊ̾ instance_name ϿƤ false ֤
-  #
-  # @else
-  #
-  # @brief Register the consumer
-  #
-  # This operation registers a consumer, which is a service
-  # placeholder this port requires. These are associated internally
-  # with specified instance_name, type_name and Consumer itself to
-  # the argument as service's instance name and its type name
-  # associated with Consumer.  The service Provider interface'
-  # references will be set automatically to the Consumer Interface
-  # object when connections are established, according to the rules
-  # that are described at the subscribeInterfaces() function's
-  # documentation.
-  #
-  # @param instance_name Instance name of the service Consumer requires
-  # @param type_name Type name of the service Consumer requires
-  # @param consumer CORBA service consumer
-  #
-  # @return False would be returned if the same instance_name was registered
-  #
-  # @endif
-  #
-  # bool registerConsumer(const char* instance_name, const char* type_name,
-  #                       CorbaConsumerBase& consumer);
-  def registerConsumer(self, instance_name, type_name, consumer):
-    self._rtcout.RTC_TRACE("registerConsumer()")
-
-    if not self.appendInterface(instance_name, type_name, RTC.REQUIRED):
-      return False
-    
-    self._consumers.append(self.CorbaConsumerHolder(type_name,
-                                                    instance_name,
-                                                    consumer,
-                                                    self))
-    return True
-
-
-  ##
-  # @if jp
-  #
-  # @brief Port ƤΥ󥿡ե activates 
-  #
-  # Port ϿƤƤΥ󥿡ե activate 롣
-  #
-  # @else
-  #
-  # @brief Activate all Port interfaces
-  #
-  # This operation activate all interfaces that is registered in the
-  # ports.
-  #
-  # @endif
-  #
-  # void CorbaPort::activateInterfaces()
-  def activateInterfaces(self):
-    for provider in self._providers:
-      provider.activate()
-
-    return
-
-
-  ##
-  # @if jp
-  #
-  # @brief Ƥ Port Υ󥿡ե deactivates 
-  #
-  # Port ϿƤƤΥ󥿡ե deactivate 롣
-  #
-  # @else
-  #
-  # @brief Deactivate all Port interfaces
-  #
-  # This operation deactivate all interfaces that is registered in the
-  # ports.
-  #
-  # @endif
-  #
-  # void CorbaPort::deactivateInterfaces()
-  def deactivateInterfaces(self):
-    for provider in self._providers:
-      provider.deactivate()
-
-    return
-
-
-
-  ##
-  # @if jp
-  #
-  # @brief Provider Interface 
-  #
-  #  Port ͭ Provider 󥿡ե˴ؤ
-  # ConnectorProfile::properties ¾ Port ФƸ롣
-  # RTCΥ󥹥̾ξ󤬰ʲ̤ǤȤơ
-  #
-  # - RTC󥹥̾:              rtc_iname
-  # - ݡ̾:                       port_name
-  # - 󥿡ե:           if_polarity
-  # - 󥿡ե̾:           if_tname
-  # - 󥿡ե󥹥̾: if_iname
-  #
-  # NameValue  ConnectorProfile::properties  name  value Ȥ
-  # ʲΤΤǼ롣
-  #
-  # - name
-  #   .port..provided..
-  # - value
-  #   Provider 󥿡ե IOR ʸ 
-  # 
-  # ʤСȤθߴΤʲɽ NameValue Ʊ
-  # ˳Ǽ뤬ΥСǤϺǽ롣
-  # 
-  # - name
-  #   port..
-  # - value
-  #   Provider 󥿡ե IOR ʸ
-  #
-  # ͤ ConnectorProfile::properties ˳Ǽ졢¾ΥݡȤФ
-  # ã롣¾ Port ǤΥ󥿡եѤ Consumer 
-  # ¸ߤСConnectorProfile 餳Υ饪֥ȥե󥹤
-  # 餫ηǻѤ롣
-  #
-  # @param connector_profile ͥץե
-  # @return ReturnCode_t Υ꥿󥳡
-  #
-  # @else
-  #
-  # @brief Publish information about interfaces
-  #
-  # This operation publishes Provider interfaces information, which
-  # is owned by this port, to the other Ports via
-  # ConnectorProfile::properties.
-  # Now it is assumed RTC instance name and other information is as follows,
-  #
-  # - RTC instance name:              rtc_iname
-  # - Port name:                      port_name
-  # - Interface polarity:             if_polarity
-  # - Interface type name:            if_tname
-  # - Interface instance name:        if_iname
-  #
-  # the following values are stored as the "name" and the "value"
-  # of the NameValue typee element in ConnectorProfile::properties.
-  #
-  # - name
-  #   .port..provided..
-  # - value
-  #   IOR string value of interface reference
-  # 
-  # In addition, although the following NameValue values are also
-  # stored for the backward compatibility, this will be deleted in
-  # the future version.
-  #
-  # - name
-  #   port..
-  # - value
-  #   IOR string value of interface reference
-  #
-  # These values are stored in the ConnectorProfile::properties and
-  # are propagated to the other Ports. If the Consumer interface
-  # exists that requires this Provider interface, it will retrieve
-  # reference from the ConnectorProfile and utilize it.
-  #
-  # @param connector_profile Connector profile
-  # @return The return code of ReturnCode_t type
-  #
-  # @endif
-  #
-  # virtual ReturnCode_t
-  #    publishInterfaces(ConnectorProfile& connector_profile);
-  def publishInterfaces(self, connector_profile):
-    self._rtcout.RTC_TRACE("publishInterfaces()")
-
-    returnvalue = self._publishInterfaces()
-
-    if returnvalue != RTC.RTC_OK:
-      return returnvalue
-
-    properties = []
-    for provider in self._providers:
-      #------------------------------------------------------------
-      # new version descriptor
-      # .port..provided..
-      newdesc = self._profile.name[:len(self._ownerInstanceName)] + \
-          ".port" +  self._profile.name[len(self._ownerInstanceName):]
-      newdesc += ".provided." + provider.descriptor()
-
-      properties.append(OpenRTM_aist.NVUtil.newNV(newdesc, provider.ior()))
-
-      #------------------------------------------------------------
-      # old version descriptor
-      # port..
-      olddesc = "port." + provider.descriptor()
-      properties.append(OpenRTM_aist.NVUtil.newNV(olddesc, provider.ior()))
-
-    OpenRTM_aist.CORBA_SeqUtil.push_back_list(connector_profile.properties, properties)
-    
-    return RTC.RTC_OK
-
-
-  ##
-  # @if jp
-  #
-  # @brief Provider Interface 
-  #
-  #  Portͭ Consumer Interface Ŭ礹 Provider
-  # Interface ˴ؤConnectorProfile::properties Ф
-  # Consumer Interface ˥֥ȻȤ򥻥åȤ롣
-  #
-  # RTC Υ󥹥̾ Consumer Interface ξ󤬰ʲΤ
-  # ǤȲꤹȡ
-  #
-  # - RTC󥹥̾:              rtc_iname
-  # - ݡ̾:                       port_name
-  # - 󥿡ե:           if_polarity
-  # - 󥿡ե̾:           if_tname
-  # - 󥿡ե󥹥̾: if_iname
-  #
-  #  Consumer Interface ɽ󥿡եҤϰʲΤ褦
-  # ɽ롣
-  #
-  # .port..required..
-  #
-  # δؿϡޤ ConnectorProfile::properties ˾嵭󥿡
-  # եҤ򥭡ȤƳǼƤ Provider Interface 
-  # ҤõФˡ Provider Interface Ҥ򥭡Ȥ
-  # ǼƤ Provider Interface λȤɽ IOR ʸ
-  # Consumer Interface ˥åȤ롣
-  #
-  # ˡProvider  prov(n), λȤIOR(n)  Consumer
-  # cons(n) Τ褦˵Ҥ餹٤ƤΥ󥿡եηƱ
-  # ǤꡢConnectorProfile ˰ʲͤꤵƤȤ롣
-  #
-  # 
-  # ConnectorProfile::properties =
-  # {
-  #   prov0: IOR0,
-  #   prov1: IOR1,
-  #   prov2: IOR2,
-  #   cons0: prov2,
-  #   cons1: prov1,
-  #   cons2: prov0
-  # }
-  # 
- # - # ΤȤcons(0..2) ˤϤ줾졢ȤʲΤ褦˥åȤ롣 - # - #
-  #   cons0 = IOR2
-  #   cons1 = IOR1
-  #   cons2 = IOR0
-  # 
- # - # ʤСȤθߴΤᡢ - # ConnectorProfile::properties Consumer Interface 򥭡Ȥ - # ͤåȤƤʤǤ⡢Υ롼뤬ŬѤ롣 - # - # Consumer Interface - # - #
-  #  PortInterfaceProfile
-  #  {
-  #    instance_name = "PA10_0";
-  #    type_name     = "Manipulator";
-  #    polarity      = REQUIRED;
-  #  }
-  # 
- # - # ȤϿƤС¾ Port - # - #
-  #  PortInterfaceProfile
-  #  {
-  #    instance_name = "PA10_0";
-  #    type_name     = "Manipulator";
-  #    polarity      = PROVIDED;
-  #  }
-  # 
- # - # ȤϿƤ Serivce Provider Υ֥ȻȤõ - # Consumer ˥åȤ롣ºݤˤϡConnectorProfile::properties - # - #
-  # NameValue = { "port.Manipulator.PA10_0":  }
-  # 
-  #
-  # ȤϿƤ NameValue õΥ֥ȻȤ
-  # Consumer ˥åȤ롣
-  #
-  # @param connector_profile ͥץե
-  # @return ReturnCode_t Υ꥿󥳡
-  #
-  # @else
-  #
-  # @brief Subscribe to interface
-  #
-  # Retrieve information associated with Provider matches Consumer
-  # owned by this port and set the object reference to Consumer.
-  #
-  # Now, Consumer is registered as the following:
-  # 
-  #  PortInterfaceProfile
-  #  {
-  #    instance_name = "PA10_0";
-  #    type_name     = "Manipulator";
-  #    polarity      = REQUIRED;
-  #  }
-  # 
- # Find the object reference of Serivce Provider that is registered as - # the following of other ports: - #
-  #  PortInterfaceProfile
-  #  {
-  #    instance_name = "PA10_0";
-  #    type_name     = "Manipulator";
-  #    polarity      = PROVIDED;
-  #  }
-  # 
- # and set to Consumer. - # In fact, find NameValue that is registered as the following to - # ConnectorProfile::properties: - #
-  # NameValue = { "port.Manipulator.PA10_0":  }
-  # 
-  # and set the object reference to Consumer.
-  #
-  # @param connector_profile Connector profile
-  #
-  # @return The return code of ReturnCode_t type
-  #
-  # @endif
-  #
-  # virtual ReturnCode_t
-  #   subscribeInterfaces(const ConnectorProfile& connector_profile);
-  def subscribeInterfaces(self, connector_profile):
-    self._rtcout.RTC_TRACE("subscribeInterfaces()")
-    nv = connector_profile.properties
-
-    strict = False # default is "best_effort"
-    index = OpenRTM_aist.NVUtil.find_index(nv, "port.connection.strictness")
-    if index >=  0:
-      strictness = str(any.from_any(nv[index].value, keep_structs=True))
-      if "best_effort" == strictness:
-        strict = False
-      elif "strict" == strictness:
-        strict = True
-
-      self._rtcout.RTC_DEBUG("Connetion strictness is: %s",strictness)
-
-    for consumer in self._consumers:
-      ior = []
-      if self.findProvider(nv, consumer, ior) and len(ior) > 0:
-        self.setObject(ior[0], consumer)
-        continue
-
-      ior = []
-      if self.findProviderOld(nv, consumer, ior) and len(ior) > 0:
-        self.setObject(ior[0], consumer)
-        continue
-
-      # never come here without error
-      # if strict connection option is set, error is returned.
-      if strict:
-        self._rtcout.RTC_ERROR("subscribeInterfaces() failed.")
-        return RTC.RTC_ERROR
-
-    self._rtcout.RTC_TRACE("subscribeInterfaces() successfully finished.")
-
-    return RTC.RTC_OK
-
-
-  ##
-  # @if jp
-  #
-  # @brief Interface ؤ³
-  #
-  # Ϳ줿 ConnectorProfile ˴Ϣ Consumer ˥åȤ줿
-  # ٤Ƥ Object ³롣
-  #
-  # @param self
-  # @param connector_profile ͥץե
-  #
-  # @else
-  #
-  # @brief Unsubscribe interfaces
-  #
-  # Release all Objects that was set in Consumer associated with the given 
-  # ConnectorProfile.
-  # 
-  # @param connector_profile Connector profile
-  #
-  # @endif
-  #  virtual void
-  #    unsubscribeInterfaces(const ConnectorProfile& connector_profile);
-  def unsubscribeInterfaces(self, connector_profile):
-    self._rtcout.RTC_TRACE("unsubscribeInterfaces()")
-    nv = connector_profile.properties
-
-    for consumer in self._consumers:
-      ior = []
-      if self.findProvider(nv, consumer, ior) and len(ior) > 0:
-        self._rtcout.RTC_DEBUG("Correspoinding consumer found.")
-        self.releaseObject(ior[0], consumer)
-        continue
-
-      ior = []
-      if self.findProviderOld(nv, consumer, ior) and len(ior) > 0:
-        self._rtcout.RTC_DEBUG("Correspoinding consumer found.")
-        self.releaseObject(ior[0], consumer)
-        continue
-
-    return
-
-
-  ##
-  # @if jp
-  # @brief Consumer ˹פ Provider  NVList 椫鸫Ĥ
-  #
-  # NVList 椫 CorbaConsumerHolder ݻƤ Consumer ˹
-  # פ륭 Provider 򸫤ĤIOR Фʥ󥰤
-  # Consumer ˥åȤ롣б륭¸ߤʤIOR Ĥ
-  # ʤʥ󥰤˼Ԥ硢false ֤
-  #
-  # @param nv Provider ޤޤƤ ConnectorProfile::properties  NVList
-  # @param cons Provider б Consumer Υۥ
-  # 
-  # @retrun bool Consumer б Provider Ĥʤ false
-  #
-  # @else
-  # @brief Find out a provider corresponding to the consumer from NVList
-  #
-  # This function finds out a Provider with the key that is matched
-  # with Cosumer's name in the CorbaConsumerHolder, extracts IOR
-  # and performs narrowing into the Consumer and set it to the
-  # Consumer. False is returned when there is no corresponding key
-  # and IOR and the narrowing failed.
-  #  
-  # @param nv NVlist of ConnectorProfile::properties that includes Provider
-  # @param cons a Consumer holder to be matched with a Provider
-  # 
-  # @return bool false is returned if there is no provider for the consumer
-  #
-  # @endif
-  #
-  # virtual bool findProvider(const NVList& nv, 
-  #                           CorbaConsumerHolder& cons,
-  #                           std::string& iorstr);
-  def findProvider(self, nv, cons, iorstr):
-    # new consumer interface descriptor
-    newdesc = self._profile.name[:len(self._ownerInstanceName)] + \
-        ".port" +  self._profile.name[len(self._ownerInstanceName):]
-    newdesc += ".required." + cons.descriptor()
-
-    # find a NameValue of the consumer
-    cons_index = OpenRTM_aist.NVUtil.find_index(nv, newdesc)
-    if cons_index < 0:
-      return False
-
-    provider = str(any.from_any(nv[cons_index].value, keep_structs=True))
-    if not provider:
-      self._rtcout.RTC_WARN("Cannot extract Provider interface descriptor")
-      return False
-
-    # find a NameValue of the provider
-    prov_index = OpenRTM_aist.NVUtil.find_index(nv, provider)
-    if prov_index < 0:
-      return False
-
-    ior_ = str(any.from_any(nv[prov_index].value, keep_structs=True))
-    if not ior_:
-      self._rtcout.RTC_WARN("Cannot extract Provider IOR string")
-      return False
- 
-    if isinstance(iorstr, list):
-      iorstr.append(ior_)
-
-    self._rtcout.RTC_ERROR("interface matched with new descriptor: %s", newdesc)
-
-    return True
-
-
-  ##
-  # @if jp
-  # @brief Consumer ˹פ Provider  NVList 椫鸫Ĥ
-  #
-  # δؿϡŤСθߴΤδؿǤ롣
-  #
-  # NVList 椫 CorbaConsumerHolder ݻƤ Consumer ˹
-  # פ륭 Provider 򸫤Ĥ롣б륭¸ߤʤ
-  # IOR Ĥʤ硢false ֤
-  #  
-  # @param nv Provider ޤޤƤ ConnectorProfile::properties  NVList
-  # @param cons Provider б Consumer Υۥ
-  # @param iorstr ĤäIORʸǼѿ
-  # 
-  # @retrun bool Consumer б Provider Ĥʤ false
-  #
-  # @else
-  # @brief Find out a provider corresponding to the consumer from NVList
-  #
-  # This function is for the old version's compatibility.
-  #
-  # This function finds out a Provider with the key that is matched
-  # with Cosumer's name in the CorbaConsumerHolder and extracts
-  # IOR.  False is returned when there is no corresponding key and
-  # IOR.
-  #  
-  # @param nv NVlist of ConnectorProfile::properties that includes Provider
-  # @param cons a Consumer holder to be matched with a Provider
-  # @param iorstr variable which is set IOR string
-  # 
-  # @return bool false is returned if there is no provider for the consumer
-  #
-  # @endif
-  #
-  # virtual bool findProviderOld(const NVList&nv,
-  #                              CorbaConsumerHolder& cons,
-  #                              std::string& iorstr);
-  def findProviderOld(self, nv, cons, iorstr):
-    # old consumer interface descriptor
-    olddesc = "port." + cons.descriptor()
-
-    # find a NameValue of the provider same as olddesc
-    index = OpenRTM_aist.NVUtil.find_index(nv, olddesc)
-    if index < 0:
-      return False
-
-    ior_ = str(any.from_any(nv[index].value, keep_structs=True))
-    if not ior_:
-      self._rtcout.RTC_WARN("Cannot extract Provider IOR string")
-      return False
-
-    if isinstance(iorstr, list):
-      iorstr.append(ior_)
-
-    self._rtcout.RTC_ERROR("interface matched with old descriptor: %s", olddesc)
-
-    return True
-
-
-  ##
-  # @if jp
-  # @brief Consumer  IOR 򥻥åȤ
-  #
-  # IOR ʥ󥰤Consumer ˥åȤ롣ʥ󥰤˼
-  # 硢false ֤IORʸ󤬡nullޤnilξ硢
-  # ֥Ȥ˲⥻åȤ true ֤
-  #
-  # @param ior åȤ IOR ʸ
-  # @param cons Consumer Υۥ
-  # 
-  # @retrun bool Consumer ؤΥʥ󥰤˼Ԥ false
-  #
-  # @else
-  # @brief Setting IOR to Consumer
-  #
-  # This function performs narrowing into the Consumer and set it to the
-  # Consumer. False is returned when the narrowing failed. But, if IOR
-  # string is "null" or "nil", this function returns true.
-  #  
-  # @param ior IOR string
-  # @param cons Consumer holder
-  # 
-  # @retrun bool false if narrowing failed.
-  #
-  # @endif
-  #
-  # bool setObject(const std::string& ior, CorbaConsumerHolder& cons);
-  def setObject(self, ior, cons):
-    # if ior string is "null" or "nil", ignore it.
-    if "null" == ior:
-      return True
-
-    if "nil"  == ior:
-      return True
-
-    # IOR should be started by "IOR:"
-    if "IOR:" != ior[:4]:
-      return False
-
-    # set IOR to the consumer
-    if not cons.setObject(ior):
-      self._rtcout.RTC_ERROR("Cannot narrow reference")
-      return False
-
-    self._rtcout.RTC_TRACE("setObject() done")
-    return True
-
-  ##
-  # @if jp
-  # @brief Consumer Υ֥Ȥ꡼
-  #
-  # Consumer ˥åȤ줿Ȥ꡼롣ConsumerIORͿ
-  # 줿IORʸȰۤʤ硢false֤
-  #
-  # @param ior åȤ IOR ʸ
-  # @param cons Consumer Υۥ
-  # 
-  # @retrun ConsumerIORͿ줿IORʸȰۤʤ硢false֤
-  #
-  # @else
-  # @brief Releasing Consumer Object
-  #
-  # This function releases object reference of Consumer. If the
-  # given IOR string is different from Consumer's IOR string, it
-  # returns false.
-  #  
-  # @param ior IOR string
-  # @param cons Consumer holder
-  # 
-  # @retrun bool False if IOR and Consumer's IOR are different
-  #
-  # @endif
-  #
-  # bool releaseObject(const std::string& ior, CorbaConsumerHolder& cons);
-  def releaseObject(self, ior, cons):
-    if ior == cons.getIor():
-      cons.releaseObject()
-      self._rtcout.RTC_DEBUG("Consumer %s released.", cons.descriptor())
-      return True
-
-    self._rtcout.RTC_WARN("IORs between Consumer and Connector are different.")
-    return False
-
-  ##
-  # @if jp
-  # @class CorbaProviderHolder
-  # @brief Provider ξǼ빽¤
-  #
-  # CORBA Provider Υۥ饹
-  #
-  # @else
-  # @class CorbaProviderHolder
-  # @brief The structure to be stored Provider information.
-  #
-  # CORBA Provider holder class
-  #
-  # @endif
-  class CorbaProviderHolder:
-    # CorbaProviderHolder(const char* type_name,
-    #                     const char* instance_name,
-    #                     PortableServer::RefCountServantBase* servant)
-    def __init__(self, type_name, instance_name, servant):
-      self._typeName = type_name
-      self._instanceName = instance_name
-      self._servant = servant
-      _mgr = OpenRTM_aist.Manager.instance()
-      self._oid = _mgr.getPOA().servant_to_id(self._servant)
-
-      obj = _mgr.getPOA().id_to_reference(self._oid)
-      self._ior = _mgr.getORB().object_to_string(obj)
-      self.deactivate()
-      return
-
-    def __del__(self):
-      self.deactivate()
-      
-    # std::string instanceName() { return m_instanceName; }
-    def instanceName(self):
-      return self._instanceName
-
-    # std::string typeName() { return m_typeName; }
-    def typeName(self):
-      return self._typeName
-
-    # std::string ior() { return m_ior; }
-    def ior(self):
-      return self._ior
-
-    # std::string descriptor() { return m_typeName + "." + m_instanceName; }
-    def descriptor(self):
-      return self._typeName + "." + self._instanceName
-
-    # void activate()
-    def activate(self):
-      try:
-        OpenRTM_aist.Manager.instance().getPOA().activate_object_with_id(self._oid, self._servant)
-      except:
-        print(OpenRTM_aist.Logger.print_exception())
-      return
-
-    # void deactivate()
-    def deactivate(self):
-      try:
-        OpenRTM_aist.Manager.instance().getPOA().deactivate_object(self._oid)
-      except:
-        pass
-        #print(OpenRTM_aist.Logger.print_exception())
-      return
-    
-
-  ##
-  # @if jp
-  # @brief Consumer ξǼ빽¤
-  # @else
-  # @brief The structure to be stored Consumer information.
-  # @endif
-  #
-  class CorbaConsumerHolder:
-    # CorbaConsumerHolder(const char* type_name,
-    #                     const char* instance_name,
-    #                     CorbaConsumerBase* consumer,
-    #                     string& owner)
-    def __init__(self, type_name, instance_name, consumer, owner):
-      self._typeName = type_name
-      self._instanceName = instance_name
-      self._consumer = consumer
-      self._owner = owner
-      self._ior = ""
-      return
-
-    # std::string instanceName() { return m_instanceName; }
-    def instanceName(self):
-      return self._instanceName
-
-    # std::string typeName() { return m_typeName; }
-    def typeName(self):
-      return self._typeName
-
-    # std::string descriptor() { return m_typeName + "." + m_instanceName; }
-    def descriptor(self):
-      return self._typeName + "." + self._instanceName
+    """
+    """
+
+    ##
+    # @if jp
+    # @brief コンストラクタ
+    #
+    # @param self
+    # @param name Port の名前
+    #
+    # @else
+    #
+    # @brief Constructor
+    #
+    # @param name The name of Port
+    #
+    # @endif
+    def __init__(self, name):
+        OpenRTM_aist.PortBase.__init__(self, name)
+        self.addProperty("port.port_type", "CorbaPort")
+        self._properties = OpenRTM_aist.Properties()
+        self._providers = []
+        self._consumers = []
+        return
+
+    def __del__(self, PortBase=OpenRTM_aist.PortBase):
+        PortBase.__del__(self)
+
+    ##
+    # @if jp
+    # @brief プロパティの初期化
+    #
+    # OutPortのプロパティを初期化する。このポートへの接続数を指定する
+    # プロパティ "connection_limit" が含まれ、適切な数値が設定されてい
+    # る場合、最大接続数としてその数値が設定される。プロパティが設定さ
+    # れていない場合、もしくは適切な値が設定されていない場合には、最大
+    # 接続数は無制限となる。
+    #
+    # @param prop CorbaPort のプロパティ
+    #
+    # @else
+    #
+    # @brief Initializing properties
+    #
+    # This operation initializes outport's properties. If a property
+    # "connection_limit" is set and appropriate value is set to this
+    # property value, the number of maximum connection is set as this
+    # value. If the property does not exist or invalid value is set
+    # to this property, the maximum number of connection will be set
+    # unlimited.
+    #
+    # @param prop properties of the CorbaPort
+    #
+    # @endif
+    #
+    # void init(coil::Properties& prop);
+
+    def init(self, prop):
+        self._rtcout.RTC_TRACE("init()")
+
+        self._properties.mergeProperties(prop)
+        prop_list = []
+        OpenRTM_aist.NVUtil.copyFromProperties(prop_list, self._properties)
+        self._profile.properties.extend(prop_list)
+
+        num = -1
+        ret, num = OpenRTM_aist.stringTo(num,
+                                         self._properties.getProperty("connection_limit", "-1"))
+        if not ret:
+            self._rtcout.RTC_ERROR("invalid connection_limit value: %s",
+                                   self._properties.getProperty("connection_limit"))
+
+        self.setConnectionLimit(num)
+
+    ##
+    # @if jp
+    #
+    # @brief Provider を登録する
+    #
+    # この Port において提供したいサーバントをこの Port に対して登録す
+    # る。サーバントは、引数で与えられる instance_name, type_name を、
+    # サーバント自身のインスタンス名およびタイプ名として、サーバントに
+    # 関連付けられる。この関数により、サーバントは CorbaPort 内部に保
+    # 持されるとともに、PortInterfaceProfile にRTC::PROVIDED インター
+    # フェースとして登録される。
+    #
+    # @param instance_name サーバントのインスタンス名
+    # @param type_name サーバントのタイプ名
+    # @param provider CORBA サーバント
+    #
+    # @return 既に同名の instance_name が登録されていれば false を返す。
+    #
+    # @else
+    #
+    # @brief Register the provider
+    #
+    # This operation registers a servant, which is provided in this
+    # Port, to the Port. The servant is associated with
+    # "instance_name" and "type_name" as the instance name of the
+    # servant and as the type name of the servant. A given servant
+    # will be stored in the CorbaPort, and this is registered as
+    # RTC::PROVIDED interface into the PortInterfaceProfile.
+    #
+    # @param instance_name Instance name of servant
+    # @param type_name Type name of the servant
+    # @param provider CORBA servant
+    #
+    # @return Return false if the same name of instance_name is already
+    #         registered.
+    #
+    # @endif
+    #
+    # bool registerProvider(const char* instance_name, const char* type_name,
+    #                       PortableServer::RefCountServantBase& provider);
+
+    def registerProvider(self, instance_name, type_name, provider):
+        self._rtcout.RTC_TRACE("registerProvider(instance=%s, type_name=%s)",
+                               (instance_name, type_name))
+
+        try:
+            self._providers.append(self.CorbaProviderHolder(type_name,
+                                                            instance_name,
+                                                            provider))
+        except BaseException:
+            self._rtcout.RTC_ERROR("appending provider interface failed")
+            self._rtcout.RTC_ERROR(OpenRTM_aist.Logger.print_exception())
+            return False
+
+        if not self.appendInterface(instance_name, type_name, RTC.PROVIDED):
+            return False
+
+        return True
+
+    ##
+    # @if jp
+    #
+    # @brief Consumer を登録する
+    #
+    # この Port が要求するサービスのプレースホルダであるコンシューマ
+    # (Consumer) を登録する。Consumer が関連付けられるサービスのインス
+    # タンス名およびタイプ名として、引数に instance_name, type_name お
+    # よび Consumer 自身を与えることにより、内部でこれらが関連付けられ
+    # る。Port 間の接続 (connect) 時 には、subscribeInterfaces() で述
+    # べられているルールに基づき、Provider Interface の参照が自動的に
+    # Consumer にセットされる。
+    #
+    # @param instance_name Consumer が要求するサービスのインスタンス名
+    # @param type_name Consumer が要求するサービスのタイプ名
+    # @param consumer CORBA サービスコンシューマ
+    #
+    # @return 既に同名の instance_name が登録されていれば false を返す。
+    #
+    # @else
+    #
+    # @brief Register the consumer
+    #
+    # This operation registers a consumer, which is a service
+    # placeholder this port requires. These are associated internally
+    # with specified instance_name, type_name and Consumer itself to
+    # the argument as service's instance name and its type name
+    # associated with Consumer.  The service Provider interface'
+    # references will be set automatically to the Consumer Interface
+    # object when connections are established, according to the rules
+    # that are described at the subscribeInterfaces() function's
+    # documentation.
+    #
+    # @param instance_name Instance name of the service Consumer requires
+    # @param type_name Type name of the service Consumer requires
+    # @param consumer CORBA service consumer
+    #
+    # @return False would be returned if the same instance_name was registered
+    #
+    # @endif
+    #
+    # bool registerConsumer(const char* instance_name, const char* type_name,
+    #                       CorbaConsumerBase& consumer);
+
+    def registerConsumer(self, instance_name, type_name, consumer):
+        self._rtcout.RTC_TRACE("registerConsumer()")
+
+        if not self.appendInterface(instance_name, type_name, RTC.REQUIRED):
+            return False
+
+        self._consumers.append(self.CorbaConsumerHolder(type_name,
+                                                        instance_name,
+                                                        consumer,
+                                                        self))
+        return True
+
+    ##
+    # @if jp
+    #
+    # @brief Port の全てのインターフェースを activates する
+    #
+    # Port に登録されている全てのインターフェースを activate する。
+    #
+    # @else
+    #
+    # @brief Activate all Port interfaces
+    #
+    # This operation activate all interfaces that is registered in the
+    # ports.
+    #
+    # @endif
+    #
+    # void CorbaPort::activateInterfaces()
+
+    def activateInterfaces(self):
+        for provider in self._providers:
+            provider.activate()
+
+        return
+
+    ##
+    # @if jp
+    #
+    # @brief 全ての Port のインターフェースを deactivates する
+    #
+    # Port に登録されている全てのインターフェースを deactivate する。
+    #
+    # @else
+    #
+    # @brief Deactivate all Port interfaces
+    #
+    # This operation deactivate all interfaces that is registered in the
+    # ports.
+    #
+    # @endif
+    #
+    # void CorbaPort::deactivateInterfaces()
+
+    def deactivateInterfaces(self):
+        for provider in self._providers:
+            provider.deactivate()
+
+        return
+
+    ##
+    # @if jp
+    #
+    # @brief Provider Interface 情報を公開する
+    #
+    # この Port が所有する Provider インターフェースに関する情報を
+    # ConnectorProfile::properties に代入し他の Port に対して公開する。
+    # 今、RTCのインスタンス名等の情報が以下の通りであるとして、
+    #
+    # - RTCインスタンス名:              rtc_iname
+    # - ポート名:                       port_name
+    # - インターフェース極性:           if_polarity
+    # - インターフェース型名:           if_tname
+    # - インターフェースインスタンス名: if_iname
+    #
+    # NameValue 型の ConnectorProfile::properties の name と value として
+    # 以下のものが格納される。
+    #
+    # - name
+    #   .port..provided..
+    # - value
+    #   Provider インターフェースの IOR 文字列
+    #
+    # なお、旧バージョンとの互換性のため以下の表記の NameValue も同時
+    # に格納されるが、将来のバージョンでは削除される可能性がある。
+    #
+    # - name
+    #   port..
+    # - value
+    #   Provider インターフェースの IOR 文字列
+    #
+    # これらの値は ConnectorProfile::properties に格納され、他のポートに対して
+    # 伝達される。他の Port でこのインターフェースを使用する Consumer が
+    # 存在すれば、ConnectorProfile からこのキーからオブジェクトリファレンスを
+    # 取得し何らかの形で使用される。
+    #
+    # @param connector_profile コネクタプロファイル
+    # @return ReturnCode_t 型のリターンコード
+    #
+    # @else
+    #
+    # @brief Publish information about interfaces
+    #
+    # This operation publishes Provider interfaces information, which
+    # is owned by this port, to the other Ports via
+    # ConnectorProfile::properties.
+    # Now it is assumed RTC instance name and other information is as follows,
+    #
+    # - RTC instance name:              rtc_iname
+    # - Port name:                      port_name
+    # - Interface polarity:             if_polarity
+    # - Interface type name:            if_tname
+    # - Interface instance name:        if_iname
+    #
+    # the following values are stored as the "name" and the "value"
+    # of the NameValue typee element in ConnectorProfile::properties.
+    #
+    # - name
+    #   .port..provided..
+    # - value
+    #   IOR string value of interface reference
+    #
+    # In addition, although the following NameValue values are also
+    # stored for the backward compatibility, this will be deleted in
+    # the future version.
+    #
+    # - name
+    #   port..
+    # - value
+    #   IOR string value of interface reference
+    #
+    # These values are stored in the ConnectorProfile::properties and
+    # are propagated to the other Ports. If the Consumer interface
+    # exists that requires this Provider interface, it will retrieve
+    # reference from the ConnectorProfile and utilize it.
+    #
+    # @param connector_profile Connector profile
+    # @return The return code of ReturnCode_t type
+    #
+    # @endif
+    #
+    # virtual ReturnCode_t
+    #    publishInterfaces(ConnectorProfile& connector_profile);
+
+    def publishInterfaces(self, connector_profile):
+        self._rtcout.RTC_TRACE("publishInterfaces()")
+
+        returnvalue = self._publishInterfaces()
+
+        if returnvalue != RTC.RTC_OK:
+            return returnvalue
+
+        properties = []
+        for provider in self._providers:
+            # ------------------------------------------------------------
+            # new version descriptor
+            # .port..provided..
+            newdesc = self._profile.name[:len(self._ownerInstanceName)] + \
+                ".port" + self._profile.name[len(self._ownerInstanceName):]
+            newdesc += ".provided." + provider.descriptor()
+
+            properties.append(
+                OpenRTM_aist.NVUtil.newNV(
+                    newdesc, provider.ior()))
+
+            # ------------------------------------------------------------
+            # old version descriptor
+            # port..
+            olddesc = "port." + provider.descriptor()
+            properties.append(
+                OpenRTM_aist.NVUtil.newNV(
+                    olddesc, provider.ior()))
+
+        OpenRTM_aist.CORBA_SeqUtil.push_back_list(
+            connector_profile.properties, properties)
+
+        return RTC.RTC_OK
+
+    ##
+    # @if jp
+    #
+    # @brief Provider Interface 情報を取得する
+    #
+    # この Portが所有する Consumer Interface に適合する Provider
+    # Interface に関する情報をConnectorProfile::properties から抽出し
+    # Consumer Interface にオブジェクト参照をセットする。
+    #
+    # 今、RTC のインスタンス名や Consumer Interface 等の情報が以下のと
+    # おりであると仮定すると、
+    #
+    # - RTCインスタンス名:              rtc_iname
+    # - ポート名:                       port_name
+    # - インターフェース極性:           if_polarity
+    # - インターフェース型名:           if_tname
+    # - インターフェースインスタンス名: if_iname
+    #
+    # この Consumer Interface を表すインターフェース指定子は以下のよう
+    # に表される。
+    #
+    # .port..required..
+    #
+    # この関数は、まず引数 ConnectorProfile::properties に上記インター
+    # フェース指定子をキーとして格納されている Provider Interface 指定
+    # 子を探し出す。さらに、その Provider Interface 指定子をキーとして
+    # 格納されている Provider Interface の参照を表す IOR 文字列を取得
+    # し、Consumer Interface にセットする。
+    #
+    # 今、仮に、Provider を prov(n), その参照をIOR(n) さらに Consumer
+    # をcons(n) のように記述し、これらすべてのインターフェースの型が同
+    # 一であり、ConnectorProfile に以下の値が設定されているとする。
+    #
+    # 
+    # ConnectorProfile::properties =
+    # {
+    #   prov0: IOR0,
+    #   prov1: IOR1,
+    #   prov2: IOR2,
+    #   cons0: prov2,
+    #   cons1: prov1,
+    #   cons2: prov0
+    # }
+    # 
+ # + # このとき、cons(0..2) にはそれぞれ、参照が以下のようにセットされる。 + # + #
+    #   cons0 = IOR2
+    #   cons1 = IOR1
+    #   cons2 = IOR0
+    # 
+ # + # なお、旧バージョンとの互換性のため、 + # ConnectorProfile::properties に Consumer Interface をキーとした + # 値がセットされていない場合でも、次のルールが適用される。 + # + # 今、仮に Consumer Interface が + # + #
+    #  PortInterfaceProfile
+    #  {
+    #    instance_name = "PA10_0";
+    #    type_name     = "Manipulator";
+    #    polarity      = REQUIRED;
+    #  }
+    # 
+ # + # として登録されていれば、他の Port の + # + #
+    #  PortInterfaceProfile
+    #  {
+    #    instance_name = "PA10_0";
+    #    type_name     = "Manipulator";
+    #    polarity      = PROVIDED;
+    #  }
+    # 
+ # + # として登録されている Serivce Provider のオブジェクト参照を探し、 + # Consumer にセットする。実際には、ConnectorProfile::properties に + # + #
+    # NameValue = { "port.Manipulator.PA10_0":  }
+    # 
+    #
+    # として登録されている NameValue を探し、そのオブジェクト参照を
+    # Consumer にセットする。
+    #
+    # @param connector_profile コネクタプロファイル
+    # @return ReturnCode_t 型のリターンコード
+    #
+    # @else
+    #
+    # @brief Subscribe to interface
+    #
+    # Retrieve information associated with Provider matches Consumer
+    # owned by this port and set the object reference to Consumer.
+    #
+    # Now, Consumer is registered as the following:
+    # 
+    #  PortInterfaceProfile
+    #  {
+    #    instance_name = "PA10_0";
+    #    type_name     = "Manipulator";
+    #    polarity      = REQUIRED;
+    #  }
+    # 
+ # Find the object reference of Serivce Provider that is registered as + # the following of other ports: + #
+    #  PortInterfaceProfile
+    #  {
+    #    instance_name = "PA10_0";
+    #    type_name     = "Manipulator";
+    #    polarity      = PROVIDED;
+    #  }
+    # 
+ # and set to Consumer. + # In fact, find NameValue that is registered as the following to + # ConnectorProfile::properties: + #
+    # NameValue = { "port.Manipulator.PA10_0":  }
+    # 
+    # and set the object reference to Consumer.
+    #
+    # @param connector_profile Connector profile
+    #
+    # @return The return code of ReturnCode_t type
+    #
+    # @endif
+    #
+    # virtual ReturnCode_t
+    #   subscribeInterfaces(const ConnectorProfile& connector_profile);
+
+    def subscribeInterfaces(self, connector_profile):
+        self._rtcout.RTC_TRACE("subscribeInterfaces()")
+        nv = connector_profile.properties
+
+        strict = False  # default is "best_effort"
+        index = OpenRTM_aist.NVUtil.find_index(
+            nv, "port.connection.strictness")
+        if index >= 0:
+            strictness = str(any.from_any(nv[index].value, keep_structs=True))
+            if "best_effort" == strictness:
+                strict = False
+            elif "strict" == strictness:
+                strict = True
+
+            self._rtcout.RTC_DEBUG("Connetion strictness is: %s", strictness)
+
+        for consumer in self._consumers:
+            ret, ior = self.findProvider(nv, consumer)
+            if ret:
+                self.setObject(ior, consumer)
+                continue
+
+            ret, ior = self.findProviderOld(nv, consumer)
+            if ret:
+                self.setObject(ior, consumer)
+                continue
+
+            # never come here without error
+            # if strict connection option is set, error is returned.
+            if strict:
+                self._rtcout.RTC_ERROR("subscribeInterfaces() failed.")
+                return RTC.RTC_ERROR
+
+        self._rtcout.RTC_TRACE("subscribeInterfaces() successfully finished.")
+
+        return RTC.RTC_OK
 
     ##
     # @if jp
-    # @brief Consumer  IOR 򥻥åȤ
+    #
+    # @brief Interface への接続を解除する
+    #
+    # 与えられた ConnectorProfile に関連する Consumer にセットされた
+    # すべての Object を解放し接続を解除する。
+    #
+    # @param self
+    # @param connector_profile コネクタプロファイル
+    #
+    # @else
+    #
+    # @brief Unsubscribe interfaces
+    #
+    # Release all Objects that was set in Consumer associated with the given
+    # ConnectorProfile.
+    #
+    # @param connector_profile Connector profile
+    #
+    # @endif
+    #  virtual void
+    #    unsubscribeInterfaces(const ConnectorProfile& connector_profile);
+
+    def unsubscribeInterfaces(self, connector_profile):
+        self._rtcout.RTC_TRACE("unsubscribeInterfaces()")
+        nv = connector_profile.properties
+
+        for consumer in self._consumers:
+            ret, ior = self.findProvider(nv, consumer)
+            if ret:
+                self._rtcout.RTC_DEBUG("Correspoinding consumer found.")
+                self.releaseObject(ior, consumer)
+                continue
+
+            ret, ior = self.findProviderOld(nv, consumer)
+            if ret:
+                self._rtcout.RTC_DEBUG("Correspoinding consumer found.")
+                self.releaseObject(ior, consumer)
+                continue
+
+        return
+
+    ##
+    # @if jp
+    # @brief Consumer に合致する Provider を NVList の中から見つける
+    #
+    # NVList 中から CorbaConsumerHolder に保持されている Consumer に合
+    # 致するキーを持つ Provider を見つけ、IOR を抽出しナローイングして
+    # Consumer にセットする。対応するキーが存在しない、IOR が見つから
+    # ない、ナローイングに失敗した場合、false を返す。
+    #
+    # @param nv Provider が含まれている ConnectorProfile::properties の NVList
+    # @param cons Provider と対応する Consumer のホルダ
+    #
+    # @retrun bool Consumer に対応する Provider が見つからない場合 false
+    #
+    # @else
+    # @brief Find out a provider corresponding to the consumer from NVList
+    #
+    # This function finds out a Provider with the key that is matched
+    # with Cosumer's name in the CorbaConsumerHolder, extracts IOR
+    # and performs narrowing into the Consumer and set it to the
+    # Consumer. False is returned when there is no corresponding key
+    # and IOR and the narrowing failed.
+    #
+    # @param nv NVlist of ConnectorProfile::properties that includes Provider
+    # @param cons a Consumer holder to be matched with a Provider
+    #
+    # @return bool false is returned if there is no provider for the consumer
+    #
+    # @endif
+    #
+    # virtual bool findProvider(const NVList& nv,
+    #                           CorbaConsumerHolder& cons,
+    #                           std::string& iorstr);
+
+    def findProvider(self, nv, cons):
+        # new consumer interface descriptor
+        newdesc = self._profile.name[:len(self._ownerInstanceName)] + \
+            ".port" + self._profile.name[len(self._ownerInstanceName):]
+        newdesc += ".required." + cons.descriptor()
+
+        # find a NameValue of the consumer
+        cons_index = OpenRTM_aist.NVUtil.find_index(nv, newdesc)
+        if cons_index < 0:
+            return False, ""
+
+        provider = str(any.from_any(nv[cons_index].value, keep_structs=True))
+        if not provider:
+            self._rtcout.RTC_WARN(
+                "Cannot extract Provider interface descriptor")
+            return False, ""
+
+        # find a NameValue of the provider
+        prov_index = OpenRTM_aist.NVUtil.find_index(nv, provider)
+        if prov_index < 0:
+            return False, ""
+
+        ior_ = str(any.from_any(nv[prov_index].value, keep_structs=True))
+        if not ior_:
+            self._rtcout.RTC_WARN("Cannot extract Provider IOR string")
+            return False, ior_
+
+        self._rtcout.RTC_TRACE(
+            "interface matched with new descriptor: %s", newdesc)
+
+        return True, ior_
+
+    ##
+    # @if jp
+    # @brief Consumer に合致する Provider を NVList の中から見つける
+    #
+    # この関数は、古いバージョンの互換性のための関数である。
+    #
+    # NVList 中から CorbaConsumerHolder に保持されている Consumer に合
+    # 致するキーを持つ Provider を見つける。対応するキーが存在しない、
+    # IOR が見つからない場合、false を返す
+    #
+    # @param nv Provider が含まれている ConnectorProfile::properties の NVList
+    # @param cons Provider と対応する Consumer のホルダ
+    # @param iorstr 見つかったIOR文字列を格納する変数
+    #
+    # @retrun bool Consumer に対応する Provider が見つからない場合 false
+    #
+    # @else
+    # @brief Find out a provider corresponding to the consumer from NVList
+    #
+    # This function is for the old version's compatibility.
+    #
+    # This function finds out a Provider with the key that is matched
+    # with Cosumer's name in the CorbaConsumerHolder and extracts
+    # IOR.  False is returned when there is no corresponding key and
+    # IOR.
+    #
+    # @param nv NVlist of ConnectorProfile::properties that includes Provider
+    # @param cons a Consumer holder to be matched with a Provider
+    # @param iorstr variable which is set IOR string
+    #
+    # @return bool false is returned if there is no provider for the consumer
+    #
+    # @endif
+    #
+    # virtual bool findProviderOld(const NVList&nv,
+    #                              CorbaConsumerHolder& cons,
+    #                              std::string& iorstr);
+
+    def findProviderOld(self, nv, cons):
+        # old consumer interface descriptor
+        olddesc = "port." + cons.descriptor()
+
+        # find a NameValue of the provider same as olddesc
+        index = OpenRTM_aist.NVUtil.find_index(nv, olddesc)
+        if index < 0:
+            return False, ""
+
+        ior_ = str(any.from_any(nv[index].value, keep_structs=True))
+        if not ior_:
+            self._rtcout.RTC_WARN("Cannot extract Provider IOR string")
+            return False, ior_
+
+        self._rtcout.RTC_TRACE(
+            "interface matched with old descriptor: %s", olddesc)
+
+        return True, ior_
+
+    ##
+    # @if jp
+    # @brief Consumer に IOR をセットする
+    #
+    # IOR をナローイングしてConsumer にセットする。ナローイングに失敗
+    # した場合、false を返す。ただし、IOR文字列が、nullまたはnilの場合、
+    # オブジェクトに何もセットせずに true を返す。
+    #
+    # @param ior セットする IOR 文字列
+    # @param cons Consumer のホルダ
+    #
+    # @retrun bool Consumer へのナローイングに失敗した場合 false
+    #
     # @else
     # @brief Setting IOR to Consumer
-    #@endif
-    #
-    # bool setObject(const char* ior)
-    def setObject(self, ior):
-      self._ior = ior
-      orb = OpenRTM_aist.Manager.instance().getORB()
-      obj = orb.string_to_object(ior)
-      if CORBA.is_nil(obj):
-        return False
+    #
+    # This function performs narrowing into the Consumer and set it to the
+    # Consumer. False is returned when the narrowing failed. But, if IOR
+    # string is "null" or "nil", this function returns true.
+    #
+    # @param ior IOR string
+    # @param cons Consumer holder
+    #
+    # @retrun bool false if narrowing failed.
+    #
+    # @endif
+    #
+    # bool setObject(const std::string& ior, CorbaConsumerHolder& cons);
+
+    def setObject(self, ior, cons):
+        # if ior string is "null" or "nil", ignore it.
+        if "null" == ior:
+            return True
+
+        if "nil" == ior:
+            return True
 
-      return self._consumer.setObject(obj)
+        # IOR should be started by "IOR:"
+        if "IOR:" != ior[:4]:
+            return False
+
+        # set IOR to the consumer
+        if not cons.setObject(ior):
+            self._rtcout.RTC_ERROR("Cannot narrow reference")
+            return False
+
+        self._rtcout.RTC_TRACE("setObject() done")
+        return True
 
     ##
     # @if jp
-    # @brief Consumer Υ֥Ȥ꡼
+    # @brief Consumer のオブジェクトをリリースする
+    #
+    # Consumer にセットされた参照をリリースする。ConsumerのIORが与えら
+    # れたIOR文字列と異なる場合、falseを返す。
+    #
+    # @param ior セットする IOR 文字列
+    # @param cons Consumer のホルダ
+    #
+    # @retrun ConsumerのIORが与えられたIOR文字列と異なる場合、falseを返す。
+    #
     # @else
     # @brief Releasing Consumer Object
+    #
+    # This function releases object reference of Consumer. If the
+    # given IOR string is different from Consumer's IOR string, it
+    # returns false.
+    #
+    # @param ior IOR string
+    # @param cons Consumer holder
+    #
+    # @retrun bool False if IOR and Consumer's IOR are different
+    #
+    # @endif
+    #
+    # bool releaseObject(const std::string& ior, CorbaConsumerHolder& cons);
+    def releaseObject(self, ior, cons):
+        if ior == cons.getIor():
+            cons.releaseObject()
+            self._rtcout.RTC_DEBUG("Consumer %s released.", cons.descriptor())
+            return True
+
+        self._rtcout.RTC_WARN(
+            "IORs between Consumer and Connector are different.")
+        return False
+
+    ##
+    # @if jp
+    # @class CorbaProviderHolder
+    # @brief Provider の情報を格納する構造体
+    #
+    # CORBA Provider のホルダクラス
+    #
+    # @else
+    # @class CorbaProviderHolder
+    # @brief The structure to be stored Provider information.
+    #
+    # CORBA Provider holder class
+    #
+    # @endif
+    class CorbaProviderHolder:
+        # CorbaProviderHolder(const char* type_name,
+        #                     const char* instance_name,
+        #                     PortableServer::RefCountServantBase* servant)
+        def __init__(self, type_name, instance_name, servant):
+            self._typeName = type_name
+            self._instanceName = instance_name
+            self._servant = servant
+            _mgr = OpenRTM_aist.Manager.instance()
+            self._oid = _mgr.getPOA().servant_to_id(self._servant)
+
+            obj = _mgr.getPOA().id_to_reference(self._oid)
+            self._ior = _mgr.getORB().object_to_string(obj)
+            self.deactivate()
+            return
+
+        def __del__(self):
+            self.deactivate()
+
+        # std::string instanceName() { return m_instanceName; }
+        def instanceName(self):
+            return self._instanceName
+
+        # std::string typeName() { return m_typeName; }
+        def typeName(self):
+            return self._typeName
+
+        # std::string ior() { return m_ior; }
+        def ior(self):
+            return self._ior
+
+        # std::string descriptor() { return m_typeName + "." + m_instanceName;
+        # }
+        def descriptor(self):
+            return self._typeName + "." + self._instanceName
+
+        # void activate()
+        def activate(self):
+            try:
+                OpenRTM_aist.Manager.instance().getPOA(
+                ).activate_object_with_id(self._oid, self._servant)
+            except BaseException:
+                print(OpenRTM_aist.Logger.print_exception())
+            return
+
+        # void deactivate()
+        def deactivate(self):
+            try:
+                OpenRTM_aist.Manager.instance().getPOA().deactivate_object(self._oid)
+            except BaseException:
+                pass
+                # print(OpenRTM_aist.Logger.print_exception())
+            return
+
+    ##
+    # @if jp
+    # @brief Consumer の情報を格納する構造体
+    # @else
+    # @brief The structure to be stored Consumer information.
     # @endif
     #
-    # void releaseObject()
-    def releaseObject(self):
-      self._consumer.releaseObject()
-      return
-
-    # const std::string& getIor()
-    def getIor(self):
-      return self._ior
-
-
-  ##
-  # @if jp
-  # @brief ConnectorProfile  Consuemr Ӥ򤷥֥ȻȤ
-  #        åȤ뤿 Functor
-  # @else
-  # @brief Subscription mutching functor for Consumer
-  # @endif
-  class subscribe:
-    def __init__(self, cons):
-      self._cons = cons
-      self._len  = len(cons)
-
-    def __call__(self, nv):
-      for i in range(self._len):
-        name_ = nv.name
-        if self._cons[i].descriptor() == name_:
-          try:
-            obj = any.from_any(nv.value, keep_structs=True)
-            self._cons[i].setObject(obj)
-          except:
-            print(OpenRTM_aist.Logger.print_exception())
-
-
-
-  ##
-  # @if jp
-  # @brief Consumer Υ֥Ȥ뤿 Functor
-  # @else
-  # @brief Functor to release Consumer's object
-  # @endif
-  class unsubscribe:
-    def __init__(self, cons):
-      self._cons = cons
-      self._len  = len(cons)
-
-    def __call__(self, nv):
-      for i in range(self._len):
-        name_ = nv.name
-        if self._cons[i].descriptor() == name_:
-          self._cons[i].releaseObject()
-          return
-
-        # for 0.4.x
-        if "port."+self._cons[i].descriptor() == name_:
-          self._cons[i].releaseObject()
 
+    class CorbaConsumerHolder:
+        # CorbaConsumerHolder(const char* type_name,
+        #                     const char* instance_name,
+        #                     CorbaConsumerBase* consumer,
+        #                     string& owner)
+        def __init__(self, type_name, instance_name, consumer, owner):
+            self._typeName = type_name
+            self._instanceName = instance_name
+            self._consumer = consumer
+            self._owner = owner
+            self._ior = ""
+            return
+
+        # std::string instanceName() { return m_instanceName; }
+        def instanceName(self):
+            return self._instanceName
+
+        # std::string typeName() { return m_typeName; }
+        def typeName(self):
+            return self._typeName
+
+        # std::string descriptor() { return m_typeName + "." + m_instanceName;
+        # }
+        def descriptor(self):
+            return self._typeName + "." + self._instanceName
+
+        ##
+        # @if jp
+        # @brief Consumer に IOR をセットする
+        # @else
+        # @brief Setting IOR to Consumer
+        # @endif
+        #
+        # bool setObject(const char* ior)
+        def setObject(self, ior):
+            self._ior = ior
+            orb = OpenRTM_aist.Manager.instance().getORB()
+            obj = orb.string_to_object(ior)
+            if CORBA.is_nil(obj):
+                return False
+
+            return self._consumer.setObject(obj)
+
+        ##
+        # @if jp
+        # @brief Consumer のオブジェクトをリリースする
+        # @else
+        # @brief Releasing Consumer Object
+        # @endif
+        #
+        # void releaseObject()
+        def releaseObject(self):
+            self._consumer.releaseObject()
+            return
+
+        # const std::string& getIor()
+        def getIor(self):
+            return self._ior
+
+    ##
+    # @if jp
+    # @brief ConnectorProfile と Consuemr の比較をしオブジェクト参照を
+    #        セットするための Functor
+    # @else
+    # @brief Subscription mutching functor for Consumer
+    # @endif
+
+    class subscribe:
+        def __init__(self, cons):
+            self._cons = cons
+
+        def __call__(self, nv):
+            for con in self._cons:
+                name_ = nv.name
+                if con.descriptor() == name_:
+                    try:
+                        obj = any.from_any(nv.value, keep_structs=True)
+                        con.setObject(obj)
+                    except BaseException:
+                        print(OpenRTM_aist.Logger.print_exception())
+
+    ##
+    # @if jp
+    # @brief Consumer のオブジェクトを解放するための Functor
+    # @else
+    # @brief Functor to release Consumer's object
+    # @endif
+
+    class unsubscribe:
+        def __init__(self, cons):
+            self._cons = cons
+
+        def __call__(self, nv):
+            for con in self._cons:
+                name_ = nv.name
+                if con.descriptor() == name_:
+                    con.releaseObject()
+                    return
 
+                # for 0.4.x
+                if "port." + con.descriptor() == name_:
+                    con.releaseObject()
diff --git a/OpenRTM_aist/DataFlowComponentBase.py b/OpenRTM_aist/DataFlowComponentBase.py
index 8d9afea2..f1637940 100644
--- a/OpenRTM_aist/DataFlowComponentBase.py
+++ b/OpenRTM_aist/DataFlowComponentBase.py
@@ -1,5 +1,5 @@
 #!/usr/bin/env python
-# -*- coding: euc-jp -*-
+# -*- coding: utf-8 -*-
 
 ##
 # \file DataFlowComponentBase.py
@@ -22,11 +22,11 @@
 ##
 # @if jp
 # @class DataFlowComponentBase
-# @brief DataFlowComponentBase 饹
+# @brief DataFlowComponentBase クラス
 #
-# ǡեRTComponentδ쥯饹
-# ƼǡեRTComponentϡܥ饹ѾǼ
-# 롣
+# データフロー型RTComponentの基底クラス。
+# 各種データフロー型RTComponentを実装する場合は、本クラスを継承する形で実装
+# する。
 #
 # @since 0.4.0
 #
@@ -34,203 +34,200 @@
 # @class DataFlowComponentBase
 # @brief DataFlowComponentBase class
 # @endif
-class DataFlowComponentBase(OpenRTM_aist.RTObject_impl, OpenRTM__POA.DataFlowComponent):
-  """
-  """
-
-
-  ##
-  # @if jp
-  # @brief 󥹥ȥ饯
-  #
-  # 󥹥ȥ饯
-  #
-  # @param self
-  # @param manager ޥ͡㥪֥
-  #
-  # @else
-  # @brief Constructor
-  # @endif
-  def __init__(self, manager=None, orb=None, poa=None):
-    OpenRTM_aist.RTObject_impl.__init__(self, manager, orb, poa)
-    self._objref = self._this()
-
-
-  ##
-  # @if jp
-  # @brief (֥饹)
-  #
-  # ǡե RTComponent ν¹Ԥ롣
-  # ºݤνϡƶݥ饹˵Ҥ롣
-  #
-  # @param self
-  #
-  # @else
-  # @brief Initialization
-  # @endif
-  def init(self):
-    pass
-
-
-  ##
-  # @if jp
-  #
-  # @brief [DataFlowComponentAction CORBA interface] RTC ()
-  #
-  # ʲξ֤ݻƤˡꤵ줿Ū˸ƤӽФ롣
-  # - RTC  Alive ֤Ǥ롣
-  # - ꤵ줿 ExecutionContext  Running ֤Ǥ롣
-  # ܥڥ졼ϡTwo-Pass Execution Ǽ¹Ԥ롣
-  # Υڥ졼ƤӽФη̤Ȥ onExecute() ХåؿƤ
-  # Ф롣
-  #
-  # 
-  # - ꤵ줿 ExecutionContext  ExecutionKind ϡ PERIODIC ǤʤФ
-  #   ʤ
-  #
-  # @param self
-  # @param ec_id о ExecutionContext  ID
-  #
-  # @return ReturnCode_t Υ꥿󥳡
-  #
-  # @else
-  #
-  # @brief [DataFlowComponentAction CORBA interface] Primary Periodic 
-  #        Operation of RTC
-  #
-  # This operation will be invoked periodically at the rate of the given
-  # execution context as long as the following conditions hold:
-  # - The RTC is Active.
-  # - The given execution context is Running
-  # This callback occurs during the first execution pass.
-  #
-  # Constraints
-  # - The execution context of the given context shall be PERIODIC.
-  #
-  # @param ec_id
-  #
-  # @return
-  #
-  # @endif
-  def on_execute(self, ec_id):
-    self._rtcout.RTC_TRACE("on_execute(%d)", ec_id)
-    ret = RTC.RTC_ERROR
-    try:
-      self.preOnExecute(ec_id)
-      if self._readAll:
-        self.readAll()
-      
-      ret = self.onExecute(ec_id)
-
-      if self._writeAll:
-        self.writeAll()
-      
-    except:
-      self._rtcout.RTC_ERROR(OpenRTM_aist.Logger.print_exception())
-      ret = RTC.RTC_ERROR
-    self.postOnExecute(ec_id, ret)
-    return ret
-
-
-  ##
-  # @if jp
-  #
-  # @brief [DataFlowComponentAction CORBA interface] RTC ()
-  #
-  # ʲξ֤ݻƤˡꤵ줿Ū˸ƤӽФ롣
-  # - RTC  Alive ֤Ǥ롣
-  # - ꤵ줿 ExecutionContext  Running ֤Ǥ롣
-  # ܥڥ졼ϡTwo-Pass Execution Ǽ¹Ԥ롣
-  # Υڥ졼ƤӽФη̤Ȥ onStateUpdate() Хåؿ
-  # ƤӽФ롣
-  #
-  # 
-  # - ꤵ줿 ExecutionContext  ExecutionKind ϡ PERIODIC ǤʤФ
-  #   ʤ
-  #
-  # @param self
-  # @param ec_id о ExecutionContext  ID
-  #
-  # @return ReturnCode_t Υ꥿󥳡
-  #
-  # @else
-  #
-  # @brief [DataFlowComponentAction CORBA interface] Secondary Periodic 
-  #        Operation of RTC
-  #
-  # This operation will be invoked periodically at the rate of the given
-  # execution context as long as the following conditions hold:
-  # - The RTC is Active.
-  # - The given execution context is Running
-  # This callback occurs during the second execution pass.
-  #
-  # Constraints
-  # - The execution context of the given context shall be PERIODIC.
-  #
-  # @param ec_id
-  #
-  # @return
-  #
-  # @endif
-  def on_state_update(self, ec_id):
-    self._rtcout.RTC_TRACE("on_state_update(%d)", ec_id)
-    ret = RTC.RTC_ERROR
-    try:
-      self.preOnStateUpdate(ec_id)
-      ret = self.onStateUpdate(ec_id)
-      self._configsets.update()
-    except:
-      self._rtcout.RTC_ERROR(OpenRTM_aist.Logger.print_exception())
-      ret = RTC.RTC_ERROR
-    self.postOnStateUpdate(ec_id, ret)
-    return ret
-
-
-
-
-  ##
-  # @if jp
-  #
-  # @brief [DataFlowComponentAction CORBA interface] ¹Լѹ
-  #
-  # ܥڥ졼ϡExecutionContext μ¹Լѹ줿ȤΤ
-  # ݤ˸ƤӽФ롣
-  # Υڥ졼ƤӽФη̤Ȥ onRateChanged() Хåؿ
-  # ƤӽФ롣
-  #
-  # 
-  # - ꤵ줿 ExecutionContext  ExecutionKind ϡ PERIODIC ǤʤФ
-  #   ʤ
-  #
-  # @param self
-  # @param ec_id о ExecutionContext  ID
-  #
-  # @return ReturnCode_t Υ꥿󥳡
-  #
-  # @else
-  #
-  # @brief [DataFlowComponentAction CORBA interface] Notify rate chenged
-  #
-  # This operation is a notification that the rate of the indicated execution 
-  # context has changed.
-  #
-  # Constraints
-  # - The execution context of the given context shall be PERIODIC.
-  #
-  # @param ec_id
-  #
-  # @return
-  #
-  # @endif
-  def on_rate_changed(self, ec_id):
-    self._rtcout.RTC_TRACE("on_rate_changed(%d)", ec_id)
-    ret = RTC.RTC_ERROR
-    try:
-      self.preOnRateChanged(ec_id)
-      ret = self.onRateChanged(ec_id)
-    except:
-      self._rtcout.RTC_ERROR(OpenRTM_aist.Logger.print_exception())
-      ret = RTC.RTC_ERROR
-    self.postOnRateChanged(ec_id, ret)
-    return ret
-
+class DataFlowComponentBase(OpenRTM_aist.RTObject_impl,
+                            OpenRTM__POA.DataFlowComponent):
+    """
+    """
+
+    ##
+    # @if jp
+    # @brief コンストラクタ
+    #
+    # コンストラクタ
+    #
+    # @param self
+    # @param manager マネージャオブジェクト
+    #
+    # @else
+    # @brief Constructor
+    # @endif
+    def __init__(self, manager=None, orb=None, poa=None):
+        OpenRTM_aist.RTObject_impl.__init__(self, manager, orb, poa)
+        self._objref = self._this()
+
+    ##
+    # @if jp
+    # @brief 初期化(サブクラス実装用)
+    #
+    # データフロー型 RTComponent の初期化を実行する。
+    # 実際の初期化処理は、各具象クラス内に記述する。
+    #
+    # @param self
+    #
+    # @else
+    # @brief Initialization
+    # @endif
+
+    def init(self):
+        pass
+
+    ##
+    # @if jp
+    #
+    # @brief [DataFlowComponentAction CORBA interface] RTC の定常処理(第一周期)
+    #
+    # 以下の状態が保持されている場合に、設定された周期で定期的に呼び出される。
+    # - RTC は Alive 状態である。
+    # - 指定された ExecutionContext が Running 状態である。
+    # 本オペレーションは、Two-Pass Execution の第一周期で実行される。
+    # このオペレーション呼び出しの結果として onExecute() コールバック関数が呼び
+    # 出される。
+    #
+    # 制約
+    # - 指定された ExecutionContext の ExecutionKind は、 PERIODIC でなければな
+    #   らない
+    #
+    # @param self
+    # @param ec_id 定常処理対象 ExecutionContext の ID
+    #
+    # @return ReturnCode_t 型のリターンコード
+    #
+    # @else
+    #
+    # @brief [DataFlowComponentAction CORBA interface] Primary Periodic
+    #        Operation of RTC
+    #
+    # This operation will be invoked periodically at the rate of the given
+    # execution context as long as the following conditions hold:
+    # - The RTC is Active.
+    # - The given execution context is Running
+    # This callback occurs during the first execution pass.
+    #
+    # Constraints
+    # - The execution context of the given context shall be PERIODIC.
+    #
+    # @param ec_id
+    #
+    # @return
+    #
+    # @endif
+
+    def on_execute(self, ec_id):
+        self._rtcout.RTC_TRACE("on_execute(%d)", ec_id)
+        ret = RTC.RTC_ERROR
+        try:
+            self.preOnExecute(ec_id)
+            if self._readAll:
+                self.readAll()
+
+            ret = self.onExecute(ec_id)
+
+            if self._writeAll:
+                self.writeAll()
+
+        except BaseException:
+            self._rtcout.RTC_ERROR(OpenRTM_aist.Logger.print_exception())
+            ret = RTC.RTC_ERROR
+        self.postOnExecute(ec_id, ret)
+        return ret
+
+    ##
+    # @if jp
+    #
+    # @brief [DataFlowComponentAction CORBA interface] RTC の定常処理(第二周期)
+    #
+    # 以下の状態が保持されている場合に、設定された周期で定期的に呼び出される。
+    # - RTC は Alive 状態である。
+    # - 指定された ExecutionContext が Running 状態である。
+    # 本オペレーションは、Two-Pass Execution の第二周期で実行される。
+    # このオペレーション呼び出しの結果として onStateUpdate() コールバック関数が
+    # 呼び出される。
+    #
+    # 制約
+    # - 指定された ExecutionContext の ExecutionKind は、 PERIODIC でなければな
+    #   らない
+    #
+    # @param self
+    # @param ec_id 定常処理対象 ExecutionContext の ID
+    #
+    # @return ReturnCode_t 型のリターンコード
+    #
+    # @else
+    #
+    # @brief [DataFlowComponentAction CORBA interface] Secondary Periodic
+    #        Operation of RTC
+    #
+    # This operation will be invoked periodically at the rate of the given
+    # execution context as long as the following conditions hold:
+    # - The RTC is Active.
+    # - The given execution context is Running
+    # This callback occurs during the second execution pass.
+    #
+    # Constraints
+    # - The execution context of the given context shall be PERIODIC.
+    #
+    # @param ec_id
+    #
+    # @return
+    #
+    # @endif
+
+    def on_state_update(self, ec_id):
+        self._rtcout.RTC_TRACE("on_state_update(%d)", ec_id)
+        ret = RTC.RTC_ERROR
+        try:
+            self.preOnStateUpdate(ec_id)
+            ret = self.onStateUpdate(ec_id)
+            self._configsets.update()
+        except BaseException:
+            self._rtcout.RTC_ERROR(OpenRTM_aist.Logger.print_exception())
+            ret = RTC.RTC_ERROR
+        self.postOnStateUpdate(ec_id, ret)
+        return ret
+
+    ##
+    # @if jp
+    #
+    # @brief [DataFlowComponentAction CORBA interface] 実行周期変更通知
+    #
+    # 本オペレーションは、ExecutionContext の実行周期が変更されたことを通知する
+    # 際に呼び出される。
+    # このオペレーション呼び出しの結果として onRateChanged() コールバック関数が
+    # 呼び出される。
+    #
+    # 制約
+    # - 指定された ExecutionContext の ExecutionKind は、 PERIODIC でなければな
+    #   らない
+    #
+    # @param self
+    # @param ec_id 定常処理対象 ExecutionContext の ID
+    #
+    # @return ReturnCode_t 型のリターンコード
+    #
+    # @else
+    #
+    # @brief [DataFlowComponentAction CORBA interface] Notify rate chenged
+    #
+    # This operation is a notification that the rate of the indicated execution
+    # context has changed.
+    #
+    # Constraints
+    # - The execution context of the given context shall be PERIODIC.
+    #
+    # @param ec_id
+    #
+    # @return
+    #
+    # @endif
+
+    def on_rate_changed(self, ec_id):
+        self._rtcout.RTC_TRACE("on_rate_changed(%d)", ec_id)
+        ret = RTC.RTC_ERROR
+        try:
+            self.preOnRateChanged(ec_id)
+            ret = self.onRateChanged(ec_id)
+        except BaseException:
+            self._rtcout.RTC_ERROR(OpenRTM_aist.Logger.print_exception())
+            ret = RTC.RTC_ERROR
+        self.postOnRateChanged(ec_id, ret)
+        return ret
diff --git a/OpenRTM_aist/DataPortStatus.py b/OpenRTM_aist/DataPortStatus.py
index 3f1d2d25..c7cc5319 100644
--- a/OpenRTM_aist/DataPortStatus.py
+++ b/OpenRTM_aist/DataPortStatus.py
@@ -1,5 +1,5 @@
 #!/usr/bin/env python
-# -*- coding: euc-jp -*-
+# -*- coding: utf-8 -*-
 
 ##
 # @file PushConnector.py
@@ -20,15 +20,15 @@
 ##
 # @if jp
 # @class DataPortStatus mixin class
-# @brief DataPortStatus mixin 饹
+# @brief DataPortStatus mixin クラス
 #
-# Υ饹ϡenum줿꥿󥳡ɤ򡢥ǡݡȴϢΥ
-# ֥饹ǶѤ뤿 mixin 饹Ǥ롣Υ꥿󥳡
-# ɤѤ륯饹ǤϡDataPortStatus 饹public Ѿ
-# define ƤDATAPORTSTATUS_ENUM 򥯥饹˵Ҥ뤳Ȥ
-# ǽȤʤ롣ˤꡢenum  ReturnCode_t Ȥ typedef 
-# ʸReturnCode_t ѤǤ褦ˤȤȤˡ֤̾ enum
-# 줿Ƽ̻Ҥ饹̾Ƴ롣
+# このクラスは、enum定義されたリターンコードを、データポート関連のサ
+# ブクラスで共通利用するための mixin クラスである。このリターンコー
+# ドを使用するクラスでは、DataPortStatus クラスをpublic 継承し、下に
+# define してあるDATAPORTSTATUS_ENUM をクラス内に記述することで利用
+# 可能となる。これにより、enum を ReturnCode_t 型として typedef し、
+# 以後ReturnCode_t を利用できるようにするとともに、名前空間に enum
+# 定義された各識別子を当該クラス名前空間内に導入する。
 #
 # @else
 # @class DataPortStatus mixin class
@@ -45,151 +45,153 @@
 # @endif
 #
 class DataPortStatus:
-  """
-  """
+    """
+    """
 
-  def __init__(self):
-    pass
+    def __init__(self):
+        pass
 
-  ##
-  # @if jp
-  # brief DataPortStatus ꥿󥳡
-  #
-  # ǡݡȴϢΥ饹Ƕ̤Υ꥿󥳡
-  #  
-  # - PORT_OK:              ェλ
-  # - PORT_ERROR:           ۾ェλ
-  # - BUFFER_ERROR:         Хåե顼
-  # - BUFFER_FULL:          Хåեե
-  # - BUFFER_EMPTY:         Хåեץƥ
-  # - BUFFER_TIMEOUT:       Хåեॢ
-  # - SEND_FULL:            ǡä¦Хåեե
-  # - SEND_TIMEOUT:         ǡä¦ॢȤ
-  # - RECV_EMPTY:           ǡ褦Ȥǡ
-  # - RECV_TIMEOUT:         ǡ褦ȤदȤ
-  # - INVALID_ARGS:         ʰ
-  # - PRECONDITION_NOT_MET: Ƥʤ
-  # - CONNECTION_LOST:      ³Ǥ줿
-  # - UNKNOWN_ERROR:        ʥ顼
-  #
-  # ǡݡȤΥǡϩΥ顼ȯĽ꤫ƤӽФ¦إ顼
-  # 뤿ˤΥ顼ɤѤ롣ˡϩΥ
-  # 顼Υ顼ʤɤͤ뤬ʬγ̤ȯ륨
-  # 顼ʲ󤹤롣
-  #
-  # (1) Push
-  #  a) InPortConsumer  Publisher/Activity ֤ȯ꥿󥳡
-  #     PORT_OK, PORT_ERROR, SEND_FULL, SEND_TIMEOUT, CONNECTION_LOST,
-  #     UNKNOWN_ERROR
-  #
-  #  b) Activity  OutPort  Buffer/Connector ֤ȯ꥿󥳡
-  #     PORT_OK, PORT_ERROR, BUFFER_ERROR, BUFFER_FULL, BUFFER_TIMEOUT,
-  #     UNKNOWN_ERROR, 
-  #
-  # (2) Pull
-  #  a) Activity  InPort δ֤ȯ꥿󥳡
-  #     PORT_OK, PORT_ERROR, RECV_EMPTY, RECV_TIMEOUT, CONNETION_LOST,
-  #     UNKNOWN_ERROR
-  #
-  # ƴؿ֤꥿󥳡ɤϴؿȤΥե󥹤򻲾ȤΤȡ
-  #
-  # @else
-  # @brief DataPortStatus return codes
-  #
-  # Common return codes for data ports related classes.
-  #
-  # - PORT_OK:              Normal return
-  # - PORT_ERROR:           Error return
-  # - BUFFER_ERROR:         Buffer error
-  # - BUFFER_FULL:          Buffer full
-  # - BUFFER_EMPTY:         Buffer empty
-  # - BUFFER_TIMEOUT:       Buffer timeout
-  # - SEND_FULL:            Buffer full although OutPort tried to send data
-  # - SEND_TIMEOUT:         Timeout although OutPort tried to send data
-  # - RECV_EMPTY:           Buffer empty although InPort tried to receive
-  #                         data
-  # - RECV_TIMEOUT:         Timeout although InPort tried to receive data
-  # - INVALID_ARGS:         Invalid arguments
-  # - PRECONDITION_NOT_MET: Precondition not met
-  # - CONNECTION_LOST:      Connection has been lost
-  # - UNKNOWN_ERROR:        Unknown error
-  #
-  # This error codes might be used to propagate error status from
-  # the error occurring point to the function caller in the data
-  # stream path. It would occur in data-transfer path and data
-  # receiver/sender. The errors that occur in the interface of each
-  # portion of data port are shown below.
-  #
-  # (1) Push Type
-  #  a) The return codes between InPortConsumer and Publisher/Activity
-  #     PORT_OK, PORT_ERROR, SEND_FULL, SEND_TIMEOUT, CONNECTION_LOST,
-  #     UNKNOWN_ERROR
-  #  b) The return codes between Activity and Buffer/Connector of OutPort
-  #     PORT_OK, PORT_ERROR, BUFFER_ERROR, BUFFER_FULL, BUFFER_TIMEOUT,
-  #     UNKNOWN_ERROR, 
-  #
-  # (2) Pull Type
-  #  a) The return codes between Activity and InPort
-  #     PORT_OK, PORT_ERROR, RECV_EMPTY, RECV_TIMEOUT, CONNETION_LOST,
-  #     UNKNOWN_ERROR
-  #
-  # See function references for detailed return codes for each function.
-  #
-  # @endif
-  #
-  PORT_OK              = 0
-  PORT_ERROR           = 1
-  BUFFER_ERROR         = 2
-  BUFFER_FULL          = 3
-  BUFFER_EMPTY         = 4
-  BUFFER_TIMEOUT       = 5
-  SEND_FULL            = 6
-  SEND_TIMEOUT         = 7
-  RECV_EMPTY           = 8
-  RECV_TIMEOUT         = 9
-  INVALID_ARGS         = 10
-  PRECONDITION_NOT_MET = 11    
-  CONNECTION_LOST      = 12
-  UNKNOWN_ERROR        = 13
+    ##
+    # @if jp
+    # brief DataPortStatus リターンコード
+    #
+    # データポート関連のクラスで共通のリターンコード
+    #
+    # - PORT_OK:              正常終了
+    # - PORT_ERROR:           異常終了
+    # - BUFFER_ERROR:         バッファエラー
+    # - BUFFER_FULL:          バッファフル
+    # - BUFFER_EMPTY:         バッファエンプティ
+    # - BUFFER_TIMEOUT:       バッファタイムアウト
+    # - SEND_FULL:            データを送ったが相手側がバッファフル状態
+    # - SEND_TIMEOUT:         データを送ったが相手側がタイムアウトした
+    # - RECV_EMPTY:           データを受信しようとしたがデータが空状態
+    # - RECV_TIMEOUT:         データを受信しようとしたがタイムうとした
+    # - INVALID_ARGS:         不正な引数
+    # - PRECONDITION_NOT_MET: 事前条件を満たしていない
+    # - CONNECTION_LOST:      接続が切断された
+    # - UNKNOWN_ERROR:        不明なエラー
+    #
+    # データポートのデータ経路上のエラー発生個所から呼び出し側へエラー
+    # 情報を伝えるためにこのエラーコードを使用する。主に、伝送路上のエ
+    # ラー、伝送先のエラーなどが考えられるが、各部分の界面で発生するエ
+    # ラーを以下に列挙する。
+    #
+    # (1) Push型
+    #  a) InPortConsumer と Publisher/Activity 間で発生するリターンコード
+    #     PORT_OK, PORT_ERROR, SEND_FULL, SEND_TIMEOUT, CONNECTION_LOST,
+    #     UNKNOWN_ERROR
+    #
+    #  b) Activity と OutPort の Buffer/Connector 間で発生するリターンコード
+    #     PORT_OK, PORT_ERROR, BUFFER_ERROR, BUFFER_FULL, BUFFER_TIMEOUT,
+    #     UNKNOWN_ERROR,
+    #
+    # (2) Pull型
+    #  a) Activity と InPort の間で発生するリターンコード
+    #     PORT_OK, PORT_ERROR, RECV_EMPTY, RECV_TIMEOUT, CONNETION_LOST,
+    #     UNKNOWN_ERROR
+    #
+    # 各関数が返すリターンコードは関数ごとのリファレンスを参照のこと。
+    #
+    # @else
+    # @brief DataPortStatus return codes
+    #
+    # Common return codes for data ports related classes.
+    #
+    # - PORT_OK:              Normal return
+    # - PORT_ERROR:           Error return
+    # - BUFFER_ERROR:         Buffer error
+    # - BUFFER_FULL:          Buffer full
+    # - BUFFER_EMPTY:         Buffer empty
+    # - BUFFER_TIMEOUT:       Buffer timeout
+    # - SEND_FULL:            Buffer full although OutPort tried to send data
+    # - SEND_TIMEOUT:         Timeout although OutPort tried to send data
+    # - RECV_EMPTY:           Buffer empty although InPort tried to receive
+    #                         data
+    # - RECV_TIMEOUT:         Timeout although InPort tried to receive data
+    # - INVALID_ARGS:         Invalid arguments
+    # - PRECONDITION_NOT_MET: Precondition not met
+    # - CONNECTION_LOST:      Connection has been lost
+    # - UNKNOWN_ERROR:        Unknown error
+    #
+    # This error codes might be used to propagate error status from
+    # the error occurring point to the function caller in the data
+    # stream path. It would occur in data-transfer path and data
+    # receiver/sender. The errors that occur in the interface of each
+    # portion of data port are shown below.
+    #
+    # (1) Push Type
+    #  a) The return codes between InPortConsumer and Publisher/Activity
+    #     PORT_OK, PORT_ERROR, SEND_FULL, SEND_TIMEOUT, CONNECTION_LOST,
+    #     UNKNOWN_ERROR
+    #  b) The return codes between Activity and Buffer/Connector of OutPort
+    #     PORT_OK, PORT_ERROR, BUFFER_ERROR, BUFFER_FULL, BUFFER_TIMEOUT,
+    #     UNKNOWN_ERROR,
+    #
+    # (2) Pull Type
+    #  a) The return codes between Activity and InPort
+    #     PORT_OK, PORT_ERROR, RECV_EMPTY, RECV_TIMEOUT, CONNETION_LOST,
+    #     UNKNOWN_ERROR
+    #
+    # See function references for detailed return codes for each function.
+    #
+    # @endif
+    #
+    PORT_OK = 0
+    PORT_ERROR = 1
+    BUFFER_ERROR = 2
+    BUFFER_FULL = 3
+    BUFFER_EMPTY = 4
+    BUFFER_TIMEOUT = 5
+    SEND_FULL = 6
+    SEND_TIMEOUT = 7
+    RECV_EMPTY = 8
+    RECV_TIMEOUT = 9
+    INVALID_ARGS = 10
+    PRECONDITION_NOT_MET = 11
+    CONNECTION_LOST = 12
+    UNKNOWN_ERROR = 13
 
-  ##
-  # @if jp
-  #
-  # @brief DataPortStatus ꥿󥳡ɤʸѴ
-  #
-  # DataPortStatus ꥿󥳡ɤʸѴ
-  #
-  # @param status Ѵо DataPortStatus ꥿󥳡
-  #
-  # @return ʸѴ
-  #
-  # @else
-  #
-  # @brief Convert DataPortStatus into the string.
-  #
-  # Convert DataPortStatus into the string.
-  #
-  # @param status The target DataPortStatus for transformation
-  #
-  # @return Trnasformation result of string representation
-  #
-  # @endif
-  #
-  def toString(status):
-    str = ["PORT_OK",
-           "PORT_ERROR",
-           "BUFFER_ERROR",
-           "BUFFER_FULL",
-           "BUFFER_EMPTY",
-           "BUFFER_TIMEOUT",
-           "SEND_FULL",
-           "SEND_TIMEOUT",
-           "RECV_EMPTY",
-           "RECV_TIMEOUT",
-           "INVALID_ARGS",
-           "PRECONDITION_NOT_MET",
-           "CONNECTION_LOST",
-           "UNKNOWN_ERROR"]
-    return str[status]
+    ##
+    # @if jp
+    #
+    # @brief DataPortStatus リターンコードを文字列に変換
+    #
+    # DataPortStatus リターンコードを文字列に変換する
+    #
+    # @param status 変換対象 DataPortStatus リターンコード
+    #
+    # @return 文字列変換結果
+    #
+    # @else
+    #
+    # @brief Convert DataPortStatus into the string.
+    #
+    # Convert DataPortStatus into the string.
+    #
+    # @param status The target DataPortStatus for transformation
+    #
+    # @return Trnasformation result of string representation
+    #
+    # @endif
+    #
+    def toString(status):
+        typeString = ["PORT_OK",
+                      "PORT_ERROR",
+                      "BUFFER_ERROR",
+                      "BUFFER_FULL",
+                      "BUFFER_EMPTY",
+                      "BUFFER_TIMEOUT",
+                      "SEND_FULL",
+                      "SEND_TIMEOUT",
+                      "RECV_EMPTY",
+                      "RECV_TIMEOUT",
+                      "INVALID_ARGS",
+                      "PRECONDITION_NOT_MET",
+                      "CONNECTION_LOST",
+                      "UNKNOWN_ERROR"]
+        if status < len(typeString):
+            return typeString[status]
+        return ""
 
-  toString = staticmethod(toString)
+    toString = staticmethod(toString)
diff --git a/OpenRTM_aist/DefaultConfiguration.py b/OpenRTM_aist/DefaultConfiguration.py
index 015d2daa..8f68473f 100644
--- a/OpenRTM_aist/DefaultConfiguration.py
+++ b/OpenRTM_aist/DefaultConfiguration.py
@@ -1,5 +1,5 @@
 #!/usr/bin/env python
-# -*- coding: euc-jp -*-
+# -*- coding: utf-8 -*-
 
 ##
 # \file DefaultConfiguration.py
@@ -15,95 +15,107 @@
 #     All rights reserved.
 
 
-
 import OpenRTM_aist
 import os
 
 
 if os.name == "nt":
     cpp_suffixes = "dll"
+    supported_languages = "C++, Python, Java"
+    lang = "Python"
 elif os.name == "posix":
     cpp_suffixes = "so"
+    supported_languages = "C++, Python, Python3, Java"
+    lang = "Python3"
 else:
     cpp_suffixes = "dylib"
+    supported_languages = "C++, Python, Python3, Java"
+    lang = "Python3"
 
 ##
 # @if jp
-# @brief Manager  ǥեȡե졼
+# @brief Manager 用 デフォルト・コンフィギュレーション
 #
-# Manager饹ѥǥեȥե졼
+# Managerクラス用デフォルトコンフィギュレーション。
 #
 # @since 0.4.0
 #
 # @else
 # @endif
-default_config =["config.version",                   OpenRTM_aist.openrtm_version,
-                 "openrtm.name",                     OpenRTM_aist.openrtm_name,
-                 "openrtm.version",                  OpenRTM_aist.openrtm_version,
-                 "manager.instance_name",            "manager",
-                 "manager.name",                     "manager",
-                 "manager.naming_formats",           "%h.host_cxt/%n.mgr",
-                 "manager.pid",                      "",
-                 "os.name",                          "",
-                 "os.release",                       "",
-                 "os.version",                       "",
-                 "os.arch",                          "",
-                 "os.hostname",                      "",
-                 "logger.enable",                    "YES",
-                 "logger.file_name",                 "./rtc%p.log",
-                 "logger.date_format",               "%b %d %H:%M:%S",
-                 "logger.log_level",                 "INFO",
-                 "logger.stream_lock",               "NO",
-                 "logger.master_logger",             "",
-                 "module.conf_path",                 "",
-                 "module.load_path",                 "",
-                 "naming.enable",                    "YES",
-                 "naming.type",                      "corba",
-                 "naming.formats",                   "%h.host_cxt/%n.rtc",
-                 "naming.update.enable",             "YES",
-                 "naming.update.interval",           "10.0",
-                 "timer.enable",                     "YES",
-                 "timer.tick",                       "0.1",
-                 "corba.args",                       "-ORBclientCallTimeOutPeriod 10000",
-                 "corba.endpoints",                   "all",
-                 "corba.id",                         OpenRTM_aist.corba_name,
-                 "corba.nameservers",               "localhost",
-                 "corba.master_manager",             "localhost:2810",
-                 "corba.nameservice.replace_endpoint", "NO",
-                 "corba.update_master_manager.enable", "YES",
-                 "corba.update_master_manager.interval", "10.0",
-                 "exec_cxt.periodic.type",           "PeriodicExecutionContext",
-                 "exec_cxt.periodic.rate",           "1000",
-                 "exec_cxt.sync_transition",         "YES",
-                 "exec_cxt.transition_timeout",      "0.5",
-                 "manager.modules.load_path",        "./",
-                 "manager.modules.abs_path_allowed", "YES",
-                 "manager.is_master",                "NO",
-                 "manager.corba_servant",            "YES",
-                 "manager.shutdown_on_nortcs",       "YES",
-                 "manager.shutdown_auto",            "YES",
-                 "manager.auto_shutdown_duration",   "10.0",
-                 "manager.termination_waittime",          "1.0",
-                 "manager.name",                     "manager",
-                 "manager.command",                  "rtcd",
-                 "manager.nameservers",               "default",
-                 "manager.language",                 "Python",
-                 "manager.components.naming_policy", "process_unique",
-                 "manager.modules.C++.manager_cmd", "rtcd",
-                 "manager.modules.Python.manager_cmd", "rtcd_python",
-                 "manager.modules.Java.manager_cmd", "rtcd_java",
-                 "manager.modules.search_auto", "YES",
-                 "manager.local_service.enabled_services","ALL",
-                 "sdo.service.provider.enabled_services",  "ALL",
-                 "sdo.service.consumer.enabled_services",  "ALL",
-                 "manager.supported_languages",  "C++, Python, Java",
-                 "manager.modules.C++.profile_cmd",  "rtcprof",
-                 "manager.modules.Python.profile_cmd",  "rtcprof_python",
-                 "manager.modules.Java.profile_cmd",  "rtcprof_java",
-                 "manager.modules.C++.suffixes",  cpp_suffixes,
-                 "manager.modules.Python.suffixes",  "py",
-                 "manager.modules.Java.suffixes",  "class",
-                 "manager.modules.C++.load_paths",  "",
-                 "manager.modules.Python.load_paths",  "",
-                 "manager.modules.Java.load_paths",  "",
-                 ""]
+default_config = ["config.version", OpenRTM_aist.openrtm_version,
+                  "openrtm.name", OpenRTM_aist.openrtm_name,
+                  "openrtm.version", OpenRTM_aist.openrtm_version,
+                  "manager.instance_name", "manager",
+                  "manager.name", "manager",
+                  "manager.naming_formats", "%h.host_cxt/%n.mgr",
+                  "manager.pid", "",
+                  "os.name", "",
+                  "os.release", "",
+                  "os.version", "",
+                  "os.arch", "",
+                  "os.hostname", "",
+                  "logger.enable", "YES",
+                  "logger.file_name", "./rtc%p.log",
+                  "logger.date_format", "%b %d %H:%M:%S",
+                  "logger.log_level", "INFO",
+                  "logger.stream_lock", "NO",
+                  "logger.main_logger", "",
+                  "module.conf_path", "",
+                  "module.load_path", "",
+                  "naming.enable", "YES",
+                  "naming.type", "corba",
+                  "naming.formats", "%h.host_cxt/%n.rtc",
+                  "naming.update.enable", "YES",
+                  "naming.update.interval", "10.0",
+                  "timer.enable", "YES",
+                  "timer.tick", "0.1",
+                  "corba.args", "-ORBclientCallTimeOutPeriod 10000",
+                  "corba.endpoints", "all",
+                  "corba.id", OpenRTM_aist.corba_name,
+                  "corba.nameservers", "localhost",
+                  "corba.main_manager", "localhost:2810",
+                  "corba.nameservice.replace_endpoint", "NO",
+                  "corba.update_main_manager.enable", "YES",
+                  "corba.update_main_manager.interval", "10.0",
+                  "exec_cxt.periodic.type", "PeriodicExecutionContext",
+                  "exec_cxt.periodic.rate", "1000",
+                  "exec_cxt.sync_transition", "YES",
+                  "exec_cxt.transition_timeout", "0.5",
+                  "manager.modules.load_path", "./",
+                  "manager.modules.abs_path_allowed", "YES",
+                  "manager.is_main", "NO",
+                  "manager.corba_servant", "YES",
+                  "manager.shutdown_on_nortcs", "YES",
+                  "manager.shutdown_auto", "YES",
+                  "manager.auto_shutdown_duration", "10.0",
+                  "manager.termination_waittime", "1.0",
+                  "manager.name", "manager",
+                  "manager.command", "rtcd",
+                  "manager.nameservers", "default",
+                  "manager.language", lang,
+                  "manager.components.naming_policy", "process_unique",
+                  "manager.modules.C++.manager_cmd", "rtcd",
+                  "manager.modules.Python.manager_cmd", "rtcd_python",
+                  "manager.modules.Java.manager_cmd", "rtcd_java",
+                  "manager.modules.search_auto", "YES",
+                  "manager.local_service.enabled_services", "ALL",
+                  "sdo.service.provider.enabled_services", "ALL",
+                  "sdo.service.consumer.enabled_services", "ALL",
+                  "manager.supported_languages", supported_languages,
+                  "manager.modules.C++.profile_cmd", "rtcprof",
+                  "manager.modules.Python.profile_cmd", "rtcprof_python",
+                  "manager.modules.Java.profile_cmd", "rtcprof_java",
+                  "manager.modules.C++.suffixes", cpp_suffixes,
+                  "manager.modules.Python.suffixes", "py",
+                  "manager.modules.Java.suffixes", "class",
+                  "manager.modules.C++.load_paths", "",
+                  "manager.modules.Python.load_paths", "",
+                  "manager.modules.Java.load_paths", ""]
+
+if os.name != "nt":
+    python3_config = [
+        "manager.modules.Python3.manager_cmd", "rtcd_python3",
+        "manager.modules.Python3.profile_cmd", "rtcprof_python3",
+        "manager.modules.Python3.suffixes", "py",
+        "manager.modules.Python3.load_paths", ""]
+    default_config.extend(python3_config)
diff --git a/OpenRTM_aist/DefaultPeriodicTask.py b/OpenRTM_aist/DefaultPeriodicTask.py
index f71a86be..38840252 100644
--- a/OpenRTM_aist/DefaultPeriodicTask.py
+++ b/OpenRTM_aist/DefaultPeriodicTask.py
@@ -1,5 +1,5 @@
 #!/usr/bin/env python
-# -*- coding: euc-jp -*-
+# -*- coding: utf-8 -*-
 
 
 ##
@@ -22,6 +22,4 @@
 
 def DefaultPeriodicTaskInit():
     OpenRTM_aist.PeriodicTaskFactory.instance().addFactory("default",
-                                                           OpenRTM_aist.PeriodicTask,
-                                                           OpenRTM_aist.Delete)
-                                                    
+                                                           OpenRTM_aist.PeriodicTask)
diff --git a/OpenRTM_aist/ECFactory.py b/OpenRTM_aist/ECFactory.py
index 7cc233ac..ba54f908 100644
--- a/OpenRTM_aist/ECFactory.py
+++ b/OpenRTM_aist/ECFactory.py
@@ -1,12 +1,12 @@
 #!/usr/bin/env python
-# -*- coding: euc-jp -*-
+# -*- coding: utf-8 -*-
 
 ##
 # @file ECFactory.py
 # @brief ExecutionContext Factory class
 # @date $Date: 2007/04/13 16:06:22 $
 # @author Noriaki Ando  and Shinji Kurihara
-# 
+#
 # Copyright (C) 2007-2008
 #     Task-intelligence Research Group,
 #     Intelligent Systems Research Institute,
@@ -15,112 +15,108 @@
 #     All rights reserved.
 
 
-
-
-
 ##
 # @if jp
 #
-# @brief ExecutionContext˴Ѵؿ
-# 
-# ExecutionContextΥ󥹥󥹤˴뤿δؿ
+# @brief ExecutionContext破棄用関数
 #
-# \param ec ˴оExecutionContextΥ󥹥
+# ExecutionContextのインスタンスを破棄するための関数。
+#
+# \param ec 破棄対象ExecutionContextのインスタンス
 #
 # @else
 #
 # @endif
 def ECDelete(ec):
-  del ec
+    del ec
 
 
 ##
 # @if jp
 # @class ECFactoryBase
-# @brief ECFactoryBase ݥ饹
-# 
-# ExecutionContextFactoryݥ饹
-# ExecutionContext뤿ζFactory饹ϡ
-# ʲδؿμ󶡤ʤФʤʤ
+# @brief ECFactoryBase 抽象クラス
+#
+# ExecutionContext生成用Factoryの抽象クラス。
+# 各ExecutionContextを生成するための具象Factoryクラスは、
+# 以下の関数の実装を提供しなければならない。
 #
-# public󥿡եȤưʲΤΤ󶡤롣
-# - name()   : оExecutionContext̾Τμ
-# - create() : ExecutionContext󥹥󥹤
-# - destroy(): ExecutionContext󥹥󥹤˴
+# publicインターフェースとして以下のものを提供する。
+# - name()   : 生成対象ExecutionContext名称の取得
+# - create() : ExecutionContextインスタンスの生成
+# - destroy(): ExecutionContextインスタンスの破棄
 #
 # @since 0.4.0
 #
 # @else
 #
 # @endif
-class ECFactoryBase :
-  """
-  """
-
-  ##
-  # @if jp
-  #
-  # @brief оExecutionContext̾μѴؿ(֥饹)
-  # 
-  # оExecutionContext̾Τ뤿δؿ
- # δؿ϶ݥ֥饹Ǽɬפ롣 - # - # @param self - # - # @return оExecutionContext̾ - # - # @else - # - # This method should be implemented in subclasses - # - # @endif - def name(self): - pass - - - ## - # @if jp - # - # @brief ExecutionContextѴؿ(֥饹) - # - # ExecutionContextΥ󥹥󥹤뤿δؿ
- # δؿ϶ݥ֥饹Ǽɬפ롣 - # - # @param self - # - # @return ExecutionContext󥹥 - # - # @else - # - # @endif - def create(self): - pass - - ## - # @if jp - # - # @brief ExecutionContext˴Ѵؿ(֥饹) - # - # ExecutionContextΥ󥹥󥹤˴뤿δؿ
- # δؿ϶ݥ֥饹Ǽɬפ롣 - # - # @param self - # @param comp ˴оݤExecutionContext󥹥 - # - # @else - # - # @endif - def destroy(self, ec): - pass - +class ECFactoryBase: + """ + """ + + ## + # @if jp + # + # @brief 生成対象ExecutionContext名称取得用関数(サブクラス実装用) + # + # 生成対象ExecutionContextの名称を取得するための関数。
+ # この関数は具象サブクラスで実装する必要がある。 + # + # @param self + # + # @return 生成対象ExecutionContext名称 + # + # @else + # + # This method should be implemented in subclasses + # + # @endif + def name(self): + pass + + ## + # @if jp + # + # @brief ExecutionContext生成用関数(サブクラス実装用) + # + # ExecutionContextのインスタンスを生成するための関数。
+ # この関数は具象サブクラスで実装する必要がある。 + # + # @param self + # + # @return 生成したExecutionContextインスタンス + # + # @else + # + # @endif + + def create(self): + pass + + ## + # @if jp + # + # @brief ExecutionContext破棄用関数(サブクラス実装用) + # + # ExecutionContextのインスタンスを破棄するための関数。
+ # この関数は具象サブクラスで実装する必要がある。 + # + # @param self + # @param comp 破棄対象のExecutionContextインスタンス + # + # @else + # + # @endif + def destroy(self, ec): + pass ## # @if jp # @class ECFactoryPython -# @brief ECFactoryPython 饹 -# -# PythonExecutionContext󥹥󥹤Factory饹 +# @brief ECFactoryPython クラス +# +# Python言語用ExecutionContextインスタンスを生成するFactoryクラス。 # # @since 0.4.1 # @@ -128,79 +124,78 @@ def destroy(self, ec): # # @endif class ECFactoryPython(ECFactoryBase): - """ - """ - - ## - # @if jp - # - # @brief 󥹥ȥ饯 - # - # 󥹥ȥ饯 - # - # @param self - # @param name оExecutionContext̾ - # @param new_func ExecutionContextѴؿ - # @param delete_func ExecutionContext˴Ѵؿ - # - # @else - # - # @endif - def __init__(self, name, new_func, delete_func): - self._name = name - self._New = new_func - self._Delete = delete_func - - return - - - ## - # @if jp - # - # @brief оExecutionContext̾Τ - # - # оݤExecutionContext̾Τ롣 - # - # @param self - # - # @return оExecutionContext̾ - # - # @else - # - # @endif - def name(self): - return self._name - - ## - # @if jp - # - # @brief оExecutionContext󥹥󥹤 - # - # оݤExecutionContext饹Υ󥹥󥹤롣 - # - # @param self - # - # @return ExecutionContext󥹥 - # - # @else - # - # @endif - def create(self): - return self._New() - - ## - # @if jp - # - # @brief оExecutionContext󥹥󥹤˴ - # - # оExecutionContext饹Υ󥹥󥹤˴롣 - # - # @param self - # @param ec ˴оExecutionContext󥹥 - # - # @else - # - # @endif - def destroy(self, ec): - self._Delete(ec) - + """ + """ + + ## + # @if jp + # + # @brief コンストラクタ + # + # コンストラクタ + # + # @param self + # @param name 生成対象ExecutionContext名称 + # @param new_func ExecutionContext生成用関数 + # @param delete_func ExecutionContext破棄用関数 + # + # @else + # + # @endif + def __init__(self, name, new_func, delete_func): + self._name = name + self._New = new_func + self._Delete = delete_func + + return + + ## + # @if jp + # + # @brief 生成対象ExecutionContext名称を取得 + # + # 生成対象のExecutionContext名称を取得する。 + # + # @param self + # + # @return 生成対象ExecutionContext名称 + # + # @else + # + # @endif + + def name(self): + return self._name + + ## + # @if jp + # + # @brief 生成対象ExecutionContextインスタンスを生成 + # + # 生成対象のExecutionContextクラスのインスタンスを生成する。 + # + # @param self + # + # @return 生成したExecutionContextインスタンス + # + # @else + # + # @endif + def create(self): + return self._New() + + ## + # @if jp + # + # @brief 対象ExecutionContextインスタンスを破棄 + # + # 対象ExecutionContextクラスのインスタンスを破棄する。 + # + # @param self + # @param ec 破棄対象ExecutionContextインスタンス + # + # @else + # + # @endif + def destroy(self, ec): + self._Delete(ec) diff --git a/OpenRTM_aist/EventDrivenExecutionContext.py b/OpenRTM_aist/EventDrivenExecutionContext.py index 40864e88..0b033bd1 100644 --- a/OpenRTM_aist/EventDrivenExecutionContext.py +++ b/OpenRTM_aist/EventDrivenExecutionContext.py @@ -1,5 +1,5 @@ #!/usr/bin/env python -# -*- coding: euc-jp -*- +# -*- coding: utf-8 -*- ## # @file EventDrivenExecutionContext.py @@ -15,17 +15,15 @@ # All rights reserved. - - import OpenRTM_aist import RTC ## # @if jp # @class PeriodicExecutionContext -# @brief PeriodicExecutionContext 饹 +# @brief PeriodicExecutionContext クラス # -# Periodic EventDrivenExecutionContext饹 +# Periodic EventDrivenExecutionContextクラス。 # # @since 2.0.0 # @@ -33,42 +31,42 @@ # @class EventDrivenExecutionContext # @brief EventDrivenExecutionContext class # @endif -class EventDrivenExecutionContext(OpenRTM_aist.PeriodicExecutionContext): - """ - """ - ## - # @if jp - # @brief 󥹥ȥ饯 - # - # 󥹥ȥ饯 - # ꤵ줿ͤץեꤹ롣 - # - # @else - # @brief Constructor - # @endif - def __init__(self): - OpenRTM_aist.PeriodicExecutionContext.__init__(self) - self._rtcout = OpenRTM_aist.Manager.instance().getLogbuf("rtobject.eventdriven_ec") - self.setKind(RTC.EVENT_DRIVEN) - return +class EventDrivenExecutionContext(OpenRTM_aist.PeriodicExecutionContext): + """ + """ + + ## + # @if jp + # @brief コンストラクタ + # + # コンストラクタ + # 設定された値をプロファイルに設定する。 + # + # @else + # @brief Constructor + # @endif + def __init__(self): + OpenRTM_aist.PeriodicExecutionContext.__init__(self) + self._rtcout = OpenRTM_aist.Manager.instance().getLogbuf("rtobject.eventdriven_ec") + self.setKind(RTC.EVENT_DRIVEN) + return ## # @if jp -# @brief ExecutionContext +# @brief ExecutionContext を初期化する # -# ExecutionContext ưѥեȥϿ롣 +# ExecutionContext 起動用ファクトリを登録する。 # -# @param manager ޥ͡㥪֥ +# @param manager マネージャオブジェクト # # @else # # @endif def EventDrivenExecutionContextInit(manager): - OpenRTM_aist.ExecutionContextFactory.instance().addFactory("EventDrivenExecutionContext", - OpenRTM_aist.EventDrivenExecutionContext, - OpenRTM_aist.ECDelete) - return + OpenRTM_aist.ExecutionContextFactory.instance().addFactory("EventDrivenExecutionContext", + OpenRTM_aist.EventDrivenExecutionContext) + return diff --git a/OpenRTM_aist/EventPort.py b/OpenRTM_aist/EventPort.py index 0bcc2770..8604cc17 100644 --- a/OpenRTM_aist/EventPort.py +++ b/OpenRTM_aist/EventPort.py @@ -1,5 +1,5 @@ #!/usr/bin/env python -# -*- coding: euc-jp -*- +# -*- coding: utf-8 -*- ## # @file EventPort.py @@ -18,91 +18,480 @@ import copy - +## +# @if jp +# +# @class Event0 +# +# @brief 引数なしのイベントを格納するクラス +# イベント受信時にリスナを格納し、Event0オブジェクトをバッファに格納する +# 実行時は__call__メソッドによりイベントを実行できる +# +# @since 2.0.0 +# +# @else +# +# @class Event0 +# +# @brief +# +# @since 2.0.0 +# +# +# @endif +# class Event0: - def __init__(self, eb): - self._eb = eb - def __call__(self): - self._eb.run() - - -class Event1(Event0): - def __init__(self, eb, data): - Event0.__init__(self, eb) - self._data = data - def __call__(self): - self._eb.run(self._data) + ## + # @if jp + # + # @brief コンストラクタ + # + # @param self + # @param eb イベント受信時のリスナ + # + # @else + # + # @brief A constructor. + # + # @param self + # @param eb + # + # @endif + # + def __init__(self, eb): + self._eb = eb + ## + # @if jp + # + # @brief イベント実行 + # + # @param self + # + # @else + # + # @brief + # + # @param self + # + # @endif + # + + def __call__(self): + self._eb.run() +## +# @if jp +# +# @class Event1 +# +# @brief 引数1つのイベントを格納するクラス +# イベント受信時にリスナ、引数を格納し、Event1オブジェクトをバッファに格納する +# 実行時は__call__メソッドによりイベントを実行できる +# +# @since 2.0.0 +# +# @else +# +# @class Event1 +# +# @brief +# +# @since 2.0.0 +# +# +# @endif +# -class EventBinder0(OpenRTM_aist.ConnectorDataListener): - def __init__(self, fsm, event_name, handler, buffer): - self._fsm = fsm - self._eventName = event_name - self._handler = handler - self._buffer = buffer - - - - def __del__(self): - pass - def __call__(self, info, data): - if info.properties.getProperty("fsm_event_name") == self._eventName or info.name == self._eventName: - self._buffer.write(Event0(self)) - - return OpenRTM_aist.ConnectorListenerStatus.NO_CHANGE - return OpenRTM_aist.ConnectorListenerStatus.NO_CHANGE - - def run(self): - self._fsm.dispatch(OpenRTM_aist.Macho.Event(self._handler)) - - - - -class EventBinder1(OpenRTM_aist.ConnectorDataListenerT): - def __init__(self, fsm, event_name, handler, data_type, buffer): - self._fsm = fsm - self._eventName = event_name - self._handler = handler - self._data_type = data_type - self._buffer = buffer - - - def __del__(self): - pass - def __call__(self, info, data): - data_ = OpenRTM_aist.ConnectorDataListenerT.__call__(self, info, data, self._data_type) - - if info.properties.getProperty("fsm_event_name") == self._eventName or info.name == self._eventName: - self._buffer.write(Event1(self, data_)) - return OpenRTM_aist.ConnectorListenerStatus.NO_CHANGE - return OpenRTM_aist.ConnectorListenerStatus.NO_CHANGE - - def run(self, data): - self._fsm.dispatch(OpenRTM_aist.Macho.Event(self._handler, data)) +class Event1(Event0): + ## + # @if jp + # + # @brief コンストラクタ + # + # @param self + # @param eb イベント受信時のリスナ + # @param data イベント実行時に指定する引数 + # + # @else + # + # @brief A constructor. + # + # @param self + # @param eb + # @param data + # + # @endif + # + def __init__(self, eb, data): + Event0.__init__(self, eb) + self._data = data + ## + # @if jp + # + # @brief イベント実行 + # + # @param self + # + # @else + # + # @brief + # + # @param self + # + # @endif + # + + def __call__(self): + self._eb.run(self._data) +## +# @if jp +# +# @class EventBinder0 +# +# @brief 引数なしのイベント受信時のリスナ +# InPortのON_RECEIVEDコールバックに指定することで、 +# イベント受信時にバッファにイベントを格納する +# +# +# @since 2.0.0 +# +# @else +# +# @class EventBinder0 +# +# @brief +# +# @since 2.0.0 +# +# +# @endif +# -class EventConnListener(OpenRTM_aist.ConnectorListener): - def __init__(self, buffer, thebuffer): - self._buffer = buffer - self._thebuffer = thebuffer - def __del__(self): - pass +class EventBinder0(OpenRTM_aist.ConnectorDataListener): + ## + # @if jp + # + # @brief コンストラクタ + # + # @param self + # @param fsm 有限状態マシン + # @param event_name イベント名 + # @param handler イベントハンドラ + # @param buffer イベントを格納するバッファ + # + # @else + # + # @brief A constructor. + # + # @param self + # @param fsm + # @param event_name + # @param handler + # @param buffer + # + # @endif + # + def __init__(self, fsm, event_name, handler, buffer): + self._fsm = fsm + self._eventName = event_name + self._handler = handler + self._buffer = buffer + + ## + # @if jp + # + # @brief デストラクタ + # + # @param self + # + # @else + # + # @brief A destructor. + # + # @param self + # + # @endif + # + def __del__(self): + pass + ## + # @if jp + # + # @brief イベント受信時のコールバック関数 + # コネクタプロファイルのfsm_event_nameの値がイベント名と一致している場合、バッファにイベントを格納する + # + # @param self + # @param info コネクタプロファイル + # @param data 受信データ + # @return リターンコード + # + # @else + # + # @brief + # + # @param self + # @param info + # @param data + # @return + # + # @endif + # + + def __call__(self, info, cdrdata): + if info.properties.getProperty( + "fsm_event_name") == self._eventName or info.name == self._eventName: + self._buffer.write(Event0(self)) + + return OpenRTM_aist.ConnectorListenerStatus.NO_CHANGE, cdrdata + return OpenRTM_aist.ConnectorListenerStatus.NO_CHANGE, cdrdata + + ## + # @if jp + # + # @brief イベント実行関数 + # イベントハンドラに指定した処理を実行する + # + # @param self + # + # @else + # + # @brief + # + # @param self + # + # @endif + # + def run(self): + self._fsm.dispatch(OpenRTM_aist.Macho.Event(self._handler)) - def __call__(self, info): - prop = OpenRTM_aist.Properties() - prop.setProperty("write.full_policy", "do_nothing") - prop.setProperty("read.empty_policy", "do_nothing") - self._thebuffer.init(prop) - prop_ = copy.copy(info.properties.getNode("dataport.buffer")) - prop_.mergeProperties(info.properties.getNode("inport.buffer")) - - self._buffer.init(prop_) - return OpenRTM_aist.ConnectorListenerStatus.NO_CHANGE +## +# @if jp +# +# @class EventBinder1 +# +# @brief 引数1つのイベント受信時のリスナ +# InPortのON_RECEIVEDコールバックに指定することで、 +# イベント受信時にバッファにイベントを格納する +# +# +# @since 2.0.0 +# +# @else +# +# @class EventBinder1 +# +# @brief +# +# @since 2.0.0 +# +# +# @endif +# +class EventBinder1(OpenRTM_aist.ConnectorDataListener): + ## + # @if jp + # + # @brief コンストラクタ + # + # @param self + # @param fsm 有限状態マシン + # @param event_name イベント名 + # @param handler イベントハンドラ + # @param data_type 入力データ型 + # @param buffer イベントを格納するバッファ + # + # @else + # + # @brief A constructor. + # + # @param self + # @param fsm + # @param event_name + # @param handler + # @param data_type + # @param buffer + # + # @endif + # + def __init__(self, fsm, event_name, handler, data_type, buffer): + self._fsm = fsm + self._eventName = event_name + self._handler = handler + self._data_type = data_type + self._buffer = buffer + + ## + # @if jp + # + # @brief デストラクタ + # + # @param self + # + # @else + # + # @brief A destructor. + # + # @param self + # + # @endif + # + def __del__(self): + pass + + ## + # @if jp + # + # @brief イベント受信時のコールバック関数 + # コネクタプロファイルのfsm_event_nameの値がイベント名と一致している場合、バッファにイベントを格納する + # + # @param self + # @param info コネクタプロファイル + # @param data 受信データ + # @return リターンコード + # + # @else + # + # @brief + # + # @param self + # @param info + # @param data + # @return + # + # @endif + # + def __call__(self, info, cdrdata): + data_ = OpenRTM_aist.ConnectorDataListenerT.__call__( + self, info, cdrdata, self._data_type, OpenRTM_aist.PortType.InPortType) + if info.properties.getProperty( + "fsm_event_name") == self._eventName or info.name == self._eventName: + self._buffer.write(Event1(self, data_)) + return OpenRTM_aist.ConnectorListenerStatus.NO_CHANGE, cdrdata + return OpenRTM_aist.ConnectorListenerStatus.NO_CHANGE, cdrdata + + ## + # @if jp + # + # @brief イベント実行関数 + # イベントハンドラに指定した処理を実行する + # + # @param self + # @param data 受信データ + # + # @else + # + # @brief + # + # @param self + # @param data + # + # @endif + # + def run(self, data): + self._fsm.dispatch(OpenRTM_aist.Macho.Event(self._handler, data)) +## +# @if jp +# +# @class EventConnListener +# +# @brief コネクタ接続時のリスナ +# InPortのON_CONNECTコールバックに指定する +# ポートが保持するバッファのwrite.full_policy、read.empty_policyをdo_nothingに設定することで、 +# ポートが保持するバッファのデータ読み込み、書き込み時にブロックやエラー等を発生させないようにする +# 有限状態マシンが保持するバッファの初期化を行う +# このため、後で接続したコネクタの設定でバッファの設定が上書きされる +# +# +# @since 2.0.0 +# +# @else +# +# @class EventConnListener +# +# @brief +# +# @since 2.0.0 +# +# +# @endif +# +class EventConnListener(OpenRTM_aist.ConnectorListener): + ## + # @if jp + # + # @brief コンストラクタ + # + # @param self + # @param buffer + # @param thebuffer + # + # @else + # + # @brief A constructor. + # + # @param self + # @param buffer + # @param thebuffer + # + # @endif + # + def __init__(self, buffer, thebuffer): + self._buffer = buffer + self._thebuffer = thebuffer + + ## + # @if jp + # + # @brief デストラクタ + # + # @param self + # + # @else + # + # @brief A destructor. + # + # @param self + # + # @endif + # + def __del__(self): + pass + + ## + # @if jp + # + # @brief コネクタ接続時のコールバック関数 + # + # @param self + # @param info コネクタプロファイル + # @return リターンコード + # + # @else + # + # @brief + # + # @param self + # @param info + # @return + # + # @endif + # + def __call__(self, info): + prop = OpenRTM_aist.Properties() + prop.setProperty("write.full_policy", "do_nothing") + prop.setProperty("read.empty_policy", "do_nothing") + self._thebuffer.init(prop) + + prop_ = copy.copy(info.properties.getNode("buffer")) + + self._buffer.init(prop_) + return OpenRTM_aist.ConnectorListenerStatus.NO_CHANGE ## @@ -110,28 +499,28 @@ def __call__(self, info): # # @class EventInPort # -# @brief EventInPort ƥץ졼ȥ饹 -# -# EventInPort μǤ EventInPort Υƥץ졼ȥ饹 -# BasicDataType.idl ˤƤ뷿ǡФȤ -# Time tm , T data ŤΤǤʤƤϤʤʤ -# EventInPort ˥󥰥Хåե줿ǡ缡 -# Υ󥰥Хåե˳Ǽ롣󥰥ХåեΥϥǥեȤ64 -# ʤäƤ뤬󥹥ȥ饯ˤꥵꤹ뤳ȤǤ롣 -# ǡϥե饰ˤä̤ɡɾ֤졢isNew(), write(), read(), -# isFull(), isEmpty() Υ᥽åɤˤϥɥ󥰤뤳ȤǤ롣 -# -# OnReadϥХå (ɤ߽Ф˵륤٥Ȥˤꥳ뤵) -# -# - void OnRead::operator(): -# EventInPort::read() ƤӽФɤ߽ФԤݤ˥뤵롣 -# -# - DataType OnReadConvert::operator(DataType): -# EventInPort::read() ƤӽФǡХåեɤߤݤ˸ƤФ -# ǡѴԤˤϥХåեɤ߽Ф줿ͤͿ졢 -# ѴΥǡͤȤ֤ͤread()֤ͤȤʤ롣 -# -# @since 0.2.0 +# @brief EventInPort テンプレートクラス +# +# EventInPort の実装である EventInPort のテンプレートクラス。 +# はBasicDataType.idl にて定義されている型で、メンバとして +# Time 型の tm , および T型の data を持つ構造体でなくてはならない。 +# EventInPort は内部にリングバッファを持ち、外部から送信されたデータを順次 +# このリングバッファに格納する。リングバッファのサイズはデフォルトで8と +# なっているが、コンストラクタ引数によりサイズを指定することができる。 +# データはフラグによって未読、既読状態が管理され、isNew(), write(), read(), +# isFull(), isEmpty() 等のメソッドによりハンドリングすることができる。 +# +# OnRead系コールバック (読み出しに起因するイベントによりコールされる) +# +# - void OnRead::operator(): +# EventInPort::read() を呼び出し読み出しを行う際にコールされる。 +# +# - DataType OnReadConvert::operator(DataType): +# EventInPort::read() を呼び出し、データをバッファから読みだす際に呼ばれ +# データの変換を行う。引数にはバッファから読み出された値が与えられ、 +# 変換後のデータを戻り値として返す。この値がread()の返す値となる。 +# +# @since 2.0.0 # # @else # @@ -145,137 +534,156 @@ def __call__(self, info): # buffer internally, and stores the received data externally in # this buffer one by one. The size of ring buffer can be specified # according to the argument of constructor, though the default size -# is 64. Unread data and data which is already read are managed +# is 8. Unread data and data which is already read are managed # with the flag, and the data can be handled by the isNew(), # write(), read(), isFull() and isEmpty() method etc. # -# @since 0.2.0 +# @since 2.0.0 # # @endif # class EventInPort(OpenRTM_aist.InPortBase): - ## - # @if jp - # - # @brief 󥹥ȥ饯 - # - # 󥹥ȥ饯 - # ѥ᡼ȤͿ T ѿ˥Хɤ롣 - # - # @param name EventInPort ̾EventInPortBase:name() ˤ껲Ȥ롣 - # @param value EventInPort ˥Хɤ T ѿ - # @param bufsize EventInPort Υ󥰥ХåեΥХåեĹ(ǥե:64) - # @param read_block ɹ֥åե饰 - # ǡɹ̤ɥǡʤ硢Υǡޤǥ֥å - # ɤ(ǥե:false) - # @param write_block ֥åե饰 - # ǡ˥ХåեեǤä硢Хåե˶Ǥ - # ޤǥ֥å뤫ɤ(ǥե:false) - # @param read_timeout ɹ֥åꤷƤʤΡǡɼ西 - # Ȼ(ߥ)(ǥե:0) - # @param write_timeout ֥åꤷƤʤΡǡ - # Ȼ(ߥ)(ǥե:0) - # - # @else - # - # @brief A constructor. - # - # constructor. - # This is bound to type-T variable given as a parameter. - # - # @param name A name of the EventInPort. This name is referred by - # EventInPortBase::name(). - # @param value type-T variable that is bound to this EventInPort. - # @param bufsize Buffer length of internal ring buffer of EventInPort - # (The default value:64) - # @param read_block Flag of reading block. - # When there are not unread data at reading data, - # set whether to block data until receiving the next - # data. (The default value:false) - # @param write_block Flag of writing block. - # If the buffer was full at writing data, set whether - # to block data until the buffer has space. - # (The default value:false) - # @param read_timeout Data reading timeout time (millisecond) - # when not specifying read blocking. - # (The default value:0) - # @param write_timeout Data writing timeout time (millisecond) - # when not specifying writing block. - # (The default value:0) - # - # @endif - # - def __init__(self, name, fsm, bufsize=64, read_block=False, write_block=False, read_timeout=0, write_timeout=0): - super(EventInPort, self).__init__(name, "any") - self._name = name - self._fsm = fsm - self._buffer = self._fsm.getBuffer() - - - - - - - ## - # @if jp - # - # @brief ǥȥ饯 - # - # ǥȥ饯 - # - # @else - # - # @brief Destructor - # - # Destructor - # - # @endif - # - def __del__(self): - pass - ## - # @if jp - # - # @brief ݡ̾Τ롣 - # - # ݡ̾Τ롣 - # - # @return ݡ̾ - # - # @else - # - # @brief Get port name - # - # Get port name. - # - # @return The port name - # - # @endif - # - def name(self): - return self._name - def init(self, prop): - OpenRTM_aist.InPortBase.init(self, prop) - self.addConnectorListener(OpenRTM_aist.ConnectorListenerType.ON_CONNECT, - EventConnListener(self._buffer, self._thebuffer)) - - def bindEvent0(self, name, handler): - self.addConnectorDataListener(OpenRTM_aist.ConnectorDataListenerType.ON_RECEIVED, - EventBinder0(self._fsm, name, handler, self._buffer)) - - def bindEvent1(self, name, handler, data_type): - self.addConnectorDataListener(OpenRTM_aist.ConnectorDataListenerType.ON_RECEIVED, - EventBinder1(self._fsm, name, handler, data_type, self._buffer)) - - - - - - - - - - - - - + ## + # @if jp + # + # @brief コンストラクタ + # + # コンストラクタ。 + # パラメータとして与えられる T 型の変数にバインドされる。 + # + # @param name EventInPort 名。EventInPortBase:name() により参照される。 + # @param value この EventInPort にバインドされる T 型の変数 + # + # @else + # + # @brief A constructor. + # + # constructor. + # This is bound to type-T variable given as a parameter. + # + # @param name A name of the EventInPort. This name is referred by + # EventInPortBase::name(). + # @param value type-T variable that is bound to this EventInPort. + # + # @endif + # + def __init__(self, name, fsm): + super(EventInPort, self).__init__(name, "any") + self._name = name + self._fsm = fsm + self._buffer = self._fsm.getBuffer() + + ## + # @if jp + # + # @brief デストラクタ + # + # デストラクタ。 + # + # @else + # + # @brief Destructor + # + # Destructor + # + # @endif + # + + def __del__(self): + super(EventInPort, self).__del__() + ## + # @if jp + # + # @brief ポート名称を取得する。 + # + # ポート名称を取得する。 + # + # @return ポート名称 + # + # @else + # + # @brief Get port name + # + # Get port name. + # + # @return The port name + # + # @endif + # + + def name(self): + return self._name + ## + # @if jp + # + # @brief 初期化 + # InPortBaseの初期化のほかにバッファ初期化のためのコネクタコールバック関数の登録を行う + # + # @param prop 設定情報 + # + # + # @else + # + # @brief + # + # + # @param prop + # + # @endif + # + + def init(self, prop): + OpenRTM_aist.InPortBase.init(self, prop) + self.addConnectorListener(OpenRTM_aist.ConnectorListenerType.ON_CONNECT, + EventConnListener(self._buffer, self._thebuffer)) + ## + # @if jp + # + # @brief 引数なしのイベントハンドラを登録する + # コネクタのON_RECEIVEDコールバック実行時にバッファに実行予定のイベントとして格納する + # バッファに格納したイベントはMachineのrun_event関数で実行する + # + # @param name イベント名 + # @param handler イベントハンドラ + # + # + # @else + # + # @brief + # + # @param name + # @param handler + # + # @endif + # + + def bindEvent0(self, name, handler): + self.addConnectorDataListener(OpenRTM_aist.ConnectorDataListenerType.ON_RECEIVED, + EventBinder0(self._fsm, name, handler, self._buffer)) + ## + # @if jp + # + # @brief 引数1つのイベントハンドラを登録する + # コネクタのON_RECEIVEDコールバック実行時にバッファに実行予定のイベントとして格納する + # バッファに格納したイベントはMachineのrun_event関数で実行する + # + # @param name イベント名 + # @param handler イベントハンドラ + # @param data_type データ型 + # + # + # @else + # + # @brief + # + # + # @param name + # @param handler + # @param data_type + # + # @endif + # + + def bindEvent1(self, name, handler, data_type): + self.addConnectorDataListener(OpenRTM_aist.ConnectorDataListenerType.ON_RECEIVED, + EventBinder1(self._fsm, name, handler, data_type, self._buffer)) diff --git a/OpenRTM_aist/EventPort_pyfsm.py b/OpenRTM_aist/EventPort_pyfsm.py index 477e5f22..9cc87eae 100644 --- a/OpenRTM_aist/EventPort_pyfsm.py +++ b/OpenRTM_aist/EventPort_pyfsm.py @@ -1,5 +1,5 @@ #!/usr/bin/env python -# -*- coding: euc-jp -*- +# -*- coding: utf-8 -*- ## # @file EventPort_pyfsm.py @@ -17,78 +17,86 @@ import OpenRTM_aist.StaticFSM_pyfsm import pyfsm + class Event0: - def __init__(self, eb): - self._eb = eb - def __call__(self): - self._eb.run() + def __init__(self, eb): + self._eb = eb + + def __call__(self): + self._eb.run() class Event1(Event0): - def __init__(self, eb, data): - Event0.__init__(self, eb) - self._data = data - def __call__(self): - self._eb.run(self._data) + def __init__(self, eb, data): + Event0.__init__(self, eb) + self._data = data + + def __call__(self): + self._eb.run(self._data) + class EventBinder0(OpenRTM_aist.ConnectorDataListener): - def __init__(self, fsm, event_name, handler, buffer): - self._fsm = fsm - self._eventName = event_name - self._handler = handler - self._buffer = buffer - - def __del__(self): - pass - def __call__(self, info, data): - if info.properties.getProperty("fsm_event_name") == self._eventName or info.name == self._eventName: - self._buffer.write(Event0(self)) - return OpenRTM_aist.ConnectorListenerStatus.NO_CHANGE - return OpenRTM_aist.ConnectorListenerStatus.NO_CHANGE - - def run(self): - self._fsm.dispatch(pyfsm.Event(self._handler)) - - -class EventBinder1(OpenRTM_aist.ConnectorDataListenerT): - def __init__(self, fsm, event_name, handler, data_type, buffer): - self._fsm = fsm - self._eventName = event_name - self._handler = handler - self._data_type = data_type - self._buffer = buffer - - def __del__(self): - pass - def __call__(self, info, data): - data_ = OpenRTM_aist.ConnectorDataListenerT.__call__(self, info, data, self._data_type) - - if info.properties.getProperty("fsm_event_name") == self._eventName or info.name == self._eventName: - self._buffer.write(Event1(self, data_)) - return OpenRTM_aist.ConnectorListenerStatus.NO_CHANGE - return OpenRTM_aist.ConnectorListenerStatus.NO_CHANGE - - def run(self, data): - self._fsm.dispatch(pyfsm.Event(self._handler, data_)) + def __init__(self, fsm, event_name, handler, buffer): + self._fsm = fsm + self._eventName = event_name + self._handler = handler + self._buffer = buffer + + def __del__(self): + pass + + def __call__(self, info, cdrdata): + if info.properties.getProperty( + "fsm_event_name") == self._eventName or info.name == self._eventName: + self._buffer.write(Event0(self)) + + return OpenRTM_aist.ConnectorListenerStatus.NO_CHANGE, cdrdata + return OpenRTM_aist.ConnectorListenerStatus.NO_CHANGE, cdrdata + + def run(self): + self._fsm.dispatch(pyfsm.Event(self._handler)) + + +class EventBinder1(OpenRTM_aist.ConnectorDataListener): + def __init__(self, fsm, event_name, handler, data_type, buffer): + self._fsm = fsm + self._eventName = event_name + self._handler = handler + self._data_type = data_type + self._buffer = buffer + + def __del__(self): + pass + + def __call__(self, info, cdrdata): + data_ = OpenRTM_aist.ConnectorDataListenerT.__call__( + self, info, cdrdata, self._data_type, OpenRTM_aist.PortType.InPortType) + if info.properties.getProperty( + "fsm_event_name") == self._eventName or info.name == self._eventName: + self._buffer.write(Event1(self, data_)) + return OpenRTM_aist.ConnectorListenerStatus.NO_CHANGE, cdrdata + return OpenRTM_aist.ConnectorListenerStatus.NO_CHANGE, cdrdata + + def run(self, data): + self._fsm.dispatch(pyfsm.Event(self._handler, data_)) class EventConnListener(OpenRTM_aist.ConnectorListener): - def __init__(self, buffer, thebuffer): - self._buffer = buffer - self._thebuffer = thebuffer + def __init__(self, buffer, thebuffer): + self._buffer = buffer + self._thebuffer = thebuffer - def __del__(self): - pass + def __del__(self): + pass - def __call__(self, info): - prop = OpenRTM_aist.Properties() - prop.setProperty("write.full_policy", "do_nothing") - prop.setProperty("read.empty_policy", "do_nothing") - self._thebuffer.init(prop) + def __call__(self, info): + prop = OpenRTM_aist.Properties() + prop.setProperty("write.full_policy", "do_nothing") + prop.setProperty("read.empty_policy", "do_nothing") + self._thebuffer.init(prop) - - self._buffer.init(info.properties.getNode("inport.buffer")) - return OpenRTM_aist.ConnectorListenerStatus.NO_CHANGE + self._buffer.init(info.properties.getNode("inport.buffer")) + return OpenRTM_aist.ConnectorListenerStatus.NO_CHANGE ## @@ -96,26 +104,26 @@ def __call__(self, info): # # @class EventInPort # -# @brief EventInPort ƥץ졼ȥ饹 -# -# EventInPort μǤ EventInPort Υƥץ졼ȥ饹 -# BasicDataType.idl ˤƤ뷿ǡФȤ -# Time tm , T data ŤΤǤʤƤϤʤʤ -# EventInPort ˥󥰥Хåե줿ǡ缡 -# Υ󥰥Хåե˳Ǽ롣󥰥ХåեΥϥǥեȤ64 -# ʤäƤ뤬󥹥ȥ饯ˤꥵꤹ뤳ȤǤ롣 -# ǡϥե饰ˤä̤ɡɾ֤졢isNew(), write(), read(), -# isFull(), isEmpty() Υ᥽åɤˤϥɥ󥰤뤳ȤǤ롣 -# -# OnReadϥХå (ɤ߽Ф˵륤٥Ȥˤꥳ뤵) +# @brief EventInPort テンプレートクラス +# +# EventInPort の実装である EventInPort のテンプレートクラス。 +# はBasicDataType.idl にて定義されている型で、メンバとして +# Time 型の tm , および T型の data を持つ構造体でなくてはならない。 +# EventInPort は内部にリングバッファを持ち、外部から送信されたデータを順次 +# このリングバッファに格納する。リングバッファのサイズはデフォルトで64と +# なっているが、コンストラクタ引数によりサイズを指定することができる。 +# データはフラグによって未読、既読状態が管理され、isNew(), write(), read(), +# isFull(), isEmpty() 等のメソッドによりハンドリングすることができる。 # -# - void OnRead::operator(): -# EventInPort::read() ƤӽФɤ߽ФԤݤ˥뤵롣 +# OnRead系コールバック (読み出しに起因するイベントによりコールされる) # -# - DataType OnReadConvert::operator(DataType): -# EventInPort::read() ƤӽФǡХåեɤߤݤ˸ƤФ -# ǡѴԤˤϥХåեɤ߽Ф줿ͤͿ졢 -# ѴΥǡͤȤ֤ͤread()֤ͤȤʤ롣 +# - void OnRead::operator(): +# EventInPort::read() を呼び出し読み出しを行う際にコールされる。 +# +# - DataType OnReadConvert::operator(DataType): +# EventInPort::read() を呼び出し、データをバッファから読みだす際に呼ばれ +# データの変換を行う。引数にはバッファから読み出された値が与えられ、 +# 変換後のデータを戻り値として返す。この値がread()の返す値となる。 # # @since 0.2.0 # @@ -140,116 +148,113 @@ def __call__(self, info): # @endif # class EventInPort(OpenRTM_aist.InPortBase): - ## - # @if jp - # - # @brief 󥹥ȥ饯 - # - # 󥹥ȥ饯 - # ѥ᡼ȤͿ T ѿ˥Хɤ롣 - # - # @param name EventInPort ̾EventInPortBase:name() ˤ껲Ȥ롣 - # @param value EventInPort ˥Хɤ T ѿ - # @param bufsize EventInPort Υ󥰥ХåեΥХåեĹ(ǥե:64) - # @param read_block ɹ֥åե饰 - # ǡɹ̤ɥǡʤ硢Υǡޤǥ֥å - # ɤ(ǥե:false) - # @param write_block ֥åե饰 - # ǡ˥ХåեեǤä硢Хåե˶Ǥ - # ޤǥ֥å뤫ɤ(ǥե:false) - # @param read_timeout ɹ֥åꤷƤʤΡǡɼ西 - # Ȼ(ߥ)(ǥե:0) - # @param write_timeout ֥åꤷƤʤΡǡ - # Ȼ(ߥ)(ǥե:0) - # - # @else - # - # @brief A constructor. - # - # constructor. - # This is bound to type-T variable given as a parameter. - # - # @param name A name of the EventInPort. This name is referred by - # EventInPortBase::name(). - # @param value type-T variable that is bound to this EventInPort. - # @param bufsize Buffer length of internal ring buffer of EventInPort - # (The default value:64) - # @param read_block Flag of reading block. - # When there are not unread data at reading data, - # set whether to block data until receiving the next - # data. (The default value:false) - # @param write_block Flag of writing block. - # If the buffer was full at writing data, set whether - # to block data until the buffer has space. - # (The default value:false) - # @param read_timeout Data reading timeout time (millisecond) - # when not specifying read blocking. - # (The default value:0) - # @param write_timeout Data writing timeout time (millisecond) - # when not specifying writing block. - # (The default value:0) - # - # @endif - # - def __init__(self, name, fsm, bufsize=64, read_block=False, write_block=False, read_timeout=0, write_timeout=0): - super(EventInPort, self).__init__(name, "any") - self._name = name - self._fsm = fsm - self._buffer = self._fsm.getBuffer() - - ## - # @if jp - # - # @brief ǥȥ饯 - # - # ǥȥ饯 - # - # @else - # - # @brief Destructor - # - # Destructor - # - # @endif - # - def __del__(self): - pass - ## - # @if jp - # - # @brief ݡ̾Τ롣 - # - # ݡ̾Τ롣 - # - # @return ݡ̾ - # - # @else - # - # @brief Get port name - # - # Get port name. - # - # @return The port name - # - # @endif - # - def name(self): - return self._name - - def init(self, prop): - OpenRTM_aist.InPortBase.init(self, prop) - self.addConnectorListener(OpenRTM_aist.ConnectorListenerType.ON_CONNECT, - EventConnListener(self._buffer, self._thebuffer)) - - def bindEvent0(self, name, handler): - self.addConnectorDataListener(OpenRTM_aist.ConnectorDataListenerType.ON_RECEIVED, - EventBinder0(self._fsm, name, handler, self._buffer)) - - def bindEvent1(self, name, handler, data_type): - self.addConnectorDataListener(OpenRTM_aist.ConnectorDataListenerType.ON_RECEIVED, - EventBinder1(self._fsm, name, handler, data_type, self._buffer)) - + ## + # @if jp + # + # @brief コンストラクタ + # + # コンストラクタ。 + # パラメータとして与えられる T 型の変数にバインドされる。 + # + # @param name EventInPort 名。EventInPortBase:name() により参照される。 + # @param value この EventInPort にバインドされる T 型の変数 + # @param bufsize EventInPort 内部のリングバッファのバッファ長(デフォルト値:64) + # @param read_block 読込ブロックフラグ。 + # データ読込時に未読データがない場合、次のデータ受信までブロックする + # かどうかを設定(デフォルト値:false) + # @param write_block 書込ブロックフラグ。 + # データ書込時にバッファがフルであった場合、バッファに空きができる + # までブロックするかどうかを設定(デフォルト値:false) + # @param read_timeout 読込ブロックを指定していない場合の、データ読取タイム + # アウト時間(ミリ秒)(デフォルト値:0) + # @param write_timeout 書込ブロックを指定していない場合の、データ書込タイム + # アウト時間(ミリ秒)(デフォルト値:0) + # + # @else + # + # @brief A constructor. + # + # constructor. + # This is bound to type-T variable given as a parameter. + # + # @param name A name of the EventInPort. This name is referred by + # EventInPortBase::name(). + # @param value type-T variable that is bound to this EventInPort. + # @param bufsize Buffer length of internal ring buffer of EventInPort + # (The default value:64) + # @param read_block Flag of reading block. + # When there are not unread data at reading data, + # set whether to block data until receiving the next + # data. (The default value:false) + # @param write_block Flag of writing block. + # If the buffer was full at writing data, set whether + # to block data until the buffer has space. + # (The default value:false) + # @param read_timeout Data reading timeout time (millisecond) + # when not specifying read blocking. + # (The default value:0) + # @param write_timeout Data writing timeout time (millisecond) + # when not specifying writing block. + # (The default value:0) + # + # @endif + # + def __init__(self, name, fsm, bufsize=64, read_block=False, + write_block=False, read_timeout=0, write_timeout=0): + super(EventInPort, self).__init__(name, "any") + self._name = name + self._fsm = fsm + self._buffer = self._fsm.getBuffer() + + ## + # @if jp + # + # @brief デストラクタ + # + # デストラクタ。 + # + # @else + # + # @brief Destructor + # + # Destructor + # + # @endif + # + def __del__(self): + pass + ## + # @if jp + # + # @brief ポート名称を取得する。 + # + # ポート名称を取得する。 + # + # @return ポート名称 + # + # @else + # + # @brief Get port name + # + # Get port name. + # + # @return The port name + # + # @endif + # + def name(self): + return self._name + def init(self, prop): + OpenRTM_aist.InPortBase.init(self, prop) + self.addConnectorListener(OpenRTM_aist.ConnectorListenerType.ON_CONNECT, + EventConnListener(self._buffer, self._thebuffer)) + def bindEvent0(self, name, handler): + self.addConnectorDataListener(OpenRTM_aist.ConnectorDataListenerType.ON_RECEIVED, + EventBinder0(self._fsm, name, handler, self._buffer)) + def bindEvent1(self, name, handler, data_type): + self.addConnectorDataListener(OpenRTM_aist.ConnectorDataListenerType.ON_RECEIVED, + EventBinder1(self._fsm, name, handler, data_type, self._buffer)) diff --git a/OpenRTM_aist/ExecutionContextBase.py b/OpenRTM_aist/ExecutionContextBase.py index c09874cd..ee1a2c68 100644 --- a/OpenRTM_aist/ExecutionContextBase.py +++ b/OpenRTM_aist/ExecutionContextBase.py @@ -1,5 +1,5 @@ #!/usr/bin/env python -# -*- coding: euc-jp -*- +# -*- coding: utf-8 -*- ## # @file ExecutionContextBase.py @@ -23,13 +23,13 @@ ## # @if jp # @class ExecutionContextBase -# @brief ExecutionContextѴ쥯饹 +# @brief ExecutionContext用基底クラス # -# ECμ饹Ǥϡδ쥯饹ѾECCORBAڥ졼 -# ʤФʤʤˡºݤ˥åư뤿 -# ᡢĤ«§ExecutionContextBaseδؿƤӽФɬפ -# 롣ECCORBAڥ졼ϰʲΤΤꡢ줾 -# ExecutionContextBaseΥдؿбƤ롣 +# ECの実装クラスでは、この基底クラスを継承し、かつECのCORBAオペレー +# ションを実装しなければならない。さらに、実際にロジックを駆動するた +# め、幾つかの約束に則りExecutionContextBaseの関数を呼び出す必要があ +# る。ECのCORBAオペレーションは以下のものがあり、それぞれ +# ExecutionContextBaseのメンバ関数に対応している。 # # - is_running(): ExecutionContextBase.isRunning() # - start(): ExecutionContextBase.start() @@ -49,23 +49,23 @@ # - get_kind(): ExecutionContextBase.getKind() # - get_profile(): ExecutionContextBase.getProfile() # -# @par ¹Ծ֤˴طؿȼˡ +# @par 実行状態に関係する関数と実装方法 # - is_running(): ExecutionContextBase.isRunning() # - start(): ExecutionContextBase.start() # - stop(): ExecutionContextBase.stop() # -# ¹Ծ֤˴طؿϡis_running(), start(), stop() 3Ĥ -# 롣ExecutionContextBaseǤñ running/stopped Υե饰 -# Ƥꡢstart/stopǥե饰ON/OFFڤؤis_running()Ǿɤ -# ФԤäƤ롣̾ECμ饹Ǥϡprotected ʲۥ -# дؿ onStarting(), onStarted(), onStopping(), onStopped() ؿ -# ǡCORBAڥ졼ʲΤ褦˼ɬפ롣 +# 実行状態に関係する関数は、is_running(), start(), stop() の3つがあ +# る。ExecutionContextBaseでは単純に running/stopped のフラグを持っ +# ており、start/stopでフラグのON/OFF切り替え、is_running()で状態読み +# 出しを行っている。通常、ECの実装クラスでは、protected な仮想メン +# バ関数 onStarting(), onStarted(), onStopping(), onStopped() 関数を +# 実装したうえで、CORBAオペレーションを以下のように実装する必要がある。 # -# is_running() CORBAڥ졼Ǥϡñ -# ExecutionContextBase isRunning() ƤӽФǤ롣δؿ -# ˴Ϣ protected ۴ؿonIsRunning() ѰդƤ뤬 -# ̾ä˼ɬפϤʤơߤ running/stopped ֤ -# 񤭴ˤδؿѤ뤳ȤǤ뤬侩Ϥʤ +# is_running() のCORBAオペレーションでは、単純に +# ExecutionContextBase の isRunning() を呼び出すだけである。この関数 +# に関連する protected 仮想関数はonIsRunning() が用意されているが、 +# 通常特に実装する必要はない。あえて、現在の running/stopped 状態を +# 書き換えたい場合にこの関数を利用することができるが推奨はされない。 # #
 # public:
@@ -80,12 +80,12 @@
 #  }
 # 
# -# start(), stop() CORBAڥ졼Ǥϡ̾ -# ExecutionContextBase start(), stop() ؿƤӽФ褦롣 -# δؿ˴Ϣ protected ۴ؿϡstart() stop() -# ĤƤ줾2ĤŤĤ onStarting(), onStarted(), -# onStopping(), onStopped() ؿ롣ECμ饹ˤƤϡ -# 줾ʲΤ褦˼롣 +# start(), stop() CORBAオペレーションでは、通常 +# ExecutionContextBase の start(), stop() 関数を呼び出すよう実装する。 +# この関数に関連する protected 仮想関数は、start() および stop() に +# ついてそれぞれ2つづつの onStarting(), onStarted(), および +# onStopping(), onStopped() 関数がある。ECの実装クラスにおいては、そ +# れぞれ以下のように実装する。 # #
 #  RTC::ReturnCode_t start()
@@ -99,42 +99,42 @@
 # protected:
 #  RTC::ReturnCode_t onStarting()
 #  {
-#    RTC::ReturnCode_t ret = // åɤ򳫻Ϥʤ
+#    RTC::ReturnCode_t ret = // スレッドを開始する処理など
 #    return ret;
 #  }
 #  RTC::ReturnCode_t onStarted()
 #  {
-#    RTC::ReturnCode_t ret = // åɤ򳫻Ϥʤ
+#    RTC::ReturnCode_t ret = // スレッドを開始する処理など
 #    return ret;
 #  }
 #  RTC::ReturnCode_t onStopping()
 #  {
-#    // åɤߤʤ
+#    // スレッドを停止する処理など
 #    return retcode;
 #  }
 #  RTC::ReturnCode_t onStopped()
 #  {
-#    // åɤߤʤ
+#    // スレッドを停止する処理など
 #    return retcode;
 #  }
 # 
# -# @par ¹Լ˴ؤؿȼˡ +# @par 実行周期に関する関数と実装方法 # - get_rate(): ExecutionContextBase.gatRate() # - set_rate(): ExecutioinContextBase.setRate() # -# ¹Լ˴ؤؿ set_rate(), get_rate() 2ब롣 -# ¹ԥƥȤ⤷ set_rate() ˤꤵѤ -# 硢ƥץ졼ȴؿ onSetRate() 򥪡С饤ɤ롣 -# onSetRate() ϰ double μꡢͤͤǤ -# ȤݾڤƤ롣onSetRate() RTC::RTC_OK ʳ֤ͤ -# 硢ECProfileμꤵͤݻ뤳Ȥݾڤ -# 롣 +# 実行周期に関する関数は set_rate(), get_rate() の2種類がある。実装 +# する実行コンテキストがもし set_rate() により指定される周期を利用する +# 場合、テンプレート関数 onSetRate() をオーバーライドし実装する。 +# onSetRate() は引数に double 型の周期を取り、この値は正当な値である +# ことが保証されている。onSetRate() がRTC::RTC_OK 以外の値を返した場 +# 合、ECのProfileの周期は設定される以前の値を保持することが保証され +# る。 # -# set_rate() Ʊ get_rate() ƤӽФonGetRate() ƤӽФ -# ̾索С饤ɤɬפϤʤget_rate() -# ֤ͤѹ硢onGetRate() 򥪡С饤ɤ뤳ȤǤ -# ͤ񤭴뤳ȤǤ롣Ͽ侩ʤ +# set_rate() 同様 get_rate() 呼び出し時にonGetRate() が呼び出される +# が、これは通常オーバーライドする必要はない。ただし、get_rate() が +# 返す値を変更したい場合、onGetRate() をオーバーライドすることでその +# 値を書き換えることができる。ただし、これは推奨されない。 # #
 # public:
@@ -149,7 +149,7 @@
 # protected:
 #  virtual RTC::ReturnCode_t onSetRate(double rate)
 #  {
-#    RTC::ReturnCode_t ret = // ꤹ벿餫ν
+#    RTC::ReturnCode_t ret = // 周期を設定する何らかの処理
 #    if (ret != RTC::RTC_OK)
 #      {
 #        RTC_ERROR(("Error message"));
@@ -158,24 +158,24 @@
 #  }
 #  virtual double onGetRate(rate)
 #  {
-#    // get_rate() ֤ͤù
-#    // ̾ϤδؿɬפϤʤ
+#    // get_rate() が返す値を加工したい場合
+#    // 通常はこの関数を実装する必要はない。
 #    return rate;
 #  }
 # 
# -# @par ݡͥȤɲäȺ˴ؤؿ +# @par コンポーネントの追加と削除に関する関数 # - add_component(): ExecutionContextBase.addComponent() # - remove_component(): ExecutionContextBase.removeComponent() # -# ݡͥȤɲäȺ˴ؤؿϡadd_component(), -# remove_component() ब롣¹ԥƥȤμ饹 -# ƤϡExecutionContextBase Τ줾 addComponent(), -# removeComponent() ƤӽФǼԤδؿ˴Ϣ -# protected ۴ؿ onAddingComponent(), onAddedComponent(), -# onRemovingComponent(), onRemovedComponent() 4ढ롣 -# β۴ؿ̾索С饤ɤɬפϤʤѤϿ侩 -# ʤ +# コンポーネントの追加と削除に関する関数は、add_component(), +# remove_component() の二種類がある。実行コンテキストの実装クラスに +# おいては、ExecutionContextBase のそれぞれ addComponent(), +# removeComponent() を呼び出す形で実装を行う。これらの関数に関連する +# protected 仮想関数は onAddingComponent(), onAddedComponent(), +# onRemovingComponent(), onRemovedComponent() の4種類ある。ただし、 +# これらの仮想関数は通常オーバーライドする必要はなく、使用は推奨され +# ない。 # #
 # public:
@@ -191,51 +191,51 @@
 #  virtual RTC::ReturnCode_t
 #  onAddingComponent(RTC::LightweightRTObject rtobj)
 #  {
-#     // ݡͥɲû˼¹Ԥ򵭽
-#     // RTC::RTC_OK ʳ֤硢ݡͥȤɲäϹԤʤ
+#     // コンポーネント追加時に実行したい処理を記述
+#     // RTC::RTC_OK 以外を返した場合、コンポーネントの追加は行われない。
 #     return RTC::RTC_OK;
 #  }
 #  virtual RTC::ReturnCode_t
 #  onAddedComponent(RTC::LightweightRTObject rtobj)
 #  {
-#     // ݡͥɲû˼¹Ԥ򵭽
-#     // RTC::RTC_OK ʳ֤硢removeComponent() ƤӽФ졢
-#     // ɲä줿ݡͥȤ롣
+#     // コンポーネント追加時に実行したい処理を記述
+#     // RTC::RTC_OK 以外を返した場合、removeComponent() が呼び出され、
+#     // 追加されたコンポーネントが削除される。
 #     return RTC::RTC_OK;
 #  }
 #  virtual RTC::ReturnCode_t
 #  onRemovingComponent(RTC::LightweightRTObject rtobj)
 #  {
-#     // ݡͥȺ˼¹Ԥ򵭽
-#     // RTC::RTC_OK ʳ֤硢ݡͥȤκϹԤʤ
+#     // コンポーネント削除時に実行したい処理を記述
+#     // RTC::RTC_OK 以外を返した場合、コンポーネントの削除は行われない。
 #     return RTC::RTC_OK;
 #  }
 #  virtual RTC::ReturnCode_t
 #  onRemovedComponent(RTC::LightweightRTObject rtobj)
 #  {
-#     // ݡͥɲû˼¹Ԥ򵭽
-#     // RTC::RTC_OK ʳ֤硢addComponent() ƤӽФ졢
-#     // 줿ݡͥȤƤɲä롣
+#     // コンポーネント追加時に実行したい処理を記述
+#     // RTC::RTC_OK 以外を返した場合、addComponent() が呼び出され、
+#     // 削除されたコンポーネントが再び追加される。
 #     return RTC::RTC_OK;
 #  }
 # 
# -# @par ݡͥȤΥƥֲ˴ؤؿ +# @par コンポーネントのアクティブ化等に関する関数 # - activate_component(): ExecutionContextBase.activateComponent() # - deactivate_component(): ExecutionContextBase.deactivateComponent() # - reset_component(): ExecutionContextBase.resetComponent() # -# ݡͥȤΥƥֲ˴ؤؿϡ -# activate_component(), deactivate_component(), reset_component() -# ब롣¹ԥƥȤμ饹ˤƤϡ -# ExecutionContextBase Τ줾 activateComponent(), -# deactivateComponent(), resetComponent() ƤӽФǼԤ -# δؿ˴Ϣ protected ۴ؿ +# コンポーネントのアクティブ化等に関する関数は、 +# activate_component(), deactivate_component(), reset_component() の +# 三種類がある。実行コンテキストの実装クラスにおいては、 +# ExecutionContextBase のそれぞれ activateComponent(), +# deactivateComponent(), resetComponent() を呼び出す形で実装を行う。 +# これらの関数に関連する protected 仮想関数は # onActivatingComponent(), onAtivatingComponent(), # onActivatedComponent(), onDeactivatingComponent(), # onDeactivatedComponent(), onResettingComponent(), -# onResetComponent() 6ढ롣β۴ؿ̾索 -# С饤ɤɬפϤʤѤϿ侩ʤ +# onResetComponent() の6種類ある。ただし、これらの仮想関数は通常オー +# バーライドする必要はなく、使用は推奨されない。 # #
 # public:
@@ -251,49 +251,49 @@
 #  virtual RTC::ReturnCode_t
 #  onAddingComponent(RTC::LightweightRTObject rtobj)
 #  {
-#    // ݡͥɲû˼¹Ԥ򵭽
-#    // RTC::RTC_OK ʳ֤硢ݡͥȤɲäϹԤʤ
+#    // コンポーネント追加時に実行したい処理を記述
+#    // RTC::RTC_OK 以外を返した場合、コンポーネントの追加は行われない。
 #    return RTC::RTC_OK;
 #  }
 #  virtual RTC::ReturnCode_t
 #  onAddedComponent(RTC::LightweightRTObject rtobj)
 #  {
-#    // ݡͥɲû˼¹Ԥ򵭽
-#    // RTC::RTC_OK ʳ֤硢removeComponent() ƤӽФ졢
-#    // ɲä줿ݡͥȤ롣
+#    // コンポーネント追加時に実行したい処理を記述
+#    // RTC::RTC_OK 以外を返した場合、removeComponent() が呼び出され、
+#    // 追加されたコンポーネントが削除される。
 #    return RTC::RTC_OK;
 #  }
 #  virtual RTC::ReturnCode_t
 #  onRemovingComponent(RTC::LightweightRTObject rtobj)
 #  {
-#    // ݡͥȺ˼¹Ԥ򵭽
-#    // RTC::RTC_OK ʳ֤硢ݡͥȤκϹԤʤ
+#    // コンポーネント削除時に実行したい処理を記述
+#    // RTC::RTC_OK 以外を返した場合、コンポーネントの削除は行われない。
 #    return RTC::RTC_OK;
 #  }
 #  virtual RTC::ReturnCode_t
 #  onRemovedComponent(RTC::LightweightRTObject rtobj)
 #  {
-#    // ݡͥɲû˼¹Ԥ򵭽
-#    // RTC::RTC_OK ʳ֤硢addComponent() ƤӽФ졢
-#    // 줿ݡͥȤƤɲä롣
+#    // コンポーネント追加時に実行したい処理を記述
+#    // RTC::RTC_OK 以外を返した場合、addComponent() が呼び出され、
+#    // 削除されたコンポーネントが再び追加される。
 #    return RTC::RTC_OK;
 #  }
 # 
# -# @par ¹ԥƥȤξ˴ؤؿ +# @par 実行コンテキストの情報取得に関する関数 # - get_component_state(): ExecutionContextBase.getComponentState() # - get_kind(): ExecutionContextBase.getKind() # - get_profile(): ExecutionContextBase.getProfile() # -# ¹ԥƥȤξ˴ؤؿϡget_component_state(), -# get_kind(), get_profile() 3ब롣¹ԥƥȤμ -# 饹ˤƤϡExecutionContextBase Τ줾 -# getComponentState(), getKind(), getProfile() ƤӽФǼ -# Ԥδؿ˴Ϣ protected ۴ؿ -# onGetComponentState(), onGetKind(), onGetProfile() 3ढ롣 -# β۴ؿ̾索С饤ɤɬפϤʤѤϿ侩 -# ֤ѹϡδؿŬڤ˼ -# 뤳ȤǡƤӽФ¦֤ͤ񤭤뤳ȤǤ롣 +# 実行コンテキストの情報取得に関する関数は、get_component_state(), +# get_kind(), get_profile() の3種類がある。実行コンテキストの実装ク +# ラスにおいては、ExecutionContextBase のそれぞれ +# getComponentState(), getKind(), getProfile() を呼び出す形で実装を +# 行う。これらの関数に関連する protected 仮想関数は +# onGetComponentState(), onGetKind(), onGetProfile() の3種類ある。こ +# れらの仮想関数は通常オーバーライドする必要はなく、使用は推奨されな +# い。ただし、返す情報を変更したい場合は、これらの関数を適切に実装す +# ることで、呼び出し側に返す値を上書きすることができる。 # #
 # public:
@@ -312,21 +312,21 @@
 #
 # protected:
 #  virtual LifeCycleState onGetComponentState(LifeCycleState state)
-#  { // ֤state񤭴Ϥδؿ
+#  { // 返すstateを書き換えたい場合はこの関数を実装する
 #    return state;
 #  }
 #  virtual ExecutionKind onGetKind(ExecutionKind kind)
-#  { // ֤kind񤭴Ϥδؿ
+#  { // 返すkindを書き換えたい場合はこの関数を実装する
 #    return kind;
 #  }
 #  virtual ExecutionContextProfile*
 #  onGetProfile(ExecutionContextProfile*& profile)
-#  { // ֤profile񤭴Ϥδؿ
+#  { // 返すprofileを書き換えたい場合はこの関数を実装する
 #    return profile;
 #  }
 # 
# -# ExecutionContextδ쥯饹 +# ExecutionContextの基底クラス。 # # @since 0.4.0 # @@ -340,1204 +340,1255 @@ # # @endif # + + class ExecutionContextBase: - """ - """ - - def __init__(self, name): - self._rtcout = OpenRTM_aist.Manager.instance().getLogbuf("ec_base") - self._activationTimeout = OpenRTM_aist.TimeValue(0.5) - self._deactivationTimeout = OpenRTM_aist.TimeValue(0.5) - self._resetTimeout = OpenRTM_aist.TimeValue(0.5) - self._syncActivation = True - self._syncDeactivation = True - self._syncReset = True - self._worker = OpenRTM_aist.ExecutionContextWorker() - self._profile = OpenRTM_aist.ExecutionContextProfile() - - - ## - # @if jp - # @brief ExecutionContextν - # - # @else - # @brief Initialization function of the ExecutionContext - # - # @endif - # virtual void init(coil::Properties& props); - def init(self, props): - self._rtcout.RTC_TRACE("init()") - self._rtcout.RTC_DEBUG(props) - - # setting rate - self.setExecutionRate(props) - - # getting sync/async mode flag - transitionMode_ = [False] - if self.setTransitionMode(props, "sync_transition", transitionMode_): - self._syncActivation = transitionMode_[0] - self._syncDeactivation = transitionMode_[0] - self._syncReset = transitionMode_[0] - - syncactivation_ = [self._syncActivation] - syncdeactivation_ = [self._syncDeactivation] - syncreset_ = [self._syncReset] - self.setTransitionMode(props, "sync_activation", syncactivation_) - self.setTransitionMode(props, "sync_deactivation", syncdeactivation_) - self.setTransitionMode(props, "sync_reset", syncreset_) - self._syncActivation = syncactivation_[0] - self._syncDeactivation = syncdeactivation_[0] - self._syncReset = syncreset_[0] - - # getting transition timeout - timeout_ = [0.0] - if self.setTimeout(props, "transition_timeout", timeout_): - self._activationTimeout = timeout_[0] - self._deactivationTimeout = timeout_[0] - self._resetTimeout = timeout_[0] - - activationTO_ = [self._activationTimeout] - deactivationTO_ = [self._deactivationTimeout] - resetTO_ = [self._resetTimeout] - self.setTimeout(props, "activation_timeout", activationTO_) - self.setTimeout(props, "deactivation_timeout", deactivationTO_) - self.setTimeout(props, "reset_timeout", resetTO_) - self._activationTimeout = activationTO_[0] - self._deactivationTimeout = deactivationTO_[0] - self._resetTimeout = resetTO_[0] - - self._rtcout.RTC_DEBUG("ExecutionContext's configurations:") - self._rtcout.RTC_DEBUG("Exec rate : %f [Hz]", self.getRate()) - - toSTR_ = lambda x: "YES" if x else "NO" - - self._rtcout.RTC_DEBUG("Activation : Sync = %s, Timeout = %f", - (toSTR_(self._syncActivation), float(self._activationTimeout.toDouble()))) - self._rtcout.RTC_DEBUG("Deactivation: Sync = %s, Timeout = %f", - (toSTR_(self._syncActivation), float(self._deactivationTimeout.toDouble()))) - self._rtcout.RTC_DEBUG("Reset : Sync = %s, Timeout = %f", - (toSTR_(self._syncReset), float(self._resetTimeout.toDouble()))) - # Setting given Properties to EC's profile::properties - self.setProperties(props) - return - - ## - # @if jp - # @brief ExecutionContextνλ - # - # @else - # @brief - # - # @endif - # virtual void exit(); - def exit(self): - self._rtcout.RTC_TRACE("exit()") - self._profile.exit() - self._worker.exit() - - ## - # @if jp - # @brief ExecutionContextνʤ(֥饹) - # - # ExecutionContextν򣱼ʬʤ롣
- # ֥饹Ǥμ - # - # @param self - # - # @else - # @brief Destructor - # @endif - #def tick(self): - # pass - - - ## - # @if jp - # @brief ݡͥȤХɤ롣 - # - # ݡͥȤХɤ롣 - # - # @else - # @brief Bind the component. - # - # Bind the component. - # - # @endif - def bindComponent(self, rtc): - self.setOwner(rtc.getObjRef()) - return self._worker.bindComponent(rtc) - - - #============================================================ - # Functions to be delegated by EC's CORBA operations - - ## - # @if jp - # @brief ExecutionContext ¹Ծֳǧؿ - # @else - # @brief Check for ExecutionContext running state - # @endif - # CORBA::Boolean ExecutionContextBase::isRunning() - def isRunning(self): - self._rtcout.RTC_TRACE("isRunning()") - return self._worker.isRunning() - - - ## - # @if jp - # @brief ExecutionContext μ¹Ԥ򳫻 - # @else - # @brief Start the ExecutionContext - # @endif - # RTC::ReturnCode_t ExecutionContextBase::start() - def start(self): - self._rtcout.RTC_TRACE("start()") - ret_ = self.onStarting() # Template - if ret_ != RTC.RTC_OK: - self._rtcout.RTC_ERROR("onStarting() failed. Starting EC aborted.") - return ret_ - - ret_ = self._worker.start() # Actual start() - if ret_ != RTC.RTC_OK: - self._rtcout.RTC_ERROR("Invoking on_startup() for each RTC failed.") - return ret_ - - ret_ = self.onStarted() # Template - if ret_ != RTC.RTC_OK: - self._rtcout.RTC_ERROR("onStartted() failed. Started EC aborted..") - self._worker.stop() - self._rtcout.RTC_ERROR("on_shutdown() was invoked, because of onStarted") - return ret_ - - return ret_ - - - ## - # @if jp - # @brief ExecutionContext μ¹Ԥ - # @else - # @brief Stopping the ExecutionContext - # @endif - # RTC::ReturnCode_t ExecutionContextBase::stop() - def stop(self): - self._rtcout.RTC_TRACE("stop()") - ret_ = self.onStopping() # Template - if ret_ != RTC.RTC_OK: - self._rtcout.RTC_ERROR("onStopping() failed. Stopping EC aborted.") - return ret_ - - ret_ = self._worker.stop() # Actual stop() - if ret_ != RTC.RTC_OK: - self._rtcout.RTC_ERROR("Invoking on_shutdown() for each RTC failed.") - return ret_ - - ret_ = self.onStopped() # Template - if ret_ != RTC.RTC_OK: - self._rtcout.RTC_ERROR("onStopped() failed. Stopped EC aborted.") - return ret_ - - return ret_ - - - ## - # @if jp - # @brief ExecutionContext μ¹Լ(Hz) - # - # Active ֤ˤRTݡͥȤ¹Ԥ(ñ:Hz) - # 롣 - # - # @return (ñ:Hz) - # - # @else - # - # @brief Get execution rate(Hz) of ExecutionContext - # - # This operation shall return the rate (in hertz) at which its - # Active participating RTCs are being invoked. - # - # @return Execution cycle(Unit:Hz) - # - # @endif - # double getRate(void) const - def getRate(self): - rate_ = self._profile.getRate() # Actual getRate() - return self.onGetRate(rate_) # Template - - - # coil::TimeValue ExecutionContextBase::getPeriod(void) const - def getPeriod(self): - return self._profile.getPeriod() - - - ## - # @if jp - # @brief ExecutionContext μ¹Լ(Hz)ꤹ - # - # Active ֤ˤRTݡͥȤ¹Ԥ(ñ:Hz)ꤹ - # 롣¹ԼѹϡDataFlowComponentAction - # on_rate_changed ˤäƳRTݡͥȤã롣 - # - # @param rate (ñ:Hz) - # - # @return ReturnCode_t Υ꥿󥳡 - # RTC_OK: ェλ - # BAD_PARAMETER: ͤ - # - # @else - # - # @brief Set execution rate(Hz) of ExecutionContext - # - # This operation shall set the rate (in hertz) at which this - # contexts Active participating RTCs are being called. If the - # execution kind of the context is PERIODIC, a rate change shall - # result in the invocation of on_rate_changed on any RTCs - # realizing DataFlowComponentAction that are registered with any - # RTCs participating in the context. - # - # @param rate Execution cycle(Unit:Hz) - # - # @return The return code of ReturnCode_t type - # RTC_OK: Succeed - # BAD_PARAMETER: Invalid value. The value might be negative. - # - # @endif - # RTC::ReturnCode_t setRate(double rate) - def setRate(self, rate): - self._rtcout.RTC_TRACE("setRate(%f)", rate) - ret_ = self._profile.setRate(self.onSettingRate(rate)) - if ret_ != RTC.RTC_OK: - self._rtcout.RTC_ERROR("Setting execution rate failed. %f", rate) - return ret_ - - ret_ = self._worker.rateChanged() - if ret_ != RTC.RTC_OK: - self._rtcout.RTC_ERROR("Invoking on_rate_changed() for each RTC failed.") - return ret_ - - ret_ = self.onSetRate(rate) - if ret_ != RTC.RTC_OK: - self._rtcout.RTC_ERROR("onSetRate(%f) failed.", rate) - return ret_ - - - - - self._rtcout.RTC_INFO("setRate(%f) done", rate) - return ret_ - - - ## - # @if jp - # @brief RTݡͥȤɲä - # @else - # @brief Add an RT-component - # @endif - # RTC::ReturnCode_t ExecutionContextBase:: - # addComponent(RTC::LightweightRTObject_ptr comp) - def addComponent(self, comp): - - self._rtcout.RTC_TRACE("addComponent()") - ret_ = self.onAddingComponent(comp) # Template - if ret_ != RTC.RTC_OK: - self._rtcout.RTC_ERROR("Error: onAddingComponent(). RTC is not attached.") - return ret_ - - ret_ = self._worker.addComponent(comp) # Actual addComponent() - if ret_ != RTC.RTC_OK: - self._rtcout.RTC_ERROR("Error: ECWorker addComponent() faild.") - return ret_ - - ret_ = self._profile.addComponent(comp) # Actual addComponent() - if ret_ != RTC.RTC_OK: - self._rtcout.RTC_ERROR("Error: ECProfile addComponent() faild.") - return ret_ - - ret_ = self.onAddedComponent(comp) # Template - if ret_ != RTC.RTC_OK: - self._rtcout.RTC_ERROR("Error: onAddedComponent() faild.") - self._rtcout.RTC_INFO("Removing attached RTC.") - self._worker.removeComponent(comp) - self._profile.removeComponent(comp) - return ret_ - - self._rtcout.RTC_INFO("Component has been added to this EC.") - return RTC.RTC_OK - - - ## - # @if jp - # @brief RTݡͥȤ򻲲üԥꥹȤ - # @else - # @brief Remove the RT-Component from participant list - # @endif - # RTC::ReturnCode_t ExecutionContextBase:: - # removeComponent(RTC::LightweightRTObject_ptr comp) - def removeComponent(self, comp): - self._rtcout.RTC_TRACE("removeComponent()") - ret_ = self.onRemovingComponent(comp) # Template - if ret_ != RTC.RTC_OK: - self._rtcout.RTC_ERROR("Error: onRemovingComponent(). " - "RTC will not not attached.") - return ret_ - - ret_ = self._worker.removeComponent(comp) # Actual removeComponent() - if ret_ != RTC.RTC_OK: - self._rtcout.RTC_ERROR("Error: ECWorker removeComponent() faild.") - return ret_ - - ret_ = self._profile.removeComponent(comp) # Actual removeComponent() - if ret_ != RTC.RTC_OK: - self._rtcout.RTC_ERROR("Error: ECProfile removeComponent() faild.") - return ret_ - - ret_ = self.onRemovedComponent(comp) # Template - if ret_ != RTC.RTC_OK: - self._rtcout.RTC_ERROR("Error: onRemovedComponent() faild.") - self._rtcout.RTC_INFO("Removing attached RTC.") - self._worker.removeComponent(comp) - self._profile.removeComponent(comp) - return ret_ - - self._rtcout.RTC_INFO("Component has been removeed to this EC.") - return RTC.RTC_OK - - - ## - # @if jp - # @brief RTݡͥȤ򥢥ƥֲ - # @else - # @brief Activate an RT-component - # @endif - # RTC::ReturnCode_t ExecutionContextBase:: - # activateComponent(RTC::LightweightRTObject_ptr comp) - def activateComponent(self, comp): - self._rtcout.RTC_TRACE("activateComponent()") - ret_ = self.onActivating(comp) # Template - if ret_ != RTC.RTC_OK: - self._rtcout.RTC_ERROR("onActivating() failed.") - return ret_ - - rtobj_ = [None] - ret_ = self._worker.activateComponent(comp, rtobj_) # Actual activateComponent() - if ret_ != RTC.RTC_OK: - return ret_ - - if not self._syncActivation: # Asynchronous activation mode - ret_ = self.onActivated(rtobj_[0], -1) - if ret_ != RTC.RTC_OK: - self._rtcout.RTC_ERROR("onActivated() failed.") - - return ret_ - - #------------------------------------------------------------ - # Synchronized activation mode - self._rtcout.RTC_DEBUG("Synchronous activation mode. " - "Waiting for the RTC to be ACTIVE state. ") - return self.waitForActivated(rtobj_[0]) - - - # RTC::ReturnCode_t ExecutionContextBase:: - # waitForActivated(RTC_impl::RTObjectStateMachine* rtobj) - def waitForActivated(self, rtobj): - count_ = 0 - ret_ = self.onWaitingActivated(rtobj, count_) - if ret_ != RTC.RTC_OK: - self._rtcout.RTC_ERROR("onWaitingActivated failed.") - return ret_ - - cycle_ = int(float(self._activationTimeout.toDouble()) / float(self.getPeriod().toDouble())) - self._rtcout.RTC_DEBUG("Timeout is %f [s] (%f [s] in %d times)", - (float(self._activationTimeout.toDouble()), self.getRate(), cycle_)) - # Wating INACTIVE -> ACTIVE - starttime_ = OpenRTM_aist.Time().gettimeofday() - - while rtobj.isCurrentState(RTC.INACTIVE_STATE): - - ret_ = self.onWaitingActivated(rtobj, count_) # Template method - if ret_ != RTC.RTC_OK: - self._rtcout.RTC_ERROR("onWaitingActivated failed.") + """ + """ + + def __init__(self, name): + self._rtcout = OpenRTM_aist.Manager.instance().getLogbuf("ec_base") + self._activationTimeout = OpenRTM_aist.TimeValue(0.5) + self._deactivationTimeout = OpenRTM_aist.TimeValue(0.5) + self._resetTimeout = OpenRTM_aist.TimeValue(0.5) + self._syncActivation = True + self._syncDeactivation = True + self._syncReset = True + self._worker = OpenRTM_aist.ExecutionContextWorker() + self._profile = OpenRTM_aist.ExecutionContextProfile() + + ## + # @if jp + # @brief ExecutionContextの初期化処理 + # + # @else + # @brief Initialization function of the ExecutionContext + # + # @endif + # virtual void init(coil::Properties& props); + + def init(self, props): + self._rtcout.RTC_TRACE("init()") + self._rtcout.RTC_DEBUG(props) + + # setting rate + self.setExecutionRate(props) + + # getting sync/async mode flag + transitionMode_ = False + ret, transitionMode_ = self.setTransitionMode( + props, "sync_transition", transitionMode_) + if ret: + self._syncActivation = transitionMode_ + self._syncDeactivation = transitionMode_ + self._syncReset = transitionMode_ + + syncactivation_ = self._syncActivation + syncdeactivation_ = self._syncDeactivation + syncreset_ = self._syncReset + _, syncactivation_ = self.setTransitionMode( + props, "sync_activation", syncactivation_) + _, syncdeactivation_ = self.setTransitionMode( + props, "sync_deactivation", syncdeactivation_) + _, syncreset_ = self.setTransitionMode(props, "sync_reset", syncreset_) + self._syncActivation = syncactivation_ + self._syncDeactivation = syncdeactivation_ + self._syncReset = syncreset_ + + # getting transition timeout + timeout_ = 0.0 + ret, timeout_ = self.setTimeout(props, "transition_timeout", timeout_) + if ret: + self._activationTimeout = timeout_ + self._deactivationTimeout = timeout_ + self._resetTimeout = timeout_ + + activationTO_ = self._activationTimeout + deactivationTO_ = self._deactivationTimeout + resetTO_ = self._resetTimeout + _, activationTO_ = self.setTimeout( + props, "activation_timeout", activationTO_) + _, deactivationTO_ = self.setTimeout( + props, "deactivation_timeout", deactivationTO_) + _, resetTO_ = self.setTimeout(props, "reset_timeout", resetTO_) + self._activationTimeout = activationTO_ + self._deactivationTimeout = deactivationTO_ + self._resetTimeout = resetTO_ + + self._rtcout.RTC_DEBUG("ExecutionContext's configurations:") + self._rtcout.RTC_DEBUG("Exec rate : %f [Hz]", self.getRate()) + + def toSTR_(x): return "YES" if x else "NO" + + self._rtcout.RTC_DEBUG("Activation : Sync = %s, Timeout = %f", + (toSTR_(self._syncActivation), float(self._activationTimeout.toDouble()))) + self._rtcout.RTC_DEBUG("Deactivation: Sync = %s, Timeout = %f", + (toSTR_(self._syncActivation), float(self._deactivationTimeout.toDouble()))) + self._rtcout.RTC_DEBUG("Reset : Sync = %s, Timeout = %f", + (toSTR_(self._syncReset), float(self._resetTimeout.toDouble()))) + # Setting given Properties to EC's profile::properties + self.setProperties(props) + return + + ## + # @if jp + # @brief ExecutionContextの終了処理 + # + # @else + # @brief + # + # @endif + # virtual void exit(); + def exit(self): + self._rtcout.RTC_TRACE("exit()") + ret_ = self._worker.removeComponent(self._profile.getOwner()) + if ret_ != RTC.RTC_OK: + self._rtcout.RTC_ERROR("Error: ECWorker removeComponent() faild.") + self._profile.exit() + self._worker.exit() + + ## + # @if jp + # @brief ExecutionContextの処理を進める(サブクラス実装用) + # + # ExecutionContextの処理を1周期分進める。
+ # ※サブクラスでの実装参照用 + # + # @param self + # + # @else + # @brief Destructor + # @endif + # def tick(self): + # pass + + ## + # @if jp + # @brief コンポーネントをバインドする。 + # + # コンポーネントをバインドする。 + # + # @else + # @brief Bind the component. + # + # Bind the component. + # + # @endif + + def bindComponent(self, rtc): + self.setOwner(rtc.getObjRef()) + return self._worker.bindComponent(rtc) + + # ============================================================ + # Functions to be delegated by EC's CORBA operations + + ## + # @if jp + # @brief ExecutionContext 実行状態確認関数 + # @else + # @brief Check for ExecutionContext running state + # @endif + # CORBA::Boolean ExecutionContextBase::isRunning() + + def isRunning(self): + self._rtcout.RTC_TRACE("isRunning()") + return self._worker.isRunning() + + ## + # @if jp + # @brief ExecutionContext の実行を開始 + # @else + # @brief Start the ExecutionContext + # @endif + # RTC::ReturnCode_t ExecutionContextBase::start() + + def start(self): + self._rtcout.RTC_TRACE("start()") + ret_ = self.onStarting() # Template + if ret_ != RTC.RTC_OK: + self._rtcout.RTC_ERROR("onStarting() failed. Starting EC aborted.") + return ret_ + + ret_ = self._worker.start() # Actual start() + if ret_ != RTC.RTC_OK: + self._rtcout.RTC_ERROR( + "Invoking on_startup() for each RTC failed.") + return ret_ + + ret_ = self.onStarted() # Template + if ret_ != RTC.RTC_OK: + self._rtcout.RTC_ERROR("onStartted() failed. Started EC aborted..") + self._worker.stop() + self._rtcout.RTC_ERROR( + "on_shutdown() was invoked, because of onStarted") + return ret_ + return ret_ - time.sleep(self.getPeriod().toDouble()) - delta_ = OpenRTM_aist.Time().gettimeofday() - starttime_ - self._rtcout.RTC_DEBUG("Waiting to be ACTIVE state. %f [s] slept (%d/%d)", - (float(delta_.toDouble()), count_, cycle_)) - count_ += 1 - if delta_.toDouble() > self._activationTimeout.toDouble() or count_ > cycle_: - self._rtcout.RTC_WARN("The component is not responding.") - break - - - # Now State must be ACTIVE or ERROR - if rtobj.isCurrentState(RTC.INACTIVE_STATE): - self._rtcout.RTC_ERROR("Unknown error: Invalid state transition.") - return RTC.RTC_ERROR - - self._rtcout.RTC_DEBUG("Current state is %s", self.getStateString(rtobj.getState())) - ret_ = self.onActivated(rtobj, count_) # Template method - if ret_ != RTC.RTC_OK: - self._rtcout.RTC_ERROR("onActivated() failed.") - - self._rtcout.RTC_DEBUG("onActivated() done.") - return ret_ - - - ## - # @if jp - # @brief RTݡͥȤ󥢥ƥֲ - # @else - # @brief Deactivate an RT-component - # @endif - # RTC::ReturnCode_t ExecutionContextBase:: - # deactivateComponent(RTC::LightweightRTObject_ptr comp) - def deactivateComponent(self, comp): - self._rtcout.RTC_TRACE("deactivateComponent()") - ret_ = self.onDeactivating(comp) # Template - if ret_ != RTC.RTC_OK: - self._rtcout.RTC_ERROR("onDeactivating() failed.") - return ret_ - - # Deactivate all the RTCs - rtobj_ = [None] - ret_ = self._worker.deactivateComponent(comp, rtobj_) - if ret_ != RTC.RTC_OK: - return ret_ - - if not self._syncDeactivation: - ret_ = self.onDeactivated(rtobj_[0], -1) - if ret_ != RTC.RTC_OK: - self._rtcout.RTC_ERROR("onDeactivated() failed.") - return ret_ - - #------------------------------------------------------------ - # Waiting for synchronized deactivation - self._rtcout.RTC_DEBUG("Synchronous deactivation mode. " - "Waiting for the RTC to be INACTIVE state. ") - return self.waitForDeactivated(rtobj_[0]) - - - # RTC::ReturnCode_t ExecutionContextBase:: - # waitForDeactivated(RTC_impl::RTObjectStateMachine* rtobj) - def waitForDeactivated(self, rtobj): - count_ = 0 - ret_ = self.onWaitingDeactivated(rtobj, count_) - if ret_ != RTC.RTC_OK: - self._rtcout.RTC_ERROR("onWaitingDeactivated failed.") - return ret_ - - cycle_ = int(float(self._deactivationTimeout.toDouble()) / float(self.getPeriod().toDouble())) - self._rtcout.RTC_DEBUG("Timeout is %f [s] (%f [s] in %d times)", - (float(self._deactivationTimeout.toDouble()), self.getRate(), cycle_)) - # Wating ACTIVE -> INACTIVE - starttime_ = OpenRTM_aist.Time().gettimeofday() - while rtobj.isCurrentState(RTC.ACTIVE_STATE): - ret_ = self.onWaitingDeactivated(rtobj, count_) # Template method - if ret_ != RTC.RTC_OK: - self._rtcout.RTC_ERROR("onWaitingDeactivated failed.") + ## + # @if jp + # @brief ExecutionContext の実行を停止 + # @else + # @brief Stopping the ExecutionContext + # @endif + # RTC::ReturnCode_t ExecutionContextBase::stop() + + def stop(self): + self._rtcout.RTC_TRACE("stop()") + ret_ = self.onStopping() # Template + if ret_ != RTC.RTC_OK: + self._rtcout.RTC_ERROR("onStopping() failed. Stopping EC aborted.") + return ret_ + + ret_ = self._worker.stop() # Actual stop() + if ret_ != RTC.RTC_OK: + self._rtcout.RTC_ERROR( + "Invoking on_shutdown() for each RTC failed.") + return ret_ + + ret_ = self.onStopped() # Template + if ret_ != RTC.RTC_OK: + self._rtcout.RTC_ERROR("onStopped() failed. Stopped EC aborted.") + return ret_ + return ret_ - time.sleep(self.getPeriod().toDouble()) - delta_ = OpenRTM_aist.Time().gettimeofday() - starttime_ - self._rtcout.RTC_DEBUG("Waiting to be INACTIVE state. Sleeping %f [s] (%d/%d)", - (float(delta_.toDouble()), count_, cycle_)) - count_ += 1 - if delta_.toDouble() > self._deactivationTimeout.toDouble() or count_ > cycle_: - self._rtcout.RTC_ERROR("The component is not responding.") - break - - - # Now State must be INACTIVE or ERROR - if rtobj.isCurrentState(RTC.ACTIVE_STATE): - self._rtcout.RTC_ERROR("Unknown error: Invalid state transition.") - return RTC.RTC_ERROR - - self._rtcout.RTC_DEBUG("Current state is %s", self.getStateString(rtobj.getState())) - ret_ = self.onDeactivated(rtobj, count_) - if ret_ != RTC.RTC_OK: - self._rtcout.RTC_ERROR("onDeactivated() failed.") - - self._rtcout.RTC_DEBUG("onDeactivated() done.") - return ret_ - - - ## - # @if jp - # @brief RTݡͥȤꥻåȤ - # @else - # @brief Reset the RT-component - # @endif - # RTC::ReturnCode_t ExecutionContextBase:: - # resetComponent(RTC::LightweightRTObject_ptr comp) - def resetComponent(self, comp): - self._rtcout.RTC_TRACE("resetComponent()") - ret_ = self.onResetting(comp) # Template - if ret_ != RTC.RTC_OK: - self._rtcout.RTC_ERROR("onResetting() failed.") - return ret_ - - rtobj_ = [None] - ret_ = self._worker.resetComponent(comp, rtobj_) # Actual resetComponent() - if ret_ != RTC.RTC_OK: - return ret_ - if not self._syncReset: - ret_ = self.onReset(rtobj_[0], -1) - if ret_ != RTC.RTC_OK: - self._rtcout.RTC_ERROR("onReset() failed.") - return ret_ - - #------------------------------------------------------------ - # Waiting for synchronized reset - self._rtcout.RTC_DEBUG("Synchronous reset mode. " - "Waiting for the RTC to be INACTIVE state. ") - return self.waitForReset(rtobj_[0]) - - - # RTC::ReturnCode_t ExecutionContextBase:: - # waitForReset(RTC_impl::RTObjectStateMachine* rtobj) - def waitForReset(self, rtobj): - count_ = 0 - ret_ = self.onWaitingReset(rtobj, count_) - if ret_ != RTC.RTC_OK: - self._rtcout.RTC_ERROR("onWaitingReset() failed.") - return ret_ - - cycle_ = int(float(self._resetTimeout.toDouble()) / float(self.getPeriod().toDouble())) - self._rtcout.RTC_DEBUG("Timeout is %f [s] (%f [s] in %d times)", - (float(self._resetTimeout.toDouble()), self.getRate(), cycle_)) - # Wating ERROR -> INACTIVE - starttime_ = OpenRTM_aist.Time().gettimeofday() - while rtobj.isCurrentState(RTC.ERROR_STATE): - ret_ = self.onWaitingReset(rtobj, count_) # Template - if ret_ != RTC.RTC_OK: - self._rtcout.RTC_ERROR("onWaitingReset failed.") + ## + # @if jp + # @brief ExecutionContext の実行周期(Hz)を取得する + # + # Active 状態にてRTコンポーネントが実行される周期(単位:Hz)を取得す + # る。 + # + # @return 処理周期(単位:Hz) + # + # @else + # + # @brief Get execution rate(Hz) of ExecutionContext + # + # This operation shall return the rate (in hertz) at which its + # Active participating RTCs are being invoked. + # + # @return Execution cycle(Unit:Hz) + # + # @endif + # double getRate(void) const + + def getRate(self): + rate_ = self._profile.getRate() # Actual getRate() + return self.onGetRate(rate_) # Template + + # coil::TimeValue ExecutionContextBase::getPeriod(void) const + + def getPeriod(self): + return self._profile.getPeriod() + + ## + # @if jp + # @brief ExecutionContext の実行周期(Hz)を設定する + # + # Active 状態にてRTコンポーネントが実行される周期(単位:Hz)を設定す + # る。実行周期の変更は、DataFlowComponentAction の + # on_rate_changed によって各RTコンポーネントに伝達される。 + # + # @param rate 処理周期(単位:Hz) + # + # @return ReturnCode_t 型のリターンコード + # RTC_OK: 正常終了 + # BAD_PARAMETER: 設定値が負の値 + # + # @else + # + # @brief Set execution rate(Hz) of ExecutionContext + # + # This operation shall set the rate (in hertz) at which this + # context’s Active participating RTCs are being called. If the + # execution kind of the context is PERIODIC, a rate change shall + # result in the invocation of on_rate_changed on any RTCs + # realizing DataFlowComponentAction that are registered with any + # RTCs participating in the context. + # + # @param rate Execution cycle(Unit:Hz) + # + # @return The return code of ReturnCode_t type + # RTC_OK: Succeed + # BAD_PARAMETER: Invalid value. The value might be negative. + # + # @endif + # RTC::ReturnCode_t setRate(double rate) + + def setRate(self, rate): + self._rtcout.RTC_TRACE("setRate(%f)", rate) + ret_ = self._profile.setRate(self.onSettingRate(rate)) + if ret_ != RTC.RTC_OK: + self._rtcout.RTC_ERROR("Setting execution rate failed. %f", rate) + return ret_ + + ret_ = self._worker.rateChanged() + if ret_ != RTC.RTC_OK: + self._rtcout.RTC_ERROR( + "Invoking on_rate_changed() for each RTC failed.") + return ret_ + + ret_ = self.onSetRate(rate) + if ret_ != RTC.RTC_OK: + self._rtcout.RTC_ERROR("onSetRate(%f) failed.", rate) + return ret_ + + self._rtcout.RTC_INFO("setRate(%f) done", rate) return ret_ - time.sleep(self.getPeriod().toDouble()) - delta_ = OpenRTM_aist.Time().gettimeofday() - starttime_ - self._rtcout.RTC_DEBUG("Waiting to be INACTIVE state. Sleeping %f [s] (%d/%d)", - (float(delta_.toDouble()), count_, cycle_)) - count_ += 1 - if delta_.toDouble() > self._resetTimeout.toDouble() or count_ > cycle_: - self._rtcout.RTC_ERROR("The component is not responding.") - break - - # Now State must be INACTIVE - if not rtobj.isCurrentState(RTC.INACTIVE_STATE): - self._rtcout.RTC_ERROR("Unknown error: Invalid state transition.") - return RTC.RTC_ERROR - - self._rtcout.RTC_DEBUG("Current state is %s", self.getStateString(rtobj.getState())) - ret_ = self.onReset(rtobj, count_) # Template method - if ret_ != RTC.RTC_OK: - self._rtcout.RTC_ERROR("onResetd() failed.") - - self._rtcout.RTC_DEBUG("onReset() done.") - return ret_ - - - ## - # @if jp - # @brief RTݡͥȤξ֤ - # - # ꤷRTݡͥȤξ(LifeCycleState)롣ꤷ - # RTݡͥȤüԥꥹȤ˴ޤޤʤϡ - # UNKNOWN_STATE ֤롣 - # - # @param comp ּоRTݡͥ - # - # @return ߤξ(LifeCycleState) - # - # @else - # - # @brief Get RT-component's state - # - # This operation shall report the LifeCycleState of the given - # participant RTC. UNKNOWN_STATE will be returned, if the given - # RT-Component is not inclued in the participant list. - # - # @param comp The target RT-Component to get the state - # - # @return The current state of the target RT-Component(LifeCycleState) - # - # @endif - # RTC::LifeCycleState ExecutionContextBase:: - # getComponentState(RTC::LightweightRTObject_ptr comp) - def getComponentState(self, comp): - state_ = self._worker.getComponentState(comp) - self._rtcout.RTC_TRACE("getComponentState() = %s", self.getStateString(state_)) - if state_ == RTC.CREATED_STATE: - self._rtcout.RTC_ERROR("CREATED state: not initialized " - "RTC or unknwon RTC specified.") - - return self.onGetComponentState(state_) - - - # const char* ExecutionContextBase::getStateString(RTC::LifeCycleState state) - def getStateString(self, state): - return self._worker.getStateString(state) - - - ## - # @if jp - # @brief ExecutionKind - # - # ExecutionContext ExecutionKind - # - # @return ExecutionKind - # - # @else - # - # @brief Get the ExecutionKind - # - # This operation shall report the execution kind of the execution - # context. - # - # @return ExecutionKind - # - # @endif - # RTC::ExecutionKind ExecutionContextBase::getKind(void) const - def getKind(self): - kind_ = self._profile.getKind() - self._rtcout.RTC_TRACE("getKind() = %s", self.getKindString(kind_)) - kind_ = self.onGetKind(kind_) - self._rtcout.RTC_DEBUG("onGetKind() returns %s", self.getKindString(kind_)) - return kind_ - - - ## - # @if jp - # @brief Profile - # - # RTC::ExecutionContextProfile 롣 - # ExecutionContextProfile νͭϸƤӽФ¦ˤ롣줿 - # ֥Ȥפˤʤä硢ƤӽФ¦Ǥ餦 - # - # @return RTC::ExecutionContextProfile - # - # @else - # @brief Getting Profile - # - # This function gets RTC::ExecutionContextProfile. The ownership - # of the obtained ExecutionContextProfile is given to caller. The - # caller should release obtained object when it is unneccessary - # anymore. - # - # @return RTC::ExecutionContextProfile - # - # @endif - # RTC::ExecutionContextProfile* ExecutionContextBase::getProfile(void) - def getProfile(self): - self._rtcout.RTC_TRACE("getProfile()") - prof_ = self._profile.getProfile() - self._rtcout.RTC_DEBUG("kind: %s", self.getKindString(prof_.kind)) - self._rtcout.RTC_DEBUG("rate: %f", prof_.rate) - self._rtcout.RTC_DEBUG("properties:") - props_ = OpenRTM_aist.Properties() - OpenRTM_aist.NVUtil.copyToProperties(props_, prof_.properties) - self._rtcout.RTC_DEBUG(props_) - return self.onGetProfile(prof_) - - - - #============================================================ - # Delegated functions to ExecutionContextProfile - #============================================================ - ## - # @if jp - # @brief CORBA ֥ȻȤμ - # - # ܥ֥Ȥ ExecutioncontextService ȤƤ CORBA ֥ - # ȻȤ롣 - # - # @return CORBA ֥Ȼ - # - # @else - # @brief Get the reference to the CORBA object - # - # Get the reference to the CORBA object as - # ExecutioncontextService of this object. - # - # @return The reference to CORBA object - # - # @endif - # void setObjRef(RTC::ExecutionContextService_ptr ec_ptr) - def setObjRef(self, ec_ptr): - self._worker.setECRef(ec_ptr) - self._profile.setObjRef(ec_ptr) - return - - - ## - # @if jp - # @brief CORBA ֥ȻȤμ - # - # ܥ֥Ȥ ExecutioncontextService ȤƤ CORBA ֥ - # ȻȤ롣 - # - # @return CORBA ֥Ȼ - # - # @else - # @brief Get the reference to the CORBA object - # - # Get the reference to the CORBA object as - # ExecutioncontextService of this object. - # - # @return The reference to CORBA object - # - # @endif - def getObjRef(self): - return self._profile.getObjRef() - - - ## - # @if jp - # @brief ExecutionKind ʸ󲽤 - # - # RTC::ExecutionKind Ƥ PERIODIC, EVENT_DRIVEN, - # OTHER ʸ󲽤롣 - # - # @param kind ExecutionKind - # @return ʸ󲽤줿ExecutionKind - # - # @else - # - # @brief Converting ExecutionKind enum to string - # - # This function converts enumeration (PERIODIC, EVENT_DRIVEN, - # OTHER) defined in RTC::ExecutionKind to string. - # - # @param kind ExecutionKind - # @return String of ExecutionKind - # - # @endif - # const char* getKindString(RTC::ExecutionKind kind) const - def getKindString(self, kind): - return self._profile.getKindString(kind) - - - ## - # @if jp - # @brief ExecutionKind ꤹ - # - # ExecutionContext ExecutionKind ꤹ - # - # @param kind ExecutionKind - # - # @else - # - # @brief Set the ExecutionKind - # - # This operation sets the kind of the execution context. - # - # @param kind ExecutionKind - # - # @endif - # RTC::ReturnCode_t setKind(RTC::ExecutionKind kind) - def setKind(self, kind): - return self._profile.setKind(kind) - - - ## - # @if jp - # @brief OwnerݡͥȤ򥻥åȤ롣 - # - # ECOwnerȤʤRTC򥻥åȤ롣 - # - # @param comp OwnerȤʤRTݡͥ - # @return ReturnCode_t Υ꥿󥳡 - # @else - # @brief Setting owner component of the execution context - # - # This function sets an RT-Component to be owner of the execution context. - # - # @param comp an owner RT-Component of this execution context - # @return The return code of ReturnCode_t type - # @endif - # RTC::ReturnCode_t setOwner(RTC::LightweightRTObject_ptr comp) - def setOwner(self, comp): - return self._profile.setOwner(comp) - - - ## - # @if jp - # @brief OwnerݡͥȤλȤ - # - # ECOwnerǤRTCλȤ롣 - # - # @return OwnerRTݡͥȤλ - # @else - # @brief Getting a reference of the owner component - # - # This function returns a reference of the owner RT-Component of - # this execution context - # - # @return a reference of the owner RT-Component - # @endif - # const RTC::RTObject_ptr getOwner() const - def getOwner(self): - return self._profile.getOwner() - - - ## - # @if jp - # @brief RTݡͥȤλüԥꥹȤ - # - # ϿƤ뻲üRTCΥꥹȤ롣 - # - # @return üRTCΥꥹ - # - # @else - # - # @brief Getting participant RTC list - # - # This function returns a list of participant RTC of the execution context. - # - # @return Participants RTC list - # - # @endif - # const RTC::RTCList& getComponentList() const - def getComponentList(self): - return self._profile.getComponentList() - - - ## - # @if jp - # @brief Properties򥻥åȤ - # - # ExecutionContextProfile::properties 򥻥åȤ롣 - # - # @param props ExecutionContextProfile::properties ˥åȤ - # ѥƥ - # - # @else - # @brief Setting Properties - # - # This function sets ExecutionContextProfile::properties by - # coil::Properties. - # - # @param props Properties to be set to - # ExecutionContextProfile::properties. - # - # @endif - # void setProperties(coil::Properties& props) - def setProperties(self, props): - self._profile.setProperties(props) - return - - - ## - # @if jp - # @brief Properties - # - # ExecutionContextProfile::properties 롣 - # - # @return coil::PropertiesѴ줿 - # ExecutionContextProfile::properties - # - # @else - # @brief Setting Properties - # - # This function sets ExecutionContextProfile::properties by - # coil::Properties. - # - # @param props Properties to be set to ExecutionContextProfile::properties. - # - # @endif - # const coil::Properties getProperties() const - def getProperties(self): - return self._profile.getProperties() - - - ## - # @if jp - # @brief Profile - # - # RTC::ExecutionContextProfile 롣 - # ExecutionContextProfile νͭϸƤӽФ¦ˤ롣줿 - # ֥Ȥפˤʤä硢ƤӽФ¦Ǥ餦 - # - # @return RTC::ExecutionContextProfile - # - # @else - # @brief Getting Profile - # - # This function gets RTC::ExecutionContextProfile. The ownership - # of the obtained ExecutionContextProfile is given to caller. The - # caller should release obtained object when it is unneccessary - # anymore. - # - # @return RTC::ExecutionContextProfile - # - # @endif - # RTC::ExecutionContextProfile* getProfile(void) - #def getProfile(self): - # return self._profile.getProfile() - - - # end of delegated functions to ExecutionContextProfile - #============================================================ - - #============================================================ - # Delegated functions to ExecutionContextWorker - #============================================================ - # bool isAllCurrentState(RTC::LifeCycleState state) - def isAllCurrentState(self, state): - return self._worker.isAllCurrentState(state) - - # bool isAllNextState(RTC::LifeCycleState state) - def isAllNextState(self, state): - return self._worker.isAllNextState(state) - - # bool isOneOfCurrentState(RTC::LifeCycleState state) - def isOneOfCurrentState(self, state): - return self._worker.isOneOfCurrentState(state) - - # bool isOneOfNextState(RTC::LifeCycleState state) - def isOneOfNextState(self, state): - return self._worker.isOneOfNextState(state) - - # void invokeWorker() { m_worker.invokeWorker(); } - def invokeWorker(self): - self._worker.invokeWorker() - return - - # void invokeWorkerPreDo() { m_worker.invokeWorkerPreDo(); } - def invokeWorkerPreDo(self): - self._worker.invokeWorkerPreDo() - return - - # void invokeWorkerDo() { m_worker.invokeWorkerDo(); } - def invokeWorkerDo(self): - self._worker.invokeWorkerDo() - return - - # void invokeWorkerPostDo() { m_worker.invokeWorkerPostDo(); } - def invokeWorkerPostDo(self): - self._worker.invokeWorkerPostDo() - return - - # template virtual functions related to start/stop - # virtual bool onIsRunning(bool running) { return running; } - def onIsRunning(self, running): - return running - - # virtual RTC::ReturnCode_t onStarting() { return RTC::RTC_OK; } - def onStarting(self): - return RTC.RTC_OK - - # virtual RTC::ReturnCode_t onStarted() { return RTC::RTC_OK; } - def onStarted(self): - return RTC.RTC_OK - - # virtual RTC::ReturnCode_t onStopping() { return RTC::RTC_OK; } - def onStopping(self): - return RTC.RTC_OK - - # virtual RTC::ReturnCode_t onStopped() { return RTC::RTC_OK; } - def onStopped(self): - return RTC.RTC_OK - - # template virtual functions getting/setting execution rate - # virtual double onGetRate(double rate) const { return rate; } - def onGetRate(self, rate): - return rate - - # virtual double onSettingRate(double rate) { return rate; } - def onSettingRate(self, rate): - return rate - - # virtual RTC::ReturnCode_t onSetRate(double rate) { return RTC::RTC_OK; } - def onSetRate(self, rate): - return RTC.RTC_OK - - # template virtual functions adding/removing component - # virtual RTC::ReturnCode_t - # onAddingComponent(RTC::LightweightRTObject_ptr rtobj) - def onAddingComponent(self, rtobj): - return RTC.RTC_OK - - # virtual RTC::ReturnCode_t - # onAddedComponent(RTC::LightweightRTObject_ptr rtobj) - def onAddedComponent(self, rtobj): - return RTC.RTC_OK - - # virtual RTC::ReturnCode_t - # onRemovingComponent(RTC::LightweightRTObject_ptr rtobj) - def onRemovingComponent(self, rtobj): - return RTC.RTC_OK - - # virtual RTC::ReturnCode_t - # onRemovedComponent(RTC::LightweightRTObject_ptr rtobj) - def onRemovedComponent(self, rtobj): - return RTC.RTC_OK - - # template virtual functions related to activation/deactivation/reset - # virtual RTC::ReturnCode_t - # onActivating(RTC::LightweightRTObject_ptr comp) - def onActivating(self, comp): - return RTC.RTC_OK - - # virtual RTC::ReturnCode_t - # onWaitingActivated(RTC_impl::RTObjectStateMachine* comp, long int count) - def onWaitingActivated(self, comp, count): - return RTC.RTC_OK - - # virtual RTC::ReturnCode_t - # onActivated(RTC_impl::RTObjectStateMachine* comp, - # long int count) - def onActivated(self, comp, count): - return RTC.RTC_OK - - # virtual RTC::ReturnCode_t - # onDeactivating(RTC::LightweightRTObject_ptr comp) - def onDeactivating(self, comp): - return RTC.RTC_OK - - # virtual RTC::ReturnCode_t - # onWaitingDeactivated(RTC_impl::RTObjectStateMachine* comp, long int count) - def onWaitingDeactivated(self, comp, count): - return RTC.RTC_OK - - # virtual RTC::ReturnCode_t - # onDeactivated(RTC_impl::RTObjectStateMachine* comp, long int count) - def onDeactivated(self, comp, count): - return RTC.RTC_OK - - # virtual RTC::ReturnCode_t onResetting(RTC::LightweightRTObject_ptr comp) - def onResetting(self, comp): - return RTC.RTC_OK - - # virtual RTC::ReturnCode_t - # onWaitingReset(RTC_impl::RTObjectStateMachine* comp, long int count) - def onWaitingReset(self, comp, count): - return RTC.RTC_OK - - # virtual RTC::ReturnCode_t - # onReset(RTC_impl::RTObjectStateMachine* comp, long int count) - def onReset(self, comp, count): - return RTC.RTC_OK - - # virtual RTC::LifeCycleState - # onGetComponentState(RTC::LifeCycleState state) - def onGetComponentState(self, state): - return state - - # virtual RTC::ExecutionKind - # onGetKind(RTC::ExecutionKind kind) const - def onGetKind(self, kind): - return kind - - # virtual RTC::ExecutionContextProfile* - # onGetProfile(RTC::ExecutionContextProfile*& profile) - def onGetProfile(self, profile): - return profile - - - #============================================================ - # private functions - - ## - # @if jp - # @brief Properties¹ԥƥȤ򥻥åȤ - # @else - # @brief Setting execution rate from given properties. - # @endif - # bool ExecutionContextBase::setExecutionRate(coil::Properties& props) - def setExecutionRate(self, props): - if props.findNode("rate"): - rate_ = [0.0] - if OpenRTM_aist.stringTo(rate_, props.getProperty("rate")): - self.setRate(rate_[0]) - return True - return False - - - ## - # @if jp - # @brief Propertiesܥ⡼ɤ򥻥åȤ - # @else - # @brief Setting state transition mode from given properties. - # @endif - # bool ExecutionContextBase:: - # setTransitionMode(coil::Properties& props, const char* key, bool& flag) - def setTransitionMode(self, props, key, flag): - self._rtcout.RTC_TRACE("setTransitionMode(%s)", key) - toSTR_ = lambda x: "YES" if x else "NO" - if props.findNode(key): - flag[0] = OpenRTM_aist.toBool(props.getProperty(key), "YES", "NO", "YES") - self._rtcout.RTC_DEBUG("Transition Mode: %s = %s", - (key, toSTR_(flag[0]))) - return True - - self._rtcout.RTC_DEBUG("Configuration %s not found.", key) - return False - - - ## - # @if jp - # @brief PropertiesTimeout򥻥åȤ - # @else - # @brief Setting state transition timeout from given properties. - # @endif - # bool ExecutionContextBase:: - # setTimeout(coil::Properties& props, const char* key, - # coil::TimeValue& timevalue) - def setTimeout(self, props, key, timevalue): - self._rtcout.RTC_TRACE("setTimeout(%s)", key) - if props.findNode(key): - timeout_ = [0.0] - if OpenRTM_aist.stringTo(timeout_, props.getProperty(key)): - timevalue[0] = OpenRTM_aist.TimeValue(timeout_[0]) - self._rtcout.RTC_DEBUG("Timeout (%s): %f [s]", (key, timeout_[0])) - return True - self._rtcout.RTC_DEBUG("Configuration %s not found.", key) - return False - - def is_running(self): - self._rtcout.RTC_TRACE("is_running()") - return self.isRunning() - def get_rate(self): - return self.getRate() - def set_rate(self, rate): - return self.setRate(rate) - def activate_component(self, comp): - return self.activateComponent(comp) - def deactivate_component(self, comp): - return self.deactivateComponent(comp) - def reset_component(self, comp): - return self.resetComponent(comp) - def get_component_state(self, comp): - return self.getComponentState(comp) - def get_kind(self): - return self.getKind() - def add_component(self, comp): - return self.addComponent(comp) - def remove_component(self, comp): - return self.removeComponent(comp) - def get_profile(self): - return self.getProfile() - - - + ## + # @if jp + # @brief RTコンポーネントを追加する + # @else + # @brief Add an RT-component + # @endif + # RTC::ReturnCode_t ExecutionContextBase:: + # addComponent(RTC::LightweightRTObject_ptr comp) + def addComponent(self, comp): + + self._rtcout.RTC_TRACE("addComponent()") + ret_ = self.onAddingComponent(comp) # Template + if ret_ != RTC.RTC_OK: + self._rtcout.RTC_ERROR( + "Error: onAddingComponent(). RTC is not attached.") + return ret_ + + ret_ = self._worker.addComponent(comp) # Actual addComponent() + if ret_ != RTC.RTC_OK: + self._rtcout.RTC_ERROR("Error: ECWorker addComponent() faild.") + return ret_ + + ret_ = self._profile.addComponent(comp) # Actual addComponent() + if ret_ != RTC.RTC_OK: + self._rtcout.RTC_ERROR("Error: ECProfile addComponent() faild.") + return ret_ + + ret_ = self.onAddedComponent(comp) # Template + if ret_ != RTC.RTC_OK: + self._rtcout.RTC_ERROR("Error: onAddedComponent() faild.") + self._rtcout.RTC_INFO("Removing attached RTC.") + self._worker.removeComponent(comp) + self._profile.removeComponent(comp) + return ret_ + + self._rtcout.RTC_INFO("Component has been added to this EC.") + return RTC.RTC_OK + + ## + # @if jp + # @brief RTコンポーネントを参加者リストから削除する + # @else + # @brief Remove the RT-Component from participant list + # @endif + # RTC::ReturnCode_t ExecutionContextBase:: + # removeComponent(RTC::LightweightRTObject_ptr comp) + + def removeComponent(self, comp): + self._rtcout.RTC_TRACE("removeComponent()") + ret_ = self.onRemovingComponent(comp) # Template + if ret_ != RTC.RTC_OK: + self._rtcout.RTC_ERROR("Error: onRemovingComponent(). " + "RTC will not not attached.") + return ret_ + + ret_ = self._worker.removeComponent(comp) # Actual removeComponent() + if ret_ != RTC.RTC_OK: + self._rtcout.RTC_ERROR("Error: ECWorker removeComponent() faild.") + return ret_ + + ret_ = self._profile.removeComponent(comp) # Actual removeComponent() + if ret_ != RTC.RTC_OK: + self._rtcout.RTC_ERROR("Error: ECProfile removeComponent() faild.") + return ret_ + + ret_ = self.onRemovedComponent(comp) # Template + if ret_ != RTC.RTC_OK: + self._rtcout.RTC_ERROR("Error: onRemovedComponent() faild.") + self._rtcout.RTC_INFO("Removing attached RTC.") + self._worker.removeComponent(comp) + self._profile.removeComponent(comp) + return ret_ + + self._rtcout.RTC_INFO("Component has been removeed to this EC.") + return RTC.RTC_OK + + ## + # @if jp + # @brief RTコンポーネントをアクティブ化する + # @else + # @brief Activate an RT-component + # @endif + # RTC::ReturnCode_t ExecutionContextBase:: + # activateComponent(RTC::LightweightRTObject_ptr comp) + + def activateComponent(self, comp): + self._rtcout.RTC_TRACE("activateComponent()") + ret_ = self.onActivating(comp) # Template + if ret_ != RTC.RTC_OK: + self._rtcout.RTC_ERROR("onActivating() failed.") + return ret_ + + ret_, rtobj_ = self._worker.activateComponent( + comp) # Actual activateComponent() + if ret_ != RTC.RTC_OK: + return ret_ + + if not self._syncActivation: # Asynchronous activation mode + ret_ = self.onActivated(rtobj_, -1) + if ret_ != RTC.RTC_OK: + self._rtcout.RTC_ERROR("onActivated() failed.") + + return ret_ + + # ------------------------------------------------------------ + # Synchronized activation mode + self._rtcout.RTC_DEBUG("Synchronous activation mode. " + "Waiting for the RTC to be ACTIVE state. ") + return self.waitForActivated(rtobj_) + + # RTC::ReturnCode_t ExecutionContextBase:: + # waitForActivated(RTC_impl::RTObjectStateMachine* rtobj) + + def waitForActivated(self, rtobj): + count_ = 0 + ret_ = self.onWaitingActivated(rtobj, count_) + if ret_ != RTC.RTC_OK: + self._rtcout.RTC_ERROR("onWaitingActivated failed.") + return ret_ + + cycle_ = int(float(self._activationTimeout.toDouble()) / + float(self.getPeriod().toDouble())) + self._rtcout.RTC_DEBUG("Timeout is %f [s] (%f [s] in %d times)", + (float(self._activationTimeout.toDouble()), self.getRate(), cycle_)) + # Wating INACTIVE -> ACTIVE + starttime_ = OpenRTM_aist.Time().gettimeofday() + + while rtobj.isCurrentState(RTC.INACTIVE_STATE): + + ret_ = self.onWaitingActivated(rtobj, count_) # Template method + if ret_ != RTC.RTC_OK: + self._rtcout.RTC_ERROR("onWaitingActivated failed.") + return ret_ + + time.sleep(self.getPeriod().toDouble()) + delta_ = OpenRTM_aist.Time().gettimeofday() - starttime_ + self._rtcout.RTC_DEBUG("Waiting to be ACTIVE state. %f [s] slept (%d/%d)", + (float(delta_.toDouble()), count_, cycle_)) + count_ += 1 + if delta_.toDouble() > self._activationTimeout.toDouble() or count_ > cycle_: + self._rtcout.RTC_WARN("The component is not responding.") + break + + # Now State must be ACTIVE or ERROR + if rtobj.isCurrentState(RTC.INACTIVE_STATE): + self._rtcout.RTC_ERROR("Unknown error: Invalid state transition.") + return RTC.RTC_ERROR + + if rtobj.isCurrentState(RTC.ERROR_STATE): + self._rtcout.RTC_ERROR( + "State of the RTC transitioned to ERROR_STATE.") + return RTC.PRECONDITION_NOT_MET + + self._rtcout.RTC_DEBUG( + "Current state is %s", + self.getStateString( + rtobj.getState())) + ret_ = self.onActivated(rtobj, count_) # Template method + if ret_ != RTC.RTC_OK: + self._rtcout.RTC_ERROR("onActivated() failed.") + + self._rtcout.RTC_DEBUG("onActivated() done.") + return ret_ + + ## + # @if jp + # @brief RTコンポーネントを非アクティブ化する + # @else + # @brief Deactivate an RT-component + # @endif + # RTC::ReturnCode_t ExecutionContextBase:: + # deactivateComponent(RTC::LightweightRTObject_ptr comp) + + def deactivateComponent(self, comp): + self._rtcout.RTC_TRACE("deactivateComponent()") + ret_ = self.onDeactivating(comp) # Template + if ret_ != RTC.RTC_OK: + self._rtcout.RTC_ERROR("onDeactivating() failed.") + return ret_ + + # Deactivate all the RTCs + ret_, rtobj_ = self._worker.deactivateComponent(comp) + if ret_ != RTC.RTC_OK: + return ret_ + + if not self._syncDeactivation: + ret_ = self.onDeactivated(rtobj_, -1) + if ret_ != RTC.RTC_OK: + self._rtcout.RTC_ERROR("onDeactivated() failed.") + return ret_ + + # ------------------------------------------------------------ + # Waiting for synchronized deactivation + self._rtcout.RTC_DEBUG("Synchronous deactivation mode. " + "Waiting for the RTC to be INACTIVE state. ") + return self.waitForDeactivated(rtobj_) + + # RTC::ReturnCode_t ExecutionContextBase:: + # waitForDeactivated(RTC_impl::RTObjectStateMachine* rtobj) + + def waitForDeactivated(self, rtobj): + count_ = 0 + ret_ = self.onWaitingDeactivated(rtobj, count_) + if ret_ != RTC.RTC_OK: + self._rtcout.RTC_ERROR("onWaitingDeactivated failed.") + return ret_ + + cycle_ = int( + float( + self._deactivationTimeout.toDouble()) / + float( + self.getPeriod().toDouble())) + self._rtcout.RTC_DEBUG("Timeout is %f [s] (%f [s] in %d times)", + (float(self._deactivationTimeout.toDouble()), self.getRate(), cycle_)) + # Wating ACTIVE -> INACTIVE + starttime_ = OpenRTM_aist.Time().gettimeofday() + while rtobj.isCurrentState(RTC.ACTIVE_STATE): + ret_ = self.onWaitingDeactivated(rtobj, count_) # Template method + if ret_ != RTC.RTC_OK: + self._rtcout.RTC_ERROR("onWaitingDeactivated failed.") + return ret_ + + time.sleep(self.getPeriod().toDouble()) + delta_ = OpenRTM_aist.Time().gettimeofday() - starttime_ + self._rtcout.RTC_DEBUG("Waiting to be INACTIVE state. Sleeping %f [s] (%d/%d)", + (float(delta_.toDouble()), count_, cycle_)) + count_ += 1 + if delta_.toDouble() > self._deactivationTimeout.toDouble() or count_ > cycle_: + self._rtcout.RTC_ERROR("The component is not responding.") + break + + # Now State must be INACTIVE or ERROR + if rtobj.isCurrentState(RTC.ACTIVE_STATE): + self._rtcout.RTC_ERROR("Unknown error: Invalid state transition.") + return RTC.RTC_ERROR + + if rtobj.isCurrentState(RTC.ERROR_STATE): + self._rtcout.RTC_ERROR( + "State of the RTC transitioned to ERROR_STATE.") + return RTC.PRECONDITION_NOT_MET + + self._rtcout.RTC_DEBUG( + "Current state is %s", + self.getStateString( + rtobj.getState())) + ret_ = self.onDeactivated(rtobj, count_) + if ret_ != RTC.RTC_OK: + self._rtcout.RTC_ERROR("onDeactivated() failed.") + + self._rtcout.RTC_DEBUG("onDeactivated() done.") + return ret_ + + ## + # @if jp + # @brief RTコンポーネントをリセットする + # @else + # @brief Reset the RT-component + # @endif + # RTC::ReturnCode_t ExecutionContextBase:: + # resetComponent(RTC::LightweightRTObject_ptr comp) + + def resetComponent(self, comp): + self._rtcout.RTC_TRACE("resetComponent()") + ret_ = self.onResetting(comp) # Template + if ret_ != RTC.RTC_OK: + self._rtcout.RTC_ERROR("onResetting() failed.") + return ret_ + + ret_, rtobj_ = self._worker.resetComponent( + comp) # Actual resetComponent() + if ret_ != RTC.RTC_OK: + return ret_ + if not self._syncReset: + ret_ = self.onReset(rtobj_, -1) + if ret_ != RTC.RTC_OK: + self._rtcout.RTC_ERROR("onReset() failed.") + return ret_ + + # ------------------------------------------------------------ + # Waiting for synchronized reset + self._rtcout.RTC_DEBUG("Synchronous reset mode. " + "Waiting for the RTC to be INACTIVE state. ") + return self.waitForReset(rtobj_) + + # RTC::ReturnCode_t ExecutionContextBase:: + # waitForReset(RTC_impl::RTObjectStateMachine* rtobj) + + def waitForReset(self, rtobj): + count_ = 0 + ret_ = self.onWaitingReset(rtobj, count_) + if ret_ != RTC.RTC_OK: + self._rtcout.RTC_ERROR("onWaitingReset() failed.") + return ret_ + + cycle_ = int(float(self._resetTimeout.toDouble()) / + float(self.getPeriod().toDouble())) + self._rtcout.RTC_DEBUG("Timeout is %f [s] (%f [s] in %d times)", + (float(self._resetTimeout.toDouble()), self.getRate(), cycle_)) + # Wating ERROR -> INACTIVE + starttime_ = OpenRTM_aist.Time().gettimeofday() + while rtobj.isCurrentState(RTC.ERROR_STATE): + ret_ = self.onWaitingReset(rtobj, count_) # Template + if ret_ != RTC.RTC_OK: + self._rtcout.RTC_ERROR("onWaitingReset failed.") + return ret_ + + time.sleep(self.getPeriod().toDouble()) + delta_ = OpenRTM_aist.Time().gettimeofday() - starttime_ + self._rtcout.RTC_DEBUG("Waiting to be INACTIVE state. Sleeping %f [s] (%d/%d)", + (float(delta_.toDouble()), count_, cycle_)) + count_ += 1 + if delta_.toDouble() > self._resetTimeout.toDouble() or count_ > cycle_: + self._rtcout.RTC_ERROR("The component is not responding.") + break + + # Now State must be INACTIVE + if not rtobj.isCurrentState(RTC.INACTIVE_STATE): + self._rtcout.RTC_ERROR("Unknown error: Invalid state transition.") + return RTC.RTC_ERROR + + self._rtcout.RTC_DEBUG( + "Current state is %s", + self.getStateString( + rtobj.getState())) + ret_ = self.onReset(rtobj, count_) # Template method + if ret_ != RTC.RTC_OK: + self._rtcout.RTC_ERROR("onResetd() failed.") + + self._rtcout.RTC_DEBUG("onReset() done.") + return ret_ + + ## + # @if jp + # @brief RTコンポーネントの状態を取得する + # + # 指定したRTコンポーネントの状態(LifeCycleState)を取得する。指定し + # たRTコンポーネントが参加者リストに含まれない場合は、 + # UNKNOWN_STATE が返される。 + # + # @param comp 状態取得対象RTコンポーネント + # + # @return 現在の状態(LifeCycleState) + # + # @else + # + # @brief Get RT-component's state + # + # This operation shall report the LifeCycleState of the given + # participant RTC. UNKNOWN_STATE will be returned, if the given + # RT-Component is not inclued in the participant list. + # + # @param comp The target RT-Component to get the state + # + # @return The current state of the target RT-Component(LifeCycleState) + # + # @endif + # RTC::LifeCycleState ExecutionContextBase:: + # getComponentState(RTC::LightweightRTObject_ptr comp) + + def getComponentState(self, comp): + state_ = self._worker.getComponentState(comp) + self._rtcout.RTC_TRACE( + "getComponentState() = %s", + self.getStateString(state_)) + if state_ == RTC.CREATED_STATE: + self._rtcout.RTC_ERROR("CREATED state: not initialized " + "RTC or unknwon RTC specified.") + + return self.onGetComponentState(state_) + + # const char* ExecutionContextBase::getStateString(RTC::LifeCycleState + # state) + + def getStateString(self, state): + return self._worker.getStateString(state) + + ## + # @if jp + # @brief ExecutionKind を取得する + # + # 本 ExecutionContext の ExecutionKind を取得する + # + # @return ExecutionKind + # + # @else + # + # @brief Get the ExecutionKind + # + # This operation shall report the execution kind of the execution + # context. + # + # @return ExecutionKind + # + # @endif + # RTC::ExecutionKind ExecutionContextBase::getKind(void) const + + def getKind(self): + kind_ = self._profile.getKind() + self._rtcout.RTC_TRACE("getKind() = %s", self.getKindString(kind_)) + kind_ = self.onGetKind(kind_) + self._rtcout.RTC_DEBUG( + "onGetKind() returns %s", + self.getKindString(kind_)) + return kind_ + + ## + # @if jp + # @brief Profileを取得する + # + # RTC::ExecutionContextProfile を取得する。取得した + # ExecutionContextProfile の所有権は呼び出し側にある。取得されたオ + # ブジェクトが不要になった場合、呼び出し側が開放する責任を負う。 + # + # @return RTC::ExecutionContextProfile + # + # @else + # @brief Getting Profile + # + # This function gets RTC::ExecutionContextProfile. The ownership + # of the obtained ExecutionContextProfile is given to caller. The + # caller should release obtained object when it is unneccessary + # anymore. + # + # @return RTC::ExecutionContextProfile + # + # @endif + # RTC::ExecutionContextProfile* ExecutionContextBase::getProfile(void) + + def getProfile(self): + self._rtcout.RTC_TRACE("getProfile()") + prof_ = self._profile.getProfile() + self._rtcout.RTC_DEBUG("kind: %s", self.getKindString(prof_.kind)) + self._rtcout.RTC_DEBUG("rate: %f", prof_.rate) + self._rtcout.RTC_DEBUG("properties:") + props_ = OpenRTM_aist.Properties() + OpenRTM_aist.NVUtil.copyToProperties(props_, prof_.properties) + self._rtcout.RTC_DEBUG(props_) + return self.onGetProfile(prof_) + + # ============================================================ + # Delegated functions to ExecutionContextProfile + # ============================================================ + ## + # @if jp + # @brief CORBA オブジェクト参照の取得 + # + # 本オブジェクトの ExecutioncontextService としての CORBA オブジェ + # クト参照を取得する。 + # + # @return CORBA オブジェクト参照 + # + # @else + # @brief Get the reference to the CORBA object + # + # Get the reference to the CORBA object as + # ExecutioncontextService of this object. + # + # @return The reference to CORBA object + # + # @endif + # void setObjRef(RTC::ExecutionContextService_ptr ec_ptr) + + def setObjRef(self, ec_ptr): + self._worker.setECRef(ec_ptr) + self._profile.setObjRef(ec_ptr) + return + + ## + # @if jp + # @brief CORBA オブジェクト参照の取得 + # + # 本オブジェクトの ExecutioncontextService としての CORBA オブジェ + # クト参照を取得する。 + # + # @return CORBA オブジェクト参照 + # + # @else + # @brief Get the reference to the CORBA object + # + # Get the reference to the CORBA object as + # ExecutioncontextService of this object. + # + # @return The reference to CORBA object + # + # @endif + + def getObjRef(self): + return self._profile.getObjRef() + + ## + # @if jp + # @brief ExecutionKind を文字列化する + # + # RTC::ExecutionKind で定義されている PERIODIC, EVENT_DRIVEN, + # OTHER を文字列化する。 + # + # @param kind ExecutionKind + # @return 文字列化されたExecutionKind + # + # @else + # + # @brief Converting ExecutionKind enum to string + # + # This function converts enumeration (PERIODIC, EVENT_DRIVEN, + # OTHER) defined in RTC::ExecutionKind to string. + # + # @param kind ExecutionKind + # @return String of ExecutionKind + # + # @endif + # const char* getKindString(RTC::ExecutionKind kind) const + + def getKindString(self, kind): + return self._profile.getKindString(kind) + + ## + # @if jp + # @brief ExecutionKind を設定する + # + # この ExecutionContext の ExecutionKind を設定する + # + # @param kind ExecutionKind + # + # @else + # + # @brief Set the ExecutionKind + # + # This operation sets the kind of the execution context. + # + # @param kind ExecutionKind + # + # @endif + # RTC::ReturnCode_t setKind(RTC::ExecutionKind kind) + + def setKind(self, kind): + return self._profile.setKind(kind) + + ## + # @if jp + # @brief Ownerコンポーネントをセットする。 + # + # このECのOwnerとなるRTCをセットする。 + # + # @param comp OwnerとなるRTコンポーネント + # @return ReturnCode_t 型のリターンコード + # @else + # @brief Setting owner component of the execution context + # + # This function sets an RT-Component to be owner of the execution context. + # + # @param comp an owner RT-Component of this execution context + # @return The return code of ReturnCode_t type + # @endif + # RTC::ReturnCode_t setOwner(RTC::LightweightRTObject_ptr comp) + + def setOwner(self, comp): + return self._profile.setOwner(comp) + + ## + # @if jp + # @brief Ownerコンポーネントの参照を取得する + # + # このECのOwnerであるRTCの参照を取得する。 + # + # @return OwnerRTコンポーネントの参照 + # @else + # @brief Getting a reference of the owner component + # + # This function returns a reference of the owner RT-Component of + # this execution context + # + # @return a reference of the owner RT-Component + # @endif + # const RTC::RTObject_ptr getOwner() const + + def getOwner(self): + return self._profile.getOwner() + + ## + # @if jp + # @brief RTコンポーネントの参加者リストを取得する + # + # 現在登録されている参加者RTCのリストを取得する。 + # + # @return 参加者RTCのリスト + # + # @else + # + # @brief Getting participant RTC list + # + # This function returns a list of participant RTC of the execution context. + # + # @return Participants RTC list + # + # @endif + # const RTC::RTCList& getComponentList() const + + def getComponentList(self): + return self._profile.getComponentList() + + ## + # @if jp + # @brief Propertiesをセットする + # + # ExecutionContextProfile::properties をセットする。 + # + # @param props ExecutionContextProfile::properties にセットするプ + # ロパティー + # + # @else + # @brief Setting Properties + # + # This function sets ExecutionContextProfile::properties by + # coil::Properties. + # + # @param props Properties to be set to + # ExecutionContextProfile::properties. + # + # @endif + # void setProperties(coil::Properties& props) + + def setProperties(self, props): + self._profile.setProperties(props) + return + + ## + # @if jp + # @brief Propertiesを取得する + # + # ExecutionContextProfile::properties を取得する。 + # + # @return coil::Propertiesに変換された + # ExecutionContextProfile::properties + # + # @else + # @brief Setting Properties + # + # This function sets ExecutionContextProfile::properties by + # coil::Properties. + # + # @param props Properties to be set to ExecutionContextProfile::properties. + # + # @endif + # const coil::Properties getProperties() const + + def getProperties(self): + return self._profile.getProperties() + + ## + # @if jp + # @brief Profileを取得する + # + # RTC::ExecutionContextProfile を取得する。取得した + # ExecutionContextProfile の所有権は呼び出し側にある。取得されたオ + # ブジェクトが不要になった場合、呼び出し側が開放する責任を負う。 + # + # @return RTC::ExecutionContextProfile + # + # @else + # @brief Getting Profile + # + # This function gets RTC::ExecutionContextProfile. The ownership + # of the obtained ExecutionContextProfile is given to caller. The + # caller should release obtained object when it is unneccessary + # anymore. + # + # @return RTC::ExecutionContextProfile + # + # @endif + # RTC::ExecutionContextProfile* getProfile(void) + # def getProfile(self): + # return self._profile.getProfile() + + # end of delegated functions to ExecutionContextProfile + # ============================================================ + + # ============================================================ + # Delegated functions to ExecutionContextWorker + # ============================================================ + # bool isAllCurrentState(RTC::LifeCycleState state) + + def isAllCurrentState(self, state): + return self._worker.isAllCurrentState(state) + + # bool isAllNextState(RTC::LifeCycleState state) + def isAllNextState(self, state): + return self._worker.isAllNextState(state) + + # bool isOneOfCurrentState(RTC::LifeCycleState state) + def isOneOfCurrentState(self, state): + return self._worker.isOneOfCurrentState(state) + + # bool isOneOfNextState(RTC::LifeCycleState state) + def isOneOfNextState(self, state): + return self._worker.isOneOfNextState(state) + + # void invokeWorker() { m_worker.invokeWorker(); } + def invokeWorker(self): + self._worker.invokeWorker() + return + + # void invokeWorkerPreDo() { m_worker.invokeWorkerPreDo(); } + def invokeWorkerPreDo(self): + self._worker.invokeWorkerPreDo() + return + + # void invokeWorkerDo() { m_worker.invokeWorkerDo(); } + def invokeWorkerDo(self): + self._worker.invokeWorkerDo() + return + + # void invokeWorkerPostDo() { m_worker.invokeWorkerPostDo(); } + def invokeWorkerPostDo(self): + self._worker.invokeWorkerPostDo() + return + + # template virtual functions related to start/stop + # virtual bool onIsRunning(bool running) { return running; } + def onIsRunning(self, running): + return running + + # virtual RTC::ReturnCode_t onStarting() { return RTC::RTC_OK; } + def onStarting(self): + return RTC.RTC_OK + + # virtual RTC::ReturnCode_t onStarted() { return RTC::RTC_OK; } + def onStarted(self): + return RTC.RTC_OK + + # virtual RTC::ReturnCode_t onStopping() { return RTC::RTC_OK; } + def onStopping(self): + return RTC.RTC_OK + + # virtual RTC::ReturnCode_t onStopped() { return RTC::RTC_OK; } + def onStopped(self): + return RTC.RTC_OK + + # template virtual functions getting/setting execution rate + # virtual double onGetRate(double rate) const { return rate; } + def onGetRate(self, rate): + return rate + + # virtual double onSettingRate(double rate) { return rate; } + def onSettingRate(self, rate): + return rate + + # virtual RTC::ReturnCode_t onSetRate(double rate) { return RTC::RTC_OK; } + def onSetRate(self, rate): + return RTC.RTC_OK + + # template virtual functions adding/removing component + # virtual RTC::ReturnCode_t + # onAddingComponent(RTC::LightweightRTObject_ptr rtobj) + def onAddingComponent(self, rtobj): + return RTC.RTC_OK + + # virtual RTC::ReturnCode_t + # onAddedComponent(RTC::LightweightRTObject_ptr rtobj) + def onAddedComponent(self, rtobj): + return RTC.RTC_OK + + # virtual RTC::ReturnCode_t + # onRemovingComponent(RTC::LightweightRTObject_ptr rtobj) + def onRemovingComponent(self, rtobj): + return RTC.RTC_OK + + # virtual RTC::ReturnCode_t + # onRemovedComponent(RTC::LightweightRTObject_ptr rtobj) + def onRemovedComponent(self, rtobj): + return RTC.RTC_OK + + # template virtual functions related to activation/deactivation/reset + # virtual RTC::ReturnCode_t + # onActivating(RTC::LightweightRTObject_ptr comp) + def onActivating(self, comp): + return RTC.RTC_OK + + # virtual RTC::ReturnCode_t + # onWaitingActivated(RTC_impl::RTObjectStateMachine* comp, long int count) + def onWaitingActivated(self, comp, count): + return RTC.RTC_OK + + # virtual RTC::ReturnCode_t + # onActivated(RTC_impl::RTObjectStateMachine* comp, + # long int count) + def onActivated(self, comp, count): + return RTC.RTC_OK + + # virtual RTC::ReturnCode_t + # onDeactivating(RTC::LightweightRTObject_ptr comp) + def onDeactivating(self, comp): + return RTC.RTC_OK + + # virtual RTC::ReturnCode_t + # onWaitingDeactivated(RTC_impl::RTObjectStateMachine* comp, long int + # count) + def onWaitingDeactivated(self, comp, count): + return RTC.RTC_OK + + # virtual RTC::ReturnCode_t + # onDeactivated(RTC_impl::RTObjectStateMachine* comp, long int count) + def onDeactivated(self, comp, count): + return RTC.RTC_OK + + # virtual RTC::ReturnCode_t onResetting(RTC::LightweightRTObject_ptr comp) + def onResetting(self, comp): + return RTC.RTC_OK + + # virtual RTC::ReturnCode_t + # onWaitingReset(RTC_impl::RTObjectStateMachine* comp, long int count) + def onWaitingReset(self, comp, count): + return RTC.RTC_OK + + # virtual RTC::ReturnCode_t + # onReset(RTC_impl::RTObjectStateMachine* comp, long int count) + def onReset(self, comp, count): + return RTC.RTC_OK + + # virtual RTC::LifeCycleState + # onGetComponentState(RTC::LifeCycleState state) + def onGetComponentState(self, state): + return state + + # virtual RTC::ExecutionKind + # onGetKind(RTC::ExecutionKind kind) const + def onGetKind(self, kind): + return kind + + # virtual RTC::ExecutionContextProfile* + # onGetProfile(RTC::ExecutionContextProfile*& profile) + def onGetProfile(self, profile): + return profile + + # ============================================================ + # private functions + + ## + # @if jp + # @brief Propertiesから実行コンテキストをセットする + # @else + # @brief Setting execution rate from given properties. + # @endif + # bool ExecutionContextBase::setExecutionRate(coil::Properties& props) + + def setExecutionRate(self, props): + if props.findNode("rate"): + rate_ = 0.0 + ret, rate_ = OpenRTM_aist.stringTo( + rate_, props.getProperty("rate")) + if ret: + self.setRate(rate_) + return True + return False + + ## + # @if jp + # @brief Propertiesから状態遷移モードをセットする + # @else + # @brief Setting state transition mode from given properties. + # @endif + # bool ExecutionContextBase:: + # setTransitionMode(coil::Properties& props, const char* key, bool& flag) + + def setTransitionMode(self, props, key, flag=False): + self._rtcout.RTC_TRACE("setTransitionMode(%s)", key) + def toSTR_(x): return "YES" if x else "NO" + if props.findNode(key): + flag = OpenRTM_aist.toBool( + props.getProperty(key), "YES", "NO", "YES") + self._rtcout.RTC_DEBUG("Transition Mode: %s = %s", + (key, toSTR_(flag))) + return True, flag + + self._rtcout.RTC_DEBUG("Configuration %s not found.", key) + return False, flag + + ## + # @if jp + # @brief Propertiesから状態遷移Timeoutをセットする + # @else + # @brief Setting state transition timeout from given properties. + # @endif + # bool ExecutionContextBase:: + # setTimeout(coil::Properties& props, const char* key, + # coil::TimeValue& timevalue) + + def setTimeout(self, props, key, timevalue=0.0): + self._rtcout.RTC_TRACE("setTimeout(%s)", key) + if props.findNode(key): + timeout_ = 0.0 + ret, timeout_ = OpenRTM_aist.stringTo( + timeout_, props.getProperty(key)) + if ret: + timevalue = OpenRTM_aist.TimeValue(timeout_) + self._rtcout.RTC_DEBUG("Timeout (%s): %f [s]", (key, timeout_)) + return True, timevalue + self._rtcout.RTC_DEBUG("Configuration %s not found.", key) + return False, timevalue + + def is_running(self): + self._rtcout.RTC_TRACE("is_running()") + return self.isRunning() + + def get_rate(self): + return self.getRate() + + def set_rate(self, rate): + return self.setRate(rate) + + def activate_component(self, comp): + return self.activateComponent(comp) + + def deactivate_component(self, comp): + return self.deactivateComponent(comp) + + def reset_component(self, comp): + return self.resetComponent(comp) + + def get_component_state(self, comp): + return self.getComponentState(comp) + + def get_kind(self): + return self.getKind() + + def add_component(self, comp): + return self.addComponent(comp) + + def remove_component(self, comp): + return self.removeComponent(comp) + + def get_profile(self): + return self.getProfile() executioncontextfactory = None - -class ExecutionContextFactory(OpenRTM_aist.Factory,ExecutionContextBase): - def __init__(self): - OpenRTM_aist.Factory.__init__(self) - return - def __del__(self): - pass - def instance(): - global executioncontextfactory +class ExecutionContextFactory(OpenRTM_aist.Factory, ExecutionContextBase): + def __init__(self): + OpenRTM_aist.Factory.__init__(self) + return + + def __del__(self): + pass - if executioncontextfactory is None: - executioncontextfactory = ExecutionContextFactory() + def instance(): + global executioncontextfactory - return executioncontextfactory + if executioncontextfactory is None: + executioncontextfactory = ExecutionContextFactory() - instance = staticmethod(instance) + return executioncontextfactory + instance = staticmethod(instance) diff --git a/OpenRTM_aist/ExecutionContextProfile.py b/OpenRTM_aist/ExecutionContextProfile.py index 7e4ee0ca..8a8f09aa 100644 --- a/OpenRTM_aist/ExecutionContextProfile.py +++ b/OpenRTM_aist/ExecutionContextProfile.py @@ -1,5 +1,5 @@ #!/usr/bin/env python -# -*- coding: euc-jp -*- +# -*- coding: utf-8 -*- ## # @file ExecutionContextProfile.py @@ -28,7 +28,7 @@ ## # @if jp # @class ExecutionContextProfile -# @brief ExecutionContextProfile 饹 +# @brief ExecutionContextProfile クラス # # @since 1.2.0 # @@ -39,617 +39,625 @@ # @since 1.2.0 # # @endif -class ExecutionContextProfile: - """ - """ - - ## - # @if jp - # @brief ǥեȥ󥹥ȥ饯 - # - # ǥեȥ󥹥ȥ饯 - # ץե˰ʲιܤꤹ롣 - # - kind : PERIODIC - # - rate : 0.0 - # - # @else - # @brief Default Constructor - # - # Default Constructor - # Set the following items to profile. - # - kind : PERIODIC - # - rate : 0.0 - # - # @endif - # ExecutionContextProfile(RTC::ExecutionKind kind = RTC::PERIODIC); - def __init__(self, kind = RTC.PERIODIC): - global DEFAULT_PERIOD - self._rtcout = OpenRTM_aist.Manager.instance().getLogbuf("periodic_ecprofile") - self._period = OpenRTM_aist.TimeValue(DEFAULT_PERIOD) - self._rtcout.RTC_TRACE("ExecutionContextProfile.__init__()") - self._rtcout.RTC_DEBUG("Actual rate: %d [sec], %d [usec]", - (self._period.sec(), self._period.usec())) - self._profileMutex = threading.RLock() - self._ref = RTC.ExecutionContext._nil - self._profile = RTC.ExecutionContextProfile(RTC.PERIODIC, - (1.0/self._period.toDouble()), - RTC.DataFlowComponent._nil, [], []) - return - - - ## - # @if jp - # @brief ExecitionContextProfileλ - # - # - # - # @else - # @brief Destructor - # - # Destructor - # - # @endif - def exit(self): - self._rtcout.RTC_TRACE("exit") - - # cleanup EC's profile - self._profile.owner = RTC.DataFlowComponent._nil - self._profile.participants = [] - self._profile.properties = [] - self._ref = RTC.ExecutionContext._nil - return - - - ## - # @if jp - # @brief CORBA ֥ȻȤ򥻥å - # - # ExecutioncontextService ȤƤ CORBA ֥ - # ȻȤ򥻥åȤ롣 - # - # @param ec_ptr CORBA ֥Ȼ - # - # @else - # @brief Set the reference to the CORBA object - # - # Set the reference to the CORBA object as - # ExecutioncontextService of this object. - # - # @param ec_ptr The reference to CORBA object - # - # @endif - # void setObjRef(RTC::ExecutionContextService_ptr ec_ptr); - def setObjRef(self, ec_ptr): - self._rtcout.RTC_TRACE("setObjRef()") - assert(not CORBA.is_nil(ec_ptr)) - guard = OpenRTM_aist.ScopedLock(self._profileMutex) - self._ref = ec_ptr - del guard - return - - - ## - # @if jp - # @brief CORBA ֥ȻȤμ - # - # ܥ֥Ȥ ExecutioncontextService ȤƤ CORBA ֥ - # ȻȤ롣 - # - # @return CORBA ֥Ȼ - # - # @else - # @brief Get the reference to the CORBA object - # - # Get the reference to the CORBA object as - # ExecutioncontextService of this object. - # - # @return The reference to CORBA object - # - # @endif - # RTC::ExecutionContextService_ptr getObjRef(void) const; - def getObjRef(self): - self._rtcout.RTC_TRACE("getObjRef()") - guard = OpenRTM_aist.ScopedLock(self._profileMutex) - return self._ref - - - ## - # @if jp - # @brief ExecutionContext μ¹Լ(Hz)ꤹ - # - # Active ֤ˤRTݡͥȤ¹Ԥ(ñ:Hz)ꤹ - # 롣¹ԼѹϡDataFlowComponentAction - # on_rate_changed ˤäƳRTݡͥȤã롣 - # - # @param rate (ñ:Hz) - # - # @return ReturnCode_t Υ꥿󥳡 - # RTC_OK: ェλ - # BAD_PARAMETER: ͤ - # - # @else - # - # @brief Set execution rate(Hz) of ExecutionContext - # - # This operation shall set the rate (in hertz) at which this - # contexts Active participating RTCs are being called. If the - # execution kind of the context is PERIODIC, a rate change shall - # result in the invocation of on_rate_changed on any RTCs - # realizing DataFlowComponentAction that are registered with any - # RTCs participating in the context. - # - # @param rate Execution cycle(Unit:Hz) - # - # @return The return code of ReturnCode_t type - # RTC_OK: Succeed - # BAD_PARAMETER: Invalid value. The value might be negative. - # - # @endif - # RTC::ReturnCode_t setRate(double rate); - def setRate(self, rate): - self._rtcout.RTC_TRACE("setRate(%f)", rate) - if rate <= 0.0: - return RTC.BAD_PARAMETER - - guard = OpenRTM_aist.ScopedLock(self._profileMutex) - self._profile.rate = rate - self._period = OpenRTM_aist.TimeValue(1.0 / rate) - return RTC.RTC_OK - - - # RTC::ReturnCode_t setPeriod(double sec, coil::TimeValue tv); - def setPeriod(self, sec=None, tv=None): - if sec: - self._rtcout.RTC_TRACE("setPeriod(%f [sec])", sec) - if sec <= 0.0: - return RTC.BAD_PARAMETER - guard = OpenRTM_aist.ScopedLock(self._profileMutex) - self._profile.rate = 1.0 / sec - self._period = OpenRTM_aist.TimeValue(sec) - del guard - return RTC.RTC_OK; - elif tv: - self._rtcout.RTC_TRACE("setPeriod(%f [sec])", tv.toDouble()) - if tv.toDouble() < 0.0: + +class ExecutionContextProfile: + """ + """ + + ## + # @if jp + # @brief デフォルトコンストラクタ + # + # デフォルトコンストラクタ + # プロファイルに以下の項目を設定する。 + # - kind : PERIODIC + # - rate : 0.0 + # + # @else + # @brief Default Constructor + # + # Default Constructor + # Set the following items to profile. + # - kind : PERIODIC + # - rate : 0.0 + # + # @endif + # ExecutionContextProfile(RTC::ExecutionKind kind = RTC::PERIODIC); + def __init__(self, kind=RTC.PERIODIC): + global DEFAULT_PERIOD + self._rtcout = OpenRTM_aist.Manager.instance().getLogbuf("periodic_ecprofile") + self._period = OpenRTM_aist.TimeValue(DEFAULT_PERIOD) + self._rtcout.RTC_TRACE("ExecutionContextProfile.__init__()") + self._rtcout.RTC_DEBUG("Actual rate: %d [sec], %d [usec]", + (self._period.sec(), self._period.usec())) + self._profileMutex = threading.RLock() + self._ref = RTC.ExecutionContext._nil + self._profile = RTC.ExecutionContextProfile(RTC.PERIODIC, + (1.0 / self._period.toDouble()), + RTC.DataFlowComponent._nil, [], []) + return + + ## + # @if jp + # @brief ExecitionContextProfile終了処理 + # + # + # + # @else + # @brief Destructor + # + # Destructor + # + # @endif + + def exit(self): + self._rtcout.RTC_TRACE("exit") + + # cleanup EC's profile + self._profile.owner = RTC.DataFlowComponent._nil + self._profile.participants = [] + self._profile.properties = [] + self._ref = RTC.ExecutionContext._nil + return + + ## + # @if jp + # @brief CORBA オブジェクト参照をセット + # + # ExecutioncontextService としての CORBA オブジェ + # クト参照をセットする。 + # + # @param ec_ptr CORBA オブジェクト参照 + # + # @else + # @brief Set the reference to the CORBA object + # + # Set the reference to the CORBA object as + # ExecutioncontextService of this object. + # + # @param ec_ptr The reference to CORBA object + # + # @endif + # void setObjRef(RTC::ExecutionContextService_ptr ec_ptr); + + def setObjRef(self, ec_ptr): + self._rtcout.RTC_TRACE("setObjRef()") + assert(not CORBA.is_nil(ec_ptr)) + guard = OpenRTM_aist.ScopedLock(self._profileMutex) + self._ref = ec_ptr + del guard + return + + ## + # @if jp + # @brief CORBA オブジェクト参照の取得 + # + # 本オブジェクトの ExecutioncontextService としての CORBA オブジェ + # クト参照を取得する。 + # + # @return CORBA オブジェクト参照 + # + # @else + # @brief Get the reference to the CORBA object + # + # Get the reference to the CORBA object as + # ExecutioncontextService of this object. + # + # @return The reference to CORBA object + # + # @endif + # RTC::ExecutionContextService_ptr getObjRef(void) const; + + def getObjRef(self): + self._rtcout.RTC_TRACE("getObjRef()") + guard = OpenRTM_aist.ScopedLock(self._profileMutex) + return self._ref + + ## + # @if jp + # @brief ExecutionContext の実行周期(Hz)を設定する + # + # Active 状態にてRTコンポーネントが実行される周期(単位:Hz)を設定す + # る。実行周期の変更は、DataFlowComponentAction の + # on_rate_changed によって各RTコンポーネントに伝達される。 + # + # @param rate 処理周期(単位:Hz) + # + # @return ReturnCode_t 型のリターンコード + # RTC_OK: 正常終了 + # BAD_PARAMETER: 設定値が負の値 + # + # @else + # + # @brief Set execution rate(Hz) of ExecutionContext + # + # This operation shall set the rate (in hertz) at which this + # context’s Active participating RTCs are being called. If the + # execution kind of the context is PERIODIC, a rate change shall + # result in the invocation of on_rate_changed on any RTCs + # realizing DataFlowComponentAction that are registered with any + # RTCs participating in the context. + # + # @param rate Execution cycle(Unit:Hz) + # + # @return The return code of ReturnCode_t type + # RTC_OK: Succeed + # BAD_PARAMETER: Invalid value. The value might be negative. + # + # @endif + # RTC::ReturnCode_t setRate(double rate); + + def setRate(self, rate): + self._rtcout.RTC_TRACE("setRate(%f)", rate) + if rate <= 0.0: + return RTC.BAD_PARAMETER + + guard = OpenRTM_aist.ScopedLock(self._profileMutex) + self._profile.rate = rate + self._period = OpenRTM_aist.TimeValue(1.0 / rate) + return RTC.RTC_OK + + # RTC::ReturnCode_t setPeriod(double sec, coil::TimeValue tv); + + def setPeriod(self, sec=None, tv=None): + if sec: + self._rtcout.RTC_TRACE("setPeriod(%f [sec])", sec) + if sec <= 0.0: + return RTC.BAD_PARAMETER + + guard = OpenRTM_aist.ScopedLock(self._profileMutex) + self._profile.rate = 1.0 / sec + self._period = OpenRTM_aist.TimeValue(sec) + del guard + return RTC.RTC_OK + elif tv: + self._rtcout.RTC_TRACE("setPeriod(%f [sec])", tv.toDouble()) + if tv.toDouble() < 0.0: + return RTC.BAD_PARAMETER + + guard = OpenRTM_aist.ScopedLock(self._profileMutex) + self._profile.rate = 1.0 / tv.toDouble() + self._period = tv + del guard + return RTC.RTC_OK return RTC.BAD_PARAMETER - guard = OpenRTM_aist.ScopedLock(self._profileMutex) - self._profile.rate = 1.0 / tv.toDouble() - self._period = tv - del guard - return RTC.RTC_OK - return RTC.BAD_PARAMETER - - - ## - # @if jp - # @brief ExecutionContext μ¹Լ(Hz) - # - # Active ֤ˤRTݡͥȤ¹Ԥ(ñ:Hz) - # 롣 - # - # @return (ñ:Hz) - # - # @else - # - # @brief Get execution rate(Hz) of ExecutionContext - # - # This operation shall return the rate (in hertz) at which its - # Active participating RTCs are being invoked. - # - # @return Execution cycle(Unit:Hz) - # - # @endif - # double getRate(void) const; - def getRate(self): - guard = OpenRTM_aist.ScopedLock(self._profileMutex) - return self._profile.rate - - - # coil::TimeValue getPeriod(void) const; - def getPeriod(self): - guard = OpenRTM_aist.ScopedLock(self._profileMutex) - return self._period - - - ## - # @if jp - # @brief ExecutionKind ʸ󲽤 - # - # RTC::ExecutionKind Ƥ PERIODIC, EVENT_DRIVEN, - # OTHER ʸ󲽤롣 - # - # @param kind ExecutionKind - # @return ʸ󲽤줿ExecutionKind - # - # @else - # - # @brief Converting ExecutionKind enum to string - # - # This function converts enumeration (PERIODIC, EVENT_DRIVEN, - # OTHER) defined in RTC::ExecutionKind to string. - # - # @param kind ExecutionKind - # @return String of ExecutionKind - # - # @endif - # const char* getKindString(RTC::ExecutionKind kind) const; - def getKindString(self, kind=None): - kinds_ = ["PERIODIC", "EVENT_DRIVEN", "OTHER"] - if not kind: - kind_ = self._profile.kind - else: - kind_ = kind - - if kind_._v < RTC.PERIODIC._v or kind_._v > RTC.OTHER._v: - return "" - - return kinds_[kind_._v] - - - ## - # @if jp - # @brief ExecutionKind ꤹ - # - # ExecutionContext ExecutionKind ꤹ - # - # @param kind ExecutionKind - # - # @else - # - # @brief Set the ExecutionKind - # - # This operation sets the kind of the execution context. - # - # @param kind ExecutionKind - # - # @endif - # RTC::ReturnCode_t setKind(RTC::ExecutionKind kind); - def setKind(self, kind): - if kind._v < RTC.PERIODIC._v or kind._v > RTC.OTHER._v: - self._rtcout.RTC_ERROR("Invalid kind is given. %d", kind._v) - return RTC.BAD_PARAMETER - - self._rtcout.RTC_TRACE("setKind(%s)", self.getKindString(kind)) - guard = OpenRTM_aist.ScopedLock(self._profileMutex) - self._profile.kind = kind - del guard - return RTC.RTC_OK - - - ## - # @if jp - # @brief ExecutionKind - # - # ExecutionContext ExecutionKind - # - # @return ExecutionKind - # - # @else - # - # @brief Get the ExecutionKind - # - # This operation shall report the execution kind of the execution - # context. - # - # @return ExecutionKind - # - # @endif - # RTC::ExecutionKind getKind(void) const; - def getKind(self): - guard = OpenRTM_aist.ScopedLock(self._profileMutex) - self._rtcout.RTC_TRACE("%s = getKind()", self.getKindString(self._profile.kind)) - return self._profile.kind - - - ## - # @if jp - # @brief OwnerݡͥȤ򥻥åȤ롣 - # - # ECOwnerȤʤRTC򥻥åȤ롣 - # - # @param comp OwnerȤʤRTݡͥ - # @return ReturnCode_t Υ꥿󥳡 - # @else - # @brief Setting owner component of the execution context - # - # This function sets an RT-Component to be owner of the execution context. - # - # @param comp an owner RT-Component of this execution context - # @return The return code of ReturnCode_t type - # @endif - # RTC::ReturnCode_t setOwner(RTC::LightweightRTObject_ptr comp); - def setOwner(self, comp): - self._rtcout.RTC_TRACE("setOwner()") - if CORBA.is_nil(comp): - return RTC.BAD_PARAMETER - rtobj_ = comp._narrow(RTC.RTObject) - if CORBA.is_nil(rtobj_): - self._rtcout.RTC_ERROR("Narrowing failed.") - return RTC.RTC_ERROR - - guard = OpenRTM_aist.ScopedLock(self._profileMutex) - self._profile.owner = rtobj_ - del guard - return RTC.RTC_OK - - - ## - # @if jp - # @brief OwnerݡͥȤλȤ - # - # ECOwnerǤRTCλȤ롣 - # - # @return OwnerRTݡͥȤλ - # @else - # @brief Getting a reference of the owner component - # - # This function returns a reference of the owner RT-Component of - # this execution context - # - # @return a reference of the owner RT-Component - # @endif - # const RTC::RTObject_ptr getOwner() const; - def getOwner(self): - self._rtcout.RTC_TRACE("getOwner()") - guard = OpenRTM_aist.ScopedLock(self._profileMutex) - return self._profile.owner - - - ## - # @if jp - # @brief RTݡͥȤɲä - # - # ꤷRTݡͥȤ򻲲üԥꥹȤɲä롣ɲä줿RT - # ݡͥȤ attach_context ƤФ졢Inactive ֤ܤ롣 - # ꤵ줿RTݡͥȤnullξϡBAD_PARAMETER ֤ - # 롣ꤵ줿RTݡͥȤ DataFlowComponent ʳξϡ - # BAD_PARAMETER ֤롣 - # - # @param comp ɲоRTݡͥ - # - # @return ReturnCode_t Υ꥿󥳡 - # - # @else - # - # @brief Add an RT-component - # - # The operation causes the given RTC to begin participating in - # the execution context. The newly added RTC will receive a call - # to LightweightRTComponent::attach_context and then enter the - # Inactive state. BAD_PARAMETER will be invoked, if the given - # RT-Component is null or if the given RT-Component is other than - # DataFlowComponent. - # - # @param comp The target RT-Component for add - # - # @return The return code of ReturnCode_t type - # - # @endif - # RTC::ReturnCode_t addComponent(RTC::LightweightRTObject_ptr comp); - def addComponent(self, comp): - self._rtcout.RTC_TRACE("addComponent()") - if CORBA.is_nil(comp): - self._rtcout.RTC_ERROR("A nil reference was given.") - return RTC.BAD_PARAMETER - - rtobj_ = comp._narrow(RTC.RTObject) - if CORBA.is_nil(rtobj_): - self._rtcout.RTC_ERROR("Narrowing was failed.") - return RTC.RTC_ERROR - - guard = OpenRTM_aist.ScopedLock(self._profileMutex) - OpenRTM_aist.CORBA_SeqUtil.push_back(self._profile.participants, - rtobj_) - del guard - return RTC.RTC_OK - - - ## - # @if jp - # @brief RTݡͥȤ򻲲üԥꥹȤ - # - # ꤷRTݡͥȤ򻲲üԥꥹȤ롣줿 - # RTݡͥȤ detach_context ƤФ롣ꤵ줿RTݡ - # ͥȤüԥꥹȤϿƤʤϡBAD_PARAMETER - # 롣 - # - # @param comp оRTݡͥ - # - # @return ReturnCode_t Υ꥿󥳡 - # - # @else - # - # @brief Remove the RT-Component from participant list - # - # This operation causes a participant RTC to stop participating in the - # execution context. - # The removed RTC will receive a call to - # LightweightRTComponent::detach_context. - # BAD_PARAMETER will be returned, if the given RT-Component is not - # participating in the participant list. - # - # @param comp The target RT-Component for delete - # - # @return The return code of ReturnCode_t type - # - # @endif - # RTC::ReturnCode_t removeComponent(RTC::LightweightRTObject_ptr comp); - def removeComponent(self, comp): - self._rtcout.RTC_TRACE("removeComponent()") - if CORBA.is_nil(comp): - self._rtcout.RTC_ERROR("A nil reference was given.") - return RTC.BAD_PARAMETER - - rtobj_ = comp._narrow(RTC.RTObject) - if CORBA.is_nil(rtobj_): - self._rtcout.RTC_ERROR("Narrowing was failed.") - return RTC.RTC_ERROR - - guard = OpenRTM_aist.ScopedLock(self._profileMutex) - - index_ = OpenRTM_aist.CORBA_SeqUtil.find(self._profile.participants, - self.find_participant(rtobj_)) - if index_ < 0: - self._rtcout.RTC_ERROR("The given RTObject does not exist in the EC.") - return RTC.BAD_PARAMETER - OpenRTM_aist.CORBA_SeqUtil.erase(self._profile.participants, index_) - return RTC.RTC_OK - - - ## - # @if jp - # @brief RTݡͥȤλüԥꥹȤ - # - # ϿƤ뻲üRTCΥꥹȤ롣 - # - # @return üRTCΥꥹ - # - # @else - # - # @brief Getting participant RTC list - # - # This function returns a list of participant RTC of the execution context. - # - # @return Participants RTC list - # - # @endif - # const RTC::RTCList& getComponentList() const; - def getComponentList(self): - self._rtcout.RTC_TRACE("getComponentList(%d)", len(self._profile.participants)) - return self._profile.participants - - - ## - # @if jp - # @brief Properties򥻥åȤ - # - # ExecutionContextProfile::properties 򥻥åȤ롣 - # - # @param props ExecutionContextProfile::properties ˥åȤ - # ѥƥ - # - # @else - # @brief Setting Properties - # - # This function sets ExecutionContextProfile::properties by - # coil::Properties. - # - # @param props Properties to be set to - # ExecutionContextProfile::properties. - # - # @endif - # void setProperties(coil::Properties& props); - def setProperties(self, props): - self._rtcout.RTC_TRACE("setProperties()") - self._rtcout.RTC_DEBUG(props) - guard = OpenRTM_aist.ScopedLock(self._profileMutex) - OpenRTM_aist.NVUtil.copyFromProperties(self._profile.properties, props) - del guard - return - - - ## - # @if jp - # @brief Properties - # - # ExecutionContextProfile::properties 롣 - # - # @return coil::PropertiesѴ줿 - # ExecutionContextProfile::properties - # - # @else - # @brief Setting Properties - # - # This function sets ExecutionContextProfile::properties by - # coil::Properties. - # - # @param props Properties to be set to ExecutionContextProfile::properties. - # - # @endif - # const coil::Properties getProperties() const; - def getProperties(self): - self._rtcout.RTC_TRACE("getProperties()") - guard = OpenRTM_aist.ScopedLock(self._profileMutex) - props_ = OpenRTM_aist.Properties() - OpenRTM_aist.NVUtil.copyToProperties(props_, self._profile.properties) - del guard - self._rtcout.RTC_DEBUG(props_) - return props_ - - - ## - # @if jp - # @brief Profile - # - # RTC::ExecutionContextProfile 롣 - # ExecutionContextProfile νͭϸƤӽФ¦ˤ롣줿 - # ֥Ȥפˤʤä硢ƤӽФ¦Ǥ餦 - # - # @return RTC::ExecutionContextProfile - # - # @else - # @brief Getting Profile - # - # This function gets RTC::ExecutionContextProfile. The ownership - # of the obtained ExecutionContextProfile is given to caller. The - # caller should release obtained object when it is unneccessary - # anymore. - # - # @return RTC::ExecutionContextProfile - # - # @endif - # RTC::ExecutionContextProfile* getProfile(void); - def getProfile(self): - self._rtcout.RTC_TRACE("getProfile()") - guard = OpenRTM_aist.ScopedLock(self._profileMutex) - return self._profile - - - ## - # @if jp - # @brief ExecutionContextProfileå - # - # Υ֥Ȥ RTC::ExecutionContextProfile å롣 - # åפˤʤäݤˤunlock()ǥåʤФʤʤ - # - # @else - # @brief Getting a lock of RTC::ExecutionContextProfile - # - # This function locks RTC::ExecutionContextProfile in the object. - # The lock should be released when the lock is unneccessary. - # - # @endif - # void lock() const; - def lock(self): - self._profileMutex.acquire() - return - - - ## - # @if jp - # @brief ExecutionContextProfile򥢥å - # - # Υ֥Ȥ RTC::ExecutionContextProfile 򥢥 - # 롣 - # - # @else - # @brief Release a lock of the RTC::ExecutionContextProfile - # - # This function release the lock of RTC::ExecutionContextProfile - # in the object. - # - # @endif - # void unlock() const; - def unlock(self): - self._profileMutex.release() - return - - class find_participant: - def __init__(self, comp): - self._comp = comp - return - - def __call__(self, comp): - return self._comp._is_equivalent(comp) + ## + # @if jp + # @brief ExecutionContext の実行周期(Hz)を取得する + # + # Active 状態にてRTコンポーネントが実行される周期(単位:Hz)を取得す + # る。 + # + # @return 処理周期(単位:Hz) + # + # @else + # + # @brief Get execution rate(Hz) of ExecutionContext + # + # This operation shall return the rate (in hertz) at which its + # Active participating RTCs are being invoked. + # + # @return Execution cycle(Unit:Hz) + # + # @endif + # double getRate(void) const; + + def getRate(self): + guard = OpenRTM_aist.ScopedLock(self._profileMutex) + return self._profile.rate + + # coil::TimeValue getPeriod(void) const; + + def getPeriod(self): + guard = OpenRTM_aist.ScopedLock(self._profileMutex) + return self._period + + ## + # @if jp + # @brief ExecutionKind を文字列化する + # + # RTC::ExecutionKind で定義されている PERIODIC, EVENT_DRIVEN, + # OTHER を文字列化する。 + # + # @param kind ExecutionKind + # @return 文字列化されたExecutionKind + # + # @else + # + # @brief Converting ExecutionKind enum to string + # + # This function converts enumeration (PERIODIC, EVENT_DRIVEN, + # OTHER) defined in RTC::ExecutionKind to string. + # + # @param kind ExecutionKind + # @return String of ExecutionKind + # + # @endif + # const char* getKindString(RTC::ExecutionKind kind) const; + + def getKindString(self, kind=None): + kinds_ = ["PERIODIC", "EVENT_DRIVEN", "OTHER"] + if not kind: + kind_ = self._profile.kind + else: + kind_ = kind + + if kind_._v < RTC.PERIODIC._v or kind_._v > RTC.OTHER._v: + return "" + + return kinds_[kind_._v] + + ## + # @if jp + # @brief ExecutionKind を設定する + # + # この ExecutionContext の ExecutionKind を設定する + # + # @param kind ExecutionKind + # + # @else + # + # @brief Set the ExecutionKind + # + # This operation sets the kind of the execution context. + # + # @param kind ExecutionKind + # + # @endif + # RTC::ReturnCode_t setKind(RTC::ExecutionKind kind); + + def setKind(self, kind): + if kind._v < RTC.PERIODIC._v or kind._v > RTC.OTHER._v: + self._rtcout.RTC_ERROR("Invalid kind is given. %d", kind._v) + return RTC.BAD_PARAMETER + + self._rtcout.RTC_TRACE("setKind(%s)", self.getKindString(kind)) + guard = OpenRTM_aist.ScopedLock(self._profileMutex) + self._profile.kind = kind + del guard + return RTC.RTC_OK + + ## + # @if jp + # @brief ExecutionKind を取得する + # + # 本 ExecutionContext の ExecutionKind を取得する + # + # @return ExecutionKind + # + # @else + # + # @brief Get the ExecutionKind + # + # This operation shall report the execution kind of the execution + # context. + # + # @return ExecutionKind + # + # @endif + # RTC::ExecutionKind getKind(void) const; + + def getKind(self): + guard = OpenRTM_aist.ScopedLock(self._profileMutex) + self._rtcout.RTC_TRACE( + "%s = getKind()", + self.getKindString( + self._profile.kind)) + return self._profile.kind + + ## + # @if jp + # @brief Ownerコンポーネントをセットする。 + # + # このECのOwnerとなるRTCをセットする。 + # + # @param comp OwnerとなるRTコンポーネント + # @return ReturnCode_t 型のリターンコード + # @else + # @brief Setting owner component of the execution context + # + # This function sets an RT-Component to be owner of the execution context. + # + # @param comp an owner RT-Component of this execution context + # @return The return code of ReturnCode_t type + # @endif + # RTC::ReturnCode_t setOwner(RTC::LightweightRTObject_ptr comp); + + def setOwner(self, comp): + self._rtcout.RTC_TRACE("setOwner()") + if CORBA.is_nil(comp): + return RTC.BAD_PARAMETER + rtobj_ = comp._narrow(RTC.RTObject) + if CORBA.is_nil(rtobj_): + self._rtcout.RTC_ERROR("Narrowing failed.") + return RTC.RTC_ERROR + + guard = OpenRTM_aist.ScopedLock(self._profileMutex) + self._profile.owner = rtobj_ + del guard + return RTC.RTC_OK + + ## + # @if jp + # @brief Ownerコンポーネントの参照を取得する + # + # このECのOwnerであるRTCの参照を取得する。 + # + # @return OwnerRTコンポーネントの参照 + # @else + # @brief Getting a reference of the owner component + # + # This function returns a reference of the owner RT-Component of + # this execution context + # + # @return a reference of the owner RT-Component + # @endif + # const RTC::RTObject_ptr getOwner() const; + + def getOwner(self): + self._rtcout.RTC_TRACE("getOwner()") + guard = OpenRTM_aist.ScopedLock(self._profileMutex) + return self._profile.owner + + ## + # @if jp + # @brief RTコンポーネントを追加する + # + # 指定したRTコンポーネントを参加者リストに追加する。追加されたRTコ + # ンポーネントは attach_context が呼ばれ、Inactive 状態に遷移する。 + # 指定されたRTコンポーネントがnullの場合は、BAD_PARAMETER が返され + # る。指定されたRTコンポーネントが DataFlowComponent 以外の場合は、 + # BAD_PARAMETER が返される。 + # + # @param comp 追加対象RTコンポーネント + # + # @return ReturnCode_t 型のリターンコード + # + # @else + # + # @brief Add an RT-component + # + # The operation causes the given RTC to begin participating in + # the execution context. The newly added RTC will receive a call + # to LightweightRTComponent::attach_context and then enter the + # Inactive state. BAD_PARAMETER will be invoked, if the given + # RT-Component is null or if the given RT-Component is other than + # DataFlowComponent. + # + # @param comp The target RT-Component for add + # + # @return The return code of ReturnCode_t type + # + # @endif + # RTC::ReturnCode_t addComponent(RTC::LightweightRTObject_ptr comp); + + def addComponent(self, comp): + self._rtcout.RTC_TRACE("addComponent()") + if CORBA.is_nil(comp): + self._rtcout.RTC_ERROR("A nil reference was given.") + return RTC.BAD_PARAMETER + + rtobj_ = comp._narrow(RTC.RTObject) + if CORBA.is_nil(rtobj_): + self._rtcout.RTC_ERROR("Narrowing was failed.") + return RTC.RTC_ERROR + + guard = OpenRTM_aist.ScopedLock(self._profileMutex) + OpenRTM_aist.CORBA_SeqUtil.push_back(self._profile.participants, + rtobj_) + del guard + return RTC.RTC_OK + + ## + # @if jp + # @brief RTコンポーネントを参加者リストから削除する + # + # 指定したRTコンポーネントを参加者リストから削除する。削除された + # RTコンポーネントは detach_context が呼ばれる。指定されたRTコンポー + # ネントが参加者リストに登録されていない場合は、BAD_PARAMETER が返 + # される。 + # + # @param comp 削除対象RTコンポーネント + # + # @return ReturnCode_t 型のリターンコード + # + # @else + # + # @brief Remove the RT-Component from participant list + # + # This operation causes a participant RTC to stop participating in the + # execution context. + # The removed RTC will receive a call to + # LightweightRTComponent::detach_context. + # BAD_PARAMETER will be returned, if the given RT-Component is not + # participating in the participant list. + # + # @param comp The target RT-Component for delete + # + # @return The return code of ReturnCode_t type + # + # @endif + # RTC::ReturnCode_t removeComponent(RTC::LightweightRTObject_ptr comp); + + def removeComponent(self, comp): + self._rtcout.RTC_TRACE("removeComponent()") + if CORBA.is_nil(comp): + self._rtcout.RTC_ERROR("A nil reference was given.") + return RTC.BAD_PARAMETER + + rtobj_ = comp._narrow(RTC.RTObject) + if CORBA.is_nil(rtobj_): + self._rtcout.RTC_ERROR("Narrowing was failed.") + return RTC.RTC_ERROR + + guard = OpenRTM_aist.ScopedLock(self._profileMutex) + + index_ = OpenRTM_aist.CORBA_SeqUtil.find(self._profile.participants, + self.find_participant(rtobj_)) + if index_ < 0: + self._rtcout.RTC_ERROR( + "The given RTObject does not exist in the EC.") + return RTC.BAD_PARAMETER + OpenRTM_aist.CORBA_SeqUtil.erase(self._profile.participants, index_) + return RTC.RTC_OK + + ## + # @if jp + # @brief RTコンポーネントの参加者リストを取得する + # + # 現在登録されている参加者RTCのリストを取得する。 + # + # @return 参加者RTCのリスト + # + # @else + # + # @brief Getting participant RTC list + # + # This function returns a list of participant RTC of the execution context. + # + # @return Participants RTC list + # + # @endif + # const RTC::RTCList& getComponentList() const; + + def getComponentList(self): + self._rtcout.RTC_TRACE( + "getComponentList(%d)", len( + self._profile.participants)) + return self._profile.participants + + ## + # @if jp + # @brief Propertiesをセットする + # + # ExecutionContextProfile::properties をセットする。 + # + # @param props ExecutionContextProfile::properties にセットするプ + # ロパティー + # + # @else + # @brief Setting Properties + # + # This function sets ExecutionContextProfile::properties by + # coil::Properties. + # + # @param props Properties to be set to + # ExecutionContextProfile::properties. + # + # @endif + # void setProperties(coil::Properties& props); + + def setProperties(self, props): + self._rtcout.RTC_TRACE("setProperties()") + self._rtcout.RTC_DEBUG(props) + guard = OpenRTM_aist.ScopedLock(self._profileMutex) + OpenRTM_aist.NVUtil.copyFromProperties(self._profile.properties, props) + del guard + return + + ## + # @if jp + # @brief Propertiesを取得する + # + # ExecutionContextProfile::properties を取得する。 + # + # @return coil::Propertiesに変換された + # ExecutionContextProfile::properties + # + # @else + # @brief Setting Properties + # + # This function sets ExecutionContextProfile::properties by + # coil::Properties. + # + # @param props Properties to be set to ExecutionContextProfile::properties. + # + # @endif + # const coil::Properties getProperties() const; + + def getProperties(self): + self._rtcout.RTC_TRACE("getProperties()") + guard = OpenRTM_aist.ScopedLock(self._profileMutex) + props_ = OpenRTM_aist.Properties() + OpenRTM_aist.NVUtil.copyToProperties(props_, self._profile.properties) + del guard + self._rtcout.RTC_DEBUG(props_) + return props_ + + ## + # @if jp + # @brief Profileを取得する + # + # RTC::ExecutionContextProfile を取得する。取得した + # ExecutionContextProfile の所有権は呼び出し側にある。取得されたオ + # ブジェクトが不要になった場合、呼び出し側が開放する責任を負う。 + # + # @return RTC::ExecutionContextProfile + # + # @else + # @brief Getting Profile + # + # This function gets RTC::ExecutionContextProfile. The ownership + # of the obtained ExecutionContextProfile is given to caller. The + # caller should release obtained object when it is unneccessary + # anymore. + # + # @return RTC::ExecutionContextProfile + # + # @endif + # RTC::ExecutionContextProfile* getProfile(void); + + def getProfile(self): + self._rtcout.RTC_TRACE("getProfile()") + guard = OpenRTM_aist.ScopedLock(self._profileMutex) + return self._profile + + ## + # @if jp + # @brief ExecutionContextProfileをロックする + # + # このオブジェクトが管理する RTC::ExecutionContextProfile をロックする。 + # ロックが不要になった際にはunlock()でロックを解除しなければならない。 + # + # @else + # @brief Getting a lock of RTC::ExecutionContextProfile + # + # This function locks RTC::ExecutionContextProfile in the object. + # The lock should be released when the lock is unneccessary. + # + # @endif + # void lock() const; + + def lock(self): + self._profileMutex.acquire() + return + + ## + # @if jp + # @brief ExecutionContextProfileをアンロックする + # + # このオブジェクトが管理する RTC::ExecutionContextProfile をアンロッ + # クする。 + # + # @else + # @brief Release a lock of the RTC::ExecutionContextProfile + # + # This function release the lock of RTC::ExecutionContextProfile + # in the object. + # + # @endif + # void unlock() const; + + def unlock(self): + self._profileMutex.release() + return + + class find_participant: + def __init__(self, comp): + self._comp = comp + return + + def __call__(self, comp): + return self._comp._is_equivalent(comp) diff --git a/OpenRTM_aist/ExecutionContextWorker.py b/OpenRTM_aist/ExecutionContextWorker.py index 8b2292bc..857d5ee7 100644 --- a/OpenRTM_aist/ExecutionContextWorker.py +++ b/OpenRTM_aist/ExecutionContextWorker.py @@ -1,5 +1,5 @@ #!/usr/bin/env python -# -*- coding: euc-jp -*- +# -*- coding: utf-8 -*- ## # @file ExecutionContextWorker.py @@ -27,9 +27,9 @@ ## # @if jp # @class PeriodicExecutionContext -# @brief PeriodicExecutionContext 饹 +# @brief PeriodicExecutionContext クラス # -# Periodic Sampled Data Processing(¹)ExecutionContext饹 +# Periodic Sampled Data Processing(周期実行用)ExecutionContextクラス。 # # @since 0.4.0 # @@ -44,729 +44,728 @@ # # @endif class ExecutionContextWorker: - """ - """ - - ## - # @if jp - # @brief ǥեȥ󥹥ȥ饯 - # - # ǥեȥ󥹥ȥ饯 - # ץե˰ʲιܤꤹ롣 - # - kind : PERIODIC - # - rate : 0.0 - # - # @else - # @brief Default Constructor - # - # Default Constructor - # Set the following items to profile. - # - kind : PERIODIC - # - rate : 0.0 - # - # @endif - def __init__(self): - self._rtcout = OpenRTM_aist.Manager.instance().getLogbuf("ec_worker") - self._running = False - self._rtcout.RTC_TRACE("ExecutionContextWorker.__init__") - self._ref = None - self._comps = [] - self._addedComps = [] - self._removedComps = [] - self._mutex = threading.RLock() - self._addedMutex = threading.RLock() - self._removedMutex = threading.RLock() - return - - - ## - # @if jp - # @brief ExecutionContextWorkerλ - # - # - # - # @else - # @brief - # - # - # - # @endif - def exit(self): - self._rtcout.RTC_TRACE("exit") - return - - - #============================================================ - # Object reference to EC - #============================================================ - # void setECRef(RTC::ExecutionContextService_ptr ref); - def setECRef(self, ref): - self._ref = ref - return - - - #RTC::ExecutionContextService_ptr getECRef(); - def getECRef(self): - return self._ref - - - #============================================================ - # ExecutionContext - #============================================================ - ## - # @if jp - # @brief ExecutionContext ¹Ծֳǧؿ - # - # ExecutionContext Runnning ֤ξ true ֤ - # Executioncontext Running δ֡ Executioncontext ˻ä - # ƤƤΥƥRTݡͥȤExecutionContext μ - # Լ˱Ƽ¹Ԥ롣 - # - # @return ֳǧؿ(ư:true:false) - # - # @else - # - # @brief Check for ExecutionContext running state - # - # This operation shall return true if the context is in the - # Running state. While the context is Running, all Active RTCs - # participating in the context shall be executed according to the - # contexts execution kind. - # - # @return Check state function (Running:trueStopping:false) - # - # @endif - # bool isRunning(void); - def isRunning(self): - self._rtcout.RTC_TRACE("isRunning()") - return self._running - - - ## - # @if jp - # @brief ExecutionContext μ¹Ԥ򳫻 - # - # ExecutionContext μ¹Ծ֤ Runnning Ȥ뤿ΥꥯȤ - # ȯԤ롣ExecutionContext ξ֤ܤ - # ComponentAction::on_startup ƤӽФ롣äƤRTݡ - # ͥȤޤ ExecutionContext 򳫻Ϥ뤳ȤϤǤ - # ʤExecutionContext ʣ󳫻/ߤ򷫤֤ȤǤ롣 - # - # @return ReturnCode_t Υ꥿󥳡 - # - # @else - # - # @brief Start the ExecutionContext - # - # Request that the context enter the Running state. Once the - # state transition occurs, the ComponentAction::on_startup - # operation will be invoked. An execution context may not be - # started until the RT-Components that participate in it have - # been initialized. An execution context may be started and - # stopped multiple times. - # - # @return The return code of ReturnCode_t type - # - # @endif - # RTC::ReturnCode_t start(void); - def start(self): - self._rtcout.RTC_TRACE("start()") - guard = OpenRTM_aist.ScopedLock(self._mutex) - if self._running: - del guard - self._rtcout.RTC_WARN("ExecutionContext is already running.") - return RTC.PRECONDITION_NOT_MET - - # invoke ComponentAction::on_startup for each comps. - for comp in self._comps: - comp.onStartup() - - self._rtcout.RTC_DEBUG("%d components started.", len(self._comps)) - # change EC thread state - self._running = True - del guard - return RTC.RTC_OK - - - ## - # @if jp - # @brief ExecutionContext μ¹Ԥ - # - # ExecutionContext ξ֤ Stopped Ȥ뤿ΥꥯȤȯԤ - # 롣ܤȯϡComponentAction::on_shutdown Ƥӽ - # 롣äƤRTݡͥȤλ - # ExecutionContext ߤɬפ롣ExecutionContext ʣ - # /ߤ򷫤֤ȤǤ롣 - # - # @return ReturnCode_t Υ꥿󥳡 - # - # @else - # - # @brief Stop the ExecutionContext - # - # Request that the context enter the Stopped state. Once the - # transition occurs, the ComponentAction::on_shutdown operation - # will be invoked. An execution context must be stopped before - # the RT components that participate in it are finalized. An - # execution context may be started and stopped multiple times. - # - # @return The return code of ReturnCode_t type - # - # @endif - # RTC::ReturnCode_t stop(void); - def stop(self): - self._rtcout.RTC_TRACE("stop()") - guard = OpenRTM_aist.ScopedLock(self._mutex) - if not self._running: - del guard - self._rtcout.RTC_WARN("ExecutionContext is already stopped.") - return RTC.PRECONDITION_NOT_MET - - # stop thread - self._running = False - - # invoke on_shutdown for each comps. - for comp in self._comps: - comp.onShutdown() - - del guard - return RTC.RTC_OK - # - # @if jp - # @brief ExecutionContext μѲ - # @return ReturnCode_t Υ꥿󥳡 - # - # @else - # - # @brief Changing execution rate of the ExecutionContext - # - # @return The return code of ReturnCode_t type - # - # @endif - # RTC::ReturnCode_t rateChanged(void); - def rateChanged(self): - self._rtcout.RTC_TRACE("rateChanged()") - guard = OpenRTM_aist.ScopedLock(self._mutex) - ret = RTC.RTC_OK - for comp in self._comps: - tmp = comp.onRateChanged() - if tmp != RTC.RTC_OK: - ret = tmp - del guard - return ret - - ## - # @if jp - # @brief RTݡͥȤ򥢥ƥֲ - # - # Inactive ֤ˤRTݡͥȤActive ܤƥ - # ֲ롣ƤФ줿̡on_activate ƤӽФ롣 - # ꤷRTݡͥȤüԥꥹȤ˴ޤޤʤϡ - # BAD_PARAMETER ֤롣ꤷRTݡͥȤξ֤ - # Inactive ʳξϡPRECONDITION_NOT_MET ֤롣 - # - # @param comp ƥֲоRTݡͥ - # - # @return ReturnCode_t Υ꥿󥳡 - # - # @else - # - # @brief Activate an RT-component - # - # The given participant RTC is Inactive and is therefore not - # being invoked according to the execution contexts execution - # kind. This operation shall cause the RTC to transition to the - # Active state such that it may subsequently be invoked in this - # execution context. The callback on_activate shall be called as - # a result of calling this operation. This operation shall not - # return until the callback has returned, and shall result in an - # error if the callback does. - # - # @param comp The target RT-Component for activation - # - # @return The return code of ReturnCode_t type - # - # @endif - # RTC::ReturnCode_t activateComponent(RTC::LightweightRTObject_ptr comp, - # RTObjectStateMachine*& rtobj); - def activateComponent(self, comp, rtobj): - self._rtcout.RTC_TRACE("activateComponent()") - guard = OpenRTM_aist.ScopedLock(self._mutex) - obj_ = self.findComponent(comp) - if not obj_: - del guard - self._rtcout.RTC_ERROR("Given RTC is not participant of this EC.") - return RTC.BAD_PARAMETER - - self._rtcout.RTC_DEBUG("Component found in the EC.") - if not obj_.isCurrentState(RTC.INACTIVE_STATE): - del guard - self._rtcout.RTC_ERROR("State of the RTC is not INACTIVE_STATE.") - return RTC.PRECONDITION_NOT_MET - - self._rtcout.RTC_DEBUG("Component is in INACTIVE state. Going to ACTIVE state.") - obj_.goTo(RTC.ACTIVE_STATE) - rtobj[0] = obj_ - del guard - self._rtcout.RTC_DEBUG("activateComponent() done.") - return RTC.RTC_OK - - - # RTC::ReturnCode_t waitActivateComplete(RTObjectStateMachine*& rtobj, - # coil::TimeValue timeout = 1.0, - # long int cycle = 1000); - def waitActivateComplete(self, rtobj, timeout = 1.0, cycle = 1000): - pass - - ## - # @if jp - # @brief RTݡͥȤ󥢥ƥֲ - # - # Inactive ֤ˤRTݡͥȤ󥢥ƥֲInactive - # ܤ롣ƤФ줿̡on_deactivate ƤӽФ - # 롣ꤷRTݡͥȤüԥꥹȤ˴ޤޤʤϡ - # BAD_PARAMETER ֤롣ꤷRTݡͥȤξ֤ - # Active ʳξϡPRECONDITION_NOT_MET ֤롣 - # - # @param comp 󥢥ƥֲоRTݡͥ - # - # @return ReturnCode_t Υ꥿󥳡 - # - # @else - # - # @brief Deactivate an RT-component - # - # The given RTC is Active in the execution context. Cause it to - # transition to the Inactive state such that it will not be - # subsequently invoked from the context unless and until it is - # activated again. The callback on_deactivate shall be called as - # a result of calling this operation. This operation shall not - # return until the callback has returned, and shall result in an - # error if the callback does. - # - # @param comp The target RT-Component for deactivate - # - # @return The return code of ReturnCode_t type - # - # @endif - # RTC::ReturnCode_t deactivateComponent(RTC::LightweightRTObject_ptr comp, - # RTObjectStateMachine*& rtobj); - def deactivateComponent(self, comp, rtobj): - self._rtcout.RTC_TRACE("deactivateComponent()") - guard = OpenRTM_aist.ScopedLock(self._mutex) - - rtobj[0] = self.findComponent(comp) - if not rtobj[0]: - del guard - self._rtcout.RTC_ERROR("Given RTC is not participant of this EC.") - return RTC.BAD_PARAMETER - - if not rtobj[0].isCurrentState(RTC.ACTIVE_STATE): - del guard - self._rtcout.RTC_ERROR("State of the RTC is not ACTIVE_STATE.") - return RTC.PRECONDITION_NOT_MET - - rtobj[0].goTo(RTC.INACTIVE_STATE) - del guard - return RTC.RTC_OK - - - # RTC::ReturnCode_t waitDeactivateComplete(RTObjectStateMachine*& rtobj, - # coil::TimeValue timeout = 1.0, - # long int cycle = 1000); - def waitDeactivateComplete(self, rtobj, timeout = 1.0, cycle = 1000): - pass - - - ## - # @if jp - # @brief RTݡͥȤꥻåȤ - # - # Error ֤RTݡͥȤߤ롣ƤФ줿 - # ̡on_reset ƤӽФ롣ꤷRTݡͥȤüԥ - # Ȥ˴ޤޤʤϡBAD_PARAMETER ֤롣ꤷRT - # ݡͥȤξ֤ Error ʳξϡPRECONDITION_NOT_MET - # 롣 - # - # @param comp ꥻåоRTݡͥ - # - # @return ReturnCode_t Υ꥿󥳡 - # - # @else - # - # @brief Reset the RT-component - # - # Attempt to recover the RTC when it is in Error. The - # ComponentAction::on_reset callback shall be invoked. This - # operation shall not return until the callback has returned, and - # shall result in an error if the callback does. If possible, the - # RTC developer should implement that callback such that the RTC - # may be returned to a valid state. - # - # @param comp The target RT-Component for reset - # - # @return The return code of ReturnCode_t type - # - # @endif - # RTC::ReturnCode_t resetComponent(RTC::LightweightRTObject_ptr com, - # RTObjectStateMachine*& rtobj); - def resetComponent(self, comp, rtobj): - self._rtcout.RTC_TRACE("resetComponent()") - guard = OpenRTM_aist.ScopedLock(self._mutex) - - rtobj[0] = self.findComponent(comp) - if not rtobj[0]: - del guard - self._rtcout.RTC_ERROR("Given RTC is not participant of this EC.") - return RTC.BAD_PARAMETER - - if not rtobj[0].isCurrentState(RTC.ERROR_STATE): - del guard - self._rtcout.RTC_ERROR("State of the RTC is not ERROR_STATE.") - return RTC.PRECONDITION_NOT_MET - - rtobj[0].goTo(RTC.INACTIVE_STATE) - del guard - return RTC.RTC_OK - - - # RTC::ReturnCode_t waitResetComplete(RTObjectStateMachine*& rtobj, - # coil::TimeValue timeout = 1.0, - # long int cycle = 1000); - def waitResetComplete(self, rtobj, timeout = 1.0, cycle = 1000): - pass - - - ## - # @if jp - # @brief RTݡͥȤξ֤ - # - # ꤷRTݡͥȤξ(LifeCycleState)롣ꤷ - # RTݡͥȤüԥꥹȤ˴ޤޤʤϡ - # UNKNOWN_STATE ֤롣 - # - # @param comp ּоRTݡͥ - # - # @return ߤξ(LifeCycleState) - # - # @else - # - # @brief Get RT-component's state - # - # This operation shall report the LifeCycleState of the given - # participant RTC. UNKNOWN_STATE will be returned, if the given - # RT-Component is not inclued in the participant list. - # - # @param comp The target RT-Component to get the state - # - # @return The current state of the target RT-Component(LifeCycleState) - # - # @endif - # RTC::LifeCycleState getComponentState(RTC::LightweightRTObject_ptr comp); - def getComponentState(self, comp): - self._rtcout.RTC_TRACE("getComponentState()") - guard = OpenRTM_aist.ScopedLock(self._mutex) - rtobj_ = self.findComponent(comp) - if not rtobj_: - del guard - self._rtcout.RTC_WARN("Given RTC is not participant of this EC.") - return RTC.CREATED_STATE - - state_ = rtobj_.getState() - self._rtcout.RTC_DEBUG("getComponentState() = %s done", self.getStateString(state_)) - return state_ - - - # const char* getStateString(RTC::LifeCycleState state) - def getStateString(self, state): - st = ["CREATED_STATE", - "INACTIVE_STATE", - "ACTIVE_STATE", - "ERROR_STATE"] - - f = lambda x: st[x._v] if x._v >= RTC.CREATED_STATE._v and x._v <= RTC.ERROR_STATE._v else "" - return f(state) - - ## - # @if jp - # @brief RTݡͥȤɲä - # - # ꤷRTݡͥȤ򻲲üԥꥹȤɲä롣ɲä줿RT - # ݡͥȤ attach_context ƤФ졢Inactive ֤ܤ롣 - # ꤵ줿RTݡͥȤnullξϡBAD_PARAMETER ֤ - # 롣ꤵ줿RTݡͥȤ DataFlowComponent ʳξϡ - # BAD_PARAMETER ֤롣 - # - # @param comp ɲоRTݡͥ - # - # @return ReturnCode_t Υ꥿󥳡 - # - # @else - # - # @brief Add an RT-component - # - # The operation causes the given RTC to begin participating in - # the execution context. The newly added RTC will receive a call - # to LightweightRTComponent::attach_context and then enter the - # Inactive state. BAD_PARAMETER will be invoked, if the given - # RT-Component is null or if the given RT-Component is other than - # DataFlowComponent. - # - # @param comp The target RT-Component for add - # - # @return The return code of ReturnCode_t type - # - # @endif - # RTC::ReturnCode_t addComponent(RTC::LightweightRTObject_ptr comp); - def addComponent(self, comp): - self._rtcout.RTC_TRACE("addComponent()") - if CORBA.is_nil(comp): - self._rtcout.RTC_ERROR("nil reference is given.") - return RTC.BAD_PARAMETER - - try: - guard = OpenRTM_aist.ScopedLock(self._addedMutex) - ec_ = self.getECRef() - id_ = comp.attach_context(ec_) - self._addedComps.append(OpenRTM_aist.RTObjectStateMachine(id_, comp)) - del guard - except: - del guard - self._rtcout.RTC_ERROR("addComponent() failed.") - return RTC.RTC_ERROR - - self._rtcout.RTC_DEBUG("addComponent() succeeded.") - if self._running == False: - self.updateComponentList() - return RTC.RTC_OK - - - ## - # @if jp - # @brief ݡͥȤХɤ롣 - # - # ݡͥȤХɤ롣 - # - # @param rtc RTݡͥ - # @return ReturnCode_t Υ꥿󥳡 - # @else - # @brief Bind the component. - # - # Bind the component. - # - # @param rtc RT-Component's instances - # @return The return code of ReturnCode_t type - # @endif - # RTC::ReturnCode_t bindComponent(RTC::RTObject_impl* rtc); - def bindComponent(self, rtc): - self._rtcout.RTC_TRACE("bindComponent()") - guard = OpenRTM_aist.ScopedLock(self._mutex) - if not rtc: - del guard - self._rtcout.RTC_ERROR("NULL pointer is given.") - return RTC.BAD_PARAMETER - - ec_ = self.getECRef() - id_ = rtc.bindContext(ec_) - if id_ < 0 or id_ > OpenRTM_aist.ECOTHER_OFFSET: - # id should be owned context id < ECOTHER_OFFSET - del guard - self._rtcout.RTC_ERROR("bindContext returns invalid id: %d", id_) - return RTC.RTC_ERROR - - self._rtcout.RTC_DEBUG("bindContext returns id = %d", id_) - - # rtc is owner of this EC - comp_ = rtc.getObjRef() - # RTObjectStateMachine o(id, comp); - self._comps.append(OpenRTM_aist.RTObjectStateMachine(id_, comp_)) - del guard - self._rtcout.RTC_DEBUG("bindComponent() succeeded.") - return RTC.RTC_OK - - - ## - # @if jp - # @brief RTݡͥȤ򻲲üԥꥹȤ - # - # ꤷRTݡͥȤ򻲲üԥꥹȤ롣줿 - # RTݡͥȤ detach_context ƤФ롣ꤵ줿RTݡ - # ͥȤüԥꥹȤϿƤʤϡBAD_PARAMETER - # 롣 - # - # @param comp оRTݡͥ - # - # @return ReturnCode_t Υ꥿󥳡 - # - # @else - # - # @brief Remove the RT-Component from participant list - # - # This operation causes a participant RTC to stop participating in the - # execution context. - # The removed RTC will receive a call to - # LightweightRTComponent::detach_context. - # BAD_PARAMETER will be returned, if the given RT-Component is not - # participating in the participant list. - # - # @param comp The target RT-Component for delete - # - # @return The return code of ReturnCode_t type - # - # @endif - # RTC::ReturnCode_t removeComponent(RTC::LightweightRTObject_ptr comp); - def removeComponent(self, comp): - self._rtcout.RTC_TRACE("removeComponent()") - if CORBA.is_nil(comp): - self._rtcout.RTC_ERROR("nil reference is given.") - return RTC.BAD_PARAMETER - - - guard = OpenRTM_aist.ScopedLock(self._mutex) - rtobj_ = self.findComponent(comp) - del guard - - if not rtobj_: - self._rtcout.RTC_ERROR("no RTC found in this context.") - return RTC.BAD_PARAMETER - - guard = OpenRTM_aist.ScopedLock(self._removedMutex) - self._removedComps.append(rtobj_) - del guard - if self._running == False: - self.updateComponentList() - return RTC.RTC_OK - - - # RTObjectStateMachine* findComponent(RTC::LightweightRTObject_ptr comp); - def findComponent(self, comp): - for comp_ in self._comps: - if comp_.isEquivalent(comp): - return comp_ - - return None - - - # bool isAllCurrentState(RTC::LifeCycleState state); - def isAllCurrentState(self, state): - guard = OpenRTM_aist.ScopedLock(self._mutex) - for comp in self._comps: - if not comp.isCurrentState(state): + """ + """ + + ## + # @if jp + # @brief デフォルトコンストラクタ + # + # デフォルトコンストラクタ + # プロファイルに以下の項目を設定する。 + # - kind : PERIODIC + # - rate : 0.0 + # + # @else + # @brief Default Constructor + # + # Default Constructor + # Set the following items to profile. + # - kind : PERIODIC + # - rate : 0.0 + # + # @endif + def __init__(self): + self._rtcout = OpenRTM_aist.Manager.instance().getLogbuf("ec_worker") + self._running = False + self._rtcout.RTC_TRACE("ExecutionContextWorker.__init__") + self._ref = None + self._comps = [] + self._addedComps = [] + self._removedComps = [] + self._mutex = threading.RLock() + self._addedMutex = threading.RLock() + self._removedMutex = threading.RLock() + return + + ## + # @if jp + # @brief ExecutionContextWorker終了処理 + # + # + # + # @else + # @brief + # + # + # + # @endif + + def exit(self): + self._rtcout.RTC_TRACE("exit") + return + + # ============================================================ + # Object reference to EC + # ============================================================ + # void setECRef(RTC::ExecutionContextService_ptr ref); + + def setECRef(self, ref): + self._ref = ref + return + + # RTC::ExecutionContextService_ptr getECRef(); + + def getECRef(self): + return self._ref + + # ============================================================ + # ExecutionContext + # ============================================================ + ## + # @if jp + # @brief ExecutionContext 実行状態確認関数 + # + # この操作は ExecutionContext が Runnning 状態の場合に true を返す。 + # Executioncontext が Running の間、当該 Executioncontext に参加し + # ている全てのアクティブRTコンポーネントが、ExecutionContext の実 + # 行種類に応じて実行される。 + # + # @return 状態確認関数(動作中:true、停止中:false) + # + # @else + # + # @brief Check for ExecutionContext running state + # + # This operation shall return true if the context is in the + # Running state. While the context is Running, all Active RTCs + # participating in the context shall be executed according to the + # context’s execution kind. + # + # @return Check state function (Running:true、Stopping:false) + # + # @endif + # bool isRunning(void); + + def isRunning(self): + self._rtcout.RTC_TRACE("isRunning()") + return self._running + + ## + # @if jp + # @brief ExecutionContext の実行を開始 + # + # ExecutionContext の実行状態を Runnning とするためのリクエストを + # 発行する。ExecutionContext の状態が遷移すると + # ComponentAction::on_startup が呼び出される。参加しているRTコンポー + # ネントが、初期化されるまで ExecutionContext を開始することはでき + # ない。ExecutionContext は複数回開始/停止を繰り返すことができる。 + # + # @return ReturnCode_t 型のリターンコード + # + # @else + # + # @brief Start the ExecutionContext + # + # Request that the context enter the Running state. Once the + # state transition occurs, the ComponentAction::on_startup + # operation will be invoked. An execution context may not be + # started until the RT-Components that participate in it have + # been initialized. An execution context may be started and + # stopped multiple times. + # + # @return The return code of ReturnCode_t type + # + # @endif + # RTC::ReturnCode_t start(void); + + def start(self): + self._rtcout.RTC_TRACE("start()") + guard = OpenRTM_aist.ScopedLock(self._mutex) + if self._running: + del guard + self._rtcout.RTC_WARN("ExecutionContext is already running.") + return RTC.PRECONDITION_NOT_MET + + # invoke ComponentAction::on_startup for each comps. + for comp in self._comps: + comp.onStartup() + + self._rtcout.RTC_DEBUG("%d components started.", len(self._comps)) + # change EC thread state + self._running = True del guard - return False + return RTC.RTC_OK + + ## + # @if jp + # @brief ExecutionContext の実行を停止 + # + # ExecutionContext の状態を Stopped とするためのリクエストを発行す + # る。遷移が発生した場合は、ComponentAction::on_shutdown が呼び出 + # される。参加しているRTコンポーネントが終了する前に + # ExecutionContext を停止する必要がある。ExecutionContext は複数回 + # 開始/停止を繰り返すことができる。 + # + # @return ReturnCode_t 型のリターンコード + # + # @else + # + # @brief Stop the ExecutionContext + # + # Request that the context enter the Stopped state. Once the + # transition occurs, the ComponentAction::on_shutdown operation + # will be invoked. An execution context must be stopped before + # the RT components that participate in it are finalized. An + # execution context may be started and stopped multiple times. + # + # @return The return code of ReturnCode_t type + # + # @endif + # RTC::ReturnCode_t stop(void); + + def stop(self): + self._rtcout.RTC_TRACE("stop()") + guard = OpenRTM_aist.ScopedLock(self._mutex) + if not self._running: + del guard + self._rtcout.RTC_WARN("ExecutionContext is already stopped.") + return RTC.PRECONDITION_NOT_MET + + # stop thread + self._running = False + + # invoke on_shutdown for each comps. + for comp in self._comps: + comp.onShutdown() - del guard - return True + del guard + return RTC.RTC_OK + # + # @if jp + # @brief ExecutionContext の周期が変化した + # @return ReturnCode_t 型のリターンコード + # + # @else + # + # @brief Changing execution rate of the ExecutionContext + # + # @return The return code of ReturnCode_t type + # + # @endif + # RTC::ReturnCode_t rateChanged(void); + + def rateChanged(self): + self._rtcout.RTC_TRACE("rateChanged()") + guard = OpenRTM_aist.ScopedLock(self._mutex) + ret = RTC.RTC_OK + for comp in self._comps: + tmp = comp.onRateChanged() + if tmp != RTC.RTC_OK: + ret = tmp + del guard + return ret + + ## + # @if jp + # @brief RTコンポーネントをアクティブ化する + # + # Inactive 状態にあるRTコンポーネントをActive に遷移させ、アクティ + # ブ化する。この操作が呼ばれた結果、on_activate が呼び出される。指 + # 定したRTコンポーネントが参加者リストに含まれない場合は、 + # BAD_PARAMETER が返される。指定したRTコンポーネントの状態が + # Inactive 以外の場合は、PRECONDITION_NOT_MET が返される。 + # + # @param comp アクティブ化対象RTコンポーネント + # + # @return ReturnCode_t 型のリターンコード + # + # @else + # + # @brief Activate an RT-component + # + # The given participant RTC is Inactive and is therefore not + # being invoked according to the execution context’s execution + # kind. This operation shall cause the RTC to transition to the + # Active state such that it may subsequently be invoked in this + # execution context. The callback on_activate shall be called as + # a result of calling this operation. This operation shall not + # return until the callback has returned, and shall result in an + # error if the callback does. + # + # @param comp The target RT-Component for activation + # + # @return The return code of ReturnCode_t type + # + # @endif + # RTC::ReturnCode_t activateComponent(RTC::LightweightRTObject_ptr comp, + # RTObjectStateMachine*& rtobj); + def activateComponent(self, comp): + self._rtcout.RTC_TRACE("activateComponent()") + guard = OpenRTM_aist.ScopedLock(self._mutex) + obj_ = self.findComponent(comp) + if not obj_: + del guard + self._rtcout.RTC_ERROR("Given RTC is not participant of this EC.") + return RTC.BAD_PARAMETER, obj_ + + self._rtcout.RTC_DEBUG("Component found in the EC.") + if not obj_.activate(): + del guard + self._rtcout.RTC_ERROR("State of the RTC is not INACTIVE_STATE.") + return RTC.PRECONDITION_NOT_MET, obj_ + + self._rtcout.RTC_DEBUG( + "Component is in INACTIVE state. Going to ACTIVE state.") + del guard + self._rtcout.RTC_DEBUG("activateComponent() done.") + return RTC.RTC_OK, obj_ + + # RTC::ReturnCode_t waitActivateComplete(RTObjectStateMachine*& rtobj, + # coil::TimeValue timeout = 1.0, + # long int cycle = 1000); + + def waitActivateComplete(self, rtobj, timeout=1.0, cycle=1000): + pass + + ## + # @if jp + # @brief RTコンポーネントを非アクティブ化する + # + # Inactive 状態にあるRTコンポーネントを非アクティブ化し、Inactive + # に遷移させる。この操作が呼ばれた結果、on_deactivate が呼び出され + # る。指定したRTコンポーネントが参加者リストに含まれない場合は、 + # BAD_PARAMETER が返される。指定したRTコンポーネントの状態が + # Active 以外の場合は、PRECONDITION_NOT_MET が返される。 + # + # @param comp 非アクティブ化対象RTコンポーネント + # + # @return ReturnCode_t 型のリターンコード + # + # @else + # + # @brief Deactivate an RT-component + # + # The given RTC is Active in the execution context. Cause it to + # transition to the Inactive state such that it will not be + # subsequently invoked from the context unless and until it is + # activated again. The callback on_deactivate shall be called as + # a result of calling this operation. This operation shall not + # return until the callback has returned, and shall result in an + # error if the callback does. + # + # @param comp The target RT-Component for deactivate + # + # @return The return code of ReturnCode_t type + # + # @endif + # RTC::ReturnCode_t deactivateComponent(RTC::LightweightRTObject_ptr comp, + # RTObjectStateMachine*& rtobj); + def deactivateComponent(self, comp): + self._rtcout.RTC_TRACE("deactivateComponent()") + guard = OpenRTM_aist.ScopedLock(self._mutex) + + rtobj = self.findComponent(comp) + if not rtobj: + del guard + self._rtcout.RTC_ERROR("Given RTC is not participant of this EC.") + return RTC.BAD_PARAMETER, rtobj + + if not rtobj.deactivate(): + del guard + self._rtcout.RTC_ERROR("State of the RTC is not ACTIVE_STATE.") + return RTC.PRECONDITION_NOT_MET, rtobj + del guard + return RTC.RTC_OK, rtobj + + # RTC::ReturnCode_t waitDeactivateComplete(RTObjectStateMachine*& rtobj, + # coil::TimeValue timeout = 1.0, + # long int cycle = 1000); + + def waitDeactivateComplete(self, rtobj, timeout=1.0, cycle=1000): + pass + + ## + # @if jp + # @brief RTコンポーネントをリセットする + # + # Error 状態のRTコンポーネントの復帰を試みる。この操作が呼ばれた結 + # 果、on_reset が呼び出される。指定したRTコンポーネントが参加者リ + # ストに含まれない場合は、BAD_PARAMETER が返される。指定したRTコン + # ポーネントの状態が Error 以外の場合は、PRECONDITION_NOT_MET が返 + # される。 + # + # @param comp リセット対象RTコンポーネント + # + # @return ReturnCode_t 型のリターンコード + # + # @else + # + # @brief Reset the RT-component + # + # Attempt to recover the RTC when it is in Error. The + # ComponentAction::on_reset callback shall be invoked. This + # operation shall not return until the callback has returned, and + # shall result in an error if the callback does. If possible, the + # RTC developer should implement that callback such that the RTC + # may be returned to a valid state. + # + # @param comp The target RT-Component for reset + # + # @return The return code of ReturnCode_t type + # + # @endif + # RTC::ReturnCode_t resetComponent(RTC::LightweightRTObject_ptr com, + # RTObjectStateMachine*& rtobj); + + def resetComponent(self, comp): + self._rtcout.RTC_TRACE("resetComponent()") + guard = OpenRTM_aist.ScopedLock(self._mutex) + + rtobj = self.findComponent(comp) + if not rtobj: + del guard + self._rtcout.RTC_ERROR("Given RTC is not participant of this EC.") + return RTC.BAD_PARAMETER, rtobj + + if not rtobj.reset(): + del guard + self._rtcout.RTC_ERROR("State of the RTC is not ERROR_STATE.") + return RTC.PRECONDITION_NOT_MET, rtobj - # bool isAllNextState(RTC::LifeCycleState state); - def isAllNextState(self, state): - guard = OpenRTM_aist.ScopedLock(self._mutex) - for comp in self._comps: - if not comp.isNextState(state): del guard - return False + return RTC.RTC_OK, rtobj + + # RTC::ReturnCode_t waitResetComplete(RTObjectStateMachine*& rtobj, + # coil::TimeValue timeout = 1.0, + # long int cycle = 1000); + + def waitResetComplete(self, rtobj, timeout=1.0, cycle=1000): + pass + + ## + # @if jp + # @brief RTコンポーネントの状態を取得する + # + # 指定したRTコンポーネントの状態(LifeCycleState)を取得する。指定し + # たRTコンポーネントが参加者リストに含まれない場合は、 + # UNKNOWN_STATE が返される。 + # + # @param comp 状態取得対象RTコンポーネント + # + # @return 現在の状態(LifeCycleState) + # + # @else + # + # @brief Get RT-component's state + # + # This operation shall report the LifeCycleState of the given + # participant RTC. UNKNOWN_STATE will be returned, if the given + # RT-Component is not inclued in the participant list. + # + # @param comp The target RT-Component to get the state + # + # @return The current state of the target RT-Component(LifeCycleState) + # + # @endif + # RTC::LifeCycleState getComponentState(RTC::LightweightRTObject_ptr comp); + + def getComponentState(self, comp): + self._rtcout.RTC_TRACE("getComponentState()") + guard = OpenRTM_aist.ScopedLock(self._mutex) + rtobj_ = self.findComponent(comp) + if not rtobj_: + del guard + self._rtcout.RTC_WARN("Given RTC is not participant of this EC.") + return RTC.CREATED_STATE + + state_ = rtobj_.getState() + self._rtcout.RTC_DEBUG( + "getComponentState() = %s done", + self.getStateString(state_)) + return state_ + + # const char* getStateString(RTC::LifeCycleState state) + + def getStateString(self, state): + st = ["CREATED_STATE", + "INACTIVE_STATE", + "ACTIVE_STATE", + "ERROR_STATE"] + + def f( + x): return st[x._v] if x._v >= RTC.CREATED_STATE._v and x._v <= RTC.ERROR_STATE._v else "" + return f(state) + + ## + # @if jp + # @brief RTコンポーネントを追加する + # + # 指定したRTコンポーネントを参加者リストに追加する。追加されたRTコ + # ンポーネントは attach_context が呼ばれ、Inactive 状態に遷移する。 + # 指定されたRTコンポーネントがnullの場合は、BAD_PARAMETER が返され + # る。指定されたRTコンポーネントが DataFlowComponent 以外の場合は、 + # BAD_PARAMETER が返される。 + # + # @param comp 追加対象RTコンポーネント + # + # @return ReturnCode_t 型のリターンコード + # + # @else + # + # @brief Add an RT-component + # + # The operation causes the given RTC to begin participating in + # the execution context. The newly added RTC will receive a call + # to LightweightRTComponent::attach_context and then enter the + # Inactive state. BAD_PARAMETER will be invoked, if the given + # RT-Component is null or if the given RT-Component is other than + # DataFlowComponent. + # + # @param comp The target RT-Component for add + # + # @return The return code of ReturnCode_t type + # + # @endif + # RTC::ReturnCode_t addComponent(RTC::LightweightRTObject_ptr comp); + def addComponent(self, comp): + self._rtcout.RTC_TRACE("addComponent()") + if CORBA.is_nil(comp): + self._rtcout.RTC_ERROR("nil reference is given.") + return RTC.BAD_PARAMETER + + try: + guard = OpenRTM_aist.ScopedLock(self._addedMutex) + ec_ = self.getECRef() + id_ = comp.attach_context(ec_) + self._addedComps.append( + OpenRTM_aist.RTObjectStateMachine( + id_, comp)) + del guard + except BaseException: + del guard + self._rtcout.RTC_ERROR("addComponent() failed.") + return RTC.RTC_ERROR + + self._rtcout.RTC_DEBUG("addComponent() succeeded.") + if self._running == False: + self.updateComponentList() + return RTC.RTC_OK + + ## + # @if jp + # @brief コンポーネントをバインドする。 + # + # コンポーネントをバインドする。 + # + # @param rtc RTコンポーネント + # @return ReturnCode_t 型のリターンコード + # @else + # @brief Bind the component. + # + # Bind the component. + # + # @param rtc RT-Component's instances + # @return The return code of ReturnCode_t type + # @endif + # RTC::ReturnCode_t bindComponent(RTC::RTObject_impl* rtc); + + def bindComponent(self, rtc): + self._rtcout.RTC_TRACE("bindComponent()") + guard = OpenRTM_aist.ScopedLock(self._mutex) + if not rtc: + del guard + self._rtcout.RTC_ERROR("NULL pointer is given.") + return RTC.BAD_PARAMETER + + ec_ = self.getECRef() + id_ = rtc.bindContext(ec_) + if id_ < 0 or id_ > OpenRTM_aist.ECOTHER_OFFSET: + # id should be owned context id < ECOTHER_OFFSET + del guard + self._rtcout.RTC_ERROR("bindContext returns invalid id: %d", id_) + return RTC.RTC_ERROR + + self._rtcout.RTC_DEBUG("bindContext returns id = %d", id_) + + # rtc is owner of this EC + comp_ = rtc.getObjRef() + # RTObjectStateMachine o(id, comp); + self._comps.append(OpenRTM_aist.RTObjectStateMachine(id_, comp_)) + del guard + self._rtcout.RTC_DEBUG("bindComponent() succeeded.") + return RTC.RTC_OK + + ## + # @if jp + # @brief RTコンポーネントを参加者リストから削除する + # + # 指定したRTコンポーネントを参加者リストから削除する。削除された + # RTコンポーネントは detach_context が呼ばれる。指定されたRTコンポー + # ネントが参加者リストに登録されていない場合は、BAD_PARAMETER が返 + # される。 + # + # @param comp 削除対象RTコンポーネント + # + # @return ReturnCode_t 型のリターンコード + # + # @else + # + # @brief Remove the RT-Component from participant list + # + # This operation causes a participant RTC to stop participating in the + # execution context. + # The removed RTC will receive a call to + # LightweightRTComponent::detach_context. + # BAD_PARAMETER will be returned, if the given RT-Component is not + # participating in the participant list. + # + # @param comp The target RT-Component for delete + # + # @return The return code of ReturnCode_t type + # + # @endif + # RTC::ReturnCode_t removeComponent(RTC::LightweightRTObject_ptr comp); + + def removeComponent(self, comp): + self._rtcout.RTC_TRACE("removeComponent()") + if CORBA.is_nil(comp): + self._rtcout.RTC_ERROR("nil reference is given.") + return RTC.BAD_PARAMETER + + guard = OpenRTM_aist.ScopedLock(self._mutex) + rtobj_ = self.findComponent(comp) + del guard + + if not rtobj_: + self._rtcout.RTC_ERROR("no RTC found in this context.") + return RTC.BAD_PARAMETER + + guard = OpenRTM_aist.ScopedLock(self._removedMutex) + self._removedComps.append(rtobj_) + del guard + if self._running == False: + self.updateComponentList() + return RTC.RTC_OK + + # RTObjectStateMachine* findComponent(RTC::LightweightRTObject_ptr comp); - del guard - return True + def findComponent(self, comp): + for comp_ in self._comps: + if comp_.isEquivalent(comp): + return comp_ + return None + + # bool isAllCurrentState(RTC::LifeCycleState state); + + def isAllCurrentState(self, state): + guard = OpenRTM_aist.ScopedLock(self._mutex) + for comp in self._comps: + if not comp.isCurrentState(state): + del guard + return False - # bool isOneOfCurrentState(RTC::LifeCycleState state); - def isOneOfCurrentState(self, state): - guard = OpenRTM_aist.ScopedLock(self._mutex) - for comp in self._comps: - if comp.isCurrentState(state): del guard return True - - del guard - return False + # bool isAllNextState(RTC::LifeCycleState state); + + def isAllNextState(self, state): + guard = OpenRTM_aist.ScopedLock(self._mutex) + for comp in self._comps: + if not comp.isNextState(state): + del guard + return False - # bool isOneOfNextState(RTC::LifeCycleState state); - def isOneOfNextState(self, state): - guard = OpenRTM_aist.ScopedLock(self._mutex) - for comp in self._comps: - if comp.isNextState(state): del guard return True - del guard - return False - - - # void invokeWorker(); - def invokeWorker(self): - self._rtcout.RTC_PARANOID("invokeWorker()") - # m_comps never changes its size here - len_ = len(self._comps) - - for i in range(len_): - self._comps[i].workerPreDo() - - for i in range(len_): - self._comps[i].workerDo() - - for i in range(len_): - self._comps[i].workerPostDo() - - self.updateComponentList() - return - - - # void invokeWorkerPreDo(); - def invokeWorkerPreDo(self): - self._rtcout.RTC_PARANOID("invokeWorkerPreDo()") - # m_comps never changes its size here - for comp in self._comps: - comp.workerPreDo() - return - - # void invokeWorkerDo(); - def invokeWorkerDo(self): - self._rtcout.RTC_PARANOID("invokeWorkerDo()") - # m_comps never changes its size here - for comp in self._comps: - comp.workerDo() - return - - # void invokeWorkerPostDo(); - def invokeWorkerPostDo(self): - self._rtcout.RTC_PARANOID("invokeWorkerPostDo()") - # m_comps never changes its size here - for comp in self._comps: - comp.workerPostDo() - # m_comps might be changed here - self.updateComponentList() - return - - # void updateComponentList(); - def updateComponentList(self): - guard = OpenRTM_aist.ScopedLock(self._mutex) - # adding component - guard_added = OpenRTM_aist.ScopedLock(self._addedMutex) - for comp in self._addedComps: - self._comps.append(comp) - self._rtcout.RTC_TRACE("Component added.") - - self._addedComps = [] - del guard_added - - # removing component - guard_removed = OpenRTM_aist.ScopedLock(self._removedMutex) - for comp in self._removedComps: - lwrtobj_ = comp.getRTObject() - lwrtobj_.detach_context(comp.getExecutionContextHandle()) - idx_ = -1 - try: - idx_ = self._comps.index(comp) - except: - idx_ = -1 - - if idx_ >= 0: - del self._comps[idx_] - self._rtcout.RTC_TRACE("Component deleted.") - - self._removedComps = [] - return + # bool isOneOfCurrentState(RTC::LifeCycleState state); + + def isOneOfCurrentState(self, state): + guard = OpenRTM_aist.ScopedLock(self._mutex) + for comp in self._comps: + if comp.isCurrentState(state): + del guard + return True + + del guard + return False + + # bool isOneOfNextState(RTC::LifeCycleState state); + + def isOneOfNextState(self, state): + guard = OpenRTM_aist.ScopedLock(self._mutex) + for comp in self._comps: + if comp.isNextState(state): + del guard + return True + + del guard + return False + # void invokeWorker(); + + def invokeWorker(self): + self._rtcout.RTC_PARANOID("invokeWorker()") + + for comp in self._comps: + comp.workerPreDo() + + for comp in self._comps: + comp.workerDo() + + for comp in self._comps: + comp.workerPostDo() + + self.updateComponentList() + return + + # void invokeWorkerPreDo(); + + def invokeWorkerPreDo(self): + self._rtcout.RTC_PARANOID("invokeWorkerPreDo()") + # m_comps never changes its size here + for comp in self._comps: + comp.workerPreDo() + return + + # void invokeWorkerDo(); + def invokeWorkerDo(self): + self._rtcout.RTC_PARANOID("invokeWorkerDo()") + # m_comps never changes its size here + for comp in self._comps: + comp.workerDo() + return + + # void invokeWorkerPostDo(); + def invokeWorkerPostDo(self): + self._rtcout.RTC_PARANOID("invokeWorkerPostDo()") + # m_comps never changes its size here + for comp in self._comps: + comp.workerPostDo() + # m_comps might be changed here + self.updateComponentList() + return + + # void updateComponentList(); + def updateComponentList(self): + guard = OpenRTM_aist.ScopedLock(self._mutex) + # adding component + guard_added = OpenRTM_aist.ScopedLock(self._addedMutex) + for comp in self._addedComps: + self._comps.append(comp) + self._rtcout.RTC_TRACE("Component added.") + + self._addedComps = [] + del guard_added + + # removing component + guard_removed = OpenRTM_aist.ScopedLock(self._removedMutex) + for comp in self._removedComps: + lwrtobj_ = comp.getRTObject() + lwrtobj_.detach_context(comp.getExecutionContextHandle()) + idx_ = -1 + try: + idx_ = self._comps.index(comp) + except BaseException: + idx_ = -1 + + if idx_ >= 0: + del self._comps[idx_] + self._rtcout.RTC_TRACE("Component deleted.") + + self._removedComps = [] + return diff --git a/OpenRTM_aist/ExtTrigExecutionContext.py b/OpenRTM_aist/ExtTrigExecutionContext.py index e21c2152..a37bf554 100644 --- a/OpenRTM_aist/ExtTrigExecutionContext.py +++ b/OpenRTM_aist/ExtTrigExecutionContext.py @@ -1,5 +1,5 @@ #!/usr/bin/env python -# -*- coding: euc-jp -*- +# -*- coding: utf-8 -*- ## # @file ExtTrigExecutionContext.py @@ -15,22 +15,22 @@ # All rights reserved. - import threading import time import OpenRTM_aist -import OpenRTM__POA, RTC +import OpenRTM__POA +import RTC ## # @if jp # @class ExtTrigExecutionContext -# @brief ƥå׼¹Ԥǽ ExecutionContext 饹 +# @brief ステップ実行が可能な ExecutionContext クラス # -# μ¹ԤǽPeriodic Sampled Data Processing(¹) -# ExecutionContext饹 -# Υ᥽åɸƤӤˤäƻ֤򣱼ŤĿʤ뤳ȤǤ롣 +# 1周期毎の実行が可能なPeriodic Sampled Data Processing(周期実行用) +# ExecutionContextクラス。 +# 外部からのメソッド呼びだしによって時間を1周期づつ進めることができる。 # # @since 0.4.0 # @@ -40,464 +40,14 @@ class ExtTrigExecutionContext(OpenRTM_aist.ExecutionContextBase, OpenRTM__POA.ExtTrigExecutionContextService, OpenRTM_aist.Task): - """ - """ - - ## - # @if jp - # @brief 󥹥ȥ饯 - # - # 󥹥ȥ饯 - # - # @param self - # - # @else - # @brief Constructor - # @endif - def __init__(self): - self._rtcout = OpenRTM_aist.Manager.instance().getLogbuf("rtobject.exttrig_async_ec") - self._rtcout.RTC_TRACE("ExtTrigExecutionContext.__init__()") - OpenRTM_aist.ExecutionContextBase.__init__(self,"exttrig_async_ec") - OpenRTM_aist.Task.__init__(self) - - # getting my reference - self.setObjRef(self._this()) - - # profile initialization - self.setKind(RTC.PERIODIC) - self.setRate(OpenRTM_aist.DEFAULT_EXECUTION_RATE) - - self._rtcout.RTC_DEBUG("Actual period: %d [sec], %d [usec]", - (self._profile.getPeriod().sec(), self._profile.getPeriod().usec())) - self._svc = False - self._workerthread = self.Worker() - self._svcmutex = threading.RLock() - return - - - def exit(self, Task=OpenRTM_aist.Task): - self._rtcout.RTC_TRACE("exit") - guard = OpenRTM_aist.ScopedLock(self._svcmutex) - self._svc = False - del guard - - guard = OpenRTM_aist.ScopedLock(self._workerthread._mutex) - self._workerthread._cond.acquire() - self._workerthread._ticked = True - self._workerthread._cond.notify() - self._workerthread._cond.release() - del guard - self.wait() - Task.__del__(self) - OpenRTM_aist.ExecutionContextBase.exit(self) - return - - - ## - # Start activity - # ACE_Task class method over ride. - # ------------------------------------------------------------ - - ## - # @if jp - # @brief ExecutionContextѥƥӥƥåɤ - # @else - # @brief Generate internal activity thread for ExecutionContext - # @endif - # int ExtTrigExecutionContext::open(void *args) - def open(self, *args): - self._rtcout.RTC_TRACE("open()") - self.activate() - return 0 - - - ## - # @if jp - # @brief Component νƤӽФ - # @else - # @brief Invoke each component's operation - # @endif - # int ExtTrigExecutionContext::svc(void) - def svc(self): - self._rtcout.RTC_TRACE("svc()") - - toSTR_ = lambda x: "True" if x else "False" - - while self.threadRunning(): - guard = OpenRTM_aist.ScopedLock(self._workerthread._mutex) - self._rtcout.RTC_DEBUG("Start of worker invocation. ticked = %s", - toSTR_(self._workerthread._ticked)) - - while not self._workerthread._ticked: - self._workerthread._cond.wait() # wait for tick - self._rtcout.RTC_DEBUG("Thread was woken up.") - - if not self._workerthread._ticked: - continue - del guard - - t0_ = OpenRTM_aist.Time() - OpenRTM_aist.ExecutionContextBase.invokeWorkerPreDo(self) - OpenRTM_aist.ExecutionContextBase.invokeWorkerDo(self) - OpenRTM_aist.ExecutionContextBase.invokeWorkerPostDo(self) - t1_ = OpenRTM_aist.Time() - guard = OpenRTM_aist.ScopedLock(self._workerthread._mutex) - self._workerthread._ticked = False - del guard - - period_ = self.getPeriod() - - exctm_ = (t1_ - t0_).getTime().toDouble() - slptm_ = period_.toDouble() - exctm_ - self._rtcout.RTC_PARANOID("Period: %f [s]", period_.toDouble()) - self._rtcout.RTC_PARANOID("Execution: %f [s]", exctm_) - self._rtcout.RTC_PARANOID("Sleep: %f [s]", slptm_) - - t2_ = OpenRTM_aist.Time() - - if period_.toDouble() > ((t1_ - t0_).getTime().toDouble()): - self._rtcout.RTC_PARANOID("sleeping...") - slptm_ = period_.toDouble() - (t1_ - t0_).getTime().toDouble() - time.sleep(slptm_) - - t3_ = OpenRTM_aist.Time() - self._rtcout.RTC_PARANOID("Slept: %f [s]", (t3_ - t2_).getTime().toDouble()) - return 0 - - - ## - # @if jp - # @brief ExecutionContext ѤΥåɼ¹Դؿ - # @else - # @brief Thread execution function for ExecutionContext - # @endif - # int ExtTrigExecutionContext::close(unsigned long flags) - def close(self, flags): - self._rtcout.RTC_TRACE("close()") - # At this point, this component have to be finished. - # Current state and Next state should be RTC_EXITING. - return 0 - - - #============================================================ - # ExtTrigExecutionContextService - #============================================================ - - ## - # @if jp - # @brief 1ƥå׿ʤ - # @else - # @brief Move forward one step of ExecutionContext - # @endif - # void ExtTrigExecutionContext::tick() - # throw (CORBA::SystemException) - def tick(self): - self._rtcout.RTC_TRACE("tick()") - if not self.isRunning(): - self._rtcout.RTC_DEBUG("EC is not running. do nothing.") - return - - guard = OpenRTM_aist.ScopedLock(self._workerthread._mutex) - self._workerthread._ticked = True - self._workerthread._cond.acquire() - self._workerthread._cond.notify() - self._workerthread._cond.release() - self._rtcout.RTC_PARANOID("EC was ticked. Signal was sent to worker thread.") - del guard - return - - - #============================================================ - # ExecutionContextService - #============================================================ - - ## - # @if jp - # @brief ExecutionContext ¹Ծֳǧؿ - # @else - # @brief Check for ExecutionContext running state - # @endif - # CORBA::Boolean ExtTrigExecutionContext::is_running() - # throw (CORBA::SystemException) - def is_running(self): - return OpenRTM_aist.ExecutionContextBase.isRunning(self) - - - ## - # @if jp - # @brief ExecutionContext μ¹Ԥ򳫻 - # @else - # @brief Start the ExecutionContext - # @endif - # RTC::ReturnCode_t ExtTrigExecutionContext::start() - # throw (CORBA::SystemException) - def start(self): - return OpenRTM_aist.ExecutionContextBase.start(self) - - - ## - # @if jp - # @brief ExecutionContext μ¹Ԥ - # @else - # @brief Stop the ExecutionContext - # @endif - # RTC::ReturnCode_t ExtTrigExecutionContext::stop() - # throw (CORBA::SystemException) - def stop(self): - return OpenRTM_aist.ExecutionContextBase.stop(self) - - - ## - # @if jp - # @brief ExecutionContext μ¹Լ(Hz) - # @else - # @brief Get execution rate(Hz) of ExecutionContext - # @endif - # CORBA::Double ExtTrigExecutionContext::get_rate() - # throw (CORBA::SystemException) - def get_rate(self): - return OpenRTM_aist.ExecutionContextBase.getRate(self) - - - ## - # @if jp - # @brief ExecutionContext μ¹Լ(Hz)ꤹ - # @else - # @brief Set execution rate(Hz) of ExecutionContext - # @endif - # RTC::ReturnCode_t ExtTrigExecutionContext::set_rate(CORBA::Double rate) - # throw (CORBA::SystemException) - def set_rate(self, rate): - return OpenRTM_aist.ExecutionContextBase.setRate(self, rate) - - - ## - # @if jp - # @brief RTݡͥȤɲä - # @else - # @brief Add an RT-Component - # @endif - # RTC::ReturnCode_t - # ExtTrigExecutionContext::add_component(RTC::LightweightRTObject_ptr comp) - # throw (CORBA::SystemException) - def add_component(self, comp): - return OpenRTM_aist.ExecutionContextBase.addComponent(self, comp) - - - ## - # @if jp - # @brief ݡͥȤ򥳥ݡͥȥꥹȤ - # @else - # @brief Remove the RT-Component from participant list - # @endif - # RTC::ReturnCode_t ExtTrigExecutionContext:: - # remove_component(RTC::LightweightRTObject_ptr comp) - # throw (CORBA::SystemException) - def remove_component(self, comp): - return OpenRTM_aist.ExecutionContextBase.removeComponent(self, comp) - - - ## - # @if jp - # @brief RTݡͥȤ򥢥ƥֲ - # @else - # @brief Activate an RT-Component - # @endif - # RTC::ReturnCode_t ExtTrigExecutionContext:: - # activate_component(RTC::LightweightRTObject_ptr comp) - # throw (CORBA::SystemException) - def activate_component(self, comp): - return OpenRTM_aist.ExecutionContextBase.activateComponent(self, comp) - - - ## - # @if jp - # @brief RTݡͥȤ󥢥ƥֲ - # @else - # @brief Deactivate an RT-Component - # @endif - # RTC::ReturnCode_t ExtTrigExecutionContext:: - # deactivate_component(RTC::LightweightRTObject_ptr comp) - # throw (CORBA::SystemException) - def deactivate_component(self, comp): - return OpenRTM_aist.ExecutionContextBase.deactivateComponent(self, comp) - - - ## - # @if jp - # @brief RTݡͥȤꥻåȤ - # @else - # @brief Reset the RT-Component - # @endif - # RTC::ReturnCode_t ExtTrigExecutionContext:: - # reset_component(RTC::LightweightRTObject_ptr comp) - # throw (CORBA::SystemException) - def reset_component(self, comp): - return OpenRTM_aist.ExecutionContextBase.resetComponent(self, comp) - - - ## - # @if jp - # @brief RTݡͥȤξ֤ - # @else - # @brief Get RT-Component's state - # @endif - # RTC::LifeCycleState ExtTrigExecutionContext:: - # get_component_state(RTC::LightweightRTObject_ptr comp) - # throw (CORBA::SystemException) - def get_component_state(self, comp): - return OpenRTM_aist.ExecutionContextBase.getComponentState(self, comp) - - - ## - # @if jp - # @brief ExecutionKind - # @else - # @brief Get the ExecutionKind - # @endif - # RTC::ExecutionKind ExtTrigExecutionContext::get_kind() - # throw (CORBA::SystemException) - def get_kind(self): - return OpenRTM_aist.ExecutionContextBase.getKind(self) - - - #------------------------------------------------------------ - # ExecutionContextService interfaces - #------------------------------------------------------------ - - ## - # @if jp - # @brief ExecutionContextProfile - # @else - # @brief Get the ExecutionContextProfile - # @endif - # RTC::ExecutionContextProfile* ExtTrigExecutionContext::get_profile() - # throw (CORBA::SystemException) - def get_profile(self): - return OpenRTM_aist.ExecutionContextBase.getProfile(self) - - - #============================================================ - # protected functions - #============================================================ - - ## - # @brief onStarted() template function - # RTC::ReturnCode_t ExtTrigExecutionContext::onStarted() - def onStarted(self): - # change EC thread state - guard = OpenRTM_aist.ScopedLock(self._svcmutex) - if not self._svc: - # If start() is called first time, start the worker thread. - self._svc = True - self.open(0) - - return RTC.RTC_OK - - # virtual RTC::ReturnCode_t onStopping(); - def onStopping(self): - guard = OpenRTM_aist.ScopedLock(self._svcmutex) - self._svc = False - del guard - - # stop thread - self.tick() - - return RTC.RTC_OK - - def onAddedComponent(self, rtobj): - guard = OpenRTM_aist.ScopedLock(self._workerthread._mutex) - if self._workerthread._ticked == False: - self._worker.updateComponentList() - return RTC.RTC_OK - - def onRemovedComponent(self, rtobj): - guard = OpenRTM_aist.ScopedLock(self._workerthread._mutex) - if self._workerthread._ticked == False: - self._worker.updateComponentList() - return RTC.RTC_OK - - ## - # @brief onWaitingActivated() template function - # RTC::ReturnCode_t ExtTrigExecutionContext:: - # onWaitingActivated(RTC_impl::RTObjectStateMachine* comp, long int count) - def onWaitingActivated(self, comp, count): - self._rtcout.RTC_TRACE("onWaitingActivated(count = %d)", count) - self._rtcout.RTC_PARANOID("curr: %s, next: %s", - (self.getStateString(comp.getStates().curr), - self.getStateString(comp.getStates().next))) - # Now comp's next state must be ACTIVE state - # If worker thread is stopped, restart worker thread. - guard = OpenRTM_aist.ScopedLock(self._workerthread._mutex) - self._workerthread._ticked = True - self._workerthread._cond.acquire() - self._workerthread._cond.notify() - self._workerthread._cond.release() - return RTC.RTC_OK - - - ## - # @brief onWaitingDeactivated() template function - # RTC::ReturnCode_t ExtTrigExecutionContext:: - # onWaitingDeactivated(RTC_impl::RTObjectStateMachine* comp, long int count) - def onWaitingDeactivated(self, comp, count): - self._rtcout.RTC_TRACE("onWaitingDeactivated(count = %d)", count) - self._rtcout.RTC_PARANOID("curr: %s, next: %s", - (self.getStateString(comp.getStates().curr), - self.getStateString(comp.getStates().next))) - guard = OpenRTM_aist.ScopedLock(self._workerthread._mutex) - self._workerthread._ticked = True - self._workerthread._cond.acquire() - self._workerthread._cond.notify() - self._workerthread._cond.release() - return RTC.RTC_OK - - - ## - # @brief onWaitingReset() template function - # RTC::ReturnCode_t ExtTrigExecutionContext:: - # onWaitingReset(RTC_impl::RTObjectStateMachine* comp, long int count) - def onWaitingReset(self, comp, count): - self._rtcout.RTC_TRACE("onWaitingReset(count = %d)", count) - self._rtcout.RTC_PARANOID("curr: %s, next: %s", - (self.getStateString(comp.getStates().curr), - self.getStateString(comp.getStates().next))) - guard = OpenRTM_aist.ScopedLock(self._workerthread._mutex) - self._workerthread._ticked = True - self._workerthread._cond.acquire() - self._workerthread._cond.notify() - self._workerthread._cond.release() - return RTC.RTC_OK - - - # bool threadRunning() - def threadRunning(self): - guard = OpenRTM_aist.ScopedLock(self._svcmutex) - return self._svc - - - - ## - # @if jp - # @class Worker - # @brief ExecutionContext ư饹 - # - # ¹Խ˴ؤ¾ʤɡºݤνƻ롦椹뤿Υ饹 - # - # @since 0.4.0 - # - # @else - # - # @endif - class Worker: """ """ - + ## # @if jp - # @brief 󥹥ȥ饯 + # @brief コンストラクタ # - # 󥹥ȥ饯 + # コンストラクタ # # @param self # @@ -505,23 +55,474 @@ class Worker: # @brief Constructor # @endif def __init__(self): - self._mutex = threading.RLock() - self._cond = threading.Condition(self._mutex) - self._ticked = False + self._rtcout = OpenRTM_aist.Manager.instance().getLogbuf("rtobject.exttrig_async_ec") + self._rtcout.RTC_TRACE("ExtTrigExecutionContext.__init__()") + OpenRTM_aist.ExecutionContextBase.__init__(self, "exttrig_async_ec") + OpenRTM_aist.Task.__init__(self) + + # getting my reference + self.setObjRef(self._this()) + + # profile initialization + self.setKind(RTC.PERIODIC) + self.setRate(OpenRTM_aist.DEFAULT_EXECUTION_RATE) + + self._rtcout.RTC_DEBUG("Actual period: %d [sec], %d [usec]", + (self._profile.getPeriod().sec(), self._profile.getPeriod().usec())) + self._svc = False + self._workerthread = self.Worker() + self._svcmutex = threading.RLock() + return + + def exit(self, Task=OpenRTM_aist.Task): + self._rtcout.RTC_TRACE("exit") + guard = OpenRTM_aist.ScopedLock(self._svcmutex) + self._svc = False + del guard + + guard = OpenRTM_aist.ScopedLock(self._workerthread._mutex) + self._workerthread._cond.acquire() + self._workerthread._ticked = True + self._workerthread._cond.notify() + self._workerthread._cond.release() + del guard + self.wait() + Task.__del__(self) + OpenRTM_aist.ExecutionContextBase.exit(self) + return + + ## + # Start activity + # ACE_Task class method over ride. + # ------------------------------------------------------------ + + ## + # @if jp + # @brief ExecutionContext用アクティビティスレッドを生成する + # @else + # @brief Generate internal activity thread for ExecutionContext + # @endif + # int ExtTrigExecutionContext::open(void *args) + + def open(self, *args): + self._rtcout.RTC_TRACE("open()") + self.activate() + return 0 + + ## + # @if jp + # @brief 各 Component の処理を呼び出す。 + # @else + # @brief Invoke each component's operation + # @endif + # int ExtTrigExecutionContext::svc(void) + + def svc(self): + self._rtcout.RTC_TRACE("svc()") + + def toSTR_(x): return "True" if x else "False" + + while self.threadRunning(): + guard = OpenRTM_aist.ScopedLock(self._workerthread._mutex) + self._rtcout.RTC_DEBUG("Start of worker invocation. ticked = %s", + toSTR_(self._workerthread._ticked)) + + while not self._workerthread._ticked: + self._workerthread._cond.wait() # wait for tick + self._rtcout.RTC_DEBUG("Thread was woken up.") + + if not self._workerthread._ticked: + continue + del guard + + t0_ = OpenRTM_aist.Time() + OpenRTM_aist.ExecutionContextBase.invokeWorkerPreDo(self) + OpenRTM_aist.ExecutionContextBase.invokeWorkerDo(self) + OpenRTM_aist.ExecutionContextBase.invokeWorkerPostDo(self) + t1_ = OpenRTM_aist.Time() + guard = OpenRTM_aist.ScopedLock(self._workerthread._mutex) + self._workerthread._ticked = False + del guard + + period_ = self.getPeriod() + + exctm_ = (t1_ - t0_).getTime().toDouble() + slptm_ = period_.toDouble() - exctm_ + self._rtcout.RTC_PARANOID("Period: %f [s]", period_.toDouble()) + self._rtcout.RTC_PARANOID("Execution: %f [s]", exctm_) + self._rtcout.RTC_PARANOID("Sleep: %f [s]", slptm_) + + t2_ = OpenRTM_aist.Time() + + if period_.toDouble() > ((t1_ - t0_).getTime().toDouble()): + self._rtcout.RTC_PARANOID("sleeping...") + slptm_ = period_.toDouble() - (t1_ - t0_).getTime().toDouble() + time.sleep(slptm_) + + t3_ = OpenRTM_aist.Time() + self._rtcout.RTC_PARANOID( + "Slept: %f [s]", + (t3_ - t2_).getTime().toDouble()) + return 0 + + ## + # @if jp + # @brief ExecutionContext 用のスレッド実行関数 + # @else + # @brief Thread execution function for ExecutionContext + # @endif + # int ExtTrigExecutionContext::close(unsigned long flags) + + def close(self, flags): + self._rtcout.RTC_TRACE("close()") + # At this point, this component have to be finished. + # Current state and Next state should be RTC_EXITING. + return 0 + + # ============================================================ + # ExtTrigExecutionContextService + # ============================================================ + + ## + # @if jp + # @brief 処理を1ステップ進める + # @else + # @brief Move forward one step of ExecutionContext + # @endif + # void ExtTrigExecutionContext::tick() + # throw (CORBA::SystemException) + + def tick(self): + self._rtcout.RTC_TRACE("tick()") + if not self.isRunning(): + self._rtcout.RTC_DEBUG("EC is not running. do nothing.") + return + + guard = OpenRTM_aist.ScopedLock(self._workerthread._mutex) + self._workerthread._ticked = True + self._workerthread._cond.acquire() + self._workerthread._cond.notify() + self._workerthread._cond.release() + self._rtcout.RTC_PARANOID( + "EC was ticked. Signal was sent to worker thread.") + del guard + return + + # ============================================================ + # ExecutionContextService + # ============================================================ + + ## + # @if jp + # @brief ExecutionContext 実行状態確認関数 + # @else + # @brief Check for ExecutionContext running state + # @endif + # CORBA::Boolean ExtTrigExecutionContext::is_running() + # throw (CORBA::SystemException) + + def is_running(self): + return OpenRTM_aist.ExecutionContextBase.isRunning(self) + + ## + # @if jp + # @brief ExecutionContext の実行を開始 + # @else + # @brief Start the ExecutionContext + # @endif + # RTC::ReturnCode_t ExtTrigExecutionContext::start() + # throw (CORBA::SystemException) + + def start(self): + return OpenRTM_aist.ExecutionContextBase.start(self) + + ## + # @if jp + # @brief ExecutionContext の実行を停止 + # @else + # @brief Stop the ExecutionContext + # @endif + # RTC::ReturnCode_t ExtTrigExecutionContext::stop() + # throw (CORBA::SystemException) + + def stop(self): + return OpenRTM_aist.ExecutionContextBase.stop(self) + + ## + # @if jp + # @brief ExecutionContext の実行周期(Hz)を取得する + # @else + # @brief Get execution rate(Hz) of ExecutionContext + # @endif + # CORBA::Double ExtTrigExecutionContext::get_rate() + # throw (CORBA::SystemException) + + def get_rate(self): + return OpenRTM_aist.ExecutionContextBase.getRate(self) + + ## + # @if jp + # @brief ExecutionContext の実行周期(Hz)を設定する + # @else + # @brief Set execution rate(Hz) of ExecutionContext + # @endif + # RTC::ReturnCode_t ExtTrigExecutionContext::set_rate(CORBA::Double rate) + # throw (CORBA::SystemException) + + def set_rate(self, rate): + return OpenRTM_aist.ExecutionContextBase.setRate(self, rate) + + ## + # @if jp + # @brief RTコンポーネントを追加する + # @else + # @brief Add an RT-Component + # @endif + # RTC::ReturnCode_t + # ExtTrigExecutionContext::add_component(RTC::LightweightRTObject_ptr comp) + # throw (CORBA::SystemException) + + def add_component(self, comp): + return OpenRTM_aist.ExecutionContextBase.addComponent(self, comp) + + ## + # @if jp + # @brief コンポーネントをコンポーネントリストから削除する + # @else + # @brief Remove the RT-Component from participant list + # @endif + # RTC::ReturnCode_t ExtTrigExecutionContext:: + # remove_component(RTC::LightweightRTObject_ptr comp) + # throw (CORBA::SystemException) + + def remove_component(self, comp): + return OpenRTM_aist.ExecutionContextBase.removeComponent(self, comp) + + ## + # @if jp + # @brief RTコンポーネントをアクティブ化する + # @else + # @brief Activate an RT-Component + # @endif + # RTC::ReturnCode_t ExtTrigExecutionContext:: + # activate_component(RTC::LightweightRTObject_ptr comp) + # throw (CORBA::SystemException) + + def activate_component(self, comp): + return OpenRTM_aist.ExecutionContextBase.activateComponent(self, comp) + + ## + # @if jp + # @brief RTコンポーネントを非アクティブ化する + # @else + # @brief Deactivate an RT-Component + # @endif + # RTC::ReturnCode_t ExtTrigExecutionContext:: + # deactivate_component(RTC::LightweightRTObject_ptr comp) + # throw (CORBA::SystemException) + + def deactivate_component(self, comp): + return OpenRTM_aist.ExecutionContextBase.deactivateComponent( + self, comp) + + ## + # @if jp + # @brief RTコンポーネントをリセットする + # @else + # @brief Reset the RT-Component + # @endif + # RTC::ReturnCode_t ExtTrigExecutionContext:: + # reset_component(RTC::LightweightRTObject_ptr comp) + # throw (CORBA::SystemException) + + def reset_component(self, comp): + return OpenRTM_aist.ExecutionContextBase.resetComponent(self, comp) + + ## + # @if jp + # @brief RTコンポーネントの状態を取得する + # @else + # @brief Get RT-Component's state + # @endif + # RTC::LifeCycleState ExtTrigExecutionContext:: + # get_component_state(RTC::LightweightRTObject_ptr comp) + # throw (CORBA::SystemException) + + def get_component_state(self, comp): + return OpenRTM_aist.ExecutionContextBase.getComponentState(self, comp) + + ## + # @if jp + # @brief ExecutionKind を取得する + # @else + # @brief Get the ExecutionKind + # @endif + # RTC::ExecutionKind ExtTrigExecutionContext::get_kind() + # throw (CORBA::SystemException) + + def get_kind(self): + return OpenRTM_aist.ExecutionContextBase.getKind(self) + + # ------------------------------------------------------------ + # ExecutionContextService interfaces + # ------------------------------------------------------------ + + ## + # @if jp + # @brief ExecutionContextProfile を取得する + # @else + # @brief Get the ExecutionContextProfile + # @endif + # RTC::ExecutionContextProfile* ExtTrigExecutionContext::get_profile() + # throw (CORBA::SystemException) + + def get_profile(self): + return OpenRTM_aist.ExecutionContextBase.getProfile(self) + + # ============================================================ + # protected functions + # ============================================================ + + ## + # @brief onStarted() template function + # RTC::ReturnCode_t ExtTrigExecutionContext::onStarted() + + def onStarted(self): + # change EC thread state + guard = OpenRTM_aist.ScopedLock(self._svcmutex) + if not self._svc: + # If start() is called first time, start the worker thread. + self._svc = True + self.open(0) + + return RTC.RTC_OK + + # virtual RTC::ReturnCode_t onStopping(); + def onStopping(self): + guard = OpenRTM_aist.ScopedLock(self._svcmutex) + self._svc = False + del guard + + # stop thread + self.tick() + + return RTC.RTC_OK + + def onAddedComponent(self, rtobj): + guard = OpenRTM_aist.ScopedLock(self._workerthread._mutex) + if self._workerthread._ticked == False: + self._worker.updateComponentList() + return RTC.RTC_OK + + def onRemovedComponent(self, rtobj): + guard = OpenRTM_aist.ScopedLock(self._workerthread._mutex) + if self._workerthread._ticked == False: + self._worker.updateComponentList() + return RTC.RTC_OK + + ## + # @brief onWaitingActivated() template function + # RTC::ReturnCode_t ExtTrigExecutionContext:: + # onWaitingActivated(RTC_impl::RTObjectStateMachine* comp, long int count) + def onWaitingActivated(self, comp, count): + self._rtcout.RTC_TRACE("onWaitingActivated(count = %d)", count) + self._rtcout.RTC_PARANOID("curr: %s, next: %s", + (self.getStateString(comp.getStates().curr), + self.getStateString(comp.getStates().next))) + # Now comp's next state must be ACTIVE state + # If worker thread is stopped, restart worker thread. + guard = OpenRTM_aist.ScopedLock(self._workerthread._mutex) + self._workerthread._ticked = True + self._workerthread._cond.acquire() + self._workerthread._cond.notify() + self._workerthread._cond.release() + return RTC.RTC_OK + + ## + # @brief onWaitingDeactivated() template function + # RTC::ReturnCode_t ExtTrigExecutionContext:: + # onWaitingDeactivated(RTC_impl::RTObjectStateMachine* comp, long int + # count) + + def onWaitingDeactivated(self, comp, count): + self._rtcout.RTC_TRACE("onWaitingDeactivated(count = %d)", count) + self._rtcout.RTC_PARANOID("curr: %s, next: %s", + (self.getStateString(comp.getStates().curr), + self.getStateString(comp.getStates().next))) + guard = OpenRTM_aist.ScopedLock(self._workerthread._mutex) + self._workerthread._ticked = True + self._workerthread._cond.acquire() + self._workerthread._cond.notify() + self._workerthread._cond.release() + return RTC.RTC_OK + + ## + # @brief onWaitingReset() template function + # RTC::ReturnCode_t ExtTrigExecutionContext:: + # onWaitingReset(RTC_impl::RTObjectStateMachine* comp, long int count) + + def onWaitingReset(self, comp, count): + self._rtcout.RTC_TRACE("onWaitingReset(count = %d)", count) + self._rtcout.RTC_PARANOID("curr: %s, next: %s", + (self.getStateString(comp.getStates().curr), + self.getStateString(comp.getStates().next))) + guard = OpenRTM_aist.ScopedLock(self._workerthread._mutex) + self._workerthread._ticked = True + self._workerthread._cond.acquire() + self._workerthread._cond.notify() + self._workerthread._cond.release() + return RTC.RTC_OK + + # bool threadRunning() + + def threadRunning(self): + guard = OpenRTM_aist.ScopedLock(self._svcmutex) + return self._svc + + ## + # @if jp + # @class Worker + # @brief ExecutionContext 駆動クラス + # + # 実行処理に関する排他制御など、実際の処理を監視・制御するためのクラス。 + # + # @since 0.4.0 + # + # @else + # + # @endif + class Worker: + """ + """ + + ## + # @if jp + # @brief コンストラクタ + # + # コンストラクタ + # + # @param self + # + # @else + # @brief Constructor + # @endif + def __init__(self): + self._mutex = threading.RLock() + self._cond = threading.Condition(self._mutex) + self._ticked = False ## # @if jp -# @brief ExecutionContext Factory饹Ͽ +# @brief 当該 ExecutionContext 用Factoryクラスの登録。 # -# ExecutionContextFactory饹 -# ExecutionContextObjectManagerϿ롣 +# このExecutionContextを生成するFactoryクラスを +# ExecutionContext管理用ObjectManagerに登録する。 # # @else # # @endif def ExtTrigExecutionContextInit(manager): - OpenRTM_aist.ExecutionContextFactory.instance().addFactory("ExtTrigExecutionContext", - OpenRTM_aist.ExtTrigExecutionContext, - OpenRTM_aist.ECDelete) + OpenRTM_aist.ExecutionContextFactory.instance().addFactory("ExtTrigExecutionContext", + OpenRTM_aist.ExtTrigExecutionContext) diff --git a/OpenRTM_aist/Factory.py b/OpenRTM_aist/Factory.py index d25faabb..2e9793a0 100644 --- a/OpenRTM_aist/Factory.py +++ b/OpenRTM_aist/Factory.py @@ -1,5 +1,5 @@ #!/usr/bin/env python -# -*- coding: euc-jp -*- +# -*- coding: utf-8 -*- ## # @file Factory.py @@ -20,31 +20,30 @@ ## # @if jp # -# @brief brief RTݡͥ˴Ѵؿ +# @brief brief RTコンポーネント破棄用関数 # -# RTݡͥȤΥ󥹥󥹤˴뤿δؿ -# ˤƻꤷRTݡͥȤΥ󥹥󥹤򡢽λƤӽФ -# ˴롣 +# RTコンポーネントのインスタンスを破棄するための関数。 +# 引数にて指定したRTコンポーネントのインスタンスを、終了処理を呼び出して +# 破棄する。 # -# @param rtc ˴оRTݡͥȤΥ󥹥 +# @param rtc 破棄対象RTコンポーネントのインスタンス # # @else # # @endif def Delete(rtc): - del rtc - + del rtc ## # @if jp # # @class FactoryBase -# @brief FactoryBase 쥯饹 -# -# RTݡͥѥեȥδ쥯饹 -# ºݤγƼեȥꥯ饹ϡܥ饹ѾǼ롣 -# ºݤ϶ݥ֥饹ˤƼɬפ롣 +# @brief FactoryBase 基底クラス +# +# RTコンポーネント生成用ファクトリの基底クラス。 +# 実際の各種ファクトリクラスを実装する場合は、本クラスを継承する形で実装する。 +# 実際の生成、削除処理は具象サブクラスにて実装する必要がある。 # # @since 0.2.0 # @@ -59,135 +58,133 @@ def Delete(rtc): # # @endif class FactoryBase: - """ - """ + """ + """ - ## - # @if jp - # - # @brief 󥹥ȥ饯 - # - # 󥹥ȥ饯 - # - # @param self - # @param profile ݡͥȤΥץե - # - # @else - # - # @brief Constructor. - # - # Constructor. - # - # @param profile component profile - # - # @endif - def __init__(self, profile): - ## self._Profile Component profile - self._Profile = profile - ## self._Number Number of current component instances. - self._Number = -1 - - pass + ## + # @if jp + # + # @brief コンストラクタ + # + # コンストラクタ。 + # + # @param self + # @param profile コンポーネントのプロファイル + # + # @else + # + # @brief Constructor. + # + # Constructor. + # + # @param profile component profile + # + # @endif + def __init__(self, profile): + # self._Profile Component profile + self._Profile = profile + # self._Number Number of current component instances. + self._Number = -1 + pass - ## - # @if jp - # - # @brief ݡͥȤ(֥饹) - # - # RTComponent Υ󥹥󥹤뤿δؿ
- # ºݤνϡƶݥ饹ˤƵҤ롣 - # - # @param self - # @param mgr ޥ͡㥪֥ - # - # @return ݡͥ - # - # @else - # - # @brief Create component - # - # @param mgr pointer to RtcManager - # - # @endif - def create(self, mgr): - pass + ## + # @if jp + # + # @brief コンポーネントの生成(サブクラス実装用) + # + # RTComponent のインスタンスを生成するための関数。
+ # 実際の初期化処理は、各具象クラス内にて記述する。 + # + # @param self + # @param mgr マネージャオブジェクト + # + # @return 生成したコンポーネント + # + # @else + # + # @brief Create component + # + # @param mgr pointer to RtcManager + # + # @endif + def create(self, mgr): + pass - ## - # @if jp - # - # @brief ݡͥȤ˴(֥饹) - # - # RTComponent Υ󥹥󥹤˴뤿δؿ
- # ºݤνϡƶݥ饹ˤƵҤ롣 - # - # @param self - # @param comp ˴о RTݡͥ - # - # @else - # - # @brief Destroy component - # - # @param comp pointer to RtcBase - # - # @endif - def destroy(self, comp): - pass + ## + # @if jp + # + # @brief コンポーネントの破棄(サブクラス実装用) + # + # RTComponent のインスタンスを破棄するための関数。
+ # 実際の初期化処理は、各具象クラス内にて記述する。 + # + # @param self + # @param comp 破棄対象 RTコンポーネント + # + # @else + # + # @brief Destroy component + # + # @param comp pointer to RtcBase + # + # @endif + def destroy(self, comp): + pass - ## - # @if jp - # - # @brief ݡͥȥץեμ - # - # ݡͥȤΥץե - # - # @param self - # - # @return ݡͥȤΥץե - # - # @else - # - # @brief Get component profile - # - # Get component profile. - # - # @endif - def profile(self): - return self._Profile + ## + # @if jp + # + # @brief コンポーネントプロファイルの取得 + # + # コンポーネントのプロファイルを取得する + # + # @param self + # + # @return コンポーネントのプロファイル + # + # @else + # + # @brief Get component profile + # + # Get component profile. + # + # @endif + def profile(self): + return self._Profile - ## - # @if jp - # - # @brief ߤΥ󥹥󥹿μ - # - # ݡͥȤθߤΥ󥹥󥹿롣 - # - # @param self - # - # @return ݡͥȤΥ󥹥󥹿 - # - # @else - # - # @brief Get number of component instances - # - # Get number of current component instances. - # - # @endif - def number(self): - return self._Number - + ## + # @if jp + # + # @brief 現在のインスタンス数の取得 + # + # コンポーネントの現在のインスタンス数を取得する。 + # + # @param self + # + # @return コンポーネントのインスタンス数 + # + # @else + # + # @brief Get number of component instances + # + # Get number of current component instances. + # + # @endif + def number(self): + return self._Number ## # @if jp # @class FactoryPython -# @brief FactoryPython 饹 -# -# Pythonѥݡͥȥեȥꥯ饹 +# @brief FactoryPython クラス +# +# Python用コンポーネントファクトリクラス。 # # @since 0.4.1 # @@ -201,114 +198,114 @@ def number(self): # # @endif class FactoryPython(FactoryBase): - """ - """ + """ + """ + + ## + # @if jp + # + # @brief コンストラクタ + # + # コンストラクタ。 + # 生成対象コンポーネントのプロファイル、コンポーネント生成用関数、 + # コンポーネント破棄用関数、コンポーネント生成時の命名ポリシーを引数に取り、 + # Python で実装されたコンポーネントのファクトリクラスを生成する。 + # + # @param self + # @param profile コンポーネントのプロファイル + # @param new_func コンポーネント生成用関数 + # @param delete_func コンポーネント破棄用関数 + # @param policy コンポーネント生成時の命名ポリシー(デフォルト値:None) + # + # @else + # + # @brief Constructor. + # + # Constructor. + # Create component factory class with three arguments: + # component profile, function pointer to object create function and + # object delete function. + # + # @param profile Component profile + # @param new_func Pointer to component create function + # @param delete_func Pointer to component delete function + # @param policy Pointer to component delete function + # + # @endif + def __init__(self, profile, new_func, delete_func, policy=None): + FactoryBase.__init__(self, profile) + + if policy is None: + self._policy = OpenRTM_aist.ProcessUniquePolicy() + else: + self._policy = policy + + self._New = new_func + + self._Delete = delete_func - ## - # @if jp - # - # @brief 󥹥ȥ饯 - # - # 󥹥ȥ饯 - # оݥݡͥȤΥץե롢ݡͥѴؿ - # ݡͥ˴Ѵؿݡͥ̿̾ݥꥷ˼ꡢ - # Python Ǽ줿ݡͥȤΥեȥꥯ饹롣 - # - # @param self - # @param profile ݡͥȤΥץե - # @param new_func ݡͥѴؿ - # @param delete_func ݡͥ˴Ѵؿ - # @param policy ݡͥ̿̾ݥꥷ(ǥե:None) - # - # @else - # - # @brief Constructor. - # - # Constructor. - # Create component factory class with three arguments: - # component profile, function pointer to object create function and - # object delete function. - # - # @param profile Component profile - # @param new_func Pointer to component create function - # @param delete_func Pointer to component delete function - # @param policy Pointer to component delete function - # - # @endif - def __init__(self, profile, new_func, delete_func, policy=None): - FactoryBase.__init__(self, profile) - - if policy is None: - self._policy = OpenRTM_aist.ProcessUniquePolicy() - else: - self._policy = policy + ## + # @if jp + # + # @brief コンポーネントの生成 + # + # RTComponent のインスタンスを生成する。 + # + # @param self + # @param mgr マネージャオブジェクト + # + # @return 生成したコンポーネント + # + # @else + # + # @brief Create component + # + # Create component implemented in Python. + # + # @param mgr + # + # @endif - self._New = new_func - - self._Delete = delete_func + def create(self, mgr): + try: + rtobj = self._New(mgr) + if rtobj is None: + return None + self._Number += 1 - ## - # @if jp - # - # @brief ݡͥȤ - # - # RTComponent Υ󥹥󥹤롣 - # - # @param self - # @param mgr ޥ͡㥪֥ - # - # @return ݡͥ - # - # @else - # - # @brief Create component - # - # Create component implemented in Python. - # - # @param mgr - # - # @endif - def create(self, mgr): - try: - rtobj = self._New(mgr) - if rtobj is None: - return None + rtobj.setProperties(self.profile()) - self._Number += 1 - - rtobj.setProperties(self.profile()) - - instance_name = rtobj.getTypeName() - instance_name += self._policy.onCreate(rtobj) - rtobj.setInstanceName(instance_name) + instance_name = rtobj.getTypeName() + instance_name += self._policy.onCreate(rtobj) + rtobj.setInstanceName(instance_name) - return rtobj - except: - print(OpenRTM_aist.Logger.print_exception()) - return None + return rtobj + except BaseException: + print(OpenRTM_aist.Logger.print_exception()) + return None + ## + # @if jp + # + # @brief コンポーネントの破棄 + # + # RTComponent のインスタンスを破棄する。 + # + # @param self + # @param comp 破棄対象 RTComponent + # + # @else + # + # @brief Destroy component + # + # Destroy component instance + # + # @param comp + # + # @endif - ## - # @if jp - # - # @brief ݡͥȤ˴ - # - # RTComponent Υ󥹥󥹤˴롣 - # - # @param self - # @param comp ˴о RTComponent - # - # @else - # - # @brief Destroy component - # - # Destroy component instance - # - # @param comp - # - # @endif - def destroy(self, comp): - self._Number -= 1 - self._policy.onDelete(comp) - self._Delete(comp) + def destroy(self, comp): + self._Number -= 1 + self._policy.onDelete(comp) + self._Delete(comp) diff --git a/OpenRTM_aist/FactoryInit.py b/OpenRTM_aist/FactoryInit.py index 1804b6aa..5727f062 100644 --- a/OpenRTM_aist/FactoryInit.py +++ b/OpenRTM_aist/FactoryInit.py @@ -1,5 +1,5 @@ #!/usr/bin/env python -# -*- coding: euc-jp -*- +# -*- coding: utf-8 -*- ## # @file FactoryInit.py @@ -18,6 +18,7 @@ import OpenRTM_aist from OpenRTM_aist.ext.sdo.observer import ComponentObserverConsumer + def FactoryInit(): # Buffers OpenRTM_aist.CdrRingBufferInit() @@ -51,4 +52,9 @@ def FactoryInit(): OpenRTM_aist.OutPortDSConsumerInit() OpenRTM_aist.InPortDSProviderInit() OpenRTM_aist.InPortDSConsumerInit() + OpenRTM_aist.InPortCSPProviderInit() + OpenRTM_aist.InPortCSPConsumerInit() + OpenRTM_aist.OutPortCSPProviderInit() + OpenRTM_aist.OutPortCSPConsumerInit() + OpenRTM_aist.CORBA_CdrMemoryStreamInit() ComponentObserverConsumer.ComponentObserverConsumerInit() diff --git a/OpenRTM_aist/FiniteStateMachineComponent.py b/OpenRTM_aist/FiniteStateMachineComponent.py index 4b9487ac..b7e5953f 100644 --- a/OpenRTM_aist/FiniteStateMachineComponent.py +++ b/OpenRTM_aist/FiniteStateMachineComponent.py @@ -1,5 +1,5 @@ #!/usr/bin/env python -# -*- coding: euc-jp -*- +# -*- coding: utf-8 -*- ## # @file FiniteStateMachineComponentBase.py @@ -15,74 +15,70 @@ # All rights reserved. - - import OpenRTM_aist -import OpenRTM, OpenRTM__POA - - - +import OpenRTM +import OpenRTM__POA ## # @if jp -# @brief -# FiniteStateMachineΥ١饹 -# 桼RTݡͥȤϡΥ饹ĥ롣 -# RTݡͥȤΥ١Ȥʤ륯饹} +# @brief +# FiniteStateMachineのベースクラス。 +# ユーザが新たなRTコンポーネントを作成する場合は、このクラスを拡張する。 +# 各RTコンポーネントのベースとなるクラス。} # # # @else -# @brief +# @brief # This is a class to be a base of each RT-Component. # This is a implementation class of lightweightRTComponent in Robotic # Technology Component specification # # @endif -class FiniteStateMachineComponent_impl(OpenRTM_aist.RTObject_impl, OpenRTM__POA.FiniteStateMachineComponent): - ## - # @if jp - # @brief 󥹥ȥ饯 - # - # 󥹥ȥ饯 - # - # @param self - # - # @else - # - # @brief Consructor - # - # - # @endif - def __init__(self, manager=None, orb=None, poa=None): - OpenRTM_aist.RTObject_impl.__init__(self, manager, orb, poa) - +class FiniteStateMachineComponent_impl( + OpenRTM_aist.RTObject_impl, OpenRTM__POA.FiniteStateMachineComponent): + ## + # @if jp + # @brief コンストラクタ + # + # コンストラクタ + # + # @param self + # + # @else + # + # @brief Consructor + # + # + # @endif + def __init__(self, manager=None, orb=None, poa=None): + OpenRTM_aist.RTObject_impl.__init__(self, manager, orb, poa) + ## + # @if jp + # + # @brief + # + # @return ReturnCode_t 型のリターンコード + # + # @else + # + # @brief + # + # @param ec_id + # + # @return + # + # @endif - ## - # @if jp - # - # @brief - # - # @return ReturnCode_t Υ꥿󥳡 - # - # @else - # - # @brief - # - # @param ec_id - # - # @return - # - # @endif - def on_action(self, ec_id): - self._rtcout.RTC_TRACE("on_action(%d)", ec_id) - ret = RTC.RTC_ERROR - try: - #self.preOnAction(ec_id) - ret = self.onAction(ec_id) - except: - self._rtcout.RTC_ERROR(OpenRTM_aist.Logger.print_exception()) - ret = RTC.RTC_ERROR - #self.postOnAction(ec_id, ret) - return ret + def on_action(self, ec_id): + self._rtcout.RTC_TRACE("on_action(%d)", ec_id) + ret = RTC.RTC_ERROR + try: + # self.preOnAction(ec_id) + ret = self.onAction(ec_id) + except BaseException: + self._rtcout.RTC_ERROR(OpenRTM_aist.Logger.print_exception()) + ret = RTC.RTC_ERROR + #self.postOnAction(ec_id, ret) + return ret diff --git a/OpenRTM_aist/FiniteStateMachineComponentBase.py b/OpenRTM_aist/FiniteStateMachineComponentBase.py index d957769a..9111784a 100644 --- a/OpenRTM_aist/FiniteStateMachineComponentBase.py +++ b/OpenRTM_aist/FiniteStateMachineComponentBase.py @@ -1,5 +1,5 @@ #!/usr/bin/env python -# -*- coding: euc-jp -*- +# -*- coding: utf-8 -*- ## # @file FiniteStateMachineComponentBase.py @@ -15,834 +15,796 @@ # All rights reserved. - - import OpenRTM_aist import RTC ## # @if jp -# @brief -# FiniteStateMachineΥ١饹 -# 桼RTݡͥȤϡΥ饹ĥ롣 -# RTݡͥȤΥ١Ȥʤ륯饹} +# @brief +# FiniteStateMachineのベースクラス。 +# ユーザが新たなRTコンポーネントを作成する場合は、このクラスを拡張する。 +# 各RTコンポーネントのベースとなるクラス。} # # # @else -# @brief +# @brief # This is a class to be a base of each RT-Component. # This is a implementation class of lightweightRTComponent in Robotic # Technology Component specification # # @endif class FiniteStateMachineComponentBase(OpenRTM_aist.RTObject_impl): - ## - # @if jp - # @brief 󥹥ȥ饯 - # - # 󥹥ȥ饯 - # - # @param self - # - # @else - # - # @brief Consructor - # - # - # @endif - def __init__(self, manager): - OpenRTM_aist.RTObject_impl.__init__(self, manager) - self._rtcout = self._manager.getLogbuf("FiniteStateMachineComponentBase") - self._ref = None - - ## - # @if jp - # - # @brief [CORBA interface] RTC - # - # Υڥ졼ƤӽФη̤ȤơComponentAction::on_initialize - # ХåؿƤФ롣 - # - # - # - RTC Created֤ξ߽Ԥ롣¾ξ֤ˤˤ - # ReturnCode_t::PRECONDITION_NOT_MET ֤ƤӽФϼԤ롣 - # - Υڥ졼 RTC Υߥɥ륦ƤФ뤳ȤꤷƤꡢ - # ץꥱȯԤľܤΥڥ졼Ƥ֤Ȥ - # Ƥʤ - # - # @param self - # - # @return ReturnCode_t Υ꥿󥳡 - # - # @else - # - # @brief Initialize the RTC that realizes this interface. - # - # The invocation of this operation shall result in the invocation of the - # callback ComponentAction::on_initialize. - # - # Constraints - # - An RTC may be initialized only while it is in the Created state. Any - # attempt to invoke this operation while in another state shall fail - # with ReturnCode_t::PRECONDITION_NOT_MET. - # - Application developers are not expected to call this operation - # directly; it exists for use by the RTC infrastructure. - # - # @return - # - # @endif - def initialize(self): - return OpenRTM_aist.RTObject_impl.initialize(self) - - - - ## - # @if jp - # - # @brief [CORBA interface] RTC λ - # - # Υڥ졼ƤӽФη̤Ȥ ComponentAction::on_finalize() - # ƤӽФ - # - # - # - RTC ExecutionContext ˽°Ƥ֤Ͻλʤξϡ - # ޤǽ ExecutionContextOperations::remove_component ˤäƻä - # ʤФʤʤʳξϡΥڥ졼ƤӽФ - # ʤ ReturnCode_t::PRECONDITION_NOT_ME ǼԤ롣 - # - RTC Created ֤Ǥ硢λϹԤʤ - # ξ硢Υڥ졼ƤӽФϤʤ - # ReturnCode_t::PRECONDITION_NOT_MET ǼԤ롣 - # - Υڥ졼RTCΥߥɥ륦ƤФ뤳ȤꤷƤꡢ - # ץꥱȯԤľܤΥڥ졼Ƥ֤Ȥ - # Ƥʤ - # - # @param self - # - # @return ReturnCode_t Υ꥿󥳡 - # - # @else - # - # @brief Finalize the RTC for preparing it for destruction - # - # This invocation of this operation shall result in the invocation of the - # callback ComponentAction::on_finalize. - # - # Constraints - # - An RTC may not be finalized while it is participating in any execution - # context. It must first be removed with - # ExecutionContextOperations::remove_component. Otherwise, this operation - # shall fail with ReturnCode_t::PRECONDITION_NOT_MET. - # - An RTC may not be finalized while it is in the Created state. Any - # attempt to invoke this operation while in that state shall fail with - # ReturnCode_t::PRECONDITION_NOT_MET. - # - Application developers are not expected to call this operation directly; - # it exists for use by the RTC infrastructure. - # - # @return - # - # @endif - def finalize(self): - return OpenRTM_aist.RTObject_impl.finalize(self) - - - - ## - # @if jp - # - # @brief [CORBA interface] RTC ʡǤ ExecutionContext - # ߤΥƥĤȶ˽λ - # - # RTC ʡǤ뤹٤Ƥμ¹ԥƥȤߤ롣 - # RTC ¾μ¹ԥƥȤͭ RTC °¹ԥƥ - # (i.e. ¹ԥƥȤͭ RTC Ϥʤμ¹ԥƥȤ - # ʡǤ롣)˻äƤ硢 RTC ϤΥƥȾ - # ʤФʤʤ - # RTC ¹Τɤ ExecutionContext Ǥ Active ֤ǤϤʤʤä塢 - # RTC Ȥ˴ޤޤ RTC λ롣 - # - # - # - RTC ƤʤСλ뤳ȤϤǤʤ - # Created ֤ˤ RTC exit() ƤӽФ硢 - # ReturnCode_t::PRECONDITION_NOT_MET ǼԤ롣 - # - # @param self - # - # @return ReturnCode_t Υ꥿󥳡 - # - # @else - # - # @brief Stop the RTC's execution context(s) and finalize it along with its - # contents. - # - # Any execution contexts for which the RTC is the owner shall be stopped. - # If the RTC participates in any execution contexts belonging to another - # RTC that contains it, directly or indirectly (i.e. the containing RTC - # is the owner of the ExecutionContext), it shall be deactivated in those - # contexts. - # After the RTC is no longer Active in any Running execution context, it - # and any RTCs contained transitively within it shall be finalized. - # - # Constraints - # - An RTC cannot be exited if it has not yet been initialized. Any - # attempt to exit an RTC that is in the Created state shall fail with - # ReturnCode_t::PRECONDITION_NOT_MET. - # - # @return - # - # @endif - def exit(self): - return OpenRTM_aist.RTObject_impl.exit(self) - - - - ## - # @if jp - # - # @brief [CORBA interface] RTC Alive ֤Ǥ뤫ɤǧ롣 - # - # RTC ꤷ ExecutionContext Ф Alive֤Ǥ뤫ɤǧ롣 - # RTC ξ֤ Active Ǥ뤫Inactive Ǥ뤫Error Ǥ뤫ϼ¹ - # ExecutionContext ˰¸롣ʤ ExecutionContext ФƤ - # Active ֤ǤäƤ⡢¾ ExecutionContext ФƤ Inactive ֤ - # ʤ⤢ꤨ롣äơΥڥ졼ϻꤵ줿 - # ExecutionContext 䤤碌ơ RTC ξ֤ ActiveInactive - # Error ξˤ Alive ֤Ȥ֤ - # - # @param self - # - # @param exec_context о ExecutionContext ϥɥ - # - # @return Alive ֳǧ - # - # @else - # - # @brief Confirm whether RTC is an Alive state or NOT. - # - # A component is alive or not regardless of the execution context from - # which it is observed. However, whether or not it is Active, Inactive, - # or in Error is dependent on the execution context(s) in which it is - # running. That is, it may be Active in one context but Inactive in - # another. Therefore, this operation shall report whether this RTC is - # either Active, Inactive or in Error; which of those states a component - # is in with respect to a particular context may be queried from the - # context itself. - # - # @return Result of Alive state confirmation - # - # @endif - # virtual CORBA::Boolean is_alive(ExecutionContext_ptr exec_context) - def is_alive(self, exec_context): - return OpenRTM_aist.RTObject_impl.is_alive(self, exec_context) - - - - - ## - # @if jp - # @brief [CORBA interface] ͭ ExecutionContextList - # - # RTC ͭ ExecutionContext ΥꥹȤ롣 - # - # @return ExecutionContext ꥹ - # - # @else - # @brief [CORBA interface] Get ExecutionContextList. - # - # This operation returns a list of all execution contexts owned by this - # RTC. - # - # @return ExecutionContext List - # - # @endif - # virtual ExecutionContextList* get_owned_contexts() - def get_owned_contexts(self): - return OpenRTM_aist.RTObject_impl.get_owned_contexts(self) - - - ## - # @if jp - # @brief [CORBA interface] ExecutionContext - # - # ꤷϥɥ ExecutionContext 롣 - # ϥɥ뤫 ExecutionContext ؤΥޥåԥ󥰤ϡ RTC 󥹥󥹤 - # ͭǤ롣ϥɥϤ RTC attach_context ݤ˼Ǥ롣 - # - # @param self - # @param ec_id о ExecutionContext ϥɥ - # - # @return ExecutionContext - # - # @else - # @brief [CORBA interface] Get ExecutionContext. - # - # Obtain a reference to the execution context represented by the given - # handle. - # The mapping from handle to context is specific to a particular RTC - # instance. The given handle must have been obtained by a previous call to - # attach_context on this RTC. - # - # @param ec_id ExecutionContext handle - # - # @return ExecutionContext - # - # @endif - # virtual ExecutionContext_ptr get_context(UniqueId exec_handle) - def get_owned_contexts(self): - return OpenRTM_aist.RTObject_impl.get_owned_contexts(self) - - - - ## - # @if jp - # @brief [CORBA interface] ExecutionContext - # - # ꤷϥɥ ExecutionContext 롣 - # ϥɥ뤫 ExecutionContext ؤΥޥåԥ󥰤ϡ RTC 󥹥󥹤 - # ͭǤ롣ϥɥϤ RTC attach_context ݤ˼Ǥ롣 - # - # @param self - # @param ec_id о ExecutionContext ϥɥ - # - # @return ExecutionContext - # - # @else - # @brief [CORBA interface] Get ExecutionContext. - # - # Obtain a reference to the execution context represented by the given - # handle. - # The mapping from handle to context is specific to a particular RTC - # instance. The given handle must have been obtained by a previous call to - # attach_context on this RTC. - # - # @param ec_id ExecutionContext handle - # - # @return ExecutionContext - # - # @endif - # virtual ExecutionContext_ptr get_context(UniqueId exec_handle) - def get_context(self, ec_id): - return OpenRTM_aist.RTObject_impl.get_context(self, ec_id) - - - - - ## - # @if jp - # @brief [CORBA interface] äƤ ExecutionContextList - # - # RTC äƤ ExecutionContext ΥꥹȤ롣 - # - # @return ExecutionContext ꥹ - # - # @else - # @brief [CORBA interface] Get participating ExecutionContextList. - # - # This operation returns a list of all execution contexts in - # which this RTC participates. - # - # @return ExecutionContext List - # - # @endif - # virtual ExecutionContextList* get_participating_contexts() - def get_participating_contexts(self): - return OpenRTM_aist.RTObject_impl.get_participating_contexts(self) - - - - ## - # @if jp - # @brief [CORBA interface] ExecutionContext Υϥɥ֤ - # - # @param ExecutionContext ¹ԥƥ - # - # @return ExecutionContextHandle - # - # Ϳ줿¹ԥƥȤ˴Ϣդ줿ϥɥ֤ - # - # @else - # @brief [CORBA interface] Return a handle of a ExecutionContext - # - # @param ExecutionContext - # - # @return ExecutionContextHandle - # - # This operation returns a handle that is associated with the given - # execution context. - # - # @endif - # - # virtual ExecutionContextHandle_t - # get_context_handle(ExecutionContext_ptr cxt) - def get_context_handle(self, cxt): - return OpenRTM_aist.RTObject_impl.get_context_handle(self, cxt) - - - - ## - # @if jp - # - # @brief [RTObject CORBA interface] ݡͥȥץե - # - # ݡͥȤΥץե֤ - # - # @param self - # - # @return ݡͥȥץե - # - # @else - # - # @brief [RTObject CORBA interface] Get RTC's profile - # - # This operation returns the ComponentProfile of the RTC - # - # @return ComponentProfile - # - # @endif - # virtual ComponentProfile* get_component_profile() - def get_component_profile(self): - return OpenRTM_aist.RTObject_impl.get_component_profile(self) - - - - - ## - # @if jp - # - # @brief [RTObject CORBA interface] ݡȤ - # - # ݡͥȤͭݡȤλȤ֤ - # - # @param self - # - # @return ݡȥꥹ - # - # @else - # - # @brief [RTObject CORBA interface] Get Ports - # - # This operation returns a list of the RTCs ports. - # - # @return PortList - # - # @endif - # virtual PortServiceList* get_ports() - def get_ports(self): - return OpenRTM_aist.RTObject_impl.get_ports(self) - - - - ## - # @if jp - # @brief [CORBA interface] ExecutionContextattach - # - # ꤷ ExecutionContext ˤ RTC °롣 RTC ȴϢ - # ExecutionContext Υϥɥ֤ - # Υڥ졼ϡExecutionContextOperations::add_component ƤФ줿 - # ݤ˸ƤӽФ롣֤줿ϥɥ¾Υ饤ȤǻѤ뤳Ȥ - # Ƥʤ - # - # @param self - # @param exec_context ° ExecutionContext - # - # @return ExecutionContext ϥɥ - # - # @else - # @brief [CORBA interface] Attach ExecutionContext. - # - # Inform this RTC that it is participating in the given execution context. - # Return a handle that represents the association of this RTC with the - # context. - # This operation is intended to be invoked by - # ExecutionContextOperations::add_component. It is not intended for use by - # other clients. - # - # @param exec_context Prticipating ExecutionContext - # - # @return ExecutionContext Handle - # - # @endif - # UniqueId attach_context(ExecutionContext_ptr exec_context) - def attach_context(self, exec_context): - return OpenRTM_aist.RTObject_impl.attach_context(self, exec_context) - - - - - ## - # @if jp - # @brief [CORBA interface] ExecutionContextdetach - # - # ꤷ ExecutionContext 餳 RTC ν°롣 - # Υڥ졼ϡExecutionContextOperations::remove_component Ƥ - # 줿ݤ˸ƤӽФ롣֤줿ϥɥ¾Υ饤ȤǻѤ뤳Ȥ - # ꤷƤʤ - # - # - # - ꤵ줿 ExecutionContext RTC Ǥ˽°Ƥʤˤϡ - # ReturnCode_t::PRECONDITION_NOT_MET ֤롣 - # - ꤵ줿 ExecutionContext ˤФ RTC Active ֤Ǥ - # ˤϡ ReturnCode_t::PRECONDITION_NOT_MET ֤롣 - # - # @param self - # @param ec_id о ExecutionContextϥɥ - # - # @return ReturnCode_t Υ꥿󥳡 - # - # @else - # @brief [CORBA interface] Attach ExecutionContext. - # - # Inform this RTC that it is no longer participating in the given execution - # context. - # This operation is intended to be invoked by - # ExecutionContextOperations::remove_component. It is not intended for use - # by other clients. - # Constraints - # - This operation may not be invoked if this RTC is not already - # participating in the execution context. Such a call shall fail with - # ReturnCode_t::PRECONDITION_NOT_MET. - # - This operation may not be invoked if this RTC is Active in the indicated - # execution context. Otherwise, it shall fail with - # ReturnCode_t::PRECONDITION_NOT_MET. - # - # @param ec_id Dettaching ExecutionContext Handle - # - # @return - # - # @endif - # ReturnCode_t detach_context(UniqueId exec_handle) - def detach_context(self, ec_id): - return OpenRTM_aist.RTObject_impl.detach_context(self, ec_id) - - - - - ## - # @if jp - # - # @brief [ComponentAction CORBA interface] RTC ν - # - # RTC 졢Alive ֤ܤ롣 - # RTC ͭνϤǼ¹Ԥ롣 - # Υڥ졼ƤӽФη̤Ȥ onInitialize() Хåؿ - # ƤӽФ롣 - # - # @param self - # - # @return ReturnCode_t Υ꥿󥳡 - # - # @else - # - # @brief [ComponentAction CORBA interface] Initialize RTC - # - # The RTC has been initialized and entered the Alive state. - # Any RTC-specific initialization logic should be performed here. - # - # @return - # - # @endif - def on_initialize(self): - return OpenRTM_aist.RTObject_impl.on_initialize(self) - - - - - ## - # @if jp - # - # @brief [ComponentAction CORBA interface] RTC νλ - # - # RTC ˴롣 - # RTC ͭνλϤǼ¹Ԥ롣 - # Υڥ졼ƤӽФη̤Ȥ onFinalize() Хåؿ - # ƤӽФ롣 - # - # @param self - # - # @return ReturnCode_t Υ꥿󥳡 - # - # @else - # - # @brief [ComponentAction CORBA interface] Finalize RTC - # - # The RTC is being destroyed. - # Any final RTC-specific tear-down logic should be performed here. - # - # @return - # - # @endif - def on_finalize(self): - return OpenRTM_aist.RTObject_impl.on_finalize(self) - - - - - - ## - # @if jp - # - # @brief [ComponentAction CORBA interface] RTC γ - # - # RTC ° ExecutionContext Stopped ֤ Running ֤ - # ˸ƤӽФ롣 - # Υڥ졼ƤӽФη̤Ȥ onStartup() Хåؿ - # ƤӽФ롣 - # - # @param self - # @param ec_id ܤ ExecutionContext ID - # - # @return ReturnCode_t Υ꥿󥳡 - # - # @else - # - # @brief [ComponentAction CORBA interface] StartUp RTC - # - # The given execution context, in which the RTC is participating, has - # transitioned from Stopped to Running. - # - # @param ec_id - # - # @return - # - # @endif - def on_startup(self, ec_id): - return OpenRTM_aist.RTObject_impl.on_startup(self, ec_id) - - - - ## - # @if jp - # - # @brief [ComponentAction CORBA interface] RTC - # - # RTC ° ExecutionContext Running ֤ Stopped ֤ - # ˸ƤӽФ롣 - # Υڥ졼ƤӽФη̤Ȥ onShutdown() Хåؿ - # ƤӽФ롣 - # - # @param self - # @param ec_id ܤ ExecutionContext ID - # - # @return ReturnCode_t Υ꥿󥳡 - # - # @else - # - # @brief [ComponentAction CORBA interface] ShutDown RTC - # - # The given execution context, in which the RTC is participating, has - # transitioned from Running to Stopped. - # - # @param ec_id - # - # @return - # - # @endif - def on_shutdown(self, ec_id): - return OpenRTM_aist.RTObject_impl.on_shutdown(self, ec_id) - - - - - ## - # @if jp - # - # @brief [ComponentAction CORBA interface] RTC γ - # - # ° ExecutionContext RTC 줿ݤ˸ƤӽФ롣 - # Υڥ졼ƤӽФη̤Ȥ onActivated() Хåؿ - # ƤӽФ롣 - # - # @param self - # @param ec_id ExecutionContext ID - # - # @return ReturnCode_t Υ꥿󥳡 - # - # @else - # - # @brief [ComponentAction CORBA interface] Activate RTC - # - # The RTC has been activated in the given execution context. - # - # @param ec_id - # - # @return - # - # @endif - def on_activated(self, ec_id): - return OpenRTM_aist.RTObject_impl.on_activated(self, ec_id) - - - - - - ## - # @if jp - # - # @brief [ComponentAction CORBA interface] RTC - # - # ° ExecutionContext RTC 줿ݤ˸ƤӽФ롣 - # Υڥ졼ƤӽФη̤Ȥ onDeactivated() Хåؿ - # ƤӽФ롣 - # - # @param self - # @param ec_id ExecutionContext ID - # - # @return ReturnCode_t Υ꥿󥳡 - # - # @else - # - # @brief [ComponentAction CORBA interface] Deactivate RTC - # - # The RTC has been deactivated in the given execution context. - # - # @param ec_id - # - # @return - # - # @endif - def on_deactivated(self, ec_id): - return OpenRTM_aist.RTObject_impl.on_deactivated(self, ec_id) - - - - - ## - # @if jp - # - # @brief [ComponentAction CORBA interface] RTC Υ顼 - # - # RTC 顼֤ˤݤ˸ƤӽФ롣 - # RTC 顼֤ξˡоݤȤʤ ExecutionContext ExecutionKind - # ߥ󥰤ǸƤӽФ롣㤨С - # - ExecutionKind PERIODIC ξ硢ܥڥ졼 - # DataFlowComponentAction::on_execute on_state_update ؤˡ - # ꤵ줿֡ꤵ줿ǸƤӽФ롣 - # - ExecutionKind EVENT_DRIVEN ξ硢ܥڥ졼 - # FsmParticipantAction::on_action ƤФ줿ݤˡؤ˸ƤӽФ롣 - # Υڥ졼ƤӽФη̤Ȥ onError() ХåؿƤӽ - # 롣 - # - # @param self - # @param ec_id о ExecutionContext ID - # - # @return ReturnCode_t Υ꥿󥳡 - # - # @else - # - # @brief [ComponentAction CORBA interface] Error Processing of RTC - # - # The RTC remains in the Error state. - # If the RTC is in the Error state relative to some execution context when - # it would otherwise be invoked from that context (according to the - # contexts ExecutionKind), this callback shall be invoked instead. - # For example, - # - If the ExecutionKind is PERIODIC, this operation shall be invoked in - # sorted order at the rate of the context instead of - # DataFlowComponentAction::on_execute and on_state_update. - # - If the ExecutionKind is EVENT_DRIVEN, this operation shall be invoked - # whenever FsmParticipantAction::on_action would otherwise have been - # invoked. - # - # @param ec_id - # - # @return - # - # @endif - def on_error(self, ec_id): - return OpenRTM_aist.RTObject_impl.on_error(self, ec_id) - - - - - ## - # @if jp - # - # @brief [ComponentAction CORBA interface] RTC Υ顼֤ؤ - # - # RTC ° ExecutionContext Active ֤ Error ֤ܤ - # ˸ƤӽФ롣 - # Υڥ졼 RTC Error ֤ܤݤ˰٤ƤӽФ롣 - # Υڥ졼ƤӽФη̤Ȥ onAborting() Хåؿ - # ƤӽФ롣 - # - # @param self - # @param ec_id ܤ ExecutionContext ID - # - # @return ReturnCode_t Υ꥿󥳡 - # - # @else - # - # @brief [ComponentAction CORBA interface] Transition Error State - # - # The RTC is transitioning from the Active state to the Error state in some - # execution context. - # This callback is invoked only a single time for time that the RTC - # transitions into the Error state from another state. This behavior is in - # contrast to that of on_error. - # - # @param ec_id - # - # @return - # - # @endif - def on_aborting(self, ec_id): - return OpenRTM_aist.RTObject_impl.on_aborting(self, ec_id) - - - - - - ## - # @if jp - # - # @brief [ComponentAction CORBA interface] RTC Υꥻå - # - # Error ֤ˤ RTC ΥꥫХ¹ԤInactive ֤ - # ˸ƤӽФ롣 - # RTC ΥꥫХ Inactive ֤뤬ʳ - # ˤ Error ֤αޤ롣 - # Υڥ졼ƤӽФη̤Ȥ onReset() ХåؿƤ - # Ф롣 - # - # @param self - # @param ec_id ꥻåо ExecutionContext ID - # - # @return ReturnCode_t Υ꥿󥳡 - # - # @else - # - # @brief [ComponentAction CORBA interface] Resetting RTC - # - # The RTC is in the Error state. An attempt is being made to recover it such - # that it can return to the Inactive state. - # If the RTC was successfully recovered and can safely return to the - # Inactive state, this method shall complete with ReturnCode_t::OK. Any - # other result shall indicate that the RTC should remain in the Error state. - # - # @param ec_id - # - # @return - # - # @endif - def on_reset(self, ec_id): - return OpenRTM_aist.RTObject_impl.on_reset(self, ec_id) - - - - - ## - # @if jp - # @brief - # - # - # - # @param self - # - # @else - # - # @brief Consructor - # - # - # @endif - def on_action(self, ec_id): - return RTC.RTC_OK \ No newline at end of file + ## + # @if jp + # @brief コンストラクタ + # + # コンストラクタ + # + # @param self + # + # @else + # + # @brief Consructor + # + # + # @endif + def __init__(self, manager): + OpenRTM_aist.RTObject_impl.__init__(self, manager) + self._rtcout = self._manager.getLogbuf( + "FiniteStateMachineComponentBase") + self._ref = None + + ## + # @if jp + # + # @brief [CORBA interface] RTCを初期化する + # + # このオペレーション呼び出しの結果として、ComponentAction::on_initialize + # コールバック関数が呼ばれる。 + # + # 制約 + # - RTC は Created状態の場合み初期化が行われる。他の状態にいる場合には + # ReturnCode_t::PRECONDITION_NOT_MET が返され呼び出しは失敗する。 + # - このオペレーションは RTC のミドルウエアから呼ばれることを想定しており、 + # アプリケーション開発者は直接このオペレーションを呼ぶことは想定 + # されていない。 + # + # @param self + # + # @return ReturnCode_t 型のリターンコード + # + # @else + # + # @brief Initialize the RTC that realizes this interface. + # + # The invocation of this operation shall result in the invocation of the + # callback ComponentAction::on_initialize. + # + # Constraints + # - An RTC may be initialized only while it is in the Created state. Any + # attempt to invoke this operation while in another state shall fail + # with ReturnCode_t::PRECONDITION_NOT_MET. + # - Application developers are not expected to call this operation + # directly; it exists for use by the RTC infrastructure. + # + # @return + # + # @endif + def initialize(self): + return OpenRTM_aist.RTObject_impl.initialize(self) + + ## + # @if jp + # + # @brief [CORBA interface] RTC を終了する + # + # このオペレーション呼び出しの結果として ComponentAction::on_finalize() + # を呼び出す。 + # + # 制約 + # - RTC が ExecutionContext に所属している間は終了されない。この場合は、 + # まず最初に ExecutionContextOperations::remove_component によって参加を + # 解除しなければならない。これ以外の場合は、このオペレーション呼び出しは + # いかなる場合も ReturnCode_t::PRECONDITION_NOT_ME で失敗する。 + # - RTC が Created 状態である場合、終了処理は行われない。 + # この場合、このオペレーション呼び出しはいかなる場合も + # ReturnCode_t::PRECONDITION_NOT_MET で失敗する。 + # - このオペレーションはRTCのミドルウエアから呼ばれることを想定しており、 + # アプリケーション開発者は直接このオペレーションを呼ぶことは想定 + # されていない。 + # + # @param self + # + # @return ReturnCode_t 型のリターンコード + # + # @else + # + # @brief Finalize the RTC for preparing it for destruction + # + # This invocation of this operation shall result in the invocation of the + # callback ComponentAction::on_finalize. + # + # Constraints + # - An RTC may not be finalized while it is participating in any execution + # context. It must first be removed with + # ExecutionContextOperations::remove_component. Otherwise, this operation + # shall fail with ReturnCode_t::PRECONDITION_NOT_MET. + # - An RTC may not be finalized while it is in the Created state. Any + # attempt to invoke this operation while in that state shall fail with + # ReturnCode_t::PRECONDITION_NOT_MET. + # - Application developers are not expected to call this operation directly; + # it exists for use by the RTC infrastructure. + # + # @return + # + # @endif + + def finalize(self): + return OpenRTM_aist.RTObject_impl.finalize(self) + + ## + # @if jp + # + # @brief [CORBA interface] RTC がオーナーである ExecutionContext を + # 停止させ、そのコンテンツと共に終了させる + # + # この RTC がオーナーであるすべての実行コンテキストを停止する。 + # この RTC が他の実行コンテキストを所有する RTC に属する実行コンテキスト + # (i.e. 実行コンテキストを所有する RTC はすなわちその実行コンテキストの + # オーナーである。)に参加している場合、当該 RTC はそれらのコンテキスト上 + # で非活性化されなければならない。 + # RTC が実行中のどの ExecutionContext でも Active 状態ではなくなった後、 + # この RTC とこれに含まれる RTC が終了する。 + # + # 制約 + # - RTC が初期化されていなければ、終了させることはできない。 + # Created 状態にある RTC に exit() を呼び出した場合、 + # ReturnCode_t::PRECONDITION_NOT_MET で失敗する。 + # + # @param self + # + # @return ReturnCode_t 型のリターンコード + # + # @else + # + # @brief Stop the RTC's execution context(s) and finalize it along with its + # contents. + # + # Any execution contexts for which the RTC is the owner shall be stopped. + # If the RTC participates in any execution contexts belonging to another + # RTC that contains it, directly or indirectly (i.e. the containing RTC + # is the owner of the ExecutionContext), it shall be deactivated in those + # contexts. + # After the RTC is no longer Active in any Running execution context, it + # and any RTCs contained transitively within it shall be finalized. + # + # Constraints + # - An RTC cannot be exited if it has not yet been initialized. Any + # attempt to exit an RTC that is in the Created state shall fail with + # ReturnCode_t::PRECONDITION_NOT_MET. + # + # @return + # + # @endif + + def exit(self): + return OpenRTM_aist.RTObject_impl.exit(self) + + ## + # @if jp + # + # @brief [CORBA interface] RTC が Alive 状態であるかどうか確認する。 + # + # RTC が指定した ExecutionContext に対して Alive状態であるかどうか確認する。 + # RTC の状態が Active であるか、Inactive であるか、Error であるかは実行中の + # ExecutionContext に依存する。すなわち、ある ExecutionContext に対しては + # Active 状態であっても、他の ExecutionContext に対しては Inactive 状態と + # なる場合もありえる。従って、このオペレーションは指定された + # ExecutionContext に問い合わせて、この RTC の状態が Active、Inactive、 + # Error の場合には Alive 状態として返す。 + # + # @param self + # + # @param exec_context 取得対象 ExecutionContext ハンドル + # + # @return Alive 状態確認結果 + # + # @else + # + # @brief Confirm whether RTC is an Alive state or NOT. + # + # A component is alive or not regardless of the execution context from + # which it is observed. However, whether or not it is Active, Inactive, + # or in Error is dependent on the execution context(s) in which it is + # running. That is, it may be Active in one context but Inactive in + # another. Therefore, this operation shall report whether this RTC is + # either Active, Inactive or in Error; which of those states a component + # is in with respect to a particular context may be queried from the + # context itself. + # + # @return Result of Alive state confirmation + # + # @endif + # virtual CORBA::Boolean is_alive(ExecutionContext_ptr exec_context) + + def is_alive(self, exec_context): + return OpenRTM_aist.RTObject_impl.is_alive(self, exec_context) + + ## + # @if jp + # @brief [CORBA interface] 所有する ExecutionContextListを 取得する + # + # この RTC が所有する ExecutionContext のリストを取得する。 + # + # @return ExecutionContext リスト + # + # @else + # @brief [CORBA interface] Get ExecutionContextList. + # + # This operation returns a list of all execution contexts owned by this + # RTC. + # + # @return ExecutionContext List + # + # @endif + # virtual ExecutionContextList* get_owned_contexts() + + def get_owned_contexts(self): + return OpenRTM_aist.RTObject_impl.get_owned_contexts(self) + + ## + # @if jp + # @brief [CORBA interface] ExecutionContextを取得する + # + # 指定したハンドルの ExecutionContext を取得する。 + # ハンドルから ExecutionContext へのマッピングは、特定の RTC インスタンスに + # 固有である。ハンドルはこの RTC を attach_context した際に取得できる。 + # + # @param self + # @param ec_id 取得対象 ExecutionContext ハンドル + # + # @return ExecutionContext + # + # @else + # @brief [CORBA interface] Get ExecutionContext. + # + # Obtain a reference to the execution context represented by the given + # handle. + # The mapping from handle to context is specific to a particular RTC + # instance. The given handle must have been obtained by a previous call to + # attach_context on this RTC. + # + # @param ec_id ExecutionContext handle + # + # @return ExecutionContext + # + # @endif + # virtual ExecutionContext_ptr get_context(UniqueId exec_handle) + + def get_owned_contexts(self): + return OpenRTM_aist.RTObject_impl.get_owned_contexts(self) + + ## + # @if jp + # @brief [CORBA interface] ExecutionContextを取得する + # + # 指定したハンドルの ExecutionContext を取得する。 + # ハンドルから ExecutionContext へのマッピングは、特定の RTC インスタンスに + # 固有である。ハンドルはこの RTC を attach_context した際に取得できる。 + # + # @param self + # @param ec_id 取得対象 ExecutionContext ハンドル + # + # @return ExecutionContext + # + # @else + # @brief [CORBA interface] Get ExecutionContext. + # + # Obtain a reference to the execution context represented by the given + # handle. + # The mapping from handle to context is specific to a particular RTC + # instance. The given handle must have been obtained by a previous call to + # attach_context on this RTC. + # + # @param ec_id ExecutionContext handle + # + # @return ExecutionContext + # + # @endif + # virtual ExecutionContext_ptr get_context(UniqueId exec_handle) + + def get_context(self, ec_id): + return OpenRTM_aist.RTObject_impl.get_context(self, ec_id) + + ## + # @if jp + # @brief [CORBA interface] 参加している ExecutionContextList を取得する + # + # この RTC が参加している ExecutionContext のリストを取得する。 + # + # @return ExecutionContext リスト + # + # @else + # @brief [CORBA interface] Get participating ExecutionContextList. + # + # This operation returns a list of all execution contexts in + # which this RTC participates. + # + # @return ExecutionContext List + # + # @endif + # virtual ExecutionContextList* get_participating_contexts() + + def get_participating_contexts(self): + return OpenRTM_aist.RTObject_impl.get_participating_contexts(self) + + ## + # @if jp + # @brief [CORBA interface] ExecutionContext のハンドルを返す + # + # @param ExecutionContext 実行コンテキスト + # + # @return ExecutionContextHandle + # + # 与えられた実行コンテキストに関連付けられたハンドルを返す。 + # + # @else + # @brief [CORBA interface] Return a handle of a ExecutionContext + # + # @param ExecutionContext + # + # @return ExecutionContextHandle + # + # This operation returns a handle that is associated with the given + # execution context. + # + # @endif + # + # virtual ExecutionContextHandle_t + # get_context_handle(ExecutionContext_ptr cxt) + + def get_context_handle(self, cxt): + return OpenRTM_aist.RTObject_impl.get_context_handle(self, cxt) + + ## + # @if jp + # + # @brief [RTObject CORBA interface] コンポーネントプロファイルを取得する + # + # 当該コンポーネントのプロファイル情報を返す。 + # + # @param self + # + # @return コンポーネントプロファイル + # + # @else + # + # @brief [RTObject CORBA interface] Get RTC's profile + # + # This operation returns the ComponentProfile of the RTC + # + # @return ComponentProfile + # + # @endif + # virtual ComponentProfile* get_component_profile() + + def get_component_profile(self): + return OpenRTM_aist.RTObject_impl.get_component_profile(self) + + ## + # @if jp + # + # @brief [RTObject CORBA interface] ポートを取得する + # + # 当該コンポーネントが保有するポートの参照を返す。 + # + # @param self + # + # @return ポートリスト + # + # @else + # + # @brief [RTObject CORBA interface] Get Ports + # + # This operation returns a list of the RTCs ports. + # + # @return PortList + # + # @endif + # virtual PortServiceList* get_ports() + + def get_ports(self): + return OpenRTM_aist.RTObject_impl.get_ports(self) + + ## + # @if jp + # @brief [CORBA interface] ExecutionContextをattachする + # + # 指定した ExecutionContext にこの RTC を所属させる。この RTC と関連する + # ExecutionContext のハンドルを返す。 + # このオペレーションは、ExecutionContextOperations::add_component が呼ばれた + # 際に呼び出される。返されたハンドルは他のクライアントで使用することを想定 + # していない。 + # + # @param self + # @param exec_context 所属先 ExecutionContext + # + # @return ExecutionContext ハンドル + # + # @else + # @brief [CORBA interface] Attach ExecutionContext. + # + # Inform this RTC that it is participating in the given execution context. + # Return a handle that represents the association of this RTC with the + # context. + # This operation is intended to be invoked by + # ExecutionContextOperations::add_component. It is not intended for use by + # other clients. + # + # @param exec_context Prticipating ExecutionContext + # + # @return ExecutionContext Handle + # + # @endif + # UniqueId attach_context(ExecutionContext_ptr exec_context) + + def attach_context(self, exec_context): + return OpenRTM_aist.RTObject_impl.attach_context(self, exec_context) + + ## + # @if jp + # @brief [CORBA interface] ExecutionContextをdetachする + # + # 指定した ExecutionContext からこの RTC の所属を解除する。 + # このオペレーションは、ExecutionContextOperations::remove_component が呼ば + # れた際に呼び出される。返されたハンドルは他のクライアントで使用することを + # 想定していない。 + # + # 制約 + # - 指定された ExecutionContext に RTC がすでに所属していない場合には、 + # ReturnCode_t::PRECONDITION_NOT_MET が返される。 + # - 指定された ExecutionContext にたしいて対して RTC がActive 状態である場 + # 合には、 ReturnCode_t::PRECONDITION_NOT_MET が返される。 + # + # @param self + # @param ec_id 解除対象 ExecutionContextハンドル + # + # @return ReturnCode_t 型のリターンコード + # + # @else + # @brief [CORBA interface] Attach ExecutionContext. + # + # Inform this RTC that it is no longer participating in the given execution + # context. + # This operation is intended to be invoked by + # ExecutionContextOperations::remove_component. It is not intended for use + # by other clients. + # Constraints + # - This operation may not be invoked if this RTC is not already + # participating in the execution context. Such a call shall fail with + # ReturnCode_t::PRECONDITION_NOT_MET. + # - This operation may not be invoked if this RTC is Active in the indicated + # execution context. Otherwise, it shall fail with + # ReturnCode_t::PRECONDITION_NOT_MET. + # + # @param ec_id Dettaching ExecutionContext Handle + # + # @return + # + # @endif + # ReturnCode_t detach_context(UniqueId exec_handle) + + def detach_context(self, ec_id): + return OpenRTM_aist.RTObject_impl.detach_context(self, ec_id) + + ## + # @if jp + # + # @brief [ComponentAction CORBA interface] RTC の初期化 + # + # RTC が初期化され、Alive 状態に遷移する。 + # RTC 固有の初期化処理はここで実行する。 + # このオペレーション呼び出しの結果として onInitialize() コールバック関数が + # 呼び出される。 + # + # @param self + # + # @return ReturnCode_t 型のリターンコード + # + # @else + # + # @brief [ComponentAction CORBA interface] Initialize RTC + # + # The RTC has been initialized and entered the Alive state. + # Any RTC-specific initialization logic should be performed here. + # + # @return + # + # @endif + + def on_initialize(self): + return OpenRTM_aist.RTObject_impl.on_initialize(self) + + ## + # @if jp + # + # @brief [ComponentAction CORBA interface] RTC の終了 + # + # RTC が破棄される。 + # RTC 固有の終了処理はここで実行する。 + # このオペレーション呼び出しの結果として onFinalize() コールバック関数が + # 呼び出される。 + # + # @param self + # + # @return ReturnCode_t 型のリターンコード + # + # @else + # + # @brief [ComponentAction CORBA interface] Finalize RTC + # + # The RTC is being destroyed. + # Any final RTC-specific tear-down logic should be performed here. + # + # @return + # + # @endif + + def on_finalize(self): + return OpenRTM_aist.RTObject_impl.on_finalize(self) + + ## + # @if jp + # + # @brief [ComponentAction CORBA interface] RTC の開始 + # + # RTC が所属する ExecutionContext が Stopped 状態から Running 状態へ遷移 + # した場合に呼び出される。 + # このオペレーション呼び出しの結果として onStartup() コールバック関数が + # 呼び出される。 + # + # @param self + # @param ec_id 状態遷移した ExecutionContext の ID + # + # @return ReturnCode_t 型のリターンコード + # + # @else + # + # @brief [ComponentAction CORBA interface] StartUp RTC + # + # The given execution context, in which the RTC is participating, has + # transitioned from Stopped to Running. + # + # @param ec_id + # + # @return + # + # @endif + + def on_startup(self, ec_id): + return OpenRTM_aist.RTObject_impl.on_startup(self, ec_id) + + ## + # @if jp + # + # @brief [ComponentAction CORBA interface] RTC の停止 + # + # RTC が所属する ExecutionContext が Running 状態から Stopped 状態へ遷移 + # した場合に呼び出される。 + # このオペレーション呼び出しの結果として onShutdown() コールバック関数が + # 呼び出される。 + # + # @param self + # @param ec_id 状態遷移した ExecutionContext の ID + # + # @return ReturnCode_t 型のリターンコード + # + # @else + # + # @brief [ComponentAction CORBA interface] ShutDown RTC + # + # The given execution context, in which the RTC is participating, has + # transitioned from Running to Stopped. + # + # @param ec_id + # + # @return + # + # @endif + + def on_shutdown(self, ec_id): + return OpenRTM_aist.RTObject_impl.on_shutdown(self, ec_id) + + ## + # @if jp + # + # @brief [ComponentAction CORBA interface] RTC の活性化 + # + # 所属する ExecutionContext から RTC が活性化された際に呼び出される。 + # このオペレーション呼び出しの結果として onActivated() コールバック関数が + # 呼び出される。 + # + # @param self + # @param ec_id 活性化 ExecutionContext の ID + # + # @return ReturnCode_t 型のリターンコード + # + # @else + # + # @brief [ComponentAction CORBA interface] Activate RTC + # + # The RTC has been activated in the given execution context. + # + # @param ec_id + # + # @return + # + # @endif + + def on_activated(self, ec_id): + return OpenRTM_aist.RTObject_impl.on_activated(self, ec_id) + + ## + # @if jp + # + # @brief [ComponentAction CORBA interface] RTC の非活性化 + # + # 所属する ExecutionContext から RTC が非活性化された際に呼び出される。 + # このオペレーション呼び出しの結果として onDeactivated() コールバック関数が + # 呼び出される。 + # + # @param self + # @param ec_id 非活性化 ExecutionContext の ID + # + # @return ReturnCode_t 型のリターンコード + # + # @else + # + # @brief [ComponentAction CORBA interface] Deactivate RTC + # + # The RTC has been deactivated in the given execution context. + # + # @param ec_id + # + # @return + # + # @endif + + def on_deactivated(self, ec_id): + return OpenRTM_aist.RTObject_impl.on_deactivated(self, ec_id) + + ## + # @if jp + # + # @brief [ComponentAction CORBA interface] RTC のエラー処理 + # + # RTC がエラー状態にいる際に呼び出される。 + # RTC がエラー状態の場合に、対象となる ExecutionContext のExecutionKind に + # 応じたタイミングで呼び出される。例えば、 + # - ExecutionKind が PERIODIC の場合、本オペレーションは + # DataFlowComponentAction::on_execute と on_state_update の替わりに、 + # 設定された順番、設定された周期で呼び出される。 + # - ExecutionKind が EVENT_DRIVEN の場合、本オペレーションは + # FsmParticipantAction::on_action が呼ばれた際に、替わりに呼び出される。 + # このオペレーション呼び出しの結果として onError() コールバック関数が呼び出 + # される。 + # + # @param self + # @param ec_id 対象 ExecutionContext の ID + # + # @return ReturnCode_t 型のリターンコード + # + # @else + # + # @brief [ComponentAction CORBA interface] Error Processing of RTC + # + # The RTC remains in the Error state. + # If the RTC is in the Error state relative to some execution context when + # it would otherwise be invoked from that context (according to the + # context’s ExecutionKind), this callback shall be invoked instead. + # For example, + # - If the ExecutionKind is PERIODIC, this operation shall be invoked in + # sorted order at the rate of the context instead of + # DataFlowComponentAction::on_execute and on_state_update. + # - If the ExecutionKind is EVENT_DRIVEN, this operation shall be invoked + # whenever FsmParticipantAction::on_action would otherwise have been + # invoked. + # + # @param ec_id + # + # @return + # + # @endif + + def on_error(self, ec_id): + return OpenRTM_aist.RTObject_impl.on_error(self, ec_id) + + ## + # @if jp + # + # @brief [ComponentAction CORBA interface] RTC のエラー状態への遷移 + # + # RTC が所属する ExecutionContext が Active 状態から Error 状態へ遷移した + # 場合に呼び出される。 + # このオペレーションは RTC が Error 状態に遷移した際に一度だけ呼び出される。 + # このオペレーション呼び出しの結果として onAborting() コールバック関数が + # 呼び出される。 + # + # @param self + # @param ec_id 状態遷移した ExecutionContext の ID + # + # @return ReturnCode_t 型のリターンコード + # + # @else + # + # @brief [ComponentAction CORBA interface] Transition Error State + # + # The RTC is transitioning from the Active state to the Error state in some + # execution context. + # This callback is invoked only a single time for time that the RTC + # transitions into the Error state from another state. This behavior is in + # contrast to that of on_error. + # + # @param ec_id + # + # @return + # + # @endif + + def on_aborting(self, ec_id): + return OpenRTM_aist.RTObject_impl.on_aborting(self, ec_id) + + ## + # @if jp + # + # @brief [ComponentAction CORBA interface] RTC のリセット + # + # Error 状態にある RTC のリカバリ処理を実行し、Inactive 状態に復帰させる + # 場合に呼び出される。 + # RTC のリカバリ処理が成功した場合は Inactive 状態に復帰するが、それ以外の + # 場合には Error 状態に留まる。 + # このオペレーション呼び出しの結果として onReset() コールバック関数が呼び + # 出される。 + # + # @param self + # @param ec_id リセット対象 ExecutionContext の ID + # + # @return ReturnCode_t 型のリターンコード + # + # @else + # + # @brief [ComponentAction CORBA interface] Resetting RTC + # + # The RTC is in the Error state. An attempt is being made to recover it such + # that it can return to the Inactive state. + # If the RTC was successfully recovered and can safely return to the + # Inactive state, this method shall complete with ReturnCode_t::OK. Any + # other result shall indicate that the RTC should remain in the Error state. + # + # @param ec_id + # + # @return + # + # @endif + + def on_reset(self, ec_id): + return OpenRTM_aist.RTObject_impl.on_reset(self, ec_id) + + ## + # @if jp + # @brief + # + # + # + # @param self + # + # @else + # + # @brief Consructor + # + # + # @endif + + def on_action(self, ec_id): + return RTC.RTC_OK diff --git a/OpenRTM_aist/FsmActionListener.py b/OpenRTM_aist/FsmActionListener.py index f542ef54..cc3048fe 100644 --- a/OpenRTM_aist/FsmActionListener.py +++ b/OpenRTM_aist/FsmActionListener.py @@ -1,5 +1,5 @@ #!/usr/bin/env python -# -*- coding: euc-jp -*- +# -*- coding: utf-8 -*- ## # @file FsmActionListener.py @@ -25,18 +25,18 @@ # @if jp # @brief # -# FSMݡͥȤ˴ؤο񤤤եå뤿Υꥹ -# ꥹʤˤ礭ʬȡ +# FSMコンポーネントに関する種々の振る舞いをフックするためのリスナ定 +# 義。リスナには大きく分けると、 # -# - FSMΤΤưեå뤿Υꥹ -# - FSM˴ؤ᥿ǡѹưեå뤿Υꥹ +# - FSMそのものの動作をフックするためのリスナ +# - FSMに関するメタデータ変更等の動作をフックするためのリスナ # -# 2ʬ롣ԤϡFSMξΥ -# 夽줾եå뤿 PreFsmActionListener -# PostFsmActionListener ĤꡢԤϡFSMProfileѹե -# FsmProfileListener FSMι¤ (Structure) ѹեå -# FsmStructureListener Ĥʬ롣ʾ塢ʲFSM˴ -# ʲ4Υꥹʡ饹󶡤Ƥ롣 +# の2種類に分けられる。さらに前者は、FSMの状態遷移等のアクションの前 +# 後それぞれをフックするための PreFsmActionListener と +# PostFsmActionListener の二つがあり、後者は、FSMのProfileの変更をフッ +# クする FsmProfileListener と FSMの構造 (Structure) の変更をフック +# する FsmStructureListener の二つに分けられる。以上、以下のFSMに関 +# する以下の4種類のリスナークラス群が提供されている。 # # - PreFsmActionListener # - PostFsmActionListener @@ -52,19 +52,19 @@ ## # @if jp -# @brief PreFsmActionListener Υ +# @brief PreFsmActionListener のタイプ # -# PreFsmActionListener ˤϰʲΥեåݥȤƤ롣 -# 餬ƤӽФ뤫ɤϡFSMμ˰¸롣 +# PreFsmActionListener には以下のフックポイントが定義されている。こ +# れらが呼び出されるかどうかは、FSMの実装に依存する。 # -# - PRE_ON_INIT: init ľ -# - PRE_ON_ENTRY: entry ľ -# - PRE_ON_DO: do ľ -# - PRE_ON_EXIT: exit ľ -# - PRE_ON_STATE_CHANGE: ľ +# - PRE_ON_INIT: init 直前 +# - PRE_ON_ENTRY: entry 直前 +# - PRE_ON_DO: do 直前 +# - PRE_ON_EXIT: exit 直前 +# - PRE_ON_STATE_CHANGE: 状態遷移直前 # # @else -# @brief The types of ConnectorDataListener +# @brief The types of PreFsmActionListenerType # # PreFsmActionListener has the following hook points. If these # listeners are actually called or not called are depends on FSM @@ -78,30 +78,32 @@ # # @endif # + + class PreFsmActionListenerType: - """ - """ + """ + """ - def __init__(self): - pass - PRE_ON_INIT = 0 - PRE_ON_ENTRY = 1 - PRE_ON_DO = 2 - PRE_ON_EXIT = 3 - PRE_ON_STATE_CHANGE = 4 - PRE_FSM_ACTION_LISTENER_NUM = 5 + def __init__(self): + pass + PRE_ON_INIT = 0 + PRE_ON_ENTRY = 1 + PRE_ON_DO = 2 + PRE_ON_EXIT = 3 + PRE_ON_STATE_CHANGE = 4 + PRE_FSM_ACTION_LISTENER_NUM = 5 ## # @if jp -# @class PreFsmActionListener 饹 -# @brief PreFsmActionListener 饹 +# @class PreFsmActionListener クラス +# @brief PreFsmActionListener クラス # -# PreFsmActionListener 饹ϡFsmΥ˴ؤ륳Хå -# ¸ꥹʡ֥Ȥδ쥯饹Ǥ롣FSMΥ -# ľưեå硢ʲΤ褦ˡΥ饹Ѿ -# Хå֥ȤŬڤʥХåؿ -# RTObjectФƥХå֥Ȥ򥻥åȤɬפ롣 +# PreFsmActionListener クラスは、Fsmのアクションに関するコールバック +# を実現するリスナーオブジェクトの基底クラスである。FSMのアクション +# の直前の動作をフックしたい場合、以下の例のように、このクラスを継承 +# したコールバックオブジェクトを定義し、適切なコールバック設定関数か +# らRTObjectに対してコールバックオブジェクトをセットする必要がある。 # #
 # class MyListener
@@ -120,8 +122,8 @@ def __init__(self):
 # };
 # 
# -# Τ褦ˤ줿ꥹʥ饹ϡʲΤ褦RTObjectФ -# ơåȤ롣 +# このようにして定義されたリスナクラスは、以下のようにRTObjectに対し +# て、セットされる。 # #
 # RTC::ReturnCode_t ConsoleIn::onInitialize()
@@ -132,28 +134,28 @@ def __init__(self):
 #    :
 # 
# -# 1 "PRE_ON_STATE_CHANGE" ϡХåեåݥ -# ȤǤꡢʲͤ뤳ȤǽǤ롣ʤ٤ƤΥХ -# ݥȤƤȤϸ¤餺餬ƤӽФ뤫ɤ -# ϡFSMμ˰¸롣 -# -# - PRE_ON_INIT: init ľ -# - PRE_ON_ENTRY: entry ľ -# - PRE_ON_DO: do ľ -# - PRE_ON_EXIT: exit ľ -# - PRE_ON_STATE_CHANGE: ľ -# -# 2ϥꥹʥ֥ȤΥݥ󥿤Ǥ롣3ϥ֥ -# ưե饰Ǥꡢtrue ξϡRTObject˼ưŪ˥ꥹ -# ʥ֥Ȥ롣falseξϡ֥Ȥνͭ -# ƤӽФ¦˻ĤꡢϸƤӽФ¦ǤǹԤʤФʤʤ -# RTObject Υ饤ե˥Хåɬפʤо嵭Τ褦 -# ƤӽФ3 true ȤƤȤ褤դˡХå -# ˱ƥåȤꥢ󥻥åȤꤹɬפ -# falseȤ֤ꥹʥ֥ȤΥݥ󥿤ѿʤɤ -# Ƥ +# 第1引数の "PRE_ON_STATE_CHANGE" は、コールバックをフックするポイン +# トであり、以下の値を取ることが可能である。なお、すべてのコールバッ +# クポイントが実装されているとは限らず、これらが呼び出されるかどうか +# は、FSMの実装に依存する。 +# +# - PRE_ON_INIT: init 直前 +# - PRE_ON_ENTRY: entry 直前 +# - PRE_ON_DO: do 直前 +# - PRE_ON_EXIT: exit 直前 +# - PRE_ON_STATE_CHANGE: 状態遷移直前 +# +# 第2引数はリスナオブジェクトのポインタである。第3引数はオブジェクト +# 自動削除フラグであり、true の場合は、RTObject削除時に自動的にリス +# ナオブジェクトが削除される。falseの場合は、オブジェクトの所有権は +# 呼び出し側に残り、削除は呼び出し側の責任で行わなければならない。 +# RTObject のライフサイクル中にコールバックが必要ならば上記のような +# 呼び出し方で第3引数を true としておくとよい。逆に、コールバックを +# 状況等に応じてセットしたりアンセットしたりする必要がある場合は +# falseとして置き、リスナオブジェクトのポインタをメンバ変数などに保 +# 持しておき、 # RTObject_impl::addPreFsmActionListener()/removePreFsmActionListener() -# ˤꡢåȤȥ󥻥åȤȤäȤǽǤ롣 +# により、セットとアンセットを管理するといった使い方も可能である。 # # @else # @class PreFsmActionListener class @@ -225,99 +227,97 @@ def __init__(self): # @endif # class PreFsmActionListener: - ## - # @if jp - # @brief 󥹥ȥ饯 - # @else - # @brief Constructor - # @endif - # - def __init__(self): - pass - - - ## - # @if jp - # @brief ǥȥ饯 - # @else - # @brief Destructor - # @endif - # - def __del__(self): - pass - - - ## - # @if jp - # - # @brief ۥХåؿ - # - # PreFsmActionListener ΥХåؿ - # - # @else - # - # @brief Virtual Callback function - # - # This is a the Callback function for PreFsmActionListener. - # - # @endif - # virtual void operator()(const char*) = 0; - def __call__(self, state): - pass - - ## - # @if jp - # - # @brief PreFsmActionListenerType ʸѴ - # - # PreFsmActionListenerType ʸѴ - # - # @param type Ѵо PreFsmActionListenerType - # - # @return ʸѴ - # - # @else - # - # @brief Convert PreFsmActionListenerType into the string. - # - # Convert PreFsmActionListenerType into the string. - # - # @param type The target PreFsmActionListenerType for transformation - # - # @return Trnasformation result of string representation - # - # @endif - # - def toString(type): - typeString = ["PRE_ON_INIT", - "PRE_ON_ENTRY", - "PRE_ON_DO", - "PRE_ON_EXIT", - "PRE_ON_STATE_CHANGE", - "PRE_FSM_ACTION_LISTENER_NUM"] - if type < PreFsmActionListenerType.PRE_FSM_ACTION_LISTENER_NUM: - return typeString[type] - - return "" - toString = staticmethod(toString) - + ## + # @if jp + # @brief コンストラクタ + # @else + # @brief Constructor + # @endif + # + def __init__(self): + pass + + ## + # @if jp + # @brief デストラクタ + # @else + # @brief Destructor + # @endif + # + + def __del__(self): + pass + + ## + # @if jp + # + # @brief 仮想コールバック関数 + # + # PreFsmActionListener のコールバック関数 + # + # @else + # + # @brief Virtual Callback function + # + # This is a the Callback function for PreFsmActionListener. + # + # @endif + # virtual void operator()(const char*) = 0; + + def __call__(self, state): + pass + + ## + # @if jp + # + # @brief PreFsmActionListenerType を文字列に変換 + # + # PreFsmActionListenerType を文字列に変換する + # + # @param type 変換対象 PreFsmActionListenerType + # + # @return 文字列変換結果 + # + # @else + # + # @brief Convert PreFsmActionListenerType into the string. + # + # Convert PreFsmActionListenerType into the string. + # + # @param type The target PreFsmActionListenerType for transformation + # + # @return Trnasformation result of string representation + # + # @endif + # + def toString(status): + typeString = ["PRE_ON_INIT", + "PRE_ON_ENTRY", + "PRE_ON_DO", + "PRE_ON_EXIT", + "PRE_ON_STATE_CHANGE"] + if status < len(typeString): + return typeString[status] + + return "" + toString = staticmethod(toString) ## # @if jp -# @brief PreFsmActionListener Υ +# @brief PreFsmActionListener のタイプ # -# PreFsmActionListener ˤϰʲΥեåݥȤƤ롣 -# 餬ƤӽФ뤫ɤϡFSMμ˰¸롣 +# PreFsmActionListener には以下のフックポイントが定義されている。こ +# れらが呼び出されるかどうかは、FSMの実装に依存する。 # -# - POST_ON_INIT: init ľ -# - POST_ON_ENTRY: entry ľ -# - POST_ON_DO: do ľ -# - POST_ON_EXIT: exit ľ -# - POST_ON_STATE_CHANGE: ľ +# - POST_ON_INIT: init 直後 +# - POST_ON_ENTRY: entry 直後 +# - POST_ON_DO: do 直後 +# - POST_ON_EXIT: exit 直後 +# - POST_ON_STATE_CHANGE: 状態遷移直後 # # @else -# @brief The types of ConnectorDataListener +# @brief The types of PostFsmActionListenerType # # PreFsmActionListener has the following hook points. If these # listeners are actually called or not called are depends on FSM @@ -332,31 +332,29 @@ def toString(type): # @endif # class PostFsmActionListenerType: - """ - """ - - def __init__(self): - pass - POST_ON_INIT = 0 - POST_ON_ENTRY = 1 - POST_ON_DO = 2 - POST_ON_EXIT = 3 - POST_ON_STATE_CHANGE = 4 - POST_FSM_ACTION_LISTENER_NUM = 5 - + """ + """ + def __init__(self): + pass + POST_ON_INIT = 0 + POST_ON_ENTRY = 1 + POST_ON_DO = 2 + POST_ON_EXIT = 3 + POST_ON_STATE_CHANGE = 4 + POST_FSM_ACTION_LISTENER_NUM = 5 ## # @if jp -# @class PostFsmActionListener 饹 -# @brief PostFsmActionListener 饹 +# @class PostFsmActionListener クラス +# @brief PostFsmActionListener クラス # -# PostFsmActionListener 饹ϡFsmΥ˴ؤ륳Хå -# ¸ꥹʡ֥Ȥδ쥯饹Ǥ롣FSMΥ -# ľưեå硢ʲΤ褦ˡΥ饹Ѿ -# Хå֥ȤŬڤʥХåؿ -# RTObjectФƥХå֥Ȥ򥻥åȤɬפ롣 +# PostFsmActionListener クラスは、Fsmのアクションに関するコールバック +# を実現するリスナーオブジェクトの基底クラスである。FSMのアクション +# の直後の動作をフックしたい場合、以下の例のように、このクラスを継承 +# したコールバックオブジェクトを定義し、適切なコールバック設定関数か +# らRTObjectに対してコールバックオブジェクトをセットする必要がある。 # #
 # class MyListener
@@ -375,8 +373,8 @@ def __init__(self):
 # };
 # 
# -# Τ褦ˤ줿ꥹʥ饹ϡʲΤ褦RTObjectФ -# ơåȤ롣 +# このようにして定義されたリスナクラスは、以下のようにRTObjectに対し +# て、セットされる。 # #
 # RTC::ReturnCode_t ConsoleIn::onInitialize()
@@ -387,28 +385,28 @@ def __init__(self):
 #    :
 # 
# -# 1 "POST_ON_STATE_CHANGE" ϡХåեåݥ -# ȤǤꡢʲͤ뤳ȤǽǤ롣ʤ٤ƤΥХ -# ݥȤƤȤϸ¤餺餬ƤӽФ뤫ɤ -# ϡFSMμ˰¸롣 -# -# - POST_ON_INIT: init ľ -# - POST_ON_ENTRY: entry ľ -# - POST_ON_DO: do ľ -# - POST_ON_EXIT: exit ľ -# - POST_ON_STATE_CHANGE: ľ -# -# 2ϥꥹʥ֥ȤΥݥ󥿤Ǥ롣3ϥ֥ -# ưե饰Ǥꡢtrue ξϡRTObject˼ưŪ˥ꥹ -# ʥ֥Ȥ롣falseξϡ֥Ȥνͭ -# ƤӽФ¦˻ĤꡢϸƤӽФ¦ǤǹԤʤФʤʤ -# RTObject Υ饤ե˥Хåɬפʤо嵭Τ褦 -# ƤӽФ3 true ȤƤȤ褤դˡХå -# ˱ƥåȤꥢ󥻥åȤꤹɬפ -# falseȤ֤ꥹʥ֥ȤΥݥ󥿤ѿʤɤ -# Ƥ +# 第1引数の "POST_ON_STATE_CHANGE" は、コールバックをフックするポイン +# トであり、以下の値を取ることが可能である。なお、すべてのコールバッ +# クポイントが実装されているとは限らず、これらが呼び出されるかどうか +# は、FSMの実装に依存する。 +# +# - POST_ON_INIT: init 直後 +# - POST_ON_ENTRY: entry 直後 +# - POST_ON_DO: do 直後 +# - POST_ON_EXIT: exit 直後 +# - POST_ON_STATE_CHANGE: 状態遷移直後 +# +# 第2引数はリスナオブジェクトのポインタである。第3引数はオブジェクト +# 自動削除フラグであり、true の場合は、RTObject削除時に自動的にリス +# ナオブジェクトが削除される。falseの場合は、オブジェクトの所有権は +# 呼び出し側に残り、削除は呼び出し側の責任で行わなければならない。 +# RTObject のライフサイクル中にコールバックが必要ならば上記のような +# 呼び出し方で第3引数を true としておくとよい。逆に、コールバックを +# 状況等に応じてセットしたりアンセットしたりする必要がある場合は +# falseとして置き、リスナオブジェクトのポインタをメンバ変数などに保 +# 持しておき、 # RTObject_impl::addPostFsmActionListener()/removePostFsmActionListener() -# ˤꡢåȤȥ󥻥åȤȤäȤǽǤ롣 +# により、セットとアンセットを管理するといった使い方も可能である。 # # @else # @class PostFsmActionListener class @@ -480,96 +478,94 @@ def __init__(self): # @endif # class PostFsmActionListener: - ## - # @if jp - # @brief 󥹥ȥ饯 - # @else - # @brief Constructor - # @endif - # - def __init__(self): - pass - - - ## - # @if jp - # @brief ǥȥ饯 - # @else - # @brief Destructor - # @endif - # - def __del__(self): - pass - - - ## - # @if jp - # - # @brief ۥХåؿ - # - # PostFsmActionListener ΥХåؿ - # - # @else - # - # @brief Virtual Callback function - # - # This is a the Callback function for PostFsmActionListener. - # - # @endif - # virtual void operator()(const char* state, ReturnCode_t ret) = 0; - def __call__(self, state, ret): - pass - - ## - # @if jp - # - # @brief PostFsmActionListenerType ʸѴ - # - # PostFsmActionListenerType ʸѴ - # - # @param type Ѵо PostFsmActionListenerType - # - # @return ʸѴ - # - # @else - # - # @brief Convert PostFsmActionListenerType into the string. - # - # Convert PostFsmActionListenerType into the string. - # - # @param type The target PostFsmActionListenerType for transformation - # - # @return Trnasformation result of string representation - # - # @endif - # - def toString(type): - typeString = ["POST_ON_INIT", - "POST_ON_ENTRY", - "POST_ON_DO", - "POST_ON_EXIT", - "POST_ON_STATE_CHANGE", - "POST_FSM_ACTION_LISTENER_NUM"] - if type < PostFsmActionListenerType.POST_FSM_ACTION_LISTENER_NUM: - return typeString[type] - - return "" - toString = staticmethod(toString) + ## + # @if jp + # @brief コンストラクタ + # @else + # @brief Constructor + # @endif + # + def __init__(self): + pass + ## + # @if jp + # @brief デストラクタ + # @else + # @brief Destructor + # @endif + # + + def __del__(self): + pass + + ## + # @if jp + # + # @brief 仮想コールバック関数 + # + # PostFsmActionListener のコールバック関数 + # + # @else + # + # @brief Virtual Callback function + # + # This is a the Callback function for PostFsmActionListener. + # + # @endif + # virtual void operator()(const char* state, ReturnCode_t ret) = 0; + + def __call__(self, state, ret): + pass + + ## + # @if jp + # + # @brief PostFsmActionListenerType を文字列に変換 + # + # PostFsmActionListenerType を文字列に変換する + # + # @param type 変換対象 PostFsmActionListenerType + # + # @return 文字列変換結果 + # + # @else + # + # @brief Convert PostFsmActionListenerType into the string. + # + # Convert PostFsmActionListenerType into the string. + # + # @param type The target PostFsmActionListenerType for transformation + # + # @return Trnasformation result of string representation + # + # @endif + # + def toString(status): + typeString = ["POST_ON_INIT", + "POST_ON_ENTRY", + "POST_ON_DO", + "POST_ON_EXIT", + "POST_ON_STATE_CHANGE"] + if status < len(typeString): + return typeString[status] + + return "" + toString = staticmethod(toString) ## # @if jp -# @brief FsmProfileListener Υ +# @brief FsmProfileListener のタイプ # -# - SET_FSM_PROFILE : FSM Profile -# - GET_FSM_PROFILE : FSM Profile -# - ADD_FSM_STATE : FSMStateɲä줿 -# - REMOVE_FSM_STATE : FSMState줿 -# - ADD_FSM_TRANSITION : FSMܤɲä줿 -# - REMOVE_FSM_TRANSITION : FSMܤ줿 -# - BIND_FSM_EVENT : FSM˥٥ȤХɤ줿 -# - UNBIND_FSM_EVENT : FSM˥٥ȤХɤ줿 +# - SET_FSM_PROFILE : FSM Profile設定時 +# - GET_FSM_PROFILE : FSM Profile取得時 +# - ADD_FSM_STATE : FSMにStateが追加された +# - REMOVE_FSM_STATE : FSMからStateが削除された +# - ADD_FSM_TRANSITION : FSMに遷移が追加された +# - REMOVE_FSM_TRANSITION : FSMから遷移が削除された +# - BIND_FSM_EVENT : FSMにイベントがバインドされた +# - UNBIND_FSM_EVENT : FSMにイベントがアンバインドされた # # @else # @brief The types of FsmProfileListener @@ -586,34 +582,33 @@ def toString(type): # @endif # class FsmProfileListenerType: - """ - """ - - def __init__(self): - pass - SET_FSM_PROFILE = 0 - GET_FSM_PROFILE = 1 - ADD_FSM_STATE = 2 - REMOVE_FSM_STATE = 3 - ADD_FSM_TRANSITION = 4 - REMOVE_FSM_TRANSITION = 5 - BIND_FSM_EVENT = 6 - UNBIND_FSM_EVENT = 7 - FSM_PROFILE_LISTENER_NUM = 8 - + """ + """ + + def __init__(self): + pass + SET_FSM_PROFILE = 0 + GET_FSM_PROFILE = 1 + ADD_FSM_STATE = 2 + REMOVE_FSM_STATE = 3 + ADD_FSM_TRANSITION = 4 + REMOVE_FSM_TRANSITION = 5 + BIND_FSM_EVENT = 6 + UNBIND_FSM_EVENT = 7 + FSM_PROFILE_LISTENER_NUM = 8 ## # @if jp -# @class FsmProfileListener 饹 -# @brief FsmProfileListener 饹 +# @class FsmProfileListener クラス +# @brief FsmProfileListener クラス # -# FsmProfileListener 饹ϡFSMProfile˴ϢΥ -# Хå¸ꥹʡ֥Ȥδ쥯饹Ǥ롣FSM -# ProfileΥưեå硢ʲΤ褦ˡ -# Υ饹ѾХå֥ȤŬڤʥХ -# ؿRTObjectФƥХå֥Ȥ򥻥åȤ -# ɬפ롣 +# FsmProfileListener クラスは、FSMのProfileに関連したアクションのコー +# ルバックを実現するリスナーオブジェクトの基底クラスである。FSM +# Profileのアクションの動作をフックしたい場合、以下の例のように、こ +# のクラスを継承したコールバックオブジェクトを定義し、適切なコールバッ +# ク設定関数からRTObjectに対してコールバックオブジェクトをセットする +# 必要がある。 # #
 # class MyListener
@@ -631,8 +626,8 @@ def __init__(self):
 # };
 # 
# -# Τ褦ˤ줿ꥹʥ饹ϡʲΤ褦RTObjectФ -# ơåȤ롣 +# このようにして定義されたリスナクラスは、以下のようにRTObjectに対し +# て、セットされる。 # #
 # RTC::ReturnCode_t ConsoleIn::onInitialize()
@@ -643,30 +638,30 @@ def __init__(self):
 #    :
 # 
# -# 1 "SET_FSM_PROFILE" ϡХåեåݥ -# ȤǤꡢʲͤ뤳ȤǽǤ롣ʤ٤ƤΥХ -# ݥȤƤȤϸ¤餺餬ƤӽФ뤫ɤ -# ϡFSMӥμ˰¸롣 -# -# - SET_FSM_PROFILE : FSM Profile -# - GET_FSM_PROFILE : FSM Profile -# - ADD_FSM_STATE : FSMStateɲä줿 -# - REMOVE_FSM_STATE : FSMState줿 -# - ADD_FSM_TRANSITION : FSMܤɲä줿 -# - REMOVE_FSM_TRANSITION : FSMܤ줿 -# - BIND_FSM_EVENT : FSM˥٥ȤХɤ줿 -# - UNBIND_FSM_EVENT : FSM˥٥ȤХɤ줿 -# -# 2ϥꥹʥ֥ȤΥݥ󥿤Ǥ롣3ϥ֥ -# ưե饰Ǥꡢtrue ξϡRTObject˼ưŪ˥ꥹ -# ʥ֥Ȥ롣falseξϡ֥Ȥνͭ -# ƤӽФ¦˻ĤꡢϸƤӽФ¦ǤǹԤʤФʤʤ -# RTObject Υ饤ե˥Хåɬפʤо嵭Τ褦 -# ƤӽФ3 true ȤƤȤ褤դˡХå -# ˱ƥåȤꥢ󥻥åȤꤹɬפ -# falseȤ֤ꥹʥ֥ȤΥݥ󥿤ѿʤɤ -# ƤaddFsmProfileListener()/removeFsmProfileListener() -# ꡢåȤȥ󥻥åȤȤäȤǽǤ롣 +# 第1引数の "SET_FSM_PROFILE" は、コールバックをフックするポイン +# トであり、以下の値を取ることが可能である。なお、すべてのコールバッ +# クポイントが実装されているとは限らず、これらが呼び出されるかどうか +# は、FSMサービスの実装に依存する。 +# +# - SET_FSM_PROFILE : FSM Profile設定時 +# - GET_FSM_PROFILE : FSM Profile取得時 +# - ADD_FSM_STATE : FSMにStateが追加された +# - REMOVE_FSM_STATE : FSMからStateが削除された +# - ADD_FSM_TRANSITION : FSMに遷移が追加された +# - REMOVE_FSM_TRANSITION : FSMから遷移が削除された +# - BIND_FSM_EVENT : FSMにイベントがバインドされた +# - UNBIND_FSM_EVENT : FSMにイベントがアンバインドされた +# +# 第2引数はリスナオブジェクトのポインタである。第3引数はオブジェクト +# 自動削除フラグであり、true の場合は、RTObject削除時に自動的にリス +# ナオブジェクトが削除される。falseの場合は、オブジェクトの所有権は +# 呼び出し側に残り、削除は呼び出し側の責任で行わなければならない。 +# RTObject のライフサイクル中にコールバックが必要ならば上記のような +# 呼び出し方で第3引数を true としておくとよい。逆に、コールバックを +# 状況等に応じてセットしたりアンセットしたりする必要がある場合は +# falseとして置き、リスナオブジェクトのポインタをメンバ変数などに保 +# 持しておき、addFsmProfileListener()/removeFsmProfileListener() に +# より、セットとアンセットを管理するといった使い方も可能である。 # # @else # @class FsmProfileListener class @@ -739,92 +734,90 @@ def __init__(self): # @endif # class FsmProfileListener: - ## - # @if jp - # @brief 󥹥ȥ饯 - # @else - # @brief Constructor - # @endif - # - def __init__(self): - pass - - ## - # @if jp - # @brief ǥȥ饯 - # @else - # @brief Destructor - # @endif - # - def __del__(self): - pass - - - ## - # @if jp - # - # @brief ۥХåؿ - # - # FsmProfileListener ΥХåؿ - # - # @else - # - # @brief Virtual Callback function - # - # This is a the Callback function for FsmProfileListener. - # - # @endif - # virtual void operator()(const ::RTC::FsmProfile& fsmprof) = 0; - def __call__(self, fsmprof): - pass - - ## - # @if jp - # - # @brief FsmProfileListenerType ʸѴ - # - # FsmProfileListenerType ʸѴ - # - # @param type Ѵо FsmProfileListenerType - # - # @return ʸѴ - # - # @else - # - # @brief Convert FsmProfileListenerType into the string. - # - # Convert FsmProfileListenerType into the string. - # - # @param type The target FsmProfileListenerType for transformation - # - # @return Trnasformation result of string representation - # - # @endif - # - def toString(type): - typeString = ["SET_FSM_PROFILE", - "GET_FSM_PROFILE", - "ADD_FSM_STATE", - "REMOVE_FSM_STATE", - "ADD_FSM_TRANSITION", - "REMOVE_FSM_TRANSITION", - "BIND_FSM_EVENT", - "UNBIND_FSM_EVENT", - "PRE_FSM_ACTION_LISTENER_NUM"] - if type < FsmProfileListenerType.FSM_PROFILE_LISTENER_NUM: - return typeString[type] - - return "" - toString = staticmethod(toString) + ## + # @if jp + # @brief コンストラクタ + # @else + # @brief Constructor + # @endif + # + def __init__(self): + pass + + ## + # @if jp + # @brief デストラクタ + # @else + # @brief Destructor + # @endif + # + def __del__(self): + pass + ## + # @if jp + # + # @brief 仮想コールバック関数 + # + # FsmProfileListener のコールバック関数 + # + # @else + # + # @brief Virtual Callback function + # + # This is a the Callback function for FsmProfileListener. + # + # @endif + # virtual void operator()(const ::RTC::FsmProfile& fsmprof) = 0; + + def __call__(self, fsmprof): + pass + + ## + # @if jp + # + # @brief FsmProfileListenerType を文字列に変換 + # + # FsmProfileListenerType を文字列に変換する + # + # @param type 変換対象 FsmProfileListenerType + # + # @return 文字列変換結果 + # + # @else + # + # @brief Convert FsmProfileListenerType into the string. + # + # Convert FsmProfileListenerType into the string. + # + # @param type The target FsmProfileListenerType for transformation + # + # @return Trnasformation result of string representation + # + # @endif + # + def toString(status): + typeString = ["SET_FSM_PROFILE", + "GET_FSM_PROFILE", + "ADD_FSM_STATE", + "REMOVE_FSM_STATE", + "ADD_FSM_TRANSITION", + "REMOVE_FSM_TRANSITION", + "BIND_FSM_EVENT", + "UNBIND_FSM_EVENT"] + if status < len(typeString): + return typeString[status] + + return "" + toString = staticmethod(toString) ## # @if jp -# @brief FsmStructureListener Υ +# @brief FsmStructureListener のタイプ # -# - SET_FSM_STRUCTURE: FSM¤ -# - GET_FSM_STRUCTURE: FSM¤μ +# - SET_FSM_STRUCTURE: FSM構造の設定 +# - GET_FSM_STRUCTURE: FSM構造の取得 # # @else # @brief The types of FsmStructureListener @@ -835,27 +828,27 @@ def toString(type): # @endif # class FsmStructureListenerType: - """ - """ - - def __init__(self): - pass - SET_FSM_STRUCTURE = 0 - GET_FSM_STRUCTURE = 1 - FSM_STRUCTURE_LISTENER_NUM = 2 + """ + """ + + def __init__(self): + pass + SET_FSM_STRUCTURE = 0 + GET_FSM_STRUCTURE = 1 + FSM_STRUCTURE_LISTENER_NUM = 2 ## # @if jp -# @class FsmStructureListener 饹 -# @brief FsmStructureListener 饹 +# @class FsmStructureListener クラス +# @brief FsmStructureListener クラス # -# FsmStructureListener 饹ϡFSM StructureΥ˴ؤ륳 -# Хå¸ꥹʡ֥Ȥδ쥯饹Ǥ롣FSM -# Structure Υľưեå硢ʲΤ -# ˡΥ饹ѾХå֥ȤŬڤ -# ХåؿRTObjectФƥХå֥Ȥ -# åȤɬפ롣 +# FsmStructureListener クラスは、FSM Structureのアクションに関するコー +# ルバックを実現するリスナーオブジェクトの基底クラスである。FSM +# Structure のアクションの直後の動作をフックしたい場合、以下の例のよ +# うに、このクラスを継承したコールバックオブジェクトを定義し、適切な +# コールバック設定関数からRTObjectに対してコールバックオブジェクトを +# セットする必要がある。 # #
 # class MyListener
@@ -872,8 +865,8 @@ def __init__(self):
 # };
 # 
# -# Τ褦ˤ줿ꥹʥ饹ϡʲΤ褦RTObjectФ -# ơåȤ롣 +# このようにして定義されたリスナクラスは、以下のようにRTObjectに対し +# て、セットされる。 # #
 # RTC::ReturnCode_t ConsoleIn::onInitialize()
@@ -884,25 +877,25 @@ def __init__(self):
 #    :
 # 
# -# 1 "SET_FSM_STRUCTURE" ϡХåեåݥ -# ȤǤꡢʲͤ뤳ȤǽǤ롣ʤ٤ƤΥХ -# ݥȤƤȤϸ¤餺餬ƤӽФ뤫ɤ -# ϡFSMμ˰¸롣 -# -# - SET_FSM_STRUCTURE: FSM¤ -# - GET_FSM_STRUCTURE: FSM¤μ -# -# 2ϥꥹʥ֥ȤΥݥ󥿤Ǥ롣3ϥ֥ -# ưե饰Ǥꡢtrue ξϡRTObject˼ưŪ˥ꥹ -# ʥ֥Ȥ롣falseξϡ֥Ȥνͭ -# ƤӽФ¦˻ĤꡢϸƤӽФ¦ǤǹԤʤФʤʤ -# RTObject Υ饤ե˥Хåɬפʤо嵭Τ褦 -# ƤӽФ3 true ȤƤȤ褤դˡХå -# ˱ƥåȤꥢ󥻥åȤꤹɬפ -# falseȤ֤ꥹʥ֥ȤΥݥ󥿤ѿʤɤ -# Ƥ +# 第1引数の "SET_FSM_STRUCTURE" は、コールバックをフックするポイン +# トであり、以下の値を取ることが可能である。なお、すべてのコールバッ +# クポイントが実装されているとは限らず、これらが呼び出されるかどうか +# は、FSMの実装に依存する。 +# +# - SET_FSM_STRUCTURE: FSM構造の設定 +# - GET_FSM_STRUCTURE: FSM構造の取得 +# +# 第2引数はリスナオブジェクトのポインタである。第3引数はオブジェクト +# 自動削除フラグであり、true の場合は、RTObject削除時に自動的にリス +# ナオブジェクトが削除される。falseの場合は、オブジェクトの所有権は +# 呼び出し側に残り、削除は呼び出し側の責任で行わなければならない。 +# RTObject のライフサイクル中にコールバックが必要ならば上記のような +# 呼び出し方で第3引数を true としておくとよい。逆に、コールバックを +# 状況等に応じてセットしたりアンセットしたりする必要がある場合は +# falseとして置き、リスナオブジェクトのポインタをメンバ変数などに保 +# 持しておき、 # RTObject_impl::addPostFsmActionListener()/removePostFsmActionListener() -# ˤꡢåȤȥ󥻥åȤȤäȤǽǤ롣 +# により、セットとアンセットを管理するといった使い方も可能である。 # # @else # @class FsmStructureListener class @@ -969,93 +962,85 @@ def __init__(self): # @endif # class FsmStructureListener: - ## - # @if jp - # @brief 󥹥ȥ饯 - # @else - # @brief Constructor - # @endif - # - def __init__(self): - pass - - - ## - # @if jp - # @brief ǥȥ饯 - # @else - # @brief Destructor - # @endif - # - def __del__(self): - pass - - - ## - # @if jp - # - # @brief ۥХåؿ - # - # FsmStructureListener ΥХåؿ - # - # @else - # - # @brief Virtual Callback function - # - # This is a the Callback function for FsmStructureListener. - # - # @endif - # virtual void operator()(const ::RTC::FsmStructure& fsmprof) = 0; - def __call__(self, pprof): - pass - - ## - # @if jp - # - # @brief FsmStructureListenerType ʸѴ - # - # FsmStructureListenerType ʸѴ - # - # @param type Ѵо FsmStructureListenerType - # - # @return ʸѴ - # - # @else - # - # @brief Convert FsmStructureListenerType into the string. - # - # Convert FsmStructureListenerType into the string. - # - # @param type The target FsmStructureListenerType for transformation - # - # @return Trnasformation result of string representation - # - # @endif - # - def toString(type): - typeString = ["SET_FSM_STRUCTURE", - "GET_FSM_STRUCTURE", - "FSM_STRUCTURE_LISTENER_NUM"] - if type < FsmStructureListenerType.FSM_STRUCTURE_LISTENER_NUM: - return typeString[type] - - return "" - toString = staticmethod(toString) - - -class Entry: - def __init__(self,listener, autoclean): - self.listener = listener - self.autoclean = autoclean - return - + ## + # @if jp + # @brief コンストラクタ + # @else + # @brief Constructor + # @endif + # + def __init__(self): + pass + + ## + # @if jp + # @brief デストラクタ + # @else + # @brief Destructor + # @endif + # + + def __del__(self): + pass + + ## + # @if jp + # + # @brief 仮想コールバック関数 + # + # FsmStructureListener のコールバック関数 + # + # @else + # + # @brief Virtual Callback function + # + # This is a the Callback function for FsmStructureListener. + # + # @endif + # virtual void operator()(const ::RTC::FsmStructure& fsmprof) = 0; + + def __call__(self, pprof): + pass + + ## + # @if jp + # + # @brief FsmStructureListenerType を文字列に変換 + # + # FsmStructureListenerType を文字列に変換する + # + # @param type 変換対象 FsmStructureListenerType + # + # @return 文字列変換結果 + # + # @else + # + # @brief Convert FsmStructureListenerType into the string. + # + # Convert FsmStructureListenerType into the string. + # + # @param type The target FsmStructureListenerType for transformation + # + # @return Trnasformation result of string representation + # + # @endif + # + def toString(status): + typeString = ["SET_FSM_STRUCTURE", + "GET_FSM_STRUCTURE"] + if status < len(typeString): + return typeString[status] + + return "" + toString = staticmethod(toString) + ## # @if jp # @class PreFsmActionListenerHolder -# @brief PreFsmActionListener ۥ饹 +# @brief PreFsmActionListener ホルダクラス # -# ʣ PreFsmActionListener ݻ륯饹 +# 複数の PreFsmActionListener を保持し管理するクラス。 # # @else # @class PreFsmActionListenerHolder @@ -1067,118 +1052,105 @@ def __init__(self,listener, autoclean): # @endif # class PreFsmActionListenerHolder: - ## - # @if jp - # @brief 󥹥ȥ饯 - # @else - # @brief Constructor - # @endif - # - def __init__(self): - self._listeners = [] - self._mutex = threading.RLock() - - ## - # @if jp - # @brief ǥȥ饯 - # @else - # @brief Destructor - # @endif - # - def __del__(self): - guard = OpenRTM_aist.Guard.ScopedLock(self._mutex) - for (idx, listener) in enumerate(self._listeners): - if listener.autoclean: - self._listeners[idx] = None - - - - ## - # @if jp - # - # @brief ꥹʡɲ - # - # ꥹʡɲä롣 - # - # @param listener ɲäꥹ - # @param autoclean true:ǥȥ饯Ǻ, - # false:ǥȥ饯Ǻʤ - # @else - # - # @brief Add the listener. - # - # This method adds the listener. - # - # @param listener Added listener - # @param autoclean true:The listener is deleted at the destructor., - # false:The listener is not deleted at the destructor. - # @endif - # - def addListener(self, listener, autoclean): - guard = OpenRTM_aist.Guard.ScopedLock(self._mutex) - self._listeners.append(Entry(listener, autoclean)) - - ## - # @if jp - # - # @brief ꥹʡκ - # - # ꥹʤ롣 - # - # @param listener ꥹ - # @else - # - # @brief Remove the listener. - # - # This method removes the listener. - # - # @param listener Removed listener - # @endif - # - def removeListener(self, listener): - guard = OpenRTM_aist.Guard.ScopedLock(self._mutex) - len_ = len(self._listeners) - for i in range(len_): - idx = (len_ - 1) - i - if self._listeners[idx].listener == listener: - if self._listeners[idx].autoclean: - self._listeners[idx].listener = None - del self._listeners[idx] - return - - ## - # @if jp - # - # @brief ꥹʡΤ - # - # ϿƤꥹʤΥХå᥽åɤƤӽФ - # - # @param info ConnectorInfo - # @else - # - # @brief Notify listeners. - # - # This calls the Callback method of the registered listener. - # - # @param info ConnectorInfo - # @endif - # - def notify(self, state): - guard = OpenRTM_aist.Guard.ScopedLock(self._mutex) - for listener in self._listeners: - listener.listener(state) - return + ## + # @if jp + # @brief コンストラクタ + # @else + # @brief Constructor + # @endif + # + def __init__(self): + self._listeners = [] + self._mutex = threading.RLock() + ## + # @if jp + # @brief デストラクタ + # @else + # @brief Destructor + # @endif + # + def __del__(self): + pass + ## + # @if jp + # + # @brief リスナーの追加 + # + # リスナーを追加する。 + # + # @param listener 追加するリスナ + # @else + # + # @brief Add the listener. + # + # This method adds the listener. + # + # @param listener Added listener + # @endif + # + + def addListener(self, listener): + guard = OpenRTM_aist.Guard.ScopedLock(self._mutex) + self._listeners.append(listener) + + ## + # @if jp + # + # @brief リスナーの削除 + # + # リスナを削除する。 + # + # @param listener 削除するリスナ + # @else + # + # @brief Remove the listener. + # + # This method removes the listener. + # + # @param listener Removed listener + # @endif + # + def removeListener(self, listener): + guard = OpenRTM_aist.Guard.ScopedLock(self._mutex) + len_ = len(self._listeners) + for i in range(len_): + idx = (len_ - 1) - i + if self._listeners[idx] == listener: + del self._listeners[idx] + return + ## + # @if jp + # + # @brief リスナーへ通知する + # + # 登録されているリスナのコールバックメソッドを呼び出す。 + # + # @param info ConnectorInfo + # @else + # + # @brief Notify listeners. + # + # This calls the Callback method of the registered listener. + # + # @param info ConnectorInfo + # @endif + # + def notify(self, state): + guard = OpenRTM_aist.Guard.ScopedLock(self._mutex) + for listener in self._listeners: + listener(state) + return ## # @if jp # @class PostFsmActionListenerHolder -# @brief PostFsmActionListener ۥ饹 +# @brief PostFsmActionListener ホルダクラス # -# ʣ PostFsmActionListener ݻ륯饹 +# 複数の PostFsmActionListener を保持し管理するクラス。 # # @else # @class PostFsmActionListenerHolder @@ -1190,115 +1162,104 @@ def notify(self, state): # @endif # class PostFsmActionListenerHolder: - ## - # @if jp - # @brief 󥹥ȥ饯 - # @else - # @brief Constructor - # @endif - # - def __init__(self): - self._listeners = [] - self._mutex = threading.RLock() - - ## - # @if jp - # @brief ǥȥ饯 - # @else - # @brief Destructor - # @endif - # - def __del__(self): - guard = OpenRTM_aist.Guard.ScopedLock(self._mutex) - for (idx, listener) in enumerate(self._listeners): - if listener.autoclean: - self._listeners[idx] = None - - - - ## - # @if jp - # - # @brief ꥹʡɲ - # - # ꥹʡɲä롣 - # - # @param listener ɲäꥹ - # @param autoclean true:ǥȥ饯Ǻ, - # false:ǥȥ饯Ǻʤ - # @else - # - # @brief Add the listener. - # - # This method adds the listener. - # - # @param listener Added listener - # @param autoclean true:The listener is deleted at the destructor., - # false:The listener is not deleted at the destructor. - # @endif - # - def addListener(self, listener, autoclean): - guard = OpenRTM_aist.Guard.ScopedLock(self._mutex) - self._listeners.append(Entry(listener, autoclean)) - - ## - # @if jp - # - # @brief ꥹʡκ - # - # ꥹʤ롣 - # - # @param listener ꥹ - # @else - # - # @brief Remove the listener. - # - # This method removes the listener. - # - # @param listener Removed listener - # @endif - # - def removeListener(self, listener): - guard = OpenRTM_aist.Guard.ScopedLock(self._mutex) - len_ = len(self._listeners) - for i in range(len_): - idx = (len_ - 1) - i - if self._listeners[idx].listener == listener: - if self._listeners[idx].autoclean: - self._listeners[idx].listener = None - del self._listeners[idx] - return - - ## - # @if jp - # - # @brief ꥹʡΤ - # - # ϿƤꥹʤΥХå᥽åɤƤӽФ - # - # @param info ConnectorInfo - # @else - # - # @brief Notify listeners. - # - # This calls the Callback method of the registered listener. - # - # @param info ConnectorInfo - # @endif - # - def notify(self, state, ret): - guard = OpenRTM_aist.Guard.ScopedLock(self._mutex) - for listener in self._listeners: - listener.listener(state, ret) - return + ## + # @if jp + # @brief コンストラクタ + # @else + # @brief Constructor + # @endif + # + def __init__(self): + self._listeners = [] + self._mutex = threading.RLock() + + ## + # @if jp + # @brief デストラクタ + # @else + # @brief Destructor + # @endif + # + def __del__(self): + pass + + ## + # @if jp + # + # @brief リスナーの追加 + # + # リスナーを追加する。 + # + # @param listener 追加するリスナ + # @else + # + # @brief Add the listener. + # + # This method adds the listener. + # + # @param listener Added listener + # @endif + # + def addListener(self, listener): + guard = OpenRTM_aist.Guard.ScopedLock(self._mutex) + self._listeners.append(listener) + + ## + # @if jp + # + # @brief リスナーの削除 + # + # リスナを削除する。 + # + # @param listener 削除するリスナ + # @else + # + # @brief Remove the listener. + # + # This method removes the listener. + # + # @param listener Removed listener + # @endif + # + def removeListener(self, listener): + guard = OpenRTM_aist.Guard.ScopedLock(self._mutex) + len_ = len(self._listeners) + for i in range(len_): + idx = (len_ - 1) - i + if self._listeners[idx] == listener: + del self._listeners[idx] + return + + ## + # @if jp + # + # @brief リスナーへ通知する + # + # 登録されているリスナのコールバックメソッドを呼び出す。 + # + # @param info ConnectorInfo + # @else + # + # @brief Notify listeners. + # + # This calls the Callback method of the registered listener. + # + # @param info ConnectorInfo + # @endif + # + def notify(self, state, ret): + guard = OpenRTM_aist.Guard.ScopedLock(self._mutex) + for listener in self._listeners: + listener(state, ret) + return ## # @if jp # @class FsmProfileListenerHolder -# @brief FsmProfileListener ۥ饹 +# @brief FsmProfileListener ホルダクラス # -# ʣ FsmProfileListener ݻ륯饹 +# 複数の FsmProfileListener を保持し管理するクラス。 # # @else # @class FsmProfileListenerHolder @@ -1310,114 +1271,104 @@ def notify(self, state, ret): # @endif # class FsmProfileListenerHolder: - ## - # @if jp - # @brief 󥹥ȥ饯 - # @else - # @brief Constructor - # @endif - # - def __init__(self): - self._listeners = [] - self._mutex = threading.RLock() - - ## - # @if jp - # @brief ǥȥ饯 - # @else - # @brief Destructor - # @endif - # - def __del__(self): - guard = OpenRTM_aist.Guard.ScopedLock(self._mutex) - for (idx, listener) in enumerate(self._listeners): - if listener.autoclean: - self._listeners[idx] = None - - - - ## - # @if jp - # - # @brief ꥹʡɲ - # - # ꥹʡɲä롣 - # - # @param listener ɲäꥹ - # @param autoclean true:ǥȥ饯Ǻ, - # false:ǥȥ饯Ǻʤ - # @else - # - # @brief Add the listener. - # - # This method adds the listener. - # - # @param listener Added listener - # @param autoclean true:The listener is deleted at the destructor., - # false:The listener is not deleted at the destructor. - # @endif - # - def addListener(self, listener, autoclean): - guard = OpenRTM_aist.Guard.ScopedLock(self._mutex) - self._listeners.append(Entry(listener, autoclean)) - - ## - # @if jp - # - # @brief ꥹʡκ - # - # ꥹʤ롣 - # - # @param listener ꥹ - # @else - # - # @brief Remove the listener. - # - # This method removes the listener. - # - # @param listener Removed listener - # @endif - # - def removeListener(self, listener): - guard = OpenRTM_aist.Guard.ScopedLock(self._mutex) - len_ = len(self._listeners) - for i in range(len_): - idx = (len_ - 1) - i - if self._listeners[idx].listener == listener: - if self._listeners[idx].autoclean: - self._listeners[idx].listener = None - del self._listeners[idx] - return - - ## - # @if jp - # - # @brief ꥹʡΤ - # - # ϿƤꥹʤΥХå᥽åɤƤӽФ - # - # @param info ConnectorInfo - # @else - # - # @brief Notify listeners. - # - # This calls the Callback method of the registered listener. - # - # @param info ConnectorInfo - # @endif - # - def notify(self, state): - guard = OpenRTM_aist.Guard.ScopedLock(self._mutex) - for listener in self._listeners: - listener.listener(state) - return + ## + # @if jp + # @brief コンストラクタ + # @else + # @brief Constructor + # @endif + # + def __init__(self): + self._listeners = [] + self._mutex = threading.RLock() + + ## + # @if jp + # @brief デストラクタ + # @else + # @brief Destructor + # @endif + # + def __del__(self): + pass + + ## + # @if jp + # + # @brief リスナーの追加 + # + # リスナーを追加する。 + # + # @param listener 追加するリスナ + # @else + # + # @brief Add the listener. + # + # This method adds the listener. + # + # @param listener Added listener + # @endif + # + + def addListener(self, listener): + guard = OpenRTM_aist.Guard.ScopedLock(self._mutex) + self._listeners.append(listener) + + ## + # @if jp + # + # @brief リスナーの削除 + # + # リスナを削除する。 + # + # @param listener 削除するリスナ + # @else + # + # @brief Remove the listener. + # + # This method removes the listener. + # + # @param listener Removed listener + # @endif + # + def removeListener(self, listener): + guard = OpenRTM_aist.Guard.ScopedLock(self._mutex) + len_ = len(self._listeners) + for i in range(len_): + idx = (len_ - 1) - i + if self._listeners[idx] == listener: + del self._listeners[idx] + return + + ## + # @if jp + # + # @brief リスナーへ通知する + # + # 登録されているリスナのコールバックメソッドを呼び出す。 + # + # @param info ConnectorInfo + # @else + # + # @brief Notify listeners. + # + # This calls the Callback method of the registered listener. + # + # @param info ConnectorInfo + # @endif + # + def notify(self, state): + guard = OpenRTM_aist.Guard.ScopedLock(self._mutex) + for listener in self._listeners: + listener(state) + return ## # @if jp # @class FsmStructureListenerHolder -# @brief FsmStructureListener ۥ饹 +# @brief FsmStructureListener ホルダクラス # -# ʣ FsmStructureListener ݻ륯饹 +# 複数の FsmStructureListener を保持し管理するクラス。 # # @else # @class FsmStructureListenerHolder @@ -1428,116 +1379,106 @@ def notify(self, state): # # @endif # + + class FsmStructureListenerHolder: - ## - # @if jp - # @brief 󥹥ȥ饯 - # @else - # @brief Constructor - # @endif - # - def __init__(self): - self._listeners = [] - self._mutex = threading.RLock() - - ## - # @if jp - # @brief ǥȥ饯 - # @else - # @brief Destructor - # @endif - # - def __del__(self): - guard = OpenRTM_aist.Guard.ScopedLock(self._mutex) - for (idx, listener) in enumerate(self._listeners): - if listener.autoclean: - self._listeners[idx] = None - - - - ## - # @if jp - # - # @brief ꥹʡɲ - # - # ꥹʡɲä롣 - # - # @param listener ɲäꥹ - # @param autoclean true:ǥȥ饯Ǻ, - # false:ǥȥ饯Ǻʤ - # @else - # - # @brief Add the listener. - # - # This method adds the listener. - # - # @param listener Added listener - # @param autoclean true:The listener is deleted at the destructor., - # false:The listener is not deleted at the destructor. - # @endif - # - def addListener(self, listener, autoclean): - guard = OpenRTM_aist.Guard.ScopedLock(self._mutex) - self._listeners.append(Entry(listener, autoclean)) - - ## - # @if jp - # - # @brief ꥹʡκ - # - # ꥹʤ롣 - # - # @param listener ꥹ - # @else - # - # @brief Remove the listener. - # - # This method removes the listener. - # - # @param listener Removed listener - # @endif - # - def removeListener(self, listener): - guard = OpenRTM_aist.Guard.ScopedLock(self._mutex) - len_ = len(self._listeners) - for i in range(len_): - idx = (len_ - 1) - i - if self._listeners[idx].listener == listener: - if self._listeners[idx].autoclean: - self._listeners[idx].listener = None - del self._listeners[idx] - return - - ## - # @if jp - # - # @brief ꥹʡΤ - # - # ϿƤꥹʤΥХå᥽åɤƤӽФ - # - # @param info ConnectorInfo - # @else - # - # @brief Notify listeners. - # - # This calls the Callback method of the registered listener. - # - # @param info ConnectorInfo - # @endif - # - def notify(self, state): - guard = OpenRTM_aist.Guard.ScopedLock(self._mutex) - for listener in self._listeners: - listener.listener(state) - return + ## + # @if jp + # @brief コンストラクタ + # @else + # @brief Constructor + # @endif + # + def __init__(self): + self._listeners = [] + self._mutex = threading.RLock() + + ## + # @if jp + # @brief デストラクタ + # @else + # @brief Destructor + # @endif + # + def __del__(self): + pass + ## + # @if jp + # + # @brief リスナーの追加 + # + # リスナーを追加する。 + # + # @param listener 追加するリスナ + # @else + # + # @brief Add the listener. + # + # This method adds the listener. + # + # @param listener Added listener + # @endif + # + def addListener(self, listener): + guard = OpenRTM_aist.Guard.ScopedLock(self._mutex) + self._listeners.append(listener) + + ## + # @if jp + # + # @brief リスナーの削除 + # + # リスナを削除する。 + # + # @param listener 削除するリスナ + # @else + # + # @brief Remove the listener. + # + # This method removes the listener. + # + # @param listener Removed listener + # @endif + # + def removeListener(self, listener): + guard = OpenRTM_aist.Guard.ScopedLock(self._mutex) + len_ = len(self._listeners) + for i in range(len_): + idx = (len_ - 1) - i + if self._listeners[idx] == listener: + del self._listeners[idx] + return + + ## + # @if jp + # + # @brief リスナーへ通知する + # + # 登録されているリスナのコールバックメソッドを呼び出す。 + # + # @param info ConnectorInfo + # @else + # + # @brief Notify listeners. + # + # This calls the Callback method of the registered listener. + # + # @param info ConnectorInfo + # @endif + # + def notify(self, state): + guard = OpenRTM_aist.Guard.ScopedLock(self._mutex) + for listener in self._listeners: + listener(state) + return ## # @if jp # @class FsmActionListeners -# @brief FsmActionListeners 饹 +# @brief FsmActionListeners クラス # # # @else @@ -1547,53 +1488,350 @@ def notify(self, state): # # @endif class FsmActionListeners: - def __init__(self): + ## + # @if jp + # @brief コンストラクタ + # + # + # @param self + # + # @else + # + # @param self + # + # @endif + def __init__(self): + + ## + # @if jp + # @brief PreFsmActionListenerType + # PreFsmActionListenerTypeリスナを格納 + # @else + # @brief PreFsmActionListenerType listener array + # The PreFsmActionListenerType listener is stored. + # @endif + self.preaction_num = PreFsmActionListenerType.PRE_FSM_ACTION_LISTENER_NUM + self.preaction_ = [PreFsmActionListenerHolder() + for i in range(self.preaction_num)] + + ## + # @if jp + # @brief PostFsmActionTypeリスナ配列 + # PostFsmActionTypeリスナを格納 + # @else + # @brief PostFsmActionType listener array + # The PostFsmActionType listener is stored. + # @endif + self.postaction_num = PostFsmActionListenerType.POST_FSM_ACTION_LISTENER_NUM + self.postaction_ = [PostFsmActionListenerHolder() + for i in range(self.postaction_num)] + + ## + # @if jp + # @brief FsmProfileType + # FsmProfileTypeリスナを格納 + # @else + # @brief FsmProfileType listener array + # The FsmProfileType listener is stored. + # @endif + self.profile_num = FsmProfileListenerType.FSM_PROFILE_LISTENER_NUM + self.profile_ = [FsmProfileListenerHolder() + for i in range(self.profile_num)] + + ## + # @if jp + # @brief FsmStructureTypeリスナ配列 + # FsmStructureTypeリスナを格納 + # @else + # @brief FsmStructureTypelistener array + # The FsmStructureType listener is stored. + # @endif + self.structure_num = FsmStructureListenerType.FSM_STRUCTURE_LISTENER_NUM + self.structure_ = [FsmStructureListenerHolder() + for i in range(self.structure_num)] + + ## + # @if jp + # @brief リスナーの追加 + # + # 指定の種類のPreFsmActionListenerを追加する。 + # + # @param self + # @param ltype リスナの種類 + # @param listener 追加するリスナ + # @return False:指定の種類のリスナが存在しない + # + # @else + # + # @param self + # @param ltype + # @param listener + # @return + # + # @endif + def addPreActionListener(self, ltype, listener): + if ltype < len(self.preaction_): + self.preaction_[ltype].addListener(listener) + return True + return False + + ## + # @if jp + # @brief リスナーの追加 + # + # 指定の種類のPostFsmActionListenerを追加する。 + # + # @param self + # @param ltype リスナの種類 + # @param listener 追加するリスナ + # @return False:指定の種類のリスナが存在しない + # + # @else + # + # @param self + # @param ltype + # @param listener + # @return + # + # @endif + def addPostActionListener(self, ltype, listener): + if ltype < len(self.postaction_): + self.postaction_[ltype].addListener(listener) + return True + return False + + ## + # @if jp + # @brief リスナーの追加 + # + # 指定の種類のFsmProfileListenerを追加する。 + # + # @param self + # @param ltype リスナの種類 + # @param listener 追加するリスナ + # @return False:指定の種類のリスナが存在しない + # + # @else + # + # @param self + # @param ltype + # @param listener + # @return + # + # @endif + def addProfileListener(self, ltype, listener): + if ltype < len(self.profile_): + self.profile_[ltype].addListener(listener) + return True + return False ## # @if jp - # @brief PreFsmActionListenerType - # PreFsmActionListenerTypeꥹʤǼ + # @brief リスナーの追加 + # + # 指定の種類のFsmStructureListenerを追加する。 + # + # @param self + # @param ltype リスナの種類 + # @param listener 追加するリスナ + # @return False:指定の種類のリスナが存在しない + # # @else - # @brief PreFsmActionListenerType listener array - # The PreFsmActionListenerType listener is stored. + # + # @param self + # @param ltype + # @param listener + # @return + # # @endif - self.preaction_num = PreFsmActionListenerType.PRE_FSM_ACTION_LISTENER_NUM - self.preaction_ = [PreFsmActionListenerHolder() - for i in range(self.preaction_num)] + def addStructureListener(self, ltype, listener): + if ltype < len(self.structure_): + self.structure_[ltype].addListener(listener) + return True + return False ## # @if jp - # @brief PostFsmActionTypeꥹ - # PostFsmActionTypeꥹʤǼ + # @brief リスナーの削除 + # + # 指定の種類のPreFsmActionListenerを削除する。 + # + # @param self + # @param ltype リスナの種類 + # @param listener 削除するリスナ + # @return False:指定の種類のリスナが存在しない + # # @else - # @brief PostFsmActionType listener array - # The PostFsmActionType listener is stored. + # + # @param self + # @param ltype + # @param listener + # @return + # # @endif - self.postaction_num = PostFsmActionListenerType.POST_FSM_ACTION_LISTENER_NUM - self.postaction_ = [PostFsmActionListenerHolder() - for i in range(self.postaction_num)] + def removePreActionListener(self, ltype, listener): + if ltype < len(self.preaction_): + self.preaction_[ltype].removeListener(listener) + return True + return False ## # @if jp - # @brief FsmProfileType - # FsmProfileTypeꥹʤǼ + # @brief リスナーの削除 + # + # 指定の種類のPostFsmActionListenerを削除する。 + # + # @param self + # @param ltype リスナの種類 + # @param listener 削除するリスナ + # @return False:指定の種類のリスナが存在しない + # # @else - # @brief FsmProfileType listener array - # The FsmProfileType listener is stored. + # + # @param self + # @param ltype + # @param listener + # @return + # # @endif - self.profile_num = FsmProfileListenerType.FSM_PROFILE_LISTENER_NUM - self.profile_ = [FsmProfileListenerHolder() - for i in range(self.profile_num)] - + def removePostActionListener(self, ltype, listener): + if ltype < len(self.postaction_): + self.postaction_[ltype].removeListener(listener) + return True + return False + + ## + # @if jp + # @brief リスナーの削除 + # + # 指定の種類のFsmProfileListenerを削除する。 + # + # @param self + # @param ltype リスナの種類 + # @param listener 削除するリスナ + # @return False:指定の種類のリスナが存在しない + # + # @else + # + # @param self + # @param ltype + # @param listener + # @return + # + # @endif + def removeProfileListener(self, ltype, listener): + if ltype < len(self.profile_): + self.profile_[ltype].removeListener(listener) + return True + return False + + ## + # @if jp + # @brief リスナーの削除 + # + # 指定の種類のFsmStructureListenerを削除する。 + # + # @param self + # @param ltype リスナの種類 + # @param listener 削除するリスナ + # @return False:指定の種類のリスナが存在しない + # + # @else + # + # @param self + # @param ltype + # @param listener + # @return + # + # @endif + def removeStructureListener(self, ltype, listener): + if ltype < len(self.structure_): + self.structure_[ltype].removeListener(listener) + return True + return False + ## # @if jp - # @brief FsmStructureTypeꥹ - # FsmStructureTypeꥹʤǼ + # @brief リスナーへ通知する + # + # 指定の種類のPreFsmActionListenerのコールバック関数を呼び出す。 + # + # @param self + # @param ltype リスナの種類 + # @param ec_id 実行コンテキストのID + # # @else - # @brief FsmStructureTypelistener array - # The FsmStructureType listener is stored. + # + # @param self + # @param ltype + # @param ec_id + # # @endif - self.structure_num = FsmStructureListenerType.FSM_STRUCTURE_LISTENER_NUM - self.structure_ = [FsmStructureListenerHolder() - for i in range(self.structure_num)] + def notifyPreAction(self, ltype, ec_id): + if ltype < len(self.preaction_): + self.preaction_[ltype].notify(ec_id) + ## + # @if jp + # @brief リスナーへ通知する + # + # 指定の種類のPostFsmActionListenerのコールバック関数を呼び出す。 + # + # @param self + # @param ltype リスナの種類 + # @param ec_id 実行コンテキストのID + # @param ret リターンコード + # + # @else + # + # @param self + # @param ltype + # @param ec_id + # @param ret + # + # @endif + def notifyPostAction(self, ltype, ec_id, ret): + if ltype < len(self.postaction_): + self.postaction_[ltype].notify(ec_id, ret) + + ## + # @if jp + # @brief リスナーへ通知する + # + # 指定の種類のFsmStructureListenerのコールバック関数を呼び出す。 + # + # @param self + # @param ltype リスナの種類 + # @param pprofile ポートプロファイル + # + # @else + # + # @param self + # @param ltype + # @param pprofile + # + # @endif + def notifyProfile(self, ltype, pprofile): + if ltype < len(self.profile_): + self.profile_[ltype].notify(pprofile) + + ## + # @if jp + # @brief リスナーへ通知する + # + # 指定の種類のFsmStructureListenerのコールバック関数を呼び出す。 + # + # @param self + # @param ltype リスナの種類 + # @param ec_id 実行コンテキストのID + # + # @else + # + # @param self + # @param ltype + # @param ec_id + # + # @endif + def notifyStructure(self, ltype, ec_id): + if ltype < len(self.structure_): + self.structure_[ltype].notify(ec_id) diff --git a/OpenRTM_aist/FsmObject.py b/OpenRTM_aist/FsmObject.py index 7cd2873d..63639bb9 100644 --- a/OpenRTM_aist/FsmObject.py +++ b/OpenRTM_aist/FsmObject.py @@ -1,5 +1,5 @@ #!/usr/bin/env python -# -*- coding: euc-jp -*- +# -*- coding: utf-8 -*- ## # @file FsmObject.py @@ -15,74 +15,73 @@ # All rights reserved. - - import OpenRTM_aist -import RTC, RTC__POA +import RTC +import RTC__POA ## # @if jp -# @brief -# FiniteStateMachineΥ١饹 -# 桼RTݡͥȤϡΥ饹ĥ롣 -# RTݡͥȤΥ١Ȥʤ륯饹} +# @brief +# FiniteStateMachineのベースクラス。 +# ユーザが新たなRTコンポーネントを作成する場合は、このクラスを拡張する。 +# 各RTコンポーネントのベースとなるクラス。} # # # @else -# @brief +# @brief # This is a class to be a base of each RT-Component. # This is a implementation class of lightweightRTComponent in Robotic # Technology Component specification # # @endif class FsmObject_impl(RTC__POA.FsmObject): - ## - # @if jp - # @brief 󥹥ȥ饯 - # - # 󥹥ȥ饯 - # - # @param self - # - # @else - # - # @brief Consructor - # - # - # @endif - def __init__(self): - pass + ## + # @if jp + # @brief コンストラクタ + # + # コンストラクタ + # + # @param self + # + # @else + # + # @brief Consructor + # + # + # @endif + def __init__(self): + pass - ## - # @if jp - # @brief - # - # - # - # @param self - # - # @else - #Send a stimulus to an FSM that realizes this interface. - # If the stimulus corresponds to any outgoing transition of the - # current state, that transition shall be taken and the state - # shall change. Any FSM participants associated with the exit of - # the current state, the transition to the new state, or the - # entry to the new state shall be invoked. If the stimulus does - # not correspond to any such transition, this operation shall - # succeed but have no effect. - # - # If the given execution context is a non-nil reference to a - # context in which this FSM participates, the transition shall be - # executed in that context. If the argument is nil, the FSM shall - # choose an EVENT_DRIVEN context in which to execute the - # transition. If the argument is non-nil, but this FSM does not - # participate in the given context, this operation shall fail - # with * ReturnCode_t::BAD_PARAMETER. - # - # @brief Consructor - # - # - # @endif - def send_stimulus(self, ids, id): - return RTC.RTC_OK + ## + # @if jp + # @brief + # + # + # + # @param self + # + # @else + # Send a stimulus to an FSM that realizes this interface. + # If the stimulus corresponds to any outgoing transition of the + # current state, that transition shall be taken and the state + # shall change. Any FSM participants associated with the exit of + # the current state, the transition to the new state, or the + # entry to the new state shall be invoked. If the stimulus does + # not correspond to any such transition, this operation shall + # succeed but have no effect. + # + # If the given execution context is a non-nil reference to a + # context in which this FSM participates, the transition shall be + # executed in that context. If the argument is nil, the FSM shall + # choose an EVENT_DRIVEN context in which to execute the + # transition. If the argument is non-nil, but this FSM does not + # participate in the given context, this operation shall fail + # with * ReturnCode_t::BAD_PARAMETER. + # + # @brief Consructor + # + # + # @endif + def send_stimulus(self, ids, id): + return RTC.RTC_OK diff --git a/OpenRTM_aist/GlobalFactory.py b/OpenRTM_aist/GlobalFactory.py index 8f60cc9b..c5a652e4 100644 --- a/OpenRTM_aist/GlobalFactory.py +++ b/OpenRTM_aist/GlobalFactory.py @@ -1,5 +1,5 @@ #!/usr/bin/env python -# -*- coding: euc-jp -*- +# -*- coding: utf-8 -*- ## # @file GlobalFactory.py @@ -17,297 +17,86 @@ # - - - class Factory: - """ - """ - - FACTORY_OK = 0 - FACTORY_ERROR = 1 - ALREADY_EXISTS = 2 - NOT_FOUND = 3 - INVALID_ARG = 4 - UNKNOWN_ERROR = 5 - - ## - # @if jp - # - # @class FactoryEntry - # @brief FactoryEntry 饹 - # - # @else - # - # @class FactoryEntry - # @brief FactoryEntry class - # - # @endif - class FactoryEntry: """ """ - ## - # @if jp - # - # @brief 󥹥ȥ饯 - # - # 󥹥ȥ饯 - # - # @param creator ꥨѥե󥯥 - # @param destructor ǥȥ饯ѥե󥯥 - # - # @else - # - # @brief Constructor - # - # Constructor - # - # @param creator Functor for creator. - # @param destructor Functor for destructor. - # - # @endif - # FactoryEntry(Identifier id, Creator creator, Destructor destructor) - def __init__(self, id, creator, destructor): - self.id_ = id - self.creator_ = creator - self.destructor_ = destructor - return - - - def __init__(self): - self._creators = {} - self._objects = {} - - - ## bool hasFactory(const Identifier& id) - def hasFactory(self, id): - if not id in self._creators: - return False - return True - - - ## std::vector getIdentifiers() - def getIdentifiers(self): - idlist = [] - - for id in self._creators.keys(): - idlist.append(id) - idlist.sort() - return idlist + FACTORY_OK = 0 + FACTORY_ERROR = 1 + ALREADY_EXISTS = 2 + NOT_FOUND = 3 + INVALID_ARG = 4 + UNKNOWN_ERROR = 5 + def __init__(self): + self._creators = {} - ## ReturnCode addFactory(const Identifier& id, - ## Creator creator, - ## Destructor destructor) - def addFactory(self, id, creator, destructor): - if not creator or not destructor: - return self.INVALID_ARG + # bool hasFactory(const Identifier& id) - if id in self._creators: - return self.ALREADY_EXISTS - - self._creators[id] = Factory.FactoryEntry(id, creator, destructor) - return self.FACTORY_OK + def hasFactory(self, id): + if not id in self._creators: + return False + return True + # std::vector getIdentifiers() - ## ReturnCode removeFactory(const Identifier& id) - def removeFactory(self, id): - if not id in self._creators: - return self.NOT_FOUND + def getIdentifiers(self): + idlist = [] - del self._creators[id] - return self.FACTORY_OK + for id in self._creators.keys(): + idlist.append(id) + idlist.sort() + return idlist + # ReturnCode addFactory(const Identifier& id, + # Creator creator) - ## AbstractClass* createObject(const Identifier& id) - def createObject(self, id): - if not id in self._creators: - print("Factory.createObject return None id: ", id) - return None - obj_ = self._creators[id].creator_() - #assert(not obj_ in self._objects) - self._objects[obj_] = self._creators[id] - return obj_ + def addFactory(self, id, creator): + if not creator: + return self.INVALID_ARG + if id in self._creators: + return self.ALREADY_EXISTS - ## ReturnCode deleteObject(const Identifier& id, AbstractClass*& obj) - def deleteObject(self, obj, id=None): - if id: - if id in self._creators: - self._creators[id].destructor_(obj) - del self._objects[obj] + self._creators[id] = creator return self.FACTORY_OK - if not obj in self._objects: - return self.NOT_FOUND + # ReturnCode removeFactory(const Identifier& id) - tmp = obj - self._objects[obj].destructor_(obj) - del self._objects[tmp] - return self.FACTORY_OK + def removeFactory(self, id): + if not id in self._creators: + return self.NOT_FOUND + del self._creators[id] + return self.FACTORY_OK - ## - # @if jp - # - # @brief Ѥߥ֥ȥꥹȤμ - # - # Υեȥ줿֥ȤΥꥹȤ롣 - # - # @return Ѥߥ֥ȥꥹ - # - # @else - # - # @brief Getting created objects - # - # This operation returns a list of created objects by the factory. - # - # @return created object list - # - # @endif - # std::vector createdObjects() - def createdObjects(self): - objects_ = [] - for id_ in self._objects.keys(): - objects_.append(id_) - - return objects_ - - - ## - # @if jp - # - # @brief ֥ȤΥեȥʪɤĴ٤ - # - # @param obj оݥ֥ - # @return true: Υեȥʪ - # false: ΥեȥʪǤϤʤ - # - # @else - # - # @brief Whether a object is a product of this factory - # - # @param obj A target object - # @return true: The object is a product of the factory - # false: The object is not a product of the factory - # - # @return created object list - # - # @endif - # bool isProducerOf(AbstractClass* obj) - def isProducerOf(self, obj): - return obj in self._objects - - - ## - # @if jp - # - # @brief ֥Ȥ饯饹̻(ID) - # - # ֥ȤΥ饹̻(ID)롣 - # - # @param obj [in] 饹̻(ID)֥ - # @param id [out] 饹̻(ID) - # @return ꥿󥳡 NOT_FOUND: ̻Ҥ¸ߤʤ - # FACTORY_OK: ェλ - # @else - # - # @brief Getting class identifier (ID) from a object - # - # This operation returns a class identifier (ID) from a object. - # - # @param obj [in] An object to investigate its class ID. - # @param id [out] Class identifier (ID) - # @return Return code NOT_FOUND: ID not found - # FACTORY_OK: normal return - # @endif - # ReturnCode objectToIdentifier(AbstractClass* obj, Identifier& id) - def objectToIdentifier(self, obj, id): - if not obj in self._objects: - return self.NOT_FOUND - - id[0] = self._objects[obj].id_ - return self.FACTORY_OK - - - ## - # @if jp - # - # @brief ֥ȤΥ󥹥ȥ饯 - # - # Υեȥ줿֥ȤΥ󥹥ȥ饯롣 - # obj ϤΥեȥ줿ΤǤʤФʤʤͽ - # isProducerOf() ؿ֥ȤΥեȥʪ - # 뤫ɤåʤФʤʤ - # - # @return ֥ȤΥǥȥ饯 - # - # @else - # - # @brief Getting destructor of the object - # - # This operation returns a constructor of the object created by - # the factory. obj must be a product of the factory. User must - # check if the object is a product of the factory by using - # isProducerOf()-function, before using this function. - # - # @return destructor of the object - # - # @endif - #Creator objectToCreator(AbstractClass* obj) - def objectToCreator(self, obj): - return self._objects[obj].creator_ - + # AbstractClass* createObject(const Identifier& id) - ## - # @if jp - # - # @brief ֥ȤΥǥȥ饯 - # - # Υեȥ줿֥ȤΥǥȥ饯롣 - # obj ϤΥեȥ줿ΤǤʤФʤʤͽ - # isProducerOf() ؿ֥ȤΥեȥʪ - # 뤫ɤåʤФʤʤ - # - # @return ֥ȤΥǥȥ饯 - # - # @else - # - # @brief Getting destructor of the object - # - # This operation returns a destructor of the object created by - # the factory. obj must be a product of the factory. User must - # check if the object is a product of the factory by using - # isProducerOf()-function, before using this function. - # - # @return destructor of the object - # - # @endif - #Destructor objectToDestructor(AbstractClass* obj) - def objectToDestructor(self, obj): - return self._objects[obj].destructor_ + def createObject(self, id): + if not id in self._creators: + print("Factory.createObject return None id: ", id) + return None + obj_ = self._creators[id]() + return obj_ - gfactory = None -class GlobalFactory(Factory): - def __init__(self): - Factory.__init__(self) - pass +class GlobalFactory(Factory): + def __init__(self): + Factory.__init__(self) + pass - def instance(): - global gfactory - - if gfactory is None: - gfactory = GlobalFactory() + def instance(): + global gfactory - return gfactory + if gfactory is None: + gfactory = GlobalFactory() - instance = staticmethod(instance) + return gfactory + instance = staticmethod(instance) - def __del__(self): - pass + def __del__(self): + pass diff --git a/OpenRTM_aist/Guard.py b/OpenRTM_aist/Guard.py index 8dcf17c4..914f3171 100644 --- a/OpenRTM_aist/Guard.py +++ b/OpenRTM_aist/Guard.py @@ -1,5 +1,5 @@ #!/usr/bin/env python -# -*- coding: euc-jp -*- +# -*- coding: utf-8 -*- ## # @file Guard.py @@ -20,9 +20,9 @@ ## # @if jp # @class ScopedLock -# @brief ScopedLock 饹 +# @brief ScopedLock クラス # -# ¾ѥå饹 +# 排他処理用ロッククラス。 # # @since 0.4.0 # @@ -30,37 +30,36 @@ # # @endif class ScopedLock: - """ - """ + """ + """ - ## - # @if jp - # @brief 󥹥ȥ饯 - # - # 󥹥ȥ饯 - # - # @param self - # @param mutex åѥߥ塼ƥå - # - # @else - # - # @endif - def __init__(self, mutex): - self.mutex = mutex - self.mutex.acquire() + ## + # @if jp + # @brief コンストラクタ + # + # コンストラクタ + # + # @param self + # @param mutex ロック用ミューテックス + # + # @else + # + # @endif + def __init__(self, mutex): + self.mutex = mutex + self.mutex.acquire() + ## + # @if jp + # @brief デストラクタ + # + # デストラクタ + # + # @param self + # + # @else + # + # @endif - ## - # @if jp - # @brief ǥȥ饯 - # - # ǥȥ饯 - # - # @param self - # - # @else - # - # @endif - def __del__(self): - self.mutex.release() - + def __del__(self): + self.mutex.release() diff --git a/OpenRTM_aist/InPort.py b/OpenRTM_aist/InPort.py index adf3bde1..eeb3a75d 100644 --- a/OpenRTM_aist/InPort.py +++ b/OpenRTM_aist/InPort.py @@ -1,12 +1,12 @@ #!/usr/bin/env python -# -*- coding: euc-jp -*- +# -*- coding: utf-8 -*- ## # @file InPort.py # @brief InPort template class # @date $Date: 2007/09/20 $ # @author Noriaki Ando and Shinji Kurihara -# +# # Copyright (C) 2003-2008 # Task-intelligence Research Group, # Intelligent Systems Research Institute, @@ -15,7 +15,6 @@ # All rights reserved. - import copy @@ -27,15 +26,15 @@ # # @class InPort # -# @brief InPort 饹 -# -# InPort μ饹 -# InPort ˥󥰥Хåե줿ǡ缡 -# Υ󥰥Хåե˳Ǽ롣󥰥ХåեΥϥǥեȤ64 -# ʤäƤ뤬󥹥ȥ饯ˤꥵꤹ뤳ȤǤ롣 -# ǡϥե饰ˤä̤ɡɾ֤졢isNew(), getNewDataLen() -# getNewList(), getNewListReverse() Υ᥽åɤˤϥɥ󥰤뤳Ȥ -# Ǥ롣 +# @brief InPort クラス +# +# InPort の実装クラス。 +# InPort は内部にリングバッファを持ち、外部から送信されたデータを順次 +# このリングバッファに格納する。リングバッファのサイズはデフォルトで64と +# なっているが、コンストラクタ引数によりサイズを指定することができる。 +# データはフラグによって未読、既読状態が管理され、isNew(), getNewDataLen() +# getNewList(), getNewListReverse() 等のメソッドによりハンドリングすることが +# できる。 # # @since 0.2.0 # @@ -50,437 +49,427 @@ # port from other components, using this template. # This is class template. This class have to be incarnated class as port # value types. This value types are previously define RtComponent IDL. -# ex. type T: TimedFload, TimedLong etc... +# ex. type T: TimedFload, TimedLong etc... # # @since 0.2.0 # # @endif + + class InPort(OpenRTM_aist.InPortBase): - """ - """ - - - - ## - # @if jp - # - # @brief 󥹥ȥ饯 - # - # 󥹥ȥ饯 - # - # @param self - # @param name InPort ̾InPortBase:name() ˤ껲Ȥ롣 - # @param value InPort ˥Хɤѿ - # @param read_block ɹ֥åե饰 - # ǡɹ̤ɥǡʤ硢Υǡޤǥ֥å - # ɤ(ǥե:False) - # @param write_block ֥åե饰 - # ǡ˥ХåեեǤä硢Хåե˶Ǥ - # ޤǥ֥å뤫ɤ(ǥե:False) - # @param read_timeout ɹ֥åꤷƤʤΡǡɼ西 - # Ȼ(ߥ)(ǥե:0) - # @param write_timeout ֥åꤷƤʤΡǡ - # Ȼ(ߥ)(ǥե:0) - # - # @else - # - # @brief A constructor. - # - # Setting channel name and registering channel value. - # - # @param self - # @param name A name of the InPort. This name is referred by - # InPortBase::name(). - # @param value A channel value related with the channel. - # @param read_block - # @param write_block - # @param read_timeout - # @param write_timeout - # - # @endif - def __init__(self, name, value, buffer=None, - read_block=False, write_block=False, - read_timeout=0, write_timeout = 0): - OpenRTM_aist.InPortBase.__init__(self, name, OpenRTM_aist.toTypename(value)) - self._name = name - self._value = value - self._OnRead = None - self._OnReadConvert = None - - self._directNewData = False - self._valueMutex = threading.RLock() - - self.addConnectorDataListener(OpenRTM_aist.ConnectorDataListenerType.ON_RECEIVED, OpenRTM_aist.Timestamp("on_received")) - self.addConnectorDataListener(OpenRTM_aist.ConnectorDataListenerType.ON_BUFFER_READ, OpenRTM_aist.Timestamp("on_read")) - - - - def __del__(self, InPortBase=OpenRTM_aist.InPortBase): - InPortBase.__del__(self) - return - - ## - # @if jp - # @brief ݡ̾Τ롣 - # - # ݡ̾Τ롣 - # - # @param self - # - # @return ݡ̾ - # - # @else - # - # @endif - # - # const char* name() - def name(self): - return self._name - - - ## - # @if jp - # @brief ǿǡǧ - # - # ߤΥХåե֤˳ǼƤǡǿǡǧ롣 - # - # @param self - # - # @return ǿǡǧ - # ( true:ǿǡǡϤޤɤ߽ФƤʤ - # false:Υǡǡϴɤ߽ФƤ) - # - # @else - # - # @endif - # - # bool isNew() - def isNew(self, names=None): - self._rtcout.RTC_TRACE("isNew()") - - - guard = OpenRTM_aist.ScopedLock(self._valueMutex) - if self._directNewData == True: - self._rtcout.RTC_TRACE("isNew() returns true because of direct write.") - return True - del guard - - if len(self._connectors) == 0: - self._rtcout.RTC_DEBUG("no connectors") - return False - - if names is None: - r = self._connectors[0].getBuffer().readable() - if r > 0: - self._rtcout.RTC_DEBUG("isNew() = True, readable data: %d",r) - return True - else: - self._rtcout.RTC_DEBUG("isNew() = False, no readable data") - return False - elif isinstance(names, str): - for con in self._connectors: - if con.name() == names: - r = con.getBuffer().readable() - if r > 0: - self._rtcout.RTC_DEBUG("isNew() = True, connector name: %s, readable data: %d",(names, r)) + """ + """ + + ## + # @if jp + # + # @brief コンストラクタ + # + # コンストラクタ。 + # + # @param self + # @param name InPort 名。InPortBase:name() により参照される。 + # @param value この InPort にバインドされる変数 + # + # @else + # + # @brief A constructor. + # + # Setting channel name and registering channel value. + # + # @param self + # @param name A name of the InPort. This name is referred by + # InPortBase::name(). + # @param value A channel value related with the channel. + # + # @endif + def __init__(self, name, value): + OpenRTM_aist.InPortBase.__init__( + self, name, OpenRTM_aist.toTypename(value)) + self._name = name + self._value = value + self._OnRead = None + self._OnReadConvert = None + + self._directNewData = False + self._valueMutex = threading.RLock() + + marshaling_types = OpenRTM_aist.SerializerFactories.instance().getSerializerList(value) + marshaling_types = OpenRTM_aist.flatten(marshaling_types).lstrip() + self.addProperty("dataport.marshaling_types", marshaling_types) + + self._listeners.setDataType(copy.deepcopy(value)) + self._listeners.setPortType(OpenRTM_aist.PortType.InPortType) + + self.addConnectorDataListener( + OpenRTM_aist.ConnectorDataListenerType.ON_RECEIVED, + OpenRTM_aist.Timestamp("on_received")) + self.addConnectorDataListener( + OpenRTM_aist.ConnectorDataListenerType.ON_BUFFER_READ, + OpenRTM_aist.Timestamp("on_read")) + + def __del__(self, InPortBase=OpenRTM_aist.InPortBase): + InPortBase.__del__(self) + return + + ## + # @if jp + # @brief ポート名称を取得する。 + # + # ポート名称を取得する。 + # + # @param self + # + # @return ポート名称 + # + # @else + # + # @endif + # + # const char* name() + def name(self): + return self._name + + ## + # @if jp + # @brief 最新データか確認 + # + # 現在のバッファ位置に格納されているデータが最新データか確認する。 + # + # @param self + # + # @return 最新データ確認結果 + # ( true:最新データ.データはまだ読み出されていない + # false:過去のデータ.データは既に読み出されている) + # + # @else + # + # @endif + # + # bool isNew() + + def isNew(self, names=None): + self._rtcout.RTC_TRACE("isNew()") + + guard = OpenRTM_aist.ScopedLock(self._valueMutex) + if self._directNewData == True: + self._rtcout.RTC_TRACE( + "isNew() returns true because of direct write.") return True - else: - self._rtcout.RTC_DEBUG("isNew() = False, connector name: %s, no readable data",names) + del guard + + if not self._connectors: + self._rtcout.RTC_DEBUG("no connectors") return False - elif isinstance(names, list): - del names[:] - for con in self._connectors: - r = con.getBuffer().readable() - if r > 0: - self._rtcout.RTC_DEBUG("isNew() = True, connector name: %s, readable data: %d",(names, r)) - names.append(con.name()) - if len(names) > 0: - return True - else: - self._rtcout.RTC_DEBUG("isNew() = False, no readable data") + + if names is None: + r = self._connectors[0].getBuffer().readable() + if r > 0: + self._rtcout.RTC_DEBUG("isNew() = True, readable data: %d", r) + return True + else: + self._rtcout.RTC_DEBUG("isNew() = False, no readable data") + return False + elif isinstance(names, str): + for con in self._connectors: + if con.name() == names: + r = con.getBuffer().readable() + if r > 0: + self._rtcout.RTC_DEBUG( + "isNew() = True, connector name: %s, readable data: %d", (names, r)) + return True + else: + self._rtcout.RTC_DEBUG( + "isNew() = False, connector name: %s, no readable data", names) + return False + elif isinstance(names, list): + del names[:] + for con in self._connectors: + r = con.getBuffer().readable() + if r > 0: + self._rtcout.RTC_DEBUG( + "isNew() = True, connector name: %s, readable data: %d", (names, r)) + names.append(con.name()) + if names: + return True + else: + self._rtcout.RTC_DEBUG("isNew() = False, no readable data") + return False + + self._rtcout.RTC_ERROR("isNew() = False, Unknown Errow") return False - - - self._rtcout.RTC_ERROR("isNew() = False, Unknown Errow") - return False - - - ## - # @if jp - # - # @brief Хåեɤǧ - # - # InPortΥХåեɤ bool ֤ͤ - # ξ true, ̤ɥǡ false ֤ - # - # @return true Хåե϶ - # false Хåե̤ɥǡ - # - # @else - # - # @brief Check whether the data is newest - # - # Check whether the data stored at a current buffer position is newest. - # - # @return Newest data check result - # ( true:Newest data. Data has not been readout yet. - # false:Past dataData has already been readout.) - # - # @endif - # - # bool isEmpty() - def isEmpty(self, names=None): - self._rtcout.RTC_TRACE("isEmpty()") - if self._directNewData == True: - return False - if len(self._connectors) == 0: - self._rtcout.RTC_DEBUG("no connectors") - return True - - if names is None: - r = self._connectors[0].getBuffer().readable() - if r == 0: - self._rtcout.RTC_DEBUG("isEmpty() = true, buffer is empty") - return True - elif isinstance(names, str): - for con in self._connectors: - if con.name() == names: - r = con.getBuffer().readable() - if r == 0: - self._rtcout.RTC_DEBUG("isEmpty() = True, connector name: %s, buffer is empty",(names)) - return True - else: - self._rtcout.RTC_DEBUG("isEmpty() = False, connector name: %s, readable data: %d",(names,r)) + + ## + # @if jp + # + # @brief バッファが空かどうか確認する + # + # InPortのバッファが空かどうかを bool 値で返す。 + # 空の場合は true, 未読データがある場合は false を返す。 + # + # @return true バッファは空 + # false バッファに未読データがある + # + # @else + # + # @brief Check whether the data is newest + # + # Check whether the data stored at a current buffer position is newest. + # + # @return Newest data check result + # ( true:Newest data. Data has not been readout yet. + # false:Past data.Data has already been readout.) + # + # @endif + # + # bool isEmpty() + + def isEmpty(self, names=None): + self._rtcout.RTC_TRACE("isEmpty()") + if self._directNewData == True: return False - elif isinstance(names, list): - del names[:] - for con in self._connectors: - r = con.getBuffer().readable() - if r == 0: - self._rtcout.RTC_DEBUG("isEmpty() = True, connector name: %s",(names)) - names.append(con.name()) - if len(names) > 0: - return True - else: - self._rtcout.RTC_DEBUG("isEmpty() = False, no readable data") - return False - - self._rtcout.RTC_DEBUG("isEmpty() = false, data exists in the buffer") - return False - - - ## - # @if jp - # - # @brief DataPort ͤɤ߽Ф - # - # InPort˽񤭹ޤ줿ǡɤߤ³0ޤϥХåե - # ǡ񤭹ޤƤʤ֤ɤߤͤǤ롣 - # Хåեξ֤ΤȤ - # ꤵ줿⡼ (readback, do_nothing, block) ˱ơ - # ʲΤ褦ư򤹤롣 - # - # - readback: Ǹͤɤߤʤ - # - # - do_nothing: ⤷ʤ - # - # - block: ֥å롣ॢȤꤵƤϡ - # ॢȤޤԤġ - # - # Хåեξ֤ǤϡInPort˥Хɤ줿ѿ֤ͤ롣 - # äơɤ߽Фˤ֤ͤǽ롣 - # δؿѤݤˤϡ - # - # - isNew(), isEmpty() ʻѤ˥Хåե֤å롣 - # - # - ɤ߽Ф֤ͤʤ褦˥Хѿ˽ - # - # - # ƥХåؿϰʲΤ褦˸ƤӽФ롣 - # - OnRead: read() ؿƤФݤɬƤФ롣 - # - # - OnReadConvert: ǡɤ߽Ф硢ɤߤǡ - # ȤOnReadConvertƤӽФ졢ͤread() - # Ȥ֤ - # - # - OnEmpty: ХåեΤǡɤ߽Ф˼ԤƤӽФ롣 - # OnEmpty ͤ read() ͤȤ֤ - # - # - OnBufferTimeout: ǡեPushξˡɤ߽Ф - # ॢȤΤ˥ǡɤ߽Ф˼Ԥ˸ƤФ롣 - # - # - OnRecvTimeout: ǡեPullξˡɤ߽Фॢ - # Τ˥ǡɤ߽Ф˼Ԥ˸ƤФ롣 - # - # - OnReadError: 嵭ʳͳɤߤ˼Ԥ˸ƤФ롣 - # ͳȤƤϡХåե硢㳰ȯʤɤͤ - # ̾ϵꤨʤХβǽ롣 - # - # @return ɤ߽Фǡ - # - # @else - # - # @brief Readout the value from DataPort - # - # Readout the value from DataPort - # - # - When Callback functor OnRead is already set, OnRead will be invoked - # before reading from the buffer held by DataPort. - # - When the buffer held by DataPort can detect the underflow, - # and when it detected the underflow at reading, callback functor - # OnUnderflow will be invoked. - # - When callback functor OnReadConvert is already set, the return value of - # operator() of OnReadConvert will be the return value of read(). - # - When timeout of reading is already set by setReadTimeout(), - # it waits for only timeout time until the state of the buffer underflow - # is reset, and if OnUnderflow is already set, this will be invoked to - # return. - # - # @return Readout data - # - # @endif - # - # DataType read() - def read(self, name=None): - self._rtcout.RTC_TRACE("DataType read()") - - if self._OnRead is not None: - self._OnRead() - self._rtcout.RTC_TRACE("OnRead called") - - guard = OpenRTM_aist.ScopedLock(self._valueMutex) - if self._directNewData == True: - - self._rtcout.RTC_TRACE("Direct data transfer") - if self._OnReadConvert is not None: - self._value = self._OnReadConvert(self._value) - self._rtcout.RTC_TRACE("OnReadConvert for direct data called") - self._directNewData = False - return self._value - del guard - - - - - if len(self._connectors) == 0: - self._rtcout.RTC_DEBUG("no connectors") - return self._value - - _val = copy.deepcopy(self._value) - cdr = [_val] - - - if name is None: - ret = self._connectors[0].read(cdr) - else: - ret = OpenRTM_aist.DataPortStatus.PRECONDITION_NOT_MET - for con in self._connectors: - if con.name() == name: - ret = con.read(cdr) - if ret == OpenRTM_aist.DataPortStatus.PRECONDITION_NOT_MET: - self._rtcout.RTC_DEBUG("not found %s",name) - return self._value + if not self._connectors: + self._rtcout.RTC_DEBUG("no connectors") + return True + if names is None: + r = self._connectors[0].getBuffer().readable() + if r == 0: + self._rtcout.RTC_DEBUG("isEmpty() = true, buffer is empty") + return True + elif isinstance(names, str): + for con in self._connectors: + if con.name() == names: + r = con.getBuffer().readable() + if r == 0: + self._rtcout.RTC_DEBUG( + "isEmpty() = True, connector name: %s, buffer is empty", (names)) + return True + else: + self._rtcout.RTC_DEBUG( + "isEmpty() = False, connector name: %s, readable data: %d", (names, r)) + return False + elif isinstance(names, list): + del names[:] + for con in self._connectors: + r = con.getBuffer().readable() + if r == 0: + self._rtcout.RTC_DEBUG( + "isEmpty() = True, connector name: %s", (names)) + names.append(con.name()) + if names: + return True + else: + self._rtcout.RTC_DEBUG("isEmpty() = False, no readable data") + return False - if ret == OpenRTM_aist.DataPortStatus.PORT_OK: - self._rtcout.RTC_DEBUG("data read succeeded") - self._value = cdr[0] + self._rtcout.RTC_DEBUG("isEmpty() = false, data exists in the buffer") + return False - if self._OnReadConvert is not None: - self._value = self._OnReadConvert(self._value) - self._rtcout.RTC_DEBUG("OnReadConvert called") + ## + # @if jp + # + # @brief DataPort から値を読み出す + # + # InPortに書き込まれたデータを読みだす。接続数が0、またはバッファに + # データが書き込まれていない状態で読みだした場合の戻り値は不定である。 + # バッファが空の状態のとき、 + # 事前に設定されたモード (readback, do_nothing, block) に応じて、 + # 以下のような動作をする。 + # + # - readback: 最後の値を読みなおす。 + # + # - do_nothing: 何もしない + # + # - block: ブロックする。タイムアウトが設定されている場合は、 + # タイムアウトするまで待つ。 + # + # バッファが空の状態では、InPortにバインドされた変数の値が返される。 + # したがって、初回読み出し時には不定値を返す可能性がある。 + # この関数を利用する際には、 + # + # - isNew(), isEmpty() と併用し、事前にバッファ状態をチェックする。 + # + # - 初回読み出し時に不定値を返さないようにバインド変数を事前に初期化する + # + # + # 各コールバック関数は以下のように呼び出される。 + # - OnRead: read() 関数が呼ばれる際に必ず呼ばれる。 + # + # - OnReadConvert: データの読み出しが成功した場合、読みだしたデータを + # 引数としてOnReadConvertが呼び出され、戻り値をread()が戻り値 + # として返す。 + # + # - OnEmpty: バッファが空のためデータの読み出しに失敗した場合呼び出される。 + # OnEmpty の戻り値を read() の戻り値として返す。 + # + # - OnBufferTimeout: データフロー型がPush型の場合に、読み出し + # タイムアウトのためにデータの読み出しに失敗した場合に呼ばれる。 + # + # - OnRecvTimeout: データフロー型がPull型の場合に、読み出しタイムアウト + # のためにデータ読み出しに失敗した場合に呼ばれる。 + # + # - OnReadError: 上記以外の理由で読みだしに失敗した場合に呼ばれる。 + # 理由としては、バッファ設定の不整合、例外の発生などが考えられる + # が通常は起こりえないためバグの可能性がある。 + # + # @return 読み出したデータ + # + # @else + # + # @brief Readout the value from DataPort + # + # Readout the value from DataPort + # + # - When Callback functor OnRead is already set, OnRead will be invoked + # before reading from the buffer held by DataPort. + # - When the buffer held by DataPort can detect the underflow, + # and when it detected the underflow at reading, callback functor + # OnUnderflow will be invoked. + # - When callback functor OnReadConvert is already set, the return value of + # operator() of OnReadConvert will be the return value of read(). + # - When timeout of reading is already set by setReadTimeout(), + # it waits for only timeout time until the state of the buffer underflow + # is reset, and if OnUnderflow is already set, this will be invoked to + # return. + # + # @return Readout data + # + # @endif + # + # DataType read() + + def read(self, name=None): + self._rtcout.RTC_TRACE("DataType read()") + + if self._OnRead is not None: + self._OnRead() + self._rtcout.RTC_TRACE("OnRead called") + + guard = OpenRTM_aist.ScopedLock(self._valueMutex) + if self._directNewData == True: + + self._rtcout.RTC_TRACE("Direct data transfer") + if self._OnReadConvert is not None: + self._value = self._OnReadConvert(self._value) + self._rtcout.RTC_TRACE("OnReadConvert for direct data called") + self._directNewData = False + return self._value + del guard + + if not self._connectors: + self._rtcout.RTC_DEBUG("no connectors") + return self._value + + _val = copy.deepcopy(self._value) + + if name is None: + ret, _val = self._connectors[0].read(_val) + else: + ret = OpenRTM_aist.DataPortStatus.PRECONDITION_NOT_MET + for con in self._connectors: + if con.name() == name: + ret, _val = con.read(_val) + if ret == OpenRTM_aist.DataPortStatus.PRECONDITION_NOT_MET: + self._rtcout.RTC_DEBUG("not found %s", name) + return self._value + + if ret == OpenRTM_aist.DataPortStatus.PORT_OK: + self._rtcout.RTC_DEBUG("data read succeeded") + self._value = _val + + if self._OnReadConvert is not None: + self._value = self._OnReadConvert(self._value) + self._rtcout.RTC_DEBUG("OnReadConvert called") + return self._value + return self._value + + elif ret == OpenRTM_aist.DataPortStatus.BUFFER_EMPTY: + self._rtcout.RTC_WARN("buffer empty") + return self._value + + elif ret == OpenRTM_aist.DataPortStatus.BUFFER_TIMEOUT: + self._rtcout.RTC_WARN("buffer read timeout") + return self._value + + self._rtcout.RTC_ERROR("unknown retern value from buffer.read()") return self._value - return self._value - - elif ret == OpenRTM_aist.DataPortStatus.BUFFER_EMPTY: - self._rtcout.RTC_WARN("buffer empty") - return self._value - - elif ret == OpenRTM_aist.DataPortStatus.BUFFER_TIMEOUT: - self._rtcout.RTC_WARN("buffer read timeout") - return self._value - - self._rtcout.RTC_ERROR("unknown retern value from buffer.read()") - return self._value - - - ## - # @if jp - # - # @brief Хɤ줿ѿ InPort Хåեκǿͤɤ߹ - # - # Хɤ줿ǡ InPort κǿͤɤ߹ࡣ - # 󥹥ȥ饯ѿ InPort ХɤƤʤФʤʤ - # Υ᥽åɤϥݥ⡼եå˻ѤȤƤ뤿ᡢ - # ˰¸ʤͤȤʤäƤ롣 - # - # @param self - # - # @else - # - # @brief Read into bound T-type data from current InPort - # - # @endif - def update(self): - self.read() - - - ## - # @if jp - # - # @brief InPort Хåեإǡɤ߹߻ΥХå - # - # InPort ĥХåեǡɤ߹ޤľ˸ƤФ륳Хå - # ֥Ȥꤹ롣 - # - # @param self - # @param on_read оݥХå֥ - # - # @else - # - # @endif - def setOnRead(self, on_read): - self._OnRead = on_read - - - ## - # @if jp - # - # @brief InPort Хåեإǡɤ߽ФΥХå - # - # InPort ĥХåեǡɤ߽Фݤ˸ƤФ륳Хå - # ֥Ȥꤹ롣Хå֥Ȥͤread()᥽å - # θƽз̤Ȥʤ롣 - # - # @param self - # @param on_rconvert оݥХå֥ - # - # @else - # - # @endif - def setOnReadConvert(self, on_rconvert): - self._OnReadConvert = on_rconvert - - ## - # @if jp - # - # @brief ǡ쥯Ȥ˽񤭹 - # - # @param self - # @param data 񤭹ǡ - # - # @else - # @brief - # - # @param self - # @param data - # @endif - # void write(const DataType& data) - def write(self, data): - guard = OpenRTM_aist.ScopedLock(self._valueMutex) - self._value = data - self._directNewData = True - del guard - - - \ No newline at end of file + + ## + # @if jp + # + # @brief バインドされた変数に InPort バッファの最新値を読み込む + # + # バインドされたデータに InPort の最新値を読み込む。 + # コンストラクタで変数と InPort がバインドされていなければならない。 + # このメソッドはポリモーフィックに使用される事を前提としているため、 + # 型に依存しない引数、戻り値となっている。 + # + # @param self + # + # @else + # + # @brief Read into bound T-type data from current InPort + # + # @endif + + def update(self): + self.read() + + ## + # @if jp + # + # @brief InPort バッファへデータ読み込み時のコールバックの設定 + # + # InPort が持つバッファからデータが読み込まれる直前に呼ばれるコールバック + # オブジェクトを設定する。 + # + # @param self + # @param on_read 設定対象コールバックオブジェクト + # + # @else + # + # @endif + + def setOnRead(self, on_read): + self._OnRead = on_read + + ## + # @if jp + # + # @brief InPort バッファへデータ読み出し時のコールバックの設定 + # + # InPort が持つバッファからデータが読み出される際に呼ばれるコールバック + # オブジェクトを設定する。コールバックオブジェクトの戻り値がread()メソッド + # の呼出結果となる。 + # + # @param self + # @param on_rconvert 設定対象コールバックオブジェクト + # + # @else + # + # @endif + + def setOnReadConvert(self, on_rconvert): + self._OnReadConvert = on_rconvert + + ## + # @if jp + # + # @brief データをダイレクトに書き込む + # + # @param self + # @param data 書き込むデータ + # + # @else + # @brief + # + # @param self + # @param data + # @endif + # void write(const DataType& data) + def write(self, data): + guard = OpenRTM_aist.ScopedLock(self._valueMutex) + self._value = data + self._directNewData = True + del guard diff --git a/OpenRTM_aist/InPortBase.py b/OpenRTM_aist/InPortBase.py index 5f36eadd..b1e238df 100644 --- a/OpenRTM_aist/InPortBase.py +++ b/OpenRTM_aist/InPortBase.py @@ -1,5 +1,5 @@ #!/usr/bin/env python -# -*- coding: euc-jp -*- +# -*- coding: utf-8 -*- ## # @file InPortBase.py @@ -25,7 +25,7 @@ # @if jp # @namespace RTC # -# @brief RTݡͥ +# @brief RTコンポーネント # # @else # @@ -39,9 +39,9 @@ ## # @if jp # @class InPortBase -# @brief InPort Port +# @brief InPort 用 Port # -# ǡϥݡȤμ饹 +# データ入力ポートの実装クラス。 # # @since 0.4.0 # @@ -55,1276 +55,1429 @@ # # @endif # + + class InPortBase(OpenRTM_aist.PortBase, OpenRTM_aist.DataPortStatus): - """ - """ - - ## - # @if jp - # @brief 󥹥ȥ饯 - # - # 󥹥ȥ饯 - # - # @param name ݡ̾ - # @param inport ǡϥݡȤ˴ϢդInPort֥ - # InPort֥ȤǰǡХåեפꤹ - # @param prop ݡѥץѥƥ - # - # @else - # @brief Constructor - # - # Constructor - # - # @param name Port name - # @param inport InPort object that is associated with this data input port. - # Specify also the data type and the buffer type used in - # the InPort object. - # @param prop Property for setting ports - # - # @endif - # - # InPortBase(const char* name, const char* data_type); - def __init__(self, name, data_type): - OpenRTM_aist.PortBase.__init__(self,name) - self._rtcout.RTC_DEBUG("Port name: %s", name) - self._singlebuffer = True - self._thebuffer = None - self._properties = OpenRTM_aist.Properties() - self._providerTypes = "" - self._consumerTypes = "" - self._connectors = [] - self._connector_mutex = threading.RLock() - - # PortProfile::properties - self._rtcout.RTC_DEBUG("setting port.port_type: DataInPort") - self.addProperty("port.port_type", "DataInPort") - - self._rtcout.RTC_DEBUG("setting port.data_type: %s", data_type) - self.addProperty("dataport.data_type", data_type) - - self.addProperty("dataport.subscription_type", "Any") - self._value = None - self._listeners = OpenRTM_aist.ConnectorListeners() - - - ## - # @if jp - # @brief ǥȥ饯 - # - # ǥȥ饯 - # - # @else - # @brief Destructor - # - # Destructor - # - # @endif - # - def __del__(self, PortBase=OpenRTM_aist.PortBase): - self._rtcout.RTC_TRACE("InPortBase destructor") - - if len(self._connectors) != 0: - self._rtcout.RTC_ERROR("connector.size should be 0 in InPortBase's dtor.") - # guard = OpenRTM_aist.ScopedLock(self._connector_mutex) - for connector in self._connectors: - connector.disconnect() - - if self._thebuffer is not None: - OpenRTM_aist.CdrBufferFactory.instance().deleteObject(self._thebuffer) - if not self._singlebuffer: - self._rtcout.RTC_ERROR("Although singlebuffer flag is true, the buffer != 0") - - PortBase.__del__(self) - return - - - ## - # @if jp - # @brief ץѥƥν - # - # ꤵ줿ץѥƥǽ롣 - # - # @param prop ꤹץѥƥ - # @else - # @brief Initializing properties - # - # This method initializes the port in the specified property. - # - # @param prop Property for setting ports - # @endif - # - # void init(coil::Properties& prop); - def init(self,prop): - self._rtcout.RTC_TRACE("init()") - self._properties.mergeProperties(prop) - if self._singlebuffer: - self._rtcout.RTC_DEBUG("single buffer mode.") - self._thebuffer = OpenRTM_aist.CdrBufferFactory.instance().createObject("ring_buffer") - - if self._thebuffer is None: - self._rtcout.RTC_ERROR("default buffer creation failed") - else: - self._rtcout.RTC_DEBUG("multi buffer mode.") - - self.initProviders() - self.initConsumers() - - num = [-1] - if not OpenRTM_aist.stringTo(num, self._properties.getProperty("connection_limit","-1")): - self._rtcout.RTC_ERROR("invalid connection_limit value: %s", - self._properties.getProperty("connection_limit")) - - self.setConnectionLimit(num[0]) - return - - - ## - # @if jp - # @brief RTObject_impl::readAll()ƤФ벾۴ؿ - # - # DataPort ǡɤ߽Ф - # - # @return true:,false: - # @else - # @brief It is a virtual method that is called from RTObject_impl::readAll(). - # This method reads out data from DataPort. - # - # @return true:Success,false:Failure - # @endif - # - # virtual bool read() = 0; - def read(self): - pass - - ## - # @if jp - # @brief ץѥƥ - # - # InPortΥץѥƥ롣 - # - # @return ץѥƥ - # - # @else - # - # @brief Get properties - # - # Getting properties of this InPort - # - # @return InPort's properties - # - # @endif - # - def properties(self): - self._rtcout.RTC_TRACE("properties()") - return self._properties - - - ## - # @if jp - # @brief Connector - # - # ߽ͭƤ륳ͥ롣 - # - # @return connector Υꥹ - # - # @else - # - # @brief Connector list - # - # This operation returns connector list - # - # @return connector list - # - # @endif - # - # const std::vector& connectors(); - def connectors(self): - self._rtcout.RTC_TRACE("connectors(): size = %d", len(self._connectors)) - # guard = OpenRTM_aist.ScopedLock(self._connector_mutex) - return self._connectors - - - ## - # @if jp - # @brief ConnectorProfile - # - # ߽ͭƤ륳ͥProfile롣 - # - # @return ConnectorProfile Υꥹ - # - # @else - # - # @brief ConnectorProfile list - # - # This operation returns ConnectorProfile list - # - # @return connector list - # - # @endif - # - # ConnectorInfoList getConnectorProfiles(); - def getConnectorProfiles(self): - self._rtcout.RTC_TRACE("getConnectorProfiles(): size = %d", len(self._connectors)) - profs = [] - # guard = OpenRTM_aist.ScopedLock(self._connector_mutex) - for con in self._connectors: - profs.append(con.profile()) - - return profs - - ## - # @if jp - # @brief ConnectorId - # - # ߽ͭƤ륳ͥID롣 - # - # @return ConnectorId Υꥹ - # - # @else - # - # @brief ConnectorId list - # - # This operation returns ConnectorId list - # - # @return connector list - # - # @endif - # - # coil::vstring getConnectorIds(); - def getConnectorIds(self): - ids = [] - - # guard = OpenRTM_aist.ScopedLock(self._connector_mutex) - for con in self._connectors: - ids.append(con.id()) - - self._rtcout.RTC_TRACE("getConnectorIds(): %s", OpenRTM_aist.flatten(ids)) - return ids - - ## - # @if jp - # @brief Connector̾ - # - # ߽ͭƤ륳ͥ̾롣 - # - # @return Connector̾Υꥹ - # - # @else - # - # @brief Connector name list - # - # This operation returns Connector name list - # - # @return connector name list - # - # @endif - # - # coil::vstring getConnectorNames(); - def getConnectorNames(self): - names = [] - # guard = OpenRTM_aist.ScopedLock(self._connector_mutex) - for con in self._connectors: - names.append(con.name()) - - self._rtcout.RTC_TRACE("getConnectorNames(): %s", OpenRTM_aist.flatten(names)) - return names - - ## - # @if jp - # @brief ConnectorProfileIDǼ - # - # ߽ͭƤ륳ͥIDǼ롣 - # - # @param id Connector ID - # @return ͥؤΥݥ - # - # @else - # - # @brief Getting ConnectorProfile by ID - # - # This operation returns Connector specified by ID. - # - # @param id Connector ID - # @return A pointer to connector - # - # @endif - # - # InPortConnector* getConnectorById(const char* id); - def getConnectorById(self, id): - self._rtcout.RTC_TRACE("getConnectorById(id = %s)", id) - - for con in self._connectors: - if id == con.id(): - return con - - self._rtcout.RTC_WARN("ConnectorProfile with the id(%s) not found.", id) - return None - - ## - # @if jp - # @brief ConnectorProfile̾Ǽ - # - # ߽ͭƤ륳ͥ̾Ǽ롣 - # - # @param name Connector name - # @return ͥؤΥݥ - # - # @else - # - # @brief Getting Connector by name - # - # This operation returns Connector specified by name. - # - # @param id Connector ID - # @return A pointer to connector - # - # @endif - # - # InPortConnector* getConnectorByName(const char* name); - def getConnectorByName(self, name): - self._rtcout.RTC_TRACE("getConnectorByName(name = %s)", name) - - for con in self._connectors: - if name == con.name(): - return con - - self._rtcout.RTC_WARN("ConnectorProfile with the name(%s) not found.", name) - return None - - ## - # @if jp - # @brief ConnectorProfileIDǼ - # - # ߽ͭƤ륳ͥIDǼ롣 - # - # @param id Connector ID - # @param prof ConnectorProfile - # @return false ꤷIDʤ - # - # @else - # - # @brief Getting ConnectorProfile by name - # - # This operation returns ConnectorProfile specified by name - # - # @param id Connector ID - # @param prof ConnectorProfile - # @return falsespecified ID does not exist - # - # @endif - # - # bool getConnectorProfileById(const char* id, - # ConnectorInfo& prof); - def getConnectorProfileById(self, id, prof): - self._rtcout.RTC_TRACE("getConnectorProfileById(id = %s)", id) - - # guard = OpenRTM_aist.ScopedLock(self._connector_mutex) - conn = self.getConnectorById(id) - if not conn: - return False - prof[0] = conn.profile() - return True - - - ## - # @if jp - # @brief ConnectorProfile̾Ǽ - # - # ߽ͭƤ륳ͥ̾Ǽ롣 - # - # @param name Connector name - # @param prof ConnectorProfile - # @return false ꤷ̾ʤ - # - # @else - # - # @brief Getting ConnectorProfile by name - # - # This operation returns ConnectorProfile specified by name - # - # @param id Connector ID - # @param prof ConnectorProfile - # @return false specified name does not exist - # - # @endif - # - # bool getConnectorProfileByName(const char* name, - # ConnectorInfo& prof); - def getConnectorProfileByName(self, name, prof): - self._rtcout.RTC_TRACE("getConnectorProfileByName(name = %s)", name) - - # guard = OpenRTM_aist.ScopedLock(self._connector_mutex) - conn = self.getConnectorByName(name) - if not conn: - return False - prof[0] = conn.profile() - return True - - - ## - # @if jp - # - # @brief [CORBA interface] Port ³Ԥ - # - # Ϳ줿 ConnectoionProfile ξ˴ŤPort֤³Ω - # 롣δؿϼ˥ץꥱץġ뤫Ƥӽ - # ȤȤƤ롣 - # - # @param connector_profile ConnectorProfile - # @return ReturnCode_t Υ꥿󥳡 - # - # @else - # - # @brief [CORBA interface] Connect the Port - # - # This operation establishes connection according to the given - # ConnectionProfile inforamtion. This function is premised on - # calling from mainly application program or tools. - # - # @param connector_profile The ConnectorProfile. - # @return ReturnCode_t The return code of ReturnCode_t type. - # - # @endif - # - def connect(self, connector_profile): - self._rtcout.RTC_TRACE("InPortBase.connect()") - - - - - - - if OpenRTM_aist.NVUtil.find_index(connector_profile.properties, - "dataport.serializer.cdr.endian") is -1: - self._rtcout.RTC_TRACE("ConnectorProfile dataport.serializer.cdr.endian set.") - connector_profile.properties.append(OpenRTM_aist.NVUtil.newNV("dataport.serializer.cdr.endian","little,big")) - - return OpenRTM_aist.PortBase.connect(self, connector_profile) - - ## - # @if jp - # - # @brief - # - # @param self - # @param connector_profile - # @return - # - # @else - # - # @brief - # - # @param self - # @param connector_profile - # @return - # - # @endif - # - def notify_connect(self, connector_profile): - - prop = OpenRTM_aist.Properties() - OpenRTM_aist.NVUtil.copyToProperties(prop, connector_profile.properties) - - node = prop.getNode("dataport.inport") - portprop = copy.deepcopy(self._properties) - portprop.mergeProperties(node) - node.mergeProperties(portprop) - OpenRTM_aist.NVUtil.copyFromProperties(connector_profile.properties, prop) - - - #_str = self._properties.getProperty("fan_in") - _str = node.getProperty("fan_in") - _type = [int(100)] - - OpenRTM_aist.stringTo(_type, _str) - - - - _str = prop.getProperty("dataport.fan_in") - OpenRTM_aist.stringTo(_type, _str) - - value = _type[0] - - if value <= len(self._connectors): - return (RTC.PRECONDITION_NOT_MET, connector_profile) - - return OpenRTM_aist.PortBase.notify_connect(self, connector_profile) - - - ## - # @if jp - # - # @brief InPort activates - # - # InPort activate 롣 - # - # @else - # - # @brief Activate all Port interfaces - # - # This operation activate all interfaces that is registered in the - # ports. - # - # @endif - # - # void activateInterfaces(); - def activateInterfaces(self): - self._rtcout.RTC_TRACE("activateInterfaces()") - - # guard = OpenRTM_aist.ScopedLock(self._connector_mutex) - for connector in self._connectors: - connector.activate() - self._rtcout.RTC_DEBUG("activate connector: %s %s", - (connector.name(),connector.id())) - - return - - - ## - # @if jp - # - # @brief Ƥ Port Υ󥿡ե deactivates - # - # Port ϿƤƤΥ󥿡ե deactivate 롣 - # - # @else - # - # @brief Deactivate all Port interfaces - # - # This operation deactivate all interfaces that is registered in the - # ports. - # - # @endif - # - # void deactivateInterfaces(); - def deactivateInterfaces(self): - self._rtcout.RTC_TRACE("deactivateInterfaces()") - - # guard = OpenRTM_aist.ScopedLock(self._connector_mutex) - for connector in self._connectors: - connector.deactivate() - self._rtcout.RTC_DEBUG("deactivate connector: %s %s", - (connector.name(),connector.id())) - return - - - ## - # @if jp - # @brief ConnectorDataListener ꥹʤɲä - # - # Хåե񤭹ߤޤɤ߽Ф٥Ȥ˴ϢƼꥹʤꤹ롣 - # - # ǤꥹʤΥפȥХå٥Ȥϰʲ̤ - # - # - ON_BUFFER_WRITE: Хåե񤭹߻ - # - ON_BUFFER_FULL: Хåեե - # - ON_BUFFER_WRITE_TIMEOUT: Хåե񤭹ߥॢȻ - # - ON_BUFFER_OVERWRITE: Хåե񤭻 - # - ON_BUFFER_READ: Хåեɤ߽Ф - # - ON_SEND: InProtؤ - # - ON_RECEIVED: InProtؤλ - # - ON_SEND_ERTIMEOUT: OutPort¦ॢȻ - # - ON_SEND_ERERROR: OutPort¦顼 - # - ON_RECEIVER_FULL: InProt¦Хåեե - # - ON_RECEIVER_TIMEOUT: InProt¦ХåեॢȻ - # - ON_RECEIVER_ERROR: InProt¦顼 - # - # ꥹʤ ConnectorDataListener ѾʲΥ˥ - # operator() Ƥɬפ롣 - # - # ConnectorDataListener:: - # operator()(const ConnectorProfile&, const cdrStream&) - # - # ǥեȤǤϡδؿͿꥹʥ֥Ȥνͭ - # OutPort˰ܤꡢOutPortλ⤷ϡ - # removeConnectorDataListener() ˤ˼ưŪ˲Τ롣 - # ꥹʥ֥ȤνͭƤӽФ¦ǰݻϡ3 - # false ꤷưŪʲΤ뤳ȤǤ롣 - # - # @param listener_type ꥹʥ - # @param listener ꥹʥ֥ȤؤΥݥ - # @param autoclean ꥹʥ֥ȤμưŪΤԤɤΥե饰 - # - # @else - # @brief Adding BufferDataListener type listener - # - # This operation adds certain listeners related to buffer writing and - # reading events. - # The following listener types are available. - # - # - ON_BUFFER_WRITE: At the time of buffer write - # - ON_BUFFER_FULL: At the time of buffer full - # - ON_BUFFER_WRITE_TIMEOUT: At the time of buffer write timeout - # - ON_BUFFER_OVERWRITE: At the time of buffer overwrite - # - ON_BUFFER_READ: At the time of buffer read - # - ON_SEND: At the time of sending to InPort - # - ON_RECEIVED: At the time of finishing sending to InPort - # - ON_SENDER_TIMEOUT: At the time of timeout of OutPort - # - ON_SENDER_ERROR: At the time of error of OutPort - # - ON_RECEIVER_FULL: At the time of bufferfull of InPort - # - ON_RECEIVER_TIMEOUT: At the time of timeout of InPort - # - ON_RECEIVER_ERROR: At the time of error of InPort - # - # Listeners should have the following function operator(). - # - # ConnectorDataListener:: - # operator()(const ConnectorProfile&, const cdrStream&) - # - # The ownership of the given listener object is transferred to - # this OutPort object in default. The given listener object will - # be destroied automatically in the OutPort's dtor or if the - # listener is deleted by removeConnectorDataListener() function. - # If you want to keep ownership of the listener object, give - # "false" value to 3rd argument to inhibit automatic destruction. - # - # @param listener_type A listener type - # @param listener A pointer to a listener object - # @param autoclean A flag for automatic listener destruction - # - # @endif - # - # void - # addConnectorDataListener(ConnectorDataListenerType type, - # ConnectorDataListener* listener, - # bool autoclean) - def addConnectorDataListener(self, listener_type, listener, autoclean = True): - self._rtcout.RTC_TRACE("addConnectorDataListener()") - - if listener_type < OpenRTM_aist.ConnectorDataListenerType.CONNECTOR_DATA_LISTENER_NUM: - self._listeners.connectorData_[listener_type].addListener(listener, autoclean) - return - - self._rtcout.RTC_ERROR("addConnectorDataListener(): Invalid listener type.") - return - - - ## - # @if jp - # @brief ConnectorDataListener ꥹʤ - # - # ꤷƼꥹʤ롣 - # - # @param listener_type ꥹʥ - # @param listener ꥹʥ֥ȤؤΥݥ - # - # @else - # @brief Removing BufferDataListener type listener - # - # This operation removes a specified listener. - # - # @param listener_type A listener type - # @param listener A pointer to a listener object - # - # @endif - # - # void removeConnectorDataListener(ConnectorDataListenerType type, - # ConnectorDataListener* listener) - def removeConnectorDataListener(self, listener_type, listener): - self._rtcout.RTC_TRACE("removeConnectorDataListener()") - - if listener_type < OpenRTM_aist.ConnectorDataListenerType.CONNECTOR_DATA_LISTENER_NUM: - self._listeners.connectorData_[listener_type].removeListener(listener) - return - - self._rtcout.RTC_ERROR("removeConnectorDataListener(): Invalid listener type.") - return - - - ## - # @if jp - # @brief ConnectorListener ꥹʤɲä - # - # Хåե񤭹ߤޤɤ߽Ф٥Ȥ˴ϢƼꥹʤꤹ롣 - # - # ǤꥹʤΥפ - # - # - ON_BUFFER_EMPTY: Хåեξ - # - ON_BUFFER_READTIMEOUT: ХåեǥॢȤ - # - # ꥹʤϰʲΥ˥ operator() Ƥɬפ롣 - # - # ConnectorListener::operator()(const ConnectorProfile&) - # - # ǥեȤǤϡδؿͿꥹʥ֥Ȥνͭ - # OutPort˰ܤꡢOutPortλ⤷ϡ - # removeConnectorListener() ˤ˼ưŪ˲Τ롣 - # ꥹʥ֥ȤνͭƤӽФ¦ǰݻϡ3 - # false ꤷưŪʲΤ뤳ȤǤ롣 - # - # @param listener_type ꥹʥ - # @param listener ꥹʥ֥ȤؤΥݥ - # @param autoclean ꥹʥ֥ȤμưŪΤԤɤΥե饰 - # - # @else - # @brief Adding ConnectorListener type listener - # - # This operation adds certain listeners related to buffer writing and - # reading events. - # The following listener types are available. - # - # - ON_BUFFER_EMPTY: At the time of buffer empty - # - ON_BUFFER_READTIMEOUT: At the time of buffer read timeout - # - # Listeners should have the following function operator(). - # - # ConnectorListener::operator()(const ConnectorProfile&) - # - # The ownership of the given listener object is transferred to - # this OutPort object in default. The given listener object will - # be destroied automatically in the OutPort's dtor or if the - # listener is deleted by removeConnectorListener() function. - # If you want to keep ownership of the listener object, give - # "false" value to 3rd argument to inhibit automatic destruction. - # - # @param listener_type A listener type - # @param listener A pointer to a listener object - # @param autoclean A flag for automatic listener destruction - # - # @endif - # - # void addConnectorListener(ConnectorListenerType type, - # ConnectorListener* listener, - # bool autoclean) - def addConnectorListener(self, listener_type, listener, autoclean = True): - self._rtcout.RTC_TRACE("addConnectorListener()") - - if listener_type < OpenRTM_aist.ConnectorListenerType.CONNECTOR_LISTENER_NUM: - self._listeners.connector_[listener_type].addListener(listener, autoclean) - return - - self._rtcout.RTC_ERROR("addConnectorListener(): Invalid listener type.") - return - - - ## - # @if jp - # @brief ConnectorDataListener ꥹʤ - # - # ꤷƼꥹʤ롣 - # - # @param listener_type ꥹʥ - # @param listener ꥹʥ֥ȤؤΥݥ - # - # @else - # @brief Removing BufferDataListener type listener - # - # This operation removes a specified listener. - # - # @param listener_type A listener type - # @param listener A pointer to a listener object - # - # @endif - # - # void removeConnectorListener(ConnectorListenerType type, - # ConnectorListener* listener) - def removeConnectorListener(self, listener_type, listener): - self._rtcout.RTC_TRACE("removeConnectorListener()") - - if listener_type < OpenRTM_aist.ConnectorListenerType.CONNECTOR_LISTENER_NUM: - self._listeners.connector_[listener_type].removeListener(listener) - return - - self._rtcout.RTC_ERROR("removeConnectorListener(): Invalid listener type.") - return - - - ## - # @if jp - # @brief Interface - # - # Interface롣 - # ConnectorProfile ˳ǼƤ dataflow_type push - # ξϡꤵ줿 interface_type InPortProvider ˴ؤ - # ConnectorProfile::properties ˽߸ƤӽФ¦᤹ - # - # dataport.dataflow_type - # - # @param connector_profile ͥץե - # - # @return ReturnCode_t Υ꥿󥳡 - # - # @else - # @brief Publish interface information - # - # Publish interface information. - # Assign the Provider information that owned by this port - # to ConnectorProfile#properties - # - # @param connector_profile The connector profile - # - # @return The return code of ReturnCode_t type - # - # @endif - # - # ReturnCode_t publishInterfaces(ConnectorProfile& connector_profile); - def publishInterfaces(self, cprof): - self._rtcout.RTC_TRACE("publishInterfaces()") - - retval = self._publishInterfaces() - if retval != RTC.RTC_OK: - return retval - - # prop: [port.outport]. - prop = copy.deepcopy(self._properties) - - conn_prop = OpenRTM_aist.Properties() - OpenRTM_aist.NVUtil.copyToProperties(conn_prop, cprof.properties) - prop.mergeProperties(conn_prop.getNode("dataport")) # marge ConnectorProfile - - # marge ConnectorProfile for buffer property. - prop.mergeProperties(conn_prop.getNode("dataport.inport")) - - # - # , ConnectorProfile properties ޡ줿ᡢ - # prop["dataflow_type"]: ǡե - # prop["interface_type"]: 󥿡ե - # ʤɤǽˤʤ롣 - # - dflow_type = prop.getProperty("dataflow_type") - dflow_type = OpenRTM_aist.normalize([dflow_type]) - - if dflow_type == "push": - self._rtcout.RTC_DEBUG("dataflow_type = push .... create PushConnector") - - # create InPortProvider - provider = self.createProvider(cprof, prop) - - if not provider: - self._rtcout.RTC_ERROR("InPort provider creation failed.") - return RTC.BAD_PARAMETER + """ + """ - # create InPortPushConnector - connector = self.createConnector(cprof, prop, provider_=provider) - if not connector: - self._rtcout.RTC_ERROR("PushConnector creation failed.") - return RTC.RTC_ERROR - - connector.setDataType(self._value) - provider.setConnector(connector) # So that a provider gets endian information from a connector. - - self._rtcout.RTC_DEBUG("publishInterfaces() successfully finished.") - return RTC.RTC_OK - - elif dflow_type == "pull": - self._rtcout.RTC_DEBUG("dataflow_type = pull .... do nothing") - return RTC.RTC_OK - - self._rtcout.RTC_ERROR("unsupported dataflow_type") - return RTC.BAD_PARAMETER - - - ## - # @if jp - # @brief Interface³ - # - # Interface³롣 - # PortͭConsumerŬ礹Provider˴ؤ - # ConnectorProfile#properties Ф - # ConsumerCORBA֥ȻȤꤹ롣 - # - # @param connector_profile ͥץե - # - # @return ReturnCode_t Υ꥿󥳡 - # - # @else - # @brief Subscribe to the interface - # - # Subscribe to interface. - # Derive Provider information that matches Consumer owned by the Port - # from ConnectorProfile#properties and - # set the Consumer to the reference of the CORBA object. - # - # @param connector_profile The connector profile - # - # @return ReturnCode_t The return code of ReturnCode_t type - # - # @endif - # - # ReturnCode_t subscribeInterfaces(const ConnectorProfile& connector_profile); - def subscribeInterfaces(self, cprof): - self._rtcout.RTC_TRACE("subscribeInterfaces()") - - # prop: [port.outport]. - prop = copy.deepcopy(self._properties) - conn_prop = OpenRTM_aist.Properties() - OpenRTM_aist.NVUtil.copyToProperties(conn_prop, cprof.properties) - prop.mergeProperties(conn_prop.getNode("dataport")) # marge ConnectorProfile - prop.mergeProperties(conn_prop.getNode("dataport.inport")) # marge ConnectorProfile for buffer property. - - # - # , ConnectorProfile properties ޡ줿ᡢ - # prop["dataflow_type"]: ǡե - # prop["interface_type"]: 󥿡ե - # ʤɤǽˤʤ롣 - # - dflow_type = prop.getProperty("dataflow_type") - dtype = [dflow_type] - OpenRTM_aist.normalize(dtype) - dflow_type = dtype[0] - - profile = OpenRTM_aist.ConnectorInfo(cprof.name, - cprof.connector_id, - OpenRTM_aist.CORBA_SeqUtil.refToVstring(cprof.ports), - prop) - if dflow_type == "push": - self._rtcout.RTC_DEBUG("dataflow_type = push .... do nothing") - - conn = self.getConnectorById(cprof.connector_id) - - if not conn: - self._rtcout.RTC_ERROR("specified connector not found: %s", - cprof.connector_id) - return RTC.RTC_ERROR - - ret = conn.setConnectorInfo(profile) - if ret == RTC.RTC_OK: - self._rtcout.RTC_DEBUG("subscribeInterfaces() successfully finished.") - - return ret - - elif dflow_type == "pull": - self._rtcout.RTC_DEBUG("dataflow_type = pull .... create PullConnector") - - # create OutPortConsumer - consumer = self.createConsumer(cprof, prop) - if not consumer: - return RTC.BAD_PARAMETER + ## + # @if jp + # @brief コンストラクタ + # + # コンストラクタ + # + # @param name ポート名称 + # @param inport 当該データ入力ポートに関連付けるInPortオブジェクト + # InPortオブジェクトで扱うデータ型、バッファタイプも指定する + # @param prop ポート設定用プロパティ + # + # @else + # @brief Constructor + # + # Constructor + # + # @param name Port name + # @param inport InPort object that is associated with this data input port. + # Specify also the data type and the buffer type used in + # the InPort object. + # @param prop Property for setting ports + # + # @endif + # + # InPortBase(const char* name, const char* data_type); + def __init__(self, name, data_type): + OpenRTM_aist.PortBase.__init__(self, name) + self._rtcout.RTC_DEBUG("Port name: %s", name) + self._singlebuffer = True + self._thebuffer = None + self._properties = OpenRTM_aist.Properties() + self._providerTypes = "" + self._consumerTypes = "" + self._connectors = [] + self._connector_mutex = threading.RLock() + + # PortProfile::properties を設定 + self._rtcout.RTC_DEBUG("setting port.port_type: DataInPort") + self.addProperty("port.port_type", "DataInPort") + + self._rtcout.RTC_DEBUG("setting port.data_type: %s", data_type) + self.addProperty("dataport.data_type", data_type) + self._properties.setProperty("data_type", data_type) + + self.addProperty("dataport.subscription_type", "Any") + self._value = None + self._listeners = OpenRTM_aist.ConnectorListeners() + + ## + # @if jp + # @brief デストラクタ + # + # デストラクタ + # + # @else + # @brief Destructor + # + # Destructor + # + # @endif + # - # create InPortPullConnector - connector = self.createConnector(cprof, prop, consumer_=consumer) - if not connector: - return RTC.RTC_ERROR - - ret = connector.setConnectorInfo(profile) - - if ret == RTC.RTC_OK: - self._rtcout.RTC_DEBUG("publishInterface() successfully finished.") - - return ret - - self._rtcout.RTC_ERROR("unsupported dataflow_type") - return RTC.BAD_PARAMETER - - - ## - # @if jp - # @brief Interfaceؤ³ - # - # Interfaceؤ³롣 - # Ϳ줿ConnectorProfile˴ϢConsumerꤵ줿ƤObject - # ³롣 - # - # @param connector_profile ͥץե - # - # @else - # @brief Disconnect the interface connection - # - # Disconnect the interface connection. - # Release all objects set in Consumer associated with - # given ConnectorProfile and unscribe the interface. - # - # @param connector_profile The connector profile - # - # @endif - # - # void unsubscribeInterfaces(const ConnectorProfile& connector_profile); - def unsubscribeInterfaces(self, connector_profile): - self._rtcout.RTC_TRACE("unsubscribeInterfaces()") - - id = connector_profile.connector_id - self._rtcout.RTC_PARANOID("connector_id: %s", id) - - len_ = len(self._connectors) - for i in range(len_): - idx = (len_ - 1) - i - # guard = OpenRTM_aist.ScopedLock(self._connector_mutex) - if id == self._connectors[idx].id(): - # Connector's dtor must call disconnect() - self._connectors[idx].deactivate() - self._connectors[idx].disconnect() - del self._connectors[idx] - self._rtcout.RTC_TRACE("delete connector: %s", id) + def __del__(self, PortBase=OpenRTM_aist.PortBase): + self._rtcout.RTC_TRACE("InPortBase destructor") + + if self._connectors: + self._rtcout.RTC_ERROR( + "connector.size should be 0 in InPortBase's dtor.") + # guard = OpenRTM_aist.ScopedLock(self._connector_mutex) + for connector in self._connectors: + prop_list = [] + prop = OpenRTM_aist.Properties() + node = prop.getNode("dataport") + node.mergeProperties(connector.profile().properties) + OpenRTM_aist.NVUtil.copyFromProperties(prop_list, prop) + connector.unsubscribeInterface(prop_list) + connector.disconnect() + + if self._thebuffer is not None: + if not self._singlebuffer: + self._rtcout.RTC_ERROR( + "Although singlebuffer flag is true, the buffer != 0") + + PortBase.__del__(self) return - self._rtcout.RTC_ERROR("specified connector not found: %s", id) - return - - - ## - # @if jp - # @brief InPort provider ν - # @else - # @brief InPort provider initialization - # @endif - # - # void initProviders(); - def initProviders(self): - self._rtcout.RTC_TRACE("initProviders()") - - # create InPort providers - factory = OpenRTM_aist.InPortProviderFactory.instance() - provider_types = factory.getIdentifiers() - - self._rtcout.RTC_DEBUG("available providers: %s", - OpenRTM_aist.flatten(provider_types)) - - if self._properties.hasKey("provider_types") and \ - OpenRTM_aist.normalize([self._properties.getProperty("provider_types")]) != "all": - self._rtcout.RTC_DEBUG("allowed providers: %s", - self._properties.getProperty("provider_types")) - - temp_types = provider_types - provider_types = [] - active_types = OpenRTM_aist.split(self._properties.getProperty("provider_types"), ",") - - temp_types.sort() - active_types.sort() - - set_ptypes = set(temp_types).intersection(set(active_types)) - provider_types = provider_types + list(set_ptypes) - - # InPortProvider supports "push" dataflow type - if len(provider_types) > 0: - self._rtcout.RTC_DEBUG("dataflow_type push is supported") - self.appendProperty("dataport.dataflow_type", "push") - for provider_type in provider_types: - self.appendProperty("dataport.interface_type",provider_type) - - - self._providerTypes = provider_types - return - - - ## - # @if jp - # @brief OutPort consumer ν - # @else - # @brief OutPort consumer initialization - # @endif - # - # void initConsumers(); - def initConsumers(self): - self._rtcout.RTC_TRACE("initConsumers()") - - # create OuPort consumers - factory = OpenRTM_aist.OutPortConsumerFactory.instance() - consumer_types = factory.getIdentifiers() - self._rtcout.RTC_DEBUG("available consumers: %s", - OpenRTM_aist.flatten(consumer_types)) - - if self._properties.hasKey("consumer_types") and \ - OpenRTM_aist.normalize([self._properties.getProperty("consumer_types")]) != "all": - self._rtcout.RTC_DEBUG("allowed consumers: %s", - self._properties.getProperty("consumer_types")) - - temp_types = consumer_types - consumer_types = [] - active_types = OpenRTM_aist.split(self._properties.getProperty("consumer_types"), ",") - - temp_types.sort() - active_types.sort() - - set_ctypes = set(temp_types).intersection(set(active_types)) - consumer_types = consumer_types + list(set_ctypes) - - # OutPortConsumer supports "pull" dataflow type - if len(consumer_types) > 0: - self._rtcout.RTC_PARANOID("dataflow_type pull is supported") - self.appendProperty("dataport.dataflow_type", "pull") - for consumer_type in consumer_types: - self.appendProperty("dataport.interface_type",consumer_type) - - - self._consumerTypes = consumer_types - return - - - ## - # @if jp - # @brief InPort provider - # - # InPortProvider ConnectorProfile ˸롣 - # ˼Ԥ 0 ֤ - # - # @else - # @brief InPort provider creation - # @endif - # - # InPortProvider* - # createProvider(ConnectorProfile& cprof, coil::Properties& prop); - def createProvider(self, cprof, prop): - if not prop.getProperty("interface_type") or \ - not OpenRTM_aist.includes(self._providerTypes, prop.getProperty("interface_type")): - self._rtcout.RTC_ERROR("no provider found") - self._rtcout.RTC_DEBUG("interface_type: %s", prop.getProperty("interface_type")) - self._rtcout.RTC_DEBUG("interface_types: %s", - OpenRTM_aist.flatten(self._providerTypes)) - return None - - - self._rtcout.RTC_DEBUG("interface_type: %s", prop.getProperty("interface_type")) - provider = OpenRTM_aist.InPortProviderFactory.instance().createObject(prop.getProperty("interface_type")) - - - if provider is not None: - self._rtcout.RTC_DEBUG("provider created") - provider.init(prop.getNode("provider")) - - if not provider.publishInterface(cprof.properties): - self._rtcout.RTC_ERROR("publishing interface information error") - OpenRTM_aist.InPortProviderFactory.instance().deleteObject(provider) - return None - return provider - - self._rtcout.RTC_ERROR("provider creation failed") - return None - - - ## - # @if jp - # @brief OutPort consumer - # - # OutPortConsumer 롣 - # ˼Ԥ 0 ֤ - # - # @else - # @brief InPort provider creation - # @endif - # - # OutPortConsumer* - # createConsumer(const ConnectorProfile& cprof, coil::Properties& prop); - def createConsumer(self, cprof, prop): - if not prop.getProperty("interface_type") or \ - not OpenRTM_aist.includes(self._consumerTypes, prop.getProperty("interface_type")): - self._rtcout.RTC_ERROR("no consumer found") - self._rtcout.RTC_DEBUG("interface_type: %s", prop.getProperty("interface_type")) - self._rtcout.RTC_DEBUG("interface_types: %s", - OpenRTM_aist.flatten(self._consumerTypes)) - return None - - self._rtcout.RTC_DEBUG("interface_type: %s", prop.getProperty("interface_type")) - consumer = OpenRTM_aist.OutPortConsumerFactory.instance().createObject(prop.getProperty("interface_type")) - - if consumer is not None: - self._rtcout.RTC_DEBUG("consumer created") - consumer.init(prop.getNode("consumer")) - - if not consumer.subscribeInterface(cprof.properties): - self._rtcout.RTC_ERROR("interface subscription failed.") - OpenRTM_aist.OutPortConsumerFactory.instance().deleteObject(consumer) - return None - return consumer - - self._rtcout.RTC_ERROR("consumer creation failed") - return None - - - ## - # @if jp - # @brief InPortPushConnector - # - # Connector m_connectors ¸롣 - # ˼Ԥ 0 ֤ - # - # @else - # @brief InPortPushConnector creation - # @endif - # - # InPortConnector* - # createConnector(ConnectorProfile& cprof, coil::Properties& prop, - # InPortProvider* provider); - def createConnector(self, cprof, prop, provider_=None, consumer_=None): - profile = OpenRTM_aist.ConnectorInfo(cprof.name, - cprof.connector_id, - OpenRTM_aist.CORBA_SeqUtil.refToVstring(cprof.ports), - prop) - connector = None - - - try: - if provider_ is not None: - if self._singlebuffer: - connector = OpenRTM_aist.InPortPushConnector(profile, provider_, - self._listeners, - self._thebuffer) - else: - connector = OpenRTM_aist.InPortPushConnector(profile, provider_, - self._listeners) + ## + # @if jp + # @brief プロパティの初期化 + # + # 指定されたプロパティで初期化する。 + # + # @param prop 設定するプロパティ + # @else + # @brief Initializing properties + # + # This method initializes the port in the specified property. + # + # @param prop Property for setting ports + # @endif + # + # void init(coil::Properties& prop); + + def init(self, prop): + self._rtcout.RTC_TRACE("init()") + self._properties.mergeProperties(prop) + prop_list = [] + OpenRTM_aist.NVUtil.copyFromProperties(prop_list, self._properties) + self._profile.properties.extend(prop_list) - elif consumer_ is not None: if self._singlebuffer: - connector = OpenRTM_aist.InPortPullConnector(profile, consumer_, - self._listeners, - self._thebuffer) + self._rtcout.RTC_DEBUG("single buffer mode.") + self._thebuffer = OpenRTM_aist.CdrBufferFactory.instance().createObject("ring_buffer") + + if self._thebuffer is None: + self._rtcout.RTC_ERROR("default buffer creation failed") else: - connector = OpenRTM_aist.InPortPullConnector(profile, consumer_, - self._listeners) + self._rtcout.RTC_DEBUG("multi buffer mode.") + + self.initProviders() + self.initConsumers() + if self._consumerTypes and self._providerTypes: + self.appendProperty("dataport.dataflow_type", "duplex") + + num = -1 + ret, num = OpenRTM_aist.stringTo( + num, self._properties.getProperty( + "connection_limit", "-1")) + if not ret: + self._rtcout.RTC_ERROR("invalid connection_limit value: %s", + self._properties.getProperty("connection_limit")) + + self.setConnectionLimit(num) + return + + ## + # @if jp + # @brief RTObject_impl::readAll()から呼ばれる仮想関数 + # + # DataPort からデータを読み出す + # + # @return true:成功,false:失敗 + # @else + # @brief It is a virtual method that is called from RTObject_impl::readAll(). + # This method reads out data from DataPort. + # + # @return true:Success,false:Failure + # @endif + # + # virtual bool read() = 0; + + def read(self): + pass - else: - self._rtcout.RTC_ERROR("provider or consumer is not passed. returned 0;") + ## + # @if jp + # @brief プロパティを取得する + # + # InPortのプロパティを取得する。 + # + # @return プロパティ + # + # @else + # + # @brief Get properties + # + # Getting properties of this InPort + # + # @return InPort's properties + # + # @endif + # + def properties(self): + self._rtcout.RTC_TRACE("properties()") + return self._properties + + ## + # @if jp + # @brief Connector を取得 + # + # 現在所有しているコネクタを取得する。 + # + # @return connector のリスト + # + # @else + # + # @brief Connector list + # + # This operation returns connector list + # + # @return connector list + # + # @endif + # + # const std::vector& connectors(); + + def connectors(self): + self._rtcout.RTC_TRACE( + "connectors(): size = %d", len( + self._connectors)) + # guard = OpenRTM_aist.ScopedLock(self._connector_mutex) + return self._connectors + + ## + # @if jp + # @brief ConnectorProfile を取得 + # + # 現在所有しているコネクタのProfileを取得する。 + # + # @return ConnectorProfile のリスト + # + # @else + # + # @brief ConnectorProfile list + # + # This operation returns ConnectorProfile list + # + # @return connector list + # + # @endif + # + # ConnectorInfoList getConnectorProfiles(); + + def getConnectorProfiles(self): + self._rtcout.RTC_TRACE( + "getConnectorProfiles(): size = %d", len( + self._connectors)) + profs = [] + # guard = OpenRTM_aist.ScopedLock(self._connector_mutex) + for con in self._connectors: + profs.append(con.profile()) + + return profs + + ## + # @if jp + # @brief ConnectorId を取得 + # + # 現在所有しているコネクタのIDを取得する。 + # + # @return ConnectorId のリスト + # + # @else + # + # @brief ConnectorId list + # + # This operation returns ConnectorId list + # + # @return connector list + # + # @endif + # + # coil::vstring getConnectorIds(); + def getConnectorIds(self): + ids = [] + + # guard = OpenRTM_aist.ScopedLock(self._connector_mutex) + for con in self._connectors: + ids.append(con.id()) + + self._rtcout.RTC_TRACE( + "getConnectorIds(): %s", + OpenRTM_aist.flatten(ids)) + return ids + + ## + # @if jp + # @brief Connectorの名前を取得 + # + # 現在所有しているコネクタの名前を取得する。 + # + # @return Connector名のリスト + # + # @else + # + # @brief Connector name list + # + # This operation returns Connector name list + # + # @return connector name list + # + # @endif + # + # coil::vstring getConnectorNames(); + def getConnectorNames(self): + names = [] + # guard = OpenRTM_aist.ScopedLock(self._connector_mutex) + for con in self._connectors: + names.append(con.name()) + + self._rtcout.RTC_TRACE( + "getConnectorNames(): %s", + OpenRTM_aist.flatten(names)) + return names + + ## + # @if jp + # @brief ConnectorProfileをIDで取得 + # + # 現在所有しているコネクタをIDで取得する。 + # + # @param id Connector ID + # @return コネクタへのポインタ + # + # @else + # + # @brief Getting ConnectorProfile by ID + # + # This operation returns Connector specified by ID. + # + # @param id Connector ID + # @return A pointer to connector + # + # @endif + # + # InPortConnector* getConnectorById(const char* id); + def getConnectorById(self, id): + self._rtcout.RTC_TRACE("getConnectorById(id = %s)", id) + + for con in self._connectors: + if id == con.id(): + return con + + self._rtcout.RTC_WARN( + "ConnectorProfile with the id(%s) not found.", id) + return None + + ## + # @if jp + # @brief ConnectorProfileを名前で取得 + # + # 現在所有しているコネクタを名前で取得する。 + # + # @param name Connector name + # @return コネクタへのポインタ + # + # @else + # + # @brief Getting Connector by name + # + # This operation returns Connector specified by name. + # + # @param id Connector ID + # @return A pointer to connector + # + # @endif + # + # InPortConnector* getConnectorByName(const char* name); + def getConnectorByName(self, name): + self._rtcout.RTC_TRACE("getConnectorByName(name = %s)", name) + + for con in self._connectors: + if name == con.name(): + return con + + self._rtcout.RTC_WARN( + "ConnectorProfile with the name(%s) not found.", name) return None - - #if connector is None: - # self._rtcout.RTC_ERROR("InPortConnector creation failed") - # return 0 + ## + # @if jp + # @brief ConnectorProfileをIDで取得 + # + # 現在所有しているコネクタをIDで取得する。 + # + # @param id Connector ID + # @param prof ConnectorProfile + # @return false 指定したIDがない + # + # @else + # + # @brief Getting ConnectorProfile by name + # + # This operation returns ConnectorProfile specified by name + # + # @param id Connector ID + # @param prof ConnectorProfile + # @return false specified ID does not exist + # + # @endif + # + # bool getConnectorProfileById(const char* id, + # ConnectorInfo& prof); + def getConnectorProfileById(self, id): + self._rtcout.RTC_TRACE("getConnectorProfileById(id = %s)", id) + + # guard = OpenRTM_aist.ScopedLock(self._connector_mutex) + conn = self.getConnectorById(id) + if not conn: + return False, None + prof = conn.profile() + return True, prof + + ## + # @if jp + # @brief ConnectorProfileを名前で取得 + # + # 現在所有しているコネクタを名前で取得する。 + # + # @param name Connector name + # @param prof ConnectorProfile + # @return false 指定した名前がない + # + # @else + # + # @brief Getting ConnectorProfile by name + # + # This operation returns ConnectorProfile specified by name + # + # @param id Connector ID + # @param prof ConnectorProfile + # @return false specified name does not exist + # + # @endif + # + # bool getConnectorProfileByName(const char* name, + # ConnectorInfo& prof); + + def getConnectorProfileByName(self, name): + self._rtcout.RTC_TRACE("getConnectorProfileByName(name = %s)", name) + + # guard = OpenRTM_aist.ScopedLock(self._connector_mutex) + conn = self.getConnectorByName(name) + if not conn: + return False, None + prof = conn.profile() + return True, prof + + ## + # @if jp + # + # @brief [CORBA interface] Port の接続を行う + # + # 与えられた ConnectoionProfile の情報に基づき、Port間の接続を確立 + # する。この関数は主にアプリケーションプログラムやツールから呼び出 + # すことを前提としている。 + # + # @param connector_profile ConnectorProfile + # @return ReturnCode_t 型のリターンコード + # + # @else + # + # @brief [CORBA interface] Connect the Port + # + # This operation establishes connection according to the given + # ConnectionProfile inforamtion. This function is premised on + # calling from mainly application program or tools. + # + # @param connector_profile The ConnectorProfile. + # @return ReturnCode_t The return code of ReturnCode_t type. + # + # @endif + # + + def connect(self, connector_profile): + self._rtcout.RTC_TRACE("InPortBase.connect()") + + if OpenRTM_aist.NVUtil.find_index(connector_profile.properties, + "dataport.serializer.cdr.endian") == -1: + self._rtcout.RTC_TRACE( + "ConnectorProfile dataport.serializer.cdr.endian set.") + connector_profile.properties.append( + OpenRTM_aist.NVUtil.newNV( + "dataport.serializer.cdr.endian", + "little,big")) + + return OpenRTM_aist.PortBase.connect(self, connector_profile) + + ## + # @if jp + # + # @brief + # + # @param self + # @param connector_profile + # @return + # + # @else + # + # @brief + # + # @param self + # @param connector_profile + # @return + # + # @endif + # + def notify_connect(self, connector_profile): + + prop = OpenRTM_aist.Properties() + OpenRTM_aist.NVUtil.copyToProperties( + prop, connector_profile.properties) + + node = prop.getNode("dataport.inport") + portprop = copy.deepcopy(self._properties) + portprop.mergeProperties(node) + node.mergeProperties(portprop) + OpenRTM_aist.NVUtil.copyFromProperties( + connector_profile.properties, prop) + + #_str = self._properties.getProperty("fan_in") + _str = node.getProperty("fan_in") + _type = int(100) + + _, _type = OpenRTM_aist.stringTo(_type, _str) + + _str = prop.getProperty("dataport.fan_in") + _, _type = OpenRTM_aist.stringTo(_type, _str) - if provider_ is not None: - self._rtcout.RTC_TRACE("InPortPushConnector created") - elif consumer_ is not None: - self._rtcout.RTC_TRACE("InPortPullConnector created") + value = _type - if OpenRTM_aist.StringUtil.normalize([prop.getProperty("interface_type")]) == "direct": - if consumer_ is not None: - outport = self.getLocalOutPort(profile) + if value <= len(self._connectors): + return (RTC.PRECONDITION_NOT_MET, connector_profile) - if outport is None: - self._rtcout.RTC_TRACE("interface_type is direct, ") - self._rtcout.RTC_TRACE("but a peer OutPort servant could not be obtained.") - del connector + return OpenRTM_aist.PortBase.notify_connect(self, connector_profile) + + ## + # @if jp + # + # @brief InPortを activates する + # + # InPortを activate する。 + # + # @else + # + # @brief Activate all Port interfaces + # + # This operation activate all interfaces that is registered in the + # ports. + # + # @endif + # + # void activateInterfaces(); + + def activateInterfaces(self): + self._rtcout.RTC_TRACE("activateInterfaces()") + + # guard = OpenRTM_aist.ScopedLock(self._connector_mutex) + for connector in self._connectors: + connector.activate() + self._rtcout.RTC_DEBUG("activate connector: %s %s", + (connector.name(), connector.id())) + + return + + ## + # @if jp + # + # @brief 全ての Port のインターフェースを deactivates する + # + # Port に登録されている全てのインターフェースを deactivate する。 + # + # @else + # + # @brief Deactivate all Port interfaces + # + # This operation deactivate all interfaces that is registered in the + # ports. + # + # @endif + # + # void deactivateInterfaces(); + + def deactivateInterfaces(self): + self._rtcout.RTC_TRACE("deactivateInterfaces()") + + # guard = OpenRTM_aist.ScopedLock(self._connector_mutex) + for connector in self._connectors: + connector.deactivate() + self._rtcout.RTC_DEBUG("deactivate connector: %s %s", + (connector.name(), connector.id())) + return + + ## + # @if jp + # @brief ConnectorDataListener リスナを追加する + # + # バッファ書き込みまたは読み出しイベントに関連する各種リスナを設定する。 + # + # 設定できるリスナのタイプとコールバックイベントは以下の通り + # + # - ON_BUFFER_WRITE: バッファ書き込み時 + # - ON_BUFFER_FULL: バッファフル時 + # - ON_BUFFER_WRITE_TIMEOUT: バッファ書き込みタイムアウト時 + # - ON_BUFFER_OVERWRITE: バッファ上書き時 + # - ON_BUFFER_READ: バッファ読み出し時 + # - ON_SEND: InProtへの送信時 + # - ON_RECEIVED: InProtへの送信完了時 + # - ON_SEND_ERTIMEOUT: OutPort側タイムアウト時 + # - ON_SEND_ERERROR: OutPort側エラー時 + # - ON_RECEIVER_FULL: InProt側バッファフル時 + # - ON_RECEIVER_TIMEOUT: InProt側バッファタイムアウト時 + # - ON_RECEIVER_ERROR: InProt側エラー時 + # + # リスナは ConnectorDataListener を継承し、以下のシグニチャを持つ + # operator() を実装している必要がある。 + # + # ConnectorDataListener:: + # operator()(const ConnectorProfile&, const cdrStream&) + # + # デフォルトでは、この関数に与えたリスナオブジェクトの所有権は + # OutPortに移り、OutPort解体時もしくは、 + # removeConnectorDataListener() により削除時に自動的に解体される。 + # リスナオブジェクトの所有権を呼び出し側で維持したい場合は、第3引 + # 数に false を指定し、自動的な解体を抑制することができる。 + # + # @param listener_type リスナタイプ + # @param listener リスナオブジェクトへのポインタ + # + # @else + # @brief Adding BufferDataListener type listener + # + # This operation adds certain listeners related to buffer writing and + # reading events. + # The following listener types are available. + # + # - ON_BUFFER_WRITE: At the time of buffer write + # - ON_BUFFER_FULL: At the time of buffer full + # - ON_BUFFER_WRITE_TIMEOUT: At the time of buffer write timeout + # - ON_BUFFER_OVERWRITE: At the time of buffer overwrite + # - ON_BUFFER_READ: At the time of buffer read + # - ON_SEND: At the time of sending to InPort + # - ON_RECEIVED: At the time of finishing sending to InPort + # - ON_SENDER_TIMEOUT: At the time of timeout of OutPort + # - ON_SENDER_ERROR: At the time of error of OutPort + # - ON_RECEIVER_FULL: At the time of bufferfull of InPort + # - ON_RECEIVER_TIMEOUT: At the time of timeout of InPort + # - ON_RECEIVER_ERROR: At the time of error of InPort + # + # Listeners should have the following function operator(). + # + # ConnectorDataListener:: + # operator()(const ConnectorProfile&, const cdrStream&) + # + # The ownership of the given listener object is transferred to + # this OutPort object in default. The given listener object will + # be destroied automatically in the OutPort's dtor or if the + # listener is deleted by removeConnectorDataListener() function. + # If you want to keep ownership of the listener object, give + # "false" value to 3rd argument to inhibit automatic destruction. + # + # @param listener_type A listener type + # @param listener A pointer to a listener object + # + # @endif + # + # void + # addConnectorDataListener(ConnectorDataListenerType type, + # ConnectorDataListener* listener) + + def addConnectorDataListener(self, listener_type, listener): + self._rtcout.RTC_TRACE("addConnectorDataListener()") + + if self._listeners.addDataListener(listener_type, listener): + return + + self._rtcout.RTC_ERROR( + "addConnectorDataListener(): Invalid listener type.") + return + + ## + # @if jp + # @brief ConnectorDataListener リスナを削除する + # + # 設定した各種リスナを削除する。 + # + # @param listener_type リスナタイプ + # @param listener リスナオブジェクトへのポインタ + # + # @else + # @brief Removing BufferDataListener type listener + # + # This operation removes a specified listener. + # + # @param listener_type A listener type + # @param listener A pointer to a listener object + # + # @endif + # + # void removeConnectorDataListener(ConnectorDataListenerType type, + # ConnectorDataListener* listener) + + def removeConnectorDataListener(self, listener_type, listener): + self._rtcout.RTC_TRACE("removeConnectorDataListener()") + + if self._listeners.removeDataListener(listener_type, listener): + return + + self._rtcout.RTC_ERROR( + "removeConnectorDataListener(): Invalid listener type.") + return + + ## + # @if jp + # @brief ConnectorListener リスナを追加する + # + # バッファ書き込みまたは読み出しイベントに関連する各種リスナを設定する。 + # + # 設定できるリスナのタイプは + # + # - ON_BUFFER_EMPTY: バッファが空の場合 + # - ON_BUFFER_READTIMEOUT: バッファが空でタイムアウトした場合 + # + # リスナは以下のシグニチャを持つ operator() を実装している必要がある。 + # + # ConnectorListener::operator()(const ConnectorProfile&) + # + # デフォルトでは、この関数に与えたリスナオブジェクトの所有権は + # OutPortに移り、OutPort解体時もしくは、 + # removeConnectorListener() により削除時に自動的に解体される。 + # リスナオブジェクトの所有権を呼び出し側で維持したい場合は、第3引 + # 数に false を指定し、自動的な解体を抑制することができる。 + # + # @param listener_type リスナタイプ + # @param listener リスナオブジェクトへのポインタ + # + # @else + # @brief Adding ConnectorListener type listener + # + # This operation adds certain listeners related to buffer writing and + # reading events. + # The following listener types are available. + # + # - ON_BUFFER_EMPTY: At the time of buffer empty + # - ON_BUFFER_READTIMEOUT: At the time of buffer read timeout + # + # Listeners should have the following function operator(). + # + # ConnectorListener::operator()(const ConnectorProfile&) + # + # The ownership of the given listener object is transferred to + # this OutPort object in default. The given listener object will + # be destroied automatically in the OutPort's dtor or if the + # listener is deleted by removeConnectorListener() function. + # If you want to keep ownership of the listener object, give + # "false" value to 3rd argument to inhibit automatic destruction. + # + # @param listener_type A listener type + # @param listener A pointer to a listener object + # + # @endif + # + # void addConnectorListener(ConnectorListenerType type, + # ConnectorListener* listener) + + def addConnectorListener(self, listener_type, listener): + self._rtcout.RTC_TRACE("addConnectorListener()") + + if listener_type < OpenRTM_aist.ConnectorListenerType.CONNECTOR_LISTENER_NUM: + self._listeners.addListener(listener_type, listener) + return + + self._rtcout.RTC_ERROR( + "addConnectorListener(): Invalid listener type.") + return + + ## + # @if jp + # @brief ConnectorDataListener リスナを削除する + # + # 設定した各種リスナを削除する。 + # + # @param listener_type リスナタイプ + # @param listener リスナオブジェクトへのポインタ + # + # @else + # @brief Removing BufferDataListener type listener + # + # This operation removes a specified listener. + # + # @param listener_type A listener type + # @param listener A pointer to a listener object + # + # @endif + # + # void removeConnectorListener(ConnectorListenerType type, + # ConnectorListener* listener) + + def removeConnectorListener(self, listener_type, listener): + self._rtcout.RTC_TRACE("removeConnectorListener()") + + if listener_type < OpenRTM_aist.ConnectorListenerType.CONNECTOR_LISTENER_NUM: + self._listeners.removeListener(listener_type, listener) + return + + self._rtcout.RTC_ERROR( + "removeConnectorListener(): Invalid listener type.") + return + + ## + # @if jp + # @brief Interface情報を公開する + # + # Interface情報を公開する。 + # 引数の ConnectorProfile に格納されている dataflow_type が push 型 + # の場合は、指定された interface_type の InPortProvider に関する情報 + # を ConnectorProfile::properties に書込み呼び出し側に戻す。 + # + # dataport.dataflow_type + # + # @param connector_profile コネクタプロファイル + # + # @return ReturnCode_t 型のリターンコード + # + # @else + # @brief Publish interface information + # + # Publish interface information. + # Assign the Provider information that owned by this port + # to ConnectorProfile#properties + # + # @param connector_profile The connector profile + # + # @return The return code of ReturnCode_t type + # + # @endif + # + # ReturnCode_t publishInterfaces(ConnectorProfile& connector_profile); + + def publishInterfaces(self, cprof): + self._rtcout.RTC_TRACE("publishInterfaces()") + + retval = self._publishInterfaces() + if retval != RTC.RTC_OK: + return retval + + # prop: [port.outport]. + prop = copy.deepcopy(self._properties) + + conn_prop = OpenRTM_aist.Properties() + OpenRTM_aist.NVUtil.copyToProperties(conn_prop, cprof.properties) + prop.mergeProperties(conn_prop.getNode("dataport") + ) # marge ConnectorProfile + + # marge ConnectorProfile for buffer property. + prop.mergeProperties(conn_prop.getNode("dataport.inport")) + + if not self.isExistingMarshalingType(prop): + return RTC.RTC_ERROR + + # + # ここで, ConnectorProfile からの properties がマージされたため、 + # prop["dataflow_type"]: データフロータイプ + # prop["interface_type"]: インターフェースタイプ + # などがアクセス可能になる。 + # + dflow_type = prop.getProperty("dataflow_type") + dflow_type = OpenRTM_aist.normalize(dflow_type) + + if dflow_type == "push": + self._rtcout.RTC_DEBUG( + "dataflow_type = push .... create PushConnector") + + # create InPortProvider + provider = self.createProvider(cprof, prop) + + if not provider: + self._rtcout.RTC_ERROR("InPort provider creation failed.") + return RTC.BAD_PARAMETER + + # create InPortPushConnector + connector = self.createConnector(cprof, prop, provider_=provider) + if not connector: + self._rtcout.RTC_ERROR("PushConnector creation failed.") + return RTC.RTC_ERROR + + connector.setDataType(self._value) + # So that a provider gets endian information from a connector. + provider.setConnector(connector) + + self._rtcout.RTC_DEBUG( + "publishInterfaces() successfully finished.") + return RTC.RTC_OK + + elif dflow_type == "pull": + self._rtcout.RTC_DEBUG("dataflow_type = pull .... do nothing") + return RTC.RTC_OK + + elif dflow_type == "duplex": + self._rtcout.RTC_DEBUG( + "dataflow_type = duplex .... create DuplexConnector") + + # create InPortProvider + provider = self.createProvider(cprof, prop) + if not provider: + self._rtcout.RTC_ERROR("InPort provider creation failed.") + return RTC.BAD_PARAMETER + + # create InPortDuplexConnector + connector = self.createDuplexConnector(cprof, prop, provider) + if not connector: + self._rtcout.RTC_ERROR("PushConnector creation failed.") + return RTC.RTC_ERROR + + connector.setDataType(self._value) + # So that a provider gets endian information from a connector. + provider.setConnector(connector) + + self._rtcout.RTC_DEBUG( + "publishInterfaces() successfully finished.") + return RTC.RTC_OK + + self._rtcout.RTC_ERROR("unsupported dataflow_type") + return RTC.BAD_PARAMETER + + ## + # @if jp + # @brief Interfaceに接続する + # + # Interfaceに接続する。 + # Portが所有するConsumerに適合するProviderに関する情報を + # ConnectorProfile#properties から抽出し、 + # ConsumerにCORBAオブジェクト参照を設定する。 + # + # @param connector_profile コネクタ・プロファイル + # + # @return ReturnCode_t 型のリターンコード + # + # @else + # @brief Subscribe to the interface + # + # Subscribe to interface. + # Derive Provider information that matches Consumer owned by the Port + # from ConnectorProfile#properties and + # set the Consumer to the reference of the CORBA object. + # + # @param connector_profile The connector profile + # + # @return ReturnCode_t The return code of ReturnCode_t type + # + # @endif + # + # ReturnCode_t subscribeInterfaces(const ConnectorProfile& + # connector_profile); + + def subscribeInterfaces(self, cprof): + self._rtcout.RTC_TRACE("subscribeInterfaces()") + + # prop: [port.outport]. + prop = copy.deepcopy(self._properties) + conn_prop = OpenRTM_aist.Properties() + OpenRTM_aist.NVUtil.copyToProperties(conn_prop, cprof.properties) + prop.mergeProperties(conn_prop.getNode("dataport") + ) # marge ConnectorProfile + # marge ConnectorProfile for buffer property. + prop.mergeProperties(conn_prop.getNode("dataport.inport")) + + if not self.isExistingMarshalingType(prop): + return RTC.RTC_ERROR + + # + # ここで, ConnectorProfile からの properties がマージされたため、 + # prop["dataflow_type"]: データフロータイプ + # prop["interface_type"]: インターフェースタイプ + # などがアクセス可能になる。 + # + dflow_type = prop.getProperty("dataflow_type") + dflow_type = OpenRTM_aist.normalize(dflow_type) + + profile = OpenRTM_aist.ConnectorInfo(cprof.name, + cprof.connector_id, + OpenRTM_aist.CORBA_SeqUtil.refToVstring( + cprof.ports), + prop) + if dflow_type == "push": + self._rtcout.RTC_DEBUG("dataflow_type = push .... do nothing") + + conn = self.getConnectorById(cprof.connector_id) + + if not conn: + self._rtcout.RTC_ERROR("specified connector not found: %s", + cprof.connector_id) + return RTC.RTC_ERROR + + ret = conn.setConnectorInfo(profile) + if ret == RTC.RTC_OK: + self._rtcout.RTC_DEBUG( + "subscribeInterfaces() successfully finished.") + + return ret + + elif dflow_type == "pull": + self._rtcout.RTC_DEBUG( + "dataflow_type = pull .... create PullConnector") + + # create OutPortConsumer + consumer = self.createConsumer(cprof, prop) + if not consumer: + return RTC.BAD_PARAMETER + + # create InPortPullConnector + connector = self.createConnector(cprof, prop, consumer_=consumer) + + if not connector: + return RTC.RTC_ERROR + + connector.setDataType(self._value) + + ret = connector.setConnectorInfo(profile) + + if ret == RTC.RTC_OK: + self._rtcout.RTC_DEBUG( + "publishInterface() successfully finished.") + + return ret + + elif dflow_type == "duplex": + self._rtcout.RTC_DEBUG( + "dataflow_type = duplex .... set Consumer Object") + # create OutPortConsumer + consumer = self.createConsumer(cprof, prop) + if not consumer: + return RTC.BAD_PARAMETER + + connector = self.getConnectorById(cprof.connector_id) + if not connector: + return RTC.RTC_ERROR + + connector.setConsumer(consumer) + ret = connector.setConnectorInfo(profile) + connector.setDataType(self._value) + + if ret == RTC.RTC_OK: + self._rtcout.RTC_DEBUG( + "publishInterface() successfully finished.") + + return ret + + self._rtcout.RTC_ERROR("unsupported dataflow_type") + return RTC.BAD_PARAMETER + + ## + # @if jp + # @brief Interfaceへの接続を解除する + # + # Interfaceへの接続を解除する。 + # 与えられたConnectorProfileに関連するConsumerに設定された全てのObjectを + # 解放し接続を解除する。 + # + # @param connector_profile コネクタ・プロファイル + # + # @else + # @brief Disconnect the interface connection + # + # Disconnect the interface connection. + # Release all objects set in Consumer associated with + # given ConnectorProfile and unscribe the interface. + # + # @param connector_profile The connector profile + # + # @endif + # + # void unsubscribeInterfaces(const ConnectorProfile& connector_profile); + + def unsubscribeInterfaces(self, connector_profile): + self._rtcout.RTC_TRACE("unsubscribeInterfaces()") + + id = connector_profile.connector_id + self._rtcout.RTC_PARANOID("connector_id: %s", id) + + len_ = len(self._connectors) + for i in range(len_): + idx = (len_ - 1) - i + # guard = OpenRTM_aist.ScopedLock(self._connector_mutex) + if id == self._connectors[idx].id(): + # Connector's dtor must call disconnect() + self._connectors[idx].unsubscribeInterface( + connector_profile.properties) + self._connectors[idx].deactivate() + self._connectors[idx].disconnect() + del self._connectors[idx] + self._rtcout.RTC_TRACE("delete connector: %s", id) + return + + self._rtcout.RTC_ERROR("specified connector not found: %s", id) + return + + ## + # @if jp + # @brief InPort provider の初期化 + # @else + # @brief InPort provider initialization + # @endif + # + # void initProviders(); + + def initProviders(self): + self._rtcout.RTC_TRACE("initProviders()") + + # create InPort providers + factory = OpenRTM_aist.InPortProviderFactory.instance() + provider_types = factory.getIdentifiers() + + self._rtcout.RTC_DEBUG("available providers: %s", + OpenRTM_aist.flatten(provider_types)) + + if self._properties.hasKey("provider_types") and \ + OpenRTM_aist.normalize(self._properties.getProperty("provider_types")) != "all": + self._rtcout.RTC_DEBUG("allowed providers: %s", + self._properties.getProperty("provider_types")) + + temp_types = provider_types + provider_types = [] + active_types = OpenRTM_aist.split( + self._properties.getProperty("provider_types"), ",") + + temp_types.sort() + active_types.sort() + + set_ptypes = set(temp_types).intersection(set(active_types)) + provider_types = provider_types + list(set_ptypes) + + # InPortProvider supports "push" dataflow type + if provider_types: + self._rtcout.RTC_DEBUG("dataflow_type push is supported") + self.appendProperty("dataport.dataflow_type", "push") + for provider_type in provider_types: + self.appendProperty("dataport.interface_type", provider_type) + + self._providerTypes = provider_types + return + + ## + # @if jp + # @brief OutPort consumer の初期化 + # @else + # @brief OutPort consumer initialization + # @endif + # + # void initConsumers(); + + def initConsumers(self): + self._rtcout.RTC_TRACE("initConsumers()") + + # create OuPort consumers + factory = OpenRTM_aist.OutPortConsumerFactory.instance() + consumer_types = factory.getIdentifiers() + self._rtcout.RTC_DEBUG("available consumers: %s", + OpenRTM_aist.flatten(consumer_types)) + + if self._properties.hasKey("consumer_types") and \ + OpenRTM_aist.normalize(self._properties.getProperty("consumer_types")) != "all": + self._rtcout.RTC_DEBUG("allowed consumers: %s", + self._properties.getProperty("consumer_types")) + + temp_types = consumer_types + consumer_types = [] + active_types = OpenRTM_aist.split( + self._properties.getProperty("consumer_types"), ",") + + temp_types.sort() + active_types.sort() + + set_ctypes = set(temp_types).intersection(set(active_types)) + consumer_types = consumer_types + list(set_ctypes) + + # OutPortConsumer supports "pull" dataflow type + if consumer_types: + self._rtcout.RTC_PARANOID("dataflow_type pull is supported") + self.appendProperty("dataport.dataflow_type", "pull") + for consumer_type in consumer_types: + self.appendProperty("dataport.interface_type", consumer_type) + + self._consumerTypes = consumer_types + return + + ## + # @if jp + # @brief InPort provider の生成 + # + # InPortProvider を生成し、情報を ConnectorProfile に公開する。 + # 生成に失敗した場合 0 を返す。 + # + # @else + # @brief InPort provider creation + # @endif + # + # InPortProvider* + # createProvider(ConnectorProfile& cprof, coil::Properties& prop); + + def createProvider(self, cprof, prop): + if not prop.getProperty("interface_type") or \ + not OpenRTM_aist.includes(self._providerTypes, prop.getProperty("interface_type")): + self._rtcout.RTC_ERROR("no provider found") + self._rtcout.RTC_DEBUG( + "interface_type: %s", + prop.getProperty("interface_type")) + self._rtcout.RTC_DEBUG("interface_types: %s", + OpenRTM_aist.flatten(self._providerTypes)) + return None + + self._rtcout.RTC_DEBUG( + "interface_type: %s", + prop.getProperty("interface_type")) + provider = OpenRTM_aist.InPortProviderFactory.instance( + ).createObject(prop.getProperty("interface_type")) + + if provider is not None: + self._rtcout.RTC_DEBUG("provider created") + provider.init(prop.getNode("provider")) + + if not provider.publishInterface(cprof.properties): + self._rtcout.RTC_ERROR( + "publishing interface information error") + return None + return provider + + self._rtcout.RTC_ERROR("provider creation failed") + return None + + ## + # @if jp + # @brief OutPort consumer の生成 + # + # OutPortConsumer を生成する。 + # 生成に失敗した場合 0 を返す。 + # + # @else + # @brief InPort provider creation + # @endif + # + # OutPortConsumer* + # createConsumer(const ConnectorProfile& cprof, coil::Properties& prop); + + def createConsumer(self, cprof, prop): + if not prop.getProperty("interface_type") or \ + not OpenRTM_aist.includes(self._consumerTypes, prop.getProperty("interface_type")): + self._rtcout.RTC_ERROR("no consumer found") + self._rtcout.RTC_DEBUG( + "interface_type: %s", + prop.getProperty("interface_type")) + self._rtcout.RTC_DEBUG("interface_types: %s", + OpenRTM_aist.flatten(self._consumerTypes)) + return None + + self._rtcout.RTC_DEBUG( + "interface_type: %s", + prop.getProperty("interface_type")) + consumer = OpenRTM_aist.OutPortConsumerFactory.instance( + ).createObject(prop.getProperty("interface_type")) + + if consumer is not None: + self._rtcout.RTC_DEBUG("consumer created") + consumer.init(prop.getNode("consumer")) + + if not consumer.subscribeInterface(cprof.properties): + self._rtcout.RTC_ERROR("interface subscription failed.") + return None + return consumer + + self._rtcout.RTC_ERROR("consumer creation failed") + return None + + ## + # @if jp + # @brief InPortPushConnector の生成 + # + # Connector を生成し、生成が成功すれば m_connectors に保存する。 + # 生成に失敗した場合 None を返す。 + # + # @else + # @brief InPortPushConnector creation + # @endif + # + # InPortConnector* + # createConnector(ConnectorProfile& cprof, coil::Properties& prop, + # InPortProvider* provider); + + def createConnector(self, cprof, prop, provider_=None, consumer_=None): + profile = OpenRTM_aist.ConnectorInfo(cprof.name, + cprof.connector_id, + OpenRTM_aist.CORBA_SeqUtil.refToVstring( + cprof.ports), + prop) + connector = None + + try: + if provider_ is not None: + if self._singlebuffer: + connector = OpenRTM_aist.InPortPushConnector(profile, provider_, + self._listeners, + self._thebuffer) + else: + connector = OpenRTM_aist.InPortPushConnector(profile, provider_, + self._listeners) + + elif consumer_ is not None: + if self._singlebuffer: + connector = OpenRTM_aist.InPortPullConnector(profile, consumer_, + self._listeners, + self._thebuffer) + else: + connector = OpenRTM_aist.InPortPullConnector(profile, consumer_, + self._listeners) + + else: + self._rtcout.RTC_ERROR( + "provider or consumer is not passed. returned 0;") + return None + + # if connector is None: + # self._rtcout.RTC_ERROR("InPortConnector creation failed") + # return 0 + + if provider_ is not None: + self._rtcout.RTC_TRACE("InPortPushConnector created") + elif consumer_ is not None: + self._rtcout.RTC_TRACE("InPortPullConnector created") + + if OpenRTM_aist.StringUtil.normalize( + prop.getProperty("interface_type")) == "direct": + if consumer_ is not None: + outport = self.getLocalOutPort(profile) + + if outport is None: + self._rtcout.RTC_TRACE("interface_type is direct, ") + self._rtcout.RTC_TRACE( + "but a peer OutPort servant could not be obtained.") + del connector + return None + connector.setOutPort(outport) + + # guard = OpenRTM_aist.ScopedLock(self._connector_mutex) + self._connectors.append(connector) + self._rtcout.RTC_PARANOID( + "connector push backed: %d", len( + self._connectors)) + return connector + except BaseException: + self._rtcout.RTC_ERROR("InPortPushConnector creation failed") + self._rtcout.RTC_ERROR(OpenRTM_aist.Logger.print_exception()) + return None + + ## + # @if jp + # @brief InPortDuplexConnector の生成 + # + # 双方向通信用コネクタを生成し、生成が成功すれば m_connectors に保存する。 + # + # + # @param cprof コネクタプロファイル + # @param prop コネクタプロファイルをプロパティに変換 + # @param provider_ プロバイダ + # @return 生成したコネクタ。生成に失敗した場合 None を返す。 + # + # @else + # @brief InPortDuplexConnector creation + # + # @param cprof + # @param prop + # @param provider_ + # @return + # + # @endif + # + def createDuplexConnector(self, cprof, prop, provider_): + profile = OpenRTM_aist.ConnectorInfo(cprof.name, + cprof.connector_id, + OpenRTM_aist.CORBA_SeqUtil.refToVstring( + cprof.ports), + prop) + connector = None + try: + if self._singlebuffer: + connector = OpenRTM_aist.InPortDuplexConnector(profile, provider_, + self._listeners, + self._thebuffer) + else: + connector = OpenRTM_aist.InPortDuplexConnector(profile, provider_, + self._listeners) + + self._rtcout.RTC_TRACE("InPortDuplexConnector created") + + # guard = OpenRTM_aist.ScopedLock(self._connector_mutex) + self._connectors.append(connector) + self._rtcout.RTC_PARANOID( + "connector duplex backed: %d", len( + self._connectors)) + return connector + except BaseException: + self._rtcout.RTC_ERROR("InPortDuplexConnector creation failed") + self._rtcout.RTC_ERROR(OpenRTM_aist.Logger.print_exception()) return None - connector.setOutPort(outport) - - - # guard = OpenRTM_aist.ScopedLock(self._connector_mutex) - self._connectors.append(connector) - self._rtcout.RTC_PARANOID("connector push backed: %d", len(self._connectors)) - return connector - except: - self._rtcout.RTC_ERROR("InPortPushConnector creation failed") - self._rtcout.RTC_ERROR(OpenRTM_aist.Logger.print_exception()) - return None - - - ## - # @if jp - # @brief ΥԥOutPort - # @param self - # @param profile ͥץե - # @return OutPortΥХ(˼ԤNone) - # @else - # @brief Getting local peer OutPort if available - # @param self - # @param profile - # @return - # @endif - # - # OutPortBase* - # getLocalOutPort(const ConnectorInfo& profile) - def getLocalOutPort(self, profile): - self._rtcout.RTC_DEBUG("Trying direct port connection.") - orb = OpenRTM_aist.Manager.instance().getORB() - self._rtcout.RTC_DEBUG("Current connector profile: name=%s, id=%s" % (profile.name, profile.id)) - for p in profile.ports: - obj = orb.string_to_object(p) - if self.getPortRef()._is_equivalent(obj): - continue - self._rtcout.RTC_DEBUG("Peer port found: %s." % p) - try: - poa = OpenRTM_aist.Manager.instance().getPOA() - outport = poa.reference_to_servant(obj) - self._rtcout.RTC_DEBUG("OutPortBase servant pointer is obtained.") - return outport - except: - self._rtcout.RTC_DEBUG("Peer port might be a remote port") - return None + + ## + # @if jp + # @brief ローカルのピアOutPortを取得 + # @param self + # @param profile コネクタプロファイル + # @return OutPortのサーバント(取得に失敗した場合はNone) + # @else + # @brief Getting local peer OutPort if available + # @param self + # @param profile + # @return + # @endif + # + # OutPortBase* + # getLocalOutPort(const ConnectorInfo& profile) + + def getLocalOutPort(self, profile): + self._rtcout.RTC_DEBUG("Trying direct port connection.") + orb = OpenRTM_aist.Manager.instance().getORB() + self._rtcout.RTC_DEBUG( + "Current connector profile: name=%s, id=%s" % + (profile.name, profile.id)) + for p in profile.ports: + obj = orb.string_to_object(p) + if self.getPortRef()._is_equivalent(obj): + continue + self._rtcout.RTC_DEBUG("Peer port found: %s." % p) + try: + poa = OpenRTM_aist.Manager.instance().getPOA() + outport = poa.reference_to_servant(obj) + self._rtcout.RTC_DEBUG( + "OutPortBase servant pointer is obtained.") + return outport + except BaseException: + self._rtcout.RTC_DEBUG("Peer port might be a remote port") + return None diff --git a/OpenRTM_aist/InPortCSPConsumer.py b/OpenRTM_aist/InPortCSPConsumer.py new file mode 100644 index 00000000..660f0d4e --- /dev/null +++ b/OpenRTM_aist/InPortCSPConsumer.py @@ -0,0 +1,194 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- + +## +# @file InPortCSPConsumer.py +# @brief InPortCSPConsumer class +# @date $Date: 2016/01/08 $ +# @author Nobuhiko Miyamoto + + +import OpenRTM_aist +import OpenRTM +import CSP + + +## +# @if jp +# @class InPortCSPConsumer +# @brief InPortCSPConsumer クラス +# +# CSPモデルのチャネルを模擬した入力ポートプロバイダーの実装クラス。 +# +# +# @else +# @class InPortCSPConsumer +# @brief InPortCSPConsumer class +# +# +# +# @endif +# +class InPortCSPConsumer(OpenRTM_aist.InPortCorbaCdrConsumer): + + """ + """ + + ## + # @if jp + # @brief コンストラクタ + # + # コンストラクタ + # Interface Typeにはshared_memoryを指定する + # 共有メモリの空間名はUUIDで作成し、コネクタプロファイルのdataport.shared_memory.addressに保存する + # + # self + # + # @else + # @brief Constructor + # + # Constructor + # + # self + # @endif + # + def __init__(self): + OpenRTM_aist.InPortCorbaCdrConsumer.__init__(self) + OpenRTM_aist.CorbaConsumer.__init__(self, CSP.InPortCsp) + self._rtcout = OpenRTM_aist.Manager.instance().getLogbuf("InPortCSPConsumer") + self._properties = None + return + + ## + # @if jp + # @brief デストラクタ + # + # デストラクタ + # + # @param self + # + # @else + # @brief Destructor + # + # Destructor + # + # @param self + # + # @endif + # + def __del__(self, CorbaConsumer=OpenRTM_aist.CorbaConsumer): + self._rtcout.RTC_PARANOID("~InPortCSPConsumer()") + CorbaConsumer.__del__(self) + + # void init(coil::Properties& prop) + + def init(self, prop): + self._rtcout.RTC_TRACE("init()") + self._properties = prop + + ## + # @if jp + # @brief バッファをセットする + # + # + # @param buffer OutPortProviderがデータを取り出すバッファへのポインタ + # + # @else + # @brief Setting outside buffer's pointer + # + # @param buffer A pointer to a data buffer to be used by OutPortProvider + # + # @endif + # + # virtual void setBuffer(CdrBufferBase* buffer); + + def setBuffer(self, buffer): + pass + + # void OutPortCorbaCdrConsumer::setListener(ConnectorInfo& info, + # ConnectorListeners* listeners) + + def setListener(self, info, listeners): + self._rtcout.RTC_TRACE("setListener()") + self._listeners = listeners + self._profile = info + return + + def setConnector(self, connector): + self._connector = connector + return + + ## + # @if jp + # @brief バッファにデータを書き込む + # + # + # @param self + # @param data 書込対象データ + # @return リターンコード + # PORT_OK:正常完了 + # PORT_ERROR:バッファ書き込みエラー、通常は発生しない + # SEND_FULL:バッファがフル + # SEND_TIMEOUT:書き込みタイムアウト + # UNKNOWN_ERROR:その他のエラー + # CONNECTION_LOST:通信エラー + # + # @else + # @brief + # + # + # @param self + # @param data + # @return + # + # @endif + # + def put(self, data): + self._rtcout.RTC_PARANOID("get()") + + try: + outportcsp = self._ptr() + if outportcsp: + ret = outportcsp.put(data) + return self.convertReturnCode(ret) + return self.CONNECTION_LOST + except BaseException: + self._rtcout.RTC_ERROR(OpenRTM_aist.Logger.print_exception()) + return self.CONNECTION_LOST + + ## + # @if jp + # @brief 書き込み可能かを接続先のProviderに確認 + # + # + # @param self + # @param retry True:再検索、False:通常の書き込み確認 + # @return True:書き込み可能、False:書き込み不可 + # + # @else + # @brief + # + # + # @param self + # @param retry + # @return + # + # @endif + # + def isWritable(self, retry=False): + self._rtcout.RTC_PARANOID("isWritable()") + try: + outportcsp = self._ptr() + if outportcsp: + return outportcsp.is_writable(retry) + return False + except BaseException: + self._rtcout.RTC_WARN("Exception caught from InPort.isWritable().") + self._rtcout.RTC_ERROR(OpenRTM_aist.Logger.print_exception()) + return False + + +def InPortCSPConsumerInit(): + factory = OpenRTM_aist.InPortConsumerFactory.instance() + factory.addFactory("csp_channel", + OpenRTM_aist.InPortCSPConsumer) diff --git a/OpenRTM_aist/InPortCSPProvider.py b/OpenRTM_aist/InPortCSPProvider.py new file mode 100644 index 00000000..f65d9f18 --- /dev/null +++ b/OpenRTM_aist/InPortCSPProvider.py @@ -0,0 +1,276 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- + +## +# @file InPortSHMProvider.py +# @brief InPortSHMProvider class +# @date $Date: 2016/01/08 $ +# @author Nobuhiko Miyamoto + + +import OpenRTM_aist +import OpenRTM +import CSP__POA + + +## +# @if jp +# @class InPortCSPProvider +# @brief InPortCSPProvider クラス +# +# CSPモデルのチャネルを模擬した入力ポートプロバイダーの実装クラス。 +# +# +# @else +# @class InPortCSPProvider +# @brief InPortCSPProvider class +# +# +# +# @endif +# +class InPortCSPProvider(OpenRTM_aist.InPortProvider, CSP__POA.InPortCsp): + + """ + """ + + ## + # @if jp + # @brief コンストラクタ + # + # コンストラクタ + # Interface Typeにはshared_memoryを指定する + # 共有メモリの空間名はUUIDで作成し、コネクタプロファイルのdataport.shared_memory.addressに保存する + # + # self + # + # @else + # @brief Constructor + # + # Constructor + # + # self + # @endif + # + def __init__(self): + OpenRTM_aist.InPortProvider.__init__(self) + self._rtcout = OpenRTM_aist.Manager.instance().getLogbuf("CSPOutPort") + + # PortProfile setting + self.setInterfaceType("csp_channel") + self._objref = self._this() + + self._buffer = None + + self._profile = None + self._listeners = None + + orb = OpenRTM_aist.Manager.instance().getORB() + self._properties.append(OpenRTM_aist.NVUtil.newNV("dataport.corba_cdr.inport_ior", + orb.object_to_string(self._objref))) + self._properties.append(OpenRTM_aist.NVUtil.newNV("dataport.corba_cdr.inport_ref", + self._objref)) + + return + + ## + # @if jp + # @brief デストラクタ + # + # デストラクタ + # + # @param self + # + # @else + # @brief Destructor + # + # Destructor + # + # @param self + # + # @endif + # + def __del__(self): + return + + ## + # @if jp + # @brief 終了処理 + # + # @else + # @brief + # + # + # + # @endif + # + def exit(self): + oid = OpenRTM_aist.Manager.instance().getPOA().servant_to_id(self) + OpenRTM_aist.Manager.instance().getPOA().deactivate_object(oid) + + # void init(coil::Properties& prop) + + def init(self, prop): + pass + + def setBuffer(self, buffer): + self._buffer = buffer + return + + def setListener(self, info, listeners): + self._profile = info + self._listeners = listeners + return + + def setConnector(self, connector): + self._connector = connector + return + ## + # @if jp + # @brief バッファにデータを書き込む + # + # データのサイズは共有メモリも先頭8byteから取得する + # 共有メモリからデータを取り出しバッファに書き込む + # + # @param data 書込対象データ + # + # @else + # @brief + # + # + # + # @param data + # + # @endif + # + # ::OpenRTM::PortStatus put() + # throw (CORBA::SystemException); + def put(self, data): + + try: + self._rtcout.RTC_PARANOID("InPortCSPProvider.put()") + + if not self._connector: + self.onReceiverError(data) + return OpenRTM.PORT_ERROR + + self._rtcout.RTC_PARANOID("received data size: %d", len(data)) + + data = self.onReceived(data) + + ret = self._connector.write(data) + + return self.convertReturn(ret, data) + + except BaseException: + self._rtcout.RTC_TRACE(OpenRTM_aist.Logger.print_exception()) + return OpenRTM.UNKNOWN_ERROR + + ## + # @if jp + # @brief データ書き込み可能かを確認 + # + # @param self + # @param retry True:再検索、False:通常の書き込み確認 + # @return True:書き込み可能、False:書き込み不可 + # + # + # @else + # @brief + # + # @param self + # @param retry + # @return + # + # @endif + # + + def is_writable(self, retry): + self._rtcout.RTC_PARANOID("is_writable()") + if self._connector: + return self._connector.isWritable(retry) + return False + + def onBufferWrite(self, data): + if self._listeners is not None and self._profile is not None: + _, data = self._listeners.notifyData( + OpenRTM_aist.ConnectorDataListenerType.ON_BUFFER_WRITE, self._profile, data) + return data + + def onBufferFull(self, data): + if self._listeners is not None and self._profile is not None: + _, data = self._listeners.notifyData( + OpenRTM_aist.ConnectorDataListenerType.ON_BUFFER_FULL, self._profile, data) + return data + + def onBufferWriteTimeout(self, data): + if self._listeners is not None and self._profile is not None: + _, data = self._listeners.notifyData( + OpenRTM_aist.ConnectorDataListenerType.ON_BUFFER_WRITE_TIMEOUT, self._profile, data) + return data + + def onBufferWriteOverwrite(self, data): + if self._listeners is not None and self._profile is not None: + _, data = self._listeners.notifyData( + OpenRTM_aist.ConnectorDataListenerType.ON_BUFFER_OVERWRITE, self._profile, data) + return data + + def onReceived(self, data): + if self._listeners is not None and self._profile is not None: + _, data = self._listeners.notifyData( + OpenRTM_aist.ConnectorDataListenerType.ON_RECEIVED, self._profile, data) + return data + + def onReceiverFull(self, data): + if self._listeners is not None and self._profile is not None: + self._listeners.notifyData( + OpenRTM_aist.ConnectorDataListenerType.ON_RECEIVER_FULL, self._profile, data) + return + + def onReceiverTimeout(self, data): + if self._listeners is not None and self._profile is not None: + _, data = self._listeners.notifyData( + OpenRTM_aist.ConnectorDataListenerType.ON_RECEIVER_TIMEOUT, self._profile, data) + return data + + def onReceiverError(self, data): + if self._listeners is not None and self._profile is not None: + _, data = self._listeners.notifyData( + OpenRTM_aist.ConnectorDataListenerType.ON_RECEIVER_ERROR, self._profile, data) + return data + + def convertReturn(self, status, data): + if status == OpenRTM_aist.BufferStatus.BUFFER_OK: + self.onBufferWrite(data) + return OpenRTM.PORT_OK + + elif status == OpenRTM_aist.BufferStatus.BUFFER_ERROR: + self.onReceiverError(data) + return OpenRTM.PORT_ERROR + + elif status == OpenRTM_aist.BufferStatus.BUFFER_FULL: + data = self.onBufferFull(data) + self.onReceiverFull(data) + return OpenRTM.BUFFER_FULL + + elif status == OpenRTM_aist.BufferStatus.BUFFER_EMPTY: + return OpenRTM.BUFFER_EMPTY + + elif status == OpenRTM_aist.BufferStatus.PRECONDITION_NOT_MET: + self.onReceiverError(data) + return OpenRTM.PORT_ERROR + + elif status == OpenRTM_aist.BufferStatus.TIMEOUT: + data = self.onBufferWriteTimeout(data) + self.onReceiverTimeout(data) + return OpenRTM.BUFFER_TIMEOUT + + else: + self.onReceiverError(data) + return OpenRTM.UNKNOWN_ERROR + + +def InPortCSPProviderInit(): + factory = OpenRTM_aist.InPortProviderFactory.instance() + factory.addFactory("csp_channel", + OpenRTM_aist.InPortCSPProvider) diff --git a/OpenRTM_aist/InPortConnector.py b/OpenRTM_aist/InPortConnector.py index cd7536d6..7b530691 100644 --- a/OpenRTM_aist/InPortConnector.py +++ b/OpenRTM_aist/InPortConnector.py @@ -1,5 +1,5 @@ #!/usr/bin/env python -# -*- coding: euc-jp -*- +# -*- coding: utf-8 -*- ## # @file InPortConnector.py @@ -23,16 +23,16 @@ ## # @if jp # @class InPortConnector -# @brief InPortConnector 쥯饹 +# @brief InPortConnector 基底クラス # -# InPort Push/Pull Ƽ Connector 뤿 -# 쥯饹 +# InPort の Push/Pull 各種 Connector を派生させるための +# 基底クラス。 # # @since 1.0.0 # # @else # @class InPortConnector -# @brief IPortConnector base class +# @brief InPortConnector base class # # The base class to derive subclasses for InPort's Push/Pull Connectors # @@ -41,179 +41,254 @@ # @endif # class InPortConnector(OpenRTM_aist.ConnectorBase): - """ - """ - - ## - # @if jp - # @brief 󥹥ȥ饯 - # @else - # @brief Constructor - # @endif - # - # InPortConnector(ConnectorInfo& info, - # CdrBufferBase* buffer); - def __init__(self, info, buffer): - self._rtcout = OpenRTM_aist.Manager.instance().getLogbuf("InPortConnector") - self._profile = info - self._buffer = buffer - self._dataType = None - self._endian = None - - - ## - # @if jp - # @brief ǥȥ饯 - # @else - # @brief Destructor - # @endif - # - def __del__(self): - pass - - - ## - # @if jp - # @brief ConnectorInfo - # - # Connector ConnectorInfo - # - # @else - # @brief Getting ConnectorInfo - # - # This operation returns ConnectorInfo - # - # @endif - # - # const ConnectorInfo& profile(); - def profile(self): - self._rtcout.RTC_TRACE("profile()") - return self._profile - - - ## - # @if jp - # @brief Connector ID - # - # Connector ID - # - # @else - # @brief Getting Connector ID - # - # This operation returns Connector ID - # - # @endif - # - # const char* id(); - def id(self): - self._rtcout.RTC_TRACE("id() = %s", self.profile().id) - return self.profile().id - - - ## - # @if jp - # @brief Connector ̾ - # - # Connector ̾ - # - # @else - # @brief Getting Connector name - # - # This operation returns Connector name - # - # @endif - # - # const char* name(); - def name(self): - self._rtcout.RTC_TRACE("name() = %s", self.profile().name) - return self.profile().name - - - ## - # @if jp - # @brief ³ؿ - # - # Connector ݻƤ³ - # - # @else - # @brief Disconnect connection - # - # This operation disconnect this connection - # - # @endif - # - # virtual ReturnCode disconnect() = 0; - def disconnect(self): - pass - - ## - # @if jp - # @brief Buffer - # - # Connector ݻƤ Buffer ֤ - # - # @else - # @brief Getting Buffer - # - # This operation returns this connector's buffer - # - # @endif - # - # virtual CdrBufferBase* getBuffer(); - def getBuffer(self): - return self._buffer - - ## - # @if jp - # @brief read ؿ - # - # Buffer ǡ InPort read ؿ - # - # @else - # @brief Destructor - # - # The read function to read data from buffer to InPort - # - # @endif - # - # virtual ReturnCode read(cdrMemoryStream& data) = 0; - def read(self, data): - pass - - # void setConnectorInfo(ConnectorInfo profile); - def setConnectorInfo(self, profile): - self._profile = profile - - if self._profile.properties.hasKey("serializer"): - endian = self._profile.properties.getProperty("serializer.cdr.endian") - if not endian: - self._rtcout.RTC_ERROR("InPortConnector.setConnectorInfo(): endian is not supported.") - return RTC.RTC_ERROR - - endian = OpenRTM_aist.split(endian, ",") # Maybe endian is ["little","big"] - endian = OpenRTM_aist.normalize(endian) # Maybe self._endian is "little" or "big" - - if endian == "little": + """ + """ + + ## + # @if jp + # @brief コンストラクタ + # @else + # @brief Constructor + # @endif + # + # InPortConnector(ConnectorInfo& info, + # CdrBufferBase* buffer); + def __init__(self, info, buffer): + self._rtcout = OpenRTM_aist.Manager.instance().getLogbuf("InPortConnector") + self._profile = info + self._buffer = buffer + self._dataType = None self._endian = True - elif endian == "big": - self._endian = False - else: - self._endian = None - - else: - self._endian = True # little endian - return RTC.RTC_OK + ## + # @if jp + # @brief デストラクタ + # @else + # @brief Destructor + # @endif + # + + def __del__(self): + pass + + ## + # @if jp + # @brief ConnectorInfo 取得 + # + # Connector ConnectorInfo を取得する + # + # @else + # @brief Getting ConnectorInfo + # + # This operation returns ConnectorInfo + # + # @endif + # + # const ConnectorInfo& profile(); + + def profile(self): + self._rtcout.RTC_TRACE("profile()") + return self._profile + + ## + # @if jp + # @brief Connector ID 取得 + # + # Connector ID を取得する + # + # @else + # @brief Getting Connector ID + # + # This operation returns Connector ID + # + # @endif + # + # const char* id(); + + def id(self): + self._rtcout.RTC_TRACE("id() = %s", self.profile().id) + return self.profile().id + + ## + # @if jp + # @brief Connector 名取得 + # + # Connector 名を取得する + # + # @else + # @brief Getting Connector name + # + # This operation returns Connector name + # + # @endif + # + # const char* name(); + + def name(self): + self._rtcout.RTC_TRACE("name() = %s", self.profile().name) + return self.profile().name + + ## + # @if jp + # @brief 接続解除関数 + # + # Connector が保持している接続を解除する + # + # @else + # @brief Disconnect connection + # + # This operation disconnect this connection + # + # @endif + # + # virtual ReturnCode disconnect() = 0; + + def disconnect(self): + pass + + ## + # @if jp + # @brief Buffer を所得する + # + # Connector が保持している Buffer を返す + # + # @else + # @brief Getting Buffer + # + # This operation returns this connector's buffer + # + # @endif + # + # virtual CdrBufferBase* getBuffer(); + def getBuffer(self): + return self._buffer + + ## + # @if jp + # @brief read 関数 + # + # Buffer からデータを InPort へ read する関数 + # + # @else + # @brief + # + # The read function to read data from buffer to InPort + # + # @endif + # + # virtual ReturnCode read(cdrMemoryStream& data) = 0; + def read(self, data=None): + pass + + # void setConnectorInfo(ConnectorInfo profile); + def setConnectorInfo(self, profile): + self._profile = profile + + if self._profile.properties.hasKey("serializer"): + endian = self._profile.properties.getProperty( + "serializer.cdr.endian") + if not endian: + self._rtcout.RTC_ERROR( + "InPortConnector.setConnectorInfo(): endian is not supported.") + return RTC.RTC_ERROR + + # Maybe endian is ["little","big"] + endian = OpenRTM_aist.split(endian, ",") + # Maybe self._endian is "little" or "big" + endian = OpenRTM_aist.normalize(endian[0]) + + if endian == "little": + self._endian = True + elif endian == "big": + self._endian = False + else: + self._endian = None + + else: + self._endian = True # little endian + + return RTC.RTC_OK + + # template + # void setDataTyep(DataType data); + + def setDataType(self, data): + self._dataType = data + + def write(self, data): + pass + + # + # @if jp + # @brief データ書き込み時のリスナ設定 + # @param self + # @param listener リスナ + # @else + # @brief + # @param self + # @param listener + # @endif + def setWriteListener(self, listener): + pass + + # + # @if jp + # @brief データ書き込み判定時のリスナ設定 + # @param self + # @param listener リスナ + # @else + # @brief + # @param self + # @param listener + # @endif + def setIsWritableListener(self, listener): + pass + # + # @if jp + # @brief データを書き込める状態かを判定 + # @param self + # @return True:書き込み可能 + # @else + # @brief + # @param self + # @return + # @endif + def isWritable(self): + return False + # + # @if jp + # @brief データを読み込める状態かを判定 + # @param self + # @param retry True:再確認、False:通常の読み込み確認 + # @return True:読み込み可能 + # @else + # @brief + # @param self + # @param retry + # @return + # @endif - # template - # void setDataTyep(DataType data); - def setDataType(self, data): - self._dataType = data + def isReadable(self, retry): + return False + ## + # @if jp + # @brief コンシューマの設定 + # @else + # @brief set Consumer + # @endif + def setConsumer(self, consumer): + pass - def write(self, data): - pass - def read(self, data): - pass \ No newline at end of file + ## + # @if jp + # @brief コンシューマのインターフェースの登録を取り消す + # @param prop コネクタプロファイルのプロパティ + # @else + # @brief + # @param prop + # @endif + def unsubscribeInterface(self, prop): + pass diff --git a/OpenRTM_aist/InPortConsumer.py b/OpenRTM_aist/InPortConsumer.py index 1b316f9b..477da4c3 100644 --- a/OpenRTM_aist/InPortConsumer.py +++ b/OpenRTM_aist/InPortConsumer.py @@ -1,5 +1,5 @@ #!/usr/bin/env python -# -*- coding: euc-jp -*- +# -*- coding: utf-8 -*- ## @@ -24,14 +24,14 @@ # # @class InPortConsumer # -# @brief InPortConsumer 쥯饹 +# @brief InPortConsumer 基底クラス # -# ϥݡȥ󥷥塼ޤΤݥ󥿡ե饹 -# ƶݥ饹ϡʲδؿμ󶡤ʤФʤʤ -# - push(): ǡ -# - clone(): ݡȤΥԡ -# - subscribeInterface(): ǡΤؤϿ -# - unsubscribeInterface(): ǡΤϿ +# 入力ポートコンシューマのための抽象インターフェースクラス +# 各具象クラスは、以下の関数の実装を提供しなければならない。 +# - push(): データ送信 +# - clone(): ポートのコピー +# - subscribeInterface(): データ送出通知への登録 +# - unsubscribeInterface(): データ送出通知の登録解除 # # @since 0.4.0 # @@ -39,62 +39,67 @@ # @class InPortConsumer # @brief InPortConsumer class # @endif -class InPortConsumer(OpenRTM_aist.DataPortStatus): - """ - """ +class InPortConsumer(OpenRTM_aist.DataPortStatus): + """ + """ - ## - # @if jp - # @brief 󥿡եץե뤿Υե󥯥 - # @else - # @brief Functor to publish interface profile - # @endif - # - class publishInterfaceProfileFunc: - def __init__(self, prop): - self._prop = prop + def put(self, data): + return self.CONNECTION_LOST - def __call__(self, consumer): - consumer.publishInterfaceProfile(self._prop) + def isWritable(self): + return True + ## + # @if jp + # @brief インターフェースプロファイルを公開するたのファンクタ + # @else + # @brief Functor to publish interface profile + # @endif + # - ## - # @if jp - # @brief 󥿡եץե뤿Υե󥯥 - # @else - # @brief Functor to publish interface profile - # @endif - # - class subscribeInterfaceFunc: - def __init__(self, prop): - self._prop = prop + class publishInterfaceProfileFunc: + def __init__(self, prop): + self._prop = prop - def __call__(self, consumer): - return consumer.subscribeInterface(self._prop) + def __call__(self, consumer): + consumer.publishInterfaceProfile(self._prop) + ## + # @if jp + # @brief インターフェースプロファイルを公開するたのファンクタ + # @else + # @brief Functor to publish interface profile + # @endif + # -inportconsumerfactory = None + class subscribeInterfaceFunc: + def __init__(self, prop): + self._prop = prop -class InPortConsumerFactory(OpenRTM_aist.Factory,InPortConsumer): + def __call__(self, consumer): + return consumer.subscribeInterface(self._prop) - def __init__(self): - OpenRTM_aist.Factory.__init__(self) - pass + +inportconsumerfactory = None - def __del__(self): - pass +class InPortConsumerFactory(OpenRTM_aist.Factory, InPortConsumer): + def __init__(self): + OpenRTM_aist.Factory.__init__(self) + pass - def instance(): - global inportconsumerfactory + def __del__(self): + pass - if inportconsumerfactory is None: - inportconsumerfactory = InPortConsumerFactory() + def instance(): + global inportconsumerfactory - return inportconsumerfactory + if inportconsumerfactory is None: + inportconsumerfactory = InPortConsumerFactory() - instance = staticmethod(instance) + return inportconsumerfactory + instance = staticmethod(instance) diff --git a/OpenRTM_aist/InPortCorbaCdrConsumer.py b/OpenRTM_aist/InPortCorbaCdrConsumer.py index c61a6586..f658c328 100644 --- a/OpenRTM_aist/InPortCorbaCdrConsumer.py +++ b/OpenRTM_aist/InPortCorbaCdrConsumer.py @@ -1,5 +1,5 @@ #!/usr/bin/env python -# -*- coding: euc-jp -*- +# -*- coding: utf-8 -*- ## # @file InPortCorbaCdrConsumer.py @@ -27,11 +27,11 @@ # # @class InPortCorbaCdrConsumer # -# @brief InPortCorbaCdrConsumer 饹 +# @brief InPortCorbaCdrConsumer クラス # -# ̿ʤ CORBA Ѥϥݡȥ󥷥塼ޤμ饹 +# 通信手段に CORBA を利用した入力ポートコンシューマの実装クラス。 # -# @param DataType ܥݡȤˤưǡ +# @param DataType 本ポートにて扱うデータ型 # # @since 1.0 # @@ -40,7 +40,7 @@ # # @brief InPortCorbaCdrConsumer class # -# This is an implementation class of the input port Consumer +# This is an implementation class of the input port Consumer # that uses CORBA for means of communication. # # @param DataType Data type for this port @@ -49,409 +49,411 @@ # # @endif # -class InPortCorbaCdrConsumer(OpenRTM_aist.InPortConsumer,OpenRTM_aist.CorbaConsumer): - """ - """ - - ## - # @if jp - # @brief 󥹥ȥ饯 - # - # 󥹥ȥ饯 - # - # @param buffer 󥷥塼ޤ˳ƤХåե֥ - # - # @else - # @brief Constructor - # - # Constructor - # - # @param buffer The buffer object that is attached to this Consumer - # - # @endif - # - def __init__(self): - OpenRTM_aist.CorbaConsumer.__init__(self) - self._rtcout = OpenRTM_aist.Manager.instance().getLogbuf("InPortCorbaCdrConsumer") - self._properties = None - return - - ## - # @if jp - # @brief ǥȥ饯 - # - # ǥȥ饯 - # - # @else - # @brief Destructor - # - # Destructor - # - # @endif - # - def __del__(self, CorbaConsumer=OpenRTM_aist.CorbaConsumer): - self._rtcout.RTC_PARANOID("~InPortCorbaCdrConsumer()") - CorbaConsumer.__del__(self) - return - - ## - # @if jp - # @brief - # - # InPortConsumerγƼԤ - # - # @else - # @brief Initializing configuration - # - # This operation would be called to configure this consumer - # in initialization. - # - # @endif - # - # virtual void init(coil::Properties& prop); - def init(self, prop): - self._rtcout.RTC_TRACE("init()") - self._properties = prop - return - - ## - # @if jp - # @brief ³ؤΥǡ - # - # ³ΥݡȤإǡ뤿ν貾۴ؿ - # - # δؿϡʲΥ꥿󥳡ɤ֤ - # - # - PORT_OK: ェλ - # - PORT_ERROR: ǡβDz餫Υ顼ȯ - # - SEND_FULL: ǡ¦Хåեեä - # - SEND_TIMEOUT: ǡ¦ХåեॢȤ - # - UNKNOWN_ERROR: Υ顼 - # - # @param data ǡ - # @return ꥿󥳡 - # - # @else - # @brief Send data to the destination port - # - # Pure virtual function to send data to the destination port. - # - # This function might the following return codes - # - # - PORT_OK: Normal return - # - PORT_ERROR: Error occurred in data transfer process - # - SEND_FULL: Buffer full although OutPort tried to send data - # - SEND_TIMEOUT: Timeout although OutPort tried to send data - # - UNKNOWN_ERROR: Unknown error - # - # @endif - # - # virtual ReturnCode put(const cdrMemoryStream& data); - def put(self, data): - self._rtcout.RTC_PARANOID("put()") - - try: - ref_ = self.getObject() - if ref_: - inportcdr = ref_._narrow(OpenRTM.InPortCdr) - return self.convertReturnCode(inportcdr.put(data)) - return self.CONNECTION_LOST - except: - self._rtcout.RTC_ERROR(OpenRTM_aist.Logger.print_exception()) - return self.CONNECTION_LOST - - - - ## - # @if jp - # @brief InterfaceProfile - # - # InterfaceProfile롣 - # ǻꤹץѥƥ NameValue ֥Ȥ - # dataport.interface_type ͤĴ١ݡȤꤵƤ - # 󥿡եפȰפΤ߾롣 - # - # @param properties InterfaceProfileץѥƥ - # - # @else - # @brief Publish InterfaceProfile information - # - # Publish interfaceProfile information. - # Check the dataport.interface_type value of the NameValue object - # specified by an argument in property information and get information - # only when the interface type of the specified port is matched. - # - # @param properties Properties to get InterfaceProfile information - # - # @endif - # - # virtual void publishInterfaceProfile(SDOPackage::NVList& properties); - def publishInterfaceProfile(self, properties): - return - - ## - # @if jp - # @brief ǡΤؤϿ - # - # ꤵ줿ץѥƥ˴ŤơǡΤμϿ롣 - # - # @param properties Ͽ - # - # @return Ͽ(Ͽ:trueϿ:false) - # - # @else - # @brief Subscribe to the data sending notification - # - # Subscribe to the data sending notification based on specified - # property information. - # - # @param properties Information for subscription - # - # @return Subscription result (Successful:true, Failed:false) - # - # @endif - # - # virtual bool subscribeInterface(const SDOPackage::NVList& properties); - def subscribeInterface(self, properties): - self._rtcout.RTC_TRACE("subscribeInterface()") - # self._rtcout.RTC_DEBUG_STR(OpenRTM_aist.NVUtil.toString(properties)) - - # getting InPort's ref from IOR string - if self.subscribeFromIor(properties): - return True - - # getting InPort's ref from Object reference - if self.subscribeFromRef(properties): - return True - - return False - - ## - # @if jp - # @brief ǡΤϿ - # - # ǡΤμ꤫Ͽ롣 - # - # @param properties Ͽ - # - # @else - # @brief Unsubscribe the data send notification - # - # Unsubscribe the data send notification. - # - # @param properties Information for unsubscription - # - # @endif - # - # virtual void unsubscribeInterface(const SDOPackage::NVList& properties); - def unsubscribeInterface(self, properties): - self._rtcout.RTC_TRACE("unsubscribeInterface()") - # self._rtcout.RTC_DEBUG_STR(OpenRTM_aist.NVUtil.toString(properties)) - - if self.unsubscribeFromIor(properties): - return - - self.unsubscribeFromRef(properties) - return - - ## - # @if jp - # @brief IORʸ󤫤饪֥ȻȤ - # - # @return true: , false: - # - # @else - # @brief Getting object reference fromn IOR string - # - # @return true: succeeded, false: failed - # - # @endif - # - # bool subscribeFromIor(const SDOPackage::NVList& properties); - def subscribeFromIor(self, properties): - self._rtcout.RTC_TRACE("subscribeFromIor()") - - index = OpenRTM_aist.NVUtil.find_index(properties, - "dataport.corba_cdr.inport_ior") - if index < 0: - self._rtcout.RTC_ERROR("inport_ior not found") - return False - - ior = "" - try: - ior = any.from_any(properties[index].value, keep_structs=True) - except: - self._rtcout.RTC_ERROR(OpenRTM_aist.Logger.print_exception()) - - if not ior: - self._rtcout.RTC_ERROR("inport_ior has no string") - return False - - orb = OpenRTM_aist.Manager.instance().getORB() - obj = orb.string_to_object(ior) - - if CORBA.is_nil(obj): - self._rtcout.RTC_ERROR("invalid IOR string has been passed") - return False - - if not self.setObject(obj): - self._rtcout.RTC_WARN("Setting object to consumer failed.") - return False - - return True - - ## - # @if jp - # @brief Anyľܥ֥ȻȤ - # - # @return true: , false: - # - # @else - # @brief Getting object reference fromn Any directry - # - # @return true: succeeded, false: failed - # - # @endif - # - # bool subscribeFromRef(const SDOPackage::NVList& properties); - def subscribeFromRef(self, properties): - self._rtcout.RTC_TRACE("subscribeFromRef()") - index = OpenRTM_aist.NVUtil.find_index(properties, - "dataport.corba_cdr.inport_ref") - if index < 0: - self._rtcout.RTC_ERROR("inport_ref not found") - return False - - obj = None - try: - obj = any.from_any(properties[index].value, keep_structs=True) - except: - self._rtcout.RTC_ERROR(OpenRTM_aist.Logger.print_exception()) - - if not obj: - self._rtcout.RTC_ERROR("prop[inport_ref] is not objref") - return False - - if CORBA.is_nil(obj): - self._rtcout.RTC_ERROR("prop[inport_ref] is not objref") - return False - - if not self.setObject(obj): - self._rtcout.RTC_ERROR("Setting object to consumer failed.") - return False - - return True - - ## - # @if jp - # @brief ³(IOR) - # - # @return true: , false: - # - # @else - # @brief ubsubscribing (IOR version) - # - # @return true: succeeded, false: failed - # - # @endif - # - # bool unsubscribeFromIor(const SDOPackage::NVList& properties); - def unsubscribeFromIor(self, properties): - self._rtcout.RTC_TRACE("unsubscribeFromIor()") - index = OpenRTM_aist.NVUtil.find_index(properties, - "dataport.corba_cdr.inport_ior") - if index < 0: - self._rtcout.RTC_ERROR("inport_ior not found") - return False - - ior = "" - try: - ior = any.from_any(properties[index].value, keep_structs=True) - except: - self._rtcout.RTC_ERROR(OpenRTM_aist.Logger.print_exception()) - - if not ior: - self._rtcout.RTC_ERROR("prop[inport_ior] is not string") - return False - - orb = OpenRTM_aist.Manager.instance().getORB() - var = orb.string_to_object(ior) - if not self._ptr(True)._is_equivalent(var): - self._rtcout.RTC_ERROR("connector property inconsistency") - return False - - self.releaseObject() - return True - - ## - # @if jp - # @brief ³(Object reference) - # - # @return true: , false: - # - # @else - # @brief ubsubscribing (Object reference version) - # - # @return true: succeeded, false: failed - # - # @endif - # - # bool unsubscribeFromRef(const SDOPackage::NVList& properties); - def unsubscribeFromRef(self, properties): - self._rtcout.RTC_TRACE("unsubscribeFromRef()") - index = OpenRTM_aist.NVUtil.find_index(properties, - "dataport.corba_cdr.inport_ref") - - if index < 0: - return False - - obj = None - try: - obj = any.from_any(properties[index].value, keep_structs=True) - except: - self._rtcout.RTC_ERROR(OpenRTM_aist.Logger.print_exception()) - - if not obj: - return False - - obj_ptr = self._ptr(True) - - if obj_ptr is None or not obj_ptr._is_equivalent(obj): - return False - - self.releaseObject() - return True - - ## - # @if jp - # @brief ꥿󥳡Ѵ - # @else - # @brief Return codes conversion - # @endif - # - # ReturnCode convertReturnCode(OpenRTM::PortStatus ret) - def convertReturnCode(self, ret): - if ret == OpenRTM.PORT_OK: - return self.PORT_OK - - elif ret == OpenRTM.PORT_ERROR: - return self.PORT_ERROR - - elif ret == OpenRTM.BUFFER_FULL: - return self.SEND_FULL - - elif ret == OpenRTM.BUFFER_TIMEOUT: - return self.SEND_TIMEOUT - - elif ret == OpenRTM.UNKNOWN_ERROR: - return self.UNKNOWN_ERROR - - else: - return self.UNKNOWN_ERROR + + +class InPortCorbaCdrConsumer( + OpenRTM_aist.InPortConsumer, OpenRTM_aist.CorbaConsumer): + """ + """ + + ## + # @if jp + # @brief コンストラクタ + # + # コンストラクタ + # + # @param buffer 当該コンシューマに割り当てるバッファオブジェクト + # + # @else + # @brief Constructor + # + # Constructor + # + # @param buffer The buffer object that is attached to this Consumer + # + # @endif + # + def __init__(self): + OpenRTM_aist.CorbaConsumer.__init__(self, OpenRTM.InPortCdr) + self._rtcout = OpenRTM_aist.Manager.instance().getLogbuf("InPortCorbaCdrConsumer") + self._properties = None + return + + ## + # @if jp + # @brief デストラクタ + # + # デストラクタ + # + # @else + # @brief Destructor + # + # Destructor + # + # @endif + # + def __del__(self, CorbaConsumer=OpenRTM_aist.CorbaConsumer): + self._rtcout.RTC_PARANOID("~InPortCorbaCdrConsumer()") + CorbaConsumer.__del__(self) + return + + ## + # @if jp + # @brief 設定初期化 + # + # InPortConsumerの各種設定を行う + # + # @else + # @brief Initializing configuration + # + # This operation would be called to configure this consumer + # in initialization. + # + # @endif + # + # virtual void init(coil::Properties& prop); + def init(self, prop): + self._rtcout.RTC_TRACE("init()") + self._properties = prop + return + + ## + # @if jp + # @brief 接続先へのデータ送信 + # + # 接続先のポートへデータを送信するための純粋仮想関数。 + # + # この関数は、以下のリターンコードを返す。 + # + # - PORT_OK: 正常終了。 + # - PORT_ERROR: データ送信の過程で何らかのエラーが発生した。 + # - SEND_FULL: データを送信したが、相手側バッファがフルだった。 + # - SEND_TIMEOUT: データを送信したが、相手側バッファがタイムアウトした。 + # - UNKNOWN_ERROR: 原因不明のエラー + # + # @param data 送信するデータ + # @return リターンコード + # + # @else + # @brief Send data to the destination port + # + # Pure virtual function to send data to the destination port. + # + # This function might the following return codes + # + # - PORT_OK: Normal return + # - PORT_ERROR: Error occurred in data transfer process + # - SEND_FULL: Buffer full although OutPort tried to send data + # - SEND_TIMEOUT: Timeout although OutPort tried to send data + # - UNKNOWN_ERROR: Unknown error + # + # @endif + # + # virtual ReturnCode put(const cdrMemoryStream& data); + def put(self, data): + self._rtcout.RTC_PARANOID("put()") + + try: + inportcdr = self._ptr() + if inportcdr: + return self.convertReturnCode(inportcdr.put(data)) + return self.CONNECTION_LOST + except BaseException: + self._rtcout.RTC_ERROR(OpenRTM_aist.Logger.print_exception()) + return self.CONNECTION_LOST + + ## + # @if jp + # @brief InterfaceProfile情報を公開する + # + # InterfaceProfile情報を公開する。 + # 引数で指定するプロパティ情報内の NameValue オブジェクトの + # dataport.interface_type 値を調べ、当該ポートに設定されている + # インターフェースタイプと一致する場合のみ情報を取得する。 + # + # @param properties InterfaceProfile情報を受け取るプロパティ + # + # @else + # @brief Publish InterfaceProfile information + # + # Publish interfaceProfile information. + # Check the dataport.interface_type value of the NameValue object + # specified by an argument in property information and get information + # only when the interface type of the specified port is matched. + # + # @param properties Properties to get InterfaceProfile information + # + # @endif + # + # virtual void publishInterfaceProfile(SDOPackage::NVList& properties); + + def publishInterfaceProfile(self, properties): + return + + ## + # @if jp + # @brief データ送信通知への登録 + # + # 指定されたプロパティに基づいて、データ送出通知の受け取りに登録する。 + # + # @param properties 登録情報 + # + # @return 登録処理結果(登録成功:true、登録失敗:false) + # + # @else + # @brief Subscribe to the data sending notification + # + # Subscribe to the data sending notification based on specified + # property information. + # + # @param properties Information for subscription + # + # @return Subscription result (Successful:true, Failed:false) + # + # @endif + # + # virtual bool subscribeInterface(const SDOPackage::NVList& properties); + def subscribeInterface(self, properties): + self._rtcout.RTC_TRACE("subscribeInterface()") + # self._rtcout.RTC_DEBUG_STR(OpenRTM_aist.NVUtil.toString(properties)) + + # getting InPort's ref from IOR string + if self.subscribeFromIor(properties): + return True + + # getting InPort's ref from Object reference + if self.subscribeFromRef(properties): + return True + + return False + + ## + # @if jp + # @brief データ送信通知からの登録解除 + # + # データ送出通知の受け取りから登録を解除する。 + # + # @param properties 登録解除情報 + # + # @else + # @brief Unsubscribe the data send notification + # + # Unsubscribe the data send notification. + # + # @param properties Information for unsubscription + # + # @endif + # + # virtual void unsubscribeInterface(const SDOPackage::NVList& properties); + def unsubscribeInterface(self, properties): + self._rtcout.RTC_TRACE("unsubscribeInterface()") + # self._rtcout.RTC_DEBUG_STR(OpenRTM_aist.NVUtil.toString(properties)) + + if self.unsubscribeFromIor(properties): + return + + self.unsubscribeFromRef(properties) + return + + ## + # @if jp + # @brief IOR文字列からオブジェクト参照を取得する + # + # @return true: 正常取得, false: 取得失敗 + # + # @else + # @brief Getting object reference fromn IOR string + # + # @return true: succeeded, false: failed + # + # @endif + # + # bool subscribeFromIor(const SDOPackage::NVList& properties); + def subscribeFromIor(self, properties): + self._rtcout.RTC_TRACE("subscribeFromIor()") + + index = OpenRTM_aist.NVUtil.find_index(properties, + "dataport.corba_cdr.inport_ior") + if index < 0: + self._rtcout.RTC_ERROR("inport_ior not found") + return False + + ior = "" + try: + ior = any.from_any(properties[index].value, keep_structs=True) + except BaseException: + self._rtcout.RTC_ERROR(OpenRTM_aist.Logger.print_exception()) + + if not ior: + self._rtcout.RTC_ERROR("inport_ior has no string") + return False + + orb = OpenRTM_aist.Manager.instance().getORB() + obj = orb.string_to_object(ior) + + if CORBA.is_nil(obj): + self._rtcout.RTC_ERROR("invalid IOR string has been passed") + return False + + if not self.setObject(obj): + self._rtcout.RTC_WARN("Setting object to consumer failed.") + return False + + return True + + ## + # @if jp + # @brief Anyから直接オブジェクト参照を取得する + # + # @return true: 正常取得, false: 取得失敗 + # + # @else + # @brief Getting object reference fromn Any directry + # + # @return true: succeeded, false: failed + # + # @endif + # + # bool subscribeFromRef(const SDOPackage::NVList& properties); + def subscribeFromRef(self, properties): + self._rtcout.RTC_TRACE("subscribeFromRef()") + index = OpenRTM_aist.NVUtil.find_index(properties, + "dataport.corba_cdr.inport_ref") + if index < 0: + self._rtcout.RTC_ERROR("inport_ref not found") + return False + + obj = None + try: + obj = any.from_any(properties[index].value, keep_structs=True) + except BaseException: + self._rtcout.RTC_ERROR(OpenRTM_aist.Logger.print_exception()) + + if not obj: + self._rtcout.RTC_ERROR("prop[inport_ref] is not objref") + return False + + if CORBA.is_nil(obj): + self._rtcout.RTC_ERROR("prop[inport_ref] is not objref") + return False + + if not self.setObject(obj): + self._rtcout.RTC_ERROR("Setting object to consumer failed.") + return False + + return True + + ## + # @if jp + # @brief 接続解除(IOR版) + # + # @return true: 正常取得, false: 取得失敗 + # + # @else + # @brief ubsubscribing (IOR version) + # + # @return true: succeeded, false: failed + # + # @endif + # + # bool unsubscribeFromIor(const SDOPackage::NVList& properties); + def unsubscribeFromIor(self, properties): + self._rtcout.RTC_TRACE("unsubscribeFromIor()") + index = OpenRTM_aist.NVUtil.find_index(properties, + "dataport.corba_cdr.inport_ior") + if index < 0: + self._rtcout.RTC_ERROR("inport_ior not found") + return False + + ior = "" + try: + ior = any.from_any(properties[index].value, keep_structs=True) + except BaseException: + self._rtcout.RTC_ERROR(OpenRTM_aist.Logger.print_exception()) + + if not ior: + self._rtcout.RTC_ERROR("prop[inport_ior] is not string") + return False + + orb = OpenRTM_aist.Manager.instance().getORB() + var = orb.string_to_object(ior) + ptr = self._ptr(True) + if ptr: + if not ptr._is_equivalent(var): + self._rtcout.RTC_ERROR("connector property inconsistency") + return False + + self.releaseObject() + return True + + ## + # @if jp + # @brief 接続解除(Object reference版) + # + # @return true: 正常取得, false: 取得失敗 + # + # @else + # @brief ubsubscribing (Object reference version) + # + # @return true: succeeded, false: failed + # + # @endif + # + # bool unsubscribeFromRef(const SDOPackage::NVList& properties); + def unsubscribeFromRef(self, properties): + self._rtcout.RTC_TRACE("unsubscribeFromRef()") + index = OpenRTM_aist.NVUtil.find_index(properties, + "dataport.corba_cdr.inport_ref") + + if index < 0: + return False + + obj = None + try: + obj = any.from_any(properties[index].value, keep_structs=True) + except BaseException: + self._rtcout.RTC_ERROR(OpenRTM_aist.Logger.print_exception()) + + if not obj: + return False + + obj_ptr = self._ptr(True) + + if obj_ptr is None or not obj_ptr._is_equivalent(obj): + return False + + self.releaseObject() + return True + + ## + # @if jp + # @brief リターンコード変換 + # @else + # @brief Return codes conversion + # @endif + # + # ReturnCode convertReturnCode(OpenRTM::PortStatus ret) + def convertReturnCode(self, ret): + if ret == OpenRTM.PORT_OK: + return self.PORT_OK + + elif ret == OpenRTM.PORT_ERROR: + return self.PORT_ERROR + + elif ret == OpenRTM.BUFFER_FULL: + return self.SEND_FULL + + elif ret == OpenRTM.BUFFER_TIMEOUT: + return self.SEND_TIMEOUT + + elif ret == OpenRTM.UNKNOWN_ERROR: + return self.UNKNOWN_ERROR + + else: + return self.UNKNOWN_ERROR def InPortCorbaCdrConsumerInit(): - factory = OpenRTM_aist.InPortConsumerFactory.instance() - factory.addFactory("corba_cdr", - OpenRTM_aist.InPortCorbaCdrConsumer, - OpenRTM_aist.Delete) + factory = OpenRTM_aist.InPortConsumerFactory.instance() + factory.addFactory("corba_cdr", + OpenRTM_aist.InPortCorbaCdrConsumer) diff --git a/OpenRTM_aist/InPortCorbaCdrProvider.py b/OpenRTM_aist/InPortCorbaCdrProvider.py index 8de7328e..4f84b92d 100644 --- a/OpenRTM_aist/InPortCorbaCdrProvider.py +++ b/OpenRTM_aist/InPortCorbaCdrProvider.py @@ -1,5 +1,5 @@ #!/usr/bin/env python -# -*- coding: euc-jp -*- +# -*- coding: utf-8 -*- ## # @file InPortCorbaCdrProvider.py @@ -16,19 +16,18 @@ # All rights reserved. - - import OpenRTM_aist -import OpenRTM__POA,OpenRTM +import OpenRTM__POA +import OpenRTM ## # @if jp # @class InPortCorbaCdrProvider -# @brief InPortCorbaCdrProvider 饹 +# @brief InPortCorbaCdrProvider クラス # -# ̿ʤ CORBA ѤϥݡȥץХμ饹 +# 通信手段に CORBA を利用した入力ポートプロバイダーの実装クラス。 # -# @param DataType ץХ˳ƤХåեݻǡ +# @param DataType 当該プロバイダに割り当てたバッファが保持するデータ型 # # @since 0.4.0 # @@ -36,253 +35,257 @@ # @class InPortCorbaCdrProvider # @brief InPortCorbaCdrProvider class # -# This is an implementation class of the input port Provider +# This is an implementation class of the input port Provider # that uses CORBA for means of communication. # -# @param DataType Data type held by the buffer that attached +# @param DataType Data type held by the buffer that attached # to this provider. # # @since 0.4.0 # # @endif # + + class InPortCorbaCdrProvider(OpenRTM_aist.InPortProvider, OpenRTM__POA.InPortCdr): - - """ - """ - - ## - # @if jp - # @brief 󥹥ȥ饯 - # - # 󥹥ȥ饯 - # ݡȥץѥƥ˰ʲιܤꤹ롣 - # - 󥿡ե : CORBA_Any - # - ǡե : Push, Pull - # - ֥ץ󥿥 : Any - # - # @param buffer ץХ˳ƤХåե֥ - # - # @else - # @brief Constructor - # - # Constructor - # Set the following items to port properties - # - Interface type : CORBA_Any - # - Data flow type : Push, Pull - # - Subscription type : Any - # - # @param buffer Buffer object that is attached to this provider - # - # @endif - # - def __init__(self): - OpenRTM_aist.InPortProvider.__init__(self) - - # PortProfile setting - self.setInterfaceType("corba_cdr") - - # ConnectorProfile setting - self._objref = self._this() - - self._buffer = None - - self._profile = None - self._listeners = None - - # set InPort's reference - orb = OpenRTM_aist.Manager.instance().getORB() - - self._properties.append(OpenRTM_aist.NVUtil.newNV("dataport.corba_cdr.inport_ior", - orb.object_to_string(self._objref))) - self._properties.append(OpenRTM_aist.NVUtil.newNV("dataport.corba_cdr.inport_ref", - self._objref)) - - return - - ## - # @if jp - # @brief ǥȥ饯 - # - # ǥȥ饯 - # - # @else - # @brief Destructor - # - # Destructor - # - # @endif - # - def __del__(self): - return - - ## - # @if jp - # @brief λ - # - # @else - # @brief - # - # - # - # @endif - # - def exit(self): - oid = OpenRTM_aist.Manager.instance().getPOA().servant_to_id(self) - OpenRTM_aist.Manager.instance().getPOA().deactivate_object(oid) - - ## virtual void init(coil::Properties& prop); - def init(self, prop): - pass - - ## virtual void setBuffer(BufferBase* buffer); - def setBuffer(self, buffer): - self._buffer = buffer - return - - # void setListener(ConnectorInfo& info, - # ConnectorListeners* listeners); - def setListener(self, info, listeners): - self._profile = info - self._listeners = listeners - return - - ## - # @if jp - # @brief [CORBA interface] Хåե˥ǡ񤭹 - # - # ꤵ줿Хåե˥ǡ񤭹ࡣ - # - # @param data оݥǡ - # - # @else - # @brief [CORBA interface] Write data into the buffer - # - # Write data into the specified buffer. - # - # @param data The target data for writing - # - # @endif - # - # virtual ::OpenRTM::PortStatus put(const ::OpenRTM::CdrData& data) - # throw (CORBA::SystemException); - def put(self, data): - try: - self._rtcout.RTC_PARANOID("InPortCorbaCdrProvider.put()") - - if not self._connector: - self.onReceiverError(data) - return OpenRTM.PORT_ERROR - - self._rtcout.RTC_PARANOID("received data size: %d", len(data)) - - self.onReceived(data) - - if not self._connector: - return OpenRTM.PORT_ERROR - - ret = self._connector.write(data) - - return self.convertReturn(ret, data) - - except: - self._rtcout.RTC_TRACE(OpenRTM_aist.Logger.print_exception()) - return OpenRTM.UNKNOWN_ERROR - - - - def convertReturn(self, status, data): - if status == OpenRTM_aist.BufferStatus.BUFFER_OK: - self.onBufferWrite(data) - return OpenRTM.PORT_OK - - elif status == OpenRTM_aist.BufferStatus.BUFFER_ERROR: - self.onReceiverError(data) - return OpenRTM.PORT_ERROR - - elif status == OpenRTM_aist.BufferStatus.BUFFER_FULL: - self.onBufferFull(data) - self.onReceiverFull(data) - return OpenRTM.BUFFER_FULL - - elif status == OpenRTM_aist.BufferStatus.BUFFER_EMPTY: - return OpenRTM.BUFFER_EMPTY - - elif status == OpenRTM_aist.BufferStatus.PRECONDITION_NOT_MET: - self.onReceiverError(data) - return OpenRTM.PORT_ERROR - - elif status == OpenRTM_aist.BufferStatus.TIMEOUT: - self.onBufferWriteTimeout(data) - self.onReceiverTimeout(data) - return OpenRTM.BUFFER_TIMEOUT - - else: - self.onReceiverError(data) - return OpenRTM.UNKNOWN_ERROR - - - ## - # @brief Connector data listener functions - # - # inline void onBufferWrite(const cdrMemoryStream& data) - def onBufferWrite(self, data): - if self._listeners is not None and self._profile is not None: - self._listeners.connectorData_[OpenRTM_aist.ConnectorDataListenerType.ON_BUFFER_WRITE].notify(self._profile, data) - return - - - ## inline void onBufferFull(const cdrMemoryStream& data) - def onBufferFull(self, data): - if self._listeners is not None and self._profile is not None: - self._listeners.connectorData_[OpenRTM_aist.ConnectorDataListenerType.ON_BUFFER_FULL].notify(self._profile, data) - return - - - ## inline void onBufferWriteTimeout(const cdrMemoryStream& data) - def onBufferWriteTimeout(self, data): - if self._listeners is not None and self._profile is not None: - self._listeners.connectorData_[OpenRTM_aist.ConnectorDataListenerType.ON_BUFFER_WRITE_TIMEOUT].notify(self._profile, data) - return - - ## inline void onBufferWriteOverwrite(const cdrMemoryStream& data) - def onBufferWriteOverwrite(self, data): - if self._listeners is not None and self._profile is not None: - self._listeners.connectorData_[OpenRTM_aist.ConnectorDataListenerType.ON_BUFFER_OVERWRITE].notify(self._profile, data) - return - - - ## inline void onReceived(const cdrMemoryStream& data) - def onReceived(self, data): - if self._listeners is not None and self._profile is not None: - self._listeners.connectorData_[OpenRTM_aist.ConnectorDataListenerType.ON_RECEIVED].notify(self._profile, data) - return - - ## inline void onReceiverFull(const cdrMemoryStream& data) - def onReceiverFull(self, data): - if self._listeners is not None and self._profile is not None: - self._listeners.connectorData_[OpenRTM_aist.ConnectorDataListenerType.ON_RECEIVER_FULL].notify(self._profile, data) - return + """ + """ + + ## + # @if jp + # @brief コンストラクタ + # + # コンストラクタ + # ポートプロパティに以下の項目を設定する。 + # - インターフェースタイプ : CORBA_Any + # - データフロータイプ : Push, Pull + # - サブスクリプションタイプ : Any + # + # @param buffer 当該プロバイダに割り当てるバッファオブジェクト + # + # @else + # @brief Constructor + # + # Constructor + # Set the following items to port properties + # - Interface type : CORBA_Any + # - Data flow type : Push, Pull + # - Subscription type : Any + # + # @param buffer Buffer object that is attached to this provider + # + # @endif + # + def __init__(self): + OpenRTM_aist.InPortProvider.__init__(self) + + # PortProfile setting + self.setInterfaceType("corba_cdr") + + # ConnectorProfile setting + self._objref = self._this() + + self._buffer = None + + self._profile = None + self._listeners = None + + # set InPort's reference + orb = OpenRTM_aist.Manager.instance().getORB() + + self._properties.append(OpenRTM_aist.NVUtil.newNV("dataport.corba_cdr.inport_ior", + orb.object_to_string(self._objref))) + self._properties.append(OpenRTM_aist.NVUtil.newNV("dataport.corba_cdr.inport_ref", + self._objref)) + + return + + ## + # @if jp + # @brief デストラクタ + # + # デストラクタ + # + # @else + # @brief Destructor + # + # Destructor + # + # @endif + # + def __del__(self): + return + + ## + # @if jp + # @brief 終了処理 + # + # @else + # @brief + # + # + # + # @endif + # + def exit(self): + oid = OpenRTM_aist.Manager.instance().getPOA().servant_to_id(self) + OpenRTM_aist.Manager.instance().getPOA().deactivate_object(oid) + + # virtual void init(coil::Properties& prop); + def init(self, prop): + pass + + # virtual void setBuffer(BufferBase* buffer); + def setBuffer(self, buffer): + self._buffer = buffer + return + + # void setListener(ConnectorInfo& info, + # ConnectorListeners* listeners); + def setListener(self, info, listeners): + self._profile = info + self._listeners = listeners + return + + ## + # @if jp + # @brief [CORBA interface] バッファにデータを書き込む + # + # 設定されたバッファにデータを書き込む。 + # + # @param data 書込対象データ + # + # @else + # @brief [CORBA interface] Write data into the buffer + # + # Write data into the specified buffer. + # + # @param data The target data for writing + # + # @endif + # + # virtual ::OpenRTM::PortStatus put(const ::OpenRTM::CdrData& data) + # throw (CORBA::SystemException); + def put(self, data): + try: + self._rtcout.RTC_PARANOID("InPortCorbaCdrProvider.put()") + + if not self._connector: + self.onReceiverError(data) + return OpenRTM.PORT_ERROR + + self._rtcout.RTC_PARANOID("received data size: %d", len(data)) + + data = self.onReceived(data) + + ret = self._connector.write(data) + + return self.convertReturn(ret, data) + + except BaseException: + self._rtcout.RTC_TRACE(OpenRTM_aist.Logger.print_exception()) + return OpenRTM.UNKNOWN_ERROR + + def convertReturn(self, status, data): + if status == OpenRTM_aist.BufferStatus.BUFFER_OK: + self.onBufferWrite(data) + return OpenRTM.PORT_OK + + elif status == OpenRTM_aist.BufferStatus.BUFFER_ERROR: + self.onReceiverError(data) + return OpenRTM.PORT_ERROR + + elif status == OpenRTM_aist.BufferStatus.BUFFER_FULL: + data = self.onBufferFull(data) + self.onReceiverFull(data) + return OpenRTM.BUFFER_FULL + + elif status == OpenRTM_aist.BufferStatus.BUFFER_EMPTY: + return OpenRTM.BUFFER_EMPTY + + elif status == OpenRTM_aist.BufferStatus.PRECONDITION_NOT_MET: + self.onReceiverError(data) + return OpenRTM.PORT_ERROR + + elif status == OpenRTM_aist.BufferStatus.TIMEOUT: + data = self.onBufferWriteTimeout(data) + self.onReceiverTimeout(data) + return OpenRTM.BUFFER_TIMEOUT + + else: + self.onReceiverError(data) + return OpenRTM.UNKNOWN_ERROR + + ## + # @brief Connector data listener functions + # + # inline void onBufferWrite(const cdrMemoryStream& data) + + def onBufferWrite(self, data): + if self._listeners is not None and self._profile is not None: + _, data = self._listeners.notifyData( + OpenRTM_aist.ConnectorDataListenerType.ON_BUFFER_WRITE, self._profile, data) + return data + + # inline void onBufferFull(const cdrMemoryStream& data) + + def onBufferFull(self, data): + if self._listeners is not None and self._profile is not None: + _, data = self._listeners.notifyData( + OpenRTM_aist.ConnectorDataListenerType.ON_BUFFER_FULL, self._profile, data) + return data + + # inline void onBufferWriteTimeout(const cdrMemoryStream& data) + + def onBufferWriteTimeout(self, data): + if self._listeners is not None and self._profile is not None: + _, data = self._listeners.notifyData( + OpenRTM_aist.ConnectorDataListenerType.ON_BUFFER_WRITE_TIMEOUT, self._profile, data) + return data + + # inline void onBufferWriteOverwrite(const cdrMemoryStream& data) + def onBufferWriteOverwrite(self, data): + if self._listeners is not None and self._profile is not None: + _, data = self._listeners.notifyData( + OpenRTM_aist.ConnectorDataListenerType.ON_BUFFER_OVERWRITE, self._profile, data) + return data + + # inline void onReceived(const cdrMemoryStream& data) + + def onReceived(self, data): + if self._listeners is not None and self._profile is not None: + _, data = self._listeners.notifyData( + OpenRTM_aist.ConnectorDataListenerType.ON_RECEIVED, self._profile, data) + return data + + # inline void onReceiverFull(const cdrMemoryStream& data) + + def onReceiverFull(self, data): + if self._listeners is not None and self._profile is not None: + _, data = self._listeners.notifyData( + OpenRTM_aist.ConnectorDataListenerType.ON_RECEIVER_FULL, self._profile, data) + return data + # inline void onReceiverTimeout(const cdrMemoryStream& data) - ## inline void onReceiverTimeout(const cdrMemoryStream& data) - def onReceiverTimeout(self, data): - if self._listeners is not None and self._profile is not None: - self._listeners.connectorData_[OpenRTM_aist.ConnectorDataListenerType.ON_RECEIVER_TIMEOUT].notify(self._profile, data) - return + def onReceiverTimeout(self, data): + if self._listeners is not None and self._profile is not None: + _, data = self._listeners.notifyData( + OpenRTM_aist.ConnectorDataListenerType.ON_RECEIVER_TIMEOUT, self._profile, data) + return data + # inline void onReceiverError(const cdrMemoryStream& data) - ## inline void onReceiverError(const cdrMemoryStream& data) - def onReceiverError(self, data): - if self._listeners is not None and self._profile is not None: - self._listeners.connectorData_[OpenRTM_aist.ConnectorDataListenerType.ON_RECEIVER_ERROR].notify(self._profile, data) - return + def onReceiverError(self, data): + if self._listeners is not None and self._profile is not None: + self._listeners.notifyData( + OpenRTM_aist.ConnectorDataListenerType.ON_RECEIVER_ERROR, self._profile, data) + return data def InPortCorbaCdrProviderInit(): - factory = OpenRTM_aist.InPortProviderFactory.instance() - factory.addFactory("corba_cdr", - OpenRTM_aist.InPortCorbaCdrProvider, - OpenRTM_aist.Delete) + factory = OpenRTM_aist.InPortProviderFactory.instance() + factory.addFactory("corba_cdr", + OpenRTM_aist.InPortCorbaCdrProvider) diff --git a/OpenRTM_aist/InPortDSConsumer.py b/OpenRTM_aist/InPortDSConsumer.py index 49f927e1..cea3dd4d 100644 --- a/OpenRTM_aist/InPortDSConsumer.py +++ b/OpenRTM_aist/InPortDSConsumer.py @@ -1,5 +1,5 @@ #!/usr/bin/env python -# -*- coding: euc-jp -*- +# -*- coding: utf-8 -*- ## # @file InPortDSConsumer.py @@ -15,7 +15,6 @@ # All rights reserved. - from omniORB import any from omniORB import CORBA import OpenRTM_aist @@ -26,11 +25,11 @@ # # @class InPortDSConsumer # -# @brief InPortDSConsumer 饹 +# @brief InPortDSConsumer クラス # -# ̿ʤ CORBA Ѥϥݡȥ󥷥塼ޤμ饹 +# 通信手段に CORBA を利用した入力ポートコンシューマの実装クラス。 # -# @param DataType ܥݡȤˤưǡ +# @param DataType 本ポートにて扱うデータ型 # # @since 1.2.0 # @@ -39,7 +38,7 @@ # # @brief InPortDSConsumer class # -# This is an implementation class of the input port Consumer +# This is an implementation class of the input port Consumer # that uses CORBA for means of communication. # # @param DataType Data type for this port @@ -48,409 +47,409 @@ # # @endif # -class InPortDSConsumer(OpenRTM_aist.InPortConsumer,OpenRTM_aist.CorbaConsumer): - """ - """ - - ## - # @if jp - # @brief 󥹥ȥ饯 - # - # 󥹥ȥ饯 - # - # @param buffer 󥷥塼ޤ˳ƤХåե֥ - # - # @else - # @brief Constructor - # - # Constructor - # - # @param buffer The buffer object that is attached to this Consumer - # - # @endif - # - def __init__(self): - OpenRTM_aist.CorbaConsumer.__init__(self) - self._rtcout = OpenRTM_aist.Manager.instance().getLogbuf("InPortDSConsumer") - self._properties = None - return - - ## - # @if jp - # @brief ǥȥ饯 - # - # ǥȥ饯 - # - # @else - # @brief Destructor - # - # Destructor - # - # @endif - # - def __del__(self, CorbaConsumer=OpenRTM_aist.CorbaConsumer): - self._rtcout.RTC_PARANOID("~InPortDSConsumer()") - CorbaConsumer.__del__(self) - return - - ## - # @if jp - # @brief - # - # InPortConsumerγƼԤ - # - # @else - # @brief Initializing configuration - # - # This operation would be called to configure this consumer - # in initialization. - # - # @endif - # - # virtual void init(coil::Properties& prop); - def init(self, prop): - self._rtcout.RTC_TRACE("init()") - self._properties = prop - return - - ## - # @if jp - # @brief ³ؤΥǡ - # - # ³ΥݡȤإǡ뤿ν貾۴ؿ - # - # δؿϡʲΥ꥿󥳡ɤ֤ - # - # - PORT_OK: ェλ - # - PORT_ERROR: ǡβDz餫Υ顼ȯ - # - SEND_FULL: ǡ¦Хåեեä - # - SEND_TIMEOUT: ǡ¦ХåեॢȤ - # - UNKNOWN_ERROR: Υ顼 - # - # @param data ǡ - # @return ꥿󥳡 - # - # @else - # @brief Send data to the destination port - # - # Pure virtual function to send data to the destination port. - # - # This function might the following return codes - # - # - PORT_OK: Normal return - # - PORT_ERROR: Error occurred in data transfer process - # - SEND_FULL: Buffer full although OutPort tried to send data - # - SEND_TIMEOUT: Timeout although OutPort tried to send data - # - UNKNOWN_ERROR: Unknown error - # - # @endif - # - # virtual ReturnCode put(const cdrMemoryStream& data); - def put(self, data): - self._rtcout.RTC_PARANOID("put()") - - try: - ref_ = self.getObject() - if ref_: - ds = ref_._narrow(RTC.DataPushService) - return self.convertReturnCode(ds.push(data)) - return self.CONNECTION_LOST - except: - self._rtcout.RTC_ERROR(OpenRTM_aist.Logger.print_exception()) - return self.CONNECTION_LOST - - - - ## - # @if jp - # @brief InterfaceProfile - # - # InterfaceProfile롣 - # ǻꤹץѥƥ NameValue ֥Ȥ - # dataport.interface_type ͤĴ١ݡȤꤵƤ - # 󥿡եפȰפΤ߾롣 - # - # @param properties InterfaceProfileץѥƥ - # - # @else - # @brief Publish InterfaceProfile information - # - # Publish interfaceProfile information. - # Check the dataport.interface_type value of the NameValue object - # specified by an argument in property information and get information - # only when the interface type of the specified port is matched. - # - # @param properties Properties to get InterfaceProfile information - # - # @endif - # - # virtual void publishInterfaceProfile(SDOPackage::NVList& properties); - def publishInterfaceProfile(self, properties): - return - - ## - # @if jp - # @brief ǡΤؤϿ - # - # ꤵ줿ץѥƥ˴ŤơǡΤμϿ롣 - # - # @param properties Ͽ - # - # @return Ͽ(Ͽ:trueϿ:false) - # - # @else - # @brief Subscribe to the data sending notification - # - # Subscribe to the data sending notification based on specified - # property information. - # - # @param properties Information for subscription - # - # @return Subscription result (Successful:true, Failed:false) - # - # @endif - # - # virtual bool subscribeInterface(const SDOPackage::NVList& properties); - def subscribeInterface(self, properties): - self._rtcout.RTC_TRACE("subscribeInterface()") - # self._rtcout.RTC_DEBUG_STR(OpenRTM_aist.NVUtil.toString(properties)) - - # getting InPort's ref from IOR string - if self.subscribeFromIor(properties): - return True - - # getting InPort's ref from Object reference - if self.subscribeFromRef(properties): - return True - - return False - - ## - # @if jp - # @brief ǡΤϿ - # - # ǡΤμ꤫Ͽ롣 - # - # @param properties Ͽ - # - # @else - # @brief Unsubscribe the data send notification - # - # Unsubscribe the data send notification. - # - # @param properties Information for unsubscription - # - # @endif - # - # virtual void unsubscribeInterface(const SDOPackage::NVList& properties); - def unsubscribeInterface(self, properties): - self._rtcout.RTC_TRACE("unsubscribeInterface()") - # self._rtcout.RTC_DEBUG_STR(OpenRTM_aist.NVUtil.toString(properties)) - - if self.unsubscribeFromIor(properties): - return - - self.unsubscribeFromRef(properties) - return - - ## - # @if jp - # @brief IORʸ󤫤饪֥ȻȤ - # - # @return true: , false: - # - # @else - # @brief Getting object reference fromn IOR string - # - # @return true: succeeded, false: failed - # - # @endif - # - # bool subscribeFromIor(const SDOPackage::NVList& properties); - def subscribeFromIor(self, properties): - self._rtcout.RTC_TRACE("subscribeFromIor()") - - index = OpenRTM_aist.NVUtil.find_index(properties, - "dataport.data_service.inport_ior") - if index < 0: - self._rtcout.RTC_ERROR("inport_ior not found") - return False - - ior = "" - try: - ior = any.from_any(properties[index].value, keep_structs=True) - except: - self._rtcout.RTC_ERROR(OpenRTM_aist.Logger.print_exception()) - - if not ior: - self._rtcout.RTC_ERROR("inport_ior has no string") - return False - - orb = OpenRTM_aist.Manager.instance().getORB() - obj = orb.string_to_object(ior) - - if CORBA.is_nil(obj): - self._rtcout.RTC_ERROR("invalid IOR string has been passed") - return False - - if not self.setObject(obj): - self._rtcout.RTC_WARN("Setting object to consumer failed.") - return False - - return True - - ## - # @if jp - # @brief Anyľܥ֥ȻȤ - # - # @return true: , false: - # - # @else - # @brief Getting object reference fromn Any directry - # - # @return true: succeeded, false: failed - # - # @endif - # - # bool subscribeFromRef(const SDOPackage::NVList& properties); - def subscribeFromRef(self, properties): - self._rtcout.RTC_TRACE("subscribeFromRef()") - index = OpenRTM_aist.NVUtil.find_index(properties, - "dataport.data_service.inport_ref") - if index < 0: - self._rtcout.RTC_ERROR("inport_ref not found") - return False - - obj = None - try: - obj = any.from_any(properties[index].value, keep_structs=True) - except: - self._rtcout.RTC_ERROR(OpenRTM_aist.Logger.print_exception()) - - if not obj: - self._rtcout.RTC_ERROR("prop[inport_ref] is not objref") - return False - - if CORBA.is_nil(obj): - self._rtcout.RTC_ERROR("prop[inport_ref] is not objref") - return False - - if not self.setObject(obj): - self._rtcout.RTC_ERROR("Setting object to consumer failed.") - return False - - return True - - ## - # @if jp - # @brief ³(IOR) - # - # @return true: , false: - # - # @else - # @brief ubsubscribing (IOR version) - # - # @return true: succeeded, false: failed - # - # @endif - # - # bool unsubscribeFromIor(const SDOPackage::NVList& properties); - def unsubscribeFromIor(self, properties): - self._rtcout.RTC_TRACE("unsubscribeFromIor()") - index = OpenRTM_aist.NVUtil.find_index(properties, - "dataport.data_service.inport_ior") - if index < 0: - self._rtcout.RTC_ERROR("inport_ior not found") - return False - - ior = "" - try: - ior = any.from_any(properties[index].value, keep_structs=True) - except: - self._rtcout.RTC_ERROR(OpenRTM_aist.Logger.print_exception()) - - if not ior: - self._rtcout.RTC_ERROR("prop[inport_ior] is not string") - return False - - orb = OpenRTM_aist.Manager.instance().getORB() - var = orb.string_to_object(ior) - if not self._ptr(True)._is_equivalent(var): - self._rtcout.RTC_ERROR("connector property inconsistency") - return False - - self.releaseObject() - return True - - ## - # @if jp - # @brief ³(Object reference) - # - # @return true: , false: - # - # @else - # @brief ubsubscribing (Object reference version) - # - # @return true: succeeded, false: failed - # - # @endif - # - # bool unsubscribeFromRef(const SDOPackage::NVList& properties); - def unsubscribeFromRef(self, properties): - self._rtcout.RTC_TRACE("unsubscribeFromRef()") - index = OpenRTM_aist.NVUtil.find_index(properties, - "dataport.data_service.inport_ref") - - if index < 0: - return False - - obj = None - try: - obj = any.from_any(properties[index].value, keep_structs=True) - except: - self._rtcout.RTC_ERROR(OpenRTM_aist.Logger.print_exception()) - - if not obj: - return False - - obj_ptr = self._ptr(True) - - if obj_ptr is None or not obj_ptr._is_equivalent(obj): - return False - - self.releaseObject() - return True - - ## - # @if jp - # @brief ꥿󥳡Ѵ - # @else - # @brief Return codes conversion - # @endif - # - # ReturnCode convertReturnCode(OpenRTM::PortStatus ret) - def convertReturnCode(self, ret): - if ret == RTC.PORT_OK: - return self.PORT_OK - - elif ret == RTC.PORT_ERROR: - return self.PORT_ERROR - - elif ret == RTC.BUFFER_FULL: - return self.SEND_FULL - - elif ret == RTC.BUFFER_TIMEOUT: - return self.SEND_TIMEOUT - - elif ret == RTC.UNKNOWN_ERROR: - return self.UNKNOWN_ERROR - - else: - return self.UNKNOWN_ERROR + + +class InPortDSConsumer(OpenRTM_aist.InPortConsumer, + OpenRTM_aist.CorbaConsumer): + """ + """ + + ## + # @if jp + # @brief コンストラクタ + # + # コンストラクタ + # + # @param buffer 当該コンシューマに割り当てるバッファオブジェクト + # + # @else + # @brief Constructor + # + # Constructor + # + # @param buffer The buffer object that is attached to this Consumer + # + # @endif + # + def __init__(self): + OpenRTM_aist.CorbaConsumer.__init__(self, RTC.DataPushService) + self._rtcout = OpenRTM_aist.Manager.instance().getLogbuf("InPortDSConsumer") + self._properties = None + return + + ## + # @if jp + # @brief デストラクタ + # + # デストラクタ + # + # @else + # @brief Destructor + # + # Destructor + # + # @endif + # + def __del__(self, CorbaConsumer=OpenRTM_aist.CorbaConsumer): + self._rtcout.RTC_PARANOID("~InPortDSConsumer()") + CorbaConsumer.__del__(self) + return + + ## + # @if jp + # @brief 設定初期化 + # + # InPortConsumerの各種設定を行う + # + # @else + # @brief Initializing configuration + # + # This operation would be called to configure this consumer + # in initialization. + # + # @endif + # + # virtual void init(coil::Properties& prop); + def init(self, prop): + self._rtcout.RTC_TRACE("init()") + self._properties = prop + return + + ## + # @if jp + # @brief 接続先へのデータ送信 + # + # 接続先のポートへデータを送信するための純粋仮想関数。 + # + # この関数は、以下のリターンコードを返す。 + # + # - PORT_OK: 正常終了。 + # - PORT_ERROR: データ送信の過程で何らかのエラーが発生した。 + # - SEND_FULL: データを送信したが、相手側バッファがフルだった。 + # - SEND_TIMEOUT: データを送信したが、相手側バッファがタイムアウトした。 + # - UNKNOWN_ERROR: 原因不明のエラー + # + # @param data 送信するデータ + # @return リターンコード + # + # @else + # @brief Send data to the destination port + # + # Pure virtual function to send data to the destination port. + # + # This function might the following return codes + # + # - PORT_OK: Normal return + # - PORT_ERROR: Error occurred in data transfer process + # - SEND_FULL: Buffer full although OutPort tried to send data + # - SEND_TIMEOUT: Timeout although OutPort tried to send data + # - UNKNOWN_ERROR: Unknown error + # + # @endif + # + # virtual ReturnCode put(const cdrMemoryStream& data); + def put(self, data): + self._rtcout.RTC_PARANOID("put()") + + try: + dataservice = self._ptr() + if dataservice: + return self.convertReturnCode(dataservice.push(data)) + return self.CONNECTION_LOST + except BaseException: + self._rtcout.RTC_ERROR(OpenRTM_aist.Logger.print_exception()) + return self.CONNECTION_LOST + + ## + # @if jp + # @brief InterfaceProfile情報を公開する + # + # InterfaceProfile情報を公開する。 + # 引数で指定するプロパティ情報内の NameValue オブジェクトの + # dataport.interface_type 値を調べ、当該ポートに設定されている + # インターフェースタイプと一致する場合のみ情報を取得する。 + # + # @param properties InterfaceProfile情報を受け取るプロパティ + # + # @else + # @brief Publish InterfaceProfile information + # + # Publish interfaceProfile information. + # Check the dataport.interface_type value of the NameValue object + # specified by an argument in property information and get information + # only when the interface type of the specified port is matched. + # + # @param properties Properties to get InterfaceProfile information + # + # @endif + # + # virtual void publishInterfaceProfile(SDOPackage::NVList& properties); + + def publishInterfaceProfile(self, properties): + return + + ## + # @if jp + # @brief データ送信通知への登録 + # + # 指定されたプロパティに基づいて、データ送出通知の受け取りに登録する。 + # + # @param properties 登録情報 + # + # @return 登録処理結果(登録成功:true、登録失敗:false) + # + # @else + # @brief Subscribe to the data sending notification + # + # Subscribe to the data sending notification based on specified + # property information. + # + # @param properties Information for subscription + # + # @return Subscription result (Successful:true, Failed:false) + # + # @endif + # + # virtual bool subscribeInterface(const SDOPackage::NVList& properties); + def subscribeInterface(self, properties): + self._rtcout.RTC_TRACE("subscribeInterface()") + # self._rtcout.RTC_DEBUG_STR(OpenRTM_aist.NVUtil.toString(properties)) + + # getting InPort's ref from IOR string + if self.subscribeFromIor(properties): + return True + + # getting InPort's ref from Object reference + if self.subscribeFromRef(properties): + return True + + return False + + ## + # @if jp + # @brief データ送信通知からの登録解除 + # + # データ送出通知の受け取りから登録を解除する。 + # + # @param properties 登録解除情報 + # + # @else + # @brief Unsubscribe the data send notification + # + # Unsubscribe the data send notification. + # + # @param properties Information for unsubscription + # + # @endif + # + # virtual void unsubscribeInterface(const SDOPackage::NVList& properties); + def unsubscribeInterface(self, properties): + self._rtcout.RTC_TRACE("unsubscribeInterface()") + # self._rtcout.RTC_DEBUG_STR(OpenRTM_aist.NVUtil.toString(properties)) + + if self.unsubscribeFromIor(properties): + return + + self.unsubscribeFromRef(properties) + return + + ## + # @if jp + # @brief IOR文字列からオブジェクト参照を取得する + # + # @return true: 正常取得, false: 取得失敗 + # + # @else + # @brief Getting object reference fromn IOR string + # + # @return true: succeeded, false: failed + # + # @endif + # + # bool subscribeFromIor(const SDOPackage::NVList& properties); + def subscribeFromIor(self, properties): + self._rtcout.RTC_TRACE("subscribeFromIor()") + + index = OpenRTM_aist.NVUtil.find_index(properties, + "dataport.data_service.inport_ior") + if index < 0: + self._rtcout.RTC_ERROR("inport_ior not found") + return False + + ior = "" + try: + ior = any.from_any(properties[index].value, keep_structs=True) + except BaseException: + self._rtcout.RTC_ERROR(OpenRTM_aist.Logger.print_exception()) + + if not ior: + self._rtcout.RTC_ERROR("inport_ior has no string") + return False + + orb = OpenRTM_aist.Manager.instance().getORB() + obj = orb.string_to_object(ior) + + if CORBA.is_nil(obj): + self._rtcout.RTC_ERROR("invalid IOR string has been passed") + return False + + if not self.setObject(obj): + self._rtcout.RTC_WARN("Setting object to consumer failed.") + return False + + return True + + ## + # @if jp + # @brief Anyから直接オブジェクト参照を取得する + # + # @return true: 正常取得, false: 取得失敗 + # + # @else + # @brief Getting object reference fromn Any directry + # + # @return true: succeeded, false: failed + # + # @endif + # + # bool subscribeFromRef(const SDOPackage::NVList& properties); + def subscribeFromRef(self, properties): + self._rtcout.RTC_TRACE("subscribeFromRef()") + index = OpenRTM_aist.NVUtil.find_index(properties, + "dataport.data_service.inport_ref") + if index < 0: + self._rtcout.RTC_ERROR("inport_ref not found") + return False + + obj = None + try: + obj = any.from_any(properties[index].value, keep_structs=True) + except BaseException: + self._rtcout.RTC_ERROR(OpenRTM_aist.Logger.print_exception()) + + if not obj: + self._rtcout.RTC_ERROR("prop[inport_ref] is not objref") + return False + + if CORBA.is_nil(obj): + self._rtcout.RTC_ERROR("prop[inport_ref] is not objref") + return False + + if not self.setObject(obj): + self._rtcout.RTC_ERROR("Setting object to consumer failed.") + return False + + return True + + ## + # @if jp + # @brief 接続解除(IOR版) + # + # @return true: 正常取得, false: 取得失敗 + # + # @else + # @brief ubsubscribing (IOR version) + # + # @return true: succeeded, false: failed + # + # @endif + # + # bool unsubscribeFromIor(const SDOPackage::NVList& properties); + def unsubscribeFromIor(self, properties): + self._rtcout.RTC_TRACE("unsubscribeFromIor()") + index = OpenRTM_aist.NVUtil.find_index(properties, + "dataport.data_service.inport_ior") + if index < 0: + self._rtcout.RTC_ERROR("inport_ior not found") + return False + + ior = "" + try: + ior = any.from_any(properties[index].value, keep_structs=True) + except BaseException: + self._rtcout.RTC_ERROR(OpenRTM_aist.Logger.print_exception()) + + if not ior: + self._rtcout.RTC_ERROR("prop[inport_ior] is not string") + return False + + orb = OpenRTM_aist.Manager.instance().getORB() + var = orb.string_to_object(ior) + if not self._ptr(True)._is_equivalent(var): + self._rtcout.RTC_ERROR("connector property inconsistency") + return False + + self.releaseObject() + return True + + ## + # @if jp + # @brief 接続解除(Object reference版) + # + # @return true: 正常取得, false: 取得失敗 + # + # @else + # @brief ubsubscribing (Object reference version) + # + # @return true: succeeded, false: failed + # + # @endif + # + # bool unsubscribeFromRef(const SDOPackage::NVList& properties); + def unsubscribeFromRef(self, properties): + self._rtcout.RTC_TRACE("unsubscribeFromRef()") + index = OpenRTM_aist.NVUtil.find_index(properties, + "dataport.data_service.inport_ref") + + if index < 0: + return False + + obj = None + try: + obj = any.from_any(properties[index].value, keep_structs=True) + except BaseException: + self._rtcout.RTC_ERROR(OpenRTM_aist.Logger.print_exception()) + + if not obj: + return False + + obj_ptr = self._ptr(True) + + if obj_ptr is None or not obj_ptr._is_equivalent(obj): + return False + + self.releaseObject() + return True + + ## + # @if jp + # @brief リターンコード変換 + # @else + # @brief Return codes conversion + # @endif + # + # ReturnCode convertReturnCode(OpenRTM::PortStatus ret) + def convertReturnCode(self, ret): + if ret == RTC.PORT_OK: + return self.PORT_OK + + elif ret == RTC.PORT_ERROR: + return self.PORT_ERROR + + elif ret == RTC.BUFFER_FULL: + return self.SEND_FULL + + elif ret == RTC.BUFFER_TIMEOUT: + return self.SEND_TIMEOUT + + elif ret == RTC.UNKNOWN_ERROR: + return self.UNKNOWN_ERROR + + else: + return self.UNKNOWN_ERROR def InPortDSConsumerInit(): - factory = OpenRTM_aist.InPortConsumerFactory.instance() - factory.addFactory("data_service", - OpenRTM_aist.InPortDSConsumer, - OpenRTM_aist.Delete) + factory = OpenRTM_aist.InPortConsumerFactory.instance() + factory.addFactory("data_service", + OpenRTM_aist.InPortDSConsumer) diff --git a/OpenRTM_aist/InPortDSProvider.py b/OpenRTM_aist/InPortDSProvider.py index bbe5797e..92f5881d 100644 --- a/OpenRTM_aist/InPortDSProvider.py +++ b/OpenRTM_aist/InPortDSProvider.py @@ -1,5 +1,5 @@ #!/usr/bin/env python -# -*- coding: euc-jp -*- +# -*- coding: utf-8 -*- ## # @file InPortDSProvider.py @@ -15,19 +15,18 @@ # All rights reserved. - - import OpenRTM_aist -import RTC__POA,RTC +import RTC__POA +import RTC ## # @if jp # @class InPortDSProvider -# @brief InPortDSProvider 饹 +# @brief InPortDSProvider クラス # -# ̿ʤ CORBA ѤϥݡȥץХμ饹 +# 通信手段に CORBA を利用した入力ポートプロバイダーの実装クラス。 # -# @param DataType ץХ˳ƤХåեݻǡ +# @param DataType 当該プロバイダに割り当てたバッファが保持するデータ型 # # @since 1.2.0 # @@ -35,256 +34,261 @@ # @class InPortDSProvider # @brief InPortDSProvider class # -# This is an implementation class of the input port Provider +# This is an implementation class of the input port Provider # that uses CORBA for means of communication. # -# @param DataType Data type held by the buffer that attached +# @param DataType Data type held by the buffer that attached # to this provider. # # @since 1.2.0 # # @endif # + + class InPortDSProvider(OpenRTM_aist.InPortProvider, - RTC__POA.DataPushService): - - """ - """ - - ## - # @if jp - # @brief 󥹥ȥ饯 - # - # 󥹥ȥ饯 - # ݡȥץѥƥ˰ʲιܤꤹ롣 - # - 󥿡ե : CORBA_Any - # - ǡե : Push, Pull - # - ֥ץ󥿥 : Any - # - # @param buffer ץХ˳ƤХåե֥ - # - # @else - # @brief Constructor - # - # Constructor - # Set the following items to port properties - # - Interface type : CORBA_Any - # - Data flow type : Push, Pull - # - Subscription type : Any - # - # @param buffer Buffer object that is attached to this provider - # - # @endif - # - def __init__(self): - OpenRTM_aist.InPortProvider.__init__(self) - - # PortProfile setting - self.setInterfaceType("data_service") - - # ConnectorProfile setting - self._objref = self._this() - - self._buffer = None - - self._profile = None - self._listeners = None - - # set InPort's reference - orb = OpenRTM_aist.Manager.instance().getORB() - - self._properties.append(OpenRTM_aist.NVUtil.newNV("dataport.data_service.inport_ior", - orb.object_to_string(self._objref))) - self._properties.append(OpenRTM_aist.NVUtil.newNV("dataport.data_service.inport_ref", - self._objref)) - - return - - ## - # @if jp - # @brief ǥȥ饯 - # - # ǥȥ饯 - # - # @else - # @brief Destructor - # - # Destructor - # - # @endif - # - def __del__(self): - return - - ## - # @if jp - # @brief λ - # - # @else - # @brief - # - # - # - # @endif - # - def exit(self): - oid = OpenRTM_aist.Manager.instance().getPOA().servant_to_id(self) - OpenRTM_aist.Manager.instance().getPOA().deactivate_object(oid) - - ## virtual void init(coil::Properties& prop); - def init(self, prop): - pass - - ## virtual void setBuffer(BufferBase* buffer); - def setBuffer(self, buffer): - self._buffer = buffer - return - - # void setListener(ConnectorInfo& info, - # ConnectorListeners* listeners); - def setListener(self, info, listeners): - self._profile = info - self._listeners = listeners - return - - def put(self, data): - self._rtcout.RTC_PARANOID("InPortDSProvider.put()") - return RTC.UNKNOWN_ERROR - ## - # @if jp - # @brief [CORBA interface] Хåե˥ǡ񤭹 - # - # ꤵ줿Хåե˥ǡ񤭹ࡣ - # - # @param data оݥǡ - # - # @else - # @brief [CORBA interface] Write data into the buffer - # - # Write data into the specified buffer. - # - # @param data The target data for writing - # - # @endif - # - # virtual ::OpenRTM::PortStatus push(const ::RTC::CdrData& data) - # throw (CORBA::SystemException); - def push(self, data): - try: - self._rtcout.RTC_PARANOID("InPortDSProvider.push()") - - if not self._buffer: - self.onReceiverError(data) - return RTC.PORT_ERROR - - self._rtcout.RTC_PARANOID("received data size: %d", len(data)) - - self.onReceived(data) - - if not self._connector: - return RTC.PORT_ERROR - - ret = self._connector.write(data) - - return self.convertReturn(ret, data) - - except: - self._rtcout.RTC_TRACE(OpenRTM_aist.Logger.print_exception()) - return RTC.UNKNOWN_ERROR - - - - def convertReturn(self, status, data): - if status == OpenRTM_aist.BufferStatus.BUFFER_OK: - self.onBufferWrite(data) - return RTC.PORT_OK - - elif status == OpenRTM_aist.BufferStatus.BUFFER_ERROR: - self.onReceiverError(data) - return RTC.PORT_ERROR - - elif status == OpenRTM_aist.BufferStatus.BUFFER_FULL: - self.onBufferFull(data) - self.onReceiverFull(data) - return RTC.BUFFER_FULL - - elif status == OpenRTM_aist.BufferStatus.BUFFER_EMPTY: - return RTC.BUFFER_EMPTY - - elif status == OpenRTM_aist.BufferStatus.PRECONDITION_NOT_MET: - self.onReceiverError(data) - return RTC.PORT_ERROR - - elif status == OpenRTM_aist.BufferStatus.TIMEOUT: - self.onBufferWriteTimeout(data) - self.onReceiverTimeout(data) - return RTC.BUFFER_TIMEOUT - - else: - self.onReceiverError(data) - return RTC.UNKNOWN_ERROR - - - ## - # @brief Connector data listener functions - # - # inline void onBufferWrite(const cdrMemoryStream& data) - def onBufferWrite(self, data): - if self._listeners is not None and self._profile is not None: - self._listeners.connectorData_[OpenRTM_aist.ConnectorDataListenerType.ON_BUFFER_WRITE].notify(self._profile, data) - return - - - ## inline void onBufferFull(const cdrMemoryStream& data) - def onBufferFull(self, data): - if self._listeners is not None and self._profile is not None: - self._listeners.connectorData_[OpenRTM_aist.ConnectorDataListenerType.ON_BUFFER_FULL].notify(self._profile, data) - return - - - ## inline void onBufferWriteTimeout(const cdrMemoryStream& data) - def onBufferWriteTimeout(self, data): - if self._listeners is not None and self._profile is not None: - self._listeners.connectorData_[OpenRTM_aist.ConnectorDataListenerType.ON_BUFFER_WRITE_TIMEOUT].notify(self._profile, data) - return - - ## inline void onBufferWriteOverwrite(const cdrMemoryStream& data) - def onBufferWriteOverwrite(self, data): - if self._listeners is not None and self._profile is not None: - self._listeners.connectorData_[OpenRTM_aist.ConnectorDataListenerType.ON_BUFFER_OVERWRITE].notify(self._profile, data) - return - - - ## inline void onReceived(const cdrMemoryStream& data) - def onReceived(self, data): - if self._listeners is not None and self._profile is not None: - self._listeners.connectorData_[OpenRTM_aist.ConnectorDataListenerType.ON_RECEIVED].notify(self._profile, data) - return + RTC__POA.DataPushService): + + """ + """ + + ## + # @if jp + # @brief コンストラクタ + # + # コンストラクタ + # ポートプロパティに以下の項目を設定する。 + # - インターフェースタイプ : CORBA_Any + # - データフロータイプ : Push, Pull + # - サブスクリプションタイプ : Any + # + # @param buffer 当該プロバイダに割り当てるバッファオブジェクト + # + # @else + # @brief Constructor + # + # Constructor + # Set the following items to port properties + # - Interface type : CORBA_Any + # - Data flow type : Push, Pull + # - Subscription type : Any + # + # @param buffer Buffer object that is attached to this provider + # + # @endif + # + def __init__(self): + OpenRTM_aist.InPortProvider.__init__(self) + + # PortProfile setting + self.setInterfaceType("data_service") + + # ConnectorProfile setting + self._objref = self._this() + + self._buffer = None + + self._profile = None + self._listeners = None + + # set InPort's reference + orb = OpenRTM_aist.Manager.instance().getORB() + + self._properties.append(OpenRTM_aist.NVUtil.newNV("dataport.data_service.inport_ior", + orb.object_to_string(self._objref))) + self._properties.append(OpenRTM_aist.NVUtil.newNV("dataport.data_service.inport_ref", + self._objref)) + + return + + ## + # @if jp + # @brief デストラクタ + # + # デストラクタ + # + # @else + # @brief Destructor + # + # Destructor + # + # @endif + # + def __del__(self): + return + + ## + # @if jp + # @brief 終了処理 + # + # @else + # @brief + # + # + # + # @endif + # + def exit(self): + oid = OpenRTM_aist.Manager.instance().getPOA().servant_to_id(self) + OpenRTM_aist.Manager.instance().getPOA().deactivate_object(oid) + + # virtual void init(coil::Properties& prop); + def init(self, prop): + pass + + # virtual void setBuffer(BufferBase* buffer); + def setBuffer(self, buffer): + self._buffer = buffer + return + + # void setListener(ConnectorInfo& info, + # ConnectorListeners* listeners); + def setListener(self, info, listeners): + self._profile = info + self._listeners = listeners + return + + def put(self, data): + self._rtcout.RTC_PARANOID("InPortDSProvider.put()") + return RTC.UNKNOWN_ERROR + ## + # @if jp + # @brief [CORBA interface] バッファにデータを書き込む + # + # 設定されたバッファにデータを書き込む。 + # + # @param data 書込対象データ + # + # @else + # @brief [CORBA interface] Write data into the buffer + # + # Write data into the specified buffer. + # + # @param data The target data for writing + # + # @endif + # + # virtual ::OpenRTM::PortStatus push(const ::RTC::CdrData& data) + # throw (CORBA::SystemException); + + def push(self, data): + try: + self._rtcout.RTC_PARANOID("InPortDSProvider.push()") + + if not self._connector: + self.onReceiverError(data) + return RTC.PORT_ERROR + + self._rtcout.RTC_PARANOID("received data size: %d", len(data)) + + data = self.onReceived(data) + + ret = self._connector.write(data) + + return self.convertReturn(ret, data) + + except BaseException: + self._rtcout.RTC_TRACE(OpenRTM_aist.Logger.print_exception()) + return RTC.UNKNOWN_ERROR + + def convertReturn(self, status, data): + if status == OpenRTM_aist.BufferStatus.BUFFER_OK: + self.onBufferWrite(data) + return RTC.PORT_OK + + elif status == OpenRTM_aist.BufferStatus.BUFFER_ERROR: + self.onReceiverError(data) + return RTC.PORT_ERROR + + elif status == OpenRTM_aist.BufferStatus.BUFFER_FULL: + data = self.onBufferFull(data) + self.onReceiverFull(data) + return RTC.BUFFER_FULL + + elif status == OpenRTM_aist.BufferStatus.BUFFER_EMPTY: + return RTC.BUFFER_EMPTY + + elif status == OpenRTM_aist.BufferStatus.PRECONDITION_NOT_MET: + self.onReceiverError(data) + return RTC.PORT_ERROR + + elif status == OpenRTM_aist.BufferStatus.TIMEOUT: + data = self.onBufferWriteTimeout(data) + self.onReceiverTimeout(data) + return RTC.BUFFER_TIMEOUT + + else: + self.onReceiverError(data) + return RTC.UNKNOWN_ERROR + + ## + # @brief Connector data listener functions + # + # inline void onBufferWrite(const cdrMemoryStream& data) + + def onBufferWrite(self, data): + if self._listeners is not None and self._profile is not None: + _, data = self._listeners.notifyData( + OpenRTM_aist.ConnectorDataListenerType.ON_BUFFER_WRITE, self._profile, data) + return data + + # inline void onBufferFull(const cdrMemoryStream& data) + + def onBufferFull(self, data): + if self._listeners is not None and self._profile is not None: + _, data = self._listeners.notifyData( + OpenRTM_aist.ConnectorDataListenerType.ON_BUFFER_FULL, self._profile, data) + return data + + # inline void onBufferWriteTimeout(const cdrMemoryStream& data) + + def onBufferWriteTimeout(self, data): + if self._listeners is not None and self._profile is not None: + _, data = self._listeners.notifyData( + OpenRTM_aist.ConnectorDataListenerType.ON_BUFFER_WRITE_TIMEOUT, self._profile, data) + return data + + # inline void onBufferWriteOverwrite(const cdrMemoryStream& data) + def onBufferWriteOverwrite(self, data): + if self._listeners is not None and self._profile is not None: + _, data = self._listeners.notifyData( + OpenRTM_aist.ConnectorDataListenerType.ON_BUFFER_OVERWRITE, self._profile, data) + return data + + # inline void onReceived(const cdrMemoryStream& data) + + def onReceived(self, data): + if self._listeners is not None and self._profile is not None: + _, data = self._listeners.notifyData( + OpenRTM_aist.ConnectorDataListenerType.ON_RECEIVED, self._profile, data) + return data + # inline void onReceiverFull(const cdrMemoryStream& data) - ## inline void onReceiverFull(const cdrMemoryStream& data) - def onReceiverFull(self, data): - if self._listeners is not None and self._profile is not None: - self._listeners.connectorData_[OpenRTM_aist.ConnectorDataListenerType.ON_RECEIVER_FULL].notify(self._profile, data) - return + def onReceiverFull(self, data): + if self._listeners is not None and self._profile is not None: + _, data = self._listeners.notifyData( + OpenRTM_aist.ConnectorDataListenerType.ON_RECEIVER_FULL, self._profile, data) + return data + # inline void onReceiverTimeout(const cdrMemoryStream& data) - ## inline void onReceiverTimeout(const cdrMemoryStream& data) - def onReceiverTimeout(self, data): - if self._listeners is not None and self._profile is not None: - self._listeners.connectorData_[OpenRTM_aist.ConnectorDataListenerType.ON_RECEIVER_TIMEOUT].notify(self._profile, data) - return + def onReceiverTimeout(self, data): + if self._listeners is not None and self._profile is not None: + _, data = self._listeners.notifyData( + OpenRTM_aist.ConnectorDataListenerType.ON_RECEIVER_TIMEOUT, self._profile, data) + return data + # inline void onReceiverError(const cdrMemoryStream& data) - ## inline void onReceiverError(const cdrMemoryStream& data) - def onReceiverError(self, data): - if self._listeners is not None and self._profile is not None: - self._listeners.connectorData_[OpenRTM_aist.ConnectorDataListenerType.ON_RECEIVER_ERROR].notify(self._profile, data) - return + def onReceiverError(self, data): + if self._listeners is not None and self._profile is not None: + _, data = self._listeners.notifyData( + OpenRTM_aist.ConnectorDataListenerType.ON_RECEIVER_ERROR, self._profile, data) + return data def InPortDSProviderInit(): - factory = OpenRTM_aist.InPortProviderFactory.instance() - factory.addFactory("data_service", - OpenRTM_aist.InPortDSProvider, - OpenRTM_aist.Delete) + factory = OpenRTM_aist.InPortProviderFactory.instance() + factory.addFactory("data_service", + OpenRTM_aist.InPortDSProvider) diff --git a/OpenRTM_aist/InPortDirectConsumer.py b/OpenRTM_aist/InPortDirectConsumer.py index 6655e839..c4a9ade0 100644 --- a/OpenRTM_aist/InPortDirectConsumer.py +++ b/OpenRTM_aist/InPortDirectConsumer.py @@ -1,13 +1,12 @@ #!/usr/bin/env python -# -*- coding: euc-jp -*- +# -*- coding: utf-8 -*- ## # @file InPortDirectConsumer.py # @brief InPortDirectConsumer class # @date $Date: 2016/01/08 $ # @author Nobuhiko Miyamoto -# - +# import OpenRTM_aist @@ -18,9 +17,9 @@ # # @class InPortDirectConsumer # -# @brief InPortDirectConsumer 饹 +# @brief InPortDirectConsumer クラス # -# ǡ쥯Ȥ˽񤭹push̿¸InPort󥷥ޡ饹 +# データをダイレクトに書き込むpush型通信を実現するInPortコンシュマークラス # # @else # @class InPortDirectConsumer @@ -32,173 +31,168 @@ # @endif # class InPortDirectConsumer(OpenRTM_aist.InPortConsumer): - """ - """ - - ## - # @if jp - # @brief 󥹥ȥ饯 - # - # 󥹥ȥ饯 - # - # @param self - # - # @else - # @brief Constructor - # - # Constructor - # - # @param self - # - # @endif - # - def __init__(self): - OpenRTM_aist.InPortConsumer.__init__(self) - self._rtcout = OpenRTM_aist.Manager.instance().getLogbuf("InPortDirectConsumer") - self._properties = None - return - - ## - # @if jp - # @brief ǥȥ饯 - # - # ǥȥ饯 - # - # @param self - # - # @else - # @brief Destructor - # - # Destructor - # - # @param self - # - # @endif - # - def __del__(self): - self._rtcout.RTC_PARANOID("~InPortDirectConsumer()") - - return - - ## - # @if jp - # @brief - # - # InPortConsumerγƼԤ - # - # @self - # - # - # @else - # @brief Initializing configuration - # - # - # @endif - # - # virtual void init(coil::Properties& prop); - def init(self, prop): - self._rtcout.RTC_TRACE("init()") - self._properties = prop - return - - ## - # @if jp - # @brief - # - # @param self - # @param data - # @return - # - # @else - # @brief - # - # @param self - # @param data - # @return - # - # @endif - # - # virtual ReturnCode put(const cdrMemoryStream& data); - def put(self, data): - self._rtcout.RTC_PARANOID("put()") - - - return self.UNKNOWN_ERROR - - ## - # @if jp - # @brief InterfaceProfile - # - # - # @param self - # @param properties InterfaceProfileץѥƥ - # - # @else - # @brief Publish InterfaceProfile information - # - # - # @param self - # @param properties Properties to get InterfaceProfile information - # - # @endif - # - # virtual void publishInterfaceProfile(SDOPackage::NVList& properties); - def publishInterfaceProfile(self, properties): - return - - ## - # @if jp - # @brief ǡΤؤϿ - # - # @param self - # @param properties Ͽ - # - # @return Ͽ(Ͽ:trueϿ:false) - # - # @else - # @brief Subscribe to the data sending notification - # - # @param self - # @param properties Information for subscription - # - # @return Subscription result (Successful:true, Failed:false) - # - # @endif - # - # virtual bool subscribeInterface(const SDOPackage::NVList& properties); - def subscribeInterface(self, properties): - self._rtcout.RTC_TRACE("subscribeInterface()") - - - return True - - ## - # @if jp - # @brief ǡΤϿ - # - # @param self - # @param properties Ͽ - # - # @else - # @brief Unsubscribe the data send notification - # - # - # @param self - # @param properties Information for unsubscription - # - # @endif - # - # virtual void unsubscribeInterface(const SDOPackage::NVList& properties); - def unsubscribeInterface(self, properties): - self._rtcout.RTC_TRACE("unsubscribeInterface()") - - return - - + """ + """ + + ## + # @if jp + # @brief コンストラクタ + # + # コンストラクタ + # + # @param self + # + # @else + # @brief Constructor + # + # Constructor + # + # @param self + # + # @endif + # + def __init__(self): + OpenRTM_aist.InPortConsumer.__init__(self) + self._rtcout = OpenRTM_aist.Manager.instance().getLogbuf("InPortDirectConsumer") + self._properties = None + return + + ## + # @if jp + # @brief デストラクタ + # + # デストラクタ + # + # @param self + # + # @else + # @brief Destructor + # + # Destructor + # + # @param self + # + # @endif + # + def __del__(self): + self._rtcout.RTC_PARANOID("~InPortDirectConsumer()") + + return + + ## + # @if jp + # @brief 設定初期化 + # + # InPortConsumerの各種設定を行う + # + # @self + # + # + # @else + # @brief Initializing configuration + # + # + # @endif + # + # virtual void init(coil::Properties& prop); + def init(self, prop): + self._rtcout.RTC_TRACE("init()") + self._properties = prop + return + + ## + # @if jp + # @brief + # + # @param self + # @param data + # @return + # + # @else + # @brief + # + # @param self + # @param data + # @return + # + # @endif + # + # virtual ReturnCode put(const cdrMemoryStream& data); + def put(self, data): + self._rtcout.RTC_PARANOID("put()") + + return self.UNKNOWN_ERROR + + ## + # @if jp + # @brief InterfaceProfile情報を公開する + # + # + # @param self + # @param properties InterfaceProfile情報を受け取るプロパティ + # + # @else + # @brief Publish InterfaceProfile information + # + # + # @param self + # @param properties Properties to get InterfaceProfile information + # + # @endif + # + # virtual void publishInterfaceProfile(SDOPackage::NVList& properties); + def publishInterfaceProfile(self, properties): + return + + ## + # @if jp + # @brief データ送信通知への登録 + # + # @param self + # @param properties 登録情報 + # + # @return 登録処理結果(登録成功:true、登録失敗:false) + # + # @else + # @brief Subscribe to the data sending notification + # + # @param self + # @param properties Information for subscription + # + # @return Subscription result (Successful:true, Failed:false) + # + # @endif + # + # virtual bool subscribeInterface(const SDOPackage::NVList& properties); + def subscribeInterface(self, properties): + self._rtcout.RTC_TRACE("subscribeInterface()") + + return True + + ## + # @if jp + # @brief データ送信通知からの登録解除 + # + # @param self + # @param properties 登録解除情報 + # + # @else + # @brief Unsubscribe the data send notification + # + # + # @param self + # @param properties Information for unsubscription + # + # @endif + # + # virtual void unsubscribeInterface(const SDOPackage::NVList& properties); + def unsubscribeInterface(self, properties): + self._rtcout.RTC_TRACE("unsubscribeInterface()") + + return def InPortDirectConsumerInit(): - factory = OpenRTM_aist.InPortConsumerFactory.instance() - factory.addFactory("direct", - OpenRTM_aist.InPortDirectConsumer, - OpenRTM_aist.Delete) + factory = OpenRTM_aist.InPortConsumerFactory.instance() + factory.addFactory("direct", + OpenRTM_aist.InPortDirectConsumer) diff --git a/OpenRTM_aist/InPortDirectProvider.py b/OpenRTM_aist/InPortDirectProvider.py index a4d4d39e..dc18e019 100644 --- a/OpenRTM_aist/InPortDirectProvider.py +++ b/OpenRTM_aist/InPortDirectProvider.py @@ -1,14 +1,12 @@ #!/usr/bin/env python -# -*- coding: euc-jp -*- +# -*- coding: utf-8 -*- ## # @file InPortDirectProvider.py # @brief InPortDirectProvider class # @date $Date: 2016/01/08 $ # @author Nobuhiko Miyamoto -# - - +# import OpenRTM_aist @@ -17,9 +15,9 @@ ## # @if jp # @class InPortDirectProvider -# @brief InPortDirectProvider 饹 +# @brief InPortDirectProvider クラス # -# ǡ쥯Ȥ˽񤭹push̿¸InPortץХ饹 +# データをダイレクトに書き込むpush型通信を実現するInPortプロバイダクラス # # @param self # @@ -33,154 +31,155 @@ # @endif # class InPortDirectProvider(OpenRTM_aist.InPortProvider): - - """ - """ - - ## - # @if jp - # @brief 󥹥ȥ饯 - # - # 󥹥ȥ饯 - # - # @param self - # - # @else - # @brief Constructor - # - # @param self - # - # @endif - # - def __init__(self): - OpenRTM_aist.InPortProvider.__init__(self) - - # PortProfile setting - self.setInterfaceType("direct") - - - - self._buffer = None - - self._profile = None - self._listeners = None - #self._connector = None - - - - return - - ## - # @if jp - # @brief ǥȥ饯 - # - # ǥȥ饯 - # - # @param self - # - # @else - # @brief Destructor - # - # Destructor - # - # @param self - # - # @endif - # - def __del__(self): - - return - ## - # @if jp - # @brief λ - # - # @else - # @brief - # - # - # - # @endif - # - def exit(self): - pass - - ## void init(coil::Properties& prop); - def init(self, prop): - pass - - ## void setBuffer(BufferBase* buffer); - def setBuffer(self, buffer): - self._buffer = buffer - return - - # void setListener(ConnectorInfo& info, - # ConnectorListeners* listeners); - def setListener(self, info, listeners): - self._profile = info - self._listeners = listeners - return - - - ## void onBufferWrite(const cdrMemoryStream& data) - def onBufferWrite(self, data): - if self._listeners is not None and self._profile is not None: - self._listeners.connectorData_[OpenRTM_aist.ConnectorDataListenerType.ON_BUFFER_WRITE].notify(self._profile, data) - return - - - ## inline void onBufferFull(const cdrMemoryStream& data) - def onBufferFull(self, data): - if self._listeners is not None and self._profile is not None: - self._listeners.connectorData_[OpenRTM_aist.ConnectorDataListenerType.ON_BUFFER_FULL].notify(self._profile, data) - return - - - ## inline void onBufferWriteTimeout(const cdrMemoryStream& data) - def onBufferWriteTimeout(self, data): - if self._listeners is not None and self._profile is not None: - self._listeners.connectorData_[OpenRTM_aist.ConnectorDataListenerType.ON_BUFFER_WRITE_TIMEOUT].notify(self._profile, data) - return - - ## inline void onBufferWriteOverwrite(const cdrMemoryStream& data) - def onBufferWriteOverwrite(self, data): - if self._listeners is not None and self._profile is not None: - self._listeners.connectorData_[OpenRTM_aist.ConnectorDataListenerType.ON_BUFFER_OVERWRITE].notify(self._profile, data) - return - - - ## inline void onReceived(const cdrMemoryStream& data) - def onReceived(self, data): - if self._listeners is not None and self._profile is not None: - self._listeners.connectorData_[OpenRTM_aist.ConnectorDataListenerType.ON_RECEIVED].notify(self._profile, data) - return - - - ## inline void onReceiverFull(const cdrMemoryStream& data) - def onReceiverFull(self, data): - if self._listeners is not None and self._profile is not None: - self._listeners.connectorData_[OpenRTM_aist.ConnectorDataListenerType.ON_RECEIVER_FULL].notify(self._profile, data) - return - - - ## inline void onReceiverTimeout(const cdrMemoryStream& data) - def onReceiverTimeout(self, data): - if self._listeners is not None and self._profile is not None: - self._listeners.connectorData_[OpenRTM_aist.ConnectorDataListenerType.ON_RECEIVER_TIMEOUT].notify(self._profile, data) - return - - - ## inline void onReceiverError(const cdrMemoryStream& data) - def onReceiverError(self, data): - if self._listeners is not None and self._profile is not None: - self._listeners.connectorData_[OpenRTM_aist.ConnectorDataListenerType.ON_RECEIVER_ERROR].notify(self._profile, data) - return - - + """ + """ + + ## + # @if jp + # @brief コンストラクタ + # + # コンストラクタ + # + # @param self + # + # @else + # @brief Constructor + # + # @param self + # + # @endif + # + def __init__(self): + OpenRTM_aist.InPortProvider.__init__(self) + + # PortProfile setting + self.setInterfaceType("direct") + + self._buffer = None + + self._profile = None + self._listeners = None + #self._connector = None + + return + + ## + # @if jp + # @brief デストラクタ + # + # デストラクタ + # + # @param self + # + # @else + # @brief Destructor + # + # Destructor + # + # @param self + # + # @endif + # + def __del__(self): + + return + ## + # @if jp + # @brief 終了処理 + # + # @else + # @brief + # + # + # + # @endif + # + + def exit(self): + pass + + # void init(coil::Properties& prop); + def init(self, prop): + pass + + # void setBuffer(BufferBase* buffer); + def setBuffer(self, buffer): + self._buffer = buffer + return + + # void setListener(ConnectorInfo& info, + # ConnectorListeners* listeners); + def setListener(self, info, listeners): + self._profile = info + self._listeners = listeners + return + + # void onBufferWrite(const cdrMemoryStream& data) + + def onBufferWrite(self, data): + if self._listeners is not None and self._profile is not None: + _, data = self._listeners.notifyData( + OpenRTM_aist.ConnectorDataListenerType.ON_BUFFER_WRITE, self._profile, data) + return data + + # inline void onBufferFull(const cdrMemoryStream& data) + + def onBufferFull(self, data): + if self._listeners is not None and self._profile is not None: + _, data = self._listeners.notifyData( + OpenRTM_aist.ConnectorDataListenerType.ON_BUFFER_FULL, self._profile, data) + return data + + # inline void onBufferWriteTimeout(const cdrMemoryStream& data) + + def onBufferWriteTimeout(self, data): + if self._listeners is not None and self._profile is not None: + _, data = self._listeners.notifyData( + OpenRTM_aist.ConnectorDataListenerType.ON_BUFFER_WRITE_TIMEOUT, self._profile, data) + return data + + # inline void onBufferWriteOverwrite(const cdrMemoryStream& data) + def onBufferWriteOverwrite(self, data): + if self._listeners is not None and self._profile is not None: + _, data = self._listeners.notifyData( + OpenRTM_aist.ConnectorDataListenerType.ON_BUFFER_OVERWRITE, self._profile, data) + return data + + # inline void onReceived(const cdrMemoryStream& data) + + def onReceived(self, data): + if self._listeners is not None and self._profile is not None: + _, data = self._listeners.notifyData( + OpenRTM_aist.ConnectorDataListenerType.ON_RECEIVED, self._profile, data) + return data + + # inline void onReceiverFull(const cdrMemoryStream& data) + + def onReceiverFull(self, data): + if self._listeners is not None and self._profile is not None: + _, data = self._listeners.notifyData( + OpenRTM_aist.ConnectorDataListenerType.ON_RECEIVER_FULL, self._profile, data) + return data + + # inline void onReceiverTimeout(const cdrMemoryStream& data) + + def onReceiverTimeout(self, data): + if self._listeners is not None and self._profile is not None: + _, data = self._listeners.notifyData( + OpenRTM_aist.ConnectorDataListenerType.ON_RECEIVER_TIMEOUT, self._profile, data) + return data + + # inline void onReceiverError(const cdrMemoryStream& data) + + def onReceiverError(self, data): + if self._listeners is not None and self._profile is not None: + _, data = self._listeners.notifyData( + OpenRTM_aist.ConnectorDataListenerType.ON_RECEIVER_ERROR, self._profile, data) + return data def InPortDirectProviderInit(): - factory = OpenRTM_aist.InPortProviderFactory.instance() - factory.addFactory("direct", - OpenRTM_aist.InPortDirectProvider, - OpenRTM_aist.Delete) + factory = OpenRTM_aist.InPortProviderFactory.instance() + factory.addFactory("direct", + OpenRTM_aist.InPortDirectProvider) diff --git a/OpenRTM_aist/InPortDuplexConnector.py b/OpenRTM_aist/InPortDuplexConnector.py new file mode 100644 index 00000000..f3580184 --- /dev/null +++ b/OpenRTM_aist/InPortDuplexConnector.py @@ -0,0 +1,544 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- + +## +# +# @file InPortDuplexConnector.py +# @brief Bidirectional type connector class +# @date $Date$ +# @author Nobuhiko Miyamoto +# +# Copyright (C) 2019 +# Noriaki Ando +# Robot Innovation Research Center, +# National Institute of +# Advanced Industrial Science and Technology (AIST), Japan +# All rights reserved. +# + + +import OpenRTM_aist +import threading + + +## +# @if jp +# @class InPortPushConnector +# @brief InPortPushConnector クラス +# +# +# @since 2.0.0 +# +# @else +# @class InPortPushConnector +# @brief InPortPushConnector class +# +# +# @since 2.0.0 +# +# @endif +# +class InPortDuplexConnector(OpenRTM_aist.InPortConnector): + """ + """ + + ## + # @if jp + # @brief コンストラクタ + # + # @param info ConnectorInfo + # @param provider InPortProvider + # @param listeners ConnectorListeners 型のリスナオブジェクトリスト + # @param buffer CdrBufferBase 型のバッファ + # + # @elsek + # @brief Constructor + # + # @param info ConnectorInfo + # @param provider InPortProvider + # @param listeners ConnectorListeners type lsitener object list + # @param buffer CdrBufferBase type buffer + # + # @endif + # + def __init__(self, info, provider, listeners, buffer=None): + OpenRTM_aist.InPortConnector.__init__(self, info, buffer) + self._provider = provider + self._listeners = listeners + + if not self._provider: + raise + + self._buffer = None + self._info = info + self._provider.init(info.properties) + self._provider.setListener(info, self._listeners) + self.onConnect() + + self._consumer = None + self._isWritableCallback = None + self._writeCallback = None + + self._marshaling_type = info.properties.getProperty( + "marshaling_type", "cdr") + self._marshaling_type = self._marshaling_type.strip() + + self._serializer = None + + return + + ## + # @if jp + # @brief デストラクタ + # + # disconnect() が呼ばれ、consumer, publisher, buffer が解体・削除される。 + # + # @else + # + # @brief Destructor + # + # This operation calls disconnect(), which destructs and deletes + # the consumer, the publisher and the buffer. + # + # @endif + # + + def __del__(self): + return + + ## + # @if jp + # @brief バッファからデータを読み出す。 + # read関数と違い、アンマーシャリングを実行しない + # + # @param self + # @return リターンコード + # + # @brief + # + # @param self + # @return + # + # @endif + # + def readBuff(self): + self._rtcout.RTC_TRACE("readBuff()") + if self._consumer: + read_ret, data = self._consumer.get() + return read_ret, data + self._rtcout.RTC_ERROR("cunsumer is not set") + return self.PORT_ERROR, None + + ## + # @if jp + # @brief データの読み出し + # + # バッファからデータを読み出す。正常に読み出せた場合、戻り値は + # PORT_OK となり、data に読み出されたデータが格納される。それ以外 + # の場合には、エラー値として BUFFER_EMPTY, TIMEOUT, + # PRECONDITION_NOT_MET, PORT_ERROR が返される。 + # + # @return PORT_OK 正常終了 + # BUFFER_EMPTY バッファは空である + # TIMEOUT タイムアウトした + # PRECONDITION_NOT_MET 事前条件を満たさない + # PORT_ERROR その他のエラー + # + # @else + # + # @brief Reading data + # + # This function reads data from the buffer. If data is read + # properly, this function will return PORT_OK return code. Except + # normal return, BUFFER_EMPTY, TIMEOUT, PRECONDITION_NOT_MET and + # PORT_ERROR will be returned as error codes. + # + # @return PORT_OK Normal return + # BUFFER_EMPTY Buffer empty + # TIMEOUT Timeout + # PRECONDITION_NOT_MET Preconditin not met + # PORT_ERROR Other error + # + # @endif + # + # virtual ReturnCode read(cdrMemoryStream& data); + def read(self, data=None): + self._rtcout.RTC_TRACE("read()") + if not self._dataType: + return self.PRECONDITION_NOT_MET + ret, cdr = self.readBuff() + if ret != self.PORT_OK: + return ret, data + else: + cdr = self.onBufferRead(cdr) + ret, _data = self.deserializeData(cdr) + return ret, _data + + # + # @if jp + # @brief データが読み込める状態かを判定 + # @param self + # @param retry True:再検索、False:通常の読み込み確認 + # @return True:読み込み可能 + # @else + # @brief + # @param self + # @param retry + # @return + # @endif + + def isReadable(self, retry=False): + if self._consumer: + return self._consumer.isReadable(retry) + return False + + ## + # @if jp + # @brief 接続解除 + # + # consumer, publisher, buffer が解体・削除される。 + # + # @return PORT_OK + # + # @else + # + # @brief disconnect + # + # This operation destruct and delete the consumer, the publisher + # and the buffer. + # + # @return PORT_OK + # + # @endif + # + # virtual ReturnCode disconnect(); + + def disconnect(self): + self._rtcout.RTC_TRACE("disconnect()") + self.onDisconnect() + # delete consumer + if self._provider: + cfactory = OpenRTM_aist.InPortProviderFactory.instance() + + self._provider.exit() + + self._provider = None + + self._consumer = None + + return self.PORT_OK + + ## + # @if jp + # @brief アクティブ化 + # + # このコネクタをアクティブ化する + # + # @else + # + # @brief Connector activation + # + # This operation activates this connector + # + # @endif + # + # virtual void activate(){}; // do nothing + def activate(self): # do nothing + pass + + ## + # @if jp + # @brief 非アクティブ化 + # + # このコネクタを非アクティブ化する + # + # @else + # + # @brief Connector deactivation + # + # This operation deactivates this connector + # + # @endif + # + # virtual void deactivate(){}; // do nothing + def deactivate(self): # do nothing + pass + + ## + # @if jp + # @brief Bufferの生成 + # + # 与えられた接続情報に基づきバッファを生成する。 + # + # @param info 接続情報 + # @return バッファへのポインタ + # + # @else + # @brief create buffer + # + # This function creates a buffer based on given information. + # + # @param info Connector information + # @return The poitner to the buffer + # + # @endif + # + # virtual CdrBufferBase* createBuffer(Profile& profile); + + def createBuffer(self, profile): + return None + + ## + # @if jp + # @brief データの書き出し + # + # バッファにデータを書き出す。正常に書き出せた場合、戻り値は + # BUFFER_OK となる。それ以外の場合には、エラー値として BUFFER_FULL,TIMEOUT + # PRECONDITION_NOT_MET, BUFFER_ERROR が返される。 + # + # @return BUFFER_OK 正常終了 + # BUFFER_FULL バッファはいっぱいである + # TIMEOUT タイムアウトした + # PRECONDITION_NOT_MET 事前条件を満たさない + # BUFFER_ERROR その他のエラー + # + # @else + # + # @brief Reading data + # + # This function write data to the buffer. If data is write + # properly, this function will return BUFFER_OK return code. Except + # normal return, BUFFER_FULL, TIMEOUT, PRECONDITION_NOT_MET and + # BUFFER_ERROR will be returned as error codes. + # + # @return BUFFER_OK Normal return + # BUFFER_FULL Buffer full + # TIMEOUT Timeout + # PRECONDITION_NOT_MET Preconditin not met + # BUFFER_ERROR Other error + # + # @endif + # + # ReturnCode write(const OpenRTM::CdrData& data); + + def write(self, data): + if self._writeCallback: + return self._writeCallback(data) + return OpenRTM_aist.BufferStatus.PRECONDITION_NOT_MET + + # + # @if jp + # @brief データを書き込める状態かを判定 + # @param self + # @param retry True:再検索、False:通常の書き込み確認 + # @return True:書き込み可能 + # @else + # @brief + # @param self + # @param retry + # @return + # @endif + def isWritable(self, retry=False): + if self._isWritableCallback: + return self._isWritableCallback(self, retry) + return False + + # + # @if jp + # @brief データ書き込み時のリスナ設定 + # @param self + # @param listener リスナ + # @else + # @brief + # @param self + # @param listener + # @endif + def setWriteListener(self, listener): + self._writeCallback = listener + + # + # @if jp + # @brief データ書き込み判定時のリスナ設定 + # @param self + # @param listener リスナ + # @else + # @brief + # @param self + # @param listener + # @endif + def setIsWritableListener(self, listener): + self._isWritableCallback = listener + + ## + # @if jp + # @brief 接続確立時にコールバックを呼ぶ + # @else + # @brief Invoke callback when connection is established + # @endif + # void onConnect() + def onConnect(self): + if self._listeners and self._profile: + self._listeners.notify(OpenRTM_aist.ConnectorListenerType.ON_CONNECT, self._profile) + return + + ## + # @if jp + # @brief 接続切断時にコールバックを呼ぶ + # @else + # @brief Invoke callback when connection is destroied + # @endif + # void onDisconnect() + def onDisconnect(self): + if self._listeners and self._profile: + self._listeners.notify(OpenRTM_aist.ConnectorListenerType.ON_DISCONNECT, self._profile) + return + + ## + # @if jp + # @brief コンシューマの設定 + # @else + # @brief set Consumer + # @endif + def setConsumer(self, consumer): + self._consumer = consumer + self._consumer.setListener(self._info, self._listeners) + + def onBufferRead(self, data): + if self._listeners and self._profile: + _, data = self._listeners.notifyData(OpenRTM_aist.ConnectorDataListenerType.ON_BUFFER_READ, self._profile, data) + return data + + def onBufferEmpty(self, data): + if self._listeners and self._profile: + self._listeners.notify(OpenRTM_aist.ConnectorListenerType.ON_BUFFER_EMPTY, self._profile) + return + + def onBufferReadTimeout(self, data): + if self._listeners and self._profile: + self._listeners.notify(OpenRTM_aist.ConnectorListenerType.ON_BUFFER_READ_TIMEOUT, self._profile) + return + + ## + # @if jp + # @brief データの復号化 + # @param self + # @param cdr 復号化前のデータ + # @return ret, data + # ret:リターンコード + # PORT_OK:正常完了 + # PRECONDITION_NOT_MET:サポートされていないエンディアン + # SERIALIZE_ERROR:復号化処理でエラー + # PRECONDITION_NOT_MET:その他のエラー + # data:復号化後のデータ + # @else + # @brief + # @param self + # @param cdr + # @return + # @endif + def deserializeData(self, cdr): + if self._serializer is None: + self._rtcout.RTC_ERROR("serializer creation failure.") + return self.UNKNOWN_ERROR, None + + self._serializer.isLittleEndian(self._endian) + ser_ret, data = self._serializer.deserialize(cdr, self._dataType) + + if ser_ret == OpenRTM_aist.ByteDataStreamBase.SERIALIZE_OK: + return self.PORT_OK, data + elif ser_ret == OpenRTM_aist.ByteDataStreamBase.SERIALIZE_NOT_SUPPORT_ENDIAN: + self._rtcout.RTC_ERROR("unknown endian from connector") + return self.UNKNOWN_ERROR, None + elif ser_ret == OpenRTM_aist.ByteDataStreamBase.SERIALIZE_ERROR: + self._rtcout.RTC_ERROR("unknown error") + return self.UNKNOWN_ERROR, None + elif ser_ret == OpenRTM_aist.ByteDataStreamBase.SERIALIZE_NOTFOUND: + self._rtcout.RTC_ERROR("unknown serializer from connector") + return self.UNKNOWN_ERROR, None + return self.UNKNOWN_ERROR, None + + ## + # @if jp + # @brief コンシューマのインターフェースの登録を取り消す + # @param prop コネクタプロファイルのプロパティ + # @else + # @brief + # @param prop + # @endif + def unsubscribeInterface(self, prop): + if self._consumer: + self._consumer.unsubscribeInterface(prop) + + + def setDataType(self, data): + OpenRTM_aist.InPortConnector.setDataType(self, data) + self._serializer = OpenRTM_aist.SerializerFactories.instance().createSerializer(self._marshaling_type, data) + + +## +# @if jp +# @class WriteListenerBase +# @brief WriteListenerBase クラス +# +# 書き込み時リスナのベースクラス +# +# @since 2.0.0 +# +# @else +# @class WriteListenerBase +# @brief WriteListenerBase class +# +# +# @since 2.0.0 +# +# @endif +# +class WriteListenerBase(object): + ## + # @if jp + # @brief 仮想コールバック関数 + # @param self + # @param data 書き込むバイト列のデータ + # @else + # @brief Destructor + # @param self + # @param data 書き込むバイト列のデータ + # @endif + def __call__(self, data): + return OpenRTM_aist.BufferStatus.PRECONDITION_NOT_MET + +## +# @if jp +# @class IsWritableListenerBase +# @brief IsWritableListenerBase クラス +# +# 書き込み確認時リスナのベースクラス +# +# @since 2.0.0 +# +# @else +# @class IsWritableListenerBase +# @brief IsWritableListenerBase class +# +# +# @since 2.0.0 +# +# @endif +# + + +class IsWritableListenerBase(object): + ## + # @if jp + # @brief 仮想コールバック関数 + # @param self + # @param con InPortConnector + # @return True:書き込み可、False:書き込み不可 + # @else + # @brief Destructor + # @param self + # @param con + # @return + # @endif + def __call__(self, con): + return False diff --git a/OpenRTM_aist/InPortProvider.py b/OpenRTM_aist/InPortProvider.py index 6d7946bd..4ff7e679 100644 --- a/OpenRTM_aist/InPortProvider.py +++ b/OpenRTM_aist/InPortProvider.py @@ -1,5 +1,5 @@ #!/usr/bin/env python -# -*- coding: euc-jp -*- +# -*- coding: utf-8 -*- ## # @file InPortProvider.py @@ -19,13 +19,12 @@ import OpenRTM_aist - ## # @if jp # @class InPortProvider -# @brief InPortProvider 饹 +# @brief InPortProvider クラス # -# InPortξݻ뤿Υ饹 +# InPortの情報を保持するためのクラス。 # # @since 0.4.0 # @@ -34,161 +33,155 @@ # @brief InPortProvider class # @endif class InPortProvider(OpenRTM_aist.DataPortStatus): - """ - """ - - - - ## - # @if jp - # @brief 󥹥ȥ饯 - # - # 󥹥ȥ饯 - # - # @param self - # - # @else - # @brief Constructor - # @endif - def __init__(self): - self._properties = [] - self._interfaceType = "" - self._dataflowType = "" - self._subscriptionType = "" - self._rtcout = OpenRTM_aist.Manager.instance().getLogbuf("InPortProvider") - self._connector = None - - ## - # @if jp - # @brief λ - # - # @else - # @brief - # - # - # - # @endif - # - def exit(self): - pass - - ## - # @if jp - # @brief InterfaceProfile - # - # InterfaceProfile롣 - # - # @param self - # @param prop InterfaceProfileץѥƥ - # - # @else - # - # @endif - def publishInterfaceProfile(self, prop): - self._rtcout.RTC_TRACE("publishInterfaceProfile()") - OpenRTM_aist.NVUtil.appendStringValue(prop, "dataport.interface_type", - self._interfaceType) - OpenRTM_aist.NVUtil.append(prop, self._properties) - - ## - # @if jp - # @brief Interface - # - # Interface롣 - # - # @param self - # @param prop Interfaceץѥƥ - # - # @else - # - # @endif - def publishInterface(self, prop): - self._rtcout.RTC_TRACE("publishInterface()") - if not OpenRTM_aist.NVUtil.isStringValue(prop, - "dataport.interface_type", - self._interfaceType): - return False - - OpenRTM_aist.NVUtil.append(prop, self._properties) - return True - - - ## - # @if jp - # @brief 󥿥եפꤹ - # - # 󥿥եפꤹ롣 - # - # @param self - # @param interface_type оݥ󥿥ե - # - # @else - # - # @endif - def setInterfaceType(self, interface_type): - self._rtcout.RTC_TRACE("setInterfaceType(%s)", interface_type) - self._interfaceType = interface_type - - - ## - # @if jp - # @brief ǡեפꤹ - # - # ǡեפꤹ롣 - # - # @param self - # @param dataflow_type оݥǡե - # - # @else - # - # @endif - def setDataFlowType(self, dataflow_type): - self._rtcout.RTC_TRACE("setDataFlowType(%s)", dataflow_type) - self._dataflowType = dataflow_type - - - ## - # @if jp - # @brief ֥ץ󥿥פꤹ - # - # ֥ץ󥿥פꤹ롣 - # - # @param self - # @param subs_type оݥ֥ץ󥿥 - # - # @else - # - # @endif - def setSubscriptionType(self, subs_type): - self._rtcout.RTC_TRACE("setSubscriptionType(%s)", subs_type) - self._subscriptionType = subs_type - - - - def setConnector(self, connector): - self._connector = connector + """ + """ + + ## + # @if jp + # @brief コンストラクタ + # + # コンストラクタ + # + # @param self + # + # @else + # @brief Constructor + # @endif + def __init__(self): + self._properties = [] + self._interfaceType = "" + self._dataflowType = "" + self._subscriptionType = "" + self._rtcout = OpenRTM_aist.Manager.instance().getLogbuf("InPortProvider") + self._connector = None + + ## + # @if jp + # @brief 終了処理 + # + # @else + # @brief + # + # + # + # @endif + # + def exit(self): + pass + + ## + # @if jp + # @brief InterfaceProfile情報を公開する + # + # InterfaceProfile情報を公開する。 + # + # @param self + # @param prop InterfaceProfile情報を受け取るプロパティ + # + # @else + # + # @endif + def publishInterfaceProfile(self, prop): + self._rtcout.RTC_TRACE("publishInterfaceProfile()") + OpenRTM_aist.NVUtil.appendStringValue(prop, "dataport.interface_type", + self._interfaceType) + OpenRTM_aist.NVUtil.append(prop, self._properties) + + ## + # @if jp + # @brief Interface情報を公開する + # + # Interface情報を公開する。 + # + # @param self + # @param prop Interface情報を受け取るプロパティ + # + # @else + # + # @endif + def publishInterface(self, prop): + self._rtcout.RTC_TRACE("publishInterface()") + if not OpenRTM_aist.NVUtil.isStringValue(prop, + "dataport.interface_type", + self._interfaceType): + return False + + OpenRTM_aist.NVUtil.append(prop, self._properties) + return True + + ## + # @if jp + # @brief インタフェースタイプを設定する + # + # インタフェースタイプを設定する。 + # + # @param self + # @param interface_type 設定対象インタフェースタイプ + # + # @else + # + # @endif + + def setInterfaceType(self, interface_type): + self._rtcout.RTC_TRACE("setInterfaceType(%s)", interface_type) + self._interfaceType = interface_type + + ## + # @if jp + # @brief データフロータイプを設定する + # + # データフロータイプを設定する。 + # + # @param self + # @param dataflow_type 設定対象データフロータイプ + # + # @else + # + # @endif + + def setDataFlowType(self, dataflow_type): + self._rtcout.RTC_TRACE("setDataFlowType(%s)", dataflow_type) + self._dataflowType = dataflow_type + + ## + # @if jp + # @brief サブスクリプションタイプを設定する + # + # サブスクリプションタイプを設定する。 + # + # @param self + # @param subs_type 設定対象サブスクリプションタイプ + # + # @else + # + # @endif + + def setSubscriptionType(self, subs_type): + self._rtcout.RTC_TRACE("setSubscriptionType(%s)", subs_type) + self._subscriptionType = subs_type + + def setConnector(self, connector): + self._connector = connector inportproviderfactory = None -class InPortProviderFactory(OpenRTM_aist.Factory,InPortProvider): - def __init__(self): - OpenRTM_aist.Factory.__init__(self) # Call GlobalFactory.Factory() - InPortProvider.__init__(self) - return - - - def instance(): - global inportproviderfactory +class InPortProviderFactory(OpenRTM_aist.Factory, InPortProvider): + def __init__(self): + OpenRTM_aist.Factory.__init__(self) # Call GlobalFactory.Factory() + InPortProvider.__init__(self) + return - if inportproviderfactory is None: - inportproviderfactory = InPortProviderFactory() + def instance(): + global inportproviderfactory - return inportproviderfactory + if inportproviderfactory is None: + inportproviderfactory = InPortProviderFactory() - instance = staticmethod(instance) + return inportproviderfactory + instance = staticmethod(instance) - def __del__(self): - pass + def __del__(self): + pass diff --git a/OpenRTM_aist/InPortPullConnector.py b/OpenRTM_aist/InPortPullConnector.py index 3cad3bbd..389c4556 100644 --- a/OpenRTM_aist/InPortPullConnector.py +++ b/OpenRTM_aist/InPortPullConnector.py @@ -1,5 +1,5 @@ #!/usr/bin/env python -# -*- coding: euc-jp -*- +# -*- coding: utf-8 -*- ## # @file InPortPullConnector.py @@ -16,8 +16,6 @@ # All rights reserved. # -from omniORB import cdrUnmarshal -from omniORB import any import OpenRTM_aist @@ -25,25 +23,25 @@ ## # @if jp # @class InPortPullConnector -# @brief InPortPullConnector 饹 +# @brief InPortPullConnector クラス # -# InPort pull ǡեΤ Connector 饹Υ -# Ȥϡ³ dataflow_type pull ꤵ줿硢 -# InPort ˤäͭ졢OutPortPullConnector Фˤʤäơ -# ǡݡȤ pull Υǡե¸롣Ĥ³Фơ -# ĤΥǡȥ꡼󶡤ͣ Connector б롣 -# Connector ³ UUID ID ˤ̤롣 +# InPort の pull 型データフローのための Connector クラス。このオブ +# ジェクトは、接続時に dataflow_type に pull が指定された場合、 +# InPort によって生成・所有され、OutPortPullConnector と対になって、 +# データポートの pull 型のデータフローを実現する。一つの接続に対して、 +# 一つのデータストリームを提供する唯一の Connector が対応する。 +# Connector は 接続時に生成される UUID 形式の ID により区別される。 # -# InPortPullConnector ϰʲλĤΥ֥Ȥͭ롣 +# InPortPullConnector は以下の三つのオブジェクトを所有し管理する。 # # - InPortConsumer # - Buffer # -# OutPort ˽񤭹ޤ줿ǡ OutPortPullConnector::write() -# Buffer ˽񤭹ޤ롣InPort::read(), -# InPortPullConnector::read() Ϸ̤ȤơOutPortConsumer::get() -# ƤӽФOutPortPullConnector λĥХåեǡɤ߽ -# InPortPullConnector ΤĥХåե˥ǡ񤭹ࡣ +# OutPort に書き込まれたデータは OutPortPullConnector::write() に渡 +# され Buffer に書き込まれる。InPort::read(), +# InPortPullConnector::read() は結果として、OutPortConsumer::get() +# を呼び出し、OutPortPullConnector の持つバッファからデータを読み出 +# し、InPortPullConnector のもつバッファにデータを書き込む。 # # @since 1.0.0 # @@ -77,305 +75,343 @@ # @endif # class InPortPullConnector(OpenRTM_aist.InPortConnector): - """ - """ - - ## - # @if jp - # @brief 󥹥ȥ饯 - # - # InPortPullConnector Υ󥹥ȥ饯ϥ֥˲ - # ˤȤ롣ConnectorInfo ³ޤߡξ˽Х - # ե롣OutPort 󥿡եΥץХ֥ - # ȤؤΥݥ󥿤ꡢͭĤΤǡInPortPullConnector - # OutPortConsumer βǤġƼ磻٥ȤФ륳Х - # 󶡤 ConnectorListeners Ŭڤʥߥ󥰤ǥ - # ХåƤӽФǡХåե⤷ InPortBase 󶡤 - # ϤΥݥ󥿤롣 - # - # @param info ConnectorInfo - # @param consumer OutPortConsumer - # @param listeners ConnectorListeners Υꥹʥ֥ȥꥹ - # @param buffer CdrBufferBase ΥХåե - # - # @else - # @brief Constructor - # - # InPortPullConnector's constructor is given the following - # arguments. According to ConnectorInfo which includes - # connection information, a buffer is created. It is also given - # a pointer to the consumer object for the OutPort interface. - # The owner-ship of the pointer is owned by this - # OutPortPullConnector, it has responsibility to destruct the - # OutPortConsumer. OutPortPullConnector also has - # ConnectorListeners to provide event callback mechanisms, and - # they would be called at the proper timing. If data buffer is - # given by OutPortBase, the pointer to the buffer is also given - # as arguments. - # - # @param info ConnectorInfo - # @param consumer OutPortConsumer - # @param listeners ConnectorListeners type lsitener object list - # @param buffer CdrBufferBase type buffer - # - # @endif - # - # InPortPullConnector(ConnectorInfo info, - # OutPortConsumer* consumer, - # ConnectorListeners& listeners, - # CdrBufferBase* buffer = 0); - def __init__(self, info, consumer, listeners, buffer = None): - OpenRTM_aist.InPortConnector.__init__(self, info, buffer) - self._consumer = consumer - self._listeners = listeners - self._directOutPort = None - self._outPortListeners = None - - - if buffer is None: - self._buffer = self.createBuffer(self._profile) - - if not self._buffer or not self._consumer: - raise - - self._buffer.init(info.properties.getNode("buffer")) - self._consumer.init(info.properties) - self._consumer.setBuffer(self._buffer) - self._consumer.setListener(info, self._listeners) - self.onConnect() - return - - - ## - # @if jp - # @brief ǥȥ饯 - # - # disconnect() ƤФ졢consumer, publisher, buffer Ρ롣 - # - # @else - # - # @brief Destructor - # - # This operation calls disconnect(), which destructs and deletes - # the consumer, the publisher and the buffer. - # - # @endif - # - def __del__(self): - return - - - ## - # @if jp - # @brief read ؿ - # - # OutPortConsumer ǡ롣ɤ߽Ф硢 - # ͤ PORT_OK Ȥʤꡢdata ɤ߽Ф줿ǡǼ롣 - # ʳξˤϡ顼ͤȤ BUFFER_EMPTY, TIMEOUT, - # PRECONDITION_NOT_MET, PORT_ERROR ֤롣 - # - # @return PORT_OK ェλ - # BUFFER_EMPTY Хåե϶Ǥ - # TIMEOUT ॢȤ - # PRECONDITION_NOT_MET ʤ - # PORT_ERROR ¾Υ顼 - # - # @else - # @brief Destructor - # - # This function get data from OutPortConsumer. If data is read - # properly, this function will return PORT_OK return code. Except - # normal return, BUFFER_EMPTY, TIMEOUT, PRECONDITION_NOT_MET and - # PORT_ERROR will be returned as error codes. - # - # @return PORT_OK Normal return - # BUFFER_EMPTY Buffer empty - # TIMEOUT Timeout - # PRECONDITION_NOT_MET Preconditin not met - # PORT_ERROR Other error - # - # @endif - # - # virtual ReturnCode read(cdrMemoryStream& data); - def read(self, data): - self._rtcout.RTC_TRACE("InPortPullConnector.read()") - - if self._directOutPort is not None: - if self._directOutPort.isEmpty(): - self._listeners.connector_[OpenRTM_aist.ConnectorListenerType.ON_BUFFER_EMPTY].notify(self._profile) - self._outPortListeners.connector_[OpenRTM_aist.ConnectorListenerType.ON_SENDER_EMPTY].notify(self._profile) - self._rtcout.RTC_TRACE("ON_BUFFER_EMPTY(InPort,OutPort), ") - self._rtcout.RTC_TRACE("ON_SENDER_EMPTY(InPort,OutPort) ") - self._rtcout.RTC_TRACE("callback called in direct mode.") - - self._directOutPort.read(data) - #self._outPortListeners.connectorData_[OpenRTM_aist.ConnectorDataListenerType.ON_BUFFER_READ].notify(self._profile, data[0]) - self._rtcout.RTC_TRACE("ON_BUFFER_READ(OutPort), ") - self._rtcout.RTC_TRACE("callback called in direct mode.") - #self._outPortListeners.connectorData_[OpenRTM_aist.ConnectorDataListenerType.ON_SEND].notify(self._profile, data[0]) - self._rtcout.RTC_TRACE("ON_SEND(OutPort), ") - self._rtcout.RTC_TRACE("callback called in direct mode.") - #self._listeners.connectorData_[OpenRTM_aist.ConnectorDataListenerType.ON_RECEIVED].notify(self._profile, data[0]) - self._rtcout.RTC_TRACE("ON_RECEIVED(InPort), ") - self._rtcout.RTC_TRACE("callback called in direct mode.") - #self._listeners.connectorData_[OpenRTM_aist.ConnectorDataListenerType.ON_SEND].notify(self._profile, data[0]) - self._rtcout.RTC_TRACE("ON_BUFFER_WRITE(InPort), ") - self._rtcout.RTC_TRACE("callback called in direct mode.") - return self.PORT_OK - - - - if not self._consumer: - return self.PORT_ERROR - - - - cdr_data = [None] - ret = self._consumer.get(cdr_data) - - if ret == self.PORT_OK: - # CDR -> (conversion) -> data - if self._endian is not None: - data[0] = cdrUnmarshal(any.to_any(data[0]).typecode(),cdr_data[0],self._endian) - - else: - self._rtcout.RTC_ERROR("unknown endian from connector") - return OpenRTM_aist.BufferStatus.PRECONDITION_NOT_MET - - return ret - - - ## - # @if jp - # @brief ³ؿ - # - # Connector ݻƤ³ - # - # @else - # @brief Disconnect connection - # - # This operation disconnect this connection - # - # @endif - # - # virtual ReturnCode disconnect(); - def disconnect(self): - self._rtcout.RTC_TRACE("disconnect()") - self.onDisconnect() - # delete consumer - if self._consumer: - OpenRTM_aist.OutPortConsumerFactory.instance().deleteObject(self._consumer) - self._consumer = 0 - - return self.PORT_OK - - ## - # @if jp - # @brief ƥֲ - # - # Υͥ򥢥ƥֲ - # - # @else - # - # @brief Connector activation - # - # This operation activates this connector - # - # @endif - # - # virtual void activate(){}; // do nothing - def activate(self): # do nothing - pass - - ## - # @if jp - # @brief 󥢥ƥֲ - # - # Υͥ󥢥ƥֲ - # - # @else - # - # @brief Connector deactivation - # - # This operation deactivates this connector - # - # @endif - # - # virtual void deactivate(){}; // do nothing - def deactivate(self): # do nothing - pass - - ## - # @if jp - # @brief Buffer - # - # Ϳ줿³˴ŤХåե롣 - # - # @param info ³ - # @return ХåեؤΥݥ - # - # @else - # @brief create buffer - # - # This function creates a buffer based on given information. - # - # @param info Connector information - # @return The poitner to the buffer - # - # @endif - # - # CdrBufferBase* createBuffer(Profile& profile); - def createBuffer(self, profile): - buf_type = profile.properties.getProperty("buffer_type","ring_buffer") - return OpenRTM_aist.CdrBufferFactory.instance().createObject(buf_type) - - ## - # @if jp - # @brief ³Ω˥ХåƤ - # @else - # @brief Invoke callback when connection is established - # @endif - # void onConnect() - def onConnect(self): - if self._listeners and self._profile: - self._listeners.connector_[OpenRTM_aist.ConnectorListenerType.ON_CONNECT].notify(self._profile) - return - - ## - # @if jp - # @brief ³ǻ˥ХåƤ - # @else - # @brief Invoke callback when connection is destroied - # @endif - # void onDisconnect() - def onDisconnect(self): - if self._listeners and self._profile: - self._listeners.connector_[OpenRTM_aist.ConnectorListenerType.ON_DISCONNECT].notify(self._profile) - return - - - - ## - # @if jp - # @brief ǡ쥯Ȥ˽񤭹िOutPortΥХȤꤹ - # - # @param self - # @param directOutPort OutPortΥХ - # @return True: False: ѤߤΤἺ - # @else - # @brief - # - # @param self - # @param directOutPort - # @return - # @endif - # - # bool setOutPort(setOutPort* directOutPort); - def setOutPort(self, directOutPort): - if self._directOutPort is not None: - return False - self._directOutPort = directOutPort - self._outPortListeners = self._directOutPort._listeners - return True - - + """ + """ + + ## + # @if jp + # @brief コンストラクタ + # + # InPortPullConnector のコンストラクタはオブジェクト生成時に下記 + # を引数にとる。ConnectorInfo は接続情報を含み、この情報に従いバッ + # ファ等を生成する。OutPort インターフェースのプロバイダオブジェク + # トへのポインタを取り、所有権を持つので、InPortPullConnector は + # OutPortConsumer の解体責任を持つ。各種イベントに対するコールバッ + # ク機構を提供する ConnectorListeners を持ち、適切なタイミングでコー + # ルバックを呼び出す。データバッファがもし InPortBase から提供さ + # れる場合はそのポインタを取る。 + # + # @param info ConnectorInfo + # @param consumer OutPortConsumer + # @param listeners ConnectorListeners 型のリスナオブジェクトリスト + # @param buffer CdrBufferBase 型のバッファ + # + # @else + # @brief Constructor + # + # InPortPullConnector's constructor is given the following + # arguments. According to ConnectorInfo which includes + # connection information, a buffer is created. It is also given + # a pointer to the consumer object for the OutPort interface. + # The owner-ship of the pointer is owned by this + # OutPortPullConnector, it has responsibility to destruct the + # OutPortConsumer. OutPortPullConnector also has + # ConnectorListeners to provide event callback mechanisms, and + # they would be called at the proper timing. If data buffer is + # given by OutPortBase, the pointer to the buffer is also given + # as arguments. + # + # @param info ConnectorInfo + # @param consumer OutPortConsumer + # @param listeners ConnectorListeners type lsitener object list + # @param buffer CdrBufferBase type buffer + # + # @endif + # + # InPortPullConnector(ConnectorInfo info, + # OutPortConsumer* consumer, + # ConnectorListeners& listeners, + # CdrBufferBase* buffer = 0); + def __init__(self, info, consumer, listeners, buffer=None): + OpenRTM_aist.InPortConnector.__init__(self, info, buffer) + self._consumer = consumer + self._listeners = listeners + self._directOutPort = None + self._outPortListeners = None + + if buffer is None: + self._buffer = self.createBuffer(self._profile) + + if not self._buffer or not self._consumer: + raise + + self._buffer.init(info.properties.getNode("buffer")) + self._consumer.init(info.properties) + self._consumer.setBuffer(self._buffer) + self._consumer.setListener(info, self._listeners) + self.onConnect() + + self._marshaling_type = info.properties.getProperty( + "marshaling_type", "cdr") + self._marshaling_type = self._marshaling_type.strip() + + self._serializer = None + + return + + ## + # @if jp + # @brief デストラクタ + # + # disconnect() が呼ばれ、consumer, publisher, buffer が解体・削除される。 + # + # @else + # + # @brief Destructor + # + # This operation calls disconnect(), which destructs and deletes + # the consumer, the publisher and the buffer. + # + # @endif + # + + def __del__(self): + return + + ## + # @if jp + # @brief read 関数 + # + # OutPortConsumer からデータを取得する。正常に読み出せた場合、戻り + # 値は PORT_OK となり、data に読み出されたデータが格納される。それ + # 以外の場合には、エラー値として BUFFER_EMPTY, TIMEOUT, + # PRECONDITION_NOT_MET, UNKNOWN_ERROR, PORT_ERROR が返される。 + # + # @return PORT_OK 正常終了 + # BUFFER_EMPTY バッファは空である + # TIMEOUT タイムアウトした + # PRECONDITION_NOT_MET 事前条件を満たさない + # UNKNOWN_ERROR 不明のエラー + # PORT_ERROR その他のエラー + # + # @else + # @brief Destructor + # + # This function get data from OutPortConsumer. If data is read + # properly, this function will return PORT_OK return code. Except + # normal return, BUFFER_EMPTY, TIMEOUT, PRECONDITION_NOT_MET, + # UNKNOWN_ERROR and PORT_ERROR will be returned as error codes. + # + # @return PORT_OK Normal return + # BUFFER_EMPTY Buffer empty + # TIMEOUT Timeout + # PRECONDITION_NOT_MET Preconditin not met + # UNKNOWN_ERROR Unknown errot + # PORT_ERROR Other error + # + # @endif + # + # virtual ReturnCode read(cdrMemoryStream& data); + + def read(self, data=None): + self._rtcout.RTC_TRACE("InPortPullConnector.read()") + + if self._directOutPort is not None: + if self._directOutPort.isEmpty(): + self._listeners.notify( + OpenRTM_aist.ConnectorListenerType.ON_BUFFER_EMPTY, self._profile) + self._outPortListeners.notify( + OpenRTM_aist.ConnectorListenerType.ON_SENDER_EMPTY, self._profile) + self._rtcout.RTC_TRACE("ON_BUFFER_EMPTY(InPort,OutPort), ") + self._rtcout.RTC_TRACE("ON_SENDER_EMPTY(InPort,OutPort) ") + self._rtcout.RTC_TRACE("callback called in direct mode.") + + data = self._directOutPort.read() + #self._outPortListeners.notifyData(OpenRTM_aist.ConnectorDataListenerType.ON_BUFFER_READ, self._profile, data) + self._rtcout.RTC_TRACE("ON_BUFFER_READ(OutPort), ") + self._rtcout.RTC_TRACE("callback called in direct mode.") + #self._outPortListeners.notifyData(OpenRTM_aist.ConnectorDataListenerType.ON_SEND, self._profile, data) + self._rtcout.RTC_TRACE("ON_SEND(OutPort), ") + self._rtcout.RTC_TRACE("callback called in direct mode.") + #self._listeners.notifyData(OpenRTM_aist.ConnectorDataListenerType.ON_RECEIVED, self._profile, data) + self._rtcout.RTC_TRACE("ON_RECEIVED(InPort), ") + self._rtcout.RTC_TRACE("callback called in direct mode.") + #self._listeners.notifyData(OpenRTM_aist.ConnectorDataListenerType.ON_SEND, self._profile, data) + self._rtcout.RTC_TRACE("ON_BUFFER_WRITE(InPort), ") + self._rtcout.RTC_TRACE("callback called in direct mode.") + return self.PORT_OK, data + + if not self._consumer: + return self.PORT_ERROR, data + + datatype = self._dataType + if datatype is None: + if data is None: + self._rtcout.RTC_ERROR("invalid data type") + return self.UNKNOWN_ERROR, data + datatype = data + + ret, cdr_data = self._consumer.get() + + if ret == self.PORT_OK: + + if self._serializer is None: + self._rtcout.RTC_ERROR("serializer creation failure.") + return self.UNKNOWN_ERROR, data + + self._serializer.isLittleEndian(self._endian) + ser_ret, data = self._serializer.deserialize(cdr_data, datatype) + + if ser_ret == OpenRTM_aist.ByteDataStreamBase.SERIALIZE_NOT_SUPPORT_ENDIAN: + self._rtcout.RTC_ERROR("unknown endian from connector") + return self.UNKNOWN_ERROR, data + elif ser_ret == OpenRTM_aist.ByteDataStreamBase.SERIALIZE_ERROR: + self._rtcout.RTC_ERROR("unknown error") + return self.UNKNOWN_ERROR, data + elif ser_ret == OpenRTM_aist.ByteDataStreamBase.SERIALIZE_NOTFOUND: + self._rtcout.RTC_ERROR("unknown serializer from connector") + return self.UNKNOWN_ERROR, data + + return ret, data + + ## + # @if jp + # @brief 接続解除関数 + # + # Connector が保持している接続を解除する + # + # @else + # @brief Disconnect connection + # + # This operation disconnect this connection + # + # @endif + # + # virtual ReturnCode disconnect(); + + def disconnect(self): + self._rtcout.RTC_TRACE("disconnect()") + self.onDisconnect() + + self._consumer = None + self._serializer = None + + return self.PORT_OK + + ## + # @if jp + # @brief アクティブ化 + # + # このコネクタをアクティブ化する + # + # @else + # + # @brief Connector activation + # + # This operation activates this connector + # + # @endif + # + # virtual void activate(){}; // do nothing + def activate(self): # do nothing + pass + + ## + # @if jp + # @brief 非アクティブ化 + # + # このコネクタを非アクティブ化する + # + # @else + # + # @brief Connector deactivation + # + # This operation deactivates this connector + # + # @endif + # + # virtual void deactivate(){}; // do nothing + def deactivate(self): # do nothing + pass + + ## + # @if jp + # @brief Bufferの生成 + # + # 与えられた接続情報に基づきバッファを生成する。 + # + # @param info 接続情報 + # @return バッファへのポインタ + # + # @else + # @brief create buffer + # + # This function creates a buffer based on given information. + # + # @param info Connector information + # @return The poitner to the buffer + # + # @endif + # + # CdrBufferBase* createBuffer(Profile& profile); + def createBuffer(self, profile): + buf_type = profile.properties.getProperty("buffer_type", "ring_buffer") + return OpenRTM_aist.CdrBufferFactory.instance().createObject(buf_type) + + ## + # @if jp + # @brief 接続確立時にコールバックを呼ぶ + # @else + # @brief Invoke callback when connection is established + # @endif + # void onConnect() + def onConnect(self): + if self._listeners and self._profile: + self._listeners.notify( + OpenRTM_aist.ConnectorListenerType.ON_CONNECT, self._profile) + return + + ## + # @if jp + # @brief 接続切断時にコールバックを呼ぶ + # @else + # @brief Invoke callback when connection is destroied + # @endif + # void onDisconnect() + def onDisconnect(self): + if self._listeners and self._profile: + self._listeners.notify( + OpenRTM_aist.ConnectorListenerType.ON_DISCONNECT, self._profile) + return + + ## + # @if jp + # @brief データをダイレクトに書き込むためのOutPortのサーバントを設定する + # + # @param self + # @param directOutPort OutPortのサーバント + # @return True: 設定に成功 False: 既に設定済みのため失敗 + # @else + # @brief + # + # @param self + # @param directOutPort + # @return + # @endif + # + # bool setOutPort(setOutPort* directOutPort); + + def setOutPort(self, directOutPort): + if self._directOutPort is not None: + return False + self._directOutPort = directOutPort + self._outPortListeners = self._directOutPort._listeners + return True + + ## + # @if jp + # @brief コンシューマのインターフェースの登録を取り消す + # @param prop コネクタプロファイルのプロパティ + # @else + # @brief + # @param prop + # @endif + + def unsubscribeInterface(self, prop): + if self._consumer: + self._consumer.unsubscribeInterface(prop) + + + def setDataType(self, data): + OpenRTM_aist.InPortConnector.setDataType(self, data) + self._serializer = OpenRTM_aist.SerializerFactories.instance().createSerializer(self._marshaling_type, data) \ No newline at end of file diff --git a/OpenRTM_aist/InPortPushConnector.py b/OpenRTM_aist/InPortPushConnector.py index a8de20bc..639f46fd 100644 --- a/OpenRTM_aist/InPortPushConnector.py +++ b/OpenRTM_aist/InPortPushConnector.py @@ -1,5 +1,5 @@ #!/usr/bin/env python -# -*- coding: euc-jp -*- +# -*- coding: utf-8 -*- ## # @@ -18,9 +18,6 @@ # -from omniORB import cdrUnmarshal -from omniORB import any - import OpenRTM_aist import threading @@ -28,23 +25,23 @@ ## # @if jp # @class InPortPushConnector -# @brief InPortPushConnector 饹 +# @brief InPortPushConnector クラス # -# InPort push ǡեΤ Connector 饹Υ -# Ȥϡ³ dataflow_type push ꤵ줿硢 -# InPort ˤäͭ졢OutPortPushConnector Фˤʤäơ -# ǡݡȤ push Υǡե¸롣Ĥ³Фơ -# ĤΥǡȥ꡼󶡤ͣ Connector б롣 -# Connector ³ UUID ID ˤ̤롣 +# InPort の push 型データフローのための Connector クラス。このオブ +# ジェクトは、接続時に dataflow_type に push が指定された場合、 +# InPort によって生成・所有され、OutPortPushConnector と対になって、 +# データポートの push 型のデータフローを実現する。一つの接続に対して、 +# 一つのデータストリームを提供する唯一の Connector が対応する。 +# Connector は 接続時に生成される UUID 形式の ID により区別される。 # -# InPortPushConnector ϰʲλĤΥ֥Ȥͭ롣 +# InPortPushConnector は以下の三つのオブジェクトを所有し管理する。 # # - InPortProvider # - Buffer # -# OutPort ˽񤭹ޤ줿ǡϡOutPortConnector ˤä -# InPortProvider::put() ˥ǡϤ롣񤭹ޤ줿ǡ -# Connector Buffer ˥ǡ񤭹ޤ롣 +# OutPort に書き込まれたデータは、OutPortConnector によって +# InPortProvider::put() にデータが渡される。書き込まれたデータは +# Connector 内で Buffer にデータが書き込まれる。 # # @since 1.0.0 # @@ -75,413 +72,459 @@ # @endif # class InPortPushConnector(OpenRTM_aist.InPortConnector): - """ - """ - - ## - # @if jp - # @brief 󥹥ȥ饯 - # - # InPortPushConnector Υ󥹥ȥ饯ϥ֥˲ - # ˤȤ롣ConnectorInfo ³ޤߡξ˽Хåե - # 롣InPort 󥿡եΥץХ֥Ȥ - # Υݥ󥿤ꡢͭĤΤǡInPortPushConnector - # InPortProvider βǤġƼ磻٥ȤФ륳Х - # 󶡤 ConnectorListeners Ŭڤʥߥ󥰤ǥ - # ХåƤӽФǡХåե⤷ InPortBase 󶡤 - # ϤΥݥ󥿤롣 - # - # @param info ConnectorInfo - # @param provider InPortProvider - # @param listeners ConnectorListeners Υꥹʥ֥ȥꥹ - # @param buffer CdrBufferBase ΥХåե - # - # @elsek - # @brief Constructor - # - # InPortPushConnector's constructor is given the following - # arguments. According to ConnectorInfo which includes - # connection information, a buffer is created. - # It is also given a pointer to the provider object for the - # InPort interface. The owner-ship of the pointer is owned by - # this InPortPushConnector, it has responsibility to destruct - # the InPortProvider. InPortPushConnector also has - # ConnectorListeners to provide event callback mechanisms, and - # they would be called at the proper timing. If data buffer is - # given by InPortBase, the pointer to the buffer is also given - # as arguments. - # - # @param info ConnectorInfo - # @param provider InPortProvider - # @param listeners ConnectorListeners type lsitener object list - # @param buffer CdrBufferBase type buffer - # - # @endif - # - # InPortPushConnector(ConnectorInfo info, InPortProvider* provider, - # ConnectorListeners listeners, CdrBufferBase* buffer = 0); - def __init__(self, info, provider, listeners, buffer = None): - OpenRTM_aist.InPortConnector.__init__(self, info, buffer) - self._provider = provider - self._listeners = listeners - - if buffer: - self._deleteBuffer = True - else: - self._deleteBuffer = False - - - if self._buffer is None: - self._buffer = self.createBuffer(info) - - - if self._buffer is None or not self._provider: - raise - - self._buffer.init(info.properties.getNode("buffer")) - self._provider.init(info.properties) - self._provider.setBuffer(self._buffer) - self._provider.setListener(info, self._listeners) - self.onConnect() - - - self._sync_readwrite = False - if OpenRTM_aist.toBool(info.properties.getProperty("sync_readwrite"),"YES","NO",False): - self._sync_readwrite = True - - - - - - - self._writecompleted_worker = InPortPushConnector.WorkerThreadCtrl() - self._readcompleted_worker = InPortPushConnector.WorkerThreadCtrl() - self._readready_worker = InPortPushConnector.WorkerThreadCtrl() - return - - - ## - # @if jp - # @brief ǥȥ饯 - # - # disconnect() ƤФ졢consumer, publisher, buffer Ρ롣 - # - # @else - # - # @brief Destructor - # - # This operation calls disconnect(), which destructs and deletes - # the consumer, the publisher and the buffer. - # - # @endif - # - def __del__(self): - return - - - ## - # @if jp - # @brief ǡɤ߽Ф - # - # Хåեǡɤ߽Фɤ߽Ф硢ͤ - # PORT_OK Ȥʤꡢdata ɤ߽Ф줿ǡǼ롣ʳ - # ξˤϡ顼ͤȤ BUFFER_EMPTY, TIMEOUT, - # PRECONDITION_NOT_MET, PORT_ERROR ֤롣 - # - # @return PORT_OK ェλ - # BUFFER_EMPTY Хåե϶Ǥ - # TIMEOUT ॢȤ - # PRECONDITION_NOT_MET ʤ - # PORT_ERROR ¾Υ顼 - # - # @else - # - # @brief Reading data - # - # This function reads data from the buffer. If data is read - # properly, this function will return PORT_OK return code. Except - # normal return, BUFFER_EMPTY, TIMEOUT, PRECONDITION_NOT_MET and - # PORT_ERROR will be returned as error codes. - # - # @return PORT_OK Normal return - # BUFFER_EMPTY Buffer empty - # TIMEOUT Timeout - # PRECONDITION_NOT_MET Preconditin not met - # PORT_ERROR Other error - # - # @endif - # - # virtual ReturnCode read(cdrMemoryStream& data); - def read(self, data): - self._rtcout.RTC_TRACE("read()") + """ + """ + + ## + # @if jp + # @brief コンストラクタ + # + # InPortPushConnector のコンストラクタはオブジェクト生成時に下記を + # 引数にとる。ConnectorInfo は接続情報を含み、この情報に従いバッファ + # 等を生成する。InPort インターフェースのプロバイダオブジェクトへ + # のポインタを取り、所有権を持つので、InPortPushConnector は + # InPortProvider の解体責任を持つ。各種イベントに対するコールバッ + # ク機構を提供する ConnectorListeners を持ち、適切なタイミングでコー + # ルバックを呼び出す。データバッファがもし InPortBase から提供され + # る場合はそのポインタを取る。 + # + # @param info ConnectorInfo + # @param provider InPortProvider + # @param listeners ConnectorListeners 型のリスナオブジェクトリスト + # @param buffer CdrBufferBase 型のバッファ + # + # @elsek + # @brief Constructor + # + # InPortPushConnector's constructor is given the following + # arguments. According to ConnectorInfo which includes + # connection information, a buffer is created. + # It is also given a pointer to the provider object for the + # InPort interface. The owner-ship of the pointer is owned by + # this InPortPushConnector, it has responsibility to destruct + # the InPortProvider. InPortPushConnector also has + # ConnectorListeners to provide event callback mechanisms, and + # they would be called at the proper timing. If data buffer is + # given by InPortBase, the pointer to the buffer is also given + # as arguments. + # + # @param info ConnectorInfo + # @param provider InPortProvider + # @param listeners ConnectorListeners type lsitener object list + # @param buffer CdrBufferBase type buffer + # + # @endif + # + # InPortPushConnector(ConnectorInfo info, InPortProvider* provider, + # ConnectorListeners listeners, CdrBufferBase* buffer = 0); + def __init__(self, info, provider, listeners, buffer=None): + OpenRTM_aist.InPortConnector.__init__(self, info, buffer) + self._provider = provider + self._listeners = listeners + + if buffer: + self._deleteBuffer = True + else: + self._deleteBuffer = False + + if self._buffer is None: + self._buffer = self.createBuffer(info) + + if self._buffer is None or not self._provider: + raise + + self._buffer.init(info.properties.getNode("buffer")) + self._provider.init(info.properties) + self._provider.setBuffer(self._buffer) + self._provider.setListener(info, self._listeners) + self.onConnect() + + self._sync_readwrite = False + if OpenRTM_aist.toBool(info.properties.getProperty( + "sync_readwrite"), "YES", "NO", False): + self._sync_readwrite = True + + self._writecompleted_worker = InPortPushConnector.WorkerThreadCtrl() + self._readcompleted_worker = InPortPushConnector.WorkerThreadCtrl() + self._readready_worker = InPortPushConnector.WorkerThreadCtrl() + + self._marshaling_type = info.properties.getProperty( + "marshaling_type", "cdr") + self._marshaling_type = self._marshaling_type.strip() + + self._serializer = None + + return + + ## + # @if jp + # @brief デストラクタ + # + # disconnect() が呼ばれ、consumer, publisher, buffer が解体・削除される。 + # + # @else + # + # @brief Destructor + # + # This operation calls disconnect(), which destructs and deletes + # the consumer, the publisher and the buffer. + # + # @endif + # + + def __del__(self): + return + + ## + # @if jp + # @brief バッファからデータを読み出す。 + # read関数と違い、アンマーシャリングを実行しない + # + # @param self + # @return リターンコード + # + # @brief + # + # @param self + # @return + # + # @endif + # + def readBuff(self): + self._rtcout.RTC_TRACE("readBuff()") + ## + # buffer returns + # BUFFER_OK + # BUFFER_EMPTY + # TIMEOUT + # PRECONDITION_NOT_MET + # + if not self._buffer: + return self.PRECONDITION_NOT_MET, None + + if self._sync_readwrite: + self._readcompleted_worker._completed = False + + self._readready_worker._completed = True + self._readready_worker._cond.acquire() + self._readready_worker._cond.notify() + self._readready_worker._cond.release() + + self._writecompleted_worker._cond.acquire() + while not self._writecompleted_worker._completed: + self._writecompleted_worker._cond.wait() + self._writecompleted_worker._cond.release() + + ret, cdr = self._buffer.read() + + if self._sync_readwrite: + self._readcompleted_worker._completed = True + self._readcompleted_worker._cond.acquire() + self._readcompleted_worker._cond.notify() + self._readcompleted_worker._cond.release() + + self._readready_worker._completed = False + + if ret == OpenRTM_aist.BufferStatus.BUFFER_OK: + return self.PORT_OK, cdr + + if ret == OpenRTM_aist.BufferStatus.BUFFER_EMPTY: + cdr = self.onBufferEmpty(cdr) + return self.BUFFER_EMPTY, cdr + + elif ret == OpenRTM_aist.BufferStatus.TIMEOUT: + cdr = self.onBufferReadTimeout(cdr) + return self.BUFFER_TIMEOUT, cdr + + elif ret == OpenRTM_aist.BufferStatus.PRECONDITION_NOT_MET: + return self.PRECONDITION_NOT_MET, cdr + + return self.PORT_ERROR, cdr + + ## + # @if jp + # @brief データの読み出し + # + # バッファからデータを読み出す。正常に読み出せた場合、戻り値は + # PORT_OK となり、data に読み出されたデータが格納される。それ以外 + # の場合には、エラー値として BUFFER_EMPTY, TIMEOUT, + # PRECONDITION_NOT_MET, UNKNOWN_ERROR, PORT_ERROR が返される。 + # + # @return PORT_OK 正常終了 + # BUFFER_EMPTY バッファは空である + # TIMEOUT タイムアウトした + # PRECONDITION_NOT_MET 事前条件を満たさない + # UNKNOWN_ERROR 不明のエラー + # PORT_ERROR その他のエラー + # + # @else + # + # @brief Reading data + # + # This function reads data from the buffer. If data is read + # properly, this function will return PORT_OK return code. Except + # normal return, BUFFER_EMPTY, TIMEOUT, PRECONDITION_NOT_MET, + # UNKNOWN_ERROR and PORT_ERROR will be returned as error codes. + # + # @return PORT_OK Normal return + # BUFFER_EMPTY Buffer empty + # TIMEOUT Timeout + # PRECONDITION_NOT_MET Preconditin not met + # UNKNOWN_ERROR Unknown errot + # PORT_ERROR Other error + # + # @endif + # + # virtual ReturnCode read(cdrMemoryStream& data); + def read(self, data=None): + self._rtcout.RTC_TRACE("read()") + + datatype = self._dataType + if datatype is None: + if data is None: + self._rtcout.RTC_ERROR("invalid data type") + return self.UNKNOWN_ERROR, data + datatype = data + + ret, cdr = self.readBuff() + + if ret != self.PORT_OK: + return ret, data + else: + cdr = self.onBufferRead(cdr) + if self._serializer is None: + self._rtcout.RTC_ERROR("serializer creation failure.") + return self.UNKNOWN_ERROR, data + self._serializer.isLittleEndian(self._endian) + ser_ret, _data = self._serializer.deserialize(cdr, datatype) + + if ser_ret == OpenRTM_aist.ByteDataStreamBase.SERIALIZE_OK: + data = _data + return self.PORT_OK, data + elif ser_ret == OpenRTM_aist.ByteDataStreamBase.SERIALIZE_NOT_SUPPORT_ENDIAN: + self._rtcout.RTC_ERROR("unknown endian from connector") + return self.UNKNOWN_ERROR, data + elif ser_ret == OpenRTM_aist.ByteDataStreamBase.SERIALIZE_ERROR: + self._rtcout.RTC_ERROR("unknown error") + return self.UNKNOWN_ERROR, data + elif ser_ret == OpenRTM_aist.ByteDataStreamBase.SERIALIZE_NOTFOUND: + self._rtcout.RTC_ERROR("unknown serializer from connector") + return self.UNKNOWN_ERROR, data + + return self.PORT_ERROR, data + + ## + # @if jp + # @brief 接続解除 + # + # consumer, publisher, buffer が解体・削除される。 + # + # @return PORT_OK + # + # @else + # + # @brief disconnect + # + # This operation destruct and delete the consumer, the publisher + # and the buffer. + # + # @return PORT_OK + # + # @endif + # + # virtual ReturnCode disconnect(); + + def disconnect(self): + self._rtcout.RTC_TRACE("disconnect()") + self.onDisconnect() + # delete consumer + if self._provider: + cfactory = OpenRTM_aist.InPortProviderFactory.instance() + + self._provider.exit() + + self._provider = None + + # delete buffer + if self._buffer and self._deleteBuffer == True: + bfactory = OpenRTM_aist.CdrBufferFactory.instance() + + self._buffer = None + + self._serializer = None + + return self.PORT_OK + + ## + # @if jp + # @brief アクティブ化 + # + # このコネクタをアクティブ化する + # + # @else + # + # @brief Connector activation + # + # This operation activates this connector + # + # @endif + # + # virtual void activate(){}; // do nothing + def activate(self): # do nothing + pass + + ## + # @if jp + # @brief 非アクティブ化 + # + # このコネクタを非アクティブ化する + # + # @else + # + # @brief Connector deactivation + # + # This operation deactivates this connector + # + # @endif + # + # virtual void deactivate(){}; // do nothing + def deactivate(self): # do nothing + pass + + ## + # @if jp + # @brief Bufferの生成 + # + # 与えられた接続情報に基づきバッファを生成する。 + # + # @param info 接続情報 + # @return バッファへのポインタ + # + # @else + # @brief create buffer + # + # This function creates a buffer based on given information. + # + # @param info Connector information + # @return The poitner to the buffer + # + # @endif + # + # virtual CdrBufferBase* createBuffer(Profile& profile); + + def createBuffer(self, profile): + buf_type = profile.properties.getProperty("buffer_type", "ring_buffer") + return OpenRTM_aist.CdrBufferFactory.instance().createObject(buf_type) + + ## + # @if jp + # @brief データの書き出し + # + # バッファにデータを書き出す。正常に書き出せた場合、戻り値は + # BUFFER_OK となる。それ以外の場合には、エラー値として BUFFER_FULL,TIMEOUT + # PRECONDITION_NOT_MET, BUFFER_ERROR が返される。 + # + # @return BUFFER_OK 正常終了 + # BUFFER_FULL バッファはいっぱいである + # TIMEOUT タイムアウトした + # PRECONDITION_NOT_MET 事前条件を満たさない + # BUFFER_ERROR その他のエラー + # + # @else + # + # @brief Reading data + # + # This function write data to the buffer. If data is write + # properly, this function will return BUFFER_OK return code. Except + # normal return, BUFFER_FULL, TIMEOUT, PRECONDITION_NOT_MET and + # BUFFER_ERROR will be returned as error codes. + # + # @return BUFFER_OK Normal return + # BUFFER_FULL Buffer full + # TIMEOUT Timeout + # PRECONDITION_NOT_MET Preconditin not met + # BUFFER_ERROR Other error + # + # @endif + # + # ReturnCode write(const OpenRTM::CdrData& data); + + def write(self, data): + if self._sync_readwrite: + self._readready_worker._cond.acquire() + while not self._readready_worker._completed: + self._readready_worker._cond.wait() + self._readready_worker._cond.release() + + ret = self._buffer.write(data) + + if self._sync_readwrite: + self._writecompleted_worker._completed = True + self._writecompleted_worker._cond.acquire() + self._writecompleted_worker._cond.notify() + self._writecompleted_worker._cond.release() + + self._readcompleted_worker._cond.acquire() + while not self._readcompleted_worker._completed: + self._readcompleted_worker._cond.wait() + self._readcompleted_worker._cond.release() + + self._writecompleted_worker._completed = False + + return ret + + ## + # @if jp + # @brief 接続確立時にコールバックを呼ぶ + # @else + # @brief Invoke callback when connection is established + # @endif + # void onConnect() + + def onConnect(self): + if self._listeners and self._profile: + self._listeners.notify( + OpenRTM_aist.ConnectorListenerType.ON_CONNECT, self._profile) + return ## - # buffer returns - # BUFFER_OK - # BUFFER_EMPTY - # TIMEOUT - # PRECONDITION_NOT_MET - # - if not self._buffer: - return self.PRECONDITION_NOT_MET - - cdr = [""] - - if self._sync_readwrite: - self._readcompleted_worker._completed = False - - self._readready_worker._completed = True - self._readready_worker._cond.acquire() - self._readready_worker._cond.notify() - self._readready_worker._cond.release() - - self._writecompleted_worker._cond.acquire() - while not self._writecompleted_worker._completed: - self._writecompleted_worker._cond.wait() - self._writecompleted_worker._cond.release() - - ret = self._buffer.read(cdr) - - if self._sync_readwrite: - self._readcompleted_worker._completed = True - self._readcompleted_worker._cond.acquire() - self._readcompleted_worker._cond.notify() - self._readcompleted_worker._cond.release() - - self._readready_worker._completed = False - - if not self._dataType: - return self.PRECONDITION_NOT_MET - if self._endian is not None: - if ret == OpenRTM_aist.BufferStatus.BUFFER_OK: - _data = cdrUnmarshal(any.to_any(self._dataType).typecode(),cdr[0],self._endian) - if type(data) == list: - data[0] = _data - else: - self._rtcout.RTC_ERROR("unknown endian from connector") - return self.PRECONDITION_NOT_MET - - - - if ret == OpenRTM_aist.BufferStatus.BUFFER_OK: - self.onBufferRead(cdr[0]) - return self.PORT_OK - - elif ret == OpenRTM_aist.BufferStatus.BUFFER_EMPTY: - self.onBufferEmpty(cdr[0]) - return self.BUFFER_EMPTY - - elif ret == OpenRTM_aist.BufferStatus.TIMEOUT: - self.onBufferReadTimeout(cdr[0]) - return self.BUFFER_TIMEOUT - - elif ret == OpenRTM_aist.BufferStatus.PRECONDITION_NOT_MET: - return self.PRECONDITION_NOT_MET - - return self.PORT_ERROR - - - ## - # @if jp - # @brief ³ - # - # consumer, publisher, buffer Ρ롣 - # - # @return PORT_OK - # - # @else - # - # @brief disconnect - # - # This operation destruct and delete the consumer, the publisher - # and the buffer. - # - # @return PORT_OK - # - # @endif - # - # virtual ReturnCode disconnect(); - def disconnect(self): - self._rtcout.RTC_TRACE("disconnect()") - self.onDisconnect() - # delete consumer - if self._provider: - cfactory = OpenRTM_aist.InPortProviderFactory.instance() - cfactory.deleteObject(self._provider) - - self._provider.exit() - - self._provider = None - - # delete buffer - if self._buffer and self._deleteBuffer == True: - bfactory = OpenRTM_aist.CdrBufferFactory.instance() - bfactory.deleteObject(self._buffer) - - self._buffer = None - - return self.PORT_OK - - ## - # @if jp - # @brief ƥֲ - # - # Υͥ򥢥ƥֲ - # - # @else - # - # @brief Connector activation - # - # This operation activates this connector - # - # @endif - # - # virtual void activate(){}; // do nothing - def activate(self): # do nothing - pass - - ## - # @if jp - # @brief 󥢥ƥֲ - # - # Υͥ󥢥ƥֲ - # - # @else - # - # @brief Connector deactivation - # - # This operation deactivates this connector - # - # @endif - # - # virtual void deactivate(){}; // do nothing - def deactivate(self): # do nothing - pass - - - ## - # @if jp - # @brief Buffer - # - # Ϳ줿³˴ŤХåե롣 - # - # @param info ³ - # @return ХåեؤΥݥ - # - # @else - # @brief create buffer - # - # This function creates a buffer based on given information. - # - # @param info Connector information - # @return The poitner to the buffer - # - # @endif - # - # virtual CdrBufferBase* createBuffer(Profile& profile); - def createBuffer(self, profile): - buf_type = profile.properties.getProperty("buffer_type","ring_buffer") - return OpenRTM_aist.CdrBufferFactory.instance().createObject(buf_type) - - - ## - # @if jp - # @brief ǡν񤭽Ф - # - # Хåե˥ǡ񤭽Ф˽񤭽Ф硢ͤ - # BUFFER_OK Ȥʤ롣ʳξˤϡ顼ͤȤ BUFFER_FULL,TIMEOUT - # PRECONDITION_NOT_MET, BUFFER_ERROR ֤롣 - # - # @return BUFFER_OK ェλ - # BUFFER_FULL ХåեϤäѤǤ - # TIMEOUT ॢȤ - # PRECONDITION_NOT_MET ʤ - # BUFFER_ERROR ¾Υ顼 - # - # @else - # - # @brief Reading data - # - # This function write data to the buffer. If data is write - # properly, this function will return BUFFER_OK return code. Except - # normal return, BUFFER_FULL, TIMEOUT, PRECONDITION_NOT_MET and - # BUFFER_ERROR will be returned as error codes. - # - # @return BUFFER_OK Normal return - # BUFFER_FULL Buffer full - # TIMEOUT Timeout - # PRECONDITION_NOT_MET Preconditin not met - # BUFFER_ERROR Other error - # - # @endif - # - # ReturnCode write(const OpenRTM::CdrData& data); - def write(self, data): - if self._sync_readwrite: - self._readready_worker._cond.acquire() - while not self._readready_worker._completed: - self._readready_worker._cond.wait() - self._readready_worker._cond.release() - - ret = self._buffer.write(data) - - if self._sync_readwrite: - self._writecompleted_worker._completed = True - self._writecompleted_worker._cond.acquire() - self._writecompleted_worker._cond.notify() - self._writecompleted_worker._cond.release() - - self._readcompleted_worker._cond.acquire() - while not self._readcompleted_worker._completed: - self._readcompleted_worker._cond.wait() - self._readcompleted_worker._cond.release() - - self._writecompleted_worker._completed = False - - return ret - - - ## - # @if jp - # @brief ³Ω˥ХåƤ - # @else - # @brief Invoke callback when connection is established - # @endif - # void onConnect() - def onConnect(self): - if self._listeners and self._profile: - self._listeners.connector_[OpenRTM_aist.ConnectorListenerType.ON_CONNECT].notify(self._profile) - return - - ## - # @if jp - # @brief ³ǻ˥ХåƤ - # @else - # @brief Invoke callback when connection is destroied - # @endif - # void onDisconnect() - def onDisconnect(self): - if self._listeners and self._profile: - self._listeners.connector_[OpenRTM_aist.ConnectorListenerType.ON_DISCONNECT].notify(self._profile) - return - - - - def onBufferRead(self, data): - if self._listeners and self._profile: - self._listeners.connectorData_[OpenRTM_aist.ConnectorDataListenerType.ON_BUFFER_READ].notify(self._profile, data) - return - def onBufferEmpty(self, data): - if self._listeners and self._profile: - self._listeners.connector_[OpenRTM_aist.ConnectorListenerType.ON_BUFFER_EMPTY].notify(self._profile) - return - def onBufferReadTimeout(self, data): - if self._listeners and self._profile: - self._listeners.connector_[OpenRTM_aist.ConnectorListenerType.ON_BUFFER_READ_TIMEOUT].notify(self._profile) - return - - class WorkerThreadCtrl: - def __init__(self): - self._mutex = threading.RLock() - self._cond = threading.Condition(self._mutex) - self._completed = False \ No newline at end of file + # @if jp + # @brief 接続切断時にコールバックを呼ぶ + # @else + # @brief Invoke callback when connection is destroied + # @endif + # void onDisconnect() + def onDisconnect(self): + if self._listeners and self._profile: + self._listeners.notify( + OpenRTM_aist.ConnectorListenerType.ON_DISCONNECT, self._profile) + return + + def onBufferRead(self, data): + if self._listeners and self._profile: + _, data = self._listeners.notifyData( + OpenRTM_aist.ConnectorDataListenerType.ON_BUFFER_READ, self._profile, data) + return data + + def onBufferEmpty(self, data): + if self._listeners and self._profile: + self._listeners.notify( + OpenRTM_aist.ConnectorListenerType.ON_BUFFER_EMPTY, self._profile) + return + + def onBufferReadTimeout(self, data): + if self._listeners and self._profile: + self._listeners.notify( + OpenRTM_aist.ConnectorListenerType.ON_BUFFER_READ_TIMEOUT, self._profile) + return + + def setDataType(self, data): + OpenRTM_aist.InPortConnector.setDataType(self, data) + self._serializer = OpenRTM_aist.SerializerFactories.instance().createSerializer( + self._marshaling_type, data) + + class WorkerThreadCtrl: + def __init__(self): + self._mutex = threading.RLock() + self._cond = threading.Condition(self._mutex) + self._completed = False diff --git a/OpenRTM_aist/InPortSHMConsumer.py b/OpenRTM_aist/InPortSHMConsumer.py index 4340c183..881f78a7 100644 --- a/OpenRTM_aist/InPortSHMConsumer.py +++ b/OpenRTM_aist/InPortSHMConsumer.py @@ -1,5 +1,5 @@ #!/usr/bin/env python -# -*- coding: euc-jp -*- +# -*- coding: utf-8 -*- ## # @file InPortSHMConsumer.py @@ -9,7 +9,6 @@ # - import OpenRTM_aist import OpenRTM__POA @@ -20,9 +19,9 @@ # # @class InPortSHMConsumer # -# @brief InPortSHMConsumer 饹 +# @brief InPortSHMConsumer クラス # -# ̿ʤ ͭ Ѥϥݡȥ󥷥塼ޤμ饹 +# 通信手段に 共有メモリ を利用した入力ポートコンシューマの実装クラス。 # # # @else @@ -34,185 +33,172 @@ # # @endif # + + class InPortSHMConsumer(OpenRTM_aist.InPortCorbaCdrConsumer): - """ - """ - - ## - # @if jp - # @brief 󥹥ȥ饯 - # - # 󥹥ȥ饯 - # - # @param self - # - # @else - # @brief Constructor - # - # Constructor - # - # @param self - # - # @endif - # - def __init__(self): - OpenRTM_aist.InPortCorbaCdrConsumer.__init__(self) - self._rtcout = OpenRTM_aist.Manager.instance().getLogbuf("InPortSHMConsumer") - self._properties = None - - self._shm_address = str(OpenRTM_aist.uuid1()) - - self._shmem = OpenRTM_aist.SharedMemory() - - - - self._mutex = threading.RLock() - - return - - ## - # @if jp - # @brief ǥȥ饯 - # - # ǥȥ饯 - # - # @param self - # @param CorbaConsumer - # - # @else - # @brief Destructor - # - # Destructor - # - # @param self - # @param CorbaConsumer - # - # @endif - # - def __del__(self, CorbaConsumer=OpenRTM_aist.CorbaConsumer): - self._rtcout.RTC_PARANOID("~InPortSHMConsumer()") - CorbaConsumer.__del__(self) - self._shmem.close_memory(True) - - oid = OpenRTM_aist.Manager.instance().getPOA().servant_to_id(self._shmem) - OpenRTM_aist.Manager.instance().getPOA().deactivate_object(oid) - self._endian = True - - return - - ## - # @if jp - # @brief - # - # InPortConsumerγƼԤ - # ץХǥͥץե˶ͭζ̾¸뤿ᡢinitؿǶͭνԤ - # - # @param self - # @param prop ͥץѥƥ - # - # @else - # @brief Initializing configuration - # - # - # @endif - # - # virtual void init(coil::Properties& prop); - def init(self, prop): - - self._rtcout.RTC_TRACE("init()") - self._properties = prop - - - - - ds = prop.getProperty("shem_default_size") - self._memory_size = self._shmem.string_to_MemorySize(ds) - - - - - if prop.hasKey("serializer"): - endian = prop.getProperty("serializer.cdr.endian") - if not endian: - self._rtcout.RTC_ERROR("init(): endian is not set.") - endian = "little" - - - endian = OpenRTM_aist.split(endian, ",") - - endian = OpenRTM_aist.normalize(endian) - if endian == "little": + """ + """ + + ## + # @if jp + # @brief コンストラクタ + # + # コンストラクタ + # + # @param self + # + # @else + # @brief Constructor + # + # Constructor + # + # @param self + # + # @endif + # + def __init__(self): + OpenRTM_aist.InPortCorbaCdrConsumer.__init__(self) + OpenRTM_aist.CorbaConsumer.__init__( + self, OpenRTM__POA.PortSharedMemory) + self._rtcout = OpenRTM_aist.Manager.instance().getLogbuf("InPortSHMConsumer") + self._properties = None + + self._shm_address = str(OpenRTM_aist.uuid1()) + + self._shmem = OpenRTM_aist.SharedMemory() + + self._mutex = threading.RLock() + + return + + ## + # @if jp + # @brief デストラクタ + # + # デストラクタ + # + # @param self + # @param CorbaConsumer + # + # @else + # @brief Destructor + # + # Destructor + # + # @param self + # @param CorbaConsumer + # + # @endif + # + def __del__(self, CorbaConsumer=OpenRTM_aist.CorbaConsumer): + self._rtcout.RTC_PARANOID("~InPortSHMConsumer()") + CorbaConsumer.__del__(self) + self._shmem.close_memory(True) + + oid = OpenRTM_aist.Manager.instance().getPOA().servant_to_id(self._shmem) + OpenRTM_aist.Manager.instance().getPOA().deactivate_object(oid) self._endian = True - elif endian == "big": - self._endian = False - else: - self._endian = True - - return - - def setObject(self, obj): - if OpenRTM_aist.CorbaConsumer.setObject(self, obj): - ref_ = self.getObject() - if ref_: - inportcdr = ref_._narrow(OpenRTM__POA.PortSharedMemory) - if inportcdr is None: - return False - self._shmem.setInterface(inportcdr) - - return True - return False - - - ## - # @if jp - # @brief ³ؤΥǡ - # - # ³ΥݡȤإǡ - # - # ǡΥ϶ͭƬ8byte - # ǡ϶ͭ˽񤭹 - # - # @param self - # @param data ǡ - # @return ꥿󥳡 - # - # @else - # @brief Send data to the destination port - # - # @param self - # @param data - # @return - # - # @endif - # - # virtual ReturnCode put(const cdrMemoryStream& data); - def put(self, data): - self._rtcout.RTC_PARANOID("put()") - - try: - ref_ = self.getObject() - if ref_: - inportcdr = ref_._narrow(OpenRTM__POA.PortSharedMemory) - - guard = OpenRTM_aist.ScopedLock(self._mutex) - - self._shmem.setEndian(self._endian) - self._shmem.create_memory(self._memory_size, self._shm_address) - self._shmem.write(data) - - - ret = inportcdr.put() - del guard - return self.convertReturnCode(ret) - return self.CONNECTION_LOST - except: - self._rtcout.RTC_ERROR(OpenRTM_aist.Logger.print_exception()) - return self.CONNECTION_LOST - - + + return + + ## + # @if jp + # @brief 設定初期化 + # + # InPortConsumerの各種設定を行う + # プロバイダでコネクタプロファイルに共有メモリの空間名を保存するため、init関数で共有メモリの初期化を行う + # + # @param self + # @param prop コネクタプロパティ + # + # @else + # @brief Initializing configuration + # + # + # @endif + # + # virtual void init(coil::Properties& prop); + def init(self, prop): + + self._rtcout.RTC_TRACE("init()") + self._properties = prop + + ds = prop.getProperty("shem_default_size") + self._memory_size = self._shmem.string_to_MemorySize(ds) + + if prop.hasKey("serializer"): + endian = prop.getProperty("serializer.cdr.endian") + if not endian: + self._rtcout.RTC_ERROR("init(): endian is not set.") + endian = "little" + + endian = OpenRTM_aist.split(endian, ",") + endian = OpenRTM_aist.normalize(endian[0]) + if endian == "little": + self._endian = True + elif endian == "big": + self._endian = False + else: + self._endian = True + + return + + def setObject(self, obj): + if OpenRTM_aist.CorbaConsumer.setObject(self, obj): + portshmem = self._ptr() + if portshmem: + self._shmem.setInterface(portshmem) + + return True + return False + + ## + # @if jp + # @brief 接続先へのデータ送信 + # + # 接続先のポートへデータを送信する + # + # データのサイズは共有メモリも先頭8byteから取得する + # データは共有メモリに書き込む + # + # @param self + # @param data 送信するデータ + # @return リターンコード + # + # @else + # @brief Send data to the destination port + # + # @param self + # @param data + # @return + # + # @endif + # + # virtual ReturnCode put(const cdrMemoryStream& data); + + def put(self, data): + self._rtcout.RTC_PARANOID("put()") + + try: + portshmem = self._ptr() + if portshmem: + + guard = OpenRTM_aist.ScopedLock(self._mutex) + + self._shmem.setEndian(self._endian) + self._shmem.create_memory(self._memory_size, self._shm_address) + self._shmem.write(data) + + ret = portshmem.put() + del guard + return self.convertReturnCode(ret) + return self.CONNECTION_LOST + except BaseException: + self._rtcout.RTC_ERROR(OpenRTM_aist.Logger.print_exception()) + return self.CONNECTION_LOST + def InPortSHMConsumerInit(): - factory = OpenRTM_aist.InPortConsumerFactory.instance() - factory.addFactory("shared_memory", - OpenRTM_aist.InPortSHMConsumer, - OpenRTM_aist.Delete) + factory = OpenRTM_aist.InPortConsumerFactory.instance() + factory.addFactory("shared_memory", + OpenRTM_aist.InPortSHMConsumer) diff --git a/OpenRTM_aist/InPortSHMProvider.py b/OpenRTM_aist/InPortSHMProvider.py index 76002b99..cb0618fd 100644 --- a/OpenRTM_aist/InPortSHMProvider.py +++ b/OpenRTM_aist/InPortSHMProvider.py @@ -1,5 +1,5 @@ #!/usr/bin/env python -# -*- coding: euc-jp -*- +# -*- coding: utf-8 -*- ## # @file InPortSHMProvider.py @@ -8,9 +8,6 @@ # @author Nobuhiko Miyamoto - - - import OpenRTM_aist import OpenRTM @@ -18,255 +15,236 @@ ## # @if jp # @class InPortSHMProvider -# @brief InPortSHMProvider 饹 +# @brief InPortSHMProvider クラス # -# ̿ʤ ͭ ѤϥݡȥץХμ饹 +# 通信手段に 共有メモリ を利用した入力ポートプロバイダーの実装クラス。 # # # @else -# @class InPortCorbaCdrProvider -# @brief InPortCorbaCdrProvider class +# @class InPortSHMProvider +# @brief InPortSHMProvider class # # # # @endif # -class InPortSHMProvider(OpenRTM_aist.InPortProvider, OpenRTM_aist.SharedMemory): - - """ - """ - - ## - # @if jp - # @brief 󥹥ȥ饯 - # - # 󥹥ȥ饯 - # Interface Typeˤshared_memoryꤹ - # ͭζ̾UUIDǺͥץեdataport.shared_memory.address¸ - # - # self - # - # @else - # @brief Constructor - # - # Constructor - # - # self - # @endif - # - def __init__(self): - OpenRTM_aist.InPortProvider.__init__(self) - OpenRTM_aist.SharedMemory.__init__(self) - - # PortProfile setting - self.setInterfaceType("shared_memory") - self._objref = self._this() - - - - self._buffer = None - - self._profile = None - self._listeners = None - - orb = OpenRTM_aist.Manager.instance().getORB() - self._properties.append(OpenRTM_aist.NVUtil.newNV("dataport.corba_cdr.inport_ior", - orb.object_to_string(self._objref))) - self._properties.append(OpenRTM_aist.NVUtil.newNV("dataport.corba_cdr.inport_ref", - self._objref)) - - - - - - - return - - ## - # @if jp - # @brief ǥȥ饯 - # - # ǥȥ饯 - # - # @param self - # - # @else - # @brief Destructor - # - # Destructor - # - # @param self - # - # @endif - # - def __del__(self): - return - - ## - # @if jp - # @brief λ - # - # @else - # @brief - # - # - # - # @endif - # - def exit(self): - oid = OpenRTM_aist.Manager.instance().getPOA().servant_to_id(self) - OpenRTM_aist.Manager.instance().getPOA().deactivate_object(oid) - - - # void init(coil::Properties& prop) - def init(self, prop): - - pass - - def setBuffer(self, buffer): - self._buffer = buffer - return - - def setListener(self, info, listeners): - self._profile = info - self._listeners = listeners - return - - - ## - # @if jp - # @brief Хåե˥ǡ񤭹 - # - # ǡΥ϶ͭƬ8byte - # ꤫ͭǡФХåե˽񤭹 - # - # @param data оݥǡ - # - # @else - # @brief - # - # - # - # @param data - # - # @endif - # - # ::OpenRTM::PortStatus put() - # throw (CORBA::SystemException); - def put(self): - - try: - self._rtcout.RTC_PARANOID("InPortCorbaCdrProvider.put()") - - - - - - shm_data = self.read() - - if not self._buffer: - self.onReceiverError(shm_data) - return OpenRTM.PORT_ERROR - - self._rtcout.RTC_PARANOID("received data size: %d", len(shm_data)) - - self.onReceived(shm_data) - - if not self._connector: - return OpenRTM.PORT_ERROR - - - - ret = self._connector.write(shm_data) - - - return self.convertReturn(ret, shm_data) - - except: - self._rtcout.RTC_TRACE(OpenRTM_aist.Logger.print_exception()) - return OpenRTM.UNKNOWN_ERROR - - - - - - def onBufferWrite(self, data): - if self._listeners is not None and self._profile is not None: - self._listeners.connectorData_[OpenRTM_aist.ConnectorDataListenerType.ON_BUFFER_WRITE].notify(self._profile, data) - return - - def onBufferFull(self, data): - if self._listeners is not None and self._profile is not None: - self._listeners.connectorData_[OpenRTM_aist.ConnectorDataListenerType.ON_BUFFER_FULL].notify(self._profile, data) - return - - def onBufferWriteTimeout(self, data): - if self._listeners is not None and self._profile is not None: - self._listeners.connectorData_[OpenRTM_aist.ConnectorDataListenerType.ON_BUFFER_WRITE_TIMEOUT].notify(self._profile, data) - return - - def onBufferWriteOverwrite(self, data): - if self._listeners is not None and self._profile is not None: - self._listeners.connectorData_[OpenRTM_aist.ConnectorDataListenerType.ON_BUFFER_OVERWRITE].notify(self._profile, data) - return - - def onReceived(self, data): - if self._listeners is not None and self._profile is not None: - self._listeners.connectorData_[OpenRTM_aist.ConnectorDataListenerType.ON_RECEIVED].notify(self._profile, data) - return - - def onReceiverFull(self, data): - if self._listeners is not None and self._profile is not None: - self._listeners.connectorData_[OpenRTM_aist.ConnectorDataListenerType.ON_RECEIVER_FULL].notify(self._profile, data) - return - - def onReceiverTimeout(self, data): - if self._listeners is not None and self._profile is not None: - self._listeners.connectorData_[OpenRTM_aist.ConnectorDataListenerType.ON_RECEIVER_TIMEOUT].notify(self._profile, data) - return - - def onReceiverError(self, data): - if self._listeners is not None and self._profile is not None: - self._listeners.connectorData_[OpenRTM_aist.ConnectorDataListenerType.ON_RECEIVER_ERROR].notify(self._profile, data) - return - - - def convertReturn(self, status, data): - if status == OpenRTM_aist.BufferStatus.BUFFER_OK: - self.onBufferWrite(data) - return OpenRTM.PORT_OK - - elif status == OpenRTM_aist.BufferStatus.BUFFER_ERROR: - self.onReceiverError(data) - return OpenRTM.PORT_ERROR - - elif status == OpenRTM_aist.BufferStatus.BUFFER_FULL: - self.onBufferFull(data) - self.onReceiverFull(data) - return OpenRTM.BUFFER_FULL - - elif status == OpenRTM_aist.BufferStatus.BUFFER_EMPTY: - return OpenRTM.BUFFER_EMPTY - - elif status == OpenRTM_aist.BufferStatus.PRECONDITION_NOT_MET: - self.onReceiverError(data) - return OpenRTM.PORT_ERROR - - elif status == OpenRTM_aist.BufferStatus.TIMEOUT: - self.onBufferWriteTimeout(data) - self.onReceiverTimeout(data) - return OpenRTM.BUFFER_TIMEOUT - - else: - self.onReceiverError(data) - return OpenRTM.UNKNOWN_ERROR - - +class InPortSHMProvider(OpenRTM_aist.InPortProvider, + OpenRTM_aist.SharedMemory): + + """ + """ + + ## + # @if jp + # @brief コンストラクタ + # + # コンストラクタ + # Interface Typeにはshared_memoryを指定する + # 共有メモリの空間名はUUIDで作成し、コネクタプロファイルのdataport.shared_memory.addressに保存する + # + # self + # + # @else + # @brief Constructor + # + # Constructor + # + # self + # @endif + # + def __init__(self): + OpenRTM_aist.InPortProvider.__init__(self) + OpenRTM_aist.SharedMemory.__init__(self) + + # PortProfile setting + self.setInterfaceType("shared_memory") + self._objref = self._this() + + self._buffer = None + + self._profile = None + self._listeners = None + + orb = OpenRTM_aist.Manager.instance().getORB() + self._properties.append(OpenRTM_aist.NVUtil.newNV("dataport.corba_cdr.inport_ior", + orb.object_to_string(self._objref))) + self._properties.append(OpenRTM_aist.NVUtil.newNV("dataport.corba_cdr.inport_ref", + self._objref)) + + return + + ## + # @if jp + # @brief デストラクタ + # + # デストラクタ + # + # @param self + # + # @else + # @brief Destructor + # + # Destructor + # + # @param self + # + # @endif + # + def __del__(self): + return + + ## + # @if jp + # @brief 終了処理 + # + # @else + # @brief + # + # + # + # @endif + # + def exit(self): + oid = OpenRTM_aist.Manager.instance().getPOA().servant_to_id(self) + OpenRTM_aist.Manager.instance().getPOA().deactivate_object(oid) + + # void init(coil::Properties& prop) + def init(self, prop): + + pass + + def setBuffer(self, buffer): + self._buffer = buffer + return + + def setListener(self, info, listeners): + self._profile = info + self._listeners = listeners + return + + ## + # @if jp + # @brief バッファにデータを書き込む + # + # データのサイズは共有メモリも先頭8byteから取得する + # 共有メモリからデータを取り出しバッファに書き込む + # + # @param data 書込対象データ + # + # @else + # @brief + # + # + # + # @param data + # + # @endif + # + # ::OpenRTM::PortStatus put() + # throw (CORBA::SystemException); + def put(self): + + try: + self._rtcout.RTC_PARANOID("InPortCorbaCdrProvider.put()") + + shm_data = self.read() + + if not self._connector: + self.onReceiverError(shm_data) + return OpenRTM.PORT_ERROR + + self._rtcout.RTC_PARANOID("received data size: %d", len(shm_data)) + + shm_data = self.onReceived(shm_data) + + ret = self._connector.write(shm_data) + + return self.convertReturn(ret, shm_data) + + except BaseException: + self._rtcout.RTC_TRACE(OpenRTM_aist.Logger.print_exception()) + return OpenRTM.UNKNOWN_ERROR + + def onBufferWrite(self, data): + if self._listeners is not None and self._profile is not None: + _, data = self._listeners.notifyData( + OpenRTM_aist.ConnectorDataListenerType.ON_BUFFER_WRITE, self._profile, data) + return data + + def onBufferFull(self, data): + if self._listeners is not None and self._profile is not None: + _, data = self._listeners.notifyData( + OpenRTM_aist.ConnectorDataListenerType.ON_BUFFER_FULL, self._profile, data) + return data + + def onBufferWriteTimeout(self, data): + if self._listeners is not None and self._profile is not None: + _, data = self._listeners.notifyData( + OpenRTM_aist.ConnectorDataListenerType.ON_BUFFER_WRITE_TIMEOUT, self._profile, data) + return data + + def onBufferWriteOverwrite(self, data): + if self._listeners is not None and self._profile is not None: + _, data = self._listeners.notifyData( + OpenRTM_aist.ConnectorDataListenerType.ON_BUFFER_OVERWRITE, self._profile, data) + return data + + def onReceived(self, data): + if self._listeners is not None and self._profile is not None: + _, data = self._listeners.notifyData( + OpenRTM_aist.ConnectorDataListenerType.ON_RECEIVED, self._profile, data) + return data + + def onReceiverFull(self, data): + if self._listeners is not None and self._profile is not None: + _, data = self._listeners.notifyData( + OpenRTM_aist.ConnectorDataListenerType.ON_RECEIVER_FULL, self._profile, data) + return data + + def onReceiverTimeout(self, data): + if self._listeners is not None and self._profile is not None: + _, data = self._listeners.notifyData( + OpenRTM_aist.ConnectorDataListenerType.ON_RECEIVER_TIMEOUT, self._profile, data) + return data + + def onReceiverError(self, data): + if self._listeners is not None and self._profile is not None: + _, data = self._listeners.notifyData( + OpenRTM_aist.ConnectorDataListenerType.ON_RECEIVER_ERROR, self._profile, data) + return data + + def convertReturn(self, status, data): + if status == OpenRTM_aist.BufferStatus.BUFFER_OK: + self.onBufferWrite(data) + return OpenRTM.PORT_OK + + elif status == OpenRTM_aist.BufferStatus.BUFFER_ERROR: + self.onReceiverError(data) + return OpenRTM.PORT_ERROR + + elif status == OpenRTM_aist.BufferStatus.BUFFER_FULL: + data = self.onBufferFull(data) + self.onReceiverFull(data) + return OpenRTM.BUFFER_FULL + + elif status == OpenRTM_aist.BufferStatus.BUFFER_EMPTY: + return OpenRTM.BUFFER_EMPTY + + elif status == OpenRTM_aist.BufferStatus.PRECONDITION_NOT_MET: + self.onReceiverError(data) + return OpenRTM.PORT_ERROR + + elif status == OpenRTM_aist.BufferStatus.TIMEOUT: + data = self.onBufferWriteTimeout(data) + self.onReceiverTimeout(data) + return OpenRTM.BUFFER_TIMEOUT + + else: + self.onReceiverError(data) + return OpenRTM.UNKNOWN_ERROR - def InPortSHMProviderInit(): - factory = OpenRTM_aist.InPortProviderFactory.instance() - factory.addFactory("shared_memory", - OpenRTM_aist.InPortSHMProvider, - OpenRTM_aist.Delete) + factory = OpenRTM_aist.InPortProviderFactory.instance() + factory.addFactory("shared_memory", + OpenRTM_aist.InPortSHMProvider) diff --git a/OpenRTM_aist/Listener.py b/OpenRTM_aist/Listener.py index 8313b6e1..49b97ddc 100644 --- a/OpenRTM_aist/Listener.py +++ b/OpenRTM_aist/Listener.py @@ -1,5 +1,5 @@ #!/usr/bin/env python -# -*- coding: euc-jp -*- +# -*- coding: utf-8 -*- ## # @file Listener.py @@ -15,13 +15,12 @@ # All rights reserved. - ## # @if jp # @class ListenerBase -# @brief ListenerBase 饹 +# @brief ListenerBase クラス # -# ޡϿꥹʡݥ󥿡ե饹 +# タイマーに登録するリスナー用抽象インターフェースクラス。 # # @since 0.4.0 # @@ -30,32 +29,31 @@ # @brief ListenerBase class # @endif class ListenerBase: - """ - """ - - ## - # @if jp - # @brief Хå(֥饹) - # - # ХåѴؿ
- # ֥饹Ǥμ - # - # @param self - # - # @else - # - # @endif - def invoke(self): - pass - + """ + """ + + ## + # @if jp + # @brief コールバック処理(サブクラス実装用) + # + # コールバック処理用関数
+ # ※サブクラスでの実装参照用 + # + # @param self + # + # @else + # + # @endif + def invoke(self): + pass ## # @if jp # @class ListenerObject -# @brief ListenerObject 饹 +# @brief ListenerObject クラス # -# ޡϿꥹʡѴ쥯饹 +# タイマーに登録するリスナー用基底クラス。 # # @since 0.4.0 # @@ -64,49 +62,48 @@ def invoke(self): # @brief ListenerObject class # @endif class ListenerObject(ListenerBase): - """ - """ - - ## - # @if jp - # @brief 󥹥ȥ饯 - # - # 󥹥ȥ饯 - # - # @param self - # @param obj ꥹʡ֥ - # @param cbf ХåѴؿ - # - # @else - # - # @endif - def __init__(self,obj,cbf): - self.obj = obj - self.cbf = cbf - - - ## - # @if jp - # @brief Хåѽ - # - # ХåѴؿ - # - # @param self - # - # @else - # - # @endif - def invoke(self): - self.cbf(self.obj) - + """ + """ + + ## + # @if jp + # @brief コンストラクタ + # + # コンストラクタ + # + # @param self + # @param obj リスナーオブジェクト + # @param cbf コールバック用関数 + # + # @else + # + # @endif + def __init__(self, obj, cbf): + self.obj = obj + self.cbf = cbf + + ## + # @if jp + # @brief コールバック用処理 + # + # コールバック処理用関数 + # + # @param self + # + # @else + # + # @endif + + def invoke(self): + self.cbf(self.obj) ## # @if jp # @class ListenerFunc -# @brief ListenerFunc 饹 +# @brief ListenerFunc クラス # -# Хåѥ֥ȡ +# コールバック用オブジェクト。 # # @since 0.4.0 # @@ -115,35 +112,35 @@ def invoke(self): # @brief ListenerFunc class # @endif class ListenerFunc(ListenerBase): - """ - """ - - ## - # @if jp - # @brief 󥹥ȥ饯 - # - # 󥹥ȥ饯 - # - # @param self - # @param cbf ХåѴؿ - # - # @else - # - # @endif - def __init__(self,cbf): - self.cbf = cbf - - - ## - # @if jp - # @brief Хå - # - # ХåѴؿ - # - # @param self - # - # @else - # - # @endif - def invoke(self): - self.cbf() + """ + """ + + ## + # @if jp + # @brief コンストラクタ + # + # コンストラクタ + # + # @param self + # @param cbf コールバック用関数 + # + # @else + # + # @endif + def __init__(self, cbf): + self.cbf = cbf + + ## + # @if jp + # @brief コールバック処理 + # + # コールバック処理用関数 + # + # @param self + # + # @else + # + # @endif + + def invoke(self): + self.cbf() diff --git a/OpenRTM_aist/ListenerHolder.py b/OpenRTM_aist/ListenerHolder.py index 671a071a..d7501fed 100644 --- a/OpenRTM_aist/ListenerHolder.py +++ b/OpenRTM_aist/ListenerHolder.py @@ -1,5 +1,5 @@ #!/usr/bin/env python -# -*- coding: euc-jp -*- +# -*- coding: utf-8 -*- ## # @file ListnerHolder.py @@ -23,40 +23,40 @@ ## # @if jp -# @class Listener ۥ饹 -# -# Υ饹ϡꥹʥ饹ñݻԤꥹʥۥ -# Ǥ롣Υ饹Ѥ뤿ˤϡƥץ졼Ȥ裱 -# ꥹʥ饹 (Listener饹) ӡListenerHolder饹 -# ƥץ졼ȤѾơºݤ˥ꥹʤθƤӽФԤ -# ListenerHolder饹ɬפ롣 -# -# Υ饹ϡåɥ֤¸뤿ᡢꥹʤɲäȺˤ -# Ƥϥߥ塼ƥåˤåԤäƤ롣˥åɥ -# ʥꥹʴ¸뤿ˤϥꥹʤΥХå򥳡뤹ݤ -# ߥ塼ƥåˤåԤɬפ롣 -# -# @section Listener饹 -# -# ٥ȯ˥ХåдؿĴ쥯饹 -# 롣ХåΤΥдؿϡǤդ͡Ĥ -# ΤǤ̾δؿǤäƤ褤operator()ʤɤΥե -# ȤƤ褤ºݤˤϴ쥯饹ˤƤδؿ貾 -# ۴ؿȤΥ饹ѾơºݤΥꥹʥ饹 -# 뤳Ȥˤʤ롣ޤҤȤĤΥꥹʥ饹ʣΥХåؿ -# Ƥ褤ºݤˤϡΥХåؿºݤ˸Ƥӽ -# ˡ˴ؤƤϡListenerHolder饹ˤƾܤ뤳 -# Ȥˤʤ롣 +# @class Listener ホルダークラス +# +# このクラスは、リスナクラスの単純な保持、管理を行うリスナホルダクラ +# スである。このクラスを利用するためには、テンプレートの第1引数に当 +# たるリスナクラス (Listenerクラス) および、このListenerHolderクラス +# テンプレートを継承して、実際にリスナの呼び出しを行う +# ListenerHolder実装クラスを実装する必要がある。 +# +# このクラスは、スレッドセーブを実現するため、リスナの追加と削除につ +# いてはミューテックスによるロックを行っている。完全にスレッドセーフ +# なリスナ管理を実現するためにはリスナのコールバックをコールする際に +# もミューテックによるロックを行う必要がある。 +# +# @section Listenerクラスの定義 +# +# イベント発生時にコールバックされるメンバ関数を持つ基底クラスを定義 +# する。コールバックのためのメンバ関数は、任意の戻り値、引数を持つも +# のが定義でき、通常の関数であってもよいし、operator()などのファンク +# タとして定義してもよい。実際には基底クラスにてこれらの関数を純粋仮 +# 想関数として定義し、このクラスを継承して、実際のリスナクラスを実装 +# することになる。また、ひとつのリスナクラスに複数のコールバック関数 +# を定義してもよい。実際には、これらのコールバック関数を実際に呼び出 +# す方法に関しては、次のListenerHolder実装クラスにて詳しく定義するこ +# とになる。 #
 # class MyListenerBase
 # {
 # public:
-#   // Хåؿ1: ؿƤӽФ黻Ҥˤ륳Хåؿ
-#   // ե󥯥Τ褦˥Хåؿ㡣
-#   virtual void operator()(std::string strarg) = 0; // 貾۴ؿ
-#   
-#   // Хåδؿ˥㤬¿ͤǤ硢Τ褦ñ
-#   // дؿȤ뤳Ȥǽ
+#   // コールバック関数1: 関数呼び出し演算子によるコールバック関数
+#   // いわゆるファンクタのようにコールバック関数を定義する例。
+#   virtual void operator()(std::string strarg) = 0; // 純粋仮想関数
+#
+#   // コールバックの関数シグニチャが多様である場合、このように単な
+#   // るメンバ関数として定義することも可能。
 #   virtual void onEvent0(const char* arg0) = 0;
 #   virtual void onEvent1(int arg0) = 0;
 #   virtual void onEvent2(double arg0) = 0;
@@ -64,25 +64,25 @@
 # };
 # 
# -# @section ListenerHolder饹 +# @section ListenerHolder実装クラス # -# ListenerHolder饹ϤLsitenerHolder饹ƥץ졼Ȥ -# ơ MyListenerBase 饹ɲäȺʤɴ -# ļºݤ˥ХåؿƤӽФʬ뤳Ȥˤʤ롣 -# ºݤ˥ХåƤӽФʬǤϡؿ˥㤬¿¿ͤǤ -# ꡢҤȤĤΥꥹʥ饹ʣΥХåؿľ礬 -# ᡢ̤Υꥹʥ饹б뤿ᡢθƤӽФʬɬפȤ -# 롣ListenerHolder饹ϡMyListenerBase饹Ʊ˥ -# ĥдؿؿǤϡListenerHolder饹ġ -# m_listeners, m_mutex ΤĤΥѿѤơϿ -# ꥹʥ֥ȤΥѿƤӽФ +# ListenerHolder実装クラスはこのLsitenerHolderクラステンプレートを継 +# 承して、上で定義した MyListenerBase クラスの追加と削除など管理を行 +# い、かつ実際にコールバック関数を呼び出す部分を実装することになる。 +# 実際にコールバックを呼び出す部分では、関数シグニチャが多種多様であっ +# たり、ひとつのリスナクラスが複数のコールバック関数を持つ場合がある +# ため、個別のリスナクラスに対応するため、この呼び出し部分が必要とな +# る。ListenerHolder実装クラスは、MyListenerBaseクラスと同じシグニチャ +# を持つメンバ関数をもち、関数内部では、ListenerHolderクラスが持つ、 +# m_listeners, m_mutex のこれら二つのメンバ変数を利用して、登録され +# たリスナオブジェクトのメンバ変数を呼び出す。 # #
 # class MyListenerHolderImpl
 #  : public ::RTM::util::ListenerHolder
 # {
 # public:
-#   // ؿƤӽФ黻ҤΥХåؿξ
+#   // 関数呼び出し演算子のコールバック関数の場合
 #   virtual void operator()(std::string strarg)
 #   {
 #     Gurad gurad(m_mutex);
@@ -103,25 +103,25 @@
 # };
 # 
# -# ꥹʥ֥ȤؤΥݥ󥿤ǼƤEntry֥Ȥ -# std::pair ȤƤꡢfirst -# Listener֥ȤؤΥݥ󥿡secondưե饰Ǥ롣 -# äơꥹʥ֥ȤإˤfirstѤ롣 -# ޥåɴĶѤ뤳ȤꤵϡGuard -# guard(m_mutex) ˤå˺줺˹Ԥȡ -# -# @section ListenerHolder饹 -# 줿MyListenerHolderImplϰȤưʲΤ褦Ѥ롣 +# リスナオブジェクトへのポインタを格納しているEntryオブジェクトは +# std::pair として定義されており、firstが +# Listenerオブジェクトへのポインタ、secondが自動削除フラグである。し +# たがって、リスナオブジェクトへアクセスする場合にはfirstを使用する。 +# マルチスレッド環境で利用することが想定される場合は、Guard +# guard(m_mutex) によるロックを忘れずに行うこと。 +# +# @section ListenerHolder実装クラスの利用 +# 実装されたMyListenerHolderImplは一例として以下のように利用する。 # #
-# // ȤХ饹ФȤ
+# // たとえばクラスメンバとして宣言
 # MyListenerHolderImpl m_holder;
 #
-# // Ͽư꡼⡼ɤϿ
-# // ֥ȤκHolder饹Ǥ
-# m_holder.addListener(new MyListener0(), true); // MyListener0
-# 
-# // ХåƤӽФ
+# // 登録、自動クリーンモードで登録、
+# // オブジェクトの削除はHolderクラスに任せる
+# m_holder.addListener(new MyListener0(), true); // MyListener0の
+#
+# // コールバックを呼び出す
 # m_holder.operator()(strarg);
 # m_holder.onEvent0("HogeHoge);
 # 
@@ -133,70 +133,70 @@ # @endif # class ListenerHolder: - """ - """ + """ + """ - ## - # @if jp - # @brief ListenerHolder饹󥹥ȥ饯 - # @else - # @brief ListenerHolder class ctor - # @endif - def __init__(self): - self.listener_mutex = threading.RLock() - self.listeners = [] - return + ## + # @if jp + # @brief ListenerHolderクラスコンストラクタ + # @else + # @brief ListenerHolder class ctor + # @endif + def __init__(self): + self.listener_mutex = threading.RLock() + self.listeners = [] + return + ## + # @if jp + # @brief ListenerHolderデストラクタ + # @else + # @brief ListenerHolder class dtor + # @endif + + def __del__(self): + pass + + ## + # @if jp + # @brief リスナを追加する + # @else + # @brief add listener object + # @endif + # virtual void addListener(ListenerClass* listener) + def addListener(self, listener): + guard = OpenRTM_aist.ScopedLock(self.listener_mutex) + self.listeners.append(listener) + del guard + return - ## - # @if jp - # @brief ListenerHolderǥȥ饯 - # @else - # @brief ListenerHolder class dtor - # @endif - def __del__(self): - guard = OpenRTM_aist.ScopedLock(self.listener_mutex) - - for listener_ in self.listeners: - for (l,f) in listener_.items(): - if f: - del l - #del guard - #return - - ## - # @if jp - # @brief ꥹʤɲä - # @else - # @brief add listener object - # @endif - # virtual void addListener(ListenerClass* listener, - # bool autoclean) - def addListener(self, listener, autoclean): - guard = OpenRTM_aist.ScopedLock(self.listener_mutex) - self.listeners.append({listener:autoclean}) - del guard - return - - ## - # @if jp - # @brief ꥹʤ - # @else - # @brief remove listener object - # @endif - # virtual void removeListener(ListenerClass* listener) - def removeListener(self, listener): - guard = OpenRTM_aist.ScopedLock(self.listener_mutex) - for (i, listener_) in enumerate(self.listeners): - if listener == listener: - del self.listeners[i] + ## + # @if jp + # @brief リスナを削除する + # @else + # @brief remove listener object + # @endif + # virtual void removeListener(ListenerClass* listener) + def removeListener(self, listener): + guard = OpenRTM_aist.ScopedLock(self.listener_mutex) + for (i, listener_) in enumerate(self.listeners): + if self.listeners[i] == listener: + del self.listeners[i] + return return - return - def LISTENERHOLDER_CALLBACK(self, func, *args): - guard = OpenRTM_aist.ScopedLock(self.listener_mutex) - for listener in self.listeners: - for (l,f) in listener.items(): - func_ = getattr(l,func,None) - func_(*args) - return + def LISTENERHOLDER_CALLBACK(self, func, *args): + guard = OpenRTM_aist.ScopedLock(self.listener_mutex) + for listener in self.listeners: + func_ = getattr(listener, func, None) + if len(args) == 1: + ret = func_(args[0]) + args = (ret,) + else: + ret = func_(*args) + if ret is not None: + args = ret + if len(args) == 1: + return args[0] + else: + return args diff --git a/OpenRTM_aist/LocalServiceAdmin.py b/OpenRTM_aist/LocalServiceAdmin.py index 0247b29f..08d35f9e 100644 --- a/OpenRTM_aist/LocalServiceAdmin.py +++ b/OpenRTM_aist/LocalServiceAdmin.py @@ -1,5 +1,5 @@ #!/usr/bin/env python -# -*- coding: euc-jp -*- +# -*- coding: utf-8 -*- ## # @file LocalServiceAdmin.py @@ -25,7 +25,7 @@ # @if jp # # @class LocalService administration class -# @brief LocalService 饹 +# @brief LocalService 管理クラス # # TODO: Documentation # @@ -42,288 +42,291 @@ # @since 1.1.0 # # @endif + + class LocalServiceAdmin: - """ - """ - - ## - # @if jp - # - # @brief 󥹥ȥ饯 - # - # 󥹥ȥ饯 - # - # @else - # - # @brief Constructor - # - # Constructor - # - # @endif - def __init__(self): - self._services = [] - self._rtcout = OpenRTM_aist.Manager.instance().getLogbuf("LocalServiceAdmin") - self._rtcout.RTC_TRACE("LocalServiceAdmin.__init__()") - self._factory = OpenRTM_aist.LocalServiceFactory.instance() - return - - - def __del__(self): - self.finalize() - return - - - ## - # @if jp - # - # @brief LocaServiceAdminν - # - # TODO: Documentation - # - # @else - # - # @brief Initialization of LocalServiceAdmin - # - # TODO: Documentation - # - # @endif - # void init(coil::Properties& props); - def init(self, props): - self._rtcout.RTC_TRACE("LocalServiceAdmin.init()") - svcs_ = props.getProperty("enabled_services").split(",") - svcs_lower_ = [s.lower() for s in svcs_] - all_enable_ = False - if "all" in svcs_lower_: - self._rtcout.RTC_INFO("All the local services are enabled.") - all_enable_ = True - - ids_ = self._factory.getIdentifiers() - self._rtcout.RTC_DEBUG("Available services: %s", OpenRTM_aist.flatten(ids_)) - for id_ in ids_: - if all_enable_ or self.isEnabled(id_, svcs_): - if self.notExisting(id_): - service_ = self._factory.createObject(id_) - self._rtcout.RTC_DEBUG("Service created: %s", id_) - prop_ = props.getNode(id_) - service_.init(prop_) - self.addLocalService(service_) - return - - - ## - # @if jp - # - # @brief LocalserviceAdmin νλ - # - # TODO: Documentation - # - # @else - # - # @brief Finalization ofLocalServiceAdmin - # - # TODO: Documentation - # - # @endif - # void finalize(); - def finalize(self): - for svc_ in self._services: - svc_.finalize() - self._factory.deleteObject(svc_) - self._services = [] - - return - - - ## - # @if jp - # - # @brief LocalServiceProfileListμ - # - # TODO: Documentation - # - # @else - # - # @brief Getting LocalServiceProfileList - # - # TODO: Documentation - # - # @endif - # ::RTM::LocalServiceProfileList getServiceProfiles(); - def getServiceProfiles(self): - profs_ = [] - for svc_ in self._services: - profs_.append(svc_.getProfile()) - return profs_ - - - ## - # @if jp - # - # @brief LocalServiceProfile - # - # id ǻꤵ줿IDLocalService - # LocalServiceProfile 롣id NULL ݥ󥿤ξ硢ꤵ줿 - # id ˳ServiceProfile ¸ߤʤ硢false֤ - # - # @param id LocalService IFR ID - # @return ꤵ줿 id LocalServiceProfile - # - # @else - # - # @brief Get LocalServiceProfile of an LocalService - # - # This operation returns LocalServiceProfile of a LocalService - # which has the specified id. If the specified id is - # NULL pointer or the specified id does not exist in the - # ServiceProfile list, false will be returned. - # - # @param id ID of an LocalService - # @return LocalServiceProfile which has the specified id - # - # @endif - # bool getServiceProfile(std::string name, - # ::RTM::LocalServiceProfile& prof); - def getServiceProfile(self, name, prof): - global services_mutex - guard_ = OpenRTM_aist.ScopedLock(services_mutex) - for svc_ in self._services: - if name == svc_.getProfile().name: - prof[0] = svc_.getProfile() + """ + """ + + ## + # @if jp + # + # @brief コンストラクタ + # + # コンストラクタ + # + # @else + # + # @brief Constructor + # + # Constructor + # + # @endif + def __init__(self): + self._services = [] + self._rtcout = OpenRTM_aist.Manager.instance().getLogbuf("LocalServiceAdmin") + self._rtcout.RTC_TRACE("LocalServiceAdmin.__init__()") + self._factory = OpenRTM_aist.LocalServiceFactory.instance() + return + + def __del__(self): + self.finalize() + return + + ## + # @if jp + # + # @brief LocaServiceAdminの初期化 + # + # TODO: Documentation + # + # @else + # + # @brief Initialization of LocalServiceAdmin + # + # TODO: Documentation + # + # @endif + # void init(coil::Properties& props); + + def init(self, props): + self._rtcout.RTC_TRACE("LocalServiceAdmin.init()") + svcs_ = props.getProperty("enabled_services").split(",") + svcs_lower_ = [s.lower() for s in svcs_] + all_enable_ = False + if "all" in svcs_lower_: + self._rtcout.RTC_INFO("All the local services are enabled.") + all_enable_ = True + + ids_ = self._factory.getIdentifiers() + self._rtcout.RTC_DEBUG( + "Available services: %s", + OpenRTM_aist.flatten(ids_)) + for id_ in ids_: + if all_enable_ or self.isEnabled(id_, svcs_): + if self.notExisting(id_): + service_ = self._factory.createObject(id_) + self._rtcout.RTC_DEBUG("Service created: %s", id_) + prop_ = props.getNode(id_) + service_.init(prop_) + self.addLocalService(service_) + return + + ## + # @if jp + # + # @brief LocalserviceAdmin の終了処理 + # + # TODO: Documentation + # + # @else + # + # @brief Finalization ofLocalServiceAdmin + # + # TODO: Documentation + # + # @endif + # void finalize(); + + def finalize(self): + for svc_ in self._services: + svc_.finalize() + self._services = [] + + return + + ## + # @if jp + # + # @brief LocalServiceProfileListの取得 + # + # TODO: Documentation + # + # @else + # + # @brief Getting LocalServiceProfileList + # + # TODO: Documentation + # + # @endif + # ::RTM::LocalServiceProfileList getServiceProfiles(); + + def getServiceProfiles(self): + profs_ = [] + for svc_ in self._services: + profs_.append(svc_.getProfile()) + return profs_ + + ## + # @if jp + # + # @brief LocalServiceProfile を取得する + # + # id で指定されたIDを持つLocalService の + # LocalServiceProfile を取得する。id が NULL ポインタの場合、指定された + # id に該当するServiceProfile が存在しない場合、falseを返す。 + # + # @param id LocalService の IFR ID + # @return 指定された id を持つ LocalServiceProfile + # + # @else + # + # @brief Get LocalServiceProfile of an LocalService + # + # This operation returns LocalServiceProfile of a LocalService + # which has the specified id. If the specified id is + # NULL pointer or the specified id does not exist in the + # ServiceProfile list, false will be returned. + # + # @param id ID of an LocalService + # @return LocalServiceProfile which has the specified id + # + # @endif + # bool getServiceProfile(std::string name, + # ::RTM::LocalServiceProfile& prof); + + def getServiceProfile(self, name): + global services_mutex + guard_ = OpenRTM_aist.ScopedLock(services_mutex) + for svc_ in self._services: + if name == svc_.getProfile().name: + prof = svc_.getProfile() + del guard_ + return True, prof + del guard_ + return False, None + + ## + # @if jp + # + # @brief LocalService の Service を取得する + # + # id で指定されたIDを持つLocalService のポインタを取得する。id が + # NULL ポインタの場合、指定された id に該当するServiceProfile が存 + # 在しない場合、NULLを返す。 + # + # @param id LocalService の ID + # @return 指定された id を持つ LocalService のポインタ + # + # @else + # + # @brief Get a pointer of a LocalService + # + # This operation returnes a pointer to the LocalService + # which has the specified id. If the specified id is + # NULL pointer or the specified id does not exist in the + # ServiceProfile list, NULL pointer will be returned. + # + # @param id ID of a LocalService + # @return a pointer which has the specified id + # + # @endif + # ::RTM::LocalServiceBase* getService(const char* id); + + def getService(self, id): + for svc_ in self._services: + if svc_.getProfile().name == id: + return svc_ + return None + + ## + # @if jp + # @brief SDO service provider をセットする + # + # TODO: Documentation + # + # @else + # @brief Set a SDO service provider + # + # TODO: Documentation + # + # @endif + # bool addLocalService(::RTM::LocalServiceBase* service); + + def addLocalService(self, service): + global services_mutex + if not service: + self._rtcout.RTC_ERROR( + "Invalid argument: addLocalService(service == NULL)") + return False + self._rtcout.RTC_TRACE("LocalServiceAdmin.addLocalService(%s)", + service.getProfile().name) + guard_ = OpenRTM_aist.ScopedLock(services_mutex) + self._services.append(service) del guard_ return True - del guard_ - return False - - - ## - # @if jp - # - # @brief LocalService Service - # - # id ǻꤵ줿IDLocalService Υݥ󥿤롣id - # NULL ݥ󥿤ξ硢ꤵ줿 id ˳ServiceProfile ¸ - # ߤʤ硢NULL֤ - # - # @param id LocalService ID - # @return ꤵ줿 id LocalService Υݥ - # - # @else - # - # @brief Get a pointer of a LocalService - # - # This operation returnes a pointer to the LocalService - # which has the specified id. If the specified id is - # NULL pointer or the specified id does not exist in the - # ServiceProfile list, NULL pointer will be returned. - # - # @param id ID of a LocalService - # @return a pointer which has the specified id - # - # @endif - # ::RTM::LocalServiceBase* getService(const char* id); - def getService(self, id): - for svc_ in self._services: - if svc_.getProfile().name == id: - return svc_ - return None - - - ## - # @if jp - # @brief SDO service provider 򥻥åȤ - # - # TODO: Documentation - # - # @else - # @brief Set a SDO service provider - # - # TODO: Documentation - # - # @endif - # bool addLocalService(::RTM::LocalServiceBase* service); - def addLocalService(self, service): - global services_mutex - if not service: - self._rtcout.RTC_ERROR("Invalid argument: addLocalService(service == NULL)") - return False - self._rtcout.RTC_TRACE("LocalServiceAdmin.addLocalService(%s)", - service.getProfile().name) - guard_ = OpenRTM_aist.ScopedLock(services_mutex) - self._services.append(service) - del guard_ - return True - - - ## - # @if jp - # @brief LocalService - # - # TODO: Documentation - # - # @else - # @brief Remove a LocalService - # - # TODO: Documentation - # - # @endif - # bool removeLocalService(const std::string name); - def removeLocalService(self, name): - global services_mutex - self._rtcout.RTC_TRACE("removeLocalService(%s)", name) - guard_ = OpenRTM_aist.ScopedLock(services_mutex) - - for (i,svc_) in enumerate(self._services): - if name == svc_.getProfile().name: - svc_.finalize() - self._factory.deleteObject(svc_) - del self._services[i] - self._rtcout.RTC_INFO("SDO service has been deleted: %s", name) + + ## + # @if jp + # @brief LocalService を削除する + # + # TODO: Documentation + # + # @else + # @brief Remove a LocalService + # + # TODO: Documentation + # + # @endif + # bool removeLocalService(const std::string name); + + def removeLocalService(self, name): + global services_mutex + self._rtcout.RTC_TRACE("removeLocalService(%s)", name) + guard_ = OpenRTM_aist.ScopedLock(services_mutex) + + for (i, svc_) in enumerate(self._services): + if name == svc_.getProfile().name: + svc_.finalize() + del self._services[i] + self._rtcout.RTC_INFO( + "SDO service has been deleted: %s", name) + del guard_ + return True + self._rtcout.RTC_WARN("Specified SDO service not found: %s", name) del guard_ - return True; - self._rtcout.RTC_WARN("Specified SDO service not found: %s", name) - del guard_ - return False - - - ## - # @if jp - # @brief ꤵ줿IDͭɤå - # @else - # @brief Check if specified ID is enabled - # @endif - # bool isEnabled(const std::string& id, const coil::vstring& enabled); - def isEnabled(self, id, enabled): - if id in enabled: - self._rtcout.RTC_DEBUG("Local service %s is enabled.", id) - return True - self._rtcout.RTC_DEBUG("Local service %s is not enabled.", id) - return False - - - ## - # @if jp - # @brief ꤵ줿IDǤ¸ߤ뤫ɤå - # @else - # @brief Check if specified ID is existing - # @endif - # bool notExisting(const std::string& id); - def notExisting(self, id): - for svc_ in self._services: - if svc_.getProfile().name == id: - self._rtcout.RTC_WARN("Local service %s already exists.", id) return False - self._rtcout.RTC_DEBUG("Local service %s does not exist.", id) - return True - - def instance(): - global localserviceadmin - global services_mutex - - if localserviceadmin is None: - guard_ = OpenRTM_aist.ScopedLock(services_mutex) - if localserviceadmin is None: - localserviceadmin = LocalServiceAdmin() - del guard_ - return localserviceadmin - - instance = staticmethod(instance) + + ## + # @if jp + # @brief 指定されたIDが有効かどうかチェックする + # @else + # @brief Check if specified ID is enabled + # @endif + # bool isEnabled(const std::string& id, const coil::vstring& enabled); + + def isEnabled(self, id, enabled): + if id in enabled: + self._rtcout.RTC_DEBUG("Local service %s is enabled.", id) + return True + self._rtcout.RTC_DEBUG("Local service %s is not enabled.", id) + return False + + ## + # @if jp + # @brief 指定されたIDがすでに存在するかどうかチェックする + # @else + # @brief Check if specified ID is existing + # @endif + # bool notExisting(const std::string& id); + + def notExisting(self, id): + for svc_ in self._services: + if svc_.getProfile().name == id: + self._rtcout.RTC_WARN("Local service %s already exists.", id) + return False + self._rtcout.RTC_DEBUG("Local service %s does not exist.", id) + return True + + def instance(): + global localserviceadmin + global services_mutex + + if localserviceadmin is None: + guard_ = OpenRTM_aist.ScopedLock(services_mutex) + if localserviceadmin is None: + localserviceadmin = LocalServiceAdmin() + del guard_ + return localserviceadmin + + instance = staticmethod(instance) diff --git a/OpenRTM_aist/LocalServiceBase.py b/OpenRTM_aist/LocalServiceBase.py index e4018d4e..38275bdf 100644 --- a/OpenRTM_aist/LocalServiceBase.py +++ b/OpenRTM_aist/LocalServiceBase.py @@ -1,5 +1,5 @@ #!/usr/bin/env python -# -*- coding: euc-jp -*- +# -*- coding: utf-8 -*- ## # @file LocalServiceBase.py @@ -21,128 +21,130 @@ ## # @if jp -# @brief LocalServiceΥץեǡ +# @brief LocalServiceのプロファイルデータ # @else # @brief Profile data structure of LocalService # @endif + + class LocalServiceProfile: - """ - """ + """ + """ - def __init__(self): - ## - # @if jp - # @brief LocalServiceΥӥ̾ - # @else - # @brief The name of LocalService - # @endif - self.name = "" + def __init__(self): + ## + # @if jp + # @brief LocalServiceのサービス名 + # @else + # @brief The name of LocalService + # @endif + self.name = "" - ## - # @if jp - # @brief LocalServiceθͭID - # @else - # @brief The unique ID of LocalService - # @endif - self.uuid = "" + ## + # @if jp + # @brief LocalServiceの固有ID + # @else + # @brief The unique ID of LocalService + # @endif + self.uuid = "" - ## - # @if jp - # @brief LocalServiceΥץѥƥ - # @else - # @brief Properties of LocalService - # @endif - self.properties = None + ## + # @if jp + # @brief LocalServiceのプロパティ + # @else + # @brief Properties of LocalService + # @endif + self.properties = None - ## - # @if jp - # @brief LocalServiceΥݥ - # @else - # @brief The pointer to LocalService - # @endif - self.service = None + ## + # @if jp + # @brief LocalServiceのポインタ + # @else + # @brief The pointer to LocalService + # @endif + self.service = None - return + return ## # @if jp # -# @brief LocalService쥯饹 +# @brief LocalService 基底クラス # -# Local Service Ȥ RT-MiddlewareΥޥ͡ǡdzƼ掠 -# 󶡤뤿λȤߤǤ롣Local ServiceˤϤĤΥ桼 -# ͤ롣 +# Local Service とは RT-Middlewareのマネージャデーモン内で各種サービ +# スを提供するための仕組みである。Local Serviceにはいくつかのユース +# ケースが考えられる。 # -# 1. RTCåФƥӥ󶡤롣ݡͥȤγ -# ȯԤϡФơLocal ServiceΥ󥹥󥹤ؤλȤ -# ơΥӥѤ뤳ȤǤ롣 +# 1. RTCの内部ロジックに対してサービスを提供する。コンポーネントの開 +# 発者は、一定の艇順を経て、Local Serviceのインスタンスへの参照を得 +# て、このサービスを利用することができる。 # -# 2. ޥ͡˵ǽɲä뤿ΥӥȤϡRTC̾ -# ϿCORBA͡ॵӥˡʥǥ쥯ȥꥵ -# ֥ɥ㥹Ȥˤ̾εǽʤɤ򿷤ʵǽޥ͡ -# ɲä뤿Ѥ뤳ȤǤ롣ޥ͡ˤϡ͡ʥ -# ФեåѰդƤꡢѤ뤳Ȥǡޥ͡ -# ͡ʥ٥ȤФƥ򵯤ȤǤ롣 +# 2. マネージャ等に機能を追加するためのサービス。たとえは、RTCの名前 +# を登録するCORBAネームサービスの代わりに、新たなディレクトリサービ +# スやブロードキャストによる名前通知機能などを新たな機能をマネージャ +# に追加するために利用することができる。マネージャには、様々なアクショ +# ンに対するフックが用意されており、これを利用することで、マネージャ +# の様々なイベントに対してアクションを起こすことができる。 # -# 3. ޥ͡ϼȤΥӥʳղŪ˳Фƥӥ -# 󶡤뵡ǽͭ롣CORBAͳǡεǽȤ -# ХǥХ꥽ΥޥͥȵǽФƥˡ -# 롣ӥΥ󥹥󥹲ˡޥ͡Фơޥ͡ -# ӥȤϿ뤳ȤǡΥդ뤳Ȥ -# Ǥ褦ˤʤ롣 +# 3. マネージャは自身のサービス以外に付加的に外部に対してサービスを +# 提供する機能を有する。外部からCORBA経由で、ローカルの機能、たとえ +# ばデバイスやリソースのマネジメント機能に対してアクセスする方法を提 +# 供する。サービスのインスタンス化後に、マネージャに対して、マネージャ +# サービスとして登録することで、外部からのアクセスを受け付けることが +# できるようになる。 # -# Local Service ϥ⥸塼Ȥƥɤ졢̾ͣΥ󥹥 -# 롣ʤLocalService ϥ󥰥ȥȤƼ -# 롣󥹥󥹲줿ӥϥӥꥹȤϿ졢RTC -# ̾UUIDˤäƥ󥹥󥹤λȤꤹ뤳ȤǤ롣 +# Local Service はモジュールとしてロードされ、通常唯一のインスタンス +# が生成される。すなわち、LocalService はシングルトンとして実装され +# る。インスタンス化されたサービスはサービスリストに登録され、RTC等 +# からは名前やUUIDによってインスタンスの参照を入手することができる。 # -# Υ֥ȤΥ饤եϰʲ̤ꡣ +# このオブジェクトのライフサイクルは以下の通り。 # -# -# ֥Ȥ̾֥ͭ (so, DLL) Ȥƥѥ롦 -# 󥯤롣 -# -# ޥ͡Фƥɤȥ⥸塼ؿˤꥪ -# ȥեȥ꤬LocalServiceFactory ФϿ롣 -# ϿΥˤUUID̾Ѥ졢ˤꥵӥ̤ -# 롣 -# -# rtc.confΥե졼ˤꡢͭ뤳Ȥ -# ꤵƤ륵ӥץХϡRTCεưƱ˥ -# 󥹲롣 -# -# 󥹥󥹲塢ؿ init() ƤФ롣ˤ -# ӥΤΥե졼󥪥ץ coil::Property -# Ϥ롣 -# -# ޥ͡㥵ӥڥ졼 reinit ƤФȡ٤Ƥ -# Local Service reinit ƤӽФ졢줿ե졼 -# ɤ߹ޤ롣 -# -# ޥ͡λˤϡ٤Ƥ Local Service finalizeƤ -# Ф졢ΤΤǡǥ꥽βʤɽλ -# +# -# オブジェクトは通常、共有オブジェクト (so, DLL) としてコンパイル・ +# リンクされる。 +# -# マネージャに対してロードされるとモジュール初期化関数によりオブ +# ジェクトファクトリが、LocalServiceFactory に対して登録される。 +# 登録のキーにはUUIDと名前が利用され、これによりサービスが区別さ +# れる。 +# -# rtc.conf等のコンフィギュレーション指定により、有効化することが +# 指定されているサービスインプロバイダは、RTCの起動と同時にインス +# タンス化される。 +# -# インスタンス化後、初期化関数 init() が呼ばれる。引数には当該サー +# ビスのためのコンフィギュレーションオプションが coil::Propertyに +# より渡される。 +# -# マネージャサービスオペレーション reinit が呼ばれると、すべての +# Local Service お reinit が呼び出され、更新されたコンフィギュレー +# ション情報が読み込まれる。 +# -# マネージャ解体時には、すべての Local Service の finalizeが呼び +# 出され、解体されるので、ここでリソースの解放など終了処理を行 +# う。 # -# Υ饹μäƤϡʤȤʲν貾۴ؿ -# ɬפ롣 +# このクラスの実装に当たっては、少なくとも以下の純粋仮想関数を実装す +# る必要がある。 # -# - init(): ؿͿ줿 RTObject ServiceProfile -# 顢֥Ȥ롣 -# - reinit(): ƽؿServiceProfile 󹹿ΤƱ -# IDǸƤӽФ뤳Ȥͭ뤬κݤˤδؿ -# ServiceProfile ȤȤ˸ƤӽФ롣ؿǤϡѹʤ -# ƽ롣 -# - getProfile(): ꤵ줿ץե֤ؿ -# - finalize(): λ󥷥塼ޤǥåݤ˸ƤӽФ -# ؿؿǤϽλ롣 +# - init(): 初期化関数。与えられた RTObject および ServiceProfile か +# ら、当該オブジェクトを初期化する。 +# - reinit(): 再初期化関数。ServiceProfile は設定情報更新のため同一 +# IDで呼び出されることが有るが、その際にこの関数が新たな +# ServiceProfile とともに呼び出される。関数内では、設定の変更など +# 再初期化処理を実装する。 +# - getProfile(): 設定されたプロファイルを返す関数。 +# - finalize(): 終了処理。コンシューマがデタッチされる際に呼び出され +# る関数。関数内では終了処理を実装する。 # -# LocalService ̾ﶦ֥ͭȤȤƥѥ롦 -# 롣֥ͭȤΥȥݥȤ̾拾ѥ뤵줿ե -# ̾ basename + "Init" ˤƤʲˡ饹̾ե -# ̾ȥݥȴؿ̾ο侩򼨤 +# LocalService は通常共有オブジェクトとしてコンパイル・リンク +# される。共有オブジェクトのエントリポイントは通常コンパイルされたファ +# イル名の basename + "Init" にしておく。以下に、クラス名、ファイル +# 名、エントリポイント関数名の推奨例を示す。 # -# - 饹̾: MyLocalService -# - ե̾: MyLocalService.h. MyLocalService.cpp -# - ֥ͭ̾: MyLocalService.so (or DLL) -# - ȥݥȴؿ̾: MyLocalServiceInit() +# - 実装クラス名: MyLocalService +# - ファイル名: MyLocalService.h. MyLocalService.cpp +# - 共有オブジェクト名: MyLocalService.so (or DLL) +# - エントリポイント関数名: MyLocalServiceInit() # -# ȥݥȴؿ̾ʲΤ褦ˡLocalServiceFactory -# 󥷥塼ޤΥեȥ (ȲΥե󥯥) Ͽʲ -# 褦ʴؿˤʤ롣 +# エントリポイント関数は通常以下のように、LocalServiceFactory +# に当該コンシューマのファクトリ (と解体ファンクタ) を登録する以下の +# ような関数になる。 # #
 # extern "C"
@@ -153,8 +155,6 @@ def __init__(self):
 #       = RTC::LocalServiceFactory::instance();
 #     factory.addFactory(::RTC::MyLocalSerivce::name,
 #                        ::coil::Creator< ::RTC::LocalServiceBase,
-#                        ::RTC::MyLocalService>,
-#                        ::coil::Destructor< ::RTC::LocalServiceBase,
 #                        ::RTC::MyLocalService>);
 #   }
 # };
@@ -163,108 +163,111 @@ def __init__(self):
 # @else
 #
 # @endif
+
+
 class LocalServiceBase:
-  """
-  """
+    """
+    """
 
-  ##
-  # @if jp
-  # @brief LocalService饹νؿ
-  #
-  # Υ֥ȤνԤLocalService 硢
-  # ϡinit()ؿˤͿ롣
-  #
-  # @param profile Ϳ줿 LocalServiceProfile
-  # @return Ϳ줿 LocalServiceProfile ξ false
-  #
-  # @else
-  # @brief Initialization function of the LocalService class
-  #
-  # @endif
-  # virtual bool
-  # init(const coil::Properties& props) = 0;
-  def init(self, props):
-    pass
+    ##
+    # @if jp
+    # @brief LocalServiceクラスの初期化関数
+    #
+    # このオブジェクトの初期化を行う。LocalService を実装する場合、外
+    # 部からの設定情報は、このinit()関数により与えられる。
+    #
+    # @param profile 外部から与えられた LocalServiceProfile
+    # @return 与えられた LocalServiceProfile が不正の場合 false
+    #
+    # @else
+    # @brief Initialization function of the LocalService class
+    #
+    # @endif
+    # virtual bool
+    # init(const coil::Properties& props) = 0;
+    def init(self, props):
+        pass
+
+    ##
+    # @if jp
+    # @brief LocalServiceクラスの再初期化関数
+    #
+    # TODO: ドキュメント作成
+    #
+    # @param profile 新たに与えられた LocalServiceProfile
+    # @return 不正な LocalServiceProfile が与えられた場合は false
+    #
+    # @else
+    # @brief Reinitialization function of the LocalService class
+    #
+    # TODO: Documentation
+    #
+    # @endif
+    # virtual bool
+    # reinit(const coil::Properties& props) = 0;
 
+    def reinit(self, props):
+        pass
 
-  ##
-  # @if jp
-  # @brief LocalService饹κƽؿ
-  #
-  # TODO: ɥȺ
-  #
-  # @param profile Ϳ줿 LocalServiceProfile
-  # @return  LocalServiceProfile Ϳ줿 false
-  #
-  # @else
-  # @brief Reinitialization function of the LocalService class
-  #
-  # TODO: Documentation
-  #
-  # @endif
-  # virtual bool
-  # reinit(const coil::Properties& props) = 0;
-  def reinit(self, props):
-    pass
-    
+    ##
+    # @if jp
+    # @brief LocalServiceProfile を返す
+    #
+    # init()/reinit()で与えられた LocalServiceProfile は通常オブジェク
+    # ト内で保持される。この関数では保持されている ServiceProfile を返
+    # す。
+    #
+    # @return このオブジェクトが保持している LocalServiceProfile
+    #
+    # @else
+    # @brief Getting LocalServiceProfile
+    #
+    # TODO: Documentation
+    #
+    # @endif
+    # virtual const LocalServiceProfile&
+    # getProfile() const = 0;
+
+    def getProfile(self):
+        pass
+
+    ##
+    # @if jp
+    # @brief 終了処理
+    #
+    # LocalService が終了する際に呼び出される終了処理用関数。当該オブ
+    # ジェクトが保持するリソースを解放するなどの処理を行う。
+    #
+    # @else
+    # @brief Finalization
+    #
+    # TODO: Documentation
+    #
+    # @endif
+    # virtual void
+    # finalize() = 0;
 
-  ##
-  # @if jp
-  # @brief LocalServiceProfile ֤
-  #
-  # init()/reinit()Ϳ줿 LocalServiceProfile ̾索֥
-  # ݻ롣δؿǤݻƤ ServiceProfile 
-  # 
-  #
-  # @return Υ֥ȤݻƤ LocalServiceProfile
-  #
-  # @else
-  # @brief Getting LocalServiceProfile
-  #
-  # TODO: Documentation
-  #
-  # @endif
-  # virtual const LocalServiceProfile&
-  # getProfile() const = 0;
-  def getProfile(self):
-    pass
-    
+    def finalize(self):
+        pass
 
-  ##
-  # @if jp
-  # @brief λ
-  #
-  # LocalService λݤ˸ƤӽФ뽪λѴؿ
-  # Ȥݻ꥽ʤɤνԤ
-  #
-  # @else
-  # @brief Finalization
-  #
-  # TODO: Documentation
-  #
-  # @endif
-  # virtual void
-  # finalize() = 0;
-  def finalize(self):
-    pass
 
 localservicefactory = None
 
-class LocalServiceFactory(OpenRTM_aist.Factory,LocalServiceBase):
-  def __init__(self):
-    OpenRTM_aist.Factory.__init__(self)
-    return
 
-  def __del__(self):
-    pass
+class LocalServiceFactory(OpenRTM_aist.Factory, LocalServiceBase):
+    def __init__(self):
+        OpenRTM_aist.Factory.__init__(self)
+        return
 
-  def instance():
-    global localservicefactory
+    def __del__(self):
+        pass
 
-    if localservicefactory is None:
-      localservicefactory = LocalServiceFactory()
+    def instance():
+        global localservicefactory
 
-    return localservicefactory
+        if localservicefactory is None:
+            localservicefactory = LocalServiceFactory()
 
-  instance = staticmethod(instance)
+        return localservicefactory
 
+    instance = staticmethod(instance)
diff --git a/OpenRTM_aist/LogstreamBase.py b/OpenRTM_aist/LogstreamBase.py
index 8066efcc..5ea3fc48 100644
--- a/OpenRTM_aist/LogstreamBase.py
+++ b/OpenRTM_aist/LogstreamBase.py
@@ -1,5 +1,5 @@
 #!/usr/bin/env python
-# -*- coding: euc-jp -*-
+# -*- coding: utf-8 -*-
 
 
 ##
@@ -15,7 +15,6 @@
 # $Id$
 
 
-
 import OpenRTM_aist
 
 
@@ -23,9 +22,9 @@
 # @if jp
 # @class LogstreamBase
 #
-# @brief LogstreamBase 饹
+# @brief LogstreamBase クラス
+#
 #
-# 
 #
 #
 # @else
@@ -37,151 +36,149 @@
 # @endif
 #
 class LogstreamBase:
-  """
-  """
-
-  ##
-  # @if jp
-  # @brief 󥹥ȥ饯
-  #
-  # 󥹥ȥ饯
-  #
-  # @else
-  # @brief Constructor
-  #
-  # Constructor
-  #
-  # @endif
-  #
-  def __init__(self):
-    pass
-
-  ##
-  # @if jp
-  # @brief ǥȥ饯
-  #
-  # ǥȥ饯
-  #
-  # @else
-  # @brief Destructor
-  #
-  # Destructor
-  #
-  # @endif
-  #
-  def __del__(self):
-    pass
-    
-
-
-  ##
-  # @if jp
-  # @brief 
-  #
-  # Logstream饹γƼԤ饹ǤϡͿ줿
-  # PropertiesɬפʾƳƼԤ
-  #
-  # @param self
-  # @param prop 
-  # @return
-  #
-  # @else
-  # @brief Initializing configuration
-  #
-  # This operation would be called to configure in initialization.
-  # In the concrete class, configuration should be performed
-  # getting appropriate information from the given Properties data.
-  #
-  # @param self
-  # @param prop Configuration information
-  # @return
-  #
-  # @endif
-  #
-  def init(self, prop):
-    return False
-
-
-  ##
-  # @if jp
-  # @brief ʸϤ
-  #
-  #
-  # @param self
-  # @param msgϤʸ
-  # @param level ٥
-  # @return
-  #
-  # @else
-  # @brief 
-  #
-  #
-  # @param self
-  # @param msg
-  # @param level
-  # @return
-  #
-  # @endif
-  #
-  def log(self, msg, level, name):
-    return False
-
-
-
-  ##
-  # @if jp
-  # @brief ٥
-  #
-  #
-  # @param self
-  # @param level ٥
-  # @return
-  #
-  # @else
-  # @brief 
-  #
-  #
-  # @param self
-  # @param level
-  # @return
-  #
-  # @endif
-  #
-  def setLogLevel(self, level):
-    pass
-
-
-  ##
-  # @if jp
-  # @brief λ
-  #
-  #
-  # @param self
-  # @return
-  #
-  # @else
-  # @brief 
-  #
-  #
-  # @param self
-  # @return
-  #
-  # @endif
-  #
-  def shutdown(self):
-    return True
-
-
+    """
+    """
+
+    ##
+    # @if jp
+    # @brief コンストラクタ
+    #
+    # コンストラクタ
+    #
+    # @else
+    # @brief Constructor
+    #
+    # Constructor
+    #
+    # @endif
+    #
+    def __init__(self):
+        pass
+
+    ##
+    # @if jp
+    # @brief デストラクタ
+    #
+    # デストラクタ
+    #
+    # @else
+    # @brief Destructor
+    #
+    # Destructor
+    #
+    # @endif
+    #
+    def __del__(self):
+        pass
+
+    ##
+    # @if jp
+    # @brief 設定初期化
+    #
+    # Logstreamクラスの各種設定を行う。実装クラスでは、与えられた
+    # Propertiesから必要な情報を取得して各種設定を行う。
+    #
+    # @param self
+    # @param prop 設定情報
+    # @return
+    #
+    # @else
+    # @brief Initializing configuration
+    #
+    # This operation would be called to configure in initialization.
+    # In the concrete class, configuration should be performed
+    # getting appropriate information from the given Properties data.
+    #
+    # @param self
+    # @param prop Configuration information
+    # @return
+    #
+    # @endif
+    #
+
+    def init(self, prop):
+        return False
+
+    ##
+    # @if jp
+    # @brief 指定文字列をログ出力する
+    #
+    #
+    # @param self
+    # @param msg ログ出力する文字列
+    # @param level ログレベル
+    # @return
+    #
+    # @else
+    # @brief
+    #
+    #
+    # @param self
+    # @param msg
+    # @param level
+    # @return
+    #
+    # @endif
+    #
+
+    def log(self, msg, level, name):
+        return False
+
+    ##
+    # @if jp
+    # @brief ログレベル設定
+    #
+    #
+    # @param self
+    # @param level ログレベル
+    # @return
+    #
+    # @else
+    # @brief
+    #
+    #
+    # @param self
+    # @param level
+    # @return
+    #
+    # @endif
+    #
+
+    def setLogLevel(self, level):
+        pass
+
+    ##
+    # @if jp
+    # @brief 終了処理
+    #
+    #
+    # @param self
+    # @return
+    #
+    # @else
+    # @brief
+    #
+    #
+    # @param self
+    # @return
+    #
+    # @endif
+    #
+
+    def shutdown(self):
+        return True
 
 
 logstreamfactory = None
 
+
 class LogstreamFactory(OpenRTM_aist.Factory):
-  def __init__(self):
-    OpenRTM_aist.Factory.__init__(self)
-  def instance():
-    global logstreamfactory
-    if logstreamfactory is None:
-      logstreamfactory = LogstreamFactory()
-    return logstreamfactory
-  instance = staticmethod(instance)
+    def __init__(self):
+        OpenRTM_aist.Factory.__init__(self)
+
+    def instance():
+        global logstreamfactory
+        if logstreamfactory is None:
+            logstreamfactory = LogstreamFactory()
+        return logstreamfactory
+    instance = staticmethod(instance)
diff --git a/OpenRTM_aist/LogstreamFile.py b/OpenRTM_aist/LogstreamFile.py
index 8e536d29..9f1e29e0 100644
--- a/OpenRTM_aist/LogstreamFile.py
+++ b/OpenRTM_aist/LogstreamFile.py
@@ -1,5 +1,5 @@
 #!/usr/bin/env python
-# -*- coding: euc-jp -*-
+# -*- coding: utf-8 -*-
 
 
 ##
@@ -15,21 +15,19 @@
 # $Id$
 
 
-
 import OpenRTM_aist
 import OpenRTM_aist.StringUtil
 import logging
 import logging.handlers
 
 
-
 ##
 # @if jp
 # @class LogstreamFile
 #
-# @brief LogstreamFile 饹
+# @brief LogstreamFile クラス
+#
 #
-# 
 #
 #
 # @else
@@ -41,308 +39,291 @@
 # @endif
 #
 class LogstreamFile(OpenRTM_aist.LogstreamBase):
-  """
-  """
-  s_logger = None
-  ##
-  # @if jp
-  # @brief 󥹥ȥ饯
-  #
-  # 󥹥ȥ饯
-  #
-  # @else
-  # @brief Constructor
-  #
-  # Constructor
-  #
-  # @endif
-  #
-  def __init__(self):
-    OpenRTM_aist.LogstreamBase.__init__(self)
-    self.handlers = []
-
-  ##
-  # @if jp
-  # @brief ǥȥ饯
-  #
-  # ǥȥ饯
-  #
-  # @else
-  # @brief Destructor
-  #
-  # Destructor
-  #
-  # @endif
-  #
-  def __del__(self):
-    pass
-    
-
-
-  ##
-  # @if jp
-  # @brief 
-  #
-  # Logstream饹γƼԤ饹ǤϡͿ줿
-  # PropertiesɬפʾƳƼԤ
-  #
-  # @param self
-  # @param prop 
-  # @return
-  #
-  # @else
-  # @brief Initializing configuration
-  #
-  # This operation would be called to configure in initialization.
-  # In the concrete class, configuration should be performed
-  # getting appropriate information from the given Properties data.
-  #
-  # @param self
-  # @param prop Configuration information
-  # @return
-  #
-  # @endif
-  #
-  def init(self, prop):
-    self.logger = logging.getLogger("file")
-    
-    
-    if LogstreamFile.s_logger is None:
-      LogstreamFile.s_logger = self
-      
-      logging.PARANOID  = logging.DEBUG - 3
-      logging.VERBOSE   = logging.DEBUG - 2
-      logging.TRACE     = logging.DEBUG - 1
-      logging.FATAL     = logging.ERROR + 1
-
-      logging.addLevelName(logging.PARANOID,  "PARANOID")
-      logging.addLevelName(logging.VERBOSE,   "VERBOSE")
-      logging.addLevelName(logging.TRACE,     "TRACE")
-      logging.addLevelName(logging.FATAL,     "FATAL")
-      
-    files = prop.getProperty("file_name")
-    files = [s.strip() for s in files.split(",")]
-
-    
-
-    
-
-    for f in files:
-      self.addHandler(f)
-      
-    if len(self.handlers) == 0:
-      return False
-
-        
-    return True
-
-
-  ##
-  # @if jp
-  # @brief ϥϥɥɲ
-  #
-  #
-  # @param self
-  # @param f ϥե̾⤷stdout
-  # @return
-  #
-  # @else
-  # @brief 
-  #
-  #
-  # @param self
-  # @param f 
-  # @return
-  #
-  # @endif
-  #
-  def addHandler(self, f):
-    formatter = logging.Formatter('%(asctime)s %(name)s %(levelname)s %(message)s')
-    tmp = [f]
-    OpenRTM_aist.eraseHeadBlank(tmp)
-    OpenRTM_aist.eraseTailBlank(tmp)
-    f = tmp[0]
-    handlers = self.logger.handlers
-    for h in handlers:
-      if h.get_name() == f:
-        return False
-
-    tmp = [f]
-    fname = OpenRTM_aist.StringUtil.normalize(tmp)
-      
-    if fname == "stdout":
-      ch = logging.StreamHandler()
-      ch.setLevel(logging.NOTSET)
-      ch.setFormatter(formatter)
-      ch.set_name(f)
-      self.logger.addHandler(ch)
-      self.handlers.append(ch)
-      return True
-
-    else:
-      try:
-        fhdlr = logging.FileHandler(fname)
-        mhdlr = logging.handlers.MemoryHandler(1024,logging.NOTSET, fhdlr)
-        fhdlr.setFormatter(formatter)
-        mhdlr.set_name(f)
-        self.logger.addHandler(mhdlr)
-        self.handlers.append(mhdlr)
-        self.logger.setLevel(logging.NOTSET)
-      except:
+    """
+    """
+    s_logger = None
+    ##
+    # @if jp
+    # @brief コンストラクタ
+    #
+    # コンストラクタ
+    #
+    # @else
+    # @brief Constructor
+    #
+    # Constructor
+    #
+    # @endif
+    #
+
+    def __init__(self):
+        OpenRTM_aist.LogstreamBase.__init__(self)
+        self.handlers = []
+
+    ##
+    # @if jp
+    # @brief デストラクタ
+    #
+    # デストラクタ
+    #
+    # @else
+    # @brief Destructor
+    #
+    # Destructor
+    #
+    # @endif
+    #
+    def __del__(self):
         pass
-      
-      return True
-
-  ##
-  # @if jp
-  # @brief ʸϤ
-  #
-  #
-  # @param self
-  # @param msgϤʸ
-  # @param level ٥
-  # @param name ν̾
-  # @return
-  #
-  # @else
-  # @brief 
-  #
-  #
-  # @param self
-  # @param msg
-  # @param level
-  # @param name 
-  # @return
-  #
-  # @endif
-  #
-  def log(self, msg, level, name):
-    log = self.getLogger(name)
-    if level == OpenRTM_aist.Logger.FATAL:
-      log.log(logging.FATAL,msg)
-    elif level == OpenRTM_aist.Logger.ERROR:
-      log.error(msg)
-    elif level == OpenRTM_aist.Logger.WARN:
-      log.warning(msg)
-    elif level == OpenRTM_aist.Logger.INFO:
-      log.info(msg)
-    elif level == OpenRTM_aist.Logger.DEBUG:
-      log.debug(msg)
-    elif level == OpenRTM_aist.Logger.TRACE:
-      log.log(logging.TRACE,msg)
-    elif level == OpenRTM_aist.Logger.VERBOSE:
-      log.log(logging.VERBOSE,msg)
-    elif level == OpenRTM_aist.Logger.PARANOID:
-      log.log(logging.PARANOID,msg)
-    else:
-      return False
-    return True
-    
-
-
-  ##
-  # @if jp
-  # @brief ٥
-  #
-  #
-  # @param self
-  # @param level ٥
-  # @return
-  #
-  # @else
-  # @brief 
-  #
-  #
-  # @param self
-  # @param level
-  # @return
-  #
-  # @endif
-  #
-  def setLogLevel(self, level):
-    if level == OpenRTM_aist.Logger.INFO:
-      self.logger.setLevel(logging.INFO)
-    elif level == OpenRTM_aist.Logger.FATAL:
-      self.logger.setLevel(logging.FATAL)
-    elif level == OpenRTM_aist.Logger.ERROR:
-      self.logger.setLevel(logging.ERROR)
-    elif level == OpenRTM_aist.Logger.WARN:
-      self.logger.setLevel(logging.WARNING)
-    elif level == OpenRTM_aist.Logger.DEBUG:
-      self.logger.setLevel(logging.DEBUG)
-    elif level == OpenRTM_aist.Logger.SILENT:
-      self.logger.setLevel(logging.NOTSET)
-    elif level == OpenRTM_aist.Logger.TRACE:
-      self.logger.setLevel(logging.TRACE)
-    elif level == OpenRTM_aist.Logger.VERBOSE:
-      self.logger.setLevel(logging.VERBOSE)
-    elif level == OpenRTM_aist.Logger.PARANOID:
-      self.logger.setLevel(logging.PARANOID)
-    else:
-      self.logger.setLevel(logging.INFO)
-
-
-
-  ##
-  # @if jp
-  # @brief λ
-  #
-  #
-  # @param self
-  # @return
-  #
-  # @else
-  # @brief 
-  #
-  #
-  # @param self
-  # @return
-  #
-  # @endif
-  #
-  def shutdown(self):
-    for h in self.handlers:
-      logging.Handler.close(h)
-      self.logger.removeHandler(h)
-    
-    LogstreamFile.s_logger = None
-    self.handlers = []
-    return True
-
-  ##
-  # @if jp
-  # @brief μ
-  #
-  #
-  # @param self
-  # @param name ν̾
-  # @return
-  #
-  # @else
-  # @brief 
-  #
-  #
-  # @param self
-  # @param name 
-  # @return
-  #
-  # @endif
-  #
-  def getLogger(self, name):
-    if name:
-      return logging.getLogger("file."+name)
-    else:
-      return self.logger
-
-
-
-
-
-      
 
+    ##
+    # @if jp
+    # @brief 設定初期化
+    #
+    # Logstreamクラスの各種設定を行う。実装クラスでは、与えられた
+    # Propertiesから必要な情報を取得して各種設定を行う。
+    #
+    # @param self
+    # @param prop 設定情報
+    # @return
+    #
+    # @else
+    # @brief Initializing configuration
+    #
+    # This operation would be called to configure in initialization.
+    # In the concrete class, configuration should be performed
+    # getting appropriate information from the given Properties data.
+    #
+    # @param self
+    # @param prop Configuration information
+    # @return
+    #
+    # @endif
+    #
+
+    def init(self, prop):
+        self.logger = logging.getLogger("file")
+
+        if LogstreamFile.s_logger is None:
+            LogstreamFile.s_logger = self
+
+            logging.PARANOID = logging.DEBUG - 3
+            logging.VERBOSE = logging.DEBUG - 2
+            logging.TRACE = logging.DEBUG - 1
+            logging.FATAL = logging.ERROR + 1
+
+            logging.addLevelName(logging.PARANOID, "PARANOID")
+            logging.addLevelName(logging.VERBOSE, "VERBOSE")
+            logging.addLevelName(logging.TRACE, "TRACE")
+            logging.addLevelName(logging.FATAL, "FATAL")
+
+        files = prop.getProperty("file_name")
+        files = [s.strip() for s in files.split(",")]
+
+        for f in files:
+            self.addHandler(f)
+
+        if not self.handlers:
+            return False
+
+        return True
+
+    ##
+    # @if jp
+    # @brief ログ出力ハンドラ追加
+    #
+    #
+    # @param self
+    # @param f ログ出力ファイル名、もしくはstdout
+    # @return
+    #
+    # @else
+    # @brief
+    #
+    #
+    # @param self
+    # @param f
+    # @return
+    #
+    # @endif
+    #
+
+    def addHandler(self, f):
+        formatter = logging.Formatter(
+            '%(asctime)s %(name)s %(levelname)s %(message)s')
+        f = OpenRTM_aist.eraseHeadBlank(f)
+        f = OpenRTM_aist.eraseTailBlank(f)
+        handlers = self.logger.handlers
+        for h in handlers:
+            if h.get_name() == f:
+                return False
+
+        fname = OpenRTM_aist.StringUtil.normalize(f)
+
+        if fname == "stdout":
+            ch = logging.StreamHandler()
+            ch.setLevel(logging.NOTSET)
+            ch.setFormatter(formatter)
+            ch.set_name(f)
+            self.logger.addHandler(ch)
+            self.handlers.append(ch)
+            return True
+
+        else:
+            try:
+                fhdlr = logging.FileHandler(fname)
+                mhdlr = logging.handlers.MemoryHandler(
+                    1024, logging.NOTSET, fhdlr)
+                fhdlr.setFormatter(formatter)
+                mhdlr.set_name(f)
+                self.logger.addHandler(mhdlr)
+                self.handlers.append(mhdlr)
+                self.logger.setLevel(logging.NOTSET)
+            except BaseException:
+                pass
+
+            return True
+
+    ##
+    # @if jp
+    # @brief 指定文字列をログ出力する
+    #
+    #
+    # @param self
+    # @param msg ログ出力する文字列
+    # @param level ログレベル
+    # @param name ログの出力名
+    # @return
+    #
+    # @else
+    # @brief
+    #
+    #
+    # @param self
+    # @param msg
+    # @param level
+    # @param name
+    # @return
+    #
+    # @endif
+    #
+    def log(self, msg, level, name):
+        log = self.getLogger(name)
+        if level == OpenRTM_aist.Logger.FATAL:
+            log.log(logging.FATAL, msg)
+        elif level == OpenRTM_aist.Logger.ERROR:
+            log.error(msg)
+        elif level == OpenRTM_aist.Logger.WARN:
+            log.warning(msg)
+        elif level == OpenRTM_aist.Logger.INFO:
+            log.info(msg)
+        elif level == OpenRTM_aist.Logger.DEBUG:
+            log.debug(msg)
+        elif level == OpenRTM_aist.Logger.TRACE:
+            log.log(logging.TRACE, msg)
+        elif level == OpenRTM_aist.Logger.VERBOSE:
+            log.log(logging.VERBOSE, msg)
+        elif level == OpenRTM_aist.Logger.PARANOID:
+            log.log(logging.PARANOID, msg)
+        else:
+            return False
+        return True
+
+    ##
+    # @if jp
+    # @brief ログレベル設定
+    #
+    #
+    # @param self
+    # @param level ログレベル
+    # @return
+    #
+    # @else
+    # @brief
+    #
+    #
+    # @param self
+    # @param level
+    # @return
+    #
+    # @endif
+    #
+
+    def setLogLevel(self, level):
+        if level == OpenRTM_aist.Logger.INFO:
+            self.logger.setLevel(logging.INFO)
+        elif level == OpenRTM_aist.Logger.FATAL:
+            self.logger.setLevel(logging.FATAL)
+        elif level == OpenRTM_aist.Logger.ERROR:
+            self.logger.setLevel(logging.ERROR)
+        elif level == OpenRTM_aist.Logger.WARN:
+            self.logger.setLevel(logging.WARNING)
+        elif level == OpenRTM_aist.Logger.DEBUG:
+            self.logger.setLevel(logging.DEBUG)
+        elif level == OpenRTM_aist.Logger.SILENT:
+            self.logger.setLevel(logging.NOTSET)
+        elif level == OpenRTM_aist.Logger.TRACE:
+            self.logger.setLevel(logging.TRACE)
+        elif level == OpenRTM_aist.Logger.VERBOSE:
+            self.logger.setLevel(logging.VERBOSE)
+        elif level == OpenRTM_aist.Logger.PARANOID:
+            self.logger.setLevel(logging.PARANOID)
+        else:
+            self.logger.setLevel(logging.INFO)
+
+    ##
+    # @if jp
+    # @brief 終了処理
+    #
+    #
+    # @param self
+    # @return
+    #
+    # @else
+    # @brief
+    #
+    #
+    # @param self
+    # @return
+    #
+    # @endif
+    #
+
+    def shutdown(self):
+        for h in self.handlers:
+            logging.Handler.close(h)
+            self.logger.removeHandler(h)
+
+        LogstreamFile.s_logger = None
+        self.handlers = []
+        return True
+
+    ##
+    # @if jp
+    # @brief ロガーの取得
+    #
+    #
+    # @param self
+    # @param name ログの出力名
+    # @return ロガー
+    #
+    # @else
+    # @brief
+    #
+    #
+    # @param self
+    # @param name
+    # @return
+    #
+    # @endif
+    #
+    def getLogger(self, name):
+        if name:
+            return logging.getLogger("file." + name)
+        else:
+            return self.logger
 
-def LogstreamFileInit():
-  OpenRTM_aist.LogstreamFactory.instance().addFactory("file",
-                                                      OpenRTM_aist.LogstreamFile,
-                                                      OpenRTM_aist.Delete)
 
+def LogstreamFileInit():
+    OpenRTM_aist.LogstreamFactory.instance().addFactory("file",
+                                                        OpenRTM_aist.LogstreamFile)
diff --git a/OpenRTM_aist/Macho.py b/OpenRTM_aist/Macho.py
index be158cfc..d63ac113 100644
--- a/OpenRTM_aist/Macho.py
+++ b/OpenRTM_aist/Macho.py
@@ -1,5 +1,5 @@
 #!/usr/bin/env python
-# -*- coding: euc-jp -*-
+# -*- coding: utf-8 -*-
 
 ##
 # @file Macho.py
@@ -14,858 +14,1031 @@
 #     All rights reserved.
 
 
-
 import types
 import OpenRTM_aist
 
 import threading
 
-class _EmptyBox:
-  def __init__(self):
-    pass
 
-_EmptyBox.theEmptyBox = _EmptyBox()
+class _EmptyBox:
+    def __init__(self):
+        pass
 
 
+_EmptyBox.theEmptyBox = _EmptyBox()
 
 
 class _KeyData:
-  def __init__(self):
-    self.instanceGenerator = None
-    self.childPredicate = None
-    self.name = None
-    self.id = 0
+    def __init__(self):
+        self.instanceGenerator = None
+        self.childPredicate = None
+        self.name = None
+        self.id = 0
 
 
 class _StateSpecification(object):
-  HISTORY = False
-  def __init__(self, instance):
-    self._myStateInstance = instance
-  def isChild(key):
-    return False
-  isChild = staticmethod(isChild)
-
-  def set_state_direct(self, S, *args):
-    return self.setStateDirect(S, *args)
-  
-  def setStateDirect(self, S, *args):
-    #global _theDefaultInitializer
-    m = self._myStateInstance.machine()
-    instance = S._getInstance(m, S.SUPER, S)
-    
-    instance.setHistory(0)
-    m.setPendingState(instance, _Initializer(*args))
-
-
-  def set_state(self, S, *args):
-    return self.setState(S, *args)
-  
-
-  def setState(self, S, *args):
-    #global _theDefaultInitializer
-    m = self._myStateInstance.machine()
-    instance = S._getInstance(m, S.SUPER, S)
-    m.setPendingState(instance, _Initializer(*args))
-
-  def setState0(self, S):
-    global _theDefaultInitializer
-    m = self._myStateInstance.machine()
-    instance = S._getInstance(m, S.SUPER, S)
-    m.setPendingState(instance, _theDefaultInitializer)
-
-
-  
-    
-  def setState1(self,S,p1):
-    m = self._myStateInstance.machine()
-    instance = S._getInstance(m, S.SUPER, S)
-    m.setPendingState(instance, _Initializer1(p1))
-    
-  def setState2(self,S,p1,p2):
-    m = self._myStateInstance.machine()
-    instance = S._getInstance(m, S.SUPER, S)
-    m.setPendingState(instance, _Initializer2(p1,p2))
-  def setState3(self,S,p1,p2,p3):
-    m = self._myStateInstance.machine()
-    instance = S._getInstance(m, S.SUPER, S)
-    m.setPendingState(instance, _Initializer3(p1,p2,p3))
-  def setState4(self,S,p1,p2,p3,p4):
-    m = self._myStateInstance.machine()
-    instance = S._getInstance(m, S.SUPER, S)
-    m.setPendingState(instance, _Initializer4(p1,p2,p3,p4))
-  def setState5(self,S,p1,p2,p3,p4,p5):
-    m = self._myStateInstance.machine()
-    instance = S._getInstance(m, S.SUPER, S)
-    m.setPendingState(instance, _Initializer5(p1,p2,p3,p4,p5))
-  def setState6(self,S,p1,p2,p3,p4,p5,p6):
-    m = self._myStateInstance.machine()
-    instance = S._getInstance(m, S.SUPER, S)
-    m.setPendingState(instance, _Initializer6(p1,p2,p3,p4,p5,p6))
-  def setStateHistory(self, S):
-    global _theHistoryInitializer
-    m = self._myStateInstance.machine()
-    instance = S._getInstance(m, S.SUPER, S)
-    m.setPendingState(instance, _theHistoryInitializer)
-  def setStateAlias(self,state):
-    state.setState(self._myStateInstance.machine())
-  def setStateBox(self, SUPERSTATE, S, box=None):
-    #global _theDefaultInitializer
-    m = self._myStateInstance.machine()
-    instance = S._getInstance(m, SUPERSTATE, S)
-    m.myPendingBox = box
-    m.setPendingState(instance, _Initializer())
-  #def setStateDirect(self, S, box=None):
-  #  #global _theDefaultInitializer
-  #  m = self._myStateInstance.machine()
-  #  instance = S._getInstance(m, S.SUPER, S)
-  #  m.myPendingBox = box
-  #  m.setPendingState(instance, _Initializer())
-  def _restore(self, current):
-    self._myStateInstance.machine().myCurrentState = current
-  def setStateCurrent(self, current):
-    #global _theDefaultInitializer
-    self._myStateInstance.machine().setPendingState(current, _Initializer())
-  def _shutdown(self):
-    self._myStateInstance.machine()._shutdown()
-  def _setHistorySuper(self, instance, deep):
-    pass
+    HISTORY = False
 
-  def _getInstance(machine, S=None, C=None):
-    instance = machine.getInstances()
-    if not instance[0]:
-      instance[0] = _RootInstance(machine, 0)
-    return instance[0]
-  _getInstance = staticmethod(_getInstance)
-  def _deleteBox(self, instance):
-    pass
-  def _saveHistory(self, instance, shallow, deep):
-    pass
+    def __init__(self, instance):
+        self._myStateInstance = instance
+
+    def isChild(key):
+        return False
+    isChild = staticmethod(isChild)
+
+    def set_state_direct(self, S, *args):
+        return self.setStateDirect(S, *args)
+
+    def setStateDirect(self, S, *args):
+        #global _theDefaultInitializer
+        m = self._myStateInstance.machine()
+        instance = S._getInstance(m, S.SUPER, S)
+
+        instance.setHistory(0)
+        m.setPendingState(instance, _Initializer(*args))
+
+    def set_state(self, S, *args):
+        return self.setState(S, *args)
+
+    def setState(self, S, *args):
+        #global _theDefaultInitializer
+        m = self._myStateInstance.machine()
+        instance = S._getInstance(m, S.SUPER, S)
+        m.setPendingState(instance, _Initializer(*args))
+
+    def setState0(self, S):
+        global _theDefaultInitializer
+        m = self._myStateInstance.machine()
+        instance = S._getInstance(m, S.SUPER, S)
+        m.setPendingState(instance, _theDefaultInitializer)
+
+    def setState1(self, S, p1):
+        m = self._myStateInstance.machine()
+        instance = S._getInstance(m, S.SUPER, S)
+        m.setPendingState(instance, _Initializer1(p1))
+
+    def setState2(self, S, p1, p2):
+        m = self._myStateInstance.machine()
+        instance = S._getInstance(m, S.SUPER, S)
+        m.setPendingState(instance, _Initializer2(p1, p2))
+
+    def setState3(self, S, p1, p2, p3):
+        m = self._myStateInstance.machine()
+        instance = S._getInstance(m, S.SUPER, S)
+        m.setPendingState(instance, _Initializer3(p1, p2, p3))
+
+    def setState4(self, S, p1, p2, p3, p4):
+        m = self._myStateInstance.machine()
+        instance = S._getInstance(m, S.SUPER, S)
+        m.setPendingState(instance, _Initializer4(p1, p2, p3, p4))
+
+    def setState5(self, S, p1, p2, p3, p4, p5):
+        m = self._myStateInstance.machine()
+        instance = S._getInstance(m, S.SUPER, S)
+        m.setPendingState(instance, _Initializer5(p1, p2, p3, p4, p5))
+
+    def setState6(self, S, p1, p2, p3, p4, p5, p6):
+        m = self._myStateInstance.machine()
+        instance = S._getInstance(m, S.SUPER, S)
+        m.setPendingState(instance, _Initializer6(p1, p2, p3, p4, p5, p6))
+
+    def setStateHistory(self, S):
+        global _theHistoryInitializer
+        m = self._myStateInstance.machine()
+        instance = S._getInstance(m, S.SUPER, S)
+        m.setPendingState(instance, _theHistoryInitializer)
+
+    def setStateAlias(self, state):
+        state.setState(self._myStateInstance.machine())
+
+    def setStateBox(self, SUPERSTATE, S, box=None):
+        #global _theDefaultInitializer
+        m = self._myStateInstance.machine()
+        instance = S._getInstance(m, SUPERSTATE, S)
+        m.myPendingBox = box
+        m.setPendingState(instance, _Initializer())
+    # def setStateDirect(self, S, box=None):
+    #  #global _theDefaultInitializer
+    #  m = self._myStateInstance.machine()
+    #  instance = S._getInstance(m, S.SUPER, S)
+    #  m.myPendingBox = box
+    #  m.setPendingState(instance, _Initializer())
+
+    def _restore(self, current):
+        self._myStateInstance.machine().myCurrentState = current
+
+    def setStateCurrent(self, current):
+        #global _theDefaultInitializer
+        self._myStateInstance.machine().setPendingState(current, _Initializer())
+
+    def _shutdown(self):
+        self._myStateInstance.machine()._shutdown()
+
+    def _setHistorySuper(self, instance, deep):
+        pass
 
+    def _getInstance(machine, S=None, C=None):
+        instance = machine.getInstances()
+        if not instance[0]:
+            instance[0] = _RootInstance(machine, 0)
+        return instance[0]
+    _getInstance = staticmethod(_getInstance)
 
-  def on_entry(self):
-    pass
-  def on_init(self):
-    pass
-  def on_exit(self):
-    pass
+    def _deleteBox(self, instance):
+        pass
 
+    def _saveHistory(self, instance, shallow, deep):
+        pass
 
+    def on_entry(self):
+        pass
 
+    def on_init(self):
+        pass
 
+    def on_exit(self):
+        pass
 
 
+class Link(_StateSpecification):
+    def __init__(self, instance):
+        super(Link, self).__init__(instance)
+        self.super_obj = self.SUPER(
+            self.SUPER._getInstance(
+                instance.machine(),
+                self.SUPER.SUPER,
+                self.SUPER))
+
+        #super_class.__init__(self, instance)
+        #self.SUPER.__init__(self, self.SUPER._getInstance(instance.machine()))
+        self._myStateInstance = instance
+
+    def key(instance):
+        k = _KeyData()
+        k.instanceGenerator = Link._getInstance
+        k.childPredicate = Link.isChild
+        k.name = instance.SUPER._state_name()
+        k.id = instance.SUPER.StateID
+        return k
+    key = staticmethod(key)
+
+    def alias():
+        return Alias(Link.key(self))
+    alias = staticmethod(alias)
+
+    def isChild(other, SUPER):
+        if other.StateID == 0:
+            return False
+        return other.StateID == SUPER.StateID or Link.isChild(
+            other.SUPER, SUPER)
+    isChild = staticmethod(isChild)
+
+    def isParent(self, other):
+        return other.childPredicate(Link.key(self))
+    #isParent = staticmethod(isParent)
+
+    def isCurrent(self, machine):
+        return machine.currentState().isChild(Link.key(self))
+    #isCurrent = staticmethod(isCurrent)
+
+    def isCurrentDirect(self, machine):
+        return Link.key(self) == machine.currentState()
+    #isCurrentDirect = staticmethod(isCurrentDirect)
+
+    def clearHistory(self, machine, StateID):
+        instance = machine.getInstance(StateID)
+        if instance:
+            instance.setHistory(0)
+    #clearHistory = staticmethod(clearHistory)
+
+    def clearHistoryDeep(self, machine, StateID):
+        instance = machine.getInstance(StateID)
+        if instance:
+            instance.clearHistoryDeep(Machine.theStateCount, instance)
+    #clearHistoryDeep = staticmethod(clearHistoryDeep)
+
+    def clear_history(self, machine):
+        self._myStateInstance.setHistory(0)
+
+    def clear_history_deep(self, machine):
+        self._myStateInstance.setHistory(0)
+        self._myStateInstance.setHistorySuper(0)
+
+    def history(machine, StateID):
+        instance = machine.getInstance(StateID)
+        history = None
+        if instance:
+            history = instance.history()
+        if history:
+            return history.key()
+        else:
+            return Link.key(self)
+    history = staticmethod(history)
+
+    def on_entry(self):
+        pass
 
+    def on_init(self):
+        pass
 
-class Link(_StateSpecification):
-  def __init__(self, instance):
-    super(Link,self).__init__(instance)
-    self.super_obj = self.SUPER(self.SUPER._getInstance(instance.machine(), self.SUPER.SUPER, self.SUPER))
-    
-    #super_class.__init__(self, instance)
-    #self.SUPER.__init__(self, self.SUPER._getInstance(instance.machine()))
-    self._myStateInstance = instance
-  def key(instance):
-    k = _KeyData()
-    k.instanceGenerator = Link._getInstance
-    k.childPredicate = Link.isChild
-    k.name = instance.SUPER._state_name()
-    k.id = instance.SUPER.StateID
-    return k
-  key = staticmethod(key)
-  def alias():
-    return Alias(Link.key(self))
-  alias = staticmethod(alias)
-  def isChild(other, SUPER):
-    if other.StateID == 0:
-      return False
-    return other.StateID == SUPER.StateID or Link.isChild(other.SUPER, SUPER)
-  isChild = staticmethod(isChild)
-  def isParent(self, other):
-    return other.childPredicate(Link.key(self))
-  #isParent = staticmethod(isParent)
-  def isCurrent(self, machine):
-    return machine.currentState().isChild(Link.key(self))
-  #isCurrent = staticmethod(isCurrent)
-  def isCurrentDirect(self, machine):
-    return Link.key(self) == machine.currentState()
-  #isCurrentDirect = staticmethod(isCurrentDirect)
-  def clearHistory(self, machine, StateID):
-    instance = machine.getInstance(StateID)
-    if instance:
-      instance.setHistory(0)
-  #clearHistory = staticmethod(clearHistory)
-  def clearHistoryDeep(self, machine, StateID):
-    instance = machine.getInstance(StateID)
-    if instance:
-      instance.clearHistoryDeep(Machine.theStateCount,instance)
-  #clearHistoryDeep = staticmethod(clearHistoryDeep)
-  def clear_history(self, machine):
-    self._myStateInstance.setHistory(0)
-  def clear_history_deep(self, machine):
-    self._myStateInstance.setHistory(0)
-    self._myStateInstance.setHistorySuper(0)
-    
-    
-  def history(machine, StateID):
-    instance = machine.getInstance(StateID)
-    history = 0
-    if instance:
-      history = instance.history()
-    if history:
-      return history.key()
-    else:
-      return Link.key(self)
-  history = staticmethod(history)
+    def on_exit(self):
+        pass
 
-  def on_entry(self):
-    pass
-  def on_init(self):
-    pass
-  def on_exit(self):
-    pass
-  def _box(self):
-    
-    return self._myStateInstance.box()
-  def _getInstance(machine, S, C):
-    
-    instance = machine.getInstances()
-    
-    if not instance[C.StateID]:
-      instance[C.StateID] = _SubstateInstance(machine, S._getInstance(machine, S.SUPER, S), C)
-    return instance[C.StateID]
-  _getInstance = staticmethod(_getInstance)
-  def _deleteBox(self, instance):
-    instance.deleteBox()
-  def _saveHistory(self,instance,shallow,deep):
-    self._setHistorySuper(instance,deep)
-  def __getitem__(self, class_):
-    if isinstance(class_, str):
-      if self.__class__.__name__ == class_:
-        return self
-    elif type(self) == class_:
-      return self
-    obj = self
-    while hasattr(obj, "super_obj"):
-      obj = obj.super_obj
-      
-      if isinstance(class_, str):
-        if obj.__class__.__name__ == class_:
-          return obj
-      elif type(obj) == class_:
-        return obj
-      
-    return None
-  def data(self, class_=None):
-    if class_:
-      return self[class_]._box()
-    else:
-      return self._box()
-    
+    def _box(self):
+
+        return self._myStateInstance.box()
+
+    def _getInstance(machine, S, C):
+
+        instance = machine.getInstances()
+
+        if not instance[C.StateID]:
+            instance[C.StateID] = _SubstateInstance(
+                machine, S._getInstance(machine, S.SUPER, S), C)
+        return instance[C.StateID]
+    _getInstance = staticmethod(_getInstance)
+
+    def _deleteBox(self, instance):
+        instance.deleteBox()
+
+    def _saveHistory(self, instance, shallow, deep):
+        self._setHistorySuper(instance, deep)
+
+    def __getitem__(self, class_):
+        if isinstance(class_, str):
+            if self.__class__.__name__ == class_:
+                return self
+        elif type(self) == class_:
+            return self
+        obj = self
+        while hasattr(obj, "super_obj"):
+            obj = obj.super_obj
+
+            if isinstance(class_, str):
+                if obj.__class__.__name__ == class_:
+                    return obj
+            elif type(obj) == class_:
+                return obj
+
+        return None
+
+    def data(self, class_=None):
+        if class_:
+            return self[class_]._box()
+        else:
+            return self._box()
+
+    def dispatch(self, event):
+        self["TopBase_"].dispatch(event)
+
+    def defer(self, event):
+        self["TopBase_"].defer(event)
 
-  def dispatch(self, event):
-    self["TopBase_"].dispatch(event)
-  def defer(self, event):
-    self["TopBase_"].defer(event)
 
 class StateID:
-  def __init__(self):
-    pass
-  value = 0
+    def __init__(self):
+        pass
+    value = 0
+
 
 class _StateInstance(object):
-  def __init__(self, machine, parent):
-    self.myMachine = machine
-    self.mySpecification = None
-    self.myHistory = None
-    self.myParent = parent
-    
-    self.myBox = None
-    self.myBoxPlace = None
-  def entry(self,previous,first=True):
-    if not self.myParent:
-      return
-    if first or not previous.isChild(self):
-      self.myParent.entry(previous,False)
-      self.createBox()
-      self.mySpecification.on_entry()
-  def exit(self,next):
-    
-    if not self.myParent:
-      return
-    
-    if self is next or not next.isChild(self):
-      self.mySpecification.on_exit()
-      if self.myBox is not _EmptyBox.theEmptyBox:
-        self.mySpecification._deleteBox(self)
-      self.myParent.exit(next)
-      
-
-  def init(self, history, *args):
-    #global _theDefaultInitializer
-    if history and self.myHistory:
-      self.myMachine.setPendingState(self.myHistory, _Initializer(*args))
-    else:
-      self.mySpecification.on_init(*args)
-    self.myHistory = None
-    
-      
-  def entry_next(self,next):
-    pass
-  def entry_history(self,history):
-    pass
-  def saveHistory(self,shallow,deep):
-    self.mySpecification._saveHistory(self, shallow, deep)
-  def setHistorySuper(self, deep):
-    if self.myParent:
-      self.myParent.saveHistory(self, deep)
-  def copy(self, original):
-    if original.myHistory:
-      history = self.myMachine.getInstance(original.myHistory.id())
-      self.setHistory(history)
-    if original.myBox:
-      self.cloneBox(original.myBox)
-  def clone(self, newMachine):
-    parent = None
-    if self.myParent:
-      parent = newMachine.createClone(self.myParent.id(), self.myParent)
-    clone = self.create(newMachine, parent)
-      
-  def shutdown(self):
-    self.mySpecification._shutdown()
-  def restore(self, instance):
-    self.mySpecification._restore(instance)
-  def id(self):
-    pass
-  def key(self):
-    pass
-  def name(self):
-    pass
-  def create(self, machine, parent):
-    pass
-  def createBox(self):
-    pass
-  def deleteBox(self):
-    pass
-  def cloneBox(self,box):
-    pass
-  def setBox(self,box):
-    if self.myBoxPlace:
-      self.myBoxPlace = None
-    self.myBox = box
-  def isChild(self,instance):
-    
-    return self==instance or (self.myParent and self.myParent.isChild(instance))
-  def specification(self):
-    return self.mySpecification
-  def box(self):
-    return self.myBox
-  def data(self):
-    return self.myBox
-  def machine(self):
-    return self.myMachine
-  def setHistory(self,history):
-    self.myHistory = history
-  def getHistory(self):
-    return self.myHistory
-  
+    def __init__(self, machine, parent):
+        self.myMachine = machine
+        self.mySpecification = None
+        self.myHistory = None
+        self.myParent = parent
+
+        self.myBox = None
+        self.myBoxPlace = None
+
+    def entry(self, previous, first=True):
+        if not self.myParent:
+            return
+        if first or not previous.isChild(self):
+            self.myParent.entry(previous, False)
+            self.createBox()
+            self.mySpecification.on_entry()
+
+    def exit(self, next):
+
+        if not self.myParent:
+            return
+
+        if self is next or not next.isChild(self):
+            self.mySpecification.on_exit()
+            if self.myBox is not _EmptyBox.theEmptyBox:
+                self.mySpecification._deleteBox(self)
+            self.myParent.exit(next)
+
+    def init(self, history, *args):
+        #global _theDefaultInitializer
+        if history and self.myHistory:
+            self.myMachine.setPendingState(self.myHistory, _Initializer(*args))
+        else:
+            self.mySpecification.on_init(*args)
+        self.myHistory = None
+
+    def entry_next(self, next):
+        pass
+
+    def entry_history(self, history):
+        pass
+
+    def saveHistory(self, shallow, deep):
+        self.mySpecification._saveHistory(self, shallow, deep)
+
+    def setHistorySuper(self, deep):
+        if self.myParent:
+            self.myParent.saveHistory(self, deep)
+
+    def copy(self, original):
+        if original.myHistory:
+            history = self.myMachine.getInstance(original.myHistory.id())
+            self.setHistory(history)
+        if original.myBox:
+            self.cloneBox(original.myBox)
+
+    def clone(self, newMachine):
+        parent = None
+        if self.myParent:
+            parent = newMachine.createClone(self.myParent.id(), self.myParent)
+        clone = self.create(newMachine, parent)
+
+    def shutdown(self):
+        self.mySpecification._shutdown()
+
+    def restore(self, instance):
+        self.mySpecification._restore(instance)
+
+    def id(self):
+        pass
+
+    def key(self):
+        pass
+
+    def name(self):
+        pass
+
+    def create(self, machine, parent):
+        pass
+
+    def createBox(self):
+        pass
+
+    def deleteBox(self):
+        pass
+
+    def cloneBox(self, box):
+        pass
+
+    def setBox(self, box):
+        if self.myBoxPlace:
+            self.myBoxPlace = None
+        self.myBox = box
+
+    def isChild(self, instance):
+
+        return self == instance or (
+            self.myParent and self.myParent.isChild(instance))
+
+    def specification(self):
+        return self.mySpecification
+
+    def box(self):
+        return self.myBox
+
+    def data(self):
+        return self.myBox
+
+    def machine(self):
+        return self.myMachine
+
+    def setHistory(self, history):
+        self.myHistory = history
+
+    def getHistory(self):
+        return self.myHistory
+
 
 class _RootInstance(_StateInstance):
-  def __init__(self, machine, parent):
-    super(_RootInstance,self).__init__(machine, parent)
-    self.mySpecification = _StateSpecification(self)
-  def id(self):
-    return 0
-  def key(self):
-    return 0
-  def name(self):
-    return ""
-  def createBox(self):
-    pass
-  def deleteBox(self):
-    pass
-  def cloneBox(self, box):
-    pass
-  def name(self):
-    return "Root"
-  def create(self, machine, parent):
-    return _RootInstance(machine,parent)
+    def __init__(self, machine, parent):
+        super(_RootInstance, self).__init__(machine, parent)
+        self.mySpecification = _StateSpecification(self)
+
+    def id(self):
+        return 0
+
+    def key(self):
+        return 0
+
+    def name(self):
+        return ""
+
+    def createBox(self):
+        pass
+
+    def deleteBox(self):
+        pass
+
+    def cloneBox(self, box):
+        pass
+
+    def name(self):
+        return "Root"
+
+    def create(self, machine, parent):
+        return _RootInstance(machine, parent)
+
 
 class _SubstateInstance(_StateInstance):
-  HISTORY = False
-  def __init__(self, machine, parent, super_class):
-    super(_SubstateInstance, self).__init__(machine, parent)
-    self.mySpecification = super_class(self)
-    
-    self.SUPER = super_class
-  def __del__(self):
-    if self.myBox:
-      _deleteBox(self.myBox,self.myBoxPlace)
-  def id(self):
-    return self.SUPER.StateID
-  def key(self):
-    return self.SUPER.key(self)
-  def name(self):
-    return self.SUPER._state_name()
-  def create(self, machine, parent):
-    _SubstateInstance(machine, parent, self.SUPER)
-  def createBox(self):
-    if not self.myBox:
-      if hasattr(self.SUPER, "Box"):
-        self.myBox = _createBox(self.myBoxPlace,self.SUPER.Box)
-      else:
-        self.myBox = _createBox(self.myBoxPlace)
-  def deleteBox(self):
-    _deleteBox(self.myBox,self.myBoxPlace)
-  def cloneBox(self, box):
-    self.myBox = _cloneBox(box)
+    HISTORY = False
+
+    def __init__(self, machine, parent, super_class):
+        super(_SubstateInstance, self).__init__(machine, parent)
+        self.mySpecification = super_class(self)
+
+        self.SUPER = super_class
+
+    def __del__(self):
+        if self.myBox:
+            _deleteBox(self.myBox, self.myBoxPlace)
+
+    def id(self):
+        return self.SUPER.StateID
+
+    def key(self):
+        return self.SUPER.key(self)
+
+    def name(self):
+        return self.SUPER._state_name()
+
+    def create(self, machine, parent):
+        _SubstateInstance(machine, parent, self.SUPER)
+
+    def createBox(self):
+        if not self.myBox:
+            if hasattr(self.SUPER, "Box"):
+                self.myBox = _createBox(self.myBoxPlace, self.SUPER.Box)
+            else:
+                self.myBox = _createBox(self.myBoxPlace)
+
+    def deleteBox(self):
+        _deleteBox(self.myBox, self.myBoxPlace)
+
+    def cloneBox(self, box):
+        self.myBox = _cloneBox(box)
+
 
 class _IEventBase:
-  def __init__(self):
-    pass
-  def dispatch(self, instance):
-    pass
+    def __init__(self):
+        pass
+
+    def dispatch(self, instance):
+        pass
+
 
 class IEvent(_IEventBase):
-  def __init__(self):
-    pass
+    def __init__(self):
+        pass
 
-class _Event6(IEvent):
-  def __init__(self, handler, p1, p2, p3, p4, p5, p6):
-    self.myHandler = handler
-    self.myParam1 = p1
-    self.myParam2 = p2
-    self.myParam3 = p3
-    self.myParam4 = p4
-    self.myParam5 = p5
-    self.myParam6 = p6
-  def dispatch(self, instance):
-    behaviour = instance.specification()
-    getattr(behaviour,self.myHandler.__name__)(self.myParam1,self.myParam2,self.myParam3,self.myParam4,self.myParam5,self.myParam6)
 
-class _Event5(IEvent):
-  def __init__(self, handler, p1, p2, p3, p4, p5):
-    self.myHandler = handler
-    self.myParam1 = p1
-    self.myParam2 = p2
-    self.myParam3 = p3
-    self.myParam4 = p4
-    self.myParam5 = p5
-  def dispatch(self, instance):
-    behaviour = instance.specification()
-    getattr(behaviour,self.myHandler.__name__)(self.myParam1,self.myParam2,self.myParam3,self.myParam4,self.myParam5)
+class _Event6(IEvent):
+    def __init__(self, handler, p1, p2, p3, p4, p5, p6):
+        self.myHandler = handler
+        self.myParam1 = p1
+        self.myParam2 = p2
+        self.myParam3 = p3
+        self.myParam4 = p4
+        self.myParam5 = p5
+        self.myParam6 = p6
+
+    def dispatch(self, instance):
+        behaviour = instance.specification()
+        getattr(
+            behaviour,
+            self.myHandler.__name__)(
+            self.myParam1,
+            self.myParam2,
+            self.myParam3,
+            self.myParam4,
+            self.myParam5,
+            self.myParam6)
 
 
+class _Event5(IEvent):
+    def __init__(self, handler, p1, p2, p3, p4, p5):
+        self.myHandler = handler
+        self.myParam1 = p1
+        self.myParam2 = p2
+        self.myParam3 = p3
+        self.myParam4 = p4
+        self.myParam5 = p5
+
+    def dispatch(self, instance):
+        behaviour = instance.specification()
+        getattr(
+            behaviour,
+            self.myHandler.__name__)(
+            self.myParam1,
+            self.myParam2,
+            self.myParam3,
+            self.myParam4,
+            self.myParam5)
 
 
 class _Event4(IEvent):
-  def __init__(self, handler, p1, p2, p3, p4):
-    self.myHandler = handler
-    self.myParam1 = p1
-    self.myParam2 = p2
-    self.myParam3 = p3
-    self.myParam4 = p4
-  def dispatch(self, instance):
-    behaviour = instance.specification()
-    getattr(behaviour,self.myHandler.__name__)(self.myParam1,self.myParam2,self.myParam3,self.myParam4)
-
+    def __init__(self, handler, p1, p2, p3, p4):
+        self.myHandler = handler
+        self.myParam1 = p1
+        self.myParam2 = p2
+        self.myParam3 = p3
+        self.myParam4 = p4
+
+    def dispatch(self, instance):
+        behaviour = instance.specification()
+        getattr(
+            behaviour,
+            self.myHandler.__name__)(
+            self.myParam1,
+            self.myParam2,
+            self.myParam3,
+            self.myParam4)
 
 
 class _Event3(IEvent):
-  def __init__(self, handler, p1, p2, p3):
-    self.myHandler = handler
-    self.myParam1 = p1
-    self.myParam2 = p2
-    self.myParam3 = p3
-  def dispatch(self, instance):
-    behaviour = instance.specification()
-    getattr(behaviour,self.myHandler.__name__)(self.myParam1,self.myParam2,self.myParam3)
-
+    def __init__(self, handler, p1, p2, p3):
+        self.myHandler = handler
+        self.myParam1 = p1
+        self.myParam2 = p2
+        self.myParam3 = p3
+
+    def dispatch(self, instance):
+        behaviour = instance.specification()
+        getattr(
+            behaviour,
+            self.myHandler.__name__)(
+            self.myParam1,
+            self.myParam2,
+            self.myParam3)
 
 
 class _Event2(IEvent):
-  def __init__(self, handler, p1, p2):
-    self.myHandler = handler
-    self.myParam1 = p1
-    self.myParam2 = p2
-  def dispatch(self, instance):
-    behaviour = instance.specification()
-    getattr(behaviour,self.myHandler.__name__)(self.myParam1,self.myParam2)
-
+    def __init__(self, handler, p1, p2):
+        self.myHandler = handler
+        self.myParam1 = p1
+        self.myParam2 = p2
 
+    def dispatch(self, instance):
+        behaviour = instance.specification()
+        getattr(
+            behaviour,
+            self.myHandler.__name__)(
+            self.myParam1,
+            self.myParam2)
 
 
 class _Event1(IEvent):
-  def __init__(self, handler, p1):
-    self.myHandler = handler
-    self.myParam1 = p1
-  def dispatch(self, instance):
-    behaviour = instance.specification()
-    getattr(behaviour,self.myHandler.__name__)(self.myParam1)
+    def __init__(self, handler, p1):
+        self.myHandler = handler
+        self.myParam1 = p1
 
+    def dispatch(self, instance):
+        behaviour = instance.specification()
+        getattr(behaviour, self.myHandler.__name__)(self.myParam1)
 
 
 class _Event0(IEvent):
-  def __init__(self, handler):
-    self.myHandler = handler
-  def dispatch(self, instance):
-    behaviour = instance.specification()
-    
-    getattr(behaviour,self.myHandler.__name__)()
+    def __init__(self, handler):
+        self.myHandler = handler
+
+    def dispatch(self, instance):
+        behaviour = instance.specification()
+
+        getattr(behaviour, self.myHandler.__name__)()
 
 
 class _Event(IEvent):
-  def __init__(self, handler, *args):
-    self.myHandler = handler
-    self.myParams = args
-  def dispatch(self, instance):
-    behaviour = instance.specification()
-    getattr(behaviour,self.myHandler.__name__)(*self.myParams)
+    def __init__(self, handler, *args):
+        self.myHandler = handler
+        self.myParams = args
 
+    def dispatch(self, instance):
+        behaviour = instance.specification()
+        getattr(behaviour, self.myHandler.__name__)(*self.myParams)
 
 
-def Event6(R,p1,p2,p3,p4,p5,p6):
-  return _Event6(R,p1,p2,p3,p4,p5,p6)
+def Event6(R, p1, p2, p3, p4, p5, p6):
+    return _Event6(R, p1, p2, p3, p4, p5, p6)
 
 
-def Event5(R,p1,p2,p3,p4,p5):
-  return _Event5(R,p1,p2,p3,p4,p5)
+def Event5(R, p1, p2, p3, p4, p5):
+    return _Event5(R, p1, p2, p3, p4, p5)
 
-def Event4(R,p1,p2,p3,p4):
-  return _Event4(R,p1,p2,p3,p4)
 
-def Event3(R,p1,p2,p3):
-  return _Event3(R,p1,p2,p3)
+def Event4(R, p1, p2, p3, p4):
+    return _Event4(R, p1, p2, p3, p4)
 
-def Event2(R,p1,p2):
-  return _Event2(R,p1,p2)
 
-def Event1(R,p1):
-  return _Event1(R,p1)
+def Event3(R, p1, p2, p3):
+    return _Event3(R, p1, p2, p3)
 
-def Event0(R):
-  return _Event0(R)
+
+def Event2(R, p1, p2):
+    return _Event2(R, p1, p2)
 
 
+def Event1(R, p1):
+    return _Event1(R, p1)
+
+
+def Event0(R):
+    return _Event0(R)
+
 
 def Event(R, *args):
-  return _Event(R, *args)
+    return _Event(R, *args)
+
 
 def execute(instance, history, *args):
-  #behaviour = instance.specification()
-  #behaviour.on_init(*args)
-  
-  instance.init(history,  *args)
+    #behaviour = instance.specification()
+    # behaviour.on_init(*args)
+
+    instance.init(history, *args)
+
 
 def execute1(instance, p1):
-  behaviour = instance.specification()
-  behaviour.on_init(p1)
+    behaviour = instance.specification()
+    behaviour.on_init(p1)
+
 
 def execute2(instance, p1, p2):
-  behaviour = instance.specification()
-  behaviour.on_init(p1, p2)
+    behaviour = instance.specification()
+    behaviour.on_init(p1, p2)
+
 
 def execute3(instance, p1, p2, p3):
-  behaviour = instance.specification()
-  behaviour.on_init(p1, p2, p3)
+    behaviour = instance.specification()
+    behaviour.on_init(p1, p2, p3)
+
 
 def execute4(instance, p1, p2, p3, p4):
-  behaviour = instance.specification()
-  behaviour.on_init(p1, p2, p3, p4)
+    behaviour = instance.specification()
+    behaviour.on_init(p1, p2, p3, p4)
+
 
 def execute5(instance, p1, p2, p3, p4, p5):
-  behaviour = instance.specification()
-  behaviour.on_init(p1, p2, p3, p4, p5)
+    behaviour = instance.specification()
+    behaviour.on_init(p1, p2, p3, p4, p5)
+
 
 def execute6(instance, p1, p2, p3, p4, p5, p6):
-  behaviour = instance.specification()
-  behaviour.on_init(p1, p2, p3, p4, p5, p6)
-  
+    behaviour = instance.specification()
+    behaviour.on_init(p1, p2, p3, p4, p5, p6)
+
 
 class __Initializer:
-  def __init__(self):
-    pass
-  def clone(self):
-    pass
-  def destroy(self):
-    pass
-  def adapt(self, key):
-    return key
-  def execute(self, instance):
-    instance.init(False)
+    def __init__(self):
+        pass
+
+    def clone(self):
+        pass
+
+    def destroy(self):
+        pass
+
+    def adapt(self, key):
+        return key
+
+    def execute(self, instance):
+        instance.init(False)
+
 
 class _StaticInitializer(__Initializer):
-  def __init__(self):
-    pass
-  def clone(self):
-    return self
-  def destroy(self):
-    pass
+    def __init__(self):
+        pass
 
+    def clone(self):
+        return self
 
-class _DefaultInitializer(_StaticInitializer):
-  def __init__(self):
-    pass
-  def execute(self, instance):
-    instance.init(False)
+    def destroy(self):
+        pass
 
 
+class _DefaultInitializer(_StaticInitializer):
+    def __init__(self):
+        pass
+
+    def execute(self, instance):
+        instance.init(False)
 
 
 class _HistoryInitializer(_StaticInitializer):
-  def __init__(self):
-    pass
-  def execute(self, instance):
-    instance.init(True)
+    def __init__(self):
+        pass
+
+    def execute(self, instance):
+        instance.init(True)
 
 
 class _AdaptingInitializer(__Initializer):
-  def __init__(self, machine):
-    self.myMachine = machine
-  def execute(self, instance):
-    instance.init(False)
-  def clone(self):
-    return _AdaptingInitializer(self.myMachine)
-  def adapt(self, key):
-    id = key.id
-    instance = self.myMachine.getInstance(id)
-    history = None
-    if instance:
-      history = instance.history()
-    if history:
-      return history.key()
-    else:
-      return key
+    def __init__(self, machine):
+        self.myMachine = machine
+
+    def execute(self, instance):
+        instance.init(False)
+
+    def clone(self):
+        return _AdaptingInitializer(self.myMachine)
+
+    def adapt(self, key):
+        id = key.id
+        instance = self.myMachine.getInstance(id)
+        history = None
+        if instance:
+            history = instance.history()
+        if history:
+            return history.key()
+        else:
+            return key
 
 
 class _Initializer(__Initializer):
-  def __init__(self, *args):
-    self.myParams = args
-  def clone(self):
-    return _Initializer(*self.myParams)
-  def execute(self, instance, history_):
-    execute(instance, history_, *self.myParams)
+    def __init__(self, *args):
+        self.myParams = args
+
+    def clone(self):
+        return _Initializer(*self.myParams)
 
+    def execute(self, instance, history_):
+        execute(instance, history_, *self.myParams)
 
 
 class _Initializer1(__Initializer):
-  def __init__(self, p1):
-    self.myParam1 = p1
-  def clone(self):
-    return _Initializer1(self.myParam1)
-  def execute(self, instance):
-    execute1(instance, self.myParam1)
+    def __init__(self, p1):
+        self.myParam1 = p1
+
+    def clone(self):
+        return _Initializer1(self.myParam1)
+
+    def execute(self, instance):
+        execute1(instance, self.myParam1)
 
 
 class _Initializer2(__Initializer):
-  def __init__(self, p1, p2):
-    self.myParam1 = p1
-    self.myParam2 = p2
-  def clone(self):
-    return _Initializer2(self.myParam1,self.myParam2)
-  def execute(self, instance):
-    execute2(instance, self.myParam1,self.myParam2)
+    def __init__(self, p1, p2):
+        self.myParam1 = p1
+        self.myParam2 = p2
+
+    def clone(self):
+        return _Initializer2(self.myParam1, self.myParam2)
 
+    def execute(self, instance):
+        execute2(instance, self.myParam1, self.myParam2)
 
 
 class _Initializer3(__Initializer):
-  def __init__(self, p1, p2, p3):
-    self.myParam1 = p1
-    self.myParam2 = p2
-    self.myParam3 = p3
-  def clone(self):
-    return _Initializer3(self.myParam1,self.myParam2,self.myParam3)
-  def execute(self, instance):
-    execute3(instance, self.myParam1,self.myParam2,self.myParam3)
+    def __init__(self, p1, p2, p3):
+        self.myParam1 = p1
+        self.myParam2 = p2
+        self.myParam3 = p3
 
+    def clone(self):
+        return _Initializer3(self.myParam1, self.myParam2, self.myParam3)
 
+    def execute(self, instance):
+        execute3(instance, self.myParam1, self.myParam2, self.myParam3)
 
 
 class _Initializer4(__Initializer):
-  def __init__(self, p1, p2, p3, p4):
-    self.myParam1 = p1
-    self.myParam2 = p2
-    self.myParam3 = p3
-    self.myParam4 = p4
-  def clone(self):
-    return _Initializer4(self.myParam1,self.myParam2,self.myParam3,self.myParam4)
-  def execute(self, instance):
-    execute4(instance, self.myParam1,self.myParam2,self.myParam3,self.myParam4)
+    def __init__(self, p1, p2, p3, p4):
+        self.myParam1 = p1
+        self.myParam2 = p2
+        self.myParam3 = p3
+        self.myParam4 = p4
 
+    def clone(self):
+        return _Initializer4(self.myParam1, self.myParam2,
+                             self.myParam3, self.myParam4)
 
+    def execute(self, instance):
+        execute4(
+            instance,
+            self.myParam1,
+            self.myParam2,
+            self.myParam3,
+            self.myParam4)
 
 
 class _Initializer5(__Initializer):
-  def __init__(self, p1, p2, p3, p4, p5):
-    self.myParam1 = p1
-    self.myParam2 = p2
-    self.myParam3 = p3
-    self.myParam4 = p4
-    self.myParam5 = p5
-  def clone(self):
-    return _Initializer5(self.myParam1,self.myParam2,self.myParam3,self.myParam4,self.myParam5)
-  def execute(self, instance):
-    execute5(instance, self.myParam1,self.myParam2,self.myParam3,self.myParam4,self.myParam5)
+    def __init__(self, p1, p2, p3, p4, p5):
+        self.myParam1 = p1
+        self.myParam2 = p2
+        self.myParam3 = p3
+        self.myParam4 = p4
+        self.myParam5 = p5
+
+    def clone(self):
+        return _Initializer5(self.myParam1, self.myParam2,
+                             self.myParam3, self.myParam4, self.myParam5)
+
+    def execute(self, instance):
+        execute5(
+            instance,
+            self.myParam1,
+            self.myParam2,
+            self.myParam3,
+            self.myParam4,
+            self.myParam5)
 
 
+class _Initializer6(__Initializer):
+    def __init__(self, p1, p2, p3, p4, p5, p6):
+        self.myParam1 = p1
+        self.myParam2 = p2
+        self.myParam3 = p3
+        self.myParam4 = p4
+        self.myParam5 = p5
+        self.myParam6 = p6
+
+    def clone(self):
+        return _Initializer6(self.myParam1, self.myParam2, self.myParam3,
+                             self.myParam4, self.myParam5, self.myParam6)
+
+    def execute(self, instance):
+        execute6(
+            instance,
+            self.myParam1,
+            self.myParam2,
+            self.myParam3,
+            self.myParam4,
+            self.myParam5,
+            self.myParam6)
 
 
+_theDefaultInitializer = _DefaultInitializer()
+_theHistoryInitializer = _HistoryInitializer()
 
 
-class _Initializer6(__Initializer):
-  def __init__(self, p1, p2, p3, p4, p5, p6):
-    self.myParam1 = p1
-    self.myParam2 = p2
-    self.myParam3 = p3
-    self.myParam4 = p4
-    self.myParam5 = p5
-    self.myParam6 = p6
-  def clone(self):
-    return _Initializer6(self.myParam1,self.myParam2,self.myParam3,self.myParam4,self.myParam5,self.myParam6)
-  def execute(self, instance):
-    execute6(instance, self.myParam1,self.myParam2,self.myParam3,self.myParam4,self.myParam5,self.myParam6)
+class _MachineBase(object):
+    def __init__(self):
+        self.myCurrentState = None
+        self.myPendingState = None
+        self.myPendingInit = None
+        self.myPendingBox = None
+        self.myPendingEvent = None
+        self.myInstances = None
+        self.myDeferEvents = []
 
+    def currentState(self):
+        return self.myCurrentState.key()
 
+    def setState(self, instance, init):
+        self.setPendingState(instance, init)
+        self.rattleOn()
 
-_theDefaultInitializer = _DefaultInitializer()
-_theHistoryInitializer = _HistoryInitializer()
+    def setStateAlias(self, state):
+        state.setState(self)
+        self.rattleOn()
 
+    def setPendingState(self, instance, init):
+        self.myPendingState = instance
+        self.myPendingInit = init
 
+    def setPendingEvent(self, event):
+        self.myPendingEvent = event
 
-class _MachineBase(object):
-  def __init__(self):
-    self.myCurrentState = None
-    self.myPendingState = None
-    self.myPendingInit = None
-    self.myPendingBox = None
-    self.myPendingEvent = None
-    self.myInstances = None
-    self.myDeferEvents = []
-  def currentState(self):
-    return self.myCurrentState.key()
-  def setState(self, instance, init):
-    self.setPendingState(instance, init)
-    self.rattleOn()
-    
-  def setStateAlias(self, state):
-    state.setState(self)
-    self.rattleOn()
-  def setPendingState(self, instance, init):
-    self.myPendingState = instance
-    self.myPendingInit = init
-  def setPendingEvent(self, event):
-    self.myPendingEvent = event
-  def rattleOn(self):
-    while self.myPendingState or self.myPendingEvent:
-      while self.myPendingState:
-        
-        self.myCurrentState.exit(self.myPendingState)
-        self.myCurrentState.setHistorySuper(self.myCurrentState)
-        previous = self.myCurrentState
-        
-        self.myCurrentState = self.myPendingState
-        if self.myPendingBox:
-          self.myCurrentState.setBox(self.myPendingBox)
-          self.myPendingBox = None
-        
-        
-        self.myCurrentState.entry(previous)
-        self.myPendingState = None
-        behaviour = self.myCurrentState.specification()
-        
-        self.myPendingInit.execute(self.myCurrentState, behaviour.HISTORY)
+    def rattleOn(self):
+        while self.myPendingState or self.myPendingEvent:
+            while self.myPendingState:
 
-        
-        for event in self.myDeferEvents:
-          event.dispatch(self.myCurrentState)
-        self.myDeferEvents = []
-        
-      if self.myPendingEvent:
-        event = self.myPendingEvent
-        self.myPendingEvent = None
-        event.dispatch(self.myCurrentState)
-    self.myPendingInit = None
-  def getInstances(self):
-    return self.myInstances
-  def start(self, instance, *args):
-    #global _theDefaultInitializer
-    self.myCurrentState = _StateSpecification._getInstance(self)
-    self.setState(instance, _Initializer(*args))
-  def startAlias(self, state):
-    self.myCurrentState = _StateSpecification._getInstance(self)
-    self.setStateAlias(state)
-  def _shutdown(self):
-    #global _theDefaultInitializer
-    self.setState(_StateSpecification._getInstance(self), _Initializer())
-    self.myCurrentState = None
-  def allocate(self, count):
-    
-    self.myInstances = [None]*count
-    
-  def free(self, count):
-    i = count
-    while i > 0:
-      i -=1
-      self.myInstances[i] = None
-    
-  def clearHistoryDeep(self, count, instance):
-    for i in range(count):
-      s = self.myInstances[i]
-      if s and s.isChild(instance):
-        s.setHistory(0)
-  def copy(self, other, count):
-    for i in range(count):
-      state = self.myInstances[i]
-      if state:
-        state.copy(other[i])
-  def createClone(self, id, original):
-    clone = self.getInstances
-    if not clone[id] and original:
-      clone[id] = original.clone(self)
-    return clone[id]
+                self.myCurrentState.exit(self.myPendingState)
+                self.myCurrentState.setHistorySuper(self.myCurrentState)
+                previous = self.myCurrentState
+
+                self.myCurrentState = self.myPendingState
+                if self.myPendingBox:
+                    self.myCurrentState.setBox(self.myPendingBox)
+                    self.myPendingBox = None
+
+                self.myCurrentState.entry(previous)
+                self.myPendingState = None
+                behaviour = self.myCurrentState.specification()
+
+                self.myPendingInit.execute(
+                    self.myCurrentState, behaviour.HISTORY)
+
+                for event in self.myDeferEvents:
+                    event.dispatch(self.myCurrentState)
+                self.myDeferEvents = []
+
+            if self.myPendingEvent:
+                event = self.myPendingEvent
+                self.myPendingEvent = None
+                event.dispatch(self.myCurrentState)
+        self.myPendingInit = None
+
+    def getInstances(self):
+        return self.myInstances
+
+    def start(self, instance, *args):
+        #global _theDefaultInitializer
+        self.myCurrentState = _StateSpecification._getInstance(self)
+        self.setState(instance, _Initializer(*args))
+
+    def startAlias(self, state):
+        self.myCurrentState = _StateSpecification._getInstance(self)
+        self.setStateAlias(state)
+
+    def _shutdown(self):
+        #global _theDefaultInitializer
+        self.setState(_StateSpecification._getInstance(self), _Initializer())
+        self.myCurrentState = None
+
+    def allocate(self, count):
+
+        self.myInstances = [None] * count
+
+    def free(self, count):
+        i = count
+        while i > 0:
+            i -= 1
+            self.myInstances[i] = None
+
+    def clearHistoryDeep(self, count, instance):
+        for i in range(count):
+            s = self.myInstances[i]
+            if s and s.isChild(instance):
+                s.setHistory(0)
+
+    def copy(self, other, count):
+        for i in range(count):
+            state = self.myInstances[i]
+            if state:
+                state.copy(other[i])
+
+    def createClone(self, id, original):
+        clone = self.getInstances
+        if not clone[id] and original:
+            clone[id] = original.clone(self)
+        return clone[id]
 
 
 class Alias:
-  def __init__(self):
-    self.myInitializer = None
-    self.myStateKey = 0
-  def __del__(self):
-    self.myInitializer.destroy()
-  def init_history(self, key, history=False):
-    global _theHistoryInitializer
-    global _theDefaultInitializer
-    self.myStateKey = key
-    if history:
-      self.myInitializer = _theHistoryInitializer
-    else:
-      self.myInitializer = _theDefaultInitializer
-  def init_Initializer(self, key, init):
-    self.myStateKey = key
-    self.myInitializer = init
-  def init_Alias(self, other):
-    self.myStateKey = key
-    self.myInitializer = other.myInitializer.clone()
-  def equal(self, other):
-    if self is other:
-      return self
-    self.myInitializer.destroy()
-    self.myStateKey = other.childPredicate
-    self.myInitializer = other.childPredicate
-
-  def Key(self):
-    return self.key()
-  def isChild(self, k):
-    return self.key().childPredicate(k)
-  def isParent(self, k):
-    return self.key().childPredicate(k)
-  def name(self):
-    return self.key().name
-  def id(self):
-    return self.key().id
-  def key(self):
-    return self.myInitializer.adapt(self.myStateKey)
-  def setState(self, machine):
-    machine.setPendingState(self.key().instanceGenerator(machine), self.myInitializer.clone())
-  
+    def __init__(self):
+        self.myInitializer = None
+        self.myStateKey = 0
+
+    def __del__(self):
+        self.myInitializer.destroy()
+
+    def init_history(self, key, history=False):
+        global _theHistoryInitializer
+        global _theDefaultInitializer
+        self.myStateKey = key
+        if history:
+            self.myInitializer = _theHistoryInitializer
+        else:
+            self.myInitializer = _theDefaultInitializer
+
+    def init_Initializer(self, key, init):
+        self.myStateKey = key
+        self.myInitializer = init
+
+    def init_Alias(self, other):
+        self.myStateKey = key
+        self.myInitializer = other.myInitializer.clone()
+
+    def equal(self, other):
+        if self is other:
+            return self
+        self.myInitializer.destroy()
+        self.myStateKey = other.childPredicate
+        self.myInitializer = other.childPredicate
+
+    def Key(self):
+        return self.key()
+
+    def isChild(self, k):
+        return self.key().childPredicate(k)
+
+    def isParent(self, k):
+        return self.key().childPredicate(k)
+
+    def name(self):
+        return self.key().name
+
+    def id(self):
+        return self.key().id
+
+    def key(self):
+        return self.myInitializer.adapt(self.myStateKey)
+
+    def setState(self, machine):
+        machine.setPendingState(
+            self.key().instanceGenerator(machine),
+            self.myInitializer.clone())
+
+
 """
 def State(S):
   return Alias(S.key())
@@ -899,319 +1072,345 @@ def StateHistory(S, machine):
 
 
 class Snapshot(_MachineBase):
-  def __init__(self, machine):
-    super(Snapshot,self).__init__()
-    self.allocate(Machine.theStateCount)
-    self.copy(machine.myInstances, Machine.theStateCounta)
-    self.myCurrentState = self.getInstances[machine.myCurrentState.id()]
-    
-  def __del__(self):
-    self.free(Machine.theStateCount)
+    def __init__(self, machine):
+        super(Snapshot, self).__init__()
+        self.allocate(Machine.theStateCount)
+        self.copy(machine.myInstances, Machine.theStateCounta)
+        self.myCurrentState = self.getInstances[machine.myCurrentState.id()]
+
+    def __del__(self):
+        self.free(Machine.theStateCount)
+
 
 class AfterAdvice:
-  def __init__(self, m):
-    self.myMachine = m
-  def __del__(self):
-    pass
-    #self.myMachine.rattleOn()
-  def __call__(self, func, *args):
-    spec = self.myMachine.myCurrentState.specification()
-    ret = getattr(spec,func)(*args)
-    self.myMachine.rattleOn()
-    return ret
-    
-    #return self.myMachine.myCurrentState.specification()
+    def __init__(self, m):
+        self.myMachine = m
+
+    def __del__(self):
+        pass
+        # self.myMachine.rattleOn()
+
+    def __call__(self, func, *args):
+        spec = self.myMachine.myCurrentState.specification()
+        ret = getattr(spec, func)(*args)
+        self.myMachine.rattleOn()
+        return ret
+
+        # return self.myMachine.myCurrentState.specification()
 
 
-    
 class Machine(_MachineBase):
-  theStateCount = 1
-  #def __init__(self, TOP, TopBase):
-  def __init__(self, TOP, initial_state=None, args=()):
-    super(Machine,self).__init__()
-    self.TOP = TOP
-    self.TopBase = TOP.SUPER(TOP._state_name)
-    self.init(box=None, initial_state=initial_state, args=args)
-    self._mutex = threading.RLock()
-  def __del__(self):
-    pass
-  def shutdown(self):
-    guard = OpenRTM_aist.ScopedLock(self._mutex)
-    self.myCurrentState.shutdown()
-    self.free(Machine.theStateCount)
-    Machine.theStateCount = 1
-  
-  def init(self, box=None,initial_state=None, args=()):
-    self.allocate(Machine.theStateCount)
-    top = self.TOP._getInstance(self, self.TopBase, self.TOP)
-    if box:
-      top.setBox(box)
-    if initial_state:
-      instance = initial_state._getInstance(self, initial_state.SUPER, initial_state)
-      self.start(instance, *args)
-    else:
-      self.start(top, *args)
-    
-  def init_Alias(self, state, box=None):
-    self.allocate(Machine.theStateCount)
-    top = self.TOP._getInstance(self, self.TopBase, self.TOP)
-    if box:
-      top.setBox(box)
-    self.start(state)
-  def init_Snapshot(self, snapshot, box=None):
-    self.allocate(Machine.theStateCount)
-    self.copy(snapshot.myInstances, Machine.theStateCount)
-  def equal(self, snapshot):
-    self.myCurrentState.shutdown()
-    self.free(Machine.theStateCount)
-    self.copy(snapshot.myInstances, Machine.theStateCount)
-    self.myCurrentState = self.getInstance(0)
-    current = self.getInstance(snapshot.myCurrentState.id())
-    current.restore(current)
-    self.rattleOn()
-    return self
-  def __call__(self):
-    return AfterAdvice(self)
-  def dispatch(self, event, destroy=True):
-    guard = OpenRTM_aist.ScopedLock(self._mutex)
-    event.dispatch(self.myCurrentState)
-    if destroy:
-      del event
-    self.rattleOn()
-
-  def box(self):
-    self.myCurrentState.specification().box()
-  def data(self):
-    self.myCurrentState.specification().box()
-
-  def getCurrentState(self):
-    return self.myCurrentState
-  def setCurrentState(self, S):
-    self.myCurrentState = S
-  def _current_state(self):
-    return self.myCurrentState
-  _current_state = property(getCurrentState, setCurrentState)
-
-  
-  def getCurrent(self):
-    spec = self.myCurrentState.specification()
-    class EventDelegator(object):
-      def __init__(self):
+    theStateCount = 1
+    # def __init__(self, TOP, TopBase):
+
+    def __init__(self, TOP, initial_state=None, args=()):
+        super(Machine, self).__init__()
+        self.TOP = TOP
+        self.TopBase = TOP.SUPER(TOP._state_name)
+        self.init(box=None, initial_state=initial_state, args=args)
+        self._mutex = threading.RLock()
+
+    def __del__(self):
         pass
-    ed = EventDelegator()
-    for name in dir(spec):
-      if name.startswith('__'):
-        continue
-      if hasattr(StateDef, name):
-        continue
-      if not isinstance(getattr(spec, name), types.MethodType):
-        continue
-      class Spec_Func(object):
-        def __init__(self, spec, name, machine):
-          self._spec = spec
-          self._name = name
-          self._machine = machine
-        def __call__(self, *args):
-          ret = getattr(self._spec,self._name)(*args)
-          self._machine.rattleOn()
-          return ret
-        
-      setattr(ed, name, Spec_Func(spec, name, self))
-    return ed
-  def setCurrent(self, state):
-    self.myCurrentState = state
-  current = property(getCurrent, setCurrent)
-
-  def addDeferEvent(self, event):
-    self.myDeferEvents.append(event)
-    
-  def is_current(self, info):
-    if info.StateID == self.myCurrentState.id():
-      return True
-    #elif Link.isChild(info, self.myCurrentState.specification().__class__):
-    #  return True
-    elif Link.isChild(self.myCurrentState.specification().__class__, info):
-      return True
-    else:
-      return False
 
-  def is_current_direct(self, info):
-    if info.StateID == self.myCurrentState.id():
-      return True
-    else:
-      return False
-      
-    
+    def shutdown(self):
+        guard = OpenRTM_aist.ScopedLock(self._mutex)
+        self.myCurrentState.shutdown()
+        self.free(Machine.theStateCount)
+        Machine.theStateCount = 1
+
+    def init(self, box=None, initial_state=None, args=()):
+        self.allocate(Machine.theStateCount)
+        top = self.TOP._getInstance(self, self.TopBase, self.TOP)
+        if box:
+            top.setBox(box)
+        if initial_state:
+            instance = initial_state._getInstance(
+                self, initial_state.SUPER, initial_state)
+            self.start(instance, *args)
+        else:
+            self.start(top, *args)
+
+    def init_Alias(self, state, box=None):
+        self.allocate(Machine.theStateCount)
+        top = self.TOP._getInstance(self, self.TopBase, self.TOP)
+        if box:
+            top.setBox(box)
+        self.start(state)
+
+    def init_Snapshot(self, snapshot, box=None):
+        self.allocate(Machine.theStateCount)
+        self.copy(snapshot.myInstances, Machine.theStateCount)
+
+    def equal(self, snapshot):
+        self.myCurrentState.shutdown()
+        self.free(Machine.theStateCount)
+        self.copy(snapshot.myInstances, Machine.theStateCount)
+        self.myCurrentState = self.getInstance(0)
+        current = self.getInstance(snapshot.myCurrentState.id())
+        current.restore(current)
+        self.rattleOn()
+        return self
+
+    def __call__(self):
+        return AfterAdvice(self)
+
+    def dispatch(self, event, destroy=True):
+        guard = OpenRTM_aist.ScopedLock(self._mutex)
+        event.dispatch(self.myCurrentState)
+        if destroy:
+            del event
+        self.rattleOn()
+
+    def box(self):
+        self.myCurrentState.specification().box()
+
+    def data(self):
+        self.myCurrentState.specification().box()
+
+    def getCurrentState(self):
+        return self.myCurrentState
+
+    def setCurrentState(self, S):
+        self.myCurrentState = S
+
+    def _current_state(self):
+        return self.myCurrentState
+    _current_state = property(getCurrentState, setCurrentState)
+
+    def getCurrent(self):
+        spec = self.myCurrentState.specification()
+
+        class EventDelegator(object):
+            def __init__(self):
+                pass
+        ed = EventDelegator()
+        for name in dir(spec):
+            if name.startswith('__'):
+                continue
+            if hasattr(StateDef, name):
+                continue
+            if not isinstance(getattr(spec, name), types.MethodType):
+                continue
+
+            class Spec_Func(object):
+                def __init__(self, spec, name, machine):
+                    self._spec = spec
+                    self._name = name
+                    self._machine = machine
+
+                def __call__(self, *args):
+                    ret = getattr(self._spec, self._name)(*args)
+                    self._machine.rattleOn()
+                    return ret
+
+            setattr(ed, name, Spec_Func(spec, name, self))
+        return ed
+
+    def setCurrent(self, state):
+        self.myCurrentState = state
+    current = property(getCurrent, setCurrent)
+
+    def addDeferEvent(self, event):
+        self.myDeferEvents.append(event)
+
+    def is_current(self, info):
+        if info.StateID == self.myCurrentState.id():
+            return True
+        # elif Link.isChild(info, self.myCurrentState.specification().__class__):
+        #  return True
+        elif Link.isChild(self.myCurrentState.specification().__class__, info):
+            return True
+        else:
+            return False
+
+    def is_current_direct(self, info):
+        if info.StateID == self.myCurrentState.id():
+            return True
+        else:
+            return False
+
+
 def _createBox(place, B=None):
-  if B:
-    return B()
-  else:
-    return _EmptyBox.theEmptyBox
+    if B:
+        return B()
+    else:
+        return _EmptyBox.theEmptyBox
 
 
 def _deleteBox(box, place):
-  pass
+    pass
+
 
 def _cloneBox(other):
-  return _EmptyBox.theEmptyBox
+    return _EmptyBox.theEmptyBox
 
 
 def TopBase(TOP):
-  class TopBase_(_StateSpecification):
-    SUPER = _StateSpecification
-    StateID = 0
-    def __init__(self, instance):
-      super(TopBase_,self).__init__(instance)
-      self.T = TOP
-    def dispatch(self, event):
-      self._myStateInstance.machine().setPendingEvent(event)
-    def machine(self):
-      return self._myStateInstance.machine()
-    def defer(self, event):
-      self._myStateInstance.machine().addDeferEvent(event)
+    class TopBase_(_StateSpecification):
+        SUPER = _StateSpecification
+        StateID = 0
+
+        def __init__(self, instance):
+            super(TopBase_, self).__init__(instance)
+            self.T = TOP
 
-  
-    
+        def dispatch(self, event):
+            self._myStateInstance.machine().setPendingEvent(event)
+
+        def machine(self):
+            return self._myStateInstance.machine()
+
+        def defer(self, event):
+            self._myStateInstance.machine().addDeferEvent(event)
+
+    return TopBase_
 
-  return TopBase_
 
 def topstate(cls):
-  class TOP(cls):
-    def __init__(self, instance):
-      super(cls,self).__init__(instance)
-    def on_init(self, *args):
-        return cls.on_init(self, *args)
-    def on_entry(self, *args):
-        return cls.on_entry(self, *args)
-    def on_exit(self, *args):
-        return cls.on_exit(self, *args)
-
-      
-  TOP.SUPER = TopBase(TOP)
-  TOP.StateID = Machine.theStateCount
-  Machine.theStateCount += 1
-  TOP._state_name = staticmethod(lambda  : TOP.__name__)
-  
-  TOP.box = lambda self: self._box()
-  TOP.HISTORY = False
-
-  if hasattr(TOP, 'Data'):
-    TOP.Box = TOP.Data
-    
-  
-  return TOP
+    class TOP(cls):
+        def __init__(self, instance):
+            super(cls, self).__init__(instance)
 
-def substate(superstate):
-  def _substate(cls):
-    class STATE(cls, superstate):
-      def __init__(self, instance):
-        cls.__init__(self, instance)
-      def on_init(self, *args):
-        return cls.on_init(self, *args)
-      def on_entry(self, *args):
-        return cls.on_entry(self, *args)
-      def on_exit(self, *args):
-        return cls.on_exit(self, *args)
-
-    STATE.SUPER = superstate
-    STATE.StateID = Machine.theStateCount
+        def on_init(self, *args):
+            return cls.on_init(self, *args)
+
+        def on_entry(self, *args):
+            return cls.on_entry(self, *args)
+
+        def on_exit(self, *args):
+            return cls.on_exit(self, *args)
+
+    TOP.SUPER = TopBase(TOP)
+    TOP.StateID = Machine.theStateCount
     Machine.theStateCount += 1
-    STATE._state_name = staticmethod(lambda : cls.__name__)
-    STATE.box = lambda self: self._box()
-    STATE.HISTORY = False
-    #STATE.data = lambda self: self._box()
+    TOP._state_name = staticmethod(lambda: TOP.__name__)
+
+    TOP.box = lambda self: self._box()
+    TOP.HISTORY = False
+
+    if hasattr(TOP, 'Data'):
+        TOP.Box = TOP.Data
+
+    return TOP
+
+
+def substate(superstate):
+    def _substate(cls):
+        class STATE(cls, superstate):
+            def __init__(self, instance):
+                cls.__init__(self, instance)
+
+            def on_init(self, *args):
+                return cls.on_init(self, *args)
+
+            def on_entry(self, *args):
+                return cls.on_entry(self, *args)
+
+            def on_exit(self, *args):
+                return cls.on_exit(self, *args)
 
-    if hasattr(STATE, 'Data'):
-      STATE.Box = STATE.Data
+        STATE.SUPER = superstate
+        STATE.StateID = Machine.theStateCount
+        Machine.theStateCount += 1
+        STATE._state_name = staticmethod(lambda: cls.__name__)
+        STATE.box = lambda self: self._box()
+        STATE.HISTORY = False
+        #STATE.data = lambda self: self._box()
 
-    return STATE
-  return _substate
+        if hasattr(STATE, 'Data'):
+            STATE.Box = STATE.Data
 
+        return STATE
+    return _substate
 
 
 def history(cls):
-  def _saveHistory(self,instance,shallow,deep):
-    if not instance.getHistory():
-      instance.setHistory(shallow)
-    #self[self.SUPER]._setHistorySuper(instance,shallow)
-    
-  cls._saveHistory = _saveHistory
+    def _saveHistory(self, instance, shallow, deep):
+        if not instance.getHistory():
+            instance.setHistory(shallow)
+        # self[self.SUPER]._setHistorySuper(instance,shallow)
+
+    cls._saveHistory = _saveHistory
+
+    cls._setHistorySuper = lambda self, instance, deep: instance.setHistorySuper(
+        deep)
+    cls.HISTORY = True
+    return cls
 
-  cls._setHistorySuper = lambda self,instance,deep: instance.setHistorySuper(deep)
-  cls.HISTORY = True
-  return cls
 
 def deephistory(cls):
-  def _saveHistory(self,instance,shallow,deep):
-    instance.setHistory(deep)
-    self[self.SUPER]._setHistorySuper(instance,deep)
-    
-  cls._saveHistory = _saveHistory
+    def _saveHistory(self, instance, shallow, deep):
+        instance.setHistory(deep)
+        self[self.SUPER]._setHistorySuper(instance, deep)
+
+    cls._saveHistory = _saveHistory
+
+    cls._setHistorySuper = lambda self, instance, deep: instance.setHistorySuper(
+        deep)
+    cls.HISTORY = True
+    return cls
 
-  cls._setHistorySuper = lambda self,instance,deep: instance.setHistorySuper(deep)
-  cls.HISTORY = True
-  return cls
 
-  
 def TOPSTATE(TOP):
-  TOP.SUPER = TopBase(TOP)
-  TOP.StateID = Machine.theStateCount
-  Machine.theStateCount += 1
-  TOP._state_name = staticmethod(lambda  : TOP.__name__)
-  
-  TOP.box = lambda self: self._box()
-  
+    TOP.SUPER = TopBase(TOP)
+    TOP.StateID = Machine.theStateCount
+    Machine.theStateCount += 1
+    TOP._state_name = staticmethod(lambda: TOP.__name__)
+
+    TOP.box = lambda self: self._box()
+
 
 def SUBSTATE(STATE, SUPERSTATE):
-  STATE.SUPER = SUPERSTATE
-  STATE.StateID = Machine.theStateCount
-  Machine.theStateCount += 1
-  STATE._state_name = staticmethod(lambda : STATE.__name__)
-  STATE.box = lambda self: self._box()
+    STATE.SUPER = SUPERSTATE
+    STATE.StateID = Machine.theStateCount
+    Machine.theStateCount += 1
+    STATE._state_name = staticmethod(lambda: STATE.__name__)
+    STATE.box = lambda self: self._box()
+
 
 def DEEPHISTORY(STATE):
-  def _saveHistory(self,instance,shallow,deep):
-    instance.setHistory(deep)
-    self[self.SUPER]._setHistorySuper(instance,deep)
-    
-  STATE._saveHistory = _saveHistory
+    def _saveHistory(self, instance, shallow, deep):
+        instance.setHistory(deep)
+        self[self.SUPER]._setHistorySuper(instance, deep)
+
+    STATE._saveHistory = _saveHistory
+
+    STATE._setHistorySuper = lambda self, instance, deep: instance.setHistorySuper(
+        deep)
 
-  STATE._setHistorySuper = lambda self,instance,deep: instance.setHistorySuper(deep)
 
 def HISTORY(STATE):
-  def _saveHistory(self,instance,shallow,deep):
-    instance.setHistory(deep)
-    self[self.SUPER]._setHistorySuper(instance,deep)
-    
-  STATE._saveHistory = _saveHistory
+    def _saveHistory(self, instance, shallow, deep):
+        instance.setHistory(deep)
+        self[self.SUPER]._setHistorySuper(instance, deep)
 
-  STATE._setHistorySuper = lambda self,instance,deep: instance.setHistorySuper(deep)
+    STATE._saveHistory = _saveHistory
+
+    STATE._setHistorySuper = lambda self, instance, deep: instance.setHistorySuper(
+        deep)
 
 
 StateDef = Link
 
 
 def State(S):
-  return S
-
+    return S
 
 
+class logger(object):
+    rtcout = None
 
+    def __init__(self):
+        pass
 
-class logger(object):
-  rtcout = None
-  def __init__(self):
-    pass
-  
-  def debug(mes):
-    logger.setLoggerFile()
-    logger.rtcout.RTC_DEBUG(mes)
-    
-  debug = staticmethod(debug)
-  
-  def setLoggerFile():
-    if logger.rtcout is None:
-      logger.rtcout = OpenRTM_aist.Manager.instance().getLogbuf('Macho')
-  setLoggerFile = staticmethod(setLoggerFile)
+    def debug(mes):
+        logger.setLoggerFile()
+        logger.rtcout.RTC_DEBUG(mes)
 
+    debug = staticmethod(debug)
 
+    def setLoggerFile():
+        if logger.rtcout is None:
+            logger.rtcout = OpenRTM_aist.Manager.instance().getLogbuf('Macho')
+    setLoggerFile = staticmethod(setLoggerFile)
diff --git a/OpenRTM_aist/Manager.py b/OpenRTM_aist/Manager.py
index 92ae20bd..396cda11 100644
--- a/OpenRTM_aist/Manager.py
+++ b/OpenRTM_aist/Manager.py
@@ -1,5 +1,5 @@
 #!/usr/bin/env python
-# -*- coding: euc-jp -*-
+# -*- coding: utf-8 -*-
 
 ##
 # @file Manager.py
@@ -16,12 +16,13 @@
 
 import threading
 
-import signal, os
+import signal
+import os
 
 import sys
 import time
 from omniORB import CORBA, PortableServer
-#from types import IntType, ListType
+# from types import IntType, ListType
 
 
 import OpenRTM_aist
@@ -32,13 +33,13 @@
 import CORBA_IORUtil
 
 
-#------------------------------------------------------------
+# ------------------------------------------------------------
 # static var
-#------------------------------------------------------------
+# ------------------------------------------------------------
 
 ##
 # @if jp
-# @brief ͣ Manager ؤΥݥ
+# @brief 唯一の Manager へのポインタ
 # @else
 # @brief The pointer to the Manager
 # @endif
@@ -46,84 +47,63 @@
 
 ##
 # @if jp
-# @brief ͣ Manager ؤΥݥ󥿤Ф mutex
+# @brief 唯一の Manager へのポインタに対する mutex
 # @else
-# @brief The mutex of the pointer to the Manager 
+# @brief The mutex of the pointer to the Manager
 # @endif
 mutex = threading.RLock()
 
 ##
 # @if jp
-# @brief WindowsAlarm
+# @brief Windows用Alarm
 # @else
 # @brief Alarm for Windows
 # @endif
 
 
-import threading
-
 class Alarm (threading.Thread):
-  def __init__ (self, timeout):
-    threading.Thread.__init__ (self)
-    self.timeout = timeout
-    self.setDaemon(True)
-  def run (self):
-    time.sleep(self.timeout)
-    os._exit(1)
+    def __init__(self, timeout):
+        threading.Thread.__init__(self)
+        self.timeout = timeout
+        self.setDaemon(True)
+
+    def run(self):
+        time.sleep(self.timeout)
+        os._exit(1)
 
 ##
 # @if jp
-# @brief λ
+# @brief 終了処理
 #
-# ޥ͡λ
+# マネージャを終了させる
 #
-# @param signum ʥֹ
-# @param frame ߤΥåե졼
+# @param signum シグナル番号
+# @param frame 現在のスタックフレーム
 #
 # @else
 #
 # @endif
+
+
 def handler(signum, frame):
-  mgr = OpenRTM_aist.Manager.instance()
-  mgr.terminate()
-  import os
-  if os.sep == '/':
-    signal.alarm(2)
-  else:
-    alarm = Alarm(2)
-    alarm.start()
+    mgr = OpenRTM_aist.Manager.instance()
+    mgr.terminate()
+    import os
+    if os.sep == '/':
+        signal.alarm(2)
+    else:
+        alarm = Alarm(2)
+        alarm.start()
+
 
 
-##
-# @if jp
-# @brief ޥ͡㽪λå
-#
-# 
-#
-#
-# @else
-#
-# @endif
-class terminate_Task(OpenRTM_aist.Task):
-  ##
-  # @brief 󥹥ȥ饯
-  # @param self
-  # @param mgr ޥ͡
-  # @param sleep_time Ե
-  def __init__(self, mgr, sleep_time):
-    OpenRTM_aist.Task.__init__(self)
-    self._mgr = mgr
-    self._sleep_time = sleep_time
-  def svc(self):
-    time.sleep(self._sleep_time)
-    self._mgr.terminate()
 
 ##
 # @if jp
 # @class Manager
-# @brief Manager 饹
+# @brief Manager クラス
 #
-# ݡͥȤʤɳƼξԤޥ͡㥯饹
+# コンポーネントなど各種の情報管理を行うマネージャクラス。
 #
 # @since 0.2.0
 #
@@ -131,3544 +111,3576 @@ def svc(self):
 # @class Manager
 # @brief Manager class
 # @endif
-class Manager:
-  """
-  """
-
-
-
-  ##
-  # @if jp
-  # @brief ԡ󥹥ȥ饯
-  #
-  # ԡ󥹥ȥ饯
-  #
-  # @param self
-  # @param _manager ԡޥ͡㥪֥(ǥե:None)
-  #
-  # @else
-  # @brief Protected Copy Constructor
-  #
-  # @endif
-  def __init__(self, _manager=None):
-    self._initProc   = None
-    self._runner     = None
-    self._terminator = None
-    self._shutdown_thread = None
-    self._compManager = OpenRTM_aist.ObjectManager(self.InstanceName)
-    self._factory = OpenRTM_aist.ObjectManager(self.FactoryPredicate)
-    self._ecfactory = OpenRTM_aist.ObjectManager(self.ECFactoryPredicate)
-    self._terminate = self.Term()
-    self._ecs = []
-    self._timer = None
-    self._orb = None
-    self._poa = None
-    self._poaManager = None 
-    self._finalized = self.Finalized()
-    self._listeners = OpenRTM_aist.ManagerActionListeners()
-    signal.signal(signal.SIGINT, handler)
-    self._rtcout = None
-    self._mgrservant = None
-    
-    
-    return
-
-
-  ##
-  # @if jp
-  # @brief ޥ͡ν
-  #
-  # ޥ͡ static ؿ
-  # ޥ͡򥳥ޥɥ饤Ϳƽ롣
-  # ޥ͡Ѥϡɬνдؿ init() 
-  # ƤФʤФʤʤ
-  # ޥ͡Υ󥹥󥹤ˡȤơinit(), instance() 
-  # 2Ĥ static ؿѰդƤ뤬init()ǤԤʤᡢ
-  # Manager ¸֤ΰֺǽˤinit()Ƥɬפ롣
-  #
-  # ޥ͡ν
-  # - initManager: configեɤ߹ߡ֥ƥ
-  # - initLogger: Logger
-  # - initORB: ORB 
-  # - initNaming: NamingService 
-  # - initExecutionContext: ExecutionContext factory 
-  # - initTimer: Timer 
-  #
-  # @param argv ޥɥ饤
-  # 
-  # @return Manager ͣΥ󥹥󥹤λ
-  #
-  # @else
-  # @brief Initializa manager
-  #
-  # This is the static function to tintialize the Manager.
-  # The Manager is initialized by given arguments.
-  # At the starting the manager, this static function "must" be called from
-  # application program. The manager has two static functions to get 
-  # the instance, "init()" and "instance()". Since initializing
-  # process is only performed by the "init()" function, the "init()" has
-  # to be called at the beginning of the lifecycle of the Manager.
-  # function.
-  #
-  # @param argv The array of the command line arguments.
-  #
-  # @endif
-  def init(*arg):
-    global manager
-    global mutex
-    if len(arg) == 1:
-      argv = arg[0]
-    elif len(arg) == 2 and \
-             isinstance(arg[0], int) and \
-             isinstance(arg[1], list):
-      # for 0.4.x
-      argv = arg[1]
-    else:
-      print("Invalid arguments for init()")
-      print("init(argc,argv) or init(argv)")
-      return None
-        
-    if manager is None:
-      guard = OpenRTM_aist.ScopedLock(mutex)
-
-      manager = Manager()
-      manager.initManager(argv)
-      manager.initFactories()
-      manager.initLogger()
-      manager.initORB()
-      manager.initNaming()
-      manager.initExecContext()
-      manager.initComposite()
-      manager.initTimer()
-      manager.initManagerServant()
-
-    return manager
-  
-  init = staticmethod(init)
-
-
-  ##
-  # @if jp
-  # @brief ޥ͡Υ󥹥󥹤μ
-  #
-  # ޥ͡Υ󥹥󥹤 static ؿ
-  # δؿƤˡɬνؿ init() ƤФƤɬפ롣
-  #
-  # @return Manager ͣΥ󥹥󥹤λ
-  # 
-  # @else
-  #
-  # @brief Get instance of the manager
-  #
-  # This is the static function to get the instance of the Manager.
-  # Before calling this function, ensure that the initialization function
-  # "init()" is called.
-  #
-  # @return The only instance reference of the manager
-  #
-  # @endif
-  def instance():
-    global manager
-    global mutex
-    
-    if manager is None:
-      guard = OpenRTM_aist.ScopedLock(mutex)
-      manager = Manager()
-      manager.initManager(None)
-      manager.initFactories()
-      manager.initLogger()
-      manager.initORB()
-      manager.initNaming()
-      manager.initExecContext()
-      manager.initComposite()
-      manager.initTimer()
-      manager.initManagerServant()
-
-    return manager
-
-  instance = staticmethod(instance)
-
-
-  ##
-  # @if jp
-  # @brief ޥ͡㽪λ
-  #
-  # ޥ͡νλ¹Ԥ롣
-  #
-  # @param self
-  #
-  # @else
-  #
-  # @endif
-  def terminate(self):
-    if self._terminator:
-      self._terminator.terminate()
-
-
-  ##
-  # @if jp
-  # @brief ޥ͡㡦åȥ
-  #
-  # ޥ͡νλ¹Ԥ롣
-  # ORBλ塢Ʊäƽλ롣
-  #
-  # @param self
-  #
-  # @else
-  #
-  # @endif
-  def shutdown(self):
-    self._rtcout.RTC_TRACE("Manager.shutdown()")
-    self._listeners.manager_.preShutdown()
-    self.shutdownTimer()
-    self.shutdownComponents()
-    self.shutdownManagerServant()
-    self.shutdownNaming()
-    self.shutdownORB()
-    self.shutdownManager()
-
-    if self._runner:
-      self._runner.wait()
-    else:
-      self.join()
-
-    self._listeners.manager_.postShutdown()
-    self.shutdownLogger()
-    global manager
-    if manager:
-      manager = None
-
-
-  ##
-  # @if jp
-  # @brief ޥ͡㽪λԤ碌
-  #
-  # Ʊ뤿ᡢޥ͡㽪λԤ碌Ԥ
-  #
-  # @param self
-  #
-  # @else
-  #
-  # @endif
-  def join(self):
-    self._rtcout.RTC_TRACE("Manager.wait()")
-    guard = OpenRTM_aist.ScopedLock(self._terminate.mutex)
-    self._terminate.waiting += 1
-    del guard
-    while 1:
-      guard = OpenRTM_aist.ScopedLock(self._terminate.mutex)
-      #if self._terminate.waiting > 1:
-      if self._terminate.waiting > 0:
-        break
-      del guard
-      time.sleep(0.001)
-
-
-  ##
-  # @if jp
-  #
-  # @brief ץΥå
-  #
-  # Υڥ졼ϥ桼Ԥ⥸塼νץ
-  # ꤹ롣ꤵ줿ץϡޥ͡㤬졢
-  # ƥֲ줿塢Ŭڤʥߥ󥰤Ǽ¹Ԥ롣
-  #
-  # @param self
-  # @param proc ץδؿݥ
-  #
-  # @else
-  #
-  # @brief Run the Manager
-  #
-  # This operation sets the initial procedure call to process module
-  # initialization, other user defined initialization and so on.
-  # The given procedure will be called at the proper timing after the 
-  # manager initialization, activation and run.
-  #
-  # @param proc A function pointer to the initial procedure call
-  #
-  # @endif
-  def setModuleInitProc(self, proc):
-    self._initProc = proc
-    return
-
-
-  ##
-  # @if jp
-  #
-  # @brief ManagerΥƥֲ
-  #
-  # Υڥ졼ϰʲνԤ
-  # - CORBA POAManager Υƥֲ
-  # - ޥ͡CORBA֥ȤΥƥֲ
-  # - Manager ֥Ȥؤνץμ¹
-  #
-  # Υڥ졼ϡޥ͡ν塢runManager()
-  # ˸Ƥɬפ롣
-  #
-  # @param self
-  #
-  # @return (ƥֲ:true:false)
-  #
-  # @else
-  #
-  # @brief Activate Manager
-  #
-  # This operation do the following,
-  # - Activate CORBA POAManager
-  # - Activate Manager CORBA object
-  # - Execute the initial procedure call of the Manager
-  #
-  # This operationo should be invoked after Manager:init(),
-  # and before tunManager().
-  #
-  # @endif
-  def activateManager(self):
-    self._rtcout.RTC_TRACE("Manager.activateManager()")
-
-    try:
-      self.getPOAManager().activate()
-      self._rtcout.RTC_TRACE("POA Manager activated.")
-    except:
-      self._rtcout.RTC_ERROR("Exception: POA Manager activation failed.")
-      self._rtcout.RTC_ERROR(OpenRTM_aist.Logger.print_exception())
-      return False
-
-    lsvc_ = [s.strip() for s in self._config.getProperty("manager.local_service.modules").split(",")]
-    for svc_ in lsvc_:
-      if len(svc_) == 0: continue
-      basename_ = svc_.split(".")[0]+"Init"
-      try:
-        self._module.load(svc_, basename_)
-      except:
-        self._rtcout.RTC_ERROR(OpenRTM_aist.Logger.print_exception())
-
-    self.initLocalService()
-
-    mods = [s.strip() for s in self._config.getProperty("manager.modules.preload").split(",")]
-
-    for i in range(len(mods)):
-      if mods[i] is None or mods[i] == "":
-        continue
-      mods[i] = mods[i].strip()
-      
-
-      basename = os.path.basename(mods[i]).split(".")[0]
-      basename += "Init"
-
-      try:
-        self._module.load(mods[i], basename)
-      except:
-        self._rtcout.RTC_ERROR(OpenRTM_aist.Logger.print_exception())
-        self.__try_direct_load(basename)
-
-    sdofactory_ = OpenRTM_aist.SdoServiceConsumerFactory.instance()
-    self._config.setProperty("sdo.service.consumer.available_services",
-                             OpenRTM_aist.flatten(sdofactory_.getIdentifiers()))
-
-
-    self.invokeInitProc()
-    self.initPreCreation()
-    
-    self.initPreConnection()
-    self.initPreActivation()
-
-    return True
-
-
-  ##
-  # @if jp
-  #
-  # @brief Managerμ¹
-  #
-  # Υڥ졼ϥޥ͡Υᥤ롼פ¹Ԥ롣
-  # Υᥤ롼ǤϡCORBA ORBΥ٥ȥ롼
-  # 롣ǥեȤǤϡΥڥ졼ϥ֥å
-  # Manager::destroy() ƤФޤǽᤵʤ
-  #  no_block  true ꤵƤϡǥ٥ȥ롼
-  # 륹åɤư֥å˽᤹
-  #
-  # @param self
-  # @param no_block false: ֥å󥰥⡼, true: Υ֥å󥰥⡼
-  #
-  # @else
-  #
-  # @brief Run the Manager
-  #
-  # This operation processes the main event loop of the Manager.
-  # In this main loop, CORBA's ORB event loop or other processes
-  # are performed. As the default behavior, this operation is going to
-  # blocking mode and never returns until manager::destroy() is called.
-  # When the given argument "no_block" is set to "true", this operation
-  # creates a thread to process the event loop internally, and it doesn't
-  # block and returns.
-  #
-  # @param no_block false: Blocking mode, true: non-blocking mode.
-  #
-  # @endif
-  def runManager(self, no_block=None):
-    if no_block is None:
-      no_block = False
-      
-    if no_block:
-      self._rtcout.RTC_TRACE("Manager.runManager(): non-blocking mode")
-      self._runner = self.OrbRunner(self._orb)
-    else:
-      self._rtcout.RTC_TRACE("Manager.runManager(): blocking mode")
-      try:
-        self._orb.run()
-        self._rtcout.RTC_TRACE("Manager.runManager(): ORB was terminated")
-        self.join()
-      except:
-        self._rtcout.RTC_ERROR(OpenRTM_aist.Logger.print_exception())
-      if self._shutdown_thread:
-        self._shutdown_thread.wait()
-    
-    return
-
-
-  ##
-  # @if jp
-  # @brief [CORBA interface] ⥸塼Υ
-  #
-  # ꤷݡͥȤΥ⥸塼ɤȤȤˡ
-  # ꤷؿ¹Ԥ롣
-  #
-  # @param self
-  # @param fname   ⥸塼ե̾
-  # @param initfunc ؿ̾
-  # @return 顼
-  #         RTC::RTC_OK ェλ
-  #         RTC::RTC_ERROR ɼԡʥ顼
-  #         RTC::PRECONDITION_NOT_MET ˤĤʤ
-  #         RTC::BAD_PARAMETER ʥѥ᡼
-  # 
-  # @else
-  #
-  # @brief [CORBA interface] Load module
-  #
-  # Load module (shared library, DLL etc..) by file name,
-  # and invoke initialize function.
-  #
-  # @param fname    The module file name
-  # @param initfunc The initialize function name
-  # @return Return code
-  #         RTC::RTC_OK Normal return
-  #         RTC::RTC_ERROR Load failed, or unknown error
-  #         RTC::PRECONDITION_NOT_MET Not allowed operation by conf
-  #         RTC::BAD_PARAMETER Invalid parameter
-  #
-  # @endif
-  def load(self, fname, initfunc):
-    self._rtcout.RTC_TRACE("Manager.load(fname = %s, initfunc = %s)",
-                           (fname, initfunc))
-    fname = fname.replace("/", os.sep)
-    fname = fname.replace("\\", os.sep)
-    self._listeners.module_.preLoad(fname, initfunc)
-    try:
-      fname_ = fname.split(os.sep)
-      
-      if len(fname_) > 1:
-        fname_ = fname_[-1]
-      else:
-        fname_ = fname_[0]
-
-      if not initfunc:
-        mod = [s.strip() for s in fname_.split(".")]
-        initfunc = mod[0]+"Init"
-      path = self._module.load(fname, initfunc)
-      self._rtcout.RTC_DEBUG("module path: %s", path)
-      self._listeners.module_.postLoad(path, initfunc)
-    except OpenRTM_aist.ModuleManager.NotAllowedOperation as e:
-      self._rtcout.RTC_ERROR("Operation not allowed: %s",(e.reason))
-      return RTC.PRECONDITION_NOT_MET
-    except OpenRTM_aist.ModuleManager.NotFound:
-      self._rtcout.RTC_ERROR("Not found: %s",(fname))
-      return RTC.RTC_ERROR
-    except OpenRTM_aist.ModuleManager.FileNotFound:
-      self._rtcout.RTC_ERROR("Not found: %s",(fname))
-      return RTC.RTC_ERROR
-    except OpenRTM_aist.ModuleManager.InvalidArguments as e:
-      self._rtcout.RTC_ERROR("Invalid argument: %s",(e.reason))
-      return RTC.BAD_PARAMETER
-    #except OpenRTM_aist.ModuleManager.Error as e:
-    #  self._rtcout.RTC_ERROR("Error: %s",(e.reason))
-    #  return RTC.RTC_ERROR
-    except:
-      self._rtcout.RTC_ERROR("Unknown error.")
-      return RTC.RTC_ERROR
-      #self.__try_direct_load(fname)
-
-    return RTC.RTC_OK
-
-
-  ##
-  # @if jp
-  #
-  # @brief ⥸塼Υ
-  #
-  # ⥸塼򥢥ɤ
-  #
-  # @param self
-  # @param fname ⥸塼Υե̾
-  # 
-  # @else
-  #
-  # @brief Unload module
-  #
-  # Unload shared library.
-  #
-  # @param pathname Module file name
-  #
-  # @endif
-  def unload(self, fname):
-    self._rtcout.RTC_TRACE("Manager.unload()")
-    self._listeners.module_.preUnload(fname)
-    self._module.unload(fname)
-    self._listeners.module_.postUnload(fname)
-    return
-
-
-  ##
-  # @if jp
-  #
-  # @brief ⥸塼Υ
-  #
-  # ⥸塼򤹤٤ƥɤ
-  #
-  # @param self
-  #
-  # @else
-  #
-  # @brief Unload module
-  #
-  # Unload all loaded shared library.
-  #
-  # @endif
-  def unloadAll(self):
-    self._rtcout.RTC_TRACE("Manager.unloadAll()")
-    self._module.unloadAll()
-    return
-
-
-  ##
-  # @if jp
-  # @brief ɺѤߤΥ⥸塼ꥹȤ
-  #
-  # ߥޥ͡˥ɤƤ⥸塼ΥꥹȤ롣
-  #
-  # @param self
-  #
-  # @return ɺѤߥ⥸塼ꥹ
-  #
-  # @else
-  # @brief Get loaded module names
-  # @endif
-  #  std::vector getLoadedModules();
-  def getLoadedModules(self):
-    self._rtcout.RTC_TRACE("Manager.getLoadedModules()")
-    return self._module.getLoadedModules()
-
-
-  ##
-  # @if jp
-  # @brief ɲǽʥ⥸塼ꥹȤ
-  #
-  # ɲǽ⥸塼ΥꥹȤ롣
-  # (ߤModuleManager¦̤)
-  #
-  # @param self
-  #
-  # @return ɲǽ⥸塼롡ꥹ
-  #
-  # @else
-  # @brief Get loadable module names
-  # @endif
-  def getLoadableModules(self):
-    self._rtcout.RTC_TRACE("Manager.getLoadableModules()")
-    return self._module.getLoadableModules()
-
-
-  #============================================================
-  # Component Factory Management
-  #============================================================
-
-  ##
-  # @if jp
-  # @brief RTݡͥѥեȥϿ
-  #
-  # RTݡͥȤΥ󥹥󥹤뤿
-  # FactoryϿ롣
-  #
-  # @param self
-  # @param profile RTݡͥ ץե
-  # @param new_func RTݡͥѴؿ
-  # @param delete_func RTݡͥ˴Ѵؿ
-  #
-  # @return Ͽ(Ͽ:true:false)
-  #
-  # @else
-  # @brief Register RT-Component Factory
-  # @endif
-  def registerFactory(self, profile, new_func, delete_func):
-    self._rtcout.RTC_TRACE("Manager.registerFactory(%s)", profile.getProperty("type_name"))
-    #try:
-    policy_name = self._config.getProperty("manager.components.naming_policy","process_unique")
-      
-      
-    policy = OpenRTM_aist.NumberingPolicyFactory.instance().createObject(policy_name)
-      
-    factory = OpenRTM_aist.FactoryPython(profile, new_func, delete_func, policy)
-    return self._factory.registerObject(factory)
-    #  return True
-    #except:
-    #  self._rtcout.RTC_ERROR(OpenRTM_aist.Logger.print_exception())
-    #  return False
-
-    
-
-
-  ##
-  # @if jp
-  # @brief եȥΥץե
-  #
-  # եȥΥץե롣
-  #
-  # @return եȥΥץե
-  #
-  # @else
-  # @brief Get profiles of factories. 
-  #
-  # Get profiles of factories. 
-  #
-  # @return profiles of factories
-  #
-  # @endif
-  #
-  def getFactoryProfiles(self):
-    factories = self._factory.getObjects()
-
-    if not factories:
-      return []
-      
-    props = []
-    for factory in factories:
-      props.append(factory.profile())
-
-    return props
-
-
-  ##
-  # @if jp
-  # @brief ExecutionContextѥեȥϿ
-  #
-  # ExecutionContextΥ󥹥󥹤뤿FactoryϿ롣
-  #
-  # @param self
-  # @param name оExecutionContext̾
-  # @param new_func ExecutionContextѴؿ
-  # @param delete_func ExecutionContext˴Ѵؿ
-  #
-  # @return Ͽ(Ͽ:true:false)
-  #
-  # @else
-  # @brief Register ExecutionContext Factory
-  # @endif
-  def registerECFactory(self, name, new_func, delete_func):
-    self._rtcout.RTC_TRACE("Manager.registerECFactory(%s)", name)
-    #try:
-    ret = OpenRTM_aist.ExecutionContextFactory.instance().addFactory(name,
-                    new_func,
-                    delete_func)
-    if ret == OpenRTM_aist.Factory.FACTORY_OK:
-      return True
-    #except:
-    #  self._rtcout.RTC_ERROR(OpenRTM_aist.Logger.print_exception())
-    else:
-      return False
-
-
-
-
-  ##
-  # @if jp
-  # @brief եȥꥹȤ
-  #
-  # ϿƤեȥꥹȤ롣
-  #
-  # @param self
-  #
-  # @return Ͽեȥ ꥹ
-  #
-  # @else
-  # @brief Get the list of all RT-Component Factory
-  # @endif
-  def getModulesFactories(self):
-    self._rtcout.RTC_TRACE("Manager.getModulesFactories()")
-
-    self._modlist = []
-    for _obj in self._factory._objects._obj:
-      self._modlist.append(_obj.profile().getProperty("implementation_id"))
-    return self._modlist
-
-
-  #============================================================
-  # Component management
-  #============================================================
-
-  ##
-  # @if jp
-  # @brief RTݡͥȤ
-  #
-  # ꤷRTݡͥȤΥ󥹥󥹤Ͽ줿Factoryͳ
-  # 롣
-  #
-  # 륳ݡͥȤγƼץեϰʲ̤ͥ
-  # ꤵ롣
-  #
-  # -# createComponent() ΰͿ줿ץե
-  # -# rtc.confǻꤵ줿եͿ줿ץե
-  # --# category.instance_name.config_file
-  # --# category.component_type.config_file
-  # -# ɤޤ줿ץե 
-  #
-  # 󥹥硢ʻưʲν¹Ԥ롣
-  #  - եꤷե졼ɤ߹ߡ
-  #  - ExecutionContextΥХɡư
-  #  - ͡ߥ󥰥ӥؤϿ
-  #
-  # @param comp_args оRTݡͥIDӥե졼
-  # եޥåȤ礭ʬ "id"  "configuration" 
-  # ʬ¸ߤ롣
-  #
-  # comp_args:     [id]?[configuration]
-  #                id ɬܡconfigurationϥץ
-  # id:            RTC:[vendor]:[category]:[implementation_id]:[version]
-  #                RTC ϸ꤫ɬ
-  #                vendor, category, version ϥץ
-  #                implementation_id ɬ
-  #                ץάǤ ":" ϾάԲ
-  # configuration: [key0]=[value0]&[key1]=[value1]&[key2]=[value2].....
-  #                RTCPropertiesͤ򤹤٤ƾ񤭤뤳ȤǤ롣
-  #                key=value ηǵҤ"&" Ƕڤ
-  #
-  # 㤨С
-  # RTC:jp.go.aist:example:ConfigSample:1.0?conf.default.str_param0=munya
-  # RTC::example:ConfigSample:?conf.default.int_param0=100
-  #
-  # @return RTݡͥȤΥ󥹥
-  #
-  # @else
-  # @brief Create RT-Components
-  #
-  # Create specified RT-Component's instances via registered Factory.
-  # When its instances have been created successfully, the following
-  # processings are also executed.
-  #  - Read and set configuration information that was set by external file.
-  #  - Bind ExecutionContext and start operation.
-  #  - Register to naming service.
-  #
-  # @param module_name Target RT-Component names for the creation
-  #
-  # @return Created RT-Component's instances
-  #
-  # @endif
-  #
-  def createComponent(self, comp_args):
-    self._rtcout.RTC_TRACE("Manager.createComponent(%s)", comp_args)
-    
-    comp_prop = OpenRTM_aist.Properties()
-    comp_id   = OpenRTM_aist.Properties()
-
-    if not self.procComponentArgs(comp_args, comp_id, comp_prop):
-      return None
-    
-    if comp_prop.getProperty("instance_name"):
-      comp = self.getComponent(comp_prop.getProperty("instance_name"))
-      if comp:
-        return comp
-    
-    self._listeners.rtclifecycle_.preCreate(comp_args)
-
-    if comp_prop.findNode("exported_ports"):
-      exported_ports = OpenRTM_aist.split(comp_prop.getProperty("exported_ports"),
-                                          ",")
-      exported_ports_str = ""
-      for i in range(len(exported_ports)):
-        keyval = OpenRTM_aist.split(exported_ports[i], ".")
-        if len(keyval) > 2:
-          exported_ports_str += (keyval[0] + "." + keyval[-1])
-        else:
-          exported_ports_str += exported_ports[i]
-
-        if i != (len(exported_ports) - 1) :
-          exported_ports_str += ","
-
-      comp_prop.setProperty("exported_ports", exported_ports_str)
-      comp_prop.setProperty("conf.default.exported_ports", exported_ports_str)
-
-    factory = self._factory.find(comp_id)
-    if factory is None:
-      self._rtcout.RTC_ERROR("createComponent: Factory not found: %s",
-                             comp_id.getProperty("implementation_id"))
-
-      if not OpenRTM_aist.toBool(self._config.getProperty("manager.modules.search_auto"), "YES", "NO", True):
-        return None
-      # automatic module loading
-      mp = self._module.getLoadableModules()
-      self._rtcout.RTC_INFO("%d loadable modules found", len(mp))
-
-      found_obj = None
-      predicate = self.ModulePredicate(comp_id)
-      for _obj in mp:
-        if predicate(_obj):
-          found_obj = _obj
-          break
-
-      if not found_obj:
-        self._rtcout.RTC_ERROR("No module for %s in loadable modules list",
-                               comp_id.getProperty("implementation_id"))
-        return None
-      
-      if not found_obj.findNode("module_file_name"):
-        self._rtcout.RTC_ERROR("Hmm...module_file_name key not found.")
-        return None
-
-      # module loading
-      self._rtcout.RTC_INFO("Loading module: %s", found_obj.getProperty("module_file_name"))
-      self.load(found_obj.getProperty("module_file_name"), "")
-      factory = self._factory.find(comp_id)
-      if not factory:
-        self._rtcout.RTC_ERROR("Factory not found for loaded module: %s",
-                               comp_id.getProperty("implementation_id"))
-        return None
-
-
-    # get default configuration of component.
-    prop = factory.profile()
-
-    inherit_prop = ["config.version",
-                    "openrtm.name",
-                    "openrtm.version",
-                    "os.name",
-                    "os.release",
-                    "os.version",
-                    "os.arch",
-                    "os.hostname",
-                    "corba.endpoints",
-                    "corba.endpoints_ipv4",
-                    "corba.endpoints_ipv6",
-                    "corba.id",
-                    "exec_cxt.periodic.type",
-                    "exec_cxt.periodic.rate",
-                    "exec_cxt.event_driven.type",
-                    "exec_cxt.sync_transition",
-                    "exec_cxt.sync_activation",
-                    "exec_cxt.sync_deactivation",
-                    "exec_cxt.sync_reset",
-                    "exec_cxt.transition_timeout",
-                    "exec_cxt.activation_timeout",
-                    "exec_cxt.deactivation_timeout",
-                    "exec_cxt.reset_timeout",
-                    "exec_cxt.cpu_affinity",
-                    "logger.enable",
-                    "logger.log_level",
-                    "naming.enable",
-                    "naming.type",
-                    "naming.formats",
-                    "sdo.service.provider.available_services",
-                    "sdo.service.consumer.available_services",
-                    "sdo.service.provider.enabled_services",
-                    "sdo.service.consumer.enabled_services",
-                    "manager.instance_name"]
-
-    prop_ = prop.getNode("port")
-    prop_.mergeProperties(self._config.getNode("port"))
-
-
-    comp = factory.create(self)
-    
-
-    for i in range(len(inherit_prop)):
-      if self._config.findNode(inherit_prop[i]):
-        prop.setProperty(inherit_prop[i],self._config.getProperty(inherit_prop[i]))
-
-    if comp is None:
-      self._rtcout.RTC_ERROR("createComponent: RTC creation failed: %s",
-                             comp_id.getProperty("implementation_id"))
-      return None
-
-    if self._config.getProperty("corba.endpoints_ipv4") == "":
-      self.setEndpointProperty(comp.getObjRef())
-      
-    self._rtcout.RTC_TRACE("RTC Created: %s", comp_id.getProperty("implementation_id"))
-    self._listeners.rtclifecycle_.postCreate(comp)
-
-    # The property specified by the parameter of createComponent() is merged.
-    # The property("instance_name") specified by the parameter of createComponent()
-    # must be merged here.
-    prop.mergeProperties(comp_prop)
-    
-
-    #------------------------------------------------------------
-    # Load configuration file specified in "rtc.conf"
-    #
-    # rtc.conf:
-    #   [category].[type_name].config_file = file_name
-    #   [category].[instance_name].config_file = file_name
-    self._listeners.rtclifecycle_.preConfigure(prop)
-    self.configureComponent(comp,prop)
-    self._listeners.rtclifecycle_.postConfigure(prop)
-
-    # The property specified by the parameter of createComponent() is set.
-    # The property("exported_ports") specified by the parameter of createComponent()
-    # must be set here.
-    #comp.setProperties(comp_prop)
-
-    # Component initialization
-    self._listeners.rtclifecycle_.preInitialize()
-    if comp.initialize() != RTC.RTC_OK:
-      self._rtcout.RTC_TRACE("RTC initialization failed: %s",
-                             comp_id.getProperty("implementation_id"))
-      self._rtcout.RTC_TRACE("%s was finalized", comp_id.getProperty("implementation_id"))
-      if comp.exit() != RTC.RTC_OK:
-        self._rtcout.RTC_DEBUG("%s finalization was failed.",
-                               comp_id.getProperty("implementation_id"))
-      comp.exit()
-      return None
-      
-    self._rtcout.RTC_TRACE("RTC initialization succeeded: %s",
-                           comp_id.getProperty("implementation_id"))
-    self._listeners.rtclifecycle_.postInitialize()
-    self.registerComponent(comp)
-    
-    
-    return comp
-
-
-
-  ##
-  # @if jp
-  # @brief RTݡͥȤľ Manager Ͽ
-  #
-  # ꤷRTݡͥȤΥ󥹥󥹤եȥͳǤϤʤ
-  # ľܥޥ͡Ͽ롣
-  #
-  # @param self
-  # @param comp ϿоRTݡͥȤΥ󥹥
-  #
-  # @return Ͽ(Ͽ:true:false)
-  #
-  # @else
-  # @brief Register RT-Component directly without Factory
-  # @endif
-  def registerComponent(self, comp):
-    self._rtcout.RTC_TRACE("Manager.registerComponent(%s)", comp.getInstanceName())
-
-    self._compManager.registerObject(comp)
-    names = comp.getNamingNames()
-
-    self._listeners.naming_.preBind(comp, names)
-    for name in names:
-      self._rtcout.RTC_TRACE("Bind name: %s", name)
-      self._namingManager.bindObject(name, comp)
-    self._listeners.naming_.postBind(comp, names)
-
-    self.publishPorts(comp)
-    self.subscribePorts(comp)
-
-    try:
-      poa = self._orb.resolve_initial_references("omniINSPOA")
-      poa._get_the_POAManager().activate()
-      id = comp.getCategory() + "." + comp.getInstanceName()
-      poa.activate_object_with_id(id, comp)
-      
-      rtcobj = poa.id_to_reference(id)
-      rtcobj._narrow(RTC.RTObject)
-      comp.setINSObjRef(rtcobj)
-    except:
-      self._rtcout.RTC_DEBUG(OpenRTM_aist.Logger.print_exception())
-      
-    
-
-    return True
-
-  
-  ##
-  # @if jp
-  # @brief RTݡͥȤϿ
-  #
-  # ꤷRTݡͥȤϿ롣
-  #
-  # @param self
-  # @param comp ϿоRTݡͥȤΥ󥹥
-  #
-  # @return Ͽ(:true:false)
-  #
-  # @else
-  # @brief Register RT-Component directly without Factory
-  # @endif
-  def unregisterComponent(self, comp):
-    self._rtcout.RTC_TRACE("Manager.unregisterComponent(%s)", comp.getInstanceName())
-    self._compManager.unregisterObject(comp.getInstanceName())
-    names = comp.getNamingNames()
-    
-    self._listeners.naming_.preUnbind(comp, names)
-    for name in names:
-      self._rtcout.RTC_TRACE("Unbind name: %s", name)
-      self._namingManager.unbindObject(name)
-    self._listeners.naming_.postUnbind(comp, names)
-
-    try:
-      poa = self._orb.resolve_initial_references("omniINSPOA")
-      poa._get_the_POAManager().activate()
-      id = comp.getCategory() + "/" + comp.getInstanceName()
-      poa.deactivate_object(id)
-    except:
-      self._rtcout.RTC_DEBUG(OpenRTM_aist.Logger.print_exception())
-
-
-
-    return True
-
-
-  ##
-  # @if jp
-  # @brief Context
-  #
-  # @return ConetextΥ󥹥
-  #
-  # @else
-  # @brief Create Context
-  #
-  # @return Created Context's instances
-  #
-  # @endif
-  #
-  # ExecutionContextBase* createContext(const char* ec_args);
-  def createContext(self, ec_args):
-    self._rtcout.RTC_TRACE("Manager.createContext()")
-    self._rtcout.RTC_TRACE("ExecutionContext type: %s",
-                           self._config.getProperty("exec_cxt.periodic.type"))
-    ec_id = [""]
-    ec_prop = OpenRTM_aist.Properties()
-
-    if not self.procContextArgs(ec_args, ec_id, ec_prop):
-      return None
-
-    avail_ec_ = OpenRTM_aist.ExecutionContextFactory.instance().getIdentifiers()
-
-    if not ec_id[0] in avail_ec_:
-      self._rtcout.RTC_ERROR("Factory not found: %s", ec_id[0])
-      return None
-
-    
-    ec = OpenRTM_aist.ExecutionContextFactory.instance().createObject(ec_id[0])
-    ec.init(ec_prop)
-    self._ecs.append(ec)
-    return ec
-    
-
-  ##
-  # @if jp
-  # @brief Manager ϿƤRTݡͥȤ(̤)
-  #
-  # ޥ͡ϿƤRTݡͥȤ롣
-  #
-  # @param self
-  # @param instance_name оRTݡͥȤΥ󥹥̾
-  #
-  # @else
-  # @brief Unregister RT-Component that is registered in the Manager
-  # @endif
-  def deleteComponent(self, instance_name=None, comp=None):
-    if instance_name:
-      self._rtcout.RTC_TRACE("Manager.deleteComponent(%s)", instance_name)
-      _comp = self._compManager.find(instance_name)
-      if _comp is None:
-        self._rtcout.RTC_WARN("RTC %s was not found in manager.", instance_name)
-        return
-      self.deleteComponent(comp=_comp)
-
-    elif comp:
-      self._rtcout.RTC_TRACE("Manager.deleteComponent(RTObject_impl)")
-      # cleanup from manager's table, and naming serivce
-      self.unregisterComponent(comp)
-      
-      comp_id = comp.getProperties()
-      factory = self._factory.find(comp_id)
-
-      if not factory:
-        self._rtcout.RTC_DEBUG("Factory not found: %s",
-                               comp_id.getProperty("implementation_id"))
-        return
-      else:
-        self._rtcout.RTC_DEBUG("Factory found: %s",
-                               comp_id.getProperty("implementation_id"))
-        factory.destroy(comp)
-        
-
-      if OpenRTM_aist.toBool(self._config.getProperty("manager.shutdown_on_nortcs"),
-                             "YES","NO",True) and \
-                             not OpenRTM_aist.toBool(self._config.getProperty("manager.is_master"),
-                                                     "YES","NO",False):
-        comps = self.getComponents()
-        if len(comps) == 0:
-          self.createShutdownThread()
-
-    return
-
-
-  ##
-  # @if jp
-  # @brief Manager ϿƤRTݡͥȤ򸡺
-  #
-  # Manager ϿƤRTݡͥȤꤷ̾ΤǸ
-  # פ륳ݡͥȤ롣
-  #
-  # @param self
-  # @param instance_name оRTݡͥȤ̾
-  #
-  # @return ̾ΤפRTݡͥȤΥ󥹥
-  #
-  # @else
-  # @brief Get RT-Component's pointer
-  # @endif
-  def getComponent(self, instance_name):
-    self._rtcout.RTC_TRACE("Manager.getComponent(%s)", instance_name)
-    return self._compManager.find(instance_name)
-
-
-  ##
-  # @if jp
-  # @brief Manager ϿƤRTݡͥȤ
-  #
-  # Manager ϿƤRTݡͥȤ󥹥󥹤롣
-  #
-  # @param self
-  #
-  # @return RTݡͥȤΥ󥹥󥹥ꥹ
-  #
-  # @else
-  # @brief Get all RT-Component's pointer
-  # @endif
-  def getComponents(self):
-    self._rtcout.RTC_TRACE("Manager.getComponents()")
-    return self._compManager.getObjects()
-
-
-  # void Manager::
-  # addManagerActionListener(RTM::ManagerActionListener* listener,
-  #                          bool autoclean)
-  def addManagerActionListener(self, listener,autoclean=True):
-    self._listeners.manager_.addListener(listener, autoclean)
-    return
-
-
-  # void Manager::
-  # removeManagerActionListener(RTM::ManagerActionListener* listener)
-  def removeManagerActionListener(self, listener):
-    self._listeners.manager_.removeListener(listener)
-    return
-  
-
-  # void Manager::
-  # addModuleActionListener(RTM::ModuleActionListener* listener,
-  #                          bool autoclean)
-  def addModuleActionListener(self, listener, autoclean=True):
-    self._listeners.module_.addListener(listener, autoclean)
-    return
-
-
-  # void Manager::
-  # removeModuleActionListener(RTM::ModuleActionListener* listener)
-  def removeModuleActionListener(self, listener):
-    self._listeners.module_.removeListener(listener)
-    return
-
-
-  # void Manager::
-  # addRtcLifecycleActionListener(RTM::RtcLifecycleActionListener* listener,
-  #                               bool autoclean)
-  def addRtcLifecycleActionListener(self, listener, autoclean=True):
-    self._listeners.rtclifecycle_.addListener(listener, autoclean)
-    return
-
-
-  # void Manager::
-  # removeRtcLifecycleActionListener(RTM::RtcLifecycleActionListener* listener)
-  def removeRtcLifecycleActionListener(self, listener):
-    self._listeners.rtclifecycle_.removeListener(listener)
-    return
-
-  
-  # void Manager::
-  # addNamingActionListener(RTM::NamingActionListener* listener,
-  #                         bool autoclean)
-  def addNamingActionListener(self, listener, autoclean=True):
-    self._listeners.naming_.addListener(listener, autoclean)
-    return
-
-
-  # void Manager::
-  # removeNamingActionListener(RTM::NamingActionListener* listener)
-  def removeNamingActionListener(self, listener):
-    self._listeners.naming_.removeListener(listener)
-    return
-  
-
-  # void Manager::
-  # addLocalServiceActionListener(RTM::LocalServiceActionListener* listener,
-  #                               bool autoclean)
-  def addLocalServiceActionListener(self, listener, autoclean=True):
-    self._listeners.localservice_.addListener(listener, autoclean)
-    return
-
-
-  # void Manager::
-  # removeLocalServiceActionListener(RTM::LocalServiceActionListener* listener)
-  def removeLocalServiceActionListener(self, listener):
-    self._listeners.localservice_.removeListener(listener)
-    return
-
-
-  #============================================================
-  # CORBA Ϣ
-  #============================================================
-
-  ##
-  # @if jp
-  # @brief ORB Υݥ󥿤
-  #
-  # Manager ꤵ줿 ORB Υݥ󥿤롣
-  #
-  # @param self
-  #
-  # @return ORB ֥
-  #
-  # @else
-  # @brief Get the pointer to the ORB
-  # @endif
-  def getORB(self):
-    self._rtcout.RTC_TRACE("Manager.getORB()")
-    return self._orb
-
-
-  ##
-  # @if jp
-  # @brief Manager  RootPOA Υݥ󥿤
-  #
-  # Manager ꤵ줿 RootPOA ؤΥݥ󥿤롣
-  #
-  # @param self
-  #
-  # @return RootPOA֥
-  #
-  # @else
-  # @brief Get the pointer to the RootPOA 
-  # @endif
-  def getPOA(self):
-    self._rtcout.RTC_TRACE("Manager.getPOA()")
-    return self._poa
-
-
-  ##
-  # @if jp
-  # @brief Manager  POAManager 
-  #
-  # Manager ꤵ줿 POAMAnager 롣
-  #
-  # @param self
-  #
-  # @return POAޥ͡
-  #
-  # @else
-  #
-  # @endif
-  def getPOAManager(self):
-    self._rtcout.RTC_TRACE("Manager.getPOAManager()")
-    return self._poaManager
-
-
-
-  #============================================================
-  # Manager initialize and finalization
-  #============================================================
-
-  ##
-  # @if jp
-  # @brief Manager 
-  # 
-  # Manager ¹Ԥ롣
-  #  - Manager ե졼
-  #  - ϥե
-  #  - λѥåɤ
-  #  - ѥåɤ(޻ѻ)
-  #
-  # @param self
-  # @param argv ޥɥ饤
-  # 
-  # @else
-  # @brief Manager internal initialization
-  # @endif
-  def initManager(self, argv):
-    config = OpenRTM_aist.ManagerConfig(argv)
-    self._config = OpenRTM_aist.Properties()
-    config.configure(self._config)
-    self._config.setProperty("logger.file_name",self.formatString(self._config.getProperty("logger.file_name"), 
-                                                                  self._config))
-    self._module = OpenRTM_aist.ModuleManager(self._config)
-    self._terminator = self.Terminator(self)
-    guard = OpenRTM_aist.ScopedLock(self._terminate.mutex)
-    self._terminate.waiting = 0
-    del guard
-
-    if OpenRTM_aist.toBool(self._config.getProperty("timer.enable"), "YES", "NO", True):
-      tm = OpenRTM_aist.TimeValue(0, 100000)
-      tick = self._config.getProperty("timer.tick")
-      if tick != "":
-        tm = tm.set_time(float(tick))
-        if self._timer:
-          self._timer.stop()
-          self._timer.join()
-        self._timer = OpenRTM_aist.Timer(tm)
-        self._timer.start()
-
-    if OpenRTM_aist.toBool(self._config.getProperty("manager.shutdown_auto"),
-                           "YES", "NO", True) and \
-                           not OpenRTM_aist.toBool(self._config.getProperty("manager.is_master"),
-                                                   "YES", "NO", False):
-      tm = OpenRTM_aist.TimeValue(10, 0)
-      if self._config.findNode("manager.auto_shutdown_duration"):
-        duration = float(self._config.getProperty("manager.auto_shutdown_duration"))
-        if duration:
-          tm.set_time(duration)
-
-      if self._timer:
-        self._timer.registerListenerObj(self,
-                                        OpenRTM_aist.Manager.shutdownOnNoRtcs,
-                                        tm)
-    
-    if self._timer:
-      tm = OpenRTM_aist.TimeValue(1, 0)
-      self._timer.registerListenerObj(self,
-                                      OpenRTM_aist.Manager.cleanupComponents,
-                                      tm)
-
-
-    lmpm_ = [s.strip() for s in self._config.getProperty("manager.preload.modules").split(",")]
-    for mpm_ in lmpm_:
-      if len(mpm_) == 0:
-        continue
-      basename_ = mpm_.split(".")[0]+"Init"
-      try:
-        self._module.load(mpm_, basename_)
-      except:
-        self._rtcout.RTC_ERROR(OpenRTM_aist.Logger.print_exception())
-    
-    self._config.setProperty("manager.instance_name",self.formatString(self._config.getProperty("manager.instance_name"), 
-                                                                  self._config))
-
-    return
-
-  ##
-  # @if jp
-  # @brief ManagerХȤνλ(̤)
-  #
-  # ManagerХȤλ
-  # 
-  #
-  # @param self
-  #
-  # @else
-  #
-  # @endif
-  def shutdownManagerServant(self):
-    self._rtcout.RTC_TRACE("Manager.shutdownManagerServant()")
-    if self._mgrservant:
-      self._mgrservant.exit()
-      self._mgrservant = None
-    return
-
-  ##
-  # @if jp
-  # @brief Manager νλ(̤)
-  #
-  # Manager λ
-  # (ߤ̤)
-  #
-  # @param self
-  #
-  # @else
-  #
-  # @endif
-  def shutdownManager(self):
-    self._rtcout.RTC_TRACE("Manager.shutdownManager()")
-
-    return
-
-
-  ##
-  # @if jp
-  # @brief Manager νλ
-  #
-  # configuration  "manager.shutdown_on_nortcs" YES ǡ
-  # ݡͥȤϿƤʤ Manager λ롣
-  #
-  # @else
-  # @brief Shutdown Manager
-  #
-  # This method shutdowns Manager as follows.
-  # - "Manager.shutdown_on_nortcs" of configuration is YES. 
-  # - The component is not registered. 
-  #
-  # @endif
-  #
-  # void shutdownOnNoRtcs();
-  def shutdownOnNoRtcs(self):
-    self._rtcout.RTC_TRACE("Manager::shutdownOnNoRtcs()")
-    if OpenRTM_aist.toBool(self._config.getProperty("manager.shutdown_on_nortcs"),
-                           "YES", "NO", True):
-
-      comps = self.getComponents()
-      
-      if len(comps) == 0:
-        self.createShutdownThread()
-
-    return
-
-
-  #============================================================
-  # Logger initialize and terminator
-  #============================================================
-
-  ##
-  # @if jp
-  # @brief
-  #
-  # 
-  # 
-  # 
-  #
-  # @param self
-  #
-  #
-  # @else
-  # @brief
-  #
-  # 
-  # 
-  # @param self
-  #
-  # 
-  # @endif
-  def initLogstreamFile(self):
-
-    logprop = self._config.getNode("logger")
-    logstream = OpenRTM_aist.LogstreamFactory.instance().createObject("file")
-
-    if logstream is None:
-      return
-    
-
-    if not logstream.init(logprop):
-      logstream = OpenRTM_aist.LogstreamFactory.instance().deleteObject(logstream)
-      return
-    
-    self._rtcout.addLogger(logstream)
-    
-
-  ##
-  # @if jp
-  # @brief
-  #
-  # 
-  # 
-  # 
-  #
-  # @param self
-  #
-  #
-  # @else
-  # @brief
-  #
-  # 
-  # 
-  # @param self
-  #
-  # 
-  # @endif
-  def initLogstreamPlugins(self):
-    lmod_ = [s.strip() for s in self._config.getProperty("logger.plugins").split(",")]
-    for mod_ in lmod_:
-      if len(mod_) == 0: continue
-      basename_ = mod_.split(".")[0]+"Init"
-      try:
-        self._module.load(mod_, basename_)
-      except:
-        self._rtcout.RTC_ERROR(OpenRTM_aist.Logger.print_exception())
-
-  ##
-  # @if jp
-  # @brief
-  #
-  # 
-  # 
-  # 
-  #
-  # @param self
-  #
-  #
-  # @else
-  # @brief
-  #
-  # 
-  # 
-  # @param self
-  #
-  # 
-  # @endif
-  def initLogstreamOthers(self):
-    factory = OpenRTM_aist.LogstreamFactory.instance()
-    pp = self._config.getNode("logger.logstream")
-
-    leaf0 = pp.getLeaf()
-
-    for l in leaf0:
-      lstype = l.getName()
-      logstream = factory.createObject(lstype)
-      if logstream is None:
-        self._rtcout.RTC_WARN("Logstream %s creation failed."%lstype)
-        continue
-      self._rtcout.RTC_INFO("Logstream %s created."%lstype)
-      if not logstream.init(l):
-        self._rtcout.RTC_WARN("Logstream %s init failed."%lstype)
-      
-        factory.deleteObject(logstream)
-        self._rtcout.RTC_WARN("Logstream %s deleted."%lstype)
-        continue
-      
-      self._rtcout.RTC_INFO("Logstream %s added."%lstype)
-      self._rtcout.addLogger(logstream)
-      
-
-  ##
-  # @if jp
-  # @brief System logger ν
-  #
-  # System logger ν¹Ԥ롣
-  # ե졼եꤵ줿˴Ť
-  # ν¹Ԥ롣
-  #
-  # @param self
-  #
-  # @return ¹Է(:true:false)
-  #
-  # @else
-  # @brief System logger initialization
-  # @endif
-  def initLogger(self):
-    #self._rtcout = OpenRTM_aist.LogStream()
-    self._rtcout = self.getLogbuf()
-    if not OpenRTM_aist.toBool(self._config.getProperty("logger.enable"), "YES", "NO", True):
-      return True
-    
-
-    
-    self.initLogstreamFile()
-    self.initLogstreamPlugins()
-    self.initLogstreamOthers()
-    
-    
-    self._rtcout.setLogLevel(self._config.getProperty("logger.log_level"))
-    self._rtcout.setLogLock(OpenRTM_aist.toBool(self._config.getProperty("logger.stream_lock"),
-                                                "enable", "disable", False))
-
-    self._rtcout.RTC_INFO("%s", self._config.getProperty("openrtm.version"))
-    self._rtcout.RTC_INFO("Copyright (C) 2003-2010")
-    self._rtcout.RTC_INFO("  Noriaki Ando")
-    self._rtcout.RTC_INFO("  Intelligent Systems Research Institute, AIST")
-    self._rtcout.RTC_INFO("Manager starting.")
-    self._rtcout.RTC_INFO("Starting local logging.")
-
-    return True
-
-
-  ##
-  # @if jp
-  # @brief System Logger νλ(̤)
-  #
-  # System Loggerνλ¹Ԥ롣
-  # (ߤ̤)
-  #
-  # @param self
-  #
-  # @else
-  # @brief System Logger finalization
-  # @endif
-  def shutdownLogger(self):
-    self._rtcout.RTC_TRACE("Manager.shutdownLogger()")
-    self._rtcout.shutdown()
-    return
-
-
-  #============================================================
-  # ORB initialization and finalization
-  #============================================================
-
-  ##
-  # @if jp
-  # @brief CORBA ORB ν
-  #
-  # 򸵤ORB롣
-  #
-  # @param self
-  #
-  # @return ORB (:true:false)
-  #
-  # @else
-  # @brief CORBA ORB initialization
-  # @endif
-  def initORB(self):
-    self._rtcout.RTC_TRACE("Manager.initORB()")
-    try:
-      tmp_args = self.createORBOptions().split("\"")
-      args = []
-      for i in range(len(tmp_args)):
-        if i%2 == 0:
-          args.extend(tmp_args[i].split(" "))
-        else:
-          args.append(tmp_args[i])
-        
-      
-      args.insert(0,"manager")
-      argv = OpenRTM_aist.toArgv(args)
-      
-      self._orb = CORBA.ORB_init(argv)
-
-      self._poa = self._orb.resolve_initial_references("RootPOA")
-      
-      if CORBA.is_nil(self._poa):
-        self._rtcout.RTC_ERROR("Could not resolve RootPOA")
-        return False
-
-      self._poaManager = self._poa._get_the_POAManager()
-
-    except:
-      self._rtcout.RTC_ERROR("Exception: Caught unknown exception in initORB().")
-      self._rtcout.RTC_ERROR(OpenRTM_aist.Logger.print_exception())
-      return False
-
-    return True
-
-
-  ##
-  # @if jp
-  # @brief ORB Υޥɥ饤󥪥ץ
-  #
-  # ե졼ꤵ줿Ƥ
-  # ORB εưץ롣
-  #
-  # @param self
-  #
-  # @return ORB ưץ
-  #
-  # @else
-  # @brief ORB command option creation
-  # @endif
-  def createORBOptions(self):
-    opt      = self._config.getProperty("corba.args")
-    self._rtcout.RTC_DEBUG("corba.args: %s",opt)
-
-    endpoints = []
-    self.createORBEndpoints(endpoints)
-    opt = [opt]
-    self.createORBEndpointOption(opt,endpoints)
-
-    self._rtcout.RTC_PARANOID("ORB options: %s", opt[0])
-
-    return opt[0]
-
-
-  ##
-  # @if jp
-  # @brief ɥݥȤ
-  #
-  # ե졼󤫤饨ɥݥȤ롣
-  #
-  # @param endpoints ɥݥȥꥹ
-  #
-  # @else
-  # @brief Create Endpoints
-  #
-  # Create Endpoints from the configuration.
-  # 
-  # @param endpoints Endpoints list
-  #
-  # @endif
-  #
-  # void createORBEndpoints(coil::vstring& endpoints);
-  def createORBEndpoints(self, endpoints):
-
-    # corba.endpoint is obsolete
-    # corba.endpoints with comma separated values are acceptable
-    if self._config.findNode("corba.endpoints"):
-      endpoints_ = [s.strip() for s in self._config.getProperty("corba.endpoints").split(",")]
-      for ep in endpoints_:
-        endpoints.append(ep)
-
-      self._rtcout.RTC_DEBUG("corba.endpoints: %s", self._config.getProperty("corba.endpoints"))
-
-    if self._config.findNode("corba.endpoint"):
-      endpoints_ = [s.strip() for s in self._config.getProperty("corba.endpoint").split(",")]
-      for ep in endpoints_:
-        endpoints.append(ep)
-      self._rtcout.RTC_DEBUG("corba.endpoint: %s", self._config.getProperty("corba.endpoint"))
-
-    # If this process has master manager,
-    # master manager's endpoint inserted at the top of endpoints
-    self._rtcout.RTC_DEBUG("manager.is_master: %s",
-                           self._config.getProperty("manager.is_master"))
-
-    if OpenRTM_aist.toBool(self._config.getProperty("manager.is_master"), "YES", "NO", False):
-      mm = self._config.getProperty("corba.master_manager", ":2810")
-      mmm = [s.strip() for s in mm.split(":")]
-      if len(mmm) == 2:
-        endpoints.insert(0, ":" + mmm[1])
-      else:
-        endpoints.insert(0, ":2810")
-
-    endpoints = OpenRTM_aist.unique_sv(endpoints)
-    
-    return
-
-    
-  ##
-  # @if jp
-  # @brief ORB  Endpoint Υޥɥ饤󥪥ץ
-  # @param opt ޥɥ饤󥪥ץ
-  # @param endpoints ɥݥȥꥹ
-  #
-  # @else
-  # @brief Create a command optional line of Endpoint of ORB.
-  # @param opt ORB options
-  # @param endpoints Endpoints list
-  #
-  # @endif
-  # void createORBEndpointOption(std::string& opt, coil::vstring& endpoints);
-  def createORBEndpointOption(self, opt, endpoints):
-    corba = self._config.getProperty("corba.id")
-    self._rtcout.RTC_DEBUG("corba.id: %s", corba)
-
-    for i in range(len(endpoints)):
-      if endpoints[i]:
-        endpoint = endpoints[i]
-      else:
-        continue
-
-      self._rtcout.RTC_DEBUG("Endpoint is : %s", endpoint)
-      if endpoint.find(":") == -1:
-        endpoint += ":"
-
-      if corba == "omniORB":
-        endpoint = OpenRTM_aist.normalize([endpoint])
-        if OpenRTM_aist.normalize([endpoint]) == "all:":
-          opt[0] += " -ORBendPointPublish all(addr)"
-        else:
-          opt[0] += " -ORBendPoint giop:tcp:" + endpoint
-
-      elif corba == "TAO":
-        opt[0] += "-ORBEndPoint iiop://" + endpoint
-      elif corba == "MICO":
-        opt[0] += "-ORBIIOPAddr inet:" + endpoint
-
-      endpoints[i] = endpoint
-
-    return
-
-
-  ##
-  # @if jp
-  # @brief ORB νλ
-  #
-  # ORB νλ¹Ԥ롣
-  # ¹Ԥν¸ߤˤϡνλޤԤġ
-  # ºݤνλǤϡPOA Manager ORB Υåȥ¹
-  # 롣
-  #
-  # @param self
-  #
-  # @else
-  # @brief ORB finalization
-  # @endif
-  def shutdownORB(self):
-    self._rtcout.RTC_TRACE("Manager.shutdownORB()")
-    if not self._orb:
-      return
-
-    try:
-      while self._orb.work_pending():
-        self._rtcout.RTC_PARANOID("Pending work still exists.")
-        if self._orb.work_pending():
-            self._orb.perform_work()
-
-
-      self._rtcout.RTC_DEBUG("No pending works of ORB. Shutting down POA and ORB.")
-    except:
-      self._rtcout.RTC_TRACE(OpenRTM_aist.Logger.print_exception())
-
-    
-    if not CORBA.is_nil(self._poa):
-      try:
-        if not CORBA.is_nil(self._poaManager):
-          self._poaManager.deactivate(False, True)
-        self._rtcout.RTC_DEBUG("POA Manager was deactivated.")
-        self._poa.destroy(False, True)
-        self._poa = PortableServer.POA._nil
-        self._rtcout.RTC_DEBUG("POA was destroyed.")
-      except CORBA.SystemException:
-        self._rtcout.RTC_ERROR("Caught SystemException during root POA destruction")
-        self._rtcout.RTC_ERROR(OpenRTM_aist.Logger.print_exception())
-      except:
-        self._rtcout.RTC_ERROR("Caught unknown exception during destruction")
-        self._rtcout.RTC_ERROR(OpenRTM_aist.Logger.print_exception())
-
-    if self._orb:
-      try:
-        self._orb.shutdown(True)
-        self._orb.destroy()
-        self._rtcout.RTC_DEBUG("ORB was shutdown.")
-        self._orb = CORBA.Object._nil
-      except CORBA.SystemException:
-        self._rtcout.RTC_ERROR("Caught CORBA::SystemException during ORB shutdown.")
-        self._rtcout.RTC_ERROR(OpenRTM_aist.Logger.print_exception())
-      except:
-        self._rtcout.RTC_ERROR("Caught unknown exception during ORB shutdown.")
-        self._rtcout.RTC_ERROR(OpenRTM_aist.Logger.print_exception())
-
-
-  #============================================================
-  # NamingService initialization and finalization
-  #============================================================
-
-  ##
-  # @if jp
-  # @brief NamingManager ν
-  #
-  # NamingManager ν¹Ԥ롣
-  #  NamingManager Ѥʤ褦˥ץѥƥꤵƤ
-  # ˤϲ⤷ʤ
-  # NamingManager Ѥ硢ץѥƥꤵƤ
-  # ǥե NamingServer Ͽ롣
-  # ޤŪ˾򹹿褦ꤵƤˤϡꤵ줿
-  # ǼưԤΥޤưȤȤˡѥ᥽åɤ򥿥ޤ
-  # Ͽ롣
-  #
-  # @param self
-  #
-  # @return (:true:false)
-  #
-  # @else
-  #
-  # @endif
-  def initNaming(self):
-    self._rtcout.RTC_TRACE("Manager.initNaming()")
-    self._namingManager = OpenRTM_aist.NamingManager(self)
-
-    if not OpenRTM_aist.toBool(self._config.getProperty("naming.enable"), "YES", "NO", True):
-      return True
-
-    #meths = OpenRTM_aist.split(self._config.getProperty("naming.type"),",")
-    meths = [s.strip() for s in self._config.getProperty("naming.type").split(",")]
-    
-    
-    for meth in meths:
-      #names = OpenRTM_aist.split(self._config.getProperty(meth+".nameservers"), ",")
-      names = [s.strip() for s in self._config.getProperty(meth+".nameservers").split(",")]
-      for name in names:
-        self._rtcout.RTC_TRACE("Register Naming Server: %s/%s", (meth, name))
-        self._namingManager.registerNameServer(meth,name)
-
-    if OpenRTM_aist.toBool(self._config.getProperty("naming.update.enable"), "YES", "NO", True):
-      tm = OpenRTM_aist.TimeValue(10,0)
-      intr = self._config.getProperty("naming.update.interval")
-      if intr != "":
-        tm = OpenRTM_aist.TimeValue(intr)
-
-      if self._timer:
-        self._timer.registerListenerObj(self._namingManager,OpenRTM_aist.NamingManager.update,tm)
-  
-    return True
-
-
-  ##
-  # @if jp
-  # @brief NamingManager νλ
-  #
-  # NamingManager λ롣
-  # ϿƤǤ򥢥Хɤλ롣
-  #
-  # @param self
-  #
-  # @else
-  #
-  # @endif
-  def shutdownNaming(self):
-    self._rtcout.RTC_TRACE("Manager.shutdownNaming()")
-    comps = self.getComponents()
-    
-    for comp in comps:
-      names = comp.getNamingNames()
-      self._listeners.naming_.preUnbind(comp, names)
-      for name in names:
-        self._namingManager.unbindObject(name)
-      self._listeners.naming_.postUnbind(comp, names)
-
-    self._namingManager.unbindAll()
-    return
-
-
-  ##
-  # @if jp
-  # @brief ExecutionContextManager ν
-  #
-  # Ѥ ExecutionContext ν¹Ԥ ExecutionContext 
-  #  Factory  ExecutionContextManager Ͽ롣
-  #
-  # @param self
-  #
-  # @return ExecutionContextManager ¹Է
-  #         (:true:false)
-  #
-  # @else
-  #
-  # @endif
-  def initExecContext(self):
-    self._rtcout.RTC_TRACE("Manager.initExecContext()")
-    OpenRTM_aist.PeriodicExecutionContextInit(self)
-    OpenRTM_aist.ExtTrigExecutionContextInit(self)
-    OpenRTM_aist.OpenHRPExecutionContextInit(self)
-    OpenRTM_aist.SimulatorExecutionContextInit(self)
-    OpenRTM_aist.MultilayerCompositeECInit(self)
-    
-    self.initCpuAffinity()
-    return True
-
-  def initCpuAffinity(self):
-    self._rtcout.RTC_TRACE("Manager.initCpuAffinity()")
-    
-    if not self._config.findNode("manager.cpu_affinity"):
-      return
-          
-
-    
-    
-    affinity_str = self._config.getProperty("manager.cpu_affinity")
-
-
-    if affinity_str:
-      self._rtcout.RTC_DEBUG("CPU affinity property: %s", affinity_str)
-
-      tmp = affinity_str.split(",")
-
-      
-      cpu_num = []
-      for num in tmp:
-        try:
-          cpu_num.append(int(num))
-          self._rtcout.RTC_DEBUG("CPU affinity mask set to %d", int(num))
-        except:
-          pass
-      
-      
-
-      if len(cpu_num) == 0:
-        return
 
 
-      ret = OpenRTM_aist.setProcessAffinity(cpu_num)
-      
-      if ret == False:
-        self._rtcout.RTC_ERROR("CPU affinity mask setting failed")
-    
-    
-
-
-
-  ##
-  # @if jp
-  # @brief PeriodicECSharedComposite ν
-  #
-  # @return PeriodicECSharedComposite ¹Է
-  #         (:true:false)
-  #
-  # @else
-  # @brief PeriodicECSharedComposite initialization
-  #
-  # @return PeriodicECSharedComposite initialization result
-  #          (Successful:true, Failed:false)
-  #
-  # @endif
-  #
-  def initComposite(self):
-    self._rtcout.RTC_TRACE("Manager.initComposite()")
-    OpenRTM_aist.PeriodicECSharedCompositeInit(self)
-    return True
-
-  
-  ##
-  # @if jp
-  # @brief եȥν
-  #
-  # Хåեåɡѥ֥å㡢ץХ󥷥塼ޤ
-  # եȥ롣
-  #
-  # @return եȥ¹Է
-  #         (:true:false)
-  #
-  # @else
-  # @brief Factories initialization
-  #
-  # Initialize buffer factories, thread factories, publisher factories, 
-  # provider factories, and consumer factories. 
-  #
-  # @return PeriodicECSharedComposite initialization result
-  #          (Successful:true, Failed:false)
-  #
-  # @endif
-  #
-  def initFactories(self):
-    #self._rtcout.RTC_TRACE("Manager.initFactories()")
-    OpenRTM_aist.FactoryInit()
-    return True
-
-  
-  ##
-  # @if jp
-  # @brief Timer ν
-  #
-  # Ѥ Timer ν¹Ԥ롣
-  # (μǤϲ⤷ʤ)
-  #
-  # @param self
-  #
-  # @return Timer ¹Է(:true:false)
-  #
-  # @else
-  #
-  # @endif
-  def initTimer(self):
-    return True
-
-  ##
-  # @if jp
-  # @brief Timer νλ
-  #
-  # Ѥ Timer νλ¹Ԥ롣
-  #
-  # @param self
-  #
-  # @else
-  #
-  # @endif
-  def shutdownTimer(self):
-    self._rtcout.RTC_TRACE("Manager.shutdownTimer()")
-    if self._timer:
-      self._timer.stop()
-      self._timer.join()
-      self._timer = None
-    
-
-  ##
-  # @if jp
-  # @brief corba.endpoint_property ץѥƥμ
-  #
-  # corba.endpoint_property ͤץȤ֤ΡɤΥ
-  # ɥݥȤ IPv4, IPv6 Τ뤫ꤹץѥƥ
-  # corba.endpoint_property  IPv4/IPv6 ̵ͭӡͭ
-  # IPɥ쥹ֹ򥿥ץͤȤ֤
-  #
-  # @return (ipv4, ipv4_list, ipv6, ipv6_list) endpoint_property 
-  # ipv4, ipv6:  IPv4/IPv6 ̵ͭ򼨤True/False
-  # ipv4_list, ipv6_list: ͭˤ륢ɥ쥹ֹ桢ꥹȤξϤ٤ͭ
-  #
-  # @else
-  # @brief ManagerServant initialization
-  #
-  # Getting corba.endpoint_property value and return them as a
-  # tuple. This function obtains corbaendpoint_property that specifies
-  # if IPv4/IPv6 addresses and IP address numbes to be published, and
-  # it returnes them as tuple.
-  #
-  # @return (ipv4, ipv4_list, ipv6, ipv6_list) endpoint_property value
-  # ipv4, ipv6: A True/False flag whether to use IPv4 / IPv6 address
-  # ipv4_list, ipv6_list: List of valid address number, empty means
-  # valid all addresses
-  #
-  # @endif
-  #
-  def endpointPropertySwitch(self):
-    ipv4 = True; ipv4_list = []
-    ipv6 = True; ipv6_list = []
-    
-    ep_prop = self._config.getProperty("corba.endpoint_property", "ipv4")
-    ep_prop = ep_prop.lower()
-
-    import re
-    if ep_prop.count("ipv4"):
-      ipv4 = True
-      m = re.match(r"ipv4\(([0-9, ]*)\)", ep_prop)
-      if m: ipv4_list = map(int, m.group(1).split(","))
-    else:
-      ipv4 = False
-    if ep_prop.count("ipv6"):
-      ipv6 = True
-      m = re.match(r"ipv6\(([0-9, ]*)\)", ep_prop)
-      if m: ipv6_list = map(int, m.group(1).split(","))
-    else:
-      ipv6 = False
-    return (ipv4, ipv4_list, ipv6, ipv6_list)
-
-  ##
-  # @if jp
-  # @brief Endpoint ץѥƥ
-  #
-  # δؿϥɥݥȤץѥƥ corba.endpoints ˻ꤹ롣
-  # Ϳ줿֥ȥե󥹤鸽ߤΥץΥɥ
-  #  (IPɥ쥹, ݡֹ)  corba.endpoints,
-  # corba.endpoints_ipv4, corba.endpoints_ipv6 ˻ꤹ롣
-  #
-  # @param objref ֥ȥե
-  #
-  # @else
-  # @brief Setting endpoint information to property
-  #
-  # This function sets endpoint information to corba.endpoints
-  # property. It extract endpoint information (list of IP address,
-  # port number) from given object reference, and set them to
-  # corba.endpoints, corba.endpoints_ipv4, corba.endpoints_ipv6
-  #
-  # @param objref A object reference
-  #
-  # @endif
-  #
-  def setEndpointProperty(self, objref):
-    import re
-    (ipv4, ipv4_list, ipv6, ipv6_list) = self.endpointPropertySwitch()
-    re_ipv4 = r"((?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?))"
-    re_ipv6 = r"(([0-9a-f]{1,4})(:([0-9a-f]{1,4})){7}((\.|#|p| port )\d{1,4})?)|\[([0-9a-f]{1,4})(:([0-9a-f]{1,4})){7}\]"
-
-    iorstr = self._orb.object_to_string(objref)
-
-    ior = CORBA_IORUtil.toIOR(iorstr)
-
-      
-    
-    endpoints = CORBA_IORUtil.getEndpoints(ior)
-    
-
-    epstr = ""; epstr_ipv4 = ""; epstr_ipv6 = "";
-    ipv4_count = 0; ipv6_count = 0
-    for e in endpoints:
-      if ipv4 and re.match(re_ipv4, e.host):
-        if len(ipv4_list) == 0 or ipv4_list.count(ipv4_count):
-          epstr += e.host + ":" + str(e.port) + ", "
-          epstr_ipv4 += e.host + ":" + str(e.port) + ", "
-        ipv4_count += 1
-      if ipv6 and re.match(re_ipv6, e.host):
-        if len(ipv6_list) == 0 or ipv6_list.count(ipv6_count):
-          epstr += e.host + ":" + str(e.port) + ", "
-          epstr_ipv6 += e.host + ":" + str(e.port) + ", "
-        ipv6_count += 1
-    epstr = epstr[:-2]
-    epstr_ipv4 = epstr_ipv4[:-2]
-    epstr_ipv6 = epstr_ipv6[:-2]
-    self._config.setProperty("corba.endpoints", epstr)
-    self._config.setProperty("corba.endpoints_ipv4", epstr_ipv4)
-    self._config.setProperty("corba.endpoints_ipv6", epstr_ipv6)
-
-  ##
-  # @if jp
-  # @brief ManagerServant ν
-  #
-  # @return Timer ¹Է(:true:false)
-  #
-  # @else
-  # @brief ManagerServant initialization
-  #
-  # @return Timer Initialization result (Successful:true, Failed:false)
-  #
-  # @endif
-  #
-  def initManagerServant(self):
-    self._rtcout.RTC_TRACE("Manager.initManagerServant()")
-    if not OpenRTM_aist.toBool(
-      self._config.getProperty("manager.corba_servant"), "YES","NO",True):
-      return True
-    
-
-    self._mgrservant = OpenRTM_aist.ManagerServant()
-    if self._config.getProperty("corba.endpoints_ipv4") == "":
-      self.setEndpointProperty(self._mgrservant.getObjRef())
-    prop = self._config.getNode("manager")
-    names = OpenRTM_aist.split(prop.getProperty("naming_formats"),",")
-    
-    if OpenRTM_aist.toBool(prop.getProperty("is_master"),
-                           "YES","NO",True):
-      for name in names:
-        mgr_name = self.formatString(name, prop)
-        self._namingManager.bindManagerObject(mgr_name, self._mgrservant)
-
-
-    
-    if OpenRTM_aist.toBool(self._config.getProperty("corba.update_master_manager.enable"),
-                           "YES", "NO", True) and \
-                           not OpenRTM_aist.toBool(self._config.getProperty("manager.is_master"),
-                                                   "YES", "NO", False):
-      tm = OpenRTM_aist.TimeValue(10, 0)
-      if self._config.findNode("corba.update_master_manager.interval"):
-        duration = float(self._config.getProperty("corba.update_master_manager.interval"))
-        if duration:
-          tm.set_time(duration)
-        if self._timer:
-          self._timer.registerListenerObj(self._mgrservant,
-                                        OpenRTM_aist.ManagerServant.updateMasterManager,
-                                        tm)
-
-    otherref = None
-
-
-
-
-    return True
-
-  
-  # bool Manager::initLocalService()
-  def initLocalService(self):
-    self._rtcout.RTC_TRACE("Manager::initLocalService()")
-    admin_ = OpenRTM_aist.LocalServiceAdmin.instance()
-    prop_ = OpenRTM_aist.Properties(prop=self._config.getNode("manager.local_service"))
-    admin_.init(prop_)
-    self._rtcout.RTC_DEBUG("LocalServiceAdmin's properties:")
-    self._rtcout.RTC_DEBUG("%s",prop_)
-
-    svclist_ = admin_.getServiceProfiles()
-    for svc_ in svclist_:
-      self._rtcout.RTC_INFO("Available local service: %s (%s)",
-                            (svc_.name, svc_.uuid))
-    return True
-
-
-  ##
-  # @if jp
-  # @brief NamingManager ϿƤݡͥȤνλ
-  #
-  # NamingManager ϿƤRTݡͥȤ ExecutionContext 
-  # ꥹȤݡͥȤλ롣
-  #
-  # @param self
-  #
-  # @else
-  #
-  # @endif
-  def shutdownComponents(self):
-    self._rtcout.RTC_TRACE("Manager.shutdownComponents()")
-    comps = self._namingManager.getObjects()
-    for comp in comps:
-      try:
-        comp.exit()
-        p = OpenRTM_aist.Properties(key=comp.getInstanceName())
-        p.mergeProperties(comp.getProperties())
-      except:
-        self._rtcout.RTC_TRACE(OpenRTM_aist.Logger.print_exception())
-
-
-    for ec in self._ecs:
-      try:
-        self._poa.deactivate_object(self._poa.servant_to_id(ec))
-      except:
-        self._rtcout.RTC_TRACE(OpenRTM_aist.Logger.print_exception())
-
-
-
-  ##
-  # @if jp
-  # @brief RTݡͥȤϿ
-  #
-  # ꤷRTݡͥȤΥ󥹥󥹤͡ߥ󥰥ӥ
-  # Ͽ롣
-  #
-  # @param self
-  # @param comp ϿоRTݡͥ
-  #
-  # @else
-  #
-  # @endif
-  def cleanupComponent(self, comp):
-    self._rtcout.RTC_TRACE("Manager.cleanupComponent()")
-    self.unregisterComponent(comp)
-
-    return
-
-
-  ##
-  # @if jp
-  # @brief RTݡͥȤκ
-  #
-  # notifyFinalized()ˤäϿ줿RTݡͥȤ롣
-  #
-  # @else
-  # @brief This method deletes RT-Components. 
-  #
-  # This method deletes RT-Components registered by notifyFinalized(). 
-  #
-  # @endif
-  #
-  # void cleanupComponents();
-  def cleanupComponents(self):
-    self._rtcout.RTC_VERBOSE("Manager.cleanupComponents()")
-    guard = OpenRTM_aist.ScopedLock(self._finalized.mutex)
-    self._rtcout.RTC_VERBOSE("%d components are marked as finalized.",
-                             len(self._finalized.comps))
-    for _comp in self._finalized.comps:
-      self.deleteComponent(comp=_comp)
-
-    self._finalized.comps = []
-    del guard
-    return
-
-
-  ##
-  # @if jp
-  # @brief RTݡͥȤκ
-  #
-  # RTݡͥȤϿ롣
-  # Ͽ줿RTݡͥȤ cleanupComponents() Ǻ롣
-  #
-  # @param RTݡͥ
-  #
-  # @else
-  # @brief This method deletes RT-Components. 
-  #
-  # The deleted RT-Component is registered. The registered RT-Components 
-  # are deleted by cleanupComponents(). 
-  #
-  # @param Deleted RT component
-  # @endif
-  #
-  # void notifyFinalized(RTObject_impl* comp);
-  def notifyFinalized(self, comp):
-    self._rtcout.RTC_TRACE("Manager.notifyFinalized()")
-    guard = OpenRTM_aist.ScopedLock(self._finalized.mutex)
-    self._finalized.comps.append(comp)
-    del guard
-    return
-
-
-  ##
-  # @if jp
-  # @brief createComponentΰ
-  # @ param self
-  # @ param comp_arg(str)
-  # @ param comp_id(Properties object)
-  # @ param comp_conf(Properties object)
-  # @ return True or False
-  # @else
-  #
-  # @endif
-  #
-  # bool procComponentArgs(const char* comp_arg,
-  #                        coil::Properties& comp_id,
-  #                        coil::Properties& comp_conf)
-  def procComponentArgs(self, comp_arg, comp_id, comp_conf):
-    id_and_conf = [s.strip() for s in comp_arg.split("?")]
-    
-    if len(id_and_conf) != 1 and len(id_and_conf) != 2:
-      self._rtcout.RTC_ERROR("Invalid arguments. Two or more '?'")
-      return False
-
-    prof = OpenRTM_aist.CompParam.prof_list
-    param_num = len(prof)
-
-    
-    if id_and_conf[0].find(":") == -1:
-      id_and_conf[0] = prof[0] + ":::" + id_and_conf[0] + "::"
-
-    id = [s.strip() for s in id_and_conf[0].split(":")]
-    
-
-    if len(id) != param_num:
-      self._rtcout.RTC_ERROR("Invalid RTC id format.")
-      return False
-
-    #prof = ["RTC", "vendor", "category", "implementation_id", "language", "version"]
-
-    if id[0] != prof[0]:
-      self._rtcout.RTC_ERROR("Invalid id type.")
-      return False
-
-    for i in range(1,param_num):
-      comp_id.setProperty(prof[i], id[i])
-      self._rtcout.RTC_TRACE("RTC basic profile %s: %s", (prof[i], id[i]))
-    
-    
-    if len(id_and_conf) == 2:
-      conf = [s.strip() for s in id_and_conf[1].split("&")]
-      for i in range(len(conf)):
-        keyval = [s.strip() for s in conf[i].split("=")]
-        if len(keyval) > 1:
-          comp_conf.setProperty(keyval[0],keyval[1])
-          self._rtcout.RTC_TRACE("RTC property %s: %s", (keyval[0], keyval[1]))
-
-    return True
-
-
-  # bool procContextArgs(const char* ec_args,
-  #                      std::string& ec_id,
-  #                      coil::Properties& ec_conf);
-  def procContextArgs(self, ec_args, ec_id, ec_conf):
-    id_and_conf = [s.strip() for s in ec_args.split("?")]
-
-    if len(id_and_conf) != 1 and len(id_and_conf) != 2:
-      self._rtcout.RTC_ERROR("Invalid arguments. Two or more '?'")
-      return False
-
-    if (id_and_conf[0] == "") or id_and_conf[0] is None:
-      self._rtcout.RTC_ERROR("Empty ExecutionContext's name")
-      return False
-
-    ec_id[0] = id_and_conf[0]
-
-    if len(id_and_conf) == 2:
-      conf = [s.strip() for s in id_and_conf[1].split("&")]
-      for i in range(len(conf)):
-        k = [s.strip() for s in conf[i].split("=")]
-        ec_conf.setProperty(k[0],k[1])
-        self._rtcout.RTC_TRACE("EC property %s: %s",(k[0],k[1]))
-        
-    return True
-
-
-  ##
-  # @if jp
-  # @brief RTݡͥȤΥե졼
-  #
-  # RTݡͥȤηӥ󥹥˵ܤ줿ץѥƥե
-  # ɤ߹ߡݡͥȤꤹ롣
-  # ޤƥݡͥȤ NamingService Ͽ̾Τꤹ롣
-  #
-  # @param self
-  # @param comp ե졼оRTݡͥ
-  #
-  # @else
-  #
-  # @endif
-  # void configureComponent(RTObject_impl* comp, const coil::Properties& prop);
-  def configureComponent(self, comp, prop):
-    category  = comp.getCategory()
-    type_name = comp.getTypeName()
-    inst_name = comp.getInstanceName()
-
-    type_conf = category + "." + type_name + ".config_file"
-    name_conf = category + "." + inst_name + ".config_file"
-    
-    type_prop = OpenRTM_aist.Properties()
-
-    name_prop = OpenRTM_aist.Properties()
-    config_fname = []
-
-    if self._config.getProperty(name_conf) != "":
-      try:
-        conff = open(self._config.getProperty(name_conf))
-        name_prop.load(conff)
-        self._rtcout.RTC_INFO("Component instance conf file: %s loaded.",
-                              self._config.getProperty(name_conf))
-        self._rtcout.RTC_DEBUG(name_prop)
-        config_fname.append(self._config.getProperty(name_conf))
-      except:
-        print("Not found. : %s" % self._config.getProperty(name_conf))
-        self._rtcout.RTC_ERROR(OpenRTM_aist.Logger.print_exception())
-      else:
-        name_prop.load(conff)
-
-    if self._config.findNode(category + "." + inst_name):
-      temp_ = OpenRTM_aist.Properties(prop=self._config.getNode(category+"."+inst_name))
-      keys_ = temp_.propertyNames()
-      if not (len(keys_) == 1 and keys_[-1] == "config_file"):
-        name_prop.mergeProperties(self._config.getNode(category + "." + inst_name))
-        self._rtcout.RTC_INFO("Component name conf exists in rtc.conf. Merged.")
-        self._rtcout.RTC_DEBUG(name_prop)
-        if self._config.findNode("config_file"):
-          config_fname.append(self._config.getProperty("config_file"))
-
-    if self._config.getProperty(type_conf) != "":
-      try:
-        conff = open(self._config.getProperty(type_conf))
-        type_prop.load(conff)
-        self._rtcout.RTC_INFO("Component type conf file: %s loaded.",
-                              self._config.getProperty(type_conf))
-        self._rtcout.RTC_DEBUG(type_prop)
-        config_fname.append(self._config.getProperty(type_conf))
-      except:
-        print("Not found. : %s" % self._config.getProperty(type_conf))
-        self._rtcout.RTC_ERROR(OpenRTM_aist.Logger.print_exception())
-      else:
-        type_prop.load(conff)
-
-    if self._config.findNode(category + "." + type_name):
-      temp_ = OpenRTM_aist.Properties(prop=self._config.getNode(category+"."+type_name))
-      keys_ = temp_.propertyNames()
-      if not (len(keys_) == 1 and keys_[-1] == "config_file"):
-        type_prop.mergeProperties(self._config.getNode(category + "." + type_name))
-        self._rtcout.RTC_INFO("Component type conf exists in rtc.conf. Merged.")
-        self._rtcout.RTC_DEBUG(type_prop)
-        if self._config.findNode("config_file"):
-          config_fname.append(self._config.getProperty("config_file"))
-    
-    comp.setProperties(prop)
-    type_prop.mergeProperties(name_prop)
-    type_prop.setProperty("config_file",OpenRTM_aist.flatten(OpenRTM_aist.unique_sv(config_fname)))
-    comp.setProperties(type_prop)
-
-    comp_prop = OpenRTM_aist.Properties(prop=comp.getProperties())
-
-    naming_formats = self._config.getProperty("naming.formats")
-    if comp_prop.findNode("naming.formats"):
-      naming_formats = comp_prop.getProperty("naming.formats")
-    naming_formats = OpenRTM_aist.flatten(OpenRTM_aist.unique_sv(OpenRTM_aist.split(naming_formats, ",")))
-
-    naming_names = self.formatString(naming_formats, comp.getProperties())
-    comp.getProperties().setProperty("naming.formats",naming_formats)
-    comp.getProperties().setProperty("naming.names",naming_names)
-    return
-
-
-  ##
-  # @if jp
-  # @brief ץѥƥΥޡ
-  #
-  # ꤵ줿եꤵƤץѥƥɤ
-  # ¸Ѥߥץѥƥȥޡ롣
-  #
-  # @param self
-  # @param prop ޡоݥץѥƥ
-  # @param file_name ץѥƥ󤬵ҤƤե̾
-  #
-  # @return ޡ¹Է(ޡ:trueޡ:false)
-  #
-  # @else
-  #
-  # @endif
-  def mergeProperty(self, prop, file_name):
-    if file_name == "":
-      self._rtcout.RTC_ERROR("Invalid configuration file name.")
-      return False
-  
-    if file_name[0] != '\0':
-      
-      try:
-        conff = open(file_name)
-      except:
-        print("Not found. : %s" % file_name)
-        self._rtcout.RTC_ERROR(OpenRTM_aist.Logger.print_exception())
-      else:
-        prop.load(conff)
-        conff.close()
-        return True
-  
-    return False
-
-
-  ##
-  # @if jp
-  # @brief NamingServer ϿݤϿȤΩƤ
-  #
-  # ꤵ줿񼰤ȥץѥƥ NameServer Ͽݤξ
-  # ȤΩƤ롣
-  # ƽ񼰻ʸΰ̣ϰʲΤȤ
-  # - % : ƥȤζڤ
-  # - n : 󥹥̾
-  # - t : ̾
-  # - m : ̾
-  # - v : С
-  # - V : ٥
-  # - c : ƥ
-  # - h : ۥ̾
-  # - M : ޥ̾͡
-  # - p : ץID
-  #
-  # @param self
-  # @param naming_format NamingService Ͽ񼰻
-  # @param prop Ѥץѥƥ
-  #
-  # @return Ѵ
-  #
-  # @else
-  #
-  # @endif
-  def formatString(self, naming_format, prop):
-    name_ = naming_format
-    str_  = ""
-    count = 0
-    len_  = len(name_)
-    it = iter(name_)
-
-    try:
-      while 1:
-        if sys.version_info[0] == 2:
-          n = it.next()
-        else:
-          n = it.__next__()
-        if n == '%':
-          count+=1
-          if not (count % 2):
-            str_ += n
-        elif n == '$':
-          count = 0
-          if sys.version_info[0] == 2:
-            n = it.next()
-          else:
-            n = it.__next__()
-          if n == '{' or n == '(':
-            n = it.next()
-            env = ""
-            while True:
-              if n == '}' or n == ')':
-                break
-              env += n
-              if sys.version_info[0] == 2:
-                n = it.next()
-              else:
-                n = it.__next__()
-            envval = os.getenv(env)
-            if envval:
-              str_ += envval
-          else:
-            str_ += n
-        else:
-          if  count > 0 and (count % 2):
-            count = 0
-            if   n == "n": str_ += prop.getProperty("instance_name")
-            elif n == "t": str_ += prop.getProperty("type_name")
-            elif n == "m": str_ += prop.getProperty("type_name")
-            elif n == "v": str_ += prop.getProperty("version")
-            elif n == "V": str_ += prop.getProperty("vendor")
-            elif n == "c": str_ += prop.getProperty("category")
-            elif n == "h": str_ += self._config.getProperty("os.hostname")
-            elif n == "M": str_ += self._config.getProperty("manager.name")
-            elif n == "p": str_ += str(self._config.getProperty("manager.pid"))
-            else: str_ += n
-          else:
-            count = 0
-            str_ += n
-    except:
-      # Caught StopIteration exception.
-      return str_
-
-    #return str_
-
-
-  ##
-  # @if jp
-  # @brief Хåեμ
-  #
-  # ޥ͡ꤷХåե롣
-  #
-  # @param self
-  #
-  # @return ޥ͡ꤷХåե
-  #
-  # @else
-  #
-  # @endif
-  def getLogbuf(self,name="manager"):
-    if not OpenRTM_aist.toBool(self._config.getProperty("logger.enable"), "YES", "NO", True):
-      return OpenRTM_aist.LogStream().getLogger(name)
-
-    if self._rtcout is None:
-        self._rtcout = OpenRTM_aist.LogStream()
-        self._rtcout.setLogLevel(self._config.getProperty("logger.log_level"))
-        return self._rtcout.getLogger(name)
-    else:
-        return self._rtcout.getLogger(name)
-
-
-  ##
-  # @if jp
-  # @brief ޥ͡㥳ե졼μ
-  #
-  # ޥ͡ꤷե졼롣
-  #
-  # @param self
-  #
-  # @return ޥ͡Υե졼
-  #
-  # @else
-  #
-  # @endif
-  def getConfig(self):
-    return self._config
-
-
-  ##
-  # @if jp
-  # @brief ݡͥȥե(.py)
-  #
-  # ޥ͡ꤷե졼롣
-  #
-  # @param self
-  #
-  # @return ޥ͡Υե졼
-  #
-  # @else
-  #
-  # @endif
-  def __try_direct_load(self, file_name):
-    try:
-      #pathChanged=False
-      splitted_name = os.path.split(file_name)
-      save_path = sys.path[:]
-      sys.path.append(splitted_name[0])
-      import_name = splitted_name[-1].split(".py")[0]
-      mo = __import__(import_name)
-      sys.path = save_path
-      _spec = getattr(mo,import_name.lower()+"_spec",None)
-      _class = getattr(mo,import_name,None)
-      if _spec and _class:
-        prof = OpenRTM_aist.Properties(defaults_str=_spec)
-        self.registerFactory(prof,
-                             _class,
-                             OpenRTM_aist.Delete)
-    except:
-      self._rtcout.RTC_ERROR("Module load error: %s", file_name)
-      self._rtcout.RTC_ERROR(OpenRTM_aist.Logger.print_exception())
-      
-
-
-
-
-
-  ##
-  # @if jp
-  #
-  # @brief ꤷRTݡͥȤݻݡȤNamingService˥Хɤ
-  # ݡȤpublish_topicȤץѥƥǥȥԥå̾ꤷȥԥå̾ΥƥȤβϿ
-  #
-  # 
-  # @param self
-  # @param comp RTݡͥ
-  #
-  # @else
-  #
-  # @brief 
-  # @param self
-  # @param comp 
-  #
-  # @endif
-  # void publishPorts(RTObject_impl* comp)
-  def publishPorts(self, comp):
-    ports = comp.get_ports()
-    for p in ports:
-      prof = p.get_port_profile()
-      prop = OpenRTM_aist.Properties()
-      OpenRTM_aist.NVUtil.copyToProperties(prop, prof.properties)
-      
-      if (prop.hasKey("publish_topic") is None or not str(prop.getProperty("publish_topic"))) and (prop.hasKey("subscribe_topic") is None or not str(prop.getProperty("subscribe_topic"))) and (prop.hasKey("rendezvous_point") is None or not str(prop.getProperty("rendezvous_point"))):
-        continue
-
-
-      if prop.getProperty("port.port_type") == "DataOutPort":
-        name  = "dataports.port_cxt/"
-        name += str(prop.getProperty("publish_topic")) + ".topic_cxt/"
-        name += prof.name
-        name += ".outport"
-      elif prop.getProperty("port.port_type") == "DataInPort":
-        name  = "dataports.port_cxt/"
-        name += str(prop.getProperty("publish_topic")) + ".topic_cxt/"
-        name += prof.name
-        name += ".inport"
-      elif prop.getProperty("port.port_type") == "CorbaPort":
-        name  = "svcports.port_cxt/"
-        name += str(prop.getProperty("publish_topic")) + ".topic_cxt/"
-        name += prof.name
-        name += ".svc"
-
-      else:
-        
-        self._rtcout.RTC_WARN("Unknown port type: %s" % str(prop.getProperty("port.port_type")))
-        continue
-
-      
-      port = self._poa.reference_to_servant(p)
-      
-      self._namingManager.bindPortObject(name, port)
-
-  ##
-  # @if jp
-  #
-  # @brief ꤷRTݡͥȤݻݡȤƱȥԥå̾ʲ³ǽʥݡȤ³
-  #
-  # 
-  # @param self
-  # @param comp RTݡͥ
-  #
-  # @else
-  #
-  # @brief 
-  # @param self
-  # @param comp 
-  #
-  # @endif
-  # void subscribePorts(RTObject_impl* comp)
-  def subscribePorts(self, comp):
-    ports = comp.get_ports()
-    
-    for p in ports:
-      
-      prof = p.get_port_profile()
-      prop = OpenRTM_aist.Properties()
-      OpenRTM_aist.NVUtil.copyToProperties(prop, prof.properties)
-      
-      if (prop.hasKey("publish_topic") is None or not str(prop.getProperty("publish_topic"))) and (prop.hasKey("subscribe_topic") is None or not str(prop.getProperty("subscribe_topic"))) and (prop.hasKey("rendezvous_point") is None or not str(prop.getProperty("rendezvous_point"))):
-        continue
-      
-            
-      
-      
-      if prop.getProperty("port.port_type") == "DataOutPort":
-        name  = "dataports.port_cxt/"
-        name += str(prop.getProperty("publish_topic")) + ".topic_cxt"
-        
-        nsports = self.getPortsOnNameServers(name, "inport")
-        
-        self.connectDataPorts(p, nsports)
-      
-      elif prop.getProperty("port.port_type") == "DataInPort":
-        name  = "dataports.port_cxt/"
-        name += str(prop.getProperty("publish_topic")) + ".topic_cxt"
-        nsports = self.getPortsOnNameServers(name, "outport")
-        self.connectDataPorts(p, nsports)
-      
-      elif prop.getProperty("port.port_type") == "CorbaPort":
-        name  = "svcports.port_cxt/"
-        name += str(prop.getProperty("publish_topic")) + ".topic_cxt"
-        nsports = self.getPortsOnNameServers(name, "svc")
-        self.connectServicePorts(p, nsports)
-
-  ##
-  # @if jp
-  #
-  # @brief Ϳ줿ѥʲλꤵ줿kindΥݡȤ
-  # 
-  # @param self
-  # @param nsname ѥ
-  # @param kind kind
-  # @return ݡȤΥ֥ȥե󥹤Υꥹ
-  #
-  # @else
-  #
-  # @brief 
-  # @param self
-  # @param nsname 
-  # @param kind
-  # @return 
-  #
-  # @endif
-  # PortServiceList_var getPortsOnNameServers(std::string nsname,std::string kind)
-  def getPortsOnNameServers(self, nsname, kind):
-    ports = []
-    ns = self._namingManager.getNameServices()
-    for n in ns:
-      noc = n.ns
-      if noc is None:
-        continue
-      cns = noc._cosnaming
-      if cns is None:
-        continue
-      
-      bl = cns.listByKind(nsname,kind)
-      
-      for b in bl:
-        if b.binding_type != CosNaming.nobject:
-          continue
-        tmp = b.binding_name[0].id + "." + b.binding_name[0].kind
-                
-        nspath = "/" + nsname + "/" + tmp
-        nspath.replace("\\","")
-        
-        obj = cns.resolveStr(nspath)
-        portsvc = obj
-        
-        if CORBA.is_nil(portsvc):
-          continue
-        
-        try:
-          portsvc.get_port_profile()
-          
-        except:
-          continue
-        ports.append(portsvc)
-
-    return ports
-
-  ##
-  # @if jp
-  # @brief ꤷǡݡȤꤷꥹΥǡݡƤ³
-  # @param self
-  # @param port оݤΥǡݡ
-  # @param target_ports ³оݤΥǡݡȤΥꥹ
-  # @else
-  #
-  # @brief 
-  # @param self
-  # @param port
-  # @param target_ports
-  # @endif
-  # void connectDataPorts(PortService_ptr port,PortServiceList_var& target_ports)
-  def connectDataPorts(self, port, target_ports):
-    for p in target_ports:
-      if port._is_equivalent(p):
-        continue
-      con_name = ""
-      p0 = port.get_port_profile()
-      p1 = p.get_port_profile()
-      con_name += p0.name
-      con_name += ":"
-      con_name += p1.name
-      prop = OpenRTM_aist.Properties()
-      if RTC.RTC_OK != OpenRTM_aist.CORBA_RTCUtil.connect(con_name,prop,port,p):
-        self._rtcout.RTC_ERROR("Connection error in topic connection.")
-
-
-  ##
-  # @if jp
-  # @brief ꤷӥݡȤꤷꥹΥӥݡƤ³
-  # @param self
-  # @param port оݤΥӥݡ
-  # @param target_ports ³оݤΥӥݡȤΥꥹ
-  # @else
-  #
-  # @brief 
-  # @param self
-  # @param port
-  # @param target_ports
-  # @endif
-  # void connectServicePorts(PortService_ptr port,PortServiceList_var& target_ports)
-  def connectServicePorts(self, port, target_ports):
-    for p in target_ports:
-      if port._is_equivalent(p):
-        continue
-      con_name = ""
-      p0 = port.get_port_profile()
-      p1 = p.get_port_profile()
-      con_name += p0.name
-      con_name += ":"
-      con_name += p1.name
-      prop = OpenRTM_aist.Properties()
-      if RTC.RTC_OK != OpenRTM_aist.CORBA_RTCUtil.connect(con_name,prop,port,p):
-        self._rtcout.RTC_ERROR("Connection error in topic connection.")
-
-
-  ##
-  # @if jp
-  # @brief ưrtc.confǻꤷݡȤ³
-  # :
-  # manager.components.preconnect: RTC0.port0?port=RTC0.port1&interface_type=corba_cdr&dataflow_type=pull&~,~
-  # @param self
-  # @else
-  #
-  # @brief 
-  # @param self
-  # @endif
-  # void initPreConnection()
-  def initPreConnection(self):
-    self._rtcout.RTC_TRACE("Connection pre-creation: %s" % str(self._config.getProperty("manager.components.preconnect")))
-    connectors = str(self._config.getProperty("manager.components.preconnect")).split(",")
-    
-    for c in connectors:
-      c = c.strip()
-      if len(c) == 0:
-        continue
-      port0_str = c.split("?")[0]
-      param = OpenRTM_aist.urlparam2map(c)
-      
-
-
-      ports = []
-      configs = {}
-      
-      for k,p in param.items():
-        if k == "port":
-          ports.append(p)
-          continue
-        tmp = k.replace("port","")
-        v = [0]
-        if OpenRTM_aist.stringTo(v, tmp) and k.find("port") != -1:
-          ports.append(p)
-          continue
-        configs[k] = p
-
-      #if len(ports) == 0:
-      #  self._rtcout.RTC_ERROR("Invalid format for pre-connection.")
-      #  self._rtcout.RTC_ERROR("Format must be Comp0.port0?port=Comp1.port1")
-      #  continue
-    
-      if not ("dataflow_type" in configs.keys()):
-        configs["dataflow_type"] = "push"
-      if not ("interface_type" in configs.keys()):
-        configs["interface_type"] = "corba_cdr"
-      
-      
-      
-      tmp = port0_str.split(".")
-      tmp.pop()
-      comp0_name = OpenRTM_aist.flatten(tmp,".")
-      
-
-      port0_name = port0_str
-      
-      
-      if comp0_name.find("://") == -1:
-        comp0 = self.getComponent(comp0_name)
-        if comp0 is None:
-          self._rtcout.RTC_ERROR("%s not found." % comp0_name)
-          continue
-        comp0_ref = comp0.getObjRef()
-      else:
-        rtcs = self._namingManager.string_to_component(comp0_name)
-        
-        if len(rtcs) == 0:
-          self._rtcout.RTC_ERROR("%s not found." % comp0_name)
-          continue
-        comp0_ref = rtcs[0]
-        port0_name = port0_str.split("/")[-1]
-      
-      
-      port0_var = OpenRTM_aist.CORBA_RTCUtil.get_port_by_name(comp0_ref, port0_name)
-      
-      
-      if CORBA.is_nil(port0_var):
-        self._rtcout.RTC_DEBUG("port %s found: " % port0_str)
-        continue
-
-      if len(ports) == 0:
-        prop = OpenRTM_aist.Properties()
-        
-        for k,v in configs.items():
-          k = k.strip()
-          v = v.strip()
-          prop.setProperty("dataport."+k,v)
-
-        if RTC.RTC_OK != OpenRTM_aist.CORBA_RTCUtil.connect(c, prop, port0_var, RTC.PortService._nil):
-          self._rtcout.RTC_ERROR("Connection error: %s" % c)
-
-      for port_str in ports:
-      
-        tmp = port_str.split(".")
-        tmp.pop()
-        comp_name = OpenRTM_aist.flatten(tmp,".")
-        port_name = port_str
-      
-      
-
-
-        if comp_name.find("://") == -1:
-          comp = self.getComponent(comp_name)
-          if comp is None:
-            self._rtcout.RTC_ERROR("%s not found." % comp_name)
-            continue
-          comp_ref = comp.getObjRef()
-        else:
-          rtcs = self._namingManager.string_to_component(comp_name)
-          
-          if len(rtcs) == 0:
-            self._rtcout.RTC_ERROR("%s not found." % comp_name)
-            continue
-          comp_ref = rtcs[0]
-          port_name = port_str.split("/")[-1]
-  
-
-        port_var = OpenRTM_aist.CORBA_RTCUtil.get_port_by_name(comp_ref, port_name)
-      
-        if CORBA.is_nil(port_var):
-          self._rtcout.RTC_DEBUG("port %s found: " % port_str)
-          continue
-      
-        prop = OpenRTM_aist.Properties()
-        
-        for k,v in configs.items():
-          k = k.strip()
-          v = v.strip()
-          prop.setProperty("dataport."+k,v)
-      
-        if RTC.RTC_OK != OpenRTM_aist.CORBA_RTCUtil.connect(c, prop, port0_var, port_var):
-          self._rtcout.RTC_ERROR("Connection error: %s" % c)
-      
-
-
-
-  ##
-  # @if jp
-  # @brief ưrtc.confǻꤷRTC򥢥ƥ١󤹤
-  # :
-  # manager.components.preactivation: RTC1,RTC2~
-  # @param self
-  # @else
-  #
-  # @brief 
-  # @param self
-  # @endif
-  # void initPreActivation()
-  def initPreActivation(self):
-    
-    self._rtcout.RTC_TRACE("Components pre-activation: %s" % str(self._config.getProperty("manager.components.preactivation")))
-    comps = str(self._config.getProperty("manager.components.preactivation")).split(",")
-    for c in comps:
-      c = c.strip()
-      if c:
-        comp_ref = None
-        if c.find("://") == -1:
-          comp = self.getComponent(c)
-          if comp is None:
-            self._rtcout.RTC_ERROR("%s not found." % c)
-            continue
-          comp_ref = comp.getObjRef()
-        else:
-          rtcs = self._namingManager.string_to_component(c)
-          if len(rtcs) == 0:
-            self._rtcout.RTC_ERROR("%s not found." % c)
-            continue
-          comp_ref = rtcs[0]
-        ret = OpenRTM_aist.CORBA_RTCUtil.activate(comp_ref)
-        if ret != RTC.RTC_OK:
-          self._rtcout.RTC_ERROR("%s activation filed." % c)
-        else:
-          self._rtcout.RTC_INFO("%s activated." % c)
-
-
-  ##
-  # @if jp
-  # @brief ưrtc.confǻꤷRTC
-  # :
-  # manager.components.precreate RTC1,RTC2~
-  # @param self
-  # @else
-  #
-  # @brief 
-  # @param self
-  # @endif
-  # void initPreCreation()
-  def initPreCreation(self):
-    comps = [s.strip() for s in self._config.getProperty("manager.components.precreate").split(",")]
-    for i in range(len(comps)):
-      if comps[i] is None or comps[i] == "":
-        continue
-
-      self.createComponent(comps[i])
-
-
-  ##
-  # @if jp
-  # @brief 
-  # @else
-  #
-  # @brief 
-  # @param self
-  # @endif
-  # void invokeInitProc()
-  def invokeInitProc(self):
-    if self._initProc:
-      self._initProc(self)
-    
-  ##
-  # @if jp
-  # @brief ManagerServant
-  # 
-  # 
-  # @param self
-  # @return ManagerServant
-  # @else
-  #
-  # @brief 
-  # @param self
-  # @return
-  # @endif
-  # ManagerServant* getManagerServant()
-  def getManagerServant(self):
-    self._rtcout.RTC_TRACE("Manager.getManagerServant()")
-    return self._mgrservant
-
-
-  ##
-  # @if jp
-  # @brief NamingManager
-  # 
-  # 
-  # @param self
-  # @return NamingManager
-  # @else
-  #
-  # @brief 
-  # @param self
-  # @return
-  # @endif
-  # NamingManager* getNaming()
-  def getNaming(self):
-    self._rtcout.RTC_TRACE("Manager.getNaming()")
-    return self._namingManager
-
-  ##
-  # @if jp
-  # @brief ޥ͡㽪λå
-  # 
-  # 
-  # @param self
-  # @param sleep_time Ե
-  # @return task
-  # @else
-  #
-  # @brief 
-  # @param self
-  # @param sleep_time 
-  # @return task
-  # @endif
-  def createShutdownThread(self, sleep_time=0):
-    self._rtcout.RTC_TRACE("Manager.createShutdownThread()")
-    self._shutdown_thread = terminate_Task(self, sleep_time)
-    self._shutdown_thread.activate()
-    return self._shutdown_thread
-
-  #============================================================
-  # ݡͥȥޥ͡
-  #============================================================
-  ##
-  # @if jp
-  # @class InstanceName
-  # @brief ObjectManager ѥե󥯥
-  #
-  # @else
-  #
-  # @endif
-  class InstanceName:
+class Manager:
     """
     """
 
     ##
     # @if jp
-    # @brief 󥹥ȥ饯
+    # @brief コピーコンストラクタ
     #
-    # 󥹥ȥ饯
+    # コピーコンストラクタ
     #
     # @param self
-    # @param name оݥݡͥ̾(ǥե:None)
-    # @param factory оݥեȥ̾(ǥե:None)
+    # @param _manager コピー元マネージャオブジェクト(デフォルト値:None)
     #
     # @else
+    # @brief Protected Copy Constructor
     #
     # @endif
-    def __init__(self, name=None, factory=None, prop=None):
-      if prop:
-        self._name = prop.getProperty("instance_name")
-      elif factory:
-        self._name = factory.getInstanceName()
-      elif name:
-        self._name = name
-      else:
-        self._name = ""
+    def __init__(self, _manager=None):
+        self._initProc = None
+        self._compManager = OpenRTM_aist.ObjectManager(self.InstanceName)
+        self._factory = OpenRTM_aist.ObjectManager(self.FactoryPredicate)
+        self._ecfactory = OpenRTM_aist.ObjectManager(self.ECFactoryPredicate)
+        self._ecs = []
+        self._scheduler = OpenRTM_aist.PeriodicTimer()
+        self._invoker = OpenRTM_aist.DelayedTimer()
+        self._needsTimer = False
+        self._orb = None
+        self._poa = None
+        self._poaManager = None
+        self._finalized = self.Finalized()
+        self._listeners = OpenRTM_aist.ManagerActionListeners()
+        signal.signal(signal.SIGINT, handler)
+        self._rtcout = None
+        self._mgrservant = None
+        self._isRunning = False
+        self._threadMain = None
+        self._threadOrb = None
+        self._eclist = []
 
-    def __call__(self, comp):
-      if not self._name:
-        return False
-      return self._name == comp.getInstanceName()
-
-
-
-  #============================================================
-  # ݡͥȥեȥ
-  #============================================================
-  ##
-  # @if jp
-  # @class FactoryPredicate
-  # @brief ݡͥȥեȥ긡ѥե󥯥
-  #
-  # @else
-  #
-  # @endif
-  class FactoryPredicate:
-
-    def __init__(self, name=None, prop=None, factory=None):
-      if name:
-        self._vendor   = ""
-        self._category = ""
-        self._impleid  = name
-        self._version  = ""
-      elif prop:
-        self._vendor   = prop.getProperty("vendor")
-        self._category = prop.getProperty("category")
-        self._impleid  = prop.getProperty("implementation_id")
-        self._version  = prop.getProperty("version")
-      elif factory:
-        self._vendor   = factory.profile().getProperty("vendor")
-        self._category = factory.profile().getProperty("category")
-        self._impleid  = factory.profile().getProperty("implementation_id")
-        self._version  = factory.profile().getProperty("version")
-
-
-    def __call__(self, factory):
-      if self._impleid == "":
-        return False
+        return
 
-      _prop = OpenRTM_aist.Properties(prop=factory.profile())
+    ##
+    # @if jp
+    # @brief マネージャの初期化
+    #
+    # マネージャを初期化する static 関数。
+    # マネージャをコマンドライン引数を与えて初期化する。
+    # マネージャを使用する場合は、必ずこの初期化メンバ関数 init() を
+    # 呼ばなければならない。
+    # マネージャのインスタンスを取得する方法として、init(), instance() の
+    # 2つの static 関数が用意されているが、初期化はinit()でしか行われないため、
+    # Manager の生存期間の一番最初にはinit()を呼ぶ必要がある。
+    #
+    # ※マネージャの初期化処理
+    # - initManager: 引数処理、configファイルの読み込み、サブシステム初期化
+    # - initLogger: Logger初期化
+    # - initORB: ORB 初期化
+    # - initNaming: NamingService 初期化
+    # - initExecutionContext: ExecutionContext factory 初期化
+    # - initTimer: Timer 初期化
+    #
+    # @param argv コマンドライン引数
+    #
+    # @return Manager の唯一のインスタンスの参照
+    #
+    # @else
+    # @brief Initializa manager
+    #
+    # This is the static function to tintialize the Manager.
+    # The Manager is initialized by given arguments.
+    # At the starting the manager, this static function "must" be called from
+    # application program. The manager has two static functions to get
+    # the instance, "init()" and "instance()". Since initializing
+    # process is only performed by the "init()" function, the "init()" has
+    # to be called at the beginning of the lifecycle of the Manager.
+    # function.
+    #
+    # @param argv The array of the command line arguments.
+    #
+    # @endif
 
-      if self._impleid != _prop.getProperty("implementation_id"):
-        return False
+    def init(*arg):
+        global manager
+        global mutex
+        if len(arg) == 1:
+            argv = arg[0]
+        elif len(arg) == 2 and \
+                isinstance(arg[0], int) and \
+                isinstance(arg[1], list):
+            # for 0.4.x
+            argv = arg[1]
+        else:
+            print("Invalid arguments for init()")
+            print("init(argc,argv) or init(argv)")
+            return None
 
-      if self._vendor != "" and self._vendor != _prop.getProperty("vendor"):
-        return False
+        if manager is None:
+            guard = OpenRTM_aist.ScopedLock(mutex)
 
-      if self._category != "" and self._category != _prop.getProperty("category"):
-        return False
+            manager = Manager()
+            manager.initManager(argv)
+            manager.initFactories()
+            manager.initLogger()
+            manager.initORB()
+            manager.initNaming()
+            manager.initExecContext()
+            manager.initComposite()
+            manager.initTimer()
+            manager.initManagerServant()
 
-      if self._version != "" and self._version != _prop.getProperty("version"):
-        return False
+        return manager
 
-      return True
+    init = staticmethod(init)
 
+    ##
+    # @if jp
+    # @brief マネージャのインスタンスの取得
+    #
+    # マネージャのインスタンスを取得する static 関数。
+    # この関数を呼ぶ前に、必ずこの初期化関数 init() が呼ばれている必要がある。
+    #
+    # @return Manager の唯一のインスタンスの参照
+    #
+    # @else
+    #
+    # @brief Get instance of the manager
+    #
+    # This is the static function to get the instance of the Manager.
+    # Before calling this function, ensure that the initialization function
+    # "init()" is called.
+    #
+    # @return The only instance reference of the manager
+    #
+    # @endif
 
+    def instance():
+        global manager
+        global mutex
 
-  #============================================================
-  # ExecutionContextեȥ
-  #============================================================
-  ##
-  # @if jp
-  # @class ECFactoryPredicate
-  # @brief ExecutionContextեȥ긡ѥե󥯥
-  #
-  # @else
-  #
-  # @endif
-  class ECFactoryPredicate:
+        if manager is None:
+            guard = OpenRTM_aist.ScopedLock(mutex)
+            manager = Manager()
+            manager.initManager(None)
+            manager.initFactories()
+            manager.initLogger()
+            manager.initORB()
+            manager.initNaming()
+            manager.initExecContext()
+            manager.initComposite()
+            manager.initTimer()
+            manager.initManagerServant()
 
+        return manager
 
+    instance = staticmethod(instance)
 
-    def __init__(self, name=None, factory=None):
-      if name:
-        self._name = name
-      elif factory:
-        self._name = factory.name()
+    ##
+    # @if jp
+    # @brief マネージャ終了処理
+    #
+    # マネージャの終了処理を実行する。
+    #
+    # @param self
+    #
+    # @else
+    #
+    # @endif
 
-    def __call__(self, factory):
-      return self._name == factory.name()
+    def terminate(self):
+        self._isRunning = False
 
+    ##
+    # @if jp
+    # @brief マネージャ・シャットダウン
+    #
+    # マネージャの終了処理を実行する。
+    # ORB、タイマースレッドの終了後、同期を取って終了する。
+    #
+    # @param self
+    #
+    # @else
+    #
+    # @endif
 
-  #============================================================
-  # Module Fanctor
-  #============================================================
-  ##
-  # @if jp
-  # @class ModulePredicate
-  # @brief Moduleѥե󥯥
-  #
-  # @else
-  #
-  # @endif
-  class ModulePredicate:
+    def shutdown(self):
+        self._rtcout.RTC_TRACE("Manager.shutdown()")
+        self.terminate()
+        self.join()
 
-      # ModulePredicate(coil::Properties& prop)
-      def __init__(self, prop):
-        self._prop = prop
-        return
+    ##
+    # @if jp
+    #
+    # @brief 初期化プロシージャのセット
+    #
+    # このオペレーションはユーザが行うモジュール等の初期化プロシージャ
+    # を設定する。ここで設定されたプロシージャは、マネージャが初期化され、
+    # アクティブ化された後、適切なタイミングで実行される。
+    #
+    # @param self
+    # @param proc 初期化プロシージャの関数ポインタ
+    #
+    # @else
+    #
+    # @brief Run the Manager
+    #
+    # This operation sets the initial procedure call to process module
+    # initialization, other user defined initialization and so on.
+    # The given procedure will be called at the proper timing after the
+    # manager initialization, activation and run.
+    #
+    # @param proc A function pointer to the initial procedure call
+    #
+    # @endif
 
-      # bool operator()(coil::Properties& prop)
-      def __call__(self, prop):
+    def setModuleInitProc(self, proc):
+        self._initProc = proc
+        return
 
-        if self._prop.getProperty("implementation_id") != prop.getProperty("implementation_id"):
-          return False
+    ##
+    # @if jp
+    #
+    # @brief Managerのアクティブ化
+    #
+    # このオペレーションは以下の処理を行う
+    # - CORBA POAManager のアクティブ化
+    # - マネージャCORBAオブジェクトのアクティブ化
+    # - Manager オブジェクトへの初期化プロシージャの実行
+    #
+    # このオペレーションは、マネージャの初期化後、runManager()
+    # の前に呼ぶ必要がある。
+    #
+    # @param self
+    #
+    # @return 処理結果(アクティブ化成功:true、失敗:false)
+    #
+    # @else
+    #
+    # @brief Activate Manager
+    #
+    # This operation do the following,
+    # - Activate CORBA POAManager
+    # - Activate Manager CORBA object
+    # - Execute the initial procedure call of the Manager
+    #
+    # This operationo should be invoked after Manager:init(),
+    # and before tunManager().
+    #
+    # @endif
 
-        if self._prop.getProperty("vendor") and \
-              self._prop.getProperty("vendor") != prop.getProperty("vendor"):
-          return False
-        
-        if self._prop.getProperty("category") and \
-              self._prop.getProperty("category") != prop.getProperty("category"):
-          return False
+    def activateManager(self):
+        self._rtcout.RTC_TRACE("Manager.activateManager()")
 
-        if self._prop.getProperty("version") and \
-              self._prop.getProperty("version") != prop.getProperty("version"):
-          return False
+        try:
+            self.getPOAManager().activate()
+            self._rtcout.RTC_TRACE("POA Manager activated.")
+        except BaseException:
+            self._rtcout.RTC_ERROR("Exception: POA Manager activation failed.")
+            self._rtcout.RTC_ERROR(OpenRTM_aist.Logger.print_exception())
+            return False
+
+        lsvc_ = [s.strip() for s in self._config.getProperty(
+            "manager.local_service.modules").split(",")]
+        for svc_ in lsvc_:
+            if not svc_:
+                continue
+            basename_ = svc_.split(".")[0] + "Init"
+            try:
+                self._module.load(svc_, basename_)
+            except BaseException:
+                self._rtcout.RTC_ERROR(OpenRTM_aist.Logger.print_exception())
+
+        self.initLocalService()
+
+        mods = [s.strip() for s in self._config.getProperty(
+            "manager.modules.preload").split(",")]
+
+        for m in mods:
+            if m is None or m == "":
+                continue
+            m = m.strip()
+
+            basename = os.path.basename(m).split(".")[0]
+            basename += "Init"
+
+            try:
+                self._module.load(m, basename)
+            except BaseException:
+                self._rtcout.RTC_ERROR(OpenRTM_aist.Logger.print_exception())
+                self.__try_direct_load(basename)
+
+        sdofactory_ = OpenRTM_aist.SdoServiceConsumerFactory.instance()
+        self._config.setProperty("sdo.service.consumer.available_services",
+                                 OpenRTM_aist.flatten(sdofactory_.getIdentifiers()))
+
+        self.invokeInitProc()
+        self.initPreCreation()
+
+        self.initPreConnection()
+        self.initPreActivation()
 
         return True
 
+    ##
+    # @if jp
+    #
+    # @brief Managerの実行
+    #
+    # このオペレーションはマネージャのメインループを実行する。
+    # このメインループ内では、CORBA ORBのイベントループ等が
+    # 処理される。デフォルトでは、このオペレーションはブロックし、
+    # Manager::destroy() が呼ばれるまで処理を戻さない。
+    # 引数 no_block が true に設定されている場合は、内部でイベントループ
+    # を処理するスレッドを起動し、ブロックせずに処理を戻す。
+    #
+    # @param self
+    # @param no_block false: ブロッキングモード, true: ノンブロッキングモード
+    #
+    # @else
+    #
+    # @brief Run the Manager
+    #
+    # This operation processes the main event loop of the Manager.
+    # In this main loop, CORBA's ORB event loop or other processes
+    # are performed. As the default behavior, this operation is going to
+    # blocking mode and never returns until manager::destroy() is called.
+    # When the given argument "no_block" is set to "true", this operation
+    # creates a thread to process the event loop internally, and it doesn't
+    # block and returns.
+    #
+    # @param no_block false: Blocking mode, true: non-blocking mode.
+    #
+    # @endif
+
+    def runManager(self, no_block=False):
+        self._rtcout.RTC_TRACE("Manager::runManager()")
+        self._isRunning = True
+        
+        if no_block:
+            self._threadMain = threading.Thread(target=self.main)
+            self._threadMain.start()
+        else:
+            self.main()
 
-  #------------------------------------------------------------
-  # ORB runner
-  #------------------------------------------------------------
-  ##
-  # @if jp
-  # @class OrbRunner
-  # @brief OrbRunner 饹
-  #
-  # ORB ¹ѥإѡ饹
-  #
-  # @since 0.4.0
-  #
-  # @else
-  # @class OrbRunner
-  # @brief OrbRunner class
-  # @endif
-  class OrbRunner:
-    """
-    """
+        return
 
     ##
     # @if jp
-    # @brief 󥹥ȥ饯
     #
-    # 󥹥ȥ饯
+    # @brief メインスレッドのメイン関数
     #
     # @param self
-    # @param orb ORB
     #
     # @else
-    # @brief Constructor
+    #
+    # @brief The main function of the Manager main thread.
+    #
+    # @param self
     #
     # @endif
-    def __init__(self, orb):
-      self._orb = orb
-      self._th = threading.Thread(target=self.run)
-      self._th.start()
+    def main(self):
+        self._rtcout.RTC_TRACE("Manager::main()")
+
+        def orbrun():
+            try:
+                self._orb.run()
+            except BaseException:
+                print(OpenRTM_aist.Logger.print_exception())
+                self.terminate()
+            return
+
+        self._threadOrb = threading.Thread(target=orbrun)
+        self._threadOrb.start()
+
+        period = OpenRTM_aist.TimeValue(0, 100000)
+        if self._config.findNode("timer.tick"):
+            tick = float(self._config.getProperty(
+                    "timer.tick"))
+            if tick:
+                period.set_time(tick)
+
+        delay = OpenRTM_aist.TimeValue(0, 500000)
+        if self._config.findNode("manager.termination_waittime"):
+            tick = float(self._config.getProperty(
+                "manager.termination_waittime"))
+            if tick:
+                delay.set_time(tick)
+
+        now = OpenRTM_aist.Time().getTime()
+        while self._isRunning:
+            prev = now
+            now = OpenRTM_aist.Time().getTime()
+            self._scheduler.tick(now - prev)
+            self._invoker.tick(now - prev)
+            time.sleep(period.toDouble())
+
+        time.sleep(delay.toDouble())
+        self.shutdownManager()
 
+    ##
+    # @if jp
+    #
+    # @brief マネージャ終了処理の待ち合わせ
+    #
+    # @param self
+    #
+    # @else
+    #
+    # @brief Wait for Manager's termination
+    #
+    # @param self
+    #
+    # @endif
+    def join(self):
+        global manager
+        if self._threadMain:
+            self._threadMain.join()
+        manager = None
+        
 
-    def __del__(self):
-      pass
-      #self._th.join()
-      #self._th = None
-      #return
+    ##
+    # @if jp
+    # @brief [CORBA interface] モジュールのロード
+    #
+    # 指定したコンポーネントのモジュールをロードするとともに、
+    # 指定した初期化関数を実行する。
+    #
+    # @param self
+    # @param fname   モジュールファイル名
+    # @param initfunc 初期化関数名
+    # @return エラーコード
+    #         RTC::RTC_OK 正常終了
+    #         RTC::RTC_ERROR ロード失敗・不明なエラー
+    #         RTC::PRECONDITION_NOT_MET 設定により許可されない操作
+    #         RTC::BAD_PARAMETER 不正なパラメータ
+    #
+    # @else
+    #
+    # @brief [CORBA interface] Load module
+    #
+    # Load module (shared library, DLL etc..) by file name,
+    # and invoke initialize function.
+    #
+    # @param fname    The module file name
+    # @param initfunc The initialize function name
+    # @return Return code
+    #         RTC::RTC_OK Normal return
+    #         RTC::RTC_ERROR Load failed, or unknown error
+    #         RTC::PRECONDITION_NOT_MET Not allowed operation by conf
+    #         RTC::BAD_PARAMETER Invalid parameter
+    #
+    # @endif
 
+    def load(self, fname, initfunc):
+        self._rtcout.RTC_TRACE("Manager.load(fname = %s, initfunc = %s)",
+                               (fname, initfunc))
+        fname = fname.replace("/", os.sep)
+        fname = fname.replace("\\", os.sep)
+        fname, initfunc = self._listeners.module_.preLoad(fname, initfunc)
+        try:
+            fname_ = fname.split(os.sep)
+
+            if len(fname_) > 1:
+                fname_ = fname_[-1]
+            else:
+                fname_ = fname_[0]
+
+            if not initfunc:
+                mod = [s.strip() for s in fname_.split(".")]
+                initfunc = mod[0] + "Init"
+            path = self._module.load(fname, initfunc)
+            self._rtcout.RTC_DEBUG("module path: %s", path)
+            path, initfunc = self._listeners.module_.postLoad(path, initfunc)
+        except OpenRTM_aist.ModuleManager.NotAllowedOperation as e:
+            self._rtcout.RTC_ERROR("Operation not allowed: %s", (e.reason))
+            return RTC.PRECONDITION_NOT_MET
+        except OpenRTM_aist.ModuleManager.NotFound:
+            self._rtcout.RTC_ERROR("Not found: %s", (fname))
+            return RTC.RTC_ERROR
+        except OpenRTM_aist.ModuleManager.FileNotFound:
+            self._rtcout.RTC_ERROR("Not found: %s", (fname))
+            return RTC.RTC_ERROR
+        except OpenRTM_aist.ModuleManager.InvalidArguments as e:
+            self._rtcout.RTC_ERROR("Invalid argument: %s", (e.reason))
+            return RTC.BAD_PARAMETER
+        # except OpenRTM_aist.ModuleManager.Error as e:
+        #  self._rtcout.RTC_ERROR("Error: %s",(e.reason))
+        #  return RTC.RTC_ERROR
+        except BaseException:
+            self._rtcout.RTC_ERROR("Unknown error.")
+            return RTC.RTC_ERROR
+            # self.__try_direct_load(fname)
+
+        return RTC.RTC_OK
 
     ##
     # @if jp
-    # @brief ORB ¹Խ
     #
-    # ORB ¹
+    # @brief モジュールのアンロード
+    #
+    # モジュールをアンロードする
     #
     # @param self
+    # @param fname モジュールのファイル名
     #
     # @else
     #
+    # @brief Unload module
+    #
+    # Unload shared library.
+    #
+    # @param pathname Module file name
+    #
     # @endif
-    def run(self):
-      try:
-        self._orb.run()
-        #Manager.instance().shutdown()
-      except:
-        print(OpenRTM_aist.Logger.print_exception())
-      return
 
+    def unload(self, fname):
+        self._rtcout.RTC_TRACE("Manager.unload()")
+        fname = self._listeners.module_.preUnload(fname)
+        self._module.unload(fname)
+        fname = self._listeners.module_.postUnload(fname)
+        return
 
     ##
     # @if jp
-    # @brief ORB wait
     #
-    # ORB wait
+    # @brief 全モジュールのアンロード
+    #
+    # モジュールをすべてアンロードする
     #
     # @param self
     #
     # @else
     #
+    # @brief Unload module
+    #
+    # Unload all loaded shared library.
+    #
     # @endif
-    def wait(self):
-      return
+
+    def unloadAll(self):
+        self._rtcout.RTC_TRACE("Manager.unloadAll()")
+        self._module.unloadAll()
+        return
 
     ##
     # @if jp
-    # @brief ORB λ(̤)
+    # @brief ロード済みのモジュールリストを取得する
     #
-    # ORB λ
+    # 現在マネージャにロードされているモジュールのリストを取得する。
     #
     # @param self
-    # @param flags λե饰
     #
-    # @return λ
+    # @return ロード済みモジュールリスト
     #
     # @else
+    # @brief Get loaded module names
+    # @endif
+    #  std::vector getLoadedModules();
+
+    def getLoadedModules(self):
+        self._rtcout.RTC_TRACE("Manager.getLoadedModules()")
+        return self._module.getLoadedModules()
+
+    ##
+    # @if jp
+    # @brief ロード可能なモジュールリストを取得する
+    #
+    # ロード可能モジュールのリストを取得する。
+    # (現在はModuleManager側で未実装)
+    #
+    # @param self
+    #
+    # @return ロード可能モジュール リスト
     #
+    # @else
+    # @brief Get loadable module names
     # @endif
-    def close(self, flags):
-      return 0
 
+    def getLoadableModules(self):
+        self._rtcout.RTC_TRACE("Manager.getLoadableModules()")
+        return self._module.getLoadableModules()
 
-  #------------------------------------------------------------
-  # Manager Terminator
-  #------------------------------------------------------------
-  ##
-  # @if jp
-  # @class Terminator
-  # @brief Terminator 饹
-  #
-  # ORB λѥإѡ饹
-  #
-  # @since 0.4.0
-  #
-  # @else
-  #
-  # @endif
-  class Terminator:
-    """
-    """
+    # ============================================================
+    # Component Factory Management
+    # ============================================================
 
     ##
     # @if jp
-    # @brief 󥹥ȥ饯
+    # @brief RTコンポーネント用ファクトリを登録する
     #
-    # 󥹥ȥ饯
+    # RTコンポーネントのインスタンスを生成するための
+    # Factoryを登録する。
     #
     # @param self
-    # @param manager ޥ͡㡦֥
+    # @param profile RTコンポーネント プロファイル
+    # @param new_func RTコンポーネント生成用関数
+    # @param delete_func RTコンポーネント破棄用関数
+    #
+    # @return 登録処理結果(登録成功:true、失敗:false)
+    #
+    # @else
+    # @brief Register RT-Component Factory
+    # @endif
+
+    def registerFactory(self, profile, new_func, delete_func):
+        self._rtcout.RTC_TRACE(
+            "Manager.registerFactory(%s)",
+            profile.getProperty("type_name"))
+        # try:
+        policy_name = self._config.getProperty(
+            "manager.components.naming_policy", "process_unique")
+
+        policy = OpenRTM_aist.NumberingPolicyFactory.instance().createObject(policy_name)
+
+        factory = OpenRTM_aist.FactoryPython(
+            profile, new_func, delete_func, policy)
+        return self._factory.registerObject(factory)
+        #  return True
+        # except:
+        #  self._rtcout.RTC_ERROR(OpenRTM_aist.Logger.print_exception())
+        #  return False
+
+    ##
+    # @if jp
+    # @brief ファクトリのプロファイルを取得
+    #
+    # ファクトリのプロファイルを取得する。
+    #
+    # @return ファクトリのプロファイル
     #
     # @else
-    # @brief Constructor
+    # @brief Get profiles of factories.
+    #
+    # Get profiles of factories.
+    #
+    # @return profiles of factories
     #
     # @endif
-    def __init__(self, manager):
-      self._manager = manager
+    #
 
+    def getFactoryProfiles(self):
+        factories = self._factory.getObjects()
+
+        if not factories:
+            return []
+
+        props = []
+        for factory in factories:
+            props.append(factory.profile())
+
+        return props
 
     ##
     # @if jp
-    # @brief λ
+    # @brief ExecutionContext用ファクトリを登録する
     #
-    # ORBޥ͡㽪λ򳫻Ϥ롣
+    # ExecutionContextのインスタンスを生成するためのFactoryを登録する。
     #
     # @param self
+    # @param name 生成対象ExecutionContext名称
+    # @param new_func ExecutionContext生成用関数
+    # @param delete_func ExecutionContext破棄用関数
+    #
+    # @return 登録処理結果(登録成功:true、失敗:false)
     #
     # @else
+    # @brief Register ExecutionContext Factory
+    # @endif
+
+    def registerECFactory(self, name, new_func, delete_func):
+        self._rtcout.RTC_TRACE("Manager.registerECFactory(%s)", name)
+        # try:
+        ret = OpenRTM_aist.ExecutionContextFactory.instance().addFactory(name,
+                                                                         new_func)
+        if ret == OpenRTM_aist.Factory.FACTORY_OK:
+            return True
+        # except:
+        #  self._rtcout.RTC_ERROR(OpenRTM_aist.Logger.print_exception())
+        else:
+            return False
+
+    ##
+    # @if jp
+    # @brief ファクトリ全リストを取得する
+    #
+    # 登録されているファクトリの全リストを取得する。
+    #
+    # @param self
+    #
+    # @return 登録ファクトリ リスト
     #
+    # @else
+    # @brief Get the list of all RT-Component Factory
     # @endif
-    def terminate(self):
-      self._manager.shutdown()
-
-
-
-  ##
-  # @if jp
-  # @class Term
-  # @brief Term 饹
-  #
-  # λѥإѡ饹
-  #
-  # @since 0.4.0
-  #
-  # @else
-  #
-  # @endif
-  class Term:
-    def __init__(self):
-      self.waiting = 0
-      self.mutex   = threading.RLock()
-
-
-  class Finalized:
-    def __init__(self):
-      self.mutex = threading.RLock()
-      self.comps = []
+
+    def getModulesFactories(self):
+        self._rtcout.RTC_TRACE("Manager.getModulesFactories()")
+
+        self._modlist = []
+        for _obj in self._factory._objects._obj:
+            self._modlist.append(
+                _obj.profile().getProperty("implementation_id"))
+        return self._modlist
+
+    # ============================================================
+    # Component management
+    # ============================================================
+
+    ##
+    # @if jp
+    # @brief RTコンポーネントを生成する
+    #
+    # 指定したRTコンポーネントのインスタンスを登録されたFactory経由
+    # で生成する。
+    #
+    # 生成されるコンポーネントの各種プロファイルは以下の優先順位で
+    # 設定される。
+    #
+    # -# createComponent() の引数で与えられたプロファイル
+    # -# rtc.confで指定された外部ファイルで与えられたプロファイル
+    # --# category.instance_name.config_file
+    # --# category.component_type.config_file
+    # -# コードに埋め込まれたプロファイル
+    #
+    # インスタンス生成が成功した場合、併せて以下の処理を実行する。
+    #  - 外部ファイルで設定したコンフィギュレーション情報の読み込み,設定
+    #  - ExecutionContextのバインド,動作開始
+    #  - ネーミングサービスへの登録
+    #
+    # @param comp_args 生成対象RTコンポーネントIDおよびコンフィギュレー
+    # ション引数。フォーマットは大きく分けて "id" と "configuration"
+    # 部分が存在する。
+    #
+    # comp_args:     [id]?[configuration]
+    #                id は必須、configurationはオプション
+    # id:            RTC:[vendor]:[category]:[implementation_id]:[version]
+    #                RTC は固定かつ必須
+    #                vendor, category, version はオプション
+    #                implementation_id は必須
+    #                オプションを省略する場合でも ":" は省略不可
+    # configuration: [key0]=[value0]&[key1]=[value1]&[key2]=[value2].....
+    #                RTCが持つPropertiesの値をすべて上書きすることができる。
+    #                key=value の形式で記述し、"&" で区切る
+    #
+    # 例えば、
+    # RTC:jp.go.aist:example:ConfigSample:1.0?conf.default.str_param0=munya
+    # RTC::example:ConfigSample:?conf.default.int_param0=100
+    #
+    # @return 生成したRTコンポーネントのインスタンス
+    #
+    # @else
+    # @brief Create RT-Components
+    #
+    # Create specified RT-Component's instances via registered Factory.
+    # When its instances have been created successfully, the following
+    # processings are also executed.
+    #  - Read and set configuration information that was set by external file.
+    #  - Bind ExecutionContext and start operation.
+    #  - Register to naming service.
+    #
+    # @param module_name Target RT-Component names for the creation
+    #
+    # @return Created RT-Component's instances
+    #
+    # @endif
+    #
+
+    def createComponent(self, comp_args):
+        self._rtcout.RTC_TRACE("Manager.createComponent(%s)", comp_args)
+
+        comp_prop = OpenRTM_aist.Properties()
+        comp_id = OpenRTM_aist.Properties()
+
+        comp_args = self._listeners.rtclifecycle_.preCreate(comp_args)
+
+        if not self.procComponentArgs(comp_args, comp_id, comp_prop):
+            return None
+
+        if comp_prop.getProperty("instance_name"):
+            comp = self.getComponent(comp_prop.getProperty("instance_name"))
+            if comp:
+                return comp
+
+        if comp_prop.findNode("exported_ports"):
+            exported_ports = OpenRTM_aist.split(comp_prop.getProperty("exported_ports"),
+                                                ",")
+            exported_ports_str = ""
+            for i,exported_port in enumerate(exported_ports):
+                keyval = OpenRTM_aist.split(exported_port, ".")
+                if len(keyval) > 2:
+                    exported_ports_str += (keyval[0] + "." + keyval[-1])
+                else:
+                    exported_ports_str += exported_port
+
+                if i != (len(exported_ports) - 1):
+                    exported_ports_str += ","
+
+            comp_prop.setProperty("exported_ports", exported_ports_str)
+            comp_prop.setProperty(
+                "conf.default.exported_ports",
+                exported_ports_str)
+
+        factory = self._factory.find(comp_id)
+        if factory is None:
+            self._rtcout.RTC_ERROR("createComponent: Factory not found: %s",
+                                   comp_id.getProperty("implementation_id"))
+
+            if not OpenRTM_aist.toBool(self._config.getProperty(
+                    "manager.modules.search_auto"), "YES", "NO", True):
+                return None
+            # automatic module loading
+            mp = self._module.getLoadableModules()
+            self._rtcout.RTC_INFO("%d loadable modules found", len(mp))
+
+            found_obj = None
+            predicate = self.ModulePredicate(comp_id)
+            for _obj in mp:
+                if predicate(_obj):
+                    found_obj = _obj
+                    break
+
+            if not found_obj:
+                self._rtcout.RTC_ERROR("No module for %s in loadable modules list",
+                                       comp_id.getProperty("implementation_id"))
+                return None
+
+            if not found_obj.findNode("module_file_name"):
+                self._rtcout.RTC_ERROR("Hmm...module_file_name key not found.")
+                return None
+
+            # module loading
+            self._rtcout.RTC_INFO(
+                "Loading module: %s",
+                found_obj.getProperty("module_file_name"))
+            self.load(found_obj.getProperty("module_file_name"), "")
+            factory = self._factory.find(comp_id)
+            if not factory:
+                self._rtcout.RTC_ERROR("Factory not found for loaded module: %s",
+                                       comp_id.getProperty("implementation_id"))
+                return None
+
+        # get default configuration of component.
+        prop = factory.profile()
+
+        inherit_prop = ["config.version",
+                        "openrtm.name",
+                        "openrtm.version",
+                        "os.name",
+                        "os.release",
+                        "os.version",
+                        "os.arch",
+                        "os.hostname",
+                        "corba.endpoints",
+                        "corba.endpoints_ipv4",
+                        "corba.endpoints_ipv6",
+                        "corba.id",
+                        "exec_cxt.periodic.type",
+                        "exec_cxt.periodic.rate",
+                        "exec_cxt.event_driven.type",
+                        "exec_cxt.sync_transition",
+                        "exec_cxt.sync_activation",
+                        "exec_cxt.sync_deactivation",
+                        "exec_cxt.sync_reset",
+                        "exec_cxt.transition_timeout",
+                        "exec_cxt.activation_timeout",
+                        "exec_cxt.deactivation_timeout",
+                        "exec_cxt.reset_timeout",
+                        "exec_cxt.cpu_affinity",
+                        "logger.enable",
+                        "logger.log_level",
+                        "naming.enable",
+                        "naming.type",
+                        "naming.formats",
+                        "sdo.service.provider.available_services",
+                        "sdo.service.consumer.available_services",
+                        "sdo.service.provider.enabled_services",
+                        "sdo.service.consumer.enabled_services",
+                        "manager.instance_name"]
+
+        prop_ = prop.getNode("port")
+        prop_.mergeProperties(self._config.getNode("port"))
+
+        comp = factory.create(self)
+
+        for i in inherit_prop:
+            if self._config.findNode(i):
+                prop.setProperty(
+                    i,
+                    self._config.getProperty(i))
+
+        if comp is None:
+            self._rtcout.RTC_ERROR("createComponent: RTC creation failed: %s",
+                                   comp_id.getProperty("implementation_id"))
+            return None
+
+        if self._config.getProperty("corba.endpoints_ipv4") == "":
+            self.setEndpointProperty(comp.getObjRef())
+
+        self._rtcout.RTC_TRACE(
+            "RTC Created: %s",
+            comp_id.getProperty("implementation_id"))
+        self._listeners.rtclifecycle_.postCreate(comp)
+
+        # The property specified by the parameter of createComponent() is merged.
+        # The property("instance_name") specified by the parameter of createComponent()
+        # must be merged here.
+        prop.mergeProperties(comp_prop)
+
+        # ------------------------------------------------------------
+        # Load configuration file specified in "rtc.conf"
+        #
+        # rtc.conf:
+        #   [category].[type_name].config_file = file_name
+        #   [category].[instance_name].config_file = file_name
+        self._listeners.rtclifecycle_.preConfigure(prop)
+        self.configureComponent(comp, prop)
+        self._listeners.rtclifecycle_.postConfigure(prop)
+
+        # The property specified by the parameter of createComponent() is set.
+        # The property("exported_ports") specified by the parameter of createComponent()
+        # must be set here.
+        # comp.setProperties(comp_prop)
+
+        # Component initialization
+        self._listeners.rtclifecycle_.preInitialize()
+        if comp.initialize() != RTC.RTC_OK:
+            self._rtcout.RTC_TRACE("RTC initialization failed: %s",
+                                   comp_id.getProperty("implementation_id"))
+            self._rtcout.RTC_TRACE(
+                "%s was finalized",
+                comp_id.getProperty("implementation_id"))
+            if comp.exit() != RTC.RTC_OK:
+                self._rtcout.RTC_DEBUG("%s finalization was failed.",
+                                       comp_id.getProperty("implementation_id"))
+            comp.exit()
+            return None
+
+        self._rtcout.RTC_TRACE("RTC initialization succeeded: %s",
+                               comp_id.getProperty("implementation_id"))
+        self._listeners.rtclifecycle_.postInitialize()
+        self.registerComponent(comp)
+
+        return comp
+
+    ##
+    # @if jp
+    # @brief RTコンポーネントを直接 Manager に登録する
+    #
+    # 指定したRTコンポーネントのインスタンスをファクトリ経由ではなく
+    # 直接マネージャに登録する。
+    #
+    # @param self
+    # @param comp 登録対象RTコンポーネントのインスタンス
+    #
+    # @return 登録処理結果(登録成功:true、失敗:false)
+    #
+    # @else
+    # @brief Register RT-Component directly without Factory
+    # @endif
+
+    def registerComponent(self, comp):
+        self._rtcout.RTC_TRACE(
+            "Manager.registerComponent(%s)",
+            comp.getInstanceName())
+
+        self._compManager.registerObject(comp)
+        names = comp.getNamingNames()
+
+        self._listeners.naming_.preBind(comp, names)
+        for name in names:
+            self._rtcout.RTC_TRACE("Bind name: %s", name)
+            self._namingManager.bindObject(name, comp)
+        self._listeners.naming_.postBind(comp, names)
+
+        self.publishPorts(comp)
+        self.subscribePorts(comp)
+
+        try:
+            poa = self._orb.resolve_initial_references("omniINSPOA")
+            poa._get_the_POAManager().activate()
+            id = comp.getCategory() + "." + comp.getInstanceName()
+            poa.activate_object_with_id(id, comp)
+
+            rtcobj = poa.id_to_reference(id)
+            rtcobj._narrow(RTC.RTObject)
+            comp.setINSObjRef(rtcobj)
+        except BaseException:
+            self._rtcout.RTC_DEBUG(OpenRTM_aist.Logger.print_exception())
+
+        return True
+
+    ##
+    # @if jp
+    # @brief RTコンポーネントの登録を解除する
+    #
+    # 指定したRTコンポーネントの登録を解除する。
+    #
+    # @param self
+    # @param comp 登録解除対象RTコンポーネントのインスタンス
+    #
+    # @return 登録解除処理結果(解除成功:true、解除失敗:false)
+    #
+    # @else
+    # @brief Register RT-Component directly without Factory
+    # @endif
+
+    def unregisterComponent(self, comp):
+        self._rtcout.RTC_TRACE(
+            "Manager.unregisterComponent(%s)",
+            comp.getInstanceName())
+        self._compManager.unregisterObject(comp.getInstanceName())
+        names = comp.getNamingNames()
+
+        self._listeners.naming_.preUnbind(comp, names)
+        for name in names:
+            self._rtcout.RTC_TRACE("Unbind name: %s", name)
+            self._namingManager.unbindObject(name)
+        self._listeners.naming_.postUnbind(comp, names)
+
+        return True
+
+    ##
+    # @if jp
+    # @brief Contextを生成する
+    #
+    # @return 生成したConetextのインスタンス
+    #
+    # @else
+    # @brief Create Context
+    #
+    # @return Created Context's instances
+    #
+    # @endif
+    #
+    # ExecutionContextBase* createContext(const char* ec_args);
+
+    def createContext(self, ec_args):
+        self._rtcout.RTC_TRACE("Manager.createContext()")
+        self._rtcout.RTC_TRACE("ExecutionContext type: %s",
+                               self._config.getProperty("exec_cxt.periodic.type"))
+        ec_prop = OpenRTM_aist.Properties()
+        ret, ec_id = self.procContextArgs(ec_args, ec_prop)
+
+        if not ret:
+            return None
+
+        avail_ec_ = OpenRTM_aist.ExecutionContextFactory.instance().getIdentifiers()
+
+        if not ec_id in avail_ec_:
+            self._rtcout.RTC_ERROR("Factory not found: %s", ec_id)
+            return None
+
+        ec = OpenRTM_aist.ExecutionContextFactory.instance().createObject(ec_id)
+        ec.init(ec_prop)
+        self._ecs.append(ec)
+        return ec
+
+    ##
+    # @if jp
+    # @brief Manager に登録されているRTコンポーネントを削除する(未実装)
+    #
+    # マネージャに登録されているRTコンポーネントを削除する。
+    #
+    # @param self
+    # @param instance_name 削除対象RTコンポーネントのインスタンス名
+    #
+    # @else
+    # @brief Unregister RT-Component that is registered in the Manager
+    # @endif
+
+    def deleteComponent(self, instance_name=None, comp=None):
+        if instance_name:
+            self._rtcout.RTC_TRACE(
+                "Manager.deleteComponent(%s)", instance_name)
+            _comp = self._compManager.find(instance_name)
+            if _comp is None:
+                self._rtcout.RTC_WARN(
+                    "RTC %s was not found in manager.", instance_name)
+                return
+            self.deleteComponent(comp=_comp)
+
+        elif comp:
+            self._rtcout.RTC_TRACE("Manager.deleteComponent(RTObject_impl)")
+            # cleanup from manager's table, and naming serivce
+            self.unregisterComponent(comp)
+
+            comp_id = comp.getProperties()
+            factory = self._factory.find(comp_id)
+
+            if not factory:
+                self._rtcout.RTC_DEBUG("Factory not found: %s",
+                                       comp_id.getProperty("implementation_id"))
+                return
+            else:
+                self._rtcout.RTC_DEBUG("Factory found: %s",
+                                       comp_id.getProperty("implementation_id"))
+                factory.destroy(comp)
+
+            if OpenRTM_aist.toBool(self._config.getProperty("manager.shutdown_on_nortcs"),
+                                   "YES", "NO", True) and \
+                not OpenRTM_aist.toBool(self._config.getProperty("manager.is_main"),
+                                        "YES", "NO", False):
+                comps = self.getComponents()
+                if not comps:
+                    self.terminate()
+
+        return
+
+    ##
+    # @if jp
+    # @brief Manager に登録されているRTコンポーネントを検索する
+    #
+    # Manager に登録されているRTコンポーネントを指定した名称で検索し、
+    # 合致するコンポーネントを取得する。
+    #
+    # @param self
+    # @param instance_name 検索対象RTコンポーネントの名称
+    #
+    # @return 名称が一致するRTコンポーネントのインスタンス
+    #
+    # @else
+    # @brief Get RT-Component's pointer
+    # @endif
+
+    def getComponent(self, instance_name):
+        self._rtcout.RTC_TRACE("Manager.getComponent(%s)", instance_name)
+        return self._compManager.find(instance_name)
+
+    ##
+    # @if jp
+    # @brief Manager に登録されている全RTコンポーネントを取得する
+    #
+    # Manager に登録されているRTコンポーネントの全インスタンスを取得する。
+    #
+    # @param self
+    #
+    # @return 全RTコンポーネントのインスタンスリスト
+    #
+    # @else
+    # @brief Get all RT-Component's pointer
+    # @endif
+
+    def getComponents(self):
+        self._rtcout.RTC_TRACE("Manager.getComponents()")
+        return self._compManager.getObjects()
+
+    # void Manager::
+    # addManagerActionListener(RTM::ManagerActionListener* listener)
+
+    def addManagerActionListener(self, listener):
+        self._listeners.manager_.addListener(listener)
+        return
+
+    # void Manager::
+    # removeManagerActionListener(RTM::ManagerActionListener* listener)
+
+    def removeManagerActionListener(self, listener):
+        self._listeners.manager_.removeListener(listener)
+        return
+
+    # void Manager::
+    # addModuleActionListener(RTM::ModuleActionListener* listener)
+
+    def addModuleActionListener(self, listener):
+        self._listeners.module_.addListener(listener)
+        return
+
+    # void Manager::
+    # removeModuleActionListener(RTM::ModuleActionListener* listener)
+
+    def removeModuleActionListener(self, listener):
+        self._listeners.module_.removeListener(listener)
+        return
+
+    # void Manager::
+    # addRtcLifecycleActionListener(RTM::RtcLifecycleActionListener* listener)
+
+    def addRtcLifecycleActionListener(self, listener):
+        self._listeners.rtclifecycle_.addListener(listener)
+        return
+
+    # void Manager::
+    # removeRtcLifecycleActionListener(RTM::RtcLifecycleActionListener*
+    # listener)
+
+    def removeRtcLifecycleActionListener(self, listener):
+        self._listeners.rtclifecycle_.removeListener(listener)
+        return
+
+    # void Manager::
+    # addNamingActionListener(RTM::NamingActionListener* listener)
+
+    def addNamingActionListener(self, listener):
+        self._listeners.naming_.addListener(listener)
+        return
+
+    # void Manager::
+    # removeNamingActionListener(RTM::NamingActionListener* listener)
+
+    def removeNamingActionListener(self, listener):
+        self._listeners.naming_.removeListener(listener)
+        return
+
+    # void Manager::
+    # addLocalServiceActionListener(RTM::LocalServiceActionListener* listener)
+
+    def addLocalServiceActionListener(self, listener):
+        self._listeners.localservice_.addListener(listener)
+        return
+
+    # void Manager::
+    # removeLocalServiceActionListener(RTM::LocalServiceActionListener*
+    # listener)
+
+    def removeLocalServiceActionListener(self, listener):
+        self._listeners.localservice_.removeListener(listener)
+        return
+
+    # ============================================================
+    # CORBA 関連
+    # ============================================================
+
+    ##
+    # @if jp
+    # @brief ORB のポインタを取得する
+    #
+    # Manager に設定された ORB のポインタを取得する。
+    #
+    # @param self
+    #
+    # @return ORB オブジェクト
+    #
+    # @else
+    # @brief Get the pointer to the ORB
+    # @endif
+
+    def getORB(self):
+        self._rtcout.RTC_TRACE("Manager.getORB()")
+        return self._orb
+
+    ##
+    # @if jp
+    # @brief Manager が持つ RootPOA のポインタを取得する
+    #
+    # Manager に設定された RootPOA へのポインタを取得する。
+    #
+    # @param self
+    #
+    # @return RootPOAオブジェクト
+    #
+    # @else
+    # @brief Get the pointer to the RootPOA
+    # @endif
+
+    def getPOA(self):
+        self._rtcout.RTC_TRACE("Manager.getPOA()")
+        return self._poa
+
+    ##
+    # @if jp
+    # @brief Manager が持つ POAManager を取得する
+    #
+    # Manager に設定された POAMAnager を取得する。
+    #
+    # @param self
+    #
+    # @return POAマネージャ
+    #
+    # @else
+    #
+    # @endif
+
+    def getPOAManager(self):
+        self._rtcout.RTC_TRACE("Manager.getPOAManager()")
+        return self._poaManager
+
+    # ============================================================
+    # Manager initialize and finalization
+    # ============================================================
+
+    ##
+    # @if jp
+    # @brief Manager の内部初期化処理
+    #
+    # Manager の内部初期化処理を実行する。
+    #  - Manager コンフィギュレーションの設定
+    #  - ログ出力ファイルの設定
+    #  - 終了処理用スレッドの生成
+    #  - タイマ用スレッドの生成(タイマ使用時)
+    #
+    # @param self
+    # @param argv コマンドライン引数
+    #
+    # @else
+    # @brief Manager internal initialization
+    # @endif
+
+    def initManager(self, argv):
+        config = OpenRTM_aist.ManagerConfig(argv)
+        self._config = OpenRTM_aist.Properties()
+        config.configure(self._config)
+        self._config.setProperty("logger.file_name", self.formatString(self._config.getProperty("logger.file_name"),
+                                                                       self._config))
+        self._module = OpenRTM_aist.ModuleManager(self._config)
+
+        self._needsTimer = OpenRTM_aist.toBool(self._config.getProperty(
+                "timer.enable"), "YES", "NO", True)
+
+
+        if OpenRTM_aist.toBool(self._config.getProperty("manager.shutdown_auto"),
+                                   "YES", "NO", True) and \
+                not OpenRTM_aist.toBool(self._config.getProperty("manager.is_main"),
+                                        "YES", "NO", False) and \
+                self._needsTimer:
+            tm = OpenRTM_aist.TimeValue(10, 0)
+            if self._config.findNode("manager.auto_shutdown_duration"):
+                duration = float(self._config.getProperty(
+                    "manager.auto_shutdown_duration"))
+                if duration:
+                    tm.set_time(duration)
+            self.addTask(self.shutdownOnNoRtcs, tm)
+
+        if self._needsTimer:
+            self.addTask(self.cleanupComponents, OpenRTM_aist.TimeValue(1, 0))
+
+        lmpm_ = [s.strip() for s in self._config.getProperty(
+            "manager.preload.modules").split(",")]
+        for mpm_ in lmpm_:
+            if not mpm_:
+                continue
+            basename_ = mpm_.split(".")[0] + "Init"
+            try:
+                self._module.load(mpm_, basename_)
+            except BaseException:
+                self._rtcout.RTC_ERROR(OpenRTM_aist.Logger.print_exception())
+
+        self._config.setProperty("manager.instance_name", self.formatString(self._config.getProperty("manager.instance_name"),
+                                                                            self._config))
+
+        return
+
+    ##
+    # @if jp
+    # @brief Managerサーバントの終了処理(未実装)
+    #
+    # Managerサーバントを終了する
+    #
+    #
+    # @param self
+    #
+    # @else
+    #
+    # @endif
+    def shutdownManagerServant(self):
+        self._rtcout.RTC_TRACE("Manager.shutdownManagerServant()")
+        if self._mgrservant:
+            self._mgrservant.exit()
+            try:
+                self._poa.deactivate_object(self._poa.servant_to_id(self._mgrservant))
+            except BaseException:
+                print(OpenRTM_aist.Logger.print_exception())
+            self._mgrservant = None
+        return
+
+    ##
+    # @if jp
+    # @brief Manager の終了処理(未実装)
+    #
+    # Manager を終了する
+    # (ただし,現在は未実装)
+    #
+    # @param self
+    #
+    # @else
+    #
+    # @endif
+    def shutdownManager(self):
+        self._rtcout.RTC_TRACE("Manager.shutdownManager()")
+        self._listeners.manager_.preShutdown()
+        self.shutdownComponents()
+        self.shutdownManagerServant()
+        self.shutdownNaming()
+        self.shutdownORB()
+
+        self._threadOrb.join()
+        self._listeners.manager_.postShutdown()
+        self.shutdownLogger()
+        global manager
+        if manager:
+            manager = None
+
+        return
+
+    ##
+    # @if jp
+    # @brief Manager の終了処理
+    #
+    # configuration の "manager.shutdown_on_nortcs" YES で、
+    # コンポーネントが登録されていない場合 Manager を終了する。
+    #
+    # @else
+    # @brief Shutdown Manager
+    #
+    # This method shutdowns Manager as follows.
+    # - "Manager.shutdown_on_nortcs" of configuration is YES.
+    # - The component is not registered.
+    #
+    # @endif
+    #
+    # void shutdownOnNoRtcs();
+
+    def shutdownOnNoRtcs(self):
+        self._rtcout.RTC_TRACE("Manager::shutdownOnNoRtcs()")
+        if OpenRTM_aist.toBool(self._config.getProperty("manager.shutdown_on_nortcs"),
+                               "YES", "NO", True):
+
+            comps = self.getComponents()
+
+            if not comps:
+                self.terminate()
+
+        return
+
+    # ============================================================
+    # Logger initialize and terminator
+    # ============================================================
+
+    ##
+    # @if jp
+    # @brief
+    #
+    #
+    #
+    #
+    #
+    # @param self
+    #
+    #
+    # @else
+    # @brief
+    #
+    #
+    #
+    # @param self
+    #
+    #
+    # @endif
+    def initLogstreamFile(self):
+
+        logprop = self._config.getNode("logger")
+        logstream = OpenRTM_aist.LogstreamFactory.instance().createObject("file")
+
+        if logstream is None:
+            return
+
+        if not logstream.init(logprop):
+            return
+
+        self._rtcout.addLogger(logstream)
+
+    ##
+    # @if jp
+    # @brief
+    #
+    #
+    #
+    #
+    #
+    # @param self
+    #
+    #
+    # @else
+    # @brief
+    #
+    #
+    #
+    # @param self
+    #
+    #
+    # @endif
+
+    def initLogstreamPlugins(self):
+        lmod_ = [s.strip()
+                 for s in self._config.getProperty("logger.plugins").split(",")]
+        for mod_ in lmod_:
+            if not mod_:
+                continue
+            basename_ = mod_.split(".")[0] + "Init"
+            try:
+                self._module.load(mod_, basename_)
+            except BaseException:
+                self._rtcout.RTC_ERROR(OpenRTM_aist.Logger.print_exception())
+
+    ##
+    # @if jp
+    # @brief
+    #
+    #
+    #
+    #
+    #
+    # @param self
+    #
+    #
+    # @else
+    # @brief
+    #
+    #
+    #
+    # @param self
+    #
+    #
+    # @endif
+    def initLogstreamOthers(self):
+        factory = OpenRTM_aist.LogstreamFactory.instance()
+        pp = self._config.getNode("logger.logstream")
+
+        leaf0 = pp.getLeaf()
+
+        for l in leaf0:
+            lstype = l.getName()
+            logstream = factory.createObject(lstype)
+            if logstream is None:
+                self._rtcout.RTC_WARN("Logstream %s creation failed." % lstype)
+                continue
+            self._rtcout.RTC_INFO("Logstream %s created." % lstype)
+            if not logstream.init(l):
+                self._rtcout.RTC_WARN("Logstream %s init failed." % lstype)
+
+                self._rtcout.RTC_WARN("Logstream %s deleted." % lstype)
+                continue
+
+            self._rtcout.RTC_INFO("Logstream %s added." % lstype)
+            self._rtcout.addLogger(logstream)
+
+    ##
+    # @if jp
+    # @brief System logger の初期化
+    #
+    # System logger の初期化を実行する。
+    # コンフィギュレーションファイルに設定された情報に基づき、
+    # ロガーの初期化,設定を実行する。
+    #
+    # @param self
+    #
+    # @return 初期化実行結果(初期化成功:true、初期化失敗:false)
+    #
+    # @else
+    # @brief System logger initialization
+    # @endif
+
+    def initLogger(self):
+        # self._rtcout = OpenRTM_aist.LogStream()
+        self._rtcout = self.getLogbuf()
+        if not OpenRTM_aist.toBool(self._config.getProperty(
+                "logger.enable"), "YES", "NO", True):
+            return True
+
+        self.initLogstreamFile()
+        self.initLogstreamPlugins()
+        self.initLogstreamOthers()
+
+        self._rtcout.setLogLevel(self._config.getProperty("logger.log_level"))
+        self._rtcout.setLogLock(OpenRTM_aist.toBool(self._config.getProperty("logger.stream_lock"),
+                                                    "enable", "disable", False))
+
+        self._rtcout.RTC_INFO(
+            "%s", self._config.getProperty("openrtm.version"))
+        self._rtcout.RTC_INFO("Copyright (C) 2003-2020, Noriaki Ando and OpenRTM development team,")
+        self._rtcout.RTC_INFO("  Intelligent Systems Research Institute, AIST,")
+        self._rtcout.RTC_INFO("Copyright (C) 2020, Noriaki Ando and OpenRTM development team,")
+        self._rtcout.RTC_INFO("  Industrial Cyber-Physical Research Center, AIST,")
+        self._rtcout.RTC_INFO("  All right reserved.")
+        self._rtcout.RTC_INFO("Manager starting.")
+        self._rtcout.RTC_INFO("Starting local logging.")
+
+        return True
+
+    ##
+    # @if jp
+    # @brief System Logger の終了処理(未実装)
+    #
+    # System Loggerの終了処理を実行する。
+    # (現在は未実装)
+    #
+    # @param self
+    #
+    # @else
+    # @brief System Logger finalization
+    # @endif
+
+    def shutdownLogger(self):
+        self._rtcout.RTC_TRACE("Manager.shutdownLogger()")
+        self._rtcout.shutdown()
+        return
+
+    # ============================================================
+    # ORB initialization and finalization
+    # ============================================================
+
+    ##
+    # @if jp
+    # @brief CORBA ORB の初期化処理
+    #
+    # 設定情報を元にORBを初期化する。
+    #
+    # @param self
+    #
+    # @return ORB 初期化処理結果(初期化成功:true、初期化失敗:false)
+    #
+    # @else
+    # @brief CORBA ORB initialization
+    # @endif
+
+    def initORB(self):
+        self._rtcout.RTC_TRACE("Manager.initORB()")
+        try:
+            tmp_args = self.createORBOptions().split("\"")
+            args = []
+            for i, tmp_arg in enumerate(tmp_args):
+                if i % 2 == 0:
+                    args.extend(tmp_arg.strip().split(" "))
+                else:
+                    args.append(tmp_arg)
+
+            args.insert(0, "manager")
+            argv = OpenRTM_aist.toArgv(args)
+
+            self._orb = CORBA.ORB_init(argv)
+
+            self._poa = self._orb.resolve_initial_references("RootPOA")
+
+            if CORBA.is_nil(self._poa):
+                self._rtcout.RTC_ERROR("Could not resolve RootPOA")
+                return False
+
+            self._poaManager = self._poa._get_the_POAManager()
+
+        except BaseException:
+            self._rtcout.RTC_ERROR(
+                "Exception: Caught unknown exception in initORB().")
+            self._rtcout.RTC_ERROR(OpenRTM_aist.Logger.print_exception())
+            return False
+
+        return True
+
+    ##
+    # @if jp
+    # @brief ORB のコマンドラインオプション作成
+    #
+    # コンフィギュレーション情報に設定された内容から
+    # ORB の起動時オプションを作成する。
+    #
+    # @param self
+    #
+    # @return ORB 起動時オプション
+    #
+    # @else
+    # @brief ORB command option creation
+    # @endif
+
+    def createORBOptions(self):
+        opt = self._config.getProperty("corba.args")
+        self._rtcout.RTC_DEBUG("corba.args: %s", opt)
+
+        endpoints = self.createORBEndpoints()
+        opt = self.createORBEndpointOption(opt, endpoints)
+
+        self._rtcout.RTC_PARANOID("ORB options: %s", opt)
+
+        return opt
+
+    ##
+    # @if jp
+    # @brief エンドポイントの生成
+    #
+    # コンフィグレーションからエンドポイントを生成する。
+    #
+    # @param endpoints エンドポイントリスト
+    #
+    # @else
+    # @brief Create Endpoints
+    #
+    # Create Endpoints from the configuration.
+    #
+    # @param endpoints Endpoints list
+    #
+    # @endif
+    #
+    # void createORBEndpoints(coil::vstring& endpoints);
+
+    def createORBEndpoints(self):
+        endpoints = []
+        # corba.endpoint is obsolete
+        # corba.endpoints with comma separated values are acceptable
+        if self._config.findNode("corba.endpoints"):
+            endpoints_ = [s.strip() for s in self._config.getProperty(
+                "corba.endpoints").split(",")]
+            for ep in endpoints_:
+                endpoints.append(ep)
+
+            self._rtcout.RTC_DEBUG(
+                "corba.endpoints: %s",
+                self._config.getProperty("corba.endpoints"))
+
+        if self._config.findNode("corba.endpoint"):
+            endpoints_ = [s.strip() for s in self._config.getProperty(
+                "corba.endpoint").split(",")]
+            for ep in endpoints_:
+                endpoints.append(ep)
+            self._rtcout.RTC_DEBUG(
+                "corba.endpoint: %s",
+                self._config.getProperty("corba.endpoint"))
+
+        # If this process has main manager,
+        # main manager's endpoint inserted at the top of endpoints
+        self._rtcout.RTC_DEBUG("manager.is_main: %s",
+                               self._config.getProperty("manager.is_main"))
+
+        if OpenRTM_aist.toBool(self._config.getProperty(
+                "manager.is_main"), "YES", "NO", False):
+            mm = self._config.getProperty("corba.main_manager", ":2810")
+            mmm = [s.strip() for s in mm.split(":")]
+            if len(mmm) == 2:
+                endpoints.insert(0, ":" + mmm[1])
+            else:
+                endpoints.insert(0, ":2810")
+
+        endpoints = OpenRTM_aist.unique_sv(endpoints)
+
+        return endpoints
+
+    ##
+    # @if jp
+    # @brief ORB の Endpoint のコマンドラインオプション作成
+    # @param opt コマンドラインオプション
+    # @param endpoints エンドポイントリスト
+    #
+    # @else
+    # @brief Create a command optional line of Endpoint of ORB.
+    # @param opt ORB options
+    # @param endpoints Endpoints list
+    #
+    # @endif
+    # void createORBEndpointOption(std::string& opt, coil::vstring& endpoints);
+
+    def createORBEndpointOption(self, opt, endpoints):
+        corba = self._config.getProperty("corba.id")
+        self._rtcout.RTC_DEBUG("corba.id: %s", corba)
+
+        for i, e in enumerate(endpoints):
+            if e:
+                endpoint = e
+            else:
+                continue
+
+            self._rtcout.RTC_DEBUG("Endpoint is : %s", endpoint)
+            if endpoint.find(":") == -1:
+                endpoint += ":"
+
+            if corba == "omniORB":
+                endpoint = OpenRTM_aist.normalize(endpoint)
+                if endpoint == "all:":
+                    opt += " -ORBendPointPublish all(addr)"
+                else:
+                    opt += " -ORBendPoint giop:tcp:" + endpoint
+
+            elif corba == "TAO":
+                opt += "-ORBEndPoint iiop://" + endpoint
+            elif corba == "MICO":
+                opt += "-ORBIIOPAddr inet:" + endpoint
+
+            endpoints[i] = endpoint
+
+        return opt
+
+    ##
+    # @if jp
+    # @brief ORB の終了処理
+    #
+    # ORB の終了処理を実行する。
+    # 実行待ちの処理が存在する場合には、その処理が終了するまで待つ。
+    # 実際の終了処理では、POA Managerを非活性化し、 ORB のシャットダウンを実行
+    # する。
+    #
+    # @param self
+    #
+    # @else
+    # @brief ORB finalization
+    # @endif
+
+    def shutdownORB(self):
+        self._rtcout.RTC_TRACE("Manager.shutdownORB()")
+        if not self._orb:
+            return
+
+        try:
+            while self._orb.work_pending():
+                self._rtcout.RTC_PARANOID("Pending work still exists.")
+                if self._orb.work_pending():
+                    self._orb.perform_work()
+
+            self._rtcout.RTC_DEBUG(
+                "No pending works of ORB. Shutting down POA and ORB.")
+        except BaseException:
+            self._rtcout.RTC_TRACE(OpenRTM_aist.Logger.print_exception())
+
+        if not CORBA.is_nil(self._poa):
+            try:
+                if not CORBA.is_nil(self._poaManager):
+                    self._poaManager.deactivate(False, True)
+                self._rtcout.RTC_DEBUG("POA Manager was deactivated.")
+                self._poa.destroy(False, True)
+                self._poa = PortableServer.POA._nil
+                self._rtcout.RTC_DEBUG("POA was destroyed.")
+            except CORBA.SystemException:
+                self._rtcout.RTC_ERROR(
+                    "Caught SystemException during root POA destruction")
+                self._rtcout.RTC_ERROR(OpenRTM_aist.Logger.print_exception())
+            except BaseException:
+                self._rtcout.RTC_ERROR(
+                    "Caught unknown exception during destruction")
+                self._rtcout.RTC_ERROR(OpenRTM_aist.Logger.print_exception())
+
+        if self._orb:
+            try:
+                self._orb.shutdown(True)
+                self._orb.destroy()
+                self._rtcout.RTC_DEBUG("ORB was shutdown.")
+                self._orb = CORBA.Object._nil
+            except CORBA.SystemException:
+                self._rtcout.RTC_ERROR(
+                    "Caught CORBA::SystemException during ORB shutdown.")
+                self._rtcout.RTC_ERROR(OpenRTM_aist.Logger.print_exception())
+            except BaseException:
+                self._rtcout.RTC_ERROR(
+                    "Caught unknown exception during ORB shutdown.")
+                self._rtcout.RTC_ERROR(OpenRTM_aist.Logger.print_exception())
+
+    # ============================================================
+    # NamingService initialization and finalization
+    # ============================================================
+
+    ##
+    # @if jp
+    # @brief NamingManager の初期化
+    #
+    # NamingManager の初期化処理を実行する。
+    # ただし、 NamingManager を使用しないようにプロパティ情報に設定されている
+    # 場合には何もしない。
+    # NamingManager を使用する場合、プロパティ情報に設定されている
+    # デフォルト NamingServer を登録する。
+    # また、定期的に情報を更新するように設定されている場合には、指定された周期
+    # で自動更新を行うためのタイマを起動するとともに、更新用メソッドをタイマに
+    # 登録する。
+    #
+    # @param self
+    #
+    # @return 初期化処理結果(初期化成功:true、初期化失敗:false)
+    #
+    # @else
+    #
+    # @endif
+
+    def initNaming(self):
+        self._rtcout.RTC_TRACE("Manager.initNaming()")
+        self._namingManager = OpenRTM_aist.NamingManager(self)
+
+        if not OpenRTM_aist.toBool(self._config.getProperty(
+                "naming.enable"), "YES", "NO", True):
+            return True
+
+        # meths = OpenRTM_aist.split(self._config.getProperty("naming.type"),",")
+        meths = [s.strip()
+                 for s in self._config.getProperty("naming.type").split(",")]
+
+        for meth in meths:
+            # names = OpenRTM_aist.split(self._config.getProperty(meth+".nameservers"), ",")
+            names = [
+                s.strip() for s in self._config.getProperty(
+                    meth + ".nameservers").split(",")]
+            for name in names:
+                self._rtcout.RTC_TRACE(
+                    "Register Naming Server: %s/%s", (meth, name))
+                self._namingManager.registerNameServer(meth, name)
+
+        if OpenRTM_aist.toBool(self._config.getProperty(
+                "naming.update.enable"), "YES", "NO", True) and self._needsTimer:
+            tm = OpenRTM_aist.TimeValue(10, 0)
+            intr = self._config.getProperty("naming.update.interval")
+            if intr != "":
+                tm = OpenRTM_aist.TimeValue(intr)
+
+            self.addTask(self._namingManager.update, tm)
+
+        return True
+
+    ##
+    # @if jp
+    # @brief NamingManager の終了処理
+    #
+    # NamingManager を終了する。
+    # 登録されている全要素をアンバインドし、終了する。
+    #
+    # @param self
+    #
+    # @else
+    #
+    # @endif
+
+    def shutdownNaming(self):
+        self._rtcout.RTC_TRACE("Manager.shutdownNaming()")
+        comps = self.getComponents()
+
+        for comp in comps:
+            names = comp.getNamingNames()
+            self._listeners.naming_.preUnbind(comp, names)
+            for name in names:
+                self._namingManager.unbindObject(name)
+            self._listeners.naming_.postUnbind(comp, names)
+
+        self._namingManager.unbindAll()
+        return
+
+    ##
+    # @if jp
+    # @brief ExecutionContextManager の初期化
+    #
+    # 使用する各 ExecutionContext の初期化処理を実行し、各 ExecutionContext
+    # 生成用 Factory を ExecutionContextManager に登録する。
+    #
+    # @param self
+    #
+    # @return ExecutionContextManager 初期化処理実行結果
+    #         (初期化成功:true、初期化失敗:false)
+    #
+    # @else
+    #
+    # @endif
+
+    def initExecContext(self):
+        self._rtcout.RTC_TRACE("Manager.initExecContext()")
+        OpenRTM_aist.PeriodicExecutionContextInit(self)
+        OpenRTM_aist.ExtTrigExecutionContextInit(self)
+        OpenRTM_aist.OpenHRPExecutionContextInit(self)
+        OpenRTM_aist.SimulatorExecutionContextInit(self)
+        OpenRTM_aist.MultilayerCompositeECInit(self)
+
+        self.initCpuAffinity()
+        return True
+
+    ##
+    # @if jp
+    # @brief CPUアフィニティの設定
+    #
+    # manager.cpu_affinityで指定したプロセスのCPUアフィニティに設定する
+    #
+    # @param self
+    #
+    #
+    # @else
+    #
+    # @param self
+    #
+    # @endif
+    def initCpuAffinity(self):
+        self._rtcout.RTC_TRACE("Manager.initCpuAffinity()")
+
+        if not self._config.findNode("manager.cpu_affinity"):
+            return
+
+        affinity_str = self._config.getProperty("manager.cpu_affinity")
+
+        if affinity_str:
+            self._rtcout.RTC_DEBUG("CPU affinity property: %s", affinity_str)
+
+            tmp = affinity_str.split(",")
+
+            cpu_num = []
+            for num in tmp:
+                try:
+                    cpu_num.append(int(num))
+                    self._rtcout.RTC_DEBUG(
+                        "CPU affinity mask set to %d", int(num))
+                except BaseException:
+                    pass
+
+            if not cpu_num:
+                return
+
+            ret = OpenRTM_aist.setProcessAffinity(cpu_num)
+
+            if ret == False:
+                self._rtcout.RTC_ERROR("CPU affinity mask setting failed")
+
+    ##
+    # @if jp
+    # @brief PeriodicECSharedComposite の初期化
+    #
+    # @return PeriodicECSharedComposite 初期化処理実行結果
+    #         (初期化成功:true、初期化失敗:false)
+    #
+    # @else
+    # @brief PeriodicECSharedComposite initialization
+    #
+    # @return PeriodicECSharedComposite initialization result
+    #          (Successful:true, Failed:false)
+    #
+    # @endif
+    #
+
+    def initComposite(self):
+        self._rtcout.RTC_TRACE("Manager.initComposite()")
+        OpenRTM_aist.PeriodicECSharedCompositeInit(self)
+        return True
+
+    ##
+    # @if jp
+    # @brief ファクトリの初期化
+    #
+    # バッファ、スレッド、パブリッシャ、プロバイダ、コンシューマの
+    # ファクトリを初期化する。
+    #
+    # @return ファクトリ初期化処理実行結果
+    #         (初期化成功:true、初期化失敗:false)
+    #
+    # @else
+    # @brief Factories initialization
+    #
+    # Initialize buffer factories, thread factories, publisher factories,
+    # provider factories, and consumer factories.
+    #
+    # @return PeriodicECSharedComposite initialization result
+    #          (Successful:true, Failed:false)
+    #
+    # @endif
+    #
+
+    def initFactories(self):
+        # self._rtcout.RTC_TRACE("Manager.initFactories()")
+        OpenRTM_aist.FactoryInit()
+        return True
+
+    ##
+    # @if jp
+    # @brief Timer の初期化
+    #
+    # 使用する各 Timer の初期化処理を実行する。
+    # (現状の実装では何もしない)
+    #
+    # @param self
+    #
+    # @return Timer 初期化処理実行結果(初期化成功:true、初期化失敗:false)
+    #
+    # @else
+    #
+    # @endif
+
+    def initTimer(self):
+        return True
+
+    ##
+    # @if jp
+    # @brief Timer の終了
+    #
+    # 使用する各 Timer の終了処理を実行する。
+    #
+    # @param self
+    #
+    # @else
+    #
+    # @endif
+    def shutdownTimer(self):
+        self._rtcout.RTC_TRACE("Manager.shutdownTimer()")
+        if self._timer:
+            self._timer.stop()
+            self._timer.join()
+            self._timer = None
+
+    ##
+    # @if jp
+    # @brief corba.endpoint_property プロパティの取得
+    #
+    # corba.endpoint_property の値を取得しタプルとして返す。ノードのエン
+    # ドポイントの内 IPv4, IPv6 のいずれを公開するかを指定するプロパティ
+    # corba.endpoint_property を取得し IPv4/IPv6 の有効無効および、有効に
+    # するIPアドレスの番号をタプル値として返す。
+    #
+    # @return (ipv4, ipv4_list, ipv6, ipv6_list) endpoint_property 値
+    # ipv4, ipv6:  IPv4/IPv6 の有効無効を示すTrue/False
+    # ipv4_list, ipv6_list: 有効にするアドレスの番号、空リストの場合はすべて有効
+    #
+    # @else
+    # @brief ManagerServant initialization
+    #
+    # Getting corba.endpoint_property value and return them as a
+    # tuple. This function obtains corbaendpoint_property that specifies
+    # if IPv4/IPv6 addresses and IP address numbes to be published, and
+    # it returnes them as tuple.
+    #
+    # @return (ipv4, ipv4_list, ipv6, ipv6_list) endpoint_property value
+    # ipv4, ipv6: A True/False flag whether to use IPv4 / IPv6 address
+    # ipv4_list, ipv6_list: List of valid address number, empty means
+    # valid all addresses
+    #
+    # @endif
+    #
+
+    def endpointPropertySwitch(self):
+        ipv4 = True
+        ipv4_list = []
+        ipv6 = True
+        ipv6_list = []
+
+        ep_prop = self._config.getProperty("corba.endpoint_property", "ipv4")
+        ep_prop = ep_prop.lower()
+
+        import re
+        if ep_prop.count("ipv4"):
+            ipv4 = True
+            m = re.match(r"ipv4\(([0-9, ]*)\)", ep_prop)
+            if m:
+                ipv4_list = map(int, m.group(1).split(","))
+        else:
+            ipv4 = False
+        if ep_prop.count("ipv6"):
+            ipv6 = True
+            m = re.match(r"ipv6\(([0-9, ]*)\)", ep_prop)
+            if m:
+                ipv6_list = map(int, m.group(1).split(","))
+        else:
+            ipv6 = False
+        return (ipv4, ipv4_list, ipv6, ipv6_list)
+
+    ##
+    # @if jp
+    # @brief Endpoint をプロパティに設定
+    #
+    # この関数はエンドポイントをプロパティ corba.endpoints に指定する。引
+    # 数に与えられたオブジェクトリファレンスから現在のプロセスのエンドポ
+    # イント (IPアドレス, ポート番号) を取得し corba.endpoints,
+    # corba.endpoints_ipv4, corba.endpoints_ipv6 に指定する。
+    #
+    # @param objref オブジェクトリファレンス
+    #
+    # @else
+    # @brief Setting endpoint information to property
+    #
+    # This function sets endpoint information to corba.endpoints
+    # property. It extract endpoint information (list of IP address,
+    # port number) from given object reference, and set them to
+    # corba.endpoints, corba.endpoints_ipv4, corba.endpoints_ipv6
+    #
+    # @param objref A object reference
+    #
+    # @endif
+    #
+    def setEndpointProperty(self, objref):
+        import re
+        (ipv4, ipv4_list, ipv6, ipv6_list) = self.endpointPropertySwitch()
+        re_ipv4 = r"((?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?))"
+        re_ipv6 = r"(([0-9a-f]{1,4})(:([0-9a-f]{1,4})){7}((\.|#|p| port )\d{1,4})?)|\[([0-9a-f]{1,4})(:([0-9a-f]{1,4})){7}\]"
+
+        iorstr = self._orb.object_to_string(objref)
+
+        ior = CORBA_IORUtil.toIOR(iorstr)
+
+        endpoints = CORBA_IORUtil.getEndpoints(ior)
+
+        epstr = ""
+        epstr_ipv4 = ""
+        epstr_ipv6 = ""
+        ipv4_count = 0
+        ipv6_count = 0
+        for e in endpoints:
+            if ipv4 and re.match(re_ipv4, e.host):
+                if not ipv4_list or ipv4_list.count(ipv4_count):
+                    epstr += e.host + ":" + str(e.port) + ", "
+                    epstr_ipv4 += e.host + ":" + str(e.port) + ", "
+                ipv4_count += 1
+            if ipv6 and re.match(re_ipv6, e.host):
+                if not ipv6_list or ipv6_list.count(ipv6_count):
+                    epstr += e.host + ":" + str(e.port) + ", "
+                    epstr_ipv6 += e.host + ":" + str(e.port) + ", "
+                ipv6_count += 1
+        epstr = epstr[:-2]
+        epstr_ipv4 = epstr_ipv4[:-2]
+        epstr_ipv6 = epstr_ipv6[:-2]
+        self._config.setProperty("corba.endpoints", epstr)
+        self._config.setProperty("corba.endpoints_ipv4", epstr_ipv4)
+        self._config.setProperty("corba.endpoints_ipv6", epstr_ipv6)
+
+    ##
+    # @if jp
+    # @brief ManagerServant の初期化
+    #
+    # @return Timer 初期化処理実行結果(初期化成功:true、初期化失敗:false)
+    #
+    # @else
+    # @brief ManagerServant initialization
+    #
+    # @return Timer Initialization result (Successful:true, Failed:false)
+    #
+    # @endif
+    #
+    def initManagerServant(self):
+        self._rtcout.RTC_TRACE("Manager.initManagerServant()")
+        if not OpenRTM_aist.toBool(
+                self._config.getProperty("manager.corba_servant"), "YES", "NO", True):
+            return True
+
+        self._mgrservant = OpenRTM_aist.ManagerServant()
+        if self._config.getProperty("corba.endpoints_ipv4") == "":
+            self.setEndpointProperty(self._mgrservant.getObjRef())
+        prop = self._config.getNode("manager")
+        names = OpenRTM_aist.split(prop.getProperty("naming_formats"), ",")
+
+        if OpenRTM_aist.toBool(prop.getProperty("is_main"),
+                               "YES", "NO", True):
+            for name in names:
+                mgr_name = self.formatString(name, prop)
+                self._namingManager.bindManagerObject(
+                    mgr_name, self._mgrservant)
+
+        if OpenRTM_aist.toBool(self._config.getProperty("corba.update_main_manager.enable"),
+                                   "YES", "NO", True) and \
+                not OpenRTM_aist.toBool(self._config.getProperty("manager.is_main"),
+                                        "YES", "NO", False) and \
+                self._needsTimer:
+            tm = OpenRTM_aist.TimeValue(10, 0)
+            if self._config.findNode("corba.update_main_manager.interval"):
+                duration = float(self._config.getProperty(
+                    "corba.update_main_manager.interval"))
+                if duration:
+                    tm.set_time(duration)
+
+            self.addTask(self._mgrservant.updateMainManager, tm)
+
+        otherref = None
+
+        return True
+
+    # bool Manager::initLocalService()
+
+    def initLocalService(self):
+        self._rtcout.RTC_TRACE("Manager::initLocalService()")
+        admin_ = OpenRTM_aist.LocalServiceAdmin.instance()
+        prop_ = OpenRTM_aist.Properties(
+            prop=self._config.getNode("manager.local_service"))
+        admin_.init(prop_)
+        self._rtcout.RTC_DEBUG("LocalServiceAdmin's properties:")
+        self._rtcout.RTC_DEBUG("%s", prop_)
+
+        svclist_ = admin_.getServiceProfiles()
+        for svc_ in svclist_:
+            self._rtcout.RTC_INFO("Available local service: %s (%s)",
+                                  (svc_.name, svc_.uuid))
+        return True
+
+    ##
+    # @if jp
+    # @brief NamingManager に登録されている全コンポーネントの終了処理
+    #
+    # NamingManager に登録されているRTコンポーネントおよび ExecutionContext の
+    # リストを取得し、全コンポーネントを終了する。
+    #
+    # @param self
+    #
+    # @else
+    #
+    # @endif
+
+    def shutdownComponents(self):
+        self._rtcout.RTC_TRACE("Manager.shutdownComponents()")
+        comps = self._namingManager.getObjects()
+        for comp in comps:
+            try:
+                comp.exit()
+                p = OpenRTM_aist.Properties(key=comp.getInstanceName())
+                p.mergeProperties(comp.getProperties())
+            except BaseException:
+                self._rtcout.RTC_TRACE(OpenRTM_aist.Logger.print_exception())
+
+        for ec in self._ecs:
+            try:
+                self._poa.deactivate_object(self._poa.servant_to_id(ec))
+            except BaseException:
+                self._rtcout.RTC_TRACE(OpenRTM_aist.Logger.print_exception())
+
+    ##
+    # @if jp
+    # @brief RTコンポーネントの登録解除
+    #
+    # 指定したRTコンポーネントのインスタンスをネーミングサービスから
+    # 登録解除する。
+    #
+    # @param self
+    # @param comp 登録解除対象RTコンポーネント
+    #
+    # @else
+    #
+    # @endif
+
+    def cleanupComponent(self, comp):
+        self._rtcout.RTC_TRACE("Manager.cleanupComponent()")
+        self.unregisterComponent(comp)
+
+        return
+
+    ##
+    # @if jp
+    # @brief RTコンポーネントの削除する
+    #
+    # notifyFinalized()によって登録されたRTコンポーネントを削除する。
+    #
+    # @else
+    # @brief This method deletes RT-Components.
+    #
+    # This method deletes RT-Components registered by notifyFinalized().
+    #
+    # @endif
+    #
+    # void cleanupComponents();
+
+    def cleanupComponents(self):
+        self._rtcout.RTC_VERBOSE("Manager.cleanupComponents()")
+        guard = OpenRTM_aist.ScopedLock(self._finalized.mutex)
+        self._rtcout.RTC_VERBOSE("%d components are marked as finalized.",
+                                 len(self._finalized.comps))
+        for _comp in self._finalized.comps:
+            self.deleteComponent(comp=_comp)
+
+        self._finalized.comps = []
+        del guard
+        return
+
+    ##
+    # @if jp
+    # @brief RTコンポーネントの削除する
+    #
+    # 削除するRTコンポーネントを登録する。
+    # 登録されたRTコンポーネントは cleanupComponents() で削除される。
+    #
+    # @param 削除するRTコンポーネント
+    #
+    # @else
+    # @brief This method deletes RT-Components.
+    #
+    # The deleted RT-Component is registered. The registered RT-Components
+    # are deleted by cleanupComponents().
+    #
+    # @param Deleted RT component
+    # @endif
+    #
+    # void notifyFinalized(RTObject_impl* comp);
+
+    def notifyFinalized(self, comp):
+        self._rtcout.RTC_TRACE("Manager.notifyFinalized()")
+        guard = OpenRTM_aist.ScopedLock(self._finalized.mutex)
+        self._finalized.comps.append(comp)
+        del guard
+        return
+
+    ##
+    # @if jp
+    # @brief createComponentの引数を処理する
+    # @ param self
+    # @ param comp_arg(str)
+    # @ param comp_id(Properties object)
+    # @ param comp_conf(Properties object)
+    # @ return True or False
+    # @else
+    #
+    # @endif
+    #
+    # bool procComponentArgs(const char* comp_arg,
+    #                        coil::Properties& comp_id,
+    #                        coil::Properties& comp_conf)
+
+    def procComponentArgs(self, comp_arg, comp_id, comp_conf):
+        id_and_conf = [s.strip() for s in comp_arg.split("?")]
+
+        if len(id_and_conf) != 1 and len(id_and_conf) != 2:
+            self._rtcout.RTC_ERROR("Invalid arguments. Two or more '?'")
+            return False
+
+        prof = OpenRTM_aist.CompParam.prof_list
+        param_num = len(prof)
+
+        if id_and_conf[0].find(":") == -1:
+            id_and_conf[0] = prof[0] + ":::" + id_and_conf[0] + "::"
+
+        id = [s.strip() for s in id_and_conf[0].split(":")]
+
+        if len(id) != param_num:
+            self._rtcout.RTC_ERROR("Invalid RTC id format.")
+            return False
+
+        # prof = ["RTC", "vendor", "category", "implementation_id", "language", "version"]
+
+        if id[0] != prof[0]:
+            self._rtcout.RTC_ERROR("Invalid id type.")
+            return False
+
+        for i in range(1, param_num):
+            comp_id.setProperty(prof[i], id[i])
+            self._rtcout.RTC_TRACE(
+                "RTC basic profile %s: %s", (prof[i], id[i]))
+
+        if len(id_and_conf) == 2:
+            conf = [s.strip() for s in id_and_conf[1].split("&")]
+            for c in conf:
+                keyval = [s.strip() for s in c.split("=")]
+                if len(keyval) > 1:
+                    comp_conf.setProperty(keyval[0], keyval[1])
+                    self._rtcout.RTC_TRACE(
+                        "RTC property %s: %s", (keyval[0], keyval[1]))
+
+        return True
+
+    # bool procContextArgs(const char* ec_args,
+    #                      std::string& ec_id,
+    #                      coil::Properties& ec_conf);
+
+    def procContextArgs(self, ec_args, ec_conf):
+        id_and_conf = [s.strip() for s in ec_args.split("?")]
+
+        if len(id_and_conf) != 1 and len(id_and_conf) != 2:
+            self._rtcout.RTC_ERROR("Invalid arguments. Two or more '?'")
+            return False, ""
+
+        if (id_and_conf[0] == "") or id_and_conf[0] is None:
+            self._rtcout.RTC_ERROR("Empty ExecutionContext's name")
+            return False, ""
+
+        ec_id = id_and_conf[0]
+
+        if len(id_and_conf) == 2:
+            conf = [s.strip() for s in id_and_conf[1].split("&")]
+            for c in conf:
+                k = [s.strip() for s in c.split("=")]
+                ec_conf.setProperty(k[0], k[1])
+                self._rtcout.RTC_TRACE("EC property %s: %s", (k[0], k[1]))
+
+        return True, ec_id
+
+    ##
+    # @if jp
+    # @brief RTコンポーネントのコンフィギュレーション処理
+    #
+    # RTコンポーネントの型およびインスタンス毎に記載されたプロパティファイルの
+    # 情報を読み込み、コンポーネントに設定する。
+    # また、各コンポーネントの NamingService 登録時の名称を取得し、設定する。
+    #
+    # @param self
+    # @param comp コンフィギュレーション対象RTコンポーネント
+    #
+    # @else
+    #
+    # @endif
+    # void configureComponent(RTObject_impl* comp, const coil::Properties&
+    # prop);
+
+    def configureComponent(self, comp, prop):
+        category = comp.getCategory()
+        type_name = comp.getTypeName()
+        inst_name = comp.getInstanceName()
+
+        type_conf = category + "." + type_name + ".config_file"
+        name_conf = category + "." + inst_name + ".config_file"
+
+        type_prop = OpenRTM_aist.Properties()
+
+        name_prop = OpenRTM_aist.Properties()
+        config_fname = []
+
+        if self._config.getProperty(name_conf) != "":
+            try:
+                conff = open(self._config.getProperty(name_conf))
+                name_prop.load(conff)
+                self._rtcout.RTC_INFO("Component instance conf file: %s loaded.",
+                                      self._config.getProperty(name_conf))
+                self._rtcout.RTC_DEBUG(name_prop)
+                config_fname.append(self._config.getProperty(name_conf))
+            except BaseException:
+                print("Not found. : %s" % self._config.getProperty(name_conf))
+                self._rtcout.RTC_ERROR(OpenRTM_aist.Logger.print_exception())
+            else:
+                name_prop.load(conff)
+                conff.close()
+
+        if self._config.findNode(category + "." + inst_name):
+            temp_ = OpenRTM_aist.Properties(
+                prop=self._config.getNode(
+                    category + "." + inst_name))
+            keys_ = temp_.propertyNames()
+            if not (len(keys_) == 1 and keys_[-1] == "config_file"):
+                name_prop.mergeProperties(
+                    self._config.getNode(
+                        category + "." + inst_name))
+                self._rtcout.RTC_INFO(
+                    "Component name conf exists in rtc.conf. Merged.")
+                self._rtcout.RTC_DEBUG(name_prop)
+                if self._config.findNode("config_file"):
+                    config_fname.append(
+                        self._config.getProperty("config_file"))
+
+        if self._config.getProperty(type_conf) != "":
+            try:
+                conff = open(self._config.getProperty(type_conf))
+                type_prop.load(conff)
+                self._rtcout.RTC_INFO("Component type conf file: %s loaded.",
+                                      self._config.getProperty(type_conf))
+                self._rtcout.RTC_DEBUG(type_prop)
+                config_fname.append(self._config.getProperty(type_conf))
+            except BaseException:
+                print("Not found. : %s" % self._config.getProperty(type_conf))
+                self._rtcout.RTC_ERROR(OpenRTM_aist.Logger.print_exception())
+            else:
+                type_prop.load(conff)
+                conff.close()
+
+        if self._config.findNode(category + "." + type_name):
+            temp_ = OpenRTM_aist.Properties(
+                prop=self._config.getNode(
+                    category + "." + type_name))
+            keys_ = temp_.propertyNames()
+            if not (len(keys_) == 1 and keys_[-1] == "config_file"):
+                type_prop.mergeProperties(
+                    self._config.getNode(
+                        category + "." + type_name))
+                self._rtcout.RTC_INFO(
+                    "Component type conf exists in rtc.conf. Merged.")
+                self._rtcout.RTC_DEBUG(type_prop)
+                if self._config.findNode("config_file"):
+                    config_fname.append(
+                        self._config.getProperty("config_file"))
+
+        comp.setProperties(prop)
+        type_prop.mergeProperties(name_prop)
+        type_prop.setProperty(
+            "config_file", OpenRTM_aist.flatten(
+                OpenRTM_aist.unique_sv(config_fname)))
+        comp.setProperties(type_prop)
+
+        comp_prop = OpenRTM_aist.Properties(prop=comp.getProperties())
+
+        naming_formats = self._config.getProperty("naming.formats")
+        if comp_prop.findNode("naming.formats"):
+            naming_formats = comp_prop.getProperty("naming.formats")
+        naming_formats = OpenRTM_aist.flatten(
+            OpenRTM_aist.unique_sv(
+                OpenRTM_aist.split(
+                    naming_formats, ",")))
+
+        naming_names = self.formatString(naming_formats, comp.getProperties())
+        comp.getProperties().setProperty("naming.formats", naming_formats)
+        comp.getProperties().setProperty("naming.names", naming_names)
+        return
+
+    ##
+    # @if jp
+    # @brief プロパティ情報のマージ
+    #
+    # 指定されたファイル内に設定されているプロパティ情報をロードし、
+    # 既存の設定済みプロパティとマージする。
+    #
+    # @param self
+    # @param prop マージ対象プロパティ
+    # @param file_name プロパティ情報が記述されているファイル名
+    #
+    # @return マージ処理実行結果(マージ成功:true、マージ失敗:false)
+    #
+    # @else
+    #
+    # @endif
+
+    def mergeProperty(self, prop, file_name):
+        if file_name == "":
+            self._rtcout.RTC_ERROR("Invalid configuration file name.")
+            return False
+
+        if file_name[0] != '\0':
+
+            try:
+                conff = open(file_name)
+            except BaseException:
+                print("Not found. : %s" % file_name)
+                self._rtcout.RTC_ERROR(OpenRTM_aist.Logger.print_exception())
+            else:
+                prop.load(conff)
+                conff.close()
+                return True
+
+        return False
+
+    ##
+    # @if jp
+    # @brief NamingServer に登録する際の登録情報を組み立てる
+    #
+    # 指定された書式とプロパティ情報を基に NameServer に登録する際の情報を
+    # 組み立てる。
+    # 各書式指定用文字の意味は以下のとおり
+    # - % : コンテキストの区切り
+    # - n : インスタンス名称
+    # - t : 型名
+    # - m : 型名
+    # - v : バージョン
+    # - V : ベンダー
+    # - c : カテゴリ
+    # - h : ホスト名
+    # - M : マネージャ名
+    # - p : プロセスID
+    #
+    # @param self
+    # @param naming_format NamingService 登録情報書式指定
+    # @param prop 使用するプロパティ情報
+    #
+    # @return 指定書式変換結果
+    #
+    # @else
+    #
+    # @endif
+
+    def formatString(self, naming_format, prop):
+        name_ = naming_format
+        str_ = ""
+        count = 0
+        len_ = len(name_)
+        it = iter(name_)
+
+        try:
+            while True:
+                if sys.version_info[0] == 2:
+                    n = it.next()
+                else:
+                    n = it.__next__()
+                if n == '%':
+                    count += 1
+                    if not (count % 2):
+                        str_ += n
+                elif n == '$':
+                    count = 0
+                    if sys.version_info[0] == 2:
+                        n = it.next()
+                    else:
+                        n = it.__next__()
+                    if n == '{' or n == '(':
+                        n = it.next()
+                        env = ""
+                        while True:
+                            if n == '}' or n == ')':
+                                break
+                            env += n
+                            if sys.version_info[0] == 2:
+                                n = it.next()
+                            else:
+                                n = it.__next__()
+                        envval = os.getenv(env)
+                        if envval:
+                            str_ += envval
+                    else:
+                        str_ += n
+                else:
+                    if count > 0 and (count % 2):
+                        count = 0
+                        if n == "n":
+                            str_ += prop.getProperty("instance_name")
+                        elif n == "t":
+                            str_ += prop.getProperty("type_name")
+                        elif n == "m":
+                            str_ += prop.getProperty("type_name")
+                        elif n == "v":
+                            str_ += prop.getProperty("version")
+                        elif n == "V":
+                            str_ += prop.getProperty("vendor")
+                        elif n == "c":
+                            str_ += prop.getProperty("category")
+                        elif n == "h":
+                            str_ += self._config.getProperty("os.hostname")
+                        elif n == "M":
+                            str_ += self._config.getProperty("manager.name")
+                        elif n == "p":
+                            str_ += str(self._config.getProperty("manager.pid"))
+                        else:
+                            str_ += n
+                    else:
+                        count = 0
+                        str_ += n
+        except BaseException:
+            # Caught StopIteration exception.
+            return str_
+
+        # return str_
+
+    ##
+    # @if jp
+    # @brief ログバッファの取得
+    #
+    # マネージャに設定したログバッファを取得する。
+    #
+    # @param self
+    #
+    # @return マネージャに設定したログバッファ
+    #
+    # @else
+    #
+    # @endif
+    def getLogbuf(self, name="manager"):
+        if not OpenRTM_aist.toBool(self._config.getProperty(
+                "logger.enable"), "YES", "NO", True):
+            return OpenRTM_aist.LogStream().getLogger(name)
+
+        if self._rtcout is None:
+            self._rtcout = OpenRTM_aist.LogStream()
+            self._rtcout.setLogLevel(
+                self._config.getProperty("logger.log_level"))
+            return self._rtcout.getLogger(name)
+        else:
+            return self._rtcout.getLogger(name)
+
+    ##
+    # @if jp
+    # @brief マネージャコンフィギュレーションの取得
+    #
+    # マネージャに設定したコンフィギュレーションを取得する。
+    #
+    # @param self
+    #
+    # @return マネージャのコンフィギュレーション
+    #
+    # @else
+    #
+    # @endif
+
+    def getConfig(self):
+        return self._config
+
+    ##
+    # @if jp
+    # @brief コンポーネントファイル(.py)から
+    #
+    # マネージャに設定したコンフィギュレーションを取得する。
+    #
+    # @param self
+    #
+    # @return マネージャのコンフィギュレーション
+    #
+    # @else
+    #
+    # @endif
+
+    def __try_direct_load(self, file_name):
+        try:
+            # pathChanged=False
+            splitted_name = os.path.split(file_name)
+            save_path = sys.path[:]
+            sys.path.append(splitted_name[0])
+            import_name = splitted_name[-1].split(".py")[0]
+            mo = __import__(import_name)
+            sys.path = save_path
+            _spec = getattr(mo, import_name.lower() + "_spec", None)
+            _class = getattr(mo, import_name, None)
+            if _spec and _class:
+                prof = OpenRTM_aist.Properties(defaults_str=_spec)
+                self.registerFactory(prof,
+                                     _class,
+                                     OpenRTM_aist.Delete)
+        except BaseException:
+            self._rtcout.RTC_ERROR("Module load error: %s", file_name)
+            self._rtcout.RTC_ERROR(OpenRTM_aist.Logger.print_exception())
+
+    ##
+    # @if jp
+    #
+    # @brief 指定したRTコンポーネントの保持するポートをNamingServiceにバインドする
+    # ポートのpublish_topicというプロパティでトピック名を設定し、トピック名のコンテキストの下に登録
+    #
+    #
+    # @param self
+    # @param comp RTコンポーネント
+    #
+    # @else
+    #
+    # @brief
+    # @param self
+    # @param comp
+    #
+    # @endif
+    # void publishPorts(RTObject_impl* comp)
+
+    def publishPorts(self, comp):
+        ports = comp.get_ports()
+        for p in ports:
+            prof = p.get_port_profile()
+            prop = OpenRTM_aist.Properties()
+            OpenRTM_aist.NVUtil.copyToProperties(prop, prof.properties)
+
+            if (prop.hasKey("publish_topic") is None or not str(prop.getProperty("publish_topic"))) and (prop.hasKey("subscribe_topic") is None or not str(
+                    prop.getProperty("subscribe_topic"))) and (prop.hasKey("rendezvous_point") is None or not str(prop.getProperty("rendezvous_point"))):
+                continue
+
+            if prop.getProperty("port.port_type") == "DataOutPort":
+                name = "dataports.port_cxt/"
+                name += str(prop.getProperty("publish_topic")) + ".topic_cxt/"
+                name += prof.name
+                name += ".outport"
+            elif prop.getProperty("port.port_type") == "DataInPort":
+                name = "dataports.port_cxt/"
+                name += str(prop.getProperty("subscribe_topic")) + \
+                    ".topic_cxt/"
+                name += prof.name
+                name += ".inport"
+            elif prop.getProperty("port.port_type") == "CorbaPort":
+                name = "svcports.port_cxt/"
+                name += str(prop.getProperty("rendezvous_point")) + \
+                    ".topic_cxt/"
+                name += prof.name
+                name += ".svc"
+
+            else:
+
+                self._rtcout.RTC_WARN(
+                    "Unknown port type: %s" % str(
+                        prop.getProperty("port.port_type")))
+                continue
+
+            port = self._poa.reference_to_servant(p)
+
+            self._namingManager.bindPortObject(name, port)
+
+    ##
+    # @if jp
+    #
+    # @brief 指定したRTコンポーネントの保持するポートを同じトピック名以下の接続可能なポートと接続
+    #
+    #
+    # @param self
+    # @param comp RTコンポーネント
+    #
+    # @else
+    #
+    # @brief
+    # @param self
+    # @param comp
+    #
+    # @endif
+    # void subscribePorts(RTObject_impl* comp)
+    def subscribePorts(self, comp):
+        ports = comp.get_ports()
+
+        for p in ports:
+
+            prof = p.get_port_profile()
+            prop = OpenRTM_aist.Properties()
+            OpenRTM_aist.NVUtil.copyToProperties(prop, prof.properties)
+
+            if (prop.hasKey("publish_topic") is None or not str(prop.getProperty("publish_topic"))) and (prop.hasKey("subscribe_topic") is None or not str(
+                    prop.getProperty("subscribe_topic"))) and (prop.hasKey("rendezvous_point") is None or not str(prop.getProperty("rendezvous_point"))):
+                continue
+
+            if prop.getProperty("port.port_type") == "DataOutPort":
+                name = "dataports.port_cxt/"
+                name += str(prop.getProperty("publish_topic")) + ".topic_cxt"
+
+                nsports = self.getPortsOnNameServers(name, "inport")
+
+                self.connectDataPorts(p, nsports)
+
+            elif prop.getProperty("port.port_type") == "DataInPort":
+                name = "dataports.port_cxt/"
+                name += str(prop.getProperty("subscribe_topic")) + ".topic_cxt"
+                nsports = self.getPortsOnNameServers(name, "outport")
+                self.connectDataPorts(p, nsports)
+
+            elif prop.getProperty("port.port_type") == "CorbaPort":
+                name = "svcports.port_cxt/"
+                name += str(prop.getProperty("rendezvous_point")) + \
+                    ".topic_cxt"
+                nsports = self.getPortsOnNameServers(name, "svc")
+                self.connectServicePorts(p, nsports)
+
+    ##
+    # @if jp
+    #
+    # @brief 与えられたパス以下の指定されたkindのポートを取得する
+    #
+    # @param self
+    # @param nsname パス
+    # @param kind kind
+    # @return ポートのオブジェクトリファレンスのリスト
+    #
+    # @else
+    #
+    # @brief
+    # @param self
+    # @param nsname
+    # @param kind
+    # @return
+    #
+    # @endif
+    # PortServiceList_var getPortsOnNameServers(std::string nsname,std::string
+    # kind)
+    def getPortsOnNameServers(self, nsname, kind):
+        ports = []
+        ns = self._namingManager.getNameServices()
+        for n in ns:
+            noc = n.ns
+            if noc is None:
+                continue
+            cns = noc._cosnaming
+            if cns is None:
+                continue
+
+            bl = cns.listByKind(nsname, kind)
+
+            for b in bl:
+                if b.binding_type != CosNaming.nobject:
+                    continue
+                tmp = b.binding_name[0].id + "." + b.binding_name[0].kind
+
+                nspath = "/" + nsname + "/" + tmp
+                nspath.replace("\\", "")
+
+                obj = cns.resolveStr(nspath)
+                portsvc = obj
+
+                if CORBA.is_nil(portsvc):
+                    continue
+
+                try:
+                    portsvc.get_port_profile()
+
+                except BaseException:
+                    continue
+                ports.append(portsvc)
+
+        return ports
+
+    ##
+    # @if jp
+    # @brief 指定したデータポートを指定したリスト内のデータポート全てと接続する
+    # @param self
+    # @param port 対象のデータポート
+    # @param target_ports 接続対象のデータポートのリスト
+    # @else
+    #
+    # @brief
+    # @param self
+    # @param port
+    # @param target_ports
+    # @endif
+    # void connectDataPorts(PortService_ptr port,PortServiceList_var&
+    # target_ports)
+    def connectDataPorts(self, port, target_ports):
+        for p in target_ports:
+            if port._is_equivalent(p):
+                continue
+            con_name = ""
+            p0 = port.get_port_profile()
+            p1 = p.get_port_profile()
+            con_name += p0.name
+            con_name += ":"
+            con_name += p1.name
+            prop = OpenRTM_aist.Properties()
+            if RTC.RTC_OK != OpenRTM_aist.CORBA_RTCUtil.connect(
+                    con_name, prop, port, p):
+                self._rtcout.RTC_ERROR("Connection error in topic connection.")
+
+    ##
+    # @if jp
+    # @brief 指定したサービスポートを指定したリスト内のサービスポート全てと接続する
+    # @param self
+    # @param port 対象のサービスポート
+    # @param target_ports 接続対象のサービスポートのリスト
+    # @else
+    #
+    # @brief
+    # @param self
+    # @param port
+    # @param target_ports
+    # @endif
+    # void connectServicePorts(PortService_ptr port,PortServiceList_var&
+    # target_ports)
+
+    def connectServicePorts(self, port, target_ports):
+        for p in target_ports:
+            if port._is_equivalent(p):
+                continue
+            con_name = ""
+            p0 = port.get_port_profile()
+            p1 = p.get_port_profile()
+            con_name += p0.name
+            con_name += ":"
+            con_name += p1.name
+            prop = OpenRTM_aist.Properties()
+            if RTC.RTC_OK != OpenRTM_aist.CORBA_RTCUtil.connect(
+                    con_name, prop, port, p):
+                self._rtcout.RTC_ERROR("Connection error in topic connection.")
+
+    ##
+    # @if jp
+    # @brief 起動時にrtc.confで指定したポートを接続する
+    # 例:
+    # manager.components.preconnect: RTC0.port0?port=RTC0.port1&interface_type=corba_cdr&dataflow_type=pull&~,~
+    # @param self
+    # @else
+    #
+    # @brief
+    # @param self
+    # @endif
+    # void initPreConnection()
+
+    def initPreConnection(self):
+        self._rtcout.RTC_TRACE("Connection pre-creation: %s" %
+                               str(self._config.getProperty("manager.components.preconnect")))
+        connectors = str(self._config.getProperty(
+            "manager.components.preconnect")).split(",")
+
+        for c in connectors:
+            c = c.strip()
+            if not c:
+                continue
+            port0_str = c.split("?")[0]
+            param = OpenRTM_aist.urlparam2map(c)
+
+            ports = []
+            configs = {}
+
+            for k, p in param.items():
+                if k == "port":
+                    ports.append(p)
+                    continue
+                tmp = k.replace("port", "")
+                v = 0
+                # パラメータ名の末尾が数字の場合(port0, port1...)
+                ret, v = OpenRTM_aist.stringTo(v, tmp)
+                if ret and k.find("port") != -1:
+                    ports.append(p)
+                    continue
+                configs[k] = p
+
+            # if len(ports) == 0:
+            #  self._rtcout.RTC_ERROR("Invalid format for pre-connection.")
+            #  self._rtcout.RTC_ERROR("Format must be Comp0.port0?port=Comp1.port1")
+            #  continue
+
+            if not ("dataflow_type" in configs.keys()):
+                configs["dataflow_type"] = "push"
+            if not ("interface_type" in configs.keys()):
+                configs["interface_type"] = "corba_cdr"
+
+            tmp = port0_str.split(".")
+            tmp.pop()
+            comp0_name = OpenRTM_aist.flatten(tmp, ".")
+
+            port0_name = port0_str
+
+            if comp0_name.find("://") == -1:
+                comp0 = self.getComponent(comp0_name)
+                if comp0 is None:
+                    self._rtcout.RTC_ERROR("%s not found." % comp0_name)
+                    continue
+                comp0_ref = comp0.getObjRef()
+            else:
+                rtcs = self._namingManager.string_to_component(comp0_name)
+
+                if not rtcs:
+                    self._rtcout.RTC_ERROR("%s not found." % comp0_name)
+                    continue
+                comp0_ref = rtcs[0]
+                port0_name = port0_str.split("/")[-1]
+
+            port0_var = OpenRTM_aist.CORBA_RTCUtil.get_port_by_name(
+                comp0_ref, port0_name)
+
+            if CORBA.is_nil(port0_var):
+                self._rtcout.RTC_DEBUG("port %s found: " % port0_str)
+                continue
+
+            if not ports:
+                prop = OpenRTM_aist.Properties()
+
+                for k, v in configs.items():
+                    k = k.strip()
+                    v = v.strip()
+                    prop.setProperty("dataport." + k, v)
+
+                if RTC.RTC_OK != OpenRTM_aist.CORBA_RTCUtil.connect(
+                        c, prop, port0_var, RTC.PortService._nil):
+                    self._rtcout.RTC_ERROR("Connection error: %s" % c)
+
+            for port_str in ports:
+
+                tmp = port_str.split(".")
+                tmp.pop()
+                comp_name = OpenRTM_aist.flatten(tmp, ".")
+                port_name = port_str
+
+                if comp_name.find("://") == -1:
+                    comp = self.getComponent(comp_name)
+                    if comp is None:
+                        self._rtcout.RTC_ERROR("%s not found." % comp_name)
+                        continue
+                    comp_ref = comp.getObjRef()
+                else:
+                    rtcs = self._namingManager.string_to_component(comp_name)
+
+                    if not rtcs:
+                        self._rtcout.RTC_ERROR("%s not found." % comp_name)
+                        continue
+                    comp_ref = rtcs[0]
+                    port_name = port_str.split("/")[-1]
+
+                port_var = OpenRTM_aist.CORBA_RTCUtil.get_port_by_name(
+                    comp_ref, port_name)
+
+                if CORBA.is_nil(port_var):
+                    self._rtcout.RTC_DEBUG("port %s found: " % port_str)
+                    continue
+
+                prop = OpenRTM_aist.Properties()
+
+                for k, v in configs.items():
+                    k = k.strip()
+                    v = v.strip()
+                    prop.setProperty("dataport." + k, v)
+
+                if RTC.RTC_OK != OpenRTM_aist.CORBA_RTCUtil.connect(
+                        c, prop, port0_var, port_var):
+                    self._rtcout.RTC_ERROR("Connection error: %s" % c)
+
+    ##
+    # @if jp
+    # @brief 起動時にrtc.confで指定したRTCをアクティベーションする
+    # 例:
+    # manager.components.preactivation: RTC1,RTC2~
+    # @param self
+    # @else
+    #
+    # @brief
+    # @param self
+    # @endif
+    # void initPreActivation()
+    def initPreActivation(self):
+
+        self._rtcout.RTC_TRACE("Components pre-activation: %s" %
+                               str(self._config.getProperty("manager.components.preactivation")))
+        comps = str(self._config.getProperty(
+            "manager.components.preactivation")).split(",")
+        for c in comps:
+            c = c.strip()
+            if c:
+                comp_ref = None
+                if c.find("://") == -1:
+                    comp = self.getComponent(c)
+                    if comp is None:
+                        self._rtcout.RTC_ERROR("%s not found." % c)
+                        continue
+                    comp_ref = comp.getObjRef()
+                else:
+                    rtcs = self._namingManager.string_to_component(c)
+                    if not rtcs:
+                        self._rtcout.RTC_ERROR("%s not found." % c)
+                        continue
+                    comp_ref = rtcs[0]
+                ret = OpenRTM_aist.CORBA_RTCUtil.activate(comp_ref)
+                if ret != RTC.RTC_OK:
+                    self._rtcout.RTC_ERROR("%s activation failed." % c)
+                else:
+                    self._rtcout.RTC_INFO("%s activated." % c)
+
+    ##
+    # @if jp
+    # @brief 起動時にrtc.confで指定したRTCを生成する
+    # 例:
+    # manager.components.precreate RTC1,RTC2~
+    # @param self
+    # @else
+    #
+    # @brief
+    # @param self
+    # @endif
+    # void initPreCreation()
+
+    def initPreCreation(self):
+        comps = [s.strip() for s in self._config.getProperty(
+            "manager.components.precreate").split(",")]
+        for comp in comps:
+            if comp is None or comp == "":
+                continue
+
+            self.createComponent(comp)
+
+    ##
+    # @if jp
+    # @brief
+    # @else
+    #
+    # @brief
+    # @param self
+    # @endif
+    # void invokeInitProc()
+
+    def invokeInitProc(self):
+        if self._initProc:
+            self._initProc(self)
+
+    ##
+    # @if jp
+    # @brief ManagerServantを取得する
+    #
+    #
+    # @param self
+    # @return ManagerServant
+    # @else
+    #
+    # @brief
+    # @param self
+    # @return
+    # @endif
+    # ManagerServant* getManagerServant()
+    def getManagerServant(self):
+        self._rtcout.RTC_TRACE("Manager.getManagerServant()")
+        return self._mgrservant
+
+    ##
+    # @if jp
+    # @brief NamingManagerを取得する
+    #
+    #
+    # @param self
+    # @return NamingManager
+    # @else
+    #
+    # @brief
+    # @param self
+    # @return
+    # @endif
+    # NamingManager* getNaming()
+
+    def getNaming(self):
+        self._rtcout.RTC_TRACE("Manager.getNaming()")
+        return self._namingManager
+
+
+    ##
+    # @if jp
+    # @brief 周期実行タスクの登録
+    #
+    #
+    # 周期的に実行する関数や関数オブジェクトを Manager のタイマーに登録する。
+    # removePeriodTask() が実行されるまで処理が継続される。本関数に登録する処理
+    # の中で sleep などの長時間ブロッキングは推奨されない。また周期タスクの中で
+    # 本関数を呼び出してはならない。
+    #
+    # @param self
+    # @param fn 周期実行する関数または関数オブジェクト
+    # @param period 周期実行の実行間隔
+    # @return id removeTask() で実行解除するための ID
+    # @return PeriodicFunction
+    # @else
+    #
+    # @brief Add a task to the Manager timer.
+    #
+    # This operation add a function or functional object to Manger's
+    # timer. It run until removeTask(). DO NOT block (Ex. sleep)
+    # in the registerd function.
+    #
+    # @param self
+    # @param fn The Function run periodically.
+    # @param period Period of fn execution.
+    # @return id ID for removetask().
+    # @return PeriodicFunction
+    # @endif
+    #
+    def addTask(self, fn, period):
+        #self._rtcout.RTC_TRACE("Manager::addTask()")
+        return self._scheduler.emplace(fn, period)
+
+    ##
+    # @if jp
+    # @brief Manger のメインスレッドで処理を実行
+    #
+    # Manger のメインスレッドで指定された処理を実行する。長時間のブロッ
+    # キングを行う関数の登録は推奨しない。
+    #
+    # @param self
+    # @param fn 関数または関数オブジェクト
+    # @param delay 起動するまでの遅延時間
+    # @return DelayedFunction
+    #
+    # @else
+    #
+    # @brief Run a function on the Manager main thread.
+    #
+    # The specified function run on the Manager main thread.  DO NOT block
+    # the thread in the function.
+    #
+    # @param self
+    # @param fn The Function run on the Manager main thread.
+    # @param delay The delay time for the function execution.
+    # @return DelayedFunction
+    #
+    # @endif
+    #
+    def invoke(self, fn, delay):
+        #self._rtcout.RTC_TRACE("Manager::invoke()")
+        return self._invoker.emplace(fn, delay)
+
+    ##
+    # @if jp
+    # @brief 周期実行タスクの削除
+    #
+    # タイマーに登録されている周期タスクを削除する。
+    #
+    # @param self
+    # @param id 削除対象のタスクを示す ID
+    #
+    # @else
+    #
+    # @brief Remove the task from the Manager timer.
+    #
+    # This operation remove the specify function.
+    #
+    # @param self
+    # @param id Task ID
+    #
+    # @endif
+    #
+    def removeTask(self, task):
+        task.stop()
+
+    ##
+    # @if jp
+    # @brief リストに実行コンテキストのインスタンスを追加
+    #
+    # Managerが管理するRTCが生成したECはリストに追加する必要がある
+    #
+    # @param self
+    # @param ec 実行コンテキスト
+    # @return 既に追加済みの場合はFalseを返す
+    #
+    # @else
+    #
+    # @brief 
+    #
+    #
+    # @param self
+    # @param ec Execution context
+    # @return
+    #
+    # @endif
+    #
+    def addExecutionContext(self, ec):
+        if ec in self._eclist:
+            return False
+        self._eclist.append(ec)
+        return True
+
+    ##
+    # @if jp
+    # @brief リストから実行コンテキストを削除
+    #
+    #
+    # @param self
+    # @param ec 実行コンテキスト
+    # @return 指定のECがリストに存在しない場合はFalseを返す
+    #
+    # @else
+    #
+    # @brief 
+    #
+    #
+    # @param self
+    # @param ec Execution context
+    # @return 
+    #
+    # @endif
+    #
+    def removeExecutionContext(self, ec):
+        if ec in self._eclist:
+            self._eclist.remove(ec)
+            return True
+        return False
+
+    ##
+    # @if jp
+    # @brief 実行コンテキストをリストを取得する
+    #
+    #
+    # @param self
+    # @return 実行コンテキストのリスト
+    #
+    # @else
+    #
+    # @brief 
+    #
+    #
+    # @param self
+    # @return 
+    #
+    # @endif
+    #
+    def createdExecutionContexts(self):
+        return self._eclist
+
+
+    # ============================================================
+    # コンポーネントマネージャ
+    # ============================================================
+    ##
+    # @if jp
+    # @class InstanceName
+    # @brief ObjectManager 検索用ファンクタ
+    #
+    # @else
+    #
+    # @endif
+    class InstanceName:
+        """
+        """
+
+        ##
+        # @if jp
+        # @brief コンストラクタ
+        #
+        # コンストラクタ
+        #
+        # @param self
+        # @param name 検索対象コンポーネント名称(デフォルト値:None)
+        # @param factory 検索対象ファクトリ名称(デフォルト値:None)
+        #
+        # @else
+        #
+        # @endif
+        def __init__(self, name=None, factory=None, prop=None):
+            if prop:
+                self._name = prop.getProperty("instance_name")
+            elif factory:
+                self._name = factory.getInstanceName()
+            elif name:
+                self._name = name
+            else:
+                self._name = ""
+
+        def __call__(self, comp):
+            if not self._name:
+                return False
+            return self._name == comp.getInstanceName()
+
+    # ============================================================
+    # コンポーネントファクトリ
+    # ============================================================
+    ##
+    # @if jp
+    # @class FactoryPredicate
+    # @brief コンポーネントファクトリ検索用ファンクタ
+    #
+    # @else
+    #
+    # @endif
+    class FactoryPredicate:
+
+        def __init__(self, name=None, prop=None, factory=None):
+            if name:
+                self._vendor = ""
+                self._category = ""
+                self._impleid = name
+                self._version = ""
+            elif prop:
+                self._vendor = prop.getProperty("vendor")
+                self._category = prop.getProperty("category")
+                self._impleid = prop.getProperty("implementation_id")
+                self._version = prop.getProperty("version")
+            elif factory:
+                self._vendor = factory.profile().getProperty("vendor")
+                self._category = factory.profile().getProperty("category")
+                self._impleid = factory.profile().getProperty("implementation_id")
+                self._version = factory.profile().getProperty("version")
+
+        def __call__(self, factory):
+            if self._impleid == "":
+                return False
+
+            _prop = OpenRTM_aist.Properties(prop=factory.profile())
+
+            if self._impleid != _prop.getProperty("implementation_id"):
+                return False
+
+            if self._vendor != "" and self._vendor != _prop.getProperty(
+                    "vendor"):
+                return False
+
+            if self._category != "" and self._category != _prop.getProperty(
+                    "category"):
+                return False
+
+            if self._version != "" and self._version != _prop.getProperty(
+                    "version"):
+                return False
+
+            return True
+
+    # ============================================================
+    # ExecutionContextファクトリ
+    # ============================================================
+    ##
+    # @if jp
+    # @class ECFactoryPredicate
+    # @brief ExecutionContextファクトリ検索用ファンクタ
+    #
+    # @else
+    #
+    # @endif
+    class ECFactoryPredicate:
+
+        def __init__(self, name=None, factory=None):
+            if name:
+                self._name = name
+            elif factory:
+                self._name = factory.name()
+
+        def __call__(self, factory):
+            return self._name == factory.name()
+
+    # ============================================================
+    # Module Fanctor
+    # ============================================================
+    ##
+    # @if jp
+    # @class ModulePredicate
+    # @brief Module検索用ファンクタ
+    #
+    # @else
+    #
+    # @endif
+    class ModulePredicate:
+
+            # ModulePredicate(coil::Properties& prop)
+        def __init__(self, prop):
+            self._prop = prop
+            return
+
+        # bool operator()(coil::Properties& prop)
+        def __call__(self, prop):
+
+            if self._prop.getProperty(
+                    "implementation_id") != prop.getProperty("implementation_id"):
+                return False
+
+            if self._prop.getProperty("vendor") and \
+                    self._prop.getProperty("vendor") != prop.getProperty("vendor"):
+                return False
+
+            if self._prop.getProperty("category") and \
+                    self._prop.getProperty("category") != prop.getProperty("category"):
+                return False
+
+            if self._prop.getProperty("version") and \
+                    self._prop.getProperty("version") != prop.getProperty("version"):
+                return False
+
+            return True
+
+
+
+
+    class Finalized:
+        def __init__(self):
+            self.mutex = threading.RLock()
+            self.comps = []
diff --git a/OpenRTM_aist/ManagerActionListener.py b/OpenRTM_aist/ManagerActionListener.py
index 6d2a4ee0..7c4ddbdb 100644
--- a/OpenRTM_aist/ManagerActionListener.py
+++ b/OpenRTM_aist/ManagerActionListener.py
@@ -1,5 +1,5 @@
 #!/usr/bin/env python
-# -*- coding: euc-jp -*-
+# -*- coding: utf-8 -*-
 
 ##
 # @file ManagerActionListener.py
@@ -19,172 +19,419 @@
 
 import OpenRTM_aist
 
+
 ##
 # @if jp
-# @class ManagerActionListenerHolder 饹
+# @class ManagerActionListener クラス
+#
+# - マネージャShutdownの直前: void onPreShutdown()
+# - マネージャShutdownの直後: void onPostShutdown()
+# - マネージャの再初期化直前: void onPreReinit()
+# - マネージャの再初期化直後: void onPostReinit()
+# @else
+# @class ManagerActionListener class
+# @endif
+class ManagerActionListener:
+    ##
+    # @if jp
+    # @brief preShutdown callback function
+    # @param self
+    # @else
+    # @brief preShutdown callback function
+    # @param self
+    # @endif
+    # virtual void preShutdown();
+    def preShutdown(self):
+        # type: () -> None
+        pass
+    ##
+    # @if jp
+    # @brief postShutdown callback function
+    # @param self
+    # @else
+    # @brief postShutdown callback function
+    # @param self
+    # @endif
+    # virtual void postShutdown();
+
+    def postShutdown(self):
+        # type: () -> None
+        pass
+    ##
+    # @if jp
+    # @brief preReinit コールバック関数
+    # @param self
+    # @else
+    # @brief preReinit callback function
+    # @param self
+    # @endif
+    # virtual void preReinit();
+
+    def preReinit(self):
+        # type: () -> None
+        pass
+    ##
+    # @if jp
+    # @brief postReinit コールバック関数
+    # @param self
+    # @else
+    # @brief postReinit callback function
+    # @param self
+    # @endif
+    # virtual void postReinit();
+
+    def postReinit(self):
+        # type: () -> None
+        pass
+
+
+##
+# @if jp
+# @class ManagerActionListenerHolder クラス
 # @else
 # @class ManagerActionListenerHolder class
 # @endif
 class ManagerActionListenerHolder(OpenRTM_aist.ListenerHolder):
-  """
-  """
-  
-  def __init__(self):
-    OpenRTM_aist.ListenerHolder.__init__(self)
-    return
-
-  def __del__(self):
-    return
-
-
-  ##
-  # @if jp
-  # @brief preShutdown Хåؿ
-  # TODO: Documentation
-  # @else
-  # @brief preShutdown callback function
-  # TODO: Documentation
-  # @endif
-  # virtual void preShutdown();
-  def preShutdown(self):
-    self.LISTENERHOLDER_CALLBACK("preShutdown")
-    return
-
-
-  ##
-  # @if jp
-  # @brief postShutdown Хåؿ
-  # TODO: Documentation
-  # @else
-  # @brief postShutdown callback function
-  # TODO: Documentation
-  # @endif
-  # virtual void postShutdown();
-  def postShutdown(self):
-    self.LISTENERHOLDER_CALLBACK("postShutdown")
-    return
-
-
-  ##
-  # @if jp
-  # @brief preReinit Хåؿ
-  # TODO: Documentation
-  # @else
-  # @brief preReinit callback function
-  # TODO: Documentation
-  # @endif
-  # virtual void preReinit();
-  def preReinit(self):
-    self.LISTENERHOLDER_CALLBACK("preReinit")
-    return
-
-
-  ##
-  # @if jp
-  # @brief postReinit Хåؿ
-  # TODO: Documentation
-  # @else
-  # @brief postReinit callback function
-  # TODO: Documentation
-  # @endif
-  # virtual void postReinit();
-  def postReinit(self):
-    self.LISTENERHOLDER_CALLBACK("postReinit")
-    return
-  
-  
+    """
+    """
+
+    def __init__(self):
+        OpenRTM_aist.ListenerHolder.__init__(self)
+        return
+
+    def __del__(self):
+        return
+
+    ##
+    # @if jp
+    # @brief preShutdown コールバック関数
+    # TODO: Documentation
+    # @else
+    # @brief preShutdown callback function
+    # TODO: Documentation
+    # @endif
+    # virtual void preShutdown();
+
+    def preShutdown(self):
+        self.LISTENERHOLDER_CALLBACK("preShutdown")
+        return
+
+    ##
+    # @if jp
+    # @brief postShutdown コールバック関数
+    # TODO: Documentation
+    # @else
+    # @brief postShutdown callback function
+    # TODO: Documentation
+    # @endif
+    # virtual void postShutdown();
+
+    def postShutdown(self):
+        self.LISTENERHOLDER_CALLBACK("postShutdown")
+        return
+
+    ##
+    # @if jp
+    # @brief preReinit コールバック関数
+    # TODO: Documentation
+    # @else
+    # @brief preReinit callback function
+    # TODO: Documentation
+    # @endif
+    # virtual void preReinit();
+
+    def preReinit(self):
+        self.LISTENERHOLDER_CALLBACK("preReinit")
+        return
+
+    ##
+    # @if jp
+    # @brief postReinit コールバック関数
+    # TODO: Documentation
+    # @else
+    # @brief postReinit callback function
+    # TODO: Documentation
+    # @endif
+    # virtual void postReinit();
+
+    def postReinit(self):
+        self.LISTENERHOLDER_CALLBACK("postReinit")
+        return
+
+
 ##
 # @if jp
-# @class ModuleActionListenerHolder 饹
-# @brief ModuleActionListenerHolder 饹
+# @class ModuleActionListener クラス
+# @else
+# @class ModuleActionListener class
+# @endif
+class ModuleActionListener:
+    ##
+    # @if jp
+    # @brief preLoad コールバック関数
+    # @param self
+    # @param modname
+    # @param funcname
+    # @return
+    # @else
+    # @brief preLoad callback function
+    # @param self
+    # @param modname
+    # @param funcname
+    # @return
+    # @endif
+    # virtual void preLoad(std::string& modname, std::string& funcname);
+    def preLoad(self, modname, funcname):
+        # type: (str, str) -> str, str
+        return modname, funcname
+    ##
+    # @if jp
+    # @brief postLoad コールバック関数
+    # @param self
+    # @param modname
+    # @param funcname
+    # @return
+    # @else
+    # @brief postLoad callback function
+    # @param self
+    # @param modname
+    # @param funcname
+    # @return
+    # @endif
+    # virtual void postLoad(std::string& modname, std::string& funcname);
+
+    def postLoad(self, modname, funcname):
+        # type: (str, str) -> str, str
+        return modname, funcname
+    ##
+    # @if jp
+    # @brief preUnload コールバック関数
+    # @param self
+    # @param modname
+    # @return
+    # @else
+    # @brief preUnload callback function
+    # @param self
+    # @param modname
+    # @return
+    # @endif
+    # virtual void preUnload(std::string& modname));
+
+    def preUnload(self, modname):
+        # type: (str) -> str
+        return modname
+    ##
+    # @if jp
+    # @brief postUnload コールバック関数
+    # @param self
+    # @else
+    # @brief postUnload callback function
+    # @param self
+    # @endif
+    # virtual void postUnload(std::string& modname));
+
+    def postUnload(self, modname):
+        # type: (str) -> str
+        return modname
+
+##
+# @if jp
+# @class ModuleActionListenerHolder クラス
+# @brief ModuleActionListenerHolder クラス
 #
 # @else
 # @class ModuleActionListenerHolder class
 # @brief ModuleActionListenerHolder class
 #
 # @endif
+
+
 class ModuleActionListenerHolder(OpenRTM_aist.ListenerHolder):
-  """
-  """
-
-  def __init__(self):
-    OpenRTM_aist.ListenerHolder.__init__(self)
-    return
-
-
-  ##
-  # @if jp
-  # @brief ǥȥ饯
-  # @else
-  # @brief Destructor
-  # @endif
-  def __del__(self):
-    pass
-    
-
-  ##
-  # @if jp
-  # @brief preLoad Хåؿ
-  # TODO: Documentation
-  # @else
-  # @brief preLoad callback function
-  # TODO: Documentation
-  # @endif
-  # virtual void preLoad(std::string& modname,
-  #                      std::string& funcname);
-  def preLoad(self, modname, funcname):
-    self.LISTENERHOLDER_CALLBACK("preLoad", modname, funcname)
-    return
-
-    
-  ##
-  # @if jp
-  # @brief postLoad Хåؿ
-  # TODO: Documentation
-  # @else
-  # @brief postLoad callback function
-  # TODO: Documentation
-  # @endif
-  # virtual void postLoad(std::string& modname,
-  #                       std::string& funcname);
-  def postLoad(self, modname, funcname):
-    self.LISTENERHOLDER_CALLBACK("postLoad", modname, funcname)
-    return
-    
-
-  ##
-  # @if jp
-  # @brief preUnload Хåؿ
-  # TODO: Documentation
-  # @else
-  # @brief preUnload callback function
-  # TODO: Documentation
-  # @endif
-  # virtual void preUnload(std::string& modname);
-  def preUnload(self, modname):
-    self.LISTENERHOLDER_CALLBACK("preUnload", modname)
-    return
-    
-
-  ##
-  # @if jp
-  # @brief postUnload Хåؿ
-  # TODO: Documentation
-  # @else
-  # @brief postUnload callback function
-  # TODO: Documentation
-  # @endif
-  # virtual void postUnload(std::string& modname);
-  def postUnload(self, modname):
-    self.LISTENERHOLDER_CALLBACK("postUnload", modname)
-    return
-  
-  
+    """
+    """
+
+    def __init__(self):
+        OpenRTM_aist.ListenerHolder.__init__(self)
+        return
+
+    ##
+    # @if jp
+    # @brief デストラクタ
+    # @else
+    # @brief Destructor
+    # @endif
+
+    def __del__(self):
+        pass
+
+    ##
+    # @if jp
+    # @brief preLoad コールバック関数
+    # TODO: Documentation
+    # @else
+    # @brief preLoad callback function
+    # TODO: Documentation
+    # @endif
+    # virtual void preLoad(std::string& modname,
+    #                      std::string& funcname);
+
+    def preLoad(self, modname, funcname):
+        return self.LISTENERHOLDER_CALLBACK("preLoad", modname, funcname)
+
+    ##
+    # @if jp
+    # @brief postLoad コールバック関数
+    # TODO: Documentation
+    # @else
+    # @brief postLoad callback function
+    # TODO: Documentation
+    # @endif
+    # virtual void postLoad(std::string& modname,
+    #                       std::string& funcname);
+
+    def postLoad(self, modname, funcname):
+        return self.LISTENERHOLDER_CALLBACK("postLoad", modname, funcname)
+
+    ##
+    # @if jp
+    # @brief preUnload コールバック関数
+    # TODO: Documentation
+    # @else
+    # @brief preUnload callback function
+    # TODO: Documentation
+    # @endif
+    # virtual void preUnload(std::string& modname);
+
+    def preUnload(self, modname):
+        return self.LISTENERHOLDER_CALLBACK("preUnload", modname)
+
+    ##
+    # @if jp
+    # @brief postUnload コールバック関数
+    # TODO: Documentation
+    # @else
+    # @brief postUnload callback function
+    # TODO: Documentation
+    # @endif
+    # virtual void postUnload(std::string& modname);
+
+    def postUnload(self, modname):
+        return self.LISTENERHOLDER_CALLBACK("postUnload", modname)
+
+
+##
+# @if jp
+# @class RtcLifecycleActionListener クラス
+#
+# RTC系
+# - RTC生成の直前 bool (std::string&)
+#   void preCreate(std::string& args) = 0;
+# - RTC生成の直後 bool (RTObject_impl*)
+#   void postCreate(RTObject_impl*) = 0;
+# - RTCのコンフィグ直前 bool (coil::Properties& prop)
+#   void preConfigure(coil::Properties& prop) = 0;
+# - RTCのコンフィグ直後 bool (coil::Properties& prop)
+#   void postConfigure(coil::Properties& prop) = 0;
+# - RTCの初期化の直前 bool (void)
+#   void preInitialize(void) = 0;
+# - RTCの初期化の直後 bool (void)
+#   void postInitialize(void) = 0;
+# @else
+# @class RtcLifecycleActionListener class
+# @endif
+class RtcLifecycleActionListener:
+    ##
+    # @if jp
+    # @brief preCreate コールバック関数
+    # @param self
+    # @param args
+    # @return
+    # @else
+    # @brief preCreate callback function
+    # @param self
+    # @param args
+    # @return
+    # @endif
+    # virtual void preCreate(std::string& args);
+    def preCreate(self, args):
+        # type: (str) -> str
+        return args
+    ##
+    # @if jp
+    # @brief postCreate コールバック関数
+    # @param self
+    # @param rtobj
+    # @else
+    # @brief postCreate callback function
+    # @param self
+    # @param rtobj
+    # @endif
+    # virtual void postCreate(RTC::RTObject_impl*);
+
+    def postCreate(self, rtobj):
+        # type: (OpenRTM_aist.RTObject_impl) -> None
+        pass
+    ##
+    # @if jp
+    # @brief preConfigure コールバック関数
+    # @param self
+    # @param prop
+    # @else
+    # @brief preConfigure callback function
+    # @param self
+    # @param prop
+    # @endif
+    # virtual void preConfigure(coil::Properties& prop);
+
+    def preConfigure(self, prop):
+        # type: (OpenRTM_aist.Properties) -> None
+        pass
+    ##
+    # @if jp
+    # @brief postConfigure コールバック関数
+    # @param self
+    # @param prop
+    # @else
+    # @brief postConfigure callback function
+    # @param self
+    # @param prop
+    # @endif
+    # virtual void postConfigure(coil::Properties& prop);
+
+    def postConfigure(self, prop):
+        # type: (OpenRTM_aist.Properties) -> None
+        pass
+
+    ##
+    # @if jp
+    # @brief preInitialize コールバック関数
+    # @param self
+    # @else
+    # @brief preInitialize callback function
+    # @param self
+    # @endif
+    # virtual void preInitialize();
+    def preInitialize(self):
+        # type: () -> None
+        pass
+
+    ##
+    # @if jp
+    # @brief postInitialize コールバック関数
+    # @param self
+    # @else
+    # @brief postInitialize callback function
+    # @param self
+    # @endif
+    # virtual void postInitialize();
+    def postInitialize(self):
+        # type: () -> None
+        pass
 
 ##
 # @if jp
-# @class RtcLifecycleActionListenerHolder 饹
-# @brief RtcLifecycleActionListenerHolder 饹
+# @class RtcLifecycleActionListenerHolder クラス
+# @brief RtcLifecycleActionListenerHolder クラス
 #
 # @else
 # @class RtcLifecycleActionListenerHolder class
@@ -194,114 +441,198 @@ def postUnload(self, modname):
 # provides callbacks for various events in rtobject.
 #
 # @endif
+
+
 class RtcLifecycleActionListenerHolder(OpenRTM_aist.ListenerHolder):
-  """
-  """
-
-  def __init__(self):
-    OpenRTM_aist.ListenerHolder.__init__(self)
-    return
-
-
-  ##
-  # @if jp
-  # @brief ǥȥ饯
-  # @else
-  # @brief Destructor
-  # @endif
-  def __del__(self):
-    pass
-    
-    
-  ##
-  # @if jp
-  # @brief preCreate Хåؿ
-  # TODO: Documentation
-  # @else
-  # @brief preCreate callback function
-  # TODO: Documentation
-  # @endif
-  # virtual void preCreate(std::string& args);
-  def preCreate(self, args):
-    self.LISTENERHOLDER_CALLBACK("preCreate", args)
-    return
-    
-
-  ##
-  # @if jp
-  # @brief postCreate Хåؿ
-  # TODO: Documentation
-  # @else
-  # @brief postCreate callback function
-  # TODO: Documentation
-  # @endif
-  # virtual void postCreate(RTC::RTObject_impl* rtobj);
-  def postCreate(self, rtobj):
-    self.LISTENERHOLDER_CALLBACK("postCreate", rtobj)
-    return
-     
-
-  ##
-  # @if jp
-  # @brief preConfigure Хåؿ
-  # TODO: Documentation
-  # @else
-  # @brief preConfigure callback function
-  # TODO: Documentation
-  # @endif
-  # virtual void preConfigure(coil::Properties& prop);
-  def preConfigure(self, prop):
-    self.LISTENERHOLDER_CALLBACK("preConfigure", prop)
-    return
-    
-
-  ##
-  # @if jp
-  # @brief postConfigure Хåؿ
-  # TODO: Documentation
-  # @else
-  # @brief postConfigure callback function
-  # TODO: Documentation
-  # @endif
-  # virtual void postConfigure(coil::Properties& prop);
-  def postConfigure(self, prop):
-    self.LISTENERHOLDER_CALLBACK("postConfigure", prop)
-    return
-    
-
-  ##
-  # @if jp
-  # @brief preInitialize Хåؿ
-  # TODO: Documentation
-  # @else
-  # @brief preInitialize callback function
-  # TODO: Documentation
-  # @endif
-  # virtual void preInitialize(void);
-  def preInitialize(self):
-    self.LISTENERHOLDER_CALLBACK("preInitialize")
-    return
-    
-
-  ##
-  # @if jp
-  # @brief postInitialize Хåؿ
-  # TODO: Documentation
-  # @else
-  # @brief postInitialize callback function
-  # TODO: Documentation
-  # @endif
-  # virtual void postInitialize(void);
-  def postInitialize(self):
-    self.LISTENERHOLDER_CALLBACK("postInitialize")
-    return
+    """
+    """
+
+    def __init__(self):
+        OpenRTM_aist.ListenerHolder.__init__(self)
+        return
+
+    ##
+    # @if jp
+    # @brief デストラクタ
+    # @else
+    # @brief Destructor
+    # @endif
+
+    def __del__(self):
+        pass
+
+    ##
+    # @if jp
+    # @brief preCreate コールバック関数
+    # TODO: Documentation
+    # @else
+    # @brief preCreate callback function
+    # TODO: Documentation
+    # @endif
+    # virtual void preCreate(std::string& args);
+
+    def preCreate(self, args):
+        return self.LISTENERHOLDER_CALLBACK("preCreate", args)
+
+    ##
+    # @if jp
+    # @brief postCreate コールバック関数
+    # TODO: Documentation
+    # @else
+    # @brief postCreate callback function
+    # TODO: Documentation
+    # @endif
+    # virtual void postCreate(RTC::RTObject_impl* rtobj);
+
+    def postCreate(self, rtobj):
+        self.LISTENERHOLDER_CALLBACK("postCreate", rtobj)
+        return
+
+    ##
+    # @if jp
+    # @brief preConfigure コールバック関数
+    # TODO: Documentation
+    # @else
+    # @brief preConfigure callback function
+    # TODO: Documentation
+    # @endif
+    # virtual void preConfigure(coil::Properties& prop);
+
+    def preConfigure(self, prop):
+        self.LISTENERHOLDER_CALLBACK("preConfigure", prop)
+        return
+
+    ##
+    # @if jp
+    # @brief postConfigure コールバック関数
+    # TODO: Documentation
+    # @else
+    # @brief postConfigure callback function
+    # TODO: Documentation
+    # @endif
+    # virtual void postConfigure(coil::Properties& prop);
 
+    def postConfigure(self, prop):
+        self.LISTENERHOLDER_CALLBACK("postConfigure", prop)
+        return
+
+    ##
+    # @if jp
+    # @brief preInitialize コールバック関数
+    # TODO: Documentation
+    # @else
+    # @brief preInitialize callback function
+    # TODO: Documentation
+    # @endif
+    # virtual void preInitialize(void);
+
+    def preInitialize(self):
+        self.LISTENERHOLDER_CALLBACK("preInitialize")
+        return
+
+    ##
+    # @if jp
+    # @brief postInitialize コールバック関数
+    # TODO: Documentation
+    # @else
+    # @brief postInitialize callback function
+    # TODO: Documentation
+    # @endif
+    # virtual void postInitialize(void);
+
+    def postInitialize(self):
+        self.LISTENERHOLDER_CALLBACK("postInitialize")
+        return
 
 
 ##
 # @if jp
-# @class NamingActionListenerHolder 饹
-# @brief NamingActionListenerHolder 饹
+# @class NamingActionListener クラス
+#
+# 各アクションに対応するユーザーコードが呼ばれる直前のタイミング
+# でコールされるリスなクラスの基底クラス。
+#
+# Registration系
+# - PRE_NS_REGISTER:    RTCの名前の登録の直前 bool (coil::vstring&)
+# - POST_NS_REGISTER:   RTCの名前の登録の直後 bool (coil::vstring&)
+# - PRE_NS_UNREGISTER:  RTCの名前の登録の直前 bool (coil::vstring&)
+# - POST_NS_UNREGISTER: RTCの名前の登録の直後 bool (coil::vstring&)
+#
+# @else
+# @class NamingActionListener class
+# @endif
+class NamingActionListener:
+    ##
+    # @if jp
+    # @brief preBind コールバック関数
+    # @param self
+    # @param rtobj
+    # @param name
+    # @else
+    # @brief preBind callback function
+    # @param self
+    # @param rtobj
+    # @param name
+    # @endif
+    # virtual void preBind(RTC::RTObject_impl* rtobj, coil::vstring& name);
+    def preBind(self, rtobj, name):
+        # type: (OpenRTM_aist.RTObject_impl, list) -> None
+        pass
+    ##
+    # @if jp
+    # @brief postBind コールバック関数
+    # @param self
+    # @param rtobj
+    # @param name
+    # @else
+    # @brief postBind callback function
+    # @param self
+    # @param rtobj
+    # @param name
+    # @endif
+    # virtual void postBind(RTC::RTObject_impl* rtobj, coil::vstring& name);
+
+    def postBind(self, rtobj, name):
+        # type: (OpenRTM_aist.RTObject_impl, list) -> None
+        pass
+    ##
+    # @if jp
+    # @brief preUnbind コールバック関数
+    # @param self
+    # @param rtobj
+    # @param name
+    # @else
+    # @brief preUnbind callback function
+    # @param self
+    # @param rtobj
+    # @param name
+    # @endif
+    # virtual void preUnbind(RTC::RTObject_impl* rtobj, coil::vstring& name);
+
+    def preUnbind(self, rtobj, name):
+        # type: (OpenRTM_aist.RTObject_impl, list) -> None
+        pass
+    ##
+    # @if jp
+    # @brief postUnbind コールバック関数
+    # @param self
+    # @param prop
+    # @else
+    # @brief postUnbind callback function
+    # @param self
+    # @param prop
+    # @endif
+    # virtual void postUnbind(RTC::RTObject_impl* rtobj, coil::vstring& name);
+
+    def postUnbind(self, rtobj, name):
+        # type: (OpenRTM_aist.RTObject_impl, list) -> None
+        pass
+
+
+##
+# @if jp
+# @class NamingActionListenerHolder クラス
+# @brief NamingActionListenerHolder クラス
 #
 # @else
 # @class NamingActionListenerHolder class
@@ -312,92 +643,218 @@ def postInitialize(self):
 #
 # @endif
 class NamingActionListenerHolder(OpenRTM_aist.ListenerHolder):
-  """
-  """
-
-  def __init__(self):
-    OpenRTM_aist.ListenerHolder.__init__(self)
-    return
-
-
-  ##
-  # @if jp
-  # @brief ǥȥ饯
-  # @else
-  # @brief Destructor
-  # @endif
-  def __del__(self):
-    pass
-    
-
-  ##
-  # @if jp
-  # @brief preBind Хåؿ
-  # TODO: Documentation
-  # @else
-  # @brief preBind callback function
-  # TODO: Documentation
-  # @endif
-  # virtual void preBind(RTC::RTObject_impl# rtobj,
-  #                      coil::vstring& name);
-  def preBind(self, rtobj, name):
-    self.LISTENERHOLDER_CALLBACK("preBind", rtobj, name)
-    return
-
-
-  ##
-  # @if jp
-  # @brief postBind Хåؿ
-  # TODO: Documentation
-  # @else
-  # @brief postBind callback function
-  # TODO: Documentation
-  # @endif
-  # virtual void postBind(RTC::RTObject_impl* rtobj,
-  #                       coil::vstring& name);
-  def postBind(self, rtobj, name):
-    self.LISTENERHOLDER_CALLBACK("postBind", rtobj, name)
-    return
-    
-
-  ##
-  # @if jp
-  # @brief preUnbind Хåؿ
-  # TODO: Documentation
-  # @else
-  # @brief preUnbind callback function
-  # TODO: Documentation
-  # @endif
-  # virtual void preUnbind(RTC::RTObject_impl* rtobj,
-  #                        coil::vstring& name);
-  def preUnbind(self, rtobj, name):
-    self.LISTENERHOLDER_CALLBACK("preUnbind", rtobj, name)
-    return
-    
-
-  ##
-  # @if jp
-  # @brief postUnbind Хåؿ
-  # TODO: Documentation
-  # @else
-  # @brief postUnbind callback function
-  # TODO: Documentation
-  # @endif
-  # virtual void postUnbind(RTC::RTObject_impl* rtobj,
-  #                         coil::vstring& name);
-  def postUnbind(self, rtobj, name):
-    self.LISTENERHOLDER_CALLBACK("postUnbind", rtobj, name)
-    return
-  
-  
-  
+    """
+    """
+
+    def __init__(self):
+        OpenRTM_aist.ListenerHolder.__init__(self)
+        return
+
+    ##
+    # @if jp
+    # @brief デストラクタ
+    # @else
+    # @brief Destructor
+    # @endif
+
+    def __del__(self):
+        pass
+
+    ##
+    # @if jp
+    # @brief preBind コールバック関数
+    # TODO: Documentation
+    # @else
+    # @brief preBind callback function
+    # TODO: Documentation
+    # @endif
+    # virtual void preBind(RTC::RTObject_impl# rtobj,
+    #                      coil::vstring& name);
+
+    def preBind(self, rtobj, name):
+        self.LISTENERHOLDER_CALLBACK("preBind", rtobj, name)
+        return
+
+    ##
+    # @if jp
+    # @brief postBind コールバック関数
+    # TODO: Documentation
+    # @else
+    # @brief postBind callback function
+    # TODO: Documentation
+    # @endif
+    # virtual void postBind(RTC::RTObject_impl* rtobj,
+    #                       coil::vstring& name);
+
+    def postBind(self, rtobj, name):
+        self.LISTENERHOLDER_CALLBACK("postBind", rtobj, name)
+        return
+
+    ##
+    # @if jp
+    # @brief preUnbind コールバック関数
+    # TODO: Documentation
+    # @else
+    # @brief preUnbind callback function
+    # TODO: Documentation
+    # @endif
+    # virtual void preUnbind(RTC::RTObject_impl* rtobj,
+    #                        coil::vstring& name);
+
+    def preUnbind(self, rtobj, name):
+        self.LISTENERHOLDER_CALLBACK("preUnbind", rtobj, name)
+        return
+
+    ##
+    # @if jp
+    # @brief postUnbind コールバック関数
+    # TODO: Documentation
+    # @else
+    # @brief postUnbind callback function
+    # TODO: Documentation
+    # @endif
+    # virtual void postUnbind(RTC::RTObject_impl* rtobj,
+    #                         coil::vstring& name);
+
+    def postUnbind(self, rtobj, name):
+        self.LISTENERHOLDER_CALLBACK("postUnbind", rtobj, name)
+        return
+
+
 ##
 # @if jp
-# @class LocalServiceActionListenerHolder 饹
-# @brief LocalServiceActionListenerHolder 饹
+# @class LocalServiceActionListener クラス
 #
-# ƥб桼ɤƤФľΥߥ
-# ǥ뤵ꥹʥ饹δ쥯饹
+# 各アクションに対応するユーザーコードが呼ばれる直前のタイミング
+# でコールされるリスナクラスの基底クラス。
+#
+# - ADD_PORT:
+# - REMOVE_PORT:
+#
+# @else
+# @class LocalServiceActionListener class
+# @endif
+class LocalServiceActionListener:
+    ##
+    # @if jp
+    # @brief preServiceRegister コールバック関数
+    # @param self
+    # @param service_name
+    # @return
+    # @else
+    # @brief preServiceRegister callback function
+    # @param self
+    # @param service_name
+    # @return
+    # @endif
+    # virtual void preServiceRegister(std::string service_name);
+    def preServiceRegister(self, service_name):
+        # type: (str) -> None
+        pass
+    ##
+    # @if jp
+    # @brief postServiceRegister コールバック関数
+    # @param self
+    # @param service_name
+    # @param service
+    # @return
+    # @else
+    # @brief postServiceRegister callback function
+    # @param self
+    # @param service_name
+    # @param service
+    # @return
+    # @endif
+    # virtual void postBind(std::string service_name, RTM::LocalServiceBase*
+    # service);
+
+    def postServiceRegister(self, service_name, service):
+        # type: (str, OpenRTM_aist.LocalServiceBase) -> None
+        pass
+    ##
+    # @if jp
+    # @brief preServiceInit コールバック関数
+    # @param self
+    # @param prop
+    # @param service
+    # @else
+    # @brief preServiceInit callback function
+    # @param self
+    # @param prop
+    # @param service
+    # @endif
+    # virtual void preServiceInit(coil::Properties& prop,
+    # RTM::LocalServiceBase* service);
+
+    def preServiceInit(self, prop, service):
+        # type: (OpenRTM_aist.Properties,  OpenRTM_aist.LocalServiceBase) ->
+        # None
+        pass
+    ##
+    # @if jp
+    # @brief preServiceReinit コールバック関数
+    # @param self
+    # @param prop
+    # @param service
+    # @else
+    # @brief preServiceReinit callback function
+    # @param self
+    # @param prop
+    # @param service
+    # @endif
+    # virtual void preServiceReinit(coil::Properties& prop,
+    # RTM::LocalServiceBase* service);
+
+    def preServiceReinit(self, prop, service):
+        # type: (OpenRTM_aist.Properties,  OpenRTM_aist.LocalServiceBase) ->
+        # None
+        pass
+
+    ##
+    # @if jp
+    # @brief postServiceFinalize コールバック関数
+    # @param self
+    # @param prop
+    # @param service
+    # @else
+    # @brief postServiceFinalize callback function
+    # @param self
+    # @param prop
+    # @param service
+    # @endif
+    # virtual void postServiceFinalize(coil::Properties& prop,
+    # RTM::LocalServiceBase* service);
+    def postServiceFinalize(self, prop, service):
+        # type: (OpenRTM_aist.Properties,  OpenRTM_aist.LocalServiceBase) ->
+        # None
+        pass
+
+    ##
+    # @if jp
+    # @brief preServiceFinalize コールバック関数
+    # @param self
+    # @param service_name
+    # @param service
+    # @else
+    # @brief preServiceFinalize callback function
+    # @param self
+    # @param service_name
+    # @param service
+    # @endif
+    # virtual void preServiceFinalize(std::string service_name,
+    # RTM::LocalServiceBase* service);
+    def preServiceFinalize(self, service_name, service):
+        # type: (str,  OpenRTM_aist.LocalServiceBase) -> None
+        pass
+
+
+##
+# @if jp
+# @class LocalServiceActionListenerHolder クラス
+# @brief LocalServiceActionListenerHolder クラス
+#
+# 各アクションに対応するユーザーコードが呼ばれる直前のタイミング
+# でコールされるリスなクラスの基底クラス。
 #
 # - ADD_PORT:
 # - REMOVE_PORT:
@@ -411,150 +868,151 @@ def postUnbind(self, rtobj, name):
 #
 # @endif
 class LocalServiceActionListenerHolder(OpenRTM_aist.ListenerHolder):
-  """
-  """
-
-  def __init__(self):
-    OpenRTM_aist.ListenerHolder.__init__(self)
-    return
-
-
-  ##
-  # @if jp
-  # @brief ǥȥ饯
-  # @else
-  # @brief Destructor
-  # @endif
-  def __del__(self):
-    pass
-    
-
-  # registration instance of service to svc admin
-  ##
-  # @if jp
-  # @brief preServiceRegister Хåؿ
-  # TODO: Documentation
-  # @else
-  # @brief preServiceRegister callback function
-  # TODO: Documentation
-  # @endif
-  # virtual void preServiceRegister(std::string service_name);
-  def preServiceRegister(self, service_name):
-    self.LISTENERHOLDER_CALLBACK("preServiceRegister", service_name)
-    return
-    
-
-  ##
-  # @if jp
-  # @brief postServiceRegister Хåؿ
-  # TODO: Documentation
-  # @else
-  # @brief postServiceRegister callback function
-  # TODO: Documentation
-  # @endif
-  # virtual void postServiceRegister(std::string service_name,
-  #                                  RTM::LocalServiceBase* service);
-  def postServiceRegister(self, service_name, service):
-    self.LISTENERHOLDER_CALLBACK("postServiceRegister", service_name, service)
-    return
-    
-
-  ##
-  # @if jp
-  # @brief preServiceInit Хåؿ
-  # TODO: Documentation
-  # @else
-  # @brief preServiceInit callback function
-  # TODO: Documentation
-  # @endif
-  # virtual void preServiceInit(coil::Properties& prop,
-  #                             RTM::LocalServiceBase* service);
-  def preServiceInit(self, prop, service):
-    self.LISTENERHOLDER_CALLBACK("preServiceInit", prop, service)
-    return
-
-
-  ##
-  # @if jp
-  # @brief postServiceInit Хåؿ
-  # TODO: Documentation
-  # @else
-  # @brief postServiceInit callback function
-  # TODO: Documentation
-  # @endif
-  # virtual void postServiceInit(coil::Properties& prop,
-  #                              RTM::LocalServiceBase* service);
-  def postServiceInit(self, prop, service):
-    self.LISTENERHOLDER_CALLBACK("postServiceInit", prop, service)
-    return
-    
-
-  ##
-  # @if jp
-  # @brief preServiceReinit Хåؿ
-  # TODO: Documentation
-  # @else
-  # @brief preServiceReinit callback function
-  # TODO: Documentation
-  # @endif
-  # virtual void preServiceReinit(coil::Properties& prop,
-  #                               RTM::LocalServiceBase* service);
-  def preServiceReinit(self, prop, service):
-    self.LISTENERHOLDER_CALLBACK("preServiceReinit", prop, service)
-    return
-
-
-  ##
-  # @if jp
-  # @brief postServiceReinit Хåؿ
-  # TODO: Documentation
-  # @else
-  # @brief postServiceReinit callback function
-  # TODO: Documentation
-  # @endif
-  # virtual void postServiceReinit(coil::Properties& prop,
-  #                                RTM::LocalServiceBase* service);
-  def postServiceReinit(self, prop, service):
-    self.LISTENERHOLDER_CALLBACK("postServiceReinit", prop, service)
-    return
-
-
-  ##
-  # @if jp
-  # @brief preServiceFinalize Хåؿ
-  # TODO: Documentation
-  # @else
-  # @brief preServiceFinalize callback function
-  # TODO: Documentation
-  # @endif
-  # virtual void preServiceFinalize(std::string service_name,
-  #                                 RTM::LocalServiceBase* service);
-  def preServiceFinalize(self, service_name, service):
-    self.LISTENERHOLDER_CALLBACK("preServiceFinalize", service_name, service)
-    return
-
-
-  ##
-  # @if jp
-  # @brief postServiceFinalize Хåؿ
-  # TODO: Documentation
-  # @else
-  # @brief postServiceFinalize callback function
-  # TODO: Documentation
-  # @endif
-  # virtual void postServiceFinalize(std::string service_name,
-  #                                  RTM::LocalServiceBase* service);
-  def postServiceFinalize(self, service_name, service):
-    self.LISTENERHOLDER_CALLBACK("postServiceFinalize", service_name, service)
-    return
-
-  
-  
-  
+    """
+    """
+
+    def __init__(self):
+        OpenRTM_aist.ListenerHolder.__init__(self)
+        return
+
+    ##
+    # @if jp
+    # @brief デストラクタ
+    # @else
+    # @brief Destructor
+    # @endif
+
+    def __del__(self):
+        pass
+
+    # registration instance of service to svc admin
+    ##
+    # @if jp
+    # @brief preServiceRegister コールバック関数
+    # TODO: Documentation
+    # @else
+    # @brief preServiceRegister callback function
+    # TODO: Documentation
+    # @endif
+    # virtual void preServiceRegister(std::string service_name);
+
+    def preServiceRegister(self, service_name):
+        self.LISTENERHOLDER_CALLBACK("preServiceRegister", service_name)
+        return
+
+    ##
+    # @if jp
+    # @brief postServiceRegister コールバック関数
+    # TODO: Documentation
+    # @else
+    # @brief postServiceRegister callback function
+    # TODO: Documentation
+    # @endif
+    # virtual void postServiceRegister(std::string service_name,
+    #                                  RTM::LocalServiceBase* service);
+
+    def postServiceRegister(self, service_name, service):
+        self.LISTENERHOLDER_CALLBACK(
+            "postServiceRegister", service_name, service)
+        return
+
+    ##
+    # @if jp
+    # @brief preServiceInit コールバック関数
+    # TODO: Documentation
+    # @else
+    # @brief preServiceInit callback function
+    # TODO: Documentation
+    # @endif
+    # virtual void preServiceInit(coil::Properties& prop,
+    #                             RTM::LocalServiceBase* service);
+
+    def preServiceInit(self, prop, service):
+        self.LISTENERHOLDER_CALLBACK("preServiceInit", prop, service)
+        return
+
+    ##
+    # @if jp
+    # @brief postServiceInit コールバック関数
+    # TODO: Documentation
+    # @else
+    # @brief postServiceInit callback function
+    # TODO: Documentation
+    # @endif
+    # virtual void postServiceInit(coil::Properties& prop,
+    #                              RTM::LocalServiceBase* service);
+
+    def postServiceInit(self, prop, service):
+        self.LISTENERHOLDER_CALLBACK("postServiceInit", prop, service)
+        return
+
+    ##
+    # @if jp
+    # @brief preServiceReinit コールバック関数
+    # TODO: Documentation
+    # @else
+    # @brief preServiceReinit callback function
+    # TODO: Documentation
+    # @endif
+    # virtual void preServiceReinit(coil::Properties& prop,
+    #                               RTM::LocalServiceBase* service);
+
+    def preServiceReinit(self, prop, service):
+        self.LISTENERHOLDER_CALLBACK("preServiceReinit", prop, service)
+        return
+
+    ##
+    # @if jp
+    # @brief postServiceReinit コールバック関数
+    # TODO: Documentation
+    # @else
+    # @brief postServiceReinit callback function
+    # TODO: Documentation
+    # @endif
+    # virtual void postServiceReinit(coil::Properties& prop,
+    #                                RTM::LocalServiceBase* service);
+
+    def postServiceReinit(self, prop, service):
+        self.LISTENERHOLDER_CALLBACK("postServiceReinit", prop, service)
+        return
+
+    ##
+    # @if jp
+    # @brief preServiceFinalize コールバック関数
+    # TODO: Documentation
+    # @else
+    # @brief preServiceFinalize callback function
+    # TODO: Documentation
+    # @endif
+    # virtual void preServiceFinalize(std::string service_name,
+    #                                 RTM::LocalServiceBase* service);
+
+    def preServiceFinalize(self, service_name, service):
+        self.LISTENERHOLDER_CALLBACK(
+            "preServiceFinalize", service_name, service)
+        return
+
+    ##
+    # @if jp
+    # @brief postServiceFinalize コールバック関数
+    # TODO: Documentation
+    # @else
+    # @brief postServiceFinalize callback function
+    # TODO: Documentation
+    # @endif
+    # virtual void postServiceFinalize(std::string service_name,
+    #                                  RTM::LocalServiceBase* service);
+
+    def postServiceFinalize(self, service_name, service):
+        self.LISTENERHOLDER_CALLBACK(
+            "postServiceFinalize", service_name, service)
+        return
+
+
 ##
 # @if jp
 # @class ManagerActionListeners
-# @brief ManagerActionListeners 饹
+# @brief ManagerActionListeners クラス
 #
 #
 # @else
@@ -564,13 +1022,12 @@ def postServiceFinalize(self, service_name, service):
 #
 # @endif
 class ManagerActionListeners:
-  """
-  """
-
-  def __init__(self):
-    self.manager_      = ManagerActionListenerHolder()
-    self.module_       = ModuleActionListenerHolder() 
-    self.rtclifecycle_ = RtcLifecycleActionListenerHolder()
-    self.naming_       = NamingActionListenerHolder()
-    self.localservice_ = LocalServiceActionListenerHolder()
+    """
+    """
 
+    def __init__(self):
+        self.manager_ = ManagerActionListenerHolder()
+        self.module_ = ModuleActionListenerHolder()
+        self.rtclifecycle_ = RtcLifecycleActionListenerHolder()
+        self.naming_ = NamingActionListenerHolder()
+        self.localservice_ = LocalServiceActionListenerHolder()
diff --git a/OpenRTM_aist/ManagerConfig.py b/OpenRTM_aist/ManagerConfig.py
index 00a461a4..5241b39d 100644
--- a/OpenRTM_aist/ManagerConfig.py
+++ b/OpenRTM_aist/ManagerConfig.py
@@ -1,5 +1,5 @@
 #!/usr/bin/env python
-# -*- coding: euc-jp -*-
+# -*- coding: utf-8 -*-
 
 ##
 # @file ManagerConfig.py
@@ -27,27 +27,27 @@
 # @if jp
 #
 # @class ManagerConfig
-# @brief Manager configuration 饹
+# @brief Manager configuration クラス
 #
-# Manager Υե졼Ԥޥɥ饤ꡢ
-# (뤤ϰʤ)󥹥󥹲롣
-# ޥɥ饤ǻꤵ줿ե롢Ķѿʤɤ Manager 
-# ץѥƥꤹ롣
+# Manager のコンフィギュレーションを行う、コマンドライン引数を受け取り、
+# (あるいは引数なしで)インスタンス化される。
+# コマンドライン引数で指定された設定ファイル、環境変数などから Manager の
+# プロパティ情報を設定する。
 #
-# ͥ٤ϰʲΤȤǤ롣
+# 各設定の優先度は以下のとおりである。
 # 
    -#
  1. ޥɥ饤󥪥ץ "-f" -#
  2. Ķѿ "RTC_MANAGER_CONFIG" -#
  3. ǥեե "./rtc.conf" -#
  4. ǥեե "/etc/rtc.conf" -#
  5. ǥեե "/etc/rtc/rtc.conf" -#
  6. ǥեե "/usr/local/etc/rtc.conf" -#
  7. ǥեե "/usr/local/etc/rtc/rtc.conf" -#
  8. ߥե졼 -#
-# ޥɥ饤󥪥ץ "-d" ꤵ줿ϡ -# (Ȥ -f եꤷƤ)ߥե졼 -# Ѥ롣 +#
  • コマンドラインオプション "-f" +#
  • 環境変数 "RTC_MANAGER_CONFIG" +#
  • デフォルト設定ファイル "./rtc.conf" +#
  • デフォルト設定ファイル "/etc/rtc.conf" +#
  • デフォルト設定ファイル "/etc/rtc/rtc.conf" +#
  • デフォルト設定ファイル "/usr/local/etc/rtc.conf" +#
  • デフォルト設定ファイル "/usr/local/etc/rtc/rtc.conf" +#
  • 埋め込みコンフィギュレーション値 +# +# ただし、コマンドラインオプション "-d" が指定された場合は、 +# (たとえ -f で設定ファイルを指定しても)埋め込みコンフィギュレーション値 +# が使用される。 # # @since 0.4.0 # @@ -56,7 +56,7 @@ # @class ManagerConfig # @brief Manager configuration class # -# Modify Manager's configuration. +# Modify Manager's configuration. # This class receives the command line arguments and will be instantiated. # Set property information of Manager with the configuration file specified # by the command line argument or the environment variable etc. @@ -78,376 +78,364 @@ # @since 0.4.0 # # @endif -class ManagerConfig : - """ - """ - ## - # @if jp - # @brief Manager ե졼Υǥեȡե롦ѥ - # @else - # @brief The default configuration file path for manager - # @endif - if os.name == 'nt': - - config_file_path = ["./rtc.conf", - "${RTM_ROOT}bin/${RTM_VC_VERSION}/rtc.conf", - "C:/Python"+str(sys.version_info[0])+str(sys.version_info[1])+"/rtc.conf", - None] - else: - config_file_path = ["./rtc.conf", - "/etc/rtc.conf", - "/etc/rtc/rtc.conf", - "/usr/local/etc/rtc.conf", - "/usr/local/etc/rtc/rtc.conf", - None] - - - ## - # @if jp - # @brief ǥեȡե졼Υե롦ѥ̤ - # Ķѿ - # @else - # @brief The environment variable to distinguish the default configuration - # file path - # @endif - config_file_env = "RTC_MANAGER_CONFIG" - - - ## - # @if jp - # - # @brief 󥹥ȥ饯 - # - # Ϳ줿ˤꥳե졼νԤ - # - # @param self - # @param argv ޥɥ饤(ǥե:None) - # - # @else - # - # @brief ManagerConfig constructor - # - # The constructor that performs initialization at the same time with - # given arguments. - # - # @param argv The command line arguments - # - # @endif - def __init__(self, argv=None): - - self._configFile = "" - self._argprop = OpenRTM_aist.Properties() - self._isMaster = False - self._ignoreNoConf = False - if argv: - self.init(argv) - - - - ## - # @if jp - # - # @brief - # - # ޥɥ饤˱ƽ¹Ԥ롣ޥɥ饤󥪥ץ - # ʲΤΤѲǽǤ롣 - # - # -a : ޥ͡㥵ӥOFFˤ롣
    - # -f file : ե졼եꤹ롣
    - # -l module : ɤ⥸塼ꤹ롣(̤)
    - # -o options: ¾ץꤹ롣
    - # -p : ݡֹꤹ롣
    - # -d : ޥޥ͡ư롣
    - # - # @param self - # @param argv ޥɥ饤 - # - # @else - # - # @brief Initialization - # - # Initialize with command line options. The following command options - # are available. - # - # -a : Disable Manager service
    - # -f file : Specify a configuration file.
    - # -l module : Specify modules to be loaded at the beginning.
    - # -o options: Other options.
    - # -p : Specify a port number.
    - # -d : Run Master Manager.
    - # - # @endif - def init(self, argv): - self.parseArgs(argv) - return - - ## - # @if jp - # @brief Configuration Property ꤹ - # - # Manager Configuration ꤵ줿 Property ꤹ롣 - # - # @param self - # @param prop Configuration о Property - # - # @else - # @brief Specify the configuration information to the Property - # - # Configure to the properties specified by Manager's configuration - # - # @endif - def configure(self, prop): - prop.setDefaults(OpenRTM_aist.default_config) - if self.findConfigFile(): - #try: - with open(self._configFile,"r") as fd: - prop.load(fd) - fd.close() - #except: - # print(OpenRTM_aist.Logger.print_exception()) - - - self.setSystemInformation(prop) - if self._isMaster: - prop.setProperty("manager.is_master","YES") - - # Properties from arguments are marged finally - prop.mergeProperties(self._argprop) - prop.setProperty("config_file", self._configFile) - return prop - - - ####### - # @if jp - # - # @brief ե졼(̤) - # - # ե졼롣init()ƤӽФ˸Ƥ֤ȡ - # Ū줿ǥեȤΥե졼֤ - # init() ƤӽФ˸Ƥ֤ȡޥɥ饤Ķѿ - # Ť줿ե졼֤ - # - # @else - # - # @brief Get configuration value. - # - # This operation returns default configuration statically defined, - # when before calling init() function. When after calling init() function, - # this operation returns initialized configuration value according to - # command option, environment value and so on. - # - # @endif - #def getConfig(self): - #pass - - - ## - # @if jp - # - # @brief ޥɰѡ - # - # -a : ޥ͡㥵ӥOFFˤ롣
    - # -f file : ե졼եꤹ롣
    - # -l module : ɤ⥸塼ꤹ롣(̤)
    - # -o options: ¾ץꤹ롣
    - # -p : ݡֹꤹ롣
    - # -d : ޥޥ͡ư롣
    - # - # @param self - # @param argv ޥɥ饤 - # - # @else - # - # @brief Parse command arguments - # - # -a : Disable Manager service
    - # -f file : Specify a configuration file.
    - # -l module : Specify modules to be loaded at the beginning.
    - # -o options: Other options.
    - # -p : Specify a port number.
    - # -d : Run Master Manager.
    - # - # @endif - def parseArgs(self, argv): - try: - opts, args = getopt.getopt(argv[1:], "adif:o:p:") - except getopt.GetoptError: - print(OpenRTM_aist.Logger.print_exception()) - return - - for opt, arg in opts: - if opt == "-a": - self._argprop.setProperty("manager.corba_servant","NO") - - if opt == "-f": - self._configFile = arg - - if opt == "-o": - pos = arg.find(":") - if pos > 0: - key = arg[:pos] - value = arg[pos+1:] - #key = OpenRTM_aist.unescape(key) - key = key.strip() - #value = OpenRTM_aist.unescape(value) - value = value.strip() - self._argprop.setProperty(key,value) - - if opt == "-p": - num = [-1] - ret = OpenRTM_aist.stringTo(num, arg) - if ret: - arg_ = ":" + arg - self._argprop.setProperty("corba.endpoints",arg_) - - if opt == "-d": - self._isMaster = True - - if opt == "-i": - self._ignoreNoConf = True - - - return - - - ## - # @if jp - # - # @brief Configuration file θ - # - # Configuration file 򸡺ꤹ롣 - # Configuration file Ѥߤξϡե¸߳ǧԤ - # - # Configuration file ͥ
    - # ޥɥץĶѿǥեȥեǥե - # - # ǥեȶץ(-d): ǥեȥե뤬äƤ̵뤷 - # ǥեȤ - # - # @param self - # - # @return Configuration file - # - # @else - # - # @brief Find the configuration file - # - # Find the configuration file and configure it. - # Confirm the file existence when the configuration file has - # already configured. - # - # The priority of the configuration file
    - # The command optionthe environment variablethe default file - # the default configuration - # - # Default force option(-d): Ignore any default files and use the default - # configuration. - # - # @return Configuration file search result - # - # @endif - def findConfigFile(self): - if self._configFile != "": - if not self.fileExist(self._configFile): - #print(OpenRTM_aist.Logger.print_exception()) - print("Configuration file: " + self._configFile + " not found.") - if not self._ignoreNoConf: - sys.exit() - return False - return True - - env = os.getenv(self.config_file_env) - if env: - if self.fileExist(env): - self._configFile = env - return True - - i = 0 - while (self.config_file_path[i]): - self.config_file_path[i] = OpenRTM_aist.replaceEnv(self.config_file_path[i]) - if self.fileExist(self.config_file_path[i]): - self._configFile = self.config_file_path[i] - return True - i += 1 - - return False - - - ## - # @if jp - # - # @brief ƥꤹ - # - # ƥץѥƥ˥åȤ롣ꤵ륭ϰʲ̤ꡣ - # - os.name : OS̾ - # - os.release : OS꡼̾ - # - os.version : OSС̾ - # - os.arch : OSƥ - # - os.hostname: ۥ̾ - # - manager.pid: ץID - # - # @param self - # @param prop ƥꤷץѥƥ - # - # @else - # - # @brief Set system information - # - # Get the following system info and set them to Manager's properties. - # - os.name : OS name - # - os.release : OS release name - # - os.version : OS version - # - os.arch : OS architecture - # - os.hostname: Hostname - # - manager.pid: process ID - # - # @endif - def setSystemInformation(self, prop): +class ManagerConfig: + """ + """ + ## + # @if jp + # @brief Manager コンフィギュレーションのデフォルト・ファイル・パス + # @else + # @brief The default configuration file path for manager + # @endif if os.name == 'nt': - sysinfo = platform.uname() - else: - sysinfo = os.uname() - - prop.setProperty("os.name", sysinfo[0]) - prop.setProperty("os.hostname", sysinfo[1]) - prop.setProperty("os.release", sysinfo[2]) - prop.setProperty("os.version", sysinfo[3]) - prop.setProperty("os.arch", sysinfo[4]) - prop.setProperty("manager.pid", os.getpid()) - - return prop - - - ## - # @if jp - # @brief ե¸߳ǧ - # - # ꤵ줿ե뤬¸ߤ뤫ǧ롣 - # - # @param self - # @param filename ǧоݥե̾ - # - # @return оݥեǧ(¸ߤtrue) - # - # @else - # @brief Check the file existence - # - # Confirm whether the specified file exists - # - # @param filename The target confirmation file - # - # @return file existance confirmation (True if the file exists.) - # - # @endif - def fileExist(self, filename): - try: - fp = open(filename) - except: - return False - else: - fp.close() - return True - + config_file_path = ["./rtc.conf", + "${PROGRAMDATA}/OpenRTM-aist/rtc.conf"] + else: + config_file_path = ["./rtc.conf", + "/etc/rtc.conf", + "/etc/rtc/rtc.conf", + "/usr/local/etc/rtc.conf", + "/usr/local/etc/rtc/rtc.conf"] + + ## + # @if jp + # @brief デフォルト・コンフィギュレーションのファイル・パスを識別する + # 環境変数 + # @else + # @brief The environment variable to distinguish the default configuration + # file path + # @endif + config_file_env = "RTC_MANAGER_CONFIG" + + ## + # @if jp + # + # @brief コンストラクタ + # + # 与えられた引数によりコンフィギュレーション情報の初期化を行う。 + # + # @param self + # @param argv コマンドライン引数(デフォルト値:None) + # + # @else + # + # @brief ManagerConfig constructor + # + # The constructor that performs initialization at the same time with + # given arguments. + # + # @param argv The command line arguments + # + # @endif + def __init__(self, argv=None): + + self._configFile = "" + self._argprop = OpenRTM_aist.Properties() + self._isMain = False + self._ignoreNoConf = False + if argv: + self.init(argv) + + ## + # @if jp + # + # @brief 初期化 + # + # コマンドライン引数に応じて初期化を実行する。コマンドラインオプションは + # 以下のものが使用可能である。 + # + # -a : マネージャサービスをOFFにする。
    + # -f file : コンフィギュレーションファイルを指定する。
    + # -l module : ロードするモジュールを指定する。(未実装)
    + # -o options: その他オプションを指定する。
    + # -p : ポート番号を指定する。
    + # -d : マスターマネージャを起動する。
    + # + # @param self + # @param argv コマンドライン引数 + # + # @else + # + # @brief Initialization + # + # Initialize with command line options. The following command options + # are available. + # + # -a : Disable Manager service
    + # -f file : Specify a configuration file.
    + # -l module : Specify modules to be loaded at the beginning.
    + # -o options: Other options.
    + # -p : Specify a port number.
    + # -d : Run Main Manager.
    + # + # @endif + + def init(self, argv): + self.parseArgs(argv) + return + + ## + # @if jp + # @brief Configuration 情報を Property に設定する + # + # Manager のConfiguration 情報を指定された Property に設定する。 + # + # @param self + # @param prop Configuration 設定対象 Property + # + # @else + # @brief Specify the configuration information to the Property + # + # Configure to the properties specified by Manager's configuration + # + # @endif + def configure(self, prop): + prop.setDefaults(OpenRTM_aist.default_config) + if self.findConfigFile(): + # try: + with open(self._configFile, "r") as fd: + prop.load(fd) + fd.close() + # except: + # print(OpenRTM_aist.Logger.print_exception()) + + self.setSystemInformation(prop) + if self._isMain: + prop.setProperty("manager.is_main", "YES") + + # Properties from arguments are marged finally + prop.mergeProperties(self._argprop) + prop.setProperty("config_file", self._configFile) + return prop + + ####### + # @if jp + # + # @brief コンフィギュレーションを取得する(未実装) + # + # コンフィギュレーションを取得する。init()呼び出し前に呼ぶと、 + # 静的に定義されたデフォルトのコンフィギュレーションを返す。 + # init() 呼び出し後に呼ぶと、コマンドライン引数、環境変数等に + # 基づいた初期化されたコンフィギュレーションを返す。 + # + # @else + # + # @brief Get configuration value. + # + # This operation returns default configuration statically defined, + # when before calling init() function. When after calling init() function, + # this operation returns initialized configuration value according to + # command option, environment value and so on. + # + # @endif + # def getConfig(self): + # pass + + ## + # @if jp + # + # @brief コマンド引数をパースする + # + # -a : マネージャサービスをOFFにする。
    + # -f file : コンフィギュレーションファイルを指定する。
    + # -l module : ロードするモジュールを指定する。(未実装)
    + # -o options: その他オプションを指定する。
    + # -p : ポート番号を指定する。
    + # -d : マスターマネージャを起動する。
    + # + # @param self + # @param argv コマンドライン引数 + # + # @else + # + # @brief Parse command arguments + # + # -a : Disable Manager service
    + # -f file : Specify a configuration file.
    + # -l module : Specify modules to be loaded at the beginning.
    + # -o options: Other options.
    + # -p : Specify a port number.
    + # -d : Run Main Manager.
    + # + # @endif + + def parseArgs(self, argv): + try: + opts, args = getopt.getopt(argv[1:], "adif:o:p:") + except getopt.GetoptError: + print(OpenRTM_aist.Logger.print_exception()) + return + + for opt, arg in opts: + if opt == "-a": + self._argprop.setProperty("manager.corba_servant", "NO") + + if opt == "-f": + self._configFile = arg + + if opt == "-o": + pos = arg.find(":") + if pos > 0: + key = arg[:pos] + value = arg[pos + 1:] + #key = OpenRTM_aist.unescape(key) + key = key.strip() + #value = OpenRTM_aist.unescape(value) + value = value.strip() + self._argprop.setProperty(key, value) + + if opt == "-p": + num = -1 + ret, num = OpenRTM_aist.stringTo(num, arg) + if ret: + arg_ = ":" + arg + self._argprop.setProperty("corba.endpoints", arg_) + + if opt == "-d": + self._isMain = True + + if opt == "-i": + self._ignoreNoConf = True + + return + + ## + # @if jp + # + # @brief Configuration file の検索 + # + # Configuration file を検索し、設定する。 + # 既に Configuration file が設定済みの場合は、ファイルの存在確認を行う。 + # + # Configuration file の優先順位
    + # コマンドオプション指定>環境変数>デフォルトファイル>デフォルト設定 + # + # デフォルト強制オプション(-d): デフォルトファイルがあっても無視して + # デフォルト設定を使う + # + # @param self + # + # @return Configuration file 検索結果 + # + # @else + # + # @brief Find the configuration file + # + # Find the configuration file and configure it. + # Confirm the file existence when the configuration file has + # already configured. + # + # The priority of the configuration file
    + # The command option>the environment variable>the default file> + # the default configuration + # + # Default force option(-d): Ignore any default files and use the default + # configuration. + # + # @return Configuration file search result + # + # @endif + + def findConfigFile(self): + if self._configFile != "": + if not self.fileExist(self._configFile): + # print(OpenRTM_aist.Logger.print_exception()) + print( + "Configuration file: " + + self._configFile + + " not found.") + if not self._ignoreNoConf: + sys.exit() + return False + return True + + env = os.getenv(self.config_file_env) + if env: + if self.fileExist(env): + self._configFile = env + return True + + for file_path in self.config_file_path: + file_path = OpenRTM_aist.replaceEnv(file_path) + if self.fileExist(file_path): + self._configFile = file_path + return True + return False + ## + # @if jp + # + # @brief システム情報を設定する + # + # システム情報を取得しプロパティにセットする。設定されるキーは以下の通り。 + # - os.name : OS名 + # - os.release : OSリリース名 + # - os.version : OSバージョン名 + # - os.arch : OSアーキテクチャ + # - os.hostname: ホスト名 + # - manager.pid: プロセスID + # + # @param self + # @param prop システム情報を設定したプロパティ + # + # @else + # + # @brief Set system information + # + # Get the following system info and set them to Manager's properties. + # - os.name : OS name + # - os.release : OS release name + # - os.version : OS version + # - os.arch : OS architecture + # - os.hostname: Hostname + # - manager.pid: process ID + # + # @endif + + def setSystemInformation(self, prop): + if os.name == 'nt': + sysinfo = platform.uname() + else: + sysinfo = os.uname() + + prop.setProperty("os.name", sysinfo[0]) + prop.setProperty("os.hostname", sysinfo[1]) + prop.setProperty("os.release", sysinfo[2]) + prop.setProperty("os.version", sysinfo[3]) + prop.setProperty("os.arch", sysinfo[4]) + prop.setProperty("manager.pid", os.getpid()) + + return prop + + ## + # @if jp + # @brief ファイルの存在確認 + # + # 指定されたファイルが存在するか確認する。 + # + # @param self + # @param filename 確認対象ファイル名称 + # + # @return 対象ファイル確認結果(存在する場合にtrue) + # + # @else + # @brief Check the file existence + # + # Confirm whether the specified file exists + # + # @param filename The target confirmation file + # + # @return file existance confirmation (True if the file exists.) + # + # @endif + + def fileExist(self, filename): + try: + fp = open(filename) + except BaseException: + return False + else: + fp.close() + return True diff --git a/OpenRTM_aist/ManagerServant.py b/OpenRTM_aist/ManagerServant.py index 814da02e..ae3a7f55 100644 --- a/OpenRTM_aist/ManagerServant.py +++ b/OpenRTM_aist/ManagerServant.py @@ -1,5 +1,5 @@ #!/usr/bin/env python -# -*- coding: euc-jp -*- +# -*- coding: utf-8 -*- ## # @file ManagerServant.py @@ -20,7 +20,9 @@ import time from omniORB import CORBA import OpenRTM_aist -import RTC,RTM,RTM__POA +import RTC +import RTM +import RTM__POA import re import os @@ -28,9 +30,9 @@ ## # @if jp # @class CompParam -# @brief CompParam 饹 +# @brief CompParam クラス # -# RTCΥ٥̾ƥ̾ID졢СǼ빽¤ +# RTCのベンダ名、カテゴリ名、ID、言語、バージョンを格納する構造体 # # @since 1.2.0 # @@ -39,1625 +41,1624 @@ # @brief CompParam class # @endif class CompParam: - prof_list = ["RTC", "vendor", "category", "implementation_id", "language", "version"] - ## - # @if jp - # @brief 󥹥ȥ饯 - # - # 󥹥ȥ饯 - # - # @param self - # @param module_name ⥸塼̾ - # - # @else - # @brief Constructor - # - # @param self - # @param module_name - # - # @endif - def __init__(self, module_name): - module_name = module_name.split("?")[0] - param_list = module_name.split(":") - if len(param_list) < len(CompParam.prof_list): - self._type = "RTC" - self._vendor = "" - self._category = "" - self._impl_id = module_name - self._language = "Python" - self._version = "" - else: - self._type = param_list[0] - self._vendor = param_list[1] - self._category = param_list[2] - self._impl_id = param_list[3] - if param_list[4]: - self._language = param_list[4] - else: - self._language = "Python" - self._version = param_list[5] - - - ## - # @if jp - # @brief ٥̾ - # - # - # - # @param self - # @return ٥̾ - # - # @else - # @brief - # - # @param self - # @return - # - # @endif - def vendor(self): - return self._vendor - ## - # @if jp - # @brief ƥ̾ - # - # - # - # @param self - # @return ƥ̾ - # - # @else - # @brief - # - # @param self - # @return - # - # @endif - def category(self): - return self._category - ## - # @if jp - # @brief ID - # - # - # - # @param self - # @return ID - # - # @else - # @brief - # - # @param self - # @return - # - # @endif - def impl_id(self): - return self._impl_id - ## - # @if jp - # @brief - # - # - # - # @param self - # @return - # - # @else - # @brief - # - # @param self - # @return - # - # @endif - def language(self): - return self._language - ## - # @if jp - # @brief С - # - # - # - # @param self - # @return С - # - # @else - # @brief - # - # @param self - # @return - # - # @endif - def version(self): - return self._version - - + prof_list = [ + "RTC", + "vendor", + "category", + "implementation_id", + "language", + "version"] + ## + # @if jp + # @brief コンストラクタ + # + # コンストラクタ + # + # @param self + # @param module_name モジュール名 + # + # @else + # @brief Constructor + # + # @param self + # @param module_name + # + # @endif + + def __init__(self, module_name): + module_name = module_name.split("?")[0] + param_list = module_name.split(":") + if len(param_list) < len(CompParam.prof_list): + self._type = "RTC" + self._vendor = "" + self._category = "" + self._impl_id = module_name + self._language = "Python" + self._version = "" + else: + self._type = param_list[0] + self._vendor = param_list[1] + self._category = param_list[2] + self._impl_id = param_list[3] + if param_list[4]: + self._language = param_list[4] + else: + self._language = "Python" + self._version = param_list[5] + + ## + # @if jp + # @brief ベンダ名取得 + # + # + # + # @param self + # @return ベンダ名 + # + # @else + # @brief + # + # @param self + # @return + # + # @endif + + def vendor(self): + return self._vendor + ## + # @if jp + # @brief カテゴリ名取得 + # + # + # + # @param self + # @return カテゴリ名 + # + # @else + # @brief + # + # @param self + # @return + # + # @endif + + def category(self): + return self._category + ## + # @if jp + # @brief ID取得 + # + # + # + # @param self + # @return ID + # + # @else + # @brief + # + # @param self + # @return + # + # @endif + + def impl_id(self): + return self._impl_id + ## + # @if jp + # @brief 言語取得 + # + # + # + # @param self + # @return 言語 + # + # @else + # @brief + # + # @param self + # @return + # + # @endif + + def language(self): + return self._language + ## + # @if jp + # @brief バージョン取得 + # + # + # + # @param self + # @return バージョン + # + # @else + # @brief + # + # @param self + # @return + # + # @endif + + def version(self): + return self._version + class ManagerServant(RTM__POA.Manager): - """ - """ - - ## - # @if jp - # @brief 󥹥ȥ饯 - # - # 󥹥ȥ饯 - # - # @else - # @brief Constructor - # - # Constructor - # - # @endif - # - def __init__(self): - self._mgr = OpenRTM_aist.Manager.instance() - self._owner = None - self._rtcout = self._mgr.getLogbuf("ManagerServant") - self._isMaster = False - self._masters = [] - self._slaves = [] - self._masterMutex = threading.RLock() - self._slaveMutex = threading.RLock() - self._objref = RTM.Manager._nil - - - config = copy.deepcopy(self._mgr.getConfig()) - - if (not self.createINSManager()): - self._rtcout.RTC_WARN("Manager CORBA servant creation failed.") - return - self._rtcout.RTC_TRACE("Manager CORBA servant was successfully created.") - - if OpenRTM_aist.toBool(config.getProperty("manager.is_master"), "YES", "NO", True): - # this is master manager - self._rtcout.RTC_TRACE("This manager is master.") - self._isMaster = True - return - else: - # this is slave manager - self._rtcout.RTC_TRACE("This manager is slave.") - try: - owner = self.findManager(config.getProperty("corba.master_manager")) - if not owner: - self._rtcout.RTC_INFO("Master manager not found") - return - self.add_master_manager(owner) - owner.add_slave_manager(self._objref) + """ + """ + + ## + # @if jp + # @brief コンストラクタ + # + # コンストラクタ + # + # @else + # @brief Constructor + # + # Constructor + # + # @endif + # + def __init__(self): + self._mgr = OpenRTM_aist.Manager.instance() + self._owner = None + self._rtcout = self._mgr.getLogbuf("ManagerServant") + self._isMain = False + self._mains = [] + self._subordinates = [] + self._mainMutex = threading.RLock() + self._subordinateMutex = threading.RLock() + self._objref = RTM.Manager._nil + + config = copy.deepcopy(self._mgr.getConfig()) + + if (not self.createINSManager()): + self._rtcout.RTC_WARN("Manager CORBA servant creation failed.") + return + self._rtcout.RTC_TRACE( + "Manager CORBA servant was successfully created.") + + if OpenRTM_aist.toBool(config.getProperty( + "manager.is_main"), "YES", "NO", True): + # this is main manager + self._rtcout.RTC_TRACE("This manager is main.") + self._isMain = True + return + else: + # this is subordinate manager + self._rtcout.RTC_TRACE("This manager is subordinate.") + try: + owner = self.findManager( + config.getProperty("corba.main_manager")) + if not owner: + self._rtcout.RTC_INFO("Main manager not found") + return + self.add_main_manager(owner) + owner.add_subordinate_manager(self._objref) + return + except BaseException: + self._rtcout.RTC_ERROR("Unknown exception cought.") + self._rtcout.RTC_ERROR(OpenRTM_aist.Logger.print_exception()) return - except: - self._rtcout.RTC_ERROR("Unknown exception cought.") - self._rtcout.RTC_ERROR(OpenRTM_aist.Logger.print_exception()) - return - - - - - - - - ## - # @if jp - # - # @brief ۥǥȥ饯 - # - # @else - # - # @brief Virtual destructor - # - # @endif - def __del__(self): - pass - - - - ## - # @if jp - # - # @brief λؿ - # - # @else - # - # @brief - # - # @endif - def exit(self): - guard_master = OpenRTM_aist.ScopedLock(self._masterMutex) - for i in range(len(self._masters)): - try: - if CORBA.is_nil(self._masters[i]): - continue - self._masters[i].remove_slave_manager(self._objref) - except: - self._masters[i] = RTM.Manager._nil - self._masters = [] - - guard_slave = OpenRTM_aist.ScopedLock(self._slaveMutex) - for i in range(len(self._slaves)): - try: - if CORBA.is_nil(self._slaves[i]): - continue - self._slaves[i].remove_master_manager(self._objref) - except: - self._slaves[i] = RTM.Manager._nil - self._slaves = [] - - del guard_slave - del guard_master - if not CORBA.is_nil(self._objref): - poa = self._mgr.getORB().resolve_initial_references("omniINSPOA") - poa.deactivate_object(poa.servant_to_id(self)) - #self._objref._release() - - return - - ## - # @if jp - # @brief ⥸塼ɤ - # - # ޥ͡˻ꤵ줿⥸塼ɤꤵ줿 - # ؿǽԤ - # - # @param pathname ⥸塼ؤΥѥ - # @param initfunc ⥸塼νؿ - # @return ꥿󥳡 - # - # @else - # @brief Loading a module - # - # This operation loads a specified loadable moduleand perform - # initialization with the specified function. - # - # @param pathname A path to a loading module. - # @param initfunc Module initialization function. - # @return The return code. - # - # @endif - # - # ReturnCode_t load_module(const char* pathname, const char* initfunc) - def load_module(self, pathname, initfunc): - self._rtcout.RTC_TRACE("ManagerServant::load_module(%s, %s)", (pathname, initfunc)) - self._mgr.load(pathname, initfunc) - return RTC.RTC_OK - - - ## - # @if jp - # @brief ⥸塼򥢥ɤ - # - # ޥ͡˻ꤵ줿⥸塼򥢥ɤ롣 - # - # @param pathname ⥸塼ؤΥѥ - # @return ꥿󥳡 - # - # @else - # @brief Unloading a module - # - # This operation unloads a specified loadable module. - # - # @param pathname A path to a loading module. - # @return The return code. - # - # @endif - # - # ReturnCode_t unload_module(const char* pathname) - def unload_module(self, pathname): - self._rtcout.RTC_TRACE("ManagerServant::unload_module(%s)", pathname) - self._mgr.unload(pathname) - return RTC.RTC_OK - - - ## - # @if jp - # @brief ɲǽʥ⥸塼Υץե - # - # ɲǽʥ⥸塼Υץե롣 - # - # @return ⥸塼ץե - # - # @else - # @brief Getting loadable module profiles - # - # This operation returns loadable module profiles. - # - # @return A module profile list. - # - # @endif - # - # ModuleProfileList* get_loadable_modules() - def get_loadable_modules(self): - self._rtcout.RTC_TRACE("get_loadable_modules()") - - # copy local module profiles - prof = self._mgr.getLoadableModules() - cprof = [ RTM.ModuleProfile([]) for i in prof ] - - for i in range(len(prof)): - OpenRTM_aist.NVUtil.copyFromProperties(cprof[i].properties, prof[i]) - - return cprof - - - ## - # @if jp - # @brief ɺѤߤΥ⥸塼Υץե - # - # ɺѤߤΥ⥸塼Υץե롣 - # - # @return ⥸塼ץե - # - # @else - # @brief Getting loaded module profiles - # - # This operation returns loaded module profiles. - # - # @return A module profile list. - # - # @endif - # - # ModuleProfileList* get_loaded_modules() - def get_loaded_modules(self): - self._rtcout.RTC_TRACE("get_loaded_modules()") - prof = self._mgr.getLoadedModules() - cprof = [RTM.ModuleProfile([]) for i in prof] - - for i in range(len(prof)): - OpenRTM_aist.NVUtil.copyFromProperties(cprof[i].properties, prof[i]) - - - if self._isMaster: - guard = OpenRTM_aist.ScopedLock(self._slaveMutex) - for slave in self._slaves[:]: - try: - profs = slave.get_loaded_modules() - cprof.extend(profs) - except: - self._rtcout.RTC_ERROR("Unknown exception cought.") - self._rtcout.RTC_DEBUG(OpenRTM_aist.Logger.print_exception()) - self._slaves.remove(slave) - - return cprof - - - ## - # @if jp - # @brief ݡͥȥեȥΥץե - # - # ɺѤߤΥ⥸塼ΤRTݡͥȤΥ⥸塼뤬 - # եȥΥץեΥꥹȤ롣 - # - # @return ݡͥȥեȥΥץեꥹ - # - # @else - # @brief Getting component factory profiles - # - # This operation returns component factory profiles from loaded - # RT-Component module factory profiles. - # - # @return An RT-Component factory profile list. - # - # @endif - # - # ModuleProfileList* get_factory_profiles() - def get_factory_profiles(self): - self._rtcout.RTC_TRACE("get_factory_profiles()") - prof = self._mgr.getFactoryProfiles() - cprof = [RTM.ModuleProfile([]) for i in prof] - - for i in range(len(prof)): - OpenRTM_aist.NVUtil.copyFromProperties(cprof[i].properties, prof[i]) - - - if self._isMaster: - guard = OpenRTM_aist.ScopedLock(self._slaveMutex) - for slave in self._slaves[:]: - try: - profs = slave.get_factory_profiles() - cprof.extend(profs) - except: - self._rtcout.RTC_ERROR("Unknown exception cought.") - self._rtcout.RTC_DEBUG(OpenRTM_aist.Logger.print_exception()) - self._slaves.remove(slave) - - return cprof - - - ## - # @if jp - # @brief ݡͥȤ - # - # ˻ꤵ줿ݡͥȤ롣 - # - # @return 줿RTݡͥ - # - # @else - # @brief Creating an RT-Component - # - # This operation creates RT-Component according to the string - # argument. - # - # @return A created RT-Component - # - # @endif - # - # RTObject_ptr create_component(const char* module_name) - def create_component(self, module_name): - - self._rtcout.RTC_TRACE("create_component(%s)", module_name) - - - rtc = self.createComponentByAddress(module_name) - if not CORBA.is_nil(rtc): - return rtc - - rtc = self.createComponentByManagerName(module_name) - - if not CORBA.is_nil(rtc): - return rtc - - - - #module_name = module_name.split("&")[0] - module_name = [module_name] - self.getParameterByModulename("manager_address",module_name) - manager_name = self.getParameterByModulename("manager_name",module_name) - module_name = module_name[0] - - comp_param = CompParam(module_name) - - - - if self._isMaster: - guard = OpenRTM_aist.ScopedLock(self._slaveMutex) - for slave in self._slaves[:]: - try: - prof = slave.get_configuration() - prop = OpenRTM_aist.Properties() - OpenRTM_aist.NVUtil.copyToProperties(prop, prof) - slave_lang = prop.getProperty("manager.language") - if slave_lang == comp_param.language(): - rtc = slave.create_component(module_name) - if not CORBA.is_nil(rtc): - return rtc - except: - self._rtcout.RTC_ERROR("Unknown exception cought.") - self._rtcout.RTC_DEBUG(OpenRTM_aist.Logger.print_exception()) - self._slaves.remove(slave) - del guard - if not manager_name: - module_name = module_name + "&manager_name=manager_%p" - + + ## + # @if jp + # + # @brief 仮想デストラクタ + # + # @else + # + # @brief Virtual destructor + # + # @endif + + def __del__(self): + pass + + ## + # @if jp + # + # @brief 終了関数 + # + # @else + # + # @brief + # + # @endif + + def exit(self): + guard_main = OpenRTM_aist.ScopedLock(self._mainMutex) + for main in self._mains: + try: + if CORBA.is_nil(main): + continue + main.remove_subordinate_manager(self._objref) + except BaseException: + pass + self._mains = [] + + guard_subordinate = OpenRTM_aist.ScopedLock(self._subordinateMutex) + for subordinate in self._subordinates: + try: + if CORBA.is_nil(subordinate): + continue + subordinate.remove_main_manager(self._objref) + except BaseException: + pass + self._subordinates = [] + + del guard_subordinate + del guard_main + if not CORBA.is_nil(self._objref): + poa = self._mgr.getORB().resolve_initial_references("omniINSPOA") + poa.deactivate_object(poa.servant_to_id(self)) + # self._objref._release() + + return + + ## + # @if jp + # @brief モジュールをロードする + # + # 当該マネージャに指定されたモジュールをロードし、指定された初期化 + # 関数で初期化を行う。 + # + # @param pathname モジュールへのパス + # @param initfunc モジュールの初期化関数 + # @return リターンコード + # + # @else + # @brief Loading a module + # + # This operation loads a specified loadable module、and perform + # initialization with the specified function. + # + # @param pathname A path to a loading module. + # @param initfunc Module initialization function. + # @return The return code. + # + # @endif + # + # ReturnCode_t load_module(const char* pathname, const char* initfunc) + def load_module(self, pathname, initfunc): + self._rtcout.RTC_TRACE( + "ManagerServant::load_module(%s, %s)", (pathname, initfunc)) + self._mgr.load(pathname, initfunc) + return RTC.RTC_OK + + ## + # @if jp + # @brief モジュールをアンロードする + # + # 当該マネージャに指定されたモジュールをアンロードする。 + # + # @param pathname モジュールへのパス + # @return リターンコード + # + # @else + # @brief Unloading a module + # + # This operation unloads a specified loadable module. + # + # @param pathname A path to a loading module. + # @return The return code. + # + # @endif + # + # ReturnCode_t unload_module(const char* pathname) + + def unload_module(self, pathname): + self._rtcout.RTC_TRACE("ManagerServant::unload_module(%s)", pathname) + self._mgr.unload(pathname) + return RTC.RTC_OK + + ## + # @if jp + # @brief ロード可能なモジュールのプロファイルを取得する + # + # ロード可能なモジュールのプロファイルを取得する。 + # + # @return モジュールプロファイル + # + # @else + # @brief Getting loadable module profiles + # + # This operation returns loadable module profiles. + # + # @return A module profile list. + # + # @endif + # + # ModuleProfileList* get_loadable_modules() + + def get_loadable_modules(self): + self._rtcout.RTC_TRACE("get_loadable_modules()") + + # copy local module profiles + prof = self._mgr.getLoadableModules() + cprof = [RTM.ModuleProfile([]) for i in prof] + + for i, p in enumerate(prof): + OpenRTM_aist.NVUtil.copyFromProperties( + cprof[i].properties, p) + + return cprof + + ## + # @if jp + # @brief ロード済みのモジュールのプロファイルを取得する + # + # ロード済みのモジュールのプロファイルを取得する。 + # + # @return モジュールプロファイル + # + # @else + # @brief Getting loaded module profiles + # + # This operation returns loaded module profiles. + # + # @return A module profile list. + # + # @endif + # + # ModuleProfileList* get_loaded_modules() + + def get_loaded_modules(self): + self._rtcout.RTC_TRACE("get_loaded_modules()") + prof = self._mgr.getLoadedModules() + cprof = [RTM.ModuleProfile([]) for i in prof] + + for i, p in enumerate(prof): + OpenRTM_aist.NVUtil.copyFromProperties( + cprof[i].properties, p) + + if self._isMain: + guard = OpenRTM_aist.ScopedLock(self._subordinateMutex) + for subordinate in self._subordinates[:]: + try: + profs = subordinate.get_loaded_modules() + cprof.extend(profs) + except BaseException: + self._rtcout.RTC_ERROR("Unknown exception cought.") + self._rtcout.RTC_DEBUG( + OpenRTM_aist.Logger.print_exception()) + self._subordinates.remove(subordinate) + + return cprof + + ## + # @if jp + # @brief コンポーネントファクトリのプロファイルを取得する + # + # ロード済みのモジュールのうち、RTコンポーネントのモジュールが持つ + # ファクトリのプロファイルのリストを取得する。 + # + # @return コンポーネントファクトリのプロファイルリスト + # + # @else + # @brief Getting component factory profiles + # + # This operation returns component factory profiles from loaded + # RT-Component module factory profiles. + # + # @return An RT-Component factory profile list. + # + # @endif + # + # ModuleProfileList* get_factory_profiles() + + def get_factory_profiles(self): + self._rtcout.RTC_TRACE("get_factory_profiles()") + prof = self._mgr.getFactoryProfiles() + cprof = [RTM.ModuleProfile([]) for i in prof] + + for i, p in enumerate(prof): + OpenRTM_aist.NVUtil.copyFromProperties( + cprof[i].properties, p) + + if self._isMain: + guard = OpenRTM_aist.ScopedLock(self._subordinateMutex) + for subordinate in self._subordinates[:]: + try: + profs = subordinate.get_factory_profiles() + cprof.extend(profs) + except BaseException: + self._rtcout.RTC_ERROR("Unknown exception cought.") + self._rtcout.RTC_DEBUG( + OpenRTM_aist.Logger.print_exception()) + self._subordinates.remove(subordinate) + + return cprof + + ## + # @if jp + # @brief コンポーネントを生成する + # + # 引数に指定されたコンポーネントを生成する。 + # + # @return 生成されたRTコンポーネント + # + # @else + # @brief Creating an RT-Component + # + # This operation creates RT-Component according to the string + # argument. + # + # @return A created RT-Component + # + # @endif + # + # RTObject_ptr create_component(const char* module_name) + def create_component(self, module_name): + + self._rtcout.RTC_TRACE("create_component(%s)", module_name) + + rtc = self.createComponentByAddress(module_name) + if not CORBA.is_nil(rtc): + return rtc + rtc = self.createComponentByManagerName(module_name) - return rtc - - else: - # create on this manager - rtc = self._mgr.createComponent(module_name) - if rtc: - return rtc.getObjRef() - - - - return RTC.RTObject._nil - - - - - - ## - # @if jp - # @brief ݡͥȤ - # - # ˻ꤵ줿ݡͥȤ롣 - # - # @return ꥿󥳡 - # - # @else - # @brief Deleting an RT-Component - # - # This operation delete an RT-Component according to the string - # argument. - # - # @return Return code - # - # @endif - # - # ReturnCode_t delete_component(const char* instance_name) - def delete_component(self, instance_name): - self._rtcout.RTC_TRACE("delete_component(%s)", instance_name) - comp_ = self._mgr.getComponent(instance_name) - if not comp_: - self._rtcout.RTC_WARN("No such component exists: %s", instance_name) - return RTC.BAD_PARAMETER - - try: - comp_.exit() - except: - self._rtcout.RTC_ERROR("Unknown exception was raised, when RTC was finalized.") - return RTC.RTC_ERROR - - return RTC.RTC_OK - - - ## - # @if jp - # @brief ưΥݡͥȤΥꥹȤ - # - # ޥ͡ǵưΥݡͥȤΥꥹȤ֤ - # - # @return RTݡͥȤΥꥹ - # - # @else - # @brief Getting RT-Component list running on this manager - # - # This operation returns RT-Component list running on this manager. - # - # @return A list of RT-Components - # - # @endif - # - # RTCList* get_components() - def get_components(self): - self._rtcout.RTC_TRACE("get_components()") - - # get local component references - rtcs = self._mgr.getComponents() - crtcs = [] - - for rtc in rtcs: - crtcs.append(rtc.getObjRef()) - - # get slaves' component references - self._rtcout.RTC_DEBUG("%d slave managers exists.", len(self._slaves)) - for slave in self._slaves[:]: - try: - if not CORBA.is_nil(slave): - srtcs = slave.get_components() - OpenRTM_aist.CORBA_SeqUtil.push_back_list(crtcs, srtcs) - - except: - self._rtcout.RTC_ERROR("Unknown exception cought.") - self._rtcout.RTC_DEBUG(OpenRTM_aist.Logger.print_exception()) - self._slaves.remove(slave) - #self._rtcout.RTC_INFO("slave (%d) has disappeared.", i) - #self._slaves[i] = RTM.Manager._nil - - #OpenRTM_aist.CORBA_SeqUtil.erase(self._slaves, i) - #i -= 1 - - return crtcs - - - ## - # @if jp - # @brief ưΥݡͥȥץեΥꥹȤ - # - # ޥ͡ǵưΥݡͥȤΥץեΥꥹ - # Ȥ֤ - # - # @return RTݡͥȥץեΥꥹ - # - # @else - # @brief Getting RT-Component's profile list running on this manager - # - # This operation returns RT-Component's profile list running on - # this manager. - # - # @return A list of RT-Components' profiles - # - # @endif - # - # ComponentProfileList* get_component_profiles() - def get_component_profiles(self): - rtcs = self._mgr.getComponents() - cprofs = [rtc.get_component_profile() for rtc in rtcs] - - # copy slaves' component profiles - guard = OpenRTM_aist.ScopedLock(self._slaveMutex) - self._rtcout.RTC_DEBUG("%d slave managers exists.", len(self._slaves)) - - for slave in self._slaves[:]: - try: - if not CORBA.is_nil(slave): - sprofs = slave.get_component_profiles() - OpenRTM_aist.CORBA_SeqUtil.push_back_list(cprofs, sprofs) - except: - self._rtcout.RTC_ERROR("Unknown exception cought.") - self._rtcout.RTC_DEBUG(OpenRTM_aist.Logger.print_exception()) - self._slaves.remove(slave) - #self._rtcout.RTC_INFO("slave (%d) has disappeared.", i) - #self._slaves[i] = RTM.Manager._nil - - #OpenRTM_aist.CORBA_SeqUtil.erase(self._slaves, i) - #i -= 1 - - del guard - return cprofs - - - ## - # @if jp - # @brief ޥ͡Υץե - # - # ޥ͡Υץե롣 - # - # @return ޥ͡ץե - # - # @else - # @brief Getting this manager's profile. - # - # This operation returns this manager's profile. - # - # @return Manager's profile - # - # @endif - # - # ManagerProfile* get_profile() - def get_profile(self): - self._rtcout.RTC_TRACE("get_profile()") - prof = RTM.ModuleProfile([]) - OpenRTM_aist.NVUtil.copyFromProperties(prof.properties, self._mgr.getConfig().getNode("manager")) - - return prof - - - ## - # @if jp - # @brief ޥ͡Υե졼 - # - # ޥ͡Υե졼롣 - # - # @return ޥ͡㥳ե졼 - # - # @else - # @brief Getting this manager's configuration. - # - # This operation returns this manager's configuration. - # - # @return Manager's configuration - # - # @endif - # - # NVList* get_configuration() - def get_configuration(self): - self._rtcout.RTC_TRACE("get_configuration()") - nvlist = [] - OpenRTM_aist.NVUtil.copyFromProperties(nvlist, self._mgr.getConfig()) - return nvlist - - - ## - # @if jp - # @brief ޥ͡Υե졼ꤹ - # - # ޥ͡Υե졼ꤹ롣 - # - # @param name åȤ륳ե졼Υ̾ - # @param value åȤ륳ե졼 - # @return ꥿󥳡 - # - # @else - # @brief Setting manager's configuration - # - # This operation sets managers configuration. - # - # @param name A configuration key name to be set - # @param value A configuration value to be set - # @return Return code - # - # @endif - # - # ReturnCode_t set_configuration(const char* name, const char* value) - def set_configuration(self, name, value): - self._rtcout.RTC_TRACE("set_configuration(name = %s, value = %s)", (name, value)) - self._mgr.getConfig().setProperty(name, value) - return RTC.RTC_OK - - - - ## - # @if jp - # @brief ޥ͡㤬ޥɤ - # - # δؿϥޥ͡㤬ޥɤ֤TrueʤС - # ͡ϥޥǤꡢʳ False ֤ - # - # @return ޥޥ͡㤫ɤbool - # - # @else - # @brief Whether this manager is master or not - # - # It returns "True" if this manager is a master, and it returns - # "False" in other cases. - # - # @return A boolean value that means it is master or not. - # - # @endif - # - # bool is_master(); - def is_master(self): - # since Python2.5 - # self._rtcout.RTC_TRACE("is_master(): %s", (lambda x: "YES" if x else "NO")(self._isMaster)) - ret = "" - if self._isMaster: - ret = "YES" - else: - ret = "NO" - self._rtcout.RTC_TRACE("is_master(): %s", ret) - return self._isMaster - - - ## - # @if jp - # @brief ޥޥ͡μ - # - # Υޥ͡㤬졼֥ޥ͡ξ硢ޥȤʤäƤ - # ͡ΥꥹȤ֤Υޥ͡㤬ޥξ硢Υꥹ - # Ȥ֤롣 - # - # @return ޥޥ͡Υꥹ - # - # @else - # @brief Getting master managers - # - # This operation returns master manager list if this manager is - # slave. If this manager is master, an empty sequence would be - # returned. - # - # @return Master manager list - # - # @endif - # - # RTM::ManagerList* get_master_managers(); - def get_master_managers(self): - self._rtcout.RTC_TRACE("get_master_managers()") - guard = OpenRTM_aist.ScopedLock(self._masterMutex) - - return self._masters - - - ## - # @if jp - # @brief ޥޥ͡ɲ - # - # Υޥ͡ΥޥȤƥޥ͡ɲä롣ͤˤϡ - # ޥ͡ɲä줿ޥޥ̤͡ˡ - # ID֤롣Υޥ͡㤬ޥξ硢IDǻꤵ줿 - # ޥޥ֤͡IDǻꤵ줿ޥޥ͡㤬ʤ - # 硢nil֥Ȥ֤롣 - # - # @return ޥޥ͡ - # - # @else - # @brief Getting a master manager - # - # This operation returns a master manager with specified id. If - # the manager with the specified id does not exist, nil object - # reference would be returned. - # - # @return A master manager - # - # @endif - # - # RTC::ReturnCode_t add_master_manager(RTM::Manager_ptr mgr); - def add_master_manager(self, mgr): - guard = OpenRTM_aist.ScopedLock(self._masterMutex) - self._rtcout.RTC_TRACE("add_master_manager(), %d masters", len(self._masters)) - index = OpenRTM_aist.CORBA_SeqUtil.find(self._masters, self.is_equiv(mgr)) - - if not (index < 0): # found in my list - self._rtcout.RTC_ERROR("Already exists.") - return RTC.BAD_PARAMETER - - OpenRTM_aist.CORBA_SeqUtil.push_back(self._masters, mgr) - self._rtcout.RTC_TRACE("add_master_manager() done, %d masters", len(self._masters)) - del guard - return RTC.RTC_OK - - - ## - # @if jp - # @brief ޥޥ͡κ - # - # Υޥ͡㤬ݻޥΤꤵ줿Τ롣 - # - # @param mgr ޥޥ͡ - # @return ReturnCode_t - # - # @else - # @brief Removing a master manager - # - # This operation removes a master manager from this manager. - # - # @param mgr A master manager - # @return ReturnCode_t - # - # @endif - # - # RTC::ReturnCode_t remove_master_manager(RTM::Manager_ptr mgr); - def remove_master_manager(self, mgr): - guard = OpenRTM_aist.ScopedLock(self._masterMutex) - self._rtcout.RTC_TRACE("remove_master_manager(), %d masters", len(self._masters)) - - index = OpenRTM_aist.CORBA_SeqUtil.find(self._masters, self.is_equiv(mgr)) - - if index < 0: # not found in my list - self._rtcout.RTC_ERROR("Not found.") - return RTC.BAD_PARAMETER - - OpenRTM_aist.CORBA_SeqUtil.erase(self._masters, index) - self._rtcout.RTC_TRACE("remove_master_manager() done, %d masters", len(self._masters)) - del guard - return RTC.RTC_OK - - - ## - # @if jp - # @brief 졼֥ޥ͡μ - # - # Υޥ͡㤬졼֥ޥ͡ξ硢졼֤ȤʤäƤ - # ͡ΥꥹȤ֤Υޥ͡㤬졼֤ξ硢Υꥹ - # Ȥ֤롣 - # - # @return 졼֥ޥ͡Υꥹ - # - # @else - # @brief Getting slave managers - # - # This operation returns slave manager list if this manager is - # slave. If this manager is slave, an empty sequence would be - # returned. - # - # @return Slave manager list - # - # @endif - # - # RTM::ManagerList* get_slave_managers(); - def get_slave_managers(self): - guard = OpenRTM_aist.ScopedLock(self._slaveMutex) - self._rtcout.RTC_TRACE("get_slave_managers(), %d slaves", len(self._slaves)) - return self._slaves - - - ## - # @if jp - # @brief 졼֥ޥ͡ɲ - # - # Υޥ͡ΥޥȤƥޥ͡ɲä롣 - # - # @param mgr 졼֥ޥ͡ - # @return ReturnCode_t - # - # @else - # @brief Getting a slave manager - # - # This operation add a slave manager to this manager. - # - # @param mgr A slave manager - # @return ReturnCode_t - # - # @endif - # - # RTC::ReturnCode_t add_slave_manager(RTM::Manager_ptr mgr); - def add_slave_manager(self, mgr): - guard = OpenRTM_aist.ScopedLock(self._slaveMutex) - self._rtcout.RTC_TRACE("add_slave_manager(), %d slaves", len(self._slaves)) - - index = OpenRTM_aist.CORBA_SeqUtil.find(self._slaves, self.is_equiv(mgr)) - - if not (index < 0): # found in my list - self._rtcout.RTC_ERROR("Already exists.") - return RTC.BAD_PARAMETER - - OpenRTM_aist.CORBA_SeqUtil.push_back(self._slaves, mgr) - self._rtcout.RTC_TRACE("add_slave_manager() done, %d slaves", len(self._slaves)) - del guard - return RTC.RTC_OK - - - ## - # @if jp - # @brief 졼֥ޥ͡κ - # - # Υޥ͡㤬ݻޥΤꤵ줿Τ롣 - # - # @param mgr 졼֥ޥ͡ - # @return ReturnCode_t - # - # @else - # @brief Removing a slave manager - # - # This operation removes a slave manager from this manager. - # - # @param mgr A slave manager - # @return ReturnCode_t - # - # @endif - # - # RTC::ReturnCode_t remove_slave_manager(RTM::Manager_ptr mgr); - def remove_slave_manager(self, mgr): - guard = OpenRTM_aist.ScopedLock(self._slaveMutex) - self._rtcout.RTC_TRACE("remove_slave_manager(), %d slaves", len(self._slaves)) - index = OpenRTM_aist.CORBA_SeqUtil.find(self._slaves, self.is_equiv(mgr)) - - if index < 0: # not found in my list - self._rtcout.RTC_ERROR("Not found.") - return RTC.BAD_PARAMETER - - OpenRTM_aist.CORBA_SeqUtil.erase(self._slaves, index) - self._rtcout.RTC_TRACE("remove_slave_manager() done, %d slaves", len(self._slaves)) - del guard - return RTC.RTC_OK - - - ## - # @if jp - # @brief ץΥԡ - # @return ReturnCode_t - # @else - # @brief The copy of the process is generated. - # @return ReturnCode_t - # @endif - # - # ReturnCode_t fork() - def fork(self): - # self._mgr.fork() - pid = OpenRTM_aist.fork() - if pid >= 0: - return RTC.RTC_OK - else: - return RTC.RTC_ERROR - - - ## - # @if jp - # @brief shutdown - # @return ReturnCode_t - # @else - # @brief This method shutdowns RTC. - # @return ReturnCode_t - # @endif - # - # ReturnCode_t shutdown() - def shutdown(self): - guard_master = OpenRTM_aist.ScopedLock(self._masterMutex) - for i in range(len(self._masters)): - try: - if CORBA.is_nil(self._masters[i]): - continue - self._masters[i].remove_slave_manager(self._objref) - except: - self._masters[i] = RTM.Manager._nil - self._masters = [] - - guard_slave = OpenRTM_aist.ScopedLock(self._slaveMutex) - for i in range(len(self._slaves)): - try: - if CORBA.is_nil(self._slaves[i]): - continue - self._slaves[i].remove_master_manager(self._objref) - except: - self._slaves[i] = RTM.Manager._nil - self._slaves = [] - - wait_time = 1.0 - if self._mgr.getConfig().findNode("manager.termination_waittime"): - s = self._mgr.getConfig().getProperty("manager.termination_waittime") - ret = [wait_time] - if OpenRTM_aist.stringTo(ret, s): - wait_time = ret[0] - - - self._mgr.createShutdownThread(wait_time) - - return RTC.RTC_OK - - - ## - # @if jp - # @brief Ƶư롣 - # @return ReturnCode_t - # @else - # @brief This method restarts RTC. - # @return ReturnCode_t - # @endif - # - # ReturnCode_t restart() - def restart(self): - # self._mgr.restart() - return RTC.RTC_OK - - - ## - # @if jp - # @brief RTCΥե󥹤롣 - # @return RTCΥե - # @else - # @brief Get the reference of RTC. - # @return RTC reference - # @endif - # - # Object_ptr get_service(const char* name) - def get_service(self, name): - return CORBA.Object._nil - - - ## - # @if jp - # @brief ManagerΥե󥹤롣 - # @return ManagerΥե - # @else - # @brief Get the reference of Manager. - # @return Manager reference - # @endif - # - # Manager_ptr getObjRef() const - def getObjRef(self): - return self._objref - - - ## - # @if jp - # @brief INSManager - # @return - # @else :true, :false - # @brief Generate INSManager. - # @return Successful:true, Failed:false - # @endif - # - # bool createINSManager(); - def createINSManager(self): - try: - poa = self._mgr.getORB().resolve_initial_references("omniINSPOA") - poa._get_the_POAManager().activate() - id = self._mgr.getConfig().getProperty("manager.name") - poa.activate_object_with_id(id, self) - mgrobj = poa.id_to_reference(id) - self._objref = mgrobj._narrow(RTM.Manager) - except: - self._rtcout.RTC_DEBUG(OpenRTM_aist.Logger.print_exception()) - return False - - return True - - - - ## - # @if jp - # @brief ManagerΥե󥹤򸡺롣 - # @return ManagerΥե - # @else - # @brief Find the reference of Manager. - # @return Manager reference - # @endif - # - # RTM::Manager_ptr findManager(const char* host_port); - def findManager(self, host_port): - self._rtcout.RTC_TRACE("findManager(host_port = %s)", host_port) - try: - config = copy.deepcopy(self._mgr.getConfig()) - mgrloc = "corbaloc:iiop:" - mgrloc += host_port - mgrloc += "/" + config.getProperty("manager.name") - - self._rtcout.RTC_DEBUG("corbaloc: %s", mgrloc) - - mobj = self._mgr.getORB().string_to_object(mgrloc) - mgr = mobj._narrow(RTM.Manager) - - return mgr - - except CORBA.SystemException: - self._rtcout.RTC_DEBUG(OpenRTM_aist.Logger.print_exception()) - - except: - self._rtcout.RTC_ERROR("Unknown exception cought.") - self._rtcout.RTC_DEBUG(OpenRTM_aist.Logger.print_exception()) - - return RTM.Manager._nil - - ## - # @if jp - # @brief ̾RTC - # @param self - # @param name RTC̾ - # @return RTCΥꥹ - # @else - # - # @brief - # @param self - # @param name - # @return - # @endif - # RTCList get_components_by_name(string name) - def get_components_by_name(self, name): - self._rtcout.RTC_TRACE("get_components_by_name()") - rtcs = self._mgr.getComponents() - crtcs = [] - tmp = [name] - OpenRTM_aist.eraseHeadBlank(tmp) - name = tmp[0] - rtc_name = name.split("/") - for rtc in rtcs: - if len(rtc_name) == 1: - if rtc.getInstanceName() == rtc_name[0]: - crtcs.append(rtc.getObjRef()) - else: - if rtc_name[0] == "*": - if rtc.getInstanceName() == rtc_name[1]: + + if not CORBA.is_nil(rtc): + return rtc + + #module_name = module_name.split("&")[0] + _, module_name = self.getParameterByModulename( + "manager_address", module_name) + manager_name, module_name = self.getParameterByModulename( + "manager_name", module_name) + + comp_param = CompParam(module_name) + + if self._isMain: + guard = OpenRTM_aist.ScopedLock(self._subordinateMutex) + for subordinate in self._subordinates[:]: + try: + prof = subordinate.get_configuration() + prop = OpenRTM_aist.Properties() + OpenRTM_aist.NVUtil.copyToProperties(prop, prof) + subordinate_lang = prop.getProperty("manager.language") + if subordinate_lang == comp_param.language(): + rtc = subordinate.create_component(module_name) + if not CORBA.is_nil(rtc): + return rtc + except BaseException: + self._rtcout.RTC_ERROR("Unknown exception cought.") + self._rtcout.RTC_DEBUG( + OpenRTM_aist.Logger.print_exception()) + self._subordinates.remove(subordinate) + del guard + if not manager_name: + module_name = module_name + "&manager_name=manager_%p" + + rtc = self.createComponentByManagerName(module_name) + return rtc + + else: + # create on this manager + rtc = self._mgr.createComponent(module_name) + if rtc: + return rtc.getObjRef() + + return RTC.RTObject._nil + + ## + # @if jp + # @brief コンポーネントを削除する + # + # 引数に指定されたコンポーネントを削除する。 + # + # @return リターンコード + # + # @else + # @brief Deleting an RT-Component + # + # This operation delete an RT-Component according to the string + # argument. + # + # @return Return code + # + # @endif + # + # ReturnCode_t delete_component(const char* instance_name) + + def delete_component(self, instance_name): + self._rtcout.RTC_TRACE("delete_component(%s)", instance_name) + comp_ = self._mgr.getComponent(instance_name) + if not comp_: + self._rtcout.RTC_WARN( + "No such component exists: %s", + instance_name) + return RTC.BAD_PARAMETER + + try: + comp_.exit() + except BaseException: + self._rtcout.RTC_ERROR( + "Unknown exception was raised, when RTC was finalized.") + return RTC.RTC_ERROR + + return RTC.RTC_OK + + ## + # @if jp + # @brief 起動中のコンポーネントのリストを取得する + # + # 現在当該マネージャ上で起動中のコンポーネントのリストを返す。 + # + # @return RTコンポーネントのリスト + # + # @else + # @brief Getting RT-Component list running on this manager + # + # This operation returns RT-Component list running on this manager. + # + # @return A list of RT-Components + # + # @endif + # + # RTCList* get_components() + + def get_components(self): + self._rtcout.RTC_TRACE("get_components()") + + # get local component references + rtcs = self._mgr.getComponents() + crtcs = [] + + for rtc in rtcs: crtcs.append(rtc.getObjRef()) + + # get subordinates' component references + self._rtcout.RTC_DEBUG("%d subordinate managers exists.", len(self._subordinates)) + for subordinate in self._subordinates[:]: + try: + if not CORBA.is_nil(subordinate): + srtcs = subordinate.get_components() + OpenRTM_aist.CORBA_SeqUtil.push_back_list(crtcs, srtcs) + + except BaseException: + self._rtcout.RTC_ERROR("Unknown exception cought.") + self._rtcout.RTC_DEBUG(OpenRTM_aist.Logger.print_exception()) + self._subordinates.remove(subordinate) + #self._rtcout.RTC_INFO("subordinate (%d) has disappeared.", i) + #self._subordinates[i] = RTM.Manager._nil + + #OpenRTM_aist.CORBA_SeqUtil.erase(self._subordinates, i) + #i -= 1 + + return crtcs + + ## + # @if jp + # @brief 起動中のコンポーネントプロファイルのリストを取得する + # + # 現在当該マネージャ上で起動中のコンポーネントのプロファイルのリス + # トを返す。 + # + # @return RTコンポーネントプロファイルのリスト + # + # @else + # @brief Getting RT-Component's profile list running on this manager + # + # This operation returns RT-Component's profile list running on + # this manager. + # + # @return A list of RT-Components' profiles + # + # @endif + # + # ComponentProfileList* get_component_profiles() + + def get_component_profiles(self): + rtcs = self._mgr.getComponents() + cprofs = [rtc.get_component_profile() for rtc in rtcs] + + # copy subordinates' component profiles + guard = OpenRTM_aist.ScopedLock(self._subordinateMutex) + self._rtcout.RTC_DEBUG("%d subordinate managers exists.", len(self._subordinates)) + + for subordinate in self._subordinates[:]: + try: + if not CORBA.is_nil(subordinate): + sprofs = subordinate.get_component_profiles() + OpenRTM_aist.CORBA_SeqUtil.push_back_list(cprofs, sprofs) + except BaseException: + self._rtcout.RTC_ERROR("Unknown exception cought.") + self._rtcout.RTC_DEBUG(OpenRTM_aist.Logger.print_exception()) + self._subordinates.remove(subordinate) + #self._rtcout.RTC_INFO("subordinate (%d) has disappeared.", i) + #self._subordinates[i] = RTM.Manager._nil + + #OpenRTM_aist.CORBA_SeqUtil.erase(self._subordinates, i) + #i -= 1 + + del guard + return cprofs + + ## + # @if jp + # @brief マネージャのプロファイルを取得する + # + # 現在当該マネージャのプロファイルを取得する。 + # + # @return マネージャプロファイル + # + # @else + # @brief Getting this manager's profile. + # + # This operation returns this manager's profile. + # + # @return Manager's profile + # + # @endif + # + # ManagerProfile* get_profile() + + def get_profile(self): + self._rtcout.RTC_TRACE("get_profile()") + prof = RTM.ModuleProfile([]) + OpenRTM_aist.NVUtil.copyFromProperties( + prof.properties, self._mgr.getConfig().getNode("manager")) + + return prof + + ## + # @if jp + # @brief マネージャのコンフィギュレーションを取得する + # + # 現在当該マネージャのコンフィギュレーションを取得する。 + # + # @return マネージャコンフィギュレーション + # + # @else + # @brief Getting this manager's configuration. + # + # This operation returns this manager's configuration. + # + # @return Manager's configuration + # + # @endif + # + # NVList* get_configuration() + + def get_configuration(self): + self._rtcout.RTC_TRACE("get_configuration()") + nvlist = [] + OpenRTM_aist.NVUtil.copyFromProperties(nvlist, self._mgr.getConfig()) + return nvlist + + ## + # @if jp + # @brief マネージャのコンフィギュレーションを設定する + # + # 現在当該マネージャのコンフィギュレーションを設定する。 + # + # @param name セットするコンフィギュレーションのキー名 + # @param value セットするコンフィギュレーションの値 + # @return リターンコード + # + # @else + # @brief Setting manager's configuration + # + # This operation sets managers configuration. + # + # @param name A configuration key name to be set + # @param value A configuration value to be set + # @return Return code + # + # @endif + # + # ReturnCode_t set_configuration(const char* name, const char* value) + + def set_configuration(self, name, value): + self._rtcout.RTC_TRACE( + "set_configuration(name = %s, value = %s)", (name, value)) + self._mgr.getConfig().setProperty(name, value) + return RTC.RTC_OK + + ## + # @if jp + # @brief マネージャがマスターかどうか + # + # この関数はマネージャがマスターかどうかを返す。Trueならば、当該マ + # ネージャはマスターであり、それ以外は False を返す。 + # + # @return マスターマネージャかどうかのbool値 + # + # @else + # @brief Whether this manager is main or not + # + # It returns "True" if this manager is a main, and it returns + # "False" in other cases. + # + # @return A boolean value that means it is main or not. + # + # @endif + # + # bool is_main(); + + def is_main(self): + # since Python2.5 + # self._rtcout.RTC_TRACE("is_main(): %s", (lambda x: "YES" if x else "NO")(self._isMain)) + ret = "" + if self._isMain: + ret = "YES" + else: + ret = "NO" + self._rtcout.RTC_TRACE("is_main(): %s", ret) + return self._isMain + + ## + # @if jp + # @brief マスターマネージャの取得 + # + # このマネージャがスレーブマネージャの場合、マスターとなっているマ + # ネージャのリストを返す。このマネージャがマスターの場合、空のリス + # トが返る。 + # + # @return マスターマネージャのリスト + # + # @else + # @brief Getting main managers + # + # This operation returns main manager list if this manager is + # subordinate. If this manager is main, an empty sequence would be + # returned. + # + # @return Main manager list + # + # @endif + # + # RTM::ManagerList* get_main_managers(); + + def get_main_managers(self): + self._rtcout.RTC_TRACE("get_main_managers()") + guard = OpenRTM_aist.ScopedLock(self._mainMutex) + + return self._mains + + ## + # @if jp + # @brief マスターマネージャの追加 + # + # このマネージャのマスタとしてマネージャを一つ追加する。戻り値には、 + # 当該マネージャ上で追加されたマスターマネージャを識別するユニーク + # なIDが返される。このマネージャがマスタの場合、当該IDで指定された + # マスターマネージャを返す。IDで指定されたマスターマネージャがない + # 場合、nilオブジェクトが返る。 + # + # @return マスターマネージャ + # + # @else + # @brief Getting a main manager + # + # This operation returns a main manager with specified id. If + # the manager with the specified id does not exist, nil object + # reference would be returned. + # + # @return A main manager + # + # @endif + # + # RTC::ReturnCode_t add_main_manager(RTM::Manager_ptr mgr); + + def add_main_manager(self, mgr): + guard = OpenRTM_aist.ScopedLock(self._mainMutex) + self._rtcout.RTC_TRACE( + "add_main_manager(), %d mains", len( + self._mains)) + index = OpenRTM_aist.CORBA_SeqUtil.find( + self._mains, self.is_equiv(mgr)) + + if not (index < 0): # found in my list + self._rtcout.RTC_ERROR("Already exists.") + return RTC.BAD_PARAMETER + + OpenRTM_aist.CORBA_SeqUtil.push_back(self._mains, mgr) + self._rtcout.RTC_TRACE( + "add_main_manager() done, %d mains", len( + self._mains)) + del guard + return RTC.RTC_OK + + ## + # @if jp + # @brief マスターマネージャの削除 + # + # このマネージャが保持するマスタのうち、指定されたものを削除する。 + # + # @param mgr マスターマネージャ + # @return ReturnCode_t + # + # @else + # @brief Removing a main manager + # + # This operation removes a main manager from this manager. + # + # @param mgr A main manager + # @return ReturnCode_t + # + # @endif + # + # RTC::ReturnCode_t remove_main_manager(RTM::Manager_ptr mgr); + + def remove_main_manager(self, mgr): + guard = OpenRTM_aist.ScopedLock(self._mainMutex) + self._rtcout.RTC_TRACE( + "remove_main_manager(), %d mains", len( + self._mains)) + + index = OpenRTM_aist.CORBA_SeqUtil.find( + self._mains, self.is_equiv(mgr)) + + if index < 0: # not found in my list + self._rtcout.RTC_ERROR("Not found.") + return RTC.BAD_PARAMETER + + OpenRTM_aist.CORBA_SeqUtil.erase(self._mains, index) + self._rtcout.RTC_TRACE( + "remove_main_manager() done, %d mains", len( + self._mains)) + del guard + return RTC.RTC_OK + + ## + # @if jp + # @brief スレーブマネージャの取得 + # + # このマネージャがスレーブマネージャの場合、スレーブとなっているマ + # ネージャのリストを返す。このマネージャがスレーブの場合、空のリス + # トが返る。 + # + # @return スレーブマネージャのリスト + # + # @else + # @brief Getting subordinate managers + # + # This operation returns subordinate manager list if this manager is + # subordinate. If this manager is subordinate, an empty sequence would be + # returned. + # + # @return Subordinate manager list + # + # @endif + # + # RTM::ManagerList* get_subordinate_managers(); + + def get_subordinate_managers(self): + guard = OpenRTM_aist.ScopedLock(self._subordinateMutex) + self._rtcout.RTC_TRACE( + "get_subordinate_managers(), %d subordinates", len( + self._subordinates)) + return self._subordinates + + ## + # @if jp + # @brief スレーブマネージャの追加 + # + # このマネージャのマスタとしてマネージャを一つ追加する。 + # + # @param mgr スレーブマネージャ + # @return ReturnCode_t + # + # @else + # @brief Getting a subordinate manager + # + # This operation add a subordinate manager to this manager. + # + # @param mgr A subordinate manager + # @return ReturnCode_t + # + # @endif + # + # RTC::ReturnCode_t add_subordinate_manager(RTM::Manager_ptr mgr); + + def add_subordinate_manager(self, mgr): + guard = OpenRTM_aist.ScopedLock(self._subordinateMutex) + self._rtcout.RTC_TRACE( + "add_subordinate_manager(), %d subordinates", len( + self._subordinates)) + + index = OpenRTM_aist.CORBA_SeqUtil.find( + self._subordinates, self.is_equiv(mgr)) + + if not (index < 0): # found in my list + self._rtcout.RTC_ERROR("Already exists.") + return RTC.BAD_PARAMETER + + OpenRTM_aist.CORBA_SeqUtil.push_back(self._subordinates, mgr) + self._rtcout.RTC_TRACE( + "add_subordinate_manager() done, %d subordinates", len( + self._subordinates)) + del guard + return RTC.RTC_OK + + ## + # @if jp + # @brief スレーブマネージャの削除 + # + # このマネージャが保持するマスタのうち、指定されたものを削除する。 + # + # @param mgr スレーブマネージャ + # @return ReturnCode_t + # + # @else + # @brief Removing a subordinate manager + # + # This operation removes a subordinate manager from this manager. + # + # @param mgr A subordinate manager + # @return ReturnCode_t + # + # @endif + # + # RTC::ReturnCode_t remove_subordinate_manager(RTM::Manager_ptr mgr); + + def remove_subordinate_manager(self, mgr): + guard = OpenRTM_aist.ScopedLock(self._subordinateMutex) + self._rtcout.RTC_TRACE( + "remove_subordinate_manager(), %d subordinates", len( + self._subordinates)) + index = OpenRTM_aist.CORBA_SeqUtil.find( + self._subordinates, self.is_equiv(mgr)) + + if index < 0: # not found in my list + self._rtcout.RTC_ERROR("Not found.") + return RTC.BAD_PARAMETER + + OpenRTM_aist.CORBA_SeqUtil.erase(self._subordinates, index) + self._rtcout.RTC_TRACE( + "remove_subordinate_manager() done, %d subordinates", len( + self._subordinates)) + del guard + return RTC.RTC_OK + + ## + # @if jp + # @brief プロセスのコピーを生成する + # @return ReturnCode_t + # @else + # @brief The copy of the process is generated. + # @return ReturnCode_t + # @endif + # + # ReturnCode_t fork() + + def fork(self): + # self._mgr.fork() + pid = OpenRTM_aist.fork() + if pid >= 0: + return RTC.RTC_OK else: - if rtc.getCategory() == rtc_name[0]: - if rtc.getInstanceName() == rtc_name[1]: - crtcs.append(rtc.getObjRef()) - - - - - return crtcs - - ## - # @if jp - # @brief ̾Υޥ͡ - # ޥ͡㤬ޥξϿƤ륹졼֥ޥ͡㤫鸡 - # ޥ͡㤬졼֤ξϿƤޥޥ͡㤫饹졼֥ޥ͡򸡺 - # @param self - # @param manager_name ޥ̾͡ - # @return ޥ͡ - # @else - # - # @brief - # @param self - # @param manager_name - # @return - # @endif - # RTC::Manager_ptr findManagerByName(string manager_name) - def findManagerByName(self, manager_name): - self._rtcout.RTC_TRACE("findManagerByName(manager_name = %s)", manager_name) - prop = self._mgr.getConfig() - name = prop.getProperty("manager.instance_name") - if name == manager_name: - return self.getObjRef() - if self._isMaster: - guard = OpenRTM_aist.ScopedLock(self._slaveMutex) - for slave in self._slaves[:]: + return RTC.RTC_ERROR + + ## + # @if jp + # @brief shutdownする + # @return ReturnCode_t + # @else + # @brief This method shutdowns RTC. + # @return ReturnCode_t + # @endif + # + # ReturnCode_t shutdown() + + def shutdown(self): + guard_main = OpenRTM_aist.ScopedLock(self._mainMutex) + for main in self._mains: + try: + if CORBA.is_nil(main): + continue + main.remove_subordinate_manager(self._objref) + except BaseException: + pass + self._mains = [] + + guard_subordinate = OpenRTM_aist.ScopedLock(self._subordinateMutex) + for subordinates in self._subordinates: + try: + if CORBA.is_nil(subordinates): + continue + subordinates.remove_main_manager(self._objref) + except BaseException: + pass + self._subordinates = [] + + wait_time = 1.0 + if self._mgr.getConfig().findNode("manager.termination_waittime"): + s = self._mgr.getConfig().getProperty("manager.termination_waittime") + ret, wait_time = OpenRTM_aist.stringTo(wait_time, s) + + self._mgr.terminate() + + return RTC.RTC_OK + + ## + # @if jp + # @brief 再起動する。 + # @return ReturnCode_t + # @else + # @brief This method restarts RTC. + # @return ReturnCode_t + # @endif + # + # ReturnCode_t restart() + + def restart(self): + # self._mgr.restart() + return RTC.RTC_OK + + ## + # @if jp + # @brief RTCのリファレンスを取得する。 + # @return RTCのリファレンス + # @else + # @brief Get the reference of RTC. + # @return RTC reference + # @endif + # + # Object_ptr get_service(const char* name) + + def get_service(self, name): + return CORBA.Object._nil + + ## + # @if jp + # @brief Managerのリファレンスを取得する。 + # @return Managerのリファレンス + # @else + # @brief Get the reference of Manager. + # @return Manager reference + # @endif + # + # Manager_ptr getObjRef() const + + def getObjRef(self): + return self._objref + + ## + # @if jp + # @brief INSManagerの生成 + # @return + # @else 成功:true, 失敗:false + # @brief Generate INSManager. + # @return Successful:true, Failed:false + # @endif + # + # bool createINSManager(); + + def createINSManager(self): try: - prof = slave.get_configuration() - prop = OpenRTM_aist.Properties() - OpenRTM_aist.NVUtil.copyToProperties(prop, prof) - name = prop.getProperty("manager.instance_name") - if name == manager_name: - return slave - - except: - self._rtcout.RTC_ERROR("Unknown exception cought.") - self._rtcout.RTC_DEBUG(OpenRTM_aist.Logger.print_exception()) - self._slaves.remove(slave) - del guard - else: - guard = OpenRTM_aist.ScopedLock(self._masterMutex) - for master in self._masters: + poa = self._mgr.getORB().resolve_initial_references("omniINSPOA") + poa._get_the_POAManager().activate() + id = self._mgr.getConfig().getProperty("manager.name") + poa.activate_object_with_id(id, self) + mgrobj = poa.id_to_reference(id) + self._objref = mgrobj._narrow(RTM.Manager) + except BaseException: + self._rtcout.RTC_DEBUG(OpenRTM_aist.Logger.print_exception()) + return False + + return True + + ## + # @if jp + # @brief Managerのリファレンスを検索する。 + # @return Managerのリファレンス + # @else + # @brief Find the reference of Manager. + # @return Manager reference + # @endif + # + # RTM::Manager_ptr findManager(const char* host_port); + + def findManager(self, host_port): + self._rtcout.RTC_TRACE("findManager(host_port = %s)", host_port) try: - prof = master.get_configuration() - prop = OpenRTM_aist.Properties() - OpenRTM_aist.NVUtil.copyToProperties(prop, prof) - name = prop.getProperty("manager.instance_name") - if name == manager_name: - return master - except: - self._rtcout.RTC_ERROR("Unknown exception cought.") - self._rtcout.RTC_DEBUG(OpenRTM_aist.Logger.print_exception()) - continue - - slaves = master.get_slave_managers() - for slave in slaves[:]: - try: - prof = slave.get_configuration() - prop = OpenRTM_aist.Properties() - OpenRTM_aist.NVUtil.copyToProperties(prop, prof) - name = prop.getProperty("manager.instance_name") - if name == manager_name: - return slave - except: - self._rtcout.RTC_ERROR("Unknown exception cought.") + config = copy.deepcopy(self._mgr.getConfig()) + mgrloc = "corbaloc:iiop:" + mgrloc += host_port + mgrloc += "/" + config.getProperty("manager.name") + + self._rtcout.RTC_DEBUG("corbaloc: %s", mgrloc) + + mobj = self._mgr.getORB().string_to_object(mgrloc) + mgr = mobj._narrow(RTM.Manager) + + return mgr + + except CORBA.SystemException: self._rtcout.RTC_DEBUG(OpenRTM_aist.Logger.print_exception()) - master.remove_slave_manager(slave) - - del guard - - return RTM.Manager._nil - - ## - # @if jp - # @brief ⥸塼̾ѥ᡼Ф - # ¶m_name=value⤷ ?param_name=value - #valueФ - # - # @param self - # @param param_name ѥ᡼̾ - # @param module_name ⥸塼̾ - # @return ѥ᡼ - # @else - # - # @brief - # @param self - # @param param_name - # @param module_name - # @return - # @endif - # std::string getParameterByModulename(string param_name, string &module_name) - def getParameterByModulename(self, param_name, module_name): - arg = module_name[0] - pos0 = arg.find("&"+param_name+"=") - pos1 = arg.find("?"+param_name+"=") - - - - if pos0 == -1 and pos1 == -1: - return "" - - pos = 0 - if pos0 == -1: - pos = pos1 - else: - pos = pos0 - - paramstr = "" - endpos = arg.find('&', pos + 1) - if endpos == -1: - endpos = arg.find('?', pos + 1) - if endpos == -1: - paramstr = arg[(pos + 1):] - else: - paramstr = arg[(pos + 1): endpos] - else: - paramstr = arg[(pos + 1): endpos] - self._rtcout.RTC_VERBOSE("%s arg: %s", (param_name, paramstr)) - - - - eqpos = paramstr.find("=") - #if eqpos == -1: - # self._rtcout.RTC_WARN("Invalid argument: %s", module_name) - # return "" - - paramstr = paramstr[eqpos + 1:] - self._rtcout.RTC_DEBUG("%s is %s",(param_name, paramstr)) - - if endpos == -1: - arg = arg[:pos] - else: - arg = arg[:pos] + arg[endpos:] - - module_name[0] = arg - - return paramstr - - - - - ## - # @if jp - # @brief Υޥ͡RTCư - # comp&manager_name=mgr - # Τ褦RTC̾&manager_name=ޥ̾͡Ȼꤹ - # @param self - # @param module_name ưRTCޥ̾͡ - # @return RTC - # @else - # - # @brief - # @param self - # @param module_name - # @return - # @endif - # RTC::RTObject_ptr createComponentByManagerName(string module_name) - def createComponentByManagerName(self, module_name): - - arg = module_name - - - tmp = [arg] - mgrstr = self.getParameterByModulename("manager_name",tmp) - arg = tmp[0] - - if not mgrstr: - return RTC.RTObject._nil - - - if mgrstr == "manager_%p": - mgrobj = RTM.Manager._nil - else: - mgrobj = self.findManagerByName(mgrstr) - - - - comp_param = CompParam(arg) - - - - - - if CORBA.is_nil(mgrobj): - self._rtcout.RTC_WARN("%s cannot be found.", mgrstr) - config = copy.deepcopy(self._mgr.getConfig()) - rtcd_cmd = config.getProperty("manager.modules."+comp_param.language()+".manager_cmd") - - if not rtcd_cmd: - rtcd_cmd = "rtcd_python" - #rtcd_cmd = "rtcd_python.bat" - - load_path = config.getProperty("manager.modules.load_path") - load_path_language = config.getProperty("manager.modules."+comp_param.language()+".load_paths") - load_path = load_path + "," + load_path_language - - if os.name == "nt": - cmd = "cmd /c " + rtcd_cmd - load_path = load_path.replace("\\","\\\\") - load_path = load_path.replace("\\","\\\\") - else: - cmd = rtcd_cmd - cmd += " -o " + "manager.is_master:NO" - cmd += " -o " + "manager.corba_servant:YES" - cmd += " -o " + "corba.master_manager:" + config.getProperty("corba.master_manager") - cmd += " -o " + "manager.name:" + config.getProperty("manager.name") - cmd += " -o " + "manager.instance_name:" + mgrstr - cmd += " -o " + "\"manager.modules.load_path:" + load_path + "\"" - cmd += " -o " + "manager.supported_languages:" + comp_param.language() - cmd += " -o " + "manager.shutdown_auto:NO" - - - - - self._rtcout.RTC_DEBUG("Invoking command: %s.", cmd) - - slaves_names = [] - regex = r'manager_[0-9]+' - if mgrstr == "manager_%p": - guard_slave = OpenRTM_aist.ScopedLock(self._slaveMutex) - for slave in self._slaves[:]: - try: - prof = slave.get_configuration() - prop = OpenRTM_aist.Properties() - OpenRTM_aist.NVUtil.copyToProperties(prop, prof) - name = prop.getProperty("manager.instance_name") - if re.match(regex, name): - slaves_names.append(name) - except: + + except BaseException: self._rtcout.RTC_ERROR("Unknown exception cought.") self._rtcout.RTC_DEBUG(OpenRTM_aist.Logger.print_exception()) - self._slaves.remove(slave) - - del guard_slave - - - ret = OpenRTM_aist.launch_shell(cmd) + return RTM.Manager._nil + + ## + # @if jp + # @brief 指定名のRTCを取得 + # @param self + # @param name RTC名 + # @return RTCのリスト + # @else + # + # @brief + # @param self + # @param name + # @return + # @endif + # RTCList get_components_by_name(string name) + def get_components_by_name(self, name): + self._rtcout.RTC_TRACE("get_components_by_name()") + rtcs = self._mgr.getComponents() + crtcs = [] + name = OpenRTM_aist.eraseHeadBlank(name) + rtc_name = name.split("/") + for rtc in rtcs: + if len(rtc_name) == 1: + if rtc.getInstanceName() == rtc_name[0]: + crtcs.append(rtc.getObjRef()) + else: + if rtc_name[0] == "*": + if rtc.getInstanceName() == rtc_name[1]: + crtcs.append(rtc.getObjRef()) + else: + if rtc.getCategory() == rtc_name[0]: + if rtc.getInstanceName() == rtc_name[1]: + crtcs.append(rtc.getObjRef()) + + return crtcs + + ## + # @if jp + # @brief 指定名のマネージャを取得 + # マネージャがマスターの場合は登録されているスレーブマネージャから検索する + # マネージャがスレーブの場合は登録されているマスターマネージャからスレーブマネージャを検索する + # @param self + # @param manager_name マネージャ名 + # @return マネージャ + # @else + # + # @brief + # @param self + # @param manager_name + # @return + # @endif + # RTC::Manager_ptr findManagerByName(string manager_name) + def findManagerByName(self, manager_name): + self._rtcout.RTC_TRACE( + "findManagerByName(manager_name = %s)", + manager_name) + prop = self._mgr.getConfig() + name = prop.getProperty("manager.instance_name") + if name == manager_name: + return self.getObjRef() + if self._isMain: + guard = OpenRTM_aist.ScopedLock(self._subordinateMutex) + for subordinate in self._subordinates[:]: + try: + prof = subordinate.get_configuration() + prop = OpenRTM_aist.Properties() + OpenRTM_aist.NVUtil.copyToProperties(prop, prof) + name = prop.getProperty("manager.instance_name") + if name == manager_name: + return subordinate + + except BaseException: + self._rtcout.RTC_ERROR("Unknown exception cought.") + self._rtcout.RTC_DEBUG( + OpenRTM_aist.Logger.print_exception()) + self._subordinates.remove(subordinate) + del guard + else: + guard = OpenRTM_aist.ScopedLock(self._mainMutex) + for main in self._mains: + try: + prof = main.get_configuration() + prop = OpenRTM_aist.Properties() + OpenRTM_aist.NVUtil.copyToProperties(prop, prof) + name = prop.getProperty("manager.instance_name") + if name == manager_name: + return main + except BaseException: + self._rtcout.RTC_ERROR("Unknown exception cought.") + self._rtcout.RTC_DEBUG( + OpenRTM_aist.Logger.print_exception()) + continue + + subordinates = main.get_subordinate_managers() + for subordinate in subordinates[:]: + try: + prof = subordinate.get_configuration() + prop = OpenRTM_aist.Properties() + OpenRTM_aist.NVUtil.copyToProperties(prop, prof) + name = prop.getProperty("manager.instance_name") + if name == manager_name: + return subordinate + except BaseException: + self._rtcout.RTC_ERROR("Unknown exception cought.") + self._rtcout.RTC_DEBUG( + OpenRTM_aist.Logger.print_exception()) + main.remove_subordinate_manager(subordinate) + + del guard + + return RTM.Manager._nil + + ## + # @if jp + # @brief モジュール名からパラメータを取り出す + # ¶m_name=value もしくは ?param_name=value + # のvalueを取り出す + # + # @param self + # @param param_name パラメータ名 + # @param module_name モジュール名 + # @return パラメータ + # @else + # + # @brief + # @param self + # @param param_name + # @param module_name + # @return + # @endif + # std::string getParameterByModulename(string param_name, string + # &module_name) + def getParameterByModulename(self, param_name, module_name): + arg = module_name + pos0 = arg.find("&" + param_name + "=") + pos1 = arg.find("?" + param_name + "=") + + if pos0 == -1 and pos1 == -1: + return "", module_name + + pos = 0 + if pos0 == -1: + pos = pos1 + else: + pos = pos0 + + paramstr = "" + endpos = arg.find('&', pos + 1) + if endpos == -1: + endpos = arg.find('?', pos + 1) + if endpos == -1: + paramstr = arg[(pos + 1):] + else: + paramstr = arg[(pos + 1): endpos] + else: + paramstr = arg[(pos + 1): endpos] + self._rtcout.RTC_VERBOSE("%s arg: %s", (param_name, paramstr)) - - if ret == -1: - self._rtcout.RTC_DEBUG("%s: failed", cmd) - return RTC.RTObject._nil - time.sleep(0.01) - count = 0 - + eqpos = paramstr.find("=") + # if eqpos == -1: + # self._rtcout.RTC_WARN("Invalid argument: %s", module_name) + # return "" + paramstr = paramstr[eqpos + 1:] + self._rtcout.RTC_DEBUG("%s is %s", (param_name, paramstr)) - t0_ = OpenRTM_aist.Time() - - while CORBA.is_nil(mgrobj): - if mgrstr == "manager_%p": - - guard_slave = OpenRTM_aist.ScopedLock(self._slaveMutex) - - for slave in self._slaves[:]: - try: - prof = slave.get_configuration() - prop = OpenRTM_aist.Properties() - OpenRTM_aist.NVUtil.copyToProperties(prop, prof) - name = prop.getProperty("manager.instance_name") - - if re.match(regex, name) and not (name in slaves_names): - mgrobj = slave - except: - self._rtcout.RTC_ERROR("Unknown exception cought.") - self._rtcout.RTC_DEBUG(OpenRTM_aist.Logger.print_exception()) - self._slaves.remove(slave) - del guard_slave - + if endpos == -1: + arg = arg[:pos] else: - mgrobj = self.findManagerByName(mgrstr) - count += 1 - if count > 1000: - break - - t1_ = OpenRTM_aist.Time() - if (t1_ - t0_).getTime().toDouble() > 10.0 and count > 10: - break - time.sleep(0.01) - - if CORBA.is_nil(mgrobj): - self._rtcout.RTC_WARN("Manager cannot be found.") - return RTC.RTObject._nil - - - - - - - - - - - self._rtcout.RTC_DEBUG("Creating component on %s", mgrstr) - self._rtcout.RTC_DEBUG("arg: %s", arg) - - - try: - rtobj = mgrobj.create_component(arg) - - return rtobj - except CORBA.SystemException: - self._rtcout.RTC_DEBUG("Exception was caught while creating component.") - self._rtcout.RTC_ERROR(OpenRTM_aist.Logger.print_exception()) - return RTC.RTObject._nil - except: - self._rtcout.RTC_DEBUG(OpenRTM_aist.Logger.print_exception()) - return RTC.RTObject._nil - - - - - ## - # @if jp - # @brief Υޥ͡RTCư - # comp&manager_address=localhost:2810 - # Τ褦RTC̾&manager_address=ޥ͡Υۥ̾ݡֹꤹ - # @param self - # @param module_name ưRTCޥ͡Υۥȥɥ쥹 - # @return RTC - # @else - # - # @brief - # @param self - # @param module_name - # @return - # @endif - # RTC::RTObject_ptr createComponentByAddress(string module_name) - def createComponentByAddress(self, module_name): - - arg = module_name - tmp = [arg] - mgrstr = self.getParameterByModulename("manager_address",tmp) - arg = tmp[0] - - if not mgrstr: - return RTC.RTObject._nil - - mgrvstr = mgrstr.split(":") - if len(mgrvstr) != 2: - self._rtcout.RTC_WARN("Invalid manager address: %s", mgrstr) - return RTC.RTObject._nil - - - # find manager - mgrobj = self.findManager(mgrstr) - - - comp_param = CompParam(arg) - - - - if CORBA.is_nil(mgrobj): - config = copy.deepcopy(self._mgr.getConfig()) - rtcd_cmd = config.getProperty("manager.modules."+comp_param.language()+".manager_cmd") - if not rtcd_cmd: - rtcd_cmd = "rtcd_python" - - load_path = config.getProperty("manager.modules.load_path") - load_path_language = config.getProperty("manager.modules."+comp_param.language()+".load_path") - load_path = load_path + "," + load_path_language - - if os.name == "nt": - cmd = "cmd /c " + rtcd_cmd - load_path = load_path.replace("\\","\\\\") - else: - cmd = rtcd_cmd - cmd += " -o corba.master_manager:" - cmd += mgrstr # port number - cmd += " -o \"manager.modules.load_path:" - cmd += load_path + "\"" - cmd += " -d " - - - self._rtcout.RTC_DEBUG("Invoking command: %s.", cmd) - ret = OpenRTM_aist.launch_shell(cmd) - - if ret == -1: - self._rtcout.RTC_DEBUG("%s: failed", cmd) - return RTC.RTObject._nil + arg = arg[:pos] + arg[endpos:] - # find manager - time.sleep(0.01) - count = 0 - t0_ = OpenRTM_aist.Time() - while CORBA.is_nil(mgrobj): - mgrobj = self.findManager(mgrstr) - count += 1 - if count > 1000: - break - - t1_ = OpenRTM_aist.Time() - if (t1_ - t0_).getTime().toDouble() > 10.0 and count > 10: - break - time.sleep(0.01) - - if CORBA.is_nil(mgrobj): - self._rtcout.RTC_WARN("Manager cannot be found.") - return RTC.RTObject._nil - - - self._rtcout.RTC_DEBUG("Creating component on %s", mgrstr) - self._rtcout.RTC_DEBUG("arg: %s", arg) - try: - rtobj = mgrobj.create_component(arg) - self._rtcout.RTC_DEBUG("Component created %s", arg) - return rtobj - except CORBA.SystemException: - self._rtcout.RTC_DEBUG("Exception was caught while creating component.") - self._rtcout.RTC_ERROR(OpenRTM_aist.Logger.print_exception()) - return RTC.RTObject._nil - except: - self._rtcout.RTC_DEBUG(OpenRTM_aist.Logger.print_exception()) - return RTC.RTObject._nil - - ## - # @if jp - # @brief ޥޥ̵ͭ͡ǧƥꥹȤ򹹿 - # - # @param self - # @else - # - # @brief - # @param self - # @endif - # void updateMasterManager() - def updateMasterManager(self): - if not self._isMaster and self._objref: - guard = OpenRTM_aist.ScopedLock(self._masterMutex) - if len(self._masters) > 0: - for master in self._masters[:]: - try: - if master._non_existent(): - self._masters.remove(master) - except: - self._rtcout.RTC_ERROR("Unknown exception cought.") - self._rtcout.RTC_ERROR(OpenRTM_aist.Logger.print_exception()) - self._masters.remove(master) - del guard - - if len(self._masters) == 0: - try: - config = self._mgr.getConfig() - owner = self.findManager(config.getProperty("corba.master_manager")) - if not owner: - self._rtcout.RTC_INFO("Master manager not found") - return - self.add_master_manager(owner) - owner.add_slave_manager(self._objref) - - return - except: - self._rtcout.RTC_ERROR("Unknown exception cought.") - self._rtcout.RTC_ERROR(OpenRTM_aist.Logger.print_exception()) + module_name = arg + + return paramstr, module_name + + ## + # @if jp + # @brief 指定のマネージャでRTCを起動する + # comp&manager_name=mgr + # のようにRTC名&manager_name=マネージャ名と指定する + # @param self + # @param module_name 起動するRTC、マネージャ名 + # @return RTC + # @else + # + # @brief + # @param self + # @param module_name + # @return + # @endif + # RTC::RTObject_ptr createComponentByManagerName(string module_name) + def createComponentByManagerName(self, module_name): + arg = module_name + mgrstr, arg = self.getParameterByModulename("manager_name", arg) - class is_equiv: - def __init__(self, mgr): - self._mgr = mgr + if not mgrstr: + return RTC.RTObject._nil - def __call__(self, mgr): - if not self._mgr or not mgr: - return self._mgr == mgr + if mgrstr == "manager_%p": + mgrobj = RTM.Manager._nil + else: + mgrobj = self.findManagerByName(mgrstr) + + comp_param = CompParam(arg) + + if CORBA.is_nil(mgrobj): + self._rtcout.RTC_WARN("%s cannot be found.", mgrstr) + config = copy.deepcopy(self._mgr.getConfig()) + rtcd_cmd = config.getProperty( + "manager.modules." + + comp_param.language() + + ".manager_cmd") + + if not rtcd_cmd: + lang = config.getProperty("manager.language") + rtcd_cmd = config.getProperty( + "manager.modules." + + lang + + ".manager_cmd") + + load_path = config.getProperty("manager.modules.load_path") + load_path_language = config.getProperty( + "manager.modules." + comp_param.language() + ".load_paths") + load_path = load_path + "," + load_path_language + + if os.name == "nt": + cmd = "cmd /c " + rtcd_cmd + load_path = load_path.replace("\\", "\\\\") + load_path = load_path.replace("\\", "\\\\") + else: + cmd = rtcd_cmd + cmd += " -o " + "manager.is_main:NO" + cmd += " -o " + "manager.corba_servant:YES" + cmd += " -o " + "corba.main_manager:" + \ + config.getProperty("corba.main_manager") + cmd += " -o " + "manager.name:" + \ + config.getProperty("manager.name") + cmd += " -o " + "manager.instance_name:" + mgrstr + cmd += " -o " + "\"manager.modules.load_path:" + load_path + "\"" + cmd += " -o " + "manager.supported_languages:" + comp_param.language() + cmd += " -o " + "manager.shutdown_auto:NO" + + self._rtcout.RTC_DEBUG("Invoking command: %s.", cmd) + + subordinates_names = [] + regex = r'manager_[0-9]+' + if mgrstr == "manager_%p": + guard_subordinate = OpenRTM_aist.ScopedLock(self._subordinateMutex) + for subordinate in self._subordinates[:]: + try: + prof = subordinate.get_configuration() + prop = OpenRTM_aist.Properties() + OpenRTM_aist.NVUtil.copyToProperties(prop, prof) + name = prop.getProperty("manager.instance_name") + if re.match(regex, name): + subordinates_names.append(name) + except BaseException: + self._rtcout.RTC_ERROR("Unknown exception cought.") + self._rtcout.RTC_DEBUG( + OpenRTM_aist.Logger.print_exception()) + self._subordinates.remove(subordinate) + + del guard_subordinate + + ret = OpenRTM_aist.launch_shell(cmd) + + if ret == -1: + self._rtcout.RTC_DEBUG("%s: failed", cmd) + return RTC.RTObject._nil + time.sleep(0.01) + count = 0 + + t0_ = OpenRTM_aist.Time() + + while CORBA.is_nil(mgrobj): + if mgrstr == "manager_%p": + + guard_subordinate = OpenRTM_aist.ScopedLock(self._subordinateMutex) + + for subordinate in self._subordinates[:]: + try: + prof = subordinate.get_configuration() + prop = OpenRTM_aist.Properties() + OpenRTM_aist.NVUtil.copyToProperties(prop, prof) + name = prop.getProperty("manager.instance_name") + + if re.match(regex, name) and not ( + name in subordinates_names): + mgrobj = subordinate + except BaseException: + self._rtcout.RTC_ERROR("Unknown exception cought.") + self._rtcout.RTC_DEBUG( + OpenRTM_aist.Logger.print_exception()) + self._subordinates.remove(subordinate) + del guard_subordinate + + else: + mgrobj = self.findManagerByName(mgrstr) + count += 1 + if count > 1000: + break + + t1_ = OpenRTM_aist.Time() + if (t1_ - t0_).getTime().toDouble() > 10.0 and count > 10: + break + time.sleep(0.01) + + if CORBA.is_nil(mgrobj): + self._rtcout.RTC_WARN("Manager cannot be found.") + return RTC.RTObject._nil + + self._rtcout.RTC_DEBUG("Creating component on %s", mgrstr) + self._rtcout.RTC_DEBUG("arg: %s", arg) + + try: + rtobj = mgrobj.create_component(arg) - return self._mgr._is_equivalent(mgr) - + return rtobj + except CORBA.SystemException: + self._rtcout.RTC_DEBUG( + "Exception was caught while creating component.") + self._rtcout.RTC_ERROR(OpenRTM_aist.Logger.print_exception()) + return RTC.RTObject._nil + except BaseException: + self._rtcout.RTC_DEBUG(OpenRTM_aist.Logger.print_exception()) + return RTC.RTObject._nil + + ## + # @if jp + # @brief 指定のマネージャでRTCを起動する + # comp&manager_address=localhost:2810 + # のようにRTC名&manager_address=マネージャのホスト名、ポート番号を指定する + # @param self + # @param module_name 起動するRTC、マネージャのホストアドレス + # @return RTC + # @else + # + # @brief + # @param self + # @param module_name + # @return + # @endif + # RTC::RTObject_ptr createComponentByAddress(string module_name) + def createComponentByAddress(self, module_name): + + arg = module_name + mgrstr, arg = self.getParameterByModulename("manager_address", arg) + + if not mgrstr: + return RTC.RTObject._nil + + mgrvstr = mgrstr.split(":") + if len(mgrvstr) != 2: + self._rtcout.RTC_WARN("Invalid manager address: %s", mgrstr) + return RTC.RTObject._nil + + # find manager + mgrobj = self.findManager(mgrstr) + + comp_param = CompParam(arg) + + if CORBA.is_nil(mgrobj): + config = copy.deepcopy(self._mgr.getConfig()) + rtcd_cmd = config.getProperty( + "manager.modules." + + comp_param.language() + + ".manager_cmd") + if not rtcd_cmd: + lang = config.getProperty("manager.language") + rtcd_cmd = config.getProperty( + "manager.modules." + + lang + + ".manager_cmd") + + load_path = config.getProperty("manager.modules.load_path") + load_path_language = config.getProperty( + "manager.modules." + comp_param.language() + ".load_path") + load_path = load_path + "," + load_path_language + + if os.name == "nt": + cmd = "cmd /c " + rtcd_cmd + load_path = load_path.replace("\\", "\\\\") + else: + cmd = rtcd_cmd + cmd += " -o corba.main_manager:" + cmd += mgrstr # port number + cmd += " -o \"manager.modules.load_path:" + cmd += load_path + "\"" + cmd += " -d " + + self._rtcout.RTC_DEBUG("Invoking command: %s.", cmd) + ret = OpenRTM_aist.launch_shell(cmd) + + if ret == -1: + self._rtcout.RTC_DEBUG("%s: failed", cmd) + return RTC.RTObject._nil + + # find manager + time.sleep(0.01) + count = 0 + t0_ = OpenRTM_aist.Time() + while CORBA.is_nil(mgrobj): + mgrobj = self.findManager(mgrstr) + count += 1 + if count > 1000: + break + + t1_ = OpenRTM_aist.Time() + if (t1_ - t0_).getTime().toDouble() > 10.0 and count > 10: + break + time.sleep(0.01) + + if CORBA.is_nil(mgrobj): + self._rtcout.RTC_WARN("Manager cannot be found.") + return RTC.RTObject._nil + + self._rtcout.RTC_DEBUG("Creating component on %s", mgrstr) + self._rtcout.RTC_DEBUG("arg: %s", arg) + try: + rtobj = mgrobj.create_component(arg) + self._rtcout.RTC_DEBUG("Component created %s", arg) + return rtobj + except CORBA.SystemException: + self._rtcout.RTC_DEBUG( + "Exception was caught while creating component.") + self._rtcout.RTC_ERROR(OpenRTM_aist.Logger.print_exception()) + return RTC.RTObject._nil + except BaseException: + self._rtcout.RTC_DEBUG(OpenRTM_aist.Logger.print_exception()) + return RTC.RTObject._nil + + ## + # @if jp + # @brief マスターマネージャの有無を確認してリストを更新する + # + # @param self + # @else + # + # @brief + # @param self + # @endif + # void updateMainManager() + def updateMainManager(self): + if not self._isMain and self._objref: + guard = OpenRTM_aist.ScopedLock(self._mainMutex) + if self._mains: + for main in self._mains[:]: + try: + if main._non_existent(): + self._mains.remove(main) + except BaseException: + self._rtcout.RTC_ERROR("Unknown exception cought.") + self._rtcout.RTC_ERROR( + OpenRTM_aist.Logger.print_exception()) + self._mains.remove(main) + del guard + + if not self._mains: + try: + config = self._mgr.getConfig() + owner = self.findManager( + config.getProperty("corba.main_manager")) + if not owner: + self._rtcout.RTC_INFO("Main manager not found") + return + self.add_main_manager(owner) + owner.add_subordinate_manager(self._objref) + + return + except BaseException: + self._rtcout.RTC_ERROR("Unknown exception cought.") + self._rtcout.RTC_ERROR( + OpenRTM_aist.Logger.print_exception()) + + class is_equiv: + def __init__(self, mgr): + self._mgr = mgr + + def __call__(self, mgr): + if not self._mgr or not mgr: + return self._mgr == mgr + + return self._mgr._is_equivalent(mgr) diff --git a/OpenRTM_aist/ModuleManager.py b/OpenRTM_aist/ModuleManager.py index a3df5826..ed11ae06 100644 --- a/OpenRTM_aist/ModuleManager.py +++ b/OpenRTM_aist/ModuleManager.py @@ -1,5 +1,5 @@ #!/usr/bin/env python -# -*- coding: euc-jp -*- +# -*- coding: utf-8 -*- ## # @file ModuleManager.py @@ -15,34 +15,35 @@ # All rights reserved. - -import sys,os +import sys +import os import glob +import encodings.aliases +import codecs import OpenRTM_aist -CONFIG_EXT = "manager.modules.config_ext" -CONFIG_PATH = "manager.modules.config_path" -DETECT_MOD = "manager.modules.detect_loadable" -MOD_LOADPTH = "manager.modules.load_path" -INITFUNC_SFX = "manager.modules.init_func_suffix" -INITFUNC_PFX = "manager.modules.init_func_prefix" +CONFIG_EXT = "manager.modules.config_ext" +CONFIG_PATH = "manager.modules.config_path" +DETECT_MOD = "manager.modules.detect_loadable" +MOD_LOADPTH = "manager.modules.load_path" +INITFUNC_SFX = "manager.modules.init_func_suffix" +INITFUNC_PFX = "manager.modules.init_func_prefix" ALLOW_ABSPATH = "manager.modules.abs_path_allowed" -ALLOW_URL = "manager.modules.download_allowed" -MOD_DWNDIR = "manager.modules.download_dir" -MOD_DELMOD = "manager.modules.download_cleanup" -MOD_PRELOAD = "manager.modules.preload" - +ALLOW_URL = "manager.modules.download_allowed" +MOD_DWNDIR = "manager.modules.download_dir" +MOD_DELMOD = "manager.modules.download_cleanup" +MOD_PRELOAD = "manager.modules.preload" ## # @if jp # -# @brief ⥸塼ޥ͡㥯饹 +# @brief モジュールマネージャクラス # @class ModuleManager # -# ⥸塼Υɡɤʤɤ륯饹 +# モジュールのロード、アンロードなどを管理するクラス # # @since 0.4.0 # @@ -52,888 +53,879 @@ # # @endif class ModuleManager: - """ - """ - - - - ## - # @if jp - # - # @brief 󥹥ȥ饯 - # - # 󥹥ȥ饯 - # ꤵ줿 Property ֥ξ˽¹Ԥ롣 - # - # @param self - # @param prop ѥץѥƥ - # - # @else - # - # @brief constructor - # - # @endif - def __init__(self, prop): - self._properties = prop - - self._configPath = prop.getProperty(CONFIG_PATH).split(",") - for i in range(len(self._configPath)): - tmp = [self._configPath[i]] - OpenRTM_aist.eraseHeadBlank(tmp) - self._configPath[i] = tmp[0] - self._loadPath = prop.getProperty(MOD_LOADPTH,"./").split(",") - for i in range(len(self._loadPath)): - tmp = [self._loadPath[i]] - OpenRTM_aist.eraseHeadBlank(tmp) - self._loadPath[i] = tmp[0] - - self._absoluteAllowed = OpenRTM_aist.toBool(prop.getProperty(ALLOW_ABSPATH), - "yes", "no", False) - - self._downloadAllowed = OpenRTM_aist.toBool(prop.getProperty(ALLOW_URL), - "yes", "no", False) - - self._initFuncSuffix = prop.getProperty(INITFUNC_SFX) - self._initFuncPrefix = prop.getProperty(INITFUNC_PFX) - self._modules = OpenRTM_aist.ObjectManager(self.DLLPred) - self._rtcout = None - self._mgr = OpenRTM_aist.Manager.instance() - if not self._rtcout: - self._rtcout = self._mgr.getLogbuf("ModuleManager") - self._modprofs = [] - self._loadfailmods = [] - - ## - # @if jp - # - # @brief ǥȥ饯(̤) - # - # @param self - # - # @else - # - # @brief destructor - # - # @endif - def __del__(self): - self.unloadAll() - - - ## - # @if jp - # @class Error - # @brief ե롦ץ㳰饹 - # @else - # - # @endif - class Error(Exception): - def __init__(self, reason_): - self.reason = reason_ - - - - ## - # @if jp - # @class NotFound - # @brief ̤⥸塼㳰饹 - # @else - # - # @endif - class NotFound(Exception): - def __init__(self, name_): - self.name = name_ - - - - ## - # @if jp - # @class FileNotFound - # @brief ե㳰饹 - # @else - # - # @endif - class FileNotFound(NotFound): - def __init__(self, name_): - ModuleManager.NotFound.__init__(self, name_) - - - - ## - # @if jp - # @class ModuleNotFound - # @brief ⥸塼㳰饹 - # @else - # - # @endif - class ModuleNotFound(NotFound): - def __init__(self, name_): - ModuleManager.NotFound.__init__(self, name_) - - - - ## - # @if jp - # @class SymbolNotFound - # @brief ꥷܥ㳰饹 - # @else - # - # @endif - class SymbolNotFound(NotFound): - def __init__(self, name_): - ModuleManager.NotFound.__init__(self, name_) - - - - ## - # @if jp - # @class NotAllowedOperation - # @brief ػ߻㳰饹 - # @else - # - # @endif - class NotAllowedOperation(Error): - def __init__(self, reason_): - ModuleManager.Error.__init__(self, reason_) - - - - ## - # @if jp - # @class InvalidArguments - # @brief 㳰饹 - # @else - # - # @endif - class InvalidArguments(Error): - def __init__(self, reason_): - ModuleManager.Error.__init__(self, reason_) - - - - ## - # @if jp - # @class InvalidOperation - # @brief 㳰饹 - # @else - # - # @endif - class InvalidOperation(Error): - def __init__(self, reason_): - ModuleManager.Error.__init__(self, reason_) - - - - ## - # @if jp - # - # @brief ⥸塼Υɡ - # - # ꤷեͭ饤֥ȤƥɤȤȤˡ - # ꤷѥڥ졼¹Ԥ롣 - # - # @param self - # @param file_name оݥ⥸塼̾ (.pyե̾) - # @param init_func ѥڥ졼(ǥե:None) - # - # @return ꤷоݥ⥸塼̾ - # - # @else - # - # @brief Load module - # - # - # @endif - # std::string ModuleManager::load(const std::string& file_name, - # const std::string& init_func) - def load(self, file_name, init_func=None): - - - self._rtcout.RTC_TRACE("load(fname = %s)", file_name) - if file_name == "": - raise ModuleManager.InvalidArguments("Invalid file name.") - - if OpenRTM_aist.isURL(file_name): - if not self._downloadAllowed: - raise ModuleManager.NotAllowedOperation("Downloading module is not allowed.") - else: - raise ModuleManager.NotFound("Not implemented.") - - import_name = os.path.split(file_name)[-1] - pathChanged=False - file_path = None - - if OpenRTM_aist.isAbsolutePath(file_name): - if not self._absoluteAllowed: - raise ModuleManager.NotAllowedOperation("Absolute path is not allowed") - else: - splitted_name = os.path.split(file_name) - save_path = sys.path[:] - sys.path.append(splitted_name[0]) - - pathChanged = True - import_name = splitted_name[-1] - file_path = file_name - - else: - file_path = self.findFile(file_name, self._loadPath) - if not file_path: - raise ModuleManager.FileNotFound(file_name) - - if not self.fileExist(file_path): - raise ModuleManager.FileNotFound(file_name) - - - with open(str(file_path)) as f: - if init_func is not None: - if f.read().find(init_func) == -1: - raise ModuleManager.FileNotFound(file_name) - - - if not pathChanged: - splitted_name = os.path.split(file_path) - sys.path.append(splitted_name[0]) - - ext_pos = import_name.find(".py") - if ext_pos > 0: - import_name = import_name[:ext_pos] - - mo = __import__(str(import_name)) - - if pathChanged: - sys.path = save_path - - file_path = file_path.replace("\\","/") - file_path = file_path.replace("//","/") - - dll = self.DLLEntity(mo,OpenRTM_aist.Properties()) - dll.properties.setProperty("file_path",file_path) - self._modules.registerObject(dll) - - - if init_func is None: - return file_name - - - self.symbol(file_path,init_func)(self._mgr) - - return file_name - - - ## - # @if jp - # @brief ⥸塼Υ - # - # ꤷɺѤߥ⥸塼򥯥ɤ롣 - # - # @param self - # @param file_name оݥ⥸塼̾ - # - # @else - # @brief Unload module - # @endif - def unload(self, file_name): - dll = self._modules.find(file_name) - if not dll: - raise ModuleManager.NotFound(file_name) - dll_name = dll.dll.__name__ - if dll_name in sys.modules.keys(): - sys.modules.pop(dll_name) - self._modules.unregisterObject(file_name) - return - - - ## - # @if jp - # @brief ⥸塼Υ - # - # ƤΥɺѤߥ⥸塼򥢥ɤ롣 - # - # @param self - # - # @else - # @brief Unload all modules - # @endif - def unloadAll(self): - dlls = self._modules.getObjects() - - for dll in dlls: - ident = dll.properties.getProperty("file_path") - self._modules.unregisterObject(ident) - return - - - ## - # @if jp - # @brief ⥸塼Υܥλ - # - # ⥸塼Υܥ - # - # @param self - # @param file_name оݥե̾ - # @param func_name оݴؿ̾ - # - # @else - # @brief Look up a named symbol in the module - # @endif - def symbol(self, file_name, func_name): - dll = self._modules.find(file_name) - if not dll: - raise ModuleManager.ModuleNotFound(file_name) - - func = getattr(dll.dll,func_name,None) - - if not func: - raise ModuleManager.SymbolNotFound(func_name) - - return func - - - ## - # @if jp - # @brief ⥸塼ɥѥꤹ - # - # ⥸塼ɻоݥ⥸塼򸡺ѥꤹ롣 - # - # @param self - # @param load_path_list ⥸塼븡оݥѥꥹ - # - # @else - # @brief Set default module load path - # @endif - def setLoadpath(self, load_path_list): - self._loadPath = load_path_list - return - - - ## - # @if jp - # @brief ⥸塼ɥѥ - # - # ꤵƤ⥸塼򸡺оݥѥꥹȤ롣 - # - # @param self - # - # @return load_path ⥸塼븡оݥѥꥹ - # - # @else - # @brief Get default module load path - # @endif - def getLoadPath(self): - return self._loadPath - - - ## - # @if jp - # @brief ⥸塼ɥѥɲä - # - # ꤵ줿ѥꥹȤ򸡺оݥѥꥹȤɲä롣 - # - # @param self - # @param load_path ɲå⥸塼븡оݥѥꥹ - # - # @else - # @brief Add module load path - # @endif - def addLoadpath(self, load_path): - for path in load_path: - self._loadPath.append(path) - return - - - ## - # @if jp - # @brief ɺѤߤΥ⥸塼ꥹȤ - # - # ˥ɺѤߤΥ⥸塼ꥹȤ롣 - # - # @param self - # - # @return ɺѤߥ⥸塼ꥹ - # - # @else - # @brief Get loaded module names - # @endif - # std::vector getLoadedModules(); - def getLoadedModules(self): - dlls = self._modules.getObjects() - modules = [] - for dll in dlls: - modules.append(dll.properties) - - return modules - - - def __getRtcProfile(self, fname): - # file name with full path - fullname = fname - # directory name - dirname = os.path.dirname(fullname) - sys.path.append(dirname) - # basename - basename = os.path.basename(fullname) - # classname - classname = basename.split(".")[0].lower() - - # loaded profile = old profiles - new profiles - # for old - oldp = self._mgr.getFactoryProfiles() - - # for new - comp_spec_name = classname+"_spec" - - - - - try: - with open(str(fullname)) as f: - if f.read().find(comp_spec_name) == -1: - return None - imp_file = __import__(basename.split(".")[0]) - except: - return None - comp_spec = getattr(imp_file,comp_spec_name,None) - if not comp_spec: - return None - newp = OpenRTM_aist.Properties(defaults_str=comp_spec) - - profs = [] - - exists = False - for i in range(len(oldp)): - if oldp[i].getProperty("implementation_id") == newp.getProperty("implementation_id") and \ - oldp[i].getProperty("type_name") == newp.getProperty("type_name") and \ - oldp[i].getProperty("description") == newp.getProperty("description") and \ - oldp[i].getProperty("version") == newp.getProperty("version"): - exists = True - if not exists: - profs.append(newp) - - - # loaded component profile have to be one - if len(profs) == 0: - return OpenRTM_aist.Properties() - - #if len(profs) > 1: - # return None - - return profs[0] - - - - ## - # @if jp - # @brief ˤɥѥΥ֥ʥեꥹȤ֤ - # - # - # @param self - # @param lang - # @param modules - # - # - # @else - # @brief Getting loadable file list on the loadpath for given language - # @endif - def getModuleList(self, lang, modules): - l = "manager.modules." + lang - lprop = self._properties.getNode(l) - - paths = lprop.getProperty("load_paths").split(",") - - - paths.extend(self._loadPath) - paths = self.deleteSamePath(paths) - - - - suffixes = lprop.getProperty("suffixes").split(",") - - - self._rtcout.RTC_DEBUG("suffixes: %s", OpenRTM_aist.flatten(suffixes)) - - for path in paths: - if not path: - self._rtcout.RTC_WARN("Given load path is empty") - continue - self._rtcout.RTC_DEBUG("Module load path: %s", path) - flist = [] - for suffix in suffixes: - tmp = [suffix] - OpenRTM_aist.eraseHeadBlank(tmp) - suffix = tmp[0] - - tmp = [] - OpenRTM_aist.getFileList(path,suffix,tmp) - - #tmp = glob.glob(path + os.sep + '*.' + suffix) - if lang == "Python": - for f in tmp: - if f.find("__init__.py") != -1: - tmp.remove(f) - - self._rtcout.RTC_DEBUG("File list (path:%s, ext:%s): %s", (path,suffix,OpenRTM_aist.flatten(suffixes))) - flist.extend(tmp) - - for f in flist: - f = f.replace("\\","/") - f = f.replace("//","/") - self.addNewFile(f, modules) - modules = list(set(modules)) - - - - - ## - # @if jp - # @brief å̵ѥmodulesɲä - # - # - # @param self - # @param fpath - # @param modules - # - # - # @else - # @brief Adding file path not existing cache - # @endif - def addNewFile(self, fpath, modules): - exists = False - for modprof in self._modprofs: - if modprof.getProperty("module_file_path") == fpath: - exists = True - self._rtcout.RTC_DEBUG("Module %s already exists in cache.",fpath) - break - for loadfailmod in self._loadfailmods: - if loadfailmod == fpath: - exists = True - break - if not exists: - self._rtcout.RTC_DEBUG("New module: %s",fpath) - modules.append(fpath) - - - ## - # @if jp - # @brief 졢եꥹȤ⥸塼Υץѥƥ֤ - # - # - # @param self - # @param lang - # @param modules - # @param modprops - # - # - # @else - # @brief Getting loadable file list on the loadpath for given language - # @endif - def getModuleProfiles(self, lang, modules, modprops): - l = "manager.modules." + lang - lprop = self._properties.getNode(l) - - paths = lprop.getProperty("load_paths").split(",") - - - - for mod_ in modules: - if lang == "Python": - prop = self.__getRtcProfile(mod_) - if prop: - prop.setProperty("module_file_name",os.path.basename(mod_)) - prop.setProperty("module_file_path", mod_) - modprops.append(prop) - else: - prop = OpenRTM_aist.Properties() - cmd = lprop.getProperty("profile_cmd") - if os.name == "nt": - cmd = "cmd /c " + cmd - cmd = cmd + " \""+mod_+"\"" - + """ + """ + + ## + # @if jp + # + # @brief コンストラクタ + # + # コンストラクタ。 + # 設定された Property オブジェクト内の情報を基に初期化を実行する。 + # + # @param self + # @param prop 初期化用プロパティ + # + # @else + # + # @brief constructor + # + # @endif + def __init__(self, prop): + self._properties = prop + + self._configPath = prop.getProperty(CONFIG_PATH).split(",") + for i, cp in enumerate(self._configPath): + self._configPath[i] = OpenRTM_aist.eraseHeadBlank( + cp) + self._loadPath = prop.getProperty(MOD_LOADPTH, "./").split(",") + for i, lp in enumerate(self._loadPath): + self._loadPath[i] = OpenRTM_aist.eraseHeadBlank(lp) + + self._absoluteAllowed = OpenRTM_aist.toBool(prop.getProperty(ALLOW_ABSPATH), + "yes", "no", False) + + self._downloadAllowed = OpenRTM_aist.toBool(prop.getProperty(ALLOW_URL), + "yes", "no", False) + + self._initFuncSuffix = prop.getProperty(INITFUNC_SFX) + self._initFuncPrefix = prop.getProperty(INITFUNC_PFX) + self._modules = OpenRTM_aist.ObjectManager(self.DLLPred) + self._rtcout = None + self._mgr = OpenRTM_aist.Manager.instance() + if not self._rtcout: + self._rtcout = self._mgr.getLogbuf("ModuleManager") + self._modprofs = [] + self._loadfailmods = {} + langs = self._properties.getProperty( + "manager.supported_languages").split(",") + for lang in langs: + lang = lang.strip() + self._loadfailmods[lang] = [] + + self._managerLanguage = self._properties.getProperty( + "manager.language") + + ## + # @if jp + # + # @brief デストラクタ(未実装) + # + # @param self + # + # @else + # + # @brief destructor + # + # @endif + def __del__(self): + self.unloadAll() + + ## + # @if jp + # @class Error + # @brief ファイル・オープン失敗例外処理用内部クラス + # @else + # + # @endif + + class Error(Exception): + def __init__(self, reason_): + self.reason = reason_ + + ## + # @if jp + # @class NotFound + # @brief 未実装部,指定モジュール不明例外処理用内部クラス + # @else + # + # @endif + + class NotFound(Exception): + def __init__(self, name_): + self.name = name_ + + ## + # @if jp + # @class FileNotFound + # @brief 指定ファイル不明例外処理用内部クラス + # @else + # + # @endif + + class FileNotFound(NotFound): + def __init__(self, name_): + ModuleManager.NotFound.__init__(self, name_) + + ## + # @if jp + # @class ModuleNotFound + # @brief 指定モジュール不明例外処理用内部クラス + # @else + # + # @endif + + class ModuleNotFound(NotFound): + def __init__(self, name_): + ModuleManager.NotFound.__init__(self, name_) + + ## + # @if jp + # @class SymbolNotFound + # @brief 指定シンボル不明例外処理用内部クラス + # @else + # + # @endif + + class SymbolNotFound(NotFound): + def __init__(self, name_): + ModuleManager.NotFound.__init__(self, name_) + + ## + # @if jp + # @class NotAllowedOperation + # @brief 指定操作禁止時例外処理用内部クラス + # @else + # + # @endif + + class NotAllowedOperation(Error): + def __init__(self, reason_): + ModuleManager.Error.__init__(self, reason_) + + ## + # @if jp + # @class InvalidArguments + # @brief 指定引数不正時例外処理用内部クラス + # @else + # + # @endif + + class InvalidArguments(Error): + def __init__(self, reason_): + ModuleManager.Error.__init__(self, reason_) + + ## + # @if jp + # @class InvalidOperation + # @brief 指定操作不正時例外処理用内部クラス + # @else + # + # @endif + + class InvalidOperation(Error): + def __init__(self, reason_): + ModuleManager.Error.__init__(self, reason_) + + ## + # @if jp + # + # @brief モジュールのロード、初期化 + # + # 指定したファイルを共有ライブラリとしてロードするとともに、 + # 指定した初期化用オペレーションを実行する。 + # + # @param self + # @param file_name ロード対象モジュール名 (.pyを除いたファイル名) + # @param init_func 初期化処理用オペレーション(デフォルト値:None) + # + # @return 指定したロード対象モジュール名 + # + # @else + # + # @brief Load module + # + # + # @endif + # std::string ModuleManager::load(const std::string& file_name, + # const std::string& init_func) + def load(self, file_name, init_func=None): + + self._rtcout.RTC_TRACE("load(fname = %s)", file_name) + if file_name == "": + raise ModuleManager.InvalidArguments("Invalid file name.") + + if OpenRTM_aist.isURL(file_name): + if not self._downloadAllowed: + raise ModuleManager.NotAllowedOperation( + "Downloading module is not allowed.") + else: + raise ModuleManager.NotFound("Not implemented.") + + import_name = os.path.split(file_name)[-1] + pathChanged = False + file_path = None + + if OpenRTM_aist.isAbsolutePath(file_name): + if not self._absoluteAllowed: + raise ModuleManager.NotAllowedOperation( + "Absolute path is not allowed") + else: + splitted_name = os.path.split(file_name) + save_path = sys.path[:] + sys.path.append(splitted_name[0]) + + pathChanged = True + import_name = splitted_name[-1] + file_path = file_name + + else: + file_path = self.findFile(file_name, self._loadPath) + if not file_path: + raise ModuleManager.FileNotFound(file_name) + + if not self.fileExist(file_path): + raise ModuleManager.FileNotFound(file_name) + + try: + code = "UTF-8-SIG" + import chardet + with open(str(file_path), mode='rb') as f: + code = chardet.detect(f.read())["encoding"] + + with codecs.open(str(file_path), "r", encoding=code) as f: + if init_func is not None: + s = f.read() + if isinstance(s, str): + if s.find(init_func) == -1: + raise ModuleManager.FileNotFound(file_name) + except BaseException: + pass + + if not pathChanged: + splitted_name = os.path.split(file_path) + sys.path.append(splitted_name[0]) + + ext_pos = import_name.find(".py") + if ext_pos > 0: + import_name = import_name[:ext_pos] + + mo = __import__(str(import_name)) + + if pathChanged: + sys.path = save_path + + file_path = file_path.replace("\\", "/") + file_path = file_path.replace("//", "/") + + dll = self.DLLEntity(mo, OpenRTM_aist.Properties()) + dll.properties.setProperty("file_path", file_path) + self._modules.registerObject(dll) + + if init_func is None: + return file_name + + self.symbol(file_path, init_func)(self._mgr) + + return file_name + + ## + # @if jp + # @brief モジュールのアンロード + # + # 指定したロード済みモジュールをクローズし、アンロードする。 + # + # @param self + # @param file_name アンロード対象モジュール名 + # + # @else + # @brief Unload module + # @endif + + def unload(self, file_name): + dll = self._modules.find(file_name) + if not dll: + raise ModuleManager.NotFound(file_name) + dll_name = dll.dll.__name__ + if dll_name in sys.modules.keys(): + sys.modules.pop(dll_name) + self._modules.unregisterObject(file_name) + return + + ## + # @if jp + # @brief 全モジュールのアンロード + # + # 全てのロード済みモジュールをアンロードする。 + # + # @param self + # + # @else + # @brief Unload all modules + # @endif + + def unloadAll(self): + dlls = self._modules.getObjects() + + for dll in dlls: + ident = dll.properties.getProperty("file_path") + self._modules.unregisterObject(ident) + return + + ## + # @if jp + # @brief モジュールのシンボルの参照 + # + # モジュールのシンボルを取得する + # + # @param self + # @param file_name 取得対象ファイル名 + # @param func_name 取得対象関数名 + # + # @else + # @brief Look up a named symbol in the module + # @endif + + def symbol(self, file_name, func_name): + dll = self._modules.find(file_name) + if not dll: + raise ModuleManager.ModuleNotFound(file_name) + + func = getattr(dll.dll, func_name, None) + + if not func: + raise ModuleManager.SymbolNotFound(func_name) + + return func + + ## + # @if jp + # @brief モジュールロードパスを指定する + # + # モジュールロード時に対象モジュールを検索するパスを指定する。 + # + # @param self + # @param load_path_list モジュール検索対象パスリスト + # + # @else + # @brief Set default module load path + # @endif + + def setLoadpath(self, load_path_list): + self._loadPath = load_path_list + return + + ## + # @if jp + # @brief モジュールロードパスを取得する + # + # 設定されているモジュールを検索対象パスリストを取得する。 + # + # @param self + # + # @return load_path モジュール検索対象パスリスト + # + # @else + # @brief Get default module load path + # @endif + + def getLoadPath(self): + return self._loadPath + + ## + # @if jp + # @brief モジュールロードパスを追加する + # + # 指定されたパスリストを検索対象パスリストに追加する。 + # + # @param self + # @param load_path 追加モジュール検索対象パスリスト + # + # @else + # @brief Add module load path + # @endif + + def addLoadpath(self, load_path): + for path in load_path: + self._loadPath.append(path) + return + + ## + # @if jp + # @brief ロード済みのモジュールリストを取得する + # + # 既にロード済みのモジュールリストを取得する。 + # + # @param self + # + # @return ロード済みモジュールリスト + # + # @else + # @brief Get loaded module names + # @endif + # std::vector getLoadedModules(); + + def getLoadedModules(self): + dlls = self._modules.getObjects() + modules = [] + for dll in dlls: + modules.append(dll.properties) + + return modules + + def __getRtcProfile(self, fname): + # file name with full path + fullname = fname + # directory name + dirname = os.path.dirname(fullname) + sys.path.append(dirname) + # basename + basename = os.path.basename(fullname) + # classname + classname = basename.split(".")[0].lower() + + # loaded profile = old profiles - new profiles + # for old + oldp = self._mgr.getFactoryProfiles() + + # for new + comp_spec_name = classname + "_spec" + try: - ret = OpenRTM_aist.popen(cmd).split(os.linesep) - count = 0 - for r in ret: - pos = r.find(":") - if r.find(":") != -1: - count += 1 - key = r[0:pos] - tmp = [key] - OpenRTM_aist.eraseHeadBlank(tmp) - key = tmp[0] - - value = r[pos+1:] - tmp = [value] - OpenRTM_aist.eraseHeadBlank(tmp) - value = tmp[0] - - prop.setProperty(key, value) - if count > 0: - self._rtcout.RTC_DEBUG("rtcprof cmd sub process done.") - prop.setProperty("module_file_name",os.path.basename(mod_)) - prop.setProperty("module_file_path", mod_) - modprops.append(prop) - else: - self._loadfailmods.append(mod_) - - - except: - self._rtcout.RTC_ERROR("popen faild") - self._loadfailmods.append(mod_) - - - ## - # @if jp - # @brief ̵ʥ⥸塼ץե - # - # - # @param self - # - # - # @else - # @brief Removing incalid module profiles - # @endif - def removeInvalidModules(self): - for modprof in self._modprofs: - if not os.path.isfile(modprof.getProperty("module_file_path")): - self._modprofs.remove(modprof) - - - - ## - # @if jp - # @brief Ʊѥ - # - # - # @param self - # @param paths - # - # - # @else - # @brief - # @endif - def deleteSamePath(self, paths): - tmp_paths = [] - for path in paths: - if path: - abs_path = os.path.abspath(path).replace("\\","/") - abs_tmp_paths = [] - for tmp_path in tmp_paths: - abs_tmp_path = os.path.abspath(tmp_path).replace("\\","/") - abs_tmp_paths.append(abs_tmp_path) - if abs_path not in abs_tmp_paths: - tmp_paths.append(path) - return tmp_paths - - - ## - # @if jp - # @brief ɲǽ⥸塼ꥹȤ(̤) - # - # ɲǽʥ⥸塼ΥꥹȤ롣 - # - # @param self - # - # @return ɲǽ⥸塼ꥹ - # - # @else - # @brief Get loadable module names - # @endif - def getLoadableModules(self): - self._rtcout.RTC_TRACE("getLoadableModules()") - # getting loadable module file path list. - langs = self._properties.getProperty("manager.supported_languages").split(",") - self._rtcout.RTC_DEBUG("langs: %s",self._properties.getProperty("manager.supported_languages")) - - for lang in langs: - tmp = [lang] - OpenRTM_aist.eraseHeadBlank(tmp) - lang = tmp[0] - - modules_ = [] - self.getModuleList(lang, modules_) - self._rtcout.RTC_DEBUG("%s: %s", (lang, OpenRTM_aist.flatten(modules_))) - - - tmpprops = [] - self.getModuleProfiles(lang, modules_, tmpprops) - self._rtcout.RTC_DEBUG("Modile profile size: %d (newly founded modules)",len(tmpprops)) - - self._modprofs.extend(tmpprops) - - self._rtcout.RTC_DEBUG("Modile profile size: %d",len(self._modprofs)) - self.removeInvalidModules() - self._rtcout.RTC_DEBUG("Modile profile size: %d (invalid mod-profiles deleted)",len(self._modprofs)) - - return self._modprofs - - - - - - ## - # @if jp - # @brief ⥸塼Хѥ - # - # оݥ⥸塼ХѥĤ褦ꤹ롣 - # - # @param self - # - # @else - # @brief Allow absolute load path - # @endif - def allowAbsolutePath(self): - self._absoluteAllowed = True - - - ## - # @if jp - # @brief ⥸塼Хѥػ - # - # оݥ⥸塼Хѥػߤ褦ꤹ롣 - # - # @param self - # - # @else - # @brief Forbid absolute load path - # @endif - def disallowAbsolutePath(self): - self._absoluteAllowed = False - - - ## - # @if jp - # @brief ⥸塼URL - # - # оݥ⥸塼URLĤ롣 - # ꤬ĤƤ硢⥸塼ɤƥɤ뤳Ȥ - # Ĥ롣 - # - # @param self - # - # @else - # @brief Allow module download - # @endif - def allowModuleDownload(self): - self._downloadAllowed = True - - - ## - # @if jp - # @brief ⥸塼URLػ - # - # оݥ⥸塼URLػߤ롣 - # - # @param self - # - # @else - # @brief Forbid module download - # @endif - def disallowModuleDownload(self): - self._downloadAllowed = False - - - ## - # @if jp - # @brief LoadPath Υեθ - # - # ꤵ줿ѥˡꤵ줿ե뤬¸ߤ뤫ǧ롣 - # - # @param self - # @param fname оݥե̾ - # @param load_path ѥꥹ - # - # @return 줿ե̾ - # - # @else - # @brief Search file from load path - # @endif - def findFile(self, fname, load_path): - file_name = fname - for path in load_path: - suffix = self._properties.getProperty("manager.modules.Python.suffixes") - if fname.find("."+suffix) == -1: - f = str(path) + os.sep + str(file_name)+"."+suffix - else: - f = str(path)+ os.sep + str(file_name) - if self.fileExist(f): - f = f.replace("\\","/") - f = f.replace("//","/") - return f - filelist = [] - OpenRTM_aist.findFile(path,file_name,filelist) - - if len(filelist) > 0: - return filelist[0] - return "" - - - ## - # @if jp - # @brief ե뤬¸ߤ뤫ɤΥå - # - # ꤵ줿ե뤬¸ߤ뤫ǧ롣 - # - # @param self - # @param filename ¸߳ǧоݥե̾ - # - # @return ե¸߳ǧ(ե뤢:trueʤ:false) - # - # @else - # @brief Check file existance - # @endif - def fileExist(self, filename): - fname = filename - suffix = self._properties.getProperty("manager.modules.Python.suffixes") - if fname.find("."+suffix) == -1: - fname = str(filename)+"."+suffix - - if os.path.isfile(fname): - return True - - return False - - - - ## - # @if jp - # @brief ؿܥ - # - # ؿ̾ΤȤΩƤ롣 - # - # @param self - # @param file_path оݥ⥸塼̾ - # - # @return ؿ̾ȤΩƷ - # - # @else - # @brief Create initialize function symbol - # @endif - def getInitFuncName(self, file_path): - base_name = os.path.basename(file_path) - return str(self._initFuncPrefix)+str(base_name)+str(self._initFuncSuffix) - - - - ## - # @if jp - # @class DLL - # @brief ⥸塼ݻ饹 - # @else - # - # @endif - class DLL: - def __init__(self, dll): - self.dll = dll - return - - - class DLLEntity: - def __init__(self,dll,prop): - self.dll = dll - self.properties = prop - - - class DLLPred: - def __init__(self, name=None, factory=None): - self._filepath = name or factory - - def __call__(self, dll): - return self._filepath == dll.properties.getProperty("file_path") + code = "UTF-8-SIG" + import chardet + with open(str(fullname), mode='rb') as f: + code = chardet.detect(f.read())["encoding"] + + with codecs.open(str(fullname), "r", encoding=code) as f: + s = f.read() + if s.find(comp_spec_name) == -1: + return None + except BaseException: + pass + + imp_file = __import__(basename.split(".")[0]) + comp_spec = getattr(imp_file, comp_spec_name, None) + if not comp_spec: + return None + newp = OpenRTM_aist.Properties(defaults_str=comp_spec) + + profs = [] + + exists = False + for o in oldp: + if o.getProperty("implementation_id") == newp.getProperty("implementation_id") and \ + o.getProperty("type_name") == newp.getProperty("type_name") and \ + o.getProperty("description") == newp.getProperty("description") and \ + o.getProperty("version") == newp.getProperty("version"): + exists = True + if not exists: + profs.append(newp) + + # loaded component profile have to be one + if not profs: + return OpenRTM_aist.Properties() + + # if len(profs) > 1: + # return None + + return profs[0] + + ## + # @if jp + # @brief 指定言語におけるロードパス上のローダブルなファイルリストを返す + # + # + # @param self + # @param lang + # @param modules + # + # + # @else + # @brief Getting loadable file list on the loadpath for given language + # @endif + + def getModuleList(self, lang, modules): + l = "manager.modules." + lang + lprop = self._properties.getNode(l) + + paths = lprop.getProperty("load_paths").split(",") + + paths.extend(self._loadPath) + paths = self.deleteSamePath(paths) + + suffixes = lprop.getProperty("suffixes").split(",") + + self._rtcout.RTC_DEBUG("suffixes: %s", OpenRTM_aist.flatten(suffixes)) + + for path in paths: + if not path: + self._rtcout.RTC_WARN("Given load path is empty") + continue + self._rtcout.RTC_DEBUG("Module load path: %s", path) + flist = [] + for suffix in suffixes: + suffix = OpenRTM_aist.eraseHeadBlank(suffix) + + tmp = [] + OpenRTM_aist.getFileList(path, suffix, tmp) + + if lang == self._managerLanguage: + for f in tmp: + if f.find("__init__.py") != -1: + tmp.remove(f) + + self._rtcout.RTC_DEBUG( + "File list (path:%s, ext:%s): %s", + (path, + suffix, + OpenRTM_aist.flatten(suffixes))) + flist.extend(tmp) + + for f in flist: + f = f.replace("\\", "/") + f = f.replace("//", "/") + self.addNewFile(f, modules, lang) + modules = list(set(modules)) + + ## + # @if jp + # @brief キャッシュに無いパスだけmodulesに追加する + # + # + # @param self + # @param fpath + # @param modules + # + # + # @else + # @brief Adding file path not existing cache + # @endif + + def addNewFile(self, fpath, modules, lang): + exists = False + for modprof in self._modprofs: + if modprof.getProperty("module_file_path") == fpath: + self._rtcout.RTC_DEBUG( + "Module %s already exists in cache.", fpath) + return + + if not (fpath in self._loadfailmods[lang]): + self._rtcout.RTC_DEBUG("New module: %s", fpath) + modules.append(fpath) + + ## + # @if jp + # @brief 指定言語、ファイルリストからモジュールのプロパティを返す + # + # + # @param self + # @param lang + # @param modules + # @param modprops + # + # + # @else + # @brief Getting loadable file list on the loadpath for given language + # @endif + + def getModuleProfiles(self, lang, modules, modprops): + l = "manager.modules." + lang + lprop = self._properties.getNode(l) + + paths = lprop.getProperty("load_paths").split(",") + + for mod_ in modules: + + if lang == self._managerLanguage: + prop = self.__getRtcProfile(mod_) + if prop: + prop.setProperty( + "module_file_name", os.path.basename(mod_)) + prop.setProperty("module_file_path", mod_) + prop.setProperty("language", lang) + modprops.append(prop) + else: + prop = OpenRTM_aist.Properties() + cmd = lprop.getProperty("profile_cmd") + if os.name == "nt": + cmd = "cmd /c " + cmd + cmd = cmd + " \"" + mod_ + "\"" + + try: + ret = OpenRTM_aist.popen(cmd).split(os.linesep) + count = 0 + for r in ret: + pos = r.find(":") + if r.find(":") != -1: + count += 1 + key = r[0:pos] + key = OpenRTM_aist.eraseHeadBlank(key) + + value = r[pos + 1:] + value = OpenRTM_aist.eraseHeadBlank(value) + + prop.setProperty(key, value) + if count > 0: + self._rtcout.RTC_DEBUG("rtcprof cmd sub process done.") + prop.setProperty( + "module_file_name", os.path.basename(mod_)) + prop.setProperty("module_file_path", mod_) + prop.setProperty("language", lang) + modprops.append(prop) + else: + self._loadfailmods[lang].append(mod_) + + except BaseException: + self._rtcout.RTC_ERROR("popen faild") + self._loadfailmods[lang].append(mod_) + + ## + # @if jp + # @brief 無効なモジュールプロファイルを削除する + # + # + # @param self + # + # + # @else + # @brief Removing incalid module profiles + # @endif + + def removeInvalidModules(self): + for modprof in self._modprofs: + if not os.path.isfile(modprof.getProperty("module_file_path")): + self._modprofs.remove(modprof) + + ## + # @if jp + # @brief 同じパスを削除 + # + # + # @param self + # @param paths + # + # + # @else + # @brief + # @endif + + def deleteSamePath(self, paths): + tmp_paths = [] + for path in paths: + if path: + abs_path = os.path.abspath(path).replace("\\", "/") + abs_tmp_paths = [] + for tmp_path in tmp_paths: + abs_tmp_path = os.path.abspath(tmp_path).replace("\\", "/") + abs_tmp_paths.append(abs_tmp_path) + if abs_path not in abs_tmp_paths: + tmp_paths.append(path) + return tmp_paths + + ## + # @if jp + # @brief ロード可能モジュールリストを取得する(未実装) + # + # ロード可能なモジュールのリストを取得する。 + # + # @param self + # + # @return ロード可能モジュールリスト + # + # @else + # @brief Get loadable module names + # @endif + + def getLoadableModules(self): + self._rtcout.RTC_TRACE("getLoadableModules()") + # getting loadable module file path list. + langs = self._properties.getProperty( + "manager.supported_languages").split(",") + self._rtcout.RTC_DEBUG( + "langs: %s", + self._properties.getProperty("manager.supported_languages")) + + for lang in langs: + lang = lang.strip() + + modules_ = [] + self.getModuleList(lang, modules_) + self._rtcout.RTC_DEBUG( + "%s: %s", (lang, OpenRTM_aist.flatten(modules_))) + + tmpprops = [] + self.getModuleProfiles(lang, modules_, tmpprops) + self._rtcout.RTC_DEBUG( + "Modile profile size: %d (newly founded modules)", + len(tmpprops)) + + self._modprofs.extend(tmpprops) + + self._rtcout.RTC_DEBUG("Modile profile size: %d", len(self._modprofs)) + self.removeInvalidModules() + self._rtcout.RTC_DEBUG( + "Modile profile size: %d (invalid mod-profiles deleted)", len(self._modprofs)) + + return self._modprofs + + ## + # @if jp + # @brief モジュールの絶対パス指定許可 + # + # ロード対象モジュールの絶対パス指定を許可するように設定する。 + # + # @param self + # + # @else + # @brief Allow absolute load path + # @endif + + def allowAbsolutePath(self): + self._absoluteAllowed = True + + ## + # @if jp + # @brief モジュールの絶対パス指定禁止 + # + # ロード対象モジュールの絶対パス指定を禁止するように設定する。 + # + # @param self + # + # @else + # @brief Forbid absolute load path + # @endif + + def disallowAbsolutePath(self): + self._absoluteAllowed = False + + ## + # @if jp + # @brief モジュールのURL指定許可 + # + # ロード対象モジュールのURL指定を許可する。 + # 本設定が許可されている場合、モジュールをダウンロードしてロードすることが + # 許可される。 + # + # @param self + # + # @else + # @brief Allow module download + # @endif + + def allowModuleDownload(self): + self._downloadAllowed = True + + ## + # @if jp + # @brief モジュールのURL指定禁止 + # + # ロード対象モジュールのURL指定を禁止する。 + # + # @param self + # + # @else + # @brief Forbid module download + # @endif + + def disallowModuleDownload(self): + self._downloadAllowed = False + + ## + # @if jp + # @brief LoadPath からのファイルの検索 + # + # 指定されたパス内に、指定されたファイルが存在するか確認する。 + # + # @param self + # @param fname 検索対象ファイル名 + # @param load_path 検索先パスリスト + # + # @return 検索されたファイル名 + # + # @else + # @brief Search file from load path + # @endif + + def findFile(self, fname, load_path): + file_name = fname + for path in load_path: + suffix = self._properties.getProperty( + "manager.modules."+self._managerLanguage+".suffixes") + if fname.find("." + suffix) == -1: + f = str(path) + os.sep + str(file_name) + "." + suffix + else: + f = str(path) + os.sep + str(file_name) + if self.fileExist(f): + f = f.replace("\\", "/") + f = f.replace("//", "/") + return f + filelist = [] + OpenRTM_aist.findFile(path, file_name, filelist) + + if filelist: + return filelist[0] + return "" + + ## + # @if jp + # @brief ファイルが存在するかどうかのチェック + # + # 指定されたファイルが存在するか確認する。 + # + # @param self + # @param filename 存在確認対象ファイル名 + # + # @return ファイル存在確認結果(ファイルあり:true,なし:false) + # + # @else + # @brief Check file existance + # @endif + + def fileExist(self, filename): + fname = filename + suffix = self._properties.getProperty( + "manager.modules."+self._managerLanguage+".suffixes") + if fname.find("." + suffix) == -1: + fname = str(filename) + "." + suffix + + if os.path.isfile(fname): + return True + + return False + + ## + # @if jp + # @brief 初期化関数シンボルを生成する + # + # 初期化関数の名称を組み立てる。 + # + # @param self + # @param file_path 初期化対象モジュール名称 + # + # @return 初期化関数名称組み立て結果 + # + # @else + # @brief Create initialize function symbol + # @endif + + def getInitFuncName(self, file_path): + base_name = os.path.basename(file_path) + return str(self._initFuncPrefix) + \ + str(base_name) + str(self._initFuncSuffix) + + ## + # @if jp + # @class DLL + # @brief モジュール保持用内部クラス + # @else + # + # @endif + + class DLL: + def __init__(self, dll): + self.dll = dll + return + + class DLLEntity: + def __init__(self, dll, prop): + self.dll = dll + self.properties = prop + + class DLLPred: + def __init__(self, name=None, factory=None): + self._filepath = name or factory + + def __call__(self, dll): + return self._filepath == dll.properties.getProperty("file_path") diff --git a/OpenRTM_aist/MultilayerCompositeEC.py b/OpenRTM_aist/MultilayerCompositeEC.py index 3f12d9ab..c63faf0d 100644 --- a/OpenRTM_aist/MultilayerCompositeEC.py +++ b/OpenRTM_aist/MultilayerCompositeEC.py @@ -1,5 +1,5 @@ #!/usr/bin/env python -# -*- coding: euc-jp -*- +# -*- coding: utf-8 -*- ## # @file MultilayerCompositeEC.py @@ -24,16 +24,17 @@ import OpenRTM_aist import OpenRTM -import RTC, RTC__POA +import RTC +import RTC__POA DEFAULT_PERIOD = 0.000001 ## # @if jp # @class MultilayerCompositeEC -# @brief MultilayerCompositeEC 饹 +# @brief MultilayerCompositeEC クラス # -# Periodic Sampled Data Processing(¹)ExecutionContext饹 +# Periodic Sampled Data Processing(周期実行用)ExecutionContextクラス。 # # @since 0.4.0 # @@ -41,596 +42,579 @@ # @class MultilayerCompositeEC # @brief MultilayerCompositeEC class # @endif -class MultilayerCompositeEC(OpenRTM_aist.PeriodicExecutionContext): - """ - """ - - ## - # @if jp - # @brief 󥹥ȥ饯 - # - # 󥹥ȥ饯 - # ꤵ줿ͤץեꤹ롣 - # - # @else - # @brief Constructor - # @endif - def __init__(self): - - OpenRTM_aist.PeriodicExecutionContext.__init__(self) - self._rtcout = OpenRTM_aist.Manager.instance().getLogbuf("rtobject.multilayercomposite_ec") - self._rtcout.RTC_TRACE("MultilayerCompositeEC.__init__()") - - self._tasklist = [] - self._ownersm = None - return - ## - # @if jp - # @brief λؿ - # - # @param self - # @param Task - # - # @else - # @brief - # @param self - # @param Task - # @endif - def exit(self, Task=OpenRTM_aist.Task): - OpenRTM_aist.PeriodicExecutionContext.exit(self) - for task in self._tasklist: - task.finalize() - return +class MultilayerCompositeEC(OpenRTM_aist.PeriodicExecutionContext): + """ + """ - ## - # @if jp - # @brief ؿ - # - # @param self - # @param props ץѥƥ - # - # @else - # @brief - # @param self - # @param props - # @endif - def init(self, props): - OpenRTM_aist.PeriodicExecutionContext.init(self, props) - #prop.getProperty("thread_type", "default") - - - - ## - # @if jp - # @brief ݡͥȤХɤ롣 - # - # @param self - # @param rtc RTC - # - # @else - # @brief Bind the component. - # - # @param self - # @param rtc RTC - # - # @endif - def bindComponent(self, rtc): - ret = OpenRTM_aist.ExecutionContextBase.bindComponent(self, rtc) - - mgr = OpenRTM_aist.Manager.instance() - - threads_str = rtc.getProperties().getProperty("conf.default.members") - str = [threads_str] - threads = str[0].split("|") - for thread in threads: - rtcs = [] - members = thread.split(",") - - for member in members: - member = member.strip() - if member == "": - continue - comp = mgr.getComponent(member) - - if comp is None: - self._rtcout.RTC_ERROR("no RTC found: %s", member) - continue - - rtobj = comp.getObjRef() - if CORBA.is_nil(rtobj): - continue - rtcs.append(rtobj) - - self.addTask(rtcs) - - - return ret - - ## - # @if jp - # @class - # @brief worker Ѿѿ饹 - # @else - # @brief - # - # @endif - class WorkerThreadCtrl: ## # @if jp - # @brief 󥹥ȥ饯 + # @brief コンストラクタ # - # 󥹥ȥ饯 - # - # @param self + # コンストラクタ + # 設定された値をプロファイルに設定する。 # # @else # @brief Constructor # @endif def __init__(self): - self._mutex = threading.RLock() - self._cond = threading.Condition(self._mutex) - self._running = False - - ## - # @if jp - # @class - # @brief RTC¹ԥå - # @else - # @brief - # - # @endif - class ChildTask: + + OpenRTM_aist.PeriodicExecutionContext.__init__(self) + self._rtcout = OpenRTM_aist.Manager.instance().getLogbuf( + "rtobject.multilayercomposite_ec") + self._rtcout.RTC_TRACE("MultilayerCompositeEC.__init__()") + + self._tasklist = [] + self._ownersm = None + + return + ## # @if jp - # @brief 󥹥ȥ饯 + # @brief 終了関数 # - # @param self - # @param task ¹ԥå - # @param ec ¹ԥƥ + # @param self  + # @param Task  # # @else - # - # @brief - # - # @param self - # @param task - # @param ec - # + # @brief + # @param self  + # @param Task  # @endif - def __init__(self, task, ec): - self._rtcs = [] - self._task = task - self._ec = ec - self._comps = [] - self._worker = MultilayerCompositeEC.WorkerThreadCtrl() - self._signal_worker = MultilayerCompositeEC.WorkerThreadCtrl() + def exit(self, Task=OpenRTM_aist.Task): + OpenRTM_aist.PeriodicExecutionContext.exit(self) + for task in self._tasklist: + task.finalize() + return ## # @if jp - # @brief ¹ԤRTCɲ + # @brief 初期化関数 # - # @param self - # @param rtc RTC + # @param self  + # @param props プロパティ # # @else - # - # @brief - # - # @param self - # @param rtc RTC - # + # @brief + # @param self  + # @param props # @endif - def addComponent(self, rtc): - self._rtcs.append(rtc) + def init(self, props): + OpenRTM_aist.PeriodicExecutionContext.init(self, props) + #prop.getProperty("thread_type", "default") ## # @if jp - # @brief ơȥޥΥꥹȤ򹹿 + # @brief コンポーネントをバインドする。 # # @param self - # @param return + # @param rtc RTC # # @else - # - # @brief + # @brief Bind the component. # # @param self - # @param return + # @param rtc RTC # # @endif - def updateCompList(self): - for rtc in self._rtcs[:]: - comp = self._ec.findComponent(rtc) - if comp: - self._rtcs.remove(rtc) - self._comps.append(comp) + + def bindComponent(self, rtc): + ret = OpenRTM_aist.ExecutionContextBase.bindComponent(self, rtc) + + mgr = OpenRTM_aist.Manager.instance() + + threads_str = rtc.getProperties().getProperty("conf.default.members") + str = [threads_str] + threads = str[0].split("|") + for thread in threads: + rtcs = [] + members = thread.split(",") + + for member in members: + member = member.strip() + if member == "": + continue + comp = mgr.getComponent(member) + + if comp is None: + self._rtcout.RTC_ERROR("no RTC found: %s", member) + continue + + rtobj = comp.getObjRef() + if CORBA.is_nil(rtobj): + continue + rtcs.append(rtobj) + + self.addTask(rtcs) + + return ret ## # @if jp - # @brief åɼ¹Դؿ - # - # @param self - # @param return - # + # @class + # @brief worker 用状態変数クラス # @else - # - # @brief - # - # @param self - # @param return + # @brief # # @endif - def svc(self): - self._worker._running = True - - - self._signal_worker._cond.acquire() - while not self._signal_worker._running: - self._signal_worker._cond.wait() - self._signal_worker._cond.release() - self._signal_worker._running = False - - - - self.updateCompList() - for comp in self._comps: - comp.workerPreDo() - comp.workerDo() - comp.workerPostDo() - self._worker._running = False - self._worker._cond.acquire() - self._worker._cond.notify() - self._worker._cond.release() - - - self._signal_worker._cond.acquire() - while not self._signal_worker._running: - self._signal_worker._cond.wait() - self._signal_worker._cond.release() - self._signal_worker._running = False - - - return 0 + class WorkerThreadCtrl: + ## + # @if jp + # @brief コンストラクタ + # + # コンストラクタ + # + # @param self + # + # @else + # @brief Constructor + # @endif + def __init__(self): + self._mutex = threading.RLock() + self._cond = threading.Condition(self._mutex) + self._running = False ## # @if jp - # @brief 1ν¹ - # - # @param self - # + # @class + # @brief RTC周期実行スレッド # @else - # - # @brief - # - # @param self + # @brief # # @endif - def signal(self): - - while not self._worker._running: - self._task.signal() - - - self._signal_worker._running = True - self._signal_worker._cond.acquire() - self._signal_worker._cond.notify() - self._signal_worker._cond.release() - - - + class ChildTask: + ## + # @if jp + # @brief コンストラクタ + # + # @param self + # @param task 周期実行スレッド + # @param ec 実行コンテキスト + # + # @else + # + # @brief + # + # @param self + # @param task + # @param ec + # + # @endif + def __init__(self, task, ec): + self._rtcs = [] + self._task = task + self._ec = ec + self._comps = [] + self._worker = MultilayerCompositeEC.WorkerThreadCtrl() + self._signal_worker = MultilayerCompositeEC.WorkerThreadCtrl() + + ## + # @if jp + # @brief 実行するRTCを追加 + # + # @param self + # @param rtc RTC + # + # @else + # + # @brief + # + # @param self + # @param rtc RTC + # + # @endif + def addComponent(self, rtc): + self._rtcs.append(rtc) + + ## + # @if jp + # @brief ステートマシンのリストを更新 + # + # @param self + # @param return + # + # @else + # + # @brief + # + # @param self + # @param return + # + # @endif + def updateCompList(self): + for rtc in self._rtcs[:]: + comp = self._ec.findComponent(rtc) + if comp: + self._rtcs.remove(rtc) + self._comps.append(comp) + + ## + # @if jp + # @brief スレッド実行関数 + # + # @param self + # @param return + # + # @else + # + # @brief + # + # @param self + # @param return + # + # @endif + def svc(self): + self._worker._running = True + + self._signal_worker._cond.acquire() + while not self._signal_worker._running: + self._signal_worker._cond.wait() + self._signal_worker._cond.release() + self._signal_worker._running = False + + self.updateCompList() + for comp in self._comps: + comp.workerPreDo() + comp.workerDo() + comp.workerPostDo() + self._worker._running = False + self._worker._cond.acquire() + self._worker._cond.notify() + self._worker._cond.release() + + self._signal_worker._cond.acquire() + while not self._signal_worker._running: + self._signal_worker._cond.wait() + self._signal_worker._cond.release() + self._signal_worker._running = False + + return 0 + + ## + # @if jp + # @brief 1回の処理を実行 + # + # @param self + # + # @else + # + # @brief + # + # @param self + # + # @endif + def signal(self): + + while not self._worker._running: + self._task.signal() + + self._signal_worker._running = True + self._signal_worker._cond.acquire() + self._signal_worker._cond.notify() + self._signal_worker._cond.release() + + ## + # @if jp + # @brief 1回の処理終了まで待機 + # + # @param self + # + # @else + # + # @brief + # + # @param self + # + # @endif + def join(self): + + self._worker._cond.acquire() + while self._worker._running: + self._worker._cond.wait() + self._worker._cond.release() + + self._signal_worker._running = True + self._signal_worker._cond.acquire() + self._signal_worker._cond.notify() + self._signal_worker._cond.release() + + ## + # @if jp + # @brief タスク周期時間計測結果を取得 + # + # @param self + # @return 計測結果 + # + # @else + # + # @brief + # + # @param self + # @return + # + # @endif + + def getPeriodStat(self): + return self._task.getPeriodStat() + + ## + # @if jp + # @brief タスク関数実行時間計測結果を取得 + # + # @param self + # @return 計測結果 + # + # @else + # + # @brief + # + # @param self + # @return + # + # @endif + + def getExecStat(self): + return self._task.getExecStat() + + ## + # @if jp + # @brief RTC実行スレッド終了関数 + # + # @param self + # + # @else + # + # @brief + # + # @param self + # + # @endif + def finalize(self): + self._task.resume() + self._task.finalize() + ## # @if jp - # @brief 1νλޤԵ + # @brief RTC実行スレッド作成 # # @param self + # @param rtcs スレッドに関連付けるRTC一覧 + # @return ステートマシン # # @else # - # @brief + # @brief # # @param self + # @param rtcs # # @endif - def join(self): - - self._worker._cond.acquire() - while self._worker._running: - self._worker._cond.wait() - self._worker._cond.release() - - - self._signal_worker._running = True - self._signal_worker._cond.acquire() - self._signal_worker._cond.notify() - self._signal_worker._cond.release() - + def addTask(self, rtcs): + prop = self._profile.getProperties().getNode("ec" + str(len(self._tasklist))) + factory = OpenRTM_aist.PeriodicTaskFactory.instance() + + task = factory.createObject(prop.getProperty("thread_type", "default")) + if not task: + self._rtcout.RTC_ERROR( + "Task creation failed: %s", prop.getProperty( + "thread_type", "default")) + return + + ct = MultilayerCompositeEC.ChildTask(task, self) + + mprop = prop.getNode("measurement") + task.setTask(ct.svc) + task.setPeriod(0.0) + task.executionMeasure(OpenRTM_aist.toBool(mprop.getProperty("exec_time"), + "enable", "disable", True)) + ecount = 0 + ret, ecount = OpenRTM_aist.stringTo( + ecount, mprop.getProperty("exec_count")) + if ret: + task.executionMeasureCount(ecount) + + task.periodicMeasure(OpenRTM_aist.toBool(mprop.getProperty("period_time"), + "enable", "disable", True)) + pcount = 0 + ret, pcount = OpenRTM_aist.stringTo( + pcount, mprop.getProperty("period_count")) + if ret: + task.periodicMeasureCount(pcount) + + for rtc in rtcs: + self.addRTCToTask(ct, rtc) + + self._tasklist.append(ct) + + task.suspend() + task.activate() + task.suspend() ## # @if jp - # @brief ַ¬̤ + # @brief コンポーネント探索関数 # # @param self - # @return ¬ + # @param rtobj RTC + # @return ステートマシン # # @else # - # @brief + # @brief # # @param self + # @param rtobj # @return # # @endif - def getPeriodStat(self): - return self._task.getPeriodStat() + def findComponent(self, rtobj): + return self._worker.findComponent(rtobj) ## # @if jp - # @brief ؿ¹Իַ¬̤ + # @brief RTC実行スレッドにRTCを追加 + # 複合コンポーネントの場合は子コンポーネントも追加 # # @param self - # @return ¬ + # @param task RTC実行スレッド + # @param rtobj RTC # # @else # - # @brief + # @brief # # @param self - # @return + # @param task + # @param rtobj # # @endif - def getExecStat(self): - return self._task.getExecStat() + def addRTCToTask(self, task, rtobj): + #comp = self._worker.findComponent(rtobj) + orglist = rtobj.get_owned_organizations() + if not orglist: + task.addComponent(rtobj) + + for org in orglist: + sdos = org.get_members() + for sdo in sdos: + dfc = sdo._narrow(OpenRTM.DataFlowComponent) + self.addRTCToTask(task, dfc) ## # @if jp - # @brief RTC¹ԥåɽλؿ + # @brief コンポーネントのアクティビティスレッド関数 # - # @param self + # コンポーネントの内部アクティビティスレッドの実行関数。 + # ACE_Task サービスクラスメソッドのオーバーライド。 # # @else # - # @brief + # @brief Create internal activity thread # - # @param self + # Run by a daemon thread to handle deferred processing. + # ACE_Task class method override. # # @endif - def finalize(self): - self._task.resume() - self._task.finalize() - - OpenRTM_aist.PeriodicTaskFactory.instance().deleteObject(self._task) - - ## - # @if jp - # @brief RTC¹ԥåɺ - # - # @param self - # @param rtcs åɤ˴ϢդRTC - # @return ơȥޥ - # - # @else - # - # @brief - # - # @param self - # @param rtcs - # - # @endif - def addTask(self, rtcs): - prop = self._profile.getProperties().getNode("ec"+str(len(self._tasklist))) - factory = OpenRTM_aist.PeriodicTaskFactory.instance() - - task = factory.createObject(prop.getProperty("thread_type", "default")) - if not task: - self._rtcout.RTC_ERROR("Task creation failed: %s", prop.getProperty("thread_type", "default")) - return - - ct = MultilayerCompositeEC.ChildTask(task, self) - - mprop = prop.getNode("measurement") - task.setTask(ct.svc) - task.setPeriod(0.0) - task.executionMeasure(OpenRTM_aist.toBool(mprop.getProperty("exec_time"), - "enable", "disable", True)) - ecount = [0] - if OpenRTM_aist.stringTo(ecount, mprop.getProperty("exec_count")): - task.executionMeasureCount(ecount[0]) - - task.periodicMeasure(OpenRTM_aist.toBool(mprop.getProperty("period_time"), - "enable", "disable", True)) - pcount = [0] - if OpenRTM_aist.stringTo(pcount, mprop.getProperty("period_count")): - task.periodicMeasureCount(pcount[0]) - - for rtc in rtcs: - self.addRTCToTask(ct, rtc) - - self._tasklist.append(ct) - - task.suspend() - task.activate() - task.suspend() - - - - ## - # @if jp - # @brief ݡͥõؿ - # - # @param self - # @param rtobj RTC - # @return ơȥޥ - # - # @else - # - # @brief - # - # @param self - # @param rtobj - # @return - # - # @endif - def findComponent(self, rtobj): - return self._worker.findComponent(rtobj) - - ## - # @if jp - # @brief RTC¹ԥåɤRTCɲ - # ʣ祳ݡͥȤξϻҥݡͥȤɲ - # - # @param self - # @param task RTC¹ԥå - # @param rtobj RTC - # - # @else - # - # @brief - # - # @param self - # @param task - # @param rtobj - # - # @endif - def addRTCToTask(self, task, rtobj): - #comp = self._worker.findComponent(rtobj) - orglist = rtobj.get_owned_organizations() - if len(orglist) == 0: - task.addComponent(rtobj) - - for org in orglist: - sdos = org.get_members() - for sdo in sdos: - dfc = sdo._narrow(OpenRTM.DataFlowComponent) - self.addRTCToTask(task, dfc) - - - - ## - # @if jp - # @brief ݡͥȤΥƥӥƥåɴؿ - # - # ݡͥȤƥӥƥåɤμ¹Դؿ - # ACE_Task ӥ饹᥽åɤΥС饤ɡ - # - # @else - # - # @brief Create internal activity thread - # - # Run by a daemon thread to handle deferred processing. - # ACE_Task class method override. - # - # @endif - def svc(self): - self._rtcout.RTC_TRACE("svc()") - count_ = 0 - owner = self.getOwner() - self._ownersm = self._worker.findComponent(owner) - - #if len(self._cpu) > 0: - # ret = OpenRTM_aist.setThreadAffinity(self._cpu) - # if ret == False: - # self._rtcout.RTC_ERROR("CPU affinity mask setting failed") - - while self.threadRunning(): - - - self._ownersm.workerPreDo() - #OpenRTM_aist.ExecutionContextBase.invokeWorkerPreDo(self) - # Thread will stopped when all RTCs are INACTIVE. - # Therefore WorkerPreDo(updating state) have to be invoked - # before stopping thread. - - guard = OpenRTM_aist.ScopedLock(self._workerthread._mutex) - while not self._workerthread._running: - self._workerthread._cond.wait() - del guard - - t0_ = OpenRTM_aist.Time() - - - #OpenRTM_aist.ExecutionContextBase.invokeWorkerDo(self) - self._ownersm.workerDo() - #OpenRTM_aist.ExecutionContextBase.invokeWorkerPostDo(self) - self._ownersm.workerPostDo() - - - for task in self._tasklist: - task.signal() - - #time.sleep(0.1) - - - for task in self._tasklist: - task.join() - #print task._task.getExecStat()._max_interval - #print task._task.getExecStat()._min_interval - #print task._task.getExecStat()._mean_interval - #print task._task.getExecStat()._std_deviation - - - - - - t1_ = OpenRTM_aist.Time() - - - period_ = self.getPeriod() - - if count_ > 1000: - exctm_ = (t1_ - t0_).getTime().toDouble() - slptm_ = period_.toDouble() - exctm_ - self._rtcout.RTC_PARANOID("Period: %f [s]", period_.toDouble()) - self._rtcout.RTC_PARANOID("Execution: %f [s]", exctm_) - self._rtcout.RTC_PARANOID("Sleep: %f [s]", slptm_) - - for i in range(len(self._tasklist)): - task = self._tasklist[i] - stat = task.getExecStat() - self._rtcout.RTC_PARANOID("MAX(%d): %f [s]", (i,stat._max_interval)) - self._rtcout.RTC_PARANOID("MIN(%d): %f [s]", (i,stat._min_interval)) - self._rtcout.RTC_PARANOID("MEAN(%d): %f [s]", (i,stat._mean_interval)) - self._rtcout.RTC_PARANOID("SD(%d): %f [s]", (i,stat._std_deviation)) - - - - t2_ = OpenRTM_aist.Time() - - if not self._nowait and period_.toDouble() > ((t1_ - t0_).getTime().toDouble()): - if count_ > 1000: - self._rtcout.RTC_PARANOID("sleeping...") - slptm_ = period_.toDouble() - (t1_ - t0_).getTime().toDouble() - time.sleep(slptm_) - - if count_ > 1000: - t3_ = OpenRTM_aist.Time() - self._rtcout.RTC_PARANOID("Slept: %f [s]", (t3_ - t2_).getTime().toDouble()) - count_ = 0 - count_ += 1 - - self._rtcout.RTC_DEBUG("Thread terminated.") - return 0 - - - + def svc(self): + self._rtcout.RTC_TRACE("svc()") + count_ = 0 + owner = self.getOwner() + self._ownersm = self._worker.findComponent(owner) + + # if len(self._cpu) > 0: + # ret = OpenRTM_aist.setThreadAffinity(self._cpu) + # if ret == False: + # self._rtcout.RTC_ERROR("CPU affinity mask setting failed") + + while self.threadRunning(): + + self._ownersm.workerPreDo() + # OpenRTM_aist.ExecutionContextBase.invokeWorkerPreDo(self) + # Thread will stopped when all RTCs are INACTIVE. + # Therefore WorkerPreDo(updating state) have to be invoked + # before stopping thread. + + guard = OpenRTM_aist.ScopedLock(self._workerthread._mutex) + while not self._workerthread._running: + self._workerthread._cond.wait() + del guard + + t0_ = OpenRTM_aist.Time() + + # OpenRTM_aist.ExecutionContextBase.invokeWorkerDo(self) + self._ownersm.workerDo() + # OpenRTM_aist.ExecutionContextBase.invokeWorkerPostDo(self) + self._ownersm.workerPostDo() + + for task in self._tasklist: + task.signal() + + # time.sleep(0.1) + + for task in self._tasklist: + task.join() + # print task._task.getExecStat()._max_interval + # print task._task.getExecStat()._min_interval + # print task._task.getExecStat()._mean_interval + # print task._task.getExecStat()._std_deviation + + t1_ = OpenRTM_aist.Time() + + period_ = self.getPeriod() + + if count_ > 1000: + exctm_ = (t1_ - t0_).getTime().toDouble() + slptm_ = period_.toDouble() - exctm_ + self._rtcout.RTC_PARANOID( + "Period: %f [s]", period_.toDouble()) + self._rtcout.RTC_PARANOID("Execution: %f [s]", exctm_) + self._rtcout.RTC_PARANOID("Sleep: %f [s]", slptm_) + + for i, task in enumerate(self._tasklist): + stat = task.getExecStat() + self._rtcout.RTC_PARANOID( + "MAX(%d): %f [s]", (i, stat._max_interval)) + self._rtcout.RTC_PARANOID( + "MIN(%d): %f [s]", (i, stat._min_interval)) + self._rtcout.RTC_PARANOID( + "MEAN(%d): %f [s]", (i, stat._mean_interval)) + self._rtcout.RTC_PARANOID( + "SD(%d): %f [s]", (i, stat._std_deviation)) + + t2_ = OpenRTM_aist.Time() + + if not self._nowait and period_.toDouble() > ((t1_ - t0_).getTime().toDouble()): + if count_ > 1000: + self._rtcout.RTC_PARANOID("sleeping...") + slptm_ = period_.toDouble() - (t1_ - t0_).getTime().toDouble() + time.sleep(slptm_) + + if count_ > 1000: + t3_ = OpenRTM_aist.Time() + self._rtcout.RTC_PARANOID( + "Slept: %f [s]", (t3_ - t2_).getTime().toDouble()) + count_ = 0 + count_ += 1 + + self._rtcout.RTC_DEBUG("Thread terminated.") + return 0 ## # @if jp -# @brief ExecutionContext +# @brief ExecutionContext を初期化する # -# ExecutionContext ưѥեȥϿ롣 +# ExecutionContext 起動用ファクトリを登録する。 # -# @param manager ޥ͡㥪֥ +# @param manager マネージャオブジェクト # # @else # # @endif def MultilayerCompositeECInit(manager): - OpenRTM_aist.ExecutionContextFactory.instance().addFactory("MultilayerCompositeEC", - OpenRTM_aist.MultilayerCompositeEC, - OpenRTM_aist.ECDelete) - return + OpenRTM_aist.ExecutionContextFactory.instance().addFactory("MultilayerCompositeEC", + OpenRTM_aist.MultilayerCompositeEC) + return diff --git a/OpenRTM_aist/NVUtil.py b/OpenRTM_aist/NVUtil.py index 7c4dc3c1..02bc87ff 100644 --- a/OpenRTM_aist/NVUtil.py +++ b/OpenRTM_aist/NVUtil.py @@ -1,12 +1,12 @@ #!/usr/bin/env python -# -*- coding: euc-jp -*- +# -*- coding: utf-8 -*- ## # @file NVUtil.py # @brief NameValue and NVList utility functions # @date $Date: 2007/09/11$ # @author Noriaki Ando and Shinji Kurihara -# +# # Copyright (C) 2006-2008 # Noriaki Ando # Task-intelligence Research Group, @@ -25,12 +25,12 @@ ## # @if jp # -# @brief NameValue +# @brief NameValue を生成する # -# Υڥ졼NameValue롣 +# このオペレーションはNameValueを作成する。 # -# @param name NameValue name -# @param value NameValue value +# @param name NameValue の name +# @param value NameValue の value # # @return NameValue # @@ -47,27 +47,26 @@ # # @endif def newNV(name, value): - try: - any_val = any.to_any(value) - except: - print("ERROR NVUtil.newNV : Can't convert to any. ", type(value)) - raise + try: + any_val = any.to_any(value) + except BaseException: + print("ERROR NVUtil.newNV : Can't convert to any. ", type(value)) + raise - - nv = SDOPackage.NameValue(name, any_val) - return nv + nv = SDOPackage.NameValue(name, any_val) + return nv ## # @if jp # -# @brief Properties NVList إԡ +# @brief Properties を NVList へコピーする # -# Υڥ졼 Properties NVList إԡ롣 -# NVList value CORBA::string Ȥƥԡ롣 +# このオペレーションは Properties を NVList へコピーする。 +# NVList の value は全て CORBA::string 型としてコピーする。 # -# @param nv Properties ͤǼ NVList -# @param prop ԡ Properties +# @param nv Properties の値を格納する NVList +# @param prop コピー元の Properties # # @else # @@ -80,28 +79,28 @@ def newNV(name, value): # @param prop Properties that is copies from # # @endif -# void copyFromProperties(SDOPackage::NVList& nv, const coil::Properties& prop); +# void copyFromProperties(SDOPackage::NVList& nv, const coil::Properties& +# prop); def copyFromProperties(nv, prop): - keys = prop.propertyNames() - keys_len = len(keys) - nv_len = len(nv) - if nv_len > 0: - for i in range(nv_len): - del nv[-1] + keys = prop.propertyNames() + nv_len = len(nv) + if nv_len > 0: + for i in range(nv_len): + del nv[-1] - for i in range(keys_len): - nv.append(newNV(keys[i], prop.getProperty(keys[i]))) + for key in keys: + nv.append(newNV(key, prop.getProperty(key))) ## # @if jp # -# @brief NVList Properties إԡ +# @brief NVList を Properties へコピーする # -# Υڥ졼 NVList Properties إԡ롣 +# このオペレーションは NVList を Properties へコピーする。 # -# @param prop NVList ͤǼ Properties -# @param nv ԡ NVList +# @param prop NVList の値を格納する Properties +# @param nv コピー元の NVList # # @else # @@ -115,79 +114,76 @@ def copyFromProperties(nv, prop): # @endif # void copyToProperties(coil::Properties& prop, const SDOPackage::NVList& nv); def copyToProperties(prop, nvlist): - for nv in nvlist: - try: - val = str(any.from_any(nv.value, keep_structs=True)) - prop.setProperty(str(nv.name),val) - except: - print(OpenRTM_aist.Logger.print_exception()) - pass - + for nv in nvlist: + try: + val = str(any.from_any(nv.value, keep_structs=True)) + prop.setProperty(str(nv.name), val) + except BaseException: + print(OpenRTM_aist.Logger.print_exception()) + pass ## # @if jp # @class to_prop -# @brief NVList Properties Ѵѥե󥯥 +# @brief NVList → Properties 変換用ファンクタ # @endif class to_prop: - def __init__(self): - self._prop = OpenRTM_aist.Properties() - - def __call__(self, nv): - self._prop.setProperty(nv.name, nv.value) + def __init__(self): + self._prop = OpenRTM_aist.Properties() + def __call__(self, nv): + self._prop.setProperty(nv.name, nv.value) ## # @if jp # -# @brief NVList Properties Ѵ +# @brief NVList を Properties へ変換する # -# Υڥ졼 NVList Properties Ѵ롣 +# このオペレーションは NVList を Properties へ変換する。 # -# @param nv Ѵ NVList +# @param nv 変換元の NVList # -# @return ѴProperty +# @return 変換結果Property # # @else # # @endif # coil::Properties toProperties(const SDOPackage::NVList& nv); def toProperties(nv): - p = OpenRTM_aist.CORBA_SeqUtil.for_each(nv, to_prop()) - return p._prop - + p = OpenRTM_aist.CORBA_SeqUtil.for_each(nv, to_prop()) + return p._prop ## # @if jp # @class nv_find -# @brief NVList ѥե󥯥 +# @brief NVList 検索用ファンクタ # @endif class nv_find: - """ - """ + """ + """ - def __init__(self, name): - self._name = name + def __init__(self, name): + self._name = name - def __call__(self, nv): - return str(self._name) == str(nv.name) + def __call__(self, nv): + return str(self._name) == str(nv.name) ## # @if jp # -# @brief NVList name ǻꤵ줿 value ֤ +# @brief NVList から name で指定された value を返す # -# Υڥ졼 name ǻꤵ줿 value Any ֤ -# ꤷ̾ΤǤ¸ߤʤ㳰ȯ롣 +# このオペレーションは name で指定された value を Any 型で返す。 +# 指定した名称の要素が存在しない場合は例外を発生させる。 # -# @param nv оݤ NVList -# @param name ̾ +# @param nv 検索対象の NVList +# @param name 検索する名前 # -# @return +# @return 検索結果 # # @else # @@ -201,97 +197,97 @@ def __call__(self, nv): # # @endif def find(nv, name): - index = OpenRTM_aist.CORBA_SeqUtil.find(nv, nv_find(name)) + index = OpenRTM_aist.CORBA_SeqUtil.find(nv, nv_find(name)) - if index < 0: - raise "Not found." + if index < 0: + raise "Not found." - return nv[index].value + return nv[index].value ## # @if jp # -# @brief name ǻꤵ줿ǤΥǥå֤ +# @brief name で指定された要素のインデックスを返す # -# Υڥ졼 name ǻꤵ줿ǤǼƤ֤ -# ǥå֤ +# このオペレーションは name で指定された要素が格納されている位置の +# インデックスを返す。 # -# @param nv оݤ NVList -# @param name ̾ +# @param nv 検索対象の NVList +# @param name 検索する名前 # -# @return оݤΥǥå +# @return 検索対象のインデックス # # @else # # @endif def find_index(nv, name): - return OpenRTM_aist.CORBA_SeqUtil.find(nv, nv_find(name)) + return OpenRTM_aist.CORBA_SeqUtil.find(nv, nv_find(name)) ## # @if jp # -# @brief ꤵ줿 name value η string Ǥ뤫ڤ +# @brief 指定された name の value の型が string であるか検証する # -# Υڥ졼 name ǻꤵ줿 value η CORBA::string -# ɤ bool ֤ͤ +# このオペレーションは name で指定された value の型が CORBA::string +# かどうかを bool 値で返す。 # -# @param nv оݤ NVList -# @param name ̾ +# @param nv 検索対象の NVList +# @param name 検索する名前 # -# @return stringڷ(string:trueʳ:false) +# @return string検証結果(string:true、それ以外:false) # # @else # # @endif def isString(nv, name): - try: - value = find(nv, name) - val = any.from_any(value, keep_structs=True) - return type(val) == str - except: - return False + try: + value = find(nv, name) + val = any.from_any(value, keep_structs=True) + return isinstance(val, str) + except BaseException: + return False ## # @if jp # -# @brief ꤵ줿 name value ηꤷʸȰפ뤫ڤ +# @brief 指定された name の value の型が指定した文字列と一致するか検証する # -# Υڥ졼 name ǻꤵ줿 value η CORBA::string -# ɤȽǤ CORBA::string ǤˤϻꤷʸȰפ뤫 -# bool ֤ͤ +# このオペレーションは name で指定された value の型が CORBA::string +# かどうかを判断し、 CORBA::string である場合には指定した文字列と一致するか +# をbool 値で返す。 # -# @param nv оݤ NVList -# @param name ̾ -# @param value оʸ +# @param nv 検索対象の NVList +# @param name 検索する名前 +# @param value 比較対象文字列 # -# @return ڷ(ʸȰ:true:false) +# @return 検証結果(文字列と一致:true、非一致:false) # # @else # # @endif def isStringValue(nv, name, value): - if isString(nv, name): - if toString(nv, name) == value: - return True - return False + if isString(nv, name): + if toString(nv, name) == value: + return True + return False ## # @if jp # -# @brief ꤵ줿 name NVList string Ȥ֤ +# @brief 指定された name の NVList を string として返す。 # -# Υڥ졼 name ǻꤵ줿 NVList ͤ string ֤ -# ⤷name ǻꤷ value ͤ CORBA::string ǤʤС -# ʸstring֤ +# このオペレーションは name で指定された NVList の値を string で返す。 +# もし、name で指定した value の値が CORBA::string でなければ、 +# 空の文字列のstringを返す。 # -# @param nv оݤ NVList -# @param name ̾ +# @param nv 検索対象の NVList +# @param name 検索する名前 # -# @return name бͤstring +# @return name に対応する値のstring型の値 # # @else # @@ -308,117 +304,117 @@ def isStringValue(nv, name, value): # # @endif def toString(nv, name=None): - if not name: - str_ = [""] - return dump_to_stream(str_, nv) - - str_value = "" - try: - ret_value = find(nv, name) - val = any.from_any(ret_value, keep_structs=True) - if type(val) == str: - str_value = val - except: - print(OpenRTM_aist.Logger.print_exception()) - pass - - return str_value + if not name: + str_ = "" + return dump_to_stream(str_, nv) + + str_value = "" + try: + ret_value = find(nv, name) + val = any.from_any(ret_value, keep_structs=True) + if isinstance(val, str): + str_value = val + except BaseException: + print(OpenRTM_aist.Logger.print_exception()) + pass + + return str_value ## # @if jp # -# @brief ꤵ줿ʸ NVList Ǥɲä롣 +# @brief 指定された文字列を NVList の要素に追加する。 # -# Υڥ졼 name ǻꤵ줿Ǥ value ǻꤵ줿ʸ -# ɲä롣 -# name ǻꤷǤ˴ value ͤꤵƤˤϲ⤷ʤ -# name ǻꤷǤ value ͤꤵƤʤϡ ,ڤ -# value ͤɲä롣 -# ꤵ줿ͤꤹ롣 -# name ǻꤷǤ¸ߤʤϡ NVList κǸ˿Ǥɲä -# ꤵ줿ͤꤹ롣 +# このオペレーションは name で指定された要素に value で指定された文字列を +# 追加する。 +# name で指定した要素に既に value の値が設定されている場合には何もしない。 +# name で指定した要素に value の値が設定されていない場合は、 「,」区切りで +# value の値を追加する。 +# 指定された値を設定する。 +# name で指定した要素が存在しない場合は、 NVList の最後に新たな要素を追加し、 +# 指定された値を設定する。 # -# @param nv оݤ NVList -# @param name ɲо̾ -# @param value ɲäʸ +# @param nv 検索対象の NVList +# @param name 追加対象要素名 +# @param value 追加する文字列 # -# @return ɲ +# @return 追加操作結果 # # @else # # @endif def appendStringValue(nv, name, value): - index = find_index(nv, name) - if index >= 0: - tmp_str = nv[index].value.value() - values = OpenRTM_aist.split(tmp_str,",") - find_flag = False - for val in values: - if val == value: - find_flag = True - - if not find_flag: - tmp_str += ", " - tmp_str += value - nv[index].value = any.to_any(tmp_str) - else: - OpenRTM_aist.CORBA_SeqUtil.push_back(nv, newNV(name, value)) + index = find_index(nv, name) + if index >= 0: + tmp_str = nv[index].value.value() + values = OpenRTM_aist.split(tmp_str, ",") + find_flag = False + for val in values: + if val == value: + find_flag = True + + if not find_flag: + tmp_str += ", " + tmp_str += value + nv[index].value = any.to_any(tmp_str) + else: + OpenRTM_aist.CORBA_SeqUtil.push_back(nv, newNV(name, value)) - return True + return True ## # @if jp # -# @brief NVList Ǥɲä롣 +# @brief NVList に要素を追加する。 # -# Υڥ졼 dest ǻꤵ줿 NVList src ǻꤵ줿Ǥ -# ɲä롣 +# このオペレーションは dest で指定された NVList に src で指定された要素を +# 追加する。 # -# @param dest ɲä NVList -# @param src ɲä NVList +# @param dest 追加される NVList +# @param src 追加する NVList # # @else # # @endif def append(dest, src): - for i in range(len(src)): - OpenRTM_aist.CORBA_SeqUtil.push_back(dest, src[i]) + for s in src: + OpenRTM_aist.CORBA_SeqUtil.push_back(dest, s) ## # @if jp -# @brief NVList ꤵƤƤʸȤƽϤ롣 +# @brief NVList に設定されている内容を文字列として出力する。 # @else # @brief Print information configured in NVList as a string type # @endif # std::ostream& dump_to_stream(std::ostream& out, const SDOPackage::NVList& nv) def dump_to_stream(out, nv): - for i in range(len(nv)): - val = any.from_any(nv[i].value, keep_structs=True) - if type(val) == str: - out[0] += (nv[i].name + ": " + str(nv[i].value) + "\n") - else: - out[0] += (nv[i].name + ": not a string value \n") + for n in nv: + val = any.from_any(n.value, keep_structs=True) + if isinstance(val, str): + out += (n.name + ": " + str(n.value) + "\n") + else: + out += (n.name + ": not a string value \n") - return out[0] + return out ## # @if jp # -# @brief NVList ꤵƤƤʸȤƽϤ롣 +# @brief NVList に設定されている内容を文字列として出力する。 # -# ꤵ줿 NVList ꤵ줿ƤʸȤƽϤ롣 -# ʤꤵƤǤʸ󷿰ʳξˤϡλ(ʸǤϤʤ) -# Ϥ롣 +# 指定された NVList に設定された内容を文字列として出力する。 +# なお、設定されている要素が文字列型以外の場合には、その旨(文字列ではない)を +# 出力する。 # -# @param nv о NVList +# @param nv 出力対象 NVList # # @else # # @endif def dump(nv): - out = [""] - print(dump_to_stream(out, nv)) + out = "" + print(dump_to_stream(out, nv)) diff --git a/OpenRTM_aist/NamingManager.py b/OpenRTM_aist/NamingManager.py index 23d0c0a0..47710fdc 100644 --- a/OpenRTM_aist/NamingManager.py +++ b/OpenRTM_aist/NamingManager.py @@ -1,5 +1,5 @@ #!/usr/bin/env python -# -*- coding: euc-jp -*- +# -*- coding: utf-8 -*- ## # @file NamingManager.py @@ -18,7 +18,6 @@ import threading - import OpenRTM_aist from omniORB import CORBA import RTM @@ -30,12 +29,12 @@ # @if jp # # @class NamingBase -# @brief NamingService ݥ饹 +# @brief NamingService 管理用抽象クラス # -# NamingServer ݥ󥿡ե饹 -# ݴ饹ϡʲδؿμ󶡤ʤФʤʤ -# - bindObject() : ꤷ֥ȤNamingServiceؤΥХ -# - unbindObject() : ꤷ֥ȤNamingServiceΥХ +# NamingServer 管理用抽象インターフェースクラス。 +# 具象管理クラスは、以下の関数の実装を提供しなければならない。 +# - bindObject() : 指定したオブジェクトのNamingServiceへのバインド +# - unbindObject() : 指定したオブジェクトのNamingServiceからのアンバインド # # @since 0.4.0 # @@ -43,94 +42,94 @@ # # @endif class NamingBase: - """ - """ - - ## - # @if jp - # - # @brief NamingServiceإХɤؿ(֥饹) - # - # ꤷ֥ȤNamingServiceإХɤ
    - # ֥饹Ǥμ - # - # @param self - # @param name Хɻ̾ - # @param rtobj Хоݥ֥ - # - # @else - # - # @endif - def bindObject(self, name, rtobj): - pass - - def bindPortObject(self, name, port): - pass - - ## - # @if jp - # - # @brief NamingService饢Хɤؿ(֥饹) - # - # ꤷ֥ȤNamingService饢Хɤ
    - # ֥饹Ǥμ - # - # @param self - # @param name Хоݥ֥ - # - # @else - # - # @endif - def unbindObject(self, name): - pass - - ## - # @if jp - # - # @brief ͡ॵФ¸ǧ롣 - # - # @return true:¸Ƥ, false:¸Ƥʤ - # - # @else - # - # @brief Check if the name service is alive - # - # @return true: alive, false:non not alive - # - # @endif - # - # virtual bool isAlive() = 0; - def isAlive(self): - return True - - ## - # @if jp - # - # @brief rtclocRTCΥ֥ȥե󥹤 - # - # @return RTCΥ֥ȥե - # - # @else - # - # @brief - # - # @return - # - # @endif - # - # virtual RTCList string_to_component(string name) = 0; - def string_to_component(self, name): - return [] + """ + """ + + ## + # @if jp + # + # @brief NamingServiceへバインドする関数(サブクラス実装用) + # + # 指定したオブジェクトをNamingServiceへバインドする
    + # ※サブクラスでの実装参照用 + # + # @param self + # @param name バインド時の名称 + # @param rtobj バインド対象オブジェクト + # + # @else + # + # @endif + def bindObject(self, name, rtobj): + pass + + def bindPortObject(self, name, port): + pass + + ## + # @if jp + # + # @brief NamingServiceからアンバインドする関数(サブクラス実装用) + # + # 指定したオブジェクトをNamingServiceからアンバインドする
    + # ※サブクラスでの実装参照用 + # + # @param self + # @param name アンバインド対象オブジェクト + # + # @else + # + # @endif + def unbindObject(self, name): + pass + + ## + # @if jp + # + # @brief ネームサーバの生存を確認する。 + # + # @return true:生存している, false:生存していない + # + # @else + # + # @brief Check if the name service is alive + # + # @return true: alive, false:non not alive + # + # @endif + # + # virtual bool isAlive() = 0; + def isAlive(self): + return True + + ## + # @if jp + # + # @brief rtcloc形式でRTCのオブジェクトリファレンスを取得する + # + # @return RTCのオブジェクトリファレンス + # + # @else + # + # @brief + # + # @return + # + # @endif + # + # virtual RTCList string_to_component(string name) = 0; + def string_to_component(self, name): + return [] ## # @if jp # # @class NamingOnCorba -# @brief CORBA NamingServer 饹 +# @brief CORBA 用 NamingServer 管理クラス # -# CORBA NamingServer ѥ饹 -# CORBA ݡͥȤNamingServiceؤϿʤɤ롣 +# CORBA 用 NamingServer 管理用クラス。 +# CORBA コンポーネントのNamingServiceへの登録、解除などを管理する。 # # @since 0.4.0 # @@ -140,455 +139,455 @@ def string_to_component(self, name): # # @endif class NamingOnCorba(NamingBase): - """ - """ - - ## - # @if jp - # - # @brief 󥹥ȥ饯 - # - # 󥹥ȥ饯 - # - # @param self - # @param orb ORB - # @param names NamingServer ̾ - # - # @else - # - # @endif - def __init__(self, orb, names): - self._rtcout = OpenRTM_aist.Manager.instance().getLogbuf('manager.namingoncorba') - self._cosnaming = OpenRTM_aist.CorbaNaming(orb,names) - self._endpoint = "" - self._replaceEndpoint = False - - ## - # @if jp - # - # @brief ꤷ CORBA ֥ȤNamingServiceإХ - # - # ꤷ CORBA ֥Ȥꤷ̾Τ CORBA NamingService - # Хɤ롣 - # - # @param self - # @param name Хɻ̾ - # @param rtobj or mgr Хоݥ֥ - # - # @else - # - # @endif - def bindObject(self, name, rtobj): - self._rtcout.RTC_TRACE("bindObject(name = %s, rtobj or mgr)", name) - try: - self._cosnaming.rebindByString(name, rtobj.getObjRef(), True) - except: - self._rtcout.RTC_ERROR(OpenRTM_aist.Logger.print_exception()) - - return - - - ## - # @if jp - # - # @brief ꤷ CORBA ֥ȤNamingServiceإХ - # - # ꤷ CORBA ֥Ȥꤷ̾Τ CORBA NamingService - # Хɤ롣 - # - # @param self - # @param name Хɻ̾ - # @param port Хоݥ֥ - # - # @else - # - # @endif - def bindPortObject(self, name, port): - self._rtcout.RTC_TRACE("bindPortObject(name = %s, port)", name) - try: - self._cosnaming.rebindByString(name, port.getPortRef(), True) - except: - self._rtcout.RTC_ERROR(OpenRTM_aist.Logger.print_exception()) - - return - - - ## - # @if jp - # - # @brief ꤷ CORBA ֥ȤNamingService饢Х - # - # ꤷ CORBA ֥Ȥ CORBA NamingService 饢Хɤ롣 - # - # @param self - # @param name Хоݥ֥ - # - # @else - # - # @endif - def unbindObject(self, name): - self._rtcout.RTC_TRACE("unbindObject(name = %s)", name) - try: - self._cosnaming.unbind(name) - except: - self._rtcout.RTC_ERROR(OpenRTM_aist.Logger.print_exception()) - - return - - - ## - # @if jp - # - # @brief ͡ॵФ¸ǧ롣 - # - # @return true:¸Ƥ, false:¸Ƥʤ - # - # @else - # - # @brief Check if the name service is alive - # - # @return true: alive, false:non not alive - # - # @endif - # - # virtual bool isAlive(); - def isAlive(self): - self._rtcout.RTC_TRACE("isAlive()") - return self._cosnaming.isAlive() - - def getCorbaNaming(self): - self._rtcout.RTC_TRACE("getCorbaNaming()") - return self._cosnaming - - - ## - # @if jp - # - # @brief RTCθ - # - # ͡ߥ󥰥ӥRTC򥤥󥹥̾鸡 - # פRTCΥꥹȤ - # - # @param self - # @param context ߸Υƥ - # @param name RTCΥ󥹥̾ - # @param rtcs RTCΥꥹ - # - # @return - # - # @else - # - # @endif - def getComponentByName(self, context, name, rtcs): - length = 500 - bl,bi = context.list(length) - for i in bl: - if i.binding_type == CosNaming.ncontext: - next_context = context.resolve(i.binding_name) - self.getComponentByName(next_context, name, rtcs) - elif i.binding_type == CosNaming.nobject: - - if i.binding_name[0].id == name and i.binding_name[0].kind == "rtc": - try: - cc = OpenRTM_aist.CorbaConsumer() - cc.setObject(context.resolve(i.binding_name)) - obj = cc.getObject()._narrow(RTC.RTObject) - if not obj._non_existent(): - rtcs.append(obj) - except: + """ + """ + + ## + # @if jp + # + # @brief コンストラクタ + # + # コンストラクタ + # + # @param self + # @param orb ORB + # @param names NamingServer 名称 + # + # @else + # + # @endif + def __init__(self, orb, names): + self._rtcout = OpenRTM_aist.Manager.instance().getLogbuf('manager.namingoncorba') + self._cosnaming = OpenRTM_aist.CorbaNaming(orb, names) + self._endpoint = "" + self._replaceEndpoint = False + + ## + # @if jp + # + # @brief 指定した CORBA オブジェクトのNamingServiceへバインド + # + # 指定した CORBA オブジェクトを指定した名称で CORBA NamingService へ + # バインドする。 + # + # @param self + # @param name バインド時の名称 + # @param rtobj or mgr バインド対象オブジェクト + # + # @else + # + # @endif + def bindObject(self, name, rtobj): + self._rtcout.RTC_TRACE("bindObject(name = %s, rtobj or mgr)", name) + try: + self._cosnaming.rebindByString(name, rtobj.getObjRef(), True) + except BaseException: self._rtcout.RTC_ERROR(OpenRTM_aist.Logger.print_exception()) - - - ## - # @if jp - # - # @brief rtcnameRTCΥ֥ȥե󥹤 - # - # @param name RTC̾ - # @return RTCΥ֥ȥե󥹤Υꥹ - # - # @else - # - # @brief - # - # @return - # - # @endif - # - # virtual RTCList string_to_component(string name) = 0; - def string_to_component(self, name): - rtc_list = [] - tmp = name.split("://") - if len(tmp) > 1: - if tmp[0] == "rtcname": - #tag = tmp[0] - url = tmp[1] - r = url.split("/") - if len(r) > 1: - host = r[0] - - rtc_name = url[len(host)+1:] - - try: - cns = None - if host == "*": - cns = self._cosnaming - else: - orb = OpenRTM_aist.Manager.instance().getORB() - cns = OpenRTM_aist.CorbaNaming(orb,host) - names = rtc_name.split("/") - - if len(names) == 2 and names[0] == "*": - root_cxt = cns.getRootContext() - self.getComponentByName(root_cxt, names[1], rtc_list) - return rtc_list - else: - rtc_name += ".rtc" - obj = cns.resolveStr(rtc_name) - if CORBA.is_nil(obj): - return [] - if obj._non_existent(): - return [] - rtc_list.append(obj) - return rtc_list - except: - return [] + return + + ## + # @if jp + # + # @brief 指定した CORBA オブジェクトのNamingServiceへバインド + # + # 指定した CORBA オブジェクトを指定した名称で CORBA NamingService へ + # バインドする。 + # + # @param self + # @param name バインド時の名称 + # @param port バインド対象オブジェクト + # + # @else + # + # @endif + + def bindPortObject(self, name, port): + self._rtcout.RTC_TRACE("bindPortObject(name = %s, port)", name) + try: + self._cosnaming.rebindByString(name, port.getPortRef(), True) + except BaseException: + self._rtcout.RTC_ERROR(OpenRTM_aist.Logger.print_exception()) + + return + + ## + # @if jp + # + # @brief 指定した CORBA オブジェクトをNamingServiceからアンバインド + # + # 指定した CORBA オブジェクトを CORBA NamingService からアンバインドする。 + # + # @param self + # @param name アンバインド対象オブジェクト + # + # @else + # + # @endif + + def unbindObject(self, name): + self._rtcout.RTC_TRACE("unbindObject(name = %s)", name) + try: + self._cosnaming.unbind(name) + except BaseException: + self._rtcout.RTC_ERROR(OpenRTM_aist.Logger.print_exception()) - - return rtc_list + return + ## + # @if jp + # + # @brief ネームサーバの生存を確認する。 + # + # @return true:生存している, false:生存していない + # + # @else + # + # @brief Check if the name service is alive + # + # @return true: alive, false:non not alive + # + # @endif + # + # virtual bool isAlive(); + + def isAlive(self): + self._rtcout.RTC_TRACE("isAlive()") + return self._cosnaming.isAlive() + + def getCorbaNaming(self): + self._rtcout.RTC_TRACE("getCorbaNaming()") + return self._cosnaming + + ## + # @if jp + # + # @brief RTCの検索 + # + # ネーミングサービスからRTCをインスタンス名から検索し、 + # 一致するRTCのリストを取得する + # + # @param self + # @param context 現在検索中のコンテキスト + # @param name RTCのインスタンス名 + # @param rtcs RTCのリスト + # + # @return + # + # @else + # + # @endif + + def getComponentByName(self, context, name, rtcs): + length = 500 + bl, bi = context.list(length) + for i in bl: + if i.binding_type == CosNaming.ncontext: + next_context = context.resolve(i.binding_name) + self.getComponentByName(next_context, name, rtcs) + elif i.binding_type == CosNaming.nobject: + + if i.binding_name[0].id == name and i.binding_name[0].kind == "rtc": + try: + cc = OpenRTM_aist.CorbaConsumer() + cc.setObject(context.resolve(i.binding_name)) + obj = cc.getObject()._narrow(RTC.RTObject) + if not obj._non_existent(): + rtcs.append(obj) + except BaseException: + self._rtcout.RTC_ERROR( + OpenRTM_aist.Logger.print_exception()) + + ## + # @if jp + # + # @brief rtcname形式でRTCのオブジェクトリファレンスを取得する + # + # @param name RTC名 + # @return RTCのオブジェクトリファレンスのリスト + # + # @else + # + # @brief + # + # @return + # + # @endif + # + # virtual RTCList string_to_component(string name) = 0; + + def string_to_component(self, name): + rtc_list = [] + tmp = name.split("://") + if len(tmp) > 1: + if tmp[0] == "rtcname": + #tag = tmp[0] + url = tmp[1] + r = url.split("/") + if len(r) > 1: + host = r[0] + + rtc_name = url[len(host) + 1:] + + try: + cns = None + if host == "*": + cns = self._cosnaming + else: + orb = OpenRTM_aist.Manager.instance().getORB() + cns = OpenRTM_aist.CorbaNaming(orb, host) + names = rtc_name.split("/") + + if len(names) == 2 and names[0] == "*": + root_cxt = cns.getRootContext() + self.getComponentByName( + root_cxt, names[1], rtc_list) + return rtc_list + else: + rtc_name += ".rtc" + obj = cns.resolveStr(rtc_name) + if CORBA.is_nil(obj): + return [] + if obj._non_existent(): + return [] + rtc_list.append(obj) + return rtc_list + except BaseException: + return [] + + return rtc_list ## # @if jp # # @class NamingOnManager -# @brief Manager NamingServer 饹 +# @brief Manager 用 NamingServer 管理クラス # # # @since 1.2.0 # # @else # -# @biref +# @biref # # @endif class NamingOnManager(NamingBase): - """ - """ - - ## - # @if jp - # - # @brief 󥹥ȥ饯 - # - # 󥹥ȥ饯 - # - # @param self - # @param orb ORB - # @param mgr ޥ͡ - # - # @else - # - # @param self - # @param orb ORB - # @param mgr - # - # @endif - def __init__(self, orb, mgr): - self._rtcout = OpenRTM_aist.Manager.instance().getLogbuf('manager.namingonmanager') - self._cosnaming = None - self._orb = orb - self._mgr = mgr - - - ## - # @if jp - # - # @brief - # - # - # - # @param self - # @param name Хɻ̾ - # @param rtobj or mgr Хоݥ֥ - # - # @else - # - # @endif - def bindObject(self, name, rtobj): - self._rtcout.RTC_TRACE("bindObject(name = %s, rtobj or mgr)", name) - """print(isinstance(rtobj, OpenRTM.ManagerServant)) + """ + """ + + ## + # @if jp + # + # @brief コンストラクタ + # + # コンストラクタ + # + # @param self + # @param orb ORB + # @param mgr マネージャ + # + # @else + # + # @param self + # @param orb ORB + # @param mgr + # + # @endif + def __init__(self, orb, mgr): + self._rtcout = OpenRTM_aist.Manager.instance().getLogbuf('manager.namingonmanager') + self._cosnaming = None + self._orb = orb + self._mgr = mgr + + ## + # @if jp + # + # @brief + # + # + # + # @param self + # @param name バインド時の名称 + # @param rtobj or mgr バインド対象オブジェクト + # + # @else + # + # @endif + + def bindObject(self, name, rtobj): + self._rtcout.RTC_TRACE("bindObject(name = %s, rtobj or mgr)", name) + """print(isinstance(rtobj, OpenRTM.ManagerServant)) if isinstance(rtobj, OpenRTM.ManagerServant): - + self.manager = rtobj""" - return - - - ## - # @if jp - # - # @brief - # - # - # @param self - # @param name Хɻ̾ - # @param port Хоݥ֥ - # - # @else - # - # @endif - def bindPortObject(self, name, port): - self._rtcout.RTC_TRACE("bindPortObject(name = %s, port)", name) - - return - - - ## - # @if jp - # - # @brief - # - # - # @param self - # @param name Хоݥ֥ - # - # @else - # - # @endif - def unbindObject(self, name): - self._rtcout.RTC_TRACE("unbindObject(name = %s)", name) - - return - - - ## - # @if jp - # - # @brief - # - # @return true:¸Ƥ, false:¸Ƥʤ - # - # @else - # - # @brief Check if the name service is alive - # - # @return true: alive, false:non not alive - # - # @endif - # - # virtual bool isAlive(); - def isAlive(self): - self._rtcout.RTC_TRACE("isAlive()") - return True - - ## - # @if jp - # - # @brief rtclocRTCΥ֥ȥե󥹤 - # - # @param name rtclocǤRTC̾ - # rtcloc://localhost:2809/example/ConsoleIn - # @return RTCΥ֥ȥե󥹤Υꥹ - # - # @else - # - # @brief - # - # @return - # - # @endif - # - # virtual RTCList string_to_component(); - def string_to_component(self, name): - rtc_list = [] - tmp = name.split("://") - - if len(tmp) > 1: - if tmp[0] == "rtcloc": - #tag = tmp[0] - url = tmp[1] - r = url.split("/") - if len(r) > 1: - host = r[0] - rtc_name = url[len(host)+1:] - - mgr = self.getManager(host) - if not CORBA.is_nil(mgr): - rtc_list = mgr.get_components_by_name(rtc_name) - - slaves = mgr.get_slave_managers() - for slave in slaves: - try: - rtc_list.extend(slave.get_components_by_name(rtc_name)) - except: - self._rtcout.RTC_DEBUG(OpenRTM_aist.Logger.print_exception()) - mgr.remove_slave_manager(slave) - - return rtc_list - return rtc_list - - ## - # @if jp - # - # @brief ۥ̾ݡ̾ManagerΥ֥ȥե󥹤 - # - # @param name ۥ̾ݡ̾ - # - # @return ManagerΥ֥ȥե - # - # @else - # - # @brief - # - # @return - # - # @endif - # - # virtual Manager_ptr getManager(string name); - def getManager(self, name): - if name == "*": - mgr_sev = self._mgr.getManagerServant() - mgr = None - if mgr_sev.is_master(): - mgr = mgr_sev.getObjRef() - else: - masters = mgr_sev.get_master_managers() - if len(masters) > 0: - mgr = masters[0] - else: - mgr = mgr_sev.getObjRef() - return mgr - try: - mgrloc = "corbaloc:iiop:" - prop = self._mgr.getConfig() - manager_name = prop.getProperty("manager.name") - mgrloc += name - mgrloc += "/" + manager_name - - mobj = self._orb.string_to_object(mgrloc) - mgr = mobj._narrow(RTM.Manager) - - self._rtcout.RTC_DEBUG("corbaloc: %s", mgrloc) - return mgr - except CORBA.SystemException: - self._rtcout.RTC_DEBUG(OpenRTM_aist.Logger.print_exception()) - except: - self._rtcout.RTC_ERROR("Unknown exception cought.") - self._rtcout.RTC_DEBUG(OpenRTM_aist.Logger.print_exception()) - return RTM.Manager._nil - + return + + ## + # @if jp + # + # @brief + # + # + # @param self + # @param name バインド時の名称 + # @param port バインド対象オブジェクト + # + # @else + # + # @endif + + def bindPortObject(self, name, port): + self._rtcout.RTC_TRACE("bindPortObject(name = %s, port)", name) + + return + + ## + # @if jp + # + # @brief + # + # + # @param self + # @param name アンバインド対象オブジェクト + # + # @else + # + # @endif + + def unbindObject(self, name): + self._rtcout.RTC_TRACE("unbindObject(name = %s)", name) + + return + + ## + # @if jp + # + # @brief + # + # @return true:生存している, false:生存していない + # + # @else + # + # @brief Check if the name service is alive + # + # @return true: alive, false:non not alive + # + # @endif + # + # virtual bool isAlive(); + + def isAlive(self): + self._rtcout.RTC_TRACE("isAlive()") + return True + + ## + # @if jp + # + # @brief rtcloc形式でRTCのオブジェクトリファレンスを取得する + # + # @param name rtcloc形式でのRTC名 + # rtcloc://localhost:2809/example/ConsoleIn + # @return RTCのオブジェクトリファレンスのリスト + # + # @else + # + # @brief + # + # @return + # + # @endif + # + # virtual RTCList string_to_component(); + def string_to_component(self, name): + rtc_list = [] + tmp = name.split("://") + + if len(tmp) > 1: + if tmp[0] == "rtcloc": + #tag = tmp[0] + url = tmp[1] + r = url.split("/") + if len(r) > 1: + host = r[0] + rtc_name = url[len(host) + 1:] + + mgr = self.getManager(host) + if not CORBA.is_nil(mgr): + rtc_list = mgr.get_components_by_name(rtc_name) + + subordinates = mgr.get_subordinate_managers() + for subordinate in subordinates: + try: + rtc_list.extend( + subordinate.get_components_by_name(rtc_name)) + except BaseException: + self._rtcout.RTC_DEBUG( + OpenRTM_aist.Logger.print_exception()) + mgr.remove_subordinate_manager(subordinate) + + return rtc_list + return rtc_list + + ## + # @if jp + # + # @brief 指定ホスト名、ポート名でManagerのオブジェクトリファレンスを取得 + # + # @param name ホスト名、ポート名 + # + # @return Managerのオブジェクトリファレンス + # + # @else + # + # @brief + # + # @return + # + # @endif + # + # virtual Manager_ptr getManager(string name); + def getManager(self, name): + if name == "*": + mgr_sev = self._mgr.getManagerServant() + mgr = None + if mgr_sev.is_main(): + mgr = mgr_sev.getObjRef() + else: + mains = mgr_sev.get_main_managers() + if mains: + mgr = mains[0] + else: + mgr = mgr_sev.getObjRef() + return mgr + try: + mgrloc = "corbaloc:iiop:" + prop = self._mgr.getConfig() + manager_name = prop.getProperty("manager.name") + mgrloc += name + mgrloc += "/" + manager_name + + mobj = self._orb.string_to_object(mgrloc) + mgr = mobj._narrow(RTM.Manager) + + self._rtcout.RTC_DEBUG("corbaloc: %s", mgrloc) + return mgr + except CORBA.SystemException: + self._rtcout.RTC_DEBUG(OpenRTM_aist.Logger.print_exception()) + except BaseException: + self._rtcout.RTC_ERROR("Unknown exception cought.") + self._rtcout.RTC_DEBUG(OpenRTM_aist.Logger.print_exception()) + return RTM.Manager._nil ## # @if jp # # @class NamingManager -# @brief NamingServer 饹 +# @brief NamingServer 管理クラス # -# NamingServer ѥ饹 -# ݡͥȤNamingServiceؤϿʤɤ롣 +# NamingServer 管理用クラス。 +# コンポーネントのNamingServiceへの登録、解除などを管理する。 # # @since 0.4.0 # @@ -598,566 +597,557 @@ def getManager(self, name): # # @endif class NamingManager: - """ - """ - - - - ## - # @if jp - # - # @brief 󥹥ȥ饯 - # - # 󥹥ȥ饯 - # - # @param self - # @param manager ޥ͡㥪֥ - # - # @else - # - # @endif - def __init__(self, manager): - self._manager = manager - self._rtcout = manager.getLogbuf('manager.namingmanager') - #self._rtcout.setLogLevel(manager.getConfig().getProperty("logger.log_level")) - #self._rtcout.setLogLock(OpenRTM_aist.toBool(manager.getConfig().getProperty("logger.stream_lock"), "enable", "disable", False)) - self._names = [] - self._namesMutex = threading.RLock() - self._compNames = [] - self._mgrNames = [] - self._portNames = [] - self._compNamesMutex = threading.RLock() - self._mgrNamesMutex = threading.RLock() - self._portNamesMutex = threading.RLock() - - - ## - # @if jp - # - # @brief NameServer Ͽ - # - # ꤷ NameServer Ͽ롣 - # CORBAManagerǽ - # - # @param self - # @param method NamingService η - # @param name_server Ͽ NameServer ̾ - # - # @else - # - # @endif - def registerNameServer(self, method, name_server): - self._rtcout.RTC_TRACE("NamingManager::registerNameServer(%s, %s)", - (method, name_server)) - name = self.createNamingObj(method, name_server) - self._names.append(self.NameServer(method, name_server, name)) - - - ## - # @if jp - # - # @brief ꤷ֥ȤNamingServiceإХ - # - # ꤷ֥Ȥꤷ̾Τ CORBA NamingService إХɤ롣 - # - # @param self - # @param name Хɻ̾ - # @param rtobj Хоݥ֥ - # - # @else - # - # @endif - def bindObject(self, name, rtobj): - self._rtcout.RTC_TRACE("NamingManager::bindObject(%s)", name) - guard = OpenRTM_aist.ScopedLock(self._namesMutex) - for i in range(len(self._names)): - if self._names[i].ns: - try: - self._names[i].ns.bindObject(name, rtobj) - except: - del self._names[i].ns - self._names[i].ns = 0 + """ + """ + + ## + # @if jp + # + # @brief コンストラクタ + # + # コンストラクタ + # + # @param self + # @param manager マネージャオブジェクト + # + # @else + # + # @endif + def __init__(self, manager): + self._manager = manager + self._rtcout = manager.getLogbuf('manager.namingmanager') + # self._rtcout.setLogLevel(manager.getConfig().getProperty("logger.log_level")) + #self._rtcout.setLogLock(OpenRTM_aist.toBool(manager.getConfig().getProperty("logger.stream_lock"), "enable", "disable", False)) + self._names = [] + self._namesMutex = threading.RLock() + self._compNames = [] + self._mgrNames = [] + self._portNames = [] + self._compNamesMutex = threading.RLock() + self._mgrNamesMutex = threading.RLock() + self._portNamesMutex = threading.RLock() + + ## + # @if jp + # + # @brief NameServer の登録 + # + # 指定した形式の NameServer を登録する。 + # CORBAとManagerが指定可能 + # + # @param self + # @param method NamingService の形式 + # @param name_server 登録する NameServer の名称 + # + # @else + # + # @endif + + def registerNameServer(self, method, name_server): + self._rtcout.RTC_TRACE("NamingManager::registerNameServer(%s, %s)", + (method, name_server)) + name = self.createNamingObj(method, name_server) + self._names.append(self.NameServer(method, name_server, name)) + + ## + # @if jp + # + # @brief 指定したオブジェクトのNamingServiceへバインド + # + # 指定したオブジェクトを指定した名称で CORBA NamingService へバインドする。 + # + # @param self + # @param name バインド時の名称 + # @param rtobj バインド対象オブジェクト + # + # @else + # + # @endif + + def bindObject(self, name, rtobj): + self._rtcout.RTC_TRACE("NamingManager::bindObject(%s)", name) + guard = OpenRTM_aist.ScopedLock(self._namesMutex) + for n in self._names: + if n.ns: + try: + n.ns.bindObject(name, rtobj) + except BaseException: + del n.ns + n.ns = None + + self.registerCompName(name, rtobj) + + def bindManagerObject(self, name, mgr): + self._rtcout.RTC_TRACE("NamingManager::bindManagerObject(%s)", name) + guard = OpenRTM_aist.ScopedLock(self._namesMutex) + for n in self._names: + if n.ns: + try: + n.ns.bindObject(name, mgr) + except BaseException: + del n.ns + n.ns = None + + self.registerMgrName(name, mgr) + + ## + # @if jp + # + # @brief 指定したポートのNamingServiceへバインド + # + # @param self + # @param name バインド時の名称 + # @param port バインド対象のポート + # + # @else + # + # @param self + # @param name + # @param port + # + # @endif + # void bindPortObject(const char* name, PortBase* port) + def bindPortObject(self, name, port): + self._rtcout.RTC_TRACE("NamingManager::bindPortObject(%s)", name) + guard = OpenRTM_aist.ScopedLock(self._namesMutex) + for n in self._names: + if n.ns: + try: + n.ns.bindPortObject(name, port) + except BaseException: + del n.ns + n.ns = None + self.registerPortName(name, port) + + ## + # @if jp + # + # @brief NamingServer の情報の更新 + # + # 設定されている NameServer 内に登録されているオブジェクトの情報を + # 更新する。 + # + # @param self + # + # @else + # + # @endif + + def update(self): + self._rtcout.RTC_TRACE("NamingManager::update()") + guard = OpenRTM_aist.ScopedLock(self._namesMutex) + rebind = OpenRTM_aist.toBool(self._manager.getConfig().getProperty("naming.update.rebind"), + "YES", "NO", False) + for i, name in enumerate(self._names): + if name.ns is None: + self._rtcout.RTC_DEBUG("Retrying connection to %s/%s", + (name.method, + name.nsname)) + self.retryConnection(name) - self.registerCompName(name, rtobj) + else: + try: + if rebind: + self.bindCompsTo(name.ns) + if not name.ns.isAlive(): + self._rtcout.RTC_INFO("Name server: %s (%s) disappeared.", + (name.nsname, + name.method)) + del name.ns + name.ns = None + except BaseException: + self._rtcout.RTC_INFO("Name server: %s (%s) disappeared.", + (name.nsname, + name.method)) + del name.ns + name.ns = None + return - def bindManagerObject(self, name, mgr): - self._rtcout.RTC_TRACE("NamingManager::bindManagerObject(%s)", name) - guard = OpenRTM_aist.ScopedLock(self._namesMutex) - for i in range(len(self._names)): - if self._names[i].ns: - try: - self._names[i].ns.bindObject(name, mgr) - except: - del self._names[i].ns - self._names[i].ns = 0 - - self.registerMgrName(name, mgr) - - ## - # @if jp - # - # @brief ꤷݡȤNamingServiceإХ - # - # @param self - # @param name Хɻ̾ - # @param port ХоݤΥݡ - # - # @else - # - # @param self - # @param name - # @param port - # - # @endif - # void bindPortObject(const char* name, PortBase* port) - def bindPortObject(self, name, port): - self._rtcout.RTC_TRACE("NamingManager::bindPortObject(%s)", name) - guard = OpenRTM_aist.ScopedLock(self._namesMutex) - for i in range(len(self._names)): - if self._names[i].ns: - try: - self._names[i].ns.bindPortObject(name, port) - except: - del self._names[i].ns - self._names[i].ns = 0 - self.registerPortName(name, port) - - - ## - # @if jp - # - # @brief NamingServer ξι - # - # ꤵƤ NameServer ϿƤ륪֥Ȥξ - # 롣 - # - # @param self - # - # @else - # - # @endif - def update(self): - self._rtcout.RTC_TRACE("NamingManager::update()") - guard = OpenRTM_aist.ScopedLock(self._namesMutex) - rebind = OpenRTM_aist.toBool(self._manager.getConfig().getProperty("naming.update.rebind"), - "YES","NO",False) - for i in range(len(self._names)): - if self._names[i].ns is None: - self._rtcout.RTC_DEBUG("Retrying connection to %s/%s", - (self._names[i].method, - self._names[i].nsname)) - self.retryConnection(self._names[i]) - - else: - try: - if rebind: - self.bindCompsTo(self._names[i].ns) - if not self._names[i].ns.isAlive(): - self._rtcout.RTC_INFO("Name server: %s (%s) disappeared.", - (self._names[i].nsname, - self._names[i].method)) - del self._names[i].ns - self._names[i].ns = None - except: - self._rtcout.RTC_INFO("Name server: %s (%s) disappeared.", - (self._names[i].nsname, - self._names[i].method)) - del self._names[i].ns - self._names[i].ns = None - - - return - - - ## - # @if jp - # - # @brief ꤷ֥ȤNamingService饢Х - # - # ꤷ֥Ȥ NamingService 饢Хɤ롣 - # - # @param self - # @param name Хоݥ֥ - # - # @else - # - # @endif - def unbindObject(self, name): - self._rtcout.RTC_TRACE("NamingManager::unbindObject(%s)", name) - guard = OpenRTM_aist.ScopedLock(self._namesMutex) - for i in range(len(self._names)): - if self._names[i].ns: - self._names[i].ns.unbindObject(name) - self.unregisterCompName(name) - self.unregisterMgrName(name) - self.unregisterPortName(name) - - - ## - # @if jp - # - # @brief ƤΥ֥ȤNamingService饢Х - # - # ƤΥ֥Ȥ CORBA NamingService 饢Хɤ롣 - # - # @param self - # - # @else - # - # @endif - def unbindAll(self): - self._rtcout.RTC_TRACE("NamingManager::unbindAll(): %d names.", len(self._compNames)) - - guard = OpenRTM_aist.ScopedLock(self._compNamesMutex) - len_ = len(self._compNames) - - for i in range(len_): - idx = (len_ - 1) - i - self.unbindObject(self._compNames[idx].name) - - guard = OpenRTM_aist.ScopedLock(self._mgrNamesMutex) - len_ = len(self._mgrNames) - for i in range(len_): - idx = (len_ - 1) - i - self.unbindObject(self._mgrNames[idx].name) - - - guard = OpenRTM_aist.ScopedLock(self._portNamesMutex) - len_ = len(self._portNames) - for i in range(len_): - idx = (len_ - 1) - i - self.unbindObject(self._portNames[idx].name) - - - ## - # @if jp - # - # @brief ХɤƤƤΥ֥Ȥ - # - # ХɤƤƤΥ֥Ȥ 롣 - # - # @param self - # - # @return ХɺѤߥ֥ ꥹ - # - # @else - # - # @endif - def getObjects(self): - comps = [] - guard = OpenRTM_aist.ScopedLock(self._compNamesMutex) - for i in range(len(self._compNames)): - comps.append(self._compNames[i].rtobj) - return comps - - - ## - # @if jp - # - # @brief NameServer ѥ֥Ȥ - # - # ꤷNameServer ѥ֥Ȥ롣 - # - # @param self - # @param method NamingService - # @param name_server NameServer ̾ - # - # @return NameServer ֥ - # - # @else - # - # @endif - def createNamingObj(self, method, name_server): - self._rtcout.RTC_TRACE("createNamingObj(method = %s, nameserver = %s)", - (method, name_server)) - mth = method - if mth == "corba": - try: - name = OpenRTM_aist.NamingOnCorba(self._manager.getORB(),name_server) - - self._rtcout.RTC_INFO("NameServer connection succeeded: %s/%s", - (method, name_server)) - return name - except: - self._rtcout.RTC_INFO("NameServer connection failed: %s/%s", - (method, name_server)) + ## + # @if jp + # + # @brief 指定したオブジェクトをNamingServiceからアンバインド + # + # 指定したオブジェクトを NamingService からアンバインドする。 + # + # @param self + # @param name アンバインド対象オブジェクト + # + # @else + # + # @endif + + def unbindObject(self, name): + self._rtcout.RTC_TRACE("NamingManager::unbindObject(%s)", name) + guard = OpenRTM_aist.ScopedLock(self._namesMutex) + for n in self._names: + if n.ns: + n.ns.unbindObject(name) + self.unregisterCompName(name) + self.unregisterMgrName(name) + self.unregisterPortName(name) + + ## + # @if jp + # + # @brief 全てのオブジェクトをNamingServiceからアンバインド + # + # 全てのオブジェクトを CORBA NamingService からアンバインドする。 + # + # @param self + # + # @else + # + # @endif + + def unbindAll(self): + self._rtcout.RTC_TRACE( + "NamingManager::unbindAll(): %d names.", len( + self._compNames)) + + guard = OpenRTM_aist.ScopedLock(self._compNamesMutex) + + for comp in self._compNames[::-1]: + self.unbindObject(comp.name) + + guard = OpenRTM_aist.ScopedLock(self._mgrNamesMutex) + + for mgr in self._mgrNames[::-1]: + self.unbindObject(mgr.name) + + guard = OpenRTM_aist.ScopedLock(self._portNamesMutex) + + for port in self._portNames[::-1]: + self.unbindObject(port.name) + + ## + # @if jp + # + # @brief バインドされている全てのオブジェクトを取得 + # + # バインドされている全てのオブジェクトを 取得する。 + # + # @param self + # + # @return バインド済みオブジェクト リスト + # + # @else + # + # @endif + + def getObjects(self): + comps = [] + guard = OpenRTM_aist.ScopedLock(self._compNamesMutex) + for comp in self._compNames: + comps.append(comp.rtobj) + return comps + + ## + # @if jp + # + # @brief NameServer 管理用オブジェクトの生成 + # + # 指定した型のNameServer 管理用オブジェクトを生成する。 + # + # @param self + # @param method NamingService 形式 + # @param name_server NameServer 名称 + # + # @return 生成した NameServer オブジェクト + # + # @else + # + # @endif + + def createNamingObj(self, method, name_server): + self._rtcout.RTC_TRACE("createNamingObj(method = %s, nameserver = %s)", + (method, name_server)) + mth = method + if mth == "corba": + try: + name = OpenRTM_aist.NamingOnCorba( + self._manager.getORB(), name_server) + + self._rtcout.RTC_INFO("NameServer connection succeeded: %s/%s", + (method, name_server)) + return name + except BaseException: + self._rtcout.RTC_INFO("NameServer connection failed: %s/%s", + (method, name_server)) + return None + + elif mth == "manager": + name = OpenRTM_aist.NamingOnManager( + self._manager.getORB(), self._manager) + return name return None - - elif mth == "manager": - name = OpenRTM_aist.NamingOnManager(self._manager.getORB(), self._manager) - return name - return None - - - ## - # @if jp - # - # @brief ѤߥݡͥȤ NameServer Ͽ - # - # ѤߥݡͥȤꤷ NameServer Ͽ롣 - # - # @param self - # @param ns Ͽо NameServer - # - # @else - # - # @endif - def bindCompsTo(self, ns): - for i in range(len(self._compNames)): - ns.bindObject(self._compNames[i].name, self._compNames[i].rtobj) - - - ## - # @if jp - # - # @brief NameServer Ͽ륳ݡͥȤ - # - # NameServer Ͽ륳ݡͥȤꤹ롣 - # - # @param self - # @param name ݡͥȤϿ̾ - # @param rtobj Ͽоݥ֥ - # - # @else - # - # @endif - def registerCompName(self, name, rtobj): - for i in range(len(self._compNames)): - if self._compNames[i].name == name: - self._compNames[i].rtobj = rtobj + ## + # @if jp + # + # @brief 設定済みコンポーネントを NameServer に登録 + # + # 設定済みコンポーネントを指定した NameServer に登録する。 + # + # @param self + # @param ns 登録対象 NameServer + # + # @else + # + # @endif + + def bindCompsTo(self, ns): + for comp in self._compNames: + ns.bindObject(comp.name, comp.rtobj) + + ## + # @if jp + # + # @brief NameServer に登録するコンポーネントの設定 + # + # NameServer に登録するコンポーネントを設定する。 + # + # @param self + # @param name コンポーネントの登録時名称 + # @param rtobj 登録対象オブジェクト + # + # @else + # + # @endif + + def registerCompName(self, name, rtobj): + for c in self._compNames: + if c.name == name: + c.rtobj = rtobj + return + + self._compNames.append(self.Comps(name, rtobj)) return - self._compNames.append(self.Comps(name, rtobj)) - return - + def registerMgrName(self, name, mgr): + for m in self._mgrNames: + if m.name == name: + m.mgr = mgr + return - def registerMgrName(self, name, mgr): - for i in range(len(self._mgrNames)): - if self._mgrNames[i].name == name: - self._mgrNames[i].mgr = mgr + self._mgrNames.append(self.Mgr(name, mgr)) return - self._mgrNames.append(self.Mgr(name, mgr)) - return - - ## - # @if jp - # - # @brief NameServer ϿݡȤ - # - # - # @param self - # @param name ݡȤϿ̾ - # @param port Ͽоݥ֥ - # - # @else - # @param self - # @param name - # @param port - # - # @endif - def registerPortName(self, name, port): - for i in range(len(self._portNames)): - if self._portNames[i].name == name: - self._portNames[i].port = port + ## + # @if jp + # + # @brief NameServer に登録するポートの設定 + # + # + # @param self + # @param name ポートの登録時名称 + # @param port 登録対象オブジェクト + # + # @else + # @param self + # @param name + # @param port + # + # @endif + def registerPortName(self, name, port): + for p in self._portNames: + if p.name == name: + p.port = port + return + + self._portNames.append(self.Port(name, port)) return - self._portNames.append(self.Port(name, port)) - return - - ## - # @if jp - # - # @brief NameServer Ͽ륳ݡͥȤ - # - # NameServer Ͽ륳ݡͥȤ롣 - # - # @param self - # @param name оݥݡͥȤ̾ - # - # @else - # - # @endif - def unregisterCompName(self, name): - len_ = len(self._compNames) - for i in range(len_): - idx = (len_-1) - i - if self._compNames[idx].name == name: - del self._compNames[idx] + ## + # @if jp + # + # @brief NameServer に登録するコンポーネントの設定解除 + # + # NameServer に登録するコンポーネントの設定を解除する。 + # + # @param self + # @param name 設定解除対象コンポーネントの名称 + # + # @else + # + # @endif + def unregisterCompName(self, name): + len_ = len(self._compNames) + for i in range(len_): + idx = (len_ - 1) - i + if self._compNames[idx].name == name: + del self._compNames[idx] + return return - return - - - def unregisterMgrName(self, name): - len_ = len(self._mgrNames) - for i in range(len_): - idx = (len_ -1) - i - if self._mgrNames[idx].name == name: - del self._mgrNames[idx] + + def unregisterMgrName(self, name): + len_ = len(self._mgrNames) + for i in range(len_): + idx = (len_ - 1) - i + if self._mgrNames[idx].name == name: + del self._mgrNames[idx] + return return - return - - - ## - # @if jp - # - # @brief NameServer ϿݡȤ - # - # - # @param self - # @param name оݥݡȤ̾ - # - # @else - # - # @param self - # @param name - # - # @endif - def unregisterPortName(self, name): - len_ = len(self._portNames) - for i in range(len_): - idx = (len_ -1) - i - if self._portNames[idx].name == name: - del self._portNames[idx] + + ## + # @if jp + # + # @brief NameServer に登録するポートの設定解除 + # + # + # @param self + # @param name 設定解除対象ポートの名称 + # + # @else + # + # @param self + # @param name + # + # @endif + + def unregisterPortName(self, name): + len_ = len(self._portNames) + for i in range(len_): + idx = (len_ - 1) - i + if self._portNames[idx].name == name: + del self._portNames[idx] + return return - return - - - ## - # @if jp - # - # @brief ݥͥȤХɤ - # - # ͡ॵФ³ƥݥͥȤХɤ롣 - # - # @param ns NameServer - # - # @else - # - # @brief Rebind the component to NameServer - # - # Connect with the NameServer and rebind the component. - # - # @param ns NameServer - # - # @endif - # - # void retryConnection(Names* ns); - def retryConnection(self, ns): - # recreate NamingObj - nsobj = 0 - try: - nsobj = self.createNamingObj(ns.method, ns.nsname) - if nsobj is not None: # if succeed - self._rtcout.RTC_INFO("Connected to a name server: %s/%s", - (ns.method, ns.nsname)) - ns.ns = nsobj - self.bindCompsTo(nsobj) # rebind all comps to new NS + + ## + # @if jp + # + # @brief コンポネントをリバインドする + # + # ネームサーバと接続してコンポネントをリバインドする。 + # + # @param ns NameServer + # + # @else + # + # @brief Rebind the component to NameServer + # + # Connect with the NameServer and rebind the component. + # + # @param ns NameServer + # + # @endif + # + # void retryConnection(Names* ns); + + def retryConnection(self, ns): + # recreate NamingObj + nsobj = None + try: + nsobj = self.createNamingObj(ns.method, ns.nsname) + if nsobj is not None: # if succeed + self._rtcout.RTC_INFO("Connected to a name server: %s/%s", + (ns.method, ns.nsname)) + ns.ns = nsobj + self.bindCompsTo(nsobj) # rebind all comps to new NS + return + else: + self._rtcout.RTC_DEBUG("Name service: %s/%s still not available.", + (ns.method, ns.nsname)) + + except BaseException: + self._rtcout.RTC_DEBUG("Name server: %s/%s disappeared again.", + (ns.method, ns.nsname)) + if nsobj is not None: + del ns.ns + ns.ns = None + return - else: - self._rtcout.RTC_DEBUG("Name service: %s/%s still not available.", - (ns.method, ns.nsname)) - - except: - self._rtcout.RTC_DEBUG("Name server: %s/%s disappeared again.", - (ns.method, ns.nsname)) - if nsobj is not None: - del ns.ns - ns.ns = 0 - - return - - - ## - # @if jp - # - # @brief Ͽ͡ॵӥΥꥹȤ - # - # @return ͡ॵӥΥꥹ - # - # @else - # - # @brief - # - # @return - # - # @endif - # - # std::vector& getNameServices(); - def getNameServices(self): - return self._names - - ## - # @if jp - # - # @brief rtclocRTCΥ֥ȥե󥹤 - # - # @param name rtclocǤRTC̾ - # rtcloc://localhost:2809/example/ConsoleIn - # @return RTCΥ֥ȥե󥹤Υꥹ - # - # @else - # - # @brief - # - # @return - # - # @endif - # - # RTCList string_to_component(string name); - def string_to_component(self, name): - for n in self._names: - if n.ns: - comps = n.ns.string_to_component(name) - if len(comps) > 0: - return comps - return [] - - # Name Servers' method/name and object - ## - # @if jp - # @class NameServer - # @brief NameServer ѥ饹 - # @else - # - # @endif - class NameServer: - def __init__(self, meth, name, naming): - self.method = meth - self.nsname = name - self.ns = naming - - - # Components' name and object - ## - # @if jp - # @class Comps - # @brief ݡͥȴѥ饹 - # @else - # - # @endif - class Comps: - def __init__(self, n, obj): - self.name = n - self.rtobj = obj - - - class Mgr: - def __init__(self, n, obj): - self.name = n - self.mgr = obj - - - ## - # @if jp - # @class Port - # @brief ݡȴѥ饹 - # @else - # - # @endif - class Port: - def __init__(self, n, obj): - self.name = n - self.port = obj + + ## + # @if jp + # + # @brief 登録したネームサービスのリストを取得する + # + # @return ネームサービスのリスト + # + # @else + # + # @brief + # + # @return + # + # @endif + # + # std::vector& getNameServices(); + + def getNameServices(self): + return self._names + + ## + # @if jp + # + # @brief rtcloc形式でRTCのオブジェクトリファレンスを取得 + # + # @param name rtcloc形式でのRTC名 + # rtcloc://localhost:2809/example/ConsoleIn + # @return RTCのオブジェクトリファレンスのリスト + # + # @else + # + # @brief + # + # @return + # + # @endif + # + # RTCList string_to_component(string name); + def string_to_component(self, name): + for n in self._names: + if n.ns: + comps = n.ns.string_to_component(name) + if comps: + return comps + return [] + + # Name Servers' method/name and object + ## + # @if jp + # @class NameServer + # @brief NameServer 管理用クラス + # @else + # + # @endif + class NameServer: + def __init__(self, meth, name, naming): + self.method = meth + self.nsname = name + self.ns = naming + + # Components' name and object + ## + # @if jp + # @class Comps + # @brief コンポーネント管理用クラス + # @else + # + # @endif + + class Comps: + def __init__(self, n, obj): + self.name = n + self.rtobj = obj + + class Mgr: + def __init__(self, n, obj): + self.name = n + self.mgr = obj + + ## + # @if jp + # @class Port + # @brief ポート管理用クラス + # @else + # + # @endif + + class Port: + def __init__(self, n, obj): + self.name = n + self.port = obj diff --git a/OpenRTM_aist/NamingServiceNumberingPolicy.py b/OpenRTM_aist/NamingServiceNumberingPolicy.py index 806b4c54..cbd547e2 100644 --- a/OpenRTM_aist/NamingServiceNumberingPolicy.py +++ b/OpenRTM_aist/NamingServiceNumberingPolicy.py @@ -1,5 +1,5 @@ #!/usr/bin/env python -# -*- coding: euc-jp -*- +# -*- coding: utf-8 -*- ## # @file NamingServiceNumberingPolicy.py @@ -12,122 +12,113 @@ import OpenRTM_aist - - - - - ## # @if jp # # @class NamingServiceNumberingPolicy -# @brief ֥͡ߥ󥰡ݥꥷ(̿̾§)ѥ饹 -#͡ߥ󥰥ӥRTC򸡺ƥʥХ󥰤Ԥ +# @brief オブジェクト生成時ネーミング・ポリシー(命名規則)管理用クラス +# ネーミングサービスからRTCを検索してナンバリングを行う # # # @else # # @endif class NamingServiceNumberingPolicy(OpenRTM_aist.NumberingPolicy): - """ - """ - - ## - # @if jp - # - # @brief 󥹥ȥ饯 - # - # 󥹥ȥ饯 - # - # @param self - # - # @else - # - # @brief virtual destractor - # - # @endif - def __init__(self): - self._num = 0 - self._objects = [] - self._mgr = OpenRTM_aist.Manager.instance() - - - ## - # @if jp - # - # @brief ֥̾κ - # - # - # - # @param self - # @param obj ̾оݥ֥ - # - # @return ֥̾ - # - # @else - # - # @endif - def onCreate(self, obj): - num = 0 - while True: - num_str = OpenRTM_aist.otos(num) - - name = obj.getTypeName() + num_str - if not self.find(name): - return num_str - else: - num += 1 - return OpenRTM_aist.otos(num) - - ## - # @if jp - # - # @brief ֥Ⱥ̾β - # - # - # - # @param self - # @param obj ̾βоݥ֥ - # - # @else - # - # @endif - def onDelete(self, obj): - pass - - - - - - ## - # @if jp - # - # @brief ֥Ȥθ - # - # ̾Υ󥹥̾RTC򸡺 - # פRTC¸ߤTrue֤ - # - # @param self - # @param name RTCΥ󥹥̾ - # - # @return Ƚ - # - # @else - # - # @endif - def find(self, name): - rtcs = [] - rtc_name = "rtcname://*/*/" - rtc_name += name - rtcs = self._mgr.getNaming().string_to_component(rtc_name) - - if len(rtcs) > 0: - return True - else: - return False + """ + """ + + ## + # @if jp + # + # @brief コンストラクタ + # + # コンストラクタ + # + # @param self + # + # @else + # + # @brief virtual destractor + # + # @endif + def __init__(self): + self._num = 0 + self._objects = [] + self._mgr = OpenRTM_aist.Manager.instance() + + ## + # @if jp + # + # @brief オブジェクト生成時の名称作成 + # + # + # + # @param self + # @param obj 名称生成対象オブジェクト + # + # @return 生成したオブジェクト名称 + # + # @else + # + # @endif + + def onCreate(self, obj): + num = 0 + while True: + num_str = OpenRTM_aist.otos(num) + + name = obj.getTypeName() + num_str + if not self.find(name): + return num_str + else: + num += 1 + return OpenRTM_aist.otos(num) + + ## + # @if jp + # + # @brief オブジェクト削除時の名称解放 + # + # + # + # @param self + # @param obj 名称解放対象オブジェクト + # + # @else + # + # @endif + def onDelete(self, obj): + pass + + ## + # @if jp + # + # @brief オブジェクトの検索 + # + # 指定名のインスタンス名のRTCを検索し、 + # 一致するRTCが存在する場合はTrueを返す + # + # @param self + # @param name RTCのインスタンス名 + # + # @return 判定 + # + # @else + # + # @endif + + def find(self, name): + rtcs = [] + rtc_name = "rtcname://*/*/" + rtc_name += name + rtcs = self._mgr.getNaming().string_to_component(rtc_name) + + if rtcs: + return True + else: + return False def NamingServiceNumberingPolicyInit(): - OpenRTM_aist.NumberingPolicyFactory.instance().addFactory("ns_unique", - OpenRTM_aist.NamingServiceNumberingPolicy, - OpenRTM_aist.Delete) + OpenRTM_aist.NumberingPolicyFactory.instance().addFactory("ns_unique", + OpenRTM_aist.NamingServiceNumberingPolicy) diff --git a/OpenRTM_aist/NodeNumberingPolicy.py b/OpenRTM_aist/NodeNumberingPolicy.py index c429d94f..9e54dc04 100644 --- a/OpenRTM_aist/NodeNumberingPolicy.py +++ b/OpenRTM_aist/NodeNumberingPolicy.py @@ -1,5 +1,5 @@ #!/usr/bin/env python -# -*- coding: euc-jp -*- +# -*- coding: utf-8 -*- ## # @file NodeNumberingPolicy.py @@ -12,125 +12,115 @@ import OpenRTM_aist - - - ## # @if jp # # @class NodeNumberingPolicy -# @brief ֥͡ߥ󥰡ݥꥷ(̿̾§)ѥ饹 -# ޥޥ͡㡢졼֥ޥ͡㤫RTC򸡺ƥʥХ󥰤Ԥ +# @brief オブジェクト生成時ネーミング・ポリシー(命名規則)管理用クラス +# マスターマネージャ、スレーブマネージャからRTCを検索してナンバリングを行う +# # -# # # # @else # # @endif class NodeNumberingPolicy(OpenRTM_aist.NumberingPolicy): - """ - """ - - ## - # @if jp - # - # @brief 󥹥ȥ饯 - # - # 󥹥ȥ饯 - # - # @param self - # - # @else - # - # @brief virtual destractor - # - # @endif - def __init__(self): - self._mgr = OpenRTM_aist.Manager.instance() - - - ## - # @if jp - # - # @brief ֥̾κ - # - # - # @param self - # @param obj ̾оݥ֥ - # - # @return ֥̾ - # - # @else - # - # @endif - def onCreate(self, obj): - num = 0 - while True: - num_str = OpenRTM_aist.otos(num) - - name = obj.getTypeName() + num_str - if not self.find(name): - return num_str - else: - num += 1 - return OpenRTM_aist.otos(num) - - - ## - # @if jp - # - # @brief ֥Ⱥ̾β - # - # - # @param self - # @param obj ̾βоݥ֥ - # - # @else - # - # @endif - def onDelete(self, obj): - pass - - - - - - ## - # @if jp - # - # @brief ֥Ȥθ - # - # ޥޥ͡㡢ӥ졼֥ޥ͡Ͽ줿RTC򸡺 - # ̾פRTC¸ߤTrue֤ - # Υץǵưޥ͡㤬ޥޥ͡ǤϤʤ - # ˥ޥޥ͡㤬1ĤϿƤʤϤΥץΥޥ͡㤫鸡 - # - # @param self - # @param name оݥ֥Ȥ̾ - # - # @return Ƚ - # - # @else - # - # @endif - def find(self, name): - rtcs = [] - rtc_name = "rtcloc://*/*/" - rtc_name += name - - rtcs = self._mgr.getNaming().string_to_component(rtc_name) - - if len(rtcs) > 0: - return True - else: - return False - - - + """ + """ + + ## + # @if jp + # + # @brief コンストラクタ + # + # コンストラクタ + # + # @param self + # + # @else + # + # @brief virtual destractor + # + # @endif + def __init__(self): + self._mgr = OpenRTM_aist.Manager.instance() + + ## + # @if jp + # + # @brief オブジェクト生成時の名称作成 + # + # + # @param self + # @param obj 名称生成対象オブジェクト + # + # @return 生成したオブジェクト名称 + # + # @else + # + # @endif + + def onCreate(self, obj): + num = 0 + while True: + num_str = OpenRTM_aist.otos(num) + + name = obj.getTypeName() + num_str + if not self.find(name): + return num_str + else: + num += 1 + return OpenRTM_aist.otos(num) + + ## + # @if jp + # + # @brief オブジェクト削除時の名称解放 + # + # + # @param self + # @param obj 名称解放対象オブジェクト + # + # @else + # + # @endif + + def onDelete(self, obj): + pass + + ## + # @if jp + # + # @brief オブジェクトの検索 + # + # マスターマネージャ、およびスレーブマネージャに登録されたRTCを検索し、 + #     名前が一致するRTCが存在する場合はTrueを返す + # このプロセスで起動したマネージャがマスターマネージャではなく、 + # さらにマスターマネージャが1つも登録されていない場合はこのプロセスのマネージャから検索 + # + # @param self + # @param name 検索対象オブジェクトの名前 + # + # @return 判定 + # + # @else + # + # @endif + + def find(self, name): + rtcs = [] + rtc_name = "rtcloc://*/*/" + rtc_name += name + + rtcs = self._mgr.getNaming().string_to_component(rtc_name) + + if rtcs: + return True + else: + return False def NodeNumberingPolicyInit(): - OpenRTM_aist.NumberingPolicyFactory.instance().addFactory("node_unique", - OpenRTM_aist.NodeNumberingPolicy, - OpenRTM_aist.Delete) + OpenRTM_aist.NumberingPolicyFactory.instance().addFactory("node_unique", + OpenRTM_aist.NodeNumberingPolicy) diff --git a/OpenRTM_aist/NumberingPolicy.py b/OpenRTM_aist/NumberingPolicy.py index 35a2de1f..4595570f 100644 --- a/OpenRTM_aist/NumberingPolicy.py +++ b/OpenRTM_aist/NumberingPolicy.py @@ -1,5 +1,5 @@ #!/usr/bin/env python -# -*- coding: euc-jp -*- +# -*- coding: utf-8 -*- ## # @file NumberingPolicy.py @@ -18,19 +18,17 @@ import OpenRTM_aist - - ## # @if jp # # @class NumberingPolicy -# @brief ֥͡ߥ󥰡ݥꥷ(̿̾§)ݥ饹 +# @brief オブジェクト生成時ネーミング・ポリシー(命名規則)管理用抽象クラス # -# ֥ȤݤΥ͡ߥ󥰡ݥꥷ(̿̾§)뤿 -# ݥ饹 -# ݥ饹ϡʲδؿμ󶡤ʤФʤʤ -# - onCreate() : ֥̾κ -# - onDelete() : ֥Ⱥ̾β +# オブジェクトを生成する際のネーミング・ポリシー(命名規則)を管理するための +# 抽象クラス。 +# 具象クラスは、以下の関数の実装を提供しなければならない。 +# - onCreate() : オブジェクト生成時の名称作成 +# - onDelete() : オブジェクト削除時の名称解放 # # @since 0.4.0 # @@ -38,68 +36,65 @@ # # @endif class NumberingPolicy(OpenRTM_aist.NumberingPolicyBase): - """ - """ - - - - ## - # @if jp - # @brief ֥̤ȯ㳰饹(̤) - # @else - # - # @endif - class ObjectNotFound(Exception): - pass - - - ## - # @if jp - # - # @brief ֥̾κ(֥饹) - # - # ֥̾Τ뤿δؿ
    - # ֥饹Ǥμ - # - # @param self - # @param obj ̾оݥ֥ - # - # @return ֥̾ - # - # @else - # - # @endif - def onCreate(self, obj): - pass - - - ## - # @if jp - # - # @brief ֥Ⱥ̾β(֥饹) - # - # ֥Ⱥ̾Τ뤿δؿ
    - # ֥饹Ǥμ - # - # @param self - # @param obj ̾βоݥ֥ - # - # @else - # - # @endif - def onDelete(self, obj): - pass - - + """ + """ + + ## + # @if jp + # @brief オブジェクト未発見例外処理用内部クラス(未実装) + # @else + # + # @endif + class ObjectNotFound(Exception): + pass + + ## + # @if jp + # + # @brief オブジェクト生成時の名称作成(サブクラス実装用) + # + # オブジェクト生成時の名称を生成するための関数
    + # ※サブクラスでの実装参照用 + # + # @param self + # @param obj 名称生成対象オブジェクト + # + # @return 生成したオブジェクト名称 + # + # @else + # + # @endif + + def onCreate(self, obj): + pass + + ## + # @if jp + # + # @brief オブジェクト削除時の名称解放(サブクラス実装用) + # + # オブジェクト削除時に名称を解放するための関数
    + # ※サブクラスでの実装参照用 + # + # @param self + # @param obj 名称解放対象オブジェクト + # + # @else + # + # @endif + + def onDelete(self, obj): + pass + ## # @if jp # # @class ProcessUniquePolicy -# @brief ֥͡ߥ󥰡ݥꥷ(̿̾§)ѥ饹 +# @brief オブジェクト生成時ネーミング・ポリシー(命名規則)管理用クラス # -# ֥ȤݤΥ͡ߥ󥰡ݥꥷ(̿̾§)뤿 -# 饹 +# オブジェクトを生成する際のネーミング・ポリシー(命名規則)を管理するための +# クラス。 # # @since 0.4.0 # @@ -107,113 +102,110 @@ def onDelete(self, obj): # # @endif class ProcessUniquePolicy(NumberingPolicy): - """ - """ - - ## - # @if jp - # - # @brief 󥹥ȥ饯 - # - # 󥹥ȥ饯 - # - # @param self - # - # @else - # - # @brief virtual destractor - # - # @endif - def __init__(self): - self._num = 0 - self._objects = [] - - - ## - # @if jp - # - # @brief ֥̾κ - # - # ֥̾Τ롣 - # Ѥߥ󥹥󥹤ο˱̾Τ롣 - # - # @param self - # @param obj ̾оݥ֥ - # - # @return ֥̾ - # - # @else - # - # @endif - def onCreate(self, obj): - self._num += 1 - - pos = 0 - try: - pos = self.find(None) - self._objects[pos] = obj - return OpenRTM_aist.otos(pos) - except NumberingPolicy.ObjectNotFound: - self._objects.append(obj) - return OpenRTM_aist.otos(int(len(self._objects) - 1)) - - - ## - # @if jp - # - # @brief ֥Ⱥ̾β - # - # ֥Ⱥ̾Τ롣 - # ֥ȺѤߥ󥹥󥹿򸺻롣 - # - # @param self - # @param obj ̾βоݥ֥ - # - # @else - # - # @endif - def onDelete(self, obj): - pos = 0 - try: - pos = self.find(obj) - except: - return - - if (pos < len(self._objects)): - self._objects[pos] = None - self._num -= 1 - - - ## - # @if jp - # - # @brief ֥Ȥθ - # - # ֥ȥꥹȤꤵ줿֥Ȥ򸡺 - # 륪֥ȤǼƤˤϥǥå֤ - # - # @param self - # @param obj оݥ֥ - # - # @return ֥ȳǼǥå - # - # @else - # - # @endif - def find(self, obj): - i = 0 - for obj_ in self._objects: - if obj_ == obj: - return i - i += 1 - raise NumberingPolicy.ObjectNotFound() + """ + """ + + ## + # @if jp + # + # @brief コンストラクタ + # + # コンストラクタ + # + # @param self + # + # @else + # + # @brief virtual destractor + # + # @endif + def __init__(self): + self._num = 0 + self._objects = [] + + ## + # @if jp + # + # @brief オブジェクト生成時の名称作成 + # + # オブジェクト生成時の名称を生成する。 + # 生成済みインスタンスの数に応じた名称を生成する。 + # + # @param self + # @param obj 名称生成対象オブジェクト + # + # @return 生成したオブジェクト名称 + # + # @else + # + # @endif + + def onCreate(self, obj): + self._num += 1 + + pos = 0 + try: + pos = self.find(None) + self._objects[pos] = obj + return OpenRTM_aist.otos(pos) + except NumberingPolicy.ObjectNotFound: + self._objects.append(obj) + return OpenRTM_aist.otos(int(len(self._objects) - 1)) + + ## + # @if jp + # + # @brief オブジェクト削除時の名称解放 + # + # オブジェクト削除時に名称を解放する。 + # オブジェクト削除時に生成済みインスタンス数を減算する。 + # + # @param self + # @param obj 名称解放対象オブジェクト + # + # @else + # + # @endif + + def onDelete(self, obj): + pos = 0 + try: + pos = self.find(obj) + except BaseException: + return + + if (pos < len(self._objects)): + self._objects[pos] = None + self._num -= 1 + + ## + # @if jp + # + # @brief オブジェクトの検索 + # + # オブジェクトリストから指定されたオブジェクトを検索し、 + # 該当するオブジェクトが格納されている場合にはインデックスを返す。 + # + # @param self + # @param obj 検索対象オブジェクト + # + # @return オブジェクト格納インデックス + # + # @else + # + # @endif + + def find(self, obj): + i = 0 + for obj_ in self._objects: + if obj_ == obj: + return i + i += 1 + raise NumberingPolicy.ObjectNotFound() def ProcessUniquePolicyInit(): - OpenRTM_aist.NumberingPolicyFactory.instance().addFactory("default", - OpenRTM_aist.ProcessUniquePolicy, - OpenRTM_aist.Delete) - OpenRTM_aist.NumberingPolicyFactory.instance().addFactory("process_unique", - OpenRTM_aist.ProcessUniquePolicy, - OpenRTM_aist.Delete) - + OpenRTM_aist.NumberingPolicyFactory.instance().addFactory("default", + OpenRTM_aist.ProcessUniquePolicy) + OpenRTM_aist.NumberingPolicyFactory.instance().addFactory("process_unique", + OpenRTM_aist.ProcessUniquePolicy) diff --git a/OpenRTM_aist/NumberingPolicyBase.py b/OpenRTM_aist/NumberingPolicyBase.py index b99c3928..c89c7d9d 100644 --- a/OpenRTM_aist/NumberingPolicyBase.py +++ b/OpenRTM_aist/NumberingPolicyBase.py @@ -1,5 +1,5 @@ #!/usr/bin/env python -# -*- coding: euc-jp -*- +# -*- coding: utf-8 -*- ## # @file NumberingPolicyBase.py @@ -9,7 +9,6 @@ # - import OpenRTM_aist @@ -17,7 +16,7 @@ # @if jp # # @class NumberingPolicyBase -# @brief ֥͡ߥ󥰡ݥꥷ(̿̾§)Ѵ쥯饹 +# @brief オブジェクト生成時ネーミング・ポリシー(命名規則)管理用基底クラス # # # @@ -25,24 +24,26 @@ # # @endif class NumberingPolicyBase: - def __init__(self): - pass - def onCreate(self, obj): - pass - def onDelete(self, obj): - pass + def __init__(self): + pass + + def onCreate(self, obj): + pass + def onDelete(self, obj): + pass numberingpolicyfactory = None -class NumberingPolicyFactory(OpenRTM_aist.Factory): - def __init__(self): - OpenRTM_aist.Factory.__init__(self) - def instance(): - global numberingpolicyfactory - if numberingpolicyfactory is None: - numberingpolicyfactory = NumberingPolicyFactory() - return numberingpolicyfactory - instance = staticmethod(instance) +class NumberingPolicyFactory(OpenRTM_aist.Factory): + def __init__(self): + OpenRTM_aist.Factory.__init__(self) + + def instance(): + global numberingpolicyfactory + if numberingpolicyfactory is None: + numberingpolicyfactory = NumberingPolicyFactory() + return numberingpolicyfactory + instance = staticmethod(instance) diff --git a/OpenRTM_aist/ObjectManager.py b/OpenRTM_aist/ObjectManager.py index 1e0f5c9a..99881165 100644 --- a/OpenRTM_aist/ObjectManager.py +++ b/OpenRTM_aist/ObjectManager.py @@ -1,5 +1,5 @@ #!/usr/bin/env python -# -*- coding: euc-jp -*- +# -*- coding: utf-8 -*- ## # @file ObjectManager.py @@ -15,19 +15,17 @@ # All rights reserved. - import threading import OpenRTM_aist - ## # @if jp # -# @brief ֥ȴѥ饹 +# @brief オブジェクト管理用クラス # -# Ƽ索֥Ȥ뤿Υ饹 +# 各種オブジェクトを管理するためのクラス。 # # @since 0.4.0 # @@ -35,165 +33,163 @@ # # @endif class ObjectManager: - """ - """ - - ## - # @if jp - # - # @brief 󥹥ȥ饯 - # - # 󥹥ȥ饯 - # - # @param self - # @param predicate ֥ȸѥե󥯥 - # - # @else - # - # @endif - def __init__(self, predicate): - self._objects = self.Objects() - self._predicate = predicate - - - - ## - # @if jp - # @class Objects - # @brief ֥ȴ饹 - # @endif - class Objects: - def __init__(self): - self._mutex = threading.RLock() - self._obj = [] - - - ## - # @if jp - # - # @brief ꤷ֥ȤϿ - # - # ꤷ֥ȤϿ롣 - # Ʊ쥪֥ȤϿѤߤξϡԤʤ - # - # @param self - # @param obj Ͽоݥ֥ - # - # @return Ͽ(֥ȤϿtrue) - # - # @else - # - # @endif - def registerObject(self, obj): - guard = OpenRTM_aist.ScopedLock(self._objects._mutex) - predi = self._predicate(factory=obj) - - for _obj in self._objects._obj: - if predi(_obj): - return False - - self._objects._obj.append(obj) - return True - - - ## - # @if jp - # - # @brief ꤷ֥ȤϿ - # - # ꤷ֥ȤϿ롣 - # ꤷ֥ȤϿƤʤˤNULL֤ - # - # @param self - # @param id Ͽоݥ֥ȤID - # - # @return Ͽ줿֥ - # - # @else - # - # @endif - def unregisterObject(self, id): - guard = OpenRTM_aist.ScopedLock(self._objects._mutex) - predi = self._predicate(name=id) - i = 0 - for _obj in self._objects._obj: - if predi(_obj): - ret = _obj - del self._objects._obj[i] - return ret - i+=1 - - return None - - - ## - # @if jp - # - # @brief ֥Ȥ򸡺 - # - # ϿƤ륪֥Ȥ椫ꤷ˹פ륪֥Ȥ򸡺 - # Ƽ롣 - # ꤷ˹פ륪֥ȤϿƤʤˤNULL֤ - # - # @param self - # @param id оݥ֥ȤID - # - # @return ֥Ȥθ - # - # @else - # - # @endif - def find(self, id): - guard = OpenRTM_aist.ScopedLock(self._objects._mutex) - if isinstance(id,str): - predi = self._predicate(name=id) - else: - predi = self._predicate(prop=id) - - for _obj in self._objects._obj: - if predi(_obj): - return _obj - - return None - - - ## - # @if jp - # - # @brief ϿƤ륪֥ȤΥꥹȤ - # - # ϿƤ륪֥ȤΥꥹȤ롣 - # - # @param self - # - # @return ϿƤ륪֥ȡꥹ - # - # @else - # - # @endif - def getObjects(self): - guard = OpenRTM_aist.ScopedLock(self._objects._mutex) - return self._objects._obj - - - ## - # @if jp - # @brief ֥Ȥ򸡺 - # - # ꤵ줿˹פ륪֥Ȥ򸡺롣 - # - # @param self - # @param p ֥ȸѥե󥯥 - # - # @else - # - # @endif - def for_each(self,p): - guard = OpenRTM_aist.ScopedLock(self._objects._mutex) - predi = p() - - for _obj in self._objects._obj: - predi(_obj) - - return predi - + """ + """ + + ## + # @if jp + # + # @brief コンストラクタ + # + # コンストラクタ + # + # @param self + # @param predicate オブジェクト検索用ファンクタ + # + # @else + # + # @endif + def __init__(self, predicate): + self._objects = self.Objects() + self._predicate = predicate + + ## + # @if jp + # @class Objects + # @brief オブジェクト管理用内部クラス + # @endif + + class Objects: + def __init__(self): + self._mutex = threading.RLock() + self._obj = [] + + ## + # @if jp + # + # @brief 指定したオブジェクトを登録する + # + # 指定したオブジェクトを登録する。 + # 同一オブジェクトが登録済みの場合は、何も行わない。 + # + # @param self + # @param obj 登録対象オブジェクト + # + # @return 登録処理結果(オブジェクトを登録した場合にtrue) + # + # @else + # + # @endif + + def registerObject(self, obj): + guard = OpenRTM_aist.ScopedLock(self._objects._mutex) + predi = self._predicate(factory=obj) + + for _obj in self._objects._obj: + if predi(_obj): + return False + + self._objects._obj.append(obj) + return True + + ## + # @if jp + # + # @brief 指定したオブジェクトを登録解除する + # + # 指定したオブジェクトの登録を解除し、取得する。 + # 指定したオブジェクトが登録されていない場合にはNULLを返す。 + # + # @param self + # @param id 登録解除対象オブジェクトのID + # + # @return 登録解除されたオブジェクト + # + # @else + # + # @endif + + def unregisterObject(self, id): + guard = OpenRTM_aist.ScopedLock(self._objects._mutex) + predi = self._predicate(name=id) + i = 0 + for _obj in self._objects._obj: + if predi(_obj): + ret = _obj + del self._objects._obj[i] + return ret + i += 1 + + return None + + ## + # @if jp + # + # @brief オブジェクトを検索する + # + # 登録されているオブジェクトの中から指定した条件に合致するオブジェクトを検索 + # して取得する。 + # 指定した条件に合致するオブジェクトが登録されていない場合にはNULLを返す。 + # + # @param self + # @param id 検索対象オブジェクトのID + # + # @return オブジェクトの検索結果 + # + # @else + # + # @endif + + def find(self, id): + guard = OpenRTM_aist.ScopedLock(self._objects._mutex) + if isinstance(id, str): + predi = self._predicate(name=id) + else: + predi = self._predicate(prop=id) + + for _obj in self._objects._obj: + if predi(_obj): + return _obj + + return None + + ## + # @if jp + # + # @brief 登録されているオブジェクトのリストを取得する + # + # 登録されているオブジェクトのリストを取得する。 + # + # @param self + # + # @return 登録されているオブジェクト・リスト + # + # @else + # + # @endif + + def getObjects(self): + guard = OpenRTM_aist.ScopedLock(self._objects._mutex) + return self._objects._obj + + ## + # @if jp + # @brief オブジェクトを検索する + # + # 指定された条件に合致するオブジェクトを検索する。 + # + # @param self + # @param p オブジェクト検索用ファンクタ + # + # @else + # + # @endif + + def for_each(self, p): + guard = OpenRTM_aist.ScopedLock(self._objects._mutex) + predi = p() + + for _obj in self._objects._obj: + predi(_obj) + + return predi diff --git a/OpenRTM_aist/OpenHRPExecutionContext.py b/OpenRTM_aist/OpenHRPExecutionContext.py index cb5d814e..014f0d97 100755 --- a/OpenRTM_aist/OpenHRPExecutionContext.py +++ b/OpenRTM_aist/OpenHRPExecutionContext.py @@ -1,5 +1,5 @@ #!/usr/bin/env python -# -*- coding: euc-jp -*- +# -*- coding: utf-8 -*- ## # @file OpenHRPExecutionContext.py @@ -18,296 +18,296 @@ import time import OpenRTM_aist -import OpenRTM__POA, RTC +import OpenRTM__POA +import RTC class OpenHRPExecutionContext(OpenRTM_aist.ExecutionContextBase, OpenRTM__POA.ExtTrigExecutionContextService): - """ - """ - - def __init__(self): - self._rtcout = OpenRTM_aist.Manager.instance().getLogbuf("rtobject.exttrig_sync_ec") - self._rtcout.RTC_TRACE("OpenHRPExecutionContext.__init__()") - OpenRTM_aist.ExecutionContextBase.__init__(self, "exttrig_sync_ec") - - self.setObjRef(self._this()) - self.setKind(RTC.PERIODIC) - self.setRate(OpenRTM_aist.DEFAULT_EXECUTION_RATE) - self._rtcout.RTC_DEBUG("Actual rate: %d [sec], %d [usec]", - (self._profile.getPeriod().sec(), self._profile.getPeriod().usec())) - self._tickmutex = threading.RLock() - self._count = 0 - return - + """ + """ + + def __init__(self): + self._rtcout = OpenRTM_aist.Manager.instance().getLogbuf("rtobject.exttrig_sync_ec") + self._rtcout.RTC_TRACE("OpenHRPExecutionContext.__init__()") + OpenRTM_aist.ExecutionContextBase.__init__(self, "exttrig_sync_ec") + + self.setObjRef(self._this()) + self.setKind(RTC.PERIODIC) + self.setRate(OpenRTM_aist.DEFAULT_EXECUTION_RATE) + self._rtcout.RTC_DEBUG("Actual rate: %d [sec], %d [usec]", + (self._profile.getPeriod().sec(), self._profile.getPeriod().usec())) + self._tickmutex = threading.RLock() + self._count = 0 + return + + def __del__(self): + self._rtcout.RTC_TRACE("OpenHRPExecutionContext().__del__()") + return + + # ============================================================ + # OpenHRPExecutionContextService + # ============================================================ + ## + # @if jp + # @brief 処理を1ステップ進める + # @else + # @brief Move forward one step of ExecutionContext + # @endif + + def tick(self): + self._rtcout.RTC_TRACE("tick()") + if not self.isRunning(): + return + + guard = OpenRTM_aist.ScopedLock(self._tickmutex) + + OpenRTM_aist.ExecutionContextBase.invokeWorkerPreDo( + self) # update state + t0 = OpenRTM_aist.Time() + OpenRTM_aist.ExecutionContextBase.invokeWorkerDo(self) + t1 = OpenRTM_aist.Time() + OpenRTM_aist.ExecutionContextBase.invokeWorkerPostDo(self) + t2 = OpenRTM_aist.Time() + + period = self.getPeriod() + + if self._count > 1000: + excdotm = (t1 - t0).getTime().toDouble() + excpdotm = (t2 - t1).getTime().toDouble() + slptm = period.toDouble() - (t2 - t0).getTime().toDouble() + self._rtcout.RTC_PARANOID("Period: %f [s]", period.toDouble()) + self._rtcout.RTC_PARANOID("Exec-Do: %f [s]", excdotm) + self._rtcout.RTC_PARANOID("Exec-PostDo: %f [s]", excpdotm) + self._rtcout.RTC_PARANOID("Sleep: %f [s]", slptm) + + t3 = OpenRTM_aist.Time() + if period.toDouble() > (t2 - t0).getTime().toDouble(): + if self._count > 1000: + self._rtcout.RTC_PARANOID("sleeping...") + slptm = period.toDouble() - (t2 - t0).getTime().toDouble() + time.sleep(slptm) + + if self._count > 1000: + t4 = OpenRTM_aist.Time() + self._rtcout.RTC_PARANOID( + "Slept: %f [s]", + (t4 - t3).getTime().toDouble()) + self._count = 0 + + self._count += 1 + return + + # ============================================================ + # ExecutionContextService + # ============================================================ + ## + # @if jp + # @brief ExecutionContext 実行状態確認関数 + # @else + # @brief Check for ExecutionContext running state + # @endif + # CORBA::Boolean OpenHRPExecutionContext::is_running() + # throw (CORBA::SystemException) + + def is_running(self): + return OpenRTM_aist.ExecutionContextBase.isRunning(self) + + ## + # @if jp + # @brief ExecutionContext の実行を開始 + # @else + # @brief Start the ExecutionContext + # @endif + # RTC::ReturnCode_t OpenHRPExecutionContext::start() + # throw (CORBA::SystemException) + + def start(self): + return OpenRTM_aist.ExecutionContextBase.start(self) + + ## + # @if jp + # @brief ExecutionContext の実行を停止 + # @else + # @brief Stop the ExecutionContext + # @endif + # RTC::ReturnCode_t OpenHRPExecutionContext::stop() + # throw (CORBA::SystemException) + + def stop(self): + return OpenRTM_aist.ExecutionContextBase.stop(self) + + ## + # @if jp + # @brief ExecutionContext の実行周期(Hz)を取得する + # @else + # @brief Get execution rate(Hz) of ExecutionContext + # @endif + # CORBA::Double OpenHRPExecutionContext::get_rate() + # throw (CORBA::SystemException) + + def get_rate(self): + return OpenRTM_aist.ExecutionContextBase.getRate(self) + + ## + # @if jp + # @brief ExecutionContext の実行周期(Hz)を設定する + # @else + # @brief Set execution rate(Hz) of ExecutionContext + # @endif + # RTC::ReturnCode_t OpenHRPExecutionContext::set_rate(CORBA::Double rate) + # throw (CORBA::SystemException) + + def set_rate(self, rate): + return OpenRTM_aist.ExecutionContextBase.setRate(self, rate) + + ## + # @if jp + # @brief RTコンポーネントを追加する + # @else + # @brief Add an RT-Component + # @endif + # RTC::ReturnCode_t + # OpenHRPExecutionContext::add_component(RTC::LightweightRTObject_ptr comp) + # throw (CORBA::SystemException) + + def add_component(self, comp): + return OpenRTM_aist.ExecutionContextBase.addComponent(self, comp) + + ## + # @if jp + # @brief コンポーネントをコンポーネントリストから削除する + # @else + # @brief Remove the RT-Component from participant list + # @endif + # RTC::ReturnCode_t OpenHRPExecutionContext:: + # remove_component(RTC::LightweightRTObject_ptr comp) + # throw (CORBA::SystemException) + + def remove_component(self, comp): + return OpenRTM_aist.ExecutionContextBase.removeComponent(self, comp) + + ## + # @if jp + # @brief RTコンポーネントをアクティブ化する + # @else + # @brief Activate an RT-Component + # @endif + # RTC::ReturnCode_t OpenHRPExecutionContext:: + # activate_component(RTC::LightweightRTObject_ptr comp) + # throw (CORBA::SystemException) + + def activate_component(self, comp): + return OpenRTM_aist.ExecutionContextBase.activateComponent(self, comp) + + ## + # @if jp + # @brief RTコンポーネントを非アクティブ化する + # @else + # @brief Deactivate an RT-Component + # @endif + # RTC::ReturnCode_t OpenHRPExecutionContext:: + # deactivate_component(RTC::LightweightRTObject_ptr comp) + # throw (CORBA::SystemException) + + def deactivate_component(self, comp): + return OpenRTM_aist.ExecutionContextBase.deactivateComponent( + self, comp) + + ## + # @if jp + # @brief RTコンポーネントをリセットする + # @else + # @brief Reset the RT-Component + # @endif + # RTC::ReturnCode_t OpenHRPExecutionContext:: + # reset_component(RTC::LightweightRTObject_ptr comp) + # throw (CORBA::SystemException) + + def reset_component(self, comp): + return OpenRTM_aist.ExecutionContextBase.resetComponent(self, comp) + + ## + # @if jp + # @brief RTコンポーネントの状態を取得する + # @else + # @brief Get RT-Component's state + # @endif + # RTC::LifeCycleState OpenHRPExecutionContext:: + # get_component_state(RTC::LightweightRTObject_ptr comp) + # throw (CORBA::SystemException) + # get_component_state(RTC::LightweightRTObject_ptr comp) + # throw (CORBA::SystemException) + + def get_component_state(self, comp): + return OpenRTM_aist.ExecutionContextBase.getComponentState(self, comp) + + ## + # @if jp + # @brief ExecutionKind を取得する + # @else + # @brief Get the ExecutionKind + # @endif + # RTC::ExecutionKind OpenHRPExecutionContext::get_kind() + # throw (CORBA::SystemException) + + def get_kind(self): + return OpenRTM_aist.ExecutionContextBase.getKind(self) + + # ------------------------------------------------------------ + # ExecutionContextService interfaces + # ------------------------------------------------------------ + ## + # @if jp + # @brief ExecutionContextProfile を取得する + # @else + # @brief Get the ExecutionContextProfile + # @endif + # RTC::ExecutionContextProfile* OpenHRPExecutionContext::get_profile() + # throw (CORBA::SystemException) + + def get_profile(self): + return OpenRTM_aist.ExecutionContextBase.getProfile(self) + + def onAddedComponent(self, rtobj): + guard = OpenRTM_aist.ScopedLock(self._tickmutex) + self._worker.updateComponentList() + return RTC.RTC_OK + + def onRemovedComponent(self, rtobj): + guard = OpenRTM_aist.ScopedLock(self._tickmutex) + self._worker.updateComponentList() + return RTC.RTC_OK + + def onWaitingActivated(self, comp, count): + self._rtcout.RTC_TRACE("onWaitingActivated(count = %d)", count) + self._rtcout.RTC_PARANOID("curr: %s, next: %s", + (self.getStateString(comp.getStates().curr), + self.getStateString(comp.getStates().next))) + self.tick() + return RTC.RTC_OK + + def onWaitingDeactivated(self, comp, count): + self._rtcout.RTC_TRACE("onWaitingDeactivated(count = %d)", count) + self._rtcout.RTC_PARANOID("curr: %s, next: %s", + (self.getStateString(comp.getStates().curr), + self.getStateString(comp.getStates().next))) + self.tick() + return RTC.RTC_OK + + def onWaitingReset(self, comp, count): + self._rtcout.RTC_TRACE("onWaitingReset(count = %d)", count) + self._rtcout.RTC_PARANOID("curr: %s, next: %s", + (self.getStateString(comp.getStates().curr), + self.getStateString(comp.getStates().next))) + self.tick() + return RTC.RTC_OK - def __del__(self): - self._rtcout.RTC_TRACE("OpenHRPExecutionContext().__del__()") - return +def OpenHRPExecutionContextInit(manager): + OpenRTM_aist.ExecutionContextFactory.instance().addFactory("OpenHRPExecutionContext", + OpenRTM_aist.OpenHRPExecutionContext) + OpenRTM_aist.ExecutionContextFactory.instance().addFactory("SynchExtTriggerEC", + OpenRTM_aist.OpenHRPExecutionContext) - #============================================================ - # OpenHRPExecutionContextService - #============================================================ - ## - # @if jp - # @brief 1ƥå׿ʤ - # @else - # @brief Move forward one step of ExecutionContext - # @endif - def tick(self): - self._rtcout.RTC_TRACE("tick()") - if not self.isRunning(): - return - - guard = OpenRTM_aist.ScopedLock(self._tickmutex) - - OpenRTM_aist.ExecutionContextBase.invokeWorkerPreDo(self) # update state - t0 = OpenRTM_aist.Time() - OpenRTM_aist.ExecutionContextBase.invokeWorkerDo(self) - t1 = OpenRTM_aist.Time() - OpenRTM_aist.ExecutionContextBase.invokeWorkerPostDo(self) - t2 = OpenRTM_aist.Time() - - period = self.getPeriod() - - if self._count > 1000: - excdotm = (t1 - t0).getTime().toDouble() - excpdotm = (t2 - t1).getTime().toDouble() - slptm = period.toDouble() - (t2 - t0).getTime().toDouble() - self._rtcout.RTC_PARANOID("Period: %f [s]", period.toDouble()) - self._rtcout.RTC_PARANOID("Exec-Do: %f [s]", excdotm) - self._rtcout.RTC_PARANOID("Exec-PostDo: %f [s]", excpdotm) - self._rtcout.RTC_PARANOID("Sleep: %f [s]", slptm) - - t3 = OpenRTM_aist.Time() - if period.toDouble() > (t2 - t0).getTime().toDouble(): - if self._count > 1000: - self._rtcout.RTC_PARANOID("sleeping...") - slptm = period.toDouble() - (t2 - t0).getTime().toDouble() - time.sleep(slptm) - - if self._count > 1000: - t4 = OpenRTM_aist.Time() - self._rtcout.RTC_PARANOID("Slept: %f [s]", (t4 - t3).getTime().toDouble()) - self._count = 0 - - self._count += 1 return - - - #============================================================ - # ExecutionContextService - #============================================================ - ## - # @if jp - # @brief ExecutionContext ¹Ծֳǧؿ - # @else - # @brief Check for ExecutionContext running state - # @endif - # CORBA::Boolean OpenHRPExecutionContext::is_running() - # throw (CORBA::SystemException) - def is_running(self): - return OpenRTM_aist.ExecutionContextBase.isRunning(self) - - - ## - # @if jp - # @brief ExecutionContext μ¹Ԥ򳫻 - # @else - # @brief Start the ExecutionContext - # @endif - # RTC::ReturnCode_t OpenHRPExecutionContext::start() - # throw (CORBA::SystemException) - def start(self): - return OpenRTM_aist.ExecutionContextBase.start(self) - - - ## - # @if jp - # @brief ExecutionContext μ¹Ԥ - # @else - # @brief Stop the ExecutionContext - # @endif - # RTC::ReturnCode_t OpenHRPExecutionContext::stop() - # throw (CORBA::SystemException) - def stop(self): - return OpenRTM_aist.ExecutionContextBase.stop(self) - - - ## - # @if jp - # @brief ExecutionContext μ¹Լ(Hz) - # @else - # @brief Get execution rate(Hz) of ExecutionContext - # @endif - # CORBA::Double OpenHRPExecutionContext::get_rate() - # throw (CORBA::SystemException) - def get_rate(self): - return OpenRTM_aist.ExecutionContextBase.getRate(self) - - - ## - # @if jp - # @brief ExecutionContext μ¹Լ(Hz)ꤹ - # @else - # @brief Set execution rate(Hz) of ExecutionContext - # @endif - # RTC::ReturnCode_t OpenHRPExecutionContext::set_rate(CORBA::Double rate) - # throw (CORBA::SystemException) - def set_rate(self, rate): - return OpenRTM_aist.ExecutionContextBase.setRate(self, rate) - - - ## - # @if jp - # @brief RTݡͥȤɲä - # @else - # @brief Add an RT-Component - # @endif - # RTC::ReturnCode_t - # OpenHRPExecutionContext::add_component(RTC::LightweightRTObject_ptr comp) - # throw (CORBA::SystemException) - def add_component(self, comp): - return OpenRTM_aist.ExecutionContextBase.addComponent(self, comp) - - - ## - # @if jp - # @brief ݡͥȤ򥳥ݡͥȥꥹȤ - # @else - # @brief Remove the RT-Component from participant list - # @endif - # RTC::ReturnCode_t OpenHRPExecutionContext:: - # remove_component(RTC::LightweightRTObject_ptr comp) - # throw (CORBA::SystemException) - def remove_component(self, comp): - return OpenRTM_aist.ExecutionContextBase.removeComponent(self, comp) - - - ## - # @if jp - # @brief RTݡͥȤ򥢥ƥֲ - # @else - # @brief Activate an RT-Component - # @endif - # RTC::ReturnCode_t OpenHRPExecutionContext:: - # activate_component(RTC::LightweightRTObject_ptr comp) - # throw (CORBA::SystemException) - def activate_component(self, comp): - return OpenRTM_aist.ExecutionContextBase.activateComponent(self, comp) - - - ## - # @if jp - # @brief RTݡͥȤ󥢥ƥֲ - # @else - # @brief Deactivate an RT-Component - # @endif - # RTC::ReturnCode_t OpenHRPExecutionContext:: - # deactivate_component(RTC::LightweightRTObject_ptr comp) - # throw (CORBA::SystemException) - def deactivate_component(self, comp): - return OpenRTM_aist.ExecutionContextBase.deactivateComponent(self, comp) - - - ## - # @if jp - # @brief RTݡͥȤꥻåȤ - # @else - # @brief Reset the RT-Component - # @endif - # RTC::ReturnCode_t OpenHRPExecutionContext:: - # reset_component(RTC::LightweightRTObject_ptr comp) - # throw (CORBA::SystemException) - def reset_component(self, comp): - return OpenRTM_aist.ExecutionContextBase.resetComponent(self, comp) - - - ## - # @if jp - # @brief RTݡͥȤξ֤ - # @else - # @brief Get RT-Component's state - # @endif - # RTC::LifeCycleState OpenHRPExecutionContext:: - # get_component_state(RTC::LightweightRTObject_ptr comp) - # throw (CORBA::SystemException) - # get_component_state(RTC::LightweightRTObject_ptr comp) - # throw (CORBA::SystemException) - def get_component_state(self, comp): - return OpenRTM_aist.ExecutionContextBase.getComponentState(self, comp) - - - ## - # @if jp - # @brief ExecutionKind - # @else - # @brief Get the ExecutionKind - # @endif - # RTC::ExecutionKind OpenHRPExecutionContext::get_kind() - # throw (CORBA::SystemException) - def get_kind(self): - return OpenRTM_aist.ExecutionContextBase.getKind(self) - - - #------------------------------------------------------------ - # ExecutionContextService interfaces - #------------------------------------------------------------ - ## - # @if jp - # @brief ExecutionContextProfile - # @else - # @brief Get the ExecutionContextProfile - # @endif - # RTC::ExecutionContextProfile* OpenHRPExecutionContext::get_profile() - # throw (CORBA::SystemException) - def get_profile(self): - return OpenRTM_aist.ExecutionContextBase.getProfile(self) - - - def onAddedComponent(self, rtobj): - guard = OpenRTM_aist.ScopedLock(self._tickmutex) - self._worker.updateComponentList() - return RTC.RTC_OK - - def onRemovedComponent(self, rtobj): - guard = OpenRTM_aist.ScopedLock(self._tickmutex) - self._worker.updateComponentList() - return RTC.RTC_OK - - def onWaitingActivated(self, comp, count): - self._rtcout.RTC_TRACE("onWaitingActivated(count = %d)", count) - self._rtcout.RTC_PARANOID("curr: %s, next: %s", - (self.getStateString(comp.getStates().curr), - self.getStateString(comp.getStates().next))) - self.tick() - return RTC.RTC_OK - - def onWaitingDeactivated(self, comp, count): - self._rtcout.RTC_TRACE("onWaitingDeactivated(count = %d)", count) - self._rtcout.RTC_PARANOID("curr: %s, next: %s", - (self.getStateString(comp.getStates().curr), - self.getStateString(comp.getStates().next))) - self.tick() - return RTC.RTC_OK - - def onWaitingReset(self, comp, count): - self._rtcout.RTC_TRACE("onWaitingReset(count = %d)", count) - self._rtcout.RTC_PARANOID("curr: %s, next: %s", - (self.getStateString(comp.getStates().curr), - self.getStateString(comp.getStates().next))) - self.tick() - return RTC.RTC_OK - - - -def OpenHRPExecutionContextInit(manager): - OpenRTM_aist.ExecutionContextFactory.instance().addFactory("OpenHRPExecutionContext", - OpenRTM_aist.OpenHRPExecutionContext, - OpenRTM_aist.ECDelete) - OpenRTM_aist.ExecutionContextFactory.instance().addFactory("SynchExtTriggerEC", - OpenRTM_aist.OpenHRPExecutionContext, - OpenRTM_aist.ECDelete) - - return diff --git a/OpenRTM_aist/OutPort.py b/OpenRTM_aist/OutPort.py index 9ec71e30..8b849897 100644 --- a/OpenRTM_aist/OutPort.py +++ b/OpenRTM_aist/OutPort.py @@ -1,5 +1,5 @@ #!/usr/bin/env python -# -*- coding: euc-jp -*- +# -*- coding: utf-8 -*- ## @@ -7,7 +7,7 @@ # @brief OutPort class # @date $Date: 2007/09/19$ # @author Noriaki Ando and Shinji Kurihara -# +# # Copyright (C) 2006-2008 # Noriaki Ando # Task-intelligence Research Group, @@ -17,22 +17,22 @@ # All rights reserved. - from omniORB import any import OpenRTM_aist import threading +import copy ## # @if jp -# @brief ǡ˥ॹפ򥻥åȤ +# @brief データにタイムスタンプをセットする # -# ǡݡȤΥǡФƥॹפ򥻥åȤ롣ǡݡ -# ΥǡϹ¤ΤΥСȤ tm.sec, tm.nsec ɬפ롣 +# データポートのデータに対してタイムスタンプをセットする。データポート +# のデータは構造体のメンバーとして tm.sec, tm.nsec を持つ必要がある。 # -# @param data ॹפ򥻥åȤǡ¹Ը¹ԻΥॹ -# פåȤ +# @param data タイムスタンプをセットするデータ。実行後実行時のタイムス +# タンプがセットされる # # @else # @brief Setting timestamp to data @@ -47,10 +47,10 @@ # template # void setTimestamp(DataType& data) def setTimestamp(data): - # set timestamp - tm = OpenRTM_aist.Time() - data.tm.sec = tm.sec - data.tm.nsec = tm.usec * 1000 + # set timestamp + tm = OpenRTM_aist.Time() + data.tm.sec = tm.sec + data.tm.nsec = tm.usec * 1000 ## @@ -58,287 +58,290 @@ def setTimestamp(data): # # @class OutPort # -# @brief OutPort 饹 -# -# OutPort ѥ饹 +# @brief OutPort クラス +# +# OutPort 用クラス # # @since 0.2.0 # # @else -# +# # @endif class OutPort(OpenRTM_aist.OutPortBase): - """ - """ - - - - ## - # @if jp - # - # @brief 󥹥ȥ饯 - # - # 󥹥ȥ饯 - # - # @param self - # @param name ݡ̾ - # @param value ΥݡȤ˥Хɤǡѿ - # @param buffer_ Хåե - # - # @else - # - # @brief Constructor - # - # @endif - def __init__(self, name, value, buffer=None): - OpenRTM_aist.OutPortBase.__init__(self, name, OpenRTM_aist.toTypename(value)) - self._value = value - #self._timeoutTick = 1000 # timeout tick: 1ms - #self._writeBlock = False - #self._writeTimeout = 0 - self._OnWrite = None - self._OnWriteConvert = None - #self._OnOverflow = None - #self._OnUnderflow = None - #self._OnConnect = None - #self._OnDisconnect = None - self.addConnectorDataListener(OpenRTM_aist.ConnectorDataListenerType.ON_BUFFER_WRITE, OpenRTM_aist.Timestamp("on_write")) - self.addConnectorDataListener(OpenRTM_aist.ConnectorDataListenerType.ON_SEND, OpenRTM_aist.Timestamp("on_send")) - self._directNewData = False - self._valueMutex = threading.RLock() - self._directValue = value - - - - def __del__(self, OutPortBase=OpenRTM_aist.OutPortBase): - OutPortBase.__del__(self) - return - - ## - # @if jp - # - # @brief ǡ񤭹 - # - # ݡȤإǡ񤭹ࡣ - # - # - Хåե󥯥 OnWrite åȤƤ硢 - # OutPort ݻХåե˽񤭹 OnWrite ƤФ롣 - # - OutPort ݻХåեСե򸡽ФǤХåեǤꡢ - # ġ񤭹ݤ˥ХåեСե򸡽Ф硢 - # Хåե󥯥 OnOverflow ƤФ롣 - # - Хåե󥯥 OnWriteConvert åȤƤ硢 - # Хåե񤭹߻ˡ OnWriteConvert operator() ͤ - # Хåե˽񤭹ޤ롣 - # - # @param self - # @param value 񤭹оݥǡ - # - # @return 񤭹߽(񤭹:true񤭹߼:false) - # - # @else - # - # @brief Write data - # - # @endif - # virtual bool write(const DataType& value) - ## - # @if jp - # - # @brief ǡ񤭹 - # - # ݡȤإǡ񤭹ࡣ - # ꤵ줿ͤݡȤ˽񤭹ࡣ - # - # @param self - # @param value 񤭹оݥǡ - # - # @return 񤭹߽(񤭹:true񤭹߼:false) - # - # @else - # - # @endif - # bool operator<<(DataType& value) - def write(self, value=None): - if not value: - value=self._value - - - if self._OnWrite: - self._OnWrite(value) - - # check number of connectors - conn_size = len(self._connectors) - if not conn_size > 0: - return False - - # set timestamp - #tm = Time() - #value.tm.sec = tm.sec - #value.tm.nsec = tm.usec * 1000 - - #tm_pre = Time() - - if self._OnWriteConvert: - value = self._OnWriteConvert(value) - - result = True - - guard = OpenRTM_aist.ScopedLock(self._connector_mutex) - for con in self._connectors: - if not con.directMode(): - ret = con.write(value) - if ret != self.PORT_OK: - result = False - if ret == self.CONNECTION_LOST: - self.disconnect(con.id()) - else: - guard = OpenRTM_aist.ScopedLock(self._valueMutex) + """ + """ + + ## + # @if jp + # + # @brief コンストラクタ + # + # コンストラクタ + # + # @param self + # @param name ポート名 + # @param value このポートにバインドされるデータ変数 + # @param buffer_ バッファ + # + # @else + # + # @brief Constructor + # + # @endif + def __init__(self, name, value, buffer=None): + OpenRTM_aist.OutPortBase.__init__( + self, name, OpenRTM_aist.toTypename(value)) + self._value = value + # self._timeoutTick = 1000 # timeout tick: 1ms + #self._writeBlock = False + #self._writeTimeout = 0 + self._OnWrite = None + self._OnWriteConvert = None + #self._OnOverflow = None + #self._OnUnderflow = None + #self._OnConnect = None + #self._OnDisconnect = None + + marshaling_types = OpenRTM_aist.SerializerFactories.instance().getSerializerList(value) + marshaling_types = OpenRTM_aist.flatten(marshaling_types).lstrip() + self.addProperty("dataport.marshaling_types", marshaling_types) + + self._listeners.setDataType(copy.deepcopy(value)) + self._listeners.setPortType(OpenRTM_aist.PortType.OutPortType) + self.addConnectorDataListener( + OpenRTM_aist.ConnectorDataListenerType.ON_BUFFER_WRITE, + OpenRTM_aist.Timestamp("on_write")) + self.addConnectorDataListener( + OpenRTM_aist.ConnectorDataListenerType.ON_SEND, + OpenRTM_aist.Timestamp("on_send")) + self._directNewData = False + self._valueMutex = threading.RLock() self._directValue = value - self._directNewData = True - del guard - - return result - - - ## - # @if jp - # - # @brief ǡ񤭹߽Υ֥å⡼ɤ - # - # 񤭹߽Фƥ֥å⡼ɤꤹ롣 - # ֥å⡼ɤꤷ硢Хåե˽񤭹ΰ褬Ǥ뤫 - # ॢȤȯޤ write() ᥽åɤθƤӤ֥å롣 - # - # @param self - # @param block ֥å⡼ɥե饰 - # - # @else - # - # @brief Set read() block mode - # - # @endif - #def setWriteBlock(self, block): - # self._writeBlock = block - - - ## - # @if jp - # - # @brief 񤭹߽ΥॢȻ֤ - # - # write() ΥॢȻ֤ usec ꤹ롣 - # write() ϥ֥å⡼ɤǤʤФʤʤ - # - # @param self - # @param timeout ॢȻ [usec] - # - # @else - # - # @brief Set write() timeout - # - # @endif - #def setWriteTimeout(self, timeout): - # self._writeTimeout = timeout - - - ## - # @if jp - # - # @brief OnWrite Хå - # - # ǡ񤭹ľ˸ƤФ OnWrite Хåե󥯥ꤹ롣 - # - # @param self - # @param on_write OnWrite Хåե󥯥 - # - # @else - # - # @brief Set OnWrite callback - # - # @endif - def setOnWrite(self, on_write): - self._OnWrite = on_write - - - ## - # @if jp - # - # @brief OnWriteConvert Хå - # - # ǡ񤭹߻˸ƤФ OnWriteConvert Хåե󥯥 - # 롣 - # ΥХåؿν̤񤭹ޤ롣 - # Τ񤭹ߥǡΥե륿󥰤ǽȤʤ롣 - # - # @param self - # @param on_wconvert OnWriteConvert Хåե󥯥 - # - # @else - # - # @brief Set OnWriteConvert callback - # - # @endif - def setOnWriteConvert(self, on_wconvert): - self._OnWriteConvert = on_wconvert - - - ## - # @if jp - # - # @brief ǡ̾ѥ᥽å - # - # ǡη̾뤿ᡢInPortCorbaProviderƤФ롣 - # - # @param self - # - # @return ХåեꤵƤǡη̾ - # - # @else - # - # @endif - def getPortDataType(self): - val = any.to_any(self._value) - return str(val.typecode().name()) - - - ## - # @if jp - # - # @brief ǡ쥯Ȥɤ߹ - # - # @param self - # @param data ɤ߹ǡ - # - # @else - # @brief - # - # @param self - # @param data - # @endif - # void read(const DataType& data) - def read(self, data): - guard = OpenRTM_aist.ScopedLock(self._valueMutex) - self._directNewData = False - data[0] = self._directValue - if self._OnWriteConvert: - data[0] = self._OnWriteConvert(data[0]) - del guard - def isEmpty(self): - return (not self._directNewData) - - - - class subscribe: - def __init__(self, prof, subs = None): - if subs: - self._prof = subs._prof - self._consumer = subs._consumer - return - self._prof = prof - self._consumer = None - + def __del__(self, OutPortBase=OpenRTM_aist.OutPortBase): + OutPortBase.__del__(self) + return - def __call__(self, cons): - if cons.subscribeInterface(self._prof.properties): - self._consumer = cons + ## + # @if jp + # + # @brief データ書き込み + # + # ポートへデータを書き込む。 + # + # - コールバックファンクタ OnWrite がセットされている場合、 + # OutPort が保持するバッファに書き込む前に OnWrite が呼ばれる。 + # - OutPort が保持するバッファがオーバーフローを検出できるバッファであり、 + # かつ、書き込む際にバッファがオーバーフローを検出した場合、 + # コールバックファンクタ OnOverflow が呼ばれる。 + # - コールバックファンクタ OnWriteConvert がセットされている場合、 + # バッファ書き込み時に、 OnWriteConvert の operator() の戻り値が + # バッファに書き込まれる。 + # + # @param self + # @param value 書き込み対象データ + # + # @return 書き込み処理結果(書き込み成功:true、書き込み失敗:false) + # + # @else + # + # @brief Write data + # + # @endif + # virtual bool write(const DataType& value) + ## + # @if jp + # + # @brief データ書き込み + # + # ポートへデータを書き込む。 + # 設定された値をポートに書き込む。 + # + # @param self + # @param value 書き込み対象データ + # + # @return 書き込み処理結果(書き込み成功:true、書き込み失敗:false) + # + # @else + # + # @endif + # bool operator<<(DataType& value) + def write(self, value=None): + if not value: + value = self._value + + if self._OnWrite: + self._OnWrite(value) + + # check number of connectors + if not self._connectors: + return False + + # set timestamp + #tm = Time() + #value.tm.sec = tm.sec + #value.tm.nsec = tm.usec * 1000 + + #tm_pre = Time() + + if self._OnWriteConvert: + value = self._OnWriteConvert(value) + + result = True + + guard = OpenRTM_aist.ScopedLock(self._connector_mutex) + for con in self._connectors: + if not con.directMode(): + ret = con.write(value) + if ret != self.PORT_OK: + result = False + if ret == self.CONNECTION_LOST: + self.disconnect(con.id()) + else: + guard = OpenRTM_aist.ScopedLock(self._valueMutex) + self._directValue = value + self._directNewData = True + del guard + + return result + + ## + # @if jp + # + # @brief データ書き込み処理のブロックモードの設定 + # + # 書き込み処理に対してブロックモードを設定する。 + # ブロックモードを指定した場合、バッファに書き込む領域ができるか + # タイムアウトが発生するまで write() メソッドの呼びだしがブロックされる。 + # + # @param self + # @param block ブロックモードフラグ + # + # @else + # + # @brief Set read() block mode + # + # @endif + # def setWriteBlock(self, block): + # self._writeBlock = block + + ## + # @if jp + # + # @brief 書き込み処理のタイムアウト時間の設定 + # + # write() のタイムアウト時間を usec で設定する。 + # write() はブロックモードでなければならない。 + # + # @param self + # @param timeout タイムアウト時間 [usec] + # + # @else + # + # @brief Set write() timeout + # + # @endif + # def setWriteTimeout(self, timeout): + # self._writeTimeout = timeout + + ## + # @if jp + # + # @brief OnWrite コールバックの設定 + # + # データ書き込み直前に呼ばれる OnWrite コールバックファンクタを設定する。 + # + # @param self + # @param on_write OnWrite コールバックファンクタ + # + # @else + # + # @brief Set OnWrite callback + # + # @endif + + def setOnWrite(self, on_write): + self._OnWrite = on_write + + ## + # @if jp + # + # @brief OnWriteConvert コールバックの設定 + # + # データ書き込み時に呼ばれる OnWriteConvert コールバックファンクタを設定 + # する。 + # このコールバック関数の処理結果が書き込まれる。 + # このため書き込みデータのフィルタリングが可能となる。 + # + # @param self + # @param on_wconvert OnWriteConvert コールバックファンクタ + # + # @else + # + # @brief Set OnWriteConvert callback + # + # @endif + + def setOnWriteConvert(self, on_wconvert): + self._OnWriteConvert = on_wconvert + + ## + # @if jp + # + # @brief データ型名取得用メソッド + # + # データの型名を取得するため、InPortCorbaProviderから呼ばれる。 + # + # @param self + # + # @return バッファに設定されているデータの型名 + # + # @else + # + # @endif + + def getPortDataType(self): + val = any.to_any(self._value) + return str(val.typecode().name()) + + ## + # @if jp + # + # @brief データをダイレクトに読み込む + # + # @param self + # @return 読み込んだデータ + # + # @else + # @brief + # + # @param self + # @return + # @endif + # void read(const DataType& data) + + def read(self): + guard = OpenRTM_aist.ScopedLock(self._valueMutex) + self._directNewData = False + data = self._directValue + if self._OnWriteConvert: + data = self._OnWriteConvert(data) + del guard + return data + + def isEmpty(self): + return (not self._directNewData) + + class subscribe: + def __init__(self, prof, subs=None): + if subs: + self._prof = subs._prof + self._consumer = subs._consumer + return + + self._prof = prof + self._consumer = None + + def __call__(self, cons): + if cons.subscribeInterface(self._prof.properties): + self._consumer = cons diff --git a/OpenRTM_aist/OutPortBase.py b/OpenRTM_aist/OutPortBase.py index 2a04300f..d8682c07 100644 --- a/OpenRTM_aist/OutPortBase.py +++ b/OpenRTM_aist/OutPortBase.py @@ -1,12 +1,12 @@ #!/usr/bin/env python -# -*- coding: euc-jp -*- +# -*- coding: utf-8 -*- ## # @file OutPortBase.py # @brief OutPortBase base class # @date $Date: 2007/09/19 $ # @author Noriaki Ando and Shinji Kurihara -# +# # Copyright (C) 2003-2008 # Task-intelligence Research Group, # Intelligent Systems Research Institute, @@ -25,24 +25,24 @@ # # @class OutPortBase # -# @brief OutPort 쥯饹 -# -# OutPort δ쥯饹 +# @brief OutPort 基底クラス +# +# OutPort の基底クラス。 # # # # Properties: port.outport -# ץѥƥ +# プロパティは # # - port.outport # - port.outport.[name] -# ConnectorProfile.properties ξ +# ConnectorProfile.properties の場合は # - dataport.outport # -# ʲ˻ꤷΤϤ롣 -# (port.outport.[name]ͥ褵) -# ˡΥץѥƥ³ ConnectorProfile ˤ -# Ϥ礬ꡢξ ConnectorProfile ͥ褵롣 +# 以下に指定したものが渡される。 +# (port.outport.[name]が優先される) +# さらに、一部のプロパティは接続時に ConnectorProfile により +# 渡される場合があり、その場合は ConnectorProfile が優先される。 # # - input.throughput.profile: enable # - input.throughput.update_rate: count [n/count] @@ -72,60 +72,60 @@ # [buffer] # # - buffer.type: -# ѲǽʥХåեΥ -# ConnectorProfile ξѤХåեΥ -# ̵ξϥǥեȤ ringbuffer Ѥ롣 +# 利用可能なバッファのタイプ +# ConnectorProfile の場合は利用するバッファのタイプ +# 無指定の場合はデフォルトの ringbuffer が使用される。 # ex. ringbuffer, shmbuffer, doublebuffer, etc. -# Consumer, Publisher ΥפˤäƤΥХåե -# ׵᤹뤬뤿Ρξϻ̵Ȥʤ롣 +# 正し、Consumer, Publisher のタイプによっては特定のバッファ型を +# 要求するがあるための、その場合は指定は無効となる。 # # - buffer.length: -# ХåեĹ +# バッファの長さ # # - buffer.write.full_policy: -# 񤭤뤫ɤΥݥꥷ -# overwrite (), do_nothing (⤷ʤ), block (֥å) -# block ꤷ硢 timeout ͤꤹСָ -# 񤭹ԲǽǤХॢȤ롣 +# 上書きするかどうかのポリシー +# overwrite (上書き), do_nothing (何もしない), block (ブロックする) +# block を指定した場合、次の timeout 値を指定すれば、指定時間後 +# 書き込み不可能であればタイムアウトする。 # # - buffer.write.timeout: -# ॢȻ֤ [sec] ǻꤹ롣 -# 1 sec -> 1.0, 1 ms -> 0.001, ॢȤʤ -> 0.0 +# タイムアウト時間を [sec] で指定する。 +# 1 sec -> 1.0, 1 ms -> 0.001, タイムアウトしない -> 0.0 # # - buffer.read.empty_policy: -# ХåեΤȤɤ߽Фݥꥷ -# last (Ǹ), do_nothing (⤷ʤ), block (֥å) -# block ꤷ硢 timeout ͤꤹСָ -# ɤ߽ФԲǽǤХॢȤ롣 +# バッファが空のときの読み出しポリシー +# last (最後の要素), do_nothing (何もしない), block (ブロックする) +# block を指定した場合、次の timeout 値を指定すれば、指定時間後 +# 読み出し不可能であればタイムアウトする。 # # - buffer.read.timeout: -# ॢȻ [sec] ǻꤹ롣 -# 1sec -> 1.0, 1ms -> 0.001, ॢȤʤ -> 0.0 +# タイムアウト時間 [sec] で指定する。 +# 1sec -> 1.0, 1ms -> 0.001, タイムアウトしない -> 0.0 # -# - ¾Хåե˸ͭʥץ +# - その他バッファ毎に固有なオプション # # # [publihser] # # - publisher.types: -# Ѳǽ Publisher Υ +# 利用可能な Publisher のタイプ # new, periodic, flush, etc.. # # - publisher.push.policy: -# InPortإǡݥꥷ -# all: ХåեˤޤäƤ뤹٤ -# fifo: ХåեFIFOȤߤʤ -# skip: Ťǡְ -# new: ˿ǡΤߤ +# InPortへデータを送信するポリシー +# all: バッファにたまっているすべて送信 +# fifo: バッファをFIFOとみなして送信 +# skip: 古いデータから一定数を間引いて送信 +# new: 常に新しいデータのみを送信 # # - publisher.push.skip_rate: -# push.policy=skip ΤȤΥåΨ -# n: nˤҤȤ +# push.policy=skip のときのスキップ率 +# n: n要素毎にひとつ送信 # # - publisher.periodic.rate: # # - publisher.thread.type: -# Publisher ΥåɤΥ +# Publisher のスレッドのタイプ # - publisher.thread.measurement.exec_time: yes/no # - publisher.thread.measurement.exec_count: number # - publisher.thread.measurement.period_time: yes/no @@ -134,57 +134,57 @@ # [interface] # # - interface.types: -# OutPort interfaceΥ -# ex. corba_cdr, corba_any, raw_tcp ʤɥ޶ڤǻꡣ -# ꤷʤѲǽʤ٤ƤΥץХѤ +# OutPort interfaceのタイプ +# ex. corba_cdr, corba_any, raw_tcp などカンマ区切りで指定。何も +# 指定しなければ利用可能なすべてのプロバイダが使用される # # # -# -# OutPort ¦ connect() ǤϰʲΥ󥹤ǽԤ롣 # -# 1. OutPort ˴Ϣ connector ӥå +# OutPort 側の connect() では以下のシーケンスで処理が行われる。 # -# 2. InPort˴Ϣ connector μ -# - ConnectorProfile::properties["dataport.corba_any.inport_ref"] -# OutPortAny Υ֥ȥե󥹤ꤵƤ硢 -# ե󥹤Consumer֥Ȥ˥åȤ롣 -# ե󥹤åȤƤʤ̵뤷Ʒ³ -# (OutPortconnect() ƤӽФΥȥݥȤξϡ -# InPortΥ֥ȥե󥹤ϥåȤƤʤϤǤ롣) -# 3. PortBase::connect() 򥳡 -# Port³δܽԤ롣 -# 4. 嵭2.InPortΥե󥹤ǤʤСInPort -# Ϣ connector 롣 +# 1. OutPort に関連する connector 情報の生成およびセット # -# 5. ConnectorProfile::properties Ϳ줿󤫤顢 -# OutPort¦νԤ +# 2. InPortに関連する connector 情報の取得 +# - ConnectorProfile::properties["dataport.corba_any.inport_ref"]に +# OutPortAny のオブジェクトリファレンスが設定されている場合、 +# リファレンスを取得してConsumerオブジェクトにセットする。 +# リファレンスがセットされていなければ無視して継続。 +# (OutPortがconnect() 呼び出しのエントリポイントの場合は、 +# InPortのオブジェクトリファレンスはセットされていないはずである。) +# 3. PortBase::connect() をコール +# Portの接続の基本処理が行われる。 +# 4. 上記2.でInPortのリファレンスが取得できなければ、再度InPortに +# 関連する connector 情報を取得する。 +# +# 5. ConnectorProfile::properties で与えられた情報から、 +# OutPort側の初期化処理を行う。 # # - [dataport.interface_type] -# -- CORBA_Any ξ: -# InPortAny ̤ƥǡ򴹤롣 -# ConnectorProfile::properties["dataport.corba_any.inport_ref"] -# InPortAny Υ֥ȥե󥹤򥻥åȤ롣 -# -- RawTCP ξ: Raw TCP socket ̤ƥǡ򴹤롣 +# -- CORBA_Any の場合: +# InPortAny を通してデータ交換される。 +# ConnectorProfile::properties["dataport.corba_any.inport_ref"]に +# InPortAny のオブジェクトリファレンスをセットする。 +# -- RawTCP の場合: Raw TCP socket を通してデータ交換される。 # ConnectorProfile::properties["dataport.raw_tcp.server_addr"] -# InPort¦ΥХɥ쥹򥻥åȤ롣 +# にInPort側のサーバアドレスをセットする。 # # - [dataport.dataflow_type] -# -- Pushξ: Subscriber롣SubscriberΥפϡ -# dataport.subscription_type ꤵƤ롣 -# -- Pullξ: InPort¦ǡPullǼ뤿ᡢ -# ä˲⤹ɬפ̵ +# -- Pushの場合: Subscriberを生成する。Subscriberのタイプは、 +# dataport.subscription_type に設定されている。 +# -- Pullの場合: InPort側がデータをPull型で取得するため、 +# 特に何もする必要が無い。 # # - [dataport.subscription_type] -# -- Onceξ: SubscriberOnce롣 -# -- Newξ: SubscriberNew롣 -# -- Periodicξ: SubscriberPeriodic롣 +# -- Onceの場合: SubscriberOnceを生成する。 +# -- Newの場合: SubscriberNewを生成する。 +# -- Periodicの場合: SubscriberPeriodicを生成する。 # # - [dataport.push_interval] -# -- dataport.subscription_type=Periodicξꤹ롣 +# -- dataport.subscription_type=Periodicの場合周期を設定する。 # -# 6. 嵭νΤĤǤ⥨顼ǤС顼꥿󤹤롣 -# ˽Ԥ줿RTC::RTC_OKǥ꥿󤹤롣 +# 6. 上記の処理のうち一つでもエラーであれば、エラーリターンする。 +# 正常に処理が行われた場合はRTC::RTC_OKでリターンする。 # # @since 0.2.0 # @@ -204,1153 +204,1278 @@ # # @endif # -class OutPortBase(OpenRTM_aist.PortBase,OpenRTM_aist.DataPortStatus): - """ - """ - - ## - # @if jp - # @brief Provider 뤿 Functor - # @else - # @brief Functor to delete Providers - # @endif - # - class provider_cleanup: - def __init__(self): - self._factory = OpenRTM_aist.OutPortProviderFactory.instance() - - def __call__(self, p): - self._factory.deleteObject(p) - - ## - # @if jp - # @brief Connector 뤿 Functor - # @else - # @brief Functor to delete Connectors - # @endif - # - class connector_cleanup: - def __init__(self): - pass - - def __call__(self, c): - del c - - - ## - # @if jp - # @brief 󥹥ȥ饯 - # - # 󥹥ȥ饯 - # - # @param self - # @param name ݡ̾ - # - # @else - # - # @brief A constructor of OutPortBase class. - # - # Constructor of OutPortBase. - # - # @endif - # OutPortBase::OutPortBase(const char* name, const char* data_type) - def __init__(self, name, data_type): - OpenRTM_aist.PortBase.__init__(self,name) - self._rtcout.RTC_DEBUG("Port name: %s", name) - - self._rtcout.RTC_DEBUG("setting port.port_type: DataOutPort") - self.addProperty("port.port_type", "DataOutPort") - - self._rtcout.RTC_DEBUG("setting dataport.data_type: %s", data_type) - self.addProperty("dataport.data_type", data_type) - - # publisher list - factory = OpenRTM_aist.PublisherFactory.instance() - pubs = OpenRTM_aist.flatten(factory.getIdentifiers()) - - # blank characters are deleted for RTSE's bug - pubs = pubs.lstrip() - - self._rtcout.RTC_DEBUG("available subscription_type: %s", pubs) - self.addProperty("dataport.subscription_type", pubs) - self.addProperty("dataport.io_mode", pubs) - - self._properties = OpenRTM_aist.Properties() - self._name = name - self._connectors = [] - self._consumers = [] - self._providerTypes = "" - self._consumerTypes = "" - self._connector_mutex = threading.RLock() - - self._listeners = OpenRTM_aist.ConnectorListeners() - return - - - ## - # @if jp - # @brief ǥȥ饯 - # - # ǥȥ饯 - # Ͽ줿Ƥ Publisher 롣 - # - # @param self - # - # @else - # - # @brief destructor - # - # Destructor - # - # @endif - def __del__(self, PortBase=OpenRTM_aist.PortBase): - self._rtcout.RTC_TRACE("OutPortBase destructor") - # connector Υ꡼ʥå - OpenRTM_aist.CORBA_SeqUtil.for_each(self._connectors, - self.connector_cleanup()) - PortBase.__del__(self) - return - - - ## - # @if jp - # @brief ץѥƥν - # - # OutPortΥץѥƥ - # - # @else - # - # @brief Initializing properties - # - # This operation initializes outport's properties - # - # @endif - # - # void init(coil::Properties& prop); - def init(self, prop): - self._rtcout.RTC_TRACE("init()") - - self._properties.mergeProperties(prop) - - self.configure() - - self.initConsumers() - self.initProviders() - - num = [-1] - if not OpenRTM_aist.stringTo(num, self._properties.getProperty("connection_limit","-1")): - self._rtcout.RTC_ERROR("invalid connection_limit value: %s", - self._properties.getProperty("connection_limit")) - - self.setConnectionLimit(num[0]) - return - - ## - # @if jp - # - # @brief ǡ񤭹 - # - # ݡȤإǡ񤭹ࡣ - # Хɤ줿ѿꤵ줿ͤݡȤ˽񤭹ࡣ - # - # @return 񤭹߽(񤭹:true񤭹߼:false) - # - # @else - # - # @brief Write data - # - # Write data to the port. - # Write the value, which was set to the bound variable, to the port. - # - # @return Writing result (Successful:true, Failed:false) - # - # @endif - # - # virtual bool write() = 0; - def write(self): - pass - - - ## - # @if jp - # - # @brief [CORBA interface] Port ³Ԥ - # - # Ϳ줿 ConnectoionProfile ξ˴ŤPort֤³Ω - # 롣δؿϼ˥ץꥱץġ뤫Ƥӽ - # ȤȤƤ롣 - # - # @param connector_profile ConnectorProfile - # @return ReturnCode_t Υ꥿󥳡 - # - # @else - # - # @brief [CORBA interface] Connect the Port - # - # This operation establishes connection according to the given - # ConnectionProfile inforamtion. This function is premised on - # calling from mainly application program or tools. - # - # @param connector_profile The ConnectorProfile. - # @return ReturnCode_t The return code of ReturnCode_t type. - # - # @endif - # - def connect(self, connector_profile): - self._rtcout.RTC_TRACE("OutPortBase.connect()") - - - - - - if OpenRTM_aist.NVUtil.find_index(connector_profile.properties, - "dataport.serializer.cdr.endian") is -1: - self._rtcout.RTC_TRACE("ConnectorProfile dataport.serializer.cdr.endian set.") - connector_profile.properties.append(OpenRTM_aist.NVUtil.newNV("dataport.serializer.cdr.endian","little,big")) - - return OpenRTM_aist.PortBase.connect(self, connector_profile) - - - - ## - # @if jp - # - # @brief - # - # @param self - # @param connector_profile - # @return - # - # @else - # - # @brief - # - # @param self - # @param connector_profile - # @return - # - # @endif - # - def notify_connect(self, connector_profile): - prop = OpenRTM_aist.Properties() - OpenRTM_aist.NVUtil.copyToProperties(prop, connector_profile.properties) - - - node = prop.getNode("dataport.outport") - portprop = copy.deepcopy(self._properties) - portprop.mergeProperties(node) - node.mergeProperties(portprop) - OpenRTM_aist.NVUtil.copyFromProperties(connector_profile.properties, prop) - - - _str = node.getProperty("fan_out") - _type = [int(100)] - - OpenRTM_aist.stringTo(_type, _str) - - - - _str = prop.getProperty("dataport.fan_out") - OpenRTM_aist.stringTo(_type, _str) - - value = _type[0] - - if value <= len(self._connectors): - return (RTC.PRECONDITION_NOT_MET, connector_profile) - - - return OpenRTM_aist.PortBase.notify_connect(self, connector_profile) - - ## - # @if jp - # @brief ץѥƥ - # - # OutPortΥץѥƥ롣 - # - # @return ץѥƥ - # - # @else - # - # @brief Get properties - # - # Getting properties of this OutPort - # - # @return OutPort's properties - # - # @endif - # - # coil::Properties& OutPortBase::properties() - def properties(self): - self._rtcout.RTC_TRACE("properties()") - return self._properties - - - ## - # @if jp - # @brief Connector - # @else - # @brief Connector list - # @endif - # - # const std::vector& OutPortBase::connectors() - def connectors(self): - self._rtcout.RTC_TRACE("connectors(): size = %d", len(self._connectors)) - return self._connectors - - - ## - # @if jp - # @brief ConnectorProfile - # @else - # @brief ConnectorProfile list - # @endif - # - # ConnectorBase::ConnectorInfoList OutPortBase::getConnectorProfiles() - def getConnectorProfiles(self): - self._rtcout.RTC_TRACE("getConnectorProfiles(): size = %d", len(self._connectors)) - profs = [] - for con in self._connectors: - profs.append(con.profile()) - - return profs - - - ## - # @if jp - # @brief ConnectorId - # @else - # @brief ConnectorId list - # @endif - # - # coil::vstring OutPortBase::getConnectorIds() - def getConnectorIds(self): - ids = [] - - for con in self._connectors: - ids.append(con.id()) - - self._rtcout.RTC_TRACE("getConnectorIds(): %s", OpenRTM_aist.flatten(ids)) - return ids - - - ## - # @if jp - # @brief Connector̾ - # @else - # @brief Connector name list - # @endif - # - # coil::vstring OutPortBase::getConnectorNames() - def getConnectorNames(self): - names = [] - for con in self._connectors: - names.append(con.name()) - - self._rtcout.RTC_TRACE("getConnectorNames(): %s", OpenRTM_aist.flatten(names)) - return names - - - ## - # @if jp - # @brief ConnectorProfileIDǼ - # - # ߽ͭƤ륳ͥIDǼ롣 - # - # @param id Connector ID - # @return ͥؤΥݥ - # - # @else - # - # @brief Getting ConnectorProfile by ID - # - # This operation returns Connector specified by ID. - # - # @param id Connector ID - # @return A pointer to connector - # - # @endif - # - # OutPortConnector* getConnectorById(const char* id); - def getConnectorById(self, id): - self._rtcout.RTC_TRACE("getConnectorById(id = %s)", id) - - for (i,con) in enumerate(self._connectors): - if id == con.id(): - return self._connectors[i] - - self._rtcout.RTC_WARN("ConnectorProfile with the id(%s) not found.", id) - return None - - ## - # @if jp - # @brief ConnectorProfile̾Ǽ - # - # ߽ͭƤ륳ͥ̾Ǽ롣 - # - # @param name Connector name - # @return ͥؤΥݥ - # - # @else - # - # @brief Getting Connector by name - # - # This operation returns Connector specified by name. - # - # @param id Connector ID - # @return A pointer to connector - # - # @endif - # - # OutPortConnector* getConnectorByName(const char* name); - def getConnectorByName(self, name): - self._rtcout.RTC_TRACE("getConnectorByName(name = %s)", name) - - for (i,con) in enumerate(self._connectors): - if name == con.name(): - return self._connectors[i] - - self._rtcout.RTC_WARN("ConnectorProfile with the name(%s) not found.", name) - return None - - - ## - # @if jp - # @brief ConnectorProfileIDǼ - # @else - # @brief Getting ConnectorProfile by name - # @endif - # - # bool OutPortBase::getConnectorProfileById(const char* id, - # ConnectorInfo& prof) - def getConnectorProfileById(self, id, prof): - self._rtcout.RTC_TRACE("getConnectorProfileById(id = %s)", id) - - conn = self.getConnectorById(id) - - if not conn: - return False - - prof[0] = conn.profile() - return True - - - ## - # @if jp - # @brief ConnectorProfile̾Ǽ - # @else - # @brief Getting ConnectorProfile by name - # @endif - # - # bool OutPortBase::getConnectorProfileByName(const char* name, - # ConnectorInfo& prof) - def getConnectorProfileByName(self, name, prof): - self._rtcout.RTC_TRACE("getConnectorProfileByName(name = %s)", name) - - conn = self.getConnectorByName(name) - - if not conn: - return False - - prof[0] = conn.profile() - return True - - - ## - # @if jp - # @brief OutPort activates - # @else - # @brief Activate all Port interfaces - # @endif - # - # void OutPortBase::activateInterfaces() - def activateInterfaces(self): - self._rtcout.RTC_TRACE("activateInterfaces()") - for con in self._connectors: - con.activate() - - - ## - # @if jp - # @brief Ƥ Port Υ󥿡ե deactivates - # @else - # @brief Deactivate all Port interfaces - # @endif - # - # void OutPortBase::deactivateInterfaces() - def deactivateInterfaces(self): - self._rtcout.RTC_TRACE("deactivateInterfaces()") - for con in self._connectors: - con.deactivate() - - - ## - # @if jp - # @brief ConnectorDataListener ꥹʤɲä - # - # Хåե񤭹ߤޤɤ߽Ф٥Ȥ˴ϢƼꥹʤꤹ롣 - # - # ǤꥹʤΥפȥХå٥Ȥϰʲ̤ - # - # - ON_BUFFER_WRITE: Хåե񤭹߻ - # - ON_BUFFER_FULL: Хåեե - # - ON_BUFFER_WRITE_TIMEOUT: Хåե񤭹ߥॢȻ - # - ON_BUFFER_OVERWRITE: Хåե񤭻 - # - ON_BUFFER_READ: Хåեɤ߽Ф - # - ON_SEND: InProtؤ - # - ON_RECEIVED: InProtؤλ - # - ON_SEND_ERTIMEOUT: OutPort¦ॢȻ - # - ON_SEND_ERERROR: OutPort¦顼 - # - ON_RECEIVER_FULL: InProt¦Хåեե - # - ON_RECEIVER_TIMEOUT: InProt¦ХåեॢȻ - # - ON_RECEIVER_ERROR: InProt¦顼 - # - # ꥹʤ ConnectorDataListener ѾʲΥ˥ - # operator() Ƥɬפ롣 - # - # ConnectorDataListener:: - # operator()(const ConnectorProfile&, const cdrStream&) - # - # ǥեȤǤϡδؿͿꥹʥ֥Ȥνͭ - # OutPort˰ܤꡢOutPortλ⤷ϡ - # removeConnectorDataListener() ˤ˼ưŪ˲Τ롣 - # ꥹʥ֥ȤνͭƤӽФ¦ǰݻϡ3 - # false ꤷưŪʲΤ뤳ȤǤ롣 - # - # @param listener_type ꥹʥ - # @param listener ꥹʥ֥ȤؤΥݥ - # @param autoclean ꥹʥ֥ȤμưŪΤԤɤΥե饰 - # - # @else - # @brief Adding BufferDataListener type listener - # - # This operation adds certain listeners related to buffer writing and - # reading events. - # The following listener types are available. - # - # - ON_BUFFER_WRITE: At the time of buffer write - # - ON_BUFFER_FULL: At the time of buffer full - # - ON_BUFFER_WRITE_TIMEOUT: At the time of buffer write timeout - # - ON_BUFFER_OVERWRITE: At the time of buffer overwrite - # - ON_BUFFER_READ: At the time of buffer read - # - ON_SEND: At the time of sending to InPort - # - ON_RECEIVED: At the time of finishing sending to InPort - # - ON_SENDER_TIMEOUT: At the time of timeout of OutPort - # - ON_SENDER_ERROR: At the time of error of OutPort - # - ON_RECEIVER_FULL: At the time of bufferfull of InPort - # - ON_RECEIVER_TIMEOUT: At the time of timeout of InPort - # - ON_RECEIVER_ERROR: At the time of error of InPort - # - # Listeners should have the following function operator(). - # - # ConnectorDataListener:: - # operator()(const ConnectorProfile&, const cdrStream&) - # - # The ownership of the given listener object is transferred to - # this OutPort object in default. The given listener object will - # be destroied automatically in the OutPort's dtor or if the - # listener is deleted by removeConnectorDataListener() function. - # If you want to keep ownership of the listener object, give - # "false" value to 3rd argument to inhibit automatic destruction. - # - # @param listener_type A listener type - # @param listener A pointer to a listener object - # @param autoclean A flag for automatic listener destruction - # - # @endif - # - # void addConnectorDataListener(ConnectorDataListenerType listener_type, - # ConnectorDataListener* listener, - # bool autoclean = true); - def addConnectorDataListener(self, listener_type, listener, autoclean = True): - self._rtcout.RTC_TRACE("addConnectorDataListener()") - if listener_type < OpenRTM_aist.ConnectorDataListenerType.CONNECTOR_DATA_LISTENER_NUM: - self._rtcout.RTC_TRACE("addConnectorDataListener(%s)", - OpenRTM_aist.ConnectorDataListener.toString(listener_type)) - self._listeners.connectorData_[listener_type].addListener(listener, autoclean) - return - - self._rtcout.RTC_ERROR("addConnectorDataListener(): Unknown Listener Type") - return - - - ## - # @if jp - # @brief ConnectorDataListener ꥹʤ - # - # ꤷƼꥹʤ롣 - # - # @param listener_type ꥹʥ - # @param listener ꥹʥ֥ȤؤΥݥ - # - # @else - # @brief Removing BufferDataListener type listener - # - # This operation removes a specified listener. - # - # @param listener_type A listener type - # @param listener A pointer to a listener object - # - # @endif - # - # void removeConnectorDataListener(ConnectorDataListenerType listener_type, - # ConnectorDataListener* listener); - def removeConnectorDataListener(self, listener_type, listener): - self._rtcout.RTC_TRACE("removeConnectorDataListener()") - - if listener_type < OpenRTM_aist.ConnectorDataListenerType.CONNECTOR_DATA_LISTENER_NUM: - self._rtcout.RTC_TRACE("removeConnectorDataListener(%s)", - OpenRTM_aist.ConnectorDataListener.toString(listener_type)) - self._listeners.connectorData_[listener_type].removeListener(listener) - return - - self._rtcout.RTC_ERROR("removeConnectorDataListener(): Unknown Listener Type") - return - - - ## - # @if jp - # @brief ConnectorListener ꥹʤɲä - # - # Хåե񤭹ߤޤɤ߽Ф٥Ȥ˴ϢƼꥹʤꤹ롣 - # - # ǤꥹʤΥפ - # - # - ON_BUFFER_EMPTY: Хåեξ - # - ON_BUFFER_READTIMEOUT: ХåեǥॢȤ - # - # ꥹʤϰʲΥ˥ operator() Ƥɬפ롣 - # - # ConnectorListener::operator()(const ConnectorProfile&) - # - # ǥեȤǤϡδؿͿꥹʥ֥Ȥνͭ - # OutPort˰ܤꡢOutPortλ⤷ϡ - # removeConnectorListener() ˤ˼ưŪ˲Τ롣 - # ꥹʥ֥ȤνͭƤӽФ¦ǰݻϡ3 - # false ꤷưŪʲΤ뤳ȤǤ롣 - # - # @param listener_type ꥹʥ - # @param listener ꥹʥ֥ȤؤΥݥ - # @param autoclean ꥹʥ֥ȤμưŪΤԤɤΥե饰 - # - # @else - # @brief Adding ConnectorListener type listener - # - # This operation adds certain listeners related to buffer writing and - # reading events. - # The following listener types are available. - # - # - ON_BUFFER_EMPTY: At the time of buffer empty - # - ON_BUFFER_READTIMEOUT: At the time of buffer read timeout - # - # Listeners should have the following function operator(). - # - # ConnectorListener::operator()(const ConnectorProfile&) - # - # The ownership of the given listener object is transferred to - # this OutPort object in default. The given listener object will - # be destroied automatically in the OutPort's dtor or if the - # listener is deleted by removeConnectorListener() function. - # If you want to keep ownership of the listener object, give - # "false" value to 3rd argument to inhibit automatic destruction. - # - # @param listener_type A listener type - # @param listener A pointer to a listener object - # @param autoclean A flag for automatic listener destruction - # - # @endif - # - # void addConnectorListener(ConnectorListenerType callback_type, - # ConnectorListener* listener, - # bool autoclean = true); - def addConnectorListener(self, callback_type, listener, autoclean = True): - self._rtcout.RTC_TRACE("addConnectorListener()") - - if callback_type < OpenRTM_aist.ConnectorListenerType.CONNECTOR_LISTENER_NUM: - self._rtcout.RTC_TRACE("addConnectorListener(%s)", - OpenRTM_aist.ConnectorListener.toString(callback_type)) - self._listeners.connector_[callback_type].addListener(listener, autoclean) - return - self._rtcout.RTC_ERROR("addConnectorListener(): Unknown Listener Type") - return - - - ## - # @if jp - # @brief ConnectorDataListener ꥹʤ - # - # ꤷƼꥹʤ롣 - # - # @param listener_type ꥹʥ - # @param listener ꥹʥ֥ȤؤΥݥ - # - # @else - # @brief Removing BufferDataListener type listener - # - # This operation removes a specified listener. - # - # @param listener_type A listener type - # @param listener A pointer to a listener object - # - # @endif - # - # void removeConnectorListener(ConnectorListenerType callback_type, - # ConnectorListener* listener); - def removeConnectorListener(self, callback_type, listener): - self._rtcout.RTC_TRACE("removeConnectorListener()") - - if callback_type < OpenRTM_aist.ConnectorListenerType.CONNECTOR_LISTENER_NUM: - self._rtcout.RTC_TRACE("removeConnectorListener(%s)", - OpenRTM_aist.ConnectorListener.toString(callback_type)) - self._listeners.connector_[callback_type].removeListener(listener) - return - self._rtcout.RTC_ERROR("removeConnectorListener(): Unknown Listener Type") - return - - - ## - # @if jp - # @brief OutPortԤ - # @else - # @brief Configureing outport - # @endif - # - #void OutPortBase::configure() - def configure(self): - pass - - - ## - # @if jp - # @brief Interface - # @else - # @brief Publish interface information - # @endif - # - # ReturnCode_t OutPortBase::publishInterfaces(ConnectorProfile& cprof) - def publishInterfaces(self, cprof): - self._rtcout.RTC_TRACE("publishInterfaces()") - - retval = self._publishInterfaces() - if retval != RTC.RTC_OK: - return retval - - # prop: [port.outport]. - prop = copy.deepcopy(self._properties) - - conn_prop = OpenRTM_aist.Properties() - - OpenRTM_aist.NVUtil.copyToProperties(conn_prop, cprof.properties) - prop.mergeProperties(conn_prop.getNode("dataport")) # marge ConnectorProfile + +class OutPortBase(OpenRTM_aist.PortBase, OpenRTM_aist.DataPortStatus): """ + """ + + ## + # @if jp + # @brief Connector を削除するための Functor + # @else + # @brief Functor to delete Connectors + # @endif + # + class connector_cleanup: + def __init__(self): + pass + + def __call__(self, c): + del c + + ## + # @if jp + # @brief コンストラクタ + # + # コンストラクタ。 + # + # @param self + # @param name ポート名 + # + # @else + # + # @brief A constructor of OutPortBase class. + # + # Constructor of OutPortBase. + # + # @endif + # OutPortBase::OutPortBase(const char* name, const char* data_type) + + def __init__(self, name, data_type): + OpenRTM_aist.PortBase.__init__(self, name) + self._rtcout.RTC_DEBUG("Port name: %s", name) + + self._rtcout.RTC_DEBUG("setting port.port_type: DataOutPort") + self.addProperty("port.port_type", "DataOutPort") + + self._rtcout.RTC_DEBUG("setting dataport.data_type: %s", data_type) + self.addProperty("dataport.data_type", data_type) + + # publisher list + factory = OpenRTM_aist.PublisherFactory.instance() + pubs = OpenRTM_aist.flatten(factory.getIdentifiers()) + + # blank characters are deleted for RTSE's bug + pubs = pubs.lstrip() + + self._rtcout.RTC_DEBUG("available subscription_type: %s", pubs) + self.addProperty("dataport.subscription_type", pubs) + self.addProperty("dataport.io_mode", pubs) + self._value = None + + self._properties = OpenRTM_aist.Properties() + self._name = name + self._connectors = [] + self._consumers = [] + self._providerTypes = "" + self._consumerTypes = "" + self._connector_mutex = threading.RLock() + + self._properties.setProperty("data_type", data_type) + + self._listeners = OpenRTM_aist.ConnectorListeners() + return + + ## + # @if jp + # @brief デストラクタ + # + # デストラクタ。 + # 登録された全ての Publisher を削除する。 + # + # @param self + # + # @else + # + # @brief destructor + # + # Destructor + # + # @endif + + def __del__(self, PortBase=OpenRTM_aist.PortBase): + self._rtcout.RTC_TRACE("OutPortBase destructor") + # connector のクリーンナップ + OpenRTM_aist.CORBA_SeqUtil.for_each(self._connectors, + self.connector_cleanup()) + PortBase.__del__(self) + return + + ## + # @if jp + # @brief プロパティの初期化 + # + # OutPortのプロパティを初期化する + # + # @else + # + # @brief Initializing properties + # + # This operation initializes outport's properties + # + # @endif + # + # void init(coil::Properties& prop); + + def init(self, prop): + self._rtcout.RTC_TRACE("init()") + + self._properties.mergeProperties(prop) + prop_list = [] + OpenRTM_aist.NVUtil.copyFromProperties(prop_list, self._properties) + self._profile.properties.extend(prop_list) + + self.configure() + + self.initConsumers() + self.initProviders() + + if self._consumerTypes and self._providerTypes: + self.appendProperty("dataport.dataflow_type", "duplex") + + num = -1 + ret, num = OpenRTM_aist.stringTo( + num, self._properties.getProperty( + "connection_limit", "-1")) + if not ret: + self._rtcout.RTC_ERROR("invalid connection_limit value: %s", + self._properties.getProperty("connection_limit")) + + self.setConnectionLimit(num) + return + + ## + # @if jp + # + # @brief データ書き込み + # + # ポートへデータを書き込む。 + # バインドされた変数に設定された値をポートに書き込む。 + # + # @return 書き込み処理結果(書き込み成功:true、書き込み失敗:false) + # + # @else + # + # @brief Write data + # + # Write data to the port. + # Write the value, which was set to the bound variable, to the port. + # + # @return Writing result (Successful:true, Failed:false) + # + # @endif + # + # virtual bool write() = 0; + def write(self): + pass + + ## + # @if jp + # + # @brief [CORBA interface] Port の接続を行う + # + # 与えられた ConnectoionProfile の情報に基づき、Port間の接続を確立 + # する。この関数は主にアプリケーションプログラムやツールから呼び出 + # すことを前提としている。 + # + # @param connector_profile ConnectorProfile + # @return ReturnCode_t 型のリターンコード + # + # @else + # + # @brief [CORBA interface] Connect the Port + # + # This operation establishes connection according to the given + # ConnectionProfile inforamtion. This function is premised on + # calling from mainly application program or tools. + # + # @param connector_profile The ConnectorProfile. + # @return ReturnCode_t The return code of ReturnCode_t type. + # + # @endif + # + + def connect(self, connector_profile): + self._rtcout.RTC_TRACE("OutPortBase.connect()") + + if OpenRTM_aist.NVUtil.find_index(connector_profile.properties, + "dataport.serializer.cdr.endian") == -1: + self._rtcout.RTC_TRACE( + "ConnectorProfile dataport.serializer.cdr.endian set.") + connector_profile.properties.append( + OpenRTM_aist.NVUtil.newNV( + "dataport.serializer.cdr.endian", + "little,big")) + + return OpenRTM_aist.PortBase.connect(self, connector_profile) + + ## + # @if jp + # + # @brief + # + # @param self + # @param connector_profile + # @return + # + # @else + # + # @brief + # + # @param self + # @param connector_profile + # @return + # + # @endif + # + + def notify_connect(self, connector_profile): + prop = OpenRTM_aist.Properties() + OpenRTM_aist.NVUtil.copyToProperties( + prop, connector_profile.properties) + + node = prop.getNode("dataport.outport") + portprop = copy.deepcopy(self._properties) + portprop.mergeProperties(node) + node.mergeProperties(portprop) + OpenRTM_aist.NVUtil.copyFromProperties( + connector_profile.properties, prop) + + _str = node.getProperty("fan_out") + _type = int(100) + + _, _type = OpenRTM_aist.stringTo(_type, _str) + + _str = prop.getProperty("dataport.fan_out") + _, _type = OpenRTM_aist.stringTo(_type, _str) + + value = _type + + if value <= len(self._connectors): + return (RTC.PRECONDITION_NOT_MET, connector_profile) + + return OpenRTM_aist.PortBase.notify_connect(self, connector_profile) + + ## + # @if jp + # @brief プロパティを取得する + # + # OutPortのプロパティを取得する。 + # + # @return プロパティ + # + # @else + # + # @brief Get properties + # + # Getting properties of this OutPort + # + # @return OutPort's properties + # + # @endif + # + # coil::Properties& OutPortBase::properties() + def properties(self): + self._rtcout.RTC_TRACE("properties()") + return self._properties + + ## + # @if jp + # @brief Connector を取得 + # @else + # @brief Connector list + # @endif + # + # const std::vector& OutPortBase::connectors() + + def connectors(self): + self._rtcout.RTC_TRACE( + "connectors(): size = %d", len( + self._connectors)) + return self._connectors + + ## + # @if jp + # @brief ConnectorProfile を取得 + # @else + # @brief ConnectorProfile list + # @endif + # + # ConnectorBase::ConnectorInfoList OutPortBase::getConnectorProfiles() + + def getConnectorProfiles(self): + self._rtcout.RTC_TRACE( + "getConnectorProfiles(): size = %d", len( + self._connectors)) + profs = [] + for con in self._connectors: + profs.append(con.profile()) + + return profs + + ## + # @if jp + # @brief ConnectorId を取得 + # @else + # @brief ConnectorId list + # @endif + # + # coil::vstring OutPortBase::getConnectorIds() + + def getConnectorIds(self): + ids = [] + + for con in self._connectors: + ids.append(con.id()) + + self._rtcout.RTC_TRACE( + "getConnectorIds(): %s", + OpenRTM_aist.flatten(ids)) + return ids + + ## + # @if jp + # @brief Connectorの名前を取得 + # @else + # @brief Connector name list + # @endif + # + # coil::vstring OutPortBase::getConnectorNames() + + def getConnectorNames(self): + names = [] + for con in self._connectors: + names.append(con.name()) + + self._rtcout.RTC_TRACE( + "getConnectorNames(): %s", + OpenRTM_aist.flatten(names)) + return names + + ## + # @if jp + # @brief ConnectorProfileをIDで取得 + # + # 現在所有しているコネクタをIDで取得する。 + # + # @param id Connector ID + # @return コネクタへのポインタ + # + # @else + # + # @brief Getting ConnectorProfile by ID + # + # This operation returns Connector specified by ID. + # + # @param id Connector ID + # @return A pointer to connector + # + # @endif + # + # OutPortConnector* getConnectorById(const char* id); + + def getConnectorById(self, id): + self._rtcout.RTC_TRACE("getConnectorById(id = %s)", id) + + for (i, con) in enumerate(self._connectors): + if id == con.id(): + return self._connectors[i] + + self._rtcout.RTC_WARN( + "ConnectorProfile with the id(%s) not found.", id) + return None + + ## + # @if jp + # @brief ConnectorProfileを名前で取得 + # + # 現在所有しているコネクタを名前で取得する。 + # + # @param name Connector name + # @return コネクタへのポインタ + # + # @else + # + # @brief Getting Connector by name + # + # This operation returns Connector specified by name. + # + # @param id Connector ID + # @return A pointer to connector + # + # @endif + # + # OutPortConnector* getConnectorByName(const char* name); + def getConnectorByName(self, name): + self._rtcout.RTC_TRACE("getConnectorByName(name = %s)", name) + + for (i, con) in enumerate(self._connectors): + if name == con.name(): + return self._connectors[i] + + self._rtcout.RTC_WARN( + "ConnectorProfile with the name(%s) not found.", name) + return None + + ## + # @if jp + # @brief ConnectorProfileをIDで取得 + # @else + # @brief Getting ConnectorProfile by name + # @endif + # + # bool OutPortBase::getConnectorProfileById(const char* id, + # ConnectorInfo& prof) + + def getConnectorProfileById(self, id): + self._rtcout.RTC_TRACE("getConnectorProfileById(id = %s)", id) + + conn = self.getConnectorById(id) + + if not conn: + return False, None + + prof = conn.profile() + return True, prof + + ## + # @if jp + # @brief ConnectorProfileを名前で取得 + # @else + # @brief Getting ConnectorProfile by name + # @endif + # + # bool OutPortBase::getConnectorProfileByName(const char* name, + # ConnectorInfo& prof) + + def getConnectorProfileByName(self, name): + self._rtcout.RTC_TRACE("getConnectorProfileByName(name = %s)", name) + + conn = self.getConnectorByName(name) + + if not conn: + return False, None + + prof = conn.profile() + return True, prof + + ## + # @if jp + # @brief OutPortを activates する + # @else + # @brief Activate all Port interfaces + # @endif + # + # void OutPortBase::activateInterfaces() + + def activateInterfaces(self): + self._rtcout.RTC_TRACE("activateInterfaces()") + for con in self._connectors: + con.activate() + + ## + # @if jp + # @brief 全ての Port のインターフェースを deactivates する + # @else + # @brief Deactivate all Port interfaces + # @endif + # + # void OutPortBase::deactivateInterfaces() + + def deactivateInterfaces(self): + self._rtcout.RTC_TRACE("deactivateInterfaces()") + for con in self._connectors: + con.deactivate() + + ## + # @if jp + # @brief ConnectorDataListener リスナを追加する + # + # バッファ書き込みまたは読み出しイベントに関連する各種リスナを設定する。 + # + # 設定できるリスナのタイプとコールバックイベントは以下の通り + # + # - ON_BUFFER_WRITE: バッファ書き込み時 + # - ON_BUFFER_FULL: バッファフル時 + # - ON_BUFFER_WRITE_TIMEOUT: バッファ書き込みタイムアウト時 + # - ON_BUFFER_OVERWRITE: バッファ上書き時 + # - ON_BUFFER_READ: バッファ読み出し時 + # - ON_SEND: InProtへの送信時 + # - ON_RECEIVED: InProtへの送信完了時 + # - ON_SEND_ERTIMEOUT: OutPort側タイムアウト時 + # - ON_SEND_ERERROR: OutPort側エラー時 + # - ON_RECEIVER_FULL: InProt側バッファフル時 + # - ON_RECEIVER_TIMEOUT: InProt側バッファタイムアウト時 + # - ON_RECEIVER_ERROR: InProt側エラー時 + # + # リスナは ConnectorDataListener を継承し、以下のシグニチャを持つ + # operator() を実装している必要がある。 + # + # ConnectorDataListener:: + # operator()(const ConnectorProfile&, const cdrStream&) + # + # デフォルトでは、この関数に与えたリスナオブジェクトの所有権は + # OutPortに移り、OutPort解体時もしくは、 + # removeConnectorDataListener() により削除時に自動的に解体される。 + # リスナオブジェクトの所有権を呼び出し側で維持したい場合は、第3引 + # 数に false を指定し、自動的な解体を抑制することができる。 + # + # @param listener_type リスナタイプ + # @param listener リスナオブジェクトへのポインタ + # + # @else + # @brief Adding BufferDataListener type listener + # + # This operation adds certain listeners related to buffer writing and + # reading events. + # The following listener types are available. + # + # - ON_BUFFER_WRITE: At the time of buffer write + # - ON_BUFFER_FULL: At the time of buffer full + # - ON_BUFFER_WRITE_TIMEOUT: At the time of buffer write timeout + # - ON_BUFFER_OVERWRITE: At the time of buffer overwrite + # - ON_BUFFER_READ: At the time of buffer read + # - ON_SEND: At the time of sending to InPort + # - ON_RECEIVED: At the time of finishing sending to InPort + # - ON_SENDER_TIMEOUT: At the time of timeout of OutPort + # - ON_SENDER_ERROR: At the time of error of OutPort + # - ON_RECEIVER_FULL: At the time of bufferfull of InPort + # - ON_RECEIVER_TIMEOUT: At the time of timeout of InPort + # - ON_RECEIVER_ERROR: At the time of error of InPort + # + # Listeners should have the following function operator(). + # + # ConnectorDataListener:: + # operator()(const ConnectorProfile&, const cdrStream&) + # + # The ownership of the given listener object is transferred to + # this OutPort object in default. The given listener object will + # be destroied automatically in the OutPort's dtor or if the + # listener is deleted by removeConnectorDataListener() function. + # If you want to keep ownership of the listener object, give + # "false" value to 3rd argument to inhibit automatic destruction. + # + # @param listener_type A listener type + # @param listener A pointer to a listener object + # + # @endif + # + # void addConnectorDataListener(ConnectorDataListenerType listener_type, + # ConnectorDataListener* listener); + + def addConnectorDataListener(self, listener_type, listener): + self._rtcout.RTC_TRACE("addConnectorDataListener()") + if self._listeners.addDataListener(listener_type, listener): + self._rtcout.RTC_TRACE("addConnectorDataListener(%s)", + OpenRTM_aist.ConnectorDataListener.toString(listener_type)) + return + + self._rtcout.RTC_ERROR( + "addConnectorDataListener(): Unknown Listener Type") + return + + ## + # @if jp + # @brief ConnectorDataListener リスナを削除する + # + # 設定した各種リスナを削除する。 + # + # @param listener_type リスナタイプ + # @param listener リスナオブジェクトへのポインタ + # + # @else + # @brief Removing BufferDataListener type listener + # + # This operation removes a specified listener. + # + # @param listener_type A listener type + # @param listener A pointer to a listener object + # + # @endif + # + # void removeConnectorDataListener(ConnectorDataListenerType listener_type, + # ConnectorDataListener* listener); + + def removeConnectorDataListener(self, listener_type, listener): + self._rtcout.RTC_TRACE("removeConnectorDataListener()") + + if self._listeners.removeDataListener(listener_type, listener): + self._rtcout.RTC_TRACE("removeConnectorDataListener(%s)", + OpenRTM_aist.ConnectorDataListener.toString(listener_type)) + return + + self._rtcout.RTC_ERROR( + "removeConnectorDataListener(): Unknown Listener Type") + return + + ## + # @if jp + # @brief ConnectorListener リスナを追加する + # + # バッファ書き込みまたは読み出しイベントに関連する各種リスナを設定する。 + # + # 設定できるリスナのタイプは + # + # - ON_BUFFER_EMPTY: バッファが空の場合 + # - ON_BUFFER_READTIMEOUT: バッファが空でタイムアウトした場合 + # + # リスナは以下のシグニチャを持つ operator() を実装している必要がある。 + # + # ConnectorListener::operator()(const ConnectorProfile&) + # + # デフォルトでは、この関数に与えたリスナオブジェクトの所有権は + # OutPortに移り、OutPort解体時もしくは、 + # removeConnectorListener() により削除時に自動的に解体される。 + # リスナオブジェクトの所有権を呼び出し側で維持したい場合は、第3引 + # 数に false を指定し、自動的な解体を抑制することができる。 + # + # @param listener_type リスナタイプ + # @param listener リスナオブジェクトへのポインタ + # + # @else + # @brief Adding ConnectorListener type listener + # + # This operation adds certain listeners related to buffer writing and + # reading events. + # The following listener types are available. + # + # - ON_BUFFER_EMPTY: At the time of buffer empty + # - ON_BUFFER_READTIMEOUT: At the time of buffer read timeout + # + # Listeners should have the following function operator(). + # + # ConnectorListener::operator()(const ConnectorProfile&) + # + # The ownership of the given listener object is transferred to + # this OutPort object in default. The given listener object will + # be destroied automatically in the OutPort's dtor or if the + # listener is deleted by removeConnectorListener() function. + # If you want to keep ownership of the listener object, give + # "false" value to 3rd argument to inhibit automatic destruction. + # + # @param listener_type A listener type + # @param listener A pointer to a listener object + # + # @endif + # + # void addConnectorListener(ConnectorListenerType callback_type, + # ConnectorListener* listener); + + def addConnectorListener(self, callback_type, listener): + self._rtcout.RTC_TRACE("addConnectorListener()") + + if self._listeners.addListener(callback_type, listener): + self._rtcout.RTC_TRACE("addConnectorListener(%s)", + OpenRTM_aist.ConnectorListener.toString(callback_type)) + return + self._rtcout.RTC_ERROR("addConnectorListener(): Unknown Listener Type") + return + + ## + # @if jp + # @brief ConnectorDataListener リスナを削除する + # + # 設定した各種リスナを削除する。 + # + # @param listener_type リスナタイプ + # @param listener リスナオブジェクトへのポインタ + # + # @else + # @brief Removing BufferDataListener type listener + # + # This operation removes a specified listener. + # + # @param listener_type A listener type + # @param listener A pointer to a listener object + # + # @endif + # + # void removeConnectorListener(ConnectorListenerType callback_type, + # ConnectorListener* listener); + + def removeConnectorListener(self, callback_type, listener): + self._rtcout.RTC_TRACE("removeConnectorListener()") + + if self._listeners.removeListener(callback_type, listener): + self._rtcout.RTC_TRACE("removeConnectorListener(%s)", + OpenRTM_aist.ConnectorListener.toString(callback_type)) + return + self._rtcout.RTC_ERROR( + "removeConnectorListener(): Unknown Listener Type") + return + + ## + # @if jp + # @brief OutPortの設定を行う + # @else + # @brief Configureing outport + # @endif + # + # void OutPortBase::configure() + + def configure(self): + pass + + ## + # @if jp + # @brief Interface情報を公開する + # @else + # @brief Publish interface information + # @endif + # + # ReturnCode_t OutPortBase::publishInterfaces(ConnectorProfile& cprof) + + def publishInterfaces(self, cprof): + self._rtcout.RTC_TRACE("publishInterfaces()") + + retval = self._publishInterfaces() + if retval != RTC.RTC_OK: + return retval + + # prop: [port.outport]. + prop = copy.deepcopy(self._properties) + + conn_prop = OpenRTM_aist.Properties() + + OpenRTM_aist.NVUtil.copyToProperties(conn_prop, cprof.properties) + prop.mergeProperties(conn_prop.getNode("dataport") + ) # marge ConnectorProfile + + """ # marge ConnectorProfile for buffer property. # e.g. # prof[buffer.write.full_policy] # << cprof[dataport.outport.buffer.write.full_policy] - # + # """ - prop.mergeProperties(conn_prop.getNode("dataport.outport")) + prop.mergeProperties(conn_prop.getNode("dataport.outport")) + if not self.isExistingMarshalingType(prop): + return RTC.RTC_ERROR - # - # , ConnectorProfile properties ޡ줿ᡢ - # prop["dataflow_type"]: ǡե - # prop["interface_type"]: 󥿡ե - # ʤɤǽˤʤ롣 - dflow_type = OpenRTM_aist.normalize([prop.getProperty("dataflow_type")]) + # + # ここで, ConnectorProfile からの properties がマージされたため、 + # prop["dataflow_type"]: データフロータイプ + # prop["interface_type"]: インターフェースタイプ + # などがアクセス可能になる。 + dflow_type = OpenRTM_aist.normalize(prop.getProperty("dataflow_type")) - if dflow_type == "push": - self._rtcout.RTC_PARANOID("dataflow_type = push .... do nothing") - return RTC.RTC_OK + if dflow_type == "push": + self._rtcout.RTC_PARANOID("dataflow_type = push .... do nothing") + return RTC.RTC_OK - elif dflow_type == "pull": - self._rtcout.RTC_PARANOID("dataflow_type = pull .... create PullConnector") + elif dflow_type == "pull": + self._rtcout.RTC_PARANOID( + "dataflow_type = pull .... create PullConnector") - provider = self.createProvider(cprof, prop) - if not provider: - return RTC.BAD_PARAMETER - - # create OutPortPullConnector - connector = self.createConnector(cprof, prop, provider_ = provider) - if not connector: - return RTC.RTC_ERROR + provider = self.createProvider(cprof, prop) + if not provider: + return RTC.BAD_PARAMETER - # connector set - provider.setConnector(connector) + # create OutPortPullConnector + connector = self.createConnector(cprof, prop, provider_=provider) + if not connector: + self._rtcout.RTC_ERROR("PullConnector creation failed.") + return RTC.RTC_ERROR + connector.setDataType(self._value) - self._rtcout.RTC_DEBUG("publishInterface() successfully finished.") - return RTC.RTC_OK + # connector set + provider.setConnector(connector) - self._rtcout.RTC_ERROR("unsupported dataflow_type") + self._rtcout.RTC_DEBUG("publishInterface() successfully finished.") + return RTC.RTC_OK - return RTC.BAD_PARAMETER + elif dflow_type == "duplex": + self._rtcout.RTC_PARANOID( + "dataflow_type = duplex .... create DuplexConnector") + provider = self.createProvider(cprof, prop) + if not provider: + return RTC.BAD_PARAMETER - ## - # @if jp - # @brief Interface - # @else - # @brief Subscribe interface - # @endif - # - # ReturnCode_t OutPortBase::subscribeInterfaces(const ConnectorProfile& cprof) - def subscribeInterfaces(self, cprof): - self._rtcout.RTC_TRACE("subscribeInterfaces()") + # create OutDuplexPullConnector + connector = self.createDuplexConnector(cprof, prop, provider) + if not connector: + self._rtcout.RTC_ERROR("DuplexConnector creation failed.") + return RTC.RTC_ERROR + connector.setDataType(self._value) - # prop: [port.outport]. - prop = copy.deepcopy(self._properties) + # connector set + provider.setConnector(connector) - conn_prop = OpenRTM_aist.Properties() - OpenRTM_aist.NVUtil.copyToProperties(conn_prop, cprof.properties) - prop.mergeProperties(conn_prop.getNode("dataport")) # marge ConnectorProfile - """ + self._rtcout.RTC_DEBUG("publishInterface() successfully finished.") + return RTC.RTC_OK + + self._rtcout.RTC_ERROR("unsupported dataflow_type") + + return RTC.BAD_PARAMETER + + ## + # @if jp + # @brief Interface情報を取得する + # @else + # @brief Subscribe interface + # @endif + # + # ReturnCode_t OutPortBase::subscribeInterfaces(const ConnectorProfile& + # cprof) + + def subscribeInterfaces(self, cprof): + self._rtcout.RTC_TRACE("subscribeInterfaces()") + + # prop: [port.outport]. + prop = copy.deepcopy(self._properties) + + conn_prop = OpenRTM_aist.Properties() + OpenRTM_aist.NVUtil.copyToProperties(conn_prop, cprof.properties) + prop.mergeProperties(conn_prop.getNode("dataport") + ) # marge ConnectorProfile + """ # marge ConnectorProfile for buffer property. # e.g. # prof[buffer.write.full_policy] # << cprof[dataport.outport.buffer.write.full_policy] """ - prop.mergeProperties(conn_prop.getNode("dataport.outport")) - - # - # , ConnectorProfile properties ޡ줿ᡢ - # prop["dataflow_type"]: ǡե - # prop["interface_type"]: 󥿡ե - # ʤɤǽˤʤ롣 - # - dflow_type = OpenRTM_aist.normalize([prop.getProperty("dataflow_type")]) - - profile = OpenRTM_aist.ConnectorInfo(cprof.name, - cprof.connector_id, - OpenRTM_aist.CORBA_SeqUtil.refToVstring(cprof.ports), - prop) - if dflow_type == "push": - self._rtcout.RTC_PARANOID("dataflow_type = push .... create PushConnector") - - # interface - consumer = self.createConsumer(cprof, prop) - if not consumer: + prop.mergeProperties(conn_prop.getNode("dataport.outport")) + + if not self.isExistingMarshalingType(prop): + return RTC.RTC_ERROR + + # + # ここで, ConnectorProfile からの properties がマージされたため、 + # prop["dataflow_type"]: データフロータイプ + # prop["interface_type"]: インターフェースタイプ + # などがアクセス可能になる。 + # + dflow_type = OpenRTM_aist.normalize(prop.getProperty("dataflow_type")) + + profile = OpenRTM_aist.ConnectorInfo(cprof.name, + cprof.connector_id, + OpenRTM_aist.CORBA_SeqUtil.refToVstring( + cprof.ports), + prop) + if dflow_type == "push": + self._rtcout.RTC_PARANOID( + "dataflow_type = push .... create PushConnector") + + # interface + consumer = self.createConsumer(cprof, prop) + if not consumer: + return RTC.BAD_PARAMETER + + # create OutPortPushConnector + connector = self.createConnector(cprof, prop, consumer_=consumer) + if not connector: + return RTC.RTC_ERROR + connector.setDataType(self._value) + + ret = connector.setConnectorInfo(profile) + + if ret == RTC.RTC_OK: + self._rtcout.RTC_DEBUG( + "subscribeInterfaces() successfully finished.") + + return ret + + elif dflow_type == "pull": + self._rtcout.RTC_PARANOID("dataflow_type = pull.") + + conn = self.getConnectorById(cprof.connector_id) + if not conn: + self._rtcout.RTC_ERROR("specified connector not found: %s", + cprof.connector_id) + return RTC.RTC_ERROR + + ret = conn.setConnectorInfo(profile) + + if ret == RTC.RTC_OK: + self._rtcout.RTC_DEBUG( + "subscribeInterfaces() successfully finished.") + + return ret + + elif dflow_type == "duplex": + self._rtcout.RTC_DEBUG( + "dataflow_type = duplex .... set Consumer Object") + # create OutPortConsumer + consumer = self.createConsumer(cprof, prop) + if not consumer: + return RTC.BAD_PARAMETER + + connector = self.getConnectorById(cprof.connector_id) + if not connector: + return RTC.RTC_ERROR + + connector.setDataType(self._value) + connector.setConsumer(consumer) + ret = connector.setConnectorInfo(profile) + + if ret == RTC.RTC_OK: + self._rtcout.RTC_DEBUG( + "publishInterface() successfully finished.") + + return ret + + self._rtcout.RTC_ERROR("unsupported dataflow_type") return RTC.BAD_PARAMETER - # create OutPortPushConnector - connector = self.createConnector(cprof, prop, consumer_ = consumer) - if not connector: - return RTC.RTC_ERROR - - ret = connector.setConnectorInfo(profile) + ## + # @if jp + # @brief 登録されているInterface情報を解除する + # @else + # @brief Unsubscribe interface + # @endif + # + # void + # OutPortBase::unsubscribeInterfaces(const ConnectorProfile& + # connector_profile) + + def unsubscribeInterfaces(self, connector_profile): + self._rtcout.RTC_TRACE("unsubscribeInterfaces()") + + id = connector_profile.connector_id + self._rtcout.RTC_PARANOID("connector_id: %s", id) + + len_ = len(self._connectors) + for i in range(len_): + idx = (len_ - 1) - i + if id == self._connectors[idx].id(): + # Connector's dtor must call disconnect() + self._connectors[idx].unsubscribeInterface( + connector_profile.properties) + self._connectors[idx].deactivate() + self._connectors[idx].disconnect() + del self._connectors[idx] + self._rtcout.RTC_TRACE("delete connector: %s", id) + return + + self._rtcout.RTC_ERROR("specified connector not found: %s", id) + return - if ret == RTC.RTC_OK: - self._rtcout.RTC_DEBUG("subscribeInterfaces() successfully finished.") + ## + # @if jp + # @brief OutPort provider の初期化 + # @else + # @brief OutPort provider initialization + # @endif + # + # void OutPortBase::initProviders() + + def initProviders(self): + self._rtcout.RTC_TRACE("initProviders()") + + # create OutPort providers + factory = OpenRTM_aist.OutPortProviderFactory.instance() + provider_types = factory.getIdentifiers() + self._rtcout.RTC_PARANOID("available OutPortProviders: %s", + OpenRTM_aist.flatten(provider_types)) + + if self._properties.hasKey("provider_types") and \ + OpenRTM_aist.normalize(self._properties.getProperty("provider_types")) != "all": + self._rtcout.RTC_DEBUG("allowed providers: %s", + self._properties.getProperty("provider_types")) + + temp_types = provider_types + provider_types = [] + active_types = OpenRTM_aist.split( + self._properties.getProperty("provider_types"), ",") + + temp_types.sort() + active_types.sort() + + set_ptypes = set(temp_types).intersection(set(active_types)) + provider_types = provider_types + list(set_ptypes) + + # OutPortProvider supports "pull" dataflow type + if provider_types: + self._rtcout.RTC_DEBUG("dataflow_type pull is supported") + self.appendProperty("dataport.dataflow_type", "pull") + for provider_type in provider_types: + self.appendProperty("dataport.interface_type", provider_type) + + self._providerTypes = provider_types + + ## + # @if jp + # @brief InPort consumer の初期化 + # @else + # @brief InPort consumer initialization + # @endif + # + # void OutPortBase::initConsumers() + + def initConsumers(self): + self._rtcout.RTC_TRACE("initConsumers()") + + # create InPort consumers + factory = OpenRTM_aist.InPortConsumerFactory.instance() + consumer_types = factory.getIdentifiers() + self._rtcout.RTC_PARANOID("available InPortConsumer: %s", + OpenRTM_aist.flatten(consumer_types)) + + if self._properties.hasKey("consumer_types") and \ + OpenRTM_aist.normalize(self._properties.getProperty("consumer_types")) != "all": + self._rtcout.RTC_DEBUG("allowed consumers: %s", + self._properties.getProperty("consumer_types")) + + temp_types = consumer_types + consumer_types = [] + active_types = OpenRTM_aist.split( + self._properties.getProperty("consumer_types"), ",") + + temp_types.sort() + active_types.sort() + + set_ctypes = set(temp_types).intersection(set(active_types)) + consumer_types = consumer_types + list(set_ctypes) + + # InPortConsumer supports "push" dataflow type + if consumer_types: + self._rtcout.RTC_PARANOID("dataflow_type push is supported") + self.appendProperty("dataport.dataflow_type", "push") + for consumer_type in consumer_types: + self.appendProperty("dataport.interface_type", consumer_type) + + self._consumerTypes = consumer_types + + ## + # @if jp + # @brief OutPort provider の生成 + # @else + # @brief OutPort provider creation + # @endif + # + # OutPortProvider* + # OutPortBase::createProvider(ConnectorProfile& cprof, coil::Properties& + # prop) + + def createProvider(self, cprof, prop): + if not prop.getProperty("interface_type") or \ + not OpenRTM_aist.includes(self._providerTypes, prop.getProperty("interface_type")): + self._rtcout.RTC_ERROR("no provider found") + self._rtcout.RTC_DEBUG( + "interface_type: %s", + prop.getProperty("interface_type")) + self._rtcout.RTC_DEBUG("interface_types: %s", + OpenRTM_aist.flatten(self._providerTypes)) + return None - return ret + self._rtcout.RTC_DEBUG( + "interface_type: %s", + prop.getProperty("interface_type")) + provider = OpenRTM_aist.OutPortProviderFactory.instance( + ).createObject(prop.getProperty("interface_type")) - elif dflow_type == "pull": - self._rtcout.RTC_PARANOID("dataflow_type = pull.") + if provider is not None: + self._rtcout.RTC_DEBUG("provider created") + provider.init(prop.getNode("provider")) - conn = self.getConnectorById(cprof.connector_id) - if not conn: - self._rtcout.RTC_ERROR("specified connector not found: %s", - cprof.connector_id) - return RTC.RTC_ERROR + if not provider.publishInterface(cprof.properties): + self._rtcout.RTC_ERROR( + "publishing interface information error") + return None - ret = conn.setConnectorInfo(profile) + return provider - if ret == RTC.RTC_OK: - self._rtcout.RTC_DEBUG("subscribeInterfaces() successfully finished.") + self._rtcout.RTC_ERROR("provider creation failed") + return None - return ret + ## + # @if jp + # @brief InPort consumer の生成 + # @else + # @brief InPort consumer creation + # @endif + # + # InPortConsumer* OutPortBase::createConsumer(const ConnectorProfile& cprof, + # coil::Properties& prop) + + def createConsumer(self, cprof, prop): + if not prop.getProperty("interface_type") or \ + not OpenRTM_aist.includes(self._consumerTypes, prop.getProperty("interface_type")): + self._rtcout.RTC_ERROR("no consumer found") + self._rtcout.RTC_DEBUG( + "interface_type: %s", + prop.getProperty("interface_type")) + self._rtcout.RTC_DEBUG("interface_types: %s", + OpenRTM_aist.flatten(self._consumerTypes)) + return None - self._rtcout.RTC_ERROR("unsupported dataflow_type") - return RTC.BAD_PARAMETER + self._rtcout.RTC_DEBUG( + "interface_type: %s", + prop.getProperty("interface_type")) + consumer = OpenRTM_aist.InPortConsumerFactory.instance( + ).createObject(prop.getProperty("interface_type")) + if consumer is not None: + self._rtcout.RTC_DEBUG("consumer created") - ## - # @if jp - # @brief ϿƤInterface - # @else - # @brief Unsubscribe interface - # @endif - # - # void - # OutPortBase::unsubscribeInterfaces(const ConnectorProfile& connector_profile) - def unsubscribeInterfaces(self, connector_profile): - self._rtcout.RTC_TRACE("unsubscribeInterfaces()") + consumer.init(prop.getNode("consumer")) - id = connector_profile.connector_id - self._rtcout.RTC_PARANOID("connector_id: %s", id) + if not consumer.subscribeInterface(cprof.properties): + self._rtcout.RTC_ERROR("interface subscription failed.") + return 0 - len_ = len(self._connectors) - for i in range(len_): - idx = (len_ - 1) - i - if id == self._connectors[idx].id(): - # Connector's dtor must call disconnect() - self._connectors[idx].deactivate() - self._connectors[idx].disconnect() - del self._connectors[idx] - self._rtcout.RTC_TRACE("delete connector: %s", id) - return + return consumer - self._rtcout.RTC_ERROR("specified connector not found: %s", id) - return - - - ## - # @if jp - # @brief OutPort provider ν - # @else - # @brief OutPort provider initialization - # @endif - # - # void OutPortBase::initProviders() - def initProviders(self): - self._rtcout.RTC_TRACE("initProviders()") - - # create OutPort providers - factory = OpenRTM_aist.OutPortProviderFactory.instance() - provider_types = factory.getIdentifiers() - self._rtcout.RTC_PARANOID("available OutPortProviders: %s", - OpenRTM_aist.flatten(provider_types)) - - if self._properties.hasKey("provider_types") and \ - OpenRTM_aist.normalize([self._properties.getProperty("provider_types")]) != "all": - self._rtcout.RTC_DEBUG("allowed providers: %s", - self._properties.getProperty("provider_types")) - - temp_types = provider_types - provider_types = [] - active_types = OpenRTM_aist.split(self._properties.getProperty("provider_types"), ",") - - temp_types.sort() - active_types.sort() - - set_ptypes = set(temp_types).intersection(set(active_types)) - provider_types = provider_types + list(set_ptypes) - - # OutPortProvider supports "pull" dataflow type - if len(provider_types) > 0: - self._rtcout.RTC_DEBUG("dataflow_type pull is supported") - self.appendProperty("dataport.dataflow_type", "pull") - for provider_type in provider_types: - self.appendProperty("dataport.interface_type",provider_type) - - self._providerTypes = provider_types - - - ## - # @if jp - # @brief InPort consumer ν - # @else - # @brief InPort consumer initialization - # @endif - # - # void OutPortBase::initConsumers() - def initConsumers(self): - self._rtcout.RTC_TRACE("initConsumers()") - - # create InPort consumers - factory = OpenRTM_aist.InPortConsumerFactory.instance() - consumer_types = factory.getIdentifiers() - self._rtcout.RTC_PARANOID("available InPortConsumer: %s", - OpenRTM_aist.flatten(consumer_types)) - - if self._properties.hasKey("consumer_types") and \ - OpenRTM_aist.normalize([self._properties.getProperty("consumer_types")]) != "all": - self._rtcout.RTC_DEBUG("allowed consumers: %s", - self._properties.getProperty("consumer_types")) - - temp_types = consumer_types - consumer_types = [] - active_types = OpenRTM_aist.split(self._properties.getProperty("consumer_types"), ",") - - temp_types.sort() - active_types.sort() - - set_ctypes = set(temp_types).intersection(set(active_types)) - consumer_types = consumer_types + list(set_ctypes) - - # InPortConsumer supports "push" dataflow type - if len(consumer_types) > 0: - self._rtcout.RTC_PARANOID("dataflow_type push is supported") - self.appendProperty("dataport.dataflow_type", "push") - for consumer_type in consumer_types: - self.appendProperty("dataport.interface_type",consumer_type) - - self._consumerTypes = consumer_types - - - ## - # @if jp - # @brief OutPort provider - # @else - # @brief OutPort provider creation - # @endif - # - # OutPortProvider* - # OutPortBase::createProvider(ConnectorProfile& cprof, coil::Properties& prop) - def createProvider(self, cprof, prop): - if not prop.getProperty("interface_type") or \ - not OpenRTM_aist.includes(self._providerTypes, prop.getProperty("interface_type")): - self._rtcout.RTC_ERROR("no provider found") - self._rtcout.RTC_DEBUG("interface_type: %s", prop.getProperty("interface_type")) - self._rtcout.RTC_DEBUG("interface_types: %s", - OpenRTM_aist.flatten(self._providerTypes)) - return None - - self._rtcout.RTC_DEBUG("interface_type: %s", prop.getProperty("interface_type")) - provider = OpenRTM_aist.OutPortProviderFactory.instance().createObject(prop.getProperty("interface_type")) - - if provider is not None: - self._rtcout.RTC_DEBUG("provider created") - provider.init(prop.getNode("provider")) - - if not provider.publishInterface(cprof.properties): - self._rtcout.RTC_ERROR("publishing interface information error") - OpenRTM_aist.OutPortProviderFactory.instance().deleteObject(provider) + self._rtcout.RTC_ERROR("consumer creation failed") return None - return provider - - self._rtcout.RTC_ERROR("provider creation failed") - return None - - - ## - # @if jp - # @brief InPort consumer - # @else - # @brief InPort consumer creation - # @endif - # - # InPortConsumer* OutPortBase::createConsumer(const ConnectorProfile& cprof, - # coil::Properties& prop) - def createConsumer(self, cprof, prop): - if not prop.getProperty("interface_type") or \ - not OpenRTM_aist.includes(self._consumerTypes, prop.getProperty("interface_type")): - self._rtcout.RTC_ERROR("no consumer found") - self._rtcout.RTC_DEBUG("interface_type: %s", prop.getProperty("interface_type")) - self._rtcout.RTC_DEBUG("interface_types: %s", - OpenRTM_aist.flatten(self._consumerTypes)) - return None - - self._rtcout.RTC_DEBUG("interface_type: %s", prop.getProperty("interface_type")) - consumer = OpenRTM_aist.InPortConsumerFactory.instance().createObject(prop.getProperty("interface_type")) - - if consumer is not None: - self._rtcout.RTC_DEBUG("consumer created") - - consumer.init(prop.getNode("consumer")) - - if not consumer.subscribeInterface(cprof.properties): - self._rtcout.RTC_ERROR("interface subscription failed.") - OpenRTM_aist.InPortConsumerFactory.instance().deleteObject(consumer) - return 0 - - return consumer - - self._rtcout.RTC_ERROR("consumer creation failed") - return None - - - ## - # @if jp - # @brief OutPortPushConnector - # @else - # @brief OutPortPushConnector creation - # @endif - # - # OutPortConnector* - # OutPortBase::createConnector(const ConnectorProfile& cprof, - # coil::Properties& prop, - # InPortConsumer* consumer) - def createConnector(self, cprof, prop, provider_ = None, consumer_ = None): - profile = OpenRTM_aist.ConnectorInfo(cprof.name, - cprof.connector_id, - OpenRTM_aist.CORBA_SeqUtil.refToVstring(cprof.ports), - prop) - - connector = None - try: - - if consumer_ is not None: - connector = OpenRTM_aist.OutPortPushConnector(profile, consumer_, self._listeners) - elif provider_ is not None: - connector = OpenRTM_aist.OutPortPullConnector(profile, provider_, self._listeners) - - else: - self._rtcout.RTC_ERROR("provider or consumer is not passed. returned 0;") - return None + ## + # @if jp + # @brief OutPortPushConnector の生成 + # @else + # @brief OutPortPushConnector creation + # @endif + # + # OutPortConnector* + # OutPortBase::createConnector(const ConnectorProfile& cprof, + # coil::Properties& prop, + # InPortConsumer* consumer) + + def createConnector(self, cprof, prop, provider_=None, consumer_=None): + profile = OpenRTM_aist.ConnectorInfo(cprof.name, + cprof.connector_id, + OpenRTM_aist.CORBA_SeqUtil.refToVstring( + cprof.ports), + prop) + + connector = None + try: + + if consumer_ is not None: + connector = OpenRTM_aist.OutPortPushConnector( + profile, consumer_, self._listeners) + elif provider_ is not None: + connector = OpenRTM_aist.OutPortPullConnector( + profile, provider_, self._listeners) + + else: + self._rtcout.RTC_ERROR( + "provider or consumer is not passed. returned 0;") + return None + + # if connector is None: + # self._rtcout.RTC_ERROR("OutPortConnector creation failed") + # return 0 + + if consumer_ is not None: + self._rtcout.RTC_TRACE("OutPortPushConnector created") + elif provider_ is not None: + self._rtcout.RTC_TRACE("OutPortPullConnector created") + + if OpenRTM_aist.StringUtil.normalize( + prop.getProperty("interface_type")) == "direct": + if consumer_ is not None: + inport = self.getLocalInPort(profile) + + if inport is None: + self._rtcout.RTC_TRACE("interface_type is direct, ") + self._rtcout.RTC_TRACE( + "but a peer InPort servant could not be obtained.") + del connector + return None + + connector.setInPort(inport) + # if consumer_ is not None: + # connector.setInPort(inport) + # elif provider_ is not None: + # connector.setInPort(inport) + else: + connector.setDirectMode() + + self._connectors.append(connector) + self._rtcout.RTC_PARANOID( + "connector push backed: %d", len( + self._connectors)) + return connector + + except BaseException: + self._rtcout.RTC_ERROR( + "Exeption: OutPortPushConnector creation failed") + self._rtcout.RTC_ERROR(OpenRTM_aist.Logger.print_exception()) + return None - #if connector is None: - # self._rtcout.RTC_ERROR("OutPortConnector creation failed") - # return 0 - - if consumer_ is not None: - self._rtcout.RTC_TRACE("OutPortPushConnector created") - elif provider_ is not None: - self._rtcout.RTC_TRACE("OutPortPullConnector created") - - - if OpenRTM_aist.StringUtil.normalize([prop.getProperty("interface_type")]) == "direct": - if consumer_ is not None: - inport = self.getLocalInPort(profile) - - if inport is None: - self._rtcout.RTC_TRACE("interface_type is direct, ") - self._rtcout.RTC_TRACE("but a peer InPort servant could not be obtained.") - del connector + ## + # @if jp + # @brief InPortDuplexConnector の生成 + # + # 双方向通信用コネクタを生成し、生成が成功すれば m_connectors に保存する。 + # + # + # @param cprof コネクタプロファイル + # @param prop コネクタプロファイルをプロパティに変換 + # @param provider_ プロバイダ + # @return 生成したコネクタ。生成に失敗した場合 None を返す。 + # + # @else + # @brief InPortDuplexConnector creation + # + # @param cprof + # @param prop + # @param provider_ + # @return + # + # @endif + # + def createDuplexConnector(self, cprof, prop, provider_): + profile = OpenRTM_aist.ConnectorInfo(cprof.name, + cprof.connector_id, + OpenRTM_aist.CORBA_SeqUtil.refToVstring( + cprof.ports), + prop) + connector = None + try: + connector = OpenRTM_aist.OutPortDuplexConnector( + profile, provider_, self._listeners) + + self._rtcout.RTC_TRACE("OutPortDuplexConnector created") + + # guard = OpenRTM_aist.ScopedLock(self._connector_mutex) + self._connectors.append(connector) + self._rtcout.RTC_PARANOID( + "connector duplex backed: %d", len( + self._connectors)) + return connector + except BaseException: + self._rtcout.RTC_ERROR("OutPortDuplexConnector creation failed") + self._rtcout.RTC_ERROR(OpenRTM_aist.Logger.print_exception()) return None - connector.setInPort(inport) - #if consumer_ is not None: - # connector.setInPort(inport) - #elif provider_ is not None: - # connector.setInPort(inport) - else: - connector.setDirectMode() - - - - self._connectors.append(connector) - self._rtcout.RTC_PARANOID("connector push backed: %d", len(self._connectors)) - return connector - - except: - self._rtcout.RTC_ERROR("Exeption: OutPortPushConnector creation failed") - self._rtcout.RTC_ERROR(OpenRTM_aist.Logger.print_exception()) - return None - - - - - - ## - # @if jp - # @brief ΥԥInPort - # @param self - # @param profile ͥץե - # @return InPortΥХ(˼ԤNone) - # @else - # @brief Getting local peer InPort if available - # @param self - # @param profile - # @return - # @endif - # - # InPortBase* - # getLocalInPort(const ConnectorInfo& profile) - def getLocalInPort(self, profile): - self._rtcout.RTC_DEBUG("Trying direct port connection.") - orb = OpenRTM_aist.Manager.instance().getORB() - self._rtcout.RTC_DEBUG("Current connector profile: name=%s, id=%s" % (profile.name, profile.id)) - for p in profile.ports: - obj = orb.string_to_object(p) - if self.getPortRef()._is_equivalent(obj): - continue - self._rtcout.RTC_DEBUG("Peer port found: %s." % p) - try: - poa = OpenRTM_aist.Manager.instance().getPOA() - inport = poa.reference_to_servant(obj) - self._rtcout.RTC_DEBUG("InPortBase servant pointer is obtained.") - return inport - except: - self._rtcout.RTC_DEBUG("Peer port might be a remote port") - return None \ No newline at end of file + ## + # @if jp + # @brief ローカルのピアInPortを取得 + # @param self + # @param profile コネクタプロファイル + # @return InPortのサーバント(取得に失敗した場合はNone) + # @else + # @brief Getting local peer InPort if available + # @param self + # @param profile + # @return + # @endif + # + # InPortBase* + # getLocalInPort(const ConnectorInfo& profile) + + def getLocalInPort(self, profile): + self._rtcout.RTC_DEBUG("Trying direct port connection.") + orb = OpenRTM_aist.Manager.instance().getORB() + self._rtcout.RTC_DEBUG( + "Current connector profile: name=%s, id=%s" % + (profile.name, profile.id)) + for p in profile.ports: + obj = orb.string_to_object(p) + if self.getPortRef()._is_equivalent(obj): + continue + self._rtcout.RTC_DEBUG("Peer port found: %s." % p) + try: + poa = OpenRTM_aist.Manager.instance().getPOA() + inport = poa.reference_to_servant(obj) + self._rtcout.RTC_DEBUG( + "InPortBase servant pointer is obtained.") + return inport + except BaseException: + self._rtcout.RTC_DEBUG("Peer port might be a remote port") + return None diff --git a/OpenRTM_aist/OutPortCSPConsumer.py b/OpenRTM_aist/OutPortCSPConsumer.py new file mode 100644 index 00000000..57d2c54f --- /dev/null +++ b/OpenRTM_aist/OutPortCSPConsumer.py @@ -0,0 +1,213 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- + +## +# @file OutPortCSPConsumer.py +# @brief OutPortCSPConsumer class +# @date $Date: 2016/01/08 $ +# @author Nobuhiko Miyamoto + + +import OpenRTM_aist +import OpenRTM +import CSP + + +## +# @if jp +# @class OutPortCSPConsumer +# @brief OutPortCSPConsumer クラス +# +# CSPモデルのチャネルを模擬した出力ポートプロバイダーの実装クラス。 +# +# +# @else +# @class OutPortCSPConsumer +# @brief OutPortCSPConsumer class +# +# +# +# @endif +# +class OutPortCSPConsumer(OpenRTM_aist.OutPortCorbaCdrConsumer): + + """ + """ + + ## + # @if jp + # @brief コンストラクタ + # + # コンストラクタ + # Interface Typeにはshared_memoryを指定する + # 共有メモリの空間名はUUIDで作成し、コネクタプロファイルのdataport.shared_memory.addressに保存する + # + # self + # + # @else + # @brief Constructor + # + # Constructor + # + # self + # @endif + # + def __init__(self): + OpenRTM_aist.OutPortCorbaCdrConsumer.__init__(self) + OpenRTM_aist.CorbaConsumer.__init__(self, CSP.OutPortCsp) + self._rtcout = OpenRTM_aist.Manager.instance().getLogbuf("OutPortCSPConsumer") + self._properties = None + return + + ## + # @if jp + # @brief デストラクタ + # + # デストラクタ + # + # @param self + # + # @else + # @brief Destructor + # + # Destructor + # + # @param self + # + # @endif + # + def __del__(self, CorbaConsumer=OpenRTM_aist.CorbaConsumer): + self._rtcout.RTC_PARANOID("~OutPortCSPConsumer()") + CorbaConsumer.__del__(self) + + # void init(coil::Properties& prop) + + def init(self, prop): + self._rtcout.RTC_TRACE("init()") + self._properties = prop + + ## + # @if jp + # @brief バッファをセットする + # + # + # @param buffer OutPortProviderがデータを取り出すバッファへのポインタ + # + # @else + # @brief Setting outside buffer's pointer + # + # @param buffer A pointer to a data buffer to be used by OutPortProvider + # + # @endif + # + # virtual void setBuffer(CdrBufferBase* buffer); + + def setBuffer(self, buffer): + pass + + # void OutPortCorbaCdrConsumer::setListener(ConnectorInfo& info, + # ConnectorListeners* listeners) + + def setListener(self, info, listeners): + self._rtcout.RTC_TRACE("setListener()") + self._listeners = listeners + self._profile = info + return + + def setConnector(self, connector): + self._connector = connector + return + + ## + # @if jp + # @brief 接続先のProviderからデータを取得する + # + # @param data データの格納先 + # @return リターンコード + # PORT_OK:正常終了 + # PORT_ERROR:バッファの読み込みエラー、通常は発生しない + # BUFFER_FULL:バッファフル、通常は発生しない + # BUFFER_EMPTY:バッファが空 + # BUFFER_TIMEOUT:一定時間以内にバッファにデータが追加されなかった + # CONNECTION_LOST:通信エラー + # UNKNOWN_ERROR:その他のエラー + # + # @else + # @brief + # + # + # @param data + # @return + # + # @endif + # + # ::OpenRTM::PortStatus put() + # throw (CORBA::SystemException); + def get(self): + self._rtcout.RTC_PARANOID("get()") + + try: + data = None + outportcsp = self._ptr() + ret, cdr_data = outportcsp.get() + + if ret == OpenRTM.PORT_OK: + self._rtcout.RTC_DEBUG("get() successful") + data = cdr_data + self.onReceived(data) + self.onBufferWrite(data) + + return self.PORT_OK, data + return self.convertReturn(ret, data) + + except BaseException: + self._rtcout.RTC_WARN("Exception caught from OutPort.get().") + self._rtcout.RTC_ERROR(OpenRTM_aist.Logger.print_exception()) + return self.CONNECTION_LOST, None + + ## + # @if jp + # @brief データ読み込み可能かを接続先のproviderに確認 + # + # + # @param self + # @param retry True:再検索、False:通常の読み込み確認 + # @return True:読み込み可能、False:読み込み不可 + # 通信エラーが発生した場合はFalseを返す + # + # @else + # @brief + # + # @param self + # @param retry + # @return + # + # @endif + # + def isReadable(self, retry=False): + self._rtcout.RTC_PARANOID("isReadable()") + try: + outportcsp = self._ptr() + return outportcsp.is_readable(retry) + except BaseException: + self._rtcout.RTC_WARN( + "Exception caught from OutPort.isReadable().") + self._rtcout.RTC_ERROR(OpenRTM_aist.Logger.print_exception()) + return False + + +## +# @if jp +# @brief モジュール登録関数 +# +# +# @else +# @brief +# +# +# @endif +# +def OutPortCSPConsumerInit(): + factory = OpenRTM_aist.OutPortConsumerFactory.instance() + factory.addFactory("csp_channel", + OpenRTM_aist.OutPortCSPConsumer) diff --git a/OpenRTM_aist/OutPortCSPProvider.py b/OpenRTM_aist/OutPortCSPProvider.py new file mode 100644 index 00000000..e4d785bb --- /dev/null +++ b/OpenRTM_aist/OutPortCSPProvider.py @@ -0,0 +1,271 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- + +## +# @file OutPortCSPProvider.py +# @brief OutPortCSPProvider class +# @date $Date: 2019/03/12 $ +# @author Nobuhiko Miyamoto + + +import OpenRTM_aist +import OpenRTM +import CSP__POA + + +## +# @if jp +# @class OutPortCSPProvider +# @brief OutPortCSPProvider クラス +# +# CSPモデルのチャネルを模擬した出力ポートプロバイダーの実装クラス。 +# +# +# @else +# @class InPortCorbaCdrProvider +# @brief InPortCorbaCdrProvider class +# +# +# +# @endif +# +class OutPortCSPProvider(OpenRTM_aist.OutPortProvider, CSP__POA.OutPortCsp): + + """ + """ + + ## + # @if jp + # @brief コンストラクタ + # + # コンストラクタ + # Interface Typeにはshared_memoryを指定する + # 共有メモリの空間名はUUIDで作成し、コネクタプロファイルのdataport.shared_memory.addressに保存する + # + # self + # + # @else + # @brief Constructor + # + # Constructor + # + # self + # @endif + # + def __init__(self): + OpenRTM_aist.OutPortProvider.__init__(self) + + # PortProfile setting + self.setInterfaceType("csp_channel") + self._objref = self._this() + self._buffer = None + orb = OpenRTM_aist.Manager.instance().getORB() + self._properties.append(OpenRTM_aist.NVUtil.newNV("dataport.corba_cdr.outport_ior", + orb.object_to_string(self._objref))) + self._properties.append(OpenRTM_aist.NVUtil.newNV("dataport.corba_cdr.outport_ref", + self._objref)) + self._listeners = None + self._connector = None + self._profile = None + + return + + ## + # @if jp + # @brief デストラクタ + # + # デストラクタ + # + # @param self + # + # @else + # @brief Destructor + # + # Destructor + # + # @param self + # + # @endif + # + def __del__(self): + return + + ## + # @if jp + # @brief 終了処理 + # + # @else + # @brief + # + # + # + # @endif + # + def exit(self): + oid = OpenRTM_aist.Manager.instance().getPOA().servant_to_id(self) + OpenRTM_aist.Manager.instance().getPOA().deactivate_object(oid) + + # void init(coil::Properties& prop) + def init(self, prop): + + pass + + def setBuffer(self, buffer): + self._buffer = buffer + return + + def setListener(self, info, listeners): + self._profile = info + self._listeners = listeners + return + + def setConnector(self, connector): + self._connector = connector + return + + ## + # @if jp + # @brief バッファからデータを取得する + # + # @param self + # @return (リターンコード、取得データ) + # PORT_OK:正常完了 + # PORT_ERROR:バッファ読み出しエラー、通常は発生しない + # BUFFER_FULL:バッファがフル、通常は発生しない + # BUFFER_EMPTY:バッファが空 + # BUFFER_TIMEOUT:読み込みタイムアウト + # UNKNOWN_ERROR:その他のエラー + # + # + # @else + # @brief Get data from the buffer + # + # @param self + # @return + # + # @endif + # + def get(self): + self._rtcout.RTC_PARANOID("OutPortCSPProvider.get()") + + if not self._connector: + self.onSenderError() + return (OpenRTM.UNKNOWN_ERROR, "") + + try: + ret, cdr = self._connector.read() + + if ret == OpenRTM_aist.BufferStatus.BUFFER_OK: + if cdr is None: + self._rtcout.RTC_ERROR("buffer is empty.") + return (OpenRTM.BUFFER_EMPTY, "") + + except BaseException: + self._rtcout.RTC_TRACE(OpenRTM_aist.Logger.print_exception()) + return (OpenRTM.UNKNOWN_ERROR, "") + + return self.convertReturn(ret, cdr) + + ## + # @if jp + # @brief データ読み込み可能かを確認 + # + # @param self + # @param retry True:再検索、False:通常の読み込み確認 + # @return True:読み込み可能、False:読み込み不可 + # + # + # @else + # @brief + # + # @param self + # @param retry + # @return + # + # @endif + # + + def is_readable(self, retry): + self._rtcout.RTC_PARANOID("is_readable()") + if self._connector: + return self._connector.isReadable(retry) + return False + + def onBufferRead(self, data): + if self._listeners and self._profile: + _, data = self._listeners.notifyData( + OpenRTM_aist.ConnectorDataListenerType.ON_BUFFER_READ, self._profile, data) + return data + + def onSend(self, data): + if self._listeners and self._profile: + _, data = self._listeners.notifyData( + OpenRTM_aist.ConnectorDataListenerType.ON_SEND, self._profile, data) + return data + + def onBufferEmpty(self): + if self._listeners and self._profile: + self._listeners.notify( + OpenRTM_aist.ConnectorListenerType.ON_BUFFER_EMPTY, self._profile) + return + + def onBufferReadTimeout(self): + if self._listeners and self._profile: + self._listeners.notify( + OpenRTM_aist.ConnectorListenerType.ON_BUFFER_READ_TIMEOUT, self._profile) + return + + def onSenderEmpty(self): + if self._listeners and self._profile: + self._listeners.notify( + OpenRTM_aist.ConnectorListenerType.ON_SENDER_EMPTY, self._profile) + return + + def onSenderTimeout(self): + if self._listeners and self._profile: + self._listeners.notify( + OpenRTM_aist.ConnectorListenerType.ON_SENDER_TIMEOUT, self._profile) + return + + def onSenderError(self): + if self._listeners and self._profile: + self._listeners.notify( + OpenRTM_aist.ConnectorListenerType.ON_SENDER_ERROR, self._profile) + return + + def convertReturn(self, status, data): + if status == OpenRTM_aist.BufferStatus.BUFFER_OK: + data = self.onBufferRead(data) + data = self.onSend(data) + return (OpenRTM.PORT_OK, data) + + elif status == OpenRTM_aist.BufferStatus.BUFFER_ERROR: + self.onSenderError() + return (OpenRTM.PORT_ERROR, data) + + elif status == OpenRTM_aist.BufferStatus.BUFFER_FULL: + # never come here + return (OpenRTM.BUFFER_FULL, data) + + elif status == OpenRTM_aist.BufferStatus.BUFFER_EMPTY: + self.onBufferEmpty() + self.onSenderEmpty() + return (OpenRTM.BUFFER_EMPTY, data) + + elif status == OpenRTM_aist.BufferStatus.PRECONDITION_NOT_MET: + self.onSenderError() + return (OpenRTM.PORT_ERROR, data) + + elif status == OpenRTM_aist.BufferStatus.TIMEOUT: + self.onBufferReadTimeout() + self.onSenderTimeout() + return (OpenRTM.BUFFER_TIMEOUT, data) + + else: + return (OpenRTM.UNKNOWN_ERROR, data) + + +def OutPortCSPProviderInit(): + factory = OpenRTM_aist.OutPortProviderFactory.instance() + factory.addFactory("csp_channel", + OpenRTM_aist.OutPortCSPProvider) diff --git a/OpenRTM_aist/OutPortConnector.py b/OpenRTM_aist/OutPortConnector.py index 1a5b6497..3e8f9062 100644 --- a/OpenRTM_aist/OutPortConnector.py +++ b/OpenRTM_aist/OutPortConnector.py @@ -1,5 +1,5 @@ #!/usr/bin/env python -# -*- coding: euc-jp -*- +# -*- coding: utf-8 -*- ## @@ -24,16 +24,16 @@ ## # @if jp # @class OutPortConnector -# @brief OutPortConnector 쥯饹 +# @brief OutPortConnector 基底クラス # -# OutPort Push/Pull Ƽ Connector 뤿 -# 쥯饹 +# OutPort の Push/Pull 各種 Connector を派生させるための +# 基底クラス。 # # @since 1.0.0 # # @else # @class OutPortConnector -# @brief IPortConnector base class +# @brief InPortConnector base class # # The base class to derive subclasses for OutPort's Push/Pull Connectors # @@ -41,152 +41,241 @@ # # @endif # + + class OutPortConnector(OpenRTM_aist.ConnectorBase): - """ - """ - - ## - # @if jp - # @brief 󥹥ȥ饯 - # @else - # @brief Constructor - # @endif - # - # OutPortConnector(ConnectorInfo& info); - def __init__(self, info): - self._rtcout = OpenRTM_aist.Manager.instance().getLogbuf("OutPortConnector") - self._profile = info - self._endian = True - self._directMode = False - return - - ## - # @if jp - # @brief ǥȥ饯 - # @else - # @brief Destructor - # @endif - # - def __del__(self): - pass - - - ## - # @if jp - # @brief ConnectorInfo - # - # ConnectorInfo - # - # @else - # @brief Getting ConnectorInfo - # - # This operation returns ConnectorInfo - # - # @endif - # - # const ConnectorInfo& profile(); - def profile(self): - self._rtcout.RTC_TRACE("profile()") - return self._profile - - ## - # @if jp - # @brief Connector ID - # - # Connector ID - # - # @else - # @brief Getting Connector ID - # - # This operation returns Connector ID - # - # @endif - # - # const char* id(); - def id(self): - self._rtcout.RTC_TRACE("id() = %s", self.profile().id) - return self.profile().id - - - ## - # @if jp - # @brief Connector ̾ - # - # Connector ̾ - # - # @else - # @brief Getting Connector name - # - # This operation returns Connector name - # - # @endif - # - # const char* name(); - def name(self): - self._rtcout.RTC_TRACE("name() = %s", self.profile().name) - return self.profile().name - - - # ReturnCode_t setConnectorInfo(ConnectorInfo info); - def setConnectorInfo(self, info): - self._profile = info - - if self._profile.properties.hasKey("serializer"): - endian = self._profile.properties.getProperty("serializer.cdr.endian") - if not endian: - self._rtcout.RTC_ERROR("InPortConnector.setConnectorInfo(): endian is not supported.") - return RTC.RTC_ERROR - - endian = OpenRTM_aist.split(endian, ",") # Maybe endian is ["little","big"] - endian = OpenRTM_aist.normalize(endian) # Maybe self._endian is "little" or "big" - - if endian == "little": + """ + """ + + ## + # @if jp + # @brief コンストラクタ + # @else + # @brief Constructor + # @endif + # + # OutPortConnector(ConnectorInfo& info); + def __init__(self, info): + self._rtcout = OpenRTM_aist.Manager.instance().getLogbuf("OutPortConnector") + self._profile = info self._endian = True - elif endian == "big": - self._endian = False - else: - return RTC.RTC_ERROR - - else: - self._endian = True # little endian - - return RTC.RTC_OK - - ## - # @if jp - # @brief 쥯³⡼ɤ - # - # - # @else - # @brief - # - # This - # - # @endif - # - # const char* name(); - def setDirectMode(self): - self._directMode = True - - ## - # @if jp - # @brief 쥯³⡼ɤȽ - # - # @return True쥯³⡼,falseʳ - # - # @else - # @brief - # - # @return - # - # @endif - # - # const char* name(); - def directMode(self): - return self._directMode - - - def write(self, data): - pass - def read(self, data): - pass \ No newline at end of file + self._directMode = False + self._dataType = None + return + + ## + # @if jp + # @brief デストラクタ + # @else + # @brief Destructor + # @endif + # + def __del__(self): + pass + + ## + # @if jp + # @brief ConnectorInfo 取得 + # + # ConnectorInfo を取得する + # + # @else + # @brief Getting ConnectorInfo + # + # This operation returns ConnectorInfo + # + # @endif + # + # const ConnectorInfo& profile(); + + def profile(self): + self._rtcout.RTC_TRACE("profile()") + return self._profile + + ## + # @if jp + # @brief Connector ID 取得 + # + # Connector ID を取得する + # + # @else + # @brief Getting Connector ID + # + # This operation returns Connector ID + # + # @endif + # + # const char* id(); + def id(self): + self._rtcout.RTC_TRACE("id() = %s", self.profile().id) + return self.profile().id + + ## + # @if jp + # @brief Connector 名取得 + # + # Connector 名を取得する + # + # @else + # @brief Getting Connector name + # + # This operation returns Connector name + # + # @endif + # + # const char* name(); + + def name(self): + self._rtcout.RTC_TRACE("name() = %s", self.profile().name) + return self.profile().name + + # ReturnCode_t setConnectorInfo(ConnectorInfo info); + + def setConnectorInfo(self, info): + self._profile = info + + if self._profile.properties.hasKey("serializer"): + endian = self._profile.properties.getProperty( + "serializer.cdr.endian") + if not endian: + self._rtcout.RTC_ERROR( + "InPortConnector.setConnectorInfo(): endian is not supported.") + return RTC.RTC_ERROR + + # Maybe endian is ["little","big"] + endian = OpenRTM_aist.split(endian, ",") + # Maybe self._endian is "little" or "big" + endian = OpenRTM_aist.normalize(endian[0]) + + if endian == "little": + self._endian = True + elif endian == "big": + self._endian = False + else: + return RTC.RTC_ERROR + + else: + self._endian = True # little endian + + return RTC.RTC_OK + + ## + # @if jp + # @brief ダイレクト接続モードに設定 + # + # + # @else + # @brief + # + # This + # + # @endif + # + # const char* name(); + def setDirectMode(self): + self._directMode = True + + ## + # @if jp + # @brief ダイレクト接続モードかの判定 + # + # @return True:ダイレクト接続モード,false:それ以外 + # + # @else + # @brief + # + # @return + # + # @endif + # + # const char* name(); + def directMode(self): + return self._directMode + + def write(self, data): + pass + + def read(self, data=None): + pass + + # + # @if jp + # @brief データを書き込める状態かを判定 + # @param self + # @param retry True:再確認、False:通常の書き込み確認 + # @return True:書き込み可能 + # @else + # @brief + # @param self + # @param retry + # @return + # @endif + def isWritable(self, retry): + return False + + # + # @if jp + # @brief データを読み込める状態かを判定 + # @param self + # @return True:読み込み可能 + # @else + # @brief + # @param self + # @return + # @return + # @endif + def isReadable(self): + return False + + # + # @if jp + # @brief データを書き込める状態かを判定 + # @param self + # @return True:書き込み可能 + # @else + # @brief + # @param self + # @return + # @endif + def setReadListener(self, listener): + pass + + # + # @if jp + # @brief データを読み込める状態かを判定 + # @param self + # @return True:読み込み可能 + # @else + # @brief + # @param self + # @return + # @return + # @endif + def setIsReadableListener(self, listener): + pass + + ## + # @if jp + # @brief コンシューマの設定 + # @else + # @brief set Consumer + # @endif + def setConsumer(self, consumer): + pass + + ## + # @if jp + # @brief コンシューマのインターフェースの登録を取り消す + # @param prop コネクタプロファイルのプロパティ + # @else + # @brief + # @param prop + # @endif + def unsubscribeInterface(self, prop): + pass + + # template + # void setDataTyep(DataType data); + + def setDataType(self, data): + self._dataType = data \ No newline at end of file diff --git a/OpenRTM_aist/OutPortConsumer.py b/OpenRTM_aist/OutPortConsumer.py index 8e3f7615..0815a69a 100644 --- a/OpenRTM_aist/OutPortConsumer.py +++ b/OpenRTM_aist/OutPortConsumer.py @@ -1,5 +1,5 @@ #!/usr/bin/env python -# -*- coding: euc-jp -*- +# -*- coding: utf-8 -*- ## # @file OutPortConsumer.py @@ -22,13 +22,13 @@ # # @class OutPortConsumer # -# @brief OutPortConsumer 饹 +# @brief OutPortConsumer クラス # -# ϥݡȥ󥷥塼ޤΤΥ饹 -# ƶݥ饹ϡʲδؿμ󶡤ʤФʤʤ -# - pull(): ǡ -# - subscribeInterface(): ǡΤؤϿ -# - unsubscribeInterface(): ǡΤϿ +# 出力ポートコンシューマのためのクラス +# 各具象クラスは、以下の関数の実装を提供しなければならない。 +# - pull(): データ受信 +# - subscribeInterface(): データ受信通知への登録 +# - unsubscribeInterface(): データ受信通知の登録解除 # # @since 0.4.0 # @@ -36,65 +36,72 @@ # @class OutPortConsumer # @brief OutPortConsumer class # @endif + + class OutPortConsumer(OpenRTM_aist.DataPortStatus): - """ - """ - - ## - # @if jp - # @brief Interface³Functor - # @else - # @brief Functor to subscribe the interface - # @endif - # - class subscribe: - # subscribe(const SDOPackage::NVList& prop) - def __init__(self, prop): - self._prop = prop - return - - # void operator()(OutPortConsumer* consumer) - def __call__(self, consumer): - consumer.subscribeInterface(self._prop) - return - - ## - # @if jp - # @brief Interface³Functor - # @else - # @brief Functor to unsubscribe the interface - # @endif - # - class unsubscribe: - # unsubscribe(const SDOPackage::NVList& prop) - def __init__(self, prop): - self._prop = prop - return - - # void operator()(OutPortConsumer* consumer) - def __call__(self, consumer): - consumer.unsubscribeInterface(self._prop) - return + """ + """ + + def get(self, data): + return self.CONNECTION_LOST + + def isReadable(self): + return True + + ## + # @if jp + # @brief Interface接続用Functor + # @else + # @brief Functor to subscribe the interface + # @endif + # + class subscribe: + # subscribe(const SDOPackage::NVList& prop) + def __init__(self, prop): + self._prop = prop + return + + # void operator()(OutPortConsumer* consumer) + def __call__(self, consumer): + consumer.subscribeInterface(self._prop) + return + + ## + # @if jp + # @brief Interface接続解除用Functor + # @else + # @brief Functor to unsubscribe the interface + # @endif + # + class unsubscribe: + # unsubscribe(const SDOPackage::NVList& prop) + def __init__(self, prop): + self._prop = prop + return + + # void operator()(OutPortConsumer* consumer) + def __call__(self, consumer): + consumer.unsubscribeInterface(self._prop) + return outportconsumerfactory = None -class OutPortConsumerFactory(OpenRTM_aist.Factory,OutPortConsumer): - def __init__(self): - OpenRTM_aist.Factory.__init__(self) - pass - - def __del__(self): - pass +class OutPortConsumerFactory(OpenRTM_aist.Factory, OutPortConsumer): + def __init__(self): + OpenRTM_aist.Factory.__init__(self) + pass + def __del__(self): + pass - def instance(): - global outportconsumerfactory + def instance(): + global outportconsumerfactory - if outportconsumerfactory is None: - outportconsumerfactory = OutPortConsumerFactory() + if outportconsumerfactory is None: + outportconsumerfactory = OutPortConsumerFactory() - return outportconsumerfactory + return outportconsumerfactory - instance = staticmethod(instance) + instance = staticmethod(instance) diff --git a/OpenRTM_aist/OutPortCorbaCdrConsumer.py b/OpenRTM_aist/OutPortCorbaCdrConsumer.py index 7829fd91..9be53e7b 100644 --- a/OpenRTM_aist/OutPortCorbaCdrConsumer.py +++ b/OpenRTM_aist/OutPortCorbaCdrConsumer.py @@ -1,5 +1,5 @@ #!/usr/bin/env python -# -*- coding: euc-jp -*- +# -*- coding: utf-8 -*- ## @@ -26,11 +26,11 @@ # @if jp # @class OutPortCorbaCdrConsumer # -# @brief OutPortCorbaCdrConsumer 饹 +# @brief OutPortCorbaCdrConsumer クラス # -# ̿ʤ CORBA Ѥϥݡȥ󥷥塼ޤμ饹 +# 通信手段に CORBA を利用した出力ポートコンシューマの実装クラス。 # -# @param DataType ܥݡȤˤưǡ +# @param DataType 本ポートにて扱うデータ型 # # @since 1.0.0 # @@ -39,7 +39,7 @@ # # @brief OutPortCorbaCdrConsumer class # -# This is an implementation class of the output Consumer +# This is an implementation class of the output Consumer # that uses CORBA for means of communication. # # @param DataType Data type for this port @@ -48,389 +48,398 @@ # # @endif # -class OutPortCorbaCdrConsumer(OpenRTM_aist.OutPortConsumer,OpenRTM_aist.CorbaConsumer): - """ - """ - - ## - # @if jp - # @brief 󥹥ȥ饯 - # - # 󥹥ȥ饯 - # - # @param buffer ܥݡȤ˳ƤХåե - # - # @else - # @brief Constructor - # - # Constructor - # - # @param buffer Buffer that is attached to this port - # - # @endif - # - def __init__(self): - OpenRTM_aist.CorbaConsumer.__init__(self) - self._rtcout = OpenRTM_aist.Manager.instance().getLogbuf("OutPortCorbaCdrConsumer") - self._buffer = None - self._profile = None - self._listeners = None - return - - ## - # @if jp - # @brief ǥȥ饯 - # - # ǥȥ饯 - # - # @else - # @brief Destructor - # - # Destructor - # - # @endif - # - def __del__(self, CorbaConsumer=OpenRTM_aist.CorbaConsumer): - self._rtcout.RTC_PARANOID("~OutPortCorbaCdrConsumer()") - CorbaConsumer.__del__(self) - pass - - - ## - # @if jp - # @brief - # - # OutPortConsumerγƼԤ饹ǤϡͿ줿 - # PropertiesɬפʾƳƼԤ init() - # ϡOutPortProviderľ太ӡ³ˤ줾ƤФ - # ǽ롣äơδؿʣƤФ뤳ȤꤷƵ - # Ҥ٤Ǥ롣 - # - # @param prop - # - # @else - # - # @brief Initializing configuration - # - # This operation would be called to configure in initialization. - # In the concrete class, configuration should be performed - # getting appropriate information from the given Properties data. - # This function might be called right after instantiation and - # connection sequence respectivly. Therefore, this function - # should be implemented assuming multiple call. - # - # @param prop Configuration information - # - # @endif - # - # virtual void init(coil::Properties& prop); - def init(self, prop): - self._rtcout.RTC_TRACE("init()") - return - - - ## - # @if jp - # @brief Хåե򥻥åȤ - # - # OutPortConsumerǡФХåե򥻥åȤ롣 - # Ǥ˥åȤ줿Хåե硢ΥХåեؤ - # ݥ󥿤Фƾ񤭤롣 - # OutPortProviderϥХåեνͭꤷƤʤΤǡ - # Хåեκϥ桼ǤǹԤʤФʤʤ - # - # @param buffer OutPortProviderǡФХåեؤΥݥ - # - # @else - # @brief Setting outside buffer's pointer - # - # A pointer to a buffer from which OutPortProvider retrieve data. - # If already buffer is set, previous buffer's pointer will be - # overwritten by the given pointer to a buffer. Since - # OutPortProvider does not assume ownership of the buffer - # pointer, destructor of the buffer should be done by user. - # - # @param buffer A pointer to a data buffer to be used by OutPortProvider - # - # @endif - # - # virtual void setBuffer(CdrBufferBase* buffer); - def setBuffer(self, buffer): - self._rtcout.RTC_TRACE("setBuffer()") - self._buffer = buffer - return - - - # void OutPortCorbaCdrConsumer::setListener(ConnectorInfo& info, - # ConnectorListeners* listeners) - def setListener(self, info, listeners): - self._rtcout.RTC_TRACE("setListener()") - self._listeners = listeners - self._profile = info - return - - - ## - # @if jp - # @brief ǡɤ߽Ф - # - # ꤵ줿ǡɤ߽Ф - # - # @param data ɤ߽Фǡ륪֥ - # - # @return ǡɤ߽Ф(ɤ߽Ф:trueɤ߽Ф:false) - # - # @else - # @brief Read data - # - # Read set data - # - # @param data Object to receive the read data - # - # @return Read result (Successful:true, Failed:false) - # - # @endif - # - # virtual ReturnCode get(cdrMemoryStream& data); - def get(self, data): - self._rtcout.RTC_PARANOID("get()") - - try: - outportcdr = self.getObject()._narrow(OpenRTM.OutPortCdr) - ret,cdr_data = outportcdr.get() - - if ret == OpenRTM.PORT_OK: - self._rtcout.RTC_DEBUG("get() successful") - data[0] = cdr_data - self.onReceived(data[0]) - self.onBufferWrite(data[0]) - - if self._buffer.full(): - self._rtcout.RTC_INFO("InPort buffer is full.") - self.onBufferFull(data[0]) - self.onReceiverFull(data[0]) - - self._buffer.put(data[0]) - self._buffer.advanceWptr() - self._buffer.advanceRptr() - - return self.PORT_OK - return self.convertReturn(ret,data[0]) - - except: - self._rtcout.RTC_WARN("Exception caught from OutPort.get().") - self._rtcout.RTC_ERROR(OpenRTM_aist.Logger.print_exception()) - return self.CONNECTION_LOST - - - - - ## - # @if jp - # @brief ǡΤؤϿ - # - # ꤵ줿ץѥƥ˴ŤơǡΤμϿ롣 - # - # @param properties Ͽ - # - # @return Ͽ(Ͽ:trueϿ:false) - # - # @else - # @brief Subscribe the data receive notification - # - # Subscribe the data receive notification based on specified property - # information - # - # @param properties Subscription information - # - # @return Subscription result (Successful:true, Failed:false) - # - # @endif - # - # virtual bool subscribeInterface(const SDOPackage::NVList& properties); - def subscribeInterface(self, properties): - self._rtcout.RTC_TRACE("subscribeInterface()") - index = OpenRTM_aist.NVUtil.find_index(properties,"dataport.corba_cdr.outport_ior") - - if index < 0: - self._rtcout.RTC_DEBUG("dataport.corba_cdr.outport_ior not found.") - return False - - if OpenRTM_aist.NVUtil.isString(properties,"dataport.corba_cdr.outport_ior"): - self._rtcout.RTC_DEBUG("dataport.corba_cdr.outport_ior found.") - ior = "" - #try: - ior = any.from_any(properties[index].value, keep_structs=True) - #except: - # self._rtcout.RTC_ERROR(OpenRTM_aist.Logger.print_exception()) - - orb = OpenRTM_aist.Manager.instance().getORB() - obj = orb.string_to_object(ior) - ret = self.setObject(obj) - if ret: - self._rtcout.RTC_DEBUG("CorbaConsumer was set successfully.") - else: - self._rtcout.RTC_ERROR("Invalid object reference.") - - return ret - - return False - - - ## - # @if jp - # @brief ǡΤϿ - # - # ǡΤμ꤫Ͽ롣 - # - # @param properties Ͽ - # - # @else - # @brief Unsubscribe the data receive notification - # - # Unsubscribe the data receive notification. - # - # @param properties Unsubscription information - # - # @endif - # - # virtual void unsubscribeInterface(const SDOPackage::NVList& properties); - def unsubscribeInterface(self, properties): - self._rtcout.RTC_TRACE("unsubscribeInterface()") - index = OpenRTM_aist.NVUtil.find_index(properties, - "dataport.corba_cdr.outport_ior") - if index < 0: - self._rtcout.RTC_DEBUG("dataport.corba_cdr.outport_ior not found.") - return - - ior = "" - - try: - ior = any.from_any(properties[index].value, keep_structs=True) - - if ior: - self._rtcout.RTC_DEBUG("dataport.corba_cdr.outport_ior found.") - orb = OpenRTM_aist.Manager.instance().getORB() - obj = orb.string_to_object(ior) - if self._ptr(True)._is_equivalent(obj): - self.releaseObject() - self._rtcout.RTC_DEBUG("CorbaConsumer's reference was released.") - return - - self._rtcout.RTC_ERROR("hmm. Inconsistent object reference.") - - except: - self._rtcout.RTC_ERROR(OpenRTM_aist.Logger.print_exception()) - - return - - ## - # @if jp - # @brief ꥿󥳡Ѵ (DataPortStatus -> BufferStatus) - # @else - # @brief Return codes conversion - # @endif - # - # ReturnCode convertReturn(::OpenRTM::PortStatus status, - # const cdrMemoryStream& data) - def convertReturn(self, status, data): - if status == OpenRTM.PORT_OK: - # never comes here - return self.PORT_OK - elif status == OpenRTM.PORT_ERROR: - self.onSenderError() - return self.PORT_ERROR +class OutPortCorbaCdrConsumer( + OpenRTM_aist.OutPortConsumer, OpenRTM_aist.CorbaConsumer): + """ + """ + + ## + # @if jp + # @brief コンストラクタ + # + # コンストラクタ + # + # @param buffer 本ポートに割り当てるバッファ + # + # @else + # @brief Constructor + # + # Constructor + # + # @param buffer Buffer that is attached to this port + # + # @endif + # + def __init__(self): + OpenRTM_aist.CorbaConsumer.__init__(self, OpenRTM.OutPortCdr) + self._rtcout = OpenRTM_aist.Manager.instance().getLogbuf("OutPortCorbaCdrConsumer") + self._buffer = None + self._profile = None + self._listeners = None + return + + ## + # @if jp + # @brief デストラクタ + # + # デストラクタ + # + # @else + # @brief Destructor + # + # Destructor + # + # @endif + # + def __del__(self, CorbaConsumer=OpenRTM_aist.CorbaConsumer): + self._rtcout.RTC_PARANOID("~OutPortCorbaCdrConsumer()") + CorbaConsumer.__del__(self) + pass + + ## + # @if jp + # @brief 設定初期化 + # + # OutPortConsumerの各種設定を行う。実装クラスでは、与えられた + # Propertiesから必要な情報を取得して各種設定を行う。この init() 関 + # 数は、OutPortProvider生成直後および、接続時にそれぞれ呼ばれる可 + # 能性がある。したがって、この関数は複数回呼ばれることを想定して記 + # 述されるべきである。 + # + # @param prop 設定情報 + # + # @else + # + # @brief Initializing configuration + # + # This operation would be called to configure in initialization. + # In the concrete class, configuration should be performed + # getting appropriate information from the given Properties data. + # This function might be called right after instantiation and + # connection sequence respectivly. Therefore, this function + # should be implemented assuming multiple call. + # + # @param prop Configuration information + # + # @endif + # + # virtual void init(coil::Properties& prop); + + def init(self, prop): + self._rtcout.RTC_TRACE("init()") + return + + ## + # @if jp + # @brief バッファをセットする + # + # OutPortConsumerがデータを取り出すバッファをセットする。 + # すでにセットされたバッファがある場合、以前のバッファへの + # ポインタに対して上書きされる。 + # OutPortProviderはバッファの所有権を仮定していないので、 + # バッファの削除はユーザの責任で行わなければならない。 + # + # @param buffer OutPortProviderがデータを取り出すバッファへのポインタ + # + # @else + # @brief Setting outside buffer's pointer + # + # A pointer to a buffer from which OutPortProvider retrieve data. + # If already buffer is set, previous buffer's pointer will be + # overwritten by the given pointer to a buffer. Since + # OutPortProvider does not assume ownership of the buffer + # pointer, destructor of the buffer should be done by user. + # + # @param buffer A pointer to a data buffer to be used by OutPortProvider + # + # @endif + # + # virtual void setBuffer(CdrBufferBase* buffer); + + def setBuffer(self, buffer): + self._rtcout.RTC_TRACE("setBuffer()") + self._buffer = buffer + return + + # void OutPortCorbaCdrConsumer::setListener(ConnectorInfo& info, + # ConnectorListeners* listeners) + + def setListener(self, info, listeners): + self._rtcout.RTC_TRACE("setListener()") + self._listeners = listeners + self._profile = info + return + + ## + # @if jp + # @brief データを読み出す + # + # 設定されたデータを読み出す。 + # + # @param data 読み出したデータを受け取るオブジェクト + # + # @return データ読み出し処理結果(読み出し成功:true、読み出し失敗:false) + # + # @else + # @brief Read data + # + # Read set data + # + # @param data Object to receive the read data + # + # @return Read result (Successful:true, Failed:false) + # + # @endif + # + # virtual ReturnCode get(cdrMemoryStream& data); + + def get(self): + self._rtcout.RTC_PARANOID("get()") + + try: + data = None + outportcdr = self._ptr() + ret, cdr_data = outportcdr.get() + + if ret == OpenRTM.PORT_OK: + self._rtcout.RTC_DEBUG("get() successful") + data = cdr_data + data = self.onReceived(data) + data = self.onBufferWrite(data) + + if self._buffer.full(): + self._rtcout.RTC_INFO("InPort buffer is full.") + data = self.onBufferFull(data) + data = self.onReceiverFull(data) + + self._buffer.put(data) + self._buffer.advanceWptr() + self._buffer.advanceRptr() + + return self.PORT_OK, data + return self.convertReturn(ret, data) + + except BaseException: + self._rtcout.RTC_WARN("Exception caught from OutPort.get().") + self._rtcout.RTC_ERROR(OpenRTM_aist.Logger.print_exception()) + return self.CONNECTION_LOST, None + + ## + # @if jp + # @brief データ受信通知への登録 + # + # 指定されたプロパティに基づいて、データ受信通知の受け取りに登録する。 + # + # @param properties 登録情報 + # + # @return 登録処理結果(登録成功:true、登録失敗:false) + # + # @else + # @brief Subscribe the data receive notification + # + # Subscribe the data receive notification based on specified property + # information + # + # @param properties Subscription information + # + # @return Subscription result (Successful:true, Failed:false) + # + # @endif + # + # virtual bool subscribeInterface(const SDOPackage::NVList& properties); + + def subscribeInterface(self, properties): + self._rtcout.RTC_TRACE("subscribeInterface()") + index = OpenRTM_aist.NVUtil.find_index( + properties, "dataport.corba_cdr.outport_ior") + + if index < 0: + self._rtcout.RTC_DEBUG("dataport.corba_cdr.outport_ior not found.") + return False + + if OpenRTM_aist.NVUtil.isString( + properties, "dataport.corba_cdr.outport_ior"): + self._rtcout.RTC_DEBUG("dataport.corba_cdr.outport_ior found.") + ior = "" + # try: + ior = any.from_any(properties[index].value, keep_structs=True) + # except: + # self._rtcout.RTC_ERROR(OpenRTM_aist.Logger.print_exception()) + + orb = OpenRTM_aist.Manager.instance().getORB() + obj = orb.string_to_object(ior) + ret = self.setObject(obj) + if ret: + self._rtcout.RTC_DEBUG("CorbaConsumer was set successfully.") + else: + self._rtcout.RTC_ERROR("Invalid object reference.") + + return ret + + return False + + ## + # @if jp + # @brief データ受信通知からの登録解除 + # + # データ受信通知の受け取りから登録を解除する。 + # + # @param properties 登録解除情報 + # + # @else + # @brief Unsubscribe the data receive notification + # + # Unsubscribe the data receive notification. + # + # @param properties Unsubscription information + # + # @endif + # + # virtual void unsubscribeInterface(const SDOPackage::NVList& properties); + + def unsubscribeInterface(self, properties): + self._rtcout.RTC_TRACE("unsubscribeInterface()") + index = OpenRTM_aist.NVUtil.find_index(properties, + "dataport.corba_cdr.outport_ior") + if index < 0: + self._rtcout.RTC_DEBUG("dataport.corba_cdr.outport_ior not found.") + return + + ior = "" + + try: + ior = any.from_any(properties[index].value, keep_structs=True) + + if ior: + self._rtcout.RTC_DEBUG("dataport.corba_cdr.outport_ior found.") + orb = OpenRTM_aist.Manager.instance().getORB() + obj = orb.string_to_object(ior) + if self._ptr(True)._is_equivalent(obj): + self.releaseObject() + self._rtcout.RTC_DEBUG( + "CorbaConsumer's reference was released.") + return + + self._rtcout.RTC_ERROR("hmm. Inconsistent object reference.") + + except BaseException: + self._rtcout.RTC_ERROR(OpenRTM_aist.Logger.print_exception()) + + return + + ## + # @if jp + # @brief リターンコード変換 (DataPortStatus -> BufferStatus) + # @else + # @brief Return codes conversion + # @endif + # + # ReturnCode convertReturn(::OpenRTM::PortStatus status, + # const cdrMemoryStream& data) + + def convertReturn(self, status, data): + if status == OpenRTM.PORT_OK: + # never comes here + return self.PORT_OK, data + + elif status == OpenRTM.PORT_ERROR: + self.onSenderError() + return self.PORT_ERROR, data + + elif status == OpenRTM.BUFFER_FULL: + # never comes here + return self.BUFFER_FULL, data + + elif status == OpenRTM.BUFFER_EMPTY: + self.onSenderEmpty() + return self.BUFFER_EMPTY, data + + elif status == OpenRTM.BUFFER_TIMEOUT: + self.onSenderTimeout() + return self.BUFFER_TIMEOUT, data + + elif status == OpenRTM.UNKNOWN_ERROR: + self.onSenderError() + return self.UNKNOWN_ERROR, data + + else: + self.onSenderError() + return self.UNKNOWN_ERROR, data - elif status == OpenRTM.BUFFER_FULL: - # never comes here - return self.BUFFER_FULL + ## + # @brief Connector data listener functions + # + # inline void onBufferWrite(const cdrMemoryStream& data) - elif status == OpenRTM.BUFFER_EMPTY: - self.onSenderEmpty() - return self.BUFFER_EMPTY + def onBufferWrite(self, data): + if self._listeners is not None and self._profile is not None: + _, data = self._listeners.notifyData( + OpenRTM_aist.ConnectorDataListenerType.ON_BUFFER_WRITE, self._profile, data) - elif status == OpenRTM.BUFFER_TIMEOUT: - self.onSenderTimeout() - return self.BUFFER_TIMEOUT + return data - elif status == OpenRTM.UNKNOWN_ERROR: - self.onSenderError() - return self.UNKNOWN_ERROR + # inline void onBufferFull(const cdrMemoryStream& data) + + def onBufferFull(self, data): + if self._listeners is not None and self._profile is not None: + _, data = self._listeners.notifyData( + OpenRTM_aist.ConnectorDataListenerType.ON_BUFFER_FULL, self._profile, data) - else: - self.onSenderError() - return self.UNKNOWN_ERROR + return data + # inline void onReceived(const cdrMemoryStream& data) + def onReceived(self, data): + if self._listeners is not None and self._profile is not None: + _, data = self._listeners.notifyData( + OpenRTM_aist.ConnectorDataListenerType.ON_RECEIVED, self._profile, data) - - ## - # @brief Connector data listener functions - # - # inline void onBufferWrite(const cdrMemoryStream& data) - def onBufferWrite(self, data): - if self._listeners is not None and self._profile is not None: - self._listeners.connectorData_[OpenRTM_aist.ConnectorDataListenerType.ON_BUFFER_WRITE].notify(self._profile, data) + return data - return - - - # inline void onBufferFull(const cdrMemoryStream& data) - def onBufferFull(self, data): - if self._listeners is not None and self._profile is not None: - self._listeners.connectorData_[OpenRTM_aist.ConnectorDataListenerType.ON_BUFFER_FULL].notify(self._profile, data) - - return - - - # inline void onReceived(const cdrMemoryStream& data) - def onReceived(self, data): - if self._listeners is not None and self._profile is not None: - self._listeners.connectorData_[OpenRTM_aist.ConnectorDataListenerType.ON_RECEIVED].notify(self._profile, data) + # inline void onReceiverFull(const cdrMemoryStream& data) - return + def onReceiverFull(self, data): + if self._listeners is not None and self._profile is not None: + _, data = self._listeners.notifyData( + OpenRTM_aist.ConnectorDataListenerType.ON_RECEIVER_FULL, self._profile, data) + return data - # inline void onReceiverFull(const cdrMemoryStream& data) - def onReceiverFull(self, data): - if self._listeners is not None and self._profile is not None: - self._listeners.connectorData_[OpenRTM_aist.ConnectorDataListenerType.ON_RECEIVER_FULL].notify(self._profile, data) + ## + # @brief Connector listener functions + # + # inline void onSenderEmpty() - return + def onSenderEmpty(self): + if self._listeners is not None and self._profile is not None: + self._listeners.notify( + OpenRTM_aist.ConnectorListenerType.ON_SENDER_EMPTY, self._profile) + return - ## - # @brief Connector listener functions - # - # inline void onSenderEmpty() - def onSenderEmpty(self): - if self._listeners is not None and self._profile is not None: - self._listeners.connector_[OpenRTM_aist.ConnectorListenerType.ON_SENDER_EMPTY].notify(self._profile) + # inline void onSenderTimeout() - return + def onSenderTimeout(self): + if self._listeners is not None and self._profile is not None: + self._listeners.notify( + OpenRTM_aist.ConnectorListenerType.ON_SENDER_TIMEOUT, self._profile) + return - # inline void onSenderTimeout() - def onSenderTimeout(self): - if self._listeners is not None and self._profile is not None: - self._listeners.connector_[OpenRTM_aist.ConnectorListenerType.ON_SENDER_TIMEOUT].notify(self._profile) + # inline void onSenderError() - return + def onSenderError(self): + if self._listeners is not None and self._profile is not None: + self._listeners.notify( + OpenRTM_aist.ConnectorListenerType.ON_SENDER_ERROR, self._profile) - - # inline void onSenderError() - def onSenderError(self): - if self._listeners is not None and self._profile is not None: - self._listeners.connector_[OpenRTM_aist.ConnectorListenerType.ON_SENDER_ERROR].notify(self._profile) - - return + return def OutPortCorbaCdrConsumerInit(): - factory = OpenRTM_aist.OutPortConsumerFactory.instance() - factory.addFactory("corba_cdr", - OpenRTM_aist.OutPortCorbaCdrConsumer, - OpenRTM_aist.Delete) - return + factory = OpenRTM_aist.OutPortConsumerFactory.instance() + factory.addFactory("corba_cdr", + OpenRTM_aist.OutPortCorbaCdrConsumer) + return diff --git a/OpenRTM_aist/OutPortCorbaCdrProvider.py b/OpenRTM_aist/OutPortCorbaCdrProvider.py index fdcc49cd..8f4c0cfb 100644 --- a/OpenRTM_aist/OutPortCorbaCdrProvider.py +++ b/OpenRTM_aist/OutPortCorbaCdrProvider.py @@ -1,5 +1,5 @@ #!/usr/bin/env python -# -*- coding: euc-jp -*- +# -*- coding: utf-8 -*- ## # @file OutPortCorbaProvider.py @@ -17,19 +17,19 @@ # - import OpenRTM_aist -import OpenRTM__POA,OpenRTM +import OpenRTM__POA +import OpenRTM ## # @if jp # @class OutPortCorbaCdrProvider -# @brief OutPortCorbaCdrProvider 饹 +# @brief OutPortCorbaCdrProvider クラス # -# OutPortProvider +# OutPortProvider # -# ǡž CORBA OpenRTM::OutPortCdr 󥿡եѤ -# pull ǡե¸ OutPort ץХ饹 +# データ転送に CORBA の OpenRTM::OutPortCdr インターフェースを利用し +# た、pull 型データフロー型を実現する OutPort プロバイダクラス。 # # @since 0.4.0 # @@ -45,404 +45,409 @@ # # @endif # + + class OutPortCorbaCdrProvider(OpenRTM_aist.OutPortProvider, OpenRTM__POA.OutPortCdr): - ## - # @if jp - # @brief 󥹥ȥ饯 - # - # 󥹥ȥ饯 - # - # @param buffer ץХ˳ƤХåե֥ - # - # @else - # @brief Constructor - # - # Constructor - # - # @param buffer Buffer object that is assigned to this provider - # - # @endif - # - def __init__(self): - OpenRTM_aist.OutPortProvider.__init__(self) - self.setInterfaceType("corba_cdr") - - # ConnectorProfile setting - self._objref = self._this() - - self._buffer = None - - # set outPort's reference - orb = OpenRTM_aist.Manager.instance().getORB() - - self._properties.append(OpenRTM_aist.NVUtil.newNV("dataport.corba_cdr.outport_ior", - orb.object_to_string(self._objref))) - self._properties.append(OpenRTM_aist.NVUtil.newNV("dataport.corba_cdr.outport_ref", - self._objref)) - - self._listeners = None - self._connector = None - self._profile = None - return - - - ## - # @if jp - # @brief ǥȥ饯 - # - # ǥȥ饯 - # - # @else - # @brief Destructor - # - # Destructor - # - # @endif - # - def __del__(self): - return - - ## - # @if jp - # @brief λ - # - # @else - # @brief - # - # - # - # @endif - # - def exit(self): - oid = self._default_POA().servant_to_id(self) - self._default_POA().deactivate_object(oid) - - ## - # @if jp - # @brief - # - # InPortConsumerγƼԤ饹ǤϡͿ줿 - # PropertiesɬפʾƳƼԤ init() - # ϡOutPortProviderľ太ӡ³ˤ줾ƤФ - # ǽ롣äơδؿʣƤФ뤳ȤꤷƵ - # Ҥ٤Ǥ롣 - # - # @param prop - # - # @else - # - # @brief Initializing configuration - # - # This operation would be called to configure in initialization. - # In the concrete class, configuration should be performed - # getting appropriate information from the given Properties data. - # This function might be called right after instantiation and - # connection sequence respectivly. Therefore, this function - # should be implemented assuming multiple call. - # - # @param prop Configuration information - # - # @endif - # - # virtual void init(coil::Properties& prop); - def init(self, prop): - pass - - - ## - # @if jp - # @brief Хåե򥻥åȤ - # - # OutPortProviderǡФХåե򥻥åȤ롣 - # Ǥ˥åȤ줿Хåե硢ΥХåեؤ - # ݥ󥿤Фƾ񤭤롣 - # OutPortProviderϥХåեνͭꤷƤʤΤǡ - # Хåեκϥ桼ǤǹԤʤФʤʤ - # - # @param buffer OutPortProviderǡФХåեؤΥݥ - # - # @else - # @brief Setting outside buffer's pointer - # - # A pointer to a buffer from which OutPortProvider retrieve data. - # If already buffer is set, previous buffer's pointer will be - # overwritten by the given pointer to a buffer. Since - # OutPortProvider does not assume ownership of the buffer - # pointer, destructor of the buffer should be done by user. - # - # @param buffer A pointer to a data buffer to be used by OutPortProvider - # - # @endif - # - # virtual void setBuffer(BufferBase* buffer); - def setBuffer(self, buffer): - self._buffer = buffer - return - - - ## - # @if jp - # @brief ꥹʤꤹ롣 - # - # OutPort ϥǡˤƼ磻٥ȤФΥꥹ - # ֥Ȥ򥳡뤹륳Хå󶡤롣ܺ٤ - # ConnectorListener.h ConnectorDataListener, ConnectorListener - # 򻲾ȤΤȡOutPortCorbaCdrProvider ǤϡʲΥХå - # 󶡤롣 - # - # - ON_BUFFER_READ - # - ON_SEND - # - ON_BUFFER_EMPTY - # - ON_BUFFER_READ_TIMEOUT - # - ON_SENDER_EMPTY - # - ON_SENDER_TIMEOUT - # - ON_SENDER_ERROR - # - # @param info ³ - # @param listeners ꥹʥ֥ - # - # @else - # @brief Set the listener. - # - # OutPort provides callback functionality that calls specific - # listener objects according to the events in the data publishing - # process. For details, see documentation of - # ConnectorDataListener class and ConnectorListener class in - # ConnectorListener.h. In this OutPortCorbaCdrProvider provides - # the following callbacks. - # - # - ON_BUFFER_READ - # - ON_SEND - # - ON_BUFFER_EMPTY - # - ON_BUFFER_READ_TIMEOUT - # - ON_SENDER_EMPTY - # - ON_SENDER_TIMEOUT - # - ON_SENDER_ERROR - # - # @param info Connector information - # @param listeners Listener objects - # - # @endif - # - # virtual void setListener(ConnectorInfo& info, - # ConnectorListeners* listeners); - def setListener(self, info, listeners): - self._profile = info - self._listeners = listeners - return - - - ## - # @if jp - # @brief Connectorꤹ롣 - # - # OutPort ³Ω OutPortConnector ֥Ȥ - # ֥ȤΥݥ󥿤ȶˤδؿƤӽФͭ - # OutPort ݻΤ OutPortProvider OutPortConnector - # ƤϤʤ - # - # @param connector OutPortConnector - # - # @else - # @brief set Connector - # - # OutPort creates OutPortConnector object when it establishes - # connection between OutPort and InPort, and it calls this - # function with a pointer to the connector object. Since the - # OutPort has the ownership of this connector, OutPortProvider - # should not delete it. - # - # @param connector OutPortConnector - # - # @endif - # - # virtual void setConnector(OutPortConnector* connector); - def setConnector(self, connector): - self._connector = connector - return - - - ## - # @if jp - # @brief [CORBA interface] Хåեǡ - # - # ꤵ줿Хåեǡ롣 - # - # @return ǡ - # - # @else - # @brief [CORBA interface] Get data from the buffer - # - # Get data from the internal buffer. - # - # @return Data got from the buffer. - # - # @endif - # - # virtual ::OpenRTM::PortStatus get(::OpenRTM::CdrData_out data); - def get(self): - self._rtcout.RTC_PARANOID("OutPortCorbaCdrProvider.get()") - if not self._connector: - self.onSenderError() - return (OpenRTM.UNKNOWN_ERROR, "") - - try: - cdr = [None] - ret = self._connector.read(cdr) - - if ret == OpenRTM_aist.BufferStatus.BUFFER_OK: - if not cdr[0]: - self._rtcout.RTC_ERROR("buffer is empty.") - return (OpenRTM.BUFFER_EMPTY, "") - - except: - self._rtcout.RTC_TRACE(OpenRTM_aist.Logger.print_exception()) - return (OpenRTM.UNKNOWN_ERROR, "") - - return self.convertReturn(ret, cdr[0]) - - ## - # @if jp - # @brief ON_BUFFER_READ ΥꥹʤΤ롣 - # @param data cdrMemoryStream - # @else - # @brief Notify an ON_BUFFER_READ event to listeners - # @param data cdrMemoryStream - # @endif - # - # inline void onBufferRead(const cdrMemoryStream& data) - def onBufferRead(self, data): - if self._listeners and self._profile: - self._listeners.connectorData_[OpenRTM_aist.ConnectorDataListenerType.ON_BUFFER_READ].notify(self._profile, data) - return - - ## - # @if jp - # @brief ON_SEND ΥꥹʤΤ롣 - # @param data cdrMemoryStream - # @else - # @brief Notify an ON_SEND event to listeners - # @param data cdrMemoryStream - # @endif - # - # inline void onSend(const cdrMemoryStream& data) - def onSend(self, data): - if self._listeners and self._profile: - self._listeners.connectorData_[OpenRTM_aist.ConnectorDataListenerType.ON_SEND].notify(self._profile, data) - return - - ## - # @if jp - # @brief ON_BUFFER_EMPTYΥꥹʤΤ롣 - # @else - # @brief Notify an ON_BUFFER_EMPTY event to listeners - # @endif - # - # inline void onBufferEmpty() - def onBufferEmpty(self): - if self._listeners and self._profile: - self._listeners.connector_[OpenRTM_aist.ConnectorListenerType.ON_BUFFER_EMPTY].notify(self._profile) - return - - ## - # @if jp - # @brief ON_BUFFER_READ_TIMEOUT ΥꥹʤΤ롣 - # @else - # @brief Notify an ON_BUFFER_READ_TIMEOUT event to listeners - # @endif - # - # inline void onBufferReadTimeout() - def onBufferReadTimeout(self): - if self._listeners and self._profile: - self._listeners.connector_[OpenRTM_aist.ConnectorListenerType.ON_BUFFER_READ_TIMEOUT].notify(self._profile) - return - - ## - # @if jp - # @brief ON_SENDER_EMPTYΥꥹʤΤ롣 - # @else - # @brief Notify an ON_SENDER_EMPTY event to listeners - # @endif - # - # inline void onSenderEmpty() - def onSenderEmpty(self): - if self._listeners and self._profile: - self._listeners.connector_[OpenRTM_aist.ConnectorListenerType.ON_SENDER_EMPTY].notify(self._profile) - return - - ## - # @if jp - # @brief ON_SENDER_TIMEOUT ΥꥹʤΤ롣 - # @else - # @brief Notify an ON_SENDER_TIMEOUT event to listeners - # @endif - # - # inline void onSenderTimeout() - def onSenderTimeout(self): - if self._listeners and self._profile: - self._listeners.connector_[OpenRTM_aist.ConnectorListenerType.ON_SENDER_TIMEOUT].notify(self._profile) - return - - ## - # @if jp - # @brief ON_SENDER_ERRORΥꥹʤΤ롣 - # @else - # @brief Notify an ON_SENDER_ERROR event to listeners - # @endif - # - # inline void onSenderError() - def onSenderError(self): - if self._listeners and self._profile: - self._listeners.connector_[OpenRTM_aist.ConnectorListenerType.ON_SENDER_ERROR].notify(self._profile) - return - - - ## - # @if jp - # @brief ꥿󥳡Ѵ - # @else - # @brief Return codes conversion - # @endif - # - # ::OpenRTM::PortStatus convertReturn(BufferStatus::Enum status, - # const cdrMemoryStream& data); - def convertReturn(self, status, data): - if status == OpenRTM_aist.BufferStatus.BUFFER_OK: - self.onBufferRead(data) - self.onSend(data) - return (OpenRTM.PORT_OK, data) - - elif status == OpenRTM_aist.BufferStatus.BUFFER_ERROR: - self.onSenderError() - return (OpenRTM.PORT_ERROR, data) - - elif status == OpenRTM_aist.BufferStatus.BUFFER_FULL: - # never come here - return (OpenRTM.BUFFER_FULL, data) - - elif status == OpenRTM_aist.BufferStatus.BUFFER_EMPTY: - self.onBufferEmpty() - self.onSenderEmpty() - return (OpenRTM.BUFFER_EMPTY, data) - - elif status == OpenRTM_aist.BufferStatus.PRECONDITION_NOT_MET: - self.onSenderError() - return (OpenRTM.PORT_ERROR, data) - - elif status == OpenRTM_aist.BufferStatus.TIMEOUT: - self.onBufferReadTimeout() - self.onSenderTimeout() - return (OpenRTM.BUFFER_TIMEOUT, data) - - else: - return (OpenRTM.UNKNOWN_ERROR, data) - - + ## + # @if jp + # @brief コンストラクタ + # + # コンストラクタ + # + # @param buffer 当該プロバイダに割り当てるバッファオブジェクト + # + # @else + # @brief Constructor + # + # Constructor + # + # @param buffer Buffer object that is assigned to this provider + # + # @endif + # + def __init__(self): + OpenRTM_aist.OutPortProvider.__init__(self) + self.setInterfaceType("corba_cdr") + + # ConnectorProfile setting + self._objref = self._this() + + self._buffer = None + + # set outPort's reference + orb = OpenRTM_aist.Manager.instance().getORB() + + self._properties.append(OpenRTM_aist.NVUtil.newNV("dataport.corba_cdr.outport_ior", + orb.object_to_string(self._objref))) + self._properties.append(OpenRTM_aist.NVUtil.newNV("dataport.corba_cdr.outport_ref", + self._objref)) + + self._listeners = None + self._connector = None + self._profile = None + return + + ## + # @if jp + # @brief デストラクタ + # + # デストラクタ + # + # @else + # @brief Destructor + # + # Destructor + # + # @endif + # + + def __del__(self): + return + + ## + # @if jp + # @brief 終了処理 + # + # @else + # @brief + # + # + # + # @endif + # + def exit(self): + oid = self._default_POA().servant_to_id(self) + self._default_POA().deactivate_object(oid) + + ## + # @if jp + # @brief 設定初期化 + # + # InPortConsumerの各種設定を行う。実装クラスでは、与えられた + # Propertiesから必要な情報を取得して各種設定を行う。この init() 関 + # 数は、OutPortProvider生成直後および、接続時にそれぞれ呼ばれる可 + # 能性がある。したがって、この関数は複数回呼ばれることを想定して記 + # 述されるべきである。 + # + # @param prop 設定情報 + # + # @else + # + # @brief Initializing configuration + # + # This operation would be called to configure in initialization. + # In the concrete class, configuration should be performed + # getting appropriate information from the given Properties data. + # This function might be called right after instantiation and + # connection sequence respectivly. Therefore, this function + # should be implemented assuming multiple call. + # + # @param prop Configuration information + # + # @endif + # + # virtual void init(coil::Properties& prop); + def init(self, prop): + pass + + ## + # @if jp + # @brief バッファをセットする + # + # OutPortProviderがデータを取り出すバッファをセットする。 + # すでにセットされたバッファがある場合、以前のバッファへの + # ポインタに対して上書きされる。 + # OutPortProviderはバッファの所有権を仮定していないので、 + # バッファの削除はユーザの責任で行わなければならない。 + # + # @param buffer OutPortProviderがデータを取り出すバッファへのポインタ + # + # @else + # @brief Setting outside buffer's pointer + # + # A pointer to a buffer from which OutPortProvider retrieve data. + # If already buffer is set, previous buffer's pointer will be + # overwritten by the given pointer to a buffer. Since + # OutPortProvider does not assume ownership of the buffer + # pointer, destructor of the buffer should be done by user. + # + # @param buffer A pointer to a data buffer to be used by OutPortProvider + # + # @endif + # + # virtual void setBuffer(BufferBase* buffer); + + def setBuffer(self, buffer): + self._buffer = buffer + return + + ## + # @if jp + # @brief リスナを設定する。 + # + # OutPort はデータ送信処理における各種イベントに対して特定のリスナ + # オブジェクトをコールするコールバック機構を提供する。詳細は + # ConnectorListener.h の ConnectorDataListener, ConnectorListener + # 等を参照のこと。OutPortCorbaCdrProvider では、以下のコールバック + # が提供される。 + # + # - ON_BUFFER_READ + # - ON_SEND + # - ON_BUFFER_EMPTY + # - ON_BUFFER_READ_TIMEOUT + # - ON_SENDER_EMPTY + # - ON_SENDER_TIMEOUT + # - ON_SENDER_ERROR + # + # @param info 接続情報 + # @param listeners リスナオブジェクト + # + # @else + # @brief Set the listener. + # + # OutPort provides callback functionality that calls specific + # listener objects according to the events in the data publishing + # process. For details, see documentation of + # ConnectorDataListener class and ConnectorListener class in + # ConnectorListener.h. In this OutPortCorbaCdrProvider provides + # the following callbacks. + # + # - ON_BUFFER_READ + # - ON_SEND + # - ON_BUFFER_EMPTY + # - ON_BUFFER_READ_TIMEOUT + # - ON_SENDER_EMPTY + # - ON_SENDER_TIMEOUT + # - ON_SENDER_ERROR + # + # @param info Connector information + # @param listeners Listener objects + # + # @endif + # + # virtual void setListener(ConnectorInfo& info, + # ConnectorListeners* listeners); + + def setListener(self, info, listeners): + self._profile = info + self._listeners = listeners + return + + ## + # @if jp + # @brief Connectorを設定する。 + # + # OutPort は接続確立時に OutPortConnector オブジェクトを生成し、生 + # 成したオブジェクトのポインタと共にこの関数を呼び出す。所有権は + # OutPort が保持するので OutPortProvider は OutPortConnector を削 + # 除してはいけない。 + # + # @param connector OutPortConnector + # + # @else + # @brief set Connector + # + # OutPort creates OutPortConnector object when it establishes + # connection between OutPort and InPort, and it calls this + # function with a pointer to the connector object. Since the + # OutPort has the ownership of this connector, OutPortProvider + # should not delete it. + # + # @param connector OutPortConnector + # + # @endif + # + # virtual void setConnector(OutPortConnector* connector); + + def setConnector(self, connector): + self._connector = connector + return + + ## + # @if jp + # @brief [CORBA interface] バッファからデータを取得する + # + # 設定された内部バッファからデータを取得する。 + # + # @return 取得データ + # + # @else + # @brief [CORBA interface] Get data from the buffer + # + # Get data from the internal buffer. + # + # @return Data got from the buffer. + # + # @endif + # + # virtual ::OpenRTM::PortStatus get(::OpenRTM::CdrData_out data); + + def get(self): + self._rtcout.RTC_PARANOID("OutPortCorbaCdrProvider.get()") + if not self._connector: + self.onSenderError() + return (OpenRTM.UNKNOWN_ERROR, "") + + try: + ret, cdr = self._connector.read() + + if ret == OpenRTM_aist.BufferStatus.BUFFER_OK: + if not cdr: + self._rtcout.RTC_ERROR("buffer is empty.") + return (OpenRTM.BUFFER_EMPTY, "") + + except BaseException: + self._rtcout.RTC_TRACE(OpenRTM_aist.Logger.print_exception()) + return (OpenRTM.UNKNOWN_ERROR, "") + + return self.convertReturn(ret, cdr) + + ## + # @if jp + # @brief ON_BUFFER_READ のリスナへ通知する。 + # @param data cdrMemoryStream + # @else + # @brief Notify an ON_BUFFER_READ event to listeners + # @param data cdrMemoryStream + # @endif + # + # inline void onBufferRead(const cdrMemoryStream& data) + def onBufferRead(self, data): + if self._listeners and self._profile: + _, data = self._listeners.notifyData( + OpenRTM_aist.ConnectorDataListenerType.ON_BUFFER_READ, self._profile, data) + return data + + ## + # @if jp + # @brief ON_SEND のリスナへ通知する。 + # @param data cdrMemoryStream + # @else + # @brief Notify an ON_SEND event to listeners + # @param data cdrMemoryStream + # @endif + # + # inline void onSend(const cdrMemoryStream& data) + def onSend(self, data): + if self._listeners and self._profile: + _, data = self._listeners.notifyData( + OpenRTM_aist.ConnectorDataListenerType.ON_SEND, self._profile, data) + return data + + ## + # @if jp + # @brief ON_BUFFER_EMPTYのリスナへ通知する。 + # @else + # @brief Notify an ON_BUFFER_EMPTY event to listeners + # @endif + # + # inline void onBufferEmpty() + def onBufferEmpty(self): + if self._listeners and self._profile: + self._listeners.notify( + OpenRTM_aist.ConnectorListenerType.ON_BUFFER_EMPTY, self._profile) + return + + ## + # @if jp + # @brief ON_BUFFER_READ_TIMEOUT のリスナへ通知する。 + # @else + # @brief Notify an ON_BUFFER_READ_TIMEOUT event to listeners + # @endif + # + # inline void onBufferReadTimeout() + def onBufferReadTimeout(self): + if self._listeners and self._profile: + self._listeners.notify( + OpenRTM_aist.ConnectorListenerType.ON_BUFFER_READ_TIMEOUT, self._profile) + return + + ## + # @if jp + # @brief ON_SENDER_EMPTYのリスナへ通知する。 + # @else + # @brief Notify an ON_SENDER_EMPTY event to listeners + # @endif + # + # inline void onSenderEmpty() + def onSenderEmpty(self): + if self._listeners and self._profile: + self._listeners.notify( + OpenRTM_aist.ConnectorListenerType.ON_SENDER_EMPTY, self._profile) + return + + ## + # @if jp + # @brief ON_SENDER_TIMEOUT のリスナへ通知する。 + # @else + # @brief Notify an ON_SENDER_TIMEOUT event to listeners + # @endif + # + # inline void onSenderTimeout() + def onSenderTimeout(self): + if self._listeners and self._profile: + self._listeners.notify( + OpenRTM_aist.ConnectorListenerType.ON_SENDER_TIMEOUT, self._profile) + return + + ## + # @if jp + # @brief ON_SENDER_ERRORのリスナへ通知する。 + # @else + # @brief Notify an ON_SENDER_ERROR event to listeners + # @endif + # + # inline void onSenderError() + def onSenderError(self): + if self._listeners and self._profile: + self._listeners.notify( + OpenRTM_aist.ConnectorListenerType.ON_SENDER_ERROR, self._profile) + return + + ## + # @if jp + # @brief リターンコード変換 + # @else + # @brief Return codes conversion + # @endif + # + # ::OpenRTM::PortStatus convertReturn(BufferStatus::Enum status, + # const cdrMemoryStream& data); + + def convertReturn(self, status, data): + if status == OpenRTM_aist.BufferStatus.BUFFER_OK: + data = self.onBufferRead(data) + data = self.onSend(data) + return (OpenRTM.PORT_OK, data) + + elif status == OpenRTM_aist.BufferStatus.BUFFER_ERROR: + self.onSenderError() + return (OpenRTM.PORT_ERROR, data) + + elif status == OpenRTM_aist.BufferStatus.BUFFER_FULL: + # never come here + return (OpenRTM.BUFFER_FULL, data) + + elif status == OpenRTM_aist.BufferStatus.BUFFER_EMPTY: + self.onBufferEmpty() + self.onSenderEmpty() + return (OpenRTM.BUFFER_EMPTY, data) + + elif status == OpenRTM_aist.BufferStatus.PRECONDITION_NOT_MET: + self.onSenderError() + return (OpenRTM.PORT_ERROR, data) + + elif status == OpenRTM_aist.BufferStatus.TIMEOUT: + self.onBufferReadTimeout() + self.onSenderTimeout() + return (OpenRTM.BUFFER_TIMEOUT, data) + + else: + return (OpenRTM.UNKNOWN_ERROR, data) def OutPortCorbaCdrProviderInit(): - factory = OpenRTM_aist.OutPortProviderFactory.instance() - factory.addFactory("corba_cdr", - OpenRTM_aist.OutPortCorbaCdrProvider, - OpenRTM_aist.Delete) + factory = OpenRTM_aist.OutPortProviderFactory.instance() + factory.addFactory("corba_cdr", + OpenRTM_aist.OutPortCorbaCdrProvider) diff --git a/OpenRTM_aist/OutPortDSConsumer.py b/OpenRTM_aist/OutPortDSConsumer.py index cb5b53a1..7c70ed82 100644 --- a/OpenRTM_aist/OutPortDSConsumer.py +++ b/OpenRTM_aist/OutPortDSConsumer.py @@ -1,5 +1,5 @@ #!/usr/bin/env python -# -*- coding: euc-jp -*- +# -*- coding: utf-8 -*- ## @@ -16,7 +16,6 @@ # All rights reserved. - from omniORB import any import OpenRTM_aist import RTC @@ -25,11 +24,11 @@ # @if jp # @class OutPortDSConsumer # -# @brief OutPortDSConsumer 饹 +# @brief OutPortDSConsumer クラス # -# ̿ʤ CORBA Ѥϥݡȥ󥷥塼ޤμ饹 +# 通信手段に CORBA を利用した出力ポートコンシューマの実装クラス。 # -# @param DataType ܥݡȤˤưǡ +# @param DataType 本ポートにて扱うデータ型 # # @since 1.2.0 # @@ -38,7 +37,7 @@ # # @brief OutPortDSConsumer class # -# This is an implementation class of the output Consumer +# This is an implementation class of the output Consumer # that uses CORBA for means of communication. # # @param DataType Data type for this port @@ -47,389 +46,400 @@ # # @endif # -class OutPortDSConsumer(OpenRTM_aist.OutPortConsumer,OpenRTM_aist.CorbaConsumer): - """ - """ - - ## - # @if jp - # @brief 󥹥ȥ饯 - # - # 󥹥ȥ饯 - # - # @param buffer ܥݡȤ˳ƤХåե - # - # @else - # @brief Constructor - # - # Constructor - # - # @param buffer Buffer that is attached to this port - # - # @endif - # - def __init__(self): - OpenRTM_aist.CorbaConsumer.__init__(self) - self._rtcout = OpenRTM_aist.Manager.instance().getLogbuf("OutPortDSConsumer") - self._buffer = None - self._profile = None - self._listeners = None - return - - ## - # @if jp - # @brief ǥȥ饯 - # - # ǥȥ饯 - # - # @else - # @brief Destructor - # - # Destructor - # - # @endif - # - def __del__(self, CorbaConsumer=OpenRTM_aist.CorbaConsumer): - self._rtcout.RTC_PARANOID("~OutPortDSConsumer()") - CorbaConsumer.__del__(self) - pass - - - ## - # @if jp - # @brief - # - # OutPortConsumerγƼԤ饹ǤϡͿ줿 - # PropertiesɬפʾƳƼԤ init() - # ϡOutPortProviderľ太ӡ³ˤ줾ƤФ - # ǽ롣äơδؿʣƤФ뤳ȤꤷƵ - # Ҥ٤Ǥ롣 - # - # @param prop - # - # @else - # - # @brief Initializing configuration - # - # This operation would be called to configure in initialization. - # In the concrete class, configuration should be performed - # getting appropriate information from the given Properties data. - # This function might be called right after instantiation and - # connection sequence respectivly. Therefore, this function - # should be implemented assuming multiple call. - # - # @param prop Configuration information - # - # @endif - # - # virtual void init(coil::Properties& prop); - def init(self, prop): - self._rtcout.RTC_TRACE("init()") - return - - - ## - # @if jp - # @brief Хåե򥻥åȤ - # - # OutPortConsumerǡФХåե򥻥åȤ롣 - # Ǥ˥åȤ줿Хåե硢ΥХåեؤ - # ݥ󥿤Фƾ񤭤롣 - # OutPortProviderϥХåեνͭꤷƤʤΤǡ - # Хåեκϥ桼ǤǹԤʤФʤʤ - # - # @param buffer OutPortProviderǡФХåեؤΥݥ - # - # @else - # @brief Setting outside buffer's pointer - # - # A pointer to a buffer from which OutPortProvider retrieve data. - # If already buffer is set, previous buffer's pointer will be - # overwritten by the given pointer to a buffer. Since - # OutPortProvider does not assume ownership of the buffer - # pointer, destructor of the buffer should be done by user. - # - # @param buffer A pointer to a data buffer to be used by OutPortProvider - # - # @endif - # - # virtual void setBuffer(CdrBufferBase* buffer); - def setBuffer(self, buffer): - self._rtcout.RTC_TRACE("setBuffer()") - self._buffer = buffer - return - - - # void OutPortDSConsumer::setListener(ConnectorInfo& info, - # ConnectorListeners* listeners) - def setListener(self, info, listeners): - self._rtcout.RTC_TRACE("setListener()") - self._listeners = listeners - self._profile = info - return - - - ## - # @if jp - # @brief ǡɤ߽Ф - # - # ꤵ줿ǡɤ߽Ф - # - # @param data ɤ߽Фǡ륪֥ - # - # @return ǡɤ߽Ф(ɤ߽Ф:trueɤ߽Ф:false) - # - # @else - # @brief Read data - # - # Read set data - # - # @param data Object to receive the read data - # - # @return Read result (Successful:true, Failed:false) - # - # @endif - # - # virtual ReturnCode get(cdrMemoryStream& data); - def get(self, data): - self._rtcout.RTC_PARANOID("get()") - - try: - ds = self.getObject()._narrow(RTC.DataPullService) - ret,cdr_data = ds.pull() - - if ret == RTC.PORT_OK: - self._rtcout.RTC_DEBUG("get() successful") - data[0] = cdr_data - self.onReceived(data[0]) - self.onBufferWrite(data[0]) - - if self._buffer.full(): - self._rtcout.RTC_INFO("InPort buffer is full.") - self.onBufferFull(data[0]) - self.onReceiverFull(data[0]) - - self._buffer.put(data[0]) - self._buffer.advanceWptr() - self._buffer.advanceRptr() - - return self.PORT_OK - return self.convertReturn(ret,data[0]) - - except: - self._rtcout.RTC_WARN("Exception caught from OutPort.get().") - self._rtcout.RTC_ERROR(OpenRTM_aist.Logger.print_exception()) - return self.CONNECTION_LOST - - - - - ## - # @if jp - # @brief ǡΤؤϿ - # - # ꤵ줿ץѥƥ˴ŤơǡΤμϿ롣 - # - # @param properties Ͽ - # - # @return Ͽ(Ͽ:trueϿ:false) - # - # @else - # @brief Subscribe the data receive notification - # - # Subscribe the data receive notification based on specified property - # information - # - # @param properties Subscription information - # - # @return Subscription result (Successful:true, Failed:false) - # - # @endif - # - # virtual bool subscribeInterface(const SDOPackage::NVList& properties); - def subscribeInterface(self, properties): - self._rtcout.RTC_TRACE("subscribeInterface()") - index = OpenRTM_aist.NVUtil.find_index(properties,"dataport.data_service.outport_ior") - - if index < 0: - self._rtcout.RTC_DEBUG("dataport.data_service.outport_ior not found.") - return False - - if OpenRTM_aist.NVUtil.isString(properties,"dataport.data_service.outport_ior"): - self._rtcout.RTC_DEBUG("dataport.data_service.outport_ior found.") - ior = "" - #try: - ior = any.from_any(properties[index].value, keep_structs=True) - #except: - # self._rtcout.RTC_ERROR(OpenRTM_aist.Logger.print_exception()) - - orb = OpenRTM_aist.Manager.instance().getORB() - obj = orb.string_to_object(ior) - ret = self.setObject(obj) - if ret: - self._rtcout.RTC_DEBUG("CorbaConsumer was set successfully.") - else: - self._rtcout.RTC_ERROR("Invalid object reference.") - - return ret - - return False - - - ## - # @if jp - # @brief ǡΤϿ - # - # ǡΤμ꤫Ͽ롣 - # - # @param properties Ͽ - # - # @else - # @brief Unsubscribe the data receive notification - # - # Unsubscribe the data receive notification. - # - # @param properties Unsubscription information - # - # @endif - # - # virtual void unsubscribeInterface(const SDOPackage::NVList& properties); - def unsubscribeInterface(self, properties): - self._rtcout.RTC_TRACE("unsubscribeInterface()") - index = OpenRTM_aist.NVUtil.find_index(properties, - "dataport.data_service.outport_ior") - if index < 0: - self._rtcout.RTC_DEBUG("dataport.data_service.outport_ior not found.") - return - - ior = "" - - try: - ior = any.from_any(properties[index].value, keep_structs=True) - - if ior: - self._rtcout.RTC_DEBUG("dataport.data_service.outport_ior found.") - orb = OpenRTM_aist.Manager.instance().getORB() - obj = orb.string_to_object(ior) - if self._ptr(True)._is_equivalent(obj): - self.releaseObject() - self._rtcout.RTC_DEBUG("CorbaConsumer's reference was released.") - return - - self._rtcout.RTC_ERROR("hmm. Inconsistent object reference.") - - except: - self._rtcout.RTC_ERROR(OpenRTM_aist.Logger.print_exception()) - - return - - - ## - # @if jp - # @brief ꥿󥳡Ѵ (DataPortStatus -> BufferStatus) - # @else - # @brief Return codes conversion - # @endif - # - # ReturnCode convertReturn(::OpenRTM::PortStatus status, - # const cdrMemoryStream& data) - def convertReturn(self, status, data): - if status == RTC.PORT_OK: - # never comes here - return self.PORT_OK - elif status == RTC.PORT_ERROR: - self.onSenderError() - return self.PORT_ERROR - elif status == RTC.BUFFER_FULL: - # never comes here - return self.BUFFER_FULL +class OutPortDSConsumer(OpenRTM_aist.OutPortConsumer, + OpenRTM_aist.CorbaConsumer): + """ + """ + + ## + # @if jp + # @brief コンストラクタ + # + # コンストラクタ + # + # @param buffer 本ポートに割り当てるバッファ + # + # @else + # @brief Constructor + # + # Constructor + # + # @param buffer Buffer that is attached to this port + # + # @endif + # + def __init__(self): + OpenRTM_aist.CorbaConsumer.__init__(self, RTC.DataPullService) + self._rtcout = OpenRTM_aist.Manager.instance().getLogbuf("OutPortDSConsumer") + self._buffer = None + self._profile = None + self._listeners = None + return + + ## + # @if jp + # @brief デストラクタ + # + # デストラクタ + # + # @else + # @brief Destructor + # + # Destructor + # + # @endif + # + def __del__(self, CorbaConsumer=OpenRTM_aist.CorbaConsumer): + self._rtcout.RTC_PARANOID("~OutPortDSConsumer()") + CorbaConsumer.__del__(self) + pass + + ## + # @if jp + # @brief 設定初期化 + # + # OutPortConsumerの各種設定を行う。実装クラスでは、与えられた + # Propertiesから必要な情報を取得して各種設定を行う。この init() 関 + # 数は、OutPortProvider生成直後および、接続時にそれぞれ呼ばれる可 + # 能性がある。したがって、この関数は複数回呼ばれることを想定して記 + # 述されるべきである。 + # + # @param prop 設定情報 + # + # @else + # + # @brief Initializing configuration + # + # This operation would be called to configure in initialization. + # In the concrete class, configuration should be performed + # getting appropriate information from the given Properties data. + # This function might be called right after instantiation and + # connection sequence respectivly. Therefore, this function + # should be implemented assuming multiple call. + # + # @param prop Configuration information + # + # @endif + # + # virtual void init(coil::Properties& prop); + + def init(self, prop): + self._rtcout.RTC_TRACE("init()") + return + + ## + # @if jp + # @brief バッファをセットする + # + # OutPortConsumerがデータを取り出すバッファをセットする。 + # すでにセットされたバッファがある場合、以前のバッファへの + # ポインタに対して上書きされる。 + # OutPortProviderはバッファの所有権を仮定していないので、 + # バッファの削除はユーザの責任で行わなければならない。 + # + # @param buffer OutPortProviderがデータを取り出すバッファへのポインタ + # + # @else + # @brief Setting outside buffer's pointer + # + # A pointer to a buffer from which OutPortProvider retrieve data. + # If already buffer is set, previous buffer's pointer will be + # overwritten by the given pointer to a buffer. Since + # OutPortProvider does not assume ownership of the buffer + # pointer, destructor of the buffer should be done by user. + # + # @param buffer A pointer to a data buffer to be used by OutPortProvider + # + # @endif + # + # virtual void setBuffer(CdrBufferBase* buffer); + + def setBuffer(self, buffer): + self._rtcout.RTC_TRACE("setBuffer()") + self._buffer = buffer + return + + # void OutPortDSConsumer::setListener(ConnectorInfo& info, + # ConnectorListeners* listeners) + + def setListener(self, info, listeners): + self._rtcout.RTC_TRACE("setListener()") + self._listeners = listeners + self._profile = info + return + + ## + # @if jp + # @brief データを読み出す + # + # 設定されたデータを読み出す。 + # + # @param data 読み出したデータを受け取るオブジェクト + # + # @return データ読み出し処理結果(読み出し成功:true、読み出し失敗:false) + # + # @else + # @brief Read data + # + # Read set data + # + # @param data Object to receive the read data + # + # @return Read result (Successful:true, Failed:false) + # + # @endif + # + # virtual ReturnCode get(cdrMemoryStream& data); + + def get(self, data): + self._rtcout.RTC_PARANOID("get()") + + try: + dataservice = self._ptr() + ret, cdr_data = dataservice.pull() + + if ret == RTC.PORT_OK: + self._rtcout.RTC_DEBUG("get() successful") + data = cdr_data + data = self.onReceived(data) + data = self.onBufferWrite(data) + + if self._buffer.full(): + self._rtcout.RTC_INFO("InPort buffer is full.") + data = self.onBufferFull(data) + data = self.onReceiverFull(data) + + self._buffer.put(data) + self._buffer.advanceWptr() + self._buffer.advanceRptr() + + return self.PORT_OK, data + return self.convertReturn(ret, data) + + except BaseException: + self._rtcout.RTC_WARN("Exception caught from OutPort.get().") + self._rtcout.RTC_ERROR(OpenRTM_aist.Logger.print_exception()) + return self.CONNECTION_LOST, None + + ## + # @if jp + # @brief データ受信通知への登録 + # + # 指定されたプロパティに基づいて、データ受信通知の受け取りに登録する。 + # + # @param properties 登録情報 + # + # @return 登録処理結果(登録成功:true、登録失敗:false) + # + # @else + # @brief Subscribe the data receive notification + # + # Subscribe the data receive notification based on specified property + # information + # + # @param properties Subscription information + # + # @return Subscription result (Successful:true, Failed:false) + # + # @endif + # + # virtual bool subscribeInterface(const SDOPackage::NVList& properties); + + def subscribeInterface(self, properties): + self._rtcout.RTC_TRACE("subscribeInterface()") + index = OpenRTM_aist.NVUtil.find_index( + properties, "dataport.data_service.outport_ior") + + if index < 0: + self._rtcout.RTC_DEBUG( + "dataport.data_service.outport_ior not found.") + return False + + if OpenRTM_aist.NVUtil.isString( + properties, "dataport.data_service.outport_ior"): + self._rtcout.RTC_DEBUG("dataport.data_service.outport_ior found.") + ior = "" + # try: + ior = any.from_any(properties[index].value, keep_structs=True) + # except: + # self._rtcout.RTC_ERROR(OpenRTM_aist.Logger.print_exception()) + + orb = OpenRTM_aist.Manager.instance().getORB() + obj = orb.string_to_object(ior) + ret = self.setObject(obj) + if ret: + self._rtcout.RTC_DEBUG("CorbaConsumer was set successfully.") + else: + self._rtcout.RTC_ERROR("Invalid object reference.") + + return ret + + return False + + ## + # @if jp + # @brief データ受信通知からの登録解除 + # + # データ受信通知の受け取りから登録を解除する。 + # + # @param properties 登録解除情報 + # + # @else + # @brief Unsubscribe the data receive notification + # + # Unsubscribe the data receive notification. + # + # @param properties Unsubscription information + # + # @endif + # + # virtual void unsubscribeInterface(const SDOPackage::NVList& properties); + + def unsubscribeInterface(self, properties): + self._rtcout.RTC_TRACE("unsubscribeInterface()") + index = OpenRTM_aist.NVUtil.find_index(properties, + "dataport.data_service.outport_ior") + if index < 0: + self._rtcout.RTC_DEBUG( + "dataport.data_service.outport_ior not found.") + return + + ior = "" + + try: + ior = any.from_any(properties[index].value, keep_structs=True) + + if ior: + self._rtcout.RTC_DEBUG( + "dataport.data_service.outport_ior found.") + orb = OpenRTM_aist.Manager.instance().getORB() + obj = orb.string_to_object(ior) + if self._ptr(True)._is_equivalent(obj): + self.releaseObject() + self._rtcout.RTC_DEBUG( + "CorbaConsumer's reference was released.") + return + + self._rtcout.RTC_ERROR("hmm. Inconsistent object reference.") + + except BaseException: + self._rtcout.RTC_ERROR(OpenRTM_aist.Logger.print_exception()) + + return + + ## + # @if jp + # @brief リターンコード変換 (DataPortStatus -> BufferStatus) + # @else + # @brief Return codes conversion + # @endif + # + # ReturnCode convertReturn(::OpenRTM::PortStatus status, + # const cdrMemoryStream& data) + + def convertReturn(self, status, data): + if status == RTC.PORT_OK: + # never comes here + return self.PORT_OK, data + + elif status == RTC.PORT_ERROR: + self.onSenderError() + return self.PORT_ERROR, data + + elif status == RTC.BUFFER_FULL: + # never comes here + return self.BUFFER_FULL, data + + elif status == RTC.BUFFER_EMPTY: + self.onSenderEmpty() + return self.BUFFER_EMPTY, data + + elif status == RTC.BUFFER_TIMEOUT: + self.onSenderTimeout() + return self.BUFFER_TIMEOUT, data + + elif status == RTC.UNKNOWN_ERROR: + self.onSenderError() + return self.UNKNOWN_ERROR, data + + else: + self.onSenderError() + return self.UNKNOWN_ERROR, data + + ## + # @brief Connector data listener functions + # + # inline void onBufferWrite(const cdrMemoryStream& data) - elif status == RTC.BUFFER_EMPTY: - self.onSenderEmpty() - return self.BUFFER_EMPTY + def onBufferWrite(self, data): + if self._listeners is not None and self._profile is not None: + _, data = self._listeners.notifyData( + OpenRTM_aist.ConnectorDataListenerType.ON_BUFFER_WRITE, self._profile, data) + + return data + + # inline void onBufferFull(const cdrMemoryStream& data) + + def onBufferFull(self, data): + if self._listeners is not None and self._profile is not None: + _, data = self._listeners.notifyData( + OpenRTM_aist.ConnectorDataListenerType.ON_BUFFER_FULL, self._profile, data) - elif status == RTC.BUFFER_TIMEOUT: - self.onSenderTimeout() - return self.BUFFER_TIMEOUT + return data - elif status == RTC.UNKNOWN_ERROR: - self.onSenderError() - return self.UNKNOWN_ERROR + # inline void onReceived(const cdrMemoryStream& data) - else: - self.onSenderError() - return self.UNKNOWN_ERROR + def onReceived(self, data): + if self._listeners is not None and self._profile is not None: + _, data = self._listeners.notifyData( + OpenRTM_aist.ConnectorDataListenerType.ON_RECEIVED, self._profile, data) + return data + # inline void onReceiverFull(const cdrMemoryStream& data) - - ## - # @brief Connector data listener functions - # - # inline void onBufferWrite(const cdrMemoryStream& data) - def onBufferWrite(self, data): - if self._listeners is not None and self._profile is not None: - self._listeners.connectorData_[OpenRTM_aist.ConnectorDataListenerType.ON_BUFFER_WRITE].notify(self._profile, data) - - return - - - # inline void onBufferFull(const cdrMemoryStream& data) - def onBufferFull(self, data): - if self._listeners is not None and self._profile is not None: - self._listeners.connectorData_[OpenRTM_aist.ConnectorDataListenerType.ON_BUFFER_FULL].notify(self._profile, data) - - return - - - # inline void onReceived(const cdrMemoryStream& data) - def onReceived(self, data): - if self._listeners is not None and self._profile is not None: - self._listeners.connectorData_[OpenRTM_aist.ConnectorDataListenerType.ON_RECEIVED].notify(self._profile, data) - - return + def onReceiverFull(self, data): + if self._listeners is not None and self._profile is not None: + _, data = self._listeners.notifyData( + OpenRTM_aist.ConnectorDataListenerType.ON_RECEIVER_FULL, self._profile, data) + return data - # inline void onReceiverFull(const cdrMemoryStream& data) - def onReceiverFull(self, data): - if self._listeners is not None and self._profile is not None: - self._listeners.connectorData_[OpenRTM_aist.ConnectorDataListenerType.ON_RECEIVER_FULL].notify(self._profile, data) - - return + ## + # @brief Connector listener functions + # + # inline void onSenderEmpty() + def onSenderEmpty(self): + if self._listeners is not None and self._profile is not None: + self._listeners.notify( + OpenRTM_aist.ConnectorListenerType.ON_SENDER_EMPTY, self._profile) - ## - # @brief Connector listener functions - # - # inline void onSenderEmpty() - def onSenderEmpty(self): - if self._listeners is not None and self._profile is not None: - self._listeners.connector_[OpenRTM_aist.ConnectorListenerType.ON_SENDER_EMPTY].notify(self._profile) + return - return + # inline void onSenderTimeout() + def onSenderTimeout(self): + if self._listeners is not None and self._profile is not None: + self._listeners.notify( + OpenRTM_aist.ConnectorListenerType.ON_SENDER_TIMEOUT, self._profile) - # inline void onSenderTimeout() - def onSenderTimeout(self): - if self._listeners is not None and self._profile is not None: - self._listeners.connector_[OpenRTM_aist.ConnectorListenerType.ON_SENDER_TIMEOUT].notify(self._profile) + return - return + # inline void onSenderError() - - # inline void onSenderError() - def onSenderError(self): - if self._listeners is not None and self._profile is not None: - self._listeners.connector_[OpenRTM_aist.ConnectorListenerType.ON_SENDER_ERROR].notify(self._profile) + def onSenderError(self): + if self._listeners is not None and self._profile is not None: + self._listeners.notify( + OpenRTM_aist.ConnectorListenerType.ON_SENDER_ERROR, self._profile) - return + return def OutPortDSConsumerInit(): - factory = OpenRTM_aist.OutPortConsumerFactory.instance() - factory.addFactory("data_service", - OpenRTM_aist.OutPortDSConsumer, - OpenRTM_aist.Delete) - return + factory = OpenRTM_aist.OutPortConsumerFactory.instance() + factory.addFactory("data_service", + OpenRTM_aist.OutPortDSConsumer) + return diff --git a/OpenRTM_aist/OutPortDSProvider.py b/OpenRTM_aist/OutPortDSProvider.py index 75b665e7..1f25962a 100644 --- a/OpenRTM_aist/OutPortDSProvider.py +++ b/OpenRTM_aist/OutPortDSProvider.py @@ -1,5 +1,5 @@ #!/usr/bin/env python -# -*- coding: euc-jp -*- +# -*- coding: utf-8 -*- ## # @file OutPortDSProvider.py @@ -15,20 +15,19 @@ # All rights reserved. - - import OpenRTM_aist -import RTC__POA,RTC +import RTC__POA +import RTC ## # @if jp # @class OutPortDSProvider -# @brief OutPortDSProvider 饹 +# @brief OutPortDSProvider クラス # -# OutPortProvider +# OutPortProvider # -# ǡž CORBA OpenRTM::DataPullService 󥿡եѤ -# pull ǡե¸ OutPort ץХ饹 +# データ転送に CORBA の OpenRTM::DataPullService インターフェースを利用し +# た、pull 型データフロー型を実現する OutPort プロバイダクラス。 # # @since 1.2.0 # @@ -44,409 +43,412 @@ # # @endif # -class OutPortDSProvider(OpenRTM_aist.OutPortProvider, - RTC__POA.DataPullService): - ## - # @if jp - # @brief 󥹥ȥ饯 - # - # 󥹥ȥ饯 - # - # @param buffer ץХ˳ƤХåե֥ - # - # @else - # @brief Constructor - # - # Constructor - # - # @param buffer Buffer object that is assigned to this provider - # - # @endif - # - def __init__(self): - OpenRTM_aist.OutPortProvider.__init__(self) - self.setInterfaceType("data_service") - - # ConnectorProfile setting - self._objref = self._this() - - self._buffer = None - - # set outPort's reference - orb = OpenRTM_aist.Manager.instance().getORB() - - self._properties.append(OpenRTM_aist.NVUtil.newNV("dataport.data_service.outport_ior", - orb.object_to_string(self._objref))) - self._properties.append(OpenRTM_aist.NVUtil.newNV("dataport.data_service.outport_ref", - self._objref)) - - self._listeners = None - self._connector = None - self._profile = None - return - - - ## - # @if jp - # @brief ǥȥ饯 - # - # ǥȥ饯 - # - # @else - # @brief Destructor - # - # Destructor - # - # @endif - # - def __del__(self): - return - - ## - # @if jp - # @brief λ - # - # @else - # @brief - # - # - # - # @endif - # - def exit(self): - oid = self._default_POA().servant_to_id(self) - self._default_POA().deactivate_object(oid) - - ## - # @if jp - # @brief - # - # InPortConsumerγƼԤ饹ǤϡͿ줿 - # PropertiesɬפʾƳƼԤ init() - # ϡOutPortProviderľ太ӡ³ˤ줾ƤФ - # ǽ롣äơδؿʣƤФ뤳ȤꤷƵ - # Ҥ٤Ǥ롣 - # - # @param prop - # - # @else - # - # @brief Initializing configuration - # - # This operation would be called to configure in initialization. - # In the concrete class, configuration should be performed - # getting appropriate information from the given Properties data. - # This function might be called right after instantiation and - # connection sequence respectivly. Therefore, this function - # should be implemented assuming multiple call. - # - # @param prop Configuration information - # - # @endif - # - # virtual void init(coil::Properties& prop); - def init(self, prop): - pass - - - ## - # @if jp - # @brief Хåե򥻥åȤ - # - # OutPortProviderǡФХåե򥻥åȤ롣 - # Ǥ˥åȤ줿Хåե硢ΥХåեؤ - # ݥ󥿤Фƾ񤭤롣 - # OutPortProviderϥХåեνͭꤷƤʤΤǡ - # Хåեκϥ桼ǤǹԤʤФʤʤ - # - # @param buffer OutPortProviderǡФХåեؤΥݥ - # - # @else - # @brief Setting outside buffer's pointer - # - # A pointer to a buffer from which OutPortProvider retrieve data. - # If already buffer is set, previous buffer's pointer will be - # overwritten by the given pointer to a buffer. Since - # OutPortProvider does not assume ownership of the buffer - # pointer, destructor of the buffer should be done by user. - # - # @param buffer A pointer to a data buffer to be used by OutPortProvider - # - # @endif - # - # virtual void setBuffer(BufferBase* buffer); - def setBuffer(self, buffer): - self._buffer = buffer - return - - - ## - # @if jp - # @brief ꥹʤꤹ롣 - # - # OutPort ϥǡˤƼ磻٥ȤФΥꥹ - # ֥Ȥ򥳡뤹륳Хå󶡤롣ܺ٤ - # ConnectorListener.h ConnectorDataListener, ConnectorListener - # 򻲾ȤΤȡOutPortDSProvider ǤϡʲΥХå - # 󶡤롣 - # - # - ON_BUFFER_READ - # - ON_SEND - # - ON_BUFFER_EMPTY - # - ON_BUFFER_READ_TIMEOUT - # - ON_SENDER_EMPTY - # - ON_SENDER_TIMEOUT - # - ON_SENDER_ERROR - # - # @param info ³ - # @param listeners ꥹʥ֥ - # - # @else - # @brief Set the listener. - # - # OutPort provides callback functionality that calls specific - # listener objects according to the events in the data publishing - # process. For details, see documentation of - # ConnectorDataListener class and ConnectorListener class in - # ConnectorListener.h. In this OutPortDSProvider provides - # the following callbacks. - # - # - ON_BUFFER_READ - # - ON_SEND - # - ON_BUFFER_EMPTY - # - ON_BUFFER_READ_TIMEOUT - # - ON_SENDER_EMPTY - # - ON_SENDER_TIMEOUT - # - ON_SENDER_ERROR - # - # @param info Connector information - # @param listeners Listener objects - # - # @endif - # - # virtual void setListener(ConnectorInfo& info, - # ConnectorListeners* listeners); - def setListener(self, info, listeners): - self._profile = info - self._listeners = listeners - return - - - ## - # @if jp - # @brief Connectorꤹ롣 - # - # OutPort ³Ω OutPortConnector ֥Ȥ - # ֥ȤΥݥ󥿤ȶˤδؿƤӽФͭ - # OutPort ݻΤ OutPortProvider OutPortConnector - # ƤϤʤ - # - # @param connector OutPortConnector - # - # @else - # @brief set Connector - # - # OutPort creates OutPortConnector object when it establishes - # connection between OutPort and InPort, and it calls this - # function with a pointer to the connector object. Since the - # OutPort has the ownership of this connector, OutPortProvider - # should not delete it. - # - # @param connector OutPortConnector - # - # @endif - # - # virtual void setConnector(OutPortConnector* connector); - def setConnector(self, connector): - self._connector = connector - return - - - def get(self): - self._rtcout.RTC_PARANOID("OutPortDSProvider.get()") - return (RTC.UNKNOWN_ERROR, "") - - ## - # @if jp - # @brief [CORBA interface] Хåեǡ - # - # ꤵ줿Хåեǡ롣 - # - # @return ǡ - # - # @else - # @brief [CORBA interface] Get data from the buffer - # - # Get data from the internal buffer. - # - # @return Data got from the buffer. - # - # @endif - # - # virtual ::OpenRTM::PortStatus pull(::RTC::CdrData_out data); - def pull(self): - self._rtcout.RTC_PARANOID("OutPortDSProvider.pull()") - if not self._connector: - self.onSenderError() - return (RTC.UNKNOWN_ERROR, "") - - try: - - cdr = [None] - ret = self._connector.read(cdr) - - if ret == OpenRTM_aist.BufferStatus.BUFFER_OK: - if not cdr[0]: - self._rtcout.RTC_ERROR("buffer is empty.") - return (RTC.BUFFER_EMPTY, "") - - except: - self._rtcout.RTC_TRACE(OpenRTM_aist.Logger.print_exception()) - return (RTC.UNKNOWN_ERROR, "") - - return self.convertReturn(ret, cdr[0]) - - ## - # @if jp - # @brief ON_BUFFER_READ ΥꥹʤΤ롣 - # @param data cdrMemoryStream - # @else - # @brief Notify an ON_BUFFER_READ event to listeners - # @param data cdrMemoryStream - # @endif - # - # inline void onBufferRead(const cdrMemoryStream& data) - def onBufferRead(self, data): - if self._listeners and self._profile: - self._listeners.connectorData_[OpenRTM_aist.ConnectorDataListenerType.ON_BUFFER_READ].notify(self._profile, data) - return - - ## - # @if jp - # @brief ON_SEND ΥꥹʤΤ롣 - # @param data cdrMemoryStream - # @else - # @brief Notify an ON_SEND event to listeners - # @param data cdrMemoryStream - # @endif - # - # inline void onSend(const cdrMemoryStream& data) - def onSend(self, data): - if self._listeners and self._profile: - self._listeners.connectorData_[OpenRTM_aist.ConnectorDataListenerType.ON_SEND].notify(self._profile, data) - return - - ## - # @if jp - # @brief ON_BUFFER_EMPTYΥꥹʤΤ롣 - # @else - # @brief Notify an ON_BUFFER_EMPTY event to listeners - # @endif - # - # inline void onBufferEmpty() - def onBufferEmpty(self): - if self._listeners and self._profile: - self._listeners.connector_[OpenRTM_aist.ConnectorListenerType.ON_BUFFER_EMPTY].notify(self._profile) - return - - ## - # @if jp - # @brief ON_BUFFER_READ_TIMEOUT ΥꥹʤΤ롣 - # @else - # @brief Notify an ON_BUFFER_READ_TIMEOUT event to listeners - # @endif - # - # inline void onBufferReadTimeout() - def onBufferReadTimeout(self): - if self._listeners and self._profile: - self._listeners.connector_[OpenRTM_aist.ConnectorListenerType.ON_BUFFER_READ_TIMEOUT].notify(self._profile) - return - - ## - # @if jp - # @brief ON_SENDER_EMPTYΥꥹʤΤ롣 - # @else - # @brief Notify an ON_SENDER_EMPTY event to listeners - # @endif - # - # inline void onSenderEmpty() - def onSenderEmpty(self): - if self._listeners and self._profile: - self._listeners.connector_[OpenRTM_aist.ConnectorListenerType.ON_SENDER_EMPTY].notify(self._profile) - return - - ## - # @if jp - # @brief ON_SENDER_TIMEOUT ΥꥹʤΤ롣 - # @else - # @brief Notify an ON_SENDER_TIMEOUT event to listeners - # @endif - # - # inline void onSenderTimeout() - def onSenderTimeout(self): - if self._listeners and self._profile: - self._listeners.connector_[OpenRTM_aist.ConnectorListenerType.ON_SENDER_TIMEOUT].notify(self._profile) - return - - ## - # @if jp - # @brief ON_SENDER_ERRORΥꥹʤΤ롣 - # @else - # @brief Notify an ON_SENDER_ERROR event to listeners - # @endif - # - # inline void onSenderError() - def onSenderError(self): - if self._listeners and self._profile: - self._listeners.connector_[OpenRTM_aist.ConnectorListenerType.ON_SENDER_ERROR].notify(self._profile) - return - - - ## - # @if jp - # @brief ꥿󥳡Ѵ - # @else - # @brief Return codes conversion - # @endif - # - # ::OpenRTM::PortStatus convertReturn(BufferStatus::Enum status, - # const cdrMemoryStream& data); - def convertReturn(self, status, data): - if status == OpenRTM_aist.BufferStatus.BUFFER_OK: - self.onBufferRead(data) - self.onSend(data) - return (RTC.PORT_OK, data) - - elif status == OpenRTM_aist.BufferStatus.BUFFER_ERROR: - self.onSenderError() - return (RTC.PORT_ERROR, data) - - elif status == OpenRTM_aist.BufferStatus.BUFFER_FULL: - # never come here - return (RTC.BUFFER_FULL, data) - - elif status == OpenRTM_aist.BufferStatus.BUFFER_EMPTY: - self.onBufferEmpty() - self.onSenderEmpty() - return (RTC.BUFFER_EMPTY, data) - - elif status == OpenRTM_aist.BufferStatus.PRECONDITION_NOT_MET: - self.onSenderError() - return (RTC.PORT_ERROR, data) - - elif status == OpenRTM_aist.BufferStatus.TIMEOUT: - self.onBufferReadTimeout() - self.onSenderTimeout() - return (RTC.BUFFER_TIMEOUT, data) - - else: - return (RTC.UNKNOWN_ERROR, data) - +class OutPortDSProvider(OpenRTM_aist.OutPortProvider, + RTC__POA.DataPullService): + ## + # @if jp + # @brief コンストラクタ + # + # コンストラクタ + # + # @param buffer 当該プロバイダに割り当てるバッファオブジェクト + # + # @else + # @brief Constructor + # + # Constructor + # + # @param buffer Buffer object that is assigned to this provider + # + # @endif + # + def __init__(self): + OpenRTM_aist.OutPortProvider.__init__(self) + self.setInterfaceType("data_service") + + # ConnectorProfile setting + self._objref = self._this() + + self._buffer = None + + # set outPort's reference + orb = OpenRTM_aist.Manager.instance().getORB() + + self._properties.append(OpenRTM_aist.NVUtil.newNV("dataport.data_service.outport_ior", + orb.object_to_string(self._objref))) + self._properties.append(OpenRTM_aist.NVUtil.newNV("dataport.data_service.outport_ref", + self._objref)) + + self._listeners = None + self._connector = None + self._profile = None + return + + ## + # @if jp + # @brief デストラクタ + # + # デストラクタ + # + # @else + # @brief Destructor + # + # Destructor + # + # @endif + # + + def __del__(self): + return + + ## + # @if jp + # @brief 終了処理 + # + # @else + # @brief + # + # + # + # @endif + # + def exit(self): + oid = self._default_POA().servant_to_id(self) + self._default_POA().deactivate_object(oid) + + ## + # @if jp + # @brief 設定初期化 + # + # InPortConsumerの各種設定を行う。実装クラスでは、与えられた + # Propertiesから必要な情報を取得して各種設定を行う。この init() 関 + # 数は、OutPortProvider生成直後および、接続時にそれぞれ呼ばれる可 + # 能性がある。したがって、この関数は複数回呼ばれることを想定して記 + # 述されるべきである。 + # + # @param prop 設定情報 + # + # @else + # + # @brief Initializing configuration + # + # This operation would be called to configure in initialization. + # In the concrete class, configuration should be performed + # getting appropriate information from the given Properties data. + # This function might be called right after instantiation and + # connection sequence respectivly. Therefore, this function + # should be implemented assuming multiple call. + # + # @param prop Configuration information + # + # @endif + # + # virtual void init(coil::Properties& prop); + def init(self, prop): + pass + + ## + # @if jp + # @brief バッファをセットする + # + # OutPortProviderがデータを取り出すバッファをセットする。 + # すでにセットされたバッファがある場合、以前のバッファへの + # ポインタに対して上書きされる。 + # OutPortProviderはバッファの所有権を仮定していないので、 + # バッファの削除はユーザの責任で行わなければならない。 + # + # @param buffer OutPortProviderがデータを取り出すバッファへのポインタ + # + # @else + # @brief Setting outside buffer's pointer + # + # A pointer to a buffer from which OutPortProvider retrieve data. + # If already buffer is set, previous buffer's pointer will be + # overwritten by the given pointer to a buffer. Since + # OutPortProvider does not assume ownership of the buffer + # pointer, destructor of the buffer should be done by user. + # + # @param buffer A pointer to a data buffer to be used by OutPortProvider + # + # @endif + # + # virtual void setBuffer(BufferBase* buffer); + + def setBuffer(self, buffer): + self._buffer = buffer + return + + ## + # @if jp + # @brief リスナを設定する。 + # + # OutPort はデータ送信処理における各種イベントに対して特定のリスナ + # オブジェクトをコールするコールバック機構を提供する。詳細は + # ConnectorListener.h の ConnectorDataListener, ConnectorListener + # 等を参照のこと。OutPortDSProvider では、以下のコールバック + # が提供される。 + # + # - ON_BUFFER_READ + # - ON_SEND + # - ON_BUFFER_EMPTY + # - ON_BUFFER_READ_TIMEOUT + # - ON_SENDER_EMPTY + # - ON_SENDER_TIMEOUT + # - ON_SENDER_ERROR + # + # @param info 接続情報 + # @param listeners リスナオブジェクト + # + # @else + # @brief Set the listener. + # + # OutPort provides callback functionality that calls specific + # listener objects according to the events in the data publishing + # process. For details, see documentation of + # ConnectorDataListener class and ConnectorListener class in + # ConnectorListener.h. In this OutPortDSProvider provides + # the following callbacks. + # + # - ON_BUFFER_READ + # - ON_SEND + # - ON_BUFFER_EMPTY + # - ON_BUFFER_READ_TIMEOUT + # - ON_SENDER_EMPTY + # - ON_SENDER_TIMEOUT + # - ON_SENDER_ERROR + # + # @param info Connector information + # @param listeners Listener objects + # + # @endif + # + # virtual void setListener(ConnectorInfo& info, + # ConnectorListeners* listeners); + + def setListener(self, info, listeners): + self._profile = info + self._listeners = listeners + return + + ## + # @if jp + # @brief Connectorを設定する。 + # + # OutPort は接続確立時に OutPortConnector オブジェクトを生成し、生 + # 成したオブジェクトのポインタと共にこの関数を呼び出す。所有権は + # OutPort が保持するので OutPortProvider は OutPortConnector を削 + # 除してはいけない。 + # + # @param connector OutPortConnector + # + # @else + # @brief set Connector + # + # OutPort creates OutPortConnector object when it establishes + # connection between OutPort and InPort, and it calls this + # function with a pointer to the connector object. Since the + # OutPort has the ownership of this connector, OutPortProvider + # should not delete it. + # + # @param connector OutPortConnector + # + # @endif + # + # virtual void setConnector(OutPortConnector* connector); + + def setConnector(self, connector): + self._connector = connector + return + + def get(self): + self._rtcout.RTC_PARANOID("OutPortDSProvider.get()") + return (RTC.UNKNOWN_ERROR, "") + + ## + # @if jp + # @brief [CORBA interface] バッファからデータを取得する + # + # 設定された内部バッファからデータを取得する。 + # + # @return 取得データ + # + # @else + # @brief [CORBA interface] Get data from the buffer + # + # Get data from the internal buffer. + # + # @return Data got from the buffer. + # + # @endif + # + # virtual ::OpenRTM::PortStatus pull(::RTC::CdrData_out data); + def pull(self): + self._rtcout.RTC_PARANOID("OutPortDSProvider.pull()") + if not self._connector: + self.onSenderError() + return (RTC.UNKNOWN_ERROR, "") + + try: + ret, cdr = self._connector.read() + + if ret == OpenRTM_aist.BufferStatus.BUFFER_OK: + if not cdr: + self._rtcout.RTC_ERROR("buffer is empty.") + return (RTC.BUFFER_EMPTY, "") + + except BaseException: + self._rtcout.RTC_TRACE(OpenRTM_aist.Logger.print_exception()) + return (RTC.UNKNOWN_ERROR, "") + + return self.convertReturn(ret, cdr) + + ## + # @if jp + # @brief ON_BUFFER_READ のリスナへ通知する。 + # @param data cdrMemoryStream + # @else + # @brief Notify an ON_BUFFER_READ event to listeners + # @param data cdrMemoryStream + # @endif + # + # inline void onBufferRead(const cdrMemoryStream& data) + def onBufferRead(self, data): + if self._listeners and self._profile: + _, data = self._listeners.notifyData( + OpenRTM_aist.ConnectorDataListenerType.ON_BUFFER_READ, self._profile, data) + return data + + ## + # @if jp + # @brief ON_SEND のリスナへ通知する。 + # @param data cdrMemoryStream + # @else + # @brief Notify an ON_SEND event to listeners + # @param data cdrMemoryStream + # @endif + # + # inline void onSend(const cdrMemoryStream& data) + def onSend(self, data): + if self._listeners and self._profile: + _, data = self._listeners.notifyData( + OpenRTM_aist.ConnectorDataListenerType.ON_SEND, self._profile, data) + return data + + ## + # @if jp + # @brief ON_BUFFER_EMPTYのリスナへ通知する。 + # @else + # @brief Notify an ON_BUFFER_EMPTY event to listeners + # @endif + # + # inline void onBufferEmpty() + def onBufferEmpty(self): + if self._listeners and self._profile: + self._listeners.notify( + OpenRTM_aist.ConnectorListenerType.ON_BUFFER_EMPTY, self._profile) + return + + ## + # @if jp + # @brief ON_BUFFER_READ_TIMEOUT のリスナへ通知する。 + # @else + # @brief Notify an ON_BUFFER_READ_TIMEOUT event to listeners + # @endif + # + # inline void onBufferReadTimeout() + def onBufferReadTimeout(self): + if self._listeners and self._profile: + self._listeners.notify( + OpenRTM_aist.ConnectorListenerType.ON_BUFFER_READ_TIMEOUT, self._profile) + return + + ## + # @if jp + # @brief ON_SENDER_EMPTYのリスナへ通知する。 + # @else + # @brief Notify an ON_SENDER_EMPTY event to listeners + # @endif + # + # inline void onSenderEmpty() + def onSenderEmpty(self): + if self._listeners and self._profile: + self._listeners.notify( + OpenRTM_aist.ConnectorListenerType.ON_SENDER_EMPTY, self._profile) + return + + ## + # @if jp + # @brief ON_SENDER_TIMEOUT のリスナへ通知する。 + # @else + # @brief Notify an ON_SENDER_TIMEOUT event to listeners + # @endif + # + # inline void onSenderTimeout() + def onSenderTimeout(self): + if self._listeners and self._profile: + self._listeners.notify( + OpenRTM_aist.ConnectorListenerType.ON_SENDER_TIMEOUT, self._profile) + return + + ## + # @if jp + # @brief ON_SENDER_ERRORのリスナへ通知する。 + # @else + # @brief Notify an ON_SENDER_ERROR event to listeners + # @endif + # + # inline void onSenderError() + def onSenderError(self): + if self._listeners and self._profile: + self._listeners.notify( + OpenRTM_aist.ConnectorListenerType.ON_SENDER_ERROR, self._profile) + return + + ## + # @if jp + # @brief リターンコード変換 + # @else + # @brief Return codes conversion + # @endif + # + # ::OpenRTM::PortStatus convertReturn(BufferStatus::Enum status, + # const cdrMemoryStream& data); + + def convertReturn(self, status, data): + if status == OpenRTM_aist.BufferStatus.BUFFER_OK: + data = self.onBufferRead(data) + data = self.onSend(data) + return (RTC.PORT_OK, data) + + elif status == OpenRTM_aist.BufferStatus.BUFFER_ERROR: + self.onSenderError() + return (RTC.PORT_ERROR, data) + + elif status == OpenRTM_aist.BufferStatus.BUFFER_FULL: + # never come here + return (RTC.BUFFER_FULL, data) + + elif status == OpenRTM_aist.BufferStatus.BUFFER_EMPTY: + self.onBufferEmpty() + self.onSenderEmpty() + return (RTC.BUFFER_EMPTY, data) + + elif status == OpenRTM_aist.BufferStatus.PRECONDITION_NOT_MET: + self.onSenderError() + return (RTC.PORT_ERROR, data) + + elif status == OpenRTM_aist.BufferStatus.TIMEOUT: + self.onBufferReadTimeout() + self.onSenderTimeout() + return (RTC.BUFFER_TIMEOUT, data) + + else: + return (RTC.UNKNOWN_ERROR, data) + def OutPortDSProviderInit(): - factory = OpenRTM_aist.OutPortProviderFactory.instance() - factory.addFactory("data_service", - OpenRTM_aist.OutPortDSProvider, - OpenRTM_aist.Delete) + factory = OpenRTM_aist.OutPortProviderFactory.instance() + factory.addFactory("data_service", + OpenRTM_aist.OutPortDSProvider) diff --git a/OpenRTM_aist/OutPortDirectConsumer.py b/OpenRTM_aist/OutPortDirectConsumer.py index 1a06dbab..bf5183db 100644 --- a/OpenRTM_aist/OutPortDirectConsumer.py +++ b/OpenRTM_aist/OutPortDirectConsumer.py @@ -1,14 +1,12 @@ #!/usr/bin/env python -# -*- coding: euc-jp -*- +# -*- coding: utf-8 -*- ## # @file OutPortDirectConsumer.py # @brief OutPortDirectConsumer class # @date $Date: 2016/01/08 $ # @author Nobuhiko Miyamoto -# - - +# import OpenRTM_aist @@ -19,9 +17,9 @@ # # @class InPortDirectConsumer # -# @brief InPortDirectConsumer 饹 +# @brief InPortDirectConsumer クラス # -# ǡ쥯Ȥ˽񤭹pull̿¸OutPort󥷥ޡ饹 +# データをダイレクトに書き込むpull型通信を実現するOutPortコンシュマークラス # # @else # @class InPortDirectConsumer @@ -33,235 +31,233 @@ # @endif # class OutPortDirectConsumer(OpenRTM_aist.OutPortConsumer): - """ - """ - - ## - # @if jp - # @brief 󥹥ȥ饯 - # - # 󥹥ȥ饯 - # - # @param self - # - # @else - # @brief Constructor - # - # Constructor - # - # @param self - # - # @endif - # - def __init__(self): - OpenRTM_aist.OutPortConsumer.__init__(self) - self._rtcout = OpenRTM_aist.Manager.instance().getLogbuf("OutPortDirectConsumer") - self._listeners = None - self._profile = None - self._properties = None - return - - ## - # @if jp - # @brief ǥȥ饯 - # - # ǥȥ饯 - # - # @param self - # - # @else - # @brief Destructor - # - # Destructor - # - # @param self - # - # @endif - # - def __del__(self, CorbaConsumer=OpenRTM_aist.CorbaConsumer): - self._rtcout.RTC_PARANOID("~OutPortDirectConsumer()") - - pass - - - ## - # @if jp - # @brief - # - # InPortConsumerγƼԤ - # - # @self - # - # - # @else - # @brief Initializing configuration - # - # - # @endif - # - # virtual void init(coil::Properties& prop); - def init(self, prop): - self._rtcout.RTC_TRACE("init()") - self._properties = prop - return - - ## - # @if jp - # @brief - # - # @param self - # @param data - # @return - # - # @else - # @brief - # - # @param self - # @param data - # @return - # - # @endif - # - # virtual ReturnCode put(const cdrMemoryStream& data); - def get(self, data): - self._rtcout.RTC_PARANOID("get()") - return self.UNKNOWN_ERROR - - - # virtual void setBuffer(CdrBufferBase* buffer); - def setBuffer(self, buffer): - self._rtcout.RTC_TRACE("setBuffer()") - return - - - # void OutPortCorbaCdrConsumer::setListener(ConnectorInfo& info, - # ConnectorListeners* listeners) - def setListener(self, info, listeners): - self._rtcout.RTC_TRACE("setListener()") - self._listeners = listeners - self._profile = info - return - - - - - - ## - # @if jp - # @brief InterfaceProfile - # - # - # @param self - # @param properties InterfaceProfileץѥƥ - # - # @else - # @brief Publish InterfaceProfile information - # - # - # @param self - # @param properties Properties to get InterfaceProfile information - # - # @endif - # - # virtual void publishInterfaceProfile(SDOPackage::NVList& properties); - def subscribeInterface(self, properties): - self._rtcout.RTC_TRACE("subscribeInterface()") - - - return True - - - ## - # @if jp - # @brief ǡΤؤϿ - # - # @param self - # @param properties Ͽ - # - # @return Ͽ(Ͽ:trueϿ:false) - # - # @else - # @brief Subscribe to the data sending notification - # - # @param self - # @param properties Information for subscription - # - # @return Subscription result (Successful:true, Failed:false) - # - # @endif - # - # virtual bool subscribeInterface(const SDOPackage::NVList& properties); - def unsubscribeInterface(self, properties): - self._rtcout.RTC_TRACE("unsubscribeInterface()") - return - - - - - - - # inline void onBufferWrite(const cdrMemoryStream& data) - def onBufferWrite(self, data): - if self._listeners is not None and self._profile is not None: - self._listeners.connectorData_[OpenRTM_aist.ConnectorDataListenerType.ON_BUFFER_WRITE].notify(self._profile, data) - - return - - - # inline void onBufferFull(const cdrMemoryStream& data) - def onBufferFull(self, data): - if self._listeners is not None and self._profile is not None: - self._listeners.connectorData_[OpenRTM_aist.ConnectorDataListenerType.ON_BUFFER_FULL].notify(self._profile, data) + """ + """ + + ## + # @if jp + # @brief コンストラクタ + # + # コンストラクタ + # + # @param self + # + # @else + # @brief Constructor + # + # Constructor + # + # @param self + # + # @endif + # + def __init__(self): + OpenRTM_aist.OutPortConsumer.__init__(self) + self._rtcout = OpenRTM_aist.Manager.instance().getLogbuf("OutPortDirectConsumer") + self._listeners = None + self._profile = None + self._properties = None + return + + ## + # @if jp + # @brief デストラクタ + # + # デストラクタ + # + # @param self + # + # @else + # @brief Destructor + # + # Destructor + # + # @param self + # + # @endif + # + def __del__(self, CorbaConsumer=OpenRTM_aist.CorbaConsumer): + self._rtcout.RTC_PARANOID("~OutPortDirectConsumer()") + + pass + + ## + # @if jp + # @brief 設定初期化 + # + # InPortConsumerの各種設定を行う + # + # @self + # + # + # @else + # @brief Initializing configuration + # + # + # @endif + # + # virtual void init(coil::Properties& prop); + + def init(self, prop): + self._rtcout.RTC_TRACE("init()") + self._properties = prop + return + + ## + # @if jp + # @brief + # + # @param self + # @param data + # @return + # + # @else + # @brief + # + # @param self + # @param data + # @return + # + # @endif + # + # virtual ReturnCode put(const cdrMemoryStream& data); + def get(self, data): + self._rtcout.RTC_PARANOID("get()") + return self.UNKNOWN_ERROR + + # virtual void setBuffer(CdrBufferBase* buffer); + + def setBuffer(self, buffer): + self._rtcout.RTC_TRACE("setBuffer()") + return + + # void OutPortCorbaCdrConsumer::setListener(ConnectorInfo& info, + # ConnectorListeners* listeners) + + def setListener(self, info, listeners): + self._rtcout.RTC_TRACE("setListener()") + self._listeners = listeners + self._profile = info + return + + ## + # @if jp + # @brief InterfaceProfile情報を公開する + # + # + # @param self + # @param properties InterfaceProfile情報を受け取るプロパティ + # + # @else + # @brief Publish InterfaceProfile information + # + # + # @param self + # @param properties Properties to get InterfaceProfile information + # + # @endif + # + # virtual void publishInterfaceProfile(SDOPackage::NVList& properties); + + def subscribeInterface(self, properties): + self._rtcout.RTC_TRACE("subscribeInterface()") + + return True + + ## + # @if jp + # @brief データ送信通知への登録 + # + # @param self + # @param properties 登録情報 + # + # @return 登録処理結果(登録成功:true、登録失敗:false) + # + # @else + # @brief Subscribe to the data sending notification + # + # @param self + # @param properties Information for subscription + # + # @return Subscription result (Successful:true, Failed:false) + # + # @endif + # + # virtual bool subscribeInterface(const SDOPackage::NVList& properties); + + def unsubscribeInterface(self, properties): + self._rtcout.RTC_TRACE("unsubscribeInterface()") + return + + # inline void onBufferWrite(const cdrMemoryStream& data) + + def onBufferWrite(self, data): + if self._listeners is not None and self._profile is not None: + _, data = self._listeners.notifyData( + OpenRTM_aist.ConnectorDataListenerType.ON_BUFFER_WRITE, self._profile, data) + + return data + + # inline void onBufferFull(const cdrMemoryStream& data) + + def onBufferFull(self, data): + if self._listeners is not None and self._profile is not None: + _, data = self._listeners.notifyData( + OpenRTM_aist.ConnectorDataListenerType.ON_BUFFER_FULL, self._profile, data) + + return data + + # inline void onReceived(const cdrMemoryStream& data) + + def onReceived(self, data): + if self._listeners is not None and self._profile is not None: + _, data = self._listeners.notifyData( + OpenRTM_aist.ConnectorDataListenerType.ON_RECEIVED, self._profile, data) + + return data + + # inline void onReceiverFull(const cdrMemoryStream& data) + + def onReceiverFull(self, data): + if self._listeners is not None and self._profile is not None: + _, data = self._listeners.notifyData( + OpenRTM_aist.ConnectorDataListenerType.ON_RECEIVER_FULL, self._profile, data) + + return data + + ## + # @brief Connector listener functions + # + # inline void onSenderEmpty() + + def onSenderEmpty(self): + if self._listeners is not None and self._profile is not None: + self._listeners.notify( + OpenRTM_aist.ConnectorListenerType.ON_SENDER_EMPTY, self._profile) + + return + + # inline void onSenderTimeout() + + def onSenderTimeout(self): + if self._listeners is not None and self._profile is not None: + self._listeners.notify( + OpenRTM_aist.ConnectorListenerType.ON_SENDER_TIMEOUT, self._profile) + + return - return - - - # inline void onReceived(const cdrMemoryStream& data) - def onReceived(self, data): - if self._listeners is not None and self._profile is not None: - self._listeners.connectorData_[OpenRTM_aist.ConnectorDataListenerType.ON_RECEIVED].notify(self._profile, data) - - return + # inline void onSenderError() + def onSenderError(self): + if self._listeners is not None and self._profile is not None: + self._listeners.notify( + OpenRTM_aist.ConnectorListenerType.ON_SENDER_ERROR, self._profile) - # inline void onReceiverFull(const cdrMemoryStream& data) - def onReceiverFull(self, data): - if self._listeners is not None and self._profile is not None: - self._listeners.connectorData_[OpenRTM_aist.ConnectorDataListenerType.ON_RECEIVER_FULL].notify(self._profile, data) - - return - - - ## - # @brief Connector listener functions - # - # inline void onSenderEmpty() - def onSenderEmpty(self): - if self._listeners is not None and self._profile is not None: - self._listeners.connector_[OpenRTM_aist.ConnectorListenerType.ON_SENDER_EMPTY].notify(self._profile) - - return - - - # inline void onSenderTimeout() - def onSenderTimeout(self): - if self._listeners is not None and self._profile is not None: - self._listeners.connector_[OpenRTM_aist.ConnectorListenerType.ON_SENDER_TIMEOUT].notify(self._profile) - - return - - - # inline void onSenderError() - def onSenderError(self): - if self._listeners is not None and self._profile is not None: - self._listeners.connector_[OpenRTM_aist.ConnectorListenerType.ON_SENDER_ERROR].notify(self._profile) - - return + return def OutPortDirectConsumerInit(): - factory = OpenRTM_aist.OutPortConsumerFactory.instance() - factory.addFactory("direct", - OpenRTM_aist.OutPortDirectConsumer, - OpenRTM_aist.Delete) - return + factory = OpenRTM_aist.OutPortConsumerFactory.instance() + factory.addFactory("direct", + OpenRTM_aist.OutPortDirectConsumer) + return diff --git a/OpenRTM_aist/OutPortDirectProvider.py b/OpenRTM_aist/OutPortDirectProvider.py index 00cea8e0..afa56015 100644 --- a/OpenRTM_aist/OutPortDirectProvider.py +++ b/OpenRTM_aist/OutPortDirectProvider.py @@ -1,14 +1,12 @@ #!/usr/bin/env python -# -*- coding: euc-jp -*- +# -*- coding: utf-8 -*- ## # @file OutPortDirectProvider.py # @brief OutPortDirectProvider class # @date $Date: 2016/01/08 $ # @author Nobuhiko Miyamoto -# - - +# import OpenRTM_aist @@ -17,9 +15,9 @@ ## # @if jp # @class OutPortDirectProvider -# @brief OutPortDirectProvider 饹 +# @brief OutPortDirectProvider クラス # -# ǡ쥯Ȥ˽񤭹pull̿¸OutPortץХ饹 +# データをダイレクトに書き込むpull型通信を実現するOutPortプロバイダクラス # # @param self # @@ -33,154 +31,148 @@ # @endif # class OutPortDirectProvider(OpenRTM_aist.OutPortProvider): - ## - # @if jp - # @brief 󥹥ȥ饯 - # - # 󥹥ȥ饯 - # - # @param self - # - # @else - # @brief Constructor - # - # @param self - # - # @endif - # - def __init__(self): - OpenRTM_aist.OutPortProvider.__init__(self) - self.setInterfaceType("direct") - - - - self._listeners = None - self._buffer = None - self._profile = None - #self._connector = None - return - - - ## - # @if jp - # @brief ǥȥ饯 - # - # ǥȥ饯 - # - # @param self - # - # @else - # @brief Destructor - # - # Destructor - # - # @param self - # - # @endif - # - def __del__(self): - - return - - ## - # @if jp - # @brief λ - # - # @else - # @brief - # - # - # - # @endif - # - def exit(self): - pass - - # void init(coil::Properties& prop); - def init(self, prop): - pass - - - - # virtual void setBuffer(BufferBase* buffer); - def setBuffer(self, buffer): - self._buffer = buffer - return - - - - # virtual void setListener(ConnectorInfo& info, - # ConnectorListeners* listeners); - def setListener(self, info, listeners): - self._profile = info - self._listeners = listeners - return - - - - # virtual void setConnector(OutPortConnector* connector); - def setConnector(self, connector): - self._connector = connector - return - - - - - - # inline void onBufferRead(const cdrMemoryStream& data) - def onBufferRead(self, data): - if self._listeners and self._profile: - self._listeners.connectorData_[OpenRTM_aist.ConnectorDataListenerType.ON_BUFFER_READ].notify(self._profile, data) - return - - - # inline void onSend(const cdrMemoryStream& data) - def onSend(self, data): - if self._listeners and self._profile: - self._listeners.connectorData_[OpenRTM_aist.ConnectorDataListenerType.ON_SEND].notify(self._profile, data) - return - - - # inline void onBufferEmpty() - def onBufferEmpty(self): - if self._listeners and self._profile: - self._listeners.connector_[OpenRTM_aist.ConnectorListenerType.ON_BUFFER_EMPTY].notify(self._profile) - return - - - # inline void onBufferReadTimeout() - def onBufferReadTimeout(self): - if self._listeners and self._profile: - self._listeners.connector_[OpenRTM_aist.ConnectorListenerType.ON_BUFFER_READ_TIMEOUT].notify(self._profile) - return - - - # inline void onSenderEmpty() - def onSenderEmpty(self): - if self._listeners and self._profile: - self._listeners.connector_[OpenRTM_aist.ConnectorListenerType.ON_SENDER_EMPTY].notify(self._profile) - return - - - # inline void onSenderTimeout() - def onSenderTimeout(self): - if self._listeners and self._profile: - self._listeners.connector_[OpenRTM_aist.ConnectorListenerType.ON_SENDER_TIMEOUT].notify(self._profile) - return - - - # inline void onSenderError() - def onSenderError(self): - if self._listeners and self._profile: - self._listeners.connector_[OpenRTM_aist.ConnectorListenerType.ON_SENDER_ERROR].notify(self._profile) - return - - - + ## + # @if jp + # @brief コンストラクタ + # + # コンストラクタ + # + # @param self + # + # @else + # @brief Constructor + # + # @param self + # + # @endif + # + def __init__(self): + OpenRTM_aist.OutPortProvider.__init__(self) + self.setInterfaceType("direct") + + self._listeners = None + self._buffer = None + self._profile = None + #self._connector = None + return + + ## + # @if jp + # @brief デストラクタ + # + # デストラクタ + # + # @param self + # + # @else + # @brief Destructor + # + # Destructor + # + # @param self + # + # @endif + # + def __del__(self): + + return + + ## + # @if jp + # @brief 終了処理 + # + # @else + # @brief + # + # + # + # @endif + # + def exit(self): + pass + + # void init(coil::Properties& prop); + def init(self, prop): + pass + + # virtual void setBuffer(BufferBase* buffer); + + def setBuffer(self, buffer): + self._buffer = buffer + return + + # virtual void setListener(ConnectorInfo& info, + # ConnectorListeners* listeners); + + def setListener(self, info, listeners): + self._profile = info + self._listeners = listeners + return + + # virtual void setConnector(OutPortConnector* connector); + + def setConnector(self, connector): + self._connector = connector + return + + # inline void onBufferRead(const cdrMemoryStream& data) + + def onBufferRead(self, data): + if self._listeners and self._profile: + _, data = self._listeners.notifyData( + OpenRTM_aist.ConnectorDataListenerType.ON_BUFFER_READ, self._profile, data) + return data + + # inline void onSend(const cdrMemoryStream& data) + + def onSend(self, data): + if self._listeners and self._profile: + _, data = self._listeners.notifyData( + OpenRTM_aist.ConnectorDataListenerType.ON_SEND, self._profile, data) + return data + + # inline void onBufferEmpty() + + def onBufferEmpty(self): + if self._listeners and self._profile: + self._listeners.notify( + OpenRTM_aist.ConnectorListenerType.ON_BUFFER_EMPTY, self._profile) + return + + # inline void onBufferReadTimeout() + + def onBufferReadTimeout(self): + if self._listeners and self._profile: + self._listeners.notify( + OpenRTM_aist.ConnectorListenerType.ON_BUFFER_READ_TIMEOUT, self._profile) + return + + # inline void onSenderEmpty() + + def onSenderEmpty(self): + if self._listeners and self._profile: + self._listeners.notify( + OpenRTM_aist.ConnectorListenerType.ON_SENDER_EMPTY, self._profile) + return + + # inline void onSenderTimeout() + + def onSenderTimeout(self): + if self._listeners and self._profile: + self._listeners.notify( + OpenRTM_aist.ConnectorListenerType.ON_SENDER_TIMEOUT, self._profile) + return + + # inline void onSenderError() + + def onSenderError(self): + if self._listeners and self._profile: + self._listeners.notify( + OpenRTM_aist.ConnectorListenerType.ON_SENDER_ERROR, self._profile) + return def OutPortDirectProviderInit(): - factory = OpenRTM_aist.OutPortProviderFactory.instance() - factory.addFactory("direct", - OpenRTM_aist.OutPortDirectProvider, - OpenRTM_aist.Delete) + factory = OpenRTM_aist.OutPortProviderFactory.instance() + factory.addFactory("direct", + OpenRTM_aist.OutPortDirectProvider) diff --git a/OpenRTM_aist/OutPortDuplexConnector.py b/OpenRTM_aist/OutPortDuplexConnector.py new file mode 100644 index 00000000..b93faf88 --- /dev/null +++ b/OpenRTM_aist/OutPortDuplexConnector.py @@ -0,0 +1,533 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- + + +## +# @file OutPortDuplexConnector.py +# @brief Bidirectional type connector class +# @date $Date$ +# @author Nobuhiko Miyamoto +# +# Copyright (C) 2019 +# Noriaki Ando +# Robot Innovation Research Center, +# National Institute of +# Advanced Industrial Science and Technology (AIST), Japan +# All rights reserved. +# + +import OpenRTM_aist +import threading + + +## +# @if jp +# @class OutPortPullConnector +# @brief OutPortPullConnector クラス +# +# +# @since 2.0.0 +# +# @else +# @class OutPortPullConnector +# @brief OutPortPullConnector class +# +# +# @since 2.0.0 +# +# @endif +# +class OutPortDuplexConnector(OpenRTM_aist.OutPortConnector): + """ + """ + + ## + # @if jp + # @brief コンストラクタ + # + # @param info ConnectorInfo + # @param provider OutPortProvider + # @param listeners ConnectorListeners 型のリスナオブジェクトリスト + # @param buffer CdrBufferBase 型のバッファ + # + # @else + # @brief Constructor + # + # + # @param info ConnectorInfo + # @param provider OutPortProvider + # @param listeners ConnectorListeners type lsitener object list + # @param buffer CdrBufferBase type buffer + # + # @endif + # + # OutPortPullConnector(ConnectorInfo info, + # OutPortProvider* provider, + # ConnectorListeners& listeners, + # CdrBufferBase* buffer = 0); + def __init__(self, info, provider, listeners, buffer=None): + OpenRTM_aist.OutPortConnector.__init__(self, info) + self._provider = provider + self._listeners = listeners + + if not self._provider: + self._rtcout.RTC_ERROR( + "Exeption: in OutPortPullConnector.__init__().") + raise + + self._buffer = buffer + self._info = info + self._provider.init(info.properties) + self._provider.setConnector(self) + self._provider.setListener(info, self._listeners) + + self._consumer = None + self._isReadableCallback = None + self._readCallback = None + + self._marshaling_type = info.properties.getProperty( + "marshaling_type", "cdr") + self._marshaling_type = self._marshaling_type.strip() + + self._serializer = None + + self.onConnect() + + return + + ## + # @if jp + # @brief デストラクタ + # + # disconnect() が呼ばれ、provider, buffer が解体・削除される。 + # + # @else + # + # @brief Destructor + # + # This operation calls disconnect(), which destructs and deletes + # the consumer, the publisher and the buffer. + # + # @endif + # + + def __del__(self): + return + + ## + # @if jp + # @brief データの書き込み + # + # 設定したConsumerオブジェクトによりInPort側にデータを送信する + # 戻り値は設定したConsumerオブジェクトに依存する + # + # @param self + # @param data 書き込むデータ + # @return リターンコード + # + # @else + # + # @param self + # @param data + # @return + # + # @endif + # + # virtual ReturnCode write(const cdrMemoryStream& data); + + def write(self, data): + self._rtcout.RTC_TRACE("write()") + + if self._consumer: + ret, cdr_data = self.serializeData(data) + if ret == self.PORT_OK: + return self._consumer.put(cdr_data) + else: + return ret + else: + return self.PORT_ERROR + + ## + # @if jp + # @brief データ書き込み可能かOutPort側に確認 + # + # 設定したConsumerオブジェクトによりInPort側にデー化書き込み可能かを確認する + # 戻り値は設定したConsumerオブジェクトに依存する + # + # @param self + # @param retry True:再検索、False:通常の書き込み確認 + # @return True:書き込み可能、False:書き込み不可 + # + # @else + # + # @brief + # + # @param self + # @param retry + # @return + # + # @endif + # + def isWritable(self, retry=False): + if self._consumer: + return self._consumer.isWritable(retry) + return False + + ## + # @if jp + # @brief データ読み込み + # InPort側からリモートに呼び出す + # 内部でデータ読み込み時のリスナが呼び出される + # 戻り値はリスナに依存する + # + # @param self + # @param data 読み込んだデータを格納する変数 + # @return リターンコード + # BUFFER_OK:正常完了 + # PRECONDITION_NOT_MET:エラー + # + # @else + # + # @brief + # + # @param self + # @param data + # @return + # + # @endif + # + def read(self, data=None): + if self._readCallback: + ret, data = self._readCallback() + return ret, data + return OpenRTM_aist.BufferStatus.PRECONDITION_NOT_MET, data + + ## + # @if jp + # @brief データ読み込み可能かを確認 + # InPort側からリモートに呼び出す + # 内部でデータ読み込み確認時のリスナが呼び出される + # 戻り値はリスナに依存する + # + # @param self + # @param retry True:再検索、False:通常の読み込み確認 + # @return True:読み込み可能、False:読み込み不可 + # + # @else + # + # @brief + # + # @param self + # @param retry + # @return + # + # @endif + # + def isReadable(self, retry=False): + if self._isReadableCallback: + return self._isReadableCallback(self, retry) + return False + + ## + # @if jp + # @brief データ読み込み時のリスナを登録 + # + # @param self + # @param listener リスナ + # + # @else + # + # @brief + # + # @param self + # @return + # + # @endif + # + + def setReadListener(self, listener): + self._readCallback = listener + + ## + # @if jp + # @brief データ読み込み確認時のリスナを登録 + # + # @param self + # @param listener リスナ + # + # @else + # + # @brief + # + # @param self + # @return + # + # @endif + # + def setIsReadableListener(self, listener): + self._isReadableCallback = listener + + ## + # @if jp + # @brief 接続解除 + # + # consumer, publisher, buffer が解体・削除される。 + # + # @else + # + # @brief disconnect + # + # This operation destruct and delete the consumer, the publisher + # and the buffer. + # + # @endif + # + # virtual ReturnCode disconnect(); + def disconnect(self): + self._rtcout.RTC_TRACE("disconnect()") + self.onDisconnect() + # delete provider + if self._provider: + self._provider.exit() + self._provider = None + + if self._serializer: + self._rtcout.RTC_DEBUG("delete serializer") + self._serializer = None + + if self._consumer: + self._rtcout.RTC_DEBUG("delete consumer") + cfactory = OpenRTM_aist.InPortConsumerFactory.instance() + + self._consumer = None + + return self.PORT_OK + + ## + # @if jp + # @brief Buffer を取得する + # + # Connector が保持している Buffer を返す + # + # @else + # @brief Getting Buffer + # + # This operation returns this connector's buffer + # + # @endif + # + # virtual CdrBufferBase* getBuffer(); + + def getBuffer(self): + return self._buffer + + ## + # @if jp + # @brief アクティブ化 + # + # このコネクタをアクティブ化する + # + # @else + # + # @brief Connector activation + # + # This operation activates this connector + # + # @endif + # + # virtual void activate(){}; // do nothing + + def activate(self): # do nothing + pass + + ## + # @if jp + # @brief 非アクティブ化 + # + # このコネクタを非アクティブ化する + # + # @else + # + # @brief Connector deactivation + # + # This operation deactivates this connector + # + # @endif + # + # virtual void deactivate(){}; // do nothing + + def deactivate(self): # do nothing + pass + + ## + # @if jp + # @brief Bufferの生成 + # @else + # @brief create buffer + # @endif + # + # CdrBufferBase* createBuffer(ConnectorInfo& info); + + def createBuffer(self, info): + buf_type = info.properties.getProperty("buffer_type", "ring_buffer") + return OpenRTM_aist.CdrBufferFactory.instance().createObject(buf_type) + + ## + # @if jp + # @brief 接続確立時にコールバックを呼ぶ + # @else + # @brief Invoke callback when connection is established + # @endif + # void onConnect() + + def onConnect(self): + if self._listeners and self._profile: + self._listeners.notify(OpenRTM_aist.ConnectorListenerType.ON_CONNECT, self._profile) + return + + ## + # @if jp + # @brief 接続切断時にコールバックを呼ぶ + # @else + # @brief Invoke callback when connection is destroied + # @endif + # void onDisconnect() + + def onDisconnect(self): + if self._listeners and self._profile: + self._listeners.notify(OpenRTM_aist.ConnectorListenerType.ON_DISCONNECT, self._profile) + return + + ## + # @if jp + # @brief コンシューマの設定 + # @else + # @brief set Consumer + # @endif + def setConsumer(self, consumer): + self._consumer = consumer + self._consumer.setListener(self._info, self._listeners) + + ## + # @if jp + # @brief データの符号化 + # @param self + # @param cdr 符号化前のデータ + # @return ret, data + # ret:リターンコード + # PORT_OK:正常完了 + # PRECONDITION_NOT_MET:サポートされていないエンディアン + # SERIALIZE_ERROR:符号化処理でエラー + # PRECONDITION_NOT_MET:その他のエラー + # data:符号化後のデータ + # @else + # @brief + # @param self + # @param cdr + # @return + # @endif + + def serializeData(self, data): + if self._serializer is None: + self._rtcout.RTC_ERROR("serializer creation failure.") + return self.UNKNOWN_ERROR, cdr_data + self._serializer.isLittleEndian(self._endian) + ser_ret, cdr_data = self._serializer.serialize(data) + if ser_ret == OpenRTM_aist.ByteDataStreamBase.SERIALIZE_NOT_SUPPORT_ENDIAN: + self._rtcout.RTC_ERROR( + "write(): endian %s is not support.", self._endian) + return self.UNKNOWN_ERROR, cdr_data + elif ser_ret == OpenRTM_aist.ByteDataStreamBase.SERIALIZE_ERROR: + self._rtcout.RTC_ERROR("unkown error.") + return self.UNKNOWN_ERROR, cdr_data + elif ser_ret == OpenRTM_aist.ByteDataStreamBase.SERIALIZE_NOTFOUND: + self._rtcout.RTC_ERROR( + "write(): serializer %s is not support.", self._marshaling_type) + return self.UNKNOWN_ERROR, cdr_data + return self.PORT_OK, cdr_data + + ## + # @if jp + # @brief コンシューマのインターフェースの登録を取り消す + # @param prop コネクタプロファイルのプロパティ + # @else + # @brief + # @param prop + # @endif + def unsubscribeInterface(self, prop): + if self._consumer: + self._consumer.unsubscribeInterface(prop) + + + def setDataType(self, data): + OpenRTM_aist.OutPortConnector.setDataType(self, data) + self._serializer = OpenRTM_aist.SerializerFactories.instance().createSerializer(self._marshaling_type, data) + + +## +# @if jp +# @class ReadListenerBase +# @brief ReadListenerBase クラス +# +# 読み込み時リスナのベースクラス +# +# @since 2.0.0 +# +# @else +# @class ReadListenerBase +# @brief ReadListenerBase class +# +# +# @since 2.0.0 +# +# @endif +# +class ReadListenerBase(object): + ## + # @if jp + # @brief 仮想コールバック関数 + # @param self + # @return 読み込んだデータ + # @else + # @brief + # @param self + # @return 読み込んだデータ + # @endif + def __call__(self): + return (OpenRTM_aist.BufferStatus.PRECONDITION_NOT_MET, None) + +## +# @if jp +# @class IsReadableListenerBase +# @brief IsReadableListenerBase クラス +# +# 読み込み確認時リスナのベースクラス +# +# @since 2.0.0 +# +# @else +# @class IsReadableListenerBase +# @brief IsReadableListenerBase class +# +# +# @since 2.0.0 +# +# @endif +# + + +class IsReadableListenerBase(object): + ## + # @if jp + # @brief 仮想コールバック関数 + # @param self + # @param con OutPortConnector + # @return True:読み込み可、False:読み込み不可 + # @else + # @brief + # @param self + # @param con + # @return + # @endif + def __call__(self, con): + return False diff --git a/OpenRTM_aist/OutPortProvider.py b/OpenRTM_aist/OutPortProvider.py index 6cf08884..a52e0823 100644 --- a/OpenRTM_aist/OutPortProvider.py +++ b/OpenRTM_aist/OutPortProvider.py @@ -1,5 +1,5 @@ #!/usr/bin/env python -# -*- coding: euc-jp -*- +# -*- coding: utf-8 -*- ## # @file OutPortProvider.py @@ -16,7 +16,6 @@ # All rights reserved. - import OpenRTM_aist ## @@ -25,221 +24,221 @@ # @class OutPortProvider # @brief OutPortProvider # -# - Port ФƲ󶡤Ƥ뤫롣 -# PortProfile properties Provider ˴ؤɲä롣 +# - Port に対して何を提供しているかを宣言する。 +# PortProfile の properties に Provider に関する情報を追加する。 # -# () OutPort Provide +# (例) OutPort を Provide する場合 # -# OutPortCorbaProvider ʲ +# OutPortCorbaProvider が以下を宣言 # - dataport.interface_type = CORBA_Any # - dataport.dataflow_type = Push, Pull # - dataport.subscription_type = Once, New, Periodic -# +# # @since 0.4.0 # # @else # # # @endif -class OutPortProvider(OpenRTM_aist.DataPortStatus): - """ - """ - - - - ## - # @if jp - # @brief 󥿡եץե뤿Υե󥯥 - # @else - # @brief Functor to publish interface profile - # @endif - # - class publishInterfaceProfileFunc: - def __init__(self, prop): - self._prop = prop - - def __call__(self, provider): - provider.publishInterfaceProfile(self._prop) - - - ## - # @if jp - # @brief 󥹥ȥ饯 - # - # 󥹥ȥ饯 - # - # @param self - # - # @else - # @brief Constructor - # @endif - def __init__(self): - self._properties = [] - self._portType = "" - self._dataType = "" - self._interfaceType = "" - self._dataflowType = "" - self._subscriptionType = "" - self._rtcout = OpenRTM_aist.Manager.instance().getLogbuf("OutPortProvider") - - ## - # @if jp - # @brief λ - # - # @else - # @brief - # - # - # - # @endif - # - def exit(self): - pass - - ## - # @if jp - # @brief InterfaceProfile - # - # InterfaceProfile롣 - # ǻꤹץѥƥ NameValue ֥Ȥ - # dataport.interface_type ͤĴ١ݡȤꤵƤ - # 󥿡եפȰפΤ߾롣 - # - # @param self - # @param prop InterfaceProfileץѥƥ - # - # @else - # - # @endif - # virtual void publishInterfaceProfile(SDOPackage::NVList& properties); - def publishInterfaceProfile(self, prop): - OpenRTM_aist.NVUtil.appendStringValue(prop, "dataport.interface_type", self._interfaceType) - OpenRTM_aist.NVUtil.append(prop, self._properties) - - ## - # @if jp - # @brief Interface - # - # Interface롣 - # ǻꤹץѥƥ NameValue ֥Ȥ - # dataport.interface_type ͤĴ١ݡȤꤵƤʤ - # NameValue ˾ɲä롣 - # ǤƱ쥤󥿡եϿѤߤξϲԤʤ - # - # @param self - # @param prop InterfaceProfileץѥƥ - # - # @else - # - # @endif - # virtual bool publishInterface(SDOPackage::NVList& properties); - def publishInterface(self, prop): - if not OpenRTM_aist.NVUtil.isStringValue(prop,"dataport.interface_type",self._interfaceType): - return False - - OpenRTM_aist.NVUtil.append(prop,self._properties) - return True - - - ## - # @if jp - # @brief ݡȥפꤹ - # - # ǻꤷݡȥפꤹ롣 - # - # @param self - # @param port_type оݥݡȥ - # - # @else - # - # @endif - def setPortType(self, port_type): - self._portType = port_type - - - ## - # @if jp - # @brief ǡפꤹ - # - # ǻꤷǡפꤹ롣 - # - # @param self - # @param data_type оݥǡ - # - # @else - # - # @endif - def setDataType(self, data_type): - self._dataType = data_type - - - ## - # @if jp - # @brief 󥿡եפꤹ - # - # ǻꤷ󥿡եפꤹ롣 - # - # @param self - # @param interface_type оݥ󥿡ե - # - # @else - # - # @endif - def setInterfaceType(self, interface_type): - self._interfaceType = interface_type - - - ## - # @if jp - # @brief ǡեפꤹ - # - # ǻꤷǡեפꤹ롣 - # - # @param self - # @param dataflow_type оݥǡե - # - # @else - # - # @endif - def setDataFlowType(self, dataflow_type): - self._dataflowType = dataflow_type - - - ## - # @if jp - # @brief ֥ץ󥿥פꤹ - # - # ǻꤷ֥ץ󥿥פꤹ롣 - # - # @param self - # @param subs_type оݥ֥ץ󥿥 - # - # @else - # - # @endif - def setSubscriptionType(self, subs_type): - self._subscriptionType = subs_type +class OutPortProvider(OpenRTM_aist.DataPortStatus): + """ + """ + + ## + # @if jp + # @brief インターフェースプロファイルを公開するたのファンクタ + # @else + # @brief Functor to publish interface profile + # @endif + # + class publishInterfaceProfileFunc: + def __init__(self, prop): + self._prop = prop + + def __call__(self, provider): + provider.publishInterfaceProfile(self._prop) + + ## + # @if jp + # @brief コンストラクタ + # + # コンストラクタ + # + # @param self + # + # @else + # @brief Constructor + # @endif + + def __init__(self): + self._properties = [] + self._portType = "" + self._dataType = "" + self._interfaceType = "" + self._dataflowType = "" + self._subscriptionType = "" + self._rtcout = OpenRTM_aist.Manager.instance().getLogbuf("OutPortProvider") + + ## + # @if jp + # @brief 終了処理 + # + # @else + # @brief + # + # + # + # @endif + # + def exit(self): + pass + + ## + # @if jp + # @brief InterfaceProfile情報を公開する + # + # InterfaceProfile情報を公開する。 + # 引数で指定するプロパティ情報内の NameValue オブジェクトの + # dataport.interface_type 値を調べ、当該ポートに設定されている + # インターフェースタイプと一致する場合のみ情報を取得する。 + # + # @param self + # @param prop InterfaceProfile情報を受け取るプロパティ + # + # @else + # + # @endif + # virtual void publishInterfaceProfile(SDOPackage::NVList& properties); + def publishInterfaceProfile(self, prop): + OpenRTM_aist.NVUtil.appendStringValue( + prop, "dataport.interface_type", self._interfaceType) + OpenRTM_aist.NVUtil.append(prop, self._properties) + + ## + # @if jp + # @brief Interface情報を公開する + # + # Interface情報を公開する。 + # 引数で指定するプロパティ情報内の NameValue オブジェクトの + # dataport.interface_type 値を調べ、当該ポートに設定されていなければ + # NameValue に情報を追加する。 + # すでに同一インターフェースが登録済みの場合は何も行わない。 + # + # @param self + # @param prop InterfaceProfile情報を受け取るプロパティ + # + # @else + # + # @endif + # virtual bool publishInterface(SDOPackage::NVList& properties); + def publishInterface(self, prop): + if not OpenRTM_aist.NVUtil.isStringValue( + prop, "dataport.interface_type", self._interfaceType): + return False + + OpenRTM_aist.NVUtil.append(prop, self._properties) + return True + + ## + # @if jp + # @brief ポートタイプを設定する + # + # 引数で指定したポートタイプを設定する。 + # + # @param self + # @param port_type 設定対象ポートタイプ + # + # @else + # + # @endif + + def setPortType(self, port_type): + self._portType = port_type + + ## + # @if jp + # @brief データタイプを設定する + # + # 引数で指定したデータタイプを設定する。 + # + # @param self + # @param data_type 設定対象データタイプ + # + # @else + # + # @endif + + def setDataType(self, data_type): + self._dataType = data_type + + ## + # @if jp + # @brief インターフェースタイプを設定する + # + # 引数で指定したインターフェースタイプを設定する。 + # + # @param self + # @param interface_type 設定対象インターフェースタイプ + # + # @else + # + # @endif + + def setInterfaceType(self, interface_type): + self._interfaceType = interface_type + + ## + # @if jp + # @brief データフロータイプを設定する + # + # 引数で指定したデータフロータイプを設定する。 + # + # @param self + # @param dataflow_type 設定対象データフロータイプ + # + # @else + # + # @endif + + def setDataFlowType(self, dataflow_type): + self._dataflowType = dataflow_type + + ## + # @if jp + # @brief サブスクリプションタイプを設定する + # + # 引数で指定したサブスクリプションタイプを設定する。 + # + # @param self + # @param subs_type 設定対象サブスクリプションタイプ + # + # @else + # + # @endif + + def setSubscriptionType(self, subs_type): + self._subscriptionType = subs_type + outportproviderfactory = None -class OutPortProviderFactory(OpenRTM_aist.Factory,OutPortProvider): - def __init__(self): - OpenRTM_aist.Factory.__init__(self) - pass +class OutPortProviderFactory(OpenRTM_aist.Factory, OutPortProvider): + def __init__(self): + OpenRTM_aist.Factory.__init__(self) + pass + + def __del__(self): + pass - def __del__(self): - pass + def instance(): + global outportproviderfactory + if outportproviderfactory is None: + outportproviderfactory = OutPortProviderFactory() - def instance(): - global outportproviderfactory - - if outportproviderfactory is None: - outportproviderfactory = OutPortProviderFactory() - - return outportproviderfactory + return outportproviderfactory - instance = staticmethod(instance) + instance = staticmethod(instance) diff --git a/OpenRTM_aist/OutPortPullConnector.py b/OpenRTM_aist/OutPortPullConnector.py index fdf8f206..2688f8a7 100644 --- a/OpenRTM_aist/OutPortPullConnector.py +++ b/OpenRTM_aist/OutPortPullConnector.py @@ -1,5 +1,5 @@ #!/usr/bin/env python -# -*- coding: euc-jp -*- +# -*- coding: utf-8 -*- ## @@ -17,8 +17,6 @@ # All rights reserved. # -from omniORB import cdrMarshal -from omniORB import any import OpenRTM_aist import threading @@ -27,24 +25,24 @@ ## # @if jp # @class OutPortPullConnector -# @brief OutPortPullConnector 饹 +# @brief OutPortPullConnector クラス # -# OutPort pull ǡեΤ Connector 饹Υ -# Ȥϡ³ dataflow_type pull ꤵ줿硢 -# OutPort ˤäͭ졢InPortPullConnector Фˤʤäơ -# ǡݡȤ pull Υǡե¸롣Ĥ³Фơ -# ĤΥǡȥ꡼󶡤ͣ Connector б롣 -# Connector ³ UUID ID ˤ̤롣 +# OutPort の pull 型データフローのための Connector クラス。このオブ +# ジェクトは、接続時に dataflow_type に pull が指定された場合、 +# OutPort によって生成・所有され、InPortPullConnector と対になって、 +# データポートの pull 型のデータフローを実現する。一つの接続に対して、 +# 一つのデータストリームを提供する唯一の Connector が対応する。 +# Connector は 接続時に生成される UUID 形式の ID により区別される。 # -# OutPortPullConnector ϰʲλĤΥ֥Ȥͭ롣 +# OutPortPullConnector は以下の三つのオブジェクトを所有し管理する。 # # - InPortConsumer # - Buffer # -# OutPort ˽񤭹ޤ줿ǡ OutPortPullConnector::write() -# Buffer ˽񤭹ޤ롣InPortPullConnector -# OutPortPullConnector ǡɤ߽ФȤ InPort ˥ǡ -# ž롣 +# OutPort に書き込まれたデータは OutPortPullConnector::write() に渡 +# され Buffer に書き込まれる。InPortPullConnector が +# OutPortPullConnector からデータを読み出すことで InPort にデータが +# 転送される。 # # @since 1.0.0 # @@ -76,336 +74,353 @@ # @endif # class OutPortPullConnector(OpenRTM_aist.OutPortConnector): - """ - """ - - ## - # @if jp - # @brief 󥹥ȥ饯 - # - # OutPortPullConnector Υ󥹥ȥ饯ϥ֥˲ - # ˤȤ롣ConnectorInfo ³ޤߡξ˽Х - # ե롣OutPort 󥿡եΥץХ֥ - # ȤؤΥݥ󥿤ꡢͭĤΤǡOutPortPullConnector - # OutPortProvider βǤġƼ磻٥ȤФ륳Х - # 󶡤 ConnectorListeners Ŭڤʥߥ󥰤ǥ - # ХåƤӽФǡХåե⤷ OutPortBase 󶡤 - # ϤΥݥ󥿤롣 - # - # @param info ConnectorInfo - # @param provider OutPortProvider - # @param listeners ConnectorListeners Υꥹʥ֥ȥꥹ - # @param buffer CdrBufferBase ΥХåե - # - # @else - # @brief Constructor - # - # OutPortPullConnector's constructor is given the following - # arguments. According to ConnectorInfo which includes - # connection information, a buffer is created. It is also given - # a pointer to the provider object for the OutPort interface. - # The owner-ship of the pointer is owned by this - # OutPortPullConnector, it has responsibility to destruct the - # OutPortProvider. OutPortPullConnector also has - # ConnectorListeners to provide event callback mechanisms, and - # they would be called at the proper timing. If data buffer is - # given by OutPortBase, the pointer to the buffer is also given - # as arguments. - # - # @param info ConnectorInfo - # @param provider OutPortProvider - # @param listeners ConnectorListeners type lsitener object list - # @param buffer CdrBufferBase type buffer - # - # @endif - # - # OutPortPullConnector(ConnectorInfo info, - # OutPortProvider* provider, - # ConnectorListeners& listeners, - # CdrBufferBase* buffer = 0); - def __init__(self, info, provider, listeners, buffer = None): - OpenRTM_aist.OutPortConnector.__init__(self, info) - self._provider = provider - self._listeners = listeners - self._buffer = buffer - self._directMode = False - - - - if not self._buffer: - self._buffer = self.createBuffer(info) - - if not self._provider or not self._buffer: - self._rtcout.RTC_ERROR("Exeption: in OutPortPullConnector.__init__().") - raise - - self._buffer.init(info.properties.getNode("buffer")) - self._provider.init(info.properties) - self._provider.setBuffer(self._buffer) - self._provider.setConnector(self) - self._provider.setListener(info, self._listeners) - self.onConnect() - - self._sync_readwrite = False - if OpenRTM_aist.toBool(info.properties.getProperty("sync_readwrite"),"YES","NO",False): - self._sync_readwrite = True - - self._writecompleted_worker = OutPortPullConnector.WorkerThreadCtrl() - self._readcompleted_worker = OutPortPullConnector.WorkerThreadCtrl() - self._readready_worker = OutPortPullConnector.WorkerThreadCtrl() - - return - - - ## - # @if jp - # @brief ǥȥ饯 - # - # disconnect() ƤФ졢provider, buffer Ρ롣 - # - # @else - # - # @brief Destructor - # - # This operation calls disconnect(), which destructs and deletes - # the consumer, the publisher and the buffer. - # - # @endif - # - def __del__(self): - return - - - ## - # @if jp - # @brief ǡν񤭹 - # - # PublisherФƥǡ񤭹ߡˤбInPort - # ǡž롣 - # - # @else - # - # @brief Writing data - # - # This operation writes data into publisher and then the data - # will be transferred to correspondent InPort. - # - # @endif - # - # virtual ReturnCode write(const cdrMemoryStream& data); - def write(self, data): - if self._directMode: - return self.PORT_OK - # data -> (conversion) -> CDR stream - cdr_data = None - if self._endian is not None: - cdr_data = cdrMarshal(any.to_any(data).typecode(), data, self._endian) - else: - self._rtcout.RTC_ERROR("write(): endian %s is not support.",self._endian) - return self.UNKNOWN_ERROR - if self._buffer: - if self._sync_readwrite: - self._readready_worker._cond.acquire() - while not self._readready_worker._completed: - self._readready_worker._cond.wait() - self._readready_worker._cond.release() - - self._buffer.write(cdr_data) - - if self._sync_readwrite: - self._writecompleted_worker._completed = True - self._writecompleted_worker._cond.acquire() - self._writecompleted_worker._cond.notify() - self._writecompleted_worker._cond.release() - - self._readcompleted_worker._cond.acquire() - while not self._readcompleted_worker._completed: - self._readcompleted_worker._cond.wait() - self._readcompleted_worker._cond.release() - - self._writecompleted_worker._completed = False - else: - return self.UNKNOWN_ERROR - return self.PORT_OK - - def read(self, data): - - if self._sync_readwrite: - self._readcompleted_worker._completed = False - - self._readready_worker._completed = True - self._readready_worker._cond.acquire() - self._readready_worker._cond.notify() - self._readready_worker._cond.release() - - self._writecompleted_worker._cond.acquire() - while not self._writecompleted_worker._completed: - self._writecompleted_worker._cond.wait() - self._writecompleted_worker._cond.release() - - - if self._buffer.empty(): - self._rtcout.RTC_ERROR("buffer is empty.") - data[0] = "" - return OpenRTM_aist.BufferStatus.BUFFER_EMPTY - - - ret = self._buffer.read(data) - - if self._sync_readwrite: - self._readcompleted_worker._completed = True - self._readcompleted_worker._cond.acquire() - self._readcompleted_worker._cond.notify() - self._readcompleted_worker._cond.release() - - self._readready_worker._completed = False - - - return ret - - - ## - # @if jp - # @brief ³ - # - # consumer, publisher, buffer Ρ롣 - # - # @else - # - # @brief disconnect - # - # This operation destruct and delete the consumer, the publisher - # and the buffer. - # - # @endif - # - # virtual ReturnCode disconnect(); - def disconnect(self): - self._rtcout.RTC_TRACE("disconnect()") - self.onDisconnect() - # delete provider - if self._provider: - OpenRTM_aist.OutPortProviderFactory.instance().deleteObject(self._provider) - self._provider.exit() - self._provider = 0 - - # delete buffer - if self._buffer: - OpenRTM_aist.CdrBufferFactory.instance().deleteObject(self._buffer) - self._buffer = 0 - - - - return self.PORT_OK - - - ## - # @if jp - # @brief Buffer - # - # Connector ݻƤ Buffer ֤ - # - # @else - # @brief Getting Buffer - # - # This operation returns this connector's buffer - # - # @endif - # - # virtual CdrBufferBase* getBuffer(); - def getBuffer(self): - return self._buffer - - - ## - # @if jp - # @brief ƥֲ - # - # Υͥ򥢥ƥֲ - # - # @else - # - # @brief Connector activation - # - # This operation activates this connector - # - # @endif - # - # virtual void activate(){}; // do nothing - def activate(self): # do nothing - pass - - - ## - # @if jp - # @brief 󥢥ƥֲ - # - # Υͥ󥢥ƥֲ - # - # @else - # - # @brief Connector deactivation - # - # This operation deactivates this connector - # - # @endif - # - # virtual void deactivate(){}; // do nothing - def deactivate(self): # do nothing - pass - - - ## - # @if jp - # @brief Buffer - # @else - # @brief create buffer - # @endif - # - # CdrBufferBase* createBuffer(ConnectorInfo& info); - def createBuffer(self, info): - buf_type = info.properties.getProperty("buffer_type","ring_buffer") - return OpenRTM_aist.CdrBufferFactory.instance().createObject(buf_type) - - - ## - # @if jp - # @brief ³Ω˥ХåƤ - # @else - # @brief Invoke callback when connection is established - # @endif - # void onConnect() - def onConnect(self): - if self._listeners and self._profile: - self._listeners.connector_[OpenRTM_aist.ConnectorListenerType.ON_CONNECT].notify(self._profile) - return - - - ## - # @if jp - # @brief ³ǻ˥ХåƤ - # @else - # @brief Invoke callback when connection is destroied - # @endif - # void onDisconnect() - def onDisconnect(self): - if self._listeners and self._profile: - self._listeners.connector_[OpenRTM_aist.ConnectorListenerType.ON_DISCONNECT].notify(self._profile) - return - - ## - # @if jp - # @brief 쥯³⡼ɤ - # @else - # @brief - # @endif - # void onDisconnect() - def setDirectMode(self): - self._directMode = True - - class WorkerThreadCtrl: - def __init__(self): - self._mutex = threading.RLock() - self._cond = threading.Condition(self._mutex) - self._completed = False - + """ + """ + + ## + # @if jp + # @brief コンストラクタ + # + # OutPortPullConnector のコンストラクタはオブジェクト生成時に下記 + # を引数にとる。ConnectorInfo は接続情報を含み、この情報に従いバッ + # ファ等を生成する。OutPort インターフェースのプロバイダオブジェク + # トへのポインタを取り、所有権を持つので、OutPortPullConnector は + # OutPortProvider の解体責任を持つ。各種イベントに対するコールバッ + # ク機構を提供する ConnectorListeners を持ち、適切なタイミングでコー + # ルバックを呼び出す。データバッファがもし OutPortBase から提供さ + # れる場合はそのポインタを取る。 + # + # @param info ConnectorInfo + # @param provider OutPortProvider + # @param listeners ConnectorListeners 型のリスナオブジェクトリスト + # @param buffer CdrBufferBase 型のバッファ + # + # @else + # @brief Constructor + # + # OutPortPullConnector's constructor is given the following + # arguments. According to ConnectorInfo which includes + # connection information, a buffer is created. It is also given + # a pointer to the provider object for the OutPort interface. + # The owner-ship of the pointer is owned by this + # OutPortPullConnector, it has responsibility to destruct the + # OutPortProvider. OutPortPullConnector also has + # ConnectorListeners to provide event callback mechanisms, and + # they would be called at the proper timing. If data buffer is + # given by OutPortBase, the pointer to the buffer is also given + # as arguments. + # + # @param info ConnectorInfo + # @param provider OutPortProvider + # @param listeners ConnectorListeners type lsitener object list + # @param buffer CdrBufferBase type buffer + # + # @endif + # + # OutPortPullConnector(ConnectorInfo info, + # OutPortProvider* provider, + # ConnectorListeners& listeners, + # CdrBufferBase* buffer = 0); + def __init__(self, info, provider, listeners, buffer=None): + OpenRTM_aist.OutPortConnector.__init__(self, info) + self._provider = provider + self._listeners = listeners + self._buffer = buffer + self._directMode = False + + if not self._buffer: + self._buffer = self.createBuffer(info) + + if not self._provider or not self._buffer: + self._rtcout.RTC_ERROR( + "Exeption: in OutPortPullConnector.__init__().") + raise + + self._buffer.init(info.properties.getNode("buffer")) + self._provider.init(info.properties) + self._provider.setBuffer(self._buffer) + self._provider.setConnector(self) + self._provider.setListener(info, self._listeners) + self.onConnect() + + self._sync_readwrite = False + if OpenRTM_aist.toBool(info.properties.getProperty( + "sync_readwrite"), "YES", "NO", False): + self._sync_readwrite = True + + self._writecompleted_worker = OutPortPullConnector.WorkerThreadCtrl() + self._readcompleted_worker = OutPortPullConnector.WorkerThreadCtrl() + self._readready_worker = OutPortPullConnector.WorkerThreadCtrl() + + self._marshaling_type = info.properties.getProperty( + "marshaling_type", "cdr") + self._marshaling_type = self._marshaling_type.strip() + + self._serializer = None + + return + + ## + # @if jp + # @brief デストラクタ + # + # disconnect() が呼ばれ、provider, buffer が解体・削除される。 + # + # @else + # + # @brief Destructor + # + # This operation calls disconnect(), which destructs and deletes + # the consumer, the publisher and the buffer. + # + # @endif + # + + def __del__(self): + return + + ## + # @if jp + # @brief データの書き込み + # + # Publisherに対してデータを書き込み、これにより対応するInPortへ + # データが転送される。 + # + # @else + # + # @brief Writing data + # + # This operation writes data into publisher and then the data + # will be transferred to correspondent InPort. + # + # @endif + # + # virtual ReturnCode write(const cdrMemoryStream& data); + + def write(self, data): + if self._directMode: + return self.PORT_OK + # data -> (conversion) -> CDR stream + if self._serializer is None: + self._rtcout.RTC_ERROR("serializer creation failure.") + return self.UNKNOWN_ERROR + + self._serializer.isLittleEndian(self._endian) + ser_ret, cdr_data = self._serializer.serialize(data) + if ser_ret == OpenRTM_aist.ByteDataStreamBase.SERIALIZE_NOT_SUPPORT_ENDIAN: + self._rtcout.RTC_ERROR( + "write(): endian %s is not support.", self._endian) + return self.UNKNOWN_ERROR + elif ser_ret == OpenRTM_aist.ByteDataStreamBase.SERIALIZE_ERROR: + self._rtcout.RTC_ERROR("unkown error.") + return self.UNKNOWN_ERROR + elif ser_ret == OpenRTM_aist.ByteDataStreamBase.SERIALIZE_NOTFOUND: + self._rtcout.RTC_ERROR( + "write(): serializer %s is not support.", + self._marshaling_type) + return self.UNKNOWN_ERROR + + if self._buffer: + if self._sync_readwrite: + self._readready_worker._cond.acquire() + while not self._readready_worker._completed: + self._readready_worker._cond.wait() + self._readready_worker._cond.release() + + self._buffer.write(cdr_data) + + if self._sync_readwrite: + self._writecompleted_worker._completed = True + self._writecompleted_worker._cond.acquire() + self._writecompleted_worker._cond.notify() + self._writecompleted_worker._cond.release() + + self._readcompleted_worker._cond.acquire() + while not self._readcompleted_worker._completed: + self._readcompleted_worker._cond.wait() + self._readcompleted_worker._cond.release() + + self._writecompleted_worker._completed = False + else: + return self.UNKNOWN_ERROR + return self.PORT_OK + + def read(self, data=None): + + if self._sync_readwrite: + self._readcompleted_worker._completed = False + + self._readready_worker._completed = True + self._readready_worker._cond.acquire() + self._readready_worker._cond.notify() + self._readready_worker._cond.release() + + self._writecompleted_worker._cond.acquire() + while not self._writecompleted_worker._completed: + self._writecompleted_worker._cond.wait() + self._writecompleted_worker._cond.release() + + if self._buffer.empty(): + self._rtcout.RTC_ERROR("buffer is empty.") + return OpenRTM_aist.BufferStatus.BUFFER_EMPTY, "" + + ret, data = self._buffer.read() + + if self._sync_readwrite: + self._readcompleted_worker._completed = True + self._readcompleted_worker._cond.acquire() + self._readcompleted_worker._cond.notify() + self._readcompleted_worker._cond.release() + + self._readready_worker._completed = False + + return ret, data + + ## + # @if jp + # @brief 接続解除 + # + # consumer, publisher, buffer が解体・削除される。 + # + # @else + # + # @brief disconnect + # + # This operation destruct and delete the consumer, the publisher + # and the buffer. + # + # @endif + # + # virtual ReturnCode disconnect(); + + def disconnect(self): + self._rtcout.RTC_TRACE("disconnect()") + self.onDisconnect() + # delete provider + if self._provider: + self._provider.exit() + self._provider = None + + # delete buffer + self._buffer = None + + self._serializer = None + + return self.PORT_OK + + ## + # @if jp + # @brief Buffer を取得する + # + # Connector が保持している Buffer を返す + # + # @else + # @brief Getting Buffer + # + # This operation returns this connector's buffer + # + # @endif + # + # virtual CdrBufferBase* getBuffer(); + + def getBuffer(self): + return self._buffer + + ## + # @if jp + # @brief アクティブ化 + # + # このコネクタをアクティブ化する + # + # @else + # + # @brief Connector activation + # + # This operation activates this connector + # + # @endif + # + # virtual void activate(){}; // do nothing + + def activate(self): # do nothing + pass + + ## + # @if jp + # @brief 非アクティブ化 + # + # このコネクタを非アクティブ化する + # + # @else + # + # @brief Connector deactivation + # + # This operation deactivates this connector + # + # @endif + # + # virtual void deactivate(){}; // do nothing + + def deactivate(self): # do nothing + pass + + ## + # @if jp + # @brief Bufferの生成 + # @else + # @brief create buffer + # @endif + # + # CdrBufferBase* createBuffer(ConnectorInfo& info); + + def createBuffer(self, info): + buf_type = info.properties.getProperty("buffer_type", "ring_buffer") + return OpenRTM_aist.CdrBufferFactory.instance().createObject(buf_type) + + ## + # @if jp + # @brief 接続確立時にコールバックを呼ぶ + # @else + # @brief Invoke callback when connection is established + # @endif + # void onConnect() + + def onConnect(self): + if self._listeners and self._profile: + self._listeners.notify( + OpenRTM_aist.ConnectorListenerType.ON_CONNECT, self._profile) + return + + ## + # @if jp + # @brief 接続切断時にコールバックを呼ぶ + # @else + # @brief Invoke callback when connection is destroied + # @endif + # void onDisconnect() + + def onDisconnect(self): + if self._listeners and self._profile: + self._listeners.notify( + OpenRTM_aist.ConnectorListenerType.ON_DISCONNECT, self._profile) + return + + ## + # @if jp + # @brief ダイレクト接続モードに設定 + # @else + # @brief + # @endif + # void onDisconnect() + def setDirectMode(self): + self._directMode = True + + def setDataType(self, data): + OpenRTM_aist.OutPortConnector.setDataType(self, data) + self._serializer = OpenRTM_aist.SerializerFactories.instance().createSerializer(self._marshaling_type, data) + + class WorkerThreadCtrl: + def __init__(self): + self._mutex = threading.RLock() + self._cond = threading.Condition(self._mutex) + self._completed = False diff --git a/OpenRTM_aist/OutPortPushConnector.py b/OpenRTM_aist/OutPortPushConnector.py index 03bb3f01..0841a01f 100644 --- a/OpenRTM_aist/OutPortPushConnector.py +++ b/OpenRTM_aist/OutPortPushConnector.py @@ -1,5 +1,5 @@ #!/usr/bin/env python -# -*- coding: euc-jp -*- +# -*- coding: utf-8 -*- ## @@ -17,8 +17,6 @@ # All rights reserved. # -from omniORB import cdrMarshal -from omniORB import any import OpenRTM_aist @@ -26,25 +24,25 @@ ## # @if jp # @class OutPortPushConnector -# @brief OutPortPushConnector 饹 +# @brief OutPortPushConnector クラス # -# OutPort push ǡեΤ Connector 饹Υ -# Ȥϡ³ dataflow_type push ꤵ줿硢 -# OutPort ˤäͭ졢InPortPushConnector Фˤʤäơ -# ǡݡȤ push Υǡե¸롣Ĥ³Фơ -# ĤΥǡȥ꡼󶡤ͣ Connector б롣 -# Connector ³ UUID ID ˤ̤롣 +# OutPort の push 型データフローのための Connector クラス。このオブ +# ジェクトは、接続時に dataflow_type に push が指定された場合、 +# OutPort によって生成・所有され、InPortPushConnector と対になって、 +# データポートの push 型のデータフローを実現する。一つの接続に対して、 +# 一つのデータストリームを提供する唯一の Connector が対応する。 +# Connector は 接続時に生成される UUID 形式の ID により区別される。 # -# OutPortPushConnector ϰʲλĤΥ֥Ȥͭ롣 +# OutPortPushConnector は以下の三つのオブジェクトを所有し管理する。 # # - InPortConsumer # - Buffer # - Publisher # -# OutPort ˽񤭹ޤ줿ǡ OutPortPushConnector::write() -# 졢Connector Publisher ˥ǡ񤭹ࡣPublisher Ϥ -# ˽äƥǡ Buffer InPortConsumer Ф -# push 뤳Ȥ InPort ˥ǡž롣 +# OutPort に書き込まれたデータは OutPortPushConnector::write() に渡 +# され、Connector は Publisher にデータを書き込む。Publisher はその +# 特性に従ってデータを Buffer から取得し InPortConsumer に対して +# push することで InPort にデータが転送される。 # # @since 1.0.0 # @@ -78,405 +76,445 @@ # @endif # class OutPortPushConnector(OpenRTM_aist.OutPortConnector): - """ - """ - - ## - # @if jp - # @brief 󥹥ȥ饯 - # - # OutPortPushConnector Υ󥹥ȥ饯ϥ֥˲ - # ˤȤ롣ConnectorInfo ³ޤߡξ˽ѥ - # åХåե롣InPort 󥿡եФ - # 󥷥塼ޥ֥ȤؤΥݥ󥿤ꡢͭĤΤǡ - # OutPortPushConnector InPortConsumer βǤġƼ磻 - # ٥ȤФ륳Хå󶡤 ConnectorListeners - # Ŭڤʥߥ󥰤ǥХåƤӽФǡХåե - # OutPortBase 󶡤ϤΥݥ󥿤롣 - # - # @param info ConnectorInfo - # @param consumer InPortConsumer - # @param listeners ConnectorListeners Υꥹʥ֥ȥꥹ - # @param buffer CdrBufferBase ΥХåե - # - # @else - # @brief Constructor - # - # OutPortPushConnector's constructor is given the following - # arguments. According to ConnectorInfo which includes - # connection information, a publisher and a buffer are created. - # It is also given a pointer to the consumer object for the - # InPort interface. The owner-ship of the pointer is owned by - # this OutPortPushConnector, it has responsibility to destruct - # the InPortConsumer. OutPortPushConnector also has - # ConnectorListeners to provide event callback mechanisms, and - # they would be called at the proper timing. If data buffer is - # given by OutPortBase, the pointer to the buffer is also given - # as arguments. - # - # @param info ConnectorInfo - # @param consumer InPortConsumer - # @param listeners ConnectorListeners type lsitener object list - # @param buffer CdrBufferBase type buffer - # - # @endif - # - # OutPortPushConnector(ConnectorInfo info, - # InPortConsumer* consumer, - # ConnectorListeners& listeners, - # CdrBufferBase* buffer = 0); - def __init__(self, info, consumer, listeners, buffer = None): - OpenRTM_aist.OutPortConnector.__init__(self, info) - - self._buffer = buffer - self._consumer = consumer - self._listeners = listeners - - self._directInPort = None - self._inPortListeners = None - - # publisher/buffer creation. This may throw std::bad_alloc; - self._publisher = self.createPublisher(info) - if not self._buffer: - self._buffer = self.createBuffer(info) - - - if not self._publisher or not self._buffer or not self._consumer: - raise - - if self._publisher.init(info.properties) != self.PORT_OK: - raise - - if self._profile.properties.hasKey("serializer"): - endian = self._profile.properties.getProperty("serializer.cdr.endian") - if not endian: - self._rtcout.RTC_ERROR("write(): endian is not set.") - raise - - endian = OpenRTM_aist.split(endian, ",") # Maybe endian is ["little","big"] - endian = OpenRTM_aist.normalize(endian) # Maybe self._endian is "little" or "big" - if endian == "little": - self._endian = True - elif endian == "big": - self._endian = False - else: - self._endian = None - - else: - self._endian = True # little endian - - self._buffer.init(info.properties.getNode("buffer")) - self._consumer.init(info.properties) - self._publisher.setConsumer(self._consumer) - self._publisher.setBuffer(self._buffer) - self._publisher.setListener(self._profile, self._listeners) - - self.onConnect() - return - - - ## - # @if jp - # @brief ǥȥ饯 - # - # disconnect() ƤФ졢consumer, publisher, buffer Ρ롣 - # - # @else - # - # @brief Destructor - # - # This operation calls disconnect(), which destructs and deletes - # the consumer, the publisher and the buffer. - # - # @endif - # - def __del__(self): - return - - ## - # @if jp - # @brief ǡν񤭹 - # - # PublisherФƥǡ񤭹ߡˤбInPortإǡ - # ž롣ェλ PORT_OK ֤롣ʳ - # 硢顼ͤȤơCONNECTION_LOST, BUFFER_FULL, - # BUFFER_ERROR, PORT_ERROR, BUFFER_TIMEOUT, PRECONDITION_NO_MET - # ֤롣 - # - # @return PORT_OK ェλ - # CONNECTION_LOST ³Ȥ - # BUFFER_FULL ХåեդǤ - # BUFFER_ERROR Хåե顼 - # BUFFER_TIMEOUT Хåեؤν񤭹ߤॢȤ - # PRECONDITION_NOT_MET ʤ - # PORT_ERROR ¾Υ顼 - # - # @else - # - # @brief Writing data - # - # This operation writes data into publisher and then the data - # will be transferred to correspondent InPort. If data is written - # properly, this function will return PORT_OK return code. Except - # normal return, CONNECTION_LOST, BUFFER_FULL, BUFFER_ERROR, - # PORT_ERROR, BUFFER_TIMEOUT and PRECONDITION_NO_MET will be - # returned as error codes. - # - # @return PORT_OK Normal return - # CONNECTION_LOST Connectin lost - # BUFFER_FULL Buffer full - # BUFFER_ERROR Buffer error - # BUFFER_TIMEOUT Timeout - # PRECONDITION_NOT_MET Precondition not met - # PORT_ERROR Other error - # - # @endif - # - # template - # virtual ReturnCode write(const DataType& data); - def write(self, data): - self._rtcout.RTC_TRACE("write()") - - if self._directInPort is not None: - if self._directInPort.isNew(): - #self._listeners.connectorData_[OpenRTM_aist.ConnectorDataListenerType.ON_BUFFER_OVERWRITE].notify(self._profile, data) - #self._inPortListeners.connectorData_[OpenRTM_aist.ConnectorDataListenerType.ON_BUFFER_OVERWRITE].notify(self._profile, data) - #self._listeners.connectorData_[OpenRTM_aist.ConnectorDataListenerType.ON_RECEIVER_FULL].notify(self._profile, data) - #self._inPortListeners.connectorData_[OpenRTM_aist.ConnectorDataListenerType.ON_RECEIVER_FULL].notify(self._profile, data) - self._rtcout.RTC_TRACE("ONBUFFER_OVERWRITE(InPort,OutPort), ") - self._rtcout.RTC_TRACE("ON_RECEIVER_FULL(InPort,OutPort) ") - self._rtcout.RTC_TRACE("callback called in direct mode.") - #self._listeners.connectorData_[OpenRTM_aist.ConnectorDataListenerType.ON_BUFFER_WRITE].notify(self._profile, data) - #self._inPortListeners.connectorData_[OpenRTM_aist.ConnectorDataListenerType.ON_BUFFER_WRITE].notify(self._profile, data) - self._rtcout.RTC_TRACE("ON_BUFFER_WRITE(InPort,OutPort), ") - self._rtcout.RTC_TRACE("callback called in direct mode.") - self._directInPort.write(data) - #self._listeners.connectorData_[OpenRTM_aist.ConnectorDataListenerType.ON_RECEIVED].notify(self._profile, data) - #self._inPortListeners.connectorData_[OpenRTM_aist.ConnectorDataListenerType.ON_RECEIVED].notify(self._profile, data) - self._rtcout.RTC_TRACE("ON_RECEIVED(InPort,OutPort), ") - self._rtcout.RTC_TRACE("callback called in direct mode.") - return self.PORT_OK - # data -> (conversion) -> CDR stream - cdr_data = None - if self._endian is not None: - cdr_data = cdrMarshal(any.to_any(data).typecode(), data, self._endian) - else: - self._rtcout.RTC_ERROR("write(): endian %s is not support.",self._endian) - return self.UNKNOWN_ERROR - - return self._publisher.write(cdr_data, -1, 0) - - - ## - # @if jp - # @brief ³ - # - # consumer, publisher, buffer Ρ롣 - # - # @else - # - # @brief disconnect - # - # This operation destruct and delete the consumer, the publisher - # and the buffer. - # - # @endif - # - # virtual ReturnCode disconnect(); - def disconnect(self): - self._rtcout.RTC_TRACE("disconnect()") - self.onDisconnect() - # delete publisher - if self._publisher: - self._rtcout.RTC_DEBUG("delete publisher") - pfactory = OpenRTM_aist.PublisherFactory.instance() - pfactory.deleteObject(self._publisher) - - self._publisher = None - - # delete consumer - if self._consumer: - self._rtcout.RTC_DEBUG("delete consumer") - cfactory = OpenRTM_aist.InPortConsumerFactory.instance() - cfactory.deleteObject(self._consumer) - - self._consumer = None - - # delete buffer - if self._buffer: - self._rtcout.RTC_DEBUG("delete buffer") - bfactory = OpenRTM_aist.CdrBufferFactory.instance() - bfactory.deleteObject(self._buffer) - - self._buffer = None - self._rtcout.RTC_TRACE("disconnect() done") - - return self.PORT_OK - - - ## - # @if jp - # @brief ƥֲ - # - # Υͥ򥢥ƥֲ - # - # @else - # - # @brief Connector activation - # - # This operation activates this connector - # - # @endif - # - # virtual void activate(); - def activate(self): - self._publisher.activate() - return - - - ## - # @if jp - # @brief 󥢥ƥֲ - # - # Υͥ󥢥ƥֲ - # - # @else - # - # @brief Connector deactivation - # - # This operation deactivates this connector - # - # @endif - # - # virtual void deactivate(); - def deactivate(self): - self._publisher.deactivate() - return - - - ## - # @if jp - # @brief Buffer - # - # Connector ݻƤ Buffer ֤ - # - # @else - # @brief Getting Buffer - # - # This operation returns this connector's buffer - # - # @endif - # - # virtual CdrBufferBase* getBuffer(); - def getBuffer(self): - return self._buffer - - - ## - # @if jp - # @brief Publisher - # - # Ϳ줿³˴Ťѥ֥å롣 - # - # @param info ³ - # @return ѥ֥åؤΥݥ - # - # @else - # @brief create buffer - # - # This function creates a publisher based on given information. - # - # @param info Connector information - # @return The poitner to the publisher - # - # @endif - # - # virtual PublisherBase* createPublisher(ConnectorInfo& info); - def createPublisher(self, info): - pub_type = info.properties.getProperty("io_mode") - if not pub_type: - pub_type = info.properties.getProperty("subscription_type","flush") - pub_type = OpenRTM_aist.normalize([pub_type]) - if pub_type == "flush": - info.properties.setProperty("io_mode","block") - elif pub_type == "new": - info.properties.setProperty("io_mode","nonblock") - else: - info.properties.setProperty("io_mode","pub_type") - - return OpenRTM_aist.PublisherFactory.instance().createObject(pub_type) - - - ## - # @if jp - # @brief Buffer - # - # Ϳ줿³˴ŤХåե롣 - # - # @param info ³ - # @return ХåեؤΥݥ - # - # @else - # @brief create buffer - # - # This function creates a buffer based on given information. - # - # @param info Connector information - # @return The poitner to the buffer - # - # @endif - # - # virtual CdrBufferBase* createBuffer(ConnectorInfo& info); - def createBuffer(self, info): - buf_type = info.properties.getProperty("buffer_type", - "ring_buffer") - - return OpenRTM_aist.CdrBufferFactory.instance().createObject(buf_type) - - - ## - # @if jp - # @brief ³Ω˥ХåƤ - # @else - # @brief Invoke callback when connection is established - # @endif - # void onConnect() - def onConnect(self): - if self._listeners and self._profile: - self._listeners.connector_[OpenRTM_aist.ConnectorListenerType.ON_CONNECT].notify(self._profile) - return - - ## - # @if jp - # @brief ³ǻ˥ХåƤ - # @else - # @brief Invoke callback when connection is destroied - # @endif - # void onDisconnect() - def onDisconnect(self): - if self._listeners and self._profile: - self._listeners.connector_[OpenRTM_aist.ConnectorListenerType.ON_DISCONNECT].notify(self._profile) - return - - ## - # @if jp - # @brief ǡ쥯Ȥ˽񤭹िInPortΥХȤꤹ - # - # @param self - # @param directInPort InPortΥХ - # @return True: False: ѤߤΤἺ - # @else - # @brief - # - # @param self - # @param directInPort - # @return - # @endif - # - # bool setInPort(InPortBase* directInPort); - def setInPort(self, directInPort): - if self._directInPort is not None: - return False - self._directInPort = directInPort - self._inPortListeners = self._directInPort._listeners - return True \ No newline at end of file + """ + """ + + ## + # @if jp + # @brief コンストラクタ + # + # OutPortPushConnector のコンストラクタはオブジェクト生成時に下記 + # を引数にとる。ConnectorInfo は接続情報を含み、この情報に従いパブ + # リッシャやバッファ等を生成する。InPort インターフェースに対する + # コンシューマオブジェクトへのポインタを取り、所有権を持つので、 + # OutPortPushConnector は InPortConsumer の解体責任を持つ。各種イ + # ベントに対するコールバック機構を提供する ConnectorListeners を持 + # ち、適切なタイミングでコールバックを呼び出す。データバッファがも + # し OutPortBase から提供される場合はそのポインタを取る。 + # + # @param info ConnectorInfo + # @param consumer InPortConsumer + # @param listeners ConnectorListeners 型のリスナオブジェクトリスト + # @param buffer CdrBufferBase 型のバッファ + # + # @else + # @brief Constructor + # + # OutPortPushConnector's constructor is given the following + # arguments. According to ConnectorInfo which includes + # connection information, a publisher and a buffer are created. + # It is also given a pointer to the consumer object for the + # InPort interface. The owner-ship of the pointer is owned by + # this OutPortPushConnector, it has responsibility to destruct + # the InPortConsumer. OutPortPushConnector also has + # ConnectorListeners to provide event callback mechanisms, and + # they would be called at the proper timing. If data buffer is + # given by OutPortBase, the pointer to the buffer is also given + # as arguments. + # + # @param info ConnectorInfo + # @param consumer InPortConsumer + # @param listeners ConnectorListeners type lsitener object list + # @param buffer CdrBufferBase type buffer + # + # @endif + # + # OutPortPushConnector(ConnectorInfo info, + # InPortConsumer* consumer, + # ConnectorListeners& listeners, + # CdrBufferBase* buffer = 0); + def __init__(self, info, consumer, listeners, buffer=None): + OpenRTM_aist.OutPortConnector.__init__(self, info) + + self._buffer = buffer + self._consumer = consumer + self._listeners = listeners + + self._directInPort = None + self._inPortListeners = None + + # publisher/buffer creation. This may throw std::bad_alloc; + self._publisher = self.createPublisher(info) + if not self._buffer: + self._buffer = self.createBuffer(info) + + if not self._publisher or not self._buffer or not self._consumer: + raise + + if self._publisher.init(info.properties) != self.PORT_OK: + raise + + if self._profile.properties.hasKey("serializer"): + endian = self._profile.properties.getProperty( + "serializer.cdr.endian") + if not endian: + self._rtcout.RTC_ERROR("write(): endian is not set.") + raise + + # Maybe endian is ["little","big"] + endian = OpenRTM_aist.split(endian, ",") + # Maybe self._endian is "little" or "big" + endian = OpenRTM_aist.normalize(endian[0]) + if endian == "little": + self._endian = True + elif endian == "big": + self._endian = False + else: + self._endian = None + + else: + self._endian = True # little endian + + self._buffer.init(info.properties.getNode("buffer")) + self._consumer.init(info.properties) + self._publisher.setConsumer(self._consumer) + self._publisher.setBuffer(self._buffer) + self._publisher.setListener(self._profile, self._listeners) + + self._marshaling_type = info.properties.getProperty( + "marshaling_type", "cdr") + self._marshaling_type = self._marshaling_type.strip() + + self._serializer = None + + self.onConnect() + return + + ## + # @if jp + # @brief デストラクタ + # + # + # + # @else + # + # @brief Destructor + # + # + # @endif + # + + def __del__(self): + return + + ## + # @if jp + # @brief データの書き込み + # + # Publisherに対してデータを書き込み、これにより対応するInPortへデー + # タが転送される。正常終了した場合 PORT_OK が返される。それ以外の + # 場合、エラー値として、CONNECTION_LOST, BUFFER_FULL, + # BUFFER_ERROR, PORT_ERROR, BUFFER_TIMEOUT, PRECONDITION_NO_MET が + # 返される。 + # + # @return PORT_OK 正常終了 + # CONNECTION_LOST 接続がロストした + # BUFFER_FULL バッファが一杯である + # BUFFER_ERROR バッファエラー + # BUFFER_TIMEOUT バッファへの書き込みがタイムアウトした + # PRECONDITION_NOT_MET 事前条件を満たさない + # PORT_ERROR その他のエラー + # + # @else + # + # @brief Writing data + # + # This operation writes data into publisher and then the data + # will be transferred to correspondent InPort. If data is written + # properly, this function will return PORT_OK return code. Except + # normal return, CONNECTION_LOST, BUFFER_FULL, BUFFER_ERROR, + # PORT_ERROR, BUFFER_TIMEOUT and PRECONDITION_NO_MET will be + # returned as error codes. + # + # @return PORT_OK Normal return + # CONNECTION_LOST Connectin lost + # BUFFER_FULL Buffer full + # BUFFER_ERROR Buffer error + # BUFFER_TIMEOUT Timeout + # PRECONDITION_NOT_MET Precondition not met + # PORT_ERROR Other error + # + # @endif + # + # template + # virtual ReturnCode write(const DataType& data); + def write(self, data): + self._rtcout.RTC_TRACE("write()") + + if self._directInPort is not None: + if self._directInPort.isNew(): + #self._listeners.notifyData(OpenRTM_aist.ConnectorDataListenerType.ON_BUFFER_OVERWRITE, self._profile, data) + #self._inPortListeners.notifyData(OpenRTM_aist.ConnectorDataListenerType.ON_BUFFER_OVERWRITE, self._profile, data) + #self._listeners.notifyData(OpenRTM_aist.ConnectorDataListenerType.ON_RECEIVER_FULL, self._profile, data) + #self._inPortListeners.notifyData(OpenRTM_aist.ConnectorDataListenerType.ON_RECEIVER_FULL, self._profile, data) + self._rtcout.RTC_TRACE("ONBUFFER_OVERWRITE(InPort,OutPort), ") + self._rtcout.RTC_TRACE("ON_RECEIVER_FULL(InPort,OutPort) ") + self._rtcout.RTC_TRACE("callback called in direct mode.") + #self._listeners.notifyData(OpenRTM_aist.ConnectorDataListenerType.ON_BUFFER_WRITE, self._profile, data) + #self._inPortListeners.notifyData(OpenRTM_aist.ConnectorDataListenerType.ON_BUFFER_WRITE, self._profile, data) + self._rtcout.RTC_TRACE("ON_BUFFER_WRITE(InPort,OutPort), ") + self._rtcout.RTC_TRACE("callback called in direct mode.") + self._directInPort.write(data) + #self._listeners.notifyData(OpenRTM_aist.ConnectorDataListenerType.ON_RECEIVED, self._profile, data) + #self._inPortListeners.notifyData(OpenRTM_aist.ConnectorDataListenerType.ON_RECEIVED, self._profile, data) + self._rtcout.RTC_TRACE("ON_RECEIVED(InPort,OutPort), ") + self._rtcout.RTC_TRACE("callback called in direct mode.") + return self.PORT_OK + # data -> (conversion) -> CDR stream + if self._serializer is None: + self._rtcout.RTC_ERROR("serializer creation failure.") + return self.UNKNOWN_ERROR + + self._serializer.isLittleEndian(self._endian) + ser_ret, cdr_data = self._serializer.serialize(data) + if ser_ret == OpenRTM_aist.ByteDataStreamBase.SERIALIZE_NOT_SUPPORT_ENDIAN: + self._rtcout.RTC_ERROR( + "write(): endian %s is not support.", self._endian) + return self.UNKNOWN_ERROR + elif ser_ret == OpenRTM_aist.ByteDataStreamBase.SERIALIZE_ERROR: + self._rtcout.RTC_ERROR("unkown error.") + return self.UNKNOWN_ERROR + elif ser_ret == OpenRTM_aist.ByteDataStreamBase.SERIALIZE_NOTFOUND: + self._rtcout.RTC_ERROR( + "write(): serializer %s is not support.", + self._marshaling_type) + return self.UNKNOWN_ERROR + + return self._publisher.write(cdr_data, -1, 0) + + ## + # @if jp + # @brief 接続解除 + # + # consumer, publisher, buffer が解体・削除される。 + # + # @else + # + # @brief disconnect + # + # This operation destruct and delete the consumer, the publisher + # and the buffer. + # + # @endif + # + # virtual ReturnCode disconnect(); + + def disconnect(self): + self._rtcout.RTC_TRACE("disconnect()") + self.onDisconnect() + # delete publisher + if self._publisher: + self._rtcout.RTC_DEBUG("delete publisher") + self._publisher.exit() + pfactory = OpenRTM_aist.PublisherFactory.instance() + + self._publisher = None + + # delete consumer + if self._consumer: + self._rtcout.RTC_DEBUG("delete consumer") + cfactory = OpenRTM_aist.InPortConsumerFactory.instance() + + self._consumer = None + + # delete buffer + if self._buffer: + self._rtcout.RTC_DEBUG("delete buffer") + bfactory = OpenRTM_aist.CdrBufferFactory.instance() + + self._buffer = None + + if self._serializer: + self._rtcout.RTC_DEBUG("delete serializer") + self._serializer = None + + self._rtcout.RTC_TRACE("disconnect() done") + + return self.PORT_OK + + ## + # @if jp + # @brief アクティブ化 + # + # このコネクタをアクティブ化する + # + # @else + # + # @brief Connector activation + # + # This operation activates this connector + # + # @endif + # + # virtual void activate(); + + def activate(self): + self._publisher.activate() + return + + ## + # @if jp + # @brief 非アクティブ化 + # + # このコネクタを非アクティブ化する + # + # @else + # + # @brief Connector deactivation + # + # This operation deactivates this connector + # + # @endif + # + # virtual void deactivate(); + + def deactivate(self): + self._publisher.deactivate() + return + + ## + # @if jp + # @brief Buffer を取得する + # + # Connector が保持している Buffer を返す + # + # @else + # @brief Getting Buffer + # + # This operation returns this connector's buffer + # + # @endif + # + # virtual CdrBufferBase* getBuffer(); + + def getBuffer(self): + return self._buffer + + ## + # @if jp + # @brief Publisherの生成 + # + # 与えられた接続情報に基づきパブリッシャを生成する。 + # + # @param info 接続情報 + # @return パブリッシャへのポインタ + # + # @else + # @brief create buffer + # + # This function creates a publisher based on given information. + # + # @param info Connector information + # @return The poitner to the publisher + # + # @endif + # + # virtual PublisherBase* createPublisher(ConnectorInfo& info); + + def createPublisher(self, info): + pub_type = info.properties.getProperty("io_mode") + if not pub_type: + pub_type = info.properties.getProperty( + "subscription_type", "flush") + pub_type = OpenRTM_aist.normalize(pub_type) + if pub_type == "flush": + info.properties.setProperty("io_mode", "block") + elif pub_type == "new": + info.properties.setProperty("io_mode", "nonblock") + else: + info.properties.setProperty("io_mode", "pub_type") + + return OpenRTM_aist.PublisherFactory.instance().createObject(pub_type) + + ## + # @if jp + # @brief Bufferの生成 + # + # 与えられた接続情報に基づきバッファを生成する。 + # + # @param info 接続情報 + # @return バッファへのポインタ + # + # @else + # @brief create buffer + # + # This function creates a buffer based on given information. + # + # @param info Connector information + # @return The poitner to the buffer + # + # @endif + # + # virtual CdrBufferBase* createBuffer(ConnectorInfo& info); + + def createBuffer(self, info): + buf_type = info.properties.getProperty("buffer_type", + "ring_buffer") + + return OpenRTM_aist.CdrBufferFactory.instance().createObject(buf_type) + + ## + # @if jp + # @brief 接続確立時にコールバックを呼ぶ + # @else + # @brief Invoke callback when connection is established + # @endif + # void onConnect() + + def onConnect(self): + if self._listeners and self._profile: + self._listeners.notify( + OpenRTM_aist.ConnectorListenerType.ON_CONNECT, self._profile) + return + + ## + # @if jp + # @brief 接続切断時にコールバックを呼ぶ + # @else + # @brief Invoke callback when connection is destroied + # @endif + # void onDisconnect() + def onDisconnect(self): + if self._listeners and self._profile: + self._listeners.notify( + OpenRTM_aist.ConnectorListenerType.ON_DISCONNECT, self._profile) + return + + ## + # @if jp + # @brief データをダイレクトに書き込むためのInPortのサーバントを設定する + # + # @param self + # @param directInPort InPortのサーバント + # @return True: 設定に成功 False: 既に設定済みのため失敗 + # @else + # @brief + # + # @param self + # @param directInPort + # @return + # @endif + # + # bool setInPort(InPortBase* directInPort); + def setInPort(self, directInPort): + if self._directInPort is not None: + return False + self._directInPort = directInPort + self._inPortListeners = self._directInPort._listeners + return True + + ## + # @if jp + # @brief コンシューマのインターフェースの登録を取り消す + # @param prop コネクタプロファイルのプロパティ + # @else + # @brief + # @param prop + # @endif + def unsubscribeInterface(self, prop): + if self._consumer: + self._consumer.unsubscribeInterface(prop) + + def setDataType(self, data): + OpenRTM_aist.OutPortConnector.setDataType(self, data) + self._serializer = OpenRTM_aist.SerializerFactories.instance().createSerializer(self._marshaling_type, data) diff --git a/OpenRTM_aist/OutPortSHMConsumer.py b/OpenRTM_aist/OutPortSHMConsumer.py index 21a6e324..110d5dd2 100644 --- a/OpenRTM_aist/OutPortSHMConsumer.py +++ b/OpenRTM_aist/OutPortSHMConsumer.py @@ -1,5 +1,5 @@ #!/usr/bin/env python -# -*- coding: euc-jp -*- +# -*- coding: utf-8 -*- ## @@ -11,7 +11,6 @@ # - import OpenRTM_aist import OpenRTM import OpenRTM__POA @@ -23,9 +22,9 @@ # @if jp # @class OutPortSHMConsumer # -# @brief OutPortSHMConsumer 饹 +# @brief OutPortSHMConsumer クラス # -# ̿ʤ ͭ ѤϥݡȥץХμ饹 +# 通信手段に 共有メモリ を利用した出力ポートプロバイダーの実装クラス。 # # # @else @@ -36,173 +35,162 @@ # # @endif # -class OutPortSHMConsumer(OpenRTM_aist.OutPortCorbaCdrConsumer): - """ - """ - - ## - # @if jp - # @brief 󥹥ȥ饯 - # - # 󥹥ȥ饯 - # - # @else - # @brief Constructor - # - # Constructor - # - # @endif - # - def __init__(self): - OpenRTM_aist.OutPortCorbaCdrConsumer.__init__(self) - self._rtcout = OpenRTM_aist.Manager.instance().getLogbuf("OutPortSHMConsumer") - - self._shmem = OpenRTM_aist.SharedMemory() - - self._mutex = threading.RLock() - self._outportcdr = OpenRTM.PortSharedMemory._nil - return - ## - # @if jp - # @brief ǥȥ饯 - # - # ǥȥ饯 - # - # @else - # @brief Destructor - # - # Destructor - # - # @endif - # - def __del__(self, CorbaConsumer=OpenRTM_aist.CorbaConsumer): - self._rtcout.RTC_PARANOID("~OutPortSHMConsumer()") - CorbaConsumer.__del__(self) - try: - if not CORBA.is_nil(self._outportcdr): - self._outportcdr.close_memory(True) - except: - self._rtcout.RTC_WARN("Exception caught from PortSharedMemory.close_memory().") - self._rtcout.RTC_ERROR(OpenRTM_aist.Logger.print_exception()) - - oid = OpenRTM_aist.Manager.instance().getPOA().servant_to_id(self._shmem) - OpenRTM_aist.Manager.instance().getPOA().deactivate_object(oid) - - - - - ## - # @if jp - # @brief - # - # OutPortConsumerγƼԤ - # - # @param self - # @param prop ͥץѥƥ - # - # @else - # @brief Initializing configuration - # - # - # @endif - # - # virtual void init(coil::Properties& prop); - def init(self, prop): - self._rtcout.RTC_TRACE("init()") - - self._properties = prop - - return - - def setObject(self, obj): - if OpenRTM_aist.CorbaConsumer.setObject(self, obj): - ref_ = self.getObject() - if ref_: - outportcdr = self.getObject()._narrow(OpenRTM__POA.PortSharedMemory) - if outportcdr is None: - return False - outportcdr.setInterface(self._shmem._this()) - return True - return False - - - - ## - # @if jp - # @brief ǡɤ߽Ф - # - # ꤵ줿ǡɤ߽Ф - # - # ǡΥ϶ͭƬ8byte - # ǡ϶꤫ͭɤ߹ - # - # @param data ɤ߽Фǡ륪֥ - # - # @return ꥿󥳡 - # - # @else - # @brief Read data - # - # Read set data - # - # @param data Object to receive the read data - # - # @return Return Code - # - # @endif - # - # virtual ReturnCode get(cdrMemoryStream& data); - def get(self, data): - self._rtcout.RTC_PARANOID("get()") - - try: - outportcdr = self.getObject()._narrow(OpenRTM__POA.PortSharedMemory) - - self._outportcdr = outportcdr - - guard = OpenRTM_aist.ScopedLock(self._mutex) - ret = outportcdr.get() - - if ret == OpenRTM.PORT_OK: - self._rtcout.RTC_DEBUG("get() successful") - - - - shm_data = self._shmem.read() - - - data[0] = shm_data - self.onReceived(data[0]) - self.onBufferWrite(data[0]) - - if self._buffer.full(): - self._rtcout.RTC_INFO("InPort buffer is full.") - self.onBufferFull(data[0]) - self.onReceiverFull(data[0]) - - self._buffer.put(data[0]) - self._buffer.advanceWptr() - self._buffer.advanceRptr() - - return self.PORT_OK - return self.convertReturn(ret,data[0]) - - except: - self._rtcout.RTC_WARN("Exception caught from OutPort.get().") - self._rtcout.RTC_ERROR(OpenRTM_aist.Logger.print_exception()) - return self.CONNECTION_LOST - - - - - +class OutPortSHMConsumer(OpenRTM_aist.OutPortCorbaCdrConsumer): + """ + """ + + ## + # @if jp + # @brief コンストラクタ + # + # コンストラクタ + # + # @else + # @brief Constructor + # + # Constructor + # + # @endif + # + def __init__(self): + OpenRTM_aist.OutPortCorbaCdrConsumer.__init__(self) + OpenRTM_aist.CorbaConsumer.__init__( + self, OpenRTM__POA.PortSharedMemory) + self._rtcout = OpenRTM_aist.Manager.instance().getLogbuf("OutPortSHMConsumer") + + self._shmem = OpenRTM_aist.SharedMemory() + + self._mutex = threading.RLock() + + return + + ## + # @if jp + # @brief デストラクタ + # + # デストラクタ + # + # @else + # @brief Destructor + # + # Destructor + # + # @endif + # + def __del__(self, CorbaConsumer=OpenRTM_aist.CorbaConsumer): + self._rtcout.RTC_PARANOID("~OutPortSHMConsumer()") + CorbaConsumer.__del__(self) + try: + if not self._ptr(): + self._ptr().close_memory(True) + except BaseException: + self._rtcout.RTC_WARN( + "Exception caught from PortSharedMemory.close_memory().") + self._rtcout.RTC_ERROR(OpenRTM_aist.Logger.print_exception()) + + oid = OpenRTM_aist.Manager.instance().getPOA().servant_to_id(self._shmem) + OpenRTM_aist.Manager.instance().getPOA().deactivate_object(oid) + + ## + # @if jp + # @brief 設定初期化 + # + # OutPortConsumerの各種設定を行う + # + # @param self + # @param prop コネクタプロパティ + # + # @else + # @brief Initializing configuration + # + # + # @endif + # + # virtual void init(coil::Properties& prop); + + def init(self, prop): + self._rtcout.RTC_TRACE("init()") + + self._properties = prop + + return + + def setObject(self, obj): + if OpenRTM_aist.CorbaConsumer.setObject(self, obj): + portshmem = self._ptr() + if portshmem: + portshmem.setInterface(self._shmem._this()) + return True + return False + + ## + # @if jp + # @brief データを読み出す + # + # 設定されたデータを読み出す。 + # + # データのサイズは共有メモリも先頭8byteから取得する + # データは共有メモリから読み込む + # + # @param data 読み出したデータを受け取るオブジェクト + # + # @return リターンコード + # + # @else + # @brief Read data + # + # Read set data + # + # @param data Object to receive the read data + # + # @return Return Code + # + # @endif + # + # virtual ReturnCode get(cdrMemoryStream& data); + + def get(self): + self._rtcout.RTC_PARANOID("get()") + + try: + portshmem = self._ptr() + + guard = OpenRTM_aist.ScopedLock(self._mutex) + ret = portshmem.get() + + data = None + + if ret == OpenRTM.PORT_OK: + self._rtcout.RTC_DEBUG("get() successful") + + shm_data = self._shmem.read() + + data = shm_data + self.onReceived(data) + self.onBufferWrite(data) + + if self._buffer.full(): + self._rtcout.RTC_INFO("InPort buffer is full.") + self.onBufferFull(data) + self.onReceiverFull(data) + + self._buffer.put(data) + self._buffer.advanceWptr() + self._buffer.advanceRptr() + + return self.PORT_OK, data + return self.convertReturn(ret, data) + + except BaseException: + self._rtcout.RTC_WARN("Exception caught from OutPort.get().") + self._rtcout.RTC_ERROR(OpenRTM_aist.Logger.print_exception()) + return self.CONNECTION_LOST, None def OutPortSHMConsumerInit(): - factory = OpenRTM_aist.OutPortConsumerFactory.instance() - factory.addFactory("shared_memory", - OpenRTM_aist.OutPortSHMConsumer, - OpenRTM_aist.Delete) - return + factory = OpenRTM_aist.OutPortConsumerFactory.instance() + factory.addFactory("shared_memory", + OpenRTM_aist.OutPortSHMConsumer) + return diff --git a/OpenRTM_aist/OutPortSHMProvider.py b/OpenRTM_aist/OutPortSHMProvider.py index 7adef647..8f1d27b7 100644 --- a/OpenRTM_aist/OutPortSHMProvider.py +++ b/OpenRTM_aist/OutPortSHMProvider.py @@ -1,5 +1,5 @@ #!/usr/bin/env python -# -*- coding: euc-jp -*- +# -*- coding: utf-8 -*- ## # @file OutPortSHMProvider.py @@ -10,7 +10,6 @@ # - import OpenRTM_aist import OpenRTM @@ -18,11 +17,11 @@ ## # @if jp # @class OutPortSHMProvider -# @brief OutPortSHMProvider 饹 +# @brief OutPortSHMProvider クラス # -# OutPortProvider +# OutPortProvider # -# ̿ʤ ͭ ѤϥݡȥץХμ饹 +# 通信手段に 共有メモリ を利用した出力ポートプロバイダの実装クラス。 # # # @else @@ -33,241 +32,227 @@ # # @endif # -class OutPortSHMProvider(OpenRTM_aist.OutPortProvider,OpenRTM_aist.SharedMemory): - ## - # @if jp - # @brief 󥹥ȥ饯 - # ͭζ̾UUIDǺͥץեdataport.shared_memory.address¸ - # - # 󥹥ȥ饯 - # - # @else - # @brief Constructor - # - # Constructor - # - # @endif - # - def __init__(self): - OpenRTM_aist.OutPortProvider.__init__(self) - OpenRTM_aist.SharedMemory.__init__(self) - self.setInterfaceType("shared_memory") - - self._objref = self._this() - self._buffer = None - orb = OpenRTM_aist.Manager.instance().getORB() - self._properties.append(OpenRTM_aist.NVUtil.newNV("dataport.corba_cdr.outport_ior", - orb.object_to_string(self._objref))) - self._properties.append(OpenRTM_aist.NVUtil.newNV("dataport.corba_cdr.outport_ref", - self._objref)) - self._listeners = None - self._connector = None - self._profile = None - - - self._shm_address = str(OpenRTM_aist.uuid1()) - - self._endian = True - - - - - - - - return - - - ## - # @if jp - # @brief ǥȥ饯 - # - # ǥȥ饯 - # - # @else - # @brief Destructor - # - # Destructor - # - # @endif - # - def __del__(self): - return - - ## - # @if jp - # @brief λ - # - # @else - # @brief - # - # - # - # @endif - # - def exit(self): - oid = self._default_POA().servant_to_id(self) - self._default_POA().deactivate_object(oid) - - # virtual void init(coil::Properties& prop); - def init(self, prop): - - ds = prop.getProperty("shem_default_size") - self._memory_size = self.string_to_MemorySize(ds) - - - if prop.hasKey("serializer"): - endian = prop.getProperty("serializer.cdr.endian", "little") - - - endian = OpenRTM_aist.split(endian, ",") - endian = OpenRTM_aist.normalize(endian) - if endian == "little": - self._endian = True - elif endian == "big": - self._endian = False - - else: - self._endian = True - - return - - def setBuffer(self, buffer): - self._buffer = buffer - return - - def setListener(self, info, listeners): - self._profile = info - self._listeners = listeners - return - - def setConnector(self, connector): - self._connector = connector - return - - - - - ## - # @if jp - # @brief Хåեǡ - # - # @return (꥿󥳡ɡǡ) - # - # @else - # @brief Get data from the buffer - # - # - # @return - # - # @endif - # - # virtual ::OpenRTM::PortStatus get(::OpenRTM::CdrData_out data); - def get(self): - self._rtcout.RTC_PARANOID("OutPortSHMProvider.get()") - - if not self._connector: - self.onSenderError() - return OpenRTM.UNKNOWN_ERROR - - try: - - cdr = [None] - ret = self._connector.read(cdr) - - if ret == OpenRTM_aist.BufferStatus.BUFFER_OK: - if cdr[0] is None: - self._rtcout.RTC_ERROR("buffer is empty.") - return OpenRTM.BUFFER_EMPTY - - except: - self._rtcout.RTC_TRACE(OpenRTM_aist.Logger.print_exception()) - return OpenRTM.UNKNOWN_ERROR - - - self.setEndian(self._endian) - self.create_memory(self._memory_size, self._shm_address) - if cdr[0]: - self.write(cdr[0]) - - return self.convertReturn(ret, cdr[0]) - - - def onBufferRead(self, data): - if self._listeners and self._profile: - self._listeners.connectorData_[OpenRTM_aist.ConnectorDataListenerType.ON_BUFFER_READ].notify(self._profile, data) - return - - def onSend(self, data): - if self._listeners and self._profile: - self._listeners.connectorData_[OpenRTM_aist.ConnectorDataListenerType.ON_SEND].notify(self._profile, data) - return - - - - def onBufferEmpty(self): - if self._listeners and self._profile: - self._listeners.connector_[OpenRTM_aist.ConnectorListenerType.ON_BUFFER_EMPTY].notify(self._profile) - return - - def onBufferReadTimeout(self): - if self._listeners and self._profile: - self._listeners.connector_[OpenRTM_aist.ConnectorListenerType.ON_BUFFER_READ_TIMEOUT].notify(self._profile) - return - - def onSenderEmpty(self): - if self._listeners and self._profile: - self._listeners.connector_[OpenRTM_aist.ConnectorListenerType.ON_SENDER_EMPTY].notify(self._profile) - return - - def onSenderTimeout(self): - if self._listeners and self._profile: - self._listeners.connector_[OpenRTM_aist.ConnectorListenerType.ON_SENDER_TIMEOUT].notify(self._profile) - return - - def onSenderError(self): - if self._listeners and self._profile: - self._listeners.connector_[OpenRTM_aist.ConnectorListenerType.ON_SENDER_ERROR].notify(self._profile) - return - - def convertReturn(self, status, data): - if status == OpenRTM_aist.BufferStatus.BUFFER_OK: - self.onBufferRead(data) - self.onSend(data) - return OpenRTM.PORT_OK - - elif status == OpenRTM_aist.BufferStatus.BUFFER_ERROR: - self.onSenderError() - return OpenRTM.PORT_ERROR - - elif status == OpenRTM_aist.BufferStatus.BUFFER_FULL: - # never come here - return OpenRTM.BUFFER_FULL - - elif status == OpenRTM_aist.BufferStatus.BUFFER_EMPTY: - self.onBufferEmpty() - self.onSenderEmpty() - return OpenRTM.BUFFER_EMPTY - - elif status == OpenRTM_aist.BufferStatus.PRECONDITION_NOT_MET: - self.onSenderError() - return OpenRTM.PORT_ERROR - - elif status == OpenRTM_aist.BufferStatus.TIMEOUT: - self.onBufferReadTimeout() - self.onSenderTimeout() - return OpenRTM.BUFFER_TIMEOUT - - else: - return OpenRTM.UNKNOWN_ERROR - - +class OutPortSHMProvider(OpenRTM_aist.OutPortProvider, + OpenRTM_aist.SharedMemory): + ## + # @if jp + # @brief コンストラクタ + # 共有メモリの空間名はUUIDで作成し、コネクタプロファイルのdataport.shared_memory.addressに保存する + # + # コンストラクタ + # + # @else + # @brief Constructor + # + # Constructor + # + # @endif + # + def __init__(self): + OpenRTM_aist.OutPortProvider.__init__(self) + OpenRTM_aist.SharedMemory.__init__(self) + self.setInterfaceType("shared_memory") + + self._objref = self._this() + self._buffer = None + orb = OpenRTM_aist.Manager.instance().getORB() + self._properties.append(OpenRTM_aist.NVUtil.newNV("dataport.corba_cdr.outport_ior", + orb.object_to_string(self._objref))) + self._properties.append(OpenRTM_aist.NVUtil.newNV("dataport.corba_cdr.outport_ref", + self._objref)) + self._listeners = None + self._connector = None + self._profile = None + + self._shm_address = str(OpenRTM_aist.uuid1()) + self._endian = True + return + + ## + # @if jp + # @brief デストラクタ + # + # デストラクタ + # + # @else + # @brief Destructor + # + # Destructor + # + # @endif + # + + def __del__(self): + return + + ## + # @if jp + # @brief 終了処理 + # + # @else + # @brief + # + # + # + # @endif + # + def exit(self): + oid = self._default_POA().servant_to_id(self) + self._default_POA().deactivate_object(oid) + + # virtual void init(coil::Properties& prop); + def init(self, prop): + + ds = prop.getProperty("shem_default_size") + self._memory_size = self.string_to_MemorySize(ds) + + if prop.hasKey("serializer"): + endian = prop.getProperty("serializer.cdr.endian", "little") + + endian = OpenRTM_aist.split(endian, ",") + endian = OpenRTM_aist.normalize(endian[0]) + if endian == "little": + self._endian = True + elif endian == "big": + self._endian = False + + else: + self._endian = True + + return + + def setBuffer(self, buffer): + self._buffer = buffer + return + + def setListener(self, info, listeners): + self._profile = info + self._listeners = listeners + return + + def setConnector(self, connector): + self._connector = connector + return + + ## + # @if jp + # @brief バッファからデータを取得する + # + # @return (リターンコード、取得データ) + # + # @else + # @brief Get data from the buffer + # + # + # @return + # + # @endif + # + # virtual ::OpenRTM::PortStatus get(::OpenRTM::CdrData_out data); + + def get(self): + self._rtcout.RTC_PARANOID("OutPortSHMProvider.get()") + + if not self._connector: + self.onSenderError() + return OpenRTM.UNKNOWN_ERROR + + try: + ret, cdr = self._connector.read() + + if ret == OpenRTM_aist.BufferStatus.BUFFER_OK: + if cdr is None: + self._rtcout.RTC_ERROR("buffer is empty.") + return OpenRTM.BUFFER_EMPTY + + except BaseException: + self._rtcout.RTC_TRACE(OpenRTM_aist.Logger.print_exception()) + return OpenRTM.UNKNOWN_ERROR + + self.setEndian(self._endian) + self.create_memory(self._memory_size, self._shm_address) + if cdr: + self.write(cdr) + + return self.convertReturn(ret, cdr) + + def onBufferRead(self, data): + if self._listeners and self._profile: + _, data = self._listeners.notifyData( + OpenRTM_aist.ConnectorDataListenerType.ON_BUFFER_READ, self._profile, data) + return data + + def onSend(self, data): + if self._listeners and self._profile: + _, data = self._listeners.notifyData( + OpenRTM_aist.ConnectorDataListenerType.ON_SEND, self._profile, data) + return data + + def onBufferEmpty(self): + if self._listeners and self._profile: + self._listeners.notify( + OpenRTM_aist.ConnectorListenerType.ON_BUFFER_EMPTY, self._profile) + return + + def onBufferReadTimeout(self): + if self._listeners and self._profile: + self._listeners.notify( + OpenRTM_aist.ConnectorListenerType.ON_BUFFER_READ_TIMEOUT, self._profile) + return + + def onSenderEmpty(self): + if self._listeners and self._profile: + self._listeners.notify( + OpenRTM_aist.ConnectorListenerType.ON_SENDER_EMPTY, self._profile) + return + + def onSenderTimeout(self): + if self._listeners and self._profile: + self._listeners.notify( + OpenRTM_aist.ConnectorListenerType.ON_SENDER_TIMEOUT, self._profile) + return + + def onSenderError(self): + if self._listeners and self._profile: + self._listeners.notify( + OpenRTM_aist.ConnectorListenerType.ON_SENDER_ERROR, self._profile) + return + + def convertReturn(self, status, data): + if status == OpenRTM_aist.BufferStatus.BUFFER_OK: + data = self.onBufferRead(data) + self.onSend(data) + return OpenRTM.PORT_OK + + elif status == OpenRTM_aist.BufferStatus.BUFFER_ERROR: + self.onSenderError() + return OpenRTM.PORT_ERROR + + elif status == OpenRTM_aist.BufferStatus.BUFFER_FULL: + # never come here + return OpenRTM.BUFFER_FULL + + elif status == OpenRTM_aist.BufferStatus.BUFFER_EMPTY: + self.onBufferEmpty() + self.onSenderEmpty() + return OpenRTM.BUFFER_EMPTY + + elif status == OpenRTM_aist.BufferStatus.PRECONDITION_NOT_MET: + self.onSenderError() + return OpenRTM.PORT_ERROR + + elif status == OpenRTM_aist.BufferStatus.TIMEOUT: + self.onBufferReadTimeout() + self.onSenderTimeout() + return OpenRTM.BUFFER_TIMEOUT + + else: + return OpenRTM.UNKNOWN_ERROR def OutPortSHMProviderInit(): - factory = OpenRTM_aist.OutPortProviderFactory.instance() - factory.addFactory("shared_memory", - OpenRTM_aist.OutPortSHMProvider, - OpenRTM_aist.Delete) + factory = OpenRTM_aist.OutPortProviderFactory.instance() + factory.addFactory("shared_memory", + OpenRTM_aist.OutPortSHMProvider) diff --git a/OpenRTM_aist/PeriodicECSharedComposite.py b/OpenRTM_aist/PeriodicECSharedComposite.py index 83b6cfc2..7268c919 100644 --- a/OpenRTM_aist/PeriodicECSharedComposite.py +++ b/OpenRTM_aist/PeriodicECSharedComposite.py @@ -1,5 +1,5 @@ #!/usr/bin/env python -# -*- coding: euc-jp -*- +# -*- coding: utf-8 -*- ## # @file PeriodicECSharedComposite.h @@ -19,8 +19,6 @@ # - - from omniORB import CORBA import OpenRTM import RTC @@ -28,46 +26,44 @@ periodicecsharedcomposite_spec = ["implementation_id", "PeriodicECSharedComposite", - "type_name", "PeriodicECSharedComposite", - "description", "PeriodicECSharedComposite", - "version", "1.0", - "vendor", "jp.go.aist", - "category", "composite.PeriodicECShared", - "activity_type", "DataFlowComponent", - "max_instance", "0", - "language", "Python", - "lang_type", "script", - "exported_ports", "", + "type_name", "PeriodicECSharedComposite", + "description", "PeriodicECSharedComposite", + "version", "1.0", + "vendor", "jp.go.aist", + "category", "composite.PeriodicECShared", + "activity_type", "DataFlowComponent", + "max_instance", "0", + "language", "Python", + "lang_type", "script", + "exported_ports", "", "conf.default.members", "", "conf.default.exported_ports", "", ""] - + def stringToStrVec(v, _is): - str = [_is] - OpenRTM_aist.eraseBlank(str) - v[0] = str[0].split(",") - return True + _str = OpenRTM_aist.eraseBlank(_is) + v = _str.split(",") + return True, v class setCallback(OpenRTM_aist.ConfigurationSetListener): - def __init__(self, org): - self._org = org - pass - - def __call__(self, config_set): - self._org.updateDelegatedPorts() + def __init__(self, org): + self._org = org + pass + def __call__(self, config_set): + self._org.updateDelegatedPorts() class addCallback(OpenRTM_aist.ConfigurationSetListener): - def __init__(self, org): - self._org = org - pass + def __init__(self, org): + self._org = org + pass - def __call__(self, config_set): - self._org.updateDelegatedPorts() - return + def __call__(self, config_set): + self._org.updateDelegatedPorts() + return ## @@ -86,518 +82,533 @@ def __call__(self, config_set): # class PeriodicECOrganization(OpenRTM_aist.Organization_impl): + ## + # @if jp + # @brief コンストラクタ + # + # コンストラクタ + # + # @param rtobj オブジェクト + # + # @else + # @brief Constructor + # + # Constructor + # + # @param rtobj Object + # + # @endif + # + def __init__(self, rtobj): + OpenRTM_aist.Organization_impl.__init__(self, rtobj.getObjRef()) + self._rtobj = rtobj + self._ec = None + self._rtcMembers = [] + self._rtcout = OpenRTM_aist.Manager.instance().getLogbuf( + "rtobject.PeriodicECOrganization") + self._expPorts = [] + return - ## - # @if jp - # @brief 󥹥ȥ饯 - # - # 󥹥ȥ饯 - # - # @param rtobj ֥ - # - # @else - # @brief Constructor - # - # Constructor - # - # @param rtobj Object - # - # @endif - # - def __init__(self, rtobj): - OpenRTM_aist.Organization_impl.__init__(self,rtobj.getObjRef()) - self._rtobj = rtobj - self._ec = None - self._rtcMembers = [] - self._rtcout = OpenRTM_aist.Manager.instance().getLogbuf("rtobject.PeriodicECOrganization") - self._expPorts = [] - return - - - ## - # @if jp - # - # @brief [CORBA interface] OrganizationСɲä - # - # Organization ݻСꥹȤͿ줿SDOListɲä롣 - # - # @param sdo_list ɲä SDO СΥꥹ - # @return ɲäɤbool֤ - # - # @else - # - # @brief [CORBA interface] Add Organization member - # - # This operation adds the given SDOList to the existing organization's - # member list - # - # @param sdo_list SDO member list to be added - # @return boolean will returned if the operation succeed - # - # @endif - # - # Boolean add_members(const SDOList& sdo_list) - def add_members(self, sdo_list): - self._rtcout.RTC_DEBUG("add_members()") - self.updateExportedPortsList() - for sdo in sdo_list: - dfc = [None] - if not self.sdoToDFC(sdo, dfc): - sdo_list.remove(sdo) - continue - member = self.Member(dfc[0]) - self.stopOwnedEC(member) - self.addOrganizationToTarget(member) - self.addParticipantToEC(member) - self.addPort(member, self._expPorts) - self._rtcMembers.append(member) - - result = OpenRTM_aist.Organization_impl.add_members(self,sdo_list) - - return result - - - ## - # @if jp - # - # @brief [CORBA interface] OrganizationС򥻥åȤ - # - # Organization ݻСꥹȤͿ줿 - # SDOList򿷵˥åȤ롣 - # - # @param sdo_list ˥åȤ SDO СΥꥹ - # @return ɲäɤbool֤ - # - # @else - # - # @brief [CORBA interface] Set Organization member - # - # This operation removes existing member list and sets the given - # SDOList to the existing organization's member list - # - # @param sdo_list SDO member list to be set - # @return boolean will returned if the operation succeed - # - # @endif - # - # Boolean set_members(const SDOList& sdo_list) - def set_members(self, sdo_list): - self._rtcout.RTC_DEBUG("set_members()") - # self._rtcMembers = [] - self.removeAllMembers() - self.updateExportedPortsList() - - for sdo in sdo_list: - dfc = [None] - if not self.sdoToDFC(sdo, dfc): - sdo_list.remove(sdo) - continue - - member = self.Member(dfc[0]) - self.stopOwnedEC(member) - self.addOrganizationToTarget(member) - self.addParticipantToEC(member) - self.addPort(member, self._expPorts) - self._rtcMembers.append(member) - - result = OpenRTM_aist.Organization_impl.set_members(self, sdo_list) - - return result - - - ## - # @if jp - # - # @brief [CORBA interface] OrganizationС - # - # Organization ݻСꥹSDO롣 - # - # @param id SDO ID - # @return ɲäɤbool֤ - # - # @else - # - # @brief [CORBA interface] Remove a member of Organization - # - # This operation removes a SDO from existing member list by specified ID. - # - # @param id The ID of the SDO to be removed - # @return boolean will returned if the operation succeed - # - # @endif - # - # Boolean remove_member(const char* id) - def remove_member(self, id): - self._rtcout.RTC_DEBUG("remove_member(id = %s)", id) - rm_rtc = [] - for member in self._rtcMembers: - if str(id) != str(member._profile.instance_name): - continue - self.removePort(member, self._expPorts) - self._rtobj.getProperties().setProperty("conf.default.exported_ports", OpenRTM_aist.flatten(self._expPorts)) - self.removeParticipantFromEC(member) - self.removeOrganizationFromTarget(member) - self.startOwnedEC(member) - #rm_rtc.append(member) - self._rtcMembers.remove(member) - break - - #for m in rm_rtc: - # self._rtcMembers.remove(m) - result = OpenRTM_aist.Organization_impl.remove_member(self, id) - return result - - - - ## - # @if jp - # @brief OrganizationС - # @else - # @brief Remove a member of Organization - # @endif - # - def removeAllMembers(self): - self._rtcout.RTC_DEBUG("removeAllMembers()") - self.updateExportedPortsList() - for member in self._rtcMembers: - self.removePort(member, self._expPorts) - self.removeParticipantFromEC(member) - self.removeOrganizationFromTarget(member) - self.startOwnedEC(member) - OpenRTM_aist.Organization_impl.remove_member(self, member._profile.instance_name) - - self._rtcMembers = [] - self._expPorts = [] - return - - - ## - # @if jp - # @brief SDODFCؤѴ - # @else - # @brief Conversion from SDO to DFC - # @endif - # - # bool sdoToDFC(const SDO_ptr sdo, ::OpenRTM::DataFlowComponent_ptr& dfc); - def sdoToDFC(self, sdo, dfc): - if CORBA.is_nil(sdo): - return False - - dfc[0] = sdo._narrow(OpenRTM.DataFlowComponent) - if CORBA.is_nil(dfc[0]): - return False - - return True - - - ## - # @if jp - # @brief Owned ExecutionContext ߤ - # @else - # @brief Stop Owned ExecutionContexts - # @endif - # - # void stopOwnedEC(Member& member); - def stopOwnedEC(self, member): - ecs = member._eclist - for ec in ecs: - ec.stop() - - return - - - ## - # @if jp - # @brief Owned ExecutionContext ư - # @else - # @brief Start Owned ExecutionContexts - # @endif - # - def startOwnedEC(self, member): - ecs = member._eclist - for ec in ecs: - ec.start() - - return - - - ## - # @if jp - # @brief DFC Organization ֥ȤͿ - # @else - # @brief Set Organization object to target DFC - # @endif - # - # void addOrganizationToTarget(Member& member); - def addOrganizationToTarget(self, member): - conf = member._config - if CORBA.is_nil(conf): - return - - conf.add_organization(self._objref) - return - - - ## - # @if jp - # @brief Organization ֥Ȥ DFC - # @else - # @brief Remove Organization object from a target DFC - # @endif - # - # void removeOrganizationFromTarget(Member& member) - def removeOrganizationFromTarget(self, member): - # get given RTC's configuration object - if CORBA.is_nil(member._config): - return - - # set organization to target RTC's conf - member._config.remove_organization(self._pId) - return - - - ## - # @if jp - # @brief Composite ExecutionContext DFC ˥åȤ - # @else - # @brief Set CompositeRTC's ExecutionContext to the given DFC - # @endif - # - # void addParticipantToEC(Member& member) - def addParticipantToEC(self, member): - if CORBA.is_nil(self._ec) or self._ec is None: - ecs = self._rtobj.get_owned_contexts() - if len(ecs) > 0: - self._ec = ecs[0] - else: + ## + # @if jp + # + # @brief [CORBA interface] Organizationメンバーを追加する + # + # Organization が保持するメンバーリストに与えられたSDOListを追加する。 + # + # @param sdo_list 追加される SDO メンバーのリスト + # @return 追加が成功したかどうかがboolで返される + # + # @else + # + # @brief [CORBA interface] Add Organization member + # + # This operation adds the given SDOList to the existing organization's + # member list + # + # @param sdo_list SDO member list to be added + # @return boolean will returned if the operation succeed + # + # @endif + # + # Boolean add_members(const SDOList& sdo_list) + + def add_members(self, sdo_list): + self._rtcout.RTC_DEBUG("add_members()") + self.updateExportedPortsList() + for sdo in sdo_list: + ret, dfc = self.sdoToDFC(sdo) + if not ret: + sdo_list.remove(sdo) + continue + member = self.Member(dfc) + self.stopOwnedEC(member) + self.addOrganizationToTarget(member) + self.addParticipantToEC(member) + self.addPort(member, self._expPorts) + self._rtcMembers.append(member) + + result = OpenRTM_aist.Organization_impl.add_members(self, sdo_list) + + return result + + ## + # @if jp + # + # @brief [CORBA interface] Organizationメンバーをセットする + # + # Organization が保持するメンバーリストを削除し、与えられた + # SDOListを新規にセットする。 + # + # @param sdo_list 新規にセットされる SDO メンバーのリスト + # @return 追加が成功したかどうかがboolで返される + # + # @else + # + # @brief [CORBA interface] Set Organization member + # + # This operation removes existing member list and sets the given + # SDOList to the existing organization's member list + # + # @param sdo_list SDO member list to be set + # @return boolean will returned if the operation succeed + # + # @endif + # + # Boolean set_members(const SDOList& sdo_list) + + def set_members(self, sdo_list): + self._rtcout.RTC_DEBUG("set_members()") + # self._rtcMembers = [] + self.removeAllMembers() + self.updateExportedPortsList() + + for sdo in sdo_list: + ret, dfc = self.sdoToDFC(sdo) + if not ret: + sdo_list.remove(sdo) + continue + + member = self.Member(dfc) + self.stopOwnedEC(member) + self.addOrganizationToTarget(member) + self.addParticipantToEC(member) + self.addPort(member, self._expPorts) + self._rtcMembers.append(member) + + result = OpenRTM_aist.Organization_impl.set_members(self, sdo_list) + + return result + + ## + # @if jp + # + # @brief [CORBA interface] Organizationメンバーを削除する + # + # Organization が保持するメンバーリスト内の特定のSDOを削除する。 + # + # @param id 削除される SDO の ID + # @return 追加が成功したかどうかがboolで返される + # + # @else + # + # @brief [CORBA interface] Remove a member of Organization + # + # This operation removes a SDO from existing member list by specified ID. + # + # @param id The ID of the SDO to be removed + # @return boolean will returned if the operation succeed + # + # @endif + # + # Boolean remove_member(const char* id) + + def remove_member(self, id): + self._rtcout.RTC_DEBUG("remove_member(id = %s)", id) + rm_rtc = [] + for member in self._rtcMembers: + if str(id) != str(member._profile.instance_name): + continue + self.removePort(member, self._expPorts) + self._rtobj.getProperties().setProperty( + "conf.default.exported_ports", + OpenRTM_aist.flatten( + self._expPorts)) + self.removeParticipantFromEC(member) + self.removeOrganizationFromTarget(member) + self.startOwnedEC(member) + # rm_rtc.append(member) + self._rtcMembers.remove(member) + break + + # for m in rm_rtc: + # self._rtcMembers.remove(m) + result = OpenRTM_aist.Organization_impl.remove_member(self, id) + return result + + ## + # @if jp + # @brief Organizationメンバーを削除する + # @else + # @brief Remove a member of Organization + # @endif + # + + def removeAllMembers(self): + self._rtcout.RTC_DEBUG("removeAllMembers()") + self.updateExportedPortsList() + for member in self._rtcMembers: + self.removePort(member, self._expPorts) + self.removeParticipantFromEC(member) + self.removeOrganizationFromTarget(member) + self.startOwnedEC(member) + OpenRTM_aist.Organization_impl.remove_member( + self, member._profile.instance_name) + + self._rtcMembers = [] + self._expPorts = [] return - - self.addRTCToEC(member._rtobj) - - return - - def addRTCToEC(self, rtobj): - - # set ec to target RTC - - - orglist = rtobj.get_owned_organizations() - if len(orglist) == 0: - self._ec.add_component(rtobj) - - #orglist = member._rtobj.get_organizations() - - for org in orglist: - sdos = org.get_members() - for sdo in sdos: - dfc = [None] - if not self.sdoToDFC(sdo, dfc): - continue - self.addRTCToEC(dfc[0]) - - - - ## - # @if jp - # @brief Composite ExecutionContext DFC - # @else - # @brief Remove participant DFC from CompositeRTC's ExecutionContext - # @endif - # - # void PeriodicECOrganization::removeParticipantFromEC(Member& member) - def removeParticipantFromEC(self, member): - if CORBA.is_nil(self._ec) or self._ec is None: - ecs = self._rtobj.get_owned_contexts() - if len(ecs) > 0: - self._ec = ecs[0] - else: - self._rtcout.RTC_FATAL("no owned EC") + + ## + # @if jp + # @brief SDOからDFCへの変換 + # @else + # @brief Conversion from SDO to DFC + # @endif + # + # bool sdoToDFC(const SDO_ptr sdo, ::OpenRTM::DataFlowComponent_ptr& dfc); + + def sdoToDFC(self, sdo): + if CORBA.is_nil(sdo): + return False, None + + dfc = sdo._narrow(OpenRTM.DataFlowComponent) + if CORBA.is_nil(dfc): + return False, dfc + + return True, dfc + + ## + # @if jp + # @brief Owned ExecutionContext を停止させる + # @else + # @brief Stop Owned ExecutionContexts + # @endif + # + # void stopOwnedEC(Member& member); + + def stopOwnedEC(self, member): + ecs = member._eclist + for ec in ecs: + ec.stop() + + return + + ## + # @if jp + # @brief Owned ExecutionContext を起動する + # @else + # @brief Start Owned ExecutionContexts + # @endif + # + + def startOwnedEC(self, member): + ecs = member._eclist + for ec in ecs: + ec.start() + + return + + ## + # @if jp + # @brief DFC に Organization オブジェクトを与える + # @else + # @brief Set Organization object to target DFC + # @endif + # + # void addOrganizationToTarget(Member& member); + + def addOrganizationToTarget(self, member): + conf = member._config + if CORBA.is_nil(conf): + return + + conf.add_organization(self._objref) + return + + ## + # @if jp + # @brief Organization オブジェクトを DFCから削除する + # @else + # @brief Remove Organization object from a target DFC + # @endif + # + # void removeOrganizationFromTarget(Member& member) + + def removeOrganizationFromTarget(self, member): + # get given RTC's configuration object + if CORBA.is_nil(member._config): + return + + # set organization to target RTC's conf + member._config.remove_organization(self._pId) + return + + ## + # @if jp + # @brief Composite の ExecutionContext を DFC にセットする + # @else + # @brief Set CompositeRTC's ExecutionContext to the given DFC + # @endif + # + # void addParticipantToEC(Member& member) + + def addParticipantToEC(self, member): + if CORBA.is_nil(self._ec) or self._ec is None: + ecs = self._rtobj.get_owned_contexts() + if ecs: + self._ec = ecs[0] + else: + return + + self.addRTCToEC(member._rtobj) + return - self._ec.remove_component(member._rtobj) - - #orglist = member._rtobj.get_organizations() - orglist = member._rtobj.get_owned_organizations() - - for org in orglist: - sdos = org.get_members() - for sdo in sdos: - dfc = [None] - if not self.sdoToDFC(sdo, dfc): - continue - self._ec.remove_component(dfc[0]) - return - - - ## - # @if jp - # @brief Composite ExecutionContext DFC ˥åȤ - # @else - # @brief Set CompositeRTC's ExecutionContext to the given DFC - # @endif - # - # void setCompositeECToTarget(::OpenRTM::DataFlowComponent_ptr dfc); - # def setCompositeECToTarget(self, dfc): - # if CORBA.is_nil(dfc): - # return - # - # if CORBA.is_nil(self._ec) or self._ec is None: - # ecs = self._rtobj.get_owned_contexts() - # if len(ecs) > 0: - # self._ec = ecs[0] - # else: - # return - # - # self._ec.add_component(dfc) - - ## - # @if jp - # @brief ݡȤѾ - # @else - # @brief Delegate given RTC's ports to the Composite - # @endif - # - # void addPort(Member& member, PortList& portlist); - def addPort(self, member, portlist): - self._rtcout.RTC_TRACE("addPort(%s)", OpenRTM_aist.flatten(portlist)) - if len(portlist) == 0: - return - - #comp_name = member._profile.instance_name - plist = member._profile.port_profiles - - # port delegation - for prof in plist: - # port name -> comp_name.port_name - port_name = prof.name - - self._rtcout.RTC_DEBUG("port_name: %s is in %s?", (port_name,OpenRTM_aist.flatten(portlist))) - if not port_name in portlist: - self._rtcout.RTC_DEBUG("Not found: %s is in %s?", (port_name,OpenRTM_aist.flatten(portlist))) - continue - - self._rtcout.RTC_DEBUG("Found: %s is in %s", (port_name,OpenRTM_aist.flatten(portlist))) - self._rtobj.addPort(prof.port_ref) - self._rtcout.RTC_DEBUG("Port %s was delegated.", port_name) - - return - - - ## - # @if jp - # @brief ѾƤݡȤ - # @else - # @brief Remove delegated participatns's ports from the composite - # @endif - # - # void removePort(Member& member, PortList& portlist) - def removePort(self, member, portlist): - self._rtcout.RTC_DEBUG("removePort()") - if len(portlist) == 0: - return - - #comp_name = member._profile.instance_name - plist = member._profile.port_profiles - - # port delegation - for prof in plist: - # port name -> comp_name.port_name - port_name = prof.name - - self._rtcout.RTC_DEBUG("port_name: %s is in %s?", (port_name,OpenRTM_aist.flatten(portlist))) - if not port_name in portlist: - self._rtcout.RTC_DEBUG("Not found: %s is in %s?", (port_name,OpenRTM_aist.flatten(portlist))) - continue - - self._rtcout.RTC_DEBUG("Found: %s is in %s", (port_name,OpenRTM_aist.flatten(portlist))) - self._rtobj.removePort(prof.port_ref) - portlist.remove(port_name) - self._rtcout.RTC_DEBUG("Port %s was deleted.", port_name) - - return - - - ## - # @if jp - # @brief PortsList򹹿 - # @else - # @brief PortsList is updated. - # @endif - # - def updateExportedPortsList(self): - plist = self._rtobj.getProperties().getProperty("conf.default.exported_ports") - if plist: - p = [plist] - OpenRTM_aist.eraseBlank(p) - self._expPorts = p[0].split(",") - - return - - ## - # @if jp - # @brief OrganizationС򹹿/ - # @else - # @brief Update/Remove a member of Organization - # @endif - # - def updateDelegatedPorts(self): - oldPorts = self._expPorts - ports = self._rtobj.getProperties().getProperty("conf.default.exported_ports") - newPorts = ports.split(",") - - - removedPorts = list(set(oldPorts).difference(set(newPorts))) - createdPorts = list(set(newPorts).difference(set(oldPorts))) - - self._rtcout.RTC_VERBOSE("old ports: %s", OpenRTM_aist.flatten(oldPorts)) - self._rtcout.RTC_VERBOSE("new ports: %s", OpenRTM_aist.flatten(newPorts)) - self._rtcout.RTC_VERBOSE("remove ports: %s", OpenRTM_aist.flatten(removedPorts)) - self._rtcout.RTC_VERBOSE("add ports: %s", OpenRTM_aist.flatten(createdPorts)) - - for member in self._rtcMembers: - self.removePort(member, removedPorts) - self.addPort(member, createdPorts) - - self._expPorts = newPorts - return - - - class Member: - def __init__(self, rtobj): - self._rtobj = rtobj - self._profile = rtobj.get_component_profile() - self._eclist = rtobj.get_owned_contexts() - self._config = rtobj.get_configuration() - return - - def __call__(self, x): - tmp = x - tmp.swap(self) - return self - - - def swap(self, x): - rtobj = x._rtobj - profile = x._profile - eclist = x._eclist - config = x._config - - x._rtobj = self._rtobj - x._profile = self._profile - x._eclist = self._eclist - x._config = self._config - - self._rtobj = rtobj - self._profile = profile - self._eclist = eclist - self._config = config - return - + + def addRTCToEC(self, rtobj): + + # set ec to target RTC + + orglist = rtobj.get_owned_organizations() + if not orglist: + self._ec.add_component(rtobj) + + #orglist = member._rtobj.get_organizations() + + for org in orglist: + sdos = org.get_members() + for sdo in sdos: + ret, dfc = self.sdoToDFC(sdo) + if not ret: + continue + self.addRTCToEC(dfc) + + ## + # @if jp + # @brief Composite の ExecutionContext から DFC を削除する + # @else + # @brief Remove participant DFC from CompositeRTC's ExecutionContext + # @endif + # + # void PeriodicECOrganization::removeParticipantFromEC(Member& member) + + def removeParticipantFromEC(self, member): + if CORBA.is_nil(self._ec) or self._ec is None: + ecs = self._rtobj.get_owned_contexts() + if ecs: + self._ec = ecs[0] + else: + self._rtcout.RTC_FATAL("no owned EC") + return + self._ec.remove_component(member._rtobj) + + #orglist = member._rtobj.get_organizations() + orglist = member._rtobj.get_owned_organizations() + + for org in orglist: + sdos = org.get_members() + for sdo in sdos: + ret, dfc = self.sdoToDFC(sdo) + if not ret: + continue + self._ec.remove_component(dfc) + return + + ## + # @if jp + # @brief Composite の ExecutionContext を DFC にセットする + # @else + # @brief Set CompositeRTC's ExecutionContext to the given DFC + # @endif + # + # void setCompositeECToTarget(::OpenRTM::DataFlowComponent_ptr dfc); + # def setCompositeECToTarget(self, dfc): + # if CORBA.is_nil(dfc): + # return + # + # if CORBA.is_nil(self._ec) or self._ec is None: + # ecs = self._rtobj.get_owned_contexts() + # if len(ecs) > 0: + # self._ec = ecs[0] + # else: + # return + # + # self._ec.add_component(dfc) + + ## + # @if jp + # @brief ポートを委譲する + # @else + # @brief Delegate given RTC's ports to the Composite + # @endif + # + # void addPort(Member& member, PortList& portlist); + + def addPort(self, member, portlist): + self._rtcout.RTC_TRACE("addPort(%s)", OpenRTM_aist.flatten(portlist)) + if not portlist: + return + + #comp_name = member._profile.instance_name + plist = member._profile.port_profiles + + # port delegation + for prof in plist: + # port name -> comp_name.port_name + port_name = prof.name + + self._rtcout.RTC_DEBUG( + "port_name: %s is in %s?", + (port_name, + OpenRTM_aist.flatten(portlist))) + if not port_name in portlist: + self._rtcout.RTC_DEBUG( + "Not found: %s is in %s?", (port_name, OpenRTM_aist.flatten(portlist))) + continue + + self._rtcout.RTC_DEBUG( + "Found: %s is in %s", (port_name, OpenRTM_aist.flatten(portlist))) + self._rtobj.addPort(prof.port_ref) + self._rtcout.RTC_DEBUG("Port %s was delegated.", port_name) + + return + + ## + # @if jp + # @brief 委譲していたポートを削除する + # @else + # @brief Remove delegated participatns's ports from the composite + # @endif + # + # void removePort(Member& member, PortList& portlist) + + def removePort(self, member, portlist): + self._rtcout.RTC_DEBUG("removePort()") + if not portlist: + return + + #comp_name = member._profile.instance_name + plist = member._profile.port_profiles + + # port delegation + for prof in plist: + # port name -> comp_name.port_name + port_name = prof.name + + self._rtcout.RTC_DEBUG( + "port_name: %s is in %s?", + (port_name, + OpenRTM_aist.flatten(portlist))) + if not port_name in portlist: + self._rtcout.RTC_DEBUG( + "Not found: %s is in %s?", (port_name, OpenRTM_aist.flatten(portlist))) + continue + + self._rtcout.RTC_DEBUG( + "Found: %s is in %s", (port_name, OpenRTM_aist.flatten(portlist))) + self._rtobj.removePort(prof.port_ref) + portlist.remove(port_name) + self._rtcout.RTC_DEBUG("Port %s was deleted.", port_name) + + return + + ## + # @if jp + # @brief PortsListを更新する + # @else + # @brief PortsList is updated. + # @endif + # + + def updateExportedPortsList(self): + plist = self._rtobj.getProperties().getProperty("conf.default.exported_ports") + if plist: + p = OpenRTM_aist.eraseBlank(plist) + self._expPorts = p.split(",") + + return + + ## + # @if jp + # @brief Organizationメンバーを更新/削除する + # @else + # @brief Update/Remove a member of Organization + # @endif + # + def updateDelegatedPorts(self): + oldPorts = self._expPorts + ports = self._rtobj.getProperties().getProperty("conf.default.exported_ports") + newPorts = ports.split(",") + + removedPorts = list(set(oldPorts).difference(set(newPorts))) + createdPorts = list(set(newPorts).difference(set(oldPorts))) + + self._rtcout.RTC_VERBOSE( + "old ports: %s", + OpenRTM_aist.flatten(oldPorts)) + self._rtcout.RTC_VERBOSE( + "new ports: %s", + OpenRTM_aist.flatten(newPorts)) + self._rtcout.RTC_VERBOSE( + "remove ports: %s", + OpenRTM_aist.flatten(removedPorts)) + self._rtcout.RTC_VERBOSE( + "add ports: %s", + OpenRTM_aist.flatten(createdPorts)) + + for member in self._rtcMembers: + self.removePort(member, removedPorts) + self.addPort(member, createdPorts) + + self._expPorts = newPorts + return + + class Member: + def __init__(self, rtobj): + self._rtobj = rtobj + self._profile = rtobj.get_component_profile() + self._eclist = rtobj.get_owned_contexts() + self._config = rtobj.get_configuration() + return + + def __call__(self, x): + tmp = x + tmp.swap(self) + return self + + def swap(self, x): + rtobj = x._rtobj + profile = x._profile + eclist = x._eclist + config = x._config + + x._rtobj = self._rtobj + x._profile = self._profile + x._eclist = self._eclist + x._config = self._config + + self._rtobj = rtobj + self._profile = profile + self._eclist = eclist + self._config = config + return + ## # @if jp # @namespace RTC # -# @brief RTݡͥ +# @brief RTコンポーネント # # @else # @@ -611,11 +622,11 @@ def swap(self, x): ## # @if jp # @class PeriodicECSharedComposite -# @brief PeriodicECSharedComposite 饹 +# @brief PeriodicECSharedComposite クラス # -# ǡեRTComponentδ쥯饹 -# ƼǡեRTComponentϡܥ饹ѾǼ -# 롣 +# データフロー型RTComponentの基底クラス。 +# 各種データフロー型RTComponentを実装する場合は、本クラスを継承する形で実装 +# する。 # # @since 0.4.0 # @@ -632,410 +643,404 @@ def swap(self, x): # class PeriodicECSharedComposite(OpenRTM_aist.DataFlowComponentBase): + ## + # @if jp + # @brief コンストラクタ + # + # コンストラクタ + # + # @param manager マネージャオブジェクト + # + # @else + # @brief Constructor + # + # Constructor + # + # @param manager Manager object + # + # @endif + # + def __init__(self, manager): + OpenRTM_aist.DataFlowComponentBase.__init__(self, manager) + + self._ref = self._this() + self._objref = self._ref + self._org = OpenRTM_aist.PeriodicECOrganization(self) + OpenRTM_aist.CORBA_SeqUtil.push_back(self._sdoOwnedOrganizations, + self._org.getObjRef()) + + self._members = [[]] + self.bindParameter("members", self._members, " ", stringToStrVec) + self._rtcout = OpenRTM_aist.Manager.instance( + ).getLogbuf("rtobject.periodic_ec_shared") + self._configsets.addConfigurationSetListener( + OpenRTM_aist.ConfigurationSetListenerType.ON_SET_CONFIG_SET, + setCallback(self._org)) + + self._configsets.addConfigurationSetListener( + OpenRTM_aist.ConfigurationSetListenerType.ON_ADD_CONFIG_SET, + addCallback(self._org)) + self._properties.setProperty("exec_cxt.periodic.sync_transition", "NO") + self._properties.setProperty("exec_cxt.periodic.sync_activation", "NO") + self._properties.setProperty( + "exec_cxt.periodic.sync_deactivation", "NO") + self._properties.setProperty("exec_cxt.periodic.sync_reset", "NO") - ## - # @if jp - # @brief 󥹥ȥ饯 - # - # 󥹥ȥ饯 - # - # @param manager ޥ͡㥪֥ - # - # @else - # @brief Constructor - # - # Constructor - # - # @param manager Manager object - # - # @endif - # - def __init__(self, manager): - OpenRTM_aist.DataFlowComponentBase.__init__(self,manager) - - self._ref = self._this() - self._objref = self._ref - self._org = OpenRTM_aist.PeriodicECOrganization(self) - OpenRTM_aist.CORBA_SeqUtil.push_back(self._sdoOwnedOrganizations, - self._org.getObjRef()) - - self._members = [[]] - self.bindParameter("members", self._members, " ", stringToStrVec) - self._rtcout = OpenRTM_aist.Manager.instance().getLogbuf("rtobject.periodic_ec_shared") - self._configsets.addConfigurationSetListener(\ - OpenRTM_aist.ConfigurationSetListenerType.ON_SET_CONFIG_SET, - setCallback(self._org)) - - self._configsets.addConfigurationSetListener(\ - OpenRTM_aist.ConfigurationSetListenerType.ON_ADD_CONFIG_SET, - addCallback(self._org)) - self._properties.setProperty("exec_cxt.periodic.sync_transition","NO") - self._properties.setProperty("exec_cxt.periodic.sync_activation","NO") - self._properties.setProperty("exec_cxt.periodic.sync_deactivation","NO") - self._properties.setProperty("exec_cxt.periodic.sync_reset","NO") - - return - - - ## - # @if jp - # @brief ǥȥ饯 - # - # ǥȥ饯 - # - # @else - # @brief Destructor - # - # Destructor - # - # @endif - # - def __del__(self): - self._rtcout.RTC_TRACE("destructor of PeriodicECSharedComposite") - OpenRTM_aist.RTObject_impl.__del__(self) - - ## - # @if jp - # @brief λؿ - # ʥ֥Ȥ󥢥ƥ֤ˤ - # - # @param self - # - # @else - # @brief - # - # @param self - # - # @endif - def shutdown(self): - OpenRTM_aist.RTObject_impl.shutdown(self) - poa = OpenRTM_aist.Manager.instance().getPOA() - poa.deactivate_object(poa.servant_to_id(self._org)) - del self._org - - ## - # @if jp - # @brief - # - # ǡե RTComponent ν¹Ԥ롣 - # ºݤνϡƶݥ饹˵Ҥ롣 - # - # @else - # @brief Initialization - # - # Initialization the data flow type RT-Component. - # Write the actual initialization code in each concrete class. - # - # @endif - # - def onInitialize(self): - self._rtcout.RTC_TRACE("onInitialize()") - - active_set = self._properties.getProperty("configuration.active_config", - "default") - if self._configsets.haveConfig(active_set): - self._configsets.update(active_set) - else: - self._configsets.update("default") - - mgr = OpenRTM_aist.Manager.instance() - sdos = [] - for member in self._members[0]: - member = member.replace("|","") - member = member.strip() - if member == "": - continue - - rtc = mgr.getComponent(member) - - if rtc is None: - print("no RTC found: ", member) - continue - - sdo = rtc.getObjRef() - if CORBA.is_nil(sdo): - continue - - OpenRTM_aist.CORBA_SeqUtil.push_back(sdos, sdo) - - try: - self._org.set_members(sdos) - except: - self._rtcout.RTC_ERROR(OpenRTM_aist.Logger.print_exception()) - - - return RTC.RTC_OK - - - ## - # @if jp - # - # @brief ѥХåؿ - # - # ComponentAction::on_activated ƤФ줿ݤ˼¹Ԥ륳Хå - # ؿ
    - # ܴؿ̵ RTC::RTC_OK ֤褦˥ߡƤΤǡ - # ƥݡͥȤμºݤγϡܴؿ򥪡С饤ɤƼ - # ɬפ롣 - # - # @param exec_handle äƤ ExecutionContext ID - # - # @return ReturnCode_t Υ꥿󥳡 - # - # @else - # - # @brief Callback function to activate - # - # This is a callback function that is executed when - # ComponentAction::on_activated was invoked.
    - # As for actual activation of each component, since this function is - # dummy-implemented to return RTC::RTC_OK unconditionally, you need to - # implement this function by overriding it. - # - # @param exec_handle ID of the participant ExecutionContext - # - # @return The return code of ReturnCode_t type - # - # @endif - # - def onActivated(self, exec_handle): - self._rtcout.RTC_TRACE("onActivated(%d)", exec_handle) - sdos = self._org.get_members() - - for sdo in sdos: - rtc = sdo._narrow(RTC.RTObject) - #ecs[0].activate_component(rtc) - self.activateChildComp(rtc) - - - len_ = len(self._members[0]) - - # since Python 2.5 - # self._rtcout.RTC_DEBUG("%d member RTC%s activated.", (len_,(lambda x: if x > 1 else "was")(len_))) - - if len_ > 1: - str_ = "s were" - else: - str_ = "was" - - self._rtcout.RTC_DEBUG("%d member RTC%s activated.", (len_, str_)) - - return RTC.RTC_OK - - ## - # @if jp - # @brief RTC򥢥ƥֲ - # ʣ祳ݡͥȤξϻҥݡͥȤ򥢥ƥֲ - # - # @param self - # @param rtobj RTC - # - # @else - # @brief - # - # @param self - # @param rtobj RTC - # - # @endif - def activateChildComp(self, rtobj): - ecs = self.get_owned_contexts() - - orglist = rtobj.get_owned_organizations() - if len(orglist) == 0: - ecs[0].activate_component(rtobj) - - for org in orglist: - child_sdos = org.get_members() - for child_sdo in child_sdos: - child = child_sdo._narrow(RTC.RTObject) - self.activateChildComp(child) - - - ## - # @if jp - # - # @brief ѥХåؿ - # - # ComponentAction::on_deactivated ƤФ줿ݤ˼¹Ԥ륳Хå - # ؿ
    - # ܴؿ̵ RTC::RTC_OK ֤褦˥ߡƤΤǡ - # ƥݡͥȤμºݤϡܴؿ򥪡С饤ɤƼ - # ɬפ롣 - # - # @param exec_handle äƤ ExecutionContext ID - # - # @return ReturnCode_t Υ꥿󥳡 - # - # @else - # - # @brief Callback function to deactivate - # - # This is a callback function that is executed when - # ComponentAction::on_deactivated was invoked.
    - # As for actual deactivation of each component, since this function is - # dummy-implemented to return RTC::RTC_OK unconditionally, you need to - # implement this function by overriding it. - # - # @param exec_handle ID of the participant ExecutionContext - # - # @return The return code of ReturnCode_t type - # - # @endif - # - def onDeactivated(self, exec_handle): - self._rtcout.RTC_TRACE("onDeactivated(%d)", exec_handle) - ecs = self.get_owned_contexts() - sdos = self._org.get_members() - - for sdo in sdos: - rtc = sdo._narrow(RTC.RTObject) - self.deactivateChildComp(rtc) - - - return RTC.RTC_OK - - ## - # @if jp - # @brief RTC󥢥ƥֲ - # ʣ祳ݡͥȤξϻҥݡͥȤ󥢥ƥֲ - # - # @param self - # @param rtobj RTC - # - # @else - # @brief - # - # @param self - # @param rtobj RTC - # - # @endif - def deactivateChildComp(self, rtobj): - ecs = self.get_owned_contexts() - - orglist = rtobj.get_owned_organizations() - if len(orglist) == 0: - ecs[0].deactivate_component(rtobj) - - for org in orglist: - child_sdos = org.get_members() - for child_sdo in child_sdos: - child = child_sdo._narrow(RTC.RTObject) - self.deactivateChildComp(child) - - ## - # @if jp - # - # @brief ꥻåȽѥХåؿ - # - # ComponentAction::on_reset ƤФ줿ݤ˼¹Ԥ륳Хåؿ
    - # ܴؿ̵ RTC::RTC_OK ֤褦˥ߡƤΤǡ - # ƥݡͥȤμºݤΥꥻåȽϡܴؿ򥪡С饤ɤƼ - # ɬפ롣 - # - # @param exec_handle äƤ ExecutionContext ID - # - # @return ReturnCode_t Υ꥿󥳡 - # - # @else - # - # @brief Callback function to reset - # - # This is a callback function that is executed when - # ComponentAction::on_reset was invoked.
    - # As for actual reset of each component, since this function is - # dummy-implemented to return RTC::RTC_OK unconditionally, you need to - # implement this function by overriding it. - # - # @param exec_handle ID of the participant ExecutionContext - # - # @return The return code of ReturnCode_t type - # - # @endif - # - def onReset(self, exec_handle): - self._rtcout.RTC_TRACE("onReset(%d)", exec_handle) - ecs = self.get_owned_contexts() - sdos = self._org.get_members() - - for sdo in sdos: - orglist = rtc.get_owned_organizations() - for org in orglist: - child_sdos = org.get_members() - for child_sdo in child_sdos: - child = child_sdo._narrow(RTC.RTObject) - - self.resetChildComp(child) - - return RTC.RTC_OK - - - ## - # @if jp - # @brief RTCꥻåȤ - # ʣ祳ݡͥȤξϻҥݡͥȤꥻåȤ - # - # @param self - # @param rtobj RTC - # - # @else - # @brief - # - # @param self - # @param rtobj RTC - # - # @endif - def resetChildComp(self, rtobj): - ecs = self.get_owned_contexts() - - orglist = rtobj.get_owned_organizations() - if len(orglist) == 0: - ecs[0].reset_component(rtobj) - - - for org in orglist: - child_sdos = org.get_members() - for child_sdo in child_sdos: - child = child_sdo._narrow(RTC.RTObject) - self.resetChildComp(child) - - ## - # @if jp - # - # @brief [ComponentAction CORBA interface] RTC νλ - # - # RTC ˴롣 - # RTC ͭνλϤǼ¹Ԥ롣 - # Υڥ졼ƤӽФη̤Ȥ onFinalize() Хåؿ - # ƤӽФ롣 - # - # @return ReturnCode_t Υ꥿󥳡 - # - # @else - # - # @brief [ComponentAction CORBA interface] Finalize RTC - # - # The RTC is being destroyed. - # Any final RTC-specific tear-down logic should be performed here. - # As a result of this operation, onFinalize() callback function is called. - # - # @return The return code of ReturnCode_t type - # - # @endif - # - def onFinalize(self): - self._rtcout.RTC_TRACE("onFinalize()") - self._org.removeAllMembers() - self._rtcout.RTC_PARANOID("onFinalize() done") - return RTC.RTC_OK - - - - - - -def PeriodicECSharedCompositeInit(manager): - profile = OpenRTM_aist.Properties(defaults_str=periodicecsharedcomposite_spec) - manager.registerFactory(profile, - OpenRTM_aist.PeriodicECSharedComposite, - OpenRTM_aist.Delete) + return + + ## + # @if jp + # @brief デストラクタ + # + # デストラクタ + # + # @else + # @brief Destructor + # + # Destructor + # + # @endif + # + + def __del__(self): + self._rtcout.RTC_TRACE("destructor of PeriodicECSharedComposite") + OpenRTM_aist.RTObject_impl.__del__(self) + + ## + # @if jp + # @brief 終了関数 + # オーガナイズオブジェクトを非アクティブにする + # + # @param self + # + # @else + # @brief + # + # @param self + # + # @endif + def shutdown(self): + OpenRTM_aist.RTObject_impl.shutdown(self) + poa = OpenRTM_aist.Manager.instance().getPOA() + poa.deactivate_object(poa.servant_to_id(self._org)) + del self._org + + ## + # @if jp + # @brief 初期化 + # + # データフロー型 RTComponent の初期化を実行する。 + # 実際の初期化処理は、各具象クラス内に記述する。 + # + # @else + # @brief Initialization + # + # Initialization the data flow type RT-Component. + # Write the actual initialization code in each concrete class. + # + # @endif + # + def onInitialize(self): + self._rtcout.RTC_TRACE("onInitialize()") + + active_set = self._properties.getProperty("configuration.active_config", + "default") + if self._configsets.haveConfig(active_set): + self._configsets.update(active_set) + else: + self._configsets.update("default") + + mgr = OpenRTM_aist.Manager.instance() + sdos = [] + for member in self._members[0]: + member = member.replace("|", "") + member = member.strip() + if member == "": + continue + + rtc = mgr.getComponent(member) + + if rtc is None: + print("no RTC found: ", member) + continue + + sdo = rtc.getObjRef() + if CORBA.is_nil(sdo): + continue + + OpenRTM_aist.CORBA_SeqUtil.push_back(sdos, sdo) + + try: + self._org.set_members(sdos) + except BaseException: + self._rtcout.RTC_ERROR(OpenRTM_aist.Logger.print_exception()) + + return RTC.RTC_OK + + ## + # @if jp + # + # @brief 活性化処理用コールバック関数 + # + # ComponentAction::on_activated が呼ばれた際に実行されるコールバック + # 関数。
    + # 本関数は無条件に RTC::RTC_OK を返すようにダミー実装されているので、 + # 各コンポーネントの実際の活性化処理は、本関数をオーバーライドして実装する + # 必要がある。 + # + # @param exec_handle 参加している ExecutionContext の ID + # + # @return ReturnCode_t 型のリターンコード + # + # @else + # + # @brief Callback function to activate + # + # This is a callback function that is executed when + # ComponentAction::on_activated was invoked.
    + # As for actual activation of each component, since this function is + # dummy-implemented to return RTC::RTC_OK unconditionally, you need to + # implement this function by overriding it. + # + # @param exec_handle ID of the participant ExecutionContext + # + # @return The return code of ReturnCode_t type + # + # @endif + # + + def onActivated(self, exec_handle): + self._rtcout.RTC_TRACE("onActivated(%d)", exec_handle) + sdos = self._org.get_members() + + for sdo in sdos: + rtc = sdo._narrow(RTC.RTObject) + # ecs[0].activate_component(rtc) + self.activateChildComp(rtc) + + len_ = len(self._members[0]) + + # since Python 2.5 + # self._rtcout.RTC_DEBUG("%d member RTC%s activated.", (len_,(lambda x: + # if x > 1 else "was")(len_))) + + if len_ > 1: + str_ = "s were" + else: + str_ = "was" + + self._rtcout.RTC_DEBUG("%d member RTC%s activated.", (len_, str_)) + + return RTC.RTC_OK + + ## + # @if jp + # @brief RTCをアクティブ化する + # 複合コンポーネントの場合は子コンポーネントをアクティブ化する + # + # @param self + # @param rtobj RTC + # + # @else + # @brief + # + # @param self + # @param rtobj RTC + # + # @endif + def activateChildComp(self, rtobj): + ecs = self.get_owned_contexts() + + orglist = rtobj.get_owned_organizations() + if not orglist: + ecs[0].activate_component(rtobj) + + for org in orglist: + child_sdos = org.get_members() + for child_sdo in child_sdos: + child = child_sdo._narrow(RTC.RTObject) + self.activateChildComp(child) + + ## + # @if jp + # + # @brief 非活性化処理用コールバック関数 + # + # ComponentAction::on_deactivated が呼ばれた際に実行されるコールバック + # 関数。
    + # 本関数は無条件に RTC::RTC_OK を返すようにダミー実装されているので、 + # 各コンポーネントの実際の非活性化処理は、本関数をオーバーライドして実装する + # 必要がある。 + # + # @param exec_handle 参加している ExecutionContext の ID + # + # @return ReturnCode_t 型のリターンコード + # + # @else + # + # @brief Callback function to deactivate + # + # This is a callback function that is executed when + # ComponentAction::on_deactivated was invoked.
    + # As for actual deactivation of each component, since this function is + # dummy-implemented to return RTC::RTC_OK unconditionally, you need to + # implement this function by overriding it. + # + # @param exec_handle ID of the participant ExecutionContext + # + # @return The return code of ReturnCode_t type + # + # @endif + # + + def onDeactivated(self, exec_handle): + self._rtcout.RTC_TRACE("onDeactivated(%d)", exec_handle) + ecs = self.get_owned_contexts() + sdos = self._org.get_members() + + for sdo in sdos: + rtc = sdo._narrow(RTC.RTObject) + self.deactivateChildComp(rtc) + + return RTC.RTC_OK + + ## + # @if jp + # @brief RTCを非アクティブ化する + # 複合コンポーネントの場合は子コンポーネントを非アクティブ化する + # + # @param self + # @param rtobj RTC + # + # @else + # @brief + # + # @param self + # @param rtobj RTC + # + # @endif + def deactivateChildComp(self, rtobj): + ecs = self.get_owned_contexts() + + orglist = rtobj.get_owned_organizations() + if not orglist: + ecs[0].deactivate_component(rtobj) + + for org in orglist: + child_sdos = org.get_members() + for child_sdo in child_sdos: + child = child_sdo._narrow(RTC.RTObject) + self.deactivateChildComp(child) + + ## + # @if jp + # + # @brief リセット処理用コールバック関数 + # + # ComponentAction::on_reset が呼ばれた際に実行されるコールバック関数。
    + # 本関数は無条件に RTC::RTC_OK を返すようにダミー実装されているので、 + # 各コンポーネントの実際のリセット処理は、本関数をオーバーライドして実装する + # 必要がある。 + # + # @param exec_handle 参加している ExecutionContext の ID + # + # @return ReturnCode_t 型のリターンコード + # + # @else + # + # @brief Callback function to reset + # + # This is a callback function that is executed when + # ComponentAction::on_reset was invoked.
    + # As for actual reset of each component, since this function is + # dummy-implemented to return RTC::RTC_OK unconditionally, you need to + # implement this function by overriding it. + # + # @param exec_handle ID of the participant ExecutionContext + # + # @return The return code of ReturnCode_t type + # + # @endif + # + def onReset(self, exec_handle): + self._rtcout.RTC_TRACE("onReset(%d)", exec_handle) + ecs = self.get_owned_contexts() + sdos = self._org.get_members() + + for sdo in sdos: + orglist = rtc.get_owned_organizations() + for org in orglist: + child_sdos = org.get_members() + for child_sdo in child_sdos: + child = child_sdo._narrow(RTC.RTObject) + + self.resetChildComp(child) + + return RTC.RTC_OK + + ## + # @if jp + # @brief RTCをリセットする + # 複合コンポーネントの場合は子コンポーネントをリセットする + # + # @param self + # @param rtobj RTC + # + # @else + # @brief + # + # @param self + # @param rtobj RTC + # + # @endif + + def resetChildComp(self, rtobj): + ecs = self.get_owned_contexts() + + orglist = rtobj.get_owned_organizations() + if not orglist: + ecs[0].reset_component(rtobj) + + for org in orglist: + child_sdos = org.get_members() + for child_sdo in child_sdos: + child = child_sdo._narrow(RTC.RTObject) + self.resetChildComp(child) + + ## + # @if jp + # + # @brief [ComponentAction CORBA interface] RTC の終了 + # + # RTC が破棄される。 + # RTC 固有の終了処理はここで実行する。 + # このオペレーション呼び出しの結果として onFinalize() コールバック関数が + # 呼び出される。 + # + # @return ReturnCode_t 型のリターンコード + # + # @else + # + # @brief [ComponentAction CORBA interface] Finalize RTC + # + # The RTC is being destroyed. + # Any final RTC-specific tear-down logic should be performed here. + # As a result of this operation, onFinalize() callback function is called. + # + # @return The return code of ReturnCode_t type + # + # @endif + # + def onFinalize(self): + self._rtcout.RTC_TRACE("onFinalize()") + self._org.removeAllMembers() + self._rtcout.RTC_PARANOID("onFinalize() done") + return RTC.RTC_OK + +def PeriodicECSharedCompositeInit(manager): + profile = OpenRTM_aist.Properties( + defaults_str=periodicecsharedcomposite_spec) + manager.registerFactory(profile, + OpenRTM_aist.PeriodicECSharedComposite, + OpenRTM_aist.Delete) diff --git a/OpenRTM_aist/PeriodicExecutionContext.py b/OpenRTM_aist/PeriodicExecutionContext.py index 75538edf..fcc7a7ff 100644 --- a/OpenRTM_aist/PeriodicExecutionContext.py +++ b/OpenRTM_aist/PeriodicExecutionContext.py @@ -1,5 +1,5 @@ #!/usr/bin/env python -# -*- coding: euc-jp -*- +# -*- coding: utf-8 -*- ## # @file PeriodicExecutionContext.py @@ -19,20 +19,19 @@ import time - - import OpenRTM_aist -import RTC, RTC__POA +import RTC +import RTC__POA DEFAULT_PERIOD = 0.000001 ## # @if jp # @class PeriodicExecutionContext -# @brief PeriodicExecutionContext 饹 +# @brief PeriodicExecutionContext クラス # -# Periodic Sampled Data Processing(¹)ExecutionContext饹 +# Periodic Sampled Data Processing(周期実行用)ExecutionContextクラス。 # # @since 0.4.0 # @@ -40,788 +39,789 @@ # @class PeriodicExecutionContext # @brief PeriodicExecutionContext class # @endif + + class PeriodicExecutionContext(OpenRTM_aist.ExecutionContextBase, RTC__POA.ExecutionContextService, OpenRTM_aist.Task): - """ - """ - - ## - # @if jp - # @brief 󥹥ȥ饯 - # - # 󥹥ȥ饯 - # ꤵ줿ͤץեꤹ롣 - # - # @else - # @brief Constructor - # @endif - def __init__(self): - self._rtcout = OpenRTM_aist.Manager.instance().getLogbuf("rtobject.periodic_ec") - self._rtcout.RTC_TRACE("PeriodicExecutionContext.__init__()") - OpenRTM_aist.ExecutionContextBase.__init__(self, "periodic_ec") - OpenRTM_aist.Task.__init__(self) - - self._svc = False - self._nowait = False - self._svcmutex = threading.RLock() - self._workerthread = self.WorkerThreadCtrl() - - global DEFAULT_PERIOD - self.setObjRef(self._this()) - self.setKind(RTC.PERIODIC) - self.setRate(1.0 / DEFAULT_PERIOD) - self._rtcout.RTC_DEBUG("Actual rate: %d [sec], %d [usec]", - (self._profile.getPeriod().sec(), self._profile.getPeriod().usec())) - - self._cpu = [] + """ + """ - return + ## + # @if jp + # @brief コンストラクタ + # + # コンストラクタ + # 設定された値をプロファイルに設定する。 + # + # @else + # @brief Constructor + # @endif + def __init__(self): + self._rtcout = OpenRTM_aist.Manager.instance().getLogbuf("rtobject.periodic_ec") + self._rtcout.RTC_TRACE("PeriodicExecutionContext.__init__()") + OpenRTM_aist.ExecutionContextBase.__init__(self, "periodic_ec") + OpenRTM_aist.Task.__init__(self) - ## - # @if jp - # @brief λؿ - # - # @param self - # @param Task - # - # @else - # @brief - # @param self - # @param Task - # @endif - def exit(self, Task=OpenRTM_aist.Task): - import OpenRTM_aist.Guard - self._rtcout.RTC_TRACE("PeriodicExecutionContext.__del__()") - guard = OpenRTM_aist.Guard.ScopedLock(self._svcmutex) - self._svc = False - del guard - - guard = OpenRTM_aist.ScopedLock(self._workerthread._mutex) - self._workerthread._cond.acquire() - self._workerthread._running = True - self._workerthread._cond.notify() - self._workerthread._cond.release() - del guard - self.wait() - Task.__del__(self) - OpenRTM_aist.ExecutionContextBase.exit(self) - return + self._svc = False + self._nowait = False + self._svcmutex = threading.RLock() + self._workerthread = self.WorkerThreadCtrl() + global DEFAULT_PERIOD + self.setObjRef(self._this()) + self.setKind(RTC.PERIODIC) + self.setRate(1.0 / DEFAULT_PERIOD) + self._rtcout.RTC_DEBUG("Actual rate: %d [sec], %d [usec]", + (self._profile.getPeriod().sec(), self._profile.getPeriod().usec())) - ## - # @if jp - # @brief ؿ - # - # @param self - # @param props ץѥƥ - # - # @else - # @brief - # @param self - # @param props - # @endif - def init(self, props): - OpenRTM_aist.ExecutionContextBase.init(self, props) - self.setCpuAffinity(props) - self._rtcout.RTC_DEBUG("init() done") - - - ## - # @if jp - # @brief ݡͥȤΥƥӥƥåɴؿ - # - # ݡͥȤƥӥƥåɤμ¹Դؿ - # ACE_Task ӥ饹᥽åɤΥС饤ɡ - # - # @else - # - # @brief Create internal activity thread - # - # Run by a daemon thread to handle deferred processing. - # ACE_Task class method override. - # - # @endif - def svc(self): - self._rtcout.RTC_TRACE("svc()") - count_ = 0 - - if len(self._cpu) > 0: - ret = OpenRTM_aist.setThreadAffinity(self._cpu) - if ret == False: - self._rtcout.RTC_ERROR("CPU affinity mask setting failed") - - while self.threadRunning(): - OpenRTM_aist.ExecutionContextBase.invokeWorkerPreDo(self) - # Thread will stopped when all RTCs are INACTIVE. - # Therefore WorkerPreDo(updating state) have to be invoked - # before stopping thread. - guard = OpenRTM_aist.ScopedLock(self._workerthread._mutex) - while not self._workerthread._running: - self._workerthread._cond.wait() - del guard - - t0_ = OpenRTM_aist.Time() - OpenRTM_aist.ExecutionContextBase.invokeWorkerDo(self) - OpenRTM_aist.ExecutionContextBase.invokeWorkerPostDo(self) - t1_ = OpenRTM_aist.Time() - - period_ = self.getPeriod() - - if count_ > 1000: - exctm_ = (t1_ - t0_).getTime().toDouble() - slptm_ = period_.toDouble() - exctm_ - self._rtcout.RTC_PARANOID("Period: %f [s]", period_.toDouble()) - self._rtcout.RTC_PARANOID("Execution: %f [s]", exctm_) - self._rtcout.RTC_PARANOID("Sleep: %f [s]", slptm_) - - - t2_ = OpenRTM_aist.Time() - - if not self._nowait and period_.toDouble() > ((t1_ - t0_).getTime().toDouble()): - if count_ > 1000: - self._rtcout.RTC_PARANOID("sleeping...") - slptm_ = period_.toDouble() - (t1_ - t0_).getTime().toDouble() - time.sleep(slptm_) - - if count_ > 1000: - t3_ = OpenRTM_aist.Time() - self._rtcout.RTC_PARANOID("Slept: %f [s]", (t3_ - t2_).getTime().toDouble()) - count_ = 0 - count_ += 1 - - self._rtcout.RTC_DEBUG("Thread terminated.") - return 0 - - - ## - # @if jp - # @brief ExecutionContextѥƥӥƥåɤ - # @else - # @brief Generate internal activity thread for ExecutionContext - # @endif - # - # int PeriodicExecutionContext::open(void *args) - def open(self, *args): - self._rtcout.RTC_TRACE("open()") - self.activate() - return 0 - - - ## - # @if jp - # @brief ExecutionContext ѤΥåɼ¹Դؿ - # - # ExecutionContext ѤΥåɽλ˸ƤФ롣 - # ݡͥȥ֥Ȥ󥢥ƥֲޥ͡ؤΤԤ - # ACE_Task ӥ饹᥽åɤΥС饤ɡ - # - # @param self - # @param flags λե饰 - # - # @return λ - # - # @else - # - # @brief Close activity thread - # - # close() method is called when activity thread svc() is returned. - # This method deactivate this object and notify it to manager. - # ACE_Task class method override. - # - # @endif - def close(self, flags): - self._rtcout.RTC_TRACE("close()") - return 0 - - - ## - # @if jp - # @brief ExecutionContext ¹Ծֳǧؿ - # - # ExecutionContext Runnning ֤ξ true ֤ - # Executioncontext Running δ֡ Executioncontext ˻äƤ - # ƤΥƥRTݡͥȤ ExecutionContext μ¹Լ˱ - # ¹Ԥ롣 - # - # @param self - # - # @return ֳǧؿ(ư:true:false) - # - # @else - # - # @brief Check for ExecutionContext running state - # - # This operation shall return true if the context is in the Running state. - # While the context is Running, all Active RTCs participating - # in the context shall be executed according to the contexts execution - # kind. - # - # @endif - def is_running(self): - self._rtcout.RTC_TRACE("is_running()") - return OpenRTM_aist.ExecutionContextBase.isRunning(self) - - - ## - # @if jp - # @brief ExecutionContext μ¹Ԥ򳫻 - # - # ExecutionContext μ¹Ծ֤ Runnning Ȥ뤿ΥꥯȤȯԤ롣 - # ExecutionContext ξ֤ܤ ComponentAction::on_startup - # ƤӽФ롣 - # äƤRTݡͥȤޤ ExecutionContext 򳫻 - # 뤳ȤϤǤʤ - # ExecutionContext ʣ󳫻/ߤ򷫤֤ȤǤ롣 - # - # @param self - # - # @return ReturnCode_t Υ꥿󥳡 - # - # @else - # - # @brief Start ExecutionContext - # - # Request that the context enter the Running state. - # Once the state transition occurs, the ComponentAction::on_startup - # operation will be invoked. - # An execution context may not be started until the RT components that - # participate in it have been initialized. - # An execution context may be started and stopped multiple times. - # - # @endif - def start(self): - return OpenRTM_aist.ExecutionContextBase.start(self) - - - ## - # @if jp - # @brief ExecutionContext μ¹Ԥ - # - # ExecutionContext ξ֤ Stopped Ȥ뤿ΥꥯȤȯԤ롣 - # ܤȯϡ ComponentAction::on_shutdown ƤӽФ롣 - # äƤRTݡͥȤλ ExecutionContext ߤ - # ɬפ롣 - # ExecutionContext ʣ󳫻/ߤ򷫤֤ȤǤ롣 - # - # @param self - # - # @return ReturnCode_t Υ꥿󥳡 - # - # @else - # - # @brief Stop ExecutionContext - # - # Request that the context enter the Stopped state. - # Once the transition occurs, the ComponentAction::on_shutdown operation - # will be invoked. - # An execution context must be stopped before the RT components that - # participate in it are finalized. - # An execution context may be started and stopped multiple times. - # - # @endif - def stop(self): - return OpenRTM_aist.ExecutionContextBase.stop(self) - - - ## - # @if jp - # @brief ExecutionContext μ¹Լ(Hz) - # - # Active ֤ˤRTݡͥȤ¹Ԥ(ñ:Hz)롣 - # - # @param self - # - # @return (ñ:Hz) - # - # @else - # - # @brief Get ExecutionRate - # - # This operation shall return the rate (in hertz) at which its Active - # participating RTCs are being invoked. - # - # @endif - def get_rate(self): - return OpenRTM_aist.ExecutionContextBase.getRate(self) - - - ## - # @if jp - # @brief ExecutionContext μ¹Լ(Hz)ꤹ - # - # Active ֤ˤRTݡͥȤ¹Ԥ(ñ:Hz)ꤹ롣 - # ¹Լѹϡ DataFlowComponentAction on_rate_changed ˤä - # RTݡͥȤã롣 - # - # @param self - # @param rate (ñ:Hz) - # - # @return ReturnCode_t Υ꥿󥳡 - # - # @else - # - # @brief Set ExecutionRate - # - # This operation shall set the rate (in hertz) at which this contexts - # Active participating RTCs are being called. - # If the execution kind of the context is PERIODIC, a rate change shall - # result in the invocation of on_rate_changed on any RTCs realizing - # DataFlowComponentAction that are registered with any RTCs participating - # in the context. - # - # @endif - def set_rate(self, rate): - return OpenRTM_aist.ExecutionContextBase.setRate(self, rate) - - - ## - # @if jp - # @brief RTݡͥȤ򥢥ƥֲ - # - # Inactive ֤ˤRTݡͥȤActive ܤƥֲ롣 - # ƤФ줿̡ on_activate ƤӽФ롣 - # ꤷRTݡͥȤüԥꥹȤ˴ޤޤʤϡ BAD_PARAMETER - # ֤롣 - # ꤷRTݡͥȤξ֤ Inactive ʳξϡ - # PRECONDITION_NOT_MET ֤롣 - # - # @param self - # @param comp ƥֲоRTݡͥ - # - # @return ReturnCode_t Υ꥿󥳡 - # - # @else - # - # @brief Activate a RT-component - # - # The given participant RTC is Inactive and is therefore not being invoked - # according to the execution contexts execution kind. This operation - # shall cause the RTC to transition to the Active state such that it may - # subsequently be invoked in this execution context. - # The callback on_activate shall be called as a result of calling this - # operation. This operation shall not return until the callback has - # returned, and shall result in an error if the callback does. - # - # @endif - def activate_component(self, comp): - return OpenRTM_aist.ExecutionContextBase.activateComponent(self, comp) - - - ## - # @if jp - # @brief RTݡͥȤ󥢥ƥֲ - # - # Inactive ֤ˤRTݡͥȤ󥢥ƥֲ - # Inactive ܤ롣 - # ƤФ줿̡ on_deactivate ƤӽФ롣 - # ꤷRTݡͥȤüԥꥹȤ˴ޤޤʤϡ BAD_PARAMETER - # ֤롣 - # ꤷRTݡͥȤξ֤ Active ʳξϡ - # PRECONDITION_NOT_MET ֤롣 - # - # @param self - # @param comp 󥢥ƥֲоRTݡͥ - # - # @return ReturnCode_t Υ꥿󥳡 - # - # @else - # - # @brief Deactivate a RT-component - # - # The given RTC is Active in the execution context. Cause it to transition - # to the Inactive state such that it will not be subsequently invoked from - # the context unless and until it is activated again. - # The callback on_deactivate shall be called as a result of calling this - # operation. This operation shall not return until the callback has - # returned, and shall result in an error if the callback does. - # - # @endif - def deactivate_component(self, comp): - return OpenRTM_aist.ExecutionContextBase.deactivateComponent(self, comp) - - - ## - # @if jp - # @brief RTݡͥȤꥻåȤ - # - # Error ֤RTݡͥȤߤ롣 - # ƤФ줿̡ on_reset ƤӽФ롣 - # ꤷRTݡͥȤüԥꥹȤ˴ޤޤʤϡ BAD_PARAMETER - # ֤롣 - # ꤷRTݡͥȤξ֤ Error ʳξϡ PRECONDITION_NOT_MET - # ֤롣 - # - # @param self - # @param comp ꥻåоRTݡͥ - # - # @return ReturnCode_t Υ꥿󥳡 - # - # @else - # - # @brief Reset a RT-component - # - # Attempt to recover the RTC when it is in Error. - # The ComponentAction::on_reset callback shall be invoked. This operation - # shall not return until the callback has returned, and shall result in an - # error if the callback does. If possible, the RTC developer should - # implement that callback such that the RTC may be returned to a valid - # state. - # - # @endif - def reset_component(self, comp): - return OpenRTM_aist.ExecutionContextBase.resetComponent(self, comp) - - - ## - # @if jp - # @brief RTݡͥȤξ֤ - # - # ꤷRTݡͥȤξ(LifeCycleState)롣 - # ꤷRTݡͥȤüԥꥹȤ˴ޤޤʤϡ CREATED_STATE - # ֤롣 - # - # @param self - # @param comp ּоRTݡͥ - # - # @return ߤξ(LifeCycleState) - # - # @else - # - # @brief Get RT-component's state - # - # This operation shall report the LifeCycleState of the given participant - # RTC. - # - # @endif - def get_component_state(self, comp): - return OpenRTM_aist.ExecutionContextBase.getComponentState(self, comp) - - - ## - # @if jp - # @brief ExecutionKind - # - # ExecutionContext ExecutionKind - # - # @param self - # - # @return ExecutionKind - # - # @else - # - # @brief Get the ExecutionKind - # - # This operation shall report the execution kind of the execution context. - # - # @endif - def get_kind(self): - return OpenRTM_aist.ExecutionContextBase.getKind(self) - - - ## - # @if jp - # @brief RTݡͥȤɲä - # - # ꤷRTݡͥȤ򻲲üԥꥹȤɲä롣 - # ɲä줿RTݡͥȤ attach_context ƤФ졢Inactive ֤ - # 롣 - # ꤵ줿RTݡͥȤnullξϡBAD_PARAMETER ֤롣 - # ꤵ줿RTݡͥȤ DataFlowComponent ʳξϡ - # BAD_PARAMETER ֤롣 - # - # @param self - # @param comp ɲоRTݡͥ - # - # @return ReturnCode_t Υ꥿󥳡 - # - # @else - # - # @brief Add a RT-component - # - # The operation causes the given RTC to begin participating in the - # execution context. - # The newly added RTC will receive a call to - # LightweightRTComponent::attach_context and then enter the Inactive state. - # - # @endif - def add_component(self, comp): - return OpenRTM_aist.ExecutionContextBase.addComponent(self, comp) - - - ## - # @if jp - # @brief RTݡͥȤ򻲲üԥꥹȤ - # - # ꤷRTݡͥȤ򻲲üԥꥹȤ롣 - # 줿RTݡͥȤ detach_context ƤФ롣 - # ꤵ줿RTݡͥȤüԥꥹȤϿƤʤϡ - # BAD_PARAMETER ֤롣 - # - # @param self - # @param comp оRTݡͥ - # - # @return ReturnCode_t Υ꥿󥳡 - # - # @else - # - # @brief Remove the RT-component from participant list - # - # This operation causes a participant RTC to stop participating in the - # execution context. - # The removed RTC will receive a call to - # LightweightRTComponent::detach_context. - # - # @endif - def remove_component(self, comp): - return OpenRTM_aist.ExecutionContextBase.removeComponent(self, comp) - - - ## - # @if jp - # @brief ExecutionContextProfile - # - # ExecutionContext Υץե롣 - # - # @param self - # - # @return ExecutionContextProfile - # - # @else - # - # @brief Get the ExecutionContextProfile - # - # This operation provides a profile descriptor for the execution - # context. - # - # @endif - def get_profile(self): - return OpenRTM_aist.ExecutionContextBase.getProfile(self) - - - # virtual RTC::ReturnCode_t onStarted(); - def onStarted(self): - # change EC thread state - guard = OpenRTM_aist.ScopedLock(self._svcmutex) - if not self._svc: - self._svc = True - self.open(0) - del guard - - if self.isAllNextState(RTC.INACTIVE_STATE): - guard = OpenRTM_aist.ScopedLock(self._workerthread._mutex) - self._workerthread._running = False - del guard - else: - guard = OpenRTM_aist.ScopedLock(self._workerthread._mutex) - self._workerthread._running = True - self._workerthread._cond.acquire() - self._workerthread._cond.notify() - self._workerthread._cond.release() - del guard - return RTC.RTC_OK - - - # virtual RTC::ReturnCode_t onStopping(); - def onStopping(self): - # stop thread - guard = OpenRTM_aist.ScopedLock(self._workerthread._mutex) - self._workerthread._running = False - return RTC.RTC_OK - - - - - def onAddedComponent(self, rtobj): - guard = OpenRTM_aist.ScopedLock(self._workerthread._mutex) - if self._workerthread._running == False: - self._worker.updateComponentList() - return RTC.RTC_OK - - def onRemovedComponent(self, rtobj): - guard = OpenRTM_aist.ScopedLock(self._workerthread._mutex) - if self._workerthread._running == False: - self._worker.updateComponentList() - return RTC.RTC_OK - - # virtual RTC::ReturnCode_t - # onWaitingActivated(RTC_impl::RTObjectStateMachine* comp, long int count); - def onWaitingActivated(self, comp, count): - self._rtcout.RTC_TRACE("onWaitingActivated(count = %d)", count) - self._rtcout.RTC_PARANOID("curr: %s, next: %s", - (self.getStateString(comp.getStates().curr), - self.getStateString(comp.getStates().next))) - # Now comp's next state must be ACTIVE state - # If worker thread is stopped, restart worker thread. - if self.isRunning(): - guard = OpenRTM_aist.ScopedLock(self._workerthread._mutex) - if self._workerthread._running == False: - self._workerthread._running = True + self._cpu = [] + + return + + ## + # @if jp + # @brief 終了関数 + # + # @param self  + # @param Task  + # + # @else + # @brief + # @param self  + # @param Task  + # @endif + def exit(self, Task=OpenRTM_aist.Task): + import OpenRTM_aist.Guard + self._rtcout.RTC_TRACE("PeriodicExecutionContext.__del__()") + guard = OpenRTM_aist.Guard.ScopedLock(self._svcmutex) + self._svc = False + del guard + + guard = OpenRTM_aist.ScopedLock(self._workerthread._mutex) self._workerthread._cond.acquire() - self._workerthread._cond.notify() - self._workerthread._cond.release() - del guard - return RTC.RTC_OK - - - # virtual RTC::ReturnCode_t - # onActivated(RTC_impl::RTObjectStateMachine* comp, long int count); - def onActivated(self, comp, count): - self._rtcout.RTC_TRACE("onActivated(count = %d)", count) - self._rtcout.RTC_PARANOID("curr: %s, next: %s", - (self.getStateString(comp.getStates().curr), - self.getStateString(comp.getStates().next))) - # count = -1; Asynch mode. Since onWaitingActivated is not - # called, onActivated() have to send restart singnal to worker - # thread. - # count > 0: Synch mode. - - # Now comp's next state must be ACTIVE state - # If worker thread is stopped, restart worker thread. - if self.isRunning(): - guard = OpenRTM_aist.ScopedLock(self._workerthread._mutex) - if self._workerthread._running == False: self._workerthread._running = True - self._workerthread._cond.acquire() self._workerthread._cond.notify() self._workerthread._cond.release() - del guard - return RTC.RTC_OK - - - # virtual RTC::ReturnCode_t - # onWaitingDeactivated(RTC_impl::RTObjectStateMachine* comp, long int count); - def onWaitingDeactivated(self, comp, count): - self._rtcout.RTC_TRACE("onWaitingDeactivated(count = %d)", count) - self._rtcout.RTC_PARANOID("curr: %s, next: %s", - (self.getStateString(comp.getStates().curr), - self.getStateString(comp.getStates().next))) - if self.isAllNextState(RTC.INACTIVE_STATE): - guard = OpenRTM_aist.ScopedLock(self._workerthread._mutex) - if self._workerthread._running == True: - self._workerthread._running = False - self._rtcout.RTC_TRACE("All RTCs are INACTIVE. Stopping worker thread.") - del guard - - return RTC.RTC_OK - - - # virtual RTC::ReturnCode_t - # onDeactivated(RTC_impl::RTObjectStateMachine* comp, long int count); - def onDeactivated(self, comp, count): - self._rtcout.RTC_TRACE("onDeactivated(count = %d)", count) - self._rtcout.RTC_PARANOID("curr: %s, next: %s", - (self.getStateString(comp.getStates().curr), - self.getStateString(comp.getStates().next))) - if self.isAllNextState(RTC.INACTIVE_STATE): - guard = OpenRTM_aist.ScopedLock(self._workerthread._mutex) - if self._workerthread._running == True: - self._workerthread._running = False - self._rtcout.RTC_TRACE("All RTCs are INACTIVE. Stopping worker thread.") - del guard - - return RTC.RTC_OK - - - # virtual RTC::ReturnCode_t - # onWaitingReset(RTC_impl::RTObjectStateMachine* comp, long int count); - def onWaitingReset(self, comp, count): - self._rtcout.RTC_TRACE("onWaitingReset(count = %d)", count) - self._rtcout.RTC_PARANOID("curr: %s, next: %s", - (self.getStateString(comp.getStates().curr), - self.getStateString(comp.getStates().next))) - if self.isAllNextState(RTC.INACTIVE_STATE): - guard = OpenRTM_aist.ScopedLock(self._workerthread._mutex) - if self._workerthread._running == True: - self._workerthread._running = False - self._rtcout.RTC_TRACE("All RTCs are INACTIVE. Stopping worker thread.") - del guard - - return RTC.RTC_OK - - - # virtual RTC::ReturnCode_t - # onReset(RTC_impl::RTObjectStateMachine* comp, long int count); - def onReset(self, comp, count): - self._rtcout.RTC_TRACE("onReset(count = %d)", count) - self._rtcout.RTC_PARANOID("curr: %s, next: %s", - (self.getStateString(comp.getStates().curr), - self.getStateString(comp.getStates().next))) - if self.isAllNextState(RTC.INACTIVE_STATE): - guard = OpenRTM_aist.ScopedLock(self._workerthread._mutex) - if self._workerthread._running == True: - self._workerthread._running = False - self._rtcout.RTC_TRACE("All RTCs are INACTIVE. Stopping worker thread.") - del guard - - return RTC.RTC_OK - - - # bool threadRunning() - def threadRunning(self): - guard = OpenRTM_aist.ScopedLock(self._svcmutex) - return self._svc - - - def setCpuAffinity(self, props): - self._rtcout.RTC_TRACE("setCpuAffinity()") - - affinity_str = props.getProperty("cpu_affinity") - if affinity_str: - self._rtcout.RTC_DEBUG("CPU affinity property: %s",affinity_str) - - tmp = affinity_str.split(",") - self._cpu = [] - for num in tmp: - try: - self._cpu.append(int(num)) - self._rtcout.RTC_DEBUG("CPU affinity int value: %d added.",int(num)) - except ValueError: - pass - - - - - ## - # @if jp - # @class WorkerThreadCtrl - # @brief worker Ѿѿ饹 - # - # @else - # @class WorkerThreadCtrl - # @brief Condition variable class for worker - # @endif - class WorkerThreadCtrl: - + del guard + self.wait() + Task.__del__(self) + OpenRTM_aist.ExecutionContextBase.exit(self) + return + ## # @if jp - # @brief 󥹥ȥ饯 + # @brief 初期化関数 # - # 󥹥ȥ饯 + # @param self  + # @param props プロパティ + # + # @else + # @brief + # @param self  + # @param props + # @endif + + def init(self, props): + OpenRTM_aist.ExecutionContextBase.init(self, props) + self.setCpuAffinity(props) + self._rtcout.RTC_DEBUG("init() done") + + ## + # @if jp + # @brief コンポーネントのアクティビティスレッド関数 + # + # コンポーネントの内部アクティビティスレッドの実行関数。 + # ACE_Task サービスクラスメソッドのオーバーライド。 + # + # @else + # + # @brief Create internal activity thread + # + # Run by a daemon thread to handle deferred processing. + # ACE_Task class method override. + # + # @endif + + def svc(self): + self._rtcout.RTC_TRACE("svc()") + count_ = 0 + + if self._cpu: + ret = OpenRTM_aist.setThreadAffinity(self._cpu) + if ret == False: + self._rtcout.RTC_ERROR("CPU affinity mask setting failed") + + while self.threadRunning(): + OpenRTM_aist.ExecutionContextBase.invokeWorkerPreDo(self) + # Thread will stopped when all RTCs are INACTIVE. + # Therefore WorkerPreDo(updating state) have to be invoked + # before stopping thread. + guard = OpenRTM_aist.ScopedLock(self._workerthread._mutex) + while not self._workerthread._running: + self._workerthread._cond.wait() + del guard + + t0_ = OpenRTM_aist.Time() + OpenRTM_aist.ExecutionContextBase.invokeWorkerDo(self) + OpenRTM_aist.ExecutionContextBase.invokeWorkerPostDo(self) + t1_ = OpenRTM_aist.Time() + + period_ = self.getPeriod() + exectime_ = (t1_ - t0_).getTime() + sleeptime_ = period_ - exectime_ + + if count_ > 1000: + self._rtcout.RTC_PARANOID("Period: %f [s]", period_.toDouble()) + self._rtcout.RTC_PARANOID("Execution: %f [s]", exectime_.toDouble()) + self._rtcout.RTC_PARANOID("Sleep: %f [s]", sleeptime_.toDouble()) + + t2_ = OpenRTM_aist.Time() + + if not self._nowait and exectime_.toDouble() >= 0.0 and sleeptime_.toDouble() > 0.0: + if count_ > 1000: + self._rtcout.RTC_PARANOID("sleeping...") + time.sleep(sleeptime_.toDouble()) + + if count_ > 1000: + t3_ = OpenRTM_aist.Time() + self._rtcout.RTC_PARANOID("Slept: %f [s]", (t3_ - t2_).getTime().toDouble()) + count_ = 0 + count_ += 1 + + self._rtcout.RTC_DEBUG("Thread terminated.") + return 0 + + ## + # @if jp + # @brief ExecutionContext用アクティビティスレッドを生成する + # @else + # @brief Generate internal activity thread for ExecutionContext + # @endif + # + # int PeriodicExecutionContext::open(void *args) + + def open(self, *args): + self._rtcout.RTC_TRACE("open()") + self.activate() + return 0 + + ## + # @if jp + # @brief ExecutionContext 用のスレッド実行関数 + # + # ExecutionContext 用のスレッド終了時に呼ばれる。 + # コンポーネントオブジェクトの非アクティブ化、マネージャへの通知を行う。 + # これは ACE_Task サービスクラスメソッドのオーバーライド。 # # @param self + # @param flags 終了処理フラグ + # + # @return 終了処理結果 # # @else - # @brief Constructor + # + # @brief Close activity thread + # + # close() method is called when activity thread svc() is returned. + # This method deactivate this object and notify it to manager. + # ACE_Task class method override. + # # @endif - def __init__(self): - self._mutex = threading.RLock() - self._cond = threading.Condition(self._mutex) - self._running = False + + def close(self, flags): + self._rtcout.RTC_TRACE("close()") + return 0 + + ## + # @if jp + # @brief ExecutionContext 実行状態確認関数 + # + # この操作は ExecutionContext が Runnning 状態の場合に true を返す。 + # Executioncontext が Running の間、当該 Executioncontext に参加している + # 全てのアクティブRTコンポーネントが、 ExecutionContext の実行種類に応じて + # 実行される。 + # + # @param self + # + # @return 状態確認関数(動作中:true、停止中:false) + # + # @else + # + # @brief Check for ExecutionContext running state + # + # This operation shall return true if the context is in the Running state. + # While the context is Running, all Active RTCs participating + # in the context shall be executed according to the context’s execution + # kind. + # + # @endif + + def is_running(self): + self._rtcout.RTC_TRACE("is_running()") + return OpenRTM_aist.ExecutionContextBase.isRunning(self) + + ## + # @if jp + # @brief ExecutionContext の実行を開始 + # + # ExecutionContext の実行状態を Runnning とするためのリクエストを発行する。 + # ExecutionContext の状態が遷移すると ComponentAction::on_startup が + # 呼び出される。 + # 参加しているRTコンポーネントが、初期化されるまで ExecutionContext を開始 + # することはできない。 + # ExecutionContext は複数回開始/停止を繰り返すことができる。 + # + # @param self + # + # @return ReturnCode_t 型のリターンコード + # + # @else + # + # @brief Start ExecutionContext + # + # Request that the context enter the Running state. + # Once the state transition occurs, the ComponentAction::on_startup + # operation will be invoked. + # An execution context may not be started until the RT components that + # participate in it have been initialized. + # An execution context may be started and stopped multiple times. + # + # @endif + + def start(self): + return OpenRTM_aist.ExecutionContextBase.start(self) + + ## + # @if jp + # @brief ExecutionContext の実行を停止 + # + # ExecutionContext の状態を Stopped とするためのリクエストを発行する。 + # 遷移が発生した場合は、 ComponentAction::on_shutdown が呼び出される。 + # 参加しているRTコンポーネントが終了する前に ExecutionContext を停止する + # 必要がある。 + # ExecutionContext は複数回開始/停止を繰り返すことができる。 + # + # @param self + # + # @return ReturnCode_t 型のリターンコード + # + # @else + # + # @brief Stop ExecutionContext + # + # Request that the context enter the Stopped state. + # Once the transition occurs, the ComponentAction::on_shutdown operation + # will be invoked. + # An execution context must be stopped before the RT components that + # participate in it are finalized. + # An execution context may be started and stopped multiple times. + # + # @endif + + def stop(self): + return OpenRTM_aist.ExecutionContextBase.stop(self) + + ## + # @if jp + # @brief ExecutionContext の実行周期(Hz)を取得する + # + # Active 状態にてRTコンポーネントが実行される周期(単位:Hz)を取得する。 + # + # @param self + # + # @return 処理周期(単位:Hz) + # + # @else + # + # @brief Get ExecutionRate + # + # This operation shall return the rate (in hertz) at which its Active + # participating RTCs are being invoked. + # + # @endif + + def get_rate(self): + return OpenRTM_aist.ExecutionContextBase.getRate(self) + + ## + # @if jp + # @brief ExecutionContext の実行周期(Hz)を設定する + # + # Active 状態にてRTコンポーネントが実行される周期(単位:Hz)を設定する。 + # 実行周期の変更は、 DataFlowComponentAction の on_rate_changed によって + # 各RTコンポーネントに伝達される。 + # + # @param self + # @param rate 処理周期(単位:Hz) + # + # @return ReturnCode_t 型のリターンコード + # + # @else + # + # @brief Set ExecutionRate + # + # This operation shall set the rate (in hertz) at which this context’s + # Active participating RTCs are being called. + # If the execution kind of the context is PERIODIC, a rate change shall + # result in the invocation of on_rate_changed on any RTCs realizing + # DataFlowComponentAction that are registered with any RTCs participating + # in the context. + # + # @endif + + def set_rate(self, rate): + return OpenRTM_aist.ExecutionContextBase.setRate(self, rate) + + ## + # @if jp + # @brief RTコンポーネントをアクティブ化する + # + # Inactive 状態にあるRTコンポーネントをActive に遷移させ、アクティブ化する。 + # この操作が呼ばれた結果、 on_activate が呼び出される。 + # 指定したRTコンポーネントが参加者リストに含まれない場合は、 BAD_PARAMETER + # が返される。 + # 指定したRTコンポーネントの状態が Inactive 以外の場合は、 + # PRECONDITION_NOT_MET が返される。 + # + # @param self + # @param comp アクティブ化対象RTコンポーネント + # + # @return ReturnCode_t 型のリターンコード + # + # @else + # + # @brief Activate a RT-component + # + # The given participant RTC is Inactive and is therefore not being invoked + # according to the execution context’s execution kind. This operation + # shall cause the RTC to transition to the Active state such that it may + # subsequently be invoked in this execution context. + # The callback on_activate shall be called as a result of calling this + # operation. This operation shall not return until the callback has + # returned, and shall result in an error if the callback does. + # + # @endif + + def activate_component(self, comp): + return OpenRTM_aist.ExecutionContextBase.activateComponent(self, comp) + + ## + # @if jp + # @brief RTコンポーネントを非アクティブ化する + # + # Inactive 状態にあるRTコンポーネントを非アクティブ化し、 + # Inactive に遷移させる。 + # この操作が呼ばれた結果、 on_deactivate が呼び出される。 + # 指定したRTコンポーネントが参加者リストに含まれない場合は、 BAD_PARAMETER + # が返される。 + # 指定したRTコンポーネントの状態が Active 以外の場合は、 + # PRECONDITION_NOT_MET が返される。 + # + # @param self + # @param comp 非アクティブ化対象RTコンポーネント + # + # @return ReturnCode_t 型のリターンコード + # + # @else + # + # @brief Deactivate a RT-component + # + # The given RTC is Active in the execution context. Cause it to transition + # to the Inactive state such that it will not be subsequently invoked from + # the context unless and until it is activated again. + # The callback on_deactivate shall be called as a result of calling this + # operation. This operation shall not return until the callback has + # returned, and shall result in an error if the callback does. + # + # @endif + + def deactivate_component(self, comp): + return OpenRTM_aist.ExecutionContextBase.deactivateComponent( + self, comp) + + ## + # @if jp + # @brief RTコンポーネントをリセットする + # + # Error 状態のRTコンポーネントの復帰を試みる。 + # この操作が呼ばれた結果、 on_reset が呼び出される。 + # 指定したRTコンポーネントが参加者リストに含まれない場合は、 BAD_PARAMETER + # が返される。 + # 指定したRTコンポーネントの状態が Error 以外の場合は、 PRECONDITION_NOT_MET + # が返される。 + # + # @param self + # @param comp リセット対象RTコンポーネント + # + # @return ReturnCode_t 型のリターンコード + # + # @else + # + # @brief Reset a RT-component + # + # Attempt to recover the RTC when it is in Error. + # The ComponentAction::on_reset callback shall be invoked. This operation + # shall not return until the callback has returned, and shall result in an + # error if the callback does. If possible, the RTC developer should + # implement that callback such that the RTC may be returned to a valid + # state. + # + # @endif + + def reset_component(self, comp): + return OpenRTM_aist.ExecutionContextBase.resetComponent(self, comp) + + ## + # @if jp + # @brief RTコンポーネントの状態を取得する + # + # 指定したRTコンポーネントの状態(LifeCycleState)を取得する。 + # 指定したRTコンポーネントが参加者リストに含まれない場合は、 CREATED_STATE + # が返される。 + # + # @param self + # @param comp 状態取得対象RTコンポーネント + # + # @return 現在の状態(LifeCycleState) + # + # @else + # + # @brief Get RT-component's state + # + # This operation shall report the LifeCycleState of the given participant + # RTC. + # + # @endif + + def get_component_state(self, comp): + return OpenRTM_aist.ExecutionContextBase.getComponentState(self, comp) + + ## + # @if jp + # @brief ExecutionKind を取得する + # + # 本 ExecutionContext の ExecutionKind を取得する + # + # @param self + # + # @return ExecutionKind + # + # @else + # + # @brief Get the ExecutionKind + # + # This operation shall report the execution kind of the execution context. + # + # @endif + + def get_kind(self): + return OpenRTM_aist.ExecutionContextBase.getKind(self) + + ## + # @if jp + # @brief RTコンポーネントを追加する + # + # 指定したRTコンポーネントを参加者リストに追加する。 + # 追加されたRTコンポーネントは attach_context が呼ばれ、Inactive 状態に遷移 + # する。 + # 指定されたRTコンポーネントがnullの場合は、BAD_PARAMETER が返される。 + # 指定されたRTコンポーネントが DataFlowComponent 以外の場合は、 + # BAD_PARAMETER が返される。 + # + # @param self + # @param comp 追加対象RTコンポーネント + # + # @return ReturnCode_t 型のリターンコード + # + # @else + # + # @brief Add a RT-component + # + # The operation causes the given RTC to begin participating in the + # execution context. + # The newly added RTC will receive a call to + # LightweightRTComponent::attach_context and then enter the Inactive state. + # + # @endif + + def add_component(self, comp): + return OpenRTM_aist.ExecutionContextBase.addComponent(self, comp) + + ## + # @if jp + # @brief RTコンポーネントを参加者リストから削除する + # + # 指定したRTコンポーネントを参加者リストから削除する。 + # 削除されたRTコンポーネントは detach_context が呼ばれる。 + # 指定されたRTコンポーネントが参加者リストに登録されていない場合は、 + # BAD_PARAMETER が返される。 + # + # @param self + # @param comp 削除対象RTコンポーネント + # + # @return ReturnCode_t 型のリターンコード + # + # @else + # + # @brief Remove the RT-component from participant list + # + # This operation causes a participant RTC to stop participating in the + # execution context. + # The removed RTC will receive a call to + # LightweightRTComponent::detach_context. + # + # @endif + + def remove_component(self, comp): + return OpenRTM_aist.ExecutionContextBase.removeComponent(self, comp) + + ## + # @if jp + # @brief ExecutionContextProfile を取得する + # + # 本 ExecutionContext のプロファイルを取得する。 + # + # @param self + # + # @return ExecutionContextProfile + # + # @else + # + # @brief Get the ExecutionContextProfile + # + # This operation provides a profile “descriptor” for the execution + # context. + # + # @endif + + def get_profile(self): + return OpenRTM_aist.ExecutionContextBase.getProfile(self) + + # virtual RTC::ReturnCode_t onStarted(); + + def onStarted(self): + # change EC thread state + guard = OpenRTM_aist.ScopedLock(self._svcmutex) + if not self._svc: + self._svc = True + self.open(0) + del guard + + if self.isAllNextState(RTC.INACTIVE_STATE): + guard = OpenRTM_aist.ScopedLock(self._workerthread._mutex) + self._workerthread._running = False + del guard + else: + guard = OpenRTM_aist.ScopedLock(self._workerthread._mutex) + self._workerthread._running = True + self._workerthread._cond.acquire() + self._workerthread._cond.notify() + self._workerthread._cond.release() + del guard + return RTC.RTC_OK + + # virtual RTC::ReturnCode_t onStopping(); + + def onStopping(self): + # stop thread + guard = OpenRTM_aist.ScopedLock(self._workerthread._mutex) + self._workerthread._running = False + return RTC.RTC_OK + + def onAddedComponent(self, rtobj): + guard = OpenRTM_aist.ScopedLock(self._workerthread._mutex) + if self._workerthread._running == False: + self._worker.updateComponentList() + return RTC.RTC_OK + + def onRemovedComponent(self, rtobj): + guard = OpenRTM_aist.ScopedLock(self._workerthread._mutex) + if self._workerthread._running == False: + self._worker.updateComponentList() + return RTC.RTC_OK + + # virtual RTC::ReturnCode_t + # onWaitingActivated(RTC_impl::RTObjectStateMachine* comp, long int count); + def onWaitingActivated(self, comp, count): + self._rtcout.RTC_TRACE("onWaitingActivated(count = %d)", count) + self._rtcout.RTC_PARANOID("curr: %s, next: %s", + (self.getStateString(comp.getStates().curr), + self.getStateString(comp.getStates().next))) + # Now comp's next state must be ACTIVE state + # If worker thread is stopped, restart worker thread. + if self.isRunning(): + guard = OpenRTM_aist.ScopedLock(self._workerthread._mutex) + if self._workerthread._running == False: + self._workerthread._running = True + self._workerthread._cond.acquire() + self._workerthread._cond.notify() + self._workerthread._cond.release() + del guard + return RTC.RTC_OK + + # virtual RTC::ReturnCode_t + # onActivated(RTC_impl::RTObjectStateMachine* comp, long int count); + + def onActivated(self, comp, count): + self._rtcout.RTC_TRACE("onActivated(count = %d)", count) + self._rtcout.RTC_PARANOID("curr: %s, next: %s", + (self.getStateString(comp.getStates().curr), + self.getStateString(comp.getStates().next))) + # count = -1; Asynch mode. Since onWaitingActivated is not + # called, onActivated() have to send restart singnal to worker + # thread. + # count > 0: Synch mode. + + # Now comp's next state must be ACTIVE state + # If worker thread is stopped, restart worker thread. + if self.isRunning(): + guard = OpenRTM_aist.ScopedLock(self._workerthread._mutex) + if self._workerthread._running == False: + self._workerthread._running = True + self._workerthread._cond.acquire() + self._workerthread._cond.notify() + self._workerthread._cond.release() + del guard + return RTC.RTC_OK + + # virtual RTC::ReturnCode_t + # onWaitingDeactivated(RTC_impl::RTObjectStateMachine* comp, long int + # count); + + def onWaitingDeactivated(self, comp, count): + self._rtcout.RTC_TRACE("onWaitingDeactivated(count = %d)", count) + self._rtcout.RTC_PARANOID("curr: %s, next: %s", + (self.getStateString(comp.getStates().curr), + self.getStateString(comp.getStates().next))) + if self.isAllNextState(RTC.INACTIVE_STATE): + guard = OpenRTM_aist.ScopedLock(self._workerthread._mutex) + if self._workerthread._running == True: + self._workerthread._running = False + self._rtcout.RTC_TRACE( + "All RTCs are INACTIVE. Stopping worker thread.") + del guard + + return RTC.RTC_OK + + # virtual RTC::ReturnCode_t + # onDeactivated(RTC_impl::RTObjectStateMachine* comp, long int count); + + def onDeactivated(self, comp, count): + self._rtcout.RTC_TRACE("onDeactivated(count = %d)", count) + self._rtcout.RTC_PARANOID("curr: %s, next: %s", + (self.getStateString(comp.getStates().curr), + self.getStateString(comp.getStates().next))) + if self.isAllNextState(RTC.INACTIVE_STATE): + guard = OpenRTM_aist.ScopedLock(self._workerthread._mutex) + if self._workerthread._running == True: + self._workerthread._running = False + self._rtcout.RTC_TRACE( + "All RTCs are INACTIVE. Stopping worker thread.") + del guard + + return RTC.RTC_OK + + # virtual RTC::ReturnCode_t + # onWaitingReset(RTC_impl::RTObjectStateMachine* comp, long int count); + + def onWaitingReset(self, comp, count): + self._rtcout.RTC_TRACE("onWaitingReset(count = %d)", count) + self._rtcout.RTC_PARANOID("curr: %s, next: %s", + (self.getStateString(comp.getStates().curr), + self.getStateString(comp.getStates().next))) + if self.isAllNextState(RTC.INACTIVE_STATE): + guard = OpenRTM_aist.ScopedLock(self._workerthread._mutex) + if self._workerthread._running == True: + self._workerthread._running = False + self._rtcout.RTC_TRACE( + "All RTCs are INACTIVE. Stopping worker thread.") + del guard + + return RTC.RTC_OK + + # virtual RTC::ReturnCode_t + # onReset(RTC_impl::RTObjectStateMachine* comp, long int count); + + def onReset(self, comp, count): + self._rtcout.RTC_TRACE("onReset(count = %d)", count) + self._rtcout.RTC_PARANOID("curr: %s, next: %s", + (self.getStateString(comp.getStates().curr), + self.getStateString(comp.getStates().next))) + if self.isAllNextState(RTC.INACTIVE_STATE): + guard = OpenRTM_aist.ScopedLock(self._workerthread._mutex) + if self._workerthread._running == True: + self._workerthread._running = False + self._rtcout.RTC_TRACE( + "All RTCs are INACTIVE. Stopping worker thread.") + del guard + + return RTC.RTC_OK + + # bool threadRunning() + + def threadRunning(self): + guard = OpenRTM_aist.ScopedLock(self._svcmutex) + return self._svc + + def setCpuAffinity(self, props): + self._rtcout.RTC_TRACE("setCpuAffinity()") + + affinity_str = props.getProperty("cpu_affinity") + if affinity_str: + self._rtcout.RTC_DEBUG("CPU affinity property: %s", affinity_str) + + tmp = affinity_str.split(",") + self._cpu = [] + for num in tmp: + try: + self._cpu.append(int(num)) + self._rtcout.RTC_DEBUG( + "CPU affinity int value: %d added.", int(num)) + except ValueError: + pass + + ## + # @if jp + # @class WorkerThreadCtrl + # @brief worker 用状態変数クラス + # + # @else + # @class WorkerThreadCtrl + # @brief Condition variable class for worker + # @endif + class WorkerThreadCtrl: + + ## + # @if jp + # @brief コンストラクタ + # + # コンストラクタ + # + # @param self + # + # @else + # @brief Constructor + # @endif + def __init__(self): + self._mutex = threading.RLock() + self._cond = threading.Condition(self._mutex) + self._running = False ## # @if jp -# @brief ExecutionContext +# @brief ExecutionContext を初期化する # -# ExecutionContext ưѥեȥϿ롣 +# ExecutionContext 起動用ファクトリを登録する。 # -# @param manager ޥ͡㥪֥ +# @param manager マネージャオブジェクト # # @else # # @endif + + def PeriodicExecutionContextInit(manager): - OpenRTM_aist.ExecutionContextFactory.instance().addFactory("PeriodicExecutionContext", - OpenRTM_aist.PeriodicExecutionContext, - OpenRTM_aist.ECDelete) - return + OpenRTM_aist.ExecutionContextFactory.instance().addFactory("PeriodicExecutionContext", + OpenRTM_aist.PeriodicExecutionContext) + return diff --git a/OpenRTM_aist/PeriodicTask.py b/OpenRTM_aist/PeriodicTask.py index 00b1a495..c75b667f 100644 --- a/OpenRTM_aist/PeriodicTask.py +++ b/OpenRTM_aist/PeriodicTask.py @@ -1,5 +1,5 @@ #!/usr/bin/env python -# -*- coding: euc-jp -*- +# -*- coding: utf-8 -*- ## @@ -23,427 +23,424 @@ ## # @if jp -# @class åɼ¹ԥ饹 +# @class 周期タスクスレッド実行クラス # -# δؿ¹Ԥ뤿Υåɥ֥Ȥ¸롣 -# Ѽϰʲ̤ꡣ +# 特定の関数を周期実行するためのスレッドオブジェクトを実現する。 +# 使用手順は以下の通り。 # -# task; // 󥹥 -# task.setTask(TaskFuncBase(obj, mem_func)); // ¹ԤؿͿ -# task.activate(); // åɤ򥹥Ȥ +# task; // インスタンス生成 +# task.setTask(TaskFuncBase(obj, mem_func)); // 実行する関数を与える +# task.activate(); // スレッドをスタートさせる # -# task.suspend(); // ¹Ԥߤ -# task.signal(); // 1¹ -# task.resume(); // ¹ԤƳ +# task.suspend(); // 周期実行を止める +# task.signal(); // 1周期だけ実行 +# task.resume(); // 周期実行を再開 +# +# task.finalize(); // タスクを終了させる # -# task.finalize(); // λ -# # @else # @brief # # @endif # + + class PeriodicTask(OpenRTM_aist.Task): - """ - """ - - ## - # @if jp - # @brief ctor - # @else - # @brief ctor - # @endif - # - def __init__(self): - OpenRTM_aist.Task.__init__(self) - self._period = OpenRTM_aist.TimeValue(0.0) - self._nowait = False - self._func = 0 - self._deleteInDtor = True - self._alive = self.alive_t(False) - self._suspend = self.suspend_t(False) - - # variables for execution time measurement - self._execMeasure = False - self._execCount = 0 - self._execCountMax = 10 - self._execStat = self.statistics_t() - self._execTime = OpenRTM_aist.TimeMeasure() - - # variables for period time measurement - self._periodMeasure = False - self._periodCount = 0 - self._periodCountMax = 10 - self._periodStat = self.statistics_t() - self._periodTime = OpenRTM_aist.TimeMeasure() - - return - - - ## - # @if jp - # @brief dtor - # @else - # @brief dtor - # @endif - # - def __del__(self, Task=OpenRTM_aist.Task): - self.finalize() - self.wait() - Task.__del__(self) - - - - ## - # @if jp - # @brief ¹Ԥ򳫻Ϥ - # - # μ¹Ԥ򳫻Ϥ뤿˥åɤ򥹥Ȥ롣 - # ˳Ϥ줿 true ֤ꡢǤ˥ϺѤߡޤ - # ϼ¹Ԥ륿ꤵƤʤ false ֤ - # - # @return true: ﳫϡfalse: åɺѤߤ̤Ǥ롣 - # - # @else - # @brief Starting the task - # - # Starting a thread to execute a task. If the task/thread is - # started properly, it will return 'TRUE'. if the task/thread - # are already started or task function object is not set, 'FALSE' - # will be returned. - # - # @return true: normal start, false: already started or task is not set - # - # @endif - # - # virtual void activate(); - def activate(self): - guard = OpenRTM_aist.ScopedLock(self._alive.mutex) - if not self._func: - return - - if self._alive.value: - return - - self._alive.value = True - OpenRTM_aist.Task.activate(self) - return - - - ## - # @if jp - # @brief ¹Ԥλ - # - # ¹Υλ롣 - # - # @else - # @brief Finalizing the task - # - # Finalizing the task running. - # - # @endif - # - # virtual void finalize(); - def finalize(self): - guard = OpenRTM_aist.ScopedLock(self._alive.mutex) - self._alive.value = False - - self._suspend.cond.acquire() - self._suspend.suspend = False - self._suspend.cond.notify() - self._suspend.cond.release() - return - - - ## - # @if jp - # @brief ¹ԤǤ - # - # ¹ΥǤ롣 - # - # @else - # @brief Suspending the task - # - # Suspending the task running. - # - # @endif - # - # virtual int suspend(void); - def suspend(self): - self._suspend.cond.acquire() - self._suspend.suspend = True - self._suspend.cond.release() - return 0 - - - ## - # @if jp - # @brief ǤƤ륿Ƴ - # - # ǤƤ륿Ƴ - # - # @else - # @brief Resuming the suspended task - # - # Resuming the suspended task - # - # @endif - # - # virtual int resume(void); - def resume(self): - self._periodTime.reset() - self._execTime.reset() - self._suspend.cond.acquire() - self._suspend.suspend = False - self._suspend.cond.notify() - self._suspend.cond.release() - return 0 - - - ## - # @if jp - # @brief ǤƤ륿1¹Ԥ - # - # ǤƤ륿1¹Ԥ - # - # @else - # @brief Executing the suspended task one tick - # - # Executing the suspended task one tick - # - # @endif - # - # virtual void signal(); - def signal(self): - self._suspend.cond.acquire() - self._suspend.cond.notify() - self._suspend.cond.release() - return - - - ## - # @if jp - # @brief ¹Դؿ򥻥åȤ - # - # @param func int (*)() δؿݥ - # - # @else - # @brief Setting task execution function - # - # @param func Set int (*)() type function pointer - # - # @endif - # - # virtual bool setTask(TaskFuncBase* func, bool delete_in_dtor = true); - def setTask(self, func, delete_in_dtor = True): - if not func: - return False - - self._deleteInDtor = delete_in_dtor - self._func = func - return True - - - ## - # @if jp - # @brief ¹Լ򥻥åȤ - # - # @param period ¹Լ [sec] - # - # @else - # @brief Setting task execution period - # - # @param period Execution period [sec] - # - # @endif - # - # virtual void setPeriod(double period); - # virtual void setPeriod(TimeValue& period); - def setPeriod(self, period): - if type(period) == float: - self._period = OpenRTM_aist.TimeValue(period) - else: - self._period = period - - if self._period.sec() == 0 and self._period.usec() == 0: - self._nowait = True - return - - self._nowait = False - return - - - ## - # @if jp - # @brief ؿ¹Իַ¬ͭˤ뤫 - # @else - # @brief - # @endif - # - # virtual void executionMeasure(bool value); - def executionMeasure(self, value): - self._execMeasure = value - return - - - ## - # @if jp - # @brief ؿ¹Իַ¬ - # @else - # @brief - # @endif - # - # virtual void executionMeasureCount(int n); - def executionMeasureCount(self, n): - self._execCountMax = n - return - - - ## - # @if jp - # @brief ַ¬ͭˤ뤫 - # @else - # @brief - # @endif - # - # virtual void periodicMeasure(bool value); - def periodicMeasure(self, value): - self._periodMeasure = value - return - - ## - # @if jp - # @brief ַ¬ - # @else - # @brief - # @endif - # - # virtual void periodicMeasureCount(int n); - def periodicMeasureCount(self, n): - self._periodCountMax = n - return - - - ## - # @if jp - # @brief ؿ¹Իַ¬̤ - # @else - # @brief - # @endif - # - # virtual TimeMeasure::Statistics getExecStat(); - def getExecStat(self): - guard = OpenRTM_aist.ScopedLock(self._execStat.mutex) - return self._execStat.stat - - - ## - # @if jp - # @brief ַ¬̤ - # @else - # @brief - # @endif - # - # virtual TimeMeasure::Statistics getPeriodStat(); - def getPeriodStat(self): - guard = OpenRTM_aist.ScopedLock(self._periodStat.mutex) - return self._periodStat.stat - - - ## virtual int svc(); - def svc(self): - - while self._alive.value: # needs lock? - if self._periodMeasure: - self._periodTime.tack() - - # wait if suspended - self._suspend.cond.acquire() - if self._suspend.suspend: - self._suspend.cond.wait() - # break if finalized - if not self._alive.value: - self._suspend.cond.release() - return 0 - self._suspend.cond.release() - - if self._periodMeasure: - self._periodTime.tick() - - # task execution - if self._execMeasure: - self._execTime.tick() - - self._func() - if self._execMeasure: - self._execTime.tack() - - # wait for next period - self.updateExecStat() - self.sleep() - self.updatePeriodStat() - - - return 0 - - - ## virtual void sleep(); - def sleep(self): - if self._nowait: - return - - sleep_sec = self._period - self._execTime.interval() - - if sleep_sec.toDouble() < 0: - return - - time.sleep(sleep_sec.toDouble()) - return - - - ## virtual void updateExecStat(); - def updateExecStat(self): - if self._execCount > self._execCountMax: - guard = OpenRTM_aist.ScopedLock(self._execStat.mutex) - - self._execStat.stat = self._execTime.getStatistics() - self._execCount = 0 - - self._execCount += 1 - return - - - ## virtual void updatePeriodStat(); - def updatePeriodStat(self): - if self._periodCount > self._periodCountMax: - guard = OpenRTM_aist.ScopedLock(self._periodStat.mutex) - self._periodStat.stat = self._periodTime.getStatistics() - self._periodCount = 0 - - self._periodCount += 1 - return - - - # alive flag - class alive_t: - def __init__(self, val): - self.value = val - self.mutex = threading.RLock() - return - - # suspend flag - class suspend_t: - def __init__(self, sus): - self.suspend = sus - self.mutex = threading.RLock() - self.cond = threading.Condition(self.mutex) - return - - - # time measurement statistics struct - class statistics_t: + """ + """ + + ## + # @if jp + # @brief ctor + # @else + # @brief ctor + # @endif + # def __init__(self): - self.stat = OpenRTM_aist.TimeMeasure.Statistics() - self.mutex = threading.RLock() + OpenRTM_aist.Task.__init__(self) + self._period = OpenRTM_aist.TimeValue(0.0) + self._nowait = False + self._func = None + self._deleteInDtor = True + self._alive = self.alive_t(False) + self._suspend = self.suspend_t(False) + + # variables for execution time measurement + self._execMeasure = False + self._execCount = 0 + self._execCountMax = 10 + self._execStat = self.statistics_t() + self._execTime = OpenRTM_aist.TimeMeasure() + + # variables for period time measurement + self._periodMeasure = False + self._periodCount = 0 + self._periodCountMax = 10 + self._periodStat = self.statistics_t() + self._periodTime = OpenRTM_aist.TimeMeasure() + + return + + ## + # @if jp + # @brief dtor + # @else + # @brief dtor + # @endif + # + + def __del__(self, Task=OpenRTM_aist.Task): + self.finalize() + self.wait() + Task.__del__(self) + + ## + # @if jp + # @brief タスク実行を開始する + # + # タスクの実行を開始するためにスレッドをスタートさせる。 タスクが + # 正常に開始された場合は true が返り、すでにタスクが開始済み、また + # は実行するタスクが設定されていなければ false を返す。 + # + # @return true: 正常開始、false: スレッド済みかタスクが未設定である。 + # + # @else + # @brief Starting the task + # + # Starting a thread to execute a task. If the task/thread is + # started properly, it will return 'TRUE'. if the task/thread + # are already started or task function object is not set, 'FALSE' + # will be returned. + # + # @return true: normal start, false: already started or task is not set + # + # @endif + # + # virtual void activate(); + + def activate(self): + guard = OpenRTM_aist.ScopedLock(self._alive.mutex) + if not self._func: + return + + if self._alive.value: + return + + self._alive.value = True + OpenRTM_aist.Task.activate(self) + return + + ## + # @if jp + # @brief タスク実行を終了する + # + # 実行中のタスクを終了する。 + # + # @else + # @brief Finalizing the task + # + # Finalizing the task running. + # + # @endif + # + # virtual void finalize(); + + def finalize(self): + guard = OpenRTM_aist.ScopedLock(self._alive.mutex) + self._alive.value = False + + self._suspend.cond.acquire() + self._suspend.suspend = False + self._suspend.cond.notify() + self._suspend.cond.release() + return + + ## + # @if jp + # @brief タスク実行を中断する + # + # 実行中のタスクを中断する。 + # + # @else + # @brief Suspending the task + # + # Suspending the task running. + # + # @endif + # + # virtual int suspend(void); + + def suspend(self): + self._suspend.cond.acquire() + self._suspend.suspend = True + self._suspend.cond.release() + return 0 + + ## + # @if jp + # @brief 中断されているタスクを再開する + # + # 中断されているタスクを再開する + # + # @else + # @brief Resuming the suspended task + # + # Resuming the suspended task + # + # @endif + # + # virtual int resume(void); + + def resume(self): + self._periodTime.reset() + self._execTime.reset() + self._suspend.cond.acquire() + self._suspend.suspend = False + self._suspend.cond.notify() + self._suspend.cond.release() + return 0 + + ## + # @if jp + # @brief 中断されているタスクを1周期だけ実行する + # + # 中断されているタスクを1周期だけ実行する + # + # @else + # @brief Executing the suspended task one tick + # + # Executing the suspended task one tick + # + # @endif + # + # virtual void signal(); + + def signal(self): + self._suspend.cond.acquire() + self._suspend.cond.notify() + self._suspend.cond.release() + return + + ## + # @if jp + # @brief タスク実行関数をセットする + # + # @param func int (*)() 型の関数ポインタ + # + # @else + # @brief Setting task execution function + # + # @param func Set int (*)() type function pointer + # + # @endif + # + # virtual bool setTask(TaskFuncBase* func, bool delete_in_dtor = true); + + def setTask(self, func, delete_in_dtor=True): + if not func: + return False + + self._deleteInDtor = delete_in_dtor + self._func = func + return True + + ## + # @if jp + # @brief タスク実行周期をセットする + # + # @param period 実行周期 [sec] + # + # @else + # @brief Setting task execution period + # + # @param period Execution period [sec] + # + # @endif + # + # virtual void setPeriod(double period); + # virtual void setPeriod(TimeValue& period); + + def setPeriod(self, period): + if isinstance(period, float): + self._period = OpenRTM_aist.TimeValue(period) + else: + self._period = period + + if self._period.sec() == 0 and self._period.usec() == 0: + self._nowait = True + return + + self._nowait = False + return + + ## + # @if jp + # @brief タスク関数実行時間計測を有効にするか + # @else + # @brief + # @endif + # + # virtual void executionMeasure(bool value); + + def executionMeasure(self, value): + self._execMeasure = value + return + + ## + # @if jp + # @brief タスク関数実行時間計測周期 + # @else + # @brief + # @endif + # + # virtual void executionMeasureCount(int n); + + def executionMeasureCount(self, n): + self._execCountMax = n + return + + ## + # @if jp + # @brief タスク周期時間計測を有効にするか + # @else + # @brief + # @endif + # + # virtual void periodicMeasure(bool value); + + def periodicMeasure(self, value): + self._periodMeasure = value + return + + ## + # @if jp + # @brief タスク周期時間計測周期 + # @else + # @brief + # @endif + # + # virtual void periodicMeasureCount(int n); + def periodicMeasureCount(self, n): + self._periodCountMax = n + return + + ## + # @if jp + # @brief タスク関数実行時間計測結果を取得 + # @else + # @brief + # @endif + # + # virtual TimeMeasure::Statistics getExecStat(); + + def getExecStat(self): + guard = OpenRTM_aist.ScopedLock(self._execStat.mutex) + return self._execStat.stat + + ## + # @if jp + # @brief タスク周期時間計測結果を取得 + # @else + # @brief + # @endif + # + # virtual TimeMeasure::Statistics getPeriodStat(); + + def getPeriodStat(self): + guard = OpenRTM_aist.ScopedLock(self._periodStat.mutex) + return self._periodStat.stat + + # virtual int svc(); + def svc(self): + + while self._alive.value: # needs lock? + if self._periodMeasure: + self._periodTime.tack() + + # wait if suspended + self._suspend.cond.acquire() + if self._suspend.suspend: + self._suspend.cond.wait() + # break if finalized + if not self._alive.value: + self._suspend.cond.release() + return 0 + self._suspend.cond.release() + + if self._periodMeasure: + self._periodTime.tick() + + # task execution + if self._execMeasure: + self._execTime.tick() + + self._func() + if self._execMeasure: + self._execTime.tack() + + # wait for next period + self.updateExecStat() + self.sleep() + self.updatePeriodStat() + + return 0 + + # virtual void sleep(); + + def sleep(self): + if self._nowait: + return + + sleep_sec = self._period - self._execTime.interval() + + if sleep_sec.toDouble() < 0: + return + + time.sleep(sleep_sec.toDouble()) + return + + # virtual void updateExecStat(); + + def updateExecStat(self): + if self._execCount > self._execCountMax: + guard = OpenRTM_aist.ScopedLock(self._execStat.mutex) + + self._execStat.stat = self._execTime.getStatistics() + self._execCount = 0 + + self._execCount += 1 + return + + # virtual void updatePeriodStat(); + + def updatePeriodStat(self): + if self._periodCount > self._periodCountMax: + guard = OpenRTM_aist.ScopedLock(self._periodStat.mutex) + self._periodStat.stat = self._periodTime.getStatistics() + self._periodCount = 0 + + self._periodCount += 1 + return + + # alive flag + + class alive_t: + def __init__(self, val): + self.value = val + self.mutex = threading.RLock() + return + + # suspend flag + class suspend_t: + def __init__(self, sus): + self.suspend = sus + self.mutex = threading.RLock() + self.cond = threading.Condition(self.mutex) + return + # time measurement statistics struct + class statistics_t: + def __init__(self): + self.stat = OpenRTM_aist.TimeMeasure.Statistics() + self.mutex = threading.RLock() diff --git a/OpenRTM_aist/PeriodicTaskFactory.py b/OpenRTM_aist/PeriodicTaskFactory.py index 5c52278d..0ba7ca45 100644 --- a/OpenRTM_aist/PeriodicTaskFactory.py +++ b/OpenRTM_aist/PeriodicTaskFactory.py @@ -1,5 +1,5 @@ #!/usr/bin/env python -# -*- coding: euc-jp -*- +# -*- coding: utf-8 -*- ## # @file PeriodicTaskFactory.py @@ -20,22 +20,21 @@ periodictaskfactory = None -class PeriodicTaskFactory(OpenRTM_aist.Factory,OpenRTM_aist.PeriodicTask): - def __init__(self): - OpenRTM_aist.Factory.__init__(self) - pass +class PeriodicTaskFactory(OpenRTM_aist.Factory, OpenRTM_aist.PeriodicTask): + def __init__(self): + OpenRTM_aist.Factory.__init__(self) + pass - def __del__(self): - pass + def __del__(self): + pass + def instance(): + global periodictaskfactory - def instance(): - global periodictaskfactory + if periodictaskfactory is None: + periodictaskfactory = PeriodicTaskFactory() - if periodictaskfactory is None: - periodictaskfactory = PeriodicTaskFactory() + return periodictaskfactory - return periodictaskfactory - - instance = staticmethod(instance) + instance = staticmethod(instance) diff --git a/OpenRTM_aist/PortAdmin.py b/OpenRTM_aist/PortAdmin.py index 0618fe22..806828da 100644 --- a/OpenRTM_aist/PortAdmin.py +++ b/OpenRTM_aist/PortAdmin.py @@ -1,5 +1,5 @@ #!/usr/bin/env python -# -*- coding: euc-jp -*- +# -*- coding: utf-8 -*- ## # @file PortAdmin.py @@ -15,20 +15,18 @@ # All rights reserved. - import RTC import OpenRTM_aist - ## # @if jp # @class PortAdmin -# @brief PortAdmin 饹 +# @brief PortAdmin クラス # -# Ƽ Port δԤ饹 -# Port Ͽ/ϿʤɳƼ¹ԤȤȤˡϿƤ -# Port δԤ饹 +# 各種 Port の管理を行うクラス。 +# Port の登録/登録解除など各種管理操作を実行するとともに、登録されている +# Port の管理を行うクラス。 # # @since 0.4.0 # @@ -37,410 +35,408 @@ # @brief PortAdmin class # @endif class PortAdmin: - """ - """ - - - - ## - # @if jp - # @class comp_op - # @brief Port 饹 - # @else - # - # @endif - class comp_op: - def __init__(self, name=None, factory=None): - if name: - self._name = name - if factory: - self._name = factory.getProfile().name - - def __call__(self, obj): - name_ = obj.getProfile().name - return self._name == name_ - - - ## - # @if jp - # @class find_port_name - # @brief Port ѥե󥯥 - # @else - # @endif - class find_port_name: - def __init__(self, name): - self._name = name - - def __call__(self, p): - prof = p.get_port_profile() - name_ = prof.name - return self._name == name_ - - - ## - # @if jp - # @brief Portѥե󥯥 - # @else - # @brief Functor to delete the Port - # @endif - class del_port: - def __init__(self, pa): - self._pa = pa - return - - def __call__(self, p): - self._pa.deletePort(p) - - - class find_port: - # find_port(const PortService_ptr& p) : m_port(p) {}; - def __init__(self, p): - self._port = p - - # bool operator()(const PortService_ptr& p) - def __call__(self, p): - return self._port._is_equivalent(p) - - - ## - # @if jp - # @brief 󥹥ȥ饯 - # - # 󥹥ȥ饯 - # - # @param self - # @param orb ORB - # @param poa POA - # - # @else - # @brief Constructor - # @endif - def __init__(self, orb, poa): - # ORB ֥ - self._orb = orb - - # POA ֥ - self._poa = poa - - # PortΥ֥ȥե󥹤Υꥹ. PortServiceList - self._portRefs = [] - - # ХȤľܳǼ륪֥ȥޥ͡ - self._portServants = OpenRTM_aist.ObjectManager(self.comp_op) - - self._rtcout = OpenRTM_aist.Manager.instance().getLogbuf("PortAdmin") - - ## - # @if jp - # - # @brief Port ꥹȤμ - # - # registerPort() ˤϿ줿 Port ꥹȤ롣 - # - # @param self - # - # @return Port ꥹ - # - # @else - # - # @brief Get PortServiceList - # - # This operation returns the pointer to the PortServiceList of Ports regsitered - # by registerPort(). - # - # @return PortServiceList+ The pointer points PortServiceList - # - # @endif - def getPortServiceList(self): - return self._portRefs - - - ## - # @if jp - # - # @brief PorProfile ꥹȤμ - # - # addPort() ˤϿ줿 Port Profile ꥹȤ롣 - # - # @return PortProfile ꥹ - # - # @else - # - # @brief Get PorProfileList - # - # This operation gets the Profile list of Ports registered by - # addPort(). - # - # @return The pointer points PortProfile list - # - # @endif - # - def getPortProfileList(self): - ret = [] - for p in self._portRefs: - ret.append(p.get_port_profile()) - - return ret - - - ## - # @if jp - # - # @brief Port Υ֥ȻȤμ - # - # port_name ǻꤷ Port Υ֥ȻȤ֤ - # port_name ǻꤹ Port Ϥ餫 registerPort() ϿƤ - # ʤФʤʤ - # - # @param self - # @param port_name Ȥ֤Port̾ - # - # @return Port_ptr PortΥ֥Ȼ - # - # @else - # - # @brief Get PortServiceList - # - # This operation returns the pointer to the PortServiceList of Ports regsitered - # by registerPort(). - # - # @param port_name The name of Port to be returned the reference. - # - # @return Port_ptr Port's object reference. - # - # @endif - def getPortRef(self, port_name): - index = OpenRTM_aist.CORBA_SeqUtil.find(self._portRefs, self.find_port_name(port_name)) - if index >= 0: - return self._portRefs[index] - return None - - - ## - # @if jp - # - # @brief Port ΥХȤΥݥ󥿤μ - # - # port_name ǻꤷ Port ΥХȤΥݥ󥿤֤ - # port_name ǻꤹ Port Ϥ餫 registerPort() ϿƤ - # ʤФʤʤ - # - # @param self - # @param port_name Ȥ֤Port̾ - # - # @return PortBase* PortХȴ쥯饹Υݥ - # - # @else - # - # @brief Getpointer to the Port's servant - # - # This operation returns the pointer to the PortBase servant regsitered - # by registerPort(). - # - # @param port_name The name of Port to be returned the servant pointer. - # - # @return PortBase* Port's servant's pointer. - # - # @endif - def getPort(self, port_name): - return self._portServants.find(port_name) - - - ## - # @if jp - # - # @brief Port Ͽ - # - # port ǻꤵ줿 Port ΥХȤϿ롣 - # Ͽ줿 Port ΥХȤϥ󥹥ȥ饯Ϳ줿POA - # activate 졢Υ֥ȻȤPortProfile˥åȤ롣 - # - # @param self - # @param port Port Х - # - # @else - # - # @brief Regsiter Port - # - # This operation registers the Port's servant given by argument. - # The given Port's servant will be activated on the POA that is given - # to the constructor, and the created object reference is set - # to the Port's profile. - # - # @param port The Port's servant. - # - # @endif - # void registerPort(PortBase& port); - def registerPort(self, port): - if not self.addPort(port): - self._rtcout.RTC_ERROR("registerPort() failed.") - return - - # void registerPort(PortService_ptr port); - # def registerPortByReference(self, port_ref): - # self.addPortByReference(port_ref) - # return - - # new interface. since 1.0.0-RELEASE - # void addPort(PortBase& port); - def addPort(self, port): - if isinstance(port, RTC._objref_PortService): - index = OpenRTM_aist.CORBA_SeqUtil.find(self._portRefs, - self.find_port_name(port.get_port_profile().name)) - if index >= 0: - return False - self._portRefs.append(port) - return True - else: - index = OpenRTM_aist.CORBA_SeqUtil.find(self._portRefs, - self.find_port_name(port.getName())) - if index >= 0: - return False - self._portRefs.append(port.getPortRef()) - return self._portServants.registerObject(port) - - - # new interface. since 1.0.0-RELEASE - # void addPort(PortService_ptr port); - # def addPortByReference(self, port_ref): - # self._portRefs.append(port_ref) - # return - - ## - # @if jp - # - # @brief Port Ͽ - # - # port ǻꤵ줿 Port Ͽ롣 - # Port deactivate 졢PortProfileΥե󥹤ˤϡ - # nilͤ롣 - # - # @param self - # @param port Port Х - # - # @else - # - # @brief Delete the Port's registration - # - # This operation unregisters the Port's registration. - # When the Port is unregistered, Port is deactivated, and the object - # reference in the Port's profile is set to nil. - # - # @param port The Port's servant. - # - # @endif - def deletePort(self, port): - if not self.removePort(port): - self._rtcout.RTC_ERROR("deletePort(PortBase&) failed.") - return - - # new interface. since 1.0.0-RELEASE - def removePort(self, port): - try: - if isinstance(port,RTC._objref_PortService): - OpenRTM_aist.CORBA_SeqUtil.erase_if(self._portRefs, self.find_port(port)) - return True - - port.disconnect_all() - tmp = port.getProfile().name - OpenRTM_aist.CORBA_SeqUtil.erase_if(self._portRefs, self.find_port_name(tmp)) - - self._poa.deactivate_object(self._poa.servant_to_id(port)) - port.setPortRef(RTC.PortService._nil) - - if not self._portServants.unregisterObject(tmp): - return False - return True - except: - self._rtcout.RTC_ERROR(OpenRTM_aist.Logger.print_exception()) - return False - - - ## - # @if jp - # - # @brief ̾λˤPort Ͽ - # - # ǻꤵ줿̾ Port Ͽ롣 - # Port deactivate 졢PortProfileΥե󥹤ˤϡ - # nilͤ롣 - # - # @param self - # @param port_name Port ̾ - # - # @else - # - # @brief Delete the Port' registration - # - # This operation delete the Port's registration specified by port_ name. - # When the Port is unregistered, Port is deactivated, and the object - # reference in the Port's profile is set to nil. - # - # @param port_name The Port's name. - # - # @endif - def deletePortByName(self, port_name): - if not port_name: - return - - p = self._portServants.find(port_name) - self.removePort(p) - return - - - ## - # @if jp - # @brief Ƥ Port Υ󥿡ե activates - # @else - # @brief Activate all Port interfaces - # @endif - # void PortAdmin::activatePorts() - def activatePorts(self): - ports = self._portServants.getObjects() - for port in ports: - port.activateInterfaces() - - return - - - ## - # @if jp - # @brief Ƥ Port Υ󥿡ե deactivates - # @else - # @brief Deactivate all Port interfaces - # @endif - # void PortAdmin::deactivatePorts() - def deactivatePorts(self): - ports = self._portServants.getObjects() - for port in ports: - port.deactivateInterfaces() - - return - - - ## - # @if jp - # - # @brief Ƥ Port deactivateϿ - # - # ϿƤƤPortФơХȤdeactivateԤ - # ϿꥹȤ롣 - # - # @param self - # - # @else - # - # @brief Unregister the Port - # - # This operation deactivates the all Port and deletes the all Port's - # registrations from the list. - # - # @endif - def finalizePorts(self): - self.deactivatePorts() - ports = self._portServants.getObjects() - len_ = len(ports) - for i in range(len_): - idx = (len_ - 1) - i - ports[idx].exit() - self.removePort(ports[idx]) + """ + """ + + ## + # @if jp + # @class comp_op + # @brief Port 管理用内部クラス + # @else + # + # @endif + class comp_op: + def __init__(self, name=None, factory=None): + if name: + self._name = name + if factory: + self._name = factory.getProfile().name + + def __call__(self, obj): + name_ = obj.getProfile().name + return self._name == name_ + + ## + # @if jp + # @class find_port_name + # @brief Port 検索用ファンクタ + # @else + # @endif + + class find_port_name: + def __init__(self, name): + self._name = name + + def __call__(self, p): + prof = p.get_port_profile() + name_ = prof.name + return self._name == name_ + + ## + # @if jp + # @brief Port削除用ファンクタ + # @else + # @brief Functor to delete the Port + # @endif + + class del_port: + def __init__(self, pa): + self._pa = pa + return + + def __call__(self, p): + self._pa.deletePort(p) + + class find_port: + # find_port(const PortService_ptr& p) : m_port(p) {}; + def __init__(self, p): + self._port = p + + # bool operator()(const PortService_ptr& p) + def __call__(self, p): + return self._port._is_equivalent(p) + + ## + # @if jp + # @brief コンストラクタ + # + # コンストラクタ + # + # @param self + # @param orb ORB + # @param poa POA + # + # @else + # @brief Constructor + # @endif + + def __init__(self, orb, poa): + # ORB オブジェクト + self._orb = orb + + # POA オブジェクト + self._poa = poa + + # Portのオブジェクトリファレンスのリスト. PortServiceList + self._portRefs = [] + + # サーバントを直接格納するオブジェクトマネージャ + self._portServants = OpenRTM_aist.ObjectManager(self.comp_op) + + self._rtcout = OpenRTM_aist.Manager.instance().getLogbuf("PortAdmin") + + ## + # @if jp + # + # @brief Port リストの取得 + # + # registerPort() により登録された Port の リストを取得する。 + # + # @param self + # + # @return Port リスト + # + # @else + # + # @brief Get PortServiceList + # + # This operation returns the pointer to the PortServiceList of Ports regsitered + # by registerPort(). + # + # @return PortServiceList+ The pointer points PortServiceList + # + # @endif + def getPortServiceList(self): + return self._portRefs + + ## + # @if jp + # + # @brief PorProfile リストの取得 + # + # addPort() により登録された Port の Profile リストを取得する。 + # + # @return PortProfile リスト + # + # @else + # + # @brief Get PorProfileList + # + # This operation gets the Profile list of Ports registered by + # addPort(). + # + # @return The pointer points PortProfile list + # + # @endif + # + + def getPortProfileList(self): + ret = [] + for p in self._portRefs: + ret.append(p.get_port_profile()) + + return ret + + ## + # @if jp + # + # @brief Port のオブジェクト参照の取得 + # + # port_name で指定した Port のオブジェクト参照を返す。 + # port_name で指定する Port はあらかじめ registerPort() で登録されてい + # なければならない。 + # + # @param self + # @param port_name 参照を返すPortの名前 + # + # @return Port_ptr Portのオブジェクト参照 + # + # @else + # + # @brief Get PortServiceList + # + # This operation returns the pointer to the PortServiceList of Ports regsitered + # by registerPort(). + # + # @param port_name The name of Port to be returned the reference. + # + # @return Port_ptr Port's object reference. + # + # @endif + + def getPortRef(self, port_name): + index = OpenRTM_aist.CORBA_SeqUtil.find( + self._portRefs, self.find_port_name(port_name)) + if index >= 0: + return self._portRefs[index] + return None + + ## + # @if jp + # + # @brief Port のサーバントのポインタの取得 + # + # port_name で指定した Port のサーバントのポインタを返す。 + # port_name で指定する Port はあらかじめ registerPort() で登録されてい + # なければならない。 + # + # @param self + # @param port_name 参照を返すPortの名前 + # + # @return PortBase* Portサーバント基底クラスのポインタ + # + # @else + # + # @brief Getpointer to the Port's servant + # + # This operation returns the pointer to the PortBase servant regsitered + # by registerPort(). + # + # @param port_name The name of Port to be returned the servant pointer. + # + # @return PortBase* Port's servant's pointer. + # + # @endif + + def getPort(self, port_name): + return self._portServants.find(port_name) + + ## + # @if jp + # + # @brief Port を登録する + # + # 引数 port で指定された Port のサーバントを登録する。 + # 登録された Port のサーバントはコンストラクタで与えられたPOA 上で + # activate され、そのオブジェクト参照はPortのProfileにセットされる。 + # + # @param self + # @param port Port サーバント + # + # @else + # + # @brief Regsiter Port + # + # This operation registers the Port's servant given by argument. + # The given Port's servant will be activated on the POA that is given + # to the constructor, and the created object reference is set + # to the Port's profile. + # + # @param port The Port's servant. + # + # @endif + # void registerPort(PortBase& port); + + def registerPort(self, port): + if not self.addPort(port): + self._rtcout.RTC_ERROR("registerPort() failed.") + return + + # void registerPort(PortService_ptr port); + # def registerPortByReference(self, port_ref): + # self.addPortByReference(port_ref) + # return + + # new interface. since 1.0.0-RELEASE + # void addPort(PortBase& port); + def addPort(self, port): + if isinstance(port, RTC._objref_PortService): + index = OpenRTM_aist.CORBA_SeqUtil.find(self._portRefs, + self.find_port_name(port.get_port_profile().name)) + if index >= 0: + return False + self._portRefs.append(port) + return True + else: + index = OpenRTM_aist.CORBA_SeqUtil.find(self._portRefs, + self.find_port_name(port.getName())) + if index >= 0: + return False + self._portRefs.append(port.getPortRef()) + return self._portServants.registerObject(port) + + # new interface. since 1.0.0-RELEASE + # void addPort(PortService_ptr port); + # def addPortByReference(self, port_ref): + # self._portRefs.append(port_ref) + # return + + ## + # @if jp + # + # @brief Port の登録を解除する + # + # 引数 port で指定された Port の登録を解除する。 + # 削除時に Port は deactivate され、PortのProfileのリファレンスには、 + # nil値が代入される。 + # + # @param self + # @param port Port サーバント + # + # @else + # + # @brief Delete the Port's registration + # + # This operation unregisters the Port's registration. + # When the Port is unregistered, Port is deactivated, and the object + # reference in the Port's profile is set to nil. + # + # @param port The Port's servant. + # + # @endif + + def deletePort(self, port): + if not self.removePort(port): + self._rtcout.RTC_ERROR("deletePort(PortBase&) failed.") + return + + # new interface. since 1.0.0-RELEASE + def removePort(self, port): + try: + if isinstance(port, RTC._objref_PortService): + OpenRTM_aist.CORBA_SeqUtil.erase_if( + self._portRefs, self.find_port(port)) + return True + + port.disconnect_all() + tmp = port.getProfile().name + OpenRTM_aist.CORBA_SeqUtil.erase_if( + self._portRefs, self.find_port_name(tmp)) + + self._poa.deactivate_object(self._poa.servant_to_id(port)) + port.setPortRef(RTC.PortService._nil) + + if not self._portServants.unregisterObject(tmp): + return False + return True + except BaseException: + self._rtcout.RTC_ERROR(OpenRTM_aist.Logger.print_exception()) + return False + + ## + # @if jp + # + # @brief 名称指定によりPort の登録を解除する + # + # 引数で指定された名前を持つ Port の登録を削除する。 + # 削除時に Port は deactivate され、PortのProfileのリファレンスには、 + # nil値が代入される。 + # + # @param self + # @param port_name Port の名前 + # + # @else + # + # @brief Delete the Port' registration + # + # This operation delete the Port's registration specified by port_ name. + # When the Port is unregistered, Port is deactivated, and the object + # reference in the Port's profile is set to nil. + # + # @param port_name The Port's name. + # + # @endif + + def deletePortByName(self, port_name): + if not port_name: + return + + p = self._portServants.find(port_name) + self.removePort(p) + return + + ## + # @if jp + # @brief 全ての Port のインターフェースを activates する + # @else + # @brief Activate all Port interfaces + # @endif + # void PortAdmin::activatePorts() + + def activatePorts(self): + ports = self._portServants.getObjects() + for port in ports: + port.activateInterfaces() + + return + + ## + # @if jp + # @brief 全ての Port のインターフェースを deactivates する + # @else + # @brief Deactivate all Port interfaces + # @endif + # void PortAdmin::deactivatePorts() + + def deactivatePorts(self): + ports = self._portServants.getObjects() + for port in ports: + port.deactivateInterfaces() + + return + + ## + # @if jp + # + # @brief 全ての Port をdeactivateし登録を削除する + # + # 登録されている全てのPortに対して、サーバントのdeactivateを行い、 + # 登録リストから削除する。 + # + # @param self + # + # @else + # + # @brief Unregister the Port + # + # This operation deactivates the all Port and deletes the all Port's + # registrations from the list. + # + # @endif + + def finalizePorts(self): + self.deactivatePorts() + ports = self._portServants.getObjects() + for port in ports[::-1]: + port.exit() + self.removePort(port) diff --git a/OpenRTM_aist/PortBase.py b/OpenRTM_aist/PortBase.py index d76bef19..70a1ba62 100644 --- a/OpenRTM_aist/PortBase.py +++ b/OpenRTM_aist/PortBase.py @@ -1,5 +1,5 @@ #!/usr/bin/env python -# -*- coding: euc-jp -*- +# -*- coding: utf-8 -*- ## # @file PortBase.py @@ -20,28 +20,28 @@ import OpenRTM_aist import OpenRTM_aist.CORBA_RTCUtil -import RTC, RTC__POA - +import RTC +import RTC__POA ## # @if jp # @class PortBase -# @brief Port δ쥯饹 +# @brief Port の基底クラス # -# RTC::Port δȤʤ륯饹 -# RTC::Port Ϥۤ UML Port γǰѾƤꡢۤƱΤΤȤߤʤ -# ȤǤ롣RT ݡͥȤΥ󥻥ץȤˤƤϡ -# Port ϥݡͥȤ°ݡͥȤ¾ΥݡͥȤߺ -# ԤǤꡢ̾ĤΥ󥿡եȴϢդ롣 -# ݡͥȤ Port ̤ƳФ󥿡ե󶡤ޤ׵ -# 뤳ȤǤPortϤ³ô +# RTC::Port の基底となるクラス。 +# RTC::Port はほぼ UML Port の概念を継承しており、ほぼ同等のものとみなす +# ことができる。RT コンポーネントのコンセプトにおいては、 +# Port はコンポーネントに付属し、コンポーネントが他のコンポーネントと相互作用 +# を行う接点であり、通常幾つかのインターフェースと関連付けられる。 +# コンポーネントは Port を通して外部に対しインターフェースを提供または要求 +# することができ、Portはその接続を管理する役割を担う。 #

    -# Port ζݥ饹ϡ̾ RT ݡͥȥ󥹥Ʊ -# 졢󶡡׵ᥤ󥿡եϿ塢RT ݡͥȤ -# Ͽ졢饢ǽ Port ȤƵǽ뤳ȤꤷƤ롣 +# Port の具象クラスは、通常 RT コンポーネントインスタンス生成時に同時に +# 生成され、提供・要求インターフェースを登録した後、RT コンポーネントに +# 登録され、外部からアクセス可能な Port として機能することを想定している。 #

    -# RTC::Port CORBA 󥿡եȤưʲΥڥ졼󶡤롣 +# RTC::Port は CORBA インターフェースとして以下のオペレーションを提供する。 # # - get_port_profile() # - get_connector_profiles() @@ -52,19 +52,19 @@ # - notify_disconnect() # - disconnect_all() # -# Υ饹ǤϡΥڥ졼μ󶡤롣 +# このクラスでは、これらのオペレーションの実装を提供する。 #

    -# Υڥ졼Τget_port_profile(), get_connector_profiles(), -# get_connector_profile(), connect(), disconnect(), disconnect_all() ϡ -# ֥饹ˤä˿񤤤ѹɬפʤᡢС饤 -# 뤳ȤϿ侩ʤ +# これらのオペレーションのうち、get_port_profile(), get_connector_profiles(), +# get_connector_profile(), connect(), disconnect(), disconnect_all() は、 +# サブクラスにおいて特に振る舞いを変更する必要がないため、オーバーライド +# することは推奨されない。 #

    -# notify_connect(), notify_disconnect() ˤĤƤϡ֥饹󶡡׵ -# 륤󥿡եμ˱ơ񤤤ѹɬפ -# ⤷ʤľܥС饤ɤ뤳ȤϿ侩줺 -# Ҥ notify_connect(), notify_disconnect() ιˤƤҤ٤̤ -# δؿ˴Ϣ ؿ򥪡С饤ɤ뤳Ȥˤ꿶񤤤ѹ -# Ȥ侩롣 +# notify_connect(), notify_disconnect() については、サブクラスが提供・要求 +# するインターフェースの種類に応じて、振る舞いを変更する必要が生ずる +# かもしれないが、これらを直接オーバーライドすることは推奨されず、 +# 後述の notify_connect(), notify_disconnect() の項においても述べられる通り +# これらの関数に関連した 関数をオーバーライドすることにより振る舞いを変更する +# ことが推奨される。 # # @since 0.4.0 # @@ -100,7 +100,7 @@ #

    # In these operations, as for get_port_profile(), get_connector_profiles(), # get_connector_profile(), connect(), disconnect() and disconnect_all(), -# since their behaviors especially need not to be change in subclass, +# since their behaviors especially need not to be change in subclass, # overriding is not recommended. #

    # As for notify_connect() and notify_disconnect(), you may have to modify @@ -114,2437 +114,2479 @@ # # @endif class PortBase(RTC__POA.PortService): - """ - """ - - - - ## - # @if jp - # @brief 󥹥ȥ饯 - # - # PortBase Υ󥹥ȥ饯 Port ̾ name ˼Ԥ - # ƱˡʬȤ CORBA Object ȤƳȤ PortProfile - # port_ref ˼ȤΥ֥ȥե󥹤Ǽ롣 - # ̾ˤϡ"." ʳʸѤ뤳ȤǤ롣 - # - # @param self - # @param name Port ̾(ǥե:None) - # - # @else - # - # @brief Constructor - # - # The constructor of the ProtBase class is given the name of this Port - # and initialized. At the same time, the PortBase activates itself - # as CORBA object and stores its object reference to the PortProfile's - # port_ref member. - # Characters except "." can be used for the name of the port. - # - # @param name The name of Port - # - # @endif - def __init__(self, name=None): - self._ownerInstanceName = "unknown" - self._objref = self._this() - - self._profile = RTC.PortProfile("", [], RTC.PortService._nil, [], RTC.RTObject._nil,[]) - # Now Port name is .. r1648 - if name is None: - self._profile.name = "unknown.unknown" - else: - self._profile.name = self._ownerInstanceName+"."+name - - self._profile.port_ref = self._objref - self._profile.owner = RTC.RTObject._nil - self._profile_mutex = threading.RLock() - self._connection_mutex = threading.RLock() - self._rtcout = OpenRTM_aist.Manager.instance().getLogbuf(name) - self._onPublishInterfaces = None - self._onSubscribeInterfaces = None - self._onConnected = None - self._onUnsubscribeInterfaces = None - self._onDisconnected = None - self._onConnectionLost = None - self._connectionLimit = -1 - self._portconnListeners = None - self._properties = OpenRTM_aist.Properties() - return - - - ## - # @if jp - # - # @brief ǥȥ饯 - # - # ǥȥ饯ǤϡPortService CORBA ֥Ȥ deactivate - # Ԥdeactivate˺ݤ㳰ꤲ뤳ȤϤʤ - # - # @else - # - # @brief Destructor - # - # In the destructor, PortService CORBA object is deactivated. - # This function never throws exception. - # - # @endif - # - def __del__(self): - pass - - - ## - # @if jp - # - # @brief λؿ - # - # @param self - # - # @else - # - # @brief - # - # @param self - # - # @endif - # - def exit(self): - self._rtcout.RTC_TRACE("PortBase.__del__()") - #try: - # poa = OpenRTM_aist.Manager.instance().getPOA() - # oid = poa.servant_to_id(self) - # poa.deactivate_object(oid) - #except: - # self._rtcout.RTC_ERROR(OpenRTM_aist.Logger.print_exception()) - - ## - # @if jp - # - # @brief [CORBA interface] PortProfile - # - # PortݻPortProfile֤ - # PortProfile ¤ΤϰʲΥСġ - # - # - name [string ] Port ̾ - # - interfaces [PortInterfaceProfileList ] Port ݻ - # PortInterfaceProfile Υ - # - port_ref [Port Object ] Port ȤΥ֥ȥե - # - connector_profile [ConnectorProfileList ] Port ݻ - # ConnectorProfile Υ - # - owner [RTObject Object ] Port ͭ - # RTObjectΥե - # - properties [NVList ] ¾Υץѥƥ - # - # @param self - # - # @return PortProfile - # - # @else - # - # @brief [CORBA interface] Get the PortProfile of the Port - # - # This operation returns the PortProfile of the Port. - # PortProfile struct has the following members, - # - # - name [string ] The name of the Port. - # - interfaces [PortInterfaceProfileList] The sequence of - # PortInterfaceProfile owned by the Port - # - port_ref [Port Object] The object reference of the Port. - # - connector_profile [ConnectorProfileList] The sequence of - # ConnectorProfile owned by the Port. - # - owner [RTObject Object] The object reference of - # RTObject that is owner of the Port. - # - properties [NVList] The other properties. - # - # @return the PortProfile of the Port - # - # @endif - # PortProfile* get_port_profile() - def get_port_profile(self): - self._rtcout.RTC_TRACE("get_port_profile()") - - self.updateConnectors() - - guard = OpenRTM_aist.ScopedLock(self._profile_mutex) - - prof = RTC.PortProfile(self._profile.name, - self._profile.interfaces, - self._profile.port_ref, - self._profile.connector_profiles, - self._profile.owner, - self._profile.properties) - - return prof - - - ## - # @if jp - # - # @brief PortProfile 롣 - # - # δؿϡ֥ݻƤ PortProfile - # const Ȥ֤ const ؿǤ롣 - # - # @post δؿƤӽФȤˤ֤ѹ뤳ȤϤʤ - # - # @return PortProfile - # - # @else - # - # @brief Get the PortProfile of the Port - # - # This function is a const function that returns a const - # reference of the PortProfile stored in this Port. - # - # @post This function never changes the state of the object. - # - # @return PortProfile - # - # @endif - # PortProfile& getPortProfile() const; - def getPortProfile(self): - self._rtcout.RTC_TRACE("getPortProfile()") - return self._profile - - - ## - # @if jp - # - # @brief [CORBA interface] ConnectorProfileList - # - # Portݻ ConnectorProfile sequence ֤ - # ConnectorProfile Port ֤³ץեݻ빽¤ΤǤꡢ - # ³Port֤Ǿ򴹤ԤϢ뤹٤Ƥ Port Ʊͤ - # ݻ롣 - # ConnectorProfile ϰʲΥСݻƤ롣 - # - # - name [string ] Υͥ̾ - # - connector_id [string ] ˡID - # - ports [Port sequnce] Υͥ˴Ϣ Port Υ֥ - # ե󥹤Υ󥹡 - # - properties [NVList ] ¾Υץѥƥ - # - # @param self - # - # @return Port ݻ ConnectorProfile - # - # @else - # - # @brief [CORBA interface] Get the ConnectorProfileList of the Port - # - # This operation returns a list of the ConnectorProfiles of the Port. - # ConnectorProfile includes the connection information that describes - # relation between (among) Ports, and Ports exchange the ConnectionProfile - # on connection process and hold the same information in each Port. - # ConnectionProfile has the following members, - # - # - name [string] The name of the connection. - # - connector_id [string] Unique identifier. - # - ports [Port sequnce] The sequence of Port's object reference - # that are related the connection. - # - properties [NVList] The other properties. - # - # @return the ConnectorProfileList of the Port - # - # @endif - # virtual ConnectorProfileList* get_connector_profiles() - def get_connector_profiles(self): - self._rtcout.RTC_TRACE("get_connector_profiles()") - - self.updateConnectors() - - guard = OpenRTM_aist.ScopedLock(self._profile_mutex) - return self._profile.connector_profiles - - - ## - # @if jp - # - # @brief [CORBA interface] ConnectorProfile - # - # connector_id ǻꤵ줿 ConnectorProfile ֤ - # ꤷ connector_id ConnectorProfile ݻƤʤϡ - # ConnectorProfile ֤ - # - # @param self - # @param connector_id ConnectorProfile ID - # - # @return connector_id ǻꤵ줿 ConnectorProfile - # - # @else - # - # @brief [CORBA interface] Get the ConnectorProfile - # - # This operation returns the ConnectorProfiles specified connector_id. - # - # @param connector_id ID of the ConnectorProfile - # - # @return the ConnectorProfile identified by the connector_id - # - # @endif - # ConnectorProfile* get_connector_profile(const char* connector_id) - def get_connector_profile(self, connector_id): - self._rtcout.RTC_TRACE("get_connector_profile(%s)", connector_id) - - self.updateConnectors() - - guard = OpenRTM_aist.ScopedLock(self._profile_mutex) - index = OpenRTM_aist.CORBA_SeqUtil.find(self._profile.connector_profiles, - self.find_conn_id(connector_id)) - if index < 0: - conn_prof = RTC.ConnectorProfile("","",[],[]) - return conn_prof - - conn_prof = RTC.ConnectorProfile(self._profile.connector_profiles[index].name, - self._profile.connector_profiles[index].connector_id, - self._profile.connector_profiles[index].ports, - self._profile.connector_profiles[index].properties) - return conn_prof - - - ## - # @if jp - # - # @brief [CORBA interface] Port ³Ԥ - # - # Ϳ줿 ConnectoionProfile ξ˴ŤPort֤³Ω - # 롣δؿϼ˥ץꥱץġ뤫Ƥӽ - # ȤȤƤ롣 - # - # @pre ץꥱץϡݡͥȴ֤ʣ - # Port ³뤿ˡŬڤͤ򥻥åȤ ConnectorProfile - # connect() ΰȤͿƸƤӽФʤФʤʤ - # - # @pre connect() Ϳ ConnectorProfile ΥСΤ - # name, ports, properties СФƥǡ򥻥åȤʤ - # ʤʤconnector_id ˤ̾ʸꤹ뤫ŬUUID - # ʸꤹɬפ롣 - # - # @pre ConnectorProfile::name ³ˤĤ̾ CORBA::string - # ˳ǼǤǤդʸǤɬפ롣 - # - # @pre ConnectorProfile::connector_id Ϥ٤Ƥ³Фưդ - # ID (̾UUID) Ǽ롣UUID connect() ؿǹ - # ΤǡƤӽФ¦϶ʸꤹ롣¸³ƱUUID - # ꤷ connect() ƤӽФˤ PRECONDITION_NOT_MET 顼 - # ֤γĥǴ¸³ץե򹹿뤿 - # ˴¸ UUID ꤷƸƤӽФˡѤǽ롣 - # - # @pre ConnectorProfile::ports RTC::PortService Υ󥹤ǡ - # ³̾2İʾΥݡȤΥ֥ȻȤɬ - # פ롣㳰ȤơݡȤΥ֥ȻȤ1ĤǼ - # connect()ƤӽФȤǡݡȤΥ󥿡ե - # ꡢüʥݡ(CORBARTC::PortServiceʳ)Ф - # ³Ԥ⤢롣 - # - # @pre ConnectorProfile::properties ϥݡȤ˴Ϣդ줿󥿡 - # եФץѥƥͿ뤿˻Ѥ롣ץѥƥϡ - # string 򥭡Any ͤȤƤĥڥΥ󥹤Ǥꡢ - # ˤǤդCORBAǡǼǤ뤬ǽʸ¤ string Ȥ - # ƳǼ뤳Ȥ侩롣 - # - # @pre ʾ connect() ƤӽФꤹ ConnectorProfile Υ - # ФޤȤȰʲΤ褦ˤʤ롣 - # - # - ConnectorProfile::name: Ǥդ³̾ - # - ConnectorProfile::connector_id: ʸ - # - ConnectorProfile::ports: 1İʾΥݡ - # - ConnectorProfile::properties: 󥿡եФץѥƥ - # - # @post connect() ؿϡConnectorProfile::ports˳Ǽ줿ݡ - # ȥ󥹤ƬΥݡȤФ notify_connect() Ƥ֡ - # - # @post notify_connect() ConnectorProfile::ports ˳Ǽ줿ݡ - # Ƚ notify_connect() 򥫥ɸƤӽФ롣Υ - # ƤӽФϡnotify_connect() ǥ顼ФƤݡȤΥ - # ȻȤͭǤ¤ꡢɬ٤ƤΥݡȤФƹԤ - # Ȥݾڤ롣ͭǤʤ֥ȻȤ¸ - # 硢ΥݡȤ򥹥åפơΥݡȤФ - # notify_connect() ƤӽФ - # - # @post connect() ؿϡnotify_connect()ͤRTC_OKǤС - # RTC_OK ֤λ³ϴλ롣RTC_OKʳ - # ξϡ³IDФdisconnect()ƤӽФ³ - # notify_connect() ֤顼꥿󥳡ɤ򤽤Τޤ֤ - # - # @post connect() ΰȤϤ ConnectorProfile ˤϡ - # ConnectorProfile::connector_id ӡΥݡȤ - # publishInterfaces() Ǹݡȥ󥿡եγƼ - # ǼƤ롣connect() notify_connect() - # ConnectorProfile::{name, ports} ѹ뤳ȤϤʤ - # - # @param connector_profile ConnectorProfile - # @return ReturnCode_t Υ꥿󥳡 - # - # @else - # - # @brief [CORBA interface] Connect the Port - # - # This operation establishes connection according to the given - # ConnectionProfile inforamtion. This function is premised on - # calling from mainly application program or tools. - # - # @pre To establish the connection among Ports of RT-Components, - # application programs must call this operation giving - # ConnectorProfile with valid values as an argument. - # - # @pre Out of ConnectorProfile member variables, "name", "ports" - # and "properties" members shall be set valid - # data. "connector_id" shall be set as empty string value or - # valid string UUID value. - # - # @pre ConnectorProfile::name that is connection identifier shall - # be any valid CORBA::string. - # - # - # @pre ConnectorProfile::connector_id shall be set unique - # identifier (usually UUID is used) for all connections. Since - # UUID string value is usually set in the connect() function, - # caller should just set empty string. If the connect() is called - # with the same UUID as existing connection, this function - # returns PRECONDITION_NOT_MET error. However, in order to update - # the existing connection profile, the "connect()" operation with - # existing connector ID might be used as valid method by future - # extension - # - # @pre ConnectorProfile::ports, which is sequence of - # RTC::PortService references, shall store usually two or more - # ports' references. As exceptions, the "connect()" operation - # might be called with only one reference in ConnectorProfile, in - # case of just getting interfaces information from the port, or - # connecting a special port (i.e. the peer port except - # RTC::PortService on CORBA). - # - # @pre ConnectorProfile::properties might be used to give certain - # properties to the service interfaces associated with the port. - # The properties is a sequence variable with a pair of key string - # and Any type value. Although the A variable can store any type - # of values, it is not recommended except string. - # - # @pre The following is the summary of the ConnectorProfile - # member to be set when this operation is called. - # - # - ConnectorProfile::name: The any name of connection - # - ConnectorProfile::connector_id: Empty string - # - ConnectorProfile::ports: One or more port references - # - ConnectorProfile::properties: Properties for the interfaces - # - # @post connect() operation will call the first port in the - # sequence of the ConnectorProfile. - # - # @post "noify_connect()"s perform cascaded call to the ports - # stored in the ConnectorProfile::ports by order. Even if errors - # are raised by intermediate notify_connect() operation, as long - # as ports' object references are valid, it is guaranteed that - # this cascaded call is completed in all the ports. If invalid - # or dead ports exist in the port's sequence, the ports are - # skipped and notify_connect() is called for the next valid port. - # - # @post connect() function returns RTC_OK if all the - # notify_connect() return RTC_OK. At this time the connection is - # completed. If notify_connect()s return except RTC_OK, - # connect() calls disconnect() operation with the connector_id to - # destruct the connection, and then it returns error code from - # notify_connect(). - # - # @post The ConnectorProfile argument of the connect() operation - # returns ConnectorProfile::connector_id and various information - # about service interfaces that is published by - # publishInterfaces() in the halfway ports. The connect() and - # halfway notify_connect() functions never change - # ConnectorProfile::{name, ports}. - # - # @param connector_profile The ConnectorProfile. - # @return ReturnCode_t The return code of ReturnCode_t type. - # - # @endif - # - # virtual ReturnCode_t connect(ConnectorProfile& connector_profile) - def connect(self, connector_profile): - self._rtcout.RTC_TRACE("connect()") - if self.isEmptyId(connector_profile): - guard = OpenRTM_aist.ScopedLock(self._profile_mutex) - self.setUUID(connector_profile) - #assert(not self.isExistingConnId(connector_profile.connector_id)) - del guard - else: - guard = OpenRTM_aist.ScopedLock(self._profile_mutex) - if self.isExistingConnId(connector_profile.connector_id): - self._rtcout.RTC_ERROR("Connection already exists.") - return (RTC.PRECONDITION_NOT_MET,connector_profile) - del guard - - - try: - retval,connector_profile = connector_profile.ports[0].notify_connect(connector_profile) - if retval != RTC.RTC_OK: - self._rtcout.RTC_ERROR("Connection failed. cleanup.") - self.disconnect(connector_profile.connector_id) - - return (retval, connector_profile) - #return connector_profile.ports[0].notify_connect(connector_profile) - except: - self._rtcout.RTC_ERROR(OpenRTM_aist.Logger.print_exception()) - return (RTC.BAD_PARAMETER, connector_profile) - - - - - ## - # @if jp - # - # @brief [CORBA interface] Port ³ΤԤ - # - # Υڥ졼ϡPort֤³ԤݤˡPort֤Ū - # ˸ƤФ륪ڥ졼Ǥäơ̾異ץꥱץ - # 䡢PortʳRTCϢ֥ƤӽФ뤳Ȥꤵ - # Ƥʤ - # - # notify_connect() Τϥƥץ졼ȥ᥽åɥѥȤơ - # 饹Ǽ뤳Ȥ publishInterfaces(), - # subscribeInterfaces() 2ĤδؿǸƤӽФμ - # ʲ̤Ǥ롣 - # - # - publishInterfaces(): 󥿡եθ - # - connectNext(): Port notify_connect() θƤӽФ - # - subscribeInterfaces(): 󥿡եμ - # - ³¸ - # - # notify_connect() ConnectorProfile::ports ˳ǼƤ - # Port ν˽äơɾ˸ƤӽФԤȤˤꡢ - # 󥿡եθȼϢ٤ƤΥݡȤФƹԤ - # ΥɸƤӽФǤ뤳ȤϤʤɬ - # ConnectorProfile::ports ˳ǼƤݡȤФƹԤ롣 - # - # @pre notify_connect() ConnectorProfile::ports ˳Ǽ - # Port ȥꥹȤΤ Port ȤλȤμ˳Ǽ - # Port Ф notify_connect() ƤӽФä - # ConnectorProfile::ports ˤ Port λȤǼƤɬ - # 롣⤷ȤλȤǼƤʤ硢¾νˤ - # ꥨ顼񤭤ʤСBAD_PARAMETER 顼֤롣 - # - # @pre ƤӽФ ConnectorProfile::connector_id ˤϰդID - # UUID ݻƤɬפ롣̾ connector_id - # connect() ؿˤͿ졢ʸξư̤Ǥ롣 - # - # @post ConnectorProfile::name, ConnectorProfile::connector_id, - # ConnectorProfile::ports notify_connect() θƤӽФˤ - # 񤭴뤳ȤϤʤѤǤ롣 - # - # @post ConnectorProfile::properties notify_connect() ǡ - # Port ĥӥ󥿡ե˴ؤ¾ Port - # 뤿ˡץѥƥ󤬽񤭹ޤ롣 - # - # @post ʤConnectorProfile::ports ΥꥹȤκǽ Port - # notify_connet() λǤϡ٤ƤδϢ Port - # notify_connect() θƤӽФλ롣publishInterfaces(), - # connectNext(), subscribeInterfaces() ³¸Τ - # 줫ʳǥ顼ȯǤ⡢顼ɤŪݻ - # Ƥꡢǽ顼Υ顼ɤ֤롣 - # - # @param connector_profile ConnectorProfile - # @return ReturnCode_t Υ꥿󥳡 - # - # @else - # - # @brief [CORBA interface] Notify the Ports connection - # - # This operation is usually called from other ports' connect() or - # notify_connect() operations when connection between ports is - # established. This function is not premised on calling from - # other functions or application programs. - # - # According to the template method pattern, the notify_connect() - # calls "publishInterfaces()" and "subsctiveInterfaces()" - # functions, which are premised on implementing in the - # subclasses. The processing sequence is as follows. - # - # - publishInterfaces(): Publishing interface information - # - connectNext(): Calling notify_connect() of the next port - # - subscribeInterfaces(): Subscribing interface information - # - Storing connection profile - # - # According to the order of port's references stored in the - # ConnectorProfile::ports, publishing interface information to - # all the ports and subscription interface information from all - # the ports is performed by "notify_connect()"s. This cascaded - # call never aborts in the halfway operations, and calling - # sequence shall be completed for all the ports. - # - # @pre notify_connect() calls notify_connect() for the port's - # reference that is stored in next of this port's reference in - # the sequence of the ConnectorProfile::ports. Therefore the - # reference of this port shall be stored in the - # ConnectorProfile::ports. If this port's reference is not stored - # in the sequence, BAD_PARAMETER error will be returned, except - # the return code is overwritten by other operations. - # - # @pre UUID shall be set to ConnectorProfile::connector_id as a - # unique identifier when this operation is called. Usually, - # connector_id is given by a connect() function and, the behavior - # is undefined in the case of a null character. - # - # @post ConnectorProfile::name, ConnectorProfile::connector_id, - # ConnectorProfile::ports are invariant, and they are never - # rewritten by notify_connect() operations. - # - # @post In order to transfer interface information to other - # ports, interface property information is stored into the - # ConnectorProfile::properties. - # - # @post At the end of notify_connect() operation for the first - # port stored in the ConnectorProfile::ports sequence, the - # related ports' notify_connect() invocations complete. Even if - # errors are raised at the halfway of publishInterfaces(), - # connectNext(), subscribeInterfaces() and storing process of - # ConnectorProfile, error codes are saved and the first error is - # returned. - # - # @param connector_profile The ConnectorProfile. - # @return ReturnCode_t The return code of ReturnCode_t type. - # - # @endif - # - # virtual ReturnCode_t notify_connect(ConnectorProfile& connector_profile) - def notify_connect(self, connector_profile): - self._rtcout.RTC_TRACE("notify_connect()") - - prop = OpenRTM_aist.Properties() - OpenRTM_aist.NVUtil.copyToProperties(prop, connector_profile.properties) - - default_value = OpenRTM_aist.toBool(self._properties.getProperty("allow_dup_connection"), "YES","NO",False) - - if not OpenRTM_aist.toBool(prop.getProperty("dataport.allow_dup_connection"), "YES","NO",default_value): - for port in connector_profile.ports: - if not port._is_equivalent(self._objref): - ret = OpenRTM_aist.CORBA_RTCUtil.already_connected(port, self._objref) - if ret: - return (RTC.PRECONDITION_NOT_MET, connector_profile) - - - guard_connection = OpenRTM_aist.ScopedLock(self._connection_mutex) - - # publish owned interface information to the ConnectorProfile - retval = [RTC.RTC_OK for i in range(3)] - - self.onNotifyConnect(self.getName(),connector_profile) - retval[0] = self.publishInterfaces(connector_profile) - if retval[0] != RTC.RTC_OK: - self._rtcout.RTC_ERROR("publishInterfaces() in notify_connect() failed.") - - self.onPublishInterfaces(self.getName(), connector_profile, retval[0]) - if self._onPublishInterfaces: - self._onPublishInterfaces(connector_profile) - - # call notify_connect() of the next Port - retval[1], connector_profile = self.connectNext(connector_profile) - if retval[1] != RTC.RTC_OK: - self._rtcout.RTC_ERROR("connectNext() in notify_connect() failed.") - - self.onConnectNextport(self.getName(), connector_profile, retval[1]) - # subscribe interface from the ConnectorProfile's information - if self._onSubscribeInterfaces: - self._onSubscribeInterfaces(connector_profile) - - retval[2] = self.subscribeInterfaces(connector_profile) - if retval[2] != RTC.RTC_OK: - self._rtcout.RTC_ERROR("subscribeInterfaces() in notify_connect() failed.") - #self.notify_disconnect(connector_profile.connector_id) - - self.onSubscribeInterfaces(self.getName(), connector_profile, retval[2]) - - self._rtcout.RTC_PARANOID("%d connectors are existing", - len(self._profile.connector_profiles)) - - guard = OpenRTM_aist.ScopedLock(self._profile_mutex) - # update ConnectorProfile - index = self.findConnProfileIndex(connector_profile.connector_id) - if index < 0: - OpenRTM_aist.CORBA_SeqUtil.push_back(self._profile.connector_profiles, - connector_profile) - self._rtcout.RTC_PARANOID("New connector_id. Push backed.") - - else: - self._profile.connector_profiles[index] = connector_profile - self._rtcout.RTC_PARANOID("Existing connector_id. Updated.") - - for ret in retval: - if ret != RTC.RTC_OK: - self.onConnected(self.getName(), connector_profile, ret) - return (ret, connector_profile) - - # connection established without errors - if self._onConnected: - self._onConnected(connector_profile) - self.onConnected(self.getName(), connector_profile, RTC.RTC_OK) - return (RTC.RTC_OK, connector_profile) - - - ## - # @if jp - # - # @brief [CORBA interface] Port ³ - # - # Υڥ졼Ϳ줿 connector_id б³ - # 롣connector_id ̾ƥΤˤưդ UUID ʸ - # Ǥꡢ connect()/notify_connect() θƤӽФˤ - # Ω줿³ץե ConnectorProfile::connector_id б - # 롣 - # - # @pre connector_id Port ݻ ConnectorProfile ξʤ - # Ĥ ID ˰פʸǤʤФʤʤ Port - # ConnectorProfile Υꥹ connector_id Ʊ ID - # ConnectorProfile ¸ߤʤФδؿ BAD_PARAMETER 顼 - # ֤ - # - # @pre connector_id Ʊ ID ConnectorProfile::ports ˤ - # ͭ Port λȤޤޤƤʤФʤʤ - # - # @post disconnect() ؿϡConnectorProfile::ports Port λ - # ȥꥹȤƬФơnotify_disconnect() ƤӽФȤ̵ - # Ǥʤɡnotify_disconnect() θƤӽФ˼Ԥˤϡ - # ȥꥹȤƬ֤ޤ notify_disconnect() θ - # ӽФnotify_disconnect() θƤӽФ˰ĤǤС - # notify_disconnect() ֵͤ򤽤Τޤ֤Ĥʤä - # ˤ RTC_ERROR 顼֤ - # - # @param connector_id ConnectorProfile ID - # @return ReturnCode_t Υ꥿󥳡 - # - # @else - # - # @brief [CORBA interface] Disconnect the Port - # - # This operation destroys connection between this port and the - # peer port according to given connector_id. Usually connector_id - # should be a UUID string that is unique in the system. And the - # connection, which is established by connect()/notify_connect() - # functions, is identified by the ConnectorProfile::connector_id. - # - # @pre connector_id shall be a character string which is same - # with ID of at least one of the ConnectorProfiles stored in this - # port. If ConnectorProfile that has same ID with the given - # connector_id does not exist in the list of ConnectorProfile, - # this operation returns BAD_PARAMTER error. - # - # @pre ConnectorProfile::ports that is same ID with given - # connector_id shall store the valid ports' references. - # - # @post disconnect() function invokes the notify_disconnect() for - # the port that is stored in the first of the - # ConnectorProfile::ports. If notify_disconnect() call fails for - # the first port, It tries on calling "notify_disconnect()" in - # order for ports stored in ConnectorProfile::ports until the - # operation call is succeeded. If notify_disconnect() succeeded - # for at least one port, it returns return code from - # notify_disconnect(). If none of notify_connect() call - # succeeded, it returns RTC_ERROR error. - # - # @param connector_id The ID of the ConnectorProfile. - # @return ReturnCode_t The return code of ReturnCode_t type. - # - # @endif - # - # virtual ReturnCode_t disconnect(const char* connector_id) - def disconnect(self, connector_id): - self._rtcout.RTC_TRACE("disconnect(%s)", connector_id) - - index = self.findConnProfileIndex(connector_id) - - if index < 0: - self._rtcout.RTC_ERROR("Invalid connector id: %s", connector_id) - return RTC.BAD_PARAMETER - prof = None - guard = OpenRTM_aist.ScopedLock(self._profile_mutex) - if index < len(self._profile.connector_profiles): - prof = self._profile.connector_profiles[index] - del guard - - if len(prof.ports) < 1: - self._rtcout.RTC_FATAL("ConnectorProfile has empty port list.") - return RTC.PRECONDITION_NOT_MET - - for i in range(len(prof.ports)): - p = prof.ports[i] - try: - return p.notify_disconnect(connector_id) - except: - self._rtcout.RTC_WARN(OpenRTM_aist.Logger.print_exception()) - continue - - self._rtcout.RTC_ERROR("notify_disconnect() for all ports failed.") - return RTC.RTC_ERROR - - - ## - # @if jp - # - # @brief [CORBA interface] Port ³ΤԤ - # - # Υڥ졼ϡPort֤³ԤݤˡPort֤ - # Ū˸ƤФ륪ڥ졼Ǥꡢ̾異ץꥱץ - # 䡢 Port ʳ RTC Ϣ֥ƤӽФ뤳Ȥ - # ꤵƤʤ - # - # notify_disconnect() Τϥƥץ졼ȥ᥽åɥѥȤơ - # ֥饹Ǽ뤳Ȥ unsubscribeInterfaces() ؿ - # ǸƤӽФμϰʲ̤Ǥ롣 - # - # - ConnectorProfile θ - # - Port notify_disconnect() ƤӽФ - # - unsubscribeInterfaces() - # - ConnectorProfile κ - # - # notify_disconnect() ConnectorProfile::ports ˳ǼƤ - # Port ν˽äơɾ˸ƤӽФԤȤˤꡢ - # ³β򤹤٤Ƥ Port Τ롣 - # - # @pre Port Ϳ줿 connector_id б ConnectorProfile - # ݻƤʤФʤʤ - # - # @post connector_id б ConnectorProfile Ĥʤ - # BAD_PARAMETER 顼֤ - # - # @post ɸƤӽФԤݤˤ ConnectorProfile::ports - # ݻƤ Port λȥꥹȤΤȤλȤμλȤ - # notify_disconnect() ƤӽФθƤӽФ㳰ȯ - # ˤϡƤӽФ򥹥åפꥹȤμλȤФ - # notify_disconnect() ƤӽФĤƤӽФʤ硢 - # RTC_ERROR 顼ɤ֤ - # - # @post ʤConnectorProfile::ports ΥꥹȤκǽ Port - # notify_disconnet() λǤϡ٤ƤδϢ Port - # notify_disconnect() θƤӽФλ롣 - # - # @param connector_id ConnectorProfile ID - # @return ReturnCode_t Υ꥿󥳡 - # - # @else - # - # @brief [CORBA interface] Notify the Ports disconnection - # - # This operation is invoked between Ports internally when the - # connection is destroied. Generally it is not premised on - # calling from application programs or RTC objects except Port - # object. - # - # According to the template method pattern, the - # notify_disconnect() calls unsubsctiveInterfaces() function, - # which are premised on implementing in the subclasses. The - # processing sequence is as follows. - # - # - Searching ConnectorProfile - # - Calling notify_disconnect() for the next port - # - Unsubscribing interfaces - # - Deleting ConnectorProfile - # - # notify_disconnect() notifies disconnection to all the ports by - # cascaded call to the stored ports in the - # ConnectorProfile::ports in order. - # - # @pre The port shall store the ConnectorProfile having same id - # with connector_id. - # - # @post If ConnectorProfile of same ID with connector_id does not - # exist, it returns BAD_PARAMETER error. - # - # @post For the cascaded call, this operation calls - # noify_disconnect() for the port that is stored in the next of - # this port in the ConnectorProfile::ports. If the operation - # call raises exception for some failure, it tries to call - # notify_disconnect() and skips until the operation succeeded. - # If none of operation call succeeded, it returns RTC_ERROR. - # - # @post At the end of notify_disconnect() operation for the first - # port stored in the ConnectorProfile::ports sequence, the - # related ports' notify_disconnect() invocations complete. - # - # @param connector_id The ID of the ConnectorProfile. - # @return ReturnCode_t The return code of ReturnCode_t type. - # - # @endif - # - # virtual ReturnCode_t notify_disconnect(const char* connector_id) - def notify_disconnect(self, connector_id): - self._rtcout.RTC_TRACE("notify_disconnect(%s)", connector_id) - - guard_connection = OpenRTM_aist.ScopedLock(self._connection_mutex) - # The Port of which the reference is stored in the beginning of - # connectorProfile's PortServiceList is master Port. - # The master Port has the responsibility of disconnecting all Ports. - # The slave Ports have only responsibility of deleting its own - # ConnectorProfile. - - guard = OpenRTM_aist.ScopedLock(self._profile_mutex) - - index = self.findConnProfileIndex(connector_id) - - if index < 0: - self._rtcout.RTC_ERROR("Invalid connector id: %s", connector_id) - return RTC.BAD_PARAMETER - - prof = RTC.ConnectorProfile(self._profile.connector_profiles[index].name, - self._profile.connector_profiles[index].connector_id, - self._profile.connector_profiles[index].ports, - self._profile.connector_profiles[index].properties) - self.onNotifyDisconnect(self.getName(), prof) - - retval = self.disconnectNext(prof) - self.onDisconnectNextport(self.getName(), prof, retval) - - if self._onUnsubscribeInterfaces: - self._onUnsubscribeInterfaces(prof) - self.onUnsubscribeInterfaces(self.getName(), prof) - self.unsubscribeInterfaces(prof) - - if self._onDisconnected: - self._onDisconnected(prof) - - OpenRTM_aist.CORBA_SeqUtil.erase(self._profile.connector_profiles, index) - - self.onDisconnected(self.getName(), prof, retval) - return retval - - - ## - # @if jp - # - # @brief [CORBA interface] Port ³ - # - # Υڥ졼Ϥ Port ˴ϢƤ³롣 - # - # @param self - # - # @return ReturnCode_t Υ꥿󥳡 - # - # @else - # - # @brief [CORBA interface] Connect the Port - # - # This operation destroys all connection channels owned by the Port. - # - # @return ReturnCode_t The return code of this operation. - # - # @endif - # virtual ReturnCode_t disconnect_all() - def disconnect_all(self): - self._rtcout.RTC_TRACE("disconnect_all()") - guard = OpenRTM_aist.ScopedLock(self._profile_mutex) - plist = copy.deepcopy(self._profile.connector_profiles) - del guard - - retcode = RTC.RTC_OK - len_ = len(plist) - self._rtcout.RTC_DEBUG("disconnecting %d connections.", len_) - - # disconnect all connections - # Call disconnect() for each ConnectorProfile. - for i in range(len_): - tmpret = self.disconnect(plist[i].connector_id) - if tmpret != RTC.RTC_OK: - retcode = tmpret - - return retcode - - - #============================================================ - # Local operations - #============================================================ - - ## - # @if jp - # @brief Port ̾ꤹ - # - # Port ̾ꤹ롣̾ Port ݻ PortProfile.name - # ȿǤ롣 - # - # @param self - # @param name Port ̾ - # - # @else - # @brief Set the name of this Port - # - # This operation sets the name of this Port. The given Port's name is - # applied to Port's PortProfile.name. - # - # @param name The name of this Port. - # - # @endif - # void setName(const char* name); - def setName(self, name): - self._rtcout.RTC_TRACE("setName(%s)", name) - guard = OpenRTM_aist.ScopedLock(self._profile_mutex) - self._profile.name = name - return - - ## - # @if jp - # @brief Port ̾ - # @else - # @brief Get the name of this Port - # @return The name of this Port. - # @endif - # - # const char* PortBase::getName() const - def getName(self): - self._rtcout.RTC_TRACE("getName() = %s", self._profile.name) - return self._profile.name - - - ## - # @if jp - # @brief PortProfile - # - # Portݻ PortProfile const Ȥ֤ - # - # @param self - # - # @return Port PortProfile - # - # @else - # @brief Get the PortProfile of the Port - # - # This operation returns const reference of the PortProfile. - # - # @return the PortProfile of the Port - # - # @endif - # const PortProfile& getProfile() const; - def getProfile(self): - self._rtcout.RTC_TRACE("getProfile()") - guard = OpenRTM_aist.ScopedLock(self._profile_mutex) - return self._profile - - - ## - # @if jp - # - # @brief Port Υ֥ȻȤꤹ - # - # Υڥ졼 Port PortProfile ˤ Port Ȥ - # ֥ȻȤꤹ롣 - # - # @param self - # @param port_ref Port Υ֥Ȼ - # - # @else - # - # @brief Set the object reference of this Port - # - # This operation sets the object reference itself - # to the Port's PortProfile. - # - # @param The object reference of this Port. - # - # @endif - # void setPortRef(PortService_ptr port_ref); - def setPortRef(self, port_ref): - self._rtcout.RTC_TRACE("setPortRef()") - guard = OpenRTM_aist.ScopedLock(self._profile_mutex) - self._profile.port_ref = port_ref - - - ## - # @if jp - # - # @brief Port Υ֥ȻȤ - # - # Υڥ졼 Port PortProfile ݻƤ - # Port ȤΥ֥ȻȤ롣 - # - # @param self - # - # @return Port Υ֥Ȼ - # - # @else - # - # @brief Get the object reference of this Port - # - # This operation returns the object reference - # that is stored in the Port's PortProfile. - # - # @return The object reference of this Port. - # - # @endif - # PortService_ptr getPortRef(); - def getPortRef(self): - self._rtcout.RTC_TRACE("getPortRef()") - guard = OpenRTM_aist.ScopedLock(self._profile_mutex) - return self._profile.port_ref - - - ## - # @if jp - # - # @brief Port owner RTObject ꤹ - # - # Υڥ졼 Port PortProfile.owner ꤹ롣 - # - # @param self - # @param owner Port ͭ RTObject λ - # - # @else - # - # @brief Set the owner RTObject of the Port - # - # This operation sets the owner RTObject of this Port. - # - # @param owner The owner RTObject's reference of this Port - # - # @endif - # void setOwner(RTObject_ptr owner); - def setOwner(self, owner): - prof = owner.get_component_profile() - self._ownerInstanceName = prof.instance_name - self._rtcout.RTC_TRACE("setOwner(%s)", self._ownerInstanceName) - - guard = OpenRTM_aist.ScopedLock(self._profile_mutex) - plist = self._profile.name.split(".") - if not self._ownerInstanceName: - self._rtcout.RTC_ERROR("Owner is not set.") - self._rtcout.RTC_ERROR("addXXXPort() should be called in onInitialize().") - portname = self._ownerInstanceName+"."+plist[-1] - - self._profile.owner = owner - self._profile.name = portname - - - #============================================================ - # callbacks - #============================================================ - - ## - # @if jp - # - # @brief 󥿡եݤ˸ƤФ륳Хå򥻥åȤ - # - # Υڥ졼ϡΥݡȤ³ˡݡȼȤĥ - # ӥ󥿡ե륿ߥ󥰤ǸƤФ륳Х - # ե󥯥򥻥åȤ롣 - # - # Хåե󥯥νͭϡƤӽФ¦ˤꡢ֥ - # ɬפʤʤä˲ΤΤϸƤӽФ¦ǤǤ롣 - # - # ΥХåե󥯥ϡPortBase饹β۴ؿǤ - # publishInterfaces() ƤФ줿ȤˡƱ ConnectorProfile - # Ȥ˸ƤӽФ롣ΥХåѤơ - # publishInterfaces() ConnectorProfile ѹ뤳Ȥ - # ǽǤ뤬³ط򾷤ʤ褦ConnectorProfile - # ѹˤդפ롣 - # - # @param on_publish ConnectionCallback Υ֥饹֥ȤΥݥ - # - # @else - # - # @brief Setting callback called on publish interfaces - # - # This operation sets a functor that is called after publishing - # interfaces process when connecting between ports. - # - # Since the ownership of the callback functor object is owned by - # the caller, it has the responsibility of object destruction. - # - # The callback functor is called after calling - # publishInterfaces() that is virtual member function of the - # PortBase class with an argument of ConnectorProfile type that - # is same as the argument of publishInterfaces() function. - # Although by using this functor, you can modify the ConnectorProfile - # published by publishInterfaces() function, the modification - # should be done carefully for fear of causing connection - # inconsistency. - # - # @param on_publish a pointer to ConnectionCallback's subclasses - # - # @endif - # - # void setOnPublishInterfaces(ConnectionCallback* on_publish); - def setOnPublishInterfaces(self, on_publish): - self._onPublishInterfaces = on_publish - return - - - ## - # @if jp - # - # @brief 󥿡եݤ˸ƤФ륳Хå򥻥åȤ - # - # Υڥ졼ϡΥݡȤ³ˡΥݡȤĥ - # ӥ󥿡ե륿ߥ󥰤ǸƤФ륳Х - # ե󥯥򥻥åȤ롣 - # - # Хåե󥯥νͭϡƤӽФ¦ˤꡢ֥ - # ɬפʤʤä˲ΤΤϸƤӽФ¦ǤǤ롣 - # - # ΥХåե󥯥ϡPortBase饹β۴ؿǤ - # subscribeInterfaces() ƤФˡƱ ConnectorProfile - # Ȥ˸ƤӽФ롣ΥХåѤơ - # subscribeInterfaces() Ϳ ConnectorProfile ѹ뤳Ȥ - # ǽǤ뤬³ط򾷤ʤ褦ConnectorProfile - # ѹˤդפ롣 - # - # @param on_subscribe ConnectionCallback Υ֥饹֥ȤΥݥ - # - # @else - # - # @brief Setting callback called on publish interfaces - # - # This operation sets a functor that is called before subscribing - # interfaces process when connecting between ports. - # - # Since the ownership of the callback functor object is owned by - # the caller, it has the responsibility of object destruction. - # - # The callback functor is called before calling - # subscribeInterfaces() that is virtual member function of the - # PortBase class with an argument of ConnectorProfile type that - # is same as the argument of subscribeInterfaces() function. - # Although by using this functor, you can modify ConnectorProfile - # argument for subscribeInterfaces() function, the modification - # should be done carefully for fear of causing connection - # inconsistency. - # - # @param on_subscribe a pointer to ConnectionCallback's subclasses - # - # @endif - # - #void setOnSubscribeInterfaces(ConnectionCallback* on_subscribe); - def setOnSubscribeInterfaces(self, on_subscribe): - self._onSubscribeInterfaces = on_subscribe - return - - - ## - # @if jp - # - # @brief ³λ˸ƤФ륳Хå򥻥åȤ - # - # Υڥ졼ϡΥݡȤ³λ˸ƤФ롢Х - # ե󥯥򥻥åȤ롣 - # - # Хåե󥯥νͭϡƤӽФ¦ˤꡢ֥ - # ɬפʤʤä˲ΤΤϸƤӽФ¦ǤǤ롣 - # - # ΥХåե󥯥ϡݡȤ³¹ԴؿǤ - # notify_connect() νλľˡ³ェλݤ˸¤ä - # ƤӽФ륳ХåǤ롣³βǥ顼ȯ - # ˤϸƤӽФʤ - # - # ΥХåե󥯥 notify_connect() out ѥ᡼ - # Ȥ֤ΤƱ ConnectorProfile ȤȤ˸ƤӽФΤǡ - # ³ˤƸ줿٤ƤΥ󥿡ե뤳 - # Ǥ롣ΥХåѤơnotify_connect() ֤ - # ConnectorProfile ѹ뤳ȤǽǤ뤬³ط - # 򾷤ʤ褦ConnectorProfile ѹˤդפ롣 - # - # @param on_subscribe ConnectionCallback Υ֥饹֥ȤΥݥ - # - # @else - # - # @brief Setting callback called on connection established - # - # This operation sets a functor that is called when connection - # between ports established. - # - # Since the ownership of the callback functor object is owned by - # the caller, it has the responsibility of object destruction. - # - # The callback functor is called only when notify_connect() - # function successfully returns. In case of error, the functor - # will not be called. - # - # Since this functor is called with ConnectorProfile argument - # that is same as out-parameter of notify_connect() function, you - # can get all the information of published interfaces of related - # ports in the connection. Although by using this functor, you - # can modify ConnectorProfile argument for out-paramter of - # notify_connect(), the modification should be done carefully for - # fear of causing connection inconsistency. - # - # @param on_subscribe a pointer to ConnectionCallback's subclasses - # - # @endif - # - # void setOnConnected(ConnectionCallback* on_connected); - def setOnConnected(self, on_connected): - self._onConnected = on_connected - return - - - ## - # @if jp - # - # @brief 󥿡եݤ˸ƤФ륳Хå򥻥åȤ - # - # Υڥ졼ϡΥݡȤ³ˡΥݡȤĥ - # ӥ󥿡ե륿ߥ󥰤ǸƤФ륳Х - # ե󥯥򥻥åȤ롣 - # - # Хåե󥯥νͭϡƤӽФ¦ˤꡢ֥ - # ɬפʤʤä˲ΤΤϸƤӽФ¦ǤǤ롣 - # - # ΥХåե󥯥ϡPortBase饹β۴ؿǤ - # unsubscribeInterfaces() ƤФˡƱ ConnectorProfile - # Ȥ˸ƤӽФ롣ΥХåѤơ - # unsubscribeInterfaces() Ϳ ConnectorProfile ѹ뤳Ȥ - # ǽǤ뤬³ط򾷤ʤ褦ConnectorProfile - # ѹˤդפ롣 - # - # @param on_unsubscribe ConnectionCallback Υ֥饹֥ - # ȤΥݥ - # - # @else - # - # @brief Setting callback called on unsubscribe interfaces - # - # This operation sets a functor that is called before unsubscribing - # interfaces process when disconnecting between ports. - # - # Since the ownership of the callback functor object is owned by - # the caller, it has the responsibility of object destruction. - # - # The callback functor is called before calling - # unsubscribeInterfaces() that is virtual member function of the - # PortBase class with an argument of ConnectorProfile type that - # is same as the argument of unsubscribeInterfaces() function. - # Although by using this functor, you can modify ConnectorProfile - # argument for unsubscribeInterfaces() function, the modification - # should be done carefully for fear of causing connection - # inconsistency. - # - # @param on_unsubscribe a pointer to ConnectionCallback's subclasses - # - # @endif - # - # void setOnUnsubscribeInterfaces(ConnectionCallback* on_subscribe); - def setOnUnsubscribeInterfaces(self, on_subscribe): - self._onUnsubscribeInterfaces = on_subscribe - return - - - ## - # @if jp - # - # @brief ³˸ƤФ륳Хå򥻥åȤ - # - # Υڥ졼ϡΥݡȤ³˸ƤФ롢Х - # ե󥯥򥻥åȤ롣 - # - # Хåե󥯥νͭϡƤӽФ¦ˤꡢ֥ - # ɬפʤʤä˲ΤΤϸƤӽФ¦ǤǤ롣 - # - # ΥХåե󥯥ϡݡȤ³¹ԴؿǤ - # notify_disconnect() νλľˡƤӽФ륳ХåǤ롣 - # - # ΥХåե󥯥³б ConnectorProfile Ȥ - # ˸ƤӽФ롣 ConnectorProfile ϤΥե󥯥ƽФ - # ˴Τǡѹۤ˱ƶͿ뤳ȤϤʤ - # - # @param on_disconnected ConnectionCallback Υ֥饹֥ - # ȤΥݥ - # - # @else - # - # @brief Setting callback called on disconnected - # - # This operation sets a functor that is called when connection - # between ports is destructed. - # - # Since the ownership of the callback functor object is owned by - # the caller, it has the responsibility of object destruction. - # - # The callback functor is called just before notify_disconnect() - # that is disconnection execution function returns. - # - # This functor is called with argument of corresponding - # ConnectorProfile. Since this ConnectorProfile will be - # destructed after calling this functor, modifications never - # affect others. - # - # @param on_disconnected a pointer to ConnectionCallback's subclasses - # - # @endif - # - # void setOnDisconnected(ConnectionCallback* on_disconnected); - def setOnDisconnected(self, on_disconnected): - self._onDisconnected = on_disconnected - return - - # void setOnConnectionLost(ConnectionCallback* on_connection_lost); - def setOnConnectionLost(self, on_connection_lost): - self._onConnectionLost = on_connection_lost - return - - - ## - # @if jp - # @brief PortConnectListeners Υۥ򥻥åȤ - # - # ݡȤ³˴ؤꥹʷݻۥ饹ؤΥݥ󥿤 - # åȤ롣δؿ̾ƤRTObjectƤФ졢RTObject - # ۥ饹ؤΥݥ󥿤åȤ롣 - # - # @param portconnListeners PortConnectListeners ֥ȤΥݥ - # - # @else - # @brief Setting PortConnectListener holder - # - # This operation sets a functor that is called when connection - # of this port does lost. - # - # @param on_connection_lost a pointer to ConnectionCallback's subclasses - # - # @endif - # - # void setPortConnectListenerHolder(PortConnectListeners* portconnListeners); - def setPortConnectListenerHolder(self, portconnListeners): - self._portconnListeners = portconnListeners - return - - - ## - # @if jp - # - # @brief Interface (֥饹) - # - # Υڥ졼ϡnotify_connect() 󥹤λϤ˥ - # ؿǤ롣 - # notify_connect() Ǥϡ - # - # - publishInterfaces() - # - connectNext() - # - subscribeInterfaces() - # - updateConnectorProfile() - # - # ν protected ؿ뤵³Ԥ롣 - #
    - # Port ǤϤΥڥ졼򥪡С饤ɤȤ - # Ϳ줿 ConnectorProfile ˽Ԥѥ᡼Ŭ - # ǤСRteurnCode_t Υ顼ɤ֤ - # ̾ publishInterafaces() ˤƤϡ Port ° - # 󥿡ե˴ؤ ConnectorProfile ФŬڤꤷ - # ¾ Port ΤʤФʤʤ - #
    - # ޤδؿ뤵ʳǤϡ¾ Port Interface ˴ؤ - # Ϥ٤ƴޤޤƤʤΤǡ¾ Port Interface - # subscribeInterfaces() ǹԤ٤Ǥ롣 - #
    - # Υڥ졼ϡ connector_id ФƤ³ - # ¸ connector_id ФƤϹŬڤ˹Ԥɬפ롣
    - # ֥饹Ǥμ - # - # @param self - # @param connector_profile ³˴ؤץե - # - # @return ReturnCode_t Υ꥿󥳡 - # - # @else - # - # @brief Publish interface information - # - # This operation is pure virutal method that would be called at the - # beginning of the notify_connect() process sequence. - # In the notify_connect(), the following methods would be called in order. - # - # - publishInterfaces() - # - connectNext() - # - subscribeInterfaces() - # - updateConnectorProfile() - # - # In the concrete Port, this method should be overridden. This method - # processes the given ConnectorProfile argument and if the given parameter - # is invalid, it would return error code of ReturnCode_t. - # Usually, publishInterfaces() method should set interfaces information - # owned by this Port, and publish it to the other Ports. - #
    - # When this method is called, other Ports' interfaces information may not - # be completed. Therefore, the process to obtain other Port's interfaces - # information should be done in the subscribeInterfaces() method. - #
    - # This operation should create the new connection for the new - # connector_id, and should update the connection for the existing - # connection_id. - # - # @param connector_profile The connection profile information - # @return The return code of ReturnCode_t type. - # - #@endif - def publishInterfaces(self, connector_profile): - return RTC.BAD_PARAMETER - - - ## - # @if jp - # - # @brief Port Ф notify_connect() 򥳡뤹 - # - # ConnectorProfile port_ref ˳ǼƤ Port Υ֥ - # ե󥹤Υ󥹤椫顢Ȥ Port μ Port Ф - # notify_connect() 򥳡뤹롣 - # - # @param self - # @param connector_profile ³˴ؤץե - # - # @return ReturnCode_t Υ꥿󥳡 - # - # @else - # - # @brief Call notify_connect() of the next Port - # - # This operation calls the notify_connect() of the next Port's - # that stored in ConnectorProfile's port_ref sequence. - # - # @param connector_profile The connection profile information - # - # @return The return code of ReturnCode_t type. - # - # @endif - # virtual ReturnCode_t connectNext(ConnectorProfile& connector_profile); - def connectNext(self, connector_profile): - index = OpenRTM_aist.CORBA_SeqUtil.find(connector_profile.ports, - self.find_port_ref(self._profile.port_ref)) - if index < 0: - return (RTC.BAD_PARAMETER, connector_profile) - - index += 1 - if index < len(connector_profile.ports): - p = connector_profile.ports[index] - return p.notify_connect(connector_profile) - - return (RTC.RTC_OK, connector_profile) - - - ## - # @if jp - # - # @brief Port Ф notify_disconnect() 򥳡뤹 - # - # ConnectorProfile port_ref ˳ǼƤ Port Υ֥ - # ե󥹤Υ󥹤椫顢Ȥ Port μ Port Ф - # notify_disconnect() 򥳡뤹롣 - # - # @param self - # @param connector_profile ³˴ؤץե - # - # @return ReturnCode_t Υ꥿󥳡 - # - # @else - # - # @brief Call notify_disconnect() of the next Port - # - # This operation calls the notify_disconnect() of the next Port's - # that stored in ConnectorProfile's port_ref sequence. - # - # @param connector_profile The connection profile information - # - # @return The return code of ReturnCode_t type. - # - # @endif - # virtual ReturnCode_t disconnectNext(ConnectorProfile& connector_profile); - def disconnectNext(self, connector_profile): - - index = OpenRTM_aist.CORBA_SeqUtil.find(connector_profile.ports, - self.find_port_ref(self._profile.port_ref)) - if index < 0: - return RTC.BAD_PARAMETER - - if index == (len(connector_profile.ports) - 1): - return RTC.RTC_OK - - index += 1 - - while index < len(connector_profile.ports): - p = connector_profile.ports[index] - index += 1 - try: - return p.notify_disconnect(connector_profile.connector_id) - except: - self._rtcout.RTC_WARN(OpenRTM_aist.Logger.print_exception()) - continue - - return RTC.RTC_ERROR - - - ## - # @if jp - # - # @brief Interface (֥饹) - # - # Υڥ졼ϡnotify_connect() 󥹤֤˥ - # ؿǤ롣 - # notify_connect() Ǥϡ - # - # - publishInterfaces() - # - connectNext() - # - subscribeInterfaces() - # - updateConnectorProfile() - # - # ν protected ؿ뤵³Ԥ롣 - #
    - # Port ǤϤΥڥ졼򥪡С饤ɤȤ - # Ϳ줿 ConnectorProfile ˽Ԥѥ᡼Ŭ - # ǤСRteurnCode_t Υ顼ɤ֤ - # ConnectorProfile ˤ¾ Port Interface ˴ؤ - # ƴޤޤƤ롣 - # ̾ subscribeInterafaces() ˤƤϡ Port Ѥ - # Interface ˴ؤ׵¦Υ󥿡եФ - # ꤷʤФʤʤ - #
    - # Υڥ졼ϡ connector_id ФƤ³ - # ¸ connector_id ФƤϹŬڤ˹Ԥɬפ롣
    - # ֥饹Ǥμ - # - # @param self - # @param connector_profile ³˴ؤץե - # - # @return ReturnCode_t Υ꥿󥳡 - # - # @else - # - # @brief Publish interface information - # - # This operation is pure virutal method that would be called at the - # mid-flow of the notify_connect() process sequence. - # In the notify_connect(), the following methods would be called in order. - # - # - publishInterfaces() - # - connectNext() - # - subscribeInterfaces() - # - updateConnectorProfile() - # - # In the concrete Port, this method should be overridden. This method - # processes the given ConnectorProfile argument and if the given parameter - # is invalid, it would return error code of ReturnCode_t. - # The given argument ConnectorProfile includes all the interfaces - # information in it. - # Usually, subscribeInterafaces() method obtains information of interfaces - # from ConnectorProfile, and should set it to the interfaces that require - # them. - #
    - # This operation should create the new connection for the new - # connector_id, and should update the connection for the existing - # connection_id. - # - # @param connector_profile The connection profile information - # - # @return The return code of ReturnCode_t type. - # - #@endif - def subscribeInterfaces(self, connector_profile): - pass - - - ## - # @if jp - # - # @brief Interface ³(֥饹) - # - # Υڥ졼ϡnotify_disconnect() 󥹤ν˥ - # ؿǤ롣 - # notify_disconnect() Ǥϡ - # - disconnectNext() - # - unsubscribeInterfaces() - # - eraseConnectorProfile() - # ν protected ؿ뤵³Ԥ롣 - #
    - # Port ǤϤΥڥ졼򥪡С饤ɤȤ - # Ϳ줿 ConnectorProfile ˽³Ԥ
    - # ֥饹Ǥμ - # - # @param self - # @param connector_profile ³˴ؤץե - # - # @else - # - # @brief Disconnect interface connection - # - # This operation is pure virutal method that would be called at the - # end of the notify_disconnect() process sequence. - # In the notify_disconnect(), the following methods would be called. - # - disconnectNext() - # - unsubscribeInterfaces() - # - eraseConnectorProfile() - #
    - # In the concrete Port, this method should be overridden. This method - # processes the given ConnectorProfile argument and disconnect interface - # connection. - # - # @param connector_profile The connection profile information - # - # @endif - def unsubscribeInterfaces(self, connector_profile): - return RTC.BAD_PARAMETER - - - ## - # @if jp - # - # @brief ³κꤹ롣 - # - # @param limit_value - # - # @else - # - # @brief Set the maximum number of connections - # - # - # @param limit_value The maximum number of connections - # - # @endif - # - # virtual void setConnectionLimit(int limit_value); - def setConnectionLimit(self, limit_value): - self._connectionLimit = limit_value - return - - - ## - # @if jp - # @brief Interface - # - # Interface롣 - # - # dataport.dataflow_type - # - # @return ReturnCode_t Υ꥿󥳡 - # - # @else - # @brief Publish interface information - # - # Publish interface information. - # - # - # @return The return code of ReturnCode_t type - # - # @endif - # - # virtual ReturnCode_t _publishInterfaces(void); - def _publishInterfaces(self): - if not (self._connectionLimit < 0) : - if self._connectionLimit <= len(self._profile.connector_profiles): - self._rtcout.RTC_PARANOID("Connected number has reached the limitation.") - self._rtcout.RTC_PARANOID("Can connect the port up to %d ports.", - self._connectionLimit) + """ + """ + + ## + # @if jp + # @brief コンストラクタ + # + # PortBase のコンストラクタは Port 名 name を引数に取り初期化を行う + # と同時に、自分自身を CORBA Object として活性化し、自身の PortProfile + # の port_ref に自身のオブジェクトリファレンスを格納する。 + # 名前には、"." 以外の文字列を使用することができる。 + # + # @param self + # @param name Port の名前(デフォルト値:None) + # + # @else + # + # @brief Constructor + # + # The constructor of the ProtBase class is given the name of this Port + # and initialized. At the same time, the PortBase activates itself + # as CORBA object and stores its object reference to the PortProfile's + # port_ref member. + # Characters except "." can be used for the name of the port. + # + # @param name The name of Port + # + # @endif + def __init__(self, name=None): + self._ownerInstanceName = "unknown" + self._objref = self._this() + + self._profile = RTC.PortProfile( + "", [], RTC.PortService._nil, [], RTC.RTObject._nil, []) + # Now Port name is .. r1648 + if name is None: + self._profile.name = "unknown.unknown" + else: + self._profile.name = self._ownerInstanceName + "." + name + + self._profile.port_ref = self._objref + self._profile.owner = RTC.RTObject._nil + self._profile_mutex = threading.RLock() + self._connection_mutex = threading.RLock() + self._rtcout = OpenRTM_aist.Manager.instance().getLogbuf(name) + self._onPublishInterfaces = None + self._onSubscribeInterfaces = None + self._onConnected = None + self._onUnsubscribeInterfaces = None + self._onDisconnected = None + self._onConnectionLost = None + self._connectionLimit = -1 + self._portconnListeners = None + self._properties = OpenRTM_aist.Properties() + return + + ## + # @if jp + # + # @brief デストラクタ + # + # デストラクタでは、PortService CORBA オブジェクトの deactivate を + # 行う。deactivateに際して例外を投げることはない。 + # + # @else + # + # @brief Destructor + # + # In the destructor, PortService CORBA object is deactivated. + # This function never throws exception. + # + # @endif + # + + def __del__(self): + pass + + ## + # @if jp + # + # @brief 終了関数 + # + # @param self + # + # @else + # + # @brief + # + # @param self + # + # @endif + # + + def exit(self): + self._rtcout.RTC_TRACE("PortBase.__del__()") + # try: + # poa = OpenRTM_aist.Manager.instance().getPOA() + # oid = poa.servant_to_id(self) + # poa.deactivate_object(oid) + # except: + # self._rtcout.RTC_ERROR(OpenRTM_aist.Logger.print_exception()) + + ## + # @if jp + # + # @brief [CORBA interface] PortProfileを取得する + # + # Portが保持するPortProfileを返す。 + # PortProfile 構造体は以下のメンバーを持つ。 + # + # - name [string 型] Port の名前。 + # - interfaces [PortInterfaceProfileList 型] Port が保持する + # PortInterfaceProfile のシーケンス + # - port_ref [Port Object 型] Port 自身のオブジェクトリファレンス + # - connector_profile [ConnectorProfileList 型] Port が現在保持する + # ConnectorProfile のシーケンス + # - owner [RTObject Object 型] この Port を所有する + # RTObjectのリファレンス + # - properties [NVList 型] その他のプロパティ。 + # + # @param self + # + # @return PortProfile + # + # @else + # + # @brief [CORBA interface] Get the PortProfile of the Port + # + # This operation returns the PortProfile of the Port. + # PortProfile struct has the following members, + # + # - name [string ] The name of the Port. + # - interfaces [PortInterfaceProfileList] The sequence of + # PortInterfaceProfile owned by the Port + # - port_ref [Port Object] The object reference of the Port. + # - connector_profile [ConnectorProfileList] The sequence of + # ConnectorProfile owned by the Port. + # - owner [RTObject Object] The object reference of + # RTObject that is owner of the Port. + # - properties [NVList] The other properties. + # + # @return the PortProfile of the Port + # + # @endif + # PortProfile* get_port_profile() + def get_port_profile(self): + self._rtcout.RTC_TRACE("get_port_profile()") + + self.updateConnectors() + + guard = OpenRTM_aist.ScopedLock(self._profile_mutex) + + prof = RTC.PortProfile(self._profile.name, + self._profile.interfaces, + self._profile.port_ref, + self._profile.connector_profiles, + self._profile.owner, + self._profile.properties) + + return prof + + ## + # @if jp + # + # @brief PortProfile を取得する。 + # + # この関数は、オブジェクト内部に保持されている PortProfile の + # const 参照を返す const 関数である。 + # + # @post この関数を呼び出すことにより内部状態が変更されることはない。 + # + # @return PortProfile + # + # @else + # + # @brief Get the PortProfile of the Port + # + # This function is a const function that returns a const + # reference of the PortProfile stored in this Port. + # + # @post This function never changes the state of the object. + # + # @return PortProfile + # + # @endif + # PortProfile& getPortProfile() const; + + def getPortProfile(self): + self._rtcout.RTC_TRACE("getPortProfile()") + return self._profile + + ## + # @if jp + # + # @brief [CORBA interface] ConnectorProfileListを取得する + # + # Portが保持する ConnectorProfile の sequence を返す。 + # ConnectorProfile は Port 間の接続プロファイル情報を保持する構造体であり、 + # 接続時にPort間で情報交換を行い、関連するすべての Port で同一の値が + # 保持される。 + # ConnectorProfile は以下のメンバーを保持している。 + # + # - name [string 型] このコネクタの名前。 + # - connector_id [string 型] ユニークなID + # - ports [Port sequnce] このコネクタに関連する Port のオブジェクト + # リファレンスのシーケンス。 + # - properties [NVList 型] その他のプロパティ。 + # + # @param self + # + # @return この Port が保持する ConnectorProfile + # + # @else + # + # @brief [CORBA interface] Get the ConnectorProfileList of the Port + # + # This operation returns a list of the ConnectorProfiles of the Port. + # ConnectorProfile includes the connection information that describes + # relation between (among) Ports, and Ports exchange the ConnectionProfile + # on connection process and hold the same information in each Port. + # ConnectionProfile has the following members, + # + # - name [string] The name of the connection. + # - connector_id [string] Unique identifier. + # - ports [Port sequnce] The sequence of Port's object reference + # that are related the connection. + # - properties [NVList] The other properties. + # + # @return the ConnectorProfileList of the Port + # + # @endif + # virtual ConnectorProfileList* get_connector_profiles() + + def get_connector_profiles(self): + self._rtcout.RTC_TRACE("get_connector_profiles()") + + self.updateConnectors() + + guard = OpenRTM_aist.ScopedLock(self._profile_mutex) + return self._profile.connector_profiles + + ## + # @if jp + # + # @brief [CORBA interface] ConnectorProfile を取得する + # + # connector_id で指定された ConnectorProfile を返す。 + # 指定した connector_id を持つ ConnectorProfile を保持していない場合は、 + # 空の ConnectorProfile を返す。 + # + # @param self + # @param connector_id ConnectorProfile の ID + # + # @return connector_id で指定された ConnectorProfile + # + # @else + # + # @brief [CORBA interface] Get the ConnectorProfile + # + # This operation returns the ConnectorProfiles specified connector_id. + # + # @param connector_id ID of the ConnectorProfile + # + # @return the ConnectorProfile identified by the connector_id + # + # @endif + # ConnectorProfile* get_connector_profile(const char* connector_id) + + def get_connector_profile(self, connector_id): + self._rtcout.RTC_TRACE("get_connector_profile(%s)", connector_id) + + self.updateConnectors() + + guard = OpenRTM_aist.ScopedLock(self._profile_mutex) + index = OpenRTM_aist.CORBA_SeqUtil.find(self._profile.connector_profiles, + self.find_conn_id(connector_id)) + if index < 0: + conn_prof = RTC.ConnectorProfile("", "", [], []) + return conn_prof + + conn_prof = RTC.ConnectorProfile(self._profile.connector_profiles[index].name, + self._profile.connector_profiles[index].connector_id, + self._profile.connector_profiles[index].ports, + self._profile.connector_profiles[index].properties) + return conn_prof + + ## + # @if jp + # + # @brief [CORBA interface] Port の接続を行う + # + # 与えられた ConnectoionProfile の情報に基づき、Port間の接続を確立 + # する。この関数は主にアプリケーションプログラムやツールから呼び出 + # すことを前提としている。 + # + # @pre アプリケーションプログラムは、コンポーネント間の複数の + # Port を接続するために、適切な値をセットした ConnectorProfile を + # connect() の引数として与えて呼び出さなければならない。 + # + # @pre connect() に与える ConnectorProfile のメンバーのうち、 + # name, ports, properties メンバーに対してデータをセットしなければ + # ならない。connector_id には通常空文字を設定するか、適当なUUIDを + # 文字列で設定する必要がある。 + # + # @pre ConnectorProfile::name は接続につける名前で CORBA::string + # 型に格納できる任意の文字列である必要がある。 + # + # @pre ConnectorProfile::connector_id はすべての接続に対して一意な + # ID (通常はUUID) が格納される。UUIDの設定は connect() 関数内で行 + # われるので、呼び出し側は空文字を設定する。既存の接続と同じUUIDを + # 設定し connect() を呼び出した場合には PRECONDITION_NOT_MET エラー + # を返す。ただし、将来の拡張で既存の接続プロファイルを更新するため + # に既存の UUID を設定して呼び出す使用法が用いられる可能性がある。 + # + # @pre ConnectorProfile::ports は RTC::PortService のシーケンスで、 + # 接続を構成する通常2つ以上のポートのオブジェクト参照を代入する必 + # 要がある。例外として、ポートのオブジェクト参照を1つだけ格納して + # connect()を呼び出すことで、ポートのインターフェース情報を取得し + # たり、特殊なポート(CORBAのRTC::PortService以外の相手)に対して接 + # 続を行う場合もある。 + # + # @pre ConnectorProfile::properties はポートに関連付けられたインター + # フェースに対するプロパティを与えるために使用する。プロパティは、 + # string 型をキー、Any 型を値としてもつペアのシーケンスであり、値 + # には任意のCORBAデータ型を格納できるが、可能な限り string 型とし + # て格納されることが推奨される。 + # + # @pre 以上 connect() 呼び出し時に設定する ConnectorProfile のメン + # バをまとめると以下のようになる。 + # + # - ConnectorProfile::name: 任意の接続名 + # - ConnectorProfile::connector_id: 空文字 + # - ConnectorProfile::ports: 1つ以上のポート + # - ConnectorProfile::properties: インターフェースに対するプロパティ + # + # @post connect() 関数は、ConnectorProfile::portsに格納されたポー + # トシーケンスの先頭のポートに対して notify_connect() を呼ぶ。 + # + # @post notify_connect() は ConnectorProfile::ports に格納されたポー + # ト順に notify_connect() をカスケード呼び出しする。このカスケード + # 呼び出しは、途中のnotify_connect() でエラーが出てもポートのオブ + # ジェクト参照が有効である限り、必ずすべてのポートに対して行われる + # ことが保証される。有効でないオブジェクト参照がシーケンス中に存在 + # する場合、そのポートをスキップして、次のポートに対して + # notify_connect() を呼び出す。 + # + # @post connect() 関数は、notify_connect()の戻り値がRTC_OKであれば、 + # RTC_OK を返す。この時点で接続は完了する。RTC_OK以外 + # の場合は、この接続IDに対してdisconnect()を呼び出し接続を解除し、 + # notify_connect() が返したエラーリターンコードをそのまま返す。 + # + # @post connect() の引数として渡した ConnectorProfile には、 + # ConnectorProfile::connector_id および、途中のポートが + # publishInterfaces() で公開したポートインターフェースの各種情報が + # 格納されている。connect() および途中の notify_connect() が + # ConnectorProfile::{name, ports} を変更することはない。 + # + # @param connector_profile ConnectorProfile + # @return ReturnCode_t 型のリターンコード + # + # @else + # + # @brief [CORBA interface] Connect the Port + # + # This operation establishes connection according to the given + # ConnectionProfile inforamtion. This function is premised on + # calling from mainly application program or tools. + # + # @pre To establish the connection among Ports of RT-Components, + # application programs must call this operation giving + # ConnectorProfile with valid values as an argument. + # + # @pre Out of ConnectorProfile member variables, "name", "ports" + # and "properties" members shall be set valid + # data. "connector_id" shall be set as empty string value or + # valid string UUID value. + # + # @pre ConnectorProfile::name that is connection identifier shall + # be any valid CORBA::string. + # + # + # @pre ConnectorProfile::connector_id shall be set unique + # identifier (usually UUID is used) for all connections. Since + # UUID string value is usually set in the connect() function, + # caller should just set empty string. If the connect() is called + # with the same UUID as existing connection, this function + # returns PRECONDITION_NOT_MET error. However, in order to update + # the existing connection profile, the "connect()" operation with + # existing connector ID might be used as valid method by future + # extension + # + # @pre ConnectorProfile::ports, which is sequence of + # RTC::PortService references, shall store usually two or more + # ports' references. As exceptions, the "connect()" operation + # might be called with only one reference in ConnectorProfile, in + # case of just getting interfaces information from the port, or + # connecting a special port (i.e. the peer port except + # RTC::PortService on CORBA). + # + # @pre ConnectorProfile::properties might be used to give certain + # properties to the service interfaces associated with the port. + # The properties is a sequence variable with a pair of key string + # and Any type value. Although the A variable can store any type + # of values, it is not recommended except string. + # + # @pre The following is the summary of the ConnectorProfile + # member to be set when this operation is called. + # + # - ConnectorProfile::name: The any name of connection + # - ConnectorProfile::connector_id: Empty string + # - ConnectorProfile::ports: One or more port references + # - ConnectorProfile::properties: Properties for the interfaces + # + # @post connect() operation will call the first port in the + # sequence of the ConnectorProfile. + # + # @post "noify_connect()"s perform cascaded call to the ports + # stored in the ConnectorProfile::ports by order. Even if errors + # are raised by intermediate notify_connect() operation, as long + # as ports' object references are valid, it is guaranteed that + # this cascaded call is completed in all the ports. If invalid + # or dead ports exist in the port's sequence, the ports are + # skipped and notify_connect() is called for the next valid port. + # + # @post connect() function returns RTC_OK if all the + # notify_connect() return RTC_OK. At this time the connection is + # completed. If notify_connect()s return except RTC_OK, + # connect() calls disconnect() operation with the connector_id to + # destruct the connection, and then it returns error code from + # notify_connect(). + # + # @post The ConnectorProfile argument of the connect() operation + # returns ConnectorProfile::connector_id and various information + # about service interfaces that is published by + # publishInterfaces() in the halfway ports. The connect() and + # halfway notify_connect() functions never change + # ConnectorProfile::{name, ports}. + # + # @param connector_profile The ConnectorProfile. + # @return ReturnCode_t The return code of ReturnCode_t type. + # + # @endif + # + # virtual ReturnCode_t connect(ConnectorProfile& connector_profile) + + def connect(self, connector_profile): + self._rtcout.RTC_TRACE("connect()") + if self.isEmptyId(connector_profile): + guard = OpenRTM_aist.ScopedLock(self._profile_mutex) + self.setUUID(connector_profile) + #assert(not self.isExistingConnId(connector_profile.connector_id)) + del guard + else: + guard = OpenRTM_aist.ScopedLock(self._profile_mutex) + if self.isExistingConnId(connector_profile.connector_id): + self._rtcout.RTC_ERROR("Connection already exists.") + return (RTC.PRECONDITION_NOT_MET, connector_profile) + del guard + + try: + retval, connector_profile = connector_profile.ports[0].notify_connect( + connector_profile) + if retval != RTC.RTC_OK: + self._rtcout.RTC_ERROR("Connection failed. cleanup.") + self.disconnect(connector_profile.connector_id) + + return (retval, connector_profile) + # return + # connector_profile.ports[0].notify_connect(connector_profile) + except BaseException: + self._rtcout.RTC_ERROR(OpenRTM_aist.Logger.print_exception()) + return (RTC.BAD_PARAMETER, connector_profile) + + ## + # @if jp + # + # @brief [CORBA interface] Port の接続通知を行う + # + # このオペレーションは、Port間の接続が行われる際に、Port間で内部的 + # に呼ばれるオペレーションであって、通常アプリケーションプログラム + # や、Port以外のRTC関連オブジェクト等から呼び出されることは想定さ + # れていない。 + # + # notify_connect() 自体はテンプレートメソッドパターンとして、サブ + # クラスで実装されることが前提の publishInterfaces(), + # subscribeInterfaces() の2つの関数を内部で呼び出す。処理の手順は + # 以下の通りである。 + # + # - publishInterfaces(): インターフェース情報の公開 + # - connectNext(): 次の Port の notify_connect() の呼び出し + # - subscribeInterfaces(): インターフェース情報の取得 + # - 接続情報の保存 + # + # notify_connect() は ConnectorProfile::ports に格納されている + # Port の順序に従って、カスケード状に呼び出しを行うことにより、イ + # ンターフェース情報の公開と取得を関連すすべてのポートに対して行う。 + # このカスケード呼び出しは途中で中断されることはなく、必ず + # ConnectorProfile::ports に格納されている全ポートに対して行われる。 + # + # @pre notify_connect() は ConnectorProfile::ports 内に格納されて + # いる Port 参照リストのうち、当該 Port 自身の参照の次に格納されて + # いる Port に対して notify_connect() を呼び出す。したがって + # ConnectorProfile::ports には当該 Port の参照が格納されている必要 + # がある。もし、自身の参照が格納されていない場合、その他の処理によ + # りエラーが上書きされなければ、BAD_PARAMETER エラーが返される。 + # + # @pre 呼び出し時に ConnectorProfile::connector_id には一意なIDと + # して UUID が保持されている必要がある。通常 connector_id は + # connect() 関数により与えられ、空文字の場合は動作は未定義である。 + # + # @post ConnectorProfile::name, ConnectorProfile::connector_id, + # ConnectorProfile::ports は notify_connect() の呼び出しにより + # 書き換えられることはなく不変である。 + # + # @post ConnectorProfile::properties は notify_connect() の内部で、 + # 当該 Port が持つサービスインターフェースに関する情報を他の Port + # に伝えるために、プロパティ情報が書き込まれる。 + # + # @post なお、ConnectorProfile::ports のリストの最初 Port の + # notify_connet() が終了した時点では、すべての関連する Port の + # notify_connect() の呼び出しが完了する。publishInterfaces(), + # connectNext(), subscribeInterfaces() および接続情報の保存のいず + # れかの段階でエラーが発生した場合でも、エラーコードは内部的に保持 + # されており、最初に生じたエラーのエラーコードが返される。 + # + # @param connector_profile ConnectorProfile + # @return ReturnCode_t 型のリターンコード + # + # @else + # + # @brief [CORBA interface] Notify the Ports connection + # + # This operation is usually called from other ports' connect() or + # notify_connect() operations when connection between ports is + # established. This function is not premised on calling from + # other functions or application programs. + # + # According to the template method pattern, the notify_connect() + # calls "publishInterfaces()" and "subsctiveInterfaces()" + # functions, which are premised on implementing in the + # subclasses. The processing sequence is as follows. + # + # - publishInterfaces(): Publishing interface information + # - connectNext(): Calling notify_connect() of the next port + # - subscribeInterfaces(): Subscribing interface information + # - Storing connection profile + # + # According to the order of port's references stored in the + # ConnectorProfile::ports, publishing interface information to + # all the ports and subscription interface information from all + # the ports is performed by "notify_connect()"s. This cascaded + # call never aborts in the halfway operations, and calling + # sequence shall be completed for all the ports. + # + # @pre notify_connect() calls notify_connect() for the port's + # reference that is stored in next of this port's reference in + # the sequence of the ConnectorProfile::ports. Therefore the + # reference of this port shall be stored in the + # ConnectorProfile::ports. If this port's reference is not stored + # in the sequence, BAD_PARAMETER error will be returned, except + # the return code is overwritten by other operations. + # + # @pre UUID shall be set to ConnectorProfile::connector_id as a + # unique identifier when this operation is called. Usually, + # connector_id is given by a connect() function and, the behavior + # is undefined in the case of a null character. + # + # @post ConnectorProfile::name, ConnectorProfile::connector_id, + # ConnectorProfile::ports are invariant, and they are never + # rewritten by notify_connect() operations. + # + # @post In order to transfer interface information to other + # ports, interface property information is stored into the + # ConnectorProfile::properties. + # + # @post At the end of notify_connect() operation for the first + # port stored in the ConnectorProfile::ports sequence, the + # related ports' notify_connect() invocations complete. Even if + # errors are raised at the halfway of publishInterfaces(), + # connectNext(), subscribeInterfaces() and storing process of + # ConnectorProfile, error codes are saved and the first error is + # returned. + # + # @param connector_profile The ConnectorProfile. + # @return ReturnCode_t The return code of ReturnCode_t type. + # + # @endif + # + # virtual ReturnCode_t notify_connect(ConnectorProfile& connector_profile) + + def notify_connect(self, connector_profile): + self._rtcout.RTC_TRACE("notify_connect()") + + prop = OpenRTM_aist.Properties() + OpenRTM_aist.NVUtil.copyToProperties( + prop, connector_profile.properties) + + default_value = OpenRTM_aist.toBool( + self._properties.getProperty("allow_dup_connection"), "YES", "NO", False) + + if not OpenRTM_aist.toBool(prop.getProperty( + "dataport.allow_dup_connection"), "YES", "NO", default_value): + for port in connector_profile.ports: + if not port._is_equivalent(self._objref): + ret = OpenRTM_aist.CORBA_RTCUtil.already_connected( + port, self._objref) + if ret: + return (RTC.PRECONDITION_NOT_MET, connector_profile) + + guard_connection = OpenRTM_aist.ScopedLock(self._connection_mutex) + + # publish owned interface information to the ConnectorProfile + retval = [RTC.RTC_OK for i in range(3)] + + self.onNotifyConnect(self.getName(), connector_profile) + retval[0] = self.publishInterfaces(connector_profile) + if retval[0] != RTC.RTC_OK: + self._rtcout.RTC_ERROR( + "publishInterfaces() in notify_connect() failed.") + + self.onPublishInterfaces(self.getName(), connector_profile, retval[0]) + if self._onPublishInterfaces: + self._onPublishInterfaces(connector_profile) + + # call notify_connect() of the next Port + retval[1], connector_profile = self.connectNext(connector_profile) + if retval[1] != RTC.RTC_OK: + self._rtcout.RTC_ERROR("connectNext() in notify_connect() failed.") + + self.onConnectNextport(self.getName(), connector_profile, retval[1]) + # subscribe interface from the ConnectorProfile's information + if self._onSubscribeInterfaces: + self._onSubscribeInterfaces(connector_profile) + + retval[2] = self.subscribeInterfaces(connector_profile) + if retval[2] != RTC.RTC_OK: + self._rtcout.RTC_ERROR( + "subscribeInterfaces() in notify_connect() failed.") + # self.notify_disconnect(connector_profile.connector_id) + + self.onSubscribeInterfaces( + self.getName(), connector_profile, retval[2]) + self._rtcout.RTC_PARANOID("%d connectors are existing", len(self._profile.connector_profiles)) + + guard = OpenRTM_aist.ScopedLock(self._profile_mutex) + # update ConnectorProfile + index = self.findConnProfileIndex(connector_profile.connector_id) + if index < 0: + OpenRTM_aist.CORBA_SeqUtil.push_back(self._profile.connector_profiles, + connector_profile) + self._rtcout.RTC_PARANOID("New connector_id. Push backed.") + + else: + self._profile.connector_profiles[index] = connector_profile + self._rtcout.RTC_PARANOID("Existing connector_id. Updated.") + + for ret in retval: + if ret != RTC.RTC_OK: + self.onConnected(self.getName(), connector_profile, ret) + return (ret, connector_profile) + + # connection established without errors + if self._onConnected: + self._onConnected(connector_profile) + self.onConnected(self.getName(), connector_profile, RTC.RTC_OK) + return (RTC.RTC_OK, connector_profile) + + ## + # @if jp + # + # @brief [CORBA interface] Port の接続を解除する + # + # このオペレーションは与えられた connector_id に対応する接続を解除 + # する。connector_id は通常、システム全体において一意な UUID の文 + # 字列であり、事前に connect()/notify_connect() の呼び出しにより確 + # 立された接続プロファイル ConnectorProfile::connector_id に対応す + # る。 + # + # @pre connector_id は Port が保持する ConnectorProfile の少なくと + # も一つの ID に一致する文字列でなければならない。当該 Port が持つ + # ConnectorProfile のリスト内に connector_id と同一の ID を持つ + # ConnectorProfile が存在しなければこの関数は BAD_PARAMETER エラー + # を返す。 + # + # @pre connector_id と同じ ID を持つ ConnectorProfile::ports には + # 有効な Port の参照が含まれていなければならない。 + # + # @post disconnect() 関数は、ConnectorProfile::ports の Port の参 + # 照リストの先頭に対して、notify_disconnect() を呼び出す。参照が無 + # 効であるなど、notify_disconnect() の呼び出しに失敗した場合には、 + # 参照リストの先頭から順番に成功するまで notify_disconnect() の呼 + # び出しを試す。notify_disconnect() の呼び出しに一つでも成功すれば、 + # notify_disconnect() の返却値をそのまま返し、一つも成功しなかった + # 場合には RTC_ERROR エラーを返す。 + # + # @param connector_id ConnectorProfile の ID + # @return ReturnCode_t 型のリターンコード + # + # @else + # + # @brief [CORBA interface] Disconnect the Port + # + # This operation destroys connection between this port and the + # peer port according to given connector_id. Usually connector_id + # should be a UUID string that is unique in the system. And the + # connection, which is established by connect()/notify_connect() + # functions, is identified by the ConnectorProfile::connector_id. + # + # @pre connector_id shall be a character string which is same + # with ID of at least one of the ConnectorProfiles stored in this + # port. If ConnectorProfile that has same ID with the given + # connector_id does not exist in the list of ConnectorProfile, + # this operation returns BAD_PARAMTER error. + # + # @pre ConnectorProfile::ports that is same ID with given + # connector_id shall store the valid ports' references. + # + # @post disconnect() function invokes the notify_disconnect() for + # the port that is stored in the first of the + # ConnectorProfile::ports. If notify_disconnect() call fails for + # the first port, It tries on calling "notify_disconnect()" in + # order for ports stored in ConnectorProfile::ports until the + # operation call is succeeded. If notify_disconnect() succeeded + # for at least one port, it returns return code from + # notify_disconnect(). If none of notify_connect() call + # succeeded, it returns RTC_ERROR error. + # + # @param connector_id The ID of the ConnectorProfile. + # @return ReturnCode_t The return code of ReturnCode_t type. + # + # @endif + # + # virtual ReturnCode_t disconnect(const char* connector_id) + + def disconnect(self, connector_id): + self._rtcout.RTC_TRACE("disconnect(%s)", connector_id) + + index = self.findConnProfileIndex(connector_id) + + if index < 0: + self._rtcout.RTC_ERROR("Invalid connector id: %s", connector_id) + return RTC.BAD_PARAMETER + prof = None + guard = OpenRTM_aist.ScopedLock(self._profile_mutex) + if index < len(self._profile.connector_profiles): + prof = self._profile.connector_profiles[index] + del guard + + if not prof.ports: + self._rtcout.RTC_FATAL("ConnectorProfile has empty port list.") + return RTC.PRECONDITION_NOT_MET + + for p in prof.ports: + try: + return p.notify_disconnect(connector_id) + except BaseException: + self._rtcout.RTC_WARN(OpenRTM_aist.Logger.print_exception()) + continue + + self._rtcout.RTC_ERROR("notify_disconnect() for all ports failed.") + return RTC.RTC_ERROR + + ## + # @if jp + # + # @brief [CORBA interface] Port の接続解除通知を行う + # + # このオペレーションは、Port間の接続解除が行われる際に、Port間で内 + # 部的に呼ばれるオペレーションであり、通常アプリケーションプログラ + # ムや、 Port 以外の RTC 関連オブジェクト等から呼び出されることは + # 想定されていない。 + # + # notify_disconnect() 自体はテンプレートメソッドパターンとして、サ + # ブクラスで実装されることが前提の unsubscribeInterfaces() 関数を + # 内部で呼び出す。処理の手順は以下の通りである。 + # + # - ConnectorProfile の検索 + # - 次の Port の notify_disconnect() 呼び出し + # - unsubscribeInterfaces() + # - ConnectorProfile の削除 + # + # notify_disconnect() は ConnectorProfile::ports に格納されている + # Port の順序に従って、カスケード状に呼び出しを行うことにより、接 + # 続の解除をすべての Port に通知する。 + # + # @pre Port は与えられた connector_id に対応する ConnectorProfile + # を保持していなければならない。 + # + # @post connector_id に対応する ConnectorProfile が見つからない場 + # 合はBAD_PARAMETER エラーを返す。 + # + # @post カスケード呼び出しを行う際には ConnectorProfile::ports に + # 保持されている Port の参照リストのうち、自身の参照の次の参照に対 + # して notify_disconnect() を呼び出すが、その呼び出しで例外が発生 + # した場合には、呼び出しをスキップしリストの次の参照に対して + # notify_disconnect() を呼び出す。一つも呼び出しに成功しない場合、 + # RTC_ERROR エラーコードを返す。 + # + # @post なお、ConnectorProfile::ports のリストの最初 Port の + # notify_disconnet() が終了した時点では、すべての関連する Port の + # notify_disconnect() の呼び出しが完了する。 + # + # @param connector_id ConnectorProfile の ID + # @return ReturnCode_t 型のリターンコード + # + # @else + # + # @brief [CORBA interface] Notify the Ports disconnection + # + # This operation is invoked between Ports internally when the + # connection is destroied. Generally it is not premised on + # calling from application programs or RTC objects except Port + # object. + # + # According to the template method pattern, the + # notify_disconnect() calls unsubsctiveInterfaces() function, + # which are premised on implementing in the subclasses. The + # processing sequence is as follows. + # + # - Searching ConnectorProfile + # - Calling notify_disconnect() for the next port + # - Unsubscribing interfaces + # - Deleting ConnectorProfile + # + # notify_disconnect() notifies disconnection to all the ports by + # cascaded call to the stored ports in the + # ConnectorProfile::ports in order. + # + # @pre The port shall store the ConnectorProfile having same id + # with connector_id. + # + # @post If ConnectorProfile of same ID with connector_id does not + # exist, it returns BAD_PARAMETER error. + # + # @post For the cascaded call, this operation calls + # noify_disconnect() for the port that is stored in the next of + # this port in the ConnectorProfile::ports. If the operation + # call raises exception for some failure, it tries to call + # notify_disconnect() and skips until the operation succeeded. + # If none of operation call succeeded, it returns RTC_ERROR. + # + # @post At the end of notify_disconnect() operation for the first + # port stored in the ConnectorProfile::ports sequence, the + # related ports' notify_disconnect() invocations complete. + # + # @param connector_id The ID of the ConnectorProfile. + # @return ReturnCode_t The return code of ReturnCode_t type. + # + # @endif + # + # virtual ReturnCode_t notify_disconnect(const char* connector_id) + + def notify_disconnect(self, connector_id): + self._rtcout.RTC_TRACE("notify_disconnect(%s)", connector_id) + + guard_connection = OpenRTM_aist.ScopedLock(self._connection_mutex) + # The Port of which the reference is stored in the beginning of + # connectorProfile's PortServiceList is main Port. + # The main Port has the responsibility of disconnecting all Ports. + # The subordinate Ports have only responsibility of deleting its own + # ConnectorProfile. + + guard = OpenRTM_aist.ScopedLock(self._profile_mutex) + + index = self.findConnProfileIndex(connector_id) + + if index < 0: + self._rtcout.RTC_ERROR("Invalid connector id: %s", connector_id) + return RTC.BAD_PARAMETER + + prof = RTC.ConnectorProfile(self._profile.connector_profiles[index].name, + self._profile.connector_profiles[index].connector_id, + self._profile.connector_profiles[index].ports, + self._profile.connector_profiles[index].properties) + self.onNotifyDisconnect(self.getName(), prof) + + retval = self.disconnectNext(prof) + self.onDisconnectNextport(self.getName(), prof, retval) + + if self._onUnsubscribeInterfaces: + self._onUnsubscribeInterfaces(prof) + self.onUnsubscribeInterfaces(self.getName(), prof) + self.unsubscribeInterfaces(prof) + + if self._onDisconnected: + self._onDisconnected(prof) + + OpenRTM_aist.CORBA_SeqUtil.erase( + self._profile.connector_profiles, index) + + self.onDisconnected(self.getName(), prof, retval) + return retval + + ## + # @if jp + # + # @brief [CORBA interface] Port の全接続を解除する + # + # このオペレーションはこの Port に関連した全ての接続を解除する。 + # + # @param self + # + # @return ReturnCode_t 型のリターンコード + # + # @else + # + # @brief [CORBA interface] Connect the Port + # + # This operation destroys all connection channels owned by the Port. + # + # @return ReturnCode_t The return code of this operation. + # + # @endif + # virtual ReturnCode_t disconnect_all() + + def disconnect_all(self): + self._rtcout.RTC_TRACE("disconnect_all()") + guard = OpenRTM_aist.ScopedLock(self._profile_mutex) + plist = copy.deepcopy(self._profile.connector_profiles) + del guard + + retcode = RTC.RTC_OK + len_ = len(plist) + self._rtcout.RTC_DEBUG("disconnecting %d connections.", len_) + + # disconnect all connections + # Call disconnect() for each ConnectorProfile. + for p in plist: + tmpret = self.disconnect(p.connector_id) + if tmpret != RTC.RTC_OK: + retcode = tmpret + + return retcode + + # ============================================================ + # Local operations + # ============================================================ + + ## + # @if jp + # @brief Port の名前を設定する + # + # Port の名前を設定する。この名前は Port が保持する PortProfile.name + # に反映される。 + # + # @param self + # @param name Port の名前 + # + # @else + # @brief Set the name of this Port + # + # This operation sets the name of this Port. The given Port's name is + # applied to Port's PortProfile.name. + # + # @param name The name of this Port. + # + # @endif + # void setName(const char* name); + + def setName(self, name): + self._rtcout.RTC_TRACE("setName(%s)", name) + guard = OpenRTM_aist.ScopedLock(self._profile_mutex) + self._profile.name = name + return + + ## + # @if jp + # @brief Port の名前を取得する + # @else + # @brief Get the name of this Port + # @return The name of this Port. + # @endif + # + # const char* PortBase::getName() const + def getName(self): + self._rtcout.RTC_TRACE("getName() = %s", self._profile.name) + return self._profile.name + + ## + # @if jp + # @brief PortProfileを取得する + # + # Portが保持する PortProfile の const 参照を返す。 + # + # @param self + # + # @return この Port の PortProfile + # + # @else + # @brief Get the PortProfile of the Port + # + # This operation returns const reference of the PortProfile. + # + # @return the PortProfile of the Port + # + # @endif + # const PortProfile& getProfile() const; + + def getProfile(self): + self._rtcout.RTC_TRACE("getProfile()") + guard = OpenRTM_aist.ScopedLock(self._profile_mutex) + return self._profile + + ## + # @if jp + # + # @brief Port のオブジェクト参照を設定する + # + # このオペレーションは Port の PortProfile にこの Port 自身の + # オブジェクト参照を設定する。 + # + # @param self + # @param port_ref この Port のオブジェクト参照 + # + # @else + # + # @brief Set the object reference of this Port + # + # This operation sets the object reference itself + # to the Port's PortProfile. + # + # @param The object reference of this Port. + # + # @endif + # void setPortRef(PortService_ptr port_ref); + + def setPortRef(self, port_ref): + self._rtcout.RTC_TRACE("setPortRef()") + guard = OpenRTM_aist.ScopedLock(self._profile_mutex) + self._profile.port_ref = port_ref + + ## + # @if jp + # + # @brief Port のオブジェクト参照を取得する + # + # このオペレーションは Port の PortProfile が保持している + # この Port 自身のオブジェクト参照を取得する。 + # + # @param self + # + # @return この Port のオブジェクト参照 + # + # @else + # + # @brief Get the object reference of this Port + # + # This operation returns the object reference + # that is stored in the Port's PortProfile. + # + # @return The object reference of this Port. + # + # @endif + # PortService_ptr getPortRef(); + + def getPortRef(self): + self._rtcout.RTC_TRACE("getPortRef()") + guard = OpenRTM_aist.ScopedLock(self._profile_mutex) + return self._profile.port_ref + + ## + # @if jp + # + # @brief Port の owner の RTObject を指定する + # + # このオペレーションは Port の PortProfile.owner を設定する。 + # + # @param self + # @param owner この Port を所有する RTObject の参照 + # + # @else + # + # @brief Set the owner RTObject of the Port + # + # This operation sets the owner RTObject of this Port. + # + # @param owner The owner RTObject's reference of this Port + # + # @endif + # void setOwner(RTObject_ptr owner); + + def setOwner(self, owner): + prof = owner.get_component_profile() + self._ownerInstanceName = prof.instance_name + self._rtcout.RTC_TRACE("setOwner(%s)", self._ownerInstanceName) + + guard = OpenRTM_aist.ScopedLock(self._profile_mutex) + plist = self._profile.name.split(".") + if not self._ownerInstanceName: + self._rtcout.RTC_ERROR("Owner is not set.") + self._rtcout.RTC_ERROR( + "addXXXPort() should be called in onInitialize().") + portname = self._ownerInstanceName + "." + plist[-1] + + self._profile.owner = owner + self._profile.name = portname + + # ============================================================ + # callbacks + # ============================================================ + + ## + # @if jp + # + # @brief インターフェースを公開する際に呼ばれるコールバックをセットする + # + # このオペレーションは、このポートが接続時に、ポート自身が持つサー + # ビスインターフェース情報を公開するタイミングで呼ばれるコールバッ + # クファンクタをセットする。 + # + # コールバックファンクタの所有権は、呼び出し側にあり、オブジェクト + # が必要なくなった時に解体するのは呼び出し側の責任である。 + # + # このコールバックファンクタは、PortBaseクラスの仮想関数である + # publishInterfaces() が呼ばれたあとに、同じ引数 ConnectorProfile と + # ともに呼び出される。このコールバックを利用して、 + # publishInterfaces() が公開した ConnectorProfile を変更することが可 + # 能であるが、接続関係の不整合を招かないよう、ConnectorProfile の + # 変更には注意を要する。 + # + # @param on_publish ConnectionCallback のサブクラスオブジェクトのポインタ + # + # @else + # + # @brief Setting callback called on publish interfaces + # + # This operation sets a functor that is called after publishing + # interfaces process when connecting between ports. + # + # Since the ownership of the callback functor object is owned by + # the caller, it has the responsibility of object destruction. + # + # The callback functor is called after calling + # publishInterfaces() that is virtual member function of the + # PortBase class with an argument of ConnectorProfile type that + # is same as the argument of publishInterfaces() function. + # Although by using this functor, you can modify the ConnectorProfile + # published by publishInterfaces() function, the modification + # should be done carefully for fear of causing connection + # inconsistency. + # + # @param on_publish a pointer to ConnectionCallback's subclasses + # + # @endif + # + # void setOnPublishInterfaces(ConnectionCallback* on_publish); + + def setOnPublishInterfaces(self, on_publish): + self._onPublishInterfaces = on_publish + return + + ## + # @if jp + # + # @brief インターフェースを取得する際に呼ばれるコールバックをセットする + # + # このオペレーションは、このポートが接続時に、相手のポートが持つサー + # ビスインターフェース情報を取得するタイミングで呼ばれるコールバッ + # クファンクタをセットする。 + # + # コールバックファンクタの所有権は、呼び出し側にあり、オブジェクト + # が必要なくなった時に解体するのは呼び出し側の責任である。 + # + # このコールバックファンクタは、PortBaseクラスの仮想関数である + # subscribeInterfaces() が呼ばれる前に、同じ引数 ConnectorProfile と + # ともに呼び出される。このコールバックを利用して、 + # subscribeInterfaces() に与える ConnectorProfile を変更することが可 + # 能であるが、接続関係の不整合を招かないよう、ConnectorProfile の + # 変更には注意を要する。 + # + # @param on_subscribe ConnectionCallback のサブクラスオブジェクトのポインタ + # + # @else + # + # @brief Setting callback called on publish interfaces + # + # This operation sets a functor that is called before subscribing + # interfaces process when connecting between ports. + # + # Since the ownership of the callback functor object is owned by + # the caller, it has the responsibility of object destruction. + # + # The callback functor is called before calling + # subscribeInterfaces() that is virtual member function of the + # PortBase class with an argument of ConnectorProfile type that + # is same as the argument of subscribeInterfaces() function. + # Although by using this functor, you can modify ConnectorProfile + # argument for subscribeInterfaces() function, the modification + # should be done carefully for fear of causing connection + # inconsistency. + # + # @param on_subscribe a pointer to ConnectionCallback's subclasses + # + # @endif + # + # void setOnSubscribeInterfaces(ConnectionCallback* on_subscribe); + + def setOnSubscribeInterfaces(self, on_subscribe): + self._onSubscribeInterfaces = on_subscribe + return + + ## + # @if jp + # + # @brief 接続完了時に呼ばれるコールバックをセットする + # + # このオペレーションは、このポートが接続完了時に呼ばれる、コールバッ + # クファンクタをセットする。 + # + # コールバックファンクタの所有権は、呼び出し側にあり、オブジェクト + # が必要なくなった時に解体するのは呼び出し側の責任である。 + # + # このコールバックファンクタは、ポートの接続実行関数である + # notify_connect() の終了直前に、接続処理が正常終了する際に限って + # 呼び出されるコールバックである。接続処理の過程でエラーが発生した + # 場合には呼び出されない。 + # + # このコールバックファンクタは notify_connect() が out パラメータ + # として返すのと同じ引数 ConnectorProfile とともに呼び出されるので、 + # この接続において公開されたすべてのインターフェース情報を得ること + # ができる。このコールバックを利用して、notify_connect() が返す + # ConnectorProfile を変更することが可能であるが、接続関係の不整合 + # を招かないよう、ConnectorProfile の変更には注意を要する。 + # + # @param on_subscribe ConnectionCallback のサブクラスオブジェクトのポインタ + # + # @else + # + # @brief Setting callback called on connection established + # + # This operation sets a functor that is called when connection + # between ports established. + # + # Since the ownership of the callback functor object is owned by + # the caller, it has the responsibility of object destruction. + # + # The callback functor is called only when notify_connect() + # function successfully returns. In case of error, the functor + # will not be called. + # + # Since this functor is called with ConnectorProfile argument + # that is same as out-parameter of notify_connect() function, you + # can get all the information of published interfaces of related + # ports in the connection. Although by using this functor, you + # can modify ConnectorProfile argument for out-paramter of + # notify_connect(), the modification should be done carefully for + # fear of causing connection inconsistency. + # + # @param on_subscribe a pointer to ConnectionCallback's subclasses + # + # @endif + # + # void setOnConnected(ConnectionCallback* on_connected); + + def setOnConnected(self, on_connected): + self._onConnected = on_connected + return + + ## + # @if jp + # + # @brief インターフェースを解放する際に呼ばれるコールバックをセットする + # + # このオペレーションは、このポートが接続時に、相手のポートが持つサー + # ビスインターフェース情報を解放するタイミングで呼ばれるコールバッ + # クファンクタをセットする。 + # + # コールバックファンクタの所有権は、呼び出し側にあり、オブジェクト + # が必要なくなった時に解体するのは呼び出し側の責任である。 + # + # このコールバックファンクタは、PortBaseクラスの仮想関数である + # unsubscribeInterfaces() が呼ばれる前に、同じ引数 ConnectorProfile と + # ともに呼び出される。このコールバックを利用して、 + # unsubscribeInterfaces() に与える ConnectorProfile を変更することが可 + # 能であるが、接続関係の不整合を招かないよう、ConnectorProfile の + # 変更には注意を要する。 + # + # @param on_unsubscribe ConnectionCallback のサブクラスオブジェク + # トのポインタ + # + # @else + # + # @brief Setting callback called on unsubscribe interfaces + # + # This operation sets a functor that is called before unsubscribing + # interfaces process when disconnecting between ports. + # + # Since the ownership of the callback functor object is owned by + # the caller, it has the responsibility of object destruction. + # + # The callback functor is called before calling + # unsubscribeInterfaces() that is virtual member function of the + # PortBase class with an argument of ConnectorProfile type that + # is same as the argument of unsubscribeInterfaces() function. + # Although by using this functor, you can modify ConnectorProfile + # argument for unsubscribeInterfaces() function, the modification + # should be done carefully for fear of causing connection + # inconsistency. + # + # @param on_unsubscribe a pointer to ConnectionCallback's subclasses + # + # @endif + # + # void setOnUnsubscribeInterfaces(ConnectionCallback* on_subscribe); + + def setOnUnsubscribeInterfaces(self, on_subscribe): + self._onUnsubscribeInterfaces = on_subscribe + return + + ## + # @if jp + # + # @brief 接続解除に呼ばれるコールバックをセットする + # + # このオペレーションは、このポートの接続解除時に呼ばれる、コールバッ + # クファンクタをセットする。 + # + # コールバックファンクタの所有権は、呼び出し側にあり、オブジェクト + # が必要なくなった時に解体するのは呼び出し側の責任である。 + # + # このコールバックファンクタは、ポートの接続解除実行関数である + # notify_disconnect() の終了直前に、呼び出されるコールバックである。 + # + # このコールバックファンクタは接続に対応する ConnectorProfile とと + # もに呼び出される。この ConnectorProfile はこのファンクタ呼出し後 + # に破棄されるので、変更がほかに影響を与えることはない。 + # + # @param on_disconnected ConnectionCallback のサブクラスオブジェク + # トのポインタ + # + # @else + # + # @brief Setting callback called on disconnected + # + # This operation sets a functor that is called when connection + # between ports is destructed. + # + # Since the ownership of the callback functor object is owned by + # the caller, it has the responsibility of object destruction. + # + # The callback functor is called just before notify_disconnect() + # that is disconnection execution function returns. + # + # This functor is called with argument of corresponding + # ConnectorProfile. Since this ConnectorProfile will be + # destructed after calling this functor, modifications never + # affect others. + # + # @param on_disconnected a pointer to ConnectionCallback's subclasses + # + # @endif + # + # void setOnDisconnected(ConnectionCallback* on_disconnected); + + def setOnDisconnected(self, on_disconnected): + self._onDisconnected = on_disconnected + return + + # void setOnConnectionLost(ConnectionCallback* on_connection_lost); + def setOnConnectionLost(self, on_connection_lost): + self._onConnectionLost = on_connection_lost + return + + ## + # @if jp + # @brief PortConnectListeners のホルダをセットする + # + # ポートの接続に関するリスナ群を保持するホルダクラスへのポインタを + # セットする。この関数は通常親のRTObjectから呼ばれ、RTObjectが持つ + # ホルダクラスへのポインタがセットされる。 + # + # @param portconnListeners PortConnectListeners オブジェクトのポインタ + # + # @else + # @brief Setting PortConnectListener holder + # + # This operation sets a functor that is called when connection + # of this port does lost. + # + # @param on_connection_lost a pointer to ConnectionCallback's subclasses + # + # @endif + # + # void setPortConnectListenerHolder(PortConnectListeners* + # portconnListeners); + + def setPortConnectListenerHolder(self, portconnListeners): + self._portconnListeners = portconnListeners + return + + ## + # @if jp + # + # @brief Interface 情報を公開する(サブクラス実装用) + # + # このオペレーションは、notify_connect() 処理シーケンスの始めにコール + # される関数である。 + # notify_connect() では、 + # + # - publishInterfaces() + # - connectNext() + # - subscribeInterfaces() + # - updateConnectorProfile() + # + # の順に protected 関数がコールされ接続処理が行われる。 + #
    + # 具象 Port ではこのオペレーションをオーバーライドし、引数として + # 与えられた ConnectorProfile に従い処理を行い、パラメータが不適切 + # であれば、RteurnCode_t 型のエラーコードを返す。 + # 通常 publishInterafaces() 内においては、この Port に属する + # インターフェースに関する情報を ConnectorProfile に対して適切に設定し + # 他の Port に通知しなければならない。 + #
    + # また、この関数がコールされる段階では、他の Port の Interface に関する + # 情報はすべて含まれていないので、他の Port の Interface を取得する処理 + # は subscribeInterfaces() 内で行われるべきである。 + #
    + # このオペレーションは、新規の connector_id に対しては接続の生成、 + # 既存の connector_id に対しては更新が適切に行われる必要がある。
    + # ※サブクラスでの実装参照用 + # + # @param self + # @param connector_profile 接続に関するプロファイル情報 + # + # @return ReturnCode_t 型のリターンコード + # + # @else + # + # @brief Publish interface information + # + # This operation is pure virutal method that would be called at the + # beginning of the notify_connect() process sequence. + # In the notify_connect(), the following methods would be called in order. + # + # - publishInterfaces() + # - connectNext() + # - subscribeInterfaces() + # - updateConnectorProfile() + # + # In the concrete Port, this method should be overridden. This method + # processes the given ConnectorProfile argument and if the given parameter + # is invalid, it would return error code of ReturnCode_t. + # Usually, publishInterfaces() method should set interfaces information + # owned by this Port, and publish it to the other Ports. + #
    + # When this method is called, other Ports' interfaces information may not + # be completed. Therefore, the process to obtain other Port's interfaces + # information should be done in the subscribeInterfaces() method. + #
    + # This operation should create the new connection for the new + # connector_id, and should update the connection for the existing + # connection_id. + # + # @param connector_profile The connection profile information + # @return The return code of ReturnCode_t type. + # + # @endif + + def publishInterfaces(self, connector_profile): + return RTC.BAD_PARAMETER + + ## + # @if jp + # + # @brief 次の Port に対して notify_connect() をコールする + # + # ConnectorProfile の port_ref 内に格納されている Port のオブジェクト + # リファレンスのシーケンスの中から、自身の Port の次の Port に対して + # notify_connect() をコールする。 + # + # @param self + # @param connector_profile 接続に関するプロファイル情報 + # + # @return ReturnCode_t 型のリターンコード + # + # @else + # + # @brief Call notify_connect() of the next Port + # + # This operation calls the notify_connect() of the next Port's + # that stored in ConnectorProfile's port_ref sequence. + # + # @param connector_profile The connection profile information + # + # @return The return code of ReturnCode_t type. + # + # @endif + # virtual ReturnCode_t connectNext(ConnectorProfile& connector_profile); + + def connectNext(self, connector_profile): + index = OpenRTM_aist.CORBA_SeqUtil.find(connector_profile.ports, + self.find_port_ref(self._profile.port_ref)) + if index < 0: + return (RTC.BAD_PARAMETER, connector_profile) + + index += 1 + if index < len(connector_profile.ports): + p = connector_profile.ports[index] + return p.notify_connect(connector_profile) + + return (RTC.RTC_OK, connector_profile) + + ## + # @if jp + # + # @brief 次の Port に対して notify_disconnect() をコールする + # + # ConnectorProfile の port_ref 内に格納されている Port のオブジェクト + # リファレンスのシーケンスの中から、自身の Port の次の Port に対して + # notify_disconnect() をコールする。 + # + # @param self + # @param connector_profile 接続に関するプロファイル情報 + # + # @return ReturnCode_t 型のリターンコード + # + # @else + # + # @brief Call notify_disconnect() of the next Port + # + # This operation calls the notify_disconnect() of the next Port's + # that stored in ConnectorProfile's port_ref sequence. + # + # @param connector_profile The connection profile information + # + # @return The return code of ReturnCode_t type. + # + # @endif + # virtual ReturnCode_t disconnectNext(ConnectorProfile& connector_profile); + def disconnectNext(self, connector_profile): + + index = OpenRTM_aist.CORBA_SeqUtil.find(connector_profile.ports, + self.find_port_ref(self._profile.port_ref)) + if index < 0: + return RTC.BAD_PARAMETER + + if index == (len(connector_profile.ports) - 1): + return RTC.RTC_OK + + index += 1 + + while index < len(connector_profile.ports): + p = connector_profile.ports[index] + index += 1 + try: + return p.notify_disconnect(connector_profile.connector_id) + except BaseException: + self._rtcout.RTC_WARN(OpenRTM_aist.Logger.print_exception()) + continue + return RTC.RTC_ERROR - return RTC.RTC_OK - - - ## - # @if jp - # - # @brief ConnectorProfile connector_id եɤɤȽ - # - # ꤵ줿 ConnectorProfile connector_id Ǥ뤫ɤȽ - # Ԥ - # - # @param self - # @param connector_profile Ƚоݥͥץե - # - # @return Ϳ줿 ConnectorProfile connector_id ǤС - # trueǤʤ false ֤ - # - # @else - # - # @brief Whether connector_id of ConnectorProfile is empty - # - # @return If the given ConnectorProfile's connector_id is empty string, - # it returns true. - # - # @endif - # bool isEmptyId(const ConnectorProfile& connector_profile) const; - def isEmptyId(self, connector_profile): - return connector_profile.connector_id == "" - - - ## - # @if jp - # - # @brief UUID - # - # Υڥ졼 UUID 롣 - # - # @param self - # - # @return uuid - # - # @else - # - # @brief Get the UUID - # - # This operation generates UUID. - # - # @return uuid - # - # @endif - # const std::string getUUID() const; - def getUUID(self): - return str(OpenRTM_aist.uuid1()) - - - ## - # @if jp - # - # @brief UUID ConnectorProfile ˥åȤ - # - # Υڥ졼 UUID ConnectorProfile ˥åȤ롣 - # - # @param self - # @param connector_profile connector_id 򥻥åȤ ConnectorProfile - # - # @else - # - # @brief Create and set the UUID to the ConnectorProfile - # - # This operation generates and set UUID to the ConnectorProfile. - # - # @param connector_profile ConnectorProfile to be set connector_id - # - # @endif - # void setUUID(ConnectorProfile& connector_profile) const; - def setUUID(self, connector_profile): - connector_profile.connector_id = self.getUUID() - assert(connector_profile.connector_id != "") - - - ## - # @if jp - # - # @brief id ¸ ConnectorProfile ΤΤɤȽꤹ - # - # Υڥ졼Ϳ줿 ID ¸ ConnectorProfile Υꥹ - # ¸ߤ뤫ɤȽꤹ롣 - # - # @param self - # @param id_ Ƚꤹ connector_id - # - # @return id ¸Ƚ - # - # @else - # - # @brief Whether the given id exists in stored ConnectorProfiles - # - # This operation returns boolean whether the given id exists in - # the Port's ConnectorProfiles. - # - # @param id connector_id to be find in Port's ConnectorProfiles - # - # @endif - # bool isExistingConnId(const char* id); - def isExistingConnId(self, id_): - return OpenRTM_aist.CORBA_SeqUtil.find(self._profile.connector_profiles, - self.find_conn_id(id_)) >= 0 - - - ## - # @if jp - # - # @brief id ConnectorProfile õ - # - # Υڥ졼Ϳ줿 ID ConnectorProfile Port - # ConnectorProfile Υꥹ椫õ - # ⤷Ʊ id ConnectorProfile ʤС ConnectorProfile - # ֤롣 - # - # @param self - # @param id_ connector_id - # - # @return connector_id ConnectorProfile - # - # @else - # - # @brief Find ConnectorProfile with id - # - # This operation returns ConnectorProfile with the given id from Port's - # ConnectorProfiles' list. - # If the ConnectorProfile with connector id that is identical with the - # given id does not exist, empty ConnectorProfile is returned. - # - # @param id the connector_id to be searched in Port's ConnectorProfiles - # - # @return CoonectorProfile with connector_id - # - # @endif - # ConnectorProfile findConnProfile(const char* id); - def findConnProfile(self, id_): - index = OpenRTM_aist.CORBA_SeqUtil.find(self._profile.connector_profiles, - self.find_conn_id(id_)) - if index < 0 or index >= len(self._profile.connector_profiles): - return RTC.ConnectorProfile("","",[],[]) - - return self._profile.connector_profiles[index] - - - ## - # @if jp - # - # @brief id ConnectorProfile õ - # - # Υڥ졼Ϳ줿 ID ConnectorProfile Port - # ConnectorProfile Υꥹ椫õǥå֤ - # ⤷Ʊ id ConnectorProfile ʤС-1 ֤ - # - # @param self - # @param id_ connector_id - # - # @return Port ConnectorProfile ꥹȤΥǥå - # - # @else - # - # @brief Find ConnectorProfile with id - # - # This operation returns ConnectorProfile with the given id from Port's - # ConnectorProfiles' list. - # If the ConnectorProfile with connector id that is identical with the - # given id does not exist, empty ConnectorProfile is returned. - # - # @param id the connector_id to be searched in Port's ConnectorProfiles - # - # @return The index of ConnectorProfile of the Port - # - # @endif - # CORBA::Long findConnProfileIndex(const char* id); - def findConnProfileIndex(self, id_): - return OpenRTM_aist.CORBA_SeqUtil.find(self._profile.connector_profiles, - self.find_conn_id(id_)) - - - ## - # @if jp - # - # @brief ConnectorProfile ɲä⤷Ϲ - # - # Υڥ졼Ϳ줿Ϳ줿 ConnectorProfile - # Port ɲä⤷Ϲ¸롣 - # Ϳ줿 ConnectorProfile connector_id Ʊ ID - # ConnectorProfile ꥹȤˤʤСꥹȤɲä - # Ʊ ID ¸ߤ ConnectorProfile ¸롣 - # - # @param self - # @param connector_profile ɲä⤷Ϲ ConnectorProfile - # - # @else - # - # @brief Append or update the ConnectorProfile list - # - # This operation appends or updates ConnectorProfile of the Port - # by the given ConnectorProfile. - # If the connector_id of the given ConnectorProfile does not exist - # in the Port's ConnectorProfile list, the given ConnectorProfile would be - # append to the list. If the same id exists, the list would be updated. - # - # @param connector_profile the ConnectorProfile to be appended or updated - # - # @endif - # void updateConnectorProfile(const ConnectorProfile& connector_profile); - def updateConnectorProfile(self, connector_profile): - index = OpenRTM_aist.CORBA_SeqUtil.find(self._profile.connector_profiles, - self.find_conn_id(connector_profile.connector_id)) - - if index < 0: - OpenRTM_aist.CORBA_SeqUtil.push_back(self._profile.connector_profiles, - connector_profile) - else: - self._profile.connector_profiles[index] = connector_profile - - - ## - # @if jp - # - # @brief ConnectorProfile - # - # Υڥ졼 Port PortProfile ݻƤ - # ConnectorProfileList ΤͿ줿 id ConnectorProfile - # 롣 - # - # @param self - # @param id_ ConnectorProfile id - # - # @return ˺Ǥ true - # ꤷ ConnectorProfile Ĥʤ false ֤ - # - # @else - # - # @brief Delete the ConnectorProfile - # - # This operation deletes a ConnectorProfile specified by id from - # ConnectorProfileList owned by PortProfile of this Port. - # - # @param id The id of the ConnectorProfile to be deleted. - # - # @endif - # bool eraseConnectorProfile(const char* id); - def eraseConnectorProfile(self, id_): - guard = OpenRTM_aist.ScopedLock(self._profile_mutex) - - index = OpenRTM_aist.CORBA_SeqUtil.find(self._profile.connector_profiles, - self.find_conn_id(id_)) - - if index < 0: - return False - - OpenRTM_aist.CORBA_SeqUtil.erase(self._profile.connector_profiles, index) - - return True - - - ## - # @if jp - # - # @brief PortInterfaceProfile 󥿡եϿ - # - # Υڥ졼 Port PortProfile ΡPortInterfaceProfile - # ˥󥿡եξɲä롣 - # ξϡget_port_profile() ä PortProfile Τ - # PortInterfaceProfile ͤѹΤߤǤꡢºݤ˥󥿡ե - # 󶡤׵ᤷꤹˤϡ֥饹ǡ publishInterface() , - # subscribeInterface() δؿŬڤ˥С饤ɤ󥿡ե - # 󶡡׵ԤʤФʤʤ - # - # 󥿡ե(Υ󥹥)̾ Port ǰդǤʤФʤʤ - # Ʊ̾Υ󥿡եǤϿƤ硢δؿ false - # ֤ - # - # @param self - # @param instance_name 󥿡եΥ󥹥󥹤̾ - # @param type_name 󥿡եη̾ - # @param pol 󥿡ե° (RTC::PROVIDED ⤷ RTC:REQUIRED) - # - # @return 󥿡եϿ̡ - # Ʊ̾Υ󥿡եϿƤ false ֤ - # - # @else - # - # @brief Append an interface to the PortInterfaceProfile - # - # This operation appends interface information to the PortInterfaceProfile - # that is owned by the Port. - # The given interfaces information only updates PortInterfaceProfile of - # PortProfile that is obtained through get_port_profile(). - # In order to provide and require interfaces, proper functions (for - # example publishInterface(), subscribeInterface() and so on) should be - # overridden in subclasses, and these functions provide concrete interface - # connection and disconnection functionality. - # - # The interface (instance) name have to be unique in the Port. - # If the given interface name is identical with stored interface name, - # this function returns false. - # - # @param name The instance name of the interface. - # @param type_name The type name of the interface. - # @param pol The interface's polarity (RTC::PROVIDED or RTC:REQUIRED) - # - # @return false would be returned if the same name is already registered. - # - # @endif - # bool appendInterface(const char* name, const char* type_name, - # PortInterfacePolarity pol); - def appendInterface(self, instance_name, type_name, pol): - index = OpenRTM_aist.CORBA_SeqUtil.find(self._profile.interfaces, - self.find_interface(instance_name, pol)) - - if index >= 0: - return False - - # setup PortInterfaceProfile - prof = RTC.PortInterfaceProfile(instance_name, type_name, pol) - OpenRTM_aist.CORBA_SeqUtil.push_back(self._profile.interfaces, prof) - - return True - - - ## - # @if jp - # - # @brief PortInterfaceProfile 饤󥿡եϿ - # - # Υڥ졼 Port PortProfile ΡPortInterfaceProfile - # 饤󥿡եξ롣 - # - # @param self - # @param name 󥿡եΥ󥹥󥹤̾ - # @param pol 󥿡ե° (RTC::PROVIDED ⤷ RTC:REQUIRED) - # - # @return 󥿡ե̡ - # 󥿡եϿƤʤ false ֤ - # - # @else - # - # @brief Delete an interface from the PortInterfaceProfile - # - # This operation deletes interface information from the - # PortInterfaceProfile that is owned by the Port. - # - # @param name The instance name of the interface. - # @param pol The interface's polarity (RTC::PROVIDED or RTC:REQUIRED) - # - # @return false would be returned if the given name is not registered. - # - # @endif - # bool deleteInterface(const char* name, PortInterfacePolarity pol); - def deleteInterface(self, name, pol): - index = OpenRTM_aist.CORBA_SeqUtil.find(self._profile.interfaces, - self.find_interface(name, pol)) - - if index < 0: - return False - - OpenRTM_aist.CORBA_SeqUtil.erase(self._profile.interfaces, index) - return True - - - ## - # @if jp - # - # @brief PortProfile properties NameValue ͤɲä - # - # PortProfile properties NameValue ͤɲä롣 - # ɲäǡηValueTypeǻꤹ롣 - # - # @param self - # @param key properties name - # @param value properties value - # - # @else - # - # @brief Add NameValue data to PortProfile's properties - # - # @param key The name of properties - # @param value The value of properties - # - # @endif - # template - # void addProperty(const char* key, ValueType value) - def addProperty(self, key, value): - OpenRTM_aist.CORBA_SeqUtil.push_back(self._profile.properties, - OpenRTM_aist.NVUtil.newNV(key, value)) - - ## - # @if jp - # - # @brief PortProfile properties NameValue ͤǤɲä - # - # PortProfile properties NameValue ͤǤɲä롣 - # - # @param key properties name - # @param value properties value - # - # @else - # - # @brief Append NameValue data to PortProfile's properties - # - # Append NameValue data to PortProfile's properties. - # - # @param key The name of properties - # @param value The value of properties - # - # @endif - # void appendProperty(const char* key, const char* value) - def appendProperty(self, key, value): - OpenRTM_aist.NVUtil.appendStringValue(self._profile.properties, key, value) - - - - ## - # @if jp - # - # @brief ¸ߤʤݡȤdisconnect롣 - # - # @else - # - # @brief Disconnect ports that doesn't exist. - # - # @endif - # void updateConnectors() - def updateConnectors(self): - guard = OpenRTM_aist.ScopedLock(self._profile_mutex) - - connector_ids = [] - clist = self._profile.connector_profiles - - for cprof in clist: - if not self.checkPorts(cprof.ports): - connector_ids.append(cprof.connector_id) - self._rtcout.RTC_WARN("Dead connection: %s", cprof.connector_id) - - for cid in connector_ids: - self.disconnect(cid) - - return - - - ## - # @if jp - # - # @brief ݡȤ¸ߤǧ롣 - # - # @param ports ǧݡ - # @return true:¸ߤ,false:¸ߤʤ - # - # @else - # - # @brief Existence of ports - # - # @param ports Checked ports - # @return true:existent,false:non existent - # - # @endif - # bool checkPorts(::RTC::PortServiceList& ports) - def checkPorts(self, ports): - for port in ports: - try: - if port._non_existent(): - self._rtcout.RTC_WARN("Dead Port reference detected.") - return False - except: - self._rtcout.RTC_WARN(OpenRTM_aist.Logger.print_exception()) - return False - - return True - - - #inline void onNotifyConnect(const char* portname, - # RTC::ConnectorProfile& profile) - def onNotifyConnect(self, portname, profile): - if self._portconnListeners != None: - type = OpenRTM_aist.PortConnectListenerType.ON_NOTIFY_CONNECT - self._portconnListeners.portconnect_[type].notify(portname, profile) - return - - - #inline void onNotifyDisconnect(const char* portname, - # RTC::ConnectorProfile& profile) - def onNotifyDisconnect(self, portname, profile): - if self._portconnListeners != None: - type = OpenRTM_aist.PortConnectListenerType.ON_NOTIFY_DISCONNECT - self._portconnListeners.portconnect_[type].notify(portname, profile) - return - - - #inline void onUnsubscribeInterfaces(const char* portname, - # RTC::ConnectorProfile& profile) - def onUnsubscribeInterfaces(self, portname, profile): - if self._portconnListeners != None: - type = OpenRTM_aist.PortConnectListenerType.ON_UNSUBSCRIBE_INTERFACES - self._portconnListeners.portconnect_[type].notify(portname, profile) - return - - - #inline void onPublishInterfaces(const char* portname, - # RTC::ConnectorProfile& profile, - # ReturnCode_t ret) - def onPublishInterfaces(self, portname, profile, ret): - if self._portconnListeners != None: - type = OpenRTM_aist.PortConnectRetListenerType.ON_PUBLISH_INTERFACES - self._portconnListeners.portconnret_[type].notify(portname, profile, ret) - return - - - #inline void onConnectNextport(const char* portname, - # RTC::ConnectorProfile& profile, - # ReturnCode_t ret) - def onConnectNextport(self, portname, profile, ret): - if self._portconnListeners != None: - type = OpenRTM_aist.PortConnectRetListenerType.ON_CONNECT_NEXTPORT - self._portconnListeners.portconnret_[type].notify(portname, profile, ret) - return - - - #inline void onSubscribeInterfaces(const char* portname, - # RTC::ConnectorProfile& profile, - # ReturnCode_t ret) - def onSubscribeInterfaces(self, portname, profile, ret): - if self._portconnListeners != None: - type = OpenRTM_aist.PortConnectRetListenerType.ON_SUBSCRIBE_INTERFACES - self._portconnListeners.portconnret_[type].notify(portname, profile, ret) - return - - - #inline void onConnected(const char* portname, - # RTC::ConnectorProfile& profile, - # ReturnCode_t ret) - def onConnected(self, portname, profile, ret): - if self._portconnListeners != None: - type = OpenRTM_aist.PortConnectRetListenerType.ON_CONNECTED - self._portconnListeners.portconnret_[type].notify(portname, profile, ret) - return - - - #inline void onDisconnectNextport(const char* portname, - # RTC::ConnectorProfile& profile, - # ReturnCode_t ret) - def onDisconnectNextport(self, portname, profile, ret): - if self._portconnListeners != None: - type = OpenRTM_aist.PortConnectRetListenerType.ON_DISCONNECT_NEXT - self._portconnListeners.portconnret_[type].notify(portname, profile, ret) - return - - - #inline void onDisconnected(const char* portname, - # RTC::ConnectorProfile& profile, - # ReturnCode_t ret) - def onDisconnected(self, portname, profile, ret): - if self._portconnListeners != None: - type = OpenRTM_aist.PortConnectRetListenerType.ON_DISCONNECTED - self._portconnListeners.portconnret_[type].notify(portname, profile, ret) - return - - - - #============================================================ - # Functor - #============================================================ - - ## - # @if jp - # @class if_name - # @brief instance_name PortInterfaceProfile õ Functor - # @else - # @brief A functor to find a PortInterfaceProfile named instance_name - # @endif - class if_name: - def __init__(self, name): - self._name = name - - def __call__(self, prof): - return str(self._name) == str(prof.instance_name) - - - ## - # @if jp - # @class find_conn_id - # @brief id ConnectorProfile õ Functor - # @else - # @brief A functor to find a ConnectorProfile named id - # @endif - class find_conn_id: - def __init__(self, id_): - """ - \param id_(string) - """ - self._id = id_ - - def __call__(self, cprof): - """ - \param cprof(RTC.ConnectorProfile) - """ - return str(self._id) == str(cprof.connector_id) - - ## - # @if jp - # @class find_port_ref - # @brief 󥹥ȥ饯 port_ref Ʊ֥ȻȤõ Functor - # @else - # @brief A functor to find the object reference that is identical port_ref - # @endif - class find_port_ref: - def __init__(self, port_ref): - """ - \param port_ref(RTC.PortService) - """ - self._port_ref = port_ref - - def __call__(self, port_ref): - """ - \param port_ref(RTC.PortService) - """ - return self._port_ref._is_equivalent(port_ref) - - ## - # @if jp - # @class connect_func - # @brief Port ³Ԥ Functor - # @else - # @brief A functor to connect Ports - # @endif - class connect_func: - def __init__(self, p, prof): - """ - \param p(RTC.PortService) - \param prof(RTC.ConnectorProfile) - """ - self._port_ref = p - self._connector_profile = prof - self.return_code = RTC.RTC_OK - - def __call__(self, p): - """ - \param p(RTC.PortService) - """ - if not self._port_ref._is_equivalent(p): - retval = p.notify_connect(self._connector_profile) - if retval != RTC.RTC_OK: - self.return_code = retval - - ## - # @if jp - # @class disconnect_func - # @brief Port ³Ԥ Functor - # @else - # @brief A functor to disconnect Ports - # @endif - class disconnect_func: - def __init__(self, p, prof): - """ - \param p(RTC.PortService) - \param prof(RTC.ConnectorProfile) - """ - self._port_ref = p - self._connector_profile = prof - self.return_code = RTC.RTC_OK - - def __call__(self, p): - """ - \param p(RTC.PortService) - """ - if not self._port_ref._is_equivalent(p): - retval = p.disconnect(self._connector_profile.connector_id) - if retval != RTC.RTC_OK: - self.return_code = retval - - ## - # @if jp - # @class disconnect_all_func - # @brief Port ³Ԥ Functor - # @else - # @brief A functor to disconnect all Ports - # @endif - class disconnect_all_func: - def __init__(self, p): - """ - \param p(OpenRTM_aist.PortBase) - """ - self.return_code = RTC.RTC_OK - self._port = p - - def __call__(self, p): - """ - \param p(RTC.ConnectorProfile) - """ - retval = self._port.disconnect(p.connector_id) - if retval != RTC.RTC_OK: - self.return_code = retval - - ## - # @if jp - # @class find_interface - # @brief name polarity interface õ Functor - # @else - # @brief A functor to find interface from name and polarity - # @endif - class find_interface: - def __init__(self, name, pol): - """ - \param name(string) - \param pol(RTC.PortInterfacePolarity) - """ - self._name = name - self._pol = pol - - def __call__(self, prof): - """ - \param prof(RTC.PortInterfaceProfile) - """ - name = prof.instance_name - return (str(self._name) == str(name)) and (self._pol == prof.polarity) + ## + # @if jp + # + # @brief Interface 情報を取得する(サブクラス実装用) + # + # このオペレーションは、notify_connect() 処理シーケンスの中間にコール + # される関数である。 + # notify_connect() では、 + # + # - publishInterfaces() + # - connectNext() + # - subscribeInterfaces() + # - updateConnectorProfile() + # + # の順に protected 関数がコールされ接続処理が行われる。 + #
    + # 具象 Port ではこのオペレーションをオーバーライドし、引数として + # 与えられた ConnectorProfile に従い処理を行い、パラメータが不適切 + # であれば、RteurnCode_t 型のエラーコードを返す。 + # 引数 ConnectorProfile には他の Port の Interface に関する情報が + # 全て含まれている。 + # 通常 subscribeInterafaces() 内においては、この Port が使用する + # Interface に関する情報を取得し、要求側のインターフェースに対して + # 情報を設定しなければならない。 + #
    + # このオペレーションは、新規の connector_id に対しては接続の生成、 + # 既存の connector_id に対しては更新が適切に行われる必要がある。
    + # ※サブクラスでの実装参照用 + # + # @param self + # @param connector_profile 接続に関するプロファイル情報 + # + # @return ReturnCode_t 型のリターンコード + # + # @else + # + # @brief Publish interface information + # + # This operation is pure virutal method that would be called at the + # mid-flow of the notify_connect() process sequence. + # In the notify_connect(), the following methods would be called in order. + # + # - publishInterfaces() + # - connectNext() + # - subscribeInterfaces() + # - updateConnectorProfile() + # + # In the concrete Port, this method should be overridden. This method + # processes the given ConnectorProfile argument and if the given parameter + # is invalid, it would return error code of ReturnCode_t. + # The given argument ConnectorProfile includes all the interfaces + # information in it. + # Usually, subscribeInterafaces() method obtains information of interfaces + # from ConnectorProfile, and should set it to the interfaces that require + # them. + #
    + # This operation should create the new connection for the new + # connector_id, and should update the connection for the existing + # connection_id. + # + # @param connector_profile The connection profile information + # + # @return The return code of ReturnCode_t type. + # + # @endif + + def subscribeInterfaces(self, connector_profile): + pass + + ## + # @if jp + # + # @brief Interface の接続を解除する(サブクラス実装用) + # + # このオペレーションは、notify_disconnect() 処理シーケンスの終わりにコール + # される関数である。 + # notify_disconnect() では、 + # - disconnectNext() + # - unsubscribeInterfaces() + # - eraseConnectorProfile() + # の順に protected 関数がコールされ接続解除処理が行われる。 + #
    + # 具象 Port ではこのオペレーションをオーバーライドし、引数として + # 与えられた ConnectorProfile に従い接続解除処理を行う。
    + # ※サブクラスでの実装参照用 + # + # @param self + # @param connector_profile 接続に関するプロファイル情報 + # + # @else + # + # @brief Disconnect interface connection + # + # This operation is pure virutal method that would be called at the + # end of the notify_disconnect() process sequence. + # In the notify_disconnect(), the following methods would be called. + # - disconnectNext() + # - unsubscribeInterfaces() + # - eraseConnectorProfile() + #
    + # In the concrete Port, this method should be overridden. This method + # processes the given ConnectorProfile argument and disconnect interface + # connection. + # + # @param connector_profile The connection profile information + # + # @endif + + def unsubscribeInterfaces(self, connector_profile): + return RTC.BAD_PARAMETER + + ## + # @if jp + # + # @brief 接続の最大数を設定する。 + # + # @param limit_value 最大数 + # + # @else + # + # @brief Set the maximum number of connections + # + # + # @param limit_value The maximum number of connections + # + # @endif + # + # virtual void setConnectionLimit(int limit_value); + + def setConnectionLimit(self, limit_value): + self._connectionLimit = limit_value + return + + ## + # @if jp + # @brief Interface情報を公開する + # + # Interface情報を公開する。 + # + # dataport.dataflow_type + # + # @return ReturnCode_t 型のリターンコード + # + # @else + # @brief Publish interface information + # + # Publish interface information. + # + # + # @return The return code of ReturnCode_t type + # + # @endif + # + # virtual ReturnCode_t _publishInterfaces(void); + + def _publishInterfaces(self): + if not (self._connectionLimit < 0): + if self._connectionLimit <= len(self._profile.connector_profiles): + self._rtcout.RTC_PARANOID( + "Connected number has reached the limitation.") + self._rtcout.RTC_PARANOID("Can connect the port up to %d ports.", + self._connectionLimit) + self._rtcout.RTC_PARANOID("%d connectors are existing", + len(self._profile.connector_profiles)) + return RTC.RTC_ERROR + + return RTC.RTC_OK + + ## + # @if jp + # + # @brief ConnectorProfile の connector_id フィールドが空かどうか判定 + # + # 指定された ConnectorProfile の connector_id が空であるかどうかの判定を + # 行う。 + # + # @param self + # @param connector_profile 判定対象コネクタプロファイル + # + # @return 引数で与えられた ConnectorProfile の connector_id が空であれば、 + # true、そうでなければ false を返す。 + # + # @else + # + # @brief Whether connector_id of ConnectorProfile is empty + # + # @return If the given ConnectorProfile's connector_id is empty string, + # it returns true. + # + # @endif + # bool isEmptyId(const ConnectorProfile& connector_profile) const; + + def isEmptyId(self, connector_profile): + return connector_profile.connector_id == "" + + ## + # @if jp + # + # @brief UUIDを生成する + # + # このオペレーションは UUID を生成する。 + # + # @param self + # + # @return uuid + # + # @else + # + # @brief Get the UUID + # + # This operation generates UUID. + # + # @return uuid + # + # @endif + # const std::string getUUID() const; + + def getUUID(self): + return str(OpenRTM_aist.uuid1()) + + ## + # @if jp + # + # @brief UUIDを生成し ConnectorProfile にセットする + # + # このオペレーションは UUID を生成し、ConnectorProfile にセットする。 + # + # @param self + # @param connector_profile connector_id をセットする ConnectorProfile + # + # @else + # + # @brief Create and set the UUID to the ConnectorProfile + # + # This operation generates and set UUID to the ConnectorProfile. + # + # @param connector_profile ConnectorProfile to be set connector_id + # + # @endif + # void setUUID(ConnectorProfile& connector_profile) const; + + def setUUID(self, connector_profile): + connector_profile.connector_id = self.getUUID() + assert(connector_profile.connector_id != "") + + ## + # @if jp + # + # @brief id が既存の ConnectorProfile のものかどうか判定する + # + # このオペレーションは与えられた ID が既存の ConnectorProfile のリスト中に + # 存在するかどうか判定する。 + # + # @param self + # @param id_ 判定する connector_id + # + # @return id の存在判定結果 + # + # @else + # + # @brief Whether the given id exists in stored ConnectorProfiles + # + # This operation returns boolean whether the given id exists in + # the Port's ConnectorProfiles. + # + # @param id connector_id to be find in Port's ConnectorProfiles + # + # @endif + # bool isExistingConnId(const char* id); + + def isExistingConnId(self, id_): + return OpenRTM_aist.CORBA_SeqUtil.find(self._profile.connector_profiles, + self.find_conn_id(id_)) >= 0 + + ## + # @if jp + # + # @brief id を持つ ConnectorProfile を探す + # + # このオペレーションは与えられた ID を持つ ConnectorProfile を Port が + # もつ ConnectorProfile のリスト中から探す。 + # もし、同一の id を持つ ConnectorProfile がなければ、空の ConnectorProfile + # が返される。 + # + # @param self + # @param id_ 検索する connector_id + # + # @return connector_id を持つ ConnectorProfile + # + # @else + # + # @brief Find ConnectorProfile with id + # + # This operation returns ConnectorProfile with the given id from Port's + # ConnectorProfiles' list. + # If the ConnectorProfile with connector id that is identical with the + # given id does not exist, empty ConnectorProfile is returned. + # + # @param id the connector_id to be searched in Port's ConnectorProfiles + # + # @return CoonectorProfile with connector_id + # + # @endif + # ConnectorProfile findConnProfile(const char* id); + + def findConnProfile(self, id_): + index = OpenRTM_aist.CORBA_SeqUtil.find(self._profile.connector_profiles, + self.find_conn_id(id_)) + if index < 0 or index >= len(self._profile.connector_profiles): + return RTC.ConnectorProfile("", "", [], []) + + return self._profile.connector_profiles[index] + + ## + # @if jp + # + # @brief id を持つ ConnectorProfile を探す + # + # このオペレーションは与えられた ID を持つ ConnectorProfile を Port が + # もつ ConnectorProfile のリスト中から探しインデックスを返す。 + # もし、同一の id を持つ ConnectorProfile がなければ、-1 を返す。 + # + # @param self + # @param id_ 検索する connector_id + # + # @return Port の ConnectorProfile リストのインデックス + # + # @else + # + # @brief Find ConnectorProfile with id + # + # This operation returns ConnectorProfile with the given id from Port's + # ConnectorProfiles' list. + # If the ConnectorProfile with connector id that is identical with the + # given id does not exist, empty ConnectorProfile is returned. + # + # @param id the connector_id to be searched in Port's ConnectorProfiles + # + # @return The index of ConnectorProfile of the Port + # + # @endif + # CORBA::Long findConnProfileIndex(const char* id); + + def findConnProfileIndex(self, id_): + return OpenRTM_aist.CORBA_SeqUtil.find(self._profile.connector_profiles, + self.find_conn_id(id_)) + + ## + # @if jp + # + # @brief ConnectorProfile の追加もしくは更新 + # + # このオペレーションは与えられた与えられた ConnectorProfile を + # Port に追加もしくは更新保存する。 + # 与えられた ConnectorProfile の connector_id と同じ ID を持つ + # ConnectorProfile がリストになければ、リストに追加し、 + # 同じ ID が存在すれば ConnectorProfile を上書き保存する。 + # + # @param self + # @param connector_profile 追加もしくは更新する ConnectorProfile + # + # @else + # + # @brief Append or update the ConnectorProfile list + # + # This operation appends or updates ConnectorProfile of the Port + # by the given ConnectorProfile. + # If the connector_id of the given ConnectorProfile does not exist + # in the Port's ConnectorProfile list, the given ConnectorProfile would be + # append to the list. If the same id exists, the list would be updated. + # + # @param connector_profile the ConnectorProfile to be appended or updated + # + # @endif + # void updateConnectorProfile(const ConnectorProfile& connector_profile); + + def updateConnectorProfile(self, connector_profile): + index = OpenRTM_aist.CORBA_SeqUtil.find(self._profile.connector_profiles, + self.find_conn_id(connector_profile.connector_id)) + + if index < 0: + OpenRTM_aist.CORBA_SeqUtil.push_back(self._profile.connector_profiles, + connector_profile) + else: + self._profile.connector_profiles[index] = connector_profile + + ## + # @if jp + # + # @brief ConnectorProfile を削除する + # + # このオペレーションは Port の PortProfile が保持している + # ConnectorProfileList のうち与えられた id を持つ ConnectorProfile + # を削除する。 + # + # @param self + # @param id_ 削除する ConnectorProfile の id + # + # @return 正常に削除できた場合は true、 + # 指定した ConnectorProfile が見つからない場合は false を返す + # + # @else + # + # @brief Delete the ConnectorProfile + # + # This operation deletes a ConnectorProfile specified by id from + # ConnectorProfileList owned by PortProfile of this Port. + # + # @param id The id of the ConnectorProfile to be deleted. + # + # @endif + # bool eraseConnectorProfile(const char* id); + + def eraseConnectorProfile(self, id_): + guard = OpenRTM_aist.ScopedLock(self._profile_mutex) + + index = OpenRTM_aist.CORBA_SeqUtil.find(self._profile.connector_profiles, + self.find_conn_id(id_)) + + if index < 0: + return False + + OpenRTM_aist.CORBA_SeqUtil.erase( + self._profile.connector_profiles, index) + + return True + + ## + # @if jp + # + # @brief PortInterfaceProfile に インターフェースを登録する + # + # このオペレーションは Port が持つ PortProfile の、PortInterfaceProfile + # にインターフェースの情報を追加する。 + # この情報は、get_port_profile() 似よって得られる PortProfile のうち + # PortInterfaceProfile の値を変更するのみであり、実際にインターフェースを + # 提供したり要求したりする場合には、サブクラスで、 publishInterface() , + # subscribeInterface() 等の関数を適切にオーバーライドしインターフェースの + # 提供、要求処理を行わなければならない。 + # + # インターフェース(のインスタンス)名は Port 内で一意でなければならない。 + # 同名のインターフェースがすでに登録されている場合、この関数は false を + # 返す。 + # + # @param self + # @param instance_name インターフェースのインスタンスの名前 + # @param type_name インターフェースの型の名前 + # @param pol インターフェースの属性 (RTC::PROVIDED もしくは RTC:REQUIRED) + # + # @return インターフェース登録処理結果。 + # 同名のインターフェースが既に登録されていれば false を返す。 + # + # @else + # + # @brief Append an interface to the PortInterfaceProfile + # + # This operation appends interface information to the PortInterfaceProfile + # that is owned by the Port. + # The given interfaces information only updates PortInterfaceProfile of + # PortProfile that is obtained through get_port_profile(). + # In order to provide and require interfaces, proper functions (for + # example publishInterface(), subscribeInterface() and so on) should be + # overridden in subclasses, and these functions provide concrete interface + # connection and disconnection functionality. + # + # The interface (instance) name have to be unique in the Port. + # If the given interface name is identical with stored interface name, + # this function returns false. + # + # @param name The instance name of the interface. + # @param type_name The type name of the interface. + # @param pol The interface's polarity (RTC::PROVIDED or RTC:REQUIRED) + # + # @return false would be returned if the same name is already registered. + # + # @endif + # bool appendInterface(const char* name, const char* type_name, + # PortInterfacePolarity pol); + + def appendInterface(self, instance_name, type_name, pol): + index = OpenRTM_aist.CORBA_SeqUtil.find(self._profile.interfaces, + self.find_interface(instance_name, pol)) + + if index >= 0: + return False + + # setup PortInterfaceProfile + prof = RTC.PortInterfaceProfile(instance_name, type_name, pol) + OpenRTM_aist.CORBA_SeqUtil.push_back(self._profile.interfaces, prof) + + return True + + ## + # @if jp + # + # @brief PortInterfaceProfile からインターフェース登録を削除する + # + # このオペレーションは Port が持つ PortProfile の、PortInterfaceProfile + # からインターフェースの情報を削除する。 + # + # @param self + # @param name インターフェースのインスタンスの名前 + # @param pol インターフェースの属性 (RTC::PROVIDED もしくは RTC:REQUIRED) + # + # @return インターフェース削除処理結果。 + # インターフェースが登録されていなければ false を返す。 + # + # @else + # + # @brief Delete an interface from the PortInterfaceProfile + # + # This operation deletes interface information from the + # PortInterfaceProfile that is owned by the Port. + # + # @param name The instance name of the interface. + # @param pol The interface's polarity (RTC::PROVIDED or RTC:REQUIRED) + # + # @return false would be returned if the given name is not registered. + # + # @endif + # bool deleteInterface(const char* name, PortInterfacePolarity pol); + + def deleteInterface(self, name, pol): + index = OpenRTM_aist.CORBA_SeqUtil.find(self._profile.interfaces, + self.find_interface(name, pol)) + + if index < 0: + return False + + OpenRTM_aist.CORBA_SeqUtil.erase(self._profile.interfaces, index) + return True + + ## + # @if jp + # + # @brief PortProfile の properties に NameValue 値を追加する + # + # PortProfile の properties に NameValue 値を追加する。 + # 追加するデータの型をValueTypeで指定する。 + # + # @param self + # @param key properties の name + # @param value properties の value + # + # @else + # + # @brief Add NameValue data to PortProfile's properties + # + # @param key The name of properties + # @param value The value of properties + # + # @endif + # template + # void addProperty(const char* key, ValueType value) + + def addProperty(self, key, value): + OpenRTM_aist.CORBA_SeqUtil.push_back(self._profile.properties, + OpenRTM_aist.NVUtil.newNV(key, value)) + + ## + # @if jp + # + # @brief PortProfile の properties に NameValue 値を要素に追加する + # + # PortProfile の properties に NameValue 値を要素に追加する。 + # + # @param key properties の name + # @param value properties の value + # + # @else + # + # @brief Append NameValue data to PortProfile's properties + # + # Append NameValue data to PortProfile's properties. + # + # @param key The name of properties + # @param value The value of properties + # + # @endif + # void appendProperty(const char* key, const char* value) + def appendProperty(self, key, value): + OpenRTM_aist.NVUtil.appendStringValue( + self._profile.properties, key, value) + + ## + # @if jp + # + # @brief 存在しないポートをdisconnectする。 + # + # @else + # + # @brief Disconnect ports that doesn't exist. + # + # @endif + # void updateConnectors() + + def updateConnectors(self): + guard = OpenRTM_aist.ScopedLock(self._profile_mutex) + + connector_ids = [] + clist = self._profile.connector_profiles + + for cprof in clist: + if not self.checkPorts(cprof.ports): + connector_ids.append(cprof.connector_id) + self._rtcout.RTC_WARN( + "Dead connection: %s", cprof.connector_id) + + for cid in connector_ids: + self.disconnect(cid) + + return + + ## + # @if jp + # + # @brief ポートの存在を確認する。 + # + # @param ports 確認するポート + # @return true:存在する,false:存在しない + # + # @else + # + # @brief Existence of ports + # + # @param ports Checked ports + # @return true:existent,false:non existent + # + # @endif + # bool checkPorts(::RTC::PortServiceList& ports) + + def checkPorts(self, ports): + for port in ports: + try: + if port._non_existent(): + self._rtcout.RTC_WARN("Dead Port reference detected.") + return False + except BaseException: + self._rtcout.RTC_WARN(OpenRTM_aist.Logger.print_exception()) + return False + + return True + + # inline void onNotifyConnect(const char* portname, + # RTC::ConnectorProfile& profile) + + def onNotifyConnect(self, portname, profile): + if self._portconnListeners is not None: + type = OpenRTM_aist.PortConnectListenerType.ON_NOTIFY_CONNECT + self._portconnListeners.notify(type, portname, profile) + return + + # inline void onNotifyDisconnect(const char* portname, + # RTC::ConnectorProfile& profile) + + def onNotifyDisconnect(self, portname, profile): + if self._portconnListeners is not None: + type = OpenRTM_aist.PortConnectListenerType.ON_NOTIFY_DISCONNECT + self._portconnListeners.notify(type, portname, profile) + return + + # inline void onUnsubscribeInterfaces(const char* portname, + # RTC::ConnectorProfile& profile) + + def onUnsubscribeInterfaces(self, portname, profile): + if self._portconnListeners is not None: + type = OpenRTM_aist.PortConnectListenerType.ON_UNSUBSCRIBE_INTERFACES + self._portconnListeners.notify(type, portname, profile) + return + + # inline void onPublishInterfaces(const char* portname, + # RTC::ConnectorProfile& profile, + # ReturnCode_t ret) + + def onPublishInterfaces(self, portname, profile, ret): + if self._portconnListeners is not None: + type = OpenRTM_aist.PortConnectRetListenerType.ON_PUBLISH_INTERFACES + self._portconnListeners.notifyRet(type, portname, profile, ret) + return + + # inline void onConnectNextport(const char* portname, + # RTC::ConnectorProfile& profile, + # ReturnCode_t ret) + + def onConnectNextport(self, portname, profile, ret): + if self._portconnListeners is not None: + type = OpenRTM_aist.PortConnectRetListenerType.ON_CONNECT_NEXTPORT + self._portconnListeners.notifyRet(type, portname, profile, ret) + return + + # inline void onSubscribeInterfaces(const char* portname, + # RTC::ConnectorProfile& profile, + # ReturnCode_t ret) + + def onSubscribeInterfaces(self, portname, profile, ret): + if self._portconnListeners is not None: + type = OpenRTM_aist.PortConnectRetListenerType.ON_SUBSCRIBE_INTERFACES + self._portconnListeners.notifyRet(type, portname, profile, ret) + return + + # inline void onConnected(const char* portname, + # RTC::ConnectorProfile& profile, + # ReturnCode_t ret) + + def onConnected(self, portname, profile, ret): + if self._portconnListeners is not None: + type = OpenRTM_aist.PortConnectRetListenerType.ON_CONNECTED + self._portconnListeners.notifyRet(type, portname, profile, ret) + return + + # inline void onDisconnectNextport(const char* portname, + # RTC::ConnectorProfile& profile, + # ReturnCode_t ret) + + def onDisconnectNextport(self, portname, profile, ret): + if self._portconnListeners is not None: + type = OpenRTM_aist.PortConnectRetListenerType.ON_DISCONNECT_NEXT + self._portconnListeners.notifyRet(type, portname, profile, ret) + return + + # inline void onDisconnected(const char* portname, + # RTC::ConnectorProfile& profile, + # ReturnCode_t ret) + + def onDisconnected(self, portname, profile, ret): + if self._portconnListeners is not None: + type = OpenRTM_aist.PortConnectRetListenerType.ON_DISCONNECTED + self._portconnListeners.notifyRet(type, portname, profile, ret) + return + + ## + # @if jp + # + # @brief 指定のシリアライザが利用可能かを判定する + # @param self + # @param con_prop プロパティ + # @return True:利用可能、False:利用不可 + # + # @else + # + # @brief + # @param self + # @param con_prop + # @return + # + # @endif + # void updateConnectors() + def isExistingMarshalingType(self, con_prop): + marshaling_type = con_prop.getProperty( + "marshaling_type", "cdr") + marshaling_type = marshaling_type.strip() + prop = OpenRTM_aist.Properties() + OpenRTM_aist.NVUtil.copyToProperties(prop, self._profile.properties) + + serializertypes = prop.getProperty("dataport.marshaling_types") + + enabledSerializerTypes = [s.strip() + for s in serializertypes.split(",")] + if marshaling_type not in enabledSerializerTypes: + self._rtcout.RTC_ERROR( + marshaling_type+" is illegal marshaling type.") + return False + return True + + # ============================================================ + # Functor + # ============================================================ + + ## + # @if jp + # @class if_name + # @brief instance_name を持つ PortInterfaceProfile を探す Functor + # @else + # @brief A functor to find a PortInterfaceProfile named instance_name + # @endif + + class if_name: + def __init__(self, name): + self._name = name + + def __call__(self, prof): + return str(self._name) == str(prof.instance_name) + + ## + # @if jp + # @class find_conn_id + # @brief id を持つ ConnectorProfile を探す Functor + # @else + # @brief A functor to find a ConnectorProfile named id + # @endif + + class find_conn_id: + def __init__(self, id_): + """ + \param id_(string) + """ + self._id = id_ + + def __call__(self, cprof): + """ + \param cprof(RTC.ConnectorProfile) + """ + return str(self._id) == str(cprof.connector_id) + + ## + # @if jp + # @class find_port_ref + # @brief コンストラクタ引数 port_ref と同じオブジェクト参照を探す Functor + # @else + # @brief A functor to find the object reference that is identical port_ref + # @endif + class find_port_ref: + def __init__(self, port_ref): + """ + \param port_ref(RTC.PortService) + """ + self._port_ref = port_ref + + def __call__(self, port_ref): + """ + \param port_ref(RTC.PortService) + """ + return self._port_ref._is_equivalent(port_ref) + + ## + # @if jp + # @class connect_func + # @brief Port の接続を行う Functor + # @else + # @brief A functor to connect Ports + # @endif + class connect_func: + def __init__(self, p, prof): + """ + \param p(RTC.PortService) + \param prof(RTC.ConnectorProfile) + """ + self._port_ref = p + self._connector_profile = prof + self.return_code = RTC.RTC_OK + + def __call__(self, p): + """ + \param p(RTC.PortService) + """ + if not self._port_ref._is_equivalent(p): + retval = p.notify_connect(self._connector_profile) + if retval != RTC.RTC_OK: + self.return_code = retval + + ## + # @if jp + # @class disconnect_func + # @brief Port の接続解除を行う Functor + # @else + # @brief A functor to disconnect Ports + # @endif + class disconnect_func: + def __init__(self, p, prof): + """ + \param p(RTC.PortService) + \param prof(RTC.ConnectorProfile) + """ + self._port_ref = p + self._connector_profile = prof + self.return_code = RTC.RTC_OK + + def __call__(self, p): + """ + \param p(RTC.PortService) + """ + if not self._port_ref._is_equivalent(p): + retval = p.disconnect(self._connector_profile.connector_id) + if retval != RTC.RTC_OK: + self.return_code = retval + + ## + # @if jp + # @class disconnect_all_func + # @brief Port の全接続解除を行う Functor + # @else + # @brief A functor to disconnect all Ports + # @endif + class disconnect_all_func: + def __init__(self, p): + """ + \param p(OpenRTM_aist.PortBase) + """ + self.return_code = RTC.RTC_OK + self._port = p + + def __call__(self, p): + """ + \param p(RTC.ConnectorProfile) + """ + retval = self._port.disconnect(p.connector_id) + if retval != RTC.RTC_OK: + self.return_code = retval + + ## + # @if jp + # @class find_interface + # @brief name と polarity から interface を探す Functor + # @else + # @brief A functor to find interface from name and polarity + # @endif + class find_interface: + def __init__(self, name, pol): + """ + \param name(string) + \param pol(RTC.PortInterfacePolarity) + """ + self._name = name + self._pol = pol + + def __call__(self, prof): + """ + \param prof(RTC.PortInterfaceProfile) + """ + name = prof.instance_name + return (str(self._name) == str(name)) and ( + self._pol == prof.polarity) diff --git a/OpenRTM_aist/PortCallBack.py b/OpenRTM_aist/PortCallBack.py index 40ec7bc3..9c5fb9b9 100644 --- a/OpenRTM_aist/PortCallBack.py +++ b/OpenRTM_aist/PortCallBack.py @@ -1,5 +1,5 @@ #!/usr/bin/env python -# -*- coding: euc-jp -*- +# -*- coding: utf-8 -*- ## @@ -7,7 +7,7 @@ # @brief PortCallBack class # @date $Date: 2007/09/20 $ # @author Noriaki Ando and Shinji Kurihara -# +# # Copyright (C) 2006-2008 # Noriaki Ando # Task-intelligence Research Group, @@ -15,19 +15,19 @@ # National Institute of # Advanced Industrial Science and Technology (AIST), Japan # All rights reserved. - -#============================================================ + +# ============================================================ # callback functor base classes # ## # @if jp # @class ConnectCallback -# @brief connect/notify_connect() ΥХåݥ饹 +# @brief connect/notify_connect() 時のコールバック抽象クラス # -# PortФconnect/notify_connect() ƤӽФ˸ƤӽФ -# Хåե󥯥 RTC::ConnectorProfile 롣 +# Portに対してconnect/notify_connect() 等が呼び出される時に呼び出される +# コールバックファンクタ。引数に RTC::ConnectorProfile を取る。 # # @param profile ConnectorProfile # @@ -48,44 +48,44 @@ # @endif # class ConnectionCallback: - """ - """ + """ + """ - ## - # @if jp - # - # @brief Хåؿ - # - # connect/notify_connect() ƤӽФ˸ƤӽФ - # Хåؿ - # - # @param self - # @param profile ConnectorProfile - # - # @else - # - # @brief Callback method - # - # This is the callback method invoked when connect/notify_connect() - # invocation in Port. - # - # @param self - # @param profile ConnectorProfile - # - # @endif - # - # virtual void operator()(RTC::ConnectorProfile& profile) = 0; - def __call__(self, profile): - pass + ## + # @if jp + # + # @brief コールバック関数 + # + # connect/notify_connect() 等が呼び出される時に呼び出される + # コールバック関数 + # + # @param self + # @param profile ConnectorProfile + # + # @else + # + # @brief Callback method + # + # This is the callback method invoked when connect/notify_connect() + # invocation in Port. + # + # @param self + # @param profile ConnectorProfile + # + # @endif + # + # virtual void operator()(RTC::ConnectorProfile& profile) = 0; + def __call__(self, profile): + pass ## # @if jp # @class DisconnectCallback -# @brief disconnect/notify_disconnect() ΥХåݥ饹 +# @brief disconnect/notify_disconnect() 時のコールバック抽象クラス # -# PortФdisconnect/notify_disconnect() ƤӽФ˸ƤӽФ -# Хåե󥯥³ID롣 +# Portに対してdisconnect/notify_disconnect() 等が呼び出される時に呼び出される +# コールバックファンクタ。引数に接続IDを取る。 # # @since 1.0.0 # @@ -93,7 +93,7 @@ def __call__(self, profile): # @class DisconnectCallback # @brief Callback functor abstract for disconnect/notify_disconnect() funcs # -# This is the interface for callback functor for +# This is the interface for callback functor for # disconnect/notify_disconnect() invocation in Port. # Argument is connector ID is given these functions. # @@ -102,44 +102,44 @@ def __call__(self, profile): # @endif # class DisconnectCallback: - """ - """ + """ + """ - ## - # @if jp - # - # @brief Хåؿ - # - # disconnect/notify_disconnect() ƤӽФ˸ƤӽФ - # Хåؿ - # - # @param self - # @param connector_id Connector ID - # - # @else - # - # @brief Callback method - # - # This is the callback method invoked when disconnect/notify_disconnect() - # invocation in Port. - # - # @param self - # @param connector_id Connector ID - # - # @endif - # - # virtual void operator()(const char* connector_id) = 0; - def __call__(self, connector_id): - pass + ## + # @if jp + # + # @brief コールバック関数 + # + # disconnect/notify_disconnect() 等が呼び出される時に呼び出される + # コールバック関数 + # + # @param self + # @param connector_id Connector ID + # + # @else + # + # @brief Callback method + # + # This is the callback method invoked when disconnect/notify_disconnect() + # invocation in Port. + # + # @param self + # @param connector_id Connector ID + # + # @endif + # + # virtual void operator()(const char* connector_id) = 0; + def __call__(self, connector_id): + pass ## # @if jp # @class OnWrite -# @brief write() ΥХå饹(֥饹) +# @brief write() 時のコールバッククラス(サブクラス実装用) # -# DataPortΥХåե˥ǡwrite()ľ˸ƤӽФ륳Хå
    -# ֥饹Ǥμ +# DataPortのバッファにデータがwrite()される直前に呼び出されるコールバック用
    +# ※サブクラスでの実装参照用 # # @since 0.4.0 # @@ -149,45 +149,44 @@ def __call__(self, connector_id): # # @endif class OnWrite: - """ - """ - - ## - # @if jp - # - # @brief Хåؿ - # - # Хåե˥ǡ񤭹ޤľ˸ƤӽФ륳Хåؿ - # - # @param self - # @param value Хåե˽񤭹ޤǡ - # - # @else - # - # @brief Callback function - # - # This is the callback method invoked immediately before data is written - # into the buffer. - # - # @param self - # @param value Data that is written into the buffer - # - # @endif - # - def __call__(self, value): - pass + """ + """ + ## + # @if jp + # + # @brief コールバック関数 + # + # バッファにデータが書き込まれる直前に呼び出されるコールバック関数 + # + # @param self + # @param value バッファに書き込まれるデータ + # + # @else + # + # @brief Callback function + # + # This is the callback method invoked immediately before data is written + # into the buffer. + # + # @param self + # @param value Data that is written into the buffer + # + # @endif + # + def __call__(self, value): + pass ## # @if jp # @class OnWriteConvert -# @brief write() ΥǡѴХå饹(֥饹) +# @brief write() 時のデータ変換コールバッククラス(サブクラス実装用) # -# InPort/OutPortΥХåե˥ǡ write()˸ƤӽФ
    -# ֥饹Ǥμ -# Хåѥ󥿡ե -# ΥХåͤХåե˳Ǽ롣 +# InPort/OutPortのバッファにデータが write()される時に呼び出される
    +# ※サブクラスでの実装参照用 +# コールバック用インターフェース。 +# このコールバックの戻り値がバッファに格納される。 # # @since 0.4.0 # @@ -197,46 +196,45 @@ def __call__(self, value): # # @endif class OnWriteConvert: - """ - """ - - ## - # @if jp - # - # @brief Хåؿ - # - # Хåե˥ǡ񤭹ޤݤ˸ƤӽФ륳Хåؿ - # - # @param self - # @param value Ѵǡ - # @return Ѵǡ - # - # @else - # - # @brief Callback function - # - # This is the callback function invoked when data is written into the - # buffer. - # - # @param self - # @param value Data to be converted - # @return Converted data - # - # @endif - # - def __call__(self,value): - pass + """ + """ + ## + # @if jp + # + # @brief コールバック関数 + # + # バッファにデータが書き込まれる際に呼び出されるコールバック関数。 + # + # @param self + # @param value 変換前データ + # @return 変換後データ + # + # @else + # + # @brief Callback function + # + # This is the callback function invoked when data is written into the + # buffer. + # + # @param self + # @param value Data to be converted + # @return Converted data + # + # @endif + # + def __call__(self, value): + pass ## # @if jp # @class OnRead -# @brief read() ΥХå饹(֥饹) +# @brief read() 時のコールバッククラス(サブクラス実装用) # -# InPort/OutPortΥХåեǡ read()ľ˸ƤӽФ -# Хåѥ󥿡ե
    -# ֥饹Ǥμ +# InPort/OutPortのバッファからデータが read()される直線に呼び出される +# コールバック用インターフェース。
    +# ※サブクラスでの実装参照用 # # @since 0.4.0 # @@ -246,38 +244,37 @@ def __call__(self,value): # # @endif class OnRead: - """ - """ - - ## - # @if jp - # - # @brief Хå᥽å - # - # Хåեǡɤ߽Фľ˸ƤӽФ륳Хåؿ - # - # @else - # - # @brief Callback function - # - # This is the callback method invoked immediately before data is readout - # from the buffer. - # - # @endif - def __call__(self): - pass + """ + """ + ## + # @if jp + # + # @brief コールバックメソッド + # + # バッファからデータが読み出される直前に呼び出されるコールバック関数。 + # + # @else + # + # @brief Callback function + # + # This is the callback method invoked immediately before data is readout + # from the buffer. + # + # @endif + def __call__(self): + pass ## # @if jp # @class OnReadConvert -# @brief read() ΥǡѴХå饹(֥饹) +# @brief read() 時のデータ変換コールバッククラス(サブクラス実装用) # -# InPort/OutPortΥХåեǡ read()ݤ˸ƤӽФ -# Хåѥ󥿡ե -# ΥХåͤread()ͤȤʤ롣
    -# ֥饹Ǥμ +# InPort/OutPortのバッファからデータが read()される際に呼び出される +# コールバック用インターフェース。 +# このコールバックの戻り値がread()の戻り値となる。
    +# ※サブクラスでの実装参照用 # # @since 0.4.0 # @@ -287,36 +284,36 @@ def __call__(self): # # @endif class OnReadConvert: - """ - """ + """ + """ - ## - # @if jp - # - # @brief Хå᥽å - # - # Хåեǡɤ߽Фݤ˸ƤӽФ륳Хåؿ - # Ǥꡢoperator()() ͤ InPort read() ͤȤʤ롢 - # ޤϥǡѿ˳Ǽ롣 - # - # @param self - # @param value Хåեɤߤ줿ǡ - # @return ѴΥǡǡݡѿˤϤͤǼ롣 - # - # @else - # - # @brief Callback method - # - # This function is the callback function invoked when data is - # readout from the buffer, and the return value of operator()() - # is used as return value of InPort's read() or it is stored in - # the InPort data variable. - # - # @param self - # @param value Data that is readout from buffer - # @return Converted data. These data are stored in the port's variable. - # - # @endif - # - def __call__(self,value): - pass + ## + # @if jp + # + # @brief コールバックメソッド + # + # バッファからデータが読み出される際に呼び出されるコールバック関数 + # であり、operator()() の戻り値は InPort の read() の戻り値となる、 + # またはデータ変数に格納される。 + # + # @param self + # @param value バッファから読みだされたデータ + # @return 変換後のデータ。データポート変数にはこの値が格納される。 + # + # @else + # + # @brief Callback method + # + # This function is the callback function invoked when data is + # readout from the buffer, and the return value of operator()() + # is used as return value of InPort's read() or it is stored in + # the InPort data variable. + # + # @param self + # @param value Data that is readout from buffer + # @return Converted data. These data are stored in the port's variable. + # + # @endif + # + def __call__(self, value): + pass diff --git a/OpenRTM_aist/PortConnectListener.py b/OpenRTM_aist/PortConnectListener.py index ed056d33..d4e9b8ab 100644 --- a/OpenRTM_aist/PortConnectListener.py +++ b/OpenRTM_aist/PortConnectListener.py @@ -1,5 +1,5 @@ #!/usr/bin/env python -# -*- coding: euc-jp -*- +# -*- coding: utf-8 -*- ## # @file PortConnectListener.py @@ -15,84 +15,87 @@ import threading + class Lock: - """ - """ - - ## - # @if jp - # @brief 󥹥ȥ饯 - # - # 󥹥ȥ饯 - # - # @param self - # @param mutex åѥߥ塼ƥå - # - # @else - # - # @endif - def __init__(self, mutex): - self.mutex = mutex - self.mutex.acquire() - - - ## - # @if jp - # @brief ǥȥ饯 - # - # ǥȥ饯 - # - # @param self - # - # @else - # - # @endif - def __del__(self): - self.mutex.release() - -#============================================================ + """ + """ + + ## + # @if jp + # @brief コンストラクタ + # + # コンストラクタ + # + # @param self + # @param mutex ロック用ミューテックス + # + # @else + # + # @endif + def __init__(self, mutex): + self.mutex = mutex + self.mutex.acquire() + + ## + # @if jp + # @brief デストラクタ + # + # デストラクタ + # + # @param self + # + # @else + # + # @endif + + def __del__(self): + self.mutex.release() + +# ============================================================ ## # @if jp -# @brief PortConnectListener Υ +# @brief PortConnectListener のタイプ # -# - ON_NOTIFY_CONNECT: notify_connect() ؿƤӽФľ -# - ON_NOTIFY_DISCONNECT: notify_disconnect() ƤӽФľ -# - ON_UNSUBSCRIBE_INTERFACES: notify_disconnect() IFɲ +# - ON_NOTIFY_CONNECT: notify_connect() 関数内呼び出し直後 +# - ON_NOTIFY_DISCONNECT: notify_disconnect() 呼び出し直後 +# - ON_UNSUBSCRIBE_INTERFACES: notify_disconnect() 内のIF購読解除時 # # @else # @brief The types of ConnectorDataListener -# +# # - ON_NOTIFY_CONNECT: right after entering into notify_connect() # - ON_NOTIFY_DISCONNECT: right after entering into notify_disconnect() # - ON_UNSUBSCRIBE_INTERFACES: unsubscribing IF in notify_disconnect() # # @endif -class PortConnectListenerType: - """ - """ - ON_NOTIFY_CONNECT = 0 - ON_NOTIFY_DISCONNECT = 1 - ON_UNSUBSCRIBE_INTERFACES = 2 - PORT_CONNECT_LISTENER_NUM = 3 - def __init__(self): - pass +class PortConnectListenerType: + """ + """ + + ON_NOTIFY_CONNECT = 0 + ON_NOTIFY_DISCONNECT = 1 + ON_UNSUBSCRIBE_INTERFACES = 2 + ON_UPDATE_CONFIG_PARAM = 3 + PORT_CONNECT_LISTENER_NUM = 4 + def __init__(self): + pass ## # @if jp -# @class PortConnectListener 饹 -# @brief PortConnectListener 饹 +# @class PortConnectListener クラス +# @brief PortConnectListener クラス # -# ƥб桼ɤƤФľΥߥ -# ǥ뤵ꥹʥ饹δ쥯饹 +# 各アクションに対応するユーザーコードが呼ばれる直前のタイミング +# でコールされるリスナクラスの基底クラス。 # -# - ON_NOTIFY_CONNECT: notify_connect() ؿƤӽФľ -# - ON_NOTIFY_DISCONNECT: notify_disconnect() ƤӽФľ -# - ON_UNSUBSCRIBE_INTERFACES: notify_disconnect() IFɲ +# - ON_NOTIFY_CONNECT: notify_connect() 関数内呼び出し直後 +# - ON_NOTIFY_DISCONNECT: notify_disconnect() 呼び出し直後 +# - ON_UNSUBSCRIBE_INTERFACES: notify_disconnect() 内のIF購読解除時 # # @else # @class PortConnectListener class @@ -107,95 +110,93 @@ def __init__(self): # # @endif class PortConnectListener: - """ - """ - - def __init__(self): - pass - - ## - # @if jp - # - # @brief PortConnectListenerType ʸѴ - # - # PortConnectListenerType ʸѴ - # - # @param type Ѵо PortConnectListenerType - # - # @return ʸѴ - # - # @else - # - # @brief Convert PortConnectListenerType into the string. - # - # Convert PortConnectListenerType into the string. - # - # @param type The target PortConnectListenerType for transformation - # - # @return Trnasformation result of string representation - # - # @endif - #static const char* toString(PortConnectListenerType type); - def toString(type): - typeString = ["ON_NOTIFY_CONNECT", - "ON_NOTIFY_DISCONNECT", - "ON_UNSUBSCRIBE_INTERFACES", - "ON_UPDATE_CONFIG_PARAM", - ""] - - if type < PortConnectListenerType.PORT_CONNECT_LISTENER_NUM: - return typeString[type] - - return "" - - toString = staticmethod(toString) - - - ## - # @if jp - # @brief ǥȥ饯 - # @else - # @brief Destructor - # @endif - def __del__(self): - pass - - - ## - # @if jp - # - # @brief ۥХåؿ - # - # PortConnectListener ΥХåؿ - # - # @else - # - # @brief Virtual Callback function - # - # This is a the Callback function for PortConnectListener. - # - # @endif - #virtual void operator()(const char* portname, - # RTC::ConnectorProfile& profile) = 0; - def __call__(self, portname, profile): - return - - - -#============================================================ + """ + """ + + def __init__(self): + pass + + ## + # @if jp + # + # @brief PortConnectListenerType を文字列に変換 + # + # PortConnectListenerType を文字列に変換する + # + # @param type 変換対象 PortConnectListenerType + # + # @return 文字列変換結果 + # + # @else + # + # @brief Convert PortConnectListenerType into the string. + # + # Convert PortConnectListenerType into the string. + # + # @param type The target PortConnectListenerType for transformation + # + # @return Trnasformation result of string representation + # + # @endif + # static const char* toString(PortConnectListenerType type); + def toString(status): + typeString = ["ON_NOTIFY_CONNECT", + "ON_NOTIFY_DISCONNECT", + "ON_UNSUBSCRIBE_INTERFACES", + "ON_UPDATE_CONFIG_PARAM"] + + if status < len(typeString): + return typeString[status] + + return "" + + toString = staticmethod(toString) + + ## + # @if jp + # @brief デストラクタ + # @else + # @brief Destructor + # @endif + + def __del__(self): + pass + + ## + # @if jp + # + # @brief 仮想コールバック関数 + # + # PortConnectListener のコールバック関数 + # + # @else + # + # @brief Virtual Callback function + # + # This is a the Callback function for PortConnectListener. + # + # @endif + # virtual void operator()(const char* portname, + # RTC::ConnectorProfile& profile) = 0; + + def __call__(self, portname, profile): + return + + +# ============================================================ ## # @if jp -# @brief PortConnectRetListenerType Υ +# @brief PortConnectRetListenerType のタイプ # -# - ON_CONNECT_NEXTPORT: notify_connect() ΥɸƤӽФľ -# - ON_SUBSCRIBE_INTERFACES: notify_connect() Υ󥿡եľ -# - ON_CONNECTED: nofity_connect() ³λ˸ƤӽФ -# - ON_DISCONNECT_NEXT: notify_disconnect() ˥ɸƤӽФľ -# - ON_DISCONNECTED: notify_disconnect() ꥿ +# - ON_CONNECT_NEXTPORT: notify_connect() 中のカスケード呼び出し直後 +# - ON_SUBSCRIBE_INTERFACES: notify_connect() 中のインターフェース購読直後 +# - ON_CONNECTED: nofity_connect() 接続処理完了時に呼び出される +# - ON_DISCONNECT_NEXT: notify_disconnect() 中にカスケード呼び出し直後 +# - ON_DISCONNECTED: notify_disconnect() リターン時 # # @else # @brief The types of PortConnectRetListenerType -# +# # - ON_CONNECT_NEXTPORT: after cascade-call in notify_connect() # - ON_SUBSCRIBE_INTERFACES: after IF subscribing in notify_connect() # - ON_CONNECTED: completed nofity_connect() connection process @@ -204,36 +205,35 @@ def __call__(self, portname, profile): # # @endif class PortConnectRetListenerType: - """ - """ + """ + """ - ON_PUBLISH_INTERFACES = 0 - ON_CONNECT_NEXTPORT = 1 - ON_SUBSCRIBE_INTERFACES = 2 - ON_CONNECTED = 3 - ON_DISCONNECT_NEXT = 4 - ON_DISCONNECTED = 5 - PORT_CONNECT_RET_LISTENER_NUM = 6 - - def __init__(self): - pass + ON_PUBLISH_INTERFACES = 0 + ON_CONNECT_NEXTPORT = 1 + ON_SUBSCRIBE_INTERFACES = 2 + ON_CONNECTED = 3 + ON_DISCONNECT_NEXT = 4 + ON_DISCONNECTED = 5 + PORT_CONNECT_RET_LISTENER_NUM = 6 + def __init__(self): + pass ## # @if jp -# @class PortConnectRetListener 饹 -# @brief PortConnectRetListener 饹 +# @class PortConnectRetListener クラス +# @brief PortConnectRetListener クラス # -# ƥб桼ɤƤФľΥߥ -# ǥ뤵ꥹʥ饹δ쥯饹 +# 各アクションに対応するユーザーコードが呼ばれる直前のタイミング +# でコールされるリスなクラスの基底クラス。 # -# - ON_PUBLISH_INTERFACES: notify_connect() Υ󥿡եľ -# - ON_CONNECT_NEXTPORT: notify_connect() ΥɸƤӽФľ -# - ON_SUBSCRIBE_INTERFACES: notify_connect() Υ󥿡եľ -# - ON_CONNECTED: nofity_connect() ³λ˸ƤӽФ -# - ON_DISCONNECT_NEXT: notify_disconnect() ˥ɸƤӽФľ -# - ON_DISCONNECTED: notify_disconnect() ꥿ +# - ON_PUBLISH_INTERFACES: notify_connect() 中のインターフェース公開直後 +# - ON_CONNECT_NEXTPORT: notify_connect() 中のカスケード呼び出し直後 +# - ON_SUBSCRIBE_INTERFACES: notify_connect() 中のインターフェース購読直後 +# - ON_CONNECTED: nofity_connect() 接続処理完了時に呼び出される +# - ON_DISCONNECT_NEXT: notify_disconnect() 中にカスケード呼び出し直後 +# - ON_DISCONNECTED: notify_disconnect() リターン時 # # @else # @class PortConnectRetListener class @@ -250,97 +250,89 @@ def __init__(self): # # @endif class PortConnectRetListener: - """ - """ - - def __init__(self): - pass - - - ## - # @if jp - # - # @brief PortConnectRetListenerType ʸѴ - # - # PortConnectRetListenerType ʸѴ - # - # @param type Ѵо PortConnectRetListenerType - # - # @return ʸѴ - # - # @else - # - # @brief Convert PortConnectRetListenerType into string. - # - # Convert PortConnectRetListenerType into string. - # - # @param type The target PortConnectRetListenerType for transformation - # - # @return Trnasformation result of string representation - # - # @endif - #static const char* toString(PortConnectRetListenerType type); - def toString(type): - typeString = ["ON_PUBLISH_INTERFACES", - "ON_CONNECT_NEXTPORT", - "ON_SUBSCRIBE_INTERFACES", - "ON_CONNECTED", - "ON_DISCONNECT_NEXT", - "ON_DISCONNECTED", - ""] - - if type < PortConnectRetListenerType.PORT_CONNECT_RET_LISTENER_NUM: - return typeString[type] - - return "" - toString = staticmethod(toString) - - - ## - # @if jp - # @brief ǥȥ饯 - # @else - # @brief Destructor - # @endif - def __del__(self): - pass - - - ## - # @if jp - # - # @brief ۥХåؿ - # - # PortConnectRetListener ΥХåؿ - # - # @else - # - # @brief Virtual Callback function - # - # This is a the Callback function for PortConnectRetListener. - # - # @endif - #virtual void operator()(const char* portname, - # RTC::ConnectorProfile& profile, - # ReturnCode_t ret) = 0; - def __call__(self, portname, profile, ret): - pass - - - -class Entry: - def __init__(self,listener, autoclean): - self.listener = listener - self.autoclean = autoclean - return - -#============================================================ + """ + """ + + def __init__(self): + pass + + ## + # @if jp + # + # @brief PortConnectRetListenerType を文字列に変換 + # + # PortConnectRetListenerType を文字列に変換する + # + # @param type 変換対象 PortConnectRetListenerType + # + # @return 文字列変換結果 + # + # @else + # + # @brief Convert PortConnectRetListenerType into string. + # + # Convert PortConnectRetListenerType into string. + # + # @param type The target PortConnectRetListenerType for transformation + # + # @return Trnasformation result of string representation + # + # @endif + # static const char* toString(PortConnectRetListenerType type); + + def toString(status): + typeString = ["ON_PUBLISH_INTERFACES", + "ON_CONNECT_NEXTPORT", + "ON_SUBSCRIBE_INTERFACES", + "ON_CONNECTED", + "ON_DISCONNECT_NEXT", + "ON_DISCONNECTED"] + + if status < len(typeString): + return typeString[status] + + return "" + toString = staticmethod(toString) + + ## + # @if jp + # @brief デストラクタ + # @else + # @brief Destructor + # @endif + + def __del__(self): + pass + + ## + # @if jp + # + # @brief 仮想コールバック関数 + # + # PortConnectRetListener のコールバック関数 + # + # @else + # + # @brief Virtual Callback function + # + # This is a the Callback function for PortConnectRetListener. + # + # @endif + # virtual void operator()(const char* portname, + # RTC::ConnectorProfile& profile, + # ReturnCode_t ret) = 0; + + def __call__(self, portname, profile, ret): + pass + + +# ============================================================ ## # @if jp -# @class PortConnectListenerHolder -# @brief PortConnectListener ۥ饹 +# @class PortConnectListenerHolder +# @brief PortConnectListener ホルダクラス # -# ʣ PortConnectListener ݻ륯饹 +# 複数の PortConnectListener を保持し管理するクラス。 # # @else # @class PortConnectListenerHolder @@ -351,120 +343,115 @@ def __init__(self,listener, autoclean): # # @endif class PortConnectListenerHolder: - """ - """ - - ## - # @if jp - # @brief 󥹥ȥ饯 - # @else - # @brief Constructor - # @endif - def __init__(self): - self._listeners = [] - self._mutex = threading.RLock() - return - - - ## - # @if jp - # @brief ǥȥ饯 - # @else - # @brief Destructor - # @endif - def __del__(self): - pass - - - ## - # @if jp - # - # @brief ꥹʡɲ - # - # ꥹʡɲä롣 - # - # @param listener ɲäꥹ - # @param autoclean true:ǥȥ饯Ǻ, - # false:ǥȥ饯Ǻʤ - # @else - # - # @brief Add the listener. - # - # This method adds the listener. - # - # @param listener Added listener - # @param autoclean true:The listener is deleted at the destructor., - # false:The listener is not deleted at the destructor. - # @endif - #void addListener(PortConnectListener* listener, bool autoclean); - def addListener(self, listener, autoclean): - guard = Lock(self._mutex) - self._listeners.append(Entry(listener, autoclean)) - del guard - return - - - ## - # @if jp - # - # @brief ꥹʡκ - # - # ꥹʤ롣 - # - # @param listener ꥹ - # @else - # - # @brief Remove the listener. - # - # This method removes the listener. - # - # @param listener Removed listener - # @endif - #void removeListener(PortConnectListener* listener); - def removeListener(self, listener): - guard = Lock(self._mutex) - len_ = len(self._listeners) - for i in range(len_): - if (self._listeners[i].listener == listener) and self._listeners[i].autoclean: - self._listeners[i].listener = None - del self._listeners[i] + """ + """ + + ## + # @if jp + # @brief コンストラクタ + # @else + # @brief Constructor + # @endif + def __init__(self): + self._listeners = [] + self._mutex = threading.RLock() + return + + ## + # @if jp + # @brief デストラクタ + # @else + # @brief Destructor + # @endif + + def __del__(self): + pass + + ## + # @if jp + # + # @brief リスナーの追加 + # + # リスナーを追加する。 + # + # @param listener 追加するリスナ + # @else + # + # @brief Add the listener. + # + # This method adds the listener. + # + # @param listener Added listener + # @endif + # void addListener(PortConnectListener* listener); + + def addListener(self, listener): + guard = Lock(self._mutex) + self._listeners.append(listener) + del guard + return + + ## + # @if jp + # + # @brief リスナーの削除 + # + # リスナを削除する。 + # + # @param listener 削除するリスナ + # @else + # + # @brief Remove the listener. + # + # This method removes the listener. + # + # @param listener Removed listener + # @endif + # void removeListener(PortConnectListener* listener); + + def removeListener(self, listener): + guard = Lock(self._mutex) + len_ = len(self._listeners) + for i in range(len_): + if (self._listeners[i] == listener): + del self._listeners[i] + del guard + return + del guard + return + + ## + # @if jp + # + # @brief リスナーへ通知する + # + # 登録されているリスナのコールバックメソッドを呼び出す。 + # + # @param info ConnectorInfo + # @else + # + # @brief Notify listeners. + # + # This calls the Callback method of the registered listener. + # + # @param info ConnectorInfo + # @endif + # void notify(const char* portname, RTC::ConnectorProfile& profile); + + def notify(self, portname, profile): + guard = Lock(self._mutex) + for listener in self._listeners: + listener(portname, profile) del guard return - del guard - return - - - ## - # @if jp - # - # @brief ꥹʡΤ - # - # ϿƤꥹʤΥХå᥽åɤƤӽФ - # - # @param info ConnectorInfo - # @else - # - # @brief Notify listeners. - # - # This calls the Callback method of the registered listener. - # - # @param info ConnectorInfo - # @endif - #void notify(const char* portname, RTC::ConnectorProfile& profile); - def notify(self, portname, profile): - guard = Lock(self._mutex) - for listener in self._listeners: - listener.listener(portname, profile) - del guard - return ## # @if jp # @class PortConnectRetListenerHolder -# @brief PortConnectRetListener ۥ饹 +# @brief PortConnectRetListener ホルダクラス # -# ʣ PortConnectRetListener ݻ륯饹 +# 複数の PortConnectRetListener を保持し管理するクラス。 # # @else # @class PortConnectRetListenerHolder @@ -475,124 +462,117 @@ def notify(self, portname, profile): # # @endif class PortConnectRetListenerHolder: - """ - """ - - ## - # @if jp - # @brief 󥹥ȥ饯 - # @else - # @brief Constructor - # @endif - #PortConnectRetListenerHolder(); - def __init__(self): - self._listeners = [] - self._mutex = threading.RLock() - return - - - ## - # @if jp - # @brief ǥȥ饯 - # @else - # @brief Destructor - # @endif - def __del__(self): - pass - - - - ## - # @if jp - # - # @brief ꥹʡɲ - # - # ꥹʡɲä롣 - # - # @param listener ɲäꥹ - # @param autoclean true:ǥȥ饯Ǻ, - # false:ǥȥ饯Ǻʤ - # @else - # - # @brief Add the listener. - # - # This method adds the listener. - # - # @param listener Added listener - # @param autoclean true:The listener is deleted at the destructor., - # false:The listener is not deleted at the destructor. - # @endif - #void addListener(PortConnectRetListener* listener, bool autoclean); - def addListener(self, listener, autoclean): - guard = Lock(self._mutex) - self._listeners.append(Entry(listener, autoclean)) - del guard - return - - - ## - # @if jp - # - # @brief ꥹʡκ - # - # ꥹʤ롣 - # - # @param listener ꥹ - # @else - # - # @brief Remove the listener. - # - # This method removes the listener. - # - # @param listener Removed listener - # @endif - #void removeListener(PortConnectRetListener* listener); - def removeListener(self, listener): - guard = Lock(self._mutex) - len_ = len(self._listeners) - for i in range(len_): - if (self._listeners[i].listener == listener) and self._listeners[i].autoclean: - self._listeners[i].listener = None - del self._listeners[i] + """ + """ + + ## + # @if jp + # @brief コンストラクタ + # @else + # @brief Constructor + # @endif + # PortConnectRetListenerHolder(); + def __init__(self): + self._listeners = [] + self._mutex = threading.RLock() + return + + ## + # @if jp + # @brief デストラクタ + # @else + # @brief Destructor + # @endif + + def __del__(self): + pass + + ## + # @if jp + # + # @brief リスナーの追加 + # + # リスナーを追加する。 + # + # @param listener 追加するリスナ + # @else + # + # @brief Add the listener. + # + # This method adds the listener. + # + # @param listener Added listener + # @endif + # void addListener(PortConnectRetListener* listener); + + def addListener(self, listener): + guard = Lock(self._mutex) + self._listeners.append(listener) del guard return - del guard - return - - - ## - # @if jp - # - # @brief ꥹʡΤ - # - # ϿƤꥹʤΥХå᥽åɤƤӽФ - # - # @param info ConnectorInfo - # @param cdrdata ǡ - # @else - # - # @brief Notify listeners. - # - # This calls the Callback method of the registered listener. - # - # @param info ConnectorInfo - # @param cdrdata Data - # @endif - #void notify(const char* portname, RTC::ConnectorProfile& profile, - # ReturnCode_t ret); - def notify(self, portname, profile, ret): - guard = Lock(self._mutex) - for listener in self._listeners: - listener.listener(portname, profile, ret) - del guard - return + ## + # @if jp + # + # @brief リスナーの削除 + # + # リスナを削除する。 + # + # @param listener 削除するリスナ + # @else + # + # @brief Remove the listener. + # + # This method removes the listener. + # + # @param listener Removed listener + # @endif + # void removeListener(PortConnectRetListener* listener); + + def removeListener(self, listener): + guard = Lock(self._mutex) + len_ = len(self._listeners) + for i in range(len_): + if (self._listeners[i] == listener): + del self._listeners[i] + del guard + return + del guard + return + + ## + # @if jp + # + # @brief リスナーへ通知する + # + # 登録されているリスナのコールバックメソッドを呼び出す。 + # + # @param info ConnectorInfo + # @param cdrdata データ + # @else + # + # @brief Notify listeners. + # + # This calls the Callback method of the registered listener. + # + # @param info ConnectorInfo + # @param cdrdata Data + # @endif + # void notify(const char* portname, RTC::ConnectorProfile& profile, + # ReturnCode_t ret); + + def notify(self, portname, profile, ret): + guard = Lock(self._mutex) + for listener in self._listeners: + listener(portname, profile, ret) + del guard + return ## # @if jp # @class PortConnectListeners -# @brief PortConnectListeners 饹 +# @brief PortConnectListeners クラス # # # @else @@ -602,28 +582,178 @@ def notify(self, portname, profile, ret): # # @endif class PortConnectListeners: - """ - """ + """ + """ + + def __init__(self): + ## + # @if jp + # @brief PortConnectListenerType リスナ配列 + # PortConnectListenerType リスナを格納 + # @else + # @brief PortConnectListenerType listener array + # The PortConnectListenerType listener is stored. + # @endif + self.portconnect_num = PortConnectListenerType.PORT_CONNECT_LISTENER_NUM + self.portconnect_ = [PortConnectListenerHolder() + for i in range(self.portconnect_num)] + + ## + # @if jp + # @brief PortConnectRetTypeリスナ配列 + # PortConnectRetTypeリスナを格納 + # @else + # @brief PortConnectRetType listener array + # The PortConnectRetType listener is stored. + # @endif + self.portconnret_num = PortConnectRetListenerType.PORT_CONNECT_RET_LISTENER_NUM + self.portconnret_ = [PortConnectRetListenerHolder() + for i in range(self.portconnret_num)] + + ## + # @if jp + # @brief リスナーの追加 + # + # 指定の種類のPortConnectListenerを追加する。 + # + # @param self + # @param ltype リスナの種類 + # @param listener 追加するリスナ + # @return False:指定の種類のリスナが存在しない + # + # @else + # + # @param self + # @param ltype + # @param listener + # @return + # + # @endif + def addListener(self, ltype, listener): + if ltype < len(self.portconnect_): + self.portconnect_[ltype].addListener(listener) + return True + return False + + ## + # @if jp + # @brief リスナーの削除 + # + # 指定の種類のPortConnectListenerを削除する。 + # + # @param self + # @param ltype リスナの種類 + # @param listener 削除するリスナ + # @return False:指定の種類のリスナが存在しない + # + # @else + # + # @param self + # @param ltype + # @param listener + # @return + # + # @endif + def removeListener(self, ltype, listener): + if ltype < len(self.portconnect_): + self.portconnect_[ltype].removeListener(listener) + return True + return False - def __init__(self): ## # @if jp - # @brief PortConnectListenerType ꥹ - # PortConnectListenerType ꥹʤǼ + # @brief リスナーの追加 + # + # 指定の種類のPortConnectRetListenerを追加する。 + # + # @param self + # @param ltype リスナの種類 + # @param listener 追加するリスナ + # @return False:指定の種類のリスナが存在しない + # # @else - # @brief PortConnectListenerType listener array - # The PortConnectListenerType listener is stored. + # + # @param self + # @param ltype + # @param listener + # @return + # # @endif - self.portconnect_num = PortConnectListenerType.PORT_CONNECT_LISTENER_NUM - self.portconnect_ = [PortConnectListenerHolder() for i in range(self.portconnect_num)] - + def addRetListener(self, ltype, listener): + if ltype < len(self.portconnret_): + self.portconnret_[ltype].addListener(listener) + return True + return False + + ## + # @if jp + # @brief リスナーの削除 + # + # 指定の種類のPortConnectRetListenerを削除する。 + # + # @param self + # @param ltype リスナの種類 + # @param listener 削除するリスナ + # @return False:指定の種類のリスナが存在しない + # + # @else + # + # @param self + # @param ltype + # @param listener + # @return + # + # @endif + def removeRetListener(self, ltype, listener): + if ltype < len(self.portconnret_): + self.portconnret_[ltype].removeListener(listener) + return True + return False + + ## + # @if jp + # @brief リスナーへ通知する + # + # 指定の種類のPortConnectListenerのコールバック関数を呼び出す。 + # + # @param self + # @param ltype リスナの種類 + # @param portname ポート名 + # @param profile ConnectorProfile + # + # @else + # + # @param self + # @param ltype + # @param portname + # @param profile + # + # @endif + def notify(self, ltype, portname, profile): + if ltype < len(self.portconnect_): + self.portconnect_[ltype].notify(portname, profile) + ## # @if jp - # @brief PortConnectRetTypeꥹ - # PortConnectRetTypeꥹʤǼ + # @brief リスナーへ通知する + # + # 指定の種類のPortConnectRetListenerのコールバック関数を呼び出す。 + # + # @param self + # @param ltype リスナの種類 + # @param portname ポート名 + # @param profile ConnectorProfile + # @param ret リターンコード + # # @else - # @brief PortConnectRetType listener array - # The PortConnectRetType listener is stored. + # + # @param self + # @param ltype + # @param portname + # @param profile + # @param ret + # # @endif - self.portconnret_num = PortConnectRetListenerType.PORT_CONNECT_RET_LISTENER_NUM - self.portconnret_ = [PortConnectRetListenerHolder() for i in range(self.portconnret_num)] + def notifyRet(self, ltype, portname, profile, ret): + if ltype < len(self.portconnret_): + self.portconnret_[ltype].notify(portname, profile, ret) diff --git a/OpenRTM_aist/PortProfileHelper.py b/OpenRTM_aist/PortProfileHelper.py index 0d3868a5..16f9acb4 100644 --- a/OpenRTM_aist/PortProfileHelper.py +++ b/OpenRTM_aist/PortProfileHelper.py @@ -1,5 +1,5 @@ #!/usr/bin/env python -# -*- coding: euc-jp -*- +# -*- coding: utf-8 -*- ## # @file PortProfileHelper.py @@ -27,10 +27,10 @@ # @if jp # # @class PortProfileHelper -# @brief PortProfile إѡ饹 +# @brief PortProfile ヘルパークラス # -# RTC::Port μΥץեݻ PortProfile 륯饹 -# Ȥ PortBase ǻѤ롣 +# RTC::Port の種々のプロファイルを保持する PortProfile を管理するクラス。 +# 主として PortBase の内部で使用される。 # # @else # @@ -43,617 +43,615 @@ # @endif # class PortProfileHelper: - """ - """ - - def __init__(self): - self._mutex = threading.RLock() - self._name = "" - self._ifProfiles = [] - self._portRef = None - self._connProfiles = [] - self._owner = None - self._properties = [] - return - - ## - # @if jp - # - # @brief PortProfile ꤹ - # - # Υ֥Ȥݻ PortProfile Ϳ줿 PortProfile - # 򥳥ԡ񤭤¸롣 - # - # @param PortProfile 񤭤 PortProfile - # - # @else - # - # @brief Set PortProfile - # - # This operation copies the given PortProfile and overwrites the existent - # PortProfile by the given ProtProfile. - # - # @param PortProfile The PortProfile to be stored. - # - # @endif - # - # void setPortProfile(const PortProfile& profile); - def setPortProfile(self, profile): - guard = OpenRTM_aist.ScopedLock(self._mutex) - self._name = profile.name - self._ifProfiles = profile.interfaces - self._portRef = profile.port_ref - self._connProfiles = profile.connector_profiles - self._owner = profile.owner - self._properties = profile.properties - return - - ## - # @if jp - # - # @brief PortProfile - # - # Υ֥Ȥݻ PortProfile ֤ - # - # @return Υ֥Ȥݻ PortProfile - # - # @else - # - # @brief Get PortProfile - # - # This operation returns the PortProfile. - # - # @return The PortProfile stored by the object. - # - # @endif - # - # PortProfile* getPortProfile(); - def getPortProfile(self): - guard = OpenRTM_aist.ScopedLock(self._mutex) - prof = RTC.PortProfile(self._name, - self._ifProfiles, - self._portRef, - self._connProfiles, - self._owner, - self._properties) - return prof - - - ## - # @if jp - # - # @brief PortProfile.name ꤹ - # - # Υڥ졼ϰͿ줿ʸ򥳥ݡ - # PortProfile.name Ȥݻ롣 - # - # @param name PortProfile.name ˳Ǽ Port ̾ - # - # @else - # - # @brief Set PortProfile.name - # - # This operation stores a copy of given name to the PortProfile.name. - # - # @param name The name of Port to be stored to the PortProfile.name. - # - # @endif - # - # void setName(const char* name); - def setName(self, name): - guard = OpenRTM_aist.ScopedLock(self._mutex) - self._name = name - return - - ## - # @if jp - # - # @brief PortProfile.name - # - # Υڥ졼 PortProfile.name 롣 - # - # @return PortProfile.name ؤΥݥ - # - # @else - # - # @brief Get PortProfile.name - # - # This operation returns a pointer to the PortProfile.name. - # - # @return The pointer to PortProfile.name. - # - # @endif - # - # const char* getName() const; - def getName(self): - guard = OpenRTM_aist.ScopedLock(self._mutex) - return self._name - - - ## - # @if jp - # - # @brief PortInterfaceProfile ɲä - # - # Υڥ졼 PortProfile PortInterfaceProfile ɲä롣 - # - # @param if_profile PortProfile ɲä PortInterfaceProfile - # - # @else - # - # @brief Append PortInterfaceProfile to the PortProfile - # - # This operation appends the PortInterfaceProfile to the PortProfile - # - # @param if_profile PortInterfaceProfile to be appended the PortProfile - # - # @endif - # - # void appendPortInterfaceProfile(PortInterfaceProfile if_prof); - def appendPortInterfaceProfile(self, if_prof): - guard = OpenRTM_aist.ScopedLock(self._mutex) - self._ifProfiles.append(if_prof) - return - - ## - # @if jp - # - # @brief PortInterfaceProfileList - # - # Υڥ졼 PortInterfaceProfileList ֤ - # - # @return PortInterfaceProfileList - # - # @else - # - # @brief Get PortInterfaceProfileList - # - # This operation returns the PortInterfaceProfileList. - # - # @return PortInterfaceProfileList - # - # @endif - # - # const PortInterfaceProfileList& getPortInterfaceProfiles() const; - def getPortInterfaceProfiles(self): - guard = OpenRTM_aist.ScopedLock(self._mutex) - return self._ifProfiles - - - ## - # @if jp - # - # @brief PortInterfaceProfile - # - # Υڥ졼 instance_name ǻꤵ줿 PortInterfaceProfile - # ֤ - # - # @param instance_name PortInterfaceProfile instance_name - # @return PortInterfaceProfile - # - # @else - # - # @brief Get PortInterfaceProfile - # - # This operation returns the PortInterfaceProfile specified - # by instance_name. - # - # @param instance_name instance_name of the PortInterfaceProfile - # @return PortInterfaceProfile - # - # @endif - # - # const PortInterfaceProfile getPortInterfaceProfile(const char* instance_name) const; - def getPortInterfaceProfile(self, instance_name): - guard = OpenRTM_aist.ScopedLock(self._mutex) - index = OpenRTM_aist.CORBA_SeqUtil.find(self._ifProfiles, - self.if_name(instance_name)) - if index < 0: - return None - else: - return self._ifProfiles[index] - - - ## - # @if jp - # - # @brief PortInterfaceProfile - # - # Υڥ졼 instance_name ǻꤵ줿PortInterfaceProfile - # 롣ꤷ̾ PortInterfaceProfile ¸ߤʤˤϡ - # NotFound exception ֤ - # - # @param instance_name PortInterfaceProfile ̾ - # - # @else - # - # @brief Erase PortInterfaceProfile from the PortProfile - # - # This operation erases the PortInterfaceProfile from the PortProfile - # - # @param instance_name PortInterfaceProfile to be erased from the - # PortProfile - # - # @endif - # - # void erasePortInterfaceProfile(const char* instance_name); - def erasePortInterfaceProfile(self, instance_name): - guard = OpenRTM_aist.ScopedLock(self._mutex) - index = OpenRTM_aist.CORBA_SeqUtil.find(self._ifProfiles, - self.if_name(instance_name)) - if index < 0: - return - else: - del self._ifProfiles[index] - - - ## - # @if jp - # - # @brief Port Υ֥ȻȤ򥻥åȤ - # - # Υڥ졼 PortProfile ˡϢ Port Υ֥Ȼ - # ꤹ롣 - # - # @param port ꤹ Port Υ֥ȥե - # - # @else - # - # @brief Set Port's object reference - # - # This operation set the object reference of the Port. - # - # @param port Port's object reference to be set. - # - # @endif - # - # void setPortRef(PortService_ptr port); - def setPortRef(self, port): - guard = OpenRTM_aist.ScopedLock(self._mutex) - self._portRef = port - return - - - ## - # @if jp - # - # @brief Port Υ֥ȻȤ - # - # Υڥ졼 PortProfile ˴Ϣդ줿 Port - # ֥ȻȤ֤ - # - # @return Ϣդ줿 Port Υ֥Ȼ - # - # @else - # - # @brief Get Port's object reference - # - # This operation returns the object reference of the PortProfile. - # - # @return Port's object reference associated with the PortProfile. - # - # @endif - # - # PortService_ptr getPortRef() const; - def getPortRef(self): - guard = OpenRTM_aist.ScopedLock(self._mutex) - return self._portRef - - - ## - # @if jp - # - # @brief ConnectorProfile ɲä - # - # Υڥ졼 PortProfile ConnectorProfile ɲä롣 - # - # @param conn_profile ConnectorProfile - # - # @else - # - # @brief Append ConnectorProfile - # - # This operation appends the ConnectorProfile to the PortProfile. - # - # @param conn_profile ConnectorProfile to be added. - # - # @endif - # - # void appendConnectorProfile(ConnectorProfile conn_profile); - def appendConnectorProfile(self, conn_profile): - guard = OpenRTM_aist.ScopedLock(self._mutex) - self._connProfiles.append(conn_profile) - return - - ## - # @if jp - # - # @brief ConnectorProfileList - # - # Υڥ졼 PortProfile ˴Ϣդ줿 ConnectorProfile - # ꥹ ConnectorProfileList ֤ - # - # @return Ϣդ줿 ConnectorProfileList - # - # @else - # - # @brief Get ConnectorProfileList - # - # This operation returns the list of ConnectorProfile of the PortProfile. - # - # @return Port's ConnectorProfileList. - # - # @endif - # - # const ConnectorProfileList getConnectorProfiles() const; - def getConnectorProfiles(self): - guard = OpenRTM_aist.ScopedLock(self._mutex) - return self._connProfiles - - - ## - # @if jp - # - # @brief ConnectorProfile - # - # Υڥ졼ϰǻꤵ줿̾ ConnectorProfile ֤ - # - # @param name ConnectorProfile ̾ - # @return ConnectorProfile - # - # @else - # - # @brief Get ConnectorProfile - # - # This operation returns the ConnectorProfile specified by name. - # - # @param name The name of ConnectorProfile - # @return ConnectorProfile. - # - # @endif - # - # const ConnectorProfile getConnectorProfile(const char* name) const; - def getConnectorProfile(self, name): - guard = OpenRTM_aist.ScopedLock(self._mutex) - index = OpenRTM_aist.CORBA_SeqUtil.find(self._connProfiles, - self.conn_name(name)) - if index < 0: - return None - else: - return self._connProfiles[index] - - - - - ## - # @if jp - # - # @brief ConnectorProfile - # - # Υڥ졼ϰǻꤵ줿ID ConnectorProfile ֤ - # - # @param id ConnectorProfile ID - # @return ConnectorProfile - # - # @else - # - # @brief Get ConnectorProfile - # - # This operation returns the ConnectorProfile specified by ID. - # - # @param id The ID of ConnectorProfile - # @return ConnectorProfile. - # - # @endif - # - # const ConnectorProfile getConnectorProfileById(const char* id) const; - def getConnectorProfileById(self, id): - guard = OpenRTM_aist.ScopedLock(self._mutex) - index = OpenRTM_aist.CORBA_SeqUtil.find(self._connProfiles, - self.conn_id(id)) - if index < 0: - return None - else: - return self._connProfiles[index] - - - - ## - # @if jp - # - # @brief ConnectorProfile - # - # Υڥ졼 PortProfile ConnectorProfile - # ̾ǻꤷƺ롣 - # - # @param naem ConnectorProfile ̾ - # - # @else - # - # @brief Erase ConnectorProfile - # - # This operation erases the ConnectorProfile from the PortProfile. - # - # @param name The name of the ConnectorProfile to be erased. - # - # @endif - # - # void eraseConnectorProfile(const char* name); - def eraseConnectorProfile(self, name): - guard = OpenRTM_aist.ScopedLock(self._mutex) - index = OpenRTM_aist.CORBA_SeqUtil.find(self._connProfiles, - self.conn_name(name)) - if index < 0: - return - else: - del self._connProfiles[index] - - return - - - ## - # @if jp - # - # @brief ConnectorProfile - # - # Υڥ졼 PortProfile ConnectorProfile - # ID ǻꤷƺ롣 - # - # @param id ConnectorProfile ID - # - # @else - # - # @brief Erase ConnectorProfile - # - # This operation erases the ConnectorProfile from the PortProfile. - # - # @param id The ID of the ConnectorProfile to be erased. - # - # @endif - # - # void eraseConnectorProfileById(const char* id); - def eraseConnectorProfileById(self, id): - guard = OpenRTM_aist.ScopedLock(self._mutex) - index = OpenRTM_aist.CORBA_SeqUtil.find(self._connProfiles, - self.conn_id(id)) - if index < 0: - return - else: - del self._connProfiles[index] - - return - - ## - # @if jp - # - # @brief PortProfile owner ꤹ - # - # Υڥ졼 PortProfile owner ꤹ롣 - # - # @param owner PortProfile owner Υ֥Ȼ - # - # @else - # - # @brief Set owner's object reference to the PortProfile - # - # This operation sets the owner's object reference to the PortProfile. - # - # @param owner The owner's object reference of PortProfile. - # - # @endif - # - # void setOwner(RTObject_ptr owner); - def setOwner(self, owner): - guard = OpenRTM_aist.ScopedLock(self._mutex) - self._owner = owner - return - - ## - # @if jp - # - # @brief PortProfile owner - # - # Υڥ졼 PortProfile owner Υ֥ȻȤ֤ - # - # @return PortProfile owner Υ֥Ȼ - # - # @else - # - # @brief Get owner's object reference from the PortProfile - # - # This operation returns the owner's object reference of the PortProfile. - # - # @return The owner's object reference of PortProfile. - # - # @endif - # - # RTObject_ptr getOwner() const; - def getOwner(self): - guard = OpenRTM_aist.ScopedLock(self._mutex) - return self._owner - - - ## - # @if jp - # - # @brief PortProfile properties ꤹ - # - # Υڥ졼 PortProfile properties ꤹ롣 - # - # @param prop PortProfile properties NVList - # - # @else - # - # @brief Set properties to the PortProfile - # - # This operation set the properties to the PortProfile. - # - # @param prop The NVList of PortProfile's properties. - # - # @endif - # - # void setProperties(NVList& prop); - def setProperties(self, prop): - guard = OpenRTM_aist.ScopedLock(self._mutex) - self._properties = prop - return - - ## - # @if jp - # - # @brief PortProfile properties - # - # Υڥ졼 PortProfile properties֤ - # - # @return PortProfile properties NVList - # - # @else - # - # @brief Get properties of the PortProfile - # - # This operation returns the properties of the PortProfile. - # - # @return The NVList of PortProfile's properties. - # - # @endif - # - # const NVList& getProperties() const; - def getProperties(self): - guard = OpenRTM_aist.ScopedLock(self._mutex) - return self._properties - - - ## - # @if jp - # @class if_name - # @brief instance_name PortInterfaceProfile õ Functor - # @else - # @brief A functor to find a PortInterfaceProfile named instance_name - # @endif - class if_name: - def __init__(self, name): - self._name = name - return - - def __call__(self, prof): - return str(self._name) == str(prof.instance_name) - - - # Functor to find ConnectorProfile by name - class conn_name: - def __init__(self, name): - self._name = name - return - - def __call__(self, cprof): - return str(self._name) == str(cprof.name) - - - # Functor to find ConnectorProfile by id - class conn_id: - def __init__(self, id_): - self._id = id_ - return - - def __call__(self, cprof): - return str(self._id) == str(cprof.connector_id) + """ + """ + + def __init__(self): + self._mutex = threading.RLock() + self._name = "" + self._ifProfiles = [] + self._portRef = None + self._connProfiles = [] + self._owner = None + self._properties = [] + return + + ## + # @if jp + # + # @brief PortProfile を設定する + # + # このオブジェクトが保持する PortProfile を引数で与えられた PortProfile + # をコピーし上書きして保存する。 + # + # @param PortProfile 上書きする PortProfile + # + # @else + # + # @brief Set PortProfile + # + # This operation copies the given PortProfile and overwrites the existent + # PortProfile by the given ProtProfile. + # + # @param PortProfile The PortProfile to be stored. + # + # @endif + # + # void setPortProfile(const PortProfile& profile); + def setPortProfile(self, profile): + guard = OpenRTM_aist.ScopedLock(self._mutex) + self._name = profile.name + self._ifProfiles = profile.interfaces + self._portRef = profile.port_ref + self._connProfiles = profile.connector_profiles + self._owner = profile.owner + self._properties = profile.properties + return + + ## + # @if jp + # + # @brief PortProfile を取得する + # + # このオブジェクトが保持する PortProfile を返す。 + # + # @return このオブジェクトが保持する PortProfile + # + # @else + # + # @brief Get PortProfile + # + # This operation returns the PortProfile. + # + # @return The PortProfile stored by the object. + # + # @endif + # + # PortProfile* getPortProfile(); + def getPortProfile(self): + guard = OpenRTM_aist.ScopedLock(self._mutex) + prof = RTC.PortProfile(self._name, + self._ifProfiles, + self._portRef, + self._connProfiles, + self._owner, + self._properties) + return prof + + ## + # @if jp + # + # @brief PortProfile.name を設定する + # + # このオペレーションは引数で与えられた文字列をコポーし、 + # PortProfile.name として保持する。 + # + # @param name PortProfile.name に格納する Port の名前 + # + # @else + # + # @brief Set PortProfile.name + # + # This operation stores a copy of given name to the PortProfile.name. + # + # @param name The name of Port to be stored to the PortProfile.name. + # + # @endif + # + # void setName(const char* name); + + def setName(self, name): + guard = OpenRTM_aist.ScopedLock(self._mutex) + self._name = name + return + + ## + # @if jp + # + # @brief PortProfile.name を取得する + # + # このオペレーションは PortProfile.name を取得する。 + # + # @return PortProfile.name へのポインタ + # + # @else + # + # @brief Get PortProfile.name + # + # This operation returns a pointer to the PortProfile.name. + # + # @return The pointer to PortProfile.name. + # + # @endif + # + # const char* getName() const; + def getName(self): + guard = OpenRTM_aist.ScopedLock(self._mutex) + return self._name + + ## + # @if jp + # + # @brief PortInterfaceProfile を追加する + # + # このオペレーションは PortProfile に PortInterfaceProfile を追加する。 + # + # @param if_profile PortProfile に追加する PortInterfaceProfile + # + # @else + # + # @brief Append PortInterfaceProfile to the PortProfile + # + # This operation appends the PortInterfaceProfile to the PortProfile + # + # @param if_profile PortInterfaceProfile to be appended the PortProfile + # + # @endif + # + # void appendPortInterfaceProfile(PortInterfaceProfile if_prof); + + def appendPortInterfaceProfile(self, if_prof): + guard = OpenRTM_aist.ScopedLock(self._mutex) + self._ifProfiles.append(if_prof) + return + + ## + # @if jp + # + # @brief PortInterfaceProfileList を取得する + # + # このオペレーションは PortInterfaceProfileList を返す。 + # + # @return PortInterfaceProfileList + # + # @else + # + # @brief Get PortInterfaceProfileList + # + # This operation returns the PortInterfaceProfileList. + # + # @return PortInterfaceProfileList + # + # @endif + # + # const PortInterfaceProfileList& getPortInterfaceProfiles() const; + def getPortInterfaceProfiles(self): + guard = OpenRTM_aist.ScopedLock(self._mutex) + return self._ifProfiles + + ## + # @if jp + # + # @brief PortInterfaceProfile を取得する + # + # このオペレーションは instance_name で指定された PortInterfaceProfile + # を返す。 + # + # @param instance_name PortInterfaceProfile の instance_name + # @return PortInterfaceProfile + # + # @else + # + # @brief Get PortInterfaceProfile + # + # This operation returns the PortInterfaceProfile specified + # by instance_name. + # + # @param instance_name instance_name of the PortInterfaceProfile + # @return PortInterfaceProfile + # + # @endif + # + # const PortInterfaceProfile getPortInterfaceProfile(const char* + # instance_name) const; + + def getPortInterfaceProfile(self, instance_name): + guard = OpenRTM_aist.ScopedLock(self._mutex) + index = OpenRTM_aist.CORBA_SeqUtil.find(self._ifProfiles, + self.if_name(instance_name)) + if index < 0: + return None + else: + return self._ifProfiles[index] + + ## + # @if jp + # + # @brief PortInterfaceProfile を削除する + # + # このオペレーションは instance_name で指定された PortInterfaceProfile + # を削除する。指定した名前の PortInterfaceProfile が存在しない場合には、 + # NotFound exception を返す。 + # + # @param instance_name 削除する PortInterfaceProfile の名前 + # + # @else + # + # @brief Erase PortInterfaceProfile from the PortProfile + # + # This operation erases the PortInterfaceProfile from the PortProfile + # + # @param instance_name PortInterfaceProfile to be erased from the + # PortProfile + # + # @endif + # + # void erasePortInterfaceProfile(const char* instance_name); + + def erasePortInterfaceProfile(self, instance_name): + guard = OpenRTM_aist.ScopedLock(self._mutex) + index = OpenRTM_aist.CORBA_SeqUtil.find(self._ifProfiles, + self.if_name(instance_name)) + if index < 0: + return + else: + del self._ifProfiles[index] + + ## + # @if jp + # + # @brief Port のオブジェクト参照をセットする + # + # このオペレーションは PortProfile に、関連する Port のオブジェクト参照 + # を設定する。 + # + # @param port 設定する Port のオブジェクトリファレンス + # + # @else + # + # @brief Set Port's object reference + # + # This operation set the object reference of the Port. + # + # @param port Port's object reference to be set. + # + # @endif + # + # void setPortRef(PortService_ptr port); + + def setPortRef(self, port): + guard = OpenRTM_aist.ScopedLock(self._mutex) + self._portRef = port + return + + ## + # @if jp + # + # @brief Port のオブジェクト参照を取得する + # + # このオペレーションは PortProfile に関連付けられた Port の + # オブジェクト参照を返す。 + # + # @return 関連付けられた Port のオブジェクト参照 + # + # @else + # + # @brief Get Port's object reference + # + # This operation returns the object reference of the PortProfile. + # + # @return Port's object reference associated with the PortProfile. + # + # @endif + # + # PortService_ptr getPortRef() const; + + def getPortRef(self): + guard = OpenRTM_aist.ScopedLock(self._mutex) + return self._portRef + + ## + # @if jp + # + # @brief ConnectorProfile を追加する + # + # このオペレーションは PortProfile に ConnectorProfile を追加する。 + # + # @param conn_profile ConnectorProfile + # + # @else + # + # @brief Append ConnectorProfile + # + # This operation appends the ConnectorProfile to the PortProfile. + # + # @param conn_profile ConnectorProfile to be added. + # + # @endif + # + # void appendConnectorProfile(ConnectorProfile conn_profile); + + def appendConnectorProfile(self, conn_profile): + guard = OpenRTM_aist.ScopedLock(self._mutex) + self._connProfiles.append(conn_profile) + return + + ## + # @if jp + # + # @brief ConnectorProfileList を取得する + # + # このオペレーションは PortProfile に関連付けられた ConnectorProfile の + # リスト ConnectorProfileList を返す。 + # + # @return 関連付けられた ConnectorProfileList + # + # @else + # + # @brief Get ConnectorProfileList + # + # This operation returns the list of ConnectorProfile of the PortProfile. + # + # @return Port's ConnectorProfileList. + # + # @endif + # + # const ConnectorProfileList getConnectorProfiles() const; + def getConnectorProfiles(self): + guard = OpenRTM_aist.ScopedLock(self._mutex) + return self._connProfiles + + ## + # @if jp + # + # @brief ConnectorProfile を取得する + # + # このオペレーションは引数で指定された名前を持つ ConnectorProfile を返す。 + # + # @param name ConnectorProfile の名前 + # @return ConnectorProfile + # + # @else + # + # @brief Get ConnectorProfile + # + # This operation returns the ConnectorProfile specified by name. + # + # @param name The name of ConnectorProfile + # @return ConnectorProfile. + # + # @endif + # + # const ConnectorProfile getConnectorProfile(const char* name) const; + + def getConnectorProfile(self, name): + guard = OpenRTM_aist.ScopedLock(self._mutex) + index = OpenRTM_aist.CORBA_SeqUtil.find(self._connProfiles, + self.conn_name(name)) + if index < 0: + return None + else: + return self._connProfiles[index] + + ## + # @if jp + # + # @brief ConnectorProfile を取得する + # + # このオペレーションは引数で指定されたIDを持つ ConnectorProfile を返す。 + # + # @param id ConnectorProfile のID + # @return ConnectorProfile + # + # @else + # + # @brief Get ConnectorProfile + # + # This operation returns the ConnectorProfile specified by ID. + # + # @param id The ID of ConnectorProfile + # @return ConnectorProfile. + # + # @endif + # + # const ConnectorProfile getConnectorProfileById(const char* id) const; + + def getConnectorProfileById(self, id): + guard = OpenRTM_aist.ScopedLock(self._mutex) + index = OpenRTM_aist.CORBA_SeqUtil.find(self._connProfiles, + self.conn_id(id)) + if index < 0: + return None + else: + return self._connProfiles[index] + + ## + # @if jp + # + # @brief ConnectorProfile を削除する + # + # このオペレーションは PortProfile の ConnectorProfile を + # 名前で指定して削除する。 + # + # @param naem ConnectorProfile の名前 + # + # @else + # + # @brief Erase ConnectorProfile + # + # This operation erases the ConnectorProfile from the PortProfile. + # + # @param name The name of the ConnectorProfile to be erased. + # + # @endif + # + # void eraseConnectorProfile(const char* name); + + def eraseConnectorProfile(self, name): + guard = OpenRTM_aist.ScopedLock(self._mutex) + index = OpenRTM_aist.CORBA_SeqUtil.find(self._connProfiles, + self.conn_name(name)) + if index < 0: + return + else: + del self._connProfiles[index] + + return + + ## + # @if jp + # + # @brief ConnectorProfile を削除する + # + # このオペレーションは PortProfile の ConnectorProfile を + # ID で指定して削除する。 + # + # @param id ConnectorProfile のID + # + # @else + # + # @brief Erase ConnectorProfile + # + # This operation erases the ConnectorProfile from the PortProfile. + # + # @param id The ID of the ConnectorProfile to be erased. + # + # @endif + # + # void eraseConnectorProfileById(const char* id); + + def eraseConnectorProfileById(self, id): + guard = OpenRTM_aist.ScopedLock(self._mutex) + index = OpenRTM_aist.CORBA_SeqUtil.find(self._connProfiles, + self.conn_id(id)) + if index < 0: + return + else: + del self._connProfiles[index] + + return + + ## + # @if jp + # + # @brief PortProfile の owner を設定する + # + # このオペレーションは PortProfile の owner を設定する。 + # + # @param owner PortProfile の owner のオブジェクト参照 + # + # @else + # + # @brief Set owner's object reference to the PortProfile + # + # This operation sets the owner's object reference to the PortProfile. + # + # @param owner The owner's object reference of PortProfile. + # + # @endif + # + # void setOwner(RTObject_ptr owner); + def setOwner(self, owner): + guard = OpenRTM_aist.ScopedLock(self._mutex) + self._owner = owner + return + + ## + # @if jp + # + # @brief PortProfile の owner を取得する + # + # このオペレーションは PortProfile の owner のオブジェクト参照を返す。 + # + # @return PortProfile の owner のオブジェクト参照 + # + # @else + # + # @brief Get owner's object reference from the PortProfile + # + # This operation returns the owner's object reference of the PortProfile. + # + # @return The owner's object reference of PortProfile. + # + # @endif + # + # RTObject_ptr getOwner() const; + def getOwner(self): + guard = OpenRTM_aist.ScopedLock(self._mutex) + return self._owner + + ## + # @if jp + # + # @brief PortProfile の properties を設定する + # + # このオペレーションは PortProfile に properties を設定する。 + # + # @param prop PortProfile の properties の NVList + # + # @else + # + # @brief Set properties to the PortProfile + # + # This operation set the properties to the PortProfile. + # + # @param prop The NVList of PortProfile's properties. + # + # @endif + # + # void setProperties(NVList& prop); + + def setProperties(self, prop): + guard = OpenRTM_aist.ScopedLock(self._mutex) + self._properties = prop + return + + ## + # @if jp + # + # @brief PortProfile の properties を取得する + # + # このオペレーションは PortProfile の propertiesを返す。 + # + # @return PortProfile の properties の NVList + # + # @else + # + # @brief Get properties of the PortProfile + # + # This operation returns the properties of the PortProfile. + # + # @return The NVList of PortProfile's properties. + # + # @endif + # + # const NVList& getProperties() const; + def getProperties(self): + guard = OpenRTM_aist.ScopedLock(self._mutex) + return self._properties + + ## + # @if jp + # @class if_name + # @brief instance_name を持つ PortInterfaceProfile を探す Functor + # @else + # @brief A functor to find a PortInterfaceProfile named instance_name + # @endif + + class if_name: + def __init__(self, name): + self._name = name + return + + def __call__(self, prof): + return str(self._name) == str(prof.instance_name) + + # Functor to find ConnectorProfile by name + + class conn_name: + def __init__(self, name): + self._name = name + return + + def __call__(self, cprof): + return str(self._name) == str(cprof.name) + + # Functor to find ConnectorProfile by id + + class conn_id: + def __init__(self, id_): + self._id = id_ + return + + def __call__(self, cprof): + return str(self._id) == str(cprof.connector_id) diff --git a/OpenRTM_aist/Process.py b/OpenRTM_aist/Process.py index fc339a3b..b8ff7dd0 100644 --- a/OpenRTM_aist/Process.py +++ b/OpenRTM_aist/Process.py @@ -1,5 +1,5 @@ #!/usr/bin/env python -# -*- coding: euc-jp -*- +# -*- coding: utf-8 -*- ## @@ -15,77 +15,82 @@ # Advanced Industrial Science and Technology (AIST), Japan # All rights reserved. -import os,sys +import os +import sys import traceback import subprocess import shlex ## # @if jp -# @brief ץư +# @brief プロセスを起動する # @else # @brief Launching a process # @endif # # int launch_shell(std::string command) -def launch_shell(command): - #args = command.split(" ") - args = shlex.split(command," ") - if os.name == "nt": - CREATE_NEW_PROCESS_GROUP = 0x00000200 - subproc_args = { 'stdin': None, - 'stdout': None, - 'stderr': None, - 'cwd': None, - 'close_fds': False, - 'creationflags': CREATE_NEW_PROCESS_GROUP} - else: - subproc_args = { 'stdin': None, - 'stdout': None, - 'stderr': None, - 'cwd': None, - 'close_fds': False, - 'preexec_fn': os.setsid} - try: - subprocess.Popen(args, **subproc_args) - except OSError: - # fork failed - if sys.version_info[0:3] >= (2, 4, 0): - print(traceback.format_exc()) +def launch_shell(command): + #args = command.split(" ") + args = shlex.split(command, " ") + + if os.name == "nt": + CREATE_NEW_PROCESS_GROUP = 0x00000200 + subproc_args = {'stdin': None, + 'stdout': None, + 'stderr': None, + 'cwd': None, + 'close_fds': False, + 'creationflags': CREATE_NEW_PROCESS_GROUP} else: - _exc_list = traceback.format_exception(*sys.exc_info()) - print("".join(_exc_list)) + subproc_args = {'stdin': None, + 'stdout': None, + 'stderr': None, + 'cwd': None, + 'close_fds': False, + 'preexec_fn': os.setsid} + + try: + subprocess.Popen(args, **subproc_args) + except OSError: + # fork failed + if sys.version_info[0:3] >= (2, 4, 0): + print(traceback.format_exc()) + else: + _exc_list = traceback.format_exception(*sys.exc_info()) + print("".join(_exc_list)) - return -1 - return 0 + return -1 + return 0 ## # @if jp -# @brief ץʣ +# @brief プロセスを複製する # @else # @brief fork process # @endif # # int fork() def fork(): - if os.name == "nt": - return -1 - else: - pid = os.fork() - return pid + if os.name == "nt": + return -1 + else: + pid = os.fork() + return pid ## # @if jp -# @brief ץưϤ +# @brief プロセスを起動し出力を取得する # @else # @brief fork process # @endif # -# int fork() +# string popen(string command) + + def popen(command): - args = shlex.split(command," ") - sp = subprocess.Popen(args, stdout=subprocess.PIPE) - return sp.communicate()[0] + args = shlex.split(command, " ") + sp = subprocess.Popen(args, stdout=subprocess.PIPE) + return sp.communicate()[0].decode("utf-8") diff --git a/OpenRTM_aist/Properties.py b/OpenRTM_aist/Properties.py index 6d22eb0f..c991a76b 100644 --- a/OpenRTM_aist/Properties.py +++ b/OpenRTM_aist/Properties.py @@ -1,6 +1,6 @@ #!/usr/bin/env python -# -*- coding: euc-jp -*- - +# -*- coding: utf-8 -*- + ## # @file Properties.py @@ -16,40 +16,39 @@ # All rights reserved. +import OpenRTM_aist import sys if sys.version_info[0] == 2: - maxint = sys.maxint + maxint = sys.maxsize else: maxint = sys.maxsize -import OpenRTM_aist - ## # @if jp # # @class Properties -# @brief ץѥƥåȤɽ륯饹 +# @brief プロパティセットを表現するクラス # -# Properties 饹ϡѤΥץѥƥåȤɽ Properties 򥹥ȥ꡼ -# ݴɤꡢȥ꡼फɤꤹ뤳ȤǤ롣 -# ץѥƥꥹȤγƥӤбͤʸȤʤäƤ롣 +# Properties クラスは、不変のプロパティセットを表す。 Properties をストリーム +# に保管したり、ストリームからロードしたりすることができる。 +# プロパティリストの各キー、およびそれに対応する値は文字列となっている。 # -# ץѥƥꥹȤˤϡΡ֥ǥե͡פȤ̤ΥץѥƥꥹȤ -# ȤǤ롣ΥץѥƥꥹȤǥץѥƥĤʤȡ -# 2ܤΥץѥƥꥹȤ롣 +# プロパティリストには、その「デフォルト値」として別のプロパティリストを持つ +# ことができる。元のプロパティリストでプロパティキーが見つからないと、この +# 2番目のプロパティリストが検索される。 # -# ץѥƥμˤ getProperty() ץѥƥΥåȤˤ setProperty() -# ä᥽åɤѤ뤳Ȥ侩롣 +# プロパティの取得には getProperty() 、プロパティのセットには setProperty() と +# いったメソッドを使用することが推奨される。 # -# ץѥƥ򥹥ȥ꡼¸Ȥޤϥȥ꡼फɤȤ -# ˡISO 8859-1 ʸ󥳡ǥ󥰤Ѥ롣Υ󥳡ǥ󥰤 -# ľɽǤʤʸϡȤǤʤ +# プロパティをストリームに保存するとき、またはストリームからロードするとき +# に、ISO 8859-1 文字エンコーディングが使用される。このエンコーディングに +# 直接表示できない文字は、扱うことができない。 # -# Υ饹ϡJava Properties 饹 (java.util.Properties) ȤۤƱͤ -# ᥽åɤġޤϤե Java Properties 饹 -# ϤΤȸߴ뤬Unicode ޤΤϰȤǤʤ +# このクラスは、Java の Properties クラス (java.util.Properties) とほぼ同様の +# メソッドを持つ。また、入出力されるファイルは Java の Properties クラスが +# 出力するものと互換性があるが、Unicode を含むものは扱うことができない。 # # @since 0.4.0 # @@ -59,1324 +58,1314 @@ # # The Properties class represents a persistent set of properties. The # Properties can be saved to a stream or loaded from a stream. Each key and -# its corresponding value in the property list is a string. +# its corresponding value in the property list is a string. # # A property list can contain another property list as its "defaults"; this # second property list is searched if the property key is not found in the -# original property list. +# original property list. # # Because Properties inherits from Hashtable, the put and putAll methods can -# be applied to a Properties object. Their use is strongly discouraged as -# they allow the caller to insert entries whose keys or values are not -# Strings. The setProperty method should be used instead. If the store or -# save method is called on a "compromised" Properties object that contains a -# non-String key or value, the call will fail. +# be applied to a Properties object. Their use is strongly discouraged as +# they allow the caller to insert entries whose keys or values are not +# Strings. The setProperty method should be used instead. If the store or +# save method is called on a "compromised" Properties object that contains a +# non-String key or value, the call will fail. # # The load and store methods load and store properties in a simple # line-oriented format specified below. This format uses the ISO 8859-1 # character encoding. Characters that cannot be directly represented in this # encoding can be written using Unicode escapes ; only a single 'u' character # is allowed in an escape sequence. The native2ascii tool can be used to -# convert property files to and from other character encodings. +# convert property files to and from other character encodings. # -# This class has almost same methods of Java's Properties class. Input and +# This class has almost same methods of Java's Properties class. Input and # Output stream of this properties are compatible each other except Unicode # encoded property file. # # @endif class Properties: - """ - """ - - ## - # @if jp - # - # @brief 󥹥ȥ饯 - # - # ʲν˰å󥹥󥹤Ԥ - # - # prop ͤꤵƤ硢 - # Ϳ줿 Properties Υͤӥǥեͤ - # ƤΤޤޥԡ롣 - # - # key ͤꤵƤ硢 - # key value ΤߤͿ Property Υ롼ȥΡɤ롣 - # ͤƥǥեͤȤꤵ롣 - # - # defaults_map ͤꤵƤ硢 - # defaults_map ꤵ줿Ƥǥեͤˤ Properties 롣 - # ͤƥǥեͤȤꤵ롣 - # - # defaults_str ͤꤵƤ硢 - # ꤵ줿ǥեͤĶΥץѥƥꥹȤ롣 - # ͤƥǥեͤȤꤵ롣 - # ǥեͤ char* ˤͿ졢key value Фˤʤä - # ꡢꥹȤνüοɽ num ʸ key Ϳ - # ʤФʤʤ - # ʲ򼨤 - # - #

    -  # const char* defaults = {
    -  #     "key1", "value1",
    -  #     "key2", "value2",
    -  #     "key3", "value3",
    -  #     "key4", "value4",
    -  #     "key5", "value5",
    -  #     "" };
    -  # Properties p(defaults);
    -  # // ⤷
    -  # Properties p(defaults, 10);
    -  # 
    - # - # @param self - # @param key ץѥƥΥ(ǥե:None) - # @param value ץѥƥ(ǥե:None) - # @param defaults_map ǥեͤȤƻꤵmap(ǥե:None) - # @param defaults_str ǥեͤꤹ(ǥե:None) - # @param num ǥեͤꤹǿ(ǥե:None) - # @param prop ǥեͤȤƻꤵproperty(ǥե:None) - # - # @else - # - # @brief Constructor - # - # All of given Properties's keys, values and default values are copied to - # new Properties. - # - # Creates a root node of Property with root's key and value. - # - # Creates an Properties with default value of std::string map. - # - # Creates an empty property list with the specified defaults. - # The default values are given by array of char*, which should be pairs - # of "key" and "value". The end of list is specified by argument "num", - # which specifies number of array or null character of key. - # The following is an example. - # - # const char* defaults = { - # "key1", "value1", - # "key2", "value2", - # "key3", "value3", - # "key4", "value4", - # "key5", "value5", - # "" }; - # Properties p(defaults); - # // or - # Properties p(defaults, 10); - # - # @endif - def __init__(self, key=None, value=None, defaults_map=None, defaults_str=None, num=None, prop=None): - self.default_value = "" - self.root = None - self.empty = "" - self.leaf = [] - - # Properties::Properties(const Properties& prop) - if prop: - self.name = prop.name - self.value = prop.value - self.default_value = prop.default_value - - keys = prop.propertyNames() - for _key in keys: - node = prop.getNode(_key) - if node: - self.setDefault(_key, node.default_value) - self.setProperty(_key, node.value) - - return - - # Properties::Properties(const char* key, const char* value) - if key: - self.name = key - if value is None: - self.value = "" - else: - self.value = value - return - - self.name = "" - self.value = "" - - # Properties::Properties(std::map& defaults) - if defaults_map: - #for i in range(len(defaults_map.items())): - # self.setDefault(defaults_map.keys()[i], defaults_map.values()[i]) - for _key, _value in defaults_map.items(): - self.setDefault(_key, _value) - return - - if defaults_str: - if num is None: - _num = maxint - else: - _num = num - self.setDefaults(defaults_str, _num) - return - - - ## - # @if jp - # @brief 黻 - # - # ͤ Properties Υͤӥǥեͤƺ졢 - # ͤ Properties ΥͤӥǥեͤƤΤޤ - # ԡ롣 - # - # @param self - # @param prop OpenRTM_aist.Properties - # - # @else - # @brief Assignment operator - # @param self - # @param prop OpenRTM_aist.Properties - # @endif - def assigmentOperator(self, prop): - self.clear() - self.name = prop.name - self.value = prop.value - self.default_value = prop.default_value - - keys = prop.propertyNames() - - for key in keys: - node = prop.getNode(key) - if node: - self.setDefault(key, node.default_value) - self.setProperty(key, node.value) - - return self - - - ## - # @if jp - # - # @brief ǥȥ饯 - # - # @param self - # - # @else - # - # @brief Destructor - # - # @endif - def __del__(self): - self.clear() - if self.root: - self.root.removeNode(self.name) - return - - #============================================================ - # public functions - #============================================================ - - - ## - # @if jp - # @brief Name μ - # - # ץѥƥ̾Τ롣 - # - # @param self - # - # @return ץѥƥ̾ - # - # @else - # - # @endif - def getName(self): - return self.name - - - ## - # @if jp - # @brief ͤμ - # - # ץѥƥͤ롣 - # - # @param self - # - # @return ץѥƥ - # - # @else - # - # @endif - def getValue(self): - return self.value - - - ## - # @if jp - # @brief ǥեͤμ - # - # ץѥƥΥǥեͤ롣 - # - # @param self - # - # @return ץѥƥǥե - # - # @else - # - # @endif - def getDefaultValue(self): - return self.default_value - - - ## - # @if jp - # @brief Ǥμ - # - # ץѥƥλǤ롣 - # - # @param self - # - # @return - # - # @else - # - # @endif - def getLeaf(self): - return self.leaf - - - ## - # @if jp - # @brief 롼Ǥμ - # - # ץѥƥΥ롼Ǥ롣 - # - # @param self - # - # @return 롼 - # - # @else - # - # @endif - def getRoot(self): - return self.root - - - ## - # @if jp - # - # @brief ꤵ줿ĥץѥƥ򡢥ץѥƥꥹȤõ - # - # ꤵ줿ĥץѥƥ򡢥ץѥƥꥹȤõ - # ΥץѥƥꥹȤˤʤϡǥեͤΰ֤롣 - # - # @param self - # @param key ץѥƥ - # @param default ǥե(ǥե:None) - # - # @return ꤵ줿ͤĤΥץѥƥꥹȤ - # - # @else - # - # @brief Searches for the property with the specified key in this property - # - # Searches for the property with the specified key in this property list. - # The method returns the default value argument if the property is not - # found. - # - # @param key the property key - # @param defaultValue a default value. - # - # @return the value in this property list with the specified key value. - # - # @endif - def getProperty(self, key, default=None): - if default is None: - keys = [] - #keys = str.split(key, ".") - self.split(key, ".", keys) - - node = self._getNode(keys, 0, self) - if node: - if node.value: - return node.value + """ + """ + + ## + # @if jp + # + # @brief コンストラクタ + # + # 以下の順に引数をチェックし、インスタンスの生成を行う。 + # + # 引数 prop に値が設定されている場合、 + # 引数に与えられた Properties のキー、値およびデフォルト値が + # 全てそのままコピーされる。 + # + # 引数 key に値が設定されている場合、 + # key と value のみを与えて Property のルートノードを作成する。 + # 値は全てデフォルト値として設定される。 + # + # 引数 defaults_map に値が設定されている場合、 + # defaults_map に設定された内容をデフォルト値にもつ Properties を作成する。 + # 値は全てデフォルト値として設定される。 + # + # 引数 defaults_str に値が設定されている場合、 + # 指定されたデフォルト値を持つ空のプロパティリストを作成する。 + # 値は全てデフォルト値として設定される。 + # デフォルト値は char* の配列により与えられ、key と value の対になって + # おり、リストの終端は配列の数を表す引数 num か、空文字の key で与えらられ + # なければならない。 + # 以下に例を示す。 + # + #
    +    # const char* defaults = {
    +    #     "key1", "value1",
    +    #     "key2", "value2",
    +    #     "key3", "value3",
    +    #     "key4", "value4",
    +    #     "key5", "value5",
    +    #     "" };
    +    # Properties p(defaults);
    +    # // もしくは
    +    # Properties p(defaults, 10);
    +    # 
    + # + # @param self + # @param key プロパティのキー(デフォルト値:None) + # @param value プロパティの値(デフォルト値:None) + # @param defaults_map デフォルト値として指定されるmap(デフォルト値:None) + # @param defaults_str デフォルト値を指定する配列(デフォルト値:None) + # @param num デフォルト値を設定する要素数(デフォルト値:None) + # @param prop デフォルト値として指定されるproperty(デフォルト値:None) + # + # @else + # + # @brief Constructor + # + # All of given Properties's keys, values and default values are copied to + # new Properties. + # + # Creates a root node of Property with root's key and value. + # + # Creates an Properties with default value of std::string map. + # + # Creates an empty property list with the specified defaults. + # The default values are given by array of char*, which should be pairs + # of "key" and "value". The end of list is specified by argument "num", + # which specifies number of array or null character of key. + # The following is an example. + # + # const char* defaults = { + # "key1", "value1", + # "key2", "value2", + # "key3", "value3", + # "key4", "value4", + # "key5", "value5", + # "" }; + # Properties p(defaults); + # // or + # Properties p(defaults, 10); + # + # @endif + def __init__(self, key=None, value=None, defaults_map=None, + defaults_str=None, num=None, prop=None): + self.default_value = "" + self.root = None + self.empty = "" + self.leaf = [] + + # Properties::Properties(const Properties& prop) + if prop: + self.name = prop.name + self.value = prop.value + self.default_value = prop.default_value + + keys = prop.propertyNames() + for _key in keys: + node = prop.getNode(_key) + if node: + self.setDefault(_key, node.default_value) + self.setProperty(_key, node.value) + + return + + # Properties::Properties(const char* key, const char* value) + if key: + self.name = key + self.value = value + return + + self.name = "" + self.value = None + + # Properties::Properties(std::map& defaults) + if defaults_map: + # for i in range(len(defaults_map.items())): + # self.setDefault(defaults_map.keys()[i], defaults_map.values()[i]) + for _key, _value in defaults_map.items(): + self.setDefault(_key, _value) + return + + if defaults_str: + if num is None: + _num = maxint + else: + _num = num + self.setDefaults(defaults_str, _num) + return + + ## + # @if jp + # @brief 代入演算子 + # + # 左辺値の Properties のキー、値およびデフォルト値は全て削除され、 + # 右辺値の Properties のキー、値およびデフォルト値が全てそのまま + # コピーされる。 + # + # @param self + # @param prop OpenRTM_aist.Properties + # + # @else + # @brief Assignment operator + # @param self + # @param prop OpenRTM_aist.Properties + # @endif + + def assigmentOperator(self, prop): + self.clear() + self.name = prop.name + self.value = prop.value + self.default_value = prop.default_value + + keys = prop.propertyNames() + + for key in keys: + node = prop.getNode(key) + if node: + self.setDefault(key, node.default_value) + self.setProperty(key, node.value) + + return self + + ## + # @if jp + # + # @brief デストラクタ + # + # @param self + # + # @else + # + # @brief Destructor + # + # @endif + + def __del__(self): + self.clear() + if self.root: + self.root.removeNode(self.name) + return + + # ============================================================ + # public functions + # ============================================================ + + ## + # @if jp + # @brief Name の取得 + # + # プロパティの名称を取得する。 + # + # @param self + # + # @return プロパティ名 + # + # @else + # + # @endif + + def getName(self): + return self.name + + ## + # @if jp + # @brief 値の取得 + # + # プロパティの値を取得する。 + # + # @param self + # + # @return プロパティ値 + # + # @else + # + # @endif + + def getValue(self): + return self.value + + ## + # @if jp + # @brief デフォルト値の取得 + # + # プロパティのデフォルト値を取得する。 + # + # @param self + # + # @return プロパティデフォルト値 + # + # @else + # + # @endif + + def getDefaultValue(self): + return self.default_value + + ## + # @if jp + # @brief 子要素の取得 + # + # プロパティの子要素を取得する。 + # + # @param self + # + # @return 子要素 + # + # @else + # + # @endif + + def getLeaf(self): + return self.leaf + + ## + # @if jp + # @brief ルート要素の取得 + # + # プロパティのルート要素を取得する。 + # + # @param self + # + # @return ルート要素 + # + # @else + # + # @endif + + def getRoot(self): + return self.root + + ## + # @if jp + # + # @brief 指定されたキーを持つプロパティを、プロパティリストから探す + # + # 指定されたキーを持つプロパティを、プロパティリストから探す。 + # そのキーがプロパティリストにない場合は、デフォルト値の引数が返される。 + # + # @param self + # @param key プロパティキー + # @param default デフォルト値(デフォルト値:None) + # + # @return 指定されたキー値を持つこのプロパティリストの値 + # + # @else + # + # @brief Searches for the property with the specified key in this property + # + # Searches for the property with the specified key in this property list. + # The method returns the default value argument if the property is not + # found. + # + # @param key the property key + # @param defaultValue a default value. + # + # @return the value in this property list with the specified key value. + # + # @endif + + def getProperty(self, key, default=None): + if default is None: + keys = [] + #keys = str.split(key, ".") + self.split(key, ".", keys) + + node = self._getNode(keys, 0, self) + if node: + if node.value is not None: + return node.value + else: + return node.default_value + return self.empty + else: - return node.default_value - return self.empty + value = self.getProperty(key) + if value: + return value + else: + return default + + ## + # @if jp + # @brief 指定されたキーに対してデフォルト値を取得する + # + # 指定されたキーを持つプロパティのデフォルト値を返す。 + # 指定されたキーを持つプロパティが存在しない場合には空文字を返す。 + # + # @param self + # @param key プロパティキー + # + # @return 指定されたキー値を持つプロパティのデフォルト値 + # + # @else + # @brief Set value as the default value to specified key's property + # @endif + + def getDefault(self, key): + keys = [] + #keys = str.split(key, ".") + self.split(key, ".", keys) + + node = self._getNode(keys, 0, self) + if node: + return node.default_value + + return self.empty + + ## + # @if jp + # + # @brief Properties に value を key について登録する + # + # Properties に value を key について登録する。 + # すでに key に対する値を持っている場合、戻り値に古い値を返す。 + # + # @param self + # @param key プロパティリストに配置されるキー + # @param value key に対応する値(デフォルト値:None) + # + # @return プロパティリストの指定されたキーの前の値。それがない場合は null + # + # @else + # + # @brief Sets a value associated with key in the property list + # + # This method sets the "value" associated with "key" in the property list. + # If the property list has a value of "key", old value is returned. + # + # @param key the key to be placed into this property list. + # @param value the value corresponding to key. + # + # @return the previous value of the specified key in this property list, + # or null if it did not have one. + # + # @endif + + def setProperty(self, key, value=None): + if value is not None: + keys = [] + #keys = str.split(key, ".") + self.split(key, ".", keys) + curr = self + for _key in keys: + next = curr.hasKey(_key) + if next is None: + next = OpenRTM_aist.Properties(key=_key) + next.root = curr + curr.leaf.append(next) + curr = next + retval = curr.value + curr.value = value + return retval - else: - value = self.getProperty(key) - if value: + else: + self.setProperty(key, self.getProperty(key)) + prop = self.getNode(key) + return prop.value + + ## + # @if jp + # @brief デフォルト値を登録する + # + # key で指定される要素にデフォルト値を登録する。 + # + # @param self + # @param key デフォルト値を登録するプロパティのキー + # @param value 登録されるデフォルト値 + # + # @return 指定されたデフォルト値 + # + # @else + # @brief Sets a default value associated with key in the property list + # @endif + + def setDefault(self, key, value): + keys = [] + self.split(key, ".", keys) + #keys = str.split(key, ".") + + curr = self + for _key in keys: + next = curr.hasKey(_key) + if next is None: + next = OpenRTM_aist.Properties(key=_key) + next.root = curr + curr.leaf.append(next) + curr = next + if value != "" and value[-1] == "\n": + value = value[0:len(value) - 1] + curr.default_value = value return value - else: - return default - - - ## - # @if jp - # @brief ꤵ줿Фƥǥեͤ - # - # ꤵ줿ĥץѥƥΥǥե֤ͤ - # ꤵ줿ĥץѥƥ¸ߤʤˤ϶ʸ֤ - # - # @param self - # @param key ץѥƥ - # - # @return ꤵ줿ͤĥץѥƥΥǥե - # - # @else - # @brief Set value as the default value to specified key's property - # @endif - def getDefault(self, key): - keys = [] - #keys = str.split(key, ".") - self.split(key, ".", keys) - - node = self._getNode(keys, 0, self) - if node: - return node.default_value - - return self.empty - - - ## - # @if jp - # - # @brief Properties value key ˤĤϿ - # - # Properties value key ˤĤϿ롣 - # Ǥ key ФͤäƤ硢ͤ˸Ť֤ͤ - # - # @param self - # @param key ץѥƥꥹȤ֤륭 - # @param value key б(ǥե:None) - # - # @return ץѥƥꥹȤλꤵ줿͡줬ʤ null - # - # @else - # - # @brief Sets a value associated with key in the property list - # - # This method sets the "value" associated with "key" in the property list. - # If the property list has a value of "key", old value is returned. - # - # @param key the key to be placed into this property list. - # @param value the value corresponding to key. - # - # @return the previous value of the specified key in this property list, - # or null if it did not have one. - # - #@endif - def setProperty(self, key, value=None): - if value is not None: - keys = [] - #keys = str.split(key, ".") - self.split(key, ".", keys) - curr = self - for _key in keys: - next = curr.hasKey(_key) - if next is None: - next = OpenRTM_aist.Properties(key=_key) - next.root = curr - curr.leaf.append(next) - curr = next - retval = curr.value - curr.value = value - return retval - - else: - self.setProperty(key, self.getProperty(key)) - prop = self.getNode(key) - return prop.value - - - ## - # @if jp - # @brief ǥեͤϿ - # - # key ǻꤵǤ˥ǥեͤϿ롣 - # - # @param self - # @param key ǥեͤϿץѥƥΥ - # @param value Ͽǥե - # - # @return ꤵ줿ǥե - # - # @else - # @brief Sets a default value associated with key in the property list - # @endif - def setDefault(self, key, value): - keys = [] - self.split(key, ".", keys) - #keys = str.split(key, ".") - - curr = self - for _key in keys: - next = curr.hasKey(_key) - if next is None: - next = OpenRTM_aist.Properties(key=_key) - next.root = curr - curr.leaf.append(next) - curr = next - if value != "" and value[-1] == "\n": - value = value[0:len(value)-1] - curr.default_value = value - return value - - - ## - # @if jp - # @brief Properties ˥ǥեͤޤȤϿ - # - # ǻꤵ줿Ǥ˥ǥեͤޤȤϿ롣 - # ǥեͤ char* ˤͿ졢key value Фˤʤä - # ꡢꥹȤνüοɽ num ʸ key Ϳ - # ʤФʤʤ - # - # @param self - # @param defaults ǥեͤꤹ - # @param num ǥեͤꤹǿ(ǥե:None) - # - # @else - # @brief Sets a default value associated with key in the property list - # @endif - def setDefaults(self, defaults, num = None): - if num is None: - num = maxint - - i = 0 - len_ = len(defaults) - while 1: - if i > num or i > (len_ - 1) or defaults[i] == "": - break - - key = [defaults[i]] - value = [defaults[i+1]] - - OpenRTM_aist.eraseHeadBlank(key) - OpenRTM_aist.eraseTailBlank(key) - - OpenRTM_aist.eraseHeadBlank(value) - OpenRTM_aist.eraseTailBlank(value) - - self.setDefault(key[0], value[0]) - - i +=2 - - - - #============================================================ - # load and save functions - #============================================================ - - ## - # @if jp - # - # @brief ꤵ줿ϥȥ꡼ˡץѥƥꥹȤϤ - # - # ꤵ줿ϥȥ꡼ˡץѥƥꥹȤϤ롣 - # Υ᥽åɤϼ˥ǥХåѤ롣 - # - # @param self - # @param out ϥȥ꡼ - # - # @else - # - # @brief Prints this property list out to the specified output stream - # - # Prints this property list out to the specified output stream. - # This method is useful for debugging. - # - # @param out an output stream. - # - # @endif - def list(self, out): - self._store(out, "", self) - return - - - ## - # @if jp - # - # @brief ϥȥ꡼फ饭ǤФˤʤäץѥƥꥹȤɤ߹ - # - # ϥȥ꡼फ饭ǤФˤʤäץѥƥꥹȤɤ߹ࡣ - # ȥ꡼ϡISO 8859-1 ʸ󥳡ǥ󥰤ѤƤȤߤʤ롣 - # ƥץѥƥϡϥȥ꡼˹ñ̤ϿƤΤȤߤʤ졢 - # ƹԤϹԶڤʸ (\\n\\rޤ \\r\\n) ǽ롣 - # ϥȥ꡼फɤ߹Ԥϡϥȥ꡼ǥեν - # ãޤǽ롣 - # - # ʸιԡޤϺǽʸ ASCII ʸ # ޤ ! Ǥ - # Ԥ̵뤵롣Ĥޤꡢ# ޤ ! ϥȹԤ򼨤 - # - # Ԥޤϥȹ԰ʳΤ٤ƤιԤϡơ֥ɲäץѥƥ - # 򵭽Ҥ롣Ԥν꤬ \ ξϡιԤз³ԤȤ - # (򻲾) ϡǽʸ顢ǽ ASCII ʸ - # =:ޤ϶ʸľޤǤΡΤ٤Ƥʸ鹽롣 - # - # ν򼨤ʸϡ \ դ뤳Ȥˤꥭ˴ޤ뤳Ȥ - # Ǥ롣θζϤ٤ƥåפ롣 - # θκǽʸ = ޤ : ǤϡΥ - # ̵뤵졢ΤȤζʸ⤹٤ƥåפ롣 - # ΤʳʸϤ٤ơϢʸΰȤʤ롣 - # ʸǤϡASCII ץ \\t\\n\\r\\\\\\" - # \\'\\ (ߵȥڡ) \\uxxxx ǧ졢ñȤʸѴ - # 롣 - # ޤԤκǸʸ \ ǤϡιԤϸߤιԤη³Ȥ - # 롣ξ硢\ ȹԶڤʸ˴졢³ԤƬ˶ - # Ф⤹٤˴졢ʸΰˤϤʤʤ - # - # ȤС 4 ԤϤ줾쥭 Truth ȴϢ Beauty ɽ - # - # Truth = Beauty
    - # Truth:Beauty
    - # Truth\\t\\t\\t:Beauty
    - # - # ޤ 3 Ԥ 1 ĤΥץѥƥɽ - # - # fruits\\t\\t\\t\\tapple, banana, pear, \
    - # cantaloupe, watermelon, \
    - # kiwi, mango
    - # fruits ǡǤ˴Ϣդ롣 - # "apple, banana, pear, cantaloupe, watermelon, kiwi, mango" - # ǽŪʷ̤ǥޤΤȤɬڡɽ褦ˡ - # \ ˥ڡ롣Ԥν򼨤 \ ȡ³ԤƬˤ - # ˴졢¾ʸִʤ - # ޤ 3 ܤǤϡ cheeses ǡϢǤʸ - # Ǥ뤳Ȥɽ - # - # cheeses
    - # ϡcheeses ǡϢǤ϶ʸǤ뤳ȤꤷƤ롣 - # - # @param self - # @param inStream ϥȥ꡼ - # - # @else - # - # @brief Loads property list consists of key:value from input stream - # - # Reads a property list (key and element pairs) from the input stream. - # The stream is assumed to be using the ISO 8859-1 character encoding; that - # is each byte is one Latin1 character. Characters not in Latin1, and - # certain special characters, can be represented in keys and elements using - # escape sequences similar to those used for character and string literals - # The differences from the character escape sequences used for characters - # and strings are: - # - Octal escapes are not recognized. - # - The character sequence \b does not represent a backspace character. - # - The method does not treat a backslash character, \, before a non-valid - # escape character as an error; the backslash is silently dropped. For - # example, in a Java string the sequence "\z" would cause a compile time - # error. In contrast, this method silently drops the backslash. - # Therefore, this method treats the two character sequence "\b" as - # equivalent to the single character 'b'. - # - Escapes are not necessary for single and double quotes; however, by the - # rule above, single and double quote characters preceded by a backslash - # still yield single and double quote characters, respectively. - # An IllegalArgumentException is thrown if a malformed Unicode escape - # appears in the input. - # - # This method processes input in terms of lines. A natural line of input is - # terminated either by a set of line terminator characters - # (\n or \r or \r\n) or by the end of the file. A natural line may be - # either a blank line, a comment line, or hold some part of a key-element - # pair. The logical line holding all the data for a key-element pair may - # be spread out across several adjacent natural lines by escaping the line - # terminator sequence with a backslash character, \. Note that a comment - # line cannot be extended in this manner; every natural line that is a - # comment must have its own comment indicator, as described below. If a - # logical line is continued over several natural lines, the continuation - # lines receive further processing, also described below. Lines are read - # from the input stream until end of file is reached. - # - # A natural line that contains only white space characters is considered - # blank and is ignored. A comment line has an ASCII '#' or '!' as its first - # non-white space character; comment lines are also ignored and do not - # encode key-element information. In addition to line terminators, this - # method considers the characters space (' ', '\u0020'), tab - # ('\t', '\u0009'), and form feed ('\f', '\u000C') to be white space. - # - # If a logical line is spread across several natural lines, the backslash - # escaping the line terminator sequence, the line terminator sequence, and - # any white space at the start the following line have no affect on the key - # or element values. The remainder of the discussion of key and element - # parsing will assume all the characters constituting the key and element - # appear on a single natural line after line continuation characters have - # been removed. Note that it is not sufficient to only examine the - # character preceding a line terminator sequence to see if the line - # terminator is escaped; there must be an odd number of contiguous - # backslashes for the line terminator to be escaped. Since the input is - # processed from left to right, a non-zero even number of 2n contiguous - # backslashes before a line terminator (or elsewhere) encodes n - # backslashes after escape processing. - # - # The key contains all of the characters in the line starting with the - # first non-white space character and up to, but not including, the first - # unescaped '=', ':', or white space character other than a line - # terminator. All of these key termination characters may be included in - # the key by escaping them with a preceding backslash character; - # for example, - # - # \:\= - # - # would be the two-character key ":=". Line terminator characters can be - # included using \r and \n escape sequences. Any white space after the key - # is skipped; if the first non-white space character after the key is '=' - # or ':', then it is ignored and any white space characters after it are - # also skipped. All remaining characters on the line become part of the - # associated element string; if there are no remaining characters, the - # element is the empty string "". Once the raw character sequences - # constituting the key and element are identified, escape processing is - # performed as described above. - # - # As an example, each of the following three lines specifies the key - # "Truth" and the associated element value "Beauty": - # - # Truth = Beauty
    - # Truth:Beauty
    - # Truth :Beauty
    - # As another example, the following three lines specify a single - # property: - # - # fruits apple, banana, pear, \
    - # cantaloupe, watermelon, \
    - # kiwi, mango
    - # The key is "fruits" and the associated element is: - # "apple, banana, pear, cantaloupe, watermelon, kiwi, mango"Note that a - # space appears before each \ so that a space will appear after each comma - # in the final result; the \, line terminator, and leading white space on - # the continuation line are merely discarded and are not replaced by one or - # more other characters. - # As a third example, the line: - # - # cheeses
    - # specifies that the key is "cheeses" and the associated element is the - # empty string "". - # - # @param inStream the input stream. - # - # @endif - def load(self, inStream): - pline = "" - for readStr in inStream: - if not readStr: - continue - - tmp = [readStr] - OpenRTM_aist.eraseHeadBlank(tmp) - _str = tmp[0] - - if _str[0] == "#" or _str[0] == "!" or _str[0] == "\n" or (_str[0] == "\r" and _str[1] == "\n"): - continue - - _str = _str.rstrip('\r\n') - _str = _str.rstrip('\n') - - if not _str: - continue - - if _str[len(_str)-1] == "\\" and not OpenRTM_aist.isEscaped(_str, len(_str)-1): - #_str = _str[0:len(_str)-1] - tmp = [_str[0:len(_str)-1]] - OpenRTM_aist.eraseTailBlank(tmp) - #pline += _str - pline += tmp[0] - continue - pline += _str - #if pline == "": - # continue - - key = [] - value = [] - self.splitKeyValue(pline, key, value) - key[0] = OpenRTM_aist.unescape(key[0]) - key[0] = key[0].strip() - - value[0] = OpenRTM_aist.unescape(value[0]) - value[0] = value[0].strip() - - self.setProperty(key[0], value[0]) - pline = "" - - - ## - # @if jp - # - # @brief ץѥƥꥹȤꤵ줿ȥ꡼¸ - # - # ץѥƥꥹȤꤵ줿ȥ꡼¸롣 - # Υ᥽åɤ Java Properties ȤθߴΤƤ롣 - # (Ūˤ store ᥽åɤѤƤ롣) - # - # @param self - # @param out ϥȥ꡼ - # @param header ץѥƥꥹȤε - # - # @else - # - # @brief Save the properties list to the stream - # - # Deprecated. - # - # @param out The output stream - # @param header A description of the property list - # - # @endif - def save(self, out, header): - self.store(out, header) - return - - - ## - # @if jp - # - # @brief ץѥƥꥹȤϥȥ꡼¸ - # - # Properties ơ֥Υץѥƥꥹ (ǤΥڥ) load - # ᥽åɤȤä Properties ơ֥˥ɤΤŬڤʥեޥåȤ - # ϥȥ꡼˽񤭹ࡣ - # - # Properties ơ֥Υץѥƥꥹ (ǤΥڥ) load - # ᥽åɤȤä Properties ơ֥˥ɤΤŬڤʥեޥåȤ - # ϥȥ꡼˽񤭹ࡣȥ꡼ϡISO 8859-1 ʸ - # 󥳡ǥ󥰤Ѥƽ񤭹ޤ롣 - # Properties ơ֥ (¸ߤ) Υǥեȥơ֥뤫 - # ץѥƥϡΥ᥽åɤˤäƤϽ񤭹ޤʤ - # - # header null ǤʤϡASCII ʸ #header ʸ - # ӹԶڤʸǽ˽ϥȥ꡼˽񤭹ޤޤΤᡢ - # header ϼ̥ȤȤƻȤȤǤ롣 - # - # ˡASCII ʸ #ߤ (Date toString ᥽åɤˤä - # ߻郎ΤƱ) Writer ˤäԶڤ - # ʤ륳ȹԤ񤭹ޤ롣 - # - # ³ơ Properties ơ֥Τ٤ƤΥȥ꤬ 1 ԤĽ񤭽Ф롣 - # ƥȥΥʸASCII ʸ=Ϣʸ󤬽񤭹ޤ롣 - # ʸγʸϡץ󥹤Ȥ褹ɬפ뤫 - # ɤǧ롣ASCII ʸ \֡ԡϤ줾 \\\\ - # \\t\\n \\r Ȥƽ񤭹ޤ롣\\u0020 꾮ʸ - # \\u007E 礭ʸϡб 16 xxxx Ȥä \\uxxxx Ȥ - # 񤭹ޤ롣߶ʸǤ񤭶ʸǤʤԶʸϡ - # \ դƽ񤭹ޤ롣ͤʸ #!= : ϡ - # ɬɤ褦ˡ˥åդƽ񤭹ޤ롣 - # - # ȥ꤬񤭹ޤ줿Ȥǡϥȥ꡼बեå夵롣 - # ϥȥ꡼ϤΥ᥽åɤȤⳫޤޤȤʤ롣 - # - # @param self - # @param out ϥȥ꡼ - # @param header ץѥƥꥹȤε - # - # @else - # - # @brief Stores property list to the output stream - # - # Writes this property list (key and element pairs) in this Properties - # table to the output stream in a format suitable for loading into a - # Properties table using the load method. The stream is written using the - # ISO 8859-1 character encoding. - # - # Properties from the defaults table of this Properties table (if any) are - # not written out by this method. - # - # If the comments argument is not null, then an ASCII # character, the - # comments string, and a line separator are first written to the output - # stream. Thus, the comments can serve as an identifying comment. - # - # Next, a comment line is always written, consisting of an ASCII # - # character, the current date and time (as if produced by the toString - # method of Date for the current time), and a line separator as generated - # by the Writer. - # - # Then every entry in this Properties table is written out, one per line. - # For each entry the key string is written, then an ASCII =, then the - # associated element string. Each character of the key and element strings - # is examined to see whether it should be rendered as an escape sequence. - # The ASCII characters \, tab, form feed, newline, and carriage return are - # written as \\, \t, \f \n, and \r, respectively. Characters less than - # \u0020 and characters greater than \u007E are written as \uxxxx for the - # appropriate hexadecimal value xxxx. For the key, all space characters are - # written with a preceding \ character. For the element, leading space - # characters, but not embedded or trailing space characters, are written - # with a preceding \ character. The key and element characters #, !, =, and - # : are written with a preceding backslash to ensure that they are properly - # loaded. - # - # After the entries have been written, the output stream is flushed. The - # output stream remains open after this method returns. - # - # @param out an output stream. - # @param header a description of the property list. - # - # @endif - def store(self, out, header): - out.write("#"+header+"\n") - self._store(out, "", self) - - - #============================================================ - # other util functions - #============================================================ - - ## - # @if jp - # - # @brief ץѥƥΥΥꥹȤ vector ֤ - # - # ᥤץѥƥꥹȤƱ̾ΥĤʤϡǥեȤ - # ץѥƥꥹȤˤ̤ΥޤࡢΥץѥƥꥹȤˤ뤹٤ - # ΥΥꥹȤ֤ - # - # @param self - # - # @return ץѥƥꥹȤˤ뤹٤ƤΥΥꥹȡ - # ǥեȤΥץѥƥꥹȤˤ륭ޤ - # - # @else - # - # @brief Returns an vector of all the keys in this property - # - # Returns an enumeration of all the keys in this property list, including - # distinct keys in the default property list if a key of the same name has - # not already been found from the main properties list. - # - # @return an vector of all the keys in this property list, including the - # keys in the default property list. - # - # @endif - def propertyNames(self): - names = [] - for leaf in self.leaf: - self._propertyNames(names, leaf.name, leaf) - return names - - - ## - # @if jp - # @brief ץѥƥο - # - # ѤߤΥץѥƥ롣 - # - # @param self - # - # @return ץѥƥ - # - # @else - # @brief Get number of Properties - # @endif - def size(self): - return len(self.propertyNames()) - - - ## - # @if jp - # @brief Ρɤ򸡺 - # @else - # @brief Find node of properties - # @endif - # Properties* const Properties::findNode(const std::string& key) const - def findNode(self, key): - if not key: - return None - - keys = [] - self.split(key, '.', keys) - return self._getNode(keys, 0, self) - - - ## - # @if jp - # @brief Ρɤ - # - # ꤷĥΡɤ롣 - # - # @param self - # @param key оݥΡɤΥ - # - # @return оݥΡ - # - # @else - # @brief Get node of Properties - # @endif - def getNode(self, key): - if not key: - return self - - leaf = self.findNode(key) - if leaf: - return leaf - - self.createNode(key) - return self.findNode(key) - - - ## - # @if jp - # @brief Ρɤ - # - # ꤷĿΡɤ롣 - # Ʊ쥭ĥΡɤϿѤߤξˤϥ顼֤ - # - # @param self - # @param key ΡɤΥ - # - # @return Ρ - # ꤷĥΡɤ¸ߤˤfalse - # - # @else - # - # @endif - def createNode(self, key): - if not key: - return False - - if self.findNode(key): - return False - - self.setProperty(key,"") - return True - - - ## - # @if jp - # @brief Ρɤ - # - # ꤷ̾Τĥץѥƥ롣 - # ץѥƥ֤ - # - # @param self - # @param leaf_name оݥץѥƥ̾ - # - # @return ץѥƥ - # - # @else - # @brief Get node of Properties - # @endif - def removeNode(self, leaf_name): - len_ = len(self.leaf) - for i in range(len_): - idx = (len_ - 1) - i - if self.leaf[idx].name == leaf_name: - prop = self.leaf[idx] - del self.leaf[idx] - return prop - return None - - - ## - # @if jp - # @brief ҥΡɤkey뤫ɤ - # - # ꤷĻҥΡɤ¸ߤ뤫ɤǧ롣 - # ¸ߤ硢ҥΡɤ֤ - # - # @param self - # @param key ǧоݤΥ - # - # @return ҥΡ - # - # @else - # @brief If key exists in the children - # @endif - def hasKey(self, key): - for leaf in self.leaf: - if leaf.name == key: - return leaf - - return None - - - ## - # @if jp - # @brief ҥΡɤƺ - # - # @param self - # - # @else - # @brief If key exists in the children - # @endif - def clear(self): - len_ = len(self.leaf) - for i in range(len_): - if self.leaf[-1]: - del self.leaf[-1] - - return - - - ## - # @if jp - # @brief Propertyޡ - # - # ߤΥץѥƥꤷץѥƥޡ롣 - # - # @param self - # @param prop ޡץѥƥ - # - # @return ץѥƥޡ - # - # @else - # @brief Merge properties - # @endif - def mergeProperties(self, prop): - keys = prop.propertyNames() - - for i in range(prop.size()): - self.setProperty(keys[i], prop.getProperty(keys[i])) - - return self - - - ## - # @if jp - # @brief ʸ򥭡ͤΥڥʬ䤹 - # - # Ϳ줿ʸꤵ줿ǥߥǥͤΥڥʬ䤹롣 - # ޤǽͿ줿ʸ':'⤷'='ޤޤ뤫򸡺 - # ɤ餫ʸޤޤƤˤϤǥߥȤƻѤ롣 - # ξȤޤޤƤʤˤϡ' '(ڡ)Ѥʬߤ롣 - # ƤΥǥߥ䤬ޤޤƤʤˤϡͿ줿ʸ򥭡Ȥ - # ꤷͤ˶ʸꤹ롣 - # ɤΥǥߥˤĤƤ⥨פƤ(ľ'\'ꤵƤ) - # ˤϡǥߥȤƻѤʤ - # - # @param self - # @param _str ʬоʸ - # @param key ʬ̥ - # @param value ʬ - # - # @else - # - # @endif - def splitKeyValue(self, _str, key, value): - i = 0 - length = len(_str) - - while i < length: - if (_str[i] == ":" or _str[i] == "=") and not OpenRTM_aist.isEscaped(_str, i): - key.append(_str[0:i]) - value.append(_str[i+1:]) + + ## + # @if jp + # @brief Properties にデフォルト値をまとめて登録する + # + # 配列で指定された要素にデフォルト値をまとめて登録する。 + # デフォルト値は char* の配列により与えられ、key と value の対になって + # おり、リストの終端は配列の数を表す引数 num か、空文字の key で与えらられ + # なければならない。 + # + # @param self + # @param defaults デフォルト値を指定する配列 + # @param num デフォルト値を設定する要素数(デフォルト値:None) + # + # @else + # @brief Sets a default value associated with key in the property list + # @endif + + def setDefaults(self, defaults, num=None): + if num is None: + num = maxint + + i = 0 + len_ = len(defaults) + while True: + if i > num or i > (len_ - 1) or defaults[i] == "": + break + + key = defaults[i] + value = defaults[i + 1] + + key = OpenRTM_aist.eraseHeadBlank(key) + key = OpenRTM_aist.eraseTailBlank(key) + + value = OpenRTM_aist.eraseHeadBlank(value) + value = OpenRTM_aist.eraseTailBlank(value) + + self.setDefault(key, value) + + i += 2 + + # ============================================================ + # load and save functions + # ============================================================ + + ## + # @if jp + # + # @brief 指定された出力ストリームに、プロパティリストを出力する + # + # 指定された出力ストリームに、プロパティリストを出力する。 + # このメソッドは主にデバッグに用いられる。 + # + # @param self + # @param out 出力ストリーム + # + # @else + # + # @brief Prints this property list out to the specified output stream + # + # Prints this property list out to the specified output stream. + # This method is useful for debugging. + # + # @param out an output stream. + # + # @endif + + def list(self, out): + self._store(out, "", self) + return + + ## + # @if jp + # + # @brief 入力ストリームからキーと要素が対になったプロパティリストを読み込む + # + # 入力ストリームからキーと要素が対になったプロパティリストを読み込む。 + # ストリームは、ISO 8859-1 文字エンコーディングを使用しているとみなされる。 + # 各プロパティは、入力ストリームに行単位で登録されているものとみなされ、 + # 各行は行区切り文字 (\\n、\\r、または \\r\\n) で終わる。 + # 入力ストリームから読み込んだ行は、入力ストリームでファイルの終わりに + # 達するまで処理される。 + # + # 空白文字だけの行、または最初の非空白文字が ASCII 文字 # または ! である + # 行は無視される。つまり、# または ! はコメント行を示す。 + # + # 空白行またはコメント行以外のすべての行は、テーブルに追加されるプロパティ + # を記述する。ただし、行の終わりが \ の場合は、次の行があれば継続行として + # 扱われる (下記を参照)。 キーは、最初の非空白文字から、最初の ASCII 文字 + # =、:、または空白文字の直前までの、行内のすべての文字から構成される。 + # + # キーの終わりを示す文字は、前に \ を付けることによりキーに含めることも + # できる。キーの後ろの空白はすべてスキップされる。 + # キーの後ろの最初の非空白文字が = または : である場合は、これらのキーは + # 無視され、そのあとの空白文字もすべてスキップされる。 + # 行内のそれ以外の文字はすべて、関連した要素文字列の一部となる。 + # 要素文字列内では、ASCII エスケープシーケンス \\t、\\n、\\r、\\\\、\\"、 + # \\'、\\ (円記号とスペース)、および \\uxxxx は認識され、単独の文字に変換 + # される。 + # また、行の最後の文字が \ である場合は、次の行は現在の行の継続として + # 扱われる。その場合、\ と行区切り文字が破棄され、継続行の先頭に空白が + # あればそれもすべて破棄され、要素文字列の一部にはならない。 + # + # たとえば、次の 4 行はそれぞれキー Truth と関連した要素値 Beauty を表す。 + # + # Truth = Beauty
    + # Truth:Beauty
    + # Truth\\t\\t\\t:Beauty
    + # + # また、次の 3 行は 1 つのプロパティを表す。 + # + # fruits\\t\\t\\t\\tapple, banana, pear, \
    + # cantaloupe, watermelon, \
    + # kiwi, mango
    + # キーは fruits で、次の要素に関連付けれられる。 + # "apple, banana, pear, cantaloupe, watermelon, kiwi, mango" + # 最終的な結果でコンマのあとに必ずスペースが表示されるように、 + # 各 \ の前にスペースがある。行の終わりを示す \ と、継続行の先頭にある + # 空白は破棄され、他の文字に置換されない。 + # また、次の 3 番目の例では、キーが cheeses で、関連した要素が空の文字列 + # であることを表す。 + # + # cheeses
    + # キーは、cheeses で、関連要素は空の文字列であることを指定している。 + # + # @param self + # @param inStream 入力ストリーム + # + # @else + # + # @brief Loads property list consists of key:value from input stream + # + # Reads a property list (key and element pairs) from the input stream. + # The stream is assumed to be using the ISO 8859-1 character encoding; that + # is each byte is one Latin1 character. Characters not in Latin1, and + # certain special characters, can be represented in keys and elements using + # escape sequences similar to those used for character and string literals + # The differences from the character escape sequences used for characters + # and strings are: + # - Octal escapes are not recognized. + # - The character sequence \b does not represent a backspace character. + # - The method does not treat a backslash character, \, before a non-valid + # escape character as an error; the backslash is silently dropped. For + # example, in a Java string the sequence "\z" would cause a compile time + # error. In contrast, this method silently drops the backslash. + # Therefore, this method treats the two character sequence "\b" as + # equivalent to the single character 'b'. + # - Escapes are not necessary for single and double quotes; however, by the + # rule above, single and double quote characters preceded by a backslash + # still yield single and double quote characters, respectively. + # An IllegalArgumentException is thrown if a malformed Unicode escape + # appears in the input. + # + # This method processes input in terms of lines. A natural line of input is + # terminated either by a set of line terminator characters + # (\n or \r or \r\n) or by the end of the file. A natural line may be + # either a blank line, a comment line, or hold some part of a key-element + # pair. The logical line holding all the data for a key-element pair may + # be spread out across several adjacent natural lines by escaping the line + # terminator sequence with a backslash character, \. Note that a comment + # line cannot be extended in this manner; every natural line that is a + # comment must have its own comment indicator, as described below. If a + # logical line is continued over several natural lines, the continuation + # lines receive further processing, also described below. Lines are read + # from the input stream until end of file is reached. + # + # A natural line that contains only white space characters is considered + # blank and is ignored. A comment line has an ASCII '#' or '!' as its first + # non-white space character; comment lines are also ignored and do not + # encode key-element information. In addition to line terminators, this + # method considers the characters space (' ', '\u0020'), tab + # ('\t', '\u0009'), and form feed ('\f', '\u000C') to be white space. + # + # If a logical line is spread across several natural lines, the backslash + # escaping the line terminator sequence, the line terminator sequence, and + # any white space at the start the following line have no affect on the key + # or element values. The remainder of the discussion of key and element + # parsing will assume all the characters constituting the key and element + # appear on a single natural line after line continuation characters have + # been removed. Note that it is not sufficient to only examine the + # character preceding a line terminator sequence to see if the line + # terminator is escaped; there must be an odd number of contiguous + # backslashes for the line terminator to be escaped. Since the input is + # processed from left to right, a non-zero even number of 2n contiguous + # backslashes before a line terminator (or elsewhere) encodes n + # backslashes after escape processing. + # + # The key contains all of the characters in the line starting with the + # first non-white space character and up to, but not including, the first + # unescaped '=', ':', or white space character other than a line + # terminator. All of these key termination characters may be included in + # the key by escaping them with a preceding backslash character; + # for example, + # + # \:\= + # + # would be the two-character key ":=". Line terminator characters can be + # included using \r and \n escape sequences. Any white space after the key + # is skipped; if the first non-white space character after the key is '=' + # or ':', then it is ignored and any white space characters after it are + # also skipped. All remaining characters on the line become part of the + # associated element string; if there are no remaining characters, the + # element is the empty string "". Once the raw character sequences + # constituting the key and element are identified, escape processing is + # performed as described above. + # + # As an example, each of the following three lines specifies the key + # "Truth" and the associated element value "Beauty": + # + # Truth = Beauty
    + # Truth:Beauty
    + # Truth :Beauty
    + # As another example, the following three lines specify a single + # property: + # + # fruits apple, banana, pear, \
    + # cantaloupe, watermelon, \
    + # kiwi, mango
    + # The key is "fruits" and the associated element is: + # "apple, banana, pear, cantaloupe, watermelon, kiwi, mango"Note that a + # space appears before each \ so that a space will appear after each comma + # in the final result; the \, line terminator, and leading white space on + # the continuation line are merely discarded and are not replaced by one or + # more other characters. + # As a third example, the line: + # + # cheeses
    + # specifies that the key is "cheeses" and the associated element is the + # empty string "". + # + # @param inStream the input stream. + # + # @endif + + def load(self, inStream): + pline = "" + for readStr in inStream: + if not readStr: + continue + + _str = OpenRTM_aist.eraseHeadBlank(readStr) + + if _str[0] == "#" or _str[0] == "!" or _str[0] == "\n" or ( + _str[0] == "\r" and _str[1] == "\n"): + continue + + _str = _str.rstrip('\r\n') + _str = _str.rstrip('\n') + + if not _str: + continue + + if _str[len( + _str) - 1] == "\\" and not OpenRTM_aist.isEscaped(_str, len(_str) - 1): + pline += OpenRTM_aist.eraseTailBlank(_str[0:len(_str) - 1]) + continue + pline += _str + # if pline == "": + # continue + + key = [] + value = [] + self.splitKeyValue(pline, key, value) + key[0] = OpenRTM_aist.unescape(key[0]) + key[0] = key[0].strip() + + value[0] = OpenRTM_aist.unescape(value[0]) + value[0] = value[0].strip() + + self.setProperty(key[0], value[0]) + pline = "" + + ## + # @if jp + # + # @brief プロパティリストを指定されたストリームに保存する + # + # プロパティリストを指定されたストリームに保存する。 + # このメソッドは Java Properties との互換性のために定義されている。 + # (内部的には store メソッドを利用している。) + # + # @param self + # @param out 出力ストリーム + # @param header プロパティリストの記述 + # + # @else + # + # @brief Save the properties list to the stream + # + # Deprecated. + # + # @param out The output stream + # @param header A description of the property list + # + # @endif + + def save(self, out, header): + self.store(out, header) + return + + ## + # @if jp + # + # @brief プロパティリストを出力ストリームへ保存する + # + # Properties テーブル内のプロパティリスト (キーと要素のペア) を、load + # メソッドを使って Properties テーブルにロードするのに適切なフォーマットで + # 出力ストリームに書き込む。 + # + # Properties テーブル内のプロパティリスト (キーと要素のペア) を、load + # メソッドを使って Properties テーブルにロードするのに適切なフォーマットで + # 出力ストリームに書き込む。ストリームは、ISO 8859-1 文字 + # エンコーディングを使用して書き込まれる。 + # Properties テーブル (存在する場合) のデフォルトテーブルからの + # プロパティは、このメソッドによっては書き込まれない。 + # + # header 引数が null でない場合は、ASCII 文字の #、header の文字列、 + # および行区切り文字が最初に出力ストリームに書き込まれます。このため、 + # header は識別コメントとして使うことができる。 + # + # 次に、ASCII 文字の #、現在の日時 (Date の toString メソッドによって + # 現在時刻が生成されるのと同様)、および Writer によって生成される行区切り + # からなるコメント行が書き込まれる。 + # + # 続いて、 Properties テーブル内のすべてのエントリが 1 行ずつ書き出される。 + # 各エントリのキー文字列、ASCII 文字の=、関連した要素文字列が書き込まれる。 + # 要素文字列の各文字は、エスケープシーケンスとして描画する必要があるか + # どうか確認される。ASCII 文字の \、タブ、改行、および復帰はそれぞれ \\\\、 + # \\t、\\n、および \\r として書き込まれる。\\u0020 より小さい文字および + # \\u007E より大きい文字は、対応する 16 進値 xxxx を使って \\uxxxx として + # 書き込まれる。埋め込み空白文字でも後書き空白文字でもない先行空白文字は、 + # 前に \ を付けて書き込まれる。キーと値の文字 #、!、=、および : は、 + # 必ず正しくロードされるように、前にスラッシュを付けて書き込まれる。 + # + # エントリが書き込まれたあとで、出力ストリームがフラッシュされる。 + # 出力ストリームはこのメソッドから復帰したあとも開いたままとなる。 + # + # @param self + # @param out 出力ストリーム + # @param header プロパティリストの記述 + # + # @else + # + # @brief Stores property list to the output stream + # + # Writes this property list (key and element pairs) in this Properties + # table to the output stream in a format suitable for loading into a + # Properties table using the load method. The stream is written using the + # ISO 8859-1 character encoding. + # + # Properties from the defaults table of this Properties table (if any) are + # not written out by this method. + # + # If the comments argument is not null, then an ASCII # character, the + # comments string, and a line separator are first written to the output + # stream. Thus, the comments can serve as an identifying comment. + # + # Next, a comment line is always written, consisting of an ASCII # + # character, the current date and time (as if produced by the toString + # method of Date for the current time), and a line separator as generated + # by the Writer. + # + # Then every entry in this Properties table is written out, one per line. + # For each entry the key string is written, then an ASCII =, then the + # associated element string. Each character of the key and element strings + # is examined to see whether it should be rendered as an escape sequence. + # The ASCII characters \, tab, form feed, newline, and carriage return are + # written as \\, \t, \f \n, and \r, respectively. Characters less than + # \u0020 and characters greater than \u007E are written as \uxxxx for the + # appropriate hexadecimal value xxxx. For the key, all space characters are + # written with a preceding \ character. For the element, leading space + # characters, but not embedded or trailing space characters, are written + # with a preceding \ character. The key and element characters #, !, =, and + # : are written with a preceding backslash to ensure that they are properly + # loaded. + # + # After the entries have been written, the output stream is flushed. The + # output stream remains open after this method returns. + # + # @param out an output stream. + # @param header a description of the property list. + # + # @endif + + def store(self, out, header): + out.write("#" + header + "\n") + self._store(out, "", self) + + # ============================================================ + # other util functions + # ============================================================ + + ## + # @if jp + # + # @brief プロパティのキーのリストを vector で返す + # + # メインプロパティリストに同じ名前のキーが見つからない場合は、デフォルトの + # プロパティリストにある個別のキーを含む、このプロパティリストにあるすべて + # のキーのリストを返す。 + # + # @param self + # + # @return プロパティリストにあるすべてのキーのリスト。 + # デフォルトのプロパティリストにあるキーを含む + # + # @else + # + # @brief Returns an vector of all the keys in this property + # + # Returns an enumeration of all the keys in this property list, including + # distinct keys in the default property list if a key of the same name has + # not already been found from the main properties list. + # + # @return an vector of all the keys in this property list, including the + # keys in the default property list. + # + # @endif + + def propertyNames(self): + names = [] + for leaf in self.leaf: + self._propertyNames(names, leaf.name, leaf) + return names + + ## + # @if jp + # @brief プロパティの数を取得する + # + # 設定済みのプロパティ数を取得する。 + # + # @param self + # + # @return プロパティ数 + # + # @else + # @brief Get number of Properties + # @endif + + def size(self): + return len(self.propertyNames()) + + ## + # @if jp + # @brief ノードを検索する + # @else + # @brief Find node of properties + # @endif + # Properties* const Properties::findNode(const std::string& key) const + + def findNode(self, key): + if not key: + return None + + keys = [] + self.split(key, '.', keys) + return self._getNode(keys, 0, self) + + ## + # @if jp + # @brief ノードを取得する + # + # 指定したキーを持つノードを取得する。 + # + # @param self + # @param key 取得対象ノードのキー + # + # @return 対象ノード + # + # @else + # @brief Get node of Properties + # @endif + + def getNode(self, key): + if not key: + return self + + leaf = self.findNode(key) + if leaf: + return leaf + + self.createNode(key) + return self.findNode(key) + + ## + # @if jp + # @brief 新規ノードを生成する + # + # 指定したキーを持つ新規ノードを生成する。 + # 既に同一キーを持つノードが登録済みの場合にはエラーを返す。 + # + # @param self + # @param key 新規ノードのキー + # + # @return 新規ノード生成結果 + # 指定したキーを持つノードが既に存在する場合にはfalse + # + # @else + # + # @endif + + def createNode(self, key): + if not key: + return False + + if self.findNode(key): + return False + + self.setProperty(key, "") + return True + + ## + # @if jp + # @brief ノードを削除する + # + # 指定した名称を持つプロパティを削除する。 + # 削除したプロパティを返す。 + # + # @param self + # @param leaf_name 削除対象プロパティ名称 + # + # @return 削除したプロパティ + # + # @else + # @brief Get node of Properties + # @endif + + def removeNode(self, leaf_name): + len_ = len(self.leaf) + for i in range(len_): + idx = (len_ - 1) - i + if self.leaf[idx].name == leaf_name: + prop = self.leaf[idx] + del self.leaf[idx] + return prop + return None + + ## + # @if jp + # @brief 子ノードにkeyがあるかどうか + # + # 指定したキーを持つ子ノードが存在するかどうか確認する。 + # 存在する場合、子ノードを返す。 + # + # @param self + # @param key 確認対象のキー + # + # @return 子ノード + # + # @else + # @brief If key exists in the children + # @endif + + def hasKey(self, key): + for leaf in self.leaf: + if leaf.name == key: + return leaf + + return None + + ## + # @if jp + # @brief 子ノードを全て削除する + # + # @param self + # + # @else + # @brief If key exists in the children + # @endif + + def clear(self): + len_ = len(self.leaf) + for i in range(len_): + if self.leaf[-1]: + del self.leaf[-1] + return - i += 1 - - # If no ':' or '=' exist, ' ' would be delimiter. - i = 0 - while i < length: - if (_str[i] == " ") and not OpenRTM_aist.isEscaped(_str, i): - key.append(_str[0:i]) - value.append(_str[i+1:]) + + ## + # @if jp + # @brief Propertyをマージする + # + # 現在のプロパティに設定したプロパティをマージする。 + # + # @param self + # @param prop マージするプロパティ + # + # @return プロパティマージ結果 + # + # @else + # @brief Merge properties + # @endif + + def mergeProperties(self, prop): + keys = prop.propertyNames() + + for i in range(prop.size()): + self.setProperty(keys[i], prop.getProperty(keys[i])) + + return self + + ## + # @if jp + # @brief 文字列をキーと値のペアに分割する + # + # 与えられた文字列を、設定されたデリミタでキーと値のペアに分割する。 + # まず最初に与えられた文字列に':'もしくは'='が含まれるかを検索し、 + # どちらかの文字が含まれている場合にはそれをデリミタとして使用する。 + # 両方とも含まれていない場合には、' '(スペース)を用いて分割を試みる。 + # 全てのデリミタ候補が含まれていない場合には、与えられた文字列をキーとして + # 設定し、値に空の文字列を設定する。 + # どのデリミタ候補についてもエスケープされている(直前に'\'が設定されている) + # 場合には、デリミタとして使用しない。 + # + # @param self + # @param _str 分割対象文字列 + # @param key 分割結果キー + # @param value 分割結果値 + # + # @else + # + # @endif + + def splitKeyValue(self, _str, key, value): + i = 0 + length = len(_str) + + while i < length: + if (_str[i] == ":" or _str[i] == + "=") and not OpenRTM_aist.isEscaped(_str, i): + key.append(_str[0:i]) + value.append(_str[i + 1:]) + return + i += 1 + + # If no ':' or '=' exist, ' ' would be delimiter. + i = 0 + while i < length: + if (_str[i] == " ") and not OpenRTM_aist.isEscaped(_str, i): + key.append(_str[0:i]) + value.append(_str[i + 1:]) + return + i += 1 + + key.append(_str) + value.append("") return - i += 1 - - key.append(_str) - value.append("") - return - - - ## - # @if jp - # @brief ʸʬ䤹 - # - # Ϳ줿ʸͿ줿ǥߥʬ䤹롣 - # Ϳ줿ʸ󤬶ξϡ顼֤ - # Ϳ줿ǥߥפƤ(ľ'\'ꤵƤ) - # ˤϡǥߥȤƻѤʤ - # - # @param self - # @param _str ʬоʸ - # @param delim ǥߥ - # @param value ʬͥꥹ - # - # @return ʬ - # - # @else - # - # @endif - def split(self, _str, delim, value): - if _str == "": - return False - - begin_it = end_it = 0 - - length = len(_str) - - while end_it < length: - if _str[end_it] == delim and not OpenRTM_aist.isEscaped(_str, end_it): + + ## + # @if jp + # @brief 文字列を分割する + # + # 与えられた文字列を、与えられたデリミタで分割する。 + # 与えられた文字列が空の場合は、エラーを返す。 + # 与えられたデリミタがエスケープされている(直前に'\'が設定されている)場合 + # には、デリミタとして使用しない。 + # + # @param self + # @param _str 分割対象文字列 + # @param delim デリミタ + # @param value 分割結果値リスト + # + # @return 分割処理結果 + # + # @else + # + # @endif + + def split(self, _str, delim, value): + if _str == "": + return False + + begin_it = end_it = 0 + + length = len(_str) + + while end_it < length: + if _str[end_it] == delim and not OpenRTM_aist.isEscaped( + _str, end_it): + value.append(_str[begin_it:end_it]) + begin_it = end_it + 1 + end_it += 1 + value.append(_str[begin_it:end_it]) - begin_it = end_it + 1 - end_it += 1 - - value.append(_str[begin_it:end_it]) - return True - - - ## - # @if jp - # @brief ץѥƥ - # - # ꥹȤǻꤵ줿ץѥƥ롣 - # ꥹȤǤϡꤹ륭ΥץѥƥǤγشطꥹȷɽ - # 롣 - # ꤷꥹȤ˳ץѥƥ¸ߤʤNone֤ - # - # @param self - # @param keys оݥץѥƥΥΥꥹɽ - # @param index ꥹȤγؿ - # @param curr оݥץѥƥ - # - # @return оݥץѥƥ - # - # @else - # - # @endif - def _getNode(self, keys, index, curr): - next = curr.hasKey(keys[index]) - if next is None: - return None - - if index < (len(keys) - 1): - index+=1 - return next._getNode(keys, index, next) - else: - return next - - - - - ## - # @if jp - # @brief ץѥƥ̾ΥꥹȤ - # - # ץѥƥ̾Τ'.'ڤɽꥹȤ롣 - # - # @param self - # @param names ץѥƥ̾Υꥹ - # @param curr_name ߤΥץѥƥ̾ - # @param curr оݥץѥƥ - # - # @else - # - # @endif - def _propertyNames(self, names, curr_name, curr): - if len(curr.leaf) > 0: - for i in range(len(curr.leaf)): - next_name = curr_name+"."+curr.leaf[i].name - self._propertyNames(names, next_name, curr.leaf[i]) - else: - names.append(curr_name) - - return - - - ## - # @if jp - # @brief ץѥƥ̾ΥꥹȤ¸ - # - # ץѥƥ̾Τ'.'ڤɽꥹȤ¸롣 - # - # @param self - # @param out ץѥƥ̾Υꥹ¸νϥȥ꡼ - # @param curr_name ߤΥץѥƥ̾ - # @param curr оݥץѥƥ - # - # @else - # - # @endif - def _store(self, out, curr_name, curr): - if len(curr.leaf) > 0: - for i in range(len(curr.leaf)): - if curr_name == "": - next_name = curr.leaf[i].name + return True + + ## + # @if jp + # @brief プロパティを取得する + # + # キーリストで指定されたプロパティを取得する。 + # キーリストでは、指定するキーのプロパティでの階層関係をリスト形式で表現 + # する。 + # 指定したキーリストに該当するプロパティが存在しない場合はNoneを返す。 + # + # @param self + # @param keys 取得対象プロパティのキーのリスト表現 + # @param index キーリストの階層数 + # @param curr 検索対象プロパティ + # + # @return 検索対象プロパティ + # + # @else + # + # @endif + + def _getNode(self, keys, index, curr): + next = curr.hasKey(keys[index]) + if next is None: + return None + + if index < (len(keys) - 1): + index += 1 + return next._getNode(keys, index, next) + else: + return next + + ## + # @if jp + # @brief プロパティの名称リストを取得する + # + # プロパティの名称を'.'区切りで表現したリストを取得する。 + # + # @param self + # @param names プロパティの名称リスト + # @param curr_name 現在のプロパティ名 + # @param curr 対象プロパティ + # + # @else + # + # @endif + + def _propertyNames(self, names, curr_name, curr): + if curr.leaf: + for l in curr.leaf: + next_name = curr_name + "." + l.name + self._propertyNames(names, next_name, l) else: - next_name = curr_name+"."+curr.leaf[i].name - self._store(out, next_name, curr.leaf[i]) - - else: - val = curr.value - if val == "": - val = curr.default_value - out.write(curr_name+": "+val+"\n") - - return - - - ## - # @if jp - # @brief ǥȤ - # - # ꤵ줿˽äǥȤ֤ - # ֤륤ǥȤϡ2Ĥζ - # - # @param self - # @param index ǥȿλ - # - # @return 줿ǥ - # - # @else - # - # @endif - def indent(self, index): - space = "" - - for i in range(index-1): - space += " " - - return space - - - ## - # @if jp - # @brief ץѥƥƤ¸ - # - # ץѥƥꤵ줿Ƥ¸롣 - # ¸ˤϥץѥƥؤοɽղä롣 - # ͤꤵƤʤץѥƥˤĤƤϡǥեͤϤ롣 - # - # @param self - # @param out ץѥƥ¸νϥȥ꡼ - # @param curr оݥץѥƥ - # @param index ߤΥץѥƥ - # - # @else - # - # @endif - def _dump(self, out, curr, index): - if index != 0: - #ut.write(self.indent(index)+"- "+curr.name) - out[0]+=self.indent(index)+"- "+curr.name - - if curr.leaf == []: - if curr.value == "": - #out.write(": "+curr.default_value+"\n") - out[0]+=": "+curr.default_value+"\n" - else: - #out.write(": "+curr.value+"\n") - out[0]+=": "+str(curr.value)+"\n" - return out[0] - - if index != 0: - #out.write("\n") - out[0]+="\n" - - for i in range(len(curr.leaf)): - self._dump(out, curr.leaf[i], index + 1) - - return out[0] - - - ## - # @if jp - # @brief ץѥƥƤϤ - # - # ץѥƥꤵ줿ƤϤ롣
    - # friend std::ostream& operator<<(std::ostream& lhs, const Properties& rhs); - # ˡprint objˤƸƤӽФǽȤ뤿Υ᥽åɡ - # - # @param self - # - # @return ץѥƥʸɽ - # - # @else - # - # @endif - def __str__(self): - string=[""] - return self._dump(string, self, 0) - - + names.append(curr_name) + + return + + ## + # @if jp + # @brief プロパティの名称リストを保存する + # + # プロパティの名称を'.'区切りで表現したリストを保存する。 + # + # @param self + # @param out プロパティの名称リスト保存先の出力ストリーム + # @param curr_name 現在のプロパティ名 + # @param curr 対象プロパティ + # + # @else + # + # @endif + + def _store(self, out, curr_name, curr): + if curr.leaf: + for l in curr.leaf: + if curr_name == "": + next_name = l.name + else: + next_name = curr_name + "." + l.name + self._store(out, next_name, l) + + else: + val = curr.value + if val is None: + val = curr.default_value + out.write(curr_name + ": " + val + "\n") + + return + + ## + # @if jp + # @brief インデントを生成する + # + # 指定された数字に従って生成したインデントを返す。 + # 返されるインデントは、指定数字×2つの空白。 + # + # @param self + # @param index インデント数の指定 + # + # @return 生成されたインデント + # + # @else + # + # @endif + + def indent(self, index): + space = "" + + for i in range(index - 1): + space += " " + + return space + + ## + # @if jp + # @brief プロパティの内容を保存する + # + # プロパティに設定された内容を保存する。 + # 保存時にはプロパティ階層の深さを表す数字が付加される。 + # 値が設定されていないプロパティについては、デフォルト値が出力される。 + # + # @param self + # @param out プロパティ内容保存先の出力ストリーム + # @param curr 対象プロパティ + # @param index 現在のプロパティ階層 + # + # @else + # + # @endif + + def _dump(self, out, curr, index): + if index != 0: + #ut.write(self.indent(index)+"- "+curr.name) + out[0] += self.indent(index) + "- " + curr.name + + if curr.leaf == []: + if curr.value is None: + #out.write(": "+curr.default_value+"\n") + out[0] += ": " + curr.default_value + "\n" + else: + #out.write(": "+curr.value+"\n") + out[0] += ": " + str(curr.value) + "\n" + return out[0] + + if index != 0: + # out.write("\n") + out[0] += "\n" + + for l in curr.leaf: + self._dump(out, l, index + 1) + + return out[0] + + ## + # @if jp + # @brief プロパティの内容を出力する + # + # プロパティに設定された内容を出力する。
    + # friend std::ostream& operator<<(std::ostream& lhs, const Properties& rhs); + # の代わりに、print objにて呼び出し可能とするためのメソッド。 + # + # @param self + # + # @return 設定プロパティ文字列表示 + # + # @else + # + # @endif + def __str__(self): + string = [""] + return self._dump(string, self, 0) diff --git a/OpenRTM_aist/PublisherBase.py b/OpenRTM_aist/PublisherBase.py index fa6abf0a..b7a17569 100644 --- a/OpenRTM_aist/PublisherBase.py +++ b/OpenRTM_aist/PublisherBase.py @@ -1,5 +1,5 @@ -#!/usr/bin/env python -# -*- coding: euc-jp -*- +#!/usr/bin/env python +# -*- coding: utf-8 -*- ## # @file PublisherBase.py @@ -23,10 +23,10 @@ # # @class PublisherBase # -# @brief Publisher 쥯饹 -# -# ǡХߥ󥰤ФưPublisher* δ쥯饹 -# Ƽ Publisher ϤΥ饹Ѿƾܺ٤롣 +# @brief Publisher 基底クラス +# +# データ送出タイミングを管理して送出を駆動するPublisher* の基底クラス。 +# 各種 Publisher はこのクラスを継承して詳細を実装する。 # # @since 0.4.0 # @@ -42,113 +42,113 @@ # # @endif class PublisherBase(OpenRTM_aist.DataPortStatus): - """ - """ - - - ## - # @if jp - # @brief - # - # InPortConsumerγƼԤ饹ǤϡͿ줿 - # PropertiesɬפʾƳƼԤ init() - # ϡOutPortProviderľ太ӡ³ˤ줾ƤФ - # ǽ롣äơδؿʣƤФ뤳ȤꤷƵ - # Ҥ٤Ǥ롣 - # - # @param prop - # - # @else - # - # @brief Initializing configuration - # - # This operation would be called to configure in initialization. - # In the concrete class, configuration should be performed - # getting appropriate information from the given Properties data. - # This function might be called right after instantiation and - # connection sequence respectivly. Therefore, this function - # should be implemented assuming multiple call. - # - # @param prop Configuration information - # - # @endif - ## virtual ReturnCode init(coil::Properties& prop) = 0; - def init(self, prop): - pass - - ## virtual ReturnCode setConsumer(InPortConsumer* consumer) = 0; - def setConsumer(self, consumer): - pass - - ## virtual ReturnCode setBuffer(BufferBase* buffer) = 0; - def setBuffer(self, buffer): - pass - - # virtual ReturnCode setListener(ConnectorInfo& info, - # ConnectorListeners* listeners) = 0; - def setListener(self, info, listeners): - pass - - # virtual ReturnCode write(const cdrMemoryStream& data, - # unsigned long sec, - # unsigned long usec) = 0; - def write(self, data, sec, usec): - pass - - ## virtual bool isActive() = 0; - def isActive(self): - pass - - ## virtual ReturnCode activate() = 0; - def activate(self): - pass - - ## virtual ReturnCode deactivate() = 0; - def deactivate(self): - pass - - - - ## - # @if jp - # - # @brief Publisher ˴롣 - # - # Publisher ˴롣 - # Publisher פˤʤä PublisherFactory ƤӽФ롣 - # - # @else - # - # @brief Release the Publisher - # - # Release this Publisher. - # When Publisher becomes unnecessary, this is invoked from - # PublisherFactory. - # - # @endif - # virtual void release(){} - def release(self): - pass + """ + """ + + ## + # @if jp + # @brief 設定初期化 + # + # InPortConsumerの各種設定を行う。実装クラスでは、与えられた + # Propertiesから必要な情報を取得して各種設定を行う。この init() 関 + # 数は、OutPortProvider生成直後および、接続時にそれぞれ呼ばれる可 + # 能性がある。したがって、この関数は複数回呼ばれることを想定して記 + # 述されるべきである。 + # + # @param prop 設定情報 + # + # @else + # + # @brief Initializing configuration + # + # This operation would be called to configure in initialization. + # In the concrete class, configuration should be performed + # getting appropriate information from the given Properties data. + # This function might be called right after instantiation and + # connection sequence respectivly. Therefore, this function + # should be implemented assuming multiple call. + # + # @param prop Configuration information + # + # @endif + # virtual ReturnCode init(coil::Properties& prop) = 0; + def init(self, prop): + pass + + def exit(self): + pass + + # virtual ReturnCode setConsumer(InPortConsumer* consumer) = 0; + def setConsumer(self, consumer): + pass + + # virtual ReturnCode setBuffer(BufferBase* buffer) = 0; + def setBuffer(self, buffer): + pass + + # virtual ReturnCode setListener(ConnectorInfo& info, + # ConnectorListeners* listeners) = 0; + def setListener(self, info, listeners): + pass + + # virtual ReturnCode write(const cdrMemoryStream& data, + # unsigned long sec, + # unsigned long usec) = 0; + def write(self, data, sec, usec): + pass + + # virtual bool isActive() = 0; + def isActive(self): + pass + + # virtual ReturnCode activate() = 0; + def activate(self): + pass + + # virtual ReturnCode deactivate() = 0; + def deactivate(self): + pass + + ## + # @if jp + # + # @brief Publisher を破棄する。 + # + # 当該 Publisher を破棄する。 + # 当該 Publisher が不要になった場合に PublisherFactory から呼び出される。 + # + # @else + # + # @brief Release the Publisher + # + # Release this Publisher. + # When Publisher becomes unnecessary, this is invoked from + # PublisherFactory. + # + # @endif + # virtual void release(){} + + def release(self): + pass publisherfactory = None -class PublisherFactory(OpenRTM_aist.Factory,PublisherBase): - def __init__(self): - OpenRTM_aist.Factory.__init__(self) - pass - - def __del__(self): - pass +class PublisherFactory(OpenRTM_aist.Factory, PublisherBase): + def __init__(self): + OpenRTM_aist.Factory.__init__(self) + pass + def __del__(self): + pass - def instance(): - global publisherfactory + def instance(): + global publisherfactory - if publisherfactory is None: - publisherfactory = PublisherFactory() + if publisherfactory is None: + publisherfactory = PublisherFactory() - return publisherfactory + return publisherfactory - instance = staticmethod(instance) + instance = staticmethod(instance) diff --git a/OpenRTM_aist/PublisherFlush.py b/OpenRTM_aist/PublisherFlush.py index f2ee5d13..1d5b166f 100644 --- a/OpenRTM_aist/PublisherFlush.py +++ b/OpenRTM_aist/PublisherFlush.py @@ -1,5 +1,5 @@ #!/usr/bin/env python -# -*- coding: euc-jp -*- +# -*- coding: utf-8 -*- ## # @file PublisherFlush.py @@ -22,476 +22,477 @@ ## # @if jp # @class PublisherFlush -# @brief PublisherFlush 饹 +# @brief PublisherFlush クラス # -# Flush Publisher 饹 -# Хåե˳ǼƤ̤ǡ롣 -# ǡФԤĥ󥷥塼ޤФ¦Ʊåɤư롣 +# Flush 型 Publisher クラス +# バッファ内に格納されている未送信データを送信する。 +# データ送出を待つコンシューマを、送出する側と同じスレッドで動作させる。 # # @else # @class PublisherFlush # @brief PublisherFlush class # @endif class PublisherFlush(OpenRTM_aist.PublisherBase): - """ - """ - - - - ## - # @if jp - # @brief 󥹥ȥ饯 - # - # 󥹥ȥ饯 - # - # @param self - # @param consumer ǡФԤĥ󥷥塼 - # @param property PublisherζưꤷProperty֥ - # - # @else - # @brief Constructor - # @endif - def __init__(self): - self._rtcout = OpenRTM_aist.Manager.instance().getLogbuf("PublisherFlush") - self._consumer = None - self._active = False - self._profile = None # ConnectorInfo - self._listeners = None # ConnectorListeners - self._retcode = self.PORT_OK - - ## - # @if jp - # @brief ǥȥ饯 - # - # ǥȥ饯 - # Publisher˴ݤˡPublisherFactoryˤƤӽФ롣 - # - # @param self - # - # @else - # @brief Destructor - # @endif - def __del__(self): - # "consumer" should be deleted in the Connector - self._rtcout.RTC_TRACE("~PublisherFlush()") - self._consumer = None - return - - ## - # @if jp - # @brief - # - # Υ饹Υ֥ȤѤΤΩɬδؿƤ - # Фɬפ롣 PublisherFlush ϸǽ - # ᡼ʤ - # - # @param property PublisherζưꤷProperty֥ - # @return ReturnCode PORT_OK ェλ - # INVALID_ARGS Properties ͤޤ - # - # @else - # @brief initialization - # - # This function have to be called before using this class object. - # However, this PublisherFlush class has no parameters to be initialized. - # - # @param property Property objects that includes the control information - # of this Publisher - # @return ReturnCode PORT_OK normal return - # INVALID_ARGS Properties with invalid values. - # @endif - # - # virtual ReturnCode init(coil::Properties& prop); - def init(self, prop): - self._rtcout.RTC_TRACE("init()") - return self.PORT_OK; - - ## - # @if jp - # @brief InPort󥷥塼ޤΥå - # - # δؿǤϡ Publisher ˴Ϣդ륳󥷥塼ޤ򥻥åȤ롣 - # 󥷥塼ޥ֥Ȥ̥ݥ󥿤ξ硢INVALID_ARGS֤롣 - # ʳξϡPORT_OK ֤롣 - # - # @param consumer Consumer ؤΥݥ - # @return ReturnCode PORT_OK ェλ - # INVALID_ARGS ͤޤޤƤ - # - # @else - # @brief Store InPort consumer - # - # This operation sets a consumer that is associated with this - # object. If the consumer object is NULL, INVALID_ARGS will be - # returned. - # - # @param consumer A pointer to a consumer object. - # @return ReturnCode PORT_OK normal return - # INVALID_ARGS given argument has invalid value - # - # PublisherFlush::setConsumer(InPortConsumer* consumer) - def setConsumer(self, consumer): - self._rtcout.RTC_TRACE("setConsumer()") - if not consumer: - return self.INVALID_ARGS - - self._consumer = consumer - - return self.PORT_OK - - ## - # @if jp - # @brief ХåեΥå - # - # PublisherFlushǤϡХåեѤʤᡢʤ - # PORT_OK ֤ - # - # @param buffer CDRХåե - # @return PORT_OK ェλ - # - # @else - # @brief Setting buffer pointer - # - # Since PublisherFlush does not use any buffers, This function - # always returns PORT_OK. - # - # @param buffer CDR buffer - # @return PORT_OK - # - # @endif - # - # PublisherBase::ReturnCode PublisherFlush::setBuffer(CdrBufferBase* buffer) - def setBuffer(self, buffer): - self._rtcout.RTC_TRACE("setBuffer()") - return self.PORT_OK - - ## - # @if jp - # @brief ꥹʤꤹ롣 - # - # Publisher Фƥꥹʥ֥ ConnectorListeners ꤹ롣 - # Ƽꥹʥ֥Ȥޤ ConnectorListeners 򥻥åȤ뤳Ȥǡ - # Хåեɤ߽񤭡ǡˤΥꥹʤ򥳡뤹롣 - # ConnectorListeners ֥ȤνͭϥݡȤޤ RTObject - # Publisher ConnectorListeners Ϻ뤳ȤϤʤ - # ConnectorListeners ̥ݥ󥿤ξ INVALID_ARGS ֤ - # - # @param info ConnectorProfile 벽֥ ConnectorInfo - # @param listeners ꥹʤ¿ݻ ConnectorListeners ֥ - # @return PORT_OK ェλ - # INVALID_ARGS ʰ - # @else - # @brief Set the listener. - # - # This function sets ConnectorListeners listener object to the - # Publisher. By setting ConnectorListeners containing various - # listeners objects, these listeners are called at the time of - # reading and writing of a buffer, and transmission of data - # etc. Since the ownership of the ConnectorListeners object is - # owned by Port or RTObject, the Publisher never deletes the - # ConnectorListeners object. If the given ConnectorListeners' - # pointer is NULL, this function returns INVALID_ARGS. - # - # @param info ConnectorInfo that is localized object of ConnectorProfile - # @param listeners ConnectorListeners that holds various listeners - # @return PORT_OK Normal return - # INVALID_ARGS Invalid arguments - # @endif - # - # virtual ::RTC::DataPortStatus::Enum - # setListener(ConnectorInfo& info, - # RTC::ConnectorListeners* listeners); - def setListener(self, info, listeners): - self._rtcout.RTC_TRACE("setListeners()") - - if not listeners: - self._rtcout.RTC_ERROR("setListeners(listeners == 0): invalid argument") - return self.INVALID_ARGS - - self._profile = info - self._listeners = listeners - - return self.PORT_OK - - ## - # @if jp - # @brief ǡ񤭹 - # - # Publisher ݻ륳󥷥塼ޤФƥǡ񤭹ࡣ - # 塼ޡꥹŬڤꤵƤʤPublisher ֥ - # ȤƤʤ硢δؿƤӽФȥ顼 - # PRECONDITION_NOT_MET ֤졢󥷥塼ޤؤν񤭹 - # ϰڹԤʤ - # - # 󥷥塼ޤؤν񤭹ߤФơ󥷥塼ޤե֡ - # 塼ޤΥ顼󥷥塼ޤؤν񤭹ߤॢȤ - # ˤϤ줾졢顼 SEND_FULL, SEND_ERROR, SEND_TIMEOUT - # ֤롣 - # - # ʳΥ顼ξ硢PORT_ERROR ֤롣 - # - # - # @param data 񤭹ǡ - # @param sec ॢȻ - # @param nsec ॢȻ - # - # @return PORT_OK ェλ - # PRECONDITION_NO_MET consumer, buffer, listenerŬڤ - # ƤʤΥ֥Ȥλ - # ʤ硣 - # SEND_FULL 褬ե - # SEND_TIMEOUT 褬ॢȤ - # CONNECTION_LOST ³Ǥ줿ȤΤ - # - # @else - # @brief Write data - # - # This function writes data into the consumer associated with - # this Publisher. If this function is called without initializing - # correctly such as a consumer, listeners, etc., error code - # PRECONDITION_NOT_MET will be returned and no operation of the - # writing to the consumer etc. will be performed. - # - # When publisher writes data to the buffer, if the consumer - # returns full-status, returns error, is returned with timeout, - # error codes BUFFER_FULL, BUFFER_ERROR and BUFFER_TIMEOUT will - # be returned respectively. - # - # In other cases, PROT_ERROR will be returned. - # - # @param data Data to be wrote to the buffer - # @param sec Timeout time in unit seconds - # @param nsec Timeout time in unit nano-seconds - # @return PORT_OK Normal return - # PRECONDITION_NO_MET Precondition does not met. A consumer, - # a buffer, listenes are not set properly. - # SEND_FULL Data was sent but full-status returned - # SEND_TIMEOUT Data was sent but timeout occurred - # CONNECTION_LOST detected that the connection has been lost - # - # @endif - # - ## PublisherBase::ReturnCode PublisherFlush::write(const cdrMemoryStream& data, - ## unsigned long sec, - ## unsigned long usec) - def write(self, data, sec, usec): - self._rtcout.RTC_PARANOID("write()") - if not self._consumer or not self._listeners: - return self.PRECONDITION_NOT_MET - - if self._retcode == self.CONNECTION_LOST: - self._rtcout.RTC_DEBUG("write(): connection lost.") - return self._retcode - - self.onSend(data) - - self._retcode = self._consumer.put(data) - - if self._retcode == self.PORT_OK: - self.onReceived(data) - return self._retcode - elif self._retcode == self.PORT_ERROR: - self.onReceiverError(data) - return self._retcode - elif self._retcode == self.SEND_FULL: - self.onReceiverFull(data) - return self._retcode - elif self._retcode == self.SEND_TIMEOUT: - self.onReceiverTimeout(data) - return self._retcode - elif self._retcode == self.CONNECTION_LOST: - self.onReceiverTimeout(data) - return self._retcode - elif self._retcode == self.UNKNOWN_ERROR: - self.onReceiverError(data) - return self._retcode - else: - self.onReceiverError(data) - return self._retcode - - - - - ## - # @if jp - # - # @brief ƥֲǧ - # - # Publisher ϥǡݡȤƱ activate/deactivate 롣 - # activate() / deactivate() ؿˤäơƥ־֤󥢥ƥ - # ־֤ڤؤ롣δؿˤꡢߥƥ־֤󥢥 - # ƥ־֤ǧ뤳ȤǤ롣 - # - # @return ֳǧ(ƥ־:true󥢥ƥ־:false) - # - # @else - # - # @brief If publisher is active state - # - # A Publisher can be activated/deactivated synchronized with the - # data port. The active state and the non-active state are made - # transition by the "activate()" and the "deactivate()" functions - # respectively. This function confirms if the publisher is in - # active state. - # - # @return Result of state confirmation - # (Active state:true, Inactive state:false) - # - # @endif - # - ## bool PublisherFlush::isActive() - def isActive(self): - return self._active - - - ## - # @if jp - # @brief ƥֲ - # - # Publisher 򥢥ƥֲ롣δؿƤӽФȤˤꡢ - # Publisherġǡ륹åɤư򳫻Ϥ롣 - # ԤƤʤʤɤˤꡢʤ硢顼 - # PRECONDITION_NOT_MET ֤ - # - # @return PORT_OK ェλ - # PRECONDITION_NOT_MET ʤ - # - # @else - # @brief activation - # - # This function activates the publisher. By calling this - # function, this publisher starts the thread that pushes data to - # InPort. If precondition such as initialization process and so - # on is not met, the error code PRECONDITION_NOT_MET is returned. - # - # @return PORT_OK normal return - # PRECONDITION_NOT_MET precondition is not met - # - # @endif - # - ## PublisherBase::ReturnCode PublisherFlush::activate() - def activate(self): - if self._active: - return self.PRECONDITION_NOT_MET - - self._active = True - - return self.PORT_OK - - ## - # @if jp - # @brief 󥢥ƥֲ - # - # Publisher 󥢥ƥֲ롣δؿƤӽФȤˤꡢ - # Publisherġǡ륹åɤưߤ롣 - # ԤƤʤʤɤˤꡢʤ硢顼 - # PRECONDITION_NOT_MET ֤ - # - # @return PORT_OK ェλ - # PRECONDITION_NOT_MET ʤ - # - # @else - # @brief deactivation - # - # This function deactivates the publisher. By calling this - # function, this publisher stops the thread that pushes data to - # InPort. If precondition such as initialization process and so - # on is not met, the error code PRECONDITION_NOT_MET is returned. - # - # @return PORT_OK normal return - # PRECONDITION_NOT_MET precondition is not met - # - # @endif - # - ## PublisherBase::ReturnCode PublisherFlush::deactivate() - def deactivate(self): - if not self._active: - return self.PRECONDITION_NOT_MET - - self._active = False - - return self.PORT_OK - - ## - # @if jp - # @brief ON_SENDΥꥹʤΤ롣 - # @param data cdrMemoryStream - # @else - # @brief Notify an ON_SEND event to listners - # @param data cdrMemoryStream - # @endif - # - # inline void onSend(const cdrMemoryStream& data) - def onSend(self, data): - if self._listeners is not None and self._profile is not None: - self._listeners.connectorData_[OpenRTM_aist.ConnectorDataListenerType.ON_SEND].notify(self._profile, data) - return - - ## - # @if jp - # @brief ON_RECEIVEDΥꥹʤΤ롣 - # @param data cdrMemoryStream - # @else - # @brief Notify an ON_RECEIVED event to listeners - # @param data cdrMemoryStream - # @endif - # - # inline void onReceived(const cdrMemoryStream& data) - def onReceived(self, data): - if self._listeners is not None and self._profile is not None: - self._listeners.connectorData_[OpenRTM_aist.ConnectorDataListenerType.ON_RECEIVED].notify(self._profile, data) - return - - ## - # @if jp - # @brief ON_RECEIVER_FULLΥꥹʤΤ롣 - # @param data cdrMemoryStream - # @else - # @brief Notify an ON_RECEIVER_FULL event to listeners - # @param data cdrMemoryStream - # @endif - # - # inline void onReceiverFull(const cdrMemoryStream& data) - def onReceiverFull(self, data): - if self._listeners is not None and self._profile is not None: - self._listeners.connectorData_[OpenRTM_aist.ConnectorDataListenerType.ON_RECEIVER_FULL].notify(self._profile, data) - return - - ## - # @if jp - # @brief ON_RECEIVER_TIMEOUTΥꥹʤΤ롣 - # @param data cdrMemoryStream - # @else - # @brief Notify an ON_RECEIVER_TIMEOUT event to listeners - # @param data cdrMemoryStream - # @endif - # - # inline void onReceiverTimeout(const cdrMemoryStream& data) - def onReceiverTimeout(self, data): - if self._listeners is not None and self._profile is not None: - self._listeners.connectorData_[OpenRTM_aist.ConnectorDataListenerType.ON_RECEIVER_TIMEOUT].notify(self._profile, data) - return - - ## - # @if jp - # @brief ON_RECEIVER_ERRORΥꥹʤΤ롣 - # @param data cdrMemoryStream - # @else - # @brief Notify an ON_RECEIVER_ERROR event to listeners - # @param data cdrMemoryStream - # @endif - # - # inline void onReceiverError(const cdrMemoryStream& data) - def onReceiverError(self, data): - if self._listeners is not None and self._profile is not None: - self._listeners.connectorData_[OpenRTM_aist.ConnectorDataListenerType.ON_RECEIVER_ERROR].notify(self._profile, data) - return - + """ + """ + + ## + # @if jp + # @brief コンストラクタ + # + # コンストラクタ + # + # @param self + # @param consumer データ送出を待つコンシューマ + # @param property 本Publisherの駆動制御情報を設定したPropertyオブジェクト + # + # @else + # @brief Constructor + # @endif + def __init__(self): + self._rtcout = OpenRTM_aist.Manager.instance().getLogbuf("PublisherFlush") + self._consumer = None + self._active = False + self._profile = None # ConnectorInfo + self._listeners = None # ConnectorListeners + self._retcode = self.PORT_OK + + ## + # @if jp + # @brief デストラクタ + # + # デストラクタ + # 当該Publisherを破棄する際に、PublisherFactoryにより呼び出される。 + # + # @param self + # + # @else + # @brief Destructor + # @endif + def __del__(self): + # "consumer" should be deleted in the Connector + self._rtcout.RTC_TRACE("~PublisherFlush()") + self._consumer = None + return + + ## + # @if jp + # @brief 初期化 + # + # このクラスのオブジェクトを使用するのに先立ち、必ずこの関数を呼び + # 出す必要がある。ただし、この PublisherFlush は現状で初期化するパ + # ラメータを持たない。 + # + # @param property 本Publisherの駆動制御情報を設定したPropertyオブジェクト + # @return ReturnCode PORT_OK 正常終了 + # INVALID_ARGS Properties が不正な値を含む + # + # @else + # @brief initialization + # + # This function have to be called before using this class object. + # However, this PublisherFlush class has no parameters to be initialized. + # + # @param property Property objects that includes the control information + # of this Publisher + # @return ReturnCode PORT_OK normal return + # INVALID_ARGS Properties with invalid values. + # @endif + # + # virtual ReturnCode init(coil::Properties& prop); + def init(self, prop): + self._rtcout.RTC_TRACE("init()") + return self.PORT_OK + + ## + # @if jp + # @brief InPortコンシューマのセット + # + # この関数では、この Publisher に関連付けられるコンシューマをセットする。 + # コンシューマオブジェクトがヌルポインタの場合、INVALID_ARGSが返される。 + # それ以外の場合は、PORT_OK が返される。 + # + # @param consumer Consumer へのポインタ + # @return ReturnCode PORT_OK 正常終了 + # INVALID_ARGS 引数に不正な値が含まれている + # + # @else + # @brief Store InPort consumer + # + # This operation sets a consumer that is associated with this + # object. If the consumer object is NULL, INVALID_ARGS will be + # returned. + # + # @param consumer A pointer to a consumer object. + # @return ReturnCode PORT_OK normal return + # INVALID_ARGS given argument has invalid value + # + # PublisherFlush::setConsumer(InPortConsumer* consumer) + def setConsumer(self, consumer): + self._rtcout.RTC_TRACE("setConsumer()") + if not consumer: + return self.INVALID_ARGS + + self._consumer = consumer + + return self.PORT_OK + + ## + # @if jp + # @brief バッファのセット + # + # PublisherFlushでは、バッファを使用しないため、いかなる場合も + # PORT_OK を返す。 + # + # @param buffer CDRバッファ + # @return PORT_OK 正常終了 + # + # @else + # @brief Setting buffer pointer + # + # Since PublisherFlush does not use any buffers, This function + # always returns PORT_OK. + # + # @param buffer CDR buffer + # @return PORT_OK + # + # @endif + # + # PublisherBase::ReturnCode PublisherFlush::setBuffer(CdrBufferBase* + # buffer) + def setBuffer(self, buffer): + self._rtcout.RTC_TRACE("setBuffer()") + return self.PORT_OK + + ## + # @if jp + # @brief リスナを設定する。 + # + # Publisher に対してリスナオブジェクト ConnectorListeners を設定する。 + # 各種リスナオブジェクトを含む ConnectorListeners をセットすることで、 + # バッファの読み書き、データの送信時等にこれらのリスナをコールする。 + # ConnectorListeners オブジェクトの所有権はポートまたは RTObject が持ち + # Publisher 削除時に ConnectorListeners は削除されることはない。 + # ConnectorListeners がヌルポインタの場合 INVALID_ARGS を返す。 + # + # @param info ConnectorProfile をローカル化したオブジェクト ConnectorInfo + # @param listeners リスナを多数保持する ConnectorListeners オブジェクト + # @return PORT_OK 正常終了 + # INVALID_ARGS 不正な引数 + # @else + # @brief Set the listener. + # + # This function sets ConnectorListeners listener object to the + # Publisher. By setting ConnectorListeners containing various + # listeners objects, these listeners are called at the time of + # reading and writing of a buffer, and transmission of data + # etc. Since the ownership of the ConnectorListeners object is + # owned by Port or RTObject, the Publisher never deletes the + # ConnectorListeners object. If the given ConnectorListeners' + # pointer is NULL, this function returns INVALID_ARGS. + # + # @param info ConnectorInfo that is localized object of ConnectorProfile + # @param listeners ConnectorListeners that holds various listeners + # @return PORT_OK Normal return + # INVALID_ARGS Invalid arguments + # @endif + # + # virtual ::RTC::DataPortStatus::Enum + # setListener(ConnectorInfo& info, + # RTC::ConnectorListeners* listeners); + def setListener(self, info, listeners): + self._rtcout.RTC_TRACE("setListeners()") + + if not listeners: + self._rtcout.RTC_ERROR( + "setListeners(listeners == 0): invalid argument") + return self.INVALID_ARGS + + self._profile = info + self._listeners = listeners + + return self.PORT_OK + + ## + # @if jp + # @brief データを書き込む + # + # Publisher が保持するコンシューマに対してデータを書き込む。コン + # シューマ、リスナ等が適切に設定されていない等、Publisher オブジェ + # クトが正しく初期化されていない場合、この関数を呼び出すとエラーコー + # ド PRECONDITION_NOT_MET が返され、コンシューマへの書き込み等の操 + # 作は一切行われない。 + # + # コンシューマへの書き込みに対して、コンシューマがフル状態、コン + # シューマのエラー、コンシューマへの書き込みがタイムアウトした場合 + # にはそれぞれ、エラーコード SEND_FULL, SEND_ERROR, SEND_TIMEOUT + # が返される。 + # + # これら以外のエラーの場合、PORT_ERROR が返される。 + # + # + # @param data 書き込むデータ + # @param sec タイムアウト時間 + # @param nsec タイムアウト時間 + # + # @return PORT_OK 正常終了 + # PRECONDITION_NO_MET consumer, buffer, listener等が適切に設定 + # されていない等、このオブジェクトの事前条件 + # を満たさない場合。 + # SEND_FULL 送信先がフル状態 + # SEND_TIMEOUT 送信先がタイムアウトした + # CONNECTION_LOST 接続が切断されたことを検知した。 + # + # @else + # @brief Write data + # + # This function writes data into the consumer associated with + # this Publisher. If this function is called without initializing + # correctly such as a consumer, listeners, etc., error code + # PRECONDITION_NOT_MET will be returned and no operation of the + # writing to the consumer etc. will be performed. + # + # When publisher writes data to the buffer, if the consumer + # returns full-status, returns error, is returned with timeout, + # error codes BUFFER_FULL, BUFFER_ERROR and BUFFER_TIMEOUT will + # be returned respectively. + # + # In other cases, PROT_ERROR will be returned. + # + # @param data Data to be wrote to the buffer + # @param sec Timeout time in unit seconds + # @param nsec Timeout time in unit nano-seconds + # @return PORT_OK Normal return + # PRECONDITION_NO_MET Precondition does not met. A consumer, + # a buffer, listenes are not set properly. + # SEND_FULL Data was sent but full-status returned + # SEND_TIMEOUT Data was sent but timeout occurred + # CONNECTION_LOST detected that the connection has been lost + # + # @endif + # + # PublisherBase::ReturnCode PublisherFlush::write(const cdrMemoryStream& data, + # unsigned long sec, + # unsigned long usec) + def write(self, data, sec, usec): + self._rtcout.RTC_PARANOID("write()") + if not self._consumer or not self._listeners: + return self.PRECONDITION_NOT_MET + + if self._retcode == self.CONNECTION_LOST: + self._rtcout.RTC_DEBUG("write(): connection lost.") + return self._retcode + + data = self.onSend(data) + + self._retcode = self._consumer.put(data) + + if self._retcode == self.PORT_OK: + data = self.onReceived(data) + return self._retcode + elif self._retcode == self.PORT_ERROR: + data = self.onReceiverError(data) + return self._retcode + elif self._retcode == self.SEND_FULL: + data = self.onReceiverFull(data) + return self._retcode + elif self._retcode == self.SEND_TIMEOUT: + data = self.onReceiverTimeout(data) + return self._retcode + elif self._retcode == self.CONNECTION_LOST: + data = self.onReceiverTimeout(data) + return self._retcode + elif self._retcode == self.UNKNOWN_ERROR: + data = self.onReceiverError(data) + return self._retcode + else: + data = self.onReceiverError(data) + return self._retcode + + ## + # @if jp + # + # @brief アクティブ化確認 + # + # Publisher はデータポートと同期して activate/deactivate される。 + # activate() / deactivate() 関数によって、アクティブ状態と非アクティ + # ブ状態が切り替わる。この関数により、現在アクティブ状態か、非アク + # ティブ状態かを確認することができる。 + # + # @return 状態確認結果(アクティブ状態:true、非アクティブ状態:false) + # + # @else + # + # @brief If publisher is active state + # + # A Publisher can be activated/deactivated synchronized with the + # data port. The active state and the non-active state are made + # transition by the "activate()" and the "deactivate()" functions + # respectively. This function confirms if the publisher is in + # active state. + # + # @return Result of state confirmation + # (Active state:true, Inactive state:false) + # + # @endif + # + # bool PublisherFlush::isActive() + + def isActive(self): + return self._active + + ## + # @if jp + # @brief アクティブ化する + # + # Publisher をアクティブ化する。この関数を呼び出すことにより、 + # Publisherが持つ、データを送信するスレッドが動作を開始する。初期 + # 化が行われていないなどにより、事前条件を満たさない場合、エラーコー + # ド PRECONDITION_NOT_MET を返す。 + # + # @return PORT_OK 正常終了 + # PRECONDITION_NOT_MET 事前条件を満たさない + # + # @else + # @brief activation + # + # This function activates the publisher. By calling this + # function, this publisher starts the thread that pushes data to + # InPort. If precondition such as initialization process and so + # on is not met, the error code PRECONDITION_NOT_MET is returned. + # + # @return PORT_OK normal return + # PRECONDITION_NOT_MET precondition is not met + # + # @endif + # + # PublisherBase::ReturnCode PublisherFlush::activate() + + def activate(self): + if self._active: + return self.PRECONDITION_NOT_MET + + self._active = True + + return self.PORT_OK + + ## + # @if jp + # @brief 非アクティブ化する + # + # Publisher を非アクティブ化する。この関数を呼び出すことにより、 + # Publisherが持つ、データを送信するスレッドが動作を停止する。初期 + # 化が行われていないなどにより、事前条件を満たさない場合、エラーコー + # ド PRECONDITION_NOT_MET を返す。 + # + # @return PORT_OK 正常終了 + # PRECONDITION_NOT_MET 事前条件を満たさない + # + # @else + # @brief deactivation + # + # This function deactivates the publisher. By calling this + # function, this publisher stops the thread that pushes data to + # InPort. If precondition such as initialization process and so + # on is not met, the error code PRECONDITION_NOT_MET is returned. + # + # @return PORT_OK normal return + # PRECONDITION_NOT_MET precondition is not met + # + # @endif + # + # PublisherBase::ReturnCode PublisherFlush::deactivate() + def deactivate(self): + if not self._active: + return self.PRECONDITION_NOT_MET + + self._active = False + + return self.PORT_OK + + ## + # @if jp + # @brief ON_SENDのリスナへ通知する。 + # @param data cdrMemoryStream + # @else + # @brief Notify an ON_SEND event to listners + # @param data cdrMemoryStream + # @endif + # + # inline void onSend(const cdrMemoryStream& data) + def onSend(self, data): + if self._listeners is not None and self._profile is not None: + _, data = self._listeners.notifyData( + OpenRTM_aist.ConnectorDataListenerType.ON_SEND, self._profile, data) + return data + + ## + # @if jp + # @brief ON_RECEIVEDのリスナへ通知する。 + # @param data cdrMemoryStream + # @else + # @brief Notify an ON_RECEIVED event to listeners + # @param data cdrMemoryStream + # @endif + # + # inline void onReceived(const cdrMemoryStream& data) + def onReceived(self, data): + if self._listeners is not None and self._profile is not None: + _, data = self._listeners.notifyData( + OpenRTM_aist.ConnectorDataListenerType.ON_RECEIVED, self._profile, data) + return data + + ## + # @if jp + # @brief ON_RECEIVER_FULLのリスナへ通知する。 + # @param data cdrMemoryStream + # @else + # @brief Notify an ON_RECEIVER_FULL event to listeners + # @param data cdrMemoryStream + # @endif + # + # inline void onReceiverFull(const cdrMemoryStream& data) + def onReceiverFull(self, data): + if self._listeners is not None and self._profile is not None: + _, data = self._listeners.notifyData( + OpenRTM_aist.ConnectorDataListenerType.ON_RECEIVER_FULL, self._profile, data) + return data + + ## + # @if jp + # @brief ON_RECEIVER_TIMEOUTのリスナへ通知する。 + # @param data cdrMemoryStream + # @else + # @brief Notify an ON_RECEIVER_TIMEOUT event to listeners + # @param data cdrMemoryStream + # @endif + # + # inline void onReceiverTimeout(const cdrMemoryStream& data) + def onReceiverTimeout(self, data): + if self._listeners is not None and self._profile is not None: + _, data = self._listeners.notifyData( + OpenRTM_aist.ConnectorDataListenerType.ON_RECEIVER_TIMEOUT, self._profile, data) + return data + + ## + # @if jp + # @brief ON_RECEIVER_ERRORのリスナへ通知する。 + # @param data cdrMemoryStream + # @else + # @brief Notify an ON_RECEIVER_ERROR event to listeners + # @param data cdrMemoryStream + # @endif + # + # inline void onReceiverError(const cdrMemoryStream& data) + def onReceiverError(self, data): + if self._listeners is not None and self._profile is not None: + _, data = self._listeners.notifyData( + OpenRTM_aist.ConnectorDataListenerType.ON_RECEIVER_ERROR, self._profile, data) + return data + def PublisherFlushInit(): - OpenRTM_aist.PublisherFactory.instance().addFactory("flush", - OpenRTM_aist.PublisherFlush, - OpenRTM_aist.Delete) - OpenRTM_aist.PublisherFactory.instance().addFactory("block", - OpenRTM_aist.PublisherFlush, - OpenRTM_aist.Delete) + OpenRTM_aist.PublisherFactory.instance().addFactory("flush", + OpenRTM_aist.PublisherFlush) + OpenRTM_aist.PublisherFactory.instance().addFactory("block", + OpenRTM_aist.PublisherFlush) diff --git a/OpenRTM_aist/PublisherNew.py b/OpenRTM_aist/PublisherNew.py index 06825a89..41274659 100644 --- a/OpenRTM_aist/PublisherNew.py +++ b/OpenRTM_aist/PublisherNew.py @@ -1,5 +1,5 @@ #!/usr/bin/env python -# -*- coding: euc-jp -*- +# -*- coding: utf-8 -*- ## # @file PublisherNew.py @@ -14,7 +14,7 @@ # National Institute of # Advanced Industrial Science and Technology (AIST), Japan # All rights reserved. - + import threading import OpenRTM_aist @@ -23,13 +23,13 @@ ## # @if jp # @class PublisherNew -# @brief PublisherNew 饹 +# @brief PublisherNew クラス # -# Хåե˿ǡǼ줿ߥ󥰤ǡοǡ롣 -# ǡХߥ󥰤Ԥĥ󥷥塼ޤФ¦Ȥϰۤʤ륹åɤ -# ư˻ѡ -# PublisherζưϡǡФΥߥ󥰤ˤʤޤǥ֥å졢 -# Хߥ󥰤Τȡ¨¤˥󥷥塼ޤнƤӽФ +# バッファ内に新規データが格納されたタイミングで、その新規データを送信する。 +# データ送出タイミングを待つコンシューマを、送出する側とは異なるスレッドで +# 動作させる場合に使用。 +# Publisherの駆動は、データ送出のタイミングになるまでブロックされ、 +# 送出タイミングの通知を受けると、即座にコンシューマの送出処理を呼び出す。 # # @else # @class PublisherNew @@ -44,1017 +44,1053 @@ # # @endif class PublisherNew(OpenRTM_aist.PublisherBase): - """ - """ - - # Policy - PUBLISHER_POLICY_ALL = 0 - PUBLISHER_POLICY_FIFO = 1 - PUBLISHER_POLICY_SKIP = 2 - PUBLISHER_POLICY_NEW = 3 - - ## - # @if jp - # @brief 󥹥ȥ饯 - # - # 󥹥ȥ饯 - # Publisher ѿåɤ롣 - # - # @param self - # @param consumer ǡФԤĥ󥷥塼 - # @param property PublisherζưꤷProperty֥ - # (PublisherǤ̤) - # @else - # @brief Constructor - # @endif - def __init__(self): - self._rtcout = OpenRTM_aist.Manager.instance().getLogbuf("PublisherNew") - self._consumer = None - self._buffer = None - self._task = None - self._retcode = self.PORT_OK - self._retmutex = threading.RLock() - self._pushPolicy = self.PUBLISHER_POLICY_NEW - self._skipn = 0 - self._active = False - self._leftskip = 0 - self._profile = None - self._listeners = None - - ## - # @if jp - # @brief ǥȥ饯 - # - # ǥȥ饯 - # - # @param self - # - # @else - # @brief Destructor - # - # @endif - def __del__(self): - self._rtcout.RTC_TRACE("~PublisherNew()") - if self._task: - self._task.resume() - self._task.finalize() - - OpenRTM_aist.PeriodicTaskFactory.instance().deleteObject(self._task) - #del self._task - self._rtcout.RTC_PARANOID("task deleted.") - - # "consumer" should be deleted in the Connector - self._consumer = 0 - # "buffer" should be deleted in the Connector - self._buffer = 0 - return - - ## - # @if jp - # @brief PushPolicy - # @else - # @brief Setting PushPolicy - # @endif - # - #void PublisherNew::setPushPolicy(const coil::Properties& prop) - def setPushPolicy(self, prop): - push_policy = prop.getProperty("publisher.push_policy","new") - self._rtcout.RTC_DEBUG("push_policy: %s", push_policy) - - push_policy = OpenRTM_aist.normalize([push_policy]) - - if push_policy == "all": - self._pushPolicy = self.PUBLISHER_POLICY_ALL - - elif push_policy == "fifo": - self._pushPolicy = self.PUBLISHER_POLICY_FIFO - - elif push_policy == "skip": - self._pushPolicy = self.PUBLISHER_POLICY_SKIP - - elif push_policy == "new": - self._pushPolicy = self.PUBLISHER_POLICY_NEW - - else: - self._rtcout.RTC_ERROR("invalid push_policy value: %s", push_policy) - self._pushPolicy = self.PUBLISHER_POLICY_NEW - - skip_count = prop.getProperty("publisher.skip_count","0") - self._rtcout.RTC_DEBUG("skip_count: %s", skip_count) - - skipn = [self._skipn] - ret = OpenRTM_aist.stringTo(skipn, skip_count) - if ret: - self._skipn = skipn[0] - else: - self._rtcout.RTC_ERROR("invalid skip_count value: %s", skip_count) - self._skipn = 0 - - if self._skipn < 0: - self._rtcout.RTC_ERROR("invalid skip_count value: %d", self._skipn) - self._skipn = 0 - - return - - ## - # @if jp - # @brief Task - # @else - # @brief Setting Task - # @endif - # - #bool PublisherNew::createTask(const coil::Properties& prop) - def createTask(self, prop): - factory = OpenRTM_aist.PeriodicTaskFactory.instance() - - th = factory.getIdentifiers() - self._rtcout.RTC_DEBUG("available task types: %s", OpenRTM_aist.flatten(th)) - - self._task = factory.createObject(prop.getProperty("thread_type", "default")) - - if not self._task: - self._rtcout.RTC_ERROR("Task creation failed: %s", - prop.getProperty("thread_type", "default")) - return self.INVALID_ARGS - - self._rtcout.RTC_PARANOID("Task creation succeeded.") - - mprop = prop.getNode("measurement") - - # setting task function - self._task.setTask(self.svc) - self._task.setPeriod(0.0) - self._task.executionMeasure(OpenRTM_aist.toBool(mprop.getProperty("exec_time"), - "enable", "disable", True)) - ecount = [0] - if OpenRTM_aist.stringTo(ecount, mprop.getProperty("exec_count")): - self._task.executionMeasureCount(ecount[0]) - - self._task.periodicMeasure(OpenRTM_aist.toBool(mprop.getProperty("period_time"), - "enable", "disable", True)) - pcount = [0] - if OpenRTM_aist.stringTo(pcount, mprop.getProperty("period_count")): - self._task.periodicMeasureCount(pcount[0]) - - self._task.suspend() - self._task.activate() - self._task.suspend() - - return self.PORT_OK - - ## - # @if jp - # @brief - # - # Υ饹Υ֥ȤѤΤΩɬδؿƤ - # Фɬפ롣ˤϡΥ֥ȤγƼޤ - # Properties Ϳ롣ǡץå夹ݤΥݥꥷȤ - # publisher.push_policy 򥭡Ȥͤˡall, fifo, skip, new - # 줫Ϳ뤳ȤǤ롣 - # - # ʲΥץͿ뤳ȤǤ롣 - # - # - thread_type: åɤΥ (ʸ󡢥ǥե: default) - # - publisher.push_policy: Pushݥꥷ (all, fifo, skip, new) - # - publisher.skip_count: 嵭ݥꥷ skip ΤȤΥå׿ - # - measurement.exec_time: ¹Իַ¬ (enable/disable) - # - measurement.exec_count: ؿ¹Իַ¬ (, ) - # - measurement.period_time: ַ¬ (enable/disable) - # - measurement.period_count: ַ¬ (, ) - # - # @param property PublisherζưꤷProperty֥ - # @return ReturnCode PORT_OK ェλ - # INVALID_ARGS Properties ͤޤ - # - # @else - # @brief Initialization - # - # This function have to be called before using this class object. - # Properties object that includes certain configuration - # information should be given as an argument. all, fifo, skip, - # new can be given as a data push policy in a value of the key - # "publisher.push_policy." - # - # The following options are available. - # - # - thread_type: Thread type (string, default: default) - # - publisher.push_policy: Push policy (all, fifo, skip, new) - # - publisher.skip_count: The number of skip count in the "skip" policy - # - measurement.exec_time: Task execution time measurement (enable/disable) - # - measurement.exec_count: Task execution time measurement count - # (numerical, number of times) - # - measurement.period_time: Task period time measurement (enable/disable) - # - measurement.period_count: Task period time measurement count - # (number, count) - # - # @param property Property objects that includes the control information - # of this Publisher - # @return ReturnCode PORT_OK normal return - # INVALID_ARGS Properties with invalid values. - # @endif - # - # PublisherBase::ReturnCode PublisherNew::init(coil::Properties& prop) - def init(self, prop): - self._rtcout.RTC_TRACE("init()") - self.setPushPolicy(prop) - return self.createTask(prop) - - ## - # @if jp - # @brief InPort󥷥塼ޤΥå - # - # δؿǤϡ Publisher ˴Ϣդ륳󥷥塼ޤ򥻥åȤ롣 - # 󥷥塼ޥ֥Ȥ̥ݥ󥿤ξ硢INVALID_ARGS֤롣 - # ʳξϡPORT_OK ֤롣 - # - # @param consumer Consumer ؤΥݥ - # @return ReturnCode PORT_OK ェλ - # INVALID_ARGS ͤޤޤƤ - # - # @else - # @brief Store InPort consumer - # - # This operation sets a consumer that is associated with this - # object. If the consumer object is NULL, INVALID_ARGS will be - # returned. - # - # @param consumer A pointer to a consumer object. - # @return ReturnCode PORT_OK normal return - # INVALID_ARGS given argument has invalid value - # - # @endif - # - # PublisherBase::ReturnCode PublisherNew::setConsumer(InPortConsumer* consumer) - def setConsumer(self, consumer): - self._rtcout.RTC_TRACE("setConsumer()") - - if not consumer: - self._rtcout.RTC_ERROR("setConsumer(consumer = 0): invalid argument.") - return self.INVALID_ARGS - - self._consumer = consumer - return self.PORT_OK - - ## - # @if jp - # @brief ХåեΥå - # - # δؿǤϡ Publisher ˴ϢդХåե򥻥åȤ롣 - # Хåե֥Ȥ̥ݥ󥿤ξ硢INVALID_ARGS֤롣 - # ʳξϡPORT_OK ֤롣 - # - # @param buffer CDR buffer ؤΥݥ - # @return ReturnCode PORT_OK ェλ - # INVALID_ARGS ͤޤޤƤ - # - # @else - # @brief Setting buffer pointer - # - # This operation sets a buffer that is associated with this - # object. If the buffer object is NULL, INVALID_ARGS will be - # returned. - # - # @param buffer A pointer to a CDR buffer object. - # @return ReturnCode PORT_OK normal return - # INVALID_ARGS given argument has invalid value - # - # @endif - # - # PublisherBase::ReturnCode PublisherNew::setBuffer(CdrBufferBase* buffer) - def setBuffer(self, buffer): - self._rtcout.RTC_TRACE("setBuffer()") - - if not buffer: - self._rtcout.RTC_ERROR("setBuffer(buffer == 0): invalid argument") - return self.INVALID_ARGS - - self._buffer = buffer - return self.PORT_OK - - ## - # @if jp - # @brief ꥹʤꤹ롣 - # - # Publisher Фƥꥹʥ֥ ConnectorListeners ꤹ롣 - # Ƽꥹʥ֥Ȥޤ ConnectorListeners 򥻥åȤ뤳Ȥǡ - # Хåեɤ߽񤭡ǡˤΥꥹʤ򥳡뤹롣 - # ConnectorListeners ֥ȤνͭϥݡȤޤ RTObject - # Publisher ConnectorListeners Ϻ뤳ȤϤʤ - # ConnectorListeners ̥ݥ󥿤ξ INVALID_ARGS ֤ - # - # @param info ConnectorProfile 벽֥ ConnectorInfo - # @param listeners ꥹʤ¿ݻ ConnectorListeners ֥ - # @return PORT_OK ェλ - # INVALID_ARGS ʰ - # @else - # @brief Set the listener. - # - # This function sets ConnectorListeners listener object to the - # Publisher. By setting ConnectorListeners containing various - # listeners objects, these listeners are called at the time of - # reading and writing of a buffer, and transmission of data - # etc. Since the ownership of the ConnectorListeners object is - # owned by Port or RTObject, the Publisher never deletes the - # ConnectorListeners object. If the given ConnectorListeners' - # pointer is NULL, this function returns INVALID_ARGS. - # - # @param info ConnectorInfo that is localized object of ConnectorProfile - # @param listeners ConnectorListeners that holds various listeners - # @return PORT_OK Normal return - # INVALID_ARGS Invalid arguments - # @endif - # - # virtual ReturnCode setListener(ConnectorInfo& info, - # ConnectorListeners* listeners); - def setListener(self, info, listeners): - self._rtcout.RTC_TRACE("setListener()") - - if not listeners: - self._rtcout.RTC_ERROR("setListeners(listeners == 0): invalid argument") - return self.INVALID_ARGS - - self._profile = info - self._listeners = listeners - - return self.PORT_OK - - ## - # @if jp - # @brief ǡ񤭹 - # - # Publisher ݻХåեФƥǡ񤭹ࡣ󥷥塼 - # ޡХåեꥹŬڤꤵƤʤPublisher - # ȤƤʤ硢δؿƤӽФȥ顼 - # PRECONDITION_NOT_MET ֤졢Хåեؤν񤭹 - # ϰڹԤʤ - # - # Хåեؤν񤭹ߤȡInPortؤΥǡƱŪ˹Ԥ - # 뤿ᡢδؿϡInPortؤΥǡη̤򼨤 - # CONNECTION_LOST, BUFFER_FULL ʤɤΥ꥿󥳡ɤ֤Ȥ - # 롣ξ硢ǡΥХåեؤν񤭹ߤϹԤʤ - # - # Хåեؤν񤭹ߤФơХåեե֡ХåեΥ - # 顼Хåեؤν񤭹ߤॢȤ硢Хåեλ - # 郎ʤˤϤ줾졢顼 BUFFER_FULL, - # BUFFER_ERROR, BUFFER_TIMEOUT, PRECONDITION_NOT_MET ֤롣 - # - # ʳΥ顼ξ硢PORT_ERROR ֤롣 - # - # - # @param data 񤭹ǡ - # @param sec ॢȻ - # @param nsec ॢȻ - # - # @return PORT_OK ェλ - # PRECONDITION_NO_MET consumer, buffer, listenerŬڤ - # ƤʤΥ֥Ȥλ - # ʤ硣 - # CONNECTION_LOST ³Ǥ줿ȤΤ - # BUFFER_FULL Хåեե֤Ǥ롣 - # BUFFER_ERROR Хåե˲餫Υ顼硣 - # NOT_SUPPORTED ݡȤʤԤ줿 - # TIMEOUT ॢȤ - # - # @else - # @brief Write data - # - # This function writes data into the buffer associated with this - # Publisher. If a Publisher object calls this function, without - # initializing correctly such as a consumer, a buffer, listeners, - # etc., error code PRECONDITION_NOT_MET will be returned and no - # operation of the writing to a buffer etc. will be performed. - # - # Since writing into the buffer and sending data to InPort are - # performed asynchronously, occasionally this function returns - # return-codes such as CONNECTION_LOST and BUFFER_FULL that - # indicate the result of sending data to InPort. In this case, - # writing data into buffer will not be performed. - # - # When publisher writes data to the buffer, if the buffer is - # filled, returns error, is returned with timeout and returns - # precondition error, error codes BUFFER_FULL, BUFFER_ERROR, - # BUFFER_TIMEOUT and PRECONDITION_NOT_MET will be returned - # respectively. - # - # In other cases, PROT_ERROR will be returned. - # - # @param data Data to be wrote to the buffer - # @param sec Timeout time in unit seconds - # @param nsec Timeout time in unit nano-seconds - # @return PORT_OK Normal return - # PRECONDITION_NO_MET Precondition does not met. A consumer, - # a buffer, listenes are not set properly. - # CONNECTION_LOST detected that the connection has been lost - # BUFFER_FULL The buffer is full status. - # BUFFER_ERROR Some kind of error occurred in the buffer. - # NOT_SUPPORTED Some kind of operation that is not supported - # has been performed. - # TIMEOUT Timeout occurred when writing to the buffer. - # - # @endif - # - # PublisherBase::ReturnCode PublisherNew::write(const cdrMemoryStream& data, - # unsigned long sec, - # unsigned long usec) - def write(self, data, sec, usec): - self._rtcout.RTC_PARANOID("write()") - - if not self._consumer or not self._buffer or not self._listeners: - return self.PRECONDITION_NOT_MET - - if self._retcode == self.CONNECTION_LOST: - self._rtcout.RTC_DEBUG("write(): connection lost.") - return self._retcode - - if self._retcode == self.SEND_FULL: - self._rtcout.RTC_DEBUG("write(): InPort buffer is full.") - ret = self._buffer.write(data, sec, usec) - self._task.signal() - return self.BUFFER_FULL - - # why? - #assert(self._buffer != 0) - - self.onBufferWrite(data) - ret = self._buffer.write(data, sec, usec) - - self._task.signal() - self._rtcout.RTC_DEBUG("%s = write()", OpenRTM_aist.DataPortStatus.toString(ret)) - - return self.convertReturn(ret, data) - - ## - # @if jp - # - # @brief ƥֲǧ - # - # Publisher ϥǡݡȤƱ activate/deactivate 롣 - # activate() / deactivate() ؿˤäơƥ־֤󥢥ƥ - # ־֤ڤؤ롣δؿˤꡢߥƥ־֤󥢥 - # ƥ־֤ǧ뤳ȤǤ롣 - # - # @return ֳǧ(ƥ־:true󥢥ƥ־:false) - # - # @else - # - # @brief If publisher is active state - # - # A Publisher can be activated/deactivated synchronized with the - # data port. The active state and the non-active state are made - # transition by the "activate()" and the "deactivate()" functions - # respectively. This function confirms if the publisher is in - # active state. - # - # @return Result of state confirmation - # (Active state:true, Inactive state:false) - # - # @endif - # - # bool PublisherNew::isActive() - def isActive(self): - return self._active - - ## - # @if jp - # @brief ƥֲ - # - # Publisher 򥢥ƥֲ롣δؿƤӽФȤˤꡢ - # Publisherġǡ륹åɤư򳫻Ϥ롣 - # ԤƤʤʤɤˤꡢʤ硢顼 - # PRECONDITION_NOT_MET ֤ - # - # @return PORT_OK ェλ - # PRECONDITION_NOT_MET ʤ - # - # @else - # @brief activation - # - # This function activates the publisher. By calling this - # function, this publisher starts the thread that pushes data to - # InPort. If precondition such as initialization process and so - # on is not met, the error code PRECONDITION_NOT_MET is returned. - # - # @return PORT_OK normal return - # PRECONDITION_NOT_MET precondition is not met - # - # @endif - # - # PublisherBase::ReturnCode PublisherNew::activate() - def activate(self): - self._active = True - return self.PORT_OK - - ## - # @if jp - # @brief 󥢥ƥֲ - # - # Publisher 󥢥ƥֲ롣δؿƤӽФȤˤꡢ - # Publisherġǡ륹åɤưߤ롣 - # ԤƤʤʤɤˤꡢʤ硢顼 - # PRECONDITION_NOT_MET ֤ - # - # @return PORT_OK ェλ - # PRECONDITION_NOT_MET ʤ - # - # @else - # @brief deactivation - # - # This function deactivates the publisher. By calling this - # function, this publisher stops the thread that pushes data to - # InPort. If precondition such as initialization process and so - # on is not met, the error code PRECONDITION_NOT_MET is returned. - # - # @return PORT_OK normal return - # PRECONDITION_NOT_MET precondition is not met - # - # @endif - # - # PublisherBase::ReturnCode PublisherNew::deactivate() - def deactivate(self): - self._active = False; - return self.PORT_OK - - ## - # @if jp - # @brief åɼ¹Դؿ - # - # coil::PeriodicTask ˤ¹Ԥ륿¹Դؿ - # - # @else - # @brief Thread execution function - # - # A task execution function to be executed by coil::PeriodicTask. - # - # @endif - # - # int PublisherNew::svc(void) - def svc(self): - guard = OpenRTM_aist.ScopedLock(self._retmutex) - - if self._pushPolicy == self.PUBLISHER_POLICY_ALL: - self._retcode = self.pushAll() - return 0 - elif self._pushPolicy == self.PUBLISHER_POLICY_FIFO: - self._retcode = self.pushFifo() - return 0 - elif self._pushPolicy == self.PUBLISHER_POLICY_SKIP: - self._retcode = self.pushSkip() - return 0 - elif self._pushPolicy == self.PUBLISHER_POLICY_NEW: - self._retcode = self.pushNew() - return 0 - else: - self._retcode = self.pushNew() - - return 0 - - ## - # @brief push all policy - # - # PublisherNew::ReturnCode PublisherNew::pushAll() - def pushAll(self): - self._rtcout.RTC_TRACE("pushAll()") - try: - - while self._buffer.readable() > 0: - cdr = self._buffer.get() - self.onBufferRead(cdr) - - self.onSend(cdr) - ret = self._consumer.put(cdr) - - if ret != self.PORT_OK: - self._rtcout.RTC_DEBUG("%s = consumer.put()", OpenRTM_aist.DataPortStatus.toString(ret)) - return self.invokeListener(ret, cdr) - self.onReceived(cdr) - - self._buffer.advanceRptr() - - return self.PORT_OK - except: - self._rtcout.RTC_ERROR(OpenRTM_aist.Logger.print_exception()) - return self.CONNECTION_LOST - - - - ## - # @brief push "fifo" policy - # - # PublisherNew::ReturnCode PublisherNew::pushFifo() - def pushFifo(self): - self._rtcout.RTC_TRACE("pushFifo()") - - try: - cdr = self._buffer.get() - self.onBufferRead(cdr) - - self.onSend(cdr) - ret = self._consumer.put(cdr) - - if ret != self.PORT_OK: - self._rtcout.RTC_DEBUG("%s = consumer.put()", OpenRTM_aist.DataPortStatus.toString(ret)) - return self.invokeListener(ret, cdr) - self.onReceived(cdr) - - self._buffer.advanceRptr() - - return self.PORT_OK - except: - self._rtcout.RTC_ERROR(OpenRTM_aist.Logger.print_exception()) - return self.CONNECTION_LOST - - - - ## - # @brief push "skip" policy - # - # PublisherNew::ReturnCode PublisherNew::pushSkip() - def pushSkip(self): - self._rtcout.RTC_TRACE("pushSkip()") - try: - ret = self.PORT_OK - - preskip = self._buffer.readable() + self._leftskip - loopcnt = preskip/(self._skipn+1) - postskip = self._skipn - self._leftskip - - for i in range(int(loopcnt)): - self._buffer.advanceRptr(postskip) - cdr = self._buffer.get() - self.onBufferRead(cdr) - - self.onSend(cdr) - ret = self._consumer.put(cdr) - if ret != self.PORT_OK: - self._buffer.advanceRptr(-postskip) - self._rtcout.RTC_DEBUG("%s = consumer.put()", OpenRTM_aist.DataPortStatus.toString(ret)) - return self.invokeListener(ret, cdr) - - self.onReceived(cdr) - postskip = self._skipn + 1 - - self._buffer.advanceRptr(self._buffer.readable()) - - if loopcnt == 0: - # Not put - self._leftskip = preskip % (self._skipn + 1) - else: - if self._retcode != self.PORT_OK: - # put Error after - self._leftskip = 0 + """ + """ + + # Policy + PUBLISHER_POLICY_ALL = 0 + PUBLISHER_POLICY_FIFO = 1 + PUBLISHER_POLICY_SKIP = 2 + PUBLISHER_POLICY_NEW = 3 + + ## + # @if jp + # @brief コンストラクタ + # + # コンストラクタ + # 本 Publisher 用新規スレッドを生成する。 + # + # @param self + # @param consumer データ送出を待つコンシューマ + # @param property 本Publisherの駆動制御情報を設定したPropertyオブジェクト + # (本Publisherでは未使用) + # @else + # @brief Constructor + # @endif + def __init__(self): + self._rtcout = OpenRTM_aist.Manager.instance().getLogbuf("PublisherNew") + self._consumer = None + self._buffer = None + self._task = None + self._retcode = self.PORT_OK + self._retmutex = threading.RLock() + self._pushPolicy = self.PUBLISHER_POLICY_NEW + self._skipn = 0 + self._active = False + self._leftskip = 0 + self._profile = None + self._listeners = None + + ## + # @if jp + # @brief デストラクタ + # + # デストラクタ + # + # @param self + # + # @else + # @brief Destructor + # + # @endif + def __del__(self): + self._rtcout.RTC_TRACE("~PublisherNew()") + + ## + # @if jp + # @brief 終了処理 + # + # @param self + # + # @else + # @brief + # @endif + def exit(self): + self._rtcout.RTC_TRACE("exit()") + if self._task: + self._task.resume() + self._task.finalize() + + #del self._task + self._rtcout.RTC_PARANOID("task deleted.") + + # "consumer" should be deleted in the Connector + self._consumer = None + # "buffer" should be deleted in the Connector + self._buffer = None + return + + + ## + # @if jp + # @brief PushPolicy の設定 + # @else + # @brief Setting PushPolicy + # @endif + # + # void PublisherNew::setPushPolicy(const coil::Properties& prop) + def setPushPolicy(self, prop): + push_policy = prop.getProperty("publisher.push_policy", "new") + self._rtcout.RTC_DEBUG("push_policy: %s", push_policy) + + push_policy = OpenRTM_aist.normalize(push_policy) + + if push_policy == "all": + self._pushPolicy = self.PUBLISHER_POLICY_ALL + + elif push_policy == "fifo": + self._pushPolicy = self.PUBLISHER_POLICY_FIFO + + elif push_policy == "skip": + self._pushPolicy = self.PUBLISHER_POLICY_SKIP + + elif push_policy == "new": + self._pushPolicy = self.PUBLISHER_POLICY_NEW + + else: + self._rtcout.RTC_ERROR( + "invalid push_policy value: %s", push_policy) + self._pushPolicy = self.PUBLISHER_POLICY_NEW + + skip_count = prop.getProperty("publisher.skip_count", "0") + self._rtcout.RTC_DEBUG("skip_count: %s", skip_count) + + skipn = self._skipn + ret, skipn = OpenRTM_aist.stringTo(skipn, skip_count) + if ret: + self._skipn = skipn + else: + self._rtcout.RTC_ERROR("invalid skip_count value: %s", skip_count) + self._skipn = 0 + + if self._skipn < 0: + self._rtcout.RTC_ERROR("invalid skip_count value: %d", self._skipn) + self._skipn = 0 + + return + + ## + # @if jp + # @brief Task の設定 + # @else + # @brief Setting Task + # @endif + # + # bool PublisherNew::createTask(const coil::Properties& prop) + def createTask(self, prop): + factory = OpenRTM_aist.PeriodicTaskFactory.instance() + + th = factory.getIdentifiers() + self._rtcout.RTC_DEBUG( + "available task types: %s", + OpenRTM_aist.flatten(th)) + + self._task = factory.createObject( + prop.getProperty("thread_type", "default")) + + if not self._task: + self._rtcout.RTC_ERROR("Task creation failed: %s", + prop.getProperty("thread_type", "default")) + return self.INVALID_ARGS + + self._rtcout.RTC_PARANOID("Task creation succeeded.") + + mprop = prop.getNode("measurement") + + # setting task function + self._task.setTask(self.svc) + self._task.setPeriod(0.0) + self._task.executionMeasure(OpenRTM_aist.toBool(mprop.getProperty("exec_time"), + "enable", "disable", True)) + ecount = 0 + ret, ecount = OpenRTM_aist.stringTo( + ecount, mprop.getProperty("exec_count")) + if ret: + self._task.executionMeasureCount(ecount) + + self._task.periodicMeasure(OpenRTM_aist.toBool(mprop.getProperty("period_time"), + "enable", "disable", True)) + pcount = 0 + ret, pcount = OpenRTM_aist.stringTo( + pcount, mprop.getProperty("period_count")) + if ret: + self._task.periodicMeasureCount(pcount) + + self._task.suspend() + self._task.activate() + self._task.suspend() + + return self.PORT_OK + + ## + # @if jp + # @brief 初期化 + # + # このクラスのオブジェクトを使用するのに先立ち、必ずこの関数を呼び + # 出す必要がある。引数には、このオブジェクトの各種設定情報を含む + # Properties を与える。データをプッシュする際のポリシーとして + # publisher.push_policy をキーとする値に、all, fifo, skip, new の + # いずれかを与えることができる。 + # + # 以下のオプションを与えることができる。 + # + # - thread_type: スレッドのタイプ (文字列、デフォルト: default) + # - publisher.push_policy: Pushポリシー (all, fifo, skip, new) + # - publisher.skip_count: 上記ポリシが skip のときのスキップ数 + # - measurement.exec_time: タスク実行時間計測 (enable/disable) + # - measurement.exec_count: タスク関数実行時間計測周期 (数値, 回数) + # - measurement.period_time: タスク周期時間計測 (enable/disable) + # - measurement.period_count: タスク周期時間計測周期 (数値, 回数) + # + # @param property 本Publisherの駆動制御情報を設定したPropertyオブジェクト + # @return ReturnCode PORT_OK 正常終了 + # INVALID_ARGS Properties が不正な値を含む + # + # @else + # @brief Initialization + # + # This function have to be called before using this class object. + # Properties object that includes certain configuration + # information should be given as an argument. all, fifo, skip, + # new can be given as a data push policy in a value of the key + # "publisher.push_policy." + # + # The following options are available. + # + # - thread_type: Thread type (string, default: default) + # - publisher.push_policy: Push policy (all, fifo, skip, new) + # - publisher.skip_count: The number of skip count in the "skip" policy + # - measurement.exec_time: Task execution time measurement (enable/disable) + # - measurement.exec_count: Task execution time measurement count + # (numerical, number of times) + # - measurement.period_time: Task period time measurement (enable/disable) + # - measurement.period_count: Task period time measurement count + # (number, count) + # + # @param property Property objects that includes the control information + # of this Publisher + # @return ReturnCode PORT_OK normal return + # INVALID_ARGS Properties with invalid values. + # @endif + # + # PublisherBase::ReturnCode PublisherNew::init(coil::Properties& prop) + def init(self, prop): + self._rtcout.RTC_TRACE("init()") + self.setPushPolicy(prop) + return self.createTask(prop) + + ## + # @if jp + # @brief InPortコンシューマのセット + # + # この関数では、この Publisher に関連付けられるコンシューマをセットする。 + # コンシューマオブジェクトがヌルポインタの場合、INVALID_ARGSが返される。 + # それ以外の場合は、PORT_OK が返される。 + # + # @param consumer Consumer へのポインタ + # @return ReturnCode PORT_OK 正常終了 + # INVALID_ARGS 引数に不正な値が含まれている + # + # @else + # @brief Store InPort consumer + # + # This operation sets a consumer that is associated with this + # object. If the consumer object is NULL, INVALID_ARGS will be + # returned. + # + # @param consumer A pointer to a consumer object. + # @return ReturnCode PORT_OK normal return + # INVALID_ARGS given argument has invalid value + # + # @endif + # + # PublisherBase::ReturnCode PublisherNew::setConsumer(InPortConsumer* + # consumer) + def setConsumer(self, consumer): + self._rtcout.RTC_TRACE("setConsumer()") + + if not consumer: + self._rtcout.RTC_ERROR( + "setConsumer(consumer = None): invalid argument.") + return self.INVALID_ARGS + + self._consumer = consumer + return self.PORT_OK + + ## + # @if jp + # @brief バッファのセット + # + # この関数では、この Publisher に関連付けられるバッファをセットする。 + # バッファオブジェクトがヌルポインタの場合、INVALID_ARGSが返される。 + # それ以外の場合は、PORT_OK が返される。 + # + # @param buffer CDR buffer へのポインタ + # @return ReturnCode PORT_OK 正常終了 + # INVALID_ARGS 引数に不正な値が含まれている + # + # @else + # @brief Setting buffer pointer + # + # This operation sets a buffer that is associated with this + # object. If the buffer object is NULL, INVALID_ARGS will be + # returned. + # + # @param buffer A pointer to a CDR buffer object. + # @return ReturnCode PORT_OK normal return + # INVALID_ARGS given argument has invalid value + # + # @endif + # + # PublisherBase::ReturnCode PublisherNew::setBuffer(CdrBufferBase* buffer) + def setBuffer(self, buffer): + self._rtcout.RTC_TRACE("setBuffer()") + + if not buffer: + self._rtcout.RTC_ERROR("setBuffer(buffer == None): invalid argument") + return self.INVALID_ARGS + + self._buffer = buffer + return self.PORT_OK + + ## + # @if jp + # @brief リスナを設定する。 + # + # Publisher に対してリスナオブジェクト ConnectorListeners を設定する。 + # 各種リスナオブジェクトを含む ConnectorListeners をセットすることで、 + # バッファの読み書き、データの送信時等にこれらのリスナをコールする。 + # ConnectorListeners オブジェクトの所有権はポートまたは RTObject が持ち + # Publisher 削除時に ConnectorListeners は削除されることはない。 + # ConnectorListeners がヌルポインタの場合 INVALID_ARGS を返す。 + # + # @param info ConnectorProfile をローカル化したオブジェクト ConnectorInfo + # @param listeners リスナを多数保持する ConnectorListeners オブジェクト + # @return PORT_OK 正常終了 + # INVALID_ARGS 不正な引数 + # @else + # @brief Set the listener. + # + # This function sets ConnectorListeners listener object to the + # Publisher. By setting ConnectorListeners containing various + # listeners objects, these listeners are called at the time of + # reading and writing of a buffer, and transmission of data + # etc. Since the ownership of the ConnectorListeners object is + # owned by Port or RTObject, the Publisher never deletes the + # ConnectorListeners object. If the given ConnectorListeners' + # pointer is NULL, this function returns INVALID_ARGS. + # + # @param info ConnectorInfo that is localized object of ConnectorProfile + # @param listeners ConnectorListeners that holds various listeners + # @return PORT_OK Normal return + # INVALID_ARGS Invalid arguments + # @endif + # + # virtual ReturnCode setListener(ConnectorInfo& info, + # ConnectorListeners* listeners); + def setListener(self, info, listeners): + self._rtcout.RTC_TRACE("setListener()") + + if not listeners: + self._rtcout.RTC_ERROR( + "setListeners(listeners == None): invalid argument") + return self.INVALID_ARGS + + self._profile = info + self._listeners = listeners + + return self.PORT_OK + + ## + # @if jp + # @brief データを書き込む + # + # Publisher が保持するバッファに対してデータを書き込む。コンシュー + # マ、バッファ、リスナ等が適切に設定されていない等、Publisher オブ + # ジェクトが正しく初期化されていない場合、この関数を呼び出すとエラー + # コード PRECONDITION_NOT_MET が返され、バッファへの書き込み等の操 + # 作は一切行われない。 + # + # バッファへの書き込みと、InPortへのデータの送信は非同期的に行われ + # るため、この関数は、InPortへのデータ送信の結果を示す、 + # CONNECTION_LOST, BUFFER_FULL などのリターンコードを返すことがあ + # る。この場合、データのバッファへの書き込みは行われない。 + # + # バッファへの書き込みに対して、バッファがフル状態、バッファのエ + # ラー、バッファへの書き込みがタイムアウトした場合、バッファの事前 + # 条件が満たされない場合にはそれぞれ、エラーコード BUFFER_FULL, + # BUFFER_ERROR, BUFFER_TIMEOUT, PRECONDITION_NOT_MET が返される。 + # + # これら以外のエラーの場合、PORT_ERROR が返される。 + # + # + # @param data 書き込むデータ + # @param sec タイムアウト時間 + # @param nsec タイムアウト時間 + # + # @return PORT_OK 正常終了 + # PRECONDITION_NO_MET consumer, buffer, listener等が適切に設定 + # されていない等、このオブジェクトの事前条件 + # を満たさない場合。 + # CONNECTION_LOST 接続が切断されたことを検知した。 + # BUFFER_FULL バッファがフル状態である。 + # BUFFER_ERROR バッファに何らかのエラーが生じた場合。 + # NOT_SUPPORTED サポートされない操作が行われた。 + # TIMEOUT タイムアウトした。 + # + # @else + # @brief Write data + # + # This function writes data into the buffer associated with this + # Publisher. If a Publisher object calls this function, without + # initializing correctly such as a consumer, a buffer, listeners, + # etc., error code PRECONDITION_NOT_MET will be returned and no + # operation of the writing to a buffer etc. will be performed. + # + # Since writing into the buffer and sending data to InPort are + # performed asynchronously, occasionally this function returns + # return-codes such as CONNECTION_LOST and BUFFER_FULL that + # indicate the result of sending data to InPort. In this case, + # writing data into buffer will not be performed. + # + # When publisher writes data to the buffer, if the buffer is + # filled, returns error, is returned with timeout and returns + # precondition error, error codes BUFFER_FULL, BUFFER_ERROR, + # BUFFER_TIMEOUT and PRECONDITION_NOT_MET will be returned + # respectively. + # + # In other cases, PROT_ERROR will be returned. + # + # @param data Data to be wrote to the buffer + # @param sec Timeout time in unit seconds + # @param nsec Timeout time in unit nano-seconds + # @return PORT_OK Normal return + # PRECONDITION_NO_MET Precondition does not met. A consumer, + # a buffer, listenes are not set properly. + # CONNECTION_LOST detected that the connection has been lost + # BUFFER_FULL The buffer is full status. + # BUFFER_ERROR Some kind of error occurred in the buffer. + # NOT_SUPPORTED Some kind of operation that is not supported + # has been performed. + # TIMEOUT Timeout occurred when writing to the buffer. + # + # @endif + # + # PublisherBase::ReturnCode PublisherNew::write(const cdrMemoryStream& data, + # unsigned long sec, + # unsigned long usec) + def write(self, data, sec, usec): + self._rtcout.RTC_PARANOID("write()") + + if not self._consumer or not self._buffer or not self._listeners: + return self.PRECONDITION_NOT_MET + + if self._retcode == self.CONNECTION_LOST: + self._rtcout.RTC_DEBUG("write(): connection lost.") + return self._retcode + + if self._retcode == self.SEND_FULL: + self._rtcout.RTC_DEBUG("write(): InPort buffer is full.") + ret = self._buffer.write(data, sec, usec) + self._task.signal() + return self.BUFFER_FULL + + # why? + #assert(self._buffer != 0) + + self.onBufferWrite(data) + ret = self._buffer.write(data, sec, usec) + + self._task.signal() + self._rtcout.RTC_DEBUG("%s = write()", + OpenRTM_aist.DataPortStatus.toString(ret)) + + return self.convertReturn(ret, data) + + ## + # @if jp + # + # @brief アクティブ化確認 + # + # Publisher はデータポートと同期して activate/deactivate される。 + # activate() / deactivate() 関数によって、アクティブ状態と非アクティ + # ブ状態が切り替わる。この関数により、現在アクティブ状態か、非アク + # ティブ状態かを確認することができる。 + # + # @return 状態確認結果(アクティブ状態:true、非アクティブ状態:false) + # + # @else + # + # @brief If publisher is active state + # + # A Publisher can be activated/deactivated synchronized with the + # data port. The active state and the non-active state are made + # transition by the "activate()" and the "deactivate()" functions + # respectively. This function confirms if the publisher is in + # active state. + # + # @return Result of state confirmation + # (Active state:true, Inactive state:false) + # + # @endif + # + # bool PublisherNew::isActive() + def isActive(self): + return self._active + + ## + # @if jp + # @brief アクティブ化する + # + # Publisher をアクティブ化する。この関数を呼び出すことにより、 + # Publisherが持つ、データを送信するスレッドが動作を開始する。初期 + # 化が行われていないなどにより、事前条件を満たさない場合、エラーコー + # ド PRECONDITION_NOT_MET を返す。 + # + # @return PORT_OK 正常終了 + # PRECONDITION_NOT_MET 事前条件を満たさない + # + # @else + # @brief activation + # + # This function activates the publisher. By calling this + # function, this publisher starts the thread that pushes data to + # InPort. If precondition such as initialization process and so + # on is not met, the error code PRECONDITION_NOT_MET is returned. + # + # @return PORT_OK normal return + # PRECONDITION_NOT_MET precondition is not met + # + # @endif + # + # PublisherBase::ReturnCode PublisherNew::activate() + def activate(self): + self._active = True + return self.PORT_OK + + ## + # @if jp + # @brief 非アクティブ化する + # + # Publisher を非アクティブ化する。この関数を呼び出すことにより、 + # Publisherが持つ、データを送信するスレッドが動作を停止する。初期 + # 化が行われていないなどにより、事前条件を満たさない場合、エラーコー + # ド PRECONDITION_NOT_MET を返す。 + # + # @return PORT_OK 正常終了 + # PRECONDITION_NOT_MET 事前条件を満たさない + # + # @else + # @brief deactivation + # + # This function deactivates the publisher. By calling this + # function, this publisher stops the thread that pushes data to + # InPort. If precondition such as initialization process and so + # on is not met, the error code PRECONDITION_NOT_MET is returned. + # + # @return PORT_OK normal return + # PRECONDITION_NOT_MET precondition is not met + # + # @endif + # + # PublisherBase::ReturnCode PublisherNew::deactivate() + def deactivate(self): + self._active = False + return self.PORT_OK + + ## + # @if jp + # @brief スレッド実行関数 + # + # coil::PeriodicTask により周期実行されるタスク実行関数。 + # + # @else + # @brief Thread execution function + # + # A task execution function to be executed by coil::PeriodicTask. + # + # @endif + # + # int PublisherNew::svc(void) + def svc(self): + guard = OpenRTM_aist.ScopedLock(self._retmutex) + + if self._pushPolicy == self.PUBLISHER_POLICY_ALL: + self._retcode = self.pushAll() + return 0 + elif self._pushPolicy == self.PUBLISHER_POLICY_FIFO: + self._retcode = self.pushFifo() + return 0 + elif self._pushPolicy == self.PUBLISHER_POLICY_SKIP: + self._retcode = self.pushSkip() + return 0 + elif self._pushPolicy == self.PUBLISHER_POLICY_NEW: + self._retcode = self.pushNew() + return 0 + else: + self._retcode = self.pushNew() + + return 0 + + ## + # @brief push all policy + # + # PublisherNew::ReturnCode PublisherNew::pushAll() + def pushAll(self): + self._rtcout.RTC_TRACE("pushAll()") + try: + + while self._buffer.readable() > 0: + _, cdr = self._buffer.get() + self.onBufferRead(cdr) + + cdr = self.onSend(cdr) + ret = self._consumer.put(cdr) + + if ret != self.PORT_OK: + self._rtcout.RTC_DEBUG( + "%s = consumer.put()", + OpenRTM_aist.DataPortStatus.toString(ret)) + return self.invokeListener(ret, cdr) + cdr = self.onReceived(cdr) + + self._buffer.advanceRptr() + + return self.PORT_OK + except BaseException: + self._rtcout.RTC_ERROR(OpenRTM_aist.Logger.print_exception()) + return self.CONNECTION_LOST + + ## + # @brief push "fifo" policy + # + # PublisherNew::ReturnCode PublisherNew::pushFifo() + + def pushFifo(self): + self._rtcout.RTC_TRACE("pushFifo()") + + try: + _, cdr = self._buffer.get() + self.onBufferRead(cdr) + + cdr = self.onSend(cdr) + ret = self._consumer.put(cdr) + + if ret != self.PORT_OK: + self._rtcout.RTC_DEBUG( + "%s = consumer.put()", + OpenRTM_aist.DataPortStatus.toString(ret)) + return self.invokeListener(ret, cdr) + cdr = self.onReceived(cdr) + + self._buffer.advanceRptr() + + return self.PORT_OK + except BaseException: + self._rtcout.RTC_ERROR(OpenRTM_aist.Logger.print_exception()) + return self.CONNECTION_LOST + + ## + # @brief push "skip" policy + # + # PublisherNew::ReturnCode PublisherNew::pushSkip() + + def pushSkip(self): + self._rtcout.RTC_TRACE("pushSkip()") + try: + ret = self.PORT_OK + + preskip = self._buffer.readable() + self._leftskip + loopcnt = preskip / (self._skipn + 1) + postskip = self._skipn - self._leftskip + + for i in range(int(loopcnt)): + self._buffer.advanceRptr(postskip) + _, cdr = self._buffer.get() + self.onBufferRead(cdr) + + cdr = self.onSend(cdr) + ret = self._consumer.put(cdr) + if ret != self.PORT_OK: + self._buffer.advanceRptr(-postskip) + self._rtcout.RTC_DEBUG( + "%s = consumer.put()", + OpenRTM_aist.DataPortStatus.toString(ret)) + return self.invokeListener(ret, cdr) + + cdr = self.onReceived(cdr) + postskip = self._skipn + 1 + + self._buffer.advanceRptr(self._buffer.readable()) + + if loopcnt == 0: + # Not put + self._leftskip = preskip % (self._skipn + 1) + else: + if self._retcode != self.PORT_OK: + # put Error after + self._leftskip = 0 + else: + # put OK after + self._leftskip = preskip % (self._skipn + 1) + + return ret + + except BaseException: + self._rtcout.RTC_ERROR(OpenRTM_aist.Logger.print_exception()) + return self.CONNECTION_LOST + + ## + # @brief push "new" policy + # + # PublisherNew::ReturnCode PublisherNew::pushNew() + + def pushNew(self): + self._rtcout.RTC_TRACE("pushNew()") + try: + self._buffer.advanceRptr(self._buffer.readable() - 1) + + _, cdr = self._buffer.get() + self.onBufferRead(cdr) + + cdr = self.onSend(cdr) + ret = self._consumer.put(cdr) + + if ret != self.PORT_OK: + self._rtcout.RTC_DEBUG( + "%s = consumer.put()", + OpenRTM_aist.DataPortStatus.toString(ret)) + return self.invokeListener(ret, cdr) + + cdr = self.onReceived(cdr) + self._buffer.advanceRptr() + + return self.PORT_OK + + except BaseException: + self._rtcout.RTC_ERROR(OpenRTM_aist.Logger.print_exception()) + return self.CONNECTION_LOST + + ## + # @if jp + # @brief BufferStatus から DataPortStatus への変換 + # + # バッファからの戻り値を DataPortStatus::Enum 型へ変換する関数。そ + # れぞれ、以下のように変換される。変換時にコールバックを呼ぶ場合、 + # コールバク関数も付記する。 + # + # - BUFFER_OK: PORT_OK + # - None + # - BUFFER_ERROR: BUFFER_ERROR + # - None + # - BUFFER_FULL: BUFFER_FULL + # - onBufferFull() + # - NOT_SUPPORTED: PORT_ERROR + # - None + # - TIMEOUT: BUFFER_TIMEOUT + # - onBufferWriteTimeout() + # - PRECONDITION_NOT_MET: PRECONDITION_NOT_MET + # - None + # - other: PORT_ERROR + # - None + # + # @param status BufferStatus + # @param data cdrMemoryStream + # @return DataPortStatu 型のリターンコード + # + # @else + # @brief Convertion from BufferStatus to DataPortStatus + # + # This function converts return value from the buffer to + # DataPortStatus::Enum typed return value. The conversion rule is + # as follows. Callback functions are also shown, if it exists. + # + # - BUFFER_OK: PORT_OK + # - None + # - BUFFER_ERROR: BUFFER_ERROR + # - None + # - BUFFER_FULL: BUFFER_FULL + # - onBufferFull() + # - NOT_SUPPORTED: PORT_ERROR + # - None + # - TIMEOUT: BUFFER_TIMEOUT + # - onBufferWriteTimeout() + # - PRECONDITION_NOT_MET: PRECONDITION_NOT_MET + # - None + # - other: PORT_ERROR + # - None + # + # @param status BufferStatus + # @param data cdrMemoryStream + # @return DataPortStatus typed return code + # + # @endif + # + # PublisherBase::ReturnCode + # PublisherNew::convertReturn(BufferStatus::Enum status, + # const cdrMemoryStream& data) + + def convertReturn(self, status, data): + ## + # BufferStatus -> DataPortStatus + # + # BUFFER_OK -> PORT_OK + # BUFFER_ERROR -> BUFFER_ERROR + # BUFFER_FULL -> BUFFER_FULL + # NOT_SUPPORTED -> PORT_ERROR + # TIMEOUT -> BUFFER_TIMEOUT + # PRECONDITION_NOT_MET -> PRECONDITION_NOT_MET + ## + if status == OpenRTM_aist.BufferStatus.BUFFER_OK: + return self.PORT_OK + + elif status == OpenRTM_aist.BufferStatus.BUFFER_ERROR: + return self.BUFFER_ERROR + + elif status == OpenRTM_aist.BufferStatus.BUFFER_FULL: + self.onBufferFull(data) + return self.BUFFER_FULL + + elif status == OpenRTM_aist.BufferStatus.NOT_SUPPORTED: + return self.PORT_ERROR + + elif status == OpenRTM_aist.BufferStatus.TIMEOUT: + self.onBufferWriteTimeout(data) + return self.BUFFER_TIMEOUT + + elif status == OpenRTM_aist.BufferStatus.PRECONDITION_NOT_MET: + return self.PRECONDITION_NOT_MET + + else: + return self.PORT_ERROR + + ## + # @if jp + # @brief DataPortStatusに従ってリスナへ通知する関数を呼び出す。 + # + # @param status DataPortStatus + # @param data cdrMemoryStream + # @return リターンコード + # + # @else + # @brief Call listeners according to the DataPortStatus + # + # @param status DataPortStatus + # @param data cdrMemoryStream + # @return Return code + # + # @endif + # + # PublisherNew::ReturnCode + # PublisherNew::invokeListener(DataPortStatus::Enum status, + # const cdrMemoryStream& data) + def invokeListener(self, status, data): + # ret: + # PORT_OK, PORT_ERROR, SEND_FULL, SEND_TIMEOUT, CONNECTION_LOST, + # UNKNOWN_ERROR + if status == self.PORT_ERROR: + self.onReceiverError(data) + return self.PORT_ERROR + + elif status == self.SEND_FULL: + self.onReceiverFull(data) + return self.SEND_FULL + + elif status == self.SEND_TIMEOUT: + self.onReceiverTimeout(data) + return self.SEND_TIMEOUT + + elif status == self.CONNECTION_LOST: + self.onReceiverError(data) + return self.CONNECTION_LOST + + elif status == self.UNKNOWN_ERROR: + self.onReceiverError(data) + return self.UNKNOWN_ERROR + else: - # put OK after - self._leftskip = preskip % (self._skipn + 1) - - return ret - - except: - self._rtcout.RTC_ERROR(OpenRTM_aist.Logger.print_exception()) - return self.CONNECTION_LOST - - - - ## - # @brief push "new" policy - # - # PublisherNew::ReturnCode PublisherNew::pushNew() - def pushNew(self): - self._rtcout.RTC_TRACE("pushNew()") - try: - self._buffer.advanceRptr(self._buffer.readable() - 1) - - cdr = self._buffer.get() - self.onBufferRead(cdr) - - self.onSend(cdr) - ret = self._consumer.put(cdr) - - if ret != self.PORT_OK: - self._rtcout.RTC_DEBUG("%s = consumer.put()", OpenRTM_aist.DataPortStatus.toString(ret)) - return self.invokeListener(ret, cdr) - - self.onReceived(cdr) - self._buffer.advanceRptr() - - return self.PORT_OK - - except: - self._rtcout.RTC_ERROR(OpenRTM_aist.Logger.print_exception()) - return self.CONNECTION_LOST - - - - ## - # @if jp - # @brief BufferStatus DataPortStatus ؤѴ - # - # Хåեͤ DataPortStatus::Enum Ѵؿ - # 줾졢ʲΤ褦Ѵ롣Ѵ˥ХåƤ־硢 - # Хؿյ롣 - # - # - BUFFER_OK: PORT_OK - # - None - # - BUFFER_ERROR: BUFFER_ERROR - # - None - # - BUFFER_FULL: BUFFER_FULL - # - onBufferFull() - # - NOT_SUPPORTED: PORT_ERROR - # - None - # - TIMEOUT: BUFFER_TIMEOUT - # - onBufferWriteTimeout() - # - PRECONDITION_NOT_MET: PRECONDITION_NOT_MET - # - None - # - other: PORT_ERROR - # - None - # - # @param status BufferStatus - # @param data cdrMemoryStream - # @return DataPortStatu Υ꥿󥳡 - # - # @else - # @brief Convertion from BufferStatus to DataPortStatus - # - # This function converts return value from the buffer to - # DataPortStatus::Enum typed return value. The conversion rule is - # as follows. Callback functions are also shown, if it exists. - # - # - BUFFER_OK: PORT_OK - # - None - # - BUFFER_ERROR: BUFFER_ERROR - # - None - # - BUFFER_FULL: BUFFER_FULL - # - onBufferFull() - # - NOT_SUPPORTED: PORT_ERROR - # - None - # - TIMEOUT: BUFFER_TIMEOUT - # - onBufferWriteTimeout() - # - PRECONDITION_NOT_MET: PRECONDITION_NOT_MET - # - None - # - other: PORT_ERROR - # - None - # - # @param status BufferStatus - # @param data cdrMemoryStream - # @return DataPortStatus typed return code - # - # @endif - # - # PublisherBase::ReturnCode - # PublisherNew::convertReturn(BufferStatus::Enum status, - # const cdrMemoryStream& data) - def convertReturn(self, status, data): + self.onReceiverError(data) + return self.PORT_ERROR + + ## + # @if jp + # @brief ON_BUFFER_WRITEのリスナへ通知する。 + # @param data cdrMemoryStream + # @else + # @brief Notify an ON_BUFFER_WRITE event to listeners + # @param data cdrMemoryStream + # @endif + # + # inline void onBufferWrite(const cdrMemoryStream& data) + def onBufferWrite(self, data): + if self._listeners is not None and self._profile is not None: + _, data = self._listeners.notifyData( + OpenRTM_aist.ConnectorDataListenerType.ON_BUFFER_WRITE, self._profile, data) + return data + + ## + # @if jp + # @brief ON_BUFFER_FULLリスナへイベントを通知する。 + # @param data cdrMemoryStream + # @else + # @brief Notify an ON_BUFFER_FULL event to listeners + # @param data cdrMemoryStream + # @endif + # + # inline void onBufferFull(const cdrMemoryStream& data) + def onBufferFull(self, data): + if self._listeners is not None and self._profile is not None: + _, data = self._listeners.notifyData( + OpenRTM_aist.ConnectorDataListenerType.ON_BUFFER_FULL, self._profile, data) + return data + + ## + # @if jp + # @brief ON_BUFFER_WRITE_TIMEOUTのリスナへ通知する。 + # @param data cdrMemoryStream + # @else + # @brief Notify an ON_BUFFER_WRITE_TIMEOUT event to listeners + # @param data cdrMemoryStream + # @endif + # + # inline void onBufferWriteTimeout(const cdrMemoryStream& data) + def onBufferWriteTimeout(self, data): + if self._listeners is not None and self._profile is not None: + _, data = self._listeners.notifyData( + OpenRTM_aist.ConnectorDataListenerType.ON_BUFFER_WRITE_TIMEOUT, self._profile, data) + return data + + ## + # @if jp + # @brief ON_BUFFER_OVERWRITEのリスナへ通知する。 + # @param data cdrMemoryStream + # @else + # @brief Notify an ON_BUFFER_OVERWRITE event to listeners + # @param data cdrMemoryStream + # @endif + # + # inline void onBufferWriteOverwrite(const cdrMemoryStream& data) + def onBufferWriteOverwrite(self, data): + if self._listeners is not None and self._profile is not None: + _, data = self._listeners.notifyData( + OpenRTM_aist.ConnectorDataListenerType.ON_BUFFER_OVERWRITE, self._profile, data) + return data + + ## + # @if jp + # @brief ON_BUFFER_READのリスナへ通知する。 + # @param data cdrMemoryStream + # @else + # @brief Notify an ON_BUFFER_READ event to listeners + # @param data cdrMemoryStream + # @endif + # + # inline void onBufferRead(const cdrMemoryStream& data) + def onBufferRead(self, data): + if self._listeners is not None and self._profile is not None: + _, data = self._listeners.notifyData( + OpenRTM_aist.ConnectorDataListenerType.ON_BUFFER_READ, self._profile, data) + return data + ## - # BufferStatus -> DataPortStatus - # - # BUFFER_OK -> PORT_OK - # BUFFER_ERROR -> BUFFER_ERROR - # BUFFER_FULL -> BUFFER_FULL - # NOT_SUPPORTED -> PORT_ERROR - # TIMEOUT -> BUFFER_TIMEOUT - # PRECONDITION_NOT_MET -> PRECONDITION_NOT_MET + # @if jp + # @brief ON_SENDのリスナへ通知する。 + # @param data cdrMemoryStream + # @else + # @brief Notify an ON_SEND event to listners + # @param data cdrMemoryStream + # @endif + # + # inline void onSend(const cdrMemoryStream& data) + def onSend(self, data): + if self._listeners is not None and self._profile is not None: + _, data = self._listeners.notifyData( + OpenRTM_aist.ConnectorDataListenerType.ON_SEND, self._profile, data) + return data + + ## + # @if jp + # @brief ON_RECEIVEDのリスナへ通知する。 + # @param data cdrMemoryStream + # @else + # @brief Notify an ON_RECEIVED event to listeners + # @param data cdrMemoryStream + # @endif + # + # inline void onReceived(const cdrMemoryStream& data) + def onReceived(self, data): + if self._listeners is not None and self._profile is not None: + _, data = self._listeners.notifyData( + OpenRTM_aist.ConnectorDataListenerType.ON_RECEIVED, self._profile, data) + return data + + ## + # @if jp + # @brief ON_RECEIVER_FULLのリスナへ通知する。 + # @param data cdrMemoryStream + # @else + # @brief Notify an ON_RECEIVER_FULL event to listeners + # @param data cdrMemoryStream + # @endif + # + # inline void onReceiverFull(const cdrMemoryStream& data) + def onReceiverFull(self, data): + if self._listeners is not None and self._profile is not None: + _, data = self._listeners.notifyData( + OpenRTM_aist.ConnectorDataListenerType.ON_RECEIVER_FULL, self._profile, data) + return data + ## - if status == OpenRTM_aist.BufferStatus.BUFFER_OK: - return self.PORT_OK - - elif status == OpenRTM_aist.BufferStatus.BUFFER_ERROR: - return self.BUFFER_ERROR - - elif status == OpenRTM_aist.BufferStatus.BUFFER_FULL: - self.onBufferFull(data) - return self.BUFFER_FULL - - elif status == OpenRTM_aist.BufferStatus.NOT_SUPPORTED: - return self.PORT_ERROR - - elif status == OpenRTM_aist.BufferStatus.TIMEOUT: - self.onBufferWriteTimeout(data) - return self.BUFFER_TIMEOUT - - elif status == OpenRTM_aist.BufferStatus.PRECONDITION_NOT_MET: - return self.PRECONDITION_NOT_MET - - else: - return self.PORT_ERROR - - ## - # @if jp - # @brief DataPortStatus˽äƥꥹʤΤؿƤӽФ - # - # @param status DataPortStatus - # @param data cdrMemoryStream - # @return ꥿󥳡 - # - # @else - # @brief Call listeners according to the DataPortStatus - # - # @param status DataPortStatus - # @param data cdrMemoryStream - # @return Return code - # - # @endif - # - # PublisherNew::ReturnCode - # PublisherNew::invokeListener(DataPortStatus::Enum status, - # const cdrMemoryStream& data) - def invokeListener(self, status, data): - # ret: - # PORT_OK, PORT_ERROR, SEND_FULL, SEND_TIMEOUT, CONNECTION_LOST, - # UNKNOWN_ERROR - if status == self.PORT_ERROR: - self.onReceiverError(data) - return self.PORT_ERROR - - elif status == self.SEND_FULL: - self.onReceiverFull(data) - return self.SEND_FULL - - elif status == self.SEND_TIMEOUT: - self.onReceiverTimeout(data) - return self.SEND_TIMEOUT - - elif status == self.CONNECTION_LOST: - self.onReceiverError(data) - return self.CONNECTION_LOST - - elif status == self.UNKNOWN_ERROR: - self.onReceiverError(data) - return self.UNKNOWN_ERROR - - else: - self.onReceiverError(data) - return self.PORT_ERROR - - ## - # @if jp - # @brief ON_BUFFER_WRITEΥꥹʤΤ롣 - # @param data cdrMemoryStream - # @else - # @brief Notify an ON_BUFFER_WRITE event to listeners - # @param data cdrMemoryStream - # @endif - # - # inline void onBufferWrite(const cdrMemoryStream& data) - def onBufferWrite(self, data): - if self._listeners is not None and self._profile is not None: - self._listeners.connectorData_[OpenRTM_aist.ConnectorDataListenerType.ON_BUFFER_WRITE].notify(self._profile, data) - return - - ## - # @if jp - # @brief ON_BUFFER_FULLꥹʤإ٥ȤΤ롣 - # @param data cdrMemoryStream - # @else - # @brief Notify an ON_BUFFER_FULL event to listeners - # @param data cdrMemoryStream - # @endif - # - # inline void onBufferFull(const cdrMemoryStream& data) - def onBufferFull(self, data): - if self._listeners is not None and self._profile is not None: - self._listeners.connectorData_[OpenRTM_aist.ConnectorDataListenerType.ON_BUFFER_FULL].notify(self._profile, data) - return - - ## - # @if jp - # @brief ON_BUFFER_WRITE_TIMEOUTΥꥹʤΤ롣 - # @param data cdrMemoryStream - # @else - # @brief Notify an ON_BUFFER_WRITE_TIMEOUT event to listeners - # @param data cdrMemoryStream - # @endif - # - # inline void onBufferWriteTimeout(const cdrMemoryStream& data) - def onBufferWriteTimeout(self, data): - if self._listeners is not None and self._profile is not None: - self._listeners.connectorData_[OpenRTM_aist.ConnectorDataListenerType.ON_BUFFER_WRITE_TIMEOUT].notify(self._profile, data) - return - - ## - # @if jp - # @brief ON_BUFFER_OVERWRITEΥꥹʤΤ롣 - # @param data cdrMemoryStream - # @else - # @brief Notify an ON_BUFFER_OVERWRITE event to listeners - # @param data cdrMemoryStream - # @endif - # - # inline void onBufferWriteOverwrite(const cdrMemoryStream& data) - def onBufferWriteOverwrite(self, data): - if self._listeners is not None and self._profile is not None: - self._listeners.connectorData_[OpenRTM_aist.ConnectorDataListenerType.ON_BUFFER_OVERWRITE].notify(self._profile, data) - return - - ## - # @if jp - # @brief ON_BUFFER_READΥꥹʤΤ롣 - # @param data cdrMemoryStream - # @else - # @brief Notify an ON_BUFFER_READ event to listeners - # @param data cdrMemoryStream - # @endif - # - # inline void onBufferRead(const cdrMemoryStream& data) - def onBufferRead(self, data): - if self._listeners is not None and self._profile is not None: - self._listeners.connectorData_[OpenRTM_aist.ConnectorDataListenerType.ON_BUFFER_READ].notify(self._profile, data) - return - - ## - # @if jp - # @brief ON_SENDΥꥹʤΤ롣 - # @param data cdrMemoryStream - # @else - # @brief Notify an ON_SEND event to listners - # @param data cdrMemoryStream - # @endif - # - #inline void onSend(const cdrMemoryStream& data) - def onSend(self, data): - if self._listeners is not None and self._profile is not None: - self._listeners.connectorData_[OpenRTM_aist.ConnectorDataListenerType.ON_SEND].notify(self._profile, data) - return - - ## - # @if jp - # @brief ON_RECEIVEDΥꥹʤΤ롣 - # @param data cdrMemoryStream - # @else - # @brief Notify an ON_RECEIVED event to listeners - # @param data cdrMemoryStream - # @endif - # - # inline void onReceived(const cdrMemoryStream& data) - def onReceived(self, data): - if self._listeners is not None and self._profile is not None: - self._listeners.connectorData_[OpenRTM_aist.ConnectorDataListenerType.ON_RECEIVED].notify(self._profile, data) - return - - ## - # @if jp - # @brief ON_RECEIVER_FULLΥꥹʤΤ롣 - # @param data cdrMemoryStream - # @else - # @brief Notify an ON_RECEIVER_FULL event to listeners - # @param data cdrMemoryStream - # @endif - # - # inline void onReceiverFull(const cdrMemoryStream& data) - def onReceiverFull(self, data): - if self._listeners is not None and self._profile is not None: - self._listeners.connectorData_[OpenRTM_aist.ConnectorDataListenerType.ON_RECEIVER_FULL].notify(self._profile, data) - return - - ## - # @if jp - # @brief ON_RECEIVER_TIMEOUTΥꥹʤΤ롣 - # @param data cdrMemoryStream - # @else - # @brief Notify an ON_RECEIVER_TIMEOUT event to listeners - # @param data cdrMemoryStream - # @endif - # - # inline void onReceiverTimeout(const cdrMemoryStream& data) - def onReceiverTimeout(self, data): - if self._listeners is not None and self._profile is not None: - self._listeners.connectorData_[OpenRTM_aist.ConnectorDataListenerType.ON_RECEIVER_TIMEOUT].notify(self._profile, data) - return - - ## - # @if jp - # @brief ON_RECEIVER_ERRORΥꥹʤΤ롣 - # @param data cdrMemoryStream - # @else - # @brief Notify an ON_RECEIVER_ERROR event to listeners - # @param data cdrMemoryStream - # @endif - # - # inline void onReceiverError(const cdrMemoryStream& data) - def onReceiverError(self, data): - if self._listeners is not None and self._profile is not None: - self._listeners.connectorData_[OpenRTM_aist.ConnectorDataListenerType.ON_RECEIVER_ERROR].notify(self._profile, data) - return - - ## - # @if jp - # @brief ON_SENDER_ERRORΥꥹʤΤ롣 - # @param data cdrMemoryStream - # @else - # @brief Notify an ON_SENDER_ERROR event to listeners - # @param data cdrMemoryStream - # @endif - # - # inline void onSenderError() - def onSenderError(self): - if self._listeners is not None and self._profile is not None: - self._listeners.connector_[OpenRTM_aist.ConnectorListenerType.ON_SENDER_ERROR].notify(self._profile) - return + # @if jp + # @brief ON_RECEIVER_TIMEOUTのリスナへ通知する。 + # @param data cdrMemoryStream + # @else + # @brief Notify an ON_RECEIVER_TIMEOUT event to listeners + # @param data cdrMemoryStream + # @endif + # + # inline void onReceiverTimeout(const cdrMemoryStream& data) + def onReceiverTimeout(self, data): + if self._listeners is not None and self._profile is not None: + _, data = self._listeners.notifyData( + OpenRTM_aist.ConnectorDataListenerType.ON_RECEIVER_TIMEOUT, self._profile, data) + return data + ## + # @if jp + # @brief ON_RECEIVER_ERRORのリスナへ通知する。 + # @param data cdrMemoryStream + # @else + # @brief Notify an ON_RECEIVER_ERROR event to listeners + # @param data cdrMemoryStream + # @endif + # + # inline void onReceiverError(const cdrMemoryStream& data) + def onReceiverError(self, data): + if self._listeners is not None and self._profile is not None: + _, data = self._listeners.notifyData( + OpenRTM_aist.ConnectorDataListenerType.ON_RECEIVER_ERROR, self._profile, data) + return data + + ## + # @if jp + # @brief ON_SENDER_ERRORのリスナへ通知する。 + # @param data cdrMemoryStream + # @else + # @brief Notify an ON_SENDER_ERROR event to listeners + # @param data cdrMemoryStream + # @endif + # + # inline void onSenderError() + def onSenderError(self): + if self._listeners is not None and self._profile is not None: + self._listeners.notify( + OpenRTM_aist.ConnectorListenerType.ON_SENDER_ERROR, self._profile) + return def PublisherNewInit(): - OpenRTM_aist.PublisherFactory.instance().addFactory("new", - OpenRTM_aist.PublisherNew, - OpenRTM_aist.Delete) - OpenRTM_aist.PublisherFactory.instance().addFactory("nonblock", - OpenRTM_aist.PublisherNew, - OpenRTM_aist.Delete) + OpenRTM_aist.PublisherFactory.instance().addFactory("new", + OpenRTM_aist.PublisherNew) + OpenRTM_aist.PublisherFactory.instance().addFactory("nonblock", + OpenRTM_aist.PublisherNew) diff --git a/OpenRTM_aist/PublisherPeriodic.py b/OpenRTM_aist/PublisherPeriodic.py index 8e6f6c4f..4b68bba6 100644 --- a/OpenRTM_aist/PublisherPeriodic.py +++ b/OpenRTM_aist/PublisherPeriodic.py @@ -1,5 +1,5 @@ #!/usr/bin/env python -# -*- coding: euc-jp -*- +# -*- coding: utf-8 -*- ## # @file PublisherPeriodic.py @@ -24,12 +24,12 @@ ## # @if jp # @class PublisherPeriodic -# @brief PublisherPeriodic 饹 +# @brief PublisherPeriodic クラス # -# Ū˥ǡ뤿 Publisher 饹Υ饹ϡ -# Connector ˤäơХåեӥ󥷥塼ޤ˴Ϣդ -# 롣Ȥ˥ХåեǡФ󥷥塼ޤФ -# ǡФ롣 +# 周期的にデータを送信するための Publisher クラス。このクラスは、通 +# 常 Connector 内にあって、バッファおよびコンシューマに関連付けられ +# る。一定周期ごとにバッファからデータを取り出しコンシューマに対して +# データを送出する。 # # @else # @class PublisherPeriodic @@ -43,1059 +43,1098 @@ # @endif # class PublisherPeriodic(OpenRTM_aist.PublisherBase): - """ - """ - - # Policy - PUBLISHER_POLICY_ALL = 0 - PUBLISHER_POLICY_FIFO = 1 - PUBLISHER_POLICY_SKIP = 2 - PUBLISHER_POLICY_NEW = 3 - - ## - # @if jp - # @brief 󥹥ȥ饯 - # - # 󥹥ȥ饯 - # нθƤӽФֳ֤Property֥Ȥdataport.push_rate - # ꤷƤɬפ롣дֳ֤ϡHzñ̤ưʸǻꡣ - # ȤС1000.0Hzξϡ1000.0פꡣ - # 嵭ץѥƥ̤ξϡ1000Hzפꡣ - # - # @param self - # @param consumer ǡФԤĥ󥷥塼 - # @param property PublisherζưꤷProperty֥ - # - # @else - # @brief Constructor - # @endif - def __init__(self): - self._rtcout = OpenRTM_aist.Manager.instance().getLogbuf("PublisherPeriodic") - self._consumer = None - self._buffer = None - self._task = None - self._retcode = self.PORT_OK - self._retmutex = threading.RLock() - self._pushPolicy = self.PUBLISHER_POLICY_NEW - self._skipn = 0 - self._active = False - self._readback = False - self._leftskip = 0 - self._profile = None - self._listeners = None - - return - - ## - # @if jp - # @brief ǥȥ饯 - # - # ǥȥ饯 - # - # @param self - # - # @else - # @brief Destructor - # @endif - def __del__(self): - self._rtcout.RTC_TRACE("~PublisherPeriodic()") - if self._task: - self._task.resume() - self._task.finalize() - self._rtcout.RTC_PARANOID("task finalized.") - - OpenRTM_aist.PeriodicTaskFactory.instance().deleteObject(self._task) - del self._task - self._rtcout.RTC_PARANOID("task deleted.") - - # "consumer" should be deleted in the Connector - self._consumer = None - # "buffer" should be deleted in the Connector - self._buffer = None - return - - ## - # @if jp - # @brief PushPolicy - # @else - # @brief Setting PushPolicy - # @endif - # - #void PublisherNew::setPushPolicy(const coil::Properties& prop) - def setPushPolicy(self, prop): - push_policy = prop.getProperty("publisher.push_policy","new") - self._rtcout.RTC_DEBUG("push_policy: %s", push_policy) - - push_policy = OpenRTM_aist.normalize([push_policy]) - - if push_policy == "all": - self._pushPolicy = self.PUBLISHER_POLICY_ALL - - elif push_policy == "fifo": - self._pushPolicy = self.PUBLISHER_POLICY_FIFO - - elif push_policy == "skip": - self._pushPolicy = self.PUBLISHER_POLICY_SKIP - - elif push_policy == "new": - self._pushPolicy = self.PUBLISHER_POLICY_NEW - - else: - self._rtcout.RTC_ERROR("invalid push_policy value: %s", push_policy) - self._pushPolicy = self.PUBLISHER_POLICY_NEW - - skip_count = prop.getProperty("publisher.skip_count","0") - self._rtcout.RTC_DEBUG("skip_count: %s", skip_count) - - skipn = [self._skipn] - ret = OpenRTM_aist.stringTo(skipn, skip_count) - if ret: - self._skipn = skipn[0] - else: - self._rtcout.RTC_ERROR("invalid skip_count value: %s", skip_count) - self._skipn = 0 - - if self._skipn < 0: - self._rtcout.RTC_ERROR("invalid skip_count value: %d", self._skipn) - self._skipn = 0 - - return - - ## - # @if jp - # @brief Task - # @else - # @brief Setting Task - # @endif - # - #bool PublisherNew::createTask(const coil::Properties& prop) - def createTask(self, prop): - factory = OpenRTM_aist.PeriodicTaskFactory.instance() - - th = factory.getIdentifiers() - self._rtcout.RTC_DEBUG("available task types: %s", OpenRTM_aist.flatten(th)) - - self._task = factory.createObject(prop.getProperty("thread_type", "default")) - if not self._task: - self._rtcout.RTC_ERROR("Task creation failed: %s", - prop.getProperty("thread_type", "default")) - return self.INVALID_ARGS - - self._rtcout.RTC_PARANOID("Task creation succeeded.") - - # setting task function - self._task.setTask(self.svc) - - # Task execution rate - rate = prop.getProperty("publisher.push_rate") - - if rate != "": - hz = float(rate) - if hz == 0: - hz = 1000.0 - self._rtcout.RTC_DEBUG("Task period %f [Hz]", hz) - else: - hz = 1000.0 - - self._task.setPeriod(1.0/hz) - - # Measurement setting - mprop = prop.getNode("measurement") - - self._task.executionMeasure(OpenRTM_aist.toBool(mprop.getProperty("exec_time"), - "enable", "disable", True)) - - ecount = [0] - if OpenRTM_aist.stringTo(ecount, mprop.getProperty("exec_count")): - self._task.executionMeasureCount(ecount[0]) - - self._task.periodicMeasure(OpenRTM_aist.toBool(mprop.getProperty("period_time"), - "enable", "disable", True)) - - pcount = [0] - if OpenRTM_aist.stringTo(pcount, mprop.getProperty("period_count")): - self._task.periodicMeasureCount(pcount[0]) - - # Start task in suspended mode - self._task.suspend() - self._task.activate() - self._task.suspend() - - return self.PORT_OK - - ## - # @if jp - # @brief - # - # Υ饹Υ֥ȤѤΤΩɬδؿƤ - # Фɬפ롣ˤϡΥ֥ȤγƼޤ - # Properties Ϳ롣ʤȤ⡢нθƤӽФñ - # Hz οͤȤ Property֥Ȥ publisher.push_rate 򥭡 - # ȤǤꤹɬפ롣 5ms ʤ200Hzξ硢 - # 200.0 ꤹ롣 dataport.publisher.push_rate ̤ξ硢 - # false ֤롣ǡץå夹ݤΥݥꥷȤ - # publisher.push_policy 򥭡Ȥͤˡall, fifo, skip, new - # 줫Ϳ뤳ȤǤ롣 - # - # ʲΥץͿ뤳ȤǤ롣 - # - # - publisher.thread_type: åɤΥ (ʸ󡢥ǥե: default) - # - publisher.push_rate: Publisher () - # - publisher.push_policy: Pushݥꥷ (all, fifo, skip, new) - # - publisher.skip_count: 嵭ݥꥷ skip ΤȤΥå׿ - # - measurement.exec_time: ¹Իַ¬ (enable/disable) - # - measurement.exec_count: ؿ¹Իַ¬ (, ) - # - measurement.period_time: ַ¬ (enable/disable) - # - measurement.period_count: ַ¬ (, ) - # - # @param property PublisherζưꤷProperty֥ - # @return ReturnCode PORT_OK ェλ - # INVALID_ARGS Properties ͤޤ - # - # @else - # @brief Initialization - # - # This function have to be called before using this class object. - # Properties object that includes certain configuration - # information should be given as an argument. At least, a - # numerical value of unit of Hz with the key of - # "dataport.publisher.push_rate" has to be set to the Properties - # object of argument. The value is the invocation cycle of data - # sending process. In case of 5 ms period or 200 Hz, the value - # should be set as 200.0. False will be returned, if there is no - # value with the key of "dataport.publisher.push_rate". - # - # The following options are available. - # - # - publisher.thread_type: Thread type (string, default: default) - # - publisher.push_rate: Publisher sending period (numberical) - # - publisher.push_policy: Push policy (all, fifo, skip, new) - # - publisher.skip_count: The number of skip count in the "skip" policy - # - measurement.exec_time: Task execution time measurement (enable/disable) - # - measurement.exec_count: Task execution time measurement count - # (numerical, number of times) - # - measurement.period_time: Task period time measurement (enable/disable) - # - measurement.period_count: Task period time measurement count - # (number, count) - # - # @param property Property objects that includes the control information - # of this Publisher - # @return ReturnCode PORT_OK normal return - # INVALID_ARGS Properties with invalid values. - # @endif - # - # PublisherBase::ReturnCode PublisherPeriodic::init(coil::Properties& prop) - def init(self, prop): - self._rtcout.RTC_TRACE("init()") - self.setPushPolicy(prop) - return self.createTask(prop) - - ## - # @if jp - # @brief InPort󥷥塼ޤΥå - # - # δؿǤϡ Publisher ˴Ϣդ륳󥷥塼ޤ򥻥åȤ롣 - # 󥷥塼ޥ֥Ȥ̥ݥ󥿤ξ硢INVALID_ARGS֤롣 - # ʳξϡPORT_OK ֤롣 - # - # @param consumer Consumer ؤΥݥ - # @return ReturnCode PORT_OK ェλ - # INVALID_ARGS ͤޤޤƤ - # - # @else - # @brief Store InPort consumer - # - # This operation sets a consumer that is associated with this - # object. If the consumer object is NULL, INVALID_ARGS will be - # returned. - # - # @param consumer A pointer to a consumer object. - # @return ReturnCode PORT_OK normal return - # INVALID_ARGS given argument has invalid value - # - # @endif - # - # PublisherBase::ReturnCode - # PublisherPeriodic::setConsumer(InPortConsumer* consumer) - def setConsumer(self, consumer): - self._rtcout.RTC_TRACE("setConsumer()") - - if not consumer: - self._rtcout.RTC_ERROR("setConsumer(consumer = 0): invalid argument.") - return self.INVALID_ARGS - - self._consumer = consumer - return self.PORT_OK - - ## - # @if jp - # @brief ХåեΥå - # - # δؿǤϡ Publisher ˴ϢդХåե򥻥åȤ롣 - # Хåե֥Ȥ̥ݥ󥿤ξ硢INVALID_ARGS֤롣 - # ʳξϡPORT_OK ֤롣 - # - # @param buffer CDR buffer ؤΥݥ - # @return ReturnCode PORT_OK ェλ - # INVALID_ARGS ͤޤޤƤ - # - # @else - # @brief Setting buffer pointer - # - # This operation sets a buffer that is associated with this - # object. If the buffer object is NULL, INVALID_ARGS will be - # returned. - # - # @param buffer A pointer to a CDR buffer object. - # @return ReturnCode PORT_OK normal return - # INVALID_ARGS given argument has invalid value - # - # @endif - # - # PublisherBase::ReturnCode PublisherPeriodic::setBuffer(CdrBufferBase* buffer) - def setBuffer(self, buffer): - self._rtcout.RTC_TRACE("setBuffer()") - - if not buffer: - self._rtcout.RTC_ERROR("setBuffer(buffer == 0): invalid argument") - return self.INVALID_ARGS - - self._buffer = buffer - return self.PORT_OK - - ## - # @if jp - # @brief ꥹʤꤹ롣 - # - # Publisher Фƥꥹʥ֥ ConnectorListeners ꤹ롣 - # Ƽꥹʥ֥Ȥޤ ConnectorListeners 򥻥åȤ뤳Ȥǡ - # Хåեɤ߽񤭡ǡˤΥꥹʤ򥳡뤹롣 - # ConnectorListeners ֥ȤνͭϥݡȤޤ RTObject - # Publisher ConnectorListeners Ϻ뤳ȤϤʤ - # ConnectorListeners ̥ݥ󥿤ξ INVALID_ARGS ֤ - # - # @param info ConnectorProfile 벽֥ ConnectorInfo - # @param listeners ꥹʤ¿ݻ ConnectorListeners ֥ - # @return PORT_OK ェλ - # INVALID_ARGS ʰ - # @else - # @brief Set the listener. - # - # This function sets ConnectorListeners listener object to the - # Publisher. By setting ConnectorListeners containing various - # listeners objects, these listeners are called at the time of - # reading and writing of a buffer, and transmission of data - # etc. Since the ownership of the ConnectorListeners object is - # owned by Port or RTObject, the Publisher never deletes the - # ConnectorListeners object. If the given ConnectorListeners' - # pointer is NULL, this function returns INVALID_ARGS. - # - # @param info ConnectorInfo that is localized object of ConnectorProfile - # @param listeners ConnectorListeners that holds various listeners - # @return PORT_OK Normal return - # INVALID_ARGS Invalid arguments - # @endif - # - #PublisherBase::ReturnCode - #PublisherPeriodic::setListener(ConnectorInfo& info, - # ConnectorListeners* listeners) - def setListener(self, info, listeners): - self._rtcout.RTC_TRACE("setListeners()") - - if not listeners: - self._rtcout.RTC_ERROR("setListeners(listeners == 0): invalid argument") - return self.INVALID_ARGS - - self._profile = info - self._listeners = listeners - return self.PORT_OK - - ## - # @if jp - # @brief ǡ񤭹 - # - # Publisher ݻХåեФƥǡ񤭹ࡣ󥷥塼 - # ޡХåեꥹŬڤꤵƤʤPublisher - # ȤƤʤ硢δؿƤӽФȥ顼 - # PRECONDITION_NOT_MET ֤졢Хåեؤν񤭹 - # ϰڹԤʤ - # - # Хåեؤν񤭹ߤȡInPortؤΥǡƱŪ˹Ԥ - # 뤿ᡢδؿϡInPortؤΥǡη̤򼨤 - # CONNECTION_LOST, BUFFER_FULL ʤɤΥ꥿󥳡ɤ֤Ȥ - # 롣ξ硢ǡΥХåեؤν񤭹ߤϹԤʤ - # - # Хåեؤν񤭹ߤФơХåեե֡ХåեΥ - # 顼Хåեؤν񤭹ߤॢȤ硢Хåեλ - # 郎ʤˤϤ줾졢顼 BUFFER_FULL, - # BUFFER_ERROR, BUFFER_TIMEOUT, PRECONDITION_NOT_MET ֤롣 - # - # ʳΥ顼ξ硢PORT_ERROR ֤롣 - # - # - # @param data 񤭹ǡ - # @param sec ॢȻ - # @param nsec ॢȻ - # - # @return PORT_OK ェλ - # PRECONDITION_NO_MET consumer, buffer, listenerŬڤ - # ƤʤΥ֥Ȥλ - # ʤ硣 - # CONNECTION_LOST ³Ǥ줿ȤΤ - # BUFFER_FULL Хåեե֤Ǥ롣 - # BUFFER_ERROR Хåե˲餫Υ顼硣 - # NOT_SUPPORTED ݡȤʤԤ줿 - # TIMEOUT ॢȤ - # - # @else - # @brief Write data - # - # This function writes data into the buffer associated with this - # Publisher. If a Publisher object calls this function, without - # initializing correctly such as a consumer, a buffer, listeners, - # etc., error code PRECONDITION_NOT_MET will be returned and no - # operation of the writing to a buffer etc. will be performed. - # - # Since writing into the buffer and sending data to InPort are - # performed asynchronously, occasionally this function returns - # return-codes such as CONNECTION_LOST and BUFFER_FULL that - # indicate the result of sending data to InPort. In this case, - # writing data into buffer will not be performed. - # - # When publisher writes data to the buffer, if the buffer is - # filled, returns error, is returned with timeout and returns - # precondition error, error codes BUFFER_FULL, BUFFER_ERROR, - # BUFFER_TIMEOUT and PRECONDITION_NOT_MET will be returned - # respectively. - # - # In other cases, PROT_ERROR will be returned. - # - # @param data Data to be wrote to the buffer - # @param sec Timeout time in unit seconds - # @param nsec Timeout time in unit nano-seconds - # @return PORT_OK Normal return - # PRECONDITION_NO_MET Precondition does not met. A consumer, - # a buffer, listenes are not set properly. - # CONNECTION_LOST detected that the connection has been lost - # BUFFER_FULL The buffer is full status. - # BUFFER_ERROR Some kind of error occurred in the buffer. - # NOT_SUPPORTED Some kind of operation that is not supported - # has been performed. - # TIMEOUT Timeout occurred when writing to the buffer. - # - # @endif - # - # PublisherBase::ReturnCode - # PublisherPeriodic::write(const cdrMemoryStream& data, - # unsigned long sec, - # unsigned long usec) - def write(self, data, sec, usec): - self._rtcout.RTC_PARANOID("write()") - - if not self._consumer or not self._buffer or not self._listeners: - return self.PRECONDITION_NOT_MET - - if self._retcode == self.CONNECTION_LOST: - self._rtcout.RTC_DEBUG("write(): connection lost.") - return self._retcode - - if self._retcode == self.SEND_FULL: - self._rtcout.RTC_DEBUG("write(): InPort buffer is full.") - self._buffer.write(data,sec,usec) - return self.BUFFER_FULL - - self.onBufferWrite(data) - ret = self._buffer.write(data, sec, usec) - self._rtcout.RTC_DEBUG("%s = write()", OpenRTM_aist.DataPortStatus.toString(ret)) - self._task.resume() - return self.convertReturn(ret, data) - - ## - # @if jp - # - # @brief ƥֲǧ - # - # Publisher ϥǡݡȤƱ activate/deactivate 롣 - # activate() / deactivate() ؿˤäơƥ־֤󥢥ƥ - # ־֤ڤؤ롣δؿˤꡢߥƥ־֤󥢥 - # ƥ־֤ǧ뤳ȤǤ롣 - # - # @return ֳǧ(ƥ־:true󥢥ƥ־:false) - # - # @else - # - # @brief If publisher is active state - # - # A Publisher can be activated/deactivated synchronized with the - # data port. The active state and the non-active state are made - # transition by the "activate()" and the "deactivate()" functions - # respectively. This function confirms if the publisher is in - # active state. - # - # @return Result of state confirmation - # (Active state:true, Inactive state:false) - # - # @endif - # - # bool PublisherPeriodic::isActive() - def isActive(self): - return self._active - - ## - # @if jp - # @brief ƥֲ - # - # Publisher 򥢥ƥֲ롣δؿƤӽФȤˤꡢ - # Publisherġǡ륹åɤư򳫻Ϥ롣 - # ԤƤʤʤɤˤꡢʤ硢顼 - # PRECONDITION_NOT_MET ֤ - # - # @return PORT_OK ェλ - # PRECONDITION_NOT_MET ʤ - # - # @else - # @brief activation - # - # This function activates the publisher. By calling this - # function, this publisher starts the thread that pushes data to - # InPort. If precondition such as initialization process and so - # on is not met, the error code PRECONDITION_NOT_MET is returned. - # - # @return PORT_OK normal return - # PRECONDITION_NOT_MET precondition is not met - # - # @endif - # - # PublisherBase::ReturnCode PublisherPeriodic::activate() - def activate(self): - if not self._task or not self._buffer: - return self.PRECONDITION_NOT_MET - self._active = True - self._task.resume() - return self.PORT_OK - - ## - # @if jp - # @brief 󥢥ƥֲ - # - # Publisher 󥢥ƥֲ롣δؿƤӽФȤˤꡢ - # Publisherġǡ륹åɤưߤ롣 - # ԤƤʤʤɤˤꡢʤ硢顼 - # PRECONDITION_NOT_MET ֤ - # - # @return PORT_OK ェλ - # PRECONDITION_NOT_MET ʤ - # - # @else - # @brief deactivation - # - # This function deactivates the publisher. By calling this - # function, this publisher stops the thread that pushes data to - # InPort. If precondition such as initialization process and so - # on is not met, the error code PRECONDITION_NOT_MET is returned. - # - # @return PORT_OK normal return - # PRECONDITION_NOT_MET precondition is not met - # - # @endif - # - # PublisherBase::ReturnCode PublisherPeriodic::deactivate() - def deactivate(self): - if not self._task: - return self.PRECONDITION_NOT_MET - self._active = False - self._task.suspend() - return self.PORT_OK - - ## - # @if jp - # @brief åɼ¹Դؿ - # @else - # @brief Thread execution function - # A task execution function to be executed by coil::PeriodicTask. - # @endif - # - # int PublisherPeriodic::svc(void) - def svc(self): - guard = OpenRTM_aist.ScopedLock(self._retmutex) - - if self._pushPolicy == self.PUBLISHER_POLICY_ALL: - self._retcode = self.pushAll() - return 0 - - elif self._pushPolicy == self.PUBLISHER_POLICY_FIFO: - self._retcode = self.pushFifo() - return 0 - - elif self._pushPolicy == self.PUBLISHER_POLICY_SKIP: - self._retcode = self.pushSkip() - return 0 - - elif self._pushPolicy == self.PUBLISHER_POLICY_NEW: - self._retcode = self.pushNew() - return 0 - - else: - self._retcode = self.pushNew() - - return 0 - - ## - # @brief push all policy - # - # PublisherBase::ReturnCode PublisherPeriodic::pushAll() - def pushAll(self): - self._rtcout.RTC_TRACE("pushAll()") - - if not self._buffer: - return self.PRECONDITION_NOT_MET - - if self.bufferIsEmpty(): - return self.BUFFER_EMPTY - - while self._buffer.readable() > 0: - cdr = self._buffer.get() - self.onBufferRead(cdr) - - self.onSend(cdr) - ret = self._consumer.put(cdr) - - if ret != self.PORT_OK: - self._rtcout.RTC_DEBUG("%s = consumer.put()", OpenRTM_aist.DataPortStatus.toString(ret)) - return self.invokeListener(ret, cdr) - - self.onReceived(cdr) - self._buffer.advanceRptr() - - return self.PORT_OK - - - ## - # @brief push "fifo" policy - # - # PublisherBase::ReturnCode PublisherPeriodic::pushFifo() - def pushFifo(self): - self._rtcout.RTC_TRACE("pushFifo()") - if not self._buffer: - return self.PRECONDITION_NOT_MET - - if self.bufferIsEmpty(): - return self.BUFFER_EMPTY - - cdr = self._buffer.get() - self.onBufferRead(cdr) - - self.onSend(cdr) - ret = self._consumer.put(cdr) - - if ret != self.PORT_OK: - self._rtcout.RTC_DEBUG("%s = consumer.put()",OpenRTM_aist.DataPortStatus.toString(ret)) - return self.invokeListener(ret, cdr) - - self.onReceived(cdr) - self._buffer.advanceRptr() - - return self.PORT_OK - - - ## - # @brief push "skip" policy - # - # PublisherBase::ReturnCode PublisherPeriodic::pushSkip() - def pushSkip(self): - self._rtcout.RTC_TRACE("pushSkip()") - if not self._buffer: - return self.PRECONDITION_NOT_MET - - if self.bufferIsEmpty(): - return self.BUFFER_EMPTY - - ret = self.PORT_OK - preskip = self._buffer.readable() + self._leftskip - loopcnt = preskip / (self._skipn + 1) - postskip = self._skipn - self._leftskip - for i in range(int(loopcnt)): - self._buffer.advanceRptr(postskip) - cdr = self._buffer.get() - self.onBufferRead(cdr) - - self.onSend(cdr) - ret = self._consumer.put(cdr) - if ret != self.PORT_OK: - self._buffer.advanceRptr(-postskip) - self._rtcout.RTC_DEBUG("%s = consumer.put()",OpenRTM_aist.DataPortStatus.toString(ret)) - return self.invokeListener(ret, cdr) - self.onReceived(cdr) - postskip = self._skipn + 1 - - self._buffer.advanceRptr(self._buffer.readable()) - self._leftskip = preskip % (self._skipn + 1) - - return ret - - - ## - # @brief push "new" policy - # - # PublisherBase::ReturnCode PublisherPeriodic::pushNew() - def pushNew(self): - self._rtcout.RTC_TRACE("pushNew()") - if not self._buffer: - return self.PRECONDITION_NOT_MET - - if self.bufferIsEmpty(): - return self.BUFFER_EMPTY - - # In case of the periodic/push_new policy, the buffer should - # allow readback. But, readback flag should be set as "true" - # after written at least one datum into the buffer. - self._readback = True - - self._buffer.advanceRptr(self._buffer.readable() - 1) - - cdr = self._buffer.get() - self.onBufferRead(cdr) - - self.onSend(cdr) - ret = self._consumer.put(cdr) - - if ret != self.PORT_OK: - self._rtcout.RTC_DEBUG("%s = consumer.put()", OpenRTM_aist.DataPortStatus.toString(ret)) - return self.invokeListener(ret, cdr) - - self.onReceived(cdr) - - self._buffer.advanceRptr() - return self.PORT_OK - - ## - # @if jp - # @brief BufferStatus DataPortStatus ؤѴ - # - # Хåեͤ DataPortStatus::Enum Ѵؿ - # 줾졢ʲΤ褦Ѵ롣Ѵ˥ХåƤ־硢 - # Хؿյ롣 - # - # - BUFFER_OK: PORT_OK - # - None - # - BUFFER_ERROR: BUFFER_ERROR - # - None - # - BUFFER_FULL: BUFFER_FULL - # - onBufferFull() - # - NOT_SUPPORTED: PORT_ERROR - # - None - # - TIMEOUT: BUFFER_TIMEOUT - # - onBufferWriteTimeout() - # - PRECONDITION_NOT_MET: PRECONDITION_NOT_MET - # - None - # - other: PORT_ERROR - # - None - # - # @param status BufferStatus - # @param data cdrMemoryStream - # @return DataPortStatu Υ꥿󥳡 - # - # @else - # @brief Convertion from BufferStatus to DataPortStatus - # - # This function converts return value from the buffer to - # DataPortStatus::Enum typed return value. The conversion rule is - # as follows. Callback functions are also shown, if it exists. - # - # - BUFFER_OK: PORT_OK - # - None - # - BUFFER_ERROR: BUFFER_ERROR - # - None - # - BUFFER_FULL: BUFFER_FULL - # - onBufferFull() - # - NOT_SUPPORTED: PORT_ERROR - # - None - # - TIMEOUT: BUFFER_TIMEOUT - # - onBufferWriteTimeout() - # - PRECONDITION_NOT_MET: PRECONDITION_NOT_MET - # - None - # - other: PORT_ERROR - # - None - # - # @param status BufferStatus - # @param data cdrMemoryStream - # @return DataPortStatus typed return code - # - # @endif - # - # PublisherBase::ReturnCodea - # PublisherPeriodic::convertReturn(BufferStatus::Enum status, - # const cdrMemoryStream& data) - def convertReturn(self, status, data): - if status == OpenRTM_aist.BufferStatus.BUFFER_OK: - return self.PORT_OK - - elif status == OpenRTM_aist.BufferStatus.BUFFER_ERROR: - return self.BUFFER_ERROR - - elif status == OpenRTM_aist.BufferStatus.BUFFER_FULL: - self.onBufferFull(data) - return self.BUFFER_FULL - - elif status == OpenRTM_aist.BufferStatus.NOT_SUPPORTED: - return self.PORT_ERROR - - elif status == OpenRTM_aist.BufferStatus.TIMEOUT: - self.onBufferWriteTimeout(data) - return self.BUFFER_TIMEOUT - - elif status == OpenRTM_aist.BufferStatus.PRECONDITION_NOT_MET: - return self.PRECONDITION_NOT_MET - - else: - return self.PORT_ERROR - - - - ## - # @if jp - # @brief DataPortStatus˽äƥꥹʤΤؿƤӽФ - # - # @param status DataPortStatus - # @param data cdrMemoryStream - # @return ꥿󥳡 - # - # @else - # @brief Call listeners according to the DataPortStatus - # - # @param status DataPortStatus - # @param data cdrMemoryStream - # @return Return code - # - # @endif - # - # PublisherPeriodic::ReturnCode - # PublisherPeriodic::invokeListener(DataPortStatus::Enum status, - # const cdrMemoryStream& data) - def invokeListener(self, status, data): - # ret: - # PORT_OK, PORT_ERROR, SEND_FULL, SEND_TIMEOUT, CONNECTION_LOST, - # UNKNOWN_ERROR - if status == self.PORT_ERROR: - self.onReceiverError(data) - return self.PORT_ERROR - - elif status == self.SEND_FULL: - self.onReceiverFull(data) - return self.SEND_FULL - - elif status == self.SEND_TIMEOUT: - self.onReceiverTimeout(data) - return self.SEND_TIMEOUT - - elif status == self.CONNECTION_LOST: - self.onReceiverError(data) - return self.CONNECTION_LOST - - elif status == self.UNKNOWN_ERROR: - self.onReceiverError(data) - return self.UNKNOWN_ERROR - - else: - self.onReceiverError(data) - return self.PORT_ERROR - - ## - # @if jp - # @brief ON_BUFFER_WRITEΥꥹʤΤ롣 - # @param data cdrMemoryStream - # @else - # @brief Notify an ON_BUFFER_WRITE event to listeners - # @param data cdrMemoryStream - # @endif - # - # inline void onBufferWrite(const cdrMemoryStream& data) - def onBufferWrite(self, data): - if self._listeners is not None and self._profile is not None: - self._listeners.connectorData_[OpenRTM_aist.ConnectorDataListenerType.ON_BUFFER_WRITE].notify(self._profile, data) - return - - ## - # @if jp - # @brief ON_BUFFER_FULLꥹʤإ٥ȤΤ롣 - # @param data cdrMemoryStream - # @else - # @brief Notify an ON_BUFFER_FULL event to listeners - # @param data cdrMemoryStream - # @endif - # - # inline void onBufferFull(const cdrMemoryStream& data) - def onBufferFull(self, data): - if self._listeners is not None and self._profile is not None: - self._listeners.connectorData_[OpenRTM_aist.ConnectorDataListenerType.ON_BUFFER_FULL].notify(self._profile, data) - return - - ## - # @if jp - # @brief ON_BUFFER_WRITE_TIMEOUTΥꥹʤΤ롣 - # @param data cdrMemoryStream - # @else - # @brief Notify an ON_BUFFER_WRITE_TIMEOUT event to listeners - # @param data cdrMemoryStream - # @endif - # - # inline void onBufferWriteTimeout(const cdrMemoryStream& data) - def onBufferWriteTimeout(self, data): - if self._listeners is not None and self._profile is not None: - self._listeners.connectorData_[OpenRTM_aist.ConnectorDataListenerType.ON_BUFFER_WRITE_TIMEOUT].notify(self._profile, data) - return - - ## - # @if jp - # @brief ON_BUFFER_READΥꥹʤΤ롣 - # @param data cdrMemoryStream - # @else - # @brief Notify an ON_BUFFER_READ event to listeners - # @param data cdrMemoryStream - # @endif - # - # inline void onBufferRead(const cdrMemoryStream& data) - def onBufferRead(self, data): - if self._listeners is not None and self._profile is not None: - self._listeners.connectorData_[OpenRTM_aist.ConnectorDataListenerType.ON_BUFFER_READ].notify(self._profile, data) - return - - ## - # @if jp - # @brief ON_SENDΥꥹʤΤ롣 - # @param data cdrMemoryStream - # @else - # @brief Notify an ON_SEND event to listners - # @param data cdrMemoryStream - # @endif - # - # inline void onSend(const cdrMemoryStream& data) - def onSend(self, data): - if self._listeners is not None and self._profile is not None: - self._listeners.connectorData_[OpenRTM_aist.ConnectorDataListenerType.ON_SEND].notify(self._profile, data) - return - - ## - # @if jp - # @brief ON_RECEIVEDΥꥹʤΤ롣 - # @param data cdrMemoryStream - # @else - # @brief Notify an ON_RECEIVED event to listeners - # @param data cdrMemoryStream - # @endif - # - # inline void onReceived(const cdrMemoryStream& data) - def onReceived(self, data): - if self._listeners is not None and self._profile is not None: - self._listeners.connectorData_[OpenRTM_aist.ConnectorDataListenerType.ON_RECEIVED].notify(self._profile, data) - return - - ## - # @if jp - # @brief ON_RECEIVER_FULLΥꥹʤΤ롣 - # @param data cdrMemoryStream - # @else - # @brief Notify an ON_RECEIVER_FULL event to listeners - # @param data cdrMemoryStream - # @endif - # - # inline void onReceiverFull(const cdrMemoryStream& data) - def onReceiverFull(self, data): - if self._listeners is not None and self._profile is not None: - self._listeners.connectorData_[OpenRTM_aist.ConnectorDataListenerType.ON_RECEIVER_FULL].notify(self._profile, data) - return - - ## - # @if jp - # @brief ON_RECEIVER_TIMEOUTΥꥹʤΤ롣 - # @param data cdrMemoryStream - # @else - # @brief Notify an ON_RECEIVER_TIMEOUT event to listeners - # @param data cdrMemoryStream - # @endif - # - # inline void onReceiverTimeout(const cdrMemoryStream& data) - def onReceiverTimeout(self, data): - if self._listeners is not None and self._profile is not None: - self._listeners.connectorData_[OpenRTM_aist.ConnectorDataListenerType.ON_RECEIVER_TIMEOUT].notify(self._profile, data) - return - - ## - # @if jp - # @brief ON_RECEIVER_ERRORΥꥹʤΤ롣 - # @param data cdrMemoryStream - # @else - # @brief Notify an ON_RECEIVER_ERROR event to listeners - # @param data cdrMemoryStream - # @endif - # - # inline void onReceiverError(const cdrMemoryStream& data) - def onReceiverError(self, data): - if self._listeners is not None and self._profile is not None: - self._listeners.connectorData_[OpenRTM_aist.ConnectorDataListenerType.ON_RECEIVER_ERROR].notify(self._profile, data) - return - - - ## - # @if jp - # @brief ON_BUFFER_EMPTYΥꥹʤΤ롣 - # @else - # @brief Notify an ON_BUFFER_EMPTY event to listeners - # @endif - # - #inline void onBufferEmpty() - def onBufferEmpty(self): - if self._listeners is not None and self._profile is not None: - self._listeners.connector_[OpenRTM_aist.ConnectorListenerType.ON_BUFFER_EMPTY].notify(self._profile) - return - - ## - # @if jp - # @brief ON_SENDER_EMPTYΥꥹʤΤ롣 - # @else - # @brief Notify an ON_SENDER_EMPTY event to listeners - # @endif - # - # inline void onSenderEmpty() - def onSenderEmpty(self): - if self._listeners is not None and self._profile is not None: - self._listeners.connector_[OpenRTM_aist.ConnectorListenerType.ON_SENDER_EMPTY].notify(self._profile) - return - - ## - # @if jp - # @brief ON_SENDER_ERRORΥꥹʤΤ롣 - # @else - # @brief Notify an ON_SENDER_ERROR event to listeners - # @endif - # - # inline void onSenderError() - def onSenderError(self): - if self._listeners is not None and self._profile is not None: - self._listeners.connector_[OpenRTM_aist.ConnectorListenerType.ON_SENDER_ERROR].notify(self._profile) - return - - - ## - # @if jp - # @brief Хåեɤå롣x - # @else - # @brief Whether a buffer is empty. - # @endif - # - # bool bufferIsEmpty() - def bufferIsEmpty(self): - if self._buffer and self._buffer.empty() and not self._readback: - self._rtcout.RTC_DEBUG("buffer empty") - self.onBufferEmpty() - self.onSenderEmpty() - return True - - return False - + """ + """ + + # Policy + PUBLISHER_POLICY_ALL = 0 + PUBLISHER_POLICY_FIFO = 1 + PUBLISHER_POLICY_SKIP = 2 + PUBLISHER_POLICY_NEW = 3 + + ## + # @if jp + # @brief コンストラクタ + # + # コンストラクタ + # 送出処理の呼び出し間隔を、Propertyオブジェクトのdataport.push_rateメンバ + # に設定しておく必要がある。送出間隔は、Hz単位の浮動小数文字列で指定。 + # たとえば、1000.0Hzの場合は、「1000.0」を設定。 + # 上記プロパティが未設定の場合は、「1000Hz」を設定。 + # + # @param self + # @param consumer データ送出を待つコンシューマ + # @param property 本Publisherの駆動制御情報を設定したPropertyオブジェクト + # + # @else + # @brief Constructor + # @endif + def __init__(self): + self._rtcout = OpenRTM_aist.Manager.instance().getLogbuf("PublisherPeriodic") + self._consumer = None + self._buffer = None + self._task = None + self._retcode = self.PORT_OK + self._retmutex = threading.RLock() + self._pushPolicy = self.PUBLISHER_POLICY_NEW + self._skipn = 0 + self._active = False + self._readback = False + self._leftskip = 0 + self._profile = None + self._listeners = None + + return + + ## + # @if jp + # @brief デストラクタ + # + # デストラクタ + # + # @param self + # + # @else + # @brief Destructor + # @endif + def __del__(self): + self._rtcout.RTC_TRACE("~PublisherPeriodic()") + + ## + # @if jp + # @brief 終了処理 + # + # @param self + # + # @else + # @brief + # @endif + def exit(self): + self._rtcout.RTC_TRACE("exit()") + if self._task: + self._task.resume() + self._task.finalize() + self._rtcout.RTC_PARANOID("task finalized.") + + self._rtcout.RTC_PARANOID("task deleted.") + + # "consumer" should be deleted in the Connector + self._consumer = None + # "buffer" should be deleted in the Connector + self._buffer = None + return + + ## + # @if jp + # @brief PushPolicy の設定 + # @else + # @brief Setting PushPolicy + # @endif + # + # void PublisherNew::setPushPolicy(const coil::Properties& prop) + def setPushPolicy(self, prop): + push_policy = prop.getProperty("publisher.push_policy", "new") + self._rtcout.RTC_DEBUG("push_policy: %s", push_policy) + + push_policy = OpenRTM_aist.normalize(push_policy) + + if push_policy == "all": + self._pushPolicy = self.PUBLISHER_POLICY_ALL + + elif push_policy == "fifo": + self._pushPolicy = self.PUBLISHER_POLICY_FIFO + + elif push_policy == "skip": + self._pushPolicy = self.PUBLISHER_POLICY_SKIP + + elif push_policy == "new": + self._pushPolicy = self.PUBLISHER_POLICY_NEW + + else: + self._rtcout.RTC_ERROR( + "invalid push_policy value: %s", push_policy) + self._pushPolicy = self.PUBLISHER_POLICY_NEW + + skip_count = prop.getProperty("publisher.skip_count", "0") + self._rtcout.RTC_DEBUG("skip_count: %s", skip_count) + + skipn = self._skipn + ret, skipn = OpenRTM_aist.stringTo(skipn, skip_count) + if ret: + self._skipn = skipn + else: + self._rtcout.RTC_ERROR("invalid skip_count value: %s", skip_count) + self._skipn = 0 + + if self._skipn < 0: + self._rtcout.RTC_ERROR("invalid skip_count value: %d", self._skipn) + self._skipn = 0 + + return + + ## + # @if jp + # @brief Task の設定 + # @else + # @brief Setting Task + # @endif + # + # bool PublisherNew::createTask(const coil::Properties& prop) + def createTask(self, prop): + factory = OpenRTM_aist.PeriodicTaskFactory.instance() + + th = factory.getIdentifiers() + self._rtcout.RTC_DEBUG( + "available task types: %s", + OpenRTM_aist.flatten(th)) + + self._task = factory.createObject( + prop.getProperty("thread_type", "default")) + if not self._task: + self._rtcout.RTC_ERROR("Task creation failed: %s", + prop.getProperty("thread_type", "default")) + return self.INVALID_ARGS + + self._rtcout.RTC_PARANOID("Task creation succeeded.") + + # setting task function + self._task.setTask(self.svc) + + # Task execution rate + rate = prop.getProperty("publisher.push_rate") + + if rate != "": + hz = float(rate) + if hz == 0: + hz = 1000.0 + self._rtcout.RTC_DEBUG("Task period %f [Hz]", hz) + else: + hz = 1000.0 + + self._task.setPeriod(1.0 / hz) + + # Measurement setting + mprop = prop.getNode("measurement") + + self._task.executionMeasure(OpenRTM_aist.toBool(mprop.getProperty("exec_time"), + "enable", "disable", True)) + + ecount = 0 + ret, ecount = OpenRTM_aist.stringTo( + ecount, mprop.getProperty("exec_count")) + if ret: + self._task.executionMeasureCount(ecount) + + self._task.periodicMeasure(OpenRTM_aist.toBool(mprop.getProperty("period_time"), + "enable", "disable", True)) + + pcount = 0 + ret, ecount = OpenRTM_aist.stringTo( + pcount, mprop.getProperty("period_count")) + if ret: + self._task.periodicMeasureCount(pcount) + + # Start task in suspended mode + self._task.suspend() + self._task.activate() + self._task.suspend() + + return self.PORT_OK + + ## + # @if jp + # @brief 初期化 + # + # このクラスのオブジェクトを使用するのに先立ち、必ずこの関数を呼び + # 出す必要がある。引数には、このオブジェクトの各種設定情報を含む + # Properties を与える。少なくとも、送出処理の呼び出し周期を単位 + # Hz の数値として Propertyオブジェクトの publisher.push_rate をキー + # とする要素に設定する必要がある。周期 5ms すなわち、200Hzの場合、 + # 200.0 を設定する。 dataport.publisher.push_rate が未設定の場合、 + # false が返される。データをプッシュする際のポリシーとして + # publisher.push_policy をキーとする値に、all, fifo, skip, new の + # いずれかを与えることができる。 + # + # 以下のオプションを与えることができる。 + # + # - publisher.thread_type: スレッドのタイプ (文字列、デフォルト: default) + # - publisher.push_rate: Publisherの送信周期 (数値) + # - publisher.push_policy: Pushポリシー (all, fifo, skip, new) + # - publisher.skip_count: 上記ポリシが skip のときのスキップ数 + # - measurement.exec_time: タスク実行時間計測 (enable/disable) + # - measurement.exec_count: タスク関数実行時間計測周期 (数値, 回数) + # - measurement.period_time: タスク周期時間計測 (enable/disable) + # - measurement.period_count: タスク周期時間計測周期 (数値, 回数) + # + # @param property 本Publisherの駆動制御情報を設定したPropertyオブジェクト + # @return ReturnCode PORT_OK 正常終了 + # INVALID_ARGS Properties が不正な値を含む + # + # @else + # @brief Initialization + # + # This function have to be called before using this class object. + # Properties object that includes certain configuration + # information should be given as an argument. At least, a + # numerical value of unit of Hz with the key of + # "dataport.publisher.push_rate" has to be set to the Properties + # object of argument. The value is the invocation cycle of data + # sending process. In case of 5 ms period or 200 Hz, the value + # should be set as 200.0. False will be returned, if there is no + # value with the key of "dataport.publisher.push_rate". + # + # The following options are available. + # + # - publisher.thread_type: Thread type (string, default: default) + # - publisher.push_rate: Publisher sending period (numberical) + # - publisher.push_policy: Push policy (all, fifo, skip, new) + # - publisher.skip_count: The number of skip count in the "skip" policy + # - measurement.exec_time: Task execution time measurement (enable/disable) + # - measurement.exec_count: Task execution time measurement count + # (numerical, number of times) + # - measurement.period_time: Task period time measurement (enable/disable) + # - measurement.period_count: Task period time measurement count + # (number, count) + # + # @param property Property objects that includes the control information + # of this Publisher + # @return ReturnCode PORT_OK normal return + # INVALID_ARGS Properties with invalid values. + # @endif + # + # PublisherBase::ReturnCode PublisherPeriodic::init(coil::Properties& prop) + def init(self, prop): + self._rtcout.RTC_TRACE("init()") + self.setPushPolicy(prop) + return self.createTask(prop) + + ## + # @if jp + # @brief InPortコンシューマのセット + # + # この関数では、この Publisher に関連付けられるコンシューマをセットする。 + # コンシューマオブジェクトがヌルポインタの場合、INVALID_ARGSが返される。 + # それ以外の場合は、PORT_OK が返される。 + # + # @param consumer Consumer へのポインタ + # @return ReturnCode PORT_OK 正常終了 + # INVALID_ARGS 引数に不正な値が含まれている + # + # @else + # @brief Store InPort consumer + # + # This operation sets a consumer that is associated with this + # object. If the consumer object is NULL, INVALID_ARGS will be + # returned. + # + # @param consumer A pointer to a consumer object. + # @return ReturnCode PORT_OK normal return + # INVALID_ARGS given argument has invalid value + # + # @endif + # + # PublisherBase::ReturnCode + # PublisherPeriodic::setConsumer(InPortConsumer* consumer) + def setConsumer(self, consumer): + self._rtcout.RTC_TRACE("setConsumer()") + + if not consumer: + self._rtcout.RTC_ERROR( + "setConsumer(consumer = None): invalid argument.") + return self.INVALID_ARGS + + self._consumer = consumer + return self.PORT_OK + + ## + # @if jp + # @brief バッファのセット + # + # この関数では、この Publisher に関連付けられるバッファをセットする。 + # バッファオブジェクトがヌルポインタの場合、INVALID_ARGSが返される。 + # それ以外の場合は、PORT_OK が返される。 + # + # @param buffer CDR buffer へのポインタ + # @return ReturnCode PORT_OK 正常終了 + # INVALID_ARGS 引数に不正な値が含まれている + # + # @else + # @brief Setting buffer pointer + # + # This operation sets a buffer that is associated with this + # object. If the buffer object is NULL, INVALID_ARGS will be + # returned. + # + # @param buffer A pointer to a CDR buffer object. + # @return ReturnCode PORT_OK normal return + # INVALID_ARGS given argument has invalid value + # + # @endif + # + # PublisherBase::ReturnCode PublisherPeriodic::setBuffer(CdrBufferBase* + # buffer) + def setBuffer(self, buffer): + self._rtcout.RTC_TRACE("setBuffer()") + + if not buffer: + self._rtcout.RTC_ERROR("setBuffer(buffer == None): invalid argument") + return self.INVALID_ARGS + + self._buffer = buffer + return self.PORT_OK + + ## + # @if jp + # @brief リスナを設定する。 + # + # Publisher に対してリスナオブジェクト ConnectorListeners を設定する。 + # 各種リスナオブジェクトを含む ConnectorListeners をセットすることで、 + # バッファの読み書き、データの送信時等にこれらのリスナをコールする。 + # ConnectorListeners オブジェクトの所有権はポートまたは RTObject が持ち + # Publisher 削除時に ConnectorListeners は削除されることはない。 + # ConnectorListeners がヌルポインタの場合 INVALID_ARGS を返す。 + # + # @param info ConnectorProfile をローカル化したオブジェクト ConnectorInfo + # @param listeners リスナを多数保持する ConnectorListeners オブジェクト + # @return PORT_OK 正常終了 + # INVALID_ARGS 不正な引数 + # @else + # @brief Set the listener. + # + # This function sets ConnectorListeners listener object to the + # Publisher. By setting ConnectorListeners containing various + # listeners objects, these listeners are called at the time of + # reading and writing of a buffer, and transmission of data + # etc. Since the ownership of the ConnectorListeners object is + # owned by Port or RTObject, the Publisher never deletes the + # ConnectorListeners object. If the given ConnectorListeners' + # pointer is NULL, this function returns INVALID_ARGS. + # + # @param info ConnectorInfo that is localized object of ConnectorProfile + # @param listeners ConnectorListeners that holds various listeners + # @return PORT_OK Normal return + # INVALID_ARGS Invalid arguments + # @endif + # + # PublisherBase::ReturnCode + # PublisherPeriodic::setListener(ConnectorInfo& info, + # ConnectorListeners* listeners) + def setListener(self, info, listeners): + self._rtcout.RTC_TRACE("setListeners()") + + if not listeners: + self._rtcout.RTC_ERROR( + "setListeners(listeners == None): invalid argument") + return self.INVALID_ARGS + + self._profile = info + self._listeners = listeners + return self.PORT_OK + + ## + # @if jp + # @brief データを書き込む + # + # Publisher が保持するバッファに対してデータを書き込む。コンシュー + # マ、バッファ、リスナ等が適切に設定されていない等、Publisher オブ + # ジェクトが正しく初期化されていない場合、この関数を呼び出すとエラー + # コード PRECONDITION_NOT_MET が返され、バッファへの書き込み等の操 + # 作は一切行われない。 + # + # バッファへの書き込みと、InPortへのデータの送信は非同期的に行われ + # るため、この関数は、InPortへのデータ送信の結果を示す、 + # CONNECTION_LOST, BUFFER_FULL などのリターンコードを返すことがあ + # る。この場合、データのバッファへの書き込みは行われない。 + # + # バッファへの書き込みに対して、バッファがフル状態、バッファのエ + # ラー、バッファへの書き込みがタイムアウトした場合、バッファの事前 + # 条件が満たされない場合にはそれぞれ、エラーコード BUFFER_FULL, + # BUFFER_ERROR, BUFFER_TIMEOUT, PRECONDITION_NOT_MET が返される。 + # + # これら以外のエラーの場合、PORT_ERROR が返される。 + # + # + # @param data 書き込むデータ + # @param sec タイムアウト時間 + # @param nsec タイムアウト時間 + # + # @return PORT_OK 正常終了 + # PRECONDITION_NO_MET consumer, buffer, listener等が適切に設定 + # されていない等、このオブジェクトの事前条件 + # を満たさない場合。 + # CONNECTION_LOST 接続が切断されたことを検知した。 + # BUFFER_FULL バッファがフル状態である。 + # BUFFER_ERROR バッファに何らかのエラーが生じた場合。 + # NOT_SUPPORTED サポートされない操作が行われた。 + # TIMEOUT タイムアウトした。 + # + # @else + # @brief Write data + # + # This function writes data into the buffer associated with this + # Publisher. If a Publisher object calls this function, without + # initializing correctly such as a consumer, a buffer, listeners, + # etc., error code PRECONDITION_NOT_MET will be returned and no + # operation of the writing to a buffer etc. will be performed. + # + # Since writing into the buffer and sending data to InPort are + # performed asynchronously, occasionally this function returns + # return-codes such as CONNECTION_LOST and BUFFER_FULL that + # indicate the result of sending data to InPort. In this case, + # writing data into buffer will not be performed. + # + # When publisher writes data to the buffer, if the buffer is + # filled, returns error, is returned with timeout and returns + # precondition error, error codes BUFFER_FULL, BUFFER_ERROR, + # BUFFER_TIMEOUT and PRECONDITION_NOT_MET will be returned + # respectively. + # + # In other cases, PROT_ERROR will be returned. + # + # @param data Data to be wrote to the buffer + # @param sec Timeout time in unit seconds + # @param nsec Timeout time in unit nano-seconds + # @return PORT_OK Normal return + # PRECONDITION_NO_MET Precondition does not met. A consumer, + # a buffer, listenes are not set properly. + # CONNECTION_LOST detected that the connection has been lost + # BUFFER_FULL The buffer is full status. + # BUFFER_ERROR Some kind of error occurred in the buffer. + # NOT_SUPPORTED Some kind of operation that is not supported + # has been performed. + # TIMEOUT Timeout occurred when writing to the buffer. + # + # @endif + # + # PublisherBase::ReturnCode + # PublisherPeriodic::write(const cdrMemoryStream& data, + # unsigned long sec, + # unsigned long usec) + def write(self, data, sec, usec): + self._rtcout.RTC_PARANOID("write()") + + if not self._consumer or not self._buffer or not self._listeners: + return self.PRECONDITION_NOT_MET + + if self._retcode == self.CONNECTION_LOST: + self._rtcout.RTC_DEBUG("write(): connection lost.") + return self._retcode + + if self._retcode == self.SEND_FULL: + self._rtcout.RTC_DEBUG("write(): InPort buffer is full.") + self._buffer.write(data, sec, usec) + return self.BUFFER_FULL + + self.onBufferWrite(data) + ret = self._buffer.write(data, sec, usec) + self._rtcout.RTC_DEBUG("%s = write()", + OpenRTM_aist.DataPortStatus.toString(ret)) + self._task.resume() + return self.convertReturn(ret, data) + + ## + # @if jp + # + # @brief アクティブ化確認 + # + # Publisher はデータポートと同期して activate/deactivate される。 + # activate() / deactivate() 関数によって、アクティブ状態と非アクティ + # ブ状態が切り替わる。この関数により、現在アクティブ状態か、非アク + # ティブ状態かを確認することができる。 + # + # @return 状態確認結果(アクティブ状態:true、非アクティブ状態:false) + # + # @else + # + # @brief If publisher is active state + # + # A Publisher can be activated/deactivated synchronized with the + # data port. The active state and the non-active state are made + # transition by the "activate()" and the "deactivate()" functions + # respectively. This function confirms if the publisher is in + # active state. + # + # @return Result of state confirmation + # (Active state:true, Inactive state:false) + # + # @endif + # + # bool PublisherPeriodic::isActive() + def isActive(self): + return self._active + + ## + # @if jp + # @brief アクティブ化する + # + # Publisher をアクティブ化する。この関数を呼び出すことにより、 + # Publisherが持つ、データを送信するスレッドが動作を開始する。初期 + # 化が行われていないなどにより、事前条件を満たさない場合、エラーコー + # ド PRECONDITION_NOT_MET を返す。 + # + # @return PORT_OK 正常終了 + # PRECONDITION_NOT_MET 事前条件を満たさない + # + # @else + # @brief activation + # + # This function activates the publisher. By calling this + # function, this publisher starts the thread that pushes data to + # InPort. If precondition such as initialization process and so + # on is not met, the error code PRECONDITION_NOT_MET is returned. + # + # @return PORT_OK normal return + # PRECONDITION_NOT_MET precondition is not met + # + # @endif + # + # PublisherBase::ReturnCode PublisherPeriodic::activate() + def activate(self): + if not self._task or not self._buffer: + return self.PRECONDITION_NOT_MET + self._active = True + self._task.resume() + return self.PORT_OK + + ## + # @if jp + # @brief 非アクティブ化する + # + # Publisher を非アクティブ化する。この関数を呼び出すことにより、 + # Publisherが持つ、データを送信するスレッドが動作を停止する。初期 + # 化が行われていないなどにより、事前条件を満たさない場合、エラーコー + # ド PRECONDITION_NOT_MET を返す。 + # + # @return PORT_OK 正常終了 + # PRECONDITION_NOT_MET 事前条件を満たさない + # + # @else + # @brief deactivation + # + # This function deactivates the publisher. By calling this + # function, this publisher stops the thread that pushes data to + # InPort. If precondition such as initialization process and so + # on is not met, the error code PRECONDITION_NOT_MET is returned. + # + # @return PORT_OK normal return + # PRECONDITION_NOT_MET precondition is not met + # + # @endif + # + # PublisherBase::ReturnCode PublisherPeriodic::deactivate() + def deactivate(self): + if not self._task: + return self.PRECONDITION_NOT_MET + self._active = False + self._task.suspend() + return self.PORT_OK + + ## + # @if jp + # @brief スレッド実行関数 + # @else + # @brief Thread execution function + # A task execution function to be executed by coil::PeriodicTask. + # @endif + # + # int PublisherPeriodic::svc(void) + def svc(self): + guard = OpenRTM_aist.ScopedLock(self._retmutex) + + if self._pushPolicy == self.PUBLISHER_POLICY_ALL: + self._retcode = self.pushAll() + return 0 + + elif self._pushPolicy == self.PUBLISHER_POLICY_FIFO: + self._retcode = self.pushFifo() + return 0 + + elif self._pushPolicy == self.PUBLISHER_POLICY_SKIP: + self._retcode = self.pushSkip() + return 0 + + elif self._pushPolicy == self.PUBLISHER_POLICY_NEW: + self._retcode = self.pushNew() + return 0 + + else: + self._retcode = self.pushNew() + + return 0 + + ## + # @brief push all policy + # + # PublisherBase::ReturnCode PublisherPeriodic::pushAll() + def pushAll(self): + self._rtcout.RTC_TRACE("pushAll()") + + if not self._buffer: + return self.PRECONDITION_NOT_MET + + if self.bufferIsEmpty(): + return self.BUFFER_EMPTY + + while self._buffer.readable() > 0: + _, cdr = self._buffer.get() + self.onBufferRead(cdr) + + cdr = self.onSend(cdr) + ret = self._consumer.put(cdr) + + if ret != self.PORT_OK: + self._rtcout.RTC_DEBUG( + "%s = consumer.put()", + OpenRTM_aist.DataPortStatus.toString(ret)) + return self.invokeListener(ret, cdr) + + cdr = self.onReceived(cdr) + self._buffer.advanceRptr() + + return self.PORT_OK + + ## + # @brief push "fifo" policy + # + # PublisherBase::ReturnCode PublisherPeriodic::pushFifo() + + def pushFifo(self): + self._rtcout.RTC_TRACE("pushFifo()") + if not self._buffer: + return self.PRECONDITION_NOT_MET + + if self.bufferIsEmpty(): + return self.BUFFER_EMPTY + + _, cdr = self._buffer.get() + self.onBufferRead(cdr) + + cdr = self.onSend(cdr) + ret = self._consumer.put(cdr) + + if ret != self.PORT_OK: + self._rtcout.RTC_DEBUG( + "%s = consumer.put()", + OpenRTM_aist.DataPortStatus.toString(ret)) + return self.invokeListener(ret, cdr) + + cdr = self.onReceived(cdr) + self._buffer.advanceRptr() + + return self.PORT_OK + + ## + # @brief push "skip" policy + # + # PublisherBase::ReturnCode PublisherPeriodic::pushSkip() + + def pushSkip(self): + self._rtcout.RTC_TRACE("pushSkip()") + if not self._buffer: + return self.PRECONDITION_NOT_MET + + if self.bufferIsEmpty(): + return self.BUFFER_EMPTY + + ret = self.PORT_OK + preskip = self._buffer.readable() + self._leftskip + loopcnt = preskip / (self._skipn + 1) + postskip = self._skipn - self._leftskip + for i in range(int(loopcnt)): + self._buffer.advanceRptr(postskip) + _, cdr = self._buffer.get() + self.onBufferRead(cdr) + + cdr = self.onSend(cdr) + ret = self._consumer.put(cdr) + if ret != self.PORT_OK: + self._buffer.advanceRptr(-postskip) + self._rtcout.RTC_DEBUG( + "%s = consumer.put()", + OpenRTM_aist.DataPortStatus.toString(ret)) + return self.invokeListener(ret, cdr) + cdr = self.onReceived(cdr) + postskip = self._skipn + 1 + + self._buffer.advanceRptr(self._buffer.readable()) + self._leftskip = preskip % (self._skipn + 1) + + return ret + + ## + # @brief push "new" policy + # + # PublisherBase::ReturnCode PublisherPeriodic::pushNew() + + def pushNew(self): + self._rtcout.RTC_TRACE("pushNew()") + if not self._buffer: + return self.PRECONDITION_NOT_MET + + if self.bufferIsEmpty(): + return self.BUFFER_EMPTY + + # In case of the periodic/push_new policy, the buffer should + # allow readback. But, readback flag should be set as "true" + # after written at least one datum into the buffer. + self._readback = True + + self._buffer.advanceRptr(self._buffer.readable() - 1) + + _, cdr = self._buffer.get() + self.onBufferRead(cdr) + + cdr = self.onSend(cdr) + ret = self._consumer.put(cdr) + + if ret != self.PORT_OK: + self._rtcout.RTC_DEBUG( + "%s = consumer.put()", + OpenRTM_aist.DataPortStatus.toString(ret)) + return self.invokeListener(ret, cdr) + + cdr = self.onReceived(cdr) + + self._buffer.advanceRptr() + return self.PORT_OK + + ## + # @if jp + # @brief BufferStatus から DataPortStatus への変換 + # + # バッファからの戻り値を DataPortStatus::Enum 型へ変換する関数。そ + # れぞれ、以下のように変換される。変換時にコールバックを呼ぶ場合、 + # コールバク関数も付記する。 + # + # - BUFFER_OK: PORT_OK + # - None + # - BUFFER_ERROR: BUFFER_ERROR + # - None + # - BUFFER_FULL: BUFFER_FULL + # - onBufferFull() + # - NOT_SUPPORTED: PORT_ERROR + # - None + # - TIMEOUT: BUFFER_TIMEOUT + # - onBufferWriteTimeout() + # - PRECONDITION_NOT_MET: PRECONDITION_NOT_MET + # - None + # - other: PORT_ERROR + # - None + # + # @param status BufferStatus + # @param data cdrMemoryStream + # @return DataPortStatu 型のリターンコード + # + # @else + # @brief Convertion from BufferStatus to DataPortStatus + # + # This function converts return value from the buffer to + # DataPortStatus::Enum typed return value. The conversion rule is + # as follows. Callback functions are also shown, if it exists. + # + # - BUFFER_OK: PORT_OK + # - None + # - BUFFER_ERROR: BUFFER_ERROR + # - None + # - BUFFER_FULL: BUFFER_FULL + # - onBufferFull() + # - NOT_SUPPORTED: PORT_ERROR + # - None + # - TIMEOUT: BUFFER_TIMEOUT + # - onBufferWriteTimeout() + # - PRECONDITION_NOT_MET: PRECONDITION_NOT_MET + # - None + # - other: PORT_ERROR + # - None + # + # @param status BufferStatus + # @param data cdrMemoryStream + # @return DataPortStatus typed return code + # + # @endif + # + # PublisherBase::ReturnCodea + # PublisherPeriodic::convertReturn(BufferStatus::Enum status, + # const cdrMemoryStream& data) + def convertReturn(self, status, data): + if status == OpenRTM_aist.BufferStatus.BUFFER_OK: + return self.PORT_OK + + elif status == OpenRTM_aist.BufferStatus.BUFFER_ERROR: + return self.BUFFER_ERROR + + elif status == OpenRTM_aist.BufferStatus.BUFFER_FULL: + self.onBufferFull(data) + return self.BUFFER_FULL + + elif status == OpenRTM_aist.BufferStatus.NOT_SUPPORTED: + return self.PORT_ERROR + + elif status == OpenRTM_aist.BufferStatus.TIMEOUT: + self.onBufferWriteTimeout(data) + return self.BUFFER_TIMEOUT + + elif status == OpenRTM_aist.BufferStatus.PRECONDITION_NOT_MET: + return self.PRECONDITION_NOT_MET + + else: + return self.PORT_ERROR + + ## + # @if jp + # @brief DataPortStatusに従ってリスナへ通知する関数を呼び出す。 + # + # @param status DataPortStatus + # @param data cdrMemoryStream + # @return リターンコード + # + # @else + # @brief Call listeners according to the DataPortStatus + # + # @param status DataPortStatus + # @param data cdrMemoryStream + # @return Return code + # + # @endif + # + # PublisherPeriodic::ReturnCode + # PublisherPeriodic::invokeListener(DataPortStatus::Enum status, + # const cdrMemoryStream& data) + + def invokeListener(self, status, data): + # ret: + # PORT_OK, PORT_ERROR, SEND_FULL, SEND_TIMEOUT, CONNECTION_LOST, + # UNKNOWN_ERROR + if status == self.PORT_ERROR: + self.onReceiverError(data) + return self.PORT_ERROR + + elif status == self.SEND_FULL: + self.onReceiverFull(data) + return self.SEND_FULL + + elif status == self.SEND_TIMEOUT: + self.onReceiverTimeout(data) + return self.SEND_TIMEOUT + + elif status == self.CONNECTION_LOST: + self.onReceiverError(data) + return self.CONNECTION_LOST + + elif status == self.UNKNOWN_ERROR: + self.onReceiverError(data) + return self.UNKNOWN_ERROR + + else: + self.onReceiverError(data) + return self.PORT_ERROR + + ## + # @if jp + # @brief ON_BUFFER_WRITEのリスナへ通知する。 + # @param data cdrMemoryStream + # @else + # @brief Notify an ON_BUFFER_WRITE event to listeners + # @param data cdrMemoryStream + # @endif + # + # inline void onBufferWrite(const cdrMemoryStream& data) + def onBufferWrite(self, data): + if self._listeners is not None and self._profile is not None: + _, data = self._listeners.notifyData( + OpenRTM_aist.ConnectorDataListenerType.ON_BUFFER_WRITE, self._profile, data) + return data + + ## + # @if jp + # @brief ON_BUFFER_FULLリスナへイベントを通知する。 + # @param data cdrMemoryStream + # @else + # @brief Notify an ON_BUFFER_FULL event to listeners + # @param data cdrMemoryStream + # @endif + # + # inline void onBufferFull(const cdrMemoryStream& data) + def onBufferFull(self, data): + if self._listeners is not None and self._profile is not None: + _, data = self._listeners.notifyData( + OpenRTM_aist.ConnectorDataListenerType.ON_BUFFER_FULL, self._profile, data) + return data + + ## + # @if jp + # @brief ON_BUFFER_WRITE_TIMEOUTのリスナへ通知する。 + # @param data cdrMemoryStream + # @else + # @brief Notify an ON_BUFFER_WRITE_TIMEOUT event to listeners + # @param data cdrMemoryStream + # @endif + # + # inline void onBufferWriteTimeout(const cdrMemoryStream& data) + def onBufferWriteTimeout(self, data): + if self._listeners is not None and self._profile is not None: + _, data = self._listeners.notifyData( + OpenRTM_aist.ConnectorDataListenerType.ON_BUFFER_WRITE_TIMEOUT, self._profile, data) + return data + + ## + # @if jp + # @brief ON_BUFFER_READのリスナへ通知する。 + # @param data cdrMemoryStream + # @else + # @brief Notify an ON_BUFFER_READ event to listeners + # @param data cdrMemoryStream + # @endif + # + # inline void onBufferRead(const cdrMemoryStream& data) + def onBufferRead(self, data): + if self._listeners is not None and self._profile is not None: + _, data = self._listeners.notifyData( + OpenRTM_aist.ConnectorDataListenerType.ON_BUFFER_READ, self._profile, data) + return data + + ## + # @if jp + # @brief ON_SENDのリスナへ通知する。 + # @param data cdrMemoryStream + # @else + # @brief Notify an ON_SEND event to listners + # @param data cdrMemoryStream + # @endif + # + # inline void onSend(const cdrMemoryStream& data) + def onSend(self, data): + if self._listeners is not None and self._profile is not None: + _, data = self._listeners.notifyData( + OpenRTM_aist.ConnectorDataListenerType.ON_SEND, self._profile, data) + return data + + ## + # @if jp + # @brief ON_RECEIVEDのリスナへ通知する。 + # @param data cdrMemoryStream + # @else + # @brief Notify an ON_RECEIVED event to listeners + # @param data cdrMemoryStream + # @endif + # + # inline void onReceived(const cdrMemoryStream& data) + def onReceived(self, data): + if self._listeners is not None and self._profile is not None: + _, data = self._listeners.notifyData( + OpenRTM_aist.ConnectorDataListenerType.ON_RECEIVED, self._profile, data) + return data + + ## + # @if jp + # @brief ON_RECEIVER_FULLのリスナへ通知する。 + # @param data cdrMemoryStream + # @else + # @brief Notify an ON_RECEIVER_FULL event to listeners + # @param data cdrMemoryStream + # @endif + # + # inline void onReceiverFull(const cdrMemoryStream& data) + def onReceiverFull(self, data): + if self._listeners is not None and self._profile is not None: + _, data = self._listeners.notifyData( + OpenRTM_aist.ConnectorDataListenerType.ON_RECEIVER_FULL, self._profile, data) + return data + + ## + # @if jp + # @brief ON_RECEIVER_TIMEOUTのリスナへ通知する。 + # @param data cdrMemoryStream + # @else + # @brief Notify an ON_RECEIVER_TIMEOUT event to listeners + # @param data cdrMemoryStream + # @endif + # + # inline void onReceiverTimeout(const cdrMemoryStream& data) + def onReceiverTimeout(self, data): + if self._listeners is not None and self._profile is not None: + _, data = self._listeners.notifyData( + OpenRTM_aist.ConnectorDataListenerType.ON_RECEIVER_TIMEOUT, self._profile, data) + return data + + ## + # @if jp + # @brief ON_RECEIVER_ERRORのリスナへ通知する。 + # @param data cdrMemoryStream + # @else + # @brief Notify an ON_RECEIVER_ERROR event to listeners + # @param data cdrMemoryStream + # @endif + # + # inline void onReceiverError(const cdrMemoryStream& data) + def onReceiverError(self, data): + if self._listeners is not None and self._profile is not None: + _, data = self._listeners.notifyData( + OpenRTM_aist.ConnectorDataListenerType.ON_RECEIVER_ERROR, self._profile, data) + return data + + ## + # @if jp + # @brief ON_BUFFER_EMPTYのリスナへ通知する。 + # @else + # @brief Notify an ON_BUFFER_EMPTY event to listeners + # @endif + # + # inline void onBufferEmpty() + + def onBufferEmpty(self): + if self._listeners is not None and self._profile is not None: + self._listeners.notify( + OpenRTM_aist.ConnectorListenerType.ON_BUFFER_EMPTY, self._profile) + return + + ## + # @if jp + # @brief ON_SENDER_EMPTYのリスナへ通知する。 + # @else + # @brief Notify an ON_SENDER_EMPTY event to listeners + # @endif + # + # inline void onSenderEmpty() + def onSenderEmpty(self): + if self._listeners is not None and self._profile is not None: + self._listeners.notify( + OpenRTM_aist.ConnectorListenerType.ON_SENDER_EMPTY, self._profile) + return + + ## + # @if jp + # @brief ON_SENDER_ERRORのリスナへ通知する。 + # @else + # @brief Notify an ON_SENDER_ERROR event to listeners + # @endif + # + # inline void onSenderError() + def onSenderError(self): + if self._listeners is not None and self._profile is not None: + self._listeners.notify( + OpenRTM_aist.ConnectorListenerType.ON_SENDER_ERROR, self._profile) + return + + ## + # @if jp + # @brief バッファが空かどうかをチェックする。x + # @else + # @brief Whether a buffer is empty. + # @endif + # + # bool bufferIsEmpty() + + def bufferIsEmpty(self): + if self._buffer and self._buffer.empty() and not self._readback: + self._rtcout.RTC_DEBUG("buffer empty") + self.onBufferEmpty() + self.onSenderEmpty() + return True + + return False def PublisherPeriodicInit(): - OpenRTM_aist.PublisherFactory.instance().addFactory("periodic", - OpenRTM_aist.PublisherPeriodic, - OpenRTM_aist.Delete) + OpenRTM_aist.PublisherFactory.instance().addFactory("periodic", + OpenRTM_aist.PublisherPeriodic) diff --git a/OpenRTM_aist/RTCUtil.py b/OpenRTM_aist/RTCUtil.py index 0c917cb9..32e5df82 100644 --- a/OpenRTM_aist/RTCUtil.py +++ b/OpenRTM_aist/RTCUtil.py @@ -1,5 +1,5 @@ #!/usr/bin/env python -# -*- coding: euc-jp -*- +# -*- coding: utf-8 -*- ## @@ -23,40 +23,42 @@ ## # @if jp # -# @brief DataFlowComponent Ǥ뤫Ƚꤹ +# @brief DataFlowComponent であるか判定する # -# ꤵ줿RTݡͥȤ DataFlowComponent Ǥ뤫Ƚꤹ롣 -# DataFlowComponent ExecutionContext Semantics -# Periodic Sampled Data Processing ξѤRTݡͥȤη -# Ǥ롣 +# 指定されたRTコンポーネントが DataFlowComponent であるか判定する。 +# DataFlowComponent、 ExecutionContext の Semantics が +# Periodic Sampled Data Processing の場合に利用されるRTコンポーネントの型 +# である。 # -# @param obj Ƚоݤ CORBA ֥ +# @param obj 判定対象の CORBA オブジェクト # -# @return DataFlowComponent Ƚ +# @return DataFlowComponent 判定結果 # # @since 0.4.0 # # @else # # @endif + + def isDataFlowComponent(obj): - dfp = obj._narrow(OpenRTM.DataFlowComponent) - return not CORBA.is_nil(dfp) + dfp = obj._narrow(OpenRTM.DataFlowComponent) + return not CORBA.is_nil(dfp) ## # @if jp # -# @brief FsmParticipant Ǥ뤫Ƚꤹ +# @brief FsmParticipant であるか判定する # -# ꤵ줿RTݡͥȤ FsmParticipant Ǥ뤫Ƚꤹ롣 -# FsmParticipant ϡ ExecutionContext Semantics -# Stimulus Response Processing ξˡΥ뤿 -# ѤRTݡͥȤηǤ롣 +# 指定されたRTコンポーネントが FsmParticipant であるか判定する。 +# FsmParticipant は、 ExecutionContext の Semantics が +# Stimulus Response Processing の場合に、状態内のアクションを定義するために +# 利用されるRTコンポーネントの型である。 # -# @param obj Ƚоݤ CORBA ֥ +# @param obj 判定対象の CORBA オブジェクト # -# @return FsmParticipant Ƚ +# @return FsmParticipant 判定結果 # # @since 0.4.0 # @@ -64,22 +66,22 @@ def isDataFlowComponent(obj): # # @endif def isFsmParticipant(obj): - fsmp = obj._narrow(RTC.FsmParticipant) - return not CORBA.is_nil(fsmp) + fsmp = obj._narrow(RTC.FsmParticipant) + return not CORBA.is_nil(fsmp) ## # @if jp # -# @brief Fsm Ǥ뤫Ƚꤹ +# @brief Fsm であるか判定する # -# ꤵ줿RTݡͥȤ Fsm Ǥ뤫Ƚꤹ롣 -# Fsm ϡ ExecutionContext Semantics Stimulus Response Processing -# ˡܤ뤿ѤRTݡͥȤηǤ롣 +# 指定されたRTコンポーネントが Fsm であるか判定する。 +# Fsm は、 ExecutionContext の Semantics が Stimulus Response Processing の +# 場合に、状態遷移を定義するために利用されるRTコンポーネントの型である。 # -# @param obj Ƚоݤ CORBA ֥ +# @param obj 判定対象の CORBA オブジェクト # -# @return Fsm Ƚ +# @return Fsm 判定結果 # # @since 0.4.0 # @@ -87,22 +89,22 @@ def isFsmParticipant(obj): # # @endif def isFsmObject(obj): - fsm = obj._narrow(RTC.FsmObject) - return not CORBA.is_nil(fsm) + fsm = obj._narrow(RTC.FsmObject) + return not CORBA.is_nil(fsm) ## # @if jp # -# @brief multiModeComponent Ǥ뤫Ƚꤹ +# @brief multiModeComponent であるか判定する # -# ꤵ줿RTݡͥȤ multiModeComponent Ǥ뤫Ƚꤹ롣 -# multiModeComponent ϡ ExecutionContext Semantics Modes of Operatin -# ξˡ Mode 뤿ѤRTݡͥȤηǤ롣 +# 指定されたRTコンポーネントが multiModeComponent であるか判定する。 +# multiModeComponent は、 ExecutionContext の Semantics が Modes of Operatin +# の場合に、 Mode を定義するために利用されるRTコンポーネントの型である。 # -# @param obj Ƚоݤ CORBA ֥ +# @param obj 判定対象の CORBA オブジェクト # -# @return multiModeComponent Ƚ +# @return multiModeComponent 判定結果 # # @since 0.4.0 # @@ -110,10 +112,8 @@ def isFsmObject(obj): # # @endif def isMultiModeObject(obj): - mmc = obj._narrow(RTC.MultiModeObject) - return not CORBA.is_nil(mmc) - - + mmc = obj._narrow(RTC.MultiModeObject) + return not CORBA.is_nil(mmc) ######################################################################### @@ -122,44 +122,51 @@ def isMultiModeObject(obj): # DataType for CORBA # def instantiateDataType(dtype): - if isinstance(dtype, int) : desc = [dtype] - elif isinstance(dtype, tuple) : desc = dtype - else : - desc=omniORB.findType(dtype._NP_RepositoryId) - - if desc[0] in [omniORB.tcInternal.tv_alias ]: return instantiateDataType(desc[3]) - - if desc[0] in [omniORB.tcInternal.tv_short, - omniORB.tcInternal.tv_long, - omniORB.tcInternal.tv_ushort, + if isinstance(dtype, int): + desc = [dtype] + elif isinstance(dtype, tuple): + desc = dtype + else: + desc = omniORB.findType(dtype._NP_RepositoryId) + + if desc[0] in [omniORB.tcInternal.tv_alias]: + return instantiateDataType(desc[3]) + + if desc[0] in [omniORB.tcInternal.tv_short, + omniORB.tcInternal.tv_long, + omniORB.tcInternal.tv_ushort, omniORB.tcInternal.tv_ulong, omniORB.tcInternal.tv_boolean, omniORB.tcInternal.tv_char, omniORB.tcInternal.tv_octet, omniORB.tcInternal.tv_longlong, omniORB.tcInternal.tv_enum - ]: return 0 + ]: + return 0 - if desc[0] in [omniORB.tcInternal.tv_float, + if desc[0] in [omniORB.tcInternal.tv_float, omniORB.tcInternal.tv_double, omniORB.tcInternal.tv_longdouble - ]: return 0.0 + ]: + return 0.0 - if desc[0] in [omniORB.tcInternal.tv_sequence, + if desc[0] in [omniORB.tcInternal.tv_sequence, omniORB.tcInternal.tv_array, - ]: return [] - + ]: + return [] - if desc[0] in [omniORB.tcInternal.tv_string ]: return "" + if desc[0] in [omniORB.tcInternal.tv_string]: + return "" if desc[0] in [omniORB.tcInternal.tv_wstring, omniORB.tcInternal.tv_wchar - ]: return u"" + ]: + return u"" if desc[0] == omniORB.tcInternal.tv_struct: arg = [] - for i in range(4, len(desc), 2): + for i in range(4, len(desc), 2): attr = desc[i] - attr_type = desc[i+1] + attr_type = desc[i + 1] arg.append(instantiateDataType(attr_type)) return desc[1](*arg) - return None \ No newline at end of file + return None diff --git a/OpenRTM_aist/RTM_IDL/BasicDataType.idl b/OpenRTM_aist/RTM_IDL/BasicDataType.idl index d089563d..2ce6125f 100644 --- a/OpenRTM_aist/RTM_IDL/BasicDataType.idl +++ b/OpenRTM_aist/RTM_IDL/BasicDataType.idl @@ -183,7 +183,28 @@ module RTC { Time tm; sequence data; }; - + + #pragma keylist TimedState + #pragma keylist TimedShort + #pragma keylist TimedLong + #pragma keylist TimedUShort + #pragma keylist TimedULong + #pragma keylist TimedFloat + #pragma keylist TimedDouble + #pragma keylist TimedChar + #pragma keylist TimedBoolean + #pragma keylist TimedOctet + #pragma keylist TimedString + #pragma keylist TimedShortSeq + #pragma keylist TimedLongSeq + #pragma keylist TimedUShortSeq + #pragma keylist TimedULongSeq + #pragma keylist TimedFloatSeq + #pragma keylist TimedDoubleSeq + #pragma keylist TimedCharSeq + #pragma keylist TimedBooleanSeq + #pragma keylist TimedOctetSeq + #pragma keylist TimedStringSeq }; #endif // end of BasicDataType_idl diff --git a/OpenRTM_aist/RTM_IDL/CSPPort.idl b/OpenRTM_aist/RTM_IDL/CSPPort.idl new file mode 100644 index 00000000..a86bf325 --- /dev/null +++ b/OpenRTM_aist/RTM_IDL/CSPPort.idl @@ -0,0 +1,52 @@ +#ifndef CSPPORT_IDL +#define CSPPORT_IDL + +#include "DataPort.idl" + +#pragma prefix "openrtm.aist.go.jp" +/*! + * @brief CSP (Communicating Sequential Processes) channel port + * + * Communicating Sequential Processes (CSP) is a formal language for + * describing patterns of interaction in concurrent systems. CSP uses + * explicit channels for message passing, whereas actor systems + * transmit messages to named destination actors. These approaches may + * be considered duals of each other, in the sense that processes + * receiving through a single channel effectively have an identity + * corresponding to that channel, while the name-based coupling + * between actors may be broken by constructing actors that behave as + * channels. + * (from https://en.wikipedia.org/wiki/Communicating_sequential_processes) + * + * http://arild.github.io/csp-presentation + * https://qiita.com/ymgyt/items/420eaf2bcf7bee4ae152 + * + + * This interface definition realizes CSP channel as an RTC port. + * + * CSP`l + * - ^bZ[WpbVO + * - mɓ`BiMMł܂ő҂j + * - ʐM”\ȑIɑIĒʐM”\ + * - M”\ȃvZXIđMiSĂMs‚̂Ƃ́AЂ + * ‚M”\ɂȂ܂őMj + * - ʐM”\ȃ`lIɑIiOIjĒʐM”\ + * - M”\ȃvZXڑĂ`lIđM + * + */ +module CSP +{ + interface InPortCsp + { + RTC::PortStatus put(in RTC::OctetSeq data); + boolean is_writable(in boolean retry); + }; + + interface OutPortCsp + { + RTC::PortStatus get(out RTC::OctetSeq data); + boolean is_readable(in boolean retry); + }; +}; + +#endif // CSPPORT_IDL \ No newline at end of file diff --git a/OpenRTM_aist/RTM_IDL/ExtendedDataTypes.idl b/OpenRTM_aist/RTM_IDL/ExtendedDataTypes.idl index 50454e9d..a13c998a 100644 --- a/OpenRTM_aist/RTM_IDL/ExtendedDataTypes.idl +++ b/OpenRTM_aist/RTM_IDL/ExtendedDataTypes.idl @@ -694,6 +694,57 @@ module RTC { Time tm; OAP data; }; + + /*! + * @struct Quaternion + * @brief Data type for Quaternion + */ + struct Quaternion + { + double x; + double y; + double z; + double w; + }; + + /*! + * @struct TimedQuaternion + * @brief Timed version data type for Quaternion + */ + struct TimedQuaternion + { + Time tm; + Quaternion data; + }; + + #pragma keylist TimedRGBColour + #pragma keylist TimedPoint2D + #pragma keylist TimedVector2D + #pragma keylist TimedPose2D + #pragma keylist TimedVelocity2D + #pragma keylist TimedAcceleration2D + #pragma keylist TimedPoseVel2D + #pragma keylist TimedSize2D + #pragma keylist TimedGeometry2D + #pragma keylist TimedCovariance2D + #pragma keylist TimedPointCovariance2D + #pragma keylist TimedCarlike + #pragma keylist TimedSpeedHeading2D + #pragma keylist TimedPoint3D + #pragma keylist TimedVector3D + #pragma keylist TimedOrientation3D + #pragma keylist TimedPose3D + #pragma keylist TimedVelocity3D + #pragma keylist TimedAngularVelocity3D + #pragma keylist TimedAcceleration3D + #pragma keylist TimedAngularAcceleration3D + #pragma keylist TimedPoseVel3D + #pragma keylist TimedSize3D + #pragma keylist TimedGeometry3D + #pragma keylist TimedCovariance3D + #pragma keylist TimedSpeedHeading3D + #pragma keylist TimedOAP + #pragma keylist TimedQuaternion }; #endif // ExtendedDataTypes_idl diff --git a/OpenRTM_aist/RTM_IDL/InterfaceDataTypes.idl b/OpenRTM_aist/RTM_IDL/InterfaceDataTypes.idl index 7bec9bf9..de5df773 100644 --- a/OpenRTM_aist/RTM_IDL/InterfaceDataTypes.idl +++ b/OpenRTM_aist/RTM_IDL/InterfaceDataTypes.idl @@ -918,6 +918,28 @@ module RTC { * @typedef RFIDTagData */ typedef sequence RFIDTagData; + + #pragma keylist ActArrayActuatorPos + #pragma keylist ActArrayActuatorSpeed + #pragma keylist ActArrayActuatorCurrent + #pragma keylist ActArrayState + #pragma keylist CameraImage + #pragma keylist Fiducials + #pragma keylist GPSData + #pragma keylist GripperState + #pragma keylist INSData + #pragma keylist LimbState + #pragma keylist Hypotheses2D + #pragma keylist Hypotheses3D + #pragma keylist Features + #pragma keylist MultiCameraImages + #pragma keylist Path2D + #pragma keylist Path3D + #pragma keylist PointCloud + #pragma keylist PanTiltAngles + #pragma keylist PanTiltState + #pragma keylist RangeData + #pragma keylist IntensityData }; #endif // InterfaceDataTypes_idl diff --git a/OpenRTM_aist/RTM_IDL/__init__.py b/OpenRTM_aist/RTM_IDL/__init__.py index 932b7982..270be2a2 100644 --- a/OpenRTM_aist/RTM_IDL/__init__.py +++ b/OpenRTM_aist/RTM_IDL/__init__.py @@ -1 +1 @@ -# Empty file +# Empty file diff --git a/OpenRTM_aist/RTM_IDL/device_interfaces/__init__.py b/OpenRTM_aist/RTM_IDL/device_interfaces/__init__.py index 932b7982..270be2a2 100644 --- a/OpenRTM_aist/RTM_IDL/device_interfaces/__init__.py +++ b/OpenRTM_aist/RTM_IDL/device_interfaces/__init__.py @@ -1 +1 @@ -# Empty file +# Empty file diff --git a/OpenRTM_aist/RTM_IDL/ext/rtmCamera/CameraCommonInterface.idl b/OpenRTM_aist/RTM_IDL/ext/rtmCamera/CameraCommonInterface.idl new file mode 100644 index 00000000..6b69871c --- /dev/null +++ b/OpenRTM_aist/RTM_IDL/ext/rtmCamera/CameraCommonInterface.idl @@ -0,0 +1,190 @@ +/* version 2.0 */ + +#ifndef CAMERACOMMONINTERFACE_IDL +#define CAMERACOMMONINTERFACE_IDL + +#include "BasicDataType.idl" + +module Img { + //============================================================ + // Definition of basic matrix for image. + //============================================================ + typedef double Vec3[3]; + typedef double Mat44[4][4]; + + //============================================================ + //Image Data Structure + //============================================================ + + //------------------------------------------------------------ + // Color Formats Definition + // The parameters of CF_XXX are defined by this idl. + // The other parameters are cited from FourCC definition. + // To obtain the detail information about FourCC formats, please visit + // following website: + // http://www.fourcc.org/ + //------------------------------------------------------------ + enum ColorFormat + { + CF_UNKNOWN, //Unknown Color Format + CF_RGB, //RGB raw data format + CF_GRAY, //8bit gray image data format + CF_JPEG, //JPEG image format + CF_PNG, //PNG image format + + //Paramter definitions based on FourCC + RGB, //Basic Windows bitmap format + RLE8, //Run length encoded 8bpp RGB image + RLE, //Run length encoded 4bpp RGB image + RAW, //Uncompressed RGB bitmaps + RGBA, //Raw RGB with alpha + RGBT, //Raw RGB with a transparency field + AYUV, //Combined YUV and alpha + CLJR, //Cirrus Logic format with 4 pixels packed into a u_int32 + CYUV, //Essentially a copy of UYUV except that the sense of the height is reserved + GREY, //Apparently a duplicate of Y800 and Y8 + IRAW, //Intel uncompressed YUV + IUYV, //Interlaced version of UYUV + IY41, //Interlaced version of Y41P + IYU1, //12bit format used in mode 2 of the IEEE 1394 Digital Camera 1.04 spec. + IYU2, //24 bit format used in mode 0 of the IEEE 1394 Digital Camera 1.04 spec. + HDYC, //YUV 4:2:2 (Y sample at every pixel, U and V sampled at every second + //pixel horizontally on each line) + UYNV, //A direct copy of UYVY registered by NVidia to work around problems in + //some old codecs which did not like hardware which offered more than 2 + //UYVY surfaces. + UYVP, //YCbCr 4:2:2 extended precision 10-bits per component in U0Y0V0Y1 order + V210, //10-bit 4:2:2 YCrCb equivalent to the Quicktime format of the same name + V422, //This is an upside down version of UYVY + V655, //16 bit YUV 4:2:2 format registered by Vitec Multimedia + VYUV, //Duplicate of YUV2 + YUNV, //A direct copy of YUY2 registered by NVidia to work around problems in + //some old codecs which did not like hardware which offered more than 2 + //YUY2 surfaces + YVYU, //YUV 4:2:2 as for UYVY but with different component ordering within the + //u_int32 macropixel + Y41P, //YUV 4:1:1 with a packed, 6 byte/4 pixel macroblock structure + Y211, //Packed YUV format with Y sampled at every second pixel across each line + //and U and V sampled at every fourth pixel + Y41T, //Format as for Y41P but the lsb of each Y component is used to signal pixel + //transparency + Y42T, //Format as for UYVY but the lsb of each Y component is used to signal + //pixel transparency + YUVP, //YCbCr 4:2:2 extended precision 10-bits per component in Y0U0Y1V0 + //order + Y800, //Simple, single Y plane for monochrome images + Y8, //Duplicate of Y800 + Y16 //16-bit uncompressed grayscale image + }; + + //============================================================ + // Camera Image Data Structure + //============================================================ + + //------------------------------------------------------------ + // Image Data Structure for still image + //------------------------------------------------------------ + struct ImageData + { + long width; + long height; + ColorFormat format; + sequence raw_data; + }; + + //------------------------------------------------------------ + // Camera Intrinsic Parameter Structure + //------------------------------------------------------------ + struct CameraIntrinsicParameter + { + double matrix_element[5]; + sequence distortion_coefficient; + }; + + //------------------------------------------------------------ + // Camera Image Structure + //------------------------------------------------------------ + struct CameraImage + { + RTC::Time captured_time; + ImageData image; + CameraIntrinsicParameter intrinsic; + Mat44 extrinsic; + }; + + //------------------------------------------------------------ + // Timed Camera Image Structure + // This structure includes time stump. + //------------------------------------------------------------ + struct TimedCameraImage + { + RTC::Time tm; + CameraImage data; + long error_code; + }; + + //============================================================ + // Multi Camera Image Data Structure + //============================================================ + + //------------------------------------------------------------ + // Multi Camera Image Structure + //------------------------------------------------------------ + struct MultiCameraImage + { + sequence image_seq; + long camera_set_id; + }; + + //------------------------------------------------------------ + // Time Multi Camera Image Structure + // This structure includes time stump. + //------------------------------------------------------------ + struct TimedMultiCameraImage + { + RTC::Time tm; + MultiCameraImage data; + long error_code; + }; + + //============================================================ + // Camera Device Profile Structure + //============================================================ + struct NamedValue + { + string name; + string value; + }; + + typedef sequence NVList; + + struct CameraDeviceProfile + { + string devtypeid; + string guid; + short unit; + string vendor_name; + string model_name; + CameraIntrinsicParameter intrinsic; + NVList properties; + }; + + //============================================================ + // Camera Control Service Interface + //============================================================ + + //------------------------------------------------------------ + // Camera Control Service Interface for image capture + //------------------------------------------------------------ + interface CameraCaptureService + { + oneway void take_one_frame(); + oneway void take_multi_frames(in long num); + oneway void start_continuous(); + oneway void stop_continuous(); + void getProfile(out CameraDeviceProfile profile); + }; +}; /* module */ + +#endif /* CAMERACOMMONINTERFACE_IDL */ + diff --git a/OpenRTM_aist/RTM_IDL/ext/rtmManipulator/ManipulatorCommonInterface_Common.idl b/OpenRTM_aist/RTM_IDL/ext/rtmManipulator/ManipulatorCommonInterface_Common.idl new file mode 100644 index 00000000..6db62d88 --- /dev/null +++ b/OpenRTM_aist/RTM_IDL/ext/rtmManipulator/ManipulatorCommonInterface_Common.idl @@ -0,0 +1,58 @@ +/* + Manipulator Common Interface (Common Commands) + - This IDL is used as service port on RTC + - This command specification is provided by Intelligent RT Software + Project of JARA. + rev. 20140205 +*/ + +#ifndef MANIPULATORCOMMONINTERFACE_COMMON_IDL +#define MANIPULATORCOMMONINTERFACE_COMMON_IDL + +#include "ManipulatorCommonInterface_DataTypes.idl" + +module JARA_ARM { + + enum AlarmType { + FAULT, + WARNING, + UNKNOWN + }; + + struct Alarm { + unsigned long code; + AlarmType type; + string description; + }; + + typedef sequence AlarmSeq; + typedef sequence LimitSeq; + + struct ManipInfo { + string manufactur; + string type; + ULONG axisNum; + ULONG cmdCycle; + boolean isGripper; + }; + + const ULONG CONST_BINARY_00000001 = 0x01; //isServoOn + const ULONG CONST_BINARY_00000010 = 0x02; //isMoving + const ULONG CONST_BINARY_00000100 = 0x04; //isAlarmed + const ULONG CONST_BINARY_00001000 = 0x08; //isBufferFull + + interface ManipulatorCommonInterface_Common { + RETURN_ID clearAlarms(); + RETURN_ID getActiveAlarm(out AlarmSeq alarms); + RETURN_ID getFeedbackPosJoint(out JointPos pos); + RETURN_ID getManipInfo(out ManipInfo mInfo); + RETURN_ID getSoftLimitJoint(out LimitSeq softLimit); + RETURN_ID getState(out ULONG state); + RETURN_ID servoOFF(); + RETURN_ID servoON(); + RETURN_ID setSoftLimitJoint(in LimitSeq softLimit); + }; +}; + +#endif // MANIPULATORCOMMONINTERFACE_COMMON_IDL + diff --git a/OpenRTM_aist/RTM_IDL/ext/rtmManipulator/ManipulatorCommonInterface_DataTypes.idl b/OpenRTM_aist/RTM_IDL/ext/rtmManipulator/ManipulatorCommonInterface_DataTypes.idl new file mode 100644 index 00000000..460e9d67 --- /dev/null +++ b/OpenRTM_aist/RTM_IDL/ext/rtmManipulator/ManipulatorCommonInterface_DataTypes.idl @@ -0,0 +1,46 @@ +/* + Manipulator Common Interface (Data type defenition) + - This IDL is used as service port on RTC + - This command specification is provided by Intelligent RT Software + Project of JARA. + rev. 20140205 +*/ + +#ifndef MANIPULATORCOMMONINTERFACE_DATATYPES_IDL +#define MANIPULATORCOMMONINTERFACE_DATATYPES_IDL + +#include "BasicDataType.idl" + +module JARA_ARM { + + typedef sequence DoubleSeq; + typedef sequence JointPos; + + struct LimitValue { + double upper; + double lower; + }; + + struct RETURN_ID{ + long id; + string comment; + }; + + const long OK = 0; + const long NG = -1; + const long STATUS_ERR = -2; + const long VALUE_ERR = -3; + const long NOT_SV_ON_ERR = -4; + const long FULL_MOTION_QUEUE_ERR = -5; + const long NOT_IMPLEMENTED = -6; + + struct TimedJointPos { + RTC::Time tm; + JointPos pos; + }; + + typedef unsigned long ULONG; +}; + +#endif // MANIPULATORCOMMONINTERFACE_DATATYPES_IDL + diff --git a/OpenRTM_aist/RTM_IDL/ext/rtmManipulator/ManipulatorCommonInterface_Middle.idl b/OpenRTM_aist/RTM_IDL/ext/rtmManipulator/ManipulatorCommonInterface_Middle.idl new file mode 100644 index 00000000..d453d895 --- /dev/null +++ b/OpenRTM_aist/RTM_IDL/ext/rtmManipulator/ManipulatorCommonInterface_Middle.idl @@ -0,0 +1,73 @@ +/* + Manipulator Common Interface (Middle Level Commands) + - This IDL is used as service port on RTC + - This command specification is provided by Intelligent RT Software + Project of JARA. + rev. 20140205 +*/ + +#ifndef MANIPULATORCOMMONINTERFACE_MIDDLE_IDL +#define MANIPULATORCOMMONINTERFACE_MIDDLE_IDL + +#include "ManipulatorCommonInterface_DataTypes.idl" + +module JARA_ARM { + + typedef double HgMatrix [3][4]; + + struct CarPosWithElbow { + HgMatrix carPos; + double elbow; + ULONG structFlag; + }; + + struct CartesianSpeed { + double translation; + double rotation; + }; + + interface ManipulatorCommonInterface_Middle { + RETURN_ID closeGripper(); + RETURN_ID getBaseOffset(out HgMatrix offset); + RETURN_ID getFeedbackPosCartesian(out CarPosWithElbow pos); + RETURN_ID getMaxSpeedCartesian(out CartesianSpeed speed); + RETURN_ID getMaxSpeedJoint(out DoubleSeq speed); + RETURN_ID getMinAccelTimeCartesian(out double aclTime); + RETURN_ID getMinAccelTimeJoint(out double aclTime); + RETURN_ID getSoftLimitCartesian(out LimitValue xLimit, + out LimitValue yLimit, out LimitValue zLimit ); + RETURN_ID moveGripper(in ULONG angleRatio); + RETURN_ID moveLinearCartesianAbs(in CarPosWithElbow carPoint); + RETURN_ID moveLinearCartesianRel(in CarPosWithElbow carPoint); + RETURN_ID movePTPCartesianAbs(in CarPosWithElbow carPoint); + RETURN_ID movePTPCartesianRel(in CarPosWithElbow carPoint); + RETURN_ID movePTPJointAbs(in JointPos jointPoints); + RETURN_ID movePTPJointRel(in JointPos jointPoints); + RETURN_ID openGripper(); + RETURN_ID pause(); + RETURN_ID resume(); + RETURN_ID stop(); + RETURN_ID setAccelTimeCartesian(in double aclTime); + RETURN_ID setAccelTimeJoint(in double aclTime); + RETURN_ID setBaseOffset(in HgMatrix offset); + RETURN_ID setControlPointOffset(in HgMatrix offset); + RETURN_ID setMaxSpeedCartesian(in CartesianSpeed speed); + RETURN_ID setMaxSpeedJoint(in DoubleSeq speed); + RETURN_ID setMinAccelTimeCartesian(in double aclTime); + RETURN_ID setMinAccelTimeJoint(in double aclTime); + RETURN_ID setSoftLimitCartesian(in LimitValue xLimit, + in LimitValue yLimit, in LimitValue zLimit); + RETURN_ID setSpeedCartesian(in ULONG spdRatio); + RETURN_ID setSpeedJoint(in ULONG spdRatio); + RETURN_ID moveCircularCartesianAbs(in CarPosWithElbow carPointR, + in CarPosWithElbow carPointT); + RETURN_ID moveCircularCartesianRel(in CarPosWithElbow carPointR, + in CarPosWithElbow carPointT); + RETURN_ID setHome(in JointPos jointPoint); + RETURN_ID getHome(out JointPos jointPoint); + RETURN_ID goHome(); + }; +}; + +#endif // MANIPULATORCOMMONINTERFACE_MIDDLE_IDL + diff --git a/OpenRTM_aist/RTObject.py b/OpenRTM_aist/RTObject.py index fc54d17b..ee2ffda2 100644 --- a/OpenRTM_aist/RTObject.py +++ b/OpenRTM_aist/RTObject.py @@ -1,5 +1,5 @@ #!/usr/bin/env python -# -*- coding: euc-jp -*- +# -*- coding: utf-8 -*- ## # @file RTObject.py @@ -15,9 +15,6 @@ # All rights reserved. - - - import copy from omniORB import any @@ -31,34 +28,33 @@ ECOTHER_OFFSET = 1000 default_conf = [ - "implementation_id","", - "type_name", "", - "description", "", - "version", "", - "vendor", "", - "category", "", - "activity_type", "", - "max_instance", "", - "language", "", - "lang_type", "", - "conf", "", - "" ] - + "implementation_id", "", + "type_name", "", + "description", "", + "version", "", + "vendor", "", + "category", "", + "activity_type", "", + "max_instance", "", + "language", "", + "lang_type", "", + "conf", "", + ""] ## # @if jp -# @brief RTݡͥȥ饹 +# @brief RTコンポーネントクラス # -# RTݡͥȤΥ١Ȥʤ륯饹 -# Robotic Technology Component lightweightRTComponentμ饹 -# ݡͥȤεǽ󶡤 ComponentAction 󥿡ե -# ݡͥȤΥ饤եԤ LightweightRTObject μ -# 󶡤롣 -# ºݤ˥桼ݡͥȤˤϡExecution Semantics б -# ƥ֥饹Ѥ롣
    -# (μǤ Periodic Sampled Data Processing ΤߥݡȤƤ뤿ᡢ -# dataFlowComponent ľܷѾƤ) +# 各RTコンポーネントのベースとなるクラス。 +# Robotic Technology Component 仕様中の lightweightRTComponentの実装クラス。 +# コンポーネントの機能を提供する ComponentAction インターフェースと +# コンポーネントのライフサイクル管理を行うための LightweightRTObject の実装を +# 提供する。 +# 実際にユーザがコンポーネントを作成する場合には、Execution Semantics に対応 +# した各サブクラスを利用する。
    +# (現状の実装では Periodic Sampled Data Processing のみサポートしているため、 +# dataFlowComponent を直接継承している) # # @since 0.2.0 # @@ -66,5363 +62,5353 @@ # # @endif class RTObject_impl: - """ - """ - - ## - # @if jp - # @brief 󥹥ȥ饯 - # - # 󥹥ȥ饯 - # - # @param self - # @param manager ޥ͡㥪֥(ǥե:None) - # @param orb ORB(ǥե:None) - # @param poa POA(ǥե:None) - # - # @else - # - # @brief Consructor - # - # @param orb ORB - # @param poa POA - # - # @endif - def __init__(self, manager=None, orb=None, poa=None): - if manager: - self._manager = manager - self._orb = self._manager.getORB() - self._poa = self._manager.getPOA() - self._portAdmin = OpenRTM_aist.PortAdmin(self._manager.getORB(),self._manager.getPOA()) - else: - self._manager = None - self._orb = orb - self._poa = poa - self._portAdmin = OpenRTM_aist.PortAdmin(self._orb,self._poa) - - if self._manager: - self._rtcout = self._manager.getLogbuf("rtobject") - else: - self._rtcout = OpenRTM_aist.Manager.instance().getLogbuf("rtobject") - - self._created = True - self._properties = OpenRTM_aist.Properties(defaults_str=default_conf) - self._configsets = OpenRTM_aist.ConfigAdmin(self._properties.getNode("conf")) - self._profile = RTC.ComponentProfile("","","","","","",[],None,[]) - - self.setInstanceName(str(OpenRTM_aist.uuid1())) - - self._sdoservice = OpenRTM_aist.SdoServiceAdmin(self) - self._SdoConfigImpl = OpenRTM_aist.Configuration_impl(self._configsets,self._sdoservice) - self._SdoConfig = self._SdoConfigImpl.getObjRef() - self._execContexts = [] - - self._sdoOwnedOrganizations = [] #SDOPackage.OrganizationList() - self._sdoSvcProfiles = [] #SDOPackage.ServiceProfileList() - self._sdoOrganizations = [] #SDOPackage.OrganizationList() - self._sdoStatus = [] #SDOPackage.NVList() - self._ecMine = [] - self._ecOther = [] - self._eclist = [] - self._exiting = False - self._readAll = False - self._writeAll = False - self._readAllCompletion = False - self._writeAllCompletion = False - self._inports = [] - self._outports = [] - self._actionListeners = OpenRTM_aist.ComponentActionListeners() - self._portconnListeners = OpenRTM_aist.PortConnectListeners() - self._fsmActionListeners = OpenRTM_aist.FsmActionListeners() - self._insref = RTC.RTObject._nil - return - - - ## - # @if jp - # - # @brief ǥȥ饯 - # - # @param self - # - # @else - # - # @brief destructor - # - # @endif - def __del__(self): - return - - - #============================================================ - # Overridden functions - #============================================================ - - ## - # @if jp - # - # @brief ѥХåؿ - # - # ComponentAction::on_initialize ƤФ줿ݤ˼¹Ԥ륳Хå - # ؿ
    - # ܴؿ̵ RTC::RTC_OK ֤褦˥ߡƤΤǡ - # ƥݡͥȤμºݤνϡܴؿ򥪡С饤ɤƼ - # ɬפ롣 - # - # @param self - # - # @return ReturnCode_t Υ꥿󥳡 - # - # @else - # - # @endif - def onInitialize(self): - self._rtcout.RTC_TRACE("onInitialize()") - return RTC.RTC_OK - - - ## - # @if jp - # - # @brief λѥХåؿ - # - # ComponentAction::on_finalize ƤФ줿ݤ˼¹Ԥ륳Хå - # ؿ
    - # ܴؿ̵ RTC::RTC_OK ֤褦˥ߡƤΤǡ - # ƥݡͥȤμºݤνλϡܴؿ򥪡С饤ɤƼ - # ɬפ롣 - # - # @param self - # - # @return ReturnCode_t Υ꥿󥳡 - # - # @else - # - # @endif - def onFinalize(self): - self._rtcout.RTC_TRACE("onFinalize()") - return RTC.RTC_OK - - - ## - # @if jp - # - # @brief ϽѥХåؿ - # - # ComponentAction::on_startup ƤФ줿ݤ˼¹Ԥ륳Хå - # ؿ
    - # ܴؿ̵ RTC::RTC_OK ֤褦˥ߡƤΤǡ - # ƥݡͥȤμºݤγϽϡܴؿ򥪡С饤ɤƼ - # ɬפ롣 - # - # @param self - # @param ec_id äƤ ExecutionContext ID - # - # @return ReturnCode_t Υ꥿󥳡 - # - # @else - # - # @endif - def onStartup(self, ec_id): - self._rtcout.RTC_TRACE("onStartup(%d)",ec_id) - return RTC.RTC_OK - - - ## - # @if jp - # - # @brief ߽ѥХåؿ - # - # ComponentAction::on_shutdown ƤФ줿ݤ˼¹Ԥ륳Хå - # ؿ
    - # ܴؿ̵ RTC::RTC_OK ֤褦˥ߡƤΤǡ - # ƥݡͥȤμºݤ߽ϡܴؿ򥪡С饤ɤƼ - # ɬפ롣 - # - # @param self - # @param ec_id äƤ ExecutionContext ID - # - # @return ReturnCode_t Υ꥿󥳡 - # - # @else - # - # @endif - def onShutdown(self, ec_id): - self._rtcout.RTC_TRACE("onShutdown(%d)",ec_id) - return RTC.RTC_OK - - - ## - # @if jp - # - # @brief ѥХåؿ - # - # ComponentAction::on_activated ƤФ줿ݤ˼¹Ԥ륳Хå - # ؿ
    - # ܴؿ̵ RTC::RTC_OK ֤褦˥ߡƤΤǡ - # ƥݡͥȤμºݤγϡܴؿ򥪡С饤ɤƼ - # ɬפ롣 - # - # @param self - # @param ec_id äƤ ExecutionContext ID - # - # @return ReturnCode_t Υ꥿󥳡 - # - # @else - # - # @endif - def onActivated(self, ec_id): - self._rtcout.RTC_TRACE("onActivated(%d)",ec_id) - return RTC.RTC_OK - - - ## - # @if jp - # - # @brief ѥХåؿ - # - # ComponentAction::on_deactivated ƤФ줿ݤ˼¹Ԥ륳Хå - # ؿ
    - # ܴؿ̵ RTC::RTC_OK ֤褦˥ߡƤΤǡ - # ƥݡͥȤμºݤϡܴؿ򥪡С饤ɤƼ - # ɬפ롣 - # - # @param self - # @param ec_id äƤ ExecutionContext ID - # - # @return ReturnCode_t Υ꥿󥳡 - # - # @else - # - # @endif - def onDeactivated(self, ec_id): - self._rtcout.RTC_TRACE("onDeactivated(%d)",ec_id) - return RTC.RTC_OK - - - ## - # @if jp - # - # @brief ѥХåؿ - # - # DataFlowComponentAction::on_execute ƤФ줿ݤ˼¹Ԥ - # Хåؿ
    - # ܴؿ̵ RTC::RTC_OK ֤褦˥ߡƤΤǡ - # ƥݡͥȤμºݤμϡܴؿ򥪡С饤ɤƼ - # ɬפ롣
    - # ܴؿ Periodic Sampled Data Processing ˤ Two-Pass Execution - # ܤμ¹ԥѥȤŪ˸ƤӽФ롣 - # - # @param self - # @param ec_id äƤ ExecutionContext ID - # - # @return ReturnCode_t Υ꥿󥳡 - # - # @else - # - # @endif - def onExecute(self, ec_id): - self._rtcout.RTC_TRACE("onExecute(%d)",ec_id) - return RTC.RTC_OK - - - ## - # @if jp - # - # @brief ǽѥХåؿ - # - # ComponentAction::on_aborting ƤФ줿ݤ˼¹Ԥ륳Хå - # ؿ
    - # ܴؿ̵ RTC::RTC_OK ֤褦˥ߡƤΤǡ - # ƥݡͥȤμºݤǽϡܴؿ򥪡С饤ɤƼ - # ɬפ롣 - # - # @param self - # @param ec_id äƤ ExecutionContext ID - # - # @return ReturnCode_t Υ꥿󥳡 - # - # @else - # - # @endif - def onAborting(self, ec_id): - self._rtcout.RTC_TRACE("onAborting(%d)",ec_id) - return RTC.RTC_OK - - - ## - # @if jp - # - # @brief 顼ѥХåؿ - # - # ComponentAction::on_error ƤФ줿ݤ˼¹Ԥ륳Хåؿ
    - # ܴؿ̵ RTC::RTC_OK ֤褦˥ߡƤΤǡ - # ƥݡͥȤμºݤΥ顼ϡܴؿ򥪡С饤ɤƼ - # ɬפ롣 - # - # @param self - # @param ec_id äƤ ExecutionContext ID - # - # @return ReturnCode_t Υ꥿󥳡 - # - # @else - # - # @endif - def onError(self, ec_id): - self._rtcout.RTC_TRACE("onError(%d)",ec_id) - return RTC.RTC_OK - - - ## - # @if jp - # - # @brief ꥻåȽѥХåؿ - # - # ComponentAction::on_reset ƤФ줿ݤ˼¹Ԥ륳Хåؿ
    - # ܴؿ̵ RTC::RTC_OK ֤褦˥ߡƤΤǡ - # ƥݡͥȤμºݤΥꥻåȽϡܴؿ򥪡С饤ɤƼ - # ɬפ롣 - # - # @param self - # @param ec_id äƤ ExecutionContext ID - # - # @return ReturnCode_t Υ꥿󥳡 - # - # @else - # - # @endif - def onReset(self, ec_id): - self._rtcout.RTC_TRACE("onReset(%d)",ec_id) - return RTC.RTC_OK - - - ## - # @if jp - # - # @brief ѹѥХåؿ - # - # DataFlowComponentAction::on_state_update ƤФ줿ݤ˼¹Ԥ - # Хåؿ
    - # ܴؿ̵ RTC::RTC_OK ֤褦˥ߡƤΤǡ - # ƥݡͥȤμºݤξѹϡܴؿ򥪡С饤ɤƼ - # ɬפ롣
    - # ܴؿ Periodic Sampled Data Processing ˤ Two-Pass Execution - # ܤμ¹ԥѥȤŪ˸ƤӽФ롣 - # - # @param self - # @param ec_id äƤ ExecutionContext ID - # - # @return ReturnCode_t Υ꥿󥳡 - # - # @else - # - # @endif - def onStateUpdate(self, ec_id): - self._rtcout.RTC_TRACE("onStateupdate(%d)",ec_id) - return RTC.RTC_OK - - - ## - # @if jp - # - # @brief ưѹѥХåؿ - # - # DataFlowComponentAction::on_rate_changed ƤФ줿ݤ˼¹Ԥ - # Хåؿ
    - # ܴؿ̵ RTC::RTC_OK ֤褦˥ߡƤΤǡ - # ƥݡͥȤμºݤξѹϡܴؿ򥪡С饤ɤƼ - # ɬפ롣
    - # ܴؿ Periodic Sampled Data Processing ˤ ExecutionContext - # ¹Ԥ줿ݤ˸ƤӽФ롣 - # - # @param self - # @param ec_id äƤ ExecutionContext ID - # - # @return ReturnCode_t Υ꥿󥳡 - # - # @else - # - # @endif - def onRateChanged(self, ec_id): - self._rtcout.RTC_TRACE("onRatechanged(%d)",ec_id) - return RTC.RTC_OK - - ## - # @if jp - # - # @brief - # - # @param self - # @param ec_id äƤ ExecutionContext ID - # - # @return ReturnCode_t Υ꥿󥳡 - # - # @else - # - # @endif - def onAction(self, ec_id): - self._rtcout.RTC_TRACE("onAction(%d)",ec_id) - return RTC.RTC_OK - - - #============================================================ - # RTC::LightweightRTObject - #============================================================ - - ## - # @if jp - # - # @brief [CORBA interface] RTC - # - # Υڥ졼ƤӽФη̤ȤơComponentAction::on_initialize - # ХåؿƤФ롣 - # - # - # - RTC Created֤ξ߽Ԥ롣¾ξ֤ˤˤ - # ReturnCode_t::PRECONDITION_NOT_MET ֤ƤӽФϼԤ롣 - # - Υڥ졼 RTC Υߥɥ륦ƤФ뤳ȤꤷƤꡢ - # ץꥱȯԤľܤΥڥ졼Ƥ֤Ȥ - # Ƥʤ - # - # @param self - # - # @return ReturnCode_t Υ꥿󥳡 - # - # @else - # - # @brief Initialize the RTC that realizes this interface. - # - # The invocation of this operation shall result in the invocation of the - # callback ComponentAction::on_initialize. - # - # Constraints - # - An RTC may be initialized only while it is in the Created state. Any - # attempt to invoke this operation while in another state shall fail - # with ReturnCode_t::PRECONDITION_NOT_MET. - # - Application developers are not expected to call this operation - # directly; it exists for use by the RTC infrastructure. - # - # @return - # - # @endif - def initialize(self): - self._rtcout.RTC_TRACE("initialize()") - - # EC creation - ec_args_ = [] - if self.getContextOptions(ec_args_) != RTC.RTC_OK: - self._rtcout.RTC_ERROR("Valid EC options are not available. Aborting") - return RTC.BAD_PARAMETER - - if self.createContexts(ec_args_) != RTC.RTC_OK: - self._rtcout.RTC_ERROR("EC creation failed. Maybe out of resources. Aborting.") - return RTC.OUT_OF_RESOURCES + """ + """ + + ## + # @if jp + # @brief コンストラクタ + # + # コンストラクタ + # + # @param self + # @param manager マネージャオブジェクト(デフォルト値:None) + # @param orb ORB(デフォルト値:None) + # @param poa POA(デフォルト値:None) + # + # @else + # + # @brief Consructor + # + # @param orb ORB + # @param poa POA + # + # @endif + def __init__(self, manager=None, orb=None, poa=None): + if manager: + self._manager = manager + self._orb = self._manager.getORB() + self._poa = self._manager.getPOA() + self._portAdmin = OpenRTM_aist.PortAdmin( + self._manager.getORB(), self._manager.getPOA()) + else: + self._manager = None + self._orb = orb + self._poa = poa + self._portAdmin = OpenRTM_aist.PortAdmin(self._orb, self._poa) + if self._manager: + self._rtcout = self._manager.getLogbuf("rtobject") + else: + self._rtcout = OpenRTM_aist.Manager.instance().getLogbuf("rtobject") + + self._created = True + self._properties = OpenRTM_aist.Properties(defaults_str=default_conf) + self._configsets = OpenRTM_aist.ConfigAdmin( + self._properties.getNode("conf")) + self._profile = RTC.ComponentProfile( + "", "", "", "", "", "", [], None, []) + + self.setInstanceName(str(OpenRTM_aist.uuid1())) + + self._sdoservice = OpenRTM_aist.SdoServiceAdmin(self) + self._SdoConfigImpl = OpenRTM_aist.Configuration_impl( + self._configsets, self._sdoservice) + self._SdoConfig = self._SdoConfigImpl.getObjRef() + self._execContexts = [] + + self._sdoOwnedOrganizations = [] # SDOPackage.OrganizationList() + self._sdoSvcProfiles = [] # SDOPackage.ServiceProfileList() + self._sdoOrganizations = [] # SDOPackage.OrganizationList() + self._sdoStatus = [] # SDOPackage.NVList() + self._ecMine = [] + self._ecOther = [] + self._eclist = [] + self._exiting = False + self._readAll = False + self._writeAll = False + self._readAllCompletion = False + self._writeAllCompletion = False + self._inports = [] + self._outports = [] + self._actionListeners = OpenRTM_aist.ComponentActionListeners() + self._portconnListeners = OpenRTM_aist.PortConnectListeners() + self._fsmActionListeners = OpenRTM_aist.FsmActionListeners() + self._insref = RTC.RTObject._nil + return - # -- entering alive state -- - toSTR_ = lambda x: " was" if len(x) == 1 else "s were" - self._rtcout.RTC_INFO("%d execution context%s created.", - (len(self._ecMine), toSTR_(self._ecMine))) + ## + # @if jp + # + # @brief デストラクタ + # + # @param self + # + # @else + # + # @brief destructor + # + # @endif + + def __del__(self): + return - ret_ = self.on_initialize() - self._created = False - if ret_ != RTC.RTC_OK: - self._rtcout.RTC_ERROR("on_initialize() failed.") - return ret_ + # ============================================================ + # Overridden functions + # ============================================================ + + ## + # @if jp + # + # @brief 初期化処理用コールバック関数 + # + # ComponentAction::on_initialize が呼ばれた際に実行されるコールバック + # 関数。
    + # 本関数は無条件に RTC::RTC_OK を返すようにダミー実装されているので、 + # 各コンポーネントの実際の初期化処理は、本関数をオーバーライドして実装する + # 必要がある。 + # + # @param self + # + # @return ReturnCode_t 型のリターンコード + # + # @else + # + # @endif + + def onInitialize(self): + self._rtcout.RTC_TRACE("onInitialize()") + return RTC.RTC_OK - self._rtcout.RTC_DEBUG("on_initialize() was properly done.") - for (idx_, ec_) in enumerate(self._ecMine): - self._rtcout.RTC_DEBUG("EC[%d] starting.", idx_) - ec_.start() + ## + # @if jp + # + # @brief 終了処理用コールバック関数 + # + # ComponentAction::on_finalize が呼ばれた際に実行されるコールバック + # 関数。
    + # 本関数は無条件に RTC::RTC_OK を返すようにダミー実装されているので、 + # 各コンポーネントの実際の終了処理は、本関数をオーバーライドして実装する + # 必要がある。 + # + # @param self + # + # @return ReturnCode_t 型のリターンコード + # + # @else + # + # @endif + + def onFinalize(self): + self._rtcout.RTC_TRACE("onFinalize()") + return RTC.RTC_OK - # ret must be RTC_OK - #assert(ret_ == RTC.RTC_OK) - self._sdoservice.init(self) - - return ret_ - - - ## - # @if jp - # - # @brief [CORBA interface] RTC λ - # - # Υڥ졼ƤӽФη̤Ȥ ComponentAction::on_finalize() - # ƤӽФ - # - # - # - RTC ExecutionContext ˽°Ƥ֤Ͻλʤξϡ - # ޤǽ ExecutionContextOperations::remove_component ˤäƻä - # ʤФʤʤʳξϡΥڥ졼ƤӽФ - # ʤ ReturnCode_t::PRECONDITION_NOT_ME ǼԤ롣 - # - RTC Created ֤Ǥ硢λϹԤʤ - # ξ硢Υڥ졼ƤӽФϤʤ - # ReturnCode_t::PRECONDITION_NOT_MET ǼԤ롣 - # - Υڥ졼RTCΥߥɥ륦ƤФ뤳ȤꤷƤꡢ - # ץꥱȯԤľܤΥڥ졼Ƥ֤Ȥ - # Ƥʤ - # - # @param self - # - # @return ReturnCode_t Υ꥿󥳡 - # - # @else - # - # @brief Finalize the RTC for preparing it for destruction - # - # This invocation of this operation shall result in the invocation of the - # callback ComponentAction::on_finalize. - # - # Constraints - # - An RTC may not be finalized while it is participating in any execution - # context. It must first be removed with - # ExecutionContextOperations::remove_component. Otherwise, this operation - # shall fail with ReturnCode_t::PRECONDITION_NOT_MET. - # - An RTC may not be finalized while it is in the Created state. Any - # attempt to invoke this operation while in that state shall fail with - # ReturnCode_t::PRECONDITION_NOT_MET. - # - Application developers are not expected to call this operation directly; - # it exists for use by the RTC infrastructure. - # - # @return - # - # @endif - def finalize(self): - self._rtcout.RTC_TRACE("finalize()") - - if self._created or not self._exiting: - return RTC.PRECONDITION_NOT_MET + ## + # @if jp + # + # @brief 開始処理用コールバック関数 + # + # ComponentAction::on_startup が呼ばれた際に実行されるコールバック + # 関数。
    + # 本関数は無条件に RTC::RTC_OK を返すようにダミー実装されているので、 + # 各コンポーネントの実際の開始処理は、本関数をオーバーライドして実装する + # 必要がある。 + # + # @param self + # @param ec_id 参加している ExecutionContext の ID + # + # @return ReturnCode_t 型のリターンコード + # + # @else + # + # @endif + + def onStartup(self, ec_id): + self._rtcout.RTC_TRACE("onStartup(%d)", ec_id) + return RTC.RTC_OK - # Return RTC::PRECONDITION_NOT_MET, - # When the component is registered in ExecutionContext. - if len(self._ecOther) != 0: - #for ec in self._ecOther: - #if not CORBA.is_nil(ec): - #return RTC.PRECONDITION_NOT_MET - - self._ecOther = [] - - ret = self.on_finalize() - self.shutdown() - return ret + ## + # @if jp + # + # @brief 停止処理用コールバック関数 + # + # ComponentAction::on_shutdown が呼ばれた際に実行されるコールバック + # 関数。
    + # 本関数は無条件に RTC::RTC_OK を返すようにダミー実装されているので、 + # 各コンポーネントの実際の停止処理は、本関数をオーバーライドして実装する + # 必要がある。 + # + # @param self + # @param ec_id 参加している ExecutionContext の ID + # + # @return ReturnCode_t 型のリターンコード + # + # @else + # + # @endif + + def onShutdown(self, ec_id): + self._rtcout.RTC_TRACE("onShutdown(%d)", ec_id) + return RTC.RTC_OK + ## + # @if jp + # + # @brief 活性化処理用コールバック関数 + # + # ComponentAction::on_activated が呼ばれた際に実行されるコールバック + # 関数。
    + # 本関数は無条件に RTC::RTC_OK を返すようにダミー実装されているので、 + # 各コンポーネントの実際の活性化処理は、本関数をオーバーライドして実装する + # 必要がある。 + # + # @param self + # @param ec_id 参加している ExecutionContext の ID + # + # @return ReturnCode_t 型のリターンコード + # + # @else + # + # @endif + + def onActivated(self, ec_id): + self._rtcout.RTC_TRACE("onActivated(%d)", ec_id) + return RTC.RTC_OK - ## - # @if jp - # - # @brief [CORBA interface] RTC ʡǤ ExecutionContext - # ߤΥƥĤȶ˽λ - # - # RTC ʡǤ뤹٤Ƥμ¹ԥƥȤߤ롣 - # RTC ¾μ¹ԥƥȤͭ RTC °¹ԥƥ - # (i.e. ¹ԥƥȤͭ RTC Ϥʤμ¹ԥƥȤ - # ʡǤ롣)˻äƤ硢 RTC ϤΥƥȾ - # ʤФʤʤ - # RTC ¹Τɤ ExecutionContext Ǥ Active ֤ǤϤʤʤä塢 - # RTC Ȥ˴ޤޤ RTC λ롣 - # - # - # - RTC ƤʤСλ뤳ȤϤǤʤ - # Created ֤ˤ RTC exit() ƤӽФ硢 - # ReturnCode_t::PRECONDITION_NOT_MET ǼԤ롣 - # - # @param self - # - # @return ReturnCode_t Υ꥿󥳡 - # - # @else - # - # @brief Stop the RTC's execution context(s) and finalize it along with its - # contents. - # - # Any execution contexts for which the RTC is the owner shall be stopped. - # If the RTC participates in any execution contexts belonging to another - # RTC that contains it, directly or indirectly (i.e. the containing RTC - # is the owner of the ExecutionContext), it shall be deactivated in those - # contexts. - # After the RTC is no longer Active in any Running execution context, it - # and any RTCs contained transitively within it shall be finalized. - # - # Constraints - # - An RTC cannot be exited if it has not yet been initialized. Any - # attempt to exit an RTC that is in the Created state shall fail with - # ReturnCode_t::PRECONDITION_NOT_MET. - # - # @return - # - # @endif - def exit(self): - self._rtcout.RTC_TRACE("exit()") - if self._created: - return RTC.PRECONDITION_NOT_MET - if self._exiting: - return RTC.RTC_OK - - organizations = self.get_organizations() - - - for o in organizations: - o.remove_member(self.getInstanceName()) - - - # deactivate myself on owned EC - OpenRTM_aist.CORBA_SeqUtil.for_each(self._ecMine, - self.deactivate_comps(self._objref)) - # deactivate myself on other EC - OpenRTM_aist.CORBA_SeqUtil.for_each(self._ecOther, - self.deactivate_comps(self._objref)) - - # stop and detach myself from owned EC - #for ec in self._ecMine: - # if not CORBA.is_nil(ec) or not ec._non_existent(): + ## + # @if jp + # + # @brief 非活性化処理用コールバック関数 + # + # ComponentAction::on_deactivated が呼ばれた際に実行されるコールバック + # 関数。
    + # 本関数は無条件に RTC::RTC_OK を返すようにダミー実装されているので、 + # 各コンポーネントの実際の非活性化処理は、本関数をオーバーライドして実装する + # 必要がある。 + # + # @param self + # @param ec_id 参加している ExecutionContext の ID + # + # @return ReturnCode_t 型のリターンコード + # + # @else + # + # @endif + + def onDeactivated(self, ec_id): + self._rtcout.RTC_TRACE("onDeactivated(%d)", ec_id) + return RTC.RTC_OK + + ## + # @if jp + # + # @brief 周期処理用コールバック関数 + # + # DataFlowComponentAction::on_execute が呼ばれた際に実行される + # コールバック関数。
    + # 本関数は無条件に RTC::RTC_OK を返すようにダミー実装されているので、 + # 各コンポーネントの実際の周期処理は、本関数をオーバーライドして実装する + # 必要がある。
    + # 本関数は Periodic Sampled Data Processing における Two-Pass Executionの + # 1回目の実行パスとして定期的に呼び出される。 + # + # @param self + # @param ec_id 参加している ExecutionContext の ID + # + # @return ReturnCode_t 型のリターンコード + # + # @else + # + # @endif + + def onExecute(self, ec_id): + self._rtcout.RTC_TRACE("onExecute(%d)", ec_id) + return RTC.RTC_OK + + ## + # @if jp + # + # @brief 中断処理用コールバック関数 + # + # ComponentAction::on_aborting が呼ばれた際に実行されるコールバック + # 関数。
    + # 本関数は無条件に RTC::RTC_OK を返すようにダミー実装されているので、 + # 各コンポーネントの実際の中断処理は、本関数をオーバーライドして実装する + # 必要がある。 + # + # @param self + # @param ec_id 参加している ExecutionContext の ID + # + # @return ReturnCode_t 型のリターンコード + # + # @else + # + # @endif + + def onAborting(self, ec_id): + self._rtcout.RTC_TRACE("onAborting(%d)", ec_id) + return RTC.RTC_OK + + ## + # @if jp + # + # @brief エラー処理用コールバック関数 + # + # ComponentAction::on_error が呼ばれた際に実行されるコールバック関数。
    + # 本関数は無条件に RTC::RTC_OK を返すようにダミー実装されているので、 + # 各コンポーネントの実際のエラー処理は、本関数をオーバーライドして実装する + # 必要がある。 + # + # @param self + # @param ec_id 参加している ExecutionContext の ID + # + # @return ReturnCode_t 型のリターンコード + # + # @else + # + # @endif + + def onError(self, ec_id): + self._rtcout.RTC_TRACE("onError(%d)", ec_id) + return RTC.RTC_OK + + ## + # @if jp + # + # @brief リセット処理用コールバック関数 + # + # ComponentAction::on_reset が呼ばれた際に実行されるコールバック関数。
    + # 本関数は無条件に RTC::RTC_OK を返すようにダミー実装されているので、 + # 各コンポーネントの実際のリセット処理は、本関数をオーバーライドして実装する + # 必要がある。 + # + # @param self + # @param ec_id 参加している ExecutionContext の ID + # + # @return ReturnCode_t 型のリターンコード + # + # @else + # + # @endif + + def onReset(self, ec_id): + self._rtcout.RTC_TRACE("onReset(%d)", ec_id) + return RTC.RTC_OK + + ## + # @if jp + # + # @brief 状態変更処理用コールバック関数 + # + # DataFlowComponentAction::on_state_update が呼ばれた際に実行される + # コールバック関数。
    + # 本関数は無条件に RTC::RTC_OK を返すようにダミー実装されているので、 + # 各コンポーネントの実際の状態変更処理は、本関数をオーバーライドして実装する + # 必要がある。
    + # 本関数は Periodic Sampled Data Processing における Two-Pass Executionの + # 2回目の実行パスとして定期的に呼び出される。 + # + # @param self + # @param ec_id 参加している ExecutionContext の ID + # + # @return ReturnCode_t 型のリターンコード + # + # @else + # + # @endif + + def onStateUpdate(self, ec_id): + self._rtcout.RTC_TRACE("onStateupdate(%d)", ec_id) + return RTC.RTC_OK + + ## + # @if jp + # + # @brief 動作周期変更通知用コールバック関数 + # + # DataFlowComponentAction::on_rate_changed が呼ばれた際に実行される + # コールバック関数。
    + # 本関数は無条件に RTC::RTC_OK を返すようにダミー実装されているので、 + # 各コンポーネントの実際の状態変更処理は、本関数をオーバーライドして実装する + # 必要がある。
    + # 本関数は Periodic Sampled Data Processing において ExecutionContext の + # 実行が更新された際に呼び出される。 + # + # @param self + # @param ec_id 参加している ExecutionContext の ID + # + # @return ReturnCode_t 型のリターンコード + # + # @else + # + # @endif + + def onRateChanged(self, ec_id): + self._rtcout.RTC_TRACE("onRatechanged(%d)", ec_id) + return RTC.RTC_OK + + ## + # @if jp + # + # @brief + # + # @param self + # @param ec_id 参加している ExecutionContext の ID + # + # @return ReturnCode_t 型のリターンコード + # + # @else + # + # @endif + def onAction(self, ec_id): + self._rtcout.RTC_TRACE("onAction(%d)", ec_id) + return RTC.RTC_OK + + # ============================================================ + # RTC::LightweightRTObject + # ============================================================ + + ## + # @if jp + # + # @brief [CORBA interface] RTCを初期化する + # + # このオペレーション呼び出しの結果として、ComponentAction::on_initialize + # コールバック関数が呼ばれる。 + # + # 制約 + # - RTC は Created状態の場合み初期化が行われる。他の状態にいる場合には + # ReturnCode_t::PRECONDITION_NOT_MET が返され呼び出しは失敗する。 + # - このオペレーションは RTC のミドルウエアから呼ばれることを想定しており、 + # アプリケーション開発者は直接このオペレーションを呼ぶことは想定 + # されていない。 + # + # @param self + # + # @return ReturnCode_t 型のリターンコード + # + # @else + # + # @brief Initialize the RTC that realizes this interface. + # + # The invocation of this operation shall result in the invocation of the + # callback ComponentAction::on_initialize. + # + # Constraints + # - An RTC may be initialized only while it is in the Created state. Any + # attempt to invoke this operation while in another state shall fail + # with ReturnCode_t::PRECONDITION_NOT_MET. + # - Application developers are not expected to call this operation + # directly; it exists for use by the RTC infrastructure. + # + # @return + # + # @endif + + def initialize(self): + self._rtcout.RTC_TRACE("initialize()") + + # EC creation + ec_args_ = [] + ret, ec_args_ = self.getContextOptions(ec_args_) + if ret != RTC.RTC_OK: + self._rtcout.RTC_ERROR( + "Valid EC options are not available. Aborting") + return RTC.BAD_PARAMETER + + if self.createContexts(ec_args_) != RTC.RTC_OK: + self._rtcout.RTC_ERROR( + "EC creation failed. Maybe out of resources. Aborting.") + return RTC.OUT_OF_RESOURCES + + # -- entering alive state -- + def toSTR_(x): return " was" if len(x) == 1 else "s were" + self._rtcout.RTC_INFO("%d execution context%s created.", + (len(self._ecMine), toSTR_(self._ecMine))) + + ret_ = self.on_initialize() + self._created = False + if ret_ != RTC.RTC_OK: + self._rtcout.RTC_ERROR("on_initialize() failed.") + return ret_ + + self._rtcout.RTC_DEBUG("on_initialize() was properly done.") + for (idx_, ec_) in enumerate(self._ecMine): + self._rtcout.RTC_DEBUG("EC[%d] starting.", idx_) + ec_.start() + + # ret must be RTC_OK + #assert(ret_ == RTC.RTC_OK) + self._sdoservice.init(self) + + return ret_ + + ## + # @if jp + # + # @brief [CORBA interface] RTC を終了する + # + # このオペレーション呼び出しの結果として ComponentAction::on_finalize() + # を呼び出す。 + # + # 制約 + # - RTC が ExecutionContext に所属している間は終了されない。この場合は、 + # まず最初に ExecutionContextOperations::remove_component によって参加を + # 解除しなければならない。これ以外の場合は、このオペレーション呼び出しは + # いかなる場合も ReturnCode_t::PRECONDITION_NOT_ME で失敗する。 + # - RTC が Created 状態である場合、終了処理は行われない。 + # この場合、このオペレーション呼び出しはいかなる場合も + # ReturnCode_t::PRECONDITION_NOT_MET で失敗する。 + # - このオペレーションはRTCのミドルウエアから呼ばれることを想定しており、 + # アプリケーション開発者は直接このオペレーションを呼ぶことは想定 + # されていない。 + # + # @param self + # + # @return ReturnCode_t 型のリターンコード + # + # @else + # + # @brief Finalize the RTC for preparing it for destruction + # + # This invocation of this operation shall result in the invocation of the + # callback ComponentAction::on_finalize. + # + # Constraints + # - An RTC may not be finalized while it is participating in any execution + # context. It must first be removed with + # ExecutionContextOperations::remove_component. Otherwise, this operation + # shall fail with ReturnCode_t::PRECONDITION_NOT_MET. + # - An RTC may not be finalized while it is in the Created state. Any + # attempt to invoke this operation while in that state shall fail with + # ReturnCode_t::PRECONDITION_NOT_MET. + # - Application developers are not expected to call this operation directly; + # it exists for use by the RTC infrastructure. + # + # @return + # + # @endif + + def finalize(self): + self._rtcout.RTC_TRACE("finalize()") + + if self._created or not self._exiting: + return RTC.PRECONDITION_NOT_MET + + # Return RTC::PRECONDITION_NOT_MET, + # When the component is registered in ExecutionContext. + if self._ecOther: + self._ecOther = [] + + ret = self.on_finalize() + self.shutdown() + return ret + + ## + # @if jp + # + # @brief [CORBA interface] RTC がオーナーである ExecutionContext を + # 停止させ、そのコンテンツと共に終了させる + # + # この RTC がオーナーであるすべての実行コンテキストを停止する。 + # この RTC が他の実行コンテキストを所有する RTC に属する実行コンテキスト + # (i.e. 実行コンテキストを所有する RTC はすなわちその実行コンテキストの + # オーナーである。)に参加している場合、当該 RTC はそれらのコンテキスト上 + # で非活性化されなければならない。 + # RTC が実行中のどの ExecutionContext でも Active 状態ではなくなった後、 + # この RTC とこれに含まれる RTC が終了する。 + # + # 制約 + # - RTC が初期化されていなければ、終了させることはできない。 + # Created 状態にある RTC に exit() を呼び出した場合、 + # ReturnCode_t::PRECONDITION_NOT_MET で失敗する。 + # + # @param self + # + # @return ReturnCode_t 型のリターンコード + # + # @else + # + # @brief Stop the RTC's execution context(s) and finalize it along with its + # contents. + # + # Any execution contexts for which the RTC is the owner shall be stopped. + # If the RTC participates in any execution contexts belonging to another + # RTC that contains it, directly or indirectly (i.e. the containing RTC + # is the owner of the ExecutionContext), it shall be deactivated in those + # contexts. + # After the RTC is no longer Active in any Running execution context, it + # and any RTCs contained transitively within it shall be finalized. + # + # Constraints + # - An RTC cannot be exited if it has not yet been initialized. Any + # attempt to exit an RTC that is in the Created state shall fail with + # ReturnCode_t::PRECONDITION_NOT_MET. + # + # @return + # + # @endif + + def exit(self): + self._rtcout.RTC_TRACE("exit()") + if self._created: + return RTC.PRECONDITION_NOT_MET + if self._exiting: + return RTC.RTC_OK + + organizations = self.get_organizations() + + for o in organizations: + o.remove_member(self.getInstanceName()) + + # deactivate myself on owned EC + OpenRTM_aist.CORBA_SeqUtil.for_each(self._ecMine, + self.deactivate_comps(self._objref)) + # deactivate myself on other EC + OpenRTM_aist.CORBA_SeqUtil.for_each(self._ecOther, + self.deactivate_comps(self._objref)) + + # stop and detach myself from owned EC + # for ec in self._ecMine: + # if not CORBA.is_nil(ec) or not ec._non_existent(): # ret = ec.stop() # ec.remove_component(self._this()) - # pass - - - # detach myself from other EC - for ec in self._ecOther: - try: - if not CORBA.is_nil(ec) or not ec._non_existent(): - # ec.stop() - ec.remove_component(self._this()) - except: - pass - - - self._exiting = True - return self.finalize() - - - ## - # @if jp - # - # @brief [CORBA interface] RTC Alive ֤Ǥ뤫ɤǧ롣 - # - # RTC ꤷ ExecutionContext Ф Alive֤Ǥ뤫ɤǧ롣 - # RTC ξ֤ Active Ǥ뤫Inactive Ǥ뤫Error Ǥ뤫ϼ¹ - # ExecutionContext ˰¸롣ʤ ExecutionContext ФƤ - # Active ֤ǤäƤ⡢¾ ExecutionContext ФƤ Inactive ֤ - # ʤ⤢ꤨ롣äơΥڥ졼ϻꤵ줿 - # ExecutionContext 䤤碌ơ RTC ξ֤ ActiveInactive - # Error ξˤ Alive ֤Ȥ֤ - # - # @param self - # - # @param exec_context о ExecutionContext ϥɥ - # - # @return Alive ֳǧ - # - # @else - # - # @brief Confirm whether RTC is an Alive state or NOT. - # - # A component is alive or not regardless of the execution context from - # which it is observed. However, whether or not it is Active, Inactive, - # or in Error is dependent on the execution context(s) in which it is - # running. That is, it may be Active in one context but Inactive in - # another. Therefore, this operation shall report whether this RTC is - # either Active, Inactive or in Error; which of those states a component - # is in with respect to a particular context may be queried from the - # context itself. - # - # @return Result of Alive state confirmation - # - # @endif - # virtual CORBA::Boolean is_alive(ExecutionContext_ptr exec_context) - def is_alive(self, exec_context): - self._rtcout.RTC_TRACE("is_alive()") - for ec in self._ecMine: - if exec_context._is_equivalent(ec): - return True + # pass + + # detach myself from other EC + for ec in self._ecOther: + try: + if not CORBA.is_nil(ec) or not ec._non_existent(): + # ec.stop() + ec.remove_component(self._this()) + except BaseException: + self._rtcout.RTC_ERROR("Unknown error") + + self._exiting = True + return self.finalize() + + ## + # @if jp + # + # @brief [CORBA interface] RTC が Alive 状態であるかどうか確認する。 + # + # RTC が指定した ExecutionContext に対して Alive状態であるかどうか確認する。 + # RTC の状態が Active であるか、Inactive であるか、Error であるかは実行中の + # ExecutionContext に依存する。すなわち、ある ExecutionContext に対しては + # Active 状態であっても、他の ExecutionContext に対しては Inactive 状態と + # なる場合もありえる。従って、このオペレーションは指定された + # ExecutionContext に問い合わせて、この RTC の状態が Active、Inactive、 + # Error の場合には Alive 状態として返す。 + # + # @param self + # + # @param exec_context 取得対象 ExecutionContext ハンドル + # + # @return Alive 状態確認結果 + # + # @else + # + # @brief Confirm whether RTC is an Alive state or NOT. + # + # A component is alive or not regardless of the execution context from + # which it is observed. However, whether or not it is Active, Inactive, + # or in Error is dependent on the execution context(s) in which it is + # running. That is, it may be Active in one context but Inactive in + # another. Therefore, this operation shall report whether this RTC is + # either Active, Inactive or in Error; which of those states a component + # is in with respect to a particular context may be queried from the + # context itself. + # + # @return Result of Alive state confirmation + # + # @endif + # virtual CORBA::Boolean is_alive(ExecutionContext_ptr exec_context) + + def is_alive(self, exec_context): + self._rtcout.RTC_TRACE("is_alive()") + for ec in self._ecMine: + if exec_context._is_equivalent(ec): + return True + + for ec in self._ecOther: + if not CORBA.is_nil(ec): + if exec_context._is_equivalent(ec): + return True + + return False + + ## + # @if jp + # @brief [CORBA interface] ExecutionContextListを取得する + # + # この RTC が所有する ExecutionContext のリストを取得する。 + # + # @param self + # + # @return ExecutionContext リスト + # + # @else + # @brief [CORBA interface] Get ExecutionContextList. + # + # This operation returns a list of all execution contexts owned by this RTC. + # + # @return ExecutionContext List + # + # @endif + # def get_contexts(self): + # execlist = [] + # OpenRTM_aist.CORBA_SeqUtil.for_each(self._execContexts, self.ec_copy(execlist)) + # return execlist + + ## + # @if jp + # @brief [CORBA interface] ExecutionContextを取得する + # + # 指定したハンドルの ExecutionContext を取得する。 + # ハンドルから ExecutionContext へのマッピングは、特定の RTC インスタンスに + # 固有である。ハンドルはこの RTC を attach_context した際に取得できる。 + # + # @param self + # @param ec_id 取得対象 ExecutionContext ハンドル + # + # @return ExecutionContext + # + # @else + # @brief [CORBA interface] Get ExecutionContext. + # + # Obtain a reference to the execution context represented by the given + # handle. + # The mapping from handle to context is specific to a particular RTC + # instance. The given handle must have been obtained by a previous call to + # attach_context on this RTC. + # + # @param ec_id ExecutionContext handle + # + # @return ExecutionContext + # + # @endif + # virtual ExecutionContext_ptr get_context(UniqueId exec_handle) + + def get_context(self, ec_id): + global ECOTHER_OFFSET + + self._rtcout.RTC_TRACE("get_context(%d)", ec_id) + # owned EC + if ec_id < ECOTHER_OFFSET: + if ec_id < len(self._ecMine): + return self._ecMine[ec_id] + else: + return RTC.ExecutionContext._nil + + # participating EC + index = ec_id - ECOTHER_OFFSET + + if index < len(self._ecOther): + if not CORBA.is_nil(self._ecOther[index]): + return self._ecOther[index] - for ec in self._ecOther: - if not CORBA.is_nil(ec): - if exec_context._is_equivalent(ec): - return True - - return False - - - ## - # @if jp - # @brief [CORBA interface] ExecutionContextList - # - # RTC ͭ ExecutionContext ΥꥹȤ롣 - # - # @param self - # - # @return ExecutionContext ꥹ - # - # @else - # @brief [CORBA interface] Get ExecutionContextList. - # - # This operation returns a list of all execution contexts owned by this RTC. - # - # @return ExecutionContext List - # - # @endif - #def get_contexts(self): - # execlist = [] - # OpenRTM_aist.CORBA_SeqUtil.for_each(self._execContexts, self.ec_copy(execlist)) - # return execlist - - - ## - # @if jp - # @brief [CORBA interface] ExecutionContext - # - # ꤷϥɥ ExecutionContext 롣 - # ϥɥ뤫 ExecutionContext ؤΥޥåԥ󥰤ϡ RTC 󥹥󥹤 - # ͭǤ롣ϥɥϤ RTC attach_context ݤ˼Ǥ롣 - # - # @param self - # @param ec_id о ExecutionContext ϥɥ - # - # @return ExecutionContext - # - # @else - # @brief [CORBA interface] Get ExecutionContext. - # - # Obtain a reference to the execution context represented by the given - # handle. - # The mapping from handle to context is specific to a particular RTC - # instance. The given handle must have been obtained by a previous call to - # attach_context on this RTC. - # - # @param ec_id ExecutionContext handle - # - # @return ExecutionContext - # - # @endif - # virtual ExecutionContext_ptr get_context(UniqueId exec_handle) - def get_context(self, ec_id): - global ECOTHER_OFFSET - - self._rtcout.RTC_TRACE("get_context(%d)", ec_id) - # owned EC - if ec_id < ECOTHER_OFFSET: - if ec_id < len(self._ecMine): - return self._ecMine[ec_id] - else: return RTC.ExecutionContext._nil - # participating EC - index = ec_id - ECOTHER_OFFSET - - if index < len(self._ecOther): - if not CORBA.is_nil(self._ecOther[index]): - return self._ecOther[index] - - return RTC.ExecutionContext._nil - - - ## - # @if jp - # @brief [CORBA interface] ͭ ExecutionContextList - # - # RTC ͭ ExecutionContext ΥꥹȤ롣 - # - # @return ExecutionContext ꥹ - # - # @else - # @brief [CORBA interface] Get ExecutionContextList. - # - # This operation returns a list of all execution contexts owned by this - # RTC. - # - # @return ExecutionContext List - # - # @endif - # virtual ExecutionContextList* get_owned_contexts() - def get_owned_contexts(self): - self._rtcout.RTC_TRACE("get_owned_contexts()") - execlist = [] - OpenRTM_aist.CORBA_SeqUtil.for_each(self._ecMine, self.ec_copy(execlist)) - return execlist - - ## - # @if jp - # @brief [CORBA interface] äƤ ExecutionContextList - # - # RTC äƤ ExecutionContext ΥꥹȤ롣 - # - # @return ExecutionContext ꥹ - # - # @else - # @brief [CORBA interface] Get participating ExecutionContextList. - # - # This operation returns a list of all execution contexts in - # which this RTC participates. - # - # @return ExecutionContext List - # - # @endif - # virtual ExecutionContextList* get_participating_contexts() - def get_participating_contexts(self): - self._rtcout.RTC_TRACE("get_participating_contexts()") - execlist = [] - OpenRTM_aist.CORBA_SeqUtil.for_each(self._ecOther, self.ec_copy(execlist)) - return execlist - - - # - # @if jp - # @brief [CORBA interface] ExecutionContext Υϥɥ֤ - # - # @param ExecutionContext ¹ԥƥ - # - # @return ExecutionContextHandle - # - # Ϳ줿¹ԥƥȤ˴Ϣդ줿ϥɥ֤ - # - # @else - # @brief [CORBA interface] Return a handle of a ExecutionContext - # - # @param ExecutionContext - # - # @return ExecutionContextHandle - # - # This operation returns a handle that is associated with the given - # execution context. - # - # @endif - # - # virtual ExecutionContextHandle_t - # get_context_handle(ExecutionContext_ptr cxt) - def get_context_handle(self, cxt): - self._rtcout.RTC_TRACE("get_context_handle()") - - num = OpenRTM_aist.CORBA_SeqUtil.find(self._ecMine, self.ec_find(cxt)) - if num != -1: - return int(num) - - num = OpenRTM_aist.CORBA_SeqUtil.find(self._ecOther, self.ec_find(cxt)) - if num != -1: - return int(num) + 1000 - - return int(-1) - - - #============================================================ - # RTC::RTObject - #============================================================ - - ## - # @if jp - # - # @brief [RTObject CORBA interface] ݡͥȥץե - # - # ݡͥȤΥץե֤ - # - # @param self - # - # @return ݡͥȥץե - # - # @else - # - # @brief [RTObject CORBA interface] Get RTC's profile - # - # This operation returns the ComponentProfile of the RTC - # - # @return ComponentProfile - # - # @endif - # virtual ComponentProfile* get_component_profile() - def get_component_profile(self): - self._rtcout.RTC_TRACE("get_component_profile()") - prop_ = RTC.ComponentProfile(self._properties.getProperty("instance_name"), - self._properties.getProperty("type_name"), - self._properties.getProperty("description"), - self._properties.getProperty("version"), - self._properties.getProperty("vendor"), - self._properties.getProperty("category"), - self._portAdmin.getPortProfileList(), - self._profile.parent, - self._profile.properties) - OpenRTM_aist.NVUtil.copyFromProperties(self._profile.properties, self._properties) - return prop_ - # return RTC.ComponentProfile(self._profile.instance_name, - # self._profile.type_name, - # self._profile.description, - # self._profile.version, - # self._profile.vendor, - # self._profile.category, - # self._portAdmin.getPortProfileList(), - # self._profile.parent, - # self._profile.properties) - - #except: - # self._rtcout.RTC_ERROR(OpenRTM_aist.Logger.print_exception()) - - - #return None - - - ## - # @if jp - # - # @brief [RTObject CORBA interface] ݡȤ - # - # ݡͥȤͭݡȤλȤ֤ - # - # @param self - # - # @return ݡȥꥹ - # - # @else - # - # @brief [RTObject CORBA interface] Get Ports - # - # This operation returns a list of the RTCs ports. - # - # @return PortList - # - # @endif - # virtual PortServiceList* get_ports() - def get_ports(self): - self._rtcout.RTC_TRACE("get_ports()") - - return self._portAdmin.getPortServiceList() - - - - - - # RTC::ComponentAction - - ## - # @if jp - # @brief [CORBA interface] ExecutionContextattach - # - # ꤷ ExecutionContext ˤ RTC °롣 RTC ȴϢ - # ExecutionContext Υϥɥ֤ - # Υڥ졼ϡExecutionContextOperations::add_component ƤФ줿 - # ݤ˸ƤӽФ롣֤줿ϥɥ¾Υ饤ȤǻѤ뤳Ȥ - # Ƥʤ - # - # @param self - # @param exec_context ° ExecutionContext - # - # @return ExecutionContext ϥɥ - # - # @else - # @brief [CORBA interface] Attach ExecutionContext. - # - # Inform this RTC that it is participating in the given execution context. - # Return a handle that represents the association of this RTC with the - # context. - # This operation is intended to be invoked by - # ExecutionContextOperations::add_component. It is not intended for use by - # other clients. - # - # @param exec_context Prticipating ExecutionContext - # - # @return ExecutionContext Handle - # - # @endif - # UniqueId attach_context(ExecutionContext_ptr exec_context) - def attach_context(self, exec_context): - global ECOTHER_OFFSET - self._rtcout.RTC_TRACE("attach_context()") - # ID: 0 - (offset-1) : owned ec - # ID: offset - : participating ec - # owned ec index = ID - # participate ec index = ID - offset - ecs = exec_context._narrow(RTC.ExecutionContextService) - if CORBA.is_nil(ecs): - return -1 - - # if m_ecOther has nil element, insert attached ec to there. - for i in range(len(self._ecOther)): - if CORBA.is_nil(self._ecOther[i]): - self._ecOther[i] = ecs - ec_id = i + ECOTHER_OFFSET + ## + # @if jp + # @brief [CORBA interface] 所有する ExecutionContextListを 取得する + # + # この RTC が所有する ExecutionContext のリストを取得する。 + # + # @return ExecutionContext リスト + # + # @else + # @brief [CORBA interface] Get ExecutionContextList. + # + # This operation returns a list of all execution contexts owned by this + # RTC. + # + # @return ExecutionContext List + # + # @endif + # virtual ExecutionContextList* get_owned_contexts() + + def get_owned_contexts(self): + self._rtcout.RTC_TRACE("get_owned_contexts()") + execlist = [] + OpenRTM_aist.CORBA_SeqUtil.for_each( + self._ecMine, self.ec_copy(execlist)) + return execlist + + ## + # @if jp + # @brief [CORBA interface] 参加している ExecutionContextList を取得する + # + # この RTC が参加している ExecutionContext のリストを取得する。 + # + # @return ExecutionContext リスト + # + # @else + # @brief [CORBA interface] Get participating ExecutionContextList. + # + # This operation returns a list of all execution contexts in + # which this RTC participates. + # + # @return ExecutionContext List + # + # @endif + # virtual ExecutionContextList* get_participating_contexts() + def get_participating_contexts(self): + self._rtcout.RTC_TRACE("get_participating_contexts()") + execlist = [] + OpenRTM_aist.CORBA_SeqUtil.for_each( + self._ecOther, self.ec_copy(execlist)) + return execlist + + # + # @if jp + # @brief [CORBA interface] ExecutionContext のハンドルを返す + # + # @param ExecutionContext 実行コンテキスト + # + # @return ExecutionContextHandle + # + # 与えられた実行コンテキストに関連付けられたハンドルを返す。 + # + # @else + # @brief [CORBA interface] Return a handle of a ExecutionContext + # + # @param ExecutionContext + # + # @return ExecutionContextHandle + # + # This operation returns a handle that is associated with the given + # execution context. + # + # @endif + # + # virtual ExecutionContextHandle_t + # get_context_handle(ExecutionContext_ptr cxt) + + def get_context_handle(self, cxt): + self._rtcout.RTC_TRACE("get_context_handle()") + + num = OpenRTM_aist.CORBA_SeqUtil.find(self._ecMine, self.ec_find(cxt)) + if num != -1: + return int(num) + + num = OpenRTM_aist.CORBA_SeqUtil.find(self._ecOther, self.ec_find(cxt)) + if num != -1: + return int(num) + 1000 + + return int(-1) + + # ============================================================ + # RTC::RTObject + # ============================================================ + + ## + # @if jp + # + # @brief [RTObject CORBA interface] コンポーネントプロファイルを取得する + # + # 当該コンポーネントのプロファイル情報を返す。 + # + # @param self + # + # @return コンポーネントプロファイル + # + # @else + # + # @brief [RTObject CORBA interface] Get RTC's profile + # + # This operation returns the ComponentProfile of the RTC + # + # @return ComponentProfile + # + # @endif + # virtual ComponentProfile* get_component_profile() + + def get_component_profile(self): + self._rtcout.RTC_TRACE("get_component_profile()") + prop_ = RTC.ComponentProfile(self._properties.getProperty("instance_name"), + self._properties.getProperty("type_name"), + self._properties.getProperty( + "description"), + self._properties.getProperty("version"), + self._properties.getProperty("vendor"), + self._properties.getProperty("category"), + self._portAdmin.getPortProfileList(), + self._profile.parent, + self._profile.properties) + OpenRTM_aist.NVUtil.copyFromProperties( + self._profile.properties, self._properties) + return prop_ + # return RTC.ComponentProfile(self._profile.instance_name, + # self._profile.type_name, + # self._profile.description, + # self._profile.version, + # self._profile.vendor, + # self._profile.category, + # self._portAdmin.getPortProfileList(), + # self._profile.parent, + # self._profile.properties) + + # except: + # self._rtcout.RTC_ERROR(OpenRTM_aist.Logger.print_exception()) + + # return None + + ## + # @if jp + # + # @brief [RTObject CORBA interface] ポートを取得する + # + # 当該コンポーネントが保有するポートの参照を返す。 + # + # @param self + # + # @return ポートリスト + # + # @else + # + # @brief [RTObject CORBA interface] Get Ports + # + # This operation returns a list of the RTCs ports. + # + # @return PortList + # + # @endif + # virtual PortServiceList* get_ports() + + def get_ports(self): + self._rtcout.RTC_TRACE("get_ports()") + + return self._portAdmin.getPortServiceList() + + # RTC::ComponentAction + + ## + # @if jp + # @brief [CORBA interface] ExecutionContextをattachする + # + # 指定した ExecutionContext にこの RTC を所属させる。この RTC と関連する + # ExecutionContext のハンドルを返す。 + # このオペレーションは、ExecutionContextOperations::add_component が呼ばれた + # 際に呼び出される。返されたハンドルは他のクライアントで使用することを想定 + # していない。 + # + # @param self + # @param exec_context 所属先 ExecutionContext + # + # @return ExecutionContext ハンドル + # + # @else + # @brief [CORBA interface] Attach ExecutionContext. + # + # Inform this RTC that it is participating in the given execution context. + # Return a handle that represents the association of this RTC with the + # context. + # This operation is intended to be invoked by + # ExecutionContextOperations::add_component. It is not intended for use by + # other clients. + # + # @param exec_context Prticipating ExecutionContext + # + # @return ExecutionContext Handle + # + # @endif + # UniqueId attach_context(ExecutionContext_ptr exec_context) + + def attach_context(self, exec_context): + global ECOTHER_OFFSET + self._rtcout.RTC_TRACE("attach_context()") + # ID: 0 - (offset-1) : owned ec + # ID: offset - : participating ec + # owned ec index = ID + # participate ec index = ID - offset + ecs = exec_context._narrow(RTC.ExecutionContextService) + if CORBA.is_nil(ecs): + return -1 + + # if m_ecOther has nil element, insert attached ec to there. + for i, ec in enumerate(self._ecOther): + if CORBA.is_nil(ec): + self._ecOther[i] = ecs + ec_id = i + ECOTHER_OFFSET + self.onAttachExecutionContext(ec_id) + return ec_id + + # no space in the list, push back ec to the last. + OpenRTM_aist.CORBA_SeqUtil.push_back(self._ecOther, ecs) + ec_id = int(len(self._ecOther) - 1 + ECOTHER_OFFSET) self.onAttachExecutionContext(ec_id) return ec_id - # no space in the list, push back ec to the last. - OpenRTM_aist.CORBA_SeqUtil.push_back(self._ecOther,ecs) - ec_id = int(len(self._ecOther) - 1 + ECOTHER_OFFSET) - self.onAttachExecutionContext(ec_id) - return ec_id - - - # UniqueId bindContext(ExecutionContext_ptr exec_context); - def bindContext(self, exec_context): - global ECOTHER_OFFSET - self._rtcout.RTC_TRACE("bindContext()") - # ID: 0 - (offset-1) : owned ec - # ID: offset - : participating ec - # owned ec index = ID - # participate ec index = ID - offset - ecs = exec_context._narrow(RTC.ExecutionContextService) - - if CORBA.is_nil(ecs): - return -1 - - # if m_ecMine has nil element, insert attached ec to there. - for i in range(len(self._ecMine)): - if CORBA.is_nil(self._ecMine[i]): - self._ecMine[i] = ecs - self.onAttachExecutionContext(i) - return i - #return i + ECOTHER_OFFSET - - # no space in the list, push back ec to the last. - OpenRTM_aist.CORBA_SeqUtil.push_back(self._ecMine,ecs) - - return int(len(self._ecMine) - 1) - #return int(len(self._ecMine) - 1 + ECOTHER_OFFSET) - - - ## - # @if jp - # @brief [CORBA interface] ExecutionContextdetach - # - # ꤷ ExecutionContext 餳 RTC ν°롣 - # Υڥ졼ϡExecutionContextOperations::remove_component Ƥ - # 줿ݤ˸ƤӽФ롣֤줿ϥɥ¾Υ饤ȤǻѤ뤳Ȥ - # ꤷƤʤ - # - # - # - ꤵ줿 ExecutionContext RTC Ǥ˽°Ƥʤˤϡ - # ReturnCode_t::PRECONDITION_NOT_MET ֤롣 - # - ꤵ줿 ExecutionContext ˤФ RTC Active ֤Ǥ - # ˤϡ ReturnCode_t::PRECONDITION_NOT_MET ֤롣 - # - # @param self - # @param ec_id о ExecutionContextϥɥ - # - # @return ReturnCode_t Υ꥿󥳡 - # - # @else - # @brief [CORBA interface] Attach ExecutionContext. - # - # Inform this RTC that it is no longer participating in the given execution - # context. - # This operation is intended to be invoked by - # ExecutionContextOperations::remove_component. It is not intended for use - # by other clients. - # Constraints - # - This operation may not be invoked if this RTC is not already - # participating in the execution context. Such a call shall fail with - # ReturnCode_t::PRECONDITION_NOT_MET. - # - This operation may not be invoked if this RTC is Active in the indicated - # execution context. Otherwise, it shall fail with - # ReturnCode_t::PRECONDITION_NOT_MET. - # - # @param ec_id Dettaching ExecutionContext Handle - # - # @return - # - # @endif - # ReturnCode_t detach_context(UniqueId exec_handle) - def detach_context(self, ec_id): - global ECOTHER_OFFSET - self._rtcout.RTC_TRACE("detach_context(%d)", ec_id) - len_ = len(self._ecOther) - - # ID: 0 - (offset-1) : owned ec - # ID: offset - : participating ec - # owned ec index = ID - # participate ec index = ID - offset - if (int(ec_id) < int(ECOTHER_OFFSET)) or \ - (int(ec_id - ECOTHER_OFFSET) > len_): - return RTC.BAD_PARAMETER - - index = int(ec_id - ECOTHER_OFFSET) - - if index < 0 or CORBA.is_nil(self._ecOther[index]): - return RTC.BAD_PARAMETER - - #OpenRTM_aist.CORBA_SeqUtil.erase(self._ecOther, index) - self._ecOther[index] = RTC.ExecutionContextService._nil - self.onDetachExecutionContext(ec_id) - return RTC.RTC_OK - - - ## - # @if jp - # - # @brief [ComponentAction CORBA interface] RTC ν - # - # RTC 졢Alive ֤ܤ롣 - # RTC ͭνϤǼ¹Ԥ롣 - # Υڥ졼ƤӽФη̤Ȥ onInitialize() Хåؿ - # ƤӽФ롣 - # - # @param self - # - # @return ReturnCode_t Υ꥿󥳡 - # - # @else - # - # @brief [ComponentAction CORBA interface] Initialize RTC - # - # The RTC has been initialized and entered the Alive state. - # Any RTC-specific initialization logic should be performed here. - # - # @return - # - # @endif - def on_initialize(self): - self._rtcout.RTC_TRACE("on_initialize()") - ret = RTC.RTC_ERROR - try: - self.preOnInitialize(0) - self._rtcout.RTC_DEBUG("Calling onInitialize().") - ret = self.onInitialize() - if ret != RTC.RTC_OK: - self._rtcout.RTC_ERROR("onInitialize() returns an ERROR (%d)", ret._v) - else: - self._rtcout.RTC_DEBUG("onInitialize() succeeded.") - - except: - self._rtcout.RTC_ERROR(OpenRTM_aist.Logger.print_exception()) - ret = RTC.RTC_ERROR - - active_set = self._properties.getProperty("configuration.active_config", - "default") - - if self._configsets.haveConfig(active_set): - self._rtcout.RTC_DEBUG("Active configuration set: %s exists.", active_set) - self._configsets.activateConfigurationSet(active_set) - self._configsets.update(active_set) - self._rtcout.RTC_INFO("Initial active configuration set is %s.", active_set) - else: - self._rtcout.RTC_DEBUG("Active configuration set: %s does not exists.", active_set) - self._configsets.activateConfigurationSet("default") - self._configsets.update("default") - self._rtcout.RTC_INFO("Initial active configuration set is default-set.") - - self.postOnInitialize(0,ret) - return ret + # UniqueId bindContext(ExecutionContext_ptr exec_context); + + def bindContext(self, exec_context): + global ECOTHER_OFFSET + self._rtcout.RTC_TRACE("bindContext()") + # ID: 0 - (offset-1) : owned ec + # ID: offset - : participating ec + # owned ec index = ID + # participate ec index = ID - offset + ecs = exec_context._narrow(RTC.ExecutionContextService) + + if CORBA.is_nil(ecs): + return -1 + + # if m_ecMine has nil element, insert attached ec to there. + for i, ec in enumerate(self._ecMine): + if CORBA.is_nil(ec): + self._ecMine[i] = ecs + self.onAttachExecutionContext(i) + return i + # return i + ECOTHER_OFFSET + + # no space in the list, push back ec to the last. + OpenRTM_aist.CORBA_SeqUtil.push_back(self._ecMine, ecs) + + return int(len(self._ecMine) - 1) + # return int(len(self._ecMine) - 1 + ECOTHER_OFFSET) + + ## + # @if jp + # @brief [CORBA interface] ExecutionContextをdetachする + # + # 指定した ExecutionContext からこの RTC の所属を解除する。 + # このオペレーションは、ExecutionContextOperations::remove_component が呼ば + # れた際に呼び出される。返されたハンドルは他のクライアントで使用することを + # 想定していない。 + # + # 制約 + # - 指定された ExecutionContext に RTC がすでに所属していない場合には、 + # ReturnCode_t::PRECONDITION_NOT_MET が返される。 + # - 指定された ExecutionContext にたしいて対して RTC がActive 状態である場 + # 合には、 ReturnCode_t::PRECONDITION_NOT_MET が返される。 + # + # @param self + # @param ec_id 解除対象 ExecutionContextハンドル + # + # @return ReturnCode_t 型のリターンコード + # + # @else + # @brief [CORBA interface] Attach ExecutionContext. + # + # Inform this RTC that it is no longer participating in the given execution + # context. + # This operation is intended to be invoked by + # ExecutionContextOperations::remove_component. It is not intended for use + # by other clients. + # Constraints + # - This operation may not be invoked if this RTC is not already + # participating in the execution context. Such a call shall fail with + # ReturnCode_t::PRECONDITION_NOT_MET. + # - This operation may not be invoked if this RTC is Active in the indicated + # execution context. Otherwise, it shall fail with + # ReturnCode_t::PRECONDITION_NOT_MET. + # + # @param ec_id Dettaching ExecutionContext Handle + # + # @return + # + # @endif + # ReturnCode_t detach_context(UniqueId exec_handle) + + def detach_context(self, ec_id): + global ECOTHER_OFFSET + self._rtcout.RTC_TRACE("detach_context(%d)", ec_id) + len_ = len(self._ecOther) + + # ID: 0 - (offset-1) : owned ec + # ID: offset - : participating ec + # owned ec index = ID + # participate ec index = ID - offset + if (int(ec_id) < int(ECOTHER_OFFSET)) or \ + (int(ec_id - ECOTHER_OFFSET) >= len_): + return RTC.BAD_PARAMETER + + index = int(ec_id - ECOTHER_OFFSET) + + if index < 0 or CORBA.is_nil(self._ecOther[index]): + return RTC.BAD_PARAMETER + + #OpenRTM_aist.CORBA_SeqUtil.erase(self._ecOther, index) + self._ecOther[index] = RTC.ExecutionContextService._nil + self.onDetachExecutionContext(ec_id) + return RTC.RTC_OK + ## + # @if jp + # + # @brief [ComponentAction CORBA interface] RTC の初期化 + # + # RTC が初期化され、Alive 状態に遷移する。 + # RTC 固有の初期化処理はここで実行する。 + # このオペレーション呼び出しの結果として onInitialize() コールバック関数が + # 呼び出される。 + # + # @param self + # + # @return ReturnCode_t 型のリターンコード + # + # @else + # + # @brief [ComponentAction CORBA interface] Initialize RTC + # + # The RTC has been initialized and entered the Alive state. + # Any RTC-specific initialization logic should be performed here. + # + # @return + # + # @endif + + def on_initialize(self): + self._rtcout.RTC_TRACE("on_initialize()") + ret = RTC.RTC_ERROR + try: + self.preOnInitialize(0) + self._rtcout.RTC_DEBUG("Calling onInitialize().") + ret = self.onInitialize() + if ret != RTC.RTC_OK: + self._rtcout.RTC_ERROR( + "onInitialize() returns an ERROR (%d)", ret._v) + else: + self._rtcout.RTC_DEBUG("onInitialize() succeeded.") + + except BaseException: + self._rtcout.RTC_ERROR(OpenRTM_aist.Logger.print_exception()) + ret = RTC.RTC_ERROR + + active_set = self._properties.getProperty("configuration.active_config", + "default") + + if self._configsets.haveConfig(active_set): + self._rtcout.RTC_DEBUG( + "Active configuration set: %s exists.", active_set) + self._configsets.activateConfigurationSet(active_set) + self._configsets.update(active_set) + self._rtcout.RTC_INFO( + "Initial active configuration set is %s.", active_set) + else: + self._rtcout.RTC_DEBUG( + "Active configuration set: %s does not exists.", active_set) + self._configsets.activateConfigurationSet("default") + self._configsets.update("default") + self._rtcout.RTC_INFO( + "Initial active configuration set is default-set.") + + self.postOnInitialize(0, ret) + return ret + + ## + # @if jp + # + # @brief [ComponentAction CORBA interface] RTC の終了 + # + # RTC が破棄される。 + # RTC 固有の終了処理はここで実行する。 + # このオペレーション呼び出しの結果として onFinalize() コールバック関数が + # 呼び出される。 + # + # @param self + # + # @return ReturnCode_t 型のリターンコード + # + # @else + # + # @brief [ComponentAction CORBA interface] Finalize RTC + # + # The RTC is being destroyed. + # Any final RTC-specific tear-down logic should be performed here. + # + # @return + # + # @endif + + def on_finalize(self): + self._rtcout.RTC_TRACE("on_finalize()") + ret = RTC.RTC_ERROR + try: + self.preOnFinalize(0) + ret = self.onFinalize() + except BaseException: + self._rtcout.RTC_ERROR(OpenRTM_aist.Logger.print_exception()) + ret = RTC.RTC_ERROR + self.postOnFinalize(0, ret) + return ret + + ## + # @if jp + # + # @brief [ComponentAction CORBA interface] RTC の開始 + # + # RTC が所属する ExecutionContext が Stopped 状態から Running 状態へ遷移 + # した場合に呼び出される。 + # このオペレーション呼び出しの結果として onStartup() コールバック関数が + # 呼び出される。 + # + # @param self + # @param ec_id 状態遷移した ExecutionContext の ID + # + # @return ReturnCode_t 型のリターンコード + # + # @else + # + # @brief [ComponentAction CORBA interface] StartUp RTC + # + # The given execution context, in which the RTC is participating, has + # transitioned from Stopped to Running. + # + # @param ec_id + # + # @return + # + # @endif + + def on_startup(self, ec_id): + self._rtcout.RTC_TRACE("on_startup(%d)", ec_id) + ret = RTC.RTC_ERROR + try: + self.preOnStartup(ec_id) + ret = self.onStartup(ec_id) + except BaseException: + self._rtcout.RTC_ERROR(OpenRTM_aist.Logger.print_exception()) + ret = RTC.RTC_ERROR + self.postOnStartup(ec_id, ret) + return ret + + ## + # @if jp + # + # @brief [ComponentAction CORBA interface] RTC の停止 + # + # RTC が所属する ExecutionContext が Running 状態から Stopped 状態へ遷移 + # した場合に呼び出される。 + # このオペレーション呼び出しの結果として onShutdown() コールバック関数が + # 呼び出される。 + # + # @param self + # @param ec_id 状態遷移した ExecutionContext の ID + # + # @return ReturnCode_t 型のリターンコード + # + # @else + # + # @brief [ComponentAction CORBA interface] ShutDown RTC + # + # The given execution context, in which the RTC is participating, has + # transitioned from Running to Stopped. + # + # @param ec_id + # + # @return + # + # @endif + + def on_shutdown(self, ec_id): + self._rtcout.RTC_TRACE("on_shutdown(%d)", ec_id) + ret = RTC.RTC_ERROR + try: + self.preOnShutdown(ec_id) + ret = self.onShutdown(ec_id) + except BaseException: + self._rtcout.RTC_ERROR(OpenRTM_aist.Logger.print_exception()) + ret = RTC.RTC_ERROR + self.postOnShutdown(ec_id, ret) + return ret + + ## + # @if jp + # + # @brief [ComponentAction CORBA interface] RTC の活性化 + # + # 所属する ExecutionContext から RTC が活性化された際に呼び出される。 + # このオペレーション呼び出しの結果として onActivated() コールバック関数が + # 呼び出される。 + # + # @param self + # @param ec_id 活性化 ExecutionContext の ID + # + # @return ReturnCode_t 型のリターンコード + # + # @else + # + # @brief [ComponentAction CORBA interface] Activate RTC + # + # The RTC has been activated in the given execution context. + # + # @param ec_id + # + # @return + # + # @endif + + def on_activated(self, ec_id): + self._rtcout.RTC_TRACE("on_activated(%d)", ec_id) + ret = RTC.RTC_ERROR + try: + self.preOnActivated(ec_id) + self._configsets.update() + ret = self.onActivated(ec_id) + self._portAdmin.activatePorts() + except BaseException: + self._rtcout.RTC_ERROR(OpenRTM_aist.Logger.print_exception()) + ret = RTC.RTC_ERROR + self.postOnActivated(ec_id, ret) + return ret + + ## + # @if jp + # + # @brief [ComponentAction CORBA interface] RTC の非活性化 + # + # 所属する ExecutionContext から RTC が非活性化された際に呼び出される。 + # このオペレーション呼び出しの結果として onDeactivated() コールバック関数が + # 呼び出される。 + # + # @param self + # @param ec_id 非活性化 ExecutionContext の ID + # + # @return ReturnCode_t 型のリターンコード + # + # @else + # + # @brief [ComponentAction CORBA interface] Deactivate RTC + # + # The RTC has been deactivated in the given execution context. + # + # @param ec_id + # + # @return + # + # @endif + + def on_deactivated(self, ec_id): + self._rtcout.RTC_TRACE("on_deactivated(%d)", ec_id) + ret = RTC.RTC_ERROR + try: + self.preOnDeactivated(ec_id) + self._portAdmin.deactivatePorts() + ret = self.onDeactivated(ec_id) + except BaseException: + self._rtcout.RTC_ERROR(OpenRTM_aist.Logger.print_exception()) + ret = RTC.RTC_ERROR + self.postOnDeactivated(ec_id, ret) + return ret + + ## + # @if jp + # + # @brief [ComponentAction CORBA interface] RTC のエラー状態への遷移 + # + # RTC が所属する ExecutionContext が Active 状態から Error 状態へ遷移した + # 場合に呼び出される。 + # このオペレーションは RTC が Error 状態に遷移した際に一度だけ呼び出される。 + # このオペレーション呼び出しの結果として onAborting() コールバック関数が + # 呼び出される。 + # + # @param self + # @param ec_id 状態遷移した ExecutionContext の ID + # + # @return ReturnCode_t 型のリターンコード + # + # @else + # + # @brief [ComponentAction CORBA interface] Transition Error State + # + # The RTC is transitioning from the Active state to the Error state in some + # execution context. + # This callback is invoked only a single time for time that the RTC + # transitions into the Error state from another state. This behavior is in + # contrast to that of on_error. + # + # @param ec_id + # + # @return + # + # @endif + + def on_aborting(self, ec_id): + self._rtcout.RTC_TRACE("on_aborting(%d)", ec_id) + ret = RTC.RTC_ERROR + try: + self.preOnAborting(ec_id) + ret = self.onAborting(ec_id) + except BaseException: + self._rtcout.RTC_ERROR(OpenRTM_aist.Logger.print_exception()) + ret = RTC.RTC_ERROR + self.postOnAborting(ec_id, ret) + return ret + + ## + # @if jp + # + # @brief [ComponentAction CORBA interface] RTC のエラー処理 + # + # RTC がエラー状態にいる際に呼び出される。 + # RTC がエラー状態の場合に、対象となる ExecutionContext のExecutionKind に + # 応じたタイミングで呼び出される。例えば、 + # - ExecutionKind が PERIODIC の場合、本オペレーションは + # DataFlowComponentAction::on_execute と on_state_update の替わりに、 + # 設定された順番、設定された周期で呼び出される。 + # - ExecutionKind が EVENT_DRIVEN の場合、本オペレーションは + # FsmParticipantAction::on_action が呼ばれた際に、替わりに呼び出される。 + # このオペレーション呼び出しの結果として onError() コールバック関数が呼び出 + # される。 + # + # @param self + # @param ec_id 対象 ExecutionContext の ID + # + # @return ReturnCode_t 型のリターンコード + # + # @else + # + # @brief [ComponentAction CORBA interface] Error Processing of RTC + # + # The RTC remains in the Error state. + # If the RTC is in the Error state relative to some execution context when + # it would otherwise be invoked from that context (according to the + # context’s ExecutionKind), this callback shall be invoked instead. + # For example, + # - If the ExecutionKind is PERIODIC, this operation shall be invoked in + # sorted order at the rate of the context instead of + # DataFlowComponentAction::on_execute and on_state_update. + # - If the ExecutionKind is EVENT_DRIVEN, this operation shall be invoked + # whenever FsmParticipantAction::on_action would otherwise have been + # invoked. + # + # @param ec_id + # + # @return + # + # @endif + + def on_error(self, ec_id): + self._rtcout.RTC_TRACE("on_error(%d)", ec_id) + ret = RTC.RTC_ERROR + try: + self.preOnError(ec_id) + ret = self.onError(ec_id) + except BaseException: + self._rtcout.RTC_ERROR(OpenRTM_aist.Logger.print_exception()) + ret = RTC.RTC_ERROR + self._configsets.update() + self.postOnError(ec_id, ret) + return ret + + ## + # @if jp + # + # @brief [ComponentAction CORBA interface] RTC のリセット + # + # Error 状態にある RTC のリカバリ処理を実行し、Inactive 状態に復帰させる + # 場合に呼び出される。 + # RTC のリカバリ処理が成功した場合は Inactive 状態に復帰するが、それ以外の + # 場合には Error 状態に留まる。 + # このオペレーション呼び出しの結果として onReset() コールバック関数が呼び + # 出される。 + # + # @param self + # @param ec_id リセット対象 ExecutionContext の ID + # + # @return ReturnCode_t 型のリターンコード + # + # @else + # + # @brief [ComponentAction CORBA interface] Resetting RTC + # + # The RTC is in the Error state. An attempt is being made to recover it such + # that it can return to the Inactive state. + # If the RTC was successfully recovered and can safely return to the + # Inactive state, this method shall complete with ReturnCode_t::OK. Any + # other result shall indicate that the RTC should remain in the Error state. + # + # @param ec_id + # + # @return + # + # @endif + + def on_reset(self, ec_id): + self._rtcout.RTC_TRACE("on_reset(%d)", ec_id) + ret = RTC.RTC_ERROR + try: + self.preOnReset(ec_id) + ret = self.onReset(ec_id) + except BaseException: + self._rtcout.RTC_ERROR(OpenRTM_aist.Logger.print_exception()) + ret = RTC.RTC_ERROR + self.postOnReset(ec_id, ret) + return ret + + # ============================================================ + # SDOPackage::SdoSystemElement + # ============================================================ + + ## + # @if jp + # + # @brief [SDO interface] Organization リストの取得 + # + # SDOSystemElement は0個もしくはそれ以上の Organization を所有することが + # 出来る。 SDOSystemElement が1つ以上の Organization を所有している場合 + # には、このオペレーションは所有する Organization のリストを返す。 + # もしOrganizationを一つも所有していないければ空のリストを返す。 + # + # @param self + # + # @return 所有している Organization リスト + # + # @exception SDONotExists ターゲットのSDOが存在しない。(本例外は、CORBA標準 + # システム例外のOBJECT_NOT_EXISTにマッピングされる) + # @exception NotAvailable SDOは存在するが応答がない。 + # @exception InternalError 内部的エラーが発生した。 + # + # @else + # + # @brief [SDO interface] Getting Organizations + # + # SDOSystemElement can be the owner of zero or more organizations. + # If the SDOSystemElement owns one or more Organizations, this operation + # returns the list of Organizations that the SDOSystemElement owns. + # If it does not own any Organization, it returns empty list. + # + # @return Owned Organization List + # + # @exception SDONotExists if the target SDO does not exist.(This exception + # is mapped to CORBA standard system exception + # OBJECT_NOT_EXIST.) + # @exception NotAvailable if the target SDO is reachable but cannot + # respond. + # @exception InternalError if the target SDO cannot execute the operation + # completely due to some internal error. + # + # @endif + # virtual SDOPackage::OrganizationList* get_owned_organizations() + + def get_owned_organizations(self): + self._rtcout.RTC_TRACE("get_owned_organizations()") + + return self._sdoOwnedOrganizations + + # ============================================================ + # SDOPackage::SDO + # ============================================================ + + ## + # @if jp + # + # @brief [SDO interface] SDO ID の取得 + # + # SDO ID を返すオペレーション。 + # このオペレーションは以下の型の例外を発生させる。 + # + # @param self + # + # @return リソースデータモデルで定義されている SDO の ID + # + # @exception SDONotExists ターゲットのSDOが存在しない。(本例外は、CORBA標準 + # システム例外のOBJECT_NOT_EXISTにマッピングされる) + # @exception NotAvailable SDOは存在するが応答がない。 + # @exception InternalError 内部的エラーが発生した。 + # + # @else + # + # @brief [SDO interface] Getting SDO ID + # + # This operation returns id of the SDO. + # This operation throws SDOException with one of the following types. + # + # @return id of the SDO defined in the resource data model. + # + # @exception SDONotExists if the target SDO does not exist.(This exception + # is mapped to CORBA standard system exception + # OBJECT_NOT_EXIST.) + # @exception NotAvailable if the target SDO is reachable but cannot + # respond. + # @exception InternalError if the target SDO cannot execute the operation + # completely due to some internal error. + # + # @endif + # virtual char* get_sdo_id() + + def get_sdo_id(self): + self._rtcout.RTC_TRACE("get_sdo_id()") + + return self._profile.instance_name + + ## + # @if jp + # + # @brief [SDO interface] SDO タイプの取得 + # + # SDO Type を返すオペレーション。 + # このオペレーションは以下の型の例外を発生させる。 + # + # @param self + # + # @return リソースデータモデルで定義されている SDO の Type + # + # @exception SDONotExists ターゲットのSDOが存在しない。(本例外は、CORBA標準 + # システム例外のOBJECT_NOT_EXISTにマッピングされる) + # @exception NotAvailable SDOは存在するが応答がない。 + # @exception InternalError 内部的エラーが発生した。 + # + # @else + # + # @brief [SDO interface] Getting SDO type + # + # This operation returns sdoType of the SDO. + # This operation throws SDOException with one of the following types. + # + # @return Type of the SDO defined in the resource data model. + # + # @exception SDONotExists if the target SDO does not exist.(This exception + # is mapped to CORBA standard system exception + # OBJECT_NOT_EXIST.) + # @exception NotAvailable if the target SDO is reachable but cannot + # respond. + # @exception InternalError if the target SDO cannot execute the operation + # completely due to some internal error. + # + # @endif + # virtual char* get_sdo_type() + + def get_sdo_type(self): + self._rtcout.RTC_TRACE("get_sdo_type()") + + return self._profile.description + + ## + # @if jp + # + # @brief [SDO interface] SDO DeviceProfile リストの取得 + # + # SDO の DeviceProfile を返すオペレーション。 SDO がハードウエアデバイス + # に関連付けられていない場合には、空の DeviceProfile が返される。 + # このオペレーションは以下の型の例外を発生させる。 + # + # @param self + # + # @return SDO DeviceProfile + # + # @exception SDONotExists ターゲットのSDOが存在しない。(本例外は、CORBA標準 + # システム例外のOBJECT_NOT_EXISTにマッピングされる) + # @exception NotAvailable SDOは存在するが応答がない。 + # @exception InternalError 内部的エラーが発生した。 + # + # @else + # + # @brief [SDO interface] Getting SDO DeviceProfile + # + # This operation returns the DeviceProfile of the SDO. If the SDO does not + # represent any hardware device, then a DeviceProfile with empty values + # are returned. + # This operation throws SDOException with one of the following types. + # + # @return The DeviceProfile of the SDO. + # + # @exception SDONotExists if the target SDO does not exist.(This exception + # is mapped to CORBA standard system exception + # OBJECT_NOT_EXIST.) + # @exception NotAvailable if the target SDO is reachable but cannot + # respond. + # @exception InternalError if the target SDO cannot execute the operation + # completely due to some internal error. + # + # @endif + # virtual SDOPackage::DeviceProfile* get_device_profile() + + def get_device_profile(self): + self._rtcout.RTC_TRACE("get_device_profile()") + + return self._SdoConfigImpl.getDeviceProfile() + + ## + # @if jp + # + # @brief [SDO interface] SDO ServiceProfile の取得 + # + # SDO が所有している Service の ServiceProfile を返すオペレーション。 + # SDO がサービスを一つも所有していない場合には、空のリストを返す。 + # このオペレーションは以下の型の例外を発生させる。 + # + # @param self + # + # @return SDO が提供する全ての Service の ServiceProfile。 + # + # @exception SDONotExists ターゲットのSDOが存在しない。(本例外は、CORBA標準 + # システム例外のOBJECT_NOT_EXISTにマッピングされる) + # @exception NotAvailable SDOは存在するが応答がない。 + # @exception InternalError 内部的エラーが発生した。 + # + # @else + # + # @brief [SDO interface] Getting SDO ServiceProfile + # + # This operation returns a list of ServiceProfiles that the SDO has. + # If the SDO does not provide any service, then an empty list is returned. + # This operation throws SDOException with one of the following types. + # + # @return List of ServiceProfiles of all the services the SDO is + # providing. + # + # @exception SDONotExists if the target SDO does not exist.(This exception + # is mapped to CORBA standard system exception + # OBJECT_NOT_EXIST.) + # @exception NotAvailable if the target SDO is reachable but cannot + # respond. + # @exception InternalError if the target SDO cannot execute the operation + # completely due to some internal error. + # + # @endif + # virtual SDOPackage::ServiceProfileList* get_service_profiles() + + def get_service_profiles(self): + self._rtcout.RTC_TRACE("get_service_profiles()") + self._sdoSvcProfiles = self._SdoConfigImpl.getServiceProfiles() + + return self._sdoSvcProfiles + + ## + # @if jp + # + # @brief [SDO interface] 特定のServiceProfileの取得 + # + # 引数 "id" で指定された名前のサービスの ServiceProfile を返す。 + # + # @param self + # @param _id SDO Service の ServiceProfile に関連付けられた識別子。 + # + # @return 指定された SDO Service の ServiceProfile。 + # + # @exception InvalidParameter "id" で指定した ServiceProfile が存在しない。 + # "id" が null。 + # @exception SDONotExists ターゲットのSDOが存在しない。(本例外は、CORBA標準 + # システム例外のOBJECT_NOT_EXISTにマッピングされる) + # @exception NotAvailable SDOは存在するが応答がない。 + # @exception InternalError 内部的エラーが発生した。 + # + # @else + # + # @brief [SDO interface] Getting Organizations + # + # This operation returns the ServiceProfile that is specified by the + # argument "id." + # + # @param _id The identifier referring to one of the ServiceProfiles. + # + # @return The profile of the specified service. + # + # @exception InvalidParameter if the ServiceProfile that is specified by + # the argument 'id' does not exist or if 'id' + # is 'null.' + # @exception SDONotExists if the target SDO does not exist.(This exception + # is mapped to CORBA standard system exception + # OBJECT_NOT_EXIST.) + # @exception NotAvailable If the target SDO is reachable but cannot + # respond. + # @exception InternalError If the target SDO cannot execute the operation + # completely due to some internal error. + # + # @endif + # virtual SDOPackage::ServiceProfile* get_service_profile(const char* id) + + def get_service_profile(self, _id): + self._rtcout.RTC_TRACE("get_service_profile(%s)", _id) + self._sdoSvcProfiles = self._SdoConfigImpl.getServiceProfiles() + if not _id: + raise SDOPackage.InvalidParameter( + "get_service_profile(): Empty name.") + + try: + index = OpenRTM_aist.CORBA_SeqUtil.find( + self._sdoSvcProfiles, self.svc_name(_id)) + + if index < 0: + raise SDOPackage.InvalidParameter( + "get_service_profile(): Not found") + + return self._sdoSvcProfiles[index] + except BaseException: + self._rtcout.RTC_ERROR(OpenRTM_aist.Logger.print_exception()) + raise SDOPackage.InternalError("get_service_profile()") + + ## + # @if jp + # + # @brief [SDO interface] 指定された SDO Service の取得 + # + # このオペレーションは引数 "id" で指定された名前によって区別される + # SDO の Service へのオブジェクト参照を返す。 SDO により提供される + # Service はそれぞれ一意の識別子により区別される。 + # + # @param self + # @param _id SDO Service に関連付けられた識別子。 + # + # @return 要求された SDO Service への参照。 + # + # + # @exception InvalidParameter "id" で指定した ServiceProfile が存在しない。 + # "id" が null。 + # @exception SDONotExists ターゲットのSDOが存在しない。(本例外は、CORBA標準 + # システム例外のOBJECT_NOT_EXISTにマッピングされる) + # @exception NotAvailable SDOは存在するが応答がない。 + # @exception InternalError 内部的エラーが発生した。 + # + # @else + # + # @brief [SDO interface] Getting specified SDO Service's reference + # + # This operation returns an object implementing an SDO's service that + # is identified by the identifier specified as an argument. Different + # services provided by an SDO are distinguished with different + # identifiers. See OMG SDO specification Section 2.2.8, "ServiceProfile," + # on page 2-12 for more details. + # + # @param _id The identifier referring to one of the SDO Service + # @return The object implementing the requested service. + # @exception InvalidParameter if argument “id” is null, or if the + # ServiceProfile that is specified by argument + # “id” does not exist. + # @exception SDONotExists if the target SDO does not exist.(This exception + # is mapped to CORBA standard system exception + # OBJECT_NOT_EXIST.) + # @exception NotAvailable If the target SDO is reachable but cannot + # respond. + # @exception InternalError If the target SDO cannot execute the operation + # completely due to some internal error. + # + # @endif + # virtual SDOPackage::SDOService_ptr get_sdo_service(const char* id) + + def get_sdo_service(self, _id): + self._rtcout.RTC_TRACE("get_sdo_service(%s)", _id) + self._sdoSvcProfiles = self._SdoConfigImpl.getServiceProfiles() + + if not _id: + raise SDOPackage.InvalidParameter("get_service(): Empty name.") + + index = OpenRTM_aist.CORBA_SeqUtil.find( + self._sdoSvcProfiles, self.svc_name(_id)) + + if index < 0: + raise SDOPackage.InvalidParameter("get_service(): Not found") + + return self._sdoSvcProfiles[index].service + + ## + # @if jp + # + # @brief [SDO interface] Configuration オブジェクトの取得 + # + # このオペレーションは Configuration interface への参照を返す。 + # Configuration interface は各 SDO を管理するためのインターフェースの + # ひとつである。このインターフェースは DeviceProfile, ServiceProfile, + # Organization で定義された SDO の属性値を設定するために使用される。 + # Configuration インターフェースの詳細については、OMG SDO specification + # の 2.3.5節, p.2-24 を参照のこと。 + # + # @param self + # + # @return SDO の Configuration インターフェースへの参照 + # + # @exception InterfaceNotImplemented SDOはConfigurationインターフェースを + # 持たない。 + # @exception SDONotExists ターゲットのSDOが存在しない。(本例外は、CORBA標準 + # システム例外のOBJECT_NOT_EXISTにマッピングされる) + # @exception NotAvailable SDOは存在するが応答がない。 + # @exception InternalError 内部的エラーが発生した。 + # + # @else + # + # @brief [SDO interface] Getting Configuration object + # + # This operation returns an object implementing the Configuration + # interface. The Configuration interface is one of the interfaces that + # each SDO maintains. The interface is used to configure the attributes + # defined in DeviceProfile, ServiceProfile, and Organization. + # See OMG SDO specification Section 2.3.5, "Configuration Interface," + # on page 2-24 for more details about the Configuration interface. + # + # @return The Configuration interface of an SDO. + # + # @exception InterfaceNotImplemented The target SDO has no Configuration + # interface. + # @exception SDONotExists if the target SDO does not exist.(This exception + # is mapped to CORBA standard system exception + # OBJECT_NOT_EXIST.) + # @exception NotAvailable The target SDO is reachable but cannot respond. + # @exception InternalError The target SDO cannot execute the operation + # completely due to some internal error. + # @endif + # virtual SDOPackage::Configuration_ptr get_configuration() + + def get_configuration(self): + self._rtcout.RTC_TRACE("get_configuration()") + if self._SdoConfig is None: + raise SDOPackage.InterfaceNotImplemented( + "InterfaceNotImplemented: get_configuration") + + return self._SdoConfig + + ## + # @if jp + # + # @brief [SDO interface] Monitoring オブジェクトの取得 + # + # このオペレーションは Monitoring interface への参照を返す。 + # Monitoring interface は SDO が管理するインターフェースの一つである。 + # このインターフェースは SDO のプロパティをモニタリングするために + # 使用される。 + # Monitoring interface の詳細については OMG SDO specification の + # 2.3.7節 "Monitoring Interface" p.2-35 を参照のこと。 + # + # @param self + # + # @return SDO の Monitoring interface への参照 + # + # @exception InterfaceNotImplemented SDOはConfigurationインターフェースを + # 持たない。 + # @exception SDONotExists ターゲットのSDOが存在しない。(本例外は、CORBA標準 + # システム例外のOBJECT_NOT_EXISTにマッピングされる) + # @exception NotAvailable SDOは存在するが応答がない。 + # @exception InternalError 内部的エラーが発生した。 + # + # @else + # + # @brief [SDO interface] Get Monitoring object + # + # This operation returns an object implementing the Monitoring interface. + # The Monitoring interface is one of the interfaces that each SDO + # maintains. The interface is used to monitor the properties of an SDO. + # See OMG SDO specification Section 2.3.7, "Monitoring Interface," on + # page 2-35 for more details about the Monitoring interface. + # + # @return The Monitoring interface of an SDO. + # + # @exception InterfaceNotImplemented The target SDO has no Configuration + # interface. + # @exception SDONotExists if the target SDO does not exist.(This exception + # is mapped to CORBA standard system exception + # OBJECT_NOT_EXIST.) + # @exception NotAvailable The target SDO is reachable but cannot respond. + # @exception InternalError The target SDO cannot execute the operation + # completely due to some internal error. + # @endif + # virtual SDOPackage::Monitoring_ptr get_monitoring() + + def get_monitoring(self): + self._rtcout.RTC_TRACE("get_monitoring()") + raise SDOPackage.InterfaceNotImplemented("Exception: get_monitoring") + + ## + # @if jp + # + # @brief [SDO interface] Organization リストの取得 + # + # SDO は0個以上の Organization (組織)に所属することができる。 もし SDO が + # 1個以上の Organization に所属している場合、このオペレーションは所属する + # Organization のリストを返す。SDO が どの Organization にも所属していない + # 場合には、空のリストが返される。 + # + # @param self + # + # @return SDO が所属する Organization のリスト。 + # + # @exception SDONotExists ターゲットのSDOが存在しない。(本例外は、CORBA標準 + # システム例外のOBJECT_NOT_EXISTにマッピングされる) + # @exception NotAvailable SDOは存在するが応答がない。 + # @exception InternalError 内部的エラーが発生した。 + # @else + # + # @brief [SDO interface] Getting Organizations + # + # An SDO belongs to zero or more organizations. If the SDO belongs to one + # or more organizations, this operation returns the list of organizations + # that the SDO belongs to. An empty list is returned if the SDO does not + # belong to any Organizations. + # + # @return The list of Organizations that the SDO belong to. + # + # @exception SDONotExists if the target SDO does not exist.(This exception + # is mapped to CORBA standard system exception + # OBJECT_NOT_EXIST.) + # @exception NotAvailable The target SDO is reachable but cannot respond. + # @exception InternalError The target SDO cannot execute the operation + # completely due to some internal error. + # @endif + # virtual SDOPackage::OrganizationList* get_organizations() + + def get_organizations(self): + self._rtcout.RTC_TRACE("get_organizations()") + self._sdoOrganizations = self._SdoConfigImpl.getOrganizations() + + return self._sdoOrganizations + + ## + # @if jp + # + # @brief [SDO interface] SDO Status リストの取得 + # + # このオペレーションは SDO のステータスを表す NVList を返す。 + # + # @param self + # + # @return SDO のステータス。 + # + # @exception SDONotExists ターゲットのSDOが存在しない。(本例外は、CORBA標準 + # システム例外のOBJECT_NOT_EXISTにマッピングされる) + # @exception NotAvailable SDOは存在するが応答がない。 + # @exception InternalError 内部的エラーが発生した。 + # + # @else + # + # @brief [SDO interface] Get SDO Status + # + # This operation returns an NVlist describing the status of an SDO. + # + # @return The actual status of an SDO. + # + # @exception SDONotExists if the target SDO does not exist.(This exception + # is mapped to CORBA standard system exception + # OBJECT_NOT_EXIST.) + # @exception NotAvailable The target SDO is reachable but cannot respond. + # @exception InternalError The target SDO cannot execute the operation + # completely due to some internal error. + # + # @endif + # virtual SDOPackage::NVList* get_status_list() + + def get_status_list(self): + self._rtcout.RTC_TRACE("get_status_list()") + + return self._sdoStatus + + ## + # @if jp + # + # @brief [SDO interface] SDO Status の取得 + # + # This operation returns the value of the specified status parameter. + # + # @param self + # @param name SDO のステータスを定義するパラメータ。 + # + # @return 指定されたパラメータのステータス値。 + # + # @exception SDONotExists ターゲットのSDOが存在しない。(本例外は、CORBA標準 + # システム例外のOBJECT_NOT_EXISTにマッピングされる) + # @exception NotAvailable SDOは存在するが応答がない。 + # @exception InvalidParameter 引数 "name" が null あるいは存在しない。 + # @exception InternalError 内部的エラーが発生した。 + # @else + # + # @brief [SDO interface] Get SDO Status + # + # @param name One of the parameters defining the "status" of an SDO. + # + # @return The value of the specified status parameter. + # + # @exception SDONotExists if the target SDO does not exist.(This exception + # is mapped to CORBA standard system exception + # OBJECT_NOT_EXIST.) + # @exception NotAvailable The target SDO is reachable but cannot respond. + # @exception InvalidParameter The parameter defined by "name" is null or + # does not exist. + # @exception InternalError The target SDO cannot execute the operation + # completely due to some internal error. + # + # + # @endif + # virtual CORBA::Any* get_status(const char* name) + + def get_status(self, name): + self._rtcout.RTC_TRACE("get_status(%s)", name) + index = OpenRTM_aist.CORBA_SeqUtil.find( + self._sdoStatus, self.nv_name(name)) + if index < 0: + raise SDOPackage.InvalidParameter("get_status(): Not found") + + try: + return any.to_any(self._sdoStatus[index].value) + except BaseException: + self._rtcout.RTC_ERROR(OpenRTM_aist.Logger.print_exception()) + raise SDOPackage.InternalError("get_status()") + + # ============================================================ + # Local interfaces + # ============================================================ + + ## + # @if jp + # + # @brief [local interface] インスタンス名の取得 + # + # ComponentProfile に設定されたインスタンス名を返す。 + # + # @param self + # + # @return インスタンス名 + # + # @else + # + # @endif + # const char* getInstanceName() + + def getInstanceName(self): + self._rtcout.RTC_TRACE("getInstanceName()") + return self._profile.instance_name + + ## + # @if jp + # + # @brief [local interface] インスタンス名の設定 + # + # ComponentProfile に指定されたインスタンス名を設定する。 + # + # @param self + # + # @param instance_name インスタンス名 + # + # @else + # + # @endif + # void setInstanceName(const char* instance_name); + + def setInstanceName(self, instance_name): + self._rtcout.RTC_TRACE("setInstanceName(%s)", instance_name) + self._properties.setProperty("instance_name", instance_name) + self._profile.instance_name = self._properties.getProperty( + "instance_name") + + ## + # @if jp + # + # @brief [local interface] 型名の取得 + # + # ComponentProfile に設定された型名を返す。 + # + # @param self + # + # @return 型名 + # + # @else + # + # @endif + # const char* getTypeName() + + def getTypeName(self): + self._rtcout.RTC_TRACE("getTypeName()") + return self._profile.type_name + + ## + # @if jp + # + # @brief [local interface] Description の取得 + # + # ComponentProfile に設定された Description を返す。 + # + # @param self + # + # @return Description + # + # @else + # + # @endif + # const char* getDescription() + + def getDescription(self): + self._rtcout.RTC_TRACE("getDescription()") + return self._profile.description + + ## + # @if jp + # + # @brief [local interface] バージョン情報の取得 + # + # ComponentProfile に設定されたバージョン情報を返す。 + # + # @param self + # + # @return バージョン情報 + # + # @else + # + # @endif + # const char* getVersion() + + def getVersion(self): + self._rtcout.RTC_TRACE("getVersion()") + return self._profile.version + + ## + # @if jp + # + # @brief [local interface] ベンダー情報の取得 + # + # ComponentProfile に設定されたベンダー情報を返す。 + # + # @param self + # + # @return ベンダー情報 + # + # @else + # + # @endif + # const char* getVendor() + + def getVendor(self): + self._rtcout.RTC_TRACE("getVendor()") + return self._profile.vendor + + ## + # @if jp + # + # @brief [local interface] カテゴリ情報の取得 + # + # ComponentProfile に設定されたカテゴリ情報を返す。 + # + # @param self + # + # @return カテゴリ情報 + # + # @else + # + # @endif + # const char* getCategory() + + def getCategory(self): + self._rtcout.RTC_TRACE("getCategory()") + return self._profile.category + + ## + # @if jp + # + # @brief [local interface] Naming Server 情報の取得 + # + # 設定された Naming Server 情報を返す。 + # + # @param self + # + # @return Naming Server リスト + # + # @else + # + # @endif + # std::vector getNamingNames(); + + def getNamingNames(self): + self._rtcout.RTC_TRACE("getNamingNames()") + return [s.strip() + for s in self._properties.getProperty("naming.names").split(",")] + + ## + # @if jp + # + # @brief [local interface] オブジェクトリファレンスの設定 + # + # RTC の CORBA オブジェクトリファレンスを設定する。 + # + # @param self + # @param rtobj オブジェクトリファレンス + # + # @else + # + # @endif + # void setObjRef(const RTObject_ptr rtobj); + + def setObjRef(self, rtobj): + self._rtcout.RTC_TRACE("setObjRef()") + self._objref = rtobj + return - ## - # @if jp - # - # @brief [ComponentAction CORBA interface] RTC νλ - # - # RTC ˴롣 - # RTC ͭνλϤǼ¹Ԥ롣 - # Υڥ졼ƤӽФη̤Ȥ onFinalize() Хåؿ - # ƤӽФ롣 - # - # @param self - # - # @return ReturnCode_t Υ꥿󥳡 - # - # @else - # - # @brief [ComponentAction CORBA interface] Finalize RTC - # - # The RTC is being destroyed. - # Any final RTC-specific tear-down logic should be performed here. - # - # @return - # - # @endif - def on_finalize(self): - self._rtcout.RTC_TRACE("on_finalize()") - ret = RTC.RTC_ERROR - try: - self.preOnFinalize(0) - ret = self.onFinalize() - except: - self._rtcout.RTC_ERROR(OpenRTM_aist.Logger.print_exception()) - ret = RTC.RTC_ERROR - self.postOnFinalize(0, ret) - return ret + ## + # @if jp + # + # @brief [local interface] オブジェクトリファレンスの取得 + # + # 設定された CORBA オブジェクトリファレンスを取得する。 + # + # @param self + # + # @return オブジェクトリファレンス + # + # @else + # + # @endif + # RTObject_ptr getObjRef() const; + + def getObjRef(self): + self._rtcout.RTC_TRACE("getObjRef()") + return self._objref + + ## + # @if jp + # + # @brief [local interface] RTC のプロパティを設定する + # + # RTC が保持すべきプロパティを設定する。与えられるプロパティは、 + # ComponentProfile 等に設定されるべき情報を持たなければならない。 + # このオペレーションは通常 RTC が初期化される際に Manager から + # 呼ばれることを意図している。 + # + # @param self + # @param prop RTC のプロパティ + # + # @else + # + # @brief [local interface] Set RTC property + # + # This operation sets the properties to the RTC. The given property + # values should include information for ComponentProfile. + # Generally, this operation is designed to be called from Manager, when + # RTC is initialized + # + # @param prop Property for RTC. + # + # @endif + # void setProperties(const coil::Properties& prop); + + def setProperties(self, prop): + self._rtcout.RTC_TRACE("setProperties()") + self._properties.mergeProperties(prop) + self._profile.instance_name = self._properties.getProperty( + "instance_name") + self._profile.type_name = self._properties.getProperty("type_name") + self._profile.description = self._properties.getProperty("description") + self._profile.version = self._properties.getProperty("version") + self._profile.vendor = self._properties.getProperty("vendor") + self._profile.category = self._properties.getProperty("category") + + ## + # @if jp + # + # @brief [local interface] RTC のプロパティを取得する + # + # RTC が保持しているプロパティを返す。 + # RTCがプロパティを持たない場合は空のプロパティが返される。 + # + # @param self + # + # @return RTC のプロパティ + # + # @else + # + # @brief [local interface] Get RTC property + # + # This operation returns the properties of the RTC. + # Empty property would be returned, if RTC has no property. + # + # @return Property for RTC. + # + # @endif + # coil::Properties& getProperties(); + + def getProperties(self): + self._rtcout.RTC_TRACE("getProperties()") + return self._properties + + ## + # @if jp + # + # @brief コンフィギュレーションパラメータの設定 + # + # コンフィギュレーションパラメータと変数をバインドする + # \としてコンフィギュレーションパラメータのデータ型を指定する。 + # + # @param self + # @param param_name コンフィギュレーションパラメータ名 + # @param var コンフィギュレーションパラメータ格納用変数 + # @param def_val コンフィギュレーションパラメータデフォルト値 + # @param trans 文字列変換用関数(デフォルト値:None) + # + # @return 設定結果(設定成功:true,設定失敗:false) + # + # @else + # + # @endif + # template + # bool bindParameter(const char* param_name, VarType& var, + # const char* def_val, + # bool (*trans)(VarType&, const char*) = coil::stringTo) + + def bindParameter(self, param_name, var, + def_val, trans=None): + self._rtcout.RTC_TRACE("bindParameter()") + if trans is None: + trans_ = OpenRTM_aist.stringTo + else: + trans_ = trans + self._configsets.bindParameter(param_name, var, def_val, trans_) + return True + ## + # @if jp + # + # @brief コンフィギュレーションサービスを取得する + # + # コンフィギュレーションサービスオブジェクトを取得する。このサービ + # スオブジェクトを利用して、コンフィギュレーションパラメータの操作 + # を行うことができる。主な操作としては、 + # + # - unbindParameter(): パラメータのアンバインド + # - update(): パラメータの更新 + # - update(set_name): 特定のセットの更新 + # - update(set_name, param_name): 特定のセットのパラメータの更新 + # - isExist(): パラメータの存在確認 + # - isChanged(): パラメータが変更されたかの確認 + # - changedParameters(): 変更されたパラメータのリスト + # - getActiveId(): アクティブセット名の取得 + # - haveConfig(config_id): コンフィグセットを持っているかどうか + # - getConfigurationSets(): 全コンフィギュレーションセットの取得 + # - getConfigurationSet(set_id): 特定セットを取得 + # + # コールバック関連 + # - addConfigurationParamListener(): リスナの追加 + # - removeConfigurationParamListener(): リスナの削除 + # - addConfigurationSetListener(): リスナの追加 + # - removeConfigurationSetListener(): リスナの削除 + # - addConfigurationSetNameListener(): リスナの追加 + # - removeConfigurationSetNameListener(): リスナの削除 + # + # 詳細はConfigAdminクラスリファレンスを参照のこと。 + # + # @return ConfigAdmin object + # + # @else + # + # @brief Getting configuration service + # + # This operation returns configuration service object. By using + # this service, user can manipulate configuration + # parameters. Mainly the following operations are supported. + # + # - unbindParameter(): Unbinding parameters + # - update(): Updateing parameters + # - update(set_name): Updating a specific configuration set + # - update(set_name, param_name): Updating specific parameter in a set + # - isExist(): Checking existence of a parameter + # - isChanged(): Check if a parameter was updated + # - changedParameters(): Getting changed parameter list + # - getActiveId(): Getting active configuration set name + # - haveConfig(config_id): Checking if having a specified configuration set + # - getConfigurationSets(): getting all the configuration sets + # - getConfigurationSet(set_id): Getting a configuration set + # + # Callback related member functions + # - addConfigurationParamListener(): Adding listener + # - removeConfigurationParamListener(): Removing listener + # - addConfigurationSetListener(): Adding listener + # - removeConfigurationSetListener(): Removing listener + # - addConfigurationSetNameListener(): Adding listener + # - removeConfigurationSetNameListener(): Removing listener + # + # See details in the ConfigAdmin class reference + # + # @return ConfigAdmin object + # + # @endif + # + # ConfigAdmin& getConfigService() { return m_configsets; } + + def getConfigService(self): + return self._configsets + + ## + # @if jp + # + # @brief コンフィギュレーションパラメータの更新(ID指定) + # + # 指定したIDのコンフィギュレーションセットに設定した値で、 + # コンフィギュレーションパラメータの値を更新する + # + # @param self + # @param config_set 設定対象のコンフィギュレーションセットID + # + # @else + # + # @endif + # void updateParameters(const char* config_set); + def updateParameters(self, config_set): + self._rtcout.RTC_TRACE("updateParameters(%s)", config_set) + self._configsets.update(config_set) + return - ## - # @if jp - # - # @brief [ComponentAction CORBA interface] RTC γ - # - # RTC ° ExecutionContext Stopped ֤ Running ֤ - # ˸ƤӽФ롣 - # Υڥ졼ƤӽФη̤Ȥ onStartup() Хåؿ - # ƤӽФ롣 - # - # @param self - # @param ec_id ܤ ExecutionContext ID - # - # @return ReturnCode_t Υ꥿󥳡 - # - # @else - # - # @brief [ComponentAction CORBA interface] StartUp RTC - # - # The given execution context, in which the RTC is participating, has - # transitioned from Stopped to Running. - # - # @param ec_id - # - # @return - # - # @endif - def on_startup(self, ec_id): - self._rtcout.RTC_TRACE("on_startup(%d)", ec_id) - ret = RTC.RTC_ERROR - try: - self.preOnStartup(ec_id) - ret = self.onStartup(ec_id) - except: - self._rtcout.RTC_ERROR(OpenRTM_aist.Logger.print_exception()) - ret = RTC.RTC_ERROR - self.postOnStartup(ec_id, ret) - return ret + ## + # @if jp + # + # @brief [local interface] Port を登録する + # + # RTC が保持するPortを登録する。 + # Port を外部からアクセス可能にするためには、このオペレーションにより + # 登録されていなければならない。登録される Port はこの RTC 内部において + # PortProfile.name により区別される。したがって、Port は RTC 内において、 + # ユニークな PortProfile.name を持たなければならない。 + # 登録された Port は内部で適切にアクティブ化された後、その参照と + # オブジェクト参照がリスト内に保存される。 + # + # @param self + # @param port RTC に登録する Port + # @param port_type if port is PortBase, port_type is None, + # if port is PortService, port_type is True + # + # @else + # + # @brief [local interface] Register Port + # + # This operation registers a Port to be held by this RTC. + # In order to enable access to the Port from outside of RTC, the Port + # must be registered by this operation. The Port that is registered by + # this operation would be identified by PortProfile.name in the inside of + # RTC. Therefore, the Port should have unique PortProfile.name in the RTC. + # The registering Port would be activated properly, and the reference + # and the object reference would be stored in lists in RTC. + # + # @param port Port which is registered in the RTC + # + # @endif + # void registerPort(PortBase& port); + + def registerPort(self, port): + self._rtcout.RTC_TRACE("registerPort()") + if not self.addPort(port): + self._rtcout.RTC_ERROR("addPort(PortBase&) failed.") + return + # void registerPort(PortService_ptr port); + # def registerPortByReference(self, port_ref): + # self._rtcout.RTC_TRACE("registerPortByReference()") + # self.addPortByReference(port_ref) + # return + + # new interface. since 1.0.0-RELEASE + # void addPort(PortBase& port); + def addPort(self, port): + self._rtcout.RTC_TRACE("addPort()") + if isinstance(port, OpenRTM_aist.CorbaPort): + self._rtcout.RTC_TRACE("addPort(CorbaPort)") + propkey = "port.corbaport." + prop = self._properties.getNode(propkey) + if prop: + self._properties.getNode(propkey).mergeProperties( + self._properties.getNode("port.corba")) + port.init(self._properties.getNode(propkey)) + port.setOwner(self.getObjRef()) + port.setPortConnectListenerHolder(self._portconnListeners) + self.onAddPort(port.getPortProfile()) + + elif isinstance(port, OpenRTM_aist.PortBase): + self._rtcout.RTC_TRACE("addPort(PortBase)") + port.setOwner(self.getObjRef()) + port.setPortConnectListenerHolder(self._portconnListeners) + self.onAddPort(port.getPortProfile()) + + elif isinstance(port, RTC._objref_PortService): + self._rtcout.RTC_TRACE("addPort(PortService)") + return self._portAdmin.addPort(port) + + # new interface. since 1.0.0-RELEASE + # void addPort(PortService_ptr port); + # def addPortByReference(self, port_ref): + # self._rtcout.RTC_TRACE("addPortByReference()") + # self._portAdmin.registerPortByReference(port_ref) + # return + + ## + # @if jp + # + # @brief [local interface] DataInPort を登録する + # + # RTC が保持する DataInPort を登録する。 + # Port のプロパティにデータポートであること("port.dataport")、 + # TCPを使用すること("tcp_any")を設定するとともに、 DataInPort の + # インスタンスを生成し、登録する。 + # + # @param self + # @param name port 名称 + # @param inport 登録対象 DataInPort + # + # @else + # + # @endif + + def registerInPort(self, name, inport): + self._rtcout.RTC_TRACE("registerInPort(%s)", name) + if not self.addInPort(name, inport): + self._rtcout.RTC_ERROR("addInPort(%s) failed.", name) + return - ## - # @if jp - # - # @brief [ComponentAction CORBA interface] RTC - # - # RTC ° ExecutionContext Running ֤ Stopped ֤ - # ˸ƤӽФ롣 - # Υڥ졼ƤӽФη̤Ȥ onShutdown() Хåؿ - # ƤӽФ롣 - # - # @param self - # @param ec_id ܤ ExecutionContext ID - # - # @return ReturnCode_t Υ꥿󥳡 - # - # @else - # - # @brief [ComponentAction CORBA interface] ShutDown RTC - # - # The given execution context, in which the RTC is participating, has - # transitioned from Running to Stopped. - # - # @param ec_id - # - # @return - # - # @endif - def on_shutdown(self, ec_id): - self._rtcout.RTC_TRACE("on_shutdown(%d)", ec_id) - ret = RTC.RTC_ERROR - try: - self.preOnShutdown(ec_id) - ret = self.onShutdown(ec_id) - except: - self._rtcout.RTC_ERROR(OpenRTM_aist.Logger.print_exception()) - ret = RTC.RTC_ERROR - self.postOnShutdown(ec_id, ret) - return ret + # new interface. since 1.0.0-RELEASE + def addInPort(self, name, inport): + self._rtcout.RTC_TRACE("addInPort(%s)", name) + + propkey = "port.inport." + name + prop_ = copy.copy(self._properties.getNode(propkey)) + prop_.mergeProperties(self._properties.getNode("port.inport.dataport")) + + ret = self.addPort(inport) + + if not ret: + self._rtcout.RTC_ERROR("addInPort() failed.") + return ret + + inport.init(prop_) + self._inports.append(inport) + return ret + + ## + # @if jp + # + # @brief [local interface] DataOutPort を登録する + # + # RTC が保持する DataOutPor tを登録する。 + # Port のプロパティにデータポートであること("port.dataport")、 + # TCPを使用すること("tcp_any")を設定するとともに、 DataOutPort の + # インスタンスを生成し、登録する。 + # + # @param self + # @param name port 名称 + # @param outport 登録対象 DataInPort + # + # @else + # + # @endif + # void registerOutPort(const char* name, OutPortBase& outport); + + def registerOutPort(self, name, outport): + self._rtcout.RTC_TRACE("registerOutPort(%s)", name) + if not self.addOutPort(name, outport): + self._rtcout.RTC_ERROR("addOutPort(%s) failed.", name) + return + # new interface. since 1.0.0-RELEASE + # void addOutPort(const char* name, OutPortBase& outport); + def addOutPort(self, name, outport): + self._rtcout.RTC_TRACE("addOutPort(%s)", name) + + propkey = "port.outport." + name + prop_ = copy.copy(self._properties.getNode(propkey)) + prop_.mergeProperties( + self._properties.getNode("port.outport.dataport")) + + ret = self.addPort(outport) + + if not ret: + self._rtcout.RTC_ERROR("addOutPort() failed.") + return ret + + outport.init(prop_) + self._outports.append(outport) + return ret + + ## + # @if jp + # + # @brief [local interface] InPort の登録を削除する + # + # RTC が保持するInPortの登録を削除する。 + # + # @param port 削除対象 Port + # @return 削除結果(削除成功:true,削除失敗:false) + # + # @else + # + # @brief [local interface] Unregister InPort + # + # This operation unregisters a InPort held by this RTC. + # + # @param port Port which is unregistered + # @return Unregister result (Successful:true, Failed:false) + # + # @endif + # + # bool removeInPort(InPortBase& port); + + def removeInPort(self, port): + self._rtcout.RTC_TRACE("removeInPort()") + ret = self.removePort(port) + + if ret: + for inport in self._inports: + if port == inport: + + self._inports.remove(port) + + return True - ## - # @if jp - # - # @brief [ComponentAction CORBA interface] RTC γ - # - # ° ExecutionContext RTC 줿ݤ˸ƤӽФ롣 - # Υڥ졼ƤӽФη̤Ȥ onActivated() Хåؿ - # ƤӽФ롣 - # - # @param self - # @param ec_id ExecutionContext ID - # - # @return ReturnCode_t Υ꥿󥳡 - # - # @else - # - # @brief [ComponentAction CORBA interface] Activate RTC - # - # The RTC has been activated in the given execution context. - # - # @param ec_id - # - # @return - # - # @endif - def on_activated(self, ec_id): - self._rtcout.RTC_TRACE("on_activated(%d)", ec_id) - ret = RTC.RTC_ERROR - try: - self.preOnActivated(ec_id) - self._configsets.update() - ret = self.onActivated(ec_id) - self._portAdmin.activatePorts() - except: - self._rtcout.RTC_ERROR(OpenRTM_aist.Logger.print_exception()) - ret = RTC.RTC_ERROR - self.postOnActivated(ec_id, ret) - return ret + return False + ## + # @if jp + # + # @brief [local interface] OutPort の登録を削除する + # + # RTC が保持するOutPortの登録を削除する。 + # + # @param port 削除対象 Port + # @return 削除結果(削除成功:true,削除失敗:false) + # + # @else + # + # @brief [local interface] Unregister OutPort + # + # This operation unregisters a OutPort held by this RTC. + # + # @param port Port which is unregistered + # @return Unregister result (Successful:true, Failed:false) + # + # @endif + # + # bool removeOutPort(OutPortBase& port); + + def removeOutPort(self, port): + self._rtcout.RTC_TRACE("removeOutPort()") + ret = self.removePort(port) + + if ret: + for outport in self._outports: + if port == outport: + + self._outports.remove(port) + + return True - ## - # @if jp - # - # @brief [ComponentAction CORBA interface] RTC - # - # ° ExecutionContext RTC 줿ݤ˸ƤӽФ롣 - # Υڥ졼ƤӽФη̤Ȥ onDeactivated() Хåؿ - # ƤӽФ롣 - # - # @param self - # @param ec_id ExecutionContext ID - # - # @return ReturnCode_t Υ꥿󥳡 - # - # @else - # - # @brief [ComponentAction CORBA interface] Deactivate RTC - # - # The RTC has been deactivated in the given execution context. - # - # @param ec_id - # - # @return - # - # @endif - def on_deactivated(self, ec_id): - self._rtcout.RTC_TRACE("on_deactivated(%d)", ec_id) - ret = RTC.RTC_ERROR - try: - self.preOnDeactivated(ec_id) - self._portAdmin.deactivatePorts() - ret = self.onDeactivated(ec_id) - except: - self._rtcout.RTC_ERROR(OpenRTM_aist.Logger.print_exception()) - ret = RTC.RTC_ERROR - self.postOnDeactivated(ec_id, ret) - return ret + return False + ## + # @if jp + # + # @brief [local interface] Port の登録を削除する + # + # RTC が保持するPortの登録を削除する。 + # + # @param self + # @param port 削除対象 Port + # + # @else + # + # @brief [local interface] Unregister Port + # + # This operation unregisters a Port to be held by this RTC. + # + # @param port Port which is unregistered in the RTC + # + # @endif + # void RTObject_impl::deletePort(PortBase& port) + + def deletePort(self, port): + self._rtcout.RTC_TRACE("deletePort()") + if not self.removePort(port): + self._rtcout.RTC_ERROR("removePort() failed.") + return - ## - # @if jp - # - # @brief [ComponentAction CORBA interface] RTC Υ顼֤ؤ - # - # RTC ° ExecutionContext Active ֤ Error ֤ܤ - # ˸ƤӽФ롣 - # Υڥ졼 RTC Error ֤ܤݤ˰٤ƤӽФ롣 - # Υڥ졼ƤӽФη̤Ȥ onAborting() Хåؿ - # ƤӽФ롣 - # - # @param self - # @param ec_id ܤ ExecutionContext ID - # - # @return ReturnCode_t Υ꥿󥳡 - # - # @else - # - # @brief [ComponentAction CORBA interface] Transition Error State - # - # The RTC is transitioning from the Active state to the Error state in some - # execution context. - # This callback is invoked only a single time for time that the RTC - # transitions into the Error state from another state. This behavior is in - # contrast to that of on_error. - # - # @param ec_id - # - # @return - # - # @endif - def on_aborting(self, ec_id): - self._rtcout.RTC_TRACE("on_aborting(%d)", ec_id) - ret = RTC.RTC_ERROR - try: - self.preOnAborting(ec_id) - ret = self.onAborting(ec_id) - except: - self._rtcout.RTC_ERROR(OpenRTM_aist.Logger.print_exception()) - ret = RTC.RTC_ERROR - self.postOnAborting(ec_id, ret) - return ret + # new interface. since 1.0.0-RELEASE + def removePort(self, port): + self._rtcout.RTC_TRACE("removePort()") + if isinstance(port, OpenRTM_aist.PortBase) or isinstance( + port, OpenRTM_aist.CorbaPort): + self.onRemovePort(port.getPortProfile()) + return self._portAdmin.removePort(port) + + ## + # @if jp + # + # @brief [local interface] 名前指定により Port の登録を削除する + # + # 名称を指定して RTC が保持するPortの登録を削除する。 + # + # @param self + # @param port_name 削除対象 Port 名 + # + # @else + # + # @endif + + def deletePortByName(self, port_name): + self._rtcout.RTC_TRACE("deletePortByName(%s)", port_name) + self._portAdmin.deletePortByName(port_name) + return + ## + # @if jp + # + # @brief [local interface] 実行コンテキストを取得する + # + # get_context() と同じ機能のローカル版。違いはない。 + # この関数は以下の関数内で呼ばれることを前提としている。 + # + # - onStartup() + # - onShutdown() + # - onActivated() + # - onDeactivated() + # - onExecute() + # - onAborting() + # - onError() + # - onReset() + # - onStateUpdate() + # - onRateChanged() + # + # この関数の引数はこれらの関数の引数 UniquieID exec_handle でなけ + # ればならない。 + # + # @param ec_id 上記関数の第1引数 exec_handle を渡す必要がある。 + # + # @else + # + # @brief [local interface] Getting current execution context + # + # This function is the local version of get_context(). completely + # same as get_context() function. This function is assumed to be + # called from the following functions. + # + # - onStartup() + # - onShutdown() + # - onActivated() + # - onDeactivated() + # - onExecute() + # - onAborting() + # - onError() + # - onReset() + # - onStateUpdate() + # - onRateChanged() + # + # The argument of this function should be the first argument + # (UniqueId ec_id) of the above functions. + # + # @param ec_id The above functions' first argument "exec_handle." + # + # @endif + # + # ExecutionContext_ptr getExecutionContext(RTC::UniqueId ec_id); + + def getExecutionContext(self, ec_id): + return self.get_context(ec_id) + + ## + # @if jp + # + # @brief [local interface] 実行コンテキストの実行レートを取得する + # + # 現在実行中の実行コンテキストの実行レートを取得する。実行コンテキ + # ストのKindがPERIODIC以外の場合の動作は未定義である。この関数は以 + # 下の関数内で呼ばれることを前提としている。 + # + # - onStartup() + # - onShutdown() + # - onActivated() + # - onDeactivated() + # - onExecute() + # - onAborting() + # - onError() + # - onReset() + # - onStateUpdate() + # - onRateChanged() + # + # この関数の引数はこれらの関数の引数 UniquieID exec_handle でなけ + # ればならない。 + # + # @param ec_id 上記関数の第1引数 exec_handle を渡す必要がある。 + # + # @else + # + # @brief [local interface] Getting current context' execution rate + # + # This function returns current execution rate in this + # context. If this context's kind is not PERIODC, behavior is not + # defined. This function is assumed to be called from the + # following functions. + # + # - onStartup() + # - onShutdown() + # - onActivated() + # - onDeactivated() + # - onExecute() + # - onAborting() + # - onError() + # - onReset() + # - onStateUpdate() + # - onRateChanged() + # + # The argument of this function should be the first argument + # (UniqueId ec_id) of the above functions. + # + # @param ec_id The above functions' first argument "exec_handle." + # + # @endif + # + # double getExecutionRate(RTC::UniqueId ec_id); + def getExecutionRate(self, ec_id): + ec = self.getExecutionContext(ec_id) + if CORBA.is_nil(ec): + return 0.0 + + return ec.get_rate() + + ## + # @if jp + # + # @brief [local interface] 実行コンテキストの実行レートを設定する + # + # 現在実行中の実行コンテキストの実行レートを設定する。実行コンテキ + # ストのKindがPERIODIC以外の場合の動作は未定義である。この関数は以 + # 下の関数内で呼ばれることを前提としている。 + # + # - onStartup() + # - onShutdown() + # - onActivated() + # - onDeactivated() + # - onExecute() + # - onAborting() + # - onError() + # - onReset() + # - onStateUpdate() + # - onRateChanged() + # + # この関数の引数はこれらの関数の引数 UniquieID exec_handle でなけ + # ればならない。 + # + # @param ec_id 上記関数の第1引数 exec_handle を渡す必要がある。 + # @param rate 実行レートを [Hz] で与える + # + # @else + # + # @brief [local interface] Setting current context' execution rate + # + # This function sets a execution rate in the context. If this + # context's kind is not PERIODC, behavior is not defined. This + # function is assumed to be called from the following functions. + # + # - onStartup() + # - onShutdown() + # - onActivated() + # - onDeactivated() + # - onExecute() + # - onAborting() + # - onError() + # - onReset() + # - onStateUpdate() + # - onRateChanged() + # + # The argument of this function should be the first argument + # (UniqueId ec_id) of the above functions. + # + # @param ec_id The above functions' first argument "exec_handle." + # @param rate Execution rate in [Hz]. + # + # @endif + # + # ReturnCode_t setExecutionRate(RTC::UniqueId ec_id, double rate); + + def setExecutionRate(self, ec_id, rate): + ec = self.getExecutionContext(ec_id) + if CORBA.is_nil(ec): + return RTC.RTC_ERROR + ec.set_rate(rate) + return RTC.RTC_OK - ## - # @if jp - # - # @brief [ComponentAction CORBA interface] RTC Υ顼 - # - # RTC 顼֤ˤݤ˸ƤӽФ롣 - # RTC 顼֤ξˡоݤȤʤ ExecutionContext ExecutionKind - # ߥ󥰤ǸƤӽФ롣㤨С - # - ExecutionKind PERIODIC ξ硢ܥڥ졼 - # DataFlowComponentAction::on_execute on_state_update ؤˡ - # ꤵ줿֡ꤵ줿ǸƤӽФ롣 - # - ExecutionKind EVENT_DRIVEN ξ硢ܥڥ졼 - # FsmParticipantAction::on_action ƤФ줿ݤˡؤ˸ƤӽФ롣 - # Υڥ졼ƤӽФη̤Ȥ onError() ХåؿƤӽ - # 롣 - # - # @param self - # @param ec_id о ExecutionContext ID - # - # @return ReturnCode_t Υ꥿󥳡 - # - # @else - # - # @brief [ComponentAction CORBA interface] Error Processing of RTC - # - # The RTC remains in the Error state. - # If the RTC is in the Error state relative to some execution context when - # it would otherwise be invoked from that context (according to the - # contexts ExecutionKind), this callback shall be invoked instead. - # For example, - # - If the ExecutionKind is PERIODIC, this operation shall be invoked in - # sorted order at the rate of the context instead of - # DataFlowComponentAction::on_execute and on_state_update. - # - If the ExecutionKind is EVENT_DRIVEN, this operation shall be invoked - # whenever FsmParticipantAction::on_action would otherwise have been - # invoked. - # - # @param ec_id - # - # @return - # - # @endif - def on_error(self, ec_id): - self._rtcout.RTC_TRACE("on_error(%d)", ec_id) - ret = RTC.RTC_ERROR - try: - self.preOnError(ec_id) - ret = self.onError(ec_id) - except: - self._rtcout.RTC_ERROR(OpenRTM_aist.Logger.print_exception()) - ret = RTC.RTC_ERROR - self._configsets.update() - self.postOnError(ec_id, ret) - return ret + ## + # @if jp + # + # @brief [local interface] 実行コンテキストの所有権を調べる + # + # 現在実行中の実行コンテキストの所有権を調べる。この関数は以下の関 + # 数内で呼ばれることを前提としている。 + # + # - onStartup() + # - onShutdown() + # - onActivated() + # - onDeactivated() + # - onExecute() + # - onAborting() + # - onError() + # - onReset() + # - onStateUpdate() + # - onRateChanged() + # + # この関数の引数はこれらの関数の引数 UniquieID exec_handle でなけ + # ればならない。 + # + # @param ec_id 上記関数の第1引数 exec_handle を渡す必要がある。 + # @return true: 自身の実行コンテキスト、false: 他の実行コンテキスト + # + # @else + # + # @brief [local interface] Checking if the current context is own context + # + # This function checks if the current context is own execution + # context. This function is assumed to be called from the + # following functions. + # + # - onStartup() + # - onShutdown() + # - onActivated() + # - onDeactivated() + # - onExecute() + # - onAborting() + # - onError() + # - onReset() + # - onStateUpdate() + # - onRateChanged() + # + # The argument of this function should be the first argument + # (UniqueId ec_id) of the above functions. + # + # @param ec_id The above functions' first argument "exec_handle." + # @return true: Own context, false: other's context + # + # @endif + # + # bool isOwnExecutionContext(RTC::UniqueId ec_id); + + def isOwnExecutionContext(self, ec_id): + global ECOTHER_OFFSET + if ec_id < ECOTHER_OFFSET: + return True + return False + ## + # @if jp + # + # @brief [local interface] 状態を Inactive に遷移させる + # + # 状態を Active から Inactive に遷移させる。この関数は以下の関 + # 数内で呼ばれることを前提としている。 + # + # - onActivated() + # - onExecute() + # - onStateUpdate() + # + # この関数の引数は上記の関数の引数 UniquieID exec_handle でなけ + # ればならない。 + # + # @param ec_id 上記関数の第1引数 exec_handle を渡す必要がある。 + # @return リターンコード + # + # @else + # + # @brief [local interface] Make transition to Inactive state + # + # This function makes transition from Active to Inactive + # state. This function is assumed to be called from the following + # functions. + # + # - onActivated() + # - onExecute() + # - onStateUpdate() + # + # The argument of this function should be the first argument + # (UniqueId ec_id) of the above function. + # + # @param ec_id The above functions' first argument "exec_handle." + # @return Return code + # + # @endif + # + # ReturnCode_t deactivate(RTC::UniqueId ec_id); + + def deactivate(self, ec_id): + ec = self.getExecutionContext(ec_id) + if CORBA.is_nil(ec): + return RTC.RTC_ERROR + return ec.deactivate_component(self.getObjRef()) + + ## + # @if jp + # + # @brief [local interface] 状態を Active に遷移させる + # + # 状態を Inactive から Active に遷移させる。この関数は以下の関 + # 数内で呼ばれることを前提としている。 + # + # - onStartup() + # - onDeactivated() + # + # この関数の引数は上記の関数の引数 UniquieID exec_handle でなけ + # ればならない。 + # + # @param ec_id 上記関数の第1引数 exec_handle を渡す必要がある。 + # @return リターンコード + # + # @else + # + # @brief [local interface] Make transition to Active state + # + # This function makes transition from Inactive to Active + # state. This function is assumed to be called from the following + # functions. + # + # - onStartup() + # - onDeactivated() + # + # The argument of this function should be the first argument + # (UniqueId ec_id) of the above function. + # + # @param ec_id The above functions' first argument "exec_handle." + # @return Return code + # + # @endif + # + # ReturnCode_t activate(RTC::UniqueId ec_id); + + def activate(self, ec_id): + ec = self.getExecutionContext(ec_id) + if CORBA.is_nil(ec): + return RTC.RTC_ERROR + return ec.activate_component(self.getObjRef()) + + ## + # @if jp + # + # @brief [local interface] 状態をリセットし Inactive に遷移させる + # + # 状態を Error から Inactive に遷移させる。この関数は以下の関 + # 数内で呼ばれることを前提としている。 + # + # - onError() + # + # この関数の引数は上記の関数の引数 UniquieID exec_handle でなけ + # ればならない。 + # + # @param ec_id 上記関数の第1引数 exec_handle を渡す必要がある。 + # @return リターンコード + # + # @else + # + # @brief [local interface] Resetting and go to Inactive state + # + # This function reset RTC and makes transition from Error to Inactive + # state. This function is assumed to be called from the following + # functions. + # + # - onError() + # + # The argument of this function should be the first argument + # (UniqueId ec_id) of the above function. + # + # @param ec_id The above functions' first argument "exec_handle." + # @return Return code + # + # @endif + # + # ReturnCode_t reset(RTC::UniqueId ec_id); + + def reset(self, ec_id): + ec = self.getExecutionContext(ec_id) + if CORBA.is_nil(ec): + return RTC.RTC_ERROR + return ec.reset_component(self.getObjRef()) + + ## + # @if jp + # @brief [local interface] SDO service provider をセットする + # @else + # @brief [local interface] Set a SDO service provider + # @endif + # + # bool addSdoServiceProvider(const SDOPackage::ServiceProfile& prof, + # SdoServiceProviderBase* provider); + + def addSdoServiceProvider(self, prof, provider): + return self._sdoservice.addSdoServiceProvider(prof, provider) + + ## + # @if jp + # @brief [local interface] SDO service provider を削除する + # @else + # @brief [local interface] Remove a SDO service provider + # @endif + # + # bool removeSdoServiceProvider(const char* id); + + def removeSdoServiceProvider(self, id): + return self._sdoservice.removeSdoServiceProvider(id) + + ## + # @if jp + # @brief [local interface] SDO service consumer をセットする + # @else + # @brief [local interface] Set a SDO service consumer + # @endif + # + # bool addSdoServiceConsumer(const SDOPackage::ServiceProfile& prof); + + def addSdoServiceConsumer(self, prof): + return self._sdoservice.addSdoServiceConsumer(prof) + + ## + # @if jp + # @brief [local interface] SDO service consumer を削除する + # @else + # @brief [local interface] Remove a SDO service consumer + # @endif + # + # bool removeSdoServiceConsumer(const char* id); + + def removeSdoServiceConsumer(self, id): + return self._sdoservice.removeSdoServiceConsumer(id) + + ## + # @if jp + # @brief [local interface] SDO service consumer を別スレッドで削除する + # @else + # @brief [local interface] Remove a SDO service consumer + # @endif + # + # bool removeSdoServiceConsumer(const char* id); + + def removeSdoServiceConsumerStartThread(self, id): + class remove_Task(OpenRTM_aist.Task): + def __init__(self, sdoservice, id): + OpenRTM_aist.Task.__init__(self) + self._sdoservice = sdoservice + self._id = id + + def svc(self): + self._sdoservice.removeSdoServiceConsumer(self._id) + + self._sdoservice.removeSdoServiceConsumer(id) + self.remove_thread = remove_Task(self._sdoservice, id) + self.remove_thread.activate() + + ## + # @if jp + # + # @brief 全 InPort のデータを読み込む。 + # + # RTC が保持する全ての InPort のデータを読み込む。 + # + # @return 読み込み結果(全ポートの読み込み成功:true,失敗:false) + # + # @else + # + # @brief Readout the value from All InPorts. + # + # This operation read the value from all InPort + # registered in the RTC. + # + # @return result (Successful:true, Failed:false) + # + # @endif + # + # bool readAll(); + def readAll(self): + self._rtcout.RTC_TRACE("readAll()") + ret = True + for inport in self._inports: + if not inport.read(): + self._rtcout.RTC_DEBUG("The error occurred in readAll().") + ret = False + if not self._readAllCompletion: + return False + + return ret + + ## + # @if jp + # + # @brief 全 OutPort のwrite()メソッドをコールする。 + # + # RTC が保持する全ての OutPort のwrite()メソッドをコールする。 + # + # @return 読み込み結果(全ポートへの書き込み成功:true,失敗:false) + # + # @else + # + # @brief The write() method of all OutPort is called. + # + # This operation call the write() method of all OutPort + # registered in the RTC. + # + # @return result (Successful:true, Failed:false) + # + # @endif + # + # bool writeAll(); + + def writeAll(self): + self._rtcout.RTC_TRACE("writeAll()") + ret = True + for outport in self._outports: + if not outport.write(): + self._rtcout.RTC_DEBUG("The error occurred in writeAll().") + ret = False + if not self._writeAllCompletion: + return False + + return ret + + ## + # @if jp + # + # @brief onExecute()実行前でのreadAll()メソッドの呼出を有効または無効にする。 + # + # このメソッドをパラメータをtrueとして呼ぶ事により、onExecute()実行前に + # readAll()が呼出されるようになる。 + # パラメータがfalseの場合は、readAll()呼出を無効にする。 + # + # @param read(default:true) + # (readAll()メソッド呼出あり:true, readAll()メソッド呼出なし:false) + # + # @param completion(default:false) + # readAll()にて、どれかの一つのInPortのread()が失敗しても全てのInPortのread()を呼び出す:true, + # readAll()にて、どれかの一つのInPortのread()が失敗した場合、すぐにfalseで抜ける:false + # + # @else + # + # @brief Set whether to execute the readAll() method. + # + # Set whether to execute the readAll() method. + # + # @param read(default:true) + # (readAll() is called:true, readAll() isn't called:false) + # + # @param completion(default:false) + # All InPort::read() calls are completed.:true, + # If one InPort::read() is False, return false.:false + # + # @param completion(default:false) + # + # @endif + # + # void setReadAll(bool read=true, bool completion=false); + + def setReadAll(self, read=True, completion=False): + self._readAll = read + self._readAllCompletion = completion + + ## + # @if jp + # + # @brief onExecute()実行後にwriteAll()メソッドの呼出を有効または無効にする。 + # + # このメソッドをパラメータをtrueとして呼ぶ事により、onExecute()実行後に + # writeAll()が呼出されるようになる。 + # パラメータがfalseの場合は、writeAll()呼出を無効にする。 + # + # @param write(default:true) + # (writeAll()メソッド呼出あり:true, writeAll()メソッド呼出なし:false) + # + # @param completion(default:false) + # writeAll()にて、どれかの一つのOutPortのwrite()が失敗しても全てのOutPortのwrite()を呼び出しを行う:true, + # writeAll()にて、どれかの一つのOutPortのwrite()が失敗した場合、すぐにfalseで抜ける:false + # + # @else + # + # @brief Set whether to execute the writeAll() method. + # + # Set whether to execute the writeAll() method. + # + # @param write(default:true) + # (writeAll() is called:true, writeAll() isn't called:false) + # + # @param completion(default:false) + # All OutPort::write() calls are completed.:true, + # If one OutPort::write() is False, return false.:false + # + # @endif + # + # void setWriteAll(bool write=true, bool completion=false); + + def setWriteAll(self, write=True, completion=False): + self._writeAll = write + self._writeAllCompletion = completion + + ## + # @if jp + # + # @brief 全 Port の登録を削除する + # + # RTC が保持する全ての Port を削除する。 + # + # @param self + # + # @else + # + # @brief Unregister the All Portse + # + # This operation deactivates the all Port and deletes the all Port's + # registrations in the RTC.. + # + # @endif + + def finalizePorts(self): + self._rtcout.RTC_TRACE("finalizePorts()") + self._portAdmin.finalizePorts() + self._inports = [] + self._outports = [] + return - ## - # @if jp - # - # @brief [ComponentAction CORBA interface] RTC Υꥻå - # - # Error ֤ˤ RTC ΥꥫХ¹ԤInactive ֤ - # ˸ƤӽФ롣 - # RTC ΥꥫХ Inactive ֤뤬ʳ - # ˤ Error ֤αޤ롣 - # Υڥ졼ƤӽФη̤Ȥ onReset() ХåؿƤ - # Ф롣 - # - # @param self - # @param ec_id ꥻåо ExecutionContext ID - # - # @return ReturnCode_t Υ꥿󥳡 - # - # @else - # - # @brief [ComponentAction CORBA interface] Resetting RTC - # - # The RTC is in the Error state. An attempt is being made to recover it such - # that it can return to the Inactive state. - # If the RTC was successfully recovered and can safely return to the - # Inactive state, this method shall complete with ReturnCode_t::OK. Any - # other result shall indicate that the RTC should remain in the Error state. - # - # @param ec_id - # - # @return - # - # @endif - def on_reset(self, ec_id): - self._rtcout.RTC_TRACE("on_reset(%d)", ec_id) - ret = RTC.RTC_ERROR - try: - self.preOnReset(ec_id) - ret = self.onReset(ec_id) - except: - self._rtcout.RTC_ERROR(OpenRTM_aist.Logger.print_exception()) - ret = RTC.RTC_ERROR - self.postOnReset(ec_id, ret) - return ret + def finalizeContexts(self): + self._rtcout.RTC_TRACE("finalizeContexts()") + for ec in self._eclist: + ec.stop() + rtcs = ec.getComponentList() + for rtc in rtcs: + try: + ec.removeComponent(rtc) + except BaseException: + self._rtcout.RTC_ERROR("UnKonwn error()") + try: + self._poa.deactivate_object(self._poa.servant_to_id(ec)) + except BaseException: + self._rtcout.RTC_TRACE(OpenRTM_aist.Logger.print_exception()) + ec.exit() + self._eclist = [] + return + ## + # @if jp + # @brief PreComponentActionListener リスナを追加する + # + # ComponentAction 実装関数の呼び出し直前のイベントに関連する各種リ + # スナを設定する。 + # + # 設定できるリスナのタイプとコールバックイベントは以下の通り + # + # - PRE_ON_INITIALIZE: onInitialize 直前 + # - PRE_ON_FINALIZE: onFinalize 直前 + # - PRE_ON_STARTUP: onStartup 直前 + # - PRE_ON_SHUTDOWN: onShutdown 直前 + # - PRE_ON_ACTIVATED: onActivated 直前 + # - PRE_ON_DEACTIVATED: onDeactivated 直前 + # - PRE_ON_ABORTING: onAborted 直前 + # - PRE_ON_ERROR: onError 直前 + # - PRE_ON_RESET: onReset 直前 + # - PRE_ON_EXECUTE: onExecute 直前 + # - PRE_ON_STATE_UPDATE: onStateUpdate 直前 + # + # リスナは PreComponentActionListener を継承し、以下のシグニチャを持つ + # operator() を実装している必要がある。 + # + # PreComponentActionListener::operator()(UniqueId ec_id) + # + # デフォルトでは、この関数に与えたリスナオブジェクトの所有権は + # RTObjectに移り、RTObject解体時もしくは、 + # removePreComponentActionListener() により削除時に自動的に解体される。 + # リスナオブジェクトの所有権を呼び出し側で維持したい場合は、第3引 + # 数に false を指定し、自動的な解体を抑制することができる。 + # + # @param listener_type リスナタイプ + # @param memfunc 関数オブジェクト + # + # @else + # @brief Adding PreComponentAction type listener + # + # This operation adds certain listeners related to ComponentActions + # pre events. + # The following listener types are available. + # + # - PRE_ON_INITIALIZE: before onInitialize + # - PRE_ON_FINALIZE: before onFinalize + # - PRE_ON_STARTUP: before onStartup + # - PRE_ON_SHUTDOWN: before onShutdown + # - PRE_ON_ACTIVATED: before onActivated + # - PRE_ON_DEACTIVATED: before onDeactivated + # - PRE_ON_ABORTING: before onAborted + # - PRE_ON_ERROR: before onError + # - PRE_ON_RESET: before onReset + # - PRE_ON_EXECUTE: before onExecute + # - PRE_ON_STATE_UPDATE: before onStateUpdate + # + # Listeners should have the following function operator(). + # + # PreComponentActionListener::operator()(UniqueId ec_id) + # + # The ownership of the given listener object is transferred to + # this RTObject object in default. The given listener object will + # be destroied automatically in the RTObject's dtor or if the + # listener is deleted by removePreComponentActionListener() function. + # If you want to keep ownership of the listener object, give + # "false" value to 3rd argument to inhibit automatic destruction. + # + # @param listener_type A listener type + # @param memfunc member function object + # + # @endif + # + # template + # PreComponentActionListener* + # addPreComponentActionListener(PreCompActionListenerType listener_type, + # void (Listener::*memfunc)(UniqueId ec_id)) + + def addPreComponentActionListener(self, listener_type, + memfunc): + class Noname(OpenRTM_aist.PreComponentActionListener): + def __init__(self, memfunc): + self._memfunc = memfunc + + def __call__(self, ec_id): + self._memfunc(ec_id) + return + + listener = Noname(memfunc) + self._actionListeners.addPreActionListener(listener_type, listener) + return listener + + ## + # @if jp + # @brief PreComponentActionListener リスナを削除する + # + # 設定した各種リスナを削除する。 + # + # @param listener_type リスナタイプ + # @param listener リスナオブジェクトへのポインタ + # + # @else + # @brief Removing PreComponentAction type listener + # + # This operation removes a specified listener. + # + # @param listener_type A listener type + # @param listener A pointer to a listener object + # + # @endif + # + # void + # removePreComponentActionListener(PreComponentActionListenerType listener_type, + # PreComponentActionListener* listener); + + def removePreComponentActionListener(self, listener_type, listener): + self._actionListeners.removePreActionListener(listener_type, listener) + return + ## + # @if jp + # @brief PostComponentActionListener リスナを追加する + # + # ComponentAction 実装関数の呼び出し直後のイベントに関連する各種リ + # スナを設定する。 + # + # 設定できるリスナのタイプとコールバックイベントは以下の通り + # + # - POST_ON_INITIALIZE: onInitialize 直後 + # - POST_ON_FINALIZE: onFinalize 直後 + # - POST_ON_STARTUP: onStartup 直後 + # - POST_ON_SHUTDOWN: onShutdown 直後 + # - POST_ON_ACTIVATED: onActivated 直後 + # - POST_ON_DEACTIVATED: onDeactivated 直後 + # - POST_ON_ABORTING: onAborted 直後 + # - POST_ON_ERROR: onError 直後 + # - POST_ON_RESET: onReset 直後 + # - POST_ON_EXECUTE: onExecute 直後 + # - POST_ON_STATE_UPDATE: onStateUpdate 直後 + # + # リスナは PostComponentActionListener を継承し、以下のシグニチャを持つ + # operator() を実装している必要がある。 + # + # PostComponentActionListener::operator()(UniqueId ec_id, ReturnCode_t ret) + # + # デフォルトでは、この関数に与えたリスナオブジェクトの所有権は + # RTObjectに移り、RTObject解体時もしくは、 + # removePostComponentActionListener() により削除時に自動的に解体される。 + # リスナオブジェクトの所有権を呼び出し側で維持したい場合は、第3引 + # 数に false を指定し、自動的な解体を抑制することができる。 + # + # @param listener_type リスナタイプ + # @param memfunc 関数オブジェクト + # + # @else + # @brief Adding PostComponentAction type listener + # + # This operation adds certain listeners related to ComponentActions + # post events. + # The following listener types are available. + # + # - POST_ON_INITIALIZE: after onInitialize + # - POST_ON_FINALIZE: after onFinalize + # - POST_ON_STARTUP: after onStartup + # - POST_ON_SHUTDOWN: after onShutdown + # - POST_ON_ACTIVATED: after onActivated + # - POST_ON_DEACTIVATED: after onDeactivated + # - POST_ON_ABORTING: after onAborted + # - POST_ON_ERROR: after onError + # - POST_ON_RESET: after onReset + # - POST_ON_EXECUTE: after onExecute + # - POST_ON_STATE_UPDATE: after onStateUpdate + # + # Listeners should have the following function operator(). + # + # PostComponentActionListener::operator()(UniqueId ec_id, ReturnCode_t ret) + # + # The ownership of the given listener object is transferred to + # this RTObject object in default. The given listener object will + # be destroied automatically in the RTObject's dtor or if the + # listener is deleted by removePostComponentActionListener() function. + # If you want to keep ownership of the listener object, give + # "false" value to 3rd argument to inhibit automatic destruction. + # + # @param listener_type A listener type + # @param memfunc member function object + # + # @endif + # + # template + # PostComponentActionListener* + # addPostComponentActionListener(PostCompActionListenerType listener_type, + # void (Listener::*memfunc)(UniqueId ec_id, + # ReturnCode_t ret)) + + def addPostComponentActionListener(self, listener_type, + memfunc): + class Noname(OpenRTM_aist.PostComponentActionListener): + def __init__(self, memfunc): + self._memfunc = memfunc + return + + def __call__(self, ec_id, ret): + self._memfunc(ec_id, ret) + return + + listener = Noname(memfunc) + self._actionListeners.addPostActionListener(listener_type, listener) + return listener + + ## + # @if jp + # @brief PostComponentActionListener リスナを削除する + # + # 設定した各種リスナを削除する。 + # + # @param listener_type リスナタイプ + # @param listener リスナオブジェクトへのポインタ + # + # @else + # @brief Removing PostComponentAction type listener + # + # This operation removes a specified listener. + # + # @param listener_type A listener type + # @param listener A pointer to a listener object + # + # @endif + ## + # void + # removePostComponentActionListener(PostComponentActionListenerType listener_type, + # PostComponentActionListener* listener); + + def removePostComponentActionListener(self, listener_type, listener): + self._actionListeners.removePostActionListener(listener_type, listener) + return + ## + # @if jp + # @brief PortActionListener リスナを追加する + # + # Portの追加、削除時にコールバックされる各種リスナを設定する。 + # + # 設定できるリスナのタイプとコールバックイベントは以下の通り + # + # - ADD_PORT: Port追加時 + # - REMOVE_PORT: Port削除時 + # + # リスナは PortActionListener を継承し、以下のシグニチャを持つ + # operator() を実装している必要がある。 + # + # PortActionListener::operator()(PortProfile& pprof) + # + # デフォルトでは、この関数に与えたリスナオブジェクトの所有権は + # RTObjectに移り、RTObject解体時もしくは、 + # removePortActionListener() により削除時に自動的に解体される。 + # リスナオブジェクトの所有権を呼び出し側で維持したい場合は、第3引 + # 数に false を指定し、自動的な解体を抑制することができる。 + # + # @param listener_type リスナタイプ + # @param memfunc 関数オブジェクト + # + # @else + # @brief Adding PortAction type listener + # + # This operation adds certain listeners related to ComponentActions + # post events. + # The following listener types are available. + # + # - ADD_PORT: At adding Port + # - REMOVE_PORT: At removing Port + # + # Listeners should have the following function operator(). + # + # PortActionListener::operator()(RTC::PortProfile pprof) + # + # The ownership of the given listener object is transferred to + # this RTObject object in default. The given listener object will + # be destroied automatically in the RTObject's dtor or if the + # listener is deleted by removePortActionListener() function. + # If you want to keep ownership of the listener object, give + # "false" value to 3rd argument to inhibit automatic destruction. + # + # @param listener_type A listener type + # @param memfunc member function object + # + # @endif + # + # template + # PortActionListener* + # addPortActionListener(PortActionListenerType listener_type, + # void (Listener::*memfunc)(const RTC::PortProfile&)) + + def addPortActionListener(self, listener_type, + memfunc): + class Noname(OpenRTM_aist.PortActionListener): + def __init__(self, memfunc): + self._memfunc = memfunc + return + + def __call__(self, pprofile): + self._memfunc(pprofile) + return + + listener = Noname(memfunc) + + self._actionListeners.addPortActionListener(listener_type, listener) + return listener + + ## + # @if jp + # @brief PortActionListener リスナを削除する + # + # 設定した各種リスナを削除する。 + # + # @param listener_type リスナタイプ + # @param listener リスナオブジェクトへのポインタ + # + # @else + # @brief Removing PortAction type listener + # + # This operation removes a specified listener. + # + # @param listener_type A listener type + # @param listener A pointer to a listener object + # + # @endif + # void + # removePortActionListener(PortActionListenerType listener_type, + # PortActionListener* listener); + + def removePortActionListener(self, listener_type, listener): + self._actionListeners.removePortActionListener(listener_type, listener) + return - #============================================================ - # SDOPackage::SdoSystemElement - #============================================================ - - ## - # @if jp - # - # @brief [SDO interface] Organization ꥹȤμ - # - # SDOSystemElement 0Ĥ⤷Ϥʾ Organization ͭ뤳Ȥ - # 롣 SDOSystemElement 1İʾ Organization ͭƤ - # ˤϡΥڥ졼Ͻͭ Organization ΥꥹȤ֤ - # ⤷OrganizationĤͭƤʤжΥꥹȤ֤ - # - # @param self - # - # @return ͭƤ Organization ꥹ - # - # @exception SDONotExists åȤSDO¸ߤʤ(㳰ϡCORBAɸ - # ƥ㳰OBJECT_NOT_EXIST˥ޥåԥ󥰤) - # @exception NotAvailable SDO¸ߤ뤬ʤ - # @exception InternalError Ū顼ȯ - # - # @else - # - # @brief [SDO interface] Getting Organizations - # - # SDOSystemElement can be the owner of zero or more organizations. - # If the SDOSystemElement owns one or more Organizations, this operation - # returns the list of Organizations that the SDOSystemElement owns. - # If it does not own any Organization, it returns empty list. - # - # @return Owned Organization List - # - # @exception SDONotExists if the target SDO does not exist.(This exception - # is mapped to CORBA standard system exception - # OBJECT_NOT_EXIST.) - # @exception NotAvailable if the target SDO is reachable but cannot - # respond. - # @exception InternalError if the target SDO cannot execute the operation - # completely due to some internal error. - # - # @endif - # virtual SDOPackage::OrganizationList* get_owned_organizations() - def get_owned_organizations(self): - self._rtcout.RTC_TRACE("get_owned_organizations()") - - return self._sdoOwnedOrganizations - - - - #============================================================ - # SDOPackage::SDO - #============================================================ - - ## - # @if jp - # - # @brief [SDO interface] SDO ID μ - # - # SDO ID ֤ڥ졼 - # Υڥ졼ϰʲη㳰ȯ롣 - # - # @param self - # - # @return ꥽ǡǥƤ SDO ID - # - # @exception SDONotExists åȤSDO¸ߤʤ(㳰ϡCORBAɸ - # ƥ㳰OBJECT_NOT_EXIST˥ޥåԥ󥰤) - # @exception NotAvailable SDO¸ߤ뤬ʤ - # @exception InternalError Ū顼ȯ - # - # @else - # - # @brief [SDO interface] Getting SDO ID - # - # This operation returns id of the SDO. - # This operation throws SDOException with one of the following types. - # - # @return id of the SDO defined in the resource data model. - # - # @exception SDONotExists if the target SDO does not exist.(This exception - # is mapped to CORBA standard system exception - # OBJECT_NOT_EXIST.) - # @exception NotAvailable if the target SDO is reachable but cannot - # respond. - # @exception InternalError if the target SDO cannot execute the operation - # completely due to some internal error. - # - # @endif - # virtual char* get_sdo_id() - def get_sdo_id(self): - self._rtcout.RTC_TRACE("get_sdo_id()") - - return self._profile.instance_name - - - - ## - # @if jp - # - # @brief [SDO interface] SDO פμ - # - # SDO Type ֤ڥ졼 - # Υڥ졼ϰʲη㳰ȯ롣 - # - # @param self - # - # @return ꥽ǡǥƤ SDO Type - # - # @exception SDONotExists åȤSDO¸ߤʤ(㳰ϡCORBAɸ - # ƥ㳰OBJECT_NOT_EXIST˥ޥåԥ󥰤) - # @exception NotAvailable SDO¸ߤ뤬ʤ - # @exception InternalError Ū顼ȯ - # - # @else - # - # @brief [SDO interface] Getting SDO type - # - # This operation returns sdoType of the SDO. - # This operation throws SDOException with one of the following types. - # - # @return Type of the SDO defined in the resource data model. - # - # @exception SDONotExists if the target SDO does not exist.(This exception - # is mapped to CORBA standard system exception - # OBJECT_NOT_EXIST.) - # @exception NotAvailable if the target SDO is reachable but cannot - # respond. - # @exception InternalError if the target SDO cannot execute the operation - # completely due to some internal error. - # - # @endif - # virtual char* get_sdo_type() - def get_sdo_type(self): - self._rtcout.RTC_TRACE("get_sdo_type()") - - return self._profile.description - - - - ## - # @if jp - # - # @brief [SDO interface] SDO DeviceProfile ꥹȤμ - # - # SDO DeviceProfile ֤ڥ졼 SDO ϡɥǥХ - # ˴ϢդƤʤˤϡ DeviceProfile ֤롣 - # Υڥ졼ϰʲη㳰ȯ롣 - # - # @param self - # - # @return SDO DeviceProfile - # - # @exception SDONotExists åȤSDO¸ߤʤ(㳰ϡCORBAɸ - # ƥ㳰OBJECT_NOT_EXIST˥ޥåԥ󥰤) - # @exception NotAvailable SDO¸ߤ뤬ʤ - # @exception InternalError Ū顼ȯ - # - # @else - # - # @brief [SDO interface] Getting SDO DeviceProfile - # - # This operation returns the DeviceProfile of the SDO. If the SDO does not - # represent any hardware device, then a DeviceProfile with empty values - # are returned. - # This operation throws SDOException with one of the following types. - # - # @return The DeviceProfile of the SDO. - # - # @exception SDONotExists if the target SDO does not exist.(This exception - # is mapped to CORBA standard system exception - # OBJECT_NOT_EXIST.) - # @exception NotAvailable if the target SDO is reachable but cannot - # respond. - # @exception InternalError if the target SDO cannot execute the operation - # completely due to some internal error. - # - # @endif - # virtual SDOPackage::DeviceProfile* get_device_profile() - def get_device_profile(self): - self._rtcout.RTC_TRACE("get_device_profile()") - - return self._SdoConfigImpl.getDeviceProfile() - - - - ## - # @if jp - # - # @brief [SDO interface] SDO ServiceProfile μ - # - # SDO ͭƤ Service ServiceProfile ֤ڥ졼 - # SDO ӥĤͭƤʤˤϡΥꥹȤ֤ - # Υڥ졼ϰʲη㳰ȯ롣 - # - # @param self - # - # @return SDO 󶡤Ƥ Service ServiceProfile - # - # @exception SDONotExists åȤSDO¸ߤʤ(㳰ϡCORBAɸ - # ƥ㳰OBJECT_NOT_EXIST˥ޥåԥ󥰤) - # @exception NotAvailable SDO¸ߤ뤬ʤ - # @exception InternalError Ū顼ȯ - # - # @else - # - # @brief [SDO interface] Getting SDO ServiceProfile - # - # This operation returns a list of ServiceProfiles that the SDO has. - # If the SDO does not provide any service, then an empty list is returned. - # This operation throws SDOException with one of the following types. - # - # @return List of ServiceProfiles of all the services the SDO is - # providing. - # - # @exception SDONotExists if the target SDO does not exist.(This exception - # is mapped to CORBA standard system exception - # OBJECT_NOT_EXIST.) - # @exception NotAvailable if the target SDO is reachable but cannot - # respond. - # @exception InternalError if the target SDO cannot execute the operation - # completely due to some internal error. - # - # @endif - # virtual SDOPackage::ServiceProfileList* get_service_profiles() - def get_service_profiles(self): - self._rtcout.RTC_TRACE("get_service_profiles()") - self._sdoSvcProfiles = self._SdoConfigImpl.getServiceProfiles() - - return self._sdoSvcProfiles - - - - - ## - # @if jp - # - # @brief [SDO interface] ServiceProfileμ - # - # "id" ǻꤵ줿̾Υӥ ServiceProfile ֤ - # - # @param self - # @param _id SDO Service ServiceProfile ˴Ϣդ줿̻ҡ - # - # @return ꤵ줿 SDO Service ServiceProfile - # - # @exception InvalidParameter "id" ǻꤷ ServiceProfile ¸ߤʤ - # "id" null - # @exception SDONotExists åȤSDO¸ߤʤ(㳰ϡCORBAɸ - # ƥ㳰OBJECT_NOT_EXIST˥ޥåԥ󥰤) - # @exception NotAvailable SDO¸ߤ뤬ʤ - # @exception InternalError Ū顼ȯ - # - # @else - # - # @brief [SDO interface] Getting Organizations - # - # This operation returns the ServiceProfile that is specified by the - # argument "id." - # - # @param _id The identifier referring to one of the ServiceProfiles. - # - # @return The profile of the specified service. - # - # @exception InvalidParameter if the ServiceProfile that is specified by - # the argument 'id' does not exist or if 'id' - # is 'null.' - # @exception SDONotExists if the target SDO does not exist.(This exception - # is mapped to CORBA standard system exception - # OBJECT_NOT_EXIST.) - # @exception NotAvailable If the target SDO is reachable but cannot - # respond. - # @exception InternalError If the target SDO cannot execute the operation - # completely due to some internal error. - # - # @endif - # virtual SDOPackage::ServiceProfile* get_service_profile(const char* id) - def get_service_profile(self, _id): - self._rtcout.RTC_TRACE("get_service_profile(%s)", _id) - self._sdoSvcProfiles = self._SdoConfigImpl.getServiceProfiles() - if not _id: - raise SDOPackage.InvalidParameter("get_service_profile(): Empty name.") - - try: - index = OpenRTM_aist.CORBA_SeqUtil.find(self._sdoSvcProfiles, self.svc_name(_id)) - - if index < 0: - raise SDOPackage.InvalidParameter("get_service_profile(): Not found") - - return self._sdoSvcProfiles[index] - except: - self._rtcout.RTC_ERROR(OpenRTM_aist.Logger.print_exception()) - raise SDOPackage.InternalError("get_service_profile()") - - - - - ## - # @if jp - # - # @brief [SDO interface] ꤵ줿 SDO Service μ - # - # Υڥ졼ϰ "id" ǻꤵ줿̾ˤäƶ̤ - # SDO Service ؤΥ֥ȻȤ֤ SDO ˤ󶡤 - # Service Ϥ줾դμ̻Ҥˤ̤롣 - # - # @param self - # @param _id SDO Service ˴Ϣդ줿̻ҡ - # - # @return ׵ᤵ줿 SDO Service ؤλȡ - # - # - # @exception InvalidParameter "id" ǻꤷ ServiceProfile ¸ߤʤ - # "id" null - # @exception SDONotExists åȤSDO¸ߤʤ(㳰ϡCORBAɸ - # ƥ㳰OBJECT_NOT_EXIST˥ޥåԥ󥰤) - # @exception NotAvailable SDO¸ߤ뤬ʤ - # @exception InternalError Ū顼ȯ - # - # @else - # - # @brief [SDO interface] Getting specified SDO Service's reference - # - # This operation returns an object implementing an SDO's service that - # is identified by the identifier specified as an argument. Different - # services provided by an SDO are distinguished with different - # identifiers. See OMG SDO specification Section 2.2.8, "ServiceProfile," - # on page 2-12 for more details. - # - # @param _id The identifier referring to one of the SDO Service - # @return The object implementing the requested service. - # @exception InvalidParameter if argument id is null, or if the - # ServiceProfile that is specified by argument - # id does not exist. - # @exception SDONotExists if the target SDO does not exist.(This exception - # is mapped to CORBA standard system exception - # OBJECT_NOT_EXIST.) - # @exception NotAvailable If the target SDO is reachable but cannot - # respond. - # @exception InternalError If the target SDO cannot execute the operation - # completely due to some internal error. - # - # @endif - # virtual SDOPackage::SDOService_ptr get_sdo_service(const char* id) - def get_sdo_service(self, _id): - self._rtcout.RTC_TRACE("get_sdo_service(%s)", _id) - self._sdoSvcProfiles = self._SdoConfigImpl.getServiceProfiles() - - if not _id: - raise SDOPackage.InvalidParameter("get_service(): Empty name.") - - index = OpenRTM_aist.CORBA_SeqUtil.find(self._sdoSvcProfiles, self.svc_name(_id)) - - if index < 0: - raise SDOPackage.InvalidParameter("get_service(): Not found") - - - return self._sdoSvcProfiles[index].service - - - - - ## - # @if jp - # - # @brief [SDO interface] Configuration ֥Ȥμ - # - # Υڥ졼 Configuration interface ؤλȤ֤ - # Configuration interface ϳ SDO 뤿Υ󥿡ե - # ҤȤĤǤ롣Υ󥿡ե DeviceProfile, ServiceProfile, - # Organization 줿 SDO °ͤꤹ뤿˻Ѥ롣 - # Configuration 󥿡եξܺ٤ˤĤƤϡOMG SDO specification - # 2.3.5, p.2-24 򻲾ȤΤȡ - # - # @param self - # - # @return SDO Configuration 󥿡եؤλ - # - # @exception InterfaceNotImplemented SDOConfiguration󥿡ե - # ʤ - # @exception SDONotExists åȤSDO¸ߤʤ(㳰ϡCORBAɸ - # ƥ㳰OBJECT_NOT_EXIST˥ޥåԥ󥰤) - # @exception NotAvailable SDO¸ߤ뤬ʤ - # @exception InternalError Ū顼ȯ - # - # @else - # - # @brief [SDO interface] Getting Configuration object - # - # This operation returns an object implementing the Configuration - # interface. The Configuration interface is one of the interfaces that - # each SDO maintains. The interface is used to configure the attributes - # defined in DeviceProfile, ServiceProfile, and Organization. - # See OMG SDO specification Section 2.3.5, "Configuration Interface," - # on page 2-24 for more details about the Configuration interface. - # - # @return The Configuration interface of an SDO. - # - # @exception InterfaceNotImplemented The target SDO has no Configuration - # interface. - # @exception SDONotExists if the target SDO does not exist.(This exception - # is mapped to CORBA standard system exception - # OBJECT_NOT_EXIST.) - # @exception NotAvailable The target SDO is reachable but cannot respond. - # @exception InternalError The target SDO cannot execute the operation - # completely due to some internal error. - # @endif - # virtual SDOPackage::Configuration_ptr get_configuration() - def get_configuration(self): - self._rtcout.RTC_TRACE("get_configuration()") - if self._SdoConfig is None: - raise SDOPackage.InterfaceNotImplemented("InterfaceNotImplemented: get_configuration") - - return self._SdoConfig - - - - - ## - # @if jp - # - # @brief [SDO interface] Monitoring ֥Ȥμ - # - # Υڥ졼 Monitoring interface ؤλȤ֤ - # Monitoring interface SDO 륤󥿡եΰĤǤ롣 - # Υ󥿡ե SDO Υץѥƥ˥󥰤뤿 - # Ѥ롣 - # Monitoring interface ξܺ٤ˤĤƤ OMG SDO specification - # 2.3.7 "Monitoring Interface" p.2-35 򻲾ȤΤȡ - # - # @param self - # - # @return SDO Monitoring interface ؤλ - # - # @exception InterfaceNotImplemented SDOConfiguration󥿡ե - # ʤ - # @exception SDONotExists åȤSDO¸ߤʤ(㳰ϡCORBAɸ - # ƥ㳰OBJECT_NOT_EXIST˥ޥåԥ󥰤) - # @exception NotAvailable SDO¸ߤ뤬ʤ - # @exception InternalError Ū顼ȯ - # - # @else - # - # @brief [SDO interface] Get Monitoring object - # - # This operation returns an object implementing the Monitoring interface. - # The Monitoring interface is one of the interfaces that each SDO - # maintains. The interface is used to monitor the properties of an SDO. - # See OMG SDO specification Section 2.3.7, "Monitoring Interface," on - # page 2-35 for more details about the Monitoring interface. - # - # @return The Monitoring interface of an SDO. - # - # @exception InterfaceNotImplemented The target SDO has no Configuration - # interface. - # @exception SDONotExists if the target SDO does not exist.(This exception - # is mapped to CORBA standard system exception - # OBJECT_NOT_EXIST.) - # @exception NotAvailable The target SDO is reachable but cannot respond. - # @exception InternalError The target SDO cannot execute the operation - # completely due to some internal error. - # @endif - # virtual SDOPackage::Monitoring_ptr get_monitoring() - def get_monitoring(self): - self._rtcout.RTC_TRACE("get_monitoring()") - raise SDOPackage.InterfaceNotImplemented("Exception: get_monitoring") - - - - ## - # @if jp - # - # @brief [SDO interface] Organization ꥹȤμ - # - # SDO 0İʾ Organization (ȿ)˽°뤳ȤǤ롣 ⤷ SDO - # 1İʾ Organization ˽°Ƥ硢Υڥ졼Ͻ° - # Organization ΥꥹȤ֤SDO ɤ Organization ˤ°Ƥʤ - # ˤϡΥꥹȤ֤롣 - # - # @param self - # - # @return SDO ° Organization Υꥹȡ - # - # @exception SDONotExists åȤSDO¸ߤʤ(㳰ϡCORBAɸ - # ƥ㳰OBJECT_NOT_EXIST˥ޥåԥ󥰤) - # @exception NotAvailable SDO¸ߤ뤬ʤ - # @exception InternalError Ū顼ȯ - # @else - # - # @brief [SDO interface] Getting Organizations - # - # An SDO belongs to zero or more organizations. If the SDO belongs to one - # or more organizations, this operation returns the list of organizations - # that the SDO belongs to. An empty list is returned if the SDO does not - # belong to any Organizations. - # - # @return The list of Organizations that the SDO belong to. - # - # @exception SDONotExists if the target SDO does not exist.(This exception - # is mapped to CORBA standard system exception - # OBJECT_NOT_EXIST.) - # @exception NotAvailable The target SDO is reachable but cannot respond. - # @exception InternalError The target SDO cannot execute the operation - # completely due to some internal error. - # @endif - # virtual SDOPackage::OrganizationList* get_organizations() - def get_organizations(self): - self._rtcout.RTC_TRACE("get_organizations()") - self._sdoOrganizations = self._SdoConfigImpl.getOrganizations() - - return self._sdoOrganizations - - - - - ## - # @if jp - # - # @brief [SDO interface] SDO Status ꥹȤμ - # - # Υڥ졼 SDO Υơɽ NVList ֤ - # - # @param self - # - # @return SDO Υơ - # - # @exception SDONotExists åȤSDO¸ߤʤ(㳰ϡCORBAɸ - # ƥ㳰OBJECT_NOT_EXIST˥ޥåԥ󥰤) - # @exception NotAvailable SDO¸ߤ뤬ʤ - # @exception InternalError Ū顼ȯ - # - # @else - # - # @brief [SDO interface] Get SDO Status - # - # This operation returns an NVlist describing the status of an SDO. - # - # @return The actual status of an SDO. - # - # @exception SDONotExists if the target SDO does not exist.(This exception - # is mapped to CORBA standard system exception - # OBJECT_NOT_EXIST.) - # @exception NotAvailable The target SDO is reachable but cannot respond. - # @exception InternalError The target SDO cannot execute the operation - # completely due to some internal error. - # - # @endif - # virtual SDOPackage::NVList* get_status_list() - def get_status_list(self): - self._rtcout.RTC_TRACE("get_status_list()") - - return self._sdoStatus - - - - - ## - # @if jp - # - # @brief [SDO interface] SDO Status μ - # - # This operation returns the value of the specified status parameter. - # - # @param self - # @param name SDO Υơѥ᡼ - # - # @return ꤵ줿ѥ᡼Υơ͡ - # - # @exception SDONotExists åȤSDO¸ߤʤ(㳰ϡCORBAɸ - # ƥ㳰OBJECT_NOT_EXIST˥ޥåԥ󥰤) - # @exception NotAvailable SDO¸ߤ뤬ʤ - # @exception InvalidParameter "name" null 뤤¸ߤʤ - # @exception InternalError Ū顼ȯ - # @else - # - # @brief [SDO interface] Get SDO Status - # - # @param name One of the parameters defining the "status" of an SDO. - # - # @return The value of the specified status parameter. - # - # @exception SDONotExists if the target SDO does not exist.(This exception - # is mapped to CORBA standard system exception - # OBJECT_NOT_EXIST.) - # @exception NotAvailable The target SDO is reachable but cannot respond. - # @exception InvalidParameter The parameter defined by "name" is null or - # does not exist. - # @exception InternalError The target SDO cannot execute the operation - # completely due to some internal error. - # - # - # @endif - # virtual CORBA::Any* get_status(const char* name) - def get_status(self, name): - self._rtcout.RTC_TRACE("get_status(%s)", name) - index = OpenRTM_aist.CORBA_SeqUtil.find(self._sdoStatus, self.nv_name(name)) - if index < 0: - raise SDOPackage.InvalidParameter("get_status(): Not found") - - try: - return any.to_any(self._sdoStatus[index].value) - except: - self._rtcout.RTC_ERROR(OpenRTM_aist.Logger.print_exception()) - raise SDOPackage.InternalError("get_status()") - - - - #============================================================ - # Local interfaces - #============================================================ - - ## - # @if jp - # - # @brief [local interface] 󥹥̾μ - # - # ComponentProfile ꤵ줿󥹥֤̾ - # - # @param self - # - # @return 󥹥̾ - # - # @else - # - # @endif - # const char* getInstanceName() - def getInstanceName(self): - self._rtcout.RTC_TRACE("getInstanceName()") - return self._profile.instance_name - - - ## - # @if jp - # - # @brief [local interface] 󥹥̾ - # - # ComponentProfile ˻ꤵ줿󥹥̾ꤹ롣 - # - # @param self - # - # @param instance_name 󥹥̾ - # - # @else - # - # @endif - # void setInstanceName(const char* instance_name); - def setInstanceName(self, instance_name): - self._rtcout.RTC_TRACE("setInstanceName(%s)", instance_name) - self._properties.setProperty("instance_name",instance_name) - self._profile.instance_name = self._properties.getProperty("instance_name") - - - ## - # @if jp - # - # @brief [local interface] ̾μ - # - # ComponentProfile ꤵ줿֤̾ - # - # @param self - # - # @return ̾ - # - # @else - # - # @endif - # const char* getTypeName() - def getTypeName(self): - self._rtcout.RTC_TRACE("getTypeName()") - return self._profile.type_name - - - ## - # @if jp - # - # @brief [local interface] Description μ - # - # ComponentProfile ꤵ줿 Description ֤ - # - # @param self - # - # @return Description - # - # @else - # - # @endif - # const char* getDescription() - def getDescription(self): - self._rtcout.RTC_TRACE("getDescription()") - return self._profile.description - - - ## - # @if jp - # - # @brief [local interface] Сμ - # - # ComponentProfile ꤵ줿С֤ - # - # @param self - # - # @return С - # - # @else - # - # @endif - # const char* getVersion() - def getVersion(self): - self._rtcout.RTC_TRACE("getVersion()") - return self._profile.version - - - ## - # @if jp - # - # @brief [local interface] ٥μ - # - # ComponentProfile ꤵ줿٥֤ - # - # @param self - # - # @return ٥ - # - # @else - # - # @endif - # const char* getVendor() - def getVendor(self): - self._rtcout.RTC_TRACE("getVendor()") - return self._profile.vendor - - - ## - # @if jp - # - # @brief [local interface] ƥμ - # - # ComponentProfile ꤵ줿ƥ֤ - # - # @param self - # - # @return ƥ - # - # @else - # - # @endif - # const char* getCategory() - def getCategory(self): - self._rtcout.RTC_TRACE("getCategory()") - return self._profile.category - - - ## - # @if jp - # - # @brief [local interface] Naming Server μ - # - # ꤵ줿 Naming Server ֤ - # - # @param self - # - # @return Naming Server ꥹ - # - # @else - # - # @endif - # std::vector getNamingNames(); - def getNamingNames(self): - self._rtcout.RTC_TRACE("getNamingNames()") - return [s.strip() for s in self._properties.getProperty("naming.names").split(",")] - - - ## - # @if jp - # - # @brief [local interface] ֥ȥե󥹤 - # - # RTC CORBA ֥ȥե󥹤ꤹ롣 - # - # @param self - # @param rtobj ֥ȥե - # - # @else - # - # @endif - # void setObjRef(const RTObject_ptr rtobj); - def setObjRef(self, rtobj): - self._rtcout.RTC_TRACE("setObjRef()") - self._objref = rtobj - return - - - ## - # @if jp - # - # @brief [local interface] ֥ȥե󥹤μ - # - # ꤵ줿 CORBA ֥ȥե󥹤롣 - # - # @param self - # - # @return ֥ȥե - # - # @else - # - # @endif - # RTObject_ptr getObjRef() const; - def getObjRef(self): - self._rtcout.RTC_TRACE("getObjRef()") - return self._objref - - - ## - # @if jp - # - # @brief [local interface] RTC Υץѥƥꤹ - # - # RTC ݻ٤ץѥƥꤹ롣Ϳץѥƥϡ - # ComponentProfile ꤵ٤ʤФʤʤ - # Υڥ졼̾ RTC ݤ Manager - # ƤФ뤳ȤտޤƤ롣 - # - # @param self - # @param prop RTC Υץѥƥ - # - # @else - # - # @brief [local interface] Set RTC property - # - # This operation sets the properties to the RTC. The given property - # values should include information for ComponentProfile. - # Generally, this operation is designed to be called from Manager, when - # RTC is initialized - # - # @param prop Property for RTC. - # - # @endif - # void setProperties(const coil::Properties& prop); - def setProperties(self, prop): - self._rtcout.RTC_TRACE("setProperties()") - self._properties.mergeProperties(prop) - self._profile.instance_name = self._properties.getProperty("instance_name") - self._profile.type_name = self._properties.getProperty("type_name") - self._profile.description = self._properties.getProperty("description") - self._profile.version = self._properties.getProperty("version") - self._profile.vendor = self._properties.getProperty("vendor") - self._profile.category = self._properties.getProperty("category") - - - ## - # @if jp - # - # @brief [local interface] RTC Υץѥƥ - # - # RTC ݻƤץѥƥ֤ - # RTCץѥƥʤ϶Υץѥƥ֤롣 - # - # @param self - # - # @return RTC Υץѥƥ - # - # @else - # - # @brief [local interface] Get RTC property - # - # This operation returns the properties of the RTC. - # Empty property would be returned, if RTC has no property. - # - # @return Property for RTC. - # - # @endif - # coil::Properties& getProperties(); - def getProperties(self): - self._rtcout.RTC_TRACE("getProperties()") - return self._properties - - - ## - # @if jp - # - # @brief ե졼ѥ᡼ - # - # ե졼ѥ᡼ѿХɤ - # \Ȥƥե졼ѥ᡼Υǡꤹ롣 - # - # @param self - # @param param_name ե졼ѥ᡼̾ - # @param var ե졼ѥ᡼Ǽѿ - # @param def_val ե졼ѥ᡼ǥե - # @param trans ʸѴѴؿ(ǥե:None) - # - # @return (:true꼺:false) - # - # @else - # - # @endif - # template - # bool bindParameter(const char* param_name, VarType& var, - # const char* def_val, - # bool (*trans)(VarType&, const char*) = coil::stringTo) - def bindParameter(self, param_name, var, - def_val, trans=None): - self._rtcout.RTC_TRACE("bindParameter()") - if trans is None: - trans_ = OpenRTM_aist.stringTo - else: - trans_ = trans - self._configsets.bindParameter(param_name, var, def_val, trans_) - return True - - - ## - # @if jp - # - # @brief ե졼󥵡ӥ - # - # ե졼󥵡ӥ֥Ȥ롣Υ - # ֥ȤѤơե졼ѥ᡼ - # ԤȤǤ롣ȤƤϡ - # - # - unbindParameter(): ѥ᡼ΥХ - # - update(): ѥ᡼ι - # - update(set_name): ΥåȤι - # - update(set_name, param_name): ΥåȤΥѥ᡼ι - # - isExist(): ѥ᡼¸߳ǧ - # - isChanged(): ѥ᡼ѹ줿γǧ - # - changedParameters(): ѹ줿ѥ᡼Υꥹ - # - getActiveId(): ƥ֥å̾μ - # - haveConfig(config_id): եåȤäƤ뤫ɤ - # - getConfigurationSets(): ե졼󥻥åȤμ - # - getConfigurationSet(set_id): ꥻåȤ - # - # ХåϢ - # - addConfigurationParamListener(): ꥹʤɲ - # - removeConfigurationParamListener(): ꥹʤκ - # - addConfigurationSetListener(): ꥹʤɲ - # - removeConfigurationSetListener(): ꥹʤκ - # - addConfigurationSetNameListener(): ꥹʤɲ - # - removeConfigurationSetNameListener(): ꥹʤκ - # - # ܺ٤ConfigAdmin饹ե󥹤򻲾ȤΤȡ - # - # @return ConfigAdmin object - # - # @else - # - # @brief Getting configuration service - # - # This operation returns configuration service object. By using - # this service, user can manipulate configuration - # parameters. Mainly the following operations are supported. - # - # - unbindParameter(): Unbinding parameters - # - update(): Updateing parameters - # - update(set_name): Updating a specific configuration set - # - update(set_name, param_name): Updating specific parameter in a set - # - isExist(): Checking existence of a parameter - # - isChanged(): Check if a parameter was updated - # - changedParameters(): Getting changed parameter list - # - getActiveId(): Getting active configuration set name - # - haveConfig(config_id): Checking if having a specified configuration set - # - getConfigurationSets(): getting all the configuration sets - # - getConfigurationSet(set_id): Getting a configuration set - # - # Callback related member functions - # - addConfigurationParamListener(): Adding listener - # - removeConfigurationParamListener(): Removing listener - # - addConfigurationSetListener(): Adding listener - # - removeConfigurationSetListener(): Removing listener - # - addConfigurationSetNameListener(): Adding listener - # - removeConfigurationSetNameListener(): Removing listener - # - # See details in the ConfigAdmin class reference - # - # @return ConfigAdmin object - # - # @endif - # - # ConfigAdmin& getConfigService() { return m_configsets; } - def getConfigService(self): - return self._configsets - - ## - # @if jp - # - # @brief ե졼ѥ᡼ι(ID) - # - # ꤷIDΥե졼󥻥åȤꤷͤǡ - # ե졼ѥ᡼ͤ򹹿 - # - # @param self - # @param config_set оݤΥե졼󥻥åID - # - # @else - # - # @endif - # void updateParameters(const char* config_set); - def updateParameters(self, config_set): - self._rtcout.RTC_TRACE("updateParameters(%s)", config_set) - self._configsets.update(config_set) - return - - - ## - # @if jp - # - # @brief [local interface] Port Ͽ - # - # RTC ݻPortϿ롣 - # Port 饢ǽˤ뤿ˤϡΥڥ졼ˤ - # ϿƤʤФʤʤϿ Port Ϥ RTC ˤ - # PortProfile.name ˤ̤롣äơPort RTC ˤơ - # ˡ PortProfile.name ʤФʤʤ - # Ͽ줿 Port Ŭڤ˥ƥֲ줿塢λȤ - # ֥ȻȤꥹ¸롣 - # - # @param self - # @param port RTC Ͽ Port - # @param port_type if port is PortBase, port_type is None, - # if port is PortService, port_type is True - # - # @else - # - # @brief [local interface] Register Port - # - # This operation registers a Port to be held by this RTC. - # In order to enable access to the Port from outside of RTC, the Port - # must be registered by this operation. The Port that is registered by - # this operation would be identified by PortProfile.name in the inside of - # RTC. Therefore, the Port should have unique PortProfile.name in the RTC. - # The registering Port would be activated properly, and the reference - # and the object reference would be stored in lists in RTC. - # - # @param port Port which is registered in the RTC - # - # @endif - # void registerPort(PortBase& port); - def registerPort(self, port): - self._rtcout.RTC_TRACE("registerPort()") - if not self.addPort(port): - self._rtcout.RTC_ERROR("addPort(PortBase&) failed.") - return - - # void registerPort(PortService_ptr port); - # def registerPortByReference(self, port_ref): - # self._rtcout.RTC_TRACE("registerPortByReference()") - # self.addPortByReference(port_ref) - # return - - # new interface. since 1.0.0-RELEASE - # void addPort(PortBase& port); - def addPort(self, port): - self._rtcout.RTC_TRACE("addPort()") - if isinstance(port, OpenRTM_aist.CorbaPort): - self._rtcout.RTC_TRACE("addPort(CorbaPort)") - propkey = "port.corbaport." - prop = self._properties.getNode(propkey) - if prop: - self._properties.getNode(propkey).mergeProperties(self._properties.getNode("port.corba")) - port.init(self._properties.getNode(propkey)) - port.setOwner(self.getObjRef()) - - elif isinstance(port, OpenRTM_aist.PortBase): - self._rtcout.RTC_TRACE("addPort(PortBase)") - port.setOwner(self.getObjRef()) - port.setPortConnectListenerHolder(self._portconnListeners) - self.onAddPort(port.getPortProfile()) - - elif isinstance(port, RTC._objref_PortService): - self._rtcout.RTC_TRACE("addPort(PortService)") - return self._portAdmin.addPort(port) - - - # new interface. since 1.0.0-RELEASE - # void addPort(PortService_ptr port); - # def addPortByReference(self, port_ref): - # self._rtcout.RTC_TRACE("addPortByReference()") - # self._portAdmin.registerPortByReference(port_ref) - # return - - - ## - # @if jp - # - # @brief [local interface] DataInPort Ͽ - # - # RTC ݻ DataInPort Ͽ롣 - # Port Υץѥƥ˥ǡݡȤǤ뤳("port.dataport") - # TCPѤ뤳("tcp_any")ꤹȤȤˡ DataInPort - # 󥹥󥹤Ͽ롣 - # - # @param self - # @param name port ̾ - # @param inport Ͽо DataInPort - # - # @else - # - # @endif - def registerInPort(self, name, inport): - self._rtcout.RTC_TRACE("registerInPort(%s)", name) - if not self.addInPort(name, inport): - self._rtcout.RTC_ERROR("addInPort(%s) failed.", name) - return - - # new interface. since 1.0.0-RELEASE - def addInPort(self, name, inport): - self._rtcout.RTC_TRACE("addInPort(%s)", name) - - propkey = "port.inport." + name - prop_ = copy.copy(self._properties.getNode(propkey)) - prop_.mergeProperties(self._properties.getNode("port.inport.dataport")) - - ret = self.addPort(inport) - - if not ret: - self._rtcout.RTC_ERROR("addInPort() failed.") - return ret - - inport.init(prop_) - self._inports.append(inport) - return ret + ## + # @if jp + # @brief ExecutionContextActionListener リスナを追加する + # + # ExecutionContextの追加、削除時にコールバックされる各種リスナを設定する。 + # + # 設定できるリスナのタイプとコールバックイベントは以下の通り + # + # - ATTACH_EC: ExecutionContext アタッチ時 + # - DETACH_EC: ExecutionContext デタッチ時 + # + # リスナは ExecutionContextActionListener を継承し、以下のシグニチャを持つ + # operator() を実装している必要がある。 + # + # ExecutionContextActionListener::operator()(UniqueId ec_id) + # + # デフォルトでは、この関数に与えたリスナオブジェクトの所有権は + # RTObjectに移り、RTObject解体時もしくは、 + # removeExecutionContextActionListener() により削除時に自動的に解体される。 + # リスナオブジェクトの所有権を呼び出し側で維持したい場合は、第3引 + # 数に false を指定し、自動的な解体を抑制することができる。 + # + # @param listener_type リスナタイプ + # @param memfunc 関数オブジェクト + # + # @else + # @brief Adding ExecutionContextAction type listener + # + # This operation adds certain listeners related to ComponentActions + # post events. + # The following listener types are available. + # + # - ADD_PORT: At adding ExecutionContext + # - REMOVE_PORT: At removing ExecutionContext + # + # Listeners should have the following function operator(). + # + # ExecutionContextActionListener::operator()(UniqueId ec_id) + # + # The ownership of the given listener object is transferred to + # this RTObject object in default. The given listener object will + # be destroied automatically in the RTObject's dtor or if the + # listener is deleted by removeExecutionContextActionListener() function. + # If you want to keep ownership of the listener object, give + # "false" value to 3rd argument to inhibit automatic destruction. + # + # @param listener_type A listener type + # @param memfunc member function object + # + # @endif + # + # template + # ECActionListener* + # addExecutionContextActionListener(ECActionListenerType listener_type, + # void (Listener::*memfunc)(UniqueId)); + + def addExecutionContextActionListener(self, listener_type, + memfunc): + class Noname(OpenRTM_aist.ExecutionContextActionListener): + def __init__(self, memfunc): + self._memfunc = memfunc + return + + def __call__(self, ec_id): + self._memfunc(ec_id) + return + + listener = Noname(memfunc) + self._actionListeners.addECActionListener(listener_type, listener) + return listener + + ## + # @if jp + # @brief ExecutionContextActionListener リスナを削除する + # + # 設定した各種リスナを削除する。 + # + # @param listener_type リスナタイプ + # @param listener リスナオブジェクトへのポインタ + # + # @else + # @brief Removing ExecutionContextAction type listener + # + # This operation removes a specified listener. + # + # @param listener_type A listener type + # @param listener A pointer to a listener object + # + # @endif + # + # void + # removeExecutionContextActionListener(ECActionListenerType listener_type, + # ECActionListener* listener); + + def removeExecutionContextActionListener(self, listener_type, listener): + self._actionListeners.removeECActionListener(listener_type, listener) + return + ## + # @if jp + # @brief PortConnectListener リスナを追加する + # + # Portの接続時や接続解除時に呼び出される各種リスナを設定する。 + # + # 設定できるリスナのタイプとコールバックイベントは以下の通り + # + # - ON_NOTIFY_CONNECT: notify_connect() 関数内呼び出し直後 + # - ON_NOTIFY_DISCONNECT: notify_disconnect() 呼び出し直後 + # - ON_UNSUBSCRIBE_INTERFACES: notify_disconnect() 内のIF購読解除時 + # + # リスナは PortConnectListener を継承し、以下のシグニチャを持つ + # operator() を実装している必要がある。 + # + # PortConnectListener::operator()(const char*, ConnectorProfile) + # + # デフォルトでは、この関数に与えたリスナオブジェクトの所有権は + # RTObjectに移り、RTObject解体時もしくは、 + # removePortConnectListener() により削除時に自動的に解体される。 + # リスナオブジェクトの所有権を呼び出し側で維持したい場合は、第3引 + # 数に false を指定し、自動的な解体を抑制することができる。 + # + # @param listener_type リスナタイプ + # @param memfunc 関数オブジェクト + # + # @else + # @brief Adding PortConnect type listener + # + # This operation adds certain listeners related to Port's connect actions. + # The following listener types are available. + # + # - ON_NOTIFY_CONNECT: right after entering into notify_connect() + # - ON_NOTIFY_DISCONNECT: right after entering into notify_disconnect() + # - ON_UNSUBSCRIBE_INTERFACES: unsubscribing IF in notify_disconnect() + # + # Listeners should have the following function operator(). + # + # PortConnectListener::operator()(const char*, ConnectorProfile) + # + # The ownership of the given listener object is transferred to + # this RTObject object in default. The given listener object will + # be destroied automatically in the RTObject's dtor or if the + # listener is deleted by removePortConnectListener() function. + # If you want to keep ownership of the listener object, give + # "false" value to 3rd argument to inhibit automatic destruction. + # + # @param listener_type A listener type + # @param memfunc member function object + # + # @endif + # + # template + # PortConnectListener* + # addPortConnectListener(PortConnectListenerType listener_type, + # void (Listener::*memfunc)(const char*, + # ConnectorProfile&)) + + def addPortConnectListener(self, listener_type, + memfunc): + class Noname(OpenRTM_aist.PortConnectListener): + def __init__(self, memfunc): + self._memfunc = memfunc + return + + def __call__(self, portname, cprofile): + self._memfunc(portname, cprofile) + return + + listener = Noname(memfunc) + self._portconnListeners.addListener(listener_type, listener) + return listener + + ## + # @if jp + # @brief PortConnectListener リスナを削除する + # + # 設定した各種リスナを削除する。 + # + # @param listener_type リスナタイプ + # @param listener リスナオブジェクトへのポインタ + # + # @else + # @brief Removing PortConnect type listener + # + # This operation removes a specified listener. + # + # @param listener_type A listener type + # @param listener A pointer to a listener object + # + # @endif + # + # void + # removePortConnectListener(PortConnectListenerType listener_type, + # PortConnectListener* listener); + + def removePortConnectListener(self, listener_type, listener): + self._portconnListeners.removeListener(listener_type, listener) + return - ## - # @if jp - # - # @brief [local interface] DataOutPort Ͽ - # - # RTC ݻ DataOutPor tϿ롣 - # Port Υץѥƥ˥ǡݡȤǤ뤳("port.dataport") - # TCPѤ뤳("tcp_any")ꤹȤȤˡ DataOutPort - # 󥹥󥹤Ͽ롣 - # - # @param self - # @param name port ̾ - # @param outport Ͽо DataInPort - # - # @else - # - # @endif - # void registerOutPort(const char* name, OutPortBase& outport); - def registerOutPort(self, name, outport): - self._rtcout.RTC_TRACE("registerOutPort(%s)", name) - if not self.addOutPort(name, outport): - self._rtcout.RTC_ERROR("addOutPort(%s) failed.", name) - return - - # new interface. since 1.0.0-RELEASE - # void addOutPort(const char* name, OutPortBase& outport); - def addOutPort(self, name, outport): - self._rtcout.RTC_TRACE("addOutPort(%s)", name) - - propkey = "port.outport." + name - prop_ = copy.copy(self._properties.getNode(propkey)) - prop_.mergeProperties(self._properties.getNode("port.outport.dataport")) - - ret = self.addPort(outport) - - if not ret: - self._rtcout.RTC_ERROR("addOutPort() failed.") - return ret + ## + # @if jp + # @brief PortConnectRetListener リスナを追加する + # + # Portの接続時や接続解除時に呼び出される各種リスナを設定する。 + # + # 設定できるリスナのタイプとコールバックイベントは以下の通り + # + # - ON_CONNECT_NEXTPORT: notify_connect() 中のカスケード呼び出し直後 + # - ON_SUBSCRIBE_INTERFACES: notify_connect() 中のインターフェース購読直後 + # - ON_CONNECTED: nofity_connect() 接続処理完了時に呼び出される + # - ON_DISCONNECT_NEXT: notify_disconnect() 中にカスケード呼び出し直後 + # - ON_DISCONNECTED: notify_disconnect() リターン時 + # + # リスナは PortConnectRetListener を継承し、以下のシグニチャを持つ + # operator() を実装している必要がある。 + # + # PortConnectRetListener::operator()(const char*, ConnectorProfile) + # + # デフォルトでは、この関数に与えたリスナオブジェクトの所有権は + # RTObjectに移り、RTObject解体時もしくは、 + # removePortConnectRetListener() により削除時に自動的に解体される。 + # リスナオブジェクトの所有権を呼び出し側で維持したい場合は、第3引 + # 数に false を指定し、自動的な解体を抑制することができる。 + # + # @param listener_type リスナタイプ + # @param memfunc 関数オブジェクト + # + # @else + # @brief Adding PortConnectRet type listener + # + # This operation adds certain listeners related to Port's connect actions. + # The following listener types are available. + # + # - ON_CONNECT_NEXTPORT: after cascade-call in notify_connect() + # - ON_SUBSCRIBE_INTERFACES: after IF subscribing in notify_connect() + # - ON_CONNECTED: completed nofity_connect() connection process + # - ON_DISCONNECT_NEXT: after cascade-call in notify_disconnect() + # - ON_DISCONNECTED: completed notify_disconnect() disconnection process + # + # Listeners should have the following function operator(). + # + # PortConnectRetListener::operator()(const char*, ConnectorProfile) + # + # The ownership of the given listener object is transferred to + # this RTObject object in default. The given listener object will + # be destroied automatically in the RTObject's dtor or if the + # listener is deleted by removePortConnectRetListener() function. + # If you want to keep ownership of the listener object, give + # "false" value to 3rd argument to inhibit automatic destruction. + # + # @param listener_type A listener type + # @param memfunc member function object + # + # @endif + # + # template + # PortConnectRetListener* + # addPortConnectRetListener(PortConnectRetListenerType listener_type, + # void (Listener::*memfunc)(const char*, + # ConnectorProfile&, + # ReturnCode_t)) + + def addPortConnectRetListener(self, listener_type, + memfunc): + class Noname(OpenRTM_aist.PortConnectRetListener): + def __init__(self, memfunc): + self._memfunc = memfunc + return + + def __call__(self, portname, cprofile, ret): + self._memfunc(portname, cprofile, ret) + return + + listener = Noname(memfunc) + self._portconnListeners.addRetListener(listener_type, listener) + return listener + + ## + # @if jp + # @brief PortConnectRetListener リスナを削除する + # + # 設定した各種リスナを削除する。 + # + # @param listener_type リスナタイプ + # @param listener リスナオブジェクトへのポインタ + # + # @else + # @brief Removing PortConnectRet type listener + # + # This operation removes a specified listener. + # + # @param listener_type A listener type + # @param listener A pointer to a listener object + # + # @endif + # + # void + # removePortConnectRetListener(PortConnectRetListenerType listener_type, + # PortConnectRetListener* listener); + + def removePortConnectRetListener(self, listener_type, listener): + self._portconnListeners.removeRetListener(listener_type, listener) + return - outport.init(prop_) - self._outports.append(outport) - return ret + ## + # @if jp + # + # @brief ConfigurationParamListener を追加する + # + # update(const char* config_set, const char* config_param) が呼ばれた際に + # コールされるリスナ ConfigurationParamListener を追加する。 + # type には現在のところ ON_UPDATE_CONFIG_PARAM のみが入る。 + # + # @param type ConfigurationParamListenerType型の値。 + # ON_UPDATE_CONFIG_PARAM がある。 + # + # @param memfunc 関数オブジェクト + # + # @else + # + # @brief Adding ConfigurationParamListener + # + # This function adds a listener object which is called when + # update(const char* config_set, const char* config_param) is + # called. In the type argument, currently only + # ON_UPDATE_CONFIG_PARAM is allowed. + # + # @param type ConfigurationParamListenerType value + # ON_UPDATE_CONFIG_PARAM is only allowed. + # + # @param memfunc member function object + # + # @endif + # + # template + # ConfigurationParamListener* + # addConfigurationParamListener(ConfigurationParamListenerType listener_type, + # void (Listener::*memfunc)(const char*, + # const char*)) + + def addConfigurationParamListener(self, type, + memfunc): + class Noname(OpenRTM_aist.ConfigurationParamListener): + def __init__(self, memfunc): + self._memfunc = memfunc + return + + def __call__(self, config_set_name, config_param_name): + self._memfunc(config_set_name, config_param_name) + return + + listener = Noname(memfunc) + self._configsets.addConfigurationParamListener(type, listener) + return listener + + ## + # @if jp + # + # @brief ConfigurationParamListener を削除する + # + # addConfigurationParamListener で追加されたリスナオブジェクトを削除する。 + # + # @param type ConfigurationParamListenerType型の値。 + # ON_UPDATE_CONFIG_PARAM がある。 + # @param listener 与えたリスナオブジェクトへのポインタ + # + # @else + # + # @brief Removing ConfigurationParamListener + # + # This function removes a listener object which is added by + # addConfigurationParamListener() function. + # + # @param type ConfigurationParamListenerType value + # ON_UPDATE_CONFIG_PARAM is only allowed. + # @param listener a pointer to ConfigurationParamListener listener object. + # + # @endif + # + # void removeConfigurationParamListener(ConfigurationParamListenerType type, + # ConfigurationParamListener* listener); + + def removeConfigurationParamListener(self, type, listener): + self._configsets.removeConfigurationParamListener(type, listener) + return + ## + # @if jp + # + # @brief ConfigurationSetListener を追加する + # + # ConfigurationSet が更新されたときなどに呼ばれるリスナ + # ConfigurationSetListener を追加する。設定可能なイベントは以下の + # 2種類がある。 + # + # - ON_SET_CONFIG_SET: setConfigurationSetValues() で + # ConfigurationSet に値が設定された場合。 + # - ON_ADD_CONFIG_SET: addConfigurationSet() で新しい + # ConfigurationSet が追加された場合。 + # + # @param type ConfigurationSetListenerType型の値。 + # @param memfunc 関数オブジェクト + # + # @else + # + # @brief Adding ConfigurationSetListener + # + # This function add a listener object which is called when + # ConfigurationSet is updated. Available events are the followings. + # + # @param type ConfigurationSetListenerType value + # @param memfunc member function object + # + # @endif + # + # template + # ConfigurationSetListener* + # addConfigurationSetListener(ConfigurationSetListenerType listener_type, + # void (Listener::*memfunc) + # (const coil::Properties& config_set)) + + def addConfigurationSetListener(self, listener_type, + memfunc): + class Noname(OpenRTM_aist.ConfigurationSetListener): + def __init__(self, memfunc): + self._memfunc = memfunc + return + + def __call__(self, config_set): + self._memfunc(config_set) + return + + listener = Noname(memfunc) + self._configsets.addConfigurationSetListener(listener_type, listener) + return listener + + ## + # @if jp + # + # @brief ConfigurationSetListener を削除する + # + # addConfigurationSetListener で追加されたリスナオブジェクトを削除する。 + # + # @param type ConfigurationSetListenerType型の値。 + # @param listener 与えたリスナオブジェクトへのポインタ + # + # @else + # + # @brief Removing ConfigurationSetListener + # + # This function removes a listener object which is added by + # addConfigurationSetListener() function. + # + # @param type ConfigurationSetListenerType value + # @param listener a pointer to ConfigurationSetListener listener object. + # + # @endif + # + # void removeConfigurationSetListener(ConfigurationSetListenerType type, + # ConfigurationSetListener* listener); + + def removeConfigurationSetListener(self, type, listener): + self._configsets.removeConfigurationSetListener(type, listener) + return - ## - # @if jp - # - # @brief [local interface] InPort Ͽ - # - # RTC ݻInPortϿ롣 - # - # @param port о Port - # @return (:true:false) - # - # @else - # - # @brief [local interface] Unregister InPort - # - # This operation unregisters a InPort held by this RTC. - # - # @param port Port which is unregistered - # @return Unregister result (Successful:true, Failed:false) - # - # @endif - # - # bool removeInPort(InPortBase& port); - def removeInPort(self, port): - self._rtcout.RTC_TRACE("removeInPort()") - ret = self.removePort(port) - - if ret: - for inport in self._inports: - if port == inport: - - self._inports.remove(port) - - return True - - return False - - - ## - # @if jp - # - # @brief [local interface] OutPort Ͽ - # - # RTC ݻOutPortϿ롣 - # - # @param port о Port - # @return (:true:false) - # - # @else - # - # @brief [local interface] Unregister OutPort - # - # This operation unregisters a OutPort held by this RTC. - # - # @param port Port which is unregistered - # @return Unregister result (Successful:true, Failed:false) - # - # @endif - # - # bool removeOutPort(OutPortBase& port); - def removeOutPort(self, port): - self._rtcout.RTC_TRACE("removeOutPort()") - ret = self.removePort(port) - - if ret: - for outport in self._outports: - if port == outport: - - self._outports.remove(port) - - return True - - return False - - - ## - # @if jp - # - # @brief [local interface] Port Ͽ - # - # RTC ݻPortϿ롣 - # - # @param self - # @param port о Port - # - # @else - # - # @brief [local interface] Unregister Port - # - # This operation unregisters a Port to be held by this RTC. - # - # @param port Port which is unregistered in the RTC - # - # @endif - # void RTObject_impl::deletePort(PortBase& port) - def deletePort(self, port): - self._rtcout.RTC_TRACE("deletePort()") - if not self.removePort(port): - self._rtcout.RTC_ERROR("removePort() failed.") - return - - # new interface. since 1.0.0-RELEASE - def removePort(self, port): - self._rtcout.RTC_TRACE("removePort()") - if isinstance(port, OpenRTM_aist.PortBase) or isinstance(port, OpenRTM_aist.CorbaPort): - self.onRemovePort(port.getPortProfile()) - return self._portAdmin.removePort(port) - - - ## - # @if jp - # - # @brief [local interface] ̾ˤ Port Ͽ - # - # ̾Τꤷ RTC ݻPortϿ롣 - # - # @param self - # @param port_name о Port ̾ - # - # @else - # - # @endif - def deletePortByName(self, port_name): - self._rtcout.RTC_TRACE("deletePortByName(%s)", port_name) - self._portAdmin.deletePortByName(port_name) - return - - - ## - # @if jp - # - # @brief [local interface] ¹ԥƥȤ - # - # get_context() ƱǽΥǡ㤤Ϥʤ - # δؿϰʲδؿǸƤФ뤳ȤȤƤ롣 - # - # - onStartup() - # - onShutdown() - # - onActivated() - # - onDeactivated() - # - onExecute() - # - onAborting() - # - onError() - # - onReset() - # - onStateUpdate() - # - onRateChanged() - # - # δؿΰϤδؿΰ UniquieID exec_handle Ǥʤ - # Фʤʤ - # - # @param ec_id 嵭ؿ1 exec_handle Ϥɬפ롣 - # - # @else - # - # @brief [local interface] Getting current execution context - # - # This function is the local version of get_context(). completely - # same as get_context() function. This function is assumed to be - # called from the following functions. - # - # - onStartup() - # - onShutdown() - # - onActivated() - # - onDeactivated() - # - onExecute() - # - onAborting() - # - onError() - # - onReset() - # - onStateUpdate() - # - onRateChanged() - # - # The argument of this function should be the first argument - # (UniqueId ec_id) of the above functions. - # - # @param ec_id The above functions' first argument "exec_handle." - # - # @endif - # - # ExecutionContext_ptr getExecutionContext(RTC::UniqueId ec_id); - def getExecutionContext(self, ec_id): - return self.get_context(ec_id) - - ## - # @if jp - # - # @brief [local interface] ¹ԥƥȤμ¹ԥ졼Ȥ - # - # ߼¹μ¹ԥƥȤμ¹ԥ졼Ȥ롣¹ԥƥ - # ȤKindPERIODICʳξư̤Ǥ롣δؿϰ - # δؿǸƤФ뤳ȤȤƤ롣 - # - # - onStartup() - # - onShutdown() - # - onActivated() - # - onDeactivated() - # - onExecute() - # - onAborting() - # - onError() - # - onReset() - # - onStateUpdate() - # - onRateChanged() - # - # δؿΰϤδؿΰ UniquieID exec_handle Ǥʤ - # Фʤʤ - # - # @param ec_id 嵭ؿ1 exec_handle Ϥɬפ롣 - # - # @else - # - # @brief [local interface] Getting current context' execution rate - # - # This function returns current execution rate in this - # context. If this context's kind is not PERIODC, behavior is not - # defined. This function is assumed to be called from the - # following functions. - # - # - onStartup() - # - onShutdown() - # - onActivated() - # - onDeactivated() - # - onExecute() - # - onAborting() - # - onError() - # - onReset() - # - onStateUpdate() - # - onRateChanged() - # - # The argument of this function should be the first argument - # (UniqueId ec_id) of the above functions. - # - # @param ec_id The above functions' first argument "exec_handle." - # - # @endif - # - # double getExecutionRate(RTC::UniqueId ec_id); - def getExecutionRate(self, ec_id): - ec = self.getExecutionContext(ec_id) - if CORBA.is_nil(ec): - return 0.0 - - return ec.get_rate() - - - ## - # @if jp - # - # @brief [local interface] ¹ԥƥȤμ¹ԥ졼Ȥꤹ - # - # ߼¹μ¹ԥƥȤμ¹ԥ졼Ȥꤹ롣¹ԥƥ - # ȤKindPERIODICʳξư̤Ǥ롣δؿϰ - # δؿǸƤФ뤳ȤȤƤ롣 - # - # - onStartup() - # - onShutdown() - # - onActivated() - # - onDeactivated() - # - onExecute() - # - onAborting() - # - onError() - # - onReset() - # - onStateUpdate() - # - onRateChanged() - # - # δؿΰϤδؿΰ UniquieID exec_handle Ǥʤ - # Фʤʤ - # - # @param ec_id 嵭ؿ1 exec_handle Ϥɬפ롣 - # @param rate ¹ԥ졼Ȥ [Hz] Ϳ - # - # @else - # - # @brief [local interface] Setting current context' execution rate - # - # This function sets a execution rate in the context. If this - # context's kind is not PERIODC, behavior is not defined. This - # function is assumed to be called from the following functions. - # - # - onStartup() - # - onShutdown() - # - onActivated() - # - onDeactivated() - # - onExecute() - # - onAborting() - # - onError() - # - onReset() - # - onStateUpdate() - # - onRateChanged() - # - # The argument of this function should be the first argument - # (UniqueId ec_id) of the above functions. - # - # @param ec_id The above functions' first argument "exec_handle." - # @param rate Execution rate in [Hz]. - # - # @endif - # - # ReturnCode_t setExecutionRate(RTC::UniqueId ec_id, double rate); - def setExecutionRate(self, ec_id, rate): - ec = self.getExecutionContext(ec_id) - if CORBA.is_nil(ec): - return RTC.RTC_ERROR - ec.set_rate(rate) - return RTC.RTC_OK - - - ## - # @if jp - # - # @brief [local interface] ¹ԥƥȤνͭĴ٤ - # - # ߼¹μ¹ԥƥȤνͭĴ٤롣δؿϰʲδ - # ǸƤФ뤳ȤȤƤ롣 - # - # - onStartup() - # - onShutdown() - # - onActivated() - # - onDeactivated() - # - onExecute() - # - onAborting() - # - onError() - # - onReset() - # - onStateUpdate() - # - onRateChanged() - # - # δؿΰϤδؿΰ UniquieID exec_handle Ǥʤ - # Фʤʤ - # - # @param ec_id 嵭ؿ1 exec_handle Ϥɬפ롣 - # @return true: Ȥμ¹ԥƥȡfalse: ¾μ¹ԥƥ - # - # @else - # - # @brief [local interface] Checking if the current context is own context - # - # This function checks if the current context is own execution - # context. This function is assumed to be called from the - # following functions. - # - # - onStartup() - # - onShutdown() - # - onActivated() - # - onDeactivated() - # - onExecute() - # - onAborting() - # - onError() - # - onReset() - # - onStateUpdate() - # - onRateChanged() - # - # The argument of this function should be the first argument - # (UniqueId ec_id) of the above functions. - # - # @param ec_id The above functions' first argument "exec_handle." - # @return true: Own context, false: other's context - # - # @endif - # - # bool isOwnExecutionContext(RTC::UniqueId ec_id); - def isOwnExecutionContext(self, ec_id): - global ECOTHER_OFFSET - if ec_id < ECOTHER_OFFSET: - return True - return False - - - ## - # @if jp - # - # @brief [local interface] ֤ Inactive ܤ - # - # ֤ Active Inactive ܤ롣δؿϰʲδ - # ǸƤФ뤳ȤȤƤ롣 - # - # - onActivated() - # - onExecute() - # - onStateUpdate() - # - # δؿΰϾ嵭δؿΰ UniquieID exec_handle Ǥʤ - # Фʤʤ - # - # @param ec_id 嵭ؿ1 exec_handle Ϥɬפ롣 - # @return ꥿󥳡 - # - # @else - # - # @brief [local interface] Make transition to Inactive state - # - # This function makes transition from Active to Inactive - # state. This function is assumed to be called from the following - # functions. - # - # - onActivated() - # - onExecute() - # - onStateUpdate() - # - # The argument of this function should be the first argument - # (UniqueId ec_id) of the above function. - # - # @param ec_id The above functions' first argument "exec_handle." - # @return Return code - # - # @endif - # - # ReturnCode_t deactivate(RTC::UniqueId ec_id); - def deactivate(self, ec_id): - ec = self.getExecutionContext(ec_id) - if CORBA.is_nil(ec): - return RTC.RTC_ERROR - return ec.deactivate_component(self.getObjRef()) - - - ## - # @if jp - # - # @brief [local interface] ֤ Active ܤ - # - # ֤ Inactive Active ܤ롣δؿϰʲδ - # ǸƤФ뤳ȤȤƤ롣 - # - # - onStartup() - # - onDeactivated() - # - # δؿΰϾ嵭δؿΰ UniquieID exec_handle Ǥʤ - # Фʤʤ - # - # @param ec_id 嵭ؿ1 exec_handle Ϥɬפ롣 - # @return ꥿󥳡 - # - # @else - # - # @brief [local interface] Make transition to Active state - # - # This function makes transition from Inactive to Active - # state. This function is assumed to be called from the following - # functions. - # - # - onStartup() - # - onDeactivated() - # - # The argument of this function should be the first argument - # (UniqueId ec_id) of the above function. - # - # @param ec_id The above functions' first argument "exec_handle." - # @return Return code - # - # @endif - # - # ReturnCode_t activate(RTC::UniqueId ec_id); - def activate(self, ec_id): - ec = self.getExecutionContext(ec_id) - if CORBA.is_nil(ec): - return RTC.RTC_ERROR - return ec.activate_component(self.getObjRef()) - - - ## - # @if jp - # - # @brief [local interface] ֤ꥻåȤ Inactive ܤ - # - # ֤ Error Inactive ܤ롣δؿϰʲδ - # ǸƤФ뤳ȤȤƤ롣 - # - # - onError() - # - # δؿΰϾ嵭δؿΰ UniquieID exec_handle Ǥʤ - # Фʤʤ - # - # @param ec_id 嵭ؿ1 exec_handle Ϥɬפ롣 - # @return ꥿󥳡 - # - # @else - # - # @brief [local interface] Resetting and go to Inactive state - # - # This function reset RTC and makes transition from Error to Inactive - # state. This function is assumed to be called from the following - # functions. - # - # - onError() - # - # The argument of this function should be the first argument - # (UniqueId ec_id) of the above function. - # - # @param ec_id The above functions' first argument "exec_handle." - # @return Return code - # - # @endif - # - # ReturnCode_t reset(RTC::UniqueId ec_id); - def reset(self, ec_id): - ec = self.getExecutionContext(ec_id) - if CORBA.is_nil(ec): - return RTC.RTC_ERROR - return ec.reset_component(self.getObjRef()) - - - ## - # @if jp - # @brief [local interface] SDO service provider 򥻥åȤ - # @else - # @brief [local interface] Set a SDO service provider - # @endif - # - # bool addSdoServiceProvider(const SDOPackage::ServiceProfile& prof, - # SdoServiceProviderBase* provider); - def addSdoServiceProvider(self, prof, provider): - return self._sdoservice.addSdoServiceProvider(prof, provider) - - - ## - # @if jp - # @brief [local interface] SDO service provider - # @else - # @brief [local interface] Remove a SDO service provider - # @endif - # - # bool removeSdoServiceProvider(const char* id); - def removeSdoServiceProvider(self, id): - return self._sdoservice.removeSdoServiceProvider(id) - - - ## - # @if jp - # @brief [local interface] SDO service consumer 򥻥åȤ - # @else - # @brief [local interface] Set a SDO service consumer - # @endif - # - # bool addSdoServiceConsumer(const SDOPackage::ServiceProfile& prof); - def addSdoServiceConsumer(self, prof): - return self._sdoservice.addSdoServiceConsumer(prof) - - - ## - # @if jp - # @brief [local interface] SDO service consumer - # @else - # @brief [local interface] Remove a SDO service consumer - # @endif - # - # bool removeSdoServiceConsumer(const char* id); - def removeSdoServiceConsumer(self, id): - return self._sdoservice.removeSdoServiceConsumer(id) - - - ## - # @if jp - # @brief [local interface] SDO service consumer ̥åɤǺ - # @else - # @brief [local interface] Remove a SDO service consumer - # @endif - # - # bool removeSdoServiceConsumer(const char* id); - def removeSdoServiceConsumerStartThread(self, id): - class remove_Task(OpenRTM_aist.Task): - def __init__(self, sdoservice, id): - OpenRTM_aist.Task.__init__(self) - self._sdoservice = sdoservice - self._id = id - def svc(self): - self._sdoservice.removeSdoServiceConsumer(self._id) - - self._sdoservice.removeSdoServiceConsumer(id) - self.remove_thread = remove_Task(self._sdoservice, id) - self.remove_thread.activate() - - ## - # @if jp - # - # @brief InPort Υǡɤ߹ࡣ - # - # RTC ݻƤ InPort Υǡɤ߹ࡣ - # - # @return ɤ߹߷(ݡȤɤ߹:true:false) - # - # @else - # - # @brief Readout the value from All InPorts. - # - # This operation read the value from all InPort - # registered in the RTC. - # - # @return result (Successful:true, Failed:false) - # - # @endif - # - # bool readAll(); - def readAll(self): - self._rtcout.RTC_TRACE("readAll()") - ret = True - for inport in self._inports: - if not inport.read(): - self._rtcout.RTC_DEBUG("The error occurred in readAll().") - ret = False - if not self._readAllCompletion: - return False + ## + # @if jp + # + # @brief ConfigurationSetNameListener を追加する + # + # ConfigurationSetName が更新されたときなどに呼ばれるリスナ + # ConfigurationSetNameListener を追加する。設定可能なイベントは以下の + # 3種類がある。 + # + # - ON_UPDATE_CONFIG_SET: ある ConfigurationSet がアップデートされた + # - ON_REMOVE_CONFIG_SET: ある ConfigurationSet が削除された + # - ON_ACTIVATE_CONFIG_SET: ある ConfigurationSet がアクティブ化された + # + # @param type ConfigurationSetNameListenerType型の値。 + # @param memfunc 関数オブジェクト + # + # @else + # + # @brief Adding ConfigurationSetNameListener + # + # This function add a listener object which is called when + # ConfigurationSetName is updated. Available events are the followings. + # + # - ON_UPDATE_CONFIG_SET: A ConfigurationSet has been updated. + # - ON_REMOVE_CONFIG_SET: A ConfigurationSet has been deleted. + # - ON_ACTIVATE_CONFIG_SET: A ConfigurationSet has been activated. + # + # @param type ConfigurationSetNameListenerType value + # @param memfunc member function object + # + # @endif + # + # template + # ConfigurationSetNameListener* + # addConfigurationSetNameListener(ConfigurationSetNameListenerType type, + # void (Listener::*memfunc)(const char*)) + + def addConfigurationSetNameListener(self, type, memfunc): + class Noname(OpenRTM_aist.ConfigurationSetNameListener): + def __init__(self, memfunc): + self._memfunc = memfunc + return + + def __call__(self, config_set_name): + self._memfunc(config_set_name) + return + + listener = Noname(memfunc) + self._configsets.addConfigurationSetNameListener(type, listener) + return listener + + ## + # @if jp + # + # @brief ConfigurationSetNameListener を削除する + # + # addConfigurationSetNameListener で追加されたリスナオブジェクトを + # 削除する。 + # + # @param type ConfigurationSetNameListenerType型の値。 + # ON_UPDATE_CONFIG_PARAM がある。 + # @param listener 与えたリスナオブジェクトへのポインタ + # + # @else + # + # @brief Removing ConfigurationSetNameListener + # + # This function removes a listener object which is added by + # addConfigurationSetNameListener() function. + # + # @param type ConfigurationSetNameListenerType value + # ON_UPDATE_CONFIG_PARAM is only allowed. + # @param listener a pointer to ConfigurationSetNameListener + # listener object. + # + # @endif + # void + # removeConfigurationSetNameListener(ConfigurationSetNameListenerType type, + # ConfigurationSetNameListener* listener); + + def removeConfigurationSetNameListener(self, type, listener): + self._configsets.removeConfigurationSetNameListener(type, listener) + return - return ret + ## + # @if jp + # + # @brief ConfigurationSetNameListener を削除する + # + # addConfigurationSetNameListener で追加されたリスナオブジェクトを + # 削除する。 + # + # @param type ConfigurationSetNameListenerType型の値。 + # ON_UPDATE_CONFIG_PARAM がある。 + # @param listener 与えたリスナオブジェクトへのポインタ + # + # @else + # + # @brief Removing ConfigurationSetNameListener + # + # This function removes a listener object which is added by + # addConfigurationSetNameListener() function. + # + # @param type ConfigurationSetNameListenerType value + # ON_UPDATE_CONFIG_PARAM is only allowed. + # @param listener a pointer to ConfigurationSetNameListener + # listener object. + # + # @endif + # void + # removeConfigurationSetNameListener(ConfigurationSetNameListenerType type, + # ConfigurationSetNameListener* listener); + def removeConfigurationSetNameListener(self, type, listener): + self._configsets.removeConfigurationSetNameListener(type, listener) + return + + ## + # @if jp + # @brief PreFsmActionListener リスナを追加する + # + # FsmAction 実装関数の呼び出し直前のイベントに関連する各種リ + # スナを設定する。 + # + # 設定できるリスナのタイプとコールバックイベントは以下の通り + # + # - PRE_ON_INITIALIZE: onInitialize 直前 + # - PRE_ON_FINALIZE: onFinalize 直前 + # - PRE_ON_STARTUP: onStartup 直前 + # - PRE_ON_SHUTDOWN: onShutdown 直前 + # - PRE_ON_ACTIVATED: onActivated 直前 + # - PRE_ON_DEACTIVATED: onDeactivated 直前 + # - PRE_ON_ABORTED: onAborted 直前 + # - PRE_ON_ERROR: onError 直前 + # - PRE_ON_RESET: onReset 直前 + # - PRE_ON_EXECUTE: onExecute 直前 + # - PRE_ON_STATE_UPDATE: onStateUpdate 直前 + # + # リスナは PreFsmActionListener を継承し、以下のシグニチャを持つ + # operator() を実装している必要がある。 + # + # PreFsmActionListener::operator()(UniqueId ec_id) + # + # デフォルトでは、この関数に与えたリスナオブジェクトの所有権は + # RTObjectに移り、RTObject解体時もしくは、 + # removePreFsmActionListener() により削除時に自動的に解体される。 + # リスナオブジェクトの所有権を呼び出し側で維持したい場合は、第3引 + # 数に false を指定し、自動的な解体を抑制することができる。 + # + # @param listener_type リスナタイプ + # @param listener リスナオブジェクトへのポインタ + # + # @else + # @brief Adding PreFsmAction type listener + # + # This operation adds certain listeners related to FsmActions + # pre events. + # The following listener types are available. + # + # - PRE_ON_INITIALIZE: before onInitialize + # - PRE_ON_FINALIZE: before onFinalize + # - PRE_ON_STARTUP: before onStartup + # - PRE_ON_SHUTDOWN: before onShutdown + # - PRE_ON_ACTIVATED: before onActivated + # - PRE_ON_DEACTIVATED: before onDeactivated + # - PRE_ON_ABORTED: before onAborted + # - PRE_ON_ERROR: before onError + # - PRE_ON_RESET: before onReset + # - PRE_ON_EXECUTE: before onExecute + # - PRE_ON_STATE_UPDATE: before onStateUpdate + # + # Listeners should have the following function operator(). + # + # PreFsmActionListener::operator()(UniqueId ec_id) + # + # The ownership of the given listener object is transferred to + # this RTObject object in default. The given listener object will + # be destroied automatically in the RTObject's dtor or if the + # listener is deleted by removePreFsmActionListener() function. + # If you want to keep ownership of the listener object, give + # "false" value to 3rd argument to inhibit automatic destruction. + # + # @param listener_type A listener type + # @param listener A pointer to a listener object + # + # @endif + # + def addPreFsmActionListener(self, listener_type, + memfunc): + class Noname(OpenRTM_aist.PreFsmActionListener): + def __init__(self, memfunc): + self._memfunc = memfunc + return + + def __call__(self, state): + self._memfunc(state) + return + + listener = Noname(memfunc) + self._fsmActionListeners.addPreActionListener(listener_type, listener) + return listener + + ## + # @if jp + # @brief PreFsmActionListener リスナを削除する + # + # 設定した各種リスナを削除する。 + # + # @param listener_type リスナタイプ + # @param listener リスナオブジェクトへのポインタ + # + # @else + # @brief Removing PreFsmAction type listener + # + # This operation removes a specified listener. + # + # @param listener_type A listener type + # @param listener A pointer to a listener object + # + # @endif + # + def removePreFsmActionListener(self, listener_type, listener): + self._fsmActionListeners.removePreActionListener(listener_type, listener) + return + ## + # @if jp + # @brief PostFsmActionListener リスナを追加する + # + # FsmAction 実装関数の呼び出し直後のイベントに関連する各種リ + # スナを設定する。 + # + # 設定できるリスナのタイプとコールバックイベントは以下の通り + # + # - POST_ON_INITIALIZE: onInitialize 直後 + # - POST_ON_FINALIZE: onFinalize 直後 + # - POST_ON_STARTUP: onStartup 直後 + # - POST_ON_SHUTDOWN: onShutdown 直後 + # - POST_ON_ACTIVATED: onActivated 直後 + # - POST_ON_DEACTIVATED: onDeactivated 直後 + # - POST_ON_ABORTED: onAborted 直後 + # - POST_ON_ERROR: onError 直後 + # - POST_ON_RESET: onReset 直後 + # - POST_ON_EXECUTE: onExecute 直後 + # - POST_ON_STATE_UPDATE: onStateUpdate 直後 + # + # リスナは PostFsmActionListener を継承し、以下のシグニチャを持つ + # operator() を実装している必要がある。 + # + # PostFsmActionListener::operator()(const char* state, ReturnCode_t ret) + # + # デフォルトでは、この関数に与えたリスナオブジェクトの所有権は + # RTObjectに移り、RTObject解体時もしくは、 + # removePostFsmActionListener() により削除時に自動的に解体される。 + # リスナオブジェクトの所有権を呼び出し側で維持したい場合は、第3引 + # 数に false を指定し、自動的な解体を抑制することができる。 + # + # @param listener_type リスナタイプ + # @param listener リスナオブジェクトへのポインタ + # + # @else + # @brief Adding PostFsmAction type listener + # + # This operation adds certain listeners related to FsmActions + # post events. + # The following listener types are available. + # + # - POST_ON_INITIALIZE: after onInitialize + # - POST_ON_FINALIZE: after onFinalize + # - POST_ON_STARTUP: after onStartup + # - POST_ON_SHUTDOWN: after onShutdown + # - POST_ON_ACTIVATED: after onActivated + # - POST_ON_DEACTIVATED: after onDeactivated + # - POST_ON_ABORTED: after onAborted + # - POST_ON_ERROR: after onError + # - POST_ON_RESET: after onReset + # - POST_ON_EXECUTE: after onExecute + # - POST_ON_STATE_UPDATE: after onStateUpdate + # + # Listeners should have the following function operator(). + # + # PostFsmActionListener::operator()(const char* state, ReturnCode_t ret) + # + # The ownership of the given listener object is transferred to + # this RTObject object in default. The given listener object will + # be destroied automatically in the RTObject's dtor or if the + # listener is deleted by removePostFsmActionListener() function. + # If you want to keep ownership of the listener object, give + # "false" value to 3rd argument to inhibit automatic destruction. + # + # @param listener_type A listener type + # @param listener A pointer to a listener object + # + # @endif + # + + def addPostFsmActionListener(self, listener_type, + memfunc): + class Noname(OpenRTM_aist.PostFsmActionListener): + def __init__(self, memfunc): + self._memfunc = memfunc + return + + def __call__(self, state, ret): + self._memfunc(state, ret) + return + + listener = Noname(memfunc) + self._fsmActionListeners.addPostActionListener(listener_type, listener) + return listener + + ## + # @if jp + # @brief PostFsmActionListener リスナを削除する + # + # 設定した各種リスナを削除する。 + # + # @param listener_type リスナタイプ + # @param listener リスナオブジェクトへのポインタ + # + # @else + # @brief Removing PostFsmActionListener type listener + # + # This operation removes a specified listener. + # + # @param listener_type A listener type + # @param listener A pointer to a listener object + # + # @endif + # + + def removePostFsmActionListener(self, listener_type, listener): + self._fsmActionListeners.removePostActionListener(listener_type, listener) + return - ## - # @if jp - # - # @brief OutPort write()᥽åɤ򥳡뤹롣 - # - # RTC ݻƤ OutPort write()᥽åɤ򥳡뤹롣 - # - # @return ɤ߹߷(ݡȤؤν񤭹:true:false) - # - # @else - # - # @brief The write() method of all OutPort is called. - # - # This operation call the write() method of all OutPort - # registered in the RTC. - # - # @return result (Successful:true, Failed:false) - # - # @endif - # - # bool writeAll(); - def writeAll(self): - self._rtcout.RTC_TRACE("writeAll()") - ret = True - for outport in self._outports: - if not outport.write(): - self._rtcout.RTC_DEBUG("The error occurred in writeAll().") - ret = False - if not self._writeAllCompletion: - return False + ## + # @if jp + # @brief FsmProfileListener リスナを追加する + # + # FSMへのプロファイルの設定、取得時、またFSM自体への状態や遷移、イ + # ベントの追加削除時にコールバックされる各種リスナを設定する。 + # + # 設定できるリスナのタイプとコールバックイベントは以下の通り + # + # - SET_FSM_PROFILE : FSM Profile設定時 + # - GET_FSM_PROFILE : FSM Profile取得時 + # - ADD_FSM_STATE : FSMにStateが追加された + # - REMOVE_FSM_STATE : FSMからStateが削除された + # - ADD_FSM_TRANSITION : FSMに遷移が追加された + # - REMOVE_FSM_TRANSITION : FSMから遷移が削除された + # - BIND_FSM_EVENT : FSMにイベントがバインドされた + # - UNBIND_FSM_EVENT : FSMにイベントがアンバインドされた + # + # リスナは FsmProfileListener を継承し、以下のシグニチャを持つ + # operator() を実装している必要がある。 + # + # FsmProfileListener::operator()(RTC::FsmProfile& pprof) + # + # デフォルトでは、この関数に与えたリスナオブジェクトの所有権は + # RTObjectに移り、RTObject解体時もしくは、 + # removeFsmProfileListener() により削除時に自動的に解体される。 + # リスナオブジェクトの所有権を呼び出し側で維持したい場合は、第3引 + # 数に false を指定し、自動的な解体を抑制することができる。 + # + # @param listener_type リスナタイプ + # @param listener リスナオブジェクトへのポインタ + # + # @else + # @brief Adding FsmProfile type listener + # + # This operation adds certain listeners that is called when + # setting/getting FsmProfile and stae/transition/event add/remove + # to/from the FSM itself. + # + # The following listener types are available. + # + # - SET_FSM_PROFILE : Setting FSM Profile + # - GET_FSM_PROFILE : Getting FSM Profile + # - ADD_FSM_STATE : A State added to the FSM + # - REMOVE_FSM_STATE : A State removed from FSM + # - ADD_FSM_TRANSITION : A transition added to the FSM + # - REMOVE_FSM_TRANSITION : A transition removed from FSM + # - BIND_FSM_EVENT : An event bounded to the FSM + # - UNBIND_FSM_EVENT : An event unbounded to the FSM + # + # Listeners should have the following function operator(). + # + # FsmProfileListener::operator()(RTC::PortProfile pprof) + # + # The ownership of the given listener object is transferred to + # this RTObject object in default. The given listener object will + # be destroied automatically in the RTObject's dtor or if the + # listener is deleted by removeFsmProfileListener() function. + # If you want to keep ownership of the listener object, give + # "false" value to 3rd argument to inhibit automatic destruction. + # + # @param listener_type A listener type + # @param listener A pointer to a listener object + # + # @endif + # + + def addFsmProfileListener(self, listener_type, + memfunc): + class Noname(OpenRTM_aist.FsmProfileListener): + def __init__(self, memfunc): + self._memfunc = memfunc + return + + def __call__(self, pprofile): + self._memfunc(pprofile) + return + + listener = Noname(memfunc) + self._fsmActionListeners.addProfileListener(listener_type, listener) + return listener + + ## + # @if jp + # @brief FsmProfileListener リスナを削除する + # + # 設定した各種リスナを削除する。 + # + # @param listener_type リスナタイプ + # @param listener リスナオブジェクトへのポインタ + # + # @else + # @brief Removing FsmProfileListener type listener + # + # This operation removes a specified listener. + # + # @param listener_type A listener type + # @param listener A pointer to a listener object + # + # @endif + # + + def removeFsmProfileListener(self, listener_type, listener): + self._fsmActionListeners.removeProfileListener(listener_type, listener) + return - return ret + ## + # @if jp + # @brief FsmStructureListener リスナを追加する + # + # ExtendedFsmService に関連する FSM structure の設定・取得時にコー + # ルバックされる各種リスナを設定する。 + # + # 設定できるリスナのタイプとコールバックイベントは以下の通り + # + # - SET_FSM_STRUCTURE: FSM構造の設定 + # - GET_FSM_STRUCTURE: FSM構造の取得 + # + # リスナは FsmStructureListener を継承し、以下のシグニチャを持つ + # operator() を実装している必要がある。 + # + # FsmStructureListener::operator()(FsmStructure& structure) + # + # デフォルトでは、この関数に与えたリスナオブジェクトの所有権は + # RTObjectに移り、RTObject解体時もしくは、 + # removeFsmStructureListener() により削除時に自動的に解体される。 + # リスナオブジェクトの所有権を呼び出し側で維持したい場合は、第3引 + # 数に false を指定し、自動的な解体を抑制することができる。 + # + # @param listener_type リスナタイプ + # @param listener リスナオブジェクトへのポインタ + # + # @else + # @brief Adding FsmStructure type listener + # + # This operation adds certain listeners related to FSM structure + # data which are handled by ExtendedFsmService. + # + # The following listener types are available. + # + # - SET_FSM_STRUCTURE: Setting FSM structure + # - GET_FSM_STRUCTURE: Getting FSM structure + # + # Listeners should have the following function operator(). + # + # FsmStructureListener::operator()(RTC::FsmStructure structure) + # + # The ownership of the given listener object is transferred to + # this RTObject object in default. The given listener object will + # be destroied automatically in the RTObject's dtor or if the + # listener is deleted by removeFsmStructureListener() function. + # If you want to keep ownership of the listener object, give + # "false" value to 3rd argument to inhibit automatic destruction. + # + # @param listener_type A listener type + # @param listener A pointer to a listener object + # + # @endif + # + def addFsmStructureListener(self, listener_type, + memfunc): + class Noname(OpenRTM_aist.FsmStructureListener): + def __init__(self, memfunc): + self._memfunc = memfunc + return + + def __call__(self, pprofile): + self._memfunc(pprofile) + return + + listener = Noname(memfunc) + self._fsmActionListeners.addStructureListener(listener_type, listener) + return listener + + ## + # @if jp + # @brief FsmStructureListener リスナを削除する + # + # 設定した各種リスナを削除する。 + # + # @param listener_type リスナタイプ + # @param listener リスナオブジェクトへのポインタ + # + # @else + # @brief Removing FsmStructureListener type listener + # + # This operation removes a specified listener. + # + # @param listener_type A listener type + # @param listener A pointer to a listener object + # + # @endif + # + + def removeFsmStructureListener(self, listener_type, listener): + self._fsmActionListeners.removeStructureListener(listener_type, listener) + return + ## + # @if jp + # + # @brief RTC を終了する + # + # RTC の終了処理を実行する。 + # 保持している全 Port の登録を解除するとともに、該当する CORBA オブジェクト + # を非活性化し、RTC を終了する。 + # + # @param self + # + # @else + # + # @endif + + def shutdown(self): + self._rtcout.RTC_TRACE("shutdown()") + try: + self.finalizePorts() + self.finalizeContexts() + self._poa.deactivate_object( + self._poa.servant_to_id( + self._SdoConfigImpl)) + self._poa.deactivate_object(self._poa.servant_to_id(self)) + self._sdoservice.exit() + if not CORBA.is_nil(self._insref): + poa = self._orb.resolve_initial_references("omniINSPOA") + poa.deactivate_object(poa.servant_to_id(self)) + except BaseException: + self._rtcout.RTC_ERROR(OpenRTM_aist.Logger.print_exception()) + + if self._manager: + self._rtcout.RTC_DEBUG("Cleanup on Manager") + self._manager.notifyFinalized(self) + + del self._actionListeners + del self._portconnListeners - ## - # @if jp - # - # @brief onExecute()¹ǤreadAll()᥽åɤθƽФͭޤ̵ˤ롣 - # - # Υ᥽åɤѥ᡼trueȤƸƤֻˤꡢonExecute()¹ - # readAll()ƽФ褦ˤʤ롣 - # ѥ᡼falseξϡreadAll()ƽФ̵ˤ롣 - # - # @param read(default:true) - # (readAll()᥽åɸƽФ:true, readAll()᥽åɸƽФʤ:false) - # - # @param completion(default:false) - # readAll()ˤơɤ줫ΰĤInPortread()ԤƤƤInPortread()ƤӽФ:true, - # readAll()ˤơɤ줫ΰĤInPortread()Ԥ硢falseȴ:false - # - # @else - # - # @brief Set whether to execute the readAll() method. - # - # Set whether to execute the readAll() method. - # - # @param read(default:true) - # (readAll() is called:true, readAll() isn't called:false) - # - # @param completion(default:false) - # All InPort::read() calls are completed.:true, - # If one InPort::read() is False, return false.:false - # - # @param completion(default:false) - # - # @endif - # - # void setReadAll(bool read=true, bool completion=false); - def setReadAll(self, read=True, completion=False): - self._readAll = read - self._readAllCompletion = completion - - - ## - # @if jp - # - # @brief onExecute()¹ԸwriteAll()᥽åɤθƽФͭޤ̵ˤ롣 - # - # Υ᥽åɤѥ᡼trueȤƸƤֻˤꡢonExecute()¹Ը - # writeAll()ƽФ褦ˤʤ롣 - # ѥ᡼falseξϡwriteAll()ƽФ̵ˤ롣 - # - # @param write(default:true) - # (writeAll()᥽åɸƽФ:true, writeAll()᥽åɸƽФʤ:false) - # - # @param completion(default:false) - # writeAll()ˤơɤ줫ΰĤOutPortwrite()ԤƤƤOutPortwrite()ƤӽФԤ:true, - # writeAll()ˤơɤ줫ΰĤOutPortwrite()Ԥ硢falseȴ:false - # - # @else - # - # @brief Set whether to execute the writeAll() method. - # - # Set whether to execute the writeAll() method. - # - # @param write(default:true) - # (writeAll() is called:true, writeAll() isn't called:false) - # - # @param completion(default:false) - # All OutPort::write() calls are completed.:true, - # If one OutPort::write() is False, return false.:false - # - # @endif - # - # void setWriteAll(bool write=true, bool completion=false); - def setWriteAll(self, write=True, completion=False): - self._writeAll = write - self._writeAllCompletion = completion - - - ## - # @if jp - # - # @brief Port Ͽ - # - # RTC ݻƤ Port 롣 - # - # @param self - # - # @else - # - # @brief Unregister the All Portse - # - # This operation deactivates the all Port and deletes the all Port's - # registrations in the RTC.. - # - # @endif - def finalizePorts(self): - self._rtcout.RTC_TRACE("finalizePorts()") - self._portAdmin.finalizePorts() - self._inports = [] - self._outports = [] - return - - - def finalizeContexts(self): - self._rtcout.RTC_TRACE("finalizeContexts()") - len_ = len(self._eclist) - for ec in self._eclist: - ec.stop() - try: - self._poa.deactivate_object(self._poa.servant_to_id(ec)) - except: - self._rtcout.RTC_TRACE(OpenRTM_aist.Logger.print_exception()) - ec.exit() - self._eclist = [] - - - return - - - ## - # @if jp - # @brief PreComponentActionListener ꥹʤɲä - # - # ComponentAction ؿθƤӽФľΥ٥Ȥ˴ϢƼ - # ʤꤹ롣 - # - # ǤꥹʤΥפȥХå٥Ȥϰʲ̤ - # - # - PRE_ON_INITIALIZE: onInitialize ľ - # - PRE_ON_FINALIZE: onFinalize ľ - # - PRE_ON_STARTUP: onStartup ľ - # - PRE_ON_SHUTDOWN: onShutdown ľ - # - PRE_ON_ACTIVATED: onActivated ľ - # - PRE_ON_DEACTIVATED: onDeactivated ľ - # - PRE_ON_ABORTING: onAborted ľ - # - PRE_ON_ERROR: onError ľ - # - PRE_ON_RESET: onReset ľ - # - PRE_ON_EXECUTE: onExecute ľ - # - PRE_ON_STATE_UPDATE: onStateUpdate ľ - # - # ꥹʤ PreComponentActionListener ѾʲΥ˥ - # operator() Ƥɬפ롣 - # - # PreComponentActionListener::operator()(UniqueId ec_id) - # - # ǥեȤǤϡδؿͿꥹʥ֥Ȥνͭ - # RTObject˰ܤꡢRTObjectλ⤷ϡ - # removePreComponentActionListener() ˤ˼ưŪ˲Τ롣 - # ꥹʥ֥ȤνͭƤӽФ¦ǰݻϡ3 - # false ꤷưŪʲΤ뤳ȤǤ롣 - # - # @param listener_type ꥹʥ - # @param memfunc ؿ֥ - # @param autoclean ꥹʥ֥ȤμưŪΤԤɤΥե饰 - # - # @else - # @brief Adding PreComponentAction type listener - # - # This operation adds certain listeners related to ComponentActions - # pre events. - # The following listener types are available. - # - # - PRE_ON_INITIALIZE: before onInitialize - # - PRE_ON_FINALIZE: before onFinalize - # - PRE_ON_STARTUP: before onStartup - # - PRE_ON_SHUTDOWN: before onShutdown - # - PRE_ON_ACTIVATED: before onActivated - # - PRE_ON_DEACTIVATED: before onDeactivated - # - PRE_ON_ABORTING: before onAborted - # - PRE_ON_ERROR: before onError - # - PRE_ON_RESET: before onReset - # - PRE_ON_EXECUTE: before onExecute - # - PRE_ON_STATE_UPDATE: before onStateUpdate - # - # Listeners should have the following function operator(). - # - # PreComponentActionListener::operator()(UniqueId ec_id) - # - # The ownership of the given listener object is transferred to - # this RTObject object in default. The given listener object will - # be destroied automatically in the RTObject's dtor or if the - # listener is deleted by removePreComponentActionListener() function. - # If you want to keep ownership of the listener object, give - # "false" value to 3rd argument to inhibit automatic destruction. - # - # @param listener_type A listener type - # @param memfunc member function object - # @param autoclean A flag for automatic listener destruction - # - # @endif - # - # template - # PreComponentActionListener* - # addPreComponentActionListener(PreCompActionListenerType listener_type, - # void (Listener::*memfunc)(UniqueId ec_id), - # bool autoclean = true) - def addPreComponentActionListener(self, listener_type, - memfunc, autoclean = True): - class Noname(OpenRTM_aist.PreComponentActionListener): - def __init__(self, memfunc): - self._memfunc = memfunc - - def __call__(self, ec_id): - self._memfunc(ec_id) return - listener = Noname(memfunc) - self._actionListeners.preaction_[listener_type].addListener(listener, autoclean) - return listener - - - ## - # @if jp - # @brief PreComponentActionListener ꥹʤ - # - # ꤷƼꥹʤ롣 - # - # @param listener_type ꥹʥ - # @param listener ꥹʥ֥ȤؤΥݥ - # - # @else - # @brief Removing PreComponentAction type listener - # - # This operation removes a specified listener. - # - # @param listener_type A listener type - # @param listener A pointer to a listener object - # - # @endif - # - # void - # removePreComponentActionListener(PreComponentActionListenerType listener_type, - # PreComponentActionListener* listener); - def removePreComponentActionListener(self, listener_type, listener): - self._actionListeners.preaction_[listener_type].removeListener(listener) - return - - - ## - # @if jp - # @brief PostComponentActionListener ꥹʤɲä - # - # ComponentAction ؿθƤӽФľΥ٥Ȥ˴ϢƼ - # ʤꤹ롣 - # - # ǤꥹʤΥפȥХå٥Ȥϰʲ̤ - # - # - POST_ON_INITIALIZE: onInitialize ľ - # - POST_ON_FINALIZE: onFinalize ľ - # - POST_ON_STARTUP: onStartup ľ - # - POST_ON_SHUTDOWN: onShutdown ľ - # - POST_ON_ACTIVATED: onActivated ľ - # - POST_ON_DEACTIVATED: onDeactivated ľ - # - POST_ON_ABORTING: onAborted ľ - # - POST_ON_ERROR: onError ľ - # - POST_ON_RESET: onReset ľ - # - POST_ON_EXECUTE: onExecute ľ - # - POST_ON_STATE_UPDATE: onStateUpdate ľ - # - # ꥹʤ PostComponentActionListener ѾʲΥ˥ - # operator() Ƥɬפ롣 - # - # PostComponentActionListener::operator()(UniqueId ec_id, ReturnCode_t ret) - # - # ǥեȤǤϡδؿͿꥹʥ֥Ȥνͭ - # RTObject˰ܤꡢRTObjectλ⤷ϡ - # removePostComponentActionListener() ˤ˼ưŪ˲Τ롣 - # ꥹʥ֥ȤνͭƤӽФ¦ǰݻϡ3 - # false ꤷưŪʲΤ뤳ȤǤ롣 - # - # @param listener_type ꥹʥ - # @param memfunc ؿ֥ - # @param autoclean ꥹʥ֥ȤμưŪΤԤɤΥե饰 - # - # @else - # @brief Adding PostComponentAction type listener - # - # This operation adds certain listeners related to ComponentActions - # post events. - # The following listener types are available. - # - # - POST_ON_INITIALIZE: after onInitialize - # - POST_ON_FINALIZE: after onFinalize - # - POST_ON_STARTUP: after onStartup - # - POST_ON_SHUTDOWN: after onShutdown - # - POST_ON_ACTIVATED: after onActivated - # - POST_ON_DEACTIVATED: after onDeactivated - # - POST_ON_ABORTING: after onAborted - # - POST_ON_ERROR: after onError - # - POST_ON_RESET: after onReset - # - POST_ON_EXECUTE: after onExecute - # - POST_ON_STATE_UPDATE: after onStateUpdate - # - # Listeners should have the following function operator(). - # - # PostComponentActionListener::operator()(UniqueId ec_id, ReturnCode_t ret) - # - # The ownership of the given listener object is transferred to - # this RTObject object in default. The given listener object will - # be destroied automatically in the RTObject's dtor or if the - # listener is deleted by removePostComponentActionListener() function. - # If you want to keep ownership of the listener object, give - # "false" value to 3rd argument to inhibit automatic destruction. - # - # @param listener_type A listener type - # @param memfunc member function object - # @param autoclean A flag for automatic listener destruction - # - # @endif - # - # template - # PostComponentActionListener* - # addPostComponentActionListener(PostCompActionListenerType listener_type, - # void (Listener::*memfunc)(UniqueId ec_id, - # ReturnCode_t ret), - # bool autoclean = true) - def addPostComponentActionListener(self, listener_type, - memfunc, autoclean = True): - class Noname(OpenRTM_aist.PostComponentActionListener): - def __init__(self, memfunc): - self._memfunc = memfunc + # inline void preOnInitialize(UniqueId ec_id) + def preOnInitialize(self, ec_id): + self._actionListeners.notifyPreAction(OpenRTM_aist.PreComponentActionListenerType.PRE_ON_INITIALIZE, ec_id) return - def __call__(self, ec_id, ret): - self._memfunc(ec_id, ret) + + # inline void preOnFinalize(UniqueId ec_id) + def preOnFinalize(self, ec_id): + self._actionListeners.notifyPreAction(OpenRTM_aist.PreComponentActionListenerType.PRE_ON_FINALIZE, ec_id) return - - listener = Noname(memfunc) - self._actionListeners.postaction_[listener_type].addListener(listener, autoclean) - return listener - - - ## - # @if jp - # @brief PostComponentActionListener ꥹʤ - # - # ꤷƼꥹʤ롣 - # - # @param listener_type ꥹʥ - # @param listener ꥹʥ֥ȤؤΥݥ - # - # @else - # @brief Removing PostComponentAction type listener - # - # This operation removes a specified listener. - # - # @param listener_type A listener type - # @param listener A pointer to a listener object - # - # @endif - ## - # void - # removePostComponentActionListener(PostComponentActionListenerType listener_type, - # PostComponentActionListener* listener); - def removePostComponentActionListener(self, listener_type, listener): - self._actionListeners.postaction_[listener_type].removeListener(listener) - return - - - ## - # @if jp - # @brief PortActionListener ꥹʤɲä - # - # Portɲá˥ХåƼꥹʤꤹ롣 - # - # ǤꥹʤΥפȥХå٥Ȥϰʲ̤ - # - # - ADD_PORT: Portɲû - # - REMOVE_PORT: Port - # - # ꥹʤ PortActionListener ѾʲΥ˥ - # operator() Ƥɬפ롣 - # - # PortActionListener::operator()(PortProfile& pprof) - # - # ǥեȤǤϡδؿͿꥹʥ֥Ȥνͭ - # RTObject˰ܤꡢRTObjectλ⤷ϡ - # removePortActionListener() ˤ˼ưŪ˲Τ롣 - # ꥹʥ֥ȤνͭƤӽФ¦ǰݻϡ3 - # false ꤷưŪʲΤ뤳ȤǤ롣 - # - # @param listener_type ꥹʥ - # @param memfunc ؿ֥ - # @param autoclean ꥹʥ֥ȤμưŪΤԤɤΥե饰 - # - # @else - # @brief Adding PortAction type listener - # - # This operation adds certain listeners related to ComponentActions - # post events. - # The following listener types are available. - # - # - ADD_PORT: At adding Port - # - REMOVE_PORT: At removing Port - # - # Listeners should have the following function operator(). - # - # PortActionListener::operator()(RTC::PortProfile pprof) - # - # The ownership of the given listener object is transferred to - # this RTObject object in default. The given listener object will - # be destroied automatically in the RTObject's dtor or if the - # listener is deleted by removePortActionListener() function. - # If you want to keep ownership of the listener object, give - # "false" value to 3rd argument to inhibit automatic destruction. - # - # @param listener_type A listener type - # @param memfunc member function object - # @param autoclean A flag for automatic listener destruction - # - # @endif - # - # template - # PortActionListener* - # addPortActionListener(PortActionListenerType listener_type, - # void (Listener::*memfunc)(const RTC::PortProfile&), - # bool autoclean=true) - def addPortActionListener(self, listener_type, - memfunc, autoclean = True): - class Noname(OpenRTM_aist.PortActionListener): - def __init__(self, memfunc): - self._memfunc = memfunc + + # inline void preOnStartup(UniqueId ec_id) + def preOnStartup(self, ec_id): + self._actionListeners.notifyPreAction(OpenRTM_aist.PreComponentActionListenerType.PRE_ON_STARTUP, ec_id) return - def __call__(self, pprofile): - self._memfunc(pprofile) + # inline void preOnShutdown(UniqueId ec_id) + def preOnShutdown(self, ec_id): + self._actionListeners.notifyPreAction(OpenRTM_aist.PreComponentActionListenerType.PRE_ON_SHUTDOWN, ec_id) return - listener = Noname(memfunc) - - self._actionListeners.portaction_[listener_type].addListener(listener, autoclean) - return listener - - - ## - # @if jp - # @brief PortActionListener ꥹʤ - # - # ꤷƼꥹʤ롣 - # - # @param listener_type ꥹʥ - # @param listener ꥹʥ֥ȤؤΥݥ - # - # @else - # @brief Removing PortAction type listener - # - # This operation removes a specified listener. - # - # @param listener_type A listener type - # @param listener A pointer to a listener object - # - # @endif - # void - # removePortActionListener(PortActionListenerType listener_type, - # PortActionListener* listener); - def removePortActionListener(self, listener_type, listener): - self._actionListeners.portaction_[listener_type].removeListener(listener) - return - - - ## - # @if jp - # @brief ExecutionContextActionListener ꥹʤɲä - # - # ExecutionContextɲá˥ХåƼꥹʤꤹ롣 - # - # ǤꥹʤΥפȥХå٥Ȥϰʲ̤ - # - # - ATTACH_EC: ExecutionContext å - # - DETACH_EC: ExecutionContext ǥå - # - # ꥹʤ ExecutionContextActionListener ѾʲΥ˥ - # operator() Ƥɬפ롣 - # - # ExecutionContextActionListener::operator()(UniqueIdec_id) - # - # ǥեȤǤϡδؿͿꥹʥ֥Ȥνͭ - # RTObject˰ܤꡢRTObjectλ⤷ϡ - # removeExecutionContextActionListener() ˤ˼ưŪ˲Τ롣 - # ꥹʥ֥ȤνͭƤӽФ¦ǰݻϡ3 - # false ꤷưŪʲΤ뤳ȤǤ롣 - # - # @param listener_type ꥹʥ - # @param memfunc ؿ֥ - # @param autoclean ꥹʥ֥ȤμưŪΤԤɤΥե饰 - # - # @else - # @brief Adding ExecutionContextAction type listener - # - # This operation adds certain listeners related to ComponentActions - # post events. - # The following listener types are available. - # - # - ADD_PORT: At adding ExecutionContext - # - REMOVE_PORT: At removing ExecutionContext - # - # Listeners should have the following function operator(). - # - # ExecutionContextActionListener::operator()(UniqueId ec_id) - # - # The ownership of the given listener object is transferred to - # this RTObject object in default. The given listener object will - # be destroied automatically in the RTObject's dtor or if the - # listener is deleted by removeExecutionContextActionListener() function. - # If you want to keep ownership of the listener object, give - # "false" value to 3rd argument to inhibit automatic destruction. - # - # @param listener_type A listener type - # @param memfunc member function object - # @param autoclean A flag for automatic listener destruction - # - # @endif - # - # template - # ECActionListener* - # addExecutionContextActionListener(ECActionListenerType listener_type, - # void (Listener::*memfunc)(UniqueId), - # bool autoclean = true); - def addExecutionContextActionListener(self, listener_type, - memfunc, autoclean = True): - class Noname(OpenRTM_aist.ExecutionContextActionListener): - def __init__(self, memfunc): - self._memfunc = memfunc + # inline void preOnActivated(UniqueId ec_id) + def preOnActivated(self, ec_id): + self._actionListeners.notifyPreAction(OpenRTM_aist.PreComponentActionListenerType.PRE_ON_ACTIVATED, ec_id) return - def __call__(self, ec_id): - self._memfunc(ec_id) + # inline void preOnDeactivated(UniqueId ec_id) + def preOnDeactivated(self, ec_id): + self._actionListeners.notifyPreAction(OpenRTM_aist.PreComponentActionListenerType.PRE_ON_DEACTIVATED, ec_id) return - listener = Noname(memfunc) - self._actionListeners.ecaction_[listener_type].addListener(listener, autoclean) - return listener - - - ## - # @if jp - # @brief ExecutionContextActionListener ꥹʤ - # - # ꤷƼꥹʤ롣 - # - # @param listener_type ꥹʥ - # @param listener ꥹʥ֥ȤؤΥݥ - # - # @else - # @brief Removing ExecutionContextAction type listener - # - # This operation removes a specified listener. - # - # @param listener_type A listener type - # @param listener A pointer to a listener object - # - # @endif - # - # void - # removeExecutionContextActionListener(ECActionListenerType listener_type, - # ECActionListener* listener); - def removeExecutionContextActionListener(self, listener_type, listener): - self._actionListeners.ecaction_[listener_type].removeListener(listener) - return - - - ## - # @if jp - # @brief PortConnectListener ꥹʤɲä - # - # Port³³˸ƤӽФƼꥹʤꤹ롣 - # - # ǤꥹʤΥפȥХå٥Ȥϰʲ̤ - # - # - ON_NOTIFY_CONNECT: notify_connect() ؿƤӽФľ - # - ON_NOTIFY_DISCONNECT: notify_disconnect() ƤӽФľ - # - ON_UNSUBSCRIBE_INTERFACES: notify_disconnect() IFɲ - # - # ꥹʤ PortConnectListener ѾʲΥ˥ - # operator() Ƥɬפ롣 - # - # PortConnectListener::operator()(const char*, ConnectorProfile) - # - # ǥեȤǤϡδؿͿꥹʥ֥Ȥνͭ - # RTObject˰ܤꡢRTObjectλ⤷ϡ - # removePortConnectListener() ˤ˼ưŪ˲Τ롣 - # ꥹʥ֥ȤνͭƤӽФ¦ǰݻϡ3 - # false ꤷưŪʲΤ뤳ȤǤ롣 - # - # @param listener_type ꥹʥ - # @param memfunc ؿ֥ - # @param autoclean ꥹʥ֥ȤμưŪΤԤɤΥե饰 - # - # @else - # @brief Adding PortConnect type listener - # - # This operation adds certain listeners related to Port's connect actions. - # The following listener types are available. - # - # - ON_NOTIFY_CONNECT: right after entering into notify_connect() - # - ON_NOTIFY_DISCONNECT: right after entering into notify_disconnect() - # - ON_UNSUBSCRIBE_INTERFACES: unsubscribing IF in notify_disconnect() - # - # Listeners should have the following function operator(). - # - # PortConnectListener::operator()(const char*, ConnectorProfile) - # - # The ownership of the given listener object is transferred to - # this RTObject object in default. The given listener object will - # be destroied automatically in the RTObject's dtor or if the - # listener is deleted by removePortConnectListener() function. - # If you want to keep ownership of the listener object, give - # "false" value to 3rd argument to inhibit automatic destruction. - # - # @param listener_type A listener type - # @param memfunc member function object - # @param autoclean A flag for automatic listener destruction - # - # @endif - # - # template - # PortConnectListener* - # addPortConnectListener(PortConnectListenerType listener_type, - # void (Listener::*memfunc)(const char*, - # ConnectorProfile&), - # bool autoclean = true) - def addPortConnectListener(self, listener_type, - memfunc, autoclean = True): - class Noname(OpenRTM_aist.PortConnectListener): - def __init__(self, memfunc): - self._memfunc = memfunc + # inline void preOnAborting(UniqueId ec_id) + def preOnAborting(self, ec_id): + self._actionListeners.notifyPreAction(OpenRTM_aist.PreComponentActionListenerType.PRE_ON_ABORTING, ec_id) return - def __call__(self, portname, cprofile): - self._memfunc(portname, cprofile) + # inline void preOnError(UniqueId ec_id) + def preOnError(self, ec_id): + self._actionListeners.notifyPreAction(OpenRTM_aist.PreComponentActionListenerType.PRE_ON_ERROR, ec_id) return - listener = Noname(memfunc) - self._portconnListeners.portconnect_[listener_type].addListener(listener, autoclean) - return listener - - - ## - # @if jp - # @brief PortConnectListener ꥹʤ - # - # ꤷƼꥹʤ롣 - # - # @param listener_type ꥹʥ - # @param listener ꥹʥ֥ȤؤΥݥ - # - # @else - # @brief Removing PortConnect type listener - # - # This operation removes a specified listener. - # - # @param listener_type A listener type - # @param listener A pointer to a listener object - # - # @endif - # - # void - # removePortConnectListener(PortConnectListenerType listener_type, - # PortConnectListener* listener); - def removePortConnectListener(self, listener_type, listener): - self._portconnListeners.portconnect_[listener_type].removeListener(listener) - return - - - ## - # @if jp - # @brief PortConnectRetListener ꥹʤɲä - # - # Port³³˸ƤӽФƼꥹʤꤹ롣 - # - # ǤꥹʤΥפȥХå٥Ȥϰʲ̤ - # - # - ON_CONNECT_NEXTPORT: notify_connect() ΥɸƤӽФľ - # - ON_SUBSCRIBE_INTERFACES: notify_connect() Υ󥿡եľ - # - ON_CONNECTED: nofity_connect() ³λ˸ƤӽФ - # - ON_DISCONNECT_NEXT: notify_disconnect() ˥ɸƤӽФľ - # - ON_DISCONNECTED: notify_disconnect() ꥿ - # - # ꥹʤ PortConnectRetListener ѾʲΥ˥ - # operator() Ƥɬפ롣 - # - # PortConnectRetListener::operator()(const char*, ConnectorProfile) - # - # ǥեȤǤϡδؿͿꥹʥ֥Ȥνͭ - # RTObject˰ܤꡢRTObjectλ⤷ϡ - # removePortConnectRetListener() ˤ˼ưŪ˲Τ롣 - # ꥹʥ֥ȤνͭƤӽФ¦ǰݻϡ3 - # false ꤷưŪʲΤ뤳ȤǤ롣 - # - # @param listener_type ꥹʥ - # @param memfunc ؿ֥ - # @param autoclean ꥹʥ֥ȤμưŪΤԤɤΥե饰 - # - # @else - # @brief Adding PortConnectRet type listener - # - # This operation adds certain listeners related to Port's connect actions. - # The following listener types are available. - # - # - ON_CONNECT_NEXTPORT: after cascade-call in notify_connect() - # - ON_SUBSCRIBE_INTERFACES: after IF subscribing in notify_connect() - # - ON_CONNECTED: completed nofity_connect() connection process - # - ON_DISCONNECT_NEXT: after cascade-call in notify_disconnect() - # - ON_DISCONNECTED: completed notify_disconnect() disconnection process - # - # Listeners should have the following function operator(). - # - # PortConnectRetListener::operator()(const char*, ConnectorProfile) - # - # The ownership of the given listener object is transferred to - # this RTObject object in default. The given listener object will - # be destroied automatically in the RTObject's dtor or if the - # listener is deleted by removePortConnectRetListener() function. - # If you want to keep ownership of the listener object, give - # "false" value to 3rd argument to inhibit automatic destruction. - # - # @param listener_type A listener type - # @param memfunc member function object - # @param autoclean A flag for automatic listener destruction - # - # @endif - # - # template - # PortConnectRetListener* - # addPortConnectRetListener(PortConnectRetListenerType listener_type, - # void (Listener::*memfunc)(const char*, - # ConnectorProfile&, - # ReturnCode_t)) - def addPortConnectRetListener(self, listener_type, - memfunc, autoclean = True): - class Noname(OpenRTM_aist.PortConnectRetListener): - def __init__(self, memfunc): - self._memfunc = memfunc + # inline void preOnReset(UniqueId ec_id) + def preOnReset(self, ec_id): + self._actionListeners.notifyPreAction(OpenRTM_aist.PreComponentActionListenerType.PRE_ON_RESET, ec_id) return - def __call__(self, portname, cprofile, ret): - self._memfunc(portname, cprofile, ret) + # inline void preOnExecute(UniqueId ec_id) + def preOnExecute(self, ec_id): + self._actionListeners.notifyPreAction(OpenRTM_aist.PreComponentActionListenerType.PRE_ON_EXECUTE, ec_id) return - listener = Noname(memfunc) - self._portconnListeners.portconnret_[listener_type].addListener(listener, autoclean) - return listener - - - ## - # @if jp - # @brief PortConnectRetListener ꥹʤ - # - # ꤷƼꥹʤ롣 - # - # @param listener_type ꥹʥ - # @param listener ꥹʥ֥ȤؤΥݥ - # - # @else - # @brief Removing PortConnectRet type listener - # - # This operation removes a specified listener. - # - # @param listener_type A listener type - # @param listener A pointer to a listener object - # - # @endif - # - # void - # removePortConnectRetListener(PortConnectRetListenerType listener_type, - # PortConnectRetListener* listener); - def removePortConnectRetListener(self, listener_type, listener): - self._portconnListeners.portconnret_[listener_type].removeListener(listener) - return - - - ## - # @if jp - # - # @brief ConfigurationParamListener ɲä - # - # update(const char* config_set, const char* config_param) ƤФ줿ݤ - # 뤵ꥹ ConfigurationParamListener ɲä롣 - # type ˤϸߤΤȤ ON_UPDATE_CONFIG_PARAM Τߤ롣 - # - # @param type ConfigurationParamListenerType͡ - # ON_UPDATE_CONFIG_PARAM 롣 - # - # @param memfunc ؿ֥ - # @param autoclean ꥹʥ֥ȤưǺ뤫ɤΥե饰 - # - # @else - # - # @brief Adding ConfigurationParamListener - # - # This function adds a listener object which is called when - # update(const char* config_set, const char* config_param) is - # called. In the type argument, currently only - # ON_UPDATE_CONFIG_PARAM is allowed. - # - # @param type ConfigurationParamListenerType value - # ON_UPDATE_CONFIG_PARAM is only allowed. - # - # @param memfunc member function object - # @param autoclean a flag whether if the listener object autocleaned. - # - # @endif - # - # template - # ConfigurationParamListener* - # addConfigurationParamListener(ConfigurationParamListenerType listener_type, - # void (Listener::*memfunc)(const char*, - # const char*), - # bool autoclean = true) - def addConfigurationParamListener(self, type, - memfunc, autoclean = True): - class Noname(OpenRTM_aist.ConfigurationParamListener): - def __init__(self, memfunc): - self._memfunc = memfunc + # inline void preOnStateUpdate(UniqueId ec_id) + def preOnStateUpdate(self, ec_id): + self._actionListeners.notifyPreAction(OpenRTM_aist.PreComponentActionListenerType.PRE_ON_STATE_UPDATE, ec_id) return - def __call__(self, config_set_name, config_param_name): - self._memfunc(config_set_name, config_param_name) + # inline void preOnRateChanged(UniqueId ec_id) + + def preOnRateChanged(self, ec_id): + self._actionListeners.notifyPreAction(OpenRTM_aist.PreComponentActionListenerType.PRE_ON_RATE_CHANGED, ec_id) return - listener = Noname(memfunc) - self._configsets.addConfigurationParamListener(type, listener, autoclean) - return listener - - - ## - # @if jp - # - # @brief ConfigurationParamListener - # - # addConfigurationParamListener ɲä줿ꥹʥ֥Ȥ롣 - # - # @param type ConfigurationParamListenerType͡ - # ON_UPDATE_CONFIG_PARAM 롣 - # @param listener Ϳꥹʥ֥ȤؤΥݥ - # - # @else - # - # @brief Removing ConfigurationParamListener - # - # This function removes a listener object which is added by - # addConfigurationParamListener() function. - # - # @param type ConfigurationParamListenerType value - # ON_UPDATE_CONFIG_PARAM is only allowed. - # @param listener a pointer to ConfigurationParamListener listener object. - # - # @endif - # - # void removeConfigurationParamListener(ConfigurationParamListenerType type, - # ConfigurationParamListener* listener); - def removeConfigurationParamListener(self, type, listener): - self._configsets.removeConfigurationParamListener(type, listener) - return - - - ## - # @if jp - # - # @brief ConfigurationSetListener ɲä - # - # ConfigurationSet 줿Ȥʤɤ˸ƤФꥹ - # ConfigurationSetListener ɲä롣ǽʥ٥Ȥϰʲ - # 2ब롣 - # - # - ON_SET_CONFIG_SET: setConfigurationSetValues() - # ConfigurationSet ͤꤵ줿硣 - # - ON_ADD_CONFIG_SET: addConfigurationSet() ǿ - # ConfigurationSet ɲä줿硣 - # - # @param type ConfigurationSetListenerType͡ - # @param memfunc ؿ֥ - # @param autoclean ꥹʥ֥ȤưǺ뤫ɤΥե饰 - # - # @else - # - # @brief Adding ConfigurationSetListener - # - # This function add a listener object which is called when - # ConfigurationSet is updated. Available events are the followings. - # - # @param type ConfigurationSetListenerType value - # @param memfunc member function object - # @param autoclean a flag whether if the listener object autocleaned. - # - # @endif - # - # template - # ConfigurationSetListener* - # addConfigurationSetListener(ConfigurationSetListenerType listener_type, - # void (Listener::*memfunc) - # (const coil::Properties& config_set)) - def addConfigurationSetListener(self, listener_type, - memfunc, autoclean = True): - class Noname(OpenRTM_aist.ConfigurationSetListener): - def __init__(self, memfunc): - self._memfunc = memfunc + # inline void postOnInitialize(UniqueId ec_id, ReturnCode_t ret) + + def postOnInitialize(self, ec_id, ret): + self._actionListeners.notifyPostAction( + OpenRTM_aist.PostComponentActionListenerType.POST_ON_INITIALIZE, ec_id, ret) return - def __call__(self, config_set): - self._memfunc(config_set) + # inline void postOnFinalize(UniqueId ec_id, ReturnCode_t ret) + + def postOnFinalize(self, ec_id, ret): + self._actionListeners.notifyPostAction( + OpenRTM_aist.PostComponentActionListenerType.POST_ON_FINALIZE, ec_id, ret) return - listener = Noname(memfunc) - self._configsets.addConfigurationSetListener(listener_type, listener, autoclean) - return listener - - - ## - # @if jp - # - # @brief ConfigurationSetListener - # - # addConfigurationSetListener ɲä줿ꥹʥ֥Ȥ롣 - # - # @param type ConfigurationSetListenerType͡ - # @param listener Ϳꥹʥ֥ȤؤΥݥ - # - # @else - # - # @brief Removing ConfigurationSetListener - # - # This function removes a listener object which is added by - # addConfigurationSetListener() function. - # - # @param type ConfigurationSetListenerType value - # @param listener a pointer to ConfigurationSetListener listener object. - # - # @endif - # - # void removeConfigurationSetListener(ConfigurationSetListenerType type, - # ConfigurationSetListener* listener); - def removeConfigurationSetListener(self, type, listener): - self._configsets.removeConfigurationSetListener(type, listener) - return - - - ## - # @if jp - # - # @brief ConfigurationSetNameListener ɲä - # - # ConfigurationSetName 줿Ȥʤɤ˸ƤФꥹ - # ConfigurationSetNameListener ɲä롣ǽʥ٥Ȥϰʲ - # 3ब롣 - # - # - ON_UPDATE_CONFIG_SET: ConfigurationSet åץǡȤ줿 - # - ON_REMOVE_CONFIG_SET: ConfigurationSet 줿 - # - ON_ACTIVATE_CONFIG_SET: ConfigurationSet ƥֲ줿 - # - # @param type ConfigurationSetNameListenerType͡ - # @param memfunc ؿ֥ - # @param autoclean ꥹʥ֥ȤưǺ뤫ɤΥե饰 - # - # @else - # - # @brief Adding ConfigurationSetNameListener - # - # This function add a listener object which is called when - # ConfigurationSetName is updated. Available events are the followings. - # - # - ON_UPDATE_CONFIG_SET: A ConfigurationSet has been updated. - # - ON_REMOVE_CONFIG_SET: A ConfigurationSet has been deleted. - # - ON_ACTIVATE_CONFIG_SET: A ConfigurationSet has been activated. - # - # @param type ConfigurationSetNameListenerType value - # @param memfunc member function object - # @param autoclean a flag whether if the listener object autocleaned. - # - # @endif - # - # template - # ConfigurationSetNameListener* - # addConfigurationSetNameListener(ConfigurationSetNameListenerType type, - # void (Listener::*memfunc)(const char*)) - def addConfigurationSetNameListener(self, type, memfunc, autoclean = True): - class Noname(OpenRTM_aist.ConfigurationSetNameListener): - def __init__(self, memfunc): - self._memfunc = memfunc + # inline void postOnStartup(UniqueId ec_id, ReturnCode_t ret) + + def postOnStartup(self, ec_id, ret): + self._actionListeners.notifyPostAction( + OpenRTM_aist.PostComponentActionListenerType.POST_ON_STARTUP, ec_id, ret) return - def __call__(self, config_set_name): - self._memfunc(config_set_name) + # inline void postOnShutdown(UniqueId ec_id, ReturnCode_t ret) + + def postOnShutdown(self, ec_id, ret): + self._actionListeners.notifyPostAction( + OpenRTM_aist.PostComponentActionListenerType.POST_ON_SHUTDOWN, ec_id, ret) return - listener = Noname(memfunc) - self._configsets.addConfigurationSetNameListener(type, listener, autoclean) - return listener - - - ## - # @if jp - # - # @brief ConfigurationSetNameListener - # - # addConfigurationSetNameListener ɲä줿ꥹʥ֥Ȥ - # 롣 - # - # @param type ConfigurationSetNameListenerType͡ - # ON_UPDATE_CONFIG_PARAM 롣 - # @param listener Ϳꥹʥ֥ȤؤΥݥ - # - # @else - # - # @brief Removing ConfigurationSetNameListener - # - # This function removes a listener object which is added by - # addConfigurationSetNameListener() function. - # - # @param type ConfigurationSetNameListenerType value - # ON_UPDATE_CONFIG_PARAM is only allowed. - # @param listener a pointer to ConfigurationSetNameListener - # listener object. - # - # @endif - # void - # removeConfigurationSetNameListener(ConfigurationSetNameListenerType type, - # ConfigurationSetNameListener* listener); - def removeConfigurationSetNameListener(self, type, listener): - self._configsets.removeConfigurationSetNameListener(type, listener) - return - - ## - # @if jp - # - # @brief ConfigurationSetNameListener - # - # addConfigurationSetNameListener ɲä줿ꥹʥ֥Ȥ - # 롣 - # - # @param type ConfigurationSetNameListenerType͡ - # ON_UPDATE_CONFIG_PARAM 롣 - # @param listener Ϳꥹʥ֥ȤؤΥݥ - # - # @else - # - # @brief Removing ConfigurationSetNameListener - # - # This function removes a listener object which is added by - # addConfigurationSetNameListener() function. - # - # @param type ConfigurationSetNameListenerType value - # ON_UPDATE_CONFIG_PARAM is only allowed. - # @param listener a pointer to ConfigurationSetNameListener - # listener object. - # - # @endif - # void - # removeConfigurationSetNameListener(ConfigurationSetNameListenerType type, - # ConfigurationSetNameListener* listener); - def removeConfigurationSetNameListener(self, type, listener): - self._configsets.removeConfigurationSetNameListener(type, listener) - return - - ## - # @if jp - # @brief PreFsmActionListener ꥹʤɲä - # - # FsmAction ؿθƤӽФľΥ٥Ȥ˴ϢƼ - # ʤꤹ롣 - # - # ǤꥹʤΥפȥХå٥Ȥϰʲ̤ - # - # - PRE_ON_INITIALIZE: onInitialize ľ - # - PRE_ON_FINALIZE: onFinalize ľ - # - PRE_ON_STARTUP: onStartup ľ - # - PRE_ON_SHUTDOWN: onShutdown ľ - # - PRE_ON_ACTIVATED: onActivated ľ - # - PRE_ON_DEACTIVATED: onDeactivated ľ - # - PRE_ON_ABORTED: onAborted ľ - # - PRE_ON_ERROR: onError ľ - # - PRE_ON_RESET: onReset ľ - # - PRE_ON_EXECUTE: onExecute ľ - # - PRE_ON_STATE_UPDATE: onStateUpdate ľ - # - # ꥹʤ PreFsmActionListener ѾʲΥ˥ - # operator() Ƥɬפ롣 - # - # PreFsmActionListener::operator()(UniqueId ec_id) - # - # ǥեȤǤϡδؿͿꥹʥ֥Ȥνͭ - # RTObject˰ܤꡢRTObjectλ⤷ϡ - # removePreFsmActionListener() ˤ˼ưŪ˲Τ롣 - # ꥹʥ֥ȤνͭƤӽФ¦ǰݻϡ3 - # false ꤷưŪʲΤ뤳ȤǤ롣 - # - # @param listener_type ꥹʥ - # @param listener ꥹʥ֥ȤؤΥݥ - # @param autoclean ꥹʥ֥ȤμưŪΤԤɤΥե饰 - # - # @else - # @brief Adding PreFsmAction type listener - # - # This operation adds certain listeners related to FsmActions - # pre events. - # The following listener types are available. - # - # - PRE_ON_INITIALIZE: before onInitialize - # - PRE_ON_FINALIZE: before onFinalize - # - PRE_ON_STARTUP: before onStartup - # - PRE_ON_SHUTDOWN: before onShutdown - # - PRE_ON_ACTIVATED: before onActivated - # - PRE_ON_DEACTIVATED: before onDeactivated - # - PRE_ON_ABORTED: before onAborted - # - PRE_ON_ERROR: before onError - # - PRE_ON_RESET: before onReset - # - PRE_ON_EXECUTE: before onExecute - # - PRE_ON_STATE_UPDATE: before onStateUpdate - # - # Listeners should have the following function operator(). - # - # PreFsmActionListener::operator()(UniqueId ec_id) - # - # The ownership of the given listener object is transferred to - # this RTObject object in default. The given listener object will - # be destroied automatically in the RTObject's dtor or if the - # listener is deleted by removePreFsmActionListener() function. - # If you want to keep ownership of the listener object, give - # "false" value to 3rd argument to inhibit automatic destruction. - # - # @param listener_type A listener type - # @param listener A pointer to a listener object - # @param autoclean A flag for automatic listener destruction - # - # @endif - # - def addPreFsmActionListener(self, listener_type, - memfunc, autoclean = True): - class Noname(OpenRTM_aist.PreFsmActionListener): - def __init__(self, memfunc): - self._memfunc = memfunc + # inline void postOnActivated(UniqueId ec_id, ReturnCode_t ret) + + def postOnActivated(self, ec_id, ret): + self._actionListeners.notifyPostAction( + OpenRTM_aist.PostComponentActionListenerType.POST_ON_ACTIVATED, ec_id, ret) return - def __call__(self, state): - self._memfunc(state) + # inline void postOnDeactivated(UniqueId ec_id, ReturnCode_t ret) + + def postOnDeactivated(self, ec_id, ret): + self._actionListeners.notifyPostAction( + OpenRTM_aist.PostComponentActionListenerType.POST_ON_DEACTIVATED, ec_id, ret) return - listener = Noname(memfunc) - self._fsmActionListeners.preaction_[listener_type].addListener(listener, autoclean) - return listener - - ## - # @if jp - # @brief PreFsmActionListener ꥹʤ - # - # ꤷƼꥹʤ롣 - # - # @param listener_type ꥹʥ - # @param listener ꥹʥ֥ȤؤΥݥ - # - # @else - # @brief Removing PreFsmAction type listener - # - # This operation removes a specified listener. - # - # @param listener_type A listener type - # @param listener A pointer to a listener object - # - # @endif - # - def removePreFsmActionListener(self, listener_type, listener): - self._fsmActionListeners.preaction_[listener_type].removeListener(listener) - return - - - ## - # @if jp - # @brief PostFsmActionListener ꥹʤɲä - # - # FsmAction ؿθƤӽФľΥ٥Ȥ˴ϢƼ - # ʤꤹ롣 - # - # ǤꥹʤΥפȥХå٥Ȥϰʲ̤ - # - # - POST_ON_INITIALIZE: onInitialize ľ - # - POST_ON_FINALIZE: onFinalize ľ - # - POST_ON_STARTUP: onStartup ľ - # - POST_ON_SHUTDOWN: onShutdown ľ - # - POST_ON_ACTIVATED: onActivated ľ - # - POST_ON_DEACTIVATED: onDeactivated ľ - # - POST_ON_ABORTED: onAborted ľ - # - POST_ON_ERROR: onError ľ - # - POST_ON_RESET: onReset ľ - # - POST_ON_EXECUTE: onExecute ľ - # - POST_ON_STATE_UPDATE: onStateUpdate ľ - # - # ꥹʤ PostFsmActionListener ѾʲΥ˥ - # operator() Ƥɬפ롣 - # - # PostFsmActionListener::operator()(const char* state, ReturnCode_t ret) - # - # ǥեȤǤϡδؿͿꥹʥ֥Ȥνͭ - # RTObject˰ܤꡢRTObjectλ⤷ϡ - # removePostFsmActionListener() ˤ˼ưŪ˲Τ롣 - # ꥹʥ֥ȤνͭƤӽФ¦ǰݻϡ3 - # false ꤷưŪʲΤ뤳ȤǤ롣 - # - # @param listener_type ꥹʥ - # @param listener ꥹʥ֥ȤؤΥݥ - # @param autoclean ꥹʥ֥ȤμưŪΤԤɤΥե饰 - # - # @else - # @brief Adding PostFsmAction type listener - # - # This operation adds certain listeners related to FsmActions - # post events. - # The following listener types are available. - # - # - POST_ON_INITIALIZE: after onInitialize - # - POST_ON_FINALIZE: after onFinalize - # - POST_ON_STARTUP: after onStartup - # - POST_ON_SHUTDOWN: after onShutdown - # - POST_ON_ACTIVATED: after onActivated - # - POST_ON_DEACTIVATED: after onDeactivated - # - POST_ON_ABORTED: after onAborted - # - POST_ON_ERROR: after onError - # - POST_ON_RESET: after onReset - # - POST_ON_EXECUTE: after onExecute - # - POST_ON_STATE_UPDATE: after onStateUpdate - # - # Listeners should have the following function operator(). - # - # PostFsmActionListener::operator()(const char* state, ReturnCode_t ret) - # - # The ownership of the given listener object is transferred to - # this RTObject object in default. The given listener object will - # be destroied automatically in the RTObject's dtor or if the - # listener is deleted by removePostFsmActionListener() function. - # If you want to keep ownership of the listener object, give - # "false" value to 3rd argument to inhibit automatic destruction. - # - # @param listener_type A listener type - # @param listener A pointer to a listener object - # @param autoclean A flag for automatic listener destruction - # - # @endif - # - def addPostFsmActionListener(self, listener_type, - memfunc, autoclean = True): - class Noname(OpenRTM_aist.PostFsmActionListener): - def __init__(self, memfunc): - self._memfunc = memfunc + # inline void postOnAborting(UniqueId ec_id, ReturnCode_t ret) + + def postOnAborting(self, ec_id, ret): + self._actionListeners.notifyPostAction( + OpenRTM_aist.PostComponentActionListenerType.POST_ON_ABORTING, ec_id, ret) return - def __call__(self, state, ret): - self._memfunc(state, ret) + # inline void postOnError(UniqueId ec_id, ReturnCode_t ret) + + def postOnError(self, ec_id, ret): + self._actionListeners.notifyPostAction( + OpenRTM_aist.PostComponentActionListenerType.POST_ON_ERROR, ec_id, ret) return - listener = Noname(memfunc) - self._fsmActionListeners.postaction_[listener_type].addListener(listener, autoclean) - return listener - - - - ## - # @if jp - # @brief PostFsmActionListener ꥹʤ - # - # ꤷƼꥹʤ롣 - # - # @param listener_type ꥹʥ - # @param listener ꥹʥ֥ȤؤΥݥ - # - # @else - # @brief Removing PostFsmActionListener type listener - # - # This operation removes a specified listener. - # - # @param listener_type A listener type - # @param listener A pointer to a listener object - # - # @endif - # - def removePostFsmActionListener(self, listener_type, listener): - self._fsmActionListeners.postaction_[listener_type].removeListener(listener) - return - - - - ## - # @if jp - # @brief FsmProfileListener ꥹʤɲä - # - # FSMؤΥץեꡢޤFSMΤؤξ֤ܡ - # ٥Ȥɲú˥ХåƼꥹʤꤹ롣 - # - # ǤꥹʤΥפȥХå٥Ȥϰʲ̤ - # - # - SET_FSM_PROFILE : FSM Profile - # - GET_FSM_PROFILE : FSM Profile - # - ADD_FSM_STATE : FSMStateɲä줿 - # - REMOVE_FSM_STATE : FSMState줿 - # - ADD_FSM_TRANSITION : FSMܤɲä줿 - # - REMOVE_FSM_TRANSITION : FSMܤ줿 - # - BIND_FSM_EVENT : FSM˥٥ȤХɤ줿 - # - UNBIND_FSM_EVENT : FSM˥٥ȤХɤ줿 - # - # ꥹʤ FsmProfileListener ѾʲΥ˥ - # operator() Ƥɬפ롣 - # - # FsmProfileListener::operator()(RTC::FsmProfile& pprof) - # - # ǥեȤǤϡδؿͿꥹʥ֥Ȥνͭ - # RTObject˰ܤꡢRTObjectλ⤷ϡ - # removeFsmProfileListener() ˤ˼ưŪ˲Τ롣 - # ꥹʥ֥ȤνͭƤӽФ¦ǰݻϡ3 - # false ꤷưŪʲΤ뤳ȤǤ롣 - # - # @param listener_type ꥹʥ - # @param listener ꥹʥ֥ȤؤΥݥ - # @param autoclean ꥹʥ֥ȤμưŪΤԤɤΥե饰 - # - # @else - # @brief Adding FsmProfile type listener - # - # This operation adds certain listeners that is called when - # setting/getting FsmProfile and stae/transition/event add/remove - # to/from the FSM itself. - # - # The following listener types are available. - # - # - SET_FSM_PROFILE : Setting FSM Profile - # - GET_FSM_PROFILE : Getting FSM Profile - # - ADD_FSM_STATE : A State added to the FSM - # - REMOVE_FSM_STATE : A State removed from FSM - # - ADD_FSM_TRANSITION : A transition added to the FSM - # - REMOVE_FSM_TRANSITION : A transition removed from FSM - # - BIND_FSM_EVENT : An event bounded to the FSM - # - UNBIND_FSM_EVENT : An event unbounded to the FSM - # - # Listeners should have the following function operator(). - # - # FsmProfileListener::operator()(RTC::PortProfile pprof) - # - # The ownership of the given listener object is transferred to - # this RTObject object in default. The given listener object will - # be destroied automatically in the RTObject's dtor or if the - # listener is deleted by removeFsmProfileListener() function. - # If you want to keep ownership of the listener object, give - # "false" value to 3rd argument to inhibit automatic destruction. - # - # @param listener_type A listener type - # @param listener A pointer to a listener object - # @param autoclean A flag for automatic listener destruction - # - # @endif - # - def addFsmProfileListener(self, listener_type, - memfunc, autoclean = True): - class Noname(OpenRTM_aist.FsmProfileListener): - def __init__(self, memfunc): - self._memfunc = memfunc + # inline void postOnReset(UniqueId ec_id, ReturnCode_t ret) + + def postOnReset(self, ec_id, ret): + self._actionListeners.notifyPostAction( + OpenRTM_aist.PostComponentActionListenerType.POST_ON_RESET, ec_id, ret) return - def __call__(self, pprofile): - self._memfunc(pprofile) + # inline void postOnExecute(UniqueId ec_id, ReturnCode_t ret) + + def postOnExecute(self, ec_id, ret): + self._actionListeners.notifyPostAction( + OpenRTM_aist.PostComponentActionListenerType.POST_ON_EXECUTE, ec_id, ret) return - listener = Noname(memfunc) - self._fsmActionListeners.profile_[listener_type].addListener(listener, autoclean) - return listener - - - - ## - # @if jp - # @brief FsmProfileListener ꥹʤ - # - # ꤷƼꥹʤ롣 - # - # @param listener_type ꥹʥ - # @param listener ꥹʥ֥ȤؤΥݥ - # - # @else - # @brief Removing FsmProfileListener type listener - # - # This operation removes a specified listener. - # - # @param listener_type A listener type - # @param listener A pointer to a listener object - # - # @endif - # - def removeFsmProfileListener(self, listener_type, listener): - self._fsmActionListeners.profile_[listener_type].removeListener(listener) - return - - ## - # @if jp - # @brief FsmStructureListener ꥹʤɲä - # - # ExtendedFsmService ˴Ϣ FSM structure ꡦ˥ - # ХåƼꥹʤꤹ롣 - # - # ǤꥹʤΥפȥХå٥Ȥϰʲ̤ - # - # - SET_FSM_STRUCTURE: FSM¤ - # - GET_FSM_STRUCTURE: FSM¤μ - # - # ꥹʤ FsmStructureListener ѾʲΥ˥ - # operator() Ƥɬפ롣 - # - # FsmStructureListener::operator()(FsmStructure& structure) - # - # ǥեȤǤϡδؿͿꥹʥ֥Ȥνͭ - # RTObject˰ܤꡢRTObjectλ⤷ϡ - # removeFsmStructureListener() ˤ˼ưŪ˲Τ롣 - # ꥹʥ֥ȤνͭƤӽФ¦ǰݻϡ3 - # false ꤷưŪʲΤ뤳ȤǤ롣 - # - # @param listener_type ꥹʥ - # @param listener ꥹʥ֥ȤؤΥݥ - # @param autoclean ꥹʥ֥ȤμưŪΤԤɤΥե饰 - # - # @else - # @brief Adding FsmStructure type listener - # - # This operation adds certain listeners related to FSM structure - # data which are handled by ExtendedFsmService. - # - # The following listener types are available. - # - # - SET_FSM_STRUCTURE: Setting FSM structure - # - GET_FSM_STRUCTURE: Getting FSM structure - # - # Listeners should have the following function operator(). - # - # FsmStructureListener::operator()(RTC::FsmStructure structure) - # - # The ownership of the given listener object is transferred to - # this RTObject object in default. The given listener object will - # be destroied automatically in the RTObject's dtor or if the - # listener is deleted by removeFsmStructureListener() function. - # If you want to keep ownership of the listener object, give - # "false" value to 3rd argument to inhibit automatic destruction. - # - # @param listener_type A listener type - # @param listener A pointer to a listener object - # @param autoclean A flag for automatic listener destruction - # - # @endif - # - def addFsmStructureListener(self, listener_type, - memfunc, autoclean = True): - class Noname(OpenRTM_aist.FsmStructureListener): - def __init__(self, memfunc): - self._memfunc = memfunc + # inline void postOnStateUpdate(UniqueId ec_id, ReturnCode_t ret) + + def postOnStateUpdate(self, ec_id, ret): + self._actionListeners.notifyPostAction( + OpenRTM_aist.PostComponentActionListenerType.POST_ON_STATE_UPDATE, ec_id, ret) return - def __call__(self, pprofile): - self._memfunc(pprofile) + # inline void postOnRateChanged(UniqueId ec_id, ReturnCode_t ret) + + def postOnRateChanged(self, ec_id, ret): + self._actionListeners.notifyPostAction( + OpenRTM_aist.PostComponentActionListenerType.POST_ON_RATE_CHANGED, ec_id, ret) return - listener = Noname(memfunc) - self._fsmActionListeners.structure_[listener_type].addListener(listener, autoclean) - return listener - - - ## - # @if jp - # @brief FsmStructureListener ꥹʤ - # - # ꤷƼꥹʤ롣 - # - # @param listener_type ꥹʥ - # @param listener ꥹʥ֥ȤؤΥݥ - # - # @else - # @brief Removing FsmStructureListener type listener - # - # This operation removes a specified listener. - # - # @param listener_type A listener type - # @param listener A pointer to a listener object - # - # @endif - # - def removeFsmStructureListener(self, listener_type, listener): - self._fsmActionListeners.structure_[listener_type].removeListener(listener) - return - - - ## - # @if jp - # - # @brief RTC λ - # - # RTC νλ¹Ԥ롣 - # ݻƤ Port ϿȤȤˡ CORBA ֥ - # RTC λ롣 - # - # @param self - # - # @else - # - # @endif - def shutdown(self): - self._rtcout.RTC_TRACE("shutdown()") - try: - self.finalizePorts() - self.finalizeContexts() - self._poa.deactivate_object(self._poa.servant_to_id(self._SdoConfigImpl)) - self._poa.deactivate_object(self._poa.servant_to_id(self)) - self._sdoservice.exit() - if not CORBA.is_nil(self._insref): - poa = self._orb.resolve_initial_references("omniINSPOA") - poa.deactivate_object(poa.servant_to_id(self)) - except: - self._rtcout.RTC_ERROR(OpenRTM_aist.Logger.print_exception()) - - if self._manager: - self._rtcout.RTC_DEBUG("Cleanup on Manager") - self._manager.notifyFinalized(self) - - del self._actionListeners - del self._portconnListeners - - - return - - # inline void preOnInitialize(UniqueId ec_id) - def preOnInitialize(self, ec_id): - self._actionListeners.preaction_[OpenRTM_aist.PreComponentActionListenerType.PRE_ON_INITIALIZE].notify(ec_id) - return - - # inline void preOnFinalize(UniqueId ec_id) - def preOnFinalize(self, ec_id): - self._actionListeners.preaction_[OpenRTM_aist.PreComponentActionListenerType.PRE_ON_FINALIZE].notify(ec_id) - return - - # inline void preOnStartup(UniqueId ec_id) - def preOnStartup(self, ec_id): - self._actionListeners.preaction_[OpenRTM_aist.PreComponentActionListenerType.PRE_ON_STARTUP].notify(ec_id) - return - - # inline void preOnShutdown(UniqueId ec_id) - def preOnShutdown(self, ec_id): - self._actionListeners.preaction_[OpenRTM_aist.PreComponentActionListenerType.PRE_ON_SHUTDOWN].notify(ec_id) - return - - # inline void preOnActivated(UniqueId ec_id) - def preOnActivated(self, ec_id): - self._actionListeners.preaction_[OpenRTM_aist.PreComponentActionListenerType.PRE_ON_ACTIVATED].notify(ec_id) - return - - # inline void preOnDeactivated(UniqueId ec_id) - def preOnDeactivated(self, ec_id): - self._actionListeners.preaction_[OpenRTM_aist.PreComponentActionListenerType.PRE_ON_DEACTIVATED].notify(ec_id) - return - - # inline void preOnAborting(UniqueId ec_id) - def preOnAborting(self, ec_id): - self._actionListeners.preaction_[OpenRTM_aist.PreComponentActionListenerType.PRE_ON_ABORTING].notify(ec_id) - return - - # inline void preOnError(UniqueId ec_id) - def preOnError(self, ec_id): - self._actionListeners.preaction_[OpenRTM_aist.PreComponentActionListenerType.PRE_ON_ERROR].notify(ec_id) - return - - # inline void preOnReset(UniqueId ec_id) - def preOnReset(self, ec_id): - self._actionListeners.preaction_[OpenRTM_aist.PreComponentActionListenerType.PRE_ON_RESET].notify(ec_id) - return - - # inline void preOnExecute(UniqueId ec_id) - def preOnExecute(self, ec_id): - self._actionListeners.preaction_[OpenRTM_aist.PreComponentActionListenerType.PRE_ON_EXECUTE].notify(ec_id) - return - - # inline void preOnStateUpdate(UniqueId ec_id) - def preOnStateUpdate(self, ec_id): - self._actionListeners.preaction_[OpenRTM_aist.PreComponentActionListenerType.PRE_ON_STATE_UPDATE].notify(ec_id) - return - - - # inline void preOnRateChanged(UniqueId ec_id) - def preOnRateChanged(self, ec_id): - self._actionListeners.preaction_[OpenRTM_aist.PreComponentActionListenerType.PRE_ON_RATE_CHANGED].notify(ec_id) - return - - - # inline void postOnInitialize(UniqueId ec_id, ReturnCode_t ret) - def postOnInitialize(self, ec_id, ret): - self._actionListeners.postaction_[OpenRTM_aist.PostComponentActionListenerType.POST_ON_INITIALIZE].notify(ec_id, ret) - return - - - # inline void postOnFinalize(UniqueId ec_id, ReturnCode_t ret) - def postOnFinalize(self, ec_id, ret): - self._actionListeners.postaction_[OpenRTM_aist.PostComponentActionListenerType.POST_ON_FINALIZE].notify(ec_id, ret) - return - - - # inline void postOnStartup(UniqueId ec_id, ReturnCode_t ret) - def postOnStartup(self, ec_id, ret): - self._actionListeners.postaction_[OpenRTM_aist.PostComponentActionListenerType.POST_ON_STARTUP].notify(ec_id, ret) - return - - - # inline void postOnShutdown(UniqueId ec_id, ReturnCode_t ret) - def postOnShutdown(self, ec_id, ret): - self._actionListeners.postaction_[OpenRTM_aist.PostComponentActionListenerType.POST_ON_SHUTDOWN].notify(ec_id, ret) - return - - - # inline void postOnActivated(UniqueId ec_id, ReturnCode_t ret) - def postOnActivated(self, ec_id, ret): - self._actionListeners.postaction_[OpenRTM_aist.PostComponentActionListenerType.POST_ON_ACTIVATED].notify(ec_id, ret) - return - - - # inline void postOnDeactivated(UniqueId ec_id, ReturnCode_t ret) - def postOnDeactivated(self, ec_id, ret): - self._actionListeners.postaction_[OpenRTM_aist.PostComponentActionListenerType.POST_ON_DEACTIVATED].notify(ec_id, ret) - return - - - # inline void postOnAborting(UniqueId ec_id, ReturnCode_t ret) - def postOnAborting(self, ec_id, ret): - self._actionListeners.postaction_[OpenRTM_aist.PostComponentActionListenerType.POST_ON_ABORTING].notify(ec_id, ret) - return - - - # inline void postOnError(UniqueId ec_id, ReturnCode_t ret) - def postOnError(self, ec_id, ret): - self._actionListeners.postaction_[OpenRTM_aist.PostComponentActionListenerType.POST_ON_ERROR].notify(ec_id, ret) - return - - - # inline void postOnReset(UniqueId ec_id, ReturnCode_t ret) - def postOnReset(self, ec_id, ret): - self._actionListeners.postaction_[OpenRTM_aist.PostComponentActionListenerType.POST_ON_RESET].notify(ec_id, ret) - return - - - # inline void postOnExecute(UniqueId ec_id, ReturnCode_t ret) - def postOnExecute(self, ec_id, ret): - self._actionListeners.postaction_[OpenRTM_aist.PostComponentActionListenerType.POST_ON_EXECUTE].notify(ec_id, ret) - return - - - # inline void postOnStateUpdate(UniqueId ec_id, ReturnCode_t ret) - def postOnStateUpdate(self, ec_id, ret): - self._actionListeners.postaction_[OpenRTM_aist.PostComponentActionListenerType.POST_ON_STATE_UPDATE].notify(ec_id, ret) - return - - - # inline void postOnRateChanged(UniqueId ec_id, ReturnCode_t ret) - def postOnRateChanged(self, ec_id, ret): - self._actionListeners.postaction_[OpenRTM_aist.PostComponentActionListenerType.POST_ON_RATE_CHANGED].notify(ec_id, ret) - return - - - # inline void onAddPort(const PortProfile& pprof) - def onAddPort(self, pprof): - self._actionListeners.portaction_[OpenRTM_aist.PortActionListenerType.ADD_PORT].notify(pprof) - return - - - # inline void onRemovePort(const PortProfile& pprof) - def onRemovePort(self, pprof): - self._actionListeners.portaction_[OpenRTM_aist.PortActionListenerType.REMOVE_PORT].notify(pprof) - return - - - # inline void onAttachExecutionContext(UniqueId ec_id) - def onAttachExecutionContext(self, ec_id): - self._actionListeners.ecaction_[OpenRTM_aist.ExecutionContextActionListenerType.EC_ATTACHED].notify(ec_id) - return - - - # inline void onDetachExecutionContext(UniqueId ec_id) - def onDetachExecutionContext(self, ec_id): - self._actionListeners.ecaction_[OpenRTM_aist.ExecutionContextActionListenerType.EC_DETACHED].notify(ec_id) - return - - - - - def preOnFsmInit(self, state): - self._fsmActionListeners.preaction_[OpenRTM_aist.PreFsmActionListenerType.PRE_ON_INIT].notify(state) - return - def preOnFsmEntry(self, state): - self._fsmActionListeners.preaction_[OpenRTM_aist.PreFsmActionListenerType.PRE_ON_ENTRY].notify(state) - return - def preOnFsmDo(self, state): - self._fsmActionListeners.preaction_[OpenRTM_aist.PreFsmActionListenerType.PRE_ON_DO].notify(state) - return - def preOnFsmExit(self, state): - self._fsmActionListeners.preaction_[OpenRTM_aist.PreFsmActionListenerType.PRE_ON_EXIT].notify(state) - return - def preOnFsmStateChange(self, state): - self._fsmActionListeners.preaction_[OpenRTM_aist.PreFsmActionListenerType.PRE_ON_STATE_CHANGE].notify(state) - return - def postOnFsmInit(self, state, ret): - self._fsmActionListeners.postaction_[OpenRTM_aist.PostFsmActionListenerType.POST_ON_INIT].notify(state, ret) - return - def postOnFsmEntry(self, state, ret): - self._fsmActionListeners.postaction_[OpenRTM_aist.PostFsmActionListenerType.POST_ON_ENTRY].notify(state, ret) - return - def postOnFsmDo(self, state, ret): - self._fsmActionListeners.postaction_[OpenRTM_aist.PostFsmActionListenerType.POST_ON_DO].notify(state, ret) - return - def postOnFsmExit(self, state, ret): - self._fsmActionListeners.postaction_[OpenRTM_aist.PostFsmActionListenerType.POST_ON_EXIT].notify(state, ret) - return - def postOnFsmStateChange(self, state, ret): - self._fsmActionListeners.postaction_[OpenRTM_aist.PostFsmActionListenerType.POST_ON_STATE_CHANGE].notify(state, ret) - return - - - # ReturnCode_t getInheritedECOptions(coil::Properties& default_opts); - def getInheritedECOptions(self, default_opts): - inherited_opts_ = ["sync_transition", - "sync_activation", - "sync_deactivation", - "sync_reset", - "transition_timeout", - "activation_timeout", - "deactivation_timeout", - "reset_timeout", - "cpu_affinity"] - - p_ = self._properties.findNode("exec_cxt") - if not p_: - self._rtcout.RTC_WARN("No exec_cxt option found.") - return RTC.RTC_ERROR + # inline void onAddPort(const PortProfile& pprof) - self._rtcout.RTC_DEBUG("Copying inherited EC options.") - for opt_ in inherited_opts_: - if p_.findNode(opt_): - self._rtcout.RTC_PARANOID("Option %s exists.", opt_) - default_opts.setProperty(opt_, p_.getProperty(opt_)) - - return RTC.RTC_OK - - - ## - # @brief getting individual EC options from RTC's configuration file - # - # ReturnCode_t - # getPrivateContextOptions(std::vector& ec_args); - def getPrivateContextOptions(self, ec_args): - self._rtcout.RTC_TRACE("getPrivateContextOptions()") - # Component specific multiple EC option available - if not self._properties.findNode("execution_contexts"): - self._rtcout.RTC_DEBUG("No component specific EC specified.") - return RTC.RTC_ERROR + def onAddPort(self, pprof): + self._actionListeners.notifyPortAction(OpenRTM_aist.PortActionListenerType.ADD_PORT, pprof) + return - args_ = self._properties.getProperty("execution_contexts") - ecs_tmp_ = [s.strip() for s in args_.split(",")] - if not ecs_tmp_[0]: - return RTC.RTC_ERROR - self._rtcout.RTC_DEBUG("Component specific e EC option available,") - self._rtcout.RTC_DEBUG("%s", args_) - - default_opts_ = OpenRTM_aist.Properties() - self.getInheritedECOptions(default_opts_) - for ec_tmp in ecs_tmp_: - if OpenRTM_aist.normalize([ec_tmp]) == "none": - self._rtcout.RTC_INFO("EC none. EC will not be bound to the RTC.") - ec_args = [] - return RTC.RTC_OK - - type_and_name_ = [s.strip() for s in ec_tmp.split("(")] - if len(type_and_name_) > 2: - self._rtcout.RTC_DEBUG("Invalid EC type specified: %s", ec_tmp) - continue - - p_ = copy.deepcopy(default_opts_) - - - # create EC's properties - p_.setProperty("type",type_and_name_[0]) - self._rtcout.RTC_DEBUG("p_type: %s", p_.getProperty("type")) - p_type_ = self._properties.findNode("ec." + p_.getProperty("type")) - - if p_type_: - self._rtcout.RTC_DEBUG("p_type props:") - self._rtcout.RTC_DEBUG(p_type_) - p_.mergeProperties(p_type_) - - else: - self._rtcout.RTC_DEBUG("p_type none") - - # EC name specified - #self._rtcout.RTC_DEBUG("size: %d, name: %s", - # (len(type_and_name_), type_and_name_[1])) - - if len(type_and_name_) == 2 and type_and_name_[1][-1] == ')': - type_and_name_ = type_and_name_[1][:-1] - p_.setProperty("name", type_and_name_) - p_name_ = self._properties.findNode("ec." + p_.getProperty("name")) - - if p_name_: - self._rtcout.RTC_DEBUG("p_name props:") - self._rtcout.RTC_DEBUG(p_name_) - p_.mergeProperties(p_name_) + # inline void onRemovePort(const PortProfile& pprof) - else: - self._rtcout.RTC_DEBUG("p_name none") + def onRemovePort(self, pprof): + self._actionListeners.notifyPortAction(OpenRTM_aist.PortActionListenerType.REMOVE_PORT, pprof) + return - ec_args.append(p_) - self._rtcout.RTC_DEBUG("New EC properties stored:") - self._rtcout.RTC_DEBUG(p_) + # inline void onAttachExecutionContext(UniqueId ec_id) - return RTC.RTC_OK + def onAttachExecutionContext(self, ec_id): + self._actionListeners.notifyECAction(OpenRTM_aist.ExecutionContextActionListenerType.EC_ATTACHED, ec_id) + return + # inline void onDetachExecutionContext(UniqueId ec_id) - ## - # @brief getting global EC options from rtc.conf - # - # ReturnCode_t - # getGlobalContextOptions(coil::Properties& global_ec_props); - def getGlobalContextOptions(self, global_ec_props): - # exec_cxt option is obsolete - self._rtcout.RTC_TRACE("getGlobalContextOptions()") + def onDetachExecutionContext(self, ec_id): + self._actionListeners.notifyECAction(OpenRTM_aist.ExecutionContextActionListenerType.EC_DETACHED, ec_id) + return - prop_ = self._properties.findNode("exec_cxt.periodic") - if not prop_: - self._rtcout.RTC_WARN("No global EC options found.") - return RTC.RTC_ERROR + def preOnFsmInit(self, state): + self._fsmActionListeners.notifyPreAction(OpenRTM_aist.PreFsmActionListenerType.PRE_ON_INIT, state) + return - self._rtcout.RTC_DEBUG("Global EC options are specified.") - self._rtcout.RTC_DEBUG(prop_) - self.getInheritedECOptions(global_ec_props) - global_ec_props.mergeProperties(prop_) - return RTC.RTC_OK - - - ## - # @brief getting EC options - # - # ReturnCode_t - # getContextOptions(std::vector& ec_args); - def getContextOptions(self, ec_args): - self._rtcout.RTC_DEBUG("getContextOptions()") - global_props_ = OpenRTM_aist.Properties() - ret_global_ = self.getGlobalContextOptions(global_props_) - ret_private_ = self.getPrivateContextOptions(ec_args) - - # private(X), global(X) -> error - # private(O), global(O) -> private - # private(X), global(O) -> global - # private(O), global(X) -> private - if ret_global_ != RTC.RTC_OK and ret_private_ != RTC.RTC_OK: - return RTC.RTC_ERROR + def preOnFsmEntry(self, state): + self._fsmActionListeners.notifyPreAction(OpenRTM_aist.PreFsmActionListenerType.PRE_ON_ENTRY, state) + return - if ret_global_ == RTC.RTC_OK and ret_private_ != RTC.RTC_OK: - ec_args.append(global_props_) + def preOnFsmDo(self, state): + self._fsmActionListeners.notifyPreAction(OpenRTM_aist.PreFsmActionListenerType.PRE_ON_DO, state) + return - return RTC.RTC_OK + def preOnFsmExit(self, state): + self._fsmActionListeners.notifyPreAction(OpenRTM_aist.PreFsmActionListenerType.PRE_ON_EXIT, state) + return + def preOnFsmStateChange(self, state): + self._fsmActionListeners.notifyPreAction(OpenRTM_aist.PreFsmActionListenerType.PRE_ON_STATE_CHANGE, state) + return - ## - # @brief fiding existing EC from the factory - # - # ReturnCode_t findExistingEC(coil::Properties& ec_arg, - # RTC::ExecutionContextBase*& ec); - def findExistingEC(self, ec_arg, ec): - eclist_ = OpenRTM_aist.ExecutionContextFactory.instance().createdObjects() - for ec_ in eclist_: - if ec_.getProperties().getProperty("type") == ec_arg.getProperty("type") and \ - ec_.getProperties().getProperty("name") == ec_arg.getProperty("name"): - ec[0] = ec_ - return RTC.RTC_OK + def postOnFsmInit(self, state, ret): + self._fsmActionListeners.notifyPostAction( + OpenRTM_aist.PostFsmActionListenerType.POST_ON_INIT, state, ret) + return - return RTC.RTC_ERROR - - - ## - # @brief creating, initializing and binding context - # - # ReturnCode_t createContexts(std::vector& ec_args); - def createContexts(self, ec_args): - ret_ = RTC.RTC_OK - avail_ec_ = OpenRTM_aist.ExecutionContextFactory.instance().getIdentifiers() - - for ec_arg_ in ec_args: - ec_type_ = ec_arg_.getProperty("type") - ec_name_ = ec_arg_.getProperty("name") - ec_ = [None] - if ec_name_ and self.findExistingEC(ec_arg_, ec_) == RTC.RTC_OK: - # if EC's name exists, find existing EC in the factory. - self._rtcout.RTC_DEBUG("EC: type=%s, name=%s already exists.", - (ec_type_, ec_name_)) - else: - # If EC's name is empty or no existing EC, create new EC. - if not ec_type_ in avail_ec_: - self._rtcout.RTC_WARN("EC %s is not available.", ec_type_) - self._rtcout.RTC_DEBUG("Available ECs: %s", - OpenRTM_aist.flatten(avail_ec_)) - continue - ec_[0] = OpenRTM_aist.ExecutionContextFactory.instance().createObject(ec_type_) - - if not ec_[0]: - # EC factory available but creation failed. Resource full? - self._rtcout.RTC_ERROR("EC (%s) creation failed.", ec_type_) - self._rtcout.RTC_DEBUG("Available EC list: %s", - OpenRTM_aist.flatten(avail_ec_)) - ret_ = RTC.RTC_ERROR - continue - - self._rtcout.RTC_DEBUG("EC (%s) created.", ec_type_) - - ec_[0].init(ec_arg_) - self._eclist.append(ec_[0]) - ec_[0].bindComponent(self) - - if len(self._eclist) == 0: - default_prop = OpenRTM_aist.Properties() - default_prop.setDefaults(OpenRTM_aist.default_config) - - ec_ = [None] - ec_type_ = default_prop.getProperty("exec_cxt.periodic.type") - if not ec_type_ in avail_ec_: - self._rtcout.RTC_WARN("EC %s is not available.", ec_type_) - self._rtcout.RTC_DEBUG("Available ECs: %s", - OpenRTM_aist.flatten(avail_ec_)) - return RTC.RTC_ERROR - - - - default_opts = OpenRTM_aist.Properties() - prop_ = default_prop.findNode("exec_cxt.periodic") - #if not prop_: - # self._rtcout.RTC_WARN("No default EC options found.") - # return RTC.RTC_ERROR - - default_opts.mergeProperties(prop_) - - inherited_opts_ = ["sync_transition", - "sync_activation", - "sync_deactivation", - "sync_reset", - "transition_timeout", - "activation_timeout", - "deactivation_timeout", - "reset_timeout", - "cpu_affinity"] - - p_ = self._properties.findNode("exec_cxt") - - if not p_: - self._rtcout.RTC_WARN("No exec_cxt option found.") - return RTC.RTC_ERROR - - self._rtcout.RTC_DEBUG("Copying inherited EC options.") - for opt_ in inherited_opts_: - if p_.findNode(opt_): - self._rtcout.RTC_PARANOID("Option %s exists.", opt_) - default_opts.setProperty(opt_, p_.getProperty(opt_)) - - - ec_[0] = OpenRTM_aist.ExecutionContextFactory.instance().createObject(ec_type_) - #if not ec_[0]: - # self._rtcout.RTC_ERROR("EC (%s) creation failed.", ec_type_) - # self._rtcout.RTC_DEBUG("Available EC list: %s", - # OpenRTM_aist.flatten(avail_ec_)) - # return RTC.RTC_ERROR - - ec_[0].init(default_opts) - self._eclist.append(ec_[0]) - ec_[0].bindComponent(self) - - - - - return ret_ - - - def getInPorts(self): - return self._inports - def getOutPorts(self): - return self._outports - - - ## - # @brief omniINSPOA֥ȤϿ - # - # @param self - # @param obj - def setINSObjRef(self, obj): - self._insref = obj - - - - ## - # @if jp - # @class svc_name - # @brief SDOService ΥץեꥹȤidǥ뤿 - # ե󥯥饹 - # @else - # - # @endif - class svc_name: - def __init__(self, _id): - self._id= _id - - def __call__(self, prof): - return self._id == prof.id - - - #------------------------------------------------------------ - # Functor - #------------------------------------------------------------ - - ## - # @if jp - # @class nv_name - # @brief NVList ѥե󥯥 - # @else - # - # @endif - class nv_name: - def __init__(self, _name): - self._name = _name - - def __call__(self, nv): - return self._name == nv.name - - - ## - # @if jp - # @class ec_find - # @brief ExecutionContext ѥե󥯥 - # @else - # - # @endif - class ec_find: - def __init__(self, _ec): - self._ec = _ec - - def __call__(self, ecs): - try: - if not CORBA.is_nil(ecs): - ec = ecs._narrow(RTC.ExecutionContext) - return self._ec._is_equivalent(ec) - except: - print(OpenRTM_aist.Logger.print_exception()) - return False + def postOnFsmEntry(self, state, ret): + self._fsmActionListeners.notifyPostAction( + OpenRTM_aist.PostFsmActionListenerType.POST_ON_ENTRY, state, ret) + return + + def postOnFsmDo(self, state, ret): + self._fsmActionListeners.notifyPostAction(OpenRTM_aist.PostFsmActionListenerType.POST_ON_DO, state, ret) + return - return False - - - ## - # @if jp - # @class ec_copy - # @brief ExecutionContext Copyѥե󥯥 - # @else - # - # @endif - class ec_copy: - def __init__(self, eclist): - self._eclist = eclist - - def __call__(self, ecs): - if not CORBA.is_nil(ecs): - self._eclist.append(ecs) - - - ## - # @if jp - # @class deactivate_comps - # @brief RTC ѥե󥯥 - # @else - # - # @endif - class deactivate_comps: - def __init__(self, comp): - self._comp = comp - - def __call__(self, ec): - try: - if not CORBA.is_nil(ec) and not ec._non_existent(): - ec.deactivate_component(self._comp) - ec.stop() - except: - print(OpenRTM_aist.Logger.print_exception()) + def postOnFsmExit(self, state, ret): + self._fsmActionListeners.notifyPostAction( + OpenRTM_aist.PostFsmActionListenerType.POST_ON_EXIT, state, ret) + return + + def postOnFsmStateChange(self, state, ret): + self._fsmActionListeners.notifyPostAction( + OpenRTM_aist.PostFsmActionListenerType.POST_ON_STATE_CHANGE, state, ret) + return + + # ReturnCode_t getInheritedECOptions(coil::Properties& default_opts); + + def getInheritedECOptions(self, default_opts): + inherited_opts_ = ["sync_transition", + "sync_activation", + "sync_deactivation", + "sync_reset", + "transition_timeout", + "activation_timeout", + "deactivation_timeout", + "reset_timeout", + "cpu_affinity"] + + p_ = self._properties.findNode("exec_cxt") + if not p_: + self._rtcout.RTC_WARN("No exec_cxt option found.") + return RTC.RTC_ERROR + + self._rtcout.RTC_DEBUG("Copying inherited EC options.") + for opt_ in inherited_opts_: + if p_.findNode(opt_): + self._rtcout.RTC_PARANOID("Option %s exists.", opt_) + default_opts.setProperty(opt_, p_.getProperty(opt_)) + + return RTC.RTC_OK + + ## + # @brief getting individual EC options from RTC's configuration file + # + # ReturnCode_t + # getPrivateContextOptions(std::vector& ec_args); + + def getPrivateContextOptions(self, ec_args): + self._rtcout.RTC_TRACE("getPrivateContextOptions()") + # Component specific multiple EC option available + if not self._properties.findNode("execution_contexts"): + self._rtcout.RTC_DEBUG("No component specific EC specified.") + return RTC.RTC_ERROR, ec_args + + args_ = self._properties.getProperty("execution_contexts") + ecs_tmp_ = [s.strip() for s in args_.split(",")] + if not ecs_tmp_[0]: + return RTC.RTC_ERROR, ec_args + self._rtcout.RTC_DEBUG("Component specific e EC option available,") + self._rtcout.RTC_DEBUG("%s", args_) + + default_opts_ = OpenRTM_aist.Properties() + self.getInheritedECOptions(default_opts_) + for ec_tmp in ecs_tmp_: + if OpenRTM_aist.normalize(ec_tmp) == "none": + self._rtcout.RTC_INFO( + "EC none. EC will not be bound to the RTC.") + ec_args = [] + return RTC.RTC_OK, ec_args + + type_and_name_ = [s.strip() for s in ec_tmp.split("(")] + if len(type_and_name_) > 2: + self._rtcout.RTC_DEBUG("Invalid EC type specified: %s", ec_tmp) + continue + + p_ = copy.deepcopy(default_opts_) + + # create EC's properties + p_.setProperty("type", type_and_name_[0]) + self._rtcout.RTC_DEBUG("p_type: %s", p_.getProperty("type")) + p_type_ = self._properties.findNode("ec." + p_.getProperty("type")) + + if p_type_: + self._rtcout.RTC_DEBUG("p_type props:") + self._rtcout.RTC_DEBUG(p_type_) + p_.mergeProperties(p_type_) + + else: + self._rtcout.RTC_DEBUG("p_type none") + + # EC name specified + # self._rtcout.RTC_DEBUG("size: %d, name: %s", + # (len(type_and_name_), type_and_name_[1])) + + if len(type_and_name_) == 2 and type_and_name_[1][-1] == ')': + type_and_name_ = type_and_name_[1][:-1] + p_.setProperty("name", type_and_name_) + p_name_ = self._properties.findNode( + "ec." + p_.getProperty("name")) + + if p_name_: + self._rtcout.RTC_DEBUG("p_name props:") + self._rtcout.RTC_DEBUG(p_name_) + p_.mergeProperties(p_name_) + + else: + self._rtcout.RTC_DEBUG("p_name none") + + ec_args.append(p_) + self._rtcout.RTC_DEBUG("New EC properties stored:") + self._rtcout.RTC_DEBUG(p_) + + return RTC.RTC_OK, ec_args + + ## + # @brief getting global EC options from rtc.conf + # + # ReturnCode_t + # getGlobalContextOptions(coil::Properties& global_ec_props); + + def getGlobalContextOptions(self, global_ec_props): + # exec_cxt option is obsolete + self._rtcout.RTC_TRACE("getGlobalContextOptions()") + + prop_ = self._properties.findNode("exec_cxt.periodic") + if not prop_: + self._rtcout.RTC_WARN("No global EC options found.") + return RTC.RTC_ERROR, global_ec_props + + self._rtcout.RTC_DEBUG("Global EC options are specified.") + self._rtcout.RTC_DEBUG(prop_) + self.getInheritedECOptions(global_ec_props) + global_ec_props.mergeProperties(prop_) + return RTC.RTC_OK, global_ec_props + + ## + # @brief getting EC options + # + # ReturnCode_t + # getContextOptions(std::vector& ec_args); + + def getContextOptions(self, ec_args): + self._rtcout.RTC_DEBUG("getContextOptions()") + global_props_ = OpenRTM_aist.Properties() + ret_global_, global_props_ = self.getGlobalContextOptions(global_props_) + ret_private_, ec_args = self.getPrivateContextOptions(ec_args) + + # private(X), global(X) -> error + # private(O), global(O) -> private + # private(X), global(O) -> global + # private(O), global(X) -> private + if ret_global_ != RTC.RTC_OK and ret_private_ != RTC.RTC_OK: + return RTC.RTC_ERROR, ec_args + + if ret_global_ == RTC.RTC_OK and ret_private_ != RTC.RTC_OK: + ec_args.append(global_props_) + + return RTC.RTC_OK, ec_args + + ## + # @brief fiding existing EC from the factory + # + # ReturnCode_t findExistingEC(coil::Properties& ec_arg, + # RTC::ExecutionContextBase*& ec); + + def findExistingEC(self, ec_arg): + if self._manager: + eclist_ = self._manager.createdExecutionContexts() + for ec in eclist_: + if ec.getProperties().getProperty("type") == ec_arg.getProperty("type") and \ + ec.getProperties().getProperty("name") == ec_arg.getProperty("name"): + return RTC.RTC_OK, ec + + return RTC.RTC_ERROR, None + + ## + # @brief creating, initializing and binding context + # + # ReturnCode_t createContexts(std::vector& ec_args); + + def createContexts(self, ec_args): + ret_ = RTC.RTC_OK + avail_ec_ = OpenRTM_aist.ExecutionContextFactory.instance().getIdentifiers() + + for ec_arg_ in ec_args: + ec_type_ = ec_arg_.getProperty("type") + ec_name_ = ec_arg_.getProperty("name") + ret, ec = self.findExistingEC(ec_arg_) + if ec_name_ and ret == RTC.RTC_OK: + # if EC's name exists, find existing EC in the factory. + self._rtcout.RTC_DEBUG("EC: type=%s, name=%s already exists.", + (ec_type_, ec_name_)) + else: + # If EC's name is empty or no existing EC, create new EC. + if not ec_type_ in avail_ec_: + self._rtcout.RTC_WARN("EC %s is not available.", ec_type_) + self._rtcout.RTC_DEBUG("Available ECs: %s", + OpenRTM_aist.flatten(avail_ec_)) + continue + ec = OpenRTM_aist.ExecutionContextFactory.instance( + ).createObject(ec_type_) + + if not ec: + # EC factory available but creation failed. Resource full? + self._rtcout.RTC_ERROR("EC (%s) creation failed.", ec_type_) + self._rtcout.RTC_DEBUG("Available EC list: %s", + OpenRTM_aist.flatten(avail_ec_)) + ret_ = RTC.RTC_ERROR + continue + + if self._manager: + self._manager.addExecutionContext(ec) + + self._rtcout.RTC_DEBUG("EC (%s) created.", ec_type_) + + ec.init(ec_arg_) + self._eclist.append(ec) + ec.bindComponent(self) + + if not self._eclist: + default_prop = OpenRTM_aist.Properties() + default_prop.setDefaults(OpenRTM_aist.default_config) + + ec_type_ = default_prop.getProperty("exec_cxt.periodic.type") + if not ec_type_ in avail_ec_: + self._rtcout.RTC_WARN("EC %s is not available.", ec_type_) + self._rtcout.RTC_DEBUG("Available ECs: %s", + OpenRTM_aist.flatten(avail_ec_)) + return RTC.RTC_ERROR + + default_opts = OpenRTM_aist.Properties() + prop_ = default_prop.findNode("exec_cxt.periodic") + # if not prop_: + # self._rtcout.RTC_WARN("No default EC options found.") + # return RTC.RTC_ERROR + + default_opts.mergeProperties(prop_) + + inherited_opts_ = ["sync_transition", + "sync_activation", + "sync_deactivation", + "sync_reset", + "transition_timeout", + "activation_timeout", + "deactivation_timeout", + "reset_timeout", + "cpu_affinity"] + + p_ = self._properties.findNode("exec_cxt") + + if not p_: + self._rtcout.RTC_WARN("No exec_cxt option found.") + return RTC.RTC_ERROR + + self._rtcout.RTC_DEBUG("Copying inherited EC options.") + for opt_ in inherited_opts_: + if p_.findNode(opt_): + self._rtcout.RTC_PARANOID("Option %s exists.", opt_) + default_opts.setProperty(opt_, p_.getProperty(opt_)) + + ec = OpenRTM_aist.ExecutionContextFactory.instance( + ).createObject(ec_type_) + + if not ec: + self._rtcout.RTC_ERROR("EC (%s) creation failed.", ec_type_) + self._rtcout.RTC_DEBUG("Available EC list: %s", + OpenRTM_aist.flatten(avail_ec_)) + return RTC.RTC_ERROR + + if self._manager: + self._manager.addExecutionContext(ec) + + ec.init(default_opts) + self._eclist.append(ec) + ec.bindComponent(self) + + return ret_ + + def getInPorts(self): + return self._inports + + def getOutPorts(self): + return self._outports + + ## + # @brief omniINSPOAから取得したオブジェクトを登録 + # + # @param self + # @param obj + + def setINSObjRef(self, obj): + self._insref = obj + + ## + # @if jp + # @class svc_name + # @brief SDOService のプロファイルリストからidでサーチするための + # ファンクタクラス + # @else + # + # @endif + + class svc_name: + def __init__(self, _id): + self._id = _id + + def __call__(self, prof): + return self._id == prof.id + + # ------------------------------------------------------------ + # Functor + # ------------------------------------------------------------ + + ## + # @if jp + # @class nv_name + # @brief NVList 検索用ファンクタ + # @else + # + # @endif + + class nv_name: + def __init__(self, _name): + self._name = _name + + def __call__(self, nv): + return self._name == nv.name + + ## + # @if jp + # @class ec_find + # @brief ExecutionContext 検索用ファンクタ + # @else + # + # @endif + + class ec_find: + def __init__(self, _ec): + self._ec = _ec + + def __call__(self, ecs): + try: + if not CORBA.is_nil(ecs): + ec = ecs._narrow(RTC.ExecutionContext) + return self._ec._is_equivalent(ec) + except BaseException: + print(OpenRTM_aist.Logger.print_exception()) + return False + + return False + + ## + # @if jp + # @class ec_copy + # @brief ExecutionContext Copy用ファンクタ + # @else + # + # @endif + + class ec_copy: + def __init__(self, eclist): + self._eclist = eclist + + def __call__(self, ecs): + if not CORBA.is_nil(ecs): + self._eclist.append(ecs) + + ## + # @if jp + # @class deactivate_comps + # @brief RTC 非活性化用ファンクタ + # @else + # + # @endif + + class deactivate_comps: + def __init__(self, comp): + self._comp = comp + + def __call__(self, ec): + try: + if not CORBA.is_nil(ec) and not ec._non_existent(): + if ec.get_component_state(self._comp) == RTC.ACTIVE_STATE: + ec.deactivate_component(self._comp) + elif ec.get_component_state(self._comp) == RTC.ERROR_STATE: + ec.reset_component(self._comp) + except BaseException: + print(OpenRTM_aist.Logger.print_exception()) # RtcBase = RTObject_impl @@ -5445,7 +5431,7 @@ def __call__(self, ec): ec.bindComponent(self) # at least one EC must be attached - if len(self._ecMine) == 0: + if not self._ecMine: return RTC.PRECONDITION_NOT_MET ret = self.on_initialize() @@ -5454,11 +5440,10 @@ def __call__(self, ec): return ret # -- entering alive state -- - for i in range(len(self._ecMine)): + for i, ec in enumerate(self._ecMine): self._rtcout.RTC_DEBUG("EC[%d] starting.", i) - self._ecMine[i].start() + ec.start() # ret must be RTC_OK return ret """ - diff --git a/OpenRTM_aist/RTObjectBase.py b/OpenRTM_aist/RTObjectBase.py index 63a9c983..70d5aa69 100644 --- a/OpenRTM_aist/RTObjectBase.py +++ b/OpenRTM_aist/RTObjectBase.py @@ -1,5 +1,5 @@ #!/usr/bin/env python -# -*- coding: euc-jp -*- +# -*- coding: utf-8 -*- ## # @file RTObjectBase.py @@ -15,9 +15,6 @@ # All rights reserved. - - - import copy from omniORB import any @@ -31,34 +28,33 @@ ECOTHER_OFFSET = 1000 default_conf = [ - "implementation_id","", - "type_name", "", - "description", "", - "version", "", - "vendor", "", - "category", "", - "activity_type", "", - "max_instance", "", - "language", "", - "lang_type", "", - "conf", "", - "" ] - + "implementation_id", "", + "type_name", "", + "description", "", + "version", "", + "vendor", "", + "category", "", + "activity_type", "", + "max_instance", "", + "language", "", + "lang_type", "", + "conf", "", + ""] ## # @if jp -# @brief RTݡͥȥ饹 +# @brief RTコンポーネントクラス # -# RTݡͥȤΥ١Ȥʤ륯饹 -# Robotic Technology Component lightweightRTComponentμ饹 -# ݡͥȤεǽ󶡤 ComponentAction 󥿡ե -# ݡͥȤΥ饤եԤ LightweightRTObject μ -# 󶡤롣 -# ºݤ˥桼ݡͥȤˤϡExecution Semantics б -# ƥ֥饹Ѥ롣
    -# (μǤ Periodic Sampled Data Processing ΤߥݡȤƤ뤿ᡢ -# dataFlowComponent ľܷѾƤ) +# 各RTコンポーネントのベースとなるクラス。 +# Robotic Technology Component 仕様中の lightweightRTComponentの実装クラス。 +# コンポーネントの機能を提供する ComponentAction インターフェースと +# コンポーネントのライフサイクル管理を行うための LightweightRTObject の実装を +# 提供する。 +# 実際にユーザがコンポーネントを作成する場合には、Execution Semantics に対応 +# した各サブクラスを利用する。
    +# (現状の実装では Periodic Sampled Data Processing のみサポートしているため、 +# dataFlowComponent を直接継承している) # # @since 0.2.0 # @@ -66,5289 +62,5272 @@ # # @endif class RTObjectBase: - """ - """ - - ## - # @if jp - # @brief 󥹥ȥ饯 - # - # 󥹥ȥ饯 - # - # @param self - # @param manager ޥ͡㥪֥(ǥե:None) - # @param orb ORB(ǥե:None) - # @param poa POA(ǥե:None) - # - # @else - # - # @brief Consructor - # - # @param orb ORB - # @param poa POA - # - # @endif - def __init__(self, manager=None, orb=None, poa=None): - if manager: - self._manager = manager - self._orb = self._manager.getORB() - self._poa = self._manager.getPOA() - self._portAdmin = OpenRTM_aist.PortAdmin(self._manager.getORB(),self._manager.getPOA()) - else: - self._manager = None - self._orb = orb - self._poa = poa - self._portAdmin = OpenRTM_aist.PortAdmin(self._orb,self._poa) - - if self._manager: - self._rtcout = self._manager.getLogbuf("rtobject") - else: - self._rtcout = OpenRTM_aist.Manager.instance().getLogbuf("rtobject") - - self._created = True - self._properties = OpenRTM_aist.Properties(defaults_str=default_conf) - self._configsets = OpenRTM_aist.ConfigAdmin(self._properties.getNode("conf")) - self._profile = RTC.ComponentProfile("","","","","","",[],None,[]) - - self._sdoservice = OpenRTM_aist.SdoServiceAdmin(self) - self._SdoConfigImpl = OpenRTM_aist.Configuration_impl(self._configsets,self._sdoservice) - self._SdoConfig = self._SdoConfigImpl.getObjRef() - self._execContexts = [] - self._objref = self._this() - self._sdoOwnedOrganizations = [] #SDOPackage.OrganizationList() - self._sdoSvcProfiles = [] #SDOPackage.ServiceProfileList() - self._sdoOrganizations = [] #SDOPackage.OrganizationList() - self._sdoStatus = [] #SDOPackage.NVList() - self._ecMine = [] - self._ecOther = [] - self._eclist = [] - self._exiting = False - self._readAll = False - self._writeAll = False - self._readAllCompletion = False - self._writeAllCompletion = False - self._inports = [] - self._outports = [] - self._actionListeners = OpenRTM_aist.ComponentActionListeners() - self._portconnListeners = OpenRTM_aist.PortConnectListeners() - self._fsmActionListeners = OpenRTM_aist.FsmActionListeners() - return - - - ## - # @if jp - # - # @brief ǥȥ饯 - # - # @param self - # - # @else - # - # @brief destructor - # - # @endif - def __del__(self): - return - - - #============================================================ - # Overridden functions - #============================================================ - - ## - # @if jp - # - # @brief ѥХåؿ - # - # ComponentAction::on_initialize ƤФ줿ݤ˼¹Ԥ륳Хå - # ؿ
    - # ܴؿ̵ RTC::RTC_OK ֤褦˥ߡƤΤǡ - # ƥݡͥȤμºݤνϡܴؿ򥪡С饤ɤƼ - # ɬפ롣 - # - # @param self - # - # @return ReturnCode_t Υ꥿󥳡 - # - # @else - # - # @endif - def onInitialize(self): - self._rtcout.RTC_TRACE("onInitialize()") - return RTC.RTC_OK - - - ## - # @if jp - # - # @brief λѥХåؿ - # - # ComponentAction::on_finalize ƤФ줿ݤ˼¹Ԥ륳Хå - # ؿ
    - # ܴؿ̵ RTC::RTC_OK ֤褦˥ߡƤΤǡ - # ƥݡͥȤμºݤνλϡܴؿ򥪡С饤ɤƼ - # ɬפ롣 - # - # @param self - # - # @return ReturnCode_t Υ꥿󥳡 - # - # @else - # - # @endif - def onFinalize(self): - self._rtcout.RTC_TRACE("onFinalize()") - return RTC.RTC_OK - - - ## - # @if jp - # - # @brief ϽѥХåؿ - # - # ComponentAction::on_startup ƤФ줿ݤ˼¹Ԥ륳Хå - # ؿ
    - # ܴؿ̵ RTC::RTC_OK ֤褦˥ߡƤΤǡ - # ƥݡͥȤμºݤγϽϡܴؿ򥪡С饤ɤƼ - # ɬפ롣 - # - # @param self - # @param ec_id äƤ ExecutionContext ID - # - # @return ReturnCode_t Υ꥿󥳡 - # - # @else - # - # @endif - def onStartup(self, ec_id): - self._rtcout.RTC_TRACE("onStartup(%d)",ec_id) - return RTC.RTC_OK - - - ## - # @if jp - # - # @brief ߽ѥХåؿ - # - # ComponentAction::on_shutdown ƤФ줿ݤ˼¹Ԥ륳Хå - # ؿ
    - # ܴؿ̵ RTC::RTC_OK ֤褦˥ߡƤΤǡ - # ƥݡͥȤμºݤ߽ϡܴؿ򥪡С饤ɤƼ - # ɬפ롣 - # - # @param self - # @param ec_id äƤ ExecutionContext ID - # - # @return ReturnCode_t Υ꥿󥳡 - # - # @else - # - # @endif - def onShutdown(self, ec_id): - self._rtcout.RTC_TRACE("onShutdown(%d)",ec_id) - return RTC.RTC_OK - - - ## - # @if jp - # - # @brief ѥХåؿ - # - # ComponentAction::on_activated ƤФ줿ݤ˼¹Ԥ륳Хå - # ؿ
    - # ܴؿ̵ RTC::RTC_OK ֤褦˥ߡƤΤǡ - # ƥݡͥȤμºݤγϡܴؿ򥪡С饤ɤƼ - # ɬפ롣 - # - # @param self - # @param ec_id äƤ ExecutionContext ID - # - # @return ReturnCode_t Υ꥿󥳡 - # - # @else - # - # @endif - def onActivated(self, ec_id): - self._rtcout.RTC_TRACE("onActivated(%d)",ec_id) - return RTC.RTC_OK - - - ## - # @if jp - # - # @brief ѥХåؿ - # - # ComponentAction::on_deactivated ƤФ줿ݤ˼¹Ԥ륳Хå - # ؿ
    - # ܴؿ̵ RTC::RTC_OK ֤褦˥ߡƤΤǡ - # ƥݡͥȤμºݤϡܴؿ򥪡С饤ɤƼ - # ɬפ롣 - # - # @param self - # @param ec_id äƤ ExecutionContext ID - # - # @return ReturnCode_t Υ꥿󥳡 - # - # @else - # - # @endif - def onDeactivated(self, ec_id): - self._rtcout.RTC_TRACE("onDeactivated(%d)",ec_id) - return RTC.RTC_OK - - - ## - # @if jp - # - # @brief ѥХåؿ - # - # DataFlowComponentAction::on_execute ƤФ줿ݤ˼¹Ԥ - # Хåؿ
    - # ܴؿ̵ RTC::RTC_OK ֤褦˥ߡƤΤǡ - # ƥݡͥȤμºݤμϡܴؿ򥪡С饤ɤƼ - # ɬפ롣
    - # ܴؿ Periodic Sampled Data Processing ˤ Two-Pass Execution - # ܤμ¹ԥѥȤŪ˸ƤӽФ롣 - # - # @param self - # @param ec_id äƤ ExecutionContext ID - # - # @return ReturnCode_t Υ꥿󥳡 - # - # @else - # - # @endif - def onExecute(self, ec_id): - self._rtcout.RTC_TRACE("onExecute(%d)",ec_id) - return RTC.RTC_OK - - - ## - # @if jp - # - # @brief ǽѥХåؿ - # - # ComponentAction::on_aborting ƤФ줿ݤ˼¹Ԥ륳Хå - # ؿ
    - # ܴؿ̵ RTC::RTC_OK ֤褦˥ߡƤΤǡ - # ƥݡͥȤμºݤǽϡܴؿ򥪡С饤ɤƼ - # ɬפ롣 - # - # @param self - # @param ec_id äƤ ExecutionContext ID - # - # @return ReturnCode_t Υ꥿󥳡 - # - # @else - # - # @endif - def onAborting(self, ec_id): - self._rtcout.RTC_TRACE("onAborting(%d)",ec_id) - return RTC.RTC_OK - - - ## - # @if jp - # - # @brief 顼ѥХåؿ - # - # ComponentAction::on_error ƤФ줿ݤ˼¹Ԥ륳Хåؿ
    - # ܴؿ̵ RTC::RTC_OK ֤褦˥ߡƤΤǡ - # ƥݡͥȤμºݤΥ顼ϡܴؿ򥪡С饤ɤƼ - # ɬפ롣 - # - # @param self - # @param ec_id äƤ ExecutionContext ID - # - # @return ReturnCode_t Υ꥿󥳡 - # - # @else - # - # @endif - def onError(self, ec_id): - self._rtcout.RTC_TRACE("onError(%d)",ec_id) - return RTC.RTC_OK - - - ## - # @if jp - # - # @brief ꥻåȽѥХåؿ - # - # ComponentAction::on_reset ƤФ줿ݤ˼¹Ԥ륳Хåؿ
    - # ܴؿ̵ RTC::RTC_OK ֤褦˥ߡƤΤǡ - # ƥݡͥȤμºݤΥꥻåȽϡܴؿ򥪡С饤ɤƼ - # ɬפ롣 - # - # @param self - # @param ec_id äƤ ExecutionContext ID - # - # @return ReturnCode_t Υ꥿󥳡 - # - # @else - # - # @endif - def onReset(self, ec_id): - self._rtcout.RTC_TRACE("onReset(%d)",ec_id) - return RTC.RTC_OK - - - ## - # @if jp - # - # @brief ѹѥХåؿ - # - # DataFlowComponentAction::on_state_update ƤФ줿ݤ˼¹Ԥ - # Хåؿ
    - # ܴؿ̵ RTC::RTC_OK ֤褦˥ߡƤΤǡ - # ƥݡͥȤμºݤξѹϡܴؿ򥪡С饤ɤƼ - # ɬפ롣
    - # ܴؿ Periodic Sampled Data Processing ˤ Two-Pass Execution - # ܤμ¹ԥѥȤŪ˸ƤӽФ롣 - # - # @param self - # @param ec_id äƤ ExecutionContext ID - # - # @return ReturnCode_t Υ꥿󥳡 - # - # @else - # - # @endif - def onStateUpdate(self, ec_id): - self._rtcout.RTC_TRACE("onStateupdate(%d)",ec_id) - return RTC.RTC_OK - - - ## - # @if jp - # - # @brief ưѹѥХåؿ - # - # DataFlowComponentAction::on_rate_changed ƤФ줿ݤ˼¹Ԥ - # Хåؿ
    - # ܴؿ̵ RTC::RTC_OK ֤褦˥ߡƤΤǡ - # ƥݡͥȤμºݤξѹϡܴؿ򥪡С饤ɤƼ - # ɬפ롣
    - # ܴؿ Periodic Sampled Data Processing ˤ ExecutionContext - # ¹Ԥ줿ݤ˸ƤӽФ롣 - # - # @param self - # @param ec_id äƤ ExecutionContext ID - # - # @return ReturnCode_t Υ꥿󥳡 - # - # @else - # - # @endif - def onRateChanged(self, ec_id): - self._rtcout.RTC_TRACE("onRatechanged(%d)",ec_id) - return RTC.RTC_OK - - - - ## - # @if jp - # - # @brief - # - # @param self - # @param ec_id äƤ ExecutionContext ID - # - # @return ReturnCode_t Υ꥿󥳡 - # - # @else - # - # @endif - def onAction(self, ec_id): - self._rtcout.RTC_TRACE("onAction(%d)",ec_id) - return RTC.RTC_OK - - - #============================================================ - # RTC::LightweightRTObject - #============================================================ - - ## - # @if jp - # - # @brief [CORBA interface] RTC - # - # Υڥ졼ƤӽФη̤ȤơComponentAction::on_initialize - # ХåؿƤФ롣 - # - # - # - RTC Created֤ξ߽Ԥ롣¾ξ֤ˤˤ - # ReturnCode_t::PRECONDITION_NOT_MET ֤ƤӽФϼԤ롣 - # - Υڥ졼 RTC Υߥɥ륦ƤФ뤳ȤꤷƤꡢ - # ץꥱȯԤľܤΥڥ졼Ƥ֤Ȥ - # Ƥʤ - # - # @param self - # - # @return ReturnCode_t Υ꥿󥳡 - # - # @else - # - # @brief Initialize the RTC that realizes this interface. - # - # The invocation of this operation shall result in the invocation of the - # callback ComponentAction::on_initialize. - # - # Constraints - # - An RTC may be initialized only while it is in the Created state. Any - # attempt to invoke this operation while in another state shall fail - # with ReturnCode_t::PRECONDITION_NOT_MET. - # - Application developers are not expected to call this operation - # directly; it exists for use by the RTC infrastructure. - # - # @return - # - # @endif - def initialize(self): - self._rtcout.RTC_TRACE("initialize()") - - # EC creation - ec_args_ = [] - if self.getContextOptions(ec_args_) != RTC.RTC_OK: - self._rtcout.RTC_ERROR("Valid EC options are not available. Aborting") - return RTC.BAD_PARAMETER - - if self.createContexts(ec_args_) != RTC.RTC_OK: - self._rtcout.RTC_ERROR("EC creation failed. Maybe out of resources. Aborting.") - return RTC.OUT_OF_RESOURCES + """ + """ + + ## + # @if jp + # @brief コンストラクタ + # + # コンストラクタ + # + # @param self + # @param manager マネージャオブジェクト(デフォルト値:None) + # @param orb ORB(デフォルト値:None) + # @param poa POA(デフォルト値:None) + # + # @else + # + # @brief Consructor + # + # @param orb ORB + # @param poa POA + # + # @endif + def __init__(self, manager=None, orb=None, poa=None): + if manager: + self._manager = manager + self._orb = self._manager.getORB() + self._poa = self._manager.getPOA() + self._portAdmin = OpenRTM_aist.PortAdmin( + self._manager.getORB(), self._manager.getPOA()) + else: + self._manager = None + self._orb = orb + self._poa = poa + self._portAdmin = OpenRTM_aist.PortAdmin(self._orb, self._poa) + if self._manager: + self._rtcout = self._manager.getLogbuf("rtobject") + else: + self._rtcout = OpenRTM_aist.Manager.instance().getLogbuf("rtobject") + + self._created = True + self._properties = OpenRTM_aist.Properties(defaults_str=default_conf) + self._configsets = OpenRTM_aist.ConfigAdmin( + self._properties.getNode("conf")) + self._profile = RTC.ComponentProfile( + "", "", "", "", "", "", [], None, []) + + self._sdoservice = OpenRTM_aist.SdoServiceAdmin(self) + self._SdoConfigImpl = OpenRTM_aist.Configuration_impl( + self._configsets, self._sdoservice) + self._SdoConfig = self._SdoConfigImpl.getObjRef() + self._execContexts = [] + self._objref = self._this() + self._sdoOwnedOrganizations = [] # SDOPackage.OrganizationList() + self._sdoSvcProfiles = [] # SDOPackage.ServiceProfileList() + self._sdoOrganizations = [] # SDOPackage.OrganizationList() + self._sdoStatus = [] # SDOPackage.NVList() + self._ecMine = [] + self._ecOther = [] + self._eclist = [] + self._exiting = False + self._readAll = False + self._writeAll = False + self._readAllCompletion = False + self._writeAllCompletion = False + self._inports = [] + self._outports = [] + self._actionListeners = OpenRTM_aist.ComponentActionListeners() + self._portconnListeners = OpenRTM_aist.PortConnectListeners() + self._fsmActionListeners = OpenRTM_aist.FsmActionListeners() + return - # -- entering alive state -- - toSTR_ = lambda x: " was" if len(x) == 1 else "s were" - self._rtcout.RTC_INFO("%d execution context%s created.", - (len(self._ecMine), toSTR_(self._ecMine))) + ## + # @if jp + # + # @brief デストラクタ + # + # @param self + # + # @else + # + # @brief destructor + # + # @endif + + def __del__(self): + return - ret_ = self.on_initialize() - self._created = False - if ret_ != RTC.RTC_OK: - self._rtcout.RTC_ERROR("on_initialize() failed.") - return ret_ + # ============================================================ + # Overridden functions + # ============================================================ + + ## + # @if jp + # + # @brief 初期化処理用コールバック関数 + # + # ComponentAction::on_initialize が呼ばれた際に実行されるコールバック + # 関数。
    + # 本関数は無条件に RTC::RTC_OK を返すようにダミー実装されているので、 + # 各コンポーネントの実際の初期化処理は、本関数をオーバーライドして実装する + # 必要がある。 + # + # @param self + # + # @return ReturnCode_t 型のリターンコード + # + # @else + # + # @endif + + def onInitialize(self): + self._rtcout.RTC_TRACE("onInitialize()") + return RTC.RTC_OK - self._rtcout.RTC_DEBUG("on_initialize() was properly done.") - for (idx_, ec_) in enumerate(self._ecMine): - self._rtcout.RTC_DEBUG("EC[%d] starting.", idx_) - ec_.start() + ## + # @if jp + # + # @brief 終了処理用コールバック関数 + # + # ComponentAction::on_finalize が呼ばれた際に実行されるコールバック + # 関数。
    + # 本関数は無条件に RTC::RTC_OK を返すようにダミー実装されているので、 + # 各コンポーネントの実際の終了処理は、本関数をオーバーライドして実装する + # 必要がある。 + # + # @param self + # + # @return ReturnCode_t 型のリターンコード + # + # @else + # + # @endif + + def onFinalize(self): + self._rtcout.RTC_TRACE("onFinalize()") + return RTC.RTC_OK - # ret must be RTC_OK - #assert(ret_ == RTC.RTC_OK) - self._sdoservice.init(self) - - return ret_ - - - ## - # @if jp - # - # @brief [CORBA interface] RTC λ - # - # Υڥ졼ƤӽФη̤Ȥ ComponentAction::on_finalize() - # ƤӽФ - # - # - # - RTC ExecutionContext ˽°Ƥ֤Ͻλʤξϡ - # ޤǽ ExecutionContextOperations::remove_component ˤäƻä - # ʤФʤʤʳξϡΥڥ졼ƤӽФ - # ʤ ReturnCode_t::PRECONDITION_NOT_ME ǼԤ롣 - # - RTC Created ֤Ǥ硢λϹԤʤ - # ξ硢Υڥ졼ƤӽФϤʤ - # ReturnCode_t::PRECONDITION_NOT_MET ǼԤ롣 - # - Υڥ졼RTCΥߥɥ륦ƤФ뤳ȤꤷƤꡢ - # ץꥱȯԤľܤΥڥ졼Ƥ֤Ȥ - # Ƥʤ - # - # @param self - # - # @return ReturnCode_t Υ꥿󥳡 - # - # @else - # - # @brief Finalize the RTC for preparing it for destruction - # - # This invocation of this operation shall result in the invocation of the - # callback ComponentAction::on_finalize. - # - # Constraints - # - An RTC may not be finalized while it is participating in any execution - # context. It must first be removed with - # ExecutionContextOperations::remove_component. Otherwise, this operation - # shall fail with ReturnCode_t::PRECONDITION_NOT_MET. - # - An RTC may not be finalized while it is in the Created state. Any - # attempt to invoke this operation while in that state shall fail with - # ReturnCode_t::PRECONDITION_NOT_MET. - # - Application developers are not expected to call this operation directly; - # it exists for use by the RTC infrastructure. - # - # @return - # - # @endif - def finalize(self): - self._rtcout.RTC_TRACE("finalize()") - - if self._created or not self._exiting: - return RTC.PRECONDITION_NOT_MET + ## + # @if jp + # + # @brief 開始処理用コールバック関数 + # + # ComponentAction::on_startup が呼ばれた際に実行されるコールバック + # 関数。
    + # 本関数は無条件に RTC::RTC_OK を返すようにダミー実装されているので、 + # 各コンポーネントの実際の開始処理は、本関数をオーバーライドして実装する + # 必要がある。 + # + # @param self + # @param ec_id 参加している ExecutionContext の ID + # + # @return ReturnCode_t 型のリターンコード + # + # @else + # + # @endif + + def onStartup(self, ec_id): + self._rtcout.RTC_TRACE("onStartup(%d)", ec_id) + return RTC.RTC_OK - # Return RTC::PRECONDITION_NOT_MET, - # When the component is registered in ExecutionContext. - if len(self._ecOther) != 0: - #for ec in self._ecOther: - #if not CORBA.is_nil(ec): - #return RTC.PRECONDITION_NOT_MET - - self._ecOther = [] - - ret = self.on_finalize() - self.shutdown() - return ret + ## + # @if jp + # + # @brief 停止処理用コールバック関数 + # + # ComponentAction::on_shutdown が呼ばれた際に実行されるコールバック + # 関数。
    + # 本関数は無条件に RTC::RTC_OK を返すようにダミー実装されているので、 + # 各コンポーネントの実際の停止処理は、本関数をオーバーライドして実装する + # 必要がある。 + # + # @param self + # @param ec_id 参加している ExecutionContext の ID + # + # @return ReturnCode_t 型のリターンコード + # + # @else + # + # @endif + + def onShutdown(self, ec_id): + self._rtcout.RTC_TRACE("onShutdown(%d)", ec_id) + return RTC.RTC_OK + ## + # @if jp + # + # @brief 活性化処理用コールバック関数 + # + # ComponentAction::on_activated が呼ばれた際に実行されるコールバック + # 関数。
    + # 本関数は無条件に RTC::RTC_OK を返すようにダミー実装されているので、 + # 各コンポーネントの実際の活性化処理は、本関数をオーバーライドして実装する + # 必要がある。 + # + # @param self + # @param ec_id 参加している ExecutionContext の ID + # + # @return ReturnCode_t 型のリターンコード + # + # @else + # + # @endif + + def onActivated(self, ec_id): + self._rtcout.RTC_TRACE("onActivated(%d)", ec_id) + return RTC.RTC_OK - ## - # @if jp - # - # @brief [CORBA interface] RTC ʡǤ ExecutionContext - # ߤΥƥĤȶ˽λ - # - # RTC ʡǤ뤹٤Ƥμ¹ԥƥȤߤ롣 - # RTC ¾μ¹ԥƥȤͭ RTC °¹ԥƥ - # (i.e. ¹ԥƥȤͭ RTC Ϥʤμ¹ԥƥȤ - # ʡǤ롣)˻äƤ硢 RTC ϤΥƥȾ - # ʤФʤʤ - # RTC ¹Τɤ ExecutionContext Ǥ Active ֤ǤϤʤʤä塢 - # RTC Ȥ˴ޤޤ RTC λ롣 - # - # - # - RTC ƤʤСλ뤳ȤϤǤʤ - # Created ֤ˤ RTC exit() ƤӽФ硢 - # ReturnCode_t::PRECONDITION_NOT_MET ǼԤ롣 - # - # @param self - # - # @return ReturnCode_t Υ꥿󥳡 - # - # @else - # - # @brief Stop the RTC's execution context(s) and finalize it along with its - # contents. - # - # Any execution contexts for which the RTC is the owner shall be stopped. - # If the RTC participates in any execution contexts belonging to another - # RTC that contains it, directly or indirectly (i.e. the containing RTC - # is the owner of the ExecutionContext), it shall be deactivated in those - # contexts. - # After the RTC is no longer Active in any Running execution context, it - # and any RTCs contained transitively within it shall be finalized. - # - # Constraints - # - An RTC cannot be exited if it has not yet been initialized. Any - # attempt to exit an RTC that is in the Created state shall fail with - # ReturnCode_t::PRECONDITION_NOT_MET. - # - # @return - # - # @endif - def exit(self): - self._rtcout.RTC_TRACE("exit()") - if self._created: - return RTC.PRECONDITION_NOT_MET - if self._exiting: - return RTC.RTC_OK - - # deactivate myself on owned EC - OpenRTM_aist.CORBA_SeqUtil.for_each(self._ecMine, - self.deactivate_comps(self._objref)) - # deactivate myself on other EC - OpenRTM_aist.CORBA_SeqUtil.for_each(self._ecOther, - self.deactivate_comps(self._objref)) - - # stop and detach myself from owned EC - #for ec in self._ecMine: - # if not CORBA.is_nil(ec) or not ec._non_existent(): + ## + # @if jp + # + # @brief 非活性化処理用コールバック関数 + # + # ComponentAction::on_deactivated が呼ばれた際に実行されるコールバック + # 関数。
    + # 本関数は無条件に RTC::RTC_OK を返すようにダミー実装されているので、 + # 各コンポーネントの実際の非活性化処理は、本関数をオーバーライドして実装する + # 必要がある。 + # + # @param self + # @param ec_id 参加している ExecutionContext の ID + # + # @return ReturnCode_t 型のリターンコード + # + # @else + # + # @endif + + def onDeactivated(self, ec_id): + self._rtcout.RTC_TRACE("onDeactivated(%d)", ec_id) + return RTC.RTC_OK + + ## + # @if jp + # + # @brief 周期処理用コールバック関数 + # + # DataFlowComponentAction::on_execute が呼ばれた際に実行される + # コールバック関数。
    + # 本関数は無条件に RTC::RTC_OK を返すようにダミー実装されているので、 + # 各コンポーネントの実際の周期処理は、本関数をオーバーライドして実装する + # 必要がある。
    + # 本関数は Periodic Sampled Data Processing における Two-Pass Executionの + # 1回目の実行パスとして定期的に呼び出される。 + # + # @param self + # @param ec_id 参加している ExecutionContext の ID + # + # @return ReturnCode_t 型のリターンコード + # + # @else + # + # @endif + + def onExecute(self, ec_id): + self._rtcout.RTC_TRACE("onExecute(%d)", ec_id) + return RTC.RTC_OK + + ## + # @if jp + # + # @brief 中断処理用コールバック関数 + # + # ComponentAction::on_aborting が呼ばれた際に実行されるコールバック + # 関数。
    + # 本関数は無条件に RTC::RTC_OK を返すようにダミー実装されているので、 + # 各コンポーネントの実際の中断処理は、本関数をオーバーライドして実装する + # 必要がある。 + # + # @param self + # @param ec_id 参加している ExecutionContext の ID + # + # @return ReturnCode_t 型のリターンコード + # + # @else + # + # @endif + + def onAborting(self, ec_id): + self._rtcout.RTC_TRACE("onAborting(%d)", ec_id) + return RTC.RTC_OK + + ## + # @if jp + # + # @brief エラー処理用コールバック関数 + # + # ComponentAction::on_error が呼ばれた際に実行されるコールバック関数。
    + # 本関数は無条件に RTC::RTC_OK を返すようにダミー実装されているので、 + # 各コンポーネントの実際のエラー処理は、本関数をオーバーライドして実装する + # 必要がある。 + # + # @param self + # @param ec_id 参加している ExecutionContext の ID + # + # @return ReturnCode_t 型のリターンコード + # + # @else + # + # @endif + + def onError(self, ec_id): + self._rtcout.RTC_TRACE("onError(%d)", ec_id) + return RTC.RTC_OK + + ## + # @if jp + # + # @brief リセット処理用コールバック関数 + # + # ComponentAction::on_reset が呼ばれた際に実行されるコールバック関数。
    + # 本関数は無条件に RTC::RTC_OK を返すようにダミー実装されているので、 + # 各コンポーネントの実際のリセット処理は、本関数をオーバーライドして実装する + # 必要がある。 + # + # @param self + # @param ec_id 参加している ExecutionContext の ID + # + # @return ReturnCode_t 型のリターンコード + # + # @else + # + # @endif + + def onReset(self, ec_id): + self._rtcout.RTC_TRACE("onReset(%d)", ec_id) + return RTC.RTC_OK + + ## + # @if jp + # + # @brief 状態変更処理用コールバック関数 + # + # DataFlowComponentAction::on_state_update が呼ばれた際に実行される + # コールバック関数。
    + # 本関数は無条件に RTC::RTC_OK を返すようにダミー実装されているので、 + # 各コンポーネントの実際の状態変更処理は、本関数をオーバーライドして実装する + # 必要がある。
    + # 本関数は Periodic Sampled Data Processing における Two-Pass Executionの + # 2回目の実行パスとして定期的に呼び出される。 + # + # @param self + # @param ec_id 参加している ExecutionContext の ID + # + # @return ReturnCode_t 型のリターンコード + # + # @else + # + # @endif + + def onStateUpdate(self, ec_id): + self._rtcout.RTC_TRACE("onStateupdate(%d)", ec_id) + return RTC.RTC_OK + + ## + # @if jp + # + # @brief 動作周期変更通知用コールバック関数 + # + # DataFlowComponentAction::on_rate_changed が呼ばれた際に実行される + # コールバック関数。
    + # 本関数は無条件に RTC::RTC_OK を返すようにダミー実装されているので、 + # 各コンポーネントの実際の状態変更処理は、本関数をオーバーライドして実装する + # 必要がある。
    + # 本関数は Periodic Sampled Data Processing において ExecutionContext の + # 実行が更新された際に呼び出される。 + # + # @param self + # @param ec_id 参加している ExecutionContext の ID + # + # @return ReturnCode_t 型のリターンコード + # + # @else + # + # @endif + + def onRateChanged(self, ec_id): + self._rtcout.RTC_TRACE("onRatechanged(%d)", ec_id) + return RTC.RTC_OK + + ## + # @if jp + # + # @brief + # + # @param self + # @param ec_id 参加している ExecutionContext の ID + # + # @return ReturnCode_t 型のリターンコード + # + # @else + # + # @endif + + def onAction(self, ec_id): + self._rtcout.RTC_TRACE("onAction(%d)", ec_id) + return RTC.RTC_OK + + # ============================================================ + # RTC::LightweightRTObject + # ============================================================ + + ## + # @if jp + # + # @brief [CORBA interface] RTCを初期化する + # + # このオペレーション呼び出しの結果として、ComponentAction::on_initialize + # コールバック関数が呼ばれる。 + # + # 制約 + # - RTC は Created状態の場合み初期化が行われる。他の状態にいる場合には + # ReturnCode_t::PRECONDITION_NOT_MET が返され呼び出しは失敗する。 + # - このオペレーションは RTC のミドルウエアから呼ばれることを想定しており、 + # アプリケーション開発者は直接このオペレーションを呼ぶことは想定 + # されていない。 + # + # @param self + # + # @return ReturnCode_t 型のリターンコード + # + # @else + # + # @brief Initialize the RTC that realizes this interface. + # + # The invocation of this operation shall result in the invocation of the + # callback ComponentAction::on_initialize. + # + # Constraints + # - An RTC may be initialized only while it is in the Created state. Any + # attempt to invoke this operation while in another state shall fail + # with ReturnCode_t::PRECONDITION_NOT_MET. + # - Application developers are not expected to call this operation + # directly; it exists for use by the RTC infrastructure. + # + # @return + # + # @endif + + def initialize(self): + self._rtcout.RTC_TRACE("initialize()") + + # EC creation + ec_args_ = [] + if self.getContextOptions(ec_args_) != RTC.RTC_OK: + self._rtcout.RTC_ERROR( + "Valid EC options are not available. Aborting") + return RTC.BAD_PARAMETER + + if self.createContexts(ec_args_) != RTC.RTC_OK: + self._rtcout.RTC_ERROR( + "EC creation failed. Maybe out of resources. Aborting.") + return RTC.OUT_OF_RESOURCES + + # -- entering alive state -- + def toSTR_(x): return " was" if len(x) == 1 else "s were" + self._rtcout.RTC_INFO("%d execution context%s created.", + (len(self._ecMine), toSTR_(self._ecMine))) + + ret_ = self.on_initialize() + self._created = False + if ret_ != RTC.RTC_OK: + self._rtcout.RTC_ERROR("on_initialize() failed.") + return ret_ + + self._rtcout.RTC_DEBUG("on_initialize() was properly done.") + for (idx_, ec_) in enumerate(self._ecMine): + self._rtcout.RTC_DEBUG("EC[%d] starting.", idx_) + ec_.start() + + # ret must be RTC_OK + #assert(ret_ == RTC.RTC_OK) + self._sdoservice.init(self) + + return ret_ + + ## + # @if jp + # + # @brief [CORBA interface] RTC を終了する + # + # このオペレーション呼び出しの結果として ComponentAction::on_finalize() + # を呼び出す。 + # + # 制約 + # - RTC が ExecutionContext に所属している間は終了されない。この場合は、 + # まず最初に ExecutionContextOperations::remove_component によって参加を + # 解除しなければならない。これ以外の場合は、このオペレーション呼び出しは + # いかなる場合も ReturnCode_t::PRECONDITION_NOT_ME で失敗する。 + # - RTC が Created 状態である場合、終了処理は行われない。 + # この場合、このオペレーション呼び出しはいかなる場合も + # ReturnCode_t::PRECONDITION_NOT_MET で失敗する。 + # - このオペレーションはRTCのミドルウエアから呼ばれることを想定しており、 + # アプリケーション開発者は直接このオペレーションを呼ぶことは想定 + # されていない。 + # + # @param self + # + # @return ReturnCode_t 型のリターンコード + # + # @else + # + # @brief Finalize the RTC for preparing it for destruction + # + # This invocation of this operation shall result in the invocation of the + # callback ComponentAction::on_finalize. + # + # Constraints + # - An RTC may not be finalized while it is participating in any execution + # context. It must first be removed with + # ExecutionContextOperations::remove_component. Otherwise, this operation + # shall fail with ReturnCode_t::PRECONDITION_NOT_MET. + # - An RTC may not be finalized while it is in the Created state. Any + # attempt to invoke this operation while in that state shall fail with + # ReturnCode_t::PRECONDITION_NOT_MET. + # - Application developers are not expected to call this operation directly; + # it exists for use by the RTC infrastructure. + # + # @return + # + # @endif + + def finalize(self): + self._rtcout.RTC_TRACE("finalize()") + + if self._created or not self._exiting: + return RTC.PRECONDITION_NOT_MET + + # Return RTC::PRECONDITION_NOT_MET, + # When the component is registered in ExecutionContext. + if self._ecOther: + # for ec in self._ecOther: + # if not CORBA.is_nil(ec): + # return RTC.PRECONDITION_NOT_MET + + self._ecOther = [] + + ret = self.on_finalize() + self.shutdown() + return ret + + ## + # @if jp + # + # @brief [CORBA interface] RTC がオーナーである ExecutionContext を + # 停止させ、そのコンテンツと共に終了させる + # + # この RTC がオーナーであるすべての実行コンテキストを停止する。 + # この RTC が他の実行コンテキストを所有する RTC に属する実行コンテキスト + # (i.e. 実行コンテキストを所有する RTC はすなわちその実行コンテキストの + # オーナーである。)に参加している場合、当該 RTC はそれらのコンテキスト上 + # で非活性化されなければならない。 + # RTC が実行中のどの ExecutionContext でも Active 状態ではなくなった後、 + # この RTC とこれに含まれる RTC が終了する。 + # + # 制約 + # - RTC が初期化されていなければ、終了させることはできない。 + # Created 状態にある RTC に exit() を呼び出した場合、 + # ReturnCode_t::PRECONDITION_NOT_MET で失敗する。 + # + # @param self + # + # @return ReturnCode_t 型のリターンコード + # + # @else + # + # @brief Stop the RTC's execution context(s) and finalize it along with its + # contents. + # + # Any execution contexts for which the RTC is the owner shall be stopped. + # If the RTC participates in any execution contexts belonging to another + # RTC that contains it, directly or indirectly (i.e. the containing RTC + # is the owner of the ExecutionContext), it shall be deactivated in those + # contexts. + # After the RTC is no longer Active in any Running execution context, it + # and any RTCs contained transitively within it shall be finalized. + # + # Constraints + # - An RTC cannot be exited if it has not yet been initialized. Any + # attempt to exit an RTC that is in the Created state shall fail with + # ReturnCode_t::PRECONDITION_NOT_MET. + # + # @return + # + # @endif + + def exit(self): + self._rtcout.RTC_TRACE("exit()") + if self._created: + return RTC.PRECONDITION_NOT_MET + if self._exiting: + return RTC.RTC_OK + + # deactivate myself on owned EC + OpenRTM_aist.CORBA_SeqUtil.for_each(self._ecMine, + self.deactivate_comps(self._objref)) + # deactivate myself on other EC + OpenRTM_aist.CORBA_SeqUtil.for_each(self._ecOther, + self.deactivate_comps(self._objref)) + + # stop and detach myself from owned EC + # for ec in self._ecMine: + # if not CORBA.is_nil(ec) or not ec._non_existent(): # ret = ec.stop() # ec.remove_component(self._this()) - # pass - - - # detach myself from other EC - for ec in self._ecOther: - try: - if not CORBA.is_nil(ec) or not ec._non_existent(): - # ec.stop() - ec.remove_component(self._this()) - except: - pass - - - self._exiting = True - return self.finalize() - - - ## - # @if jp - # - # @brief [CORBA interface] RTC Alive ֤Ǥ뤫ɤǧ롣 - # - # RTC ꤷ ExecutionContext Ф Alive֤Ǥ뤫ɤǧ롣 - # RTC ξ֤ Active Ǥ뤫Inactive Ǥ뤫Error Ǥ뤫ϼ¹ - # ExecutionContext ˰¸롣ʤ ExecutionContext ФƤ - # Active ֤ǤäƤ⡢¾ ExecutionContext ФƤ Inactive ֤ - # ʤ⤢ꤨ롣äơΥڥ졼ϻꤵ줿 - # ExecutionContext 䤤碌ơ RTC ξ֤ ActiveInactive - # Error ξˤ Alive ֤Ȥ֤ - # - # @param self - # - # @param exec_context о ExecutionContext ϥɥ - # - # @return Alive ֳǧ - # - # @else - # - # @brief Confirm whether RTC is an Alive state or NOT. - # - # A component is alive or not regardless of the execution context from - # which it is observed. However, whether or not it is Active, Inactive, - # or in Error is dependent on the execution context(s) in which it is - # running. That is, it may be Active in one context but Inactive in - # another. Therefore, this operation shall report whether this RTC is - # either Active, Inactive or in Error; which of those states a component - # is in with respect to a particular context may be queried from the - # context itself. - # - # @return Result of Alive state confirmation - # - # @endif - # virtual CORBA::Boolean is_alive(ExecutionContext_ptr exec_context) - def is_alive(self, exec_context): - self._rtcout.RTC_TRACE("is_alive()") - for ec in self._ecMine: - if exec_context._is_equivalent(ec): - return True + # pass + + # detach myself from other EC + for ec in self._ecOther: + try: + if not CORBA.is_nil(ec) or not ec._non_existent(): + # ec.stop() + ec.remove_component(self._this()) + except BaseException: + pass + + self._exiting = True + return self.finalize() + + ## + # @if jp + # + # @brief [CORBA interface] RTC が Alive 状態であるかどうか確認する。 + # + # RTC が指定した ExecutionContext に対して Alive状態であるかどうか確認する。 + # RTC の状態が Active であるか、Inactive であるか、Error であるかは実行中の + # ExecutionContext に依存する。すなわち、ある ExecutionContext に対しては + # Active 状態であっても、他の ExecutionContext に対しては Inactive 状態と + # なる場合もありえる。従って、このオペレーションは指定された + # ExecutionContext に問い合わせて、この RTC の状態が Active、Inactive、 + # Error の場合には Alive 状態として返す。 + # + # @param self + # + # @param exec_context 取得対象 ExecutionContext ハンドル + # + # @return Alive 状態確認結果 + # + # @else + # + # @brief Confirm whether RTC is an Alive state or NOT. + # + # A component is alive or not regardless of the execution context from + # which it is observed. However, whether or not it is Active, Inactive, + # or in Error is dependent on the execution context(s) in which it is + # running. That is, it may be Active in one context but Inactive in + # another. Therefore, this operation shall report whether this RTC is + # either Active, Inactive or in Error; which of those states a component + # is in with respect to a particular context may be queried from the + # context itself. + # + # @return Result of Alive state confirmation + # + # @endif + # virtual CORBA::Boolean is_alive(ExecutionContext_ptr exec_context) + + def is_alive(self, exec_context): + self._rtcout.RTC_TRACE("is_alive()") + for ec in self._ecMine: + if exec_context._is_equivalent(ec): + return True + + for ec in self._ecOther: + if not CORBA.is_nil(ec): + if exec_context._is_equivalent(ec): + return True + + return False + + ## + # @if jp + # @brief [CORBA interface] ExecutionContextListを取得する + # + # この RTC が所有する ExecutionContext のリストを取得する。 + # + # @param self + # + # @return ExecutionContext リスト + # + # @else + # @brief [CORBA interface] Get ExecutionContextList. + # + # This operation returns a list of all execution contexts owned by this RTC. + # + # @return ExecutionContext List + # + # @endif + # def get_contexts(self): + # execlist = [] + # OpenRTM_aist.CORBA_SeqUtil.for_each(self._execContexts, self.ec_copy(execlist)) + # return execlist + + ## + # @if jp + # @brief [CORBA interface] ExecutionContextを取得する + # + # 指定したハンドルの ExecutionContext を取得する。 + # ハンドルから ExecutionContext へのマッピングは、特定の RTC インスタンスに + # 固有である。ハンドルはこの RTC を attach_context した際に取得できる。 + # + # @param self + # @param ec_id 取得対象 ExecutionContext ハンドル + # + # @return ExecutionContext + # + # @else + # @brief [CORBA interface] Get ExecutionContext. + # + # Obtain a reference to the execution context represented by the given + # handle. + # The mapping from handle to context is specific to a particular RTC + # instance. The given handle must have been obtained by a previous call to + # attach_context on this RTC. + # + # @param ec_id ExecutionContext handle + # + # @return ExecutionContext + # + # @endif + # virtual ExecutionContext_ptr get_context(UniqueId exec_handle) + + def get_context(self, ec_id): + global ECOTHER_OFFSET + + self._rtcout.RTC_TRACE("get_context(%d)", ec_id) + # owned EC + if ec_id < ECOTHER_OFFSET: + if ec_id < len(self._ecMine): + return self._ecMine[ec_id] + else: + return RTC.ExecutionContext._nil + + # participating EC + index = ec_id - ECOTHER_OFFSET + + if index < len(self._ecOther): + if not CORBA.is_nil(self._ecOther[index]): + return self._ecOther[index] - for ec in self._ecOther: - if not CORBA.is_nil(ec): - if exec_context._is_equivalent(ec): - return True - - return False - - - ## - # @if jp - # @brief [CORBA interface] ExecutionContextList - # - # RTC ͭ ExecutionContext ΥꥹȤ롣 - # - # @param self - # - # @return ExecutionContext ꥹ - # - # @else - # @brief [CORBA interface] Get ExecutionContextList. - # - # This operation returns a list of all execution contexts owned by this RTC. - # - # @return ExecutionContext List - # - # @endif - #def get_contexts(self): - # execlist = [] - # OpenRTM_aist.CORBA_SeqUtil.for_each(self._execContexts, self.ec_copy(execlist)) - # return execlist - - - ## - # @if jp - # @brief [CORBA interface] ExecutionContext - # - # ꤷϥɥ ExecutionContext 롣 - # ϥɥ뤫 ExecutionContext ؤΥޥåԥ󥰤ϡ RTC 󥹥󥹤 - # ͭǤ롣ϥɥϤ RTC attach_context ݤ˼Ǥ롣 - # - # @param self - # @param ec_id о ExecutionContext ϥɥ - # - # @return ExecutionContext - # - # @else - # @brief [CORBA interface] Get ExecutionContext. - # - # Obtain a reference to the execution context represented by the given - # handle. - # The mapping from handle to context is specific to a particular RTC - # instance. The given handle must have been obtained by a previous call to - # attach_context on this RTC. - # - # @param ec_id ExecutionContext handle - # - # @return ExecutionContext - # - # @endif - # virtual ExecutionContext_ptr get_context(UniqueId exec_handle) - def get_context(self, ec_id): - global ECOTHER_OFFSET - - self._rtcout.RTC_TRACE("get_context(%d)", ec_id) - # owned EC - if ec_id < ECOTHER_OFFSET: - if ec_id < len(self._ecMine): - return self._ecMine[ec_id] - else: return RTC.ExecutionContext._nil - # participating EC - index = ec_id - ECOTHER_OFFSET - - if index < len(self._ecOther): - if not CORBA.is_nil(self._ecOther[index]): - return self._ecOther[index] - - return RTC.ExecutionContext._nil - - - ## - # @if jp - # @brief [CORBA interface] ͭ ExecutionContextList - # - # RTC ͭ ExecutionContext ΥꥹȤ롣 - # - # @return ExecutionContext ꥹ - # - # @else - # @brief [CORBA interface] Get ExecutionContextList. - # - # This operation returns a list of all execution contexts owned by this - # RTC. - # - # @return ExecutionContext List - # - # @endif - # virtual ExecutionContextList* get_owned_contexts() - def get_owned_contexts(self): - self._rtcout.RTC_TRACE("get_owned_contexts()") - execlist = [] - OpenRTM_aist.CORBA_SeqUtil.for_each(self._ecMine, self.ec_copy(execlist)) - return execlist - - ## - # @if jp - # @brief [CORBA interface] äƤ ExecutionContextList - # - # RTC äƤ ExecutionContext ΥꥹȤ롣 - # - # @return ExecutionContext ꥹ - # - # @else - # @brief [CORBA interface] Get participating ExecutionContextList. - # - # This operation returns a list of all execution contexts in - # which this RTC participates. - # - # @return ExecutionContext List - # - # @endif - # virtual ExecutionContextList* get_participating_contexts() - def get_participating_contexts(self): - self._rtcout.RTC_TRACE("get_participating_contexts()") - execlist = [] - OpenRTM_aist.CORBA_SeqUtil.for_each(self._ecOther, self.ec_copy(execlist)) - return execlist - - - ## - # @if jp - # @brief [CORBA interface] ExecutionContext Υϥɥ֤ - # - # @param ExecutionContext ¹ԥƥ - # - # @return ExecutionContextHandle - # - # Ϳ줿¹ԥƥȤ˴Ϣդ줿ϥɥ֤ - # - # @else - # @brief [CORBA interface] Return a handle of a ExecutionContext - # - # @param ExecutionContext - # - # @return ExecutionContextHandle - # - # This operation returns a handle that is associated with the given - # execution context. - # - # @endif - # - # virtual ExecutionContextHandle_t - # get_context_handle(ExecutionContext_ptr cxt) - def get_context_handle(self, cxt): - self._rtcout.RTC_TRACE("get_context_handle()") - - num = OpenRTM_aist.CORBA_SeqUtil.find(self._ecMine, self.ec_find(cxt)) - if num != -1: - return int(num) - - num = OpenRTM_aist.CORBA_SeqUtil.find(self._ecOther, self.ec_find(cxt)) - if num != -1: - return int(num) + 1000 - - return int(-1) - - - #============================================================ - # RTC::RTObject - #============================================================ - - ## - # @if jp - # - # @brief [RTObject CORBA interface] ݡͥȥץե - # - # ݡͥȤΥץե֤ - # - # @param self - # - # @return ݡͥȥץե - # - # @else - # - # @brief [RTObject CORBA interface] Get RTC's profile - # - # This operation returns the ComponentProfile of the RTC - # - # @return ComponentProfile - # - # @endif - # virtual ComponentProfile* get_component_profile() - def get_component_profile(self): - self._rtcout.RTC_TRACE("get_component_profile()") - prop_ = RTC.ComponentProfile(self._properties.getProperty("instance_name"), - self._properties.getProperty("type_name"), - self._properties.getProperty("description"), - self._properties.getProperty("version"), - self._properties.getProperty("vendor"), - self._properties.getProperty("category"), - self._portAdmin.getPortProfileList(), - self._profile.parent, - self._profile.properties) - OpenRTM_aist.NVUtil.copyFromProperties(self._profile.properties, self._properties) - return prop_ - # return RTC.ComponentProfile(self._profile.instance_name, - # self._profile.type_name, - # self._profile.description, - # self._profile.version, - # self._profile.vendor, - # self._profile.category, - # self._portAdmin.getPortProfileList(), - # self._profile.parent, - # self._profile.properties) - - #except: - # self._rtcout.RTC_ERROR(OpenRTM_aist.Logger.print_exception()) - - - #return None - - - ## - # @if jp - # - # @brief [RTObject CORBA interface] ݡȤ - # - # ݡͥȤͭݡȤλȤ֤ - # - # @param self - # - # @return ݡȥꥹ - # - # @else - # - # @brief [RTObject CORBA interface] Get Ports - # - # This operation returns a list of the RTCs ports. - # - # @return PortList - # - # @endif - # virtual PortServiceList* get_ports() - def get_ports(self): - self._rtcout.RTC_TRACE("get_ports()") - - return self._portAdmin.getPortServiceList() - - - - - - # RTC::ComponentAction - - ## - # @if jp - # @brief [CORBA interface] ExecutionContextattach - # - # ꤷ ExecutionContext ˤ RTC °롣 RTC ȴϢ - # ExecutionContext Υϥɥ֤ - # Υڥ졼ϡExecutionContextOperations::add_component ƤФ줿 - # ݤ˸ƤӽФ롣֤줿ϥɥ¾Υ饤ȤǻѤ뤳Ȥ - # Ƥʤ - # - # @param self - # @param exec_context ° ExecutionContext - # - # @return ExecutionContext ϥɥ - # - # @else - # @brief [CORBA interface] Attach ExecutionContext. - # - # Inform this RTC that it is participating in the given execution context. - # Return a handle that represents the association of this RTC with the - # context. - # This operation is intended to be invoked by - # ExecutionContextOperations::add_component. It is not intended for use by - # other clients. - # - # @param exec_context Prticipating ExecutionContext - # - # @return ExecutionContext Handle - # - # @endif - # UniqueId attach_context(ExecutionContext_ptr exec_context) - def attach_context(self, exec_context): - global ECOTHER_OFFSET - self._rtcout.RTC_TRACE("attach_context()") - # ID: 0 - (offset-1) : owned ec - # ID: offset - : participating ec - # owned ec index = ID - # participate ec index = ID - offset - ecs = exec_context._narrow(RTC.ExecutionContextService) - if CORBA.is_nil(ecs): - return -1 - - # if m_ecOther has nil element, insert attached ec to there. - for i in range(len(self._ecOther)): - if CORBA.is_nil(self._ecOther[i]): - self._ecOther[i] = ecs - ec_id = i + ECOTHER_OFFSET + ## + # @if jp + # @brief [CORBA interface] 所有する ExecutionContextListを 取得する + # + # この RTC が所有する ExecutionContext のリストを取得する。 + # + # @return ExecutionContext リスト + # + # @else + # @brief [CORBA interface] Get ExecutionContextList. + # + # This operation returns a list of all execution contexts owned by this + # RTC. + # + # @return ExecutionContext List + # + # @endif + # virtual ExecutionContextList* get_owned_contexts() + + def get_owned_contexts(self): + self._rtcout.RTC_TRACE("get_owned_contexts()") + execlist = [] + OpenRTM_aist.CORBA_SeqUtil.for_each( + self._ecMine, self.ec_copy(execlist)) + return execlist + + ## + # @if jp + # @brief [CORBA interface] 参加している ExecutionContextList を取得する + # + # この RTC が参加している ExecutionContext のリストを取得する。 + # + # @return ExecutionContext リスト + # + # @else + # @brief [CORBA interface] Get participating ExecutionContextList. + # + # This operation returns a list of all execution contexts in + # which this RTC participates. + # + # @return ExecutionContext List + # + # @endif + # virtual ExecutionContextList* get_participating_contexts() + def get_participating_contexts(self): + self._rtcout.RTC_TRACE("get_participating_contexts()") + execlist = [] + OpenRTM_aist.CORBA_SeqUtil.for_each( + self._ecOther, self.ec_copy(execlist)) + return execlist + + ## + # @if jp + # @brief [CORBA interface] ExecutionContext のハンドルを返す + # + # @param ExecutionContext 実行コンテキスト + # + # @return ExecutionContextHandle + # + # 与えられた実行コンテキストに関連付けられたハンドルを返す。 + # + # @else + # @brief [CORBA interface] Return a handle of a ExecutionContext + # + # @param ExecutionContext + # + # @return ExecutionContextHandle + # + # This operation returns a handle that is associated with the given + # execution context. + # + # @endif + # + # virtual ExecutionContextHandle_t + # get_context_handle(ExecutionContext_ptr cxt) + + def get_context_handle(self, cxt): + self._rtcout.RTC_TRACE("get_context_handle()") + + num = OpenRTM_aist.CORBA_SeqUtil.find(self._ecMine, self.ec_find(cxt)) + if num != -1: + return int(num) + + num = OpenRTM_aist.CORBA_SeqUtil.find(self._ecOther, self.ec_find(cxt)) + if num != -1: + return int(num) + 1000 + + return int(-1) + + # ============================================================ + # RTC::RTObject + # ============================================================ + + ## + # @if jp + # + # @brief [RTObject CORBA interface] コンポーネントプロファイルを取得する + # + # 当該コンポーネントのプロファイル情報を返す。 + # + # @param self + # + # @return コンポーネントプロファイル + # + # @else + # + # @brief [RTObject CORBA interface] Get RTC's profile + # + # This operation returns the ComponentProfile of the RTC + # + # @return ComponentProfile + # + # @endif + # virtual ComponentProfile* get_component_profile() + + def get_component_profile(self): + self._rtcout.RTC_TRACE("get_component_profile()") + prop_ = RTC.ComponentProfile(self._properties.getProperty("instance_name"), + self._properties.getProperty("type_name"), + self._properties.getProperty( + "description"), + self._properties.getProperty("version"), + self._properties.getProperty("vendor"), + self._properties.getProperty("category"), + self._portAdmin.getPortProfileList(), + self._profile.parent, + self._profile.properties) + OpenRTM_aist.NVUtil.copyFromProperties( + self._profile.properties, self._properties) + return prop_ + # return RTC.ComponentProfile(self._profile.instance_name, + # self._profile.type_name, + # self._profile.description, + # self._profile.version, + # self._profile.vendor, + # self._profile.category, + # self._portAdmin.getPortProfileList(), + # self._profile.parent, + # self._profile.properties) + + # except: + # self._rtcout.RTC_ERROR(OpenRTM_aist.Logger.print_exception()) + + # return None + + ## + # @if jp + # + # @brief [RTObject CORBA interface] ポートを取得する + # + # 当該コンポーネントが保有するポートの参照を返す。 + # + # @param self + # + # @return ポートリスト + # + # @else + # + # @brief [RTObject CORBA interface] Get Ports + # + # This operation returns a list of the RTCs ports. + # + # @return PortList + # + # @endif + # virtual PortServiceList* get_ports() + + def get_ports(self): + self._rtcout.RTC_TRACE("get_ports()") + + return self._portAdmin.getPortServiceList() + + # RTC::ComponentAction + + ## + # @if jp + # @brief [CORBA interface] ExecutionContextをattachする + # + # 指定した ExecutionContext にこの RTC を所属させる。この RTC と関連する + # ExecutionContext のハンドルを返す。 + # このオペレーションは、ExecutionContextOperations::add_component が呼ばれた + # 際に呼び出される。返されたハンドルは他のクライアントで使用することを想定 + # していない。 + # + # @param self + # @param exec_context 所属先 ExecutionContext + # + # @return ExecutionContext ハンドル + # + # @else + # @brief [CORBA interface] Attach ExecutionContext. + # + # Inform this RTC that it is participating in the given execution context. + # Return a handle that represents the association of this RTC with the + # context. + # This operation is intended to be invoked by + # ExecutionContextOperations::add_component. It is not intended for use by + # other clients. + # + # @param exec_context Prticipating ExecutionContext + # + # @return ExecutionContext Handle + # + # @endif + # UniqueId attach_context(ExecutionContext_ptr exec_context) + + def attach_context(self, exec_context): + global ECOTHER_OFFSET + self._rtcout.RTC_TRACE("attach_context()") + # ID: 0 - (offset-1) : owned ec + # ID: offset - : participating ec + # owned ec index = ID + # participate ec index = ID - offset + ecs = exec_context._narrow(RTC.ExecutionContextService) + if CORBA.is_nil(ecs): + return -1 + + # if m_ecOther has nil element, insert attached ec to there. + for i, ec in enumerate(self._ecOther): + if CORBA.is_nil(ec): + self._ecOther[i] = ecs + ec_id = i + ECOTHER_OFFSET + self.onAttachExecutionContext(ec_id) + return ec_id + + # no space in the list, push back ec to the last. + OpenRTM_aist.CORBA_SeqUtil.push_back(self._ecOther, ecs) + ec_id = int(len(self._ecOther) - 1 + ECOTHER_OFFSET) self.onAttachExecutionContext(ec_id) return ec_id - # no space in the list, push back ec to the last. - OpenRTM_aist.CORBA_SeqUtil.push_back(self._ecOther,ecs) - ec_id = int(len(self._ecOther) - 1 + ECOTHER_OFFSET) - self.onAttachExecutionContext(ec_id) - return ec_id - - - # UniqueId bindContext(ExecutionContext_ptr exec_context); - def bindContext(self, exec_context): - global ECOTHER_OFFSET - self._rtcout.RTC_TRACE("bindContext()") - # ID: 0 - (offset-1) : owned ec - # ID: offset - : participating ec - # owned ec index = ID - # participate ec index = ID - offset - ecs = exec_context._narrow(RTC.ExecutionContextService) - - if CORBA.is_nil(ecs): - return -1 - - # if m_ecMine has nil element, insert attached ec to there. - for i in range(len(self._ecMine)): - if CORBA.is_nil(self._ecMine[i]): - self._ecMine[i] = ecs - self.onAttachExecutionContext(i) - return i - #return i + ECOTHER_OFFSET - - # no space in the list, push back ec to the last. - OpenRTM_aist.CORBA_SeqUtil.push_back(self._ecMine,ecs) - - return int(len(self._ecMine) - 1) - #return int(len(self._ecMine) - 1 + ECOTHER_OFFSET) - - - ## - # @if jp - # @brief [CORBA interface] ExecutionContextdetach - # - # ꤷ ExecutionContext 餳 RTC ν°롣 - # Υڥ졼ϡExecutionContextOperations::remove_component Ƥ - # 줿ݤ˸ƤӽФ롣֤줿ϥɥ¾Υ饤ȤǻѤ뤳Ȥ - # ꤷƤʤ - # - # - # - ꤵ줿 ExecutionContext RTC Ǥ˽°Ƥʤˤϡ - # ReturnCode_t::PRECONDITION_NOT_MET ֤롣 - # - ꤵ줿 ExecutionContext ˤФ RTC Active ֤Ǥ - # ˤϡ ReturnCode_t::PRECONDITION_NOT_MET ֤롣 - # - # @param self - # @param ec_id о ExecutionContextϥɥ - # - # @return ReturnCode_t Υ꥿󥳡 - # - # @else - # @brief [CORBA interface] Attach ExecutionContext. - # - # Inform this RTC that it is no longer participating in the given execution - # context. - # This operation is intended to be invoked by - # ExecutionContextOperations::remove_component. It is not intended for use - # by other clients. - # Constraints - # - This operation may not be invoked if this RTC is not already - # participating in the execution context. Such a call shall fail with - # ReturnCode_t::PRECONDITION_NOT_MET. - # - This operation may not be invoked if this RTC is Active in the indicated - # execution context. Otherwise, it shall fail with - # ReturnCode_t::PRECONDITION_NOT_MET. - # - # @param ec_id Dettaching ExecutionContext Handle - # - # @return - # - # @endif - # ReturnCode_t detach_context(UniqueId exec_handle) - def detach_context(self, ec_id): - global ECOTHER_OFFSET - self._rtcout.RTC_TRACE("detach_context(%d)", ec_id) - len_ = len(self._ecOther) - - # ID: 0 - (offset-1) : owned ec - # ID: offset - : participating ec - # owned ec index = ID - # participate ec index = ID - offset - if (int(ec_id) < int(ECOTHER_OFFSET)) or \ - (int(ec_id - ECOTHER_OFFSET) > len_): - return RTC.BAD_PARAMETER - - index = int(ec_id - ECOTHER_OFFSET) - - if index < 0 or CORBA.is_nil(self._ecOther[index]): - return RTC.BAD_PARAMETER - - #OpenRTM_aist.CORBA_SeqUtil.erase(self._ecOther, index) - self._ecOther[index] = RTC.ExecutionContextService._nil - self.onDetachExecutionContext(ec_id) - return RTC.RTC_OK - - - ## - # @if jp - # - # @brief [ComponentAction CORBA interface] RTC ν - # - # RTC 졢Alive ֤ܤ롣 - # RTC ͭνϤǼ¹Ԥ롣 - # Υڥ졼ƤӽФη̤Ȥ onInitialize() Хåؿ - # ƤӽФ롣 - # - # @param self - # - # @return ReturnCode_t Υ꥿󥳡 - # - # @else - # - # @brief [ComponentAction CORBA interface] Initialize RTC - # - # The RTC has been initialized and entered the Alive state. - # Any RTC-specific initialization logic should be performed here. - # - # @return - # - # @endif - def on_initialize(self): - self._rtcout.RTC_TRACE("on_initialize()") - ret = RTC.RTC_ERROR - try: - self.preOnInitialize(0) - self._rtcout.RTC_DEBUG("Calling onInitialize().") - ret = self.onInitialize() - if ret != RTC.RTC_OK: - self._rtcout.RTC_ERROR("onInitialize() returns an ERROR (%d)", ret._v) - else: - self._rtcout.RTC_DEBUG("onInitialize() succeeded.") - - except: - self._rtcout.RTC_ERROR(OpenRTM_aist.Logger.print_exception()) - ret = RTC.RTC_ERROR - - active_set = self._properties.getProperty("configuration.active_config", - "default") - - if self._configsets.haveConfig(active_set): - self._rtcout.RTC_DEBUG("Active configuration set: %s exists.", active_set) - self._configsets.activateConfigurationSet(active_set) - self._configsets.update(active_set) - self._rtcout.RTC_INFO("Initial active configuration set is %s.", active_set) - else: - self._rtcout.RTC_DEBUG("Active configuration set: %s does not exists.", active_set) - self._configsets.activateConfigurationSet("default") - self._configsets.update("default") - self._rtcout.RTC_INFO("Initial active configuration set is default-set.") - - self.postOnInitialize(0,ret) - return ret - - - ## - # @if jp - # - # @brief [ComponentAction CORBA interface] RTC νλ - # - # RTC ˴롣 - # RTC ͭνλϤǼ¹Ԥ롣 - # Υڥ졼ƤӽФη̤Ȥ onFinalize() Хåؿ - # ƤӽФ롣 - # - # @param self - # - # @return ReturnCode_t Υ꥿󥳡 - # - # @else - # - # @brief [ComponentAction CORBA interface] Finalize RTC - # - # The RTC is being destroyed. - # Any final RTC-specific tear-down logic should be performed here. - # - # @return - # - # @endif - def on_finalize(self): - self._rtcout.RTC_TRACE("on_finalize()") - ret = RTC.RTC_ERROR - try: - self.preOnFinalize(0) - ret = self.onFinalize() - except: - self._rtcout.RTC_ERROR(OpenRTM_aist.Logger.print_exception()) - ret = RTC.RTC_ERROR - self.postOnFinalize(0, ret) - return ret + # UniqueId bindContext(ExecutionContext_ptr exec_context); + + def bindContext(self, exec_context): + global ECOTHER_OFFSET + self._rtcout.RTC_TRACE("bindContext()") + # ID: 0 - (offset-1) : owned ec + # ID: offset - : participating ec + # owned ec index = ID + # participate ec index = ID - offset + ecs = exec_context._narrow(RTC.ExecutionContextService) + + if CORBA.is_nil(ecs): + return -1 + + # if m_ecMine has nil element, insert attached ec to there. + for i, ec in enumerate(self._ecMine): + if CORBA.is_nil(ec): + self._ecMine[i] = ecs + self.onAttachExecutionContext(i) + return i + # return i + ECOTHER_OFFSET + + # no space in the list, push back ec to the last. + OpenRTM_aist.CORBA_SeqUtil.push_back(self._ecMine, ecs) + + return int(len(self._ecMine) - 1) + # return int(len(self._ecMine) - 1 + ECOTHER_OFFSET) + + ## + # @if jp + # @brief [CORBA interface] ExecutionContextをdetachする + # + # 指定した ExecutionContext からこの RTC の所属を解除する。 + # このオペレーションは、ExecutionContextOperations::remove_component が呼ば + # れた際に呼び出される。返されたハンドルは他のクライアントで使用することを + # 想定していない。 + # + # 制約 + # - 指定された ExecutionContext に RTC がすでに所属していない場合には、 + # ReturnCode_t::PRECONDITION_NOT_MET が返される。 + # - 指定された ExecutionContext にたしいて対して RTC がActive 状態である場 + # 合には、 ReturnCode_t::PRECONDITION_NOT_MET が返される。 + # + # @param self + # @param ec_id 解除対象 ExecutionContextハンドル + # + # @return ReturnCode_t 型のリターンコード + # + # @else + # @brief [CORBA interface] Attach ExecutionContext. + # + # Inform this RTC that it is no longer participating in the given execution + # context. + # This operation is intended to be invoked by + # ExecutionContextOperations::remove_component. It is not intended for use + # by other clients. + # Constraints + # - This operation may not be invoked if this RTC is not already + # participating in the execution context. Such a call shall fail with + # ReturnCode_t::PRECONDITION_NOT_MET. + # - This operation may not be invoked if this RTC is Active in the indicated + # execution context. Otherwise, it shall fail with + # ReturnCode_t::PRECONDITION_NOT_MET. + # + # @param ec_id Dettaching ExecutionContext Handle + # + # @return + # + # @endif + # ReturnCode_t detach_context(UniqueId exec_handle) + + def detach_context(self, ec_id): + global ECOTHER_OFFSET + self._rtcout.RTC_TRACE("detach_context(%d)", ec_id) + len_ = len(self._ecOther) + + # ID: 0 - (offset-1) : owned ec + # ID: offset - : participating ec + # owned ec index = ID + # participate ec index = ID - offset + if (int(ec_id) < int(ECOTHER_OFFSET)) or \ + (int(ec_id - ECOTHER_OFFSET) > len_): + return RTC.BAD_PARAMETER + + index = int(ec_id - ECOTHER_OFFSET) + + if index < 0 or CORBA.is_nil(self._ecOther[index]): + return RTC.BAD_PARAMETER + + #OpenRTM_aist.CORBA_SeqUtil.erase(self._ecOther, index) + self._ecOther[index] = RTC.ExecutionContextService._nil + self.onDetachExecutionContext(ec_id) + return RTC.RTC_OK + ## + # @if jp + # + # @brief [ComponentAction CORBA interface] RTC の初期化 + # + # RTC が初期化され、Alive 状態に遷移する。 + # RTC 固有の初期化処理はここで実行する。 + # このオペレーション呼び出しの結果として onInitialize() コールバック関数が + # 呼び出される。 + # + # @param self + # + # @return ReturnCode_t 型のリターンコード + # + # @else + # + # @brief [ComponentAction CORBA interface] Initialize RTC + # + # The RTC has been initialized and entered the Alive state. + # Any RTC-specific initialization logic should be performed here. + # + # @return + # + # @endif + + def on_initialize(self): + self._rtcout.RTC_TRACE("on_initialize()") + ret = RTC.RTC_ERROR + try: + self.preOnInitialize(0) + self._rtcout.RTC_DEBUG("Calling onInitialize().") + ret = self.onInitialize() + if ret != RTC.RTC_OK: + self._rtcout.RTC_ERROR( + "onInitialize() returns an ERROR (%d)", ret._v) + else: + self._rtcout.RTC_DEBUG("onInitialize() succeeded.") + + except BaseException: + self._rtcout.RTC_ERROR(OpenRTM_aist.Logger.print_exception()) + ret = RTC.RTC_ERROR + + active_set = self._properties.getProperty("configuration.active_config", + "default") + + if self._configsets.haveConfig(active_set): + self._rtcout.RTC_DEBUG( + "Active configuration set: %s exists.", active_set) + self._configsets.activateConfigurationSet(active_set) + self._configsets.update(active_set) + self._rtcout.RTC_INFO( + "Initial active configuration set is %s.", active_set) + else: + self._rtcout.RTC_DEBUG( + "Active configuration set: %s does not exists.", active_set) + self._configsets.activateConfigurationSet("default") + self._configsets.update("default") + self._rtcout.RTC_INFO( + "Initial active configuration set is default-set.") + + self.postOnInitialize(0, ret) + return ret + + ## + # @if jp + # + # @brief [ComponentAction CORBA interface] RTC の終了 + # + # RTC が破棄される。 + # RTC 固有の終了処理はここで実行する。 + # このオペレーション呼び出しの結果として onFinalize() コールバック関数が + # 呼び出される。 + # + # @param self + # + # @return ReturnCode_t 型のリターンコード + # + # @else + # + # @brief [ComponentAction CORBA interface] Finalize RTC + # + # The RTC is being destroyed. + # Any final RTC-specific tear-down logic should be performed here. + # + # @return + # + # @endif + + def on_finalize(self): + self._rtcout.RTC_TRACE("on_finalize()") + ret = RTC.RTC_ERROR + try: + self.preOnFinalize(0) + ret = self.onFinalize() + except BaseException: + self._rtcout.RTC_ERROR(OpenRTM_aist.Logger.print_exception()) + ret = RTC.RTC_ERROR + self.postOnFinalize(0, ret) + return ret + + ## + # @if jp + # + # @brief [ComponentAction CORBA interface] RTC の開始 + # + # RTC が所属する ExecutionContext が Stopped 状態から Running 状態へ遷移 + # した場合に呼び出される。 + # このオペレーション呼び出しの結果として onStartup() コールバック関数が + # 呼び出される。 + # + # @param self + # @param ec_id 状態遷移した ExecutionContext の ID + # + # @return ReturnCode_t 型のリターンコード + # + # @else + # + # @brief [ComponentAction CORBA interface] StartUp RTC + # + # The given execution context, in which the RTC is participating, has + # transitioned from Stopped to Running. + # + # @param ec_id + # + # @return + # + # @endif + + def on_startup(self, ec_id): + self._rtcout.RTC_TRACE("on_startup(%d)", ec_id) + ret = RTC.RTC_ERROR + try: + self.preOnStartup(ec_id) + ret = self.onStartup(ec_id) + except BaseException: + self._rtcout.RTC_ERROR(OpenRTM_aist.Logger.print_exception()) + ret = RTC.RTC_ERROR + self.postOnStartup(ec_id, ret) + return ret + + ## + # @if jp + # + # @brief [ComponentAction CORBA interface] RTC の停止 + # + # RTC が所属する ExecutionContext が Running 状態から Stopped 状態へ遷移 + # した場合に呼び出される。 + # このオペレーション呼び出しの結果として onShutdown() コールバック関数が + # 呼び出される。 + # + # @param self + # @param ec_id 状態遷移した ExecutionContext の ID + # + # @return ReturnCode_t 型のリターンコード + # + # @else + # + # @brief [ComponentAction CORBA interface] ShutDown RTC + # + # The given execution context, in which the RTC is participating, has + # transitioned from Running to Stopped. + # + # @param ec_id + # + # @return + # + # @endif + + def on_shutdown(self, ec_id): + self._rtcout.RTC_TRACE("on_shutdown(%d)", ec_id) + ret = RTC.RTC_ERROR + try: + self.preOnShutdown(ec_id) + ret = self.onShutdown(ec_id) + except BaseException: + self._rtcout.RTC_ERROR(OpenRTM_aist.Logger.print_exception()) + ret = RTC.RTC_ERROR + self.postOnShutdown(ec_id, ret) + return ret + + ## + # @if jp + # + # @brief [ComponentAction CORBA interface] RTC の活性化 + # + # 所属する ExecutionContext から RTC が活性化された際に呼び出される。 + # このオペレーション呼び出しの結果として onActivated() コールバック関数が + # 呼び出される。 + # + # @param self + # @param ec_id 活性化 ExecutionContext の ID + # + # @return ReturnCode_t 型のリターンコード + # + # @else + # + # @brief [ComponentAction CORBA interface] Activate RTC + # + # The RTC has been activated in the given execution context. + # + # @param ec_id + # + # @return + # + # @endif + + def on_activated(self, ec_id): + self._rtcout.RTC_TRACE("on_activated(%d)", ec_id) + ret = RTC.RTC_ERROR + try: + self.preOnActivated(ec_id) + self._configsets.update() + ret = self.onActivated(ec_id) + self._portAdmin.activatePorts() + except BaseException: + self._rtcout.RTC_ERROR(OpenRTM_aist.Logger.print_exception()) + ret = RTC.RTC_ERROR + self.postOnActivated(ec_id, ret) + return ret + + ## + # @if jp + # + # @brief [ComponentAction CORBA interface] RTC の非活性化 + # + # 所属する ExecutionContext から RTC が非活性化された際に呼び出される。 + # このオペレーション呼び出しの結果として onDeactivated() コールバック関数が + # 呼び出される。 + # + # @param self + # @param ec_id 非活性化 ExecutionContext の ID + # + # @return ReturnCode_t 型のリターンコード + # + # @else + # + # @brief [ComponentAction CORBA interface] Deactivate RTC + # + # The RTC has been deactivated in the given execution context. + # + # @param ec_id + # + # @return + # + # @endif + + def on_deactivated(self, ec_id): + self._rtcout.RTC_TRACE("on_deactivated(%d)", ec_id) + ret = RTC.RTC_ERROR + try: + self.preOnDeactivated(ec_id) + self._portAdmin.deactivatePorts() + ret = self.onDeactivated(ec_id) + except BaseException: + self._rtcout.RTC_ERROR(OpenRTM_aist.Logger.print_exception()) + ret = RTC.RTC_ERROR + self.postOnDeactivated(ec_id, ret) + return ret + + ## + # @if jp + # + # @brief [ComponentAction CORBA interface] RTC のエラー状態への遷移 + # + # RTC が所属する ExecutionContext が Active 状態から Error 状態へ遷移した + # 場合に呼び出される。 + # このオペレーションは RTC が Error 状態に遷移した際に一度だけ呼び出される。 + # このオペレーション呼び出しの結果として onAborting() コールバック関数が + # 呼び出される。 + # + # @param self + # @param ec_id 状態遷移した ExecutionContext の ID + # + # @return ReturnCode_t 型のリターンコード + # + # @else + # + # @brief [ComponentAction CORBA interface] Transition Error State + # + # The RTC is transitioning from the Active state to the Error state in some + # execution context. + # This callback is invoked only a single time for time that the RTC + # transitions into the Error state from another state. This behavior is in + # contrast to that of on_error. + # + # @param ec_id + # + # @return + # + # @endif + + def on_aborting(self, ec_id): + self._rtcout.RTC_TRACE("on_aborting(%d)", ec_id) + ret = RTC.RTC_ERROR + try: + self.preOnAborting(ec_id) + ret = self.onAborting(ec_id) + except BaseException: + self._rtcout.RTC_ERROR(OpenRTM_aist.Logger.print_exception()) + ret = RTC.RTC_ERROR + self.postOnAborting(ec_id, ret) + return ret + + ## + # @if jp + # + # @brief [ComponentAction CORBA interface] RTC のエラー処理 + # + # RTC がエラー状態にいる際に呼び出される。 + # RTC がエラー状態の場合に、対象となる ExecutionContext のExecutionKind に + # 応じたタイミングで呼び出される。例えば、 + # - ExecutionKind が PERIODIC の場合、本オペレーションは + # DataFlowComponentAction::on_execute と on_state_update の替わりに、 + # 設定された順番、設定された周期で呼び出される。 + # - ExecutionKind が EVENT_DRIVEN の場合、本オペレーションは + # FsmParticipantAction::on_action が呼ばれた際に、替わりに呼び出される。 + # このオペレーション呼び出しの結果として onError() コールバック関数が呼び出 + # される。 + # + # @param self + # @param ec_id 対象 ExecutionContext の ID + # + # @return ReturnCode_t 型のリターンコード + # + # @else + # + # @brief [ComponentAction CORBA interface] Error Processing of RTC + # + # The RTC remains in the Error state. + # If the RTC is in the Error state relative to some execution context when + # it would otherwise be invoked from that context (according to the + # context’s ExecutionKind), this callback shall be invoked instead. + # For example, + # - If the ExecutionKind is PERIODIC, this operation shall be invoked in + # sorted order at the rate of the context instead of + # DataFlowComponentAction::on_execute and on_state_update. + # - If the ExecutionKind is EVENT_DRIVEN, this operation shall be invoked + # whenever FsmParticipantAction::on_action would otherwise have been + # invoked. + # + # @param ec_id + # + # @return + # + # @endif + + def on_error(self, ec_id): + self._rtcout.RTC_TRACE("on_error(%d)", ec_id) + ret = RTC.RTC_ERROR + try: + self.preOnError(ec_id) + ret = self.onError(ec_id) + except BaseException: + self._rtcout.RTC_ERROR(OpenRTM_aist.Logger.print_exception()) + ret = RTC.RTC_ERROR + self._configsets.update() + self.postOnError(ec_id, ret) + return ret + + ## + # @if jp + # + # @brief [ComponentAction CORBA interface] RTC のリセット + # + # Error 状態にある RTC のリカバリ処理を実行し、Inactive 状態に復帰させる + # 場合に呼び出される。 + # RTC のリカバリ処理が成功した場合は Inactive 状態に復帰するが、それ以外の + # 場合には Error 状態に留まる。 + # このオペレーション呼び出しの結果として onReset() コールバック関数が呼び + # 出される。 + # + # @param self + # @param ec_id リセット対象 ExecutionContext の ID + # + # @return ReturnCode_t 型のリターンコード + # + # @else + # + # @brief [ComponentAction CORBA interface] Resetting RTC + # + # The RTC is in the Error state. An attempt is being made to recover it such + # that it can return to the Inactive state. + # If the RTC was successfully recovered and can safely return to the + # Inactive state, this method shall complete with ReturnCode_t::OK. Any + # other result shall indicate that the RTC should remain in the Error state. + # + # @param ec_id + # + # @return + # + # @endif + + def on_reset(self, ec_id): + self._rtcout.RTC_TRACE("on_reset(%d)", ec_id) + ret = RTC.RTC_ERROR + try: + self.preOnReset(ec_id) + ret = self.onReset(ec_id) + except BaseException: + self._rtcout.RTC_ERROR(OpenRTM_aist.Logger.print_exception()) + ret = RTC.RTC_ERROR + self.postOnReset(ec_id, ret) + return ret + + # ============================================================ + # SDOPackage::SdoSystemElement + # ============================================================ + + ## + # @if jp + # + # @brief [SDO interface] Organization リストの取得 + # + # SDOSystemElement は0個もしくはそれ以上の Organization を所有することが + # 出来る。 SDOSystemElement が1つ以上の Organization を所有している場合 + # には、このオペレーションは所有する Organization のリストを返す。 + # もしOrganizationを一つも所有していないければ空のリストを返す。 + # + # @param self + # + # @return 所有している Organization リスト + # + # @exception SDONotExists ターゲットのSDOが存在しない。(本例外は、CORBA標準 + # システム例外のOBJECT_NOT_EXISTにマッピングされる) + # @exception NotAvailable SDOは存在するが応答がない。 + # @exception InternalError 内部的エラーが発生した。 + # + # @else + # + # @brief [SDO interface] Getting Organizations + # + # SDOSystemElement can be the owner of zero or more organizations. + # If the SDOSystemElement owns one or more Organizations, this operation + # returns the list of Organizations that the SDOSystemElement owns. + # If it does not own any Organization, it returns empty list. + # + # @return Owned Organization List + # + # @exception SDONotExists if the target SDO does not exist.(This exception + # is mapped to CORBA standard system exception + # OBJECT_NOT_EXIST.) + # @exception NotAvailable if the target SDO is reachable but cannot + # respond. + # @exception InternalError if the target SDO cannot execute the operation + # completely due to some internal error. + # + # @endif + # virtual SDOPackage::OrganizationList* get_owned_organizations() + + def get_owned_organizations(self): + self._rtcout.RTC_TRACE("get_owned_organizations()") + + return self._sdoOwnedOrganizations + + # ============================================================ + # SDOPackage::SDO + # ============================================================ + + ## + # @if jp + # + # @brief [SDO interface] SDO ID の取得 + # + # SDO ID を返すオペレーション。 + # このオペレーションは以下の型の例外を発生させる。 + # + # @param self + # + # @return リソースデータモデルで定義されている SDO の ID + # + # @exception SDONotExists ターゲットのSDOが存在しない。(本例外は、CORBA標準 + # システム例外のOBJECT_NOT_EXISTにマッピングされる) + # @exception NotAvailable SDOは存在するが応答がない。 + # @exception InternalError 内部的エラーが発生した。 + # + # @else + # + # @brief [SDO interface] Getting SDO ID + # + # This operation returns id of the SDO. + # This operation throws SDOException with one of the following types. + # + # @return id of the SDO defined in the resource data model. + # + # @exception SDONotExists if the target SDO does not exist.(This exception + # is mapped to CORBA standard system exception + # OBJECT_NOT_EXIST.) + # @exception NotAvailable if the target SDO is reachable but cannot + # respond. + # @exception InternalError if the target SDO cannot execute the operation + # completely due to some internal error. + # + # @endif + # virtual char* get_sdo_id() + + def get_sdo_id(self): + self._rtcout.RTC_TRACE("get_sdo_id()") + + return self._profile.instance_name + + ## + # @if jp + # + # @brief [SDO interface] SDO タイプの取得 + # + # SDO Type を返すオペレーション。 + # このオペレーションは以下の型の例外を発生させる。 + # + # @param self + # + # @return リソースデータモデルで定義されている SDO の Type + # + # @exception SDONotExists ターゲットのSDOが存在しない。(本例外は、CORBA標準 + # システム例外のOBJECT_NOT_EXISTにマッピングされる) + # @exception NotAvailable SDOは存在するが応答がない。 + # @exception InternalError 内部的エラーが発生した。 + # + # @else + # + # @brief [SDO interface] Getting SDO type + # + # This operation returns sdoType of the SDO. + # This operation throws SDOException with one of the following types. + # + # @return Type of the SDO defined in the resource data model. + # + # @exception SDONotExists if the target SDO does not exist.(This exception + # is mapped to CORBA standard system exception + # OBJECT_NOT_EXIST.) + # @exception NotAvailable if the target SDO is reachable but cannot + # respond. + # @exception InternalError if the target SDO cannot execute the operation + # completely due to some internal error. + # + # @endif + # virtual char* get_sdo_type() + + def get_sdo_type(self): + self._rtcout.RTC_TRACE("get_sdo_type()") + + return self._profile.description + + ## + # @if jp + # + # @brief [SDO interface] SDO DeviceProfile リストの取得 + # + # SDO の DeviceProfile を返すオペレーション。 SDO がハードウエアデバイス + # に関連付けられていない場合には、空の DeviceProfile が返される。 + # このオペレーションは以下の型の例外を発生させる。 + # + # @param self + # + # @return SDO DeviceProfile + # + # @exception SDONotExists ターゲットのSDOが存在しない。(本例外は、CORBA標準 + # システム例外のOBJECT_NOT_EXISTにマッピングされる) + # @exception NotAvailable SDOは存在するが応答がない。 + # @exception InternalError 内部的エラーが発生した。 + # + # @else + # + # @brief [SDO interface] Getting SDO DeviceProfile + # + # This operation returns the DeviceProfile of the SDO. If the SDO does not + # represent any hardware device, then a DeviceProfile with empty values + # are returned. + # This operation throws SDOException with one of the following types. + # + # @return The DeviceProfile of the SDO. + # + # @exception SDONotExists if the target SDO does not exist.(This exception + # is mapped to CORBA standard system exception + # OBJECT_NOT_EXIST.) + # @exception NotAvailable if the target SDO is reachable but cannot + # respond. + # @exception InternalError if the target SDO cannot execute the operation + # completely due to some internal error. + # + # @endif + # virtual SDOPackage::DeviceProfile* get_device_profile() + + def get_device_profile(self): + self._rtcout.RTC_TRACE("get_device_profile()") + + return self._SdoConfigImpl.getDeviceProfile() + + ## + # @if jp + # + # @brief [SDO interface] SDO ServiceProfile の取得 + # + # SDO が所有している Service の ServiceProfile を返すオペレーション。 + # SDO がサービスを一つも所有していない場合には、空のリストを返す。 + # このオペレーションは以下の型の例外を発生させる。 + # + # @param self + # + # @return SDO が提供する全ての Service の ServiceProfile。 + # + # @exception SDONotExists ターゲットのSDOが存在しない。(本例外は、CORBA標準 + # システム例外のOBJECT_NOT_EXISTにマッピングされる) + # @exception NotAvailable SDOは存在するが応答がない。 + # @exception InternalError 内部的エラーが発生した。 + # + # @else + # + # @brief [SDO interface] Getting SDO ServiceProfile + # + # This operation returns a list of ServiceProfiles that the SDO has. + # If the SDO does not provide any service, then an empty list is returned. + # This operation throws SDOException with one of the following types. + # + # @return List of ServiceProfiles of all the services the SDO is + # providing. + # + # @exception SDONotExists if the target SDO does not exist.(This exception + # is mapped to CORBA standard system exception + # OBJECT_NOT_EXIST.) + # @exception NotAvailable if the target SDO is reachable but cannot + # respond. + # @exception InternalError if the target SDO cannot execute the operation + # completely due to some internal error. + # + # @endif + # virtual SDOPackage::ServiceProfileList* get_service_profiles() + + def get_service_profiles(self): + self._rtcout.RTC_TRACE("get_service_profiles()") + self._sdoSvcProfiles = self._SdoConfigImpl.getServiceProfiles() + + return self._sdoSvcProfiles + + ## + # @if jp + # + # @brief [SDO interface] 特定のServiceProfileの取得 + # + # 引数 "id" で指定された名前のサービスの ServiceProfile を返す。 + # + # @param self + # @param _id SDO Service の ServiceProfile に関連付けられた識別子。 + # + # @return 指定された SDO Service の ServiceProfile。 + # + # @exception InvalidParameter "id" で指定した ServiceProfile が存在しない。 + # "id" が null。 + # @exception SDONotExists ターゲットのSDOが存在しない。(本例外は、CORBA標準 + # システム例外のOBJECT_NOT_EXISTにマッピングされる) + # @exception NotAvailable SDOは存在するが応答がない。 + # @exception InternalError 内部的エラーが発生した。 + # + # @else + # + # @brief [SDO interface] Getting Organizations + # + # This operation returns the ServiceProfile that is specified by the + # argument "id." + # + # @param _id The identifier referring to one of the ServiceProfiles. + # + # @return The profile of the specified service. + # + # @exception InvalidParameter if the ServiceProfile that is specified by + # the argument 'id' does not exist or if 'id' + # is 'null.' + # @exception SDONotExists if the target SDO does not exist.(This exception + # is mapped to CORBA standard system exception + # OBJECT_NOT_EXIST.) + # @exception NotAvailable If the target SDO is reachable but cannot + # respond. + # @exception InternalError If the target SDO cannot execute the operation + # completely due to some internal error. + # + # @endif + # virtual SDOPackage::ServiceProfile* get_service_profile(const char* id) + + def get_service_profile(self, _id): + self._rtcout.RTC_TRACE("get_service_profile(%s)", _id) + self._sdoSvcProfiles = self._SdoConfigImpl.getServiceProfiles() + if not _id: + raise SDOPackage.InvalidParameter( + "get_service_profile(): Empty name.") + + try: + index = OpenRTM_aist.CORBA_SeqUtil.find( + self._sdoSvcProfiles, self.svc_name(_id)) + + if index < 0: + raise SDOPackage.InvalidParameter( + "get_service_profile(): Not found") + + return self._sdoSvcProfiles[index] + except BaseException: + self._rtcout.RTC_ERROR(OpenRTM_aist.Logger.print_exception()) + raise SDOPackage.InternalError("get_service_profile()") + + ## + # @if jp + # + # @brief [SDO interface] 指定された SDO Service の取得 + # + # このオペレーションは引数 "id" で指定された名前によって区別される + # SDO の Service へのオブジェクト参照を返す。 SDO により提供される + # Service はそれぞれ一意の識別子により区別される。 + # + # @param self + # @param _id SDO Service に関連付けられた識別子。 + # + # @return 要求された SDO Service への参照。 + # + # + # @exception InvalidParameter "id" で指定した ServiceProfile が存在しない。 + # "id" が null。 + # @exception SDONotExists ターゲットのSDOが存在しない。(本例外は、CORBA標準 + # システム例外のOBJECT_NOT_EXISTにマッピングされる) + # @exception NotAvailable SDOは存在するが応答がない。 + # @exception InternalError 内部的エラーが発生した。 + # + # @else + # + # @brief [SDO interface] Getting specified SDO Service's reference + # + # This operation returns an object implementing an SDO's service that + # is identified by the identifier specified as an argument. Different + # services provided by an SDO are distinguished with different + # identifiers. See OMG SDO specification Section 2.2.8, "ServiceProfile," + # on page 2-12 for more details. + # + # @param _id The identifier referring to one of the SDO Service + # @return The object implementing the requested service. + # @exception InvalidParameter if argument “id” is null, or if the + # ServiceProfile that is specified by argument + # “id” does not exist. + # @exception SDONotExists if the target SDO does not exist.(This exception + # is mapped to CORBA standard system exception + # OBJECT_NOT_EXIST.) + # @exception NotAvailable If the target SDO is reachable but cannot + # respond. + # @exception InternalError If the target SDO cannot execute the operation + # completely due to some internal error. + # + # @endif + # virtual SDOPackage::SDOService_ptr get_sdo_service(const char* id) + + def get_sdo_service(self, _id): + self._rtcout.RTC_TRACE("get_sdo_service(%s)", _id) + self._sdoSvcProfiles = self._SdoConfigImpl.getServiceProfiles() + + if not _id: + raise SDOPackage.InvalidParameter("get_service(): Empty name.") + + index = OpenRTM_aist.CORBA_SeqUtil.find( + self._sdoSvcProfiles, self.svc_name(_id)) + + if index < 0: + raise SDOPackage.InvalidParameter("get_service(): Not found") + + return self._sdoSvcProfiles[index].service + + ## + # @if jp + # + # @brief [SDO interface] Configuration オブジェクトの取得 + # + # このオペレーションは Configuration interface への参照を返す。 + # Configuration interface は各 SDO を管理するためのインターフェースの + # ひとつである。このインターフェースは DeviceProfile, ServiceProfile, + # Organization で定義された SDO の属性値を設定するために使用される。 + # Configuration インターフェースの詳細については、OMG SDO specification + # の 2.3.5節, p.2-24 を参照のこと。 + # + # @param self + # + # @return SDO の Configuration インターフェースへの参照 + # + # @exception InterfaceNotImplemented SDOはConfigurationインターフェースを + # 持たない。 + # @exception SDONotExists ターゲットのSDOが存在しない。(本例外は、CORBA標準 + # システム例外のOBJECT_NOT_EXISTにマッピングされる) + # @exception NotAvailable SDOは存在するが応答がない。 + # @exception InternalError 内部的エラーが発生した。 + # + # @else + # + # @brief [SDO interface] Getting Configuration object + # + # This operation returns an object implementing the Configuration + # interface. The Configuration interface is one of the interfaces that + # each SDO maintains. The interface is used to configure the attributes + # defined in DeviceProfile, ServiceProfile, and Organization. + # See OMG SDO specification Section 2.3.5, "Configuration Interface," + # on page 2-24 for more details about the Configuration interface. + # + # @return The Configuration interface of an SDO. + # + # @exception InterfaceNotImplemented The target SDO has no Configuration + # interface. + # @exception SDONotExists if the target SDO does not exist.(This exception + # is mapped to CORBA standard system exception + # OBJECT_NOT_EXIST.) + # @exception NotAvailable The target SDO is reachable but cannot respond. + # @exception InternalError The target SDO cannot execute the operation + # completely due to some internal error. + # @endif + # virtual SDOPackage::Configuration_ptr get_configuration() + + def get_configuration(self): + self._rtcout.RTC_TRACE("get_configuration()") + if self._SdoConfig is None: + raise SDOPackage.InterfaceNotImplemented( + "InterfaceNotImplemented: get_configuration") + + return self._SdoConfig + + ## + # @if jp + # + # @brief [SDO interface] Monitoring オブジェクトの取得 + # + # このオペレーションは Monitoring interface への参照を返す。 + # Monitoring interface は SDO が管理するインターフェースの一つである。 + # このインターフェースは SDO のプロパティをモニタリングするために + # 使用される。 + # Monitoring interface の詳細については OMG SDO specification の + # 2.3.7節 "Monitoring Interface" p.2-35 を参照のこと。 + # + # @param self + # + # @return SDO の Monitoring interface への参照 + # + # @exception InterfaceNotImplemented SDOはConfigurationインターフェースを + # 持たない。 + # @exception SDONotExists ターゲットのSDOが存在しない。(本例外は、CORBA標準 + # システム例外のOBJECT_NOT_EXISTにマッピングされる) + # @exception NotAvailable SDOは存在するが応答がない。 + # @exception InternalError 内部的エラーが発生した。 + # + # @else + # + # @brief [SDO interface] Get Monitoring object + # + # This operation returns an object implementing the Monitoring interface. + # The Monitoring interface is one of the interfaces that each SDO + # maintains. The interface is used to monitor the properties of an SDO. + # See OMG SDO specification Section 2.3.7, "Monitoring Interface," on + # page 2-35 for more details about the Monitoring interface. + # + # @return The Monitoring interface of an SDO. + # + # @exception InterfaceNotImplemented The target SDO has no Configuration + # interface. + # @exception SDONotExists if the target SDO does not exist.(This exception + # is mapped to CORBA standard system exception + # OBJECT_NOT_EXIST.) + # @exception NotAvailable The target SDO is reachable but cannot respond. + # @exception InternalError The target SDO cannot execute the operation + # completely due to some internal error. + # @endif + # virtual SDOPackage::Monitoring_ptr get_monitoring() + + def get_monitoring(self): + self._rtcout.RTC_TRACE("get_monitoring()") + raise SDOPackage.InterfaceNotImplemented("Exception: get_monitoring") + + ## + # @if jp + # + # @brief [SDO interface] Organization リストの取得 + # + # SDO は0個以上の Organization (組織)に所属することができる。 もし SDO が + # 1個以上の Organization に所属している場合、このオペレーションは所属する + # Organization のリストを返す。SDO が どの Organization にも所属していない + # 場合には、空のリストが返される。 + # + # @param self + # + # @return SDO が所属する Organization のリスト。 + # + # @exception SDONotExists ターゲットのSDOが存在しない。(本例外は、CORBA標準 + # システム例外のOBJECT_NOT_EXISTにマッピングされる) + # @exception NotAvailable SDOは存在するが応答がない。 + # @exception InternalError 内部的エラーが発生した。 + # @else + # + # @brief [SDO interface] Getting Organizations + # + # An SDO belongs to zero or more organizations. If the SDO belongs to one + # or more organizations, this operation returns the list of organizations + # that the SDO belongs to. An empty list is returned if the SDO does not + # belong to any Organizations. + # + # @return The list of Organizations that the SDO belong to. + # + # @exception SDONotExists if the target SDO does not exist.(This exception + # is mapped to CORBA standard system exception + # OBJECT_NOT_EXIST.) + # @exception NotAvailable The target SDO is reachable but cannot respond. + # @exception InternalError The target SDO cannot execute the operation + # completely due to some internal error. + # @endif + # virtual SDOPackage::OrganizationList* get_organizations() + + def get_organizations(self): + self._rtcout.RTC_TRACE("get_organizations()") + self._sdoOrganizations = self._SdoConfigImpl.getOrganizations() + + return self._sdoOrganizations + + ## + # @if jp + # + # @brief [SDO interface] SDO Status リストの取得 + # + # このオペレーションは SDO のステータスを表す NVList を返す。 + # + # @param self + # + # @return SDO のステータス。 + # + # @exception SDONotExists ターゲットのSDOが存在しない。(本例外は、CORBA標準 + # システム例外のOBJECT_NOT_EXISTにマッピングされる) + # @exception NotAvailable SDOは存在するが応答がない。 + # @exception InternalError 内部的エラーが発生した。 + # + # @else + # + # @brief [SDO interface] Get SDO Status + # + # This operation returns an NVlist describing the status of an SDO. + # + # @return The actual status of an SDO. + # + # @exception SDONotExists if the target SDO does not exist.(This exception + # is mapped to CORBA standard system exception + # OBJECT_NOT_EXIST.) + # @exception NotAvailable The target SDO is reachable but cannot respond. + # @exception InternalError The target SDO cannot execute the operation + # completely due to some internal error. + # + # @endif + # virtual SDOPackage::NVList* get_status_list() + + def get_status_list(self): + self._rtcout.RTC_TRACE("get_status_list()") + + return self._sdoStatus + + ## + # @if jp + # + # @brief [SDO interface] SDO Status の取得 + # + # This operation returns the value of the specified status parameter. + # + # @param self + # @param name SDO のステータスを定義するパラメータ。 + # + # @return 指定されたパラメータのステータス値。 + # + # @exception SDONotExists ターゲットのSDOが存在しない。(本例外は、CORBA標準 + # システム例外のOBJECT_NOT_EXISTにマッピングされる) + # @exception NotAvailable SDOは存在するが応答がない。 + # @exception InvalidParameter 引数 "name" が null あるいは存在しない。 + # @exception InternalError 内部的エラーが発生した。 + # @else + # + # @brief [SDO interface] Get SDO Status + # + # @param name One of the parameters defining the "status" of an SDO. + # + # @return The value of the specified status parameter. + # + # @exception SDONotExists if the target SDO does not exist.(This exception + # is mapped to CORBA standard system exception + # OBJECT_NOT_EXIST.) + # @exception NotAvailable The target SDO is reachable but cannot respond. + # @exception InvalidParameter The parameter defined by "name" is null or + # does not exist. + # @exception InternalError The target SDO cannot execute the operation + # completely due to some internal error. + # + # + # @endif + # virtual CORBA::Any* get_status(const char* name) + + def get_status(self, name): + self._rtcout.RTC_TRACE("get_status(%s)", name) + index = OpenRTM_aist.CORBA_SeqUtil.find( + self._sdoStatus, self.nv_name(name)) + if index < 0: + raise SDOPackage.InvalidParameter("get_status(): Not found") + + try: + return any.to_any(self._sdoStatus[index].value) + except BaseException: + self._rtcout.RTC_ERROR(OpenRTM_aist.Logger.print_exception()) + raise SDOPackage.InternalError("get_status()") + + # ============================================================ + # Local interfaces + # ============================================================ + + ## + # @if jp + # + # @brief [local interface] インスタンス名の取得 + # + # ComponentProfile に設定されたインスタンス名を返す。 + # + # @param self + # + # @return インスタンス名 + # + # @else + # + # @endif + # const char* getInstanceName() + + def getInstanceName(self): + self._rtcout.RTC_TRACE("getInstanceName()") + return self._profile.instance_name + + ## + # @if jp + # + # @brief [local interface] インスタンス名の設定 + # + # ComponentProfile に指定されたインスタンス名を設定する。 + # + # @param self + # + # @param instance_name インスタンス名 + # + # @else + # + # @endif + # void setInstanceName(const char* instance_name); + + def setInstanceName(self, instance_name): + self._rtcout.RTC_TRACE("setInstanceName(%s)", instance_name) + self._properties.setProperty("instance_name", instance_name) + self._profile.instance_name = self._properties.getProperty( + "instance_name") + + ## + # @if jp + # + # @brief [local interface] 型名の取得 + # + # ComponentProfile に設定された型名を返す。 + # + # @param self + # + # @return 型名 + # + # @else + # + # @endif + # const char* getTypeName() + + def getTypeName(self): + self._rtcout.RTC_TRACE("getTypeName()") + return self._profile.type_name + + ## + # @if jp + # + # @brief [local interface] Description の取得 + # + # ComponentProfile に設定された Description を返す。 + # + # @param self + # + # @return Description + # + # @else + # + # @endif + # const char* getDescription() + + def getDescription(self): + self._rtcout.RTC_TRACE("getDescription()") + return self._profile.description + + ## + # @if jp + # + # @brief [local interface] バージョン情報の取得 + # + # ComponentProfile に設定されたバージョン情報を返す。 + # + # @param self + # + # @return バージョン情報 + # + # @else + # + # @endif + # const char* getVersion() + + def getVersion(self): + self._rtcout.RTC_TRACE("getVersion()") + return self._profile.version + + ## + # @if jp + # + # @brief [local interface] ベンダー情報の取得 + # + # ComponentProfile に設定されたベンダー情報を返す。 + # + # @param self + # + # @return ベンダー情報 + # + # @else + # + # @endif + # const char* getVendor() + + def getVendor(self): + self._rtcout.RTC_TRACE("getVendor()") + return self._profile.vendor + + ## + # @if jp + # + # @brief [local interface] カテゴリ情報の取得 + # + # ComponentProfile に設定されたカテゴリ情報を返す。 + # + # @param self + # + # @return カテゴリ情報 + # + # @else + # + # @endif + # const char* getCategory() + + def getCategory(self): + self._rtcout.RTC_TRACE("getCategory()") + return self._profile.category + + ## + # @if jp + # + # @brief [local interface] Naming Server 情報の取得 + # + # 設定された Naming Server 情報を返す。 + # + # @param self + # + # @return Naming Server リスト + # + # @else + # + # @endif + # std::vector getNamingNames(); + + def getNamingNames(self): + self._rtcout.RTC_TRACE("getNamingNames()") + return [s.strip() + for s in self._properties.getProperty("naming.names").split(",")] + + ## + # @if jp + # + # @brief [local interface] オブジェクトリファレンスの設定 + # + # RTC の CORBA オブジェクトリファレンスを設定する。 + # + # @param self + # @param rtobj オブジェクトリファレンス + # + # @else + # + # @endif + # void setObjRef(const RTObject_ptr rtobj); + + def setObjRef(self, rtobj): + self._rtcout.RTC_TRACE("setObjRef()") + self._objref = rtobj + return - ## - # @if jp - # - # @brief [ComponentAction CORBA interface] RTC γ - # - # RTC ° ExecutionContext Stopped ֤ Running ֤ - # ˸ƤӽФ롣 - # Υڥ졼ƤӽФη̤Ȥ onStartup() Хåؿ - # ƤӽФ롣 - # - # @param self - # @param ec_id ܤ ExecutionContext ID - # - # @return ReturnCode_t Υ꥿󥳡 - # - # @else - # - # @brief [ComponentAction CORBA interface] StartUp RTC - # - # The given execution context, in which the RTC is participating, has - # transitioned from Stopped to Running. - # - # @param ec_id - # - # @return - # - # @endif - def on_startup(self, ec_id): - self._rtcout.RTC_TRACE("on_startup(%d)", ec_id) - ret = RTC.RTC_ERROR - try: - self.preOnStartup(ec_id) - ret = self.onStartup(ec_id) - except: - self._rtcout.RTC_ERROR(OpenRTM_aist.Logger.print_exception()) - ret = RTC.RTC_ERROR - self.postOnStartup(ec_id, ret) - return ret + ## + # @if jp + # + # @brief [local interface] オブジェクトリファレンスの取得 + # + # 設定された CORBA オブジェクトリファレンスを取得する。 + # + # @param self + # + # @return オブジェクトリファレンス + # + # @else + # + # @endif + # RTObject_ptr getObjRef() const; + + def getObjRef(self): + self._rtcout.RTC_TRACE("getObjRef()") + return self._objref + + ## + # @if jp + # + # @brief [local interface] RTC のプロパティを設定する + # + # RTC が保持すべきプロパティを設定する。与えられるプロパティは、 + # ComponentProfile 等に設定されるべき情報を持たなければならない。 + # このオペレーションは通常 RTC が初期化される際に Manager から + # 呼ばれることを意図している。 + # + # @param self + # @param prop RTC のプロパティ + # + # @else + # + # @brief [local interface] Set RTC property + # + # This operation sets the properties to the RTC. The given property + # values should include information for ComponentProfile. + # Generally, this operation is designed to be called from Manager, when + # RTC is initialized + # + # @param prop Property for RTC. + # + # @endif + # void setProperties(const coil::Properties& prop); + + def setProperties(self, prop): + self._rtcout.RTC_TRACE("setProperties()") + self._properties.mergeProperties(prop) + self._profile.instance_name = self._properties.getProperty( + "instance_name") + self._profile.type_name = self._properties.getProperty("type_name") + self._profile.description = self._properties.getProperty("description") + self._profile.version = self._properties.getProperty("version") + self._profile.vendor = self._properties.getProperty("vendor") + self._profile.category = self._properties.getProperty("category") + + ## + # @if jp + # + # @brief [local interface] RTC のプロパティを取得する + # + # RTC が保持しているプロパティを返す。 + # RTCがプロパティを持たない場合は空のプロパティが返される。 + # + # @param self + # + # @return RTC のプロパティ + # + # @else + # + # @brief [local interface] Get RTC property + # + # This operation returns the properties of the RTC. + # Empty property would be returned, if RTC has no property. + # + # @return Property for RTC. + # + # @endif + # coil::Properties& getProperties(); + + def getProperties(self): + self._rtcout.RTC_TRACE("getProperties()") + return self._properties + + ## + # @if jp + # + # @brief コンフィギュレーションパラメータの設定 + # + # コンフィギュレーションパラメータと変数をバインドする + # \としてコンフィギュレーションパラメータのデータ型を指定する。 + # + # @param self + # @param param_name コンフィギュレーションパラメータ名 + # @param var コンフィギュレーションパラメータ格納用変数 + # @param def_val コンフィギュレーションパラメータデフォルト値 + # @param trans 文字列変換用関数(デフォルト値:None) + # + # @return 設定結果(設定成功:true,設定失敗:false) + # + # @else + # + # @endif + # template + # bool bindParameter(const char* param_name, VarType& var, + # const char* def_val, + # bool (*trans)(VarType&, const char*) = coil::stringTo) + + def bindParameter(self, param_name, var, + def_val, trans=None): + self._rtcout.RTC_TRACE("bindParameter()") + if trans is None: + trans_ = OpenRTM_aist.stringTo + else: + trans_ = trans + self._configsets.bindParameter(param_name, var, def_val, trans_) + return True + ## + # @if jp + # + # @brief コンフィギュレーションサービスを取得する + # + # コンフィギュレーションサービスオブジェクトを取得する。このサービ + # スオブジェクトを利用して、コンフィギュレーションパラメータの操作 + # を行うことができる。主な操作としては、 + # + # - unbindParameter(): パラメータのアンバインド + # - update(): パラメータの更新 + # - update(set_name): 特定のセットの更新 + # - update(set_name, param_name): 特定のセットのパラメータの更新 + # - isExist(): パラメータの存在確認 + # - isChanged(): パラメータが変更されたかの確認 + # - changedParameters(): 変更されたパラメータのリスト + # - getActiveId(): アクティブセット名の取得 + # - haveConfig(config_id): コンフィグセットを持っているかどうか + # - getConfigurationSets(): 全コンフィギュレーションセットの取得 + # - getConfigurationSet(set_id): 特定セットを取得 + # + # コールバック関連 + # - addConfigurationParamListener(): リスナの追加 + # - removeConfigurationParamListener(): リスナの削除 + # - addConfigurationSetListener(): リスナの追加 + # - removeConfigurationSetListener(): リスナの削除 + # - addConfigurationSetNameListener(): リスナの追加 + # - removeConfigurationSetNameListener(): リスナの削除 + # + # 詳細はConfigAdminクラスリファレンスを参照のこと。 + # + # @return ConfigAdmin object + # + # @else + # + # @brief Getting configuration service + # + # This operation returns configuration service object. By using + # this service, user can manipulate configuration + # parameters. Mainly the following operations are supported. + # + # - unbindParameter(): Unbinding parameters + # - update(): Updateing parameters + # - update(set_name): Updating a specific configuration set + # - update(set_name, param_name): Updating specific parameter in a set + # - isExist(): Checking existence of a parameter + # - isChanged(): Check if a parameter was updated + # - changedParameters(): Getting changed parameter list + # - getActiveId(): Getting active configuration set name + # - haveConfig(config_id): Checking if having a specified configuration set + # - getConfigurationSets(): getting all the configuration sets + # - getConfigurationSet(set_id): Getting a configuration set + # + # Callback related member functions + # - addConfigurationParamListener(): Adding listener + # - removeConfigurationParamListener(): Removing listener + # - addConfigurationSetListener(): Adding listener + # - removeConfigurationSetListener(): Removing listener + # - addConfigurationSetNameListener(): Adding listener + # - removeConfigurationSetNameListener(): Removing listener + # + # See details in the ConfigAdmin class reference + # + # @return ConfigAdmin object + # + # @endif + # + # ConfigAdmin& getConfigService() { return m_configsets; } + + def getConfigService(self): + return self._configsets + + ## + # @if jp + # + # @brief コンフィギュレーションパラメータの更新(ID指定) + # + # 指定したIDのコンフィギュレーションセットに設定した値で、 + # コンフィギュレーションパラメータの値を更新する + # + # @param self + # @param config_set 設定対象のコンフィギュレーションセットID + # + # @else + # + # @endif + # void updateParameters(const char* config_set); + def updateParameters(self, config_set): + self._rtcout.RTC_TRACE("updateParameters(%s)", config_set) + self._configsets.update(config_set) + return - ## - # @if jp - # - # @brief [ComponentAction CORBA interface] RTC - # - # RTC ° ExecutionContext Running ֤ Stopped ֤ - # ˸ƤӽФ롣 - # Υڥ졼ƤӽФη̤Ȥ onShutdown() Хåؿ - # ƤӽФ롣 - # - # @param self - # @param ec_id ܤ ExecutionContext ID - # - # @return ReturnCode_t Υ꥿󥳡 - # - # @else - # - # @brief [ComponentAction CORBA interface] ShutDown RTC - # - # The given execution context, in which the RTC is participating, has - # transitioned from Running to Stopped. - # - # @param ec_id - # - # @return - # - # @endif - def on_shutdown(self, ec_id): - self._rtcout.RTC_TRACE("on_shutdown(%d)", ec_id) - ret = RTC.RTC_ERROR - try: - self.preOnShutdown(ec_id) - ret = self.onShutdown(ec_id) - except: - self._rtcout.RTC_ERROR(OpenRTM_aist.Logger.print_exception()) - ret = RTC.RTC_ERROR - self.postOnShutdown(ec_id, ret) - return ret + ## + # @if jp + # + # @brief [local interface] Port を登録する + # + # RTC が保持するPortを登録する。 + # Port を外部からアクセス可能にするためには、このオペレーションにより + # 登録されていなければならない。登録される Port はこの RTC 内部において + # PortProfile.name により区別される。したがって、Port は RTC 内において、 + # ユニークな PortProfile.name を持たなければならない。 + # 登録された Port は内部で適切にアクティブ化された後、その参照と + # オブジェクト参照がリスト内に保存される。 + # + # @param self + # @param port RTC に登録する Port + # @param port_type if port is PortBase, port_type is None, + # if port is PortService, port_type is True + # + # @else + # + # @brief [local interface] Register Port + # + # This operation registers a Port to be held by this RTC. + # In order to enable access to the Port from outside of RTC, the Port + # must be registered by this operation. The Port that is registered by + # this operation would be identified by PortProfile.name in the inside of + # RTC. Therefore, the Port should have unique PortProfile.name in the RTC. + # The registering Port would be activated properly, and the reference + # and the object reference would be stored in lists in RTC. + # + # @param port Port which is registered in the RTC + # + # @endif + # void registerPort(PortBase& port); + + def registerPort(self, port): + self._rtcout.RTC_TRACE("registerPort()") + if not self.addPort(port): + self._rtcout.RTC_ERROR("addPort(PortBase&) failed.") + return + # void registerPort(PortService_ptr port); + # def registerPortByReference(self, port_ref): + # self._rtcout.RTC_TRACE("registerPortByReference()") + # self.addPortByReference(port_ref) + # return + + # new interface. since 1.0.0-RELEASE + # void addPort(PortBase& port); + def addPort(self, port): + self._rtcout.RTC_TRACE("addPort()") + if isinstance(port, OpenRTM_aist.CorbaPort): + self._rtcout.RTC_TRACE("addPort(CorbaPort)") + propkey = "port.corbaport." + prop = self._properties.getNode(propkey) + if prop: + self._properties.getNode(propkey).mergeProperties( + self._properties.getNode("port.corba")) + port.init(self._properties.getNode(propkey)) + port.setOwner(self.getObjRef()) + + elif isinstance(port, OpenRTM_aist.PortBase): + self._rtcout.RTC_TRACE("addPort(PortBase)") + port.setOwner(self.getObjRef()) + port.setPortConnectListenerHolder(self._portconnListeners) + self.onAddPort(port.getPortProfile()) + + elif isinstance(port, RTC._objref_PortService): + self._rtcout.RTC_TRACE("addPort(PortService)") + return self._portAdmin.addPort(port) + + # new interface. since 1.0.0-RELEASE + # void addPort(PortService_ptr port); + # def addPortByReference(self, port_ref): + # self._rtcout.RTC_TRACE("addPortByReference()") + # self._portAdmin.registerPortByReference(port_ref) + # return + + ## + # @if jp + # + # @brief [local interface] DataInPort を登録する + # + # RTC が保持する DataInPort を登録する。 + # Port のプロパティにデータポートであること("port.dataport")、 + # TCPを使用すること("tcp_any")を設定するとともに、 DataInPort の + # インスタンスを生成し、登録する。 + # + # @param self + # @param name port 名称 + # @param inport 登録対象 DataInPort + # + # @else + # + # @endif + + def registerInPort(self, name, inport): + self._rtcout.RTC_TRACE("registerInPort(%s)", name) + if not self.addInPort(name, inport): + self._rtcout.RTC_ERROR("addInPort(%s) failed.", name) + return - ## - # @if jp - # - # @brief [ComponentAction CORBA interface] RTC γ - # - # ° ExecutionContext RTC 줿ݤ˸ƤӽФ롣 - # Υڥ졼ƤӽФη̤Ȥ onActivated() Хåؿ - # ƤӽФ롣 - # - # @param self - # @param ec_id ExecutionContext ID - # - # @return ReturnCode_t Υ꥿󥳡 - # - # @else - # - # @brief [ComponentAction CORBA interface] Activate RTC - # - # The RTC has been activated in the given execution context. - # - # @param ec_id - # - # @return - # - # @endif - def on_activated(self, ec_id): - self._rtcout.RTC_TRACE("on_activated(%d)", ec_id) - ret = RTC.RTC_ERROR - try: - self.preOnActivated(ec_id) - self._configsets.update() - ret = self.onActivated(ec_id) - self._portAdmin.activatePorts() - except: - self._rtcout.RTC_ERROR(OpenRTM_aist.Logger.print_exception()) - ret = RTC.RTC_ERROR - self.postOnActivated(ec_id, ret) - return ret + # new interface. since 1.0.0-RELEASE + def addInPort(self, name, inport): + self._rtcout.RTC_TRACE("addInPort(%s)", name) + + propkey = "port.inport." + name + prop_ = copy.copy(self._properties.getNode(propkey)) + prop_.mergeProperties(self._properties.getNode("port.inport.dataport")) + + ret = self.addPort(inport) + + if not ret: + self._rtcout.RTC_ERROR("addInPort() failed.") + return ret + + inport.init(self._properties.getNode(propkey)) + self._inports.append(inport) + return ret + + ## + # @if jp + # + # @brief [local interface] DataOutPort を登録する + # + # RTC が保持する DataOutPor tを登録する。 + # Port のプロパティにデータポートであること("port.dataport")、 + # TCPを使用すること("tcp_any")を設定するとともに、 DataOutPort の + # インスタンスを生成し、登録する。 + # + # @param self + # @param name port 名称 + # @param outport 登録対象 DataInPort + # + # @else + # + # @endif + # void registerOutPort(const char* name, OutPortBase& outport); + + def registerOutPort(self, name, outport): + self._rtcout.RTC_TRACE("registerOutPort(%s)", name) + if not self.addOutPort(name, outport): + self._rtcout.RTC_ERROR("addOutPort(%s) failed.", name) + return + # new interface. since 1.0.0-RELEASE + # void addOutPort(const char* name, OutPortBase& outport); + def addOutPort(self, name, outport): + self._rtcout.RTC_TRACE("addOutPort(%s)", name) + + propkey = "port.outport." + name + prop_ = copy.copy(self._properties.getNode(propkey)) + prop_.mergeProperties( + self._properties.getNode("port.outport.dataport")) + + ret = self.addPort(outport) + + if not ret: + self._rtcout.RTC_ERROR("addOutPort() failed.") + return ret + + outport.init(self._properties.getNode(propkey)) + self._outports.append(outport) + return ret + + ## + # @if jp + # + # @brief [local interface] InPort の登録を削除する + # + # RTC が保持するInPortの登録を削除する。 + # + # @param port 削除対象 Port + # @return 削除結果(削除成功:true,削除失敗:false) + # + # @else + # + # @brief [local interface] Unregister InPort + # + # This operation unregisters a InPort held by this RTC. + # + # @param port Port which is unregistered + # @return Unregister result (Successful:true, Failed:false) + # + # @endif + # + # bool removeInPort(InPortBase& port); + + def removeInPort(self, port): + self._rtcout.RTC_TRACE("removeInPort()") + ret = self.removePort(port) + + if ret: + for inport in self._inports: + if port == inport: + + self._inports.remove(port) + + return True - ## - # @if jp - # - # @brief [ComponentAction CORBA interface] RTC - # - # ° ExecutionContext RTC 줿ݤ˸ƤӽФ롣 - # Υڥ졼ƤӽФη̤Ȥ onDeactivated() Хåؿ - # ƤӽФ롣 - # - # @param self - # @param ec_id ExecutionContext ID - # - # @return ReturnCode_t Υ꥿󥳡 - # - # @else - # - # @brief [ComponentAction CORBA interface] Deactivate RTC - # - # The RTC has been deactivated in the given execution context. - # - # @param ec_id - # - # @return - # - # @endif - def on_deactivated(self, ec_id): - self._rtcout.RTC_TRACE("on_deactivated(%d)", ec_id) - ret = RTC.RTC_ERROR - try: - self.preOnDeactivated(ec_id) - self._portAdmin.deactivatePorts() - ret = self.onDeactivated(ec_id) - except: - self._rtcout.RTC_ERROR(OpenRTM_aist.Logger.print_exception()) - ret = RTC.RTC_ERROR - self.postOnDeactivated(ec_id, ret) - return ret + return False + ## + # @if jp + # + # @brief [local interface] OutPort の登録を削除する + # + # RTC が保持するOutPortの登録を削除する。 + # + # @param port 削除対象 Port + # @return 削除結果(削除成功:true,削除失敗:false) + # + # @else + # + # @brief [local interface] Unregister OutPort + # + # This operation unregisters a OutPort held by this RTC. + # + # @param port Port which is unregistered + # @return Unregister result (Successful:true, Failed:false) + # + # @endif + # + # bool removeOutPort(OutPortBase& port); + + def removeOutPort(self, port): + self._rtcout.RTC_TRACE("removeOutPort()") + ret = self.removePort(port) + + if ret: + for outport in self._outports: + if port == outport: + + self._outports.remove(port) + + return True - ## - # @if jp - # - # @brief [ComponentAction CORBA interface] RTC Υ顼֤ؤ - # - # RTC ° ExecutionContext Active ֤ Error ֤ܤ - # ˸ƤӽФ롣 - # Υڥ졼 RTC Error ֤ܤݤ˰٤ƤӽФ롣 - # Υڥ졼ƤӽФη̤Ȥ onAborting() Хåؿ - # ƤӽФ롣 - # - # @param self - # @param ec_id ܤ ExecutionContext ID - # - # @return ReturnCode_t Υ꥿󥳡 - # - # @else - # - # @brief [ComponentAction CORBA interface] Transition Error State - # - # The RTC is transitioning from the Active state to the Error state in some - # execution context. - # This callback is invoked only a single time for time that the RTC - # transitions into the Error state from another state. This behavior is in - # contrast to that of on_error. - # - # @param ec_id - # - # @return - # - # @endif - def on_aborting(self, ec_id): - self._rtcout.RTC_TRACE("on_aborting(%d)", ec_id) - ret = RTC.RTC_ERROR - try: - self.preOnAborting(ec_id) - ret = self.onAborting(ec_id) - except: - self._rtcout.RTC_ERROR(OpenRTM_aist.Logger.print_exception()) - ret = RTC.RTC_ERROR - self.postOnAborting(ec_id, ret) - return ret + return False + ## + # @if jp + # + # @brief [local interface] Port の登録を削除する + # + # RTC が保持するPortの登録を削除する。 + # + # @param self + # @param port 削除対象 Port + # + # @else + # + # @brief [local interface] Unregister Port + # + # This operation unregisters a Port to be held by this RTC. + # + # @param port Port which is unregistered in the RTC + # + # @endif + # void RTObject_impl::deletePort(PortBase& port) + + def deletePort(self, port): + self._rtcout.RTC_TRACE("deletePort()") + if not self.removePort(port): + self._rtcout.RTC_ERROR("removePort() failed.") + return - ## - # @if jp - # - # @brief [ComponentAction CORBA interface] RTC Υ顼 - # - # RTC 顼֤ˤݤ˸ƤӽФ롣 - # RTC 顼֤ξˡоݤȤʤ ExecutionContext ExecutionKind - # ߥ󥰤ǸƤӽФ롣㤨С - # - ExecutionKind PERIODIC ξ硢ܥڥ졼 - # DataFlowComponentAction::on_execute on_state_update ؤˡ - # ꤵ줿֡ꤵ줿ǸƤӽФ롣 - # - ExecutionKind EVENT_DRIVEN ξ硢ܥڥ졼 - # FsmParticipantAction::on_action ƤФ줿ݤˡؤ˸ƤӽФ롣 - # Υڥ졼ƤӽФη̤Ȥ onError() ХåؿƤӽ - # 롣 - # - # @param self - # @param ec_id о ExecutionContext ID - # - # @return ReturnCode_t Υ꥿󥳡 - # - # @else - # - # @brief [ComponentAction CORBA interface] Error Processing of RTC - # - # The RTC remains in the Error state. - # If the RTC is in the Error state relative to some execution context when - # it would otherwise be invoked from that context (according to the - # contexts ExecutionKind), this callback shall be invoked instead. - # For example, - # - If the ExecutionKind is PERIODIC, this operation shall be invoked in - # sorted order at the rate of the context instead of - # DataFlowComponentAction::on_execute and on_state_update. - # - If the ExecutionKind is EVENT_DRIVEN, this operation shall be invoked - # whenever FsmParticipantAction::on_action would otherwise have been - # invoked. - # - # @param ec_id - # - # @return - # - # @endif - def on_error(self, ec_id): - self._rtcout.RTC_TRACE("on_error(%d)", ec_id) - ret = RTC.RTC_ERROR - try: - self.preOnError(ec_id) - ret = self.onError(ec_id) - except: - self._rtcout.RTC_ERROR(OpenRTM_aist.Logger.print_exception()) - ret = RTC.RTC_ERROR - self._configsets.update() - self.postOnError(ec_id, ret) - return ret + # new interface. since 1.0.0-RELEASE + def removePort(self, port): + self._rtcout.RTC_TRACE("removePort()") + if isinstance(port, OpenRTM_aist.PortBase) or isinstance( + port, OpenRTM_aist.CorbaPort): + self.onRemovePort(port.getPortProfile()) + return self._portAdmin.removePort(port) + + ## + # @if jp + # + # @brief [local interface] 名前指定により Port の登録を削除する + # + # 名称を指定して RTC が保持するPortの登録を削除する。 + # + # @param self + # @param port_name 削除対象 Port 名 + # + # @else + # + # @endif + + def deletePortByName(self, port_name): + self._rtcout.RTC_TRACE("deletePortByName(%s)", port_name) + self._portAdmin.deletePortByName(port_name) + return + ## + # @if jp + # + # @brief [local interface] 実行コンテキストを取得する + # + # get_context() と同じ機能のローカル版。違いはない。 + # この関数は以下の関数内で呼ばれることを前提としている。 + # + # - onStartup() + # - onShutdown() + # - onActivated() + # - onDeactivated() + # - onExecute() + # - onAborting() + # - onError() + # - onReset() + # - onStateUpdate() + # - onRateChanged() + # + # この関数の引数はこれらの関数の引数 UniquieID exec_handle でなけ + # ればならない。 + # + # @param ec_id 上記関数の第1引数 exec_handle を渡す必要がある。 + # + # @else + # + # @brief [local interface] Getting current execution context + # + # This function is the local version of get_context(). completely + # same as get_context() function. This function is assumed to be + # called from the following functions. + # + # - onStartup() + # - onShutdown() + # - onActivated() + # - onDeactivated() + # - onExecute() + # - onAborting() + # - onError() + # - onReset() + # - onStateUpdate() + # - onRateChanged() + # + # The argument of this function should be the first argument + # (UniqueId ec_id) of the above functions. + # + # @param ec_id The above functions' first argument "exec_handle." + # + # @endif + # + # ExecutionContext_ptr getExecutionContext(RTC::UniqueId ec_id); + + def getExecutionContext(self, ec_id): + return self.get_context(ec_id) + + ## + # @if jp + # + # @brief [local interface] 実行コンテキストの実行レートを取得する + # + # 現在実行中の実行コンテキストの実行レートを取得する。実行コンテキ + # ストのKindがPERIODIC以外の場合の動作は未定義である。この関数は以 + # 下の関数内で呼ばれることを前提としている。 + # + # - onStartup() + # - onShutdown() + # - onActivated() + # - onDeactivated() + # - onExecute() + # - onAborting() + # - onError() + # - onReset() + # - onStateUpdate() + # - onRateChanged() + # + # この関数の引数はこれらの関数の引数 UniquieID exec_handle でなけ + # ればならない。 + # + # @param ec_id 上記関数の第1引数 exec_handle を渡す必要がある。 + # + # @else + # + # @brief [local interface] Getting current context' execution rate + # + # This function returns current execution rate in this + # context. If this context's kind is not PERIODC, behavior is not + # defined. This function is assumed to be called from the + # following functions. + # + # - onStartup() + # - onShutdown() + # - onActivated() + # - onDeactivated() + # - onExecute() + # - onAborting() + # - onError() + # - onReset() + # - onStateUpdate() + # - onRateChanged() + # + # The argument of this function should be the first argument + # (UniqueId ec_id) of the above functions. + # + # @param ec_id The above functions' first argument "exec_handle." + # + # @endif + # + # double getExecutionRate(RTC::UniqueId ec_id); + def getExecutionRate(self, ec_id): + ec = self.getExecutionContext(ec_id) + if CORBA.is_nil(ec): + return 0.0 + + return ec.get_rate() + + ## + # @if jp + # + # @brief [local interface] 実行コンテキストの実行レートを設定する + # + # 現在実行中の実行コンテキストの実行レートを設定する。実行コンテキ + # ストのKindがPERIODIC以外の場合の動作は未定義である。この関数は以 + # 下の関数内で呼ばれることを前提としている。 + # + # - onStartup() + # - onShutdown() + # - onActivated() + # - onDeactivated() + # - onExecute() + # - onAborting() + # - onError() + # - onReset() + # - onStateUpdate() + # - onRateChanged() + # + # この関数の引数はこれらの関数の引数 UniquieID exec_handle でなけ + # ればならない。 + # + # @param ec_id 上記関数の第1引数 exec_handle を渡す必要がある。 + # @param rate 実行レートを [Hz] で与える + # + # @else + # + # @brief [local interface] Setting current context' execution rate + # + # This function sets a execution rate in the context. If this + # context's kind is not PERIODC, behavior is not defined. This + # function is assumed to be called from the following functions. + # + # - onStartup() + # - onShutdown() + # - onActivated() + # - onDeactivated() + # - onExecute() + # - onAborting() + # - onError() + # - onReset() + # - onStateUpdate() + # - onRateChanged() + # + # The argument of this function should be the first argument + # (UniqueId ec_id) of the above functions. + # + # @param ec_id The above functions' first argument "exec_handle." + # @param rate Execution rate in [Hz]. + # + # @endif + # + # ReturnCode_t setExecutionRate(RTC::UniqueId ec_id, double rate); + + def setExecutionRate(self, ec_id, rate): + ec = self.getExecutionContext(ec_id) + if CORBA.is_nil(ec): + return RTC.RTC_ERROR + ec.set_rate(rate) + return RTC.RTC_OK - ## - # @if jp - # - # @brief [ComponentAction CORBA interface] RTC Υꥻå - # - # Error ֤ˤ RTC ΥꥫХ¹ԤInactive ֤ - # ˸ƤӽФ롣 - # RTC ΥꥫХ Inactive ֤뤬ʳ - # ˤ Error ֤αޤ롣 - # Υڥ졼ƤӽФη̤Ȥ onReset() ХåؿƤ - # Ф롣 - # - # @param self - # @param ec_id ꥻåо ExecutionContext ID - # - # @return ReturnCode_t Υ꥿󥳡 - # - # @else - # - # @brief [ComponentAction CORBA interface] Resetting RTC - # - # The RTC is in the Error state. An attempt is being made to recover it such - # that it can return to the Inactive state. - # If the RTC was successfully recovered and can safely return to the - # Inactive state, this method shall complete with ReturnCode_t::OK. Any - # other result shall indicate that the RTC should remain in the Error state. - # - # @param ec_id - # - # @return - # - # @endif - def on_reset(self, ec_id): - self._rtcout.RTC_TRACE("on_reset(%d)", ec_id) - ret = RTC.RTC_ERROR - try: - self.preOnReset(ec_id) - ret = self.onReset(ec_id) - except: - self._rtcout.RTC_ERROR(OpenRTM_aist.Logger.print_exception()) - ret = RTC.RTC_ERROR - self.postOnReset(ec_id, ret) - return ret + ## + # @if jp + # + # @brief [local interface] 実行コンテキストの所有権を調べる + # + # 現在実行中の実行コンテキストの所有権を調べる。この関数は以下の関 + # 数内で呼ばれることを前提としている。 + # + # - onStartup() + # - onShutdown() + # - onActivated() + # - onDeactivated() + # - onExecute() + # - onAborting() + # - onError() + # - onReset() + # - onStateUpdate() + # - onRateChanged() + # + # この関数の引数はこれらの関数の引数 UniquieID exec_handle でなけ + # ればならない。 + # + # @param ec_id 上記関数の第1引数 exec_handle を渡す必要がある。 + # @return true: 自身の実行コンテキスト、false: 他の実行コンテキスト + # + # @else + # + # @brief [local interface] Checking if the current context is own context + # + # This function checks if the current context is own execution + # context. This function is assumed to be called from the + # following functions. + # + # - onStartup() + # - onShutdown() + # - onActivated() + # - onDeactivated() + # - onExecute() + # - onAborting() + # - onError() + # - onReset() + # - onStateUpdate() + # - onRateChanged() + # + # The argument of this function should be the first argument + # (UniqueId ec_id) of the above functions. + # + # @param ec_id The above functions' first argument "exec_handle." + # @return true: Own context, false: other's context + # + # @endif + # + # bool isOwnExecutionContext(RTC::UniqueId ec_id); + + def isOwnExecutionContext(self, ec_id): + global ECOTHER_OFFSET + if ec_id < ECOTHER_OFFSET: + return True + return False + ## + # @if jp + # + # @brief [local interface] 状態を Inactive に遷移させる + # + # 状態を Active から Inactive に遷移させる。この関数は以下の関 + # 数内で呼ばれることを前提としている。 + # + # - onActivated() + # - onExecute() + # - onStateUpdate() + # + # この関数の引数は上記の関数の引数 UniquieID exec_handle でなけ + # ればならない。 + # + # @param ec_id 上記関数の第1引数 exec_handle を渡す必要がある。 + # @return リターンコード + # + # @else + # + # @brief [local interface] Make transition to Inactive state + # + # This function makes transition from Active to Inactive + # state. This function is assumed to be called from the following + # functions. + # + # - onActivated() + # - onExecute() + # - onStateUpdate() + # + # The argument of this function should be the first argument + # (UniqueId ec_id) of the above function. + # + # @param ec_id The above functions' first argument "exec_handle." + # @return Return code + # + # @endif + # + # ReturnCode_t deactivate(RTC::UniqueId ec_id); + + def deactivate(self, ec_id): + ec = self.getExecutionContext(ec_id) + if CORBA.is_nil(ec): + return RTC.RTC_ERROR + return ec.deactivate_component(self.getObjRef()) + + ## + # @if jp + # + # @brief [local interface] 状態を Active に遷移させる + # + # 状態を Inactive から Active に遷移させる。この関数は以下の関 + # 数内で呼ばれることを前提としている。 + # + # - onStartup() + # - onDeactivated() + # + # この関数の引数は上記の関数の引数 UniquieID exec_handle でなけ + # ればならない。 + # + # @param ec_id 上記関数の第1引数 exec_handle を渡す必要がある。 + # @return リターンコード + # + # @else + # + # @brief [local interface] Make transition to Active state + # + # This function makes transition from Inactive to Active + # state. This function is assumed to be called from the following + # functions. + # + # - onStartup() + # - onDeactivated() + # + # The argument of this function should be the first argument + # (UniqueId ec_id) of the above function. + # + # @param ec_id The above functions' first argument "exec_handle." + # @return Return code + # + # @endif + # + # ReturnCode_t activate(RTC::UniqueId ec_id); + + def activate(self, ec_id): + ec = self.getExecutionContext(ec_id) + if CORBA.is_nil(ec): + return RTC.RTC_ERROR + return ec.activate_component(self.getObjRef()) + + ## + # @if jp + # + # @brief [local interface] 状態をリセットし Inactive に遷移させる + # + # 状態を Error から Inactive に遷移させる。この関数は以下の関 + # 数内で呼ばれることを前提としている。 + # + # - onError() + # + # この関数の引数は上記の関数の引数 UniquieID exec_handle でなけ + # ればならない。 + # + # @param ec_id 上記関数の第1引数 exec_handle を渡す必要がある。 + # @return リターンコード + # + # @else + # + # @brief [local interface] Resetting and go to Inactive state + # + # This function reset RTC and makes transition from Error to Inactive + # state. This function is assumed to be called from the following + # functions. + # + # - onError() + # + # The argument of this function should be the first argument + # (UniqueId ec_id) of the above function. + # + # @param ec_id The above functions' first argument "exec_handle." + # @return Return code + # + # @endif + # + # ReturnCode_t reset(RTC::UniqueId ec_id); + + def reset(self, ec_id): + ec = self.getExecutionContext(ec_id) + if CORBA.is_nil(ec): + return RTC.RTC_ERROR + return ec.reset_component(self.getObjRef()) + + ## + # @if jp + # @brief [local interface] SDO service provider をセットする + # @else + # @brief [local interface] Set a SDO service provider + # @endif + # + # bool addSdoServiceProvider(const SDOPackage::ServiceProfile& prof, + # SdoServiceProviderBase* provider); + + def addSdoServiceProvider(self, prof, provider): + return self._sdoservice.addSdoServiceProvider(prof, provider) + + ## + # @if jp + # @brief [local interface] SDO service provider を削除する + # @else + # @brief [local interface] Remove a SDO service provider + # @endif + # + # bool removeSdoServiceProvider(const char* id); + + def removeSdoServiceProvider(self, id): + return self._sdoservice.removeSdoServiceProvider(id) + + ## + # @if jp + # @brief [local interface] SDO service consumer をセットする + # @else + # @brief [local interface] Set a SDO service consumer + # @endif + # + # bool addSdoServiceConsumer(const SDOPackage::ServiceProfile& prof); + + def addSdoServiceConsumer(self, prof): + return self._sdoservice.addSdoServiceConsumer(prof) + + ## + # @if jp + # @brief [local interface] SDO service consumer を削除する + # @else + # @brief [local interface] Remove a SDO service consumer + # @endif + # + # bool removeSdoServiceConsumer(const char* id); + + def removeSdoServiceConsumer(self, id): + return self._sdoservice.removeSdoServiceConsumer(id) + + ## + # @if jp + # + # @brief 全 InPort のデータを読み込む。 + # + # RTC が保持する全ての InPort のデータを読み込む。 + # + # @return 読み込み結果(全ポートの読み込み成功:true,失敗:false) + # + # @else + # + # @brief Readout the value from All InPorts. + # + # This operation read the value from all InPort + # registered in the RTC. + # + # @return result (Successful:true, Failed:false) + # + # @endif + # + # bool readAll(); + + def readAll(self): + self._rtcout.RTC_TRACE("readAll()") + ret = True + for inport in self._inports: + if not inport.read(): + self._rtcout.RTC_DEBUG("The error occurred in readAll().") + ret = False + if not self._readAllCompletion: + return False + + return ret + + ## + # @if jp + # + # @brief 全 OutPort のwrite()メソッドをコールする。 + # + # RTC が保持する全ての OutPort のwrite()メソッドをコールする。 + # + # @return 読み込み結果(全ポートへの書き込み成功:true,失敗:false) + # + # @else + # + # @brief The write() method of all OutPort is called. + # + # This operation call the write() method of all OutPort + # registered in the RTC. + # + # @return result (Successful:true, Failed:false) + # + # @endif + # + # bool writeAll(); + + def writeAll(self): + self._rtcout.RTC_TRACE("writeAll()") + ret = True + for outport in self._outports: + if not outport.write(): + self._rtcout.RTC_DEBUG("The error occurred in writeAll().") + ret = False + if not self._writeAllCompletion: + return False + + return ret + + ## + # @if jp + # + # @brief onExecute()実行前でのreadAll()メソッドの呼出を有効または無効にする。 + # + # このメソッドをパラメータをtrueとして呼ぶ事により、onExecute()実行前に + # readAll()が呼出されるようになる。 + # パラメータがfalseの場合は、readAll()呼出を無効にする。 + # + # @param read(default:true) + # (readAll()メソッド呼出あり:true, readAll()メソッド呼出なし:false) + # + # @param completion(default:false) + # readAll()にて、どれかの一つのInPortのread()が失敗しても全てのInPortのread()を呼び出す:true, + # readAll()にて、どれかの一つのInPortのread()が失敗した場合、すぐにfalseで抜ける:false + # + # @else + # + # @brief Set whether to execute the readAll() method. + # + # Set whether to execute the readAll() method. + # + # @param read(default:true) + # (readAll() is called:true, readAll() isn't called:false) + # + # @param completion(default:false) + # All InPort::read() calls are completed.:true, + # If one InPort::read() is False, return false.:false + # + # @param completion(default:false) + # + # @endif + # + # void setReadAll(bool read=true, bool completion=false); + + def setReadAll(self, read=True, completion=False): + self._readAll = read + self._readAllCompletion = completion + + ## + # @if jp + # + # @brief onExecute()実行後にwriteAll()メソッドの呼出を有効または無効にする。 + # + # このメソッドをパラメータをtrueとして呼ぶ事により、onExecute()実行後に + # writeAll()が呼出されるようになる。 + # パラメータがfalseの場合は、writeAll()呼出を無効にする。 + # + # @param write(default:true) + # (writeAll()メソッド呼出あり:true, writeAll()メソッド呼出なし:false) + # + # @param completion(default:false) + # writeAll()にて、どれかの一つのOutPortのwrite()が失敗しても全てのOutPortのwrite()を呼び出しを行う:true, + # writeAll()にて、どれかの一つのOutPortのwrite()が失敗した場合、すぐにfalseで抜ける:false + # + # @else + # + # @brief Set whether to execute the writeAll() method. + # + # Set whether to execute the writeAll() method. + # + # @param write(default:true) + # (writeAll() is called:true, writeAll() isn't called:false) + # + # @param completion(default:false) + # All OutPort::write() calls are completed.:true, + # If one OutPort::write() is False, return false.:false + # + # @endif + # + # void setWriteAll(bool write=true, bool completion=false); + + def setWriteAll(self, write=True, completion=False): + self._writeAll = write + self._writeAllCompletion = completion + + ## + # @if jp + # + # @brief 全 Port の登録を削除する + # + # RTC が保持する全ての Port を削除する。 + # + # @param self + # + # @else + # + # @brief Unregister the All Portse + # + # This operation deactivates the all Port and deletes the all Port's + # registrations in the RTC.. + # + # @endif + + def finalizePorts(self): + self._rtcout.RTC_TRACE("finalizePorts()") + self._portAdmin.finalizePorts() + self._inports = [] + self._outports = [] + return + def finalizeContexts(self): + self._rtcout.RTC_TRACE("finalizeContexts()") + len_ = len(self._eclist) + for i in range(len_): + idx = (len_ - 1) - i + self._eclist[idx].stop() + try: + self._poa.deactivate_object( + self._poa.servant_to_id( + self._eclist[idx])) + except BaseException: + self._rtcout.RTC_TRACE(OpenRTM_aist.Logger.print_exception()) + del self._eclist[idx] + return + ## + # @if jp + # @brief PreComponentActionListener リスナを追加する + # + # ComponentAction 実装関数の呼び出し直前のイベントに関連する各種リ + # スナを設定する。 + # + # 設定できるリスナのタイプとコールバックイベントは以下の通り + # + # - PRE_ON_INITIALIZE: onInitialize 直前 + # - PRE_ON_FINALIZE: onFinalize 直前 + # - PRE_ON_STARTUP: onStartup 直前 + # - PRE_ON_SHUTDOWN: onShutdown 直前 + # - PRE_ON_ACTIVATED: onActivated 直前 + # - PRE_ON_DEACTIVATED: onDeactivated 直前 + # - PRE_ON_ABORTING: onAborted 直前 + # - PRE_ON_ERROR: onError 直前 + # - PRE_ON_RESET: onReset 直前 + # - PRE_ON_EXECUTE: onExecute 直前 + # - PRE_ON_STATE_UPDATE: onStateUpdate 直前 + # + # リスナは PreComponentActionListener を継承し、以下のシグニチャを持つ + # operator() を実装している必要がある。 + # + # PreComponentActionListener::operator()(UniqueId ec_id) + # + # デフォルトでは、この関数に与えたリスナオブジェクトの所有権は + # RTObjectに移り、RTObject解体時もしくは、 + # removePreComponentActionListener() により削除時に自動的に解体される。 + # リスナオブジェクトの所有権を呼び出し側で維持したい場合は、第3引 + # 数に false を指定し、自動的な解体を抑制することができる。 + # + # @param listener_type リスナタイプ + # @param memfunc 関数オブジェクト + # + # @else + # @brief Adding PreComponentAction type listener + # + # This operation adds certain listeners related to ComponentActions + # pre events. + # The following listener types are available. + # + # - PRE_ON_INITIALIZE: before onInitialize + # - PRE_ON_FINALIZE: before onFinalize + # - PRE_ON_STARTUP: before onStartup + # - PRE_ON_SHUTDOWN: before onShutdown + # - PRE_ON_ACTIVATED: before onActivated + # - PRE_ON_DEACTIVATED: before onDeactivated + # - PRE_ON_ABORTING: before onAborted + # - PRE_ON_ERROR: before onError + # - PRE_ON_RESET: before onReset + # - PRE_ON_EXECUTE: before onExecute + # - PRE_ON_STATE_UPDATE: before onStateUpdate + # + # Listeners should have the following function operator(). + # + # PreComponentActionListener::operator()(UniqueId ec_id) + # + # The ownership of the given listener object is transferred to + # this RTObject object in default. The given listener object will + # be destroied automatically in the RTObject's dtor or if the + # listener is deleted by removePreComponentActionListener() function. + # If you want to keep ownership of the listener object, give + # "false" value to 3rd argument to inhibit automatic destruction. + # + # @param listener_type A listener type + # @param memfunc member function object + # + # @endif + # + # template + # PreComponentActionListener* + # addPreComponentActionListener(PreCompActionListenerType listener_type, + # void (Listener::*memfunc)(UniqueId ec_id)) + + def addPreComponentActionListener(self, listener_type, + memfunc): + class Noname(OpenRTM_aist.PreComponentActionListener): + def __init__(self, memfunc): + self._memfunc = memfunc + + def __call__(self, ec_id): + self._memfunc(ec_id) + return + + listener = Noname(memfunc) + self._actionListeners.addPreActionListener(listener_type, listener) + return listener + + ## + # @if jp + # @brief PreComponentActionListener リスナを削除する + # + # 設定した各種リスナを削除する。 + # + # @param listener_type リスナタイプ + # @param listener リスナオブジェクトへのポインタ + # + # @else + # @brief Removing PreComponentAction type listener + # + # This operation removes a specified listener. + # + # @param listener_type A listener type + # @param listener A pointer to a listener object + # + # @endif + # + # void + # removePreComponentActionListener(PreComponentActionListenerType listener_type, + # PreComponentActionListener* listener); + + def removePreComponentActionListener(self, listener_type, listener): + self._actionListeners.removePreActionListener(listener_type, listener) + return + ## + # @if jp + # @brief PostComponentActionListener リスナを追加する + # + # ComponentAction 実装関数の呼び出し直後のイベントに関連する各種リ + # スナを設定する。 + # + # 設定できるリスナのタイプとコールバックイベントは以下の通り + # + # - POST_ON_INITIALIZE: onInitialize 直後 + # - POST_ON_FINALIZE: onFinalize 直後 + # - POST_ON_STARTUP: onStartup 直後 + # - POST_ON_SHUTDOWN: onShutdown 直後 + # - POST_ON_ACTIVATED: onActivated 直後 + # - POST_ON_DEACTIVATED: onDeactivated 直後 + # - POST_ON_ABORTING: onAborted 直後 + # - POST_ON_ERROR: onError 直後 + # - POST_ON_RESET: onReset 直後 + # - POST_ON_EXECUTE: onExecute 直後 + # - POST_ON_STATE_UPDATE: onStateUpdate 直後 + # + # リスナは PostComponentActionListener を継承し、以下のシグニチャを持つ + # operator() を実装している必要がある。 + # + # PostComponentActionListener::operator()(UniqueId ec_id, ReturnCode_t ret) + # + # デフォルトでは、この関数に与えたリスナオブジェクトの所有権は + # RTObjectに移り、RTObject解体時もしくは、 + # removePostComponentActionListener() により削除時に自動的に解体される。 + # リスナオブジェクトの所有権を呼び出し側で維持したい場合は、第3引 + # 数に false を指定し、自動的な解体を抑制することができる。 + # + # @param listener_type リスナタイプ + # @param memfunc 関数オブジェクト + # + # @else + # @brief Adding PostComponentAction type listener + # + # This operation adds certain listeners related to ComponentActions + # post events. + # The following listener types are available. + # + # - POST_ON_INITIALIZE: after onInitialize + # - POST_ON_FINALIZE: after onFinalize + # - POST_ON_STARTUP: after onStartup + # - POST_ON_SHUTDOWN: after onShutdown + # - POST_ON_ACTIVATED: after onActivated + # - POST_ON_DEACTIVATED: after onDeactivated + # - POST_ON_ABORTING: after onAborted + # - POST_ON_ERROR: after onError + # - POST_ON_RESET: after onReset + # - POST_ON_EXECUTE: after onExecute + # - POST_ON_STATE_UPDATE: after onStateUpdate + # + # Listeners should have the following function operator(). + # + # PostComponentActionListener::operator()(UniqueId ec_id, ReturnCode_t ret) + # + # The ownership of the given listener object is transferred to + # this RTObject object in default. The given listener object will + # be destroied automatically in the RTObject's dtor or if the + # listener is deleted by removePostComponentActionListener() function. + # If you want to keep ownership of the listener object, give + # "false" value to 3rd argument to inhibit automatic destruction. + # + # @param listener_type A listener type + # @param memfunc member function object + # + # @endif + # + # template + # PostComponentActionListener* + # addPostComponentActionListener(PostCompActionListenerType listener_type, + # void (Listener::*memfunc)(UniqueId ec_id, + # ReturnCode_t ret)) + + def addPostComponentActionListener(self, listener_type, + memfunc): + class Noname(OpenRTM_aist.PostComponentActionListener): + def __init__(self, memfunc): + self._memfunc = memfunc + return + + def __call__(self, ec_id, ret): + self._memfunc(ec_id, ret) + return + + listener = Noname(memfunc) + self._actionListeners.addPostActionListener(listener_type, listener) + return listener + + ## + # @if jp + # @brief PostComponentActionListener リスナを削除する + # + # 設定した各種リスナを削除する。 + # + # @param listener_type リスナタイプ + # @param listener リスナオブジェクトへのポインタ + # + # @else + # @brief Removing PostComponentAction type listener + # + # This operation removes a specified listener. + # + # @param listener_type A listener type + # @param listener A pointer to a listener object + # + # @endif + ## + # void + # removePostComponentActionListener(PostComponentActionListenerType listener_type, + # PostComponentActionListener* listener); + + def removePostComponentActionListener(self, listener_type, listener): + self._actionListeners.removePostActionListener(listener_type, listener) + return + ## + # @if jp + # @brief PortActionListener リスナを追加する + # + # Portの追加、削除時にコールバックされる各種リスナを設定する。 + # + # 設定できるリスナのタイプとコールバックイベントは以下の通り + # + # - ADD_PORT: Port追加時 + # - REMOVE_PORT: Port削除時 + # + # リスナは PortActionListener を継承し、以下のシグニチャを持つ + # operator() を実装している必要がある。 + # + # PortActionListener::operator()(PortProfile& pprof) + # + # デフォルトでは、この関数に与えたリスナオブジェクトの所有権は + # RTObjectに移り、RTObject解体時もしくは、 + # removePortActionListener() により削除時に自動的に解体される。 + # リスナオブジェクトの所有権を呼び出し側で維持したい場合は、第3引 + # 数に false を指定し、自動的な解体を抑制することができる。 + # + # @param listener_type リスナタイプ + # @param memfunc 関数オブジェクト + # + # @else + # @brief Adding PortAction type listener + # + # This operation adds certain listeners related to ComponentActions + # post events. + # The following listener types are available. + # + # - ADD_PORT: At adding Port + # - REMOVE_PORT: At removing Port + # + # Listeners should have the following function operator(). + # + # PortActionListener::operator()(RTC::PortProfile pprof) + # + # The ownership of the given listener object is transferred to + # this RTObject object in default. The given listener object will + # be destroied automatically in the RTObject's dtor or if the + # listener is deleted by removePortActionListener() function. + # If you want to keep ownership of the listener object, give + # "false" value to 3rd argument to inhibit automatic destruction. + # + # @param listener_type A listener type + # @param memfunc member function object + # + # @endif + # + # template + # PortActionListener* + # addPortActionListener(PortActionListenerType listener_type, + # void (Listener::*memfunc)(const RTC::PortProfile&)) + + def addPortActionListener(self, listener_type, + memfunc): + class Noname(OpenRTM_aist.PortActionListener): + def __init__(self, memfunc): + self._memfunc = memfunc + return + + def __call__(self, pprofile): + self._memfunc(pprofile) + return + + listener = Noname(memfunc) + + self._actionListeners.addPortActionListener(listener_type, listener) + return listener + + ## + # @if jp + # @brief PortActionListener リスナを削除する + # + # 設定した各種リスナを削除する。 + # + # @param listener_type リスナタイプ + # @param listener リスナオブジェクトへのポインタ + # + # @else + # @brief Removing PortAction type listener + # + # This operation removes a specified listener. + # + # @param listener_type A listener type + # @param listener A pointer to a listener object + # + # @endif + # void + # removePortActionListener(PortActionListenerType listener_type, + # PortActionListener* listener); + + def removePortActionListener(self, listener_type, listener): + self._actionListeners.removePortActionListener(listener_type, listener) + return + ## + # @if jp + # @brief ExecutionContextActionListener リスナを追加する + # + # ExecutionContextの追加、削除時にコールバックされる各種リスナを設定する。 + # + # 設定できるリスナのタイプとコールバックイベントは以下の通り + # + # - ATTACH_EC: ExecutionContext アタッチ時 + # - DETACH_EC: ExecutionContext デタッチ時 + # + # リスナは ExecutionContextActionListener を継承し、以下のシグニチャを持つ + # operator() を実装している必要がある。 + # + # ExecutionContextActionListener::operator()(UniqueId ec_id) + # + # デフォルトでは、この関数に与えたリスナオブジェクトの所有権は + # RTObjectに移り、RTObject解体時もしくは、 + # removeExecutionContextActionListener() により削除時に自動的に解体される。 + # リスナオブジェクトの所有権を呼び出し側で維持したい場合は、第3引 + # 数に false を指定し、自動的な解体を抑制することができる。 + # + # @param listener_type リスナタイプ + # @param memfunc 関数オブジェクト + # + # @else + # @brief Adding ExecutionContextAction type listener + # + # This operation adds certain listeners related to ComponentActions + # post events. + # The following listener types are available. + # + # - ADD_PORT: At adding ExecutionContext + # - REMOVE_PORT: At removing ExecutionContext + # + # Listeners should have the following function operator(). + # + # ExecutionContextActionListener::operator()(UniqueId ec_id) + # + # The ownership of the given listener object is transferred to + # this RTObject object in default. The given listener object will + # be destroied automatically in the RTObject's dtor or if the + # listener is deleted by removeExecutionContextActionListener() function. + # If you want to keep ownership of the listener object, give + # "false" value to 3rd argument to inhibit automatic destruction. + # + # @param listener_type A listener type + # @param memfunc member function object + # + # @endif + # + # template + # ECActionListener* + # addExecutionContextActionListener(ECActionListenerType listener_type, + # void (Listener::*memfunc)(UniqueId)); + + def addExecutionContextActionListener(self, listener_type, + memfunc): + class Noname(OpenRTM_aist.ExecutionContextActionListener): + def __init__(self, memfunc): + self._memfunc = memfunc + return + + def __call__(self, ec_id): + self._memfunc(ec_id) + return + + listener = Noname(memfunc) + self._actionListeners.addECActionListener(listener_type, listener) + return listener + + ## + # @if jp + # @brief ExecutionContextActionListener リスナを削除する + # + # 設定した各種リスナを削除する。 + # + # @param listener_type リスナタイプ + # @param listener リスナオブジェクトへのポインタ + # + # @else + # @brief Removing ExecutionContextAction type listener + # + # This operation removes a specified listener. + # + # @param listener_type A listener type + # @param listener A pointer to a listener object + # + # @endif + # + # void + # removeExecutionContextActionListener(ECActionListenerType listener_type, + # ECActionListener* listener); + + def removeExecutionContextActionListener(self, listener_type, listener): + self._actionListeners.removeECActionListener(listener_type, listener) + return + ## + # @if jp + # @brief PortConnectListener リスナを追加する + # + # Portの接続時や接続解除時に呼び出される各種リスナを設定する。 + # + # 設定できるリスナのタイプとコールバックイベントは以下の通り + # + # - ON_NOTIFY_CONNECT: notify_connect() 関数内呼び出し直後 + # - ON_NOTIFY_DISCONNECT: notify_disconnect() 呼び出し直後 + # - ON_UNSUBSCRIBE_INTERFACES: notify_disconnect() 内のIF購読解除時 + # + # リスナは PortConnectListener を継承し、以下のシグニチャを持つ + # operator() を実装している必要がある。 + # + # PortConnectListener::operator()(const char*, ConnectorProfile) + # + # デフォルトでは、この関数に与えたリスナオブジェクトの所有権は + # RTObjectに移り、RTObject解体時もしくは、 + # removePortConnectListener() により削除時に自動的に解体される。 + # リスナオブジェクトの所有権を呼び出し側で維持したい場合は、第3引 + # 数に false を指定し、自動的な解体を抑制することができる。 + # + # @param listener_type リスナタイプ + # @param memfunc 関数オブジェクト + # + # @else + # @brief Adding PortConnect type listener + # + # This operation adds certain listeners related to Port's connect actions. + # The following listener types are available. + # + # - ON_NOTIFY_CONNECT: right after entering into notify_connect() + # - ON_NOTIFY_DISCONNECT: right after entering into notify_disconnect() + # - ON_UNSUBSCRIBE_INTERFACES: unsubscribing IF in notify_disconnect() + # + # Listeners should have the following function operator(). + # + # PortConnectListener::operator()(const char*, ConnectorProfile) + # + # The ownership of the given listener object is transferred to + # this RTObject object in default. The given listener object will + # be destroied automatically in the RTObject's dtor or if the + # listener is deleted by removePortConnectListener() function. + # If you want to keep ownership of the listener object, give + # "false" value to 3rd argument to inhibit automatic destruction. + # + # @param listener_type A listener type + # @param memfunc member function object + # + # @endif + # + # template + # PortConnectListener* + # addPortConnectListener(PortConnectListenerType listener_type, + # void (Listener::*memfunc)(const char*, + # ConnectorProfile&)) + + def addPortConnectListener(self, listener_type, + memfunc): + class Noname(OpenRTM_aist.PortConnectListener): + def __init__(self, memfunc): + self._memfunc = memfunc + return + + def __call__(self, portname, cprofile): + self._memfunc(portname, cprofile) + return + + listener = Noname(memfunc) + self._portconnListeners.addListener(listener_type, listener) + return listener + + ## + # @if jp + # @brief PortConnectListener リスナを削除する + # + # 設定した各種リスナを削除する。 + # + # @param listener_type リスナタイプ + # @param listener リスナオブジェクトへのポインタ + # + # @else + # @brief Removing PortConnect type listener + # + # This operation removes a specified listener. + # + # @param listener_type A listener type + # @param listener A pointer to a listener object + # + # @endif + # + # void + # removePortConnectListener(PortConnectListenerType listener_type, + # PortConnectListener* listener); + + def removePortConnectListener(self, listener_type, listener): + self._portconnListeners.removeListener(listener_type, listener) + return + ## + # @if jp + # @brief PortConnectRetListener リスナを追加する + # + # Portの接続時や接続解除時に呼び出される各種リスナを設定する。 + # + # 設定できるリスナのタイプとコールバックイベントは以下の通り + # + # - ON_CONNECT_NEXTPORT: notify_connect() 中のカスケード呼び出し直後 + # - ON_SUBSCRIBE_INTERFACES: notify_connect() 中のインターフェース購読直後 + # - ON_CONNECTED: nofity_connect() 接続処理完了時に呼び出される + # - ON_DISCONNECT_NEXT: notify_disconnect() 中にカスケード呼び出し直後 + # - ON_DISCONNECTED: notify_disconnect() リターン時 + # + # リスナは PortConnectRetListener を継承し、以下のシグニチャを持つ + # operator() を実装している必要がある。 + # + # PortConnectRetListener::operator()(const char*, ConnectorProfile) + # + # デフォルトでは、この関数に与えたリスナオブジェクトの所有権は + # RTObjectに移り、RTObject解体時もしくは、 + # removePortConnectRetListener() により削除時に自動的に解体される。 + # リスナオブジェクトの所有権を呼び出し側で維持したい場合は、第3引 + # 数に false を指定し、自動的な解体を抑制することができる。 + # + # @param listener_type リスナタイプ + # @param memfunc 関数オブジェクト + # + # @else + # @brief Adding PortConnectRet type listener + # + # This operation adds certain listeners related to Port's connect actions. + # The following listener types are available. + # + # - ON_CONNECT_NEXTPORT: after cascade-call in notify_connect() + # - ON_SUBSCRIBE_INTERFACES: after IF subscribing in notify_connect() + # - ON_CONNECTED: completed nofity_connect() connection process + # - ON_DISCONNECT_NEXT: after cascade-call in notify_disconnect() + # - ON_DISCONNECTED: completed notify_disconnect() disconnection process + # + # Listeners should have the following function operator(). + # + # PortConnectRetListener::operator()(const char*, ConnectorProfile) + # + # The ownership of the given listener object is transferred to + # this RTObject object in default. The given listener object will + # be destroied automatically in the RTObject's dtor or if the + # listener is deleted by removePortConnectRetListener() function. + # If you want to keep ownership of the listener object, give + # "false" value to 3rd argument to inhibit automatic destruction. + # + # @param listener_type A listener type + # @param memfunc member function object + # + # @endif + # + # template + # PortConnectRetListener* + # addPortConnectRetListener(PortConnectRetListenerType listener_type, + # void (Listener::*memfunc)(const char*, + # ConnectorProfile&, + # ReturnCode_t)) + + def addPortConnectRetListener(self, listener_type, + memfunc): + class Noname(OpenRTM_aist.PortConnectRetListener): + def __init__(self, memfunc): + self._memfunc = memfunc + return + + def __call__(self, portname, cprofile, ret): + self._memfunc(portname, cprofile, ret) + return + + listener = Noname(memfunc) + self._portconnListeners.addRetListener(listener_type, listener) + return listener + + ## + # @if jp + # @brief PortConnectRetListener リスナを削除する + # + # 設定した各種リスナを削除する。 + # + # @param listener_type リスナタイプ + # @param listener リスナオブジェクトへのポインタ + # + # @else + # @brief Removing PortConnectRet type listener + # + # This operation removes a specified listener. + # + # @param listener_type A listener type + # @param listener A pointer to a listener object + # + # @endif + # + # void + # removePortConnectRetListener(PortConnectRetListenerType listener_type, + # PortConnectRetListener* listener); + + def removePortConnectRetListener(self, listener_type, listener): + self._portconnListeners.removeRetListener(listener_type, listener) + return - #============================================================ - # SDOPackage::SdoSystemElement - #============================================================ - - ## - # @if jp - # - # @brief [SDO interface] Organization ꥹȤμ - # - # SDOSystemElement 0Ĥ⤷Ϥʾ Organization ͭ뤳Ȥ - # 롣 SDOSystemElement 1İʾ Organization ͭƤ - # ˤϡΥڥ졼Ͻͭ Organization ΥꥹȤ֤ - # ⤷OrganizationĤͭƤʤжΥꥹȤ֤ - # - # @param self - # - # @return ͭƤ Organization ꥹ - # - # @exception SDONotExists åȤSDO¸ߤʤ(㳰ϡCORBAɸ - # ƥ㳰OBJECT_NOT_EXIST˥ޥåԥ󥰤) - # @exception NotAvailable SDO¸ߤ뤬ʤ - # @exception InternalError Ū顼ȯ - # - # @else - # - # @brief [SDO interface] Getting Organizations - # - # SDOSystemElement can be the owner of zero or more organizations. - # If the SDOSystemElement owns one or more Organizations, this operation - # returns the list of Organizations that the SDOSystemElement owns. - # If it does not own any Organization, it returns empty list. - # - # @return Owned Organization List - # - # @exception SDONotExists if the target SDO does not exist.(This exception - # is mapped to CORBA standard system exception - # OBJECT_NOT_EXIST.) - # @exception NotAvailable if the target SDO is reachable but cannot - # respond. - # @exception InternalError if the target SDO cannot execute the operation - # completely due to some internal error. - # - # @endif - # virtual SDOPackage::OrganizationList* get_owned_organizations() - def get_owned_organizations(self): - self._rtcout.RTC_TRACE("get_owned_organizations()") - - return self._sdoOwnedOrganizations - - - - #============================================================ - # SDOPackage::SDO - #============================================================ - - ## - # @if jp - # - # @brief [SDO interface] SDO ID μ - # - # SDO ID ֤ڥ졼 - # Υڥ졼ϰʲη㳰ȯ롣 - # - # @param self - # - # @return ꥽ǡǥƤ SDO ID - # - # @exception SDONotExists åȤSDO¸ߤʤ(㳰ϡCORBAɸ - # ƥ㳰OBJECT_NOT_EXIST˥ޥåԥ󥰤) - # @exception NotAvailable SDO¸ߤ뤬ʤ - # @exception InternalError Ū顼ȯ - # - # @else - # - # @brief [SDO interface] Getting SDO ID - # - # This operation returns id of the SDO. - # This operation throws SDOException with one of the following types. - # - # @return id of the SDO defined in the resource data model. - # - # @exception SDONotExists if the target SDO does not exist.(This exception - # is mapped to CORBA standard system exception - # OBJECT_NOT_EXIST.) - # @exception NotAvailable if the target SDO is reachable but cannot - # respond. - # @exception InternalError if the target SDO cannot execute the operation - # completely due to some internal error. - # - # @endif - # virtual char* get_sdo_id() - def get_sdo_id(self): - self._rtcout.RTC_TRACE("get_sdo_id()") - - return self._profile.instance_name - - - - ## - # @if jp - # - # @brief [SDO interface] SDO פμ - # - # SDO Type ֤ڥ졼 - # Υڥ졼ϰʲη㳰ȯ롣 - # - # @param self - # - # @return ꥽ǡǥƤ SDO Type - # - # @exception SDONotExists åȤSDO¸ߤʤ(㳰ϡCORBAɸ - # ƥ㳰OBJECT_NOT_EXIST˥ޥåԥ󥰤) - # @exception NotAvailable SDO¸ߤ뤬ʤ - # @exception InternalError Ū顼ȯ - # - # @else - # - # @brief [SDO interface] Getting SDO type - # - # This operation returns sdoType of the SDO. - # This operation throws SDOException with one of the following types. - # - # @return Type of the SDO defined in the resource data model. - # - # @exception SDONotExists if the target SDO does not exist.(This exception - # is mapped to CORBA standard system exception - # OBJECT_NOT_EXIST.) - # @exception NotAvailable if the target SDO is reachable but cannot - # respond. - # @exception InternalError if the target SDO cannot execute the operation - # completely due to some internal error. - # - # @endif - # virtual char* get_sdo_type() - def get_sdo_type(self): - self._rtcout.RTC_TRACE("get_sdo_type()") - - return self._profile.description - - - - ## - # @if jp - # - # @brief [SDO interface] SDO DeviceProfile ꥹȤμ - # - # SDO DeviceProfile ֤ڥ졼 SDO ϡɥǥХ - # ˴ϢդƤʤˤϡ DeviceProfile ֤롣 - # Υڥ졼ϰʲη㳰ȯ롣 - # - # @param self - # - # @return SDO DeviceProfile - # - # @exception SDONotExists åȤSDO¸ߤʤ(㳰ϡCORBAɸ - # ƥ㳰OBJECT_NOT_EXIST˥ޥåԥ󥰤) - # @exception NotAvailable SDO¸ߤ뤬ʤ - # @exception InternalError Ū顼ȯ - # - # @else - # - # @brief [SDO interface] Getting SDO DeviceProfile - # - # This operation returns the DeviceProfile of the SDO. If the SDO does not - # represent any hardware device, then a DeviceProfile with empty values - # are returned. - # This operation throws SDOException with one of the following types. - # - # @return The DeviceProfile of the SDO. - # - # @exception SDONotExists if the target SDO does not exist.(This exception - # is mapped to CORBA standard system exception - # OBJECT_NOT_EXIST.) - # @exception NotAvailable if the target SDO is reachable but cannot - # respond. - # @exception InternalError if the target SDO cannot execute the operation - # completely due to some internal error. - # - # @endif - # virtual SDOPackage::DeviceProfile* get_device_profile() - def get_device_profile(self): - self._rtcout.RTC_TRACE("get_device_profile()") - - return self._SdoConfigImpl.getDeviceProfile() - - - - ## - # @if jp - # - # @brief [SDO interface] SDO ServiceProfile μ - # - # SDO ͭƤ Service ServiceProfile ֤ڥ졼 - # SDO ӥĤͭƤʤˤϡΥꥹȤ֤ - # Υڥ졼ϰʲη㳰ȯ롣 - # - # @param self - # - # @return SDO 󶡤Ƥ Service ServiceProfile - # - # @exception SDONotExists åȤSDO¸ߤʤ(㳰ϡCORBAɸ - # ƥ㳰OBJECT_NOT_EXIST˥ޥåԥ󥰤) - # @exception NotAvailable SDO¸ߤ뤬ʤ - # @exception InternalError Ū顼ȯ - # - # @else - # - # @brief [SDO interface] Getting SDO ServiceProfile - # - # This operation returns a list of ServiceProfiles that the SDO has. - # If the SDO does not provide any service, then an empty list is returned. - # This operation throws SDOException with one of the following types. - # - # @return List of ServiceProfiles of all the services the SDO is - # providing. - # - # @exception SDONotExists if the target SDO does not exist.(This exception - # is mapped to CORBA standard system exception - # OBJECT_NOT_EXIST.) - # @exception NotAvailable if the target SDO is reachable but cannot - # respond. - # @exception InternalError if the target SDO cannot execute the operation - # completely due to some internal error. - # - # @endif - # virtual SDOPackage::ServiceProfileList* get_service_profiles() - def get_service_profiles(self): - self._rtcout.RTC_TRACE("get_service_profiles()") - self._sdoSvcProfiles = self._SdoConfigImpl.getServiceProfiles() - - return self._sdoSvcProfiles - - - - - ## - # @if jp - # - # @brief [SDO interface] ServiceProfileμ - # - # "id" ǻꤵ줿̾Υӥ ServiceProfile ֤ - # - # @param self - # @param _id SDO Service ServiceProfile ˴Ϣդ줿̻ҡ - # - # @return ꤵ줿 SDO Service ServiceProfile - # - # @exception InvalidParameter "id" ǻꤷ ServiceProfile ¸ߤʤ - # "id" null - # @exception SDONotExists åȤSDO¸ߤʤ(㳰ϡCORBAɸ - # ƥ㳰OBJECT_NOT_EXIST˥ޥåԥ󥰤) - # @exception NotAvailable SDO¸ߤ뤬ʤ - # @exception InternalError Ū顼ȯ - # - # @else - # - # @brief [SDO interface] Getting Organizations - # - # This operation returns the ServiceProfile that is specified by the - # argument "id." - # - # @param _id The identifier referring to one of the ServiceProfiles. - # - # @return The profile of the specified service. - # - # @exception InvalidParameter if the ServiceProfile that is specified by - # the argument 'id' does not exist or if 'id' - # is 'null.' - # @exception SDONotExists if the target SDO does not exist.(This exception - # is mapped to CORBA standard system exception - # OBJECT_NOT_EXIST.) - # @exception NotAvailable If the target SDO is reachable but cannot - # respond. - # @exception InternalError If the target SDO cannot execute the operation - # completely due to some internal error. - # - # @endif - # virtual SDOPackage::ServiceProfile* get_service_profile(const char* id) - def get_service_profile(self, _id): - self._rtcout.RTC_TRACE("get_service_profile(%s)", _id) - self._sdoSvcProfiles = self._SdoConfigImpl.getServiceProfiles() - if not _id: - raise SDOPackage.InvalidParameter("get_service_profile(): Empty name.") - - try: - index = OpenRTM_aist.CORBA_SeqUtil.find(self._sdoSvcProfiles, self.svc_name(_id)) - - if index < 0: - raise SDOPackage.InvalidParameter("get_service_profile(): Not found") - - return self._sdoSvcProfiles[index] - except: - self._rtcout.RTC_ERROR(OpenRTM_aist.Logger.print_exception()) - raise SDOPackage.InternalError("get_service_profile()") - - - - - ## - # @if jp - # - # @brief [SDO interface] ꤵ줿 SDO Service μ - # - # Υڥ졼ϰ "id" ǻꤵ줿̾ˤäƶ̤ - # SDO Service ؤΥ֥ȻȤ֤ SDO ˤ󶡤 - # Service Ϥ줾դμ̻Ҥˤ̤롣 - # - # @param self - # @param _id SDO Service ˴Ϣդ줿̻ҡ - # - # @return ׵ᤵ줿 SDO Service ؤλȡ - # - # - # @exception InvalidParameter "id" ǻꤷ ServiceProfile ¸ߤʤ - # "id" null - # @exception SDONotExists åȤSDO¸ߤʤ(㳰ϡCORBAɸ - # ƥ㳰OBJECT_NOT_EXIST˥ޥåԥ󥰤) - # @exception NotAvailable SDO¸ߤ뤬ʤ - # @exception InternalError Ū顼ȯ - # - # @else - # - # @brief [SDO interface] Getting specified SDO Service's reference - # - # This operation returns an object implementing an SDO's service that - # is identified by the identifier specified as an argument. Different - # services provided by an SDO are distinguished with different - # identifiers. See OMG SDO specification Section 2.2.8, "ServiceProfile," - # on page 2-12 for more details. - # - # @param _id The identifier referring to one of the SDO Service - # @return The object implementing the requested service. - # @exception InvalidParameter if argument id is null, or if the - # ServiceProfile that is specified by argument - # id does not exist. - # @exception SDONotExists if the target SDO does not exist.(This exception - # is mapped to CORBA standard system exception - # OBJECT_NOT_EXIST.) - # @exception NotAvailable If the target SDO is reachable but cannot - # respond. - # @exception InternalError If the target SDO cannot execute the operation - # completely due to some internal error. - # - # @endif - # virtual SDOPackage::SDOService_ptr get_sdo_service(const char* id) - def get_sdo_service(self, _id): - self._rtcout.RTC_TRACE("get_sdo_service(%s)", _id) - self._sdoSvcProfiles = self._SdoConfigImpl.getServiceProfiles() - - if not _id: - raise SDOPackage.InvalidParameter("get_service(): Empty name.") - - index = OpenRTM_aist.CORBA_SeqUtil.find(self._sdoSvcProfiles, self.svc_name(_id)) - - if index < 0: - raise SDOPackage.InvalidParameter("get_service(): Not found") - - - return self._sdoSvcProfiles[index].service - - - - - ## - # @if jp - # - # @brief [SDO interface] Configuration ֥Ȥμ - # - # Υڥ졼 Configuration interface ؤλȤ֤ - # Configuration interface ϳ SDO 뤿Υ󥿡ե - # ҤȤĤǤ롣Υ󥿡ե DeviceProfile, ServiceProfile, - # Organization 줿 SDO °ͤꤹ뤿˻Ѥ롣 - # Configuration 󥿡եξܺ٤ˤĤƤϡOMG SDO specification - # 2.3.5, p.2-24 򻲾ȤΤȡ - # - # @param self - # - # @return SDO Configuration 󥿡եؤλ - # - # @exception InterfaceNotImplemented SDOConfiguration󥿡ե - # ʤ - # @exception SDONotExists åȤSDO¸ߤʤ(㳰ϡCORBAɸ - # ƥ㳰OBJECT_NOT_EXIST˥ޥåԥ󥰤) - # @exception NotAvailable SDO¸ߤ뤬ʤ - # @exception InternalError Ū顼ȯ - # - # @else - # - # @brief [SDO interface] Getting Configuration object - # - # This operation returns an object implementing the Configuration - # interface. The Configuration interface is one of the interfaces that - # each SDO maintains. The interface is used to configure the attributes - # defined in DeviceProfile, ServiceProfile, and Organization. - # See OMG SDO specification Section 2.3.5, "Configuration Interface," - # on page 2-24 for more details about the Configuration interface. - # - # @return The Configuration interface of an SDO. - # - # @exception InterfaceNotImplemented The target SDO has no Configuration - # interface. - # @exception SDONotExists if the target SDO does not exist.(This exception - # is mapped to CORBA standard system exception - # OBJECT_NOT_EXIST.) - # @exception NotAvailable The target SDO is reachable but cannot respond. - # @exception InternalError The target SDO cannot execute the operation - # completely due to some internal error. - # @endif - # virtual SDOPackage::Configuration_ptr get_configuration() - def get_configuration(self): - self._rtcout.RTC_TRACE("get_configuration()") - if self._SdoConfig is None: - raise SDOPackage.InterfaceNotImplemented("InterfaceNotImplemented: get_configuration") - - return self._SdoConfig - - - - - ## - # @if jp - # - # @brief [SDO interface] Monitoring ֥Ȥμ - # - # Υڥ졼 Monitoring interface ؤλȤ֤ - # Monitoring interface SDO 륤󥿡եΰĤǤ롣 - # Υ󥿡ե SDO Υץѥƥ˥󥰤뤿 - # Ѥ롣 - # Monitoring interface ξܺ٤ˤĤƤ OMG SDO specification - # 2.3.7 "Monitoring Interface" p.2-35 򻲾ȤΤȡ - # - # @param self - # - # @return SDO Monitoring interface ؤλ - # - # @exception InterfaceNotImplemented SDOConfiguration󥿡ե - # ʤ - # @exception SDONotExists åȤSDO¸ߤʤ(㳰ϡCORBAɸ - # ƥ㳰OBJECT_NOT_EXIST˥ޥåԥ󥰤) - # @exception NotAvailable SDO¸ߤ뤬ʤ - # @exception InternalError Ū顼ȯ - # - # @else - # - # @brief [SDO interface] Get Monitoring object - # - # This operation returns an object implementing the Monitoring interface. - # The Monitoring interface is one of the interfaces that each SDO - # maintains. The interface is used to monitor the properties of an SDO. - # See OMG SDO specification Section 2.3.7, "Monitoring Interface," on - # page 2-35 for more details about the Monitoring interface. - # - # @return The Monitoring interface of an SDO. - # - # @exception InterfaceNotImplemented The target SDO has no Configuration - # interface. - # @exception SDONotExists if the target SDO does not exist.(This exception - # is mapped to CORBA standard system exception - # OBJECT_NOT_EXIST.) - # @exception NotAvailable The target SDO is reachable but cannot respond. - # @exception InternalError The target SDO cannot execute the operation - # completely due to some internal error. - # @endif - # virtual SDOPackage::Monitoring_ptr get_monitoring() - def get_monitoring(self): - self._rtcout.RTC_TRACE("get_monitoring()") - raise SDOPackage.InterfaceNotImplemented("Exception: get_monitoring") - - - - ## - # @if jp - # - # @brief [SDO interface] Organization ꥹȤμ - # - # SDO 0İʾ Organization (ȿ)˽°뤳ȤǤ롣 ⤷ SDO - # 1İʾ Organization ˽°Ƥ硢Υڥ졼Ͻ° - # Organization ΥꥹȤ֤SDO ɤ Organization ˤ°Ƥʤ - # ˤϡΥꥹȤ֤롣 - # - # @param self - # - # @return SDO ° Organization Υꥹȡ - # - # @exception SDONotExists åȤSDO¸ߤʤ(㳰ϡCORBAɸ - # ƥ㳰OBJECT_NOT_EXIST˥ޥåԥ󥰤) - # @exception NotAvailable SDO¸ߤ뤬ʤ - # @exception InternalError Ū顼ȯ - # @else - # - # @brief [SDO interface] Getting Organizations - # - # An SDO belongs to zero or more organizations. If the SDO belongs to one - # or more organizations, this operation returns the list of organizations - # that the SDO belongs to. An empty list is returned if the SDO does not - # belong to any Organizations. - # - # @return The list of Organizations that the SDO belong to. - # - # @exception SDONotExists if the target SDO does not exist.(This exception - # is mapped to CORBA standard system exception - # OBJECT_NOT_EXIST.) - # @exception NotAvailable The target SDO is reachable but cannot respond. - # @exception InternalError The target SDO cannot execute the operation - # completely due to some internal error. - # @endif - # virtual SDOPackage::OrganizationList* get_organizations() - def get_organizations(self): - self._rtcout.RTC_TRACE("get_organizations()") - self._sdoOrganizations = self._SdoConfigImpl.getOrganizations() - - return self._sdoOrganizations - - - - - ## - # @if jp - # - # @brief [SDO interface] SDO Status ꥹȤμ - # - # Υڥ졼 SDO Υơɽ NVList ֤ - # - # @param self - # - # @return SDO Υơ - # - # @exception SDONotExists åȤSDO¸ߤʤ(㳰ϡCORBAɸ - # ƥ㳰OBJECT_NOT_EXIST˥ޥåԥ󥰤) - # @exception NotAvailable SDO¸ߤ뤬ʤ - # @exception InternalError Ū顼ȯ - # - # @else - # - # @brief [SDO interface] Get SDO Status - # - # This operation returns an NVlist describing the status of an SDO. - # - # @return The actual status of an SDO. - # - # @exception SDONotExists if the target SDO does not exist.(This exception - # is mapped to CORBA standard system exception - # OBJECT_NOT_EXIST.) - # @exception NotAvailable The target SDO is reachable but cannot respond. - # @exception InternalError The target SDO cannot execute the operation - # completely due to some internal error. - # - # @endif - # virtual SDOPackage::NVList* get_status_list() - def get_status_list(self): - self._rtcout.RTC_TRACE("get_status_list()") - - return self._sdoStatus - - - - - ## - # @if jp - # - # @brief [SDO interface] SDO Status μ - # - # This operation returns the value of the specified status parameter. - # - # @param self - # @param name SDO Υơѥ᡼ - # - # @return ꤵ줿ѥ᡼Υơ͡ - # - # @exception SDONotExists åȤSDO¸ߤʤ(㳰ϡCORBAɸ - # ƥ㳰OBJECT_NOT_EXIST˥ޥåԥ󥰤) - # @exception NotAvailable SDO¸ߤ뤬ʤ - # @exception InvalidParameter "name" null 뤤¸ߤʤ - # @exception InternalError Ū顼ȯ - # @else - # - # @brief [SDO interface] Get SDO Status - # - # @param name One of the parameters defining the "status" of an SDO. - # - # @return The value of the specified status parameter. - # - # @exception SDONotExists if the target SDO does not exist.(This exception - # is mapped to CORBA standard system exception - # OBJECT_NOT_EXIST.) - # @exception NotAvailable The target SDO is reachable but cannot respond. - # @exception InvalidParameter The parameter defined by "name" is null or - # does not exist. - # @exception InternalError The target SDO cannot execute the operation - # completely due to some internal error. - # - # - # @endif - # virtual CORBA::Any* get_status(const char* name) - def get_status(self, name): - self._rtcout.RTC_TRACE("get_status(%s)", name) - index = OpenRTM_aist.CORBA_SeqUtil.find(self._sdoStatus, self.nv_name(name)) - if index < 0: - raise SDOPackage.InvalidParameter("get_status(): Not found") - - try: - return any.to_any(self._sdoStatus[index].value) - except: - self._rtcout.RTC_ERROR(OpenRTM_aist.Logger.print_exception()) - raise SDOPackage.InternalError("get_status()") - - - - #============================================================ - # Local interfaces - #============================================================ - - ## - # @if jp - # - # @brief [local interface] 󥹥̾μ - # - # ComponentProfile ꤵ줿󥹥֤̾ - # - # @param self - # - # @return 󥹥̾ - # - # @else - # - # @endif - # const char* getInstanceName() - def getInstanceName(self): - self._rtcout.RTC_TRACE("getInstanceName()") - return self._profile.instance_name - - - ## - # @if jp - # - # @brief [local interface] 󥹥̾ - # - # ComponentProfile ˻ꤵ줿󥹥̾ꤹ롣 - # - # @param self - # - # @param instance_name 󥹥̾ - # - # @else - # - # @endif - # void setInstanceName(const char* instance_name); - def setInstanceName(self, instance_name): - self._rtcout.RTC_TRACE("setInstanceName(%s)", instance_name) - self._properties.setProperty("instance_name",instance_name) - self._profile.instance_name = self._properties.getProperty("instance_name") - - - ## - # @if jp - # - # @brief [local interface] ̾μ - # - # ComponentProfile ꤵ줿֤̾ - # - # @param self - # - # @return ̾ - # - # @else - # - # @endif - # const char* getTypeName() - def getTypeName(self): - self._rtcout.RTC_TRACE("getTypeName()") - return self._profile.type_name - - - ## - # @if jp - # - # @brief [local interface] Description μ - # - # ComponentProfile ꤵ줿 Description ֤ - # - # @param self - # - # @return Description - # - # @else - # - # @endif - # const char* getDescription() - def getDescription(self): - self._rtcout.RTC_TRACE("getDescription()") - return self._profile.description - - - ## - # @if jp - # - # @brief [local interface] Сμ - # - # ComponentProfile ꤵ줿С֤ - # - # @param self - # - # @return С - # - # @else - # - # @endif - # const char* getVersion() - def getVersion(self): - self._rtcout.RTC_TRACE("getVersion()") - return self._profile.version - - - ## - # @if jp - # - # @brief [local interface] ٥μ - # - # ComponentProfile ꤵ줿٥֤ - # - # @param self - # - # @return ٥ - # - # @else - # - # @endif - # const char* getVendor() - def getVendor(self): - self._rtcout.RTC_TRACE("getVendor()") - return self._profile.vendor - - - ## - # @if jp - # - # @brief [local interface] ƥμ - # - # ComponentProfile ꤵ줿ƥ֤ - # - # @param self - # - # @return ƥ - # - # @else - # - # @endif - # const char* getCategory() - def getCategory(self): - self._rtcout.RTC_TRACE("getCategory()") - return self._profile.category - - - ## - # @if jp - # - # @brief [local interface] Naming Server μ - # - # ꤵ줿 Naming Server ֤ - # - # @param self - # - # @return Naming Server ꥹ - # - # @else - # - # @endif - # std::vector getNamingNames(); - def getNamingNames(self): - self._rtcout.RTC_TRACE("getNamingNames()") - return [s.strip() for s in self._properties.getProperty("naming.names").split(",")] - - - ## - # @if jp - # - # @brief [local interface] ֥ȥե󥹤 - # - # RTC CORBA ֥ȥե󥹤ꤹ롣 - # - # @param self - # @param rtobj ֥ȥե - # - # @else - # - # @endif - # void setObjRef(const RTObject_ptr rtobj); - def setObjRef(self, rtobj): - self._rtcout.RTC_TRACE("setObjRef()") - self._objref = rtobj - return - - - ## - # @if jp - # - # @brief [local interface] ֥ȥե󥹤μ - # - # ꤵ줿 CORBA ֥ȥե󥹤롣 - # - # @param self - # - # @return ֥ȥե - # - # @else - # - # @endif - # RTObject_ptr getObjRef() const; - def getObjRef(self): - self._rtcout.RTC_TRACE("getObjRef()") - return self._objref - - - ## - # @if jp - # - # @brief [local interface] RTC Υץѥƥꤹ - # - # RTC ݻ٤ץѥƥꤹ롣Ϳץѥƥϡ - # ComponentProfile ꤵ٤ʤФʤʤ - # Υڥ졼̾ RTC ݤ Manager - # ƤФ뤳ȤտޤƤ롣 - # - # @param self - # @param prop RTC Υץѥƥ - # - # @else - # - # @brief [local interface] Set RTC property - # - # This operation sets the properties to the RTC. The given property - # values should include information for ComponentProfile. - # Generally, this operation is designed to be called from Manager, when - # RTC is initialized - # - # @param prop Property for RTC. - # - # @endif - # void setProperties(const coil::Properties& prop); - def setProperties(self, prop): - self._rtcout.RTC_TRACE("setProperties()") - self._properties.mergeProperties(prop) - self._profile.instance_name = self._properties.getProperty("instance_name") - self._profile.type_name = self._properties.getProperty("type_name") - self._profile.description = self._properties.getProperty("description") - self._profile.version = self._properties.getProperty("version") - self._profile.vendor = self._properties.getProperty("vendor") - self._profile.category = self._properties.getProperty("category") - - - ## - # @if jp - # - # @brief [local interface] RTC Υץѥƥ - # - # RTC ݻƤץѥƥ֤ - # RTCץѥƥʤ϶Υץѥƥ֤롣 - # - # @param self - # - # @return RTC Υץѥƥ - # - # @else - # - # @brief [local interface] Get RTC property - # - # This operation returns the properties of the RTC. - # Empty property would be returned, if RTC has no property. - # - # @return Property for RTC. - # - # @endif - # coil::Properties& getProperties(); - def getProperties(self): - self._rtcout.RTC_TRACE("getProperties()") - return self._properties - - - ## - # @if jp - # - # @brief ե졼ѥ᡼ - # - # ե졼ѥ᡼ѿХɤ - # \Ȥƥե졼ѥ᡼Υǡꤹ롣 - # - # @param self - # @param param_name ե졼ѥ᡼̾ - # @param var ե졼ѥ᡼Ǽѿ - # @param def_val ե졼ѥ᡼ǥե - # @param trans ʸѴѴؿ(ǥե:None) - # - # @return (:true꼺:false) - # - # @else - # - # @endif - # template - # bool bindParameter(const char* param_name, VarType& var, - # const char* def_val, - # bool (*trans)(VarType&, const char*) = coil::stringTo) - def bindParameter(self, param_name, var, - def_val, trans=None): - self._rtcout.RTC_TRACE("bindParameter()") - if trans is None: - trans_ = OpenRTM_aist.stringTo - else: - trans_ = trans - self._configsets.bindParameter(param_name, var, def_val, trans_) - return True - - - ## - # @if jp - # - # @brief ե졼󥵡ӥ - # - # ե졼󥵡ӥ֥Ȥ롣Υ - # ֥ȤѤơե졼ѥ᡼ - # ԤȤǤ롣ȤƤϡ - # - # - unbindParameter(): ѥ᡼ΥХ - # - update(): ѥ᡼ι - # - update(set_name): ΥåȤι - # - update(set_name, param_name): ΥåȤΥѥ᡼ι - # - isExist(): ѥ᡼¸߳ǧ - # - isChanged(): ѥ᡼ѹ줿γǧ - # - changedParameters(): ѹ줿ѥ᡼Υꥹ - # - getActiveId(): ƥ֥å̾μ - # - haveConfig(config_id): եåȤäƤ뤫ɤ - # - getConfigurationSets(): ե졼󥻥åȤμ - # - getConfigurationSet(set_id): ꥻåȤ - # - # ХåϢ - # - addConfigurationParamListener(): ꥹʤɲ - # - removeConfigurationParamListener(): ꥹʤκ - # - addConfigurationSetListener(): ꥹʤɲ - # - removeConfigurationSetListener(): ꥹʤκ - # - addConfigurationSetNameListener(): ꥹʤɲ - # - removeConfigurationSetNameListener(): ꥹʤκ - # - # ܺ٤ConfigAdmin饹ե󥹤򻲾ȤΤȡ - # - # @return ConfigAdmin object - # - # @else - # - # @brief Getting configuration service - # - # This operation returns configuration service object. By using - # this service, user can manipulate configuration - # parameters. Mainly the following operations are supported. - # - # - unbindParameter(): Unbinding parameters - # - update(): Updateing parameters - # - update(set_name): Updating a specific configuration set - # - update(set_name, param_name): Updating specific parameter in a set - # - isExist(): Checking existence of a parameter - # - isChanged(): Check if a parameter was updated - # - changedParameters(): Getting changed parameter list - # - getActiveId(): Getting active configuration set name - # - haveConfig(config_id): Checking if having a specified configuration set - # - getConfigurationSets(): getting all the configuration sets - # - getConfigurationSet(set_id): Getting a configuration set - # - # Callback related member functions - # - addConfigurationParamListener(): Adding listener - # - removeConfigurationParamListener(): Removing listener - # - addConfigurationSetListener(): Adding listener - # - removeConfigurationSetListener(): Removing listener - # - addConfigurationSetNameListener(): Adding listener - # - removeConfigurationSetNameListener(): Removing listener - # - # See details in the ConfigAdmin class reference - # - # @return ConfigAdmin object - # - # @endif - # - # ConfigAdmin& getConfigService() { return m_configsets; } - def getConfigService(self): - return self._configsets - - ## - # @if jp - # - # @brief ե졼ѥ᡼ι(ID) - # - # ꤷIDΥե졼󥻥åȤꤷͤǡ - # ե졼ѥ᡼ͤ򹹿 - # - # @param self - # @param config_set оݤΥե졼󥻥åID - # - # @else - # - # @endif - # void updateParameters(const char* config_set); - def updateParameters(self, config_set): - self._rtcout.RTC_TRACE("updateParameters(%s)", config_set) - self._configsets.update(config_set) - return - - - ## - # @if jp - # - # @brief [local interface] Port Ͽ - # - # RTC ݻPortϿ롣 - # Port 饢ǽˤ뤿ˤϡΥڥ졼ˤ - # ϿƤʤФʤʤϿ Port Ϥ RTC ˤ - # PortProfile.name ˤ̤롣äơPort RTC ˤơ - # ˡ PortProfile.name ʤФʤʤ - # Ͽ줿 Port Ŭڤ˥ƥֲ줿塢λȤ - # ֥ȻȤꥹ¸롣 - # - # @param self - # @param port RTC Ͽ Port - # @param port_type if port is PortBase, port_type is None, - # if port is PortService, port_type is True - # - # @else - # - # @brief [local interface] Register Port - # - # This operation registers a Port to be held by this RTC. - # In order to enable access to the Port from outside of RTC, the Port - # must be registered by this operation. The Port that is registered by - # this operation would be identified by PortProfile.name in the inside of - # RTC. Therefore, the Port should have unique PortProfile.name in the RTC. - # The registering Port would be activated properly, and the reference - # and the object reference would be stored in lists in RTC. - # - # @param port Port which is registered in the RTC - # - # @endif - # void registerPort(PortBase& port); - def registerPort(self, port): - self._rtcout.RTC_TRACE("registerPort()") - if not self.addPort(port): - self._rtcout.RTC_ERROR("addPort(PortBase&) failed.") - return - - # void registerPort(PortService_ptr port); - # def registerPortByReference(self, port_ref): - # self._rtcout.RTC_TRACE("registerPortByReference()") - # self.addPortByReference(port_ref) - # return - - # new interface. since 1.0.0-RELEASE - # void addPort(PortBase& port); - def addPort(self, port): - self._rtcout.RTC_TRACE("addPort()") - if isinstance(port, OpenRTM_aist.CorbaPort): - self._rtcout.RTC_TRACE("addPort(CorbaPort)") - propkey = "port.corbaport." - prop = self._properties.getNode(propkey) - if prop: - self._properties.getNode(propkey).mergeProperties(self._properties.getNode("port.corba")) - port.init(self._properties.getNode(propkey)) - port.setOwner(self.getObjRef()) - - elif isinstance(port, OpenRTM_aist.PortBase): - self._rtcout.RTC_TRACE("addPort(PortBase)") - port.setOwner(self.getObjRef()) - port.setPortConnectListenerHolder(self._portconnListeners) - self.onAddPort(port.getPortProfile()) - - elif isinstance(port, RTC._objref_PortService): - self._rtcout.RTC_TRACE("addPort(PortService)") - return self._portAdmin.addPort(port) - - - # new interface. since 1.0.0-RELEASE - # void addPort(PortService_ptr port); - # def addPortByReference(self, port_ref): - # self._rtcout.RTC_TRACE("addPortByReference()") - # self._portAdmin.registerPortByReference(port_ref) - # return - - - ## - # @if jp - # - # @brief [local interface] DataInPort Ͽ - # - # RTC ݻ DataInPort Ͽ롣 - # Port Υץѥƥ˥ǡݡȤǤ뤳("port.dataport") - # TCPѤ뤳("tcp_any")ꤹȤȤˡ DataInPort - # 󥹥󥹤Ͽ롣 - # - # @param self - # @param name port ̾ - # @param inport Ͽо DataInPort - # - # @else - # - # @endif - def registerInPort(self, name, inport): - self._rtcout.RTC_TRACE("registerInPort(%s)", name) - if not self.addInPort(name, inport): - self._rtcout.RTC_ERROR("addInPort(%s) failed.", name) - return - - # new interface. since 1.0.0-RELEASE - def addInPort(self, name, inport): - self._rtcout.RTC_TRACE("addInPort(%s)", name) - - propkey = "port.inport." + name - prop_ = copy.copy(self._properties.getNode(propkey)) - prop_.mergeProperties(self._properties.getNode("port.inport.dataport")) - - ret = self.addPort(inport) - - if not ret: - self._rtcout.RTC_ERROR("addInPort() failed.") - return ret - - inport.init(self._properties.getNode(propkey)) - self._inports.append(inport) - return ret + ## + # @if jp + # + # @brief ConfigurationParamListener を追加する + # + # update(const char* config_set, const char* config_param) が呼ばれた際に + # コールされるリスナ ConfigurationParamListener を追加する。 + # type には現在のところ ON_UPDATE_CONFIG_PARAM のみが入る。 + # + # @param type ConfigurationParamListenerType型の値。 + # ON_UPDATE_CONFIG_PARAM がある。 + # + # @param memfunc 関数オブジェクト + # + # @else + # + # @brief Adding ConfigurationParamListener + # + # This function adds a listener object which is called when + # update(const char* config_set, const char* config_param) is + # called. In the type argument, currently only + # ON_UPDATE_CONFIG_PARAM is allowed. + # + # @param type ConfigurationParamListenerType value + # ON_UPDATE_CONFIG_PARAM is only allowed. + # + # @param memfunc member function object + # + # @endif + # + # template + # ConfigurationParamListener* + # addConfigurationParamListener(ConfigurationParamListenerType listener_type, + # void (Listener::*memfunc)(const char*, + # const char*)) + + def addConfigurationParamListener(self, type, + memfunc): + class Noname(OpenRTM_aist.ConfigurationParamListener): + def __init__(self, memfunc): + self._memfunc = memfunc + return + + def __call__(self, config_set_name, config_param_name): + self._memfunc(config_set_name, config_param_name) + return + + listener = Noname(memfunc) + self._configsets.addConfigurationParamListener(type, listener) + return listener + + ## + # @if jp + # + # @brief ConfigurationParamListener を削除する + # + # addConfigurationParamListener で追加されたリスナオブジェクトを削除する。 + # + # @param type ConfigurationParamListenerType型の値。 + # ON_UPDATE_CONFIG_PARAM がある。 + # @param listener 与えたリスナオブジェクトへのポインタ + # + # @else + # + # @brief Removing ConfigurationParamListener + # + # This function removes a listener object which is added by + # addConfigurationParamListener() function. + # + # @param type ConfigurationParamListenerType value + # ON_UPDATE_CONFIG_PARAM is only allowed. + # @param listener a pointer to ConfigurationParamListener listener object. + # + # @endif + # + # void removeConfigurationParamListener(ConfigurationParamListenerType type, + # ConfigurationParamListener* listener); + + def removeConfigurationParamListener(self, type, listener): + self._configsets.removeConfigurationParamListener(type, listener) + return + ## + # @if jp + # + # @brief ConfigurationSetListener を追加する + # + # ConfigurationSet が更新されたときなどに呼ばれるリスナ + # ConfigurationSetListener を追加する。設定可能なイベントは以下の + # 2種類がある。 + # + # - ON_SET_CONFIG_SET: setConfigurationSetValues() で + # ConfigurationSet に値が設定された場合。 + # - ON_ADD_CONFIG_SET: addConfigurationSet() で新しい + # ConfigurationSet が追加された場合。 + # + # @param type ConfigurationSetListenerType型の値。 + # @param memfunc 関数オブジェクト + # + # @else + # + # @brief Adding ConfigurationSetListener + # + # This function add a listener object which is called when + # ConfigurationSet is updated. Available events are the followings. + # + # @param type ConfigurationSetListenerType value + # @param memfunc member function object + # + # @endif + # + # template + # ConfigurationSetListener* + # addConfigurationSetListener(ConfigurationSetListenerType listener_type, + # void (Listener::*memfunc) + # (const coil::Properties& config_set)) + + def addConfigurationSetListener(self, listener_type, + memfunc): + class Noname(OpenRTM_aist.ConfigurationSetListener): + def __init__(self, memfunc): + self._memfunc = memfunc + return + + def __call__(self, config_set): + self._memfunc(config_set) + return + + listener = Noname(memfunc) + self._configsets.addConfigurationSetListener(listener_type, listener) + return listener + + ## + # @if jp + # + # @brief ConfigurationSetListener を削除する + # + # addConfigurationSetListener で追加されたリスナオブジェクトを削除する。 + # + # @param type ConfigurationSetListenerType型の値。 + # @param listener 与えたリスナオブジェクトへのポインタ + # + # @else + # + # @brief Removing ConfigurationSetListener + # + # This function removes a listener object which is added by + # addConfigurationSetListener() function. + # + # @param type ConfigurationSetListenerType value + # @param listener a pointer to ConfigurationSetListener listener object. + # + # @endif + # + # void removeConfigurationSetListener(ConfigurationSetListenerType type, + # ConfigurationSetListener* listener); + + def removeConfigurationSetListener(self, type, listener): + self._configsets.removeConfigurationSetListener(type, listener) + return - ## - # @if jp - # - # @brief [local interface] DataOutPort Ͽ - # - # RTC ݻ DataOutPor tϿ롣 - # Port Υץѥƥ˥ǡݡȤǤ뤳("port.dataport") - # TCPѤ뤳("tcp_any")ꤹȤȤˡ DataOutPort - # 󥹥󥹤Ͽ롣 - # - # @param self - # @param name port ̾ - # @param outport Ͽо DataInPort - # - # @else - # - # @endif - # void registerOutPort(const char* name, OutPortBase& outport); - def registerOutPort(self, name, outport): - self._rtcout.RTC_TRACE("registerOutPort(%s)", name) - if not self.addOutPort(name, outport): - self._rtcout.RTC_ERROR("addOutPort(%s) failed.", name) - return - - # new interface. since 1.0.0-RELEASE - # void addOutPort(const char* name, OutPortBase& outport); - def addOutPort(self, name, outport): - self._rtcout.RTC_TRACE("addOutPort(%s)", name) - - propkey = "port.outport." + name - prop_ = copy.copy(self._properties.getNode(propkey)) - prop_.mergeProperties(self._properties.getNode("port.outport.dataport")) - - ret = self.addPort(outport) - - if not ret: - self._rtcout.RTC_ERROR("addOutPort() failed.") - return ret + ## + # @if jp + # + # @brief ConfigurationSetNameListener を追加する + # + # ConfigurationSetName が更新されたときなどに呼ばれるリスナ + # ConfigurationSetNameListener を追加する。設定可能なイベントは以下の + # 3種類がある。 + # + # - ON_UPDATE_CONFIG_SET: ある ConfigurationSet がアップデートされた + # - ON_REMOVE_CONFIG_SET: ある ConfigurationSet が削除された + # - ON_ACTIVATE_CONFIG_SET: ある ConfigurationSet がアクティブ化された + # + # @param type ConfigurationSetNameListenerType型の値。 + # @param memfunc 関数オブジェクト + # + # @else + # + # @brief Adding ConfigurationSetNameListener + # + # This function add a listener object which is called when + # ConfigurationSetName is updated. Available events are the followings. + # + # - ON_UPDATE_CONFIG_SET: A ConfigurationSet has been updated. + # - ON_REMOVE_CONFIG_SET: A ConfigurationSet has been deleted. + # - ON_ACTIVATE_CONFIG_SET: A ConfigurationSet has been activated. + # + # @param type ConfigurationSetNameListenerType value + # @param memfunc member function object + # + # @endif + # + # template + # ConfigurationSetNameListener* + # addConfigurationSetNameListener(ConfigurationSetNameListenerType type, + # void (Listener::*memfunc)(const char*)) + + def addConfigurationSetNameListener(self, type, memfunc): + class Noname(OpenRTM_aist.ConfigurationSetNameListener): + def __init__(self, memfunc): + self._memfunc = memfunc + return + + def __call__(self, config_set_name): + self._memfunc(config_set_name) + return + + listener = Noname(memfunc) + self._configsets.addConfigurationSetNameListener(type, listener) + return listener + + ## + # @if jp + # + # @brief ConfigurationSetNameListener を削除する + # + # addConfigurationSetNameListener で追加されたリスナオブジェクトを + # 削除する。 + # + # @param type ConfigurationSetNameListenerType型の値。 + # ON_UPDATE_CONFIG_PARAM がある。 + # @param listener 与えたリスナオブジェクトへのポインタ + # + # @else + # + # @brief Removing ConfigurationSetNameListener + # + # This function removes a listener object which is added by + # addConfigurationSetNameListener() function. + # + # @param type ConfigurationSetNameListenerType value + # ON_UPDATE_CONFIG_PARAM is only allowed. + # @param listener a pointer to ConfigurationSetNameListener + # listener object. + # + # @endif + # void + # removeConfigurationSetNameListener(ConfigurationSetNameListenerType type, + # ConfigurationSetNameListener* listener); + + def removeConfigurationSetNameListener(self, type, listener): + self._configsets.removeConfigurationSetNameListener(type, listener) + return - outport.init(self._properties.getNode(propkey)) - self._outports.append(outport) - return ret + ## + # @if jp + # @brief PreFsmActionListener リスナを追加する + # + # FsmAction 実装関数の呼び出し直前のイベントに関連する各種リ + # スナを設定する。 + # + # 設定できるリスナのタイプとコールバックイベントは以下の通り + # + # - PRE_ON_INITIALIZE: onInitialize 直前 + # - PRE_ON_FINALIZE: onFinalize 直前 + # - PRE_ON_STARTUP: onStartup 直前 + # - PRE_ON_SHUTDOWN: onShutdown 直前 + # - PRE_ON_ACTIVATED: onActivated 直前 + # - PRE_ON_DEACTIVATED: onDeactivated 直前 + # - PRE_ON_ABORTED: onAborted 直前 + # - PRE_ON_ERROR: onError 直前 + # - PRE_ON_RESET: onReset 直前 + # - PRE_ON_EXECUTE: onExecute 直前 + # - PRE_ON_STATE_UPDATE: onStateUpdate 直前 + # + # リスナは PreFsmActionListener を継承し、以下のシグニチャを持つ + # operator() を実装している必要がある。 + # + # PreFsmActionListener::operator()(UniqueId ec_id) + # + # デフォルトでは、この関数に与えたリスナオブジェクトの所有権は + # RTObjectに移り、RTObject解体時もしくは、 + # removePreFsmActionListener() により削除時に自動的に解体される。 + # リスナオブジェクトの所有権を呼び出し側で維持したい場合は、第3引 + # 数に false を指定し、自動的な解体を抑制することができる。 + # + # @param listener_type リスナタイプ + # @param listener リスナオブジェクトへのポインタ + # + # @else + # @brief Adding PreFsmAction type listener + # + # This operation adds certain listeners related to FsmActions + # pre events. + # The following listener types are available. + # + # - PRE_ON_INITIALIZE: before onInitialize + # - PRE_ON_FINALIZE: before onFinalize + # - PRE_ON_STARTUP: before onStartup + # - PRE_ON_SHUTDOWN: before onShutdown + # - PRE_ON_ACTIVATED: before onActivated + # - PRE_ON_DEACTIVATED: before onDeactivated + # - PRE_ON_ABORTED: before onAborted + # - PRE_ON_ERROR: before onError + # - PRE_ON_RESET: before onReset + # - PRE_ON_EXECUTE: before onExecute + # - PRE_ON_STATE_UPDATE: before onStateUpdate + # + # Listeners should have the following function operator(). + # + # PreFsmActionListener::operator()(UniqueId ec_id) + # + # The ownership of the given listener object is transferred to + # this RTObject object in default. The given listener object will + # be destroied automatically in the RTObject's dtor or if the + # listener is deleted by removePreFsmActionListener() function. + # If you want to keep ownership of the listener object, give + # "false" value to 3rd argument to inhibit automatic destruction. + # + # @param listener_type A listener type + # @param listener A pointer to a listener object + # + # @endif + # + def addPreFsmActionListener(self, listener_type, + memfunc): + class Noname(OpenRTM_aist.PreFsmActionListener): + def __init__(self, memfunc): + self._memfunc = memfunc + return + + def __call__(self, state): + self._memfunc(state) + return + + listener = Noname(memfunc) + self._fsmActionListeners.addPreActionListener(listener_type, listener) + return listener + + ## + # @if jp + # @brief PreFsmActionListener リスナを削除する + # + # 設定した各種リスナを削除する。 + # + # @param listener_type リスナタイプ + # @param listener リスナオブジェクトへのポインタ + # + # @else + # @brief Removing PreFsmAction type listener + # + # This operation removes a specified listener. + # + # @param listener_type A listener type + # @param listener A pointer to a listener object + # + # @endif + # + def removePreFsmActionListener(self, listener_type, listener): + self._fsmActionListeners.removePreActionListener(listener_type, listener) + return + ## + # @if jp + # @brief PostFsmActionListener リスナを追加する + # + # FsmAction 実装関数の呼び出し直後のイベントに関連する各種リ + # スナを設定する。 + # + # 設定できるリスナのタイプとコールバックイベントは以下の通り + # + # - POST_ON_INITIALIZE: onInitialize 直後 + # - POST_ON_FINALIZE: onFinalize 直後 + # - POST_ON_STARTUP: onStartup 直後 + # - POST_ON_SHUTDOWN: onShutdown 直後 + # - POST_ON_ACTIVATED: onActivated 直後 + # - POST_ON_DEACTIVATED: onDeactivated 直後 + # - POST_ON_ABORTED: onAborted 直後 + # - POST_ON_ERROR: onError 直後 + # - POST_ON_RESET: onReset 直後 + # - POST_ON_EXECUTE: onExecute 直後 + # - POST_ON_STATE_UPDATE: onStateUpdate 直後 + # + # リスナは PostFsmActionListener を継承し、以下のシグニチャを持つ + # operator() を実装している必要がある。 + # + # PostFsmActionListener::operator()(const char* state, ReturnCode_t ret) + # + # デフォルトでは、この関数に与えたリスナオブジェクトの所有権は + # RTObjectに移り、RTObject解体時もしくは、 + # removePostFsmActionListener() により削除時に自動的に解体される。 + # リスナオブジェクトの所有権を呼び出し側で維持したい場合は、第3引 + # 数に false を指定し、自動的な解体を抑制することができる。 + # + # @param listener_type リスナタイプ + # @param listener リスナオブジェクトへのポインタ + # + # @else + # @brief Adding PostFsmAction type listener + # + # This operation adds certain listeners related to FsmActions + # post events. + # The following listener types are available. + # + # - POST_ON_INITIALIZE: after onInitialize + # - POST_ON_FINALIZE: after onFinalize + # - POST_ON_STARTUP: after onStartup + # - POST_ON_SHUTDOWN: after onShutdown + # - POST_ON_ACTIVATED: after onActivated + # - POST_ON_DEACTIVATED: after onDeactivated + # - POST_ON_ABORTED: after onAborted + # - POST_ON_ERROR: after onError + # - POST_ON_RESET: after onReset + # - POST_ON_EXECUTE: after onExecute + # - POST_ON_STATE_UPDATE: after onStateUpdate + # + # Listeners should have the following function operator(). + # + # PostFsmActionListener::operator()(const char* state, ReturnCode_t ret) + # + # The ownership of the given listener object is transferred to + # this RTObject object in default. The given listener object will + # be destroied automatically in the RTObject's dtor or if the + # listener is deleted by removePostFsmActionListener() function. + # If you want to keep ownership of the listener object, give + # "false" value to 3rd argument to inhibit automatic destruction. + # + # @param listener_type A listener type + # @param listener A pointer to a listener object + # + # @endif + # + + def addPostFsmActionListener(self, listener_type, + memfunc): + class Noname(OpenRTM_aist.PostFsmActionListener): + def __init__(self, memfunc): + self._memfunc = memfunc + return + + def __call__(self, state, ret): + self._memfunc(state, ret) + return + + listener = Noname(memfunc) + self._fsmActionListeners.addPostActionListener(listener_type, listener) + return listener + + ## + # @if jp + # @brief PostFsmActionListener リスナを削除する + # + # 設定した各種リスナを削除する。 + # + # @param listener_type リスナタイプ + # @param listener リスナオブジェクトへのポインタ + # + # @else + # @brief Removing PostFsmActionListener type listener + # + # This operation removes a specified listener. + # + # @param listener_type A listener type + # @param listener A pointer to a listener object + # + # @endif + # + + def removePostFsmActionListener(self, listener_type, listener): + self._fsmActionListeners.removePostActionListener(listener_type, listener) + return - ## - # @if jp - # - # @brief [local interface] InPort Ͽ - # - # RTC ݻInPortϿ롣 - # - # @param port о Port - # @return (:true:false) - # - # @else - # - # @brief [local interface] Unregister InPort - # - # This operation unregisters a InPort held by this RTC. - # - # @param port Port which is unregistered - # @return Unregister result (Successful:true, Failed:false) - # - # @endif - # - # bool removeInPort(InPortBase& port); - def removeInPort(self, port): - self._rtcout.RTC_TRACE("removeInPort()") - ret = self.removePort(port) - - if ret: - for inport in self._inports: - if port == inport: - - self._inports.remove(port) - - return True - - return False - - - ## - # @if jp - # - # @brief [local interface] OutPort Ͽ - # - # RTC ݻOutPortϿ롣 - # - # @param port о Port - # @return (:true:false) - # - # @else - # - # @brief [local interface] Unregister OutPort - # - # This operation unregisters a OutPort held by this RTC. - # - # @param port Port which is unregistered - # @return Unregister result (Successful:true, Failed:false) - # - # @endif - # - # bool removeOutPort(OutPortBase& port); - def removeOutPort(self, port): - self._rtcout.RTC_TRACE("removeOutPort()") - ret = self.removePort(port) - - if ret: - for outport in self._outports: - if port == outport: - - self._outports.remove(port) - - return True - - return False - - - ## - # @if jp - # - # @brief [local interface] Port Ͽ - # - # RTC ݻPortϿ롣 - # - # @param self - # @param port о Port - # - # @else - # - # @brief [local interface] Unregister Port - # - # This operation unregisters a Port to be held by this RTC. - # - # @param port Port which is unregistered in the RTC - # - # @endif - # void RTObject_impl::deletePort(PortBase& port) - def deletePort(self, port): - self._rtcout.RTC_TRACE("deletePort()") - if not self.removePort(port): - self._rtcout.RTC_ERROR("removePort() failed.") - return - - # new interface. since 1.0.0-RELEASE - def removePort(self, port): - self._rtcout.RTC_TRACE("removePort()") - if isinstance(port, OpenRTM_aist.PortBase) or isinstance(port, OpenRTM_aist.CorbaPort): - self.onRemovePort(port.getPortProfile()) - return self._portAdmin.removePort(port) - - - ## - # @if jp - # - # @brief [local interface] ̾ˤ Port Ͽ - # - # ̾Τꤷ RTC ݻPortϿ롣 - # - # @param self - # @param port_name о Port ̾ - # - # @else - # - # @endif - def deletePortByName(self, port_name): - self._rtcout.RTC_TRACE("deletePortByName(%s)", port_name) - self._portAdmin.deletePortByName(port_name) - return - - - ## - # @if jp - # - # @brief [local interface] ¹ԥƥȤ - # - # get_context() ƱǽΥǡ㤤Ϥʤ - # δؿϰʲδؿǸƤФ뤳ȤȤƤ롣 - # - # - onStartup() - # - onShutdown() - # - onActivated() - # - onDeactivated() - # - onExecute() - # - onAborting() - # - onError() - # - onReset() - # - onStateUpdate() - # - onRateChanged() - # - # δؿΰϤδؿΰ UniquieID exec_handle Ǥʤ - # Фʤʤ - # - # @param ec_id 嵭ؿ1 exec_handle Ϥɬפ롣 - # - # @else - # - # @brief [local interface] Getting current execution context - # - # This function is the local version of get_context(). completely - # same as get_context() function. This function is assumed to be - # called from the following functions. - # - # - onStartup() - # - onShutdown() - # - onActivated() - # - onDeactivated() - # - onExecute() - # - onAborting() - # - onError() - # - onReset() - # - onStateUpdate() - # - onRateChanged() - # - # The argument of this function should be the first argument - # (UniqueId ec_id) of the above functions. - # - # @param ec_id The above functions' first argument "exec_handle." - # - # @endif - # - # ExecutionContext_ptr getExecutionContext(RTC::UniqueId ec_id); - def getExecutionContext(self, ec_id): - return self.get_context(ec_id) - - ## - # @if jp - # - # @brief [local interface] ¹ԥƥȤμ¹ԥ졼Ȥ - # - # ߼¹μ¹ԥƥȤμ¹ԥ졼Ȥ롣¹ԥƥ - # ȤKindPERIODICʳξư̤Ǥ롣δؿϰ - # δؿǸƤФ뤳ȤȤƤ롣 - # - # - onStartup() - # - onShutdown() - # - onActivated() - # - onDeactivated() - # - onExecute() - # - onAborting() - # - onError() - # - onReset() - # - onStateUpdate() - # - onRateChanged() - # - # δؿΰϤδؿΰ UniquieID exec_handle Ǥʤ - # Фʤʤ - # - # @param ec_id 嵭ؿ1 exec_handle Ϥɬפ롣 - # - # @else - # - # @brief [local interface] Getting current context' execution rate - # - # This function returns current execution rate in this - # context. If this context's kind is not PERIODC, behavior is not - # defined. This function is assumed to be called from the - # following functions. - # - # - onStartup() - # - onShutdown() - # - onActivated() - # - onDeactivated() - # - onExecute() - # - onAborting() - # - onError() - # - onReset() - # - onStateUpdate() - # - onRateChanged() - # - # The argument of this function should be the first argument - # (UniqueId ec_id) of the above functions. - # - # @param ec_id The above functions' first argument "exec_handle." - # - # @endif - # - # double getExecutionRate(RTC::UniqueId ec_id); - def getExecutionRate(self, ec_id): - ec = self.getExecutionContext(ec_id) - if CORBA.is_nil(ec): - return 0.0 - - return ec.get_rate() - - - ## - # @if jp - # - # @brief [local interface] ¹ԥƥȤμ¹ԥ졼Ȥꤹ - # - # ߼¹μ¹ԥƥȤμ¹ԥ졼Ȥꤹ롣¹ԥƥ - # ȤKindPERIODICʳξư̤Ǥ롣δؿϰ - # δؿǸƤФ뤳ȤȤƤ롣 - # - # - onStartup() - # - onShutdown() - # - onActivated() - # - onDeactivated() - # - onExecute() - # - onAborting() - # - onError() - # - onReset() - # - onStateUpdate() - # - onRateChanged() - # - # δؿΰϤδؿΰ UniquieID exec_handle Ǥʤ - # Фʤʤ - # - # @param ec_id 嵭ؿ1 exec_handle Ϥɬפ롣 - # @param rate ¹ԥ졼Ȥ [Hz] Ϳ - # - # @else - # - # @brief [local interface] Setting current context' execution rate - # - # This function sets a execution rate in the context. If this - # context's kind is not PERIODC, behavior is not defined. This - # function is assumed to be called from the following functions. - # - # - onStartup() - # - onShutdown() - # - onActivated() - # - onDeactivated() - # - onExecute() - # - onAborting() - # - onError() - # - onReset() - # - onStateUpdate() - # - onRateChanged() - # - # The argument of this function should be the first argument - # (UniqueId ec_id) of the above functions. - # - # @param ec_id The above functions' first argument "exec_handle." - # @param rate Execution rate in [Hz]. - # - # @endif - # - # ReturnCode_t setExecutionRate(RTC::UniqueId ec_id, double rate); - def setExecutionRate(self, ec_id, rate): - ec = self.getExecutionContext(ec_id) - if CORBA.is_nil(ec): - return RTC.RTC_ERROR - ec.set_rate(rate) - return RTC.RTC_OK - - - ## - # @if jp - # - # @brief [local interface] ¹ԥƥȤνͭĴ٤ - # - # ߼¹μ¹ԥƥȤνͭĴ٤롣δؿϰʲδ - # ǸƤФ뤳ȤȤƤ롣 - # - # - onStartup() - # - onShutdown() - # - onActivated() - # - onDeactivated() - # - onExecute() - # - onAborting() - # - onError() - # - onReset() - # - onStateUpdate() - # - onRateChanged() - # - # δؿΰϤδؿΰ UniquieID exec_handle Ǥʤ - # Фʤʤ - # - # @param ec_id 嵭ؿ1 exec_handle Ϥɬפ롣 - # @return true: Ȥμ¹ԥƥȡfalse: ¾μ¹ԥƥ - # - # @else - # - # @brief [local interface] Checking if the current context is own context - # - # This function checks if the current context is own execution - # context. This function is assumed to be called from the - # following functions. - # - # - onStartup() - # - onShutdown() - # - onActivated() - # - onDeactivated() - # - onExecute() - # - onAborting() - # - onError() - # - onReset() - # - onStateUpdate() - # - onRateChanged() - # - # The argument of this function should be the first argument - # (UniqueId ec_id) of the above functions. - # - # @param ec_id The above functions' first argument "exec_handle." - # @return true: Own context, false: other's context - # - # @endif - # - # bool isOwnExecutionContext(RTC::UniqueId ec_id); - def isOwnExecutionContext(self, ec_id): - global ECOTHER_OFFSET - if ec_id < ECOTHER_OFFSET: - return True - return False - - - ## - # @if jp - # - # @brief [local interface] ֤ Inactive ܤ - # - # ֤ Active Inactive ܤ롣δؿϰʲδ - # ǸƤФ뤳ȤȤƤ롣 - # - # - onActivated() - # - onExecute() - # - onStateUpdate() - # - # δؿΰϾ嵭δؿΰ UniquieID exec_handle Ǥʤ - # Фʤʤ - # - # @param ec_id 嵭ؿ1 exec_handle Ϥɬפ롣 - # @return ꥿󥳡 - # - # @else - # - # @brief [local interface] Make transition to Inactive state - # - # This function makes transition from Active to Inactive - # state. This function is assumed to be called from the following - # functions. - # - # - onActivated() - # - onExecute() - # - onStateUpdate() - # - # The argument of this function should be the first argument - # (UniqueId ec_id) of the above function. - # - # @param ec_id The above functions' first argument "exec_handle." - # @return Return code - # - # @endif - # - # ReturnCode_t deactivate(RTC::UniqueId ec_id); - def deactivate(self, ec_id): - ec = self.getExecutionContext(ec_id) - if CORBA.is_nil(ec): - return RTC.RTC_ERROR - return ec.deactivate_component(self.getObjRef()) - - - ## - # @if jp - # - # @brief [local interface] ֤ Active ܤ - # - # ֤ Inactive Active ܤ롣δؿϰʲδ - # ǸƤФ뤳ȤȤƤ롣 - # - # - onStartup() - # - onDeactivated() - # - # δؿΰϾ嵭δؿΰ UniquieID exec_handle Ǥʤ - # Фʤʤ - # - # @param ec_id 嵭ؿ1 exec_handle Ϥɬפ롣 - # @return ꥿󥳡 - # - # @else - # - # @brief [local interface] Make transition to Active state - # - # This function makes transition from Inactive to Active - # state. This function is assumed to be called from the following - # functions. - # - # - onStartup() - # - onDeactivated() - # - # The argument of this function should be the first argument - # (UniqueId ec_id) of the above function. - # - # @param ec_id The above functions' first argument "exec_handle." - # @return Return code - # - # @endif - # - # ReturnCode_t activate(RTC::UniqueId ec_id); - def activate(self, ec_id): - ec = self.getExecutionContext(ec_id) - if CORBA.is_nil(ec): - return RTC.RTC_ERROR - return ec.activate_component(self.getObjRef()) - - - ## - # @if jp - # - # @brief [local interface] ֤ꥻåȤ Inactive ܤ - # - # ֤ Error Inactive ܤ롣δؿϰʲδ - # ǸƤФ뤳ȤȤƤ롣 - # - # - onError() - # - # δؿΰϾ嵭δؿΰ UniquieID exec_handle Ǥʤ - # Фʤʤ - # - # @param ec_id 嵭ؿ1 exec_handle Ϥɬפ롣 - # @return ꥿󥳡 - # - # @else - # - # @brief [local interface] Resetting and go to Inactive state - # - # This function reset RTC and makes transition from Error to Inactive - # state. This function is assumed to be called from the following - # functions. - # - # - onError() - # - # The argument of this function should be the first argument - # (UniqueId ec_id) of the above function. - # - # @param ec_id The above functions' first argument "exec_handle." - # @return Return code - # - # @endif - # - # ReturnCode_t reset(RTC::UniqueId ec_id); - def reset(self, ec_id): - ec = self.getExecutionContext(ec_id) - if CORBA.is_nil(ec): - return RTC.RTC_ERROR - return ec.reset_component(self.getObjRef()) - - - ## - # @if jp - # @brief [local interface] SDO service provider 򥻥åȤ - # @else - # @brief [local interface] Set a SDO service provider - # @endif - # - # bool addSdoServiceProvider(const SDOPackage::ServiceProfile& prof, - # SdoServiceProviderBase* provider); - def addSdoServiceProvider(self, prof, provider): - return self._sdoservice.addSdoServiceProvider(prof, provider) - - - ## - # @if jp - # @brief [local interface] SDO service provider - # @else - # @brief [local interface] Remove a SDO service provider - # @endif - # - # bool removeSdoServiceProvider(const char* id); - def removeSdoServiceProvider(self, id): - return self._sdoservice.removeSdoServiceProvider(id) - - - ## - # @if jp - # @brief [local interface] SDO service consumer 򥻥åȤ - # @else - # @brief [local interface] Set a SDO service consumer - # @endif - # - # bool addSdoServiceConsumer(const SDOPackage::ServiceProfile& prof); - def addSdoServiceConsumer(self, prof): - return self._sdoservice.addSdoServiceConsumer(prof) - - - ## - # @if jp - # @brief [local interface] SDO service consumer - # @else - # @brief [local interface] Remove a SDO service consumer - # @endif - # - # bool removeSdoServiceConsumer(const char* id); - def removeSdoServiceConsumer(self, id): - return self._sdoservice.removeSdoServiceConsumer(id) - - - ## - # @if jp - # - # @brief InPort Υǡɤ߹ࡣ - # - # RTC ݻƤ InPort Υǡɤ߹ࡣ - # - # @return ɤ߹߷(ݡȤɤ߹:true:false) - # - # @else - # - # @brief Readout the value from All InPorts. - # - # This operation read the value from all InPort - # registered in the RTC. - # - # @return result (Successful:true, Failed:false) - # - # @endif - # - # bool readAll(); - def readAll(self): - self._rtcout.RTC_TRACE("readAll()") - ret = True - for inport in self._inports: - if not inport.read(): - self._rtcout.RTC_DEBUG("The error occurred in readAll().") - ret = False - if not self._readAllCompletion: - return False + ## + # @if jp + # @brief FsmProfileListener リスナを追加する + # + # FSMへのプロファイルの設定、取得時、またFSM自体への状態や遷移、イ + # ベントの追加削除時にコールバックされる各種リスナを設定する。 + # + # 設定できるリスナのタイプとコールバックイベントは以下の通り + # + # - SET_FSM_PROFILE : FSM Profile設定時 + # - GET_FSM_PROFILE : FSM Profile取得時 + # - ADD_FSM_STATE : FSMにStateが追加された + # - REMOVE_FSM_STATE : FSMからStateが削除された + # - ADD_FSM_TRANSITION : FSMに遷移が追加された + # - REMOVE_FSM_TRANSITION : FSMから遷移が削除された + # - BIND_FSM_EVENT : FSMにイベントがバインドされた + # - UNBIND_FSM_EVENT : FSMにイベントがアンバインドされた + # + # リスナは FsmProfileListener を継承し、以下のシグニチャを持つ + # operator() を実装している必要がある。 + # + # FsmProfileListener::operator()(RTC::FsmProfile& pprof) + # + # デフォルトでは、この関数に与えたリスナオブジェクトの所有権は + # RTObjectに移り、RTObject解体時もしくは、 + # removeFsmProfileListener() により削除時に自動的に解体される。 + # リスナオブジェクトの所有権を呼び出し側で維持したい場合は、第3引 + # 数に false を指定し、自動的な解体を抑制することができる。 + # + # @param listener_type リスナタイプ + # @param listener リスナオブジェクトへのポインタ + # + # @else + # @brief Adding FsmProfile type listener + # + # This operation adds certain listeners that is called when + # setting/getting FsmProfile and stae/transition/event add/remove + # to/from the FSM itself. + # + # The following listener types are available. + # + # - SET_FSM_PROFILE : Setting FSM Profile + # - GET_FSM_PROFILE : Getting FSM Profile + # - ADD_FSM_STATE : A State added to the FSM + # - REMOVE_FSM_STATE : A State removed from FSM + # - ADD_FSM_TRANSITION : A transition added to the FSM + # - REMOVE_FSM_TRANSITION : A transition removed from FSM + # - BIND_FSM_EVENT : An event bounded to the FSM + # - UNBIND_FSM_EVENT : An event unbounded to the FSM + # + # Listeners should have the following function operator(). + # + # FsmProfileListener::operator()(RTC::PortProfile pprof) + # + # The ownership of the given listener object is transferred to + # this RTObject object in default. The given listener object will + # be destroied automatically in the RTObject's dtor or if the + # listener is deleted by removeFsmProfileListener() function. + # If you want to keep ownership of the listener object, give + # "false" value to 3rd argument to inhibit automatic destruction. + # + # @param listener_type A listener type + # @param listener A pointer to a listener object + # + # @endif + # + + def addFsmProfileListener(self, listener_type, + memfunc): + class Noname(OpenRTM_aist.FsmProfileListener): + def __init__(self, memfunc): + self._memfunc = memfunc + return + + def __call__(self, pprofile): + self._memfunc(pprofile) + return + + listener = Noname(memfunc) + self._fsmActionListeners.addProfileListener(listener_type, listener) + return listener + + ## + # @if jp + # @brief FsmProfileListener リスナを削除する + # + # 設定した各種リスナを削除する。 + # + # @param listener_type リスナタイプ + # @param listener リスナオブジェクトへのポインタ + # + # @else + # @brief Removing FsmProfileListener type listener + # + # This operation removes a specified listener. + # + # @param listener_type A listener type + # @param listener A pointer to a listener object + # + # @endif + # + + def removeFsmProfileListener(self, listener_type, listener): + self._fsmActionListeners.removeProfileListener(listener_type, listener) + return - return ret + ## + # @if jp + # @brief FsmStructureListener リスナを追加する + # + # ExtendedFsmService に関連する FSM structure の設定・取得時にコー + # ルバックされる各種リスナを設定する。 + # + # 設定できるリスナのタイプとコールバックイベントは以下の通り + # + # - SET_FSM_STRUCTURE: FSM構造の設定 + # - GET_FSM_STRUCTURE: FSM構造の取得 + # + # リスナは FsmStructureListener を継承し、以下のシグニチャを持つ + # operator() を実装している必要がある。 + # + # FsmStructureListener::operator()(FsmStructure& structure) + # + # デフォルトでは、この関数に与えたリスナオブジェクトの所有権は + # RTObjectに移り、RTObject解体時もしくは、 + # removeFsmStructureListener() により削除時に自動的に解体される。 + # リスナオブジェクトの所有権を呼び出し側で維持したい場合は、第3引 + # 数に false を指定し、自動的な解体を抑制することができる。 + # + # @param listener_type リスナタイプ + # @param listener リスナオブジェクトへのポインタ + # + # @else + # @brief Adding FsmStructure type listener + # + # This operation adds certain listeners related to FSM structure + # data which are handled by ExtendedFsmService. + # + # The following listener types are available. + # + # - SET_FSM_STRUCTURE: Setting FSM structure + # - GET_FSM_STRUCTURE: Getting FSM structure + # + # Listeners should have the following function operator(). + # + # FsmStructureListener::operator()(RTC::FsmStructure structure) + # + # The ownership of the given listener object is transferred to + # this RTObject object in default. The given listener object will + # be destroied automatically in the RTObject's dtor or if the + # listener is deleted by removeFsmStructureListener() function. + # If you want to keep ownership of the listener object, give + # "false" value to 3rd argument to inhibit automatic destruction. + # + # @param listener_type A listener type + # @param listener A pointer to a listener object + # + # @endif + # + def addFsmStructureListener(self, listener_type, + memfunc): + class Noname(OpenRTM_aist.FsmStructureListener): + def __init__(self, memfunc): + self._memfunc = memfunc + return + + def __call__(self, pprofile): + self._memfunc(pprofile) + return + + listener = Noname(memfunc) + self._fsmActionListeners.structure_[ + listener_type].addListener(listener) + return listener + + ## + # @if jp + # @brief FsmStructureListener リスナを削除する + # + # 設定した各種リスナを削除する。 + # + # @param listener_type リスナタイプ + # @param listener リスナオブジェクトへのポインタ + # + # @else + # @brief Removing FsmStructureListener type listener + # + # This operation removes a specified listener. + # + # @param listener_type A listener type + # @param listener A pointer to a listener object + # + # @endif + # + + def removeFsmStructureListener(self, listener_type, listener): + self._fsmActionListeners.structure_[ + listener_type].removeListener(listener) + return + ## + # @if jp + # + # @brief RTC を終了する + # + # RTC の終了処理を実行する。 + # 保持している全 Port の登録を解除するとともに、該当する CORBA オブジェクト + # を非活性化し、RTC を終了する。 + # + # @param self + # + # @else + # + # @endif + def shutdown(self): + self._rtcout.RTC_TRACE("shutdown()") + try: + self.finalizePorts() + self.finalizeContexts() + self._poa.deactivate_object( + self._poa.servant_to_id( + self._SdoConfigImpl)) + self._poa.deactivate_object(self._poa.servant_to_id(self)) + self._sdoservice.exit() + except BaseException: + self._rtcout.RTC_ERROR(OpenRTM_aist.Logger.print_exception()) + + if self._manager: + self._rtcout.RTC_DEBUG("Cleanup on Manager") + self._manager.notifyFinalized(self) + + del self._actionListeners + del self._portconnListeners - ## - # @if jp - # - # @brief OutPort write()᥽åɤ򥳡뤹롣 - # - # RTC ݻƤ OutPort write()᥽åɤ򥳡뤹롣 - # - # @return ɤ߹߷(ݡȤؤν񤭹:true:false) - # - # @else - # - # @brief The write() method of all OutPort is called. - # - # This operation call the write() method of all OutPort - # registered in the RTC. - # - # @return result (Successful:true, Failed:false) - # - # @endif - # - # bool writeAll(); - def writeAll(self): - self._rtcout.RTC_TRACE("writeAll()") - ret = True - for outport in self._outports: - if not outport.write(): - self._rtcout.RTC_DEBUG("The error occurred in writeAll().") - ret = False - if not self._writeAllCompletion: - return False + return - return ret + # inline void preOnInitialize(UniqueId ec_id) + def preOnInitialize(self, ec_id): + self._actionListeners.notifyPreAction(OpenRTM_aist.PreComponentActionListenerType.PRE_ON_INITIALIZE, ec_id) + return + # inline void preOnFinalize(UniqueId ec_id) + def preOnFinalize(self, ec_id): + self._actionListeners.notifyPreAction(OpenRTM_aist.PreComponentActionListenerType.PRE_ON_FINALIZE, ec_id) + return - ## - # @if jp - # - # @brief onExecute()¹ǤreadAll()᥽åɤθƽФͭޤ̵ˤ롣 - # - # Υ᥽åɤѥ᡼trueȤƸƤֻˤꡢonExecute()¹ - # readAll()ƽФ褦ˤʤ롣 - # ѥ᡼falseξϡreadAll()ƽФ̵ˤ롣 - # - # @param read(default:true) - # (readAll()᥽åɸƽФ:true, readAll()᥽åɸƽФʤ:false) - # - # @param completion(default:false) - # readAll()ˤơɤ줫ΰĤInPortread()ԤƤƤInPortread()ƤӽФ:true, - # readAll()ˤơɤ줫ΰĤInPortread()Ԥ硢falseȴ:false - # - # @else - # - # @brief Set whether to execute the readAll() method. - # - # Set whether to execute the readAll() method. - # - # @param read(default:true) - # (readAll() is called:true, readAll() isn't called:false) - # - # @param completion(default:false) - # All InPort::read() calls are completed.:true, - # If one InPort::read() is False, return false.:false - # - # @param completion(default:false) - # - # @endif - # - # void setReadAll(bool read=true, bool completion=false); - def setReadAll(self, read=True, completion=False): - self._readAll = read - self._readAllCompletion = completion - - - ## - # @if jp - # - # @brief onExecute()¹ԸwriteAll()᥽åɤθƽФͭޤ̵ˤ롣 - # - # Υ᥽åɤѥ᡼trueȤƸƤֻˤꡢonExecute()¹Ը - # writeAll()ƽФ褦ˤʤ롣 - # ѥ᡼falseξϡwriteAll()ƽФ̵ˤ롣 - # - # @param write(default:true) - # (writeAll()᥽åɸƽФ:true, writeAll()᥽åɸƽФʤ:false) - # - # @param completion(default:false) - # writeAll()ˤơɤ줫ΰĤOutPortwrite()ԤƤƤOutPortwrite()ƤӽФԤ:true, - # writeAll()ˤơɤ줫ΰĤOutPortwrite()Ԥ硢falseȴ:false - # - # @else - # - # @brief Set whether to execute the writeAll() method. - # - # Set whether to execute the writeAll() method. - # - # @param write(default:true) - # (writeAll() is called:true, writeAll() isn't called:false) - # - # @param completion(default:false) - # All OutPort::write() calls are completed.:true, - # If one OutPort::write() is False, return false.:false - # - # @endif - # - # void setWriteAll(bool write=true, bool completion=false); - def setWriteAll(self, write=True, completion=False): - self._writeAll = write - self._writeAllCompletion = completion - - - ## - # @if jp - # - # @brief Port Ͽ - # - # RTC ݻƤ Port 롣 - # - # @param self - # - # @else - # - # @brief Unregister the All Portse - # - # This operation deactivates the all Port and deletes the all Port's - # registrations in the RTC.. - # - # @endif - def finalizePorts(self): - self._rtcout.RTC_TRACE("finalizePorts()") - self._portAdmin.finalizePorts() - self._inports = [] - self._outports = [] - return - - - def finalizeContexts(self): - self._rtcout.RTC_TRACE("finalizeContexts()") - len_ = len(self._eclist) - for i in range(len_): - idx = (len_ - 1) - i - self._eclist[idx].stop() - try: - self._poa.deactivate_object(self._poa.servant_to_id(self._eclist[idx])) - except: - self._rtcout.RTC_TRACE(OpenRTM_aist.Logger.print_exception()) - del self._eclist[idx] - - - return - - - ## - # @if jp - # @brief PreComponentActionListener ꥹʤɲä - # - # ComponentAction ؿθƤӽФľΥ٥Ȥ˴ϢƼ - # ʤꤹ롣 - # - # ǤꥹʤΥפȥХå٥Ȥϰʲ̤ - # - # - PRE_ON_INITIALIZE: onInitialize ľ - # - PRE_ON_FINALIZE: onFinalize ľ - # - PRE_ON_STARTUP: onStartup ľ - # - PRE_ON_SHUTDOWN: onShutdown ľ - # - PRE_ON_ACTIVATED: onActivated ľ - # - PRE_ON_DEACTIVATED: onDeactivated ľ - # - PRE_ON_ABORTING: onAborted ľ - # - PRE_ON_ERROR: onError ľ - # - PRE_ON_RESET: onReset ľ - # - PRE_ON_EXECUTE: onExecute ľ - # - PRE_ON_STATE_UPDATE: onStateUpdate ľ - # - # ꥹʤ PreComponentActionListener ѾʲΥ˥ - # operator() Ƥɬפ롣 - # - # PreComponentActionListener::operator()(UniqueId ec_id) - # - # ǥեȤǤϡδؿͿꥹʥ֥Ȥνͭ - # RTObject˰ܤꡢRTObjectλ⤷ϡ - # removePreComponentActionListener() ˤ˼ưŪ˲Τ롣 - # ꥹʥ֥ȤνͭƤӽФ¦ǰݻϡ3 - # false ꤷưŪʲΤ뤳ȤǤ롣 - # - # @param listener_type ꥹʥ - # @param memfunc ؿ֥ - # @param autoclean ꥹʥ֥ȤμưŪΤԤɤΥե饰 - # - # @else - # @brief Adding PreComponentAction type listener - # - # This operation adds certain listeners related to ComponentActions - # pre events. - # The following listener types are available. - # - # - PRE_ON_INITIALIZE: before onInitialize - # - PRE_ON_FINALIZE: before onFinalize - # - PRE_ON_STARTUP: before onStartup - # - PRE_ON_SHUTDOWN: before onShutdown - # - PRE_ON_ACTIVATED: before onActivated - # - PRE_ON_DEACTIVATED: before onDeactivated - # - PRE_ON_ABORTING: before onAborted - # - PRE_ON_ERROR: before onError - # - PRE_ON_RESET: before onReset - # - PRE_ON_EXECUTE: before onExecute - # - PRE_ON_STATE_UPDATE: before onStateUpdate - # - # Listeners should have the following function operator(). - # - # PreComponentActionListener::operator()(UniqueId ec_id) - # - # The ownership of the given listener object is transferred to - # this RTObject object in default. The given listener object will - # be destroied automatically in the RTObject's dtor or if the - # listener is deleted by removePreComponentActionListener() function. - # If you want to keep ownership of the listener object, give - # "false" value to 3rd argument to inhibit automatic destruction. - # - # @param listener_type A listener type - # @param memfunc member function object - # @param autoclean A flag for automatic listener destruction - # - # @endif - # - # template - # PreComponentActionListener* - # addPreComponentActionListener(PreCompActionListenerType listener_type, - # void (Listener::*memfunc)(UniqueId ec_id), - # bool autoclean = true) - def addPreComponentActionListener(self, listener_type, - memfunc, autoclean = True): - class Noname(OpenRTM_aist.PreComponentActionListener): - def __init__(self, memfunc): - self._memfunc = memfunc - - def __call__(self, ec_id): - self._memfunc(ec_id) + # inline void preOnStartup(UniqueId ec_id) + def preOnStartup(self, ec_id): + self._actionListeners.notifyPreAction(OpenRTM_aist.PreComponentActionListenerType.PRE_ON_STARTUP, ec_id) return - listener = Noname(memfunc) - self._actionListeners.preaction_[listener_type].addListener(listener, autoclean) - return listener - - - ## - # @if jp - # @brief PreComponentActionListener ꥹʤ - # - # ꤷƼꥹʤ롣 - # - # @param listener_type ꥹʥ - # @param listener ꥹʥ֥ȤؤΥݥ - # - # @else - # @brief Removing PreComponentAction type listener - # - # This operation removes a specified listener. - # - # @param listener_type A listener type - # @param listener A pointer to a listener object - # - # @endif - # - # void - # removePreComponentActionListener(PreComponentActionListenerType listener_type, - # PreComponentActionListener* listener); - def removePreComponentActionListener(self, listener_type, listener): - self._actionListeners.preaction_[listener_type].removeListener(listener) - return - - - ## - # @if jp - # @brief PostComponentActionListener ꥹʤɲä - # - # ComponentAction ؿθƤӽФľΥ٥Ȥ˴ϢƼ - # ʤꤹ롣 - # - # ǤꥹʤΥפȥХå٥Ȥϰʲ̤ - # - # - POST_ON_INITIALIZE: onInitialize ľ - # - POST_ON_FINALIZE: onFinalize ľ - # - POST_ON_STARTUP: onStartup ľ - # - POST_ON_SHUTDOWN: onShutdown ľ - # - POST_ON_ACTIVATED: onActivated ľ - # - POST_ON_DEACTIVATED: onDeactivated ľ - # - POST_ON_ABORTING: onAborted ľ - # - POST_ON_ERROR: onError ľ - # - POST_ON_RESET: onReset ľ - # - POST_ON_EXECUTE: onExecute ľ - # - POST_ON_STATE_UPDATE: onStateUpdate ľ - # - # ꥹʤ PostComponentActionListener ѾʲΥ˥ - # operator() Ƥɬפ롣 - # - # PostComponentActionListener::operator()(UniqueId ec_id, ReturnCode_t ret) - # - # ǥեȤǤϡδؿͿꥹʥ֥Ȥνͭ - # RTObject˰ܤꡢRTObjectλ⤷ϡ - # removePostComponentActionListener() ˤ˼ưŪ˲Τ롣 - # ꥹʥ֥ȤνͭƤӽФ¦ǰݻϡ3 - # false ꤷưŪʲΤ뤳ȤǤ롣 - # - # @param listener_type ꥹʥ - # @param memfunc ؿ֥ - # @param autoclean ꥹʥ֥ȤμưŪΤԤɤΥե饰 - # - # @else - # @brief Adding PostComponentAction type listener - # - # This operation adds certain listeners related to ComponentActions - # post events. - # The following listener types are available. - # - # - POST_ON_INITIALIZE: after onInitialize - # - POST_ON_FINALIZE: after onFinalize - # - POST_ON_STARTUP: after onStartup - # - POST_ON_SHUTDOWN: after onShutdown - # - POST_ON_ACTIVATED: after onActivated - # - POST_ON_DEACTIVATED: after onDeactivated - # - POST_ON_ABORTING: after onAborted - # - POST_ON_ERROR: after onError - # - POST_ON_RESET: after onReset - # - POST_ON_EXECUTE: after onExecute - # - POST_ON_STATE_UPDATE: after onStateUpdate - # - # Listeners should have the following function operator(). - # - # PostComponentActionListener::operator()(UniqueId ec_id, ReturnCode_t ret) - # - # The ownership of the given listener object is transferred to - # this RTObject object in default. The given listener object will - # be destroied automatically in the RTObject's dtor or if the - # listener is deleted by removePostComponentActionListener() function. - # If you want to keep ownership of the listener object, give - # "false" value to 3rd argument to inhibit automatic destruction. - # - # @param listener_type A listener type - # @param memfunc member function object - # @param autoclean A flag for automatic listener destruction - # - # @endif - # - # template - # PostComponentActionListener* - # addPostComponentActionListener(PostCompActionListenerType listener_type, - # void (Listener::*memfunc)(UniqueId ec_id, - # ReturnCode_t ret), - # bool autoclean = true) - def addPostComponentActionListener(self, listener_type, - memfunc, autoclean = True): - class Noname(OpenRTM_aist.PostComponentActionListener): - def __init__(self, memfunc): - self._memfunc = memfunc + # inline void preOnShutdown(UniqueId ec_id) + def preOnShutdown(self, ec_id): + self._actionListeners.notifyPreAction(OpenRTM_aist.PreComponentActionListenerType.PRE_ON_SHUTDOWN, ec_id) return - def __call__(self, ec_id, ret): - self._memfunc(ec_id, ret) + + # inline void preOnActivated(UniqueId ec_id) + def preOnActivated(self, ec_id): + self._actionListeners.notifyPreAction(OpenRTM_aist.PreComponentActionListenerType.PRE_ON_ACTIVATED, ec_id) return - - listener = Noname(memfunc) - self._actionListeners.postaction_[listener_type].addListener(listener, autoclean) - return listener - - - ## - # @if jp - # @brief PostComponentActionListener ꥹʤ - # - # ꤷƼꥹʤ롣 - # - # @param listener_type ꥹʥ - # @param listener ꥹʥ֥ȤؤΥݥ - # - # @else - # @brief Removing PostComponentAction type listener - # - # This operation removes a specified listener. - # - # @param listener_type A listener type - # @param listener A pointer to a listener object - # - # @endif - ## - # void - # removePostComponentActionListener(PostComponentActionListenerType listener_type, - # PostComponentActionListener* listener); - def removePostComponentActionListener(self, listener_type, listener): - self._actionListeners.postaction_[listener_type].removeListener(listener) - return - - - ## - # @if jp - # @brief PortActionListener ꥹʤɲä - # - # Portɲá˥ХåƼꥹʤꤹ롣 - # - # ǤꥹʤΥפȥХå٥Ȥϰʲ̤ - # - # - ADD_PORT: Portɲû - # - REMOVE_PORT: Port - # - # ꥹʤ PortActionListener ѾʲΥ˥ - # operator() Ƥɬפ롣 - # - # PortActionListener::operator()(PortProfile& pprof) - # - # ǥեȤǤϡδؿͿꥹʥ֥Ȥνͭ - # RTObject˰ܤꡢRTObjectλ⤷ϡ - # removePortActionListener() ˤ˼ưŪ˲Τ롣 - # ꥹʥ֥ȤνͭƤӽФ¦ǰݻϡ3 - # false ꤷưŪʲΤ뤳ȤǤ롣 - # - # @param listener_type ꥹʥ - # @param memfunc ؿ֥ - # @param autoclean ꥹʥ֥ȤμưŪΤԤɤΥե饰 - # - # @else - # @brief Adding PortAction type listener - # - # This operation adds certain listeners related to ComponentActions - # post events. - # The following listener types are available. - # - # - ADD_PORT: At adding Port - # - REMOVE_PORT: At removing Port - # - # Listeners should have the following function operator(). - # - # PortActionListener::operator()(RTC::PortProfile pprof) - # - # The ownership of the given listener object is transferred to - # this RTObject object in default. The given listener object will - # be destroied automatically in the RTObject's dtor or if the - # listener is deleted by removePortActionListener() function. - # If you want to keep ownership of the listener object, give - # "false" value to 3rd argument to inhibit automatic destruction. - # - # @param listener_type A listener type - # @param memfunc member function object - # @param autoclean A flag for automatic listener destruction - # - # @endif - # - # template - # PortActionListener* - # addPortActionListener(PortActionListenerType listener_type, - # void (Listener::*memfunc)(const RTC::PortProfile&), - # bool autoclean=true) - def addPortActionListener(self, listener_type, - memfunc, autoclean = True): - class Noname(OpenRTM_aist.PortActionListener): - def __init__(self, memfunc): - self._memfunc = memfunc + + # inline void preOnDeactivated(UniqueId ec_id) + def preOnDeactivated(self, ec_id): + self._actionListeners.notifyPreAction(OpenRTM_aist.PreComponentActionListenerType.PRE_ON_DEACTIVATED, ec_id) return - def __call__(self, pprofile): - self._memfunc(pprofile) + # inline void preOnAborting(UniqueId ec_id) + def preOnAborting(self, ec_id): + self._actionListeners.notifyPreAction(OpenRTM_aist.PreComponentActionListenerType.PRE_ON_ABORTING, ec_id) return - listener = Noname(memfunc) - - self._actionListeners.portaction_[listener_type].addListener(listener, autoclean) - return listener - - - ## - # @if jp - # @brief PortActionListener ꥹʤ - # - # ꤷƼꥹʤ롣 - # - # @param listener_type ꥹʥ - # @param listener ꥹʥ֥ȤؤΥݥ - # - # @else - # @brief Removing PortAction type listener - # - # This operation removes a specified listener. - # - # @param listener_type A listener type - # @param listener A pointer to a listener object - # - # @endif - # void - # removePortActionListener(PortActionListenerType listener_type, - # PortActionListener* listener); - def removePortActionListener(self, listener_type, listener): - self._actionListeners.portaction_[listener_type].removeListener(listener) - return - - - ## - # @if jp - # @brief ExecutionContextActionListener ꥹʤɲä - # - # ExecutionContextɲá˥ХåƼꥹʤꤹ롣 - # - # ǤꥹʤΥפȥХå٥Ȥϰʲ̤ - # - # - ATTACH_EC: ExecutionContext å - # - DETACH_EC: ExecutionContext ǥå - # - # ꥹʤ ExecutionContextActionListener ѾʲΥ˥ - # operator() Ƥɬפ롣 - # - # ExecutionContextActionListener::operator()(UniqueIdec_id) - # - # ǥեȤǤϡδؿͿꥹʥ֥Ȥνͭ - # RTObject˰ܤꡢRTObjectλ⤷ϡ - # removeExecutionContextActionListener() ˤ˼ưŪ˲Τ롣 - # ꥹʥ֥ȤνͭƤӽФ¦ǰݻϡ3 - # false ꤷưŪʲΤ뤳ȤǤ롣 - # - # @param listener_type ꥹʥ - # @param memfunc ؿ֥ - # @param autoclean ꥹʥ֥ȤμưŪΤԤɤΥե饰 - # - # @else - # @brief Adding ExecutionContextAction type listener - # - # This operation adds certain listeners related to ComponentActions - # post events. - # The following listener types are available. - # - # - ADD_PORT: At adding ExecutionContext - # - REMOVE_PORT: At removing ExecutionContext - # - # Listeners should have the following function operator(). - # - # ExecutionContextActionListener::operator()(UniqueId ec_id) - # - # The ownership of the given listener object is transferred to - # this RTObject object in default. The given listener object will - # be destroied automatically in the RTObject's dtor or if the - # listener is deleted by removeExecutionContextActionListener() function. - # If you want to keep ownership of the listener object, give - # "false" value to 3rd argument to inhibit automatic destruction. - # - # @param listener_type A listener type - # @param memfunc member function object - # @param autoclean A flag for automatic listener destruction - # - # @endif - # - # template - # ECActionListener* - # addExecutionContextActionListener(ECActionListenerType listener_type, - # void (Listener::*memfunc)(UniqueId), - # bool autoclean = true); - def addExecutionContextActionListener(self, listener_type, - memfunc, autoclean = True): - class Noname(OpenRTM_aist.ExecutionContextActionListener): - def __init__(self, memfunc): - self._memfunc = memfunc + # inline void preOnError(UniqueId ec_id) + def preOnError(self, ec_id): + self._actionListeners.notifyPreAction(OpenRTM_aist.PreComponentActionListenerType.PRE_ON_ERROR, ec_id) return - def __call__(self, ec_id): - self._memfunc(ec_id) + # inline void preOnReset(UniqueId ec_id) + def preOnReset(self, ec_id): + self._actionListeners.notifyPreAction(OpenRTM_aist.PreComponentActionListenerType.PRE_ON_RESET, ec_id) return - listener = Noname(memfunc) - self._actionListeners.ecaction_[listener_type].addListener(listener, autoclean) - return listener - - - ## - # @if jp - # @brief ExecutionContextActionListener ꥹʤ - # - # ꤷƼꥹʤ롣 - # - # @param listener_type ꥹʥ - # @param listener ꥹʥ֥ȤؤΥݥ - # - # @else - # @brief Removing ExecutionContextAction type listener - # - # This operation removes a specified listener. - # - # @param listener_type A listener type - # @param listener A pointer to a listener object - # - # @endif - # - # void - # removeExecutionContextActionListener(ECActionListenerType listener_type, - # ECActionListener* listener); - def removeExecutionContextActionListener(self, listener_type, listener): - self._actionListeners.ecaction_[listener_type].removeListener(listener) - return - - - ## - # @if jp - # @brief PortConnectListener ꥹʤɲä - # - # Port³³˸ƤӽФƼꥹʤꤹ롣 - # - # ǤꥹʤΥפȥХå٥Ȥϰʲ̤ - # - # - ON_NOTIFY_CONNECT: notify_connect() ؿƤӽФľ - # - ON_NOTIFY_DISCONNECT: notify_disconnect() ƤӽФľ - # - ON_UNSUBSCRIBE_INTERFACES: notify_disconnect() IFɲ - # - # ꥹʤ PortConnectListener ѾʲΥ˥ - # operator() Ƥɬפ롣 - # - # PortConnectListener::operator()(const char*, ConnectorProfile) - # - # ǥեȤǤϡδؿͿꥹʥ֥Ȥνͭ - # RTObject˰ܤꡢRTObjectλ⤷ϡ - # removePortConnectListener() ˤ˼ưŪ˲Τ롣 - # ꥹʥ֥ȤνͭƤӽФ¦ǰݻϡ3 - # false ꤷưŪʲΤ뤳ȤǤ롣 - # - # @param listener_type ꥹʥ - # @param memfunc ؿ֥ - # @param autoclean ꥹʥ֥ȤμưŪΤԤɤΥե饰 - # - # @else - # @brief Adding PortConnect type listener - # - # This operation adds certain listeners related to Port's connect actions. - # The following listener types are available. - # - # - ON_NOTIFY_CONNECT: right after entering into notify_connect() - # - ON_NOTIFY_DISCONNECT: right after entering into notify_disconnect() - # - ON_UNSUBSCRIBE_INTERFACES: unsubscribing IF in notify_disconnect() - # - # Listeners should have the following function operator(). - # - # PortConnectListener::operator()(const char*, ConnectorProfile) - # - # The ownership of the given listener object is transferred to - # this RTObject object in default. The given listener object will - # be destroied automatically in the RTObject's dtor or if the - # listener is deleted by removePortConnectListener() function. - # If you want to keep ownership of the listener object, give - # "false" value to 3rd argument to inhibit automatic destruction. - # - # @param listener_type A listener type - # @param memfunc member function object - # @param autoclean A flag for automatic listener destruction - # - # @endif - # - # template - # PortConnectListener* - # addPortConnectListener(PortConnectListenerType listener_type, - # void (Listener::*memfunc)(const char*, - # ConnectorProfile&), - # bool autoclean = true) - def addPortConnectListener(self, listener_type, - memfunc, autoclean = True): - class Noname(OpenRTM_aist.PortConnectListener): - def __init__(self, memfunc): - self._memfunc = memfunc + # inline void preOnExecute(UniqueId ec_id) + def preOnExecute(self, ec_id): + self._actionListeners.notifyPreAction(OpenRTM_aist.PreComponentActionListenerType.PRE_ON_EXECUTE, ec_id) return - def __call__(self, portname, cprofile): - self._memfunc(portname, cprofile) + # inline void preOnStateUpdate(UniqueId ec_id) + def preOnStateUpdate(self, ec_id): + self._actionListeners.notifyPreAction(OpenRTM_aist.PreComponentActionListenerType.PRE_ON_STATE_UPDATE, ec_id) return - listener = Noname(memfunc) - self._portconnListeners.portconnect_[listener_type].addListener(listener, autoclean) - return listener - - - ## - # @if jp - # @brief PortConnectListener ꥹʤ - # - # ꤷƼꥹʤ롣 - # - # @param listener_type ꥹʥ - # @param listener ꥹʥ֥ȤؤΥݥ - # - # @else - # @brief Removing PortConnect type listener - # - # This operation removes a specified listener. - # - # @param listener_type A listener type - # @param listener A pointer to a listener object - # - # @endif - # - # void - # removePortConnectListener(PortConnectListenerType listener_type, - # PortConnectListener* listener); - def removePortConnectListener(self, listener_type, listener): - self._portconnListeners.portconnect_[listener_type].removeListener(listener) - return - - - ## - # @if jp - # @brief PortConnectRetListener ꥹʤɲä - # - # Port³³˸ƤӽФƼꥹʤꤹ롣 - # - # ǤꥹʤΥפȥХå٥Ȥϰʲ̤ - # - # - ON_CONNECT_NEXTPORT: notify_connect() ΥɸƤӽФľ - # - ON_SUBSCRIBE_INTERFACES: notify_connect() Υ󥿡եľ - # - ON_CONNECTED: nofity_connect() ³λ˸ƤӽФ - # - ON_DISCONNECT_NEXT: notify_disconnect() ˥ɸƤӽФľ - # - ON_DISCONNECTED: notify_disconnect() ꥿ - # - # ꥹʤ PortConnectRetListener ѾʲΥ˥ - # operator() Ƥɬפ롣 - # - # PortConnectRetListener::operator()(const char*, ConnectorProfile) - # - # ǥեȤǤϡδؿͿꥹʥ֥Ȥνͭ - # RTObject˰ܤꡢRTObjectλ⤷ϡ - # removePortConnectRetListener() ˤ˼ưŪ˲Τ롣 - # ꥹʥ֥ȤνͭƤӽФ¦ǰݻϡ3 - # false ꤷưŪʲΤ뤳ȤǤ롣 - # - # @param listener_type ꥹʥ - # @param memfunc ؿ֥ - # @param autoclean ꥹʥ֥ȤμưŪΤԤɤΥե饰 - # - # @else - # @brief Adding PortConnectRet type listener - # - # This operation adds certain listeners related to Port's connect actions. - # The following listener types are available. - # - # - ON_CONNECT_NEXTPORT: after cascade-call in notify_connect() - # - ON_SUBSCRIBE_INTERFACES: after IF subscribing in notify_connect() - # - ON_CONNECTED: completed nofity_connect() connection process - # - ON_DISCONNECT_NEXT: after cascade-call in notify_disconnect() - # - ON_DISCONNECTED: completed notify_disconnect() disconnection process - # - # Listeners should have the following function operator(). - # - # PortConnectRetListener::operator()(const char*, ConnectorProfile) - # - # The ownership of the given listener object is transferred to - # this RTObject object in default. The given listener object will - # be destroied automatically in the RTObject's dtor or if the - # listener is deleted by removePortConnectRetListener() function. - # If you want to keep ownership of the listener object, give - # "false" value to 3rd argument to inhibit automatic destruction. - # - # @param listener_type A listener type - # @param memfunc member function object - # @param autoclean A flag for automatic listener destruction - # - # @endif - # - # template - # PortConnectRetListener* - # addPortConnectRetListener(PortConnectRetListenerType listener_type, - # void (Listener::*memfunc)(const char*, - # ConnectorProfile&, - # ReturnCode_t)) - def addPortConnectRetListener(self, listener_type, - memfunc, autoclean = True): - class Noname(OpenRTM_aist.PortConnectRetListener): - def __init__(self, memfunc): - self._memfunc = memfunc + # inline void preOnRateChanged(UniqueId ec_id) + + def preOnRateChanged(self, ec_id): + self._actionListeners.notifyPreAction(OpenRTM_aist.PreComponentActionListenerType.PRE_ON_RATE_CHANGED, ec_id) return - def __call__(self, portname, cprofile, ret): - self._memfunc(portname, cprofile, ret) + # inline void postOnInitialize(UniqueId ec_id, ReturnCode_t ret) + + def postOnInitialize(self, ec_id, ret): + self._actionListeners.notifyPostAction( + OpenRTM_aist.PostComponentActionListenerType.POST_ON_INITIALIZE, ec_id, ret) return - listener = Noname(memfunc) - self._portconnListeners.portconnret_[listener_type].addListener(listener, autoclean) - return listener - - - ## - # @if jp - # @brief PortConnectRetListener ꥹʤ - # - # ꤷƼꥹʤ롣 - # - # @param listener_type ꥹʥ - # @param listener ꥹʥ֥ȤؤΥݥ - # - # @else - # @brief Removing PortConnectRet type listener - # - # This operation removes a specified listener. - # - # @param listener_type A listener type - # @param listener A pointer to a listener object - # - # @endif - # - # void - # removePortConnectRetListener(PortConnectRetListenerType listener_type, - # PortConnectRetListener* listener); - def removePortConnectRetListener(self, listener_type, listener): - self._portconnListeners.portconnret_[listener_type].removeListener(listener) - return - - - ## - # @if jp - # - # @brief ConfigurationParamListener ɲä - # - # update(const char* config_set, const char* config_param) ƤФ줿ݤ - # 뤵ꥹ ConfigurationParamListener ɲä롣 - # type ˤϸߤΤȤ ON_UPDATE_CONFIG_PARAM Τߤ롣 - # - # @param type ConfigurationParamListenerType͡ - # ON_UPDATE_CONFIG_PARAM 롣 - # - # @param memfunc ؿ֥ - # @param autoclean ꥹʥ֥ȤưǺ뤫ɤΥե饰 - # - # @else - # - # @brief Adding ConfigurationParamListener - # - # This function adds a listener object which is called when - # update(const char* config_set, const char* config_param) is - # called. In the type argument, currently only - # ON_UPDATE_CONFIG_PARAM is allowed. - # - # @param type ConfigurationParamListenerType value - # ON_UPDATE_CONFIG_PARAM is only allowed. - # - # @param memfunc member function object - # @param autoclean a flag whether if the listener object autocleaned. - # - # @endif - # - # template - # ConfigurationParamListener* - # addConfigurationParamListener(ConfigurationParamListenerType listener_type, - # void (Listener::*memfunc)(const char*, - # const char*), - # bool autoclean = true) - def addConfigurationParamListener(self, type, - memfunc, autoclean = True): - class Noname(OpenRTM_aist.ConfigurationParamListener): - def __init__(self, memfunc): - self._memfunc = memfunc + # inline void postOnFinalize(UniqueId ec_id, ReturnCode_t ret) + + def postOnFinalize(self, ec_id, ret): + self._actionListeners.notifyPostAction( + OpenRTM_aist.PostComponentActionListenerType.POST_ON_FINALIZE, ec_id, ret) return - def __call__(self, config_set_name, config_param_name): - self._memfunc(config_set_name, config_param_name) + # inline void postOnStartup(UniqueId ec_id, ReturnCode_t ret) + + def postOnStartup(self, ec_id, ret): + self._actionListeners.notifyPostAction( + OpenRTM_aist.PostComponentActionListenerType.POST_ON_STARTUP, ec_id, ret) return - listener = Noname(memfunc) - self._configsets.addConfigurationParamListener(type, listener, autoclean) - return listener - - - ## - # @if jp - # - # @brief ConfigurationParamListener - # - # addConfigurationParamListener ɲä줿ꥹʥ֥Ȥ롣 - # - # @param type ConfigurationParamListenerType͡ - # ON_UPDATE_CONFIG_PARAM 롣 - # @param listener Ϳꥹʥ֥ȤؤΥݥ - # - # @else - # - # @brief Removing ConfigurationParamListener - # - # This function removes a listener object which is added by - # addConfigurationParamListener() function. - # - # @param type ConfigurationParamListenerType value - # ON_UPDATE_CONFIG_PARAM is only allowed. - # @param listener a pointer to ConfigurationParamListener listener object. - # - # @endif - # - # void removeConfigurationParamListener(ConfigurationParamListenerType type, - # ConfigurationParamListener* listener); - def removeConfigurationParamListener(self, type, listener): - self._configsets.removeConfigurationParamListener(type, listener) - return - - - ## - # @if jp - # - # @brief ConfigurationSetListener ɲä - # - # ConfigurationSet 줿Ȥʤɤ˸ƤФꥹ - # ConfigurationSetListener ɲä롣ǽʥ٥Ȥϰʲ - # 2ब롣 - # - # - ON_SET_CONFIG_SET: setConfigurationSetValues() - # ConfigurationSet ͤꤵ줿硣 - # - ON_ADD_CONFIG_SET: addConfigurationSet() ǿ - # ConfigurationSet ɲä줿硣 - # - # @param type ConfigurationSetListenerType͡ - # @param memfunc ؿ֥ - # @param autoclean ꥹʥ֥ȤưǺ뤫ɤΥե饰 - # - # @else - # - # @brief Adding ConfigurationSetListener - # - # This function add a listener object which is called when - # ConfigurationSet is updated. Available events are the followings. - # - # @param type ConfigurationSetListenerType value - # @param memfunc member function object - # @param autoclean a flag whether if the listener object autocleaned. - # - # @endif - # - # template - # ConfigurationSetListener* - # addConfigurationSetListener(ConfigurationSetListenerType listener_type, - # void (Listener::*memfunc) - # (const coil::Properties& config_set)) - def addConfigurationSetListener(self, listener_type, - memfunc, autoclean = True): - class Noname(OpenRTM_aist.ConfigurationSetListener): - def __init__(self, memfunc): - self._memfunc = memfunc + # inline void postOnShutdown(UniqueId ec_id, ReturnCode_t ret) + + def postOnShutdown(self, ec_id, ret): + self._actionListeners.notifyPostAction( + OpenRTM_aist.PostComponentActionListenerType.POST_ON_SHUTDOWN, ec_id, ret) return - def __call__(self, config_set): - self._memfunc(config_set) + # inline void postOnActivated(UniqueId ec_id, ReturnCode_t ret) + + def postOnActivated(self, ec_id, ret): + self._actionListeners.notifyPostAction( + OpenRTM_aist.PostComponentActionListenerType.POST_ON_ACTIVATED, ec_id, ret) return - listener = Noname(memfunc) - self._configsets.addConfigurationSetListener(listener_type, listener, autoclean) - return listener - - - ## - # @if jp - # - # @brief ConfigurationSetListener - # - # addConfigurationSetListener ɲä줿ꥹʥ֥Ȥ롣 - # - # @param type ConfigurationSetListenerType͡ - # @param listener Ϳꥹʥ֥ȤؤΥݥ - # - # @else - # - # @brief Removing ConfigurationSetListener - # - # This function removes a listener object which is added by - # addConfigurationSetListener() function. - # - # @param type ConfigurationSetListenerType value - # @param listener a pointer to ConfigurationSetListener listener object. - # - # @endif - # - # void removeConfigurationSetListener(ConfigurationSetListenerType type, - # ConfigurationSetListener* listener); - def removeConfigurationSetListener(self, type, listener): - self._configsets.removeConfigurationSetListener(type, listener) - return - - - ## - # @if jp - # - # @brief ConfigurationSetNameListener ɲä - # - # ConfigurationSetName 줿Ȥʤɤ˸ƤФꥹ - # ConfigurationSetNameListener ɲä롣ǽʥ٥Ȥϰʲ - # 3ब롣 - # - # - ON_UPDATE_CONFIG_SET: ConfigurationSet åץǡȤ줿 - # - ON_REMOVE_CONFIG_SET: ConfigurationSet 줿 - # - ON_ACTIVATE_CONFIG_SET: ConfigurationSet ƥֲ줿 - # - # @param type ConfigurationSetNameListenerType͡ - # @param memfunc ؿ֥ - # @param autoclean ꥹʥ֥ȤưǺ뤫ɤΥե饰 - # - # @else - # - # @brief Adding ConfigurationSetNameListener - # - # This function add a listener object which is called when - # ConfigurationSetName is updated. Available events are the followings. - # - # - ON_UPDATE_CONFIG_SET: A ConfigurationSet has been updated. - # - ON_REMOVE_CONFIG_SET: A ConfigurationSet has been deleted. - # - ON_ACTIVATE_CONFIG_SET: A ConfigurationSet has been activated. - # - # @param type ConfigurationSetNameListenerType value - # @param memfunc member function object - # @param autoclean a flag whether if the listener object autocleaned. - # - # @endif - # - # template - # ConfigurationSetNameListener* - # addConfigurationSetNameListener(ConfigurationSetNameListenerType type, - # void (Listener::*memfunc)(const char*)) - def addConfigurationSetNameListener(self, type, memfunc, autoclean = True): - class Noname(OpenRTM_aist.ConfigurationSetNameListener): - def __init__(self, memfunc): - self._memfunc = memfunc + # inline void postOnDeactivated(UniqueId ec_id, ReturnCode_t ret) + + def postOnDeactivated(self, ec_id, ret): + self._actionListeners.notifyPostAction( + OpenRTM_aist.PostComponentActionListenerType.POST_ON_DEACTIVATED, ec_id, ret) return - def __call__(self, config_set_name): - self._memfunc(config_set_name) + # inline void postOnAborting(UniqueId ec_id, ReturnCode_t ret) + + def postOnAborting(self, ec_id, ret): + self._actionListeners.notifyPostAction( + OpenRTM_aist.PostComponentActionListenerType.POST_ON_ABORTING, ec_id, ret) return - listener = Noname(memfunc) - self._configsets.addConfigurationSetNameListener(type, listener, autoclean) - return listener - - - ## - # @if jp - # - # @brief ConfigurationSetNameListener - # - # addConfigurationSetNameListener ɲä줿ꥹʥ֥Ȥ - # 롣 - # - # @param type ConfigurationSetNameListenerType͡ - # ON_UPDATE_CONFIG_PARAM 롣 - # @param listener Ϳꥹʥ֥ȤؤΥݥ - # - # @else - # - # @brief Removing ConfigurationSetNameListener - # - # This function removes a listener object which is added by - # addConfigurationSetNameListener() function. - # - # @param type ConfigurationSetNameListenerType value - # ON_UPDATE_CONFIG_PARAM is only allowed. - # @param listener a pointer to ConfigurationSetNameListener - # listener object. - # - # @endif - # void - # removeConfigurationSetNameListener(ConfigurationSetNameListenerType type, - # ConfigurationSetNameListener* listener); - def removeConfigurationSetNameListener(self, type, listener): - self._configsets.removeConfigurationSetNameListener(type, listener) - return - - ## - # @if jp - # @brief PreFsmActionListener ꥹʤɲä - # - # FsmAction ؿθƤӽФľΥ٥Ȥ˴ϢƼ - # ʤꤹ롣 - # - # ǤꥹʤΥפȥХå٥Ȥϰʲ̤ - # - # - PRE_ON_INITIALIZE: onInitialize ľ - # - PRE_ON_FINALIZE: onFinalize ľ - # - PRE_ON_STARTUP: onStartup ľ - # - PRE_ON_SHUTDOWN: onShutdown ľ - # - PRE_ON_ACTIVATED: onActivated ľ - # - PRE_ON_DEACTIVATED: onDeactivated ľ - # - PRE_ON_ABORTED: onAborted ľ - # - PRE_ON_ERROR: onError ľ - # - PRE_ON_RESET: onReset ľ - # - PRE_ON_EXECUTE: onExecute ľ - # - PRE_ON_STATE_UPDATE: onStateUpdate ľ - # - # ꥹʤ PreFsmActionListener ѾʲΥ˥ - # operator() Ƥɬפ롣 - # - # PreFsmActionListener::operator()(UniqueId ec_id) - # - # ǥեȤǤϡδؿͿꥹʥ֥Ȥνͭ - # RTObject˰ܤꡢRTObjectλ⤷ϡ - # removePreFsmActionListener() ˤ˼ưŪ˲Τ롣 - # ꥹʥ֥ȤνͭƤӽФ¦ǰݻϡ3 - # false ꤷưŪʲΤ뤳ȤǤ롣 - # - # @param listener_type ꥹʥ - # @param listener ꥹʥ֥ȤؤΥݥ - # @param autoclean ꥹʥ֥ȤμưŪΤԤɤΥե饰 - # - # @else - # @brief Adding PreFsmAction type listener - # - # This operation adds certain listeners related to FsmActions - # pre events. - # The following listener types are available. - # - # - PRE_ON_INITIALIZE: before onInitialize - # - PRE_ON_FINALIZE: before onFinalize - # - PRE_ON_STARTUP: before onStartup - # - PRE_ON_SHUTDOWN: before onShutdown - # - PRE_ON_ACTIVATED: before onActivated - # - PRE_ON_DEACTIVATED: before onDeactivated - # - PRE_ON_ABORTED: before onAborted - # - PRE_ON_ERROR: before onError - # - PRE_ON_RESET: before onReset - # - PRE_ON_EXECUTE: before onExecute - # - PRE_ON_STATE_UPDATE: before onStateUpdate - # - # Listeners should have the following function operator(). - # - # PreFsmActionListener::operator()(UniqueId ec_id) - # - # The ownership of the given listener object is transferred to - # this RTObject object in default. The given listener object will - # be destroied automatically in the RTObject's dtor or if the - # listener is deleted by removePreFsmActionListener() function. - # If you want to keep ownership of the listener object, give - # "false" value to 3rd argument to inhibit automatic destruction. - # - # @param listener_type A listener type - # @param listener A pointer to a listener object - # @param autoclean A flag for automatic listener destruction - # - # @endif - # - def addPreFsmActionListener(self, listener_type, - memfunc, autoclean = True): - class Noname(OpenRTM_aist.PreFsmActionListener): - def __init__(self, memfunc): - self._memfunc = memfunc + # inline void postOnError(UniqueId ec_id, ReturnCode_t ret) + + def postOnError(self, ec_id, ret): + self._actionListeners.notifyPostAction( + OpenRTM_aist.PostComponentActionListenerType.POST_ON_ERROR, ec_id, ret) return - def __call__(self, state): - self._memfunc(state) + # inline void postOnReset(UniqueId ec_id, ReturnCode_t ret) + + def postOnReset(self, ec_id, ret): + self._actionListeners.notifyPostAction( + OpenRTM_aist.PostComponentActionListenerType.POST_ON_RESET, ec_id, ret) return - listener = Noname(memfunc) - self._fsmActionListeners.preaction_[listener_type].addListener(listener, autoclean) - return listener - - ## - # @if jp - # @brief PreFsmActionListener ꥹʤ - # - # ꤷƼꥹʤ롣 - # - # @param listener_type ꥹʥ - # @param listener ꥹʥ֥ȤؤΥݥ - # - # @else - # @brief Removing PreFsmAction type listener - # - # This operation removes a specified listener. - # - # @param listener_type A listener type - # @param listener A pointer to a listener object - # - # @endif - # - def removePreFsmActionListener(self, listener_type, listener): - self._fsmActionListeners.preaction_[listener_type].removeListener(listener) - return - - - ## - # @if jp - # @brief PostFsmActionListener ꥹʤɲä - # - # FsmAction ؿθƤӽФľΥ٥Ȥ˴ϢƼ - # ʤꤹ롣 - # - # ǤꥹʤΥפȥХå٥Ȥϰʲ̤ - # - # - POST_ON_INITIALIZE: onInitialize ľ - # - POST_ON_FINALIZE: onFinalize ľ - # - POST_ON_STARTUP: onStartup ľ - # - POST_ON_SHUTDOWN: onShutdown ľ - # - POST_ON_ACTIVATED: onActivated ľ - # - POST_ON_DEACTIVATED: onDeactivated ľ - # - POST_ON_ABORTED: onAborted ľ - # - POST_ON_ERROR: onError ľ - # - POST_ON_RESET: onReset ľ - # - POST_ON_EXECUTE: onExecute ľ - # - POST_ON_STATE_UPDATE: onStateUpdate ľ - # - # ꥹʤ PostFsmActionListener ѾʲΥ˥ - # operator() Ƥɬפ롣 - # - # PostFsmActionListener::operator()(const char* state, ReturnCode_t ret) - # - # ǥեȤǤϡδؿͿꥹʥ֥Ȥνͭ - # RTObject˰ܤꡢRTObjectλ⤷ϡ - # removePostFsmActionListener() ˤ˼ưŪ˲Τ롣 - # ꥹʥ֥ȤνͭƤӽФ¦ǰݻϡ3 - # false ꤷưŪʲΤ뤳ȤǤ롣 - # - # @param listener_type ꥹʥ - # @param listener ꥹʥ֥ȤؤΥݥ - # @param autoclean ꥹʥ֥ȤμưŪΤԤɤΥե饰 - # - # @else - # @brief Adding PostFsmAction type listener - # - # This operation adds certain listeners related to FsmActions - # post events. - # The following listener types are available. - # - # - POST_ON_INITIALIZE: after onInitialize - # - POST_ON_FINALIZE: after onFinalize - # - POST_ON_STARTUP: after onStartup - # - POST_ON_SHUTDOWN: after onShutdown - # - POST_ON_ACTIVATED: after onActivated - # - POST_ON_DEACTIVATED: after onDeactivated - # - POST_ON_ABORTED: after onAborted - # - POST_ON_ERROR: after onError - # - POST_ON_RESET: after onReset - # - POST_ON_EXECUTE: after onExecute - # - POST_ON_STATE_UPDATE: after onStateUpdate - # - # Listeners should have the following function operator(). - # - # PostFsmActionListener::operator()(const char* state, ReturnCode_t ret) - # - # The ownership of the given listener object is transferred to - # this RTObject object in default. The given listener object will - # be destroied automatically in the RTObject's dtor or if the - # listener is deleted by removePostFsmActionListener() function. - # If you want to keep ownership of the listener object, give - # "false" value to 3rd argument to inhibit automatic destruction. - # - # @param listener_type A listener type - # @param listener A pointer to a listener object - # @param autoclean A flag for automatic listener destruction - # - # @endif - # - def addPostFsmActionListener(self, listener_type, - memfunc, autoclean = True): - class Noname(OpenRTM_aist.PostFsmActionListener): - def __init__(self, memfunc): - self._memfunc = memfunc + # inline void postOnExecute(UniqueId ec_id, ReturnCode_t ret) + + def postOnExecute(self, ec_id, ret): + self._actionListeners.notifyPostAction( + OpenRTM_aist.PostComponentActionListenerType.POST_ON_EXECUTE, ec_id, ret) return - def __call__(self, state, ret): - self._memfunc(state, ret) + # inline void postOnStateUpdate(UniqueId ec_id, ReturnCode_t ret) + + def postOnStateUpdate(self, ec_id, ret): + self._actionListeners.notifyPostAction( + OpenRTM_aist.PostComponentActionListenerType.POST_ON_STATE_UPDATE, ec_id, ret) return - listener = Noname(memfunc) - self._fsmActionListeners.postaction_[listener_type].addListener(listener, autoclean) - return listener - - - - ## - # @if jp - # @brief PostFsmActionListener ꥹʤ - # - # ꤷƼꥹʤ롣 - # - # @param listener_type ꥹʥ - # @param listener ꥹʥ֥ȤؤΥݥ - # - # @else - # @brief Removing PostFsmActionListener type listener - # - # This operation removes a specified listener. - # - # @param listener_type A listener type - # @param listener A pointer to a listener object - # - # @endif - # - def removePostFsmActionListener(self, listener_type, listener): - self._fsmActionListeners.postaction_[listener_type].removeListener(listener) - return - - - - ## - # @if jp - # @brief FsmProfileListener ꥹʤɲä - # - # FSMؤΥץեꡢޤFSMΤؤξ֤ܡ - # ٥Ȥɲú˥ХåƼꥹʤꤹ롣 - # - # ǤꥹʤΥפȥХå٥Ȥϰʲ̤ - # - # - SET_FSM_PROFILE : FSM Profile - # - GET_FSM_PROFILE : FSM Profile - # - ADD_FSM_STATE : FSMStateɲä줿 - # - REMOVE_FSM_STATE : FSMState줿 - # - ADD_FSM_TRANSITION : FSMܤɲä줿 - # - REMOVE_FSM_TRANSITION : FSMܤ줿 - # - BIND_FSM_EVENT : FSM˥٥ȤХɤ줿 - # - UNBIND_FSM_EVENT : FSM˥٥ȤХɤ줿 - # - # ꥹʤ FsmProfileListener ѾʲΥ˥ - # operator() Ƥɬפ롣 - # - # FsmProfileListener::operator()(RTC::FsmProfile& pprof) - # - # ǥեȤǤϡδؿͿꥹʥ֥Ȥνͭ - # RTObject˰ܤꡢRTObjectλ⤷ϡ - # removeFsmProfileListener() ˤ˼ưŪ˲Τ롣 - # ꥹʥ֥ȤνͭƤӽФ¦ǰݻϡ3 - # false ꤷưŪʲΤ뤳ȤǤ롣 - # - # @param listener_type ꥹʥ - # @param listener ꥹʥ֥ȤؤΥݥ - # @param autoclean ꥹʥ֥ȤμưŪΤԤɤΥե饰 - # - # @else - # @brief Adding FsmProfile type listener - # - # This operation adds certain listeners that is called when - # setting/getting FsmProfile and stae/transition/event add/remove - # to/from the FSM itself. - # - # The following listener types are available. - # - # - SET_FSM_PROFILE : Setting FSM Profile - # - GET_FSM_PROFILE : Getting FSM Profile - # - ADD_FSM_STATE : A State added to the FSM - # - REMOVE_FSM_STATE : A State removed from FSM - # - ADD_FSM_TRANSITION : A transition added to the FSM - # - REMOVE_FSM_TRANSITION : A transition removed from FSM - # - BIND_FSM_EVENT : An event bounded to the FSM - # - UNBIND_FSM_EVENT : An event unbounded to the FSM - # - # Listeners should have the following function operator(). - # - # FsmProfileListener::operator()(RTC::PortProfile pprof) - # - # The ownership of the given listener object is transferred to - # this RTObject object in default. The given listener object will - # be destroied automatically in the RTObject's dtor or if the - # listener is deleted by removeFsmProfileListener() function. - # If you want to keep ownership of the listener object, give - # "false" value to 3rd argument to inhibit automatic destruction. - # - # @param listener_type A listener type - # @param listener A pointer to a listener object - # @param autoclean A flag for automatic listener destruction - # - # @endif - # - def addFsmProfileListener(self, listener_type, - memfunc, autoclean = True): - class Noname(OpenRTM_aist.FsmProfileListener): - def __init__(self, memfunc): - self._memfunc = memfunc + # inline void postOnRateChanged(UniqueId ec_id, ReturnCode_t ret) + + def postOnRateChanged(self, ec_id, ret): + self._actionListeners.notifyPostAction( + OpenRTM_aist.PostComponentActionListenerType.POST_ON_RATE_CHANGED, ec_id, ret) return - def __call__(self, pprofile): - self._memfunc(pprofile) + # inline void onAddPort(const PortProfile& pprof) + + def onAddPort(self, pprof): + self._actionListeners.notifyPortAction(OpenRTM_aist.PortActionListenerType.ADD_PORT, pprof) return - listener = Noname(memfunc) - self._fsmActionListeners.profile_[listener_type].addListener(listener, autoclean) - return listener - - - - ## - # @if jp - # @brief FsmProfileListener ꥹʤ - # - # ꤷƼꥹʤ롣 - # - # @param listener_type ꥹʥ - # @param listener ꥹʥ֥ȤؤΥݥ - # - # @else - # @brief Removing FsmProfileListener type listener - # - # This operation removes a specified listener. - # - # @param listener_type A listener type - # @param listener A pointer to a listener object - # - # @endif - # - def removeFsmProfileListener(self, listener_type, listener): - self._fsmActionListeners.profile_[listener_type].removeListener(listener) - return - - ## - # @if jp - # @brief FsmStructureListener ꥹʤɲä - # - # ExtendedFsmService ˴Ϣ FSM structure ꡦ˥ - # ХåƼꥹʤꤹ롣 - # - # ǤꥹʤΥפȥХå٥Ȥϰʲ̤ - # - # - SET_FSM_STRUCTURE: FSM¤ - # - GET_FSM_STRUCTURE: FSM¤μ - # - # ꥹʤ FsmStructureListener ѾʲΥ˥ - # operator() Ƥɬפ롣 - # - # FsmStructureListener::operator()(FsmStructure& structure) - # - # ǥեȤǤϡδؿͿꥹʥ֥Ȥνͭ - # RTObject˰ܤꡢRTObjectλ⤷ϡ - # removeFsmStructureListener() ˤ˼ưŪ˲Τ롣 - # ꥹʥ֥ȤνͭƤӽФ¦ǰݻϡ3 - # false ꤷưŪʲΤ뤳ȤǤ롣 - # - # @param listener_type ꥹʥ - # @param listener ꥹʥ֥ȤؤΥݥ - # @param autoclean ꥹʥ֥ȤμưŪΤԤɤΥե饰 - # - # @else - # @brief Adding FsmStructure type listener - # - # This operation adds certain listeners related to FSM structure - # data which are handled by ExtendedFsmService. - # - # The following listener types are available. - # - # - SET_FSM_STRUCTURE: Setting FSM structure - # - GET_FSM_STRUCTURE: Getting FSM structure - # - # Listeners should have the following function operator(). - # - # FsmStructureListener::operator()(RTC::FsmStructure structure) - # - # The ownership of the given listener object is transferred to - # this RTObject object in default. The given listener object will - # be destroied automatically in the RTObject's dtor or if the - # listener is deleted by removeFsmStructureListener() function. - # If you want to keep ownership of the listener object, give - # "false" value to 3rd argument to inhibit automatic destruction. - # - # @param listener_type A listener type - # @param listener A pointer to a listener object - # @param autoclean A flag for automatic listener destruction - # - # @endif - # - def addFsmStructureListener(self, listener_type, - memfunc, autoclean = True): - class Noname(OpenRTM_aist.FsmStructureListener): - def __init__(self, memfunc): - self._memfunc = memfunc + # inline void onRemovePort(const PortProfile& pprof) + + def onRemovePort(self, pprof): + self._actionListeners.notifyPortAction(OpenRTM_aist.PortActionListenerType.REMOVE_PORT, pprof) return - def __call__(self, pprofile): - self._memfunc(pprofile) + # inline void onAttachExecutionContext(UniqueId ec_id) + + def onAttachExecutionContext(self, ec_id): + self._actionListeners.notifyECAction(OpenRTM_aist.ExecutionContextActionListenerType.EC_ATTACHED, ec_id) return - listener = Noname(memfunc) - self._fsmActionListeners.structure_[listener_type].addListener(listener, autoclean) - return listener - - - ## - # @if jp - # @brief FsmStructureListener ꥹʤ - # - # ꤷƼꥹʤ롣 - # - # @param listener_type ꥹʥ - # @param listener ꥹʥ֥ȤؤΥݥ - # - # @else - # @brief Removing FsmStructureListener type listener - # - # This operation removes a specified listener. - # - # @param listener_type A listener type - # @param listener A pointer to a listener object - # - # @endif - # - def removeFsmStructureListener(self, listener_type, listener): - self._fsmActionListeners.structure_[listener_type].removeListener(listener) - return - - ## - # @if jp - # - # @brief RTC λ - # - # RTC νλ¹Ԥ롣 - # ݻƤ Port ϿȤȤˡ CORBA ֥ - # RTC λ롣 - # - # @param self - # - # @else - # - # @endif - def shutdown(self): - self._rtcout.RTC_TRACE("shutdown()") - try: - self.finalizePorts() - self.finalizeContexts() - self._poa.deactivate_object(self._poa.servant_to_id(self._SdoConfigImpl)) - self._poa.deactivate_object(self._poa.servant_to_id(self)) - self._sdoservice.exit() - except: - self._rtcout.RTC_ERROR(OpenRTM_aist.Logger.print_exception()) - - if self._manager: - self._rtcout.RTC_DEBUG("Cleanup on Manager") - self._manager.notifyFinalized(self) - - del self._actionListeners - del self._portconnListeners - - - return - - # inline void preOnInitialize(UniqueId ec_id) - def preOnInitialize(self, ec_id): - self._actionListeners.preaction_[OpenRTM_aist.PreComponentActionListenerType.PRE_ON_INITIALIZE].notify(ec_id) - return - - # inline void preOnFinalize(UniqueId ec_id) - def preOnFinalize(self, ec_id): - self._actionListeners.preaction_[OpenRTM_aist.PreComponentActionListenerType.PRE_ON_FINALIZE].notify(ec_id) - return - - # inline void preOnStartup(UniqueId ec_id) - def preOnStartup(self, ec_id): - self._actionListeners.preaction_[OpenRTM_aist.PreComponentActionListenerType.PRE_ON_STARTUP].notify(ec_id) - return - - # inline void preOnShutdown(UniqueId ec_id) - def preOnShutdown(self, ec_id): - self._actionListeners.preaction_[OpenRTM_aist.PreComponentActionListenerType.PRE_ON_SHUTDOWN].notify(ec_id) - return - - # inline void preOnActivated(UniqueId ec_id) - def preOnActivated(self, ec_id): - self._actionListeners.preaction_[OpenRTM_aist.PreComponentActionListenerType.PRE_ON_ACTIVATED].notify(ec_id) - return - - # inline void preOnDeactivated(UniqueId ec_id) - def preOnDeactivated(self, ec_id): - self._actionListeners.preaction_[OpenRTM_aist.PreComponentActionListenerType.PRE_ON_DEACTIVATED].notify(ec_id) - return - - # inline void preOnAborting(UniqueId ec_id) - def preOnAborting(self, ec_id): - self._actionListeners.preaction_[OpenRTM_aist.PreComponentActionListenerType.PRE_ON_ABORTING].notify(ec_id) - return - - # inline void preOnError(UniqueId ec_id) - def preOnError(self, ec_id): - self._actionListeners.preaction_[OpenRTM_aist.PreComponentActionListenerType.PRE_ON_ERROR].notify(ec_id) - return - - # inline void preOnReset(UniqueId ec_id) - def preOnReset(self, ec_id): - self._actionListeners.preaction_[OpenRTM_aist.PreComponentActionListenerType.PRE_ON_RESET].notify(ec_id) - return - - # inline void preOnExecute(UniqueId ec_id) - def preOnExecute(self, ec_id): - self._actionListeners.preaction_[OpenRTM_aist.PreComponentActionListenerType.PRE_ON_EXECUTE].notify(ec_id) - return - - # inline void preOnStateUpdate(UniqueId ec_id) - def preOnStateUpdate(self, ec_id): - self._actionListeners.preaction_[OpenRTM_aist.PreComponentActionListenerType.PRE_ON_STATE_UPDATE].notify(ec_id) - return - - - # inline void preOnRateChanged(UniqueId ec_id) - def preOnRateChanged(self, ec_id): - self._actionListeners.preaction_[OpenRTM_aist.PreComponentActionListenerType.PRE_ON_RATE_CHANGED].notify(ec_id) - return - - - # inline void postOnInitialize(UniqueId ec_id, ReturnCode_t ret) - def postOnInitialize(self, ec_id, ret): - self._actionListeners.postaction_[OpenRTM_aist.PostComponentActionListenerType.POST_ON_INITIALIZE].notify(ec_id, ret) - return - - - # inline void postOnFinalize(UniqueId ec_id, ReturnCode_t ret) - def postOnFinalize(self, ec_id, ret): - self._actionListeners.postaction_[OpenRTM_aist.PostComponentActionListenerType.POST_ON_FINALIZE].notify(ec_id, ret) - return - - - # inline void postOnStartup(UniqueId ec_id, ReturnCode_t ret) - def postOnStartup(self, ec_id, ret): - self._actionListeners.postaction_[OpenRTM_aist.PostComponentActionListenerType.POST_ON_STARTUP].notify(ec_id, ret) - return - - - # inline void postOnShutdown(UniqueId ec_id, ReturnCode_t ret) - def postOnShutdown(self, ec_id, ret): - self._actionListeners.postaction_[OpenRTM_aist.PostComponentActionListenerType.POST_ON_SHUTDOWN].notify(ec_id, ret) - return - - - # inline void postOnActivated(UniqueId ec_id, ReturnCode_t ret) - def postOnActivated(self, ec_id, ret): - self._actionListeners.postaction_[OpenRTM_aist.PostComponentActionListenerType.POST_ON_ACTIVATED].notify(ec_id, ret) - return - - - # inline void postOnDeactivated(UniqueId ec_id, ReturnCode_t ret) - def postOnDeactivated(self, ec_id, ret): - self._actionListeners.postaction_[OpenRTM_aist.PostComponentActionListenerType.POST_ON_DEACTIVATED].notify(ec_id, ret) - return - - - # inline void postOnAborting(UniqueId ec_id, ReturnCode_t ret) - def postOnAborting(self, ec_id, ret): - self._actionListeners.postaction_[OpenRTM_aist.PostComponentActionListenerType.POST_ON_ABORTING].notify(ec_id, ret) - return - - - # inline void postOnError(UniqueId ec_id, ReturnCode_t ret) - def postOnError(self, ec_id, ret): - self._actionListeners.postaction_[OpenRTM_aist.PostComponentActionListenerType.POST_ON_ERROR].notify(ec_id, ret) - return - - - # inline void postOnReset(UniqueId ec_id, ReturnCode_t ret) - def postOnReset(self, ec_id, ret): - self._actionListeners.postaction_[OpenRTM_aist.PostComponentActionListenerType.POST_ON_RESET].notify(ec_id, ret) - return - - - # inline void postOnExecute(UniqueId ec_id, ReturnCode_t ret) - def postOnExecute(self, ec_id, ret): - self._actionListeners.postaction_[OpenRTM_aist.PostComponentActionListenerType.POST_ON_EXECUTE].notify(ec_id, ret) - return - - - # inline void postOnStateUpdate(UniqueId ec_id, ReturnCode_t ret) - def postOnStateUpdate(self, ec_id, ret): - self._actionListeners.postaction_[OpenRTM_aist.PostComponentActionListenerType.POST_ON_STATE_UPDATE].notify(ec_id, ret) - return - - - # inline void postOnRateChanged(UniqueId ec_id, ReturnCode_t ret) - def postOnRateChanged(self, ec_id, ret): - self._actionListeners.postaction_[OpenRTM_aist.PostComponentActionListenerType.POST_ON_RATE_CHANGED].notify(ec_id, ret) - return - - - # inline void onAddPort(const PortProfile& pprof) - def onAddPort(self, pprof): - self._actionListeners.portaction_[OpenRTM_aist.PortActionListenerType.ADD_PORT].notify(pprof) - return - - - # inline void onRemovePort(const PortProfile& pprof) - def onRemovePort(self, pprof): - self._actionListeners.portaction_[OpenRTM_aist.PortActionListenerType.REMOVE_PORT].notify(pprof) - return - - - # inline void onAttachExecutionContext(UniqueId ec_id) - def onAttachExecutionContext(self, ec_id): - self._actionListeners.ecaction_[OpenRTM_aist.ExecutionContextActionListenerType.EC_ATTACHED].notify(ec_id) - return - - - # inline void onDetachExecutionContext(UniqueId ec_id) - def onDetachExecutionContext(self, ec_id): - self._actionListeners.ecaction_[OpenRTM_aist.ExecutionContextActionListenerType.EC_DETACHED].notify(ec_id) - return - - - - def preOnFsmInit(self, state): - self._fsmActionListeners.preaction_[OpenRTM_aist.PreFsmActionListenerType.PRE_ON_INIT].notify(state) - return - def preOnFsmEntry(self, state): - self._fsmActionListeners.preaction_[OpenRTM_aist.PreFsmActionListenerType.PRE_ON_ENTRY].notify(state) - return - def preOnFsmDo(self, state): - self._fsmActionListeners.preaction_[OpenRTM_aist.PreFsmActionListenerType.PRE_ON_DO].notify(state) - return - def preOnFsmExit(self, state): - self._fsmActionListeners.preaction_[OpenRTM_aist.PreFsmActionListenerType.PRE_ON_EXIT].notify(state) - return - def preOnFsmStateChange(self, state): - self._fsmActionListeners.preaction_[OpenRTM_aist.PreFsmActionListenerType.PRE_ON_STATE_CHANGE].notify(state) - return - def postOnFsmInit(self, state, ret): - self._fsmActionListeners.postaction_[OpenRTM_aist.PostFsmActionListenerType.POST_ON_INIT].notify(state, ret) - return - def postOnFsmEntry(self, state, ret): - self._fsmActionListeners.postaction_[OpenRTM_aist.PostFsmActionListenerType.POST_ON_ENTRY].notify(state, ret) - return - def postOnFsmDo(self, state, ret): - self._fsmActionListeners.postaction_[OpenRTM_aist.PostFsmActionListenerType.POST_ON_DO].notify(state, ret) - return - def postOnFsmExit(self, state, ret): - self._fsmActionListeners.postaction_[OpenRTM_aist.PostFsmActionListenerType.POST_ON_EXIT].notify(state, ret) - return - def postOnFsmStateChange(self, state, ret): - self._fsmActionListeners.postaction_[OpenRTM_aist.PostFsmActionListenerType.POST_ON_STATE_CHANGE].notify(state, ret) - return - - - # ReturnCode_t getInheritedECOptions(coil::Properties& default_opts); - def getInheritedECOptions(self, default_opts): - inherited_opts_ = ["sync_transition", - "sync_activation", - "sync_deactivation", - "sync_reset", - "transition_timeout", - "activation_timeout", - "deactivation_timeout", - "reset_timeout" - "cpu_affinity"] - - p_ = self._properties.findNode("exec_cxt") - if not p_: - self._rtcout.RTC_WARN("No exec_cxt option found.") - return RTC.RTC_ERROR + # inline void onDetachExecutionContext(UniqueId ec_id) - self._rtcout.RTC_DEBUG("Copying inherited EC options.") - for opt_ in inherited_opts_: - if p_.findNode(opt_): - self._rtcout.RTC_PARANOID("Option %s exists.", opt_) - default_opts.setProperty(opt_, p_.getProperty(opt_)) - - return RTC.RTC_OK - - - ## - # @brief getting individual EC options from RTC's configuration file - # - # ReturnCode_t - # getPrivateContextOptions(std::vector& ec_args); - def getPrivateContextOptions(self, ec_args): - self._rtcout.RTC_TRACE("getPrivateContextOptions()") - # Component specific multiple EC option available - if not self._properties.findNode("execution_contexts"): - self._rtcout.RTC_DEBUG("No component specific EC specified.") - return RTC.RTC_ERROR + def onDetachExecutionContext(self, ec_id): + self._actionListeners.notifyECAction(OpenRTM_aist.ExecutionContextActionListenerType.EC_DETACHED, ec_id) + return - args_ = self._properties.getProperty("execution_contexts") - ecs_tmp_ = [s.strip() for s in args_.split(",")] - if not ecs_tmp_[0]: - return RTC.RTC_ERROR - self._rtcout.RTC_DEBUG("Component specific e EC option available,") - self._rtcout.RTC_DEBUG("%s", args_) - - default_opts_ = OpenRTM_aist.Properties() - self.getInheritedECOptions(default_opts_) - for ec_tmp in ecs_tmp_: - if OpenRTM_aist.normalize([ec_tmp]) == "none": - self._rtcout.RTC_INFO("EC none. EC will not be bound to the RTC.") - ec_args = [] - return RTC.RTC_OK - - type_and_name_ = [s.strip() for s in ec_tmp.split("(")] - if len(type_and_name_) > 2: - self._rtcout.RTC_DEBUG("Invalid EC type specified: %s", ec_tmp) - continue - - p_ = copy.deepcopy(default_opts_) - - - # create EC's properties - p_.setProperty("type",type_and_name_[0]) - self._rtcout.RTC_DEBUG("p_type: %s", p_.getProperty("type")) - p_type_ = self._properties.findNode("ec." + p_.getProperty("type")) - - if p_type_: - self._rtcout.RTC_DEBUG("p_type props:") - self._rtcout.RTC_DEBUG(p_type_) - p_.mergeProperties(p_type_) - - else: - self._rtcout.RTC_DEBUG("p_type none") - - # EC name specified - #self._rtcout.RTC_DEBUG("size: %d, name: %s", - # (len(type_and_name_), type_and_name_[1])) - - if len(type_and_name_) == 2 and type_and_name_[1][-1] == ')': - type_and_name_ = type_and_name_[1][:-1] - p_.setProperty("name", type_and_name_) - p_name_ = self._properties.findNode("ec." + p_.getProperty("name")) - - if p_name_: - self._rtcout.RTC_DEBUG("p_name props:") - self._rtcout.RTC_DEBUG(p_name_) - p_.mergeProperties(p_name_) + def preOnFsmInit(self, state): + self._fsmActionListeners.notifyPreAction(OpenRTM_aist.PreFsmActionListenerType.PRE_ON_INIT, state) + return - else: - self._rtcout.RTC_DEBUG("p_name none") + def preOnFsmEntry(self, state): + self._fsmActionListeners.notifyPreAction(OpenRTM_aist.PreFsmActionListenerType.PRE_ON_ENTRY, state) + return - ec_args.append(p_) - self._rtcout.RTC_DEBUG("New EC properties stored:") - self._rtcout.RTC_DEBUG(p_) + def preOnFsmDo(self, state): + self._fsmActionListeners.notifyPreAction(OpenRTM_aist.PreFsmActionListenerType.PRE_ON_DO, state) + return - return RTC.RTC_OK + def preOnFsmExit(self, state): + self._fsmActionListeners.notifyPreAction(OpenRTM_aist.PreFsmActionListenerType.PRE_ON_EXIT, state) + return + def preOnFsmStateChange(self, state): + self._fsmActionListeners.notifyPreAction(OpenRTM_aist.PreFsmActionListenerType.PRE_ON_STATE_CHANGE, state) + return - ## - # @brief getting global EC options from rtc.conf - # - # ReturnCode_t - # getGlobalContextOptions(coil::Properties& global_ec_props); - def getGlobalContextOptions(self, global_ec_props): - # exec_cxt option is obsolete - self._rtcout.RTC_TRACE("getGlobalContextOptions()") + def postOnFsmInit(self, state, ret): + self._fsmActionListeners.notifyPostAction( + OpenRTM_aist.PostFsmActionListenerType.POST_ON_INIT, state, ret) + return - prop_ = self._properties.findNode("exec_cxt.periodic") - if not prop_: - self._rtcout.RTC_WARN("No global EC options found.") - return RTC.RTC_ERROR + def postOnFsmEntry(self, state, ret): + self._fsmActionListeners.notifyPostAction( + OpenRTM_aist.PostFsmActionListenerType.POST_ON_ENTRY, state, ret) + return - self._rtcout.RTC_DEBUG("Global EC options are specified.") - self._rtcout.RTC_DEBUG(prop_) - self.getInheritedECOptions(global_ec_props) - global_ec_props.mergeProperties(prop_) - return RTC.RTC_OK - - - ## - # @brief getting EC options - # - # ReturnCode_t - # getContextOptions(std::vector& ec_args); - def getContextOptions(self, ec_args): - self._rtcout.RTC_DEBUG("getContextOptions()") - global_props_ = OpenRTM_aist.Properties() - ret_global_ = self.getGlobalContextOptions(global_props_) - ret_private_ = self.getPrivateContextOptions(ec_args) - - # private(X), global(X) -> error - # private(O), global(O) -> private - # private(X), global(O) -> global - # private(O), global(X) -> private - if ret_global_ != RTC.RTC_OK and ret_private_ != RTC.RTC_OK: - return RTC.RTC_ERROR + def postOnFsmDo(self, state, ret): + self._fsmActionListeners.notifyPostAction(OpenRTM_aist.PostFsmActionListenerType.POST_ON_DO, state, ret) + return - if ret_global_ == RTC.RTC_OK and ret_private_ != RTC.RTC_OK: - ec_args.append(global_props_) + def postOnFsmExit(self, state, ret): + self._fsmActionListeners.notifyPostAction( + OpenRTM_aist.PostFsmActionListenerType.POST_ON_EXIT, state, ret) + return - return RTC.RTC_OK + def postOnFsmStateChange(self, state, ret): + self._fsmActionListeners.notifyPostAction( + OpenRTM_aist.PostFsmActionListenerType.POST_ON_STATE_CHANGE, state, ret) + return + # ReturnCode_t getInheritedECOptions(coil::Properties& default_opts); + + def getInheritedECOptions(self, default_opts): + inherited_opts_ = ["sync_transition", + "sync_activation", + "sync_deactivation", + "sync_reset", + "transition_timeout", + "activation_timeout", + "deactivation_timeout", + "reset_timeout" + "cpu_affinity"] + + p_ = self._properties.findNode("exec_cxt") + if not p_: + self._rtcout.RTC_WARN("No exec_cxt option found.") + return RTC.RTC_ERROR + + self._rtcout.RTC_DEBUG("Copying inherited EC options.") + for opt_ in inherited_opts_: + if p_.findNode(opt_): + self._rtcout.RTC_PARANOID("Option %s exists.", opt_) + default_opts.setProperty(opt_, p_.getProperty(opt_)) - ## - # @brief fiding existing EC from the factory - # - # ReturnCode_t findExistingEC(coil::Properties& ec_arg, - # RTC::ExecutionContextBase*& ec); - def findExistingEC(self, ec_arg, ec): - eclist_ = OpenRTM_aist.ExecutionContextFactory.instance().createdObjects() - for ec_ in eclist_: - if ec_.getProperties().getProperty("type") == ec_arg.getProperty("type") and \ - ec_.getProperties().getProperty("name") == ec_arg.getProperty("name"): - ec[0] = ec_ return RTC.RTC_OK - return RTC.RTC_ERROR - - - ## - # @brief creating, initializing and binding context - # - # ReturnCode_t createContexts(std::vector& ec_args); - def createContexts(self, ec_args): - ret_ = RTC.RTC_OK - avail_ec_ = OpenRTM_aist.ExecutionContextFactory.instance().getIdentifiers() - - for ec_arg_ in ec_args: - ec_type_ = ec_arg_.getProperty("type") - ec_name_ = ec_arg_.getProperty("name") - ec_ = [None] - if ec_name_ and self.findExistingEC(ec_arg_, ec_) == RTC.RTC_OK: - # if EC's name exists, find existing EC in the factory. - self._rtcout.RTC_DEBUG("EC: type=%s, name=%s already exists.", - (ec_type_, ec_name_)) - else: - # If EC's name is empty or no existing EC, create new EC. - if not ec_type_ in avail_ec_: - self._rtcout.RTC_WARN("EC %s is not available.", ec_type_) - self._rtcout.RTC_DEBUG("Available ECs: %s", - OpenRTM_aist.flatten(avail_ec_)) - continue - ec_[0] = OpenRTM_aist.ExecutionContextFactory.instance().createObject(ec_type_) - - if not ec_[0]: - # EC factory available but creation failed. Resource full? - self._rtcout.RTC_ERROR("EC (%s) creation failed.", ec_type_) - self._rtcout.RTC_DEBUG("Available EC list: %s", - OpenRTM_aist.flatten(avail_ec_)) - ret_ = RTC.RTC_ERROR - continue - - self._rtcout.RTC_DEBUG("EC (%s) created.", ec_type_) - - ec_[0].init(ec_arg_) - self._eclist.append(ec_[0]) - ec_[0].bindComponent(self) - - if len(self._eclist) == 0: - default_prop = OpenRTM_aist.Properties() - default_prop.setDefaults(OpenRTM_aist.default_config) - - ec_ = [None] - ec_type_ = default_prop.getProperty("exec_cxt.periodic.type") - if not ec_type_ in avail_ec_: - self._rtcout.RTC_WARN("EC %s is not available.", ec_type_) - self._rtcout.RTC_DEBUG("Available ECs: %s", - OpenRTM_aist.flatten(avail_ec_)) - return RTC.RTC_ERROR - - - - default_opts = OpenRTM_aist.Properties() - prop_ = default_prop.findNode("exec_cxt.periodic") - #if not prop_: - # self._rtcout.RTC_WARN("No default EC options found.") - # return RTC.RTC_ERROR - - default_opts.mergeProperties(prop_) - - inherited_opts_ = ["sync_transition", - "sync_activation", - "sync_deactivation", - "sync_reset", - "transition_timeout", - "activation_timeout", - "deactivation_timeout", - "reset_timeout", - "cpu_affinity"] - - p_ = self._properties.findNode("exec_cxt") - - if not p_: - self._rtcout.RTC_WARN("No exec_cxt option found.") - return RTC.RTC_ERROR - - self._rtcout.RTC_DEBUG("Copying inherited EC options.") - for opt_ in inherited_opts_: - if p_.findNode(opt_): - self._rtcout.RTC_PARANOID("Option %s exists.", opt_) - default_opts.setProperty(opt_, p_.getProperty(opt_)) - - - ec_[0] = OpenRTM_aist.ExecutionContextFactory.instance().createObject(ec_type_) - #if not ec_[0]: - # self._rtcout.RTC_ERROR("EC (%s) creation failed.", ec_type_) - # self._rtcout.RTC_DEBUG("Available EC list: %s", - # OpenRTM_aist.flatten(avail_ec_)) - # return RTC.RTC_ERROR - - ec_[0].init(default_opts) - self._eclist.append(ec_[0]) - ec_[0].bindComponent(self) - - - - - return ret_ - - - - - - ## - # @if jp - # @class svc_name - # @brief SDOService ΥץեꥹȤidǥ뤿 - # ե󥯥饹 - # @else - # - # @endif - class svc_name: - def __init__(self, _id): - self._id= _id - - def __call__(self, prof): - return self._id == prof.id - - - #------------------------------------------------------------ - # Functor - #------------------------------------------------------------ - - ## - # @if jp - # @class nv_name - # @brief NVList ѥե󥯥 - # @else - # - # @endif - class nv_name: - def __init__(self, _name): - self._name = _name - - def __call__(self, nv): - return self._name == nv.name - - - ## - # @if jp - # @class ec_find - # @brief ExecutionContext ѥե󥯥 - # @else - # - # @endif - class ec_find: - def __init__(self, _ec): - self._ec = _ec - - def __call__(self, ecs): - try: - if not CORBA.is_nil(ecs): - ec = ecs._narrow(RTC.ExecutionContext) - return self._ec._is_equivalent(ec) - except: - print(OpenRTM_aist.Logger.print_exception()) - return False - - return False - - - ## - # @if jp - # @class ec_copy - # @brief ExecutionContext Copyѥե󥯥 - # @else - # - # @endif - class ec_copy: - def __init__(self, eclist): - self._eclist = eclist - - def __call__(self, ecs): - if not CORBA.is_nil(ecs): - self._eclist.append(ecs) - - - ## - # @if jp - # @class deactivate_comps - # @brief RTC ѥե󥯥 - # @else - # - # @endif - class deactivate_comps: - def __init__(self, comp): - self._comp = comp - - def __call__(self, ec): - try: - if not CORBA.is_nil(ec) and not ec._non_existent(): - ec.deactivate_component(self._comp) - ec.stop() - except: - print(OpenRTM_aist.Logger.print_exception()) + ## + # @brief getting individual EC options from RTC's configuration file + # + # ReturnCode_t + # getPrivateContextOptions(std::vector& ec_args); + + def getPrivateContextOptions(self, ec_args): + self._rtcout.RTC_TRACE("getPrivateContextOptions()") + # Component specific multiple EC option available + if not self._properties.findNode("execution_contexts"): + self._rtcout.RTC_DEBUG("No component specific EC specified.") + return RTC.RTC_ERROR, ec_args + + args_ = self._properties.getProperty("execution_contexts") + ecs_tmp_ = [s.strip() for s in args_.split(",")] + if not ecs_tmp_[0]: + return RTC.RTC_ERROR, ec_args + self._rtcout.RTC_DEBUG("Component specific e EC option available,") + self._rtcout.RTC_DEBUG("%s", args_) + + default_opts_ = OpenRTM_aist.Properties() + self.getInheritedECOptions(default_opts_) + for ec_tmp in ecs_tmp_: + if OpenRTM_aist.normalize(ec_tmp) == "none": + self._rtcout.RTC_INFO( + "EC none. EC will not be bound to the RTC.") + ec_args = [] + return RTC.RTC_OK, ec_args + + type_and_name_ = [s.strip() for s in ec_tmp.split("(")] + if len(type_and_name_) > 2: + self._rtcout.RTC_DEBUG("Invalid EC type specified: %s", ec_tmp) + continue + + p_ = copy.deepcopy(default_opts_) + + # create EC's properties + p_.setProperty("type", type_and_name_[0]) + self._rtcout.RTC_DEBUG("p_type: %s", p_.getProperty("type")) + p_type_ = self._properties.findNode("ec." + p_.getProperty("type")) + + if p_type_: + self._rtcout.RTC_DEBUG("p_type props:") + self._rtcout.RTC_DEBUG(p_type_) + p_.mergeProperties(p_type_) + + else: + self._rtcout.RTC_DEBUG("p_type none") + + # EC name specified + # self._rtcout.RTC_DEBUG("size: %d, name: %s", + # (len(type_and_name_), type_and_name_[1])) + + if len(type_and_name_) == 2 and type_and_name_[1][-1] == ')': + type_and_name_ = type_and_name_[1][:-1] + p_.setProperty("name", type_and_name_) + p_name_ = self._properties.findNode( + "ec." + p_.getProperty("name")) + + if p_name_: + self._rtcout.RTC_DEBUG("p_name props:") + self._rtcout.RTC_DEBUG(p_name_) + p_.mergeProperties(p_name_) + + else: + self._rtcout.RTC_DEBUG("p_name none") + + ec_args.append(p_) + self._rtcout.RTC_DEBUG("New EC properties stored:") + self._rtcout.RTC_DEBUG(p_) + + return RTC.RTC_OK, ec_args + + ## + # @brief getting global EC options from rtc.conf + # + # ReturnCode_t + # getGlobalContextOptions(coil::Properties& global_ec_props); + + def getGlobalContextOptions(self, global_ec_props): + # exec_cxt option is obsolete + self._rtcout.RTC_TRACE("getGlobalContextOptions()") + + prop_ = self._properties.findNode("exec_cxt.periodic") + if not prop_: + self._rtcout.RTC_WARN("No global EC options found.") + return RTC.RTC_ERROR, global_ec_props + + self._rtcout.RTC_DEBUG("Global EC options are specified.") + self._rtcout.RTC_DEBUG(prop_) + self.getInheritedECOptions(global_ec_props) + global_ec_props.mergeProperties(prop_) + return RTC.RTC_OK, global_ec_props + + ## + # @brief getting EC options + # + # ReturnCode_t + # getContextOptions(std::vector& ec_args); + + def getContextOptions(self, ec_args): + self._rtcout.RTC_DEBUG("getContextOptions()") + global_props_ = OpenRTM_aist.Properties() + ret_global_, global_props_ = self.getGlobalContextOptions( + global_props_) + ret_private_, ec_args = self.getPrivateContextOptions(ec_args) + + # private(X), global(X) -> error + # private(O), global(O) -> private + # private(X), global(O) -> global + # private(O), global(X) -> private + if ret_global_ != RTC.RTC_OK and ret_private_ != RTC.RTC_OK: + return RTC.RTC_ERROR, ec_args + + if ret_global_ == RTC.RTC_OK and ret_private_ != RTC.RTC_OK: + ec_args.append(global_props_) + + return RTC.RTC_OK, ec_args + + ## + # @brief fiding existing EC from the factory + # + # ReturnCode_t findExistingEC(coil::Properties& ec_arg, + # RTC::ExecutionContextBase*& ec); + + def findExistingEC(self, ec_arg): + if self._manager: + eclist_ = self._manager.createdExecutionContexts() + for e_ in eclist_: + if ec.getProperties().getProperty("type") == ec_arg.getProperty("type") and \ + ec.getProperties().getProperty("name") == ec_arg.getProperty("name"): + return RTC.RTC_OK, ec + + return RTC.RTC_ERROR, None + + ## + # @brief creating, initializing and binding context + # + # ReturnCode_t createContexts(std::vector& ec_args); + + def createContexts(self, ec_args): + ret_ = RTC.RTC_OK + avail_ec_ = OpenRTM_aist.ExecutionContextFactory.instance().getIdentifiers() + + for ec_arg_ in ec_args: + ec_type_ = ec_arg_.getProperty("type") + ec_name_ = ec_arg_.getProperty("name") + ret, ec = self.findExistingEC(ec_arg_) + if ec_name_ and ret == RTC.RTC_OK: + # if EC's name exists, find existing EC in the factory. + self._rtcout.RTC_DEBUG("EC: type=%s, name=%s already exists.", + (ec_type_, ec_name_)) + else: + # If EC's name is empty or no existing EC, create new EC. + if not ec_type_ in avail_ec_: + self._rtcout.RTC_WARN("EC %s is not available.", ec_type_) + self._rtcout.RTC_DEBUG("Available ECs: %s", + OpenRTM_aist.flatten(avail_ec_)) + continue + ec = OpenRTM_aist.ExecutionContextFactory.instance( + ).createObject(ec_type_) + + if not ec: + # EC factory available but creation failed. Resource full? + self._rtcout.RTC_ERROR("EC (%s) creation failed.", ec_type_) + self._rtcout.RTC_DEBUG("Available EC list: %s", + OpenRTM_aist.flatten(avail_ec_)) + ret_ = RTC.RTC_ERROR + continue + + if self._manager: + self._manager.addExecutionContext(ec) + + self._rtcout.RTC_DEBUG("EC (%s) created.", ec_type_) + + ec.init(ec_arg_) + self._eclist.append(ec) + ec.bindComponent(self) + + if not self._eclist: + default_prop = OpenRTM_aist.Properties() + default_prop.setDefaults(OpenRTM_aist.default_config) + + ec_ = [None] + ec_type_ = default_prop.getProperty("exec_cxt.periodic.type") + if not ec_type_ in avail_ec_: + self._rtcout.RTC_WARN("EC %s is not available.", ec_type_) + self._rtcout.RTC_DEBUG("Available ECs: %s", + OpenRTM_aist.flatten(avail_ec_)) + return RTC.RTC_ERROR + + default_opts = OpenRTM_aist.Properties() + prop_ = default_prop.findNode("exec_cxt.periodic") + # if not prop_: + # self._rtcout.RTC_WARN("No default EC options found.") + # return RTC.RTC_ERROR + + default_opts.mergeProperties(prop_) + + inherited_opts_ = ["sync_transition", + "sync_activation", + "sync_deactivation", + "sync_reset", + "transition_timeout", + "activation_timeout", + "deactivation_timeout", + "reset_timeout", + "cpu_affinity"] + + p_ = self._properties.findNode("exec_cxt") + + if not p_: + self._rtcout.RTC_WARN("No exec_cxt option found.") + return RTC.RTC_ERROR + + self._rtcout.RTC_DEBUG("Copying inherited EC options.") + for opt_ in inherited_opts_: + if p_.findNode(opt_): + self._rtcout.RTC_PARANOID("Option %s exists.", opt_) + default_opts.setProperty(opt_, p_.getProperty(opt_)) + + ec = OpenRTM_aist.ExecutionContextFactory.instance( + ).createObject(ec_type_) + if not ec: + self._rtcout.RTC_ERROR("EC (%s) creation failed.", ec_type_) + self._rtcout.RTC_DEBUG("Available EC list: %s", + OpenRTM_aist.flatten(avail_ec_)) + return RTC.RTC_ERROR + + if self._manager: + self._manager.addExecutionContext(ec) + + ec.init(default_opts) + self._eclist.append(ec) + ec.bindComponent(self) + + return ret_ + + ## + # @if jp + # @class svc_name + # @brief SDOService のプロファイルリストからidでサーチするための + # ファンクタクラス + # @else + # + # @endif + + class svc_name: + def __init__(self, _id): + self._id = _id + + def __call__(self, prof): + return self._id == prof.id + + # ------------------------------------------------------------ + # Functor + # ------------------------------------------------------------ + + ## + # @if jp + # @class nv_name + # @brief NVList 検索用ファンクタ + # @else + # + # @endif + + class nv_name: + def __init__(self, _name): + self._name = _name + + def __call__(self, nv): + return self._name == nv.name + + ## + # @if jp + # @class ec_find + # @brief ExecutionContext 検索用ファンクタ + # @else + # + # @endif + + class ec_find: + def __init__(self, _ec): + self._ec = _ec + + def __call__(self, ecs): + try: + if not CORBA.is_nil(ecs): + ec = ecs._narrow(RTC.ExecutionContext) + return self._ec._is_equivalent(ec) + except BaseException: + print(OpenRTM_aist.Logger.print_exception()) + return False + + return False + + ## + # @if jp + # @class ec_copy + # @brief ExecutionContext Copy用ファンクタ + # @else + # + # @endif + + class ec_copy: + def __init__(self, eclist): + self._eclist = eclist + + def __call__(self, ecs): + if not CORBA.is_nil(ecs): + self._eclist.append(ecs) + + ## + # @if jp + # @class deactivate_comps + # @brief RTC 非活性化用ファンクタ + # @else + # + # @endif + + class deactivate_comps: + def __init__(self, comp): + self._comp = comp + + def __call__(self, ec): + try: + if not CORBA.is_nil(ec) and not ec._non_existent(): + ec.deactivate_component(self._comp) + ec.stop() + except BaseException: + print(OpenRTM_aist.Logger.print_exception()) # RtcBase = RTObject_impl @@ -5371,7 +5350,7 @@ def __call__(self, ec): ec.bindComponent(self) # at least one EC must be attached - if len(self._ecMine) == 0: + if not self._ecMine: return RTC.PRECONDITION_NOT_MET ret = self.on_initialize() @@ -5380,11 +5359,10 @@ def __call__(self, ec): return ret # -- entering alive state -- - for i in range(len(self._ecMine)): + for i, ec in enumerate(self._ecMine): self._rtcout.RTC_DEBUG("EC[%d] starting.", i) - self._ecMine[i].start() + ec.start() # ret must be RTC_OK return ret """ - diff --git a/OpenRTM_aist/RTObjectStateMachine.py b/OpenRTM_aist/RTObjectStateMachine.py index 66e75f3f..d5a57e11 100644 --- a/OpenRTM_aist/RTObjectStateMachine.py +++ b/OpenRTM_aist/RTObjectStateMachine.py @@ -1,5 +1,5 @@ #!/usr/bin/env python -# -*- coding: euc-jp -*- +# -*- coding: utf-8 -*- ## # @file RTObjectStateMachine.py @@ -24,308 +24,352 @@ NUM_OF_LIFECYCLESTATE = 4 + class RTObjectStateMachine: - """ - """ - - # RTObjectStateMachine(RTC::ExecutionContextHandle_t id, - # RTC::LightweightRTObject_ptr comp); - def __init__(self, id, comp): - global NUM_OF_LIFECYCLESTATE - self._id = id - self._rtobj = comp - self._sm = OpenRTM_aist.StateMachine(NUM_OF_LIFECYCLESTATE) - self._ca = False - self._dfc = False - self._fsm = False - self._mode = False - self._caVar = None - self._dfcVar = None - self._fsmVar = None - self._modeVar = None - self._rtObjPtr = None - - # Setting Action callback objects - self.setComponentAction(comp) - self.setDataFlowComponentAction(comp) - self.setFsmParticipantAction(comp) - self.setMultiModeComponentAction(comp) - # Setting callback functions to StateMachine - self._sm.setListener(self) - self._sm.setEntryAction (RTC.ACTIVE_STATE, - self.onActivated) - self._sm.setDoAction (RTC.ACTIVE_STATE, + """ + """ + + # RTObjectStateMachine(RTC::ExecutionContextHandle_t id, + # RTC::LightweightRTObject_ptr comp); + def __init__(self, id, comp): + global NUM_OF_LIFECYCLESTATE + self._id = id + self._rtobj = comp + self._sm = OpenRTM_aist.StateMachine(NUM_OF_LIFECYCLESTATE) + self._ca = False + self._dfc = False + self._fsm = False + self._mode = False + self._caVar = None + self._dfcVar = None + self._fsmVar = None + self._modeVar = None + self._rtObjPtr = None + self._activation = False + self._deactivation = False + self._reset = False + + # Setting Action callback objects + self.setComponentAction(comp) + self.setDataFlowComponentAction(comp) + self.setFsmParticipantAction(comp) + self.setMultiModeComponentAction(comp) + # Setting callback functions to StateMachine + self._sm.setListener(self) + self._sm.setEntryAction(RTC.ACTIVE_STATE, + self.onActivated) + self._sm.setDoAction(RTC.ACTIVE_STATE, self.onExecute) - self._sm.setPostDoAction(RTC.ACTIVE_STATE, - self.onStateUpdate) - self._sm.setExitAction (RTC.ACTIVE_STATE, - self.onDeactivated) - #self._sm.setDoAction (RTC.ACTIVE_STATE, - # self.onAction) - self._sm.setEntryAction (RTC.ERROR_STATE, - self.onAborting) - self._sm.setDoAction (RTC.ERROR_STATE, + self._sm.setPostDoAction(RTC.ACTIVE_STATE, + self.onStateUpdate) + self._sm.setExitAction(RTC.ACTIVE_STATE, + self.onDeactivated) + # self._sm.setDoAction (RTC.ACTIVE_STATE, + # self.onAction) + self._sm.setEntryAction(RTC.ERROR_STATE, + self.onAborting) + self._sm.setDoAction(RTC.ERROR_STATE, self.onError) - self._sm.setExitAction (RTC.ERROR_STATE, - self.onReset) - # Setting inital state - st = OpenRTM_aist.StateHolder() - st.prev = RTC.INACTIVE_STATE - st.curr = RTC.INACTIVE_STATE - st.next = RTC.INACTIVE_STATE - self._sm.setStartState(st) - self._sm.goTo(RTC.INACTIVE_STATE) - return - - - def __del__(self): - if self._ca: - self._ca = False - self._caVar = None - - if self._dfc: - self._dfc = False - self._dfcVar = None - - if self._fsm: - self._fsm = False - self._fsmVar = None - - if self._mode: - self._mode = False - self._modeVar = None - - return - - - # functions for stored RTObject reference - # RTC::LightweightRTObject_ptr getRTObject(); - def getRTObject(self): - return self._rtobj - - # bool isEquivalent(RTC::LightweightRTObject_ptr comp); - def isEquivalent(self, comp): - return self._rtobj._is_equivalent(comp) - - # RTC::ExecutionContextHandle_t getExecutionContextHandle(); - def getExecutionContextHandle(self): - return self._id - - # RTC::ComponentAction operations - # void onStartup(void); - def onStartup(self): - if self._rtObjPtr: - self._rtObjPtr.on_startup(self._id) - return - if not self._ca: - return - self._caVar.on_startup(self._id) - return - - # void onShutdown(void); - def onShutdown(self): - if self._rtObjPtr: - self._rtObjPtr.on_shutdown(self._id) - return - - if not self._ca: - return - self._caVar.on_shutdown(self._id) - return - - # void onActivated(const ExecContextStates& st); - def onActivated(self, st): - if self._rtObjPtr: - if self._rtObjPtr.on_activated(self._id) != RTC.RTC_OK: - self._sm.goTo(RTC.ERROR_STATE) - return - - if not self._ca: - return - if self._caVar.on_activated(self._id) != RTC.RTC_OK: - self._sm.goTo(RTC.ERROR_STATE) - return - - # void onDeactivated(const ExecContextStates& st); - def onDeactivated(self, st): - if self._rtObjPtr: - self._rtObjPtr.on_deactivated(self._id) - return - - if not self._ca: - return - self._caVar.on_deactivated(self._id) - return - - # void onAborting(const ExecContextStates& st); - def onAborting(self, st): - if self._rtObjPtr: - self._rtObjPtr.on_aborting(self._id) - return - - if not self._ca: - return - self._caVar.on_aborting(self._id) - return - - # void onError(const ExecContextStates& st); - def onError(self, st): - if self._rtObjPtr: - self._rtObjPtr.on_error(self._id) - return - - if not self._ca: - return - self._caVar.on_error(self._id) - return - - # void onReset(const ExecContextStates& st); - def onReset(self, st): - if self._rtObjPtr: - if self._rtObjPtr.on_reset(self._id) != RTC.RTC_OK: - self._sm.goTo(RTC.ERROR_STATE) - return - - if not self._ca: - return - if self._caVar.on_reset(self._id) != RTC.RTC_OK: - self._sm.goTo(RTC.ERROR_STATE) - return - - # RTC::DataflowComponentAction - # void onExecute(const ExecContextStates& st); - def onExecute(self, st): - if self._rtObjPtr: - if self._rtObjPtr.on_execute(self._id) != RTC.RTC_OK: - self._sm.goTo(RTC.ERROR_STATE) - return - - if not self._dfc: - return - - if self._dfcVar.on_execute(self._id) != RTC.RTC_OK: - self._sm.goTo(RTC.ERROR_STATE) - return - - # void onStateUpdate(const ExecContextStates& st); - def onStateUpdate(self, st): - if self._rtObjPtr: - if self._rtObjPtr.on_state_update(self._id) != RTC.RTC_OK: - self._sm.goTo(RTC.ERROR_STATE) - return - - if not self._dfc: - return - - if self._dfcVar.on_state_update(self._id) != RTC.RTC_OK: - self._sm.goTo(RTC.ERROR_STATE) - return - - # RTC::ReturnCode_t onRateChanged(void); - def onRateChanged(self): - if self._rtObjPtr: - ret = self._rtObjPtr.on_rate_changed(self._id) - if ret != RTC.RTC_OK: - self._sm.goTo(RTC.ERROR_STATE) - return ret - - if not self._dfc: - return RTC.RTC_ERROR - - ret = self._dfcVar.on_rate_changed(self._id) - if ret != RTC.RTC_OK: - self._sm.goTo(RTC.ERROR_STATE) - return ret - - # FsmParticipantAction - # void onAction(const ExecContextStates& st); - def onAction(self, st): - if not self._fsm: - return - - if self._fsmVar.on_action(self._id) != RTC.RTC_OK: - self._sm.goTo(RTC.ERROR_STATE) - return - - # MultiModeComponentAction - # void onModeChanged(const ExecContextStates& st); - def onModeChanged(self, st): - if not self._mode: - return - - if self._modeVar.on_mode_changed(self._id) != RTC.RTC_OK: - self._sm.goTo(RTC.ERROR_STATE) - return - - # Getting state of the context - # ExecContextState getState(void); - def getState(self): - return self._sm.getState() - - # ExecContextStates getStates(void); - def getStates(self): - return self._sm.getStates() - - # bool isCurrentState(ExecContextState state); - def isCurrentState(self, state): - return self.getState() == state - - # bool isNextState(ExecContextState state); - def isNextState(self, state): - return self._sm.getStates().next == state - - # void goTo(ExecContextState state); - def goTo(self, state): - self._sm.goTo(state) - return - - # Workers - # void workerPreDo(void); - def workerPreDo(self): - return self._sm.worker_pre() - - # void workerDo(void); - def workerDo(self): - return self._sm.worker_do() - - # void workerPostDo(void); - def workerPostDo(self): - return self._sm.worker_post() - - # void setComponentAction(const RTC::LightweightRTObject_ptr comp); - def setComponentAction(self, comp): - self._caVar = comp._narrow(RTC.ComponentAction) - if CORBA.is_nil(self._caVar): - return - self._ca = True - - poa = OpenRTM_aist.Manager.instance().getPOA() - try: - self._rtObjPtr = poa.reference_to_servant(comp) - except CORBA.SystemException: - self._rtObjPtr = None - except: - self._rtObjPtr = None - - return - - # void setDataFlowComponentAction(const RTC::LightweightRTObject_ptr comp); - def setDataFlowComponentAction(self, comp): - self._dfcVar = comp._narrow(RTC.DataFlowComponentAction) - if not CORBA.is_nil(self._dfcVar): - self._dfc = True - return - - # void setFsmParticipantAction(const RTC::LightweightRTObject_ptr comp); - def setFsmParticipantAction(self, comp): - self._fsmVar = comp._narrow(RTC.FsmParticipantAction) - if not CORBA.is_nil(self._fsmVar): - self._fsm = True - return - - # void setMultiModeComponentAction(const RTC::LightweightRTObject_ptr comp); - def setMultiModeComponentAction(self, comp): - self._modeVar = comp._narrow(RTC.MultiModeComponentAction) - if not CORBA.is_nil(self._modeVar): - self._mode = True - return + self._sm.setExitAction(RTC.ERROR_STATE, + self.onReset) + # Setting inital state + st = OpenRTM_aist.StateHolder() + st.prev = RTC.INACTIVE_STATE + st.curr = RTC.INACTIVE_STATE + st.next = RTC.INACTIVE_STATE + self._sm.setStartState(st) + self._sm.goTo(RTC.INACTIVE_STATE) + return + + def __del__(self): + if self._ca: + self._ca = False + self._caVar = None + + if self._dfc: + self._dfc = False + self._dfcVar = None + + if self._fsm: + self._fsm = False + self._fsmVar = None + + if self._mode: + self._mode = False + self._modeVar = None + + return + + # functions for stored RTObject reference + # RTC::LightweightRTObject_ptr getRTObject(); + + def getRTObject(self): + return self._rtobj + + # bool isEquivalent(RTC::LightweightRTObject_ptr comp); + def isEquivalent(self, comp): + return self._rtobj._is_equivalent(comp) + + # RTC::ExecutionContextHandle_t getExecutionContextHandle(); + def getExecutionContextHandle(self): + return self._id + + # RTC::ComponentAction operations + # void onStartup(void); + def onStartup(self): + if self._rtObjPtr: + self._rtObjPtr.on_startup(self._id) + return + if not self._ca: + return + self._caVar.on_startup(self._id) + return + + # void onShutdown(void); + def onShutdown(self): + if self._rtObjPtr: + self._rtObjPtr.on_shutdown(self._id) + return + + if not self._ca: + return + self._caVar.on_shutdown(self._id) + return + + # void onActivated(const ExecContextStates& st); + def onActivated(self, st): + if self._rtObjPtr: + if self._rtObjPtr.on_activated(self._id) != RTC.RTC_OK: + self._sm.goTo(RTC.ERROR_STATE) + return + + if not self._ca: + return + if self._caVar.on_activated(self._id) != RTC.RTC_OK: + self._sm.goTo(RTC.ERROR_STATE) + return + + # void onDeactivated(const ExecContextStates& st); + def onDeactivated(self, st): + if self._rtObjPtr: + self._rtObjPtr.on_deactivated(self._id) + return + + if not self._ca: + return + self._caVar.on_deactivated(self._id) + return + + # void onAborting(const ExecContextStates& st); + def onAborting(self, st): + if self._rtObjPtr: + self._rtObjPtr.on_aborting(self._id) + return + + if not self._ca: + return + self._caVar.on_aborting(self._id) + return + + # void onError(const ExecContextStates& st); + def onError(self, st): + if self._rtObjPtr: + self._rtObjPtr.on_error(self._id) + return + + if not self._ca: + return + self._caVar.on_error(self._id) + return + + # void onReset(const ExecContextStates& st); + def onReset(self, st): + if self._rtObjPtr: + if self._rtObjPtr.on_reset(self._id) != RTC.RTC_OK: + self._sm.goTo(RTC.ERROR_STATE) + return + + if not self._ca: + return + if self._caVar.on_reset(self._id) != RTC.RTC_OK: + self._sm.goTo(RTC.ERROR_STATE) + return + + # RTC::DataflowComponentAction + # void onExecute(const ExecContextStates& st); + def onExecute(self, st): + if self.isNextState(RTC.ERROR_STATE): + return + if self._rtObjPtr: + if self._rtObjPtr.on_execute(self._id) != RTC.RTC_OK: + self._sm.goTo(RTC.ERROR_STATE) + return + + if not self._dfc: + return + + if self._dfcVar.on_execute(self._id) != RTC.RTC_OK: + self._sm.goTo(RTC.ERROR_STATE) + return + + # void onStateUpdate(const ExecContextStates& st); + def onStateUpdate(self, st): + if self.isNextState(RTC.ERROR_STATE): + return + if self._rtObjPtr: + if self._rtObjPtr.on_state_update(self._id) != RTC.RTC_OK: + self._sm.goTo(RTC.ERROR_STATE) + return + + if not self._dfc: + return + + if self._dfcVar.on_state_update(self._id) != RTC.RTC_OK: + self._sm.goTo(RTC.ERROR_STATE) + return + + # RTC::ReturnCode_t onRateChanged(void); + def onRateChanged(self): + if self._rtObjPtr: + ret = self._rtObjPtr.on_rate_changed(self._id) + if ret != RTC.RTC_OK: + self._sm.goTo(RTC.ERROR_STATE) + return ret + + if not self._dfc: + return RTC.RTC_ERROR + + ret = self._dfcVar.on_rate_changed(self._id) + if ret != RTC.RTC_OK: + self._sm.goTo(RTC.ERROR_STATE) + return ret + + # FsmParticipantAction + # void onAction(const ExecContextStates& st); + def onAction(self, st): + if not self._fsm: + return + + if self._fsmVar.on_action(self._id) != RTC.RTC_OK: + self._sm.goTo(RTC.ERROR_STATE) + return + + # MultiModeComponentAction + # void onModeChanged(const ExecContextStates& st); + def onModeChanged(self, st): + if not self._mode: + return + + if self._modeVar.on_mode_changed(self._id) != RTC.RTC_OK: + self._sm.goTo(RTC.ERROR_STATE) + return + + # Getting state of the context + # ExecContextState getState(void); + def getState(self): + return self._sm.getState() + + # ExecContextStates getStates(void); + def getStates(self): + return self._sm.getStates() + + # bool isCurrentState(ExecContextState state); + def isCurrentState(self, state): + return self.getState() == state + + # bool isNextState(ExecContextState state); + def isNextState(self, state): + return self._sm.getStates().next == state + + # void goTo(ExecContextState state); + def goTo(self, state): + self._sm.goTo(state) + return + + # Workers + # void workerPreDo(void); + def workerPreDo(self): + self.updateState() + return self._sm.worker_pre() + + # void workerDo(void); + def workerDo(self): + return self._sm.worker_do() + + # void workerPostDo(void); + def workerPostDo(self): + return self._sm.worker_post() + + def activate(self): + if self.isCurrentState(RTC.INACTIVE_STATE): + self._activation = True + return True + return False + + def deactivate(self): + if self.isCurrentState(RTC.ACTIVE_STATE): + self._deactivation = True + return True + return False + + def reset(self): + if self.isCurrentState(RTC.ERROR_STATE): + self._reset = True + return True + return False + + def updateState(self): + if self._activation: + if self.isCurrentState(RTC.INACTIVE_STATE) and not self.isNextState(RTC.ERROR_STATE): + self._sm.goTo(RTC.ACTIVE_STATE) + self._activation = False + + if self._deactivation: + if self.isCurrentState(RTC.ACTIVE_STATE) and not self.isNextState(RTC.ERROR_STATE): + self._sm.goTo(RTC.INACTIVE_STATE) + self._deactivation = False + + if self._reset: + if self.isCurrentState(RTC.ERROR_STATE): + self._sm.goTo(RTC.INACTIVE_STATE) + self._reset = False + + # void setComponentAction(const RTC::LightweightRTObject_ptr comp); + + def setComponentAction(self, comp): + self._caVar = comp._narrow(RTC.ComponentAction) + if CORBA.is_nil(self._caVar): + return + self._ca = True + + poa = OpenRTM_aist.Manager.instance().getPOA() + try: + self._rtObjPtr = poa.reference_to_servant(comp) + except CORBA.SystemException: + self._rtObjPtr = None + except BaseException: + self._rtObjPtr = None + + return + + # void setDataFlowComponentAction(const RTC::LightweightRTObject_ptr comp); + def setDataFlowComponentAction(self, comp): + self._dfcVar = comp._narrow(RTC.DataFlowComponentAction) + if not CORBA.is_nil(self._dfcVar): + self._dfc = True + return + + # void setFsmParticipantAction(const RTC::LightweightRTObject_ptr comp); + def setFsmParticipantAction(self, comp): + self._fsmVar = comp._narrow(RTC.FsmParticipantAction) + if not CORBA.is_nil(self._fsmVar): + self._fsm = True + return + + # void setMultiModeComponentAction(const RTC::LightweightRTObject_ptr + # comp); + def setMultiModeComponentAction(self, comp): + self._modeVar = comp._narrow(RTC.MultiModeComponentAction) + if not CORBA.is_nil(self._modeVar): + self._mode = True + return diff --git a/OpenRTM_aist/RingBuffer.py b/OpenRTM_aist/RingBuffer.py index 74d45f55..396a474a 100644 --- a/OpenRTM_aist/RingBuffer.py +++ b/OpenRTM_aist/RingBuffer.py @@ -1,5 +1,5 @@ #!/usr/bin/env python -# -*- coding: euc-jp -*- +# -*- coding: utf-8 -*- ## # @file RingBuffer.py @@ -23,16 +23,16 @@ ## # @if jp # @class RingBuffer -# @brief 󥰥Хåե饹 -# -# ꤷĹΥ󥰾ХåեĥХåե饹 -# ХåեΤ˥ǡǼ줿硢ʹߤΥǡϸŤǡ -# 缡񤭤롣 -# äơХåեˤľΥХåեĹʬΥǡΤݻ롣 +# @brief リングバッファ実装クラス # -# )ߤμǤϡֺǸ˳ǼǡΤߥХåեɤ߽Фǽ +# 指定した長さのリング状バッファを持つバッファ実装クラス。 +# バッファ全体にデータが格納された場合、以降のデータは古いデータから +# 順次上書きされる。 +# 従って、バッファ内には直近のバッファ長分のデータのみ保持される。 # -# @param DataType Хåե˳Ǽǡ +# 注)現在の実装では、一番最後に格納したデータのみバッファから読み出し可能 +# +# @param DataType バッファに格納するデータ型 # # @since 0.4.0 # @@ -40,760 +40,749 @@ # # @endif class RingBuffer(OpenRTM_aist.BufferBase): - """ - """ - - RINGBUFFER_DEFAULT_LENGTH = 8 - - ## - # @if jp - # - # @brief 󥹥ȥ饯 - # - # 󥹥ȥ饯 - # ꤵ줿ХåեĹǥХåե롣 - # - # @param length ХåեĹ - # - # @else - # - # @brief Constructor - # - # Constructor. - # Initialize the buffer by specified buffer length. - # However, if the specified length is less than two, the buffer should - # be initialized by two in length. - # - # @param length Buffer length - # - # @endif - # - # @endif - def __init__(self, length=RINGBUFFER_DEFAULT_LENGTH): - self._overwrite = True - self._readback = True - self._timedwrite = False - self._timedread = False - self._wtimeout = OpenRTM_aist.TimeValue(1,0) - self._rtimeout = OpenRTM_aist.TimeValue(1,0) - self._length = length - self._wpos = 0 - self._rpos = 0 - self._fillcount = 0 - self._wcount = 0 - self._buffer = [None for i in range(self._length)] - self._pos_mutex = threading.RLock() - self._full_mutex = threading.RLock() - self._empty_mutex = threading.RLock() - self._full_cond = threading.Condition(self._full_mutex) - self._empty_cond = threading.Condition(self._empty_mutex) - - - self.reset() - - - ## - # @if jp - # @brief Хåե - # - # Properties Ϳץѥƥˤꡢ - # Хåե롣 - # ѤǤ륪ץỌ̇̄ϰʲ̤ - # - # - buffer.length: - # ХåեĹʳοͤꤵƤ̵뤵롣 - # Ǥ˥ХåեѾ֤Ǥ⡢Ĺꤵ줿Τ٤Ƥ - # ݥ󥿤롣 - # - # - buffer.write.full_policy: - # 񤭤뤫ɤΥݥꥷ - # overwrite (), do_nothing (⤷ʤ), block (֥å) - # block ꤷ硢 timeout ͤꤹСָ - # 񤭹ԲǽǤХॢȤ롣 - # ǥեȤ overwrite () - # - # - buffer.write.timeout: - # ॢȻ֤ [sec] ǻꤹ롣ǥեȤ 1.0 [sec] - # 1 sec -> 1.0, 1 ms -> 0.001, ॢȤʤ -> 0.0 - # - # - buffer.read.empty_policy: - # ХåեΤȤɤ߽Фݥꥷ - # readback (Ǹ), do_nothing (⤷ʤ), block (֥å) - # block ꤷ硢 timeout ͤꤹСָ - # ɤ߽ФԲǽǤХॢȤ롣 - # ǥեȤ readback (Ǹ) - # - # - buffer.read.timeout: - # ॢȻ [sec] ǻꤹ롣ǥեȤ 1.0 [sec] - # 1sec -> 1.0, 1ms -> 0.001, ॢȤʤ -> 0.0 - # - # @else - # - # @endif - # - # void init(const coil::Properties& prop) - def init(self, prop): - self.__initLength(prop) - self.__initWritePolicy(prop) - self.__initReadPolicy(prop) - - - ## - # @if jp - # - # @brief ХåեĹ - # - # ХåեĹ롣 - # - # @param self - # - # @return ХåեĹ - # - # @else - # - # @brief Get the buffer length - # - # @endif - # - # size_t length(void) const - def length(self, n = None): - if n is None: - guard = OpenRTM_aist.ScopedLock(self._pos_mutex) - return self._length - - if n < 1: - return OpenRTM_aist.BufferStatus.NOT_SUPPORTED - - self._buffer = [None for i in range(n)] - self._length = n - self.reset() - return OpenRTM_aist.BufferStatus.BUFFER_OK - - - ## - # @if jp - # - # @brief Хåեξ֤ꥻåȤ - # - # Хåեɤ߽Фݥ󥿤Ƚ񤭹ߥݥ󥿤ΰ֤ꥻåȤ롣 - # μǤ BUFFER_OK ֤ʤ - # - # @return BUFFER_OK: ェλ - # NOT_SUPPORTED: ꥻåԲǽ - # BUFFER_ERROR: ۾ェλ - # - # @else - # - # @brief Get the buffer length - # - # Pure virtual function to get the buffer length. - # - # @return buffer length - # - # @endif - # - # ReturnCode reset() - def reset(self): - guard = OpenRTM_aist.ScopedLock(self._pos_mutex) - self._fillcount = 0 - self._wcount = 0 - self._wpos = 0 - self._rpos = 0 - return OpenRTM_aist.BufferStatus.BUFFER_OK - - - ## - # @if jp - # - # @brief ХåեθߤνǤΥݥ - # - # ХåեθߤνǤΥݥ󥿤ޤϡnΥݥ󥿤֤ - # - # @param n ߥݥ + n ΰ֤Υݥ - # @return ֤߰Υݥ - # - # @else - # - # @brief Get the buffer length - # - # Pure virtual function to get the buffer length. - # - # @return buffer length - # - # @endif - # - # DataType* wptr(long int n = 0) - def wptr(self, n = 0): - guard = OpenRTM_aist.ScopedLock(self._pos_mutex) - return self._buffer[(self._wpos + n + self._length) % self._length] - - - ## - # @if jp - # - # @brief ߥݥ󥿤ʤ - # - # ߤν񤭹֤߰Υݥ󥿤 n Ŀʤ롣 - # 񤭹߲ǽǿʾοͤꤷ硢PRECONDITION_NOT_MET - # ֤ - # - # @param n ߥݥ + n ΰ֤Υݥ - # @param unlock_enable Trueξ˥ХåեץƥΥ֥å - # @return BUFFER_OK: ェλ - # PRECONDITION_NOT_MET: n > writable() - # - # @else - # - # @brief Get the buffer length - # - # Pure virtual function to get the buffer length. - # - # @param n - # @param unlock_enable - # - # @return buffer length - # - # @endif - # - # ReturnCode advanceWptr(long int n = 1) - def advanceWptr(self, n = 1, unlock_enable=True): - empty = False - if unlock_enable and n > 0: - self._empty_cond.acquire() - empty = self.empty() - # n > 0 : - # n satisfies n <= writable elements - # n <= m_length - m_fillcout - # n < 0 : -n = n' - # n satisfies n'<= readable elements - # n'<= m_fillcount - # n >= - m_fillcount - guard = OpenRTM_aist.ScopedLock(self._pos_mutex) - if (n > 0 and n > (self._length - self._fillcount)) or \ - (n < 0 and n < (-self._fillcount)): - if unlock_enable and n > 0: - self._empty_cond.release() - return OpenRTM_aist.BufferStatus.PRECONDITION_NOT_MET - - self._wpos = (self._wpos + n + self._length) % self._length - self._fillcount += n - self._wcount += n - del guard - - if unlock_enable and n > 0: - if empty: - self._empty_cond.notify() - self._empty_cond.release() - - return OpenRTM_aist.BufferStatus.BUFFER_OK - - - ## - # @if jp - # - # @brief Хåե˥ǡ񤭹 - # - # Хåե˥ǡ񤭹ࡣ񤭹ߥݥ󥿤ΰ֤ѹʤ - # μǤϾ BUFFER_OK ֤ - # - # @param value 񤭹оݥǡ - # - # @return BUFFER_OK: ェλ - # BUFFER_ERROR: ۾ェλ - # - # @else - # - # @brief Write data into the buffer - # - # Pure virtual function to write data into the buffer. - - # - # @param value Target data to write. - # - # @return BUFFER_OK: Successful - # BUFFER_ERROR: Failed - # - # @endif - # - # ReturnCode put(const DataType& value) - def put(self, value): - guard = OpenRTM_aist.ScopedLock(self._pos_mutex) - self._buffer[self._wpos] = value - return OpenRTM_aist.BufferStatus.BUFFER_OK - - ## - # @if jp - # - # @brief Хåե˽񤭹 - # - # Ϳ줿ǡХåե˽񤭹ࡣ - # - # 2(sec)3(nsec)ꤵƤʤ硢Хåեե - # νߥ⡼ (overwrite, do_nothing, block) init() - # 줿⡼ɤ˽ - # - # 2(sec) ˰ꤵ줿ϡinit() ꤵ줿⡼ - # ˴ؤ餺block ⡼ɤȤʤꡢХåեե֤Ǥл - # ֤ޤॢȤ롣3(nsec)ϻꤵʤ0Ȥ - # 롣ॢԤˡɤ߽Фå¦ǥХåե - # ɤ߽ФС֥å󥰤ϲǡ񤭹ޤ롣 - # - # 񤭹߻˥Хåե(empty)֤ǡ̤Υåɤblock⡼ - # ɤ߽ФԤ򤷤Ƥ硢signalȯԤɤ߽Ф¦Υ֥ - # 󥰤롣 - # - # @param value 񤭹оݥǡ - # @param sec ॢȻ sec (default -1: ̵) - # @param nsec ॢȻ nsec (default 0) - # @return BUFFER_OK ェλ - # BUFFER_FULL Хåեե - # TIMEOUT ߤॢȤ - # PRECONDITION_NOT_MET ۾ - # - # @else - # - # @brief Write data into the buffer - # - # Write data which is given argument into the buffer. - # - # @param value Target data for writing - # - # @return Writing result (Always true: writing success is returned) - # - # @endif - # - # ReturnCode write(const DataType& value, - # long int sec = -1, long int nsec = 0) - def write(self, value, sec = -1, nsec = 0): - try: - self._full_cond.acquire() - self.full() - if self.full(): - timedwrite = self._timedwrite # default is False - overwrite = self._overwrite # default is True - - if not (sec < 0): # if second arg is set -> block mode - timedwrite = True - overwrite = False - - if overwrite and not timedwrite: # "overwrite" mode - self.advanceRptr(unlock_enable=False) - - elif not overwrite and not timedwrite: # "do_nothing" mode - self._full_cond.release() - return OpenRTM_aist.BufferStatus.BUFFER_FULL - - elif not overwrite and timedwrite: # "block" mode - - if sec < 0: - sec = self._wtimeout.sec() - nsec = self._wtimeout.usec() * 1000 - - # true: signaled, false: timeout - if sec != 0 or nsec != 0: - wait_time = sec + (nsec/1000000000.0) - else: - wait_time = None - ret = self._full_cond.wait(wait_time) - if sys.version_info[0] == 3: - if not ret: - self._full_cond.release() - return OpenRTM_aist.BufferStatus.TIMEOUT - else: - if self.full(): - self._full_cond.release() - return OpenRTM_aist.BufferStatus.TIMEOUT - - else: # unknown condition - self._full_cond.release() - return OpenRTM_aist.BufferStatus.PRECONDITION_NOT_MET - self._full_cond.release() - - self.put(value) - - self.advanceWptr(1) - - return OpenRTM_aist.BufferStatus.BUFFER_OK - except: - return OpenRTM_aist.BufferStatus.BUFFER_OK - - - ## - # @if jp - # - # @brief Хåե˽߲ǽǿ - # - # Хåե˽߲ǽǿ֤ - # - # @return 񤭹߲ǽǿ - # - # @else - # - # @brief Write data into the buffer - # - # Pure virtual function to write data into the buffer. - # - # @param value Target data to write. - # - # @return Result of having written in data (true:Successful, false:Failed) - # - # @endif - # - # size_t writable() const - def writable(self): - guard = OpenRTM_aist.ScopedLock(self._pos_mutex) - return self._length - self._fillcount - - - ## - # @if jp - # - # @brief Хåեfullå - # - # Хåեfullåѽ貾۴ؿ - # - # @return fullå(true:Хåեfullfalse:Хåե) - # - # @else - # - # @brief Check on whether the buffer is full. - # - # Pure virtual function to check on whether the buffer is full. - # - # @return True if the buffer is full, else false. - # - # @endif - # - # bool full(void) const - def full(self): - guard = OpenRTM_aist.ScopedLock(self._pos_mutex) - return self._length == self._fillcount - - - ## - # @if jp - # - # @brief Хåեθߤɤ߽ФǤΥݥ - # - # Хåեθߤɤ߽ФǤΥݥ󥿤ޤϡnΥݥ󥿤֤ - # - # @param n ɤ߽Фݥ + n ΰ֤Υݥ - # @return ɤ߽Ф֤Υݥ - # - # @else - # - # @brief Get the buffer length - # - # Pure virtual function to get the buffer length. - # - # @return buffer length - # - # @endif - def rptr(self, n = 0): - guard = OpenRTM_aist.ScopedLock(self._pos_mutex) - return self._buffer[(self._rpos + n + self._length) % self._length] - - - ## - # @if jp - # - # @brief ɤ߽Фݥ󥿤ʤ - # - # ߤɤ߽Ф֤Υݥ󥿤 n Ŀʤ롣 - # - # @param n ɤ߽Фݥ + n ΰ֤Υݥ - # @param unlock_enable Trueξ˥ХåեեΥ֥å - # @return BUFFER_OK: ェλ - # BUFFER_ERROR: ۾ェλ - # - # @else - # - # @brief Get the buffer length - # - # Pure virtual function to get the buffer length. - # - # @param n - # @param unlock_enable - # - # @return buffer length - # - # @endif - # - # DataType* rptr(long int n = 0) - def advanceRptr(self, n = 1, unlock_enable=True): - full_ = False - if unlock_enable and n > 0: - self._full_cond.acquire() - full_ = self.full() - # n > 0 : - # n satisfies n <= readable elements - # n <= m_fillcout - # n < 0 : -n = n' - # n satisfies n'<= m_length - m_fillcount - # n >= m_fillcount - m_length - guard = OpenRTM_aist.ScopedLock(self._pos_mutex) - if (n > 0 and n > self._fillcount) or \ - (n < 0 and n < (self._fillcount - self._length)): - if unlock_enable and n > 0: - self._full_cond.release() - return OpenRTM_aist.BufferStatus.PRECONDITION_NOT_MET - - self._rpos = (self._rpos + n + self._length) % self._length - self._fillcount -= n - del guard - - - - if unlock_enable and n > 0: - if full_: - self._full_cond.notify() - self._full_cond.release() - - return OpenRTM_aist.BufferStatus.BUFFER_OK - - - - ## - # @if jp - # - # @brief Хåեǡɤ߽Ф - # - # Хåեǡɤߤɤ߽Фݥ󥿤ΰ֤ѹʤ - # - # @param value ɤ߽Фǡ - # - # @return BUFFER_OK: ェλ - # BUFFER_ERROR: ۾ェλ - # - # @else - # - # @brief Write data into the buffer - # - # Pure virtual function to write data into the buffer. - # - # @param value Target data to write. - # - # @return Result of having written in data (true:Successful, false:Failed) - # - # @endif - # - # ReturnCode get(DataType& value) - def get(self, value=None): - guard = OpenRTM_aist.ScopedLock(self._pos_mutex) - if value is None: - return self._buffer[self._rpos] - - value[0] = self._buffer[self._rpos] - return OpenRTM_aist.BufferStatus.BUFFER_OK - - - ## - # @if jp - # - # @brief Хåեɤ߽Ф - # - # Хåե˳Ǽ줿ǡɤ߽Ф - # - # 2(sec)3(nsec)ꤵƤʤ硢Хåե - # ֤Ǥɤ߽Ф⡼ (readback, do_nothing, block) init() - # ꤵ줿⡼ɤ˽ - # - # 2(sec) ˰ꤵ줿ϡinit() ꤵ줿⡼ - # ˴ؤ餺block ⡼ɤȤʤꡢХåե֤Ǥл - # ԤॢȤ롣3(nsec)ϻꤵʤ0Ȥư - # 롣ॢԤˡߥå¦ǥХåեؽ - # С֥å󥰤ϲǡɤߤ롣 - # - # ɤ߽Ф˥Хåե(empty)֤ǡ̤Υåɤblock⡼ - # ǽԤ򤷤Ƥ硢signalȯԤƽ¦Υ֥å - # 롣 - # - # @param value(list) ɤ߽Фоݥǡ - # @param sec ॢȻ sec (default -1: ̵) - # @param nsec ॢȻ nsec (default 0) - # @return BUFFER_OK ェλ - # BUFFER_EMPTY Хåեե - # TIMEOUT ߤॢȤ - # PRECONDITION_NOT_MET ۾ - # - # @else - # - # @brief Readout data from the buffer - # - # Readout data stored into the buffer. - # - # @param value(list) Readout data - # - # @return Readout result (Always true: readout success is returned) - # - # @endif - # - # ReturnCode read(DataType& value, - # long int sec = -1, long int nsec = 0) - def read(self, value, sec = -1, nsec = 0): - self._empty_cond.acquire() - - if self.empty(): - timedread = self._timedread - readback = self._readback - - if not (sec < 0): # if second arg is set -> block mode - timedread = True - readback = False - sec = self._rtimeout.sec() - nsec = self._rtimeout.usec() * 1000 - - if readback and not timedread: # "readback" mode - if not self._wcount > 0: - self._empty_cond.release() - return OpenRTM_aist.BufferStatus.BUFFER_EMPTY - self.advanceRptr(-1) - - elif not readback and not timedread: # "do_nothing" mode - self._empty_cond.release() - return OpenRTM_aist.BufferStatus.BUFFER_EMPTY - - elif not readback and timedread: # "block" mode - if sec < 0: - sec = self._rtimeout.sec() - nsec = self._rtimeout.usec() * 1000 - # true: signaled, false: timeout - if sec != 0 or nsec != 0: - wait_time = sec + (nsec/1000000000.0) - else: - wait_time = None - ret = self._empty_cond.wait(wait_time) - if sys.version_info[0] == 3: - if not ret: + """ + """ + + RINGBUFFER_DEFAULT_LENGTH = 8 + + ## + # @if jp + # + # @brief コンストラクタ + # + # コンストラクタ + # 指定されたバッファ長でバッファを初期化する。 + # + # @param length バッファ長 + # + # @else + # + # @brief Constructor + # + # Constructor. + # Initialize the buffer by specified buffer length. + # However, if the specified length is less than two, the buffer should + # be initialized by two in length. + # + # @param length Buffer length + # + # @endif + # + # @endif + def __init__(self, length=RINGBUFFER_DEFAULT_LENGTH): + self._overwrite = True + self._readback = True + self._timedwrite = False + self._timedread = False + self._wtimeout = OpenRTM_aist.TimeValue(1, 0) + self._rtimeout = OpenRTM_aist.TimeValue(1, 0) + self._length = length + self._wpos = 0 + self._rpos = 0 + self._fillcount = 0 + self._wcount = 0 + self._buffer = [None for i in range(self._length)] + self._pos_mutex = threading.RLock() + self._full_mutex = threading.RLock() + self._empty_mutex = threading.RLock() + self._full_cond = threading.Condition(self._full_mutex) + self._empty_cond = threading.Condition(self._empty_mutex) + + self.reset() + + ## + # @if jp + # @brief バッファの設定 + # + # Properties で与えられるプロパティにより、 + # バッファの設定を初期化する。 + # 使用できるオプションと意味は以下の通り + # + # - buffer.length: + # バッファの長さ。自然数以外の数値が指定されても無視される。す + # でにバッファが使用状態でも、長さが再設定されたのち、すべての + # ポインタが初期化される。 + # + # - buffer.write.full_policy: + # 上書きするかどうかのポリシー。 + # overwrite (上書き), do_nothing (何もしない), block (ブロックする) + # block を指定した場合、次の timeout 値を指定すれば、指定時間後 + # 書き込み不可能であればタイムアウトする。 + # デフォルトは overwrite (上書き)。 + # + # - buffer.write.timeout: + # タイムアウト時間を [sec] で指定する。デフォルトは 1.0 [sec]。 + # 1 sec -> 1.0, 1 ms -> 0.001, タイムアウトしない -> 0.0 + # + # - buffer.read.empty_policy: + # バッファが空のときの読み出しポリシー。 + # readback (最後の要素), do_nothing (何もしない), block (ブロックする) + # block を指定した場合、次の timeout 値を指定すれば、指定時間後 + # 読み出し不可能であればタイムアウトする。 + # デフォルトは readback (最後の要素)。 + # + # - buffer.read.timeout: + # タイムアウト時間 [sec] で指定する。デフォルトは 1.0 [sec]。 + # 1sec -> 1.0, 1ms -> 0.001, タイムアウトしない -> 0.0 + # + # @else + # + # @endif + # + # void init(const coil::Properties& prop) + + def init(self, prop): + self.__initLength(prop) + self.__initWritePolicy(prop) + self.__initReadPolicy(prop) + + ## + # @if jp + # + # @brief バッファ長を取得する + # + # バッファ長を取得する。 + # + # @param self + # + # @return バッファ長 + # + # @else + # + # @brief Get the buffer length + # + # @endif + # + # size_t length(void) const + + def length(self, n=None): + if n is None: + guard = OpenRTM_aist.ScopedLock(self._pos_mutex) + return self._length + + if n < 1: + return OpenRTM_aist.BufferStatus.NOT_SUPPORTED + + self._buffer = [None for i in range(n)] + self._length = n + self.reset() + return OpenRTM_aist.BufferStatus.BUFFER_OK + + ## + # @if jp + # + # @brief バッファの状態をリセットする + # + # バッファの読み出しポインタと書き込みポインタの位置をリセットする。 + # この実装では BUFFER_OK しか返さない。 + # + # @return BUFFER_OK: 正常終了 + # NOT_SUPPORTED: リセット不可能 + # BUFFER_ERROR: 異常終了 + # + # @else + # + # @brief Get the buffer length + # + # Pure virtual function to get the buffer length. + # + # @return buffer length + # + # @endif + # + # ReturnCode reset() + + def reset(self): + guard = OpenRTM_aist.ScopedLock(self._pos_mutex) + self._fillcount = 0 + self._wcount = 0 + self._wpos = 0 + self._rpos = 0 + return OpenRTM_aist.BufferStatus.BUFFER_OK + + ## + # @if jp + # + # @brief バッファの現在の書込み要素のポインタ + # + # バッファの現在の書込み要素のポインタまたは、n個先のポインタを返す + # + # @param n 書込みポインタ + n の位置のポインタ + # @return 書込み位置のポインタ + # + # @else + # + # @brief Get the buffer length + # + # Pure virtual function to get the buffer length. + # + # @return buffer length + # + # @endif + # + # DataType* wptr(long int n = 0) + + def wptr(self, n=0): + guard = OpenRTM_aist.ScopedLock(self._pos_mutex) + return self._buffer[(self._wpos + n + self._length) % self._length] + + ## + # @if jp + # + # @brief 書込みポインタを進める + # + # 現在の書き込み位置のポインタを n 個進める。 + # 書き込み可能な要素数以上の数値を指定した場合、PRECONDITION_NOT_MET + # を返す。 + # + # @param n 書込みポインタ + n の位置のポインタ + # @param unlock_enable Trueの場合にバッファエンプティのブロックを解除する + # @return BUFFER_OK: 正常終了 + # PRECONDITION_NOT_MET: n > writable() + # + # @else + # + # @brief Get the buffer length + # + # Pure virtual function to get the buffer length. + # + # @param n + # @param unlock_enable + # + # @return buffer length + # + # @endif + # + # ReturnCode advanceWptr(long int n = 1) + + def advanceWptr(self, n=1, unlock_enable=True): + empty = False + if unlock_enable and n > 0: + self._empty_cond.acquire() + empty = self.empty() + # n > 0 : + # n satisfies n <= writable elements + # n <= m_length - m_fillcout + # n < 0 : -n = n' + # n satisfies n'<= readable elements + # n'<= m_fillcount + # n >= - m_fillcount + guard = OpenRTM_aist.ScopedLock(self._pos_mutex) + if (n > 0 and n > (self._length - self._fillcount)) or \ + (n < 0 and n < (-self._fillcount)): + if unlock_enable and n > 0: + self._empty_cond.release() + return OpenRTM_aist.BufferStatus.PRECONDITION_NOT_MET + + self._wpos = (self._wpos + n + self._length) % self._length + self._fillcount += n + self._wcount += n + del guard + + if unlock_enable and n > 0: + if empty: + self._empty_cond.notify() self._empty_cond.release() - return OpenRTM_aist.BufferStatus.TIMEOUT - else: - if self.empty(): - self._empty_cond.release() - return OpenRTM_aist.BufferStatus.TIMEOUT - else: # unknown condition + return OpenRTM_aist.BufferStatus.BUFFER_OK + + ## + # @if jp + # + # @brief バッファにデータを書き込む + # + # バッファにデータを書き込む。書き込みポインタの位置は変更されない。 + # この実装では常に BUFFER_OK を返す。 + # + # @param value 書き込み対象データ + # + # @return BUFFER_OK: 正常終了 + # BUFFER_ERROR: 異常終了 + # + # @else + # + # @brief Write data into the buffer + # + # Pure virtual function to write data into the buffer. + + # + # @param value Target data to write. + # + # @return BUFFER_OK: Successful + # BUFFER_ERROR: Failed + # + # @endif + # + # ReturnCode put(const DataType& value) + + def put(self, value): + guard = OpenRTM_aist.ScopedLock(self._pos_mutex) + self._buffer[self._wpos] = value + return OpenRTM_aist.BufferStatus.BUFFER_OK + + ## + # @if jp + # + # @brief バッファに書き込む + # + # 引数で与えられたデータをバッファに書き込む。 + # + # 第2引数(sec)、第3引数(nsec)が指定されていない場合、バッファフル + # 時の書込みモード (overwrite, do_nothing, block) は init() で設定 + # されたモードに従う。 + # + # 第2引数(sec) に引数が指定された場合は、init() で設定されたモード + # に関わらず、block モードとなり、バッファがフル状態であれば指定時 + # 間まち、タイムアウトする。第3引数(nsec)は指定されない場合0として + # 扱われる。タイムアウト待ち中に、読み出しスレッド側でバッファから + # 読み出せば、ブロッキングは解除されデータが書き込まれる。 + # + # 書き込み時にバッファが空(empty)状態で、別のスレッドがblockモード + # で読み出し待ちをしている場合、signalを発行して読み出し側のブロッ + # キングが解除される。 + # + # @param value 書き込み対象データ + # @param sec タイムアウト時間 sec (default -1: 無効) + # @param nsec タイムアウト時間 nsec (default 0) + # @return BUFFER_OK 正常終了 + # BUFFER_FULL バッファがフル状態 + # TIMEOUT 書込みがタイムアウトした + # PRECONDITION_NOT_MET 設定異常 + # + # @else + # + # @brief Write data into the buffer + # + # Write data which is given argument into the buffer. + # + # @param value Target data for writing + # + # @return Writing result (Always true: writing success is returned) + # + # @endif + # + # ReturnCode write(const DataType& value, + # long int sec = -1, long int nsec = 0) + def write(self, value, sec=-1, nsec=0): + try: + self._full_cond.acquire() + if self.full(): + timedwrite = self._timedwrite # default is False + overwrite = self._overwrite # default is True + + if not (sec < 0): # if second arg is set -> block mode + timedwrite = True + overwrite = False + + if overwrite and not timedwrite: # "overwrite" mode + self.advanceRptr(unlock_enable=False) + + elif not overwrite and not timedwrite: # "do_nothing" mode + self._full_cond.release() + return OpenRTM_aist.BufferStatus.BUFFER_FULL + + elif not overwrite and timedwrite: # "block" mode + + if sec < 0: + sec = self._wtimeout.sec() + nsec = self._wtimeout.usec() * 1000 + + # true: signaled, false: timeout + if sec != 0 or nsec != 0: + wait_time = sec + (nsec / 1000000000.0) + else: + wait_time = None + ret = self._full_cond.wait(wait_time) + if sys.version_info[0] == 3: + if not ret: + self._full_cond.release() + return OpenRTM_aist.BufferStatus.TIMEOUT + else: + if self.full(): + self._full_cond.release() + return OpenRTM_aist.BufferStatus.TIMEOUT + + else: # unknown condition + self._full_cond.release() + return OpenRTM_aist.BufferStatus.PRECONDITION_NOT_MET + self._full_cond.release() + + self.put(value) + + self.advanceWptr(1) + + return OpenRTM_aist.BufferStatus.BUFFER_OK + except BaseException: + return OpenRTM_aist.BufferStatus.BUFFER_OK + + ## + # @if jp + # + # @brief バッファに書込み可能な要素数 + # + # バッファに書込み可能な要素数を返す。 + # + # @return 書き込み可能な要素数 + # + # @else + # + # @brief Write data into the buffer + # + # Pure virtual function to write data into the buffer. + # + # @param value Target data to write. + # + # @return Result of having written in data (true:Successful, false:Failed) + # + # @endif + # + # size_t writable() const + + def writable(self): + guard = OpenRTM_aist.ScopedLock(self._pos_mutex) + return self._length - self._fillcount + + ## + # @if jp + # + # @brief バッファfullチェック + # + # バッファfullチェック用純粋仮想関数 + # + # @return fullチェック結果(true:バッファfull,false:バッファ空きあり) + # + # @else + # + # @brief Check on whether the buffer is full. + # + # Pure virtual function to check on whether the buffer is full. + # + # @return True if the buffer is full, else false. + # + # @endif + # + # bool full(void) const + + def full(self): + guard = OpenRTM_aist.ScopedLock(self._pos_mutex) + return self._length == self._fillcount + + ## + # @if jp + # + # @brief バッファの現在の読み出し要素のポインタ + # + # バッファの現在の読み出し要素のポインタまたは、n個先のポインタを返す + # + # @param n 読み出しポインタ + n の位置のポインタ + # @return 読み出し位置のポインタ + # + # @else + # + # @brief Get the buffer length + # + # Pure virtual function to get the buffer length. + # + # @return buffer length + # + # @endif + + def rptr(self, n=0): + guard = OpenRTM_aist.ScopedLock(self._pos_mutex) + return self._buffer[(self._rpos + n + self._length) % self._length] + + ## + # @if jp + # + # @brief 読み出しポインタを進める + # + # 現在の読み出し位置のポインタを n 個進める。 + # + # @param n 読み出しポインタ + n の位置のポインタ + # @param unlock_enable Trueの場合にバッファフルのブロックを解除する + # @return BUFFER_OK: 正常終了 + # BUFFER_ERROR: 異常終了 + # + # @else + # + # @brief Get the buffer length + # + # Pure virtual function to get the buffer length. + # + # @param n + # @param unlock_enable + # + # @return buffer length + # + # @endif + # + # DataType* rptr(long int n = 0) + + def advanceRptr(self, n=1, unlock_enable=True): + full_ = False + if unlock_enable and n > 0: + self._full_cond.acquire() + full_ = self.full() + # n > 0 : + # n satisfies n <= readable elements + # n <= m_fillcout + # n < 0 : -n = n' + # n satisfies n'<= m_length - m_fillcount + # n >= m_fillcount - m_length + guard = OpenRTM_aist.ScopedLock(self._pos_mutex) + if (n > 0 and n > self._fillcount) or \ + (n < 0 and n < (self._fillcount - self._length)): + if unlock_enable and n > 0: + self._full_cond.release() + return OpenRTM_aist.BufferStatus.PRECONDITION_NOT_MET + + self._rpos = (self._rpos + n + self._length) % self._length + self._fillcount -= n + del guard + + if unlock_enable and n > 0: + if full_: + self._full_cond.notify() + self._full_cond.release() + + return OpenRTM_aist.BufferStatus.BUFFER_OK + + ## + # @if jp + # + # @brief バッファからデータを読み出す + # + # バッファからデータを読みだす。読み出しポインタの位置は変更されない。 + # + # + # @return ret, value + # ret : BUFFER_OK: 正常終了 + # BUFFER_ERROR: 異常終了 + # value : 読み出しデータ + # + # @else + # + # @brief Write data into the buffer + # + # Pure virtual function to write data into the buffer. + # + # @param value Target data to write. + # + # @return Result of having written in data (true:Successful, false:Failed) + # + # @endif + # + # ReturnCode get(DataType& value) + + def get(self): + guard = OpenRTM_aist.ScopedLock(self._pos_mutex) + return OpenRTM_aist.BufferStatus.BUFFER_OK, self._buffer[self._rpos] + + ## + # @if jp + # + # @brief バッファから読み出す + # + # バッファに格納されたデータを読み出す。 + # + # 第1引数(sec)、第2引数(nsec)が指定されていない場合、バッファ空状 + # 態での読み出しモード (readback, do_nothing, block) は init() で設 + # 定されたモードに従う。 + # + # 第1引数(sec) に引数が指定された場合は、init() で設定されたモード + # に関わらず、block モードとなり、バッファが空状態であれば指定時間 + # 待ち、タイムアウトする。第2引数(nsec)は指定されない場合0として扱 + # われる。タイムアウト待ち中に、書込みスレッド側でバッファへ書込み + # があれば、ブロッキングは解除されデータが読みだされる。 + # + # 読み出し時にバッファが空(empty)状態で、別のスレッドがblockモード + # で書込み待ちをしている場合、signalを発行して書込み側のブロッキン + # グが解除される。 + # + # @param value(list) 読み出し対象データ + # @param sec タイムアウト時間 sec (default -1: 無効) + # @param nsec タイムアウト時間 nsec (default 0) + # @return BUFFER_OK 正常終了 + # BUFFER_EMPTY バッファがフル状態 + # TIMEOUT 書込みがタイムアウトした + # PRECONDITION_NOT_MET 設定異常 + # + # @else + # + # @brief Readout data from the buffer + # + # Readout data stored into the buffer. + # + # @param value(list) Readout data + # + # @return Readout result (Always true: readout success is returned) + # + # @endif + # + # ReturnCode read(DataType& value, + # long int sec = -1, long int nsec = 0) + + def read(self, sec=-1, nsec=0): + self._empty_cond.acquire() + + if self.empty(): + timedread = self._timedread + readback = self._readback + + if not (sec < 0): # if second arg is set -> block mode + timedread = True + readback = False + sec = self._rtimeout.sec() + nsec = self._rtimeout.usec() * 1000 + + if readback and not timedread: # "readback" mode + if not self._wcount > 0: + self._empty_cond.release() + return OpenRTM_aist.BufferStatus.BUFFER_EMPTY, None + self.advanceRptr(-1) + + elif not readback and not timedread: # "do_nothing" mode + self._empty_cond.release() + return OpenRTM_aist.BufferStatus.BUFFER_EMPTY, None + + elif not readback and timedread: # "block" mode + if sec < 0: + sec = self._rtimeout.sec() + nsec = self._rtimeout.usec() * 1000 + # true: signaled, false: timeout + if sec != 0 or nsec != 0: + wait_time = sec + (nsec / 1000000000.0) + else: + wait_time = None + ret = self._empty_cond.wait(wait_time) + if sys.version_info[0] == 3: + if not ret: + self._empty_cond.release() + return OpenRTM_aist.BufferStatus.TIMEOUT, None + else: + if self.empty(): + self._empty_cond.release() + return OpenRTM_aist.BufferStatus.TIMEOUT, None + + else: # unknown condition + self._empty_cond.release() + return OpenRTM_aist.BufferStatus.PRECONDITION_NOT_MET, None + self._empty_cond.release() - return OpenRTM_aist.BufferStatus.PRECONDITION_NOT_MET - - self._empty_cond.release() - - val = self.get() - - if len(value) > 0: - value[0] = val - else: - value.append(val) - - self.advanceRptr() - - - return OpenRTM_aist.BufferStatus.BUFFER_OK - - - ## - # @if jp - # - # @brief Хåեɤ߽Фǽǿ - # - # Хåեɤ߽Фǽǿ֤ - # - # @return ɤ߽Фǽǿ - # - # @return BUFFER_OK: ェλ - # BUFFER_ERROR: ۾ェλ - # - # @else - # - # @brief Write data into the buffer - # - # Pure virtual function to write data into the buffer. - # - # @param value Target data to write. - # - # @return Result of having written in data (true:Successful, false:Failed) - # - # @endif - # - # size_t readable() const - def readable(self): - guard = OpenRTM_aist.ScopedLock(self._pos_mutex) - return self._fillcount - - - ## - # @if jp - # - # @brief Хåեemptyå - # - # Хåեemptyåѽ貾۴ؿ - # - # @return emptyå(true:Хåեemptyfalse:Хåեǡ) - # - # @else - # - # @brief Check on whether the buffer is empty. - # - # Pure virtual function to check on whether the buffer is empty. - # - # @return True if the buffer is empty, else false. - # - # @endif - # - # bool empty(void) const - def empty(self): - guard = OpenRTM_aist.ScopedLock(self._pos_mutex) - return self._fillcount == 0 - - - ## void initLength(const coil::Properties& prop) - def __initLength(self, prop): - if prop.getProperty("length"): - n = [0] - if OpenRTM_aist.stringTo(n, prop.getProperty("length")): - n = n[0] - if n > 0: - self.length(n) - - - ## void initWritePolicy(const coil::Properties& prop) - def __initWritePolicy(self, prop): - policy = OpenRTM_aist.normalize([prop.getProperty("write.full_policy")]) - - if policy == "overwrite": - self._overwrite = True - self._timedwrite = False - - elif policy == "do_nothing": - self._overwrite = False - self._timedwrite = False - - elif policy == "block": - self._overwrite = False - self._timedwrite = True - - tm = [0.0] - if OpenRTM_aist.stringTo(tm, prop.getProperty("write.timeout")): - tm = tm[0] - if not (tm < 0): - self._wtimeout.set_time(tm) - - - ## void initReadPolicy(const coil::Properties& prop) - def __initReadPolicy(self, prop): - policy = prop.getProperty("read.empty_policy") - - if policy == "readback": - self._readback = True - self._timedread = False - - elif policy == "do_nothing": - self._readback = False - self._timedread = False - - elif policy == "block": - self._readback = False - self._timedread = True - tm = [0.0] - if OpenRTM_aist.stringTo(tm, prop.getProperty("read.timeout")): - self._rtimeout.set_time(tm[0]) + + _, value = self.get() + + self.advanceRptr() + + return OpenRTM_aist.BufferStatus.BUFFER_OK, value + + ## + # @if jp + # + # @brief バッファから読み出し可能な要素数 + # + # バッファから読み出し可能な要素数を返す。 + # + # @return 読み出し可能な要素数 + # + # @return BUFFER_OK: 正常終了 + # BUFFER_ERROR: 異常終了 + # + # @else + # + # @brief Write data into the buffer + # + # Pure virtual function to write data into the buffer. + # + # @param value Target data to write. + # + # @return Result of having written in data (true:Successful, false:Failed) + # + # @endif + # + # size_t readable() const + + def readable(self): + guard = OpenRTM_aist.ScopedLock(self._pos_mutex) + return self._fillcount + + ## + # @if jp + # + # @brief バッファemptyチェック + # + # バッファemptyチェック用純粋仮想関数 + # + # @return emptyチェック結果(true:バッファempty,false:バッファデータあり) + # + # @else + # + # @brief Check on whether the buffer is empty. + # + # Pure virtual function to check on whether the buffer is empty. + # + # @return True if the buffer is empty, else false. + # + # @endif + # + # bool empty(void) const + + def empty(self): + guard = OpenRTM_aist.ScopedLock(self._pos_mutex) + return self._fillcount == 0 + + # void initLength(const coil::Properties& prop) + + def __initLength(self, prop): + if prop.getProperty("length"): + n = 0 + ret, n = OpenRTM_aist.stringTo(n, prop.getProperty("length")) + if ret: + if n > 0: + self.length(n) + + # void initWritePolicy(const coil::Properties& prop) + + def __initWritePolicy(self, prop): + policy = OpenRTM_aist.normalize(prop.getProperty("write.full_policy")) + + if policy == "overwrite": + self._overwrite = True + self._timedwrite = False + + elif policy == "do_nothing": + self._overwrite = False + self._timedwrite = False + + elif policy == "block": + self._overwrite = False + self._timedwrite = True + + tm = 0.0 + ret, tm = OpenRTM_aist.stringTo( + tm, prop.getProperty("write.timeout")) + if ret: + if not (tm < 0): + self._wtimeout.set_time(tm) + + # void initReadPolicy(const coil::Properties& prop) + + def __initReadPolicy(self, prop): + policy = prop.getProperty("read.empty_policy") + + if policy == "readback": + self._readback = True + self._timedread = False + + elif policy == "do_nothing": + self._readback = False + self._timedread = False + + elif policy == "block": + self._readback = False + self._timedread = True + tm = 0.0 + ret, tm = OpenRTM_aist.stringTo( + tm, prop.getProperty("read.timeout")) + if ret: + self._rtimeout.set_time(tm) diff --git a/OpenRTM_aist/SdoConfiguration.py b/OpenRTM_aist/SdoConfiguration.py index 4d117c83..1e3f04a6 100644 --- a/OpenRTM_aist/SdoConfiguration.py +++ b/OpenRTM_aist/SdoConfiguration.py @@ -1,5 +1,5 @@ #!/usr/bin/env python -# -*- coding: euc-jp -*- +# -*- coding: utf-8 -*- ## # @file SdoConfiguration.py @@ -23,15 +23,15 @@ # @if jp # @namespace SDOPackage # -# @brief SDO ѥå +# @brief SDO パッケージ # # @else # # @namespace SDOPackage # # @endif -import SDOPackage, SDOPackage__POA - +import SDOPackage +import SDOPackage__POA # SdoConfiguration with SeqEx 159120 @@ -40,94 +40,93 @@ ## # @if jp -# -# @brief NVList Properties إԡ -# -# Υڥ졼 NVList Properties إԡ롣 -# -# @param prop NVList ͤǼ Properties -# @param nv ԡ NVList -# +# +# @brief NVList を Properties へコピーする +# +# このオペレーションは NVList を Properties へコピーする。 +# +# @param prop NVList の値を格納する Properties +# @param nv コピー元の NVList +# # @else -# +# # @brief Copy to Proeprties from NVList -# +# # This operation copies NVList to Properties. -# +# # @param prop Properties to store NVList values # @param nv NVList that is copies from -# +# # @endif def toProperties(prop, conf): - OpenRTM_aist.NVUtil.copyToProperties(prop, conf.configuration_data) + OpenRTM_aist.NVUtil.copyToProperties(prop, conf.configuration_data) ## # @if jp -# -# @brief Properties NVList إԡ -# -# Υڥ졼 Properties NVList إԡ롣 -# NVList value CORBA::string Ȥƥԡ롣 -# -# @param nv Properties ͤǼ NVList -# @param prop ԡ Properties -# +# +# @brief Properties を NVList へコピーする +# +# このオペレーションは Properties を NVList へコピーする。 +# NVList の value は全て CORBA::string 型としてコピーする。 +# +# @param nv Properties の値を格納する NVList +# @param prop コピー元の Properties +# # @else -# +# # @brief Copy to NVList from Proeprties -# +# # This operation copies Properties to NVList. # Created NVList's values are CORBA::string. -# +# # @param nv NVList to store Properties values # @param prop Properties that is copies from -# +# # @endif def toConfigurationSet(conf, prop): - conf.description = prop.getProperty("description") - conf.id = prop.getName() - OpenRTM_aist.NVUtil.copyFromProperties(conf.configuration_data, prop) - + conf.description = prop.getProperty("description") + conf.id = prop.getName() + OpenRTM_aist.NVUtil.copyFromProperties(conf.configuration_data, prop) ## # @if jp # # @class Configuration_impl -# @brief SDO Configuration 饹 +# @brief SDO Configuration 実装クラス +# +# Configuration interface は Resource Data Model で定義されたデータの +# 追加、削除等の操作を行うためのインターフェースである。 +# DeviceProfile, ServiceProfile, ConfigurationProfile および Organization +# の変更を行うためのオペレーションを備えている。SDO の仕様ではアクセス制御 +# およびセキュリティに関する詳細については規定していない。 # -# Configuration interface Resource Data Model 줿ǡ -# ɲáԤΥ󥿡եǤ롣 -# DeviceProfile, ServiceProfile, ConfigurationProfile Organization -# ѹԤΥڥ졼Ƥ롣SDO λͤǤϥ -# ӥƥ˴ؤܺ٤ˤĤƤϵꤷƤʤ -# -# ʣ (Configuration) ݻ뤳Ȥˤꡢưפ᤯ -# ȿǤ뤳ȤǤ롣줿ʣ ConfigurationSets -# configuration profile Ȥݻ뤳ȤǤ롣ҤȤĤ -# ConfigurationSet ˴Ϣդ줿ץѥƥͤΥꥹȤ -# ˡIDܺ٤ȤȤ˻äƤ롣ˤꡢܤξܺ٤򵭽Ҥ -# ̤뤳ȤǤ롣Configuration interface Υڥ졼Ϥ -# ConfiguratioinSets δٱ礹롣 +# 複数の設定 (Configuration) を保持することにより、容易かつ素早くある設定 +# を反映させることができる。事前に定義された複数の設定を ConfigurationSets +# および configuration profile として保持することができる。ひとつの +# ConfigurationSet は特定の設定に関連付けられた全プロパティ値のリストを、 +# ユニークID、詳細とともに持っている。これにより、各設定項目の詳細を記述し +# 区別することができる。Configuration interface のオペレーションはこれら +# ConfiguratioinSets の管理を支援する。 # # -# - ConfigurationSet: id, description, NVList 鹽1åȤ -# - ConfigurationSetList: ConfigurationSet Υꥹ -# - Parameter: name, type, allowed_values 鹽ѥ᡼ -# - ActiveConfigurationSet: ͭʥե졼1åȡ +# - ConfigurationSet: id, description, NVList から構成される1セットの設定 +# - ConfigurationSetList: ConfigurationSet のリスト +# - Parameter: name, type, allowed_values から構成されるパラメータ定義。 +# - ActiveConfigurationSet: 現在有効なコンフィギュレーションの1セット。 # -# ʲSDOͤƤʤ⤷ϲ᤬狼ʤȼ +# 以下、SDO仕様に明記されていないもしくは解釈がわからないため独自解釈 # -# ʲδؿ ParameterList ФƽԤ +# 以下の関数は ParameterList に対して処理を行う。 # - get_configuration_parameters() # -# ʲδؿϥƥ֤ConfigurationSetФԤ +# 以下の関数はアクティブなConfigurationSetに対する処理を行う # - get_configuration_parameter_values() # - get_configuration_parameter_value() # - set_configuration_parameter() # -# ʲδؿConfigurationSetListФƽԤ +# 以下の関数はConfigurationSetListに対して処理を行う # - get_configuration_sets() # - get_configuration_set() # - set_configuration_set_values() @@ -162,1152 +161,1139 @@ def toConfigurationSet(conf, prop): # # @endif class Configuration_impl(SDOPackage__POA.Configuration): - """ - """ - - ## - # @if jp - # - # @brief 󥹥ȥ饯 - # - # 󥹥ȥ饯 - # - # @param self - # @param configAdmin ConfigurationSetList - # @param sdoServiceAdmin SdoServiceAdmin - # - # @else - # @brief class constructor - # @param self - # @param configAdmin ConfigurationSetList - # @param sdoServiceAdmin SdoServiceAdmin - # - # @endif - # Configuration_impl(RTC::ConfigAdmin& configAdmin, - # RTC::SdoServiceAdmin& sdoServiceAdmin); - def __init__(self, configAdmin, sdoServiceAdmin): """ - \var self._deviceProfile SDO DeviceProfile with mutex lock """ - self._deviceProfile = SDOPackage.DeviceProfile("","","","",[]) - self._dprofile_mutex = threading.RLock() - """ + ## + # @if jp + # + # @brief コンストラクタ + # + # コンストラクタ + # + # @param self + # @param configAdmin ConfigurationSetList + # @param sdoServiceAdmin SdoServiceAdmin + # + # @else + # @brief class constructor + # @param self + # @param configAdmin ConfigurationSetList + # @param sdoServiceAdmin SdoServiceAdmin + # + # @endif + # Configuration_impl(RTC::ConfigAdmin& configAdmin, + # RTC::SdoServiceAdmin& sdoServiceAdmin); + def __init__(self, configAdmin, sdoServiceAdmin): + """ + \var self._deviceProfile SDO DeviceProfile with mutex lock + """ + self._deviceProfile = SDOPackage.DeviceProfile("", "", "", "", []) + self._dprofile_mutex = threading.RLock() + + """ \var self._serviceProfiles SDO ServiceProfileList """ - self._serviceProfiles = [] - self._sprofile_mutex = threading.RLock() + self._serviceProfiles = [] + self._sprofile_mutex = threading.RLock() - self._parameters = [] - self._params_mutex = threading.RLock() + self._parameters = [] + self._params_mutex = threading.RLock() - self._configsets = configAdmin - self._config_mutex = threading.RLock() + self._configsets = configAdmin + self._config_mutex = threading.RLock() - self._sdoservice = sdoServiceAdmin + self._sdoservice = sdoServiceAdmin - """ + """ \var self._organizations SDO OrganizationList """ - self._organizations = [] - self._org_mutex = threading.RLock() - - self._objref = self._this() - self._rtcout = OpenRTM_aist.Manager.instance().getLogbuf("rtobject.sdo_config") - - - #============================================================ - # - # <<< CORBA interfaces >>> - # - #============================================================ - - ## - # @if jp - # - # @brief [CORBA interface] SDO DeviceProfile Υå - # - # Υڥ졼 SDO DeviceProfile 򥻥åȤ롣SDO - # DeviceProfile ݻƤʤϿ DeviceProfile - # DeviceProfile 򤹤ǤݻƤϴ¸ΤΤ֤롣 - # - # @param self - # @param dProfile SDO ˴Ϣդ DeviceProfile - # - # @return ڥ졼ɤ֤ - # - # @exception SDONotExists åȤSDO¸ߤʤ(㳰ϡCORBAɸ - # ƥ㳰OBJECT_NOT_EXIST˥ޥåԥ󥰤) - # @exception NotAvailable SDO¸ߤ뤬ʤ - # @exception InvalidParameter "dProfile" null Ǥ롣 - # @exception InternalError Ū顼ȯ - # - # @else - # - # @brief [CORBA interface] Set DeviceProfile of SDO - # - # This operation sets the DeviceProfile of an SDO. If the SDO does not - # have DeviceProfile, the operation will create a new DeviceProfile, - # otherwise it will replace the existing DeviceProfile. - # - # @param self - # @param dProfile The device profile that is to be assigned to this SDO. - # - # @return If the operation was successfully completed. - # - # @exception SDONotExists if the target SDO does not exist.(This exception - # is mapped to CORBA standard system exception - # OBJECT_NOT_EXIST.) - # @exception NotAvailable The target SDO is reachable but cannot respond. - # @exception InvalidParameter The argument "dProfile" is null. - # @exception InternalError The target SDO cannot execute the operation - # completely due to some internal error. - # @endif - def set_device_profile(self, dProfile): - self._rtcout.RTC_TRACE("set_device_profile()") - if dProfile is None: - raise SDOPackage.InvalidParameter("dProfile is empty.") - - - guard = OpenRTM_aist.ScopedLock(self._dprofile_mutex) - self._deviceProfile = dProfile - - - return True - - - ## - # @if jp - # - # @brief [CORBA interface] SDO ServiceProfile Υå - # - # Υڥ졼Ϥ Configuration interface ͭо SDO - # ServiceProfile ɲä롣⤷ ServiceProfile id Ǥ - # ID 줽 ServiceProfile Ǽ롣⤷ id - # ʤСSDO Ʊ id ServiceProfile 򸡺롣 - # Ʊ id ¸ߤʤФ ServiceProfile ɲäid ¸ߤ - # 񤭤򤹤롣
    - # (աǿСǤϥڥ졼̾add_service_profileѹ) - # - # @param self - # @param sProfile ɲä ServiceProfile - # - # @return ڥ졼ɤ֤ - # - # @exception SDONotExists åȤSDO¸ߤʤ(㳰ϡCORBAɸ - # ƥ㳰OBJECT_NOT_EXIST˥ޥåԥ󥰤) - # @exception InvalidParameter "sProfile" nullǤ롣 - # @exception NotAvailable SDO¸ߤ뤬ʤ - # @exception InternalError Ū顼ȯ - # @else - # - # @brief [CORBA interface] Set SDO's ServiceProfile - # - # This operation adds ServiceProfile to the target SDO that navigates this - # Configuration interface. If the id in argument ServiceProfile is null, - # new id is created and the ServiceProfile is stored. If the id is not - # null, the target SDO searches for ServiceProfile in it with the same id. - # It adds the ServiceProfile if not exist, or overwrites if exist. - # - # @param self - # @param sProfile ServiceProfile to be added. - # - # @return If the operation was successfully completed. - # - # @exception SDONotExists if the target SDO does not exist.(This exception - # is mapped to CORBA standard system exception - # OBJECT_NOT_EXIST.) - # @exception NotAvailable The target SDO is reachable but cannot respond. - # @exception InvalidParameter The argument "sProfile" is null. - # @exception InternalError The target SDO cannot execute the operation - # completely due to some internal error. - # @endif - def add_service_profile(self, sProfile): - self._rtcout.RTC_TRACE("add_service_profile()") - if sProfile is None: - raise SDOPackage.InvalidParameter("sProfile is empty.") - - try: - return self._sdoservice.addSdoServiceConsumer(sProfile) - except: - self._rtcout.RTC_ERROR(OpenRTM_aist.Logger.print_exception()) - raise SDOPackage.InternalError("Configuration.add_service_profile") - - - - - ## - # @if jp - # - # @brief [CORBA interface] Organization ɲ - # - # Υڥ졼 Organization object Υե󥹤ɲä롣 - # - # @param self - # @param org ɲä Organization - # - # @return ڥ졼ɤ֤ - # - # @exception SDONotExists åȤSDO¸ߤʤ(㳰ϡCORBAɸ - # ƥ㳰OBJECT_NOT_EXIST˥ޥåԥ󥰤) - # @exception NotAvailable SDO¸ߤ뤬ʤ - # @exception InvalidParameter "organization" null Ǥ롣 - # @exception InternalError Ū顼ȯ - # @else - # - # @brief [CORBA interface] Add Organization - # - # This operation adds reference of an Organization object. - # - # @param self - # @param org Organization to be added. - # - # @return If the operation was successfully completed. - # - # @exception SDONotExists if the target SDO does not exist.(This exception - # is mapped to CORBA standard system exception - # OBJECT_NOT_EXIST.) - # @exception NotAvailable The target SDO is reachable but cannot respond. - # @exception InvalidParameter The argument "organization" is null. - # @exception InternalError The target SDO cannot execute the operation - # completely due to some internal error. - # @endif - def add_organization(self, org): - self._rtcout.RTC_TRACE("add_organization()") - if org is None: - raise SDOPackage.InvalidParameter("org is empty.") - - - OpenRTM_aist.CORBA_SeqUtil.push_back(self._organizations, org) - - return True - - - ## - # @if jp - # - # @brief [CORBA interface] ServiceProfile κ - # - # Υڥ졼Ϥ Configuration interface SDO - # Service ServiceProfile 롣 ServiceProfile - # ϰˤꤵ롣 - # - # @param self - # @param id_ ServcieProfile serviceID - # - # @return ڥ졼ɤ֤ - # - # @exception SDONotExists åȤSDO¸ߤʤ(㳰ϡCORBAɸ - # ƥ㳰OBJECT_NOT_EXIST˥ޥåԥ󥰤) - # @exception InvalidParameter "id" null Ǥ롣⤷ "id" - # Ϣդ줿 ServiceProfile ¸ߤʤ - # @exception NotAvailable SDO¸ߤ뤬ʤ - # @exception InternalError Ū顼ȯ - # @else - # - # @brief [CORBA interface] Remove ServiceProfile - # - # This operation removes ServiceProfile object to the SDO that has this - # Configuration interface. The ServiceProfile object to be removed is - # specified by argument. - # - # @param self - # @param id_ serviceID of a ServiceProfile to be removed. - # - # @return If the operation was successfully completed. - # - # @exception SDONotExists if the target SDO does not exist.(This exception - # is mapped to CORBA standard system exception - # OBJECT_NOT_EXIST.) - # @exception InvalidParameter The argument "sProfile" is null, or if the - # object that is specified by argument "sProfile" does not exist. - # @exception NotAvailable The target SDO is reachable but cannot respond. - # @exception InternalError The target SDO cannot execute the operation - # completely due to some internal error. - # @endif - def remove_service_profile(self, id_): - self._rtcout.RTC_TRACE("remove_service_profile(%s)", id_) - if id_ is None: - raise SDOPackage.InvalidParameter("id is empty.") - - try: - return self._sdoservice.removeSdoServiceConsumer(id_) - except: - self._rtcout.RTC_ERROR(OpenRTM_aist.Logger.print_exception()) - raise SDOPackage.InternalError("Configuration.remove_service_profile") - - - - - ## - # @if jp - # - # @brief [CORBA interface] Organization λȤκ - # - # Υڥ졼 Organization λȤ롣 - # - # @param self - # @param organization_id Organization ΰդ id - # - # @return ڥ졼ɤ֤ - # - # @exception SDONotExists åȤSDO¸ߤʤ(㳰ϡCORBAɸ - # ƥ㳰OBJECT_NOT_EXIST˥ޥåԥ󥰤) - # @exception InvalidParameter "organization_id" null Ǥ롣 - # ⤷ "organization_id" ˴Ϣդ줿 - # OrganizationProfile ¸ߤʤ - # @exception NotAvailable SDO¸ߤ뤬ʤ - # @exception InternalError Ū顼ȯ - # @else - # - # @brief [CORBA interface] Remove the reference of Organization - # - # This operation removes the reference of an Organization object. - # - # @param self - # @param organization_id Unique id of the organization to be removed. - # - # @return If the operation was successfully completed. - # - # @exception SDONotExists if the target SDO does not exist.(This exception - # is mapped to CORBA standard system exception - # OBJECT_NOT_EXIST.) - # @exception InvalidParameter The argument "organizationID" is null, - # or the object which is specified by argument "organizationID" - # does not exist. - # @exception NotAvailable The target SDO is reachable but cannot respond. - # @exception InternalError The target SDO cannot execute the operation - # completely due to some internal error. - # @endif - def remove_organization(self, organization_id): - self._rtcout.RTC_TRACE("remove_organization(%s)", organization_id) - if organization_id is None: - raise SDOPackage.InvalidParameter("organization_id is empty.") - - try: - guard = OpenRTM_aist.ScopedLock(self._org_mutex) - OpenRTM_aist.CORBA_SeqUtil.erase_if(self._organizations, - self.org_id(organization_id)) - except: - self._rtcout.RTC_ERROR(OpenRTM_aist.Logger.print_exception()) - raise SDOPackage.InternalError("Configuration.remove_organization") - - return True - - - ## - # @if jp - # - # @brief [CORBA interface] ѥ᡼ΥꥹȤμ - # - # Υڥ졼 configuration parameter ΥꥹȤ֤ - # SDO ǽʥѥ᡼ʤжΥꥹȤ֤ - # - # @param self - # - # @return ħդѥ᡼Υꥹȡ - # - # @exception SDONotExists åȤSDO¸ߤʤ(㳰ϡCORBAɸ - # ƥ㳰OBJECT_NOT_EXIST˥ޥåԥ󥰤) - # @exception NotAvailable SDO¸ߤ뤬ʤ - # @exception InternalError Ū顼ȯ - # @else - # - # @brief [CORBA interface] Getting a list of configuration parameter - # - # This operation returns a list of Parameters. An empty list is returned - # if the SDO does not have any configurable parameter. - # - # @param self - # @return The list with definitions of parameters characterizing the - # configuration. - # - # @exception SDONotExists if the target SDO does not exist.(This exception - # is mapped to CORBA standard system exception - # OBJECT_NOT_EXIST.) - # @exception NotAvailable The target SDO is reachable but cannot respond. - # @exception InternalError The target SDO cannot execute the operation - # completely due to some internal error. - # @endif - def get_configuration_parameters(self): - self._rtcout.RTC_TRACE("get_configuration_parameters()") - - guard = OpenRTM_aist.ScopedLock(self._params_mutex) - param = copy.copy(self._parameters) - return param - - - - ## - # @if jp - # - # @brief [CORBA interface] Configuration parameter ͤΥꥹȤμ - # - # Υڥ졼Ƥ configuration ѥ᡼֤ͤ
    - # ܼǤϾ˶ΥꥹȤ֤ - # - # @param self - # - # @return Ƥ configuration ѥ᡼ͤΥꥹȡ - # - # @exception SDONotExists åȤSDO¸ߤʤ(㳰ϡCORBAɸ - # ƥ㳰OBJECT_NOT_EXIST˥ޥåԥ󥰤) - # @exception NotAvailable SDO¸ߤ뤬ʤ - # @exception InternalError Ū顼ȯ - # @else - # - # @brief [CORBA interface] Getting value list of configuration parameter - # - # This operation returns all configuration parameters and their values. - # - # @param self - # @return List of all configuration parameters and their values. - # - # @exception SDONotExists if the target SDO does not exist.(This exception - # is mapped to CORBA standard system exception - # OBJECT_NOT_EXIST.) - # @exception NotAvailable The target SDO is reachable but cannot respond. - # @exception InternalError The target SDO cannot execute the operation - # completely due to some internal error. - # @endif - def get_configuration_parameter_values(self): - self._rtcout.RTC_TRACE("get_configuration_parameter_values()") - guard = OpenRTM_aist.ScopedLock(self._config_mutex) - nvlist = [] - return nvlist - - - ## - # @if jp - # - # @brief [CORBA interface] Configuration parameter ͤμ - # - # Υڥ졼ϰ "name" ǻꤵ줿ѥ᡼֤ͤ
    - # ܼǤϾ None ֤ - # - # @param self - # @param name ͤ׵᤹ѥ᡼̾ - # - # @return ꤵ줿ѥ᡼͡ - # - # @exception SDONotExists åȤSDO¸ߤʤ(㳰ϡCORBAɸ - # ƥ㳰OBJECT_NOT_EXIST˥ޥåԥ󥰤) - # @exception InvalidParameter "name" null Ǥ롣 - # ⤷ "name" ˴Ϣդ줿ѥ᡼¸ߤʤ - # @exception NotAvailable SDO¸ߤ뤬ʤ - # @exception InternalError Ū顼ȯ - # @else - # - # @brief [CORBA interface] Getting value of configuration parameter - # - # This operation returns a value of parameter that is specified by - # argument "name." - # - # @param self - # @param Name of the parameter whose value is requested. - # - # @return The value of the specified parameter. - # - # @exception SDONotExists if the target SDO does not exist.(This exception - # is mapped to CORBA standard system exception - # OBJECT_NOT_EXIST.) - # @exception InvalidParameter if the value of the argument "name" is - # empty String, or null, or if the parameter - # that is specified by argument "name" - # does not exist. - # @exception NotAvailable The target SDO is reachable but cannot respond. - # @exception InternalError The target SDO cannot execute the operation - # completely due to some internal error. - # @endif - def get_configuration_parameter_value(self, name): - self._rtcout.RTC_TRACE("get_configuration_parameter_value(%s)", name) - if not name: - self._rtcout.RTC_ERROR(OpenRTM_aist.Logger.print_exception()) - raise SDOPackage.InvalidParameter("Name is empty.") - - return None - - - ## - # @if jp - # - # @brief [CORBA interface] Configuration ѥ᡼ѹ - # - # Υڥ졼 "name" ǻꤷѥ᡼ͤ "value" - # ѹ롣
    - # ܼǤϾTrue֤ - # - # @param self - # @param name ѹоݥѥ᡼̾ - # @param value ѹоݥѥ᡼ο͡ - # - # @return ڥ졼ɤ֤ - # - # @exception SDONotExists åȤSDO¸ߤʤ(㳰ϡCORBAɸ - # ƥ㳰OBJECT_NOT_EXIST˥ޥåԥ󥰤) - # @exception InvalidParameter ( "name"⤷"value") null Ǥ롣 - # ⤷ "name" ˴Ϣդ줿ѥ᡼¸ߤʤ - # @exception NotAvailable SDO¸ߤ뤬ʤ - # @exception InternalError Ū顼ȯ - # @else - # - # @brief [CORBA interface] Modify the parameter value - # - # This operation sets a parameter to a value that is specified by argument - # "value." The parameter to be modified is specified by argument " name." - # - # @param self - # @param name The name of parameter to be modified. - # @param value New value of the specified parameter. - # - # @return If the operation was successfully completed. - # - # @exception SDONotExists if the target SDO does not exist.(This exception - # is mapped to CORBA standard system exception - # OBJECT_NOT_EXIST.) - # @exception InvalidParameter if arguments ("name" and/or "value") is - # null, or if the parameter that is specified by the argument - # "name" does not exist. - # @exception NotAvailable The target SDO is reachable but cannot respond. - # @exception InternalError The target SDO cannot execute the operation - # completely due to some internal error. - # @endif - def set_configuration_parameter(self, name, value): - self._rtcout.RTC_TRACE("set_configuration_parameter(%s, value)", name) - if name is None or value is None: - raise SDOPackage.InvalidParameter("Name/Value is empty.") - return True - - - ## - # @if jp - # - # @brief [CORBA interface] ConfigurationSet ꥹȤμ - # - # Υڥ졼 ConfigurationProfile ConfigurationSet - # ꥹȤ֤ SDO ConfigurationSet ʤжΥꥹȤ֤ - # - # @param self - # - # @return ݻƤ ConfigurationSet ΥꥹȤθ͡ - # - # @exception SDONotExists åȤSDO¸ߤʤ(㳰ϡCORBAɸ - # ƥ㳰OBJECT_NOT_EXIST˥ޥåԥ󥰤) - # @exception NotAvailable SDO¸ߤ뤬ʤ - # @exception InternalError Ū顼ȯ - # @else - # - # @brief [CORBA interface] Getting list of ConfigurationSet - # - # This operation returns a list of ConfigurationSets that the - # ConfigurationProfile has. An empty list is returned if the SDO does not - # have any ConfigurationSets. - # This operation returns a list of all ConfigurationSets of the SDO. - # If no predefined ConfigurationSets exist, then empty list is returned. - # - # @param self - # @return The list of stored configuration with their current values. - # - # @exception SDONotExists if the target SDO does not exist.(This exception - # is mapped to CORBA standard system exception - # OBJECT_NOT_EXIST.) - # @exception NotAvailable The target SDO is reachable but cannot respond. - # @exception InternalError The target SDO cannot execute the operation - # completely due to some internal error. - # @endif - def get_configuration_sets(self): - self._rtcout.RTC_TRACE("get_configuration_sets()") - try: - guard = OpenRTM_aist.ScopedLock(self._config_mutex) - - cf = self._configsets.getConfigurationSets() - len_ = len(cf) - - config_sets = [SDOPackage.ConfigurationSet("","",[]) for i in range(len_)] - for i in range(len_): - toConfigurationSet(config_sets[i], cf[i]) - - return config_sets - - except: - self._rtcout.RTC_ERROR(OpenRTM_aist.Logger.print_exception()) - raise SDOPackage.InternalError("Configuration.get_configuration_sets") - - - - ## - # @if jp - # - # @brief [CORBA interface] ConfigurationSet μ - # - # Υڥ졼ϰǻꤵ줿 ConfigurationSet ID ˴Ϣ - # դ줿 ConfigurationSet ֤ - # - # @param self - # @param config_id ConfigurationSet μ̻ҡ - # - # @return ˤꤵ줿 ConfigurationSet - # - # @exception SDONotExists åȤSDO¸ߤʤ(㳰ϡCORBAɸ - # ƥ㳰OBJECT_NOT_EXIST˥ޥåԥ󥰤) - # @exception InvalidParameter "config_id" null ꤵ줿 - # ConfigurationSet ¸ߤʤ - # @exception NotAvailable SDO¸ߤ뤬ʤ - # @exception InternalError Ū顼ȯ - # @else - # - # @brief [CORBA interface] Getting a ConfigurationSet - # - # This operation returns the ConfigurationSet specified by the parameter - # configurationSetID. - # - # @param self - # @param config_id Identifier of ConfigurationSet requested. - # - # @return The configuration set specified by the parameter config_id. - # - # @exception SDONotExists if the target SDO does not exist.(This exception - # is mapped to CORBA standard system exception - # OBJECT_NOT_EXIST.) - # @exception InvalidParameter If the parameter 'config_id' is null - # or if there are no ConfigurationSets stored with such id. - # @exception NotAvailable The target SDO is reachable but cannot respond. - # @exception InternalError The target SDO cannot execute the operation - # completely due to some internal error. - # @endif - def get_configuration_set(self, config_id): - self._rtcout.RTC_TRACE("get_configuration_set(%s)", config_id) - if not config_id: - raise SDOPackage.InvalidParameter("ID is empty") - - guard = OpenRTM_aist.ScopedLock(self._config_mutex) - - - if not self._configsets.haveConfig(config_id): - self._rtcout.RTC_ERROR("No such ConfigurationSet") - raise SDOPackage.InternalError("No such ConfigurationSet") - - - - configset = self._configsets.getConfigurationSet(config_id) - - - config = SDOPackage.ConfigurationSet("","",[]) - toConfigurationSet(config, configset) - return config - - - - - ## - # @if jp - # - # @brief [CORBA interface] ConfigurationSet 򥻥åȤ - # - # Υڥ졼ϻꤵ줿 id ConfigurationSet 򹹿롣 - # - # @param self - # @param configuration_set ѹ ConfigurationSet ΤΡ - # - # @return ConfigurationSet ˹Ǥ true - # Ǥʤ false ֤ - # - # @exception InvalidParameter config_id null - # ꤵ줿 id dzǼ줿 ConfigurationSet¸ߤʤ - # ꤵ줿 configuration_set°ΣĤ - # @exception SDONotExists åȤSDO¸ߤʤ(㳰ϡCORBAɸ - # ƥ㳰OBJECT_NOT_EXIST˥ޥåԥ󥰤) - # @exception NotAvailable SDO¸ߤ뤬ʤ - # @exception InternalError Ū顼ȯ - # @else - # - # @brief [CORBA interface] Set ConfigurationSet - # - # This operation modifies the specified ConfigurationSet of an SDO. - # - # @param self - # @param configuration_set ConfigurationSet to be replaced. - # - # @return A flag indicating if the ConfigurationSet was modified - # successfully. "true" - The ConfigurationSet was modified - # successfully. "false" - The ConfigurationSet could not be - # modified successfully. - # - # @exception InvalidParameter if the parameter 'configurationSetID' is - # null or if there is no ConfigurationSet stored with such id. - # This exception is also raised if one of the attributes - # defining ConfigurationSet is not valid. - # @exception SDONotExists if the target SDO does not exist.(This exception - # is mapped to CORBA standard system exception - # OBJECT_NOT_EXIST.) - # @exception NotAvailable The target SDO is reachable but cannot respond. - # @exception InternalError The target SDO cannot execute the operation - # completely due to some internal error. - # @endif - def set_configuration_set_values(self, configuration_set): - self._rtcout.RTC_TRACE("set_configuration_set_values()") - if not configuration_set or not configuration_set.id: - raise SDOPackage.InvalidParameter("ID is empty.") - - try: - conf = OpenRTM_aist.Properties(key=configuration_set.id) - toProperties(conf, configuration_set) - # ---------------------------------------------------------------------------- - # Because the format of port-name had been changed from - # to ., the following processing was added. - # (since r1648) - - if conf.findNode("exported_ports"): - exported_ports = conf.getProperty("exported_ports").split(",") - exported_ports_str = "" - for i in range(len(exported_ports)): - keyval = exported_ports[i].split(".") - if len(keyval) > 2: - exported_ports_str += keyval[0] + "." + keyval[-1] - else: - exported_ports_str += exported_ports[i] - - if i != (len(exported_ports)-1): - exported_ports_str += "," - - conf.setProperty("exported_ports",exported_ports_str) - #--------------------------------------------------------------------------- - return self._configsets.setConfigurationSetValues(conf) - except: - self._rtcout.RTC_ERROR(OpenRTM_aist.Logger.print_exception()) - raise SDOPackage.InternalError("Configuration::set_configuration_set_values()") - - - - - ## - # @if jp - # - # @brief [CORBA interface] ƥ֤ ConfigurationSet - # - # Υڥ졼SDOθߥƥ֤ ConfigurationSet ֤ - # (⤷SDOθߤ꤬ͽ줿 ConfigurationSet ˤꤵ - # ʤС) - # ConfigurationSet ϰʲξˤϥƥ֤ǤϤʤΤȤߤʤ롣 - # - # - ߤ꤬ͽ줿 ConfigurationSet ˤꥻåȤƤʤ - # - SDO ꤬ƥ֤ˤʤäѹ줿 - # - SDO ꤹ ConfigurationSet ѹ줿 - # - # ξˤϡ ConfigurationSet ֤롣 - # - # @param self - # - # @return ߥƥ֤ ConfigurationSet - # - # @exception SDONotExists åȤSDO¸ߤʤ(㳰ϡCORBAɸ - # ƥ㳰OBJECT_NOT_EXIST˥ޥåԥ󥰤) - # @exception NotAvailable SDO¸ߤ뤬ʤ - # @exception InternalError Ū顼ȯ - # @else - # - # @brief [CORBA interface] Get active ConfigurationSet - # - # This operation returns the current active ConfigurationSet of an - # SDO (i.e., if the current configuration of the SDO was set using - # predefined configuration set). - # ConfigurationSet cannot be considered active if the: - # - # - current configuration of the SDO was not set using any predefined - # ConfigurationSet, or - # - configuration of the SDO was changed after it has been active, or - # - ConfigurationSet that was used to configure the SDO was modified. - # - # Empty ConfigurationSet is returned in these cases. - # - # @param self - # @return The active ConfigurationSet. - # - # @exception SDONotExists if the target SDO does not exist.(This exception - # is mapped to CORBA standard system exception - # OBJECT_NOT_EXIST.) - # @exception NotAvailable The target SDO is reachable but cannot respond. - # @exception InternalError The target SDO cannot execute the operation - # completely due to some internal error. - # @endif - def get_active_configuration_set(self): - self._rtcout.RTC_TRACE("get_active_configuration_set()") - if not self._configsets.isActive(): - raise SDOPackage.NotAvailable("NotAvailable: Configuration.get_active_configuration_set()") - - try: - guard = OpenRTM_aist.ScopedLock(self._config_mutex) - config = SDOPackage.ConfigurationSet("","",[]) - toConfigurationSet(config, self._configsets.getActiveConfigurationSet()) - return config - except: - self._rtcout.RTC_ERROR(OpenRTM_aist.Logger.print_exception()) - raise SDOPackage.InternalError("Configuration.get_active_configuration_set()") - - - - ## - # @if jp - # - # @brief [CORBA interface] ConfigurationSet ɲä - # - # ConfigurationProfile ConfigurationSet ɲä륪ڥ졼 - # - # @param self - # @param configuration_set ɲä ConfigurationSet - # - # @return ڥ졼ɤ - # - # @exception SDONotExists åȤSDO¸ߤʤ(㳰ϡCORBAɸ - # ƥ㳰OBJECT_NOT_EXIST˥ޥåԥ󥰤) - # @exception InvalidParameter "configurationSet" null - # "configurationSet"줿°ΣĤ - # ꤵ줿 configurationSet ID¸ߤ롣 - # @exception NotAvailable SDO¸ߤ뤬ʤ - # @exception InternalError Ū顼ȯ - # @else - # - # @brief [CORBA interface] Add ConfigurationSet - # - # This operation adds a ConfigurationSet to the ConfigurationProfile. - # - # @param self - # @param configuration_set The ConfigurationSet that is added. - # - # @return If the operation was successfully completed. - # - # @exception SDONotExists if the target SDO does not exist.(This exception - # is mapped to CORBA standard system exception - # OBJECT_NOT_EXIST.) - # @exception InvalidParameter If the argument "configurationSet" is null, - # or if one of the attributes defining "configurationSet" is - # invalid, or if the specified identifier of the configuration - # set already exists. - # @exception NotAvailable The target SDO is reachable but cannot respond. - # @exception InternalError The target SDO cannot execute the operation - # completely due to some internal error. - # @endif - def add_configuration_set(self, configuration_set): - self._rtcout.RTC_TRACE("add_configuration_set()") - if configuration_set is None: - raise SDOPackage.InvalidParameter("configuration_set is empty.") - - try: - guard = OpenRTM_aist.ScopedLock(self._config_mutex) - config_id = configuration_set.id - config = OpenRTM_aist.Properties(key=config_id) - toProperties(config, configuration_set) - - return self._configsets.addConfigurationSet(config) - except: - self._rtcout.RTC_ERROR(OpenRTM_aist.Logger.print_exception()) - raise SDOPackage.InternalError("Configuration::add_configuration_set()") - - - - - ## - # @if jp - # - # @brief [CORBA interface] ConfigurationSet - # - # ConfigurationProfile ConfigurationSet 롣 - # - # @param self - # @param config_id ConfigurationSet id - # - # @return ڥ졼ɤ - # - # @exception SDONotExists åȤSDO¸ߤʤ(㳰ϡCORBAɸ - # ƥ㳰OBJECT_NOT_EXIST˥ޥåԥ󥰤) - # @exception InvalidParameter "configurationSetID" null Ǥ롢 - # ⤷ϡǻꤵ줿 ConfigurationSet ¸ߤʤ - # @exception NotAvailable SDO¸ߤ뤬ʤ - # @exception InternalError Ū顼ȯ - # @else - # - # @brief [CORBA interface] Remove ConfigurationSet - # - # This operation removes a ConfigurationSet from the ConfigurationProfile. - # - # @param self - # @param config_id The id of ConfigurationSet which is removed. - # - # @return If the operation was successfully completed. - # - # @exception SDONotExists if the target SDO does not exist.(This exception - # is mapped to CORBA standard system exception - # OBJECT_NOT_EXIST.) - # @exception InvalidParameter The arguments "configurationSetID" is null, - # or if the object specified by the argument - # "configurationSetID" does not exist. - # @exception NotAvailable The target SDO is reachable but cannot respond. - # @exception InternalError The target SDO cannot execute the operation - # completely due to some internal error. - # @endif - def remove_configuration_set(self, config_id): - self._rtcout.RTC_TRACE("remove_configuration_set(%s)", config_id) - if not config_id: - raise SDOPackage.InvalidParameter("ID is empty.") - - try: - guard = OpenRTM_aist.ScopedLock(self._config_mutex) - return self._configsets.removeConfigurationSet(config_id) - except: - self._rtcout.RTC_ERROR(OpenRTM_aist.Logger.print_exception()) - raise SDOPackage.InternalError("Configuration.remove_configuration_set()") - - - - - ## - # @if jp - # - # @brief [CORBA interface] ConfigurationSet Υƥֲ - # - # ConfigurationProfile ˳Ǽ줿 ConfigurationSet ΤĤ - # ƥ֤ˤ롣 - # Υڥ졼 ConfigurationSet 򥢥ƥ֤ˤ롣 - # ʤSDO Υե졼󡦥ץѥƥγǼƤ - # ConfigurationSet ˤꤵץѥƥͤѹ롣 - # ꤵ줿 ConfigurationSet ͤƥ֡ե졼 - # ˥ԡȤȤ̣롣 - # - # @param self - # @param config_id ƥֲ ConfigurationSet id - # - # @return ڥ졼ɤ - # - # @exception SDONotExists åȤSDO¸ߤʤ(㳰ϡCORBAɸ - # ƥ㳰OBJECT_NOT_EXIST˥ޥåԥ󥰤) - # @exception InvalidParameter "config_id" null Ǥ롢⤷ - # ǻꤵ줿 ConfigurationSet ¸ߤʤ - # @exception NotAvailable SDO¸ߤ뤬ʤ - # @exception InternalError Ū顼ȯ - # @else - # - # @brief [CORBA interface] Activate ConfigurationSet - # - # This operation activates one of the stored ConfigurationSets in the - # ConfigurationProfile. - # This operation activates the specified stored ConfigurationSets. - # This means that the configuration properties of the SDO are changed as - # the values of these properties specified in the stored ConfigurationSet. - # In other words, values of the specified ConfigurationSet are now copied - # to the active configuration. - # - # @param self - # @param Identifier of ConfigurationSet to be activated. - # - # @return If the operation was successfully completed. - # - # @exception SDONotExists if the target SDO does not exist.(This exception - # is mapped to CORBA standard system exception - # OBJECT_NOT_EXIST.) - # @exception InvalidParameter if the argument ("configID") is null or - # there is no configuration set with identifier specified by - # the argument. - # @exception NotAvailable The target SDO is reachable but cannot respond. - # @exception InternalError The target SDO cannot execute the operation - # completely due to some internal error. - # @endif - def activate_configuration_set(self, config_id): - self._rtcout.RTC_TRACE("activate_configuration_set(%s)", config_id) - if not config_id: - raise SDOPackage.InvalidParameter("ID is empty.") - - if self._configsets.activateConfigurationSet(config_id): - return True - else: - raise SDOPackage.InternalError("Configuration.activate_configuration_set()") - - - - - #============================================================ - # end of CORBA interface definition - #============================================================ - - ## - # @if jp - # - # @brief ֥ȡե󥹤 - # - # оݤΥ֥ȥե󥹤 - # - # @param self - # - # @return ֥ȥե - # - # @else - # - # @endif - def getObjRef(self): - return self._objref - - - ## - # @if jp - # - # @brief SDO DeviceProfile - # - # SDO DeviceProfile - # - # @param self - # - # @return SDO DeviceProfile - # - # @else - # - # @endif - def getDeviceProfile(self): - return self._deviceProfile - - - ## - # @if jp - # - # @brief SDO ServiceProfile ΥꥹȤ - # - # SDO ServiceProfile ΥꥹȤ - # - # @param self - # - # @return SDO ServiceProfileꥹ - # - # @else - # - # @endif - def getServiceProfiles(self): - return self._serviceProfiles - - - ## - # @if jp - # - # @brief SDO ServiceProfile - # - # Υڥ졼ϰ "id" ǻꤵ줿SDO ServiceProfile֤ - # "id" ǻꤵ줿 ServiceProfile¸ߤʤ硢 - # ServiceProfileΥ󥹥󥹤֤ - # - # @param self - # @param id ServiceProfile μ̻ҡ - # - # @return ꤵ줿 SDO ServiceProfile - # - # @else - # - # @endif - def getServiceProfile(self, id): - index = OpenRTM_aist.CORBA_SeqUtil.find(self._serviceProfiles, - self.service_id(id)) - - if index < 0: - return SDOPackage.ServiceProfile("","",[],None) - - return self._serviceProfiles[index] - - - ## - # @if jp - # - # @brief SDO Organization ꥹȤ - # - # SDO Organization ꥹȤ - # - # @param self - # - # @return SDO Organization ꥹ - # - # @else - # - # @endif - def getOrganizations(self): - return self._organizations - - - ## - # @if jp - # - # @brief UUID - # - # UUID - # - # @param self - # - # @return UUID - # - # @else - # - # @endif - def getUUID(self): - return OpenRTM_aist.uuid1() - - - # functor for NVList - ## - # @if jp - # @class nv_name - # @brief NVListfunctor - # @else - # @brief functor for NVList - # @endif - class nv_name: - def __init__(self, name_): - self._name = str(name_) - - def __call__(self, nv): - name_ = str(nv.name) - return self._name == name_ - - - # functor for ServiceProfile - ## - # @if jp - # @class service_id - # @brief ServiceProfilefunctor - # @else - # @brief functor for ServiceProfile - # @endif - class service_id: - def __init__(self, id_): - self._id = str(id_) - - def __call__(self, s): - id_ = str(s.id) - return self._id == id_ - - - # functor for Organization - ## - # @if jp - # @class org_id - # @brief Organizationfunctor - # @else - # @brief functor for Organization - # @endif - class org_id: - def __init__(self, id_): - self._id = str(id_) - - def __call__(self, o): - id_ = str(o.get_organization_id()) - return self._id == id_ - - - # functor for ConfigurationSet - ## - # @if jp - # @class config_id - # @brief ConfigurationSetfunctor - # @else - # @brief functor for ConfigurationSet - # @endif - class config_id: - def __init__(self, id_): - self._id = str(id_) - - def __call__(self, c): - id_ = str(c.id) - return self._id == id_ + self._organizations = [] + self._org_mutex = threading.RLock() + + self._objref = self._this() + self._rtcout = OpenRTM_aist.Manager.instance().getLogbuf("rtobject.sdo_config") + + # ============================================================ + # + # <<< CORBA interfaces >>> + # + # ============================================================ + + ## + # @if jp + # + # @brief [CORBA interface] SDO の DeviceProfile のセット + # + # このオペレーションは SDO の DeviceProfile をセットする。SDO が + # DeviceProfile を保持していない場合は新たな DeviceProfile を生成し、 + # DeviceProfile をすでに保持している場合は既存のものと置き換える。 + # + # @param self + # @param dProfile SDO に関連付けられる DeviceProfile。 + # + # @return オペレーションが成功したかどうかを返す。 + # + # @exception SDONotExists ターゲットのSDOが存在しない。(本例外は、CORBA標準 + # システム例外のOBJECT_NOT_EXISTにマッピングされる) + # @exception NotAvailable SDOは存在するが応答がない。 + # @exception InvalidParameter 引数 "dProfile" が null である。 + # @exception InternalError 内部的エラーが発生した。 + # + # @else + # + # @brief [CORBA interface] Set DeviceProfile of SDO + # + # This operation sets the DeviceProfile of an SDO. If the SDO does not + # have DeviceProfile, the operation will create a new DeviceProfile, + # otherwise it will replace the existing DeviceProfile. + # + # @param self + # @param dProfile The device profile that is to be assigned to this SDO. + # + # @return If the operation was successfully completed. + # + # @exception SDONotExists if the target SDO does not exist.(This exception + # is mapped to CORBA standard system exception + # OBJECT_NOT_EXIST.) + # @exception NotAvailable The target SDO is reachable but cannot respond. + # @exception InvalidParameter The argument "dProfile" is null. + # @exception InternalError The target SDO cannot execute the operation + # completely due to some internal error. + # @endif + + def set_device_profile(self, dProfile): + self._rtcout.RTC_TRACE("set_device_profile()") + if dProfile is None: + raise SDOPackage.InvalidParameter("dProfile is empty.") + + guard = OpenRTM_aist.ScopedLock(self._dprofile_mutex) + self._deviceProfile = dProfile + + return True + + ## + # @if jp + # + # @brief [CORBA interface] SDO の ServiceProfile のセット + # + # このオペレーションはこの Configuration interface を所有する対象 SDO の + # ServiceProfile を追加する。もし引数の ServiceProfile の id が空であれば + # 新しい ID が生成されその ServiceProfile を格納する。もし id が空で + # なければ、SDO は同じ id を持つ ServiceProfile を検索する。 + # 同じ id が存在しなければこの ServiceProfile を追加し、id が存在すれば + # 上書きをする。
    + # (注意:最新バージョンではオペレーション名がadd_service_profile変更) + # + # @param self + # @param sProfile 追加する ServiceProfile + # + # @return オペレーションが成功したかどうかを返す。 + # + # @exception SDONotExists ターゲットのSDOが存在しない。(本例外は、CORBA標準 + # システム例外のOBJECT_NOT_EXISTにマッピングされる) + # @exception InvalidParameter 引数 "sProfile" が nullである。 + # @exception NotAvailable SDOは存在するが応答がない。 + # @exception InternalError 内部的エラーが発生した。 + # @else + # + # @brief [CORBA interface] Set SDO's ServiceProfile + # + # This operation adds ServiceProfile to the target SDO that navigates this + # Configuration interface. If the id in argument ServiceProfile is null, + # new id is created and the ServiceProfile is stored. If the id is not + # null, the target SDO searches for ServiceProfile in it with the same id. + # It adds the ServiceProfile if not exist, or overwrites if exist. + # + # @param self + # @param sProfile ServiceProfile to be added. + # + # @return If the operation was successfully completed. + # + # @exception SDONotExists if the target SDO does not exist.(This exception + # is mapped to CORBA standard system exception + # OBJECT_NOT_EXIST.) + # @exception NotAvailable The target SDO is reachable but cannot respond. + # @exception InvalidParameter The argument "sProfile" is null. + # @exception InternalError The target SDO cannot execute the operation + # completely due to some internal error. + # @endif + + def add_service_profile(self, sProfile): + self._rtcout.RTC_TRACE("add_service_profile()") + if sProfile is None: + raise SDOPackage.InvalidParameter("sProfile is empty.") + + try: + return self._sdoservice.addSdoServiceConsumer(sProfile) + except BaseException: + self._rtcout.RTC_ERROR(OpenRTM_aist.Logger.print_exception()) + raise SDOPackage.InternalError("Configuration.add_service_profile") + + ## + # @if jp + # + # @brief [CORBA interface] Organization の追加 + # + # このオペレーションは Organization object のリファレンスを追加する。 + # + # @param self + # @param org 追加する Organization + # + # @return オペレーションが成功したかどうかを返す。 + # + # @exception SDONotExists ターゲットのSDOが存在しない。(本例外は、CORBA標準 + # システム例外のOBJECT_NOT_EXISTにマッピングされる) + # @exception NotAvailable SDOは存在するが応答がない。 + # @exception InvalidParameter 引数 "organization" が null である。 + # @exception InternalError 内部的エラーが発生した。 + # @else + # + # @brief [CORBA interface] Add Organization + # + # This operation adds reference of an Organization object. + # + # @param self + # @param org Organization to be added. + # + # @return If the operation was successfully completed. + # + # @exception SDONotExists if the target SDO does not exist.(This exception + # is mapped to CORBA standard system exception + # OBJECT_NOT_EXIST.) + # @exception NotAvailable The target SDO is reachable but cannot respond. + # @exception InvalidParameter The argument "organization" is null. + # @exception InternalError The target SDO cannot execute the operation + # completely due to some internal error. + # @endif + + def add_organization(self, org): + self._rtcout.RTC_TRACE("add_organization()") + if org is None: + raise SDOPackage.InvalidParameter("org is empty.") + + OpenRTM_aist.CORBA_SeqUtil.push_back(self._organizations, org) + + return True + + ## + # @if jp + # + # @brief [CORBA interface] ServiceProfile の削除 + # + # このオペレーションはこの Configuration interface を持つ SDO の + # Service の ServiceProfile を削除する。削除する ServiceProfile + # は引数により指定される。 + # + # @param self + # @param id_ 削除する ServcieProfile の serviceID。 + # + # @return オペレーションが成功したかどうかを返す。 + # + # @exception SDONotExists ターゲットのSDOが存在しない。(本例外は、CORBA標準 + # システム例外のOBJECT_NOT_EXISTにマッピングされる) + # @exception InvalidParameter 引数 "id" が null である。もしくは "id" に + # 関連付けられた ServiceProfile が存在しない。 + # @exception NotAvailable SDOは存在するが応答がない。 + # @exception InternalError 内部的エラーが発生した。 + # @else + # + # @brief [CORBA interface] Remove ServiceProfile + # + # This operation removes ServiceProfile object to the SDO that has this + # Configuration interface. The ServiceProfile object to be removed is + # specified by argument. + # + # @param self + # @param id_ serviceID of a ServiceProfile to be removed. + # + # @return If the operation was successfully completed. + # + # @exception SDONotExists if the target SDO does not exist.(This exception + # is mapped to CORBA standard system exception + # OBJECT_NOT_EXIST.) + # @exception InvalidParameter The argument "sProfile" is null, or if the + # object that is specified by argument "sProfile" does not exist. + # @exception NotAvailable The target SDO is reachable but cannot respond. + # @exception InternalError The target SDO cannot execute the operation + # completely due to some internal error. + # @endif + + def remove_service_profile(self, id_): + self._rtcout.RTC_TRACE("remove_service_profile(%s)", id_) + if id_ is None: + raise SDOPackage.InvalidParameter("id is empty.") + + try: + return self._sdoservice.removeSdoServiceConsumer(id_) + except BaseException: + self._rtcout.RTC_ERROR(OpenRTM_aist.Logger.print_exception()) + raise SDOPackage.InternalError( + "Configuration.remove_service_profile") + + ## + # @if jp + # + # @brief [CORBA interface] Organization の参照の削除 + # + # このオペレーションは Organization の参照を削除する。 + # + # @param self + # @param organization_id 削除する Organization の一意な id。 + # + # @return オペレーションが成功したかどうかを返す。 + # + # @exception SDONotExists ターゲットのSDOが存在しない。(本例外は、CORBA標準 + # システム例外のOBJECT_NOT_EXISTにマッピングされる) + # @exception InvalidParameter 引数 "organization_id" が null である。 + # もしくは "organization_id" に関連付けられた + # OrganizationProfile が存在しない。 + # @exception NotAvailable SDOは存在するが応答がない。 + # @exception InternalError 内部的エラーが発生した。 + # @else + # + # @brief [CORBA interface] Remove the reference of Organization + # + # This operation removes the reference of an Organization object. + # + # @param self + # @param organization_id Unique id of the organization to be removed. + # + # @return If the operation was successfully completed. + # + # @exception SDONotExists if the target SDO does not exist.(This exception + # is mapped to CORBA standard system exception + # OBJECT_NOT_EXIST.) + # @exception InvalidParameter The argument "organizationID" is null, + # or the object which is specified by argument "organizationID" + # does not exist. + # @exception NotAvailable The target SDO is reachable but cannot respond. + # @exception InternalError The target SDO cannot execute the operation + # completely due to some internal error. + # @endif + + def remove_organization(self, organization_id): + self._rtcout.RTC_TRACE("remove_organization(%s)", organization_id) + if organization_id is None: + raise SDOPackage.InvalidParameter("organization_id is empty.") + + try: + guard = OpenRTM_aist.ScopedLock(self._org_mutex) + OpenRTM_aist.CORBA_SeqUtil.erase_if(self._organizations, + self.org_id(organization_id)) + except BaseException: + self._rtcout.RTC_ERROR(OpenRTM_aist.Logger.print_exception()) + raise SDOPackage.InternalError("Configuration.remove_organization") + + return True + + ## + # @if jp + # + # @brief [CORBA interface] 設定パラメータのリストの取得 + # + # このオペレーションは configuration parameter のリストを返す。 + # SDO が設定可能なパラメータを持たなければ空のリストを返す。 + # + # @param self + # + # @return 設定を特徴付けるパラメータ定義のリスト。 + # + # @exception SDONotExists ターゲットのSDOが存在しない。(本例外は、CORBA標準 + # システム例外のOBJECT_NOT_EXISTにマッピングされる) + # @exception NotAvailable SDOは存在するが応答がない。 + # @exception InternalError 内部的エラーが発生した。 + # @else + # + # @brief [CORBA interface] Getting a list of configuration parameter + # + # This operation returns a list of Parameters. An empty list is returned + # if the SDO does not have any configurable parameter. + # + # @param self + # @return The list with definitions of parameters characterizing the + # configuration. + # + # @exception SDONotExists if the target SDO does not exist.(This exception + # is mapped to CORBA standard system exception + # OBJECT_NOT_EXIST.) + # @exception NotAvailable The target SDO is reachable but cannot respond. + # @exception InternalError The target SDO cannot execute the operation + # completely due to some internal error. + # @endif + + def get_configuration_parameters(self): + self._rtcout.RTC_TRACE("get_configuration_parameters()") + + guard = OpenRTM_aist.ScopedLock(self._params_mutex) + param = copy.copy(self._parameters) + return param + + ## + # @if jp + # + # @brief [CORBA interface] Configuration parameter の値のリストの取得 + # + # このオペレーションは全ての configuration パラメータおよび値を返す。
    + # ※本実装では常に空のリストを返す + # + # @param self + # + # @return 全ての configuration パラメータと値のリスト。 + # + # @exception SDONotExists ターゲットのSDOが存在しない。(本例外は、CORBA標準 + # システム例外のOBJECT_NOT_EXISTにマッピングされる) + # @exception NotAvailable SDOは存在するが応答がない。 + # @exception InternalError 内部的エラーが発生した。 + # @else + # + # @brief [CORBA interface] Getting value list of configuration parameter + # + # This operation returns all configuration parameters and their values. + # + # @param self + # @return List of all configuration parameters and their values. + # + # @exception SDONotExists if the target SDO does not exist.(This exception + # is mapped to CORBA standard system exception + # OBJECT_NOT_EXIST.) + # @exception NotAvailable The target SDO is reachable but cannot respond. + # @exception InternalError The target SDO cannot execute the operation + # completely due to some internal error. + # @endif + + def get_configuration_parameter_values(self): + self._rtcout.RTC_TRACE("get_configuration_parameter_values()") + guard = OpenRTM_aist.ScopedLock(self._config_mutex) + nvlist = [] + return nvlist + + ## + # @if jp + # + # @brief [CORBA interface] Configuration parameter の値の取得 + # + # このオペレーションは引数 "name" で指定されたパラメータ値を返す。
    + # ※本実装では常に None を返す + # + # @param self + # @param name 値を要求するパラメータの名前。 + # + # @return 指定されたパラメータの値。 + # + # @exception SDONotExists ターゲットのSDOが存在しない。(本例外は、CORBA標準 + # システム例外のOBJECT_NOT_EXISTにマッピングされる) + # @exception InvalidParameter 引数 "name" が null である。 + # もしくは "name" に関連付けられたパラメータが存在しない。 + # @exception NotAvailable SDOは存在するが応答がない。 + # @exception InternalError 内部的エラーが発生した。 + # @else + # + # @brief [CORBA interface] Getting value of configuration parameter + # + # This operation returns a value of parameter that is specified by + # argument "name." + # + # @param self + # @param Name of the parameter whose value is requested. + # + # @return The value of the specified parameter. + # + # @exception SDONotExists if the target SDO does not exist.(This exception + # is mapped to CORBA standard system exception + # OBJECT_NOT_EXIST.) + # @exception InvalidParameter if the value of the argument "name" is + # empty String, or null, or if the parameter + # that is specified by argument "name" + # does not exist. + # @exception NotAvailable The target SDO is reachable but cannot respond. + # @exception InternalError The target SDO cannot execute the operation + # completely due to some internal error. + # @endif + + def get_configuration_parameter_value(self, name): + self._rtcout.RTC_TRACE("get_configuration_parameter_value(%s)", name) + if not name: + self._rtcout.RTC_ERROR(OpenRTM_aist.Logger.print_exception()) + raise SDOPackage.InvalidParameter("Name is empty.") + + return None + + ## + # @if jp + # + # @brief [CORBA interface] Configuration パラメータの変更 + # + # このオペレーションは "name" で指定したパラメータの値を "value" に + # 変更する。
    + # ※本実装では常にTrueを返す + # + # @param self + # @param name 変更対象パラメータの名前。 + # @param value 変更対象パラメータの新しい値。 + # + # @return オペレーションが成功したかどうかを返す。 + # + # @exception SDONotExists ターゲットのSDOが存在しない。(本例外は、CORBA標準 + # システム例外のOBJECT_NOT_EXISTにマッピングされる) + # @exception InvalidParameter 引数( "name"もしくは"value") が null である。 + # もしくは "name" に関連付けられたパラメータが存在しない。 + # @exception NotAvailable SDOは存在するが応答がない。 + # @exception InternalError 内部的エラーが発生した。 + # @else + # + # @brief [CORBA interface] Modify the parameter value + # + # This operation sets a parameter to a value that is specified by argument + # "value." The parameter to be modified is specified by argument " name." + # + # @param self + # @param name The name of parameter to be modified. + # @param value New value of the specified parameter. + # + # @return If the operation was successfully completed. + # + # @exception SDONotExists if the target SDO does not exist.(This exception + # is mapped to CORBA standard system exception + # OBJECT_NOT_EXIST.) + # @exception InvalidParameter if arguments ("name" and/or "value") is + # null, or if the parameter that is specified by the argument + # "name" does not exist. + # @exception NotAvailable The target SDO is reachable but cannot respond. + # @exception InternalError The target SDO cannot execute the operation + # completely due to some internal error. + # @endif + + def set_configuration_parameter(self, name, value): + self._rtcout.RTC_TRACE("set_configuration_parameter(%s, value)", name) + if name is None or value is None: + raise SDOPackage.InvalidParameter("Name/Value is empty.") + return True + + ## + # @if jp + # + # @brief [CORBA interface] ConfigurationSet リストの取得 + # + # このオペレーションは ConfigurationProfile が持つ ConfigurationSet の + # リストを返す。 SDO が ConfigurationSet を持たなければ空のリストを返す。 + # + # @param self + # + # @return 保持している ConfigurationSet のリストの現在値。 + # + # @exception SDONotExists ターゲットのSDOが存在しない。(本例外は、CORBA標準 + # システム例外のOBJECT_NOT_EXISTにマッピングされる) + # @exception NotAvailable SDOは存在するが応答がない。 + # @exception InternalError 内部的エラーが発生した。 + # @else + # + # @brief [CORBA interface] Getting list of ConfigurationSet + # + # This operation returns a list of ConfigurationSets that the + # ConfigurationProfile has. An empty list is returned if the SDO does not + # have any ConfigurationSets. + # This operation returns a list of all ConfigurationSets of the SDO. + # If no predefined ConfigurationSets exist, then empty list is returned. + # + # @param self + # @return The list of stored configuration with their current values. + # + # @exception SDONotExists if the target SDO does not exist.(This exception + # is mapped to CORBA standard system exception + # OBJECT_NOT_EXIST.) + # @exception NotAvailable The target SDO is reachable but cannot respond. + # @exception InternalError The target SDO cannot execute the operation + # completely due to some internal error. + # @endif + + def get_configuration_sets(self): + self._rtcout.RTC_TRACE("get_configuration_sets()") + try: + guard = OpenRTM_aist.ScopedLock(self._config_mutex) + + cf = self._configsets.getConfigurationSets() + len_ = len(cf) + + config_sets = [ + SDOPackage.ConfigurationSet( + "", "", []) for i in range(len_)] + for i, c in enumerate(cf): + toConfigurationSet(config_sets[i], c) + + return config_sets + + except BaseException: + self._rtcout.RTC_ERROR(OpenRTM_aist.Logger.print_exception()) + raise SDOPackage.InternalError( + "Configuration.get_configuration_sets") + + ## + # @if jp + # + # @brief [CORBA interface] ConfigurationSet の取得 + # + # このオペレーションは引数で指定された ConfigurationSet の ID に関連 + # 付けられた ConfigurationSet を返す。 + # + # @param self + # @param config_id ConfigurationSet の識別子。 + # + # @return 引数により指定された ConfigurationSet。 + # + # @exception SDONotExists ターゲットのSDOが存在しない。(本例外は、CORBA標準 + # システム例外のOBJECT_NOT_EXISTにマッピングされる) + # @exception InvalidParameter "config_id" が null か、指定された + # ConfigurationSet が存在しない。 + # @exception NotAvailable SDOは存在するが応答がない。 + # @exception InternalError 内部的エラーが発生した。 + # @else + # + # @brief [CORBA interface] Getting a ConfigurationSet + # + # This operation returns the ConfigurationSet specified by the parameter + # configurationSetID. + # + # @param self + # @param config_id Identifier of ConfigurationSet requested. + # + # @return The configuration set specified by the parameter config_id. + # + # @exception SDONotExists if the target SDO does not exist.(This exception + # is mapped to CORBA standard system exception + # OBJECT_NOT_EXIST.) + # @exception InvalidParameter If the parameter 'config_id' is null + # or if there are no ConfigurationSets stored with such id. + # @exception NotAvailable The target SDO is reachable but cannot respond. + # @exception InternalError The target SDO cannot execute the operation + # completely due to some internal error. + # @endif + + def get_configuration_set(self, config_id): + self._rtcout.RTC_TRACE("get_configuration_set(%s)", config_id) + if not config_id: + raise SDOPackage.InvalidParameter("ID is empty") + + guard = OpenRTM_aist.ScopedLock(self._config_mutex) + + if not self._configsets.haveConfig(config_id): + self._rtcout.RTC_ERROR("No such ConfigurationSet") + raise SDOPackage.InternalError("No such ConfigurationSet") + + configset = self._configsets.getConfigurationSet(config_id) + + config = SDOPackage.ConfigurationSet("", "", []) + toConfigurationSet(config, configset) + return config + + ## + # @if jp + # + # @brief [CORBA interface] ConfigurationSet をセットする + # + # このオペレーションは指定された id の ConfigurationSet を更新する。 + # + # @param self + # @param configuration_set 変更する ConfigurationSet そのもの。 + # + # @return ConfigurationSet が正常に更新できた場合は true。 + # そうでなければ false を返す。 + # + # @exception InvalidParameter config_id が null か、 + # 指定された id で格納された ConfigurationSetが存在しないか、 + # 指定された configuration_set内の属性の1つが不正。 + # @exception SDONotExists ターゲットのSDOが存在しない。(本例外は、CORBA標準 + # システム例外のOBJECT_NOT_EXISTにマッピングされる) + # @exception NotAvailable SDOは存在するが応答がない。 + # @exception InternalError 内部的エラーが発生した。 + # @else + # + # @brief [CORBA interface] Set ConfigurationSet + # + # This operation modifies the specified ConfigurationSet of an SDO. + # + # @param self + # @param configuration_set ConfigurationSet to be replaced. + # + # @return A flag indicating if the ConfigurationSet was modified + # successfully. "true" - The ConfigurationSet was modified + # successfully. "false" - The ConfigurationSet could not be + # modified successfully. + # + # @exception InvalidParameter if the parameter 'configurationSetID' is + # null or if there is no ConfigurationSet stored with such id. + # This exception is also raised if one of the attributes + # defining ConfigurationSet is not valid. + # @exception SDONotExists if the target SDO does not exist.(This exception + # is mapped to CORBA standard system exception + # OBJECT_NOT_EXIST.) + # @exception NotAvailable The target SDO is reachable but cannot respond. + # @exception InternalError The target SDO cannot execute the operation + # completely due to some internal error. + # @endif + + def set_configuration_set_values(self, configuration_set): + self._rtcout.RTC_TRACE("set_configuration_set_values()") + if not configuration_set or not configuration_set.id: + raise SDOPackage.InvalidParameter("ID is empty.") + + try: + conf = OpenRTM_aist.Properties(key=configuration_set.id) + toProperties(conf, configuration_set) + # ---------------------------------------------------------------------------- + # Because the format of port-name had been changed from + # to ., the following processing was added. + # (since r1648) + + if conf.findNode("exported_ports"): + exported_ports = conf.getProperty("exported_ports").split(",") + exported_ports_str = "" + for i, exported_port in enumerate(exported_ports): + keyval = exported_port.split(".") + if len(keyval) > 2: + exported_ports_str += keyval[0] + "." + keyval[-1] + else: + exported_ports_str += exported_port + + if i != (len(exported_ports) - 1): + exported_ports_str += "," + + conf.setProperty("exported_ports", exported_ports_str) + # --------------------------------------------------------------------------- + return self._configsets.setConfigurationSetValues(conf) + except BaseException: + self._rtcout.RTC_ERROR(OpenRTM_aist.Logger.print_exception()) + raise SDOPackage.InternalError( + "Configuration::set_configuration_set_values()") + + ## + # @if jp + # + # @brief [CORBA interface] アクティブな ConfigurationSet を取得する + # + # このオペレーションは当該SDOの現在アクティブな ConfigurationSet を返す。 + # (もしSDOの現在の設定が予め定義された ConfigurationSet により設定されて + # いるならば。) + # ConfigurationSet は以下の場合にはアクティブではないものとみなされる。 + # + # - 現在の設定が予め定義された ConfigurationSet によりセットされていない、 + # - SDO の設定がアクティブになった後に変更された、 + # - SDO を設定する ConfigurationSet が変更された、 + # + # これらの場合には、空の ConfigurationSet が返される。 + # + # @param self + # + # @return 現在アクティブな ConfigurationSet。 + # + # @exception SDONotExists ターゲットのSDOが存在しない。(本例外は、CORBA標準 + # システム例外のOBJECT_NOT_EXISTにマッピングされる) + # @exception NotAvailable SDOは存在するが応答がない。 + # @exception InternalError 内部的エラーが発生した。 + # @else + # + # @brief [CORBA interface] Get active ConfigurationSet + # + # This operation returns the current active ConfigurationSet of an + # SDO (i.e., if the current configuration of the SDO was set using + # predefined configuration set). + # ConfigurationSet cannot be considered active if the: + # + # - current configuration of the SDO was not set using any predefined + # ConfigurationSet, or + # - configuration of the SDO was changed after it has been active, or + # - ConfigurationSet that was used to configure the SDO was modified. + # + # Empty ConfigurationSet is returned in these cases. + # + # @param self + # @return The active ConfigurationSet. + # + # @exception SDONotExists if the target SDO does not exist.(This exception + # is mapped to CORBA standard system exception + # OBJECT_NOT_EXIST.) + # @exception NotAvailable The target SDO is reachable but cannot respond. + # @exception InternalError The target SDO cannot execute the operation + # completely due to some internal error. + # @endif + + def get_active_configuration_set(self): + self._rtcout.RTC_TRACE("get_active_configuration_set()") + if not self._configsets.isActive(): + raise SDOPackage.NotAvailable( + "NotAvailable: Configuration.get_active_configuration_set()") + + try: + guard = OpenRTM_aist.ScopedLock(self._config_mutex) + config = SDOPackage.ConfigurationSet("", "", []) + toConfigurationSet( + config, self._configsets.getActiveConfigurationSet()) + return config + except BaseException: + self._rtcout.RTC_ERROR(OpenRTM_aist.Logger.print_exception()) + raise SDOPackage.InternalError( + "Configuration.get_active_configuration_set()") + + ## + # @if jp + # + # @brief [CORBA interface] ConfigurationSet を追加する + # + # ConfigurationProfile に ConfigurationSet を追加するオペレーション。 + # + # @param self + # @param configuration_set 追加する ConfigurationSet。 + # + # @return オペレーションが成功したかどうか。 + # + # @exception SDONotExists ターゲットのSDOが存在しない。(本例外は、CORBA標準 + # システム例外のOBJECT_NOT_EXISTにマッピングされる) + # @exception InvalidParameter "configurationSet" が null か、 + # "configurationSet"で定義された属性の1つが不正か、 + # 指定された configurationSet もIDが既に存在する。 + # @exception NotAvailable SDOは存在するが応答がない。 + # @exception InternalError 内部的エラーが発生した。 + # @else + # + # @brief [CORBA interface] Add ConfigurationSet + # + # This operation adds a ConfigurationSet to the ConfigurationProfile. + # + # @param self + # @param configuration_set The ConfigurationSet that is added. + # + # @return If the operation was successfully completed. + # + # @exception SDONotExists if the target SDO does not exist.(This exception + # is mapped to CORBA standard system exception + # OBJECT_NOT_EXIST.) + # @exception InvalidParameter If the argument "configurationSet" is null, + # or if one of the attributes defining "configurationSet" is + # invalid, or if the specified identifier of the configuration + # set already exists. + # @exception NotAvailable The target SDO is reachable but cannot respond. + # @exception InternalError The target SDO cannot execute the operation + # completely due to some internal error. + # @endif + + def add_configuration_set(self, configuration_set): + self._rtcout.RTC_TRACE("add_configuration_set()") + if configuration_set is None: + raise SDOPackage.InvalidParameter("configuration_set is empty.") + + try: + guard = OpenRTM_aist.ScopedLock(self._config_mutex) + config_id = configuration_set.id + config = OpenRTM_aist.Properties(key=config_id) + toProperties(config, configuration_set) + + return self._configsets.addConfigurationSet(config) + except BaseException: + self._rtcout.RTC_ERROR(OpenRTM_aist.Logger.print_exception()) + raise SDOPackage.InternalError( + "Configuration::add_configuration_set()") + + ## + # @if jp + # + # @brief [CORBA interface] ConfigurationSet を削除する + # + # ConfigurationProfile から ConfigurationSet を削除する。 + # + # @param self + # @param config_id 削除する ConfigurationSet の id。 + # + # @return オペレーションが成功したかどうか。 + # + # @exception SDONotExists ターゲットのSDOが存在しない。(本例外は、CORBA標準 + # システム例外のOBJECT_NOT_EXISTにマッピングされる) + # @exception InvalidParameter 引数 "configurationSetID" が null である、 + # もしくは、引数で指定された ConfigurationSet が存在しない。 + # @exception NotAvailable SDOは存在するが応答がない。 + # @exception InternalError 内部的エラーが発生した。 + # @else + # + # @brief [CORBA interface] Remove ConfigurationSet + # + # This operation removes a ConfigurationSet from the ConfigurationProfile. + # + # @param self + # @param config_id The id of ConfigurationSet which is removed. + # + # @return If the operation was successfully completed. + # + # @exception SDONotExists if the target SDO does not exist.(This exception + # is mapped to CORBA standard system exception + # OBJECT_NOT_EXIST.) + # @exception InvalidParameter The arguments "configurationSetID" is null, + # or if the object specified by the argument + # "configurationSetID" does not exist. + # @exception NotAvailable The target SDO is reachable but cannot respond. + # @exception InternalError The target SDO cannot execute the operation + # completely due to some internal error. + # @endif + + def remove_configuration_set(self, config_id): + self._rtcout.RTC_TRACE("remove_configuration_set(%s)", config_id) + if not config_id: + raise SDOPackage.InvalidParameter("ID is empty.") + + try: + guard = OpenRTM_aist.ScopedLock(self._config_mutex) + return self._configsets.removeConfigurationSet(config_id) + except BaseException: + self._rtcout.RTC_ERROR(OpenRTM_aist.Logger.print_exception()) + raise SDOPackage.InternalError( + "Configuration.remove_configuration_set()") + + ## + # @if jp + # + # @brief [CORBA interface] ConfigurationSet のアクティブ化 + # + # ConfigurationProfile に格納された ConfigurationSet のうち一つを + # アクティブにする。 + # このオペレーションは特定の ConfigurationSet をアクティブにする。 + # すなわち、SDO のコンフィギュレーション・プロパティがその格納されている + # ConfigurationSet により設定されるプロパティの値に変更される。 + # 指定された ConfigurationSet の値がアクティブ・コンフィギュレーション + # にコピーされるということを意味する。 + # + # @param self + # @param config_id アクティブ化する ConfigurationSet の id。 + # + # @return オペレーションが成功したかどうか。 + # + # @exception SDONotExists ターゲットのSDOが存在しない。(本例外は、CORBA標準 + # システム例外のOBJECT_NOT_EXISTにマッピングされる) + # @exception InvalidParameter 引数 "config_id" が null である、もしくは + # 引数で指定された ConfigurationSet が存在しない。 + # @exception NotAvailable SDOは存在するが応答がない。 + # @exception InternalError 内部的エラーが発生した。 + # @else + # + # @brief [CORBA interface] Activate ConfigurationSet + # + # This operation activates one of the stored ConfigurationSets in the + # ConfigurationProfile. + # This operation activates the specified stored ConfigurationSets. + # This means that the configuration properties of the SDO are changed as + # the values of these properties specified in the stored ConfigurationSet. + # In other words, values of the specified ConfigurationSet are now copied + # to the active configuration. + # + # @param self + # @param Identifier of ConfigurationSet to be activated. + # + # @return If the operation was successfully completed. + # + # @exception SDONotExists if the target SDO does not exist.(This exception + # is mapped to CORBA standard system exception + # OBJECT_NOT_EXIST.) + # @exception InvalidParameter if the argument ("configID") is null or + # there is no configuration set with identifier specified by + # the argument. + # @exception NotAvailable The target SDO is reachable but cannot respond. + # @exception InternalError The target SDO cannot execute the operation + # completely due to some internal error. + # @endif + + def activate_configuration_set(self, config_id): + self._rtcout.RTC_TRACE("activate_configuration_set(%s)", config_id) + if not config_id: + raise SDOPackage.InvalidParameter("ID is empty.") + + if self._configsets.activateConfigurationSet(config_id): + return True + else: + raise SDOPackage.InternalError( + "Configuration.activate_configuration_set()") + + # ============================================================ + # end of CORBA interface definition + # ============================================================ + + ## + # @if jp + # + # @brief オブジェクト リファレンスを取得する + # + # 対象のオブジェクトリファレンスを取得する + # + # @param self + # + # @return オブジェクトリファレンス + # + # @else + # + # @endif + + def getObjRef(self): + return self._objref + + ## + # @if jp + # + # @brief SDO の DeviceProfile を取得する + # + # SDO の DeviceProfile を取得する + # + # @param self + # + # @return SDO の DeviceProfile + # + # @else + # + # @endif + + def getDeviceProfile(self): + return self._deviceProfile + + ## + # @if jp + # + # @brief SDO の ServiceProfile のリストを取得する + # + # SDO の ServiceProfile のリストを取得する + # + # @param self + # + # @return SDO ServiceProfileリスト + # + # @else + # + # @endif + + def getServiceProfiles(self): + return self._serviceProfiles + + ## + # @if jp + # + # @brief SDO の ServiceProfile を取得する + # + # このオペレーションは引数 "id" で指定されたSDO の ServiceProfileを返す。 + # "id" で指定された ServiceProfileが存在しない場合、 + # ServiceProfileのインスタンスを生成し返す。 + # + # @param self + # @param id ServiceProfile の識別子。 + # + # @return 指定された SDO ServiceProfile + # + # @else + # + # @endif + + def getServiceProfile(self, id): + index = OpenRTM_aist.CORBA_SeqUtil.find(self._serviceProfiles, + self.service_id(id)) + + if index < 0: + return SDOPackage.ServiceProfile("", "", [], None) + + return self._serviceProfiles[index] + + ## + # @if jp + # + # @brief SDO の Organization リストを取得する + # + # SDO の Organization リストを取得する + # + # @param self + # + # @return SDO の Organization リスト + # + # @else + # + # @endif + + def getOrganizations(self): + return self._organizations + + ## + # @if jp + # + # @brief UUIDを生成する + # + # UUIDを生成する + # + # @param self + # + # @return 生成したUUID + # + # @else + # + # @endif + + def getUUID(self): + return OpenRTM_aist.uuid1() + + # functor for NVList + ## + # @if jp + # @class nv_name + # @brief NVList用functor + # @else + # @brief functor for NVList + # @endif + + class nv_name: + def __init__(self, name_): + self._name = str(name_) + + def __call__(self, nv): + name_ = str(nv.name) + return self._name == name_ + + # functor for ServiceProfile + ## + # @if jp + # @class service_id + # @brief ServiceProfile用functor + # @else + # @brief functor for ServiceProfile + # @endif + + class service_id: + def __init__(self, id_): + self._id = str(id_) + + def __call__(self, s): + id_ = str(s.id) + return self._id == id_ + + # functor for Organization + ## + # @if jp + # @class org_id + # @brief Organization用functor + # @else + # @brief functor for Organization + # @endif + + class org_id: + def __init__(self, id_): + self._id = str(id_) + + def __call__(self, o): + id_ = str(o.get_organization_id()) + return self._id == id_ + + # functor for ConfigurationSet + ## + # @if jp + # @class config_id + # @brief ConfigurationSet用functor + # @else + # @brief functor for ConfigurationSet + # @endif + + class config_id: + def __init__(self, id_): + self._id = str(id_) + + def __call__(self, c): + id_ = str(c.id) + return self._id == id_ diff --git a/OpenRTM_aist/SdoOrganization.py b/OpenRTM_aist/SdoOrganization.py index 1e0208a5..82884004 100644 --- a/OpenRTM_aist/SdoOrganization.py +++ b/OpenRTM_aist/SdoOrganization.py @@ -1,12 +1,12 @@ #!/usr/bin/env python -# -*- coding: euc-jp -*- +# -*- coding: utf-8 -*- ## # @file SdoOrganization.py # @brief SDO Organization implementation class # @date $Date: 2007/09/12 $ # @author Noriaki Ando and Shinji Kurihara -# +# # Copyright (C) 2006 # Task-intelligence Research Group, # Intelligent Systems Research Institute, @@ -20,808 +20,796 @@ import threading import OpenRTM_aist -import SDOPackage, SDOPackage__POA +import SDOPackage +import SDOPackage__POA ## # @if jp -# +# # @class Organization_impl -# @brief SDO Organization 饹 -# -# Organization interface Resource Data Model 줿ǡ -# ɲáԤΥ󥿡եǤ롣 -# +# @brief SDO Organization 実装クラス +# +# Organization interface は Resource Data Model で定義されたデータの +# 追加、削除等の操作を行うためのインターフェースである。 +# # @since 0.4.0 -# +# # @else -# +# # @class Organization_impl # @brief Organization implementation class -# +# # The Organization interface is used to manage the Organization attribute. -# +# # @since 0.4.0 -# +# # @endif class Organization_impl(SDOPackage__POA.Organization): - """ - """ - - ## - # @if jp - # - # @brief 󥹥ȥ饯 - # - # 󥹥ȥ饯 - # - # @else - # - # @endif - def __init__(self, sdo): - self._pId = str(OpenRTM_aist.uuid1()) - self._org_mutex = threading.RLock() - - self._orgProperty = SDOPackage.OrganizationProperty([]) - self._varOwner = sdo - self._memberList = [] - self._dependency = SDOPackage.OWN - self._objref = self._this() - self.__rtcout = OpenRTM_aist.Manager.instance().getLogbuf("rtobject.sdo_organization") - - - #============================================================ - # - # <<< CORBA interfaces >>> - # - #============================================================ - ## - # @if jp - # - # @brief [CORBA interface] Organization ID - # - # Organization ID ֤ڥ졼 - # - # @param self - # - # @return Resource Data Model 줿 Organization ID - # - # @exception SDONotExists åȤSDO¸ߤʤ(㳰ϡCORBAɸ - # ƥ㳰OBJECT_NOT_EXIST˥ޥåԥ󥰤) - # @exception NotAvailable SDO¸ߤ뤬ʤ - # @exception InternalError Ū顼ȯ - # @else - # - # @brief [CORBA interface] Get Organization Id - # - # This operation returns the 'id' of the Organization. - # - # @param self - # - # @return The id of the Organization defined in the resource data model. - # - # @exception SDONotExists if the target SDO does not exist.(This exception - # is mapped to CORBA standard system exception - # OBJECT_NOT_EXIST.) - # @exception NotAvailable The target SDO is reachable but cannot respond. - # @exception InternalError The target SDO cannot execute the operation - # completely due to some internal error. - # @endif - def get_organization_id(self): - self.__rtcout.RTC_TRACE("get_organization_id() = %s", self._pId) - return self._pId - - - ## - # @if jp - # - # @brief [CORBA interface] OrganizationProperty μ - # - # Organization ͭ OrganizationProperty ֤ڥ졼 - # Organization ץѥƥʤжΥꥹȤ֤ - # - # @param self - # - # @return Organization ΥץѥƥΥꥹȡ - # - # @exception SDONotExists åȤSDO¸ߤʤ(㳰ϡCORBAɸ - # ƥ㳰OBJECT_NOT_EXIST˥ޥåԥ󥰤) - # @exception NotAvailable SDO¸ߤ뤬ʤ - # @exception InternalError Ū顼ȯ - # @else - # - # @brief [CORBA interface] Get OrganizationProperty - # - # This operation returns the OrganizationProperty that an Organization - # has. An empty OrganizationProperty is returned if the Organization does - # not have any properties. - # - # @param self - # - # @return The list with properties of the organization. - # - # @exception SDONotExists if the target SDO does not exist.(This exception - # is mapped to CORBA standard system exception - # OBJECT_NOT_EXIST.) - # @exception NotAvailable The target SDO is reachable but cannot respond. - # @exception InternalError The target SDO cannot execute the operation - # completely due to some internal error. - # @endif - def get_organization_property(self): - self.__rtcout.RTC_TRACE("get_organization_property()") - guard = OpenRTM_aist.ScopedLock(self._org_mutex) - prop = SDOPackage.OrganizationProperty(self._orgProperty.properties) - return prop - - - ## - # @if jp - # - # @brief [CORBA interface] OrganizationProperty ͤμ - # - # OrganizationProperty λꤵ줿֤ͤڥ졼 - # "name" ǻꤵ줿ץѥƥ֤ͤ - # - # @param self - # @param name ֤ͤץѥƥ̾ - # - # @return "name" ǻꤵ줿ץѥƥ͡ - # - # @exception SDONotExists åȤSDO¸ߤʤ(㳰ϡCORBAɸ - # ƥ㳰OBJECT_NOT_EXIST˥ޥåԥ󥰤) - # @exception InvalidParameter "namne" ǻꤵ줿ץѥƥ - # ¸ߤʤ - # @exception NotAvailable SDO¸ߤ뤬ʤ - # @exception InternalError Ū顼ȯ - # @else - # - # @brief [CORBA interface] Get specified value of OrganizationProperty - # - # This operation returns a value in the OrganizationProperty. - # The value to be returned is specified by argument "name." - # - # @param self - # @param name The name of the value to be returned. - # - # @return The value of property which is specified by argument "name". - # - # @exception SDONotExists if the target SDO does not exist.(This exception - # is mapped to CORBA standard system exception - # OBJECT_NOT_EXIST.) - # @exception InvalidParameter If there are no Property stored with argument - # "name". - # @exception NotAvailable The target SDO is reachable but cannot respond. - # @exception InternalError The target SDO cannot execute the operation - # completely due to some internal error. - # @endif - def get_organization_property_value(self, name): - self.__rtcout.RTC_TRACE("get_organization_property_value(%s)", name) - if not name: - raise SDOPackage.InvalidParameter("Empty name.") - - index = OpenRTM_aist.CORBA_SeqUtil.find(self._orgProperty.properties, self.nv_name(name)) - - if index < 0: - raise SDOPackage.InvalidParameter("Not found.") - - try: - value = omniORB.any.to_any(self._orgProperty.properties[index].value) - return value - except: - self.__rtcout.RTC_ERROR(OpenRTM_aist.Logger.print_exception()) - raise SDOPackage.InternalError("get_organization_property_value()") - - - - - ## - # @if jp - # - # @brief [CORBA interface] OrganizationProperty Υå - # - # SDO Specification PIM Ҥȥڥ졼̾ۤʤ롣 - # addOrganizationProperty б
    - # OrganizationProperty Organization ɲä륪ڥ졼 - # OrganizationProperty Organization ΥץѥƥҤǤ롣 - # - # @param self - # @param org_property åȤ OrganizationProperty - # - # @return ڥ졼ɤ֤ - # - # @exception SDONotExists åȤSDO¸ߤʤ(㳰ϡCORBAɸ - # ƥ㳰OBJECT_NOT_EXIST˥ޥåԥ󥰤) - # @exception InvalidParameter "org_property" null - # @exception NotAvailable SDO¸ߤ뤬ʤ - # @exception InternalError Ū顼ȯ - # @else - # - # @brief [CORBA interface] Set OrganizationProperty - # - # This operation adds the OrganizationProperty to an Organization. The - # OrganizationProperty is the property description of an Organization. - # - # @param self - # @param org_property The type of organization to be added. - # - # @return If the operation was successfully completed. - # - # @exception SDONotExists if the target SDO does not exist.(This exception - # is mapped to CORBA standard system exception - # OBJECT_NOT_EXIST.) - # @exception InvalidParameter The argument "organizationProperty" is null. - # @exception NotAvailable The target SDO is reachable but cannot respond. - # @exception InternalError The target SDO cannot execute the operation - # completely due to some internal error. - # @endif - def add_organization_property(self, org_property): - self.__rtcout.RTC_TRACE("add_organization_property()") - if org_property is None: - raise SDOPackage.InvalidParameter("org_property is Empty.") - - - guard = OpenRTM_aist.ScopedLock(self._org_mutex) - self._orgProperty = org_property - return True - - - - - ## - # @if jp - # - # @brief [CORBA interface] OrganizationProperty ͤΥå - # - # OrganizationProperty NVList name value ΥåȤɲä⤷ - # 륪ڥ졼name value ϰ "name" "value" ˤ - # ꤹ롣 - # - # @param self - # @param name ɲáץѥƥ̾ - # @param value ɲáץѥƥ͡ - # - # @return ڥ졼ɤ֤ - # - # @exception SDONotExists åȤSDO¸ߤʤ(㳰ϡCORBAɸ - # ƥ㳰OBJECT_NOT_EXIST˥ޥåԥ󥰤) - # @exception InvalidParameter "name" ǻꤵ줿ץѥƥ - # ¸ߤʤ - # @exception NotAvailable SDO¸ߤ뤬ʤ - # @exception InternalError Ū顼ȯ - # @else - # - # @brief [CORBA interface] Set specified value of OrganizationProperty - # - # This operation adds or updates a pair of name and value as a property - # of Organization to/in NVList of the OrganizationProperty. The name and - # the value to be added/updated are specified by argument "name" and - # "value." - # - # @param self - # @param name The name of the property to be added/updated. - # @param value The value of the property to be added/updated. - # - # @return If the operation was successfully completed. - # - # @exception SDONotExists if the target SDO does not exist.(This exception - # is mapped to CORBA standard system exception - # OBJECT_NOT_EXIST.) - # @exception NotAvailable The target SDO is reachable but cannot respond. - # @exception InvalidParameter The property that is specified by argument - # "name" does not exist. - # @exception InternalError The target SDO cannot execute the operation - # completely due to some internal error. - # @endif - def set_organization_property_value(self, name, value): - self.__rtcout.RTC_TRACE("set_organization_property_value(name=%s)", name) - if not name: - raise SDOPackage.InvalidParameter("set_organization_property_value(): Enpty name.") - - index = OpenRTM_aist.CORBA_SeqUtil.find(self._orgProperty.properties, self.nv_name(name)) - - if index < 0: - nv = SDOPackage.NameValue(name, value) - OpenRTM_aist.CORBA_SeqUtil.push_back(self._orgProperty.properties, nv) - else: - self._orgProperty.properties[index].value = value - - return True - - - ## - # @if jp - # - # @brief [CORBA interface] OrganizationProperty κ - # - # OrganizationProperty NVList Υץѥƥ롣 - # ץѥƥ̾ϰ "name" ˤꤵ롣 - # - # @param self - # @param name ץѥƥ̾ - # - # @return ڥ졼ɤ֤ - # - # @exception SDONotExists åȤSDO¸ߤʤ(㳰ϡCORBAɸ - # ƥ㳰OBJECT_NOT_EXIST˥ޥåԥ󥰤) - # @exception InvalidParameter "name" ǻꤵ줿ץѥƥ - # ¸ߤʤ - # @exception NotAvailable SDO¸ߤ뤬ʤ - # @exception InternalError Ū顼ȯ - # @else - # - # @brief [CORBA interface] Remove specified OrganizationProperty - # - # This operation removes a property of Organization from NVList of the - # OrganizationProperty. The property to be removed is specified by - # argument "name." - # - # @param self - # @param name The name of the property to be removed. - # - # @return If the operation was successfully completed. - # - # @exception SDONotExists if the target SDO does not exist.(This exception - # is mapped to CORBA standard system exception - # OBJECT_NOT_EXIST.) - # @exception NotAvailable The target SDO is reachable but cannot respond. - # @exception InvalidParameter The property that is specified by argument - # "name" does not exist. - # @exception InternalError The target SDO cannot execute the operation - # completely due to some internal error. - # @endif - def remove_organization_property(self, name): - self.__rtcout.RTC_TRACE("remove_organization_property(%s)", name) - if not name: - raise SDOPackage.InvalidParameter("remove_organization_property_value(): Enpty name.") - - index = OpenRTM_aist.CORBA_SeqUtil.find(self._orgProperty.properties, self.nv_name(name)) - - if index < 0: - raise SDOPackage.InvalidParameter("remove_organization_property_value(): Not found.") - - - OpenRTM_aist.CORBA_SeqUtil.erase(self._orgProperty.properties, index) - return True - - - - ## - # @if jp - # - # @brief [CORBA interface] Organization Υʡ - # - # Organization ΥʡؤλȤ֤ - # - # @param self - # - # @return ʡ֥Ȥؤλȡ - # - # @exception SDONotExists åȤSDO¸ߤʤ(㳰ϡCORBAɸ - # ƥ㳰OBJECT_NOT_EXIST˥ޥåԥ󥰤) - # @exception NotAvailable SDO¸ߤ뤬ʤ - # @exception InternalError Ū顼ȯ - # @else - # - # @brief [CORBA interface] Get the owner of the SDO - # - # This operation returns the SDOSystemElement that is owner of - # the Organization. - # - # @param self - # - # @return Reference of owner object. - # - # @exception SDONotExists if the target SDO does not exist.(This exception - # is mapped to CORBA standard system exception - # OBJECT_NOT_EXIST.) - # @exception NotAvailable The target SDO is reachable but cannot respond. - # @exception InternalError The target SDO cannot execute the operation - # completely due to some internal error. - # @endif - def get_owner(self): - self.__rtcout.RTC_TRACE("get_owner()") - return self._varOwner - - - ## - # @if jp - # - # @brief [CORBA interface] Organization ˥ʡ򥻥åȤ - # - # Organization Ф SDOSystemElement 򥪡ʡȤƥåȤ롣 - # "sdo" ˥åȤ SDOSystemElement ꤹ롣 - # - # @param self - # @param sdo ʡ֥Ȥλȡ - # - # @return ڥ졼ɤ֤ - # - # @exception SDONotExists åȤSDO¸ߤʤ(㳰ϡCORBAɸ - # ƥ㳰OBJECT_NOT_EXIST˥ޥåԥ󥰤) - # @exception InvalidParameter "sdo" nullǤ롢⤷ϡ - # "sdo" ¸ߤʤ - # @exception NotAvailable SDO¸ߤ뤬ʤ - # @exception InternalError Ū顼ȯ - # @else - # - # @brief [CORBA interface] Set the orner of the Organization - # - # This operation sets an SDOSystemElement to the owner of the - # Organization. The SDOSystemElement to be set is specified by argument - # "sdo." - # - # @param self - # @param sdo Reference of owner object. - # - # @return If the operation was successfully completed. - # - # @exception SDONotExists if the target SDO does not exist.(This exception - # is mapped to CORBA standard system exception - # OBJECT_NOT_EXIST.) - # @exception NotAvailable The target SDO is reachable but cannot respond. - # @exception InvalidParameter The argument "sdo" is null, or the object - # that is specified by "sdo" in argument "sdo" does not exist. - # @exception InternalError The target SDO cannot execute the operation - # completely due to some internal error. - # @endif - def set_owner(self, sdo): - self.__rtcout.RTC_TRACE("set_owner()") - if CORBA.is_nil(sdo): - raise SDOPackage.InvalidParameter("set_owner(): sdo is nil") - - - self._varOwner = sdo - return True - - - - - - ## - # @if jp - # - # @brief [CORBA interface] Organization ΥС - # - # Organization ΥС SDO ΥꥹȤ֤ - # С¸ߤʤжΥꥹȤ֤ - # - # @param self - # - # @return Organization ˴ޤޤС SDO Υꥹȡ - # - # @exception SDONotExists åȤSDO¸ߤʤ(㳰ϡCORBAɸ - # ƥ㳰OBJECT_NOT_EXIST˥ޥåԥ󥰤) - # @exception NotAvailable SDO¸ߤ뤬ʤ - # @exception InternalError Ū顼ȯ - # @else - # - # @brief [CORBA interface] Get a menber list of the Organization - # - # This operation returns a list of SDOs that are members of an - # Organization. An empty list is returned if the Organization does not - # have any members. - # - # @param self - # - # @return Member SDOs that are contained in the Organization object. - # - # @exception SDONotExists if the target SDO does not exist.(This exception - # is mapped to CORBA standard system exception - # OBJECT_NOT_EXIST.) - # @exception NotAvailable The target SDO is reachable but cannot respond. - # @exception InternalError The target SDO cannot execute the operation - # completely due to some internal error. - # @endif - def get_members(self): - self.__rtcout.RTC_TRACE("get_members()") - - return self._memberList - - - - ## - # @if jp - # - # @brief [CORBA interface] SDO å - # - # SDO ΥꥹȤ Organization ΥСȤƥåȤ롣 - # Organization Ǥ˥С SDO Ƥϡ - # Ϳ줿 SDO ΥꥹȤ֤롣 - # - # @param self - # @param sdos С SDO - # - # @return ڥ졼ɤ֤ - # - # @exception SDONotExists åȤSDO¸ߤʤ(㳰ϡCORBAɸ - # ƥ㳰OBJECT_NOT_EXIST˥ޥåԥ󥰤) - # @exception InvalidParameter "SDOList" nullǤ롢⤷ - # ˻ꤵ줿 "SDOList" ¸ߤʤ - # @exception NotAvailable SDO¸ߤ뤬ʤ - # @exception InternalError Ū顼ȯ - # @else - # - # @brief [CORBA interface] Set SDO's ServiceProfile - # - # This operation assigns a list of SDOs to an Organization as its members. - # If the Organization has already maintained a member SDO(s) when it is - # called, the operation replaces the member(s) with specified list of - # SDOs. - # - # @param self - # @param sdos Member SDOs to be assigned. - # - # @return If the operation was successfully completed. - # - # @exception SDONotExists if the target SDO does not exist.(This exception - # is mapped to CORBA standard system exception - # OBJECT_NOT_EXIST.) - # @exception NotAvailable The target SDO is reachable but cannot respond. - # @exception InvalidParameter The argument "SDOList" is null, or if the - # object that is specified by the argument "sdos" does not - # exist. - # @exception InternalError The target SDO cannot execute the operation - # completely due to some internal error. - # @endif - def set_members(self, sdos): - self.__rtcout.RTC_TRACE("set_members()") - if sdos is None: - raise SDOPackage.InvalidParameter("set_members(): SDOList is empty.") - - - self._memberList = sdos - return True - - - - - - ## - # @if jp - # - # @brief [CORBA interface] SDO Сɲ - # - # Organization ˥СȤ SDO ɲä롣 - # "sdo" ɲäС SDO ꤹ롣 - # - # @param self - # @param sdo_list Organization ɲä SDO Υꥹȡ - # - # @return ڥ졼ɤ֤ - # - # @exception SDONotExists åȤSDO¸ߤʤ(㳰ϡCORBAɸ - # ƥ㳰OBJECT_NOT_EXIST˥ޥåԥ󥰤) - # @exception InvalidParameter "sdo" nullǤ롣 - # @exception NotAvailable SDO¸ߤ뤬ʤ - # @exception InternalError Ū顼ȯ - # @else - # - # @brief [CORBA interface] Add the menebr SDOs - # - # This operation adds a member that is an SDO to the organization. - # The member to be added is specified by argument "sdo." - # - # @param self - # @param sdo The member to be added to the organization. - # - # @return If the operation was successfully completed. - # - # @exception SDONotExists if the target SDO does not exist.(This exception - # is mapped to CORBA standard system exception - # OBJECT_NOT_EXIST.) - # @exception NotAvailable The target SDO is reachable but cannot respond. - # @exception InvalidParameter The argument "sdo" is null. - # @exception InternalError The target SDO cannot execute the operation - # completely due to some internal error. - # @endif - def add_members(self, sdo_list): - self.__rtcout.RTC_TRACE("add_members()") - if not sdo_list: - raise SDOPackage.InvalidParameter("add_members(): SDOList is empty.") - - try: - OpenRTM_aist.CORBA_SeqUtil.push_back_list(self._memberList, sdo_list) - return True - except: - self.__rtcout.RTC_ERROR(OpenRTM_aist.Logger.print_exception()) - raise SDOPackage.InternalError("add_members()") - - - - - ## - # @if jp - # - # @brief [CORBA interface] SDO Сκ - # - # Organization ǻꤵ줿 "id" SDO 롣 - # - # @param self - # @param id SDO id - # - # @return ڥ졼ɤ֤ - # - # @exception SDONotExists åȤSDO¸ߤʤ(㳰ϡCORBAɸ - # ƥ㳰OBJECT_NOT_EXIST˥ޥåԥ󥰤) - # @exception InvalidParameter "id" null ⤷¸ߤʤ - # @exception NotAvailable SDO¸ߤ뤬ʤ - # @exception InternalError Ū顼ȯ - # @else - # - # @brief [CORBA interface] Remove menber SDO from Organization - # - # This operation removes a member from the organization. The member to be - # removed is specified by argument "id." - # - # @param self - # @param id Id of the SDO to be removed from the organization. - # - # @return If the operation was successfully completed. - # - # @exception SDONotExists if the target SDO does not exist.(This exception - # is mapped to CORBA standard system exception - # OBJECT_NOT_EXIST.) - # @exception NotAvailable The target SDO is reachable but cannot respond. - # @exception InvalidParameter The argument "id" is null or does not exist. - # @exception InternalError The target SDO cannot execute the operation - # completely due to some internal error. - # @endif - def remove_member(self, id): - self.__rtcout.RTC_TRACE("remove_member(%s)", id) - if not id: - self.__rtcout.RTC_ERROR("remove_member(): Enpty name.") - raise SDOPackage.InvalidParameter("remove_member(): Empty name.") - - index = OpenRTM_aist.CORBA_SeqUtil.find(self._memberList, self.sdo_id(id)) - - if index < 0: - self.__rtcout.RTC_ERROR("remove_member(): Not found.") - raise SDOPackage.InvalidParameter("remove_member(): Not found.") - - - #try: - OpenRTM_aist.CORBA_SeqUtil.erase(self._memberList, index) - return True - #except: - # self.__rtcout.RTC_ERROR("unknown exception") - # raise SDOPackage.InternalError("remove_member(): Not found.") - - - - - ## - # @if jp - # - # @brief [CORBA interface] Organization DependencyType - # - # Organization δطɽ "DependencyType" ֤ - # - # @param self - # - # @return Organizaton ΰ¸ط DependencyType ֤ - # DependencyType OMG SDO ͤ Section 2.2.2 2-3 ڡ - # "Data Structures Used by Resource Data Model" 򻲾ȡ - # - # @exception SDONotExists åȤSDO¸ߤʤ(㳰ϡCORBAɸ - # ƥ㳰OBJECT_NOT_EXIST˥ޥåԥ󥰤) - # @exception NotAvailable SDO¸ߤ뤬ʤ - # @exception InternalError Ū顼ȯ - # @else - # - # @brief [CORBA interface] Get the DependencyType of the Organization - # - # This operation gets the relationship "DependencyType" of the - # Organization. - # - # @param self - # - # @return The relationship of the Organization as DependencyType. - # DependencyType is defined in Section 2.2.2, "Data Structures - # Used by Resource Data Model," on page 2-3 - # of OMG SDO Specification. - # - # @exception SDONotExists if the target SDO does not exist.(This exception - # is mapped to CORBA standard system exception - # OBJECT_NOT_EXIST.) - # @exception NotAvailable The target SDO is reachable but cannot respond. - # @exception InternalError The target SDO cannot execute the operation - # completely due to some internal error. - # @endif - def get_dependency(self): - self.__rtcout.RTC_TRACE("get_dependency()") - return self._dependency - - - ## - # @if jp - # - # @brief [CORBA interface] Organization DependencyType 򥻥åȤ - # - # Organization ΰ¸ط "DependencyType" 򥻥åȤ롣 - # "dependencty" ˤ¸طͿ롣 - # - # @param self - # @param dependency Organization ΰ¸طɽ DependencyType - # DependencyType OMG SDO ͤ Section 2.2.22-3 ڡ - # "Data Structures Used by Resource Data Model" 򻲾ȡ - # - # @return ڥ졼ɤ֤ - # - # @exception SDONotExists åȤSDO¸ߤʤ(㳰ϡCORBAɸ - # ƥ㳰OBJECT_NOT_EXIST˥ޥåԥ󥰤) - # @exception InvalidParameter "sProfile" nullǤ롣 - # @exception NotAvailable SDO¸ߤ뤬ʤ - # @exception InternalError Ū顼ȯ - # @else - # - # @brief [CORBA interface] Set the DependencyType of the Organization - # - # This operation sets the relationship "DependencyType" of the - # Organization. The value to be set is specified by argument "dependency." - # - # @param self - # @param dependency The relationship of the Organization as - # DependencyType. DependencyType is defined in Section - # 2.2.2, "Data Structures Used by Resource Data Model," - # on page 2-3. - # - # @return If the operation was successfully completed. - # - # @exception SDONotExists if the target SDO does not exist.(This exception - # is mapped to CORBA standard system exception - # OBJECT_NOT_EXIST.) - # @exception NotAvailable The target SDO is reachable but cannot respond. - # @exception InvalidParameter The argument "dependency" is null. - # @exception InternalError The target SDO cannot execute the operation - # completely due to some internal error. - # @endif - def set_dependency(self, dependency): - self.__rtcout.RTC_TRACE("set_dependency()") - if dependency is None: - raise SDOPackage.InvalidParameter("set_dependency(): Empty dependency.") - - - self._dependency = dependency - return True - - - - - def getObjRef(self): - return self._objref - - - - # end of CORBA interface definition - #============================================================ - - - ## - # @if jp - # @class nv_name - # @brief NVListfunctor - # @else - # - # @endif - class nv_name: - def __init__(self, name): - self._name = name - - def __call__(self, nv): - return str(self._name) == str(nv.name) - - ## - # @if jp - # @class sdo_id - # @brief SDOfunctor - # @else - # - # @endif - class sdo_id: - def __init__(self, id_): - self._id = id_ - - def __call__(self, sdo): - id_ = sdo.get_sdo_id() - return str(self._id) == str(id_) - + """ + """ + + ## + # @if jp + # + # @brief コンストラクタ + # + # コンストラクタ + # + # @else + # + # @endif + def __init__(self, sdo): + self._pId = str(OpenRTM_aist.uuid1()) + self._org_mutex = threading.RLock() + + self._orgProperty = SDOPackage.OrganizationProperty([]) + self._varOwner = sdo + self._memberList = [] + self._dependency = SDOPackage.OWN + self._objref = self._this() + self.__rtcout = OpenRTM_aist.Manager.instance( + ).getLogbuf("rtobject.sdo_organization") + + # ============================================================ + # + # <<< CORBA interfaces >>> + # + # ============================================================ + ## + # @if jp + # + # @brief [CORBA interface] Organization ID を取得する + # + # Organization の ID を返すオペレーション。 + # + # @param self + # + # @return Resource Data Model で定義された Organization ID。 + # + # @exception SDONotExists ターゲットのSDOが存在しない。(本例外は、CORBA標準 + # システム例外のOBJECT_NOT_EXISTにマッピングされる) + # @exception NotAvailable SDOは存在するが応答がない。 + # @exception InternalError 内部的エラーが発生した。 + # @else + # + # @brief [CORBA interface] Get Organization Id + # + # This operation returns the 'id' of the Organization. + # + # @param self + # + # @return The id of the Organization defined in the resource data model. + # + # @exception SDONotExists if the target SDO does not exist.(This exception + # is mapped to CORBA standard system exception + # OBJECT_NOT_EXIST.) + # @exception NotAvailable The target SDO is reachable but cannot respond. + # @exception InternalError The target SDO cannot execute the operation + # completely due to some internal error. + # @endif + + def get_organization_id(self): + self.__rtcout.RTC_TRACE("get_organization_id() = %s", self._pId) + return self._pId + + ## + # @if jp + # + # @brief [CORBA interface] OrganizationProperty の取得 + # + # Organization が所有する OrganizationProperty を返すオペレーション。 + # Organization がプロパティを持たなければ空のリストを返す。 + # + # @param self + # + # @return Organization のプロパティのリスト。 + # + # @exception SDONotExists ターゲットのSDOが存在しない。(本例外は、CORBA標準 + # システム例外のOBJECT_NOT_EXISTにマッピングされる) + # @exception NotAvailable SDOは存在するが応答がない。 + # @exception InternalError 内部的エラーが発生した。 + # @else + # + # @brief [CORBA interface] Get OrganizationProperty + # + # This operation returns the OrganizationProperty that an Organization + # has. An empty OrganizationProperty is returned if the Organization does + # not have any properties. + # + # @param self + # + # @return The list with properties of the organization. + # + # @exception SDONotExists if the target SDO does not exist.(This exception + # is mapped to CORBA standard system exception + # OBJECT_NOT_EXIST.) + # @exception NotAvailable The target SDO is reachable but cannot respond. + # @exception InternalError The target SDO cannot execute the operation + # completely due to some internal error. + # @endif + + def get_organization_property(self): + self.__rtcout.RTC_TRACE("get_organization_property()") + guard = OpenRTM_aist.ScopedLock(self._org_mutex) + prop = SDOPackage.OrganizationProperty(self._orgProperty.properties) + return prop + + ## + # @if jp + # + # @brief [CORBA interface] OrganizationProperty の特定の値の取得 + # + # OrganizationProperty の指定された値を返すオペレーション。 + # 引数 "name" で指定されたプロパティの値を返す。 + # + # @param self + # @param name 値を返すプロパティの名前。 + # + # @return 引数 "name" で指定されたプロパティの値。 + # + # @exception SDONotExists ターゲットのSDOが存在しない。(本例外は、CORBA標準 + # システム例外のOBJECT_NOT_EXISTにマッピングされる) + # @exception InvalidParameter 引数 "namne" で指定されたプロパティが + # 存在しない。 + # @exception NotAvailable SDOは存在するが応答がない。 + # @exception InternalError 内部的エラーが発生した。 + # @else + # + # @brief [CORBA interface] Get specified value of OrganizationProperty + # + # This operation returns a value in the OrganizationProperty. + # The value to be returned is specified by argument "name." + # + # @param self + # @param name The name of the value to be returned. + # + # @return The value of property which is specified by argument "name". + # + # @exception SDONotExists if the target SDO does not exist.(This exception + # is mapped to CORBA standard system exception + # OBJECT_NOT_EXIST.) + # @exception InvalidParameter If there are no Property stored with argument + # "name". + # @exception NotAvailable The target SDO is reachable but cannot respond. + # @exception InternalError The target SDO cannot execute the operation + # completely due to some internal error. + # @endif + + def get_organization_property_value(self, name): + self.__rtcout.RTC_TRACE("get_organization_property_value(%s)", name) + if not name: + raise SDOPackage.InvalidParameter("Empty name.") + + index = OpenRTM_aist.CORBA_SeqUtil.find( + self._orgProperty.properties, self.nv_name(name)) + + if index < 0: + raise SDOPackage.InvalidParameter("Not found.") + + try: + value = omniORB.any.to_any( + self._orgProperty.properties[index].value) + return value + except BaseException: + self.__rtcout.RTC_ERROR(OpenRTM_aist.Logger.print_exception()) + raise SDOPackage.InternalError("get_organization_property_value()") + + ## + # @if jp + # + # @brief [CORBA interface] OrganizationProperty のセット + # + # ※ SDO Specification の PIM 記述とオペレーション名が異なる。 + # ※ addOrganizationProperty に対応か?
    + # OrganizationProperty を Organization に追加するオペレーション。 + # OrganizationProperty は Organization のプロパティ記述である。 + # + # @param self + # @param org_property セットする OrganizationProperty + # + # @return オペレーションが成功したかどうかを返す。 + # + # @exception SDONotExists ターゲットのSDOが存在しない。(本例外は、CORBA標準 + # システム例外のOBJECT_NOT_EXISTにマッピングされる) + # @exception InvalidParameter "org_property" が null。 + # @exception NotAvailable SDOは存在するが応答がない。 + # @exception InternalError 内部的エラーが発生した。 + # @else + # + # @brief [CORBA interface] Set OrganizationProperty + # + # This operation adds the OrganizationProperty to an Organization. The + # OrganizationProperty is the property description of an Organization. + # + # @param self + # @param org_property The type of organization to be added. + # + # @return If the operation was successfully completed. + # + # @exception SDONotExists if the target SDO does not exist.(This exception + # is mapped to CORBA standard system exception + # OBJECT_NOT_EXIST.) + # @exception InvalidParameter The argument "organizationProperty" is null. + # @exception NotAvailable The target SDO is reachable but cannot respond. + # @exception InternalError The target SDO cannot execute the operation + # completely due to some internal error. + # @endif + + def add_organization_property(self, org_property): + self.__rtcout.RTC_TRACE("add_organization_property()") + if org_property is None: + raise SDOPackage.InvalidParameter("org_property is Empty.") + + guard = OpenRTM_aist.ScopedLock(self._org_mutex) + self._orgProperty = org_property + return True + + ## + # @if jp + # + # @brief [CORBA interface] OrganizationProperty の値のセット + # + # OrganizationProperty の NVList に name と value のセットを追加もしくは + # 更新するオペレーション。name と value は引数 "name" と "value" により + # 指定する。 + # + # @param self + # @param name 追加・更新されるプロパティの名前。 + # @param value 追加・更新されるプロパティの値。 + # + # @return オペレーションが成功したかどうかを返す。 + # + # @exception SDONotExists ターゲットのSDOが存在しない。(本例外は、CORBA標準 + # システム例外のOBJECT_NOT_EXISTにマッピングされる) + # @exception InvalidParameter 引数 "name" で指定されたプロパティは + # 存在しない。 + # @exception NotAvailable SDOは存在するが応答がない。 + # @exception InternalError 内部的エラーが発生した。 + # @else + # + # @brief [CORBA interface] Set specified value of OrganizationProperty + # + # This operation adds or updates a pair of name and value as a property + # of Organization to/in NVList of the OrganizationProperty. The name and + # the value to be added/updated are specified by argument "name" and + # "value." + # + # @param self + # @param name The name of the property to be added/updated. + # @param value The value of the property to be added/updated. + # + # @return If the operation was successfully completed. + # + # @exception SDONotExists if the target SDO does not exist.(This exception + # is mapped to CORBA standard system exception + # OBJECT_NOT_EXIST.) + # @exception NotAvailable The target SDO is reachable but cannot respond. + # @exception InvalidParameter The property that is specified by argument + # "name" does not exist. + # @exception InternalError The target SDO cannot execute the operation + # completely due to some internal error. + # @endif + + def set_organization_property_value(self, name, value): + self.__rtcout.RTC_TRACE( + "set_organization_property_value(name=%s)", name) + if not name: + raise SDOPackage.InvalidParameter( + "set_organization_property_value(): Enpty name.") + + index = OpenRTM_aist.CORBA_SeqUtil.find( + self._orgProperty.properties, self.nv_name(name)) + + if index < 0: + nv = SDOPackage.NameValue(name, value) + OpenRTM_aist.CORBA_SeqUtil.push_back( + self._orgProperty.properties, nv) + else: + self._orgProperty.properties[index].value = value + + return True + + ## + # @if jp + # + # @brief [CORBA interface] OrganizationProperty の削除 + # + # OrganizationProperty の NVList から特定のプロパティを削除する。 + # 削除されるプロパティの名前は引数 "name" により指定される。 + # + # @param self + # @param name 削除するプロパティの名前。 + # + # @return オペレーションが成功したかどうかを返す。 + # + # @exception SDONotExists ターゲットのSDOが存在しない。(本例外は、CORBA標準 + # システム例外のOBJECT_NOT_EXISTにマッピングされる) + # @exception InvalidParameter 引数 "name" で指定されたプロパティは + # 存在しない。 + # @exception NotAvailable SDOは存在するが応答がない。 + # @exception InternalError 内部的エラーが発生した。 + # @else + # + # @brief [CORBA interface] Remove specified OrganizationProperty + # + # This operation removes a property of Organization from NVList of the + # OrganizationProperty. The property to be removed is specified by + # argument "name." + # + # @param self + # @param name The name of the property to be removed. + # + # @return If the operation was successfully completed. + # + # @exception SDONotExists if the target SDO does not exist.(This exception + # is mapped to CORBA standard system exception + # OBJECT_NOT_EXIST.) + # @exception NotAvailable The target SDO is reachable but cannot respond. + # @exception InvalidParameter The property that is specified by argument + # "name" does not exist. + # @exception InternalError The target SDO cannot execute the operation + # completely due to some internal error. + # @endif + + def remove_organization_property(self, name): + self.__rtcout.RTC_TRACE("remove_organization_property(%s)", name) + if not name: + raise SDOPackage.InvalidParameter( + "remove_organization_property_value(): Enpty name.") + + index = OpenRTM_aist.CORBA_SeqUtil.find( + self._orgProperty.properties, self.nv_name(name)) + + if index < 0: + raise SDOPackage.InvalidParameter( + "remove_organization_property_value(): Not found.") + + OpenRTM_aist.CORBA_SeqUtil.erase(self._orgProperty.properties, index) + return True + + ## + # @if jp + # + # @brief [CORBA interface] Organization のオーナーを取得する + # + # この Organization のオーナーへの参照を返す。 + # + # @param self + # + # @return オーナーオブジェクトへの参照。 + # + # @exception SDONotExists ターゲットのSDOが存在しない。(本例外は、CORBA標準 + # システム例外のOBJECT_NOT_EXISTにマッピングされる) + # @exception NotAvailable SDOは存在するが応答がない。 + # @exception InternalError 内部的エラーが発生した。 + # @else + # + # @brief [CORBA interface] Get the owner of the SDO + # + # This operation returns the SDOSystemElement that is owner of + # the Organization. + # + # @param self + # + # @return Reference of owner object. + # + # @exception SDONotExists if the target SDO does not exist.(This exception + # is mapped to CORBA standard system exception + # OBJECT_NOT_EXIST.) + # @exception NotAvailable The target SDO is reachable but cannot respond. + # @exception InternalError The target SDO cannot execute the operation + # completely due to some internal error. + # @endif + + def get_owner(self): + self.__rtcout.RTC_TRACE("get_owner()") + return self._varOwner + + ## + # @if jp + # + # @brief [CORBA interface] Organization にオーナーをセットする + # + # Organization に対して SDOSystemElement をオーナーとしてセットする。 + # 引数 "sdo" にセットする SDOSystemElement を指定する。 + # + # @param self + # @param sdo オーナーオブジェクトの参照。 + # + # @return オペレーションが成功したかどうかを返す。 + # + # @exception SDONotExists ターゲットのSDOが存在しない。(本例外は、CORBA標準 + # システム例外のOBJECT_NOT_EXISTにマッピングされる) + # @exception InvalidParameter 引数 "sdo" が nullである、もしくは、 + # "sdo" が存在しない。 + # @exception NotAvailable SDOは存在するが応答がない。 + # @exception InternalError 内部的エラーが発生した。 + # @else + # + # @brief [CORBA interface] Set the orner of the Organization + # + # This operation sets an SDOSystemElement to the owner of the + # Organization. The SDOSystemElement to be set is specified by argument + # "sdo." + # + # @param self + # @param sdo Reference of owner object. + # + # @return If the operation was successfully completed. + # + # @exception SDONotExists if the target SDO does not exist.(This exception + # is mapped to CORBA standard system exception + # OBJECT_NOT_EXIST.) + # @exception NotAvailable The target SDO is reachable but cannot respond. + # @exception InvalidParameter The argument "sdo" is null, or the object + # that is specified by "sdo" in argument "sdo" does not exist. + # @exception InternalError The target SDO cannot execute the operation + # completely due to some internal error. + # @endif + + def set_owner(self, sdo): + self.__rtcout.RTC_TRACE("set_owner()") + if CORBA.is_nil(sdo): + raise SDOPackage.InvalidParameter("set_owner(): sdo is nil") + + self._varOwner = sdo + return True + + ## + # @if jp + # + # @brief [CORBA interface] Organization のメンバーを取得する + # + # Organization のメンバーの SDO のリストを返す。 + # メンバーが存在しなければ空のリストを返す。 + # + # @param self + # + # @return Organization に含まれるメンバー SDO のリスト。 + # + # @exception SDONotExists ターゲットのSDOが存在しない。(本例外は、CORBA標準 + # システム例外のOBJECT_NOT_EXISTにマッピングされる) + # @exception NotAvailable SDOは存在するが応答がない。 + # @exception InternalError 内部的エラーが発生した。 + # @else + # + # @brief [CORBA interface] Get a menber list of the Organization + # + # This operation returns a list of SDOs that are members of an + # Organization. An empty list is returned if the Organization does not + # have any members. + # + # @param self + # + # @return Member SDOs that are contained in the Organization object. + # + # @exception SDONotExists if the target SDO does not exist.(This exception + # is mapped to CORBA standard system exception + # OBJECT_NOT_EXIST.) + # @exception NotAvailable The target SDO is reachable but cannot respond. + # @exception InternalError The target SDO cannot execute the operation + # completely due to some internal error. + # @endif + + def get_members(self): + self.__rtcout.RTC_TRACE("get_members()") + + return self._memberList + + ## + # @if jp + # + # @brief [CORBA interface] SDO の セット + # + # SDO のリストを Organization のメンバーとしてセットする。 + # Organization がすでにメンバーの SDO を管理している場合は、 + # 与えられた SDO のリストに置き換える。 + # + # @param self + # @param sdos メンバーの SDO。 + # + # @return オペレーションが成功したかどうかを返す。 + # + # @exception SDONotExists ターゲットのSDOが存在しない。(本例外は、CORBA標準 + # システム例外のOBJECT_NOT_EXISTにマッピングされる) + # @exception InvalidParameter 引数 "SDOList" が nullである、もしくは + # 引数に指定された "SDOList" が存在しない。 + # @exception NotAvailable SDOは存在するが応答がない。 + # @exception InternalError 内部的エラーが発生した。 + # @else + # + # @brief [CORBA interface] Set SDO's ServiceProfile + # + # This operation assigns a list of SDOs to an Organization as its members. + # If the Organization has already maintained a member SDO(s) when it is + # called, the operation replaces the member(s) with specified list of + # SDOs. + # + # @param self + # @param sdos Member SDOs to be assigned. + # + # @return If the operation was successfully completed. + # + # @exception SDONotExists if the target SDO does not exist.(This exception + # is mapped to CORBA standard system exception + # OBJECT_NOT_EXIST.) + # @exception NotAvailable The target SDO is reachable but cannot respond. + # @exception InvalidParameter The argument "SDOList" is null, or if the + # object that is specified by the argument "sdos" does not + # exist. + # @exception InternalError The target SDO cannot execute the operation + # completely due to some internal error. + # @endif + + def set_members(self, sdos): + self.__rtcout.RTC_TRACE("set_members()") + if sdos is None: + raise SDOPackage.InvalidParameter( + "set_members(): SDOList is empty.") + + self._memberList = sdos + return True + + ## + # @if jp + # + # @brief [CORBA interface] SDO メンバーの追加 + # + # Organization にメンバーとして SDO を追加する。 + # 引数 "sdo" に追加するメンバー SDO を指定する。 + # + # @param self + # @param sdo_list Organization に追加される SDO のリスト。 + # + # @return オペレーションが成功したかどうかを返す。 + # + # @exception SDONotExists ターゲットのSDOが存在しない。(本例外は、CORBA標準 + # システム例外のOBJECT_NOT_EXISTにマッピングされる) + # @exception InvalidParameter 引数 "sdo" が nullである。 + # @exception NotAvailable SDOは存在するが応答がない。 + # @exception InternalError 内部的エラーが発生した。 + # @else + # + # @brief [CORBA interface] Add the menebr SDOs + # + # This operation adds a member that is an SDO to the organization. + # The member to be added is specified by argument "sdo." + # + # @param self + # @param sdo The member to be added to the organization. + # + # @return If the operation was successfully completed. + # + # @exception SDONotExists if the target SDO does not exist.(This exception + # is mapped to CORBA standard system exception + # OBJECT_NOT_EXIST.) + # @exception NotAvailable The target SDO is reachable but cannot respond. + # @exception InvalidParameter The argument "sdo" is null. + # @exception InternalError The target SDO cannot execute the operation + # completely due to some internal error. + # @endif + + def add_members(self, sdo_list): + self.__rtcout.RTC_TRACE("add_members()") + if not sdo_list: + raise SDOPackage.InvalidParameter( + "add_members(): SDOList is empty.") + + try: + OpenRTM_aist.CORBA_SeqUtil.push_back_list( + self._memberList, sdo_list) + return True + except BaseException: + self.__rtcout.RTC_ERROR(OpenRTM_aist.Logger.print_exception()) + raise SDOPackage.InternalError("add_members()") + + ## + # @if jp + # + # @brief [CORBA interface] SDO メンバーの削除 + # + # Organization から引数で指定された "id" の SDO を削除する。 + # + # @param self + # @param id 削除する SDO の id。 + # + # @return オペレーションが成功したかどうかを返す。 + # + # @exception SDONotExists ターゲットのSDOが存在しない。(本例外は、CORBA標準 + # システム例外のOBJECT_NOT_EXISTにマッピングされる) + # @exception InvalidParameter 引数 "id" が null もしくは存在しない。 + # @exception NotAvailable SDOは存在するが応答がない。 + # @exception InternalError 内部的エラーが発生した。 + # @else + # + # @brief [CORBA interface] Remove menber SDO from Organization + # + # This operation removes a member from the organization. The member to be + # removed is specified by argument "id." + # + # @param self + # @param id Id of the SDO to be removed from the organization. + # + # @return If the operation was successfully completed. + # + # @exception SDONotExists if the target SDO does not exist.(This exception + # is mapped to CORBA standard system exception + # OBJECT_NOT_EXIST.) + # @exception NotAvailable The target SDO is reachable but cannot respond. + # @exception InvalidParameter The argument "id" is null or does not exist. + # @exception InternalError The target SDO cannot execute the operation + # completely due to some internal error. + # @endif + + def remove_member(self, id): + self.__rtcout.RTC_TRACE("remove_member(%s)", id) + if not id: + self.__rtcout.RTC_ERROR("remove_member(): Enpty name.") + raise SDOPackage.InvalidParameter("remove_member(): Empty name.") + + index = OpenRTM_aist.CORBA_SeqUtil.find( + self._memberList, self.sdo_id(id)) + + if index < 0: + self.__rtcout.RTC_ERROR("remove_member(): Not found.") + raise SDOPackage.InvalidParameter("remove_member(): Not found.") + + # try: + OpenRTM_aist.CORBA_SeqUtil.erase(self._memberList, index) + return True + # except: + # self.__rtcout.RTC_ERROR("unknown exception") + # raise SDOPackage.InternalError("remove_member(): Not found.") + + ## + # @if jp + # + # @brief [CORBA interface] Organization の DependencyType を取得 + # + # Organization の関係を表す "DependencyType" を返す。 + # + # @param self + # + # @return Organizaton の依存関係 DependencyType を返す。 + # DependencyType は OMG SDO 仕様の Section 2.2.2 2-3 ページの + # "Data Structures Used by Resource Data Model" を参照。 + # + # @exception SDONotExists ターゲットのSDOが存在しない。(本例外は、CORBA標準 + # システム例外のOBJECT_NOT_EXISTにマッピングされる) + # @exception NotAvailable SDOは存在するが応答がない。 + # @exception InternalError 内部的エラーが発生した。 + # @else + # + # @brief [CORBA interface] Get the DependencyType of the Organization + # + # This operation gets the relationship "DependencyType" of the + # Organization. + # + # @param self + # + # @return The relationship of the Organization as DependencyType. + # DependencyType is defined in Section 2.2.2, "Data Structures + # Used by Resource Data Model," on page 2-3 + # of OMG SDO Specification. + # + # @exception SDONotExists if the target SDO does not exist.(This exception + # is mapped to CORBA standard system exception + # OBJECT_NOT_EXIST.) + # @exception NotAvailable The target SDO is reachable but cannot respond. + # @exception InternalError The target SDO cannot execute the operation + # completely due to some internal error. + # @endif + + def get_dependency(self): + self.__rtcout.RTC_TRACE("get_dependency()") + return self._dependency + + ## + # @if jp + # + # @brief [CORBA interface] Organization の DependencyType をセットする + # + # Organization の依存関係 "DependencyType" をセットする。 + # 引数 "dependencty" により依存関係を与える。 + # + # @param self + # @param dependency Organization の依存関係を表す DependencyType。 + # DependencyType は OMG SDO 仕様の Section 2.2.2、2-3 ページの + # "Data Structures Used by Resource Data Model" を参照。 + # + # @return オペレーションが成功したかどうかを返す。 + # + # @exception SDONotExists ターゲットのSDOが存在しない。(本例外は、CORBA標準 + # システム例外のOBJECT_NOT_EXISTにマッピングされる) + # @exception InvalidParameter 引数 "sProfile" が nullである。 + # @exception NotAvailable SDOは存在するが応答がない。 + # @exception InternalError 内部的エラーが発生した。 + # @else + # + # @brief [CORBA interface] Set the DependencyType of the Organization + # + # This operation sets the relationship "DependencyType" of the + # Organization. The value to be set is specified by argument "dependency." + # + # @param self + # @param dependency The relationship of the Organization as + # DependencyType. DependencyType is defined in Section + # 2.2.2, "Data Structures Used by Resource Data Model," + # on page 2-3. + # + # @return If the operation was successfully completed. + # + # @exception SDONotExists if the target SDO does not exist.(This exception + # is mapped to CORBA standard system exception + # OBJECT_NOT_EXIST.) + # @exception NotAvailable The target SDO is reachable but cannot respond. + # @exception InvalidParameter The argument "dependency" is null. + # @exception InternalError The target SDO cannot execute the operation + # completely due to some internal error. + # @endif + + def set_dependency(self, dependency): + self.__rtcout.RTC_TRACE("set_dependency()") + if dependency is None: + raise SDOPackage.InvalidParameter( + "set_dependency(): Empty dependency.") + + self._dependency = dependency + return True + + def getObjRef(self): + return self._objref + + # end of CORBA interface definition + # ============================================================ + + ## + # @if jp + # @class nv_name + # @brief NVList検索用functor + # @else + # + # @endif + + class nv_name: + def __init__(self, name): + self._name = name + + def __call__(self, nv): + return str(self._name) == str(nv.name) + + ## + # @if jp + # @class sdo_id + # @brief SDO検索用functor + # @else + # + # @endif + class sdo_id: + def __init__(self, id_): + self._id = id_ + + def __call__(self, sdo): + id_ = sdo.get_sdo_id() + return str(self._id) == str(id_) diff --git a/OpenRTM_aist/SdoService.py b/OpenRTM_aist/SdoService.py index 3c543940..b3a5f92c 100644 --- a/OpenRTM_aist/SdoService.py +++ b/OpenRTM_aist/SdoService.py @@ -1,29 +1,28 @@ #!/usr/bin/env python -# -*- coding: euc-jp -*- +# -*- coding: utf-8 -*- ## # @file SdoService.py # @brief SDO Service administration class # @date $Date: 2007/09/12 $ # @author Noriaki Ando and Shinji Kurihara -# +# # Copyright (C) 2006-2008 # Task-intelligence Research Group, # Intelligent Systems Research Institute, # National Institute of # Advanced Industrial Science and Technology (AIST), Japan # All rights reserved. -# - +# ## # @if jp # # @class SDOServiceProfile -# @brief SDO Service Profile饹 +# @brief SDO Service Profileクラス # -# SDO Service Profile SDO Service ξݻ뤿Υ饹Ǥ롣 +# SDO Service Profile は SDO Service の情報を保持するためのクラスである。 # # @since 0.4.0 # @@ -36,222 +35,219 @@ # # @endif class SDOServiceProfile: - """ - """ - - ## - # @if jp - # - # @brief 󥹥ȥ饯 - # - # 󥹥ȥ饯 - # - # @param self - # @param id_ Service ID(ǥե:None) - # @param type_ Service η(ǥե:None) - # - # @else - # - # @endif - def __init__(self, id_=None, type_=None): - if id_ is None: - self.id = "" - else: - self.id = id_ - - if type_ is None: - self.type = "" - else: - self.type = type_ - - self.interfaceType = "" - self.idlDefinition = "" - self.properties = [] - self.serviceRef = None - - - ## - # @if jp - # - # @brief Service Profile - # - # Service Profile - # - # @param self - # - # @return Service Profile - # - # @else - # - # @endif - def getProfile(self): - return self - - - ## - # @if jp - # @brief ServiceProfile.id 򥻥åȤ - # - # SDO Service ID򥻥åȤ - # - # @param self - # @param id_ Service ID - # - # @else - # @brief Setting ServiceProfile.id - # @endif - def setName(self, id_): - self.id = id_ - - - ## - # @if jp - # @brief ServiceProfile.id - # - # SDO Service ID - # - # @param self - # - # @return Service ID - # - # @else - # @brief Getting ServiceProfile.id - # @endif - def getName(self): - return self.id - - - ## - # @if jp - # @brief SDO ServiceProfile.interfaceType 򥻥åȤ - # - # SDO Service interfaceType򥻥åȤ - # - # @param self - # @param interfaceType Service interfaceType - # - # @else - # @brief Setting SDOServiceProfile.interfaceType - # @endif - def setInterfaceType(self, interfaceType): - self.interfaceType = interfaceType - - - - # @if jp - # @brief SDO ServiceProfile.interfaceType - # - # SDO Service interfaceType - # - # @param self - # - # @return Service interfaceType - # - # @else - # @brief Getting SDOServiceProfile.interfaceType - # @endif - def getInterfaceType(self): - return self.interfaceType - - - ## - # @if jp - # @brief SDO ServiceProfile.idlDefinition 򥻥åȤ - # - # SDO Service idlDefinition򥻥åȤ - # - # @param self - # @param idlDefinition Service idlDefinition - # - # @else - # @brief Setting SDOServiceProfile.idlDefnition - # @endif - def setIdlDefinition(self, idlDefinition): - self.idlDefinition = idlDefinition - - - ## - # @if jp - # @brief SDO ServiceProfile.idlDefinition - # - # SDO Service idlDefinition - # - # @param self - # - # @return Service idlDefinition - # - # @else - # @brief Getting SDO ServiceProfile.idlDefnition - # @endif - def getIdlDefinition(self): - return self.idlDefinition - - - ## - # @if jp - # @brief SDO ServiceProfile.properties 򥻥åȤ - # - # SDO Service properties򥻥åȤ - # - # @param self - # @param properties Service properties - # - # @else - # @brief Setting SDO ServiceProfile.properties - # @endif - def setProperties(self, properties): - self.properties = properties - - - ## - # @if jp - # @brief SDO ServiceProfile.properties - # - # SDO Service properties - # - # @param self - # - # @return Service properties - # - # @else - # @brief Getting SDO ServiceProfile.properties - # @endif - def getProperties(self): - return self.properties - - - # bool addProperty(char name, CORBA::Any data); - - - ## - # @if jp - # @brief SDO ServiceProfile.serviceRef 򥻥åȤ - # - # SDO Service serviceRef򥻥åȤ - # - # @param self - # @param serviceRef Serviceؤλ - # - # @else - # @brief Setting SDO ServiceProfile.serviceRef - # @endif - def setServiceRef(self, serviceRef): - self.serviceRef = serviceRef - - - ## - # @if jp - # @brief SDO ServiceProfile.serviceRef - # - # SDO Service ؤλȤ - # - # @param self - # - # @return Serviceؤλ - # - # @else - # @brief Getting SDO ServiceProfile.serviceRef - # @endif - def getServiceRef(self): - return self.serviceRef - + """ + """ + + ## + # @if jp + # + # @brief コンストラクタ + # + # コンストラクタ + # + # @param self + # @param id_ Service のID(デフォルト値:None) + # @param type_ Service の型(デフォルト値:None) + # + # @else + # + # @endif + def __init__(self, id_=None, type_=None): + if id_ is None: + self.id = "" + else: + self.id = id_ + + if type_ is None: + self.type = "" + else: + self.type = type_ + + self.interfaceType = "" + self.idlDefinition = "" + self.properties = [] + self.serviceRef = None + + ## + # @if jp + # + # @brief Service Profileを取得する + # + # Service Profileを取得する + # + # @param self + # + # @return Service Profile + # + # @else + # + # @endif + + def getProfile(self): + return self + + ## + # @if jp + # @brief ServiceProfile.id をセットする + # + # SDO Service のIDをセットする + # + # @param self + # @param id_ Service のID + # + # @else + # @brief Setting ServiceProfile.id + # @endif + + def setName(self, id_): + self.id = id_ + + ## + # @if jp + # @brief ServiceProfile.id を取得 + # + # SDO Service のIDを取得する + # + # @param self + # + # @return Service のID + # + # @else + # @brief Getting ServiceProfile.id + # @endif + + def getName(self): + return self.id + + ## + # @if jp + # @brief SDO ServiceProfile.interfaceType をセットする + # + # SDO Service のinterfaceTypeをセットする + # + # @param self + # @param interfaceType Service のinterfaceType + # + # @else + # @brief Setting SDOServiceProfile.interfaceType + # @endif + + def setInterfaceType(self, interfaceType): + self.interfaceType = interfaceType + + # @if jp + # @brief SDO ServiceProfile.interfaceType を取得する + # + # SDO Service のinterfaceTypeを取得する + # + # @param self + # + # @return Service のinterfaceType + # + # @else + # @brief Getting SDOServiceProfile.interfaceType + # @endif + + def getInterfaceType(self): + return self.interfaceType + + ## + # @if jp + # @brief SDO ServiceProfile.idlDefinition をセットする + # + # SDO Service のidlDefinitionをセットする + # + # @param self + # @param idlDefinition Service のidlDefinition + # + # @else + # @brief Setting SDOServiceProfile.idlDefnition + # @endif + + def setIdlDefinition(self, idlDefinition): + self.idlDefinition = idlDefinition + + ## + # @if jp + # @brief SDO ServiceProfile.idlDefinition を取得する + # + # SDO Service のidlDefinitionを取得する + # + # @param self + # + # @return Service のidlDefinition + # + # @else + # @brief Getting SDO ServiceProfile.idlDefnition + # @endif + + def getIdlDefinition(self): + return self.idlDefinition + + ## + # @if jp + # @brief SDO ServiceProfile.properties をセットする + # + # SDO Service のpropertiesをセットする + # + # @param self + # @param properties Service のproperties + # + # @else + # @brief Setting SDO ServiceProfile.properties + # @endif + + def setProperties(self, properties): + self.properties = properties + + ## + # @if jp + # @brief SDO ServiceProfile.properties を取得する + # + # SDO Service のpropertiesを取得する + # + # @param self + # + # @return Service のproperties + # + # @else + # @brief Getting SDO ServiceProfile.properties + # @endif + + def getProperties(self): + return self.properties + + # bool addProperty(char name, CORBA::Any data); + + ## + # @if jp + # @brief SDO ServiceProfile.serviceRef をセットする + # + # SDO Service のserviceRefをセットする + # + # @param self + # @param serviceRef Serviceへの参照 + # + # @else + # @brief Setting SDO ServiceProfile.serviceRef + # @endif + + def setServiceRef(self, serviceRef): + self.serviceRef = serviceRef + + ## + # @if jp + # @brief SDO ServiceProfile.serviceRef を取得する + # + # SDO Service への参照を取得する + # + # @param self + # + # @return Serviceへの参照 + # + # @else + # @brief Getting SDO ServiceProfile.serviceRef + # @endif + + def getServiceRef(self): + return self.serviceRef diff --git a/OpenRTM_aist/SdoServiceAdmin.py b/OpenRTM_aist/SdoServiceAdmin.py index 32f50f63..61e81fc3 100644 --- a/OpenRTM_aist/SdoServiceAdmin.py +++ b/OpenRTM_aist/SdoServiceAdmin.py @@ -1,5 +1,5 @@ #!/usr/bin/env python -# -*- coding: euc-jp -*- +# -*- coding: utf-8 -*- ## # @file SdoServiceAdmin.py @@ -23,57 +23,57 @@ # @if jp # # @class SDO service administration class -# @brief SDO service 饹 +# @brief SDO service 管理クラス # -# Υ饹ϡSDO Service 뤿Υ饹Ǥ롣SDO -# Service OMG SDO Specification ˤƤ롢SDO -# εǽΤ󶡤ޤ׵᤹륵ӥΰĤǤ롣ܺ٤ϻͤˤ -# Ƥʤܥ饹ǤϰʲΤ褦˿񤦥ӥ -# ΤȤ뤿Υ饹ܥ饹Ǥ롣 +# このクラスは、SDO Service を管理するためのクラスである。SDO +# Service は OMG SDO Specification において定義されている、SDOが特定 +# の機能のために提供また要求するサービスの一つである。詳細は仕様にお +# いて定義されていないが、本クラスでは以下のように振る舞うサービスで +# あるものとし、これらを管理するためのクラスが本クラスである。 # -# SDO Service ˤƤϡSDO/RTC˽ͭ졢Υӥ -# Τ SDO Service Provider¾SDO/RTC䥢ץꥱ -# 륵ӥ֥ȤλȤꡢεǽѤ -# ΤSDO Service Consumer ȸƤ֡ +# SDO Service においては、SDO/RTCに所有され、ある種のサービスを提供 +# するものを SDO Service Provider、他のSDO/RTCやアプリケーションが提 +# 供するサービスオブジェクトの参照を受け取り、それらの機能を利用する +# ものを、SDO Service Consumer と呼ぶ。 # -# SDO Service Provider ¾Υץꥱ󤫤ƤФ졢SDO/RTC -# εǽ˥뤿Ѥ롣¾SDO/RTCޤϥץꥱ -# ϡ +# SDO Service Provider は他のアプリケーションから呼ばれ、SDO/RTC内部 +# の機能にアクセスするために用いられる。他のSDO/RTCまたはアプリケー +# ションは、 # # - SDO::get_service_profiles () # - SDO::get_service_profile (in UniqueIdentifier id) -# - SDO::get_sdo_service (in UniqueIdentifier id) +# - SDO::get_sdo_service (in UniqueIdentifier id) # -# Τ줫Υڥ졼ˤꡢServiceProfile ޤ SDO -# Service λȤǽѤ뤿Υڥ졼Ƥӽ -# ¾SDO/RTCޤϥץꥱǤλȤ˴ǤդΥ -# ߥ󥰤ǹԤ졢ӥ¦ǤϡɤɤȤƤ -# Τ뤳ȤϤǤʤǡSDO/RTC¦⡢ǤդΥߥ󥰤ǥ -# ӥ󶡤ߤ뤳ȤǤ뤿ᡢӥ¦Ǥϡ -# ӥѤǤȤϸ¤ʤΤȤƥӥڥ졼 -# ƤӽФɬפ롣 +# のいずれかのオペレーションにより、ServiceProfile または SDO +# Service の参照を取得し、機能を利用するためのオペレーションを呼び出 +# す。他のSDO/RTCまたはアプリケーション上での参照の破棄は任意のタイ +# ミングで行われ、サービス提供側では、どこからどれだけ参照されている +# かは知ることはできない。一方で、SDO/RTC側も、任意のタイミングでサー +# ビスの提供を停止することもできるため、サービスの利用側では、常に +# サービスが利用できるとは限らないものとしてサービスオペレーションを +# 呼び出す必要がある。 # -# SDO Service Consumer SDO/RTCʳSDO/RTCޤϥץ -# 󤬥ӥμΤSDO/RTC˥֥ȻȤ -# ޤץեͿ뤳ȤǡSDO/RTC¦饵ӥڥ졼 -# 󤬸ƤФ쳰SDO/RTCޤϥץꥱ󶡤뵡ǽ -# Ǥ롣ޤ֥Ūʥ֥ȤͿ뤳ȤǡSDO/RTC¦ -# ΥХå¸뤿ˤѤ뤳ȤǤ롣󥷥塼 -# ޤϡץХȤϰۤʤꡢSDO Configuration󥿡ե -# ɲáԤ롣Ϣ륪ڥ졼ϰʲΤȤǤ롣 +# 一方、SDO Service Consumer は当該SDO/RTC以外のSDO/RTCまたはアプリ +# ケーションがサービスの実体を持ち、当該SDO/RTCにオブジェクト参照を +# 含むプロファイルを与えることで、SDO/RTC側からサービスオペレーショ +# ンが呼ばれ外部のSDO/RTCまたはアプリケーションが提供する機能を利用 +# できる。また、オブザーバ的なオブジェクトを与えることで、SDO/RTC側 +# からのコールバックを実現するためにも利用することができる。コンシュー +# マは、プロバイダとは異なり、SDO Configurationインターフェースから +# 追加、削除が行われる。関連するオペレーションは以下のとおりである。 # # - Configuration::add_service_profile (in ServiceProfile sProfile) # - Configuration::remove_service_profile (in UniqueIdentifier id) # -# SDO/RTCޤϥץꥱϡȤSDO Servcie -# Provider λȤIDinterface typeץѥƥȤȤ -# ServcieProfile ˥åȤǡadd_service_profile() ΰ -# Ϳ뤳ȤǡSDO/RTC˥ӥͿ롣κݡIDUUID -# ʤɰդIDǤʤФʤʤޤݤˤIDˤоݤ -# ServiceProfileõ뤿ᡢӥ¦ǤϺޤID -# ݻƤʤФʤʤ +# 外部のSDO/RTCまたはアプリケーションは、自身が持つSDO Servcie +# Provider の参照をIDおよびinterface type、プロパティとともに +# ServcieProfile にセットしたうえで、add_service_profile() の引数と +# して与えることで、当該SDO/RTCにサービスを与える。この際、IDはUUID +# など一意なIDでなければならない。また、削除する際にはIDにより対象と +# するServiceProfileを探索するため、サービス提供側では削除時までIDを +# 保持しておかなければならない。 +# # -# # # # @@ -89,434 +89,446 @@ # # @endif class SdoServiceAdmin: - """ - """ - - - ## - # @if jp - # @brief 󥹥ȥ饯 - # 󥹥ȥ饯 - # @param - # - # @else - # @brief Constructor - # Constructor - # @param - # @endif - # SdoServiceAdmin(::RTC::RTObject_impl& rtobj); - def __init__(self, rtobj): - self._rtobj = rtobj - self._consumerTypes = [] - self._providers = [] - self._allConsumerEnabled = False + """ + """ + + ## + # @if jp + # @brief コンストラクタ + # コンストラクタ + # @param + # + # @else + # @brief Constructor + # Constructor + # @param + # @endif + # SdoServiceAdmin(::RTC::RTObject_impl& rtobj); + def __init__(self, rtobj): + self._rtobj = rtobj + self._consumerTypes = [] + self._providers = [] + self._allConsumerEnabled = False + + ## + # @if jp + # @brief Lock 付き SDO ServiceProfileList + # @else + # @brief SDO ServiceProfileList with mutex lock + # @endif + self._providerProfiles = [] + self._provider_mutex = threading.RLock() + + ## + # @if jp + # @brief Lock 付き SDO ServiceProfileList + # @else + # @brief SDO ServiceProfileList with mutex lock + # @endif + self._consumers = [] + self._consumer_mutex = threading.RLock() + + ## + # @if jp + # @brief logger + # @else + # @brief logger + # @endif + self._rtcout = OpenRTM_aist.Manager.instance().getLogbuf("SdoServiceAdmin") + + return + + ## + # @if jp + # @brief 仮想デストラクタ + # 仮想デストラクタ。 + # + # @else + # @brief Virtual destractor + # Virtual destractor. + # @endif + + def __del__(self): + pass + + ## + # @if jp + # @brief 初期化 + # @param self + # @param rtobj + # + # @else + # @brief + # @param self + # @param rtobj + # + def init(self, rtobj): + + self._rtcout.RTC_TRACE("SdoServiceAdmin::SdoServiceAdmin(%s)", + rtobj.getProperties().getProperty("instance_name")) + + prop = self._rtobj.getProperties() + + # ------------------------------------------------------------ + # SDO service provider + enabledProviderTypes = [s.strip() for s in prop.getProperty( + "sdo.service.provider.enabled_services").split(",")] + self._rtcout.RTC_DEBUG("sdo.service.provider.enabled_services: %s", + prop.getProperty("sdo.service.provider.enabled_services")) + + availableProviderTypes = OpenRTM_aist.SdoServiceProviderFactory.instance().getIdentifiers() + prop.setProperty("sdo.service.provider.available_services", + str(OpenRTM_aist.flatten(availableProviderTypes))) + self._rtcout.RTC_DEBUG("sdo.service.provider.available_services: %s", + prop.getProperty("sdo.service.provider.available_services")) + + # If types include '[Aa][Ll][Ll]', all types enabled in this RTC + activeProviderTypes = [] + for enabledProviderType in enabledProviderTypes: + tmp = enabledProviderType.lower() + if tmp == "all": + activeProviderTypes = availableProviderTypes + self._rtcout.RTC_DEBUG( + "sdo.service.provider.enabled_services: ALL") + break + + for availableProviderType in availableProviderTypes: + if availableProviderType == enabledProviderType: + activeProviderTypes.append(availableProviderType) + + factory = OpenRTM_aist.SdoServiceProviderFactory.instance() + for activeProviderType in activeProviderTypes: + svc = factory.createObject(activeProviderType) + propkey = self.ifrToKey(activeProviderType) + properties = [] + OpenRTM_aist.NVUtil.copyFromProperties(properties, + prop.getNode(str(propkey))) + prof = SDOPackage.ServiceProfile(str(activeProviderType), + str(activeProviderType), + properties, + svc._this()) + + if not svc.init(rtobj, prof): + svc.finalize() + continue + self._providers.append(svc) + + # ------------------------------------------------------------ + # SDO service consumer + # getting consumer types from RTC's properties + constypes = prop.getProperty("sdo.service.consumer.enabled_services") + + self._consumerTypes = [s.strip() for s in constypes.split(",")] + self._rtcout.RTC_DEBUG("sdo.service.consumer.enabled_services: %s", + str(constypes)) + + prop.setProperty("sdo.service.consumer.available_services", + str(OpenRTM_aist.flatten(OpenRTM_aist.SdoServiceConsumerFactory.instance().getIdentifiers()))) + self._rtcout.RTC_DEBUG("sdo.service.consumer.available_services: %s", + prop.getProperty("sdo.service.consumer.available_services")) + + # If types include '[Aa][Ll][Ll]', all types allowed in this RTC + for ctype in self._consumerTypes: + + tmp = ctype.lower() + if tmp == "all": + self._allConsumerEnabled = True + self._rtcout.RTC_DEBUG("sdo_service.consumer_types: ALL") + + return + + ## + # @if jp + # @brief 終了処理 + # @param self + # + # @else + # @brief + # @param self + # + + def exit(self): + len_ = len(self._providers) + for i in range(len_): + idx = (len_ - 1) - i + self._providers[idx].finalize() + del self._providers[idx] + + self._providers = [] + len_ = len(self._consumers) + for i in range(len_): + idx = (len_ - 1) - i + self._consumers[idx].finalize() + del self._consumers[idx] + + self._consumers = [] + return ## # @if jp - # @brief Lock դ SDO ServiceProfileList + # @brief SDO Service Provider の ServiceProfileList を取得する # @else - # @brief SDO ServiceProfileList with mutex lock + # @brief Get ServiceProfileList of SDO Service Provider # @endif - self._providerProfiles = [] - self._provider_mutex = threading.RLock() - + # + # SDOPackage::ServiceProfileList* + # SdoServiceAdmin::getServiceProviderProfiles() + + def getServiceProviderProfiles(self): + prof = [] + guard = OpenRTM_aist.ScopedLock(self._provider_mutex) + for provider in self._providers: + prof.append(provider.getProfile()) + return prof + ## # @if jp - # @brief Lock դ SDO ServiceProfileList + # @brief SDO Service Provider の ServiceProfile を取得する # @else - # @brief SDO ServiceProfileList with mutex lock + # @brief Get ServiceProfile of an SDO Service Provider # @endif - self._consumers = [] - self._consumer_mutex = threading.RLock() + # + # SDOPackage::ServiceProfile* + # SdoServiceAdmin::getServiceProviderProfile(const char* id) + + def getServiceProviderProfile(self, id): + idstr = id + guard = OpenRTM_aist.ScopedLock(self._provider_mutex) + for provider in self._providers: + if idstr == str(provider.getProfile().id): + return provider.getProfile() + + raise SDOPackage.InvalidParameter("") ## # @if jp - # @brief logger + # @brief SDO Service Provider の Service を取得する # @else - # @brief logger + # @brief Get ServiceProfile of an SDO Service # @endif - self._rtcout = OpenRTM_aist.Manager.instance().getLogbuf("SdoServiceAdmin") - - return - - - ## - # @if jp - # @brief ۥǥȥ饯 - # ۥǥȥ饯 - # - # @else - # @brief Virtual destractor - # Virtual destractor. - # @endif - def __del__(self): - pass - - - ## - # @if jp - # @brief - # @param self - # @param rtobj - # - # @else - # @brief - # @param self - # @param rtobj - # - def init(self, rtobj): - - - self._rtcout.RTC_TRACE("SdoServiceAdmin::SdoServiceAdmin(%s)", - rtobj.getProperties().getProperty("instance_name")) - - prop = self._rtobj.getProperties() - - # ------------------------------------------------------------ - # SDO service provider - enabledProviderTypes = [s.strip() for s in prop.getProperty("sdo.service.provider.enabled_services").split(",")] - self._rtcout.RTC_DEBUG("sdo.service.provider.enabled_services: %s", - prop.getProperty("sdo.service.provider.enabled_services")) - - availableProviderTypes = OpenRTM_aist.SdoServiceProviderFactory.instance().getIdentifiers() - prop.setProperty("sdo.service.provider.available_services", - str(OpenRTM_aist.flatten(availableProviderTypes))) - self._rtcout.RTC_DEBUG("sdo.service.provider.available_services: %s", - prop.getProperty("sdo.service.provider.available_services")) - - - # If types include '[Aa][Ll][Ll]', all types enabled in this RTC - activeProviderTypes = [] - for i in range(len(enabledProviderTypes)): - tmp = enabledProviderTypes[i].lower() - if tmp == "all": - activeProviderTypes = availableProviderTypes - self._rtcout.RTC_DEBUG("sdo.service.provider.enabled_services: ALL") - break - - for j in range(len(availableProviderTypes)): - if availableProviderTypes[j] == enabledProviderTypes[i]: - activeProviderTypes.append(availableProviderTypes[j]) - - factory = OpenRTM_aist.SdoServiceProviderFactory.instance() - for i in range(len(activeProviderTypes)): - svc = factory.createObject(activeProviderTypes[i]) - propkey = self.ifrToKey(activeProviderTypes[i]) - properties = [] - OpenRTM_aist.NVUtil.copyFromProperties(properties, - prop.getNode(str(propkey))) - prof = SDOPackage.ServiceProfile(str(activeProviderTypes[i]), - str(activeProviderTypes[i]), - properties, - svc._this()) - - if not svc.init(rtobj, prof): - svc.finalize() - continue - self._providers.append(svc) - - - # ------------------------------------------------------------ - # SDO service consumer - # getting consumer types from RTC's properties - constypes = prop.getProperty("sdo.service.consumer.enabled_services") - - self._consumerTypes = [s.strip() for s in constypes.split(",")] - self._rtcout.RTC_DEBUG("sdo.service.consumer.enabled_services: %s", - str(constypes)) - - prop.setProperty("sdo.service.consumer.available_services", - str(OpenRTM_aist.flatten(OpenRTM_aist.SdoServiceConsumerFactory.instance().getIdentifiers()))) - self._rtcout.RTC_DEBUG("sdo.service.consumer.available_services: %s", - prop.getProperty("sdo.service.consumer.available_services")) - - # If types include '[Aa][Ll][Ll]', all types allowed in this RTC - for ctype in self._consumerTypes: - - tmp = ctype.lower() - if tmp == "all": - self._allConsumerEnabled = True - self._rtcout.RTC_DEBUG("sdo_service.consumer_types: ALL") - - return - - - - ## - # @if jp - # @brief λ - # @param self - # - # @else - # @brief - # @param self - # - def exit(self): - len_ = len(self._providers) - for i in range(len_): - idx = (len_ - 1) - i - self._providers[idx].finalize() - del self._providers[idx] - - self._providers = [] - - len_ = len(self._consumers) - for i in range(len_): - idx = (len_ - 1) - i - self._consumers[idx].finalize() - del self._consumers[idx] - - self._consumers = [] - return - - - ## - # @if jp - # @brief SDO Service Provider ServiceProfileList - # @else - # @brief Get ServiceProfileList of SDO Service Provider - # @endif - # - # SDOPackage::ServiceProfileList* SdoServiceAdmin::getServiceProviderProfiles() - def getServiceProviderProfiles(self): - prof = [] - guard = OpenRTM_aist.ScopedLock(self._provider_mutex) - for i in range(len(self._providers)): - prof.append(self._providers[i].getProfile()) - return prof - - - ## - # @if jp - # @brief SDO Service Provider ServiceProfile - # @else - # @brief Get ServiceProfile of an SDO Service Provider - # @endif - # - # SDOPackage::ServiceProfile* - # SdoServiceAdmin::getServiceProviderProfile(const char* id) - def getServiceProviderProfile(self, id): - idstr = id - guard = OpenRTM_aist.ScopedLock(self._provider_mutex) - for i in range(len(self._providers)): - if idstr == str(self._providers[i].getProfile().id): - return self._providers[i].getProfile() - - raise SDOPackage.InvalidParameter("") - - - ## - # @if jp - # @brief SDO Service Provider Service - # @else - # @brief Get ServiceProfile of an SDO Service - # @endif - # - # SDOPackage::SDOService_ptr SdoServiceAdmin::getServiceProvider(const char* id) - def getServiceProvider(self, id): - prof = self.getServiceProviderProfile(id) - return prof.service - - - ## - # @if jp - # @brief SDO service provider 򥻥åȤ - # @else - # @brief Set a SDO service provider - # @endif - # - # bool SdoServiceAdmin:: - # addSdoServiceProvider(const SDOPackage::ServiceProfile& prof, - # SdoServiceProviderBase* provider) - def addSdoServiceProvider(self, prof, provider): - self._rtcout.RTC_TRACE("SdoServiceAdmin::addSdoServiceProvider(if=%s)", - prof.interface_type) - guard = OpenRTM_aist.ScopedLock(self._provider_mutex) - id = prof.id - for i in range(len(self._providers)): - if id == str(self._providers[i].getProfile().id): - self._rtcout.RTC_ERROR("SDO service(id=%s, ifr=%s) already exists", - (str(prof.id), str(prof.interface_type))) - return False + # + # SDOPackage::SDOService_ptr SdoServiceAdmin::getServiceProvider(const + # char* id) - self._providers.append(provider) - return True - - - ## - # @if jp - # @brief SDO service provider - # @else - # @brief Remove a SDO service provider - # @endif - # - # bool SdoServiceAdmin::removeSdoServiceProvider(const char* id) - def removeSdoServiceProvider(self, id): - self._rtcout.RTC_TRACE("removeSdoServiceProvider(%d)", id) - guard = OpenRTM_aist.ScopedLock(self._provider_mutex) - - strid = id - len_ = len(self._providers) - for i in range(len_): - idx = (len_ - 1) - i - if strid == str(self._providers[idx].getProfile().id): - self._providers[idx].finalize() - factory = OpenRTM_aist.SdoServiceProviderFactory.instance() - factory.deleteObject(self._providers[idx]) - del self._providers[idx] - self._rtcout.RTC_INFO("SDO service provider has been deleted: %s", id) + def getServiceProvider(self, id): + prof = self.getServiceProviderProfile(id) + return prof.service + + ## + # @if jp + # @brief SDO service provider をセットする + # @else + # @brief Set a SDO service provider + # @endif + # + # bool SdoServiceAdmin:: + # addSdoServiceProvider(const SDOPackage::ServiceProfile& prof, + # SdoServiceProviderBase* provider) + + def addSdoServiceProvider(self, prof, provider): + self._rtcout.RTC_TRACE("SdoServiceAdmin::addSdoServiceProvider(if=%s)", + prof.interface_type) + guard = OpenRTM_aist.ScopedLock(self._provider_mutex) + id = prof.id + for p in self._providers: + if id == str(p.getProfile().id): + self._rtcout.RTC_ERROR("SDO service(id=%s, ifr=%s) already exists", + (str(prof.id), str(prof.interface_type))) + return False + + self._providers.append(provider) return True - self._rtcout.RTC_WARN("Specified SDO service provider not found: %s", id) - return False - - - ## - # @if jp - # @brief Service Consumer ɲä - # - # @else - # @brief Add Service Consumer - # @endif - # bool addSdoServiceConsumer(const SDOPackage::ServiceProfile& sProfile); - def addSdoServiceConsumer(self, sProfile): - self._rtcout.RTC_TRACE("addSdoServiceConsumer(IFR = %s)", - sProfile.interface_type) - profile = copy.deepcopy(sProfile) - - # Not supported consumer type -> error return - if not self.isEnabledConsumerType(sProfile): - self._rtcout.RTC_ERROR("Not supported consumer type. %s", profile.interface_type) - return False - - if not self.isExistingConsumerType(sProfile): - self._rtcout.RTC_ERROR("type %s not exists.", profile.interface_type) - return False - if str(profile.id) == "": - self._rtcout.RTC_WARN("No id specified. It should be given by clients.") - return False - - # re-initialization - guard = OpenRTM_aist.ScopedLock(self._consumer_mutex) - id = str(sProfile.id) - for i in range(len(self._consumers)): - if id == str(self._consumers[i].getProfile().id): - self._rtcout.RTC_INFO("Existing consumer is reinitilized.") - self._rtcout.RTC_DEBUG("Propeteis are: %s", - OpenRTM_aist.NVUtil.toString(sProfile.properties)) - return self._consumers[i].reinit(sProfile) - del guard - - # new pofile - factory = OpenRTM_aist.SdoServiceConsumerFactory.instance() - ctype = str(profile.interface_type) - consumer = factory.createObject(ctype) - #if consumer is None: - # self._rtcout.RTC_ERROR("Hmm... consumer must be created.") - # return False - - # initialize - if not consumer.init(self._rtobj, sProfile): - self._rtcout.RTC_WARN("SDO service initialization was failed.") - self._rtcout.RTC_DEBUG("id: %s", str(sProfile.id)) - self._rtcout.RTC_DEBUG("IFR: %s", str(sProfile.interface_type)) - self._rtcout.RTC_DEBUG("properties: %s", OpenRTM_aist.NVUtil.toString(sProfile.properties)) - factory.deleteObject(consumer) - self._rtcout.RTC_INFO("SDO consumer was deleted by initialization failure") - return False - - # store consumer - guard = OpenRTM_aist.ScopedLock(self._consumer_mutex) - self._consumers.append(consumer) - del guard - - return True - - - ## - # @if jp - # @brief Service Consumer - # - # @else - # @brief Remove Service Consumer - # @endif - # bool removeSdoServiceConsumer(const char* id); - def removeSdoServiceConsumer(self, id): - if id == None or id[0] == '\0': - self._rtcout.RTC_ERROR("removeSdoServiceConsumer(): id is invalid.") - return False - - self._rtcout.RTC_TRACE("removeSdoServiceConsumer(id = %s)", id) - - guard = OpenRTM_aist.ScopedLock(self._consumer_mutex) - strid = id - - for (idx,cons) in enumerate(self._consumers): - if strid == str(cons.getProfile().id): - cons.finalize() - del self._consumers[idx] + + ## + # @if jp + # @brief SDO service provider を削除する + # @else + # @brief Remove a SDO service provider + # @endif + # + # bool SdoServiceAdmin::removeSdoServiceProvider(const char* id) + + def removeSdoServiceProvider(self, id): + self._rtcout.RTC_TRACE("removeSdoServiceProvider(%d)", id) + guard = OpenRTM_aist.ScopedLock(self._provider_mutex) + + strid = id + len_ = len(self._providers) + for i in range(len_): + idx = (len_ - 1) - i + if strid == str(self._providers[idx].getProfile().id): + self._providers[idx].finalize() + factory = OpenRTM_aist.SdoServiceProviderFactory.instance() + del self._providers[idx] + self._rtcout.RTC_INFO( + "SDO service provider has been deleted: %s", id) + return True + self._rtcout.RTC_WARN( + "Specified SDO service provider not found: %s", id) + return False + + ## + # @if jp + # @brief Service Consumer を追加する + # + # @else + # @brief Add Service Consumer + # @endif + # bool addSdoServiceConsumer(const SDOPackage::ServiceProfile& sProfile); + + def addSdoServiceConsumer(self, sProfile): + self._rtcout.RTC_TRACE("addSdoServiceConsumer(IFR = %s)", + sProfile.interface_type) + profile = copy.deepcopy(sProfile) + + # Not supported consumer type -> error return + if not self.isEnabledConsumerType(sProfile): + self._rtcout.RTC_ERROR( + "Not supported consumer type. %s", + profile.interface_type) + return False + + if not self.isExistingConsumerType(sProfile): + self._rtcout.RTC_ERROR( + "type %s not exists.", + profile.interface_type) + return False + if str(profile.id) == "": + self._rtcout.RTC_WARN( + "No id specified. It should be given by clients.") + return False + + # re-initialization + guard = OpenRTM_aist.ScopedLock(self._consumer_mutex) + id = str(sProfile.id) + for consumer in self._consumers: + if id == str(consumer.getProfile().id): + self._rtcout.RTC_INFO("Existing consumer is reinitilized.") + self._rtcout.RTC_DEBUG("Propeteis are: %s", + OpenRTM_aist.NVUtil.toString(sProfile.properties)) + return consumer.reinit(sProfile) + del guard + + # new pofile factory = OpenRTM_aist.SdoServiceConsumerFactory.instance() - factory.deleteObject(cons) - self._rtcout.RTC_INFO("SDO service has been deleted: %s", id) - return True + ctype = str(profile.interface_type) + consumer = factory.createObject(ctype) + # if consumer is None: + # self._rtcout.RTC_ERROR("Hmm... consumer must be created.") + # return False + + # initialize + if not consumer.init(self._rtobj, sProfile): + self._rtcout.RTC_WARN("SDO service initialization was failed.") + self._rtcout.RTC_DEBUG("id: %s", str(sProfile.id)) + self._rtcout.RTC_DEBUG( + "IFR: %s", str( + sProfile.interface_type)) + self._rtcout.RTC_DEBUG( + "properties: %s", + OpenRTM_aist.NVUtil.toString( + sProfile.properties)) + self._rtcout.RTC_INFO( + "SDO consumer was deleted by initialization failure") + return False + + # store consumer + guard = OpenRTM_aist.ScopedLock(self._consumer_mutex) + self._consumers.append(consumer) + del guard - self._rtcout.RTC_WARN(("Specified SDO consumer not found: %s", id)) - return False - - - ## - # @if jp - # @brief Ĥ줿ӥɤĴ٤ - # @else - # @brief If it is enabled service type - # @endif - # - # bool SdoServiceAdmin:: - # isEnabledConsumerType(const SDOPackage::ServiceProfile& sProfile) - def isEnabledConsumerType(self, sProfile): - if self._allConsumerEnabled: - return True - - for i in range(len(self._consumerTypes)): - if self._consumerTypes[i] == str(sProfile.interface_type): - self._rtcout.RTC_DEBUG("%s is supported SDO service.", - str(sProfile.interface_type)) return True - self._rtcout.RTC_WARN("Consumer type is not supported: %s", - str(sProfile.interface_type)) - return False - - - ## - # @if jp - # @brief ¸ߤ륵ӥɤĴ٤ - # - # @else - # @brief If it is existing service type - # @endif - # bool isExistingConsumerType(const SDOPackage::ServiceProfile& sProfile); - def isExistingConsumerType(self, sProfile): - factory = OpenRTM_aist.SdoServiceConsumerFactory.instance() - consumerTypes = factory.getIdentifiers() - for i in range(len(consumerTypes)): - if consumerTypes[i] == str(sProfile.interface_type): - self._rtcout.RTC_DEBUG("%s exists in the SDO service factory.", str(sProfile.interface_type)) - self._rtcout.RTC_PARANOID("Available SDO serices in the factory: %s", str(OpenRTM_aist.flatten(consumerTypes))) - return True - self._rtcout.RTC_WARN("No available SDO service in the factory: %s", - str(sProfile.interface_type)) - return False - - - # const std::string getUUID() const; - def getUUID(self): - return str(OpenRTM_aist.uuid1()) - - # std::string SdoServiceAdmin::ifrToKey(std::string& ifr) - def ifrToKey(self, ifr): - ifrvstr = ifr.split(":") - ifrvstr[1] = ifrvstr[1].lower() - ifrvstr[1] = ifrvstr[1].replace(".", "_") - ifrvstr[1] = ifrvstr[1].replace("/", ".") - return ifrvstr[1] + ## + # @if jp + # @brief Service Consumer を削除する + # + # @else + # @brief Remove Service Consumer + # @endif + # bool removeSdoServiceConsumer(const char* id); + + def removeSdoServiceConsumer(self, id): + if id is None or id[0] == '\0': + self._rtcout.RTC_ERROR( + "removeSdoServiceConsumer(): id is invalid.") + return False + + self._rtcout.RTC_TRACE("removeSdoServiceConsumer(id = %s)", id) + + guard = OpenRTM_aist.ScopedLock(self._consumer_mutex) + strid = id + + for (idx, cons) in enumerate(self._consumers): + if strid == str(cons.getProfile().id): + cons.finalize() + del self._consumers[idx] + factory = OpenRTM_aist.SdoServiceConsumerFactory.instance() + self._rtcout.RTC_INFO("SDO service has been deleted: %s", id) + return True + + self._rtcout.RTC_WARN(("Specified SDO consumer not found: %s", id)) + return False + + ## + # @if jp + # @brief 許可されたサービス型かどうか調べる + # @else + # @brief If it is enabled service type + # @endif + # + # bool SdoServiceAdmin:: + # isEnabledConsumerType(const SDOPackage::ServiceProfile& sProfile) + + def isEnabledConsumerType(self, sProfile): + if self._allConsumerEnabled: + return True + + for consumerType in self._consumerTypes: + if consumerType == str(sProfile.interface_type): + self._rtcout.RTC_DEBUG("%s is supported SDO service.", + str(sProfile.interface_type)) + return True + + self._rtcout.RTC_WARN("Consumer type is not supported: %s", + str(sProfile.interface_type)) + return False + + ## + # @if jp + # @brief 存在するサービス型かどうか調べる + # + # @else + # @brief If it is existing service type + # @endif + # bool isExistingConsumerType(const SDOPackage::ServiceProfile& sProfile); + + def isExistingConsumerType(self, sProfile): + factory = OpenRTM_aist.SdoServiceConsumerFactory.instance() + consumerTypes = factory.getIdentifiers() + for consumerType in consumerTypes: + if consumerType == str(sProfile.interface_type): + self._rtcout.RTC_DEBUG( + "%s exists in the SDO service factory.", str( + sProfile.interface_type)) + self._rtcout.RTC_PARANOID( + "Available SDO serices in the factory: %s", str( + OpenRTM_aist.flatten(consumerTypes))) + return True + self._rtcout.RTC_WARN("No available SDO service in the factory: %s", + str(sProfile.interface_type)) + return False + + # const std::string getUUID() const; + + def getUUID(self): + return str(OpenRTM_aist.uuid1()) + + # std::string SdoServiceAdmin::ifrToKey(std::string& ifr) + def ifrToKey(self, ifr): + ifrvstr = ifr.split(":") + ifrvstr[1] = ifrvstr[1].lower() + ifrvstr[1] = ifrvstr[1].replace(".", "_") + ifrvstr[1] = ifrvstr[1].replace("/", ".") + return ifrvstr[1] diff --git a/OpenRTM_aist/SdoServiceConsumerBase.py b/OpenRTM_aist/SdoServiceConsumerBase.py index a085f661..870e3456 100644 --- a/OpenRTM_aist/SdoServiceConsumerBase.py +++ b/OpenRTM_aist/SdoServiceConsumerBase.py @@ -1,5 +1,5 @@ #!/usr/bin/env python -# -*- coding: euc-jp -*- +# -*- coding: utf-8 -*- ## # @file SdoServiceConsumerBase.py @@ -25,8 +25,6 @@ # # factory.addFactory(toRepositoryId(), # Creator< SdoServiceConsumerBase, -# your_sdo_service_consumer_subclass>, -# Destructor< SdoServiceConsumerBase, # your_sdo_service_consumer_subclass>); # # @else @@ -35,136 +33,138 @@ # # @endif class SdoServiceConsumerBase: - """ - """ - - def __init__(self): - pass - - def __del__(self): - pass - - ## - # @if jp - # @brief 󥷥塼ޥ饹νؿ - # - # ؿͿ줿 RTObject ServiceProfile 顢 - # ֥ȤޤΥӥ - # ''sdo.service.provider.enabled_services'' ͭƤС - # δؿбRTC󥹥󥹲줿ľ˸ƤӽФޤ - # - # ServiceProfile ˤϰʲξä֤ǸƤӽФޤ - # - # - ServiceProfile.id: ӥIFR - # - ServiceProfile.interface_type: ӥIFR - # - ServiceProfile.service: ӥΥ֥Ȼ - # - ServiceProfile.properties: rtc.conf .conf Ϳ - # 줿SDOӥͭΥץϤ롣 - # confե - # ϡ''..'' - # ȤץեåĤץȤͿ - # 뤳ȤǤproperties ˤϡΥץ - # եåץkey:value - # ޤޤƤ롣 - # - # ؿǤϡ properties Ƥɤ߹ߥӥͭ - # ԤޤͿ줿 ServiceProfileƤ뤤 - # Ϥ¾ͳӥ򥤥󥹥󥹲ʤ false - # ֤ޤξ硢finalize() ƤӽФ줽θ奪֥ - # Ϻޤʳξ true ֤ȡӥ֥ - # Ȥ RTC ݻޤ - # - # @param rtobj Υ֥Ȥ󥹥󥹲줿 RTC - # @param profile Ϳ줿 SDO ServiceProfile - # @return Ϳ줿 SDO Service ServiceProfile ξ false - # - # @else - # @brief Initialization function of the consumer class - # - # @endif - # - # virtual bool init(RTObject_impl& rtobj, - # const SDOPackage::ServiceProfile& profile) = 0; - def init(self, rtobj, profile): - pass - - ## - # @if jp - # @brief 󥷥塼ޥ饹κƽؿ - # - # Υ֥ȤκƽԤServiceProfile ˤ id ե - # ɤ˥åͭ UUID åȤƤ뤬Ʊ id ξ - # 硢properties ꤵ줿ѹ䡢service ե - # ΥӥλȤѹԤ롣κݤ˸ƤФΤ - # reinit() ؿǤ롣Ǥϡservice եɤΥ֥ - # ե󥹤ƱǧۤʤäƤݻƤե - # 󥹤򹹿ɬפ롣ޤ properties ˤϿ꤬Ϳ - # ƤǽΤǡƤɤ߹򹹿롣 - # - # @param profile Ϳ줿 SDO ServiceProfile - # @return ServiceProfile Ϳ줿 false - # - # @else - # @brief Reinitialization function of the consumer class - # - # @endif - # - # virtual bool reinit(const SDOPackage::ServiceProfile& profile) = 0; - def reinit(self, profile): - pass - - ## - # @if jp - # @brief ServiceProfile ֤ - # - # init()/reinit()Ϳ줿 ServiceProfile ̾索֥ - # ݻ롣SDO Service ե졼ϴ夳Υ֥ - # Ȥб ServiceProfile ɬפȤΤǡδؿǤݻ - # Ƥ ServiceProfile ֤ - # - # @return Υ֥ȤݻƤ ServiceProfile - # - # @else - # @brief Getting ServiceProfile - # @endif - # - # virtual const SDOPackage::ServiceProfile& getProfile() const = 0; - def getProfile(self): - pass - - ## - # @if jp - # @brief λ - # - # SDOӥǥåݤ˸ƤӽФ뽪λѴؿ - # ӥΤǥå˺ݤơ֥Ȥݻ꥽ - # ʤɤνԤ - # - # @else - # @brief Finalization - # - # @endif - # - # virtual void finalize() = 0; - def finalize(self): - pass + """ + """ + + def __init__(self): + pass + + def __del__(self): + pass + + ## + # @if jp + # @brief コンシューマクラスの初期化関数 + # + # 初期化関数。与えられた RTObject および ServiceProfile から、当該 + # オブジェクトを初期化します。このサービスが + # ''sdo.service.provider.enabled_services'' で有効化されていれば、 + # この関数は対応するRTCがインスタンス化された直後に呼び出されます。 + # + # ServiceProfile には以下の情報が入った状態で呼び出されます。 + # + # - ServiceProfile.id: 当該サービスのIFR型 + # - ServiceProfile.interface_type: 当該サービスのIFR型 + # - ServiceProfile.service: 当該サービスのオブジェクト参照 + # - ServiceProfile.properties: rtc.conf や .conf 等で与 + # えられたSDOサービス固有のオプションが渡される。 + # confファイル内で + # は、''..'' + # というプリフィックスをつけたオプションとして与 + # えることができ、properties 内には、このプリ + # フィックスを除いたオプションがkey:value形式で + # 含まれている。 + # + # 関数内では、主に properties から設定内容を読み込みサービス固有の + # 設定等を行います。与えられた ServiceProfileの内容が不正、あるい + # はその他の理由で当該サービスをインスタンス化しない場合は false + # を返します。その場合、finalize() が呼び出されその後オブジェクト + # は削除されます。それ以外の場合は true を返すと、サービスオブジェ + # クトは RTC 内に保持されます。 + # + # @param rtobj このオブジェクトがインスタンス化された RTC + # @param profile 外部から与えられた SDO ServiceProfile + # @return 与えられた SDO Service や ServiceProfile が不正の場合 false + # + # @else + # @brief Initialization function of the consumer class + # + # @endif + # + # virtual bool init(RTObject_impl& rtobj, + # const SDOPackage::ServiceProfile& profile) = 0; + def init(self, rtobj, profile): + pass + + ## + # @if jp + # @brief コンシューマクラスの再初期化関数 + # + # このオブジェクトの再初期化を行う。ServiceProfile には id フィー + # ルドにセッション固有の UUID がセットされているが、同一の id の場 + # 合、properties に設定された設定情報の変更や、service フィールド + # のサービスの参照の変更が行われる。その際に呼ばれるのがこの + # reinit() 関数である。実装では、service フィールドのオブジェクト + # リファレンスの同一性を確認し、異なっている場合保持しているリファ + # レンスを更新する必要がある。また properties には新たな設定が与え + # られている可能性があるので、内容を読み込み設定を更新する。 + # + # @param profile 新たに与えられた SDO ServiceProfile + # @return 不正な ServiceProfile が与えられた場合は false + # + # @else + # @brief Reinitialization function of the consumer class + # + # @endif + # + # virtual bool reinit(const SDOPackage::ServiceProfile& profile) = 0; + def reinit(self, profile): + pass + + ## + # @if jp + # @brief ServiceProfile を返す + # + # init()/reinit()で与えられた ServiceProfile は通常オブジェクト内 + # で保持される。SDO Service 管理フレームワークは管理上このオブジェ + # クトに対応する ServiceProfile を必要とするので、この関数では保持 + # されている ServiceProfile を返す。 + # + # @return このオブジェクトが保持している ServiceProfile + # + # @else + # @brief Getting ServiceProfile + # @endif + # + # virtual const SDOPackage::ServiceProfile& getProfile() const = 0; + def getProfile(self): + pass + + ## + # @if jp + # @brief 終了処理 + # + # SDOサービスがでタッチされる際に呼び出される終了処理用関数。サー + # ビスのでタッチに際して、当該オブジェクトが保持するリソースを解放 + # するなどの処理を行う。 + # + # @else + # @brief Finalization + # + # @endif + # + # virtual void finalize() = 0; + def finalize(self): + pass + sdoserviceconsumerfactory = None -class SdoServiceConsumerFactory(OpenRTM_aist.Factory,SdoServiceConsumerBase): - def __init__(self): - OpenRTM_aist.Factory.__init__(self) - return - def __del__(self): - pass +class SdoServiceConsumerFactory(OpenRTM_aist.Factory, SdoServiceConsumerBase): + def __init__(self): + OpenRTM_aist.Factory.__init__(self) + return + + def __del__(self): + pass - def instance(): - global sdoserviceconsumerfactory + def instance(): + global sdoserviceconsumerfactory - if sdoserviceconsumerfactory is None: - sdoserviceconsumerfactory = SdoServiceConsumerFactory() + if sdoserviceconsumerfactory is None: + sdoserviceconsumerfactory = SdoServiceConsumerFactory() - return sdoserviceconsumerfactory + return sdoserviceconsumerfactory - instance = staticmethod(instance) + instance = staticmethod(instance) diff --git a/OpenRTM_aist/SdoServiceProviderBase.py b/OpenRTM_aist/SdoServiceProviderBase.py index 58194f88..c131083b 100644 --- a/OpenRTM_aist/SdoServiceProviderBase.py +++ b/OpenRTM_aist/SdoServiceProviderBase.py @@ -1,5 +1,5 @@ #!/usr/bin/env python -# -*- coding: euc-jp -*- +# -*- coding: utf-8 -*- ## # @file SdoServiceProviderBase.py @@ -15,7 +15,6 @@ # All rights reserved. - import OpenRTM_aist import SDOPackage__POA @@ -23,36 +22,36 @@ ## # @if jp # -# @brief SdoServiceProvider쥯饹 -# -# SDOƤSDOӥΥץХ뤿δ쥯 -# SDOӥˤϡ󶡥ӥRTC(SDO)¦Ѥ -# SDOӥ󥷥塼ޤȡRTC(SDO)ȤSDOӥ󶡤SDO -# ӥץХ롣٤ƤSDOӥץХϤδ -# 饹ѾƼ롣 -# -# Υ֥ȤΥ饤եϰʲ̤ꡣ -# -# -# ޥ͡Фƥɤȥ⥸塼ؿˤꥪ -# ȥեȥ꤬SdoServiceProviderFactory ФϿ -# 롣ϿΥˤϥӥ󥿡ե IFR (interface -# repository) ID Ѥ졢ˤꥵӥ̤롣 -# -# rtc.confΥե졼ˤꡢͭ뤳Ȥ -# ꤵƤ륵ӥץХϡRTCεưƱ˥ -# 󥹲롣 -# -# 󥹥󥹲塢ؿ init() ƤФ롣ˤ -# ӥΤΥե졼󥪥ץ Property -# Ϥ롣 -# -# 󥹥󥹲줿SDOӥץХ -# SDO.get_sdo_service() ˤ곰饢롣Τ -# ӥꤹIDIFR IDƱǤ롣ΤȤΥ -# 󥹤ϰʲ̤ꡣ -# -# RTCfinalizeΤƱSDOӥץХ -# 뤬κݤˤSdoServiceProviderBase.finalize() -# Τǡǥ꥽βʤɽλԤ +# @brief SdoServiceProvider 基底クラス +# +# SDOで定義されているSDOサービスのプロバイダを実装するための基底クラ +# ス。SDOサービスには、外部から提供サービスをRTC(SDO)側で利用する +# SDOサービスコンシューマと、RTC(SDO)自身がSDOサービスを提供するSDO +# サービスプロバイダがある。すべてのSDOサービスプロバイダはこの基底 +# クラスを継承して実装される。 +# +# このオブジェクトのライフサイクルは以下の通り。 +# +# -# マネージャに対してロードされるとモジュール初期化関数によりオブ +# ジェクトファクトリが、SdoServiceProviderFactory に対して登録さ +# れる。登録のキーにはサービスインターフェースの IFR (interface +# repository) ID が利用され、これによりサービスが区別される。 +# -# rtc.conf等のコンフィギュレーション指定により、有効化することが +# 指定されているサービスインプロバイダは、RTCの起動と同時にインス +# タンス化される。 +# -# インスタンス化後、初期化関数 init() が呼ばれる。引数には当該サー +# ビスのためのコンフィギュレーションオプションが Propertyに +# より渡される。 +# -# インスタンス化されたSDOサービスプロバイダは +# SDO.get_sdo_service() により外部からアクセスされる。このと +# き、サービスを指定するIDはIFR IDと同じである。このときのアタッ +# チシーケンスは以下の通り。 +# -# RTCがfinalizeされ解体されると同時にSDOサービスプロバイダも解体 +# されるが、その際にはSdoServiceProviderBase.finalize()がコール +# されるので、ここでリソースの解放など終了処理を行う。 # #
    -# 
    +#
     #   [RTC]      [SDO service]               [Other]
     #     |              :                        |
     #     | instantiate  :                        |
    @@ -72,176 +71,176 @@
     #
     # 
    # -# Υ饹μäƤϡʤȤʲν貾۴ؿ -# ɬפ롣 +# このクラスの実装に当たっては、少なくとも以下の純粋仮想関数を実装す +# る必要がある。 # -# - init(): ؿͿ줿 RTObject ServiceProfile -# 顢֥Ȥ롣 -# - reinit(): ƽؿServiceProfile 󹹿ΤƱ -# IDǸƤӽФ뤳Ȥͭ뤬κݤˤδؿ -# ServiceProfile ȤȤ˸ƤӽФ롣ؿǤϡѹʤ -# ƽ롣 -# - getProfile(): ꤵ줿ץե֤ؿ -# - finalize(): λ󥷥塼ޤǥåݤ˸ƤӽФ -# ؿؿǤϽλ롣 +# - init(): 初期化関数。与えられた RTObject および ServiceProfile か +# ら、当該オブジェクトを初期化する。 +# - reinit(): 再初期化関数。ServiceProfile は設定情報更新のため同一 +# IDで呼び出されることが有るが、その際にこの関数が新たな +# ServiceProfile とともに呼び出される。関数内では、設定の変更など +# 再初期化処理を実装する。 +# - getProfile(): 設定されたプロファイルを返す関数。 +# - finalize(): 終了処理。コンシューマがデタッチされる際に呼び出され +# る関数。関数内では終了処理を実装する。 # -# SdoServiceProviderΥȥݥȤ̾ե̾ basename + "Init" -# ˤƤʲˡ饹̾ե -# ̾ȥݥȴؿ̾ο侩򼨤 +# SdoServiceProviderのエントリポイントは通常、ファイル名の basename + "Init" +# にしておく。以下に、クラス名、ファイル +# 名、エントリポイント関数名の推奨例を示す。 # -# - 饹̾: MySdoServiceProvider -# - ե̾: MySdoServiceProvider.py -# - ȥݥȴؿ̾: MySdoServiceProviderInit() +# - 実装クラス名: MySdoServiceProvider +# - ファイル名: MySdoServiceProvider.py +# - エントリポイント関数名: MySdoServiceProviderInit() # -# ȥݥȴؿ̾ʲΤ褦ˡSdoServiceProviderFactory -# 󥷥塼ޤΥեȥ (ȲΥե󥯥) Ͽʲ -# 褦ʴؿˤʤ롣 +# エントリポイント関数は通常以下のように、SdoServiceProviderFactory +# に当該コンシューマのファクトリ (と解体ファンクタ) を登録する以下の +# ような関数になる。 # #
     #   def MySdoServiceProviderInit(mgr=None):
     #     factory = OpenRTM_aist.SdoServiceProviderFactory.instance()
     #     factory.addFactory(OpenRTM.MySdoService._NP_RepositoryId,
    -#                        MySdoServiceProvider,
    -#                        OpenRTM_aist.Delete)
    +#                        MySdoServiceProvider)
     #     return
     # 
    -# +# # @else # # @endif # class SdoServiceProviderBase(SDOPackage__POA.SDOService): - """ - """ - - def __init__(self): - pass - ## - # @if jp - # @brief ۥǥȥ饯 - # @else - # @brief virtual destructor - # @endif - def __del__(self): - pass - - ## - # @if jp - # @brief 󥷥塼ޥ饹νؿ - # - # Υ֥ȤνԤSDOӥ - # ServiceProfile ȤȤ˥åȡSDO󥷥塼ޤ - # 󥹲졢ľ SDO ӥå줿 RTC Ϳ - # 줿 ServiceProfile ȤƤδؿƤФ롣 - # - # ؿǤϡServiceProfile SDO ӥե󥹤 - # CorbaProvider 饹Ѥ֥ݻȤȤˡ - # properties Ƥɤ߹ߥӥͭԤͿ - # 줿ӥΥ֥ȥե󥹤뤤 - # properties Ƥξͤ false ֤ - # - # @param rtobj Υ֥Ȥ󥹥󥹲줿 RTC - # @param profile Ϳ줿 SDO ServiceProfile - # @return Ϳ줿 SDO Service ServiceProfile ξ false - # - # @else - # @brief Initialization function of the consumer class - # - # @endif - # virtual bool init(RTObject_impl& rtobj, - # const SDOPackage::ServiceProfile& profile) = 0; - def init(self, rtobj, profile): - pass - - - ## - # @if jp - # @brief 󥷥塼ޥ饹κƽؿ - # - # Υ֥ȤκƽԤServiceProfile ˤ id ե - # ɤ˥åͭ UUID åȤƤ뤬Ʊ id ξ - # 硢properties ꤵ줿ѹ䡢service ե - # ΥӥλȤѹԤ롣κݤ˸ƤФΤ - # reinit() ؿǤ롣Ǥϡservice եɤΥ֥ - # ե󥹤ƱǧۤʤäƤݻƤե - # 󥹤򹹿ɬפ롣ޤ properties ˤϿ꤬Ϳ - # ƤǽΤǡƤɤ߹򹹿롣 - # - # @param profile Ϳ줿 SDO ServiceProfile - # @return ServiceProfile Ϳ줿 false - # - # @else - # @brief Reinitialization function of the consumer class - # - # @endif - # virtual bool reinit(const SDOPackage::ServiceProfile& profile) = 0; - def reinit(self, profile): - pass - - - ## - # @if jp - # @brief ServiceProfile ֤ - # - # init()/reinit()Ϳ줿 ServiceProfile ̾索֥ - # ݻ롣SDO Service ե졼ϴ夳Υ֥ - # Ȥб ServiceProfile ɬפȤΤǡδؿǤݻ - # Ƥ ServiceProfile ֤ - # - # @return Υ֥ȤݻƤ ServiceProfile - # - # @else - # @brief Getting ServiceProfile - # @endif - # virtual const SDOPackage::ServiceProfile& getProfile() const = 0; - def getProfile(self): - pass - - - ## - # @if jp - # @brief λ - # - # SDOӥǥåݤ˸ƤӽФ뽪λѴؿ - # ӥΤǥå˺ݤơ֥Ȥݻ꥽ - # ʤɤνԤ - # - # @else - # @brief Finalization - # - # @endif - # virtual void finalize() = 0; - def finalize(self): - poa = OpenRTM_aist.Manager.instance().getPOA() - poa.deactivate_object(poa.servant_to_id(self)) - + """ + """ + + def __init__(self): + pass + ## + # @if jp + # @brief 仮想デストラクタ + # @else + # @brief virtual destructor + # @endif + + def __del__(self): + pass + + ## + # @if jp + # @brief コンシューマクラスの初期化関数 + # + # このオブジェクトの初期化を行う。外部からSDOサービスが + # ServiceProfile とともにアタッチされると、SDOコンシューマがインス + # タンス化され、その直後に SDO サービスがアタッチされた RTC と与え + # られた ServiceProfile を引数としてこの関数が呼ばれる。 + # + # 関数内では、ServiceProfile 内の SDO サービスリファレンスを + # CorbaProvider クラス等を利用しオブジェクト内に保持するとともに、 + # properties から設定内容を読み込みサービス固有の設定等を行う。与 + # えられたサービスのオブジェクトリファレンスが不正、あるいは + # properties の内容が不正、等の場合は戻り値に false を返す。 + # + # @param rtobj このオブジェクトがインスタンス化された RTC + # @param profile 外部から与えられた SDO ServiceProfile + # @return 与えられた SDO Service や ServiceProfile が不正の場合 false + # + # @else + # @brief Initialization function of the consumer class + # + # @endif + # virtual bool init(RTObject_impl& rtobj, + # const SDOPackage::ServiceProfile& profile) = 0; + def init(self, rtobj, profile): + pass + + ## + # @if jp + # @brief コンシューマクラスの再初期化関数 + # + # このオブジェクトの再初期化を行う。ServiceProfile には id フィー + # ルドにセッション固有の UUID がセットされているが、同一の id の場 + # 合、properties に設定された設定情報の変更や、service フィールド + # のサービスの参照の変更が行われる。その際に呼ばれるのがこの + # reinit() 関数である。実装では、service フィールドのオブジェクト + # リファレンスの同一性を確認し、異なっている場合保持しているリファ + # レンスを更新する必要がある。また properties には新たな設定が与え + # られている可能性があるので、内容を読み込み設定を更新する。 + # + # @param profile 新たに与えられた SDO ServiceProfile + # @return 不正な ServiceProfile が与えられた場合は false + # + # @else + # @brief Reinitialization function of the consumer class + # + # @endif + # virtual bool reinit(const SDOPackage::ServiceProfile& profile) = 0; + + def reinit(self, profile): + pass + + ## + # @if jp + # @brief ServiceProfile を返す + # + # init()/reinit()で与えられた ServiceProfile は通常オブジェクト内 + # で保持される。SDO Service 管理フレームワークは管理上このオブジェ + # クトに対応する ServiceProfile を必要とするので、この関数では保持 + # されている ServiceProfile を返す。 + # + # @return このオブジェクトが保持している ServiceProfile + # + # @else + # @brief Getting ServiceProfile + # @endif + # virtual const SDOPackage::ServiceProfile& getProfile() const = 0; + + def getProfile(self): + pass + + ## + # @if jp + # @brief 終了処理 + # + # SDOサービスがでタッチされる際に呼び出される終了処理用関数。サー + # ビスのでタッチに際して、当該オブジェクトが保持するリソースを解放 + # するなどの処理を行う。 + # + # @else + # @brief Finalization + # + # @endif + # virtual void finalize() = 0; + + def finalize(self): + poa = OpenRTM_aist.Manager.instance().getPOA() + poa.deactivate_object(poa.servant_to_id(self)) sdoserviceproviderfactory = None - + ## # @if jp -# @brief SdoServiceProviderFactory typedef +# @brief SdoServiceProviderFactory の typedef # @else # @brief typedef of sdoServiceProviderFactory # @endif # typedef ::coil::GlobalFactory< # ::RTC::SdoServiceProviderBase > SdoServiceProviderFactory; -class SdoServiceProviderFactory(OpenRTM_aist.Factory,SdoServiceProviderBase): - def __init__(self): - OpenRTM_aist.Factory.__init__(self) - return - def __del__(self): - pass - def instance(): - global sdoserviceproviderfactory +class SdoServiceProviderFactory(OpenRTM_aist.Factory, SdoServiceProviderBase): + def __init__(self): + OpenRTM_aist.Factory.__init__(self) + return + + def __del__(self): + pass - if sdoserviceproviderfactory is None: - sdoserviceproviderfactory = SdoServiceProviderFactory() + def instance(): + global sdoserviceproviderfactory - return sdoserviceproviderfactory + if sdoserviceproviderfactory is None: + sdoserviceproviderfactory = SdoServiceProviderFactory() - instance = staticmethod(instance) + return sdoserviceproviderfactory + instance = staticmethod(instance) diff --git a/OpenRTM_aist/SharedMemory.py b/OpenRTM_aist/SharedMemory.py index 46cd9b64..c4dbb309 100644 --- a/OpenRTM_aist/SharedMemory.py +++ b/OpenRTM_aist/SharedMemory.py @@ -1,5 +1,5 @@ #!/usr/bin/env python -# -*- coding: euc-jp -*- +# -*- coding: utf-8 -*- ## # @file SharedMemory.py @@ -9,7 +9,8 @@ # -import mmap, os +import mmap +import os import ctypes from omniORB import cdrMarshal from omniORB import cdrUnmarshal @@ -19,17 +20,15 @@ import OpenRTM - - ## # @if jp # # @class SharedMemory # -# @brief SharedMemory 饹 +# @brief SharedMemory クラス # -# ͭ饹 -# CORBAˤ̿ˤꡢmmapνλʤɤ⡼ȤǤ +# 共有メモリ操作クラス +# CORBAによる通信により、mmapの初期化、終了などがリモートに操作できる # # # @else @@ -42,408 +41,414 @@ # @endif # class SharedMemory(OpenRTM__POA.PortSharedMemory): - default_size = 8 - default_memory_size = 2097152 - - - ## - # @if jp - # @brief 󥹥ȥ饯 - # - # 󥹥ȥ饯 - # - # @param self - # - # @else - # @brief Constructor - # - # Constructor - # - # @param self - # - # @endif - # - def __init__(self): - self._rtcout = OpenRTM_aist.Manager.instance().getLogbuf("SharedMemory") - self._shmem = None - self._smInterface = OpenRTM.PortSharedMemory._nil - self._shm_address = "" - self._memory_size = SharedMemory.default_memory_size - self._endian = True - if os.name == "nt": - pass - else: - #from ctypes.util import find_library - #librt = find_library("librt") - #if librt is None: - # raise - #self.rt = ctypes.CDLL(librt) - try: - self.rt = ctypes.CDLL('librt.so') - except: - self.rt = ctypes.CDLL('librt.so.1') - self.rt.shm_open.argtypes = [ctypes.c_char_p, ctypes.c_int, ctypes.c_int] - self.rt.shm_open.restype = ctypes.c_int - self.rt.ftruncate.argtypes = [ctypes.c_int, ctypes.c_int] - self.rt.ftruncate.restype = ctypes.c_int - self.rt.close.argtypes = [ctypes.c_int] - self.rt.close.restype = ctypes.c_int - self.rt.shm_unlink.argtypes = [ctypes.c_char_p] - self.rt.shm_unlink.restype = ctypes.c_int - - self.fd = -1 - return - - - - ## - # @if jp - # @brief ǥȥ饯 - # - # ǥȥ饯 - # - # @param self - # - # @else - # @brief Destructor - # - # Destructor - # - # @param self - # @endif - # - def __del__(self): - self._rtcout.RTC_PARANOID("~SharedMemory()") - return - - - ## - # @if jp - # @brief ʸǻꤷǡͤѴ - # 1M 1048576 - # 1k 1024 - # 100 100 - # - # - # @param self - # @param size_str ǡ(ʸ) - # @return ǡ() - # - # @else - # @brief - # - # @param self - # @param size_str - # @return - # - # @endif - # - # int string_to_MemorySize(string size_str); - def string_to_MemorySize(self, size_str): - memory_size = SharedMemory.default_memory_size - if size_str: - if size_str[-1] == "M": - memory_size = 1048576 * int(size_str[0:-1]) - elif size_str[-1] == "k": - memory_size = 1024 * int(size_str[0:-1]) - else: - memory_size = int(size_str) - return memory_size - - - - ## - # @if jp - # @brief ͭν - # windowsǤϥڡ󥰥եΰݤ - # LinuxǤ/dev/shmʲ˥ե - # եƤۥɥ쥹˥ޥåԥ󥰤 - # - # - # - # @param self - # @param memory_size ͭΥ - # @param shm_address ̾ - # - # @else - # @brief - # - # @param memory_size - # @param shm_address - # - # @endif - # - # void create_memory(int memory_size, string shm_address); - def create_memory(self, memory_size, shm_address): - - - if self._shmem is None: - self._rtcout.RTC_TRACE("create():memory_size="+str(memory_size)+",shm_address="+str(shm_address)) - self._memory_size = memory_size - self._shm_address = shm_address - - if os.name == "nt": - self._shmem = mmap.mmap(0, self._memory_size, self._shm_address, mmap.ACCESS_WRITE) - else: - O_RDWR = 2 - O_CREAT = 64 - - S_IRUSR = 256 - S_IWUSR = 128 - S_IRGRP = 32 - S_IWGRP = 16 - S_IROTH = 4 - - self.fd = self.rt.shm_open(self._shm_address,O_RDWR | O_CREAT,S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP|S_IROTH) - if self.fd < 0: - return - self.rt.ftruncate(self.fd, self._memory_size) - self._shmem = mmap.mmap(self.fd, self._memory_size, mmap.MAP_SHARED) - self.rt.close( self.fd ) - - - if not CORBA.is_nil(self._smInterface): - self._smInterface.open_memory(self._memory_size, self._shm_address) - - - - ## - # @if jp - # @brief ͭΥޥåԥ󥰤Ԥ - # - # - # - # @param self - # @param memory_size ͭΥ - # @parama shm_address ̾ - # - # @else - # @brief - # - # @param memory_size - # @parama shm_address - # - # @endif - # - # void open_memory(int memory_size, string shm_address); - def open_memory(self, memory_size, shm_address): - self._rtcout.RTC_TRACE("open():memory_size="+str(memory_size)+",shm_address="+str(shm_address)) - self._memory_size = memory_size - self._shm_address = shm_address - if self._shmem is None: - if os.name == "nt": - self._shmem = mmap.mmap(0, self._memory_size, self._shm_address, mmap.ACCESS_WRITE) - else: - O_RDWR = 2 - self.fd = self.rt.shm_open(self._shm_address,O_RDWR,0) - if self.fd < 0: - return - self.rt.ftruncate(self.fd, self._memory_size) - self._shmem = mmap.mmap(self.fd, self._memory_size, mmap.MAP_SHARED) - self.rt.close( self.fd ) - - - - ## - # @if jp - # @brief ޥåԥ󥰤ͭ򥢥ޥåפ - # - # - # - # @param self - # @param unlink Linux/dev/shmʲ˺եTrueˤ - # - # @else - # @brief - # - # @param self - # @param unlink - # - # @endif - # - # void close_memory(boolean unlink); - def close_memory(self, unlink=False): - self._rtcout.RTC_TRACE("open()") - if self._shmem: - self._shmem.close() - if os.name == "nt": - pass - else: - if unlink: - self.rt.shm_unlink(self._shm_address) - self._shmem = None - - try: - if not CORBA.is_nil(self._smInterface) and self._smInterface._non_existent(): - self._smInterface.close_memory(False) - except: - pass - - - - - - ## - # @if jp - # @brief ǡ񤭹 - # Ƭ8byte˥ǡ񤭹ߡθ˥ǡ񤭹 - # ꤷǡͭΥä硢ͭνԤ - # - # - # - # @param self - # @param data 񤭹ǡ - # - # @else - # @brief - # - # @param self - # @param data - # - # - # @endif - # - # void write(const cdrMemoryStream& data); - def write(self, data): - self._rtcout.RTC_TRACE("write()") - - if self._shmem: - data_size = len(data) - - - if data_size + SharedMemory.default_size > self._memory_size: - self._memory_size = data_size + SharedMemory.default_size - - if not CORBA.is_nil(self._smInterface): - self._smInterface.close_memory(False) - - - self.close_memory(True) - self.create_memory(self._memory_size, self._shm_address) - - - - data_size_cdr = cdrMarshal(CORBA.TC_ulonglong, data_size, self._endian) - - self._shmem.seek(os.SEEK_SET) - self._shmem.write(data_size_cdr) - self._shmem.write(data) - - - ## - # @if jp - # @brief ǡɤ߹ - # - # - # - # @param self - # @return ǡ - # - # @else - # @brief - # - # @param self - # @return - # - # @endif - # - # cdrMemoryStream read(data); - def read(self): - self._rtcout.RTC_TRACE("read()") - if self._shmem: - - self._shmem.seek(os.SEEK_SET) - - data_size_cdr = self._shmem.read(SharedMemory.default_size) - data_size = cdrUnmarshal(CORBA.TC_ulonglong, data_size_cdr, self._endian) - - - - shm_data = self._shmem.read(data_size) - - return shm_data - return "" - - - - ## - # @if jp - # @brief ̿CORBA󥿡եϿ - # Ͽˤ궦ͭνȤˡ̿Ǥޥåԥ󥰤ľȤǤ - # - # - # - # @param self - # @param sm SharedMemoryΥ֥ȥե - # - # @else - # @brief - # - # - # @endif - # - # void setInterface(::OpenRTM::PortSharedMemory_var sm); - def setInterface(self, sm): - self._smInterface = sm - - - ## - # @if jp - # @brief ǥꤹ - # - # - # - # @param self - # @param endian ǥ - # - # @else - # @brief - # - # @param self - # @param endian endian - # - # @endif - # - # void setEndian(bool endian); - def setEndian(self, endian): - self._endian = endian - if not CORBA.is_nil(self._smInterface): - self._smInterface.setEndian(self._endian) - - ## - # @if jp - # @brief ǡΤ餻 - # - # - # - # @param self - # - # @else - # @brief - # - # @param self - # - # @endif - # - # PortStatus put(); - def put(self): - return OpenRTM.UNKNOWN_ERROR - - ## - # @if jp - # @brief ǡ׵᤹ - # - # - # - # @param self - # - # @else - # @brief - # - # @param self - # - # @endif - # - # PortStatus get(); - def get(self): - return OpenRTM.UNKNOWN_ERROR \ No newline at end of file + default_size = 8 + default_memory_size = 2097152 + + ## + # @if jp + # @brief コンストラクタ + # + # コンストラクタ + # + # @param self + # + # @else + # @brief Constructor + # + # Constructor + # + # @param self + # + # @endif + # + + def __init__(self): + self._rtcout = OpenRTM_aist.Manager.instance().getLogbuf("SharedMemory") + self._shmem = None + self._smInterface = OpenRTM.PortSharedMemory._nil + self._shm_address = "" + self._memory_size = SharedMemory.default_memory_size + self._endian = True + if os.name == "nt": + pass + else: + #from ctypes.util import find_library + #librt = find_library("librt") + # if librt is None: + # raise + #self.rt = ctypes.CDLL(librt) + try: + self.rt = ctypes.CDLL('librt.so') + except BaseException: + self.rt = ctypes.CDLL('librt.so.1') + self.rt.shm_open.argtypes = [ + ctypes.c_char_p, ctypes.c_int, ctypes.c_int] + self.rt.shm_open.restype = ctypes.c_int + self.rt.ftruncate.argtypes = [ctypes.c_int, ctypes.c_int] + self.rt.ftruncate.restype = ctypes.c_int + self.rt.close.argtypes = [ctypes.c_int] + self.rt.close.restype = ctypes.c_int + self.rt.shm_unlink.argtypes = [ctypes.c_char_p] + self.rt.shm_unlink.restype = ctypes.c_int + + self.fd = -1 + return + + ## + # @if jp + # @brief デストラクタ + # + # デストラクタ + # + # @param self + # + # @else + # @brief Destructor + # + # Destructor + # + # @param self + # @endif + # + + def __del__(self): + self._rtcout.RTC_PARANOID("~SharedMemory()") + return + + ## + # @if jp + # @brief 文字列で指定したデータサイズを数値に変換する + # 1M → 1048576 + # 1k → 1024 + # 100 → 100 + # + # + # @param self + # @param size_str データサイズ(文字列) + # @return データサイズ(数値) + # + # @else + # @brief + # + # @param self + # @param size_str + # @return + # + # @endif + # + # int string_to_MemorySize(string size_str); + + def string_to_MemorySize(self, size_str): + memory_size = SharedMemory.default_memory_size + if size_str: + if size_str[-1] == "M": + memory_size = 1048576 * int(size_str[0:-1]) + elif size_str[-1] == "k": + memory_size = 1024 * int(size_str[0:-1]) + else: + memory_size = int(size_str) + return memory_size + + ## + # @if jp + # @brief 共有メモリの初期化 + # windowsではページングファイル上に領域を確保する + # Linuxでは/dev/shm以下にファイルを作成する + # 作成したファイルの内容を仮想アドレスにマッピングする + # + # + # + # @param self + # @param memory_size 共有メモリのサイズ + # @param shm_address 空間名 + # + # @else + # @brief + # + # @param memory_size + # @param shm_address + # + # @endif + # + # void create_memory(int memory_size, string shm_address); + def create_memory(self, memory_size, shm_address): + + if self._shmem is None: + self._rtcout.RTC_TRACE( + "create():memory_size=" + + str(memory_size) + + ",shm_address=" + + str(shm_address)) + self._memory_size = memory_size + self._shm_address = shm_address + + if os.name == "nt": + self._shmem = mmap.mmap( + 0, self._memory_size, self._shm_address, mmap.ACCESS_WRITE) + else: + O_RDWR = 2 + O_CREAT = 64 + + S_IRUSR = 256 + S_IWUSR = 128 + S_IRGRP = 32 + S_IWGRP = 16 + S_IROTH = 4 + + self.fd = self.rt.shm_open( + self._shm_address, + O_RDWR | O_CREAT, + S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH) + if self.fd < 0: + return + self.rt.ftruncate(self.fd, self._memory_size) + self._shmem = mmap.mmap( + self.fd, self._memory_size, mmap.MAP_SHARED) + self.rt.close(self.fd) + + if self._smInterface is not None: + self._smInterface.open_memory( + self._memory_size, self._shm_address) + + ## + # @if jp + # @brief 共有メモリのマッピングを行う + # + # + # + # @param self + # @param memory_size 共有メモリのサイズ + # @parama shm_address 空間名 + # + # @else + # @brief + # + # @param memory_size + # @parama shm_address + # + # @endif + # + # void open_memory(int memory_size, string shm_address); + + def open_memory(self, memory_size, shm_address): + self._rtcout.RTC_TRACE( + "open():memory_size=" + + str(memory_size) + + ",shm_address=" + + str(shm_address)) + self._memory_size = memory_size + self._shm_address = shm_address + if self._shmem is None: + if os.name == "nt": + self._shmem = mmap.mmap( + 0, self._memory_size, self._shm_address, mmap.ACCESS_WRITE) + else: + O_RDWR = 2 + self.fd = self.rt.shm_open(self._shm_address, O_RDWR, 0) + if self.fd < 0: + return + self.rt.ftruncate(self.fd, self._memory_size) + self._shmem = mmap.mmap( + self.fd, self._memory_size, mmap.MAP_SHARED) + self.rt.close(self.fd) + + ## + # @if jp + # @brief マッピングした共有メモリをアンマップする + # + # + # + # @param self + # @param unlink Linuxで/dev/shm以下に作成したファイルを削除する場合にTrueにする + # + # @else + # @brief + # + # @param self + # @param unlink + # + # @endif + # + # void close_memory(boolean unlink); + + def close_memory(self, unlink=False): + self._rtcout.RTC_TRACE("open()") + if self._shmem: + self._shmem.close() + if os.name == "nt": + pass + else: + if unlink: + self.rt.shm_unlink(self._shm_address) + self._shmem = None + + try: + if self._smInterface is not None and self._smInterface._non_existent(): + self._smInterface.close_memory(False) + except BaseException: + pass + + ## + # @if jp + # @brief データを書き込む + # 先頭8byteにデータサイズを書き込み、その後ろにデータを書き込む + # 設定したデータサイズが共有メモリのサイズを上回った場合、共有メモリの初期化を行う + # + # + # + # @param self + # @param data 書き込むデータ + # + # @else + # @brief + # + # @param self + # @param data + # + # + # @endif + # + # void write(const cdrMemoryStream& data); + + def write(self, data): + self._rtcout.RTC_TRACE("write()") + + if self._shmem: + data_size = len(data) + + if data_size + SharedMemory.default_size > self._memory_size: + self._memory_size = data_size + SharedMemory.default_size + + if self._smInterface is not None: + self._smInterface.close_memory(False) + + self.close_memory(True) + self.create_memory(self._memory_size, self._shm_address) + + data_size_cdr = cdrMarshal( + CORBA.TC_ulonglong, data_size, self._endian) + + self._shmem.seek(os.SEEK_SET) + self._shmem.write(data_size_cdr) + self._shmem.write(data) + + ## + # @if jp + # @brief データを読み込む + # + # + # + # @param self + # @return データ + # + # @else + # @brief + # + # @param self + # @return + # + # @endif + # + # cdrMemoryStream read(data); + + def read(self): + self._rtcout.RTC_TRACE("read()") + if self._shmem: + + self._shmem.seek(os.SEEK_SET) + + data_size_cdr = self._shmem.read(SharedMemory.default_size) + data_size = cdrUnmarshal( + CORBA.TC_ulonglong, data_size_cdr, self._endian) + + shm_data = self._shmem.read(data_size) + + return shm_data + return "" + + ## + # @if jp + # @brief 通信先のCORBAインターフェースを登録する + # 登録する事により共有メモリの初期化したときに、通信先でもマッピングをやり直すことができる + # + # + # + # @param self + # @param sm SharedMemoryのオブジェクトリファレンス + # + # @else + # @brief + # + # + # @endif + # + # void setInterface(::OpenRTM::PortSharedMemory_var sm); + + def setInterface(self, sm): + if isinstance(sm, SharedMemory): + self._smInterface = sm + else: + if not CORBA.is_nil(sm): + self._smInterface = sm + + ## + # @if jp + # @brief エンディアンを設定する + # + # + # + # @param self + # @param endian エンディアン + # + # @else + # @brief + # + # @param self + # @param endian endian + # + # @endif + # + # void setEndian(bool endian); + + def setEndian(self, endian): + self._endian = endian + if self._smInterface is not None: + self._smInterface.setEndian(self._endian) + + ## + # @if jp + # @brief データの送信を知らせる + # + # + # + # @param self + # + # @else + # @brief + # + # @param self + # + # @endif + # + # PortStatus put(); + def put(self): + return OpenRTM.UNKNOWN_ERROR + + ## + # @if jp + # @brief データの送信を要求する + # + # + # + # @param self + # + # @else + # @brief + # + # @param self + # + # @endif + # + # PortStatus get(); + def get(self): + return OpenRTM.UNKNOWN_ERROR diff --git a/OpenRTM_aist/SimulatorExecutionContext.py b/OpenRTM_aist/SimulatorExecutionContext.py index 76068241..9bf954f0 100644 --- a/OpenRTM_aist/SimulatorExecutionContext.py +++ b/OpenRTM_aist/SimulatorExecutionContext.py @@ -1,5 +1,5 @@ #!/usr/bin/env python -# -*- coding: euc-jp -*- +# -*- coding: utf-8 -*- ## # @file SimulatorExecutionContext.py @@ -17,186 +17,186 @@ import time import OpenRTM_aist -import OpenRTM__POA, RTC +import OpenRTM__POA +import RTC class SimulatorExecutionContext(OpenRTM_aist.OpenHRPExecutionContext): - """ - """ - - ## - # @if jp - # @brief 󥹥ȥ饯 - # - # 󥹥ȥ饯 - # - # @param self - # - # @else - # @brief Constructor - # - # Constructor - # - # @param self - # - # @endif - # - def __init__(self): - OpenRTM_aist.OpenHRPExecutionContext.__init__(self) - return - - ## - # @if jp - # @brief ǥȥ饯 - # - # ǥȥ饯 - # - # @param self - # - # @else - # @brief Destructor - # - # Destructor - # - # @param self - # @endif - # - def __del__(self): - return - - - ## - # @if jp - # @brief оݤRTC򥢥ƥֲ - # invokeWorkerPreDoؿƤ֤ᡢ¨¤ - # ֤ܤ뤳ȤǤ롣 - # tick¹ξϼ¹ԽλޤԤ - # - # @param self - # @param comp ƥֲоRTݡͥ - # @return ReturnCode_t Υ꥿󥳡 - # - # @else - # @brief Activate an RT-component - # - # - # @param self - # @param comp The target RT-Component for activation - # @return The return code of ReturnCode_t type - # - # @endif - # - def activate_component(self, comp): - guard = OpenRTM_aist.ScopedLock(self._tickmutex) - rtobj = self._worker.findComponent(comp) - if not rtobj: - return RTC.BAD_PARAMETER - if not rtobj.isCurrentState(RTC.INACTIVE_STATE): - return RTC.PRECONDITION_NOT_MET - - self._syncActivation = False - OpenRTM_aist.ExecutionContextBase.activateComponent(self, comp) - - self.invokeWorkerPreDo() - - if rtobj.isCurrentState(RTC.ACTIVE_STATE): - return RTC.RTC_OK - - return RTC.RTC_ERROR - - - ## - # @if jp - # @brief оݤRTC󥢥ƥֲ - # invokeWorkerPreDoؿƤ֤ᡢ¨¤ - # ֤ܤ뤳ȤǤ롣 - # tick¹ξϼ¹ԽλޤԤ - # - # @param self - # @param comp 󥢥ƥֲоRTݡͥ - # @return ReturnCode_t Υ꥿󥳡 - # - # @else - # @brief Deactivate an RT-component - # - # - # @param self - # @param comp The target RT-Component for deactivation - # @return The return code of ReturnCode_t type - # - # @endif - # - def deactivate_component(self, comp): - guard = OpenRTM_aist.ScopedLock(self._tickmutex) - rtobj = self._worker.findComponent(comp) - if not rtobj: - return RTC.BAD_PARAMETER - if not rtobj.isCurrentState(RTC.ACTIVE_STATE): - return RTC.PRECONDITION_NOT_MET - - self._syncDeactivation = False - OpenRTM_aist.ExecutionContextBase.deactivateComponent(self, comp) - - self.invokeWorkerPreDo() - self.invokeWorkerDo() - self.invokeWorkerPostDo() - - if rtobj.isCurrentState(RTC.INACTIVE_STATE): - return RTC.RTC_OK - - return RTC.RTC_ERROR - - ## - # @if jp - # @brief оݤRTCꥻåȲ - # invokeWorkerPreDoؿƤ֤ᡢ¨¤ - # ֤ܤ뤳ȤǤ롣 - # tick¹ξϼ¹ԽλޤԤ - # - # @param self - # @param comp ꥻåоRTݡͥ - # @return ReturnCode_t Υ꥿󥳡 - # - # @else - # @brief Reset an RT-component - # - # - # @param self - # @param comp The target RT-Component for reset - # @return The return code of ReturnCode_t type - # - # @endif - # - def reset_component(self, comp): - guard = OpenRTM_aist.ScopedLock(self._tickmutex) - rtobj = self._worker.findComponent(comp) - if not rtobj: - return RTC.BAD_PARAMETER - if not rtobj.isCurrentState(RTC.ERROR_STATE): - return RTC.PRECONDITION_NOT_MET - - self._syncReset = False - OpenRTM_aist.ExecutionContextBase.resetComponent(self, comp) - - self.invokeWorkerPreDo() - self.invokeWorkerDo() - self.invokeWorkerPostDo() - - if rtobj.isCurrentState(RTC.INACTIVE_STATE): - return RTC.RTC_OK - - return RTC.RTC_ERROR + """ + """ + + ## + # @if jp + # @brief コンストラクタ + # + # コンストラクタ + # + # @param self + # + # @else + # @brief Constructor + # + # Constructor + # + # @param self + # + # @endif + # + def __init__(self): + OpenRTM_aist.OpenHRPExecutionContext.__init__(self) + return + + ## + # @if jp + # @brief デストラクタ + # + # デストラクタ + # + # @param self + # + # @else + # @brief Destructor + # + # Destructor + # + # @param self + # @endif + # + def __del__(self): + return + + ## + # @if jp + # @brief 対象のRTCをアクティブ化する + # 内部でinvokeWorkerPreDo関数を呼ぶため、即座に + # 状態を遷移させることができる。 + # 現在tick実行中の場合は実行終了まで待つ + # + # @param self + # @param comp アクティブ化対象RTコンポーネント + # @return ReturnCode_t 型のリターンコード + # + # @else + # @brief Activate an RT-component + # + # + # @param self + # @param comp The target RT-Component for activation + # @return The return code of ReturnCode_t type + # + # @endif + # + + def activate_component(self, comp): + guard = OpenRTM_aist.ScopedLock(self._tickmutex) + rtobj = self._worker.findComponent(comp) + if not rtobj: + return RTC.BAD_PARAMETER + if not rtobj.isCurrentState(RTC.INACTIVE_STATE): + return RTC.PRECONDITION_NOT_MET + + self._syncActivation = False + OpenRTM_aist.ExecutionContextBase.activateComponent(self, comp) + + self.invokeWorkerPreDo() + + if rtobj.isCurrentState(RTC.ACTIVE_STATE): + return RTC.RTC_OK + + return RTC.RTC_ERROR + + ## + # @if jp + # @brief 対象のRTCを非アクティブ化する + # 内部でinvokeWorkerPreDo関数を呼ぶため、即座に + # 状態を遷移させることができる。 + # 現在tick実行中の場合は実行終了まで待つ + # + # @param self + # @param comp 非アクティブ化対象RTコンポーネント + # @return ReturnCode_t 型のリターンコード + # + # @else + # @brief Deactivate an RT-component + # + # + # @param self + # @param comp The target RT-Component for deactivation + # @return The return code of ReturnCode_t type + # + # @endif + # + + def deactivate_component(self, comp): + guard = OpenRTM_aist.ScopedLock(self._tickmutex) + rtobj = self._worker.findComponent(comp) + if not rtobj: + return RTC.BAD_PARAMETER + if not rtobj.isCurrentState(RTC.ACTIVE_STATE): + return RTC.PRECONDITION_NOT_MET + + self._syncDeactivation = False + OpenRTM_aist.ExecutionContextBase.deactivateComponent(self, comp) + + self.invokeWorkerPreDo() + self.invokeWorkerDo() + self.invokeWorkerPostDo() + + if rtobj.isCurrentState(RTC.INACTIVE_STATE): + return RTC.RTC_OK + + return RTC.RTC_ERROR + + ## + # @if jp + # @brief 対象のRTCをリセット化する + # 内部でinvokeWorkerPreDo関数を呼ぶため、即座に + # 状態を遷移させることができる。 + # 現在tick実行中の場合は実行終了まで待つ + # + # @param self + # @param comp リセット対象RTコンポーネント + # @return ReturnCode_t 型のリターンコード + # + # @else + # @brief Reset an RT-component + # + # + # @param self + # @param comp The target RT-Component for reset + # @return The return code of ReturnCode_t type + # + # @endif + # + def reset_component(self, comp): + guard = OpenRTM_aist.ScopedLock(self._tickmutex) + rtobj = self._worker.findComponent(comp) + if not rtobj: + return RTC.BAD_PARAMETER + if not rtobj.isCurrentState(RTC.ERROR_STATE): + return RTC.PRECONDITION_NOT_MET + + self._syncReset = False + OpenRTM_aist.ExecutionContextBase.resetComponent(self, comp) + + self.invokeWorkerPreDo() + self.invokeWorkerDo() + self.invokeWorkerPostDo() + + if rtobj.isCurrentState(RTC.INACTIVE_STATE): + return RTC.RTC_OK + + return RTC.RTC_ERROR ## # @if jp -# @brief ECFactoryؤϿΤνؿ +# @brief ECFactoryへの登録のための初期化関数 # @else # @brief Initialization function to register to ECFactory # @endif # def SimulatorExecutionContextInit(manager): - OpenRTM_aist.ExecutionContextFactory.instance().addFactory("SimulatorExecutionContext", - OpenRTM_aist.SimulatorExecutionContext, - OpenRTM_aist.ECDelete) - return + OpenRTM_aist.ExecutionContextFactory.instance().addFactory("SimulatorExecutionContext", + OpenRTM_aist.SimulatorExecutionContext) + return diff --git a/OpenRTM_aist/Singleton.py b/OpenRTM_aist/Singleton.py index 23bc0af7..00e0f2a0 100644 --- a/OpenRTM_aist/Singleton.py +++ b/OpenRTM_aist/Singleton.py @@ -1,5 +1,5 @@ -#/usr/bin/env python -# -*- coding: euc-jp -*- +#!/usr/bin/env python +# -*- coding: utf-8 -*- ## # @file Singleton.h @@ -27,36 +27,35 @@ ## # @if jp -# @class Singleton 饹ƥץ졼 +# @class Singleton クラステンプレート # -# Υƥץ졼ȤϡǤդΥ饹 Singleton ˤƥץ졼ȤǤ롣 -# ʲΤ褦ˤƻѤ롣 +# このテンプレートは、任意のクラスを Singleton にするテンプレートである。 +# 以下のようにして使用する。 # # class A(Singleton): # def __init__(self): # pass -class Singleton(object): - __lockObj = allocate_lock() - __instance = None - - def __new__(self, *args, **kargs): - return self.instance(*args, **kargs) - def __init__(self, *args, **kargs): - self.instance(*args, **kargs) +class Singleton(object): + __lockObj = allocate_lock() + __instance = None + def __new__(self, *args, **kargs): + return self.instance(*args, **kargs) - def instance(self, *args, **kargs): - self.__lockObj.acquire() - try: - if self.__instance is None: - self.__instance = object.__new__(self, *args, **kargs) + def __init__(self, *args, **kargs): + self.instance(*args, **kargs) - finally: - self.__lockObj.release() + def instance(self, *args, **kargs): + self.__lockObj.acquire() + try: + if self.__instance is None: + self.__instance = object.__new__(self, *args, **kargs) - return self.__instance + finally: + self.__lockObj.release() - instance = classmethod(instance) + return self.__instance + instance = classmethod(instance) diff --git a/OpenRTM_aist/StateMachine.py b/OpenRTM_aist/StateMachine.py index 17039d7c..a8817171 100644 --- a/OpenRTM_aist/StateMachine.py +++ b/OpenRTM_aist/StateMachine.py @@ -1,5 +1,5 @@ #!/usr/bin/env python -# -*- coding: euc-jp -*- +# -*- coding: utf-8 -*- ## # @file StateMachine.py @@ -24,12 +24,12 @@ ## # @if jp # @class StateHolder -# @brief ݻѥ饹 -# -# ֤ݻ뤿Υۥ饹 -# ߤξ֤ȡξ֡ͽξ֤ݻ롣 +# @brief 状態保持用クラス # -# @param State ݻ֤η +# 状態を保持するためのホルダークラス。 +# 現在の状態と、1つ前の状態、遷移予定の状態を保持する。 +# +# @param State 保持する状態の型 # # @since 0.4.0 # @@ -37,10 +37,10 @@ # # @endif class StateHolder: - def __init__(self): - self.curr = None - self.prev = None - self.next = None + def __init__(self): + self.curr = None + self.prev = None + self.next = None ## @@ -48,56 +48,56 @@ def __init__(self): # # @class StateMachine # -# @brief ֥ޥ󥯥饹 +# @brief 状態マシンクラス # -# StateMachine 饹Ͼ֥ޥ¸륯饹Ǥ롣 +# StateMachine クラスは状態マシンを実現するクラスである。 # -# : ActiveObjectϾ֥ޥĥƥ֥֥ȤǤȤ롣 -# ֤3 INACTIVE, ACTIVE, ERROR ꡢƾ֤ǤEntryExitư -# ȤȡʲΤ褦˼¸롣 +# 例: ActiveObjectは状態マシンを持つアクティブオブジェクトであるとする。 +# 状態は3状態 INACTIVE, ACTIVE, ERROR があり、各状態でのEntryやExit動作を +# 定義したいとすると、以下のように実現される。 #
     # class ActiveObject:
     #   class MyState:
     #     INACTIVE, ACTIVE, ERROR = range(3)
    -# 
    +#
     #   def __init__(self):
     #     m_sm = StateMachine(3)
     #     m_sm.setNOP(nullAction)
     #     m_sm.setListener(self)
    -# 
    +#
     #     m_sm.setExitAction(MyState.INACTIVE, self.inactiveExit)
    -#       : 
    +#       :
     #     m_sm.setPostDoAction(MyState.ERROR, self.errorPostDo)
    -#     m_sm.setTransitionAction(self.transition); 
    -# 
    +#     m_sm.setTransitionAction(self.transition);
    +#
     #   def nullAction(myStates):
     #     pass
     #   def inactiveExit(myStates):
     #     pass
    -#     : 
    +#     :
     #   def errorPostDo(myStates):
     #     pass
     #   def transition(myStates:
     #     pass
     # 
    -# ֤饹ϰʲξ褦˼ʤФʤʤ +# 状態を持たせたいクラスは以下の条件を満たすように実装しなければならない。 #
      -#
    1. 饹Ǿ֤ -#
    2. StateMachine Υ󥹥ȥ饯Ͼ֤ο -#
    3. ʲΥؿ(Return _function_name_(States)) δؿȤ +#
    4. 内部クラスで状態を定義 +#
    5. StateMachine のコンストラクタ引数は状態の数 +#
    6. 以下のアクション関数を(Return _function_name_(States)) の関数として設定 #
        -#
      1. ⤷ʤؿɬsetNOP ͿʤФʤʤ -#
      2. ƾ, set(Entry|PreDo|Do|PostDo|Exit)Action ǥ -#
      3. ܻΥ setTransitionAction() ꡣ +#
      4. 何もしない関数を必ず定義し、setNOP で与えなければならない +#
      5. 各状態毎に, set(Entry|PreDo|Do|PostDo|Exit)Action でアクションを設定 +#
      6. 状態遷移時のアクションを setTransitionAction() で設定。 #
      -#
    7. ܻΥϡͿ줿߾֤֡֡򸵤ˡ -# 桼ʤФʤʤ -#
    8. ֤ѹ goTo() ǡ֤Υå isIn(state) ǹԤ -#
    9. goTo()ϼ֤Ū˥åȤؿǤꡢܤβݤϡ -# 桼߾֤ȽǤåʤФʤʤ +#
    10. 遷移時のアクションは、与えられた現在状態、次状態、前状態を元に、 +# ユーザが実装しなければならない。 +#
    11. 状態の変更は goTo() で、状態のチェックは isIn(state) で行う。 +#
    12. goTo()は次状態を強制的にセットする関数であり、遷移の可否は、 +# ユーザが現在状態を取得し判断するロジックを実装しなければならない。 #
    # -# Υ饹ϡĤξ֤Фơ +# このクラスは、一つの状態に対して、 #
      #
    • Entry action #
    • PreDo action @@ -105,23 +105,23 @@ def __init__(self): #
    • PostDo action #
    • Exit action #
    -# 5ĤΥ뤳ȤǤ롣 -# Transition action ϤִܤǸƤӽФ륢ǡ -# ο񤤤ϥ桼ʤФʤʤ -# -# Υ饹ϰʲΤ褦ʥߥ󥰤dzƥ󤬼¹Ԥ롣 +# 5つのアクションが定義することができる。 +# Transition action はあらゆる状態間遷移で呼び出されるアクションで、 +# その振る舞いはユーザが定義しなければならない。 +# +# このクラスは以下のようなタイミングで各アクションが実行される。 # #
      -#
    • ֤ѹ(A->B)֤ܤ
      -# (A:Exit)->|(ֹ:A->B)->(B:Entry)->(B:PreDo)->(B:Do)->(B:PostDo) +#
    • 状態が変更され(A->B)状態が遷移する場合
      +# (A:Exit)->|(状態更新:A->B)->(B:Entry)->(B:PreDo)->(B:Do)->(B:PostDo) # -#
    • ֤ѹ줺B֤ݻ (|ϥƥåפζڤɽ)
      +#
    • 状態が変更されず、B状態を維持する場合 (|はステップの区切りを表す)
      # (B(n-1):PostDo)->|(B(n):PreDo)->(B(n):Do)->(B(n):PostDo)->|(B(n+1):PreDo)
      -# PreDo, Do, PostDo ֤¹Ԥ롣 +# PreDo, Do, PostDo が繰り返し実行される。 # -#
    • ܤ
      +#
    • 自己遷移する場合
      # (B(n-1):PostDo)->(B(n-1):Exit)->|(B(n):Entry)->(B(n):PreDo)
      -# ö Exit ƤФ줿塢Entry ¹Ԥ졢ʹߤƱư򤹤롣 +# 一旦 Exit が呼ばれた後、Entry が実行され、以降は前項と同じ動作をする。 #
    # # @since 0.4.0 @@ -132,480 +132,478 @@ def __init__(self): # # @endif class StateMachine: - """ - """ - - state_array = (RTC.CREATED_STATE, - RTC.INACTIVE_STATE, - RTC.ACTIVE_STATE, - RTC.ERROR_STATE) - - ## - # @if jp - # @brief 󥹥ȥ饯 - # - # 󥹥ȥ饯 - # - # @param self - # @param num_of_state ơȥޥξֿ - # - # @else - # @brief Constructor - # @endif - def __init__(self, num_of_state): - self._num = num_of_state - self._listener = None - self._entry = {} - self._predo = {} - self._do = {} - self._postdo = {} - self._exit = {} - - self.setNullFunc(self._entry, None) - self.setNullFunc(self._do, None) - self.setNullFunc(self._exit, None) - self.setNullFunc(self._predo, None) - self.setNullFunc(self._postdo, None) - self._transit = None - self._selftrans = False - self._mutex = threading.RLock() - - - ## - # @if jp - # @brief NOPؿϿ - # - # NOPؿ(⤷ʤؿ)Ͽ롣 - # - # @param self - # @param call_back Хåؿ - # - # @else - # @brief Set NOP function - # @endif - def setNOP(self, call_back): - self.setNullFunc(self._entry, call_back) - self.setNullFunc(self._do, call_back) - self.setNullFunc(self._exit, call_back) - self.setNullFunc(self._predo, call_back) - self.setNullFunc(self._postdo, call_back) - self._transit = call_back - - - ## - # @if jp - # @brief Listener ֥ȤϿ - # - # Ƽ異¹Ի˸ƤӽФ Listener ֥ȤϿ롣 - # - # @param self - # @param listener Listener ֥ - # - # @else - # @brief Set Listener Object - # @endif - def setListener(self, listener): - assert(listener) - self._listener = listener - return - - - ## - # @if jp - # @brief Entry action ؿϿ - # - # ƾ֤äݤ˼¹Ԥ Entry action ѥХåؿϿ롣 - # - # @param self - # @param state Ͽоݾ - # @param call_back Entry action ѥХåؿ - # - # @return ¹Է - # - # @else - # @brief Set Entry action function - # @endif - def setEntryAction(self, state, call_back): - if state in self._entry: - self._entry[state] = call_back - else: - return False - return True - - - ## - # @if jp - # @brief PreDo action ؿϿ - # - # ƾǼ¹Ԥ PreDo action ѥХåؿϿ롣 - # - # @param self - # @param state Ͽоݾ - # @param call_back PreDo action ѥХåؿ - # - # @return ¹Է - # - # @else - # @brief Set PreDo action function - # @endif - def setPreDoAction(self, state, call_back): - if state in self._predo: - self._predo[state] = call_back - else: - return False - return True - - - ## - # @if jp - # @brief Do action ؿϿ - # - # ƾǼ¹Ԥ Do action ѥХåؿϿ롣 - # - # @param self - # @param state Ͽоݾ - # @param call_back Do action ѥХåؿ - # - # @return ¹Է - # - # @else - # @brief Set Do action function - # @endif - def setDoAction(self, state, call_back): - if state in self._do: - self._do[state] = call_back - else: - return False - return True - - - ## - # @if jp - # @brief PostDo action ؿϿ - # - # ƾǼ¹Ԥ PostDo action ѥХåؿϿ롣 - # - # @param self - # @param state Ͽоݾ - # @param call_back PostDo action ѥХåؿ - # - # @return ¹Է - # - # @else - # @brief Set PostDo action function - # @endif - def setPostDoAction(self, state, call_back): - if state in self._postdo: - self._postdo[state] = call_back - else: - return False - return True - - - ## - # @if jp - # @brief Exit action ؿϿ - # - # ƾǼ¹Ԥ Exit action ѥХåؿϿ롣 - # - # @param self - # @param state Ͽоݾ - # @param call_back Exit action ѥХåؿ - # - # @return ¹Է - # - # @else - # @brief Set Exit action function - # @endif - def setExitAction(self, state, call_back): - if state in self._exit: - self._exit[state] = call_back - else: - return False - return True - - - ## - # @if jp - # @brief State transition action ؿϿ - # - # ܻ˼¹Ԥ State transition action ѥХåؿ - # Ͽ롣 - # - # @param self - # @param call_back State transition ѥХåؿ - # - # @return ¹Է - # - # @else - # @brief Set state transition action function - # @endif - def setTransitionAction(self, call_back): - self._transit = call_back - return True - - - ## - # @if jp - # @brief ֤򥻥åȤ - # - # ơȥޥν֤ꤹ롣 - # - # @param self - # @param states - # - # @else - # @brief Set Exit action function - # @endif - def setStartState(self, states): - self._states = StateHolder() - self._states.curr = states.curr - self._states.prev = states.prev - self._states.next = states.next - - - ## - # @if jp - # @brief ֤ - # - # ־롣 - # ߤξ֡ξ֡ͽξ֤뤳ȤǤ롣 - # - # @param self - # - # @return ־ - # - # @else - # @brief Get state machine's status - # @endif - def getStates(self): - guard = OpenRTM_aist.ScopedLock(self._mutex) - return self._states - - - ## - # @if jp - # @brief ߤξ֤ - # - # ߤξ֤롣 - # - # @param self - # - # @return ߤξ - # - # @else - # @brief Get current state - # @endif - def getState(self): - guard = OpenRTM_aist.ScopedLock(self._mutex) - return self._states.curr - - - ## - # @if jp - # @brief ߾֤ǧ - # - # ߤξ֤ǻꤷ֤Ȱפ뤫ǧ롣 - # - # @param self - # @param state ǧоݾ - # - # @return ֳǧ - # - # @else - # @brief Evaluate current status - # @endif - def isIn(self, state): - guard = OpenRTM_aist.ScopedLock(self._mutex) - if self._states.curr == state: - return True - else: - return False - - - ## - # @if jp - # @brief ֤ - # - # ꤷ֤˾֤ܤ롣 - # ܴؿϼ֤Ū˥åȤؿǤ롣 - # Τᡢܤβݤϡ桼߾֤ȽǤå - # ʤФʤʤ - # 褬ߤξ֤Ʊˤϡܥե饰򥻥åȤ롣 - # - # @param self - # @param state - # - # @else - # @brief Change status - # @endif - def goTo(self, state): - guard = OpenRTM_aist.ScopedLock(self._mutex) - self._states.next = state - if self._states.curr == state: - self._selftrans = True - return - - - ## - # @if jp - # @brief ưؿ - # - # ơȥޥζưؿ - # ºݤξܤӾȯγƥθƤӤ¹Ԥ롣 - # - # @param self - # - # @else - # @brief Worker function - # @endif - def worker(self): - states = StateHolder() - self.sync(states) - # If no state transition required, execute set of do-actions - if states.curr == states.next: - # pre-do - if self._predo[states.curr]: - self._predo[states.curr](states) - - - if self.need_trans(): + """ + """ + + state_array = (RTC.CREATED_STATE, + RTC.INACTIVE_STATE, + RTC.ACTIVE_STATE, + RTC.ERROR_STATE) + + ## + # @if jp + # @brief コンストラクタ + # + # コンストラクタ + # + # @param self + # @param num_of_state ステートマシン中の状態数 + # + # @else + # @brief Constructor + # @endif + def __init__(self, num_of_state): + self._num = num_of_state + self._listener = None + self._entry = {} + self._predo = {} + self._do = {} + self._postdo = {} + self._exit = {} + + self.setNullFunc(self._entry, None) + self.setNullFunc(self._do, None) + self.setNullFunc(self._exit, None) + self.setNullFunc(self._predo, None) + self.setNullFunc(self._postdo, None) + self._transit = None + self._selftrans = False + self._mutex = threading.RLock() + + ## + # @if jp + # @brief NOP関数を登録する + # + # NOP関数(何もしない関数)を登録する。 + # + # @param self + # @param call_back コールバック関数 + # + # @else + # @brief Set NOP function + # @endif + + def setNOP(self, call_back): + self.setNullFunc(self._entry, call_back) + self.setNullFunc(self._do, call_back) + self.setNullFunc(self._exit, call_back) + self.setNullFunc(self._predo, call_back) + self.setNullFunc(self._postdo, call_back) + self._transit = call_back + + ## + # @if jp + # @brief Listener オブジェクトを登録する + # + # 各種アクション実行時に呼び出される Listener オブジェクトを登録する。 + # + # @param self + # @param listener Listener オブジェクト + # + # @else + # @brief Set Listener Object + # @endif + + def setListener(self, listener): + assert(listener) + self._listener = listener + return + + ## + # @if jp + # @brief Entry action 関数を登録する + # + # 各状態に入った際に実行される Entry action 用コールバック関数を登録する。 + # + # @param self + # @param state 登録対象状態 + # @param call_back Entry action 用コールバック関数 + # + # @return アクション実行結果 + # + # @else + # @brief Set Entry action function + # @endif + + def setEntryAction(self, state, call_back): + if state in self._entry: + self._entry[state] = call_back + else: + return False + return True + + ## + # @if jp + # @brief PreDo action 関数を登録する + # + # 各状態内で実行される PreDo action 用コールバック関数を登録する。 + # + # @param self + # @param state 登録対象状態 + # @param call_back PreDo action 用コールバック関数 + # + # @return アクション実行結果 + # + # @else + # @brief Set PreDo action function + # @endif + + def setPreDoAction(self, state, call_back): + if state in self._predo: + self._predo[state] = call_back + else: + return False + return True + + ## + # @if jp + # @brief Do action 関数を登録する + # + # 各状態内で実行される Do action 用コールバック関数を登録する。 + # + # @param self + # @param state 登録対象状態 + # @param call_back Do action 用コールバック関数 + # + # @return アクション実行結果 + # + # @else + # @brief Set Do action function + # @endif + + def setDoAction(self, state, call_back): + if state in self._do: + self._do[state] = call_back + else: + return False + return True + + ## + # @if jp + # @brief PostDo action 関数を登録する + # + # 各状態内で実行される PostDo action 用コールバック関数を登録する。 + # + # @param self + # @param state 登録対象状態 + # @param call_back PostDo action 用コールバック関数 + # + # @return アクション実行結果 + # + # @else + # @brief Set PostDo action function + # @endif + + def setPostDoAction(self, state, call_back): + if state in self._postdo: + self._postdo[state] = call_back + else: + return False + return True + + ## + # @if jp + # @brief Exit action 関数を登録する + # + # 各状態内で実行される Exit action 用コールバック関数を登録する。 + # + # @param self + # @param state 登録対象状態 + # @param call_back Exit action 用コールバック関数 + # + # @return アクション実行結果 + # + # @else + # @brief Set Exit action function + # @endif + + def setExitAction(self, state, call_back): + if state in self._exit: + self._exit[state] = call_back + else: + return False + return True + + ## + # @if jp + # @brief State transition action 関数を登録する + # + # 状態遷移時に実行される State transition action 用コールバック関数を + # 登録する。 + # + # @param self + # @param call_back State transition 用コールバック関数 + # + # @return アクション実行結果 + # + # @else + # @brief Set state transition action function + # @endif + + def setTransitionAction(self, call_back): + self._transit = call_back + return True + + ## + # @if jp + # @brief 初期状態をセットする + # + # ステートマシンの初期状態を設定する。 + # + # @param self + # @param states 初期状態 + # + # @else + # @brief Set Exit action function + # @endif + + def setStartState(self, states): + self._states = StateHolder() + self._states.curr = states.curr + self._states.prev = states.prev + self._states.next = states.next + + ## + # @if jp + # @brief 状態を取得する + # + # 状態情報を取得する。 + # 現在の状態、1つ前の状態、遷移予定の状態を取得することができる。 + # + # @param self + # + # @return 状態情報 + # + # @else + # @brief Get state machine's status + # @endif + + def getStates(self): + guard = OpenRTM_aist.ScopedLock(self._mutex) + return self._states + + ## + # @if jp + # @brief 現在の状態を取得する + # + # 現在の状態を取得する。 + # + # @param self + # + # @return 現在の状態 + # + # @else + # @brief Get current state + # @endif + + def getState(self): + guard = OpenRTM_aist.ScopedLock(self._mutex) + return self._states.curr + + ## + # @if jp + # @brief 現在状態を確認 + # + # 現在の状態が、引数で指定した状態と一致するか確認する。 + # + # @param self + # @param state 確認対象状態 + # + # @return 状態確認結果 + # + # @else + # @brief Evaluate current status + # @endif + + def isIn(self, state): + guard = OpenRTM_aist.ScopedLock(self._mutex) + if self._states.curr == state: + return True + else: + return False + + ## + # @if jp + # @brief 状態を遷移 + # + # 指定した状態に状態を遷移する。 + # 本関数は次状態を強制的にセットする関数である。 + # このため、遷移の可否は、ユーザが現在状態を取得し判断するロジックを + # 実装しなければならない。 + # 遷移先が現在の状態と同じ場合には、自己遷移フラグをセットする。 + # + # @param self + # @param state 遷移先状態 + # + # @else + # @brief Change status + # @endif + + def goTo(self, state): + guard = OpenRTM_aist.ScopedLock(self._mutex) + self._states.next = state + if self._states.curr == state: + self._selftrans = True + return + + ## + # @if jp + # @brief 駆動関数 + # + # ステートマシンの駆動関数。 + # 実際の状態遷移および状態遷移発生時の各アクションの呼びだしを実行する。 + # + # @param self + # + # @else + # @brief Worker function + # @endif + + def worker(self): + states = StateHolder() + self.sync(states) + # If no state transition required, execute set of do-actions + if states.curr == states.next: + # pre-do + if self._predo[states.curr]: + self._predo[states.curr](states) + + if self.need_trans(): + return + + # do + if self._do[states.curr]: + self._do[states.curr](states) + + if self.need_trans(): + return + + # post-do + if self._postdo[states.curr]: + self._postdo[states.curr](states) + + # If state transition required, exit current state and enter next state + else: + if self._exit[states.curr]: + self._exit[states.curr](states) + + self.sync(states) + + # If state transition still required, move to the next state + if states.curr != states.next: + states.curr = states.next + if self._entry[states.curr]: + self._entry[states.curr](states) + self.update_curr(states.curr) + return - # do - if self._do[states.curr]: - self._do[states.curr](states) + # void worker_pre() + + def worker_pre(self): + state = StateHolder() + self.sync(state) + if state.curr == state.next: + if self._predo[state.curr]: + self._predo[state.curr](state) + return + + # State changed + if self._exit[state.curr]: + self._exit[state.curr](state) + + self.sync(state) + if state.curr != state.next: + state.curr = state.next + if self._entry[state.curr]: + self._entry[state.curr](state) + self.update_curr(state.curr) + + return + + # void worker_do() + def worker_do(self): + state = StateHolder() + self.sync(state) + + if self._do[state.curr]: + self._do[state.curr](state) + + return + + # void worker_post() + + def worker_post(self): + state = StateHolder() + self.sync(state) + if self._postdo[state.curr]: + self._postdo[state.curr](state) + + return - if self.need_trans(): + ## + # @if jp + # @brief NOP関数を設定 + # + # NOP関数(何もしない関数)を登録する。 + # + # @param self + # @param s コールバック関数設定先 + # @param nullfunc コールバック関数(NOP関数) + # + # @else + # @brief Worker function + # @endif + + def setNullFunc(self, s, nullfunc): + for i in range(self._num): + if StateMachine.state_array[i] in s: + s[StateMachine.state_array[i]] = nullfunc + else: + s.setdefault(StateMachine.state_array[i], nullfunc) return - # post-do - if self._postdo[states.curr]: - self._postdo[states.curr](states) - - # If state transition required, exit current state and enter next state - else: - if self._exit[states.curr]: - self._exit[states.curr](states) - - self.sync(states) - - # If state transition still required, move to the next state - if states.curr != states.next: - states.curr = states.next - if self._entry[states.curr]: - self._entry[states.curr](states) - self.update_curr(states.curr) - - return - - - # void worker_pre() - def worker_pre(self): - state = StateHolder() - self.sync(state) - if state.curr == state.next: - if self._predo[state.curr]: - self._predo[state.curr](state) - return - - # State changed - if self._exit[state.curr]: - self._exit[state.curr](state) - - self.sync(state) - if state.curr != state.next: - state.curr = state.next - if self._entry[state.curr]: - self._entry[state.curr](state) - self.update_curr(state.curr) - - return - - # void worker_do() - def worker_do(self): - state = StateHolder() - self.sync(state) - - if self._do[state.curr]: - self._do[state.curr](state) - - return - - - # void worker_post() - def worker_post(self): - state = StateHolder() - self.sync(state) - if self._postdo[state.curr]: - self._postdo[state.curr](state) - - return - - - ## - # @if jp - # @brief NOPؿ - # - # NOPؿ(⤷ʤؿ)Ͽ롣 - # - # @param self - # @param s Хåؿ - # @param nullfunc Хåؿ(NOPؿ) - # - # @else - # @brief Worker function - # @endif - def setNullFunc(self, s, nullfunc): - for i in range(self._num): - if StateMachine.state_array[i] in s: - s[StateMachine.state_array[i]] = nullfunc - else: - s.setdefault(StateMachine.state_array[i], nullfunc) - return - - - ## - # @if jp - # @brief ֤Ʊ - # - # @param self - # @param states OpenRTM_aist.StateHolder - # - # @else - # @endif - def sync(self, states): - guard = OpenRTM_aist.ScopedLock(self._mutex) - states.prev = self._states.prev - states.curr = self._states.curr - states.next = self._states.next - - - - ## - # @if jp - # @brief ܤɬå - # - # @param self - # - # @return ɬǧ - # - # @else - # @endif - def need_trans(self): - guard = OpenRTM_aist.ScopedLock(self._mutex) - return (self._states.curr != self._states.next) - - - ## - # @if jp - # @brief ߾֤ι - # - # @param self - # @param curr RTC.LifeCycleState - # - # @else - # @endif - def update_curr(self, curr): - guard = OpenRTM_aist.ScopedLock(self._mutex) - self._states.curr = curr + ## + # @if jp + # @brief 状態の同期処理 + # + # @param self + # @param states OpenRTM_aist.StateHolder + # + # @else + # @endif + + def sync(self, states): + guard = OpenRTM_aist.ScopedLock(self._mutex) + states.prev = self._states.prev + states.curr = self._states.curr + states.next = self._states.next + + ## + # @if jp + # @brief 遷移の必要性チェック + # + # @param self + # + # @return 遷移必要性確認結果 + # + # @else + # @endif + + def need_trans(self): + guard = OpenRTM_aist.ScopedLock(self._mutex) + return (self._states.curr != self._states.next) + + ## + # @if jp + # @brief 現在状態の更新 + # + # @param self + # @param curr RTC.LifeCycleState + # + # @else + # @endif + + def update_curr(self, curr): + guard = OpenRTM_aist.ScopedLock(self._mutex) + self._states.curr = curr diff --git a/OpenRTM_aist/StaticFSM.py b/OpenRTM_aist/StaticFSM.py index 7292c9c8..ac0ec94d 100644 --- a/OpenRTM_aist/StaticFSM.py +++ b/OpenRTM_aist/StaticFSM.py @@ -1,5 +1,5 @@ #!/usr/bin/env python -# -*- coding: euc-jp -*- +# -*- coding: utf-8 -*- ## # @file StaticFSM.py @@ -18,121 +18,504 @@ import RTC +## +# @if jp +# +# @brief FSMの最上位の状態生成 +# +# @param TOP 状態遷移マシンの最上位状態を定義したクラス +# @return 最上位の状態 +# +# @else +# +# @brief +# +# @param TOP +# +# @endif +# def fsm_topstate(TOP): - ret = OpenRTM_aist.Macho.topstate(TOP) - class STATE(ret): - def __init__(self, instance): - ret.__init__(self, instance) - def on_entry(self, *argv): - ret.call_entry(self, ret, *argv) - def on_exit(self, *argv): - ret.call_exit(self, ret, *argv) - def on_init(self, *argv): - ret.call_init(self, ret, *argv) - return STATE + ret = OpenRTM_aist.Macho.topstate(TOP) - -def fsm_substate(superstate): - def _fsm_substate(cls): - ret = OpenRTM_aist.Macho.substate(superstate)(cls) class STATE(ret): - def __init__(self, instance): - ret.__init__(self, instance) - def on_entry(self, *argv): - ret.call_entry(self, cls, *argv) - def on_exit(self, *argv): - ret.call_exit(self, cls, *argv) - def on_init(self, *argv): - ret.call_init(self, cls, *argv) + def __init__(self, instance): + ret.__init__(self, instance) + def on_entry(self, *argv): + ret.call_entry(self, ret, *argv) + + def on_exit(self, *argv): + ret.call_exit(self, ret, *argv) + + def on_init(self, *argv): + ret.call_init(self, ret, *argv) return STATE - return _fsm_substate + +## +# @if jp +# +# @brief FSMのサブ状態生成 +# +# @param TOP 状態遷移マシンのサブ状態を定義したクラス +# @return サブ状態 +# +# @else +# +# @brief +# +# @param TOP +# +# @endif +# +def fsm_substate(superstate): + def _fsm_substate(cls): + ret = OpenRTM_aist.Macho.substate(superstate)(cls) + + class STATE(ret): + def __init__(self, instance): + ret.__init__(self, instance) + + def on_entry(self, *argv): + ret.call_entry(self, cls, *argv) + + def on_exit(self, *argv): + ret.call_exit(self, cls, *argv) + + def on_init(self, *argv): + ret.call_init(self, cls, *argv) + + return STATE + return _fsm_substate + + +## +# @if jp +# +# @brief FSMの最上位状態生成関数 +# Machoやpyfsmで定義したクラスにデコレートして使用する +# @StaticFSM.FSM_TOPSTATE +# class TOP(StaticFSM.Link): +# +# @param TOP 最上位状態 +# @return 最上位状態 +# +# @else +# +# @brief +# +# @param TOP +# @return +# +# +# @endif +# def FSM_TOPSTATE(TOP): - return fsm_topstate(TOP) + return fsm_topstate(TOP) + +## +# @if jp +# +# @brief FSMのサブ位状態生成関数 +# Machoやpyfsmで定義したクラスにデコレートして使用する +# @StaticFSM.FSM_SUBSTATE(TOP) +# class Disabled(StaticFSM.Link): +# +# @param SUPERSTATE 上位の状態 +# @return サブ状態を生成する関数 +# +# @else +# +# @brief +# +# @param SUPERSTATE +# @return +# +# +# @endif +# def FSM_SUBSTATE(SUPERSTATE): - return fsm_substate(SUPERSTATE) - + return fsm_substate(SUPERSTATE) +## +# @if jp +# +# @class CSPMachine +# +# @brief 有限状態マシン +# 初期化時に最上位状態、RTCを指定する +# 最上位状態から開始し、その後イベントによって状態遷移する +# EventPortで受信したイベントは一旦バッファに保存されるため、 +# run_event関数を呼び出すことでバッファ内のイベントを実行する必要がある +# バッファは全てのEventPortで共有される +# +# @since 2.0.0 +# +# @else +# +# @class CSPMachine +# +# @brief +# +# @since 2.0.0 +# +# +# @endif +# class Machine(OpenRTM_aist.Macho.Machine): - def __init__(self, TOP, comp): - #super(Machine,self).__init__(TOP, OpenRTM_aist.Macho.TopBase(TOP)) - self._rtComponent = comp - super(Machine,self).__init__(TOP) - self._buffer = OpenRTM_aist.CdrBufferFactory.instance().createObject("ring_buffer") - - - - def __del__(self): - pass - def getBuffer(self): - return self._buffer - def init_other(self, other): - pass - def equal(self, snapshot): - pass - def getComp(self): - return self._rtComponent - def run_event(self): - while self._buffer.readable() > 0: - event = self._buffer.get() - event() - self._buffer.advanceRptr() + ## + # @if jp + # + # @brief コンストラクタ + # + # @param self + # @param TOP 最上位状態 + # @param comp RTC + # + # @else + # + # @brief A constructor. + # + # @param self + # @param TOP + # @param comp + # + # @endif + # + def __init__(self, TOP, comp): + #super(Machine,self).__init__(TOP, OpenRTM_aist.Macho.TopBase(TOP)) + self._rtComponent = comp + super(Machine, self).__init__(TOP) + self._buffer = OpenRTM_aist.CdrBufferFactory.instance().createObject("ring_buffer") + ## + # @if jp + # + # @brief デストラクタ + # + # @param self + # + # @else + # + # @brief A destructor. + # + # @param self + # + # @endif + # + + def __del__(self): + pass + ## + # @if jp + # + # @brief バッファ取得 + # + # @param self + # @return バッファ + # + # @else + # + # @brief + # + # @param self + # @return + # + # @endif + # + + def getBuffer(self): + return self._buffer + + def init_other(self, other): + pass + + def equal(self, snapshot): + pass + ## + # @if jp + # + # @brief RTC取得 + # + # @param self + # @return RTC + # + # @else + # + # @brief + # + # @param self + # @return + # + # @endif + # + def getComp(self): + return self._rtComponent + ## + # @if jp + # + # @brief イベント実行 + # バッファが空になるまでイベントを実行する + # + # @param self + # + # @else + # + # @brief + # + # @param self + # + # @endif + # + def run_event(self): + while self._buffer.readable() > 0: + _, event = self._buffer.get() + event() + self._buffer.advanceRptr() + +## +# @if jp +# +# @class Link +# +# @brief 状態定義の基底クラス +# 最上位状態、サブ状態を定義する場合はこのクラスを継承する必要がある +# +# @since 2.0.0 +# +# @else +# +# @class Link +# +# @brief +# +# @since 2.0.0 +# +# +# @endif +# class Link(OpenRTM_aist.Macho.StateDef): - def __init__(self, instance): - super(Link,self).__init__(instance) - self._rtComponent = None - def __del__(self): - pass - def setrtc(self): - if self._rtComponent: - return - machine = self._myStateInstance.machine() - if machine: - self._rtComponent = machine.getComp() - - def call_entry(self, cls, *argv): - self.setrtc() - if not self._rtComponent: - cls.onEntry(self, *argv) - else: - self._rtComponent.postOnFsmStateChange(self._state_name(), RTC.RTC_OK) - self._rtComponent.preOnFsmEntry(self._state_name()) - self._rtComponent.postOnFsmEntry(self._state_name(),cls.onEntry(self, *argv)) - - def call_init(self, cls, *argv): - self.setrtc() - if not self._rtComponent: - cls.onInit(self, *argv) - else: - self._rtComponent.preOnFsmInit(self._state_name()) - self._rtComponent.postOnFsmInit(self._state_name(), cls.onInit(self, *argv)) - - - def call_exit(self, cls, *argv): - self.setrtc() - if not self._rtComponent: - cls.onExit(self, *argv) - else: - self._rtComponent.preOnFsmExit(self._state_name()) - self._rtComponent.postOnFsmExit(self._state_name(), cls.onExit(self, *argv)) - self._rtComponent.preOnFsmStateChange(self._state_name()) - - def onEntry(self): - return RTC.RTC_OK - def onInit(self): - return RTC.RTC_OK - def onExit(self): - return RTC.RTC_OK + ## + # @if jp + # + # @brief コンストラクタ + # + # @param self + # @param instance + # + # @else + # + # @brief A constructor. + # + # @param self + # @param instance + # + # @endif + # + def __init__(self, instance): + super(Link, self).__init__(instance) + self._rtComponent = None + ## + # @if jp + # + # @brief デストラクタ + # + # @param self + # + # @else + # + # @brief A destructor. + # + # @param self + # + # @endif + # + + def __del__(self): + pass + ## + # @if jp + # + # @brief 内部の変数に状態遷移マシンが保持するRTCの参照を格納する + # + # @param self + # + # @else + # + # @brief + # + # @param self + # + # @endif + # + + def setrtc(self): + if self._rtComponent: + return + machine = self._myStateInstance.machine() + if machine: + self._rtComponent = machine.getComp() + + ## + # @if jp + # + # @brief 現在の状態のonEntry関数を呼び出す + # RTCを設定している場合はpostOnFsmStateChange、preOnFsmEntry、postOnFsmEntryコールバックを呼び出す + # + # @param self + # @param cls 現在の状態 + # @param argv + # + # @else + # + # @brief + # + # @param self + # @param cls + # @param argv + # + # @endif + # + def call_entry(self, cls, *argv): + self.setrtc() + if not self._rtComponent: + cls.onEntry(self, *argv) + else: + self._rtComponent.postOnFsmStateChange( + self._state_name(), RTC.RTC_OK) + self._rtComponent.preOnFsmEntry(self._state_name()) + self._rtComponent.postOnFsmEntry( + self._state_name(), cls.onEntry(self, *argv)) + + ## + # @if jp + # + # @brief 現在の状態のonInit関数を呼び出す + # RTCを設定している場合はpostOnFsmStateChange、preOnFsmEntry、postOnFsmEntryコールバックを呼び出す + # + # @param self + # @param cls 現在の状態 + # @param argv + # + # @else + # + # @brief + # + # @param self + # @param cls + # @param argv + # + # @endif + # + def call_init(self, cls, *argv): + self.setrtc() + if not self._rtComponent: + cls.onInit(self, *argv) + else: + self._rtComponent.preOnFsmInit(self._state_name()) + self._rtComponent.postOnFsmInit( + self._state_name(), cls.onInit(self, *argv)) + + ## + # @if jp + # + # @brief 現在の状態のonExit関数を呼び出す + # RTCを設定している場合はpostOnFsmStateChange、preOnFsmEntry、postOnFsmEntryコールバックを呼び出す + # + # @param self + # @param cls 現在の状態 + # @param argv + # + # @else + # + # @brief + # + # @param self + # @param cls + # @param argv + # + # @endif + # + def call_exit(self, cls, *argv): + self.setrtc() + if not self._rtComponent: + cls.onExit(self, *argv) + else: + self._rtComponent.preOnFsmExit(self._state_name()) + self._rtComponent.postOnFsmExit( + self._state_name(), cls.onExit(self, *argv)) + self._rtComponent.preOnFsmStateChange(self._state_name()) + + ## + # @if jp + # + # @brief 入場動作を定義した関数 + # Linkを継承したクラスでonEntry関数を定義し処理を実装する + # + # @param self + # @return リターンコード + # + # @else + # + # @brief + # + # @param self + # @return + # + # @endif + # + def onEntry(self): + return RTC.RTC_OK + ## + # @if jp + # + # @brief 開始動作を定義した関数 + # Linkを継承したクラスでonInit関数を定義し処理を実装する + # + # @param self + # @return リターンコード + # + # @else + # + # @brief + # + # @param self + # @return + # + # @endif + # + + def onInit(self): + return RTC.RTC_OK + ## + # @if jp + # + # @brief 退場動作を定義した関数 + # Linkを継承したクラスでonExit関数を定義し処理を実装する + # + # @param self + # @return リターンコード + # + # @else + # + # @brief + # + # @param self + # @return + # + # @endif + # + + def onExit(self): + return RTC.RTC_OK State = OpenRTM_aist.Macho.State deephistory = OpenRTM_aist.Macho.deephistory -Event = OpenRTM_aist.Macho.Event \ No newline at end of file +Event = OpenRTM_aist.Macho.Event diff --git a/OpenRTM_aist/StaticFSM_pyfsm.py b/OpenRTM_aist/StaticFSM_pyfsm.py index 5c6f2915..989277be 100644 --- a/OpenRTM_aist/StaticFSM_pyfsm.py +++ b/OpenRTM_aist/StaticFSM_pyfsm.py @@ -1,5 +1,5 @@ #!/usr/bin/env python -# -*- coding: euc-jp -*- +# -*- coding: utf-8 -*- ## # @file StaticFSM_pyfsm.py @@ -19,119 +19,135 @@ def fsm_topstate(TOP): - ret = pyfsm.topstate(TOP) - class STATE(ret): - def __init__(self, instance): - ret.__init__(self, instance) - def on_entry(self, *argv): - ret.call_entry(self, ret, *argv) - def on_exit(self, *argv): - ret.call_exit(self, ret, *argv) - def on_init(self, *argv): - ret.call_init(self, ret, *argv) - return STATE + ret = pyfsm.topstate(TOP) - -def fsm_substate(superstate): - def _fsm_substate(cls): - ret = pyfsm.substate(superstate)(cls) class STATE(ret): - def __init__(self, instance): - ret.__init__(self, instance) - def on_entry(self, *argv): - ret.call_entry(self, cls, *argv) - def on_exit(self, *argv): - ret.call_exit(self, cls, *argv) - def on_init(self, *argv): - ret.call_init(self, cls, *argv) + def __init__(self, instance): + ret.__init__(self, instance) + + def on_entry(self, *argv): + ret.call_entry(self, ret, *argv) + def on_exit(self, *argv): + ret.call_exit(self, ret, *argv) + + def on_init(self, *argv): + ret.call_init(self, ret, *argv) return STATE - return _fsm_substate +def fsm_substate(superstate): + def _fsm_substate(cls): + ret = pyfsm.substate(superstate)(cls) + + class STATE(ret): + def __init__(self, instance): + ret.__init__(self, instance) + + def on_entry(self, *argv): + ret.call_entry(self, cls, *argv) + + def on_exit(self, *argv): + ret.call_exit(self, cls, *argv) + + def on_init(self, *argv): + ret.call_init(self, cls, *argv) + + return STATE + return _fsm_substate + def FSM_TOPSTATE(TOP): - return fsm_topstate(TOP) + return fsm_topstate(TOP) def FSM_SUBSTATE(SUPERSTATE): - return fsm_substate(SUPERSTATE) - + return fsm_substate(SUPERSTATE) class Machine(pyfsm.Machine): - def __init__(self, TOP, comp): - self._rtComponent = comp - super(Machine,self).__init__(TOP) - self._buffer = OpenRTM_aist.CdrBufferFactory.instance().createObject("ring_buffer") - - - def __del__(self): - pass - def getBuffer(self): - return self._buffer - - def init_other(self, other): - pass - def equal(self, snapshot): - pass - def getComp(self): - return self._rtComponent - def run_event(self): - while self._buffer.readable() > 0: - event = self._buffer.get() - event() - self._buffer.advanceRptr() + def __init__(self, TOP, comp): + self._rtComponent = comp + super(Machine, self).__init__(TOP) + self._buffer = OpenRTM_aist.CdrBufferFactory.instance().createObject("ring_buffer") + + def __del__(self): + pass + + def getBuffer(self): + return self._buffer + + def init_other(self, other): + pass + + def equal(self, snapshot): + pass + + def getComp(self): + return self._rtComponent + + def run_event(self): + while self._buffer.readable() > 0: + _, event = self._buffer.get() + event() + self._buffer.advanceRptr() class Link(pyfsm.StateDef): - def __init__(self): - super(Link,self).__init__() - self._rtComponent = None - def __del__(self): - pass - def setrtc(self): - if self._rtComponent: - return - machine = self._myStateInstance.machine() - if machine: - self._rtComponent = machine.getComp() - - def call_entry(self, cls, *argv): - self.setrtc() - if not self._rtComponent: - self.onEntry(*argv) - else: - self._rtComponent.postOnFsmStateChange(self._state_name(), RTC.RTC_OK) - self._rtComponent.preOnFsmEntry(self._state_name()) - self._rtComponent.postOnFsmEntry(self._state_name(),cls.onEntry(self, *argv)) - - def call_init(self, cls, *argv): - self.setrtc() - if not self._rtComponent: - self.onInit(*argv) - else: - self._rtComponent.preOnFsmInit(self._state_name()) - self._rtComponent.postOnFsmInit(self._state_name(), cls.onInit(self, *argv)) - - - def call_exit(self, cls, *argv): - self.setrtc() - if not self._rtComponent: - self.onExit(*argv) - else: - self._rtComponent.preOnFsmExit(self._state_name()) - self._rtComponent.postOnFsmExit(self._state_name(), cls.onExit(self, *argv)) - self._rtComponent.preOnFsmStateChange(self._state_name()) - - def onEntry(self): - return RTC.RTC_OK - def onInit(self): - return RTC.RTC_OK - def onExit(self): - return RTC.RTC_OK + def __init__(self): + super(Link, self).__init__() + self._rtComponent = None + + def __del__(self): + pass + + def setrtc(self): + if self._rtComponent: + return + machine = self._myStateInstance.machine() + if machine: + self._rtComponent = machine.getComp() + + def call_entry(self, cls, *argv): + self.setrtc() + if not self._rtComponent: + self.onEntry(*argv) + else: + self._rtComponent.postOnFsmStateChange( + self._state_name(), RTC.RTC_OK) + self._rtComponent.preOnFsmEntry(self._state_name()) + self._rtComponent.postOnFsmEntry( + self._state_name(), cls.onEntry(self, *argv)) + + def call_init(self, cls, *argv): + self.setrtc() + if not self._rtComponent: + self.onInit(*argv) + else: + self._rtComponent.preOnFsmInit(self._state_name()) + self._rtComponent.postOnFsmInit( + self._state_name(), cls.onInit(self, *argv)) + + def call_exit(self, cls, *argv): + self.setrtc() + if not self._rtComponent: + self.onExit(*argv) + else: + self._rtComponent.preOnFsmExit(self._state_name()) + self._rtComponent.postOnFsmExit( + self._state_name(), cls.onExit(self, *argv)) + self._rtComponent.preOnFsmStateChange(self._state_name()) + + def onEntry(self): + return RTC.RTC_OK + + def onInit(self): + return RTC.RTC_OK + + def onExit(self): + return RTC.RTC_OK State = pyfsm.State deephistory = pyfsm.deephistory -Event = pyfsm.Event \ No newline at end of file +Event = pyfsm.Event diff --git a/OpenRTM_aist/StringUtil.py b/OpenRTM_aist/StringUtil.py index 1d30dc7f..7384049f 100644 --- a/OpenRTM_aist/StringUtil.py +++ b/OpenRTM_aist/StringUtil.py @@ -1,5 +1,5 @@ #!/usr/bin/env python -# -*- coding: euc-jp -*- +# -*- coding: utf-8 -*- ## # @file StringUtil.py @@ -24,14 +24,14 @@ ## # @if jp -# @brief ʸ󤬥פƤ뤫ȽǤ +# @brief 文字列がエスケープされているか判断する # -# ꤵ줿ʸפƤ뤫ɤȽǤ롣 +# 指定された文字がエスケープされているかどうかを判断する。 # -# @param _str פƤ뤫ɤȽǤʸޤʸ -# @param pos פƤ뤫ɤȽǤʸΰ +# @param _str エスケープされているかどうか判断する文字を含む文字列 +# @param pos エスケープされているかどうか判断する文字の位置 # -# @return ꤷʸפƤ true, ʳ false +# @return 指定した文字がエスケープされていれば true, それ以外は false # # @else # @brief Whether the character is escaped or not @@ -46,153 +46,153 @@ # # @endif def isEscaped(_str, pos): - pos -= 1 - - i = 0 - while pos >= 0 and _str[pos] == "\\": - i += 1 pos -= 1 - return i % 2 == 1 + i = 0 + while pos >= 0 and _str[pos] == "\\": + i += 1 + pos -= 1 + + return i % 2 == 1 ## # @if jp # @class escape_functor -# @brief ʸ󥨥׽functor +# @brief 文字列エスケープ処理用functor # @else # # @endif class escape_functor: - def __init__(self): - self._str = "" - - def __call__(self,c): - if c == '\t': - self._str += "\\t" - elif c == '\n': - self._str += "\\n" - elif c == '\f': - self._str += "\\f" - elif c == '\r': - self._str += "\\r" - elif c == '\\': - self._str += "\\\\" - else: - self._str += c + def __init__(self): + self._str = "" + + def __call__(self, c): + if c == '\t': + self._str += "\\t" + elif c == '\n': + self._str += "\\n" + elif c == '\f': + self._str += "\\f" + elif c == '\r': + self._str += "\\r" + elif c == '\\': + self._str += "\\\\" + else: + self._str += c ## # @if jp # @class unescape_functor -# @brief ʸ󥢥󥨥׽functor +# @brief 文字列アンエスケープ処理用functor # @else # # @endif class unescape_functor: - def __init__(self): - self.count = 0 - self._str = "" - - def __call__(self,c): - if c == "\\": - self.count += 1 - if not (self.count % 2): - self._str += c - else: - if self.count > 0 and (self.count % 2): + def __init__(self): self.count = 0 - if c == 't': - self._str+='\t' - elif c == 'n': - self._str+='\n' - elif c == 'f': - self._str+='\f' - elif c == 'r': - self._str+='\r' - elif c == '\"': - self._str+='\"' - elif c == '\'': - self._str+='\'' + self._str = "" + + def __call__(self, c): + if c == "\\": + self.count += 1 + if not (self.count % 2): + self._str += c else: - self._str+=c - else: - self.count = 0 - self._str+=c + if self.count > 0 and (self.count % 2): + self.count = 0 + if c == 't': + self._str += '\t' + elif c == 'n': + self._str += '\n' + elif c == 'f': + self._str += '\f' + elif c == 'r': + self._str += '\r' + elif c == '\"': + self._str += '\"' + elif c == '\'': + self._str += '\'' + else: + self._str += c + else: + self.count = 0 + self._str += c ## # @if jp # @class unique_strvec -# @brief ʣʸfunctor +# @brief 重複文字削除処理用functor # @else # # @endif class unique_strvec: - def __init__(self): - self._str = [] + def __init__(self): + self._str = [] - def __call__(self,s): - if self._str.count(s) == 0: - return self._str.append(s) + def __call__(self, s): + if self._str.count(s) == 0: + return self._str.append(s) ## # @if jp -# @brief 󥹥functor +# @brief インスタンス生成用functor # @else # # @endif def for_each(_str, instance): - for i in _str: - instance(i) + for i in _str: + instance(i) - return instance + return instance ## # @if jp -# @brief ʸ򥨥פ -# -# ʸ򥨥ץ󥹤Ѵ롣
    +# @brief 文字列をエスケープする +# +# 次の文字をエスケープシーケンスに変換する。
    # HT -> "\t"
    # LF -> "\n"
    # CR -> "\r"
    # FF -> "\f"
    -# 󥰥륯ȡ֥륯ȤˤĤƤϤȤ˽Ϥʤ -# +# シングルクオート、ダブルクオートについてはとくに処理はしない。 +# # @else -# +# # @brief Escape string -# +# # The following characters are converted.
    # HT -> "\t"
    # LF -> "\n"
    # CR -> "\r"
    # FF -> "\f"
    # Single quote and dobule quote are not processed. -# +# # @endif def escape(_str): - return for_each(_str, escape_functor())._str + return for_each(_str, escape_functor())._str ## # @if jp -# @brief ʸΥפ᤹ -# -# Υץ󥹤ʸѴ롣
    +# @brief 文字列のエスケープを戻す +# +# 次のエスケープシーケンスを文字に変換する。
    # "\t" -> HT
    # "\n" -> LF
    # "\r" -> CR
    # "\f" -> FF
    # "\"" -> "
    # "\'" -> '
    -# +# # @else -# +# # @brief Unescape string -# +# # The following characters are converted.
    # "\t" -> HT
    # "\n" -> LF
    @@ -202,17 +202,17 @@ def escape(_str): # "\"" -> "
    # @endif def unescape(_str): - return for_each(_str, unescape_functor())._str + return for_each(_str, unescape_functor())._str ## # @if jp -# @brief ʸζʸ +# @brief 文字列の空白文字を削除する # -# Ϳ줿ʸζʸ롣 -# ʸȤưΤ' '(ڡ)'\\t'() +# 与えられた文字列の空白文字を削除する。 +# 空白文字として扱うのは' '(スペース)と'\\t'(タブ)。 # -# @param str(list) ʸʸΥꥹ +# @param str(list) 空白文字削除処理文字列のリスト # # @else # @brief Erase blank characters of string @@ -224,172 +224,175 @@ def unescape(_str): # # @endif # -def eraseBlank(str): - if len(str) == 0: - return - str[0] = str[0].strip(" ") - l_str = str[0].split(" ") +def eraseBlank(_str): + _str = _str.strip(" ") + l_str = _str.split(" ") tmp_str = "" for s in l_str: if s: - tmp_str+=s.strip(" ") + tmp_str += s.strip(" ") tmp_str = tmp_str.strip('\t') l_str = tmp_str.split('\t') tmp_str = "" for s in l_str: if s: - tmp_str+=s.strip('\t') + tmp_str += s.strip('\t') - str[0] = tmp_str + _str = tmp_str + return _str ## # @if jp -# @brief ʸƬζʸ +# @brief 文字列の先頭の空白文字を削除する # -# Ϳ줿ʸƬ¸ߤʸ롣 -# ʸȤưΤ' '(ڡ)'\\t'() +# 与えられた文字列の先頭に存在する空白文字を削除する。 +# 空白文字として扱うのは' '(スペース)と'\\t'(タブ)。 # -# @param _str Ƭʸʸ +# @param _str 先頭空白文字削除処理文字列 # # @else # @brief Erase the head blank characters of string # @endif def eraseHeadBlank(_str): - _str[0] = _str[0].lstrip('\t ') - + _str = _str.lstrip('\t ') + return _str ## # @if jp -# @brief ʸζʸ +# @brief 文字列の末尾の空白文字を削除する # -# Ϳ줿ʸ¸ߤʸ롣 -# ʸȤưΤ' '(ڡ)'\\t'() +# 与えられた文字列の末尾に存在する空白文字を削除する。 +# 空白文字として扱うのは' '(スペース)と'\\t'(タブ)。 # -# @param _str ʸʸ +# @param _str 末尾空白文字削除処理文字列 # # @else # @brief Erase the tail blank characters of string # @endif -def eraseTailBlank(_str): - #_str[0] = _str[0].rstrip('\t ') - if _str[0] == "": - return - while (_str[0][-1] == " " or _str[0][-1] == '\t') and not isEscaped(_str[0], len(_str[0]) - 1): - _str[0] = _str[0][:-1] +def eraseTailBlank(_str): + #_str = _str.rstrip('\t ') + if _str == "": + return _str + + while (_str[-1] == " " or _str[-1] == + '\t') and not isEscaped(_str, len(_str) - 1): + _str = _str[:-1] + return _str # # @if jp -# @brief ʸ +# @brief 文字列を正規化する # @else # @brief Erase the head/tail blank and replace upper case to lower case # @endif # + + def normalize(_str): - _str[0] = _str[0].strip().lower() - return _str[0] + _str = _str.strip().lower() + return _str ## # @if jp -# @brief ʸ֤ +# @brief 文字列を置き換える # -# Ϳ줿ʸФơꤷʸ֤Ԥ +# 与えられた文字列に対して、指定した文字の置き換えを行う。 # -# @param str ֤оʸ -# @param _from ִʸ -# @param _to ִʸ +# @param str 置き換え処理対象文字列 +# @param _from 置換元文字 +# @param _to 置換先文字 +# @return 置き換え結果文字列 # # @else # @brief Replace string # @endif -def replaceString(str, _from, _to): - str[0] = str[0].replace(_from, _to) +def replaceString(_str, _from, _to): + return _str.replace(_from, _to) ## # @if jp -# @brief ʸʬʸʬ䤹 -# -# ꤵ줿ʸͿ줿ǥߥʬ䤹롣 +# @brief 文字列を分割文字で分割する +# +# 設定された文字列を与えられたデリミタで分割する。 # -# @param input ʬоʸ -# @param delimiter ʬʸ(ǥߥ) +# @param input 分割対象文字列 +# @param delimiter 分割文字列(デリミタ) # -# @return ʸʬ̥ꥹ +# @return 文字列分割結果リスト # # @else # @brief Split string by delimiter # @endif def split(input, delimiter): - if not input: - return [] + if not input: + return [] - del_result = input.split(delimiter) + del_result = input.split(delimiter) - len_ = len(del_result) + result = [] + for i, dl in enumerate(del_result): + if dl == "" or dl == " ": + continue - result = [] - for i in range(len_): - if del_result[i] == "" or del_result[i] == " ": - continue - - str_ = [del_result[i]] - eraseHeadBlank(str_) - eraseTailBlank(str_) - result.append(str_[0]) - - return result + str_ = dl + str_ = eraseHeadBlank(str_) + str_ = eraseTailBlank(str_) + result.append(str_) + + return result ## # @if jp -# @brief Ϳ줿ʸboolͤѴ -# -# ꤵ줿ʸtrueɽʸfalseɽʸӤη̤ -# boolͤȤ֤ -# Ӥη̡trueɽʸfalseɽʸΤɤȤפʤϡ -# Ϳ줿ǥե֤ͤ -# -# @param _str Ƚоʸ -# @param yes trueɽʸ -# @param no falseɽʸ -# @param default_value ǥե(ǥե:None) +# @brief 与えられた文字列をbool値に変換する +# +# 指定された文字列を、true表現文字列、false表現文字列と比較し、その結果を +# bool値として返す。 +# 比較の結果、true表現文字列、false表現文字列のどちらとも一致しない場合は、 +# 与えられたデフォルト値を返す。 +# +# @param _str 判断対象文字列 +# @param yes true表現文字列 +# @param no false表現文字列 +# @param default_value デフォルト値(デフォルト値:None) # @else # @brief Convert given string to bool value # @endif def toBool(_str, yes, no, default_value=None): - if default_value is None: - default_value = True + if default_value is None: + default_value = True - _str = _str.upper() - yes = yes.upper() - no = no.upper() + _str = _str.upper() + yes = yes.upper() + no = no.upper() - if _str.find(yes) != -1: - return True - elif (_str.find(no)) != -1: - return False - else: - return default_value + if _str.find(yes) != -1: + return True + elif (_str.find(no)) != -1: + return False + else: + return default_value ## # @if jp -# @brief ʸꥹˤʸ󤬴ޤޤ뤫ɤ -# -# 1˥޶ڤΥꥹȤ2õоʸꤷ -# ʸ1˴ޤޤ뤫ȽǤ롣 +# @brief 文字列リスト中にある文字列が含まれるかどうか # -# @param list оݥꥹ -# @param value õʸ -# @return true: ޤޤ롢false: ޤޤʤ +# 第1引数にカンマ区切りのリストを、第2引数に探索対象文字列を指定し、 +# その文字列が第1引数の中に含まれるかを判断する。 +# +# @param list 対象リスト +# @param value 探索文字列 +# @return true: 含まれる、false: 含まれない # # @else # @brief Include if a string is included in string list -# +# # if the second argument is included in the comma separated string # list of the first argument, This operation returns "true value". # @@ -401,219 +404,216 @@ def toBool(_str, yes, no, default_value=None): # # bool includes(const vstring& list, std::string value, # bool ignore_case = true); -def includes(_list, value, ignore_case = True): - if not (type(_list) == list or type(_list) == str): - return False - if type(_list) == str: - _list = _list.split(",") - tmp_list = _list - if ignore_case: - value = value.lower() - tmp_list = list(map((lambda x: x.lower()),_list)) - - if tmp_list.count(value) > 0: - return True +def includes(_list, value, ignore_case=True): + if not (isinstance(_list, list) or isinstance(_list, str)): + return False + + if isinstance(_list, str): + _list = _list.split(",") + + tmp_list = _list + if ignore_case: + value = value.lower() + tmp_list = list(map((lambda x: x.lower()), _list)) - return False - + if tmp_list.count(value) > 0: + return True + + return False ## # @if jp -# @brief Ϳ줿ʸХѥɤȽǤ +# @brief 与えられた文字列が絶対パスかどうかを判断する # -# Ϳ줿ʸХѥɽǤ뤫ɤȽǤ롣 -# ʸ󤬰ʲξˤХѥȤȽǤ롣 -# - Ƭʸ'/' (UNIXξ) -# - Ƭʸե٥åȡ'/''\\' (Windowsξ) -# - Ƭʸ'\\\\' (Windowsͥåȥѥξ) +# 与えられた文字列が絶対パス表現であるかどうかを判断する。 +# 文字列が以下の場合には絶対パスとして判断する。 +# - 先頭文字が'/' (UNIXの場合) +# - 先頭3文字がアルファベット+'/'+'\\' (Windowsの場合) +# - 先頭2文字が'\\\\' (Windowsネットワークパスの場合) # -# @param str Ƚоʸ +# @param str 判定対象文字列 # -# @return ХѥȽ +# @return 絶対パス判定結果 # # @else # @brief Investigate whether the given string is absolute path or not # @endif def isAbsolutePath(str): - if str[0] == "/": - return True - if str[0].isalpha() and str[1] == ":" and (str[2] == "\\" or str[2] == "/"): - return True - if str[0] == "\\" and str[1] == "\\": - return True + if str[0] == "/": + return True + if str[0].isalpha() and str[1] == ":" and ( + str[2] == "\\" or str[2] == "/"): + return True + if str[0] == "\\" and str[1] == "\\": + return True - return False + return False ## # @if jp -# @brief Ϳ줿ʸURLɤȽǤ +# @brief 与えられた文字列がURLかどうかを判断する # -# Ϳ줿ʸURLɽɤȽǤ롣 -# Ϳ줿ʸˡ'://'Ȥʸ󤬴ޤޤƤˤ -# URLɽȤȽǤ롣 +# 与えられた文字列がURL表現かどうかを判断する。 +# 与えられた文字列中に、'://'という文字列が含まれている場合には +# URL表現として判断する。 # -# @param str Ƚоʸ +# @param str 判定対象文字列 # -# @return URLȽ +# @return URL判定結果 # # @else # @brief Investigate whether the given string is URL or not # @endif def isURL(str): - pos = 0 - if str == "": - return False + pos = 0 + if str == "": + return False - pos = str.find(":") - if pos != 0 and pos != -1 and str[pos+1] == "/" and str[pos+2] == "/": - return True + pos = str.find(":") + if pos != 0 and pos != -1 and str[pos + 1] == "/" and str[pos + 2] == "/": + return True - return False + return False ## # @if jp -# @brief Ϳ줿֥ȤʸѴ +# @brief 与えられたオブジェクトを文字列に変換 # -# ǻꤵ줿֥ȤʸѴ롣 +# 引数で指定されたオブジェクトを文字列に変換する。 # -# @param n Ѵоݥ֥ +# @param n 変換対象オブジェクト # -# @return ʸѴ +# @return 文字列変換結果 # # @else # @brief Convert the given object to st::string. # @endif def otos(n): - if type(n) == int or type(n) == str or type(n) == long or type(n) == float: - return str(n) - + if isinstance(n, int) or isinstance(n, str) or isinstance( + n, long) or isinstance(n, float): + return str(n) ## # @if jp -# @brief Ϳ줿ʸꥹȤѴ +# @brief 与えられた文字列をリストに変換 # -# ǻꤵ줿ʸ,ʬ䤷ꥹȤѴ롣 +# 引数で指定された文字列を「,」で分割し、リストに変換する。 # -# @param _type Ѵ̥ꥹ -# @param _str Ѵʸ +# @param _str 変換元文字列 # -# @return ꥹѴ +# @return リスト変換処理結果 # # @else -# +# # @endif def _stringToList(_type, _str): - list_ = split(_str,",") - len_ = len(list_) - - if len(_type[0]) < len(list_): - sub = len(list_) - len(_type[0]) - for i in range(sub): - _type[0].append(_type[0][0]) - elif len(_type[0]) > len(list_): - sub = len(_type[0]) - len(list_) - for i in range(sub): - del _type[0][-1] - - for i in range(len_): - str_ = [list_[i]] - eraseHeadBlank(str_) - eraseTailBlank(str_) - list_[i] = str_[0] - - for i in range(len(list_)): - if type(_type[0][i]) == int: - _type[0][i] = int(list_[i]) - elif type(_type[0][i]) == long: - _type[0][i] = long(list_[i]) - elif type(_type[0][i]) == float: - _type[0][i] = float(list_[i]) - elif type(_type[0][i]) == str: - _type[0][i] = str(list_[i]) - - - else: - return False + list_ = split(_str, ",") + len_ = len(list_) + + if len(_type) < len(list_): + sub = len(list_) - len(_type) + for i in range(sub): + _type.append(_type[0]) + elif len(_type) > len(list_): + sub = len(_type) - len(list_) + for i in range(sub): + del _type[-1] + + for i in range(len_): + list_[i] = eraseHeadBlank(list_[i]) + list_[i] = eraseTailBlank(list_[i]) + + for i, l in enumerate(list_): + if isinstance(_type[i], int): + _type[i] = int(l) + elif isinstance(_type[i], long): + _type[i] = long(l) + elif isinstance(_type[i], float): + _type[i] = float(l) + elif isinstance(_type[i], str): + _type[i] = str(l) + + else: + return False, _type - return True + return True, _type ## # @if jp -# @brief Ϳ줿ʸ򥪥֥ȤѴ +# @brief 与えられた文字列をオブジェクトに変換 # -# Ϳ줿ʸꤵ줿֥ȤѴ롣 +# 引数で与えられた文字列を指定されたオブジェクトに変換する。 # -# @param _type Ѵ襪֥ -# @param _str Ѵʸ +# @param _str 変換元文字列 # -# @return Ѵ¹Է +# @return 変換処理実行結果 # # @else # @brief Convert the given object to st::string. # @endif def stringTo(_type, _str): - if not _str: - return False - - try: - if type(_type[0]) == int: - _type[0] = int(_str) - return True - elif type(_type[0]) == long: - _type[0] = long(_str) - return True - elif type(_type[0]) == float: - _type[0] = float(_str) - return True - elif type(_type[0]) == list: - return _stringToList(_type, _str) - elif type(_type[0]) == str: - _type[0] = str(_str) - return True - - #except ValueError: - # return False - except: - return False - - return False + if not _str: + return False, _type + + try: + if isinstance(_type, int): + _type = int(_str) + return True, _type + elif isinstance(_type, long): + _type = long(_str) + return True, _type + elif isinstance(_type, float): + _type = float(_str) + return True, _type + elif isinstance(_type, list): + return _stringToList(_type, _str) + elif isinstance(_type, str): + _type = str(_str) + return True, _type + + # except ValueError: + # return False, _type + except BaseException: + return False, _type + + return False, _type ## # @if jp -# @brief Ϳ줿ʸꥹȤʣ +# @brief 与えられた文字列リストから重複を削除 # -# Ϳ줿ʸꥹȤʣꥹȤ롣 +# 引数で与えられた文字列リストから重複を削除したリストを作成する。 # -# @param sv ǧʸꥹ +# @param sv 確認元文字列リスト # -# @return ʣ̥ꥹ +# @return 重複削除処理結果リスト # # @else # # @endif def unique_sv(sv): - return for_each(sv, unique_strvec())._str + return for_each(sv, unique_strvec())._str ## # @if jp -# @brief Ϳ줿ʸꥹȤCSV +# @brief 与えられた文字列リストからCSVを生成 # -# Ϳ줿ʸꥹȤγǤ¤٤CSV롣 -# ʸꥹȤξˤ϶ʸ֤ +# 引数で与えられた文字列リストの各要素を並べたCSVを生成する。 +# 文字列リストが空の場合には空白文字を返す。 # -# @param sv CSVѴоʸꥹ -# @param delimiter ³ʸδ֤ʸ (ǥե: ", ") +# @param sv CSV変換対象文字列リスト +# @param delimiter 接続される文字列の間の文字 (デフォルト: ", ") # -# @return CSVѴʸ +# @return CSV変換結果文字列 # # @else # @brief Create CSV file from the given string list @@ -629,47 +629,45 @@ def unique_sv(sv): # # @endif def flatten(sv, delimiter=", "): - if len(sv) == 0: - return "" + if not sv: + return "" - _str = delimiter.join(sv) + _str = delimiter.join(sv) - return _str + return _str ## # @if jp -# @brief Ϳ줿ʸꥹȤꥹȤѴ +# @brief 与えられた文字列リストを引数リストに変換 # -# Ϳ줿ʸꥹȤγ'\\0'ä -# ꥹȤѴ롣
    -# ܥ⥸塼Ǥϰ򤽤Τޤ֤ +# 引数で与えられた文字列リストの各要素末尾に'\\0'を加え、 +# 引数リストに変換する。
    +# ※本モジュールでは引数をそのまま返す # -# @param args Ѵоʸꥹ +# @param args 変換対象文字列リスト # -# @return Ѵʸ +# @return 引数変換結果文字列 # # @else # # @endif def toArgv(args): - return args - - + return args ## # @if jp -# @brief URLѥ᡼mapstringʬ򤷤֤ +# @brief URLパラメータをmapstringに分解して返す # -# URLѥ᡼ɽ something?key0=value0&key1=value1.... Τ -# '?' ʹߤʬʬ򤷤ơstd::map -# Ѵ롣Ϳ줿ʸ򺸤饵'?' 걦¦ʬ -# ĤƲϤԤ'&'ʬ䤷 '=' 򸡺ǽ '=' -# դȺդ򤽤줾졢key value Ȥ map ˳Ǽ롣 +# URLパラメータ表現 something?key0=value0&key1=value1.... のうち +# '?' 以降の部分を分解して、std::map 形式 +# に変換する。与えられた文字列を左からサーチし、'?' より右側の部分に +# ついて解析を行う。'&'で分割し、左から '=' を検索し、最初の '=' の +# 右辺と左辺をそれぞれ、key と value として map に格納する。 # -# @param str ʬоʸ -# @return mapstring key/valueǡ +# @param str 分解対象文字列 +# @return mapstring 型の key/valueデータ # # # @else @@ -693,36 +691,38 @@ def urlparam2map(_str): if qpos == -1: qpos = 0 else: - qpos+=1 + qpos += 1 tmp = _str[qpos:].split("&") retmap = {} for v in tmp: pos = v.find("=") if pos != -1: - retmap[v[0:pos]] = v[pos+1:] + retmap[v[0:pos]] = v[pos + 1:] else: retmap[v] = "" return retmap ## # @if jp -# @brief ʸδĶѿ֤ +# @brief 文字列中の環境変数を置き換える # -# ʸ${}ǰϤޤ줿ʸ󤬤ˡĶѿ֤ -# 㡧${RTM_ROOT}\bin -> C:\Program Files (x86)\OpenRTM-aist\1.1.2\ +# 文字列中に${}で囲まれた文字列がある場合に、環境変数と置き換える +# 例:${RTM_ROOT}\bin -> C:\Program Files (x86)\OpenRTM-aist\1.1.2\ # -# @param _str ֤ʸ -# @return ֤ʸ +# @param _str 置き換え前の文字列 +# @return 置き換え後の文字列 # # # @else -# @brief +# @brief # # @param _str # -# @return +# @return # # @endif + + def replaceEnv(_str): tmp = _str.split("${") if len(tmp) < 2: @@ -734,71 +734,73 @@ def replaceEnv(_str): if tmp2[0] in os.environ: ret.append(os.environ[tmp2[0]]) ret.append(tmp2[1]) - + else: ret.append(v) ret_str = "" for s in ret: ret_str = ret_str + s return ret_str - ## # @if jp -# @brief ե̾ǥ쥯ȥ꤫õ +# @brief 指定ファイル名を指定ディレクトリから探査する # -# @param dir ǥ쥯ȥѥ -# @param filename ե̾ -# @param filelist ե +# @param dir ディレクトリパス +# @param filename ファイル名 +# @param filelist ファイル一覧 # # # # @else -# @brief +# @brief # -# @param dir +# @param dir # @param filename -# @param filelist +# @param filelist # # # @endif def findFile(dir, filename, filelist): - dirs = glob.glob(os.path.join(dir,"*")) - for d in dirs: - if os.path.isdir(d): - findFile(d, filename, filelist) - files = glob.glob(os.path.join(dir,filename)) - for f in files: - if os.path.isfile(d): - filelist.append(f) + dirs = glob.glob(os.path.join(dir, "*")) + for d in dirs: + if os.path.isdir(d): + findFile(d, filename, filelist) + files = glob.glob(os.path.join(dir, filename)) + for f in files: + if os.path.isfile(d): + filelist.append(f) ## # @if jp -# @brief եǥ쥯ȥ꤫õ +# @brief ファイル一覧を指定ディレクトリから探査する # -# @param dir ǥ쥯ȥѥ -# @param ext ĥ -# @param filelist ե +# @param dir ディレクトリパス +# @param ext 拡張子 +# @param filelist ファイル一覧 # # # # @else -# @brief +# @brief # -# @param dir -# @param ext -# @param filelist +# @param dir +# @param ext +# @param filelist # # # @endif -def getFileList(dir, ext, filelist): - dirs = glob.glob(os.path.join(dir,"*")) +def getFileList(dir, ext, filelist=None): + if filelist is None: + filelist = [] + dirs = glob.glob(os.path.join(dir, "*")) for d in dirs: if os.path.isdir(d): - getFileList(d, ext, filelist) - files = glob.glob(os.path.join(dir,"*."+ext)) + filelist = getFileList(d, ext, filelist) + files = glob.glob(os.path.join(dir, "*." + ext)) for f in files: if os.path.isfile(f): - filelist.append(f) \ No newline at end of file + filelist.append(f) + return filelist diff --git a/OpenRTM_aist/SystemLogger.py b/OpenRTM_aist/SystemLogger.py index 24ad5d04..ccaa8652 100644 --- a/OpenRTM_aist/SystemLogger.py +++ b/OpenRTM_aist/SystemLogger.py @@ -1,5 +1,5 @@ #!/usr/bin/env python -# -*- coding: euc-jp -*- +# -*- coding: utf-8 -*- ## # @file SystemLogger.py @@ -24,125 +24,120 @@ import copy - - ## # @if jp # # @class Logg # -# @brief եޥåȥߡ饹 +# @brief ロガーフォーマットダミークラス # -# եޥåѥߡ饹 +# ログフォーマット用ダミークラス。 # # @else # # @endif class Logger: - """ - """ - - SILENT = 0 # () - FATAL = 41 # (FATAL) - ERROR = 40 # (FATAL, ERROR) - WARN = 30 # (FATAL, ERROR, WARN) - INFO = 20 # (FATAL, ERROR, WARN, INFO) - DEBUG = 10 # (FATAL, ERROR, WARN, INFO, DEBUG) - TRACE = 9 # (FATAL, ERROR, WARN, INFO, DEBUG, TRACE) - VERBOSE = 8 # (FATAL, ERROR, WARN, INFO, DEBUG, TRACE, VERBOSE) - PARANOID = 7 # (FATAL, ERROR, WARN, INFO, DEBUG, TRACE, VERBOSE, PARA) - - - ## - # @if jp - # - # @brief ٥ - # - # Ϳ줿ʸб٥ꤹ롣 - # - # @param self - # @param lv ٥ʸ - # - # @return ꤷ٥ - # - # @else - # - # @endif - def strToLogLevel(lv): - if lv == "SILENT": - return Logger.SILENT - elif lv == "FATAL": - return Logger.FATAL - elif lv == "ERROR": - return Logger.ERROR - elif lv == "WARN": - return Logger.WARN - elif lv == "INFO": - return Logger.INFO - elif lv == "DEBUG": - return Logger.DEBUG - elif lv == "TRACE": - return Logger.TRACE - elif lv == "VERBOSE": - return Logger.VERBOSE - elif lv == "PARANOID": - return Logger.PARANOID - else: - return Logger.INFO - - strToLogLevel = staticmethod(strToLogLevel) - - - - - ## - # @if jp - # - # @brief printf եޥåȽ - # - # printf饤ʽ񼰤ǥϤ롣
    - # ܼǤϰ fmt Ϳ줿ʸ򤽤Τޤ֤ - # - # @param self - # @param fmt ʸ - # - # @return դʸ - # - # @else - # - # @brief Formatted output like printf - # - # @endif - def printf(fmt): - return fmt - - printf = staticmethod(printf) - - - ## - # @if jp - # - # @brief 㳰 - # 㳰ʸ֤ - # - # @return 㳰ʸ - # - # @else - # - # @brief Print exception information - # @return Return exception information string. - # - # @endif - def print_exception(): - if sys.version_info[0:3] >= (2, 4, 0): - return traceback.format_exc() - else: - _exc_list = traceback.format_exception(*sys.exc_info()) - _exc_str = "".join(_exc_list) - return _exc_str - - print_exception = staticmethod(print_exception) - + """ + """ + + SILENT = 0 # () + FATAL = 41 # (FATAL) + ERROR = 40 # (FATAL, ERROR) + WARN = 30 # (FATAL, ERROR, WARN) + INFO = 20 # (FATAL, ERROR, WARN, INFO) + DEBUG = 10 # (FATAL, ERROR, WARN, INFO, DEBUG) + TRACE = 9 # (FATAL, ERROR, WARN, INFO, DEBUG, TRACE) + VERBOSE = 8 # (FATAL, ERROR, WARN, INFO, DEBUG, TRACE, VERBOSE) + PARANOID = 7 # (FATAL, ERROR, WARN, INFO, DEBUG, TRACE, VERBOSE, PARA) + + ## + # @if jp + # + # @brief ログレベル設定 + # + # 与えられた文字列に対応したログレベルを設定する。 + # + # @param self + # @param lv ログレベル文字列 + # + # @return 設定したログレベル + # + # @else + # + # @endif + + def strToLogLevel(lv): + if lv == "SILENT": + return Logger.SILENT + elif lv == "FATAL": + return Logger.FATAL + elif lv == "ERROR": + return Logger.ERROR + elif lv == "WARN": + return Logger.WARN + elif lv == "INFO": + return Logger.INFO + elif lv == "DEBUG": + return Logger.DEBUG + elif lv == "TRACE": + return Logger.TRACE + elif lv == "VERBOSE": + return Logger.VERBOSE + elif lv == "PARANOID": + return Logger.PARANOID + else: + return Logger.INFO + + strToLogLevel = staticmethod(strToLogLevel) + + ## + # @if jp + # + # @brief printf フォーマット出力 + # + # printfライクな書式でログ出力する。
    + # ※本実装では引数 fmt で与えられた文字をそのまま返す。 + # + # @param self + # @param fmt 書式文字列 + # + # @return 書式付き文字列出力 + # + # @else + # + # @brief Formatted output like printf + # + # @endif + + def printf(fmt): + return fmt + + printf = staticmethod(printf) + + ## + # @if jp + # + # @brief 例外情報出力 + # 例外情報を文字列で返す。 + # + # @return 例外情報の文字列出力 + # + # @else + # + # @brief Print exception information + # @return Return exception information string. + # + # @endif + + def print_exception(): + if sys.version_info[0:3] >= (2, 4, 0): + return traceback.format_exc() + else: + _exc_list = traceback.format_exception(*sys.exc_info()) + _exc_str = "".join(_exc_list) + return _exc_str + + print_exception = staticmethod(print_exception) ## @@ -150,537 +145,518 @@ def print_exception(): # # @class Logg # -# @brief եޥåȥߡ饹 +# @brief ロガーフォーマットダミークラス # -# եޥåѥߡ饹 +# ログフォーマット用ダミークラス。 # # @else # # @endif class LogStream: - """ - """ - - ## - # @if jp - # - # @brief 󥹥ȥ饯 - # - # 󥹥ȥ饯 - # - # @param self - # @param (mode,file_name,address) - # - # @else - # - # @brief constructor. - # - # @endif - def __init__(self, *args): - self._LogLock = False - self._log_enable = False - - - - self._logger_name = "" - self._mutex = threading.RLock() - self._loggerObj = [] - self._log_enable = True - self.guard = None - - - def __del__(self): - return - - def shutdown(self): - for log in self._loggerObj: - log.shutdown() - self._loggerObj = [] - return - - def addLogger(self, loggerObj): - self.acquire() - self._loggerObj.append(loggerObj) - self.release() - - ## - # @if jp - # - # @brief ٥ - # - # ٥ꤹ롣 - # - # @param self - # @param level ٥ - # - # @else - # - # @endif - def setLogLevel(self, level): - lvl = Logger.strToLogLevel(level) - for log in self._loggerObj: - log.setLogLevel(lvl) - - - - - ## - # @if jp - # - # @brief å⡼ - # - # Υå⡼ɤꤹ롣 - # - # @param self - # @param lock åե饰 - # - # @else - # - # @endif - def setLogLock(self, lock): - if lock == 1: - self._LogLock = True - elif lock == 0: - self._LogLock = False - - - ## - # @if jp - # - # @brief å⡼ͭ - # - # @param self - # - # å⡼ɤͭˤ롣 - # - # @else - # - # @endif - def enableLogLock(self): - self._LogLock = True - - - ## - # @if jp - # - # @brief å⡼ɲ - # - # @param self - # - # å⡼ɤ̵ˤ롣 - # - # @else - # - # @endif - def disableLogLock(self): - self._LogLock = False - - - ## - # @if jp - # - # @brief å - # å⡼ɤꤵƤ硢Υå롣 - # - # @param self - # - # @else - # - # @endif - def acquire(self): - if self._LogLock: - self.guard = OpenRTM_aist.ScopedLock(self._mutex) - - - ## - # @if jp - # - # @brief å - # å⡼ɤꤵƤˡΥå롣 - # - # @param self - # - # @else - # - # @endif - def release(self): - if self._LogLock and self.guard: - del self.guard - - - ## - # @if jp - # - # @brief ѥ - # - # ٥뤪ӽϥեޥåʸȤƤȤꡤ - # ѥϤ롣 - # - # @param self - # @param LV ٥ - # @param msg å - # @param opt ץ(ǥե:None) - # - # @else - # - # @brief Log output macro - # - # @endif - def RTC_LOG(self, LV, msg, opt=None): - if self._log_enable: - self.acquire() - - if opt is None: - messages = msg - else: - try: - messages = msg%(opt) - except: - print("RTC_LOG : argument error") - return - for log in self._loggerObj: - log.log(messages, LV, self._logger_name) - - - self.release() - - - ## - # @if jp - # - # @brief FATAL顼 - # - # FATAL顼٥ΥϤ롣
    ٥뤬 - # FATAL, ERROR, WARN, INFO, DEBUG, TRACE, VERBOSE, PARANOID - # ξ˥Ϥ롣 - # - # @param self - # @param msg å - # @param opt ץ(ǥե:None) - # - # @else - # - # @brief Error log output macro. - # - # @endif - def RTC_FATAL(self, msg, opt=None): - if self._log_enable: - self.acquire() - - if opt is None: - messages = msg - else: - try: - messages = msg%(opt) - except: - print("RTC_FATAL : argument error") - return - - for log in self._loggerObj: - log.log(messages, Logger.FATAL, self._logger_name) - - self.release() - - - ## - # @if jp - # - # @brief 顼 - # - # 顼٥ΥϤ롣
    ٥뤬 - # ERROR, WARN, INFO, DEBUG, TRACE, VERBOSE, PARANOID - # ξ˥Ϥ롣 - # - # @param self - # @param msg å - # @param opt ץ(ǥե:None) - # - # @else - # - # @brief Error log output macro. - # - # @endif - def RTC_ERROR(self, msg, opt=None): - if self._log_enable: - self.acquire() - - if opt is None: - messages = msg - else: - try: - messages = msg%(opt) - except: - print("RTC_ERROR : argument error") - return - - - for log in self._loggerObj: - log.log(messages, Logger.ERROR, self._logger_name) - - self.release() - - - ## - # @if jp - # - # @brief ˥󥰥 - # - # ˥󥰥٥ΥϤ롣
    ٥뤬 - # ( WARN, INFO, DEBUG, TRACE, VERBOSE, PARANOID ) - # ξ˥Ϥ롣 - # - # @param self - # @param msg å - # @param opt ץ(ǥե:None) - # - # @else - # - # @brief Warning log output macro. - # - # If logging levels are - # ( WARN, INFO, DEBUG, TRACE, VERBOSE, PARANOID ), - # message will be output to log. - # - # @endif - def RTC_WARN(self, msg, opt=None): - if self._log_enable: - self.acquire() - - if opt is None: - messages = msg - else: - try: - messages = msg%(opt) - except: - print("RTC_WARN : argument error") - return - - - for log in self._loggerObj: - log.log(messages, Logger.WARN, self._logger_name) - - self.release() - - - ## - # @if jp - # - # @brief ե - # - # ե٥ΥϤ롣
    ٥뤬 - # ( INFO, DEBUG, TRACE, VERBOSE, PARANOID ) - # ξ˥Ϥ롣 - # - # @param self - # @param msg å - # @param opt ץ(ǥե:None) - # - # @else - # - # @brief Infomation level log output macro. - # - # If logging levels are - # ( INFO, DEBUG, TRACE, VERBOSE, PARANOID ), - # message will be output to log. - # - # @endif - def RTC_INFO(self, msg, opt=None): - if self._log_enable: - self.acquire() - - if opt is None: - messages = msg - else: - try: - messages = msg%(opt) - except: - print("RTC_INFO : argument error") - return - - - for log in self._loggerObj: - log.log(messages, Logger.INFO, self._logger_name) - - self.release() - - - ## - # @if jp - # - # @brief ǥХå - # - # ǥХå٥ΥϤ롣
    ٥뤬 - # ( DEBUG, TRACE, VERBOSE, PARANOID ) - # ξ˥Ϥ롣 - # - # @param self - # @param msg å - # @param opt ץ(ǥե:None) - # - # @else - # - # @brief Debug level log output macro. - # - # If logging levels are - # ( DEBUG, TRACE, VERBOSE, PARANOID ), - # message will be output to log. - # - # @endif - def RTC_DEBUG(self, msg, opt=None): - if self._log_enable: - self.acquire() - - if opt is None: - messages = msg - else: - try: - messages = msg%(opt) - except: - print("RTC_DEBUG : argument error") - return - - - for log in self._loggerObj: - log.log(messages, Logger.DEBUG, self._logger_name) - - self.release() - - - ## - # @if jp - # - # @brief ȥ졼 - # - # ȥ졼٥ΥϤ롣
    ٥뤬 - # ( TRACE, VERBOSE, PARANOID ) - # ξ˥Ϥ롣 - # - # @param self - # @param msg å - # @param opt ץ(ǥե:None) - # - # @else - # - # @brief Trace level log output macro. - # - # If logging levels are - # ( TRACE, VERBOSE, PARANOID ), - # message will be output to log. - # - # @endif - def RTC_TRACE(self, msg, opt=None): - if self._log_enable: - self.acquire() - - if opt is None: - messages = msg - - else: - try: - messages = msg%(opt) - except: - print("RTC_TRACE : argument error") - return - - - for log in self._loggerObj: - log.log(messages, Logger.TRACE, self._logger_name) - - self.release() - - - ## - # @if jp - # - # @brief ٥ܡ - # - # ٥ܡ٥ΥϤ롣
    ٥뤬 - # ( VERBOSE, PARANOID ) - # ξ˥Ϥ롣
    - # Ǥ̤ - # - # @param self - # @param msg å - # @param opt ץ(ǥե:None) - # - # @else - # - # @brief Verbose level log output macro. - # - # If logging levels are - # ( VERBOSE, PARANOID ), - # message will be output to log. - # - # @endif - def RTC_VERBOSE(self, msg, opt=None): - if self._log_enable: - self.acquire() - - if opt is None: - messages = msg - else: - try: - messages = msg%(opt) - except: - print("RTC_VERBOSE : argument error") - return - - - for log in self._loggerObj: - log.log(messages, Logger.VERBOSE, self._logger_name) - - self.release() - - - - ## - # @if jp - # - # @brief ѥΥɥ - # - # ѥΥɥ٥ΥϤ롣
    ٥뤬 - # ( PARANOID ) - # ξ˥Ϥ롣
    - # Ǥ̤ - # - # @param self - # @param msg å - # @param opt ץ(ǥե:None) - # - # @else - # - # @brief Paranoid level log output macro. - # - # If logging levels are - # ( PARANOID ), - # message will be output to log. - # - # @endif - def RTC_PARANOID(self, msg, opt=None): - if self._log_enable: - self.acquire() - - if opt is None: - messages = msg - else: - try: - messages = msg%(opt) - except: - print("RTC_PARANOID : argument error") - return - - - for log in self._loggerObj: - log.log(messages, Logger.PARANOID, self._logger_name) - - self.release() - - - def getLogger(self, name): - syslogger = copy.copy(self) - syslogger._logger_name = name - return syslogger - - - - + """ + """ + + ## + # @if jp + # + # @brief コンストラクタ + # + # コンストラクタ + # + # @param self + # @param (mode,file_name,address) + # + # @else + # + # @brief constructor. + # + # @endif + def __init__(self, *args): + self._LogLock = False + self._log_enable = False + + self._logger_name = "" + self._mutex = threading.RLock() + self._loggerObj = [] + self._log_enable = True + self.guard = None + + def __del__(self): + return + + def shutdown(self): + for log in self._loggerObj: + log.shutdown() + self._loggerObj = [] + return + + def addLogger(self, loggerObj): + self.acquire() + self._loggerObj.append(loggerObj) + self.release() + + ## + # @if jp + # + # @brief ログレベル設定 + # + # ログレベルを設定する。 + # + # @param self + # @param level ログレベル + # + # @else + # + # @endif + def setLogLevel(self, level): + lvl = Logger.strToLogLevel(level) + for log in self._loggerObj: + log.setLogLevel(lvl) + + ## + # @if jp + # + # @brief ロックモード設定 + # + # ログのロックモードを設定する。 + # + # @param self + # @param lock ログロックフラグ + # + # @else + # + # @endif + + def setLogLock(self, lock): + if lock == 1: + self._LogLock = True + elif lock == 0: + self._LogLock = False + + ## + # @if jp + # + # @brief ロックモード有効化 + # + # @param self + # + # ロックモードを有効にする。 + # + # @else + # + # @endif + + def enableLogLock(self): + self._LogLock = True + + ## + # @if jp + # + # @brief ロックモード解除 + # + # @param self + # + # ロックモードを無効にする。 + # + # @else + # + # @endif + + def disableLogLock(self): + self._LogLock = False + + ## + # @if jp + # + # @brief ログロック取得 + # ロックモードが設定されている場合、ログのロックを取得する。 + # + # @param self + # + # @else + # + # @endif + + def acquire(self): + if self._LogLock: + self.guard = OpenRTM_aist.ScopedLock(self._mutex) + + ## + # @if jp + # + # @brief ログロック解放 + # ロックモードが設定されている場合に、ログのロックを解放する。 + # + # @param self + # + # @else + # + # @endif + + def release(self): + if self._LogLock and self.guard: + del self.guard + + ## + # @if jp + # + # @brief 汎用ログ出力 + # + # ログレベルおよび出力フォーマット文字列を引数としてとり, + # 汎用ログを出力する。 + # + # @param self + # @param LV ログレベル + # @param msg ログメッセージ + # @param opt オプション(デフォルト値:None) + # + # @else + # + # @brief Log output macro + # + # @endif + + def RTC_LOG(self, LV, msg, opt=None): + if self._log_enable: + self.acquire() + + if opt is None: + messages = msg + else: + try: + messages = msg % (opt) + except BaseException: + print("RTC_LOG : argument error") + return + for log in self._loggerObj: + log.log(str(messages), LV, self._logger_name) + + self.release() + + ## + # @if jp + # + # @brief FATALエラーログ出力 + # + # FATALエラーレベルのログを出力する。
    ログレベルが + # FATAL, ERROR, WARN, INFO, DEBUG, TRACE, VERBOSE, PARANOID + # の場合にログ出力される。 + # + # @param self + # @param msg ログメッセージ + # @param opt オプション(デフォルト値:None) + # + # @else + # + # @brief Error log output macro. + # + # @endif + + def RTC_FATAL(self, msg, opt=None): + if self._log_enable: + self.acquire() + + if opt is None: + messages = msg + else: + try: + messages = msg % (opt) + except BaseException: + print("RTC_FATAL : argument error") + return + + for log in self._loggerObj: + log.log(str(messages), Logger.FATAL, self._logger_name) + + self.release() + + ## + # @if jp + # + # @brief エラーログ出力 + # + # エラーレベルのログを出力する。
    ログレベルが + # ERROR, WARN, INFO, DEBUG, TRACE, VERBOSE, PARANOID + # の場合にログ出力される。 + # + # @param self + # @param msg ログメッセージ + # @param opt オプション(デフォルト値:None) + # + # @else + # + # @brief Error log output macro. + # + # @endif + + def RTC_ERROR(self, msg, opt=None): + if self._log_enable: + self.acquire() + + if opt is None: + messages = msg + else: + try: + messages = msg % (opt) + except BaseException: + print("RTC_ERROR : argument error") + return + + for log in self._loggerObj: + log.log(str(messages), Logger.ERROR, self._logger_name) + + self.release() + + ## + # @if jp + # + # @brief ワーニングログ出力 + # + # ワーニングレベルのログを出力する。
    ログレベルが + # ( WARN, INFO, DEBUG, TRACE, VERBOSE, PARANOID ) + # の場合にログ出力される。 + # + # @param self + # @param msg ログメッセージ + # @param opt オプション(デフォルト値:None) + # + # @else + # + # @brief Warning log output macro. + # + # If logging levels are + # ( WARN, INFO, DEBUG, TRACE, VERBOSE, PARANOID ), + # message will be output to log. + # + # @endif + + def RTC_WARN(self, msg, opt=None): + if self._log_enable: + self.acquire() + + if opt is None: + messages = msg + else: + try: + messages = msg % (opt) + except BaseException: + print("RTC_WARN : argument error") + return + + for log in self._loggerObj: + log.log(str(messages), Logger.WARN, self._logger_name) + + self.release() + + ## + # @if jp + # + # @brief インフォログ出力 + # + # インフォレベルのログを出力する。
    ログレベルが + # ( INFO, DEBUG, TRACE, VERBOSE, PARANOID ) + # の場合にログ出力される。 + # + # @param self + # @param msg ログメッセージ + # @param opt オプション(デフォルト値:None) + # + # @else + # + # @brief Infomation level log output macro. + # + # If logging levels are + # ( INFO, DEBUG, TRACE, VERBOSE, PARANOID ), + # message will be output to log. + # + # @endif + + def RTC_INFO(self, msg, opt=None): + if self._log_enable: + self.acquire() + + if opt is None: + messages = msg + else: + try: + messages = msg % (opt) + except BaseException: + print("RTC_INFO : argument error") + return + + for log in self._loggerObj: + log.log(str(messages), Logger.INFO, self._logger_name) + + self.release() + + ## + # @if jp + # + # @brief デバッグログ出力 + # + # デバッグレベルのログを出力する。
    ログレベルが + # ( DEBUG, TRACE, VERBOSE, PARANOID ) + # の場合にログ出力される。 + # + # @param self + # @param msg ログメッセージ + # @param opt オプション(デフォルト値:None) + # + # @else + # + # @brief Debug level log output macro. + # + # If logging levels are + # ( DEBUG, TRACE, VERBOSE, PARANOID ), + # message will be output to log. + # + # @endif + + def RTC_DEBUG(self, msg, opt=None): + if self._log_enable: + self.acquire() + + if opt is None: + messages = msg + else: + try: + messages = msg % (opt) + except BaseException: + print("RTC_DEBUG : argument error") + return + + for log in self._loggerObj: + log.log(str(messages), Logger.DEBUG, self._logger_name) + + self.release() + + ## + # @if jp + # + # @brief トレースログ出力 + # + # トレースレベルのログを出力する。
    ログレベルが + # ( TRACE, VERBOSE, PARANOID ) + # の場合にログ出力される。 + # + # @param self + # @param msg ログメッセージ + # @param opt オプション(デフォルト値:None) + # + # @else + # + # @brief Trace level log output macro. + # + # If logging levels are + # ( TRACE, VERBOSE, PARANOID ), + # message will be output to log. + # + # @endif + + def RTC_TRACE(self, msg, opt=None): + if self._log_enable: + self.acquire() + + if opt is None: + messages = msg + + else: + try: + messages = msg % (opt) + except BaseException: + print("RTC_TRACE : argument error") + return + + for log in self._loggerObj: + log.log(str(messages), Logger.TRACE, self._logger_name) + + self.release() + + ## + # @if jp + # + # @brief ベルボーズログ出力 + # + # ベルボーズレベルのログを出力する。
    ログレベルが + # ( VERBOSE, PARANOID ) + # の場合にログ出力される。
    + # ※現状では未実装 + # + # @param self + # @param msg ログメッセージ + # @param opt オプション(デフォルト値:None) + # + # @else + # + # @brief Verbose level log output macro. + # + # If logging levels are + # ( VERBOSE, PARANOID ), + # message will be output to log. + # + # @endif + + def RTC_VERBOSE(self, msg, opt=None): + if self._log_enable: + self.acquire() + + if opt is None: + messages = msg + else: + try: + messages = msg % (opt) + except BaseException: + print("RTC_VERBOSE : argument error") + return + + for log in self._loggerObj: + log.log(str(messages), Logger.VERBOSE, self._logger_name) + + self.release() + + ## + # @if jp + # + # @brief パラノイドログ出力 + # + # パラノイドレベルのログを出力する。
    ログレベルが + # ( PARANOID ) + # の場合にログ出力される。
    + # ※現状では未実装 + # + # @param self + # @param msg ログメッセージ + # @param opt オプション(デフォルト値:None) + # + # @else + # + # @brief Paranoid level log output macro. + # + # If logging levels are + # ( PARANOID ), + # message will be output to log. + # + # @endif + + def RTC_PARANOID(self, msg, opt=None): + if self._log_enable: + self.acquire() + + if opt is None: + messages = msg + else: + try: + messages = msg % (opt) + except BaseException: + print("RTC_PARANOID : argument error") + return + + for log in self._loggerObj: + log.log(str(messages), Logger.PARANOID, self._logger_name) + + self.release() + + def getLogger(self, name): + syslogger = copy.copy(self) + syslogger._logger_name = name + return syslogger diff --git a/OpenRTM_aist/Task.py b/OpenRTM_aist/Task.py index 9afaf4e7..8c862e7e 100644 --- a/OpenRTM_aist/Task.py +++ b/OpenRTM_aist/Task.py @@ -1,5 +1,5 @@ #!/usr/bin/env python -# -*- coding: euc-jp -*- +# -*- coding: utf-8 -*- ## # @file Task.py @@ -17,66 +17,57 @@ import threading -class Task: - def __init__(self): - self._count = 0 - self._thread = None - return - - - def __del__(self): - self._count = 0 - #if self._thread: - # if self._thread.isAlive(): - # self._thread.join() - self._thread = None - return - - - def open(self, args = None): - return 0 - - - def close(self, flags = 0): - return 0 - - - def svc(self): - return 0 - - - def activate(self): - if self._count == 0: - self._thread = threading.Thread(target=self.svc_run) - self._count += 1 - self._thread.start() - return - - def wait(self): - if self._count > 0: - self._thread.join() - return - - - def suspend(self): - return 0 - - - def resume(self): - return 0 - - - def reset(self): - self._count = 0 - return - - - def finalize(self): - self.reset() - return - - def svc_run(self): - self.svc() - self.finalize() - return +class Task: + def __init__(self): + self._count = 0 + self._thread = None + return + + def __del__(self): + self._count = 0 + # if self._thread: + # if self._thread.isAlive(): + # self._thread.join() + self._thread = None + return + + def open(self, args=None): + return 0 + + def close(self, flags=0): + return 0 + + def svc(self): + return 0 + + def activate(self): + if self._count == 0: + self._thread = threading.Thread(target=self.svc_run) + self._count += 1 + self._thread.start() + return + + def wait(self): + if self._count > 0: + self._thread.join() + return + + def suspend(self): + return 0 + + def resume(self): + return 0 + + def reset(self): + self._count = 0 + return + + def finalize(self): + self.reset() + return + + def svc_run(self): + self.svc() + self.finalize() + return diff --git a/OpenRTM_aist/TimeMeasure.py b/OpenRTM_aist/TimeMeasure.py index 939ba2df..0fec69a2 100644 --- a/OpenRTM_aist/TimeMeasure.py +++ b/OpenRTM_aist/TimeMeasure.py @@ -1,5 +1,5 @@ #!/usr/bin/env python -# -*- coding: euc-jp -*- +# -*- coding: utf-8 -*- ## # @file TimeMeasure.py @@ -29,11 +29,11 @@ ULLONG_MAX = 0xffffffffffffffff if sys.version_info[0] == 3: - long = int + long = int ## # @if jp -# @brief ñѴ +# @brief 時間単位変換用定数 # @else # @endif usec_per_sec = 1000000 @@ -41,279 +41,285 @@ ## # @if jp # @class Time -# @brief ִѥ饹 -# -# ꤷͤݻ뤿Υ饹 -# +# @brief 時間管理用クラス +# +# 指定した時間値を保持するためのクラス。 +# # @since 0.4.1 -# +# # @else -# +# # @endif + + class Time: - """ - """ - - ## - # @if jp - # @brief 󥹥ȥ饯 - # - # 󥹥ȥ饯 - # - # @param self - # - # @else - # @brief Constructor. - # - # Constructor. - # - # @param self - # - # @endif - def __init__(self): - global usec_per_sec - tm = time.time() - tm_f = float(tm - long(tm)) # μФ - self.sec = long(tm - tm_f) # μФ - self.usec = long(float(tm_f) * float(usec_per_sec)) # sec -> usec (micro second) - self._timevalue = OpenRTM_aist.TimeValue(self.sec,self.usec) - return - - ## - # @if jp - # - # @brief ָ - # - # ꤵ줿֤Ϳ줿֤򸺻롣 - # - # @param self - # @param tm - # - # @return - # - # @else - # - # @endif - def __sub__(self, tm): - global usec_per_sec - - res = Time() - - if self.sec >= tm.sec: - if self.usec >= tm.usec: - res.sec = self.sec - tm.sec - res.usec = self.usec - tm.usec - else: - res.sec = self.sec - tm.sec - 1 - res.usec = (self.usec + usec_per_sec) - tm.usec - else: - if tm.usec >= self.usec: - res.sec = -(tm.sec - self.sec) - res.usec = -(tm.usec - self.usec) - else: - res.sec = -(tm.sec - self.sec - 1) - res.usec = -(tm.usec + usec_per_sec) + self.usec - return res - - - def gettimeofday(self): - global usec_per_sec - - - tm = time.time() - tm_f = float(tm - long(tm)) # μФ - self.sec = long(float(tm) - float(tm_f)) # μФ - self.usec = long(float(tm_f) * float(usec_per_sec)) # sec -> usec (micro second) - return OpenRTM_aist.TimeValue(self.sec, self.usec) - - - def getTime(self): - return OpenRTM_aist.TimeValue(self.sec, self.usec) - - - # inline int settimeofday(const struct timeval *tv , const struct timezone *tz) - def settimeofday(self, tv, tz): - if os.name == "nt": - from ctypes import windll, Structure, c_ushort, byref, c_ulong, c_long - class SYSTEMTIME(Structure): - _fields_ = [('wYear', c_ushort), - ('wMonth', c_ushort), - ('wDayOfWeek', c_ushort), - ('wDay', c_ushort), - ('wHour', c_ushort), - ('wMinute', c_ushort), - ('wSecond', c_ushort), - ('wMilliseconds', c_ushort)] - - - class LARGE_INTEGER(Structure): - _fields_ = [('low', c_ulong), - ('high', c_long)] - - global usec_per_sec - - tm = long(tv.tv_sec*1e6) + long(tv.tv_usec) - st = SYSTEMTIME(0,0,0,0,0,0,0,0) - ft = LARGE_INTEGER(tm&0xFFFFFFFF,tm>>32) - # 100 nanosecond units (since 16010101) - ret = windll.kernel32.FileTimeToSystemTime(byref(ft), - byref(st)) - if not ret: - return -1 - - #windll.kernel32.SetSystemTime(byref(st)) - print("settime Yer:", st.wYear, " Month:", st.wMonth, \ - " DayOfWeek:", st.wDayOfWeek, " wDay:", st.wDay, \ - " Hour:", st.wHour, "Minute:", st.wMinute, \ - " Second:", st.wSecond, "Milliseconds:", st.wMilliseconds) - - - else: - import ctypes - class timespec(ctypes.Structure): - _fields_ = [('tv_sec', ctypes.c_long), - ('tv_nsec', ctypes.c_long)] - - #librt = ctypes.cdll.LoadLibrary('librt.so') - #ts = timespec(long(tv.tv_sec),long(tv.tv_usec*1000)) - #return librt.clock_settime(0, ctypes.pointer(ts)) - - return 0 + """ + """ + + ## + # @if jp + # @brief コンストラクタ + # + # コンストラクタ。 + # + # @param self + # + # @else + # @brief Constructor. + # + # Constructor. + # + # @param self + # + # @endif + def __init__(self): + global usec_per_sec + tm = time.time() + tm_f = float(tm - long(tm)) # 小数部の取り出し + self.sec = long(tm - tm_f) # 整数部の取り出し + self.usec = long(float(tm_f) * float(usec_per_sec) + ) # sec -> usec (micro second) + self._timevalue = OpenRTM_aist.TimeValue(self.sec, self.usec) + return + + ## + # @if jp + # + # @brief 時間減算 + # + # 設定された時間から引数で与えられた時間を減算する。 + # + # @param self + # @param tm 減算時間 + # + # @return 減算結果 + # + # @else + # + # @endif + def __sub__(self, tm): + global usec_per_sec + + res = Time() + + if self.sec >= tm.sec: + if self.usec >= tm.usec: + res.sec = self.sec - tm.sec + res.usec = self.usec - tm.usec + else: + res.sec = self.sec - tm.sec - 1 + res.usec = (self.usec + usec_per_sec) - tm.usec + else: + if tm.usec >= self.usec: + res.sec = -(tm.sec - self.sec) + res.usec = -(tm.usec - self.usec) + else: + res.sec = -(tm.sec - self.sec - 1) + res.usec = -(tm.usec + usec_per_sec) + self.usec + return res + + def gettimeofday(self): + global usec_per_sec + + tm = time.time() + tm_f = float(tm - long(tm)) # 小数部の取り出し + self.sec = long(float(tm) - float(tm_f)) # 整数部の取り出し + self.usec = long(float(tm_f) * float(usec_per_sec) + ) # sec -> usec (micro second) + return OpenRTM_aist.TimeValue(self.sec, self.usec) + + def getTime(self): + return OpenRTM_aist.TimeValue(self.sec, self.usec) + + # inline int settimeofday(const struct timeval *tv , const struct timezone + # *tz) + + def settimeofday(self, tv, tz): + if os.name == "nt": + from ctypes import windll, Structure, c_ushort, byref, c_ulong, c_long + + class SYSTEMTIME(Structure): + _fields_ = [('wYear', c_ushort), + ('wMonth', c_ushort), + ('wDayOfWeek', c_ushort), + ('wDay', c_ushort), + ('wHour', c_ushort), + ('wMinute', c_ushort), + ('wSecond', c_ushort), + ('wMilliseconds', c_ushort)] + + class LARGE_INTEGER(Structure): + _fields_ = [('low', c_ulong), + ('high', c_long)] + + global usec_per_sec + + tm = long(tv.tv_sec * 1e6) + long(tv.tv_usec) + st = SYSTEMTIME(0, 0, 0, 0, 0, 0, 0, 0) + ft = LARGE_INTEGER(tm & 0xFFFFFFFF, tm >> 32) + # 100 nanosecond units (since 16010101) + ret = windll.kernel32.FileTimeToSystemTime(byref(ft), + byref(st)) + if not ret: + return -1 + + # windll.kernel32.SetSystemTime(byref(st)) + print("settime Yer:", st.wYear, " Month:", st.wMonth, + " DayOfWeek:", st.wDayOfWeek, " wDay:", st.wDay, + " Hour:", st.wHour, "Minute:", st.wMinute, + " Second:", st.wSecond, "Milliseconds:", st.wMilliseconds) + + else: + import ctypes + + class timespec(ctypes.Structure): + _fields_ = [('tv_sec', ctypes.c_long), + ('tv_nsec', ctypes.c_long)] + + #librt = ctypes.cdll.LoadLibrary('librt.so') + #ts = timespec(long(tv.tv_sec),long(tv.tv_usec*1000)) + # return librt.clock_settime(0, ctypes.pointer(ts)) + + return 0 ## # TimeMeasure object # -# This object is used for getting statistics of code execution time. +# This object is used for getting statistics of code execution time. # Using get_stat you can get maximum, minimum, mean and standard # deviation time for code execution. # + + class TimeMeasure: - """ - """ - - ## - # @brief Time statictics object for profiling. - # - # Constructor - # - def __init__(self, buflen=100): - self._countMax = buflen + 1 - self._record = [OpenRTM_aist.TimeValue(0, 0) for i in range(self._countMax)] - self._begin = Time().gettimeofday() - self._end = Time().gettimeofday() - self._count = 0 - self._recurred = False - self._interval = OpenRTM_aist.TimeValue(0.0) - return - - ## - # @brief Begin time measurement for time statistics. - # - # Begin time measurement for time statistics - # - def tick(self): - self._begin = Time().gettimeofday() - return - - ## - # @brief Finish time measurement for time statistics. - # - # End of time measurement for time statistics - # - def tack(self): - if self._begin.sec() == 0: - return - - self._interval = Time().gettimeofday() - self._begin - self._end = Time().gettimeofday() - self._record[self._count] = self._interval - self._count += 1 - if self._count == self._countMax: - self._count = 0 - self._recurred = True - return - - def interval(self): - return self._interval - - - def reset(self): - self._count = 0 - self._recurred = False - self._begin = OpenRTM_aist.TimeValue(0.0) - return - - ## - # Get number of time measurement buffer - # - # @brief Get number of time measurement buffer. - # - # - def count(self): - if self._recurred: - - return len(self._record) - else: - return self._count - - - ## - # @brief Get total statistics. - # Get total statistics - # max_interval, min_interval, mean_interval [ns] - # - def getStatistics(self, max_interval=None, min_interval=None, - mean_interval=None, stddev=None): - global ULLONG_MAX - - if not max_interval and not min_interval and not mean_interval and not stddev: - max_i = [0.0] - min_i = [0.0] - mean_i = [0.0] - stdd = [0.0] - - self.getStatistics(max_i, min_i, mean_i, stdd) - return self.Statistics(max_i[0], min_i[0], mean_i[0], stdd[0]) - - max_interval[0] = 0.0 - min_interval[0] = ULLONG_MAX - - sum_ = 0.0 - sq_sum_ = 0.0 - len_ = self.count() - - if len_ == 0: - return False - - for i in range(len_): - trecord_ = self._record[i].toDouble() - sum_ += trecord_ - sq_sum_ += (trecord_ * trecord_) - - if trecord_ > max_interval[0]: - max_interval[0] = trecord_ - - if trecord_ < min_interval[0]: - min_interval[0] = trecord_ - - - mean_interval[0] = sum_ / len_ - stddev[0] = math.sqrt(sq_sum_ / len_ - (mean_interval[0] * mean_interval[0])) - - return True - - - class Statistics: - def __init__(self, max=None, min=None, mean=None, stdd=None): - if not max and not min and not mean and not stdd: - self._max_interval = 0.0 - self._min_interval = 0.0 - self._mean_interval = 0.0 - self._std_deviation = 0.0 + """ + """ + + ## + # @brief Time statictics object for profiling. + # + # Constructor + # + def __init__(self, buflen=100): + self._countMax = buflen + 1 + self._record = [ + OpenRTM_aist.TimeValue( + 0, + 0) for i in range( + self._countMax)] + self._begin = Time().gettimeofday() + self._end = Time().gettimeofday() + self._count = 0 + self._recurred = False + self._interval = OpenRTM_aist.TimeValue(0.0) + return + + ## + # @brief Begin time measurement for time statistics. + # + # Begin time measurement for time statistics + # + def tick(self): + self._begin = Time().gettimeofday() + return + + ## + # @brief Finish time measurement for time statistics. + # + # End of time measurement for time statistics + # + def tack(self): + if self._begin.sec() == 0: + return + + self._interval = Time().gettimeofday() - self._begin + self._end = Time().gettimeofday() + self._record[self._count] = self._interval + self._count += 1 + if self._count == self._countMax: + self._count = 0 + self._recurred = True + return + + def interval(self): + return self._interval + + def reset(self): + self._count = 0 + self._recurred = False + self._begin = OpenRTM_aist.TimeValue(0.0) return - self._max_interval = max - self._min_interval = min - self._mean_interval = mean - self._std_deviation = stdd - return + ## + # Get number of time measurement buffer + # + # @brief Get number of time measurement buffer. + # + # + def count(self): + if self._recurred: + + return len(self._record) + else: + return self._count + + ## + # @brief Get total statistics. + # Get total statistics + # max_interval, min_interval, mean_interval [ns] + # + + def getStatistics(self, max_interval=None, min_interval=None, + mean_interval=None, stddev=None): + global ULLONG_MAX + + if not max_interval and not min_interval and not mean_interval and not stddev: + max_i = [0.0] + min_i = [0.0] + mean_i = [0.0] + stdd = [0.0] + + self.getStatistics(max_i, min_i, mean_i, stdd) + return self.Statistics(max_i[0], min_i[0], mean_i[0], stdd[0]) + + max_interval[0] = 0.0 + min_interval[0] = ULLONG_MAX + + sum_ = 0.0 + sq_sum_ = 0.0 + len_ = self.count() + + if len_ == 0: + return False + + for i in range(len_): + trecord_ = self._record[i].toDouble() + sum_ += trecord_ + sq_sum_ += (trecord_ * trecord_) + + if trecord_ > max_interval[0]: + max_interval[0] = trecord_ + + if trecord_ < min_interval[0]: + min_interval[0] = trecord_ + + mean_interval[0] = sum_ / len_ + stddev[0] = math.sqrt( + sq_sum_ / len_ - (mean_interval[0] * mean_interval[0])) + + return True + + class Statistics: + def __init__(self, max=None, min=None, mean=None, stdd=None): + if not max and not min and not mean and not stdd: + self._max_interval = 0.0 + self._min_interval = 0.0 + self._mean_interval = 0.0 + self._std_deviation = 0.0 + return + + self._max_interval = max + self._min_interval = min + self._mean_interval = mean + self._std_deviation = stdd + return diff --git a/OpenRTM_aist/TimeValue.py b/OpenRTM_aist/TimeValue.py index 412cfa17..028bb6b4 100644 --- a/OpenRTM_aist/TimeValue.py +++ b/OpenRTM_aist/TimeValue.py @@ -1,5 +1,5 @@ #!/usr/bin/env python -# -*- coding: euc-jp -*- +# -*- coding: utf-8 -*- ## @@ -18,273 +18,274 @@ import sys -TIMEVALUE_ONE_SECOND_IN_USECS = 1000000 # 1 [sec] = 1000000 [usec] +TIMEVALUE_ONE_SECOND_IN_USECS = 1000000 # 1 [sec] = 1000000 [usec] if sys.version_info[0] == 3: - long = int + long = int ## # @if jp # @class TimeValue -# @brief ַ׻ѥ饹 -# -# ꤷͤݻ뤿Υ饹 -# ͤФƼ׻ѥڥ졼󶡤롣 +# @brief 時間計算用クラス +# +# 指定した時間値を保持するためのクラス。 +# 時間値に対する各種計算用オペレーションを提供する。 # # @since 0.4.0 # # @else # # @endif + + class TimeValue: - """ - """ - - - - ## - # @if jp - # - # @brief 󥹥ȥ饯 - # - # 󥹥ȥ饯 - # ꤵ줿áޥäǽ롣 - # - # @param self - # @param sec (ǥե:None) - # @param usec ޥ(ǥե:None) - # - # @else - # - # @endif - def __init__(self, sec=None, usec=None): - global TIMEVALUE_ONE_SECOND_IN_USECS - - - if type(sec) == str: - sec = float(sec) - if type(usec) == str: - usec = float(usec) - - # TimeValue(double timeval) - if sec and usec is None: - if sec >= 0.0: - dbHalfAdj_ = 0.5 - else: - dbHalfAdj_ = -0.5 - - self.tv_sec = long(sec) - self.tv_usec = long((sec - float(self.tv_sec)) * - float(TIMEVALUE_ONE_SECOND_IN_USECS) + dbHalfAdj_) - self.normalize() - return - - if sec is None: - self.tv_sec = long(0) - else: - self.tv_sec = long(sec) - - if usec is None: - self.tv_usec = long(0) - else: - self.tv_usec = long(usec) - self.normalize() - return - - - ## - # @if jp - # - # @brief ָ - # - # ꤵ줿֤Ϳ줿֤򸺻롣 - # - # @param self - # @param tm - # - # @return - # - # @else - # - # @endif - def __sub__(self, tm): - global TIMEVALUE_ONE_SECOND_IN_USECS - - res = TimeValue() - - if self.tv_sec >= tm.tv_sec: - # + - if self.tv_usec >= tm.tv_usec: - # 겼̵ - res.tv_sec = self.tv_sec - tm.tv_sec - res.tv_usec = self.tv_usec - tm.tv_usec - else: - # self.tv_usec < tm.tv_usec 겼ͭ - res.tv_sec = self.tv_sec - tm.tv_sec - 1 - res.tv_usec = (self.tv_usec + TIMEVALUE_ONE_SECOND_IN_USECS) - tm.tv_usec - else: - # self.tv_sec < tm.tv_sec # - - if tm.tv_usec >= self.tv_usec: - # 겼̵ - res.tv_sec = -(tm.tv_sec - self.tv_sec) - res.tv_usec = -(tm.tv_usec - self.tv_usec) - else: - # tm.tv_usec < self.tv_usec 겼ͭ - res.tv_sec = -(tm.tv_sec - self.tv_sec - 1) - res.tv_usec = -(tm.tv_usec + TIMEVALUE_ONE_SECOND_IN_USECS) + self.tv_usec - - res.normalize() - return res - - - ## - # @if jp - # - # @brief ֲû - # - # ꤵ줿֤˰Ϳ줿֤û롣 - # - # @param self - # @param tm û - # - # @return û - # - # @else - # - # @endif - def __add__(self, tm): - global TIMEVALUE_ONE_SECOND_IN_USECS - res = TimeValue() - res.tv_sec = self.tv_sec + tm.tv_sec - res.tv_usec = self.tv_usec + tm.tv_usec - if res.tv_usec > TIMEVALUE_ONE_SECOND_IN_USECS: - res.tv_sec += 1 - res.tv_usec -= TIMEVALUE_ONE_SECOND_IN_USECS - - res.normalize() - return res - - - def sec(self): - return self.tv_sec - - - def usec(self): - return self.tv_usec - - - ## - # @if jp - # - # @brief doubleַѴ - # - # Ϳ줿doubleַѴ롣 - # - # @param self - # @param time Ѵ - # - # @return Ѵ - # - # @else - # - # @endif - def set_time(self, time): - global TIMEVALUE_ONE_SECOND_IN_USECS - - self.tv_sec = long(time) - self.tv_usec = long((time - float(self.tv_sec)) * float(TIMEVALUE_ONE_SECOND_IN_USECS)) - return self - - ## - # @if jp - # - # @brief ַdoubleѴ - # - # ݻƤƤdoubleѴ롣 - # - # @param self - # @return doubleѴ - # - # @else - # - # @endif - def toDouble(self): - global TIMEVALUE_ONE_SECOND_IN_USECS - return float(self.tv_sec) + float(self.tv_usec / float(TIMEVALUE_ONE_SECOND_IN_USECS)) - - - ## - # @if jp - # @brief ֤Ϥ - # - # ֤ʸϤ롣
    - # - # @param self - # - # @return ʸɽ - # - # @else - # - # @endif - def __str__(self): - global TIMEVALUE_ONE_SECOND_IN_USECS - return str(self.tv_sec + self.tv_usec / float(TIMEVALUE_ONE_SECOND_IN_USECS)) - - ## - # @if jp - # @brief Ƚ - # - # ݻƤƤȽꤹ롣
    - # - # @param self - # - # @return ʤ1ʤ-10ʤ0 - # - # @else - # - # @endif - def sign(self): - if self.tv_sec > 0: - return 1 - if self.tv_sec < 0: - return -1 - if self.tv_usec > 0: - return 1 - if self.tv_usec < 0: - return -1 - return 0 - - - ## - # @if jp - # @brief - # @else - # @brief Normalize - # @endif - # - def normalize(self): - global TIMEVALUE_ONE_SECOND_IN_USECS - if self.tv_usec >= TIMEVALUE_ONE_SECOND_IN_USECS: - self.tv_sec += 1 - self.tv_usec -= TIMEVALUE_ONE_SECOND_IN_USECS - - while self.tv_usec >= TIMEVALUE_ONE_SECOND_IN_USECS: - self.tv_sec += 1 - self.tv_usec -= TIMEVALUE_ONE_SECOND_IN_USECS - - elif self.tv_usec <= -TIMEVALUE_ONE_SECOND_IN_USECS: - self.tv_sec -= 1 - self.tv_usec += TIMEVALUE_ONE_SECOND_IN_USECS - - while self.tv_usec <= -TIMEVALUE_ONE_SECOND_IN_USECS: - self.tv_sec -= 1 - self.tv_usec += TIMEVALUE_ONE_SECOND_IN_USECS - - - if self.tv_sec >= 1 and self.tv_usec < 0: - self.tv_sec -= 1 - self.tv_usec += TIMEVALUE_ONE_SECOND_IN_USECS - - elif self.tv_sec < 0 and self.tv_usec > 0: - self.tv_sec += 1 - self.tv_usec -= TIMEVALUE_ONE_SECOND_IN_USECS + """ + """ + + ## + # @if jp + # + # @brief コンストラクタ + # + # コンストラクタ + # 指定された秒,マイクロ秒で初期化する。 + # + # @param self + # @param sec 秒(デフォルト値:None) + # @param usec マイクロ秒(デフォルト値:None) + # + # @else + # + # @endif + def __init__(self, sec=None, usec=None): + global TIMEVALUE_ONE_SECOND_IN_USECS + + if isinstance(sec, str): + sec = float(sec) + if isinstance(usec, str): + usec = float(usec) + + # TimeValue(double timeval) + if sec and usec is None: + if sec >= 0.0: + dbHalfAdj_ = 0.5 + else: + dbHalfAdj_ = -0.5 + + self.tv_sec = long(sec) + self.tv_usec = long((sec - float(self.tv_sec)) * + float(TIMEVALUE_ONE_SECOND_IN_USECS) + dbHalfAdj_) + self.normalize() + return + + if sec is None: + self.tv_sec = long(0) + else: + self.tv_sec = long(sec) + + if usec is None: + self.tv_usec = long(0) + else: + self.tv_usec = long(usec) + self.normalize() + return + + ## + # @if jp + # + # @brief 時間減算 + # + # 設定された時間から引数で与えられた時間を減算する。 + # + # @param self + # @param tm 減算時間 + # + # @return 減算結果 + # + # @else + # + # @endif + + def __sub__(self, tm): + global TIMEVALUE_ONE_SECOND_IN_USECS + + res = TimeValue() + + if self.tv_sec >= tm.tv_sec: + # + + if self.tv_usec >= tm.tv_usec: + # 繰り下がり無し + res.tv_sec = self.tv_sec - tm.tv_sec + res.tv_usec = self.tv_usec - tm.tv_usec + else: + # self.tv_usec < tm.tv_usec 繰り下がり有り + res.tv_sec = self.tv_sec - tm.tv_sec - 1 + res.tv_usec = ( + self.tv_usec + TIMEVALUE_ONE_SECOND_IN_USECS) - tm.tv_usec + else: + # self.tv_sec < tm.tv_sec # - + if tm.tv_usec >= self.tv_usec: + # 繰り下がり無し + res.tv_sec = -(tm.tv_sec - self.tv_sec) + res.tv_usec = -(tm.tv_usec - self.tv_usec) + else: + # tm.tv_usec < self.tv_usec 繰り下がり有り + res.tv_sec = -(tm.tv_sec - self.tv_sec - 1) + res.tv_usec = - \ + (tm.tv_usec + TIMEVALUE_ONE_SECOND_IN_USECS) + self.tv_usec + + res.normalize() + return res + + ## + # @if jp + # + # @brief 時間加算 + # + # 設定された時間に引数で与えられた時間を加算する。 + # + # @param self + # @param tm 加算時間 + # + # @return 加算結果 + # + # @else + # + # @endif + + def __add__(self, tm): + global TIMEVALUE_ONE_SECOND_IN_USECS + res = TimeValue() + res.tv_sec = self.tv_sec + tm.tv_sec + res.tv_usec = self.tv_usec + tm.tv_usec + if res.tv_usec > TIMEVALUE_ONE_SECOND_IN_USECS: + res.tv_sec += 1 + res.tv_usec -= TIMEVALUE_ONE_SECOND_IN_USECS + + res.normalize() + return res + + def sec(self): + return self.tv_sec + + def usec(self): + return self.tv_usec + + ## + # @if jp + # + # @brief double型→時間型変換 + # + # 引数で与えられたdouble型を時間型に変換する。 + # + # @param self + # @param time 変換元値 + # + # @return 変換結果 + # + # @else + # + # @endif + + def set_time(self, time): + global TIMEVALUE_ONE_SECOND_IN_USECS + + self.tv_sec = long(time) + self.tv_usec = long((time - float(self.tv_sec)) * + float(TIMEVALUE_ONE_SECOND_IN_USECS)) + return self + + ## + # @if jp + # + # @brief 時間型→double型変換 + # + # 保持している内容をdouble型に変換する。 + # + # @param self + # @return double型変換結果 + # + # @else + # + # @endif + def toDouble(self): + global TIMEVALUE_ONE_SECOND_IN_USECS + return float(self.tv_sec) + float(self.tv_usec / + float(TIMEVALUE_ONE_SECOND_IN_USECS)) + + ## + # @if jp + # @brief 設定時間を出力する + # + # 設定時間を文字列出力する。
    + # + # @param self + # + # @return 設定時間文字列表示 + # + # @else + # + # @endif + + def __str__(self): + global TIMEVALUE_ONE_SECOND_IN_USECS + return str(self.tv_sec + self.tv_usec / + float(TIMEVALUE_ONE_SECOND_IN_USECS)) + + ## + # @if jp + # @brief 符号判定 + # + # 保持している内容の符号を判定する。
    + # + # @param self + # + # @return 正ならば1を、負ならば-1を、0ならば0 + # + # @else + # + # @endif + def sign(self): + if self.tv_sec > 0: + return 1 + if self.tv_sec < 0: + return -1 + if self.tv_usec > 0: + return 1 + if self.tv_usec < 0: + return -1 + return 0 + + ## + # @if jp + # @brief 正規化 + # @else + # @brief Normalize + # @endif + # + + def normalize(self): + global TIMEVALUE_ONE_SECOND_IN_USECS + if self.tv_usec >= TIMEVALUE_ONE_SECOND_IN_USECS: + self.tv_sec += 1 + self.tv_usec -= TIMEVALUE_ONE_SECOND_IN_USECS + + while self.tv_usec >= TIMEVALUE_ONE_SECOND_IN_USECS: + self.tv_sec += 1 + self.tv_usec -= TIMEVALUE_ONE_SECOND_IN_USECS + + elif self.tv_usec <= -TIMEVALUE_ONE_SECOND_IN_USECS: + self.tv_sec -= 1 + self.tv_usec += TIMEVALUE_ONE_SECOND_IN_USECS + + while self.tv_usec <= -TIMEVALUE_ONE_SECOND_IN_USECS: + self.tv_sec -= 1 + self.tv_usec += TIMEVALUE_ONE_SECOND_IN_USECS + + if self.tv_sec >= 1 and self.tv_usec < 0: + self.tv_sec -= 1 + self.tv_usec += TIMEVALUE_ONE_SECOND_IN_USECS + + elif self.tv_sec < 0 and self.tv_usec > 0: + self.tv_sec += 1 + self.tv_usec -= TIMEVALUE_ONE_SECOND_IN_USECS diff --git a/OpenRTM_aist/Timer.py b/OpenRTM_aist/Timer.py index 4b03f75b..5923e59d 100644 --- a/OpenRTM_aist/Timer.py +++ b/OpenRTM_aist/Timer.py @@ -1,5 +1,5 @@ -#!/usr/bin/env/python -# -*- coding: euc-jp -*- +#!/usr/bin/env python +# -*- coding: utf-8 -*- ## # @file Timer.py @@ -20,347 +20,349 @@ import OpenRTM_aist - ## # @if jp -# @class Timer -# @brief Timer饹 -# -# Ͽ줿ꥹʡΥХåؿꤵ줿Ū˸ƤӽФ +# @class DelayedFunction +# @brief 実行遅延関数呼び出し # -# @since 0.4.0 +# @since 2.0.0 # # @else # -# @class Timer -# @brief Timer class -# -# Invoke the callback function of registered listener periodically -# at the set cycle. +# @class DelayedFunction +# @brief Delayed function call # -# @since 0.4.0 +# @since 2.0.0 # # @endif -class Timer: - """ - """ - ## - # @if jp - # @brief 󥹥ȥ饯 - # - # 󥹥ȥ饯 - # - # @param self - # @param interval ޵ư - # - # @else - # - # @brief Constructor - # - # Constructor - # - # @param interval The interval of timer - # - # @endif - def __init__(self, interval): - self._interval = interval - self._running = False - self._runningMutex = threading.RLock() - self._tasks = [] - self._taskMutex = threading.RLock() - self._thread = threading.Thread(target=self.run) - return - ## - # @if jp - # @brief ǥȥ饯 - # - # ǥȥ饯 - # - # @else - # @brief Destructor - # - # Destructor - # - # @endif - # - def __del__(self): - self._running = False +class DelayedFunction(object): + ## + # @if jp + # @brief コンストラクタ + # @param fn: 実行する関数または関数オブジェクト + # @param delay: 実行までの遅延時間 + # + # @else + # @brief Constructor + # @param fn: Function or functional object + # @return delay: the delay until function call + # + # @endif + def __init__(self, function, delay): + self._fn = function + self._remains = delay + ## + # @if jp + # @brief 1回の時間経過 + # @param interval: 経過した時間 + # @return bool true: 期限が来た + # false: 期限が来ていない + # + # interval 分だけ期限を減算し、期限切れの場合に関数を実行する。 + # + # @else + # @brief Tick + # @param interval: Tick interval + # @return bool true: The function is expired and executed. + # false: The function is unexpired. + # @endif - self.join() + def tick(self, interval): + self._remains -= interval + is_expired = (self._remains.toDouble() <= 0.0) + if is_expired: + self._fn() + return is_expired + +## +# @if jp +# @class PeriodicFunction +# @brief 周期関数呼び出し +# +# @since 2.0.0 +# +# @else +# +# @class PeriodicFunction +# @brief Periodic function call +# +# @since 2.0.0 +# +# @endif - self._thread = None - def join(self): - try: - self._thread.join() - #self._thread = threading.Thread(target=self.run) - except: - pass +class PeriodicFunction(object): + ## + # @if jp + # @brief コンストラクタ + # @param fn 実行する関数または関数オブジェクト + # @param period 実行間隔 + # + # @else + # @brief Constructor + # @param fn Function or functional object + # @param period + # + # + # @endif + def __init__(self, function, period): + self._fn = function + self._remains = OpenRTM_aist.TimeValue(0, 0) + self._period = period + self._lock = threading.RLock() + self._isRemoved = False + ## + # @if jp + # @brief 1回の時間経過 + # @param interval: 経過した時間 + # @return 停止中の場合は実行せずにTrueを返す + # + # interval 分だけ期限を減算し、期限切れの場合に関数を実行する。 + # 関数が実行されると周期が再設定される。 + # + # @else + # @brief Tick + # @param interval: Tick interval + # @return + # @endif - return + def tick(self, interval): + guard = OpenRTM_aist.ScopedLock(self._lock) + if self._isRemoved: + return True + self._remains -= interval + if self._remains.toDouble() <= 0.0: + self._fn() + self._remains = self._period + return False + ## + # @if jp + # @brief 周期実行を停止する + # + # + # @param self + # + # @else + # + # @brief Stop to execute function + # + # + # @param self + # + # @endif - ## - # @if jp - # @brief Timer ѤΥåɼ¹Դؿ - # - # Timer ѤΥåɼ¹Դؿ - # Ͽ줿ꥹʡΥХåؿƤӽФ - # - # @return ¹Է - # - # @else - # @brief Thread execution function for Timer - # - # Thread execution function for Timer. - # Invoke the callback function of registered listener. - # - # @return Execution result - # - # @endif - def run(self): - while self._running: - self.invoke() - if self._interval.tv_sec != 0: - time.sleep(self._interval.tv_sec) - elif self._interval.tv_usec: - time.sleep(self._interval.tv_usec/1000000.0) - return 0 + def stop(self): + guard = OpenRTM_aist.ScopedLock(self._lock) + self._isRemoved = True +## +# @if jp +# @class Timer +# @brief Timerクラス +# +# 登録されたリスナーのコールバック関数を、設定された周期で定期的に呼び出す。 +# +# @since 0.4.0 +# +# @else +# +# @class Timer +# @brief Timer class +# +# Invoke the callback function of registered listener periodically +# at the set cycle. +# +# @since 0.4.0 +# +# @endif - ## - # @if jp - # @brief Timer - # - # Timer ѿåɤ򳫻Ϥ롣 - # - # @param self - # - # @brief Start Timer task - # - # Create a new theread for Timer and start processing. - # - # @else - # - # @endif - def start(self): - guard = OpenRTM_aist.ScopedLock(self._runningMutex) - if not self._running: - self._running = True - self._thread.start() - return +# TODO: The "object" class inheritance must be removed in Python3 +class Timer(object): + """ + """ + ## + # @if jp + # @brief コンストラクタ + # + # コンストラクタ + # + # @param self + # @param interval タイマ起動周期 + # + # @else + # + # @brief Constructor + # + # Constructor + # + # @param self + # @param interval The interval of timer + # + # @endif - ## - # @if jp - # @brief Timer - # - # @param self - # - # Timer ߤ롣 - # - # @else - # - # @brief Stop Timer task - # - # Stop Timer task. - # - # @endif - def stop(self): - guard = OpenRTM_aist.ScopedLock(self._runningMutex) - if self._running: - self._running = False - self.join() - return + def __init__(self): + self._lock = threading.RLock() + self._tasks = [] + return + ## + # @if jp + # @brief デストラクタ + # + # デストラクタ + # + # @param self + # + # @else + # @brief Destructor + # + # Destructor + # + # @param self + # + # @endif + # + def __del__(self): + pass - ## - # @if jp - # @brief Timer ¹ - # - # @param self - # - # Ͽ줿ƥꥹʤεưԤ֤饿޵ư򸺻롣 - # ưԤ֤Ȥʤäꥹʤ¸ߤϡ - # ХåؿƤӽФ - # - # @else - # - # @brief Invoke Timer task - # - # Subtract the interval of timer from the waiting time for invocation - # of each registered listener. - # If the listener whose waiting time reached 0 exists, invoke the - # callback function. - # - # @endif - def invoke(self): - guard = OpenRTM_aist.ScopedLock(self._taskMutex) - for i in range(len(self._tasks)): - self._tasks[i].remains = self._tasks[i].remains - self._interval - if self._tasks[i].remains.sign() <= 0.0: - self._tasks[i].remains = self._tasks[i].period - self._tasks[i].listener.invoke() - del guard - return + ## + # @if jp + # @brief 1回の時間経過 + # @param interval: 経過した時間 + # @return bool true 固定 + # + # interval 分だけ期限を減算し、期限切れの場合に関数を実行する。 + # 関数が実行されると周期が再設定される。 + # + # @else + # @brief Tick + # @param interval: Tick interval + # @return bool true only + # + # @endif + def tick(self, interval): + guard = OpenRTM_aist.ScopedLock(self._lock) + tasks = self._tasks[:] + del guard + for task in tasks: + if task.tick(interval): + guard = OpenRTM_aist.ScopedLock(self._lock) + self._tasks.remove(task) + del guard - ## - # @if jp - # @brief ꥹʡϿ - # - # Timer 鵯ư륳ХåؿѤΥꥹʡưꤷ - # Ͽ롣 - # ƱꥹʡϿѤߤξϡꥹʡεưꤷͤ - # 롣 - # - # @param self - # @param listener Ͽоݥꥹʡ - # @param tm ꥹʡư - # - # @return Ͽꥹʡ - # - # @else - # - # @brief Register listener - # - # Register the listener of callback function invoked from this Timer by - # specifying the interval. - # If the same listener has already been regiseterd, the value specified - # the invocation interval of listener will be updated. - # - # - # @param listener Listener for the registration - # @param tm The invocation interval of listener - # - # @return ID of the registerd listener - # - # @endif - # ListenerId registerListener(ListenerBase* listener, TimeValue tm); - def registerListener(self, listener, tm): - guard = OpenRTM_aist.ScopedLock(self._taskMutex) - for i in range(len(self._tasks)): - if self._tasks[i].listener == listener: - self._tasks[i].period = tm - self._tasks[i].remains = tm - return listener - self._tasks.append(self.Task(listener, tm)) - return listener +## +# @if jp +# @class DelayedTimer +# @brief 実行遅延関数呼び出し用のタイマー +# @since 2.0.0 +# @else +# @class DelayedTimer +# @brief Timer of delayed function call +# @since 2.0.0 +# @endif +# - ## - # @if jp - # @brief ꥹʡϿ - # - # Хåоݥ֥ȡХåоݥ᥽åɤӵư - # ꤷƥꥹʡϿ롣 - # - # @param self - # @param obj Хåоݥ֥ - # @param cbf Хåоݥ᥽å - # @param tm ꥹʡư - # - # @return Ͽꥹʡ - # - # @else - # - # @brief Register listener - # - # Register listener by specifying the object for callback, the method - # for callback and the invocation interval. - # - # @param obj Target object for callback - # @param cbf Target method for callback - # @param tm The invocation interval of listener - # - # @return ID of the registerd listener - # - # - # @endif - # template - # ListenerId registerListenerObj(ListenerClass* obj, - # void (ListenerClass::*cbf)(), - # TimeValue tm) - def registerListenerObj(self, obj, cbf, tm): - return self.registerListener(OpenRTM_aist.ListenerObject(obj, cbf), tm) +class DelayedTimer(Timer): + ## + # @if jp + # @brief コンストラクタ + # + # コンストラクタ + # + # @param self + # + # @else + # + # @brief Constructor + # + # Constructor + # + # @param self + # + # @endif + def __init__(self): + super(DelayedTimer, self).__init__() - ## - # @if jp - # @brief ꥹʡϿ - # - # Хåоݥ᥽åɤȵưꤷƥꥹʡϿ롣 - # - # @param self - # @param cbf Хåоݥ᥽å - # @param tm ꥹʡư - # - # @return Ͽꥹʡ - # - # @else - # - # @brief Register listener - # - # Register listener by specifying the method for callback and the - # invocation interval. - # - # @param cbf Target method for callback - # @param tm The invocation interval of listener - # - # @return ID of the registerd listener - # - # @endif - # ListenerId registerListenerFunc(void (*cbf)(), TimeValue tm) - def registerListenerFunc(self, cbf, tm): - return self.registerListener(OpenRTM_aist.ListenerFunc(cbf), tm) + ## + # @if jp + # @brief 非同期処理を登録する + # + # @param self + # @param fn 登録関数 + # @return 関数オブジェクト + # + # @else + # + # @brief Add an async function into list. + # + # @param self + # @param fn 登録関数 + # @return 関数オブジェクト + # + # @endif + def emplace(self, fn, *args): + guard = OpenRTM_aist.ScopedLock(self._lock) + funcobj = DelayedFunction(fn, *args) + self._tasks.append(funcobj) + return funcobj +## +# @if jp +# @class PeriodicTimer +# @brief 周期関数呼び出し用タイマー +# @since 2.0.0 +# @else +# @class PeriodicTimer +# @brief Timer of periodic function call +# @endif +# - ## - # @if jp - # @brief ꥹʡϿ - # - # ꤷIDΥꥹʡϿ롣 - # ꤷIDΥꥹʡ̤Ͽξ硢false ֤ - # - # @param self - # @param id ϿоݥꥹʡID - # - # @return Ͽ - # - # @else - # - # @brief Unregister listener - # - # Unregister the listener specified by ID. - # If the listener specified by ID is not registerd, false will be returned. - # - # @param id ID of the unregisterd listener - # - # @return Unregistration result - # - # @endif - # bool unregisterListener(ListenerId id); - def unregisterListener(self, id): - guard = OpenRTM_aist.ScopedLock(self._taskMutex) - len_ = len(self._tasks) - for i in range(len_): - idx = (len_ - 1) - i - if self._tasks[idx].listener == id: - del self._tasks[idx] - return True - return False +class PeriodicTimer(Timer): + ## + # @if jp + # @brief コンストラクタ + # + # コンストラクタ + # + # @param self + # + # @else + # + # @brief Constructor + # + # Constructor + # + # @param self + # + # @endif + def __init__(self): + super(PeriodicTimer, self).__init__() - ## - # @if jp - # @class Task - # @brief ѥ饹 - # @else - # - # @endif - class Task: - def __init__(self, lb, tm): - self.listener = lb - self.period = tm - self.remains = tm - return + ## + # @if jp + # @brief 非同期処理を登録する + # + # @param self + # @param fn 登録関数 + # @return 関数オブジェクト + # + # @else + # + # @brief Add an async function into list. + # + # @param self + # @param fn 登録関数 + # @return 関数オブジェクト + # + # @endif + def emplace(self, fn, *args): + guard = OpenRTM_aist.ScopedLock(self._lock) + funcobj = PeriodicFunction(fn, *args) + self._tasks.append(funcobj) + return funcobj diff --git a/OpenRTM_aist/Timestamp.py b/OpenRTM_aist/Timestamp.py index acc2b37e..9cdf5586 100644 --- a/OpenRTM_aist/Timestamp.py +++ b/OpenRTM_aist/Timestamp.py @@ -1,5 +1,5 @@ #!/usr/bin/env python -# -*- coding: euc-jp -*- +# -*- coding: utf-8 -*- ## # @file Timestamp.py @@ -17,23 +17,16 @@ class Timestamp(OpenRTM_aist.ConnectorDataListenerT): - def __init__(self, ts_type): - self._ts_type = ts_type - def __del__(self): - pass - def __call__(self, info, data): - if info.properties.getProperty("timestamp_policy") != self._ts_type: - return OpenRTM_aist.ConnectorListenerStatus.NO_CHANGE - tm = OpenRTM_aist.Time().gettimeofday() - data.tm.sec = tm.sec() - data.tm.nsec = tm.usec() * 1000 - return OpenRTM_aist.ConnectorListenerStatus.DATA_CHANGED - - - - - - - - - + def __init__(self, ts_type): + self._ts_type = ts_type + + def __del__(self): + pass + + def __call__(self, info, data): + if info.properties.getProperty("timestamp_policy") != self._ts_type: + return OpenRTM_aist.ConnectorListenerStatus.NO_CHANGE, data + tm = OpenRTM_aist.Time().gettimeofday() + data.tm.sec = tm.sec() + data.tm.nsec = tm.usec() * 1000 + return OpenRTM_aist.ConnectorListenerStatus.DATA_CHANGED, data diff --git a/OpenRTM_aist/Typename.py b/OpenRTM_aist/Typename.py index f25c77c6..a95623da 100644 --- a/OpenRTM_aist/Typename.py +++ b/OpenRTM_aist/Typename.py @@ -1,5 +1,5 @@ #!/usr/bin/env python -# -*- coding: euc-jp -*- +# -*- coding: utf-8 -*- ## # @file Typename.py @@ -17,9 +17,6 @@ # - - - -## const char* toTypename(value) +# const char* toTypename(value) def toTypename(value): - return str(value._NP_RepositoryId) + return str(value._NP_RepositoryId) diff --git a/OpenRTM_aist/__init__.py b/OpenRTM_aist/__init__.py index 35386ec7..01c9e51c 100644 --- a/OpenRTM_aist/__init__.py +++ b/OpenRTM_aist/__init__.py @@ -131,4 +131,14 @@ from Timestamp import * from MultilayerCompositeEC import * #from MultilayerCompositeChildEC import * - +from ByteDataStreamBase import * +from CORBA_CdrMemoryStream import * +from InPortCSPConsumer import * +from OutPortCSPConsumer import * +from InPortCSPProvider import * +from OutPortCSPProvider import * +from InPortDuplexConnector import * +from OutPortDuplexConnector import * +from CSPInPort import * +from CSPOutPort import * +from CSPManager import * diff --git a/OpenRTM_aist/docs/__init__.py b/OpenRTM_aist/docs/__init__.py index 932b7982..270be2a2 100644 --- a/OpenRTM_aist/docs/__init__.py +++ b/OpenRTM_aist/docs/__init__.py @@ -1 +1 @@ -# Empty file +# Empty file diff --git a/OpenRTM_aist/examples/AutoControl/AutoControl.py b/OpenRTM_aist/examples/AutoControl/AutoControl.py index 3509193d..01ae22a8 100644 --- a/OpenRTM_aist/examples/AutoControl/AutoControl.py +++ b/OpenRTM_aist/examples/AutoControl/AutoControl.py @@ -1,14 +1,14 @@ -#!/usr/bin/env python +#!/usr/bin/env python # -*- coding: utf-8 -*- # -*- Python -*- +import OpenRTM_aist +import RTC import sys import time sys.path.append(".") # Import RTM module -import RTC -import OpenRTM_aist # Import Service implementation class # @@ -22,109 +22,104 @@ # This module's spesification # -AutoControl_spec = ["implementation_id", "AutoControl", - "type_name", "AutoControl", - "description", "Auto controller component for MobileRobot", - "version", "1.0.0", - "vendor", "AIST", - "category", "example", - "activity_type", "DataFlowComponent", - "max_instance", "1", - "language", "Python", - "lang_type", "SCRIPT", +AutoControl_spec = ["implementation_id", "AutoControl", + "type_name", "AutoControl", + "description", "Auto controller component for MobileRobot", + "version", "1.0.0", + "vendor", "AIST", + "category", "example", + "activity_type", "DataFlowComponent", + "max_instance", "1", + "language", "Python", + "lang_type", "SCRIPT", "conf.default.velocity", "80.0", "conf.default.turn_velocity", "80.0", "conf.default.distance_to_env", "40.0", ""] # + class AutoControl(OpenRTM_aist.DataFlowComponentBase): - def __init__(self, manager): - OpenRTM_aist.DataFlowComponentBase.__init__(self, manager) - # initialize of configuration-data. - # - self._velocity = [80.0] - self._turn_velocity = [80.0] - self._distance_to_env = [40.0] - - return - - - def onInitialize(self): - # Bind variables and configuration variable - self.bindParameter("velocity", self._velocity, "80.0") - self.bindParameter("turn_velocity", self._turn_velocity, "80.0") - self.bindParameter("distance_to_env", self._distance_to_env, "40.0") - - self._d_sens = RTC.TimedFloatSeq(RTC.Time(0,0),[]) - self._sensIn = OpenRTM_aist.InPort("sens", self._d_sens) - self._d_vel = RTC.TimedFloatSeq(RTC.Time(0,0),[]) - self._velOut = OpenRTM_aist.OutPort("vel", self._d_vel) - - # Set InPort buffers - self.addInPort("sens",self._sensIn) - - # Set OutPort buffers - self.addOutPort("vel",self._velOut) - - return RTC.RTC_OK - - - - def onActivated(self, ec_id): - self._d_vel.data = [0.0, 0.0] - self._velOut.write() - return RTC.RTC_OK - - def onDeactivated(self, ec_id): - self._d_vel.data = [0.0, 0.0] - self._velOut.write() - return RTC.RTC_OK - - def onExecute(self, ec_id): - if self._sensIn.isNew(): - self._d_sens = self._sensIn.read() - self._d_vel.data = self.calcVel() - self._velOut.write() - time.sleep(0.1) - return RTC.RTC_OK - - time.sleep(0.1) - return RTC.RTC_OK - - - - def calcVel(self): - if self._d_sens.data[3] <= self._distance_to_env[0]: - return [self._turn_velocity[0], -(self._turn_velocity[0])] - - elif self._d_sens.data[3] > self._distance_to_env[0]: - return [self._velocity[0] for i in range(2)] - else: - return [0.0 for i in range(2)] - - + def __init__(self, manager): + OpenRTM_aist.DataFlowComponentBase.__init__(self, manager) + # initialize of configuration-data. + # + self._velocity = [80.0] + self._turn_velocity = [80.0] + self._distance_to_env = [40.0] + + return + + def onInitialize(self): + # Bind variables and configuration variable + self.bindParameter("velocity", self._velocity, "80.0") + self.bindParameter("turn_velocity", self._turn_velocity, "80.0") + self.bindParameter("distance_to_env", self._distance_to_env, "40.0") + + self._d_sens = RTC.TimedFloatSeq(RTC.Time(0, 0), []) + self._sensIn = OpenRTM_aist.InPort("sens", self._d_sens) + self._d_vel = RTC.TimedFloatSeq(RTC.Time(0, 0), []) + self._velOut = OpenRTM_aist.OutPort("vel", self._d_vel) + + # Set InPort buffers + self.addInPort("sens", self._sensIn) + + # Set OutPort buffers + self.addOutPort("vel", self._velOut) + + return RTC.RTC_OK + + def onActivated(self, ec_id): + self._d_vel.data = [0.0, 0.0] + self._velOut.write() + return RTC.RTC_OK + + def onDeactivated(self, ec_id): + self._d_vel.data = [0.0, 0.0] + self._velOut.write() + return RTC.RTC_OK + + def onExecute(self, ec_id): + if self._sensIn.isNew(): + self._d_sens = self._sensIn.read() + self._d_vel.data = self.calcVel() + self._velOut.write() + time.sleep(0.1) + return RTC.RTC_OK + + time.sleep(0.1) + return RTC.RTC_OK + + def calcVel(self): + if self._d_sens.data[3] <= self._distance_to_env[0]: + return [self._turn_velocity[0], -(self._turn_velocity[0])] + + elif self._d_sens.data[3] > self._distance_to_env[0]: + return [self._velocity[0] for i in range(2)] + else: + return [0.0 for i in range(2)] + def AutoControlInit(manager): - profile = OpenRTM_aist.Properties(defaults_str=AutoControl_spec) - manager.registerFactory(profile, - AutoControl, - OpenRTM_aist.Delete) + profile = OpenRTM_aist.Properties(defaults_str=AutoControl_spec) + manager.registerFactory(profile, + AutoControl, + OpenRTM_aist.Delete) -def MyModuleInit(manager): - AutoControlInit(manager) - # Create a component - comp = manager.createComponent("AutoControl") +def MyModuleInit(manager): + AutoControlInit(manager) + # Create a component + comp = manager.createComponent("AutoControl") def main(): - mgr = OpenRTM_aist.Manager.init(sys.argv) - mgr.setModuleInitProc(MyModuleInit) - mgr.activateManager() - mgr.runManager() + mgr = OpenRTM_aist.Manager.init(sys.argv) + mgr.setModuleInitProc(MyModuleInit) + mgr.activateManager() + mgr.runManager() -if __name__ == "__main__": - main() +if __name__ == "__main__": + main() diff --git a/OpenRTM_aist/examples/AutoControl/__init__.py b/OpenRTM_aist/examples/AutoControl/__init__.py index 932b7982..270be2a2 100644 --- a/OpenRTM_aist/examples/AutoControl/__init__.py +++ b/OpenRTM_aist/examples/AutoControl/__init__.py @@ -1 +1 @@ -# Empty file +# Empty file diff --git a/OpenRTM_aist/examples/AutoTest/AutoTestComposite.py b/OpenRTM_aist/examples/AutoTest/AutoTestComposite.py index ddd544e4..30a6cbdc 100644 --- a/OpenRTM_aist/examples/AutoTest/AutoTestComposite.py +++ b/OpenRTM_aist/examples/AutoTest/AutoTestComposite.py @@ -1,4 +1,4 @@ -#!/usr/bin/env python +#!/usr/bin/env python # -*- coding: utf-8 -*- # -*- Python -*- @@ -7,45 +7,48 @@ import socket from rtc_handle10_11 import * -from CorbaNaming import * +import OpenRTM_aist +from OpenRTM_aist.CorbaNaming import * import RTM +def main(): + env = RtmEnv(sys.argv, ["localhost:2809"]) -env = RtmEnv(sys.argv, ["localhost:2809"]) + # Get Manager object reference + mgr_name = socket.gethostname() + ".host_cxt/manager.mgr" + naming = CorbaNaming(env.orb, "localhost:2809") + manager = naming.resolve(mgr_name)._narrow(RTM.Manager) -## Get Manager object reference -mgr_name = socket.gethostname()+".host_cxt/manager.mgr" -naming = CorbaNaming(env.orb, "localhost:2809") -manager = naming.resolve(mgr_name)._narrow(RTM.Manager) + listo = env.name_space["localhost:2809"].list_obj() + env.name_space['localhost:2809'].rtc_handles.keys() -listo = env.name_space["localhost:2809"].list_obj() -env.name_space['localhost:2809'].rtc_handles.keys() + ns = env.name_space['localhost:2809'] -ns = env.name_space['localhost:2809'] + comp = ns.rtc_handles["PeriodicECSharedComposite0.rtc"] + config = comp.rtc_ref.get_configuration() + configset = config.get_configuration_sets() + config_data = configset[0].configuration_data -comp = ns.rtc_handles["PeriodicECSharedComposite0.rtc"] -config = comp.rtc_ref.get_configuration() -configset = config.get_configuration_sets() -config_data = configset[0].configuration_data + time.sleep(1) + motor = ns.rtc_handles["Motor0.rtc"] + sensor = ns.rtc_handles["Sensor0.rtc"] + controller = ns.rtc_handles["Controller0.rtc"] + loop_count = 1000 + for i in range(loop_count): + manager.create_component("PeriodicECSharedComposite?instance_name=aaa") + env.name_space["localhost:2809"].list_obj() + aaa = ns.rtc_handles[socket.gethostname() + ".host_cxt/aaa.rtc"] + org = aaa.rtc_ref.get_owned_organizations()[0] + org.set_members([motor.rtc_ref, sensor.rtc_ref, controller.rtc_ref]) + time.sleep(1) + ret = org.remove_member("Motor0") + ret = org.remove_member("Sensor0") + ret = org.remove_member("Controller0") + aaa.rtc_ref.exit() + time.sleep(1) -time.sleep(1) - -motor = ns.rtc_handles["Motor0.rtc"] -sensor = ns.rtc_handles["Sensor0.rtc"] -controller = ns.rtc_handles["Controller0.rtc"] -loop_count = 1000 -for i in range(loop_count): - manager.create_component("PeriodicECSharedComposite?instance_name=aaa") - env.name_space["localhost:2809"].list_obj() - aaa=ns.rtc_handles[socket.gethostname()+".host_cxt/aaa.rtc"] - org=aaa.rtc_ref.get_owned_organizations()[0] - org.set_members ([motor.rtc_ref,sensor.rtc_ref,controller.rtc_ref]) - time.sleep(1) - ret = org.remove_member("Motor0") - ret = org.remove_member("Sensor0") - ret = org.remove_member("Controller0") - aaa.rtc_ref.exit() - time.sleep(1) +if __name__ == '__main__': + main() diff --git a/OpenRTM_aist/examples/AutoTest/AutoTestIn.py b/OpenRTM_aist/examples/AutoTest/AutoTestIn.py index 1a7d7b06..7717e635 100755 --- a/OpenRTM_aist/examples/AutoTest/AutoTestIn.py +++ b/OpenRTM_aist/examples/AutoTest/AutoTestIn.py @@ -1,4 +1,4 @@ -#!/usr/bin/env python +#!/usr/bin/env python # -*- coding:utf-8 -*- ## @@ -8,17 +8,18 @@ # from __future__ import print_function +import AutoTest__POA +import AutoTest +import os.path +import math +import OpenRTM_aist +import RTC import sys import string import time sys.path.append(".") # Import RTM module -import RTC -import OpenRTM_aist -import math -import AutoTest, AutoTest__POA -import os.path # @@ -29,16 +30,16 @@ # This module's spesification # -AutoTestIn_spec = ["implementation_id", "AutoTestIn", - "type_name", "AutoTestIn", - "description", "ModuleDescription", - "version", "1.0.0", - "vendor", "HarumiMiyamoto", - "category", "example", - "activity_type", "STATIC", - "max_instance", "1", - "language", "Python", - "lang_type", "SCRIPT", +AutoTestIn_spec = ["implementation_id", "AutoTestIn", + "type_name", "AutoTestIn", + "description", "ModuleDescription", + "version", "1.0.0", + "vendor", "HarumiMiyamoto", + "category", "example", + "activity_type", "STATIC", + "max_instance", "1", + "language", "Python", + "lang_type", "SCRIPT", "exec_cxt.periodic.rate", "1.0", ""] # @@ -46,141 +47,142 @@ # Class implementing IDL interface MyService(MyService.idl) class MyServiceSVC_impl(AutoTest__POA.MyService): - def __init__(self): - self._echoList = [] - self._valueList = [] - self._value = 0 - self.__echo_msg= "" - self._isNew = False - - def __del__(self): - pass - - def echo(self, msg): - OpenRTM_aist.CORBA_SeqUtil.push_back(self._echoList, msg) - self.__echo_msg = msg - if self._isNew: - #print("echo's message was overwritten !!!") - pass - self._isNew = True - return msg - - def get_echo(self): - if self._isNew: - self._isNew = False - echomsg = self.__echo_msg - return echomsg - - return "" - - def reset_message(self): - self._isNew = False - self.__echo_msg = "" + def __init__(self): + self._echoList = [] + self._valueList = [] + self._value = 0 + self.__echo_msg = "" + self._isNew = False + + def __del__(self): + pass + + def echo(self, msg): + OpenRTM_aist.CORBA_SeqUtil.push_back(self._echoList, msg) + self.__echo_msg = msg + if self._isNew: + #print("echo's message was overwritten !!!") + pass + self._isNew = True + return msg + + def get_echo(self): + if self._isNew: + self._isNew = False + echomsg = self.__echo_msg + return echomsg + + return "" + + def reset_message(self): + self._isNew = False + self.__echo_msg = "" + class AutoTestIn(OpenRTM_aist.DataFlowComponentBase): - - """ - \class AutoTestIn - \brief ModuleDescription - - """ - def __init__(self, manager): + """ - \brief constructor - \param manager Maneger Object + \class AutoTestIn + \brief ModuleDescription + """ - OpenRTM_aist.DataFlowComponentBase.__init__(self, manager) - self._cnt=0 - self._flag=0 - - def onInitialize(self): - self._d_dp_vIn = RTC.TimedFloat(RTC.Time(0,0),0) - self._d_dp_vSeqIn = RTC.TimedFloatSeq(RTC.Time(0,0),[]) - - self._InIn = OpenRTM_aist.InPort("in", self._d_dp_vIn, OpenRTM_aist.RingBuffer(8)) - self._SeqInIn = OpenRTM_aist.InPort("seqin", self._d_dp_vSeqIn, OpenRTM_aist.RingBuffer(8)) - - - # Set InPort buffers - self.addInPort("in",self._InIn) - self.addInPort("seqin",self._SeqInIn) - - # Set OutPort buffers - self._MyServicePort = OpenRTM_aist.CorbaPort("MyService") - #self._myservice0_var = MyService_i() - - # initialization of Provider - self._myservice0_var = MyServiceSVC_impl() - - # Set service provider to Ports - self._MyServicePort.registerProvider("myservice0", "MyService", self._myservice0_var) - - # Set CORBA Service Ports - self.addPort(self._MyServicePort) - - return RTC.RTC_OK - - - def onActivated(self, ec_id): - self._file=open('received-data','w') - self._msg = "" - return RTC.RTC_OK - - def onDeactivated(self, ec_id): - self._file.close() - self._myservice0_var.reset_message() - return RTC.RTC_OK - - def onExecute(self, ec_id): - if not self._msg: - self._msg = self._myservice0_var.get_echo() - if self._msg: - self._msg += "\n" - - if self._InIn.isNew() and self._SeqInIn.isNew() and self._msg: - floatdata = self._InIn.read() - fdata = "%.6f\n" % floatdata.data - print("fdata:", fdata) - self._file.write(fdata) - - seqfloatdata = self._SeqInIn.read() - - t_sdata = tuple(d for d in seqfloatdata.data) - sdata = "%.6f %.6f %.6f %.6f %.6f\n" % t_sdata - - print("sdata: ", sdata) - self._file.write(sdata) - - self._file.write(self._msg) - self._msg = "" - - return RTC.RTC_OK - else: - return RTC.RTC_OK - + def __init__(self, manager): + """ + \brief constructor + \param manager Maneger Object + """ + OpenRTM_aist.DataFlowComponentBase.__init__(self, manager) + self._cnt = 0 + self._flag = 0 + + def onInitialize(self): + self._d_dp_vIn = RTC.TimedFloat(RTC.Time(0, 0), 0) + self._d_dp_vSeqIn = RTC.TimedFloatSeq(RTC.Time(0, 0), []) + + self._InIn = OpenRTM_aist.InPort( + "in", self._d_dp_vIn, OpenRTM_aist.RingBuffer(8)) + self._SeqInIn = OpenRTM_aist.InPort( + "seqin", self._d_dp_vSeqIn, OpenRTM_aist.RingBuffer(8)) + + # Set InPort buffers + self.addInPort("in", self._InIn) + self.addInPort("seqin", self._SeqInIn) + + # Set OutPort buffers + self._MyServicePort = OpenRTM_aist.CorbaPort("MyService") + #self._myservice0_var = MyService_i() + + # initialization of Provider + self._myservice0_var = MyServiceSVC_impl() + + # Set service provider to Ports + self._MyServicePort.registerProvider( + "myservice0", "MyService", self._myservice0_var) + + # Set CORBA Service Ports + self.addPort(self._MyServicePort) + + return RTC.RTC_OK + + def onActivated(self, ec_id): + self._file = open('received-data', 'w') + self._msg = "" + return RTC.RTC_OK + + def onDeactivated(self, ec_id): + self._file.close() + self._myservice0_var.reset_message() + return RTC.RTC_OK + + def onExecute(self, ec_id): + if not self._msg: + self._msg = self._myservice0_var.get_echo() + if self._msg: + self._msg += "\n" + + if self._InIn.isNew() and self._SeqInIn.isNew() and self._msg: + floatdata = self._InIn.read() + fdata = "%.6f\n" % floatdata.data + print("fdata:", fdata) + self._file.write(fdata) + + seqfloatdata = self._SeqInIn.read() + + t_sdata = tuple(d for d in seqfloatdata.data) + sdata = "%.6f %.6f %.6f %.6f %.6f\n" % t_sdata + + print("sdata: ", sdata) + self._file.write(sdata) + + self._file.write(self._msg) + self._msg = "" + + return RTC.RTC_OK + else: + return RTC.RTC_OK def AutoTestInInit(manager): - profile = OpenRTM_aist.Properties(defaults_str=AutoTestIn_spec) - manager.registerFactory(profile, - AutoTestIn, - OpenRTM_aist.Delete) + profile = OpenRTM_aist.Properties(defaults_str=AutoTestIn_spec) + manager.registerFactory(profile, + AutoTestIn, + OpenRTM_aist.Delete) -def MyModuleInit(manager): - AutoTestInInit(manager) - # Create a component - comp = manager.createComponent("AutoTestIn") +def MyModuleInit(manager): + AutoTestInInit(manager) + # Create a component + comp = manager.createComponent("AutoTestIn") def main(): - mgr = OpenRTM_aist.Manager.init(len(sys.argv), sys.argv) - mgr.setModuleInitProc(MyModuleInit) - mgr.activateManager() - mgr.runManager() + mgr = OpenRTM_aist.Manager.init(len(sys.argv), sys.argv) + mgr.setModuleInitProc(MyModuleInit) + mgr.activateManager() + mgr.runManager() -if __name__ == "__main__": - main() +if __name__ == "__main__": + main() diff --git a/OpenRTM_aist/examples/AutoTest/AutoTestOut.py b/OpenRTM_aist/examples/AutoTest/AutoTestOut.py index 9b5ee6de..85cf31a7 100755 --- a/OpenRTM_aist/examples/AutoTest/AutoTestOut.py +++ b/OpenRTM_aist/examples/AutoTest/AutoTestOut.py @@ -1,4 +1,4 @@ -#!/usr/bin/env python +#!/usr/bin/env python # -*- coding: utf-8 -*- # -*- Python -*- @@ -10,14 +10,17 @@ """ from __future__ import print_function +import AutoTest__POA +import AutoTest +from omniORB import CORBA +import OpenRTM_aist +import RTC import sys import string import time sys.path.append(".") # Import RTM module -import RTC -import OpenRTM_aist # Import Service implementation class # @@ -26,8 +29,6 @@ # Import Service stub modules # -import AutoTest, AutoTest__POA -from omniORB import CORBA #import csv @@ -36,117 +37,121 @@ # This module's spesification # -AutoTestOut_spec = ["implementation_id", "AutoTestOut", - "type_name", "AutoTestOut", - "description", "ModuleDescription", - "version", "1.0.0", - "vendor", "HarumiMiyamoto", - "category", "example", - "activity_type", "STATIC", - "max_instance", "1", - "language", "Python", - "lang_type", "SCRIPT", +AutoTestOut_spec = ["implementation_id", "AutoTestOut", + "type_name", "AutoTestOut", + "description", "ModuleDescription", + "version", "1.0.0", + "vendor", "HarumiMiyamoto", + "category", "example", + "activity_type", "STATIC", + "max_instance", "1", + "language", "Python", + "lang_type", "SCRIPT", "exec_cxt.periodic.rate", "1.0", ""] class AutoTestOut(OpenRTM_aist.DataFlowComponentBase): - - """ - \class AutoTestOut - \brief ModuleDescription - """ - def __init__(self, manager): - OpenRTM_aist.DataFlowComponentBase.__init__(self, manager) - return - - def onInitialize(self): - self._d_dp_vOut = RTC.TimedFloat(RTC.Time(0,0),0) - self._d_dp_vSeqOut = RTC.TimedFloatSeq(RTC.Time(0,0),[]) - - self._OutOut = OpenRTM_aist.OutPort("out", self._d_dp_vOut, OpenRTM_aist.RingBuffer(8)) - self._SeqOutOut = OpenRTM_aist.OutPort("seqout", self._d_dp_vSeqOut, OpenRTM_aist.RingBuffer(8)) - - # Set OutPort buffers - self.addOutPort("out", self._OutOut) - self.addOutPort("seqout", self._SeqOutOut) - - self._MyServicePort = OpenRTM_aist.CorbaPort("MyService") - self._myservice0_var = OpenRTM_aist.CorbaConsumer(interfaceType=AutoTest.MyService) - - # Set service consumers to Ports - self._MyServicePort.registerConsumer("myservice0", "MyService", self._myservice0_var) - - # Set CORBA Service Ports - self.addPort(self._MyServicePort) - - return RTC.RTC_OK - - def onActivated(self, ec_id): - try: - self._file=open('original-data') - except: - print("Can not open 'original-data' file.") - return RTC.RTC_ERROR - - return RTC.RTC_OK - - def onDeactivated(self, ec_id): - self._file.close() - return RTC.RTC_OK - - - def onExecute(self, ec_id): - floatSeq=[] - str1 = self._file.readline() - str2 = self._file.readline() - str3 = self._file.readline() - - if str1: - self._d_dp_vOut.data = float(str1) - - if str2: - str2 = str2.split(' ') - floatSeq.append(float(str2[0])) - floatSeq.append(float(str2[1])) - floatSeq.append(float(str2[2])) - floatSeq.append(float(str2[3])) - floatSeq.append(float(str2[4])) - self._d_dp_vSeqOut.data = floatSeq - - if str3: - if self._myservice0_var._ptr(): - # Write out data - self._OutOut.write() - self._SeqOutOut.write() - - # invoking echo operation - retmsg = self._myservice0_var._ptr().echo(str3.rstrip('\r\n')) - - return RTC.RTC_OK - + + """ + \class AutoTestOut + \brief ModuleDescription + """ + + def __init__(self, manager): + OpenRTM_aist.DataFlowComponentBase.__init__(self, manager) + return + + def onInitialize(self): + self._d_dp_vOut = RTC.TimedFloat(RTC.Time(0, 0), 0) + self._d_dp_vSeqOut = RTC.TimedFloatSeq(RTC.Time(0, 0), []) + + self._OutOut = OpenRTM_aist.OutPort( + "out", self._d_dp_vOut, OpenRTM_aist.RingBuffer(8)) + self._SeqOutOut = OpenRTM_aist.OutPort( + "seqout", self._d_dp_vSeqOut, OpenRTM_aist.RingBuffer(8)) + + # Set OutPort buffers + self.addOutPort("out", self._OutOut) + self.addOutPort("seqout", self._SeqOutOut) + + self._MyServicePort = OpenRTM_aist.CorbaPort("MyService") + self._myservice0_var = OpenRTM_aist.CorbaConsumer( + interfaceType=AutoTest.MyService) + + # Set service consumers to Ports + self._MyServicePort.registerConsumer( + "myservice0", "MyService", self._myservice0_var) + + # Set CORBA Service Ports + self.addPort(self._MyServicePort) + + return RTC.RTC_OK + + def onActivated(self, ec_id): + try: + self._file = open('original-data') + except BaseException: + print("Can not open 'original-data' file.") + return RTC.RTC_ERROR + + return RTC.RTC_OK + + def onDeactivated(self, ec_id): + self._file.close() + return RTC.RTC_OK + + def onExecute(self, ec_id): + floatSeq = [] + str1 = self._file.readline() + str2 = self._file.readline() + str3 = self._file.readline() + + if str1: + self._d_dp_vOut.data = float(str1) + + if str2: + str2 = str2.split(' ') + floatSeq.append(float(str2[0])) + floatSeq.append(float(str2[1])) + floatSeq.append(float(str2[2])) + floatSeq.append(float(str2[3])) + floatSeq.append(float(str2[4])) + self._d_dp_vSeqOut.data = floatSeq + + if str3: + if self._myservice0_var._ptr(): + # Write out data + self._OutOut.write() + self._SeqOutOut.write() + + # invoking echo operation + retmsg = self._myservice0_var._ptr().echo(str3.rstrip('\r\n')) + + return RTC.RTC_OK + def AutoTestOutInit(manager): - profile = OpenRTM_aist.Properties(defaults_str=AutoTestOut_spec) - manager.registerFactory(profile, - AutoTestOut, - OpenRTM_aist.Delete) + profile = OpenRTM_aist.Properties(defaults_str=AutoTestOut_spec) + manager.registerFactory(profile, + AutoTestOut, + OpenRTM_aist.Delete) -def MyModuleInit(manager): - AutoTestOutInit(manager) - # Create a component - comp = manager.createComponent("AutoTestOut") +def MyModuleInit(manager): + AutoTestOutInit(manager) + # Create a component + comp = manager.createComponent("AutoTestOut") def main(): - mgr = OpenRTM_aist.Manager.init(len(sys.argv), sys.argv) - mgr.setModuleInitProc(MyModuleInit) - mgr.activateManager() - mgr.runManager() + mgr = OpenRTM_aist.Manager.init(len(sys.argv), sys.argv) + mgr.setModuleInitProc(MyModuleInit) + mgr.activateManager() + mgr.runManager() + if __name__ == "__main__": - - main() + main() diff --git a/OpenRTM_aist/examples/AutoTest/ConnectTest.py b/OpenRTM_aist/examples/AutoTest/ConnectTest.py index 46192361..a600c2b1 100644 --- a/OpenRTM_aist/examples/AutoTest/ConnectTest.py +++ b/OpenRTM_aist/examples/AutoTest/ConnectTest.py @@ -1,4770 +1,4985 @@ -#!/usr/bin/env python +#!/usr/bin/env python # -*- coding: utf-8 -*- # -*- Python -*- # -## ConnectTest.py +# ConnectTest.py ## -## コンポーネント接続テスト +# コンポーネント接続テスト ## from __future__ import print_function from rtc_handle import * from BasicDataType_idl import * import time -import commands import SDOPackage import os -##-------------------------------------------------------------------- -g_test_name = "<< component connection test >>" - -## ネームサーバー定義 -#env = RtmEnv(sys.argv, ["localhost:2809"]) -#list0 = env.name_space["localhost:2809"].list_obj() -#env.name_space['localhost:2809'].rtc_handles.keys() -#ns = env.name_space['localhost:2809'] -env = RtmEnv(sys.argv, ["localhost:2809"]) -list0 = env.name_space["localhost:2809"].list_obj() -env.name_space['localhost:2809'].rtc_handles.keys() -ns = env.name_space['localhost:2809'] - -g_compo_send = ns.rtc_handles["AutoTestOut0.rtc"] -g_compo_recv = ns.rtc_handles["AutoTestIn0.rtc"] - -ec_send = g_compo_send.rtc_ref.get_owned_contexts() -ec_recv = g_compo_recv.rtc_ref.get_owned_contexts() - -g_out_ports = g_compo_send.rtc_ref.get_ports() -g_in_ports = g_compo_recv.rtc_ref.get_ports() -#print "<<< g_out_ports.length=",len(g_out_ports) -#SeqOutの場合 -#length=8 [0]:Short [1]:Long [2]:Float [3]:Double [4]:ShortSeq [5]:LongSeq [6]:FloatSeq [7]:DoubleSeq -#print "<<< g_in_ports.length=",len(g_in_ports) - -time.sleep(2) - -##-------------------------------------------------------------------- -## コネクタープロファイルデフォルト定義 -g_interface_type1 = "corba_cdr" -g_dataflow_type = "push" -g_subscription_type = "flush" -g_push_policy = "NEW" -g_push_rate = "2000" -g_skip_count = "4" -#g_skip_count = "0" - -## ポート番号指定 ( get_ports()より ) -g_port1 = 0 -g_port2 = 1 -g_port3 = 2 - -## ConnectorProfile(name, connector_id, ports, properties) -## String name -## String connector_id -## RTC.PortService ports[] -## SDOPackage.NameValue properties[] - -## データポート TimedFloat -g_name1 = "out" -g_connector_id1 = "001" -g_data_type1 = "TimedFloat" - -g_conprof1 = RTC.ConnectorProfile(g_name1, g_connector_id1, [g_out_ports[g_port1], g_in_ports[g_port1]], [SDOPackage.NameValue("dataport.data_type",any.to_any(g_data_type1)),SDOPackage.NameValue("dataport.interface_type",any.to_any(g_interface_type1)),SDOPackage.NameValue("dataport.dataflow_type",any.to_any(g_dataflow_type)),SDOPackage.NameValue("dataport.subscription_type",any.to_any(g_subscription_type)),SDOPackage.NameValue("dataport.publisher.push_policy",any.to_any(g_push_policy)),SDOPackage.NameValue("dataport.publisher.push_rate",any.to_any(g_push_rate)),SDOPackage.NameValue("dataport.publisher.skip_count",any.to_any(g_skip_count))]) - -## データポート TimedFloatSeq -g_name2 = "seqout" -g_connector_id2 = "002" -g_data_type2 = "TimedFloatSeq" - -g_conprof2 = RTC.ConnectorProfile(g_name2, g_connector_id2, [g_out_ports[g_port2], g_in_ports[g_port2]], [SDOPackage.NameValue("dataport.data_type",any.to_any(g_data_type2)),SDOPackage.NameValue("dataport.interface_type",any.to_any(g_interface_type1)),SDOPackage.NameValue("dataport.dataflow_type",any.to_any(g_dataflow_type)),SDOPackage.NameValue("dataport.subscription_type",any.to_any(g_subscription_type)),SDOPackage.NameValue("dataport.publisher.push_policy",any.to_any(g_push_policy)),SDOPackage.NameValue("dataport.publisher.push_rate",any.to_any(g_push_rate)),SDOPackage.NameValue("dataport.publisher.skip_count",any.to_any(g_skip_count))]) - -## サービスポート -g_name3 = "MyService" -g_connector_id3 = "003" -g_interface_type3 = "MyService" - -g_conprof3 = RTC.ConnectorProfile(g_name3, g_connector_id3, [g_out_ports[g_port3], g_in_ports[g_port3]], [SDOPackage.NameValue("dataport.interface_type",any.to_any(g_interface_type3))]) - -##-------------------------------------------------------------------- -## 送受信結果判定関連 -g_diff_send_file = "./original-data" -g_diff_recv_file = "./received-data" -g_check_message = g_diff_recv_file + " file not found." -g_test_result_file = "./ResultTest.log" -g_test_case = "case" -g_test_cnt = "count" -g_test_ok = "OK." -g_test_ng = "NG detected." -g_test_ng_message = " < received-data >" -g_mess_header = "< " -g_mess_footer = " > " -# テスト結果内容 -# 例)ケース1、1回目 -> "<<< case1 count1 >>> OK." -# 例)ケース1、2回目 -> "<<< case1 count2 >>> NG detected." - -##-------------------------------------------------------------------- -## 内部関数:コネクタープロファイル設定(データポート) -## -## (引数) -## subscription_type : "flush", "new", "periodic" -## push_policy : "ALL", "FIFO", "SKIP", "NEW", "" -## connect_direction : 0:outport -> inport, 1:inport -> outport -##-------------------------------------------------------------------- -def make_connecter_profile(subscription_type, push_policy, connect_direction): - global g_conprof1, g_conprof2, g_conprof3 - - if connect_direction == 0: - ## outport -> inport Set - g_conprof1 = RTC.ConnectorProfile(g_name1, g_connector_id1, [g_out_ports[g_port1], g_in_ports[g_port1]], [SDOPackage.NameValue("dataport.data_type",any.to_any(g_data_type1)),SDOPackage.NameValue("dataport.interface_type",any.to_any(g_interface_type1)),SDOPackage.NameValue("dataport.dataflow_type",any.to_any(g_dataflow_type)),SDOPackage.NameValue("dataport.subscription_type",any.to_any(subscription_type)),SDOPackage.NameValue("dataport.publisher.push_policy",any.to_any(push_policy)),SDOPackage.NameValue("dataport.publisher.push_rate",any.to_any(g_push_rate)),SDOPackage.NameValue("dataport.publisher.skip_count",any.to_any(g_skip_count))]) +# -------------------------------------------------------------------- + + +def main(): + g_test_name = "<< component connection test >>" + + # ネームサーバー定義 + #env = RtmEnv(sys.argv, ["localhost:2809"]) + #list0 = env.name_space["localhost:2809"].list_obj() + # env.name_space['localhost:2809'].rtc_handles.keys() + #ns = env.name_space['localhost:2809'] + env = RtmEnv(sys.argv, ["localhost:2809"]) + list0 = env.name_space["localhost:2809"].list_obj() + env.name_space['localhost:2809'].rtc_handles.keys() + ns = env.name_space['localhost:2809'] + + g_compo_send = ns.rtc_handles["AutoTestOut0.rtc"] + g_compo_recv = ns.rtc_handles["AutoTestIn0.rtc"] + + ec_send = g_compo_send.rtc_ref.get_owned_contexts() + ec_recv = g_compo_recv.rtc_ref.get_owned_contexts() + + g_out_ports = g_compo_send.rtc_ref.get_ports() + g_in_ports = g_compo_recv.rtc_ref.get_ports() + # print "<<< g_out_ports.length=",len(g_out_ports) + # SeqOutの場合 + # length=8 [0]:Short [1]:Long [2]:Float [3]:Double [4]:ShortSeq [5]:LongSeq [6]:FloatSeq [7]:DoubleSeq + # print "<<< g_in_ports.length=",len(g_in_ports) + + time.sleep(2) + + # -------------------------------------------------------------------- + # コネクタープロファイルデフォルト定義 + g_interface_type1 = "corba_cdr" + g_dataflow_type = "push" + g_subscription_type = "flush" + g_push_policy = "NEW" + g_push_rate = "2000" + g_skip_count = "4" + #g_skip_count = "0" + + # ポート番号指定 ( get_ports()より ) + g_port1 = 0 + g_port2 = 1 + g_port3 = 2 + + ## ConnectorProfile(name, connector_id, ports, properties) + # String name + # String connector_id + # RTC.PortService ports[] + # SDOPackage.NameValue properties[] + + # データポート TimedFloat + g_name1 = "out" + g_connector_id1 = "001" + g_data_type1 = "TimedFloat" + + g_conprof1 = RTC.ConnectorProfile( + g_name1, g_connector_id1, [ + g_out_ports[g_port1], g_in_ports[g_port1]], [ + SDOPackage.NameValue( + "dataport.data_type", any.to_any(g_data_type1)), SDOPackage.NameValue( + "dataport.interface_type", any.to_any(g_interface_type1)), SDOPackage.NameValue( + "dataport.dataflow_type", any.to_any(g_dataflow_type)), SDOPackage.NameValue( + "dataport.subscription_type", any.to_any(g_subscription_type)), SDOPackage.NameValue( + "dataport.publisher.push_policy", any.to_any(g_push_policy)), SDOPackage.NameValue( + "dataport.publisher.push_rate", any.to_any(g_push_rate)), SDOPackage.NameValue( + "dataport.publisher.skip_count", any.to_any(g_skip_count))]) + + # データポート TimedFloatSeq + g_name2 = "seqout" + g_connector_id2 = "002" + g_data_type2 = "TimedFloatSeq" + + g_conprof2 = RTC.ConnectorProfile( + g_name2, g_connector_id2, [ + g_out_ports[g_port2], g_in_ports[g_port2]], [ + SDOPackage.NameValue( + "dataport.data_type", any.to_any(g_data_type2)), SDOPackage.NameValue( + "dataport.interface_type", any.to_any(g_interface_type1)), SDOPackage.NameValue( + "dataport.dataflow_type", any.to_any(g_dataflow_type)), SDOPackage.NameValue( + "dataport.subscription_type", any.to_any(g_subscription_type)), SDOPackage.NameValue( + "dataport.publisher.push_policy", any.to_any(g_push_policy)), SDOPackage.NameValue( + "dataport.publisher.push_rate", any.to_any(g_push_rate)), SDOPackage.NameValue( + "dataport.publisher.skip_count", any.to_any(g_skip_count))]) + + # サービスポート + g_name3 = "MyService" + g_connector_id3 = "003" + g_interface_type3 = "MyService" + + g_conprof3 = RTC.ConnectorProfile( + g_name3, g_connector_id3, [ + g_out_ports[g_port3], g_in_ports[g_port3]], [ + SDOPackage.NameValue( + "dataport.interface_type", any.to_any(g_interface_type3))]) + + # -------------------------------------------------------------------- + # 送受信結果判定関連 + g_diff_send_file = "./original-data" + g_diff_recv_file = "./received-data" + g_check_message = g_diff_recv_file + " file not found." + g_test_result_file = "./ResultTest.log" + g_test_case = "case" + g_test_cnt = "count" + g_test_ok = "OK." + g_test_ng = "NG detected." + g_test_ng_message = " < received-data >" + g_mess_header = "< " + g_mess_footer = " > " + # テスト結果内容 + # 例)ケース1、1回目 -> "<<< case1 count1 >>> OK." + # 例)ケース1、2回目 -> "<<< case1 count2 >>> NG detected." + + # -------------------------------------------------------------------- + # 内部関数:コネクタープロファイル設定(データポート) + ## + # (引数) + # subscription_type : "flush", "new", "periodic" + # push_policy : "ALL", "FIFO", "SKIP", "NEW", "" + # connect_direction : 0:outport -> inport, 1:inport -> outport + # -------------------------------------------------------------------- + def make_connecter_profile( + subscription_type, push_policy, connect_direction): + global g_conprof1, g_conprof2, g_conprof3 + + if connect_direction == 0: + # outport -> inport Set + g_conprof1 = RTC.ConnectorProfile( + g_name1, g_connector_id1, [ + g_out_ports[g_port1], g_in_ports[g_port1]], [ + SDOPackage.NameValue( + "dataport.data_type", any.to_any(g_data_type1)), SDOPackage.NameValue( + "dataport.interface_type", any.to_any(g_interface_type1)), SDOPackage.NameValue( + "dataport.dataflow_type", any.to_any(g_dataflow_type)), SDOPackage.NameValue( + "dataport.subscription_type", any.to_any(subscription_type)), SDOPackage.NameValue( + "dataport.publisher.push_policy", any.to_any(push_policy)), SDOPackage.NameValue( + "dataport.publisher.push_rate", any.to_any(g_push_rate)), SDOPackage.NameValue( + "dataport.publisher.skip_count", any.to_any(g_skip_count))]) + + g_conprof2 = RTC.ConnectorProfile( + g_name2, g_connector_id2, [ + g_out_ports[g_port2], g_in_ports[g_port2]], [ + SDOPackage.NameValue( + "dataport.data_type", any.to_any(g_data_type2)), SDOPackage.NameValue( + "dataport.interface_type", any.to_any(g_interface_type1)), SDOPackage.NameValue( + "dataport.dataflow_type", any.to_any(g_dataflow_type)), SDOPackage.NameValue( + "dataport.subscription_type", any.to_any(subscription_type)), SDOPackage.NameValue( + "dataport.publisher.push_policy", any.to_any(push_policy)), SDOPackage.NameValue( + "dataport.publisher.push_rate", any.to_any(g_push_rate)), SDOPackage.NameValue( + "dataport.publisher.skip_count", any.to_any(g_skip_count))]) + + # print "outport -> inport set >>>" + # print "g_conprof1=",g_conprof1 + # print "g_conprof2=",g_conprof2 + else: + # inport -> outport Set + g_conprof1 = RTC.ConnectorProfile( + g_name1, g_connector_id1, [ + g_in_ports[g_port1], g_out_ports[g_port1]], [ + SDOPackage.NameValue( + "dataport.data_type", any.to_any(g_data_type1)), SDOPackage.NameValue( + "dataport.interface_type", any.to_any(g_interface_type1)), SDOPackage.NameValue( + "dataport.dataflow_type", any.to_any(g_dataflow_type)), SDOPackage.NameValue( + "dataport.subscription_type", any.to_any(subscription_type)), SDOPackage.NameValue( + "dataport.publisher.push_policy", any.to_any(push_policy)), SDOPackage.NameValue( + "dataport.publisher.push_rate", any.to_any(g_push_rate)), SDOPackage.NameValue( + "dataport.publisher.skip_count", any.to_any(g_skip_count))]) + + g_conprof2 = RTC.ConnectorProfile( + g_name2, g_connector_id2, [ + g_in_ports[g_port2], g_out_ports[g_port2]], [ + SDOPackage.NameValue( + "dataport.data_type", any.to_any(g_data_type2)), SDOPackage.NameValue( + "dataport.interface_type", any.to_any(g_interface_type1)), SDOPackage.NameValue( + "dataport.dataflow_type", any.to_any(g_dataflow_type)), SDOPackage.NameValue( + "dataport.subscription_type", any.to_any(subscription_type)), SDOPackage.NameValue( + "dataport.publisher.push_policy", any.to_any(push_policy)), SDOPackage.NameValue( + "dataport.publisher.push_rate", any.to_any(g_push_rate)), SDOPackage.NameValue( + "dataport.publisher.skip_count", any.to_any(g_skip_count))]) + + # print "inport -> outport set >>>" + # print "g_conprof1=",g_conprof1 + # print "g_conprof2=",g_conprof2 + return + + # -------------------------------------------------------------------- + # 内部関数:受信ファイル削除 + ## + # (引数) + # なし + # -------------------------------------------------------------------- + + def delete_recv_file(): + # ファイルが存在する場合 + if os.path.isfile(g_diff_recv_file) == True: + os.remove(g_diff_recv_file) + return + + # -------------------------------------------------------------------- + # 内部関数:送受信ファイルのデータ比較 + ## + # (引数) + # なし + # (戻り値) True : 一致、 False : 不一致 + # -------------------------------------------------------------------- + + def diff_file(): + bret = True + + # if connect_direction == 0: + # else: + # 送信ファイル有無判定 + if os.path.isfile(g_diff_send_file) == False: + print("send_file (%s) not found." % send_file) + return False + + # 受信ファイル有無判定 + if os.path.isfile(g_diff_recv_file) == False: + print("recv_file (%s) not found." % recv_file) + return False + + # 送受信データ差分判定 + f_send = open(g_diff_send_file, 'r') + f_recv = open(g_diff_recv_file, 'r') - g_conprof2 = RTC.ConnectorProfile(g_name2, g_connector_id2, [g_out_ports[g_port2], g_in_ports[g_port2]], [SDOPackage.NameValue("dataport.data_type",any.to_any(g_data_type2)),SDOPackage.NameValue("dataport.interface_type",any.to_any(g_interface_type1)),SDOPackage.NameValue("dataport.dataflow_type",any.to_any(g_dataflow_type)),SDOPackage.NameValue("dataport.subscription_type",any.to_any(subscription_type)),SDOPackage.NameValue("dataport.publisher.push_policy",any.to_any(push_policy)),SDOPackage.NameValue("dataport.publisher.push_rate",any.to_any(g_push_rate)),SDOPackage.NameValue("dataport.publisher.skip_count",any.to_any(g_skip_count))]) + while(1): + str_send = f_send.readline() + str_recv = f_recv.readline() + if len(str_send) == 0: + break - #print "outport -> inport set >>>" - #print "g_conprof1=",g_conprof1 - #print "g_conprof2=",g_conprof2 - else: - ## inport -> outport Set - g_conprof1 = RTC.ConnectorProfile(g_name1, g_connector_id1, [g_in_ports[g_port1], g_out_ports[g_port1]], [SDOPackage.NameValue("dataport.data_type",any.to_any(g_data_type1)),SDOPackage.NameValue("dataport.interface_type",any.to_any(g_interface_type1)),SDOPackage.NameValue("dataport.dataflow_type",any.to_any(g_dataflow_type)),SDOPackage.NameValue("dataport.subscription_type",any.to_any(subscription_type)),SDOPackage.NameValue("dataport.publisher.push_policy",any.to_any(push_policy)),SDOPackage.NameValue("dataport.publisher.push_rate",any.to_any(g_push_rate)),SDOPackage.NameValue("dataport.publisher.skip_count",any.to_any(g_skip_count))]) + # print "original send date=(%s)" % str_send + # print ''.join(['%x ' % ord(s) for s in str_send]) + # print "original recv date=(%s)" % str_recv + # print ''.join(['%x ' % ord(s) for s in str_recv]) + + # 末尾の改行、復帰コード削除 + str_send2 = str_send.rstrip('\n') + str_send2 = str_send2.rstrip('\r') + str_recv2 = str_recv.rstrip('\n') + str_recv2 = str_recv2.rstrip('\r') + + # print "rstrip after send date=(%s)" % str_send2 + # print "rstrip after recv date=(%s)" % str_recv2 + + # データ比較 + if str_send2 != str_recv2: + # print "data difference" + # print "send date=(%s)" % str_send2 + # print "recv date=(%s)" % str_recv2 + bret = False + break - g_conprof2 = RTC.ConnectorProfile(g_name2, g_connector_id2, [g_in_ports[g_port2], g_out_ports[g_port2]], [SDOPackage.NameValue("dataport.data_type",any.to_any(g_data_type2)),SDOPackage.NameValue("dataport.interface_type",any.to_any(g_interface_type1)),SDOPackage.NameValue("dataport.dataflow_type",any.to_any(g_dataflow_type)),SDOPackage.NameValue("dataport.subscription_type",any.to_any(subscription_type)),SDOPackage.NameValue("dataport.publisher.push_policy",any.to_any(push_policy)),SDOPackage.NameValue("dataport.publisher.push_rate",any.to_any(g_push_rate)),SDOPackage.NameValue("dataport.publisher.skip_count",any.to_any(g_skip_count))]) + f_recv.close() + f_send.close() + return bret - #print "inport -> outport set >>>" - #print "g_conprof1=",g_conprof1 - #print "g_conprof2=",g_conprof2 - return + # -------------------------------------------------------------------- + # テストケース番号の初期値設定 + # 上から連番を振っている + case_no = 0 + # ケース毎のテスト回数 + loop_count = 3 -##-------------------------------------------------------------------- -## 内部関数:受信ファイル削除 -## -## (引数) -## なし -##-------------------------------------------------------------------- -def delete_recv_file(): - ## ファイルが存在する場合 - if os.path.isfile(g_diff_recv_file) == True: - os.remove(g_diff_recv_file) - return - - -##-------------------------------------------------------------------- -## 内部関数:送受信ファイルのデータ比較 -## -## (引数) -## なし -## (戻り値) True : 一致、 False : 不一致 -##-------------------------------------------------------------------- -def diff_file(): - bret = True - - ## if connect_direction == 0: - ## else: - ## 送信ファイル有無判定 - if os.path.isfile(g_diff_send_file) == False: - print("send_file (%s) not found." % send_file) - return False - - ## 受信ファイル有無判定 - if os.path.isfile(g_diff_recv_file) == False: - print("recv_file (%s) not found." % recv_file) - return False - - ## 送受信データ差分判定 - f_send = open(g_diff_send_file, 'r') - f_recv = open(g_diff_recv_file, 'r') - - while(1): - str_send = f_send.readline() - str_recv = f_recv.readline() - if len(str_send) == 0: - break - - #print "original send date=(%s)" % str_send - #print ''.join(['%x ' % ord(s) for s in str_send]) - #print "original recv date=(%s)" % str_recv - #print ''.join(['%x ' % ord(s) for s in str_recv]) - - ## 末尾の改行、復帰コード削除 - str_send2 = str_send.rstrip('\n') - str_send2 = str_send2.rstrip('\r') - str_recv2 = str_recv.rstrip('\n') - str_recv2 = str_recv2.rstrip('\r') - - #print "rstrip after send date=(%s)" % str_send2 - #print "rstrip after recv date=(%s)" % str_recv2 - - ## データ比較 - if str_send2 != str_recv2: - #print "data difference" - #print "send date=(%s)" % str_send2 - #print "recv date=(%s)" % str_recv2 - bret = False - break; - - f_recv.close() - f_send.close() - return bret - -##-------------------------------------------------------------------- -## テストケース番号の初期値設定 -## 上から連番を振っている -case_no = 0 - -## ケース毎のテスト回数 -loop_count = 3 - -## 受信側activate_componentから送信側activate_componentまでのスリープ時間(秒数) -sleep_recv_act_time = 1 - -## activate_componentからdeactivate_componentまでのスリープ時間(秒数) -sleep_act_time = 10 - -## forループのスリープ時間(秒数) -sleep_for_time = 2 - -## connectからdisconnectまでのスリープ時間(秒数) -sleep_connect_time = 2 - -# テスト結果ファイルの作成 -fout = open(g_test_result_file, 'w') -fout.write(g_test_name + '\n') -fout.close() -#print g_test_name - -time.sleep(1) - -##-------------------------------------------------------------------- -## 接続タイプ:flush 方向:out->in 接続・切断テスト2 -##-------------------------------------------------------------------- -case_no = case_no + 1 -fout = open(g_test_result_file, 'a') -message = g_mess_header + g_test_case + str(case_no) + " " -message = message + "Connect(out->in, flush) -> Disconnect" -message = message + g_mess_footer -fout.write(message + '\n') -fout.close() -print(message) - -for i in range(loop_count): - - ## 1 コネクタープロファイル設定 - make_connecter_profile("flush", "", 0) + # 受信側activate_componentから送信側activate_componentまでのスリープ時間(秒数) + sleep_recv_act_time = 1 - ## 3 ポート接続 - # データポート1 TimedFloat - ret0 = g_out_ports[g_port1].connect(g_conprof1) + # activate_componentからdeactivate_componentまでのスリープ時間(秒数) + sleep_act_time = 10 - # データポート2 TimedFloatSeq - ret1 = g_out_ports[g_port2].connect(g_conprof2) + # forループのスリープ時間(秒数) + sleep_for_time = 2 - # サービスポート MyService - ret2 = g_out_ports[g_port3].connect(g_conprof3) + # connectからdisconnectまでのスリープ時間(秒数) + sleep_connect_time = 2 - time.sleep(sleep_connect_time) + # テスト結果ファイルの作成 + fout = open(g_test_result_file, 'w') + fout.write(g_test_name + '\n') + fout.close() + # print g_test_name - ## 6 ポート切断 - g_in_ports[g_port3].disconnect(g_conprof3.connector_id) - g_in_ports[g_port2].disconnect(g_conprof2.connector_id) - g_in_ports[g_port1].disconnect(g_conprof1.connector_id) + time.sleep(1) - ## テスト結果出力 + # -------------------------------------------------------------------- + # 接続タイプ:flush 方向:out->in 接続・切断テスト2 + # -------------------------------------------------------------------- + case_no = case_no + 1 fout = open(g_test_result_file, 'a') - message = g_mess_header + g_test_case + str(case_no) + " " + g_test_cnt + str(i+1) + g_mess_footer - message = message + g_test_ok - print(message) + message = g_mess_header + g_test_case + str(case_no) + " " + message = message + "Connect(out->in, flush) -> Disconnect" + message = message + g_mess_footer fout.write(message + '\n') fout.close() + print(message) - time.sleep(sleep_for_time) + for i in range(loop_count): -##-------------------------------------------------------------------- -## 接続タイプ:flush 方向:in->out 接続・切断テスト1 -##-------------------------------------------------------------------- -case_no = case_no + 1 -fout = open(g_test_result_file, 'a') -message = g_mess_header + g_test_case + str(case_no) + " " -message = message + "Connect(in->out, flush) -> Disconnect" -message = message + g_mess_footer -fout.write(message + '\n') -fout.close() -print(message) + # 1 コネクタープロファイル設定 + make_connecter_profile("flush", "", 0) -for i in range(loop_count): + # 3 ポート接続 + # データポート1 TimedFloat + ret0 = g_out_ports[g_port1].connect(g_conprof1) - ## 1 コネクタープロファイル設定 - make_connecter_profile("flush", "", 1) + # データポート2 TimedFloatSeq + ret1 = g_out_ports[g_port2].connect(g_conprof2) - ## 3 ポート接続 - # データポート1 TimedFloat - ret0 = g_out_ports[g_port1].connect(g_conprof1) + # サービスポート MyService + ret2 = g_out_ports[g_port3].connect(g_conprof3) - # データポート2 TimedFloatSeq - ret1 = g_out_ports[g_port2].connect(g_conprof2) + time.sleep(sleep_connect_time) - # サービスポート MyService - ret2 = g_out_ports[g_port3].connect(g_conprof3) + # 6 ポート切断 + g_in_ports[g_port3].disconnect(g_conprof3.connector_id) + g_in_ports[g_port2].disconnect(g_conprof2.connector_id) + g_in_ports[g_port1].disconnect(g_conprof1.connector_id) - time.sleep(sleep_connect_time) + # テスト結果出力 + fout = open(g_test_result_file, 'a') + message = g_mess_header + g_test_case + \ + str(case_no) + " " + g_test_cnt + str(i + 1) + g_mess_footer + message = message + g_test_ok + print(message) + fout.write(message + '\n') + fout.close() - ## 6 ポート切断 - g_in_ports[g_port3].disconnect(g_conprof3.connector_id) - g_in_ports[g_port2].disconnect(g_conprof2.connector_id) - g_in_ports[g_port1].disconnect(g_conprof1.connector_id) + time.sleep(sleep_for_time) - ## テスト結果出力 + # -------------------------------------------------------------------- + # 接続タイプ:flush 方向:in->out 接続・切断テスト1 + # -------------------------------------------------------------------- + case_no = case_no + 1 fout = open(g_test_result_file, 'a') - message = g_mess_header + g_test_case + str(case_no) + " " + g_test_cnt + str(i+1) + g_mess_footer - message = message + g_test_ok - print(message) + message = g_mess_header + g_test_case + str(case_no) + " " + message = message + "Connect(in->out, flush) -> Disconnect" + message = message + g_mess_footer fout.write(message + '\n') fout.close() + print(message) - time.sleep(sleep_for_time) - -##-------------------------------------------------------------------- -## 接続タイプ:flush 方向:out->in Activate・Deactivateテスト1 -##-------------------------------------------------------------------- -case_no = case_no + 1 -fout = open(g_test_result_file, 'a') -message = g_mess_header + g_test_case + str(case_no) + " " -message = message + "Connecting(out->in, flush), Activate -> send/recv -> Deactivate" -message = message + g_mess_footer -fout.write(message + '\n') -fout.close() -print(message) - -## 1 コネクタープロファイル設定 -make_connecter_profile("flush", "", 0) - -## 3 ポート接続 -# データポート1 TimedFloat -ret0 = g_out_ports[g_port1].connect(g_conprof1) - -# データポート2 TimedFloatSeq -ret1 = g_out_ports[g_port2].connect(g_conprof2) + for i in range(loop_count): -# サービスポート MyService -ret2 = g_out_ports[g_port3].connect(g_conprof3) + # 1 コネクタープロファイル設定 + make_connecter_profile("flush", "", 1) -for i in range(loop_count): + # 3 ポート接続 + # データポート1 TimedFloat + ret0 = g_out_ports[g_port1].connect(g_conprof1) - ## 2 受信データファイル削除 - delete_recv_file() + # データポート2 TimedFloatSeq + ret1 = g_out_ports[g_port2].connect(g_conprof2) - ## 4 アクティベート - ec_recv[0].activate_component(g_compo_recv.rtc_ref) - time.sleep(sleep_recv_act_time) - ec_send[0].activate_component(g_compo_send.rtc_ref) + # サービスポート MyService + ret2 = g_out_ports[g_port3].connect(g_conprof3) - time.sleep(sleep_act_time) + time.sleep(sleep_connect_time) - ## 5 ディアクティベート - ec_send[0].deactivate_component(g_compo_send.rtc_ref) - ec_recv[0].deactivate_component(g_compo_recv.rtc_ref) + # 6 ポート切断 + g_in_ports[g_port3].disconnect(g_conprof3.connector_id) + g_in_ports[g_port2].disconnect(g_conprof2.connector_id) + g_in_ports[g_port1].disconnect(g_conprof1.connector_id) - ## 受信ファイル有無判定 - if os.path.isfile(g_diff_recv_file) == False: + # テスト結果出力 fout = open(g_test_result_file, 'a') - message = g_mess_header + g_test_case + str(case_no) + " " + g_test_cnt + str(i+1) + g_mess_footer - message = message + g_check_message + message = g_mess_header + g_test_case + \ + str(case_no) + " " + g_test_cnt + str(i + 1) + g_mess_footer + message = message + g_test_ok + print(message) fout.write(message + '\n') fout.close() - print(message) - time.sleep(sleep_for_time) - continue - ## 7 送受信データ比較 - time.sleep(sleep_act_time) - bret = diff_file() + time.sleep(sleep_for_time) - ## 差分ファイルからテスト結果出力 + # -------------------------------------------------------------------- + # 接続タイプ:flush 方向:out->in Activate・Deactivateテスト1 + # -------------------------------------------------------------------- + case_no = case_no + 1 fout = open(g_test_result_file, 'a') - message = g_mess_header + g_test_case + str(case_no) + " " + g_test_cnt + str(i+1) + g_mess_footer - # bret==True なら送受信データ一致 - if bret == True: - # テスト結果 OK - message = message + g_test_ok - print(message) - fout.write(message + '\n') - else: - # テスト結果 NG - message = message + g_test_ng - print(message) - message = message + g_test_ng_message - fout.write(message + '\n') - # 受信データをテスト結果ファイルへコピー - fin2 = open(g_diff_recv_file, 'r') - while(1): - s2 = fin2.readline() - if len(s2) == 0: - break - fout.write(s2) - fin2.close() + message = g_mess_header + g_test_case + str(case_no) + " " + message = message + \ + "Connecting(out->in, flush), Activate -> send/recv -> Deactivate" + message = message + g_mess_footer + fout.write(message + '\n') fout.close() + print(message) - time.sleep(sleep_for_time) - -## 6 ポート切断 -g_in_ports[g_port3].disconnect(g_conprof3.connector_id) -g_in_ports[g_port2].disconnect(g_conprof2.connector_id) -g_in_ports[g_port1].disconnect(g_conprof1.connector_id) + # 1 コネクタープロファイル設定 + make_connecter_profile("flush", "", 0) -##-------------------------------------------------------------------- -## 接続タイプ:flush 方向:in->out Activate・Deactivateテスト1 -##-------------------------------------------------------------------- -case_no = case_no + 1 -fout = open(g_test_result_file, 'a') -message = g_mess_header + g_test_case + str(case_no) + " " -message = message + "Connecting(in->out, flush), Activate -> send/recv -> Deactivate" -message = message + g_mess_footer -fout.write(message + '\n') -fout.close() -print(message) + # 3 ポート接続 + # データポート1 TimedFloat + ret0 = g_out_ports[g_port1].connect(g_conprof1) -## 1 コネクタープロファイル設定 -make_connecter_profile("flush", "", 1) + # データポート2 TimedFloatSeq + ret1 = g_out_ports[g_port2].connect(g_conprof2) -## 3 ポート接続 -# データポート1 TimedFloat -ret0 = g_out_ports[g_port1].connect(g_conprof1) + # サービスポート MyService + ret2 = g_out_ports[g_port3].connect(g_conprof3) -# データポート2 TimedFloatSeq -ret1 = g_out_ports[g_port2].connect(g_conprof2) + for i in range(loop_count): -# サービスポート MyService -ret2 = g_out_ports[g_port3].connect(g_conprof3) + # 2 受信データファイル削除 + delete_recv_file() -for i in range(loop_count): + # 4 アクティベート + ec_recv[0].activate_component(g_compo_recv.rtc_ref) + time.sleep(sleep_recv_act_time) + ec_send[0].activate_component(g_compo_send.rtc_ref) - ## 2 受信データファイル削除 - delete_recv_file() + time.sleep(sleep_act_time) - ## 4 アクティベート - ec_recv[0].activate_component(g_compo_recv.rtc_ref) - time.sleep(sleep_recv_act_time) - ec_send[0].activate_component(g_compo_send.rtc_ref) + # 5 ディアクティベート + ec_send[0].deactivate_component(g_compo_send.rtc_ref) + ec_recv[0].deactivate_component(g_compo_recv.rtc_ref) - time.sleep(sleep_act_time) + # 受信ファイル有無判定 + if os.path.isfile(g_diff_recv_file) == False: + fout = open(g_test_result_file, 'a') + message = g_mess_header + g_test_case + \ + str(case_no) + " " + g_test_cnt + str(i + 1) + g_mess_footer + message = message + g_check_message + fout.write(message + '\n') + fout.close() + print(message) + time.sleep(sleep_for_time) + continue - ## 5 ディアクティベート - ec_send[0].deactivate_component(g_compo_send.rtc_ref) - ec_recv[0].deactivate_component(g_compo_recv.rtc_ref) + # 7 送受信データ比較 + time.sleep(sleep_act_time) + bret = diff_file() - ## 受信ファイル有無判定 - if os.path.isfile(g_diff_recv_file) == False: + # 差分ファイルからテスト結果出力 fout = open(g_test_result_file, 'a') - message = g_mess_header + g_test_case + str(case_no) + " " + g_test_cnt + str(i+1) + g_mess_footer - message = message + g_check_message - fout.write(message + '\n') + message = g_mess_header + g_test_case + \ + str(case_no) + " " + g_test_cnt + str(i + 1) + g_mess_footer + # bret==True なら送受信データ一致 + if bret == True: + # テスト結果 OK + message = message + g_test_ok + print(message) + fout.write(message + '\n') + else: + # テスト結果 NG + message = message + g_test_ng + print(message) + message = message + g_test_ng_message + fout.write(message + '\n') + # 受信データをテスト結果ファイルへコピー + fin2 = open(g_diff_recv_file, 'r') + while(1): + s2 = fin2.readline() + if len(s2) == 0: + break + fout.write(s2) + fin2.close() fout.close() - print(message) + time.sleep(sleep_for_time) - continue - ## 7 送受信データ比較 - time.sleep(sleep_act_time) - bret = diff_file() + # 6 ポート切断 + g_in_ports[g_port3].disconnect(g_conprof3.connector_id) + g_in_ports[g_port2].disconnect(g_conprof2.connector_id) + g_in_ports[g_port1].disconnect(g_conprof1.connector_id) - ## 差分ファイルからテスト結果出力 + # -------------------------------------------------------------------- + # 接続タイプ:flush 方向:in->out Activate・Deactivateテスト1 + # -------------------------------------------------------------------- + case_no = case_no + 1 fout = open(g_test_result_file, 'a') - message = g_mess_header + g_test_case + str(case_no) + " " + g_test_cnt + str(i+1) + g_mess_footer - # bret==True なら送受信データ一致 - if bret == True: - # テスト結果 OK - message = message + g_test_ok - print(message) - fout.write(message + '\n') - else: - # テスト結果 NG - message = message + g_test_ng - print(message) - message = message + g_test_ng_message - fout.write(message + '\n') - # 受信データをテスト結果ファイルへコピー - fin2 = open(g_diff_recv_file, 'r') - while(1): - s2 = fin2.readline() - if len(s2) == 0: - break - fout.write(s2) - fin2.close() + message = g_mess_header + g_test_case + str(case_no) + " " + message = message + \ + "Connecting(in->out, flush), Activate -> send/recv -> Deactivate" + message = message + g_mess_footer + fout.write(message + '\n') fout.close() + print(message) - time.sleep(sleep_for_time) - -## 6 ポート切断 -g_in_ports[g_port3].disconnect(g_conprof3.connector_id) -g_in_ports[g_port2].disconnect(g_conprof2.connector_id) -g_in_ports[g_port1].disconnect(g_conprof1.connector_id) + # 1 コネクタープロファイル設定 + make_connecter_profile("flush", "", 1) -##-------------------------------------------------------------------- -## 接続タイプ:flush 方向:out->in Activate・Deactivateテスト10 -##-------------------------------------------------------------------- -case_no = case_no + 1 -fout = open(g_test_result_file, 'a') -message = g_mess_header + g_test_case + str(case_no) + " " -message = message + "Not Connect(out->in, flush), Activate -> Deactivate" -message = message + g_mess_footer -fout.write(message + '\n') -fout.close() -print(message) + # 3 ポート接続 + # データポート1 TimedFloat + ret0 = g_out_ports[g_port1].connect(g_conprof1) -for i in range(loop_count): + # データポート2 TimedFloatSeq + ret1 = g_out_ports[g_port2].connect(g_conprof2) - ## 1 コネクタープロファイル設定 - make_connecter_profile("flush", "", 0) + # サービスポート MyService + ret2 = g_out_ports[g_port3].connect(g_conprof3) - ## 4 アクティベート - ec_recv[0].activate_component(g_compo_recv.rtc_ref) - time.sleep(sleep_recv_act_time) - ec_send[0].activate_component(g_compo_send.rtc_ref) + for i in range(loop_count): - time.sleep(sleep_act_time) + # 2 受信データファイル削除 + delete_recv_file() - ## 5 ディアクティベート - ec_send[0].deactivate_component(g_compo_send.rtc_ref) - ec_recv[0].deactivate_component(g_compo_recv.rtc_ref) + # 4 アクティベート + ec_recv[0].activate_component(g_compo_recv.rtc_ref) + time.sleep(sleep_recv_act_time) + ec_send[0].activate_component(g_compo_send.rtc_ref) - ## テスト結果出力 - fout = open(g_test_result_file, 'a') - message = g_mess_header + g_test_case + str(case_no) + " " + g_test_cnt + str(i+1) + g_mess_footer - message = message + g_test_ok - print(message) - fout.write(message + '\n') - fout.close() + time.sleep(sleep_act_time) - time.sleep(sleep_for_time) + # 5 ディアクティベート + ec_send[0].deactivate_component(g_compo_send.rtc_ref) + ec_recv[0].deactivate_component(g_compo_recv.rtc_ref) -##-------------------------------------------------------------------- -## 接続タイプ:flush 方向:out->in 接続・切断・Activate・Deactivateテスト1 -##-------------------------------------------------------------------- -case_no = case_no + 1 -fout = open(g_test_result_file, 'a') -message = g_mess_header + g_test_case + str(case_no) + " " -message = message + "Connect(out->in, flush) -> Activate -> send/recv -> Deactivate -> Disconnect" -message = message + g_mess_footer -fout.write(message + '\n') -fout.close() -print(message) + # 受信ファイル有無判定 + if os.path.isfile(g_diff_recv_file) == False: + fout = open(g_test_result_file, 'a') + message = g_mess_header + g_test_case + \ + str(case_no) + " " + g_test_cnt + str(i + 1) + g_mess_footer + message = message + g_check_message + fout.write(message + '\n') + fout.close() + print(message) + time.sleep(sleep_for_time) + continue -for i in range(loop_count): + # 7 送受信データ比較 + time.sleep(sleep_act_time) + bret = diff_file() - ## 2 受信データファイル削除 - delete_recv_file() + # 差分ファイルからテスト結果出力 + fout = open(g_test_result_file, 'a') + message = g_mess_header + g_test_case + \ + str(case_no) + " " + g_test_cnt + str(i + 1) + g_mess_footer + # bret==True なら送受信データ一致 + if bret == True: + # テスト結果 OK + message = message + g_test_ok + print(message) + fout.write(message + '\n') + else: + # テスト結果 NG + message = message + g_test_ng + print(message) + message = message + g_test_ng_message + fout.write(message + '\n') + # 受信データをテスト結果ファイルへコピー + fin2 = open(g_diff_recv_file, 'r') + while(1): + s2 = fin2.readline() + if len(s2) == 0: + break + fout.write(s2) + fin2.close() + fout.close() - ## 1 コネクタープロファイル設定 - make_connecter_profile("flush", "", 0) + time.sleep(sleep_for_time) - ## 3 ポート接続 - # データポート1 TimedFloat - ret0 = g_out_ports[g_port1].connect(g_conprof1) + # 6 ポート切断 + g_in_ports[g_port3].disconnect(g_conprof3.connector_id) + g_in_ports[g_port2].disconnect(g_conprof2.connector_id) + g_in_ports[g_port1].disconnect(g_conprof1.connector_id) - # データポート2 TimedFloatSeq - ret1 = g_out_ports[g_port2].connect(g_conprof2) + # -------------------------------------------------------------------- + # 接続タイプ:flush 方向:out->in Activate・Deactivateテスト10 + # -------------------------------------------------------------------- + case_no = case_no + 1 + fout = open(g_test_result_file, 'a') + message = g_mess_header + g_test_case + str(case_no) + " " + message = message + "Not Connect(out->in, flush), Activate -> Deactivate" + message = message + g_mess_footer + fout.write(message + '\n') + fout.close() + print(message) - # サービスポート MyService - ret2 = g_out_ports[g_port3].connect(g_conprof3) + for i in range(loop_count): - ## 4 アクティベート - ec_recv[0].activate_component(g_compo_recv.rtc_ref) - time.sleep(sleep_recv_act_time) - ec_send[0].activate_component(g_compo_send.rtc_ref) + # 1 コネクタープロファイル設定 + make_connecter_profile("flush", "", 0) - time.sleep(sleep_act_time) + # 4 アクティベート + ec_recv[0].activate_component(g_compo_recv.rtc_ref) + time.sleep(sleep_recv_act_time) + ec_send[0].activate_component(g_compo_send.rtc_ref) - ## 5 ディアクティベート - ec_send[0].deactivate_component(g_compo_send.rtc_ref) - ec_recv[0].deactivate_component(g_compo_recv.rtc_ref) + time.sleep(sleep_act_time) - ## 6 ポート切断 - g_in_ports[g_port3].disconnect(g_conprof3.connector_id) - g_in_ports[g_port2].disconnect(g_conprof2.connector_id) - g_in_ports[g_port1].disconnect(g_conprof1.connector_id) + # 5 ディアクティベート + ec_send[0].deactivate_component(g_compo_send.rtc_ref) + ec_recv[0].deactivate_component(g_compo_recv.rtc_ref) - ## 受信ファイル有無判定 - if os.path.isfile(g_diff_recv_file) == False: + # テスト結果出力 fout = open(g_test_result_file, 'a') - message = g_mess_header + g_test_case + str(case_no) + " " + g_test_cnt + str(i+1) + g_mess_footer - message = message + g_check_message + message = g_mess_header + g_test_case + \ + str(case_no) + " " + g_test_cnt + str(i + 1) + g_mess_footer + message = message + g_test_ok + print(message) fout.write(message + '\n') fout.close() - print(message) - time.sleep(sleep_for_time) - continue - ## 7 送受信データ比較 - time.sleep(sleep_act_time) - bret = diff_file() + time.sleep(sleep_for_time) - ## 差分ファイルからテスト結果出力 + # -------------------------------------------------------------------- + # 接続タイプ:flush 方向:out->in 接続・切断・Activate・Deactivateテスト1 + # -------------------------------------------------------------------- + case_no = case_no + 1 fout = open(g_test_result_file, 'a') - message = g_mess_header + g_test_case + str(case_no) + " " + g_test_cnt + str(i+1) + g_mess_footer - # bret==True なら送受信データ一致 - if bret == True: - # テスト結果 OK - message = message + g_test_ok - print(message) - fout.write(message + '\n') - else: - # テスト結果 NG - message = message + g_test_ng - print(message) - message = message + g_test_ng_message - fout.write(message + '\n') - # 受信データをテスト結果ファイルへコピー - fin2 = open(g_diff_recv_file, 'r') - while(1): - s2 = fin2.readline() - if len(s2) == 0: - break - fout.write(s2) - fin2.close() + message = g_mess_header + g_test_case + str(case_no) + " " + message = message + \ + "Connect(out->in, flush) -> Activate -> send/recv -> Deactivate -> Disconnect" + message = message + g_mess_footer + fout.write(message + '\n') fout.close() + print(message) - time.sleep(sleep_for_time) + for i in range(loop_count): -##-------------------------------------------------------------------- -## 接続タイプ:flush 方向:in->out 接続・切断・Activate・Deactivateテスト1 -##-------------------------------------------------------------------- -case_no = case_no + 1 -fout = open(g_test_result_file, 'a') -message = g_mess_header + g_test_case + str(case_no) + " " -message = message + "Connect(in->out, flush) -> Activate -> send/recv -> Deactivate -> Disconnect" -message = message + g_mess_footer -fout.write(message + '\n') -fout.close() -print(message) + # 2 受信データファイル削除 + delete_recv_file() -for i in range(loop_count): + # 1 コネクタープロファイル設定 + make_connecter_profile("flush", "", 0) - ## 2 受信データファイル削除 - delete_recv_file() + # 3 ポート接続 + # データポート1 TimedFloat + ret0 = g_out_ports[g_port1].connect(g_conprof1) - ## 1 コネクタープロファイル設定 - make_connecter_profile("flush", "", 1) + # データポート2 TimedFloatSeq + ret1 = g_out_ports[g_port2].connect(g_conprof2) - ## 3 ポート接続 - # データポート1 TimedFloat - ret0 = g_out_ports[g_port1].connect(g_conprof1) + # サービスポート MyService + ret2 = g_out_ports[g_port3].connect(g_conprof3) - # データポート2 TimedFloatSeq - ret1 = g_out_ports[g_port2].connect(g_conprof2) + # 4 アクティベート + ec_recv[0].activate_component(g_compo_recv.rtc_ref) + time.sleep(sleep_recv_act_time) + ec_send[0].activate_component(g_compo_send.rtc_ref) - # サービスポート MyService - ret2 = g_out_ports[g_port3].connect(g_conprof3) + time.sleep(sleep_act_time) - ## 4 アクティベート - ec_recv[0].activate_component(g_compo_recv.rtc_ref) - time.sleep(sleep_recv_act_time) - ec_send[0].activate_component(g_compo_send.rtc_ref) + # 5 ディアクティベート + ec_send[0].deactivate_component(g_compo_send.rtc_ref) + ec_recv[0].deactivate_component(g_compo_recv.rtc_ref) - time.sleep(sleep_act_time) + # 6 ポート切断 + g_in_ports[g_port3].disconnect(g_conprof3.connector_id) + g_in_ports[g_port2].disconnect(g_conprof2.connector_id) + g_in_ports[g_port1].disconnect(g_conprof1.connector_id) - ## 5 ディアクティベート - ec_send[0].deactivate_component(g_compo_send.rtc_ref) - ec_recv[0].deactivate_component(g_compo_recv.rtc_ref) + # 受信ファイル有無判定 + if os.path.isfile(g_diff_recv_file) == False: + fout = open(g_test_result_file, 'a') + message = g_mess_header + g_test_case + \ + str(case_no) + " " + g_test_cnt + str(i + 1) + g_mess_footer + message = message + g_check_message + fout.write(message + '\n') + fout.close() + print(message) + time.sleep(sleep_for_time) + continue - ## 6 ポート切断 - g_in_ports[g_port3].disconnect(g_conprof3.connector_id) - g_in_ports[g_port2].disconnect(g_conprof2.connector_id) - g_in_ports[g_port1].disconnect(g_conprof1.connector_id) + # 7 送受信データ比較 + time.sleep(sleep_act_time) + bret = diff_file() - ## 受信ファイル有無判定 - if os.path.isfile(g_diff_recv_file) == False: + # 差分ファイルからテスト結果出力 fout = open(g_test_result_file, 'a') - message = g_mess_header + g_test_case + str(case_no) + " " + g_test_cnt + str(i+1) + g_mess_footer - message = message + g_check_message - fout.write(message + '\n') + message = g_mess_header + g_test_case + \ + str(case_no) + " " + g_test_cnt + str(i + 1) + g_mess_footer + # bret==True なら送受信データ一致 + if bret == True: + # テスト結果 OK + message = message + g_test_ok + print(message) + fout.write(message + '\n') + else: + # テスト結果 NG + message = message + g_test_ng + print(message) + message = message + g_test_ng_message + fout.write(message + '\n') + # 受信データをテスト結果ファイルへコピー + fin2 = open(g_diff_recv_file, 'r') + while(1): + s2 = fin2.readline() + if len(s2) == 0: + break + fout.write(s2) + fin2.close() fout.close() - print(message) - time.sleep(sleep_for_time) - continue - ## 7 送受信データ比較 - time.sleep(sleep_act_time) - bret = diff_file() + time.sleep(sleep_for_time) - ## 差分ファイルからテスト結果出力 + # -------------------------------------------------------------------- + # 接続タイプ:flush 方向:in->out 接続・切断・Activate・Deactivateテスト1 + # -------------------------------------------------------------------- + case_no = case_no + 1 fout = open(g_test_result_file, 'a') - message = g_mess_header + g_test_case + str(case_no) + " " + g_test_cnt + str(i+1) + g_mess_footer - # bret==True なら送受信データ一致 - if bret == True: - # テスト結果 OK - message = message + g_test_ok - print(message) - fout.write(message + '\n') - else: - # テスト結果 NG - message = message + g_test_ng - print(message) - message = message + g_test_ng_message - fout.write(message + '\n') - # 受信データをテスト結果ファイルへコピー - fin2 = open(g_diff_recv_file, 'r') - while(1): - s2 = fin2.readline() - if len(s2) == 0: - break - fout.write(s2) - fin2.close() + message = g_mess_header + g_test_case + str(case_no) + " " + message = message + \ + "Connect(in->out, flush) -> Activate -> send/recv -> Deactivate -> Disconnect" + message = message + g_mess_footer + fout.write(message + '\n') fout.close() + print(message) - time.sleep(sleep_for_time) + for i in range(loop_count): -##-------------------------------------------------------------------- -## 接続タイプ:flush 方向:out->in 接続・切断・Activate・Deactivateテスト2 -##-------------------------------------------------------------------- -case_no = case_no + 1 -fout = open(g_test_result_file, 'a') -message = g_mess_header + g_test_case + str(case_no) + " " -message = message + "Connect(out->in, flush) -> Activate -> send/recv -> Disconnect -> Deactivate" -message = message + g_mess_footer -fout.write(message + '\n') -fout.close() -print(message) + # 2 受信データファイル削除 + delete_recv_file() -for i in range(loop_count): + # 1 コネクタープロファイル設定 + make_connecter_profile("flush", "", 1) - ## 2 受信データファイル削除 - delete_recv_file() + # 3 ポート接続 + # データポート1 TimedFloat + ret0 = g_out_ports[g_port1].connect(g_conprof1) - ## 1 コネクタープロファイル設定 - make_connecter_profile("flush", "", 0) + # データポート2 TimedFloatSeq + ret1 = g_out_ports[g_port2].connect(g_conprof2) - ## 3 ポート接続 - # データポート1 TimedFloat - ret0 = g_out_ports[g_port1].connect(g_conprof1) + # サービスポート MyService + ret2 = g_out_ports[g_port3].connect(g_conprof3) - # データポート2 TimedFloatSeq - ret1 = g_out_ports[g_port2].connect(g_conprof2) + # 4 アクティベート + ec_recv[0].activate_component(g_compo_recv.rtc_ref) + time.sleep(sleep_recv_act_time) + ec_send[0].activate_component(g_compo_send.rtc_ref) - # サービスポート MyService - ret2 = g_out_ports[g_port3].connect(g_conprof3) + time.sleep(sleep_act_time) - ## 4 アクティベート - ec_recv[0].activate_component(g_compo_recv.rtc_ref) - time.sleep(sleep_recv_act_time) - ec_send[0].activate_component(g_compo_send.rtc_ref) + # 5 ディアクティベート + ec_send[0].deactivate_component(g_compo_send.rtc_ref) + ec_recv[0].deactivate_component(g_compo_recv.rtc_ref) - time.sleep(sleep_act_time) + # 6 ポート切断 + g_in_ports[g_port3].disconnect(g_conprof3.connector_id) + g_in_ports[g_port2].disconnect(g_conprof2.connector_id) + g_in_ports[g_port1].disconnect(g_conprof1.connector_id) - ## 6 ポート切断 - g_in_ports[g_port3].disconnect(g_conprof3.connector_id) - g_in_ports[g_port2].disconnect(g_conprof2.connector_id) - g_in_ports[g_port1].disconnect(g_conprof1.connector_id) + # 受信ファイル有無判定 + if os.path.isfile(g_diff_recv_file) == False: + fout = open(g_test_result_file, 'a') + message = g_mess_header + g_test_case + \ + str(case_no) + " " + g_test_cnt + str(i + 1) + g_mess_footer + message = message + g_check_message + fout.write(message + '\n') + fout.close() + print(message) + time.sleep(sleep_for_time) + continue - ## 5 ディアクティベート - ec_send[0].deactivate_component(g_compo_send.rtc_ref) - ec_recv[0].deactivate_component(g_compo_recv.rtc_ref) + # 7 送受信データ比較 + time.sleep(sleep_act_time) + bret = diff_file() - ## 受信ファイル有無判定 - if os.path.isfile(g_diff_recv_file) == False: + # 差分ファイルからテスト結果出力 fout = open(g_test_result_file, 'a') - message = g_mess_header + g_test_case + str(case_no) + " " + g_test_cnt + str(i+1) + g_mess_footer - message = message + g_check_message - fout.write(message + '\n') + message = g_mess_header + g_test_case + \ + str(case_no) + " " + g_test_cnt + str(i + 1) + g_mess_footer + # bret==True なら送受信データ一致 + if bret == True: + # テスト結果 OK + message = message + g_test_ok + print(message) + fout.write(message + '\n') + else: + # テスト結果 NG + message = message + g_test_ng + print(message) + message = message + g_test_ng_message + fout.write(message + '\n') + # 受信データをテスト結果ファイルへコピー + fin2 = open(g_diff_recv_file, 'r') + while(1): + s2 = fin2.readline() + if len(s2) == 0: + break + fout.write(s2) + fin2.close() fout.close() - print(message) - time.sleep(sleep_for_time) - continue - ## 7 送受信データ比較 - time.sleep(sleep_act_time) - bret = diff_file() + time.sleep(sleep_for_time) - ## 差分ファイルからテスト結果出力 + # -------------------------------------------------------------------- + # 接続タイプ:flush 方向:out->in 接続・切断・Activate・Deactivateテスト2 + # -------------------------------------------------------------------- + case_no = case_no + 1 fout = open(g_test_result_file, 'a') - message = g_mess_header + g_test_case + str(case_no) + " " + g_test_cnt + str(i+1) + g_mess_footer - # bret==True なら送受信データ一致 - if bret == True: - # テスト結果 OK - message = message + g_test_ok - print(message) - fout.write(message + '\n') - else: - # テスト結果 NG - message = message + g_test_ng - print(message) - message = message + g_test_ng_message - fout.write(message + '\n') - # 受信データをテスト結果ファイルへコピー - fin2 = open(g_diff_recv_file, 'r') - while(1): - s2 = fin2.readline() - if len(s2) == 0: - break - fout.write(s2) - fin2.close() + message = g_mess_header + g_test_case + str(case_no) + " " + message = message + \ + "Connect(out->in, flush) -> Activate -> send/recv -> Disconnect -> Deactivate" + message = message + g_mess_footer + fout.write(message + '\n') fout.close() + print(message) - time.sleep(sleep_for_time) + for i in range(loop_count): -##-------------------------------------------------------------------- -## 接続タイプ:flush 方向:in->out 接続・切断・Activate・Deactivateテスト2 -##-------------------------------------------------------------------- -case_no = case_no + 1 -fout = open(g_test_result_file, 'a') -message = g_mess_header + g_test_case + str(case_no) + " " -message = message + "Connect(in->out, flush) -> Activate -> send/recv -> Disconnect -> Deactivate" -message = message + g_mess_footer -fout.write(message + '\n') -fout.close() -print(message) + # 2 受信データファイル削除 + delete_recv_file() -for i in range(loop_count): + # 1 コネクタープロファイル設定 + make_connecter_profile("flush", "", 0) - ## 2 受信データファイル削除 - delete_recv_file() + # 3 ポート接続 + # データポート1 TimedFloat + ret0 = g_out_ports[g_port1].connect(g_conprof1) - ## 1 コネクタープロファイル設定 - make_connecter_profile("flush", "", 1) + # データポート2 TimedFloatSeq + ret1 = g_out_ports[g_port2].connect(g_conprof2) - ## 3 ポート接続 - # データポート1 TimedFloat - ret0 = g_out_ports[g_port1].connect(g_conprof1) + # サービスポート MyService + ret2 = g_out_ports[g_port3].connect(g_conprof3) - # データポート2 TimedFloatSeq - ret1 = g_out_ports[g_port2].connect(g_conprof2) + # 4 アクティベート + ec_recv[0].activate_component(g_compo_recv.rtc_ref) + time.sleep(sleep_recv_act_time) + ec_send[0].activate_component(g_compo_send.rtc_ref) - # サービスポート MyService - ret2 = g_out_ports[g_port3].connect(g_conprof3) + time.sleep(sleep_act_time) - ## 4 アクティベート - ec_recv[0].activate_component(g_compo_recv.rtc_ref) - time.sleep(sleep_recv_act_time) - ec_send[0].activate_component(g_compo_send.rtc_ref) + # 6 ポート切断 + g_in_ports[g_port3].disconnect(g_conprof3.connector_id) + g_in_ports[g_port2].disconnect(g_conprof2.connector_id) + g_in_ports[g_port1].disconnect(g_conprof1.connector_id) - time.sleep(sleep_act_time) + # 5 ディアクティベート + ec_send[0].deactivate_component(g_compo_send.rtc_ref) + ec_recv[0].deactivate_component(g_compo_recv.rtc_ref) - ## 6 ポート切断 - g_in_ports[g_port3].disconnect(g_conprof3.connector_id) - g_in_ports[g_port2].disconnect(g_conprof2.connector_id) - g_in_ports[g_port1].disconnect(g_conprof1.connector_id) + # 受信ファイル有無判定 + if os.path.isfile(g_diff_recv_file) == False: + fout = open(g_test_result_file, 'a') + message = g_mess_header + g_test_case + \ + str(case_no) + " " + g_test_cnt + str(i + 1) + g_mess_footer + message = message + g_check_message + fout.write(message + '\n') + fout.close() + print(message) + time.sleep(sleep_for_time) + continue - ## 5 ディアクティベート - ec_send[0].deactivate_component(g_compo_send.rtc_ref) - ec_recv[0].deactivate_component(g_compo_recv.rtc_ref) + # 7 送受信データ比較 + time.sleep(sleep_act_time) + bret = diff_file() - ## 受信ファイル有無判定 - if os.path.isfile(g_diff_recv_file) == False: + # 差分ファイルからテスト結果出力 fout = open(g_test_result_file, 'a') - message = g_mess_header + g_test_case + str(case_no) + " " + g_test_cnt + str(i+1) + g_mess_footer - message = message + g_check_message - fout.write(message + '\n') + message = g_mess_header + g_test_case + \ + str(case_no) + " " + g_test_cnt + str(i + 1) + g_mess_footer + # bret==True なら送受信データ一致 + if bret == True: + # テスト結果 OK + message = message + g_test_ok + print(message) + fout.write(message + '\n') + else: + # テスト結果 NG + message = message + g_test_ng + print(message) + message = message + g_test_ng_message + fout.write(message + '\n') + # 受信データをテスト結果ファイルへコピー + fin2 = open(g_diff_recv_file, 'r') + while(1): + s2 = fin2.readline() + if len(s2) == 0: + break + fout.write(s2) + fin2.close() fout.close() - print(message) - time.sleep(sleep_for_time) - continue - ## 7 送受信データ比較 - time.sleep(sleep_act_time) - bret = diff_file() + time.sleep(sleep_for_time) - ## 差分ファイルからテスト結果出力 + # -------------------------------------------------------------------- + # 接続タイプ:flush 方向:in->out 接続・切断・Activate・Deactivateテスト2 + # -------------------------------------------------------------------- + case_no = case_no + 1 fout = open(g_test_result_file, 'a') - message = g_mess_header + g_test_case + str(case_no) + " " + g_test_cnt + str(i+1) + g_mess_footer - # bret==True なら送受信データ一致 - if bret == True: - # テスト結果 OK - message = message + g_test_ok - print(message) - fout.write(message + '\n') - else: - # テスト結果 NG - message = message + g_test_ng - print(message) - message = message + g_test_ng_message - fout.write(message + '\n') - # 受信データをテスト結果ファイルへコピー - fin2 = open(g_diff_recv_file, 'r') - while(1): - s2 = fin2.readline() - if len(s2) == 0: - break - fout.write(s2) - fin2.close() + message = g_mess_header + g_test_case + str(case_no) + " " + message = message + \ + "Connect(in->out, flush) -> Activate -> send/recv -> Disconnect -> Deactivate" + message = message + g_mess_footer + fout.write(message + '\n') fout.close() + print(message) - time.sleep(sleep_for_time) - + for i in range(loop_count): -##-------------------------------------------------------------------- -## 接続タイプ:flush 方向:out->in 接続・切断・Activate・Deactivateテスト3 -##-------------------------------------------------------------------- -## ●注意:Activateを先に行っている為、受信データは途中からの内容になります。 -case_no = case_no + 1 -fout = open(g_test_result_file, 'a') -message = g_mess_header + g_test_case + str(case_no) + " " -message = message + "Activate -> Connect(out->in, flush) -> send/recv -> Deactivate -> Disconnect" -message = message + g_mess_footer -fout.write(message + '\n') -fout.close() -print(message) + # 2 受信データファイル削除 + delete_recv_file() -for i in range(loop_count): + # 1 コネクタープロファイル設定 + make_connecter_profile("flush", "", 1) - ## 2 受信データファイル削除 - delete_recv_file() + # 3 ポート接続 + # データポート1 TimedFloat + ret0 = g_out_ports[g_port1].connect(g_conprof1) - ## 1 コネクタープロファイル設定 - make_connecter_profile("flush", "", 0) + # データポート2 TimedFloatSeq + ret1 = g_out_ports[g_port2].connect(g_conprof2) - ## 4 アクティベート - ec_recv[0].activate_component(g_compo_recv.rtc_ref) - time.sleep(sleep_recv_act_time) - ec_send[0].activate_component(g_compo_send.rtc_ref) + # サービスポート MyService + ret2 = g_out_ports[g_port3].connect(g_conprof3) - ## 3 ポート接続 - # データポート1 TimedFloat - ret0 = g_out_ports[g_port1].connect(g_conprof1) + # 4 アクティベート + ec_recv[0].activate_component(g_compo_recv.rtc_ref) + time.sleep(sleep_recv_act_time) + ec_send[0].activate_component(g_compo_send.rtc_ref) - # データポート2 TimedFloatSeq - ret1 = g_out_ports[g_port2].connect(g_conprof2) + time.sleep(sleep_act_time) - # サービスポート MyService - ret2 = g_out_ports[g_port3].connect(g_conprof3) + # 6 ポート切断 + g_in_ports[g_port3].disconnect(g_conprof3.connector_id) + g_in_ports[g_port2].disconnect(g_conprof2.connector_id) + g_in_ports[g_port1].disconnect(g_conprof1.connector_id) - time.sleep(sleep_act_time) + # 5 ディアクティベート + ec_send[0].deactivate_component(g_compo_send.rtc_ref) + ec_recv[0].deactivate_component(g_compo_recv.rtc_ref) - ## 5 ディアクティベート - ec_send[0].deactivate_component(g_compo_send.rtc_ref) - ec_recv[0].deactivate_component(g_compo_recv.rtc_ref) + # 受信ファイル有無判定 + if os.path.isfile(g_diff_recv_file) == False: + fout = open(g_test_result_file, 'a') + message = g_mess_header + g_test_case + \ + str(case_no) + " " + g_test_cnt + str(i + 1) + g_mess_footer + message = message + g_check_message + fout.write(message + '\n') + fout.close() + print(message) + time.sleep(sleep_for_time) + continue - ## 6 ポート切断 - g_in_ports[g_port3].disconnect(g_conprof3.connector_id) - g_in_ports[g_port2].disconnect(g_conprof2.connector_id) - g_in_ports[g_port1].disconnect(g_conprof1.connector_id) + # 7 送受信データ比較 + time.sleep(sleep_act_time) + bret = diff_file() - ## 受信ファイル有無判定 - if os.path.isfile(g_diff_recv_file) == False: + # 差分ファイルからテスト結果出力 fout = open(g_test_result_file, 'a') - message = g_mess_header + g_test_case + str(case_no) + " " + g_test_cnt + str(i+1) + g_mess_footer - message = message + g_check_message - fout.write(message + '\n') + message = g_mess_header + g_test_case + \ + str(case_no) + " " + g_test_cnt + str(i + 1) + g_mess_footer + # bret==True なら送受信データ一致 + if bret == True: + # テスト結果 OK + message = message + g_test_ok + print(message) + fout.write(message + '\n') + else: + # テスト結果 NG + message = message + g_test_ng + print(message) + message = message + g_test_ng_message + fout.write(message + '\n') + # 受信データをテスト結果ファイルへコピー + fin2 = open(g_diff_recv_file, 'r') + while(1): + s2 = fin2.readline() + if len(s2) == 0: + break + fout.write(s2) + fin2.close() fout.close() - print(message) - time.sleep(sleep_for_time) - continue - ## 7 送受信データ比較 - time.sleep(sleep_act_time) - bret = diff_file() + time.sleep(sleep_for_time) - ## 差分ファイルからテスト結果出力 + # -------------------------------------------------------------------- + # 接続タイプ:flush 方向:out->in 接続・切断・Activate・Deactivateテスト3 + # -------------------------------------------------------------------- + # ●注意:Activateを先に行っている為、受信データは途中からの内容になります。 + case_no = case_no + 1 fout = open(g_test_result_file, 'a') - message = g_mess_header + g_test_case + str(case_no) + " " + g_test_cnt + str(i+1) + g_mess_footer - # bret==True なら送受信データ一致 - if bret == True: - # テスト結果 OK - message = message + g_test_ok - print(message) - fout.write(message + '\n') - else: - # テスト結果 NG - message = message + g_test_ng - print(message) - message = message + g_test_ng_message - fout.write(message + '\n') - # 受信データをテスト結果ファイルへコピー - fin2 = open(g_diff_recv_file, 'r') - while(1): - s2 = fin2.readline() - if len(s2) == 0: - break - fout.write(s2) - fin2.close() + message = g_mess_header + g_test_case + str(case_no) + " " + message = message + \ + "Activate -> Connect(out->in, flush) -> send/recv -> Deactivate -> Disconnect" + message = message + g_mess_footer + fout.write(message + '\n') fout.close() + print(message) - time.sleep(sleep_for_time) + for i in range(loop_count): -##-------------------------------------------------------------------- -## 接続タイプ:flush 方向:in->out 接続・切断・Activate・Deactivateテスト3 -##-------------------------------------------------------------------- -## ●注意:Activateを先に行っている為、受信データは途中からの内容になります。 -case_no = case_no + 1 -fout = open(g_test_result_file, 'a') -message = g_mess_header + g_test_case + str(case_no) + " " -message = message + "Activate -> Connect(in->out, flush) -> send/recv -> Deactivate -> Disconnect" -message = message + g_mess_footer -fout.write(message + '\n') -fout.close() -print(message) + # 2 受信データファイル削除 + delete_recv_file() -for i in range(loop_count): + # 1 コネクタープロファイル設定 + make_connecter_profile("flush", "", 0) - ## 2 受信データファイル削除 - delete_recv_file() + # 4 アクティベート + ec_recv[0].activate_component(g_compo_recv.rtc_ref) + time.sleep(sleep_recv_act_time) + ec_send[0].activate_component(g_compo_send.rtc_ref) - ## 1 コネクタープロファイル設定 - make_connecter_profile("flush", "", 1) + # 3 ポート接続 + # データポート1 TimedFloat + ret0 = g_out_ports[g_port1].connect(g_conprof1) - ## 4 アクティベート - ec_recv[0].activate_component(g_compo_recv.rtc_ref) - time.sleep(sleep_recv_act_time) - ec_send[0].activate_component(g_compo_send.rtc_ref) + # データポート2 TimedFloatSeq + ret1 = g_out_ports[g_port2].connect(g_conprof2) - ## 3 ポート接続 - # データポート1 TimedFloat - ret0 = g_out_ports[g_port1].connect(g_conprof1) + # サービスポート MyService + ret2 = g_out_ports[g_port3].connect(g_conprof3) - # データポート2 TimedFloatSeq - ret1 = g_out_ports[g_port2].connect(g_conprof2) + time.sleep(sleep_act_time) - # サービスポート MyService - ret2 = g_out_ports[g_port3].connect(g_conprof3) + # 5 ディアクティベート + ec_send[0].deactivate_component(g_compo_send.rtc_ref) + ec_recv[0].deactivate_component(g_compo_recv.rtc_ref) - time.sleep(sleep_act_time) + # 6 ポート切断 + g_in_ports[g_port3].disconnect(g_conprof3.connector_id) + g_in_ports[g_port2].disconnect(g_conprof2.connector_id) + g_in_ports[g_port1].disconnect(g_conprof1.connector_id) - ## 5 ディアクティベート - ec_send[0].deactivate_component(g_compo_send.rtc_ref) - ec_recv[0].deactivate_component(g_compo_recv.rtc_ref) + # 受信ファイル有無判定 + if os.path.isfile(g_diff_recv_file) == False: + fout = open(g_test_result_file, 'a') + message = g_mess_header + g_test_case + \ + str(case_no) + " " + g_test_cnt + str(i + 1) + g_mess_footer + message = message + g_check_message + fout.write(message + '\n') + fout.close() + print(message) + time.sleep(sleep_for_time) + continue - ## 6 ポート切断 - g_in_ports[g_port3].disconnect(g_conprof3.connector_id) - g_in_ports[g_port2].disconnect(g_conprof2.connector_id) - g_in_ports[g_port1].disconnect(g_conprof1.connector_id) + # 7 送受信データ比較 + time.sleep(sleep_act_time) + bret = diff_file() - ## 受信ファイル有無判定 - if os.path.isfile(g_diff_recv_file) == False: + # 差分ファイルからテスト結果出力 fout = open(g_test_result_file, 'a') - message = g_mess_header + g_test_case + str(case_no) + " " + g_test_cnt + str(i+1) + g_mess_footer - message = message + g_check_message - fout.write(message + '\n') + message = g_mess_header + g_test_case + \ + str(case_no) + " " + g_test_cnt + str(i + 1) + g_mess_footer + # bret==True なら送受信データ一致 + if bret == True: + # テスト結果 OK + message = message + g_test_ok + print(message) + fout.write(message + '\n') + else: + # テスト結果 NG + message = message + g_test_ng + print(message) + message = message + g_test_ng_message + fout.write(message + '\n') + # 受信データをテスト結果ファイルへコピー + fin2 = open(g_diff_recv_file, 'r') + while(1): + s2 = fin2.readline() + if len(s2) == 0: + break + fout.write(s2) + fin2.close() fout.close() - print(message) - time.sleep(sleep_for_time) - continue - ## 7 送受信データ比較 - time.sleep(sleep_act_time) - bret = diff_file() + time.sleep(sleep_for_time) - ## 差分ファイルからテスト結果出力 + # -------------------------------------------------------------------- + # 接続タイプ:flush 方向:in->out 接続・切断・Activate・Deactivateテスト3 + # -------------------------------------------------------------------- + # ●注意:Activateを先に行っている為、受信データは途中からの内容になります。 + case_no = case_no + 1 fout = open(g_test_result_file, 'a') - message = g_mess_header + g_test_case + str(case_no) + " " + g_test_cnt + str(i+1) + g_mess_footer - # bret==True なら送受信データ一致 - if bret == True: - # テスト結果 OK - message = message + g_test_ok - print(message) - fout.write(message + '\n') - else: - # テスト結果 NG - message = message + g_test_ng - print(message) - message = message + g_test_ng_message - fout.write(message + '\n') - # 受信データをテスト結果ファイルへコピー - fin2 = open(g_diff_recv_file, 'r') - while(1): - s2 = fin2.readline() - if len(s2) == 0: - break - fout.write(s2) - fin2.close() + message = g_mess_header + g_test_case + str(case_no) + " " + message = message + \ + "Activate -> Connect(in->out, flush) -> send/recv -> Deactivate -> Disconnect" + message = message + g_mess_footer + fout.write(message + '\n') fout.close() + print(message) - time.sleep(sleep_for_time) + for i in range(loop_count): -##-------------------------------------------------------------------- -## 接続タイプ:flush 方向:out->in 接続・切断・Activate・Deactivateテスト4 -##-------------------------------------------------------------------- -## ●注意:Activateを先に行っている為、受信データは途中からの内容になります。 -case_no = case_no + 1 -fout = open(g_test_result_file, 'a') -message = g_mess_header + g_test_case + str(case_no) + " " -message = message + "Activate -> Connect(out->in, flush) -> send/recv -> Disconnect -> Deactivate" -message = message + g_mess_footer -fout.write(message + '\n') -fout.close() -print(message) + # 2 受信データファイル削除 + delete_recv_file() -for i in range(loop_count): + # 1 コネクタープロファイル設定 + make_connecter_profile("flush", "", 1) - ## 2 受信データファイル削除 - delete_recv_file() + # 4 アクティベート + ec_recv[0].activate_component(g_compo_recv.rtc_ref) + time.sleep(sleep_recv_act_time) + ec_send[0].activate_component(g_compo_send.rtc_ref) - ## 1 コネクタープロファイル設定 - make_connecter_profile("flush", "", 0) + # 3 ポート接続 + # データポート1 TimedFloat + ret0 = g_out_ports[g_port1].connect(g_conprof1) - ## 4 アクティベート - ec_recv[0].activate_component(g_compo_recv.rtc_ref) - time.sleep(sleep_recv_act_time) - ec_send[0].activate_component(g_compo_send.rtc_ref) + # データポート2 TimedFloatSeq + ret1 = g_out_ports[g_port2].connect(g_conprof2) - ## 3 ポート接続 - # データポート1 TimedFloat - ret0 = g_out_ports[g_port1].connect(g_conprof1) + # サービスポート MyService + ret2 = g_out_ports[g_port3].connect(g_conprof3) - # データポート2 TimedFloatSeq - ret1 = g_out_ports[g_port2].connect(g_conprof2) + time.sleep(sleep_act_time) - # サービスポート MyService - ret2 = g_out_ports[g_port3].connect(g_conprof3) + # 5 ディアクティベート + ec_send[0].deactivate_component(g_compo_send.rtc_ref) + ec_recv[0].deactivate_component(g_compo_recv.rtc_ref) - time.sleep(sleep_act_time) + # 6 ポート切断 + g_in_ports[g_port3].disconnect(g_conprof3.connector_id) + g_in_ports[g_port2].disconnect(g_conprof2.connector_id) + g_in_ports[g_port1].disconnect(g_conprof1.connector_id) - ## 6 ポート切断 - g_in_ports[g_port3].disconnect(g_conprof3.connector_id) - g_in_ports[g_port2].disconnect(g_conprof2.connector_id) - g_in_ports[g_port1].disconnect(g_conprof1.connector_id) + # 受信ファイル有無判定 + if os.path.isfile(g_diff_recv_file) == False: + fout = open(g_test_result_file, 'a') + message = g_mess_header + g_test_case + \ + str(case_no) + " " + g_test_cnt + str(i + 1) + g_mess_footer + message = message + g_check_message + fout.write(message + '\n') + fout.close() + print(message) + time.sleep(sleep_for_time) + continue - ## 5 ディアクティベート - ec_send[0].deactivate_component(g_compo_send.rtc_ref) - ec_recv[0].deactivate_component(g_compo_recv.rtc_ref) + # 7 送受信データ比較 + time.sleep(sleep_act_time) + bret = diff_file() - ## 受信ファイル有無判定 - if os.path.isfile(g_diff_recv_file) == False: + # 差分ファイルからテスト結果出力 fout = open(g_test_result_file, 'a') - message = g_mess_header + g_test_case + str(case_no) + " " + g_test_cnt + str(i+1) + g_mess_footer - message = message + g_check_message - fout.write(message + '\n') + message = g_mess_header + g_test_case + \ + str(case_no) + " " + g_test_cnt + str(i + 1) + g_mess_footer + # bret==True なら送受信データ一致 + if bret == True: + # テスト結果 OK + message = message + g_test_ok + print(message) + fout.write(message + '\n') + else: + # テスト結果 NG + message = message + g_test_ng + print(message) + message = message + g_test_ng_message + fout.write(message + '\n') + # 受信データをテスト結果ファイルへコピー + fin2 = open(g_diff_recv_file, 'r') + while(1): + s2 = fin2.readline() + if len(s2) == 0: + break + fout.write(s2) + fin2.close() fout.close() - print(message) - time.sleep(sleep_for_time) - continue - ## 7 送受信データ比較 - time.sleep(sleep_act_time) - bret = diff_file() + time.sleep(sleep_for_time) - ## 差分ファイルからテスト結果出力 + # -------------------------------------------------------------------- + # 接続タイプ:flush 方向:out->in 接続・切断・Activate・Deactivateテスト4 + # -------------------------------------------------------------------- + # ●注意:Activateを先に行っている為、受信データは途中からの内容になります。 + case_no = case_no + 1 fout = open(g_test_result_file, 'a') - message = g_mess_header + g_test_case + str(case_no) + " " + g_test_cnt + str(i+1) + g_mess_footer - # bret==True なら送受信データ一致 - if bret == True: - # テスト結果 OK - message = message + g_test_ok - print(message) - fout.write(message + '\n') - else: - # テスト結果 NG - message = message + g_test_ng - print(message) - message = message + g_test_ng_message - fout.write(message + '\n') - # 受信データをテスト結果ファイルへコピー - fin2 = open(g_diff_recv_file, 'r') - while(1): - s2 = fin2.readline() - if len(s2) == 0: - break - fout.write(s2) - fin2.close() + message = g_mess_header + g_test_case + str(case_no) + " " + message = message + \ + "Activate -> Connect(out->in, flush) -> send/recv -> Disconnect -> Deactivate" + message = message + g_mess_footer + fout.write(message + '\n') fout.close() + print(message) - time.sleep(sleep_for_time) + for i in range(loop_count): -##-------------------------------------------------------------------- -## 接続タイプ:flush 方向:in->out 接続・切断・Activate・Deactivateテスト4 -##-------------------------------------------------------------------- -## ●注意:Activateを先に行っている為、受信データは途中からの内容になります。 -case_no = case_no + 1 -fout = open(g_test_result_file, 'a') -message = g_mess_header + g_test_case + str(case_no) + " " -message = message + "Activate -> Connect(in->out, flush) -> send/recv -> Disconnect -> Deactivate" -message = message + g_mess_footer -fout.write(message + '\n') -fout.close() -print(message) + # 2 受信データファイル削除 + delete_recv_file() -for i in range(loop_count): + # 1 コネクタープロファイル設定 + make_connecter_profile("flush", "", 0) - ## 2 受信データファイル削除 - delete_recv_file() + # 4 アクティベート + ec_recv[0].activate_component(g_compo_recv.rtc_ref) + time.sleep(sleep_recv_act_time) + ec_send[0].activate_component(g_compo_send.rtc_ref) - ## 1 コネクタープロファイル設定 - make_connecter_profile("flush", "", 1) + # 3 ポート接続 + # データポート1 TimedFloat + ret0 = g_out_ports[g_port1].connect(g_conprof1) - ## 4 アクティベート - ec_recv[0].activate_component(g_compo_recv.rtc_ref) - time.sleep(sleep_recv_act_time) - ec_send[0].activate_component(g_compo_send.rtc_ref) + # データポート2 TimedFloatSeq + ret1 = g_out_ports[g_port2].connect(g_conprof2) - ## 3 ポート接続 - # データポート1 TimedFloat - ret0 = g_out_ports[g_port1].connect(g_conprof1) + # サービスポート MyService + ret2 = g_out_ports[g_port3].connect(g_conprof3) - # データポート2 TimedFloatSeq - ret1 = g_out_ports[g_port2].connect(g_conprof2) + time.sleep(sleep_act_time) - # サービスポート MyService - ret2 = g_out_ports[g_port3].connect(g_conprof3) + # 6 ポート切断 + g_in_ports[g_port3].disconnect(g_conprof3.connector_id) + g_in_ports[g_port2].disconnect(g_conprof2.connector_id) + g_in_ports[g_port1].disconnect(g_conprof1.connector_id) - time.sleep(sleep_act_time) + # 5 ディアクティベート + ec_send[0].deactivate_component(g_compo_send.rtc_ref) + ec_recv[0].deactivate_component(g_compo_recv.rtc_ref) - ## 6 ポート切断 - g_in_ports[g_port3].disconnect(g_conprof3.connector_id) - g_in_ports[g_port2].disconnect(g_conprof2.connector_id) - g_in_ports[g_port1].disconnect(g_conprof1.connector_id) + # 受信ファイル有無判定 + if os.path.isfile(g_diff_recv_file) == False: + fout = open(g_test_result_file, 'a') + message = g_mess_header + g_test_case + \ + str(case_no) + " " + g_test_cnt + str(i + 1) + g_mess_footer + message = message + g_check_message + fout.write(message + '\n') + fout.close() + print(message) + time.sleep(sleep_for_time) + continue - ## 5 ディアクティベート - ec_send[0].deactivate_component(g_compo_send.rtc_ref) - ec_recv[0].deactivate_component(g_compo_recv.rtc_ref) + # 7 送受信データ比較 + time.sleep(sleep_act_time) + bret = diff_file() - ## 受信ファイル有無判定 - if os.path.isfile(g_diff_recv_file) == False: + # 差分ファイルからテスト結果出力 fout = open(g_test_result_file, 'a') - message = g_mess_header + g_test_case + str(case_no) + " " + g_test_cnt + str(i+1) + g_mess_footer - message = message + g_check_message - fout.write(message + '\n') + message = g_mess_header + g_test_case + \ + str(case_no) + " " + g_test_cnt + str(i + 1) + g_mess_footer + # bret==True なら送受信データ一致 + if bret == True: + # テスト結果 OK + message = message + g_test_ok + print(message) + fout.write(message + '\n') + else: + # テスト結果 NG + message = message + g_test_ng + print(message) + message = message + g_test_ng_message + fout.write(message + '\n') + # 受信データをテスト結果ファイルへコピー + fin2 = open(g_diff_recv_file, 'r') + while(1): + s2 = fin2.readline() + if len(s2) == 0: + break + fout.write(s2) + fin2.close() fout.close() - print(message) - time.sleep(sleep_for_time) - continue - ## 7 送受信データ比較 - time.sleep(sleep_act_time) - bret = diff_file() + time.sleep(sleep_for_time) - ## 差分ファイルからテスト結果出力 + # -------------------------------------------------------------------- + # 接続タイプ:flush 方向:in->out 接続・切断・Activate・Deactivateテスト4 + # -------------------------------------------------------------------- + # ●注意:Activateを先に行っている為、受信データは途中からの内容になります。 + case_no = case_no + 1 fout = open(g_test_result_file, 'a') - message = g_mess_header + g_test_case + str(case_no) + " " + g_test_cnt + str(i+1) + g_mess_footer - # bret==True なら送受信データ一致 - if bret == True: - # テスト結果 OK - message = message + g_test_ok - print(message) - fout.write(message + '\n') - else: - # テスト結果 NG - message = message + g_test_ng - print(message) - message = message + g_test_ng_message - fout.write(message + '\n') - # 受信データをテスト結果ファイルへコピー - fin2 = open(g_diff_recv_file, 'r') - while(1): - s2 = fin2.readline() - if len(s2) == 0: - break - fout.write(s2) - fin2.close() + message = g_mess_header + g_test_case + str(case_no) + " " + message = message + \ + "Activate -> Connect(in->out, flush) -> send/recv -> Disconnect -> Deactivate" + message = message + g_mess_footer + fout.write(message + '\n') fout.close() + print(message) - time.sleep(sleep_for_time) + for i in range(loop_count): -##-------------------------------------------------------------------- -##-------------------------------------------------------------------- -## 接続タイプ:new 方向:out->in ポリシー:ALL 接続・切断テスト3 -##-------------------------------------------------------------------- -case_no = case_no + 1 -fout = open(g_test_result_file, 'a') -message = g_mess_header + g_test_case + str(case_no) + " " -message = message + "Connect(out->in, new,ALL) -> Disconnect" -message = message + g_mess_footer -fout.write(message + '\n') -fout.close() -print(message) + # 2 受信データファイル削除 + delete_recv_file() -for i in range(loop_count): + # 1 コネクタープロファイル設定 + make_connecter_profile("flush", "", 1) - ## 1 コネクタープロファイル設定 - make_connecter_profile("new", "ALL", 0) + # 4 アクティベート + ec_recv[0].activate_component(g_compo_recv.rtc_ref) + time.sleep(sleep_recv_act_time) + ec_send[0].activate_component(g_compo_send.rtc_ref) - ## 3 ポート接続 - # データポート1 TimedFloat - ret0 = g_out_ports[g_port1].connect(g_conprof1) + # 3 ポート接続 + # データポート1 TimedFloat + ret0 = g_out_ports[g_port1].connect(g_conprof1) - # データポート2 TimedFloatSeq - ret1 = g_out_ports[g_port2].connect(g_conprof2) + # データポート2 TimedFloatSeq + ret1 = g_out_ports[g_port2].connect(g_conprof2) - # サービスポート MyService - ret2 = g_out_ports[g_port3].connect(g_conprof3) + # サービスポート MyService + ret2 = g_out_ports[g_port3].connect(g_conprof3) - time.sleep(sleep_connect_time) + time.sleep(sleep_act_time) - ## 6 ポート切断 - g_in_ports[g_port3].disconnect(g_conprof3.connector_id) - g_in_ports[g_port2].disconnect(g_conprof2.connector_id) - g_in_ports[g_port1].disconnect(g_conprof1.connector_id) + # 6 ポート切断 + g_in_ports[g_port3].disconnect(g_conprof3.connector_id) + g_in_ports[g_port2].disconnect(g_conprof2.connector_id) + g_in_ports[g_port1].disconnect(g_conprof1.connector_id) + + # 5 ディアクティベート + ec_send[0].deactivate_component(g_compo_send.rtc_ref) + ec_recv[0].deactivate_component(g_compo_recv.rtc_ref) + + # 受信ファイル有無判定 + if os.path.isfile(g_diff_recv_file) == False: + fout = open(g_test_result_file, 'a') + message = g_mess_header + g_test_case + \ + str(case_no) + " " + g_test_cnt + str(i + 1) + g_mess_footer + message = message + g_check_message + fout.write(message + '\n') + fout.close() + print(message) + time.sleep(sleep_for_time) + continue - ## テスト結果出力 + # 7 送受信データ比較 + time.sleep(sleep_act_time) + bret = diff_file() + + # 差分ファイルからテスト結果出力 + fout = open(g_test_result_file, 'a') + message = g_mess_header + g_test_case + \ + str(case_no) + " " + g_test_cnt + str(i + 1) + g_mess_footer + # bret==True なら送受信データ一致 + if bret == True: + # テスト結果 OK + message = message + g_test_ok + print(message) + fout.write(message + '\n') + else: + # テスト結果 NG + message = message + g_test_ng + print(message) + message = message + g_test_ng_message + fout.write(message + '\n') + # 受信データをテスト結果ファイルへコピー + fin2 = open(g_diff_recv_file, 'r') + while(1): + s2 = fin2.readline() + if len(s2) == 0: + break + fout.write(s2) + fin2.close() + fout.close() + + time.sleep(sleep_for_time) + + # -------------------------------------------------------------------- + # -------------------------------------------------------------------- + # 接続タイプ:new 方向:out->in ポリシー:ALL 接続・切断テスト3 + # -------------------------------------------------------------------- + case_no = case_no + 1 fout = open(g_test_result_file, 'a') - message = g_mess_header + g_test_case + str(case_no) + " " + g_test_cnt + str(i+1) + g_mess_footer - message = message + g_test_ok - print(message) + message = g_mess_header + g_test_case + str(case_no) + " " + message = message + "Connect(out->in, new,ALL) -> Disconnect" + message = message + g_mess_footer fout.write(message + '\n') fout.close() + print(message) - time.sleep(sleep_for_time) + for i in range(loop_count): -##-------------------------------------------------------------------- -## 接続タイプ:new 方向:out->in ポリシー:FIFO 接続・切断テスト4 -##-------------------------------------------------------------------- -case_no = case_no + 1 -fout = open(g_test_result_file, 'a') -message = g_mess_header + g_test_case + str(case_no) + " " -message = message + "Connect(out->in, new,FIFO) -> Disconnect" -message = message + g_mess_footer -fout.write(message + '\n') -fout.close() -print(message) + # 1 コネクタープロファイル設定 + make_connecter_profile("new", "ALL", 0) -for i in range(loop_count): + # 3 ポート接続 + # データポート1 TimedFloat + ret0 = g_out_ports[g_port1].connect(g_conprof1) - ## 1 コネクタープロファイル設定 - make_connecter_profile("new", "FIFO", 0) + # データポート2 TimedFloatSeq + ret1 = g_out_ports[g_port2].connect(g_conprof2) - ## 3 ポート接続 - # データポート1 TimedFloat - ret0 = g_out_ports[g_port1].connect(g_conprof1) + # サービスポート MyService + ret2 = g_out_ports[g_port3].connect(g_conprof3) - # データポート2 TimedFloatSeq - ret1 = g_out_ports[g_port2].connect(g_conprof2) + time.sleep(sleep_connect_time) - # サービスポート MyService - ret2 = g_out_ports[g_port3].connect(g_conprof3) + # 6 ポート切断 + g_in_ports[g_port3].disconnect(g_conprof3.connector_id) + g_in_ports[g_port2].disconnect(g_conprof2.connector_id) + g_in_ports[g_port1].disconnect(g_conprof1.connector_id) - time.sleep(sleep_connect_time) + # テスト結果出力 + fout = open(g_test_result_file, 'a') + message = g_mess_header + g_test_case + \ + str(case_no) + " " + g_test_cnt + str(i + 1) + g_mess_footer + message = message + g_test_ok + print(message) + fout.write(message + '\n') + fout.close() - ## 6 ポート切断 - g_in_ports[g_port3].disconnect(g_conprof3.connector_id) - g_in_ports[g_port2].disconnect(g_conprof2.connector_id) - g_in_ports[g_port1].disconnect(g_conprof1.connector_id) + time.sleep(sleep_for_time) - ## テスト結果出力 + # -------------------------------------------------------------------- + # 接続タイプ:new 方向:out->in ポリシー:FIFO 接続・切断テスト4 + # -------------------------------------------------------------------- + case_no = case_no + 1 fout = open(g_test_result_file, 'a') - message = g_mess_header + g_test_case + str(case_no) + " " + g_test_cnt + str(i+1) + g_mess_footer - message = message + g_test_ok - print(message) + message = g_mess_header + g_test_case + str(case_no) + " " + message = message + "Connect(out->in, new,FIFO) -> Disconnect" + message = message + g_mess_footer fout.write(message + '\n') fout.close() + print(message) - time.sleep(sleep_for_time) + for i in range(loop_count): -##-------------------------------------------------------------------- -## 接続タイプ:new 方向:out->in ポリシー:NEW 接続・切断テスト6 -##-------------------------------------------------------------------- -case_no = case_no + 1 -fout = open(g_test_result_file, 'a') -message = g_mess_header + g_test_case + str(case_no) + " " -message = message + "Connect(out->in, new,NEW) -> Disconnect" -message = message + g_mess_footer -fout.write(message + '\n') -fout.close() -print(message) + # 1 コネクタープロファイル設定 + make_connecter_profile("new", "FIFO", 0) -for i in range(loop_count): + # 3 ポート接続 + # データポート1 TimedFloat + ret0 = g_out_ports[g_port1].connect(g_conprof1) - ## 1 コネクタープロファイル設定 - make_connecter_profile("new", "NEW", 0) + # データポート2 TimedFloatSeq + ret1 = g_out_ports[g_port2].connect(g_conprof2) - ## 3 ポート接続 - # データポート1 TimedFloat - ret0 = g_out_ports[g_port1].connect(g_conprof1) + # サービスポート MyService + ret2 = g_out_ports[g_port3].connect(g_conprof3) - # データポート2 TimedFloatSeq - ret1 = g_out_ports[g_port2].connect(g_conprof2) + time.sleep(sleep_connect_time) - # サービスポート MyService - ret2 = g_out_ports[g_port3].connect(g_conprof3) + # 6 ポート切断 + g_in_ports[g_port3].disconnect(g_conprof3.connector_id) + g_in_ports[g_port2].disconnect(g_conprof2.connector_id) + g_in_ports[g_port1].disconnect(g_conprof1.connector_id) - time.sleep(sleep_connect_time) + # テスト結果出力 + fout = open(g_test_result_file, 'a') + message = g_mess_header + g_test_case + \ + str(case_no) + " " + g_test_cnt + str(i + 1) + g_mess_footer + message = message + g_test_ok + print(message) + fout.write(message + '\n') + fout.close() - ## 6 ポート切断 - g_in_ports[g_port3].disconnect(g_conprof3.connector_id) - g_in_ports[g_port2].disconnect(g_conprof2.connector_id) - g_in_ports[g_port1].disconnect(g_conprof1.connector_id) + time.sleep(sleep_for_time) - ## テスト結果出力 + # -------------------------------------------------------------------- + # 接続タイプ:new 方向:out->in ポリシー:NEW 接続・切断テスト6 + # -------------------------------------------------------------------- + case_no = case_no + 1 fout = open(g_test_result_file, 'a') - message = g_mess_header + g_test_case + str(case_no) + " " + g_test_cnt + str(i+1) + g_mess_footer - message = message + g_test_ok - print(message) + message = g_mess_header + g_test_case + str(case_no) + " " + message = message + "Connect(out->in, new,NEW) -> Disconnect" + message = message + g_mess_footer fout.write(message + '\n') fout.close() + print(message) - time.sleep(sleep_for_time) + for i in range(loop_count): -##-------------------------------------------------------------------- -## 接続タイプ:new 方向:out->in ポリシー:SKIP 接続・切断テスト5 -##-------------------------------------------------------------------- -case_no = case_no + 1 -fout = open(g_test_result_file, 'a') -message = g_mess_header + g_test_case + str(case_no) + " " -message = message + "Connect(out->in, new,SKIP) -> Disconnect" -message = message + g_mess_footer -fout.write(message + '\n') -fout.close() -print(message) + # 1 コネクタープロファイル設定 + make_connecter_profile("new", "NEW", 0) -for i in range(loop_count): + # 3 ポート接続 + # データポート1 TimedFloat + ret0 = g_out_ports[g_port1].connect(g_conprof1) - ## 1 コネクタープロファイル設定 - make_connecter_profile("new", "SKIP", 0) + # データポート2 TimedFloatSeq + ret1 = g_out_ports[g_port2].connect(g_conprof2) - ## 3 ポート接続 - # データポート1 TimedFloat - ret0 = g_out_ports[g_port1].connect(g_conprof1) + # サービスポート MyService + ret2 = g_out_ports[g_port3].connect(g_conprof3) - # データポート2 TimedFloatSeq - ret1 = g_out_ports[g_port2].connect(g_conprof2) + time.sleep(sleep_connect_time) - # サービスポート MyService - ret2 = g_out_ports[g_port3].connect(g_conprof3) + # 6 ポート切断 + g_in_ports[g_port3].disconnect(g_conprof3.connector_id) + g_in_ports[g_port2].disconnect(g_conprof2.connector_id) + g_in_ports[g_port1].disconnect(g_conprof1.connector_id) - time.sleep(sleep_connect_time) + # テスト結果出力 + fout = open(g_test_result_file, 'a') + message = g_mess_header + g_test_case + \ + str(case_no) + " " + g_test_cnt + str(i + 1) + g_mess_footer + message = message + g_test_ok + print(message) + fout.write(message + '\n') + fout.close() - ## 6 ポート切断 - g_in_ports[g_port3].disconnect(g_conprof3.connector_id) - g_in_ports[g_port2].disconnect(g_conprof2.connector_id) - g_in_ports[g_port1].disconnect(g_conprof1.connector_id) + time.sleep(sleep_for_time) - ## テスト結果出力 + # -------------------------------------------------------------------- + # 接続タイプ:new 方向:out->in ポリシー:SKIP 接続・切断テスト5 + # -------------------------------------------------------------------- + case_no = case_no + 1 fout = open(g_test_result_file, 'a') - message = g_mess_header + g_test_case + str(case_no) + " " + g_test_cnt + str(i+1) + g_mess_footer - message = message + g_test_ok - print(message) + message = g_mess_header + g_test_case + str(case_no) + " " + message = message + "Connect(out->in, new,SKIP) -> Disconnect" + message = message + g_mess_footer fout.write(message + '\n') fout.close() + print(message) - time.sleep(sleep_for_time) + for i in range(loop_count): -##-------------------------------------------------------------------- -## 接続タイプ:new 方向:in->out ポリシー:ALL 接続・切断テスト3 -##-------------------------------------------------------------------- -case_no = case_no + 1 -fout = open(g_test_result_file, 'a') -message = g_mess_header + g_test_case + str(case_no) + " " -message = message + "Connect(in->out, new,ALL) -> Disconnect" -message = message + g_mess_footer -fout.write(message + '\n') -fout.close() -print(message) + # 1 コネクタープロファイル設定 + make_connecter_profile("new", "SKIP", 0) -for i in range(loop_count): + # 3 ポート接続 + # データポート1 TimedFloat + ret0 = g_out_ports[g_port1].connect(g_conprof1) - ## 1 コネクタープロファイル設定 - make_connecter_profile("new", "ALL", 1) + # データポート2 TimedFloatSeq + ret1 = g_out_ports[g_port2].connect(g_conprof2) - ## 3 ポート接続 - # データポート1 TimedFloat - ret0 = g_out_ports[g_port1].connect(g_conprof1) + # サービスポート MyService + ret2 = g_out_ports[g_port3].connect(g_conprof3) - # データポート2 TimedFloatSeq - ret1 = g_out_ports[g_port2].connect(g_conprof2) + time.sleep(sleep_connect_time) - # サービスポート MyService - ret2 = g_out_ports[g_port3].connect(g_conprof3) + # 6 ポート切断 + g_in_ports[g_port3].disconnect(g_conprof3.connector_id) + g_in_ports[g_port2].disconnect(g_conprof2.connector_id) + g_in_ports[g_port1].disconnect(g_conprof1.connector_id) - time.sleep(sleep_connect_time) + # テスト結果出力 + fout = open(g_test_result_file, 'a') + message = g_mess_header + g_test_case + \ + str(case_no) + " " + g_test_cnt + str(i + 1) + g_mess_footer + message = message + g_test_ok + print(message) + fout.write(message + '\n') + fout.close() - ## 6 ポート切断 - g_in_ports[g_port3].disconnect(g_conprof3.connector_id) - g_in_ports[g_port2].disconnect(g_conprof2.connector_id) - g_in_ports[g_port1].disconnect(g_conprof1.connector_id) + time.sleep(sleep_for_time) - ## テスト結果出力 + # -------------------------------------------------------------------- + # 接続タイプ:new 方向:in->out ポリシー:ALL 接続・切断テスト3 + # -------------------------------------------------------------------- + case_no = case_no + 1 fout = open(g_test_result_file, 'a') - message = g_mess_header + g_test_case + str(case_no) + " " + g_test_cnt + str(i+1) + g_mess_footer - message = message + g_test_ok - print(message) + message = g_mess_header + g_test_case + str(case_no) + " " + message = message + "Connect(in->out, new,ALL) -> Disconnect" + message = message + g_mess_footer fout.write(message + '\n') fout.close() + print(message) - time.sleep(sleep_for_time) + for i in range(loop_count): -##-------------------------------------------------------------------- -## 接続タイプ:new 方向:in->out ポリシー:FIFO 接続・切断テスト4 -##-------------------------------------------------------------------- -case_no = case_no + 1 -fout = open(g_test_result_file, 'a') -message = g_mess_header + g_test_case + str(case_no) + " " -message = message + "Connect(in->out, new,FIFO) -> Disconnect" -message = message + g_mess_footer -fout.write(message + '\n') -fout.close() -print(message) + # 1 コネクタープロファイル設定 + make_connecter_profile("new", "ALL", 1) -for i in range(loop_count): + # 3 ポート接続 + # データポート1 TimedFloat + ret0 = g_out_ports[g_port1].connect(g_conprof1) - ## 1 コネクタープロファイル設定 - make_connecter_profile("new", "FIFO", 1) + # データポート2 TimedFloatSeq + ret1 = g_out_ports[g_port2].connect(g_conprof2) - ## 3 ポート接続 - # データポート1 TimedFloat - ret0 = g_out_ports[g_port1].connect(g_conprof1) + # サービスポート MyService + ret2 = g_out_ports[g_port3].connect(g_conprof3) - # データポート2 TimedFloatSeq - ret1 = g_out_ports[g_port2].connect(g_conprof2) + time.sleep(sleep_connect_time) - # サービスポート MyService - ret2 = g_out_ports[g_port3].connect(g_conprof3) + # 6 ポート切断 + g_in_ports[g_port3].disconnect(g_conprof3.connector_id) + g_in_ports[g_port2].disconnect(g_conprof2.connector_id) + g_in_ports[g_port1].disconnect(g_conprof1.connector_id) - time.sleep(sleep_connect_time) + # テスト結果出力 + fout = open(g_test_result_file, 'a') + message = g_mess_header + g_test_case + \ + str(case_no) + " " + g_test_cnt + str(i + 1) + g_mess_footer + message = message + g_test_ok + print(message) + fout.write(message + '\n') + fout.close() - ## 6 ポート切断 - g_in_ports[g_port3].disconnect(g_conprof3.connector_id) - g_in_ports[g_port2].disconnect(g_conprof2.connector_id) - g_in_ports[g_port1].disconnect(g_conprof1.connector_id) + time.sleep(sleep_for_time) - ## テスト結果出力 + # -------------------------------------------------------------------- + # 接続タイプ:new 方向:in->out ポリシー:FIFO 接続・切断テスト4 + # -------------------------------------------------------------------- + case_no = case_no + 1 fout = open(g_test_result_file, 'a') - message = g_mess_header + g_test_case + str(case_no) + " " + g_test_cnt + str(i+1) + g_mess_footer - message = message + g_test_ok - print(message) + message = g_mess_header + g_test_case + str(case_no) + " " + message = message + "Connect(in->out, new,FIFO) -> Disconnect" + message = message + g_mess_footer fout.write(message + '\n') fout.close() + print(message) - time.sleep(sleep_for_time) + for i in range(loop_count): -##-------------------------------------------------------------------- -## 接続タイプ:new 方向:in->out ポリシー:NEW 接続・切断テスト6 -##-------------------------------------------------------------------- -case_no = case_no + 1 -fout = open(g_test_result_file, 'a') -message = g_mess_header + g_test_case + str(case_no) + " " -message = message + "Connect(in->out, new,NEW) -> Disconnect" -message = message + g_mess_footer -fout.write(message + '\n') -fout.close() -print(message) + # 1 コネクタープロファイル設定 + make_connecter_profile("new", "FIFO", 1) -for i in range(loop_count): + # 3 ポート接続 + # データポート1 TimedFloat + ret0 = g_out_ports[g_port1].connect(g_conprof1) - ## 1 コネクタープロファイル設定 - make_connecter_profile("new", "NEW", 1) + # データポート2 TimedFloatSeq + ret1 = g_out_ports[g_port2].connect(g_conprof2) - ## 3 ポート接続 - # データポート1 TimedFloat - ret0 = g_out_ports[g_port1].connect(g_conprof1) + # サービスポート MyService + ret2 = g_out_ports[g_port3].connect(g_conprof3) - # データポート2 TimedFloatSeq - ret1 = g_out_ports[g_port2].connect(g_conprof2) + time.sleep(sleep_connect_time) - # サービスポート MyService - ret2 = g_out_ports[g_port3].connect(g_conprof3) + # 6 ポート切断 + g_in_ports[g_port3].disconnect(g_conprof3.connector_id) + g_in_ports[g_port2].disconnect(g_conprof2.connector_id) + g_in_ports[g_port1].disconnect(g_conprof1.connector_id) - time.sleep(sleep_connect_time) + # テスト結果出力 + fout = open(g_test_result_file, 'a') + message = g_mess_header + g_test_case + \ + str(case_no) + " " + g_test_cnt + str(i + 1) + g_mess_footer + message = message + g_test_ok + print(message) + fout.write(message + '\n') + fout.close() - ## 6 ポート切断 - g_in_ports[g_port3].disconnect(g_conprof3.connector_id) - g_in_ports[g_port2].disconnect(g_conprof2.connector_id) - g_in_ports[g_port1].disconnect(g_conprof1.connector_id) + time.sleep(sleep_for_time) - ## テスト結果出力 + # -------------------------------------------------------------------- + # 接続タイプ:new 方向:in->out ポリシー:NEW 接続・切断テスト6 + # -------------------------------------------------------------------- + case_no = case_no + 1 fout = open(g_test_result_file, 'a') - message = g_mess_header + g_test_case + str(case_no) + " " + g_test_cnt + str(i+1) + g_mess_footer - message = message + g_test_ok - print(message) + message = g_mess_header + g_test_case + str(case_no) + " " + message = message + "Connect(in->out, new,NEW) -> Disconnect" + message = message + g_mess_footer fout.write(message + '\n') fout.close() + print(message) - time.sleep(sleep_for_time) + for i in range(loop_count): -##-------------------------------------------------------------------- -## 接続タイプ:new 方向:in->out ポリシー:SKIP 接続・切断テスト5 -##-------------------------------------------------------------------- -case_no = case_no + 1 -fout = open(g_test_result_file, 'a') -message = g_mess_header + g_test_case + str(case_no) + " " -message = message + "Connect(in->out, new,SKIP) -> Disconnect" -message = message + g_mess_footer -fout.write(message + '\n') -fout.close() -print(message) + # 1 コネクタープロファイル設定 + make_connecter_profile("new", "NEW", 1) -for i in range(loop_count): + # 3 ポート接続 + # データポート1 TimedFloat + ret0 = g_out_ports[g_port1].connect(g_conprof1) - ## 1 コネクタープロファイル設定 - make_connecter_profile("new", "SKIP", 1) + # データポート2 TimedFloatSeq + ret1 = g_out_ports[g_port2].connect(g_conprof2) - ## 3 ポート接続 - # データポート1 TimedFloat - ret0 = g_out_ports[g_port1].connect(g_conprof1) + # サービスポート MyService + ret2 = g_out_ports[g_port3].connect(g_conprof3) - # データポート2 TimedFloatSeq - ret1 = g_out_ports[g_port2].connect(g_conprof2) + time.sleep(sleep_connect_time) - # サービスポート MyService - ret2 = g_out_ports[g_port3].connect(g_conprof3) + # 6 ポート切断 + g_in_ports[g_port3].disconnect(g_conprof3.connector_id) + g_in_ports[g_port2].disconnect(g_conprof2.connector_id) + g_in_ports[g_port1].disconnect(g_conprof1.connector_id) - time.sleep(sleep_connect_time) + # テスト結果出力 + fout = open(g_test_result_file, 'a') + message = g_mess_header + g_test_case + \ + str(case_no) + " " + g_test_cnt + str(i + 1) + g_mess_footer + message = message + g_test_ok + print(message) + fout.write(message + '\n') + fout.close() - ## 6 ポート切断 - g_in_ports[g_port3].disconnect(g_conprof3.connector_id) - g_in_ports[g_port2].disconnect(g_conprof2.connector_id) - g_in_ports[g_port1].disconnect(g_conprof1.connector_id) + time.sleep(sleep_for_time) - ## テスト結果出力 + # -------------------------------------------------------------------- + # 接続タイプ:new 方向:in->out ポリシー:SKIP 接続・切断テスト5 + # -------------------------------------------------------------------- + case_no = case_no + 1 fout = open(g_test_result_file, 'a') - message = g_mess_header + g_test_case + str(case_no) + " " + g_test_cnt + str(i+1) + g_mess_footer - message = message + g_test_ok + message = g_mess_header + g_test_case + str(case_no) + " " + message = message + "Connect(in->out, new,SKIP) -> Disconnect" + message = message + g_mess_footer + fout.write(message + '\n') + fout.close() print(message) + + for i in range(loop_count): + + # 1 コネクタープロファイル設定 + make_connecter_profile("new", "SKIP", 1) + + # 3 ポート接続 + # データポート1 TimedFloat + ret0 = g_out_ports[g_port1].connect(g_conprof1) + + # データポート2 TimedFloatSeq + ret1 = g_out_ports[g_port2].connect(g_conprof2) + + # サービスポート MyService + ret2 = g_out_ports[g_port3].connect(g_conprof3) + + time.sleep(sleep_connect_time) + + # 6 ポート切断 + g_in_ports[g_port3].disconnect(g_conprof3.connector_id) + g_in_ports[g_port2].disconnect(g_conprof2.connector_id) + g_in_ports[g_port1].disconnect(g_conprof1.connector_id) + + # テスト結果出力 + fout = open(g_test_result_file, 'a') + message = g_mess_header + g_test_case + \ + str(case_no) + " " + g_test_cnt + str(i + 1) + g_mess_footer + message = message + g_test_ok + print(message) + fout.write(message + '\n') + fout.close() + + time.sleep(sleep_for_time) + + # -------------------------------------------------------------------- + # 接続タイプ:new 方向:out->in ポリシー:ALL Activate・Deactivateテスト2 + # -------------------------------------------------------------------- + case_no = case_no + 1 + fout = open(g_test_result_file, 'a') + message = g_mess_header + g_test_case + str(case_no) + " " + message = message + \ + "Connecting(out->in, new,ALL), Activate -> send/recv -> Deactivate" + message = message + g_mess_footer fout.write(message + '\n') fout.close() + print(message) - time.sleep(sleep_for_time) + # 1 コネクタープロファイル設定 + make_connecter_profile("new", "ALL", 0) -##-------------------------------------------------------------------- -## 接続タイプ:new 方向:out->in ポリシー:ALL Activate・Deactivateテスト2 -##-------------------------------------------------------------------- -case_no = case_no + 1 -fout = open(g_test_result_file, 'a') -message = g_mess_header + g_test_case + str(case_no) + " " -message = message + "Connecting(out->in, new,ALL), Activate -> send/recv -> Deactivate" -message = message + g_mess_footer -fout.write(message + '\n') -fout.close() -print(message) + # 3 ポート接続 + # データポート1 TimedFloat + ret0 = g_out_ports[g_port1].connect(g_conprof1) -## 1 コネクタープロファイル設定 -make_connecter_profile("new", "ALL", 0) + # データポート2 TimedFloatSeq + ret1 = g_out_ports[g_port2].connect(g_conprof2) -## 3 ポート接続 -# データポート1 TimedFloat -ret0 = g_out_ports[g_port1].connect(g_conprof1) + # サービスポート MyService + ret2 = g_out_ports[g_port3].connect(g_conprof3) -# データポート2 TimedFloatSeq -ret1 = g_out_ports[g_port2].connect(g_conprof2) + for i in range(loop_count): -# サービスポート MyService -ret2 = g_out_ports[g_port3].connect(g_conprof3) + # 2 受信データファイル削除 + delete_recv_file() -for i in range(loop_count): + # 4 アクティベート + ec_recv[0].activate_component(g_compo_recv.rtc_ref) + time.sleep(sleep_recv_act_time) + ec_send[0].activate_component(g_compo_send.rtc_ref) - ## 2 受信データファイル削除 - delete_recv_file() + time.sleep(sleep_act_time) - ## 4 アクティベート - ec_recv[0].activate_component(g_compo_recv.rtc_ref) - time.sleep(sleep_recv_act_time) - ec_send[0].activate_component(g_compo_send.rtc_ref) + # 5 ディアクティベート + ec_send[0].deactivate_component(g_compo_send.rtc_ref) + ec_recv[0].deactivate_component(g_compo_recv.rtc_ref) - time.sleep(sleep_act_time) + # 受信ファイル有無判定 + if os.path.isfile(g_diff_recv_file) == False: + fout = open(g_test_result_file, 'a') + message = g_mess_header + g_test_case + \ + str(case_no) + " " + g_test_cnt + str(i + 1) + g_mess_footer + message = message + g_check_message + fout.write(message + '\n') + fout.close() + print(message) + time.sleep(sleep_for_time) + continue - ## 5 ディアクティベート - ec_send[0].deactivate_component(g_compo_send.rtc_ref) - ec_recv[0].deactivate_component(g_compo_recv.rtc_ref) + # 7 送受信データ比較 + time.sleep(sleep_act_time) + bret = diff_file() - ## 受信ファイル有無判定 - if os.path.isfile(g_diff_recv_file) == False: + # 差分ファイルからテスト結果出力 fout = open(g_test_result_file, 'a') - message = g_mess_header + g_test_case + str(case_no) + " " + g_test_cnt + str(i+1) + g_mess_footer - message = message + g_check_message - fout.write(message + '\n') + message = g_mess_header + g_test_case + \ + str(case_no) + " " + g_test_cnt + str(i + 1) + g_mess_footer + # bret==True なら送受信データ一致 + if bret == True: + # テスト結果 OK + message = message + g_test_ok + print(message) + fout.write(message + '\n') + else: + # テスト結果 NG + message = message + g_test_ng + print(message) + message = message + g_test_ng_message + fout.write(message + '\n') + # 受信データをテスト結果ファイルへコピー + fin2 = open(g_diff_recv_file, 'r') + while(1): + s2 = fin2.readline() + if len(s2) == 0: + break + fout.write(s2) + fin2.close() fout.close() - print(message) + time.sleep(sleep_for_time) - continue - ## 7 送受信データ比較 - time.sleep(sleep_act_time) - bret = diff_file() + # 6 ポート切断 + g_in_ports[g_port3].disconnect(g_conprof3.connector_id) + g_in_ports[g_port2].disconnect(g_conprof2.connector_id) + g_in_ports[g_port1].disconnect(g_conprof1.connector_id) - ## 差分ファイルからテスト結果出力 + # -------------------------------------------------------------------- + # 接続タイプ:new 方向:out->in ポリシー:FIFO Activate・Deactivateテスト3 + # -------------------------------------------------------------------- + case_no = case_no + 1 fout = open(g_test_result_file, 'a') - message = g_mess_header + g_test_case + str(case_no) + " " + g_test_cnt + str(i+1) + g_mess_footer - # bret==True なら送受信データ一致 - if bret == True: - # テスト結果 OK - message = message + g_test_ok - print(message) - fout.write(message + '\n') - else: - # テスト結果 NG - message = message + g_test_ng - print(message) - message = message + g_test_ng_message - fout.write(message + '\n') - # 受信データをテスト結果ファイルへコピー - fin2 = open(g_diff_recv_file, 'r') - while(1): - s2 = fin2.readline() - if len(s2) == 0: - break - fout.write(s2) - fin2.close() + message = g_mess_header + g_test_case + str(case_no) + " " + message = message + \ + "Connecting(out->in, new,FIFO), Activate -> send/recv -> Deactivate" + message = message + g_mess_footer + fout.write(message + '\n') fout.close() + print(message) - time.sleep(sleep_for_time) - -## 6 ポート切断 -g_in_ports[g_port3].disconnect(g_conprof3.connector_id) -g_in_ports[g_port2].disconnect(g_conprof2.connector_id) -g_in_ports[g_port1].disconnect(g_conprof1.connector_id) + # 1 コネクタープロファイル設定 + make_connecter_profile("new", "FIFO", 0) -##-------------------------------------------------------------------- -## 接続タイプ:new 方向:out->in ポリシー:FIFO Activate・Deactivateテスト3 -##-------------------------------------------------------------------- -case_no = case_no + 1 -fout = open(g_test_result_file, 'a') -message = g_mess_header + g_test_case + str(case_no) + " " -message = message + "Connecting(out->in, new,FIFO), Activate -> send/recv -> Deactivate" -message = message + g_mess_footer -fout.write(message + '\n') -fout.close() -print(message) + # 3 ポート接続 + # データポート1 TimedFloat + ret0 = g_out_ports[g_port1].connect(g_conprof1) -## 1 コネクタープロファイル設定 -make_connecter_profile("new", "FIFO", 0) + # データポート2 TimedFloatSeq + ret1 = g_out_ports[g_port2].connect(g_conprof2) -## 3 ポート接続 -# データポート1 TimedFloat -ret0 = g_out_ports[g_port1].connect(g_conprof1) + # サービスポート MyService + ret2 = g_out_ports[g_port3].connect(g_conprof3) -# データポート2 TimedFloatSeq -ret1 = g_out_ports[g_port2].connect(g_conprof2) + for i in range(loop_count): -# サービスポート MyService -ret2 = g_out_ports[g_port3].connect(g_conprof3) + # 2 受信データファイル削除 + delete_recv_file() -for i in range(loop_count): + # 4 アクティベート + ec_recv[0].activate_component(g_compo_recv.rtc_ref) + time.sleep(sleep_recv_act_time) + ec_send[0].activate_component(g_compo_send.rtc_ref) - ## 2 受信データファイル削除 - delete_recv_file() + time.sleep(sleep_act_time) - ## 4 アクティベート - ec_recv[0].activate_component(g_compo_recv.rtc_ref) - time.sleep(sleep_recv_act_time) - ec_send[0].activate_component(g_compo_send.rtc_ref) + # 5 ディアクティベート + ec_send[0].deactivate_component(g_compo_send.rtc_ref) + ec_recv[0].deactivate_component(g_compo_recv.rtc_ref) - time.sleep(sleep_act_time) + # 受信ファイル有無判定 + if os.path.isfile(g_diff_recv_file) == False: + fout = open(g_test_result_file, 'a') + message = g_mess_header + g_test_case + \ + str(case_no) + " " + g_test_cnt + str(i + 1) + g_mess_footer + message = message + g_check_message + fout.write(message + '\n') + fout.close() + print(message) + time.sleep(sleep_for_time) + continue - ## 5 ディアクティベート - ec_send[0].deactivate_component(g_compo_send.rtc_ref) - ec_recv[0].deactivate_component(g_compo_recv.rtc_ref) + # 7 送受信データ比較 + time.sleep(sleep_act_time) + bret = diff_file() - ## 受信ファイル有無判定 - if os.path.isfile(g_diff_recv_file) == False: + # 差分ファイルからテスト結果出力 fout = open(g_test_result_file, 'a') - message = g_mess_header + g_test_case + str(case_no) + " " + g_test_cnt + str(i+1) + g_mess_footer - message = message + g_check_message - fout.write(message + '\n') + message = g_mess_header + g_test_case + \ + str(case_no) + " " + g_test_cnt + str(i + 1) + g_mess_footer + # bret==True なら送受信データ一致 + if bret == True: + # テスト結果 OK + message = message + g_test_ok + print(message) + fout.write(message + '\n') + else: + # テスト結果 NG + message = message + g_test_ng + print(message) + message = message + g_test_ng_message + fout.write(message + '\n') + # 受信データをテスト結果ファイルへコピー + fin2 = open(g_diff_recv_file, 'r') + while(1): + s2 = fin2.readline() + if len(s2) == 0: + break + fout.write(s2) + fin2.close() fout.close() - print(message) + time.sleep(sleep_for_time) - continue - ## 7 送受信データ比較 - time.sleep(sleep_act_time) - bret = diff_file() + # 6 ポート切断 + g_in_ports[g_port3].disconnect(g_conprof3.connector_id) + g_in_ports[g_port2].disconnect(g_conprof2.connector_id) + g_in_ports[g_port1].disconnect(g_conprof1.connector_id) - ## 差分ファイルからテスト結果出力 + # -------------------------------------------------------------------- + # 接続タイプ:new 方向:out->in ポリシー:NEW Activate・Deactivateテスト5 + # -------------------------------------------------------------------- + case_no = case_no + 1 fout = open(g_test_result_file, 'a') - message = g_mess_header + g_test_case + str(case_no) + " " + g_test_cnt + str(i+1) + g_mess_footer - # bret==True なら送受信データ一致 - if bret == True: - # テスト結果 OK - message = message + g_test_ok - print(message) - fout.write(message + '\n') - else: - # テスト結果 NG - message = message + g_test_ng - print(message) - message = message + g_test_ng_message - fout.write(message + '\n') - # 受信データをテスト結果ファイルへコピー - fin2 = open(g_diff_recv_file, 'r') - while(1): - s2 = fin2.readline() - if len(s2) == 0: - break - fout.write(s2) - fin2.close() + message = g_mess_header + g_test_case + str(case_no) + " " + message = message + \ + "Connecting(out->in, new,NEW), Activate -> send/recv -> Deactivate" + message = message + g_mess_footer + fout.write(message + '\n') fout.close() + print(message) - time.sleep(sleep_for_time) - -## 6 ポート切断 -g_in_ports[g_port3].disconnect(g_conprof3.connector_id) -g_in_ports[g_port2].disconnect(g_conprof2.connector_id) -g_in_ports[g_port1].disconnect(g_conprof1.connector_id) + # 1 コネクタープロファイル設定 + make_connecter_profile("new", "NEW", 0) -##-------------------------------------------------------------------- -## 接続タイプ:new 方向:out->in ポリシー:NEW Activate・Deactivateテスト5 -##-------------------------------------------------------------------- -case_no = case_no + 1 -fout = open(g_test_result_file, 'a') -message = g_mess_header + g_test_case + str(case_no) + " " -message = message + "Connecting(out->in, new,NEW), Activate -> send/recv -> Deactivate" -message = message + g_mess_footer -fout.write(message + '\n') -fout.close() -print(message) + # 3 ポート接続 + # データポート1 TimedFloat + ret0 = g_out_ports[g_port1].connect(g_conprof1) -## 1 コネクタープロファイル設定 -make_connecter_profile("new", "NEW", 0) + # データポート2 TimedFloatSeq + ret1 = g_out_ports[g_port2].connect(g_conprof2) -## 3 ポート接続 -# データポート1 TimedFloat -ret0 = g_out_ports[g_port1].connect(g_conprof1) + # サービスポート MyService + ret2 = g_out_ports[g_port3].connect(g_conprof3) -# データポート2 TimedFloatSeq -ret1 = g_out_ports[g_port2].connect(g_conprof2) + for i in range(loop_count): -# サービスポート MyService -ret2 = g_out_ports[g_port3].connect(g_conprof3) + # 2 受信データファイル削除 + delete_recv_file() -for i in range(loop_count): + # 4 アクティベート + ec_recv[0].activate_component(g_compo_recv.rtc_ref) + time.sleep(sleep_recv_act_time) + ec_send[0].activate_component(g_compo_send.rtc_ref) - ## 2 受信データファイル削除 - delete_recv_file() + time.sleep(sleep_act_time) - ## 4 アクティベート - ec_recv[0].activate_component(g_compo_recv.rtc_ref) - time.sleep(sleep_recv_act_time) - ec_send[0].activate_component(g_compo_send.rtc_ref) + # 5 ディアクティベート + ec_send[0].deactivate_component(g_compo_send.rtc_ref) + ec_recv[0].deactivate_component(g_compo_recv.rtc_ref) - time.sleep(sleep_act_time) + # 受信ファイル有無判定 + if os.path.isfile(g_diff_recv_file) == False: + fout = open(g_test_result_file, 'a') + message = g_mess_header + g_test_case + \ + str(case_no) + " " + g_test_cnt + str(i + 1) + g_mess_footer + message = message + g_check_message + fout.write(message + '\n') + fout.close() + print(message) + time.sleep(sleep_for_time) + continue - ## 5 ディアクティベート - ec_send[0].deactivate_component(g_compo_send.rtc_ref) - ec_recv[0].deactivate_component(g_compo_recv.rtc_ref) + # 7 送受信データ比較 + time.sleep(sleep_act_time) + bret = diff_file() - ## 受信ファイル有無判定 - if os.path.isfile(g_diff_recv_file) == False: + # 差分ファイルからテスト結果出力 fout = open(g_test_result_file, 'a') - message = g_mess_header + g_test_case + str(case_no) + " " + g_test_cnt + str(i+1) + g_mess_footer - message = message + g_check_message - fout.write(message + '\n') + message = g_mess_header + g_test_case + \ + str(case_no) + " " + g_test_cnt + str(i + 1) + g_mess_footer + # bret==True なら送受信データ一致 + if bret == True: + # テスト結果 OK + message = message + g_test_ok + print(message) + fout.write(message + '\n') + else: + # テスト結果 NG + message = message + g_test_ng + print(message) + message = message + g_test_ng_message + fout.write(message + '\n') + # 受信データをテスト結果ファイルへコピー + fin2 = open(g_diff_recv_file, 'r') + while(1): + s2 = fin2.readline() + if len(s2) == 0: + break + fout.write(s2) + fin2.close() fout.close() - print(message) + time.sleep(sleep_for_time) - continue - ## 7 送受信データ比較 - time.sleep(sleep_act_time) - bret = diff_file() + # 6 ポート切断 + g_in_ports[g_port3].disconnect(g_conprof3.connector_id) + g_in_ports[g_port2].disconnect(g_conprof2.connector_id) + g_in_ports[g_port1].disconnect(g_conprof1.connector_id) - ## 差分ファイルからテスト結果出力 + # -------------------------------------------------------------------- + # 接続タイプ:new 方向:out->in ポリシー:SKIP Activate・Deactivateテスト4 + # -------------------------------------------------------------------- + case_no = case_no + 1 fout = open(g_test_result_file, 'a') - message = g_mess_header + g_test_case + str(case_no) + " " + g_test_cnt + str(i+1) + g_mess_footer - # bret==True なら送受信データ一致 - if bret == True: - # テスト結果 OK - message = message + g_test_ok - print(message) - fout.write(message + '\n') - else: - # テスト結果 NG - message = message + g_test_ng - print(message) - message = message + g_test_ng_message - fout.write(message + '\n') - # 受信データをテスト結果ファイルへコピー - fin2 = open(g_diff_recv_file, 'r') - while(1): - s2 = fin2.readline() - if len(s2) == 0: - break - fout.write(s2) - fin2.close() + message = g_mess_header + g_test_case + str(case_no) + " " + message = message + \ + "Connecting(out->in, new,SKIP), Activate -> send/recv -> Deactivate" + message = message + g_mess_footer + fout.write(message + '\n') fout.close() + print(message) - time.sleep(sleep_for_time) - -## 6 ポート切断 -g_in_ports[g_port3].disconnect(g_conprof3.connector_id) -g_in_ports[g_port2].disconnect(g_conprof2.connector_id) -g_in_ports[g_port1].disconnect(g_conprof1.connector_id) + # 1 コネクタープロファイル設定 + make_connecter_profile("new", "SKIP", 0) -##-------------------------------------------------------------------- -## 接続タイプ:new 方向:out->in ポリシー:SKIP Activate・Deactivateテスト4 -##-------------------------------------------------------------------- -case_no = case_no + 1 -fout = open(g_test_result_file, 'a') -message = g_mess_header + g_test_case + str(case_no) + " " -message = message + "Connecting(out->in, new,SKIP), Activate -> send/recv -> Deactivate" -message = message + g_mess_footer -fout.write(message + '\n') -fout.close() -print(message) + # 3 ポート接続 + # データポート1 TimedFloat + ret0 = g_out_ports[g_port1].connect(g_conprof1) -## 1 コネクタープロファイル設定 -make_connecter_profile("new", "SKIP", 0) + # データポート2 TimedFloatSeq + ret1 = g_out_ports[g_port2].connect(g_conprof2) -## 3 ポート接続 -# データポート1 TimedFloat -ret0 = g_out_ports[g_port1].connect(g_conprof1) + # サービスポート MyService + ret2 = g_out_ports[g_port3].connect(g_conprof3) -# データポート2 TimedFloatSeq -ret1 = g_out_ports[g_port2].connect(g_conprof2) + for i in range(loop_count): -# サービスポート MyService -ret2 = g_out_ports[g_port3].connect(g_conprof3) + # 2 受信データファイル削除 + delete_recv_file() -for i in range(loop_count): + # 4 アクティベート + ec_recv[0].activate_component(g_compo_recv.rtc_ref) + time.sleep(sleep_recv_act_time) + ec_send[0].activate_component(g_compo_send.rtc_ref) - ## 2 受信データファイル削除 - delete_recv_file() + time.sleep(sleep_act_time) - ## 4 アクティベート - ec_recv[0].activate_component(g_compo_recv.rtc_ref) - time.sleep(sleep_recv_act_time) - ec_send[0].activate_component(g_compo_send.rtc_ref) + # 5 ディアクティベート + ec_send[0].deactivate_component(g_compo_send.rtc_ref) + ec_recv[0].deactivate_component(g_compo_recv.rtc_ref) - time.sleep(sleep_act_time) + # 受信ファイル有無判定 + if os.path.isfile(g_diff_recv_file) == False: + fout = open(g_test_result_file, 'a') + message = g_mess_header + g_test_case + \ + str(case_no) + " " + g_test_cnt + str(i + 1) + g_mess_footer + message = message + g_check_message + fout.write(message + '\n') + fout.close() + print(message) + time.sleep(sleep_for_time) + continue - ## 5 ディアクティベート - ec_send[0].deactivate_component(g_compo_send.rtc_ref) - ec_recv[0].deactivate_component(g_compo_recv.rtc_ref) + # 7 送受信データ比較 + time.sleep(sleep_act_time) + bret = diff_file() - ## 受信ファイル有無判定 - if os.path.isfile(g_diff_recv_file) == False: + # 差分ファイルからテスト結果出力 fout = open(g_test_result_file, 'a') - message = g_mess_header + g_test_case + str(case_no) + " " + g_test_cnt + str(i+1) + g_mess_footer - message = message + g_check_message - fout.write(message + '\n') + message = g_mess_header + g_test_case + \ + str(case_no) + " " + g_test_cnt + str(i + 1) + g_mess_footer + # bret==True なら送受信データ一致 + if bret == True: + # テスト結果 OK + message = message + g_test_ok + print(message) + fout.write(message + '\n') + else: + # テスト結果 NG + message = message + g_test_ng + print(message) + message = message + g_test_ng_message + fout.write(message + '\n') + # 受信データをテスト結果ファイルへコピー + fin2 = open(g_diff_recv_file, 'r') + while(1): + s2 = fin2.readline() + if len(s2) == 0: + break + fout.write(s2) + fin2.close() fout.close() - print(message) + time.sleep(sleep_for_time) - continue - ## 7 送受信データ比較 - time.sleep(sleep_act_time) - bret = diff_file() + # 6 ポート切断 + g_in_ports[g_port3].disconnect(g_conprof3.connector_id) + g_in_ports[g_port2].disconnect(g_conprof2.connector_id) + g_in_ports[g_port1].disconnect(g_conprof1.connector_id) - ## 差分ファイルからテスト結果出力 + # -------------------------------------------------------------------- + # 接続タイプ:new 方向:in->out ポリシー:ALL Activate・Deactivateテスト2 + # -------------------------------------------------------------------- + case_no = case_no + 1 fout = open(g_test_result_file, 'a') - message = g_mess_header + g_test_case + str(case_no) + " " + g_test_cnt + str(i+1) + g_mess_footer - # bret==True なら送受信データ一致 - if bret == True: - # テスト結果 OK - message = message + g_test_ok - print(message) - fout.write(message + '\n') - else: - # テスト結果 NG - message = message + g_test_ng - print(message) - message = message + g_test_ng_message - fout.write(message + '\n') - # 受信データをテスト結果ファイルへコピー - fin2 = open(g_diff_recv_file, 'r') - while(1): - s2 = fin2.readline() - if len(s2) == 0: - break - fout.write(s2) - fin2.close() + message = g_mess_header + g_test_case + str(case_no) + " " + message = message + \ + "Connecting(in->out, new,ALL), Activate -> send/recv -> Deactivate" + message = message + g_mess_footer + fout.write(message + '\n') fout.close() + print(message) - time.sleep(sleep_for_time) - -## 6 ポート切断 -g_in_ports[g_port3].disconnect(g_conprof3.connector_id) -g_in_ports[g_port2].disconnect(g_conprof2.connector_id) -g_in_ports[g_port1].disconnect(g_conprof1.connector_id) + # 1 コネクタープロファイル設定 + make_connecter_profile("new", "ALL", 1) -##-------------------------------------------------------------------- -## 接続タイプ:new 方向:in->out ポリシー:ALL Activate・Deactivateテスト2 -##-------------------------------------------------------------------- -case_no = case_no + 1 -fout = open(g_test_result_file, 'a') -message = g_mess_header + g_test_case + str(case_no) + " " -message = message + "Connecting(in->out, new,ALL), Activate -> send/recv -> Deactivate" -message = message + g_mess_footer -fout.write(message + '\n') -fout.close() -print(message) + # 3 ポート接続 + # データポート1 TimedFloat + ret0 = g_out_ports[g_port1].connect(g_conprof1) -## 1 コネクタープロファイル設定 -make_connecter_profile("new", "ALL", 1) + # データポート2 TimedFloatSeq + ret1 = g_out_ports[g_port2].connect(g_conprof2) -## 3 ポート接続 -# データポート1 TimedFloat -ret0 = g_out_ports[g_port1].connect(g_conprof1) + # サービスポート MyService + ret2 = g_out_ports[g_port3].connect(g_conprof3) -# データポート2 TimedFloatSeq -ret1 = g_out_ports[g_port2].connect(g_conprof2) + for i in range(loop_count): -# サービスポート MyService -ret2 = g_out_ports[g_port3].connect(g_conprof3) + # 2 受信データファイル削除 + delete_recv_file() -for i in range(loop_count): + # 4 アクティベート + ec_recv[0].activate_component(g_compo_recv.rtc_ref) + time.sleep(sleep_recv_act_time) + ec_send[0].activate_component(g_compo_send.rtc_ref) - ## 2 受信データファイル削除 - delete_recv_file() + time.sleep(sleep_act_time) - ## 4 アクティベート - ec_recv[0].activate_component(g_compo_recv.rtc_ref) - time.sleep(sleep_recv_act_time) - ec_send[0].activate_component(g_compo_send.rtc_ref) + # 5 ディアクティベート + ec_send[0].deactivate_component(g_compo_send.rtc_ref) + ec_recv[0].deactivate_component(g_compo_recv.rtc_ref) - time.sleep(sleep_act_time) + # 受信ファイル有無判定 + if os.path.isfile(g_diff_recv_file) == False: + fout = open(g_test_result_file, 'a') + message = g_mess_header + g_test_case + \ + str(case_no) + " " + g_test_cnt + str(i + 1) + g_mess_footer + message = message + g_check_message + fout.write(message + '\n') + fout.close() + print(message) + time.sleep(sleep_for_time) + continue - ## 5 ディアクティベート - ec_send[0].deactivate_component(g_compo_send.rtc_ref) - ec_recv[0].deactivate_component(g_compo_recv.rtc_ref) + # 7 送受信データ比較 + time.sleep(sleep_act_time) + bret = diff_file() - ## 受信ファイル有無判定 - if os.path.isfile(g_diff_recv_file) == False: + # 差分ファイルからテスト結果出力 fout = open(g_test_result_file, 'a') - message = g_mess_header + g_test_case + str(case_no) + " " + g_test_cnt + str(i+1) + g_mess_footer - message = message + g_check_message - fout.write(message + '\n') + message = g_mess_header + g_test_case + \ + str(case_no) + " " + g_test_cnt + str(i + 1) + g_mess_footer + # bret==True なら送受信データ一致 + if bret == True: + # テスト結果 OK + message = message + g_test_ok + print(message) + fout.write(message + '\n') + else: + # テスト結果 NG + message = message + g_test_ng + print(message) + message = message + g_test_ng_message + fout.write(message + '\n') + # 受信データをテスト結果ファイルへコピー + fin2 = open(g_diff_recv_file, 'r') + while(1): + s2 = fin2.readline() + if len(s2) == 0: + break + fout.write(s2) + fin2.close() fout.close() - print(message) + time.sleep(sleep_for_time) - continue - ## 7 送受信データ比較 - time.sleep(sleep_act_time) - bret = diff_file() + # 6 ポート切断 + g_in_ports[g_port3].disconnect(g_conprof3.connector_id) + g_in_ports[g_port2].disconnect(g_conprof2.connector_id) + g_in_ports[g_port1].disconnect(g_conprof1.connector_id) - ## 差分ファイルからテスト結果出力 + # -------------------------------------------------------------------- + # 接続タイプ:new 方向:in->out ポリシー:FIFO Activate・Deactivateテスト3 + # -------------------------------------------------------------------- + case_no = case_no + 1 fout = open(g_test_result_file, 'a') - message = g_mess_header + g_test_case + str(case_no) + " " + g_test_cnt + str(i+1) + g_mess_footer - # bret==True なら送受信データ一致 - if bret == True: - # テスト結果 OK - message = message + g_test_ok - print(message) - fout.write(message + '\n') - else: - # テスト結果 NG - message = message + g_test_ng - print(message) - message = message + g_test_ng_message - fout.write(message + '\n') - # 受信データをテスト結果ファイルへコピー - fin2 = open(g_diff_recv_file, 'r') - while(1): - s2 = fin2.readline() - if len(s2) == 0: - break - fout.write(s2) - fin2.close() + message = g_mess_header + g_test_case + str(case_no) + " " + message = message + \ + "Connecting(in->out, new,FIFO), Activate -> send/recv -> Deactivate" + message = message + g_mess_footer + fout.write(message + '\n') fout.close() + print(message) - time.sleep(sleep_for_time) - -## 6 ポート切断 -g_in_ports[g_port3].disconnect(g_conprof3.connector_id) -g_in_ports[g_port2].disconnect(g_conprof2.connector_id) -g_in_ports[g_port1].disconnect(g_conprof1.connector_id) + # 1 コネクタープロファイル設定 + make_connecter_profile("new", "FIFO", 1) -##-------------------------------------------------------------------- -## 接続タイプ:new 方向:in->out ポリシー:FIFO Activate・Deactivateテスト3 -##-------------------------------------------------------------------- -case_no = case_no + 1 -fout = open(g_test_result_file, 'a') -message = g_mess_header + g_test_case + str(case_no) + " " -message = message + "Connecting(in->out, new,FIFO), Activate -> send/recv -> Deactivate" -message = message + g_mess_footer -fout.write(message + '\n') -fout.close() -print(message) + # 3 ポート接続 + # データポート1 TimedFloat + ret0 = g_out_ports[g_port1].connect(g_conprof1) -## 1 コネクタープロファイル設定 -make_connecter_profile("new", "FIFO", 1) + # データポート2 TimedFloatSeq + ret1 = g_out_ports[g_port2].connect(g_conprof2) -## 3 ポート接続 -# データポート1 TimedFloat -ret0 = g_out_ports[g_port1].connect(g_conprof1) + # サービスポート MyService + ret2 = g_out_ports[g_port3].connect(g_conprof3) -# データポート2 TimedFloatSeq -ret1 = g_out_ports[g_port2].connect(g_conprof2) + for i in range(loop_count): -# サービスポート MyService -ret2 = g_out_ports[g_port3].connect(g_conprof3) + # 2 受信データファイル削除 + delete_recv_file() -for i in range(loop_count): + # 4 アクティベート + ec_recv[0].activate_component(g_compo_recv.rtc_ref) + time.sleep(sleep_recv_act_time) + ec_send[0].activate_component(g_compo_send.rtc_ref) - ## 2 受信データファイル削除 - delete_recv_file() + time.sleep(sleep_act_time) - ## 4 アクティベート - ec_recv[0].activate_component(g_compo_recv.rtc_ref) - time.sleep(sleep_recv_act_time) - ec_send[0].activate_component(g_compo_send.rtc_ref) + # 5 ディアクティベート + ec_send[0].deactivate_component(g_compo_send.rtc_ref) + ec_recv[0].deactivate_component(g_compo_recv.rtc_ref) - time.sleep(sleep_act_time) + # 受信ファイル有無判定 + if os.path.isfile(g_diff_recv_file) == False: + fout = open(g_test_result_file, 'a') + message = g_mess_header + g_test_case + \ + str(case_no) + " " + g_test_cnt + str(i + 1) + g_mess_footer + message = message + g_check_message + fout.write(message + '\n') + fout.close() + print(message) + time.sleep(sleep_for_time) + continue - ## 5 ディアクティベート - ec_send[0].deactivate_component(g_compo_send.rtc_ref) - ec_recv[0].deactivate_component(g_compo_recv.rtc_ref) + # 7 送受信データ比較 + time.sleep(sleep_act_time) + bret = diff_file() - ## 受信ファイル有無判定 - if os.path.isfile(g_diff_recv_file) == False: + # 差分ファイルからテスト結果出力 fout = open(g_test_result_file, 'a') - message = g_mess_header + g_test_case + str(case_no) + " " + g_test_cnt + str(i+1) + g_mess_footer - message = message + g_check_message - fout.write(message + '\n') + message = g_mess_header + g_test_case + \ + str(case_no) + " " + g_test_cnt + str(i + 1) + g_mess_footer + # bret==True なら送受信データ一致 + if bret == True: + # テスト結果 OK + message = message + g_test_ok + print(message) + fout.write(message + '\n') + else: + # テスト結果 NG + message = message + g_test_ng + print(message) + message = message + g_test_ng_message + fout.write(message + '\n') + # 受信データをテスト結果ファイルへコピー + fin2 = open(g_diff_recv_file, 'r') + while(1): + s2 = fin2.readline() + if len(s2) == 0: + break + fout.write(s2) + fin2.close() fout.close() - print(message) + time.sleep(sleep_for_time) - continue - ## 7 送受信データ比較 - time.sleep(sleep_act_time) - bret = diff_file() + # 6 ポート切断 + g_in_ports[g_port3].disconnect(g_conprof3.connector_id) + g_in_ports[g_port2].disconnect(g_conprof2.connector_id) + g_in_ports[g_port1].disconnect(g_conprof1.connector_id) - ## 差分ファイルからテスト結果出力 + # -------------------------------------------------------------------- + # 接続タイプ:new 方向:in->out ポリシー:NEW Activate・Deactivateテスト5 + # -------------------------------------------------------------------- + case_no = case_no + 1 fout = open(g_test_result_file, 'a') - message = g_mess_header + g_test_case + str(case_no) + " " + g_test_cnt + str(i+1) + g_mess_footer - # bret==True なら送受信データ一致 - if bret == True: - # テスト結果 OK - message = message + g_test_ok - print(message) - fout.write(message + '\n') - else: - # テスト結果 NG - message = message + g_test_ng - print(message) - message = message + g_test_ng_message - fout.write(message + '\n') - # 受信データをテスト結果ファイルへコピー - fin2 = open(g_diff_recv_file, 'r') - while(1): - s2 = fin2.readline() - if len(s2) == 0: - break - fout.write(s2) - fin2.close() + message = g_mess_header + g_test_case + str(case_no) + " " + message = message + \ + "Connecting(in->out, new,NEW), Activate -> send/recv -> Deactivate" + message = message + g_mess_footer + fout.write(message + '\n') fout.close() + print(message) - time.sleep(sleep_for_time) - -## 6 ポート切断 -g_in_ports[g_port3].disconnect(g_conprof3.connector_id) -g_in_ports[g_port2].disconnect(g_conprof2.connector_id) -g_in_ports[g_port1].disconnect(g_conprof1.connector_id) + # 1 コネクタープロファイル設定 + make_connecter_profile("new", "NEW", 1) -##-------------------------------------------------------------------- -## 接続タイプ:new 方向:in->out ポリシー:NEW Activate・Deactivateテスト5 -##-------------------------------------------------------------------- -case_no = case_no + 1 -fout = open(g_test_result_file, 'a') -message = g_mess_header + g_test_case + str(case_no) + " " -message = message + "Connecting(in->out, new,NEW), Activate -> send/recv -> Deactivate" -message = message + g_mess_footer -fout.write(message + '\n') -fout.close() -print(message) + # 3 ポート接続 + # データポート1 TimedFloat + ret0 = g_out_ports[g_port1].connect(g_conprof1) -## 1 コネクタープロファイル設定 -make_connecter_profile("new", "NEW", 1) + # データポート2 TimedFloatSeq + ret1 = g_out_ports[g_port2].connect(g_conprof2) -## 3 ポート接続 -# データポート1 TimedFloat -ret0 = g_out_ports[g_port1].connect(g_conprof1) + # サービスポート MyService + ret2 = g_out_ports[g_port3].connect(g_conprof3) -# データポート2 TimedFloatSeq -ret1 = g_out_ports[g_port2].connect(g_conprof2) + for i in range(loop_count): -# サービスポート MyService -ret2 = g_out_ports[g_port3].connect(g_conprof3) + # 2 受信データファイル削除 + delete_recv_file() -for i in range(loop_count): + # 4 アクティベート + ec_recv[0].activate_component(g_compo_recv.rtc_ref) + time.sleep(sleep_recv_act_time) + ec_send[0].activate_component(g_compo_send.rtc_ref) - ## 2 受信データファイル削除 - delete_recv_file() + time.sleep(sleep_act_time) - ## 4 アクティベート - ec_recv[0].activate_component(g_compo_recv.rtc_ref) - time.sleep(sleep_recv_act_time) - ec_send[0].activate_component(g_compo_send.rtc_ref) + # 5 ディアクティベート + ec_send[0].deactivate_component(g_compo_send.rtc_ref) + ec_recv[0].deactivate_component(g_compo_recv.rtc_ref) - time.sleep(sleep_act_time) + # 受信ファイル有無判定 + if os.path.isfile(g_diff_recv_file) == False: + fout = open(g_test_result_file, 'a') + message = g_mess_header + g_test_case + \ + str(case_no) + " " + g_test_cnt + str(i + 1) + g_mess_footer + message = message + g_check_message + fout.write(message + '\n') + fout.close() + print(message) + time.sleep(sleep_for_time) + continue - ## 5 ディアクティベート - ec_send[0].deactivate_component(g_compo_send.rtc_ref) - ec_recv[0].deactivate_component(g_compo_recv.rtc_ref) + # 7 送受信データ比較 + time.sleep(sleep_act_time) + bret = diff_file() - ## 受信ファイル有無判定 - if os.path.isfile(g_diff_recv_file) == False: + # 差分ファイルからテスト結果出力 fout = open(g_test_result_file, 'a') - message = g_mess_header + g_test_case + str(case_no) + " " + g_test_cnt + str(i+1) + g_mess_footer - message = message + g_check_message - fout.write(message + '\n') + message = g_mess_header + g_test_case + \ + str(case_no) + " " + g_test_cnt + str(i + 1) + g_mess_footer + # bret==True なら送受信データ一致 + if bret == True: + # テスト結果 OK + message = message + g_test_ok + print(message) + fout.write(message + '\n') + else: + # テスト結果 NG + message = message + g_test_ng + print(message) + message = message + g_test_ng_message + fout.write(message + '\n') + # 受信データをテスト結果ファイルへコピー + fin2 = open(g_diff_recv_file, 'r') + while(1): + s2 = fin2.readline() + if len(s2) == 0: + break + fout.write(s2) + fin2.close() fout.close() - print(message) + time.sleep(sleep_for_time) - continue - ## 7 送受信データ比較 - time.sleep(sleep_act_time) - bret = diff_file() + # 6 ポート切断 + g_in_ports[g_port3].disconnect(g_conprof3.connector_id) + g_in_ports[g_port2].disconnect(g_conprof2.connector_id) + g_in_ports[g_port1].disconnect(g_conprof1.connector_id) - ## 差分ファイルからテスト結果出力 + # -------------------------------------------------------------------- + # 接続タイプ:new 方向:in->out ポリシー:SKIP Activate・Deactivateテスト4 + # -------------------------------------------------------------------- + case_no = case_no + 1 fout = open(g_test_result_file, 'a') - message = g_mess_header + g_test_case + str(case_no) + " " + g_test_cnt + str(i+1) + g_mess_footer - # bret==True なら送受信データ一致 - if bret == True: - # テスト結果 OK - message = message + g_test_ok - print(message) - fout.write(message + '\n') - else: - # テスト結果 NG - message = message + g_test_ng - print(message) - message = message + g_test_ng_message - fout.write(message + '\n') - # 受信データをテスト結果ファイルへコピー - fin2 = open(g_diff_recv_file, 'r') - while(1): - s2 = fin2.readline() - if len(s2) == 0: - break - fout.write(s2) - fin2.close() + message = g_mess_header + g_test_case + str(case_no) + " " + message = message + \ + "Connecting(in->out, new,SKIP), Activate -> send/recv -> Deactivate" + message = message + g_mess_footer + fout.write(message + '\n') fout.close() + print(message) - time.sleep(sleep_for_time) - -## 6 ポート切断 -g_in_ports[g_port3].disconnect(g_conprof3.connector_id) -g_in_ports[g_port2].disconnect(g_conprof2.connector_id) -g_in_ports[g_port1].disconnect(g_conprof1.connector_id) + # 1 コネクタープロファイル設定 + make_connecter_profile("new", "SKIP", 1) -##-------------------------------------------------------------------- -## 接続タイプ:new 方向:in->out ポリシー:SKIP Activate・Deactivateテスト4 -##-------------------------------------------------------------------- -case_no = case_no + 1 -fout = open(g_test_result_file, 'a') -message = g_mess_header + g_test_case + str(case_no) + " " -message = message + "Connecting(in->out, new,SKIP), Activate -> send/recv -> Deactivate" -message = message + g_mess_footer -fout.write(message + '\n') -fout.close() -print(message) + # 3 ポート接続 + # データポート1 TimedFloat + ret0 = g_out_ports[g_port1].connect(g_conprof1) -## 1 コネクタープロファイル設定 -make_connecter_profile("new", "SKIP", 1) + # データポート2 TimedFloatSeq + ret1 = g_out_ports[g_port2].connect(g_conprof2) -## 3 ポート接続 -# データポート1 TimedFloat -ret0 = g_out_ports[g_port1].connect(g_conprof1) + # サービスポート MyService + ret2 = g_out_ports[g_port3].connect(g_conprof3) -# データポート2 TimedFloatSeq -ret1 = g_out_ports[g_port2].connect(g_conprof2) + for i in range(loop_count): -# サービスポート MyService -ret2 = g_out_ports[g_port3].connect(g_conprof3) + # 2 受信データファイル削除 + delete_recv_file() -for i in range(loop_count): + # 4 アクティベート + ec_recv[0].activate_component(g_compo_recv.rtc_ref) + time.sleep(sleep_recv_act_time) + ec_send[0].activate_component(g_compo_send.rtc_ref) - ## 2 受信データファイル削除 - delete_recv_file() + time.sleep(sleep_act_time) - ## 4 アクティベート - ec_recv[0].activate_component(g_compo_recv.rtc_ref) - time.sleep(sleep_recv_act_time) - ec_send[0].activate_component(g_compo_send.rtc_ref) + # 5 ディアクティベート + ec_send[0].deactivate_component(g_compo_send.rtc_ref) + ec_recv[0].deactivate_component(g_compo_recv.rtc_ref) - time.sleep(sleep_act_time) + # 受信ファイル有無判定 + if os.path.isfile(g_diff_recv_file) == False: + fout = open(g_test_result_file, 'a') + message = g_mess_header + g_test_case + \ + str(case_no) + " " + g_test_cnt + str(i + 1) + g_mess_footer + message = message + g_check_message + fout.write(message + '\n') + fout.close() + print(message) + time.sleep(sleep_for_time) + continue - ## 5 ディアクティベート - ec_send[0].deactivate_component(g_compo_send.rtc_ref) - ec_recv[0].deactivate_component(g_compo_recv.rtc_ref) + # 7 送受信データ比較 + time.sleep(sleep_act_time) + bret = diff_file() - ## 受信ファイル有無判定 - if os.path.isfile(g_diff_recv_file) == False: + # 差分ファイルからテスト結果出力 fout = open(g_test_result_file, 'a') - message = g_mess_header + g_test_case + str(case_no) + " " + g_test_cnt + str(i+1) + g_mess_footer - message = message + g_check_message - fout.write(message + '\n') + message = g_mess_header + g_test_case + \ + str(case_no) + " " + g_test_cnt + str(i + 1) + g_mess_footer + # bret==True なら送受信データ一致 + if bret == True: + # テスト結果 OK + message = message + g_test_ok + print(message) + fout.write(message + '\n') + else: + # テスト結果 NG + message = message + g_test_ng + print(message) + message = message + g_test_ng_message + fout.write(message + '\n') + # 受信データをテスト結果ファイルへコピー + fin2 = open(g_diff_recv_file, 'r') + while(1): + s2 = fin2.readline() + if len(s2) == 0: + break + fout.write(s2) + fin2.close() fout.close() - print(message) + time.sleep(sleep_for_time) - continue - ## 7 送受信データ比較 - time.sleep(sleep_act_time) - bret = diff_file() + # 6 ポート切断 + g_in_ports[g_port3].disconnect(g_conprof3.connector_id) + g_in_ports[g_port2].disconnect(g_conprof2.connector_id) + g_in_ports[g_port1].disconnect(g_conprof1.connector_id) - ## 差分ファイルからテスト結果出力 + # -------------------------------------------------------------------- + # 接続タイプ:new 方向:out->in ポリシー:ALL 接続・切断・Activate・Deactivateテスト1 + # -------------------------------------------------------------------- + case_no = case_no + 1 fout = open(g_test_result_file, 'a') - message = g_mess_header + g_test_case + str(case_no) + " " + g_test_cnt + str(i+1) + g_mess_footer - # bret==True なら送受信データ一致 - if bret == True: - # テスト結果 OK - message = message + g_test_ok - print(message) - fout.write(message + '\n') - else: - # テスト結果 NG - message = message + g_test_ng - print(message) - message = message + g_test_ng_message - fout.write(message + '\n') - # 受信データをテスト結果ファイルへコピー - fin2 = open(g_diff_recv_file, 'r') - while(1): - s2 = fin2.readline() - if len(s2) == 0: - break - fout.write(s2) - fin2.close() + message = g_mess_header + g_test_case + str(case_no) + " " + message = message + \ + "Connect(out->in, new,ALL) -> Activate -> send/recv -> Deactivate -> Disconnect" + message = message + g_mess_footer + fout.write(message + '\n') fout.close() + print(message) - time.sleep(sleep_for_time) - -## 6 ポート切断 -g_in_ports[g_port3].disconnect(g_conprof3.connector_id) -g_in_ports[g_port2].disconnect(g_conprof2.connector_id) -g_in_ports[g_port1].disconnect(g_conprof1.connector_id) + for i in range(loop_count): -##-------------------------------------------------------------------- -## 接続タイプ:new 方向:out->in ポリシー:ALL 接続・切断・Activate・Deactivateテスト1 -##-------------------------------------------------------------------- -case_no = case_no + 1 -fout = open(g_test_result_file, 'a') -message = g_mess_header + g_test_case + str(case_no) + " " -message = message + "Connect(out->in, new,ALL) -> Activate -> send/recv -> Deactivate -> Disconnect" -message = message + g_mess_footer -fout.write(message + '\n') -fout.close() -print(message) + # 2 受信データファイル削除 + delete_recv_file() -for i in range(loop_count): + # 1 コネクタープロファイル設定 + make_connecter_profile("new", "ALL", 0) - ## 2 受信データファイル削除 - delete_recv_file() + # 3 ポート接続 + # データポート1 TimedFloat + ret0 = g_out_ports[g_port1].connect(g_conprof1) - ## 1 コネクタープロファイル設定 - make_connecter_profile("new", "ALL", 0) + # データポート2 TimedFloatSeq + ret1 = g_out_ports[g_port2].connect(g_conprof2) - ## 3 ポート接続 - # データポート1 TimedFloat - ret0 = g_out_ports[g_port1].connect(g_conprof1) + # サービスポート MyService + ret2 = g_out_ports[g_port3].connect(g_conprof3) - # データポート2 TimedFloatSeq - ret1 = g_out_ports[g_port2].connect(g_conprof2) + # 4 アクティベート + ec_recv[0].activate_component(g_compo_recv.rtc_ref) + time.sleep(sleep_recv_act_time) + ec_send[0].activate_component(g_compo_send.rtc_ref) - # サービスポート MyService - ret2 = g_out_ports[g_port3].connect(g_conprof3) + time.sleep(sleep_act_time) - ## 4 アクティベート - ec_recv[0].activate_component(g_compo_recv.rtc_ref) - time.sleep(sleep_recv_act_time) - ec_send[0].activate_component(g_compo_send.rtc_ref) + # 5 ディアクティベート + ec_send[0].deactivate_component(g_compo_send.rtc_ref) + ec_recv[0].deactivate_component(g_compo_recv.rtc_ref) - time.sleep(sleep_act_time) + # 6 ポート切断 + g_in_ports[g_port3].disconnect(g_conprof3.connector_id) + g_in_ports[g_port2].disconnect(g_conprof2.connector_id) + g_in_ports[g_port1].disconnect(g_conprof1.connector_id) - ## 5 ディアクティベート - ec_send[0].deactivate_component(g_compo_send.rtc_ref) - ec_recv[0].deactivate_component(g_compo_recv.rtc_ref) + # 受信ファイル有無判定 + if os.path.isfile(g_diff_recv_file) == False: + fout = open(g_test_result_file, 'a') + message = g_mess_header + g_test_case + \ + str(case_no) + " " + g_test_cnt + str(i + 1) + g_mess_footer + message = message + g_check_message + fout.write(message + '\n') + fout.close() + print(message) + time.sleep(sleep_for_time) + continue - ## 6 ポート切断 - g_in_ports[g_port3].disconnect(g_conprof3.connector_id) - g_in_ports[g_port2].disconnect(g_conprof2.connector_id) - g_in_ports[g_port1].disconnect(g_conprof1.connector_id) + # 7 送受信データ比較 + time.sleep(sleep_act_time) + bret = diff_file() - ## 受信ファイル有無判定 - if os.path.isfile(g_diff_recv_file) == False: + # 差分ファイルからテスト結果出力 fout = open(g_test_result_file, 'a') - message = g_mess_header + g_test_case + str(case_no) + " " + g_test_cnt + str(i+1) + g_mess_footer - message = message + g_check_message - fout.write(message + '\n') + message = g_mess_header + g_test_case + \ + str(case_no) + " " + g_test_cnt + str(i + 1) + g_mess_footer + # bret==True なら送受信データ一致 + if bret == True: + # テスト結果 OK + message = message + g_test_ok + print(message) + fout.write(message + '\n') + else: + # テスト結果 NG + message = message + g_test_ng + print(message) + message = message + g_test_ng_message + fout.write(message + '\n') + # 受信データをテスト結果ファイルへコピー + fin2 = open(g_diff_recv_file, 'r') + while(1): + s2 = fin2.readline() + if len(s2) == 0: + break + fout.write(s2) + fin2.close() fout.close() - print(message) - time.sleep(sleep_for_time) - continue - ## 7 送受信データ比較 - time.sleep(sleep_act_time) - bret = diff_file() + time.sleep(sleep_for_time) - ## 差分ファイルからテスト結果出力 + # -------------------------------------------------------------------- + # 接続タイプ:new 方向:out->in ポリシー:FIFO 接続・切断・Activate・Deactivateテスト1 + # -------------------------------------------------------------------- + case_no = case_no + 1 fout = open(g_test_result_file, 'a') - message = g_mess_header + g_test_case + str(case_no) + " " + g_test_cnt + str(i+1) + g_mess_footer - # bret==True なら送受信データ一致 - if bret == True: - # テスト結果 OK - message = message + g_test_ok - print(message) - fout.write(message + '\n') - else: - # テスト結果 NG - message = message + g_test_ng - print(message) - message = message + g_test_ng_message - fout.write(message + '\n') - # 受信データをテスト結果ファイルへコピー - fin2 = open(g_diff_recv_file, 'r') - while(1): - s2 = fin2.readline() - if len(s2) == 0: - break - fout.write(s2) - fin2.close() + message = g_mess_header + g_test_case + str(case_no) + " " + message = message + \ + "Connect(out->in, new,FIFO) -> Activate -> send/recv -> Deactivate -> Disconnect" + message = message + g_mess_footer + fout.write(message + '\n') fout.close() + print(message) - time.sleep(sleep_for_time) + for i in range(loop_count): -##-------------------------------------------------------------------- -## 接続タイプ:new 方向:out->in ポリシー:FIFO 接続・切断・Activate・Deactivateテスト1 -##-------------------------------------------------------------------- -case_no = case_no + 1 -fout = open(g_test_result_file, 'a') -message = g_mess_header + g_test_case + str(case_no) + " " -message = message + "Connect(out->in, new,FIFO) -> Activate -> send/recv -> Deactivate -> Disconnect" -message = message + g_mess_footer -fout.write(message + '\n') -fout.close() -print(message) + # 2 受信データファイル削除 + delete_recv_file() -for i in range(loop_count): + # 1 コネクタープロファイル設定 + make_connecter_profile("new", "FIFO", 0) - ## 2 受信データファイル削除 - delete_recv_file() + # 3 ポート接続 + # データポート1 TimedFloat + ret0 = g_out_ports[g_port1].connect(g_conprof1) - ## 1 コネクタープロファイル設定 - make_connecter_profile("new", "FIFO", 0) + # データポート2 TimedFloatSeq + ret1 = g_out_ports[g_port2].connect(g_conprof2) - ## 3 ポート接続 - # データポート1 TimedFloat - ret0 = g_out_ports[g_port1].connect(g_conprof1) + # サービスポート MyService + ret2 = g_out_ports[g_port3].connect(g_conprof3) - # データポート2 TimedFloatSeq - ret1 = g_out_ports[g_port2].connect(g_conprof2) + # 4 アクティベート + ec_recv[0].activate_component(g_compo_recv.rtc_ref) + time.sleep(sleep_recv_act_time) + ec_send[0].activate_component(g_compo_send.rtc_ref) - # サービスポート MyService - ret2 = g_out_ports[g_port3].connect(g_conprof3) + time.sleep(sleep_act_time) - ## 4 アクティベート - ec_recv[0].activate_component(g_compo_recv.rtc_ref) - time.sleep(sleep_recv_act_time) - ec_send[0].activate_component(g_compo_send.rtc_ref) + # 5 ディアクティベート + ec_send[0].deactivate_component(g_compo_send.rtc_ref) + ec_recv[0].deactivate_component(g_compo_recv.rtc_ref) - time.sleep(sleep_act_time) + # 6 ポート切断 + g_in_ports[g_port3].disconnect(g_conprof3.connector_id) + g_in_ports[g_port2].disconnect(g_conprof2.connector_id) + g_in_ports[g_port1].disconnect(g_conprof1.connector_id) - ## 5 ディアクティベート - ec_send[0].deactivate_component(g_compo_send.rtc_ref) - ec_recv[0].deactivate_component(g_compo_recv.rtc_ref) + # 受信ファイル有無判定 + if os.path.isfile(g_diff_recv_file) == False: + fout = open(g_test_result_file, 'a') + message = g_mess_header + g_test_case + \ + str(case_no) + " " + g_test_cnt + str(i + 1) + g_mess_footer + message = message + g_check_message + fout.write(message + '\n') + fout.close() + print(message) + time.sleep(sleep_for_time) + continue - ## 6 ポート切断 - g_in_ports[g_port3].disconnect(g_conprof3.connector_id) - g_in_ports[g_port2].disconnect(g_conprof2.connector_id) - g_in_ports[g_port1].disconnect(g_conprof1.connector_id) + # 7 送受信データ比較 + time.sleep(sleep_act_time) + bret = diff_file() - ## 受信ファイル有無判定 - if os.path.isfile(g_diff_recv_file) == False: + # 差分ファイルからテスト結果出力 fout = open(g_test_result_file, 'a') - message = g_mess_header + g_test_case + str(case_no) + " " + g_test_cnt + str(i+1) + g_mess_footer - message = message + g_check_message - fout.write(message + '\n') + message = g_mess_header + g_test_case + \ + str(case_no) + " " + g_test_cnt + str(i + 1) + g_mess_footer + # bret==True なら送受信データ一致 + if bret == True: + # テスト結果 OK + message = message + g_test_ok + print(message) + fout.write(message + '\n') + else: + # テスト結果 NG + message = message + g_test_ng + print(message) + message = message + g_test_ng_message + fout.write(message + '\n') + # 受信データをテスト結果ファイルへコピー + fin2 = open(g_diff_recv_file, 'r') + while(1): + s2 = fin2.readline() + if len(s2) == 0: + break + fout.write(s2) + fin2.close() fout.close() - print(message) - time.sleep(sleep_for_time) - continue - ## 7 送受信データ比較 - time.sleep(sleep_act_time) - bret = diff_file() + time.sleep(sleep_for_time) - ## 差分ファイルからテスト結果出力 + # -------------------------------------------------------------------- + # 接続タイプ:new 方向:out->in ポリシー:NEW 接続・切断・Activate・Deactivateテスト1 + # -------------------------------------------------------------------- + case_no = case_no + 1 fout = open(g_test_result_file, 'a') - message = g_mess_header + g_test_case + str(case_no) + " " + g_test_cnt + str(i+1) + g_mess_footer - # bret==True なら送受信データ一致 - if bret == True: - # テスト結果 OK - message = message + g_test_ok - print(message) - fout.write(message + '\n') - else: - # テスト結果 NG - message = message + g_test_ng - print(message) - message = message + g_test_ng_message - fout.write(message + '\n') - # 受信データをテスト結果ファイルへコピー - fin2 = open(g_diff_recv_file, 'r') - while(1): - s2 = fin2.readline() - if len(s2) == 0: - break - fout.write(s2) - fin2.close() + message = g_mess_header + g_test_case + str(case_no) + " " + message = message + \ + "Connect(out->in, new,NEW) -> Activate -> send/recv -> Deactivate -> Disconnect" + message = message + g_mess_footer + fout.write(message + '\n') fout.close() + print(message) - time.sleep(sleep_for_time) + for i in range(loop_count): -##-------------------------------------------------------------------- -## 接続タイプ:new 方向:out->in ポリシー:NEW 接続・切断・Activate・Deactivateテスト1 -##-------------------------------------------------------------------- -case_no = case_no + 1 -fout = open(g_test_result_file, 'a') -message = g_mess_header + g_test_case + str(case_no) + " " -message = message + "Connect(out->in, new,NEW) -> Activate -> send/recv -> Deactivate -> Disconnect" -message = message + g_mess_footer -fout.write(message + '\n') -fout.close() -print(message) + # 2 受信データファイル削除 + delete_recv_file() -for i in range(loop_count): + # 1 コネクタープロファイル設定 + make_connecter_profile("new", "NEW", 0) - ## 2 受信データファイル削除 - delete_recv_file() + # 3 ポート接続 + # データポート1 TimedFloat + ret0 = g_out_ports[g_port1].connect(g_conprof1) - ## 1 コネクタープロファイル設定 - make_connecter_profile("new", "NEW", 0) + # データポート2 TimedFloatSeq + ret1 = g_out_ports[g_port2].connect(g_conprof2) - ## 3 ポート接続 - # データポート1 TimedFloat - ret0 = g_out_ports[g_port1].connect(g_conprof1) + # サービスポート MyService + ret2 = g_out_ports[g_port3].connect(g_conprof3) - # データポート2 TimedFloatSeq - ret1 = g_out_ports[g_port2].connect(g_conprof2) + # 4 アクティベート + ec_recv[0].activate_component(g_compo_recv.rtc_ref) + time.sleep(sleep_recv_act_time) + ec_send[0].activate_component(g_compo_send.rtc_ref) - # サービスポート MyService - ret2 = g_out_ports[g_port3].connect(g_conprof3) + time.sleep(sleep_act_time) - ## 4 アクティベート - ec_recv[0].activate_component(g_compo_recv.rtc_ref) - time.sleep(sleep_recv_act_time) - ec_send[0].activate_component(g_compo_send.rtc_ref) + # 5 ディアクティベート + ec_send[0].deactivate_component(g_compo_send.rtc_ref) + ec_recv[0].deactivate_component(g_compo_recv.rtc_ref) - time.sleep(sleep_act_time) + # 6 ポート切断 + g_in_ports[g_port3].disconnect(g_conprof3.connector_id) + g_in_ports[g_port2].disconnect(g_conprof2.connector_id) + g_in_ports[g_port1].disconnect(g_conprof1.connector_id) - ## 5 ディアクティベート - ec_send[0].deactivate_component(g_compo_send.rtc_ref) - ec_recv[0].deactivate_component(g_compo_recv.rtc_ref) + # 受信ファイル有無判定 + if os.path.isfile(g_diff_recv_file) == False: + fout = open(g_test_result_file, 'a') + message = g_mess_header + g_test_case + \ + str(case_no) + " " + g_test_cnt + str(i + 1) + g_mess_footer + message = message + g_check_message + fout.write(message + '\n') + fout.close() + print(message) + time.sleep(sleep_for_time) + continue - ## 6 ポート切断 - g_in_ports[g_port3].disconnect(g_conprof3.connector_id) - g_in_ports[g_port2].disconnect(g_conprof2.connector_id) - g_in_ports[g_port1].disconnect(g_conprof1.connector_id) + # 7 送受信データ比較 + time.sleep(sleep_act_time) + bret = diff_file() - ## 受信ファイル有無判定 - if os.path.isfile(g_diff_recv_file) == False: + # 差分ファイルからテスト結果出力 fout = open(g_test_result_file, 'a') - message = g_mess_header + g_test_case + str(case_no) + " " + g_test_cnt + str(i+1) + g_mess_footer - message = message + g_check_message - fout.write(message + '\n') + message = g_mess_header + g_test_case + \ + str(case_no) + " " + g_test_cnt + str(i + 1) + g_mess_footer + # bret==True なら送受信データ一致 + if bret == True: + # テスト結果 OK + message = message + g_test_ok + print(message) + fout.write(message + '\n') + else: + # テスト結果 NG + message = message + g_test_ng + print(message) + message = message + g_test_ng_message + fout.write(message + '\n') + # 受信データをテスト結果ファイルへコピー + fin2 = open(g_diff_recv_file, 'r') + while(1): + s2 = fin2.readline() + if len(s2) == 0: + break + fout.write(s2) + fin2.close() fout.close() - print(message) - time.sleep(sleep_for_time) - continue - ## 7 送受信データ比較 - time.sleep(sleep_act_time) - bret = diff_file() + time.sleep(sleep_for_time) - ## 差分ファイルからテスト結果出力 + # -------------------------------------------------------------------- + # 接続タイプ:new 方向:out->in ポリシー:SKIP 接続・切断・Activate・Deactivateテスト1 + # -------------------------------------------------------------------- + case_no = case_no + 1 fout = open(g_test_result_file, 'a') - message = g_mess_header + g_test_case + str(case_no) + " " + g_test_cnt + str(i+1) + g_mess_footer - # bret==True なら送受信データ一致 - if bret == True: - # テスト結果 OK - message = message + g_test_ok - print(message) - fout.write(message + '\n') - else: - # テスト結果 NG - message = message + g_test_ng - print(message) - message = message + g_test_ng_message - fout.write(message + '\n') - # 受信データをテスト結果ファイルへコピー - fin2 = open(g_diff_recv_file, 'r') - while(1): - s2 = fin2.readline() - if len(s2) == 0: - break - fout.write(s2) - fin2.close() + message = g_mess_header + g_test_case + str(case_no) + " " + message = message + \ + "Connect(out->in, new,SKIP) -> Activate -> send/recv -> Deactivate -> Disconnect" + message = message + g_mess_footer + fout.write(message + '\n') fout.close() + print(message) - time.sleep(sleep_for_time) + for i in range(loop_count): -##-------------------------------------------------------------------- -## 接続タイプ:new 方向:out->in ポリシー:SKIP 接続・切断・Activate・Deactivateテスト1 -##-------------------------------------------------------------------- -case_no = case_no + 1 -fout = open(g_test_result_file, 'a') -message = g_mess_header + g_test_case + str(case_no) + " " -message = message + "Connect(out->in, new,SKIP) -> Activate -> send/recv -> Deactivate -> Disconnect" -message = message + g_mess_footer -fout.write(message + '\n') -fout.close() -print(message) + # 2 受信データファイル削除 + delete_recv_file() -for i in range(loop_count): + # 1 コネクタープロファイル設定 + make_connecter_profile("new", "SKIP", 0) - ## 2 受信データファイル削除 - delete_recv_file() + # 3 ポート接続 + # データポート1 TimedFloat + ret0 = g_out_ports[g_port1].connect(g_conprof1) - ## 1 コネクタープロファイル設定 - make_connecter_profile("new", "SKIP", 0) + # データポート2 TimedFloatSeq + ret1 = g_out_ports[g_port2].connect(g_conprof2) - ## 3 ポート接続 - # データポート1 TimedFloat - ret0 = g_out_ports[g_port1].connect(g_conprof1) + # サービスポート MyService + ret2 = g_out_ports[g_port3].connect(g_conprof3) - # データポート2 TimedFloatSeq - ret1 = g_out_ports[g_port2].connect(g_conprof2) + # 4 アクティベート + ec_recv[0].activate_component(g_compo_recv.rtc_ref) + time.sleep(sleep_recv_act_time) + ec_send[0].activate_component(g_compo_send.rtc_ref) - # サービスポート MyService - ret2 = g_out_ports[g_port3].connect(g_conprof3) + time.sleep(sleep_act_time) - ## 4 アクティベート - ec_recv[0].activate_component(g_compo_recv.rtc_ref) - time.sleep(sleep_recv_act_time) - ec_send[0].activate_component(g_compo_send.rtc_ref) + # 5 ディアクティベート + ec_send[0].deactivate_component(g_compo_send.rtc_ref) + ec_recv[0].deactivate_component(g_compo_recv.rtc_ref) - time.sleep(sleep_act_time) + # 6 ポート切断 + g_in_ports[g_port3].disconnect(g_conprof3.connector_id) + g_in_ports[g_port2].disconnect(g_conprof2.connector_id) + g_in_ports[g_port1].disconnect(g_conprof1.connector_id) - ## 5 ディアクティベート - ec_send[0].deactivate_component(g_compo_send.rtc_ref) - ec_recv[0].deactivate_component(g_compo_recv.rtc_ref) + # 受信ファイル有無判定 + if os.path.isfile(g_diff_recv_file) == False: + fout = open(g_test_result_file, 'a') + message = g_mess_header + g_test_case + \ + str(case_no) + " " + g_test_cnt + str(i + 1) + g_mess_footer + message = message + g_check_message + fout.write(message + '\n') + fout.close() + print(message) + time.sleep(sleep_for_time) + continue - ## 6 ポート切断 - g_in_ports[g_port3].disconnect(g_conprof3.connector_id) - g_in_ports[g_port2].disconnect(g_conprof2.connector_id) - g_in_ports[g_port1].disconnect(g_conprof1.connector_id) + # 7 送受信データ比較 + time.sleep(sleep_act_time) + bret = diff_file() - ## 受信ファイル有無判定 - if os.path.isfile(g_diff_recv_file) == False: + # 差分ファイルからテスト結果出力 fout = open(g_test_result_file, 'a') - message = g_mess_header + g_test_case + str(case_no) + " " + g_test_cnt + str(i+1) + g_mess_footer - message = message + g_check_message - fout.write(message + '\n') + message = g_mess_header + g_test_case + \ + str(case_no) + " " + g_test_cnt + str(i + 1) + g_mess_footer + # bret==True なら送受信データ一致 + if bret == True: + # テスト結果 OK + message = message + g_test_ok + print(message) + fout.write(message + '\n') + else: + # テスト結果 NG + message = message + g_test_ng + print(message) + message = message + g_test_ng_message + fout.write(message + '\n') + # 受信データをテスト結果ファイルへコピー + fin2 = open(g_diff_recv_file, 'r') + while(1): + s2 = fin2.readline() + if len(s2) == 0: + break + fout.write(s2) + fin2.close() fout.close() - print(message) - time.sleep(sleep_for_time) - continue - ## 7 送受信データ比較 - time.sleep(sleep_act_time) - bret = diff_file() + time.sleep(sleep_for_time) - ## 差分ファイルからテスト結果出力 + # -------------------------------------------------------------------- + # 接続タイプ:new 方向:in->out ポリシー:ALL 接続・切断・Activate・Deactivateテスト1 + # -------------------------------------------------------------------- + case_no = case_no + 1 fout = open(g_test_result_file, 'a') - message = g_mess_header + g_test_case + str(case_no) + " " + g_test_cnt + str(i+1) + g_mess_footer - # bret==True なら送受信データ一致 - if bret == True: - # テスト結果 OK - message = message + g_test_ok - print(message) - fout.write(message + '\n') - else: - # テスト結果 NG - message = message + g_test_ng - print(message) - message = message + g_test_ng_message - fout.write(message + '\n') - # 受信データをテスト結果ファイルへコピー - fin2 = open(g_diff_recv_file, 'r') - while(1): - s2 = fin2.readline() - if len(s2) == 0: - break - fout.write(s2) - fin2.close() + message = g_mess_header + g_test_case + str(case_no) + " " + message = message + \ + "Connect(in->out, new,ALL) -> Activate -> send/recv -> Deactivate -> Disconnect" + message = message + g_mess_footer + fout.write(message + '\n') fout.close() + print(message) - time.sleep(sleep_for_time) + for i in range(loop_count): -##-------------------------------------------------------------------- -## 接続タイプ:new 方向:in->out ポリシー:ALL 接続・切断・Activate・Deactivateテスト1 -##-------------------------------------------------------------------- -case_no = case_no + 1 -fout = open(g_test_result_file, 'a') -message = g_mess_header + g_test_case + str(case_no) + " " -message = message + "Connect(in->out, new,ALL) -> Activate -> send/recv -> Deactivate -> Disconnect" -message = message + g_mess_footer -fout.write(message + '\n') -fout.close() -print(message) + # 2 受信データファイル削除 + delete_recv_file() -for i in range(loop_count): + # 1 コネクタープロファイル設定 + make_connecter_profile("new", "ALL", 1) - ## 2 受信データファイル削除 - delete_recv_file() + # 3 ポート接続 + # データポート1 TimedFloat + ret0 = g_out_ports[g_port1].connect(g_conprof1) - ## 1 コネクタープロファイル設定 - make_connecter_profile("new", "ALL", 1) + # データポート2 TimedFloatSeq + ret1 = g_out_ports[g_port2].connect(g_conprof2) - ## 3 ポート接続 - # データポート1 TimedFloat - ret0 = g_out_ports[g_port1].connect(g_conprof1) + # サービスポート MyService + ret2 = g_out_ports[g_port3].connect(g_conprof3) - # データポート2 TimedFloatSeq - ret1 = g_out_ports[g_port2].connect(g_conprof2) + # 4 アクティベート + ec_recv[0].activate_component(g_compo_recv.rtc_ref) + time.sleep(sleep_recv_act_time) + ec_send[0].activate_component(g_compo_send.rtc_ref) - # サービスポート MyService - ret2 = g_out_ports[g_port3].connect(g_conprof3) + time.sleep(sleep_act_time) - ## 4 アクティベート - ec_recv[0].activate_component(g_compo_recv.rtc_ref) - time.sleep(sleep_recv_act_time) - ec_send[0].activate_component(g_compo_send.rtc_ref) + # 5 ディアクティベート + ec_send[0].deactivate_component(g_compo_send.rtc_ref) + ec_recv[0].deactivate_component(g_compo_recv.rtc_ref) - time.sleep(sleep_act_time) + # 6 ポート切断 + g_in_ports[g_port3].disconnect(g_conprof3.connector_id) + g_in_ports[g_port2].disconnect(g_conprof2.connector_id) + g_in_ports[g_port1].disconnect(g_conprof1.connector_id) - ## 5 ディアクティベート - ec_send[0].deactivate_component(g_compo_send.rtc_ref) - ec_recv[0].deactivate_component(g_compo_recv.rtc_ref) + # 受信ファイル有無判定 + if os.path.isfile(g_diff_recv_file) == False: + fout = open(g_test_result_file, 'a') + message = g_mess_header + g_test_case + \ + str(case_no) + " " + g_test_cnt + str(i + 1) + g_mess_footer + message = message + g_check_message + fout.write(message + '\n') + fout.close() + print(message) + time.sleep(sleep_for_time) + continue - ## 6 ポート切断 - g_in_ports[g_port3].disconnect(g_conprof3.connector_id) - g_in_ports[g_port2].disconnect(g_conprof2.connector_id) - g_in_ports[g_port1].disconnect(g_conprof1.connector_id) + # 7 送受信データ比較 + time.sleep(sleep_act_time) + bret = diff_file() - ## 受信ファイル有無判定 - if os.path.isfile(g_diff_recv_file) == False: + # 差分ファイルからテスト結果出力 fout = open(g_test_result_file, 'a') - message = g_mess_header + g_test_case + str(case_no) + " " + g_test_cnt + str(i+1) + g_mess_footer - message = message + g_check_message - fout.write(message + '\n') + message = g_mess_header + g_test_case + \ + str(case_no) + " " + g_test_cnt + str(i + 1) + g_mess_footer + # bret==True なら送受信データ一致 + if bret == True: + # テスト結果 OK + message = message + g_test_ok + print(message) + fout.write(message + '\n') + else: + # テスト結果 NG + message = message + g_test_ng + print(message) + message = message + g_test_ng_message + fout.write(message + '\n') + # 受信データをテスト結果ファイルへコピー + fin2 = open(g_diff_recv_file, 'r') + while(1): + s2 = fin2.readline() + if len(s2) == 0: + break + fout.write(s2) + fin2.close() fout.close() - print(message) - time.sleep(sleep_for_time) - continue - ## 7 送受信データ比較 - time.sleep(sleep_act_time) - bret = diff_file() + time.sleep(sleep_for_time) - ## 差分ファイルからテスト結果出力 + # -------------------------------------------------------------------- + # 接続タイプ:new 方向:in->out ポリシー:FIFO 接続・切断・Activate・Deactivateテスト1 + # -------------------------------------------------------------------- + case_no = case_no + 1 fout = open(g_test_result_file, 'a') - message = g_mess_header + g_test_case + str(case_no) + " " + g_test_cnt + str(i+1) + g_mess_footer - # bret==True なら送受信データ一致 - if bret == True: - # テスト結果 OK - message = message + g_test_ok - print(message) - fout.write(message + '\n') - else: - # テスト結果 NG - message = message + g_test_ng - print(message) - message = message + g_test_ng_message - fout.write(message + '\n') - # 受信データをテスト結果ファイルへコピー - fin2 = open(g_diff_recv_file, 'r') - while(1): - s2 = fin2.readline() - if len(s2) == 0: - break - fout.write(s2) - fin2.close() + message = g_mess_header + g_test_case + str(case_no) + " " + message = message + \ + "Connect(in->out, new,FIFO) -> Activate -> send/recv -> Deactivate -> Disconnect" + message = message + g_mess_footer + fout.write(message + '\n') fout.close() + print(message) - time.sleep(sleep_for_time) + for i in range(loop_count): -##-------------------------------------------------------------------- -## 接続タイプ:new 方向:in->out ポリシー:FIFO 接続・切断・Activate・Deactivateテスト1 -##-------------------------------------------------------------------- -case_no = case_no + 1 -fout = open(g_test_result_file, 'a') -message = g_mess_header + g_test_case + str(case_no) + " " -message = message + "Connect(in->out, new,FIFO) -> Activate -> send/recv -> Deactivate -> Disconnect" -message = message + g_mess_footer -fout.write(message + '\n') -fout.close() -print(message) + # 2 受信データファイル削除 + delete_recv_file() -for i in range(loop_count): + # 1 コネクタープロファイル設定 + make_connecter_profile("new", "FIFO", 1) - ## 2 受信データファイル削除 - delete_recv_file() + # 3 ポート接続 + # データポート1 TimedFloat + ret0 = g_out_ports[g_port1].connect(g_conprof1) - ## 1 コネクタープロファイル設定 - make_connecter_profile("new", "FIFO", 1) + # データポート2 TimedFloatSeq + ret1 = g_out_ports[g_port2].connect(g_conprof2) - ## 3 ポート接続 - # データポート1 TimedFloat - ret0 = g_out_ports[g_port1].connect(g_conprof1) + # サービスポート MyService + ret2 = g_out_ports[g_port3].connect(g_conprof3) - # データポート2 TimedFloatSeq - ret1 = g_out_ports[g_port2].connect(g_conprof2) + # 4 アクティベート + ec_recv[0].activate_component(g_compo_recv.rtc_ref) + time.sleep(sleep_recv_act_time) + ec_send[0].activate_component(g_compo_send.rtc_ref) - # サービスポート MyService - ret2 = g_out_ports[g_port3].connect(g_conprof3) + time.sleep(sleep_act_time) - ## 4 アクティベート - ec_recv[0].activate_component(g_compo_recv.rtc_ref) - time.sleep(sleep_recv_act_time) - ec_send[0].activate_component(g_compo_send.rtc_ref) + # 5 ディアクティベート + ec_send[0].deactivate_component(g_compo_send.rtc_ref) + ec_recv[0].deactivate_component(g_compo_recv.rtc_ref) - time.sleep(sleep_act_time) + # 6 ポート切断 + g_in_ports[g_port3].disconnect(g_conprof3.connector_id) + g_in_ports[g_port2].disconnect(g_conprof2.connector_id) + g_in_ports[g_port1].disconnect(g_conprof1.connector_id) - ## 5 ディアクティベート - ec_send[0].deactivate_component(g_compo_send.rtc_ref) - ec_recv[0].deactivate_component(g_compo_recv.rtc_ref) + # 受信ファイル有無判定 + if os.path.isfile(g_diff_recv_file) == False: + fout = open(g_test_result_file, 'a') + message = g_mess_header + g_test_case + \ + str(case_no) + " " + g_test_cnt + str(i + 1) + g_mess_footer + message = message + g_check_message + fout.write(message + '\n') + fout.close() + print(message) + time.sleep(sleep_for_time) + continue - ## 6 ポート切断 - g_in_ports[g_port3].disconnect(g_conprof3.connector_id) - g_in_ports[g_port2].disconnect(g_conprof2.connector_id) - g_in_ports[g_port1].disconnect(g_conprof1.connector_id) + # 7 送受信データ比較 + time.sleep(sleep_act_time) + bret = diff_file() - ## 受信ファイル有無判定 - if os.path.isfile(g_diff_recv_file) == False: + # 差分ファイルからテスト結果出力 fout = open(g_test_result_file, 'a') - message = g_mess_header + g_test_case + str(case_no) + " " + g_test_cnt + str(i+1) + g_mess_footer - message = message + g_check_message - fout.write(message + '\n') + message = g_mess_header + g_test_case + \ + str(case_no) + " " + g_test_cnt + str(i + 1) + g_mess_footer + # bret==True なら送受信データ一致 + if bret == True: + # テスト結果 OK + message = message + g_test_ok + print(message) + fout.write(message + '\n') + else: + # テスト結果 NG + message = message + g_test_ng + print(message) + message = message + g_test_ng_message + fout.write(message + '\n') + # 受信データをテスト結果ファイルへコピー + fin2 = open(g_diff_recv_file, 'r') + while(1): + s2 = fin2.readline() + if len(s2) == 0: + break + fout.write(s2) + fin2.close() fout.close() - print(message) - time.sleep(sleep_for_time) - continue - ## 7 送受信データ比較 - time.sleep(sleep_act_time) - bret = diff_file() + time.sleep(sleep_for_time) - ## 差分ファイルからテスト結果出力 + # -------------------------------------------------------------------- + # 接続タイプ:new 方向:in->out ポリシー:NEW 接続・切断・Activate・Deactivateテスト1 + # -------------------------------------------------------------------- + case_no = case_no + 1 fout = open(g_test_result_file, 'a') - message = g_mess_header + g_test_case + str(case_no) + " " + g_test_cnt + str(i+1) + g_mess_footer - # bret==True なら送受信データ一致 - if bret == True: - # テスト結果 OK - message = message + g_test_ok - print(message) - fout.write(message + '\n') - else: - # テスト結果 NG - message = message + g_test_ng - print(message) - message = message + g_test_ng_message - fout.write(message + '\n') - # 受信データをテスト結果ファイルへコピー - fin2 = open(g_diff_recv_file, 'r') - while(1): - s2 = fin2.readline() - if len(s2) == 0: - break - fout.write(s2) - fin2.close() + message = g_mess_header + g_test_case + str(case_no) + " " + message = message + \ + "Connect(in->out, new,NEW) -> Activate -> send/recv -> Deactivate -> Disconnect" + message = message + g_mess_footer + fout.write(message + '\n') fout.close() + print(message) - time.sleep(sleep_for_time) + for i in range(loop_count): -##-------------------------------------------------------------------- -## 接続タイプ:new 方向:in->out ポリシー:NEW 接続・切断・Activate・Deactivateテスト1 -##-------------------------------------------------------------------- -case_no = case_no + 1 -fout = open(g_test_result_file, 'a') -message = g_mess_header + g_test_case + str(case_no) + " " -message = message + "Connect(in->out, new,NEW) -> Activate -> send/recv -> Deactivate -> Disconnect" -message = message + g_mess_footer -fout.write(message + '\n') -fout.close() -print(message) + # 2 受信データファイル削除 + delete_recv_file() -for i in range(loop_count): + # 1 コネクタープロファイル設定 + make_connecter_profile("new", "NEW", 1) - ## 2 受信データファイル削除 - delete_recv_file() + # 3 ポート接続 + # データポート1 TimedFloat + ret0 = g_out_ports[g_port1].connect(g_conprof1) - ## 1 コネクタープロファイル設定 - make_connecter_profile("new", "NEW", 1) + # データポート2 TimedFloatSeq + ret1 = g_out_ports[g_port2].connect(g_conprof2) - ## 3 ポート接続 - # データポート1 TimedFloat - ret0 = g_out_ports[g_port1].connect(g_conprof1) + # サービスポート MyService + ret2 = g_out_ports[g_port3].connect(g_conprof3) - # データポート2 TimedFloatSeq - ret1 = g_out_ports[g_port2].connect(g_conprof2) + # 4 アクティベート + ec_recv[0].activate_component(g_compo_recv.rtc_ref) + time.sleep(sleep_recv_act_time) + ec_send[0].activate_component(g_compo_send.rtc_ref) - # サービスポート MyService - ret2 = g_out_ports[g_port3].connect(g_conprof3) + time.sleep(sleep_act_time) - ## 4 アクティベート - ec_recv[0].activate_component(g_compo_recv.rtc_ref) - time.sleep(sleep_recv_act_time) - ec_send[0].activate_component(g_compo_send.rtc_ref) + # 5 ディアクティベート + ec_send[0].deactivate_component(g_compo_send.rtc_ref) + ec_recv[0].deactivate_component(g_compo_recv.rtc_ref) - time.sleep(sleep_act_time) + # 6 ポート切断 + g_in_ports[g_port3].disconnect(g_conprof3.connector_id) + g_in_ports[g_port2].disconnect(g_conprof2.connector_id) + g_in_ports[g_port1].disconnect(g_conprof1.connector_id) - ## 5 ディアクティベート - ec_send[0].deactivate_component(g_compo_send.rtc_ref) - ec_recv[0].deactivate_component(g_compo_recv.rtc_ref) + # 受信ファイル有無判定 + if os.path.isfile(g_diff_recv_file) == False: + fout = open(g_test_result_file, 'a') + message = g_mess_header + g_test_case + \ + str(case_no) + " " + g_test_cnt + str(i + 1) + g_mess_footer + message = message + g_check_message + fout.write(message + '\n') + fout.close() + print(message) + time.sleep(sleep_for_time) + continue - ## 6 ポート切断 - g_in_ports[g_port3].disconnect(g_conprof3.connector_id) - g_in_ports[g_port2].disconnect(g_conprof2.connector_id) - g_in_ports[g_port1].disconnect(g_conprof1.connector_id) + # 7 送受信データ比較 + time.sleep(sleep_act_time) + bret = diff_file() - ## 受信ファイル有無判定 - if os.path.isfile(g_diff_recv_file) == False: + # 差分ファイルからテスト結果出力 fout = open(g_test_result_file, 'a') - message = g_mess_header + g_test_case + str(case_no) + " " + g_test_cnt + str(i+1) + g_mess_footer - message = message + g_check_message - fout.write(message + '\n') + message = g_mess_header + g_test_case + \ + str(case_no) + " " + g_test_cnt + str(i + 1) + g_mess_footer + # bret==True なら送受信データ一致 + if bret == True: + # テスト結果 OK + message = message + g_test_ok + print(message) + fout.write(message + '\n') + else: + # テスト結果 NG + message = message + g_test_ng + print(message) + message = message + g_test_ng_message + fout.write(message + '\n') + # 受信データをテスト結果ファイルへコピー + fin2 = open(g_diff_recv_file, 'r') + while(1): + s2 = fin2.readline() + if len(s2) == 0: + break + fout.write(s2) + fin2.close() fout.close() - print(message) - time.sleep(sleep_for_time) - continue - ## 7 送受信データ比較 - time.sleep(sleep_act_time) - bret = diff_file() + time.sleep(sleep_for_time) - ## 差分ファイルからテスト結果出力 + # -------------------------------------------------------------------- + # 接続タイプ:new 方向:in->out ポリシー:SKIP 接続・切断・Activate・Deactivateテスト1 + # -------------------------------------------------------------------- + case_no = case_no + 1 fout = open(g_test_result_file, 'a') - message = g_mess_header + g_test_case + str(case_no) + " " + g_test_cnt + str(i+1) + g_mess_footer - # bret==True なら送受信データ一致 - if bret == True: - # テスト結果 OK - message = message + g_test_ok - print(message) - fout.write(message + '\n') - else: - # テスト結果 NG - message = message + g_test_ng - print(message) - message = message + g_test_ng_message - fout.write(message + '\n') - # 受信データをテスト結果ファイルへコピー - fin2 = open(g_diff_recv_file, 'r') - while(1): - s2 = fin2.readline() - if len(s2) == 0: - break - fout.write(s2) - fin2.close() + message = g_mess_header + g_test_case + str(case_no) + " " + message = message + \ + "Connect(in->out, new,SKIP) -> Activate -> send/recv -> Deactivate -> Disconnect" + message = message + g_mess_footer + fout.write(message + '\n') fout.close() + print(message) - time.sleep(sleep_for_time) + for i in range(loop_count): -##-------------------------------------------------------------------- -## 接続タイプ:new 方向:in->out ポリシー:SKIP 接続・切断・Activate・Deactivateテスト1 -##-------------------------------------------------------------------- -case_no = case_no + 1 -fout = open(g_test_result_file, 'a') -message = g_mess_header + g_test_case + str(case_no) + " " -message = message + "Connect(in->out, new,SKIP) -> Activate -> send/recv -> Deactivate -> Disconnect" -message = message + g_mess_footer -fout.write(message + '\n') -fout.close() -print(message) + # 2 受信データファイル削除 + delete_recv_file() -for i in range(loop_count): + # 1 コネクタープロファイル設定 + make_connecter_profile("new", "SKIP", 1) - ## 2 受信データファイル削除 - delete_recv_file() + # 3 ポート接続 + # データポート1 TimedFloat + ret0 = g_out_ports[g_port1].connect(g_conprof1) - ## 1 コネクタープロファイル設定 - make_connecter_profile("new", "SKIP", 1) + # データポート2 TimedFloatSeq + ret1 = g_out_ports[g_port2].connect(g_conprof2) - ## 3 ポート接続 - # データポート1 TimedFloat - ret0 = g_out_ports[g_port1].connect(g_conprof1) + # サービスポート MyService + ret2 = g_out_ports[g_port3].connect(g_conprof3) - # データポート2 TimedFloatSeq - ret1 = g_out_ports[g_port2].connect(g_conprof2) + # 4 アクティベート + ec_recv[0].activate_component(g_compo_recv.rtc_ref) + time.sleep(sleep_recv_act_time) + ec_send[0].activate_component(g_compo_send.rtc_ref) - # サービスポート MyService - ret2 = g_out_ports[g_port3].connect(g_conprof3) + time.sleep(sleep_act_time) - ## 4 アクティベート - ec_recv[0].activate_component(g_compo_recv.rtc_ref) - time.sleep(sleep_recv_act_time) - ec_send[0].activate_component(g_compo_send.rtc_ref) + # 5 ディアクティベート + ec_send[0].deactivate_component(g_compo_send.rtc_ref) + ec_recv[0].deactivate_component(g_compo_recv.rtc_ref) - time.sleep(sleep_act_time) + # 6 ポート切断 + g_in_ports[g_port3].disconnect(g_conprof3.connector_id) + g_in_ports[g_port2].disconnect(g_conprof2.connector_id) + g_in_ports[g_port1].disconnect(g_conprof1.connector_id) - ## 5 ディアクティベート - ec_send[0].deactivate_component(g_compo_send.rtc_ref) - ec_recv[0].deactivate_component(g_compo_recv.rtc_ref) + # 受信ファイル有無判定 + if os.path.isfile(g_diff_recv_file) == False: + fout = open(g_test_result_file, 'a') + message = g_mess_header + g_test_case + \ + str(case_no) + " " + g_test_cnt + str(i + 1) + g_mess_footer + message = message + g_check_message + fout.write(message + '\n') + fout.close() + print(message) + time.sleep(sleep_for_time) + continue - ## 6 ポート切断 - g_in_ports[g_port3].disconnect(g_conprof3.connector_id) - g_in_ports[g_port2].disconnect(g_conprof2.connector_id) - g_in_ports[g_port1].disconnect(g_conprof1.connector_id) + # 7 送受信データ比較 + time.sleep(sleep_act_time) + bret = diff_file() - ## 受信ファイル有無判定 - if os.path.isfile(g_diff_recv_file) == False: + # 差分ファイルからテスト結果出力 fout = open(g_test_result_file, 'a') - message = g_mess_header + g_test_case + str(case_no) + " " + g_test_cnt + str(i+1) + g_mess_footer - message = message + g_check_message - fout.write(message + '\n') + message = g_mess_header + g_test_case + \ + str(case_no) + " " + g_test_cnt + str(i + 1) + g_mess_footer + # bret==True なら送受信データ一致 + if bret == True: + # テスト結果 OK + message = message + g_test_ok + print(message) + fout.write(message + '\n') + else: + # テスト結果 NG + message = message + g_test_ng + print(message) + message = message + g_test_ng_message + fout.write(message + '\n') + # 受信データをテスト結果ファイルへコピー + fin2 = open(g_diff_recv_file, 'r') + while(1): + s2 = fin2.readline() + if len(s2) == 0: + break + fout.write(s2) + fin2.close() fout.close() - print(message) - time.sleep(sleep_for_time) - continue - ## 7 送受信データ比較 - time.sleep(sleep_act_time) - bret = diff_file() + time.sleep(sleep_for_time) - ## 差分ファイルからテスト結果出力 + # -------------------------------------------------------------------- + # -------------------------------------------------------------------- + # 接続タイプ:periodic 方向:out->in ポリシー:ALL 接続・切断テスト7 + # -------------------------------------------------------------------- + case_no = case_no + 1 fout = open(g_test_result_file, 'a') - message = g_mess_header + g_test_case + str(case_no) + " " + g_test_cnt + str(i+1) + g_mess_footer - # bret==True なら送受信データ一致 - if bret == True: - # テスト結果 OK - message = message + g_test_ok - print(message) - fout.write(message + '\n') - else: - # テスト結果 NG - message = message + g_test_ng - print(message) - message = message + g_test_ng_message - fout.write(message + '\n') - # 受信データをテスト結果ファイルへコピー - fin2 = open(g_diff_recv_file, 'r') - while(1): - s2 = fin2.readline() - if len(s2) == 0: - break - fout.write(s2) - fin2.close() + message = g_mess_header + g_test_case + str(case_no) + " " + message = message + "Connect(out->in, periodic,ALL) -> Disconnect" + message = message + g_mess_footer + fout.write(message + '\n') fout.close() + print(message) - time.sleep(sleep_for_time) + for i in range(loop_count): -##-------------------------------------------------------------------- -##-------------------------------------------------------------------- -## 接続タイプ:periodic 方向:out->in ポリシー:ALL 接続・切断テスト7 -##-------------------------------------------------------------------- -case_no = case_no + 1 -fout = open(g_test_result_file, 'a') -message = g_mess_header + g_test_case + str(case_no) + " " -message = message + "Connect(out->in, periodic,ALL) -> Disconnect" -message = message + g_mess_footer -fout.write(message + '\n') -fout.close() -print(message) + # 1 コネクタープロファイル設定 + make_connecter_profile("periodic", "ALL", 0) -for i in range(loop_count): + # 3 ポート接続 + # データポート1 TimedFloat + ret0 = g_out_ports[g_port1].connect(g_conprof1) - ## 1 コネクタープロファイル設定 - make_connecter_profile("periodic", "ALL", 0) + # データポート2 TimedFloatSeq + ret1 = g_out_ports[g_port2].connect(g_conprof2) - ## 3 ポート接続 - # データポート1 TimedFloat - ret0 = g_out_ports[g_port1].connect(g_conprof1) + # サービスポート MyService + ret2 = g_out_ports[g_port3].connect(g_conprof3) - # データポート2 TimedFloatSeq - ret1 = g_out_ports[g_port2].connect(g_conprof2) + time.sleep(sleep_connect_time) - # サービスポート MyService - ret2 = g_out_ports[g_port3].connect(g_conprof3) + # 6 ポート切断 + g_in_ports[g_port3].disconnect(g_conprof3.connector_id) + g_in_ports[g_port2].disconnect(g_conprof2.connector_id) + g_in_ports[g_port1].disconnect(g_conprof1.connector_id) - time.sleep(sleep_connect_time) + # テスト結果出力 + fout = open(g_test_result_file, 'a') + message = g_mess_header + g_test_case + \ + str(case_no) + " " + g_test_cnt + str(i + 1) + g_mess_footer + message = message + g_test_ok + print(message) + fout.write(message + '\n') + fout.close() - ## 6 ポート切断 - g_in_ports[g_port3].disconnect(g_conprof3.connector_id) - g_in_ports[g_port2].disconnect(g_conprof2.connector_id) - g_in_ports[g_port1].disconnect(g_conprof1.connector_id) + time.sleep(sleep_for_time) - ## テスト結果出力 + # -------------------------------------------------------------------- + # 接続タイプ:periodic 方向:out->in ポリシー:FIFO 接続・切断テスト8 + # -------------------------------------------------------------------- + case_no = case_no + 1 fout = open(g_test_result_file, 'a') - message = g_mess_header + g_test_case + str(case_no) + " " + g_test_cnt + str(i+1) + g_mess_footer - message = message + g_test_ok - print(message) + message = g_mess_header + g_test_case + str(case_no) + " " + message = message + "Connect(out->in, periodic,FIFO) -> Disconnect" + message = message + g_mess_footer fout.write(message + '\n') fout.close() + print(message) - time.sleep(sleep_for_time) + for i in range(loop_count): -##-------------------------------------------------------------------- -## 接続タイプ:periodic 方向:out->in ポリシー:FIFO 接続・切断テスト8 -##-------------------------------------------------------------------- -case_no = case_no + 1 -fout = open(g_test_result_file, 'a') -message = g_mess_header + g_test_case + str(case_no) + " " -message = message + "Connect(out->in, periodic,FIFO) -> Disconnect" -message = message + g_mess_footer -fout.write(message + '\n') -fout.close() -print(message) + # 1 コネクタープロファイル設定 + make_connecter_profile("periodic", "FIFO", 0) -for i in range(loop_count): + # 3 ポート接続 + # データポート1 TimedFloat + ret0 = g_out_ports[g_port1].connect(g_conprof1) - ## 1 コネクタープロファイル設定 - make_connecter_profile("periodic", "FIFO", 0) + # データポート2 TimedFloatSeq + ret1 = g_out_ports[g_port2].connect(g_conprof2) - ## 3 ポート接続 - # データポート1 TimedFloat - ret0 = g_out_ports[g_port1].connect(g_conprof1) + # サービスポート MyService + ret2 = g_out_ports[g_port3].connect(g_conprof3) - # データポート2 TimedFloatSeq - ret1 = g_out_ports[g_port2].connect(g_conprof2) + time.sleep(sleep_connect_time) - # サービスポート MyService - ret2 = g_out_ports[g_port3].connect(g_conprof3) + # 6 ポート切断 + g_in_ports[g_port3].disconnect(g_conprof3.connector_id) + g_in_ports[g_port2].disconnect(g_conprof2.connector_id) + g_in_ports[g_port1].disconnect(g_conprof1.connector_id) - time.sleep(sleep_connect_time) + # テスト結果出力 + fout = open(g_test_result_file, 'a') + message = g_mess_header + g_test_case + \ + str(case_no) + " " + g_test_cnt + str(i + 1) + g_mess_footer + message = message + g_test_ok + print(message) + fout.write(message + '\n') + fout.close() - ## 6 ポート切断 - g_in_ports[g_port3].disconnect(g_conprof3.connector_id) - g_in_ports[g_port2].disconnect(g_conprof2.connector_id) - g_in_ports[g_port1].disconnect(g_conprof1.connector_id) + time.sleep(sleep_for_time) - ## テスト結果出力 + # -------------------------------------------------------------------- + # 接続タイプ:periodic 方向:out->in ポリシー:NEW 接続・切断テスト10 + # -------------------------------------------------------------------- + case_no = case_no + 1 fout = open(g_test_result_file, 'a') - message = g_mess_header + g_test_case + str(case_no) + " " + g_test_cnt + str(i+1) + g_mess_footer - message = message + g_test_ok - print(message) + message = g_mess_header + g_test_case + str(case_no) + " " + message = message + "Connect(out->in, periodic,NEW) -> Disconnect" + message = message + g_mess_footer fout.write(message + '\n') fout.close() + print(message) - time.sleep(sleep_for_time) + for i in range(loop_count): -##-------------------------------------------------------------------- -## 接続タイプ:periodic 方向:out->in ポリシー:NEW 接続・切断テスト10 -##-------------------------------------------------------------------- -case_no = case_no + 1 -fout = open(g_test_result_file, 'a') -message = g_mess_header + g_test_case + str(case_no) + " " -message = message + "Connect(out->in, periodic,NEW) -> Disconnect" -message = message + g_mess_footer -fout.write(message + '\n') -fout.close() -print(message) + # 1 コネクタープロファイル設定 + make_connecter_profile("periodic", "NEW", 0) -for i in range(loop_count): + # 3 ポート接続 + # データポート1 TimedFloat + ret0 = g_out_ports[g_port1].connect(g_conprof1) - ## 1 コネクタープロファイル設定 - make_connecter_profile("periodic", "NEW", 0) + # データポート2 TimedFloatSeq + ret1 = g_out_ports[g_port2].connect(g_conprof2) - ## 3 ポート接続 - # データポート1 TimedFloat - ret0 = g_out_ports[g_port1].connect(g_conprof1) + # サービスポート MyService + ret2 = g_out_ports[g_port3].connect(g_conprof3) - # データポート2 TimedFloatSeq - ret1 = g_out_ports[g_port2].connect(g_conprof2) + time.sleep(sleep_connect_time) - # サービスポート MyService - ret2 = g_out_ports[g_port3].connect(g_conprof3) + # 6 ポート切断 + g_in_ports[g_port3].disconnect(g_conprof3.connector_id) + g_in_ports[g_port2].disconnect(g_conprof2.connector_id) + g_in_ports[g_port1].disconnect(g_conprof1.connector_id) - time.sleep(sleep_connect_time) + # テスト結果出力 + fout = open(g_test_result_file, 'a') + message = g_mess_header + g_test_case + \ + str(case_no) + " " + g_test_cnt + str(i + 1) + g_mess_footer + message = message + g_test_ok + print(message) + fout.write(message + '\n') + fout.close() - ## 6 ポート切断 - g_in_ports[g_port3].disconnect(g_conprof3.connector_id) - g_in_ports[g_port2].disconnect(g_conprof2.connector_id) - g_in_ports[g_port1].disconnect(g_conprof1.connector_id) + time.sleep(sleep_for_time) - ## テスト結果出力 + # -------------------------------------------------------------------- + # 接続タイプ:periodic 方向:out->in ポリシー:SKIP 接続・切断テスト9 + # -------------------------------------------------------------------- + case_no = case_no + 1 fout = open(g_test_result_file, 'a') - message = g_mess_header + g_test_case + str(case_no) + " " + g_test_cnt + str(i+1) + g_mess_footer - message = message + g_test_ok - print(message) + message = g_mess_header + g_test_case + str(case_no) + " " + message = message + "Connect(out->in, periodic,SKIP) -> Disconnect" + message = message + g_mess_footer fout.write(message + '\n') fout.close() + print(message) - time.sleep(sleep_for_time) + for i in range(loop_count): -##-------------------------------------------------------------------- -## 接続タイプ:periodic 方向:out->in ポリシー:SKIP 接続・切断テスト9 -##-------------------------------------------------------------------- -case_no = case_no + 1 -fout = open(g_test_result_file, 'a') -message = g_mess_header + g_test_case + str(case_no) + " " -message = message + "Connect(out->in, periodic,SKIP) -> Disconnect" -message = message + g_mess_footer -fout.write(message + '\n') -fout.close() -print(message) + # 1 コネクタープロファイル設定 + make_connecter_profile("periodic", "SKIP", 0) -for i in range(loop_count): + # 3 ポート接続 + # データポート1 TimedFloat + ret0 = g_out_ports[g_port1].connect(g_conprof1) - ## 1 コネクタープロファイル設定 - make_connecter_profile("periodic", "SKIP", 0) + # データポート2 TimedFloatSeq + ret1 = g_out_ports[g_port2].connect(g_conprof2) - ## 3 ポート接続 - # データポート1 TimedFloat - ret0 = g_out_ports[g_port1].connect(g_conprof1) + # サービスポート MyService + ret2 = g_out_ports[g_port3].connect(g_conprof3) - # データポート2 TimedFloatSeq - ret1 = g_out_ports[g_port2].connect(g_conprof2) + time.sleep(sleep_connect_time) - # サービスポート MyService - ret2 = g_out_ports[g_port3].connect(g_conprof3) + # 6 ポート切断 + g_in_ports[g_port3].disconnect(g_conprof3.connector_id) + g_in_ports[g_port2].disconnect(g_conprof2.connector_id) + g_in_ports[g_port1].disconnect(g_conprof1.connector_id) - time.sleep(sleep_connect_time) + # テスト結果出力 + fout = open(g_test_result_file, 'a') + message = g_mess_header + g_test_case + \ + str(case_no) + " " + g_test_cnt + str(i + 1) + g_mess_footer + message = message + g_test_ok + print(message) + fout.write(message + '\n') + fout.close() - ## 6 ポート切断 - g_in_ports[g_port3].disconnect(g_conprof3.connector_id) - g_in_ports[g_port2].disconnect(g_conprof2.connector_id) - g_in_ports[g_port1].disconnect(g_conprof1.connector_id) + time.sleep(sleep_for_time) - ## テスト結果出力 + # -------------------------------------------------------------------- + # 接続タイプ:periodic 方向:in->out ポリシー:ALL 接続・切断テスト7 + # -------------------------------------------------------------------- + case_no = case_no + 1 fout = open(g_test_result_file, 'a') - message = g_mess_header + g_test_case + str(case_no) + " " + g_test_cnt + str(i+1) + g_mess_footer - message = message + g_test_ok - print(message) + message = g_mess_header + g_test_case + str(case_no) + " " + message = message + "Connect(in->out, periodic,ALL) -> Disconnect" + message = message + g_mess_footer fout.write(message + '\n') fout.close() + print(message) - time.sleep(sleep_for_time) + for i in range(loop_count): -##-------------------------------------------------------------------- -## 接続タイプ:periodic 方向:in->out ポリシー:ALL 接続・切断テスト7 -##-------------------------------------------------------------------- -case_no = case_no + 1 -fout = open(g_test_result_file, 'a') -message = g_mess_header + g_test_case + str(case_no) + " " -message = message + "Connect(in->out, periodic,ALL) -> Disconnect" -message = message + g_mess_footer -fout.write(message + '\n') -fout.close() -print(message) + # 1 コネクタープロファイル設定 + make_connecter_profile("periodic", "ALL", 1) -for i in range(loop_count): + # 3 ポート接続 + # データポート1 TimedFloat + ret0 = g_out_ports[g_port1].connect(g_conprof1) - ## 1 コネクタープロファイル設定 - make_connecter_profile("periodic", "ALL", 1) + # データポート2 TimedFloatSeq + ret1 = g_out_ports[g_port2].connect(g_conprof2) - ## 3 ポート接続 - # データポート1 TimedFloat - ret0 = g_out_ports[g_port1].connect(g_conprof1) + # サービスポート MyService + ret2 = g_out_ports[g_port3].connect(g_conprof3) - # データポート2 TimedFloatSeq - ret1 = g_out_ports[g_port2].connect(g_conprof2) + time.sleep(sleep_connect_time) - # サービスポート MyService - ret2 = g_out_ports[g_port3].connect(g_conprof3) + # 6 ポート切断 + g_in_ports[g_port3].disconnect(g_conprof3.connector_id) + g_in_ports[g_port2].disconnect(g_conprof2.connector_id) + g_in_ports[g_port1].disconnect(g_conprof1.connector_id) - time.sleep(sleep_connect_time) + # テスト結果出力 + fout = open(g_test_result_file, 'a') + message = g_mess_header + g_test_case + \ + str(case_no) + " " + g_test_cnt + str(i + 1) + g_mess_footer + message = message + g_test_ok + print(message) + fout.write(message + '\n') + fout.close() - ## 6 ポート切断 - g_in_ports[g_port3].disconnect(g_conprof3.connector_id) - g_in_ports[g_port2].disconnect(g_conprof2.connector_id) - g_in_ports[g_port1].disconnect(g_conprof1.connector_id) + time.sleep(sleep_for_time) - ## テスト結果出力 + # -------------------------------------------------------------------- + # 接続タイプ:periodic 方向:in->out ポリシー:FIFO 接続・切断テスト8 + # -------------------------------------------------------------------- + case_no = case_no + 1 fout = open(g_test_result_file, 'a') - message = g_mess_header + g_test_case + str(case_no) + " " + g_test_cnt + str(i+1) + g_mess_footer - message = message + g_test_ok - print(message) + message = g_mess_header + g_test_case + str(case_no) + " " + message = message + "Connect(in->out, periodic,FIFO) -> Disconnect" + message = message + g_mess_footer fout.write(message + '\n') fout.close() + print(message) - time.sleep(sleep_for_time) + for i in range(loop_count): -##-------------------------------------------------------------------- -## 接続タイプ:periodic 方向:in->out ポリシー:FIFO 接続・切断テスト8 -##-------------------------------------------------------------------- -case_no = case_no + 1 -fout = open(g_test_result_file, 'a') -message = g_mess_header + g_test_case + str(case_no) + " " -message = message + "Connect(in->out, periodic,FIFO) -> Disconnect" -message = message + g_mess_footer -fout.write(message + '\n') -fout.close() -print(message) + # 1 コネクタープロファイル設定 + make_connecter_profile("periodic", "FIFO", 1) -for i in range(loop_count): + # 3 ポート接続 + # データポート1 TimedFloat + ret0 = g_out_ports[g_port1].connect(g_conprof1) - ## 1 コネクタープロファイル設定 - make_connecter_profile("periodic", "FIFO", 1) + # データポート2 TimedFloatSeq + ret1 = g_out_ports[g_port2].connect(g_conprof2) - ## 3 ポート接続 - # データポート1 TimedFloat - ret0 = g_out_ports[g_port1].connect(g_conprof1) + # サービスポート MyService + ret2 = g_out_ports[g_port3].connect(g_conprof3) - # データポート2 TimedFloatSeq - ret1 = g_out_ports[g_port2].connect(g_conprof2) + time.sleep(sleep_connect_time) - # サービスポート MyService - ret2 = g_out_ports[g_port3].connect(g_conprof3) + # 6 ポート切断 + g_in_ports[g_port3].disconnect(g_conprof3.connector_id) + g_in_ports[g_port2].disconnect(g_conprof2.connector_id) + g_in_ports[g_port1].disconnect(g_conprof1.connector_id) - time.sleep(sleep_connect_time) + # テスト結果出力 + fout = open(g_test_result_file, 'a') + message = g_mess_header + g_test_case + \ + str(case_no) + " " + g_test_cnt + str(i + 1) + g_mess_footer + message = message + g_test_ok + print(message) + fout.write(message + '\n') + fout.close() - ## 6 ポート切断 - g_in_ports[g_port3].disconnect(g_conprof3.connector_id) - g_in_ports[g_port2].disconnect(g_conprof2.connector_id) - g_in_ports[g_port1].disconnect(g_conprof1.connector_id) + time.sleep(sleep_for_time) - ## テスト結果出力 + # -------------------------------------------------------------------- + # 接続タイプ:periodic 方向:in->out ポリシー:NEW 接続・切断テスト10 + # -------------------------------------------------------------------- + case_no = case_no + 1 fout = open(g_test_result_file, 'a') - message = g_mess_header + g_test_case + str(case_no) + " " + g_test_cnt + str(i+1) + g_mess_footer - message = message + g_test_ok - print(message) + message = g_mess_header + g_test_case + str(case_no) + " " + message = message + "Connect(in->out, periodic,NEW) -> Disconnect" + message = message + g_mess_footer fout.write(message + '\n') fout.close() + print(message) - time.sleep(sleep_for_time) + for i in range(loop_count): -##-------------------------------------------------------------------- -## 接続タイプ:periodic 方向:in->out ポリシー:NEW 接続・切断テスト10 -##-------------------------------------------------------------------- -case_no = case_no + 1 -fout = open(g_test_result_file, 'a') -message = g_mess_header + g_test_case + str(case_no) + " " -message = message + "Connect(in->out, periodic,NEW) -> Disconnect" -message = message + g_mess_footer -fout.write(message + '\n') -fout.close() -print(message) + # 1 コネクタープロファイル設定 + make_connecter_profile("periodic", "NEW", 1) -for i in range(loop_count): + # 3 ポート接続 + # データポート1 TimedFloat + ret0 = g_out_ports[g_port1].connect(g_conprof1) - ## 1 コネクタープロファイル設定 - make_connecter_profile("periodic", "NEW", 1) + # データポート2 TimedFloatSeq + ret1 = g_out_ports[g_port2].connect(g_conprof2) - ## 3 ポート接続 - # データポート1 TimedFloat - ret0 = g_out_ports[g_port1].connect(g_conprof1) + # サービスポート MyService + ret2 = g_out_ports[g_port3].connect(g_conprof3) - # データポート2 TimedFloatSeq - ret1 = g_out_ports[g_port2].connect(g_conprof2) + time.sleep(sleep_connect_time) - # サービスポート MyService - ret2 = g_out_ports[g_port3].connect(g_conprof3) + # 6 ポート切断 + g_in_ports[g_port3].disconnect(g_conprof3.connector_id) + g_in_ports[g_port2].disconnect(g_conprof2.connector_id) + g_in_ports[g_port1].disconnect(g_conprof1.connector_id) - time.sleep(sleep_connect_time) + # テスト結果出力 + fout = open(g_test_result_file, 'a') + message = g_mess_header + g_test_case + \ + str(case_no) + " " + g_test_cnt + str(i + 1) + g_mess_footer + message = message + g_test_ok + print(message) + fout.write(message + '\n') + fout.close() - ## 6 ポート切断 - g_in_ports[g_port3].disconnect(g_conprof3.connector_id) - g_in_ports[g_port2].disconnect(g_conprof2.connector_id) - g_in_ports[g_port1].disconnect(g_conprof1.connector_id) + time.sleep(sleep_for_time) - ## テスト結果出力 + # -------------------------------------------------------------------- + # 接続タイプ:periodic 方向:in->out ポリシー:SKIP 接続・切断テスト9 + # -------------------------------------------------------------------- + case_no = case_no + 1 fout = open(g_test_result_file, 'a') - message = g_mess_header + g_test_case + str(case_no) + " " + g_test_cnt + str(i+1) + g_mess_footer - message = message + g_test_ok - print(message) + message = g_mess_header + g_test_case + str(case_no) + " " + message = message + "Connect(in->out, periodic,SKIP) -> Disconnect" + message = message + g_mess_footer fout.write(message + '\n') fout.close() + print(message) - time.sleep(sleep_for_time) + for i in range(loop_count): -##-------------------------------------------------------------------- -## 接続タイプ:periodic 方向:in->out ポリシー:SKIP 接続・切断テスト9 -##-------------------------------------------------------------------- -case_no = case_no + 1 -fout = open(g_test_result_file, 'a') -message = g_mess_header + g_test_case + str(case_no) + " " -message = message + "Connect(in->out, periodic,SKIP) -> Disconnect" -message = message + g_mess_footer -fout.write(message + '\n') -fout.close() -print(message) + # 1 コネクタープロファイル設定 + make_connecter_profile("periodic", "SKIP", 1) -for i in range(loop_count): + # 3 ポート接続 + # データポート1 TimedFloat + ret0 = g_out_ports[g_port1].connect(g_conprof1) - ## 1 コネクタープロファイル設定 - make_connecter_profile("periodic", "SKIP", 1) + # データポート2 TimedFloatSeq + ret1 = g_out_ports[g_port2].connect(g_conprof2) - ## 3 ポート接続 - # データポート1 TimedFloat - ret0 = g_out_ports[g_port1].connect(g_conprof1) + # サービスポート MyService + ret2 = g_out_ports[g_port3].connect(g_conprof3) - # データポート2 TimedFloatSeq - ret1 = g_out_ports[g_port2].connect(g_conprof2) + time.sleep(sleep_connect_time) - # サービスポート MyService - ret2 = g_out_ports[g_port3].connect(g_conprof3) + # 6 ポート切断 + g_in_ports[g_port3].disconnect(g_conprof3.connector_id) + g_in_ports[g_port2].disconnect(g_conprof2.connector_id) + g_in_ports[g_port1].disconnect(g_conprof1.connector_id) - time.sleep(sleep_connect_time) + # テスト結果出力 + fout = open(g_test_result_file, 'a') + message = g_mess_header + g_test_case + \ + str(case_no) + " " + g_test_cnt + str(i + 1) + g_mess_footer + message = message + g_test_ok + print(message) + fout.write(message + '\n') + fout.close() - ## 6 ポート切断 - g_in_ports[g_port3].disconnect(g_conprof3.connector_id) - g_in_ports[g_port2].disconnect(g_conprof2.connector_id) - g_in_ports[g_port1].disconnect(g_conprof1.connector_id) + time.sleep(sleep_for_time) - ## テスト結果出力 + # -------------------------------------------------------------------- + # 接続タイプ:periodic 方向:out->in ポリシー:ALL Activate・Deactivateテスト6 + # -------------------------------------------------------------------- + case_no = case_no + 1 fout = open(g_test_result_file, 'a') - message = g_mess_header + g_test_case + str(case_no) + " " + g_test_cnt + str(i+1) + g_mess_footer - message = message + g_test_ok - print(message) + message = g_mess_header + g_test_case + str(case_no) + " " + message = message + \ + "Connecting(out->in, periodic,ALL), Activate -> send/recv -> Deactivate" + message = message + g_mess_footer fout.write(message + '\n') fout.close() + print(message) - time.sleep(sleep_for_time) + # 1 コネクタープロファイル設定 + make_connecter_profile("periodic", "ALL", 0) -##-------------------------------------------------------------------- -## 接続タイプ:periodic 方向:out->in ポリシー:ALL Activate・Deactivateテスト6 -##-------------------------------------------------------------------- -case_no = case_no + 1 -fout = open(g_test_result_file, 'a') -message = g_mess_header + g_test_case + str(case_no) + " " -message = message + "Connecting(out->in, periodic,ALL), Activate -> send/recv -> Deactivate" -message = message + g_mess_footer -fout.write(message + '\n') -fout.close() -print(message) + # 3 ポート接続 + # データポート1 TimedFloat + ret0 = g_out_ports[g_port1].connect(g_conprof1) -## 1 コネクタープロファイル設定 -make_connecter_profile("periodic", "ALL", 0) + # データポート2 TimedFloatSeq + ret1 = g_out_ports[g_port2].connect(g_conprof2) -## 3 ポート接続 -# データポート1 TimedFloat -ret0 = g_out_ports[g_port1].connect(g_conprof1) + # サービスポート MyService + ret2 = g_out_ports[g_port3].connect(g_conprof3) -# データポート2 TimedFloatSeq -ret1 = g_out_ports[g_port2].connect(g_conprof2) + for i in range(loop_count): -# サービスポート MyService -ret2 = g_out_ports[g_port3].connect(g_conprof3) + # 2 受信データファイル削除 + delete_recv_file() -for i in range(loop_count): + # 4 アクティベート + ec_recv[0].activate_component(g_compo_recv.rtc_ref) + time.sleep(sleep_recv_act_time) + ec_send[0].activate_component(g_compo_send.rtc_ref) - ## 2 受信データファイル削除 - delete_recv_file() + time.sleep(sleep_act_time) - ## 4 アクティベート - ec_recv[0].activate_component(g_compo_recv.rtc_ref) - time.sleep(sleep_recv_act_time) - ec_send[0].activate_component(g_compo_send.rtc_ref) + # 5 ディアクティベート + ec_send[0].deactivate_component(g_compo_send.rtc_ref) + ec_recv[0].deactivate_component(g_compo_recv.rtc_ref) - time.sleep(sleep_act_time) + # 受信ファイル有無判定 + if os.path.isfile(g_diff_recv_file) == False: + fout = open(g_test_result_file, 'a') + message = g_mess_header + g_test_case + \ + str(case_no) + " " + g_test_cnt + str(i + 1) + g_mess_footer + message = message + g_check_message + fout.write(message + '\n') + fout.close() + print(message) + time.sleep(sleep_for_time) + continue - ## 5 ディアクティベート - ec_send[0].deactivate_component(g_compo_send.rtc_ref) - ec_recv[0].deactivate_component(g_compo_recv.rtc_ref) + # 7 送受信データ比較 + time.sleep(sleep_act_time) + bret = diff_file() - ## 受信ファイル有無判定 - if os.path.isfile(g_diff_recv_file) == False: + # 差分ファイルからテスト結果出力 fout = open(g_test_result_file, 'a') - message = g_mess_header + g_test_case + str(case_no) + " " + g_test_cnt + str(i+1) + g_mess_footer - message = message + g_check_message - fout.write(message + '\n') + message = g_mess_header + g_test_case + \ + str(case_no) + " " + g_test_cnt + str(i + 1) + g_mess_footer + # bret==True なら送受信データ一致 + if bret == True: + # テスト結果 OK + message = message + g_test_ok + print(message) + fout.write(message + '\n') + else: + # テスト結果 NG + message = message + g_test_ng + print(message) + message = message + g_test_ng_message + fout.write(message + '\n') + # 受信データをテスト結果ファイルへコピー + fin2 = open(g_diff_recv_file, 'r') + while(1): + s2 = fin2.readline() + if len(s2) == 0: + break + fout.write(s2) + fin2.close() fout.close() - print(message) + time.sleep(sleep_for_time) - continue - ## 7 送受信データ比較 - time.sleep(sleep_act_time) - bret = diff_file() + # 6 ポート切断 + g_in_ports[g_port3].disconnect(g_conprof3.connector_id) + g_in_ports[g_port2].disconnect(g_conprof2.connector_id) + g_in_ports[g_port1].disconnect(g_conprof1.connector_id) - ## 差分ファイルからテスト結果出力 + # -------------------------------------------------------------------- + # 接続タイプ:periodic 方向:out->in ポリシー:FIFO Activate・Deactivateテスト7 + # -------------------------------------------------------------------- + case_no = case_no + 1 fout = open(g_test_result_file, 'a') - message = g_mess_header + g_test_case + str(case_no) + " " + g_test_cnt + str(i+1) + g_mess_footer - # bret==True なら送受信データ一致 - if bret == True: - # テスト結果 OK - message = message + g_test_ok - print(message) - fout.write(message + '\n') - else: - # テスト結果 NG - message = message + g_test_ng - print(message) - message = message + g_test_ng_message - fout.write(message + '\n') - # 受信データをテスト結果ファイルへコピー - fin2 = open(g_diff_recv_file, 'r') - while(1): - s2 = fin2.readline() - if len(s2) == 0: - break - fout.write(s2) - fin2.close() + message = g_mess_header + g_test_case + str(case_no) + " " + message = message + \ + "Connecting(out->in, periodic,FIFO), Activate -> send/recv -> Deactivate" + message = message + g_mess_footer + fout.write(message + '\n') fout.close() + print(message) - time.sleep(sleep_for_time) - -## 6 ポート切断 -g_in_ports[g_port3].disconnect(g_conprof3.connector_id) -g_in_ports[g_port2].disconnect(g_conprof2.connector_id) -g_in_ports[g_port1].disconnect(g_conprof1.connector_id) + # 1 コネクタープロファイル設定 + make_connecter_profile("periodic", "FIFO", 0) -##-------------------------------------------------------------------- -## 接続タイプ:periodic 方向:out->in ポリシー:FIFO Activate・Deactivateテスト7 -##-------------------------------------------------------------------- -case_no = case_no + 1 -fout = open(g_test_result_file, 'a') -message = g_mess_header + g_test_case + str(case_no) + " " -message = message + "Connecting(out->in, periodic,FIFO), Activate -> send/recv -> Deactivate" -message = message + g_mess_footer -fout.write(message + '\n') -fout.close() -print(message) + # 3 ポート接続 + # データポート1 TimedFloat + ret0 = g_out_ports[g_port1].connect(g_conprof1) -## 1 コネクタープロファイル設定 -make_connecter_profile("periodic", "FIFO", 0) + # データポート2 TimedFloatSeq + ret1 = g_out_ports[g_port2].connect(g_conprof2) -## 3 ポート接続 -# データポート1 TimedFloat -ret0 = g_out_ports[g_port1].connect(g_conprof1) + # サービスポート MyService + ret2 = g_out_ports[g_port3].connect(g_conprof3) -# データポート2 TimedFloatSeq -ret1 = g_out_ports[g_port2].connect(g_conprof2) + for i in range(loop_count): -# サービスポート MyService -ret2 = g_out_ports[g_port3].connect(g_conprof3) + # 2 受信データファイル削除 + delete_recv_file() -for i in range(loop_count): + # 4 アクティベート + ec_recv[0].activate_component(g_compo_recv.rtc_ref) + time.sleep(sleep_recv_act_time) + ec_send[0].activate_component(g_compo_send.rtc_ref) - ## 2 受信データファイル削除 - delete_recv_file() + time.sleep(sleep_act_time) - ## 4 アクティベート - ec_recv[0].activate_component(g_compo_recv.rtc_ref) - time.sleep(sleep_recv_act_time) - ec_send[0].activate_component(g_compo_send.rtc_ref) + # 5 ディアクティベート + ec_send[0].deactivate_component(g_compo_send.rtc_ref) + ec_recv[0].deactivate_component(g_compo_recv.rtc_ref) - time.sleep(sleep_act_time) + # 受信ファイル有無判定 + if os.path.isfile(g_diff_recv_file) == False: + fout = open(g_test_result_file, 'a') + message = g_mess_header + g_test_case + \ + str(case_no) + " " + g_test_cnt + str(i + 1) + g_mess_footer + message = message + g_check_message + fout.write(message + '\n') + fout.close() + print(message) + time.sleep(sleep_for_time) + continue - ## 5 ディアクティベート - ec_send[0].deactivate_component(g_compo_send.rtc_ref) - ec_recv[0].deactivate_component(g_compo_recv.rtc_ref) + # 7 送受信データ比較 + time.sleep(sleep_act_time) + bret = diff_file() - ## 受信ファイル有無判定 - if os.path.isfile(g_diff_recv_file) == False: + # 差分ファイルからテスト結果出力 fout = open(g_test_result_file, 'a') - message = g_mess_header + g_test_case + str(case_no) + " " + g_test_cnt + str(i+1) + g_mess_footer - message = message + g_check_message - fout.write(message + '\n') + message = g_mess_header + g_test_case + \ + str(case_no) + " " + g_test_cnt + str(i + 1) + g_mess_footer + # bret==True なら送受信データ一致 + if bret == True: + # テスト結果 OK + message = message + g_test_ok + print(message) + fout.write(message + '\n') + else: + # テスト結果 NG + message = message + g_test_ng + print(message) + message = message + g_test_ng_message + fout.write(message + '\n') + # 受信データをテスト結果ファイルへコピー + fin2 = open(g_diff_recv_file, 'r') + while(1): + s2 = fin2.readline() + if len(s2) == 0: + break + fout.write(s2) + fin2.close() fout.close() - print(message) + time.sleep(sleep_for_time) - continue - ## 7 送受信データ比較 - time.sleep(sleep_act_time) - bret = diff_file() + # 6 ポート切断 + g_in_ports[g_port3].disconnect(g_conprof3.connector_id) + g_in_ports[g_port2].disconnect(g_conprof2.connector_id) + g_in_ports[g_port1].disconnect(g_conprof1.connector_id) - ## 差分ファイルからテスト結果出力 + # -------------------------------------------------------------------- + # 接続タイプ:periodic 方向:out->in ポリシー:NEW Activate・Deactivateテスト9 + # -------------------------------------------------------------------- + case_no = case_no + 1 fout = open(g_test_result_file, 'a') - message = g_mess_header + g_test_case + str(case_no) + " " + g_test_cnt + str(i+1) + g_mess_footer - # bret==True なら送受信データ一致 - if bret == True: - # テスト結果 OK - message = message + g_test_ok - print(message) - fout.write(message + '\n') - else: - # テスト結果 NG - message = message + g_test_ng - print(message) - message = message + g_test_ng_message - fout.write(message + '\n') - # 受信データをテスト結果ファイルへコピー - fin2 = open(g_diff_recv_file, 'r') - while(1): - s2 = fin2.readline() - if len(s2) == 0: - break - fout.write(s2) - fin2.close() + message = g_mess_header + g_test_case + str(case_no) + " " + message = message + \ + "Connecting(out->in, periodic,NEW), Activate -> send/recv -> Deactivate" + message = message + g_mess_footer + fout.write(message + '\n') fout.close() + print(message) - time.sleep(sleep_for_time) - -## 6 ポート切断 -g_in_ports[g_port3].disconnect(g_conprof3.connector_id) -g_in_ports[g_port2].disconnect(g_conprof2.connector_id) -g_in_ports[g_port1].disconnect(g_conprof1.connector_id) + # 1 コネクタープロファイル設定 + make_connecter_profile("periodic", "NEW", 0) -##-------------------------------------------------------------------- -## 接続タイプ:periodic 方向:out->in ポリシー:NEW Activate・Deactivateテスト9 -##-------------------------------------------------------------------- -case_no = case_no + 1 -fout = open(g_test_result_file, 'a') -message = g_mess_header + g_test_case + str(case_no) + " " -message = message + "Connecting(out->in, periodic,NEW), Activate -> send/recv -> Deactivate" -message = message + g_mess_footer -fout.write(message + '\n') -fout.close() -print(message) + # 3 ポート接続 + # データポート1 TimedFloat + ret0 = g_out_ports[g_port1].connect(g_conprof1) -## 1 コネクタープロファイル設定 -make_connecter_profile("periodic", "NEW", 0) + # データポート2 TimedFloatSeq + ret1 = g_out_ports[g_port2].connect(g_conprof2) -## 3 ポート接続 -# データポート1 TimedFloat -ret0 = g_out_ports[g_port1].connect(g_conprof1) + # サービスポート MyService + ret2 = g_out_ports[g_port3].connect(g_conprof3) -# データポート2 TimedFloatSeq -ret1 = g_out_ports[g_port2].connect(g_conprof2) + for i in range(loop_count): -# サービスポート MyService -ret2 = g_out_ports[g_port3].connect(g_conprof3) + # 2 受信データファイル削除 + delete_recv_file() -for i in range(loop_count): + # 4 アクティベート + ec_recv[0].activate_component(g_compo_recv.rtc_ref) + time.sleep(sleep_recv_act_time) + ec_send[0].activate_component(g_compo_send.rtc_ref) - ## 2 受信データファイル削除 - delete_recv_file() + time.sleep(sleep_act_time) - ## 4 アクティベート - ec_recv[0].activate_component(g_compo_recv.rtc_ref) - time.sleep(sleep_recv_act_time) - ec_send[0].activate_component(g_compo_send.rtc_ref) + # 5 ディアクティベート + ec_send[0].deactivate_component(g_compo_send.rtc_ref) + ec_recv[0].deactivate_component(g_compo_recv.rtc_ref) - time.sleep(sleep_act_time) + # 受信ファイル有無判定 + if os.path.isfile(g_diff_recv_file) == False: + fout = open(g_test_result_file, 'a') + message = g_mess_header + g_test_case + \ + str(case_no) + " " + g_test_cnt + str(i + 1) + g_mess_footer + message = message + g_check_message + fout.write(message + '\n') + fout.close() + print(message) + time.sleep(sleep_for_time) + continue - ## 5 ディアクティベート - ec_send[0].deactivate_component(g_compo_send.rtc_ref) - ec_recv[0].deactivate_component(g_compo_recv.rtc_ref) + # 7 送受信データ比較 + time.sleep(sleep_act_time) + bret = diff_file() - ## 受信ファイル有無判定 - if os.path.isfile(g_diff_recv_file) == False: + # 差分ファイルからテスト結果出力 fout = open(g_test_result_file, 'a') - message = g_mess_header + g_test_case + str(case_no) + " " + g_test_cnt + str(i+1) + g_mess_footer - message = message + g_check_message - fout.write(message + '\n') + message = g_mess_header + g_test_case + \ + str(case_no) + " " + g_test_cnt + str(i + 1) + g_mess_footer + # bret==True なら送受信データ一致 + if bret == True: + # テスト結果 OK + message = message + g_test_ok + print(message) + fout.write(message + '\n') + else: + # テスト結果 NG + message = message + g_test_ng + print(message) + message = message + g_test_ng_message + fout.write(message + '\n') + # 受信データをテスト結果ファイルへコピー + fin2 = open(g_diff_recv_file, 'r') + while(1): + s2 = fin2.readline() + if len(s2) == 0: + break + fout.write(s2) + fin2.close() fout.close() - print(message) + time.sleep(sleep_for_time) - continue - ## 7 送受信データ比較 - time.sleep(sleep_act_time) - bret = diff_file() + # 6 ポート切断 + g_in_ports[g_port3].disconnect(g_conprof3.connector_id) + g_in_ports[g_port2].disconnect(g_conprof2.connector_id) + g_in_ports[g_port1].disconnect(g_conprof1.connector_id) - ## 差分ファイルからテスト結果出力 + # -------------------------------------------------------------------- + # 接続タイプ:periodic 方向:out->in ポリシー:SKIP Activate・Deactivateテスト8 + # -------------------------------------------------------------------- + case_no = case_no + 1 fout = open(g_test_result_file, 'a') - message = g_mess_header + g_test_case + str(case_no) + " " + g_test_cnt + str(i+1) + g_mess_footer - # bret==True なら送受信データ一致 - if bret == True: - # テスト結果 OK - message = message + g_test_ok - print(message) - fout.write(message + '\n') - else: - # テスト結果 NG - message = message + g_test_ng - print(message) - message = message + g_test_ng_message - fout.write(message + '\n') - # 受信データをテスト結果ファイルへコピー - fin2 = open(g_diff_recv_file, 'r') - while(1): - s2 = fin2.readline() - if len(s2) == 0: - break - fout.write(s2) - fin2.close() + message = g_mess_header + g_test_case + str(case_no) + " " + message = message + \ + "Connecting(out->in, periodic,SKIP), Activate -> send/recv -> Deactivate" + message = message + g_mess_footer + fout.write(message + '\n') fout.close() + print(message) - time.sleep(sleep_for_time) - -## 6 ポート切断 -g_in_ports[g_port3].disconnect(g_conprof3.connector_id) -g_in_ports[g_port2].disconnect(g_conprof2.connector_id) -g_in_ports[g_port1].disconnect(g_conprof1.connector_id) + # 1 コネクタープロファイル設定 + make_connecter_profile("periodic", "SKIP", 0) -##-------------------------------------------------------------------- -## 接続タイプ:periodic 方向:out->in ポリシー:SKIP Activate・Deactivateテスト8 -##-------------------------------------------------------------------- -case_no = case_no + 1 -fout = open(g_test_result_file, 'a') -message = g_mess_header + g_test_case + str(case_no) + " " -message = message + "Connecting(out->in, periodic,SKIP), Activate -> send/recv -> Deactivate" -message = message + g_mess_footer -fout.write(message + '\n') -fout.close() -print(message) + # 3 ポート接続 + # データポート1 TimedFloat + ret0 = g_out_ports[g_port1].connect(g_conprof1) -## 1 コネクタープロファイル設定 -make_connecter_profile("periodic", "SKIP", 0) + # データポート2 TimedFloatSeq + ret1 = g_out_ports[g_port2].connect(g_conprof2) -## 3 ポート接続 -# データポート1 TimedFloat -ret0 = g_out_ports[g_port1].connect(g_conprof1) + # サービスポート MyService + ret2 = g_out_ports[g_port3].connect(g_conprof3) -# データポート2 TimedFloatSeq -ret1 = g_out_ports[g_port2].connect(g_conprof2) + for i in range(loop_count): -# サービスポート MyService -ret2 = g_out_ports[g_port3].connect(g_conprof3) + # 2 受信データファイル削除 + delete_recv_file() -for i in range(loop_count): + # 4 アクティベート + ec_recv[0].activate_component(g_compo_recv.rtc_ref) + time.sleep(sleep_recv_act_time) + ec_send[0].activate_component(g_compo_send.rtc_ref) - ## 2 受信データファイル削除 - delete_recv_file() + time.sleep(sleep_act_time) - ## 4 アクティベート - ec_recv[0].activate_component(g_compo_recv.rtc_ref) - time.sleep(sleep_recv_act_time) - ec_send[0].activate_component(g_compo_send.rtc_ref) + # 5 ディアクティベート + ec_send[0].deactivate_component(g_compo_send.rtc_ref) + ec_recv[0].deactivate_component(g_compo_recv.rtc_ref) - time.sleep(sleep_act_time) + # 受信ファイル有無判定 + if os.path.isfile(g_diff_recv_file) == False: + fout = open(g_test_result_file, 'a') + message = g_mess_header + g_test_case + \ + str(case_no) + " " + g_test_cnt + str(i + 1) + g_mess_footer + message = message + g_check_message + fout.write(message + '\n') + fout.close() + print(message) + time.sleep(sleep_for_time) + continue - ## 5 ディアクティベート - ec_send[0].deactivate_component(g_compo_send.rtc_ref) - ec_recv[0].deactivate_component(g_compo_recv.rtc_ref) + # 7 送受信データ比較 + time.sleep(sleep_act_time) + bret = diff_file() - ## 受信ファイル有無判定 - if os.path.isfile(g_diff_recv_file) == False: + # 差分ファイルからテスト結果出力 fout = open(g_test_result_file, 'a') - message = g_mess_header + g_test_case + str(case_no) + " " + g_test_cnt + str(i+1) + g_mess_footer - message = message + g_check_message - fout.write(message + '\n') + message = g_mess_header + g_test_case + \ + str(case_no) + " " + g_test_cnt + str(i + 1) + g_mess_footer + # bret==True なら送受信データ一致 + if bret == True: + # テスト結果 OK + message = message + g_test_ok + print(message) + fout.write(message + '\n') + else: + # テスト結果 NG + message = message + g_test_ng + print(message) + message = message + g_test_ng_message + fout.write(message + '\n') + # 受信データをテスト結果ファイルへコピー + fin2 = open(g_diff_recv_file, 'r') + while(1): + s2 = fin2.readline() + if len(s2) == 0: + break + fout.write(s2) + fin2.close() fout.close() - print(message) + time.sleep(sleep_for_time) - continue - ## 7 送受信データ比較 - time.sleep(sleep_act_time) - bret = diff_file() + # 6 ポート切断 + g_in_ports[g_port3].disconnect(g_conprof3.connector_id) + g_in_ports[g_port2].disconnect(g_conprof2.connector_id) + g_in_ports[g_port1].disconnect(g_conprof1.connector_id) - ## 差分ファイルからテスト結果出力 + # -------------------------------------------------------------------- + # 接続タイプ:periodic 方向:in->out ポリシー:ALL Activate・Deactivateテスト6 + # -------------------------------------------------------------------- + case_no = case_no + 1 fout = open(g_test_result_file, 'a') - message = g_mess_header + g_test_case + str(case_no) + " " + g_test_cnt + str(i+1) + g_mess_footer - # bret==True なら送受信データ一致 - if bret == True: - # テスト結果 OK - message = message + g_test_ok - print(message) - fout.write(message + '\n') - else: - # テスト結果 NG - message = message + g_test_ng - print(message) - message = message + g_test_ng_message - fout.write(message + '\n') - # 受信データをテスト結果ファイルへコピー - fin2 = open(g_diff_recv_file, 'r') - while(1): - s2 = fin2.readline() - if len(s2) == 0: - break - fout.write(s2) - fin2.close() + message = g_mess_header + g_test_case + str(case_no) + " " + message = message + \ + "Connecting(in->out, periodic,ALL), Activate -> send/recv -> Deactivate" + message = message + g_mess_footer + fout.write(message + '\n') fout.close() + print(message) - time.sleep(sleep_for_time) - -## 6 ポート切断 -g_in_ports[g_port3].disconnect(g_conprof3.connector_id) -g_in_ports[g_port2].disconnect(g_conprof2.connector_id) -g_in_ports[g_port1].disconnect(g_conprof1.connector_id) + # 1 コネクタープロファイル設定 + make_connecter_profile("periodic", "ALL", 1) -##-------------------------------------------------------------------- -## 接続タイプ:periodic 方向:in->out ポリシー:ALL Activate・Deactivateテスト6 -##-------------------------------------------------------------------- -case_no = case_no + 1 -fout = open(g_test_result_file, 'a') -message = g_mess_header + g_test_case + str(case_no) + " " -message = message + "Connecting(in->out, periodic,ALL), Activate -> send/recv -> Deactivate" -message = message + g_mess_footer -fout.write(message + '\n') -fout.close() -print(message) + # 3 ポート接続 + # データポート1 TimedFloat + ret0 = g_out_ports[g_port1].connect(g_conprof1) -## 1 コネクタープロファイル設定 -make_connecter_profile("periodic", "ALL", 1) + # データポート2 TimedFloatSeq + ret1 = g_out_ports[g_port2].connect(g_conprof2) -## 3 ポート接続 -# データポート1 TimedFloat -ret0 = g_out_ports[g_port1].connect(g_conprof1) + # サービスポート MyService + ret2 = g_out_ports[g_port3].connect(g_conprof3) -# データポート2 TimedFloatSeq -ret1 = g_out_ports[g_port2].connect(g_conprof2) + for i in range(loop_count): -# サービスポート MyService -ret2 = g_out_ports[g_port3].connect(g_conprof3) + # 2 受信データファイル削除 + delete_recv_file() -for i in range(loop_count): + # 4 アクティベート + ec_recv[0].activate_component(g_compo_recv.rtc_ref) + time.sleep(sleep_recv_act_time) + ec_send[0].activate_component(g_compo_send.rtc_ref) - ## 2 受信データファイル削除 - delete_recv_file() + time.sleep(sleep_act_time) - ## 4 アクティベート - ec_recv[0].activate_component(g_compo_recv.rtc_ref) - time.sleep(sleep_recv_act_time) - ec_send[0].activate_component(g_compo_send.rtc_ref) + # 5 ディアクティベート + ec_send[0].deactivate_component(g_compo_send.rtc_ref) + ec_recv[0].deactivate_component(g_compo_recv.rtc_ref) - time.sleep(sleep_act_time) + # 受信ファイル有無判定 + if os.path.isfile(g_diff_recv_file) == False: + fout = open(g_test_result_file, 'a') + message = g_mess_header + g_test_case + \ + str(case_no) + " " + g_test_cnt + str(i + 1) + g_mess_footer + message = message + g_check_message + fout.write(message + '\n') + fout.close() + print(message) + time.sleep(sleep_for_time) + continue - ## 5 ディアクティベート - ec_send[0].deactivate_component(g_compo_send.rtc_ref) - ec_recv[0].deactivate_component(g_compo_recv.rtc_ref) + # 7 送受信データ比較 + time.sleep(sleep_act_time) + bret = diff_file() - ## 受信ファイル有無判定 - if os.path.isfile(g_diff_recv_file) == False: + # 差分ファイルからテスト結果出力 fout = open(g_test_result_file, 'a') - message = g_mess_header + g_test_case + str(case_no) + " " + g_test_cnt + str(i+1) + g_mess_footer - message = message + g_check_message - fout.write(message + '\n') + message = g_mess_header + g_test_case + \ + str(case_no) + " " + g_test_cnt + str(i + 1) + g_mess_footer + # bret==True なら送受信データ一致 + if bret == True: + # テスト結果 OK + message = message + g_test_ok + print(message) + fout.write(message + '\n') + else: + # テスト結果 NG + message = message + g_test_ng + print(message) + message = message + g_test_ng_message + fout.write(message + '\n') + # 受信データをテスト結果ファイルへコピー + fin2 = open(g_diff_recv_file, 'r') + while(1): + s2 = fin2.readline() + if len(s2) == 0: + break + fout.write(s2) + fin2.close() fout.close() - print(message) + time.sleep(sleep_for_time) - continue - ## 7 送受信データ比較 - time.sleep(sleep_act_time) - bret = diff_file() + # 6 ポート切断 + g_in_ports[g_port3].disconnect(g_conprof3.connector_id) + g_in_ports[g_port2].disconnect(g_conprof2.connector_id) + g_in_ports[g_port1].disconnect(g_conprof1.connector_id) - ## 差分ファイルからテスト結果出力 + # -------------------------------------------------------------------- + # 接続タイプ:periodic 方向:in->out ポリシー:FIFO Activate・Deactivateテスト7 + # -------------------------------------------------------------------- + case_no = case_no + 1 fout = open(g_test_result_file, 'a') - message = g_mess_header + g_test_case + str(case_no) + " " + g_test_cnt + str(i+1) + g_mess_footer - # bret==True なら送受信データ一致 - if bret == True: - # テスト結果 OK - message = message + g_test_ok - print(message) - fout.write(message + '\n') - else: - # テスト結果 NG - message = message + g_test_ng - print(message) - message = message + g_test_ng_message - fout.write(message + '\n') - # 受信データをテスト結果ファイルへコピー - fin2 = open(g_diff_recv_file, 'r') - while(1): - s2 = fin2.readline() - if len(s2) == 0: - break - fout.write(s2) - fin2.close() + message = g_mess_header + g_test_case + str(case_no) + " " + message = message + \ + "Connecting(in->out, periodic,FIFO), Activate -> send/recv -> Deactivate" + message = message + g_mess_footer + fout.write(message + '\n') fout.close() + print(message) - time.sleep(sleep_for_time) - -## 6 ポート切断 -g_in_ports[g_port3].disconnect(g_conprof3.connector_id) -g_in_ports[g_port2].disconnect(g_conprof2.connector_id) -g_in_ports[g_port1].disconnect(g_conprof1.connector_id) + # 1 コネクタープロファイル設定 + make_connecter_profile("periodic", "FIFO", 1) -##-------------------------------------------------------------------- -## 接続タイプ:periodic 方向:in->out ポリシー:FIFO Activate・Deactivateテスト7 -##-------------------------------------------------------------------- -case_no = case_no + 1 -fout = open(g_test_result_file, 'a') -message = g_mess_header + g_test_case + str(case_no) + " " -message = message + "Connecting(in->out, periodic,FIFO), Activate -> send/recv -> Deactivate" -message = message + g_mess_footer -fout.write(message + '\n') -fout.close() -print(message) + # 3 ポート接続 + # データポート1 TimedFloat + ret0 = g_out_ports[g_port1].connect(g_conprof1) -## 1 コネクタープロファイル設定 -make_connecter_profile("periodic", "FIFO", 1) + # データポート2 TimedFloatSeq + ret1 = g_out_ports[g_port2].connect(g_conprof2) -## 3 ポート接続 -# データポート1 TimedFloat -ret0 = g_out_ports[g_port1].connect(g_conprof1) + # サービスポート MyService + ret2 = g_out_ports[g_port3].connect(g_conprof3) -# データポート2 TimedFloatSeq -ret1 = g_out_ports[g_port2].connect(g_conprof2) + for i in range(loop_count): -# サービスポート MyService -ret2 = g_out_ports[g_port3].connect(g_conprof3) + # 2 受信データファイル削除 + delete_recv_file() -for i in range(loop_count): + # 4 アクティベート + ec_recv[0].activate_component(g_compo_recv.rtc_ref) + time.sleep(sleep_recv_act_time) + ec_send[0].activate_component(g_compo_send.rtc_ref) - ## 2 受信データファイル削除 - delete_recv_file() + time.sleep(sleep_act_time) - ## 4 アクティベート - ec_recv[0].activate_component(g_compo_recv.rtc_ref) - time.sleep(sleep_recv_act_time) - ec_send[0].activate_component(g_compo_send.rtc_ref) + # 5 ディアクティベート + ec_send[0].deactivate_component(g_compo_send.rtc_ref) + ec_recv[0].deactivate_component(g_compo_recv.rtc_ref) - time.sleep(sleep_act_time) + # 受信ファイル有無判定 + if os.path.isfile(g_diff_recv_file) == False: + fout = open(g_test_result_file, 'a') + message = g_mess_header + g_test_case + \ + str(case_no) + " " + g_test_cnt + str(i + 1) + g_mess_footer + message = message + g_check_message + fout.write(message + '\n') + fout.close() + print(message) + time.sleep(sleep_for_time) + continue - ## 5 ディアクティベート - ec_send[0].deactivate_component(g_compo_send.rtc_ref) - ec_recv[0].deactivate_component(g_compo_recv.rtc_ref) + # 7 送受信データ比較 + time.sleep(sleep_act_time) + bret = diff_file() - ## 受信ファイル有無判定 - if os.path.isfile(g_diff_recv_file) == False: + # 差分ファイルからテスト結果出力 fout = open(g_test_result_file, 'a') - message = g_mess_header + g_test_case + str(case_no) + " " + g_test_cnt + str(i+1) + g_mess_footer - message = message + g_check_message - fout.write(message + '\n') + message = g_mess_header + g_test_case + \ + str(case_no) + " " + g_test_cnt + str(i + 1) + g_mess_footer + # bret==True なら送受信データ一致 + if bret == True: + # テスト結果 OK + message = message + g_test_ok + print(message) + fout.write(message + '\n') + else: + # テスト結果 NG + message = message + g_test_ng + print(message) + message = message + g_test_ng_message + fout.write(message + '\n') + # 受信データをテスト結果ファイルへコピー + fin2 = open(g_diff_recv_file, 'r') + while(1): + s2 = fin2.readline() + if len(s2) == 0: + break + fout.write(s2) + fin2.close() fout.close() - print(message) + time.sleep(sleep_for_time) - continue - ## 7 送受信データ比較 - time.sleep(sleep_act_time) - bret = diff_file() + # 6 ポート切断 + g_in_ports[g_port3].disconnect(g_conprof3.connector_id) + g_in_ports[g_port2].disconnect(g_conprof2.connector_id) + g_in_ports[g_port1].disconnect(g_conprof1.connector_id) - ## 差分ファイルからテスト結果出力 + # -------------------------------------------------------------------- + # 接続タイプ:periodic 方向:in->out ポリシー:NEW Activate・Deactivateテスト9 + # -------------------------------------------------------------------- + case_no = case_no + 1 fout = open(g_test_result_file, 'a') - message = g_mess_header + g_test_case + str(case_no) + " " + g_test_cnt + str(i+1) + g_mess_footer - # bret==True なら送受信データ一致 - if bret == True: - # テスト結果 OK - message = message + g_test_ok - print(message) - fout.write(message + '\n') - else: - # テスト結果 NG - message = message + g_test_ng - print(message) - message = message + g_test_ng_message - fout.write(message + '\n') - # 受信データをテスト結果ファイルへコピー - fin2 = open(g_diff_recv_file, 'r') - while(1): - s2 = fin2.readline() - if len(s2) == 0: - break - fout.write(s2) - fin2.close() + message = g_mess_header + g_test_case + str(case_no) + " " + message = message + \ + "Connecting(in->out, periodic,NEW), Activate -> send/recv -> Deactivate" + message = message + g_mess_footer + fout.write(message + '\n') fout.close() + print(message) - time.sleep(sleep_for_time) - -## 6 ポート切断 -g_in_ports[g_port3].disconnect(g_conprof3.connector_id) -g_in_ports[g_port2].disconnect(g_conprof2.connector_id) -g_in_ports[g_port1].disconnect(g_conprof1.connector_id) + # 1 コネクタープロファイル設定 + make_connecter_profile("periodic", "NEW", 1) -##-------------------------------------------------------------------- -## 接続タイプ:periodic 方向:in->out ポリシー:NEW Activate・Deactivateテスト9 -##-------------------------------------------------------------------- -case_no = case_no + 1 -fout = open(g_test_result_file, 'a') -message = g_mess_header + g_test_case + str(case_no) + " " -message = message + "Connecting(in->out, periodic,NEW), Activate -> send/recv -> Deactivate" -message = message + g_mess_footer -fout.write(message + '\n') -fout.close() -print(message) + # 3 ポート接続 + # データポート1 TimedFloat + ret0 = g_out_ports[g_port1].connect(g_conprof1) -## 1 コネクタープロファイル設定 -make_connecter_profile("periodic", "NEW", 1) + # データポート2 TimedFloatSeq + ret1 = g_out_ports[g_port2].connect(g_conprof2) -## 3 ポート接続 -# データポート1 TimedFloat -ret0 = g_out_ports[g_port1].connect(g_conprof1) + # サービスポート MyService + ret2 = g_out_ports[g_port3].connect(g_conprof3) -# データポート2 TimedFloatSeq -ret1 = g_out_ports[g_port2].connect(g_conprof2) + for i in range(loop_count): -# サービスポート MyService -ret2 = g_out_ports[g_port3].connect(g_conprof3) + # 2 受信データファイル削除 + delete_recv_file() -for i in range(loop_count): + # 4 アクティベート + ec_recv[0].activate_component(g_compo_recv.rtc_ref) + time.sleep(sleep_recv_act_time) + ec_send[0].activate_component(g_compo_send.rtc_ref) - ## 2 受信データファイル削除 - delete_recv_file() + time.sleep(sleep_act_time) - ## 4 アクティベート - ec_recv[0].activate_component(g_compo_recv.rtc_ref) - time.sleep(sleep_recv_act_time) - ec_send[0].activate_component(g_compo_send.rtc_ref) + # 5 ディアクティベート + ec_send[0].deactivate_component(g_compo_send.rtc_ref) + ec_recv[0].deactivate_component(g_compo_recv.rtc_ref) - time.sleep(sleep_act_time) + # 受信ファイル有無判定 + if os.path.isfile(g_diff_recv_file) == False: + fout = open(g_test_result_file, 'a') + message = g_mess_header + g_test_case + \ + str(case_no) + " " + g_test_cnt + str(i + 1) + g_mess_footer + message = message + g_check_message + fout.write(message + '\n') + fout.close() + print(message) + time.sleep(sleep_for_time) + continue - ## 5 ディアクティベート - ec_send[0].deactivate_component(g_compo_send.rtc_ref) - ec_recv[0].deactivate_component(g_compo_recv.rtc_ref) + # 7 送受信データ比較 + time.sleep(sleep_act_time) + bret = diff_file() - ## 受信ファイル有無判定 - if os.path.isfile(g_diff_recv_file) == False: + # 差分ファイルからテスト結果出力 fout = open(g_test_result_file, 'a') - message = g_mess_header + g_test_case + str(case_no) + " " + g_test_cnt + str(i+1) + g_mess_footer - message = message + g_check_message - fout.write(message + '\n') + message = g_mess_header + g_test_case + \ + str(case_no) + " " + g_test_cnt + str(i + 1) + g_mess_footer + # bret==True なら送受信データ一致 + if bret == True: + # テスト結果 OK + message = message + g_test_ok + print(message) + fout.write(message + '\n') + else: + # テスト結果 NG + message = message + g_test_ng + print(message) + message = message + g_test_ng_message + fout.write(message + '\n') + # 受信データをテスト結果ファイルへコピー + fin2 = open(g_diff_recv_file, 'r') + while(1): + s2 = fin2.readline() + if len(s2) == 0: + break + fout.write(s2) + fin2.close() fout.close() - print(message) + time.sleep(sleep_for_time) - continue - ## 7 送受信データ比較 - time.sleep(sleep_act_time) - bret = diff_file() + # 6 ポート切断 + g_in_ports[g_port3].disconnect(g_conprof3.connector_id) + g_in_ports[g_port2].disconnect(g_conprof2.connector_id) + g_in_ports[g_port1].disconnect(g_conprof1.connector_id) - ## 差分ファイルからテスト結果出力 + # -------------------------------------------------------------------- + # 接続タイプ:periodic 方向:in->out ポリシー:SKIP Activate・Deactivateテスト8 + # -------------------------------------------------------------------- + case_no = case_no + 1 fout = open(g_test_result_file, 'a') - message = g_mess_header + g_test_case + str(case_no) + " " + g_test_cnt + str(i+1) + g_mess_footer - # bret==True なら送受信データ一致 - if bret == True: - # テスト結果 OK - message = message + g_test_ok - print(message) - fout.write(message + '\n') - else: - # テスト結果 NG - message = message + g_test_ng - print(message) - message = message + g_test_ng_message - fout.write(message + '\n') - # 受信データをテスト結果ファイルへコピー - fin2 = open(g_diff_recv_file, 'r') - while(1): - s2 = fin2.readline() - if len(s2) == 0: - break - fout.write(s2) - fin2.close() + message = g_mess_header + g_test_case + str(case_no) + " " + message = message + \ + "Connecting(in->out, periodic,SKIP), Activate -> send/recv -> Deactivate" + message = message + g_mess_footer + fout.write(message + '\n') fout.close() + print(message) - time.sleep(sleep_for_time) - -## 6 ポート切断 -g_in_ports[g_port3].disconnect(g_conprof3.connector_id) -g_in_ports[g_port2].disconnect(g_conprof2.connector_id) -g_in_ports[g_port1].disconnect(g_conprof1.connector_id) + # 1 コネクタープロファイル設定 + make_connecter_profile("periodic", "SKIP", 1) -##-------------------------------------------------------------------- -## 接続タイプ:periodic 方向:in->out ポリシー:SKIP Activate・Deactivateテスト8 -##-------------------------------------------------------------------- -case_no = case_no + 1 -fout = open(g_test_result_file, 'a') -message = g_mess_header + g_test_case + str(case_no) + " " -message = message + "Connecting(in->out, periodic,SKIP), Activate -> send/recv -> Deactivate" -message = message + g_mess_footer -fout.write(message + '\n') -fout.close() -print(message) + # 3 ポート接続 + # データポート1 TimedFloat + ret0 = g_out_ports[g_port1].connect(g_conprof1) -## 1 コネクタープロファイル設定 -make_connecter_profile("periodic", "SKIP", 1) + # データポート2 TimedFloatSeq + ret1 = g_out_ports[g_port2].connect(g_conprof2) -## 3 ポート接続 -# データポート1 TimedFloat -ret0 = g_out_ports[g_port1].connect(g_conprof1) + # サービスポート MyService + ret2 = g_out_ports[g_port3].connect(g_conprof3) -# データポート2 TimedFloatSeq -ret1 = g_out_ports[g_port2].connect(g_conprof2) + for i in range(loop_count): -# サービスポート MyService -ret2 = g_out_ports[g_port3].connect(g_conprof3) + # 2 受信データファイル削除 + delete_recv_file() -for i in range(loop_count): + # 4 アクティベート + ec_recv[0].activate_component(g_compo_recv.rtc_ref) + time.sleep(sleep_recv_act_time) + ec_send[0].activate_component(g_compo_send.rtc_ref) - ## 2 受信データファイル削除 - delete_recv_file() + time.sleep(sleep_act_time) - ## 4 アクティベート - ec_recv[0].activate_component(g_compo_recv.rtc_ref) - time.sleep(sleep_recv_act_time) - ec_send[0].activate_component(g_compo_send.rtc_ref) + # 5 ディアクティベート + ec_send[0].deactivate_component(g_compo_send.rtc_ref) + ec_recv[0].deactivate_component(g_compo_recv.rtc_ref) - time.sleep(sleep_act_time) + # 受信ファイル有無判定 + if os.path.isfile(g_diff_recv_file) == False: + fout = open(g_test_result_file, 'a') + message = g_mess_header + g_test_case + \ + str(case_no) + " " + g_test_cnt + str(i + 1) + g_mess_footer + message = message + g_check_message + fout.write(message + '\n') + fout.close() + print(message) + time.sleep(sleep_for_time) + continue - ## 5 ディアクティベート - ec_send[0].deactivate_component(g_compo_send.rtc_ref) - ec_recv[0].deactivate_component(g_compo_recv.rtc_ref) + # 7 送受信データ比較 + time.sleep(sleep_act_time) + bret = diff_file() - ## 受信ファイル有無判定 - if os.path.isfile(g_diff_recv_file) == False: + # 差分ファイルからテスト結果出力 fout = open(g_test_result_file, 'a') - message = g_mess_header + g_test_case + str(case_no) + " " + g_test_cnt + str(i+1) + g_mess_footer - message = message + g_check_message - fout.write(message + '\n') + message = g_mess_header + g_test_case + \ + str(case_no) + " " + g_test_cnt + str(i + 1) + g_mess_footer + # bret==True なら送受信データ一致 + if bret == True: + # テスト結果 OK + message = message + g_test_ok + print(message) + fout.write(message + '\n') + else: + # テスト結果 NG + message = message + g_test_ng + print(message) + message = message + g_test_ng_message + fout.write(message + '\n') + # 受信データをテスト結果ファイルへコピー + fin2 = open(g_diff_recv_file, 'r') + while(1): + s2 = fin2.readline() + if len(s2) == 0: + break + fout.write(s2) + fin2.close() fout.close() - print(message) + time.sleep(sleep_for_time) - continue - ## 7 送受信データ比較 - time.sleep(sleep_act_time) - bret = diff_file() + # 6 ポート切断 + g_in_ports[g_port3].disconnect(g_conprof3.connector_id) + g_in_ports[g_port2].disconnect(g_conprof2.connector_id) + g_in_ports[g_port1].disconnect(g_conprof1.connector_id) - ## 差分ファイルからテスト結果出力 + # -------------------------------------------------------------------- + # 接続タイプ:periodic 方向:out->in ポリシー:ALL 接続・切断・Activate・Deactivateテスト1 + # -------------------------------------------------------------------- + case_no = case_no + 1 fout = open(g_test_result_file, 'a') - message = g_mess_header + g_test_case + str(case_no) + " " + g_test_cnt + str(i+1) + g_mess_footer - # bret==True なら送受信データ一致 - if bret == True: - # テスト結果 OK - message = message + g_test_ok - print(message) - fout.write(message + '\n') - else: - # テスト結果 NG - message = message + g_test_ng - print(message) - message = message + g_test_ng_message - fout.write(message + '\n') - # 受信データをテスト結果ファイルへコピー - fin2 = open(g_diff_recv_file, 'r') - while(1): - s2 = fin2.readline() - if len(s2) == 0: - break - fout.write(s2) - fin2.close() + message = g_mess_header + g_test_case + str(case_no) + " " + message = message + \ + "Connect(out->in, periodic,ALL) -> Activate -> send/recv -> Deactivate -> Disconnect" + message = message + g_mess_footer + fout.write(message + '\n') fout.close() + print(message) - time.sleep(sleep_for_time) - -## 6 ポート切断 -g_in_ports[g_port3].disconnect(g_conprof3.connector_id) -g_in_ports[g_port2].disconnect(g_conprof2.connector_id) -g_in_ports[g_port1].disconnect(g_conprof1.connector_id) + for i in range(loop_count): -##-------------------------------------------------------------------- -## 接続タイプ:periodic 方向:out->in ポリシー:ALL 接続・切断・Activate・Deactivateテスト1 -##-------------------------------------------------------------------- -case_no = case_no + 1 -fout = open(g_test_result_file, 'a') -message = g_mess_header + g_test_case + str(case_no) + " " -message = message + "Connect(out->in, periodic,ALL) -> Activate -> send/recv -> Deactivate -> Disconnect" -message = message + g_mess_footer -fout.write(message + '\n') -fout.close() -print(message) + # 2 受信データファイル削除 + delete_recv_file() -for i in range(loop_count): + # 1 コネクタープロファイル設定 + make_connecter_profile("periodic", "ALL", 0) - ## 2 受信データファイル削除 - delete_recv_file() + # 3 ポート接続 + # データポート1 TimedFloat + ret0 = g_out_ports[g_port1].connect(g_conprof1) - ## 1 コネクタープロファイル設定 - make_connecter_profile("periodic", "ALL", 0) + # データポート2 TimedFloatSeq + ret1 = g_out_ports[g_port2].connect(g_conprof2) - ## 3 ポート接続 - # データポート1 TimedFloat - ret0 = g_out_ports[g_port1].connect(g_conprof1) + # サービスポート MyService + ret2 = g_out_ports[g_port3].connect(g_conprof3) - # データポート2 TimedFloatSeq - ret1 = g_out_ports[g_port2].connect(g_conprof2) + # 4 アクティベート + ec_recv[0].activate_component(g_compo_recv.rtc_ref) + time.sleep(sleep_recv_act_time) + ec_send[0].activate_component(g_compo_send.rtc_ref) - # サービスポート MyService - ret2 = g_out_ports[g_port3].connect(g_conprof3) + time.sleep(sleep_act_time) - ## 4 アクティベート - ec_recv[0].activate_component(g_compo_recv.rtc_ref) - time.sleep(sleep_recv_act_time) - ec_send[0].activate_component(g_compo_send.rtc_ref) + # 5 ディアクティベート + ec_send[0].deactivate_component(g_compo_send.rtc_ref) + ec_recv[0].deactivate_component(g_compo_recv.rtc_ref) - time.sleep(sleep_act_time) + # 6 ポート切断 + g_in_ports[g_port3].disconnect(g_conprof3.connector_id) + g_in_ports[g_port2].disconnect(g_conprof2.connector_id) + g_in_ports[g_port1].disconnect(g_conprof1.connector_id) - ## 5 ディアクティベート - ec_send[0].deactivate_component(g_compo_send.rtc_ref) - ec_recv[0].deactivate_component(g_compo_recv.rtc_ref) + # 受信ファイル有無判定 + if os.path.isfile(g_diff_recv_file) == False: + fout = open(g_test_result_file, 'a') + message = g_mess_header + g_test_case + \ + str(case_no) + " " + g_test_cnt + str(i + 1) + g_mess_footer + message = message + g_check_message + fout.write(message + '\n') + fout.close() + print(message) + time.sleep(sleep_for_time) + continue - ## 6 ポート切断 - g_in_ports[g_port3].disconnect(g_conprof3.connector_id) - g_in_ports[g_port2].disconnect(g_conprof2.connector_id) - g_in_ports[g_port1].disconnect(g_conprof1.connector_id) + # 7 送受信データ比較 + time.sleep(sleep_act_time) + bret = diff_file() - ## 受信ファイル有無判定 - if os.path.isfile(g_diff_recv_file) == False: + # 差分ファイルからテスト結果出力 fout = open(g_test_result_file, 'a') - message = g_mess_header + g_test_case + str(case_no) + " " + g_test_cnt + str(i+1) + g_mess_footer - message = message + g_check_message - fout.write(message + '\n') + message = g_mess_header + g_test_case + \ + str(case_no) + " " + g_test_cnt + str(i + 1) + g_mess_footer + # bret==True なら送受信データ一致 + if bret == True: + # テスト結果 OK + message = message + g_test_ok + print(message) + fout.write(message + '\n') + else: + # テスト結果 NG + message = message + g_test_ng + print(message) + message = message + g_test_ng_message + fout.write(message + '\n') + # 受信データをテスト結果ファイルへコピー + fin2 = open(g_diff_recv_file, 'r') + while(1): + s2 = fin2.readline() + if len(s2) == 0: + break + fout.write(s2) + fin2.close() fout.close() - print(message) - time.sleep(sleep_for_time) - continue - ## 7 送受信データ比較 - time.sleep(sleep_act_time) - bret = diff_file() + time.sleep(sleep_for_time) - ## 差分ファイルからテスト結果出力 + # -------------------------------------------------------------------- + # 接続タイプ:periodic 方向:out->in ポリシー:FIFO 接続・切断・Activate・Deactivateテスト1 + # -------------------------------------------------------------------- + case_no = case_no + 1 fout = open(g_test_result_file, 'a') - message = g_mess_header + g_test_case + str(case_no) + " " + g_test_cnt + str(i+1) + g_mess_footer - # bret==True なら送受信データ一致 - if bret == True: - # テスト結果 OK - message = message + g_test_ok - print(message) - fout.write(message + '\n') - else: - # テスト結果 NG - message = message + g_test_ng - print(message) - message = message + g_test_ng_message - fout.write(message + '\n') - # 受信データをテスト結果ファイルへコピー - fin2 = open(g_diff_recv_file, 'r') - while(1): - s2 = fin2.readline() - if len(s2) == 0: - break - fout.write(s2) - fin2.close() + message = g_mess_header + g_test_case + str(case_no) + " " + message = message + \ + "Connect(out->in, periodic,FIFO) -> Activate -> send/recv -> Deactivate -> Disconnect" + message = message + g_mess_footer + fout.write(message + '\n') fout.close() + print(message) - time.sleep(sleep_for_time) + for i in range(loop_count): -##-------------------------------------------------------------------- -## 接続タイプ:periodic 方向:out->in ポリシー:FIFO 接続・切断・Activate・Deactivateテスト1 -##-------------------------------------------------------------------- -case_no = case_no + 1 -fout = open(g_test_result_file, 'a') -message = g_mess_header + g_test_case + str(case_no) + " " -message = message + "Connect(out->in, periodic,FIFO) -> Activate -> send/recv -> Deactivate -> Disconnect" -message = message + g_mess_footer -fout.write(message + '\n') -fout.close() -print(message) + # 2 受信データファイル削除 + delete_recv_file() -for i in range(loop_count): + # 1 コネクタープロファイル設定 + make_connecter_profile("periodic", "FIFO", 0) - ## 2 受信データファイル削除 - delete_recv_file() + # 3 ポート接続 + # データポート1 TimedFloat + ret0 = g_out_ports[g_port1].connect(g_conprof1) - ## 1 コネクタープロファイル設定 - make_connecter_profile("periodic", "FIFO", 0) + # データポート2 TimedFloatSeq + ret1 = g_out_ports[g_port2].connect(g_conprof2) - ## 3 ポート接続 - # データポート1 TimedFloat - ret0 = g_out_ports[g_port1].connect(g_conprof1) + # サービスポート MyService + ret2 = g_out_ports[g_port3].connect(g_conprof3) - # データポート2 TimedFloatSeq - ret1 = g_out_ports[g_port2].connect(g_conprof2) + # 4 アクティベート + ec_recv[0].activate_component(g_compo_recv.rtc_ref) + time.sleep(sleep_recv_act_time) + ec_send[0].activate_component(g_compo_send.rtc_ref) - # サービスポート MyService - ret2 = g_out_ports[g_port3].connect(g_conprof3) + time.sleep(sleep_act_time) - ## 4 アクティベート - ec_recv[0].activate_component(g_compo_recv.rtc_ref) - time.sleep(sleep_recv_act_time) - ec_send[0].activate_component(g_compo_send.rtc_ref) + # 5 ディアクティベート + ec_send[0].deactivate_component(g_compo_send.rtc_ref) + ec_recv[0].deactivate_component(g_compo_recv.rtc_ref) - time.sleep(sleep_act_time) + # 6 ポート切断 + g_in_ports[g_port3].disconnect(g_conprof3.connector_id) + g_in_ports[g_port2].disconnect(g_conprof2.connector_id) + g_in_ports[g_port1].disconnect(g_conprof1.connector_id) - ## 5 ディアクティベート - ec_send[0].deactivate_component(g_compo_send.rtc_ref) - ec_recv[0].deactivate_component(g_compo_recv.rtc_ref) + # 受信ファイル有無判定 + if os.path.isfile(g_diff_recv_file) == False: + fout = open(g_test_result_file, 'a') + message = g_mess_header + g_test_case + \ + str(case_no) + " " + g_test_cnt + str(i + 1) + g_mess_footer + message = message + g_check_message + fout.write(message + '\n') + fout.close() + print(message) + time.sleep(sleep_for_time) + continue - ## 6 ポート切断 - g_in_ports[g_port3].disconnect(g_conprof3.connector_id) - g_in_ports[g_port2].disconnect(g_conprof2.connector_id) - g_in_ports[g_port1].disconnect(g_conprof1.connector_id) + # 7 送受信データ比較 + time.sleep(sleep_act_time) + bret = diff_file() - ## 受信ファイル有無判定 - if os.path.isfile(g_diff_recv_file) == False: + # 差分ファイルからテスト結果出力 fout = open(g_test_result_file, 'a') - message = g_mess_header + g_test_case + str(case_no) + " " + g_test_cnt + str(i+1) + g_mess_footer - message = message + g_check_message - fout.write(message + '\n') + message = g_mess_header + g_test_case + \ + str(case_no) + " " + g_test_cnt + str(i + 1) + g_mess_footer + # bret==True なら送受信データ一致 + if bret == True: + # テスト結果 OK + message = message + g_test_ok + print(message) + fout.write(message + '\n') + else: + # テスト結果 NG + message = message + g_test_ng + print(message) + message = message + g_test_ng_message + fout.write(message + '\n') + # 受信データをテスト結果ファイルへコピー + fin2 = open(g_diff_recv_file, 'r') + while(1): + s2 = fin2.readline() + if len(s2) == 0: + break + fout.write(s2) + fin2.close() fout.close() - print(message) - time.sleep(sleep_for_time) - continue - ## 7 送受信データ比較 - time.sleep(sleep_act_time) - bret = diff_file() + time.sleep(sleep_for_time) - ## 差分ファイルからテスト結果出力 + # -------------------------------------------------------------------- + # 接続タイプ:periodic 方向:out->in ポリシー:NEW 接続・切断・Activate・Deactivateテスト1 + # -------------------------------------------------------------------- + case_no = case_no + 1 fout = open(g_test_result_file, 'a') - message = g_mess_header + g_test_case + str(case_no) + " " + g_test_cnt + str(i+1) + g_mess_footer - # bret==True なら送受信データ一致 - if bret == True: - # テスト結果 OK - message = message + g_test_ok - print(message) - fout.write(message + '\n') - else: - # テスト結果 NG - message = message + g_test_ng - print(message) - message = message + g_test_ng_message - fout.write(message + '\n') - # 受信データをテスト結果ファイルへコピー - fin2 = open(g_diff_recv_file, 'r') - while(1): - s2 = fin2.readline() - if len(s2) == 0: - break - fout.write(s2) - fin2.close() + message = g_mess_header + g_test_case + str(case_no) + " " + message = message + \ + "Connect(out->in, periodic,NEW) -> Activate -> send/recv -> Deactivate -> Disconnect" + message = message + g_mess_footer + fout.write(message + '\n') fout.close() + print(message) - time.sleep(sleep_for_time) + for i in range(loop_count): -##-------------------------------------------------------------------- -## 接続タイプ:periodic 方向:out->in ポリシー:NEW 接続・切断・Activate・Deactivateテスト1 -##-------------------------------------------------------------------- -case_no = case_no + 1 -fout = open(g_test_result_file, 'a') -message = g_mess_header + g_test_case + str(case_no) + " " -message = message + "Connect(out->in, periodic,NEW) -> Activate -> send/recv -> Deactivate -> Disconnect" -message = message + g_mess_footer -fout.write(message + '\n') -fout.close() -print(message) + # 2 受信データファイル削除 + delete_recv_file() -for i in range(loop_count): + # 1 コネクタープロファイル設定 + make_connecter_profile("periodic", "NEW", 0) - ## 2 受信データファイル削除 - delete_recv_file() + # 3 ポート接続 + # データポート1 TimedFloat + ret0 = g_out_ports[g_port1].connect(g_conprof1) - ## 1 コネクタープロファイル設定 - make_connecter_profile("periodic", "NEW", 0) + # データポート2 TimedFloatSeq + ret1 = g_out_ports[g_port2].connect(g_conprof2) - ## 3 ポート接続 - # データポート1 TimedFloat - ret0 = g_out_ports[g_port1].connect(g_conprof1) + # サービスポート MyService + ret2 = g_out_ports[g_port3].connect(g_conprof3) - # データポート2 TimedFloatSeq - ret1 = g_out_ports[g_port2].connect(g_conprof2) + # 4 アクティベート + ec_recv[0].activate_component(g_compo_recv.rtc_ref) + time.sleep(sleep_recv_act_time) + ec_send[0].activate_component(g_compo_send.rtc_ref) - # サービスポート MyService - ret2 = g_out_ports[g_port3].connect(g_conprof3) + time.sleep(sleep_act_time) - ## 4 アクティベート - ec_recv[0].activate_component(g_compo_recv.rtc_ref) - time.sleep(sleep_recv_act_time) - ec_send[0].activate_component(g_compo_send.rtc_ref) + # 5 ディアクティベート + ec_send[0].deactivate_component(g_compo_send.rtc_ref) + ec_recv[0].deactivate_component(g_compo_recv.rtc_ref) - time.sleep(sleep_act_time) + # 6 ポート切断 + g_in_ports[g_port3].disconnect(g_conprof3.connector_id) + g_in_ports[g_port2].disconnect(g_conprof2.connector_id) + g_in_ports[g_port1].disconnect(g_conprof1.connector_id) - ## 5 ディアクティベート - ec_send[0].deactivate_component(g_compo_send.rtc_ref) - ec_recv[0].deactivate_component(g_compo_recv.rtc_ref) + # 受信ファイル有無判定 + if os.path.isfile(g_diff_recv_file) == False: + fout = open(g_test_result_file, 'a') + message = g_mess_header + g_test_case + \ + str(case_no) + " " + g_test_cnt + str(i + 1) + g_mess_footer + message = message + g_check_message + fout.write(message + '\n') + fout.close() + print(message) + time.sleep(sleep_for_time) + continue - ## 6 ポート切断 - g_in_ports[g_port3].disconnect(g_conprof3.connector_id) - g_in_ports[g_port2].disconnect(g_conprof2.connector_id) - g_in_ports[g_port1].disconnect(g_conprof1.connector_id) + # 7 送受信データ比較 + time.sleep(sleep_act_time) + bret = diff_file() - ## 受信ファイル有無判定 - if os.path.isfile(g_diff_recv_file) == False: + # 差分ファイルからテスト結果出力 fout = open(g_test_result_file, 'a') - message = g_mess_header + g_test_case + str(case_no) + " " + g_test_cnt + str(i+1) + g_mess_footer - message = message + g_check_message - fout.write(message + '\n') + message = g_mess_header + g_test_case + \ + str(case_no) + " " + g_test_cnt + str(i + 1) + g_mess_footer + # bret==True なら送受信データ一致 + if bret == True: + # テスト結果 OK + message = message + g_test_ok + print(message) + fout.write(message + '\n') + else: + # テスト結果 NG + message = message + g_test_ng + print(message) + message = message + g_test_ng_message + fout.write(message + '\n') + # 受信データをテスト結果ファイルへコピー + fin2 = open(g_diff_recv_file, 'r') + while(1): + s2 = fin2.readline() + if len(s2) == 0: + break + fout.write(s2) + fin2.close() fout.close() - print(message) - time.sleep(sleep_for_time) - continue - ## 7 送受信データ比較 - time.sleep(sleep_act_time) - bret = diff_file() + time.sleep(sleep_for_time) - ## 差分ファイルからテスト結果出力 + # -------------------------------------------------------------------- + # 接続タイプ:periodic 方向:out->in ポリシー:SKIP 接続・切断・Activate・Deactivateテスト1 + # -------------------------------------------------------------------- + case_no = case_no + 1 fout = open(g_test_result_file, 'a') - message = g_mess_header + g_test_case + str(case_no) + " " + g_test_cnt + str(i+1) + g_mess_footer - # bret==True なら送受信データ一致 - if bret == True: - # テスト結果 OK - message = message + g_test_ok - print(message) - fout.write(message + '\n') - else: - # テスト結果 NG - message = message + g_test_ng - print(message) - message = message + g_test_ng_message - fout.write(message + '\n') - # 受信データをテスト結果ファイルへコピー - fin2 = open(g_diff_recv_file, 'r') - while(1): - s2 = fin2.readline() - if len(s2) == 0: - break - fout.write(s2) - fin2.close() + message = g_mess_header + g_test_case + str(case_no) + " " + message = message + \ + "Connect(out->in, periodic,SKIP) -> Activate -> send/recv -> Deactivate -> Disconnect" + message = message + g_mess_footer + fout.write(message + '\n') fout.close() + print(message) - time.sleep(sleep_for_time) + for i in range(loop_count): -##-------------------------------------------------------------------- -## 接続タイプ:periodic 方向:out->in ポリシー:SKIP 接続・切断・Activate・Deactivateテスト1 -##-------------------------------------------------------------------- -case_no = case_no + 1 -fout = open(g_test_result_file, 'a') -message = g_mess_header + g_test_case + str(case_no) + " " -message = message + "Connect(out->in, periodic,SKIP) -> Activate -> send/recv -> Deactivate -> Disconnect" -message = message + g_mess_footer -fout.write(message + '\n') -fout.close() -print(message) + # 2 受信データファイル削除 + delete_recv_file() -for i in range(loop_count): + # 1 コネクタープロファイル設定 + make_connecter_profile("periodic", "SKIP", 0) - ## 2 受信データファイル削除 - delete_recv_file() + # 3 ポート接続 + # データポート1 TimedFloat + ret0 = g_out_ports[g_port1].connect(g_conprof1) - ## 1 コネクタープロファイル設定 - make_connecter_profile("periodic", "SKIP", 0) + # データポート2 TimedFloatSeq + ret1 = g_out_ports[g_port2].connect(g_conprof2) - ## 3 ポート接続 - # データポート1 TimedFloat - ret0 = g_out_ports[g_port1].connect(g_conprof1) + # サービスポート MyService + ret2 = g_out_ports[g_port3].connect(g_conprof3) - # データポート2 TimedFloatSeq - ret1 = g_out_ports[g_port2].connect(g_conprof2) + # 4 アクティベート + ec_recv[0].activate_component(g_compo_recv.rtc_ref) + time.sleep(sleep_recv_act_time) + ec_send[0].activate_component(g_compo_send.rtc_ref) - # サービスポート MyService - ret2 = g_out_ports[g_port3].connect(g_conprof3) + time.sleep(sleep_act_time) - ## 4 アクティベート - ec_recv[0].activate_component(g_compo_recv.rtc_ref) - time.sleep(sleep_recv_act_time) - ec_send[0].activate_component(g_compo_send.rtc_ref) + # 5 ディアクティベート + ec_send[0].deactivate_component(g_compo_send.rtc_ref) + ec_recv[0].deactivate_component(g_compo_recv.rtc_ref) - time.sleep(sleep_act_time) + # 6 ポート切断 + g_in_ports[g_port3].disconnect(g_conprof3.connector_id) + g_in_ports[g_port2].disconnect(g_conprof2.connector_id) + g_in_ports[g_port1].disconnect(g_conprof1.connector_id) - ## 5 ディアクティベート - ec_send[0].deactivate_component(g_compo_send.rtc_ref) - ec_recv[0].deactivate_component(g_compo_recv.rtc_ref) + # 受信ファイル有無判定 + if os.path.isfile(g_diff_recv_file) == False: + fout = open(g_test_result_file, 'a') + message = g_mess_header + g_test_case + \ + str(case_no) + " " + g_test_cnt + str(i + 1) + g_mess_footer + message = message + g_check_message + fout.write(message + '\n') + fout.close() + print(message) + time.sleep(sleep_for_time) + continue - ## 6 ポート切断 - g_in_ports[g_port3].disconnect(g_conprof3.connector_id) - g_in_ports[g_port2].disconnect(g_conprof2.connector_id) - g_in_ports[g_port1].disconnect(g_conprof1.connector_id) + # 7 送受信データ比較 + time.sleep(sleep_act_time) + bret = diff_file() - ## 受信ファイル有無判定 - if os.path.isfile(g_diff_recv_file) == False: + # 差分ファイルからテスト結果出力 fout = open(g_test_result_file, 'a') - message = g_mess_header + g_test_case + str(case_no) + " " + g_test_cnt + str(i+1) + g_mess_footer - message = message + g_check_message - fout.write(message + '\n') + message = g_mess_header + g_test_case + \ + str(case_no) + " " + g_test_cnt + str(i + 1) + g_mess_footer + # bret==True なら送受信データ一致 + if bret == True: + # テスト結果 OK + message = message + g_test_ok + print(message) + fout.write(message + '\n') + else: + # テスト結果 NG + message = message + g_test_ng + print(message) + message = message + g_test_ng_message + fout.write(message + '\n') + # 受信データをテスト結果ファイルへコピー + fin2 = open(g_diff_recv_file, 'r') + while(1): + s2 = fin2.readline() + if len(s2) == 0: + break + fout.write(s2) + fin2.close() fout.close() - print(message) - time.sleep(sleep_for_time) - continue - ## 7 送受信データ比較 - time.sleep(sleep_act_time) - bret = diff_file() + time.sleep(sleep_for_time) - ## 差分ファイルからテスト結果出力 + # -------------------------------------------------------------------- + # 接続タイプ:periodic 方向:in->out ポリシー:ALL 接続・切断・Activate・Deactivateテスト1 + # -------------------------------------------------------------------- + case_no = case_no + 1 fout = open(g_test_result_file, 'a') - message = g_mess_header + g_test_case + str(case_no) + " " + g_test_cnt + str(i+1) + g_mess_footer - # bret==True なら送受信データ一致 - if bret == True: - # テスト結果 OK - message = message + g_test_ok - print(message) - fout.write(message + '\n') - else: - # テスト結果 NG - message = message + g_test_ng - print(message) - message = message + g_test_ng_message - fout.write(message + '\n') - # 受信データをテスト結果ファイルへコピー - fin2 = open(g_diff_recv_file, 'r') - while(1): - s2 = fin2.readline() - if len(s2) == 0: - break - fout.write(s2) - fin2.close() + message = g_mess_header + g_test_case + str(case_no) + " " + message = message + \ + "Connect(in->out, periodic,ALL) -> Activate -> send/recv -> Deactivate -> Disconnect" + message = message + g_mess_footer + fout.write(message + '\n') fout.close() + print(message) - time.sleep(sleep_for_time) + for i in range(loop_count): -##-------------------------------------------------------------------- -## 接続タイプ:periodic 方向:in->out ポリシー:ALL 接続・切断・Activate・Deactivateテスト1 -##-------------------------------------------------------------------- -case_no = case_no + 1 -fout = open(g_test_result_file, 'a') -message = g_mess_header + g_test_case + str(case_no) + " " -message = message + "Connect(in->out, periodic,ALL) -> Activate -> send/recv -> Deactivate -> Disconnect" -message = message + g_mess_footer -fout.write(message + '\n') -fout.close() -print(message) + # 2 受信データファイル削除 + delete_recv_file() -for i in range(loop_count): + # 1 コネクタープロファイル設定 + make_connecter_profile("periodic", "ALL", 1) - ## 2 受信データファイル削除 - delete_recv_file() + # 3 ポート接続 + # データポート1 TimedFloat + ret0 = g_out_ports[g_port1].connect(g_conprof1) - ## 1 コネクタープロファイル設定 - make_connecter_profile("periodic", "ALL", 1) + # データポート2 TimedFloatSeq + ret1 = g_out_ports[g_port2].connect(g_conprof2) - ## 3 ポート接続 - # データポート1 TimedFloat - ret0 = g_out_ports[g_port1].connect(g_conprof1) + # サービスポート MyService + ret2 = g_out_ports[g_port3].connect(g_conprof3) - # データポート2 TimedFloatSeq - ret1 = g_out_ports[g_port2].connect(g_conprof2) + # 4 アクティベート + ec_recv[0].activate_component(g_compo_recv.rtc_ref) + time.sleep(sleep_recv_act_time) + ec_send[0].activate_component(g_compo_send.rtc_ref) - # サービスポート MyService - ret2 = g_out_ports[g_port3].connect(g_conprof3) + time.sleep(sleep_act_time) - ## 4 アクティベート - ec_recv[0].activate_component(g_compo_recv.rtc_ref) - time.sleep(sleep_recv_act_time) - ec_send[0].activate_component(g_compo_send.rtc_ref) + # 5 ディアクティベート + ec_send[0].deactivate_component(g_compo_send.rtc_ref) + ec_recv[0].deactivate_component(g_compo_recv.rtc_ref) - time.sleep(sleep_act_time) + # 6 ポート切断 + g_in_ports[g_port3].disconnect(g_conprof3.connector_id) + g_in_ports[g_port2].disconnect(g_conprof2.connector_id) + g_in_ports[g_port1].disconnect(g_conprof1.connector_id) - ## 5 ディアクティベート - ec_send[0].deactivate_component(g_compo_send.rtc_ref) - ec_recv[0].deactivate_component(g_compo_recv.rtc_ref) + # 受信ファイル有無判定 + if os.path.isfile(g_diff_recv_file) == False: + fout = open(g_test_result_file, 'a') + message = g_mess_header + g_test_case + \ + str(case_no) + " " + g_test_cnt + str(i + 1) + g_mess_footer + message = message + g_check_message + fout.write(message + '\n') + fout.close() + print(message) + time.sleep(sleep_for_time) + continue - ## 6 ポート切断 - g_in_ports[g_port3].disconnect(g_conprof3.connector_id) - g_in_ports[g_port2].disconnect(g_conprof2.connector_id) - g_in_ports[g_port1].disconnect(g_conprof1.connector_id) + # 7 送受信データ比較 + time.sleep(sleep_act_time) + bret = diff_file() - ## 受信ファイル有無判定 - if os.path.isfile(g_diff_recv_file) == False: + # 差分ファイルからテスト結果出力 fout = open(g_test_result_file, 'a') - message = g_mess_header + g_test_case + str(case_no) + " " + g_test_cnt + str(i+1) + g_mess_footer - message = message + g_check_message - fout.write(message + '\n') + message = g_mess_header + g_test_case + \ + str(case_no) + " " + g_test_cnt + str(i + 1) + g_mess_footer + # bret==True なら送受信データ一致 + if bret == True: + # テスト結果 OK + message = message + g_test_ok + print(message) + fout.write(message + '\n') + else: + # テスト結果 NG + message = message + g_test_ng + print(message) + message = message + g_test_ng_message + fout.write(message + '\n') + # 受信データをテスト結果ファイルへコピー + fin2 = open(g_diff_recv_file, 'r') + while(1): + s2 = fin2.readline() + if len(s2) == 0: + break + fout.write(s2) + fin2.close() fout.close() - print(message) - time.sleep(sleep_for_time) - continue - ## 7 送受信データ比較 - time.sleep(sleep_act_time) - bret = diff_file() + time.sleep(sleep_for_time) - ## 差分ファイルからテスト結果出力 + # -------------------------------------------------------------------- + # 接続タイプ:periodic 方向:in->out ポリシー:FIFO 接続・切断・Activate・Deactivateテスト1 + # -------------------------------------------------------------------- + case_no = case_no + 1 fout = open(g_test_result_file, 'a') - message = g_mess_header + g_test_case + str(case_no) + " " + g_test_cnt + str(i+1) + g_mess_footer - # bret==True なら送受信データ一致 - if bret == True: - # テスト結果 OK - message = message + g_test_ok - print(message) - fout.write(message + '\n') - else: - # テスト結果 NG - message = message + g_test_ng - print(message) - message = message + g_test_ng_message - fout.write(message + '\n') - # 受信データをテスト結果ファイルへコピー - fin2 = open(g_diff_recv_file, 'r') - while(1): - s2 = fin2.readline() - if len(s2) == 0: - break - fout.write(s2) - fin2.close() + message = g_mess_header + g_test_case + str(case_no) + " " + message = message + \ + "Connect(in->out, periodic,FIFO) -> Activate -> send/recv -> Deactivate -> Disconnect" + message = message + g_mess_footer + fout.write(message + '\n') fout.close() + print(message) - time.sleep(sleep_for_time) + for i in range(loop_count): -##-------------------------------------------------------------------- -## 接続タイプ:periodic 方向:in->out ポリシー:FIFO 接続・切断・Activate・Deactivateテスト1 -##-------------------------------------------------------------------- -case_no = case_no + 1 -fout = open(g_test_result_file, 'a') -message = g_mess_header + g_test_case + str(case_no) + " " -message = message + "Connect(in->out, periodic,FIFO) -> Activate -> send/recv -> Deactivate -> Disconnect" -message = message + g_mess_footer -fout.write(message + '\n') -fout.close() -print(message) + # 2 受信データファイル削除 + delete_recv_file() -for i in range(loop_count): + # 1 コネクタープロファイル設定 + make_connecter_profile("periodic", "FIFO", 1) - ## 2 受信データファイル削除 - delete_recv_file() + # 3 ポート接続 + # データポート1 TimedFloat + ret0 = g_out_ports[g_port1].connect(g_conprof1) - ## 1 コネクタープロファイル設定 - make_connecter_profile("periodic", "FIFO", 1) + # データポート2 TimedFloatSeq + ret1 = g_out_ports[g_port2].connect(g_conprof2) - ## 3 ポート接続 - # データポート1 TimedFloat - ret0 = g_out_ports[g_port1].connect(g_conprof1) + # サービスポート MyService + ret2 = g_out_ports[g_port3].connect(g_conprof3) - # データポート2 TimedFloatSeq - ret1 = g_out_ports[g_port2].connect(g_conprof2) + # 4 アクティベート + ec_recv[0].activate_component(g_compo_recv.rtc_ref) + time.sleep(sleep_recv_act_time) + ec_send[0].activate_component(g_compo_send.rtc_ref) - # サービスポート MyService - ret2 = g_out_ports[g_port3].connect(g_conprof3) + time.sleep(sleep_act_time) - ## 4 アクティベート - ec_recv[0].activate_component(g_compo_recv.rtc_ref) - time.sleep(sleep_recv_act_time) - ec_send[0].activate_component(g_compo_send.rtc_ref) + # 5 ディアクティベート + ec_send[0].deactivate_component(g_compo_send.rtc_ref) + ec_recv[0].deactivate_component(g_compo_recv.rtc_ref) - time.sleep(sleep_act_time) + # 6 ポート切断 + g_in_ports[g_port3].disconnect(g_conprof3.connector_id) + g_in_ports[g_port2].disconnect(g_conprof2.connector_id) + g_in_ports[g_port1].disconnect(g_conprof1.connector_id) - ## 5 ディアクティベート - ec_send[0].deactivate_component(g_compo_send.rtc_ref) - ec_recv[0].deactivate_component(g_compo_recv.rtc_ref) + # 受信ファイル有無判定 + if os.path.isfile(g_diff_recv_file) == False: + fout = open(g_test_result_file, 'a') + message = g_mess_header + g_test_case + \ + str(case_no) + " " + g_test_cnt + str(i + 1) + g_mess_footer + message = message + g_check_message + fout.write(message + '\n') + fout.close() + print(message) + time.sleep(sleep_for_time) + continue - ## 6 ポート切断 - g_in_ports[g_port3].disconnect(g_conprof3.connector_id) - g_in_ports[g_port2].disconnect(g_conprof2.connector_id) - g_in_ports[g_port1].disconnect(g_conprof1.connector_id) + # 7 送受信データ比較 + time.sleep(sleep_act_time) + bret = diff_file() - ## 受信ファイル有無判定 - if os.path.isfile(g_diff_recv_file) == False: + # 差分ファイルからテスト結果出力 fout = open(g_test_result_file, 'a') - message = g_mess_header + g_test_case + str(case_no) + " " + g_test_cnt + str(i+1) + g_mess_footer - message = message + g_check_message - fout.write(message + '\n') + message = g_mess_header + g_test_case + \ + str(case_no) + " " + g_test_cnt + str(i + 1) + g_mess_footer + # bret==True なら送受信データ一致 + if bret == True: + # テスト結果 OK + message = message + g_test_ok + print(message) + fout.write(message + '\n') + else: + # テスト結果 NG + message = message + g_test_ng + print(message) + message = message + g_test_ng_message + fout.write(message + '\n') + # 受信データをテスト結果ファイルへコピー + fin2 = open(g_diff_recv_file, 'r') + while(1): + s2 = fin2.readline() + if len(s2) == 0: + break + fout.write(s2) + fin2.close() fout.close() - print(message) - time.sleep(sleep_for_time) - continue - ## 7 送受信データ比較 - time.sleep(sleep_act_time) - bret = diff_file() + time.sleep(sleep_for_time) - ## 差分ファイルからテスト結果出力 + # -------------------------------------------------------------------- + # 接続タイプ:periodic 方向:in->out ポリシー:NEW 接続・切断・Activate・Deactivateテスト1 + # -------------------------------------------------------------------- + case_no = case_no + 1 fout = open(g_test_result_file, 'a') - message = g_mess_header + g_test_case + str(case_no) + " " + g_test_cnt + str(i+1) + g_mess_footer - # bret==True なら送受信データ一致 - if bret == True: - # テスト結果 OK - message = message + g_test_ok - print(message) - fout.write(message + '\n') - else: - # テスト結果 NG - message = message + g_test_ng - print(message) - message = message + g_test_ng_message - fout.write(message + '\n') - # 受信データをテスト結果ファイルへコピー - fin2 = open(g_diff_recv_file, 'r') - while(1): - s2 = fin2.readline() - if len(s2) == 0: - break - fout.write(s2) - fin2.close() + message = g_mess_header + g_test_case + str(case_no) + " " + message = message + \ + "Connect(in->out, periodic,NEW) -> Activate -> send/recv -> Deactivate -> Disconnect" + message = message + g_mess_footer + fout.write(message + '\n') fout.close() + print(message) - time.sleep(sleep_for_time) + for i in range(loop_count): -##-------------------------------------------------------------------- -## 接続タイプ:periodic 方向:in->out ポリシー:NEW 接続・切断・Activate・Deactivateテスト1 -##-------------------------------------------------------------------- -case_no = case_no + 1 -fout = open(g_test_result_file, 'a') -message = g_mess_header + g_test_case + str(case_no) + " " -message = message + "Connect(in->out, periodic,NEW) -> Activate -> send/recv -> Deactivate -> Disconnect" -message = message + g_mess_footer -fout.write(message + '\n') -fout.close() -print(message) + # 2 受信データファイル削除 + delete_recv_file() -for i in range(loop_count): + # 1 コネクタープロファイル設定 + make_connecter_profile("periodic", "NEW", 1) - ## 2 受信データファイル削除 - delete_recv_file() + # 3 ポート接続 + # データポート1 TimedFloat + ret0 = g_out_ports[g_port1].connect(g_conprof1) - ## 1 コネクタープロファイル設定 - make_connecter_profile("periodic", "NEW", 1) + # データポート2 TimedFloatSeq + ret1 = g_out_ports[g_port2].connect(g_conprof2) - ## 3 ポート接続 - # データポート1 TimedFloat - ret0 = g_out_ports[g_port1].connect(g_conprof1) + # サービスポート MyService + ret2 = g_out_ports[g_port3].connect(g_conprof3) - # データポート2 TimedFloatSeq - ret1 = g_out_ports[g_port2].connect(g_conprof2) + # 4 アクティベート + ec_recv[0].activate_component(g_compo_recv.rtc_ref) + time.sleep(sleep_recv_act_time) + ec_send[0].activate_component(g_compo_send.rtc_ref) - # サービスポート MyService - ret2 = g_out_ports[g_port3].connect(g_conprof3) + time.sleep(sleep_act_time) - ## 4 アクティベート - ec_recv[0].activate_component(g_compo_recv.rtc_ref) - time.sleep(sleep_recv_act_time) - ec_send[0].activate_component(g_compo_send.rtc_ref) + # 5 ディアクティベート + ec_send[0].deactivate_component(g_compo_send.rtc_ref) + ec_recv[0].deactivate_component(g_compo_recv.rtc_ref) - time.sleep(sleep_act_time) + # 6 ポート切断 + g_in_ports[g_port3].disconnect(g_conprof3.connector_id) + g_in_ports[g_port2].disconnect(g_conprof2.connector_id) + g_in_ports[g_port1].disconnect(g_conprof1.connector_id) - ## 5 ディアクティベート - ec_send[0].deactivate_component(g_compo_send.rtc_ref) - ec_recv[0].deactivate_component(g_compo_recv.rtc_ref) + # 受信ファイル有無判定 + if os.path.isfile(g_diff_recv_file) == False: + fout = open(g_test_result_file, 'a') + message = g_mess_header + g_test_case + \ + str(case_no) + " " + g_test_cnt + str(i + 1) + g_mess_footer + message = message + g_check_message + fout.write(message + '\n') + fout.close() + print(message) + time.sleep(sleep_for_time) + continue - ## 6 ポート切断 - g_in_ports[g_port3].disconnect(g_conprof3.connector_id) - g_in_ports[g_port2].disconnect(g_conprof2.connector_id) - g_in_ports[g_port1].disconnect(g_conprof1.connector_id) + # 7 送受信データ比較 + time.sleep(sleep_act_time) + bret = diff_file() - ## 受信ファイル有無判定 - if os.path.isfile(g_diff_recv_file) == False: + # 差分ファイルからテスト結果出力 fout = open(g_test_result_file, 'a') - message = g_mess_header + g_test_case + str(case_no) + " " + g_test_cnt + str(i+1) + g_mess_footer - message = message + g_check_message - fout.write(message + '\n') + message = g_mess_header + g_test_case + \ + str(case_no) + " " + g_test_cnt + str(i + 1) + g_mess_footer + # bret==True なら送受信データ一致 + if bret == True: + # テスト結果 OK + message = message + g_test_ok + print(message) + fout.write(message + '\n') + else: + # テスト結果 NG + message = message + g_test_ng + print(message) + message = message + g_test_ng_message + fout.write(message + '\n') + # 受信データをテスト結果ファイルへコピー + fin2 = open(g_diff_recv_file, 'r') + while(1): + s2 = fin2.readline() + if len(s2) == 0: + break + fout.write(s2) + fin2.close() fout.close() - print(message) - time.sleep(sleep_for_time) - continue - ## 7 送受信データ比較 - time.sleep(sleep_act_time) - bret = diff_file() + time.sleep(sleep_for_time) - ## 差分ファイルからテスト結果出力 + # -------------------------------------------------------------------- + # 接続タイプ:periodic 方向:in->out ポリシー:SKIP 接続・切断・Activate・Deactivateテスト1 + # -------------------------------------------------------------------- + case_no = case_no + 1 fout = open(g_test_result_file, 'a') - message = g_mess_header + g_test_case + str(case_no) + " " + g_test_cnt + str(i+1) + g_mess_footer - # bret==True なら送受信データ一致 - if bret == True: - # テスト結果 OK - message = message + g_test_ok - print(message) - fout.write(message + '\n') - else: - # テスト結果 NG - message = message + g_test_ng - print(message) - message = message + g_test_ng_message - fout.write(message + '\n') - # 受信データをテスト結果ファイルへコピー - fin2 = open(g_diff_recv_file, 'r') - while(1): - s2 = fin2.readline() - if len(s2) == 0: - break - fout.write(s2) - fin2.close() + message = g_mess_header + g_test_case + str(case_no) + " " + message = message + \ + "Connect(in->out, periodic,SKIP) -> Activate -> send/recv -> Deactivate -> Disconnect" + message = message + g_mess_footer + fout.write(message + '\n') fout.close() + print(message) - time.sleep(sleep_for_time) + for i in range(loop_count): -##-------------------------------------------------------------------- -## 接続タイプ:periodic 方向:in->out ポリシー:SKIP 接続・切断・Activate・Deactivateテスト1 -##-------------------------------------------------------------------- -case_no = case_no + 1 -fout = open(g_test_result_file, 'a') -message = g_mess_header + g_test_case + str(case_no) + " " -message = message + "Connect(in->out, periodic,SKIP) -> Activate -> send/recv -> Deactivate -> Disconnect" -message = message + g_mess_footer -fout.write(message + '\n') -fout.close() -print(message) + # 2 受信データファイル削除 + delete_recv_file() -for i in range(loop_count): + # 1 コネクタープロファイル設定 + make_connecter_profile("periodic", "SKIP", 1) - ## 2 受信データファイル削除 - delete_recv_file() + # 3 ポート接続 + # データポート1 TimedFloat + ret0 = g_out_ports[g_port1].connect(g_conprof1) - ## 1 コネクタープロファイル設定 - make_connecter_profile("periodic", "SKIP", 1) + # データポート2 TimedFloatSeq + ret1 = g_out_ports[g_port2].connect(g_conprof2) - ## 3 ポート接続 - # データポート1 TimedFloat - ret0 = g_out_ports[g_port1].connect(g_conprof1) + # サービスポート MyService + ret2 = g_out_ports[g_port3].connect(g_conprof3) - # データポート2 TimedFloatSeq - ret1 = g_out_ports[g_port2].connect(g_conprof2) + # 4 アクティベート + ec_recv[0].activate_component(g_compo_recv.rtc_ref) + time.sleep(sleep_recv_act_time) + ec_send[0].activate_component(g_compo_send.rtc_ref) - # サービスポート MyService - ret2 = g_out_ports[g_port3].connect(g_conprof3) + time.sleep(sleep_act_time) - ## 4 アクティベート - ec_recv[0].activate_component(g_compo_recv.rtc_ref) - time.sleep(sleep_recv_act_time) - ec_send[0].activate_component(g_compo_send.rtc_ref) + # 5 ディアクティベート + ec_send[0].deactivate_component(g_compo_send.rtc_ref) + ec_recv[0].deactivate_component(g_compo_recv.rtc_ref) - time.sleep(sleep_act_time) + # 6 ポート切断 + g_in_ports[g_port3].disconnect(g_conprof3.connector_id) + g_in_ports[g_port2].disconnect(g_conprof2.connector_id) + g_in_ports[g_port1].disconnect(g_conprof1.connector_id) - ## 5 ディアクティベート - ec_send[0].deactivate_component(g_compo_send.rtc_ref) - ec_recv[0].deactivate_component(g_compo_recv.rtc_ref) + # 受信ファイル有無判定 + if os.path.isfile(g_diff_recv_file) == False: + fout = open(g_test_result_file, 'a') + message = g_mess_header + g_test_case + \ + str(case_no) + " " + g_test_cnt + str(i + 1) + g_mess_footer + message = message + g_check_message + fout.write(message + '\n') + fout.close() + print(message) + time.sleep(sleep_for_time) + continue - ## 6 ポート切断 - g_in_ports[g_port3].disconnect(g_conprof3.connector_id) - g_in_ports[g_port2].disconnect(g_conprof2.connector_id) - g_in_ports[g_port1].disconnect(g_conprof1.connector_id) + # 7 送受信データ比較 + time.sleep(sleep_act_time) + bret = diff_file() - ## 受信ファイル有無判定 - if os.path.isfile(g_diff_recv_file) == False: + # 差分ファイルからテスト結果出力 fout = open(g_test_result_file, 'a') - message = g_mess_header + g_test_case + str(case_no) + " " + g_test_cnt + str(i+1) + g_mess_footer - message = message + g_check_message - fout.write(message + '\n') + message = g_mess_header + g_test_case + \ + str(case_no) + " " + g_test_cnt + str(i + 1) + g_mess_footer + # bret==True なら送受信データ一致 + if bret == True: + # テスト結果 OK + message = message + g_test_ok + print(message) + fout.write(message + '\n') + else: + # テスト結果 NG + message = message + g_test_ng + print(message) + message = message + g_test_ng_message + fout.write(message + '\n') + # 受信データをテスト結果ファイルへコピー + fin2 = open(g_diff_recv_file, 'r') + while(1): + s2 = fin2.readline() + if len(s2) == 0: + break + fout.write(s2) + fin2.close() fout.close() - print(message) - time.sleep(sleep_for_time) - continue - ## 7 送受信データ比較 - time.sleep(sleep_act_time) - bret = diff_file() + time.sleep(sleep_for_time) - ## 差分ファイルからテスト結果出力 - fout = open(g_test_result_file, 'a') - message = g_mess_header + g_test_case + str(case_no) + " " + g_test_cnt + str(i+1) + g_mess_footer - # bret==True なら送受信データ一致 - if bret == True: - # テスト結果 OK - message = message + g_test_ok - print(message) - fout.write(message + '\n') - else: - # テスト結果 NG - message = message + g_test_ng - print(message) - message = message + g_test_ng_message - fout.write(message + '\n') - # 受信データをテスト結果ファイルへコピー - fin2 = open(g_diff_recv_file, 'r') - while(1): - s2 = fin2.readline() - if len(s2) == 0: - break - fout.write(s2) - fin2.close() - fout.close() + print("Test Complete.") - time.sleep(sleep_for_time) -print("Test Complete.") +if __name__ == '__main__': + main() diff --git a/OpenRTM_aist/examples/AutoTest/CorbaNaming.py b/OpenRTM_aist/examples/AutoTest/CorbaNaming.py deleted file mode 100755 index 6ceb7305..00000000 --- a/OpenRTM_aist/examples/AutoTest/CorbaNaming.py +++ /dev/null @@ -1,1247 +0,0 @@ -#!/usr/bin/env python -# -*- coding: euc-jp -*- - - -## -# \file CorbaNaming.py -# \brief CORBA naming service helper class -# \author Noriaki Ando and Shinji Kurihara -# -# Copyright (C) 2006-2008 -# Noriaki Ando -# Task-intelligence Research Group, -# Intelligent Systems Research Institute, -# National Institute of -# Advanced Industrial Science and Technology (AIST), Japan -# All rights reserved. - -from __future__ import print_function -import omniORB.CORBA as CORBA -import CosNaming -import string -import sys -import traceback - -## -# @if jp -# @class CorbaNaming -# @brief CORBA Naming Service إѡ饹 -# -# Υ饹ϡCosNaming::NamingContext Фåѡ饹Ǥ롣 -# CosNaming::NamingContext ĥڥ졼ȤۤƱǽ -# ڥ졼󶡤ȤȤˡ͡ॳݡͥ CosNaming::Name -# ʸˤ̾ɽդ륪ڥ졼󶡤롣 -# -# ֥Ȥ뤤ľ CORBA ͡ॵФ³ -# ʸ塢Υ͡ॵФΥ롼ȥƥȤФƼΥڥ졼 -# 롣 -# ؤΥ͡ߥ󥰥ƥȤκ䥪֥ȤΥХɤˤơ -# ΥƥȤ¸ߤʤǤ⡢Ū˥ƥȤХ -# ŪΥƥȤ䥪֥ȤΥХɤԤȤǤ롣 -# -# @since 0.4.0 -# -# @else -# @class CorbaNaming -# @brief CORBA Naming Service helper class -# -# This class is a wrapper class of CosNaming::NamingContext. -# Almost the same operations which CosNaming::NamingContext has are -# provided, and some operation allows string naming representation of -# context and object instead of CosNaming::Name. -# -# The object of the class would connect to a CORBA naming server at -# the instantiation or immediately after instantiation. -# After that the object invokes operations to the root context of it. -# This class realizes forced binding to deep NamingContext, without binding -# intermediate NamingContexts explicitly. -# -# @since 0.4.0 -# -# @endif -class CorbaNaming: - """ - """ - - - - ## - # @if jp - # - # @brief 󥹥ȥ饯 - # - # @param self - # @param orb ORB - # @param name_server ͡ॵФ̾(ǥե:None) - # - # @else - # - # @brief Consructor - # - # @endif - def __init__(self, orb, name_server=None): - self._orb = orb - self._nameServer = "" - self._rootContext = CosNaming.NamingContext._nil - self._blLength = 100 - - if name_server: - self._nameServer = "corbaloc::" + name_server + "/NameService" - try: - obj = orb.string_to_object(self._nameServer) - self._rootContext = obj._narrow(CosNaming.NamingContext) - if CORBA.is_nil(self._rootContext): - print("CorbaNaming: Failed to narrow the root naming context.") - - except CORBA.ORB.InvalidName: - self.__print_exception() - print("Service required is invalid [does not exist].") - - return - - - ## - # @if jp - # - # @brief ǥȥ饯 - # - # @param self - # - # @else - # - # @brief destructor - # - # @endif - def __del__(self): - return - - - ## - # @if jp - # - # @brief ͡ߥ󥰥ӥν - # - # ꤵ줿͡ॵоΥ͡ߥ󥰥ӥޤ - # - # @param self - # @param name_server ͡ॵФ̾ - # - # @else - # - # @endif - def init(self, name_server): - self._nameServer = "corbaloc::" + name_server + "/NameService" - obj = self._orb.string_to_object(self._nameServer) - self._rootContext = obj._narrow(CosNaming.NamingContext) - if CORBA.is_nil(self._rootContext): - raise MemoryError - - return - - - ## - # @if jp - # - # @brief 롼ȥƥȤ¸Ƥ뤫֤ - # - # 롼ȥƥȤ¸Ƥ뤫ΥåԤ - # - # @param self - # @else - # @brief Check on whether the root context is alive. - # Check on whether the root context is alive. - # @param self - # @endif - # bool CorbaNaming::isAlive() - def isAlive(self): - try: - if self._rootContext._non_existent(): - return False - return True - except: - self.__print_exception() - return False - - return False - - - ## - # @if jp - # - # @brief Object bind - # - # CosNaming::bind() ȤۤƱƯ򤹤뤬Ϳ줿͡ॵФ - # 롼ȥƥȤФbind()ƤӽФۤʤ롣 - # - # Name Object NamingContext ˥Хɤ롣 - # c_n n ܤ NameComponent 򤢤魯Ȥȡ - # name n Ĥ NameComponent ȤʲΤ褦˰롣 - # - # cxt->bind(, obj) ϰʲƱǤ롣 - # cxt->resolve()->bind(, obj) - # - # ʤ1ܤn-1ܤΥƥȤ褷n-1ܤΥƥ - # name Ȥơobj bind 롣 - # ̾˻ä NemingContext ϡ - # bindContext() rebindContext() Ǵ˥ХɺѤߤǤʤФʤʤ - # ⤷ NamingContext ¸ߤʤˤϡ - # NotFound 㳰ȯ롣 - # - # Хɥե饰 force true λϡ - # ¸ߤʤˤ⡢ƵŪ˥ƥȤХɤʤ顢 - # ǽŪ obj ̾ name ˥Хɤ롣 - # - # ξǤ⡢n-1ܤΥƥȾ name Υ֥ - # (Object 뤤 ƥ) ХɤƤ - # AlreadyBound 㳰ȯ롣 - # - # @param self - # @param name_list ֥Ȥդ̾ NameComponent - # @param obj Ϣդ Object - # @param force trueξ硢ΥƥȤŪ˥Хɤ - # (ǥե:None) - # - # @exception NotFound ¸ߤʤ - # @exception CannotProceed 餫ͳǽ³Ǥʤ - # @exception InvalidName name_list ̾ - # @exception AlreadyBound name Object Ǥ˥ХɤƤ롣 - # - # @else - # - # @brief - # - # @endif - def bind(self, name_list, obj, force=None): - if force is None : - force = True - - try: - self._rootContext.bind(name_list, obj) - except CosNaming.NamingContext.NotFound: - if force: - self.bindRecursive(self._rootContext, name_list, obj) - else: - raise - except CosNaming.NamingContext.CannotProceed, err: - if force: - self.bindRecursive(err.cxt, err.rest_of_name, obj) - else: - raise - except CosNaming.NamingContext.AlreadyBound: - self._rootContext.rebind(name_list, obj) - - - ## - # @if jp - # - # @brief Object bind - # - # Object bind ݤͿ̾ʸɽǤ뤳Ȱʳϡbind() - # ƱǤ롣bind(toName(string_name), obj) - # - # @param self - # @param string_name ֥Ȥդ̾ʸɽ - # @param obj Ϣդ륪֥ - # @param force trueξ硢ΥƥȤŪ˥Хɤ - # (ǥե:true) - # - # @exception NotFound ¸ߤʤ - # @exception CannotProceed 餫ͳǽ³Ǥʤ - # @exception InvalidName string_name ̾ - # @exception AlreadyBound name Object Ǥ˥ХɤƤ롣 - # - # @else - # - # @brief - # - # @endif - def bindByString(self, string_name, obj, force=True): - self.bind(self.toName(string_name), obj, force) - - - ## - # @if jp - # - # @brief ΥƥȤ bind ʤ Object bind - # - # context Ϳ줿 NamingContext Фơname ǻꤵ줿 - # ͡ॳݡͥ NamingContext Ȥ - # 褷ʤ顢̾ Ф obj bind 롣 - # ⤷ б NamingContext ʤˤ - # NamingContext Хɤ롣 - # - # ǽŪ б NamingContext - # ޤϲ褵줿ǡCosNaming::bind(, object) ƤӽФ롣 - # ΤȤǤ˥Хǥ󥰤¸ߤ AlreadyBound㳰ȯ롣 - # - # ΥƥȤ褹ǡ褷褦Ȥ륳ƥȤ - # Ʊ̾ NamingContext ǤϤʤ Binding ¸ߤ硢 - # CannotProceed 㳰ȯߤ롣 - # - # @param self - # @param context bind 򳫻Ϥ롡NamingContext - # @param name_list ֥Ȥդ̾Υ͡ॳݡͥ - # @param obj Ϣդ륪֥ - # - # @exception CannotProceed б NamingContext - # ΤҤȤĤǤ NamingContext ʳ object ˥Х - # Ƥꡢ³Ǥʤ - # @exception InvalidName ̾ name_list - # @exception AlreadyBound name ˤǤ˲餫 object Х - # Ƥ롣 - # @else - # - # @brief - # - # @endif - def bindRecursive(self, context, name_list, obj): - length = len(name_list) - cxt = context - for i in range(length): - if i == length -1: - try: - cxt.bind(self.subName(name_list, i, i), obj) - except CosNaming.NamingContext.AlreadyBound: - cxt.rebind(self.subName(name_list, i, i), obj) - return - else: - if self.objIsNamingContext(cxt): - cxt = self.bindOrResolveContext(cxt,self.subName(name_list, i, i)) - else: - raise CosNaming.NamingContext.CannotProceed(cxt, self.subName(name_list, i)) - return - - - ## - # @if jp - # - # @brief Object rebind - # - # name_list ǻꤵ줿 Binding Ǥ¸ߤ bind() Ʊ - # Ǥ롣Хǥ󥰤Ǥ¸ߤˤϡХǥ󥰤 - # ֤롣 - # - # @param self - # @param name_list ֥Ȥդ̾ NameComponent - # @param obj Ϣդ륪֥ - # @param force trueξ硢ΥƥȤŪ˥Хɤ - # (ǥե:true) - # - # @exception NotFound ¸ߤʤ - # @exception CannotProceed 餫ͳǽ³Ǥʤ - # @exception InvalidName ̾ name_list - # - # @else - # - # @brief - # - # @endif - def rebind(self, name_list, obj, force=True): - if force is None: - force = True - - try: - self._rootContext.rebind(name_list, obj) - - except CosNaming.NamingContext.NotFound: - if force: - self.rebindRecursive(self._rootContext, name_list, obj) - else: - self.__print_exception() - raise - - except CosNaming.NamingContext.CannotProceed, err: - if force: - self.rebindRecursive(err.cxt, err,rest_of_name, obj) - else: - self.__print_exception() - raise - - return - - - ## - # @if jp - # - # @brief Object rebind - # - # Object rebind ݤͿ̾ʸɽǤ뤳Ȱʳ rebind() - # ƱǤ롣rebind(toName(string_name), obj) - # - # @param self - # @param string_name ֥Ȥդ̾ʸɽ - # @param obj Ϣդ륪֥ - # @param force trueξ硢ΥƥȤŪ˥Хɤ - # (ǥե:true) - # - # @exception NotFound ¸ߤʤ - # @exception CannotProceed 餫ͳǽ³Ǥʤ - # @exception InvalidName string_name ̾ - # - # @else - # - # @brief - # - # @endif - def rebindByString(self, string_name, obj, force=True): - self.rebind(self.toName(string_name), obj, force) - - return - - - ## - # @if jp - # - # @brief ΥƥȤ bind ʤ Object rebind - # - # name_list ǻꤵ줿 NamingContext ⤷ Object Ǥ¸ߤ - # bindRecursive() ƱǤ롣 - # - # name_list ǻꤵ줿Хǥ󥰤Ǥ¸ߤˤϡ - # Хǥ󥰤֤롣 - # - # @param self - # @param context bind 򳫻Ϥ롡NamingContext - # @param name_list ֥Ȥդ̾ NameComponent - # @param obj Ϣդ륪֥ - # - # @exception CannotProceed ΥƥȤǤʤ - # @exception InvalidName Ϳ줿 name_list - # - # @else - # - # @brief - # - # @endif - def rebindRecursive(self, context, name_list, obj): - length = len(name_list) - for i in range(length): - if i == length - 1: - context.rebind(self.subName(name_list, i, i), obj) - return - else: - if self.objIsNamingContext(context): - try: - context = context.bind_new_context(self.subName(name_list, i, i)) - except CosNaming.NamingContext.AlreadyBound: - obj_ = context.resolve(self.subName(name_list, i, i)) - context = obj_._narrow(CosNaming.NamingContext) - else: - raise CosNaming.NamingContext.CannotProceed(context, self.subName(name_list, i)) - return - - - ## - # @if jp - # - # @brief NamingContext bind - # - # bind оݤȤƻꤵ줿 name ʸξ bindByString() ȡ - # ʳξ bind() ƱǤ롣 - # - # @param self - # @param name ֥Ȥդ̾ - # @param name_cxt Ϣդ NamingContext - # @param force trueξ硢ΥƥȤŪ˥Хɤ - # (ǥե:True) - # - # @exception NotFound ¸ߤʤ - # @exception CannotProceed 餫ͳǽ³Ǥʤ - # @exception InvalidName name ̾ - # @exception AlreadyBound name Object Ǥ˥ХɤƤ롣 - # - # @else - # - # @brief - # - # @endif - def bindContext(self, name, name_cxt, force=True): - if isinstance(name, basestring): - self.bind(self.toName(name), name_cxt, force) - else: - self.bind(name, name_cxt, force) - return - - - ## - # @if jp - # - # @brief NamingContext bind - # - # bind 륪֥Ȥ NamingContext Ǥ뤳Ȥ - # bindRecursive() ƱǤ롣 - # - # @param self - # @param context bind 򳫻Ϥ롡NamingContext - # @param name_list ֥Ȥդ̾Υ͡ॳݡͥ - # @param name_cxt Ϣդ NamingContext - # - # @else - # - # @brief - # - # @endif - def bindContextRecursive(self, context, name_list, name_cxt): - self.bindRecursive(context, name_list, name_cxt) - return - - - ## - # @if jp - # - # @brief NamingContext rebind - # - # bind оݤȤƻꤵ줿 name ʸξ rebindByString() ȡ - # ʳξ rebind() ƱǤ롣 - # ɤξХǥ󥰤Ǥ¸ߤˤϡ - # Хǥ󥰤֤롣 - # - # @param self - # @param name ֥Ȥդ̾Υ͡ॳݡͥ - # @param name_cxt Ϣդ NamingContext - # @param force trueξ硢ΥƥȤŪ˥Хɤ - # (ǥե:true) - # - # @exception NotFound ¸ߤʤ - # @exception CannotProceed 餫ͳǽ³Ǥʤ - # @exception InvalidName name ̾ - # - # @else - # - # @endif - def rebindContext(self, name, name_cxt, force=True): - if isinstance(name, basestring): - self.rebind(self.toName(name), name_cxt, force) - else: - self.rebind(name, name_cxt, force) - return - - - ## - # @if jp - # - # @brief ΥƥȤƵŪ rebind NamingContext rebind # - # bind 륪֥Ȥ NamingContext Ǥ뤳Ȥ - # rebindRecursive() ƱǤ롣 - # - # @param self - # @param context bind 򳫻Ϥ롡NamingContext - # @param name_list ֥Ȥդ̾ NameComponent - # @param name_cxt Ϣդ NamingContext - # - # @else - # - # @brief - # - # @endif - def rebindContextRecursive(self, context, name_list, name_cxt): - self.rebindRecursive(context, name_list, name_cxt) - return - - - ## - # @if jp - # - # @brief Object name 褹 - # - # name bind Ƥ륪֥ȻȤ֤ - # ͡ॳݡͥ ϺƵŪ˲褵롣 - # - # name Ϳ줿ͤʸξˤϤޤǽ toName() ˤä - # NameComponent Ѵ롣 - # - # CosNaming::resolve() ȤۤƱƯ򤹤뤬Ϳ줿 - # ͡ॵФΥ롼ȥƥȤФ resolve() ƤӽФ - # ۤʤ롣 - # - # @param self - # @param name 褹٤֥Ȥ̾Υ͡ॳݡͥ - # - # @return 褵줿֥Ȼ - # - # @exception NotFound ¸ߤʤ - # @exception CannotProceed 餫ͳǽ³Ǥʤ - # @exception InvalidName name ̾ - # - # @else - # - # @endif - def resolve(self, name): - if isinstance(name, basestring): - name_ = self.toName(name) - else: - name_ = name - - try: - obj = self._rootContext.resolve(name_) - return obj - except CosNaming.NamingContext.NotFound, ex: - self.__print_exception() - return None - - - ## - # @if jp - # - # @brief ꤵ줿̾Υ֥Ȥ bind - # - # name bind Ƥ륪֥ȻȤ롣 - # ͡ॳݡͥ ϺƵŪ˲褵롣 - # - # name Ϳ줿ͤʸξˤϤޤǽ toName() ˤä - # NameComponent Ѵ롣 - # - # CosNaming::unbind() ȤۤƱƯ򤹤뤬Ϳ줿 - # ͡ॵФΥ롼ȥƥȤФ unbind() ƤӽФ - # ۤʤ롣 - # - # @param self - # @param name 륪֥ȤΥ͡ॳݡͥ - # - # @exception NotFound ¸ߤʤ - # @exception CannotProceed 餫ͳǽ³Ǥʤ - # @exception InvalidName name ̾ - # - # @else - # - # @endif - # void unbind(const CosNaming::Name& name) - # throw(NotFound, CannotProceed, InvalidName); - def unbind(self, name): - if isinstance(name, basestring): - name_ = self.toName(name) - else: - name_ = name - - try: - self._rootContext.unbind(name_) - except: - self.__print_exception() - - return - - - ## - # @if jp - # - # @brief ƥȤ - # - # Ϳ줿͡ॵо줿 NamingContext ֤ - # ֤줿 NamingContext bind Ƥʤ - # - # @param self - # - # @return 줿 NamingContext - # - # @else - # - # @endif - def newContext(self): - return self._rootContext.new_context() - - - ## - # @if jp - # - # @brief ƥȤ bind - # - # Ϳ줿 name ФƿƥȤХɤ롣 - # 줿NamingContext ϥ͡ॵо줿ΤǤ롣 - # - # name Ϳ줿ͤʸξˤϤޤǽ toName() ˤä - # NameComponent Ѵ롣 - # - # @param self - # @param name NamingContextդ̾Υ͡ॳݡͥ - # @param force trueξ硢ΥƥȤŪ˥Хɤ - # (ǥե:true) - # - # @return 줿 NamingContext - # - # @exception NotFound ¸ߤʤ - # @exception CannotProceed 餫ͳǽ³Ǥʤ - # @exception InvalidName name ̾ - # @exception AlreadyBound name Object Ǥ˥ХɤƤ롣 - # - # @else - # - # @endif - def bindNewContext(self, name, force=True): - if force is None: - force = True - - if isinstance(name, basestring): - name_ = self.toName(name) - else: - name_ = name - - try: - return self._rootContext.bind_new_context(name_) - except CosNaming.NamingContext.NotFound: - if force: - self.bindRecursive(self._rootContext, name_, self.newContext()) - else: - self.__print_exception() - raise - except CosNaming.NamingContext.CannotProceed, err: - if force: - self.bindRecursive(err.cxt, err.rest_of_name, self.newContext()) - else: - self.__print_exception() - raise - return None - - - ## - # @if jp - # - # @brief NamingContext 󥢥ƥֲ - # - # context ǻꤵ줿 NamingContext 󥢥ƥֲ롣 - # context ¾ΥƥȤХɤƤ NotEmpty 㳰 - # ȯ롣 - # - # @param self - # @param context 󥢥ƥֲ NamingContext - # - # @exception NotEmpty оcontext ¾ΥƥȤХɤƤ롣 - # - # @else - # - # @else - # - # @brief Destroy the naming context - # - # Delete the specified naming context. - # any bindings should be in which the given context is bound to - # some names before invoking operation on it. - # - # @param context NamingContext which is destroied. - # - # @exception NotEmpty - # - # @else - # - # @endif - def destroy(self, context): - context.destroy() - - - ## - # @if jp - # @brief NamingContext ƵŪ˲ä󥢥ƥֲ - # - # context Ϳ줿 NamingContext Фơname ǻꤵ줿 - # ͡ॳݡͥ NamingContext Ȥ - # 褷ʤ顢̾ Ф 󥢥ƥֲԤ - # - # @param self - # @param context 󥢥ƥֲ NamingContext - # - # @exception NotEmpty оcontext ¾ΥƥȤХɤƤ롣 - # @exception NotFound ¸ߤʤ - # @exception CannotProceed 餫ͳǽ³Ǥʤ - # @exception InvalidName name ̾ - # - # @else - # @brief Destroy the naming context recursively - # @endif - def destroyRecursive(self, context): - cont = True - bl = [] - bi = 0 - bl, bi = context.list(self._blLength) - while cont: - for i in range(len(bl)): - if bl[i].binding_type == CosNaming.ncontext: - obj = context.resolve(bl[i].binding_name) - next_context = obj._narrow(CosNaming.NamingContext) - - self.destroyRecursive(next_context) - context.unbind(bl[i].binding_name) - next_context.destroy() - elif bl[i].binding_type == CosNaming.nobject: - context.unbind(bl[i].binding_name) - else: - assert(0) - if CORBA.is_nil(bi): - cont = False - else: - bi.next_n(self._blLength, bl) - - if not (CORBA.is_nil(bi)): - bi.destroy() - return - - - ## - # @if jp - # @brief ٤Ƥ Binding - # - # ϿƤƤBinding 롣 - # - # @param self - # - # @else - # @brief Destroy all binding - # @endif - def clearAll(self): - self.destroyRecursive(self._rootContext) - return - - - ## - # @if jp - # @brief Ϳ줿 NamingContext Binding - # - # ꤵ줿 NamingContext Binding 롣 - # - # @param self - # @param name_cxt Binding о NamingContext - # @param how_many Binding 볬ؤο - # @param rbl Binding ݻۥ - # @param rbi Binding 򤿤ɤ뤿Υƥ졼 - # - # @else - # @endif - def list(self, name_cxt, how_many, rbl, rbi): - bl, bi = name_cxt.list(how_many) - - for i in bl: - rbl.append(bl) - - rbi.append(bi) - - - #============================================================ - # interface of NamingContext - #============================================================ - - ## - # @if jp - # @brief Ϳ줿 NameComponent ʸɽ֤ - # - # ꤵ줿 NameComponent ʸѴ롣 - # - # @param self - # @param name_list Ѵо NameComponent - # - # @return ʸѴ - # - # @exception InvalidName name_list ̾ - # - # @else - # @brief Get string representation of given NameComponent - # @endif - def toString(self, name_list): - if len(name_list) == 0: - raise CosNaming.NamingContext.InvalidName - - slen = self.getNameLength(name_list) - string_name = [""] - self.nameToString(name_list, string_name, slen) - - return string_name[0] - - - ## - # @if jp - # @brief Ϳ줿ʸɽ NameComponent ʬ򤹤 - # - # ꤵ줿ʸ NameComponent Ѵ롣 - # - # @param self - # @param sname Ѵоʸ - # - # @return NameComponent Ѵ - # - # @exception InvalidName sname - # - # @else - # @brief Get NameComponent from gien string name representation - # @endif - def toName(self, sname): - if not sname: - raise CosNaming.NamingContext.InvalidName - - string_name = sname - name_comps = [] - - nc_length = 0 - nc_length = self.split(string_name, "/", name_comps) - - if not (nc_length > 0): - raise CosNaming.NamingContext.InvalidName - - name_list = [CosNaming.NameComponent("","") for i in range(nc_length)] - - for i in range(nc_length): - pos = str.rfind(name_comps[i][0:],".") - if pos == -1: - name_list[i].id = name_comps[i] - name_list[i].kind = "" - else: - name_list[i].id = name_comps[i][0:pos] - name_list[i].kind = name_comps[i][(pos+1):] - - return name_list - - - ## - # @if jp - # @brief Ϳ줿 addr string_name URLɽ - # - # ꤵ줿ɥ쥹̾ΤURLѴ롣 - # - # @param self - # @param addr Ѵоݥɥ쥹 - # @param string_name Ѵо̾ - # - # @return URL Ѵ - # - # @exception InvalidAddress addr - # @exception InvalidName string_name - # - # @else - # @brief Get URL representation from given addr and string_name - # @endif - def toUrl(self, addr, string_name): - return self._rootContext.to_url(addr, string_name) - - - ## - # @if jp - # @brief Ϳ줿ʸɽ resolve ֥Ȥ֤ - # - # ꤵ줿ʸɽresolve֥Ȥ롣 - # - # @param self - # @param string_name оݥ֥ʸɽ - # - # @return 褵줿֥ - # - # @exception NotFound ¸ߤʤ - # @exception CannotProceed 餫ͳǽ³Ǥʤ - # @exception InvalidName name ̾ - # @exception AlreadyBound name Object Ǥ˥ХɤƤ롣 - # - # @else - # @brief Resolve from name of string representation and get object - # @endif - def resolveStr(self, string_name): - return self.resolve(self.toName(string_name)) - - - #============================================================ - # Find functions - #============================================================ - - ## - # @if jp - # - # @brief ֥Ȥ̾Хɤޤϲ褹 - # - # ꤵ줿ƥȤФƥ֥Ȥ NameComponent ǻꤵ줿 - # ֤˥Хɤ롣 - # Ʊս˴¾ǤХɺѤߤξϡ¸ΥХɺѤǤ - # 롣 - # - # @param self - # @param context bind ⤷ resole оݥƥ - # @param name_list ֥Ȥդ̾ NameComponent - # @param obj Ϣդ Object - # - # @return NameComponent ǻꤵ줿֤˥ХɤƤ륪֥ - # - # @else - # @brief Bind of resolve the given name component - # @endif - def bindOrResolve(self, context, name_list, obj): - try: - context.bind_context(name_list, obj) - return obj - except CosNaming.NamingContext.AlreadyBound: - obj = context.resolve(name_list) - return obj - return CORBA.Object._nil - - - ## - # @if jp - # - # @brief ƥȤ̾Хɤޤϲ褹 - # - # ꤵ줿ƥȤФ Context NameComponent ǻꤵ줿֤ - # Хɤ롣 - # Context ξϿƥȤƥХɤ롣 - # Ʊս˴¾ǤХɺѤߤξϡ¸ΥХɺѤǤ - # 롣 - # - # @param self - # @param context bind ⤷ resole оݥƥ - # @param name_list ƥȤդ̾ NameComponent - # @param new_context Ϣդ Context(ǥե:None) - # - # @return NameComponent ǻꤵ줿֤˥ХɤƤContext - # - # @else - # @brief Bind of resolve the given name component - # @endif - def bindOrResolveContext(self, context, name_list, new_context=None): - if new_context is None: - new_cxt = self.newContext() - else: - new_cxt = new_context - - obj = self.bindOrResolve(context, name_list, new_cxt) - return obj._narrow(CosNaming.NamingContext) - - - ## - # @if jp - # @brief ͡ॵФ̾ - # - # ꤷ͡ॵФ̾롣 - # - # @param self - # - # @return ͡ॵФ̾ - # - # @else - # @brief Get the name of naming server - # @endif - def getNameServer(self): - return self._nameServer - - - ## - # @if jp - # @brief 롼ȥƥȤ - # - # ꤷ͡ॵФΥ롼ȥƥȤ롣 - # - # @param self - # - # @return ͡ॵФΥ롼ȥƥ - # - # @else - # @brief Get the root context - # @endif - def getRootContext(self): - return self._rootContext - - - ## - # @if jp - # @brief ֥Ȥ͡ߥ󥰥ƥȤȽ̤ - # - # ꤷǤ͡ߥ󥰥ƥȤȽ̤ - # - # @param self - # @param obj Ƚо - # - # @return Ƚ̷(͡ߥ󥰥ƥ:trueʳ:false) - # - # @else - # @brief Whether the object is NamingContext - # @endif - def objIsNamingContext(self, obj): - nc = obj._narrow(CosNaming.NamingContext) - if CORBA.is_nil(nc): - return False - else: - return True - - - ## - # @if jp - # @brief Ϳ줿̾͡ߥ󥰥ƥȤɤȽ̤ - # - # NameComponent ⤷ʸǻꤷǤ͡ߥ󥰥ƥȤ - # Ƚ̤ - # - # @param self - # @param name_list Ƚо - # - # @return Ƚ̷(͡ߥ󥰥ƥ:trueʳ:false) - # - # @else - # @brief Whether the given name component is NamingContext - # @endif - def nameIsNamingContext(self, name_list): - return self.objIsNamingContext(self.resolve(name_list)) - - - ## - # @if jp - # @brief ͡ॳݡͥȤʬ֤ - # - # ꤵ줿ϰϤΥ͡ॳݡͥȤ롣 - # λ֤ꤵƤʤϡǸǤ͡ॳݡͥ - # ֤ - # - # @param self - # @param name_list оNameComponent - # @param begin ϰϳϰ - # @param end ϰϽλ(ǥե:None) - # - # @return NameComponent - # - # @else - # @brief Get subset of given name component - # @endif - def subName(self, name_list, begin, end = None): - if end is None or end < 0: - end = len(name_list) - 1 - - sub_len = end - (begin -1) - objId = "" - kind = "" - - sub_name = [] - for i in range(sub_len): - sub_name.append(name_list[begin + i]) - - return sub_name - - - ## - # @if jp - # @brief ͡ॳݡͥȤʸɽ - # - # ꤷϰϤΥ͡ॳݡͥȤʸɽ롣 - # ʸɽϡNameComponentι{Nc[0],Nc[1],Nc[2]}ξ硢 - # Nc[0]id.Nc[0].kind/Nc[1]id.Nc[1].kind/Nc[2].id/Nc[2].kind - # ȤǼǤ롣 - # ʸĹꤷĹʾξϡ - # ꤷĹڤΤƤ롣 - # - # @param self - # @param name_list оNameComponent - # @param string_name ʸ - # @param slen оʸ - # - # @else - # @brief Get string representation of name component - # @endif - def nameToString(self, name_list, string_name, slen): - for i in range(len(name_list)): - for id_ in name_list[i].id: - if id_ == "/" or id_ == "." or id_ == "\\": - string_name[0] += "\\" - string_name[0] += id_ - - if name_list[i].id == "" or name_list[i].kind != "": - string_name[0] += "." - - for kind_ in name_list[i].kind: - if kind_ == "/" or kind_ == "." or kind_ == "\\": - string_name[0] += "\\" - string_name[0] += kind_ - - string_name[0] += "/" - - - ## - # @if jp - # @brief ͡ॳݡͥȤʸɽʸĹ - # - # ꤷ͡ॳݡͥȤʸɽĹ롣 - # ʸɽϡNameComponentι{Nc[0],Nc[1],Nc[2]}ξ硢 - # Nc[0]id.Nc[0].kind/Nc[1]id.Nc[1].kind/Nc[2].id/Nc[2].kind - # ȤǼǤ롣 - # - # @param self - # @param name_list оNameComponent - # - # @return ꤷ͡ॳݡͥȤʸĹ - # - # @else - # @brief Get string length of the name component's string representation - # @endif - def getNameLength(self, name_list): - slen = 0 - - for i in range(len(name_list)): - for id_ in name_list[i].id: - if id_ == "/" or id_ == "." or id_ == "\\": - slen += 1 - slen += 1 - if name_list[i].id == "" or name_list[i].kind == "": - slen += 1 - - for kind_ in name_list[i].kind: - if kind_ == "/" or kind_ == "." or kind_ == "\\": - slen += 1 - slen += 1 - - slen += 1 - - return slen - - - ## - # @if jp - # @brief ʸʬ - # - # ʸꤷǥߥʬ䤹롣 - # - # @param self - # @param input ʬоʸ - # @param delimiter ʬѥǥߥ - # @param results ʬ - # - # @return ʬ䤷ʸǿ - # - # @else - # @brief Split of string - # @endif - def split(self, input, delimiter, results): - delim_size = len(delimiter) - found_pos = 0 - begin_pos = 0 - pre_pos = 0 - substr_size = 0 - - if input[0:delim_size] == delimiter: - begin_pos = delim_size - pre_pos = delim_size - - while 1: - found_pos = str.find(input[begin_pos:],delimiter) - if found_pos == -1: - results.append(input[pre_pos:]) - break - - if found_pos > 0 and input[found_pos + begin_pos - 1] == "\\": - begin_pos += found_pos + delim_size - else: - substr_size = found_pos + (begin_pos - pre_pos) - if substr_size > 0: - results.append(input[pre_pos:(pre_pos+substr_size)]) - begin_pos += found_pos + delim_size - pre_pos = begin_pos - - return len(results) - - - ## - # @if jp - # - # @brief 㳰 - # 㳰Ϥ롣 - # - # @else - # - # @brief Print exception information - # Print exception information - # @endif - def __print_exception(self): - if sys.version_info[0:3] >= (2, 4, 0): - print(traceback.format_exc()) - else: - _exc_list = traceback.format_exception(*sys.exc_info()) - _exc_str = "".join(_exc_list) - print(_exc_str) - - return diff --git a/OpenRTM_aist/examples/AutoTest/__init__.py b/OpenRTM_aist/examples/AutoTest/__init__.py index 932b7982..270be2a2 100644 --- a/OpenRTM_aist/examples/AutoTest/__init__.py +++ b/OpenRTM_aist/examples/AutoTest/__init__.py @@ -1 +1 @@ -# Empty file +# Empty file diff --git a/OpenRTM_aist/examples/AutoTest/rtc_handle.py b/OpenRTM_aist/examples/AutoTest/rtc_handle.py index 4bd7a9a8..a21a4f6f 100755 --- a/OpenRTM_aist/examples/AutoTest/rtc_handle.py +++ b/OpenRTM_aist/examples/AutoTest/rtc_handle.py @@ -1,4 +1,4 @@ -#/usr/bin/env python +#!/usr/bin/env python # -*- coding: utf-8 -*- # -*- Python -*- @@ -11,26 +11,28 @@ import RTC -from CorbaNaming import * +from OpenRTM_aist.CorbaNaming import * import SDOPackage # class RtmEnv : # rtm environment manager # orb, naming service, rtc proxy list # -class RtmEnv : - def __init__(self, orb_args, nserver_names=["localhost"], - orb=None, naming=None): - if not orb : + +class RtmEnv: + + def __init__(self, orb_args, nserver_names=["localhost"], + orb=None, naming=None): + if not orb: orb = CORBA.ORB_init(orb_args) self.orb = orb self.name_space = {} - if naming : # naming can specify only one naming service - self.name_space['default']=NameSpace(orb, naming=naming) - else : - for ns in nserver_names : - self.name_space[ns]=NameSpace(orb, server_name=ns) + if naming: # naming can specify only one naming service + self.name_space['default'] = NameSpace(orb, naming=naming) + else: + for ns in nserver_names: + self.name_space[ns] = NameSpace(orb, server_name=ns) def __del__(self): self.orb.shutdown(wait_for_completion=CORBA.FALSE) @@ -39,77 +41,80 @@ def __del__(self): # class NameSpace : # rtc_handles and object list in naming service # -class NameSpace : + + +class NameSpace: def __init__(self, orb, server_name=None, naming=None): self.orb = orb self.name = server_name - if naming : - self.naming = naming - else : - self.naming = CorbaNaming(self.orb, server_name) + if naming: + self.naming = naming + else: + self.naming = CorbaNaming(self.orb, server_name) - self.b_len = 10 # iteration cut off no. + self.b_len = 10 # iteration cut off no. self.rtc_handles = {} self.obj_list = {} def get_object_by_name(self, name, cl=RTC.RTObject): ref = self.naming.resolveStr(name) - if ref is None: return None # return CORBA.nil ? - if cl : + if ref is None: + return None # return CORBA.nil ? + if cl: return ref._narrow(cl) - else : + else: return ref - def list_obj(self) : + def list_obj(self): self.rtc_handes = {} self.obj_list = {} return self.list_obj1(self.naming._rootContext, "") - def list_obj1(self, name_context, parent) : - if not name_context : - name_context = self.naming._rootContext + def list_obj1(self, name_context, parent): + if not name_context: + name_context = self.naming._rootContext rslt = [] b_list = name_context.list(self.b_len) - for bd in b_list[0] : + for bd in b_list[0]: rslt = rslt + self.proc_bd(bd, name_context, parent) - if b_list[1] : # iterator : there exists remaining. + if b_list[1]: # iterator : there exists remaining. t_list = b_list[1].next_n(self.b_len) - while t_list[0] : - for bd in t_list[1] : + while t_list[0]: + for bd in t_list[1]: rslt = rslt + self.proc_bd(bd, name_context, parent) t_list = b_list[1].next_n(self.b_len) return rslt - def proc_bd(self, bd, name_context, parent) : -# print('-------------------------------------------------------------------') -# print('bd= ', bd) -# print('name_context= ', name_context) -# print('parent= ', parent) + def proc_bd(self, bd, name_context, parent): + # print('-------------------------------------------------------------------') + # print('bd= ', bd) + # print('name_context= ', name_context) + # print('parent= ', parent) rslt = [] pre = "" - if parent : + if parent: pre = parent + "/" nam = pre + URI.nameToString(bd.binding_name) - if bd.binding_type == CosNaming.nobject : + if bd.binding_type == CosNaming.nobject: tmp = name_context.resolve(bd.binding_name) - self.obj_list[nam]=tmp - print('objcet '+nam+' was listed.') - try : + self.obj_list[nam] = tmp + print('objcet ' + nam + ' was listed.') + try: tmp = tmp._narrow(RTC.RTObject) - except : - print(nam+' is not RTC.') + except BaseException: + print(nam + ' is not RTC.') tmp = None - try : - if tmp : - rslt = [[nam, tmp]] - self.rtc_handles[nam]=RtcHandle(nam,self,tmp) - print('handle for '+nam+' was created.') - else : - pass - except : - print(nam+' is not alive.') + try: + if tmp: + rslt = [[nam, tmp]] + self.rtc_handles[nam] = RtcHandle(nam, self, tmp) + print('handle for ' + nam + ' was created.') + else: + pass + except BaseException: + print(nam + ' is not alive.') pass - else : + else: tmp = name_context.resolve(bd.binding_name) tmp = tmp._narrow(CosNaming.NamingContext) rslt = self.list_obj1(tmp, nam) @@ -118,120 +123,132 @@ def proc_bd(self, bd, name_context, parent) : # # data conversion # -def nvlist2dict(nvlist) : + + +def nvlist2dict(nvlist): rslt = {} - for tmp in nvlist : - rslt[tmp.name]=tmp.value.value() # nv.value and any.value() + for tmp in nvlist: + rslt[tmp.name] = tmp.value.value() # nv.value and any.value() return rslt -def dict2nvlist(dict) : + + +def dict2nvlist(dict): rslt = [] - for tmp in dict.keys() : + for tmp in dict.keys(): rslt.append(SDOPackage.NameValue(tmp, any.to_any(dict[tmp]))) return rslt # # connector, port, inport, outport, service -# - -class Connector : - def __init__(self, plist, name = None, id="", prop_dict={}) : - self.plist = plist - self.port_reflist = [tmp.port_profile.port_ref for tmp in plist] - if name : - self.name = name - else : - self.name = string.join([tmp.name for tmp in plist],'_') - self.prop_dict = prop_dict - self.prop_nvlist = dict2nvlist(self.prop_dict) - self.profile = RTC.ConnectorProfile(self.name, id, self.port_reflist, self.prop_nvlist) - self.nego_prop() - - def nego_prop(self) : - self.possible = True - for kk in self.def_prop : - if kk in self.prop_dict : - if not self.prop_dict[kk] : - self.prop_dict[kk]=self.def_prop[kk] - else : - self.prop_dict[kk]=self.def_prop[kk] - for pp in self.plist : - if not ((self.prop_dict[kk] in pp.prop[kk]) or - ('Any' in pp.prop[kk])) : - self.prop_dict[kk] = "" - self.possible = False - self.prop_nvlist = dict2nvlist(self.prop_dict) - self.profile.properties = self.prop_nvlist - return self.possible - - def connect(self) : # -# out and inout parameters are retuned as a tuple -# - ret, self.profile = self.port_reflist[0].connect(self.profile) - self.prop_nvlist = self.profile.properties - self.prop_dict = nvlist2dict(self.prop_nvlist) - return ret - - def disconnect(self) : - ret = self.port_reflist[0].disconnect(self.profile.connector_id) - return ret - -class IOConnector(Connector) : - def __init__(self, plist, name = None, id="", prop_dict={}) : -# self.def_prop = {'dataport.dataflow_type':'Push' , -# 'dataport.interface_type':'CORBA_Any' , -# 'dataport.subscription_type':'Flush'} - self.def_prop = {'dataport.dataflow_type':'push' , - 'dataport.interface_type':'corba_cdr' , - 'dataport.subscription_type':'flush'} - Connector.__init__(self, plist, name, id, prop_dict) - -class ServiceConnector(Connector) : - def __init__(self, plist, name = None, id="", prop_dict={}) : - self.def_prop = {'port.port_type':'CorbaPort' } - Connector.__init__(self, plist, name, id, prop_dict) - - -class Port : - def __init__(self, profile,nv_dict=None) : - self.name=profile.name + + +class Connector: + def __init__(self, plist, name=None, id="", prop_dict={}): + self.plist = plist + self.port_reflist = [tmp.port_profile.port_ref for tmp in plist] + if name: + self.name = name + else: + self.name = string.join([tmp.name for tmp in plist], '_') + self.prop_dict = prop_dict + self.prop_nvlist = dict2nvlist(self.prop_dict) + self.profile = RTC.ConnectorProfile( + self.name, id, self.port_reflist, self.prop_nvlist) + self.nego_prop() + + def nego_prop(self): + self.possible = True + for kk in self.def_prop: + if kk in self.prop_dict: + if not self.prop_dict[kk]: + self.prop_dict[kk] = self.def_prop[kk] + else: + self.prop_dict[kk] = self.def_prop[kk] + for pp in self.plist: + if not ((self.prop_dict[kk] in pp.prop[kk]) or + ('Any' in pp.prop[kk])): + self.prop_dict[kk] = "" + self.possible = False + self.prop_nvlist = dict2nvlist(self.prop_dict) + self.profile.properties = self.prop_nvlist + return self.possible + + def connect(self): + # + # out and inout parameters are retuned as a tuple + # + ret, self.profile = self.port_reflist[0].connect(self.profile) + self.prop_nvlist = self.profile.properties + self.prop_dict = nvlist2dict(self.prop_nvlist) + return ret + + def disconnect(self): + ret = self.port_reflist[0].disconnect(self.profile.connector_id) + return ret + + +class IOConnector(Connector): + def __init__(self, plist, name=None, id="", prop_dict={}): + # self.def_prop = {'dataport.dataflow_type':'Push' , + # 'dataport.interface_type':'CORBA_Any' , + # 'dataport.subscription_type':'Flush'} + self.def_prop = {'dataport.dataflow_type': 'push', + 'dataport.interface_type': 'corba_cdr', + 'dataport.subscription_type': 'flush'} + Connector.__init__(self, plist, name, id, prop_dict) + + +class ServiceConnector(Connector): + def __init__(self, plist, name=None, id="", prop_dict={}): + self.def_prop = {'port.port_type': 'CorbaPort'} + Connector.__init__(self, plist, name, id, prop_dict) + + +class Port: + def __init__(self, profile, nv_dict=None): + self.name = profile.name self.port_profile = profile - if not nv_dict : + if not nv_dict: nv_dict = nvlist2dict(profile.properties) self.prop = nv_dict self.con = None # this must be set in each subclasses - def get_info(self) : + + def get_info(self): self.con.connect() tmp1 = self.get_connections() tmp2 = [pp.connector_id for pp in tmp1] - if self.con.profile.connector_id in tmp2 : + if self.con.profile.connector_id in tmp2: self.con.disconnect() - def get_connections(self) : + def get_connections(self): return self.port_profile.port_ref.get_connector_profiles() -class CorbaServer : - def __init__(self, profile, port) : + +class CorbaServer: + def __init__(self, profile, port): self.profile = profile self.port = port self.name = profile.instance_name self.type = profile.type_name self.ref = None ref_key = 'port.' + self.type + '.' + self.name - self.ref=self.port.con.prop_dict[ref_key] + self.ref = self.port.con.prop_dict[ref_key] # # if we import stubs before we create instances, # we rarely need to narrow the object references. # we need to specify global symbol table to evaluate class symbols. # - def narrow_ref(self, gls) : - if self.type.find('::') == -1 : + + def narrow_ref(self, gls): + if self.type.find('::') == -1: self.narrow_sym = eval('_GlobalIDL.' + self.type, gls) - else : - self.narrow_sym = eval(self.type.replace('::','.'), gls) + else: + self.narrow_sym = eval(self.type.replace('::', '.'), gls) self.ref = self.ref._narrow(self.narrow_sym) -class CorbaClient : - def __init__(self, profile) : + +class CorbaClient: + def __init__(self, profile): self.profile = profile self.name = profile.instance_name self.type = profile.type_name @@ -241,114 +258,123 @@ def __init__(self, profile) : # but .... # -class RtcService(Port) : - def __init__(self, profile,nv_dict=None) : + +class RtcService(Port): + def __init__(self, profile, nv_dict=None): Port.__init__(self, profile, nv_dict) self.con = ServiceConnector([self]) self.get_info() - self.provided={} - self.required={} + self.provided = {} + self.required = {} tmp = self.port_profile.interfaces - for itf in tmp : - if itf.polarity == RTC.PROVIDED : - self.provided[itf.instance_name] = CorbaServer(itf,self) - elif itf.polarity == RTC.REQUIRED : + for itf in tmp: + if itf.polarity == RTC.PROVIDED: + self.provided[itf.instance_name] = CorbaServer(itf, self) + elif itf.polarity == RTC.REQUIRED: self.required[itf.instance_name] = CorbaClient(itf) -class RtcInport(Port) : - def __init__(self, profile, nv_dict=None) : + +class RtcInport(Port): + def __init__(self, profile, nv_dict=None): Port.__init__(self, profile, nv_dict) self.con = IOConnector([self]) - self.get_info() + self.get_info() # self.ref = self.con.prop_dict['dataport.corba_any.inport_ref'] self.ref = self.con.prop_dict['dataport.corba_cdr.inport_ref'] self.data_class = eval('RTC.' + self.prop['dataport.data_type']) self.data_tc = eval('RTC._tc_' + self.prop['dataport.data_type']) - def write(self,data) : + + def write(self, data): self.ref.put(CORBA.Any(self.data_tc, - self.data_class(RTC.Time(0,0),data))) + self.data_class(RTC.Time(0, 0), data))) + -class RtcOutport(Port) : - def __init__(self, profile,nv_dict=None) : +class RtcOutport(Port): + def __init__(self, profile, nv_dict=None): Port.__init__(self, profile, nv_dict) self.con = IOConnector([self]) self.get_info() - if 'dataport.corba_any.outport_ref' in self.con.prop_dict : - self.ref = self.con.prop_dict['dataport.corba_cdr.outport_ref'] + if 'dataport.corba_any.outport_ref' in self.con.prop_dict: + self.ref = self.con.prop_dict['dataport.corba_cdr.outport_ref'] # self.ref = self.con.prop_dict['dataport.corba_any.outport_ref'] - else : - self.ref=None + else: + self.ref = None self.data_class = eval('RTC.' + self.prop['dataport.data_type']) self.data_tc = eval('RTC._tc_' + self.prop['dataport.data_type']) - def read(self) : - if self.ref : - return self.ref.get().value() - else : - print("not supported") - return None + def read(self): + if self.ref: + return self.ref.get().value() + else: + print("not supported") + return None # # RtcHandle # -class RtcHandle : - def __init__(self, name, env, ref=None) : - self.name = name - self.env = env - if ref : - self.rtc_ref = ref - else : - self.rtc_ref = env.naming.resolve(name)._narrow(RTC.RTObject) - self.conf_ref = None - self.retrieve_info() - - def retrieve_info(self) : - self.conf_set={} - self.conf_set_data={} - self.port_refs = [] - self.execution_contexts =[] - if self.rtc_ref : - self.conf_ref = self.rtc_ref.get_configuration() - conf_set = self.conf_ref.get_configuration_sets() - for cc in conf_set : - self.conf_set[cc.id]=cc - self.conf_set_data[cc.id]=nvlist2dict(cc.configuration_data) - self.profile = self.rtc_ref.get_component_profile() - self.prop = nvlist2dict(self.profile.properties) - #self.execution_contexts = self.rtc_ref.get_contexts() - self.execution_contexts = self.rtc_ref.get_owned_contexts() - self.port_refs = self.rtc_ref.get_ports() - # this includes inports, outports and service ports - self.ports = {} - self.services = {} - self.inports = {} - self.outports = {} - for pp in self.port_refs : - tmp = pp.get_port_profile() - tmp_prop = nvlist2dict(tmp.properties) + + +class RtcHandle: + def __init__(self, name, env, ref=None): + self.name = name + self.env = env + if ref: + self.rtc_ref = ref + else: + self.rtc_ref = env.naming.resolve(name)._narrow(RTC.RTObject) + self.conf_ref = None + self.retrieve_info() + + def retrieve_info(self): + self.conf_set = {} + self.conf_set_data = {} + self.port_refs = [] + self.execution_contexts = [] + if self.rtc_ref: + self.conf_ref = self.rtc_ref.get_configuration() + conf_set = self.conf_ref.get_configuration_sets() + for cc in conf_set: + self.conf_set[cc.id] = cc + self.conf_set_data[cc.id] = nvlist2dict(cc.configuration_data) + self.profile = self.rtc_ref.get_component_profile() + self.prop = nvlist2dict(self.profile.properties) + #self.execution_contexts = self.rtc_ref.get_contexts() + self.execution_contexts = self.rtc_ref.get_owned_contexts() + self.port_refs = self.rtc_ref.get_ports() + # this includes inports, outports and service ports + self.ports = {} + self.services = {} + self.inports = {} + self.outports = {} + for pp in self.port_refs: + tmp = pp.get_port_profile() + tmp_prop = nvlist2dict(tmp.properties) # self.ports[tmp.name]=Port(tmp, tmp_prop) - if tmp_prop['port.port_type']=='DataInPort' : - self.inports[tmp.name]=RtcInport(tmp,tmp_prop) + if tmp_prop['port.port_type'] == 'DataInPort': + self.inports[tmp.name] = RtcInport(tmp, tmp_prop) # self.inports[tmp.name]=Port(tmp, tmp_prop) - elif tmp_prop['port.port_type']=='DataOutPort' : - self.outports[tmp.name]=RtcOutport(tmp, tmp_prop) + elif tmp_prop['port.port_type'] == 'DataOutPort': + self.outports[tmp.name] = RtcOutport(tmp, tmp_prop) # self.outports[tmp.name]=Port(tmp, tmp_prop) - elif tmp_prop['port.port_type']=='CorbaPort' : - self.services[tmp.name]=RtcService(tmp, tmp_prop) + elif tmp_prop['port.port_type'] == 'CorbaPort': + self.services[tmp.name] = RtcService(tmp, tmp_prop) # self.services[tmp.name]=Port(tmp, tmp_prop) - def set_conf(self,conf_set_name,param_name,value) : - conf_set=self.conf_set[conf_set_name] - conf_set_data=self.conf_set_data[conf_set_name] - conf_set_data[param_name]=value - conf_set.configuration_data=dict2nvlist(conf_set_data) - self.conf_ref.set_configuration_set_values(conf_set_name,conf_set) - def set_conf_activate(self,conf_set_name,param_name,value) : - self.set_conf(conf_set_name,param_name,value) - self.conf_ref.activate_configuration_set(conf_set_name) - def activate(self): - return self.execution_contexts[0].activate_component(self.rtc_ref) - def deactivate(self): - return self.execution_contexts[0].deactivate_component(self.rtc_ref) + def set_conf(self, conf_set_name, param_name, value): + conf_set = self.conf_set[conf_set_name] + conf_set_data = self.conf_set_data[conf_set_name] + conf_set_data[param_name] = value + conf_set.configuration_data = dict2nvlist(conf_set_data) + self.conf_ref.set_configuration_set_values(conf_set_name, conf_set) + + def set_conf_activate(self, conf_set_name, param_name, value): + self.set_conf(conf_set_name, param_name, value) + self.conf_ref.activate_configuration_set(conf_set_name) + + def activate(self): + return self.execution_contexts[0].activate_component(self.rtc_ref) + + def deactivate(self): + return self.execution_contexts[0].deactivate_component(self.rtc_ref) # # pipe # a pipe is an port (interface & implementation) @@ -356,11 +382,14 @@ def deactivate(self): # you can subscribe and communicate to the outside port with the pipe. # you need an rtc implementation to use pipes. # -class Pipe : + + +class Pipe: pass + class PipeOut(Pipe): - def __init__(self, name, data_buf, size=8) : - self.name = name - self.data = data_buf - self.OpenRTM_aist.InPort(name,data_buf,OpenRTM_aist.RingBuffer(size)) + def __init__(self, name, data_buf, size=8): + self.name = name + self.data = data_buf + self.OpenRTM_aist.InPort(name, data_buf, OpenRTM_aist.RingBuffer(size)) diff --git a/OpenRTM_aist/examples/AutoTest/rtc_handle10_11.py b/OpenRTM_aist/examples/AutoTest/rtc_handle10_11.py index 19d1c97c..432516f9 100644 --- a/OpenRTM_aist/examples/AutoTest/rtc_handle10_11.py +++ b/OpenRTM_aist/examples/AutoTest/rtc_handle10_11.py @@ -1,4 +1,4 @@ -#/usr/bin/env python +#!/usr/bin/env python # -*- coding: utf-8 -*- # -*- Python -*- @@ -12,7 +12,7 @@ import RTC -from CorbaNaming import * +from OpenRTM_aist.CorbaNaming import * import SDOPackage # from EmbryonicRtc import * @@ -20,19 +20,21 @@ # rtm environment manager # orb, naming service, rtc proxy list # -class RtmEnv : - def __init__(self, orb_args, nserver_names=["localhost"], - orb=None, naming=None): - if not orb : + +class RtmEnv: + + def __init__(self, orb_args, nserver_names=["localhost"], + orb=None, naming=None): + if not orb: orb = CORBA.ORB_init(orb_args) self.orb = orb self.name_space = {} - if naming : # naming can specify only one naming service - self.name_space['default']=NameSpace(orb, naming=naming) - else : - for ns in nserver_names : - self.name_space[ns]=NameSpace(orb, server_name=ns) + if naming: # naming can specify only one naming service + self.name_space['default'] = NameSpace(orb, naming=naming) + else: + for ns in nserver_names: + self.name_space[ns] = NameSpace(orb, server_name=ns) def __del__(self): self.orb.shutdown(wait_for_completion=CORBA.FALSE) @@ -41,77 +43,80 @@ def __del__(self): # class NameSpace : # rtc_handles and object list in naming service # -class NameSpace : + + +class NameSpace: def __init__(self, orb, server_name=None, naming=None): self.orb = orb self.name = server_name - if naming : - self.naming = naming - else : - self.naming = CorbaNaming(self.orb, server_name) + if naming: + self.naming = naming + else: + self.naming = CorbaNaming(self.orb, server_name) - self.b_len = 10 # iteration cut off no. + self.b_len = 10 # iteration cut off no. self.rtc_handles = {} self.obj_list = {} def get_object_by_name(self, name, cl=RTC.RTObject): ref = self.naming.resolveStr(name) - if ref is None: return None # return CORBA.nil ? - if cl : + if ref is None: + return None # return CORBA.nil ? + if cl: return ref._narrow(cl) - else : + else: return ref - def list_obj(self) : + def list_obj(self): self.rtc_handes = {} self.obj_list = {} return self.list_obj1(self.naming._rootContext, "") - def list_obj1(self, name_context, parent) : - if not name_context : - name_context = self.naming._rootContext + def list_obj1(self, name_context, parent): + if not name_context: + name_context = self.naming._rootContext rslt = [] b_list = name_context.list(self.b_len) - for bd in b_list[0] : + for bd in b_list[0]: rslt = rslt + self.proc_bd(bd, name_context, parent) - if b_list[1] : # iterator : there exists remaining. + if b_list[1]: # iterator : there exists remaining. t_list = b_list[1].next_n(self.b_len) - while t_list[0] : - for bd in t_list[1] : + while t_list[0]: + for bd in t_list[1]: rslt = rslt + self.proc_bd(bd, name_context, parent) t_list = b_list[1].next_n(self.b_len) return rslt - def proc_bd(self, bd, name_context, parent) : -# print('-------------------------------------------------------------------') -# print('bd= ', bd) -# print('name_context= ', name_context) -# print('parent= ', parent) + def proc_bd(self, bd, name_context, parent): + # print('-------------------------------------------------------------------') + # print('bd= ', bd) + # print('name_context= ', name_context) + # print('parent= ', parent) rslt = [] pre = "" - if parent : + if parent: pre = parent + "/" nam = pre + URI.nameToString(bd.binding_name) - if bd.binding_type == CosNaming.nobject : + if bd.binding_type == CosNaming.nobject: tmp = name_context.resolve(bd.binding_name) - self.obj_list[nam]=tmp - print('objcet '+nam+' was listed.') - try : + self.obj_list[nam] = tmp + print('objcet ' + nam + ' was listed.') + try: tmp = tmp._narrow(RTC.RTObject) - except : - print(nam+' is not RTC.') + except BaseException: + print(nam + ' is not RTC.') tmp = None - try : - if tmp : - rslt = [[nam, tmp]] - self.rtc_handles[nam]=RtcHandle(nam,self,tmp) - print('handle for '+nam+' was created.') - else : - pass - except : - print(nam+' is not alive.' , sys.exc_info()[0]) + try: + if tmp: + rslt = [[nam, tmp]] + self.rtc_handles[nam] = RtcHandle(nam, self, tmp) + print('handle for ' + nam + ' was created.') + else: + pass + except BaseException: + print(nam + ' is not alive.', sys.exc_info()[0]) pass - else : + else: tmp = name_context.resolve(bd.binding_name) tmp = tmp._narrow(CosNaming.NamingContext) rslt = self.list_obj1(tmp, nam) @@ -120,136 +125,147 @@ def proc_bd(self, bd, name_context, parent) : # # data conversion # -def nvlist2dict(nvlist) : + + +def nvlist2dict(nvlist): rslt = {} - for tmp in nvlist : - rslt[tmp.name]=tmp.value.value() # nv.value and any.value() + for tmp in nvlist: + rslt[tmp.name] = tmp.value.value() # nv.value and any.value() return rslt -def dict2nvlist(dict) : + + +def dict2nvlist(dict): rslt = [] - for tmp in dict.keys() : + for tmp in dict.keys(): rslt.append(SDOPackage.NameValue(tmp, any.to_any(dict[tmp]))) return rslt # # connector, port, inport, outport, service -# - -class Connector : - def __init__(self, plist, name = None, id="", prop_dict={}) : - self.connectp=False - self.plist = plist - self.port_reflist = [tmp.port_profile.port_ref for tmp in plist] - if name : - self.name = name - else : - self.name = string.join([tmp.name for tmp in plist],'_') - self.prop_dict_req = prop_dict - self.prop_nvlist_req = dict2nvlist(self.prop_dict_req) - self.profile_req = RTC.ConnectorProfile(self.name, id, self.port_reflist, - self.prop_nvlist_req) - self.nego_prop() - - def nego_prop(self) : - self.possible = True - for kk in self.def_prop : - if kk in self.prop_dict_req : - if not self.prop_dict_req[kk] : - self.prop_dict_req[kk]=self.def_prop[kk] - else : - self.prop_dict_req[kk]=self.def_prop[kk] - for pp in self.plist : - if not ((self.prop_dict_req[kk] in pp.prop[kk]) or - ('Any' in pp.prop[kk])) : - print(kk, self.prop_dict_req[kk]) - self.prop_dict_req[kk] = "" - self.possible = False - self.prop_nvlist_req = dict2nvlist(self.prop_dict_req) - self.profile_req.properties = self.prop_nvlist_req - return self.possible - - def connect(self) : -# -# out and inout parameters are retuned as a tuple # - if self.connectp == False : - ret, self.profile = self.port_reflist[0].connect(self.profile_req) - self.prop_nvlist = self.profile.properties - self.prop_dict = nvlist2dict(self.prop_nvlist) - if ret == RTC.RTC_OK : - self.connectp=True - else : - ret = "?" - return ret - - def disconnect(self) : - if self.connectp == True : - ret = self.port_reflist[0].disconnect(self.profile.connector_id) - else : - ret = "?" - self.connectp = False - return ret - -class IOConnector(Connector) : - def __init__(self, plist, name = None, id="", prop_dict={}) : -# self.def_prop = {'dataport.dataflow_type':'Push' , -# 'dataport.interface_type':'CORBA_Any' , -# 'dataport.subscription_type':'Flush'} - self.def_prop = {'dataport.dataflow_type':'push', - 'dataport.interface_type':'corba_cdr' , - 'dataport.subscription_type':'flush'} - Connector.__init__(self, plist, name, id, prop_dict) - -class ServiceConnector(Connector) : - def __init__(self, plist, name = None, id="", prop_dict={}) : - self.def_prop = {'port.port_type':'CorbaPort' } - Connector.__init__(self, plist, name, id, prop_dict) - - -class Port : - def __init__(self, profile,nv_dict=None,handle=None) : - self.handle=handle - self.name=profile.name + + +class Connector: + def __init__(self, plist, name=None, id="", prop_dict={}): + self.connectp = False + self.plist = plist + self.port_reflist = [tmp.port_profile.port_ref for tmp in plist] + if name: + self.name = name + else: + self.name = string.join([tmp.name for tmp in plist], '_') + self.prop_dict_req = prop_dict + self.prop_nvlist_req = dict2nvlist(self.prop_dict_req) + self.profile_req = RTC.ConnectorProfile(self.name, id, self.port_reflist, + self.prop_nvlist_req) + self.nego_prop() + + def nego_prop(self): + self.possible = True + for kk in self.def_prop: + if kk in self.prop_dict_req: + if not self.prop_dict_req[kk]: + self.prop_dict_req[kk] = self.def_prop[kk] + else: + self.prop_dict_req[kk] = self.def_prop[kk] + for pp in self.plist: + if not ((self.prop_dict_req[kk] in pp.prop[kk]) or + ('Any' in pp.prop[kk])): + print(kk, self.prop_dict_req[kk]) + self.prop_dict_req[kk] = "" + self.possible = False + self.prop_nvlist_req = dict2nvlist(self.prop_dict_req) + self.profile_req.properties = self.prop_nvlist_req + return self.possible + + def connect(self): + # + # out and inout parameters are retuned as a tuple + # + if self.connectp == False: + ret, self.profile = self.port_reflist[0].connect(self.profile_req) + self.prop_nvlist = self.profile.properties + self.prop_dict = nvlist2dict(self.prop_nvlist) + if ret == RTC.RTC_OK: + self.connectp = True + else: + ret = "?" + return ret + + def disconnect(self): + if self.connectp == True: + ret = self.port_reflist[0].disconnect(self.profile.connector_id) + else: + ret = "?" + self.connectp = False + return ret + + +class IOConnector(Connector): + def __init__(self, plist, name=None, id="", prop_dict={}): + # self.def_prop = {'dataport.dataflow_type':'Push' , + # 'dataport.interface_type':'CORBA_Any' , + # 'dataport.subscription_type':'Flush'} + self.def_prop = {'dataport.dataflow_type': 'push', + 'dataport.interface_type': 'corba_cdr', + 'dataport.subscription_type': 'flush'} + Connector.__init__(self, plist, name, id, prop_dict) + + +class ServiceConnector(Connector): + def __init__(self, plist, name=None, id="", prop_dict={}): + self.def_prop = {'port.port_type': 'CorbaPort'} + Connector.__init__(self, plist, name, id, prop_dict) + + +class Port: + def __init__(self, profile, nv_dict=None, handle=None): + self.handle = handle + self.name = profile.name self.port_profile = profile - if not nv_dict : + if not nv_dict: nv_dict = nvlist2dict(profile.properties) self.prop = nv_dict self.con = None # this must be set in each subclasses - def get_info(self) : + + def get_info(self): self.con.connect() tmp1 = self.get_connections() tmp2 = [pp.connector_id for pp in tmp1] - if self.con.profile.connector_id in tmp2 : + if self.con.profile.connector_id in tmp2: print("connecting") self.con.disconnect() - def get_connections(self) : + def get_connections(self): return self.port_profile.port_ref.get_connector_profiles() -class CorbaServer : - def __init__(self, profile, port) : + +class CorbaServer: + def __init__(self, profile, port): self.profile = profile self.port = port self.name = profile.instance_name self.type = profile.type_name self.ref = None ref_key = 'port.' + self.type + '.' + self.name - self.ref=self.port.con.prop_dict[ref_key] - if isinstance(self.ref,str) : - self.ref=port.handle.env.orb.string_to_object(self.ref) + self.ref = self.port.con.prop_dict[ref_key] + if isinstance(self.ref, str): + self.ref = port.handle.env.orb.string_to_object(self.ref) # # if we import stubs before we create instances, # we rarely need to narrow the object references. # we need to specify global symbol table to evaluate class symbols. # - def narrow_ref(self, gls) : - if self.type.find('::') == -1 : + + def narrow_ref(self, gls): + if self.type.find('::') == -1: self.narrow_sym = eval('_GlobalIDL.' + self.type, gls) - else : - self.narrow_sym = eval(self.type.replace('::','.'), gls) + else: + self.narrow_sym = eval(self.type.replace('::', '.'), gls) self.ref = self.ref._narrow(self.narrow_sym) -class CorbaClient : - def __init__(self, profile) : + +class CorbaClient: + def __init__(self, profile): self.profile = profile self.name = profile.instance_name self.type = profile.type_name @@ -259,18 +275,19 @@ def __init__(self, profile) : # but .... # -class RtcService(Port) : - def __init__(self, profile,nv_dict=None, handle=None) : + +class RtcService(Port): + def __init__(self, profile, nv_dict=None, handle=None): Port.__init__(self, profile, nv_dict, handle) self.con = ServiceConnector([self]) self.get_info() - self.provided={} - self.required={} + self.provided = {} + self.required = {} tmp = self.port_profile.interfaces - for itf in tmp : - if itf.polarity == RTC.PROVIDED : - self.provided[itf.instance_name] = CorbaServer(itf,self) - elif itf.polarity == RTC.REQUIRED : + for itf in tmp: + if itf.polarity == RTC.PROVIDED: + self.provided[itf.instance_name] = CorbaServer(itf, self) + elif itf.polarity == RTC.REQUIRED: self.required[itf.instance_name] = CorbaClient(itf) # def open(self) : @@ -286,150 +303,165 @@ def __init__(self, profile,nv_dict=None, handle=None) : # def close(self) : # return self.con.disconnect() -def strip_data_class(data_class_str) : + + +def strip_data_class(data_class_str): tmp = data_class_str.split(':') - if len(tmp) == 1 : + if len(tmp) == 1: return data_class_str - else : + else: tmp = tmp[1].split('/') return tmp[1] -class RtcInport(Port) : - def __init__(self, profile, nv_dict=None, handle=None) : + +class RtcInport(Port): + def __init__(self, profile, nv_dict=None, handle=None): Port.__init__(self, profile, nv_dict, handle) - self.con = IOConnector([self], prop_dict={'dataport.dataflow_type':'push'}) - self.get_info() + self.con = IOConnector( + [self], prop_dict={ + 'dataport.dataflow_type': 'push'}) + self.get_info() # self.ref = self.con.prop_dict['dataport.corba_any.inport_ref'] self.ref = self.con.prop_dict['dataport.corba_cdr.inport_ref'] # self.data_class = eval('RTC.' + self.prop['dataport.data_type']) # self.data_tc = eval('RTC._tc_' + self.prop['dataport.data_type']) - tmp=strip_data_class(self.prop['dataport.data_type']) + tmp = strip_data_class(self.prop['dataport.data_type']) print(tmp) self.data_class = eval('RTC.' + tmp) self.data_tc = eval('RTC._tc_' + tmp) - def write(self,data) : -# self.ref.put(CORBA.Any(self.data_tc, -# self.data_class(RTC.Time(0,0),data))) + + def write(self, data): + # self.ref.put(CORBA.Any(self.data_tc, + # self.data_class(RTC.Time(0,0),data))) self.ref.put(cdrMarshal(self.data_tc, - self.data_class(RTC.Time(0,0),data), 1)) - def open(self) : + self.data_class(RTC.Time(0, 0), data), 1)) + + def open(self): self.con.connect() self.ref = self.con.prop_dict['dataport.corba_cdr.inport_ref'] - def close(self) : + def close(self): return self.con.disconnect() -class RtcOutport(Port) : - def __init__(self, profile,nv_dict=None, handle=None) : + +class RtcOutport(Port): + def __init__(self, profile, nv_dict=None, handle=None): Port.__init__(self, profile, nv_dict, handle) - con_prop_dict={'dataport.dataflow_type':'pull', - 'dataport.buffer.type':'ringbuffer', - 'dataport.buffer.read.empty_policy':'last', - 'dataport.buffer.length':'1'} + con_prop_dict = {'dataport.dataflow_type': 'pull', + 'dataport.buffer.type': 'ringbuffer', + 'dataport.buffer.read.empty_policy': 'last', + 'dataport.buffer.length': '1'} self.con = IOConnector([self], prop_dict=con_prop_dict) self.get_info() # if 'dataport.corba_any.outport_ref' in self.con.prop_dict : # self.ref = self.con.prop_dict['dataport.corba_any.outport_ref'] - if 'dataport.corba_cdr.outport_ref' in self.con.prop_dict : - self.ref = self.con.prop_dict['dataport.corba_cdr.outport_ref'] - else : - self.ref=None + if 'dataport.corba_cdr.outport_ref' in self.con.prop_dict: + self.ref = self.con.prop_dict['dataport.corba_cdr.outport_ref'] + else: + self.ref = None # self.data_class = eval('RTC.' + self.prop['dataport.data_type']) # self.data_tc = eval('RTC._tc_' + self.prop['dataport.data_type']) - tmp=strip_data_class(self.prop['dataport.data_type']) + tmp = strip_data_class(self.prop['dataport.data_type']) self.data_class = eval('RTC.' + tmp) self.data_tc = eval('RTC._tc_' + tmp) - def read(self) : - if self.ref : - try : - tmp1=self.ref.get() - tmp2= cdrUnmarshal(self.data_tc,tmp1[1], 1) -# return tmp2.data - return tmp2 - except : + def read(self): + if self.ref: + try: + tmp1 = self.ref.get() + tmp2 = cdrUnmarshal(self.data_tc, tmp1[1], 1) +# return tmp2.data + return tmp2 + except BaseException: return None - else : - print("not supported") - return None + else: + print("not supported") + return None - def open(self) : + def open(self): self.con.connect() - if 'dataport.corba_cdr.outport_ref' in self.con.prop_dict : - self.ref = self.con.prop_dict['dataport.corba_cdr.outport_ref'] + if 'dataport.corba_cdr.outport_ref' in self.con.prop_dict: + self.ref = self.con.prop_dict['dataport.corba_cdr.outport_ref'] - def close(self) : + def close(self): return self.con.disconnect() # # RtcHandle # -class RtcHandle : - def __init__(self, name, env, ref=None) : - self.name = name - self.env = env - if ref : - self.rtc_ref = ref - else : - self.rtc_ref = env.naming.resolve(name)._narrow(RTC.RTObject) - self.conf_ref = None - self.retrieve_info() - - def retrieve_info(self) : - self.conf_set={} - self.conf_set_data={} - self.port_refs = [] - self.execution_contexts =[] - if self.rtc_ref : - self.conf_ref = self.rtc_ref.get_configuration() - conf_set = self.conf_ref.get_configuration_sets() - for cc in conf_set : - self.conf_set[cc.id]=cc - self.conf_set_data[cc.id]=nvlist2dict(cc.configuration_data) - self.profile = self.rtc_ref.get_component_profile() - self.prop = nvlist2dict(self.profile.properties) - #self.execution_contexts = self.rtc_ref.get_contexts() - self.execution_contexts = self.rtc_ref.get_owned_contexts() - self.port_refs = self.rtc_ref.get_ports() - # this includes inports, outports and service ports - self.ports = {} - self.services = {} - self.inports = {} - self.outports = {} - for pp in self.port_refs : - tmp = pp.get_port_profile() - tmp_prop = nvlist2dict(tmp.properties) - tmp_name = tmp.name.lstrip(self.name.split('.')[0]).lstrip('.') - print('port_name:', tmp_name) + + +class RtcHandle: + def __init__(self, name, env, ref=None): + self.name = name + self.env = env + if ref: + self.rtc_ref = ref + else: + self.rtc_ref = env.naming.resolve(name)._narrow(RTC.RTObject) + self.conf_ref = None + self.retrieve_info() + + def retrieve_info(self): + self.conf_set = {} + self.conf_set_data = {} + self.port_refs = [] + self.execution_contexts = [] + if self.rtc_ref: + self.conf_ref = self.rtc_ref.get_configuration() + conf_set = self.conf_ref.get_configuration_sets() + for cc in conf_set: + self.conf_set[cc.id] = cc + self.conf_set_data[cc.id] = nvlist2dict(cc.configuration_data) + self.profile = self.rtc_ref.get_component_profile() + self.prop = nvlist2dict(self.profile.properties) + #self.execution_contexts = self.rtc_ref.get_contexts() + self.execution_contexts = self.rtc_ref.get_owned_contexts() + self.port_refs = self.rtc_ref.get_ports() + # this includes inports, outports and service ports + self.ports = {} + self.services = {} + self.inports = {} + self.outports = {} + for pp in self.port_refs: + tmp = pp.get_port_profile() + tmp_prop = nvlist2dict(tmp.properties) + tmp_name = tmp.name.lstrip(self.name.split('.')[0]).lstrip('.') + print('port_name:', tmp_name) # self.ports[tmp.name]=Port(tmp, tmp_prop) - if tmp_prop['port.port_type']=='DataInPort' : - self.inports[tmp_name]=RtcInport(tmp,tmp_prop, self) + if tmp_prop['port.port_type'] == 'DataInPort': + self.inports[tmp_name] = RtcInport(tmp, tmp_prop, self) # self.inports[tmp.name]=Port(tmp, tmp_prop) - elif tmp_prop['port.port_type']=='DataOutPort' : - self.outports[tmp_name]=RtcOutport(tmp, tmp_prop, self) + elif tmp_prop['port.port_type'] == 'DataOutPort': + self.outports[tmp_name] = RtcOutport(tmp, tmp_prop, self) # self.outports[tmp.name]=Port(tmp, tmp_prop) - elif tmp_prop['port.port_type']=='CorbaPort' : - self.services[tmp_name]=RtcService(tmp, tmp_prop, self) + elif tmp_prop['port.port_type'] == 'CorbaPort': + self.services[tmp_name] = RtcService(tmp, tmp_prop, self) # self.services[tmp.name]=Port(tmp, tmp_prop) - def set_conf(self,conf_set_name,param_name,value) : - conf_set=self.conf_set[conf_set_name] - conf_set_data=self.conf_set_data[conf_set_name] - conf_set_data[param_name]=value - conf_set.configuration_data=dict2nvlist(conf_set_data) + def set_conf(self, conf_set_name, param_name, value): + conf_set = self.conf_set[conf_set_name] + conf_set_data = self.conf_set_data[conf_set_name] + conf_set_data[param_name] = value + conf_set.configuration_data = dict2nvlist(conf_set_data) # self.conf_ref.set_configuration_set_values(conf_set_name,conf_set) - self.conf_ref.set_configuration_set_values(conf_set) - def set_conf_activate(self,conf_set_name,param_name,value) : - self.set_conf(conf_set_name,param_name,value) - self.conf_ref.activate_configuration_set(conf_set_name) - def activate(self): - return self.execution_contexts[0].activate_component(self.rtc_ref) - def deactivate(self): - return self.execution_contexts[0].deactivate_component(self.rtc_ref) - def reset(self): - return self.execution_contexts[0].reset_component(self.rtc_ref) - def get_state(self): - return self.execution_contexts[0].get_component_state(self.rtc_ref) + self.conf_ref.set_configuration_set_values(conf_set) + + def set_conf_activate(self, conf_set_name, param_name, value): + self.set_conf(conf_set_name, param_name, value) + self.conf_ref.activate_configuration_set(conf_set_name) + + def activate(self): + return self.execution_contexts[0].activate_component(self.rtc_ref) + + def deactivate(self): + return self.execution_contexts[0].deactivate_component(self.rtc_ref) + + def reset(self): + return self.execution_contexts[0].reset_component(self.rtc_ref) + + def get_state(self): + return self.execution_contexts[0].get_component_state(self.rtc_ref) # # pipe @@ -437,48 +469,62 @@ def get_state(self): # for a port(an RtcInport or RtcOutport object) of an outside rtc. # you need an empty rtc (comp) to create pipes. # you can subscribe and communicate to the outside port with the pipe. -# # -class InPipe() : - def __init__(self,comp, port) : - self.comp=comp - self.port=port - self.pname=port.name.replace('.','_') - self.pipe=comp.makeOutPort(self.pname,port.data_class(RTC.Time(0,0),[]),OpenRTM_aist.RingBuffer(1)) - self.buf=getattr(comp,'_d_'+self.pname) - tmp = self.pipe.getPortProfile() - self.pipe_port = RtcOutport(tmp, nvlist2dict(tmp.properties)) - self.con = IOConnector([self.pipe_port,self.port]) - def connect(self): - return self.con.connect() - def disconnect(self): - return self.con.disconnect() - def write(self, data) : - self.buf.data=data - self.pipe.write() -class OutPipe() : - def __init__(self,comp, port) : - self.comp=comp - self.port=port - self.pname=port.name.replace('.','_') - self.pipe=comp.makeInPort(self.pname,port.data_class(RTC.Time(0,0),[]),OpenRTM_aist.RingBuffer(1)) - self.buf=getattr(comp,'_d_'+self.pname) - tmp = self.pipe.getPortProfile() - self.pipe_port = RtcInport(tmp, nvlist2dict(tmp.properties)) - self.con = IOConnector([self.pipe_port,self.port]) - def connect(self): - return self.con.connect() - def disconnect(self): - return self.con.disconnect() - def read(self) : - return self.pipe.read().data +# + + +class InPipe(): + def __init__(self, comp, port): + self.comp = comp + self.port = port + self.pname = port.name.replace('.', '_') + self.pipe = comp.makeOutPort(self.pname, port.data_class( + RTC.Time(0, 0), []), OpenRTM_aist.RingBuffer(1)) + self.buf = getattr(comp, '_d_' + self.pname) + tmp = self.pipe.getPortProfile() + self.pipe_port = RtcOutport(tmp, nvlist2dict(tmp.properties)) + self.con = IOConnector([self.pipe_port, self.port]) + + def connect(self): + return self.con.connect() + + def disconnect(self): + return self.con.disconnect() + + def write(self, data): + self.buf.data = data + self.pipe.write() + + +class OutPipe(): + def __init__(self, comp, port): + self.comp = comp + self.port = port + self.pname = port.name.replace('.', '_') + self.pipe = comp.makeInPort(self.pname, port.data_class( + RTC.Time(0, 0), []), OpenRTM_aist.RingBuffer(1)) + self.buf = getattr(comp, '_d_' + self.pname) + tmp = self.pipe.getPortProfile() + self.pipe_port = RtcInport(tmp, nvlist2dict(tmp.properties)) + self.con = IOConnector([self.pipe_port, self.port]) + + def connect(self): + return self.con.connect() + + def disconnect(self): + return self.con.disconnect() + + def read(self): + return self.pipe.read().data # # # -def make_pipe(comp, handle) : - handle.in_pipe={} - for i_port in handle.inports : - handle.in_pipe[i_port]=InPipe(comp, handle.inports[i_port]) - handle.out_pipe={} - for o_port in handle.outports : - handle.out_pipe[o_port]=OutPipe(comp, handle.outports[o_port]) + + +def make_pipe(comp, handle): + handle.in_pipe = {} + for i_port in handle.inports: + handle.in_pipe[i_port] = InPipe(comp, handle.inports[i_port]) + handle.out_pipe = {} + for o_port in handle.outports: + handle.out_pipe[o_port] = OutPipe(comp, handle.outports[o_port]) diff --git a/OpenRTM_aist/examples/CSPSample/DataIn2.py b/OpenRTM_aist/examples/CSPSample/DataIn2.py new file mode 100644 index 00000000..12afc3a4 --- /dev/null +++ b/OpenRTM_aist/examples/CSPSample/DataIn2.py @@ -0,0 +1,80 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +# -*- Python -*- + + +from __future__ import print_function +import sys +import time + +import RTC +import OpenRTM_aist + +datain2_spec = ["implementation_id", "DataIn2", + "type_name", "DataIn2", + "description", "Console output component", + "version", "1.0", + "vendor", "Shinji Kurihara", + "category", "example", + "activity_type", "DataFlowComponent", + "max_instance", "10", + "language", "Python", + "lang_type", "script", + ""] + + +class DataIn2(OpenRTM_aist.DataFlowComponentBase): + def __init__(self, manager): + OpenRTM_aist.DataFlowComponentBase.__init__(self, manager) + return + + def onInitialize(self): + self._data = RTC.TimedLong(RTC.Time(0, 0), 0) + self._inport = OpenRTM_aist.CSPInPort("in", self._data) + # Set InPort buffer + self.addInPort("in", self._inport) + + return RTC.RTC_OK + + def onExecute(self, ec_id): + data = self._inport.read() + self._rtcout.RTC_ERROR("dataread: %s", str(data)) + + return RTC.RTC_OK + + +def DataIn2Init(manager): + profile = OpenRTM_aist.Properties(defaults_str=datain2_spec) + manager.registerFactory(profile, + DataIn2, + OpenRTM_aist.Delete) + + +def MyModuleInit(manager): + DataIn2Init(manager) + + # Create a component + comp = manager.createComponent("DataIn2") + + +def main(): + # Initialize manager + mgr = OpenRTM_aist.Manager.init(sys.argv) + + # Set module initialization proceduer + # This procedure will be invoked in activateManager() function. + mgr.setModuleInitProc(MyModuleInit) + + # Activate manager and register to naming service + mgr.activateManager() + + # run the manager in blocking mode + # runManager(False) is the default + mgr.runManager() + + # If you want to run the manager in non-blocking mode, do like this + # mgr.runManager(True) + + +if __name__ == "__main__": + main() diff --git a/OpenRTM_aist/examples/CSPSample/DataOut2.py b/OpenRTM_aist/examples/CSPSample/DataOut2.py new file mode 100644 index 00000000..619cf788 --- /dev/null +++ b/OpenRTM_aist/examples/CSPSample/DataOut2.py @@ -0,0 +1,79 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +# -*- Python -*- + +from __future__ import print_function +import sys + +import RTC +import OpenRTM_aist + +dataout2_spec = ["implementation_id", "DataOut2", + "type_name", "DataOut2", + "description", "Data output component", + "version", "1.0", + "vendor", "Nobuhiko Miyamoto", + "category", "example", + "activity_type", "DataFlowComponent", + "max_instance", "10", + "language", "Python", + "lang_type", "script", + ""] + + +class DataOut2(OpenRTM_aist.DataFlowComponentBase): + def __init__(self, manager): + OpenRTM_aist.DataFlowComponentBase.__init__(self, manager) + return + + def onInitialize(self): + self._data = RTC.TimedLong(RTC.Time(0, 0), 0) + self._outport = OpenRTM_aist.CSPOutPort("out", self._data) + # Set OutPort buffer + self.addOutPort("out", self._outport) + + return RTC.RTC_OK + + def onExecute(self, ec_id): + self._data.data = 1 + self._outport.write() + self._rtcout.RTC_ERROR("writedata") + + return RTC.RTC_OK + + +def DataOut2Init(manager): + profile = OpenRTM_aist.Properties(defaults_str=dataout2_spec) + manager.registerFactory(profile, + DataOut2, + OpenRTM_aist.Delete) + + +def MyModuleInit(manager): + DataOut2Init(manager) + + # Create a component + comp = manager.createComponent("DataOut2") + + +def main(): + # Initialize manager + mgr = OpenRTM_aist.Manager.init(sys.argv) + + # Set module initialization proceduer + # This procedure will be invoked in activateManager() function. + mgr.setModuleInitProc(MyModuleInit) + + # Activate manager and register to naming service + mgr.activateManager() + + # run the manager in blocking mode + # runManager(False) is the default + mgr.runManager() + + # If you want to run the manager in non-blocking mode, do like this + # mgr.runManager(True) + + +if __name__ == "__main__": + main() diff --git a/OpenRTM_aist/examples/CSPSample/rtc_samplecsp.conf b/OpenRTM_aist/examples/CSPSample/rtc_samplecsp.conf new file mode 100644 index 00000000..e8ce6f6e --- /dev/null +++ b/OpenRTM_aist/examples/CSPSample/rtc_samplecsp.conf @@ -0,0 +1,16 @@ +corba.nameservers: localhost +naming.formats: %n.rtc +logger.enable: YES +logger.log_level: ERROR +logger.file_name: stdout +corba.args: +manager.components.precreate: DataIn2 +manager.components.preconnect: DataOut20.out?port=DataIn20.in&dataflow_type=duplex&interface_type=csp_channel +manager.components.preactivation: DataOut20, DataIn20 + +port.inport.in.buffer.length: 0 +#port.inport.in.csp.sync_wait: YES +#port.outport.out.csp.sync_wait: YES + +example.DataOut20.exec_cxt.periodic.rate: 1000 +example.DataIn20.exec_cxt.periodic.rate: 1 \ No newline at end of file diff --git a/OpenRTM_aist/examples/CSPSample/samplecsp.bat b/OpenRTM_aist/examples/CSPSample/samplecsp.bat new file mode 100644 index 00000000..14b5e5bf --- /dev/null +++ b/OpenRTM_aist/examples/CSPSample/samplecsp.bat @@ -0,0 +1,2 @@ +python DataOut2.py -f rtc_samplecsp.conf +pause \ No newline at end of file diff --git a/OpenRTM_aist/examples/CSPSelectSample/DataIn.py b/OpenRTM_aist/examples/CSPSelectSample/DataIn.py new file mode 100644 index 00000000..8c19a8c1 --- /dev/null +++ b/OpenRTM_aist/examples/CSPSelectSample/DataIn.py @@ -0,0 +1,84 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +# -*- Python -*- + + +from __future__ import print_function +import sys +import time + +import RTC +import OpenRTM_aist + +datain_spec = ["implementation_id", "DataIn", + "type_name", "DataIn", + "description", "Console output component", + "version", "1.0", + "vendor", "Shinji Kurihara", + "category", "example", + "activity_type", "DataFlowComponent", + "max_instance", "10", + "language", "Python", + "lang_type", "script", + ""] + + +class DataIn(OpenRTM_aist.DataFlowComponentBase): + def __init__(self, manager): + OpenRTM_aist.DataFlowComponentBase.__init__(self, manager) + return + + def onInitialize(self): + self._data = RTC.TimedLong(RTC.Time(0, 0), 0) + self._cspmanager = OpenRTM_aist.CSPManager() + self._inport = OpenRTM_aist.CSPInPort( + "in", self._data, self._cspmanager) + # Set InPort buffer + self.addInPort("in", self._inport) + + return RTC.RTC_OK + + def onExecute(self, ec_id): + ret, outport, inport = self._cspmanager.select(100) + if ret: + if inport: + inport.readData() + #self._rtcout.RTC_ERROR("dataread: %s", (str(inport.readData()))) + return RTC.RTC_OK + + +def DataInInit(manager): + profile = OpenRTM_aist.Properties(defaults_str=datain_spec) + manager.registerFactory(profile, + DataIn, + OpenRTM_aist.Delete) + + +def MyModuleInit(manager): + DataInInit(manager) + + # Create a component + comp = manager.createComponent("DataIn") + + +def main(): + # Initialize manager + mgr = OpenRTM_aist.Manager.init(sys.argv) + + # Set module initialization proceduer + # This procedure will be invoked in activateManager() function. + mgr.setModuleInitProc(MyModuleInit) + + # Activate manager and register to naming service + mgr.activateManager() + + # run the manager in blocking mode + # runManager(False) is the default + mgr.runManager() + + # If you want to run the manager in non-blocking mode, do like this + # mgr.runManager(True) + + +if __name__ == "__main__": + main() diff --git a/OpenRTM_aist/examples/CSPSelectSample/DataInOut.py b/OpenRTM_aist/examples/CSPSelectSample/DataInOut.py new file mode 100644 index 00000000..ce372b76 --- /dev/null +++ b/OpenRTM_aist/examples/CSPSelectSample/DataInOut.py @@ -0,0 +1,112 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +# -*- Python -*- + + +from __future__ import print_function +import sys +import time + +import RTC +import OpenRTM_aist + +datainout_spec = ["implementation_id", "DataInOut", + "type_name", "DataInOut", + "description", "Console output component", + "version", "1.0", + "vendor", "Shinji Kurihara", + "category", "example", + "activity_type", "DataFlowComponent", + "max_instance", "10", + "language", "Python", + "lang_type", "script", + ""] + + +class DataInOut(OpenRTM_aist.DataFlowComponentBase): + def __init__(self, manager): + OpenRTM_aist.DataFlowComponentBase.__init__(self, manager) + return + + def onInitialize(self): + self._indata1 = RTC.TimedLong(RTC.Time(0, 0), 0) + self._indata2 = RTC.TimedLong(RTC.Time(0, 0), 0) + self._indata3 = RTC.TimedLong(RTC.Time(0, 0), 0) + self._outdata1 = RTC.TimedLong(RTC.Time(0, 0), 0) + self._outdata2 = RTC.TimedLong(RTC.Time(0, 0), 0) + self._outdata3 = RTC.TimedLong(RTC.Time(0, 0), 0) + self._cspmanager = OpenRTM_aist.CSPManager() + self._inport1 = OpenRTM_aist.CSPInPort( + "in1", self._indata1, self._cspmanager) + self._inport2 = OpenRTM_aist.CSPInPort( + "in2", self._indata2, self._cspmanager) + self._inport3 = OpenRTM_aist.CSPInPort( + "in3", self._indata3, self._cspmanager) + self._outport1 = OpenRTM_aist.CSPOutPort( + "out1", self._outdata1, self._cspmanager) + self._outport2 = OpenRTM_aist.CSPOutPort( + "out2", self._outdata2, self._cspmanager) + self._outport3 = OpenRTM_aist.CSPOutPort( + "out3", self._outdata3, self._cspmanager) + # Set InPort buffer + self.addInPort("in1", self._inport1) + self.addInPort("in2", self._inport2) + self.addInPort("in3", self._inport3) + self.addOutPort("out1", self._outport1) + self.addOutPort("out2", self._outport2) + self.addOutPort("out3", self._outport3) + + return RTC.RTC_OK + + def onExecute(self, ec_id): + self._outdata1.data = 1 + self._outdata2.data = 1 + self._outdata3.data = 1 + ret, outport, inport = self._cspmanager.select(100) + if ret: + if inport: + inport.readData() + self._rtcout.RTC_ERROR("dataread: %s", (inport.name())) + #self._rtcout.RTC_ERROR("dataread: %s %s", (inport.name(), str(inport.readData()))) + elif outport: + self._rtcout.RTC_ERROR("datawrite: %s", outport.name()) + outport.writeData() + + return RTC.RTC_OK + + +def DataInOutInit(manager): + profile = OpenRTM_aist.Properties(defaults_str=datainout_spec) + manager.registerFactory(profile, + DataInOut, + OpenRTM_aist.Delete) + + +def MyModuleInit(manager): + DataInOutInit(manager) + + # Create a component + comp = manager.createComponent("DataInOut") + + +def main(): + # Initialize manager + mgr = OpenRTM_aist.Manager.init(sys.argv) + + # Set module initialization proceduer + # This procedure will be invoked in activateManager() function. + mgr.setModuleInitProc(MyModuleInit) + + # Activate manager and register to naming service + mgr.activateManager() + + # run the manager in blocking mode + # runManager(False) is the default + mgr.runManager() + + # If you want to run the manager in non-blocking mode, do like this + # mgr.runManager(True) + + +if __name__ == "__main__": + main() diff --git a/OpenRTM_aist/examples/CSPSelectSample/DataIn_port3.py b/OpenRTM_aist/examples/CSPSelectSample/DataIn_port3.py new file mode 100644 index 00000000..24c0e7e6 --- /dev/null +++ b/OpenRTM_aist/examples/CSPSelectSample/DataIn_port3.py @@ -0,0 +1,94 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +# -*- Python -*- + + +from __future__ import print_function +import sys +import time + +import RTC +import OpenRTM_aist + +datain_port3_spec = ["implementation_id", "DataIn_port3", + "type_name", "DataIn_port3", + "description", "Console output component", + "version", "1.0", + "vendor", "Shinji Kurihara", + "category", "example", + "activity_type", "DataFlowComponent", + "max_instance", "10", + "language", "Python", + "lang_type", "script", + ""] + + +class DataIn_port3(OpenRTM_aist.DataFlowComponentBase): + def __init__(self, manager): + OpenRTM_aist.DataFlowComponentBase.__init__(self, manager) + return + + def onInitialize(self): + self._data1 = RTC.TimedLong(RTC.Time(0, 0), 0) + self._data2 = RTC.TimedLong(RTC.Time(0, 0), 0) + self._data3 = RTC.TimedLong(RTC.Time(0, 0), 0) + self._cspmanager = OpenRTM_aist.CSPManager() + self._inport1 = OpenRTM_aist.CSPInPort( + "in1", self._data1, self._cspmanager) + self._inport2 = OpenRTM_aist.CSPInPort( + "in2", self._data2, self._cspmanager) + self._inport3 = OpenRTM_aist.CSPInPort( + "in3", self._data3, self._cspmanager) + # Set InPort buffer + self.addInPort("in1", self._inport1) + self.addInPort("in2", self._inport2) + self.addInPort("in3", self._inport3) + + return RTC.RTC_OK + + def onExecute(self, ec_id): + ret, outport, inport = self._cspmanager.select(100) + if ret: + if inport: + inport.readData() + self._rtcout.RTC_ERROR("dataread: %s", (inport.name())) + #self._rtcout.RTC_ERROR("dataread: %s %s", (inport.name(), str(inport.readData()))) + + return RTC.RTC_OK + + +def DataIn_port3Init(manager): + profile = OpenRTM_aist.Properties(defaults_str=datain_port3_spec) + manager.registerFactory(profile, + DataIn_port3, + OpenRTM_aist.Delete) + + +def MyModuleInit(manager): + DataIn_port3Init(manager) + + # Create a component + comp = manager.createComponent("DataIn_port3") + + +def main(): + # Initialize manager + mgr = OpenRTM_aist.Manager.init(sys.argv) + + # Set module initialization proceduer + # This procedure will be invoked in activateManager() function. + mgr.setModuleInitProc(MyModuleInit) + + # Activate manager and register to naming service + mgr.activateManager() + + # run the manager in blocking mode + # runManager(False) is the default + mgr.runManager() + + # If you want to run the manager in non-blocking mode, do like this + # mgr.runManager(True) + + +if __name__ == "__main__": + main() diff --git a/OpenRTM_aist/examples/CSPSelectSample/DataOut.py b/OpenRTM_aist/examples/CSPSelectSample/DataOut.py new file mode 100644 index 00000000..8b304fb3 --- /dev/null +++ b/OpenRTM_aist/examples/CSPSelectSample/DataOut.py @@ -0,0 +1,84 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +# -*- Python -*- + +from __future__ import print_function +import sys + +import RTC +import OpenRTM_aist + +dataout_spec = ["implementation_id", "DataOut", + "type_name", "DataOut", + "description", "Data output component", + "version", "1.0", + "vendor", "Nobuhiko Miyamoto", + "category", "example", + "activity_type", "DataFlowComponent", + "max_instance", "10", + "language", "Python", + "lang_type", "script", + ""] + + +class DataOut(OpenRTM_aist.DataFlowComponentBase): + def __init__(self, manager): + OpenRTM_aist.DataFlowComponentBase.__init__(self, manager) + return + + def onInitialize(self): + self._data = RTC.TimedLong(RTC.Time(0, 0), 0) + self._cspmanager = OpenRTM_aist.CSPManager() + self._outport = OpenRTM_aist.CSPOutPort( + "out", self._data, self._cspmanager) + # Set OutPort buffer + self.addOutPort("out", self._outport) + + return RTC.RTC_OK + + def onExecute(self, ec_id): + self._data.data = 1 + OpenRTM_aist.setTimestamp(self._data) + ret, outport, inport = self._cspmanager.select(100) + if ret: + if outport: + outport.writeData() + + return RTC.RTC_OK + + +def DataOutInit(manager): + profile = OpenRTM_aist.Properties(defaults_str=dataout_spec) + manager.registerFactory(profile, + DataOut, + OpenRTM_aist.Delete) + + +def MyModuleInit(manager): + DataOutInit(manager) + + # Create a component + comp = manager.createComponent("DataOut") + + +def main(): + # Initialize manager + mgr = OpenRTM_aist.Manager.init(sys.argv) + + # Set module initialization proceduer + # This procedure will be invoked in activateManager() function. + mgr.setModuleInitProc(MyModuleInit) + + # Activate manager and register to naming service + mgr.activateManager() + + # run the manager in blocking mode + # runManager(False) is the default + mgr.runManager() + + # If you want to run the manager in non-blocking mode, do like this + # mgr.runManager(True) + + +if __name__ == "__main__": + main() diff --git a/OpenRTM_aist/examples/CSPSelectSample/DataOut_port3.py b/OpenRTM_aist/examples/CSPSelectSample/DataOut_port3.py new file mode 100644 index 00000000..1b9c6d58 --- /dev/null +++ b/OpenRTM_aist/examples/CSPSelectSample/DataOut_port3.py @@ -0,0 +1,97 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +# -*- Python -*- + +from __future__ import print_function +import sys + +import RTC +import OpenRTM_aist + +dataout_port3_spec = ["implementation_id", "DataOut_port3", + "type_name", "DataOut_port3", + "description", "Data output component", + "version", "1.0", + "vendor", "Nobuhiko Miyamoto", + "category", "example", + "activity_type", "DataFlowComponent", + "max_instance", "10", + "language", "Python", + "lang_type", "script", + ""] + + +class DataOut_port3(OpenRTM_aist.DataFlowComponentBase): + def __init__(self, manager): + OpenRTM_aist.DataFlowComponentBase.__init__(self, manager) + return + + def onInitialize(self): + self._data1 = RTC.TimedLong(RTC.Time(0, 0), 0) + self._data2 = RTC.TimedLong(RTC.Time(0, 0), 0) + self._data3 = RTC.TimedLong(RTC.Time(0, 0), 0) + self._cspmanager = OpenRTM_aist.CSPManager() + self._outport1 = OpenRTM_aist.CSPOutPort( + "out1", self._data1, self._cspmanager) + self._outport2 = OpenRTM_aist.CSPOutPort( + "out2", self._data2, self._cspmanager) + self._outport3 = OpenRTM_aist.CSPOutPort( + "out3", self._data3, self._cspmanager) + # Set OutPort buffer + self.addOutPort("out1", self._outport1) + self.addOutPort("out2", self._outport2) + self.addOutPort("out3", self._outport3) + + return RTC.RTC_OK + + def onExecute(self, ec_id): + self._data1.data = 1 + self._data2.data = 2 + self._data3.data = 3 + OpenRTM_aist.setTimestamp(self._data1) + OpenRTM_aist.setTimestamp(self._data2) + OpenRTM_aist.setTimestamp(self._data3) + ret, outport, inport = self._cspmanager.select(100) + if ret: + if outport: + self._rtcout.RTC_ERROR("datawrite: %s", outport.name()) + outport.writeData() + + return RTC.RTC_OK + + +def DataOut_port3Init(manager): + profile = OpenRTM_aist.Properties(defaults_str=dataout_port3_spec) + manager.registerFactory(profile, + DataOut_port3, + OpenRTM_aist.Delete) + + +def MyModuleInit(manager): + DataOut_port3Init(manager) + + # Create a component + comp = manager.createComponent("DataOut_port3") + + +def main(): + # Initialize manager + mgr = OpenRTM_aist.Manager.init(sys.argv) + + # Set module initialization proceduer + # This procedure will be invoked in activateManager() function. + mgr.setModuleInitProc(MyModuleInit) + + # Activate manager and register to naming service + mgr.activateManager() + + # run the manager in blocking mode + # runManager(False) is the default + mgr.runManager() + + # If you want to run the manager in non-blocking mode, do like this + # mgr.runManager(True) + + +if __name__ == "__main__": + main() diff --git a/OpenRTM_aist/examples/CSPSelectSample/out1in3.bat b/OpenRTM_aist/examples/CSPSelectSample/out1in3.bat new file mode 100644 index 00000000..24134536 --- /dev/null +++ b/OpenRTM_aist/examples/CSPSelectSample/out1in3.bat @@ -0,0 +1,2 @@ +python DataOut_port3.py -f rtc_out1in3.conf +pause \ No newline at end of file diff --git a/OpenRTM_aist/examples/CSPSelectSample/out3in1.bat b/OpenRTM_aist/examples/CSPSelectSample/out3in1.bat new file mode 100644 index 00000000..042ffc0a --- /dev/null +++ b/OpenRTM_aist/examples/CSPSelectSample/out3in1.bat @@ -0,0 +1 @@ +python DataIn_port3.py -f rtc_out3in1.conf \ No newline at end of file diff --git a/OpenRTM_aist/examples/CSPSelectSample/out3in3.bat b/OpenRTM_aist/examples/CSPSelectSample/out3in3.bat new file mode 100644 index 00000000..502c558f --- /dev/null +++ b/OpenRTM_aist/examples/CSPSelectSample/out3in3.bat @@ -0,0 +1 @@ +python DataInOut.py -f rtc_out3in3.conf \ No newline at end of file diff --git a/OpenRTM_aist/examples/CSPSelectSample/rtc_out1in3.conf b/OpenRTM_aist/examples/CSPSelectSample/rtc_out1in3.conf new file mode 100644 index 00000000..b0b88b53 --- /dev/null +++ b/OpenRTM_aist/examples/CSPSelectSample/rtc_out1in3.conf @@ -0,0 +1,26 @@ +corba.nameservers: localhost +naming.formats: %n.rtc +logger.enable: YES +logger.log_level: ERROR +logger.file_name: stdout +corba.args: +manager.components.precreate: DataIn, DataIn, DataIn +manager.components.preconnect: DataOut_port30.out1?port=DataIn0.in&dataflow_type=duplex&interface_type=csp_channel, \ + DataOut_port30.out2?port=DataIn1.in&dataflow_type=duplex&interface_type=csp_channel, \ + DataOut_port30.out3?port=DataIn2.in&dataflow_type=duplex&interface_type=csp_channel +manager.components.preactivation: DataOut_port30, DataIn0, DataIn1, DataIn2 + +#manager.components.precreate: DataIn +#manager.components.preconnect: DataOut_port30.out0?port=DataIn0.in&dataflow_type=duplex&interface_type=csp_channel +#manager.components.preactivation: DataOut_port30, DataIn0 + +port.inport.in.buffer.length: 0 +port.inport.in.csp.sync_wait: YES +port.outport.out1.csp.sync_wait: NO +port.outport.out2.csp.sync_wait: NO +port.outport.out3.csp.sync_wait: NO + +example.DataOut_port30.exec_cxt.periodic.rate: 1000 +example.DataIn0.exec_cxt.periodic.rate: 10 +example.DataIn1.exec_cxt.periodic.rate: 2 +example.DataIn2.exec_cxt.periodic.rate: 1 \ No newline at end of file diff --git a/OpenRTM_aist/examples/CSPSelectSample/rtc_out3in1.conf b/OpenRTM_aist/examples/CSPSelectSample/rtc_out3in1.conf new file mode 100644 index 00000000..2a569812 --- /dev/null +++ b/OpenRTM_aist/examples/CSPSelectSample/rtc_out3in1.conf @@ -0,0 +1,22 @@ +corba.nameservers: localhost +naming.formats: %n.rtc +logger.enable: YES +logger.log_level: ERROR +logger.file_name: stdout +corba.args: +manager.components.precreate: DataOut, DataOut, DataOut +manager.components.preconnect: DataOut0.out?port=DataIn_port30.in1&dataflow_type=duplex&interface_type=csp_channel, \ + DataOut1.out?port=DataIn_port30.in2&dataflow_type=duplex&interface_type=csp_channel, \ + DataOut2.out?port=DataIn_port30.in3&dataflow_type=duplex&interface_type=csp_channel +manager.components.preactivation: DataIn_port30, DataOut0, DataOut1, DataOut2 + +#manager.components.precreate: DataOut +#manager.components.preconnect: DataOut0.out?port=DataIn_port30.in0&dataflow_type=duplex&interface_type=csp_channel +#manager.components.preactivation: DataIn_port30, DataOut0 + +port.inport.in.buffer.length: 0 + +example.DataIn_port30.exec_cxt.periodic.rate: 1000 +example.DataOut0.exec_cxt.periodic.rate: 5 +example.DataOut1.exec_cxt.periodic.rate: 2 +example.DataOut2.exec_cxt.periodic.rate: 1 \ No newline at end of file diff --git a/OpenRTM_aist/examples/CSPSelectSample/rtc_out3in3.conf b/OpenRTM_aist/examples/CSPSelectSample/rtc_out3in3.conf new file mode 100644 index 00000000..15475550 --- /dev/null +++ b/OpenRTM_aist/examples/CSPSelectSample/rtc_out3in3.conf @@ -0,0 +1,24 @@ +corba.nameservers: localhost +naming.formats: %n.rtc +logger.enable: YES +logger.log_level: ERROR +logger.file_name: stdout +corba.args: +manager.components.precreate: DataIn, DataIn, DataIn, DataOut, DataOut, DataOut +manager.components.preconnect: DataInOut0.out1?port=DataIn0.in&dataflow_type=duplex&interface_type=csp_channel, \ + DataInOut0.out2?port=DataIn1.in&dataflow_type=duplex&interface_type=csp_channel, \ + DataInOut0.out3?port=DataIn2.in&dataflow_type=duplex&interface_type=csp_channel, \ + DataOut0.out?port=DataInOut0.in1&dataflow_type=duplex&interface_type=csp_channel, \ + DataOut1.out?port=DataInOut0.in2&dataflow_type=duplex&interface_type=csp_channel, \ + DataOut2.out?port=DataInOut0.in3&dataflow_type=duplex&interface_type=csp_channel +manager.components.preactivation: DataInOut0, DataIn0, DataIn1, DataIn2, DataOut0, DataOut1, DataOut2 + +port.inport.in.buffer.length: 0 + +example.DataInOut0.exec_cxt.periodic.rate: 1000 +example.DataIn0.exec_cxt.periodic.rate: 5 +example.DataIn1.exec_cxt.periodic.rate: 2 +example.DataIn2.exec_cxt.periodic.rate: 1 +example.DataOut0.exec_cxt.periodic.rate: 5 +example.DataOut1.exec_cxt.periodic.rate: 2 +example.DataOut2.exec_cxt.periodic.rate: 1 \ No newline at end of file diff --git a/OpenRTM_aist/examples/CSPStaticFsmSample/Inputbutton.py b/OpenRTM_aist/examples/CSPStaticFsmSample/Inputbutton.py new file mode 100644 index 00000000..8b3c4244 --- /dev/null +++ b/OpenRTM_aist/examples/CSPStaticFsmSample/Inputbutton.py @@ -0,0 +1,155 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- + +## +# @file Inputbutton.py +# @brief example StaticFSM +# @date $Date: $ +# @author Nobuhiko Miyamoto +# +# Copyright (C) 2017 +# Intelligent Systems Research Institute, +# National Institute of +# Advanced Industrial Science and Technology (AIST), Japan +# All rights reserved. + +from __future__ import print_function +import sys + +import RTC +import OpenRTM_aist +import OpenRTM_aist.StringUtil + +inputbutton_spec = ["implementation_id", "Inputbutton", + "type_name", "Inputbutton", + "description", "Console input component", + "version", "1.0", + "vendor", "Nobuhiko Miyamoto", + "category", "example", + "activity_type", "DataFlowComponent", + "max_instance", "10", + "language", "Python", + "lang_type", "script", + ""] + + +class Inputbutton(OpenRTM_aist.DataFlowComponentBase): + def __init__(self, manager): + OpenRTM_aist.DataFlowComponentBase.__init__(self, manager) + return + + def onInitialize(self): + self._open = RTC.TimedLong(RTC.Time(0, 0), 0) + self._close = RTC.TimedLong(RTC.Time(0, 0), 0) + self._minute = RTC.TimedLong(RTC.Time(0, 0), 0) + self._start = RTC.TimedLong(RTC.Time(0, 0), 0) + self._stop = RTC.TimedLong(RTC.Time(0, 0), 0) + self._tick = RTC.TimedLong(RTC.Time(0, 0), 0) + + self._openOut = OpenRTM_aist.CSPOutPort("open", self._open) + self._closeOut = OpenRTM_aist.CSPOutPort("close", self._close) + self._minuteOut = OpenRTM_aist.CSPOutPort("minute", self._minute) + self._startOut = OpenRTM_aist.CSPOutPort("start", self._start) + self._stopOut = OpenRTM_aist.CSPOutPort("stop", self._stop) + self._tickOut = OpenRTM_aist.CSPOutPort("tick", self._tick) + # Set OutPort buffer + self.addOutPort("open", self._openOut) + self.addOutPort("close", self._closeOut) + self.addOutPort("minute", self._minuteOut) + self.addOutPort("start", self._startOut) + self.addOutPort("stop", self._stopOut) + self.addOutPort("tick", self._tickOut) + + return RTC.RTC_OK + + def onExecute(self, ec_id): + print("") + print("Please select action!!") + print("Commands: ") + print(" open : Open the microwave's door.") + print(" close : Close the microwave's door.") + print(" minute : Increment timer. ") + print(" start : Start the microwave.") + print(" stop : Stop the microwave.") + print(" tick : Proceed time.") + print(" -> others are interpreted as tick commnad.") + print(">> ", end="") + #print(">> ",end="") + cmds = sys.stdin.readline() + cmds = cmds.split(" ") + OpenRTM_aist.StringUtil.eraseBlank(cmds) + cmds[0] = cmds[0].replace("\n", "") + cmds[0] = cmds[0].replace("\r", "") + print("[command]: ", cmds[0]) + #print(" [args]: ",end="") + print(" [args]: ", end="") + for n in range(len(cmds)): + if n == 0: + continue + # print(cmds[n],end="") + print(cmds[n], end="") + print("") + if cmds[0] == "open": + self._open.data = 0 + self._openOut.write() + elif cmds[0] == "close": + self._close.data = 0 + self._closeOut.write() + elif cmds[0] == "minute": + min = [0] + if len(cmds) < 2 or not OpenRTM_aist.StringUtil.stringTo( + min, cmds[1]): + print("minute command needs an integer arg.") + return RTC.RTC_OK + + self._minute.data = min[0] + self._minuteOut.write() + elif cmds[0] == "start": + self._start.data = 0 + self._startOut.write() + elif cmds[0] == "stop": + self._stop.data = 0 + self._stopOut.write() + else: + print("tick") + self._tick.data = 0 + self._tickOut.write() + + return RTC.RTC_OK + + +def InputbuttonInit(manager): + profile = OpenRTM_aist.Properties(defaults_str=inputbutton_spec) + manager.registerFactory(profile, + Inputbutton, + OpenRTM_aist.Delete) + + +def MyModuleInit(manager): + InputbuttonInit(manager) + + # Create a component + comp = manager.createComponent("Inputbutton") + + +def main(): + # Initialize manager + mgr = OpenRTM_aist.Manager.init(sys.argv) + + # Set module initialization proceduer + # This procedure will be invoked in activateManager() function. + mgr.setModuleInitProc(MyModuleInit) + + # Activate manager and register to naming service + mgr.activateManager() + + # run the manager in blocking mode + # runManager(False) is the default + mgr.runManager() + + # If you want to run the manager in non-blocking mode, do like this + # mgr.runManager(True) + + +if __name__ == "__main__": + main() diff --git a/OpenRTM_aist/examples/CSPStaticFsmSample/Microwave.py b/OpenRTM_aist/examples/CSPStaticFsmSample/Microwave.py new file mode 100644 index 00000000..dbbf78c3 --- /dev/null +++ b/OpenRTM_aist/examples/CSPStaticFsmSample/Microwave.py @@ -0,0 +1,121 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- + +## +# @file Microwave.py +# @brief example StaticFSM +# @date $Date: $ +# @author Nobuhiko Miyamoto +# +# Copyright (C) 2017 +# Intelligent Systems Research Institute, +# National Institute of +# Advanced Industrial Science and Technology (AIST), Japan +# All rights reserved. + +import sys + +import RTC +import OpenRTM_aist + +import OpenRTM_aist.CSPMachine as CSPMachine +import OpenRTM_aist.CSPEventPort as CSPEventPort + +import MicrowaveFsm + +microwave_spec = ["implementation_id", "Microwave", + "type_name", "Microwave", + "description", "Console input component", + "version", "1.0", + "vendor", "Nobuhiko Miyamoto", + "category", "example", + "activity_type", "DataFlowComponent", + "max_instance", "10", + "language", "Python", + "lang_type", "script", + ""] + + +class Microwave(OpenRTM_aist.DataFlowComponentBase): + def __init__(self, manager): + OpenRTM_aist.DataFlowComponentBase.__init__(self, manager) + + return + + def onInitialize(self): + self._fsm = CSPMachine.CSPMachine(MicrowaveFsm.TOP, self) + # self._fsm.init() + self._cspmanager = OpenRTM_aist.CSPManager() + self._eventIn = CSPEventPort.CSPEventPort( + "event", self._fsm, self._cspmanager) + + self.addInPort("event", self._eventIn) + self._eventIn.bindEvent0("open", MicrowaveFsm.TOP.open) + self._eventIn.bindEvent0("close", MicrowaveFsm.TOP.close) + self._eventIn.bindEvent1( + "minute", + MicrowaveFsm.TOP.minute, + RTC.TimedLong( + RTC.Time( + 0, + 0), + 0)) + self._eventIn.bindEvent0("start", MicrowaveFsm.TOP.start) + self._eventIn.bindEvent0("stop", MicrowaveFsm.TOP.stop) + self._eventIn.bindEvent0("tick", MicrowaveFsm.TOP.tick) + + return RTC.RTC_OK + + def onFinalize(self): + self._fsm.shutdown() + return RTC.RTC_OK + + def onExecute(self, ec_id): + # self._fsm.run_event() + ret, outport, inport = self._cspmanager.select(10) + if ret: + if inport: + event = inport.readData() + event() + return RTC.RTC_OK + elif outport: + outport.write() + return RTC.RTC_OK + return RTC.RTC_OK + + +def MicrowaveInit(manager): + profile = OpenRTM_aist.Properties(defaults_str=microwave_spec) + manager.registerFactory(profile, + Microwave, + OpenRTM_aist.Delete) + + +def MyModuleInit(manager): + MicrowaveInit(manager) + + # Create a component + comp = manager.createComponent("Microwave") + + +def main(): + # Initialize manager + mgr = OpenRTM_aist.Manager.init(sys.argv) + + # Set module initialization proceduer + # This procedure will be invoked in activateManager() function. + mgr.setModuleInitProc(MyModuleInit) + + # Activate manager and register to naming service + mgr.activateManager() + + # run the manager in blocking mode + # runManager(False) is the default + mgr.runManager() + + # If you want to run the manager in non-blocking mode, do like this + # mgr.runManager(True) + + +if __name__ == "__main__": + main() diff --git a/OpenRTM_aist/examples/CSPStaticFsmSample/MicrowaveFsm.py b/OpenRTM_aist/examples/CSPStaticFsmSample/MicrowaveFsm.py new file mode 100644 index 00000000..134bd48b --- /dev/null +++ b/OpenRTM_aist/examples/CSPStaticFsmSample/MicrowaveFsm.py @@ -0,0 +1,138 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- + +## +# @file Microwave.py +# @brief example StaticFSM +# @date $Date: $ +# @author Nobuhiko Miyamoto +# +# Copyright (C) 2017 +# Intelligent Systems Research Institute, +# National Institute of +# Advanced Industrial Science and Technology (AIST), Japan +# All rights reserved. + +from __future__ import print_function +import sys + + +import RTC +import OpenRTM_aist.StaticFSM as StaticFSM + + +@StaticFSM.FSM_TOPSTATE +class TOP(StaticFSM.Link): + def onInit(self): + self.set_state(StaticFSM.State(Operational)) + return RTC.RTC_OK + + def open(self): + pass + + def close(self): + pass + + def minute(self, time_): + pass + + def start(self): + pass + + def stop(self): + pass + + def tick(self): + pass + + class Data: + def __init__(self): + self.myCookingTime = 0 + + def printTimer(self): + print(" Timer set to ", self.myCookingTime, " minutes") + + def incrementTimer(self): + self.myCookingTime += 1 + + def decrementTimer(self): + self.myCookingTime -= 1 + + def resetTimer(self): + self.myCookingTime = 0 + + def getRemainingTime(self): + return self.myCookingTime + + +@StaticFSM.FSM_SUBSTATE(TOP) +class Disabled(StaticFSM.Link): + def onEntry(self): + print(" Microwave opened") + return RTC.RTC_OK + + def onExit(self): + print(" Microwave closed") + return RTC.RTC_OK + + def close(self): + # self.setStateHistory(OpenRTM_aist.Macho.State(Operational)) + self.set_state(StaticFSM.State(Operational)) + + +@StaticFSM.deephistory +@StaticFSM.FSM_SUBSTATE(TOP) +class Operational(StaticFSM.Link): + def open(self): + self.set_state(StaticFSM.State(Disabled)) + + def stop(self): + self.set_state(StaticFSM.State(Idle)) + + def onInit(self): + self.set_state(StaticFSM.State(Idle)) + return RTC.RTC_OK + + +@StaticFSM.FSM_SUBSTATE(Operational) +class Idle(StaticFSM.Link): + def minute(self, time_): + self.set_state(StaticFSM.State(Programmed)) + self.dispatch(StaticFSM.Event(TOP.minute, time_)) + + def onEntry(self): + self.data(TOP).resetTimer() + print(" Microwave ready") + return RTC.RTC_OK + + +@StaticFSM.FSM_SUBSTATE(Operational) +class Programmed(StaticFSM.Link): + def minute(self, time_): + for t in range(time_.data): + self.data(TOP).incrementTimer() + self.data(TOP).printTimer() + + def start(self): + self.set_state(StaticFSM.State(Cooking)) + + +@StaticFSM.FSM_SUBSTATE(Programmed) +class Cooking(StaticFSM.Link): + def tick(self): + print(" Clock tick") + tb = self.data(TOP) + tb.decrementTimer() + if tb.getRemainingTime() == 0: + print(" Finished") + self.set_state(StaticFSM.State(Idle)) + else: + tb.printTimer() + + def onEntry(self): + print(" Heating on") + return RTC.RTC_OK + + def onExit(self): + print(" Heating off") + return RTC.RTC_OK diff --git a/OpenRTM_aist/examples/CSPStaticFsmSample/MicrowaveFsm_pyfsm.py b/OpenRTM_aist/examples/CSPStaticFsmSample/MicrowaveFsm_pyfsm.py new file mode 100644 index 00000000..67a34ff3 --- /dev/null +++ b/OpenRTM_aist/examples/CSPStaticFsmSample/MicrowaveFsm_pyfsm.py @@ -0,0 +1,137 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- + +## +# @file Microwave.py +# @brief example StaticFSM +# @date $Date: $ +# @author Nobuhiko Miyamoto +# +# Copyright (C) 2017 +# Intelligent Systems Research Institute, +# National Institute of +# Advanced Industrial Science and Technology (AIST), Japan +# All rights reserved. + +from __future__ import print_function +import sys + + +import OpenRTM_aist.StaticFSM_pyfsm as StaticFSM + + +@StaticFSM.FSM_TOPSTATE +class TOP(StaticFSM.Link): + def onInit(self): + self.set_state(StaticFSM.State(Operational)) + return RTC.RTC_OK + + def open(self): + pass + + def close(self): + pass + + def minute(self, time_): + pass + + def start(self): + pass + + def stop(self): + pass + + def tick(self): + pass + + class Data: + def __init__(self): + self.myCookingTime = 0 + + def printTimer(self): + print(" Timer set to ", self.myCookingTime, " minutes") + + def incrementTimer(self): + self.myCookingTime += 1 + + def decrementTimer(self): + self.myCookingTime -= 1 + + def resetTimer(self): + self.myCookingTime = 0 + + def getRemainingTime(self): + return self.myCookingTime + + +@StaticFSM.FSM_SUBSTATE(TOP) +class Disabled(StaticFSM.Link): + def onEntry(self): + print(" Microwave opened") + return RTC.RTC_OK + + def onExit(self): + print(" Microwave closed") + return RTC.RTC_OK + + def close(self): + # self.setStateHistory(OpenRTM_aist.Macho.State(Operational)) + self.set_state(StaticFSM.State(Operational)) + + +@StaticFSM.deephistory +@StaticFSM.FSM_SUBSTATE(TOP) +class Operational(StaticFSM.Link): + def open(self): + self.set_state(StaticFSM.State(Disabled)) + + def stop(self): + self.set_state(StaticFSM.State(Idle)) + + def onInit(self): + self.set_state(StaticFSM.State(Idle)) + return RTC.RTC_OK + + +@StaticFSM.FSM_SUBSTATE(Operational) +class Idle(StaticFSM.Link): + def minute(self, time_): + self.set_state(StaticFSM.State(Programmed)) + self.dispatch(StaticFSM.Event(TOP.minute, time_)) + + def onEntry(self): + self.data(TOP).resetTimer() + print(" Microwave ready") + return RTC.RTC_OK + + +@StaticFSM.FSM_SUBSTATE(Operational) +class Programmed(StaticFSM.Link): + def minute(self, time_): + for t in range(time_.data): + self.data(TOP).incrementTimer() + self.data(TOP).printTimer() + + def start(self): + self.set_state(StaticFSM.State(Cooking)) + + +@StaticFSM.FSM_SUBSTATE(Programmed) +class Cooking(StaticFSM.Link): + def tick(self): + print(" Clock tick") + tb = self.data(TOP) + tb.decrementTimer() + if tb.getRemainingTime() == 0: + print(" Finished") + self.set_state(StaticFSM.State(Idle)) + else: + tb.printTimer() + + def onEntry(self): + print(" Heating on") + return RTC.RTC_OK + + def onExit(self): + print(" Heating off") + return RTC.RTC_OK diff --git a/OpenRTM_aist/examples/CSPStaticFsmSample/Microwave_pyfsm.py b/OpenRTM_aist/examples/CSPStaticFsmSample/Microwave_pyfsm.py new file mode 100644 index 00000000..33fb7b33 --- /dev/null +++ b/OpenRTM_aist/examples/CSPStaticFsmSample/Microwave_pyfsm.py @@ -0,0 +1,111 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- + +## +# @file Microwave.py +# @brief example StaticFSM +# @date $Date: $ +# @author Nobuhiko Miyamoto +# +# Copyright (C) 2017 +# Intelligent Systems Research Institute, +# National Institute of +# Advanced Industrial Science and Technology (AIST), Japan +# All rights reserved. + +import sys + +import RTC +import OpenRTM_aist +import OpenRTM_aist.StaticFSM_pyfsm as StaticFSM +import OpenRTM_aist.EventPort_pyfsm as EventPort + + +import MicrowaveFsm_pyfsm + +microwave_spec = ["implementation_id", "Microwave", + "type_name", "Microwave", + "description", "Console input component", + "version", "1.0", + "vendor", "Nobuhiko Miyamoto", + "category", "example", + "activity_type", "DataFlowComponent", + "max_instance", "10", + "language", "Python", + "lang_type", "script", + ""] + + +class Microwave(OpenRTM_aist.DataFlowComponentBase): + def __init__(self, manager): + OpenRTM_aist.DataFlowComponentBase.__init__(self, manager) + + return + + def onFinalize(self): + self._fsm.exit() + return RTC.RTC_OK + + def onInitialize(self): + self._fsm = StaticFSM.Machine(MicrowaveFsm.TOP, self) + # self._fsm.init() + self._eventIn = EventPort.EventInPort("event", self._fsm) + + self.addInPort("event", self._eventIn) + self._eventIn.bindEvent0("open", MicrowaveFsm.TOP.open) + self._eventIn.bindEvent0("close", MicrowaveFsm.TOP.close) + self._eventIn.bindEvent1( + "minute", + MicrowaveFsm.TOP.minute, + RTC.TimedLong( + RTC.Time( + 0, + 0), + 0)) + self._eventIn.bindEvent0("start", MicrowaveFsm.TOP.start) + self._eventIn.bindEvent0("stop", MicrowaveFsm.TOP.stop) + self._eventIn.bindEvent0("tick", MicrowaveFsm.TOP.tick) + + return RTC.RTC_OK + + def onExecute(self, ec_id): + self._fsm.run_event() + + return RTC.RTC_OK + + +def MicrowaveInit(manager): + profile = OpenRTM_aist.Properties(defaults_str=microwave_spec) + manager.registerFactory(profile, + Microwave, + OpenRTM_aist.Delete) + + +def MyModuleInit(manager): + MicrowaveInit(manager) + + # Create a component + comp = manager.createComponent("Microwave") + + +def main(): + # Initialize manager + mgr = OpenRTM_aist.Manager.init(sys.argv) + + # Set module initialization proceduer + # This procedure will be invoked in activateManager() function. + mgr.setModuleInitProc(MyModuleInit) + + # Activate manager and register to naming service + mgr.activateManager() + + # run the manager in blocking mode + # runManager(False) is the default + mgr.runManager() + + # If you want to run the manager in non-blocking mode, do like this + # mgr.runManager(True) + + +if __name__ == "__main__": + main() diff --git a/OpenRTM_aist/examples/CSPStaticFsmSample/inputbutton.conf b/OpenRTM_aist/examples/CSPStaticFsmSample/inputbutton.conf new file mode 100644 index 00000000..69a895f3 --- /dev/null +++ b/OpenRTM_aist/examples/CSPStaticFsmSample/inputbutton.conf @@ -0,0 +1,5 @@ +#============================================================ +# component profile +#============================================================ +# data port configurations +# diff --git a/OpenRTM_aist/examples/CSPStaticFsmSample/microwave.conf b/OpenRTM_aist/examples/CSPStaticFsmSample/microwave.conf new file mode 100644 index 00000000..69a895f3 --- /dev/null +++ b/OpenRTM_aist/examples/CSPStaticFsmSample/microwave.conf @@ -0,0 +1,5 @@ +#============================================================ +# component profile +#============================================================ +# data port configurations +# diff --git a/OpenRTM_aist/examples/CSPStaticFsmSample/rtc.conf b/OpenRTM_aist/examples/CSPStaticFsmSample/rtc.conf new file mode 100644 index 00000000..278beebd --- /dev/null +++ b/OpenRTM_aist/examples/CSPStaticFsmSample/rtc.conf @@ -0,0 +1,20 @@ +corba.nameservers: localhost +naming.formats: %n.rtc +logger.enable: YES +logger.log_level: ERROR +logger.file_name: stdout + +manager.modules.load_path: ./ +manager.modules.preload: Microwave.py +manager.components.precreate: Microwave +manager.components.preactivation: Inputbutton0, Microwave0 +manager.components.preconnect: \ + Inputbutton0.open?port=Microwave0.event&fsm_event_name=open&dataflow_type=duplex&interface_type=csp_channel, \ + Inputbutton0.close?port=Microwave0.event&fsm_event_name=close&dataflow_type=duplex&interface_type=csp_channel, \ + Inputbutton0.minute?port=Microwave0.event&fsm_event_name=minute&dataflow_type=duplex&interface_type=csp_channel, \ + Inputbutton0.start?port=Microwave0.event&fsm_event_name=start&dataflow_type=duplex&interface_type=csp_channel, \ + Inputbutton0.stop?port=Microwave0.event&fsm_event_name=stop&dataflow_type=duplex&interface_type=csp_channel, \ + Inputbutton0.tick?port=Microwave0.event&fsm_event_name=tick&dataflow_type=duplex&interface_type=csp_channel + + +port.inport.event.buffer.length: 1 \ No newline at end of file diff --git a/OpenRTM_aist/examples/Composite/Composite.py b/OpenRTM_aist/examples/Composite/Composite.py index bc0358e3..c9836e52 100644 --- a/OpenRTM_aist/examples/Composite/Composite.py +++ b/OpenRTM_aist/examples/Composite/Composite.py @@ -1,4 +1,4 @@ -#!/usr/bin/env python +#!/usr/bin/env python # -*- coding: utf-8 -*- # -*- Python -*- @@ -21,15 +21,16 @@ import OpenRTM_aist + def main(): - manager = OpenRTM_aist.Manager.init(sys.argv) + manager = OpenRTM_aist.Manager.init(sys.argv) + + manager.activateManager() - manager.activateManager() - - manager.runManager() + manager.runManager() - return 0 + return 0 if __name__ == "__main__": - main() + main() diff --git a/OpenRTM_aist/examples/Composite/Controller.py b/OpenRTM_aist/examples/Composite/Controller.py index d396fe5b..69157e54 100644 --- a/OpenRTM_aist/examples/Composite/Controller.py +++ b/OpenRTM_aist/examples/Composite/Controller.py @@ -1,78 +1,77 @@ -#!/usr/bin/env python +#!/usr/bin/env python # -*- coding: utf-8 -*- # -*- Python -*- from __future__ import print_function +import OpenRTM_aist +import RTC import sys import time sys.path.append(".") # Import RTM module -import RTC -import OpenRTM_aist -controller_spec = ["implementation_id", "Controller", - "type_name", "Controller", - "description", "Controller component", - "version", "1.0", - "vendor", "Shinji Kurihara, AIST", - "category", "example", - "activity_type", "DataFlowComponent", - "max_instance", "10", - "language", "Python", - "lang_type", "SCRIPT", +controller_spec = ["implementation_id", "Controller", + "type_name", "Controller", + "description", "Controller component", + "version", "1.0", + "vendor", "Shinji Kurihara, AIST", + "category", "example", + "activity_type", "DataFlowComponent", + "max_instance", "10", + "language", "Python", + "lang_type", "SCRIPT", ""] + class Controller(OpenRTM_aist.DataFlowComponentBase): - def __init__(self, manager): - OpenRTM_aist.DataFlowComponentBase.__init__(self, manager) - return - - def onInitialize(self): - self._d_in = RTC.TimedFloat(RTC.Time(0,0),0) - self._inIn = OpenRTM_aist.InPort("in", self._d_in) - self._d_out = RTC.TimedFloat(RTC.Time(0,0),0) - self._outOut = OpenRTM_aist.OutPort("out", self._d_out) - - # Set InPort buffers - self.addInPort("in",self._inIn) - - # Set OutPort buffers - self.addOutPort("out",self._outOut) - - return RTC.RTC_OK - - - def onExecute(self, ec_id): - if self._inIn.isNew(): - data = self._inIn.read() - print("Controller Received data: ", data.data) - self._d_out.data = data.data *2 - self._outOut.write() - return RTC.RTC_OK - + def __init__(self, manager): + OpenRTM_aist.DataFlowComponentBase.__init__(self, manager) + return + + def onInitialize(self): + self._d_in = RTC.TimedFloat(RTC.Time(0, 0), 0) + self._inIn = OpenRTM_aist.InPort("in", self._d_in) + self._d_out = RTC.TimedFloat(RTC.Time(0, 0), 0) + self._outOut = OpenRTM_aist.OutPort("out", self._d_out) + # Set InPort buffers + self.addInPort("in", self._inIn) + + # Set OutPort buffers + self.addOutPort("out", self._outOut) + + return RTC.RTC_OK + + def onExecute(self, ec_id): + if self._inIn.isNew(): + data = self._inIn.read() + print("Controller Received data: ", data.data) + self._d_out.data = data.data * 2 + self._outOut.write() + return RTC.RTC_OK def ControllerInit(manager): - profile = OpenRTM_aist.Properties(defaults_str=controller_spec) - manager.registerFactory(profile, - Controller, - OpenRTM_aist.Delete) + profile = OpenRTM_aist.Properties(defaults_str=controller_spec) + manager.registerFactory(profile, + Controller, + OpenRTM_aist.Delete) -def MyModuleInit(manager): - ControllerInit(manager) - # Create a component - comp = manager.createComponent("Controller") +def MyModuleInit(manager): + ControllerInit(manager) + # Create a component + comp = manager.createComponent("Controller") def main(): - mgr = OpenRTM_aist.Manager.init(sys.argv) - mgr.setModuleInitProc(MyModuleInit) - mgr.activateManager() - mgr.runManager() + mgr = OpenRTM_aist.Manager.init(sys.argv) + mgr.setModuleInitProc(MyModuleInit) + mgr.activateManager() + mgr.runManager() + if __name__ == "__main__": - main() + main() diff --git a/OpenRTM_aist/examples/Composite/Motor.py b/OpenRTM_aist/examples/Composite/Motor.py index a501de7f..77392e77 100644 --- a/OpenRTM_aist/examples/Composite/Motor.py +++ b/OpenRTM_aist/examples/Composite/Motor.py @@ -1,85 +1,83 @@ -#!/usr/bin/env python +#!/usr/bin/env python # -*- coding: utf-8 -*- # -*- Python -*- from __future__ import print_function +import OpenRTM_aist +import RTC import sys import time sys.path.append(".") # Import RTM module -import RTC -import OpenRTM_aist -motor_spec = ["implementation_id", "Motor", - "type_name", "Motor", - "description", "Motor component", - "version", "1.0", - "vendor", "Noriaki Ando, AIST", - "category", "example", - "activity_type", "DataFlowComponent", - "max_instance", "10", - "language", "Python", - "lang_type", "SCRIPT", +motor_spec = ["implementation_id", "Motor", + "type_name", "Motor", + "description", "Motor component", + "version", "1.0", + "vendor", "Noriaki Ando, AIST", + "category", "example", + "activity_type", "DataFlowComponent", + "max_instance", "10", + "language", "Python", + "lang_type", "SCRIPT", "conf.default.motor_id", "0", ""] + class Motor(OpenRTM_aist.DataFlowComponentBase): - def __init__(self, manager): - OpenRTM_aist.DataFlowComponentBase.__init__(self, manager) - return + def __init__(self, manager): + OpenRTM_aist.DataFlowComponentBase.__init__(self, manager) + return - def onInitialize(self): - self._d_in = RTC.TimedFloat(RTC.Time(0,0),0) - self._inIn = OpenRTM_aist.InPort("in", self._d_in) - self._d_out = RTC.TimedLong(RTC.Time(0,0),0) - self._outOut = OpenRTM_aist.OutPort("out", self._d_out) + def onInitialize(self): + self._d_in = RTC.TimedFloat(RTC.Time(0, 0), 0) + self._inIn = OpenRTM_aist.InPort("in", self._d_in) + self._d_out = RTC.TimedLong(RTC.Time(0, 0), 0) + self._outOut = OpenRTM_aist.OutPort("out", self._d_out) - # Set InPort buffers - self.addInPort("in",self._inIn) - - # Set OutPort buffers - self.addOutPort("out",self._outOut) + # Set InPort buffers + self.addInPort("in", self._inIn) - self._motor_id = [0] - - # Bind variables and configuration variable - self.bindParameter("motor_id", self._motor_id, "0") - self._configsets.update("default") - return RTC.RTC_OK + # Set OutPort buffers + self.addOutPort("out", self._outOut) + self._motor_id = [0] - def onExecute(self, ec_id): - if self._inIn.isNew(): - data = self._inIn.read() - print("Motor Received data: ", data.data) - self._d_out.data = int(data.data *2) - self._outOut.write() - return RTC.RTC_OK - + # Bind variables and configuration variable + self.bindParameter("motor_id", self._motor_id, "0") + self._configsets.update("default") + return RTC.RTC_OK + def onExecute(self, ec_id): + if self._inIn.isNew(): + data = self._inIn.read() + print("Motor Received data: ", data.data) + self._d_out.data = int(data.data * 2) + self._outOut.write() + return RTC.RTC_OK def MotorInit(manager): - profile = OpenRTM_aist.Properties(defaults_str=motor_spec) - manager.registerFactory(profile, - Motor, - OpenRTM_aist.Delete) + profile = OpenRTM_aist.Properties(defaults_str=motor_spec) + manager.registerFactory(profile, + Motor, + OpenRTM_aist.Delete) -def MyModuleInit(manager): - MotorInit(manager) - # Create a component - comp = manager.createComponent("Motor") +def MyModuleInit(manager): + MotorInit(manager) + # Create a component + comp = manager.createComponent("Motor") def main(): - mgr = OpenRTM_aist.Manager.init(sys.argv) - mgr.setModuleInitProc(MyModuleInit) - mgr.activateManager() - mgr.runManager() + mgr = OpenRTM_aist.Manager.init(sys.argv) + mgr.setModuleInitProc(MyModuleInit) + mgr.activateManager() + mgr.runManager() -if __name__ == "__main__": - main() +if __name__ == "__main__": + main() diff --git a/OpenRTM_aist/examples/Composite/Sensor.py b/OpenRTM_aist/examples/Composite/Sensor.py index 26b8b18e..d348c34b 100644 --- a/OpenRTM_aist/examples/Composite/Sensor.py +++ b/OpenRTM_aist/examples/Composite/Sensor.py @@ -1,77 +1,76 @@ -#!/usr/bin/env python +#!/usr/bin/env python # -*- coding: utf-8 -*- # -*- Python -*- from __future__ import print_function +import OpenRTM_aist +import RTC import sys import time sys.path.append(".") -import RTC -import OpenRTM_aist -sensor_spec = ["implementation_id", "Sensor", - "type_name", "Sensor", - "description", "Sensor component", - "version", "1.0", - "vendor", "Noriaki Ando, AIST", - "category", "example", - "activity_type", "DataFlowComponent", - "max_instance", "10", - "language", "Python", - "lang_type", "SCRIPT", +sensor_spec = ["implementation_id", "Sensor", + "type_name", "Sensor", + "description", "Sensor component", + "version", "1.0", + "vendor", "Noriaki Ando, AIST", + "category", "example", + "activity_type", "DataFlowComponent", + "max_instance", "10", + "language", "Python", + "lang_type", "SCRIPT", ""] class Sensor(OpenRTM_aist.DataFlowComponentBase): - def __init__(self, manager): - OpenRTM_aist.DataFlowComponentBase.__init__(self, manager) - return - - def onInitialize(self): - self._d_in = RTC.TimedLong(RTC.Time(0,0),0) - self._inIn = OpenRTM_aist.InPort("in", self._d_in) - self._d_out = RTC.TimedFloat(RTC.Time(0,0),0) - self._outOut = OpenRTM_aist.OutPort("out", self._d_out) - - # Set InPort buffers - self.addInPort("in",self._inIn) - - # Set OutPort buffers - self.addOutPort("out",self._outOut) - - return RTC.RTC_OK - - - def onExecute(self, ec_id): - if self._inIn.isNew(): - data = self._inIn.read() - print("Sensor Received data: ", data.data) - self._d_out.data = data.data *2 - self._outOut.write() - return RTC.RTC_OK - + def __init__(self, manager): + OpenRTM_aist.DataFlowComponentBase.__init__(self, manager) + return + + def onInitialize(self): + self._d_in = RTC.TimedLong(RTC.Time(0, 0), 0) + self._inIn = OpenRTM_aist.InPort("in", self._d_in) + self._d_out = RTC.TimedFloat(RTC.Time(0, 0), 0) + self._outOut = OpenRTM_aist.OutPort("out", self._d_out) + + # Set InPort buffers + self.addInPort("in", self._inIn) + + # Set OutPort buffers + self.addOutPort("out", self._outOut) + + return RTC.RTC_OK + + def onExecute(self, ec_id): + if self._inIn.isNew(): + data = self._inIn.read() + print("Sensor Received data: ", data.data) + self._d_out.data = data.data * 2 + self._outOut.write() + return RTC.RTC_OK def SensorInit(manager): - profile = OpenRTM_aist.Properties(defaults_str=sensor_spec) - manager.registerFactory(profile, - Sensor, - OpenRTM_aist.Delete) + profile = OpenRTM_aist.Properties(defaults_str=sensor_spec) + manager.registerFactory(profile, + Sensor, + OpenRTM_aist.Delete) + def MyModuleInit(manager): - SensorInit(manager) + SensorInit(manager) - # Create a component - comp = manager.createComponent("Sensor") + # Create a component + comp = manager.createComponent("Sensor") def main(): - mgr = OpenRTM_aist.Manager.init(sys.argv) - mgr.setModuleInitProc(MyModuleInit) - mgr.activateManager() - mgr.runManager() + mgr = OpenRTM_aist.Manager.init(sys.argv) + mgr.setModuleInitProc(MyModuleInit) + mgr.activateManager() + mgr.runManager() -if __name__ == "__main__": - main() +if __name__ == "__main__": + main() diff --git a/OpenRTM_aist/examples/Composite/__init__.py b/OpenRTM_aist/examples/Composite/__init__.py index 932b7982..270be2a2 100644 --- a/OpenRTM_aist/examples/Composite/__init__.py +++ b/OpenRTM_aist/examples/Composite/__init__.py @@ -1 +1 @@ -# Empty file +# Empty file diff --git a/OpenRTM_aist/examples/ConfigSample/ConfigSample.py b/OpenRTM_aist/examples/ConfigSample/ConfigSample.py index 6be33cb2..cb573975 100644 --- a/OpenRTM_aist/examples/ConfigSample/ConfigSample.py +++ b/OpenRTM_aist/examples/ConfigSample/ConfigSample.py @@ -1,4 +1,4 @@ -#!/usr/bin/env python +#!/usr/bin/env python # -*- coding: utf-8 -*- # -*- Python -*- @@ -11,15 +11,15 @@ # Module specification configsample_spec = ["implementation_id", "ConfigSample", - "type_name", "ConfigSample", - "description", "Configuration example component", - "version", "1.0", - "vendor", "Shinji Kurihara", - "category", "example", - "activity_type", "DataFlowComponent", - "max_instance", "10", - "language", "Python", - "lang_type", "script", + "type_name", "ConfigSample", + "description", "Configuration example component", + "version", "1.0", + "vendor", "Shinji Kurihara", + "category", "example", + "activity_type", "DataFlowComponent", + "max_instance", "10", + "language", "Python", + "lang_type", "script", "conf.default.int_param0", "0", "conf.default.int_param1", "1", "conf.default.double_param0", "0.11", @@ -32,136 +32,146 @@ i = 0 maxlen = 0 + def ticktack(): - global i - str_ = "/-\\|" - i = (i+1) % 4 - return str_[i] + global i + str_ = "/-\\|" + i = (i + 1) % 4 + return str_[i] + class MyConfigurationParamListner(OpenRTM_aist.ConfigurationParamListener): - def __init__(self): - pass + def __init__(self): + pass + + def __call__(self, config_set_name, config_param_name): + print( + "Changed config_set_name: ", + config_set_name, + " config_param_name: ", + config_param_name) + return - def __call__(self, config_set_name, config_param_name): - print("Changed config_set_name: ", config_set_name, " config_param_name: ", config_param_name) - return - class ConfigSample(OpenRTM_aist.DataFlowComponentBase): - # class constructor - def __init__(self, manager): - OpenRTM_aist.DataFlowComponentBase.__init__(self, manager) - print("ConfigSample constructor.") - self._int_param0 = [0] - self._int_param1 = [1] - self._double_param0 = [0.11] - self._double_param1 = [9.9] - self._str_param0 = ["hoge"] - self._str_param1 = ["dara"] - self._vector_param0 = [[0.0, 1.0, 2.0, 3.0, 4.0]] - - # The initialize action (on CREATED->ALIVE transition) - def onInitialize(self): - self.bindParameter("int_param0", self._int_param0, "0") - self.bindParameter("int_param1", self._int_param1, "1") - self.bindParameter("double_param0", self._double_param0, "0.11") - self.bindParameter("double_param1", self._double_param1, "9.9") - self.bindParameter("str_param0", self._str_param0, "hoge") - self.bindParameter("str_param1", self._str_param1, "dara") - self.bindParameter("vector_param0", self._vector_param0, "0.0,1.0,2.0,3.0,4.0") - self.addConfigurationParamListener(OpenRTM_aist.ConfigurationParamListenerType.ON_UPDATE_CONFIG_PARAM, - MyConfigurationParamListner()) - - print("\n Please change configuration values from RtcLink") - - return RTC.RTC_OK - - # The execution action that is invoked periodically - def onExecute(self, ec_id): - global maxlen - curlen = 0 - c = " " - - print("---------------------------------------") - print(" Active Configuration Set: ", self._configsets.getActiveId(),c) - print("---------------------------------------") - - print("int_param0: ", self._int_param0, c) - print("int_param1: ", self._int_param1, c) - print("double_param0: ", self._double_param0, c) - print("double_param1: ", self._double_param1, c) - print("str_param0: ", self._str_param0, c) - print("str_param1: ", self._str_param1, c) - - for idx in range(len(self._vector_param0[0])): - print("vector_param0[", idx, "]: ", self._vector_param0[0][idx], c) - - print("---------------------------------------") - - curlen = len(self._vector_param0[0]) - - if maxlen > curlen: - maxlen = maxlen - else: - maxlen = curlen - - for idx in range(maxlen - curlen): - print(c, c) - - print("Updating.... ", ticktack(), c) - - str_ = "" - for idx in range(12 + maxlen): - str_ += "\r" - print(str_) - - - if self._int_param0 > 1000 and self._int_param0 < 1000000: - time.sleep(self._int_param0/1000000.0) - else: - time.sleep(0.1) - - return RTC.RTC_OK + # class constructor + def __init__(self, manager): + OpenRTM_aist.DataFlowComponentBase.__init__(self, manager) + print("ConfigSample constructor.") + self._int_param0 = [0] + self._int_param1 = [1] + self._double_param0 = [0.11] + self._double_param1 = [9.9] + self._str_param0 = ["hoge"] + self._str_param1 = ["dara"] + self._vector_param0 = [[0.0, 1.0, 2.0, 3.0, 4.0]] + + # The initialize action (on CREATED->ALIVE transition) + def onInitialize(self): + self.bindParameter("int_param0", self._int_param0, "0") + self.bindParameter("int_param1", self._int_param1, "1") + self.bindParameter("double_param0", self._double_param0, "0.11") + self.bindParameter("double_param1", self._double_param1, "9.9") + self.bindParameter("str_param0", self._str_param0, "hoge") + self.bindParameter("str_param1", self._str_param1, "dara") + self.bindParameter( + "vector_param0", + self._vector_param0, + "0.0,1.0,2.0,3.0,4.0") + self.addConfigurationParamListener(OpenRTM_aist.ConfigurationParamListenerType.ON_UPDATE_CONFIG_PARAM, + MyConfigurationParamListner()) + + print("\n Please change configuration values from RtcLink") + + return RTC.RTC_OK + + # The execution action that is invoked periodically + def onExecute(self, ec_id): + global maxlen + curlen = 0 + c = " " + + print("---------------------------------------") + print(" Active Configuration Set: ", self._configsets.getActiveId(), c) + print("---------------------------------------") + + print("int_param0: ", self._int_param0, c) + print("int_param1: ", self._int_param1, c) + print("double_param0: ", self._double_param0, c) + print("double_param1: ", self._double_param1, c) + print("str_param0: ", self._str_param0, c) + print("str_param1: ", self._str_param1, c) + + for idx in range(len(self._vector_param0[0])): + print("vector_param0[", idx, "]: ", self._vector_param0[0][idx], c) + + print("---------------------------------------") + + curlen = len(self._vector_param0[0]) + + if maxlen > curlen: + maxlen = maxlen + else: + maxlen = curlen + + for idx in range(maxlen - curlen): + print(c, c) + + print("Updating.... ", ticktack(), c) + + str_ = "" + for idx in range(12 + maxlen): + str_ += "\r" + print(str_) + + if self._int_param0[0] > 1000 and self._int_param0[0] < 1000000: + time.sleep(self._int_param0[0] / 1000000.0) + else: + time.sleep(0.1) + + return RTC.RTC_OK def ConfigSampleInit(manager): - profile = OpenRTM_aist.Properties(defaults_str=configsample_spec) - manager.registerFactory(profile, - ConfigSample, - OpenRTM_aist.Delete) + profile = OpenRTM_aist.Properties(defaults_str=configsample_spec) + manager.registerFactory(profile, + ConfigSample, + OpenRTM_aist.Delete) + def MyModuleInit(manager): - ConfigSampleInit(manager) + ConfigSampleInit(manager) + + # Create a component + comp = manager.createComponent("ConfigSample") - # Create a component - comp = manager.createComponent("ConfigSample") + # Activate component + poa = manager.getPOA() + obj = comp._default_POA().servant_to_reference(comp) + rtobj = obj._narrow(RTC.RTObject) - # Activate component - poa = manager.getPOA() - obj = comp._default_POA().servant_to_reference(comp) - rtobj = obj._narrow(RTC.RTObject) + ecs = rtobj.get_owned_contexts() + ecs[0].activate_component(rtobj) - ecs = rtobj.get_owned_contexts() - ecs[0].activate_component(rtobj) - def main(): - # Initialize manager - mgr = OpenRTM_aist.Manager.init(sys.argv) + # Initialize manager + mgr = OpenRTM_aist.Manager.init(sys.argv) + + # Set module initialization proceduer + # This procedure will be invoked in activateManager() function. + mgr.setModuleInitProc(MyModuleInit) - # Set module initialization proceduer - # This procedure will be invoked in activateManager() function. - mgr.setModuleInitProc(MyModuleInit) + # Activate manager and register to naming service + mgr.activateManager() - # Activate manager and register to naming service - mgr.activateManager() + # run the manager in blocking mode + # runManager(False) is the default + mgr.runManager() - # run the manager in blocking mode - # runManager(False) is the default - mgr.runManager() + # If you want to run the manager in non-blocking mode, do like this + # mgr.runManager(True) - # If you want to run the manager in non-blocking mode, do like this - # mgr.runManager(True) if __name__ == "__main__": - main() + main() diff --git a/OpenRTM_aist/examples/ConfigSample/__init__.py b/OpenRTM_aist/examples/ConfigSample/__init__.py index 932b7982..270be2a2 100644 --- a/OpenRTM_aist/examples/ConfigSample/__init__.py +++ b/OpenRTM_aist/examples/ConfigSample/__init__.py @@ -1 +1 @@ -# Empty file +# Empty file diff --git a/OpenRTM_aist/examples/ExtTrigger/Connector.py b/OpenRTM_aist/examples/ExtTrigger/Connector.py index dc738962..685d1f80 100644 --- a/OpenRTM_aist/examples/ExtTrigger/Connector.py +++ b/OpenRTM_aist/examples/ExtTrigger/Connector.py @@ -1,4 +1,4 @@ -#!/usr/bin/env python +#!/usr/bin/env python # -*- coding: utf-8 -*- # -*- Python -*- @@ -14,89 +14,96 @@ def main(): - # subscription type - subs_type = "Flush" - - # initialization of ORB - orb = CORBA.ORB_init(sys.argv) - - # get NamingService - naming = OpenRTM_aist.CorbaNaming(orb, "localhost") - - conin = OpenRTM_aist.CorbaConsumer() - conout = OpenRTM_aist.CorbaConsumer() - - ec0 = OpenRTM_aist.CorbaConsumer(interfaceType=OpenRTM.ExtTrigExecutionContextService) - ec1 = OpenRTM_aist.CorbaConsumer(interfaceType=OpenRTM.ExtTrigExecutionContextService) - - # find ConsoleIn0 component - conin.setObject(naming.resolve("ConsoleIn0.rtc")) - - # get ports - inobj = conin.getObject()._narrow(RTC.RTObject) - pin = inobj.get_ports() - pin[0].disconnect_all() - - # activate ConsoleIn0 - eclisti = inobj.get_owned_contexts() - eclisti[0].activate_component(inobj) - ec0.setObject(eclisti[0]) - - - # find ConsoleOut0 component - conout.setObject(naming.resolve("ConsoleOut0.rtc")) - - # get ports - outobj = conout.getObject()._narrow(RTC.RTObject) - pout = outobj.get_ports() - pout[0].disconnect_all() - - # activate ConsoleOut0 - eclisto = outobj.get_owned_contexts() - eclisto[0].activate_component(outobj) - ec1.setObject(eclisto[0]) - - - # connect ports - conprof = RTC.ConnectorProfile("connector0", "", [pin[0],pout[0]], []) - OpenRTM_aist.CORBA_SeqUtil.push_back(conprof.properties, - OpenRTM_aist.NVUtil.newNV("dataport.interface_type", - "corba_cdr")) - - OpenRTM_aist.CORBA_SeqUtil.push_back(conprof.properties, - OpenRTM_aist.NVUtil.newNV("dataport.dataflow_type", - "push")) - - OpenRTM_aist.CORBA_SeqUtil.push_back(conprof.properties, - OpenRTM_aist.NVUtil.newNV("dataport.subscription_type", - subs_type)) - - ret = pin[0].connect(conprof) - - - while 1: - try: - print("\n\n") - print("0: tick ConsoleIn component") - print("1: tick ConsoleOut component") - print("2: tick both components") - print("q: exit") - print("cmd? >") - cmd = str(sys.stdin.readline()) - if cmd == "0\n": - ec0._ptr().tick() - elif cmd == "1\n": - ec1._ptr().tick() - elif cmd == "2\n": - ec0._ptr().tick() - ec1._ptr().tick() - elif cmd == "q\n": - print("exit") - break - - except: - print("Exception.") - pass + # subscription type + subs_type = "Flush" + + # initialization of ORB + manager = OpenRTM_aist.Manager.init( + sys.argv + ["-o", "manager.shutdown_auto:NO", "-o", "manager.shutdown_on_nortcs:NO"]) + manager.activateManager() + manager.runManager(True) + + orb = CORBA.ORB_init(sys.argv) + + # get NamingService + naming = OpenRTM_aist.CorbaNaming(orb, "localhost") + + conin = OpenRTM_aist.CorbaConsumer() + conout = OpenRTM_aist.CorbaConsumer() + + ec0 = OpenRTM_aist.CorbaConsumer( + interfaceType=OpenRTM.ExtTrigExecutionContextService) + ec1 = OpenRTM_aist.CorbaConsumer( + interfaceType=OpenRTM.ExtTrigExecutionContextService) + + # find ConsoleIn0 component + conin.setObject(naming.resolve("ConsoleIn0.rtc")) + + # get ports + inobj = conin.getObject()._narrow(RTC.RTObject) + pin = inobj.get_ports() + pin[0].disconnect_all() + + # activate ConsoleIn0 + eclisti = inobj.get_owned_contexts() + eclisti[0].activate_component(inobj) + ec0.setObject(eclisti[0]) + + # find ConsoleOut0 component + conout.setObject(naming.resolve("ConsoleOut0.rtc")) + + # get ports + outobj = conout.getObject()._narrow(RTC.RTObject) + pout = outobj.get_ports() + pout[0].disconnect_all() + + # activate ConsoleOut0 + eclisto = outobj.get_owned_contexts() + eclisto[0].activate_component(outobj) + ec1.setObject(eclisto[0]) + + # connect ports + conprof = RTC.ConnectorProfile("connector0", "", [pin[0], pout[0]], []) + OpenRTM_aist.CORBA_SeqUtil.push_back(conprof.properties, + OpenRTM_aist.NVUtil.newNV("dataport.interface_type", + "corba_cdr")) + + OpenRTM_aist.CORBA_SeqUtil.push_back(conprof.properties, + OpenRTM_aist.NVUtil.newNV("dataport.dataflow_type", + "push")) + + OpenRTM_aist.CORBA_SeqUtil.push_back(conprof.properties, + OpenRTM_aist.NVUtil.newNV("dataport.subscription_type", + subs_type)) + + ret = pin[0].connect(conprof) + + while True: + try: + print("\n\n") + print("0: tick ConsoleIn component") + print("1: tick ConsoleOut component") + print("2: tick both components") + print("q: exit") + print("cmd? >") + cmd = str(sys.stdin.readline()) + if cmd == "0\n": + ec0._ptr().tick() + elif cmd == "1\n": + ec1._ptr().tick() + elif cmd == "2\n": + ec0._ptr().tick() + ec1._ptr().tick() + elif cmd == "q\n": + print("exit") + break + + except BaseException: + print("Exception.") + pass + + manager.shutdown() + if __name__ == "__main__": - main() + main() diff --git a/OpenRTM_aist/examples/ExtTrigger/ConsoleIn.py b/OpenRTM_aist/examples/ExtTrigger/ConsoleIn.py index ba867869..6152fc81 100644 --- a/OpenRTM_aist/examples/ExtTrigger/ConsoleIn.py +++ b/OpenRTM_aist/examples/ExtTrigger/ConsoleIn.py @@ -1,4 +1,4 @@ -#!/usr/bin/env python +#!/usr/bin/env python # -*- coding: utf-8 -*- # -*- Python -*- @@ -9,66 +9,67 @@ import OpenRTM_aist consolein_spec = ["implementation_id", "ConsoleIn", - "type_name", "ConsoleIn", - "description", "Console input component", - "version", "1.0", - "vendor", "Shinji Kurihara", - "category", "example", - "activity_type", "DataFlowComponent", - "max_instance", "10", - "language", "Python", - "lang_type", "script", + "type_name", "ConsoleIn", + "description", "Console input component", + "version", "1.0", + "vendor", "Shinji Kurihara", + "category", "example", + "activity_type", "DataFlowComponent", + "max_instance", "10", + "language", "Python", + "lang_type", "script", ""] class ConsoleIn(OpenRTM_aist.DataFlowComponentBase): - def __init__(self, manager): - OpenRTM_aist.DataFlowComponentBase.__init__(self, manager) - return - - def onInitialize(self): - self._data = RTC.TimedLong(RTC.Time(0,0),0) - self._outport = OpenRTM_aist.OutPort("out", self._data) - # Set OutPort buffer - self.addOutPort("out", self._outport) - return RTC.RTC_OK - - def onExecute(self, ec_id): - print("> ",end="") - self._data.data = int(input()) - print("Sending to subscriber: ", self._data.data) - self._outport.write() - return RTC.RTC_OK + def __init__(self, manager): + OpenRTM_aist.DataFlowComponentBase.__init__(self, manager) + return + + def onInitialize(self): + self._data = RTC.TimedLong(RTC.Time(0, 0), 0) + self._outport = OpenRTM_aist.OutPort("out", self._data) + # Set OutPort buffer + self.addOutPort("out", self._outport) + return RTC.RTC_OK + + def onExecute(self, ec_id): + print("> ", end="") + self._data.data = int(input()) + print("Sending to subscriber: ", self._data.data) + self._outport.write() + return RTC.RTC_OK def MyModuleInit(manager): - profile = OpenRTM_aist.Properties(defaults_str=consolein_spec) - manager.registerFactory(profile, - ConsoleIn, - OpenRTM_aist.Delete) + profile = OpenRTM_aist.Properties(defaults_str=consolein_spec) + manager.registerFactory(profile, + ConsoleIn, + OpenRTM_aist.Delete) - # Create a component - comp = manager.createComponent("ConsoleIn") - return + # Create a component + comp = manager.createComponent("ConsoleIn") + return def main(): - # Initialize manager - mgr = OpenRTM_aist.Manager.init(sys.argv) - - # Set module initialization proceduer - # This procedure will be invoked in activateManager() function. - mgr.setModuleInitProc(MyModuleInit) - - # Activate manager and register to naming service - mgr.activateManager() - - # run the manager in blocking mode - # runManager(False) is the default - mgr.runManager() - - # If you want to run the manager in non-blocking mode, do like this - # mgr.runManager(True) + # Initialize manager + mgr = OpenRTM_aist.Manager.init(sys.argv) + + # Set module initialization proceduer + # This procedure will be invoked in activateManager() function. + mgr.setModuleInitProc(MyModuleInit) + + # Activate manager and register to naming service + mgr.activateManager() + + # run the manager in blocking mode + # runManager(False) is the default + mgr.runManager() + + # If you want to run the manager in non-blocking mode, do like this + # mgr.runManager(True) + if __name__ == "__main__": - main() + main() diff --git a/OpenRTM_aist/examples/ExtTrigger/ConsoleOut.py b/OpenRTM_aist/examples/ExtTrigger/ConsoleOut.py index d6d576da..67a7bf79 100644 --- a/OpenRTM_aist/examples/ExtTrigger/ConsoleOut.py +++ b/OpenRTM_aist/examples/ExtTrigger/ConsoleOut.py @@ -1,4 +1,4 @@ -#!/usr/bin/env python +#!/usr/bin/env python # -*- coding: utf-8 -*- # -*- Python -*- @@ -10,66 +10,67 @@ import OpenRTM_aist consoleout_spec = ["implementation_id", "ConsoleOut", - "type_name", "ConsoleOut", - "description", "Console output component", - "version", "1.0", - "vendor", "Shinji Kurihara", - "category", "example", - "activity_type", "DataFlowComponent", - "max_instance", "10", - "language", "Python", - "lang_type", "script", + "type_name", "ConsoleOut", + "description", "Console output component", + "version", "1.0", + "vendor", "Shinji Kurihara", + "category", "example", + "activity_type", "DataFlowComponent", + "max_instance", "10", + "language", "Python", + "lang_type", "script", ""] class ConsoleOut(OpenRTM_aist.DataFlowComponentBase): - def __init__(self, manager): - OpenRTM_aist.DataFlowComponentBase.__init__(self, manager) - return - - def onInitialize(self): - self._data = RTC.TimedLong(RTC.Time(0,0),0) - self._inport = OpenRTM_aist.InPort("in", self._data) - # Set InPort buffer - self.addInPort("in", self._inport) - return RTC.RTC_OK - - def onExecute(self, ec_id): - if self._inport.isNew(): - data = self._inport.read() - print("Received: ", data.data) - print("TimeStamp: ", data.tm.sec, "[s] ", data.tm.nsec, "[ns]") - time.sleep(0.001) - return RTC.RTC_OK + def __init__(self, manager): + OpenRTM_aist.DataFlowComponentBase.__init__(self, manager) + return + + def onInitialize(self): + self._data = RTC.TimedLong(RTC.Time(0, 0), 0) + self._inport = OpenRTM_aist.InPort("in", self._data) + # Set InPort buffer + self.addInPort("in", self._inport) + return RTC.RTC_OK + + def onExecute(self, ec_id): + if self._inport.isNew(): + data = self._inport.read() + print("Received: ", data.data) + print("TimeStamp: ", data.tm.sec, "[s] ", data.tm.nsec, "[ns]") + time.sleep(0.001) + return RTC.RTC_OK def MyModuleInit(manager): - profile = OpenRTM_aist.Properties(defaults_str=consoleout_spec) - manager.registerFactory(profile, - ConsoleOut, - OpenRTM_aist.Delete) + profile = OpenRTM_aist.Properties(defaults_str=consoleout_spec) + manager.registerFactory(profile, + ConsoleOut, + OpenRTM_aist.Delete) - # Create a component - comp = manager.createComponent("ConsoleOut") + # Create a component + comp = manager.createComponent("ConsoleOut") def main(): - # Initialize manager - mgr = OpenRTM_aist.Manager.init(sys.argv) + # Initialize manager + mgr = OpenRTM_aist.Manager.init(sys.argv) - # Set module initialization proceduer - # This procedure will be invoked in activateManager() function. - mgr.setModuleInitProc(MyModuleInit) + # Set module initialization proceduer + # This procedure will be invoked in activateManager() function. + mgr.setModuleInitProc(MyModuleInit) - # Activate manager and register to naming service - mgr.activateManager() + # Activate manager and register to naming service + mgr.activateManager() - # run the manager in blocking mode - # runManager(False) is the default - mgr.runManager() + # run the manager in blocking mode + # runManager(False) is the default + mgr.runManager() + + # If you want to run the manager in non-blocking mode, do like this + # mgr.runManager(True) - # If you want to run the manager in non-blocking mode, do like this - # mgr.runManager(True) if __name__ == "__main__": - main() + main() diff --git a/OpenRTM_aist/examples/ExtTrigger/__init__.py b/OpenRTM_aist/examples/ExtTrigger/__init__.py index 932b7982..270be2a2 100644 --- a/OpenRTM_aist/examples/ExtTrigger/__init__.py +++ b/OpenRTM_aist/examples/ExtTrigger/__init__.py @@ -1 +1 @@ -# Empty file +# Empty file diff --git a/OpenRTM_aist/examples/ExtTrigger/run.py b/OpenRTM_aist/examples/ExtTrigger/run.py index 72aca4cb..999d05d1 100644 --- a/OpenRTM_aist/examples/ExtTrigger/run.py +++ b/OpenRTM_aist/examples/ExtTrigger/run.py @@ -1,4 +1,4 @@ -#!/usr/bin/env python +#!/usr/bin/env python # -*- coding: utf-8 -*- # -*- Python -*- @@ -15,53 +15,83 @@ # from __future__ import print_function -import sys,os,platform +import sys +import os +import platform import time import subprocess -nsport="2809" +nsport = "2809" sysinfo = platform.uname() -hostname= sysinfo[1] -plat=sys.platform +hostname = sysinfo[1] +plat = sys.platform if plat == "win32": - subprocess.call("start \"\" \"%RTM_ROOT%\\bin\\rtm-naming.bat\"", shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) + subprocess.call( + "start \"\" \"%RTM_ROOT%\\bin\\rtm-naming.bat\"", + shell=True, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE) time.sleep(5) - subprocess.call("start python ConsoleIn.py", shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) - subprocess.call("start python Consoleout.py", shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) + subprocess.call( + "start python ConsoleIn.py", + shell=True, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE) + subprocess.call( + "start python Consoleout.py", + shell=True, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE) time.sleep(3) subprocess.call("python Connector.py", shell=True) else: - p=subprocess.Popen("which xterm", shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) + p = subprocess.Popen( + "which xterm", + shell=True, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE) term, stderr = p.communicate() status = p.returncode - term = term.replace("\n","") + term = term.replace("\n", "") term += " -e" if status != 0: - p=subprocess.Popen("which kterm", shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) - term, stderr = p.communicate() - status = p.returncode - term = term.replace("\n","") - term += " -e" + p = subprocess.Popen( + "which kterm", + shell=True, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE) + term, stderr = p.communicate() + status = p.returncode + term = term.replace("\n", "") + term += " -e" if status != 0: - p=subprocess.Popen("which uxterm", shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) - term, stderr = p.communicate() - status = p.returncode - term = term.replace("\n","") - term += " -e" - + p = subprocess.Popen( + "which uxterm", + shell=True, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE) + term, stderr = p.communicate() + status = p.returncode + term = term.replace("\n", "") + term += " -e" + if status != 0: - p=subprocess.Popen("which gnome-terminal", shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) - term, stderr = p.communicate() - status = p.returncode - term = term.replace("\n","") - term += " -x" + p = subprocess.Popen( + "which gnome-terminal", + shell=True, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE) + term, stderr = p.communicate() + status = p.returncode + term = term.replace("\n", "") + term += " -x" if status != 0: - print("No terminal program (kterm/xterm/gnome-terminal) exists.") - sys.exit(0) + print("No terminal program (kterm/xterm/gnome-terminal) exists.") + sys.exit(0) """ path = None @@ -75,10 +105,22 @@ os.system('python %s/rtm-naming.py &'%path) """ cmd = 'rtm-naming&' - subprocess.call(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) - cmd = '%s python ConsoleIn.py&'%term - subprocess.call(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) - cmd = '%s python ConsoleOut.py&'%term - subprocess.call(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) + subprocess.call( + cmd, + shell=True, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE) + cmd = '%s python ConsoleIn.py&' % term + subprocess.call( + cmd, + shell=True, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE) + cmd = '%s python ConsoleOut.py&' % term + subprocess.call( + cmd, + shell=True, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE) time.sleep(3) subprocess.call("python Connector.py", shell=True) diff --git a/OpenRTM_aist/examples/MobileRobotCanvas/TkMobileRobotSimulator.py b/OpenRTM_aist/examples/MobileRobotCanvas/TkMobileRobotSimulator.py index b3fb87d7..56b00edf 100644 --- a/OpenRTM_aist/examples/MobileRobotCanvas/TkMobileRobotSimulator.py +++ b/OpenRTM_aist/examples/MobileRobotCanvas/TkMobileRobotSimulator.py @@ -1,4 +1,4 @@ -#!/usr/bin/env python +#!/usr/bin/env python # -*- coding: utf-8 -*- # -*- Python -*- @@ -21,947 +21,922 @@ # #from Tkinter import * +import OpenRTM_aist +import RTC +import math +import time import sys if sys.version_info[0] == 2: - from Tix import * + from Tix import * else: - from tkinter.tix import * -import time -import math + from tkinter.tix import * # Import RTM module -import RTC -import OpenRTM_aist # This module's spesification # -tkmobilerobotsimulator_spec = ["implementation_id", "TkMobileRobotSimulator", - "type_name", "TkMobileRobotSimulator", - "description", "sample component for Python and Tkinter", - "version", "1.0", - "vendor", "Noriaki Ando, AIST", - "category", "example", - "activity_type", "DataFlowComponent", - "max_instance", "10", - "language", "Python", - "lang_type", "SCRIPT", +tkmobilerobotsimulator_spec = ["implementation_id", "TkMobileRobotSimulator", + "type_name", "TkMobileRobotSimulator", + "description", "sample component for Python and Tkinter", + "version", "1.0", + "vendor", "Noriaki Ando, AIST", + "category", "example", + "activity_type", "DataFlowComponent", + "max_instance", "10", + "language", "Python", + "lang_type", "SCRIPT", ""] # class TkMobileRobotSimulator(OpenRTM_aist.DataFlowComponentBase): - def __init__(self, manager): - OpenRTM_aist.DataFlowComponentBase.__init__(self, manager) - - self.pos = [] - self.vel = [] - return + def __init__(self, manager): + OpenRTM_aist.DataFlowComponentBase.__init__(self, manager) - def onInitialize(self): - self._d_vel = RTC.TimedFloatSeq(RTC.Time(0,0),[]) - self._velIn = OpenRTM_aist.InPort("vel", self._d_vel) - - self._d_pos = RTC.TimedFloatSeq(RTC.Time(0,0),[]) - self._posOut = OpenRTM_aist.OutPort("pos", self._d_pos) - - # Set InPort buffers - self.addInPort("vel",self._velIn) - self.addOutPort("pos",self._posOut) + self.pos = [] + self.vel = [] + return - # Bind variables and configuration variable - return RTC.RTC_OK + def onInitialize(self): + self._d_vel = RTC.TimedFloatSeq(RTC.Time(0, 0), []) + self._velIn = OpenRTM_aist.InPort("vel", self._d_vel) - def onShutdown(self, ec_id): - return RTC.RTC_OK + self._d_pos = RTC.TimedFloatSeq(RTC.Time(0, 0), []) + self._posOut = OpenRTM_aist.OutPort("pos", self._d_pos) - def onDeactivated(self, ec_id): - self.pos = [] - self.vel = [] - return RTC.RTC_OK + # Set InPort buffers + self.addInPort("vel", self._velIn) + self.addOutPort("pos", self._posOut) - def onExecute(self, ec_id): - if self._velIn.isNew(): - self.vel = self._velIn.read().data - self._d_pos.data = self.pos - self._posOut.write() - time.sleep(0.01) - return RTC.RTC_OK + # Bind variables and configuration variable + return RTC.RTC_OK - def get_velocity(self): - return self.vel + def onShutdown(self, ec_id): + return RTC.RTC_OK - def set_position(self, pos): - self.pos = pos + def onDeactivated(self, ec_id): + self.pos = [] + self.vel = [] + return RTC.RTC_OK + def onExecute(self, ec_id): + if self._velIn.isNew(): + self.vel = self._velIn.read().data + self._d_pos.data = self.pos + self._posOut.write() + time.sleep(0.01) + return RTC.RTC_OK -class ToggleItem: - def __init__(self): - self.active = True - return + def get_velocity(self): + return self.vel - def __del__(self): - self.delete() - return + def set_position(self, pos): + self.pos = pos - def activate(self): - self.active = True - self.draw() - return - def deactivate(self): - self.active = False - self.delete() - return +class ToggleItem: + def __init__(self): + self.active = True + return - def toggle(self): - if self.active: - self.deactivate() - else: - self.activate() - return + def __del__(self): + self.delete() + return -class CanvasText(ToggleItem): - def __init__(self, canvas, text, x, y): - ToggleItem.__init__(self) - self.canvas = canvas - self.id = self.canvas.create_text(x, y, text=text) - self.text = text - self.x = x - self.y = y - self.draw_text(x, y, text) - return + def activate(self): + self.active = True + self.draw() + return - def draw(self): - if self.active == False: return - self.delete() - self.id = self.canvas.create_text(self.x, self.y, text=self.text) - return + def deactivate(self): + self.active = False + self.delete() + return - def draw_text(self, x, y, text): - self.x = x - self.y = y - self.text = text - self.draw() - return - - def delete(self): - self.canvas.delete(self.id) - return + def toggle(self): + if self.active: + self.deactivate() + else: + self.activate() + return -class RobotTitle(ToggleItem): - def __init__(self, simulator, robot, name, r): - ToggleItem.__init__(self) - self.canvas = simulator.get_canvas() - self.trans = simulator.get_translation() - self.robot = robot - self.name = name - self.r = r - self.id_circle = None - self.id_line0 = None - self.id_line1 = None - self.id_name = None - self.id_pos = None - self.llength = 50 - return - def draw(self): - if self.active == False: return - self.delete() - rx, ry, rt = self.robot.get_pos() - - tmp_x0 = - self.r - tmp_y0 = - self.r - tmp_x1 = self.r - tmp_y1 = self.r - x0, y0 = self.trans(tmp_x0, tmp_y0, rx, ry, 0) - x1, y1 = self.trans(tmp_x1, tmp_y1, rx, ry, 0) - - self.id_circle = self.canvas.create_oval(x0, y0, x1, y1, - width=2, - fill="", outline="#aaaaaa") - r = (x1 - x0)/2 - xo = x0 + r - yo = y0 - r - - lx0 = xo + (r / math.sqrt(2)) - ly0 = yo - (r / math.sqrt(2)) - lx1 = lx0 + self.llength - ly1 = ly0 - self.llength - - self.id_line0 = self.canvas.create_line(lx0, ly0, lx1, ly1, - fill="#777777") - self.id_line1 = self.canvas.create_line(lx1, ly1, lx1 + 120, ly1, - fill="#777777") - self.id_name = self.canvas.create_text(lx1+120, ly1-8, - anchor=E, text=self.name) - pos_text = '(%5.2f, %5.2f, %5.2f)' % (rx, ry, (rt*180/math.pi)%360) - self.id_pos = self.canvas.create_text(lx1+120, ly1+8, - anchor=E, text=pos_text) - return +class CanvasText(ToggleItem): + def __init__(self, canvas, text, x, y): + ToggleItem.__init__(self) + self.canvas = canvas + self.id = self.canvas.create_text(x, y, text=text) + self.text = text + self.x = x + self.y = y + self.draw_text(x, y, text) + return + + def draw(self): + if self.active == False: + return + self.delete() + self.id = self.canvas.create_text(self.x, self.y, text=self.text) + return + + def draw_text(self, x, y, text): + self.x = x + self.y = y + self.text = text + self.draw() + return + + def delete(self): + self.canvas.delete(self.id) + return - def delete(self): - if self.id_circle != None: - self.canvas.delete(self.id_circle) - if self.id_line0 != None: - self.canvas.delete(self.id_line0) - if self.id_line1 != None: - self.canvas.delete(self.id_line1) - if self.id_name != None: - self.canvas.delete(self.id_name) - if self.id_pos != None: - self.canvas.delete(self.id_pos) - return +class RobotTitle(ToggleItem): + def __init__(self, simulator, robot, name, r): + ToggleItem.__init__(self) + self.canvas = simulator.get_canvas() + self.trans = simulator.get_translation() + self.robot = robot + self.name = name + self.r = r + self.id_circle = None + self.id_line0 = None + self.id_line1 = None + self.id_name = None + self.id_pos = None + self.llength = 50 + return + + def draw(self): + if self.active == False: + return + self.delete() + rx, ry, rt = self.robot.get_pos() + + tmp_x0 = - self.r + tmp_y0 = - self.r + tmp_x1 = self.r + tmp_y1 = self.r + x0, y0 = self.trans(tmp_x0, tmp_y0, rx, ry, 0) + x1, y1 = self.trans(tmp_x1, tmp_y1, rx, ry, 0) + + self.id_circle = self.canvas.create_oval(x0, y0, x1, y1, + width=2, + fill="", outline="#aaaaaa") + r = (x1 - x0) / 2 + xo = x0 + r + yo = y0 - r + + lx0 = xo + (r / math.sqrt(2)) + ly0 = yo - (r / math.sqrt(2)) + lx1 = lx0 + self.llength + ly1 = ly0 - self.llength + + self.id_line0 = self.canvas.create_line(lx0, ly0, lx1, ly1, + fill="#777777") + self.id_line1 = self.canvas.create_line(lx1, ly1, lx1 + 120, ly1, + fill="#777777") + self.id_name = self.canvas.create_text(lx1 + 120, ly1 - 8, + anchor=E, text=self.name) + pos_text = '(%5.2f, %5.2f, %5.2f)' % ( + rx, ry, (rt * 180 / math.pi) % 360) + self.id_pos = self.canvas.create_text(lx1 + 120, ly1 + 8, + anchor=E, text=pos_text) + return + + def delete(self): + if self.id_circle is not None: + self.canvas.delete(self.id_circle) + if self.id_line0 is not None: + self.canvas.delete(self.id_line0) + if self.id_line1 is not None: + self.canvas.delete(self.id_line1) + if self.id_name is not None: + self.canvas.delete(self.id_name) + if self.id_pos is not None: + self.canvas.delete(self.id_pos) + return class CanvasGrid(ToggleItem): - def __init__(self, canvas, x0, y0, width, height, pitch, color, linewd): - ToggleItem.__init__(self) - self.canvas = canvas - self.x0 = x0 - self.y0 = y0 - self.width = width - self.height = height - self.pitch = pitch - self.color = color - self.linewd = linewd - self.idx = [] - self.idy = [] - - self.draw() - return - - - def draw(self): - if self.active == False: return - self.delete() - - x_start = int(self.x0 % self.pitch) - x_num = int((self.width - x_start) / self.pitch) + 1 - for x in range(x_num): - x0 = x_start + self.pitch * x - id = self.canvas.create_line(x0, 0, x0, self.height, - fill=self.color, width=self.linewd) - self.idx.append(id) - - y_start = int(self.y0 % self.pitch) - y_num = int((self.height - y_start) / self.pitch) + 1 - for y in range(y_num): - y0 = y_start + self.pitch * y - id = self.canvas.create_line(0, y0, self.width, y0, - fill=self.color, width=self.linewd) - self.idy.append(id) - - for i in self.idx: - self.canvas.tag_lower(i) - for i in self.idy: - self.canvas.tag_lower(i) - return - - - def delete(self): - for i in self.idx: - self.canvas.delete(i) - for i in self.idy: - self.canvas.delete(i) - return - - - def set_pitch(self, pitch): - self.pitch = pitch - self.draw() - return + def __init__(self, canvas, x0, y0, width, height, pitch, color, linewd): + ToggleItem.__init__(self) + self.canvas = canvas + self.x0 = x0 + self.y0 = y0 + self.width = width + self.height = height + self.pitch = pitch + self.color = color + self.linewd = linewd + self.idx = [] + self.idy = [] + + self.draw() + return + + def draw(self): + if self.active == False: + return + self.delete() + + x_start = int(self.x0 % self.pitch) + x_num = int((self.width - x_start) / self.pitch) + 1 + for x in range(x_num): + x0 = x_start + self.pitch * x + id = self.canvas.create_line(x0, 0, x0, self.height, + fill=self.color, width=self.linewd) + self.idx.append(id) + + y_start = int(self.y0 % self.pitch) + y_num = int((self.height - y_start) / self.pitch) + 1 + for y in range(y_num): + y0 = y_start + self.pitch * y + id = self.canvas.create_line(0, y0, self.width, y0, + fill=self.color, width=self.linewd) + self.idy.append(id) + + for i in self.idx: + self.canvas.tag_lower(i) + for i in self.idy: + self.canvas.tag_lower(i) + return + + def delete(self): + for i in self.idx: + self.canvas.delete(i) + for i in self.idy: + self.canvas.delete(i) + return + + def set_pitch(self, pitch): + self.pitch = pitch + self.draw() + return class CanvasAxis(ToggleItem): - def __init__(self, canvas, width, height): - ToggleItem.__init__(self) - self.x0 = width/2 - self.y0 = height/2 - self.width = width - self.height = height - self.canvas = canvas - self.id = [None] * 4 - self.draw() - return - - - def draw(self): - if self.active == False: return - self.delete() - self.id[0] = self.canvas.create_line(0, self.height/2, - self.width, self.height/2) - self.id[1] = self.canvas.create_text(self.width - 10, - self.height/2 + 10, - text="x") - self.id[2] = self.canvas.create_line(self.width/2, 0, - self.width/2, self.height) - self.id[3] = self.canvas.create_text(self.width/2 + 10, - + 10, text="y") - - return - - def delete(self): - for i in self.id: - self.canvas.delete(i) - return - + def __init__(self, canvas, width, height): + ToggleItem.__init__(self) + self.x0 = width / 2 + self.y0 = height / 2 + self.width = width + self.height = height + self.canvas = canvas + self.id = [None] * 4 + self.draw() + return + + def draw(self): + if self.active == False: + return + self.delete() + self.id[0] = self.canvas.create_line(0, self.height / 2, + self.width, self.height / 2) + self.id[1] = self.canvas.create_text(self.width - 10, + self.height / 2 + 10, + text="x") + self.id[2] = self.canvas.create_line(self.width / 2, 0, + self.width / 2, self.height) + self.id[3] = self.canvas.create_text(self.width / 2 + 10, + + 10, text="y") + + return + + def delete(self): + for i in self.id: + self.canvas.delete(i) + return class SimulatedObject: - def __init__(self, simulator): - self.simulator = simulator - self.tick = simulator.get_tick() - self.canvas = simulator.get_canvas() - self.trans = simulator.get_translation() - return + def __init__(self, simulator): + self.simulator = simulator + self.tick = simulator.get_tick() + self.canvas = simulator.get_canvas() + self.trans = simulator.get_translation() + return - def translate(self, x, y, dx, dy, dth): - return self.trans(x, y, dx, dy, dth) + def translate(self, x, y, dx, dy, dth): + return self.trans(x, y, dx, dy, dth) - def get_tick(self): - return self.simulator.get_tick() + def get_tick(self): + return self.simulator.get_tick() if sys.version_info[0] == 2: - import tkSimpleDialog + import tkSimpleDialog else: - import tkinter.simpledialog as tkSimpleDialog - -class PropertyDialog: - def __init__(self): - # robot's profile - self.name = "" - self.type = "" - self.description = "" - self.vendor = "" - # robot's parameter/input/output - self.param = [] - self.input = [] - self.output = [] - # max length of label text - self.label_len = 0 - # max length of unit text - self.unit_len = 0 - - self.apply_param = None - self.apply_input = None - self.reset_output = None - return + import tkinter.simpledialog as tkSimpleDialog - def set_profile(self, name, type, description, vendor): - self.name = name - self.type = type - self.description = description - self.vendor =vendor - return - - def append_parameter(self, label, variable, unit): - self.param.append({"label":label, "var":variable, "unit":unit}) - self.label_len = max(len(label), self.label_len) - self.unit_len = max(len(unit), self.unit_len) - return - - def append_input(self, label, variable, unit): - self.input.append({"label":label, "var":variable, "unit":unit}) - self.label_len = max(len(label), self.label_len) - self.unit_len = max(len(unit), self.unit_len) - return - - def append_output(self, label, variable, unit): - self.output.append({"label":label, "var":variable, "unit":unit}) - self.label_len = max(len(label), self.label_len) - self.unit_len = max(len(unit), self.unit_len) - return - - def set_apply_param(self, func): - self.apply_param = func - return - - def set_apply_input(self, func): - self.apply_input = func - return - - def set_reset_output(self, func): - self.reset_output = func - return - - def pack(self): - f = Toplevel() - self.toplevel = f - f.title(self.name) - w0 = LabelFrame(f, label="Robot's Profile", - options="frame.anchor w frame.justify left") - prof_frame = w0.subwidget('frame') - self.profile_label(prof_frame) - - w1 = LabelFrame(f, label="Robot's Parameters") - param_frame = w1.subwidget('frame') - self.label_entries(param_frame, self.param) - if self.apply_param != None: - self.button(param_frame, "Apply", self.apply_param) - - w2 = LabelFrame(f, label="Robot's Input Values") - input_frame = w2.subwidget('frame') - self.label_entries(input_frame, self.input) - if self.apply_input != None: - self.button(input_frame, "Set", self.apply_input) - - w3 = LabelFrame(f, label="Robot's Output Values") - output_frame = w3.subwidget('frame') - self.label_entries(output_frame, self.output) - if self.reset_output != None: - self.button(output_frame, "Reset", self.reset_output) - - - for w in [w0, w1, w2, w3]: - w.pack(side=TOP, anchor=W, fill=X) - self.button(f, "OK", self.on_ok) - - return - - def on_ok(self): - self.toplevel.destroy() - return - - - def button(self, master, label, func): - bt = Button(master, text=label, command=func, width=10, - padx=3, pady=3) - bt.pack(side=TOP, padx=5, pady=5) - return - - - def profile_label(self, master): - t = ["Robot's name: ", "Robot's type: ", "Description: ", "Vendor: "] - for i in range(len(t)): - Label(master, text=t[i], anchor=W).grid(row=i, sticky=W, - padx=3, pady=3) - l = [self.name, self.type, self.description, self.vendor] - for i in range(len(l)): - Label(master, text=l[i], anchor=W).grid(row=i, column=1, sticky=W, - padx=3, pady=3) - return - - - def label_entry(self, master, label0, var, label1): - f = Frame(master) - l0 = Label(f, text=label0, width=self.label_len, justify=LEFT, anchor=W) - e = Entry(f, width=7, textvariable=var, - justify=RIGHT, relief=GROOVE, bd=2) - l1 = Label(f, text=label1, width=self.unit_len, justify=LEFT, anchor=W) - for w in [l0, e, l1]: - w.pack(side=LEFT, anchor=W, padx=3, pady=3) - return f - - def label_entries(self, f, props): - for p in props: - self.label_entry(f, p["label"], p["var"], p["unit"]).pack(side=TOP) - return +class PropertyDialog: + def __init__(self): + # robot's profile + self.name = "" + self.type = "" + self.description = "" + self.vendor = "" + # robot's parameter/input/output + self.param = [] + self.input = [] + self.output = [] + # max length of label text + self.label_len = 0 + # max length of unit text + self.unit_len = 0 + + self.apply_param = None + self.apply_input = None + self.reset_output = None + return + + def set_profile(self, name, type, description, vendor): + self.name = name + self.type = type + self.description = description + self.vendor = vendor + return + + def append_parameter(self, label, variable, unit): + self.param.append({"label": label, "var": variable, "unit": unit}) + self.label_len = max(len(label), self.label_len) + self.unit_len = max(len(unit), self.unit_len) + return + + def append_input(self, label, variable, unit): + self.input.append({"label": label, "var": variable, "unit": unit}) + self.label_len = max(len(label), self.label_len) + self.unit_len = max(len(unit), self.unit_len) + return + + def append_output(self, label, variable, unit): + self.output.append({"label": label, "var": variable, "unit": unit}) + self.label_len = max(len(label), self.label_len) + self.unit_len = max(len(unit), self.unit_len) + return + + def set_apply_param(self, func): + self.apply_param = func + return + + def set_apply_input(self, func): + self.apply_input = func + return + + def set_reset_output(self, func): + self.reset_output = func + return + + def pack(self): + f = Toplevel() + self.toplevel = f + f.title(self.name) + w0 = LabelFrame(f, label="Robot's Profile", + options="frame.anchor w frame.justify left") + prof_frame = w0.subwidget('frame') + self.profile_label(prof_frame) + + w1 = LabelFrame(f, label="Robot's Parameters") + param_frame = w1.subwidget('frame') + self.label_entries(param_frame, self.param) + if self.apply_param is not None: + self.button(param_frame, "Apply", self.apply_param) + + w2 = LabelFrame(f, label="Robot's Input Values") + input_frame = w2.subwidget('frame') + self.label_entries(input_frame, self.input) + if self.apply_input is not None: + self.button(input_frame, "Set", self.apply_input) + + w3 = LabelFrame(f, label="Robot's Output Values") + output_frame = w3.subwidget('frame') + self.label_entries(output_frame, self.output) + if self.reset_output is not None: + self.button(output_frame, "Reset", self.reset_output) + + for w in [w0, w1, w2, w3]: + w.pack(side=TOP, anchor=W, fill=X) + self.button(f, "OK", self.on_ok) + + return + + def on_ok(self): + self.toplevel.destroy() + return + + def button(self, main, label, func): + bt = Button(main, text=label, command=func, width=10, + padx=3, pady=3) + bt.pack(side=TOP, padx=5, pady=5) + return + + def profile_label(self, main): + t = ["Robot's name: ", "Robot's type: ", "Description: ", "Vendor: "] + for i in range(len(t)): + Label(main, text=t[i], anchor=W).grid(row=i, sticky=W, + padx=3, pady=3) + l = [self.name, self.type, self.description, self.vendor] + for i in range(len(l)): + Label(main, text=l[i], anchor=W).grid(row=i, column=1, sticky=W, + padx=3, pady=3) + return + + def label_entry(self, main, label0, var, label1): + f = Frame(main) + l0 = Label( + f, + text=label0, + width=self.label_len, + justify=LEFT, + anchor=W) + e = Entry(f, width=7, textvariable=var, + justify=RIGHT, relief=GROOVE, bd=2) + l1 = Label(f, text=label1, width=self.unit_len, justify=LEFT, anchor=W) + for w in [l0, e, l1]: + w.pack(side=LEFT, anchor=W, padx=3, pady=3) + return f + + def label_entries(self, f, props): + for p in props: + self.label_entry(f, p["label"], p["var"], p["unit"]).pack(side=TOP) + return class DiffMobileModel: - def __init__(self, radius, wheeld, pos = (0, 0, math.pi/2), dt=0.1): - self.radius = radius - self.wheeld = wheeld - self.dt = dt - self.pre_x = pos[0] - self.pre_y = pos[1] - self.pre_t = pos[2] - self.pre_x_dot = 0 - self.pre_y_dot = 0 - self.pre_t_dot = 0 - return - - - def set_wheel_radius(self, radius): - # wheel radius [m] - self.radius = radius - return - - - def set_wheel_distance(self, distance): - # distance between wheels [m] - self.wheeld = distance - return - - - def set_time_tick(self, tick): - # time tick for simulation [sec] - self.dt = tick - return - - - def set_pos(self, pos = (0, 0, math.pi/2)): - # x: pos[0] [m] - # y: pos[1] [m] - # theta: pos[2] [rad] - self.pre_x = pos[0] - self.pre_y = pos[1] - self.pre_t = pos[2] - return - - - def get_pos(self): - return self.pre_x, self.pre_y, self.pre_t - - def control(self, w1, w2): - # w1: [rad/s] - # w2: [rad/s] - x_dot = self.radius * (w1 + w2) * math.cos(self.pre_t) - y_dot = self.radius * (w1 + w2) * math.sin(self.pre_t) - t_dot = self.radius * (-w1 + w2) / self.wheeld - - x = (self.dt * (self.pre_x_dot + x_dot) / 2) + self.pre_x - y = (self.dt * (self.pre_y_dot + y_dot) / 2) + self.pre_y - theta = (self.dt * (self.pre_t_dot + t_dot) / 2) + self.pre_t - - self.pre_x = x - self.pre_y = y - self.pre_t = theta - - self.pre_x_dot = x_dot - self.pre_y_dot = y_dot - self.pre_t_dot = t_dot - - return x, y, theta - + def __init__(self, radius, wheeld, pos=(0, 0, math.pi / 2), dt=0.1): + self.radius = radius + self.wheeld = wheeld + self.dt = dt + self.pre_x = pos[0] + self.pre_y = pos[1] + self.pre_t = pos[2] + self.pre_x_dot = 0 + self.pre_y_dot = 0 + self.pre_t_dot = 0 + return + + def set_wheel_radius(self, radius): + # wheel radius [m] + self.radius = radius + return + + def set_wheel_distance(self, distance): + # distance between wheels [m] + self.wheeld = distance + return + + def set_time_tick(self, tick): + # time tick for simulation [sec] + self.dt = tick + return + + def set_pos(self, pos=(0, 0, math.pi / 2)): + # x: pos[0] [m] + # y: pos[1] [m] + # theta: pos[2] [rad] + self.pre_x = pos[0] + self.pre_y = pos[1] + self.pre_t = pos[2] + return + + def get_pos(self): + return self.pre_x, self.pre_y, self.pre_t + + def control(self, w1, w2): + # w1: [rad/s] + # w2: [rad/s] + x_dot = self.radius * (w1 + w2) * math.cos(self.pre_t) + y_dot = self.radius * (w1 + w2) * math.sin(self.pre_t) + t_dot = self.radius * (-w1 + w2) / self.wheeld + + x = (self.dt * (self.pre_x_dot + x_dot) / 2) + self.pre_x + y = (self.dt * (self.pre_y_dot + y_dot) / 2) + self.pre_y + theta = (self.dt * (self.pre_t_dot + t_dot) / 2) + self.pre_t + + self.pre_x = x + self.pre_y = y + self.pre_t = theta + + self.pre_x_dot = x_dot + self.pre_y_dot = y_dot + self.pre_t_dot = t_dot + + return x, y, theta class DDMobileRobot(SimulatedObject): - count = 0 - def __init__(self, simulator, radius=2, wheeld=20, - pos = (0, 0, math.pi/2)): - SimulatedObject.__init__(self, simulator) - self.tick = self.get_tick() - self.model = DiffMobileModel(radius, wheeld, pos, self.tick) - self.fig = [[10, 0], [5, 10], [-10, 10], [-10, -10], [5, -10]] - self.id = None - self.wl = 0.0 - self.wr = 0.0 - self.name = "DDMobileRobot" + str(self.__class__.count) - self.__class__.count += 1 - self.comp = OpenRTM_aist.Manager.instance().createComponent("TkMobileRobotSimulator") - - # properties - self.rentry = StringVar() - self.rentry.set(radius) - self.dentry = StringVar() - self.dentry.set(wheeld) - # input variables - self.wlentry = StringVar() - self.wrentry = StringVar() - # output variables - self.xentry = StringVar() - self.yentry = StringVar() - self.tentry = StringVar() - return - - - def __del__(self): - try: - self.comp.exit() - del self.comp - except: - pass - self.delete() - return - - - def get_name(self): - return self.name - - - def set_pos(self, x, y, th): - self.model.set_pos((x, y, th)) - return - - - def get_pos(self): - return self.model.get_pos() - - - def set_wheel_velocity(self, wl, wr): - self.wl = wl - self.wr = wr - self.wlentry.set('%5.2f'%self.wl) - self.wrentry.set('%5.2f'%self.wr) - return - - - def on_update(self): - self.model.set_time_tick(self.get_tick()) - v = self.comp.get_velocity() - if len(v) == 2: - self.set_wheel_velocity(v[0], v[1]) - self.x, self.y, self.th = self.model.control(self.wl, self.wr) - self.th_deg = (self.th * 180 / math.pi) % 360 - self.comp.set_position((self.x, self.y, self.th_deg)) - self.xentry.set('%5.2f'%self.x) - self.yentry.set('%5.2f'%self.y) - self.tentry.set('%5.2f'%self.th_deg) - self.draw() - return - - - def draw(self): - # converting actual coordinate system into display coordinate - # system, and drawing figures - robotfig = [] - for pos in self.fig: - robotfig.append(self.translate(pos[0], pos[1], - self.x, self.y, self.th)) - if self.id != None: - self.canvas.delete(self.id) - self.id = self.canvas.create_polygon(robotfig, - fill="#00aa00", - outline="#eeeeee") - return - - - def delete(self): - if self.id != None: - self.canvas.delete(self.id) - return - - - def property_page(self): - p = PropertyDialog() - p.set_profile(self.name, "DDMobileRobot", - "Differential Drive Mobile Robot", "AIST") - p.append_parameter("Wheel radius r: ", self.rentry, "[m]") - p.append_parameter("Wheel distance d: ", self.dentry, "[m]") - p.append_input("Angular velocity (LEFT) wl: ", self.wlentry, "[rad/s]") - p.append_input("Angular velocity (RIGHT) wr: ", self.wrentry, "[rad/s]") - p.append_output("Robot position x : ", self.xentry, "[m]") - p.append_output("Robot position y : ", self.yentry, "[m]") - p.append_output("Robot position th: ", self.tentry, "[deg]") - p.set_apply_param(self.on_apply_param) - p.set_apply_input(self.on_apply_input) - p.set_reset_output(self.on_reset_output) - p.pack() - return - - - def on_reset_output(self): - self.set_pos(0.0, 0.0, math.pi/2) - return - - - def on_apply_param(self): - r = float(self.rentry.get()) - d = float(self.dentry.get()) - self.model.set_wheel_radius(r) - self.model.set_wheel_distance(d) - return - - - def on_apply_input(self): - self.wl = float(self.wlentry.get()) - self.wr = float(self.wrentry.get()) - return - - + count = 0 + + def __init__(self, simulator, radius=2, wheeld=20, + pos=(0, 0, math.pi / 2)): + SimulatedObject.__init__(self, simulator) + self.tick = self.get_tick() + self.model = DiffMobileModel(radius, wheeld, pos, self.tick) + self.fig = [[10, 0], [5, 10], [-10, 10], [-10, -10], [5, -10]] + self.id = None + self.wl = 0.0 + self.wr = 0.0 + self.name = "DDMobileRobot" + str(self.__class__.count) + self.__class__.count += 1 + self.comp = OpenRTM_aist.Manager.instance( + ).createComponent("TkMobileRobotSimulator") + + # properties + self.rentry = StringVar() + self.rentry.set(radius) + self.dentry = StringVar() + self.dentry.set(wheeld) + # input variables + self.wlentry = StringVar() + self.wrentry = StringVar() + # output variables + self.xentry = StringVar() + self.yentry = StringVar() + self.tentry = StringVar() + return + + def __del__(self): + try: + self.comp.exit() + del self.comp + except BaseException: + pass + self.delete() + return + + def get_name(self): + return self.name + + def set_pos(self, x, y, th): + self.model.set_pos((x, y, th)) + return + + def get_pos(self): + return self.model.get_pos() + + def set_wheel_velocity(self, wl, wr): + self.wl = wl + self.wr = wr + self.wlentry.set('%5.2f' % self.wl) + self.wrentry.set('%5.2f' % self.wr) + return + + def on_update(self): + self.model.set_time_tick(self.get_tick()) + v = self.comp.get_velocity() + if len(v) == 2: + self.set_wheel_velocity(v[0], v[1]) + self.x, self.y, self.th = self.model.control(self.wl, self.wr) + self.th_deg = (self.th * 180 / math.pi) % 360 + self.comp.set_position((self.x, self.y, self.th_deg)) + self.xentry.set('%5.2f' % self.x) + self.yentry.set('%5.2f' % self.y) + self.tentry.set('%5.2f' % self.th_deg) + self.draw() + return + + def draw(self): + # converting actual coordinate system into display coordinate + # system, and drawing figures + robotfig = [] + for pos in self.fig: + robotfig.append(self.translate(pos[0], pos[1], + self.x, self.y, self.th)) + if self.id is not None: + self.canvas.delete(self.id) + self.id = self.canvas.create_polygon(robotfig, + fill="#00aa00", + outline="#eeeeee") + return + + def delete(self): + if self.id is not None: + self.canvas.delete(self.id) + return + + def property_page(self): + p = PropertyDialog() + p.set_profile(self.name, "DDMobileRobot", + "Differential Drive Mobile Robot", "AIST") + p.append_parameter("Wheel radius r: ", self.rentry, "[m]") + p.append_parameter("Wheel distance d: ", self.dentry, "[m]") + p.append_input( + "Angular velocity (LEFT) wl: ", + self.wlentry, + "[rad/s]") + p.append_input( + "Angular velocity (RIGHT) wr: ", + self.wrentry, + "[rad/s]") + p.append_output("Robot position x : ", self.xentry, "[m]") + p.append_output("Robot position y : ", self.yentry, "[m]") + p.append_output("Robot position th: ", self.tentry, "[deg]") + p.set_apply_param(self.on_apply_param) + p.set_apply_input(self.on_apply_input) + p.set_reset_output(self.on_reset_output) + p.pack() + return + + def on_reset_output(self): + self.set_pos(0.0, 0.0, math.pi / 2) + return + + def on_apply_param(self): + r = float(self.rentry.get()) + d = float(self.dentry.get()) + self.model.set_wheel_radius(r) + self.model.set_wheel_distance(d) + return + + def on_apply_input(self): + self.wl = float(self.wlentry.get()) + self.wr = float(self.wrentry.get()) + return class TkMobileRobot(Frame): - def __init__(self, master=None, width=800, height=600): - Frame.__init__(self, master) - - # canvas properties - self.width = width - self.height = height - # zero of canvas - self.x0 = width/2 - self.y0 = height/2 - - self.wd = 150 - - self.robots = {} - - self.robot = None - self.postext = None - - self.scale = 1.0 - self.scale_var = DoubleVar() - self.scale_var.set(self.scale) - - self.grid_pitch = 50 - - self.tick = 0.1 - self.default_tick = 0.1 - self.tickscale_var = DoubleVar() - self.tickscale_var.set(self.tick) - - self.axis_check = StringVar() - self.axis_check.set("on") - self.grid_check = StringVar() - self.grid_check.set("on") - self.rname_check = StringVar() - self.rname_check.set("on") - self.rnames = {} - - self.robot_kind_var = StringVar() - self.robot_factory = {"DDMobileRobot": DDMobileRobot} - - - - self.init() - self.pack() - - - self.after(20, self.on_update) - return - - def init(self): - self.canvas = Canvas(self, bg="#eeeeee", - width = self.width, height = self.height) - self.canvas.pack(side=LEFT) - - self.can_grid = CanvasGrid(self.canvas, self.x0, self.y0, - self.width, self.height, self.grid_pitch, - "#aaaaaa", 1) - self.can_axis = CanvasAxis(self.canvas, self.width, self.height) - - self.frame = Frame(self) - self.frame.pack(side=LEFT) - - # Screen control - self.scrctrl_frame = Frame(self.frame, width=self.wd, height=300, - relief=GROOVE, bd=2) - self.scrctrl_frame.pack(side=TOP, fill=X) - self.create_scale(self.scrctrl_frame) - self.create_checkbutton(self.scrctrl_frame) - - # Robot manager - self.robomgr_frame = Frame(self.frame, width=self.wd, height=300, - relief=GROOVE, bd=2) - self.robomgr_frame.pack(side=TOP) - self.create_robotcreator(self.robomgr_frame) - self.create_robotlist(self.robomgr_frame) - return - - - def on_update(self): - for o in self.robots.keys(): - self.robots[o].on_update() - for r in self.rnames.keys(): - self.rnames[r].draw() - self.after(20, self.on_update) - return - - - def get_tick(self): - return self.tick - - - def get_canvas(self): - return self.canvas - - - def get_translation(self): - return self.real_to_canvas - - - #------------------------------------------------------------ - # Scale control set - def create_scale(self, frame): - dummy = Frame(frame, width=self.wd) - dummy.pack(side=TOP) - sl = Scale(frame, from_=0, to=10, resolution=0.01, - label="Scale Factor", command=self.on_scale, - variable=self.scale_var, orient=HORIZONTAL) - bt = Button(frame, text="Reset Scale", command=self.reset_scale) - sl.pack(side=TOP, fill=X) - bt.pack(side=TOP, fill=X) - - sl = Scale(frame, from_=0.001, to=1, resolution=0.001, - label="Time tick [s]", command=self.on_tickchange, - variable=self.tickscale_var, orient=HORIZONTAL) - bt = Button(frame, text="Reset Tick", command=self.reset_tickscale) - sl.pack(side=TOP, fill=X) - bt.pack(side=TOP, fill=X) - return - - - def on_scale(self, val): - v = float(val) - if v == 0.0: - pitch = 0 - else: - pitch = self.grid_pitch/v - self.scale = v - self.can_grid.set_pitch(pitch) - return - - - def reset_scale(self): - self.scale_var.set(1.) - pitch = self.grid_pitch/1.0 - self.scale = 1.0 - self.can_grid.set_pitch(pitch) - return - - - def on_tickchange(self, val): - v = self.tickscale_var.get() - if v == 0.0: - self.tick = 0 - else: - self.tick = v - return - - def reset_tickscale(self): - self.tick = self.default_tick - self.tickscale_var.set(self.default_tick) - return - # end of Scale widget set - #------------------------------------------------------------ - - #------------------------------------------------------------ - # Canvas control set - def create_checkbutton(self, frame): - axis = Checkbutton(frame, text="Axis", - onvalue="on", offvalue="off", - justify=LEFT, anchor=W, - variable=self.axis_check, - command=self.can_axis.toggle) - grid = Checkbutton(frame, text="Grid", - onvalue="on", offvalue="off", - justify=LEFT, anchor=W, - variable=self.grid_check, - command=self.can_grid.toggle) - rname = Checkbutton(frame, text="Robots' name", - onvalue="on", offvalue="off", - justify=LEFT, anchor=W, - variable=self.rname_check, - command=self.on_rname_toggle) - for w in [axis, grid, rname]: - w.pack(side=TOP, anchor=W, fill=X) - return - - - def on_rname_toggle(self): - for r in self.rnames.keys(): - self.rnames[r].toggle() - return - - - # end of Canvas control set - #------------------------------------------------------------ - - - #------------------------------------------------------------ - # Robot creator control set - def create_robotcreator(self, frame): - lb = Label(frame, text="Robot Type", anchor=W, justify=LEFT) - - om = OptionMenu(frame, label="Type: ", variable=self.robot_kind_var) - for opt in self.robot_factory.keys(): - om.add_command(opt, label=opt) - if sys.version_info[0] == 2: - self.robot_kind_var.set(self.robot_factory.keys()[0]) - else: - self.robot_kind_var.set(list(self.robot_factory.keys())[0]) - - creater = Button(frame, text="Create", command=self.create_robot) - deleter = Button(frame, text="Delete", command=self.delete_robot) - - om.pack(side=TOP, fill=X) - creater.pack(side=TOP, fill=X) - deleter.pack(side=TOP, fill=X) - return - - - def create_robotlist(self, frame): - f = Frame(frame, width=self.wd, height=200) - f.pack(side=TOP, fill=BOTH, expand=1) - ys = Scrollbar(f, orient = VERTICAL) - ys.grid(row = 0, column=1, sticky = N+S) - xs = Scrollbar(f, orient = HORIZONTAL) - xs.grid(row = 1, column=0, sticky = E+W) - - self.rlistbox = Listbox(f, - xscrollcommand = xs.set, - yscrollcommand = ys.set, - selectmode = 'single', - setgrid = TRUE, - height=20) - self.rlistbox.grid(row = 0, column = 0, sticky = N+S+E+W,) - xs['command']=self.rlistbox.xview - ys['command']=self.rlistbox.yview - self.rlistbox.bind("", self.on_clickrlistbox) - return - - - def on_clickrlistbox(self, event): - index = self.rlistbox.curselection() - if len(index) > 0: - robot_name = self.rlistbox.get(index[0]) - self.robots[robot_name].property_page() - return - - - def create_robot(self): - kind = self.robot_kind_var.get() - robot = self.robot_factory[kind](self) - - self.rlistbox.insert(END, robot.get_name()) - self.rnames[robot.get_name()] = RobotTitle(self, - robot, - robot.get_name(), - 20) - self.robots[robot.get_name()] = robot - return - - - def delete_robot(self): - index = self.rlistbox.curselection() - if len(index) > 0: - robot_name = self.rlistbox.get(index[0]) - r = self.rnames.pop(robot_name) - del(r) - r = self.robots.pop(robot_name) - del(r) - self.rlistbox.delete(index) - return - - # end of Robot creator control set - #------------------------------------------------------------ - - - #------------------------------------------------------------ - # - def real_to_canvas(self, x, y, dx, dy, dt): - # Simulator coordinate system -> display coordinate system - # x, y: original position - # dx, dy, dt: translation and rotation vector - # translation and rotation - x_tmp = (math.cos(dt) * x - math.sin(dt) * y + dx)/self.scale - y_tmp = (math.sin(dt) * x + math.cos(dt) * y + dy)/self.scale - # align to canvas coordinate system (origin is center and y+ is upward) - xo = x_tmp + self.x0 - yo = -y_tmp + self.y0 - return xo, yo + def __init__(self, main=None, width=800, height=600): + Frame.__init__(self, main) + + # canvas properties + self.width = width + self.height = height + # zero of canvas + self.x0 = width / 2 + self.y0 = height / 2 + + self.wd = 150 + + self.robots = {} + + self.robot = None + self.postext = None + + self.scale = 1.0 + self.scale_var = DoubleVar() + self.scale_var.set(self.scale) + + self.grid_pitch = 50 + + self.tick = 0.1 + self.default_tick = 0.1 + self.tickscale_var = DoubleVar() + self.tickscale_var.set(self.tick) + + self.axis_check = StringVar() + self.axis_check.set("on") + self.grid_check = StringVar() + self.grid_check.set("on") + self.rname_check = StringVar() + self.rname_check.set("on") + self.rnames = {} + + self.robot_kind_var = StringVar() + self.robot_factory = {"DDMobileRobot": DDMobileRobot} + + self.init() + self.pack() + + self.after(20, self.on_update) + return + + def init(self): + self.canvas = Canvas(self, bg="#eeeeee", + width=self.width, height=self.height) + self.canvas.pack(side=LEFT) + + self.can_grid = CanvasGrid(self.canvas, self.x0, self.y0, + self.width, self.height, self.grid_pitch, + "#aaaaaa", 1) + self.can_axis = CanvasAxis(self.canvas, self.width, self.height) + + self.frame = Frame(self) + self.frame.pack(side=LEFT) + + # Screen control + self.scrctrl_frame = Frame(self.frame, width=self.wd, height=300, + relief=GROOVE, bd=2) + self.scrctrl_frame.pack(side=TOP, fill=X) + self.create_scale(self.scrctrl_frame) + self.create_checkbutton(self.scrctrl_frame) + + # Robot manager + self.robomgr_frame = Frame(self.frame, width=self.wd, height=300, + relief=GROOVE, bd=2) + self.robomgr_frame.pack(side=TOP) + self.create_robotcreator(self.robomgr_frame) + self.create_robotlist(self.robomgr_frame) + return + + def on_update(self): + for o in self.robots.keys(): + self.robots[o].on_update() + for r in self.rnames.keys(): + self.rnames[r].draw() + self.after(20, self.on_update) + return + + def get_tick(self): + return self.tick + + def get_canvas(self): + return self.canvas + + def get_translation(self): + return self.real_to_canvas + + # ------------------------------------------------------------ + # Scale control set + + def create_scale(self, frame): + dummy = Frame(frame, width=self.wd) + dummy.pack(side=TOP) + sl = Scale(frame, from_=0, to=10, resolution=0.01, + label="Scale Factor", command=self.on_scale, + variable=self.scale_var, orient=HORIZONTAL) + bt = Button(frame, text="Reset Scale", command=self.reset_scale) + sl.pack(side=TOP, fill=X) + bt.pack(side=TOP, fill=X) + + sl = Scale(frame, from_=0.001, to=1, resolution=0.001, + label="Time tick [s]", command=self.on_tickchange, + variable=self.tickscale_var, orient=HORIZONTAL) + bt = Button(frame, text="Reset Tick", command=self.reset_tickscale) + sl.pack(side=TOP, fill=X) + bt.pack(side=TOP, fill=X) + return + + def on_scale(self, val): + v = float(val) + if v == 0.0: + pitch = 0 + else: + pitch = self.grid_pitch / v + self.scale = v + self.can_grid.set_pitch(pitch) + return + + def reset_scale(self): + self.scale_var.set(1.) + pitch = self.grid_pitch / 1.0 + self.scale = 1.0 + self.can_grid.set_pitch(pitch) + return + + def on_tickchange(self, val): + v = self.tickscale_var.get() + if v == 0.0: + self.tick = 0 + else: + self.tick = v + return + + def reset_tickscale(self): + self.tick = self.default_tick + self.tickscale_var.set(self.default_tick) + return + # end of Scale widget set + # ------------------------------------------------------------ + + # ------------------------------------------------------------ + # Canvas control set + def create_checkbutton(self, frame): + axis = Checkbutton(frame, text="Axis", + onvalue="on", offvalue="off", + justify=LEFT, anchor=W, + variable=self.axis_check, + command=self.can_axis.toggle) + grid = Checkbutton(frame, text="Grid", + onvalue="on", offvalue="off", + justify=LEFT, anchor=W, + variable=self.grid_check, + command=self.can_grid.toggle) + rname = Checkbutton(frame, text="Robots' name", + onvalue="on", offvalue="off", + justify=LEFT, anchor=W, + variable=self.rname_check, + command=self.on_rname_toggle) + for w in [axis, grid, rname]: + w.pack(side=TOP, anchor=W, fill=X) + return + + def on_rname_toggle(self): + for r in self.rnames.keys(): + self.rnames[r].toggle() + return + + # end of Canvas control set + # ------------------------------------------------------------ + + # ------------------------------------------------------------ + # Robot creator control set + + def create_robotcreator(self, frame): + lb = Label(frame, text="Robot Type", anchor=W, justify=LEFT) + + om = OptionMenu(frame, label="Type: ", variable=self.robot_kind_var) + for opt in self.robot_factory.keys(): + om.add_command(opt, label=opt) + if sys.version_info[0] == 2: + self.robot_kind_var.set(self.robot_factory.keys()[0]) + else: + self.robot_kind_var.set(list(self.robot_factory.keys())[0]) + + creater = Button(frame, text="Create", command=self.create_robot) + deleter = Button(frame, text="Delete", command=self.delete_robot) + + om.pack(side=TOP, fill=X) + creater.pack(side=TOP, fill=X) + deleter.pack(side=TOP, fill=X) + return + + def create_robotlist(self, frame): + f = Frame(frame, width=self.wd, height=200) + f.pack(side=TOP, fill=BOTH, expand=1) + ys = Scrollbar(f, orient=VERTICAL) + ys.grid(row=0, column=1, sticky=N + S) + xs = Scrollbar(f, orient=HORIZONTAL) + xs.grid(row=1, column=0, sticky=E + W) + + self.rlistbox = Listbox(f, + xscrollcommand=xs.set, + yscrollcommand=ys.set, + selectmode='single', + setgrid=TRUE, + height=20) + self.rlistbox.grid(row=0, column=0, sticky=N + S + E + W,) + xs['command'] = self.rlistbox.xview + ys['command'] = self.rlistbox.yview + self.rlistbox.bind("", self.on_clickrlistbox) + return + + def on_clickrlistbox(self, event): + index = self.rlistbox.curselection() + if len(index) > 0: + robot_name = self.rlistbox.get(index[0]) + self.robots[robot_name].property_page() + return + + def create_robot(self): + kind = self.robot_kind_var.get() + robot = self.robot_factory[kind](self) + + self.rlistbox.insert(END, robot.get_name()) + self.rnames[robot.get_name()] = RobotTitle(self, + robot, + robot.get_name(), + 20) + self.robots[robot.get_name()] = robot + return + + def delete_robot(self): + index = self.rlistbox.curselection() + if len(index) > 0: + robot_name = self.rlistbox.get(index[0]) + r = self.rnames.pop(robot_name) + del(r) + r = self.robots.pop(robot_name) + del(r) + self.rlistbox.delete(index) + return + + # end of Robot creator control set + # ------------------------------------------------------------ + + # ------------------------------------------------------------ + # + + def real_to_canvas(self, x, y, dx, dy, dt): + # Simulator coordinate system -> display coordinate system + # x, y: original position + # dx, dy, dt: translation and rotation vector + # translation and rotation + x_tmp = (math.cos(dt) * x - math.sin(dt) * y + dx) / self.scale + y_tmp = (math.sin(dt) * x + math.cos(dt) * y + dy) / self.scale + # align to canvas coordinate system (origin is center and y+ is upward) + xo = x_tmp + self.x0 + yo = -y_tmp + self.y0 + return xo, yo def TkMobileRobotSimulatorInit(manager): - profile = OpenRTM_aist.Properties(defaults_str=tkmobilerobotsimulator_spec) - manager.registerFactory(profile, - TkMobileRobotSimulator, - OpenRTM_aist.Delete) - return + profile = OpenRTM_aist.Properties(defaults_str=tkmobilerobotsimulator_spec) + manager.registerFactory(profile, + TkMobileRobotSimulator, + OpenRTM_aist.Delete) + return def main(): - m = TkMobileRobot(Tk()) - m.master.title("Tk Mobile Robot Simulator") - mgr = OpenRTM_aist.Manager.init(sys.argv) - mgr.activateManager() - profile = OpenRTM_aist.Properties(defaults_str=tkmobilerobotsimulator_spec) - mgr.registerFactory(profile, TkMobileRobotSimulator, OpenRTM_aist.Delete) - mgr.runManager(True) - m.mainloop() - -if __name__ == '__main__': - main() + m = TkMobileRobot(Tk()) + m.main.title("Tk Mobile Robot Simulator") + mgr = OpenRTM_aist.Manager.init(sys.argv) + mgr.activateManager() + profile = OpenRTM_aist.Properties(defaults_str=tkmobilerobotsimulator_spec) + mgr.registerFactory(profile, TkMobileRobotSimulator, OpenRTM_aist.Delete) + mgr.runManager(True) + m.mainloop() + + +if __name__ == '__main__': + main() diff --git a/OpenRTM_aist/examples/MobileRobotCanvas/__init__.py b/OpenRTM_aist/examples/MobileRobotCanvas/__init__.py index 932b7982..270be2a2 100644 --- a/OpenRTM_aist/examples/MobileRobotCanvas/__init__.py +++ b/OpenRTM_aist/examples/MobileRobotCanvas/__init__.py @@ -1 +1 @@ -# Empty file +# Empty file diff --git a/OpenRTM_aist/examples/NXTRTC/NXTBrick.py b/OpenRTM_aist/examples/NXTRTC/NXTBrick.py index 94c15005..2f3369bc 100644 --- a/OpenRTM_aist/examples/NXTRTC/NXTBrick.py +++ b/OpenRTM_aist/examples/NXTRTC/NXTBrick.py @@ -1,4 +1,4 @@ -#!/usr/bin/env python +#!/usr/bin/env python # -*- coding: utf-8 -*- # -*- Python -*- @@ -8,100 +8,100 @@ from nxt.motor import * import time + class NXTBrick: - def __init__(self, bsock=None): - """ - Ctor - Connecting to NXT brick and creating motor object, sensor object - and so on. Motor encoders will be reset. - """ - if bsock: - self.sock = bsock - else: - self.sock = nxt.locator.find_one_brick().connect() - - self.motors = [Motor(self.sock, PORT_A), - Motor(self.sock, PORT_B), - Motor(self.sock, PORT_C)] - - self.sensors = [TouchSensor(self.sock, PORT_1), - SoundSensor(self.sock, PORT_2), - LightSensor(self.sock, PORT_3), - UltrasonicSensor(self.sock, PORT_4)] - self.resetPosition() - - def close(self): - """ - Finalizing connection with NXT brick. - """ - self.sock.close() - - def resetPosition(self, relative = 0): - """ - Resetting encoders of NXT motors - """ - for m in self.motors: - m.reset_position(relative) - - def setMotors(self, vels): - """ - This operation receives array and set them as motor power. If the - number of vels items does not match with the number of motors, - smaller number of them will be taken and set respectively. - """ - for i, v in enumerate(vels[:min(len(vels),len(self.motors))]): - self.motors[i].power = max(min(v,127),-127) - self.motors[i].mode = MODE_MOTOR_ON | MODE_REGULATED - self.motors[i].regulation_mode = REGULATION_MOTOR_SYNC - self.motors[i].run_state = RUN_STATE_RUNNING - self.motors[i].tacho_limit = 0 - self.motors[i].set_output_state() - - def getMotors(self): - """ - Getting motors' angle (degrees) - """ - state = [] - for m in self.motors: - stat = None - for i in range(3): - try: - stat = m.get_output_state() - break - except: - time.sleep(0.01) - continue - - if stat == None: - import sys - print("Unknown motor encoder error") - print(sys.exc_info()[1]) - state.append(stat) - - return state - - - def getSensors(self): - """ - Getting sensors' values. Data will be returned as array. - """ - state = [] - for s in self.sensors: - stat = None - for i in range(3): - try: - stat = s.get_sample() - break - except: - time.sleep(0.01) - continue - if stat == None: - import sys - print("Unknown sensor error") - print(sys.exc_info()[1]) - state.append(stat) - - return state + def __init__(self, bsock=None): + """ + Ctor + Connecting to NXT brick and creating motor object, sensor object + and so on. Motor encoders will be reset. + """ + if bsock: + self.sock = bsock + else: + self.sock = nxt.locator.find_one_brick().connect() + + self.motors = [Motor(self.sock, PORT_A), + Motor(self.sock, PORT_B), + Motor(self.sock, PORT_C)] + + self.sensors = [TouchSensor(self.sock, PORT_1), + SoundSensor(self.sock, PORT_2), + LightSensor(self.sock, PORT_3), + UltrasonicSensor(self.sock, PORT_4)] + self.resetPosition() + + def close(self): + """ + Finalizing connection with NXT brick. + """ + self.sock.close() + + def resetPosition(self, relative=0): + """ + Resetting encoders of NXT motors + """ + for m in self.motors: + m.reset_position(relative) + + def setMotors(self, vels): + """ + This operation receives array and set them as motor power. If the + number of vels items does not match with the number of motors, + smaller number of them will be taken and set respectively. + """ + for i, v in enumerate(vels[:min(len(vels), len(self.motors))]): + self.motors[i].power = max(min(v, 127), -127) + self.motors[i].mode = MODE_MOTOR_ON | MODE_REGULATED + self.motors[i].regulation_mode = REGULATION_MOTOR_SYNC + self.motors[i].run_state = RUN_STATE_RUNNING + self.motors[i].tacho_limit = 0 + self.motors[i].set_output_state() + + def getMotors(self): + """ + Getting motors' angle (degrees) + """ + state = [] + for m in self.motors: + stat = None + for i in range(3): + try: + stat = m.get_output_state() + break + except BaseException: + time.sleep(0.01) + continue + + if stat is None: + import sys + print("Unknown motor encoder error") + print(sys.exc_info()[1]) + state.append(stat) + + return state + + def getSensors(self): + """ + Getting sensors' values. Data will be returned as array. + """ + state = [] + for s in self.sensors: + stat = None + for i in range(3): + try: + stat = s.get_sample() + break + except BaseException: + time.sleep(0.01) + continue + if stat is None: + import sys + print("Unknown sensor error") + print(sys.exc_info()[1]) + state.append(stat) + + return state """ @@ -110,23 +110,23 @@ def getSensors(self): obtained and shown. Sensor data are also obtained and shown. """ if __name__ == "__main__": - import time - nxt = NXTBrick() - print("connected") - - # Testing motors - for i in range(0): - nxt.setMotors([80,-80,80]) - print("Motor: ") - mstat = nxt.getMotors() - for i, m in enumerate(mstat): - print("(" , i, "): ", m) - time.sleep(0.1) - nxt.setMotors([0,0,0]) - - # Testing sensors - for i in range(100): - sensors = ["Touch", "Sound", "Light", "USonic"] - sval = nxt.getSensors() - print(sval) - time.sleep(0.1) + import time + nxt = NXTBrick() + print("connected") + + # Testing motors + for i in range(0): + nxt.setMotors([80, -80, 80]) + print("Motor: ") + mstat = nxt.getMotors() + for i, m in enumerate(mstat): + print("(", i, "): ", m) + time.sleep(0.1) + nxt.setMotors([0, 0, 0]) + + # Testing sensors + for i in range(100): + sensors = ["Touch", "Sound", "Light", "USonic"] + sval = nxt.getSensors() + print(sval) + time.sleep(0.1) diff --git a/OpenRTM_aist/examples/NXTRTC/NXTBrick20.py b/OpenRTM_aist/examples/NXTRTC/NXTBrick20.py index b511961a..37effa7b 100644 --- a/OpenRTM_aist/examples/NXTRTC/NXTBrick20.py +++ b/OpenRTM_aist/examples/NXTRTC/NXTBrick20.py @@ -1,4 +1,4 @@ -#!/usr/bin/env python +#!/usr/bin/env python # -*- coding: utf-8 -*- # -*- Python -*- @@ -8,96 +8,96 @@ from nxt.motor import * import time + class NXTBrick: - def __init__(self, bsock=None): - """ - Ctor - Connecting to NXT brick and creating motor object, sensor object - and so on. Motor encoders will be reset. - """ - if bsock: - self.sock = bsock - else: - self.sock = nxt.locator.find_one_brick() - - self.motors = [Motor(self.sock, PORT_A), - Motor(self.sock, PORT_B), - Motor(self.sock, PORT_C)] - - self.sensors = [Touch(self.sock, PORT_1), - Sound(self.sock, PORT_2), - Light(self.sock, PORT_3), - Ultrasonic(self.sock, PORT_4)] - self.resetPosition() - - def close(self): - """ - Finalizing connection with NXT brick. - """ - self.sock.close() - - def resetPosition(self, relative = 0): - """ - Resetting encoders of NXT motors - """ - for m in self.motors: - m.reset_position(relative) - - def setMotors(self, vels): - """ - This operation receives array and set them as motor power. If the - number of vels items does not match with the number of motors, - smaller number of them will be taken and set respectively. - """ - for i, v in enumerate(vels[:min(len(vels),len(self.motors))]): - self.motors[i].sync = 1 - self.motors[i].run(max(min(v,127),-127)) - - def getMotors(self): - """ - Getting motors' angle (degrees) - """ - state = [] - for m in self.motors: - stat = None - for i in range(3): - try: - stat = m.get_tacho().tacho_count - break - except: - time.sleep(0.01) - continue - - if stat == None: - import sys - print("Unknown motor encoder error") - print(sys.exc_info()[1]) - state.append(stat) - - return state - - - def getSensors(self): - """ - Getting sensors' values. Data will be returned as array. - """ - state = [] - for s in self.sensors: - stat = None - for i in range(3): - try: - stat = s.get_sample() - break - except: - time.sleep(0.01) - continue - if stat == None: - import sys - print("Unknown sensor error") - print(sys.exc_info()[1]) - state.append(stat) - - return state + def __init__(self, bsock=None): + """ + Ctor + Connecting to NXT brick and creating motor object, sensor object + and so on. Motor encoders will be reset. + """ + if bsock: + self.sock = bsock + else: + self.sock = nxt.locator.find_one_brick() + + self.motors = [Motor(self.sock, PORT_A), + Motor(self.sock, PORT_B), + Motor(self.sock, PORT_C)] + + self.sensors = [Touch(self.sock, PORT_1), + Sound(self.sock, PORT_2), + Light(self.sock, PORT_3), + Ultrasonic(self.sock, PORT_4)] + self.resetPosition() + + def close(self): + """ + Finalizing connection with NXT brick. + """ + self.sock.close() + + def resetPosition(self, relative=0): + """ + Resetting encoders of NXT motors + """ + for m in self.motors: + m.reset_position(relative) + + def setMotors(self, vels): + """ + This operation receives array and set them as motor power. If the + number of vels items does not match with the number of motors, + smaller number of them will be taken and set respectively. + """ + for i, v in enumerate(vels[:min(len(vels), len(self.motors))]): + self.motors[i].sync = 1 + self.motors[i].run(max(min(v, 127), -127)) + + def getMotors(self): + """ + Getting motors' angle (degrees) + """ + state = [] + for m in self.motors: + stat = None + for i in range(3): + try: + stat = m.get_tacho().tacho_count + break + except BaseException: + time.sleep(0.01) + continue + + if stat is None: + import sys + print("Unknown motor encoder error") + print(sys.exc_info()[1]) + state.append(stat) + + return state + + def getSensors(self): + """ + Getting sensors' values. Data will be returned as array. + """ + state = [] + for s in self.sensors: + stat = None + for i in range(3): + try: + stat = s.get_sample() + break + except BaseException: + time.sleep(0.01) + continue + if stat is None: + import sys + print("Unknown sensor error") + print(sys.exc_info()[1]) + state.append(stat) + + return state """ @@ -106,23 +106,23 @@ def getSensors(self): obtained and shown. Sensor data are also obtained and shown. """ if __name__ == "__main__": - import time - nxt = NXTBrick() - print("connected") - - # Testing motors - for i in range(0): - nxt.setMotors([80,-80,80]) - print("Motor: ") - mstat = nxt.getMotors() - for i, m in enumerate(mstat): - print("(" , i, "): ", m) - time.sleep(0.1) - nxt.setMotors([0,0,0]) - - # Testing sensors - for i in range(100): - sensors = ["Touch", "Sound", "Light", "USonic"] - sval = nxt.getSensors() - print(sval) - time.sleep(0.1) + import time + nxt = NXTBrick() + print("connected") + + # Testing motors + for i in range(0): + nxt.setMotors([80, -80, 80]) + print("Motor: ") + mstat = nxt.getMotors() + for i, m in enumerate(mstat): + print("(", i, "): ", m) + time.sleep(0.1) + nxt.setMotors([0, 0, 0]) + + # Testing sensors + for i in range(100): + sensors = ["Touch", "Sound", "Light", "USonic"] + sval = nxt.getSensors() + print(sval) + time.sleep(0.1) diff --git a/OpenRTM_aist/examples/NXTRTC/NXTRTC.py b/OpenRTM_aist/examples/NXTRTC/NXTRTC.py index e42f2905..7b2c5df1 100644 --- a/OpenRTM_aist/examples/NXTRTC/NXTRTC.py +++ b/OpenRTM_aist/examples/NXTRTC/NXTRTC.py @@ -1,152 +1,150 @@ -#!/usr/bin/env python +#!/usr/bin/env python # -*- coding:utf-8 -*- # -*- Python -*- from __future__ import print_function +import NXTBrick +import OpenRTM_aist +import RTC import sys import time sys.path.append(".") # Import RTM module -import RTC -import OpenRTM_aist # import NXTBrick class -import NXTBrick # This module's spesification # -nxtrtc_spec = ["implementation_id", "NXTRTC", - "type_name", "NXTRTC", - "description", "NXT sample component", - "version", "0.1", - "vendor", "AIST", - "category", "example", - "activity_type", "DataFlowComponent", - "max_instance", "10", - "language", "Python", - "lang_type", "SCRIPT", +nxtrtc_spec = ["implementation_id", "NXTRTC", + "type_name", "NXTRTC", + "description", "NXT sample component", + "version", "0.1", + "vendor", "AIST", + "category", "example", + "activity_type", "DataFlowComponent", + "max_instance", "10", + "language", "Python", + "lang_type", "SCRIPT", "conf.default.map", "A,B", ""] # + class NXTRTC(OpenRTM_aist.DataFlowComponentBase): - def __init__(self, manager): - OpenRTM_aist.DataFlowComponentBase.__init__(self, manager) - - # initialize of configuration-data. - # - self._map = [['A', 'B']] - self._nxtbrick = None - self._mapping = {'A':0,'B':1,'C':2} - - def onInitialize(self): - # DataPorts initialization - # - self._d_vel = RTC.TimedFloatSeq(RTC.Time(0,0),[]) - self._velIn = OpenRTM_aist.InPort("vel", self._d_vel) - self.addInPort("vel",self._velIn) - self._d_pos = RTC.TimedFloatSeq(RTC.Time(0,0),[]) - self._posOut = OpenRTM_aist.OutPort("pos", self._d_pos) - self.addOutPort("pos",self._posOut) - self._d_sens = RTC.TimedFloatSeq(RTC.Time(0,0),[]) - self._sensOut = OpenRTM_aist.OutPort("sens", self._d_sens) - self.addOutPort("sens",self._sensOut) - - # Bind variables and configuration variable - # - self.bindParameter("map", self._map, "A,B") - - # create NXTBrick object - try: - print("Connecting to NXT brick ....") - self._nxtbrick = NXTBrick.NXTBrick() - print("Connection established.") - except: - print("NXTBrick connection failed.") - return RTC.RTC_ERROR - - return RTC.RTC_OK - - def onFinalize(self): - self._nxtbrick.close() - - def onActivated(self, ec_id): - self._nxtbrick.setMotors([0,0,0]) - # reset NXTBrick's position. - self._nxtbrick.resetPosition() - return RTC.RTC_OK - - def onDeactivated(self, ec_id): - self._nxtbrick.setMotors([0,0,0]) - # reset NXTBrick's position. - self._nxtbrick.resetPosition() - - return RTC.RTC_OK - - def onExecute(self, ec_id): - try: - # check new data. - if self._velIn.isNew(): - # read velocity data from inport. - self._d_vel = self._velIn.read() - - vel_ = [0,0,0] - vel_[self._mapping[self._map[0][0]]] = self._d_vel.data[0] - vel_[self._mapping[self._map[0][1]]] = self._d_vel.data[1] - # set velocity + def __init__(self, manager): + OpenRTM_aist.DataFlowComponentBase.__init__(self, manager) + + # initialize of configuration-data. + # + self._map = [['A', 'B']] + self._nxtbrick = None + self._mapping = {'A': 0, 'B': 1, 'C': 2} + + def onInitialize(self): + # DataPorts initialization + # + self._d_vel = RTC.TimedFloatSeq(RTC.Time(0, 0), []) + self._velIn = OpenRTM_aist.InPort("vel", self._d_vel) + self.addInPort("vel", self._velIn) + self._d_pos = RTC.TimedFloatSeq(RTC.Time(0, 0), []) + self._posOut = OpenRTM_aist.OutPort("pos", self._d_pos) + self.addOutPort("pos", self._posOut) + self._d_sens = RTC.TimedFloatSeq(RTC.Time(0, 0), []) + self._sensOut = OpenRTM_aist.OutPort("sens", self._d_sens) + self.addOutPort("sens", self._sensOut) + + # Bind variables and configuration variable + # + self.bindParameter("map", self._map, "A,B") + + # create NXTBrick object + try: + print("Connecting to NXT brick ....") + self._nxtbrick = NXTBrick.NXTBrick() + print("Connection established.") + except BaseException: + print("NXTBrick connection failed.") + return RTC.RTC_ERROR + + return RTC.RTC_OK + + def onFinalize(self): + self._nxtbrick.close() + + def onActivated(self, ec_id): + self._nxtbrick.setMotors([0, 0, 0]) + # reset NXTBrick's position. + self._nxtbrick.resetPosition() + return RTC.RTC_OK + + def onDeactivated(self, ec_id): + self._nxtbrick.setMotors([0, 0, 0]) + # reset NXTBrick's position. + self._nxtbrick.resetPosition() + + return RTC.RTC_OK + + def onExecute(self, ec_id): + try: + # check new data. + if self._velIn.isNew(): + # read velocity data from inport. + self._d_vel = self._velIn.read() + + vel_ = [0, 0, 0] + vel_[self._mapping[self._map[0][0]]] = self._d_vel.data[0] + vel_[self._mapping[self._map[0][1]]] = self._d_vel.data[1] + # set velocity # print(vel_) - self._nxtbrick.setMotors(vel_) - else: - print("buffer empty") - - # get sensor data. - sensor_ = self._nxtbrick.getSensors() - if sensor_: - self._d_sens.data = sensor_ - # write sensor data to outport. - self._sensOut.write() - - # get position data. - position_ = self._nxtbrick.getMotors() - if position_: - self._d_pos.data = \ - [position_[self._mapping[self._map[0][0]]][9], \ - position_[self._mapping[self._map[0][1]]][9]] - # write position data to outport. - self._posOut.write() - except: - print(sys.exc_info()[1]) - - return RTC.RTC_OK - + self._nxtbrick.setMotors(vel_) + else: + print("buffer empty") + + # get sensor data. + sensor_ = self._nxtbrick.getSensors() + if sensor_: + self._d_sens.data = sensor_ + # write sensor data to outport. + self._sensOut.write() + + # get position data. + position_ = self._nxtbrick.getMotors() + if position_: + self._d_pos.data = \ + [position_[self._mapping[self._map[0][0]]][9], + position_[self._mapping[self._map[0][1]]][9]] + # write position data to outport. + self._posOut.write() + except BaseException: + print(sys.exc_info()[1]) + + return RTC.RTC_OK def NXTRTCInit(manager): - profile = OpenRTM_aist.Properties(defaults_str=nxtrtc_spec) - manager.registerFactory(profile, - NXTRTC, - OpenRTM_aist.Delete) + profile = OpenRTM_aist.Properties(defaults_str=nxtrtc_spec) + manager.registerFactory(profile, + NXTRTC, + OpenRTM_aist.Delete) def MyModuleInit(manager): - NXTRTCInit(manager) - - # Create a component - comp = manager.createComponent("NXTRTC") + NXTRTCInit(manager) + # Create a component + comp = manager.createComponent("NXTRTC") def main(): - mgr = OpenRTM_aist.Manager.init(sys.argv) - mgr.setModuleInitProc(MyModuleInit) - mgr.activateManager() - mgr.runManager() - -if __name__ == "__main__": - main() + mgr = OpenRTM_aist.Manager.init(sys.argv) + mgr.setModuleInitProc(MyModuleInit) + mgr.activateManager() + mgr.runManager() +if __name__ == "__main__": + main() diff --git a/OpenRTM_aist/examples/NXTRTC/NXTRTC20.py b/OpenRTM_aist/examples/NXTRTC/NXTRTC20.py index 709405e4..49eb097c 100644 --- a/OpenRTM_aist/examples/NXTRTC/NXTRTC20.py +++ b/OpenRTM_aist/examples/NXTRTC/NXTRTC20.py @@ -1,151 +1,149 @@ -#!/usr/bin/env python +#!/usr/bin/env python # -*- coding:utf-8 -*- # -*- Python -*- from __future__ import print_function +import NXTBrick20 +import OpenRTM_aist +import RTC import sys import time sys.path.append(".") # Import RTM module -import RTC -import OpenRTM_aist # import NXTBrick class -import NXTBrick20 # This module's spesification # -nxtrtc_spec = ["implementation_id", "NXTRTC", - "type_name", "NXTRTC", - "description", "NXT sample component", - "version", "0.1", - "vendor", "AIST", - "category", "example", - "activity_type", "DataFlowComponent", - "max_instance", "10", - "language", "Python", - "lang_type", "SCRIPT", +nxtrtc_spec = ["implementation_id", "NXTRTC", + "type_name", "NXTRTC", + "description", "NXT sample component", + "version", "0.1", + "vendor", "AIST", + "category", "example", + "activity_type", "DataFlowComponent", + "max_instance", "10", + "language", "Python", + "lang_type", "SCRIPT", "conf.default.map", "A,B", ""] # -class NXTRTC(OpenRTM_aist.DataFlowComponentBase): - def __init__(self, manager): - OpenRTM_aist.DataFlowComponentBase.__init__(self, manager) - - # initialize of configuration-data. - # - self._map = [['A', 'B']] - self._nxtbrick = None - self._mapping = {'A':0,'B':1,'C':2} - - def onInitialize(self): - # DataPorts initialization - # - self._d_vel = RTC.TimedFloatSeq(RTC.Time(0,0),[]) - self._velIn = OpenRTM_aist.InPort("vel", self._d_vel) - self.addInPort("vel",self._velIn) - self._d_pos = RTC.TimedFloatSeq(RTC.Time(0,0),[]) - self._posOut = OpenRTM_aist.OutPort("pos", self._d_pos) - self.addOutPort("pos",self._posOut) - self._d_sens = RTC.TimedFloatSeq(RTC.Time(0,0),[]) - self._sensOut = OpenRTM_aist.OutPort("sens", self._d_sens) - self.addOutPort("sens",self._sensOut) - - # Bind variables and configuration variable - # - self.bindParameter("map", self._map, "A,B") - - # create NXTBrick object - try: - print("Connecting to NXT brick ....") - self._nxtbrick = NXTBrick20.NXTBrick() - print("Connection established.") - except: - print("NXTBrick connection failed.") - return RTC.RTC_ERROR - - return RTC.RTC_OK - - def onFinalize(self): - self._nxtbrick.close() - - def onActivated(self, ec_id): - self._nxtbrick.setMotors([0,0,0]) - # reset NXTBrick's position. - self._nxtbrick.resetPosition() - return RTC.RTC_OK - - def onDeactivated(self, ec_id): - self._nxtbrick.setMotors([0,0,0]) - # reset NXTBrick's position. - self._nxtbrick.resetPosition() - - return RTC.RTC_OK - - def onExecute(self, ec_id): - try: - # check new data. - if self._velIn.isNew(): - # read velocity data from inport. - self._d_vel = self._velIn.read() - - vel_ = [0,0,0] - vel_[self._mapping[self._map[0][0]]] = self._d_vel.data[0] - vel_[self._mapping[self._map[0][1]]] = self._d_vel.data[1] - # set velocity - self._nxtbrick.setMotors(vel_) - else: - print("buffer empty") - - # get sensor data. - sensor_ = self._nxtbrick.getSensors() - if sensor_: - self._d_sens.data = sensor_ - # write sensor data to outport. - self._sensOut.write() - - # get position data. - position_ = self._nxtbrick.getMotors() - if position_: - self._d_pos.data = \ - [position_[self._mapping[self._map[0][0]]], \ - position_[self._mapping[self._map[0][1]]]] - # write position data to outport. - self._posOut.write() - except: - print(sys.exc_info()[1]) - - return RTC.RTC_OK +class NXTRTC(OpenRTM_aist.DataFlowComponentBase): + def __init__(self, manager): + OpenRTM_aist.DataFlowComponentBase.__init__(self, manager) + + # initialize of configuration-data. + # + self._map = [['A', 'B']] + self._nxtbrick = None + self._mapping = {'A': 0, 'B': 1, 'C': 2} + + def onInitialize(self): + # DataPorts initialization + # + self._d_vel = RTC.TimedFloatSeq(RTC.Time(0, 0), []) + self._velIn = OpenRTM_aist.InPort("vel", self._d_vel) + self.addInPort("vel", self._velIn) + self._d_pos = RTC.TimedFloatSeq(RTC.Time(0, 0), []) + self._posOut = OpenRTM_aist.OutPort("pos", self._d_pos) + self.addOutPort("pos", self._posOut) + self._d_sens = RTC.TimedFloatSeq(RTC.Time(0, 0), []) + self._sensOut = OpenRTM_aist.OutPort("sens", self._d_sens) + self.addOutPort("sens", self._sensOut) + + # Bind variables and configuration variable + # + self.bindParameter("map", self._map, "A,B") + + # create NXTBrick object + try: + print("Connecting to NXT brick ....") + self._nxtbrick = NXTBrick20.NXTBrick() + print("Connection established.") + except BaseException: + print("NXTBrick connection failed.") + return RTC.RTC_ERROR + + return RTC.RTC_OK + + def onFinalize(self): + self._nxtbrick.close() + + def onActivated(self, ec_id): + self._nxtbrick.setMotors([0, 0, 0]) + # reset NXTBrick's position. + self._nxtbrick.resetPosition() + return RTC.RTC_OK + + def onDeactivated(self, ec_id): + self._nxtbrick.setMotors([0, 0, 0]) + # reset NXTBrick's position. + self._nxtbrick.resetPosition() + + return RTC.RTC_OK + + def onExecute(self, ec_id): + try: + # check new data. + if self._velIn.isNew(): + # read velocity data from inport. + self._d_vel = self._velIn.read() + + vel_ = [0, 0, 0] + vel_[self._mapping[self._map[0][0]]] = self._d_vel.data[0] + vel_[self._mapping[self._map[0][1]]] = self._d_vel.data[1] + # set velocity + self._nxtbrick.setMotors(vel_) + else: + print("buffer empty") + + # get sensor data. + sensor_ = self._nxtbrick.getSensors() + if sensor_: + self._d_sens.data = sensor_ + # write sensor data to outport. + self._sensOut.write() + + # get position data. + position_ = self._nxtbrick.getMotors() + if position_: + self._d_pos.data = \ + [position_[self._mapping[self._map[0][0]]], + position_[self._mapping[self._map[0][1]]]] + # write position data to outport. + self._posOut.write() + except BaseException: + print(sys.exc_info()[1]) + + return RTC.RTC_OK def NXTRTCInit(manager): - profile = OpenRTM_aist.Properties(defaults_str=nxtrtc_spec) - manager.registerFactory(profile, - NXTRTC, - OpenRTM_aist.Delete) + profile = OpenRTM_aist.Properties(defaults_str=nxtrtc_spec) + manager.registerFactory(profile, + NXTRTC, + OpenRTM_aist.Delete) def MyModuleInit(manager): - NXTRTCInit(manager) - - # Create a component - comp = manager.createComponent("NXTRTC") + NXTRTCInit(manager) + # Create a component + comp = manager.createComponent("NXTRTC") def main(): - mgr = OpenRTM_aist.Manager.init(sys.argv) - mgr.setModuleInitProc(MyModuleInit) - mgr.activateManager() - mgr.runManager() - -if __name__ == "__main__": - main() + mgr = OpenRTM_aist.Manager.init(sys.argv) + mgr.setModuleInitProc(MyModuleInit) + mgr.activateManager() + mgr.runManager() +if __name__ == "__main__": + main() diff --git a/OpenRTM_aist/examples/NXTRTC/NXTRTC20_callback.py b/OpenRTM_aist/examples/NXTRTC/NXTRTC20_callback.py index ec43aa81..ed8147d9 100644 --- a/OpenRTM_aist/examples/NXTRTC/NXTRTC20_callback.py +++ b/OpenRTM_aist/examples/NXTRTC/NXTRTC20_callback.py @@ -1,33 +1,33 @@ -#!/usr/bin/env python +#!/usr/bin/env python # -*- coding:utf-8 -*- # -*- Python -*- from __future__ import print_function +import NXTBrick20 +import OpenRTM_aist +import RTC import sys import time sys.path.append(".") # Import RTM module -import RTC -import OpenRTM_aist # import NXTBrick class -import NXTBrick20 # This module's spesification # -nxtrtc_spec = ["implementation_id", "NXTRTC", - "type_name", "NXTRTC", - "description", "NXT sample component", - "version", "0.1", - "vendor", "AIST", - "category", "example", - "activity_type", "DataFlowComponent", - "max_instance", "10", - "language", "Python", - "lang_type", "SCRIPT", +nxtrtc_spec = ["implementation_id", "NXTRTC", + "type_name", "NXTRTC", + "description", "NXT sample component", + "version", "0.1", + "vendor", "AIST", + "category", "example", + "activity_type", "DataFlowComponent", + "max_instance", "10", + "language", "Python", + "lang_type", "SCRIPT", "conf.default.map", "A,B", ""] @@ -38,120 +38,118 @@ # # when data is written in the buffer of InPort, # it is called. + + class CallBackClass: - def __init__(self, nxtbrick_, map_): - self._nxtbrick = nxtbrick_ - self._map = map_ - self._mapping = {'A':0,'B':1,'C':2} + def __init__(self, nxtbrick_, map_): + self._nxtbrick = nxtbrick_ + self._map = map_ + self._mapping = {'A': 0, 'B': 1, 'C': 2} - def __call__(self, pData): - vel_ = [0,0,0] - vel_[self._mapping[self._map[0][0]]] = pData.data[0] - vel_[self._mapping[self._map[0][1]]] = pData.data[1] - # set velocity - self._nxtbrick.setMotors(vel_) + def __call__(self, pData): + vel_ = [0, 0, 0] + vel_[self._mapping[self._map[0][0]]] = pData.data[0] + vel_[self._mapping[self._map[0][1]]] = pData.data[1] + # set velocity + self._nxtbrick.setMotors(vel_) class NXTRTC(OpenRTM_aist.DataFlowComponentBase): - def __init__(self, manager): - OpenRTM_aist.DataFlowComponentBase.__init__(self, manager) - - # initialize of configuration-data. - # - self._map = [['A', 'B']] - self._nxtbrick = None - self._mapping = {'A':0,'B':1,'C':2} - - def onInitialize(self): - # DataPorts initialization - # - self._d_vel = RTC.TimedFloatSeq(RTC.Time(0,0),[]) - self._velIn = OpenRTM_aist.InPort("vel", self._d_vel) - self.addInPort("vel",self._velIn) - self._d_pos = RTC.TimedFloatSeq(RTC.Time(0,0),[]) - self._posOut = OpenRTM_aist.OutPort("pos", self._d_pos) - self.addOutPort("pos",self._posOut) - self._d_sens = RTC.TimedFloatSeq(RTC.Time(0,0),[]) - self._sensOut = OpenRTM_aist.OutPort("sens", self._d_sens) - self.addOutPort("sens",self._sensOut) - - # Bind variables and configuration variable - # - self.bindParameter("map", self._map, "A,B") - - # create NXTBrick object - try: - print("Connecting to NXT brick ....") - self._nxtbrick = NXTBrick.NXTBrick() - print("Connection established.") - except: - print("NXTBrick connection failed.") - return RTC.RTC_ERROR - - # set callback class - self._velIn.setOnWrite(CallBackClass(self._ntxbrick,self._map)) - - return RTC.RTC_OK - - def onFinalize(self): - self._nxtbrick.close() - - def onActivated(self, ec_id): - # reset NXTBrick's position. - self._nxtbrick.resetPosition() - - return RTC.RTC_OK - - - def onDeactivated(self, ec_id): - # reset NXTBrick's position. - self._nxtbrick.resetPosition() - - return RTC.RTC_OK - - - def onExecute(self, ec_id): - # get sensor data. - sensor_ = self._nxtbrick.getSensors() - if sensor_: - self._d_sens.data = sensor_ - # write sensor data to outport. - self._sensOut.write() - - # get position data. - position_ = self._nxtbrick.getMotors() - if position_: - self._d_pos.data = [position_[self._mapping[self._map[0][0]]],position_[self._mapping[self._map[0][1]]]] - # write position data to outport. - self._posOut.write() - - return RTC.RTC_OK - + def __init__(self, manager): + OpenRTM_aist.DataFlowComponentBase.__init__(self, manager) + + # initialize of configuration-data. + # + self._map = [['A', 'B']] + self._nxtbrick = None + self._mapping = {'A': 0, 'B': 1, 'C': 2} + + def onInitialize(self): + # DataPorts initialization + # + self._d_vel = RTC.TimedFloatSeq(RTC.Time(0, 0), []) + self._velIn = OpenRTM_aist.InPort("vel", self._d_vel) + self.addInPort("vel", self._velIn) + self._d_pos = RTC.TimedFloatSeq(RTC.Time(0, 0), []) + self._posOut = OpenRTM_aist.OutPort("pos", self._d_pos) + self.addOutPort("pos", self._posOut) + self._d_sens = RTC.TimedFloatSeq(RTC.Time(0, 0), []) + self._sensOut = OpenRTM_aist.OutPort("sens", self._d_sens) + self.addOutPort("sens", self._sensOut) + + # Bind variables and configuration variable + # + self.bindParameter("map", self._map, "A,B") + + # create NXTBrick object + try: + print("Connecting to NXT brick ....") + self._nxtbrick = NXTBrick.NXTBrick() + print("Connection established.") + except BaseException: + print("NXTBrick connection failed.") + return RTC.RTC_ERROR + + # set callback class + self._velIn.setOnWrite(CallBackClass(self._ntxbrick, self._map)) + + return RTC.RTC_OK + + def onFinalize(self): + self._nxtbrick.close() + + def onActivated(self, ec_id): + # reset NXTBrick's position. + self._nxtbrick.resetPosition() + + return RTC.RTC_OK + + def onDeactivated(self, ec_id): + # reset NXTBrick's position. + self._nxtbrick.resetPosition() + + return RTC.RTC_OK + + def onExecute(self, ec_id): + # get sensor data. + sensor_ = self._nxtbrick.getSensors() + if sensor_: + self._d_sens.data = sensor_ + # write sensor data to outport. + self._sensOut.write() + + # get position data. + position_ = self._nxtbrick.getMotors() + if position_: + self._d_pos.data = [position_[self._mapping[self._map[0][0]]], position_[ + self._mapping[self._map[0][1]]]] + # write position data to outport. + self._posOut.write() + + return RTC.RTC_OK def NXTRTC_callbackInit(manager): - profile = OpenRTM_aist.Properties(defaults_str=nxtrtc_spec) - manager.registerFactory(profile, - NXTRTC, - OpenRTM_aist.Delete) + profile = OpenRTM_aist.Properties(defaults_str=nxtrtc_spec) + manager.registerFactory(profile, + NXTRTC, + OpenRTM_aist.Delete) def MyModuleInit(manager): - NXTRTC_callbackInit(manager) - - # Create a component - comp = manager.createComponent("NXTRTC") + NXTRTC_callbackInit(manager) + # Create a component + comp = manager.createComponent("NXTRTC") def main(): - mgr = OpenRTM_aist.Manager.init(len(sys.argv), sys.argv) - #mgr = OpenRTM_aist.Manager.init(sys.argv) - mgr.setModuleInitProc(MyModuleInit) - mgr.activateManager() - mgr.runManager() - -if __name__ == "__main__": - main() + mgr = OpenRTM_aist.Manager.init(len(sys.argv), sys.argv) + #mgr = OpenRTM_aist.Manager.init(sys.argv) + mgr.setModuleInitProc(MyModuleInit) + mgr.activateManager() + mgr.runManager() +if __name__ == "__main__": + main() diff --git a/OpenRTM_aist/examples/NXTRTC/NXTRTC_callback.py b/OpenRTM_aist/examples/NXTRTC/NXTRTC_callback.py index fff00f47..41fc5e81 100644 --- a/OpenRTM_aist/examples/NXTRTC/NXTRTC_callback.py +++ b/OpenRTM_aist/examples/NXTRTC/NXTRTC_callback.py @@ -1,33 +1,33 @@ -#!/usr/bin/env python +#!/usr/bin/env python # -*- coding:utf-8 -*- # -*- Python -*- from __future__ import print_function +import NXTBrick +import OpenRTM_aist +import RTC import sys import time sys.path.append(".") # Import RTM module -import RTC -import OpenRTM_aist # import NXTBrick class -import NXTBrick # This module's spesification # -nxtrtc_spec = ["implementation_id", "NXTRTC", - "type_name", "NXTRTC", - "description", "NXT sample component", - "version", "0.1", - "vendor", "AIST", - "category", "example", - "activity_type", "DataFlowComponent", - "max_instance", "10", - "language", "Python", - "lang_type", "SCRIPT", +nxtrtc_spec = ["implementation_id", "NXTRTC", + "type_name", "NXTRTC", + "description", "NXT sample component", + "version", "0.1", + "vendor", "AIST", + "category", "example", + "activity_type", "DataFlowComponent", + "max_instance", "10", + "language", "Python", + "lang_type", "SCRIPT", "conf.default.map", "A,B", ""] @@ -38,120 +38,118 @@ # # when data is written in the buffer of InPort, # it is called. + + class CallBackClass: - def __init__(self, nxtbrick_, map_): - self._nxtbrick = nxtbrick_ - self._map = map_ - self._mapping = {'A':0,'B':1,'C':2} + def __init__(self, nxtbrick_, map_): + self._nxtbrick = nxtbrick_ + self._map = map_ + self._mapping = {'A': 0, 'B': 1, 'C': 2} - def __call__(self, pData): - vel_ = [0,0,0] - vel_[self._mapping[self._map[0][0]]] = pData.data[0] - vel_[self._mapping[self._map[0][1]]] = pData.data[1] - # set velocity - self._nxtbrick.setMotors(vel_) + def __call__(self, pData): + vel_ = [0, 0, 0] + vel_[self._mapping[self._map[0][0]]] = pData.data[0] + vel_[self._mapping[self._map[0][1]]] = pData.data[1] + # set velocity + self._nxtbrick.setMotors(vel_) class NXTRTC(OpenRTM_aist.DataFlowComponentBase): - def __init__(self, manager): - OpenRTM_aist.DataFlowComponentBase.__init__(self, manager) - - # initialize of configuration-data. - # - self._map = [['A', 'B']] - self._nxtbrick = None - self._mapping = {'A':0,'B':1,'C':2} - - def onInitialize(self): - # DataPorts initialization - # - self._d_vel = RTC.TimedFloatSeq(RTC.Time(0,0),[]) - self._velIn = OpenRTM_aist.InPort("vel", self._d_vel) - self.addInPort("vel",self._velIn) - self._d_pos = RTC.TimedFloatSeq(RTC.Time(0,0),[]) - self._posOut = OpenRTM_aist.OutPort("pos", self._d_pos) - self.addOutPort("pos",self._posOut) - self._d_sens = RTC.TimedFloatSeq(RTC.Time(0,0),[]) - self._sensOut = OpenRTM_aist.OutPort("sens", self._d_sens) - self.addOutPort("sens",self._sensOut) - - # Bind variables and configuration variable - # - self.bindParameter("map", self._map, "A,B") - - # create NXTBrick object - try: - print("Connecting to NXT brick ....") - self._nxtbrick = NXTBrick.NXTBrick() - print("Connection established.") - except: - print("NXTBrick connection failed.") - return RTC.RTC_ERROR - - # set callback class - self._velIn.setOnWrite(CallBackClass(self._ntxbrick,self._map)) - - return RTC.RTC_OK - - def onFinalize(self): - self._nxtbrick.close() - - def onActivated(self, ec_id): - # reset NXTBrick's position. - self._nxtbrick.resetPosition() - - return RTC.RTC_OK - - - def onDeactivated(self, ec_id): - # reset NXTBrick's position. - self._nxtbrick.resetPosition() - - return RTC.RTC_OK - - - def onExecute(self, ec_id): - # get sensor data. - sensor_ = self._nxtbrick.getSensors() - if sensor_: - self._d_sens.data = [sensor_[3]] - # write sensor data to outport. - self._sensOut.write() - - # get position data. - position_ = self._nxtbrick.getMotors() - if position_: - self._d_pos.data = [position_[self._mapping[self._map[0][0]]][9],position_[self._mapping[self._map[0][1]]][9]] - # write position data to outport. - self._posOut.write() - - return RTC.RTC_OK - + def __init__(self, manager): + OpenRTM_aist.DataFlowComponentBase.__init__(self, manager) + + # initialize of configuration-data. + # + self._map = [['A', 'B']] + self._nxtbrick = None + self._mapping = {'A': 0, 'B': 1, 'C': 2} + + def onInitialize(self): + # DataPorts initialization + # + self._d_vel = RTC.TimedFloatSeq(RTC.Time(0, 0), []) + self._velIn = OpenRTM_aist.InPort("vel", self._d_vel) + self.addInPort("vel", self._velIn) + self._d_pos = RTC.TimedFloatSeq(RTC.Time(0, 0), []) + self._posOut = OpenRTM_aist.OutPort("pos", self._d_pos) + self.addOutPort("pos", self._posOut) + self._d_sens = RTC.TimedFloatSeq(RTC.Time(0, 0), []) + self._sensOut = OpenRTM_aist.OutPort("sens", self._d_sens) + self.addOutPort("sens", self._sensOut) + + # Bind variables and configuration variable + # + self.bindParameter("map", self._map, "A,B") + + # create NXTBrick object + try: + print("Connecting to NXT brick ....") + self._nxtbrick = NXTBrick.NXTBrick() + print("Connection established.") + except BaseException: + print("NXTBrick connection failed.") + return RTC.RTC_ERROR + + # set callback class + self._velIn.setOnWrite(CallBackClass(self._ntxbrick, self._map)) + + return RTC.RTC_OK + + def onFinalize(self): + self._nxtbrick.close() + + def onActivated(self, ec_id): + # reset NXTBrick's position. + self._nxtbrick.resetPosition() + + return RTC.RTC_OK + + def onDeactivated(self, ec_id): + # reset NXTBrick's position. + self._nxtbrick.resetPosition() + + return RTC.RTC_OK + + def onExecute(self, ec_id): + # get sensor data. + sensor_ = self._nxtbrick.getSensors() + if sensor_: + self._d_sens.data = [sensor_[3]] + # write sensor data to outport. + self._sensOut.write() + + # get position data. + position_ = self._nxtbrick.getMotors() + if position_: + self._d_pos.data = [position_[self._mapping[self._map[0][0]]][9], position_[ + self._mapping[self._map[0][1]]][9]] + # write position data to outport. + self._posOut.write() + + return RTC.RTC_OK def NXTRTC_callbackInit(manager): - profile = OpenRTM_aist.Properties(defaults_str=nxtrtc_spec) - manager.registerFactory(profile, - NXTRTC, - OpenRTM_aist.Delete) + profile = OpenRTM_aist.Properties(defaults_str=nxtrtc_spec) + manager.registerFactory(profile, + NXTRTC, + OpenRTM_aist.Delete) def MyModuleInit(manager): - NXTRTC_callbackInit(manager) - - # Create a component - comp = manager.createComponent("NXTRTC") + NXTRTC_callbackInit(manager) + # Create a component + comp = manager.createComponent("NXTRTC") def main(): - mgr = OpenRTM_aist.Manager.init(len(sys.argv), sys.argv) - #mgr = OpenRTM_aist.Manager.init(sys.argv) - mgr.setModuleInitProc(MyModuleInit) - mgr.activateManager() - mgr.runManager() - -if __name__ == "__main__": - main() + mgr = OpenRTM_aist.Manager.init(len(sys.argv), sys.argv) + #mgr = OpenRTM_aist.Manager.init(sys.argv) + mgr.setModuleInitProc(MyModuleInit) + mgr.activateManager() + mgr.runManager() +if __name__ == "__main__": + main() diff --git a/OpenRTM_aist/examples/NXTRTC/__init__.py b/OpenRTM_aist/examples/NXTRTC/__init__.py index 932b7982..270be2a2 100644 --- a/OpenRTM_aist/examples/NXTRTC/__init__.py +++ b/OpenRTM_aist/examples/NXTRTC/__init__.py @@ -1 +1 @@ -# Empty file +# Empty file diff --git a/OpenRTM_aist/examples/SeqIO/SeqIn.py b/OpenRTM_aist/examples/SeqIO/SeqIn.py index f2f9086a..5dca8649 100644 --- a/OpenRTM_aist/examples/SeqIO/SeqIn.py +++ b/OpenRTM_aist/examples/SeqIO/SeqIn.py @@ -1,4 +1,4 @@ -#!/usr/bin/env python +#!/usr/bin/env python # -*- coding: utf-8 -*- # -*- Python -*- @@ -10,161 +10,162 @@ import OpenRTM_aist seqin_spec = ["implementation_id", "SeqIn", - "type_name", "SequenceInComponent", - "description", "Sequence InPort component", - "version", "1.0", - "vendor", "Shinji Kurihara", - "category", "example", - "activity_type", "DataFlowComponent", - "max_instance", "10", - "language", "Python", - "lang_type", "script", + "type_name", "SequenceInComponent", + "description", "Sequence InPort component", + "version", "1.0", + "vendor", "Shinji Kurihara", + "category", "example", + "activity_type", "DataFlowComponent", + "max_instance", "10", + "language", "Python", + "lang_type", "script", ""] class SeqIn(OpenRTM_aist.DataFlowComponentBase): - def __init__(self, manager): - OpenRTM_aist.DataFlowComponentBase.__init__(self, manager) - return - - - def onInitialize(self): - self._octet = RTC.TimedOctet(RTC.Time(0,0),0) - self._short = RTC.TimedShort(RTC.Time(0,0),0) - self._long = RTC.TimedLong(RTC.Time(0,0),0) - self._float = RTC.TimedFloat(RTC.Time(0,0),0) - self._double = RTC.TimedDouble(RTC.Time(0,0),0) - - self._octetSeq = RTC.TimedOctetSeq(RTC.Time(0,0),"") - if sys.version_info[0] == 3: - self._octetSeq.data = self._octetSeq.data.encode("utf-8") - - self._shortSeq = RTC.TimedShortSeq(RTC.Time(0,0),[]) - self._longSeq = RTC.TimedLongSeq(RTC.Time(0,0),[]) - self._floatSeq = RTC.TimedFloatSeq(RTC.Time(0,0),[]) - self._doubleSeq = RTC.TimedDoubleSeq(RTC.Time(0,0),[]) - - self._octetIn = OpenRTM_aist.InPort("Octet", self._octet) - self._shortIn = OpenRTM_aist.InPort("Short", self._short) - self._longIn = OpenRTM_aist.InPort("Long", self._long) - self._floatIn = OpenRTM_aist.InPort("Float", self._float) - self._doubleIn = OpenRTM_aist.InPort("Double", self._double) - self._octetSeqIn = OpenRTM_aist.InPort("OctetSeq", self._octetSeq) - self._shortSeqIn = OpenRTM_aist.InPort("ShortSeq", self._shortSeq) - self._longSeqIn = OpenRTM_aist.InPort("LongSeq", self._longSeq) - self._floatSeqIn = OpenRTM_aist.InPort("FloatSeq", self._floatSeq) - self._doubleSeqIn = OpenRTM_aist.InPort("DoubleSeq", self._doubleSeq) - - - # Set InPort buffer - self.addInPort("Octet", self._octetIn) - self.addInPort("Short", self._shortIn) - self.addInPort("Long", self._longIn) - self.addInPort("Float", self._floatIn) - self.addInPort("Double", self._doubleIn) - - self.addInPort("OctetSeq", self._octetSeqIn) - self.addInPort("ShortSeq", self._shortSeqIn) - self.addInPort("LongSeq", self._longSeqIn) - self.addInPort("FloatSeq", self._floatSeqIn) - self.addInPort("DoubleSeq", self._doubleSeqIn) - return RTC.RTC_OK - - - def onExecute(self, ec_id): - octet_ = self._octetIn.read() - short_ = self._shortIn.read() - long_ = self._longIn.read() - float_ = self._floatIn.read() - double_ = self._doubleIn.read() - - octetSeq_ = self._octetSeqIn.read() - shortSeq_ = self._shortSeqIn.read() - longSeq_ = self._longSeqIn.read() - floatSeq_ = self._floatSeqIn.read() - doubleSeq_ = self._doubleSeqIn.read() - - - if sys.version_info[0] == 2: - octet_data = octetSeq_.data - else: - octet_data = octetSeq_.data.decode("utf-8") - - octetSize_ = len(octet_data) - shortSize_ = len(shortSeq_.data) - longSize_ = len(longSeq_.data) - floatSize_ = len(floatSeq_.data) - doubleSize_ = len(doubleSeq_.data) - - octetSeqDisp_ = [] - for i in range(octetSize_): - octetSeqDisp_.append(ord(octet_data[i])) - - maxsize = max(octetSize_, shortSize_, longSize_, floatSize_, doubleSize_) - octetSeqDisp_ = octetSeqDisp_ + [ord("-")] * (maxsize - octetSize_) - shortSeq_.data = shortSeq_.data + ['-'] * (maxsize - shortSize_) - longSeq_.data = longSeq_.data + ['-'] * (maxsize - longSize_) - floatSeq_.data = floatSeq_.data + ['-'] * (maxsize - floatSize_) - doubleSeq_.data = doubleSeq_.data + ['-'] * (maxsize - doubleSize_) - - if 0x20 <= octet_.data < 0x7e : - octetDisp_ = chr(octet_.data) - else: - octetDisp_ = " " - print('%3.2s %10.8s %10.8s %10.8s %10.8s %10.8s' \ - % (' ', 'octet', 'short', 'long', 'float', 'double')) - print('%3.2s %7s[%s] %10.8s %10.8s %10.8s %10.8s' \ - % (' ', octet_.data, octetDisp_, short_.data, long_.data, float_.data, double_.data)) - print("-----------------------------------------------------------") - print(" Sequence Data ") - print("-----------------------------------------------------------") - for i in range(maxsize): - if 0x20 <= octetSeqDisp_[i] < 0x7e : - octetDisp_ = chr(octetSeqDisp_[i]) - else: - octetDisp_ = " " - print('%3.2s %7s[%s] %10.8s %10.8s %10.8s %10.8s' \ - % (i, octetSeqDisp_[i], octetDisp_, shortSeq_.data[i], longSeq_.data[i], floatSeq_.data[i], doubleSeq_.data[i])) - - # Moving cursor (^[[nA : n lines upward) - print("\r\r\r\r\r\r\r\r\r\r\r\r\r\r\r\r") - - time.sleep(0.5) - return RTC.RTC_OK + def __init__(self, manager): + OpenRTM_aist.DataFlowComponentBase.__init__(self, manager) + return + + def onInitialize(self): + self._octet = RTC.TimedOctet(RTC.Time(0, 0), 0) + self._short = RTC.TimedShort(RTC.Time(0, 0), 0) + self._long = RTC.TimedLong(RTC.Time(0, 0), 0) + self._float = RTC.TimedFloat(RTC.Time(0, 0), 0) + self._double = RTC.TimedDouble(RTC.Time(0, 0), 0) + + self._octetSeq = RTC.TimedOctetSeq(RTC.Time(0, 0), "") + if sys.version_info[0] == 3: + self._octetSeq.data = self._octetSeq.data.encode("utf-8") + + self._shortSeq = RTC.TimedShortSeq(RTC.Time(0, 0), []) + self._longSeq = RTC.TimedLongSeq(RTC.Time(0, 0), []) + self._floatSeq = RTC.TimedFloatSeq(RTC.Time(0, 0), []) + self._doubleSeq = RTC.TimedDoubleSeq(RTC.Time(0, 0), []) + + self._octetIn = OpenRTM_aist.InPort("Octet", self._octet) + self._shortIn = OpenRTM_aist.InPort("Short", self._short) + self._longIn = OpenRTM_aist.InPort("Long", self._long) + self._floatIn = OpenRTM_aist.InPort("Float", self._float) + self._doubleIn = OpenRTM_aist.InPort("Double", self._double) + self._octetSeqIn = OpenRTM_aist.InPort("OctetSeq", self._octetSeq) + self._shortSeqIn = OpenRTM_aist.InPort("ShortSeq", self._shortSeq) + self._longSeqIn = OpenRTM_aist.InPort("LongSeq", self._longSeq) + self._floatSeqIn = OpenRTM_aist.InPort("FloatSeq", self._floatSeq) + self._doubleSeqIn = OpenRTM_aist.InPort("DoubleSeq", self._doubleSeq) + + # Set InPort buffer + self.addInPort("Octet", self._octetIn) + self.addInPort("Short", self._shortIn) + self.addInPort("Long", self._longIn) + self.addInPort("Float", self._floatIn) + self.addInPort("Double", self._doubleIn) + + self.addInPort("OctetSeq", self._octetSeqIn) + self.addInPort("ShortSeq", self._shortSeqIn) + self.addInPort("LongSeq", self._longSeqIn) + self.addInPort("FloatSeq", self._floatSeqIn) + self.addInPort("DoubleSeq", self._doubleSeqIn) + return RTC.RTC_OK + + def onExecute(self, ec_id): + octet_ = self._octetIn.read() + short_ = self._shortIn.read() + long_ = self._longIn.read() + float_ = self._floatIn.read() + double_ = self._doubleIn.read() + + octetSeq_ = self._octetSeqIn.read() + shortSeq_ = self._shortSeqIn.read() + longSeq_ = self._longSeqIn.read() + floatSeq_ = self._floatSeqIn.read() + doubleSeq_ = self._doubleSeqIn.read() + + if sys.version_info[0] == 2: + octet_data = octetSeq_.data + else: + octet_data = octetSeq_.data.decode("utf-8") + + octetSize_ = len(octet_data) + shortSize_ = len(shortSeq_.data) + longSize_ = len(longSeq_.data) + floatSize_ = len(floatSeq_.data) + doubleSize_ = len(doubleSeq_.data) + + octetSeqDisp_ = [] + for i in range(octetSize_): + octetSeqDisp_.append(ord(octet_data[i])) + + maxsize = max( + octetSize_, + shortSize_, + longSize_, + floatSize_, + doubleSize_) + octetSeqDisp_ = octetSeqDisp_ + [ord("-")] * (maxsize - octetSize_) + shortSeq_.data = shortSeq_.data + ['-'] * (maxsize - shortSize_) + longSeq_.data = longSeq_.data + ['-'] * (maxsize - longSize_) + floatSeq_.data = floatSeq_.data + ['-'] * (maxsize - floatSize_) + doubleSeq_.data = doubleSeq_.data + ['-'] * (maxsize - doubleSize_) + + if 0x20 <= octet_.data < 0x7e: + octetDisp_ = chr(octet_.data) + else: + octetDisp_ = " " + print('%3.2s %10.8s %10.8s %10.8s %10.8s %10.8s' + % (' ', 'octet', 'short', 'long', 'float', 'double')) + print('%3.2s %7s[%s] %10.8s %10.8s %10.8s %10.8s' + % (' ', octet_.data, octetDisp_, short_.data, long_.data, float_.data, double_.data)) + print("-----------------------------------------------------------") + print(" Sequence Data ") + print("-----------------------------------------------------------") + for i in range(maxsize): + if 0x20 <= octetSeqDisp_[i] < 0x7e: + octetDisp_ = chr(octetSeqDisp_[i]) + else: + octetDisp_ = " " + print('%3.2s %7s[%s] %10.8s %10.8s %10.8s %10.8s' + % (i, octetSeqDisp_[i], octetDisp_, shortSeq_.data[i], longSeq_.data[i], floatSeq_.data[i], doubleSeq_.data[i])) + + # Moving cursor (^[[nA : n lines upward) + print("\r\r\r\r\r\r\r\r\r\r\r\r\r\r\r\r") + + time.sleep(0.5) + return RTC.RTC_OK def SeqInInit(manager): - profile = OpenRTM_aist.Properties(defaults_str=seqin_spec) - manager.registerFactory(profile, - SeqIn, - OpenRTM_aist.Delete) + profile = OpenRTM_aist.Properties(defaults_str=seqin_spec) + manager.registerFactory(profile, + SeqIn, + OpenRTM_aist.Delete) def MyModuleInit(manager): - SeqInInit(manager) + SeqInInit(manager) - # Create a component - comp = manager.createComponent("SeqIn") + # Create a component + comp = manager.createComponent("SeqIn") def main(): - # Initialize manager - mgr = OpenRTM_aist.Manager.init(sys.argv) + # Initialize manager + mgr = OpenRTM_aist.Manager.init(sys.argv) - # Set module initialization proceduer - # This procedure will be invoked in activateManager() function. - mgr.setModuleInitProc(MyModuleInit) + # Set module initialization proceduer + # This procedure will be invoked in activateManager() function. + mgr.setModuleInitProc(MyModuleInit) - # Activate manager and register to naming service - mgr.activateManager() + # Activate manager and register to naming service + mgr.activateManager() - # run the manager in blocking mode - # runManager(False) is the default - mgr.runManager() + # run the manager in blocking mode + # runManager(False) is the default + mgr.runManager() - # If you want to run the manager in non-blocking mode, do like this - # mgr.runManager(True) + # If you want to run the manager in non-blocking mode, do like this + # mgr.runManager(True) -if __name__ == "__main__": - main() +if __name__ == "__main__": + main() diff --git a/OpenRTM_aist/examples/SeqIO/SeqOut.py b/OpenRTM_aist/examples/SeqIO/SeqOut.py index edb46de6..802dfcb5 100644 --- a/OpenRTM_aist/examples/SeqIO/SeqOut.py +++ b/OpenRTM_aist/examples/SeqIO/SeqOut.py @@ -1,4 +1,4 @@ -#!/usr/bin/env python +#!/usr/bin/env python # -*- coding: utf-8 -*- # -*- Python -*- @@ -12,155 +12,153 @@ import time seqout_spec = ["implementation_id", "SeqOut", - "type_name", "SequenceOutComponent", - "description", "Sequence OutPort component", - "version", "1.0", - "vendor", "Shinji Kurihara", - "category", "example", - "activity_type", "DataFlowComponent", - "max_instance", "10", - "language", "Python", - "lang_type", "script", + "type_name", "SequenceOutComponent", + "description", "Sequence OutPort component", + "version", "1.0", + "vendor", "Shinji Kurihara", + "category", "example", + "activity_type", "DataFlowComponent", + "max_instance", "10", + "language", "Python", + "lang_type", "script", ""] - class SeqOut(OpenRTM_aist.DataFlowComponentBase): - def __init__(self, manager): - OpenRTM_aist.DataFlowComponentBase.__init__(self, manager) - return - - def onInitialize(self): - self._octet = RTC.TimedOctet(RTC.Time(0,0),0) - self._short = RTC.TimedShort(RTC.Time(0,0),0) - self._long = RTC.TimedLong(RTC.Time(0,0),0) - self._float = RTC.TimedFloat(RTC.Time(0,0),0) - self._double = RTC.TimedDouble(RTC.Time(0,0),0) - self._octetSeq = RTC.TimedOctetSeq(RTC.Time(0,0),[]) - self._shortSeq = RTC.TimedShortSeq(RTC.Time(0,0),[]) - self._longSeq = RTC.TimedLongSeq(RTC.Time(0,0),[]) - self._floatSeq = RTC.TimedFloatSeq(RTC.Time(0,0),[]) - self._doubleSeq = RTC.TimedDoubleSeq(RTC.Time(0,0),[]) - - self._octetOut = OpenRTM_aist.OutPort("Octet", self._octet) - self._shortOut = OpenRTM_aist.OutPort("Short", self._short) - self._longOut = OpenRTM_aist.OutPort("Long", self._long) - self._floatOut = OpenRTM_aist.OutPort("Float", self._float) - self._doubleOut = OpenRTM_aist.OutPort("Double", self._double) - self._octetSeqOut = OpenRTM_aist.OutPort("OctetSeq", self._octetSeq) - self._shortSeqOut = OpenRTM_aist.OutPort("ShortSeq", self._shortSeq) - self._longSeqOut = OpenRTM_aist.OutPort("LongSeq", self._longSeq) - self._floatSeqOut = OpenRTM_aist.OutPort("FloatSeq", self._floatSeq) - self._doubleSeqOut = OpenRTM_aist.OutPort("DoubleSeq", self._doubleSeq) - - - # Set OutPort buffer - self.addOutPort("Octet", self._octetOut) - self.addOutPort("Short", self._shortOut) - self.addOutPort("Long", self._longOut) - self.addOutPort("Float", self._floatOut) - self.addOutPort("Double", self._doubleOut) - - self.addOutPort("OctetSeq", self._octetSeqOut) - self.addOutPort("ShortSeq", self._shortSeqOut) - self.addOutPort("LongSeq", self._longSeqOut) - self.addOutPort("FloatSeq", self._floatSeqOut) - self.addOutPort("DoubleSeq", self._doubleSeqOut) - return RTC.RTC_OK - - - def onExecute(self, ec_id): - octetSeq = "" - shortSeq = [] - longSeq = [] - floatSeq = [] - doubleSeq = [] - - self._octet.data = int(random.uniform(0x41, 0x4a)) - self._short.data = int(random.uniform(0, 10)) - self._long.data = int(random.uniform(0, 10)) - self._float.data = float(random.uniform(0.0, 10.0)) - self._double.data = float(random.uniform(0.0, 10.0)) - - print('%3.2s %10.8s %10.8s %10.8s %10.8s %10.8s' \ - % (' ', 'octet', 'short', 'long', 'float', 'double')) - print('%3.2s %7s[%s] %10.8s %10.8s %10.8s %10.8s' \ - % (' ', self._octet.data, chr(self._octet.data), self._short.data, self._long.data, self._float.data, self._double.data)) - print("-------------------------------------------------------------") - print(" Sequence Data ") - print("-------------------------------------------------------------") - for i in range(10): - octetSeq = octetSeq + chr(int(random.uniform(0x41, 0x4a))) - shortSeq.append(int(random.uniform(0, 10))) - longSeq.append(int(random.uniform(0, 10))) - floatSeq.append(float(random.uniform(0.0, 10.0))) - doubleSeq.append(float(random.uniform(0.0, 10.0))) - print('%3.2s : %7s[%s] %10.8s %10.8s %10.8s %10.8s' \ - % (str(i), ord(octetSeq[i]), octetSeq[i], shortSeq[i], longSeq[i], floatSeq[i], doubleSeq[i])) - - # Moving cursor (^[[nA : n lines upward) - print("\r\r\r\r\r\r\r\r\r\r\r\r\r\r\r\r") - - - if sys.version_info[0] == 2: - self._octetSeq.data = octetSeq - else: - self._octetSeq.data = octetSeq.encode("utf-8") - self._shortSeq.data = shortSeq - self._longSeq.data = longSeq - self._floatSeq.data = floatSeq - self._doubleSeq.data = doubleSeq - - self._octetOut.write() - self._shortOut.write() - self._longOut.write() - self._floatOut.write() - self._doubleOut.write() - self._octetSeqOut.write() - self._shortSeqOut.write() - self._longSeqOut.write() - self._floatSeqOut.write() - self._doubleSeqOut.write() - - time.sleep(1) - - return RTC.RTC_OK + def __init__(self, manager): + OpenRTM_aist.DataFlowComponentBase.__init__(self, manager) + return + + def onInitialize(self): + self._octet = RTC.TimedOctet(RTC.Time(0, 0), 0) + self._short = RTC.TimedShort(RTC.Time(0, 0), 0) + self._long = RTC.TimedLong(RTC.Time(0, 0), 0) + self._float = RTC.TimedFloat(RTC.Time(0, 0), 0) + self._double = RTC.TimedDouble(RTC.Time(0, 0), 0) + self._octetSeq = RTC.TimedOctetSeq(RTC.Time(0, 0), []) + self._shortSeq = RTC.TimedShortSeq(RTC.Time(0, 0), []) + self._longSeq = RTC.TimedLongSeq(RTC.Time(0, 0), []) + self._floatSeq = RTC.TimedFloatSeq(RTC.Time(0, 0), []) + self._doubleSeq = RTC.TimedDoubleSeq(RTC.Time(0, 0), []) + + self._octetOut = OpenRTM_aist.OutPort("Octet", self._octet) + self._shortOut = OpenRTM_aist.OutPort("Short", self._short) + self._longOut = OpenRTM_aist.OutPort("Long", self._long) + self._floatOut = OpenRTM_aist.OutPort("Float", self._float) + self._doubleOut = OpenRTM_aist.OutPort("Double", self._double) + self._octetSeqOut = OpenRTM_aist.OutPort("OctetSeq", self._octetSeq) + self._shortSeqOut = OpenRTM_aist.OutPort("ShortSeq", self._shortSeq) + self._longSeqOut = OpenRTM_aist.OutPort("LongSeq", self._longSeq) + self._floatSeqOut = OpenRTM_aist.OutPort("FloatSeq", self._floatSeq) + self._doubleSeqOut = OpenRTM_aist.OutPort("DoubleSeq", self._doubleSeq) + + # Set OutPort buffer + self.addOutPort("Octet", self._octetOut) + self.addOutPort("Short", self._shortOut) + self.addOutPort("Long", self._longOut) + self.addOutPort("Float", self._floatOut) + self.addOutPort("Double", self._doubleOut) + + self.addOutPort("OctetSeq", self._octetSeqOut) + self.addOutPort("ShortSeq", self._shortSeqOut) + self.addOutPort("LongSeq", self._longSeqOut) + self.addOutPort("FloatSeq", self._floatSeqOut) + self.addOutPort("DoubleSeq", self._doubleSeqOut) + return RTC.RTC_OK + + def onExecute(self, ec_id): + octetSeq = "" + shortSeq = [] + longSeq = [] + floatSeq = [] + doubleSeq = [] + + self._octet.data = int(random.uniform(0x41, 0x4a)) + self._short.data = int(random.uniform(0, 10)) + self._long.data = int(random.uniform(0, 10)) + self._float.data = float(random.uniform(0.0, 10.0)) + self._double.data = float(random.uniform(0.0, 10.0)) + + print('%3.2s %10.8s %10.8s %10.8s %10.8s %10.8s' + % (' ', 'octet', 'short', 'long', 'float', 'double')) + print('%3.2s %7s[%s] %10.8s %10.8s %10.8s %10.8s' + % (' ', self._octet.data, chr(self._octet.data), self._short.data, self._long.data, self._float.data, self._double.data)) + print("-------------------------------------------------------------") + print(" Sequence Data ") + print("-------------------------------------------------------------") + for i in range(10): + octetSeq = octetSeq + chr(int(random.uniform(0x41, 0x4a))) + shortSeq.append(int(random.uniform(0, 10))) + longSeq.append(int(random.uniform(0, 10))) + floatSeq.append(float(random.uniform(0.0, 10.0))) + doubleSeq.append(float(random.uniform(0.0, 10.0))) + print('%3.2s : %7s[%s] %10.8s %10.8s %10.8s %10.8s' + % (str(i), ord(octetSeq[i]), octetSeq[i], shortSeq[i], longSeq[i], floatSeq[i], doubleSeq[i])) + + # Moving cursor (^[[nA : n lines upward) + print( + "\r\r\r\r\r\r\r\r\r\r\r\r\r\r\r\r") + + if sys.version_info[0] == 2: + self._octetSeq.data = octetSeq + else: + self._octetSeq.data = octetSeq.encode("utf-8") + self._shortSeq.data = shortSeq + self._longSeq.data = longSeq + self._floatSeq.data = floatSeq + self._doubleSeq.data = doubleSeq + + self._octetOut.write() + self._shortOut.write() + self._longOut.write() + self._floatOut.write() + self._doubleOut.write() + self._octetSeqOut.write() + self._shortSeqOut.write() + self._longSeqOut.write() + self._floatSeqOut.write() + self._doubleSeqOut.write() + + time.sleep(1) + + return RTC.RTC_OK def SeqOutInit(manager): - profile = OpenRTM_aist.Properties(defaults_str=seqout_spec) - manager.registerFactory(profile, - SeqOut, - OpenRTM_aist.Delete) - return + profile = OpenRTM_aist.Properties(defaults_str=seqout_spec) + manager.registerFactory(profile, + SeqOut, + OpenRTM_aist.Delete) + return def MyModuleInit(manager): - SeqOutInit(manager) + SeqOutInit(manager) - # Create a component - comp = manager.createComponent("SeqOut") + # Create a component + comp = manager.createComponent("SeqOut") - print("Component created") + print("Component created") def main(): - # Initialize manager - mgr = OpenRTM_aist.Manager.init(sys.argv) + # Initialize manager + mgr = OpenRTM_aist.Manager.init(sys.argv) + + # Set module initialization proceduer + # This procedure will be invoked in activateManager() function. + mgr.setModuleInitProc(MyModuleInit) - # Set module initialization proceduer - # This procedure will be invoked in activateManager() function. - mgr.setModuleInitProc(MyModuleInit) + # Activate manager and register to naming service + mgr.activateManager() - # Activate manager and register to naming service - mgr.activateManager() + # run the manager in blocking mode + # runManager(False) is the default + mgr.runManager() - # run the manager in blocking mode - # runManager(False) is the default - mgr.runManager() + # If you want to run the manager in non-blocking mode, do like this + # mgr.runManager(True) - # If you want to run the manager in non-blocking mode, do like this - # mgr.runManager(True) if __name__ == "__main__": - main() + main() diff --git a/OpenRTM_aist/examples/SeqIO/__init__.py b/OpenRTM_aist/examples/SeqIO/__init__.py index 932b7982..270be2a2 100644 --- a/OpenRTM_aist/examples/SeqIO/__init__.py +++ b/OpenRTM_aist/examples/SeqIO/__init__.py @@ -1 +1 @@ -# Empty file +# Empty file diff --git a/OpenRTM_aist/examples/Serializer/ConsoleInShort.py b/OpenRTM_aist/examples/Serializer/ConsoleInShort.py new file mode 100644 index 00000000..9dbe75d8 --- /dev/null +++ b/OpenRTM_aist/examples/Serializer/ConsoleInShort.py @@ -0,0 +1,139 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +# -*- Python -*- + +from __future__ import print_function +import sys + +import RTC +import OpenRTM_aist + +consoleinshort_spec = ["implementation_id", "ConsoleInShort", + "type_name", "ConsoleInShort", + "description", "Console input component", + "version", "1.0", + "vendor", "Shinji Kurihara", + "category", "example", + "activity_type", "DataFlowComponent", + "max_instance", "10", + "language", "Python", + "lang_type", "script", + ""] + + +class DataListener(OpenRTM_aist.ConnectorDataListenerT): + def __init__(self, name): + self._name = name + + def __del__(self): + print("dtor of ", self._name) + + def __call__(self, info, data): + print("------------------------------") + print("Listener: ", self._name) + print("Profile::name: ", info.name) + print("Profile::id: ", info.id) + print("Data: ", data.data) + print("------------------------------") + return OpenRTM_aist.ConnectorListenerStatus.NO_CHANGE, data + + +class ConnListener(OpenRTM_aist.ConnectorListener): + def __init__(self, name): + self._name = name + + def __del__(self): + print("dtor of ", self._name) + + def __call__(self, info): + print("------------------------------") + print("Listener: ", self._name) + print("Profile::name: ", info.name) + print("Profile::id: ", info.id) + print("------------------------------") + return OpenRTM_aist.ConnectorListenerStatus.NO_CHANGE + + +class ConsoleInShort(OpenRTM_aist.DataFlowComponentBase): + def __init__(self, manager): + OpenRTM_aist.DataFlowComponentBase.__init__(self, manager) + return + + def onInitialize(self): + self._data = RTC.TimedShort(RTC.Time(0, 0), 0) + self._outport = OpenRTM_aist.OutPort("out", self._data) + # Set OutPort buffer + self.addOutPort("out", self._outport) + self._outport.addConnectorDataListener(OpenRTM_aist.ConnectorDataListenerType.ON_BUFFER_WRITE, + DataListener("ON_BUFFER_WRITE")) + self._outport.addConnectorDataListener(OpenRTM_aist.ConnectorDataListenerType.ON_BUFFER_FULL, + DataListener("ON_BUFFER_FULL")) + self._outport.addConnectorDataListener(OpenRTM_aist.ConnectorDataListenerType.ON_BUFFER_WRITE_TIMEOUT, + DataListener("ON_BUFFER_WRITE_TIMEOUT")) + self._outport.addConnectorDataListener(OpenRTM_aist.ConnectorDataListenerType.ON_BUFFER_OVERWRITE, + DataListener("ON_BUFFER_OVERWRITE")) + self._outport.addConnectorDataListener(OpenRTM_aist.ConnectorDataListenerType.ON_BUFFER_READ, + DataListener("ON_BUFFER_READ")) + self._outport.addConnectorDataListener(OpenRTM_aist.ConnectorDataListenerType.ON_SEND, + DataListener("ON_SEND")) + self._outport.addConnectorDataListener(OpenRTM_aist.ConnectorDataListenerType.ON_RECEIVED, + DataListener("ON_RECEIVED")) + self._outport.addConnectorDataListener(OpenRTM_aist.ConnectorDataListenerType.ON_RECEIVER_FULL, + DataListener("ON_RECEIVER_FULL")) + self._outport.addConnectorDataListener(OpenRTM_aist.ConnectorDataListenerType.ON_RECEIVER_TIMEOUT, + DataListener("ON_RECEIVER_TIMEOUT")) + self._outport.addConnectorDataListener(OpenRTM_aist.ConnectorDataListenerType.ON_RECEIVER_ERROR, + DataListener("ON_RECEIVER_ERROR")) + + self._outport.addConnectorListener(OpenRTM_aist.ConnectorListenerType.ON_CONNECT, + ConnListener("ON_CONNECT")) + self._outport.addConnectorListener(OpenRTM_aist.ConnectorListenerType.ON_DISCONNECT, + ConnListener("ON_DISCONNECT")) + + return RTC.RTC_OK + + def onExecute(self, ec_id): + print("Please input number: ", end="") + self._data.data = int(input()) + + OpenRTM_aist.setTimestamp(self._data) + print("Sending to subscriber: ", self._data.data) + self._outport.write() + return RTC.RTC_OK + + +def ConsoleInShortInit(manager): + profile = OpenRTM_aist.Properties(defaults_str=consoleinshort_spec) + manager.registerFactory(profile, + ConsoleInShort, + OpenRTM_aist.Delete) + + +def MyModuleInit(manager): + ConsoleInShortInit(manager) + + # Create a component + comp = manager.createComponent("ConsoleInShort") + + +def main(): + # Initialize manager + mgr = OpenRTM_aist.Manager.init(sys.argv) + + # Set module initialization proceduer + # This procedure will be invoked in activateManager() function. + mgr.setModuleInitProc(MyModuleInit) + + # Activate manager and register to naming service + mgr.activateManager() + + # run the manager in blocking mode + # runManager(False) is the default + mgr.runManager() + + # If you want to run the manager in non-blocking mode, do like this + # mgr.runManager(True) + + +if __name__ == "__main__": + main() diff --git a/OpenRTM_aist/examples/Serializer/ConsoleOutDouble.py b/OpenRTM_aist/examples/Serializer/ConsoleOutDouble.py new file mode 100644 index 00000000..783cb490 --- /dev/null +++ b/OpenRTM_aist/examples/Serializer/ConsoleOutDouble.py @@ -0,0 +1,152 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +# -*- Python -*- + + +from __future__ import print_function +import sys +import time + +import RTC +import OpenRTM_aist + +consoleoutdouble_spec = ["implementation_id", "ConsoleOutDouble", + "type_name", "ConsoleOutDouble", + "description", "Console output component", + "version", "1.0", + "vendor", "Shinji Kurihara", + "category", "example", + "activity_type", "DataFlowComponent", + "max_instance", "10", + "language", "Python", + "lang_type", "script", + ""] + + +class DataListener(OpenRTM_aist.ConnectorDataListenerT): + def __init__(self, name): + self._name = name + + def __del__(self): + print("dtor of ", self._name) + + def __call__(self, info, data): + print("------------------------------") + print("Listener: ", self._name) + print("Profile::name: ", info.name) + print("Profile::id: ", info.id) + print("Data: ", data.data) + print("------------------------------") + return OpenRTM_aist.ConnectorListenerStatus.NO_CHANGE, data + + +class ConnListener(OpenRTM_aist.ConnectorListener): + def __init__(self, name): + self._name = name + + def __del__(self): + print("dtor of ", self._name) + + def __call__(self, info): + print("------------------------------") + print("Listener: ", self._name) + print("Profile::name: ", info.name) + print("Profile::id: ", info.id) + print("------------------------------") + return OpenRTM_aist.ConnectorListenerStatus.NO_CHANGE + + +class ConsoleOutDouble(OpenRTM_aist.DataFlowComponentBase): + def __init__(self, manager): + OpenRTM_aist.DataFlowComponentBase.__init__(self, manager) + return + + def onInitialize(self): + self._data = RTC.TimedDouble(RTC.Time(0, 0), 0) + self._inport = OpenRTM_aist.InPort("in", self._data) + # Set InPort buffer + self.addInPort("in", self._inport) + + self._inport.addConnectorDataListener(OpenRTM_aist.ConnectorDataListenerType.ON_BUFFER_WRITE, + DataListener("ON_BUFFER_WRITE")) + + self._inport.addConnectorDataListener(OpenRTM_aist.ConnectorDataListenerType.ON_BUFFER_FULL, + DataListener("ON_BUFFER_FULL")) + + self._inport.addConnectorDataListener(OpenRTM_aist.ConnectorDataListenerType.ON_BUFFER_WRITE_TIMEOUT, + DataListener("ON_BUFFER_WRITE_TIMEOUT")) + + self._inport.addConnectorDataListener(OpenRTM_aist.ConnectorDataListenerType.ON_BUFFER_OVERWRITE, + DataListener("ON_BUFFER_OVERWRITE")) + + self._inport.addConnectorDataListener(OpenRTM_aist.ConnectorDataListenerType.ON_BUFFER_READ, + DataListener("ON_BUFFER_READ")) + + self._inport.addConnectorDataListener(OpenRTM_aist.ConnectorDataListenerType.ON_SEND, + DataListener("ON_SEND")) + + self._inport.addConnectorDataListener(OpenRTM_aist.ConnectorDataListenerType.ON_RECEIVED, + DataListener("ON_RECEIVED")) + + self._inport.addConnectorDataListener(OpenRTM_aist.ConnectorDataListenerType.ON_RECEIVER_FULL, + DataListener("ON_RECEIVER_FULL")) + + self._inport.addConnectorDataListener(OpenRTM_aist.ConnectorDataListenerType.ON_RECEIVER_TIMEOUT, + DataListener("ON_RECEIVER_TIMEOUT")) + + self._inport.addConnectorDataListener(OpenRTM_aist.ConnectorDataListenerType.ON_RECEIVER_ERROR, + DataListener("ON_RECEIVER_ERROR")) + + self._inport.addConnectorListener(OpenRTM_aist.ConnectorListenerType.ON_CONNECT, + ConnListener("ON_CONNECT")) + self._inport.addConnectorListener(OpenRTM_aist.ConnectorListenerType.ON_DISCONNECT, + ConnListener("ON_DISCONNECT")) + + return RTC.RTC_OK + + def onExecute(self, ec_id): + + if self._inport.isNew(): + data = self._inport.read() + print("Received: ", data) + print("Received: ", data.data) + print("TimeStamp: ", data.tm.sec, "[s] ", data.tm.nsec, "[ns]") + + return RTC.RTC_OK + + +def ConsoleOutDoubleInit(manager): + profile = OpenRTM_aist.Properties(defaults_str=consoleoutdouble_spec) + manager.registerFactory(profile, + ConsoleOutDouble, + OpenRTM_aist.Delete) + + +def MyModuleInit(manager): + ConsoleOutDoubleInit(manager) + + # Create a component + comp = manager.createComponent("ConsoleOutDouble") + + +def main(): + # Initialize manager + mgr = OpenRTM_aist.Manager.init(sys.argv) + + # Set module initialization proceduer + # This procedure will be invoked in activateManager() function. + mgr.setModuleInitProc(MyModuleInit) + + # Activate manager and register to naming service + mgr.activateManager() + + # run the manager in blocking mode + # runManager(False) is the default + mgr.runManager() + + # If you want to run the manager in non-blocking mode, do like this + # mgr.runManager(True) + + +if __name__ == "__main__": + main() diff --git a/OpenRTM_aist/examples/Serializer/LongToDoubleDeserializer.py b/OpenRTM_aist/examples/Serializer/LongToDoubleDeserializer.py new file mode 100644 index 00000000..b2ffdc97 --- /dev/null +++ b/OpenRTM_aist/examples/Serializer/LongToDoubleDeserializer.py @@ -0,0 +1,32 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +# -*- Python -*- + +from __future__ import print_function +import sys + +import RTC +import OpenRTM_aist + + +class LongToDoubleDeserializer(OpenRTM_aist.CORBA_CdrMemoryStream): + def __init__(self): + OpenRTM_aist.CORBA_CdrMemoryStream.__init__(self) + return + + def serialize(self, data): + tmp_data = RTC.TimedLong(data.tm, data.data) + ret, cdr = OpenRTM_aist.CORBA_CdrMemoryStream.serialize( + self, tmp_data) + return ret, cdr + + def deserialize(self, cdr, data_type): + ret, tmp_data = OpenRTM_aist.CORBA_CdrMemoryStream.deserialize( + self, cdr, RTC.TimedLong) + data = RTC.TimedDouble(tmp_data.tm, float(tmp_data.data)) + return ret, data + + +def LongToDoubleDeserializerInit(mgr): + OpenRTM_aist.SerializerFactories.instance().addSerializer( + "cdr:RTC/TimedLong:RTC/TimedDouble", LongToDoubleDeserializer, RTC.TimedDouble) # addSerializer関数の第1引数で登録名を設定。独自シリアライザを利用するときはこの名前を使用する。 diff --git a/OpenRTM_aist/examples/Serializer/ShortToDoubleDeserializer.py b/OpenRTM_aist/examples/Serializer/ShortToDoubleDeserializer.py new file mode 100644 index 00000000..fd9e688e --- /dev/null +++ b/OpenRTM_aist/examples/Serializer/ShortToDoubleDeserializer.py @@ -0,0 +1,26 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +# -*- Python -*- + +from __future__ import print_function +import sys + +import RTC +import OpenRTM_aist + + +class ShortToDoubleDeserializer(OpenRTM_aist.CORBA_CdrMemoryStream): + def __init__(self): + OpenRTM_aist.CORBA_CdrMemoryStream.__init__(self) + return + + def deserialize(self, cdr, data_type): + ret, tmp_data = OpenRTM_aist.CORBA_CdrMemoryStream.deserialize( + self, cdr, RTC.TimedShort) + data = RTC.TimedDouble(tmp_data.tm, float(tmp_data.data)) + return ret, data + + +def ShortToDoubleDeserializerInit(mgr): + OpenRTM_aist.SerializerFactories.instance().addSerializer( + "cdr:RTC/TimedShort:RTC/TimedDouble", ShortToDoubleDeserializer, RTC.TimedDouble) # addSerializer関数の第1引数で登録名を設定。独自シリアライザを利用するときはこの名前を使用する。 diff --git a/OpenRTM_aist/examples/Serializer/ShortToDoubleSerializer.py b/OpenRTM_aist/examples/Serializer/ShortToDoubleSerializer.py new file mode 100644 index 00000000..b3ce1902 --- /dev/null +++ b/OpenRTM_aist/examples/Serializer/ShortToDoubleSerializer.py @@ -0,0 +1,26 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +# -*- Python -*- + +from __future__ import print_function +import sys + +import RTC +import OpenRTM_aist + + +class ShortToDoubleSerializer(OpenRTM_aist.CORBA_CdrMemoryStream): + def __init__(self): + OpenRTM_aist.CORBA_CdrMemoryStream.__init__(self) + return + + def serialize(self, data): + tmp_data = RTC.TimedDouble(data.tm, float(data.data)) + ret, cdr = OpenRTM_aist.CORBA_CdrMemoryStream.serialize( + self, tmp_data) + return ret, cdr + + +def ShortToDoubleSerializerInit(mgr): + OpenRTM_aist.SerializerFactories.instance().addSerializer( + "cdr:RTC/TimedDouble:RTC/TimedShort", ShortToDoubleSerializer, RTC.TimedShort) # addSerializer関数の第1引数で登録名を設定。独自シリアライザを利用するときはこの名前を使用する。 diff --git a/OpenRTM_aist/examples/Serializer/ShortToLongSerializer.py b/OpenRTM_aist/examples/Serializer/ShortToLongSerializer.py new file mode 100644 index 00000000..d625a09f --- /dev/null +++ b/OpenRTM_aist/examples/Serializer/ShortToLongSerializer.py @@ -0,0 +1,32 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +# -*- Python -*- + +from __future__ import print_function +import sys + +import RTC +import OpenRTM_aist + + +class ShortToLongSerializer(OpenRTM_aist.CORBA_CdrMemoryStream): + def __init__(self): + OpenRTM_aist.CORBA_CdrMemoryStream.__init__(self) + return + + def serialize(self, data): + tmp_data = RTC.TimedLong(data.tm, data.data) + ret, cdr = OpenRTM_aist.CORBA_CdrMemoryStream.serialize( + self, tmp_data) + return ret, cdr + + def deserialize(self, cdr, data_type): + ret, tmp_data = OpenRTM_aist.CORBA_CdrMemoryStream.deserialize( + self, cdr, RTC.TimedLong) + data = RTC.TimedShort(tmp_data.tm, int(tmp_data.data)) + return ret, data + + +def ShortToLongSerializerInit(mgr): + OpenRTM_aist.SerializerFactories.instance().addSerializer( + "cdr:RTC/TimedLong:RTC/TimedShort", ShortToLongSerializer, RTC.TimedShort) # addSerializer関数の第1引数で登録名を設定。独自シリアライザを利用するときはこの名前を使用する。 diff --git a/OpenRTM_aist/examples/Serializer/TestSerializer.py b/OpenRTM_aist/examples/Serializer/TestSerializer.py new file mode 100644 index 00000000..eaf3d81a --- /dev/null +++ b/OpenRTM_aist/examples/Serializer/TestSerializer.py @@ -0,0 +1,34 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +# -*- Python -*- + +from __future__ import print_function +import sys + +import RTC +import OpenRTM_aist + + +class TestSerializer(OpenRTM_aist.CORBA_CdrMemoryStream): + def __init__(self): + OpenRTM_aist.CORBA_CdrMemoryStream.__init__(self) + return + + def serialize(self, data): + tmp_data = RTC.TimedLong(data.tm, data.data) + ret, cdr = OpenRTM_aist.CORBA_CdrMemoryStream.serialize( + self, tmp_data) + return ret, cdr + + def deserialize(self, cdr, data_type): + ret, tmp_data = OpenRTM_aist.CORBA_CdrMemoryStream.deserialize( + self, cdr, RTC.TimedLong) + data = RTC.TimedDouble(tmp_data.tm, float(tmp_data.data)) + return ret, data + + +def TestSerializerInit(mgr): + OpenRTM_aist.SerializerFactories.instance().addSerializer("test:dummydata", # addFactory関数の第1引数で登録名を設定。独自シリアライザを利用するときはこの名前を使用する。 + TestSerializer, RTC.TimedDouble) + OpenRTM_aist.SerializerFactories.instance().addSerializer("test:dummydata", # addFactory関数の第1引数で登録名を設定。独自シリアライザを利用するときはこの名前を使用する。 + TestSerializer, RTC.TimedShort) diff --git a/OpenRTM_aist/examples/Serializer/rtc.conf b/OpenRTM_aist/examples/Serializer/rtc.conf new file mode 100644 index 00000000..60bc8986 --- /dev/null +++ b/OpenRTM_aist/examples/Serializer/rtc.conf @@ -0,0 +1,10 @@ +corba.nameservers: localhost +naming.formats: %n.rtc +logger.enable: YES +logger.file_name: stdout +logger.log_level: ERROR +manager.modules.load_path: . +manager.modules.preload: ConsoleOutDouble, ShortToDoubleDeserializer +manager.components.precreate: ConsoleOutDouble +manager.components.preconnect: ConsoleOutDouble0.in?port=ConsoleInShort0.out&inport.marshaling_type=cdr:RTC/TimedShort:RTC/TimedDouble&outport.marshaling_type=cdr +manager.components.preactivation: ConsoleOutDouble0, ConsoleInShort0 diff --git a/OpenRTM_aist/examples/Serializer/rtc_in_serializer.conf b/OpenRTM_aist/examples/Serializer/rtc_in_serializer.conf new file mode 100644 index 00000000..e22c07e8 --- /dev/null +++ b/OpenRTM_aist/examples/Serializer/rtc_in_serializer.conf @@ -0,0 +1,10 @@ +corba.nameservers: localhost +naming.formats: %n.rtc +logger.enable: YES +logger.file_name: stdout +logger.log_level: ERROR +manager.modules.load_path: . +manager.modules.preload: ConsoleOutDouble, ShortToDoubleDeserializer +manager.components.precreate: ConsoleOutDouble +#manager.components.preconnect: ConsoleOutDouble0.in?port=ConsoleInShort0.out&inport.marshaling_type=cdr:RTC/TimedShort:RTC/TimedDouble&outport.marshaling_type=cdr +#manager.components.preactivation: ConsoleOutDouble0, ConsoleInShort0 diff --git a/OpenRTM_aist/examples/Serializer/rtc_inout_serializer.conf b/OpenRTM_aist/examples/Serializer/rtc_inout_serializer.conf new file mode 100644 index 00000000..93e000b5 --- /dev/null +++ b/OpenRTM_aist/examples/Serializer/rtc_inout_serializer.conf @@ -0,0 +1,10 @@ +corba.nameservers: localhost +naming.formats: %n.rtc +logger.enable: YES +logger.file_name: stdout +logger.log_level: ERROR +manager.modules.load_path: . +manager.modules.preload: ConsoleOutDouble, ShortToLongSerializer, LongToDoubleDeserializer +manager.components.precreate: ConsoleOutDouble +#manager.components.preconnect: ConsoleOutDouble0.in?port=ConsoleInShort0.out&outport.marshaling_type=cdr:RTC/TimedLong:RTC/TimedShort&inport.marshaling_type=cdr:RTC/TimedLong:RTC/TimedDouble +#manager.components.preactivation: ConsoleOutDouble0, ConsoleInShort0 diff --git a/OpenRTM_aist/examples/Serializer/rtc_original_serializer.conf b/OpenRTM_aist/examples/Serializer/rtc_original_serializer.conf new file mode 100644 index 00000000..6bf16890 --- /dev/null +++ b/OpenRTM_aist/examples/Serializer/rtc_original_serializer.conf @@ -0,0 +1,10 @@ +corba.nameservers: localhost +naming.formats: %n.rtc +logger.enable: YES +logger.file_name: stdout +logger.log_level: ERROR +manager.modules.load_path: . +manager.modules.preload: ConsoleOutDouble, TestSerializer +manager.components.precreate: ConsoleOutDouble +#manager.components.preconnect: ConsoleOutDouble0.in?port=ConsoleInShort0.out&outport.marshaling_type=test:dummydata&inport.marshaling_type=test:dummydata +#manager.components.preactivation: ConsoleOutDouble0, ConsoleInShort0 diff --git a/OpenRTM_aist/examples/Serializer/rtc_out_serializer.conf b/OpenRTM_aist/examples/Serializer/rtc_out_serializer.conf new file mode 100644 index 00000000..48f32261 --- /dev/null +++ b/OpenRTM_aist/examples/Serializer/rtc_out_serializer.conf @@ -0,0 +1,10 @@ +corba.nameservers: localhost +naming.formats: %n.rtc +logger.enable: YES +logger.file_name: stdout +logger.log_level: ERROR +manager.modules.load_path: . +manager.modules.preload: ConsoleOutDouble, ShortToDoubleSerializer +manager.components.precreate: ConsoleOutDouble +#manager.components.preconnect: ConsoleOutDouble0.in?port=ConsoleInShort0.out&outport.marshaling_type=cdr:RTC/TimedDouble:RTC/TimedShort&inport.marshaling_type=cdr +#manager.components.preactivation: ConsoleOutDouble0, ConsoleInShort0 diff --git a/OpenRTM_aist/examples/SimpleIO/Connector.py b/OpenRTM_aist/examples/SimpleIO/Connector.py index 2fc8a736..7d8a6e51 100644 --- a/OpenRTM_aist/examples/SimpleIO/Connector.py +++ b/OpenRTM_aist/examples/SimpleIO/Connector.py @@ -1,4 +1,4 @@ -#!/usr/bin/env python +#!/usr/bin/env python # -*- coding: utf-8 -*- # -*- Python -*- @@ -11,129 +11,128 @@ import RTC import OpenRTM_aist + def usage(): - print("usage: ConnectorComp [options]") - print(" --flush ") - print(": Set subscription type Flush") - print(" --new ") - print(": Set subscription type New") - print(" --periodic [Hz] ") - print(": Set subscription type Periodic \n") - print("exsample:") - print(" ConnectorComp --flush") - print(" ConnectorComp --new") - print(" ConnectorComp --new --policy ALL") - print(" ConnectorComp --new --policy SKIP --skip 100") - print(" ConnectorComp --periodic 10") - print(" ConnectorComp --periodic 10 --policy FIFO") - print(" ConnectorComp --periodic 10 --policy NEW \n") + print("usage: ConnectorComp [options]") + print(" --flush ") + print(": Set subscription type Flush") + print(" --new ") + print(": Set subscription type New") + print(" --periodic [Hz] ") + print(": Set subscription type Periodic \n") + print("exsample:") + print(" ConnectorComp --flush") + print(" ConnectorComp --new") + print(" ConnectorComp --new --policy ALL") + print(" ConnectorComp --new --policy SKIP --skip 100") + print(" ConnectorComp --periodic 10") + print(" ConnectorComp --periodic 10 --policy FIFO") + print(" ConnectorComp --periodic 10 --policy NEW \n") + def main(): - # initialization of ORB - orb = CORBA.ORB_init(sys.argv) - - # get NamingService - naming = OpenRTM_aist.CorbaNaming(orb, "localhost") - - conin = OpenRTM_aist.CorbaConsumer() - conout = OpenRTM_aist.CorbaConsumer() - - # find ConsoleIn0 component - conin.setObject(naming.resolve("ConsoleIn0.rtc")) - - # get ports - inobj = conin.getObject()._narrow(RTC.RTObject) - pin = inobj.get_ports() - pin[0].disconnect_all() - - - # find ConsoleOut0 component - conout.setObject(naming.resolve("ConsoleOut0.rtc")) - - # get ports - outobj = conout.getObject()._narrow(RTC.RTObject) - pout = outobj.get_ports() - pout[0].disconnect_all() - - - # subscription type - subs_type = "flush" - period = "1.0" - push_policy = "new" - skip_count = "0" - - for arg in sys.argv[1:]: - if arg == "--flush": - subs_type = "flush" - break - - elif arg == "--new": - subs_type = "new" - if len(sys.argv) > 2: - push_policy = OpenRTM_aist.normalize([sys.argv[3]]) - if push_policy == "skip": - skip_count = sys.argv[5] - break - - elif arg == "--periodic": - subs_type = "periodic" - period = sys.argv[2] - if len(sys.argv) > 3: - push_policy = OpenRTM_aist.normalize([sys.argv[4]]) - if push_policy == "skip": - skip_count = sys.argv[6] - break - - # elif sbus_type == "periodic" and type(arg) == float: - # period = srt(arg) - # break - - else: - usage() - - print("Subscription Type: ", subs_type) - print("Period: ", period, " [Hz]") - print("push policy: ", push_policy) - print("skip count: ", skip_count) - - # connect ports - conprof = RTC.ConnectorProfile("connector0", "", [pin[0],pout[0]], []) - OpenRTM_aist.CORBA_SeqUtil.push_back(conprof.properties, - OpenRTM_aist.NVUtil.newNV("dataport.interface_type", - "corba_cdr")) - - OpenRTM_aist.CORBA_SeqUtil.push_back(conprof.properties, - OpenRTM_aist.NVUtil.newNV("dataport.dataflow_type", - "push")) - - OpenRTM_aist.CORBA_SeqUtil.push_back(conprof.properties, - OpenRTM_aist.NVUtil.newNV("dataport.subscription_type", - subs_type)) - - if subs_type == "periodic": + # initialization of ORB + orb = CORBA.ORB_init(sys.argv) + + # get NamingService + naming = OpenRTM_aist.CorbaNaming(orb, "localhost") + + conin = OpenRTM_aist.CorbaConsumer() + conout = OpenRTM_aist.CorbaConsumer() + + # find ConsoleIn0 component + conin.setObject(naming.resolve("ConsoleIn0.rtc")) + + # get ports + inobj = conin.getObject()._narrow(RTC.RTObject) + pin = inobj.get_ports() + pin[0].disconnect_all() + + # find ConsoleOut0 component + conout.setObject(naming.resolve("ConsoleOut0.rtc")) + + # get ports + outobj = conout.getObject()._narrow(RTC.RTObject) + pout = outobj.get_ports() + pout[0].disconnect_all() + + # subscription type + subs_type = "flush" + period = "1.0" + push_policy = "new" + skip_count = "0" + + for arg in sys.argv[1:]: + if arg == "--flush": + subs_type = "flush" + break + + elif arg == "--new": + subs_type = "new" + if len(sys.argv) > 2: + push_policy = OpenRTM_aist.normalize([sys.argv[3]]) + if push_policy == "skip": + skip_count = sys.argv[5] + break + + elif arg == "--periodic": + subs_type = "periodic" + period = sys.argv[2] + if len(sys.argv) > 3: + push_policy = OpenRTM_aist.normalize([sys.argv[4]]) + if push_policy == "skip": + skip_count = sys.argv[6] + break + + # elif sbus_type == "periodic" and type(arg) == float: + # period = srt(arg) + # break + + else: + usage() + + print("Subscription Type: ", subs_type) + print("Period: ", period, " [Hz]") + print("push policy: ", push_policy) + print("skip count: ", skip_count) + + # connect ports + conprof = RTC.ConnectorProfile("connector0", "", [pin[0], pout[0]], []) + OpenRTM_aist.CORBA_SeqUtil.push_back(conprof.properties, + OpenRTM_aist.NVUtil.newNV("dataport.interface_type", + "corba_cdr")) + OpenRTM_aist.CORBA_SeqUtil.push_back(conprof.properties, - OpenRTM_aist.NVUtil.newNV("dataport.publisher.push_rate", + OpenRTM_aist.NVUtil.newNV("dataport.dataflow_type", + "push")) + + OpenRTM_aist.CORBA_SeqUtil.push_back(conprof.properties, + OpenRTM_aist.NVUtil.newNV("dataport.subscription_type", + subs_type)) + + if subs_type == "periodic": + OpenRTM_aist.CORBA_SeqUtil.push_back(conprof.properties, + OpenRTM_aist.NVUtil.newNV("dataport.publisher.push_rate", period)) - OpenRTM_aist.CORBA_SeqUtil.push_back(conprof.properties, - OpenRTM_aist.NVUtil.newNV("dataport.publisher.push_policy", - push_policy)) - if push_policy == "skip": OpenRTM_aist.CORBA_SeqUtil.push_back(conprof.properties, - OpenRTM_aist.NVUtil.newNV("dataport.publisher.skip_count", - skip_count)) + OpenRTM_aist.NVUtil.newNV("dataport.publisher.push_policy", + push_policy)) + if push_policy == "skip": + OpenRTM_aist.CORBA_SeqUtil.push_back(conprof.properties, + OpenRTM_aist.NVUtil.newNV("dataport.publisher.skip_count", + skip_count)) + ret, conprof = pin[0].connect(conprof) - ret,conprof = pin[0].connect(conprof) - - # activate ConsoleIn0 - eclistin = inobj.get_owned_contexts() - eclistin[0].activate_component(inobj) + # activate ConsoleIn0 + eclistin = inobj.get_owned_contexts() + eclistin[0].activate_component(inobj) - # activate ConsoleOut0 - eclistout = outobj.get_owned_contexts() - eclistout[0].activate_component(outobj) + # activate ConsoleOut0 + eclistout = outobj.get_owned_contexts() + eclistout[0].activate_component(outobj) if __name__ == "__main__": - main() + main() diff --git a/OpenRTM_aist/examples/SimpleIO/ConsoleIn.py b/OpenRTM_aist/examples/SimpleIO/ConsoleIn.py index 1e35d9ce..676b78b3 100644 --- a/OpenRTM_aist/examples/SimpleIO/ConsoleIn.py +++ b/OpenRTM_aist/examples/SimpleIO/ConsoleIn.py @@ -1,4 +1,4 @@ -#!/usr/bin/env python +#!/usr/bin/env python # -*- coding: utf-8 -*- # -*- Python -*- @@ -9,130 +9,131 @@ import OpenRTM_aist consolein_spec = ["implementation_id", "ConsoleIn", - "type_name", "ConsoleIn", - "description", "Console input component", - "version", "1.0", - "vendor", "Shinji Kurihara", - "category", "example", - "activity_type", "DataFlowComponent", - "max_instance", "10", - "language", "Python", - "lang_type", "script", + "type_name", "ConsoleIn", + "description", "Console input component", + "version", "1.0", + "vendor", "Shinji Kurihara", + "category", "example", + "activity_type", "DataFlowComponent", + "max_instance", "10", + "language", "Python", + "lang_type", "script", ""] class DataListener(OpenRTM_aist.ConnectorDataListenerT): - def __init__(self, name): - self._name = name - - def __del__(self): - print("dtor of ", self._name) - - def __call__(self, info, cdrdata): - data = OpenRTM_aist.ConnectorDataListenerT.__call__(self, info, cdrdata, RTC.TimedLong(RTC.Time(0,0),0)) - print("------------------------------") - print("Listener: ", self._name) - print("Profile::name: ", info.name) - print("Profile::id: ", info.id) - print("Data: ", data.data) - print("------------------------------") - return OpenRTM_aist.ConnectorListenerStatus.NO_CHANGE - + def __init__(self, name): + self._name = name + + def __del__(self): + print("dtor of ", self._name) + + def __call__(self, info, data): + print("------------------------------") + print("Listener: ", self._name) + print("Profile::name: ", info.name) + print("Profile::id: ", info.id) + print("Data: ", data.data) + print("------------------------------") + return OpenRTM_aist.ConnectorListenerStatus.NO_CHANGE, data + + class ConnListener(OpenRTM_aist.ConnectorListener): - def __init__(self, name): - self._name = name + def __init__(self, name): + self._name = name - def __del__(self): - print("dtor of ", self._name) + def __del__(self): + print("dtor of ", self._name) - def __call__(self, info): - print("------------------------------") - print("Listener: ", self._name) - print("Profile::name: ", info.name) - print("Profile::id: ", info.id) - print("------------------------------") - return OpenRTM_aist.ConnectorListenerStatus.NO_CHANGE + def __call__(self, info): + print("------------------------------") + print("Listener: ", self._name) + print("Profile::name: ", info.name) + print("Profile::id: ", info.id) + print("------------------------------") + return OpenRTM_aist.ConnectorListenerStatus.NO_CHANGE class ConsoleIn(OpenRTM_aist.DataFlowComponentBase): - def __init__(self, manager): - OpenRTM_aist.DataFlowComponentBase.__init__(self, manager) - return - - def onInitialize(self): - self._data = RTC.TimedLong(RTC.Time(0,0),0) - self._outport = OpenRTM_aist.OutPort("out", self._data) - # Set OutPort buffer - self.addOutPort("out", self._outport) - self._outport.addConnectorDataListener(OpenRTM_aist.ConnectorDataListenerType.ON_BUFFER_WRITE, - DataListener("ON_BUFFER_WRITE")) - self._outport.addConnectorDataListener(OpenRTM_aist.ConnectorDataListenerType.ON_BUFFER_FULL, - DataListener("ON_BUFFER_FULL")) - self._outport.addConnectorDataListener(OpenRTM_aist.ConnectorDataListenerType.ON_BUFFER_WRITE_TIMEOUT, - DataListener("ON_BUFFER_WRITE_TIMEOUT")) - self._outport.addConnectorDataListener(OpenRTM_aist.ConnectorDataListenerType.ON_BUFFER_OVERWRITE, - DataListener("ON_BUFFER_OVERWRITE")) - self._outport.addConnectorDataListener(OpenRTM_aist.ConnectorDataListenerType.ON_BUFFER_READ, - DataListener("ON_BUFFER_READ")) - self._outport.addConnectorDataListener(OpenRTM_aist.ConnectorDataListenerType.ON_SEND, - DataListener("ON_SEND")) - self._outport.addConnectorDataListener(OpenRTM_aist.ConnectorDataListenerType.ON_RECEIVED, - DataListener("ON_RECEIVED")) - self._outport.addConnectorDataListener(OpenRTM_aist.ConnectorDataListenerType.ON_RECEIVER_FULL, - DataListener("ON_RECEIVER_FULL")) - self._outport.addConnectorDataListener(OpenRTM_aist.ConnectorDataListenerType.ON_RECEIVER_TIMEOUT, - DataListener("ON_RECEIVER_TIMEOUT")) - self._outport.addConnectorDataListener(OpenRTM_aist.ConnectorDataListenerType.ON_RECEIVER_ERROR, - DataListener("ON_RECEIVER_ERROR")) - - self._outport.addConnectorListener(OpenRTM_aist.ConnectorListenerType.ON_CONNECT, - ConnListener("ON_CONNECT")) - self._outport.addConnectorListener(OpenRTM_aist.ConnectorListenerType.ON_DISCONNECT, - ConnListener("ON_DISCONNECT")) - - return RTC.RTC_OK - - - def onExecute(self, ec_id): - print("Please input number: ",end="") - self._data.data = int(input()) - - OpenRTM_aist.setTimestamp(self._data) - print("Sending to subscriber: ", self._data.data) - self._outport.write() - return RTC.RTC_OK + def __init__(self, manager): + OpenRTM_aist.DataFlowComponentBase.__init__(self, manager) + return + + def onInitialize(self): + self._data = RTC.TimedLong(RTC.Time(0, 0), 0) + self._outport = OpenRTM_aist.OutPort("out", self._data) + # Set OutPort buffer + self.addOutPort("out", self._outport) + self._outport.addConnectorDataListener(OpenRTM_aist.ConnectorDataListenerType.ON_BUFFER_WRITE, + DataListener("ON_BUFFER_WRITE")) + self._outport.addConnectorDataListener(OpenRTM_aist.ConnectorDataListenerType.ON_BUFFER_FULL, + DataListener("ON_BUFFER_FULL")) + self._outport.addConnectorDataListener(OpenRTM_aist.ConnectorDataListenerType.ON_BUFFER_WRITE_TIMEOUT, + DataListener("ON_BUFFER_WRITE_TIMEOUT")) + self._outport.addConnectorDataListener(OpenRTM_aist.ConnectorDataListenerType.ON_BUFFER_OVERWRITE, + DataListener("ON_BUFFER_OVERWRITE")) + self._outport.addConnectorDataListener(OpenRTM_aist.ConnectorDataListenerType.ON_BUFFER_READ, + DataListener("ON_BUFFER_READ")) + self._outport.addConnectorDataListener(OpenRTM_aist.ConnectorDataListenerType.ON_SEND, + DataListener("ON_SEND")) + self._outport.addConnectorDataListener(OpenRTM_aist.ConnectorDataListenerType.ON_RECEIVED, + DataListener("ON_RECEIVED")) + self._outport.addConnectorDataListener(OpenRTM_aist.ConnectorDataListenerType.ON_RECEIVER_FULL, + DataListener("ON_RECEIVER_FULL")) + self._outport.addConnectorDataListener(OpenRTM_aist.ConnectorDataListenerType.ON_RECEIVER_TIMEOUT, + DataListener("ON_RECEIVER_TIMEOUT")) + self._outport.addConnectorDataListener(OpenRTM_aist.ConnectorDataListenerType.ON_RECEIVER_ERROR, + DataListener("ON_RECEIVER_ERROR")) + + self._outport.addConnectorListener(OpenRTM_aist.ConnectorListenerType.ON_CONNECT, + ConnListener("ON_CONNECT")) + self._outport.addConnectorListener(OpenRTM_aist.ConnectorListenerType.ON_DISCONNECT, + ConnListener("ON_DISCONNECT")) + + return RTC.RTC_OK + + def onExecute(self, ec_id): + print("Please input number: ", end="") + self._data.data = int(input()) + + OpenRTM_aist.setTimestamp(self._data) + print("Sending to subscriber: ", self._data.data) + self._outport.write() + return RTC.RTC_OK def ConsoleInInit(manager): - profile = OpenRTM_aist.Properties(defaults_str=consolein_spec) - manager.registerFactory(profile, - ConsoleIn, - OpenRTM_aist.Delete) + profile = OpenRTM_aist.Properties(defaults_str=consolein_spec) + manager.registerFactory(profile, + ConsoleIn, + OpenRTM_aist.Delete) def MyModuleInit(manager): - ConsoleInInit(manager) + ConsoleInInit(manager) + + # Create a component + comp = manager.createComponent("ConsoleIn") - # Create a component - comp = manager.createComponent("ConsoleIn") def main(): - # Initialize manager - mgr = OpenRTM_aist.Manager.init(sys.argv) + # Initialize manager + mgr = OpenRTM_aist.Manager.init(sys.argv) + + # Set module initialization proceduer + # This procedure will be invoked in activateManager() function. + mgr.setModuleInitProc(MyModuleInit) - # Set module initialization proceduer - # This procedure will be invoked in activateManager() function. - mgr.setModuleInitProc(MyModuleInit) + # Activate manager and register to naming service + mgr.activateManager() - # Activate manager and register to naming service - mgr.activateManager() + # run the manager in blocking mode + # runManager(False) is the default + mgr.runManager() - # run the manager in blocking mode - # runManager(False) is the default - mgr.runManager() + # If you want to run the manager in non-blocking mode, do like this + # mgr.runManager(True) - # If you want to run the manager in non-blocking mode, do like this - # mgr.runManager(True) if __name__ == "__main__": - main() + main() diff --git a/OpenRTM_aist/examples/SimpleIO/ConsoleOut.py b/OpenRTM_aist/examples/SimpleIO/ConsoleOut.py index d3fd66fc..a7f40043 100644 --- a/OpenRTM_aist/examples/SimpleIO/ConsoleOut.py +++ b/OpenRTM_aist/examples/SimpleIO/ConsoleOut.py @@ -1,4 +1,4 @@ -#!/usr/bin/env python +#!/usr/bin/env python # -*- coding: utf-8 -*- # -*- Python -*- @@ -11,143 +11,142 @@ import OpenRTM_aist consoleout_spec = ["implementation_id", "ConsoleOut", - "type_name", "ConsoleOut", - "description", "Console output component", - "version", "1.0", - "vendor", "Shinji Kurihara", - "category", "example", - "activity_type", "DataFlowComponent", - "max_instance", "10", - "language", "Python", - "lang_type", "script", + "type_name", "ConsoleOut", + "description", "Console output component", + "version", "1.0", + "vendor", "Shinji Kurihara", + "category", "example", + "activity_type", "DataFlowComponent", + "max_instance", "10", + "language", "Python", + "lang_type", "script", ""] class DataListener(OpenRTM_aist.ConnectorDataListenerT): - def __init__(self, name): - self._name = name + def __init__(self, name): + self._name = name - def __del__(self): - print("dtor of ", self._name) + def __del__(self): + print("dtor of ", self._name) - def __call__(self, info, cdrdata): - data = OpenRTM_aist.ConnectorDataListenerT.__call__(self, info, cdrdata, RTC.TimedLong(RTC.Time(0,0),0)) - print("------------------------------") - print("Listener: ", self._name) - print("Profile::name: ", info.name) - print("Profile::id: ", info.id) - print("Data: ", data.data) - print("------------------------------") - return OpenRTM_aist.ConnectorListenerStatus.NO_CHANGE + def __call__(self, info, data): + print("------------------------------") + print("Listener: ", self._name) + print("Profile::name: ", info.name) + print("Profile::id: ", info.id) + print("Data: ", data.data) + print("------------------------------") + return OpenRTM_aist.ConnectorListenerStatus.NO_CHANGE, data class ConnListener(OpenRTM_aist.ConnectorListener): - def __init__(self, name): - self._name = name + def __init__(self, name): + self._name = name - def __del__(self): - print("dtor of ", self._name) - - def __call__(self, info): - print("------------------------------") - print("Listener: ", self._name) - print("Profile::name: ", info.name) - print("Profile::id: ", info.id) - print("------------------------------") - return OpenRTM_aist.ConnectorListenerStatus.NO_CHANGE + def __del__(self): + print("dtor of ", self._name) + def __call__(self, info): + print("------------------------------") + print("Listener: ", self._name) + print("Profile::name: ", info.name) + print("Profile::id: ", info.id) + print("------------------------------") + return OpenRTM_aist.ConnectorListenerStatus.NO_CHANGE class ConsoleOut(OpenRTM_aist.DataFlowComponentBase): - def __init__(self, manager): - OpenRTM_aist.DataFlowComponentBase.__init__(self, manager) - return - - def onInitialize(self): - self._data = RTC.TimedLong(RTC.Time(0,0),0) - self._inport = OpenRTM_aist.InPort("in", self._data) - # Set InPort buffer - self.addInPort("in", self._inport) + def __init__(self, manager): + OpenRTM_aist.DataFlowComponentBase.__init__(self, manager) + return - self._inport.addConnectorDataListener(OpenRTM_aist.ConnectorDataListenerType.ON_BUFFER_WRITE, - DataListener("ON_BUFFER_WRITE")) + def onInitialize(self): + self._data = RTC.TimedLong(RTC.Time(0, 0), 0) + self._inport = OpenRTM_aist.InPort("in", self._data) + # Set InPort buffer + self.addInPort("in", self._inport) + self._inport.addConnectorDataListener(OpenRTM_aist.ConnectorDataListenerType.ON_BUFFER_WRITE, + DataListener("ON_BUFFER_WRITE")) - self._inport.addConnectorDataListener(OpenRTM_aist.ConnectorDataListenerType.ON_BUFFER_FULL, - DataListener("ON_BUFFER_FULL")) + self._inport.addConnectorDataListener(OpenRTM_aist.ConnectorDataListenerType.ON_BUFFER_FULL, + DataListener("ON_BUFFER_FULL")) - self._inport.addConnectorDataListener(OpenRTM_aist.ConnectorDataListenerType.ON_BUFFER_WRITE_TIMEOUT, - DataListener("ON_BUFFER_WRITE_TIMEOUT")) + self._inport.addConnectorDataListener(OpenRTM_aist.ConnectorDataListenerType.ON_BUFFER_WRITE_TIMEOUT, + DataListener("ON_BUFFER_WRITE_TIMEOUT")) - self._inport.addConnectorDataListener(OpenRTM_aist.ConnectorDataListenerType.ON_BUFFER_OVERWRITE, - DataListener("ON_BUFFER_OVERWRITE")) + self._inport.addConnectorDataListener(OpenRTM_aist.ConnectorDataListenerType.ON_BUFFER_OVERWRITE, + DataListener("ON_BUFFER_OVERWRITE")) - self._inport.addConnectorDataListener(OpenRTM_aist.ConnectorDataListenerType.ON_BUFFER_READ, - DataListener("ON_BUFFER_READ")) + self._inport.addConnectorDataListener(OpenRTM_aist.ConnectorDataListenerType.ON_BUFFER_READ, + DataListener("ON_BUFFER_READ")) - self._inport.addConnectorDataListener(OpenRTM_aist.ConnectorDataListenerType.ON_SEND, - DataListener("ON_SEND")) + self._inport.addConnectorDataListener(OpenRTM_aist.ConnectorDataListenerType.ON_SEND, + DataListener("ON_SEND")) - self._inport.addConnectorDataListener(OpenRTM_aist.ConnectorDataListenerType.ON_RECEIVED, - DataListener("ON_RECEIVED")) + self._inport.addConnectorDataListener(OpenRTM_aist.ConnectorDataListenerType.ON_RECEIVED, + DataListener("ON_RECEIVED")) - self._inport.addConnectorDataListener(OpenRTM_aist.ConnectorDataListenerType.ON_RECEIVER_FULL, - DataListener("ON_RECEIVER_FULL")) + self._inport.addConnectorDataListener(OpenRTM_aist.ConnectorDataListenerType.ON_RECEIVER_FULL, + DataListener("ON_RECEIVER_FULL")) - self._inport.addConnectorDataListener(OpenRTM_aist.ConnectorDataListenerType.ON_RECEIVER_TIMEOUT, - DataListener("ON_RECEIVER_TIMEOUT")) + self._inport.addConnectorDataListener(OpenRTM_aist.ConnectorDataListenerType.ON_RECEIVER_TIMEOUT, + DataListener("ON_RECEIVER_TIMEOUT")) - self._inport.addConnectorDataListener(OpenRTM_aist.ConnectorDataListenerType.ON_RECEIVER_ERROR, - DataListener("ON_RECEIVER_ERROR")) + self._inport.addConnectorDataListener(OpenRTM_aist.ConnectorDataListenerType.ON_RECEIVER_ERROR, + DataListener("ON_RECEIVER_ERROR")) - self._inport.addConnectorListener(OpenRTM_aist.ConnectorListenerType.ON_CONNECT, - ConnListener("ON_CONNECT")) - self._inport.addConnectorListener(OpenRTM_aist.ConnectorListenerType.ON_DISCONNECT, - ConnListener("ON_DISCONNECT")) + self._inport.addConnectorListener(OpenRTM_aist.ConnectorListenerType.ON_CONNECT, + ConnListener("ON_CONNECT")) + self._inport.addConnectorListener(OpenRTM_aist.ConnectorListenerType.ON_DISCONNECT, + ConnListener("ON_DISCONNECT")) - return RTC.RTC_OK + return RTC.RTC_OK - def onExecute(self, ec_id): + def onExecute(self, ec_id): - if self._inport.isNew(): - data = self._inport.read() - print("Received: ", data) - print("Received: ", data.data) - print("TimeStamp: ", data.tm.sec, "[s] ", data.tm.nsec, "[ns]") + if self._inport.isNew(): + data = self._inport.read() + print("Received: ", data) + print("Received: ", data.data) + print("TimeStamp: ", data.tm.sec, "[s] ", data.tm.nsec, "[ns]") - return RTC.RTC_OK + return RTC.RTC_OK def ConsoleOutInit(manager): - profile = OpenRTM_aist.Properties(defaults_str=consoleout_spec) - manager.registerFactory(profile, - ConsoleOut, - OpenRTM_aist.Delete) + profile = OpenRTM_aist.Properties(defaults_str=consoleout_spec) + manager.registerFactory(profile, + ConsoleOut, + OpenRTM_aist.Delete) + def MyModuleInit(manager): - ConsoleOutInit(manager) + ConsoleOutInit(manager) - # Create a component - comp = manager.createComponent("ConsoleOut") + # Create a component + comp = manager.createComponent("ConsoleOut") def main(): - # Initialize manager - mgr = OpenRTM_aist.Manager.init(sys.argv) + # Initialize manager + mgr = OpenRTM_aist.Manager.init(sys.argv) + + # Set module initialization proceduer + # This procedure will be invoked in activateManager() function. + mgr.setModuleInitProc(MyModuleInit) - # Set module initialization proceduer - # This procedure will be invoked in activateManager() function. - mgr.setModuleInitProc(MyModuleInit) + # Activate manager and register to naming service + mgr.activateManager() - # Activate manager and register to naming service - mgr.activateManager() + # run the manager in blocking mode + # runManager(False) is the default + mgr.runManager() - # run the manager in blocking mode - # runManager(False) is the default - mgr.runManager() + # If you want to run the manager in non-blocking mode, do like this + # mgr.runManager(True) - # If you want to run the manager in non-blocking mode, do like this - # mgr.runManager(True) if __name__ == "__main__": - main() + main() diff --git a/OpenRTM_aist/examples/SimpleIO/__init__.py b/OpenRTM_aist/examples/SimpleIO/__init__.py index 932b7982..270be2a2 100644 --- a/OpenRTM_aist/examples/SimpleIO/__init__.py +++ b/OpenRTM_aist/examples/SimpleIO/__init__.py @@ -1 +1 @@ -# Empty file +# Empty file diff --git a/OpenRTM_aist/examples/SimpleIO/run.py b/OpenRTM_aist/examples/SimpleIO/run.py index ed1eb741..1613587e 100644 --- a/OpenRTM_aist/examples/SimpleIO/run.py +++ b/OpenRTM_aist/examples/SimpleIO/run.py @@ -1,4 +1,4 @@ -#!/usr/bin/env python +#!/usr/bin/env python # -*- coding: utf-8 -*- # -*- Python -*- @@ -15,57 +15,87 @@ # from __future__ import print_function -import sys,os,platform +import sys +import os +import platform import time import subprocess -nsport="2809" +nsport = "2809" sysinfo = platform.uname() -hostname= sysinfo[1] -plat=sys.platform +hostname = sysinfo[1] +plat = sys.platform + def main(): - if plat == "win32": - subprocess.call('start \"\" \"%RTM_ROOT%\\bin\\rtm-naming.bat\"', shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) - time.sleep(5) - subprocess.call("start python ConsoleIn.py".split(" "), shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) - subprocess.call("start python Consoleout.py".split(" "), shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) - time.sleep(3) - subprocess.call("python Connector.py".split(" "), shell=True) - - - else: - p=subprocess.Popen("which xterm", shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) - term, stderr = p.communicate() - status = p.returncode - term = term.replace("\n","") - term += " -e" - if status != 0: - p=subprocess.Popen("which kterm", shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) - term, stderr = p.communicate() - status = p.returncode - term = term.replace("\n","") - term += " -e" + if plat == "win32": + subprocess.call( + 'start \"\" \"%RTM_ROOT%\\bin\\rtm-naming.bat\"', + shell=True, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE) + time.sleep(5) + subprocess.call( + "start python ConsoleIn.py".split(" "), + shell=True, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE) + subprocess.call( + "start python Consoleout.py".split(" "), + shell=True, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE) + time.sleep(3) + subprocess.call("python Connector.py".split(" "), shell=True) - if status != 0: - p=subprocess.Popen("which uxterm", shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) - term, stderr = p.communicate() - status = p.returncode - term = term.replace("\n","") - term += " -e" - - if status != 0: - p=subprocess.Popen("which gnome-terminal", shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) - term, stderr = p.communicate() - status = p.returncode - term = term.replace("\n","") - term += " -x" + else: + p = subprocess.Popen( + "which xterm", + shell=True, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE) + term, stderr = p.communicate() + status = p.returncode + term = term.replace("\n", "") + term += " -e" + if status != 0: + p = subprocess.Popen( + "which kterm", + shell=True, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE) + term, stderr = p.communicate() + status = p.returncode + term = term.replace("\n", "") + term += " -e" - if status != 0: - print("No terminal program (kterm/xterm/gnome-terminal) exists.") - sys.exit(0) + if status != 0: + p = subprocess.Popen( + "which uxterm", + shell=True, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE) + term, stderr = p.communicate() + status = p.returncode + term = term.replace("\n", "") + term += " -e" - """ + if status != 0: + p = subprocess.Popen( + "which gnome-terminal", + shell=True, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE) + term, stderr = p.communicate() + status = p.returncode + term = term.replace("\n", "") + term += " -x" + + if status != 0: + print("No terminal program (kterm/xterm/gnome-terminal) exists.") + sys.exit(0) + + """ path = None for p in sys.path: if os.path.exists(os.path.join(p,"OpenRTM_aist")): @@ -76,17 +106,29 @@ def main(): sys.exit(0) os.system('python %s/rtm-naming.py &'%path) """ - cmd = 'rtm-naming&' - subprocess.call(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) - cmd = '%s python ConsoleIn.py&'%term - subprocess.call(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) - cmd = '%s python ConsoleOut.py&'%term - subprocess.call(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) - time.sleep(3) - subprocess.call("python Connector.py", shell=True) - + cmd = 'rtm-naming&' + subprocess.call( + cmd, + shell=True, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE) + cmd = '%s python ConsoleIn.py&' % term + subprocess.call( + cmd, + shell=True, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE) + cmd = '%s python ConsoleOut.py&' % term + subprocess.call( + cmd, + shell=True, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE) + time.sleep(3) + subprocess.call("python Connector.py", shell=True) + + return - return if __name__ == "__main__": - main() + main() diff --git a/OpenRTM_aist/examples/SimpleService/Connector.py b/OpenRTM_aist/examples/SimpleService/Connector.py index 1556f56b..3575e9fa 100644 --- a/OpenRTM_aist/examples/SimpleService/Connector.py +++ b/OpenRTM_aist/examples/SimpleService/Connector.py @@ -1,4 +1,4 @@ -#!/usr/bin/env python +#!/usr/bin/env python # -*- coding: utf-8 -*- # -*- Python -*- @@ -10,6 +10,7 @@ import RTC import OpenRTM_aist + def usage(): print("usage: ConnectorComp [options]") print(" python MyServiceProvider.py ") @@ -24,7 +25,7 @@ def main(): # get NamingService naming = OpenRTM_aist.CorbaNaming(orb, "localhost") - + consumer = OpenRTM_aist.CorbaConsumer() provider = OpenRTM_aist.CorbaConsumer() @@ -36,7 +37,6 @@ def main(): pcons = consobj.get_ports() pcons[0].disconnect_all() - # find MyServiceProvider0 component provider.setObject(naming.resolve("MyServiceProvider0.rtc")) @@ -45,12 +45,11 @@ def main(): prov = provobj.get_ports() prov[0].disconnect_all() - # connect ports - conprof = RTC.ConnectorProfile("connector0", "", [pcons[0],prov[0]], []) + conprof = RTC.ConnectorProfile("connector0", "", [pcons[0], prov[0]], []) ret = pcons[0].connect(conprof) - + # activate ConsoleIn0 eclistin = consobj.get_owned_contexts() eclistin[0].activate_component(consobj) @@ -60,6 +59,5 @@ def main(): eclistout[0].activate_component(provobj) - if __name__ == "__main__": - main() + main() diff --git a/OpenRTM_aist/examples/SimpleService/MyServiceConsumer.py b/OpenRTM_aist/examples/SimpleService/MyServiceConsumer.py index 494e6770..d44c6096 100644 --- a/OpenRTM_aist/examples/SimpleService/MyServiceConsumer.py +++ b/OpenRTM_aist/examples/SimpleService/MyServiceConsumer.py @@ -1,4 +1,4 @@ -#!/usr/bin/env python +#!/usr/bin/env python # -*- coding: utf-8 -*- # -*- Python -*- @@ -12,162 +12,163 @@ from omniORB import CORBA myserviceconsumer_spec = ["implementation_id", "MyServiceConsumer", - "type_name", "MyServiceConsumer", - "description", "MyService Consumer Sample component", - "version", "1.0", - "vendor", "Shinji Kurihara", - "category", "example", - "activity_type", "DataFlowComponent", - "max_instance", "10", - "language", "Python", - "lang_type", "script", + "type_name", "MyServiceConsumer", + "description", "MyService Consumer Sample component", + "version", "1.0", + "vendor", "Shinji Kurihara", + "category", "example", + "activity_type", "DataFlowComponent", + "max_instance", "10", + "language", "Python", + "lang_type", "script", ""] + class echo_functor: - def __init__(self, msg, result): - self._msg = msg - self._result = result - return + def __init__(self, msg, result): + self._msg = msg + self._result = result + return - def __call__(self, obj): - try: - if CORBA.is_nil(obj): - print("No service connected.") - else: - self._result[0] = obj.echo(self._msg) - except: - pass + def __call__(self, obj): + try: + if CORBA.is_nil(obj): + print("No service connected.") + else: + self._result[0] = obj.echo(self._msg) + except BaseException: + pass class MyServiceConsumer(OpenRTM_aist.DataFlowComponentBase): - # constructor - def __init__(self, manager): - OpenRTM_aist.DataFlowComponentBase.__init__(self, manager) + # constructor + def __init__(self, manager): + OpenRTM_aist.DataFlowComponentBase.__init__(self, manager) + + self._async_echo = None + self._result = [None] + return + + def onInitialize(self): + # initialization of CORBA Port + self._myServicePort = OpenRTM_aist.CorbaPort("MyService") + + # initialization of Consumer + self._myservice0 = OpenRTM_aist.CorbaConsumer( + interfaceType=SimpleService.MyService) + + # Set service consumers to Ports + self._myServicePort.registerConsumer( + "myservice0", "MyService", self._myservice0) + + # Set CORBA Service Ports + self.addPort(self._myServicePort) + + return RTC.RTC_OK + + # The execution action that is invoked periodically + def onExecute(self, ec_id): + print("\n") + print("Command list: ") + print(" echo [msg] : echo message.") + print(" set_value [value]: set value.") + print(" get_value : get current value.") + print(" get_echo_history : get input messsage history.") + print(" get_value_history: get input value history.") + print("> ", end="") + args = str(sys.stdin.readline()) + + argv = str.split(args) + argv[-1] = argv[-1].rstrip("\n") + + if self._async_echo and self._async_echo.finished(): + print("echo() finished: ", self._result[0]) + self._async_echo = None + + if argv[0] == "echo" and len(argv) > 1: + if not self._async_echo: + retmsg = "" + func = echo_functor(argv[1], self._result) + self._async_echo = OpenRTM_aist.Async_tInvoker(self._myservice0._ptr(), + func) + self._async_echo.invoke() + else: + print("echo() still invoking") - self._async_echo = None - self._result = [None] - return + return RTC.RTC_OK - def onInitialize(self): - # initialization of CORBA Port - self._myServicePort = OpenRTM_aist.CorbaPort("MyService") - - # initialization of Consumer - self._myservice0 = OpenRTM_aist.CorbaConsumer(interfaceType=SimpleService.MyService) - - # Set service consumers to Ports - self._myServicePort.registerConsumer("myservice0", "MyService", self._myservice0) - - # Set CORBA Service Ports - self.addPort(self._myServicePort) - - return RTC.RTC_OK - - # The execution action that is invoked periodically - def onExecute(self, ec_id): - print("\n") - print("Command list: ") - print(" echo [msg] : echo message.") - print(" set_value [value]: set value.") - print(" get_value : get current value.") - print(" get_echo_history : get input messsage history.") - print(" get_value_history: get input value history.") - print("> ",end="") - args = str(sys.stdin.readline()) - - - - argv = str.split(args) - argv[-1] = argv[-1].rstrip("\n") - - if self._async_echo and self._async_echo.finished(): - print("echo() finished: ", self._result[0]) - self._async_echo = None - - if argv[0] == "echo" and len(argv) > 1: - if not self._async_echo: - retmsg = "" - func = echo_functor(argv[1],self._result) - self._async_echo = OpenRTM_aist.Async_tInvoker(self._myservice0._ptr(), - func) - self._async_echo.invoke() - else: - print("echo() still invoking") - - return RTC.RTC_OK - - if argv[0] == "set_value" and len(argv) > 1: - val = float(argv[1]) - self._myservice0._ptr().set_value(val) - print("Set remote value: ", val) - return RTC.RTC_OK - - if argv[0] == "get_value": - retval = self._myservice0._ptr().get_value() - print("Current remote value: ", retval) - return RTC.RTC_OK; - - if argv[0] == "get_echo_history": - OpenRTM_aist.CORBA_SeqUtil.for_each(self._myservice0._ptr().get_echo_history(), - self.seq_print()) - return RTC.RTC_OK - - if argv[0] == "get_value_history": - OpenRTM_aist.CORBA_SeqUtil.for_each(self._myservice0._ptr().get_value_history(), - self.seq_print()) - return RTC.RTC_OK - - print("Invalid command or argument(s).") - - return RTC.RTC_OK - - - # functor class to print sequence data - class seq_print: - def __init__(self): - self._cnt = 0 - return - - def __call__(self, val): - print(self._cnt, ": ", val) - self._cnt += 1 - return + if argv[0] == "set_value" and len(argv) > 1: + val = float(argv[1]) + self._myservice0._ptr().set_value(val) + print("Set remote value: ", val) + return RTC.RTC_OK + + if argv[0] == "get_value": + retval = self._myservice0._ptr().get_value() + print("Current remote value: ", retval) + return RTC.RTC_OK + + if argv[0] == "get_echo_history": + OpenRTM_aist.CORBA_SeqUtil.for_each(self._myservice0._ptr().get_echo_history(), + self.seq_print()) + return RTC.RTC_OK + + if argv[0] == "get_value_history": + OpenRTM_aist.CORBA_SeqUtil.for_each(self._myservice0._ptr().get_value_history(), + self.seq_print()) + return RTC.RTC_OK + + print("Invalid command or argument(s).") + + return RTC.RTC_OK + + # functor class to print sequence data + + class seq_print: + def __init__(self): + self._cnt = 0 + return + + def __call__(self, val): + print(self._cnt, ": ", val) + self._cnt += 1 + return def MyServiceConsumerInit(manager): - profile = OpenRTM_aist.Properties(defaults_str=myserviceconsumer_spec) - manager.registerFactory(profile, - MyServiceConsumer, - OpenRTM_aist.Delete) + profile = OpenRTM_aist.Properties(defaults_str=myserviceconsumer_spec) + manager.registerFactory(profile, + MyServiceConsumer, + OpenRTM_aist.Delete) def MyModuleInit(manager): - MyServiceConsumerInit(manager) + MyServiceConsumerInit(manager) - # Create a component - comp = manager.createComponent("MyServiceConsumer") - return + # Create a component + comp = manager.createComponent("MyServiceConsumer") + return def main(): - # Initialize manager - mgr = OpenRTM_aist.Manager.init(sys.argv) + # Initialize manager + mgr = OpenRTM_aist.Manager.init(sys.argv) - # Set module initialization proceduer - # This procedure will be invoked in activateManager() function. - mgr.setModuleInitProc(MyModuleInit) + # Set module initialization proceduer + # This procedure will be invoked in activateManager() function. + mgr.setModuleInitProc(MyModuleInit) - # Activate manager and register to naming service - mgr.activateManager() + # Activate manager and register to naming service + mgr.activateManager() - # run the manager in blocking mode - # runManager(False) is the default - mgr.runManager() + # run the manager in blocking mode + # runManager(False) is the default + mgr.runManager() - # If you want to run the manager in non-blocking mode, do like this - # mgr.runManager(True) - return + # If you want to run the manager in non-blocking mode, do like this + # mgr.runManager(True) + return if __name__ == "__main__": - main() + main() diff --git a/OpenRTM_aist/examples/SimpleService/MyServiceProvider.py b/OpenRTM_aist/examples/SimpleService/MyServiceProvider.py index 99c08c86..1f6be0c3 100644 --- a/OpenRTM_aist/examples/SimpleService/MyServiceProvider.py +++ b/OpenRTM_aist/examples/SimpleService/MyServiceProvider.py @@ -1,4 +1,4 @@ -#!/usr/bin/env python +#!/usr/bin/env python # -*- coding: utf-8 -*- # -*- Python -*- @@ -8,143 +8,145 @@ import time import RTC -import SimpleService, SimpleService__POA +import SimpleService +import SimpleService__POA import OpenRTM_aist # Module specification myserviceprovider_spec = ["implementation_id", "MyServiceProvider", - "type_name", "MyServiceProvider", - "description", "MyService Provider Sample component", - "version", "1.0", - "vendor", "Shinji Kurihara", - "category", "example", - "activity_type", "DataFlowComponent", - "max_instance", "10", - "language", "Python", - "lang_type", "script", + "type_name", "MyServiceProvider", + "description", "MyService Provider Sample component", + "version", "1.0", + "vendor", "Shinji Kurihara", + "category", "example", + "activity_type", "DataFlowComponent", + "max_instance", "10", + "language", "Python", + "lang_type", "script", ""] # functor class to print sequence data + + class seq_print: - def __init__(self): - self._cnt = 0 - return + def __init__(self): + self._cnt = 0 + return - def __call__(self, val): - print(self._cnt, ": ", val) - self._cnt += 1 - return + def __call__(self, val): + print(self._cnt, ": ", val) + self._cnt += 1 + return # Class implementing IDL interface MyService(MyService.idl) class MyServiceSVC_impl(SimpleService__POA.MyService): - def __init__(self): - self._echoList = [] - self._valueList = [] - self._value = 0 - return - - def __del__(self): - pass - - def echo(self, msg): - OpenRTM_aist.CORBA_SeqUtil.push_back(self._echoList, msg) - print("MyService::echo() was called.") - for i in range(10): - print("Message: ", msg) - time.sleep(1) - print("MyService::echo() was finished.") - return msg - - def get_echo_history(self): - print("MyService::get_echo_history() was called.") - OpenRTM_aist.CORBA_SeqUtil.for_each(self._echoList, seq_print()) - return self._echoList - - def set_value(self, value): - OpenRTM_aist.CORBA_SeqUtil.push_back(self._valueList, value) - self._value = value - print("MyService::set_value() was called.") - print("Current value: ", self._value) - return - - def get_value(self): - print("MyService::get_value() was called.") - print("Current value: ", self._value) - return float(self._value) - - def get_value_history(self): - print("MyService::get_value_history() was called.") - OpenRTM_aist.CORBA_SeqUtil.for_each(self._valueList, seq_print()) - - return self._valueList - + def __init__(self): + self._echoList = [] + self._valueList = [] + self._value = 0 + return + + def __del__(self): + pass + + def echo(self, msg): + OpenRTM_aist.CORBA_SeqUtil.push_back(self._echoList, msg) + print("MyService::echo() was called.") + for i in range(10): + print("Message: ", msg) + time.sleep(1) + print("MyService::echo() was finished.") + return msg + + def get_echo_history(self): + print("MyService::get_echo_history() was called.") + OpenRTM_aist.CORBA_SeqUtil.for_each(self._echoList, seq_print()) + return self._echoList + + def set_value(self, value): + OpenRTM_aist.CORBA_SeqUtil.push_back(self._valueList, value) + self._value = value + print("MyService::set_value() was called.") + print("Current value: ", self._value) + return + + def get_value(self): + print("MyService::get_value() was called.") + print("Current value: ", self._value) + return float(self._value) + + def get_value_history(self): + print("MyService::get_value_history() was called.") + OpenRTM_aist.CORBA_SeqUtil.for_each(self._valueList, seq_print()) + + return self._valueList class MyServiceProvider(OpenRTM_aist.DataFlowComponentBase): - def __init__(self, manager): - OpenRTM_aist.DataFlowComponentBase.__init__(self, manager) + def __init__(self, manager): + OpenRTM_aist.DataFlowComponentBase.__init__(self, manager) - return - + return - def onInitialize(self): - # initialization of CORBA Port - self._myServicePort = OpenRTM_aist.CorbaPort("MyService") + def onInitialize(self): + # initialization of CORBA Port + self._myServicePort = OpenRTM_aist.CorbaPort("MyService") - # initialization of Provider - self._myservice0 = MyServiceSVC_impl() + # initialization of Provider + self._myservice0 = MyServiceSVC_impl() - # Set service providers to Ports - self._myServicePort.registerProvider("myservice0", "MyService", self._myservice0) + # Set service providers to Ports + self._myServicePort.registerProvider( + "myservice0", "MyService", self._myservice0) - # Set CORBA Service Ports - self.addPort(self._myServicePort) + # Set CORBA Service Ports + self.addPort(self._myServicePort) - return RTC.RTC_OK + return RTC.RTC_OK def MyServiceProviderInit(manager): - profile = OpenRTM_aist.Properties(defaults_str=myserviceprovider_spec) - manager.registerFactory(profile, - MyServiceProvider, - OpenRTM_aist.Delete) - return + profile = OpenRTM_aist.Properties(defaults_str=myserviceprovider_spec) + manager.registerFactory(profile, + MyServiceProvider, + OpenRTM_aist.Delete) + return def MyModuleInit(manager): - MyServiceProviderInit(manager) + MyServiceProviderInit(manager) - # Create a component - comp = manager.createComponent("MyServiceProvider") + # Create a component + comp = manager.createComponent("MyServiceProvider") - """ + """ rtobj = manager.getPOA().servant_to_reference(comp)._narrow(RTC.RTObject) ecs = rtobj.get_execution_context_services() ecs[0].activate_component(rtobj) """ - return + return def main(): - # Initialize manager - mgr = OpenRTM_aist.Manager.init(sys.argv) + # Initialize manager + mgr = OpenRTM_aist.Manager.init(sys.argv) - # Set module initialization proceduer - # This procedure will be invoked in activateManager() function. - mgr.setModuleInitProc(MyModuleInit) + # Set module initialization proceduer + # This procedure will be invoked in activateManager() function. + mgr.setModuleInitProc(MyModuleInit) - # Activate manager and register to naming service - mgr.activateManager() + # Activate manager and register to naming service + mgr.activateManager() - # run the manager in blocking mode - # runManager(False) is the default - mgr.runManager() + # run the manager in blocking mode + # runManager(False) is the default + mgr.runManager() - # If you want to run the manager in non-blocking mode, do like this - # mgr.runManager(True) + # If you want to run the manager in non-blocking mode, do like this + # mgr.runManager(True) if __name__ == "__main__": - main() + main() diff --git a/OpenRTM_aist/examples/SimpleService/__init__.py b/OpenRTM_aist/examples/SimpleService/__init__.py index 932b7982..270be2a2 100644 --- a/OpenRTM_aist/examples/SimpleService/__init__.py +++ b/OpenRTM_aist/examples/SimpleService/__init__.py @@ -1 +1 @@ -# Empty file +# Empty file diff --git a/OpenRTM_aist/examples/SimpleService/run.py b/OpenRTM_aist/examples/SimpleService/run.py index 95720247..7f5ad4dc 100644 --- a/OpenRTM_aist/examples/SimpleService/run.py +++ b/OpenRTM_aist/examples/SimpleService/run.py @@ -1,4 +1,4 @@ -#!/usr/bin/env python +#!/usr/bin/env python # -*- coding: utf-8 -*- # -*- Python -*- @@ -15,58 +15,88 @@ # from __future__ import print_function -import sys,os,platform +import sys +import os +import platform import time import subprocess -nsport="2809" +nsport = "2809" sysinfo = platform.uname() -hostname= sysinfo[1] -plat=sys.platform +hostname = sysinfo[1] +plat = sys.platform if plat == "win32": #os.system("rd /S /Q SimpleService") #os.system("rd /S /Q SimpleService__POA") #os.system("omniidl.exe -bpython MyService.idl") - subprocess.call("start \"\" \"%RTM_ROOT%\\bin\\rtm-naming.bat\"", shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) + subprocess.call( + "start \"\" \"%RTM_ROOT%\\bin\\rtm-naming.bat\"", + shell=True, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE) time.sleep(5) - subprocess.call("start python MyServiceConsumer.py", shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) - subprocess.call("start python MyServiceProvider.py", shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) + subprocess.call( + "start python MyServiceConsumer.py", + shell=True, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE) + subprocess.call( + "start python MyServiceProvider.py", + shell=True, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE) time.sleep(3) subprocess.call("python Connector.py", shell=True) else: #os.system('rm -rf SimpleService*') #os.system('omniidl -bpython MyService.idl') - p=subprocess.Popen("which xterm", shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) + p = subprocess.Popen( + "which xterm", + shell=True, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE) term, stderr = p.communicate() status = p.returncode - term = term.replace("\n","") + term = term.replace("\n", "") term += " -e" if status != 0: - p=subprocess.Popen("which kterm", shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) - term, stderr = p.communicate() - status = p.returncode - term = term.replace("\n","") - term += " -e" + p = subprocess.Popen( + "which kterm", + shell=True, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE) + term, stderr = p.communicate() + status = p.returncode + term = term.replace("\n", "") + term += " -e" if status != 0: - p=subprocess.Popen("which uxterm", shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) - term, stderr = p.communicate() - status = p.returncode - term = term.replace("\n","") - term += " -e" - + p = subprocess.Popen( + "which uxterm", + shell=True, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE) + term, stderr = p.communicate() + status = p.returncode + term = term.replace("\n", "") + term += " -e" + if status != 0: - p=subprocess.Popen("which gnome-terminal", shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) - term, stderr = p.communicate() - status = p.returncode - term = term.replace("\n","") - term += " -x" + p = subprocess.Popen( + "which gnome-terminal", + shell=True, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE) + term, stderr = p.communicate() + status = p.returncode + term = term.replace("\n", "") + term += " -x" if status != 0: - print("No terminal program (kterm/xterm/gnome-terminal) exists.") - sys.exit(0) + print("No terminal program (kterm/xterm/gnome-terminal) exists.") + sys.exit(0) """ path = None @@ -81,10 +111,22 @@ """ cmd = 'rtm-naming&' - subprocess.call(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) - cmd = '%s python MyServiceConsumer.py &'%term - subprocess.call(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) - cmd = '%s python MyServiceProvider.py &'%term - subprocess.call(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) + subprocess.call( + cmd, + shell=True, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE) + cmd = '%s python MyServiceConsumer.py &' % term + subprocess.call( + cmd, + shell=True, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE) + cmd = '%s python MyServiceProvider.py &' % term + subprocess.call( + cmd, + shell=True, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE) time.sleep(3) subprocess.call("python Connector.py", shell=True) diff --git a/OpenRTM_aist/examples/Slider_and_Motor/Connector.py b/OpenRTM_aist/examples/Slider_and_Motor/Connector.py index d0211227..fd4d077d 100644 --- a/OpenRTM_aist/examples/Slider_and_Motor/Connector.py +++ b/OpenRTM_aist/examples/Slider_and_Motor/Connector.py @@ -1,4 +1,4 @@ -#!/usr/bin/env python +#!/usr/bin/env python # -*- coding: utf-8 -*- # -*- Python -*- @@ -20,8 +20,8 @@ def main(): # get NamingService naming = OpenRTM_aist.CorbaNaming(orb, "localhost") - - sl = OpenRTM_aist.CorbaConsumer() + + sl = OpenRTM_aist.CorbaConsumer() tkm = OpenRTM_aist.CorbaConsumer() # find TkMotorComp0 component @@ -32,7 +32,6 @@ def main(): pin = inobj.get_ports() pin[0].disconnect_all() - # find SliderComp0 component sl.setObject(naming.resolve("SliderComp0.rtc")) @@ -41,23 +40,22 @@ def main(): pout = outobj.get_ports() pout[0].disconnect_all() - # connect ports - conprof = RTC.ConnectorProfile("connector0", "", [pin[0],pout[0]], []) + conprof = RTC.ConnectorProfile("connector0", "", [pin[0], pout[0]], []) OpenRTM_aist.CORBA_SeqUtil.push_back(conprof.properties, - OpenRTM_aist.NVUtil.newNV("dataport.interface_type", - "corba_cdr")) + OpenRTM_aist.NVUtil.newNV("dataport.interface_type", + "corba_cdr")) OpenRTM_aist.CORBA_SeqUtil.push_back(conprof.properties, - OpenRTM_aist.NVUtil.newNV("dataport.dataflow_type", - "push")) + OpenRTM_aist.NVUtil.newNV("dataport.dataflow_type", + "push")) OpenRTM_aist.CORBA_SeqUtil.push_back(conprof.properties, - OpenRTM_aist.NVUtil.newNV("dataport.subscription_type", - subs_type)) + OpenRTM_aist.NVUtil.newNV("dataport.subscription_type", + subs_type)) ret = pin[0].connect(conprof) - + # activate TkMotorComp0 eclistin = inobj.get_owned_contexts() eclistin[0].activate_component(inobj) @@ -67,6 +65,5 @@ def main(): eclistout[0].activate_component(outobj) - if __name__ == "__main__": - main() + main() diff --git a/OpenRTM_aist/examples/Slider_and_Motor/SliderComp.py b/OpenRTM_aist/examples/Slider_and_Motor/SliderComp.py index 294c51c2..c99b599e 100644 --- a/OpenRTM_aist/examples/Slider_and_Motor/SliderComp.py +++ b/OpenRTM_aist/examples/Slider_and_Motor/SliderComp.py @@ -1,100 +1,101 @@ -#!/usr/bin/env python +#!/usr/bin/env python # -*- coding: utf-8 -*- # -*- Python -*- from __future__ import print_function +import slider +import OpenRTM_aist +import RTC import sys import time sys.path.append(".") -import RTC -import OpenRTM_aist - -import slider - channels = ( - ("motor0", -360, 360, 0.1, 200), - ("motor1", -360, 360, 0.1, 200), - ("motor2", -360, 360, 0.1, 200), - ("motor3", -360, 360, 0.1, 200), - ("motor4", -360, 360, 0.1, 200), - ("motor5", -360, 360, 0.1, 200)) - -mod_spec = ["implementation_id", "SliderComp", - "type_name", "SliderComp", - "description", "slider component", - "version", "1.0", - "vendor", "Noriaki Ando and Shinji Kurihara", - "category", "Generic", - "activity_type", "DataFlowComponent", - "max_instance", "10", - "language", "Python", + ("motor0", -360, 360, 0.1, 200), + ("motor1", -360, 360, 0.1, 200), + ("motor2", -360, 360, 0.1, 200), + ("motor3", -360, 360, 0.1, 200), + ("motor4", -360, 360, 0.1, 200), + ("motor5", -360, 360, 0.1, 200)) + +mod_spec = ["implementation_id", "SliderComp", + "type_name", "SliderComp", + "description", "slider component", + "version", "1.0", + "vendor", "Noriaki Ando and Shinji Kurihara", + "category", "Generic", + "activity_type", "DataFlowComponent", + "max_instance", "10", + "language", "Python", "lang_type""SCRIPT", ""] sl = slider.SliderMulti(channels) # thread.start_new_thread(sl.mainloop, ()) + class SliderComp(OpenRTM_aist.DataFlowComponentBase): - def __init__(self, manager): - OpenRTM_aist.DataFlowComponentBase.__init__(self, manager) - return + def __init__(self, manager): + OpenRTM_aist.DataFlowComponentBase.__init__(self, manager) + return - def onInitialize(self): - self._sl_data = RTC.TimedFloatSeq(RTC.Time(0,0), []) - self._slOut = OpenRTM_aist.OutPort("slider", self._sl_data) + def onInitialize(self): + self._sl_data = RTC.TimedFloatSeq(RTC.Time(0, 0), []) + self._slOut = OpenRTM_aist.OutPort("slider", self._sl_data) - self.addOutPort("slider", self._slOut) - return RTC.RTC_OK + self.addOutPort("slider", self._slOut) + return RTC.RTC_OK - def onActivated(self, ec_id): - return RTC.RTC_OK + def onActivated(self, ec_id): + return RTC.RTC_OK - def onExecute(self, ec_id): - self._sl_data.data = sl.get() - self._slOut.write() - time.sleep(0.01) - return RTC.RTC_OK + def onExecute(self, ec_id): + self._sl_data.data = sl.get() + self._slOut.write() + time.sleep(0.01) + return RTC.RTC_OK - def onShutdown(self, ec_id): - sl.quit() - return RTC.RTC_OK + def onShutdown(self, ec_id): + sl.quit() + return RTC.RTC_OK def SliderCompInit(manager): - profile = OpenRTM_aist.Properties(defaults_str=mod_spec) - manager.registerFactory(profile, - SliderComp, - OpenRTM_aist.Delete) + profile = OpenRTM_aist.Properties(defaults_str=mod_spec) + manager.registerFactory(profile, + SliderComp, + OpenRTM_aist.Delete) + def MyModuleInit(manager): - SliderCompInit(manager) + SliderCompInit(manager) - # Create a component - comp = manager.createComponent("SliderComp") + # Create a component + comp = manager.createComponent("SliderComp") - print("Componet created") + print("Componet created") def main(): - # Initialize manager - mgr = OpenRTM_aist.Manager.init(sys.argv) + # Initialize manager + mgr = OpenRTM_aist.Manager.init(sys.argv) + + # Set module initialization proceduer + # This procedure will be invoked in activateManager() function. + mgr.setModuleInitProc(MyModuleInit) - # Set module initialization proceduer - # This procedure will be invoked in activateManager() function. - mgr.setModuleInitProc(MyModuleInit) + # Activate manager and register to naming service + mgr.activateManager() - # Activate manager and register to naming service - mgr.activateManager() + # run the manager in blocking mode + # runManager(False) is the default + # mgr.runManager() - # run the manager in blocking mode - # runManager(False) is the default - #mgr.runManager() + # If you want to run the manager in non-blocking mode, do like this + mgr.runManager(True) + sl.mainloop() - # If you want to run the manager in non-blocking mode, do like this - mgr.runManager(True) - sl.mainloop() if __name__ == "__main__": - main() + main() diff --git a/OpenRTM_aist/examples/Slider_and_Motor/TkMotorComp.py b/OpenRTM_aist/examples/Slider_and_Motor/TkMotorComp.py index c7bfb130..67bef66f 100644 --- a/OpenRTM_aist/examples/Slider_and_Motor/TkMotorComp.py +++ b/OpenRTM_aist/examples/Slider_and_Motor/TkMotorComp.py @@ -1,27 +1,25 @@ -#!/usr/bin/env python +#!/usr/bin/env python # -*- coding: utf-8 -*- # -*- Python -*- from __future__ import print_function +import time +import tkmotor +import OpenRTM_aist +import RTC import sys sys.path.append(".") -import RTC -import OpenRTM_aist -import tkmotor -import time - - -mod_spec = ["implementation_id", "TkMotorComp", - "type_name", "TkMotorComp", - "description", "Tk Motor component (velocity control)", - "version", "1.0", - "vendor", "Noriaki Ando and Shinji Kurihara", - "category", "Generic", - "activity_type", "DataFlowComponent", - "max_instance", "10", - "language", "Python", +mod_spec = ["implementation_id", "TkMotorComp", + "type_name", "TkMotorComp", + "description", "Tk Motor component (velocity control)", + "version", "1.0", + "vendor", "Noriaki Ando and Shinji Kurihara", + "category", "Generic", + "activity_type", "DataFlowComponent", + "max_instance", "10", + "language", "Python", "lang_type""SCRIPT", ""] @@ -29,86 +27,84 @@ tkm = tkmotor.TkMotor(6, 40) #thread.start_new_thread(tkm.mainloop, ()) -class TkMotorComp(OpenRTM_aist.DataFlowComponentBase): - def __init__(self, manager): - OpenRTM_aist.DataFlowComponentBase.__init__(self, manager) - self._cnt = 0 - self._num = 6 - return - - - def onInitialize(self): - self._tk_data = RTC.TimedFloatSeq(RTC.Time(0,0), []) - self._tkIn = OpenRTM_aist.InPort("vel", self._tk_data) - - self.addInPort("vel", self._tkIn) - return RTC.RTC_OK - - def onActivated(self, ec_id): - val = [self._cnt] * self._num - tkm.set_angle(val) - time.sleep(0.01) - self._cnt += 1 - self._v = [0] * 6 - return RTC.RTC_OK - - - def onExecute(self, ec_id): - try: - indata = self._tkIn.read() - val = indata.data - print(val) - if len(val) == 6: - for i in range(6): - self._v[i] += val[i] / 2 - tkm.set_angle(self._v) - except: - print("Exception cought in onExecute()") - - time.sleep(0.01) - return RTC.RTC_OK - - - def onShutdown(self, ec_id): - tkm.quit() - return RTC.RTC_OK +class TkMotorComp(OpenRTM_aist.DataFlowComponentBase): + def __init__(self, manager): + OpenRTM_aist.DataFlowComponentBase.__init__(self, manager) + self._cnt = 0 + self._num = 6 + return + + def onInitialize(self): + self._tk_data = RTC.TimedFloatSeq(RTC.Time(0, 0), []) + self._tkIn = OpenRTM_aist.InPort("vel", self._tk_data) + + self.addInPort("vel", self._tkIn) + return RTC.RTC_OK + + def onActivated(self, ec_id): + val = [self._cnt] * self._num + tkm.set_angle(val) + time.sleep(0.01) + self._cnt += 1 + self._v = [0] * 6 + return RTC.RTC_OK + + def onExecute(self, ec_id): + try: + indata = self._tkIn.read() + val = indata.data + print(val) + if len(val) == 6: + for i in range(6): + self._v[i] += val[i] / 2 + tkm.set_angle(self._v) + except BaseException: + print("Exception cought in onExecute()") + + time.sleep(0.01) + return RTC.RTC_OK + + def onShutdown(self, ec_id): + tkm.quit() + return RTC.RTC_OK def TkMotorCompInit(manager): - profile = OpenRTM_aist.Properties(defaults_str=mod_spec) - manager.registerFactory(profile, - TkMotorComp, - OpenRTM_aist.Delete) + profile = OpenRTM_aist.Properties(defaults_str=mod_spec) + manager.registerFactory(profile, + TkMotorComp, + OpenRTM_aist.Delete) def MyModuleInit(manager): - TkMotorCompInit(manager) + TkMotorCompInit(manager) - # Create a component - comp = manager.createComponent("TkMotorComp") + # Create a component + comp = manager.createComponent("TkMotorComp") - print("Componet created") + print("Componet created") def main(): - # Initialize manager - mgr = OpenRTM_aist.Manager.init(sys.argv) + # Initialize manager + mgr = OpenRTM_aist.Manager.init(sys.argv) + + # Set module initialization proceduer + # This procedure will be invoked in activateManager() function. + mgr.setModuleInitProc(MyModuleInit) - # Set module initialization proceduer - # This procedure will be invoked in activateManager() function. - mgr.setModuleInitProc(MyModuleInit) + # Activate manager and register to naming service + mgr.activateManager() - # Activate manager and register to naming service - mgr.activateManager() + # run the manager in blocking mode + # runManager(False) is the default + # mgr.runManager() - # run the manager in blocking mode - # runManager(False) is the default - #mgr.runManager() + # If you want to run the manager in non-blocking mode, do like this + mgr.runManager(True) + tkm.mainloop() - # If you want to run the manager in non-blocking mode, do like this - mgr.runManager(True) - tkm.mainloop() if __name__ == "__main__": - main() + main() diff --git a/OpenRTM_aist/examples/Slider_and_Motor/TkMotorPosComp.py b/OpenRTM_aist/examples/Slider_and_Motor/TkMotorPosComp.py index ac11827c..cd6e35cf 100644 --- a/OpenRTM_aist/examples/Slider_and_Motor/TkMotorPosComp.py +++ b/OpenRTM_aist/examples/Slider_and_Motor/TkMotorPosComp.py @@ -1,27 +1,25 @@ -#!/usr/bin/env python +#!/usr/bin/env python # -*- coding: utf-8 -*- # -*- Python -*- from __future__ import print_function +import time +import tkmotor +import OpenRTM_aist +import RTC import sys sys.path.append(".") -import RTC -import OpenRTM_aist - -import tkmotor -import time - -mod_spec = ["implementation_id", "TkMotorPosComp", - "type_name", "TkMotorPosComp", - "description", "Tk Motor component (position control)", - "version", "1.0", - "vendor", "Noriaki Ando and Shinji Kurihara", - "category", "Generic", - "activity_type", "DataFlowComponent", - "max_instance", "10", - "language", "Python", +mod_spec = ["implementation_id", "TkMotorPosComp", + "type_name", "TkMotorPosComp", + "description", "Tk Motor component (position control)", + "version", "1.0", + "vendor", "Noriaki Ando and Shinji Kurihara", + "category", "Generic", + "activity_type", "DataFlowComponent", + "max_instance", "10", + "language", "Python", "lang_type""SCRIPT", ""] @@ -29,86 +27,84 @@ tkm = tkmotor.TkMotor(6, 40) #thread.start_new_thread(tkm.mainloop, ()) -class TkMotorPosComp(OpenRTM_aist.DataFlowComponentBase): - def __init__(self, manager): - OpenRTM_aist.DataFlowComponentBase.__init__(self, manager) - self._cnt = 0 - self._num = 6 - return - - - def onInitialize(self): - self._tk_data = RTC.TimedFloatSeq(RTC.Time(0,0), []) - self._tkIn = OpenRTM_aist.InPort("pos", self._tk_data) - - self.addInPort("pos", self._tkIn) - return RTC.RTC_OK - - - def onActivated(self, ec_id): - val = [self._cnt] * self._num - tkm.set_angle(val) - time.sleep(0.01) - self._cnt += 1 - self._v = [0] * 6 - return RTC.RTC_OK - - - def onExecute(self, ec_id): - try: - indata = self._tkIn.read() - val = indata.data - print(val) - if len(val) == 6: - for i in range(6): - self._v[i] = val[i] * 10 - tkm.set_angle(self._v) - except: - print("Exception cought in onExecute()") - - time.sleep(0.01) - return RTC.RTC_OK - - - def onShutdown(self, ec_id): - tkm.quit() - return RTC.RTC_OK +class TkMotorPosComp(OpenRTM_aist.DataFlowComponentBase): + def __init__(self, manager): + OpenRTM_aist.DataFlowComponentBase.__init__(self, manager) + self._cnt = 0 + self._num = 6 + return + + def onInitialize(self): + self._tk_data = RTC.TimedFloatSeq(RTC.Time(0, 0), []) + self._tkIn = OpenRTM_aist.InPort("pos", self._tk_data) + + self.addInPort("pos", self._tkIn) + return RTC.RTC_OK + + def onActivated(self, ec_id): + val = [self._cnt] * self._num + tkm.set_angle(val) + time.sleep(0.01) + self._cnt += 1 + self._v = [0] * 6 + return RTC.RTC_OK + + def onExecute(self, ec_id): + try: + indata = self._tkIn.read() + val = indata.data + print(val) + if len(val) == 6: + for i in range(6): + self._v[i] = val[i] * 10 + tkm.set_angle(self._v) + except BaseException: + print("Exception cought in onExecute()") + + time.sleep(0.01) + return RTC.RTC_OK + + def onShutdown(self, ec_id): + tkm.quit() + return RTC.RTC_OK def TkMotorPosCompInit(manager): - profile = OpenRTM_aist.Properties(defaults_str=mod_spec) - manager.registerFactory(profile, - TkMotorPosComp, - OpenRTM_aist.Delete) + profile = OpenRTM_aist.Properties(defaults_str=mod_spec) + manager.registerFactory(profile, + TkMotorPosComp, + OpenRTM_aist.Delete) + def MyModuleInit(manager): - TkMotorPosCompInit(manager) + TkMotorPosCompInit(manager) - # Create a component - comp = manager.createComponent("TkMotorPosComp") + # Create a component + comp = manager.createComponent("TkMotorPosComp") - print("Componet created") + print("Componet created") def main(): - # Initialize manager - mgr = OpenRTM_aist.Manager.init(sys.argv) + # Initialize manager + mgr = OpenRTM_aist.Manager.init(sys.argv) + + # Set module initialization proceduer + # This procedure will be invoked in activateManager() function. + mgr.setModuleInitProc(MyModuleInit) - # Set module initialization proceduer - # This procedure will be invoked in activateManager() function. - mgr.setModuleInitProc(MyModuleInit) + # Activate manager and register to naming service + mgr.activateManager() - # Activate manager and register to naming service - mgr.activateManager() + # run the manager in blocking mode + # runManager(False) is the default + # mgr.runManager() - # run the manager in blocking mode - # runManager(False) is the default - #mgr.runManager() + # If you want to run the manager in non-blocking mode, do like this + mgr.runManager(True) + tkm.mainloop() - # If you want to run the manager in non-blocking mode, do like this - mgr.runManager(True) - tkm.mainloop() if __name__ == "__main__": - main() + main() diff --git a/OpenRTM_aist/examples/Slider_and_Motor/__init__.py b/OpenRTM_aist/examples/Slider_and_Motor/__init__.py index 932b7982..270be2a2 100644 --- a/OpenRTM_aist/examples/Slider_and_Motor/__init__.py +++ b/OpenRTM_aist/examples/Slider_and_Motor/__init__.py @@ -1 +1 @@ -# Empty file +# Empty file diff --git a/OpenRTM_aist/examples/Slider_and_Motor/run.py b/OpenRTM_aist/examples/Slider_and_Motor/run.py index 6afe17b9..9f235ab7 100644 --- a/OpenRTM_aist/examples/Slider_and_Motor/run.py +++ b/OpenRTM_aist/examples/Slider_and_Motor/run.py @@ -1,4 +1,4 @@ -#!/usr/bin/env python +#!/usr/bin/env python # -*- coding: utf-8 -*- # -*- Python -*- @@ -15,53 +15,83 @@ # from __future__ import print_function -import sys,os,platform +import sys +import os +import platform import time import subprocess -nsport="2809" +nsport = "2809" sysinfo = platform.uname() -hostname= sysinfo[1] -plat=sys.platform +hostname = sysinfo[1] +plat = sys.platform if plat == "win32": - subprocess.call("start \"\" \"%RTM_ROOT%\\bin\\rtm-naming.bat\"", shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) + subprocess.call( + "start \"\" \"%RTM_ROOT%\\bin\\rtm-naming.bat\"", + shell=True, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE) time.sleep(5) - subprocess.call("start python SliderComp.py", shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) - subprocess.call("start python TkMotorComp.py", shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) + subprocess.call( + "start python SliderComp.py", + shell=True, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE) + subprocess.call( + "start python TkMotorComp.py", + shell=True, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE) time.sleep(5) subprocess.call("python Connector.py", shell=True) else: - p=subprocess.Popen("which xterm", shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) + p = subprocess.Popen( + "which xterm", + shell=True, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE) term, stderr = p.communicate() status = p.returncode - term = term.replace("\n","") + term = term.replace("\n", "") term += " -e" if status != 0: - p=subprocess.Popen("which kterm", shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) - term, stderr = p.communicate() - status = p.returncode - term = term.replace("\n","") - term += " -e" + p = subprocess.Popen( + "which kterm", + shell=True, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE) + term, stderr = p.communicate() + status = p.returncode + term = term.replace("\n", "") + term += " -e" if status != 0: - p=subprocess.Popen("which uxterm", shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) - term, stderr = p.communicate() - status = p.returncode - term = term.replace("\n","") - term += " -e" - + p = subprocess.Popen( + "which uxterm", + shell=True, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE) + term, stderr = p.communicate() + status = p.returncode + term = term.replace("\n", "") + term += " -e" + if status != 0: - p=subprocess.Popen("which gnome-terminal", shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) - term, stderr = p.communicate() - status = p.returncode - term = term.replace("\n","") - term += " -x" + p = subprocess.Popen( + "which gnome-terminal", + shell=True, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE) + term, stderr = p.communicate() + status = p.returncode + term = term.replace("\n", "") + term += " -x" if status != 0: - print("No terminal program (kterm/xterm/gnome-terminal) exists.") - sys.exit(0) + print("No terminal program (kterm/xterm/gnome-terminal) exists.") + sys.exit(0) """ path = None @@ -75,8 +105,20 @@ os.system('python %s/rtm-naming.py &'%path) """ cmd = 'rtm-naming&' - subprocess.call(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) - cmd = '%s python SliderComp.py &'%term - subprocess.call(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) - cmd = '%s python TkMotorComp.py &'%term - subprocess.call(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) + subprocess.call( + cmd, + shell=True, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE) + cmd = '%s python SliderComp.py &' % term + subprocess.call( + cmd, + shell=True, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE) + cmd = '%s python TkMotorComp.py &' % term + subprocess.call( + cmd, + shell=True, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE) diff --git a/OpenRTM_aist/examples/Slider_and_Motor/slider.py b/OpenRTM_aist/examples/Slider_and_Motor/slider.py index d1759d40..2bf882ca 100644 --- a/OpenRTM_aist/examples/Slider_and_Motor/slider.py +++ b/OpenRTM_aist/examples/Slider_and_Motor/slider.py @@ -1,68 +1,71 @@ -#!/usr/bin/env python +#!/usr/bin/env python # -*- coding: utf-8 -*- # -*- Python -*- from __future__ import print_function +import time +import dummy_threading import sys if sys.version_info[0] == 2: - from Tkinter import * + from Tkinter import * else: - from tkinter import * + from tkinter import * #import thread -import dummy_threading -import time + class SliderMulti(Frame): - def __init__(self, channels, master=None): - Frame.__init__(self, master) - self.init(channels) - self.pack() + def __init__(self, channels, main=None): + Frame.__init__(self, main) + self.init(channels) + self.pack() + def init(self, channels): + self._channels = channels + self.var = [] + self.scales = [] + self.option_add('*font', 'system 9') - def init(self, channels): - self._channels = channels - self.var = [] - self.scales = [] - - i = 0 - for channel in self._channels: - self.var.append(DoubleVar(0)) - self.scales.append( - Scale(self, label=channel[0], variable=self.var[i], - to=channel[1], orient=VERTICAL)) - self.scales[i]["from"] = channel[2] - self.scales[i]["resolution"] = channel[3] - self.scales[i]["length"] = channel[4] - self.scales[i].pack(side=LEFT) - i = i + 1 + i = 0 + for channel in self._channels: + self.var.append(DoubleVar(0)) + self.scales.append( + Scale(self, label=channel[0], variable=self.var[i], + to=channel[1], orient=VERTICAL)) + self.scales[i]["from"] = channel[2] + self.scales[i]["resolution"] = channel[3] + self.scales[i]["length"] = channel[4] + self.scales[i].pack(side=LEFT) + i = i + 1 - def get(self): - val = [] - for v in self.var: - val.append(v.get()) + def get(self): + val = [] + for v in self.var: + val.append(v.get()) - return val + return val - def set(self, value): - i = 0 - for v in value: - self.var[i].set(v) + def set(self, value): + i = 0 + for v in value: + self.var[i].set(v) - i = i + 1 - return + i = i + 1 + return -def test (): - channels = (("angle", 0, 360, 0.1, 200), ("velocity", -100, 100, 0.1, 200)) - slider = SliderMulti(channels) - sth = dummy_threading.Thread(target=slider.mainloop, args=()) - sth.start() +def test(): + channels = (("angle", 0, 360, 0.1, 200), ("velocity", -100, 100, 0.1, 200)) + slider = SliderMulti(channels) + sth = dummy_threading.Thread(target=slider.mainloop, args=()) + sth.start() # thread.start_new_thread(slider.mainloop, ()) - while (1): - print(slider.get()) - time.sleep(0.5) + while (1): + print(slider.get()) + time.sleep(0.5) # slider.update() -if __name__ == '__main__': test() + +if __name__ == '__main__': + test() diff --git a/OpenRTM_aist/examples/Slider_and_Motor/tkmotor.py b/OpenRTM_aist/examples/Slider_and_Motor/tkmotor.py index 21172625..f9a891c0 100644 --- a/OpenRTM_aist/examples/Slider_and_Motor/tkmotor.py +++ b/OpenRTM_aist/examples/Slider_and_Motor/tkmotor.py @@ -1,98 +1,105 @@ -#!/usr/bin/env python +#!/usr/bin/env python # -*- coding: utf-8 -*- # -*- Python -*- +import math +import time import sys if sys.version_info[0] == 2: - from Tkinter import * - import thread + from Tkinter import * + import thread else: - from tkinter import * - import _thread as thread + from tkinter import * + import _thread as thread -import time -import math class TkMotor(Frame): - def __init__(self, num, radius, master=None): - Frame.__init__(self, master) - self.num = num - self.r = radius - self.init() - self.pack() - + def __init__(self, num, radius, main=None): + Frame.__init__(self, main) + self.num = num + self.r = radius + self.init() + self.pack() + def init(self): + self.space = 4 + canwidth = self.r * self.space * self.num + canheight = self.r * self.space + self.can = Canvas(self, bg="white", + width=canwidth, height=canheight) + self.can.pack() + self.circ = [] + self.line = [] + self.x = [] + self.y = [] + self.x1 = [] + self.y1 = [] + self.x2 = [] + self.y2 = [] + self.sx1 = [] + self.sy1 = [] + self.sx2 = [] + self.sy2 = [] - def init(self): - self.space = 4 - canwidth = self.r * self.space * self.num - canheight = self.r * self.space - self.can = Canvas(self, bg="white", - width=canwidth, height=canheight) - self.can.pack() - self.circ = [] - self.line = [] - self.x = [] - self.y = [] - self.x1 = [] - self.y1 = [] - self.x2 = [] - self.y2 = [] - self.sx1 = [] - self.sy1 = [] - self.sx2 = [] - self.sy2 = [] - - for i in range(self.num): - self.x.append(self.r * self.space / 2 * (i+0.5) * 2) - self.y.append(self.r * self.space / 2) - self.x1.append(self.x[i] - self.r) - self.y1.append(self.y[i] - self.r) - self.x2.append(self.x[i] + self.r) - self.y2.append(self.y[i] + self.r) - self.sx1.append(self.x[i] - self.r * 0.1) - self.sy1.append(self.y[i] - self.r * 0.1) - self.sx2.append(self.x[i] + self.r * 0.1) - self.sy2.append(self.y[i] + self.r * 0.1) - self.circ.append(self.can.create_oval(self.x1[i], self.y1[i], - self.x2[i], self.y2[i], - outline="#aaaaaa", - fill="#dddddd")) - self.circ.append(self.can.create_oval(self.sx1[i], self.sy1[i], - self.sx2[i], self.sy2[i], - outline="#000000", - fill="#000000")) - self.line.append(self.can.create_line(self.x[i], self.y[i], - self.x[i], - self.y[i] - self.r, - fill="#700040", width=5)) + for i in range(self.num): + self.x.append(self.r * self.space / 2 * (i + 0.5) * 2) + self.y.append(self.r * self.space / 2) + self.x1.append(self.x[i] - self.r) + self.y1.append(self.y[i] - self.r) + self.x2.append(self.x[i] + self.r) + self.y2.append(self.y[i] + self.r) + self.sx1.append(self.x[i] - self.r * 0.1) + self.sy1.append(self.y[i] - self.r * 0.1) + self.sx2.append(self.x[i] + self.r * 0.1) + self.sy2.append(self.y[i] + self.r * 0.1) + self.circ.append(self.can.create_oval(self.x1[i], self.y1[i], + self.x2[i], self.y2[i], + outline="#aaaaaa", + fill="#dddddd")) + self.circ.append(self.can.create_oval(self.sx1[i], self.sy1[i], + self.sx2[i], self.sy2[i], + outline="#000000", + fill="#000000")) + self.line.append(self.can.create_line(self.x[i], self.y[i], + self.x[i], + self.y[i] - self.r, + fill="#700040", width=5)) - - def set_angle(self, angle): - if len(angle) != self.num: return - i = 0 - for a in angle: - a = a * math.pi / 180 - self.can.delete(self.line[i]) - self.line[i] = self.can.create_line(self.x[i], self.y[i], - self.x[i] + self.r * math.cos(a), - self.y[i] + self.r * math.sin(a), - fill="#700040", width=5) - i = i + 1 + def set_angle(self, angle): + if len(angle) != self.num: + return + i = 0 + for a in angle: + a = a * math.pi / 180 + self.can.delete(self.line[i]) + self.line[i] = self.can.create_line(self.x[i], self.y[i], + self.x[i] + self.r * + math.cos(a), + self.y[i] + self.r * + math.sin(a), + fill="#700040", width=5) + i = i + 1 +def test(): + m = TkMotor(6, 40, Toplevel()) + n = TkMotor(6, 40, Toplevel()) + thread.start_new_thread(m.mainloop, ()) + thread.start_new_thread(n.mainloop, ()) + cnt = 0 + while(1): + angle = [ + cnt % + 360, - cnt % + 360, cnt % + 360, - cnt % + 360, cnt % + 360, - cnt % + 360] + m.set_angle(angle) + time.sleep(0.001) + cnt = cnt + 1 -def test (): - m = TkMotor(6, 40, Toplevel()) - n = TkMotor(6, 40, Toplevel()) - thread.start_new_thread(m.mainloop, ()) - thread.start_new_thread(n.mainloop, ()) - cnt = 0 - while(1): - angle = [cnt % 360, - cnt % 360, cnt % 360, - cnt % 360, cnt % 360, - cnt % 360] - m.set_angle(angle) - time.sleep(0.001) - cnt = cnt + 1 - -if __name__ == '__main__': test() +if __name__ == '__main__': + test() diff --git a/OpenRTM_aist/examples/StaticFsm/Display.py b/OpenRTM_aist/examples/StaticFsm/Display.py index 014f96d4..83fba1a1 100644 --- a/OpenRTM_aist/examples/StaticFsm/Display.py +++ b/OpenRTM_aist/examples/StaticFsm/Display.py @@ -1,5 +1,5 @@ -#!/usr/bin/env python -# -*- coding: euc-jp -*- +#!/usr/bin/env python +# -*- coding: utf-8 -*- ## # @file Display.py @@ -21,151 +21,147 @@ import OpenRTM_aist.StringUtil display_spec = ["implementation_id", "Display", - "type_name", "Display", - "description", "Console input component", - "version", "1.0", - "vendor", "Nobuhiko Miyamoto", - "category", "example", - "activity_type", "DataFlowComponent", - "max_instance", "10", - "language", "Python", - "lang_type", "script", - ""] - + "type_name", "Display", + "description", "Display component for Microwave example", + "version", "1.0", + "vendor", "Nobuhiko Miyamoto", + "category", "example", + "activity_type", "DataFlowComponent", + "max_instance", "10", + "language", "Python", + "lang_type", "script", + ""] class DataListener(OpenRTM_aist.ConnectorDataListenerT): - def __init__(self, name): - self._name = name - - def __del__(self): - print("dtor of ", self._name) - - def __call__(self, info, cdrdata): - data = OpenRTM_aist.ConnectorDataListenerT.__call__(self, info, cdrdata, RTC.TimedLong(RTC.Time(0,0),0)) - print("------------------------------") - print("Listener: ", self._name) - print("Profile::name: ", info.name) - print("Profile::id: ", info.id) - print("Data: ", data.data) - print("------------------------------") - return OpenRTM_aist.ConnectorListenerStatus.NO_CHANGE + def __init__(self, name): + self._name = name + + def __del__(self): + print("dtor of ", self._name) + + def __call__(self, info, cdrdata): + data = OpenRTM_aist.ConnectorDataListenerT.__call__( + self, info, cdrdata, RTC.TimedLong( + RTC.Time( + 0, 0), 0), OpenRTM_aist.PortType.InPortType) + print("------------------------------") + print("Listener: ", self._name) + print("Profile::name: ", info.name) + print("Profile::id: ", info.id) + print("Data: ", data.data) + print("------------------------------") + return OpenRTM_aist.ConnectorListenerStatus.NO_CHANGE class ConnListener(OpenRTM_aist.ConnectorListener): - def __init__(self, name): - self._name = name - - def __del__(self): - print("dtor of ", self._name) - - def __call__(self, info): - print("------------------------------") - print("Listener: ", self._name) - print("Profile::name: ", info.name) - print("Profile::id: ", info.id) - print("------------------------------") - return OpenRTM_aist.ConnectorListenerStatus.NO_CHANGE + def __init__(self, name): + self._name = name + def __del__(self): + print("dtor of ", self._name) + def __call__(self, info): + print("------------------------------") + print("Listener: ", self._name) + print("Profile::name: ", info.name) + print("Profile::id: ", info.id) + print("------------------------------") + return OpenRTM_aist.ConnectorListenerStatus.NO_CHANGE class Display(OpenRTM_aist.DataFlowComponentBase): - def __init__(self, manager): - OpenRTM_aist.DataFlowComponentBase.__init__(self, manager) - return + def __init__(self, manager): + OpenRTM_aist.DataFlowComponentBase.__init__(self, manager) + return - def onInitialize(self): - self._in = RTC.TimedLong(RTC.Time(0,0),0) + def onInitialize(self): + self._in = RTC.TimedLong(RTC.Time(0, 0), 0) - - self._inIn = OpenRTM_aist.InPort("in", self._in) + self._inIn = OpenRTM_aist.InPort("in", self._in) - # Set OutPort buffer - self.addInPort("in", self._inIn) + # Set OutPort buffer + self.addInPort("in", self._inIn) + self._inIn.addConnectorDataListener(OpenRTM_aist.ConnectorDataListenerType.ON_BUFFER_WRITE, + DataListener("ON_BUFFER_WRITE")) - self._inIn.addConnectorDataListener(OpenRTM_aist.ConnectorDataListenerType.ON_BUFFER_WRITE, - DataListener("ON_BUFFER_WRITE")) + self._inIn.addConnectorDataListener(OpenRTM_aist.ConnectorDataListenerType.ON_BUFFER_FULL, + DataListener("ON_BUFFER_FULL")) + self._inIn.addConnectorDataListener(OpenRTM_aist.ConnectorDataListenerType.ON_BUFFER_WRITE_TIMEOUT, + DataListener("ON_BUFFER_WRITE_TIMEOUT")) - self._inIn.addConnectorDataListener(OpenRTM_aist.ConnectorDataListenerType.ON_BUFFER_FULL, - DataListener("ON_BUFFER_FULL")) + self._inIn.addConnectorDataListener(OpenRTM_aist.ConnectorDataListenerType.ON_BUFFER_OVERWRITE, + DataListener("ON_BUFFER_OVERWRITE")) - self._inIn.addConnectorDataListener(OpenRTM_aist.ConnectorDataListenerType.ON_BUFFER_WRITE_TIMEOUT, - DataListener("ON_BUFFER_WRITE_TIMEOUT")) + self._inIn.addConnectorDataListener(OpenRTM_aist.ConnectorDataListenerType.ON_BUFFER_READ, + DataListener("ON_BUFFER_READ")) - self._inIn.addConnectorDataListener(OpenRTM_aist.ConnectorDataListenerType.ON_BUFFER_OVERWRITE, - DataListener("ON_BUFFER_OVERWRITE")) + self._inIn.addConnectorDataListener(OpenRTM_aist.ConnectorDataListenerType.ON_SEND, + DataListener("ON_SEND")) - self._inIn.addConnectorDataListener(OpenRTM_aist.ConnectorDataListenerType.ON_BUFFER_READ, - DataListener("ON_BUFFER_READ")) + self._inIn.addConnectorDataListener(OpenRTM_aist.ConnectorDataListenerType.ON_RECEIVED, + DataListener("ON_RECEIVED")) - self._inIn.addConnectorDataListener(OpenRTM_aist.ConnectorDataListenerType.ON_SEND, - DataListener("ON_SEND")) + self._inIn.addConnectorDataListener(OpenRTM_aist.ConnectorDataListenerType.ON_RECEIVER_FULL, + DataListener("ON_RECEIVER_FULL")) - self._inIn.addConnectorDataListener(OpenRTM_aist.ConnectorDataListenerType.ON_RECEIVED, - DataListener("ON_RECEIVED")) + self._inIn.addConnectorDataListener(OpenRTM_aist.ConnectorDataListenerType.ON_RECEIVER_TIMEOUT, + DataListener("ON_RECEIVER_TIMEOUT")) - self._inIn.addConnectorDataListener(OpenRTM_aist.ConnectorDataListenerType.ON_RECEIVER_FULL, - DataListener("ON_RECEIVER_FULL")) + self._inIn.addConnectorDataListener(OpenRTM_aist.ConnectorDataListenerType.ON_RECEIVER_ERROR, + DataListener("ON_RECEIVER_ERROR")) - self._inIn.addConnectorDataListener(OpenRTM_aist.ConnectorDataListenerType.ON_RECEIVER_TIMEOUT, - DataListener("ON_RECEIVER_TIMEOUT")) + self._inIn.addConnectorListener(OpenRTM_aist.ConnectorListenerType.ON_CONNECT, + ConnListener("ON_CONNECT")) + self._inIn.addConnectorListener(OpenRTM_aist.ConnectorListenerType.ON_DISCONNECT, + ConnListener("ON_DISCONNECT")) - self._inIn.addConnectorDataListener(OpenRTM_aist.ConnectorDataListenerType.ON_RECEIVER_ERROR, - DataListener("ON_RECEIVER_ERROR")) + return RTC.RTC_OK - self._inIn.addConnectorListener(OpenRTM_aist.ConnectorListenerType.ON_CONNECT, - ConnListener("ON_CONNECT")) - self._inIn.addConnectorListener(OpenRTM_aist.ConnectorListenerType.ON_DISCONNECT, - ConnListener("ON_DISCONNECT")) + def onExecute(self, ec_id): + if self._inIn.isNew(): + data = self._inIn.read() + print("Received: ", data.data) + print("TimeStamp: ", data.tm.sec, "[s]") + print("TimeStamp: ", data.tm.nsec, "[ns]") - - return RTC.RTC_OK - - - def onExecute(self, ec_id): - if self._inIn.isNew(): - data = self._inIn.read() - print("Received: ", data.data) - print("TimeStamp: ", data.tm.sec,"[s]") - print("TimeStamp: ", data.tm.nsec,"[ns]") - - - return RTC.RTC_OK + return RTC.RTC_OK def DisplayInit(manager): - profile = OpenRTM_aist.Properties(defaults_str=display_spec) - manager.registerFactory(profile, - Display, - OpenRTM_aist.Delete) + profile = OpenRTM_aist.Properties(defaults_str=display_spec) + manager.registerFactory(profile, + Display, + OpenRTM_aist.Delete) def MyModuleInit(manager): - DisplayInit(manager) + DisplayInit(manager) + + # Create a component + comp = manager.createComponent("Display") - # Create a component - comp = manager.createComponent("Display") def main(): - # Initialize manager - mgr = OpenRTM_aist.Manager.init(sys.argv) + # Initialize manager + mgr = OpenRTM_aist.Manager.init(sys.argv) + + # Set module initialization proceduer + # This procedure will be invoked in activateManager() function. + mgr.setModuleInitProc(MyModuleInit) - # Set module initialization proceduer - # This procedure will be invoked in activateManager() function. - mgr.setModuleInitProc(MyModuleInit) + # Activate manager and register to naming service + mgr.activateManager() - # Activate manager and register to naming service - mgr.activateManager() + # run the manager in blocking mode + # runManager(False) is the default + mgr.runManager() - # run the manager in blocking mode - # runManager(False) is the default - mgr.runManager() + # If you want to run the manager in non-blocking mode, do like this + # mgr.runManager(True) - # If you want to run the manager in non-blocking mode, do like this - # mgr.runManager(True) if __name__ == "__main__": - main() + main() diff --git a/OpenRTM_aist/examples/StaticFsm/Inputbutton.py b/OpenRTM_aist/examples/StaticFsm/Inputbutton.py index 2ed2784a..cafd4c5b 100644 --- a/OpenRTM_aist/examples/StaticFsm/Inputbutton.py +++ b/OpenRTM_aist/examples/StaticFsm/Inputbutton.py @@ -1,5 +1,5 @@ -#!/usr/bin/env python -# -*- coding: euc-jp -*- +#!/usr/bin/env python +# -*- coding: utf-8 -*- ## # @file Inputbutton.py @@ -21,139 +21,135 @@ import OpenRTM_aist.StringUtil inputbutton_spec = ["implementation_id", "Inputbutton", - "type_name", "Inputbutton", - "description", "Console input component", - "version", "1.0", - "vendor", "Nobuhiko Miyamoto", - "category", "example", - "activity_type", "DataFlowComponent", - "max_instance", "10", - "language", "Python", - "lang_type", "script", - ""] + "type_name", "Inputbutton", + "description", "InputButton component for Microwave example", + "version", "1.0", + "vendor", "Nobuhiko Miyamoto", + "category", "example", + "activity_type", "DataFlowComponent", + "max_instance", "10", + "language", "Python", + "lang_type", "script", + ""] +class Inputbutton(OpenRTM_aist.DataFlowComponentBase): + def __init__(self, manager): + OpenRTM_aist.DataFlowComponentBase.__init__(self, manager) + return + + def onInitialize(self): + self._open = RTC.TimedLong(RTC.Time(0, 0), 0) + self._close = RTC.TimedLong(RTC.Time(0, 0), 0) + self._minute = RTC.TimedLong(RTC.Time(0, 0), 0) + self._start = RTC.TimedLong(RTC.Time(0, 0), 0) + self._stop = RTC.TimedLong(RTC.Time(0, 0), 0) + self._tick = RTC.TimedLong(RTC.Time(0, 0), 0) + + self._openOut = OpenRTM_aist.OutPort("open", self._open) + self._closeOut = OpenRTM_aist.OutPort("close", self._close) + self._minuteOut = OpenRTM_aist.OutPort("minute", self._minute) + self._startOut = OpenRTM_aist.OutPort("start", self._start) + self._stopOut = OpenRTM_aist.OutPort("stop", self._stop) + self._tickOut = OpenRTM_aist.OutPort("tick", self._tick) + # Set OutPort buffer + self.addOutPort("open", self._openOut) + self.addOutPort("close", self._closeOut) + self.addOutPort("minute", self._minuteOut) + self.addOutPort("start", self._startOut) + self.addOutPort("stop", self._stopOut) + self.addOutPort("tick", self._tickOut) + return RTC.RTC_OK + def onExecute(self, ec_id): + print("") + print("Please select action!!") + print("Commands: ") + print(" open : Open the microwave's door.") + print(" close : Close the microwave's door.") + print(" minute : Increment timer. ") + print(" start : Start the microwave.") + print(" stop : Stop the microwave.") + print(" tick : Proceed time.") + print(" -> others are interpreted as tick commnad.") + print(">> ", end="") + #print(">> ",end="") + cmds = sys.stdin.readline() + cmds = cmds.split(" ") + cmds[0] = OpenRTM_aist.StringUtil.eraseBlank(cmds[0]) + cmds[0] = cmds[0].replace("\n", "") + cmds[0] = cmds[0].replace("\r", "") + print("[command]: ", cmds[0]) + #print(" [args]: ",end="") + print(" [args]: ", end="") + for n in range(len(cmds)): + if n == 0: + continue + # print(cmds[n],end="") + print(cmds[n], end="") + print("") + if cmds[0] == "open": + self._open.data = 0 + self._openOut.write() + elif cmds[0] == "close": + self._close.data = 0 + self._closeOut.write() + elif cmds[0] == "minute": + min = 0 + ret, min = OpenRTM_aist.StringUtil.stringTo(min, cmds[1]) + if len(cmds) < 2 or not ret: + print("minute command needs an integer arg.") + return RTC.RTC_OK + + self._minute.data = min + self._minuteOut.write() + elif cmds[0] == "start": + self._start.data = 0 + self._startOut.write() + elif cmds[0] == "stop": + self._stop.data = 0 + self._stopOut.write() + else: + print("tick") + self._tick.data = 0 + self._tickOut.write() -class Inputbutton(OpenRTM_aist.DataFlowComponentBase): - def __init__(self, manager): - OpenRTM_aist.DataFlowComponentBase.__init__(self, manager) - return - - def onInitialize(self): - self._open = RTC.TimedLong(RTC.Time(0,0),0) - self._close = RTC.TimedLong(RTC.Time(0,0),0) - self._minute = RTC.TimedLong(RTC.Time(0,0),0) - self._start = RTC.TimedLong(RTC.Time(0,0),0) - self._stop = RTC.TimedLong(RTC.Time(0,0),0) - self._tick = RTC.TimedLong(RTC.Time(0,0),0) - - self._openOut = OpenRTM_aist.OutPort("open", self._open) - self._closeOut = OpenRTM_aist.OutPort("close", self._close) - self._minuteOut = OpenRTM_aist.OutPort("minute", self._minute) - self._startOut = OpenRTM_aist.OutPort("start", self._start) - self._stopOut = OpenRTM_aist.OutPort("stop", self._stop) - self._tickOut = OpenRTM_aist.OutPort("tick", self._tick) - # Set OutPort buffer - self.addOutPort("out", self._openOut) - self.addOutPort("out", self._closeOut) - self.addOutPort("out", self._minuteOut) - self.addOutPort("out", self._startOut) - self.addOutPort("out", self._stopOut) - self.addOutPort("out", self._tickOut) - - - return RTC.RTC_OK - - - def onExecute(self, ec_id): - print("") - print("Please select action!!") - print("Commands: ") - print(" open : Open the microwave's door.") - print(" close : Close the microwave's door.") - print(" minute : Increment timer. ") - print(" start : Start the microwave.") - print(" stop : Stop the microwave.") - print(" tick : Proceed time.") - print(" -> others are interpreted as tick commnad.") - print(">> ", end="") - #print(">> ",end="") - cmds = sys.stdin.readline() - cmds = cmds.split(" ") - OpenRTM_aist.StringUtil.eraseBlank(cmds) - cmds[0] = cmds[0].replace("\n","") - cmds[0] = cmds[0].replace("\r","") - print("[command]: ",cmds[0]) - #print(" [args]: ",end="") - print(" [args]: ", end="") - for n in range(len(cmds)): - if n == 0: - continue - #print(cmds[n],end="") - print(cmds[n], end="") - print("") - if cmds[0] == "open": - self._open.data = 0 - self._openOut.write() - elif cmds[0] == "close": - self._close.data = 0 - self._closeOut.write() - elif cmds[0] == "minute": - min = [0] - if len(cmds) < 2 or not OpenRTM_aist.StringUtil.stringTo(min, cmds[1]): - print("minute command needs an integer arg.") return RTC.RTC_OK - - self._minute.data = min[0] - self._minuteOut.write() - elif cmds[0] == "start": - self._start.data = 0 - self._startOut.write() - elif cmds[0] == "stop": - self._stop.data = 0 - self._stopOut.write() - else: - print("tick") - self._tick.data = 0 - self._tickOut.write() - - - - return RTC.RTC_OK def InputbuttonInit(manager): - profile = OpenRTM_aist.Properties(defaults_str=inputbutton_spec) - manager.registerFactory(profile, - Inputbutton, - OpenRTM_aist.Delete) + profile = OpenRTM_aist.Properties(defaults_str=inputbutton_spec) + manager.registerFactory(profile, + Inputbutton, + OpenRTM_aist.Delete) def MyModuleInit(manager): - InputbuttonInit(manager) + InputbuttonInit(manager) + + # Create a component + comp = manager.createComponent("Inputbutton") - # Create a component - comp = manager.createComponent("Inputbutton") def main(): - # Initialize manager - mgr = OpenRTM_aist.Manager.init(sys.argv) + # Initialize manager + mgr = OpenRTM_aist.Manager.init(sys.argv) + + # Set module initialization proceduer + # This procedure will be invoked in activateManager() function. + mgr.setModuleInitProc(MyModuleInit) - # Set module initialization proceduer - # This procedure will be invoked in activateManager() function. - mgr.setModuleInitProc(MyModuleInit) + # Activate manager and register to naming service + mgr.activateManager() - # Activate manager and register to naming service - mgr.activateManager() + # run the manager in blocking mode + # runManager(False) is the default + mgr.runManager() - # run the manager in blocking mode - # runManager(False) is the default - mgr.runManager() + # If you want to run the manager in non-blocking mode, do like this + # mgr.runManager(True) - # If you want to run the manager in non-blocking mode, do like this - # mgr.runManager(True) if __name__ == "__main__": - main() + main() diff --git a/OpenRTM_aist/examples/StaticFsm/Microwave.py b/OpenRTM_aist/examples/StaticFsm/Microwave.py index 43e1cca8..1b1d2696 100644 --- a/OpenRTM_aist/examples/StaticFsm/Microwave.py +++ b/OpenRTM_aist/examples/StaticFsm/Microwave.py @@ -1,5 +1,5 @@ -#!/usr/bin/env python -# -*- coding: euc-jp -*- +#!/usr/bin/env python +# -*- coding: utf-8 -*- ## # @file Microwave.py @@ -24,88 +24,87 @@ import MicrowaveFsm microwave_spec = ["implementation_id", "Microwave", - "type_name", "Microwave", - "description", "Console input component", - "version", "1.0", - "vendor", "Nobuhiko Miyamoto", - "category", "example", - "activity_type", "DataFlowComponent", - "max_instance", "10", - "language", "Python", - "lang_type", "script", + "type_name", "Microwave", + "description", "Microwave Static FSM component", + "version", "1.0", + "vendor", "Nobuhiko Miyamoto", + "category", "example", + "activity_type", "DataFlowComponent", + "max_instance", "10", + "language", "Python", + "lang_type", "script", ""] - - - class Microwave(OpenRTM_aist.DataFlowComponentBase): - def __init__(self, manager): - OpenRTM_aist.DataFlowComponentBase.__init__(self, manager) - - return + def __init__(self, manager): + OpenRTM_aist.DataFlowComponentBase.__init__(self, manager) + return + def onInitialize(self): + self._fsm = StaticFSM.Machine(MicrowaveFsm.TOP, self) + self._eventIn = EventPort.EventInPort("event", self._fsm) - def onInitialize(self): - self._fsm = StaticFSM.Machine(MicrowaveFsm.TOP, self) - #self._fsm.init() - self._eventIn = EventPort.EventInPort("event", self._fsm) - - self.addInPort("event", self._eventIn) - self._eventIn.bindEvent0("open", MicrowaveFsm.TOP.open) - self._eventIn.bindEvent0("close", MicrowaveFsm.TOP.close) - self._eventIn.bindEvent1("minute", MicrowaveFsm.TOP.minute, RTC.TimedLong(RTC.Time(0,0),0)) - self._eventIn.bindEvent0("start", MicrowaveFsm.TOP.start) - self._eventIn.bindEvent0("stop", MicrowaveFsm.TOP.stop) - self._eventIn.bindEvent0("tick", MicrowaveFsm.TOP.tick) - + self.addInPort("event", self._eventIn) + self._eventIn.bindEvent0("open", MicrowaveFsm.TOP.open) + self._eventIn.bindEvent0("close", MicrowaveFsm.TOP.close) + self._eventIn.bindEvent1( + "minute", + MicrowaveFsm.TOP.minute, + RTC.TimedLong( + RTC.Time( + 0, + 0), + 0)) + self._eventIn.bindEvent0("start", MicrowaveFsm.TOP.start) + self._eventIn.bindEvent0("stop", MicrowaveFsm.TOP.stop) + self._eventIn.bindEvent0("tick", MicrowaveFsm.TOP.tick) + return RTC.RTC_OK - return RTC.RTC_OK + def onFinalize(self): + self._fsm.shutdown() + return RTC.RTC_OK + def onExecute(self, ec_id): + self._fsm.run_event() - def onFinalize(self): - self._fsm.shutdown() - return RTC.RTC_OK - - - def onExecute(self, ec_id): - self._fsm.run_event() - - return RTC.RTC_OK + return RTC.RTC_OK def MicrowaveInit(manager): - profile = OpenRTM_aist.Properties(defaults_str=microwave_spec) - manager.registerFactory(profile, - Microwave, - OpenRTM_aist.Delete) + profile = OpenRTM_aist.Properties(defaults_str=microwave_spec) + manager.registerFactory(profile, + Microwave, + OpenRTM_aist.Delete) def MyModuleInit(manager): - MicrowaveInit(manager) + MicrowaveInit(manager) + + # Create a component + comp = manager.createComponent("Microwave") - # Create a component - comp = manager.createComponent("Microwave") def main(): - # Initialize manager - mgr = OpenRTM_aist.Manager.init(sys.argv) + # Initialize manager + mgr = OpenRTM_aist.Manager.init(sys.argv) + + # Set module initialization proceduer + # This procedure will be invoked in activateManager() function. + mgr.setModuleInitProc(MyModuleInit) - # Set module initialization proceduer - # This procedure will be invoked in activateManager() function. - mgr.setModuleInitProc(MyModuleInit) + # Activate manager and register to naming service + mgr.activateManager() - # Activate manager and register to naming service - mgr.activateManager() + # run the manager in blocking mode + # runManager(False) is the default + mgr.runManager() - # run the manager in blocking mode - # runManager(False) is the default - mgr.runManager() + # If you want to run the manager in non-blocking mode, do like this + # mgr.runManager(True) - # If you want to run the manager in non-blocking mode, do like this - # mgr.runManager(True) if __name__ == "__main__": - main() + main() diff --git a/OpenRTM_aist/examples/StaticFsm/MicrowaveFsm.py b/OpenRTM_aist/examples/StaticFsm/MicrowaveFsm.py index e49d0d23..134bd48b 100644 --- a/OpenRTM_aist/examples/StaticFsm/MicrowaveFsm.py +++ b/OpenRTM_aist/examples/StaticFsm/MicrowaveFsm.py @@ -1,5 +1,5 @@ -#!/usr/bin/env python -# -*- coding: euc-jp -*- +#!/usr/bin/env python +# -*- coding: utf-8 -*- ## # @file Microwave.py @@ -23,118 +23,116 @@ @StaticFSM.FSM_TOPSTATE class TOP(StaticFSM.Link): - def onInit(self): - self.set_state(StaticFSM.State(Operational)) - return RTC.RTC_OK - - - def open(self): - pass - def close(self): - pass - def minute(self, time_): - pass - def start(self): - pass - def stop(self): - pass - def tick(self): - pass - - class Data: - def __init__(self): - self.myCookingTime = 0 - def printTimer(self): - print(" Timer set to ", self.myCookingTime, " minutes") - def incrementTimer(self): - self.myCookingTime+=1 - def decrementTimer(self): - self.myCookingTime-=1 - def resetTimer(self): - self.myCookingTime = 0 - def getRemainingTime(self): - return self.myCookingTime - - - - -@StaticFSM.FSM_SUBSTATE(TOP) -class Disabled(StaticFSM.Link): - def onEntry(self): - print(" Microwave opened") - return RTC.RTC_OK - def onExit(self): - print(" Microwave closed") - return RTC.RTC_OK - def close(self): - #self.setStateHistory(OpenRTM_aist.Macho.State(Operational)) - self.set_state(StaticFSM.State(Operational)) + def onInit(self): + self.set_state(StaticFSM.State(Operational)) + return RTC.RTC_OK + def open(self): + pass -@StaticFSM.deephistory -@StaticFSM.FSM_SUBSTATE(TOP) -class Operational(StaticFSM.Link): - def open(self): - self.set_state(StaticFSM.State(Disabled)) - def stop(self): - self.set_state(StaticFSM.State(Idle)) - def onInit(self): - self.set_state(StaticFSM.State(Idle)) - return RTC.RTC_OK + def close(self): + pass + def minute(self, time_): + pass - + def start(self): + pass + def stop(self): + pass + def tick(self): + pass + class Data: + def __init__(self): + self.myCookingTime = 0 + def printTimer(self): + print(" Timer set to ", self.myCookingTime, " minutes") + def incrementTimer(self): + self.myCookingTime += 1 -@StaticFSM.FSM_SUBSTATE(Operational) -class Idle(StaticFSM.Link): - def minute(self, time_): - self.set_state(StaticFSM.State(Programmed)) - self.dispatch(StaticFSM.Event(TOP.minute,time_)) - - def onEntry(self): - self.data(TOP).resetTimer() - print(" Microwave ready") - return RTC.RTC_OK + def decrementTimer(self): + self.myCookingTime -= 1 + + def resetTimer(self): + self.myCookingTime = 0 + + def getRemainingTime(self): + return self.myCookingTime + + +@StaticFSM.FSM_SUBSTATE(TOP) +class Disabled(StaticFSM.Link): + def onEntry(self): + print(" Microwave opened") + return RTC.RTC_OK + def onExit(self): + print(" Microwave closed") + return RTC.RTC_OK + def close(self): + # self.setStateHistory(OpenRTM_aist.Macho.State(Operational)) + self.set_state(StaticFSM.State(Operational)) +@StaticFSM.deephistory +@StaticFSM.FSM_SUBSTATE(TOP) +class Operational(StaticFSM.Link): + def open(self): + self.set_state(StaticFSM.State(Disabled)) + + def stop(self): + self.set_state(StaticFSM.State(Idle)) + + def onInit(self): + self.set_state(StaticFSM.State(Idle)) + return RTC.RTC_OK + @StaticFSM.FSM_SUBSTATE(Operational) -class Programmed(StaticFSM.Link): - def minute(self, time_): - for t in range(time_.data): - self.data(TOP).incrementTimer() - self.data(TOP).printTimer() - def start(self): - self.set_state(StaticFSM.State(Cooking)) +class Idle(StaticFSM.Link): + def minute(self, time_): + self.set_state(StaticFSM.State(Programmed)) + self.dispatch(StaticFSM.Event(TOP.minute, time_)) + + def onEntry(self): + self.data(TOP).resetTimer() + print(" Microwave ready") + return RTC.RTC_OK +@StaticFSM.FSM_SUBSTATE(Operational) +class Programmed(StaticFSM.Link): + def minute(self, time_): + for t in range(time_.data): + self.data(TOP).incrementTimer() + self.data(TOP).printTimer() + def start(self): + self.set_state(StaticFSM.State(Cooking)) @StaticFSM.FSM_SUBSTATE(Programmed) class Cooking(StaticFSM.Link): - def tick(self): - print(" Clock tick") - tb = self.data(TOP) - tb.decrementTimer() - if tb.getRemainingTime() == 0: - print(" Finished") - self.set_state(StaticFSM.State(Idle)) - else: - tb.printTimer() - - def onEntry(self): - print(" Heating on") - return RTC.RTC_OK - def onExit(self): - print(" Heating off") - return RTC.RTC_OK - - + def tick(self): + print(" Clock tick") + tb = self.data(TOP) + tb.decrementTimer() + if tb.getRemainingTime() == 0: + print(" Finished") + self.set_state(StaticFSM.State(Idle)) + else: + tb.printTimer() + + def onEntry(self): + print(" Heating on") + return RTC.RTC_OK + + def onExit(self): + print(" Heating off") + return RTC.RTC_OK diff --git a/OpenRTM_aist/examples/StaticFsm/MicrowaveFsm_pyfsm.py b/OpenRTM_aist/examples/StaticFsm/MicrowaveFsm_pyfsm.py index 9056dd8d..67a34ff3 100644 --- a/OpenRTM_aist/examples/StaticFsm/MicrowaveFsm_pyfsm.py +++ b/OpenRTM_aist/examples/StaticFsm/MicrowaveFsm_pyfsm.py @@ -1,5 +1,5 @@ -#!/usr/bin/env python -# -*- coding: euc-jp -*- +#!/usr/bin/env python +# -*- coding: utf-8 -*- ## # @file Microwave.py @@ -17,124 +17,121 @@ import sys - import OpenRTM_aist.StaticFSM_pyfsm as StaticFSM @StaticFSM.FSM_TOPSTATE class TOP(StaticFSM.Link): - def onInit(self): - self.set_state(StaticFSM.State(Operational)) - return RTC.RTC_OK - - - def open(self): - pass - def close(self): - pass - def minute(self, time_): - pass - def start(self): - pass - def stop(self): - pass - def tick(self): - pass - - class Data: - def __init__(self): - self.myCookingTime = 0 - def printTimer(self): - print(" Timer set to ", self.myCookingTime, " minutes") - def incrementTimer(self): - self.myCookingTime+=1 - def decrementTimer(self): - self.myCookingTime-=1 - def resetTimer(self): - self.myCookingTime = 0 - def getRemainingTime(self): - return self.myCookingTime - - - - -@StaticFSM.FSM_SUBSTATE(TOP) -class Disabled(StaticFSM.Link): - def onEntry(self): - print(" Microwave opened") - return RTC.RTC_OK - def onExit(self): - print(" Microwave closed") - return RTC.RTC_OK - def close(self): - #self.setStateHistory(OpenRTM_aist.Macho.State(Operational)) - self.set_state(StaticFSM.State(Operational)) + def onInit(self): + self.set_state(StaticFSM.State(Operational)) + return RTC.RTC_OK + def open(self): + pass -@StaticFSM.deephistory -@StaticFSM.FSM_SUBSTATE(TOP) -class Operational(StaticFSM.Link): - def open(self): - self.set_state(StaticFSM.State(Disabled)) - def stop(self): - self.set_state(StaticFSM.State(Idle)) - def onInit(self): - self.set_state(StaticFSM.State(Idle)) - return RTC.RTC_OK + def close(self): + pass + def minute(self, time_): + pass - + def start(self): + pass + def stop(self): + pass + def tick(self): + pass + class Data: + def __init__(self): + self.myCookingTime = 0 + def printTimer(self): + print(" Timer set to ", self.myCookingTime, " minutes") + def incrementTimer(self): + self.myCookingTime += 1 -@StaticFSM.FSM_SUBSTATE(Operational) -class Idle(StaticFSM.Link): - def minute(self, time_): - self.set_state(StaticFSM.State(Programmed)) - self.dispatch(StaticFSM.Event(TOP.minute,time_)) - - def onEntry(self): - self.data(TOP).resetTimer() - print(" Microwave ready") - return RTC.RTC_OK + def decrementTimer(self): + self.myCookingTime -= 1 + + def resetTimer(self): + self.myCookingTime = 0 + def getRemainingTime(self): + return self.myCookingTime +@StaticFSM.FSM_SUBSTATE(TOP) +class Disabled(StaticFSM.Link): + def onEntry(self): + print(" Microwave opened") + return RTC.RTC_OK + + def onExit(self): + print(" Microwave closed") + return RTC.RTC_OK + + def close(self): + # self.setStateHistory(OpenRTM_aist.Macho.State(Operational)) + self.set_state(StaticFSM.State(Operational)) + + +@StaticFSM.deephistory +@StaticFSM.FSM_SUBSTATE(TOP) +class Operational(StaticFSM.Link): + def open(self): + self.set_state(StaticFSM.State(Disabled)) + + def stop(self): + self.set_state(StaticFSM.State(Idle)) + + def onInit(self): + self.set_state(StaticFSM.State(Idle)) + return RTC.RTC_OK @StaticFSM.FSM_SUBSTATE(Operational) -class Programmed(StaticFSM.Link): - def minute(self, time_): - for t in range(time_.data): - self.data(TOP).incrementTimer() - self.data(TOP).printTimer() - def start(self): - self.set_state(StaticFSM.State(Cooking)) +class Idle(StaticFSM.Link): + def minute(self, time_): + self.set_state(StaticFSM.State(Programmed)) + self.dispatch(StaticFSM.Event(TOP.minute, time_)) + + def onEntry(self): + self.data(TOP).resetTimer() + print(" Microwave ready") + return RTC.RTC_OK +@StaticFSM.FSM_SUBSTATE(Operational) +class Programmed(StaticFSM.Link): + def minute(self, time_): + for t in range(time_.data): + self.data(TOP).incrementTimer() + self.data(TOP).printTimer() + def start(self): + self.set_state(StaticFSM.State(Cooking)) @StaticFSM.FSM_SUBSTATE(Programmed) class Cooking(StaticFSM.Link): - def tick(self): - print(" Clock tick") - tb = self.data(TOP) - tb.decrementTimer() - if tb.getRemainingTime() == 0: - print(" Finished") - self.set_state(StaticFSM.State(Idle)) - else: - tb.printTimer() - - def onEntry(self): - print(" Heating on") - return RTC.RTC_OK - def onExit(self): - print(" Heating off") - return RTC.RTC_OK - - + def tick(self): + print(" Clock tick") + tb = self.data(TOP) + tb.decrementTimer() + if tb.getRemainingTime() == 0: + print(" Finished") + self.set_state(StaticFSM.State(Idle)) + else: + tb.printTimer() + + def onEntry(self): + print(" Heating on") + return RTC.RTC_OK + + def onExit(self): + print(" Heating off") + return RTC.RTC_OK diff --git a/OpenRTM_aist/examples/StaticFsm/Microwave_pyfsm.py b/OpenRTM_aist/examples/StaticFsm/Microwave_pyfsm.py index 551e1cc0..9bdded84 100644 --- a/OpenRTM_aist/examples/StaticFsm/Microwave_pyfsm.py +++ b/OpenRTM_aist/examples/StaticFsm/Microwave_pyfsm.py @@ -1,5 +1,5 @@ -#!/usr/bin/env python -# -*- coding: euc-jp -*- +#!/usr/bin/env python +# -*- coding: utf-8 -*- ## # @file Microwave.py @@ -24,85 +24,87 @@ import MicrowaveFsm_pyfsm microwave_spec = ["implementation_id", "Microwave", - "type_name", "Microwave", - "description", "Console input component", - "version", "1.0", - "vendor", "Nobuhiko Miyamoto", - "category", "example", - "activity_type", "DataFlowComponent", - "max_instance", "10", - "language", "Python", - "lang_type", "script", + "type_name", "Microwave", + "description", "Console input component", + "version", "1.0", + "vendor", "Nobuhiko Miyamoto", + "category", "example", + "activity_type", "DataFlowComponent", + "max_instance", "10", + "language", "Python", + "lang_type", "script", ""] +class Microwave(OpenRTM_aist.DataFlowComponentBase): + def __init__(self, manager): + OpenRTM_aist.DataFlowComponentBase.__init__(self, manager) + return + def onFinalize(self): + self._fsm.exit() + return RTC.RTC_OK -class Microwave(OpenRTM_aist.DataFlowComponentBase): - def __init__(self, manager): - OpenRTM_aist.DataFlowComponentBase.__init__(self, manager) - - return - - def onFinalize(self): - self._fsm.exit() - return RTC.RTC_OK - - def onInitialize(self): - self._fsm = StaticFSM.Machine(MicrowaveFsm.TOP, self) - #self._fsm.init() - self._eventIn = EventPort.EventInPort("event", self._fsm) - - self.addInPort("event", self._eventIn) - self._eventIn.bindEvent0("open", MicrowaveFsm.TOP.open) - self._eventIn.bindEvent0("close", MicrowaveFsm.TOP.close) - self._eventIn.bindEvent1("minute", MicrowaveFsm.TOP.minute, RTC.TimedLong(RTC.Time(0,0),0)) - self._eventIn.bindEvent0("start", MicrowaveFsm.TOP.start) - self._eventIn.bindEvent0("stop", MicrowaveFsm.TOP.stop) - self._eventIn.bindEvent0("tick", MicrowaveFsm.TOP.tick) - - - - return RTC.RTC_OK - - - def onExecute(self, ec_id): - self._fsm.run_event() - - return RTC.RTC_OK + def onInitialize(self): + self._fsm = StaticFSM.Machine(MicrowaveFsm.TOP, self) + self._eventIn = EventPort.EventInPort("event", self._fsm) + + self.addInPort("event", self._eventIn) + self._eventIn.bindEvent0("open", MicrowaveFsm.TOP.open) + self._eventIn.bindEvent0("close", MicrowaveFsm.TOP.close) + self._eventIn.bindEvent1( + "minute", + MicrowaveFsm.TOP.minute, + RTC.TimedLong( + RTC.Time( + 0, + 0), + 0)) + self._eventIn.bindEvent0("start", MicrowaveFsm.TOP.start) + self._eventIn.bindEvent0("stop", MicrowaveFsm.TOP.stop) + self._eventIn.bindEvent0("tick", MicrowaveFsm.TOP.tick) + + return RTC.RTC_OK + + def onExecute(self, ec_id): + self._fsm.run_event() + + return RTC.RTC_OK def MicrowaveInit(manager): - profile = OpenRTM_aist.Properties(defaults_str=microwave_spec) - manager.registerFactory(profile, - Microwave, - OpenRTM_aist.Delete) + profile = OpenRTM_aist.Properties(defaults_str=microwave_spec) + manager.registerFactory(profile, + Microwave, + OpenRTM_aist.Delete) def MyModuleInit(manager): - MicrowaveInit(manager) + MicrowaveInit(manager) + + # Create a component + comp = manager.createComponent("Microwave") - # Create a component - comp = manager.createComponent("Microwave") def main(): - # Initialize manager - mgr = OpenRTM_aist.Manager.init(sys.argv) + # Initialize manager + mgr = OpenRTM_aist.Manager.init(sys.argv) + + # Set module initialization proceduer + # This procedure will be invoked in activateManager() function. + mgr.setModuleInitProc(MyModuleInit) - # Set module initialization proceduer - # This procedure will be invoked in activateManager() function. - mgr.setModuleInitProc(MyModuleInit) + # Activate manager and register to naming service + mgr.activateManager() - # Activate manager and register to naming service - mgr.activateManager() + # run the manager in blocking mode + # runManager(False) is the default + mgr.runManager() - # run the manager in blocking mode - # runManager(False) is the default - mgr.runManager() + # If you want to run the manager in non-blocking mode, do like this + # mgr.runManager(True) - # If you want to run the manager in non-blocking mode, do like this - # mgr.runManager(True) if __name__ == "__main__": - main() + main() diff --git a/OpenRTM_aist/examples/Templates/__init__.py b/OpenRTM_aist/examples/Templates/__init__.py index 932b7982..270be2a2 100644 --- a/OpenRTM_aist/examples/Templates/__init__.py +++ b/OpenRTM_aist/examples/Templates/__init__.py @@ -1 +1 @@ -# Empty file +# Empty file diff --git a/OpenRTM_aist/examples/Throughput/Throughput_py.py b/OpenRTM_aist/examples/Throughput/Throughput_py.py index 9c69d143..1e6f25a1 100644 --- a/OpenRTM_aist/examples/Throughput/Throughput_py.py +++ b/OpenRTM_aist/examples/Throughput/Throughput_py.py @@ -16,15 +16,14 @@ """ from __future__ import print_function +import math +import OpenRTM_aist +import RTC import sys import time sys.path.append(".") # Import RTM module -import RTC -import OpenRTM_aist - -import math # Import Service implementation class @@ -39,86 +38,87 @@ # This module's spesification # -throughput_py_spec = ["implementation_id", "Throughput_py", - "type_name", "Throughput_py", - "description", "Throughput sample", - "version", "1.0.0", - "vendor", "AIST", - "category", "example", - "activity_type", "STATIC", - "max_instance", "1", - "language", "Python", - "lang_type", "SCRIPT", - "conf.default.datatype", "double", - "conf.default.outputfile", "test.dat", - "conf.default.increment", "100", - "conf.default.sleep_time", "0.1", - "conf.default.mode", "logincr", - "conf.default.maxsize", "1000000", - "conf.default.maxsend", "1000", - "conf.default.maxsample", "100", - "conf.default.filesuffix", "-test", - - "conf.__widget__.datatype", "radio", - "conf.__widget__.outputfile", "text", - "conf.__widget__.increment", "text", - "conf.__widget__.sleep_time", "text", - "conf.__widget__.mode", "radio", - "conf.__widget__.maxsize", "text", - "conf.__widget__.maxsend", "text", - "conf.__widget__.maxsample", "text", - "conf.__widget__.filesuffix", "text", - "conf.__constraints__.datatype", "(octet,short,long,float,double)", - "conf.__constraints__.mode", "(logincr,incr,const)", - - "conf.__type__.datatype", "string", - "conf.__type__.outputfile", "string", - "conf.__type__.increment", "long", - "conf.__type__.sleep_time", "double", - "conf.__type__.mode", "string", - "conf.__type__.maxsize", "long", - "conf.__type__.maxsend", "long", - "conf.__type__.maxsample", "long", - "conf.__type__.filesuffix", "string", - - ""] +throughput_py_spec = ["implementation_id", "Throughput_py", + "type_name", "Throughput_py", + "description", "Throughput sample", + "version", "1.0.0", + "vendor", "AIST", + "category", "example", + "activity_type", "STATIC", + "max_instance", "1", + "language", "Python", + "lang_type", "SCRIPT", + "conf.default.datatype", "double", + "conf.default.outputfile", "test.dat", + "conf.default.increment", "100", + "conf.default.sleep_time", "0.1", + "conf.default.mode", "logincr", + "conf.default.maxsize", "1000000", + "conf.default.maxsend", "1000", + "conf.default.maxsample", "100", + "conf.default.filesuffix", "-test", + + "conf.__widget__.datatype", "radio", + "conf.__widget__.outputfile", "text", + "conf.__widget__.increment", "text", + "conf.__widget__.sleep_time", "text", + "conf.__widget__.mode", "radio", + "conf.__widget__.maxsize", "text", + "conf.__widget__.maxsend", "text", + "conf.__widget__.maxsample", "text", + "conf.__widget__.filesuffix", "text", + "conf.__constraints__.datatype", "(octet,short,long,float,double)", + "conf.__constraints__.mode", "(logincr,incr,const)", + + "conf.__type__.datatype", "string", + "conf.__type__.outputfile", "string", + "conf.__type__.increment", "long", + "conf.__type__.sleep_time", "double", + "conf.__type__.mode", "string", + "conf.__type__.maxsize", "long", + "conf.__type__.maxsend", "long", + "conf.__type__.maxsample", "long", + "conf.__type__.filesuffix", "string", + + ""] # -class DataListener(OpenRTM_aist.ConnectorDataListenerT): - def __init__(self, comp, data): - self._comp = comp - self._data = data - def __del__(self): - pass +class DataListener(OpenRTM_aist.ConnectorDataListenerT): + def __init__(self, comp, data): + self._comp = comp + self._data = data - def __call__(self, info, cdrdata): - data = OpenRTM_aist.ConnectorDataListenerT.__call__(self, info, cdrdata, self._data) - self._comp.receiveData(data.tm, len(data.data)) + def __del__(self): + pass + def __call__(self, info, cdrdata): + data = OpenRTM_aist.ConnectorDataListenerT.__call__( + self, info, cdrdata, self._data, OpenRTM_aist.PortType.InPortType) + self._comp.receiveData(data.tm, len(data.data)) class ConnListener(OpenRTM_aist.ConnectorListener): - def __init__(self, comp): - self._comp = comp + def __init__(self, comp): + self._comp = comp - def __del__(self): - print("dtor of ", self._name) + def __del__(self): + print("dtor of ", self._name) - def __call__(self, info): - print("------------------------------") - print("Profile::name: ", info.name) - print("Profile::id: ", info.id) - print("Profile::properties: ") - print(info.properties) - print("------------------------------") - self._comp.setConnectorProfile(info) + def __call__(self, info): + print("------------------------------") + print("Profile::name: ", info.name) + print("Profile::id: ", info.id) + print("Profile::properties: ") + print(info.properties) + print("------------------------------") + self._comp.setConnectorProfile(info) ## # @class Throughput_py # @brief Throughput sample -# +# # データポートのスループットを計測するコンポーネント。interface_type, # subscription_type 等 ConnectorProfile パラメータやデータサイズ、サン # プル数などを変更して、その際の転送時間(最大、最小、平均、標準偏差) @@ -138,54 +138,49 @@ def __call__(self, info): # -# 必要なコネクタプロファイルを設定してポートを接続する # -# コンポーネントをアクティベートする # 計測結果はデータを受け取ったコンポーネントがファイルに記録する。 -# -# +# +# class Throughput_py(OpenRTM_aist.DataFlowComponentBase): - - ## - # @brief constructor - # @param manager Maneger Object - # - def __init__(self, manager): - OpenRTM_aist.DataFlowComponentBase.__init__(self, manager) - self._size = 0 - - - - - - # initialize of configuration-data. - # - """ + ## + # @brief constructor + # @param manager Maneger Object + # + def __init__(self, manager): + OpenRTM_aist.DataFlowComponentBase.__init__(self, manager) + self._size = 0 + + # initialize of configuration-data. + # + """ データ型 - Name: datatype datatype - DefaultValue: double - Constraint: (octet,short,long,float,double) """ - self._datatype = ['double'] - """ + self._datatype = ['double'] + """ 出力ファイル名。onActivated時、またはデータ受信時にファイルがオープンされるの で、それ以降にパラメータを設定した場合は反映されない。 - Name: outputfile outputfile - DefaultValue: test.dat """ - self._outputfile = ['test.dat'] - """ + self._outputfile = ['test.dat'] + """ データ増分。mode が incr の場合のデータ増分を byte で指定する。 - Name: increment increment - DefaultValue: 100 - Unit: byte """ - self._increment = [100] - """ + self._increment = [100] + """ onExecute内で待機する時間 - Name: sleep_time sleep_time - DefaultValue: 0.1 - Unit: s """ - self._sleep_time = [0.1] - """ + self._sleep_time = [0.1] + """ - mode: 計測モード名。logincr, incr, const から選択可能。 - logincr: logスケールでデータ数を増加させ計測。実際には、1, 2, 5, 10, .. といった間隔でデータ数を増加させ、logスケールでプ @@ -197,22 +192,22 @@ def __init__(self, manager): - DefaultValue: logincr - Constraint: (logincr,incr,const) """ - self._mode = ['logincr'] - """ + self._mode = ['logincr'] + """ 最大データ個数を指定する。送信するシーケンスデータのサイズを指定する。実際の データサイズは、この個数に1データ当たりのバイト数をかけたものとなる。 - Name: maxsize maxsize - DefaultValue: 1000000 """ - self._maxsize = [1000000] - """ + self._maxsize = [1000000] + """ 最大送信数。データ送信回数の最大値を指定する。モードがlogincr, incr の場合、データサイズ毎に maxsend 回数データを送信する。 - Name: maxsend maxsend - DefaultValue: 1000 """ - self._maxsend = [1000] - """ + self._maxsend = [1000] + """ 最大サンプリング数。データを受信し、統計情報を計算する際の最大サンプル数を指 定する。データ送信側の送信数がサンプル数より少ない場合、受信したサンプル数で 統計情報を計算する。データ送信側の送信数がサンプル数より多い場合、古い情報は @@ -220,368 +215,367 @@ def __init__(self, manager): - Name: maxsample maxsample - DefaultValue: 100 """ - self._maxsample = [100] - """ + self._maxsample = [100] + """ ファイル識別子 - Name: filesuffix filesuffix - DefaultValue: -test """ - self._filesuffix = ['-test'] - - # - self._datasize = 0 - self._fs = None - self._record = [] - self._sendcount = 0 - self._logmulcnt = 0 - self._varsize = 0 - - - - ## - # - # The initialize action (on CREATED->ALIVE transition) - # formaer rtc_init_entry() - # - # @return RTC::ReturnCode_t - # - # - def onInitialize(self): - # Bind variables and configuration variable - self.bindParameter("datatype", self._datatype, "double") - self.bindParameter("outputfile", self._outputfile, "test.dat") - self.bindParameter("increment", self._increment, "100") - self.bindParameter("sleep_time", self._sleep_time, "0.1") - self.bindParameter("mode", self._mode, "logincr") - self.bindParameter("maxsize", self._maxsize, "1000000") - self.bindParameter("maxsend", self._maxsend, "1000") - self.bindParameter("maxsample", self._maxsample, "100") - self.bindParameter("filesuffix", self._filesuffix, "-test") - - # Set InPort buffers - - # Set OutPort buffers - - # Set service provider to Ports - - # Set service consumers to Ports - - # Set CORBA Service Ports - #self.getConfigService().update() - #print self._datatype - self._data_type = OpenRTM_aist.normalize(self._datatype) - if self._data_type == "octet": - self._d_in = RTC.TimedOctetSeq(RTC.Time(0,0), []) - self._d_out = RTC.TimedOctetSeq(RTC.Time(0,0), []) - self._varsize = 1 - elif self._data_type == "short": - self._d_in = RTC.TimedShortSeq(RTC.Time(0,0), []) - self._d_out = RTC.TimedShortSeq(RTC.Time(0,0), []) - self._varsize = 2 - elif self._data_type == "long": - self._d_in = RTC.TimedLongSeq(RTC.Time(0,0), []) - self._d_out = RTC.TimedLongSeq(RTC.Time(0,0), []) - self._varsize = 4 - elif self._data_type == "float": - self._d_in = RTC.TimedFloatSeq(RTC.Time(0,0), []) - self._d_out = RTC.TimedFloatSeq(RTC.Time(0,0), []) - self._varsize = 4 - elif self._data_type == "double": - self._d_in = RTC.TimedDoubleSeq(RTC.Time(0,0), []) - self._d_out = RTC.TimedDoubleSeq(RTC.Time(0,0), []) - self._varsize = 8 - else: - return RTC.RTC_ERROR - - - self._inIn = OpenRTM_aist.InPort("in", self._d_in) - self.addInPort("in",self._inIn) - self._outOut = OpenRTM_aist.OutPort("out", self._d_out) - self.addOutPort("out",self._outOut) - self._inIn.addConnectorDataListener(OpenRTM_aist.ConnectorDataListenerType.ON_BUFFER_WRITE, - DataListener(self, self._d_in)) - self._inIn.addConnectorListener(OpenRTM_aist.ConnectorListenerType.ON_CONNECT, - ConnListener(self)) - - return RTC.RTC_OK - - def receiveData(self, tm, seq_length): - received_time = OpenRTM_aist.Time().getTime() - if self._size == 0: - self._size = seq_length - record_num = len(self._record) - record_ptr = record_num - if self._size != seq_length and record_num != 0: - - max_latency = 0.0 - min_latency = 0.0 - mean_latency = 0.0 - variance = 0.0 - stddev = 0.0 - throughput = 0.0 - sum = 0.0 - sq_sum = 0.0 - record_len = len(self._record) - - #print record_len - - - for d in self._record: - tmp = d - sum += tmp - sq_sum += tmp * tmp - if tmp > max_latency: - max_latency = tmp - elif tmp < min_latency: - min_latency = tmp - - mean_latency = sum / record_len - variance = (sq_sum / record_len) - (mean_latency * mean_latency) - stddev = math.sqrt(variance) - throughput = ((((self._size * self._varsize) + 8) * 8) / mean_latency) / (1024 * 1024) - - self._fs.write(str(self._size)+"\t") - self._fs.write(str(min_latency)+"\t"+str(max_latency)+"\t") - self._fs.write(str(mean_latency)+"\t"+str(stddev)+"\t") - self._fs.write(str(throughput)+"\n") - self._record = [] - - if seq_length < self._size: - - async = OpenRTM_aist.Async_tInvoker(self, Throughput_py.exit) - async.invoke() - return - send_time = OpenRTM_aist.TimeValue(tm.sec, tm.nsec/1000) - if record_ptr == self._maxsample[0]: - self._record.pop(0) - self._record.append((received_time-send_time).toDouble()) - self._size = seq_length - - - def setConnectorProfile(self, info): - outputfile = self._datatype[0] + "-" + info.properties.getProperty("interface_type") + self._filesuffix[0] + ".dat" - if self._fs is None: - try: - self._fs = open(outputfile, 'w') - except: - print("File open failed!!") - return - self._fs.write("# Profile::name: " + info.name + "\n") - self._fs.write("# Profile::id: " + info.id + "\n") - self._fs.write("# Profile::properties: " + "\n") - ss = str(info.properties) - propv = ss.split("\n") - for prop in propv: - self._fs.write("# " + prop + "\n") - self._fs.write("size[byte]\tmin[s]\tmax[s]\tmean[s]\tstddev[s]\tthroughpiut[Mbps]" + "\n") - - #print outputfile - #print "setConnectorProfile" - def setDataSize(self, size): - self._d_out.data = [0]*size - #print "setDataSize" - def getDataSize(self): - #print "getDataSize" - return len(self._d_out.data) - def writeData(self): - OpenRTM_aist.setTimestamp(self._d_out) - self._outOut.write() - #print "writeData" - def getInPortConnectorSize(self): - return len(self._inIn.get_connector_profiles()) - - # ## - # # - # # The finalize action (on ALIVE->END transition) - # # formaer rtc_exiting_entry() - # # - # # @return RTC::ReturnCode_t - # - # # - #def onFinalize(self): - # - # return RTC.RTC_OK - - # ## - # # - # # The startup action when ExecutionContext startup - # # former rtc_starting_entry() - # # - # # @param ec_id target ExecutionContext Id - # # - # # @return RTC::ReturnCode_t - # # - # # - #def onStartup(self, ec_id): - # - # return RTC.RTC_OK - - # ## - # # - # # The shutdown action when ExecutionContext stop - # # former rtc_stopping_entry() - # # - # # @param ec_id target ExecutionContext Id - # # - # # @return RTC::ReturnCode_t - # # - # # - #def onShutdown(self, ec_id): - # - # return RTC.RTC_OK - - ## - # - # The activated action (Active state entry action) - # former rtc_active_entry() - # - # @param ec_id target ExecutionContext Id - # - # @return RTC::ReturnCode_t - # - # - def onActivated(self, ec_id): - self._datasize = 1 - self.setDataSize(int(self._datasize)) - self._sendcount = 0 - self._logmulcnt = 0 - return RTC.RTC_OK - - ## - # - # The deactivated action (Active state exit action) - # former rtc_active_exit() - # - # @param ec_id target ExecutionContext Id - # - # @return RTC::ReturnCode_t - # - # - def onDeactivated(self, ec_id): - if self._fs: - self._fs.close() - self._fs = None - self._datasize = 1 - self.setDataSize(self._datasize) - self._sendcount = 0 - self._logmulcnt = 0 - - if self.getInPortConnectorSize() == 0: - async = OpenRTM_aist.Async_tInvoker(self, Throughput_py.exit) - async.invoke() - return RTC.RTC_OK - - ## - # - # The execution action that is invoked periodically - # former rtc_active_do() - # - # @param ec_id target ExecutionContext Id - # - # @return RTC::ReturnCode_t - # - # - def onExecute(self, ec_id): - logmul = [2.0, 2.5, 2.0] - if self.getDataSize() != self._datasize: - self.setDataSize(int(self._datasize)) - self.writeData() - self._sendcount += 1 - if self._sendcount%(self._maxsample[0]+1) != 0: - return RTC.RTC_OK - - if self._mode[0] == "logincr": - self._datasize *= logmul[self._logmulcnt%3] - self._logmulcnt += 1 - #print self._datasize, self._logmulcnt - elif self._mode[0] == "incr": - self._datasize += self._increment[0] - else: - if self._sendcount > self._maxsend[0]: - self.deactivate(ec_id) - return RTC.RTC_OK - time.sleep(self._sleep_time[0]) - if self._datasize > self._maxsize[0]: - print("Exiting") - self.setDataSize(1) - self.writeData() - self.deactivate(ec_id) - - - return RTC.RTC_OK - - # ## - # # - # # The aborting action when main logic error occurred. - # # former rtc_aborting_entry() - # # - # # @param ec_id target ExecutionContext Id - # # - # # @return RTC::ReturnCode_t - # # - # # - #def onAborting(self, ec_id): - # - # return RTC.RTC_OK - - # ## - # # - # # The error action in ERROR state - # # former rtc_error_do() - # # - # # @param ec_id target ExecutionContext Id - # # - # # @return RTC::ReturnCode_t - # # - # # - #def onError(self, ec_id): - # - # return RTC.RTC_OK - - # ## - # # - # # The reset action that is invoked resetting - # # This is same but different the former rtc_init_entry() - # # - # # @param ec_id target ExecutionContext Id - # # - # # @return RTC::ReturnCode_t - # # - # # - #def onReset(self, ec_id): - # - # return RTC.RTC_OK - - # ## - # # - # # The state update action that is invoked after onExecute() action - # # no corresponding operation exists in OpenRTm-aist-0.2.0 - # # - # # @param ec_id target ExecutionContext Id - # # - # # @return RTC::ReturnCode_t - # # - - # # - #def onStateUpdate(self, ec_id): - # - # return RTC.RTC_OK - - # ## - # # - # # The action that is invoked when execution context's rate is changed - # # no corresponding operation exists in OpenRTm-aist-0.2.0 - # # - # # @param ec_id target ExecutionContext Id - # # - # # @return RTC::ReturnCode_t - # # - # # - #def onRateChanged(self, ec_id): - # - # return RTC.RTC_OK - - + self._filesuffix = ['-test'] + + # + self._datasize = 0 + self._fs = None + self._record = [] + self._sendcount = 0 + self._logmulcnt = 0 + self._varsize = 0 + + ## + # + # The initialize action (on CREATED->ALIVE transition) + # formaer rtc_init_entry() + # + # @return RTC::ReturnCode_t + # + # + + def onInitialize(self): + # Bind variables and configuration variable + self.bindParameter("datatype", self._datatype, "double") + self.bindParameter("outputfile", self._outputfile, "test.dat") + self.bindParameter("increment", self._increment, "100") + self.bindParameter("sleep_time", self._sleep_time, "0.1") + self.bindParameter("mode", self._mode, "logincr") + self.bindParameter("maxsize", self._maxsize, "1000000") + self.bindParameter("maxsend", self._maxsend, "1000") + self.bindParameter("maxsample", self._maxsample, "100") + self.bindParameter("filesuffix", self._filesuffix, "-test") + + # Set InPort buffers + + # Set OutPort buffers + + # Set service provider to Ports + + # Set service consumers to Ports + + # Set CORBA Service Ports + # self.getConfigService().update() + # print self._datatype + self._data_type = OpenRTM_aist.normalize(self._datatype) + if self._data_type == "octet": + self._d_in = RTC.TimedOctetSeq(RTC.Time(0, 0), []) + self._d_out = RTC.TimedOctetSeq(RTC.Time(0, 0), []) + self._varsize = 1 + elif self._data_type == "short": + self._d_in = RTC.TimedShortSeq(RTC.Time(0, 0), []) + self._d_out = RTC.TimedShortSeq(RTC.Time(0, 0), []) + self._varsize = 2 + elif self._data_type == "long": + self._d_in = RTC.TimedLongSeq(RTC.Time(0, 0), []) + self._d_out = RTC.TimedLongSeq(RTC.Time(0, 0), []) + self._varsize = 4 + elif self._data_type == "float": + self._d_in = RTC.TimedFloatSeq(RTC.Time(0, 0), []) + self._d_out = RTC.TimedFloatSeq(RTC.Time(0, 0), []) + self._varsize = 4 + elif self._data_type == "double": + self._d_in = RTC.TimedDoubleSeq(RTC.Time(0, 0), []) + self._d_out = RTC.TimedDoubleSeq(RTC.Time(0, 0), []) + self._varsize = 8 + else: + return RTC.RTC_ERROR + + self._inIn = OpenRTM_aist.InPort("in", self._d_in) + self.addInPort("in", self._inIn) + self._outOut = OpenRTM_aist.OutPort("out", self._d_out) + self.addOutPort("out", self._outOut) + self._inIn.addConnectorDataListener(OpenRTM_aist.ConnectorDataListenerType.ON_BUFFER_WRITE, + DataListener(self, self._d_in)) + self._inIn.addConnectorListener(OpenRTM_aist.ConnectorListenerType.ON_CONNECT, + ConnListener(self)) + + return RTC.RTC_OK + + def receiveData(self, tm, seq_length): + received_time = OpenRTM_aist.Time().getTime() + if self._size == 0: + self._size = seq_length + record_num = len(self._record) + record_ptr = record_num + if self._size != seq_length and record_num != 0: + + max_latency = 0.0 + min_latency = 0.0 + mean_latency = 0.0 + variance = 0.0 + stddev = 0.0 + throughput = 0.0 + sum = 0.0 + sq_sum = 0.0 + record_len = len(self._record) + + # print record_len + + for d in self._record: + tmp = d + sum += tmp + sq_sum += tmp * tmp + if tmp > max_latency: + max_latency = tmp + elif tmp < min_latency: + min_latency = tmp + + mean_latency = sum / record_len + variance = (sq_sum / record_len) - (mean_latency * mean_latency) + stddev = math.sqrt(variance) + throughput = ((((self._size * self._varsize) + 8) + * 8) / mean_latency) / (1024 * 1024) + + self._fs.write(str(self._size) + "\t") + self._fs.write(str(min_latency) + "\t" + str(max_latency) + "\t") + self._fs.write(str(mean_latency) + "\t" + str(stddev) + "\t") + self._fs.write(str(throughput) + "\n") + self._record = [] + + if seq_length < self._size: + async_ = OpenRTM_aist.Async_tInvoker(self, Throughput_py.exit) + async_.invoke() + return + send_time = OpenRTM_aist.TimeValue(tm.sec, tm.nsec / 1000) + if record_ptr == self._maxsample[0]: + self._record.pop(0) + self._record.append((received_time - send_time).toDouble()) + self._size = seq_length + + def setConnectorProfile(self, info): + outputfile = self._datatype[0] + "-" + info.properties.getProperty( + "interface_type") + self._filesuffix[0] + ".dat" + if self._fs is None: + try: + self._fs = open(outputfile, 'w') + except BaseException: + print("File open failed!!") + return + self._fs.write("# Profile::name: " + info.name + "\n") + self._fs.write("# Profile::id: " + info.id + "\n") + self._fs.write("# Profile::properties: " + "\n") + ss = str(info.properties) + propv = ss.split("\n") + for prop in propv: + self._fs.write("# " + prop + "\n") + self._fs.write( + "size[byte]\tmin[s]\tmax[s]\tmean[s]\tstddev[s]\tthroughpiut[Mbps]" + + "\n") + + # print outputfile + # print "setConnectorProfile" + def setDataSize(self, size): + self._d_out.data = [0] * size + # print "setDataSize" + + def getDataSize(self): + # print "getDataSize" + return len(self._d_out.data) + + def writeData(self): + OpenRTM_aist.setTimestamp(self._d_out) + self._outOut.write() + # print "writeData" + + def getInPortConnectorSize(self): + return len(self._inIn.get_connector_profiles()) + + # ## + # # + # # The finalize action (on ALIVE->END transition) + # # formaer rtc_exiting_entry() + # # + # # @return RTC::ReturnCode_t + # + # # + # def onFinalize(self): + # + # return RTC.RTC_OK + + # ## + # # + # # The startup action when ExecutionContext startup + # # former rtc_starting_entry() + # # + # # @param ec_id target ExecutionContext Id + # # + # # @return RTC::ReturnCode_t + # # + # # + # def onStartup(self, ec_id): + # + # return RTC.RTC_OK + + # ## + # # + # # The shutdown action when ExecutionContext stop + # # former rtc_stopping_entry() + # # + # # @param ec_id target ExecutionContext Id + # # + # # @return RTC::ReturnCode_t + # # + # # + # def onShutdown(self, ec_id): + # + # return RTC.RTC_OK + + ## + # + # The activated action (Active state entry action) + # former rtc_active_entry() + # + # @param ec_id target ExecutionContext Id + # + # @return RTC::ReturnCode_t + # + # + def onActivated(self, ec_id): + self._datasize = 1 + self.setDataSize(int(self._datasize)) + self._sendcount = 0 + self._logmulcnt = 0 + return RTC.RTC_OK + + ## + # + # The deactivated action (Active state exit action) + # former rtc_active_exit() + # + # @param ec_id target ExecutionContext Id + # + # @return RTC::ReturnCode_t + # + # + def onDeactivated(self, ec_id): + if self._fs: + self._fs.close() + self._fs = None + self._datasize = 1 + self.setDataSize(self._datasize) + self._sendcount = 0 + self._logmulcnt = 0 + + if self.getInPortConnectorSize() == 0: + async_ = OpenRTM_aist.Async_tInvoker(self, Throughput_py.exit) + async_.invoke() + return RTC.RTC_OK + + ## + # + # The execution action that is invoked periodically + # former rtc_active_do() + # + # @param ec_id target ExecutionContext Id + # + # @return RTC::ReturnCode_t + # + # + def onExecute(self, ec_id): + logmul = [2.0, 2.5, 2.0] + if self.getDataSize() != self._datasize: + self.setDataSize(int(self._datasize)) + self.writeData() + self._sendcount += 1 + if self._sendcount % (self._maxsample[0] + 1) != 0: + return RTC.RTC_OK + + if self._mode[0] == "logincr": + self._datasize *= logmul[self._logmulcnt % 3] + self._logmulcnt += 1 + # print self._datasize, self._logmulcnt + elif self._mode[0] == "incr": + self._datasize += self._increment[0] + else: + if self._sendcount > self._maxsend[0]: + self.deactivate(ec_id) + return RTC.RTC_OK + time.sleep(self._sleep_time[0]) + if self._datasize > self._maxsize[0]: + print("Exiting") + self.setDataSize(1) + self.writeData() + self.deactivate(ec_id) + + return RTC.RTC_OK + + # ## + # # + # # The aborting action when main logic error occurred. + # # former rtc_aborting_entry() + # # + # # @param ec_id target ExecutionContext Id + # # + # # @return RTC::ReturnCode_t + # # + # # + # def onAborting(self, ec_id): + # + # return RTC.RTC_OK + + # ## + # # + # # The error action in ERROR state + # # former rtc_error_do() + # # + # # @param ec_id target ExecutionContext Id + # # + # # @return RTC::ReturnCode_t + # # + # # + # def onError(self, ec_id): + # + # return RTC.RTC_OK + + # ## + # # + # # The reset action that is invoked resetting + # # This is same but different the former rtc_init_entry() + # # + # # @param ec_id target ExecutionContext Id + # # + # # @return RTC::ReturnCode_t + # # + # # + # def onReset(self, ec_id): + # + # return RTC.RTC_OK + + # ## + # # + # # The state update action that is invoked after onExecute() action + # # no corresponding operation exists in OpenRTm-aist-0.2.0 + # # + # # @param ec_id target ExecutionContext Id + # # + # # @return RTC::ReturnCode_t + # # + + # # + # def onStateUpdate(self, ec_id): + # + # return RTC.RTC_OK + + # ## + # # + # # The action that is invoked when execution context's rate is changed + # # no corresponding operation exists in OpenRTm-aist-0.2.0 + # # + # # @param ec_id target ExecutionContext Id + # # + # # @return RTC::ReturnCode_t + # # + # # + # def onRateChanged(self, ec_id): + # + # return RTC.RTC_OK def Throughput_pyInit(manager): @@ -590,18 +584,20 @@ def Throughput_pyInit(manager): Throughput_py, OpenRTM_aist.Delete) + def MyModuleInit(manager): Throughput_pyInit(manager) # Create a component comp = manager.createComponent("Throughput_py") + def main(): - mgr = OpenRTM_aist.Manager.init(sys.argv) - mgr.setModuleInitProc(MyModuleInit) - mgr.activateManager() - mgr.runManager() + mgr = OpenRTM_aist.Manager.init(sys.argv) + mgr.setModuleInitProc(MyModuleInit) + mgr.activateManager() + mgr.runManager() -if __name__ == "__main__": - main() +if __name__ == "__main__": + main() diff --git a/OpenRTM_aist/examples/TkJoyStick/TkJoyStickComp.py b/OpenRTM_aist/examples/TkJoyStick/TkJoyStickComp.py index b7cc9ee4..2669345e 100644 --- a/OpenRTM_aist/examples/TkJoyStick/TkJoyStickComp.py +++ b/OpenRTM_aist/examples/TkJoyStick/TkJoyStickComp.py @@ -1,101 +1,99 @@ -#!/usr/bin/env python +#!/usr/bin/env python # -*- coding: utf-8 -*- # -*- Python -*- from __future__ import print_function +import tkjoystick +import math +import OpenRTM_aist +import RTC import sys import time sys.path.append(".") # Import RTM module -import RTC -import OpenRTM_aist # for convert() -import math # This module's spesification # -tkjoystick_spec = ["implementation_id", "TkJoyStick", - "type_name", "TkJoyStick", - "description", "Sample component for MobileRobotCanvas component", - "version", "1.0", - "vendor", "Noriaki Ando and Shinji Kurihara", - "category", "example", - "activity_type", "DataFlowComponent", - "max_instance", "10", - "language", "Python", - "lang_type", "SCRIPT", +tkjoystick_spec = ["implementation_id", "TkJoyStick", + "type_name", "TkJoyStick", + "description", "Sample component for MobileRobotCanvas component", + "version", "1.0", + "vendor", "Noriaki Ando and Shinji Kurihara", + "category", "example", + "activity_type", "DataFlowComponent", + "max_instance", "10", + "language", "Python", + "lang_type", "SCRIPT", ""] # -import tkjoystick class Position: - def __init__(self, x = 0.0, y = 0.0, r = 0.0, th = 0.0): - self.x = x - self.y = y - self.r = r - self.th = th + def __init__(self, x=0.0, y=0.0, r=0.0, th=0.0): + self.x = x + self.y = y + self.r = r + self.th = th + position = Position() #tkJoyCanvas = tkjoystick.TkJoystick() class TkJoyStick(OpenRTM_aist.DataFlowComponentBase): - def __init__(self, manager): - OpenRTM_aist.DataFlowComponentBase.__init__(self, manager) - - self._k = 1.0 - self.x = 0.0 - self.y = 0.0 - - - def onInitialize(self): - self._d_pos = RTC.TimedFloatSeq(RTC.Time(0,0),[]) - self._posOut = OpenRTM_aist.OutPort("pos", self._d_pos) - self._d_vel = RTC.TimedFloatSeq(RTC.Time(0,0),[]) - self._velOut = OpenRTM_aist.OutPort("vel", self._d_vel) - - # Set OutPort buffers - self.addOutPort("pos",self._posOut) - self.addOutPort("vel",self._velOut) - - return RTC.RTC_OK - - - def onShutdown(self, ec_id): - return RTC.RTC_OK - - - def onExecute(self, ec_id): - self._d_pos.data = [self.x, self.y] - self._d_vel.data = self.convert(self.x, self.y) - self._posOut.write() - self._velOut.write() - - return RTC.RTC_OK + def __init__(self, manager): + OpenRTM_aist.DataFlowComponentBase.__init__(self, manager) - """ + self._k = 1.0 + self.x = 0.0 + self.y = 0.0 + + def onInitialize(self): + self._d_pos = RTC.TimedFloatSeq(RTC.Time(0, 0), []) + self._posOut = OpenRTM_aist.OutPort("pos", self._d_pos) + self._d_vel = RTC.TimedFloatSeq(RTC.Time(0, 0), []) + self._velOut = OpenRTM_aist.OutPort("vel", self._d_vel) + + # Set OutPort buffers + self.addOutPort("pos", self._posOut) + self.addOutPort("vel", self._velOut) + + return RTC.RTC_OK + + def onShutdown(self, ec_id): + return RTC.RTC_OK + + def onExecute(self, ec_id): + self._d_pos.data = [self.x, self.y] + self._d_vel.data = self.convert(self.x, self.y) + self._posOut.write() + self._velOut.write() + + return RTC.RTC_OK + + """ \brief Converting from canvas data to MobileRobotCanvas data """ - def convert(self, x, y): - _th = math.atan2(y,x) - _v = self._k * math.hypot(x, y) - _vl = _v * math.cos(_th - (math.pi/4.0)) - _vr = _v * math.sin(_th - (math.pi/4.0)) - print(x, y, _vl, _vr) - return [_vl, _vr] - def set_pos(self, pos, pol): - self.x = pos[0] - self.y = pos[1] - self.r = pol[0] - self.th = pol[1] + def convert(self, x, y): + _th = math.atan2(y, x) + _v = self._k * math.hypot(x, y) + _vl = _v * math.cos(_th - (math.pi / 4.0)) + _vr = _v * math.sin(_th - (math.pi / 4.0)) + print(x, y, _vl, _vr) + return [_vl, _vr] + def set_pos(self, pos, pol): + self.x = pos[0] + self.y = pos[1] + self.r = pol[0] + self.th = pol[1] -#def MyModuleInit(manager): +# def MyModuleInit(manager): # profile = OpenRTM_aist.Properties(defaults_str=tkjoystick_spec) # manager.registerFactory(profile, # TkJoyStick, @@ -105,25 +103,24 @@ def set_pos(self, pos, pol): # comp = manager.createComponent("TkJoyStick") - def main(): - tkJoyCanvas = tkjoystick.TkJoystick() - tkJoyCanvas.master.title("TkJoystick") - mgr = OpenRTM_aist.Manager.init(sys.argv) - mgr.activateManager() - - # Register component - profile = OpenRTM_aist.Properties(defaults_str=tkjoystick_spec) - mgr.registerFactory(profile, - TkJoyStick, - OpenRTM_aist.Delete) - # Create a component - comp = mgr.createComponent("TkJoyStick") - - tkJoyCanvas.set_on_update(comp.set_pos) - mgr.runManager(True) - tkJoyCanvas.mainloop() + tkJoyCanvas = tkjoystick.TkJoystick() + tkJoyCanvas.main.title("TkJoystick") + mgr = OpenRTM_aist.Manager.init(sys.argv) + mgr.activateManager() -if __name__ == "__main__": - main() + # Register component + profile = OpenRTM_aist.Properties(defaults_str=tkjoystick_spec) + mgr.registerFactory(profile, + TkJoyStick, + OpenRTM_aist.Delete) + # Create a component + comp = mgr.createComponent("TkJoyStick") + + tkJoyCanvas.set_on_update(comp.set_pos) + mgr.runManager(True) + tkJoyCanvas.mainloop() + +if __name__ == "__main__": + main() diff --git a/OpenRTM_aist/examples/TkJoyStick/__init__.py b/OpenRTM_aist/examples/TkJoyStick/__init__.py index 932b7982..270be2a2 100644 --- a/OpenRTM_aist/examples/TkJoyStick/__init__.py +++ b/OpenRTM_aist/examples/TkJoyStick/__init__.py @@ -1 +1 @@ -# Empty file +# Empty file diff --git a/OpenRTM_aist/examples/TkJoyStick/tkjoystick.py b/OpenRTM_aist/examples/TkJoyStick/tkjoystick.py index e06f022e..d16b8cf6 100644 --- a/OpenRTM_aist/examples/TkJoyStick/tkjoystick.py +++ b/OpenRTM_aist/examples/TkJoyStick/tkjoystick.py @@ -1,4 +1,4 @@ -#!/usr/bin/env python +#!/usr/bin/env python # -*- coding: utf-8 -*- # -*- Python -*- @@ -34,7 +34,6 @@ from tkinter import * - class ToggleItem: def __init__(self): self.active = True @@ -62,12 +61,15 @@ def __init__(self, canvas, text, x, y): self.text = text self.x = x self.y = y + self.font = ('system', 9) self.draw_text(x, y, text) def draw(self): - if self.active == False: return + if self.active == False: + return self.delete() - self.id = self.canvas.create_text(self.x, self.y, text=self.text) + self.id = self.canvas.create_text(self.x, self.y, text=self.text, + font=self.font) def draw_text(self, x, y, text): self.x = x @@ -82,32 +84,35 @@ def delete(self): class CanvasAxis(ToggleItem): def __init__(self, canvas, width, height): ToggleItem.__init__(self) - self.x0 = width/2 - self.y0 = height/2 + self.x0 = width / 2 + self.y0 = height / 2 self.width = width self.height = height self.canvas = canvas self.id = [None] * 4 + self.font = ('system', 9) self.draw() def draw(self): - if self.active == False: return + if self.active == False: + return self.delete() - self.id[0] = self.canvas.create_line(0, self.height/2, - self.width, self.height/2) + self.id[0] = self.canvas.create_line(0, self.height / 2, + self.width, self.height / 2) self.id[1] = self.canvas.create_text(self.width - 10, - self.height/2 + 10, - text="x") - self.id[2] = self.canvas.create_line(self.width/2, 0, - self.width/2, self.height) - self.id[3] = self.canvas.create_text(self.width/2 + 10, - + 10, text="y") + self.height / 2 + 10, + text="x", font=self.font) + self.id[2] = self.canvas.create_line(self.width / 2, 0, + self.width / 2, self.height) + self.id[3] = self.canvas.create_text(self.width / 2 + 10, + + 10, text="y", font=self.font) return def delete(self): for i in self.id: self.canvas.delete(i) + class CanvasCircle(ToggleItem): def __init__(self, canvas, x, y, width, height, pitch): ToggleItem.__init__(self) @@ -121,7 +126,8 @@ def __init__(self, canvas, x, y, width, height, pitch): self.draw() def draw(self): - if self.active == False: return + if self.active == False: + return self.delete() if self.pitch == 0: circnum = 0 @@ -142,7 +148,7 @@ def draw(self): else: color = "#eeeeee" id = self.canvas.create_oval(x0, y0, x1, y1, fill=color, - outline="#ffffff") + outline="#ffffff") self.id.append(id) id = self.id id.reverse() @@ -157,6 +163,7 @@ def set_pitch(self, pitch): self.pitch = pitch self.draw() + class CanvasLine(ToggleItem): def __init__(self, canvas, x0, y0, x1, y1, color, width): ToggleItem.__init__(self) @@ -172,10 +179,12 @@ def __init__(self, canvas, x0, y0, x1, y1, color, width): self.draw() def draw(self): - if self.active == False: return + if self.active == False: + return self.delete() self.id = self.canvas.create_line(self.x0, self.y0, self.x1, self.y1, fill=self.color, width=self.width) + def draw_line(self, x0, y0, x1, y1): self.x0 = x0 self.y0 = y0 @@ -186,12 +195,13 @@ def draw_line(self, x0, y0, x1, y1): def delete(self): self.canvas.delete(self.id) + class Stick: def __init__(self, canvas, x, y, r, **key): self.canvas = canvas # Joystick ID self.key = key - self.id = self.canvas.create_oval(x-r, y-r, x+r, y+r, **key) + self.id = self.canvas.create_oval(x - r, y - r, x + r, y + r, **key) # ID of the line from center to joystick handle self.line = None # (x,y) text ID @@ -232,7 +242,7 @@ def make_binds(self): self.canvas.tag_bind(self.id, '<1>', self.drag_start) self.canvas.tag_bind(self.id, '', self.dragging) self.canvas.tag_bind(self.id, '', self.drag_end) - + def drag_start(self, event): # Calculate offset on the clocked position x1 = event.x - self.offsetx @@ -244,9 +254,9 @@ def drag_start(self, event): # self.draw_text() # Callback - if self.on_drag_start != None: + if self.on_drag_start is not None: self.on_drag_start((self.pos_x, self.pos_y), (self.r, self.th)) - + def dragging(self, event): # Moving length of drag x1 = event.x - self.offsetx @@ -261,11 +271,11 @@ def dragging(self, event): self.x = x1 - self.coffx self.y = y1 - self.coffy self.pos_x = self.x - self.pos_y = -self.y + self.pos_y = -self.y self.calc_pol(self.pos_x, self.pos_y) # Callback - if self.on_dragging != None: + if self.on_dragging is not None: self.on_dragging((self.pos_x, self.pos_y), (self.r, self.th)) def drag_end(self, event): @@ -281,7 +291,7 @@ def drag_end(self, event): self.pos_y = 0 self.calc_pol(self.pos_x, self.pos_y) # Callback - if self.on_drag_end != None: + if self.on_drag_end is not None: self.on_drag_end((self.pos_x, self.pos_y), (self.r, self.th)) def calc_pol(self, x, y): @@ -301,8 +311,8 @@ def get_pos(self): class TkJoystick(Frame): - def __init__(self, r=10, width=300, height=300, master=None): - Frame.__init__(self, master) + def __init__(self, r=10, width=300, height=300, main=None): + Frame.__init__(self, main) self.pos_x = 0.0 self.pos_y = 0.0 @@ -316,8 +326,8 @@ def __init__(self, r=10, width=300, height=300, master=None): self.wd = 160 - self.x0 = width/2 - self.y0 = height/2 + self.x0 = width / 2 + self.y0 = height / 2 self.xentry = "" self.yentry = "" @@ -369,16 +379,16 @@ def __init__(self, r=10, width=300, height=300, master=None): self.init() self.pack() - def init(self): - self.canvas = Canvas(self, bg="white", \ - width = self.width, height = self.height) + self.canvas = Canvas(self, bg="white", + width=self.width, height=self.height) + self.canvas.option_add('*font', 'system 9') self.canvas.pack(side=LEFT) # coaxial pattern - self.can_circle = CanvasCircle(self.canvas, - self.x0, self.y0, - self.width, self.height, pitch=50) + self.can_circle = CanvasCircle(self.canvas, + self.x0, self.y0, + self.width, self.height, pitch=50) # axis self.can_axis = CanvasAxis(self.canvas, self.width, self.height) @@ -392,20 +402,19 @@ def init(self): text = 'r: %4.2f, th: NaN' % (0.0) self.can_poltext = CanvasText(self.canvas, text, self.poltext_x, self.poltext_y) - + self.can_vline = CanvasLine(self.canvas, self.x0, self.y0, self.x0, self.y0, self.vline_color, self.vline_width) # joystick circle - self.stick = Stick(self.canvas, self.width/2, self.height/2, + self.stick = Stick(self.canvas, self.width / 2, self.height / 2, self.stick_r, fill="#999999", width=1) self.stick.set_on_drag_start(self.on_pos_update) self.stick.set_on_dragging(self.on_pos_update) self.stick.set_on_drag_end(self.on_pos_update) - # right side widgets self.frame = Frame(self, height=self.height, width=self.wd) self.frame.pack(side=LEFT, fill=Y, padx=3, pady=3) @@ -428,11 +437,11 @@ def create_scale(self, frame): return f def on_scale(self, val): - v = float(val) + v = float(val) if v == 0.0: pitch = 0 else: - pitch = self.default_pitch/v + pitch = self.default_pitch / v self.can_circle.set_pitch(pitch) def create_checkbutton(self, frame): @@ -440,10 +449,10 @@ def create_checkbutton(self, frame): dummy = Frame(f, width=self.wd) dummy.pack(side=TOP) vec = Checkbutton(f, text="Vector Line", - onvalue="on", offvalue="off", - justify=LEFT, anchor=W, - variable=self.vline_check, - command=self.can_vline.toggle) + onvalue="on", offvalue="off", + justify=LEFT, anchor=W, + variable=self.vline_check, + command=self.can_vline.toggle) axis = Checkbutton(f, text="Axis", onvalue="on", offvalue="off", justify=LEFT, anchor=W, @@ -454,16 +463,16 @@ def create_checkbutton(self, frame): justify=LEFT, anchor=W, variable=self.circ_check, command=self.can_circle.toggle) - xy = Checkbutton(f, text="X-Y position", - onvalue="on", offvalue="off", - justify=LEFT, anchor=W, - variable=self.xy_check, - command=self.can_xytext.toggle) - pol = Checkbutton(f, text="Polar postion", - onvalue="on", offvalue="off", - justify=LEFT, anchor=W, - variable=self.pol_check, - command=self.can_poltext.toggle) + xy = Checkbutton(f, text="X-Y position", + onvalue="on", offvalue="off", + justify=LEFT, anchor=W, + variable=self.xy_check, + command=self.can_xytext.toggle) + pol = Checkbutton(f, text="Polar postion", + onvalue="on", offvalue="off", + justify=LEFT, anchor=W, + variable=self.pol_check, + command=self.can_poltext.toggle) for w in [vec, axis, circ, xy, pol]: w.pack(side=TOP, anchor=W, fill=X) return f @@ -499,9 +508,9 @@ def create_pollabel(self, frame): def reset_scale(self): self.scale_var.set(1.) - pitch = self.default_pitch/1.0 + pitch = self.default_pitch / 1.0 self.can_circle.set_pitch(pitch) - + def get_pos(self): return self.pos_x, self.pos_y, self.pol_r, self.pol_th @@ -514,8 +523,10 @@ def on_pos_update(self, pos, pol): xt = '%4d' % (self.pos_x) yt = '%4d' % (self.pos_y) rt = '%5.2f' % (self.pol_r) - if pol[1] > 360: tht = 'NaN' - else: tht = '%5.2f' % self.pol_th + if pol[1] > 360: + tht = 'NaN' + else: + tht = '%5.2f' % self.pol_th self.xentry.set(xt) self.yentry.set(yt) @@ -534,19 +545,21 @@ def on_pos_update(self, pos, pol): self.x0 + pos[0], self.y0 - pos[1]) - if self.on_update != None: + if self.on_update is not None: self.on_update((self.pos_x, self.pos_y), (self.pol_r, self.pol_th)) def set_on_update(self, func): self.on_update = func -def test (): + +def test(): m = TkJoystick() - while 1: + while True: m.update() print(m.get_pos()) -if __name__ == '__main__': test() +if __name__ == '__main__': + test() diff --git a/OpenRTM_aist/examples/TkLRFViewer/TkLRFViewer.py b/OpenRTM_aist/examples/TkLRFViewer/TkLRFViewer.py index 49989e86..b81e61b3 100644 --- a/OpenRTM_aist/examples/TkLRFViewer/TkLRFViewer.py +++ b/OpenRTM_aist/examples/TkLRFViewer/TkLRFViewer.py @@ -1,4 +1,4 @@ -#!/usr/bin/env python +#!/usr/bin/env python # -*- coding: utf-8 -*- # -*- Python -*- # @@ -20,697 +20,700 @@ # $Log$ # +import threading +import OpenRTM_aist +import RTC +import math +import time import sys if sys.version_info[0] == 2: - from Tix import * + from Tix import * else: - from tkinter.tix import * -import time -import math + from tkinter.tix import * # Import RTM module -import RTC -import OpenRTM_aist # This module's spesification # -lrfviewer_spec = ["implementation_id", "LRFViewer", - "type_name", "LRFViewer", - "description", "Laser Range Finder Viewer component", - "version", "1.0", - "vendor", "Noriaki Ando, AIST", - "category", "example", - "activity_type", "DataFlowComponent", - "max_instance", "1", - "language", "Python", - "lang_type", "SCRIPT", +lrfviewer_spec = ["implementation_id", "LRFViewer", + "type_name", "LRFViewer", + "description", "Laser Range Finder Viewer component", + "version", "1.0", + "vendor", "Noriaki Ando, AIST", + "category", "example", + "activity_type", "DataFlowComponent", + "max_instance", "1", + "language", "Python", + "lang_type", "SCRIPT", ""] # -#------------------------------------------------------------ +# ------------------------------------------------------------ # LRFViewer component # -#------------------------------------------------------------ +# ------------------------------------------------------------ class LRFViewer(OpenRTM_aist.DataFlowComponentBase): - def __init__(self, manager): - OpenRTM_aist.DataFlowComponentBase.__init__(self, manager) - - self.range_data = [] - self.start_point = 0 - self.end_point = 768 - self.angular_res = 0.0 - return - - def onInitialize(self): - _pose3D = RTC.Pose3D(RTC.Point3D(0.0, 0.0, 0.0), - RTC.Orientation3D(0.0, 0.0, 0.0)) - _size3D = RTC.Size3D(0.0, 0.0, 0.0) - _geometry3D = RTC.Geometry3D(_pose3D, _size3D) - _rangerConfig = RTC.RangerConfig(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0) - self._d_rangeData = RTC.RangeData(RTC.Time(0,0), - [], - RTC.RangerGeometry(_geometry3D, []), - _rangerConfig) - - self._rangeDataIn = OpenRTM_aist.InPort("range_data", self._d_rangeData) - self.addInPort("range_data", self._rangeDataIn) - - return RTC.RTC_OK - - def onShutdown(self, ec_id): - return RTC.RTC_OK - - def onDeactivated(self, ec_id): - self.range_data = [] - self.start_point = 0 - self.end_point = 768 - return RTC.RTC_OK - - def onExecute(self, ec_id): - if self._rangeDataIn.isNew(): - _rangeData = self._rangeDataIn.read() - self.range_data = _rangeData.ranges - self.start_point = _rangeData.config.minAngle - self.end_point = _rangeData.config.maxAngle - self.angular_res = _rangeData.config.angularRes - time.sleep(0.01) - return RTC.RTC_OK - - def get_range_data(self): - return self.range_data - - def get_start_point(self): - return self.start_point - - def get_end_point(self): - return self.end_point - - def get_angular_res(self): - return self.angular_res + def __init__(self, manager): + OpenRTM_aist.DataFlowComponentBase.__init__(self, manager) + + self.range_data = [] + self.start_point = 0 + self.end_point = 768 + self.angular_res = 0.0 + return + + def onInitialize(self): + _pose3D = RTC.Pose3D(RTC.Point3D(0.0, 0.0, 0.0), + RTC.Orientation3D(0.0, 0.0, 0.0)) + _size3D = RTC.Size3D(0.0, 0.0, 0.0) + _geometry3D = RTC.Geometry3D(_pose3D, _size3D) + _rangerConfig = RTC.RangerConfig(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0) + self._d_rangeData = RTC.RangeData(RTC.Time(0, 0), + [], + RTC.RangerGeometry(_geometry3D, []), + _rangerConfig) + + self._rangeDataIn = OpenRTM_aist.InPort( + "range_data", self._d_rangeData) + self.addInPort("range_data", self._rangeDataIn) + + return RTC.RTC_OK + + def onShutdown(self, ec_id): + return RTC.RTC_OK + + def onDeactivated(self, ec_id): + self.range_data = [] + self.start_point = 0 + self.end_point = 768 + return RTC.RTC_OK + + def onExecute(self, ec_id): + if self._rangeDataIn.isNew(): + _rangeData = self._rangeDataIn.read() + self.range_data = _rangeData.ranges + self.start_point = _rangeData.config.minAngle + self.end_point = _rangeData.config.maxAngle + self.angular_res = _rangeData.config.angularRes + time.sleep(0.01) + return RTC.RTC_OK + + def get_range_data(self): + return self.range_data + + def get_start_point(self): + return self.start_point + + def get_end_point(self): + return self.end_point + + def get_angular_res(self): + return self.angular_res class ToggleItem: - def __init__(self): - self.active = True - return - - def __del__(self): - self.delete() - return - - def activate(self): - self.active = True - self.draw() - return - - def deactivate(self): - self.active = False - self.delete() - return - - def toggle(self): - if self.active: - self.deactivate() - else: - self.activate() - return + def __init__(self): + self.active = True + return + + def __del__(self): + self.delete() + return + + def activate(self): + self.active = True + self.draw() + return + + def deactivate(self): + self.active = False + self.delete() + return + + def toggle(self): + if self.active: + self.deactivate() + else: + self.activate() + return class CanvasText(ToggleItem): - def __init__(self, canvas, text, x, y): - ToggleItem.__init__(self) - self.canvas = canvas - self.id = self.canvas.create_text(x, y, text=text) - self.text = text - self.x = x - self.y = y - self.draw_text(x, y, text) - return - - def draw(self): - if self.active == False: return - self.delete() - self.id = self.canvas.create_text(self.x, self.y, text=self.text) - return - - def draw_text(self, x, y, text): - self.x = x - self.y = y - self.text = text - self.draw() - return - - def delete(self): - self.canvas.delete(self.id) - return + def __init__(self, canvas, text, x, y): + ToggleItem.__init__(self) + self.canvas = canvas + self.id = self.canvas.create_text(x, y, text=text) + self.text = text + self.x = x + self.y = y + self.draw_text(x, y, text) + return + + def draw(self): + if self.active == False: + return + self.delete() + self.id = self.canvas.create_text(self.x, self.y, text=self.text) + return + + def draw_text(self, x, y, text): + self.x = x + self.y = y + self.text = text + self.draw() + return + + def delete(self): + self.canvas.delete(self.id) + return + class CanvasGrid(ToggleItem): - def __init__(self, canvas, x0, y0, width, height, pitch, color, linewd): - ToggleItem.__init__(self) - self.canvas = canvas - self.x0 = x0 - self.y0 = y0 - self.width = width - self.height = height - self.pitch = pitch - self.color = color - self.linewd = linewd - self.idx = [] - self.idy = [] - - self.draw() - return - - def draw(self): - if self.active == False: return - self.delete() - - x_start = int(self.x0 % self.pitch) - x_num = int((self.width - x_start) / self.pitch) + 1 - for x in range(x_num): - x0 = x_start + self.pitch * x - id = self.canvas.create_line(x0, 0, x0, self.height, - fill=self.color, width=self.linewd) - self.idx.append(id) - - y_start = int(self.y0 % self.pitch) - y_num = int((self.height - y_start) / self.pitch) + 1 - for y in range(y_num): - y0 = y_start + self.pitch * y - id = self.canvas.create_line(0, y0, self.width, y0, - fill=self.color, width=self.linewd) - self.idy.append(id) - - for i in self.idx: - self.canvas.tag_lower(i) - for i in self.idy: - self.canvas.tag_lower(i) - - return - - def delete(self): - for i in self.idx: - self.canvas.delete(i) - for i in self.idy: - self.canvas.delete(i) - return - - def set_pitch(self, pitch): - if pitch != 0: - self.pitch = pitch - - self.draw() - return + def __init__(self, canvas, x0, y0, width, height, pitch, color, linewd): + ToggleItem.__init__(self) + self.canvas = canvas + self.x0 = x0 + self.y0 = y0 + self.width = width + self.height = height + self.pitch = pitch + self.color = color + self.linewd = linewd + self.idx = [] + self.idy = [] + + self.draw() + return + + def draw(self): + if self.active == False: + return + self.delete() + + x_start = int(self.x0 % self.pitch) + x_num = int((self.width - x_start) / self.pitch) + 1 + for x in range(x_num): + x0 = x_start + self.pitch * x + id = self.canvas.create_line(x0, 0, x0, self.height, + fill=self.color, width=self.linewd) + self.idx.append(id) + + y_start = int(self.y0 % self.pitch) + y_num = int((self.height - y_start) / self.pitch) + 1 + for y in range(y_num): + y0 = y_start + self.pitch * y + id = self.canvas.create_line(0, y0, self.width, y0, + fill=self.color, width=self.linewd) + self.idy.append(id) + + for i in self.idx: + self.canvas.tag_lower(i) + for i in self.idy: + self.canvas.tag_lower(i) + + return + + def delete(self): + for i in self.idx: + self.canvas.delete(i) + for i in self.idy: + self.canvas.delete(i) + return + + def set_pitch(self, pitch): + if pitch != 0: + self.pitch = pitch + + self.draw() + return class CanvasAxis(ToggleItem): - def __init__(self, canvas, width, height, color="#ffffff", linewd=1): - ToggleItem.__init__(self) - self.x0 = width/2 - self.y0 = height/2 - self.width = width - self.height = height - self.color = color - self.linewd = linewd - self.canvas = canvas - self.id = [None] * 4 - self.draw() - return - - def draw(self): - if self.active == False: return - self.delete() - self.id[0] = self.canvas.create_line(0, self.height/2, - self.width, self.height/2, - fill = self.color, - width = self.linewd) - self.id[1] = self.canvas.create_text(self.width - 10, - self.height/2 + 10, - text="x", - fill = self.color, - font="courier 12") - self.id[2] = self.canvas.create_line(self.width/2, 0, - self.width/2, self.height, - fill = self.color, - width = self.linewd) - self.id[3] = self.canvas.create_text(self.width/2 + 10, - + 10, text="y", - fill = self.color, - font="courier 12") - - return - - def delete(self): - for i in self.id: - self.canvas.delete(i) - return + def __init__(self, canvas, width, height, color="#ffffff", linewd=1): + ToggleItem.__init__(self) + self.x0 = width / 2 + self.y0 = height / 2 + self.width = width + self.height = height + self.color = color + self.linewd = linewd + self.canvas = canvas + self.id = [None] * 4 + self.draw() + return + + def draw(self): + if self.active == False: + return + self.delete() + self.id[0] = self.canvas.create_line(0, self.height / 2, + self.width, self.height / 2, + fill=self.color, + width=self.linewd) + self.id[1] = self.canvas.create_text(self.width - 10, + self.height / 2 + 10, + text="x", + fill=self.color, + font="courier 12") + self.id[2] = self.canvas.create_line(self.width / 2, 0, + self.width / 2, self.height, + fill=self.color, + width=self.linewd) + self.id[3] = self.canvas.create_text(self.width / 2 + 10, + + 10, text="y", + fill=self.color, + font="courier 12") + + return + + def delete(self): + for i in self.id: + self.canvas.delete(i) + return class ScaledObject: - def __init__(self, simulator): - self.simulator = simulator - self.tick = simulator.get_tick() - self.canvas = simulator.get_canvas() - self.trans = simulator.get_translation() - return + def __init__(self, simulator): + self.simulator = simulator + self.tick = simulator.get_tick() + self.canvas = simulator.get_canvas() + self.trans = simulator.get_translation() + return - def translate(self, x, y, dx, dy, dth): - return self.trans(x, y, dx, dy, dth) + def translate(self, x, y, dx, dy, dth): + return self.trans(x, y, dx, dy, dth) - def get_tick(self): - return self.simulator.get_tick() + def get_tick(self): + return self.simulator.get_tick() -#------------------------------------------------------------ +# ------------------------------------------------------------ # LRFrange range data drawing # -#------------------------------------------------------------ +# ------------------------------------------------------------ class LRFrange(ScaledObject): - def __init__(self, simulator, - line_color="#ff0000", fill_color="#ff0000", linewd=1): - ScaledObject.__init__(self, simulator) - self.fill_color = fill_color - self.line_color = line_color - self.default_fill_color = fill_color - self.default_line_color = line_color - self.linewd = linewd - self.rdata = [] - self.pre_data = [] - self.poly_id = None - self.source = None - - # URG parameter - self.beg_angle = -45 - self.end_angle = 225 - self.angle_per_step = 360.0 / 1024.0 - self.valid_beg_angle = 44 * 360.0 / 1024.0 - self.valid_end_angle = self.valid_beg_angle + 725 * self.angle_per_step - self.offset_step = 0 - - self.threshold = 0.0 - self.sfilter = 0.0 - self.tfilter = 0.0 - - self.threshold_check = BooleanVar() - self.threshold_check.set(True) - self.tfilter_check = BooleanVar() - self.tfilter_check.set(True) - self.sfilter_check = BooleanVar() - self.sfilter_check.set(True) - - self.threshold_var = DoubleVar() - self.threshold_var.set(self.threshold) - self.tfilter_var = DoubleVar() - self.tfilter_var.set(self.tfilter) - self.sfilter_var = DoubleVar() - self.sfilter_var.set(self.sfilter) - - self.update() - return - - def create_ctrl(self, frame): - self.lrf_fill_check = StringVar() - self.lrf_fill_check.set("on") - self.lrf_line_check = StringVar() - self.lrf_line_check.set("on") - - text = Label(frame, text="LRF range area", anchor=W, justify=LEFT) - # "Line" check box - line = Checkbutton(frame, text="Line", - onvalue="on", offvalue="off", - justify=LEFT, anchor=W, - variable=self.lrf_line_check, - command=self.line_toggle) - # "Fill" check box - fill = Checkbutton(frame, text="Fill", - onvalue="on", offvalue="off", - justify=LEFT, anchor=W, - variable=self.lrf_fill_check, - command=self.fill_toggle) - # Threshold (check box/scale) - thresh = Checkbutton(frame, text="Threshold", - onvalue=True, offvalue=False, - justify=LEFT, anchor=W, - variable=self.threshold_check) - thresh_scale = Scale(frame, from_=0, to=100, resolution=0.1, - label="Threshold", command=self.on_threshold, - variable=self.threshold_var, orient=HORIZONTAL) - # Time-Filter (check box/scale) - tfilter = Checkbutton(frame, text="Filter(Time)", - onvalue=True, offvalue=False, - justify=LEFT, anchor=W, - variable=self.tfilter_check) - tfilter_scale = Scale(frame, from_=0, to=1, resolution=0.01, - label="Filter", command=self.on_tfilter, - variable=self.tfilter_var, orient=HORIZONTAL) - # Spacial-Filter (check box/scale) - sfilter = Checkbutton(frame, text="Filter(Spacial)", - onvalue=True, offvalue=False, - justify=LEFT, anchor=W, - variable=self.sfilter_check) - sfilter_scale = Scale(frame, from_=0, to=1, resolution=0.01, - label="Filter", command=self.on_sfilter, - variable=self.sfilter_var, orient=HORIZONTAL) - - for w in [text, line, fill, thresh, thresh_scale, - tfilter, tfilter_scale, sfilter, sfilter_scale]: - w.pack(side=TOP, anchor=W, fill=X) - return - - def on_threshold(self, var): - self.threshold = self.threshold_var.get() - return - - def on_sfilter(self, var): - self.sfilter = self.sfilter_var.get() - return - - def on_tfilter(self, var): - self.tfilter = self.tfilter_var.get() - return - - def line_toggle(self): - if self.lrf_line_check.get() == "on": - self.line_color = self.default_line_color - else: - self.line_color = "" - return - - def fill_toggle(self): - if self.lrf_fill_check.get() == "on": - self.fill_color = self.default_fill_color - else: - self.fill_color = "" - return - - def set_data_source(self, source): - self.source = source - return - - def set_value(self, data): - self.rdata = data - return - - def draw(self): - self.delete() - rpos = [] - rpos.append(self.translate(0, 0, 0, 0, 0)) - rpos.append(self.range_to_pos(self.rdata)) - self.poly_id = self.canvas.create_polygon(rpos, - width = self.linewd, - outline = self.line_color, - fill = self.fill_color, - smooth = 1, - splinesteps = 5) - return - - def range_to_pos(self, data): - pos = [] - pre_d = 0 - - tfilter = self.tfilter_check.get() - sfilter = self.sfilter_check.get() - thresh = self.threshold_check.get() - - # Time-Filter - if tfilter and len(data) == len(self.pre_data): - for (n, d) in enumerate(data): - k_t = self.tfilter - data[n] = self.pre_data[n] * k_t + d * (1 - k_t) - - # Spacial Filter - for (n, d) in enumerate(data): - # Threshold - if thresh and d < self.threshold: - d = 10000 #pre_d - - if sfilter: - k_s = self.sfilter - d = pre_d * k_s + d * (1 - k_s) - pre_d = d - - # n: step number - # d: length data - #deg = (n + self.offset_step) * self.angle_per_step + self.beg_angle - #th = deg * math.pi / 180 - th = (n + self.offset_step) * self.angle_per_step + self.beg_angle - x = d * math.cos(th) - y = d * math.sin(th) - pos.append(self.translate(x, y, 0, 0, 0)) - self.pre_data = data - return pos - - def delete(self): - if self.poly_id != None: - self.canvas.delete(self.poly_id) - return - - def update(self): - if self.source != None: - rdata = self.source.get_range_data() - if len(rdata) != 0: - self.rdata = rdata - - res = self.source.get_angular_res() - if res: - self.angle_per_step = res - - beg_angle = self.source.get_start_point() - if beg_angle: - self.beg_angle = beg_angle - - end_angle = self.source.get_end_point() - if end_angle: - self.end_angle = end_angle - - else: - pass - self.draw() - - - -#------------------------------------------------------------ + def __init__(self, simulator, + line_color="#ff0000", fill_color="#ff0000", linewd=1): + ScaledObject.__init__(self, simulator) + self.fill_color = fill_color + self.line_color = line_color + self.default_fill_color = fill_color + self.default_line_color = line_color + self.linewd = linewd + self.rdata = [] + self.pre_data = [] + self.poly_id = None + self.source = None + + # URG parameter + self.beg_angle = -45 + self.end_angle = 225 + self.angle_per_step = 360.0 / 1024.0 + self.valid_beg_angle = 44 * 360.0 / 1024.0 + self.valid_end_angle = self.valid_beg_angle + 725 * self.angle_per_step + self.offset_step = 0 + + self.threshold = 0.0 + self.sfilter = 0.0 + self.tfilter = 0.0 + + self.threshold_check = BooleanVar() + self.threshold_check.set(True) + self.tfilter_check = BooleanVar() + self.tfilter_check.set(True) + self.sfilter_check = BooleanVar() + self.sfilter_check.set(True) + + self.threshold_var = DoubleVar() + self.threshold_var.set(self.threshold) + self.tfilter_var = DoubleVar() + self.tfilter_var.set(self.tfilter) + self.sfilter_var = DoubleVar() + self.sfilter_var.set(self.sfilter) + + self.update() + return + + def create_ctrl(self, frame): + self.lrf_fill_check = StringVar() + self.lrf_fill_check.set("on") + self.lrf_line_check = StringVar() + self.lrf_line_check.set("on") + + text = Label(frame, text="LRF range area", anchor=W, justify=LEFT) + # "Line" check box + line = Checkbutton(frame, text="Line", + onvalue="on", offvalue="off", + justify=LEFT, anchor=W, + variable=self.lrf_line_check, + command=self.line_toggle) + # "Fill" check box + fill = Checkbutton(frame, text="Fill", + onvalue="on", offvalue="off", + justify=LEFT, anchor=W, + variable=self.lrf_fill_check, + command=self.fill_toggle) + # Threshold (check box/scale) + thresh = Checkbutton(frame, text="Threshold", + onvalue=True, offvalue=False, + justify=LEFT, anchor=W, + variable=self.threshold_check) + thresh_scale = Scale(frame, from_=0, to=100, resolution=0.1, + label="Threshold", command=self.on_threshold, + variable=self.threshold_var, orient=HORIZONTAL) + # Time-Filter (check box/scale) + tfilter = Checkbutton(frame, text="Filter(Time)", + onvalue=True, offvalue=False, + justify=LEFT, anchor=W, + variable=self.tfilter_check) + tfilter_scale = Scale(frame, from_=0, to=1, resolution=0.01, + label="Filter", command=self.on_tfilter, + variable=self.tfilter_var, orient=HORIZONTAL) + # Spacial-Filter (check box/scale) + sfilter = Checkbutton(frame, text="Filter(Spacial)", + onvalue=True, offvalue=False, + justify=LEFT, anchor=W, + variable=self.sfilter_check) + sfilter_scale = Scale(frame, from_=0, to=1, resolution=0.01, + label="Filter", command=self.on_sfilter, + variable=self.sfilter_var, orient=HORIZONTAL) + + for w in [text, line, fill, thresh, thresh_scale, + tfilter, tfilter_scale, sfilter, sfilter_scale]: + w.pack(side=TOP, anchor=W, fill=X) + return + + def on_threshold(self, var): + self.threshold = self.threshold_var.get() + return + + def on_sfilter(self, var): + self.sfilter = self.sfilter_var.get() + return + + def on_tfilter(self, var): + self.tfilter = self.tfilter_var.get() + return + + def line_toggle(self): + if self.lrf_line_check.get() == "on": + self.line_color = self.default_line_color + else: + self.line_color = "" + return + + def fill_toggle(self): + if self.lrf_fill_check.get() == "on": + self.fill_color = self.default_fill_color + else: + self.fill_color = "" + return + + def set_data_source(self, source): + self.source = source + return + + def set_value(self, data): + self.rdata = data + return + + def draw(self): + self.delete() + rpos = [] + rpos.append(self.translate(0, 0, 0, 0, 0)) + rpos.append(self.range_to_pos(self.rdata)) + self.poly_id = self.canvas.create_polygon(rpos, + width=self.linewd, + outline=self.line_color, + fill=self.fill_color, + smooth=1, + splinesteps=5) + return + + def range_to_pos(self, data): + pos = [] + pre_d = 0 + scale_adj = 100.0 # change from 1 dot/m to 100 dot/m (dot/cm) + scale_threshold = 0.01 # change threshold value from m unit to cm unit + tfilter = self.tfilter_check.get() + sfilter = self.sfilter_check.get() + thresh = self.threshold_check.get() + + # Time-Filter + if tfilter and len(data) == len(self.pre_data): + for (n, d) in enumerate(data): + k_t = self.tfilter + data[n] = self.pre_data[n] * k_t + d * (1 - k_t) + + # Spacial Filter + for (n, d) in enumerate(data): + # Threshold + if thresh and d < self.threshold * scale_threshold: + d = 10000 # pre_d + + if sfilter: + k_s = self.sfilter + d = pre_d * k_s + d * (1 - k_s) + pre_d = d + + # n: step number + # d: length data + #deg = (n + self.offset_step) * self.angle_per_step + self.beg_angle + #th = deg * math.pi / 180 + th = (n + self.offset_step) * self.angle_per_step + self.beg_angle + x = d * math.cos(th) * scale_adj + y = d * math.sin(th) * scale_adj + pos.append(self.translate(x, y, 0, 0, 0)) + self.pre_data = data + return pos + + def delete(self): + if self.poly_id is not None: + self.canvas.delete(self.poly_id) + return + + def update(self): + if self.source is not None: + rdata = self.source.get_range_data() + if len(rdata) != 0: + self.rdata = rdata + + res = self.source.get_angular_res() + if res: + self.angle_per_step = res + + beg_angle = self.source.get_start_point() + if beg_angle: + self.beg_angle = beg_angle + + end_angle = self.source.get_end_point() + if end_angle: + self.end_angle = end_angle + + else: + pass + self.draw() + + +# ------------------------------------------------------------ # TkLRFViewer main windows class # -#------------------------------------------------------------ +# ------------------------------------------------------------ class TkLRFViewer(Frame): - def __init__(self, master=None, width=480, height=480): - Frame.__init__(self, master) + def __init__(self, main=None, width=480, height=480): + Frame.__init__(self, main) + + # canvas properties + self.width = width + self.height = height + # zero of canvas + self.x0 = width / 2 + self.y0 = height / 2 + + self.wd = 150 + + self.robots = {} + + self.robot = None + self.postext = None + + self.scale = 1.0 + self.scale_var = DoubleVar() + self.scale_var.set(self.scale) + + self.grid_pitch = 50 + + self.tick = 0.1 + self.default_tick = 0.1 + self.tickscale_var = DoubleVar() + self.tickscale_var.set(self.tick) + + self.axis_check = StringVar() + self.axis_check.set("on") + self.grid_check = StringVar() + self.grid_check.set("on") + self.rnames = {} + + self.init() + self.pack() + + self.after(20, self.on_update) + return + + def init(self): + self.canvas = Canvas(self, bg="#000000", + width=self.width, height=self.height) + self.canvas.option_add('*font', 'system 9') + self.canvas.pack(side=LEFT) + + self.can_grid = CanvasGrid(self.canvas, self.x0, self.y0, + self.width, self.height, self.grid_pitch, + "#aaaaaa", 1) + self.can_axis = CanvasAxis(self.canvas, self.width, self.height, + "#ffffff", 1) + + self.frame = Frame(self) + self.frame.pack(side=LEFT) + + # Screen control + self.scrctrl_frame = Frame(self.frame, width=self.wd, height=300, + relief=GROOVE, bd=2) + self.scrctrl_frame.pack(side=TOP, fill=X) + self.create_scale(self.scrctrl_frame) + self.create_checkbutton(self.scrctrl_frame) + + self.lrfctrl_frame = Frame(self.frame, width=self.wd, height=300, + relief=GROOVE, bd=2) + self.lrfctrl_frame.pack(side=TOP, fill=X) + self.lrf = LRFrange(self) + self.lrf.create_ctrl(self.lrfctrl_frame) + + return + + def on_update(self): + self.lrf.update() + self.after(20, self.on_update) + return + + def get_tick(self): + return self.tick + + def get_canvas(self): + return self.canvas + + def get_translation(self): + return self.real_to_canvas + + # ------------------------------------------------------------ + # Scale control set + + def create_scale(self, frame): + dummy = Frame(frame, width=self.wd) + dummy.pack(side=TOP) + sl = Scale(frame, from_=0, to=10, resolution=0.01, + label="Scale Factor", command=self.on_scale, + variable=self.scale_var, orient=HORIZONTAL) + bt = Button(frame, text="Reset Scale", command=self.reset_scale) + sl.pack(side=TOP, fill=X) + bt.pack(side=TOP, fill=X) + return + + def on_scale(self, val): + v = float(val) + if v == 0.0: + pitch = 0 + else: + pitch = self.grid_pitch / v + self.scale = v + self.can_grid.set_pitch(pitch) + return + + def reset_scale(self): + self.scale_var.set(1.) + pitch = self.grid_pitch / 1.0 + self.scale = 1.0 + self.can_grid.set_pitch(pitch) + return + + def on_tickchange(self, val): + v = self.tickscale_var.get() + if v == 0.0: + self.tick = 0 + else: + self.tick = v + return + + def reset_tickscale(self): + self.tick = self.default_tick + self.tickscale_var.set(self.default_tick) + + # end of Scale widget set + # ------------------------------------------------------------ + + # ------------------------------------------------------------ + # Canvas control set + def create_checkbutton(self, frame): + axis = Checkbutton(frame, text="Axis", + onvalue="on", offvalue="off", + justify=LEFT, anchor=W, + variable=self.axis_check, + command=self.can_axis.toggle) + grid = Checkbutton(frame, text="Grid", + onvalue="on", offvalue="off", + justify=LEFT, anchor=W, + variable=self.grid_check, + command=self.can_grid.toggle) + for w in [axis, grid]: + w.pack(side=TOP, anchor=W, fill=X) + + def on_rname_toggle(self): + for r in self.rnames.keys(): + self.rnames[r].toggle() + return + + # end of Canvas control set + # ------------------------------------------------------------ + + # ------------------------------------------------------------ + # + def real_to_canvas(self, x, y, dx, dy, dt): + # Simulator coordinate system -> display coordinate system + # x, y: original position + # dx, dy, dt: translation and rotation vector + # translation and rotation + x_tmp = (math.cos(dt) * x - math.sin(dt) * y + dx) / self.scale + y_tmp = (math.sin(dt) * x + math.cos(dt) * y + dy) / self.scale + # align to canvas coordinate system (origin is center and y+ is upward) + xo = x_tmp + self.x0 + yo = -y_tmp + self.y0 + return xo, yo - # canvas properties - self.width = width - self.height = height - # zero of canvas - self.x0 = width/2 - self.y0 = height/2 - - self.wd = 150 - - self.robots = {} - - self.robot = None - self.postext = None - - self.scale = 1.0 - self.scale_var = DoubleVar() - self.scale_var.set(self.scale) - - self.grid_pitch = 50 - - self.tick = 0.1 - self.default_tick = 0.1 - self.tickscale_var = DoubleVar() - self.tickscale_var.set(self.tick) - - self.axis_check = StringVar() - self.axis_check.set("on") - self.grid_check = StringVar() - self.grid_check.set("on") - self.rnames = {} - - - self.init() - self.pack() - - - self.after(20, self.on_update) - return - - def init(self): - self.canvas = Canvas(self, bg="#000000", - width = self.width, height = self.height) - self.canvas.pack(side=LEFT) - - self.can_grid = CanvasGrid(self.canvas, self.x0, self.y0, - self.width, self.height, self.grid_pitch, - "#aaaaaa", 1) - self.can_axis = CanvasAxis(self.canvas, self.width, self.height, - "#ffffff", 1) - - self.frame = Frame(self) - self.frame.pack(side=LEFT) - - # Screen control - self.scrctrl_frame = Frame(self.frame, width=self.wd, height=300, - relief=GROOVE, bd=2) - self.scrctrl_frame.pack(side=TOP, fill=X) - self.create_scale(self.scrctrl_frame) - self.create_checkbutton(self.scrctrl_frame) - - - self.lrfctrl_frame = Frame(self.frame, width=self.wd, height=300, - relief=GROOVE, bd=2) - self.lrfctrl_frame.pack(side=TOP, fill=X) - self.lrf = LRFrange(self) - self.lrf.create_ctrl(self.lrfctrl_frame) - - return - - - - def on_update(self): - self.lrf.update() - self.after(20, self.on_update) - return - - def get_tick(self): - return self.tick - - def get_canvas(self): - return self.canvas - - def get_translation(self): - return self.real_to_canvas - - - #------------------------------------------------------------ - # Scale control set - def create_scale(self, frame): - dummy = Frame(frame, width=self.wd) - dummy.pack(side=TOP) - sl = Scale(frame, from_=0, to=10, resolution=0.01, - label="Scale Factor", command=self.on_scale, - variable=self.scale_var, orient=HORIZONTAL) - bt = Button(frame, text="Reset Scale", command=self.reset_scale) - sl.pack(side=TOP, fill=X) - bt.pack(side=TOP, fill=X) - return - - def on_scale(self, val): - v = float(val) - if v == 0.0: - pitch = 0 - else: - pitch = self.grid_pitch/v - self.scale = v - self.can_grid.set_pitch(pitch) - return - - def reset_scale(self): - self.scale_var.set(1.) - pitch = self.grid_pitch/1.0 - self.scale = 1.0 - self.can_grid.set_pitch(pitch) - return - - def on_tickchange(self, val): - v = self.tickscale_var.get() - if v == 0.0: - self.tick = 0 - else: - self.tick = v - return - - def reset_tickscale(self): - self.tick = self.default_tick - self.tickscale_var.set(self.default_tick) - - # end of Scale widget set - #------------------------------------------------------------ - - #------------------------------------------------------------ - # Canvas control set - def create_checkbutton(self, frame): - axis = Checkbutton(frame, text="Axis", - onvalue="on", offvalue="off", - justify=LEFT, anchor=W, - variable=self.axis_check, - command=self.can_axis.toggle) - grid = Checkbutton(frame, text="Grid", - onvalue="on", offvalue="off", - justify=LEFT, anchor=W, - variable=self.grid_check, - command=self.can_grid.toggle) - for w in [axis, grid]: - w.pack(side=TOP, anchor=W, fill=X) - - def on_rname_toggle(self): - for r in self.rnames.keys(): - self.rnames[r].toggle() - return - - # end of Canvas control set - #------------------------------------------------------------ - - #------------------------------------------------------------ - # - def real_to_canvas(self, x, y, dx, dy, dt): - # Simulator coordinate system -> display coordinate system - # x, y: original position - # dx, dy, dt: translation and rotation vector - # translation and rotation - x_tmp = (math.cos(dt) * x - math.sin(dt) * y + dx)/self.scale - y_tmp = (math.sin(dt) * x + math.cos(dt) * y + dy)/self.scale - # align to canvas coordinate system (origin is center and y+ is upward) - xo = x_tmp + self.x0 - yo = -y_tmp + self.y0 - return xo, yo - -import threading class test_data_creator(threading.Thread): - def __init__(self, lrf, step = 681): - threading.Thread.__init__(self) - import time - self.lrf = lrf - self.step = step - self.flag = True - return - - def stop(self): - self.flag = False - return - - def run(self): - import random - data = [0] * 681 - pre = 0 - while self.flag: - for i in range(681): - if i % 5 == 0: - data[i] = pre * 0.9 + random.randint(0, 255) * 0.1 - pre = data[i] - else: - data[i] = pre - pre = data[i] - self.lrf.set_value(data) - time.sleep(0.1) - - return + def __init__(self, lrf, step=681): + threading.Thread.__init__(self) + import time + self.lrf = lrf + self.step = step + self.flag = True + return + + def stop(self): + self.flag = False + return + + def run(self): + import random + data = [0] * 681 + pre = 0 + while self.flag: + for i in range(681): + if i % 5 == 0: + data[i] = pre * 0.9 + random.randint(0, 255) * 0.1 + pre = data[i] + else: + data[i] = pre + pre = data[i] + self.lrf.set_value(data) + time.sleep(0.1) + + return + def main(): - m = TkLRFViewer(Tk()) - m.master.title("Laser Range Finder Viewer") - - mgr = OpenRTM_aist.Manager.init(sys.argv) - mgr.activateManager() - profile = OpenRTM_aist.Properties(defaults_str=lrfviewer_spec) - mgr.registerFactory(profile, LRFViewer, OpenRTM_aist.Delete) - mgr.runManager(True) - lrf_rtc = mgr.createComponent("LRFViewer") - m.lrf.set_data_source(lrf_rtc) - m.mainloop() - mgr.shutdown() - - -if __name__ == '__main__': main() + m = TkLRFViewer(Tk()) + m.main.title("Laser Range Finder Viewer") + + mgr = OpenRTM_aist.Manager.init(sys.argv) + mgr.activateManager() + profile = OpenRTM_aist.Properties(defaults_str=lrfviewer_spec) + mgr.registerFactory(profile, LRFViewer, OpenRTM_aist.Delete) + mgr.runManager(True) + lrf_rtc = mgr.createComponent("LRFViewer") + m.lrf.set_data_source(lrf_rtc) + m.mainloop() + mgr.shutdown() + + +if __name__ == '__main__': + main() diff --git a/OpenRTM_aist/examples/TkLRFViewer/__init__.py b/OpenRTM_aist/examples/TkLRFViewer/__init__.py index 932b7982..270be2a2 100644 --- a/OpenRTM_aist/examples/TkLRFViewer/__init__.py +++ b/OpenRTM_aist/examples/TkLRFViewer/__init__.py @@ -1 +1 @@ -# Empty file +# Empty file diff --git a/OpenRTM_aist/examples/__init__.py b/OpenRTM_aist/examples/__init__.py index 932b7982..270be2a2 100644 --- a/OpenRTM_aist/examples/__init__.py +++ b/OpenRTM_aist/examples/__init__.py @@ -1 +1 @@ -# Empty file +# Empty file diff --git a/OpenRTM_aist/ext/__init__.py b/OpenRTM_aist/ext/__init__.py index 932b7982..270be2a2 100644 --- a/OpenRTM_aist/ext/__init__.py +++ b/OpenRTM_aist/ext/__init__.py @@ -1 +1 @@ -# Empty file +# Empty file diff --git a/OpenRTM_aist/ext/extended_fsm/ExtendedFsmServiceProvider.py b/OpenRTM_aist/ext/extended_fsm/ExtendedFsmServiceProvider.py index 609a6d4e..e7d8fed9 100644 --- a/OpenRTM_aist/ext/extended_fsm/ExtendedFsmServiceProvider.py +++ b/OpenRTM_aist/ext/extended_fsm/ExtendedFsmServiceProvider.py @@ -1,5 +1,5 @@ -#!/usr/bin/env python -# -*- coding: euc-jp -*- +#!/usr/bin/env python +# -*- coding: utf-8 -*- ## # @file ComponentObserverProvider.py @@ -18,18 +18,22 @@ import sys from omniORB import CORBA, PortableServer -import RTC, RTC__POA -import OpenRTM, OpenRTM__POA +import RTC +import RTC__POA +import OpenRTM +import OpenRTM__POA import SDOPackage import OpenRTM_aist import OpenRTM_aist.NVUtil -class ExtendedFsmServiceProvider(RTC__POA.ExtendedFsmService, OpenRTM_aist.SdoServiceProviderBase): - def __init__(self): - self._rtobj = None - self._profile = None - self._fsmState = "" - structure = """ + +class ExtendedFsmServiceProvider( + RTC__POA.ExtendedFsmService, OpenRTM_aist.SdoServiceProviderBase): + def __init__(self): + self._rtobj = None + self._profile = None + self._fsmState = "" + structure = """ @@ -49,250 +53,248 @@ def __init__(self): """ - event_profile = RTC.FsmEventProfile("toggle","TimedShort") - nv = OpenRTM_aist.NVUtil.newNV("fsm_structure.format","scxml") - self._fsmStructure = RTC.FsmStructure("dummy_name","",[event_profile],[nv]) + event_profile = RTC.FsmEventProfile("toggle", "TimedShort") + nv = OpenRTM_aist.NVUtil.newNV("fsm_structure.format", "scxml") + self._fsmStructure = RTC.FsmStructure( + "dummy_name", "", [event_profile], [nv]) + + ## + # @if jp + # @brief 初期化 + # @else + # @brief Initialization + # @endif + # + def init(self, rtobj, profile): + self._rtobj = rtobj + self._profile = profile + return True + + ## + # @if jp + # @brief 再初期化 + # @else + # @brief Re-initialization + # @endif + # + def reinit(self, profile): + self._profile = profile + return True - ## - # @if jp - # @brief - # @else - # @brief Initialization - # @endif - # - def init(self, rtobj, profile): - self._rtobj = rtobj - self._profile = profile - return True + ## + # @if jp + # @brief ServiceProfile を取得する + # @else + # @brief getting ServiceProfile + # @endif + # + def getProfile(self): + return self._profile - ## - # @if jp - # @brief ƽ - # @else - # @brief Re-initialization - # @endif - # - def reinit(self, profile): - self._profile = profile - return True + ## + # @if jp + # @brief 終了処理 + # @else + # @brief Finalization + # @endif + # + def finalize(self): + pass - ## - # @if jp - # @brief ServiceProfile - # @else - # @brief getting ServiceProfile - # @endif - # - def getProfile(self): - return self._profile + ## + # @if jp + # @brief FSMの現在の状態を取得 + # + # このオペレーションはFSMコンポーネントのFSMの現在の状態を返す。 + # (FSM4RTC spec. p.20) + # + # @return 現在の状態を表す文字列 + # + # @else + # @brief Get Current FSM State + # + # This operation returns the current state of an FSM in the + # target FSM component. (FSM4RTC spec. p.20) + # + # @return A string which represent the current status + # + # @endif + # + def get_current_state(self): + return self._fsmState - ## - # @if jp - # @brief λ - # @else - # @brief Finalization - # @endif - # - def finalize(self): - pass + ## + # @if jp + # @brief FSMの構造を設定する + # + # このオペレーションは対象のコンポーネントに対して、FSMの構造を保 + # 持する FsmStruccture を設定する。対象コンポーネントは + # fsm_structure に与えられた値を基に状態遷移ルール等のFSM構造を再 + # 設定する。このオペレーションが未実装の場合は、UNSUPPORTED を返す。 + # + # @param fsm_structure FSMの構造を表すFsmStructure構造体。 + # @return RTC_OK 正常終了 + # RTC_ERROR その他のエラー + # BAD_PARAMETER 不正なパラメータ + # UNSUPPORTED 未サポート + # + # @else + # @brief Set FSM Structure + # + # This operation sets an FsmStructure to the target + # component. Then the target component reconfigures its FSM + # structure such as transition rules according to the values of + # the given fsm_structure. RTCs may return UNSUPPORTED if this + # operation is not implemented. + # + # @param fsm_structure FsmStructure structure which represents + # FSM structure + # @return RTC_OK normal return + # RTC_ERROR other error + # BAD_PARAMETER invalid parameter + # UNSUPPORTED unsupported or not implemented + # + # @endif + # + def set_fsm_structure(self, fsm_structure): + self._fsmStructure = fsm_structure + return RTC.RTC_OK - ## - # @if jp - # @brief FSMθߤξ֤ - # - # Υڥ졼FSMݡͥȤFSMθߤξ֤֤ - # (FSM4RTC spec. p.20) - # - # @return ߤξ֤ɽʸ - # - # @else - # @brief Get Current FSM State - # - # This operation returns the current state of an FSM in the - # target FSM component. (FSM4RTC spec. p.20) - # - # @return A string which represent the current status - # - # @endif - # - def get_current_state(self): - return self._fsmState + ## + # @if jp + # @brief FSMの構造を取得する + # + # このオペレーションは対象のコンポーネントに対して、現在保持してい + # るFSMの構造を取得する。ExtendedFsmService 構造体はフィールド + # name (FSMの名称), structure (FSMの構造) 、EventProfile などを返 + # す。structure のフォーマットは、フィールド properties 内に格納さ + # れたキー "fsm_structure.format" に指定される。このオペレーション + # が未実装の場合は、UNSUPPORTED を返す。 + # + # ref: SCXML https://www.w3.org/TR/scxml/ + # + # @param fsm_structure FSMの構造を表すFsmStructure構造体。 + # @return RTC_OK 正常終了 + # RTC_ERROR その他のエラー + # BAD_PARAMETER 不正なパラメータ + # UNSUPPORTED 未サポート + # + # @else + # @brief Set FSM Structure + # + # This operation returns the structure of an FSM in the target + # FSM component. ExtendedFsmService returns the name, structure + # with format specified by fsm_structure.format and + # EventProfiles. RTCs may return UNSUPPORTED if this operation is + # not implemented. + # + # @param fsm_structure FsmStructure structure which represents + # FSM structure + # @return RTC_OK normal return + # RTC_ERROR other error + # BAD_PARAMETER invalid parameter + # UNSUPPORTED unsupported or not implemented + # + # @endif + # - ## - # @if jp - # @brief FSMι¤ꤹ - # - # Υڥ졼оݤΥݡͥȤФơFSMι¤ - # FsmStruccture ꤹ롣оݥݡͥȤ - # fsm_structure Ϳ줿ͤ˾ܥ롼FSM¤ - # ꤹ롣Υڥ졼̤ξϡUNSUPPORTED ֤ - # - # @param fsm_structure FSMι¤ɽFsmStructure¤Ρ - # @return RTC_OK ェλ - # RTC_ERROR ¾Υ顼 - # BAD_PARAMETER ʥѥ᡼ - # UNSUPPORTED ̤ݡ - # - # @else - # @brief Set FSM Structure - # - # This operation sets an FsmStructure to the target - # component. Then the target component reconfigures its FSM - # structure such as transition rules according to the values of - # the given fsm_structure. RTCs may return UNSUPPORTED if this - # operation is not implemented. - # - # @param fsm_structure FsmStructure structure which represents - # FSM structure - # @return RTC_OK normal return - # RTC_ERROR other error - # BAD_PARAMETER invalid parameter - # UNSUPPORTED unsupported or not implemented - # - # @endif - # - def set_fsm_structure(self, fsm_structure): - self._fsmStructure = fsm_structure - return RTC.RTC_OK - + def get_fsm_structure(self): + return (RTC.RTC_OK, self._fsmStructure) - ## - # @if jp - # @brief FSMι¤ - # - # Υڥ졼оݤΥݡͥȤФơݻƤ - # FSMι¤롣ExtendedFsmService ¤Τϥե - # name (FSM̾), structure (FSMι¤) EventProfile ʤɤ - # structure ΥեޥåȤϡե properties ˳Ǽ - # 줿 "fsm_structure.format" ˻ꤵ롣Υڥ졼 - # ̤ξϡUNSUPPORTED ֤ - # - # ref: SCXML https://www.w3.org/TR/scxml/ - # - # @param fsm_structure FSMι¤ɽFsmStructure¤Ρ - # @return RTC_OK ェλ - # RTC_ERROR ¾Υ顼 - # BAD_PARAMETER ʥѥ᡼ - # UNSUPPORTED ̤ݡ - # - # @else - # @brief Set FSM Structure - # - # This operation returns the structure of an FSM in the target - # FSM component. ExtendedFsmService returns the name, structure - # with format specified by fsm_structure.format and - # EventProfiles. RTCs may return UNSUPPORTED if this operation is - # not implemented. - # - # @param fsm_structure FsmStructure structure which represents - # FSM structure - # @return RTC_OK normal return - # RTC_ERROR other error - # BAD_PARAMETER invalid parameter - # UNSUPPORTED unsupported or not implemented - # - # @endif - # - def get_fsm_structure(self): - return (RTC.RTC_OK,self._fsmStructure) + ## + # @if jp + # @brief RTObjectへのリスナ接続処理 + # @else + # @brief Connectiong listeners to RTObject + # @endif + # + def setListeners(self, prop): + pass - ## - # @if jp - # @brief RTObjectؤΥꥹ³ - # @else - # @brief Connectiong listeners to RTObject - # @endif - # - def setListeners(self, prop): - pass + ## + # @if jp + # @brief FSM状態遷移 + # @else + # @brief FSM status change + # @endif + # + def changeStatus(self, state): + self._fsmState = state - ## - # @if jp - # @brief FSM - # @else - # @brief FSM status change - # @endif - # - def changeStatus(self, state): - self._fsmState = state + ## + # @if jp + # @brief ハートビートを解除する + # @else + # @brief Unsetting heartbeat + # @endif + # + def changeStructure(self, fsm_structure): + self._fsmStructure.structure = fsm_structure - ## - # @if jp - # @brief ϡȥӡȤ - # @else - # @brief Unsetting heartbeat - # @endif - # - def changeStructure(self, fsm_structure): - self._fsmStructure.structure = fsm_structure + ## + # @if jp + # @brief FSM状態変化リスナの設定処理 + # @else + # @brief Setting FSM status listeners + # @endif + # + def setFSMStatusListeners(self): + pass - ## - # @if jp - # @brief FSMѲꥹʤ - # @else - # @brief Setting FSM status listeners - # @endif - # - def setFSMStatusListeners(self): - pass + ## + # @if jp + # @brief FSM状態変化リスナの解除処理 + # @else + # @brief Unsetting FSM status listeners + # @endif + # + def unsetFSMStatusListeners(self): + pass - ## - # @if jp - # @brief FSMѲꥹʤβ - # @else - # @brief Unsetting FSM status listeners - # @endif - # - def unsetFSMStatusListeners(self): - pass + ## + # @if jp + # @brief FsmProfile状態変化リスナの設定 + # @else + # @brief Setting FsmProfile listener + # @endif + # + def setFSMProfileListeners(self): + pass - ## - # @if jp - # @brief FsmProfileѲꥹʤ - # @else - # @brief Setting FsmProfile listener - # @endif - # - def setFSMProfileListeners(self): - pass + ## + # @if jp + # @brief FsmProfile状態変化リスナの解除 + # @else + # @brief Unsetting FsmProfile listener + # @endif + # + def unsetFSMProfileListeners(self): + pass - ## - # @if jp - # @brief FsmProfileѲꥹʤβ - # @else - # @brief Unsetting FsmProfile listener - # @endif - # - def unsetFSMProfileListeners(self): - pass + ## + # @if jp + # @brief FsmStructure状態変化リスナの設定 + # @else + # @brief Setting FsmStructure listener + # @endif + # + def setFSMStructureListeners(self): + pass - ## - # @if jp - # @brief FsmStructureѲꥹʤ - # @else - # @brief Setting FsmStructure listener - # @endif - # - def setFSMStructureListeners(self): - pass + ## + # @if jp + # @brief FsmStructure状態変化リスナの解除 + # @else + # @brief Unsetting FsmStructure listener + # @endif + # + def unsetFSMStructureListeners(self): + pass - ## - # @if jp - # @brief FsmStructureѲꥹʤβ - # @else - # @brief Unsetting FsmStructure listener - # @endif - # - def unsetFSMStructureListeners(self): - pass - - - def ExtendedFsmServiceProviderInit(mgr=None): - factory = OpenRTM_aist.SdoServiceProviderFactory.instance() - factory.addFactory(RTC.ExtendedFsmService._NP_RepositoryId, - ExtendedFsmServiceProvider, - OpenRTM_aist.Delete) - return + factory = OpenRTM_aist.SdoServiceProviderFactory.instance() + factory.addFactory(RTC.ExtendedFsmService._NP_RepositoryId, + ExtendedFsmServiceProvider) + return diff --git a/OpenRTM_aist/ext/extended_fsm/__init__.py b/OpenRTM_aist/ext/extended_fsm/__init__.py new file mode 100644 index 00000000..270be2a2 --- /dev/null +++ b/OpenRTM_aist/ext/extended_fsm/__init__.py @@ -0,0 +1 @@ +# Empty file diff --git a/OpenRTM_aist/ext/fsm4rtc_observer/COCTestRTC.py b/OpenRTM_aist/ext/fsm4rtc_observer/COCTestRTC.py index 26aee382..4107d319 100644 --- a/OpenRTM_aist/ext/fsm4rtc_observer/COCTestRTC.py +++ b/OpenRTM_aist/ext/fsm4rtc_observer/COCTestRTC.py @@ -1,4 +1,4 @@ -#!/usr/bin/env python +#!/usr/bin/env python # -*- coding: utf-8 -*- # -*- Python -*- @@ -8,127 +8,130 @@ import OpenRTM_aist coctestrtc_spec = ["implementation_id", "COCTestRTC", - "type_name", "COCTestRTC", - "description", "Console input component", - "version", "1.0", - "vendor", "Shinji Kurihara", - "category", "example", - "activity_type", "DataFlowComponent", - "max_instance", "10", - "language", "Python", - "lang_type", "script", - ""] + "type_name", "COCTestRTC", + "description", "Console input component", + "version", "1.0", + "vendor", "Shinji Kurihara", + "category", "example", + "activity_type", "DataFlowComponent", + "max_instance", "10", + "language", "Python", + "lang_type", "script", + ""] class DataListener(OpenRTM_aist.ConnectorDataListenerT): - def __init__(self, name): - self._name = name - - def __del__(self): - print("dtor of ", self._name) - - def __call__(self, info, cdrdata): - data = OpenRTM_aist.ConnectorDataListenerT.__call__(self, info, cdrdata, RTC.TimedLong(RTC.Time(0,0),0)) - print("------------------------------") - print("Listener: ", self._name) - print("Profile::name: ", info.name) - print("Profile::id: ", info.id) - print("Data: ", data.data) - print("------------------------------") - + def __init__(self, name): + self._name = name + + def __del__(self): + print("dtor of ", self._name) + + def __call__(self, info, data): + print("------------------------------") + print("Listener: ", self._name) + print("Profile::name: ", info.name) + print("Profile::id: ", info.id) + print("Data: ", data.data) + print("------------------------------") + return OpenRTM_aist.ConnectorListenerStatus.NO_CHANGE, data + + class ConnListener(OpenRTM_aist.ConnectorListener): - def __init__(self, name): - self._name = name + def __init__(self, name): + self._name = name - def __del__(self): - print("dtor of ", self._name) + def __del__(self): + print("dtor of ", self._name) - def __call__(self, info): - print("------------------------------") - print("Listener: ", self._name) - print("Profile::name: ", info.name) - print("Profile::id: ", info.id) - print("------------------------------") + def __call__(self, info): + print("------------------------------") + print("Listener: ", self._name) + print("Profile::name: ", info.name) + print("Profile::id: ", info.id) + print("------------------------------") + return OpenRTM_aist.ConnectorListenerStatus.NO_CHANGE class COCTestRTC(OpenRTM_aist.DataFlowComponentBase): - def __init__(self, manager): - OpenRTM_aist.DataFlowComponentBase.__init__(self, manager) - return - - def onInitialize(self): - self._data = RTC.TimedLong(RTC.Time(0,0),0) - self._outport = OpenRTM_aist.OutPort("out", self._data) - # Set OutPort buffer - self.addOutPort("out", self._outport) - self._outport.addConnectorDataListener(OpenRTM_aist.ConnectorDataListenerType.ON_BUFFER_WRITE, - DataListener("ON_BUFFER_WRITE")) - self._outport.addConnectorDataListener(OpenRTM_aist.ConnectorDataListenerType.ON_BUFFER_FULL, - DataListener("ON_BUFFER_FULL")) - self._outport.addConnectorDataListener(OpenRTM_aist.ConnectorDataListenerType.ON_BUFFER_WRITE_TIMEOUT, - DataListener("ON_BUFFER_WRITE_TIMEOUT")) - self._outport.addConnectorDataListener(OpenRTM_aist.ConnectorDataListenerType.ON_BUFFER_OVERWRITE, - DataListener("ON_BUFFER_OVERWRITE")) - self._outport.addConnectorDataListener(OpenRTM_aist.ConnectorDataListenerType.ON_BUFFER_READ, - DataListener("ON_BUFFER_READ")) - self._outport.addConnectorDataListener(OpenRTM_aist.ConnectorDataListenerType.ON_SEND, - DataListener("ON_SEND")) - self._outport.addConnectorDataListener(OpenRTM_aist.ConnectorDataListenerType.ON_RECEIVED, - DataListener("ON_RECEIVED")) - self._outport.addConnectorDataListener(OpenRTM_aist.ConnectorDataListenerType.ON_RECEIVER_FULL, - DataListener("ON_RECEIVER_FULL")) - self._outport.addConnectorDataListener(OpenRTM_aist.ConnectorDataListenerType.ON_RECEIVER_TIMEOUT, - DataListener("ON_RECEIVER_TIMEOUT")) - self._outport.addConnectorDataListener(OpenRTM_aist.ConnectorDataListenerType.ON_RECEIVER_ERROR, - DataListener("ON_RECEIVER_ERROR")) - - self._outport.addConnectorListener(OpenRTM_aist.ConnectorListenerType.ON_CONNECT, - ConnListener("ON_CONNECT")) - self._outport.addConnectorListener(OpenRTM_aist.ConnectorListenerType.ON_DISCONNECT, - ConnListener("ON_DISCONNECT")) - - return RTC.RTC_OK - - - def onExecute(self, ec_id): - print("Please input number: ") - self._data.data = long(sys.stdin.readline()) - OpenRTM_aist.setTimestamp(self._data) - print("Sending to subscriber: ", self._data.data) - self._outport.write() - return RTC.RTC_OK + def __init__(self, manager): + OpenRTM_aist.DataFlowComponentBase.__init__(self, manager) + return + + def onInitialize(self): + self._data = RTC.TimedLong(RTC.Time(0, 0), 0) + self._outport = OpenRTM_aist.OutPort("out", self._data) + # Set OutPort buffer + self.addOutPort("out", self._outport) + self._outport.addConnectorDataListener(OpenRTM_aist.ConnectorDataListenerType.ON_BUFFER_WRITE, + DataListener("ON_BUFFER_WRITE")) + self._outport.addConnectorDataListener(OpenRTM_aist.ConnectorDataListenerType.ON_BUFFER_FULL, + DataListener("ON_BUFFER_FULL")) + self._outport.addConnectorDataListener(OpenRTM_aist.ConnectorDataListenerType.ON_BUFFER_WRITE_TIMEOUT, + DataListener("ON_BUFFER_WRITE_TIMEOUT")) + self._outport.addConnectorDataListener(OpenRTM_aist.ConnectorDataListenerType.ON_BUFFER_OVERWRITE, + DataListener("ON_BUFFER_OVERWRITE")) + self._outport.addConnectorDataListener(OpenRTM_aist.ConnectorDataListenerType.ON_BUFFER_READ, + DataListener("ON_BUFFER_READ")) + self._outport.addConnectorDataListener(OpenRTM_aist.ConnectorDataListenerType.ON_SEND, + DataListener("ON_SEND")) + self._outport.addConnectorDataListener(OpenRTM_aist.ConnectorDataListenerType.ON_RECEIVED, + DataListener("ON_RECEIVED")) + self._outport.addConnectorDataListener(OpenRTM_aist.ConnectorDataListenerType.ON_RECEIVER_FULL, + DataListener("ON_RECEIVER_FULL")) + self._outport.addConnectorDataListener(OpenRTM_aist.ConnectorDataListenerType.ON_RECEIVER_TIMEOUT, + DataListener("ON_RECEIVER_TIMEOUT")) + self._outport.addConnectorDataListener(OpenRTM_aist.ConnectorDataListenerType.ON_RECEIVER_ERROR, + DataListener("ON_RECEIVER_ERROR")) + + self._outport.addConnectorListener(OpenRTM_aist.ConnectorListenerType.ON_CONNECT, + ConnListener("ON_CONNECT")) + self._outport.addConnectorListener(OpenRTM_aist.ConnectorListenerType.ON_DISCONNECT, + ConnListener("ON_DISCONNECT")) + + return RTC.RTC_OK + + def onExecute(self, ec_id): + print("Please input number: ") + self._data.data = long(sys.stdin.readline()) + OpenRTM_aist.setTimestamp(self._data) + print("Sending to subscriber: ", self._data.data) + self._outport.write() + return RTC.RTC_OK def COCTestRTCInit(manager): - profile = OpenRTM_aist.Properties(defaults_str=coctestrtc_spec) - manager.registerFactory(profile, - COCTestRTC, - OpenRTM_aist.Delete) + profile = OpenRTM_aist.Properties(defaults_str=coctestrtc_spec) + manager.registerFactory(profile, + COCTestRTC, + OpenRTM_aist.Delete) def MyModuleInit(manager): - COCTestRTCInit(manager) + COCTestRTCInit(manager) + + # Create a component + comp = manager.createComponent("COCTestRTC") - # Create a component - comp = manager.createComponent("COCTestRTC") def main(): - # Initialize manager - mgr = OpenRTM_aist.Manager.init(sys.argv) + # Initialize manager + mgr = OpenRTM_aist.Manager.init(sys.argv) + + # Set module initialization proceduer + # This procedure will be invoked in activateManager() function. + mgr.setModuleInitProc(MyModuleInit) - # Set module initialization proceduer - # This procedure will be invoked in activateManager() function. - mgr.setModuleInitProc(MyModuleInit) + # Activate manager and register to naming service + mgr.activateManager() - # Activate manager and register to naming service - mgr.activateManager() + # run the manager in blocking mode + # runManager(False) is the default + mgr.runManager() - # run the manager in blocking mode - # runManager(False) is the default - mgr.runManager() + # If you want to run the manager in non-blocking mode, do like this + # mgr.runManager(True) - # If you want to run the manager in non-blocking mode, do like this - # mgr.runManager(True) if __name__ == "__main__": - main() + main() diff --git a/OpenRTM_aist/ext/fsm4rtc_observer/ComponentObserverConsumer.py b/OpenRTM_aist/ext/fsm4rtc_observer/ComponentObserverConsumer.py index 27b05ce0..150ffb3c 100644 --- a/OpenRTM_aist/ext/fsm4rtc_observer/ComponentObserverConsumer.py +++ b/OpenRTM_aist/ext/fsm4rtc_observer/ComponentObserverConsumer.py @@ -1,5 +1,5 @@ -#!/usr/bin/env python -# -*- coding: euc-jp -*- +#!/usr/bin/env python +# -*- coding: utf-8 -*- ## # @file ComponentObserverConsumer.py @@ -15,1305 +15,1305 @@ # All rights reserved. # +import OpenRTM_aist +import OpenRTM +import RTC import sys -sys.path.insert(1,".") +sys.path.insert(1, ".") -import RTC -import OpenRTM -import OpenRTM_aist ## # @if jp # @else # @endif # -class ComponentObserverConsumer(OpenRTM_aist.SdoServiceConsumerBase): - """ - """ - - ## - # @if jp - # @class ComponentObserverConsumer 饹 - # @brief ComponentObserver ⥸塼 - # - # ݡͥȤγƼ֤ComponentObserverӥФƥ - # Хå뤿Υ饹ġݡͥȤξѲΤꤿ - # ƥƥӥץХݡͥȤФƥ - # Ȥȡбܥ󥷥塼ޤå졢ݡͥȤξ - # Ѳ˱ơupdate_status() ڥ졼STATUS_KIND ȥҥ - # Ȥ˸ƤӽФܵǽϡOMG FSM4RTC - # (formal/16-04-01) 7.2.4.2 ComponentObserver Interface ˵Ҥ - # 롣 - # - # STATUS_KIND ˤϰʲμब롣 - # - # - COMPONENT_PROFILE: ݡͥȤΥץեѲ - # - RTC_STATUS : ݡͥȤξ (Init, Alive) Ѳ - # - EC_STATUS : ECξ (Inavtive, Active, Error) Ѳ - # - PORT_PROFILE : ݡȤΥץե뤬Ѳ - # - CONFIGURATION : ե졼Ѳ - # - RTC_HEARTBEAT : RTC¸ǧΥϡȥӡ - # - EC_HEARTBEAT : EC¸ǧΥϡȥӡ - # - FSM_PROFILE : FSMΥץե뤬Ѳ - # - FSM_STATUS : FSMξ֤Ѳ - # - FSM_STRUCTURE : FSMι¤Ѳ - # - USER_DEFINED : 桼 - # - # \subsection COMPONENT_PROFILE COMPONENT_PROFILE - # ݡͥȤΥץեѲݤˤΥ̾(enum) - # 1ˤ update_status() ڥ졼󤬸ƤӽФ롣(̤) - # - # \subsection RTC_STATUS RTC_STATUS - # - # ݡͥȤξ (Init, Alive) ѲݤˤΥ̾ - # (enum)1ˤ update_status() ڥ졼󤬸ƤӽФ - # 롣̩ˤECξ֤Ǥ뤬Inavtive, Active, Error, Finalize - # 4Ĥξ֤ѲȤΤ뤳ȤǤ롣ʲξѲˡ - # 줾ҥȤȤưʲʸȤȤ˥Хå롣 - # - # - onActivated ƤӽФ: ACTIVE: - # - onDeactivated ƤӽФ: INACTIVE: - # - onReset ƤӽФ: INACTIVE: - # - onAborting ƤӽФ: ERROR: - # - onFinalize ƤӽФ: FINALIZE: - # - # \subsection EC_STATUS EC_STATUS - # - # ECξ (Inavtive, Active, Error) ѲݤˤΥ̾(enum) - # 1ˤ update_status() ڥ졼󤬸ƤӽФ롣 - # - # \subsection PORT_PROFILE PORT_PROFILE - # ݡȤΥץե뤬ѲݤˤΥ̾(enum) - # 1ˤ update_status() ڥ졼󤬸ƤӽФ롣 - # - # \subsection CONFIGURATION CONFIGURATION - # ե졼ѲݤˤΥ̾(enum) - # 1ˤ update_status() ڥ졼󤬸ƤӽФ롣 - # - # \subsection RTC_HEARTBEAT RTC_HEARTBEAT - # RTC¸ǧΥϡȥӡɤݤˤΥ̾(enum) - # 1ˤ update_status() ڥ졼󤬸ƤӽФ롣 - # - # \subsection EC_HEARTBEAT EC_HEARTBEAT - # EC¸ǧΥϡȥӡȤݤˤΥ̾(enum) - # 1ˤ update_status() ڥ졼󤬸ƤӽФ롣 - # - # \subsection FSM_PROFILE FSM_PROFILE - # FSMΥץե뤬ѲݤˤΥ̾(enum) - # 1ˤ update_status() ڥ졼󤬸ƤӽФ롣 - # - # \subsection FSM_STATUS FSM_STATUS - # FSMξ֤ѲݤˤΥ̾(enum) - # 1ˤ update_status() ڥ졼󤬸ƤӽФ롣 - # - # \subsection FSM_STRUCTURE FSM_STRUCTURE - # FSMι¤ѲݤˤΥ̾(enum) - # 1ˤ update_status() ڥ졼󤬸ƤӽФ롣 - # - # \subsection USER_DEFINED USER_DEFINED - # 桼ݤˤΥ̾(enum) - # 1ˤ update_status() ڥ졼󤬸ƤӽФ롣 - # @else - # @brief ctor of ComponentObserverConsumer - # @endif - # - def __init__(self): - self._rtobj = None - self._profile = None - self._observer = OpenRTM_aist.CorbaConsumer(interfaceType=RTC.ComponentObserver) - self._observed = [ False for i in range(RTC.STATUS_KIND_NUM._v)] - - self._compstat = self.CompStatMsg(self) - self._portaction = self.PortAction(self) - self._ecaction = self.ECAction(self) - self._configMsg = self.ConfigAction(self) - self._fsmaction = self.FSMAction(self) - - self._rtcInterval = OpenRTM_aist.TimeValue(1, 0) - self._rtcHeartbeat = False - self._rtcHblistenerid = None - self._ecInterval = OpenRTM_aist.TimeValue(1, 0) - self._ecHeartbeat = False - self._ecHblistenerid = None - - # ΥޡϤ쥰Хʥޤˤ - self._timer = OpenRTM_aist.Timer(self._rtcInterval) - return - - - ## - # @if jp - # @brief dtor - # @else - # @brief dtor - # @endif - # - def __del__(self): - self.unsetComponentProfileListeners() - self.unsetComponentStatusListeners() - self.unsetPortProfileListeners() - self.unsetExecutionContextListeners() - self.unsetConfigurationListeners() - self.unsetRTCHeartbeat() - self.unsetECHeartbeat() - del self._timer - return - - - ## - # @if jp - # @brief - # @else - # @brief Initialization - # @endif - # - # virtual bool init(RTObject_impl& rtobj, - # const SDOPackage::ServiceProfile& profile); - def init(self, rtobj, profile): - if not self._observer.setObject(profile.service): - # narrowing failed - return False - - self._rtobj = rtobj - self._profile = profile - prop = OpenRTM_aist.Properties() - OpenRTM_aist.NVUtil.copyToProperties(prop, profile.properties) - self.setRTCHeartbeat(prop) - self.setECHeartbeat(prop) - self.setListeners(prop) - return True - - - ## - # @if jp - # @brief ƽ - # @else - # @brief Re-initialization - # @endif - # - # virtual bool reinit(const SDOPackage::ServiceProfile& profile); - def reinit(self, profile): - if not self._observer._ptr()._is_equivalent(profile.service): - tmp = OpenRTM_aist.CorbaConsumer(interfaceType=RTC.ComponentObserver) - if not tmp.setObject(profile.service): - return False - self._observer.releaseObject() - self._observer.setObject(profile.service) - - self._profile= profile - prop = OpenRTM_aist.Properties() - OpenRTM_aist.NVUtil.copyToProperties(prop, profile.properties) - self.setRTCHeartbeat(prop) - self.setECHeartbeat(prop) - self.setListeners(prop) - return True - - - ## - # @if jp - # @brief ServiceProfile - # @else - # @brief getting ServiceProfile - # @endif - # - # virtual const SDOPackage::ServiceProfile& getProfile() const; - def getProfile(self): - return self._profile - - - ## - # @if jp - # @brief λ - # @else - # @brief Finalization - # @endif - # - # virtual void finalize(); - def finalize(self): - self.unsetComponentProfileListeners() - self.unsetComponentStatusListeners() - self.unsetPortProfileListeners() - self.unsetExecutionContextListeners() - self.unsetConfigurationListeners() - self.unsetRTCHeartbeat() - self.unsetECHeartbeat() - return - - - ## - # @if jp - # @brief ⡼ȥ֥ȥ - # @else - # @brief Calling remote object - # @endif - # - # inline void updateStatus(OpenRTM::StatusKind statuskind, const char* msg) - def updateStatus(self, statuskind, msg): - try: - self._observer._ptr().update_status(statuskind, msg) - except: - self._rtobj.removeSdoServiceConsumer(self._profile.id) - return - - ## - # @if jp - # @brief KindʸѴ - # @else - # @brief Converting kind to string - # @endif - # - # inline const char* toString(OpenRTM::StatusKind kind) - def toString(self, kind): - kinds = ["COMPONENT_PROFILE", - "RTC_STATUS", - "EC_STATUS", - "PORT_PROFILE", - "CONFIGURATION", - "RTC_HEARTBEAT" - "EC_HEARTBEAT", - "FSM_PROFILE", - "FSM_STATUS", - "FSM_STRUCTURE", - "USER_DEFINED"] - if kind._v < RTC.STATUS_KIND_NUM._v: - return kinds[kind._v] - return "" - - - ## - # @if jp - # @brief RTObjectؤΥꥹ³ - # @else - # @brief Connectiong listeners to RTObject - # @endif - # - # void setListeners(coil::Properties& prop); - def setListeners(self, prop): - if not prop.getProperty("observed_status"): - prop.setProperty("observed_status", "ALL") - - observed_ = [s.strip() for s in prop.getProperty("observed_status").split(",")] - flags_ = [ False for i in range(RTC.STATUS_KIND_NUM._v) ] - - for i in range(len(observed_)): - observed_[i] = observed_[i].upper() - if observed_[i] == "COMPONENT_PROFILE": - flags_[RTC.COMPONENT_PROFILE._v] = True - elif observed_[i] == "RTC_STATUS": - flags_[RTC.RTC_STATUS._v] = True - elif observed_[i] == "EC_STATUS": - flags_[RTC.EC_STATUS._v] = True - elif observed_[i] == "PORT_PROFILE": - flags_[RTC.PORT_PROFILE._v] = True - elif observed_[i] == "CONFIGURATION": - flags_[RTC.CONFIGURATION._v] = True - elif observed_[i] == "FSM_PROFILE": - flags_[RTC.FSM_PROFILE._v] = True - elif observed_[i] == "FSM_STATUS": - flags_[RTC.FSM_STRUCTURE._v] = True - elif observed_[i] == "FSM_STRUCTURE": - flags_[RTC.CONFIGURATION._v] = True - elif observed_[i] == "ALL": - for j in range(RTC.STATUS_KIND_NUM._v): - flags_[j] = True - break - - self.switchListeners(flags_[RTC.COMPONENT_PROFILE._v], - self._observed, - RTC.COMPONENT_PROFILE._v, - self.setComponentProfileListeners, - self.unsetComponentProfileListeners) - - self.switchListeners(flags_[RTC.RTC_STATUS._v], - self._observed, - RTC.RTC_STATUS._v, - self.setComponentStatusListeners, - self.unsetComponentStatusListeners) - - self.switchListeners(flags_[RTC.EC_STATUS._v], - self._observed, - RTC.EC_STATUS._v, - self.setExecutionContextListeners, - self.unsetExecutionContextListeners) - - self.switchListeners(flags_[RTC.PORT_PROFILE._v], - self._observed, - RTC.PORT_PROFILE._v, - self.setPortProfileListeners, - self.unsetPortProfileListeners) - - self.switchListeners(flags_[RTC.CONFIGURATION._v], - self._observed, - RTC.CONFIGURATION._v, - self.setConfigurationListeners, - self.unsetConfigurationListeners) - - self.switchListeners(flags_[RTC.FSM_PROFILE._v], - self._observed, - RTC.FSM_PROFILE._v, - self.setFSMProfileListeners, - self.unsetFSMProfileListeners) - self.switchListeners(flags_[RTC.FSM_STATUS._v], - self._observed, - RTC.FSM_STATUS._v, - self.setFSMStatusListeners, - self.unsetFSMStatusListeners) - self.switchListeners(flags_[RTC.FSM_STRUCTURE._v], - self._observed, - RTC.FSM_STRUCTURE._v, - self.setFSMStructureListeners, - self.unsetFSMStructureListeners) - - return - - - ## - # @if jp - # @brief ꥹ³ǥå󥰽 - # @else - # @brief Switching listeners connecting/disconnecting - # @endif - # - # void switchListeners(bool& next, bool& pre, - # void (ComponentObserverConsumer::*setfunc)(), - # void (ComponentObserverConsumer::*unsetfunc)()); - def switchListeners(self, next, pre, pre_idx, setfunc, unsetfunc): - if (not pre[pre_idx]) and next: - setfunc() - pre[pre_idx] = True - elif pre[pre_idx] and (not next): - unsetfunc() - pre[pre_idx] = False - - return - - - #============================================================ - # Heartbeat related functions - - ## - # @if jp - # @brief ϡȥӡȤ򥪥֥Ф - # @else - # @brief Sending a heartbeart signal to observer - # @endif - # - # void rtcHeartbeat(); - def rtcHeartbeat(self): - self.updateStatus(RTC.RTC_HEARTBEAT, "") - return - - - ## - # @if jp - # @brief ϡȥӡȤꤹ - # @else - # @brief Setting heartbeat - # @endif - # - # void setRTCHeartbeat(coil::Properties& prop); - def setRTCHeartbeat(self, prop): - if prop.getProperty("rtc_heartbeat.enable"): - prop.setProperty("heartbeat.enable",prop.getProperty("rtc_heartbeat.enable")) - if prop.getProperty("rtc_heartbeat.interval"): - prop.setProperty("heartbeat.interval",prop.getProperty("rtc_heartbeat.interval")) - - if OpenRTM_aist.toBool(prop.getProperty("heartbeat.enable"), "YES", "NO", False): - interval_ = prop.getProperty("heartbeat.interval") - if not interval_: - self._rtcInterval.set_time(1.0) - else: - tmp_ = float(interval_) - self._rtcInterval.set_time(tmp_) - - tm_ = self._rtcInterval - self._rtcHblistenerid = self._timer.registerListenerObj(self, - ComponentObserverConsumer.rtcHeartbeat, - tm_) - self._timer.start() - self._rtcHeartbeat = True - - else: - if self._rtcHeartbeat and self._rtcHblistenerid: - self.unsetRTCHeartbeat() - self._timer.stop() - - return - - - ## - # @if jp - # @brief ϡȥӡȤ - # @else - # @brief Unsetting heartbeat - # @endif - # - # void unsetRTCHeartbeat(); - def unsetRTCHeartbeat(self): - self._timer.unregisterListener(self._rtcHblistenerid) - self._rtcHblistenerid = 0 - self._timer.stop() - self._rtcHeartbeat = False - return - - - ## - # @if jp - # @brief ϡȥӡȤ򥪥֥Ф - # @else - # @brief Sending a heartbeart signal to observer - # @endif - # - # void ecHeartbeat(); - def ecHeartbeat(self): - self.updateStatus(RTC.EC_HEARTBEAT, "") - return - - - ## - # @if jp - # @brief ϡȥӡȤꤹ - # @else - # @brief Setting heartbeat - # @endif - # - # void setECHeartbeat(coil::Properties& prop); - def setECHeartbeat(self, prop): - - if OpenRTM_aist.toBool(prop.getProperty("ec_heartbeat.enable"), "YES", "NO", False): - interval_ = prop.getProperty("ec_heartbeat.interval") - if not interval_: - self._ecInterval.set_time(1.0) - else: - tmp_ = float(interval_) - self._ecInterval.set_time(tmp_) - - tm_ = self._ecInterval - self._ecHblistenerid = self._timer.registerListenerObj(self, - ComponentObserverConsumer.ecHeartbeat, - tm_) - self._timer.start() - self._ecHeartbeat = True - - else: - if self._ecHeartbeat and self._ecHblistenerid: - self.unsetECHeartbeat() - self._timer.stop() - - return - - - ## - # @if jp - # @brief ϡȥӡȤ - # @else - # @brief Unsetting heartbeat - # @endif - # - # void unsetECHeartbeat(); - def unsetECHeartbeat(self): - self._timer.unregisterListener(self._ecHblistenerid) - self._ecHblistenerid = 0 - self._timer.stop() - self._ecHeartbeat = False - return - - - #============================================================ - # Component status related functions - - ## - # @if jp - # @brief RTCѲꥹʤ - # @else - # @brief Setting RTC status listeners - # @endif - # - # void setComponentStatusListeners(); - def setComponentStatusListeners(self): - postclistener_ = OpenRTM_aist.PostComponentActionListenerType - if not self._compstat.activatedListener: - self._compstat.activatedListener = \ - self._rtobj.addPostComponentActionListener(postclistener_.POST_ON_ACTIVATED, - self._compstat.onActivated) - if not self._compstat.deactivatedListener: - self._compstat.deactivatedListener = \ - self._rtobj.addPostComponentActionListener(postclistener_.POST_ON_DEACTIVATED, - self._compstat.onDeactivated) - - if not self._compstat.resetListener: - self._compstat.resetListener = \ - self._rtobj.addPostComponentActionListener(postclistener_.POST_ON_RESET, - self._compstat.onReset) - - if not self._compstat.abortingListener: - self._compstat.abortingListener = \ - self._rtobj.addPostComponentActionListener(postclistener_.POST_ON_ABORTING, - self._compstat.onAborting) - - if not self._compstat.finalizeListener: - self._compstat.finalizeListener = \ - self._rtobj.addPostComponentActionListener(postclistener_.POST_ON_FINALIZE, - self._compstat.onFinalize) - - return - - - ## - # @if jp - # @brief RTCѲꥹʤβ - # @else - # @brief Unsetting RTC status listeners - # @endif - # - # void unsetComponentStatusListeners(); - def unsetComponentStatusListeners(self): - postclistener_ = OpenRTM_aist.PostComponentActionListenerType - if self._compstat.activatedListener: - self._rtobj.removePostComponentActionListener(postclistener_.POST_ON_ACTIVATED, - self._compstat.activatedListener) - self._compstat.activatedListener = None - - if self._compstat.deactivatedListener: - self._rtobj.removePostComponentActionListener(postclistener_.POST_ON_DEACTIVATED, - self._compstat.deactivatedListener) - self._compstat.deactivatedListener = None - - if self._compstat.resetListener: - self._rtobj.removePostComponentActionListener(postclistener_.POST_ON_RESET, - self._compstat.resetListener) - self._compstat.resetListener = None - - if self._compstat.abortingListener: - self._rtobj.removePostComponentActionListener(postclistener_.POST_ON_ABORTING, - self._compstat.abortingListener) - self._compstat.abortingListener = None - - if self._compstat.finalizeListener: - self._rtobj.removePostComponentActionListener(postclistener_.POST_ON_FINALIZE, - self._compstat.finalizeListener) - self._compstat.finalizeListener = None - - return - - - def setFSMStatusListeners(self): - pass - def unsetFSMStatusListeners(self): - pass - - - #============================================================ - # Port profile related functions - - ## - # @if jp - # @brief PortץեѲꥹʤ - # @else - # @brief Setting port profile listener - # @endif - # - # void setPortProfileListeners(); - def setPortProfileListeners(self): - plistener_ = OpenRTM_aist.PortActionListenerType - if not self._portaction.portAddListener: - self._portaction.portAddListener = \ - self._rtobj.addPortActionListener(plistener_.ADD_PORT, - self._portaction.onAddPort) - - if not self._portaction.portRemoveListener: - self._portaction.portRemoveListener = \ - self._rtobj.addPortActionListener(plistener_.REMOVE_PORT, - self._portaction.onRemovePort) - - pclistener_ = OpenRTM_aist.PortConnectRetListenerType - if not self._portaction.portConnectListener: - self._portaction.portConnectListener = \ - self._rtobj.addPortConnectRetListener(pclistener_.ON_CONNECTED, - self._portaction.onConnect) - - if not self._portaction.portDisconnectListener: - self._portaction.portDisconnectListener = \ - self._rtobj.addPortConnectRetListener(pclistener_.ON_DISCONNECTED, - self._portaction.onDisconnect) - - return - - ## - # @if jp - # @brief PortץեѲꥹʤβ - # @else - # @brief Unsetting port profile listener - # @endif - # - # void unsetPortProfileListeners(); - def unsetPortProfileListeners(self): - plistener_ = OpenRTM_aist.PortActionListenerType - if self._portaction.portAddListener: - self._rtobj.removePortActionListener(plistener_.ADD_PORT, - self._portaction.portAddListener) - self._portaction.portAddListener = None - - if self._portaction.portRemoveListener: - self._rtobj.removePortActionListener(plistener_.REMOVE_PORT, - self._portaction.portRemoveListener) - self._portaction.portRemoveListener = None - - pclistener_ = OpenRTM_aist.PortConnectRetListenerType - if self._portaction.portConnectListener: - self._rtobj.removePortConnectRetListener(pclistener_.ON_CONNECTED, - self._portaction.portConnectListener) - self._portaction.portConnectListener = None - - if self._portaction.portDisconnectListener: - self._rtobj.removePortConnectRetListener(pclistener_.ON_DISCONNECTED, - self._portaction.portDisconnectListener) - self._portaction.portDisconnectListener = None - - return - - - #============================================================ - # EC profile related functions - - ## - # @if jp - # @brief ECξѲꥹʤ - # @else - # @brief Setting EC status listener - # @endif - # - # void setExecutionContextListeners(); - def setExecutionContextListeners(self): - ectype_ = OpenRTM_aist.ExecutionContextActionListenerType - if not self._ecaction.ecAttached: - self._ecaction.ecAttached = \ - self._rtobj.addExecutionContextActionListener(ectype_.EC_ATTACHED, - self._ecaction.onAttached) - - if not self._ecaction.ecDetached: - self._ecaction.ecDetached = \ - self._rtobj.addExecutionContextActionListener(ectype_.EC_DETACHED, - self._ecaction.onDetached) - - pcaltype_ = OpenRTM_aist.PostComponentActionListenerType - if not self._ecaction.ecRatechanged: - self._ecaction.ecRatechanged = \ - self._rtobj.addPostComponentActionListener(pcaltype_.POST_ON_RATE_CHANGED, - self._ecaction.onRateChanged) - - if not self._ecaction.ecStartup: - self._ecaction.ecStartup = \ - self._rtobj.addPostComponentActionListener(pcaltype_.POST_ON_STARTUP, - self._ecaction.onStartup) - - if not self._ecaction.ecShutdown: - self._ecaction.ecShutdown = \ - self._rtobj.addPostComponentActionListener(pcaltype_.POST_ON_SHUTDOWN, - self._ecaction.onShutdown) - - return - - - ## - # @if jp - # @brief ECξѲꥹʤβ - # @else - # @brief Unsetting EC status listener - # @endif - # - # void unsetExecutionContextListeners(); - def unsetExecutionContextListeners(self): - ectype_ = OpenRTM_aist.ExecutionContextActionListenerType - if self._ecaction.ecAttached: - self._rtobj.removeExecutionContextActionListener(ectype_.EC_ATTACHED, - self._ecaction.ecAttached) - - if self._ecaction.ecDetached: - self._rtobj.removeExecutionContextActionListener(ectype_.EC_ATTACHED, - self._ecaction.ecDetached) - - pcaltype_ = OpenRTM_aist.PostComponentActionListenerType - if self._ecaction.ecRatechanged: - self._rtobj.removePostComponentActionListener(pcaltype_.POST_ON_RATE_CHANGED, - self._ecaction.ecRatechanged) - - if self._ecaction.ecStartup: - self._rtobj.removePostComponentActionListener(pcaltype_.POST_ON_STARTUP, - self._ecaction.ecStartup) - - if self._ecaction.ecShutdown: - self._rtobj.removePostComponentActionListener(pcaltype_.POST_ON_SHUTDOWN, - self._ecaction.ecShutdown) - return - - - #============================================================ - # ComponentProfile related functions - - ## - # @if jp - # @brief ComponentProfileѲꥹʤ - # @else - # @brief Setting ComponentProfile listener - # @endif - # - # void setComponentProfileListeners(); - def setComponentProfileListeners(self): - pass - - - ## - # @if jp - # @brief ComponentProfileѲꥹʤβ - # @else - # @brief Unsetting ComponentProfile listener - # @endif - # - # void unsetComponentProfileListeners(); - def unsetComponentProfileListeners(self): - pass - - - #============================================================ - # FsmStructure related functions - - ## - # @if jp - # @brief FsmStructureѲꥹʤ - # @else - # @brief Setting FsmStructure listener - # @endif - # - # void setConfigurationListeners(); - def setFSMStructureListeners(self): - fsmactionlistenertype_ = OpenRTM_aist.PreFsmActionListenerType - self._fsmaction.preOnFsmInitListener = \ - self._rtobj.addPreFsmActionListener(fsmactionlistenertype_.PRE_ON_INIT, - self._fsmaction.preInit) - - self._fsmaction.preOnFsmEntryListener = \ - self._rtobj.addPreFsmActionListener(fsmactionlistenertype_.PRE_ON_ENTRY, - self._fsmaction.preEntry) - - self._fsmaction.preOnFsmDoListener = \ - self._rtobj.addPreFsmActionListener(fsmactionlistenertype_.PRE_ON_DO, - self._fsmaction.preDo) - - self._fsmaction.preOnFsmExitListener = \ - self._rtobj.addPreFsmActionListener(fsmactionlistenertype_.PRE_ON_EXIT, - self._fsmaction.preExit) - - self._fsmaction.preOnFsmStateChangeListener = \ - self._rtobj.addPreFsmActionListener(fsmactionlistenertype_.PRE_ON_STATE_CHANGE, - self._fsmaction.postInit) - - fsmactionlistenertype_ = OpenRTM_aist.PostFsmActionListenerType - - self._fsmaction.postOnFsmInitListener = \ - self._rtobj.addPostFsmActionListener(fsmactionlistenertype_.POST_ON_INIT, - self._fsmaction.preStateChange) - - self._fsmaction.postOnFsmEntryListener = \ - self._rtobj.addPostFsmActionListener(fsmactionlistenertype_.POST_ON_ENTRY, - self._fsmaction.postEntry) - - self._fsmaction.postOnFsmDoListener = \ - self._rtobj.addPostFsmActionListener(fsmactionlistenertype_.POST_ON_DO, - self._fsmaction.postDo) - - self._fsmaction.postOnFsmExitListener = \ - self._rtobj.addPostFsmActionListener(fsmactionlistenertype_.POST_ON_EXIT, - self._fsmaction.postExit) - - self._fsmaction.postOnFsmStateChangeListener = \ - self._rtobj.addPostFsmActionListener(fsmactionlistenertype_.POST_ON_STATE_CHANGE, - self._fsmaction.postStateChange) - - - - def unsetFSMStructureListeners(self): - fsmactionlistenertype_ = OpenRTM_aist.FSMActionListenerType - if self._fsmaction.preOnFsmInitListener: - self._rtobj.removePreFsmActionListener(fsmactionlistenertype_.PRE_ON_INIT, - self._fsmaction.preOnFsmInitListener) - self._fsmaction.preOnFsmInitListener = None - - if self._fsmaction.preOnFsmEntryListener: - self._rtobj.removePreFsmActionListener(fsmactionlistenertype_.PRE_ON_ENTRY, - self._fsmaction.preOnFsmEntryListener) - self._fsmaction.preOnFsmEntryListener = None - - if self._fsmaction.preOnFsmDoListener: - self._rtobj.removePreFsmActionListener(fsmactionlistenertype_.PRE_ON_DO, - self._fsmaction.preOnFsmDoListener) - self._fsmaction.preOnFsmDoListener = None - - if self._fsmaction.preOnFsmExitListener: - self._rtobj.removePreFsmActionListener(fsmactionlistenertype_.PRE_ON_EXIT, - self._fsmaction.preOnFsmExitListener) - self._fsmaction.preOnFsmExitListener = None - - if self._fsmaction.preOnFsmStateChangeListener: - self._rtobj.removePreFsmActionListener(fsmactionlistenertype_.PRE_ON_STATE_CHANGE, - self._fsmaction.preOnFsmStateChangeListener) - self._fsmaction.preOnFsmStateChangeListener = None - - if self._fsmaction.postOnFsmInitListener: - self._rtobj.removePostFsmActionListener(fsmactionlistenertype_.POST_ON_INIT, - self._fsmaction.postOnFsmInitListener) - self._fsmaction.postOnFsmInitListener = None - - if self._fsmaction.postOnFsmEntryListener: - self._rtobj.removePostFsmActionListener(fsmactionlistenertype_.POST_ON_ENTRY, - self._fsmaction.postOnFsmEntryListener) - self._fsmaction.postOnFsmEntryListener = None - - if self._fsmaction.postOnFsmDoListener: - self._rtobj.removePostFsmActionListener(fsmactionlistenertype_.POST_ON_DO, - self._fsmaction.postOnFsmDoListener) - self._fsmaction.postOnFsmDoListener = None - - - if self._fsmaction.postOnFsmExitListener: - self._rtobj.removePostFsmActionListener(fsmactionlistenertype_.POST_ON_EXIT, - self._fsmaction.postOnFsmExitListener) - self._fsmaction.postOnFsmExitListener = None - - if self._fsmaction.postOnFsmStateChangeListener: - self._rtobj.removePostFsmActionListener(fsmactionlistenertype_.POST_ON_EXIT, - self._fsmaction.postOnFsmStateChangeListener) - self._fsmaction.postOnFsmStateChangeListener = None - - #============================================================ - # Configuration related functions - - ## - # @if jp - # @brief ConfigurationѲꥹʤ - # @else - # @brief Setting Configuration listener - # @endif - # - # void setConfigurationListeners(); - def setConfigurationListeners(self): - confprmlistenertype_ = OpenRTM_aist.ConfigurationParamListenerType - self._configMsg.updateConfigParamListener = \ - self._rtobj.addConfigurationParamListener(confprmlistenertype_.ON_UPDATE_CONFIG_PARAM, - self._configMsg.updateConfigParam) - - confsetlistenertype_ = OpenRTM_aist.ConfigurationSetListenerType - self._configMsg.setConfigSetListener = \ - self._rtobj.addConfigurationSetListener(confsetlistenertype_.ON_SET_CONFIG_SET, - self._configMsg.setConfigSet) - - self._configMsg.addConfigSetListener = \ - self._rtobj.addConfigurationSetListener(confsetlistenertype_.ON_ADD_CONFIG_SET, - self._configMsg.addConfigSet) - - confsetnamelistenertype_ = OpenRTM_aist.ConfigurationSetNameListenerType - self._configMsg.updateConfigSetListener = \ - self._rtobj.addConfigurationSetNameListener(confsetnamelistenertype_.ON_UPDATE_CONFIG_SET, - self._configMsg.updateConfigSet) - - self._configMsg.removeConfigSetListener = \ - self._rtobj.addConfigurationSetNameListener(confsetnamelistenertype_.ON_REMOVE_CONFIG_SET, - self._configMsg.removeConfigSet) - self._configMsg.activateConfigSetListener = \ - self._rtobj.addConfigurationSetNameListener(confsetnamelistenertype_.ON_ACTIVATE_CONFIG_SET, - self._configMsg.activateConfigSet) - return - - - ## - # @if jp - # @brief ConfigurationѲꥹʤβ - # @else - # @brief Unsetting Configurationlistener - # @endif - # - # void unsetConfigurationListeners(); - def unsetConfigurationListeners(self): - confprmlistenertype_ = OpenRTM_aist.ConfigurationParamListenerType - if self._configMsg.updateConfigParamListener: - self._rtobj.removeConfigurationParamListener(confprmlistenertype_.ON_UPDATE_CONFIG_PARAM, - self._configMsg.updateConfigParamListener) - self._configMsg.updateConfigParamListener = None - - confsetlistenertype_ = OpenRTM_aist.ConfigurationSetListenerType - if self._configMsg.setConfigSetListener: - self._rtobj.removeConfigurationSetListener(confsetlistenertype_.ON_SET_CONFIG_SET, - self._configMsg.setConfigSetListener) - self._configMsg.setConfigSetListener = None - - if self._configMsg.addConfigSetListener: - self._rtobj.removeConfigurationSetListener(confsetlistenertype_.ON_ADD_CONFIG_SET, - self._configMsg.addConfigSetListener) - self._configMsg.addConfigSetListener = None - - confsetnamelistenertype_ = OpenRTM_aist.ConfigurationSetNameListenerType - if self._configMsg.updateConfigSetListener: - self._rtobj.removeConfigurationSetNameListener(confsetnamelistenertype_.ON_UPDATE_CONFIG_SET, - self._configMsg.updateConfigSetListener) - self._configMsg.updateConfigSetListener = None - - if self._configMsg.removeConfigSetListener: - self._rtobj.removeConfigurationSetNameListener(confsetnamelistenertype_.ON_REMOVE_CONFIG_SET, - self._configMsg.removeConfigSetListener) - self._configMsg.removeConfigSetListener = None - - if self._configMsg.activateConfigSetListener: - self._rtobj.removeConfigurationSetNameListener(confsetnamelistenertype_.ON_ACTIVATE_CONFIG_SET, - self._configMsg.activateConfigSetListener) - self._configMsg.activateConfigSetListener = None - - return - - ## - # @if jp - # @brief FsmProfileѲꥹʤ - # @else - # @brief Setting FsmProfile listener - # @endif - # - def setFSMProfileListeners(self): - pass - - ## - # @if jp - # @brief FsmProfileѲꥹʤ - # @else - # @brief Setting FsmProfile listener - # @endif - # - def unsetFSMProfileListeners(self): - pass - - - ## - # @if jp - # @brief PostComponentActionListener class - # @else - # @brief PostComponentActionListener class - # @endif - # - class CompStatMsg: - """ - """ - - #CompStatMsg(ComponentObserverConsumer& coc) - def __init__(self, coc): - self.activatedListener = None - self.deactivatedListener = None - self.resetListener = None - self.abortingListener = None - self.finalizeListener = None - self._coc = coc - return - - def __del__(self): - del self._coc - return - - #void onGeneric(const char* msgprefix, UniqueId ec_id, ReturnCode_t ret) - def onGeneric(self, msgprefix, ec_id, ret): - if ret == RTC.RTC_OK: - msg_ = msgprefix - msg_ += str(ec_id) - self._coc.updateStatus(RTC.RTC_STATUS, msg_) - return - - #void onActivated(UniqueId ec_id, ReturnCode_t ret) - def onActivated(self, ec_id, ret): - self.onGeneric("ACTIVE:", ec_id, ret) - return - - #void onDeactivated(UniqueId ec_id, ReturnCode_t ret) - def onDeactivated(self, ec_id, ret): - self.onGeneric("INACTIVE:", ec_id, ret) - return - - #void onReset(UniqueId ec_id, ReturnCode_t ret) - def onReset(self, ec_id, ret): - self.onGeneric("INACTIVE:", ec_id, ret) - return - - #void onAborting(UniqueId ec_id, ReturnCode_t ret) - def onAborting(self, ec_id, ret): - self.onGeneric("ERROR:", ec_id, ret) - return - - #void onFinalize(UniqueId ec_id, ReturnCode_t ret) - def onFinalize(self, ec_id, ret): - self.onGeneric("FINALIZE:", ec_id, ret) - return - - ## - # @if jp - # @brief PortActionListener - # @else - # @brief PortActionListener - # @endif - # - class PortAction: +class ComponentObserverConsumer(OpenRTM_aist.SdoServiceConsumerBase): """ """ - #PortAction(ComponentObserverConsumer& coc) - def __init__(self, coc): - self.portAddListener = None - self.portRemoveListener = None - self.portConnectListener = None - self.portDisconnectListener = None - self._coc = coc - return + ## + # @if jp + # @class ComponentObserverConsumer クラス + # @brief ComponentObserver モジュール + # + # コンポーネントの各種状態をComponentObserverサービスに対してコール + # バックするためのクラス。ツール等、コンポーネントの状態変化を知りた + # いエンティティがサービスプロバイダを当該コンポーネントに対してセッ + # トすると、対応する本コンシューマがアタッチされ、コンポーネントの状 + # 態変化に応じて、update_status() オペレーションをSTATUS_KIND とヒン + # トを引数に呼び出す。本機能は、OMG の FSM4RTC仕様 + # (formal/16-04-01) 7.2.4.2 ComponentObserver Interface に記述されて + # いる。 + # + # STATUS_KIND には以下の種類がある。 + # + # - COMPONENT_PROFILE: コンポーネントのプロファイル情報が変化 + # - RTC_STATUS : コンポーネントの状態 (Init, Alive) が変化 + # - EC_STATUS : ECの状態 (Inavtive, Active, Error) が変化 + # - PORT_PROFILE : ポートのプロファイルが変化 + # - CONFIGURATION : コンフィギュレーションが変化 + # - RTC_HEARTBEAT : RTCの生存確認のハートビード + # - EC_HEARTBEAT : ECの生存確認のハートビート + # - FSM_PROFILE : FSMのプロファイルが変化 + # - FSM_STATUS : FSMの状態が変化 + # - FSM_STRUCTURE : FSMの構造が変化 + # - USER_DEFINED : ユーザ定義 + # + # \subsection COMPONENT_PROFILE COMPONENT_PROFILE + # コンポーネントのプロファイル情報が変化した際にこのタグ名(enum値)を + # 第1引数にして update_status() オペレーションが呼び出される。(未実装) + # + # \subsection RTC_STATUS RTC_STATUS + # + # コンポーネントの状態 (Init, Alive) が変化した際にこのタグ名 + # (enum値)を第1引数にして update_status() オペレーションが呼び出され + # る。厳密にはECの状態であるが、Inavtive, Active, Error, Finalize の + # 4つの状態に変化したことを検知することができる。以下の状態変化時に、 + # それぞれヒントとして以下の文字列とともにコールバックされる。 + # + # - onActivated 呼び出し成功時: ACTIVE: + # - onDeactivated 呼び出し成功時: INACTIVE: + # - onReset 呼び出し成功時: INACTIVE: + # - onAborting 呼び出し成功時: ERROR: + # - onFinalize 呼び出し成功時: FINALIZE: + # + # \subsection EC_STATUS EC_STATUS + # + # ECの状態 (Inavtive, Active, Error) が変化した際にこのタグ名(enum値)を + # 第1引数にして update_status() オペレーションが呼び出される。 + # + # \subsection PORT_PROFILE PORT_PROFILE + # ポートのプロファイルが変化した際にこのタグ名(enum値)を + # 第1引数にして update_status() オペレーションが呼び出される。 + # + # \subsection CONFIGURATION CONFIGURATION + # コンフィギュレーションが変化した際にこのタグ名(enum値)を + # 第1引数にして update_status() オペレーションが呼び出される。 + # + # \subsection RTC_HEARTBEAT RTC_HEARTBEAT + # RTCの生存確認のハートビードした際にこのタグ名(enum値)を + # 第1引数にして update_status() オペレーションが呼び出される。 + # + # \subsection EC_HEARTBEAT EC_HEARTBEAT + # ECの生存確認のハートビートした際にこのタグ名(enum値)を + # 第1引数にして update_status() オペレーションが呼び出される。 + # + # \subsection FSM_PROFILE FSM_PROFILE + # FSMのプロファイルが変化した際にこのタグ名(enum値)を + # 第1引数にして update_status() オペレーションが呼び出される。 + # + # \subsection FSM_STATUS FSM_STATUS + # FSMの状態が変化した際にこのタグ名(enum値)を + # 第1引数にして update_status() オペレーションが呼び出される。 + # + # \subsection FSM_STRUCTURE FSM_STRUCTURE + # FSMの構造が変化した際にこのタグ名(enum値)を + # 第1引数にして update_status() オペレーションが呼び出される。 + # + # \subsection USER_DEFINED USER_DEFINED + # ユーザ定義した際にこのタグ名(enum値)を + # 第1引数にして update_status() オペレーションが呼び出される。 + # @else + # @brief ctor of ComponentObserverConsumer + # @endif + # + def __init__(self): + self._rtobj = None + self._profile = None + self._observer = OpenRTM_aist.CorbaConsumer( + interfaceType=RTC.ComponentObserver) + self._observed = [False for i in range(RTC.STATUS_KIND_NUM._v)] + + self._compstat = self.CompStatMsg(self) + self._portaction = self.PortAction(self) + self._ecaction = self.ECAction(self) + self._configMsg = self.ConfigAction(self) + self._fsmaction = self.FSMAction(self) + + self._rtcInterval = OpenRTM_aist.TimeValue(1, 0) + self._rtcHeartbeat = False + self._ecInterval = OpenRTM_aist.TimeValue(1, 0) + self._ecHeartbeat = False + self._rtcHbTaskId = None + self._ecHbTaskId = None + + return + + ## + # @if jp + # @brief dtor + # @else + # @brief dtor + # @endif + # def __del__(self): - del self._coc - return - - #void onGeneric(const char* _msg, const char* portname) - def onGeneric(self, _msg, portname): - msg_ = _msg - msg_ += portname - self._coc.updateStatus(RTC.PORT_PROFILE, msg_) - return - - #void onAddPort(const ::RTC::PortProfile& pprof) - def onAddPort(self, pprof): - self.onGeneric("ADD:", str(pprof.name)) - return - - #void onRemovePort(const ::RTC::PortProfile& pprof) - def onRemovePort(self, pprof): - self.onGeneric("REMOVE:", str(pprof.name)) - return - - #void onConnect(const char* portname, - # ::RTC::ConnectorProfile& pprof, ReturnCode_t ret) - def onConnect(self, portname, pprof, ret): - if ret == RTC.RTC_OK: - self.onGeneric("CONNECT:", portname) - return - - #void onDisconnect(const char* portname, - # ::RTC::ConnectorProfile& pprof, ReturnCode_t ret) - def onDisconnect(self, portname, pprof, ret): - if ret == RTC.RTC_OK: - self.onGeneric("DISCONNECT:", portname) - return - - - ## - # @if jp - # @brief ExecutionContextActionListener - # @else - # @brief ExecutionContextActionListener - # @endif - # - class ECAction: - """ - """ - - #ECAction(ComponentObserverConsumer& coc) - def __init__(self, coc): - self.ecAttached = None - self.ecDetached = None - self.ecRatechanged = None - self.ecStartup = None - self.ecShutdown = None - self._coc = coc - return + return + + ## + # @if jp + # @brief 初期化 + # @else + # @brief Initialization + # @endif + # + # virtual bool init(RTObject_impl& rtobj, + # const SDOPackage::ServiceProfile& profile); + + def init(self, rtobj, profile): + if not self._observer.setObject(profile.service): + # narrowing failed + return False + + self._rtobj = rtobj + self._profile = profile + prop = OpenRTM_aist.Properties() + OpenRTM_aist.NVUtil.copyToProperties(prop, profile.properties) + self.setRTCHeartbeat(prop) + self.setECHeartbeat(prop) + self.setListeners(prop) + return True + + ## + # @if jp + # @brief 再初期化 + # @else + # @brief Re-initialization + # @endif + # + # virtual bool reinit(const SDOPackage::ServiceProfile& profile); + + def reinit(self, profile): + if not self._observer._ptr()._is_equivalent(profile.service): + tmp = OpenRTM_aist.CorbaConsumer( + interfaceType=RTC.ComponentObserver) + if not tmp.setObject(profile.service): + return False + self._observer.releaseObject() + self._observer.setObject(profile.service) + + self._profile = profile + prop = OpenRTM_aist.Properties() + OpenRTM_aist.NVUtil.copyToProperties(prop, profile.properties) + self.setRTCHeartbeat(prop) + self.setECHeartbeat(prop) + self.setListeners(prop) + return True + + ## + # @if jp + # @brief ServiceProfile を取得する + # @else + # @brief getting ServiceProfile + # @endif + # + # virtual const SDOPackage::ServiceProfile& getProfile() const; + + def getProfile(self): + return self._profile + + ## + # @if jp + # @brief 終了処理 + # @else + # @brief Finalization + # @endif + # + # virtual void finalize(); + + def finalize(self): + self.unsetComponentProfileListeners() + self.unsetComponentStatusListeners() + self.unsetPortProfileListeners() + self.unsetExecutionContextListeners() + self.unsetConfigurationListeners() + self.unsetRTCHeartbeat() + return + + ## + # @if jp + # @brief リモートオブジェクトコール + # @else + # @brief Calling remote object + # @endif + # + # inline void updateStatus(OpenRTM::StatusKind statuskind, const char* msg) + + def updateStatus(self, statuskind, msg): + try: + self._observer._ptr().update_status(statuskind, msg) + except BaseException: + self._rtobj.removeSdoServiceConsumer(self._profile.id) + return + + ## + # @if jp + # @brief Kindを文字列へ変換する + # @else + # @brief Converting kind to string + # @endif + # + # inline const char* toString(OpenRTM::StatusKind kind) + def toString(self, kind): + kinds = ["COMPONENT_PROFILE", + "RTC_STATUS", + "EC_STATUS", + "PORT_PROFILE", + "CONFIGURATION", + "RTC_HEARTBEAT" + "EC_HEARTBEAT", + "FSM_PROFILE", + "FSM_STATUS", + "FSM_STRUCTURE", + "USER_DEFINED"] + if kind._v < len(kinds): + return kinds[kind._v] + return "" + + ## + # @if jp + # @brief RTObjectへのリスナ接続処理 + # @else + # @brief Connectiong listeners to RTObject + # @endif + # + # void setListeners(coil::Properties& prop); + + def setListeners(self, prop): + if not prop.getProperty("observed_status"): + prop.setProperty("observed_status", "ALL") + + observed_ = [s.strip() + for s in prop.getProperty("observed_status").split(",")] + flags_ = [False for i in range(RTC.STATUS_KIND_NUM._v)] + + for i in range(len(observed_)): + observed_[i] = observed_[i].upper() + if observed_[i] == "COMPONENT_PROFILE": + flags_[RTC.COMPONENT_PROFILE._v] = True + elif observed_[i] == "RTC_STATUS": + flags_[RTC.RTC_STATUS._v] = True + elif observed_[i] == "EC_STATUS": + flags_[RTC.EC_STATUS._v] = True + elif observed_[i] == "PORT_PROFILE": + flags_[RTC.PORT_PROFILE._v] = True + elif observed_[i] == "CONFIGURATION": + flags_[RTC.CONFIGURATION._v] = True + elif observed_[i] == "FSM_PROFILE": + flags_[RTC.FSM_PROFILE._v] = True + elif observed_[i] == "FSM_STATUS": + flags_[RTC.FSM_STRUCTURE._v] = True + elif observed_[i] == "FSM_STRUCTURE": + flags_[RTC.CONFIGURATION._v] = True + elif observed_[i] == "ALL": + for j in range(RTC.STATUS_KIND_NUM._v): + flags_[j] = True + break + + self.switchListeners(flags_[RTC.COMPONENT_PROFILE._v], + self._observed, + RTC.COMPONENT_PROFILE._v, + self.setComponentProfileListeners, + self.unsetComponentProfileListeners) + + self.switchListeners(flags_[RTC.RTC_STATUS._v], + self._observed, + RTC.RTC_STATUS._v, + self.setComponentStatusListeners, + self.unsetComponentStatusListeners) + + self.switchListeners(flags_[RTC.EC_STATUS._v], + self._observed, + RTC.EC_STATUS._v, + self.setExecutionContextListeners, + self.unsetExecutionContextListeners) + + self.switchListeners(flags_[RTC.PORT_PROFILE._v], + self._observed, + RTC.PORT_PROFILE._v, + self.setPortProfileListeners, + self.unsetPortProfileListeners) + + self.switchListeners(flags_[RTC.CONFIGURATION._v], + self._observed, + RTC.CONFIGURATION._v, + self.setConfigurationListeners, + self.unsetConfigurationListeners) + + self.switchListeners(flags_[RTC.FSM_PROFILE._v], + self._observed, + RTC.FSM_PROFILE._v, + self.setFSMProfileListeners, + self.unsetFSMProfileListeners) + self.switchListeners(flags_[RTC.FSM_STATUS._v], + self._observed, + RTC.FSM_STATUS._v, + self.setFSMStatusListeners, + self.unsetFSMStatusListeners) + self.switchListeners(flags_[RTC.FSM_STRUCTURE._v], + self._observed, + RTC.FSM_STRUCTURE._v, + self.setFSMStructureListeners, + self.unsetFSMStructureListeners) + + return + + ## + # @if jp + # @brief リスナ接続・切断スイッチング処理 + # @else + # @brief Switching listeners connecting/disconnecting + # @endif + # + # void switchListeners(bool& next, bool& pre, + # void (ComponentObserverConsumer::*setfunc)(), + # void (ComponentObserverConsumer::*unsetfunc)()); + + def switchListeners(self, next, pre, pre_idx, setfunc, unsetfunc): + if (not pre[pre_idx]) and next: + setfunc() + pre[pre_idx] = True + elif pre[pre_idx] and (not next): + unsetfunc() + pre[pre_idx] = False + + return + + # ============================================================ + # Heartbeat related functions + + ## + # @if jp + # @brief ハートビートをオブザーバに伝える + # @else + # @brief Sending a heartbeart signal to observer + # @endif + # + # void rtcHeartbeat(); + + def rtcHeartbeat(self): + if self._rtcHeartbeat: + self.updateStatus(RTC.RTC_HEARTBEAT, "") + return + + ## + # @if jp + # @brief ハートビートを設定する + # @else + # @brief Setting heartbeat + # @endif + # + # void setRTCHeartbeat(coil::Properties& prop); + + def setRTCHeartbeat(self, prop): + self.unsetRTCHeartbeat() + if prop.getProperty("rtc_heartbeat.enable"): + prop.setProperty( + "heartbeat.enable", + prop.getProperty("rtc_heartbeat.enable")) + if prop.getProperty("rtc_heartbeat.interval"): + prop.setProperty( + "heartbeat.interval", + prop.getProperty("rtc_heartbeat.interval")) + + if OpenRTM_aist.toBool(prop.getProperty( + "heartbeat.enable"), "YES", "NO", False): + interval_ = prop.getProperty("heartbeat.interval") + if not interval_: + self._rtcInterval.set_time(1.0) + else: + tmp_ = float(interval_) + self._rtcInterval.set_time(tmp_) + + tm_ = self._rtcInterval + self._rtcHeartbeat = True + self._rtcHbTaskId = OpenRTM_aist.Manager.instance().addTask(self.rtcHeartbeat, tm_) + + return + + ## + # @if jp + # @brief ハートビートを解除する + # @else + # @brief Unsetting heartbeat + # @endif + # + # void unsetRTCHeartbeat(); + + def unsetRTCHeartbeat(self): + if self._rtcHeartbeat: + OpenRTM_aist.Manager.instance().removeTask(self._rtcHbTaskId) + self._rtcHeartbeat = False + return + + + ## + # @if jp + # @brief ハートビートをオブザーバに伝える + # @else + # @brief Sending a heartbeart signal to observer + # @endif + # + # void ecHeartbeat(); + + def ecHeartbeat(self): + if self._ecHeartbeat: + ecs = self._rtobj.get_owned_contexts() + for i in range(len(ecs)): + self.updateStatus(RTC.EC_HEARTBEAT, "HEARTBEAT:" + str(i)) + ecs = self._rtobj.get_participating_contexts() + for i in range(len(ecs)): + self.updateStatus(RTC.EC_HEARTBEAT, "HEARTBEAT:" + + str(i + OpenRTM_aist.ECOTHER_OFFSET)) + + return + + ## + # @if jp + # @brief ハートビートを設定する + # @else + # @brief Setting heartbeat + # @endif + # + # void setECHeartbeat(coil::Properties& prop); + def setECHeartbeat(self, prop): + self.unsetECHeartbeat() + if OpenRTM_aist.toBool(prop.getProperty( + "ec_heartbeat.enable"), "YES", "NO", False): + interval_ = prop.getProperty("ec_heartbeat.interval") + if not interval_: + self._ecInterval.set_time(1.0) + else: + tmp_ = float(interval_) + self._ecInterval.set_time(tmp_) + + tm_ = self._ecInterval + self._ecHeartbeat = True + self._ecHbTaskId = OpenRTM_aist.Manager.instance().addTask(self.ecHeartbeat, tm_) + + return + + ## + # @if jp + # @brief ハートビートを解除する + # @else + # @brief Unsetting heartbeat + # @endif + # + # void unsetECHeartbeat(); + + def unsetECHeartbeat(self): + if self._ecHeartbeat: + OpenRTM_aist.Manager.instance().removeTask(self._ecHbTaskId) + self._ecHeartbeat = False + return + + # ============================================================ + # Component status related functions + + ## + # @if jp + # @brief RTC状態変化リスナの設定処理 + # @else + # @brief Setting RTC status listeners + # @endif + # + # void setComponentStatusListeners(); + + def setComponentStatusListeners(self): + postclistener_ = OpenRTM_aist.PostComponentActionListenerType + if not self._compstat.activatedListener: + self._compstat.activatedListener = \ + self._rtobj.addPostComponentActionListener(postclistener_.POST_ON_ACTIVATED, + self._compstat.onActivated) + if not self._compstat.deactivatedListener: + self._compstat.deactivatedListener = \ + self._rtobj.addPostComponentActionListener(postclistener_.POST_ON_DEACTIVATED, + self._compstat.onDeactivated) + + if not self._compstat.resetListener: + self._compstat.resetListener = \ + self._rtobj.addPostComponentActionListener(postclistener_.POST_ON_RESET, + self._compstat.onReset) + + if not self._compstat.abortingListener: + self._compstat.abortingListener = \ + self._rtobj.addPostComponentActionListener(postclistener_.POST_ON_ABORTING, + self._compstat.onAborting) + + if not self._compstat.finalizeListener: + self._compstat.finalizeListener = \ + self._rtobj.addPostComponentActionListener(postclistener_.POST_ON_FINALIZE, + self._compstat.onFinalize) + + return + + ## + # @if jp + # @brief RTC状態変化リスナの解除処理 + # @else + # @brief Unsetting RTC status listeners + # @endif + # + # void unsetComponentStatusListeners(); + + def unsetComponentStatusListeners(self): + postclistener_ = OpenRTM_aist.PostComponentActionListenerType + if self._compstat.activatedListener: + self._rtobj.removePostComponentActionListener(postclistener_.POST_ON_ACTIVATED, + self._compstat.activatedListener) + self._compstat.activatedListener = None + + if self._compstat.deactivatedListener: + self._rtobj.removePostComponentActionListener(postclistener_.POST_ON_DEACTIVATED, + self._compstat.deactivatedListener) + self._compstat.deactivatedListener = None + + if self._compstat.resetListener: + self._rtobj.removePostComponentActionListener(postclistener_.POST_ON_RESET, + self._compstat.resetListener) + self._compstat.resetListener = None + + if self._compstat.abortingListener: + self._rtobj.removePostComponentActionListener(postclistener_.POST_ON_ABORTING, + self._compstat.abortingListener) + self._compstat.abortingListener = None + + if self._compstat.finalizeListener: + self._rtobj.removePostComponentActionListener(postclistener_.POST_ON_FINALIZE, + self._compstat.finalizeListener) + self._compstat.finalizeListener = None + + return + + def setFSMStatusListeners(self): + pass + + def unsetFSMStatusListeners(self): + pass + + # ============================================================ + # Port profile related functions + + ## + # @if jp + # @brief Portプロファイル変化リスナの設定処理 + # @else + # @brief Setting port profile listener + # @endif + # + # void setPortProfileListeners(); + + def setPortProfileListeners(self): + plistener_ = OpenRTM_aist.PortActionListenerType + if not self._portaction.portAddListener: + self._portaction.portAddListener = \ + self._rtobj.addPortActionListener(plistener_.ADD_PORT, + self._portaction.onAddPort) + + if not self._portaction.portRemoveListener: + self._portaction.portRemoveListener = \ + self._rtobj.addPortActionListener(plistener_.REMOVE_PORT, + self._portaction.onRemovePort) + + pclistener_ = OpenRTM_aist.PortConnectRetListenerType + if not self._portaction.portConnectListener: + self._portaction.portConnectListener = \ + self._rtobj.addPortConnectRetListener(pclistener_.ON_CONNECTED, + self._portaction.onConnect) + + if not self._portaction.portDisconnectListener: + self._portaction.portDisconnectListener = \ + self._rtobj.addPortConnectRetListener(pclistener_.ON_DISCONNECTED, + self._portaction.onDisconnect) + + return + + ## + # @if jp + # @brief Portプロファイル変化リスナの解除処理 + # @else + # @brief Unsetting port profile listener + # @endif + # + # void unsetPortProfileListeners(); + def unsetPortProfileListeners(self): + plistener_ = OpenRTM_aist.PortActionListenerType + if self._portaction.portAddListener: + self._rtobj.removePortActionListener(plistener_.ADD_PORT, + self._portaction.portAddListener) + self._portaction.portAddListener = None + + if self._portaction.portRemoveListener: + self._rtobj.removePortActionListener(plistener_.REMOVE_PORT, + self._portaction.portRemoveListener) + self._portaction.portRemoveListener = None + + pclistener_ = OpenRTM_aist.PortConnectRetListenerType + if self._portaction.portConnectListener: + self._rtobj.removePortConnectRetListener(pclistener_.ON_CONNECTED, + self._portaction.portConnectListener) + self._portaction.portConnectListener = None + + if self._portaction.portDisconnectListener: + self._rtobj.removePortConnectRetListener(pclistener_.ON_DISCONNECTED, + self._portaction.portDisconnectListener) + self._portaction.portDisconnectListener = None + + return + + # ============================================================ + # EC profile related functions + + ## + # @if jp + # @brief ECの状態変化リスナの設定 + # @else + # @brief Setting EC status listener + # @endif + # + # void setExecutionContextListeners(); + + def setExecutionContextListeners(self): + ectype_ = OpenRTM_aist.ExecutionContextActionListenerType + if not self._ecaction.ecAttached: + self._ecaction.ecAttached = \ + self._rtobj.addExecutionContextActionListener(ectype_.EC_ATTACHED, + self._ecaction.onAttached) + + if not self._ecaction.ecDetached: + self._ecaction.ecDetached = \ + self._rtobj.addExecutionContextActionListener(ectype_.EC_DETACHED, + self._ecaction.onDetached) + + pcaltype_ = OpenRTM_aist.PostComponentActionListenerType + if not self._ecaction.ecRatechanged: + self._ecaction.ecRatechanged = \ + self._rtobj.addPostComponentActionListener(pcaltype_.POST_ON_RATE_CHANGED, + self._ecaction.onRateChanged) + + if not self._ecaction.ecStartup: + self._ecaction.ecStartup = \ + self._rtobj.addPostComponentActionListener(pcaltype_.POST_ON_STARTUP, + self._ecaction.onStartup) + + if not self._ecaction.ecShutdown: + self._ecaction.ecShutdown = \ + self._rtobj.addPostComponentActionListener(pcaltype_.POST_ON_SHUTDOWN, + self._ecaction.onShutdown) + + return + + ## + # @if jp + # @brief ECの状態変化リスナの解除 + # @else + # @brief Unsetting EC status listener + # @endif + # + # void unsetExecutionContextListeners(); + + def unsetExecutionContextListeners(self): + ectype_ = OpenRTM_aist.ExecutionContextActionListenerType + if self._ecaction.ecAttached: + self._rtobj.removeExecutionContextActionListener(ectype_.EC_ATTACHED, + self._ecaction.ecAttached) + + if self._ecaction.ecDetached: + self._rtobj.removeExecutionContextActionListener(ectype_.EC_DETACHED, + self._ecaction.ecDetached) + + pcaltype_ = OpenRTM_aist.PostComponentActionListenerType + if self._ecaction.ecRatechanged: + self._rtobj.removePostComponentActionListener(pcaltype_.POST_ON_RATE_CHANGED, + self._ecaction.ecRatechanged) + + if self._ecaction.ecStartup: + self._rtobj.removePostComponentActionListener(pcaltype_.POST_ON_STARTUP, + self._ecaction.ecStartup) + + if self._ecaction.ecShutdown: + self._rtobj.removePostComponentActionListener(pcaltype_.POST_ON_SHUTDOWN, + self._ecaction.ecShutdown) + + return + + # ============================================================ + # ComponentProfile related functions + + ## + # @if jp + # @brief ComponentProfile状態変化リスナの設定 + # @else + # @brief Setting ComponentProfile listener + # @endif + # + # void setComponentProfileListeners(); + + def setComponentProfileListeners(self): + pass + + ## + # @if jp + # @brief ComponentProfile状態変化リスナの解除 + # @else + # @brief Unsetting ComponentProfile listener + # @endif + # + # void unsetComponentProfileListeners(); + + def unsetComponentProfileListeners(self): + pass + + # ============================================================ + # FsmStructure related functions + + ## + # @if jp + # @brief FsmStructure状態変化リスナの設定 + # @else + # @brief Setting FsmStructure listener + # @endif + # + # void setConfigurationListeners(); + + def setFSMStructureListeners(self): + fsmactionlistenertype_ = OpenRTM_aist.PreFsmActionListenerType + self._fsmaction.preOnFsmInitListener = \ + self._rtobj.addPreFsmActionListener(fsmactionlistenertype_.PRE_ON_INIT, + self._fsmaction.preInit) + + self._fsmaction.preOnFsmEntryListener = \ + self._rtobj.addPreFsmActionListener(fsmactionlistenertype_.PRE_ON_ENTRY, + self._fsmaction.preEntry) + + self._fsmaction.preOnFsmDoListener = \ + self._rtobj.addPreFsmActionListener(fsmactionlistenertype_.PRE_ON_DO, + self._fsmaction.preDo) + + self._fsmaction.preOnFsmExitListener = \ + self._rtobj.addPreFsmActionListener(fsmactionlistenertype_.PRE_ON_EXIT, + self._fsmaction.preExit) + + self._fsmaction.preOnFsmStateChangeListener = \ + self._rtobj.addPreFsmActionListener(fsmactionlistenertype_.PRE_ON_STATE_CHANGE, + self._fsmaction.postInit) + + fsmactionlistenertype_ = OpenRTM_aist.PostFsmActionListenerType + + self._fsmaction.postOnFsmInitListener = \ + self._rtobj.addPostFsmActionListener(fsmactionlistenertype_.POST_ON_INIT, + self._fsmaction.preStateChange) + + self._fsmaction.postOnFsmEntryListener = \ + self._rtobj.addPostFsmActionListener(fsmactionlistenertype_.POST_ON_ENTRY, + self._fsmaction.postEntry) + + self._fsmaction.postOnFsmDoListener = \ + self._rtobj.addPostFsmActionListener(fsmactionlistenertype_.POST_ON_DO, + self._fsmaction.postDo) + + self._fsmaction.postOnFsmExitListener = \ + self._rtobj.addPostFsmActionListener(fsmactionlistenertype_.POST_ON_EXIT, + self._fsmaction.postExit) + + self._fsmaction.postOnFsmStateChangeListener = \ + self._rtobj.addPostFsmActionListener(fsmactionlistenertype_.POST_ON_STATE_CHANGE, + self._fsmaction.postStateChange) + + def unsetFSMStructureListeners(self): + fsmactionlistenertype_ = OpenRTM_aist.FSMActionListenerType + if self._fsmaction.preOnFsmInitListener: + self._rtobj.removePreFsmActionListener(fsmactionlistenertype_.PRE_ON_INIT, + self._fsmaction.preOnFsmInitListener) + self._fsmaction.preOnFsmInitListener = None - def __del__(self): - del self._coc - return - - #void onGeneric(const char* _msg, UniqueId ec_id) - def onGeneric(self, _msg, ec_id): - msg_ = _msg + str(ec_id) - self._coc.updateStatus(RTC.EC_STATUS, msg_) - return - - #void onAttached(UniqueId ec_id) - def onAttached(self, ec_id): - self.onGeneric("ATTACHED:", ec_id) - return - - #void onDetached(UniqueId ec_id) - def onDetached(self, ec_id): - self.onGeneric("DETACHED:", ec_id) - return - - #void onRateChanged(UniqueId ec_id, ReturnCode_t ret) - def onRateChanged(self, ec_id, ret): - if ret == RTC.RTC_OK: - self.onGeneric("RATE_CHANGED:", ec_id) - return - - #void onStartup(UniqueId ec_id, ReturnCode_t ret) - def onStartup(self, ec_id, ret): - if ret == RTC.RTC_OK: - self.onGeneric("STARTUP:", ec_id) - return - - #void onShutdown(UniqueId ec_id, ReturnCode_t ret) - def onShutdown(self, ec_id, ret): - if ret == RTC.RTC_OK: - self.onGeneric("SHUTDOWN:", ec_id) - return - - - ## - # @if jp - # @brief ConfigActionListener - # @else - # @brief ConfigActionListener - # @endif - # - class ConfigAction: - """ - """ + if self._fsmaction.preOnFsmEntryListener: + self._rtobj.removePreFsmActionListener(fsmactionlistenertype_.PRE_ON_ENTRY, + self._fsmaction.preOnFsmEntryListener) + self._fsmaction.preOnFsmEntryListener = None - #ConfigAction(ComponentObserverConsumer& coc) - def __init__(self, coc): - self.updateConfigParamListener = None - self.setConfigSetListener = None - self.addConfigSetListener = None - self.updateConfigSetListener = None - self.removeConfigSetListener = None - self.activateConfigSetListener = None - self._coc = coc + if self._fsmaction.preOnFsmDoListener: + self._rtobj.removePreFsmActionListener(fsmactionlistenertype_.PRE_ON_DO, + self._fsmaction.preOnFsmDoListener) + self._fsmaction.preOnFsmDoListener = None - def __del__(self): - del self._coc - return - - #void updateConfigParam(const char* configsetname, - # const char* configparamname) - def updateConfigParam(self, configsetname, configparamname): - msg_ = "UPDATE_CONFIG_PARAM: " - msg_ += configsetname - msg_ += "." - msg_ += configparamname - self._coc.updateStatus(RTC.CONFIGURATION, msg_) - return - - #void setConfigSet(const coil::Properties& config_set) - def setConfigSet(self, config_set): - msg_ = "SET_CONFIG_SET: " - msg_ += config_set.getName() - self._coc.updateStatus(RTC.CONFIGURATION, msg_) - return - - #void addConfigSet(const coil::Properties& config_set) - def addConfigSet(self, config_set): - msg_ = "ADD_CONFIG_SET: " - msg_ += config_set.getName() - self._coc.updateStatus(RTC.CONFIGURATION, msg_) - return - - #void updateConfigSet(const char* config_set_name) - def updateConfigSet(self, config_set_name): - msg_ = "UPDATE_CONFIG_SET: " - msg_ += config_set_name - self._coc.updateStatus(RTC.CONFIGURATION, msg_) - return - - #void removeConfigSet(const char* config_set_name) - def removeConfigSet(self, config_set_name): - msg_ = "REMOVE_CONFIG_SET: " - msg_ += config_set_name - self._coc.updateStatus(RTC.CONFIGURATION, msg_) - return - - #void activateConfigSet(const char* config_set_name) - def activateConfigSet(self, config_set_name): - msg_ = "ACTIVATE_CONFIG_SET: " - msg_ += config_set_name - self._coc.updateStatus(RTC.CONFIGURATION, msg_) - return - - - ## - # @if jp - # @brief FSMActionListener - # @else - # @brief FSMActionListener - # @endif - # - class FSMAction: - """ - """ + if self._fsmaction.preOnFsmExitListener: + self._rtobj.removePreFsmActionListener(fsmactionlistenertype_.PRE_ON_EXIT, + self._fsmaction.preOnFsmExitListener) + self._fsmaction.preOnFsmExitListener = None - #ConfigAction(ComponentObserverConsumer& coc) - def __init__(self, coc): - self.updateFsmStatusListener = None - self.preOnFsmInitListener = None - self.preOnFsmEntryListener = None - self.preOnFsmDoListener = None - self.preOnFsmExitListener = None - self.preOnFsmStateChangeListener = None - self.postOnFsmInitListener = None - self.postOnFsmEntryListener = None - self.postOnFsmDoListener = None - self.postOnFsmExitListener = None - self.postOnFsmStateChangeListener = None - self._coc = coc + if self._fsmaction.preOnFsmStateChangeListener: + self._rtobj.removePreFsmActionListener(fsmactionlistenertype_.PRE_ON_STATE_CHANGE, + self._fsmaction.preOnFsmStateChangeListener) + self._fsmaction.preOnFsmStateChangeListener = None + + if self._fsmaction.postOnFsmInitListener: + self._rtobj.removePostFsmActionListener(fsmactionlistenertype_.POST_ON_INIT, + self._fsmaction.postOnFsmInitListener) + self._fsmaction.postOnFsmInitListener = None + + if self._fsmaction.postOnFsmEntryListener: + self._rtobj.removePostFsmActionListener(fsmactionlistenertype_.POST_ON_ENTRY, + self._fsmaction.postOnFsmEntryListener) + self._fsmaction.postOnFsmEntryListener = None + + if self._fsmaction.postOnFsmDoListener: + self._rtobj.removePostFsmActionListener(fsmactionlistenertype_.POST_ON_DO, + self._fsmaction.postOnFsmDoListener) + self._fsmaction.postOnFsmDoListener = None + + if self._fsmaction.postOnFsmExitListener: + self._rtobj.removePostFsmActionListener(fsmactionlistenertype_.POST_ON_EXIT, + self._fsmaction.postOnFsmExitListener) + self._fsmaction.postOnFsmExitListener = None + + if self._fsmaction.postOnFsmStateChangeListener: + self._rtobj.removePostFsmActionListener(fsmactionlistenertype_.POST_ON_EXIT, + self._fsmaction.postOnFsmStateChangeListener) + self._fsmaction.postOnFsmStateChangeListener = None + + # ============================================================ + # Configuration related functions + + ## + # @if jp + # @brief Configuration状態変化リスナの設定 + # @else + # @brief Setting Configuration listener + # @endif + # + # void setConfigurationListeners(); + def setConfigurationListeners(self): + confprmlistenertype_ = OpenRTM_aist.ConfigurationParamListenerType + self._configMsg.updateConfigParamListener = \ + self._rtobj.addConfigurationParamListener(confprmlistenertype_.ON_UPDATE_CONFIG_PARAM, + self._configMsg.updateConfigParam) + + confsetlistenertype_ = OpenRTM_aist.ConfigurationSetListenerType + self._configMsg.setConfigSetListener = \ + self._rtobj.addConfigurationSetListener(confsetlistenertype_.ON_SET_CONFIG_SET, + self._configMsg.setConfigSet) + + self._configMsg.addConfigSetListener = \ + self._rtobj.addConfigurationSetListener(confsetlistenertype_.ON_ADD_CONFIG_SET, + self._configMsg.addConfigSet) + + confsetnamelistenertype_ = OpenRTM_aist.ConfigurationSetNameListenerType + self._configMsg.updateConfigSetListener = \ + self._rtobj.addConfigurationSetNameListener(confsetnamelistenertype_.ON_UPDATE_CONFIG_SET, + self._configMsg.updateConfigSet) + + self._configMsg.removeConfigSetListener = \ + self._rtobj.addConfigurationSetNameListener(confsetnamelistenertype_.ON_REMOVE_CONFIG_SET, + self._configMsg.removeConfigSet) + self._configMsg.activateConfigSetListener = \ + self._rtobj.addConfigurationSetNameListener(confsetnamelistenertype_.ON_ACTIVATE_CONFIG_SET, + self._configMsg.activateConfigSet) + return + + ## + # @if jp + # @brief Configuration状態変化リスナの解除 + # @else + # @brief Unsetting Configurationlistener + # @endif + # + # void unsetConfigurationListeners(); + + def unsetConfigurationListeners(self): + confprmlistenertype_ = OpenRTM_aist.ConfigurationParamListenerType + if self._configMsg.updateConfigParamListener: + self._rtobj.removeConfigurationParamListener(confprmlistenertype_.ON_UPDATE_CONFIG_PARAM, + self._configMsg.updateConfigParamListener) + self._configMsg.updateConfigParamListener = None + + confsetlistenertype_ = OpenRTM_aist.ConfigurationSetListenerType + if self._configMsg.setConfigSetListener: + self._rtobj.removeConfigurationSetListener(confsetlistenertype_.ON_SET_CONFIG_SET, + self._configMsg.setConfigSetListener) + self._configMsg.setConfigSetListener = None + + if self._configMsg.addConfigSetListener: + self._rtobj.removeConfigurationSetListener(confsetlistenertype_.ON_ADD_CONFIG_SET, + self._configMsg.addConfigSetListener) + self._configMsg.addConfigSetListener = None + + confsetnamelistenertype_ = OpenRTM_aist.ConfigurationSetNameListenerType + if self._configMsg.updateConfigSetListener: + self._rtobj.removeConfigurationSetNameListener(confsetnamelistenertype_.ON_UPDATE_CONFIG_SET, + self._configMsg.updateConfigSetListener) + self._configMsg.updateConfigSetListener = None + + if self._configMsg.removeConfigSetListener: + self._rtobj.removeConfigurationSetNameListener(confsetnamelistenertype_.ON_REMOVE_CONFIG_SET, + self._configMsg.removeConfigSetListener) + self._configMsg.removeConfigSetListener = None + + if self._configMsg.activateConfigSetListener: + self._rtobj.removeConfigurationSetNameListener(confsetnamelistenertype_.ON_ACTIVATE_CONFIG_SET, + self._configMsg.activateConfigSetListener) + self._configMsg.activateConfigSetListener = None + + return + + ## + # @if jp + # @brief FsmProfile状態変化リスナの設定 + # @else + # @brief Setting FsmProfile listener + # @endif + # + def setFSMProfileListeners(self): + pass + + ## + # @if jp + # @brief FsmProfile状態変化リスナの設定 + # @else + # @brief Setting FsmProfile listener + # @endif + # + def unsetFSMProfileListeners(self): + pass + + ## + # @if jp + # @brief PostComponentActionListener class + # @else + # @brief PostComponentActionListener class + # @endif + # + + class CompStatMsg: + """ + """ + + #CompStatMsg(ComponentObserverConsumer& coc) + def __init__(self, coc): + self.activatedListener = None + self.deactivatedListener = None + self.resetListener = None + self.abortingListener = None + self.finalizeListener = None + self._coc = coc + return + + def __del__(self): + del self._coc + return + + # void onGeneric(const char* msgprefix, UniqueId ec_id, ReturnCode_t + # ret) + def onGeneric(self, msgprefix, ec_id, ret): + if ret == RTC.RTC_OK: + msg_ = msgprefix + msg_ += str(ec_id) + self._coc.updateStatus(RTC.RTC_STATUS, msg_) + return + + # void onActivated(UniqueId ec_id, ReturnCode_t ret) + def onActivated(self, ec_id, ret): + self.onGeneric("ACTIVE:", ec_id, ret) + return + + # void onDeactivated(UniqueId ec_id, ReturnCode_t ret) + def onDeactivated(self, ec_id, ret): + self.onGeneric("INACTIVE:", ec_id, ret) + return + + # void onReset(UniqueId ec_id, ReturnCode_t ret) + def onReset(self, ec_id, ret): + self.onGeneric("INACTIVE:", ec_id, ret) + return + + # void onAborting(UniqueId ec_id, ReturnCode_t ret) + def onAborting(self, ec_id, ret): + self.onGeneric("ERROR:", ec_id, ret) + return + + # void onFinalize(UniqueId ec_id, ReturnCode_t ret) + def onFinalize(self, ec_id, ret): + self._coc.unsetRTCHeartbeat() + self._coc.unsetECHeartbeat() + self.onGeneric("FINALIZE:", ec_id, ret) + return + + ## + # @if jp + # @brief PortActionListener + # @else + # @brief PortActionListener + # @endif + # + class PortAction: + """ + """ + + #PortAction(ComponentObserverConsumer& coc) + def __init__(self, coc): + self.portAddListener = None + self.portRemoveListener = None + self.portConnectListener = None + self.portDisconnectListener = None + self._coc = coc + return + + def __del__(self): + del self._coc + return + + # void onGeneric(const char* _msg, const char* portname) + def onGeneric(self, _msg, portname): + msg_ = _msg + msg_ += portname + self._coc.updateStatus(RTC.PORT_PROFILE, msg_) + return + + # void onAddPort(const ::RTC::PortProfile& pprof) + def onAddPort(self, pprof): + self.onGeneric("ADD:", str(pprof.name)) + return + + # void onRemovePort(const ::RTC::PortProfile& pprof) + def onRemovePort(self, pprof): + self.onGeneric("REMOVE:", str(pprof.name)) + return + + # void onConnect(const char* portname, + # ::RTC::ConnectorProfile& pprof, ReturnCode_t ret) + def onConnect(self, portname, pprof, ret): + if ret == RTC.RTC_OK: + self.onGeneric("CONNECT:", portname) + return + + # void onDisconnect(const char* portname, + # ::RTC::ConnectorProfile& pprof, ReturnCode_t ret) + def onDisconnect(self, portname, pprof, ret): + if ret == RTC.RTC_OK: + self.onGeneric("DISCONNECT:", portname) + return + + ## + # @if jp + # @brief ExecutionContextActionListener + # @else + # @brief ExecutionContextActionListener + # @endif + # + + class ECAction: + """ + """ + + #ECAction(ComponentObserverConsumer& coc) + def __init__(self, coc): + self.ecAttached = None + self.ecDetached = None + self.ecRatechanged = None + self.ecStartup = None + self.ecShutdown = None + self._coc = coc + return + + def __del__(self): + del self._coc + return + + # void onGeneric(const char* _msg, UniqueId ec_id) + def onGeneric(self, _msg, ec_id): + msg_ = _msg + str(ec_id) + self._coc.updateStatus(RTC.EC_STATUS, msg_) + return + + # void onAttached(UniqueId ec_id) + def onAttached(self, ec_id): + self.onGeneric("ATTACHED:", ec_id) + return + + # void onDetached(UniqueId ec_id) + def onDetached(self, ec_id): + self.onGeneric("DETACHED:", ec_id) + return + + # void onRateChanged(UniqueId ec_id, ReturnCode_t ret) + def onRateChanged(self, ec_id, ret): + if ret == RTC.RTC_OK: + self.onGeneric("RATE_CHANGED:", ec_id) + return + + # void onStartup(UniqueId ec_id, ReturnCode_t ret) + def onStartup(self, ec_id, ret): + if ret == RTC.RTC_OK: + self.onGeneric("STARTUP:", ec_id) + return + + # void onShutdown(UniqueId ec_id, ReturnCode_t ret) + def onShutdown(self, ec_id, ret): + if ret == RTC.RTC_OK: + self.onGeneric("SHUTDOWN:", ec_id) + return + + ## + # @if jp + # @brief ConfigActionListener + # @else + # @brief ConfigActionListener + # @endif + # + + class ConfigAction: + """ + """ + + #ConfigAction(ComponentObserverConsumer& coc) + def __init__(self, coc): + self.updateConfigParamListener = None + self.setConfigSetListener = None + self.addConfigSetListener = None + self.updateConfigSetListener = None + self.removeConfigSetListener = None + self.activateConfigSetListener = None + self._coc = coc + + def __del__(self): + del self._coc + return + + # void updateConfigParam(const char* configsetname, + # const char* configparamname) + def updateConfigParam(self, configsetname, configparamname): + msg_ = "UPDATE_CONFIG_PARAM: " + msg_ += configsetname + msg_ += "." + msg_ += configparamname + self._coc.updateStatus(RTC.CONFIGURATION, msg_) + return + + # void setConfigSet(const coil::Properties& config_set) + def setConfigSet(self, config_set): + msg_ = "SET_CONFIG_SET: " + msg_ += config_set.getName() + self._coc.updateStatus(RTC.CONFIGURATION, msg_) + return + + # void addConfigSet(const coil::Properties& config_set) + def addConfigSet(self, config_set): + msg_ = "ADD_CONFIG_SET: " + msg_ += config_set.getName() + self._coc.updateStatus(RTC.CONFIGURATION, msg_) + return + + # void updateConfigSet(const char* config_set_name) + def updateConfigSet(self, config_set_name): + msg_ = "UPDATE_CONFIG_SET: " + msg_ += config_set_name + self._coc.updateStatus(RTC.CONFIGURATION, msg_) + return + + # void removeConfigSet(const char* config_set_name) + def removeConfigSet(self, config_set_name): + msg_ = "REMOVE_CONFIG_SET: " + msg_ += config_set_name + self._coc.updateStatus(RTC.CONFIGURATION, msg_) + return + + # void activateConfigSet(const char* config_set_name) + def activateConfigSet(self, config_set_name): + msg_ = "ACTIVATE_CONFIG_SET: " + msg_ += config_set_name + self._coc.updateStatus(RTC.CONFIGURATION, msg_) + return + + ## + # @if jp + # @brief FSMActionListener + # @else + # @brief FSMActionListener + # @endif + # + + class FSMAction: + """ + """ + + #ConfigAction(ComponentObserverConsumer& coc) + def __init__(self, coc): + self.updateFsmStatusListener = None + self.preOnFsmInitListener = None + self.preOnFsmEntryListener = None + self.preOnFsmDoListener = None + self.preOnFsmExitListener = None + self.preOnFsmStateChangeListener = None + self.postOnFsmInitListener = None + self.postOnFsmEntryListener = None + self.postOnFsmDoListener = None + self.postOnFsmExitListener = None + self.postOnFsmStateChangeListener = None + self._coc = coc + + def __del__(self): + del self._coc + return + + def updateFsmStatus(self, state): + self._coc.updateStatus(RTC.FSM_STATUS, state) + return + + def preInit(self, state): + msg_ = state + " PRE_ON_INIT" + self._coc.updateStatus(RTC.FSM_STATUS, msg_) + return + + def preEntry(self, state): + msg_ = state + " PRE_ONENTRY" + self._coc.updateStatus(RTC.FSM_STATUS, msg_) + return + + def preDo(self, state): + msg_ = state + " PRE_ON_DO" + self._coc.updateStatus(RTC.FSM_STATUS, msg_) + return + + def preExit(self, state): + msg_ = state + " PRE_ON_EXIT" + self._coc.updateStatus(RTC.FSM_STATUS, msg_) + return + + def preStateChange(self, state): + msg_ = state + " PRE_ON_STATE_CHANGE" + self._coc.updateStatus(RTC.FSM_STATUS, msg_) + return + + def postInit(self, state): + msg_ = state + " POST_ON_INIT" + self._coc.updateStatus(RTC.FSM_STATUS, msg_) + return + + def postEntry(self, state): + msg_ = state + " POST_ONENTRY" + self._coc.updateStatus(RTC.FSM_STATUS, msg_) + return + + def postDo(self, state): + msg_ = state + " POST_ON_DO" + self._coc.updateStatus(RTC.FSM_STATUS, msg_) + return + + def postExit(self, state): + msg_ = state + " POST_ON_EXIT" + self._coc.updateStatus(RTC.FSM_STATUS, msg_) + return + + def postStateChange(self, state): + msg_ = state + " POST_ON_STATE_CHNAGE" + self._coc.updateStatus(RTC.FSM_STATUS, msg_) + return - def __del__(self): - del self._coc - return - - - def updateFsmStatus(self, state): - self._coc.updateStatus(RTC.FSM_STATUS, state) - return - def preInit(self, state): - msg_ = state+" PRE_ON_INIT" - self._coc.updateStatus(RTC.FSM_STATUS, msg_) - return - def preEntry(self, state): - msg_ = state+" PRE_ONENTRY" - self._coc.updateStatus(RTC.FSM_STATUS, msg_) - return - def preDo(self, state): - msg_ = state+" PRE_ON_DO" - self._coc.updateStatus(RTC.FSM_STATUS, msg_) - return - def preExit(self, state): - msg_ = state+" PRE_ON_EXIT" - self._coc.updateStatus(RTC.FSM_STATUS, msg_) - return - def preStateChange(self, state): - msg_ = state+" PRE_ON_STATE_CHANGE" - self._coc.updateStatus(RTC.FSM_STATUS, msg_) - return - def postInit(self, state): - msg_ = state+" POST_ON_INIT" - self._coc.updateStatus(RTC.FSM_STATUS, msg_) - return - def postEntry(self, state): - msg_ = state+" POST_ONENTRY" - self._coc.updateStatus(RTC.FSM_STATUS, msg_) - return - def postDo(self, state): - msg_ = state+" POST_ON_DO" - self._coc.updateStatus(RTC.FSM_STATUS, msg_) - return - def postExit(self, state): - msg_ = state+" POST_ON_EXIT" - self._coc.updateStatus(RTC.FSM_STATUS, msg_) - return - def postStateChange(self, state): - msg_ = state+" POST_ON_STATE_CHNAGE" - self._coc.updateStatus(RTC.FSM_STATUS, msg_) - return def ComponentObserverConsumerInit(mgr=None): - factory = OpenRTM_aist.SdoServiceConsumerFactory.instance() - factory.addFactory(RTC.ComponentObserver._NP_RepositoryId, - ComponentObserverConsumer, - OpenRTM_aist.Delete) - return + factory = OpenRTM_aist.SdoServiceConsumerFactory.instance() + factory.addFactory(RTC.ComponentObserver._NP_RepositoryId, + ComponentObserverConsumer) + return diff --git a/OpenRTM_aist/ext/fsm4rtc_observer/__init__.py b/OpenRTM_aist/ext/fsm4rtc_observer/__init__.py new file mode 100644 index 00000000..270be2a2 --- /dev/null +++ b/OpenRTM_aist/ext/fsm4rtc_observer/__init__.py @@ -0,0 +1 @@ +# Empty file diff --git a/OpenRTM_aist/ext/local_service/__init__.py b/OpenRTM_aist/ext/local_service/__init__.py new file mode 100644 index 00000000..270be2a2 --- /dev/null +++ b/OpenRTM_aist/ext/local_service/__init__.py @@ -0,0 +1 @@ +# Empty file diff --git a/OpenRTM_aist/ext/local_service/nameservice_file/FileNameservice.py b/OpenRTM_aist/ext/local_service/nameservice_file/FileNameservice.py index e2fadd1b..d08c980b 100644 --- a/OpenRTM_aist/ext/local_service/nameservice_file/FileNameservice.py +++ b/OpenRTM_aist/ext/local_service/nameservice_file/FileNameservice.py @@ -1,9 +1,9 @@ -#!/usr/bin/env python -# -*- coding: euc-jp -*- +#!/usr/bin/env python +# -*- coding: utf-8 -*- ## # @file FileNameservice.py -# @brief FileNameservice +# @brief FileNameservice # @date 2012/01/17 # @author n-ando and Shinji Kurihara # @@ -15,350 +15,349 @@ # All rights reserved. # # $Id$ -# +# import shutil import os.path import OpenRTM_aist service_name = "org.openrtm.local_service.nameservice.file_nameservice" -service_uuid = "7288D080-F618-480B-B6D9-A199686F3101"; -default_config = ["base_path", "./openrtm_ns/", - "file_structure", "tree", +service_uuid = "7288D080-F618-480B-B6D9-A199686F3101" +default_config = ["base_path", "./openrtm_ns/", + "file_structure", "tree", "context_delimiter", "|", ""] ## # @if jp -# @class FileNameservice 饹 -# @brief FileNameservice 饹 +# @class FileNameservice クラス +# @brief FileNameservice クラス # @else # @class FileNameservice class # @brief FileNameservice class # @endif class FileNameservice(OpenRTM_aist.LocalServiceBase): - """ - """ - - ## - # @if jp - # @brief FileNameService ctor - # @else - # @brief FileNameService ctor - # @endif - def __init__(self): - global service_name - global service_uuid - global default_config - - self._profile = OpenRTM_aist.LocalServiceProfile() - self._profile.name = service_name - self._profile.uuid = service_uuid - prop = OpenRTM_aist.Properties(defaults_str=default_config) - self._profile.properties = prop - self._profile.service = self - self._files = [] - self._rtcout = OpenRTM_aist.Manager.instance().getLogbuf("file_nameservice") - self._rtcout.RTC_DEBUG("FileNameservice was created(") - self._rtcout.RTC_DEBUG(" name = %s", self._profile.name) - self._rtcout.RTC_DEBUG(" uuid = %s", self._profile.uuid) - self._rtcout.RTC_DEBUG(" properties = %s", self._profile.properties) - self._rtcout.RTC_DEBUG(" service = %s)", self.__class__.__name__) - return - - - ## - # @if jp - # @brief FileNameService dtor - # @else - # @brief FileNameService dtor - # @endif - def __del__(self): - self._rtcout.RTC_TRACE("FileNameservice.__del__()") - self.cleanupFiles() - return - - - ## - # @if jp - # @brief ؿ - # - # TODO: Documentation - # - # @param profile Ϳ줿 property - # @return - # - # @else - # @brief Initialization function - # - # TODO: Documentation - # - # @endif - # virtual bool - # init(const ::coil::Properties& profile); - def init(self, profile): - self._rtcout.RTC_TRACE("init()") - self._rtcout.RTC_DEBUG(profile) - self._profile.properties.mergeProperties(profile) - - manager_ = OpenRTM_aist.Manager.instance() - manager_.addNamingActionListener(NamingAction(self), True) - return True - - - ## - # @if jp - # @brief ƽؿ - # - # TODO: Documentation - # - # @param profile Ϳ줿 property - # @return - # - # @else - # @brief Reinitialization function - # - # TODO: Documentation - # - # @endif - # virtual bool - # reinit(const ::coil::Properties& profile); - def reinit(self, profile): - self._rtcout.RTC_TRACE("reinit()") - self._rtcout.RTC_DEBUG(profile) - ret = self.processServiceProfile(profile) - self._profile.properties.mergeProperties(profile) - return ret - - - ## - # @if jp - # @brief LocalServiceProfile - # - # TODO: Documentation - # - # @return Υ֥ȤݻƤ LocalServiceProfile - # - # @else - # @brief Getting LocalServiceProfile - # - # TODO: Documentation - # - # @return LocalServiceProfile of this service class - # - # @endif - # virtual const LocalServiceProfile& getProfile() const; - def getProfile(self): - self._rtcout.RTC_TRACE("getProfile()") - return self._profile - - - ## - # @if jp - # @brief λؿ - # - # TODO: Documentation - # - # @else - # @brief Finalization function - # - # TODO: Documentation - # - # @endif - # virtual void finalize(); - def finalize(self): - self.cleanupFiles() - return - - - ## - # @if jp - # @brief ̾Ͽ˸ƤФ륳Хå - # - # TODO: Documentation - # - # @else - # @brief A call-back at name registration - # - # TODO: Documentation - # - # @endif - # void - # onRegisterNameservice(coil::vstring& path, coil::vstring& ns_info); - def onRegisterNameservice(self, path, ns_info): - self._rtcout.RTC_TRACE("onRegisterNameservice(path = %s", - OpenRTM_aist.flatten(path)) - self._rtcout.RTC_TRACE(" nsinfo = %s", - OpenRTM_aist.flatten(ns_info)) - - for i in range(len(path)): - filepath_ = self.getFname(path[i]) - directory_ = os.path.dirname(filepath_) - self._rtcout.RTC_DEBUG("file path: %s", filepath_) - self._rtcout.RTC_DEBUG("directory: %s", directory_) - if not self.createDirectory(directory_): - continue; - try: - filename_ = os.path.basename(filepath_) - self._rtcout.RTC_DEBUG("file name: %s", filename_) - ofile_ = open(filepath_, 'w') - ofs_ = [] - for info in ns_info: - ofs_.append(info) - ofile_.writelines(ofs_) - ofile_.close() - self._rtcout.RTC_INFO("RTC %s's IOR has been successfully registered: %s", - (filename_, filepath_)) - self._files.append(filepath_) - except: - self._rtcout.RTC_ERROR("Creating file has been failed. %s", - filepath_) - return - - - ## - # @if jp - # @brief ̾Ͽ˸ƤФ륳Хå - # - # TODO: Documentation - # - # @else - # @brief A call-back at name runegistration - # - # TODO: Documentation - # - # @endif - # void - # onUnregisterNameservice(coil::vstring& path); - def onUnregisterNameservice(self, path): - self._rtcout.RTC_TRACE("onUnregisterNameservice(%s)", - OpenRTM_aist.flatten(path)) - for i in range(len(path)): - filepath_ = self.getFname(path[i]) - if not os.path.exists(filepath_): - self._rtcout.RTC_ERROR("No such file: %s", filepath_) - continue - - found_path_ = self._files.count(filepath_) - if not found_path_: - self._rtcout.RTC_WARN("This file (%s) might not be my file.", - filepath_) - continue - found_idx_ = self._files.index(filepath_) - del self._files[found_idx_] - - try: - os.remove(filepath_) - self._rtcout.RTC_DEBUG("Removing file: %s", filepath_) - except: - self._rtcout.RTC_ERROR("Removing a file has been failed. %s", - filepath_) - continue - - self._rtcout.RTC_PARANOID("Removing a file done: %s", filepath_) + """ + """ + + ## + # @if jp + # @brief FileNameService ctor + # @else + # @brief FileNameService ctor + # @endif + def __init__(self): + global service_name + global service_uuid + global default_config + + self._profile = OpenRTM_aist.LocalServiceProfile() + self._profile.name = service_name + self._profile.uuid = service_uuid + prop = OpenRTM_aist.Properties(defaults_str=default_config) + self._profile.properties = prop + self._profile.service = self + self._files = [] + self._rtcout = OpenRTM_aist.Manager.instance().getLogbuf("file_nameservice") + self._rtcout.RTC_DEBUG("FileNameservice was created(") + self._rtcout.RTC_DEBUG(" name = %s", self._profile.name) + self._rtcout.RTC_DEBUG(" uuid = %s", self._profile.uuid) + self._rtcout.RTC_DEBUG(" properties = %s", self._profile.properties) + self._rtcout.RTC_DEBUG(" service = %s)", self.__class__.__name__) + return + + ## + # @if jp + # @brief FileNameService dtor + # @else + # @brief FileNameService dtor + # @endif + + def __del__(self): + self._rtcout.RTC_TRACE("FileNameservice.__del__()") + self.cleanupFiles() + return + + ## + # @if jp + # @brief 初期化関数 + # + # TODO: Documentation + # + # @param profile 外部から与えられた property + # @return + # + # @else + # @brief Initialization function + # + # TODO: Documentation + # + # @endif + # virtual bool + # init(const ::coil::Properties& profile); + + def init(self, profile): + self._rtcout.RTC_TRACE("init()") + self._rtcout.RTC_DEBUG(profile) + self._profile.properties.mergeProperties(profile) + + manager_ = OpenRTM_aist.Manager.instance() + manager_.addNamingActionListener(NamingAction(self)) + return True + + ## + # @if jp + # @brief 再初期化関数 + # + # TODO: Documentation + # + # @param profile 外部から与えられた property + # @return + # + # @else + # @brief Reinitialization function + # + # TODO: Documentation + # + # @endif + # virtual bool + # reinit(const ::coil::Properties& profile); + + def reinit(self, profile): + self._rtcout.RTC_TRACE("reinit()") + self._rtcout.RTC_DEBUG(profile) + ret = self.processServiceProfile(profile) + self._profile.properties.mergeProperties(profile) + return ret + + ## + # @if jp + # @brief LocalServiceProfile を取得する + # + # TODO: Documentation + # + # @return このオブジェクトが保持している LocalServiceProfile + # + # @else + # @brief Getting LocalServiceProfile + # + # TODO: Documentation + # + # @return LocalServiceProfile of this service class + # + # @endif + # virtual const LocalServiceProfile& getProfile() const; + + def getProfile(self): + self._rtcout.RTC_TRACE("getProfile()") + return self._profile + + ## + # @if jp + # @brief 終了関数 + # + # TODO: Documentation + # + # @else + # @brief Finalization function + # + # TODO: Documentation + # + # @endif + # virtual void finalize(); + + def finalize(self): + self.cleanupFiles() + return + + ## + # @if jp + # @brief 名前登録時に呼ばれるコールバック + # + # TODO: Documentation + # + # @else + # @brief A call-back at name registration + # + # TODO: Documentation + # + # @endif + # void + # onRegisterNameservice(coil::vstring& path, coil::vstring& ns_info); + + def onRegisterNameservice(self, path, ns_info): + self._rtcout.RTC_TRACE("onRegisterNameservice(path = %s", + OpenRTM_aist.flatten(path)) + self._rtcout.RTC_TRACE(" nsinfo = %s", + OpenRTM_aist.flatten(ns_info)) + + for p in path: + filepath_ = self.getFname(p) + directory_ = os.path.dirname(filepath_) + self._rtcout.RTC_DEBUG("file path: %s", filepath_) + self._rtcout.RTC_DEBUG("directory: %s", directory_) + if not self.createDirectory(directory_): + continue + try: + filename_ = os.path.basename(filepath_) + self._rtcout.RTC_DEBUG("file name: %s", filename_) + ofile_ = open(filepath_, 'w') + ofs_ = [] + for info in ns_info: + ofs_.append(info) + ofile_.writelines(ofs_) + ofile_.close() + self._rtcout.RTC_INFO("RTC %s's IOR has been successfully registered: %s", + (filename_, filepath_)) + self._files.append(filepath_) + except BaseException: + self._rtcout.RTC_ERROR("Creating file has been failed. %s", + filepath_) + return + + ## + # @if jp + # @brief 名前登録解除に呼ばれるコールバック + # + # TODO: Documentation + # + # @else + # @brief A call-back at name runegistration + # + # TODO: Documentation + # + # @endif + # void + # onUnregisterNameservice(coil::vstring& path); + + def onUnregisterNameservice(self, path): + self._rtcout.RTC_TRACE("onUnregisterNameservice(%s)", + OpenRTM_aist.flatten(path)) + for p in path: + filepath_ = self.getFname(p) + if not os.path.exists(filepath_): + self._rtcout.RTC_ERROR("No such file: %s", filepath_) + continue + + found_path_ = self._files.count(filepath_) + if not found_path_: + self._rtcout.RTC_WARN("This file (%s) might not be my file.", + filepath_) + continue + found_idx_ = self._files.index(filepath_) + del self._files[found_idx_] + + try: + os.remove(filepath_) + self._rtcout.RTC_DEBUG("Removing file: %s", filepath_) + except BaseException: + self._rtcout.RTC_ERROR("Removing a file has been failed. %s", + filepath_) + continue + + self._rtcout.RTC_PARANOID("Removing a file done: %s", filepath_) + + return + + ## + # @if jp + # @brief ディレクトリ作成 + # TODO: Documentation + # @else + # @brief Creating directories + # TODO: Documentation + # @endif + # bool createDirectory(fs::path& directory); + + def createDirectory(self, directory): + self._rtcout.RTC_TRACE("createDirectory(%s)", directory) + if not os.path.exists(directory): + self._rtcout.RTC_DEBUG("Directory %s not found", directory) + try: + os.makedirs(directory) + self._rtcout.RTC_DEBUG("Creating directory: %s", directory) + except BaseException: + self._rtcout.RTC_ERROR("Creating directory has been failed. %s", + directory) + return False + + self._rtcout.RTC_PARANOID("Creating directory done: %s", + directory) + + elif os.path.exists(directory) and os.path.isdir(directory): + self._rtcout.RTC_DEBUG("Directory %s exists.", directory) + + else: + self._rtcout.RTC_ERROR("File exists instead of base directory %s.", + directory) + return False + + return True + + ## + # @if jp + # @brief ファイル名取得 + # TODO: Documentation + # @else + # @brief Getting file name + # TODO: Documentation + # @endif + # std::string getFname(std::string& path) const; + + def getFname(self, path): + self._rtcout.RTC_TRACE("getFname(%s)", path) + + pathstring_ = self._profile.properties.getProperty("base_path") + pathstring_ += "/" + + fs_ = self._profile.properties.getProperty("file_structure") + fs_ = fs_.strip().lower() + + if fs_ == "flat": + self._rtcout.RTC_DEBUG("file_structure = flat") + d_ = self._profile.properties.getProperty("context_delimiter") + ns_path_ = OpenRTM_aist.replaceString(path, "/", d_) + pathstring_ += ns_path_ + + elif fs_ == "tree": + self._rtcout.RTC_DEBUG("file_structure = tree") + pathstring_ += path + + self._rtcout.RTC_DEBUG("path string = %s", pathstring_) + + return pathstring_ + + ## + # @if jp + # @brief 全ファイル削除 + # TODO: Documentation + # @else + # @brief Deleting all files + # TODO: Documentation + # @endif + # void cleanupFiles(); + + def cleanupFiles(self): + self._rtcout.RTC_TRACE("cleanupFiles()") + for file in self._files: + os.remove(file) + + self._files = [] + + ## + # @if jp + # @brief プロパティの処理 + # TODO: Documentation + # @else + # @brief Processing properties + # TODO: Documentation + # @endif + # bool processServiceProfile(const ::coil::Properties& props); + + def processServiceProfile(self, props): + return True - return - - - ## - # @if jp - # @brief ǥ쥯ȥ - # TODO: Documentation - # @else - # @brief Creating directories - # TODO: Documentation - # @endif - # bool createDirectory(fs::path& directory); - def createDirectory(self, directory): - self._rtcout.RTC_TRACE("createDirectory(%s)", directory) - if not os.path.exists(directory): - self._rtcout.RTC_DEBUG("Directory %s not found", directory) - try: - os.mkdir(directory) - self._rtcout.RTC_DEBUG("Creating directory: %s", directory) - except: - self._rtcout.RTC_ERROR("Creating directory has been failed. %s", - directory) - return False - - self._rtcout.RTC_PARANOID("Creating directory done: %s", - directory) - - elif os.path.exists(directory) and os.path.isdir(directory): - self._rtcout.RTC_DEBUG("Directory %s exists.", directory) - - else: - self._rtcout.RTC_ERROR("File exists instead of base directory %s.", - directory) - return False - - return True - - - ## - # @if jp - # @brief ե̾ - # TODO: Documentation - # @else - # @brief Getting file name - # TODO: Documentation - # @endif - # std::string getFname(std::string& path) const; - def getFname(self, path): - self._rtcout.RTC_TRACE("getFname(%s)", path) - - pathstring_ = self._profile.properties.getProperty("base_path") - pathstring_ += "/" - - fs_ = self._profile.properties.getProperty("file_structure") - fs_ = fs_.strip().lower() - - if fs_ == "flat": - self._rtcout.RTC_DEBUG("file_structure = flat") - d_ = self._profile.properties.getProperty("context_delimiter") - ns_path_ = [path] - OpenRTM_aist.replaceString(ns_path_, "/", d_) - pathstring_ += ns_path_[0] - - elif fs_ == "tree": - self._rtcout.RTC_DEBUG("file_structure = tree") - pathstring_ += path - - self._rtcout.RTC_DEBUG("path string = %s", pathstring_) - - return pathstring_ - - - ## - # @if jp - # @brief ե - # TODO: Documentation - # @else - # @brief Deleting all files - # TODO: Documentation - # @endif - # void cleanupFiles(); - def cleanupFiles(self): - self._rtcout.RTC_TRACE("cleanupFiles()") - for file in self._files: - os.remove(file) - - self._files = [] - - - ## - # @if jp - # @brief ץѥƥν - # TODO: Documentation - # @else - # @brief Processing properties - # TODO: Documentation - # @endif - # bool processServiceProfile(const ::coil::Properties& props); - def processServiceProfile(self, props): - return True - ## # @if jp @@ -369,97 +368,96 @@ def processServiceProfile(self, props): # TODO: Documentation # @endif class NamingAction: - """ - """ - - ## - # @if jp - # @brief 󥹥ȥ饯 - # @else - # @brief Constructor - # @endif - def __init__(self, fns): - self._fns = fns - return - - - ## - # @if jp - # @brief ǥȥ饯 - # @else - # @brief Destructor - # @endif - def __del__(self): - return - - - ## - # @if jp - # @brief preBind Хåؿ - # TODO: Documentation - # @else - # @brief preBind callback function - # TODO: Documentation - # @endif - # virtual void preBind(RTC::RTObject_impl* rtobj, - # coil::vstring& name); - def preBind(self, rtobj, name): - objref_ = rtobj.getObjRef() - ior_ = OpenRTM_aist.Manager.instance().getORB().object_to_string(objref_) - ns_info_ = [ior_] - self._fns.onRegisterNameservice(name, ns_info_) - return - - - ## - # @if jp - # @brief postBind Хåؿ - # TODO: Documentation - # @else - # @brief postBind callback function - # TODO: Documentation - # @endif - # virtual void postBind(RTC::RTObject_impl* rtobj, - # coil::vstring& name); - def postBind(self, rtobj, name): - return - - - ## - # @if jp - # @brief preUnbind Хåؿ - # TODO: Documentation - # @else - # @brief preUnbind callback function - # TODO: Documentation - # @endif - # virtual void preUnbind(RTC::RTObject_impl* rtobj, - # coil::vstring& name); - def preUnbind(self, rtobj, name): - return - - - ## - # @if jp - # @brief postUnbind Хåؿ - # TODO: Documentation - # @else - # @brief postUnbind callback function - # TODO: Documentation - # @endif - # virtual void postUnbind(RTC::RTObject_impl* rtobj, - # coil::vstring& name); - def postUnbind(self, rtobj, name): - self._fns.onUnregisterNameservice(name) - return - + """ + """ + + ## + # @if jp + # @brief コンストラクタ + # @else + # @brief Constructor + # @endif + def __init__(self, fns): + self._fns = fns + return + + ## + # @if jp + # @brief デストラクタ + # @else + # @brief Destructor + # @endif + + def __del__(self): + return + + ## + # @if jp + # @brief preBind コールバック関数 + # TODO: Documentation + # @else + # @brief preBind callback function + # TODO: Documentation + # @endif + # virtual void preBind(RTC::RTObject_impl* rtobj, + # coil::vstring& name); + + def preBind(self, rtobj, name): + objref_ = rtobj.getObjRef() + ior_ = OpenRTM_aist.Manager.instance().getORB().object_to_string(objref_) + ns_info_ = [ior_] + self._fns.onRegisterNameservice(name, ns_info_) + return + + ## + # @if jp + # @brief postBind コールバック関数 + # TODO: Documentation + # @else + # @brief postBind callback function + # TODO: Documentation + # @endif + # virtual void postBind(RTC::RTObject_impl* rtobj, + # coil::vstring& name); + + def postBind(self, rtobj, name): + return + + ## + # @if jp + # @brief preUnbind コールバック関数 + # TODO: Documentation + # @else + # @brief preUnbind callback function + # TODO: Documentation + # @endif + # virtual void preUnbind(RTC::RTObject_impl* rtobj, + # coil::vstring& name); + + def preUnbind(self, rtobj, name): + return + + ## + # @if jp + # @brief postUnbind コールバック関数 + # TODO: Documentation + # @else + # @brief postUnbind callback function + # TODO: Documentation + # @endif + # virtual void postUnbind(RTC::RTObject_impl* rtobj, + # coil::vstring& name); + + def postUnbind(self, rtobj, name): + self._fns.onUnregisterNameservice(name) + return ## # @if jp -# @brief ⥸塼ؿ +# @brief モジュール初期化関数 # -# FileNameserviceեȥϿؿ +# FileNameserviceをファクトリに登録する初期化関数。 # # @else # @brief Module initialization @@ -468,9 +466,8 @@ def postUnbind(self, rtobj, name): # # @endif def FileNameserviceInit(manager): - global service_name - factory_ = OpenRTM_aist.LocalServiceFactory.instance() - factory_.addFactory(service_name, - FileNameservice, - OpenRTM_aist.Delete) - return + global service_name + factory_ = OpenRTM_aist.LocalServiceFactory.instance() + factory_.addFactory(service_name, + FileNameservice) + return diff --git a/OpenRTM_aist/ext/local_service/nameservice_file/__init__.py b/OpenRTM_aist/ext/local_service/nameservice_file/__init__.py new file mode 100644 index 00000000..270be2a2 --- /dev/null +++ b/OpenRTM_aist/ext/local_service/nameservice_file/__init__.py @@ -0,0 +1 @@ +# Empty file diff --git a/OpenRTM_aist/ext/logger/__init__.py b/OpenRTM_aist/ext/logger/__init__.py index 932b7982..270be2a2 100644 --- a/OpenRTM_aist/ext/logger/__init__.py +++ b/OpenRTM_aist/ext/logger/__init__.py @@ -1 +1 @@ -# Empty file +# Empty file diff --git a/OpenRTM_aist/ext/logger/fluentbit_stream/FluentBit.py b/OpenRTM_aist/ext/logger/fluentbit_stream/FluentBit.py deleted file mode 100644 index 1b388850..00000000 --- a/OpenRTM_aist/ext/logger/fluentbit_stream/FluentBit.py +++ /dev/null @@ -1,415 +0,0 @@ -#!/usr/bin/env python -# -*- coding: euc-jp -*- - - -## -# @file FluentBit.py -# @brief File logger stream class -# @date $Date: $ -# @author Nobuhiko Miyamoto -# Copyright (C) 2017 -# Nobuhiko Miyamoto -# National Institute of -# Advanced Industrial Science and Technology (AIST), Japan -# All rights reserved. -# $Id$ - -import OpenRTM_aist -from fluent import sender -from fluent import event -from fluent import handler -import logging -import logging.handlers - - - - - - - -## -# @if jp -# @class FluentBit -# -# @brief FluentBit 饹 -# -# Υ饹 Ϥ fluent-bit 뤿Υȥ꡼ -# ѥץ饰󥯥饹Ǥ롣 -# -# fluent-bit ϥʬۥߥɥ륦 fluentd CǤ롣 -# fluent-bit/fluentd ͡ʥץȥǥμե륿󥰡 -# ԤȤǤ롣Υ饹ϡȥ꡼Υץ饰 -# FluentBit 饹 std::stream_buff 饹Υ֥饹 -# ꡢºݤ FluentBit ؤΥνʬô饹Ǥ롣 -# -# ǥեȤǤϡOpenRTMΥϤ (input) ȤƼꡢ -# rtc.conf ꤵ줿 (output) ФƥФ뤳Ȥ -# 롣input fluent-bit ѤǤץ饰 rtc.conf ͭ -# ˤ뤳ȤǤ¾ fluentd/fluent-bit ΥϤ -# ꡢCPṲʤɤϤȤƼ뤳ȤǽǤ -# 롣¼Ūˡޥɥ饤ץ fluent-bit ȤۤƱ -# ¸ǽˤʤäƤ롣 -# -# ץϡŪˤ fluent-bit key-value Υץѥƥ -# rtc.conf ǻꤹ뤳ȤǤ٤ƤΥץ饰ѤǤ뤬ʲˡ -# ɽŪʥץ饰ȤΥץ򼨤 -# -# * Available Output plugins -# - reference: http://fluentbit.io/documentation/0.8/output/index.html -# -# ** forward: fluentd forwarding -# ______________________________________________________________________ -# | key | Description | Default | -# ---------------------------------------------------------------------- -# | host | Target host where Fluent-Bit or Fluentd are | 127.0.0.1 | -# | | listening for Forward messages. | | -# ---------------------------------------------------------------------- -# | port | TCP port of the target service. | 24224 | -# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -# Example: -# logger.logstream.fluentd.output0.plugin: forward -# logger.logstream.fluentd.output0.tag: -# logger.logstream.fluentd.output0.host: -# logger.logstream.fluentd.output0.port: -# -# ** es: Elasticsearch -# ______________________________________________________________________ -# | key | Description | Default | -# ---------------------------------------------------------------------- -# | host | IP address or hostname of the target | 127.0.0.1 | -# | | Elasticsearch instance. | | -# ---------------------------------------------------------------------- -# | port | TCP port of the target Elasticsearch | 9200 | -# | | instance. | | -# ---------------------------------------------------------------------- -# | index | Elastic index. | fluentbit | -# ---------------------------------------------------------------------- -# | type | Elastic type. | test | -# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -# -# Example: -# logger.logstream.fluentd.output0.plugin: es -# logger.logstream.fluentd.output0.tag: -# logger.logstream.fluentd.output0.host: -# logger.logstream.fluentd.output0.port: -# logger.logstream.fluentd.output0.index: -# logger.logstream.fluentd.output0.type: -# -# ** http: HTTP POST request in MessagePack format -# ______________________________________________________________________ -# | key | Description | Default | -# ---------------------------------------------------------------------- -# | Host | IP address or hostname of the target HTTP | 127.0.0.1 | -# | | Server. | | -# ---------------------------------------------------------------------- -# | Port | TCP port of the target HTTP Server. | 80 | -# ---------------------------------------------------------------------- -# | Proxy | Specify an HTTP Proxy. The expected format | | -# | | of this value is http://host:port. | | -# | | Note that https is not supported yet. | | -# ---------------------------------------------------------------------- -# | URI | Specify an optional HTTP URI for the target | / | -# | | web server, e.g: /something | | -# ---------------------------------------------------------------------- -# | Format | Specify the data format to be used in the | msgpack | -# | | HTTP request body, by default it uses | | -# | | msgpack, optionally it can be set to json. | | -# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -# -# Example: -# logger.logstream.fluentd.output0.plugin: http -# logger.logstream.fluentd.output0.tag: -# logger.logstream.fluentd.output0.host: 127.0.0.1 -# logger.logstream.fluentd.output0.port: 80 -# logger.logstream.fluentd.output0.proxy: -# logger.logstream.fluentd.output0.uri: /openrtm/ -# logger.logstream.fluentd.output0.format: msgpack -# -# ** nats: NATS output plugin -# ______________________________________________________________________ -# | key | Description | Default | -# ---------------------------------------------------------------------- -# | host | IP address or hostname of the NATS Server. | 127.0.0.1 | -# ---------------------------------------------------------------------- -# | port | TCP port of the target NATS Server. | 4222 | -# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -# -# Example: -# logger.logstream.fluentd.output0.plugin: nats -# logger.logstream.fluentd.output0.tag: -# logger.logstream.fluentd.output0.host: -# logger.logstream.fluentd.output0.port: -# -# * stdout: Standard Output plugin -# -# Example: -# logger.logstream.fluentd.output0.plugin: stdin -# -# -# @else -# @class FluentBit -# -# @brief FluentBit class -# -# -# -# @endif -# -class FluentBit(OpenRTM_aist.LogstreamBase): - s_logger = None - ## - # @if jp - # @brief 󥹥ȥ饯 - # - # 󥹥ȥ饯 - # - # @else - # @brief Constructor - # - # Constructor - # - # @endif - # - def __init__(self): - OpenRTM_aist.LogstreamBase.__init__(self) - ## - # @if jp - # @brief ǥȥ饯 - # - # ǥȥ饯 - # - # @else - # @brief Destructor - # - # Destructor - # - # @endif - # - def __del__(self): - pass - ## - # @if jp - # @brief - # - #Logstream饹γƼԤ饹ǤϡͿ줿 - #PropertiesɬפʾƳƼԤ - # - # @param self - # @param prop - # @return - # - # @else - # @brief Initializing configuration - # - # This operation would be called to configure in initialization. - # In the concrete class, configuration should be performed - # getting appropriate information from the given Properties data. - # - # @param self - # @param prop Configuration information - # @return - # - # @endif - # - def init(self, prop): - self.logger = logging.getLogger("fluent") - self.handlers = [] - - if FluentBit.s_logger is None: - FluentBit.s_logger = self - - logging.PARANOID = logging.DEBUG - 3 - logging.VERBOSE = logging.DEBUG - 2 - logging.TRACE = logging.DEBUG - 1 - logging.FATAL = logging.ERROR + 1 - - logging.addLevelName(logging.PARANOID, "PARANOID") - logging.addLevelName(logging.VERBOSE, "VERBOSE") - logging.addLevelName(logging.TRACE, "TRACE") - logging.addLevelName(logging.FATAL, "FATAL") - - - leaf0 = prop.getLeaf() - for l in leaf0: - key = l.getName() - if key.find("output") != -1: - formatter = handler.FluentRecordFormatter() - tag = l.getProperty("tag") - if tag == "": - return False - host = l.getProperty("host") - if host == "": - host = "127.0.0.1" - port = l.getProperty("port") - try: - port = int(port) - except: - port = 24224 - - fhdlr = handler.FluentHandler(tag, host=host, port=port) - fmt = { - "time": "%(asctime)s", - "name": "%(name)s", - "level": "%(levelname)s", - } - formatter = handler.FluentRecordFormatter(fmt=fmt) - #formatter = logging.Formatter('{Time:%(asctime)s,Name:%(name)s,LEVEL:%(levelname)s,MESSAGE:%(message)s}') - fhdlr.setFormatter(formatter) - self.handlers.append(fhdlr) - self.logger.addHandler(fhdlr) - - self.logger.setLevel(logging.INFO) - - return True - - - - ## - # @if jp - # @brief ʸϤ - # - # - # @param self - # @param msgϤʸ - # @param level ٥ - # @param name ν̾ - # @return - # - # @else - # @brief - # - # - # @param self - # @param msg - # @param level - # @param name - # @return - # - # @endif - # - def log(self, msg, level, name): - log = self.getLogger(name) - if level == OpenRTM_aist.Logger.FATAL: - log.log(logging.FATAL,msg) - elif level == OpenRTM_aist.Logger.ERROR: - log.error(msg) - elif level == OpenRTM_aist.Logger.WARN: - log.warning(msg) - elif level == OpenRTM_aist.Logger.INFO: - log.info(msg) - elif level == OpenRTM_aist.Logger.DEBUG: - log.debug(msg) - elif level == OpenRTM_aist.Logger.TRACE: - log.log(logging.TRACE,msg) - elif level == OpenRTM_aist.Logger.VERBOSE: - log.log(logging.VERBOSE,msg) - elif level == OpenRTM_aist.Logger.PARANOID: - log.log(logging.PARANOID,msg) - else: - return False - - return True - - - - ## - # @if jp - # @brief ٥ - # - # - # @param self - # @param level ٥ - # @return - # - # @else - # @brief - # - # - # @param self - # @param level - # @return - # - # @endif - # - def setLogLevel(self, level): - if level == OpenRTM_aist.Logger.INFO: - self.logger.setLevel(logging.INFO) - elif level == OpenRTM_aist.Logger.FATAL: - self.logger.setLevel(logging.FATAL) - elif level == OpenRTM_aist.Logger.ERROR: - self.logger.setLevel(logging.ERROR) - elif level == OpenRTM_aist.Logger.WARN: - self.logger.setLevel(logging.WARNING) - elif level == OpenRTM_aist.Logger.DEBUG: - self.logger.setLevel(logging.DEBUG) - elif level == OpenRTM_aist.Logger.SILENT: - self.logger.setLevel(logging.NOTSET) - elif level == OpenRTM_aist.Logger.TRACE: - self.logger.setLevel(logging.TRACE) - elif level == OpenRTM_aist.Logger.VERBOSE: - self.logger.setLevel(logging.VERBOSE) - elif level == OpenRTM_aist.Logger.PARANOID: - self.logger.setLevel(logging.PARANOID) - else: - self.logger.setLevel(logging.INFO) - - - - - - ## - # @if jp - # @brief λ - # - # - # @param self - # @return - # - # @else - # @brief - # - # - # @param self - # @return - # - # @endif - # - def shutdown(self): - for h in self.handlers: - logging.Handler.close(h) - self.logger.removeHandler(h) - - FluentBit.s_logger = None - return True - - ## - # @if jp - # @brief μ - # - # - # @param self - # @param name ν̾ - # @return - # - # @else - # @brief - # - # - # @param self - # @param name - # @return - # - # @endif - # - def getLogger(self, name): - if name: - return logging.getLogger("fluent."+name) - else: - return self.logger - - -def FluentBitInit(mgr): - OpenRTM_aist.LogstreamFactory.instance().addFactory("fluentd", - FluentBit, - OpenRTM_aist.Delete) - diff --git a/OpenRTM_aist/ext/logger/fluentbit_stream/__init__.py b/OpenRTM_aist/ext/logger/fluentbit_stream/__init__.py deleted file mode 100644 index 932b7982..00000000 --- a/OpenRTM_aist/ext/logger/fluentbit_stream/__init__.py +++ /dev/null @@ -1 +0,0 @@ -# Empty file diff --git a/OpenRTM_aist/ext/logger/fluentlogger/FluentLogger.py b/OpenRTM_aist/ext/logger/fluentlogger/FluentLogger.py new file mode 100644 index 00000000..fe87dcf3 --- /dev/null +++ b/OpenRTM_aist/ext/logger/fluentlogger/FluentLogger.py @@ -0,0 +1,384 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- + + +## +# @file FluentLogger.py +# @brief File logger stream class +# @date $Date: $ +# @author Nobuhiko Miyamoto +# Copyright (C) 2017 +# Nobuhiko Miyamoto +# National Institute of +# Advanced Industrial Science and Technology (AIST), Japan +# All rights reserved. +# $Id$ + +import OpenRTM_aist +import fluent.handler +import logging +import logging.handlers + + +## +# @if jp +# @class FluentLogger +# +# @brief FluentLogger クラス +# +# このクラスは ログ出力を fluent-bit へ送信するためのログストリーム +# 用プラグインクラスである。 +# +# fluent-logger-python はログ収集・分配ミドルウェア fluentd へイベントを送信することができる。 +# ログストリームのプラグインを構成する FluentLogger クラスはLogstreamBase クラスの +# サブクラスであり、実際の fluent-logger-python へのログの出力部分を担うクラスである。 +# +# OpenRTMのログ出力を Fluentd の forward 入力に送信する。 +# forwardプラグインは TCP でイベントの受信、 UDP でハートビートを受信する。 +# elasticsearch、httpプラグインなどにログを送信する場合はfluentdを経由する +# 必要がある。 +# rtc.conf に設定されたホスト、ポートへのログの送信を行い、 +# CPUやメモリ使用量などを送信することも可能である。 +# また yaml ファイルによりfluent-logger-pythonの詳細な設定が可能である。 +# +# 以下にrtc.confへのオプションの設定例を示す。 +# +# * Available Output plugins +# - reference: https://github.com/fluent/fluent-logger-python +# +# ** forward: fluentd forwarding +# ______________________________________________________________________ +# | key | Description | Default | +# ---------------------------------------------------------------------- +# | host | Target host where Fluent-Bit or Fluentd are | 127.0.0.1 | +# | | listening for Forward messages. | | +# ---------------------------------------------------------------------- +# | port | TCP port of the target service. | 24224 | +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +# Example: +# logger.logstream.fluentd.output0.tag: +# logger.logstream.fluentd.output0.host: +# logger.logstream.fluentd.output0.port: +# +# +# +# @else +# @class FluentLogger +# +# @brief FluentLogger class +# +# +# +# @endif +# +class FluentLogger(OpenRTM_aist.LogstreamBase): + s_logger = None + ## + # @if jp + # @brief コンストラクタ + # + # コンストラクタ + # + # @else + # @brief Constructor + # + # Constructor + # + # @endif + # + + def __init__(self): + OpenRTM_aist.LogstreamBase.__init__(self) + ## + # @if jp + # @brief デストラクタ + # + # デストラクタ + # + # @else + # @brief Destructor + # + # Destructor + # + # @endif + # + + def __del__(self): + pass + ## + # @if jp + # @brief 設定初期化 + # + # LogstreamBaseクラスの各種設定を行う。実装クラスでは、与えられた + # Propertiesから必要な情報を取得して各種設定を行う。 + # + # @param self + # @param prop 設定情報 + # @return + # + # @else + # @brief Initializing configuration + # + # This operation would be called to configure in initialization. + # In the concrete class, configuration should be performed + # getting appropriate information from the given Properties data. + # + # @param self + # @param prop Configuration information + # @return + # + # @endif + # + + def init(self, prop): + self.logger = logging.getLogger("fluent") + self.handlers = [] + + if FluentLogger.s_logger is None: + FluentLogger.s_logger = self + + logging.PARANOID = logging.DEBUG - 3 + logging.VERBOSE = logging.DEBUG - 2 + logging.TRACE = logging.DEBUG - 1 + logging.FATAL = logging.ERROR + 1 + + logging.addLevelName(logging.PARANOID, "PARANOID") + logging.addLevelName(logging.VERBOSE, "VERBOSE") + logging.addLevelName(logging.TRACE, "TRACE") + logging.addLevelName(logging.FATAL, "FATAL") + + leaf0 = prop.getLeaf() + for l in leaf0: + key = l.getName() + if key.find("output") != -1: + formatter = fluent.handler.FluentRecordFormatter() + tag = l.getProperty("tag") + if tag == "": + return False + host = l.getProperty("host") + if host == "": + host = "127.0.0.1" + port = l.getProperty("port") + try: + port = int(port) + except BaseException: + port = 24224 + + fhdlr = fluent.handler.FluentHandler(tag, host=host, port=port) + fhdlr.addFilter(ManagerNameFilter()) + fmt = { + "time": "%(asctime)s", + "name": "%(name)s", + "level": "%(levelname)s", + "pid": "%(process)d", + "host": "%(hostname)s", + "manager": "%(manager)s" + } + formatter = fluent.handler.FluentRecordFormatter(fmt=fmt) + #formatter = logging.Formatter('{Time:%(asctime)s,Name:%(name)s,LEVEL:%(levelname)s,MESSAGE:%(message)s}') + fhdlr.setFormatter(formatter) + self.handlers.append(fhdlr) + self.logger.addHandler(fhdlr) + + self.logger.setLevel(logging.INFO) + + return True + + ## + # @if jp + # @brief 指定文字列をログ出力する + # + # + # @param self + # @param msg ログ出力する文字列 + # @param level ログレベル + # @param name ログの出力名 + # @return + # + # @else + # @brief + # + # + # @param self + # @param msg + # @param level + # @param name + # @return + # + # @endif + # + + def log(self, msg, level, name): + log = self.getLogger(name) + if level == OpenRTM_aist.Logger.FATAL: + log.log(logging.FATAL, msg) + elif level == OpenRTM_aist.Logger.ERROR: + log.error(msg) + elif level == OpenRTM_aist.Logger.WARN: + log.warning(msg) + elif level == OpenRTM_aist.Logger.INFO: + log.info(msg) + elif level == OpenRTM_aist.Logger.DEBUG: + log.debug(msg) + elif level == OpenRTM_aist.Logger.TRACE: + log.log(logging.TRACE, msg) + elif level == OpenRTM_aist.Logger.VERBOSE: + log.log(logging.VERBOSE, msg) + elif level == OpenRTM_aist.Logger.PARANOID: + log.log(logging.PARANOID, msg) + else: + return False + + return True + + ## + # @if jp + # @brief ログレベル設定 + # + # + # @param self + # @param level ログレベル + # @return + # + # @else + # @brief + # + # + # @param self + # @param level + # @return + # + # @endif + # + + def setLogLevel(self, level): + if level == OpenRTM_aist.Logger.INFO: + self.logger.setLevel(logging.INFO) + elif level == OpenRTM_aist.Logger.FATAL: + self.logger.setLevel(logging.FATAL) + elif level == OpenRTM_aist.Logger.ERROR: + self.logger.setLevel(logging.ERROR) + elif level == OpenRTM_aist.Logger.WARN: + self.logger.setLevel(logging.WARNING) + elif level == OpenRTM_aist.Logger.DEBUG: + self.logger.setLevel(logging.DEBUG) + elif level == OpenRTM_aist.Logger.SILENT: + self.logger.setLevel(logging.NOTSET) + elif level == OpenRTM_aist.Logger.TRACE: + self.logger.setLevel(logging.TRACE) + elif level == OpenRTM_aist.Logger.VERBOSE: + self.logger.setLevel(logging.VERBOSE) + elif level == OpenRTM_aist.Logger.PARANOID: + self.logger.setLevel(logging.PARANOID) + else: + self.logger.setLevel(logging.INFO) + + ## + # @if jp + # @brief 終了処理 + # + # + # @param self + # @return + # + # @else + # @brief + # + # + # @param self + # @return + # + # @endif + # + + def shutdown(self): + for h in self.handlers: + logging.Handler.close(h) + self.logger.removeHandler(h) + + FluentLogger.s_logger = None + return True + + ## + # @if jp + # @brief ロガーの取得 + # + # + # @param self + # @param name ログの出力名 + # @return ロガー + # + # @else + # @brief + # + # + # @param self + # @param name + # @return + # + # @endif + # + def getLogger(self, name): + if name: + return logging.getLogger("fluent." + name) + else: + return self.logger + +## +# @if jp +# @class ManagerNameFilter +# +# @brief ManagerNameFilter クラス +# +# ログのフォーマットの"manager"キーにマネージャ名を設定する +# +# @else +# @class ManagerNameFilter +# +# @brief ManagerNameFilter class +# +# +# +# @endif +# + + +class ManagerNameFilter(logging.Filter): + ## + # @if jp + # @brief コンストラクタ + # + # コンストラクタ + # + # @else + # @brief Constructor + # + # Constructor + # + # @endif + # + def __init__(self): + logging.Filter.__init__(self) + conf = OpenRTM_aist.Manager.instance().getConfig() + self._managername = conf.getProperty("manager.instance_name") + ## + # @if jp + # @brief フィルタリングしてメッセージにマネージャ名を追加する + # + # + # @else + # @brief + # + # + # + # @endif + # + + def filter(self, record): + record.manager = self._managername + return True + + +def FluentLoggerInit(mgr): + OpenRTM_aist.LogstreamFactory.instance().addFactory("fluentd", + FluentLogger) diff --git a/OpenRTM_aist/ext/logger/fluentlogger/__init__.py b/OpenRTM_aist/ext/logger/fluentlogger/__init__.py new file mode 100644 index 00000000..270be2a2 --- /dev/null +++ b/OpenRTM_aist/ext/logger/fluentlogger/__init__.py @@ -0,0 +1 @@ +# Empty file diff --git a/OpenRTM_aist/ext/logger/fluentbit_stream/fluentbit.conf b/OpenRTM_aist/ext/logger/fluentlogger/fluentlogger.conf similarity index 75% rename from OpenRTM_aist/ext/logger/fluentbit_stream/fluentbit.conf rename to OpenRTM_aist/ext/logger/fluentlogger/fluentlogger.conf index 12e2569a..a1b13305 100644 --- a/OpenRTM_aist/ext/logger/fluentbit_stream/fluentbit.conf +++ b/OpenRTM_aist/ext/logger/fluentlogger/fluentlogger.conf @@ -1,10 +1,10 @@ -# This is fluentbit logger plugin example in rtc.conf +# This is fluent-python-logger plugin example in rtc.conf logger.enable: YES logger.log_level: PARANOID logger.file_name: rtc%p.log, stdout # fluentbit specific configurations -logger.plugins: FluentBit.py +logger.plugins: FluentLogger.py # Output example (forward) logger.logstream.fluentd.output0.tag: fluent_forward diff --git a/OpenRTM_aist/ext/sdo/__init__.py b/OpenRTM_aist/ext/sdo/__init__.py index 932b7982..270be2a2 100644 --- a/OpenRTM_aist/ext/sdo/__init__.py +++ b/OpenRTM_aist/ext/sdo/__init__.py @@ -1 +1 @@ -# Empty file +# Empty file diff --git a/OpenRTM_aist/ext/sdo/observer/COCTestRTC.py b/OpenRTM_aist/ext/sdo/observer/COCTestRTC.py index 26aee382..4107d319 100644 --- a/OpenRTM_aist/ext/sdo/observer/COCTestRTC.py +++ b/OpenRTM_aist/ext/sdo/observer/COCTestRTC.py @@ -1,4 +1,4 @@ -#!/usr/bin/env python +#!/usr/bin/env python # -*- coding: utf-8 -*- # -*- Python -*- @@ -8,127 +8,130 @@ import OpenRTM_aist coctestrtc_spec = ["implementation_id", "COCTestRTC", - "type_name", "COCTestRTC", - "description", "Console input component", - "version", "1.0", - "vendor", "Shinji Kurihara", - "category", "example", - "activity_type", "DataFlowComponent", - "max_instance", "10", - "language", "Python", - "lang_type", "script", - ""] + "type_name", "COCTestRTC", + "description", "Console input component", + "version", "1.0", + "vendor", "Shinji Kurihara", + "category", "example", + "activity_type", "DataFlowComponent", + "max_instance", "10", + "language", "Python", + "lang_type", "script", + ""] class DataListener(OpenRTM_aist.ConnectorDataListenerT): - def __init__(self, name): - self._name = name - - def __del__(self): - print("dtor of ", self._name) - - def __call__(self, info, cdrdata): - data = OpenRTM_aist.ConnectorDataListenerT.__call__(self, info, cdrdata, RTC.TimedLong(RTC.Time(0,0),0)) - print("------------------------------") - print("Listener: ", self._name) - print("Profile::name: ", info.name) - print("Profile::id: ", info.id) - print("Data: ", data.data) - print("------------------------------") - + def __init__(self, name): + self._name = name + + def __del__(self): + print("dtor of ", self._name) + + def __call__(self, info, data): + print("------------------------------") + print("Listener: ", self._name) + print("Profile::name: ", info.name) + print("Profile::id: ", info.id) + print("Data: ", data.data) + print("------------------------------") + return OpenRTM_aist.ConnectorListenerStatus.NO_CHANGE, data + + class ConnListener(OpenRTM_aist.ConnectorListener): - def __init__(self, name): - self._name = name + def __init__(self, name): + self._name = name - def __del__(self): - print("dtor of ", self._name) + def __del__(self): + print("dtor of ", self._name) - def __call__(self, info): - print("------------------------------") - print("Listener: ", self._name) - print("Profile::name: ", info.name) - print("Profile::id: ", info.id) - print("------------------------------") + def __call__(self, info): + print("------------------------------") + print("Listener: ", self._name) + print("Profile::name: ", info.name) + print("Profile::id: ", info.id) + print("------------------------------") + return OpenRTM_aist.ConnectorListenerStatus.NO_CHANGE class COCTestRTC(OpenRTM_aist.DataFlowComponentBase): - def __init__(self, manager): - OpenRTM_aist.DataFlowComponentBase.__init__(self, manager) - return - - def onInitialize(self): - self._data = RTC.TimedLong(RTC.Time(0,0),0) - self._outport = OpenRTM_aist.OutPort("out", self._data) - # Set OutPort buffer - self.addOutPort("out", self._outport) - self._outport.addConnectorDataListener(OpenRTM_aist.ConnectorDataListenerType.ON_BUFFER_WRITE, - DataListener("ON_BUFFER_WRITE")) - self._outport.addConnectorDataListener(OpenRTM_aist.ConnectorDataListenerType.ON_BUFFER_FULL, - DataListener("ON_BUFFER_FULL")) - self._outport.addConnectorDataListener(OpenRTM_aist.ConnectorDataListenerType.ON_BUFFER_WRITE_TIMEOUT, - DataListener("ON_BUFFER_WRITE_TIMEOUT")) - self._outport.addConnectorDataListener(OpenRTM_aist.ConnectorDataListenerType.ON_BUFFER_OVERWRITE, - DataListener("ON_BUFFER_OVERWRITE")) - self._outport.addConnectorDataListener(OpenRTM_aist.ConnectorDataListenerType.ON_BUFFER_READ, - DataListener("ON_BUFFER_READ")) - self._outport.addConnectorDataListener(OpenRTM_aist.ConnectorDataListenerType.ON_SEND, - DataListener("ON_SEND")) - self._outport.addConnectorDataListener(OpenRTM_aist.ConnectorDataListenerType.ON_RECEIVED, - DataListener("ON_RECEIVED")) - self._outport.addConnectorDataListener(OpenRTM_aist.ConnectorDataListenerType.ON_RECEIVER_FULL, - DataListener("ON_RECEIVER_FULL")) - self._outport.addConnectorDataListener(OpenRTM_aist.ConnectorDataListenerType.ON_RECEIVER_TIMEOUT, - DataListener("ON_RECEIVER_TIMEOUT")) - self._outport.addConnectorDataListener(OpenRTM_aist.ConnectorDataListenerType.ON_RECEIVER_ERROR, - DataListener("ON_RECEIVER_ERROR")) - - self._outport.addConnectorListener(OpenRTM_aist.ConnectorListenerType.ON_CONNECT, - ConnListener("ON_CONNECT")) - self._outport.addConnectorListener(OpenRTM_aist.ConnectorListenerType.ON_DISCONNECT, - ConnListener("ON_DISCONNECT")) - - return RTC.RTC_OK - - - def onExecute(self, ec_id): - print("Please input number: ") - self._data.data = long(sys.stdin.readline()) - OpenRTM_aist.setTimestamp(self._data) - print("Sending to subscriber: ", self._data.data) - self._outport.write() - return RTC.RTC_OK + def __init__(self, manager): + OpenRTM_aist.DataFlowComponentBase.__init__(self, manager) + return + + def onInitialize(self): + self._data = RTC.TimedLong(RTC.Time(0, 0), 0) + self._outport = OpenRTM_aist.OutPort("out", self._data) + # Set OutPort buffer + self.addOutPort("out", self._outport) + self._outport.addConnectorDataListener(OpenRTM_aist.ConnectorDataListenerType.ON_BUFFER_WRITE, + DataListener("ON_BUFFER_WRITE")) + self._outport.addConnectorDataListener(OpenRTM_aist.ConnectorDataListenerType.ON_BUFFER_FULL, + DataListener("ON_BUFFER_FULL")) + self._outport.addConnectorDataListener(OpenRTM_aist.ConnectorDataListenerType.ON_BUFFER_WRITE_TIMEOUT, + DataListener("ON_BUFFER_WRITE_TIMEOUT")) + self._outport.addConnectorDataListener(OpenRTM_aist.ConnectorDataListenerType.ON_BUFFER_OVERWRITE, + DataListener("ON_BUFFER_OVERWRITE")) + self._outport.addConnectorDataListener(OpenRTM_aist.ConnectorDataListenerType.ON_BUFFER_READ, + DataListener("ON_BUFFER_READ")) + self._outport.addConnectorDataListener(OpenRTM_aist.ConnectorDataListenerType.ON_SEND, + DataListener("ON_SEND")) + self._outport.addConnectorDataListener(OpenRTM_aist.ConnectorDataListenerType.ON_RECEIVED, + DataListener("ON_RECEIVED")) + self._outport.addConnectorDataListener(OpenRTM_aist.ConnectorDataListenerType.ON_RECEIVER_FULL, + DataListener("ON_RECEIVER_FULL")) + self._outport.addConnectorDataListener(OpenRTM_aist.ConnectorDataListenerType.ON_RECEIVER_TIMEOUT, + DataListener("ON_RECEIVER_TIMEOUT")) + self._outport.addConnectorDataListener(OpenRTM_aist.ConnectorDataListenerType.ON_RECEIVER_ERROR, + DataListener("ON_RECEIVER_ERROR")) + + self._outport.addConnectorListener(OpenRTM_aist.ConnectorListenerType.ON_CONNECT, + ConnListener("ON_CONNECT")) + self._outport.addConnectorListener(OpenRTM_aist.ConnectorListenerType.ON_DISCONNECT, + ConnListener("ON_DISCONNECT")) + + return RTC.RTC_OK + + def onExecute(self, ec_id): + print("Please input number: ") + self._data.data = long(sys.stdin.readline()) + OpenRTM_aist.setTimestamp(self._data) + print("Sending to subscriber: ", self._data.data) + self._outport.write() + return RTC.RTC_OK def COCTestRTCInit(manager): - profile = OpenRTM_aist.Properties(defaults_str=coctestrtc_spec) - manager.registerFactory(profile, - COCTestRTC, - OpenRTM_aist.Delete) + profile = OpenRTM_aist.Properties(defaults_str=coctestrtc_spec) + manager.registerFactory(profile, + COCTestRTC, + OpenRTM_aist.Delete) def MyModuleInit(manager): - COCTestRTCInit(manager) + COCTestRTCInit(manager) + + # Create a component + comp = manager.createComponent("COCTestRTC") - # Create a component - comp = manager.createComponent("COCTestRTC") def main(): - # Initialize manager - mgr = OpenRTM_aist.Manager.init(sys.argv) + # Initialize manager + mgr = OpenRTM_aist.Manager.init(sys.argv) + + # Set module initialization proceduer + # This procedure will be invoked in activateManager() function. + mgr.setModuleInitProc(MyModuleInit) - # Set module initialization proceduer - # This procedure will be invoked in activateManager() function. - mgr.setModuleInitProc(MyModuleInit) + # Activate manager and register to naming service + mgr.activateManager() - # Activate manager and register to naming service - mgr.activateManager() + # run the manager in blocking mode + # runManager(False) is the default + mgr.runManager() - # run the manager in blocking mode - # runManager(False) is the default - mgr.runManager() + # If you want to run the manager in non-blocking mode, do like this + # mgr.runManager(True) - # If you want to run the manager in non-blocking mode, do like this - # mgr.runManager(True) if __name__ == "__main__": - main() + main() diff --git a/OpenRTM_aist/ext/sdo/observer/ComponentObserverConsumer.py b/OpenRTM_aist/ext/sdo/observer/ComponentObserverConsumer.py index 92bd27d5..94904c5f 100644 --- a/OpenRTM_aist/ext/sdo/observer/ComponentObserverConsumer.py +++ b/OpenRTM_aist/ext/sdo/observer/ComponentObserverConsumer.py @@ -1,5 +1,5 @@ -#!/usr/bin/env python -# -*- coding: euc-jp -*- +#!/usr/bin/env python +# -*- coding: utf-8 -*- ## # @file ComponentObserverConsumer.py @@ -15,1012 +15,1003 @@ # All rights reserved. # -import sys -sys.path.insert(1,".") - -import RTC -import OpenRTM +import threading import OpenRTM_aist +import OpenRTM +import RTC +import sys +sys.path.insert(1, ".") -import threading ## # @if jp # @else # @endif # -class ComponentObserverConsumer(OpenRTM_aist.SdoServiceConsumerBase): - """ - """ - - ## - # @if jp - # @brief ctor of ComponentObserverConsumer - # @else - # @brief ctor of ComponentObserverConsumer - # @endif - # - def __init__(self): - self._rtobj = None - self._profile = None - self._observer = OpenRTM_aist.CorbaConsumer(interfaceType=OpenRTM.ComponentObserver) - self._observed = [ False for i in range(OpenRTM.STATUS_KIND_NUM._v)] - - self._compstat = self.CompStatMsg(self) - self._portaction = self.PortAction(self) - self._ecaction = self.ECAction(self) - self._configMsg = self.ConfigAction(self) - - self._interval = OpenRTM_aist.TimeValue(1, 0) - self._heartbeat = False - self._hblistenerid = None - - self._inportInterval = OpenRTM_aist.TimeValue(1, 0) - self._outportInterval = OpenRTM_aist.TimeValue(1, 0) - - # ΥޡϤ쥰Хʥޤˤ - self._timer = OpenRTM_aist.Timer(self._interval) - self._mutex = threading.RLock() - self._recievedactions = [] - self._sendactions = [] - return - - - ## - # @if jp - # @brief dtor - # @else - # @brief dtor - # @endif - # - def __del__(self): - return - - - ## - # @if jp - # @brief - # @else - # @brief Initialization - # @endif - # - # virtual bool init(RTObject_impl& rtobj, - # const SDOPackage::ServiceProfile& profile); - def init(self, rtobj, profile): - if not self._observer.setObject(profile.service): - # narrowing failed - return False - - self._rtobj = rtobj - self._profile = profile - prop = OpenRTM_aist.Properties() - OpenRTM_aist.NVUtil.copyToProperties(prop, profile.properties) - self.setHeartbeat(prop) - self.setDataPortInterval(prop) - self.setListeners(prop) - return True - - - ## - # @if jp - # @brief ƽ - # @else - # @brief Re-initialization - # @endif - # - # virtual bool reinit(const SDOPackage::ServiceProfile& profile); - def reinit(self, profile): - if not self._observer._ptr()._is_equivalent(profile.service): - tmp = OpenRTM_aist.CorbaConsumer(interfaceType=OpenRTM.ComponentObserver) - if not tmp.setObject(profile.service): - return False - self._observer.releaseObject() - self._observer.setObject(profile.service) - - self._profile= profile - prop = OpenRTM_aist.Properties() - OpenRTM_aist.NVUtil.copyToProperties(prop, profile.properties) - self.setHeartbeat(prop) - self.setListeners(prop) - return True - - - ## - # @if jp - # @brief ServiceProfile - # @else - # @brief getting ServiceProfile - # @endif - # - # virtual const SDOPackage::ServiceProfile& getProfile() const; - def getProfile(self): - return self._profile - - - ## - # @if jp - # @brief λ - # @else - # @brief Finalization - # @endif - # - # virtual void finalize(); - def finalize(self): - guard = OpenRTM_aist.ScopedLock(self._mutex) - self.unsetComponentProfileListeners() - self.unsetComponentStatusListeners() - self.unsetPortProfileListeners() - self.unsetExecutionContextListeners() - self.unsetConfigurationListeners() - self.unsetHeartbeat() - - del self._timer - return - - - ## - # @if jp - # @brief ⡼ȥ֥ȥ - # @else - # @brief Calling remote object - # @endif - # - # inline void updateStatus(OpenRTM::StatusKind statuskind, const char* msg) - def updateStatus(self, statuskind, msg): - try: - self._observer._ptr().update_status(statuskind, msg) - except: - self._rtobj.removeSdoServiceConsumerStartThread(self._profile.id) - return - - ## - # @if jp - # @brief KindʸѴ - # @else - # @brief Converting kind to string - # @endif - # - # inline const char* toString(OpenRTM::StatusKind kind) - def toString(self, kind): - kinds = ["COMPONENT_PROFILE", - "RTC_STATUS", - "EC_STATUS", - "PORT_PROFILE", - "CONFIGURATION", - "HEARTBEAT"] - if kind._v < OpenRTM.STATUS_KIND_NUM._v: - return kinds[kind._v] - return "" - - - ## - # @if jp - # @brief RTObjectؤΥꥹ³ - # @else - # @brief Connectiong listeners to RTObject - # @endif - # - # void setListeners(coil::Properties& prop); - def setListeners(self, prop): - if not prop.getProperty("observed_status"): - prop.setProperty("observed_status", "ALL") - - observed_ = [s.strip() for s in prop.getProperty("observed_status").split(",")] - flags_ = [ False for i in range(OpenRTM.STATUS_KIND_NUM._v) ] - - for i in range(len(observed_)): - observed_[i] = observed_[i].upper() - if observed_[i] == "COMPONENT_PROFILE": - flags_[OpenRTM.COMPONENT_PROFILE._v] = True - elif observed_[i] == "RTC_STATUS": - flags_[OpenRTM.RTC_STATUS._v] = True - elif observed_[i] == "EC_STATUS": - flags_[OpenRTM.EC_STATUS._v] = True - elif observed_[i] == "PORT_PROFILE": - flags_[OpenRTM.PORT_PROFILE._v] = True - elif observed_[i] == "CONFIGURATION": - flags_[OpenRTM.CONFIGURATION._v] = True - elif observed_[i] == "ALL": - for j in range(OpenRTM.STATUS_KIND_NUM._v): - flags_[j] = True - break - - self.switchListeners(flags_[OpenRTM.COMPONENT_PROFILE._v], - self._observed, - OpenRTM.COMPONENT_PROFILE._v, - self.setComponentProfileListeners, - self.unsetComponentProfileListeners) - - self.switchListeners(flags_[OpenRTM.RTC_STATUS._v], - self._observed, - OpenRTM.RTC_STATUS._v, - self.setComponentStatusListeners, - self.unsetComponentStatusListeners) - - self.switchListeners(flags_[OpenRTM.EC_STATUS._v], - self._observed, - OpenRTM.EC_STATUS._v, - self.setExecutionContextListeners, - self.unsetExecutionContextListeners) - - self.switchListeners(flags_[OpenRTM.PORT_PROFILE._v], - self._observed, - OpenRTM.PORT_PROFILE._v, - self.setPortProfileListeners, - self.unsetPortProfileListeners) - - self.switchListeners(flags_[OpenRTM.CONFIGURATION._v], - self._observed, - OpenRTM.CONFIGURATION._v, - self.setConfigurationListeners, - self.unsetConfigurationListeners) - - return - - - ## - # @if jp - # @brief ꥹ³ǥå󥰽 - # @else - # @brief Switching listeners connecting/disconnecting - # @endif - # - # void switchListeners(bool& next, bool& pre, - # void (ComponentObserverConsumer::*setfunc)(), - # void (ComponentObserverConsumer::*unsetfunc)()); - def switchListeners(self, next, pre, pre_idx, setfunc, unsetfunc): - if (not pre[pre_idx]) and next: - setfunc() - pre[pre_idx] = True - elif pre[pre_idx] and (not next): - unsetfunc() - pre[pre_idx] = False - - return - - - #============================================================ - # Heartbeat related functions - - ## - # @if jp - # @brief ϡȥӡȤ򥪥֥Ф - # @else - # @brief Sending a heartbeart signal to observer - # @endif - # - # void heartbeat(); - def heartbeat(self): - self.updateStatus(OpenRTM.HEARTBEAT, "") - return - - - - ## - # @if jp - # @brief ǡݡȥ٥Ȥδֳ֤ꤹ - # @else - # @brief Setting interval of dataport events - # @endif - # - # void setDataPortInterval(coil::Properties& prop); - def setDataPortInterval(self, prop): - - outportInterval = [0.0] - if OpenRTM_aist.stringTo(outportInterval, prop.getProperty("port_profile.send_event.min_interval")): - self._outportInterval = OpenRTM_aist.TimeValue(outportInterval[0]) - - inportInterval = [0.0] - if OpenRTM_aist.stringTo(inportInterval, prop.getProperty("port_profile.receive_event.min_interval")): - self._inportInterval = OpenRTM_aist.TimeValue(inportInterval[0]) - - - - ## - # @if jp - # @brief ϡȥӡȤꤹ - # @else - # @brief Setting heartbeat - # @endif - # - # void setHeartbeat(coil::Properties& prop); - def setHeartbeat(self, prop): - if OpenRTM_aist.toBool(prop.getProperty("heartbeat.enable"), "YES", "NO", False): - interval_ = prop.getProperty("heartbeat.interval") - if not interval_: - self._interval.set_time(1.0) - else: - tmp_ = float(interval_) - self._interval.set_time(tmp_) - - tm_ = self._interval - self._hblistenerid = self._timer.registerListenerObj(self, - ComponentObserverConsumer.heartbeat, - tm_) - if not self._heartbeat: - self._timer.start() - self._heartbeat = True - - else: - if self._heartbeat and self._hblistenerid: - self.unsetHeartbeat() - - return - - - ## - # @if jp - # @brief ϡȥӡȤ - # @else - # @brief Unsetting heartbeat - # @endif - # - # void unsetHeartbeat(); - def unsetHeartbeat(self): - self._timer.unregisterListener(self._hblistenerid) - self._hblistenerid = 0 - self._timer.stop() - self._heartbeat = False - return - - - #============================================================ - # Component status related functions - - ## - # @if jp - # @brief RTCѲꥹʤ - # @else - # @brief Setting RTC status listeners - # @endif - # - # void setComponentStatusListeners(); - def setComponentStatusListeners(self): - postclistener_ = OpenRTM_aist.PostComponentActionListenerType - if not self._compstat.activatedListener: - self._compstat.activatedListener = \ - self._rtobj.addPostComponentActionListener(postclistener_.POST_ON_ACTIVATED, - self._compstat.onActivated) - if not self._compstat.deactivatedListener: - self._compstat.deactivatedListener = \ - self._rtobj.addPostComponentActionListener(postclistener_.POST_ON_DEACTIVATED, - self._compstat.onDeactivated) - - if not self._compstat.resetListener: - self._compstat.resetListener = \ - self._rtobj.addPostComponentActionListener(postclistener_.POST_ON_RESET, - self._compstat.onReset) - - if not self._compstat.abortingListener: - self._compstat.abortingListener = \ - self._rtobj.addPostComponentActionListener(postclistener_.POST_ON_ABORTING, - self._compstat.onAborting) - - if not self._compstat.finalizeListener: - self._compstat.finalizeListener = \ - self._rtobj.addPostComponentActionListener(postclistener_.POST_ON_FINALIZE, - self._compstat.onFinalize) - - return - - - ## - # @if jp - # @brief RTCѲꥹʤβ - # @else - # @brief Unsetting RTC status listeners - # @endif - # - # void unsetComponentStatusListeners(); - def unsetComponentStatusListeners(self): - postclistener_ = OpenRTM_aist.PostComponentActionListenerType - if self._compstat.activatedListener: - self._rtobj.removePostComponentActionListener(postclistener_.POST_ON_ACTIVATED, - self._compstat.activatedListener) - self._compstat.activatedListener = None - - if self._compstat.deactivatedListener: - self._rtobj.removePostComponentActionListener(postclistener_.POST_ON_DEACTIVATED, - self._compstat.deactivatedListener) - self._compstat.deactivatedListener = None - - if self._compstat.resetListener: - self._rtobj.removePostComponentActionListener(postclistener_.POST_ON_RESET, - self._compstat.resetListener) - self._compstat.resetListener = None - - if self._compstat.abortingListener: - self._rtobj.removePostComponentActionListener(postclistener_.POST_ON_ABORTING, - self._compstat.abortingListener) - self._compstat.abortingListener = None - - if self._compstat.finalizeListener: - self._rtobj.removePostComponentActionListener(postclistener_.POST_ON_FINALIZE, - self._compstat.finalizeListener) - self._compstat.finalizeListener = None - return - - - #============================================================ - # Port profile related functions - - ## - # @if jp - # @brief PortץեѲꥹʤ - # @else - # @brief Setting port profile listener - # @endif - # - # void setPortProfileListeners(); - def setPortProfileListeners(self): - plistener_ = OpenRTM_aist.PortActionListenerType - if not self._portaction.portAddListener: - self._portaction.portAddListener = \ - self._rtobj.addPortActionListener(plistener_.ADD_PORT, - self._portaction.onAddPort) - - if not self._portaction.portRemoveListener: - self._portaction.portRemoveListener = \ - self._rtobj.addPortActionListener(plistener_.REMOVE_PORT, - self._portaction.onRemovePort) - - pclistener_ = OpenRTM_aist.PortConnectRetListenerType - if not self._portaction.portConnectListener: - self._portaction.portConnectListener = \ - self._rtobj.addPortConnectRetListener(pclistener_.ON_CONNECTED, - self._portaction.onConnect) - - if not self._portaction.portDisconnectListener: - self._portaction.portDisconnectListener = \ - self._rtobj.addPortConnectRetListener(pclistener_.ON_DISCONNECTED, - self._portaction.onDisconnect) - inports = self._rtobj.getInPorts() - for inport in inports: - msg = "RECEIVE:InPort:" - msg += inport.getName() - - action = self.DataPortAction(self, msg, self._inportInterval) - inport.addConnectorDataListener(OpenRTM_aist.ConnectorDataListenerType.ON_RECEIVED, - action) - self._recievedactions.append(action) - - outports = self._rtobj.getOutPorts() - for outport in outports: - msg = "SEND:OutPort:" - msg += outport.getName() - - action = self.DataPortAction(self, msg, self._outportInterval) - outport.addConnectorDataListener(OpenRTM_aist.ConnectorDataListenerType.ON_SEND, - action) - self._sendactions.append(action) - - return - - ## - # @if jp - # @brief PortץեѲꥹʤβ - # @else - # @brief Unsetting port profile listener - # @endif - # - # void unsetPortProfileListeners(); - def unsetPortProfileListeners(self): - plistener_ = OpenRTM_aist.PortActionListenerType - if self._portaction.portAddListener: - self._rtobj.removePortActionListener(plistener_.ADD_PORT, - self._portaction.portAddListener) - self._portaction.portAddListener = None - - if self._portaction.portRemoveListener: - self._rtobj.removePortActionListener(plistener_.REMOVE_PORT, - self._portaction.portRemoveListener) - self._portaction.portRemoveListener = None - - pclistener_ = OpenRTM_aist.PortConnectRetListenerType - if self._portaction.portConnectListener: - self._rtobj.removePortConnectRetListener(pclistener_.ON_CONNECTED, - self._portaction.portConnectListener) - self._portaction.portConnectListener = None - - if self._portaction.portDisconnectListener: - self._rtobj.removePortConnectRetListener(pclistener_.ON_DISCONNECTED, - self._portaction.portDisconnectListener) - self._portaction.portDisconnectListener = None - - - inports = self._rtobj.getInPorts() - for inport in inports: - for action in self._recievedactions: - inport.removeConnectorDataListener(OpenRTM_aist.ConnectorDataListenerType.ON_RECEIVED, - action) - - - outports = self._rtobj.getOutPorts() - for outport in outports: - for action in self._sendactions: - outport.removeConnectorDataListener(OpenRTM_aist.ConnectorDataListenerType.ON_SEND, - action) - - - return - - - #============================================================ - # EC profile related functions - - ## - # @if jp - # @brief ECξѲꥹʤ - # @else - # @brief Setting EC status listener - # @endif - # - # void setExecutionContextListeners(); - def setExecutionContextListeners(self): - ectype_ = OpenRTM_aist.ExecutionContextActionListenerType - if not self._ecaction.ecAttached: - self._ecaction.ecAttached = \ - self._rtobj.addExecutionContextActionListener(ectype_.EC_ATTACHED, - self._ecaction.onAttached) - - if not self._ecaction.ecDetached: - self._ecaction.ecDetached = \ - self._rtobj.addExecutionContextActionListener(ectype_.EC_DETACHED, - self._ecaction.onDetached) - - pcaltype_ = OpenRTM_aist.PostComponentActionListenerType - if not self._ecaction.ecRatechanged: - self._ecaction.ecRatechanged = \ - self._rtobj.addPostComponentActionListener(pcaltype_.POST_ON_RATE_CHANGED, - self._ecaction.onRateChanged) - - if not self._ecaction.ecStartup: - self._ecaction.ecStartup = \ - self._rtobj.addPostComponentActionListener(pcaltype_.POST_ON_STARTUP, - self._ecaction.onStartup) - - if not self._ecaction.ecShutdown: - self._ecaction.ecShutdown = \ - self._rtobj.addPostComponentActionListener(pcaltype_.POST_ON_SHUTDOWN, - self._ecaction.onShutdown) - - return - - - ## - # @if jp - # @brief ECξѲꥹʤβ - # @else - # @brief Unsetting EC status listener - # @endif - # - # void unsetExecutionContextListeners(); - def unsetExecutionContextListeners(self): - ectype_ = OpenRTM_aist.ExecutionContextActionListenerType - if self._ecaction.ecAttached: - self._rtobj.removeExecutionContextActionListener(ectype_.EC_ATTACHED, - self._ecaction.ecAttached) - - if self._ecaction.ecDetached: - self._rtobj.removeExecutionContextActionListener(ectype_.EC_ATTACHED, - self._ecaction.ecDetached) - - pcaltype_ = OpenRTM_aist.PostComponentActionListenerType - if self._ecaction.ecRatechanged: - self._rtobj.removePostComponentActionListener(pcaltype_.POST_ON_RATE_CHANGED, - self._ecaction.ecRatechanged) - - if self._ecaction.ecStartup: - self._rtobj.removePostComponentActionListener(pcaltype_.POST_ON_STARTUP, - self._ecaction.ecStartup) - - if self._ecaction.ecShutdown: - self._rtobj.removePostComponentActionListener(pcaltype_.POST_ON_SHUTDOWN, - self._ecaction.ecShutdown) - - return - - - #============================================================ - # ComponentProfile related functions - - ## - # @if jp - # @brief ComponentProfileѲꥹʤ - # @else - # @brief Setting ComponentProfile listener - # @endif - # - # void setComponentProfileListeners(); - def setComponentProfileListeners(self): - pass - - - ## - # @if jp - # @brief ComponentProfileѲꥹʤβ - # @else - # @brief Unsetting ComponentProfile listener - # @endif - # - # void unsetComponentProfileListeners(); - def unsetComponentProfileListeners(self): - pass - - - #============================================================ - # Configuration related functions - - ## - # @if jp - # @brief ConfigurationѲꥹʤ - # @else - # @brief Setting Configuration listener - # @endif - # - # void setConfigurationListeners(); - def setConfigurationListeners(self): - confprmlistenertype_ = OpenRTM_aist.ConfigurationParamListenerType - self._configMsg.updateConfigParamListener = \ - self._rtobj.addConfigurationParamListener(confprmlistenertype_.ON_UPDATE_CONFIG_PARAM, - self._configMsg.updateConfigParam) - - confsetlistenertype_ = OpenRTM_aist.ConfigurationSetListenerType - self._configMsg.setConfigSetListener = \ - self._rtobj.addConfigurationSetListener(confsetlistenertype_.ON_SET_CONFIG_SET, - self._configMsg.setConfigSet) - - self._configMsg.addConfigSetListener = \ - self._rtobj.addConfigurationSetListener(confsetlistenertype_.ON_ADD_CONFIG_SET, - self._configMsg.addConfigSet) - - confsetnamelistenertype_ = OpenRTM_aist.ConfigurationSetNameListenerType - self._configMsg.updateConfigSetListener = \ - self._rtobj.addConfigurationSetNameListener(confsetnamelistenertype_.ON_UPDATE_CONFIG_SET, - self._configMsg.updateConfigSet) - - self._configMsg.removeConfigSetListener = \ - self._rtobj.addConfigurationSetNameListener(confsetnamelistenertype_.ON_REMOVE_CONFIG_SET, - self._configMsg.removeConfigSet) - self._configMsg.activateConfigSetListener = \ - self._rtobj.addConfigurationSetNameListener(confsetnamelistenertype_.ON_ACTIVATE_CONFIG_SET, - self._configMsg.activateConfigSet) - return - - - ## - # @if jp - # @brief ConfigurationѲꥹʤβ - # @else - # @brief Unsetting Configurationlistener - # @endif - # - # void unsetConfigurationListeners(); - def unsetConfigurationListeners(self): - confprmlistenertype_ = OpenRTM_aist.ConfigurationParamListenerType - if self._configMsg.updateConfigParamListener: - self._rtobj.removeConfigurationParamListener(confprmlistenertype_.ON_UPDATE_CONFIG_PARAM, - self._configMsg.updateConfigParamListener) - self._configMsg.updateConfigParamListener = None - - confsetlistenertype_ = OpenRTM_aist.ConfigurationSetListenerType - if self._configMsg.setConfigSetListener: - self._rtobj.removeConfigurationSetListener(confsetlistenertype_.ON_SET_CONFIG_SET, - self._configMsg.setConfigSetListener) - self._configMsg.setConfigSetListener = None - - if self._configMsg.addConfigSetListener: - self._rtobj.removeConfigurationSetListener(confsetlistenertype_.ON_ADD_CONFIG_SET, - self._configMsg.addConfigSetListener) - self._configMsg.addConfigSetListener = None - - confsetnamelistenertype_ = OpenRTM_aist.ConfigurationSetNameListenerType - if self._configMsg.updateConfigSetListener: - self._rtobj.removeConfigurationSetNameListener(confsetnamelistenertype_.ON_UPDATE_CONFIG_SET, - self._configMsg.updateConfigSetListener) - self._configMsg.updateConfigSetListener = None - - if self._configMsg.removeConfigSetListener: - self._rtobj.removeConfigurationSetNameListener(confsetnamelistenertype_.ON_REMOVE_CONFIG_SET, - self._configMsg.removeConfigSetListener) - self._configMsg.removeConfigSetListener = None - - if self._configMsg.activateConfigSetListener: - self._rtobj.removeConfigurationSetNameListener(confsetnamelistenertype_.ON_ACTIVATE_CONFIG_SET, - self._configMsg.activateConfigSetListener) - self._configMsg.activateConfigSetListener = None - - return - - - ## - # @if jp - # @brief PostComponentActionListener class - # @else - # @brief PostComponentActionListener class - # @endif - # - class CompStatMsg: - """ - """ - - #CompStatMsg(ComponentObserverConsumer& coc) - def __init__(self, coc): - self.activatedListener = None - self.deactivatedListener = None - self.resetListener = None - self.abortingListener = None - self.finalizeListener = None - self._coc = coc - return - - def __del__(self): - del self._coc - return - - #void onGeneric(const char* msgprefix, UniqueId ec_id, ReturnCode_t ret) - def onGeneric(self, msgprefix, ec_id, ret): - if ret == RTC.RTC_OK: - msg_ = msgprefix - msg_ += str(ec_id) - self._coc.updateStatus(OpenRTM.RTC_STATUS, msg_) - return - - #void onActivated(UniqueId ec_id, ReturnCode_t ret) - def onActivated(self, ec_id, ret): - self.onGeneric("ACTIVE:", ec_id, ret) - return - - #void onDeactivated(UniqueId ec_id, ReturnCode_t ret) - def onDeactivated(self, ec_id, ret): - self.onGeneric("INACTIVE:", ec_id, ret) - return - - #void onReset(UniqueId ec_id, ReturnCode_t ret) - def onReset(self, ec_id, ret): - self.onGeneric("INACTIVE:", ec_id, ret) - return - - #void onAborting(UniqueId ec_id, ReturnCode_t ret) - def onAborting(self, ec_id, ret): - self.onGeneric("ERROR:", ec_id, ret) - return - - #void onFinalize(UniqueId ec_id, ReturnCode_t ret) - def onFinalize(self, ec_id, ret): - self.onGeneric("FINALIZE:", ec_id, ret) - return - - ## - # @if jp - # @brief PortActionListener - # @else - # @brief PortActionListener - # @endif - # - class PortAction: - """ - """ - - #PortAction(ComponentObserverConsumer& coc) - def __init__(self, coc): - self.portAddListener = None - self.portRemoveListener = None - self.portConnectListener = None - self.portDisconnectListener = None - self._coc = coc - return - - def __del__(self): - del self._coc - return - - #void onGeneric(const char* _msg, const char* portname) - def onGeneric(self, _msg, portname): - msg_ = _msg - msg_ += portname - self._coc.updateStatus(OpenRTM.PORT_PROFILE, msg_) - return - - #void onAddPort(const ::RTC::PortProfile& pprof) - def onAddPort(self, pprof): - self.onGeneric("ADD:", str(pprof.name)) - return - - #void onRemovePort(const ::RTC::PortProfile& pprof) - def onRemovePort(self, pprof): - self.onGeneric("REMOVE:", str(pprof.name)) - return - - #void onConnect(const char* portname, - # ::RTC::ConnectorProfile& pprof, ReturnCode_t ret) - def onConnect(self, portname, pprof, ret): - if ret == RTC.RTC_OK: - self.onGeneric("CONNECT:", portname) - return - - #void onDisconnect(const char* portname, - # ::RTC::ConnectorProfile& pprof, ReturnCode_t ret) - def onDisconnect(self, portname, pprof, ret): - if ret == RTC.RTC_OK: - self.onGeneric("DISCONNECT:", portname) - return - - - - ## - # @if jp - # @brief DataPortǡꥹ - # @else - # @brief DataPort's data send/receive action listener - # @endif - # - class DataPortAction(OpenRTM_aist.ConnectorDataListenerT): - """ - """ - def __init__(self, coc, msg, interval): - self._coc = coc - self._msg = msg - self._interval = interval - self._last = OpenRTM_aist.Time() - return - - def __call__(self, info, cdrdata): - curr = OpenRTM_aist.Time() - intvl = curr - self._last - - - if intvl.getTime().toDouble() > self._interval.toDouble(): - self._last = curr - self._coc.updateStatus(OpenRTM.PORT_PROFILE, self._msg) - - return OpenRTM_aist.ConnectorListenerStatus.NO_CHANGE - - - ## - # @if jp - # @brief ExecutionContextActionListener - # @else - # @brief ExecutionContextActionListener - # @endif - # - class ECAction: +class ComponentObserverConsumer(OpenRTM_aist.SdoServiceConsumerBase): """ """ - #ECAction(ComponentObserverConsumer& coc) - def __init__(self, coc): - self.ecAttached = None - self.ecDetached = None - self.ecRatechanged = None - self.ecStartup = None - self.ecShutdown = None - self._coc = coc - return + ## + # @if jp + # @brief ctor of ComponentObserverConsumer + # @else + # @brief ctor of ComponentObserverConsumer + # @endif + # + def __init__(self): + self._rtobj = None + self._profile = None + self._observer = OpenRTM_aist.CorbaConsumer( + interfaceType=OpenRTM.ComponentObserver) + self._observed = [False for i in range(OpenRTM.STATUS_KIND_NUM._v)] + + self._compstat = self.CompStatMsg(self) + self._portaction = self.PortAction(self) + self._ecaction = self.ECAction(self) + self._configMsg = self.ConfigAction(self) + + self._interval = OpenRTM_aist.TimeValue(0, 100000) + self._heartbeat = False + self._hbtaskid = None + + self._inportInterval = OpenRTM_aist.TimeValue(1, 0) + self._outportInterval = OpenRTM_aist.TimeValue(1, 0) + + self._mutex = threading.RLock() + self._recievedactions = [] + self._sendactions = [] + + return + + ## + # @if jp + # @brief dtor + # @else + # @brief dtor + # @endif + # def __del__(self): - del self._coc - return - - #void onGeneric(const char* _msg, UniqueId ec_id) - def onGeneric(self, _msg, ec_id): - msg_ = _msg + str(ec_id) - self._coc.updateStatus(OpenRTM.EC_STATUS, msg_) - return - - #void onAttached(UniqueId ec_id) - def onAttached(self, ec_id): - self.onGeneric("ATTACHED:", ec_id) - return - - #void onDetached(UniqueId ec_id) - def onDetached(self, ec_id): - self.onGeneric("DETACHED:", ec_id) - return - - #void onRateChanged(UniqueId ec_id, ReturnCode_t ret) - def onRateChanged(self, ec_id, ret): - if ret == RTC.RTC_OK: - self.onGeneric("RATE_CHANGED:", ec_id) - return - - #void onStartup(UniqueId ec_id, ReturnCode_t ret) - def onStartup(self, ec_id, ret): - if ret == RTC.RTC_OK: - self.onGeneric("STARTUP:", ec_id) - return - - #void onShutdown(UniqueId ec_id, ReturnCode_t ret) - def onShutdown(self, ec_id, ret): - if ret == RTC.RTC_OK: - self.onGeneric("SHUTDOWN:", ec_id) - return - - - ## - # @if jp - # @brief ConfigActionListener - # @else - # @brief ConfigActionListener - # @endif - # - class ConfigAction: - """ - """ + return + + ## + # @if jp + # @brief 初期化 + # @else + # @brief Initialization + # @endif + # + # virtual bool init(RTObject_impl& rtobj, + # const SDOPackage::ServiceProfile& profile); + + def init(self, rtobj, profile): + if not self._observer.setObject(profile.service): + # narrowing failed + return False + + self._rtobj = rtobj + self._profile = profile + prop = OpenRTM_aist.Properties() + OpenRTM_aist.NVUtil.copyToProperties(prop, profile.properties) + self.setHeartbeat(prop) + self.setDataPortInterval(prop) + self.setListeners(prop) + return True + + ## + # @if jp + # @brief 再初期化 + # @else + # @brief Re-initialization + # @endif + # + # virtual bool reinit(const SDOPackage::ServiceProfile& profile); + + def reinit(self, profile): + if not self._observer._ptr()._is_equivalent(profile.service): + tmp = OpenRTM_aist.CorbaConsumer( + interfaceType=OpenRTM.ComponentObserver) + if not tmp.setObject(profile.service): + return False + self._observer.releaseObject() + self._observer.setObject(profile.service) + + self._profile = profile + prop = OpenRTM_aist.Properties() + OpenRTM_aist.NVUtil.copyToProperties(prop, profile.properties) + self.setHeartbeat(prop) + self.setListeners(prop) + return True + + ## + # @if jp + # @brief ServiceProfile を取得する + # @else + # @brief getting ServiceProfile + # @endif + # + # virtual const SDOPackage::ServiceProfile& getProfile() const; + + def getProfile(self): + return self._profile + + ## + # @if jp + # @brief 終了処理 + # @else + # @brief Finalization + # @endif + # + # virtual void finalize(); + + def finalize(self): + guard = OpenRTM_aist.ScopedLock(self._mutex) + self.unsetComponentProfileListeners() + self.unsetComponentStatusListeners() + self.unsetPortProfileListeners() + self.unsetExecutionContextListeners() + self.unsetConfigurationListeners() + self.unsetHeartbeat() + return + + ## + # @if jp + # @brief リモートオブジェクトコール + # @else + # @brief Calling remote object + # @endif + # + # inline void updateStatus(OpenRTM::StatusKind statuskind, const char* msg) + + def updateStatus(self, statuskind, msg): + try: + self._observer._ptr().update_status(statuskind, msg) + except BaseException: + self._rtobj.removeSdoServiceConsumerStartThread(self._profile.id) + return + + ## + # @if jp + # @brief Kindを文字列へ変換する + # @else + # @brief Converting kind to string + # @endif + # + # inline const char* toString(OpenRTM::StatusKind kind) + def toString(self, kind): + kinds = ["COMPONENT_PROFILE", + "RTC_STATUS", + "EC_STATUS", + "PORT_PROFILE", + "CONFIGURATION", + "HEARTBEAT"] + if kind._v < len(kinds): + return kinds[kind._v] + return "" + + ## + # @if jp + # @brief RTObjectへのリスナ接続処理 + # @else + # @brief Connectiong listeners to RTObject + # @endif + # + # void setListeners(coil::Properties& prop); + + def setListeners(self, prop): + if not prop.getProperty("observed_status"): + prop.setProperty("observed_status", "ALL") + + observed_ = [s.strip() + for s in prop.getProperty("observed_status").split(",")] + flags_ = [False for i in range(OpenRTM.STATUS_KIND_NUM._v)] + + for i in range(len(observed_)): + observed_[i] = observed_[i].upper() + if observed_[i] == "COMPONENT_PROFILE": + flags_[OpenRTM.COMPONENT_PROFILE._v] = True + elif observed_[i] == "RTC_STATUS": + flags_[OpenRTM.RTC_STATUS._v] = True + elif observed_[i] == "EC_STATUS": + flags_[OpenRTM.EC_STATUS._v] = True + elif observed_[i] == "PORT_PROFILE": + flags_[OpenRTM.PORT_PROFILE._v] = True + elif observed_[i] == "CONFIGURATION": + flags_[OpenRTM.CONFIGURATION._v] = True + elif observed_[i] == "ALL": + for j in range(OpenRTM.STATUS_KIND_NUM._v): + flags_[j] = True + break + + self.switchListeners(flags_[OpenRTM.COMPONENT_PROFILE._v], + self._observed, + OpenRTM.COMPONENT_PROFILE._v, + self.setComponentProfileListeners, + self.unsetComponentProfileListeners) + + self.switchListeners(flags_[OpenRTM.RTC_STATUS._v], + self._observed, + OpenRTM.RTC_STATUS._v, + self.setComponentStatusListeners, + self.unsetComponentStatusListeners) + + self.switchListeners(flags_[OpenRTM.EC_STATUS._v], + self._observed, + OpenRTM.EC_STATUS._v, + self.setExecutionContextListeners, + self.unsetExecutionContextListeners) + + self.switchListeners(flags_[OpenRTM.PORT_PROFILE._v], + self._observed, + OpenRTM.PORT_PROFILE._v, + self.setPortProfileListeners, + self.unsetPortProfileListeners) + + self.switchListeners(flags_[OpenRTM.CONFIGURATION._v], + self._observed, + OpenRTM.CONFIGURATION._v, + self.setConfigurationListeners, + self.unsetConfigurationListeners) + + return + + ## + # @if jp + # @brief リスナ接続・切断スイッチング処理 + # @else + # @brief Switching listeners connecting/disconnecting + # @endif + # + # void switchListeners(bool& next, bool& pre, + # void (ComponentObserverConsumer::*setfunc)(), + # void (ComponentObserverConsumer::*unsetfunc)()); + + def switchListeners(self, next, pre, pre_idx, setfunc, unsetfunc): + if (not pre[pre_idx]) and next: + setfunc() + pre[pre_idx] = True + elif pre[pre_idx] and (not next): + unsetfunc() + pre[pre_idx] = False + + return + + # ============================================================ + # Heartbeat related functions + + ## + # @if jp + # @brief ハートビートをオブザーバに伝える + # @else + # @brief Sending a heartbeart signal to observer + # @endif + # + # void heartbeat(); + + def heartbeat(self): + if self._heartbeat: + self.updateStatus(OpenRTM.HEARTBEAT, "") + return + + ## + # @if jp + # @brief データポートイベントの間隔を設定する + # @else + # @brief Setting interval of dataport events + # @endif + # + # void setDataPortInterval(coil::Properties& prop); + def setDataPortInterval(self, prop): + + outportInterval = [0.0] + if OpenRTM_aist.stringTo(outportInterval, prop.getProperty( + "port_profile.send_event.min_interval")): + self._outportInterval = OpenRTM_aist.TimeValue(outportInterval[0]) + + inportInterval = [0.0] + if OpenRTM_aist.stringTo(inportInterval, prop.getProperty( + "port_profile.receive_event.min_interval")): + self._inportInterval = OpenRTM_aist.TimeValue(inportInterval[0]) + + ## + # @if jp + # @brief ハートビートを設定する + # @else + # @brief Setting heartbeat + # @endif + # + # void setHeartbeat(coil::Properties& prop); + + def setHeartbeat(self, prop): + self.unsetHeartbeat() + if OpenRTM_aist.toBool(prop.getProperty( + "heartbeat.enable"), "YES", "NO", False): + interval_ = prop.getProperty("heartbeat.interval") + tm_ = OpenRTM_aist.TimeValue(1, 0) + + if interval_: + tmp_ = float(interval_) + tm_.set_time(tmp_) + + self._heartbeat = True + self._hbtaskid = OpenRTM_aist.Manager.instance().addTask(self.heartbeat, tm_) + + return + + ## + # @if jp + # @brief ハートビートを解除する + # @else + # @brief Unsetting heartbeat + # @endif + # + # void unsetHeartbeat(); + + def unsetHeartbeat(self): + if self._heartbeat: + OpenRTM_aist.Manager.instance().removeTask(self._hbtaskid) + self._heartbeat = False + return + + # ============================================================ + # Component status related functions + + ## + # @if jp + # @brief RTC状態変化リスナの設定処理 + # @else + # @brief Setting RTC status listeners + # @endif + # + # void setComponentStatusListeners(); + + def setComponentStatusListeners(self): + postclistener_ = OpenRTM_aist.PostComponentActionListenerType + if not self._compstat.activatedListener: + self._compstat.activatedListener = \ + self._rtobj.addPostComponentActionListener(postclistener_.POST_ON_ACTIVATED, + self._compstat.onActivated) + if not self._compstat.deactivatedListener: + self._compstat.deactivatedListener = \ + self._rtobj.addPostComponentActionListener(postclistener_.POST_ON_DEACTIVATED, + self._compstat.onDeactivated) + + if not self._compstat.resetListener: + self._compstat.resetListener = \ + self._rtobj.addPostComponentActionListener(postclistener_.POST_ON_RESET, + self._compstat.onReset) + + if not self._compstat.abortingListener: + self._compstat.abortingListener = \ + self._rtobj.addPostComponentActionListener(postclistener_.POST_ON_ABORTING, + self._compstat.onAborting) + + if not self._compstat.finalizeListener: + self._compstat.finalizeListener = \ + self._rtobj.addPostComponentActionListener(postclistener_.POST_ON_FINALIZE, + self._compstat.onFinalize) + + return + + ## + # @if jp + # @brief RTC状態変化リスナの解除処理 + # @else + # @brief Unsetting RTC status listeners + # @endif + # + # void unsetComponentStatusListeners(); + + def unsetComponentStatusListeners(self): + postclistener_ = OpenRTM_aist.PostComponentActionListenerType + if self._compstat.activatedListener: + self._rtobj.removePostComponentActionListener(postclistener_.POST_ON_ACTIVATED, + self._compstat.activatedListener) + self._compstat.activatedListener = None + + if self._compstat.deactivatedListener: + self._rtobj.removePostComponentActionListener(postclistener_.POST_ON_DEACTIVATED, + self._compstat.deactivatedListener) + self._compstat.deactivatedListener = None + + if self._compstat.resetListener: + self._rtobj.removePostComponentActionListener(postclistener_.POST_ON_RESET, + self._compstat.resetListener) + self._compstat.resetListener = None + + if self._compstat.abortingListener: + self._rtobj.removePostComponentActionListener(postclistener_.POST_ON_ABORTING, + self._compstat.abortingListener) + self._compstat.abortingListener = None + + if self._compstat.finalizeListener: + self._rtobj.removePostComponentActionListener(postclistener_.POST_ON_FINALIZE, + self._compstat.finalizeListener) + self._compstat.finalizeListener = None + + return + + # ============================================================ + # Port profile related functions + + ## + # @if jp + # @brief Portプロファイル変化リスナの設定処理 + # @else + # @brief Setting port profile listener + # @endif + # + # void setPortProfileListeners(); + + def setPortProfileListeners(self): + plistener_ = OpenRTM_aist.PortActionListenerType + if not self._portaction.portAddListener: + self._portaction.portAddListener = \ + self._rtobj.addPortActionListener(plistener_.ADD_PORT, + self._portaction.onAddPort) + + if not self._portaction.portRemoveListener: + self._portaction.portRemoveListener = \ + self._rtobj.addPortActionListener(plistener_.REMOVE_PORT, + self._portaction.onRemovePort) + + pclistener_ = OpenRTM_aist.PortConnectRetListenerType + if not self._portaction.portConnectListener: + self._portaction.portConnectListener = \ + self._rtobj.addPortConnectRetListener(pclistener_.ON_CONNECTED, + self._portaction.onConnect) + + if not self._portaction.portDisconnectListener: + self._portaction.portDisconnectListener = \ + self._rtobj.addPortConnectRetListener(pclistener_.ON_DISCONNECTED, + self._portaction.onDisconnect) + inports = self._rtobj.getInPorts() + for inport in inports: + msg = "RECEIVE:InPort:" + msg += inport.getName() + + action = self.DataPortAction(self, msg, self._inportInterval) + inport.addConnectorDataListener(OpenRTM_aist.ConnectorDataListenerType.ON_RECEIVED, + action) + self._recievedactions.append(action) + + outports = self._rtobj.getOutPorts() + for outport in outports: + msg = "SEND:OutPort:" + msg += outport.getName() + + action = self.DataPortAction(self, msg, self._outportInterval) + outport.addConnectorDataListener(OpenRTM_aist.ConnectorDataListenerType.ON_SEND, + action) + self._sendactions.append(action) + + return + + ## + # @if jp + # @brief Portプロファイル変化リスナの解除処理 + # @else + # @brief Unsetting port profile listener + # @endif + # + # void unsetPortProfileListeners(); + def unsetPortProfileListeners(self): + plistener_ = OpenRTM_aist.PortActionListenerType + if self._portaction.portAddListener: + self._rtobj.removePortActionListener(plistener_.ADD_PORT, + self._portaction.portAddListener) + self._portaction.portAddListener = None + + if self._portaction.portRemoveListener: + self._rtobj.removePortActionListener(plistener_.REMOVE_PORT, + self._portaction.portRemoveListener) + self._portaction.portRemoveListener = None + + pclistener_ = OpenRTM_aist.PortConnectRetListenerType + if self._portaction.portConnectListener: + self._rtobj.removePortConnectRetListener(pclistener_.ON_CONNECTED, + self._portaction.portConnectListener) + self._portaction.portConnectListener = None + + if self._portaction.portDisconnectListener: + self._rtobj.removePortConnectRetListener(pclistener_.ON_DISCONNECTED, + self._portaction.portDisconnectListener) + self._portaction.portDisconnectListener = None + + inports = self._rtobj.getInPorts() + for inport in inports: + for action in self._recievedactions: + inport.removeConnectorDataListener(OpenRTM_aist.ConnectorDataListenerType.ON_RECEIVED, + action) + + outports = self._rtobj.getOutPorts() + for outport in outports: + for action in self._sendactions: + outport.removeConnectorDataListener(OpenRTM_aist.ConnectorDataListenerType.ON_SEND, + action) + + return + + # ============================================================ + # EC profile related functions + + ## + # @if jp + # @brief ECの状態変化リスナの設定 + # @else + # @brief Setting EC status listener + # @endif + # + # void setExecutionContextListeners(); + + def setExecutionContextListeners(self): + ectype_ = OpenRTM_aist.ExecutionContextActionListenerType + if not self._ecaction.ecAttached: + self._ecaction.ecAttached = \ + self._rtobj.addExecutionContextActionListener(ectype_.EC_ATTACHED, + self._ecaction.onAttached) + + if not self._ecaction.ecDetached: + self._ecaction.ecDetached = \ + self._rtobj.addExecutionContextActionListener(ectype_.EC_DETACHED, + self._ecaction.onDetached) + + pcaltype_ = OpenRTM_aist.PostComponentActionListenerType + if not self._ecaction.ecRatechanged: + self._ecaction.ecRatechanged = \ + self._rtobj.addPostComponentActionListener(pcaltype_.POST_ON_RATE_CHANGED, + self._ecaction.onRateChanged) + + if not self._ecaction.ecStartup: + self._ecaction.ecStartup = \ + self._rtobj.addPostComponentActionListener(pcaltype_.POST_ON_STARTUP, + self._ecaction.onStartup) + + if not self._ecaction.ecShutdown: + self._ecaction.ecShutdown = \ + self._rtobj.addPostComponentActionListener(pcaltype_.POST_ON_SHUTDOWN, + self._ecaction.onShutdown) + + return + + ## + # @if jp + # @brief ECの状態変化リスナの解除 + # @else + # @brief Unsetting EC status listener + # @endif + # + # void unsetExecutionContextListeners(); + + def unsetExecutionContextListeners(self): + ectype_ = OpenRTM_aist.ExecutionContextActionListenerType + if self._ecaction.ecAttached: + self._rtobj.removeExecutionContextActionListener(ectype_.EC_ATTACHED, + self._ecaction.ecAttached) + + if self._ecaction.ecDetached: + self._rtobj.removeExecutionContextActionListener(ectype_.EC_DETACHED, + self._ecaction.ecDetached) + + pcaltype_ = OpenRTM_aist.PostComponentActionListenerType + if self._ecaction.ecRatechanged: + self._rtobj.removePostComponentActionListener(pcaltype_.POST_ON_RATE_CHANGED, + self._ecaction.ecRatechanged) + + if self._ecaction.ecStartup: + self._rtobj.removePostComponentActionListener(pcaltype_.POST_ON_STARTUP, + self._ecaction.ecStartup) + + if self._ecaction.ecShutdown: + self._rtobj.removePostComponentActionListener(pcaltype_.POST_ON_SHUTDOWN, + self._ecaction.ecShutdown) + + return + + # ============================================================ + # ComponentProfile related functions + + ## + # @if jp + # @brief ComponentProfile状態変化リスナの設定 + # @else + # @brief Setting ComponentProfile listener + # @endif + # + # void setComponentProfileListeners(); + + def setComponentProfileListeners(self): + pass + + ## + # @if jp + # @brief ComponentProfile状態変化リスナの解除 + # @else + # @brief Unsetting ComponentProfile listener + # @endif + # + # void unsetComponentProfileListeners(); + + def unsetComponentProfileListeners(self): + pass + + # ============================================================ + # Configuration related functions + + ## + # @if jp + # @brief Configuration状態変化リスナの設定 + # @else + # @brief Setting Configuration listener + # @endif + # + # void setConfigurationListeners(); + + def setConfigurationListeners(self): + confprmlistenertype_ = OpenRTM_aist.ConfigurationParamListenerType + self._configMsg.updateConfigParamListener = \ + self._rtobj.addConfigurationParamListener(confprmlistenertype_.ON_UPDATE_CONFIG_PARAM, + self._configMsg.updateConfigParam) + + confsetlistenertype_ = OpenRTM_aist.ConfigurationSetListenerType + self._configMsg.setConfigSetListener = \ + self._rtobj.addConfigurationSetListener(confsetlistenertype_.ON_SET_CONFIG_SET, + self._configMsg.setConfigSet) + + self._configMsg.addConfigSetListener = \ + self._rtobj.addConfigurationSetListener(confsetlistenertype_.ON_ADD_CONFIG_SET, + self._configMsg.addConfigSet) + + confsetnamelistenertype_ = OpenRTM_aist.ConfigurationSetNameListenerType + self._configMsg.updateConfigSetListener = \ + self._rtobj.addConfigurationSetNameListener(confsetnamelistenertype_.ON_UPDATE_CONFIG_SET, + self._configMsg.updateConfigSet) + + self._configMsg.removeConfigSetListener = \ + self._rtobj.addConfigurationSetNameListener(confsetnamelistenertype_.ON_REMOVE_CONFIG_SET, + self._configMsg.removeConfigSet) + self._configMsg.activateConfigSetListener = \ + self._rtobj.addConfigurationSetNameListener(confsetnamelistenertype_.ON_ACTIVATE_CONFIG_SET, + self._configMsg.activateConfigSet) + return + + ## + # @if jp + # @brief Configuration状態変化リスナの解除 + # @else + # @brief Unsetting Configurationlistener + # @endif + # + # void unsetConfigurationListeners(); + + def unsetConfigurationListeners(self): + confprmlistenertype_ = OpenRTM_aist.ConfigurationParamListenerType + if self._configMsg.updateConfigParamListener: + self._rtobj.removeConfigurationParamListener(confprmlistenertype_.ON_UPDATE_CONFIG_PARAM, + self._configMsg.updateConfigParamListener) + self._configMsg.updateConfigParamListener = None + + confsetlistenertype_ = OpenRTM_aist.ConfigurationSetListenerType + if self._configMsg.setConfigSetListener: + self._rtobj.removeConfigurationSetListener(confsetlistenertype_.ON_SET_CONFIG_SET, + self._configMsg.setConfigSetListener) + self._configMsg.setConfigSetListener = None + + if self._configMsg.addConfigSetListener: + self._rtobj.removeConfigurationSetListener(confsetlistenertype_.ON_ADD_CONFIG_SET, + self._configMsg.addConfigSetListener) + self._configMsg.addConfigSetListener = None + + confsetnamelistenertype_ = OpenRTM_aist.ConfigurationSetNameListenerType + if self._configMsg.updateConfigSetListener: + self._rtobj.removeConfigurationSetNameListener(confsetnamelistenertype_.ON_UPDATE_CONFIG_SET, + self._configMsg.updateConfigSetListener) + self._configMsg.updateConfigSetListener = None + + if self._configMsg.removeConfigSetListener: + self._rtobj.removeConfigurationSetNameListener(confsetnamelistenertype_.ON_REMOVE_CONFIG_SET, + self._configMsg.removeConfigSetListener) + self._configMsg.removeConfigSetListener = None + + if self._configMsg.activateConfigSetListener: + self._rtobj.removeConfigurationSetNameListener(confsetnamelistenertype_.ON_ACTIVATE_CONFIG_SET, + self._configMsg.activateConfigSetListener) + self._configMsg.activateConfigSetListener = None + + return + + ## + # @if jp + # @brief PostComponentActionListener class + # @else + # @brief PostComponentActionListener class + # @endif + # + + class CompStatMsg: + """ + """ + + #CompStatMsg(ComponentObserverConsumer& coc) + def __init__(self, coc): + self.activatedListener = None + self.deactivatedListener = None + self.resetListener = None + self.abortingListener = None + self.finalizeListener = None + self._coc = coc + return + + def __del__(self): + del self._coc + return + + # void onGeneric(const char* msgprefix, UniqueId ec_id, ReturnCode_t + # ret) + def onGeneric(self, msgprefix, ec_id, ret): + if ret == RTC.RTC_OK: + msg_ = msgprefix + msg_ += str(ec_id) + self._coc.updateStatus(OpenRTM.RTC_STATUS, msg_) + return + + # void onActivated(UniqueId ec_id, ReturnCode_t ret) + def onActivated(self, ec_id, ret): + self.onGeneric("ACTIVE:", ec_id, ret) + return + + # void onDeactivated(UniqueId ec_id, ReturnCode_t ret) + def onDeactivated(self, ec_id, ret): + self.onGeneric("INACTIVE:", ec_id, ret) + return + + # void onReset(UniqueId ec_id, ReturnCode_t ret) + def onReset(self, ec_id, ret): + self.onGeneric("INACTIVE:", ec_id, ret) + return + + # void onAborting(UniqueId ec_id, ReturnCode_t ret) + def onAborting(self, ec_id, ret): + self.onGeneric("ERROR:", ec_id, ret) + return + + # void onFinalize(UniqueId ec_id, ReturnCode_t ret) + def onFinalize(self, ec_id, ret): + self._coc.unsetHeartbeat() + self.onGeneric("FINALIZE:", ec_id, ret) + return + + ## + # @if jp + # @brief PortActionListener + # @else + # @brief PortActionListener + # @endif + # + class PortAction: + """ + """ + + #PortAction(ComponentObserverConsumer& coc) + def __init__(self, coc): + self.portAddListener = None + self.portRemoveListener = None + self.portConnectListener = None + self.portDisconnectListener = None + self._coc = coc + return + + def __del__(self): + del self._coc + return + + # void onGeneric(const char* _msg, const char* portname) + def onGeneric(self, _msg, portname): + msg_ = _msg + msg_ += portname + self._coc.updateStatus(OpenRTM.PORT_PROFILE, msg_) + return + + # void onAddPort(const ::RTC::PortProfile& pprof) + def onAddPort(self, pprof): + self.onGeneric("ADD:", str(pprof.name)) + return + + # void onRemovePort(const ::RTC::PortProfile& pprof) + def onRemovePort(self, pprof): + self.onGeneric("REMOVE:", str(pprof.name)) + return + + # void onConnect(const char* portname, + # ::RTC::ConnectorProfile& pprof, ReturnCode_t ret) + def onConnect(self, portname, pprof, ret): + if ret == RTC.RTC_OK: + self.onGeneric("CONNECT:", portname) + return + + # void onDisconnect(const char* portname, + # ::RTC::ConnectorProfile& pprof, ReturnCode_t ret) + def onDisconnect(self, portname, pprof, ret): + if ret == RTC.RTC_OK: + self.onGeneric("DISCONNECT:", portname) + return + + ## + # @if jp + # @brief DataPortデータ送信・受信アクションリスナ + # @else + # @brief DataPort's data send/receive action listener + # @endif + # + + class DataPortAction(OpenRTM_aist.ConnectorDataListener): + """ + """ + + def __init__(self, coc, msg, interval): + self._coc = coc + self._msg = msg + self._interval = interval + self._last = OpenRTM_aist.Time() + return + + def __call__(self, info, cdrdata): + curr = OpenRTM_aist.Time() + intvl = curr - self._last + + if intvl.getTime().toDouble() > self._interval.toDouble(): + self._last = curr + self._coc.updateStatus(OpenRTM.PORT_PROFILE, self._msg) + + return OpenRTM_aist.ConnectorListenerStatus.NO_CHANGE, cdrdata + + ## + # @if jp + # @brief ExecutionContextActionListener + # @else + # @brief ExecutionContextActionListener + # @endif + # + + class ECAction: + """ + """ + + #ECAction(ComponentObserverConsumer& coc) + def __init__(self, coc): + self.ecAttached = None + self.ecDetached = None + self.ecRatechanged = None + self.ecStartup = None + self.ecShutdown = None + self._coc = coc + return + + def __del__(self): + del self._coc + return + + # void onGeneric(const char* _msg, UniqueId ec_id) + def onGeneric(self, _msg, ec_id): + msg_ = _msg + str(ec_id) + self._coc.updateStatus(OpenRTM.EC_STATUS, msg_) + return + + # void onAttached(UniqueId ec_id) + def onAttached(self, ec_id): + self.onGeneric("ATTACHED:", ec_id) + return + + # void onDetached(UniqueId ec_id) + def onDetached(self, ec_id): + self.onGeneric("DETACHED:", ec_id) + return + + # void onRateChanged(UniqueId ec_id, ReturnCode_t ret) + def onRateChanged(self, ec_id, ret): + if ret == RTC.RTC_OK: + self.onGeneric("RATE_CHANGED:", ec_id) + return + + # void onStartup(UniqueId ec_id, ReturnCode_t ret) + def onStartup(self, ec_id, ret): + if ret == RTC.RTC_OK: + self.onGeneric("STARTUP:", ec_id) + return + + # void onShutdown(UniqueId ec_id, ReturnCode_t ret) + def onShutdown(self, ec_id, ret): + if ret == RTC.RTC_OK: + self.onGeneric("SHUTDOWN:", ec_id) + return + + ## + # @if jp + # @brief ConfigActionListener + # @else + # @brief ConfigActionListener + # @endif + # + + class ConfigAction: + """ + """ + + #ConfigAction(ComponentObserverConsumer& coc) + def __init__(self, coc): + self.updateConfigParamListener = None + self.setConfigSetListener = None + self.addConfigSetListener = None + self.updateConfigSetListener = None + self.removeConfigSetListener = None + self.activateConfigSetListener = None + self._coc = coc + + def __del__(self): + del self._coc + return + + # void updateConfigParam(const char* configsetname, + # const char* configparamname) + def updateConfigParam(self, configsetname, configparamname): + msg_ = "UPDATE_CONFIG_PARAM: " + msg_ += configsetname + msg_ += "." + msg_ += configparamname + self._coc.updateStatus(OpenRTM.CONFIGURATION, msg_) + return + + # void setConfigSet(const coil::Properties& config_set) + def setConfigSet(self, config_set): + msg_ = "SET_CONFIG_SET: " + msg_ += config_set.getName() + self._coc.updateStatus(OpenRTM.CONFIGURATION, msg_) + return + + # void addConfigSet(const coil::Properties& config_set) + def addConfigSet(self, config_set): + msg_ = "ADD_CONFIG_SET: " + msg_ += config_set.getName() + self._coc.updateStatus(OpenRTM.CONFIGURATION, msg_) + return + + # void updateConfigSet(const char* config_set_name) + def updateConfigSet(self, config_set_name): + msg_ = "UPDATE_CONFIG_SET: " + msg_ += config_set_name + self._coc.updateStatus(OpenRTM.CONFIGURATION, msg_) + return + + # void removeConfigSet(const char* config_set_name) + def removeConfigSet(self, config_set_name): + msg_ = "REMOVE_CONFIG_SET: " + msg_ += config_set_name + self._coc.updateStatus(OpenRTM.CONFIGURATION, msg_) + return + + # void activateConfigSet(const char* config_set_name) + def activateConfigSet(self, config_set_name): + msg_ = "ACTIVATE_CONFIG_SET: " + msg_ += config_set_name + self._coc.updateStatus(OpenRTM.CONFIGURATION, msg_) + return + + class ConnectorDataAction: + def __init__(self, coc, portname): + self.onBufferWriteListener = None + self._coc = coc + self._portname = portname + + def onBufferWrite(self, info, cdrdata): + param = self._portname + ":" + info + self._coc.updateStatus(OpenRTM.CONFIGURATION, msg_) + return - #ConfigAction(ComponentObserverConsumer& coc) - def __init__(self, coc): - self.updateConfigParamListener = None - self.setConfigSetListener = None - self.addConfigSetListener = None - self.updateConfigSetListener = None - self.removeConfigSetListener = None - self.activateConfigSetListener = None - self._coc = coc - - def __del__(self): - del self._coc - return - - #void updateConfigParam(const char* configsetname, - # const char* configparamname) - def updateConfigParam(self, configsetname, configparamname): - msg_ = "UPDATE_CONFIG_PARAM: " - msg_ += configsetname - msg_ += "." - msg_ += configparamname - self._coc.updateStatus(OpenRTM.CONFIGURATION, msg_) - return - - #void setConfigSet(const coil::Properties& config_set) - def setConfigSet(self, config_set): - msg_ = "SET_CONFIG_SET: " - msg_ += config_set.getName() - self._coc.updateStatus(OpenRTM.CONFIGURATION, msg_) - return - - #void addConfigSet(const coil::Properties& config_set) - def addConfigSet(self, config_set): - msg_ = "ADD_CONFIG_SET: " - msg_ += config_set.getName() - self._coc.updateStatus(OpenRTM.CONFIGURATION, msg_) - return - - #void updateConfigSet(const char* config_set_name) - def updateConfigSet(self, config_set_name): - msg_ = "UPDATE_CONFIG_SET: " - msg_ += config_set_name - self._coc.updateStatus(OpenRTM.CONFIGURATION, msg_) - return - - #void removeConfigSet(const char* config_set_name) - def removeConfigSet(self, config_set_name): - msg_ = "REMOVE_CONFIG_SET: " - msg_ += config_set_name - self._coc.updateStatus(OpenRTM.CONFIGURATION, msg_) - return - - #void activateConfigSet(const char* config_set_name) - def activateConfigSet(self, config_set_name): - msg_ = "ACTIVATE_CONFIG_SET: " - msg_ += config_set_name - self._coc.updateStatus(OpenRTM.CONFIGURATION, msg_) - return - - class ConnectorDataAction: - def __init__(self, coc, portname): - self.onBufferWriteListener = None - self._coc = coc - self._portname = portname - def onBufferWrite(self, info, cdrdata): - param = self._portname + ":" + info - self._coc.updateStatus(OpenRTM.CONFIGURATION, msg_) - return def ComponentObserverConsumerInit(mgr=None): - factory = OpenRTM_aist.SdoServiceConsumerFactory.instance() - factory.addFactory(OpenRTM.ComponentObserver._NP_RepositoryId, - ComponentObserverConsumer, - OpenRTM_aist.Delete) - return + factory = OpenRTM_aist.SdoServiceConsumerFactory.instance() + factory.addFactory(OpenRTM.ComponentObserver._NP_RepositoryId, + ComponentObserverConsumer) + return diff --git a/OpenRTM_aist/ext/sdo/observer/ComponentObserver.idl b/OpenRTM_aist/ext/sdo/observer/ComponentObserver_OpenRTM.idl similarity index 100% rename from OpenRTM_aist/ext/sdo/observer/ComponentObserver.idl rename to OpenRTM_aist/ext/sdo/observer/ComponentObserver_OpenRTM.idl diff --git a/OpenRTM_aist/ext/sdo/observer/__init__.py b/OpenRTM_aist/ext/sdo/observer/__init__.py index 932b7982..270be2a2 100644 --- a/OpenRTM_aist/ext/sdo/observer/__init__.py +++ b/OpenRTM_aist/ext/sdo/observer/__init__.py @@ -1 +1 @@ -# Empty file +# Empty file diff --git a/OpenRTM_aist/ext/sdo/observer/test/ComponentObserverProvider.py b/OpenRTM_aist/ext/sdo/observer/test/ComponentObserverProvider.py index 8b52d806..72843f91 100644 --- a/OpenRTM_aist/ext/sdo/observer/test/ComponentObserverProvider.py +++ b/OpenRTM_aist/ext/sdo/observer/test/ComponentObserverProvider.py @@ -1,5 +1,5 @@ -#!/usr/bin/env python -# -*- coding: euc-jp -*- +#!/usr/bin/env python +# -*- coding: utf-8 -*- ## # @file ComponentObserverProvider.py @@ -19,45 +19,49 @@ from omniORB import CORBA, PortableServer import RTC -import OpenRTM, OpenRTM__POA +import OpenRTM +import OpenRTM__POA import SDOPackage import OpenRTM_aist + class ComponentObserver_i(OpenRTM__POA.ComponentObserver): - def __init__(self): - pass + def __init__(self): + pass + + def update_status(self, status_kind, hint): + print("update_status: ", status_kind, ", ", hint) + return - def update_status(self, status_kind, hint): - print("update_status: ", status_kind, ", ", hint) - return def main(): - orb = CORBA.ORB_init(sys.argv) - poa = orb.resolve_initial_references("RootPOA") - poa._get_the_POAManager().activate() - naming = OpenRTM_aist.CorbaNaming(orb, "localhost") - servant = ComponentObserver_i() - oid = poa.servant_to_id(servant) - provider = poa.id_to_reference(oid) - - rtc = naming.resolve("COCTestRTC0.rtc")._narrow(RTC.RTObject) - config = rtc.get_configuration() - properties = [OpenRTM_aist.NVUtil.newNV("heartbeat.enable","YES"), - OpenRTM_aist.NVUtil.newNV("heartbeat.interval","10"), - OpenRTM_aist.NVUtil.newNV("observed_status","ALL")] - - id = OpenRTM_aist.toTypename(servant) - sprof = SDOPackage.ServiceProfile("test_id", id, - properties, provider) - - ret = config.add_service_profile(sprof) - flag = True - print("If you exit program, please input 'q'.") - sys.stdin.readline() - ret = config.remove_service_profile("test_id") - print("test program end. ret : ", ret) - return - + orb = CORBA.ORB_init(sys.argv) + poa = orb.resolve_initial_references("RootPOA") + poa._get_the_POAManager().activate() + naming = OpenRTM_aist.CorbaNaming(orb, "localhost") + servant = ComponentObserver_i() + oid = poa.servant_to_id(servant) + provider = poa.id_to_reference(oid) + + rtc = naming.resolve("COCTestRTC0.rtc")._narrow(RTC.RTObject) + config = rtc.get_configuration() + properties = [OpenRTM_aist.NVUtil.newNV("heartbeat.enable", "YES"), + OpenRTM_aist.NVUtil.newNV("heartbeat.interval", "10"), + OpenRTM_aist.NVUtil.newNV("observed_status", "ALL")] + + id = OpenRTM_aist.toTypename(servant) + sprof = SDOPackage.ServiceProfile("test_id", id, + properties, provider) + + ret = config.add_service_profile(sprof) + flag = True + print("If you exit program, please input 'q'.") + sys.stdin.readline() + ret = config.remove_service_profile("test_id") + print("test program end. ret : ", ret) + return + + ############### test ################# if __name__ == '__main__': - main() + main() diff --git a/OpenRTM_aist/ext/sdo/observer/test/__init__.py b/OpenRTM_aist/ext/sdo/observer/test/__init__.py index 932b7982..270be2a2 100644 --- a/OpenRTM_aist/ext/sdo/observer/test/__init__.py +++ b/OpenRTM_aist/ext/sdo/observer/test/__init__.py @@ -1 +1 @@ -# Empty file +# Empty file diff --git a/OpenRTM_aist/ext/sdo/observer/test/test_ComponentObserverConsumer.py b/OpenRTM_aist/ext/sdo/observer/test/test_ComponentObserverConsumer.py index 8d8395ce..ce035abc 100644 --- a/OpenRTM_aist/ext/sdo/observer/test/test_ComponentObserverConsumer.py +++ b/OpenRTM_aist/ext/sdo/observer/test/test_ComponentObserverConsumer.py @@ -1,5 +1,5 @@ -#!/usr/bin/env python -# -*- coding: euc-jp -*- +#!/usr/bin/env python +# -*- coding: utf-8 -*- ## # @file test_ComponentObserverConsumer.py @@ -15,192 +15,191 @@ # All rights reserved. # -import sys -sys.path.insert(1,"../") - -import unittest -import time - -from omniORB import CORBA, PortableServer -import RTC -import OpenRTM, OpenRTM__POA -import SDOPackage +import OpenRTM__POA +import OpenRTM +from ComponentObserverConsumer import * import OpenRTM_aist +import SDOPackage +import RTC +from omniORB import CORBA, PortableServer +import time +import unittest +import sys +sys.path.insert(1, "../") -from ComponentObserverConsumer import * class ComponentObserver_i(OpenRTM__POA.ComponentObserver): - def __init__(self): - pass + def __init__(self): + pass - def update_status(self, status_kind, hint): - print("update_status: ", status_kind, ", ", hint) - return + def update_status(self, status_kind, hint): + print("update_status: ", status_kind, ", ", hint) + return class MockRTC(OpenRTM_aist.RTObject_impl): - def __init__(self): - self._orb = CORBA.ORB_init() - self._poa = self._orb.resolve_initial_references("RootPOA") - OpenRTM_aist.RTObject_impl.__init__(self, orb=self._orb, poa=self._poa) - pass + def __init__(self): + self._orb = CORBA.ORB_init() + self._poa = self._orb.resolve_initial_references("RootPOA") + OpenRTM_aist.RTObject_impl.__init__(self, orb=self._orb, poa=self._poa) + pass ## # @if jp # @else # @endif # -class TestComponentObserverConsumer(unittest.TestCase): - """ - """ - - def setUp(self): - self._orb = CORBA.ORB_init(sys.argv) - self._poa = self._orb.resolve_initial_references("RootPOA") - self._poa._get_the_POAManager().activate() - self.coc = ComponentObserverConsumer() - servant_ = ComponentObserver_i() - mgr_ = OpenRTM_aist.Manager.instance() - oid_ = mgr_.getPOA().servant_to_id(servant_) - self._provider = mgr_.getPOA().id_to_reference(oid_) - self._mock = MockRTC() - self._properties = [OpenRTM_aist.NVUtil.newNV("heartbeat.enable","YES"), - OpenRTM_aist.NVUtil.newNV("heartbeat.interval","0.1"), - OpenRTM_aist.NVUtil.newNV("observed_status","ALL")] - self._sprof = SDOPackage.ServiceProfile("test_id", "interface_type", - self._properties, self._provider) - self.coc.init(self._mock, self._sprof) - return - - def tearDown(self): - self.coc.finalize() - del self.coc - self._mock.exit() - time.sleep(0.1) - OpenRTM_aist.Manager.instance().shutdownManager() - return - - - def test_reinit(self): - self.assertEqual(self.coc.reinit(self._sprof), True) - return - - - def test_getProfile(self): - self.coc.getProfile() - return - - - def test_finalize(self): - self.coc.finalize() - return - - - def test_updateStatus(self): - self.coc.updateStatus(OpenRTM.COMPONENT_PROFILE, "update Component profile") - return - - - def test_toString(self): - self.assertEqual("COMPONENT_PROFILE",self.coc.toString(OpenRTM.COMPONENT_PROFILE)) - self.assertEqual("RTC_STATUS",self.coc.toString(OpenRTM.RTC_STATUS)) - self.assertEqual("EC_STATUS",self.coc.toString(OpenRTM.EC_STATUS)) - self.assertEqual("PORT_PROFILE",self.coc.toString(OpenRTM.PORT_PROFILE)) - self.assertEqual("CONFIGURATION",self.coc.toString(OpenRTM.CONFIGURATION)) - self.assertEqual("HEARTBEAT",self.coc.toString(OpenRTM.HEARTBEAT)) - return - - - def test_setListeners(self): - prop = OpenRTM_aist.Properties() - prop.setProperty("observed_status", - "component_profile, rtc_status, port_profile, \ - ec_status, port_profile , configuration") - self.coc.setListeners(prop) - return - - - def setfunc(self): - print("setfunc") - return - - def unsetfunc(self): - print("unsetfunc") - return - - def test_switchListeners(self): - self.coc.switchListeners(True, [True], 0, self.setfunc, self. unsetfunc) - self.coc.switchListeners(True, [False], 0, self.setfunc, self. unsetfunc) - self.coc.switchListeners(False, [True], 0, self.setfunc, self. unsetfunc) - self.coc.switchListeners(False, [False], 0, self.setfunc, self. unsetfunc) - return - def test_heartbeat(self): - self.coc.heartbeat() - return - - - def test_setHeartbeat(self): - prop = OpenRTM_aist.Properties() - prop.setProperty("heartbeat.enable","NO") - prop.setProperty("heartbeat.interval","1.0") - self.coc.setHeartbeat(prop) - prop = OpenRTM_aist.Properties() - prop.setProperty("heartbeat.enable","YES") - prop.setProperty("heartbeat.interval","0.01") - self.coc.setHeartbeat(prop) - prop = OpenRTM_aist.Properties() - prop.setProperty("heartbeat.enable","YES") - self.coc.setHeartbeat(prop) - return - - - def test_unsetHeartbeat(self): - self.coc.unsetHeartbeat() - return - - - def test_setComponentStatusListeners(self): - self.coc.setComponentStatusListeners() - return - - - def test_unsetComponentStatusListeners(self): - self.coc.unsetComponentStatusListeners() - return - - - def test_setPortProfileListeners(self): - self.coc.setPortProfileListeners() - return - - - def test_unsetPortProfileListeners(self): - self.coc.unsetPortProfileListeners() - return - - - def test_setExecutionContextListeners(self): - self.coc.setExecutionContextListeners() - return - - - def test_unsetExecutionContextListeners(self): - self.coc.unsetExecutionContextListeners() - return - - - def test_setConfigurationListeners(self): - self.coc.setConfigurationListeners() - return - - - def test_unsetConfigurationListeners(self): - self.coc.unsetConfigurationListeners() - return +class TestComponentObserverConsumer(unittest.TestCase): + """ + """ + + def setUp(self): + self._orb = CORBA.ORB_init(sys.argv) + self._poa = self._orb.resolve_initial_references("RootPOA") + self._poa._get_the_POAManager().activate() + self.coc = ComponentObserverConsumer() + servant_ = ComponentObserver_i() + mgr_ = OpenRTM_aist.Manager.instance() + oid_ = mgr_.getPOA().servant_to_id(servant_) + self._provider = mgr_.getPOA().id_to_reference(oid_) + self._mock = MockRTC() + self._properties = [OpenRTM_aist.NVUtil.newNV("heartbeat.enable", "YES"), + OpenRTM_aist.NVUtil.newNV( + "heartbeat.interval", "0.1"), + OpenRTM_aist.NVUtil.newNV("observed_status", "ALL")] + self._sprof = SDOPackage.ServiceProfile("test_id", "interface_type", + self._properties, self._provider) + self.coc.init(self._mock, self._sprof) + return + + def tearDown(self): + self.coc.finalize() + del self.coc + self._mock.exit() + time.sleep(0.1) + OpenRTM_aist.Manager.instance().shutdownManager() + return + + def test_reinit(self): + self.assertEqual(self.coc.reinit(self._sprof), True) + return + + def test_getProfile(self): + self.coc.getProfile() + return + + def test_finalize(self): + self.coc.finalize() + return + + def test_updateStatus(self): + self.coc.updateStatus( + OpenRTM.COMPONENT_PROFILE, + "update Component profile") + return + + def test_toString(self): + self.assertEqual( + "COMPONENT_PROFILE", + self.coc.toString( + OpenRTM.COMPONENT_PROFILE)) + self.assertEqual("RTC_STATUS", self.coc.toString(OpenRTM.RTC_STATUS)) + self.assertEqual("EC_STATUS", self.coc.toString(OpenRTM.EC_STATUS)) + self.assertEqual( + "PORT_PROFILE", + self.coc.toString( + OpenRTM.PORT_PROFILE)) + self.assertEqual( + "CONFIGURATION", + self.coc.toString( + OpenRTM.CONFIGURATION)) + self.assertEqual("HEARTBEAT", self.coc.toString(OpenRTM.HEARTBEAT)) + return + + def test_setListeners(self): + prop = OpenRTM_aist.Properties() + prop.setProperty("observed_status", + "component_profile, rtc_status, port_profile, \ + ec_status, port_profile , configuration") + self.coc.setListeners(prop) + return + + def setfunc(self): + print("setfunc") + return + + def unsetfunc(self): + print("unsetfunc") + return + + def test_switchListeners(self): + self.coc.switchListeners( + True, [True], 0, self.setfunc, self. unsetfunc) + self.coc.switchListeners( + True, [False], 0, self.setfunc, self. unsetfunc) + self.coc.switchListeners( + False, [True], 0, self.setfunc, self. unsetfunc) + self.coc.switchListeners( + False, [False], 0, self.setfunc, self. unsetfunc) + return + + def test_heartbeat(self): + self.coc.heartbeat() + return + + def test_setHeartbeat(self): + prop = OpenRTM_aist.Properties() + prop.setProperty("heartbeat.enable", "NO") + prop.setProperty("heartbeat.interval", "1.0") + self.coc.setHeartbeat(prop) + prop = OpenRTM_aist.Properties() + prop.setProperty("heartbeat.enable", "YES") + prop.setProperty("heartbeat.interval", "0.01") + self.coc.setHeartbeat(prop) + prop = OpenRTM_aist.Properties() + prop.setProperty("heartbeat.enable", "YES") + self.coc.setHeartbeat(prop) + return + + def test_unsetHeartbeat(self): + self.coc.unsetHeartbeat() + return + + def test_setComponentStatusListeners(self): + self.coc.setComponentStatusListeners() + return + + def test_unsetComponentStatusListeners(self): + self.coc.unsetComponentStatusListeners() + return + + def test_setPortProfileListeners(self): + self.coc.setPortProfileListeners() + return + + def test_unsetPortProfileListeners(self): + self.coc.unsetPortProfileListeners() + return + + def test_setExecutionContextListeners(self): + self.coc.setExecutionContextListeners() + return + + def test_unsetExecutionContextListeners(self): + self.coc.unsetExecutionContextListeners() + return + + def test_setConfigurationListeners(self): + self.coc.setConfigurationListeners() + return + + def test_unsetConfigurationListeners(self): + self.coc.unsetConfigurationListeners() + return ############### test ################# if __name__ == '__main__': - unittest.main() + unittest.main() diff --git a/OpenRTM_aist/ext/ssl/SSLTransport.py b/OpenRTM_aist/ext/ssl/SSLTransport.py index 5c86a467..4ebcd207 100644 --- a/OpenRTM_aist/ext/ssl/SSLTransport.py +++ b/OpenRTM_aist/ext/ssl/SSLTransport.py @@ -1,5 +1,5 @@ -#!/usr/bin/env python -# -*- coding: euc-jp -*- +#!/usr/bin/env python +# -*- coding: utf-8 -*- ## @@ -14,35 +14,30 @@ import OpenRTM_aist - def SSLTransportInit(manager): - #os.environ['ORBtraceLevel'] = '25' #os.environ['ORBendPoint'] = 'giop:ssl::' #os.environ['ORBsslVerifyMode'] = "none" - prop = manager.getConfig() - certificate_authority_file = prop.getProperty("corba.ssl.certificate_authority_file") + certificate_authority_file = prop.getProperty( + "corba.ssl.certificate_authority_file") key_file = prop.getProperty("corba.ssl.key_file") key_file_password = prop.getProperty("corba.ssl.key_file_password") corba_args = prop.getProperty("corba.args") corba_args += " -ORBendPoint giop:ssl::" - if not OpenRTM_aist.toBool(prop.getProperty("manager.is_master"), "YES", "NO", True): - if len(prop.getProperty("corba.endpoints")) == 0: - if len(prop.getProperty("corba.endpoint")) == 0: - if str(prop.getProperty("corba.args")).find("-ORBendPoint") == -1: + if not OpenRTM_aist.toBool(prop.getProperty( + "manager.is_main"), "YES", "NO", True): + if not prop.getProperty("corba.endpoints"): + if not prop.getProperty("corba.endpoint"): + if str(prop.getProperty("corba.args")).find( + "-ORBendPoint") == -1: corba_args += " -ORBendPoint giop:tcp::" - - prop.setProperty("corba.args",corba_args) + prop.setProperty("corba.args", corba_args) - - - sslTP.certificate_authority_file(certificate_authority_file) sslTP.key_file(key_file) sslTP.key_file_password(key_file_password) - \ No newline at end of file diff --git a/OpenRTM_aist/ext/ssl/__init__.py b/OpenRTM_aist/ext/ssl/__init__.py index 932b7982..270be2a2 100644 --- a/OpenRTM_aist/ext/ssl/__init__.py +++ b/OpenRTM_aist/ext/ssl/__init__.py @@ -1 +1 @@ -# Empty file +# Empty file diff --git a/OpenRTM_aist/ext/ssl/test/test_SSLTransport.py b/OpenRTM_aist/ext/ssl/test/test_SSLTransport.py index 9c8868c3..5f581f49 100644 --- a/OpenRTM_aist/ext/ssl/test/test_SSLTransport.py +++ b/OpenRTM_aist/ext/ssl/test/test_SSLTransport.py @@ -1,46 +1,43 @@ -#!/usr/bin/env python -# -*- coding: euc-jp -*- +#!/usr/bin/env python +# -*- coding: utf-8 -*- # # \file test_SSLTrasport.py -# \brief +# \brief # \date $Date: $ # \author Nobuhiko Miyamoto # +import threading +import os +import multiprocessing +import RTC +import OpenRTM_aist +import time import sys -sys.path.insert(1,"../") +sys.path.insert(1, "../") try: import unittest2 as unittest except (ImportError): import unittest -import time #from Manager import * -import OpenRTM_aist -import RTC -import multiprocessing -import os -import threading - def RunOutPort(q): - + argv = sys.argv[:] #argv.extend(['-o', 'corba.endpoint::2810']) - + manager = OpenRTM_aist.Manager.init(argv) manager.activateManager() - _d_out = RTC.TimedLong(RTC.Time(0,0),0) + _d_out = RTC.TimedLong(RTC.Time(0, 0), 0) _outOut = OpenRTM_aist.OutPort("out", _d_out) prop = OpenRTM_aist.Properties() _outOut.init(prop) - - """orb = manager.getORB() poa = orb.resolve_initial_references("omniINSPOA") @@ -50,80 +47,67 @@ def RunOutPort(q): manager._namingManager.bindPortObject("test", _outOut) - q.get() _d_out.data = 100 _outOut.write() q.get() - - - + manager.shutdown() class TestSSLTransport(unittest.TestCase): - - def setUp(self): - self.queue = multiprocessing.Queue() - - sys.argv.extend(['-o', 'manager.preload.modules:SSLTransport.py']) - sys.argv.extend(['-o', 'manager.modules.load_path:./,../']) - sys.argv.extend(['-o', 'corba.ssl.certificate_authority_file:root.crt']) - sys.argv.extend(['-o', 'corba.ssl.key_file:server.pem']) - sys.argv.extend(['-o', 'corba.ssl.key_file_password:password']) - os.environ['ORBsslVerifyMode'] = "none" - self.outport_process = multiprocessing.Process(target=RunOutPort, args=(self.queue,)) - self.outport_process.start() - - - time.sleep(1) - os.environ['ORBtraceLevel'] = '25' - - - self.manager = OpenRTM_aist.Manager.init(sys.argv) - self.manager.activateManager() - self._d_in = RTC.TimedLong(RTC.Time(0,0),0) - self._inIn = OpenRTM_aist.InPort("in", self._d_in) - prop = OpenRTM_aist.Properties() - self._inIn.init(prop) - self.inport_obj = self._inIn.getPortRef() - + def setUp(self): + self.queue = multiprocessing.Queue() - orb = self.manager.getORB() - #outport_name = "corbaloc:iiop:localhost:2810/test" - outport_name = "corbaname::localhost:2809/NameService#test" - oobj = orb.string_to_object(outport_name) - self.outport_obj = oobj._narrow(RTC.PortService) - - + sys.argv.extend(['-o', 'manager.preload.modules:SSLTransport.py']) + sys.argv.extend(['-o', 'manager.modules.load_path:./,../']) + sys.argv.extend( + ['-o', 'corba.ssl.certificate_authority_file:root.crt']) + sys.argv.extend(['-o', 'corba.ssl.key_file:server.pem']) + sys.argv.extend(['-o', 'corba.ssl.key_file_password:password']) + os.environ['ORBsslVerifyMode'] = "none" + self.outport_process = multiprocessing.Process( + target=RunOutPort, args=(self.queue,)) + self.outport_process.start() - def tearDown(self): - self.manager.shutdownManager() - self.queue.put("") + time.sleep(1) + os.environ['ORBtraceLevel'] = '25' - def test_Connect(self): - - prop = OpenRTM_aist.Properties() - ret = OpenRTM_aist.connect("con1",prop,self.inport_obj,self.outport_obj) - - self.queue.put("") + self.manager = OpenRTM_aist.Manager.init(sys.argv) + self.manager.activateManager() + self._d_in = RTC.TimedLong(RTC.Time(0, 0), 0) + self._inIn = OpenRTM_aist.InPort("in", self._d_in) + prop = OpenRTM_aist.Properties() + self._inIn.init(prop) + self.inport_obj = self._inIn.getPortRef() + + orb = self.manager.getORB() + #outport_name = "corbaloc:iiop:localhost:2810/test" + outport_name = "corbaname::localhost:2809/NameService#test" + oobj = orb.string_to_object(outport_name) + self.outport_obj = oobj._narrow(RTC.PortService) + + def tearDown(self): + self.manager.shutdownManager() + self.queue.put("") - #ret = self._inIn.isNew() - #data = self._inIn.read() - - + def test_Connect(self): - #self.outport_obj.disconnect_all() + prop = OpenRTM_aist.Properties() + ret = OpenRTM_aist.connect( + "con1", prop, self.inport_obj, self.outport_obj) - + self.queue.put("") + #ret = self._inIn.isNew() + #data = self._inIn.read() + # self.outport_obj.disconnect_all() - ############### test ################# if __name__ == '__main__': - unittest.main() + unittest.main() diff --git a/OpenRTM_aist/ext/transport/OpenSplice/OpenSpliceInPort.py b/OpenRTM_aist/ext/transport/OpenSplice/OpenSpliceInPort.py new file mode 100644 index 00000000..81c519cd --- /dev/null +++ b/OpenRTM_aist/ext/transport/OpenSplice/OpenSpliceInPort.py @@ -0,0 +1,393 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- + +## +# @file OpenSpliceInPort.py +# @brief OpenSplice OutPort class +# @date $Date$ +# @author Nobuhiko Miyamoto +# +# Copyright (C) 2019 +# Noriaki Ando +# Robot Innovation Research Center, +# National Institute of +# Advanced Industrial Science and Technology (AIST), Japan +# All rights reserved. +# +# $Id$ +# + +import OpenRTM_aist +from OpenSpliceTopicManager import OpenSpliceTopicManager +import OpenSpliceMessageInfo +import RTC +import dds +import threading + + +## +# @if jp +# @class OpenSpliceInPort +# @brief OpenSplice Subscriberに対応するクラス +# InPortProviderオブジェクトとして使用する +# +# @else +# @class OpenSpliceInPort +# @brief +# +# +# @endif +class OpenSpliceInPort(OpenRTM_aist.InPortProvider): + """ + """ + + ## + # @if jp + # @brief コンストラクタ + # + # コンストラクタ + # ポートプロパティに以下の項目を設定する。 + # - インターフェースタイプ : opensplice + # - データフロータイプ : Push + # + # @param self + # + # @else + # @brief Constructor + # + # Constructor + # Set the following items to port properties + # - Interface type : CORBA_Any + # - Data flow type : Push, Pull + # + # @param self + # + # @endif + # + def __init__(self): + OpenRTM_aist.InPortProvider.__init__(self) + + # PortProfile setting + self.setInterfaceType("opensplice") + + self._profile = None + self._listeners = None + + self._dataType = RTC.TimedLong._NP_RepositoryId + self._topic = "chatter" + self._reader = None + + self._mutex = threading.RLock() + + ## + # @if jp + # @brief デストラクタ + # + # デストラクタ + # + # @param self + # + # @else + # @brief Destructor + # + # Destructor + # + # @param self + # + # @endif + # + + def __del__(self): + return + + ## + # @if jp + # @brief 終了処理 + # + # @param self + # + # @else + # @brief + # + # @param self + # + # @endif + # + + def exit(self): + self._rtcout.RTC_PARANOID("exit()") + if self._reader: + self._reader.close() + self._rtcout.RTC_VERBOSE("remove reader") + + ## + # @if jp + # @brief 初期化 + # + # @param self + # @param prop 接続設定 + # marshaling_type シリアライザの種類 デフォルト:opensplice + # topic トピック名 デフォルト chatter + # + # @else + # @brief + # + # @param self + # @param prop + # + # @endif + # + # virtual void init(coil::Properties& prop); + + def init(self, prop): + self._rtcout.RTC_PARANOID("init()") + + if not prop.propertyNames(): + self._rtcout.RTC_DEBUG("Property is empty.") + return + + self._properties = prop + + qosxml = prop.getProperty("opensplice.QOSXML") + qosprofile = prop.getProperty("opensplice.QOSPrfile") + self._topicmgr = OpenSpliceTopicManager.instance(qosxml, qosprofile) + + self._dataType = prop.getProperty("data_type", self._dataType) + + self._topic = prop.getProperty("opensplice.topic", "chatter") + + topic = self._topicmgr.createTopic(self._dataType, self._topic) + + self._rtcout.RTC_VERBOSE("data type: %s", self._dataType) + self._rtcout.RTC_VERBOSE("topic name: %s", self._topic) + + self._reader = self._topicmgr.createReader(topic, SubListener(self)) + + # virtual void setBuffer(BufferBase* buffer); + + def setBuffer(self, buffer): + return + + ## + # @if jp + # @brief コネクタリスナの設定 + # + # @param info 接続情報 + # @param listeners リスナ + # + # @else + # @brief + # + # @param info + # @param listeners + # + # @endif + # + # void setListener(ConnectorInfo& info, + # ConnectorListeners* listeners); + def setListener(self, info, listeners): + self._profile = info + self._listeners = listeners + return + + ## + # @if jp + # @brief バッファにデータを書き込む + # + # 設定されたバッファにデータを書き込む。 + # + # @param data 書込対象データ + # + # @else + # @brief Write data into the buffer + # + # Write data into the specified buffer. + # + # @param data The target data for writing + # + # @endif + # + + def put(self, data): + guard = OpenRTM_aist.Guard.ScopedLock(self._mutex) + try: + self._rtcout.RTC_PARANOID("OpenSpliceInPort.put()") + if not self._connector: + self.onReceiverError(data) + return OpenRTM.PORT_ERROR + + data = self.onReceived(data) + + ret = self._connector.write(data) + + self.convertReturn(ret, data) + + except BaseException: + self._rtcout.RTC_TRACE(OpenRTM_aist.Logger.print_exception()) + + def convertReturn(self, status, data): + if status == OpenRTM_aist.BufferStatus.BUFFER_OK: + self.onBufferWrite(data) + return + + elif status == OpenRTM_aist.BufferStatus.BUFFER_ERROR: + self.onReceiverError(data) + return + + elif status == OpenRTM_aist.BufferStatus.BUFFER_FULL: + data = self.onBufferFull(data) + self.onReceiverFull(data) + return + + elif status == OpenRTM_aist.BufferStatus.BUFFER_EMPTY: + return + + elif status == OpenRTM_aist.BufferStatus.PRECONDITION_NOT_MET: + self.onReceiverError(data) + return + + elif status == OpenRTM_aist.BufferStatus.TIMEOUT: + data = self.onBufferWriteTimeout(data) + self.onReceiverTimeout(data) + return + + else: + self.onReceiverError(data) + return + + ## + # @brief Connector data listener functions + # + # inline void onBufferWrite(const cdrMemoryStream& data) + + def onBufferWrite(self, data): + if self._listeners is not None and self._profile is not None: + _, data = self._listeners.notifyData( + OpenRTM_aist.ConnectorDataListenerType.ON_BUFFER_WRITE, self._profile, data) + return data + + # inline void onBufferFull(const cdrMemoryStream& data) + + def onBufferFull(self, data): + if self._listeners is not None and self._profile is not None: + _, data = self._listeners.notifyData( + OpenRTM_aist.ConnectorDataListenerType.ON_BUFFER_FULL, self._profile, data) + return data + + # inline void onBufferWriteTimeout(const cdrMemoryStream& data) + + def onBufferWriteTimeout(self, data): + if self._listeners is not None and self._profile is not None: + _, data = self._listeners.notifyData( + OpenRTM_aist.ConnectorDataListenerType.ON_BUFFER_WRITE_TIMEOUT, self._profile, data) + return data + + # inline void onBufferWriteOverwrite(const cdrMemoryStream& data) + def onBufferWriteOverwrite(self, data): + if self._listeners is not None and self._profile is not None: + _, data = self._listeners.notifyData( + OpenRTM_aist.ConnectorDataListenerType.ON_BUFFER_OVERWRITE, self._profile, data) + return data + + # inline void onReceived(const cdrMemoryStream& data) + + def onReceived(self, data): + if self._listeners is not None and self._profile is not None: + _, data = self._listeners.notifyData( + OpenRTM_aist.ConnectorDataListenerType.ON_RECEIVED, self._profile, data) + return data + + # inline void onReceiverFull(const cdrMemoryStream& data) + + def onReceiverFull(self, data): + if self._listeners is not None and self._profile is not None: + _, data = self._listeners.notifyData( + OpenRTM_aist.ConnectorDataListenerType.ON_RECEIVER_FULL, self._profile, data) + return data + + # inline void onReceiverTimeout(const cdrMemoryStream& data) + + def onReceiverTimeout(self, data): + if self._listeners is not None and self._profile is not None: + _, data = self._listeners.notifyData( + OpenRTM_aist.ConnectorDataListenerType.ON_RECEIVER_TIMEOUT, self._profile, data) + return data + + # inline void onReceiverError(const cdrMemoryStream& data) + + def onReceiverError(self, data): + if self._listeners is not None and self._profile is not None: + _, data = self._listeners.notifyData( + OpenRTM_aist.ConnectorDataListenerType.ON_RECEIVER_ERROR, self._profile, data) + return data + +## +# @if jp +# @class SubListener +# @brief OpenSplice Subscriberのデータ受信時のリスナ +# +# +# @else +# @class SubListener +# @brief +# +# +# @endif + + +class SubListener(dds.Listener): + ## + # @if jp + # @brief コンストラクタ + # + # @param self + # @param sub OpenSpliceInPort + # + # @else + # @brief Constructor + # + # @param self + # @param sub + # + # @endif + # + def __init__(self, subscriber): + dds.Listener.__init__(self) + self._sub = subscriber + + ## + # @if jp + # @brief 受信処理 + # + # @param self + # @param entity + # + # @else + # @brief + # + # @param self + # @param entity + # + # @endif + # + def on_data_available(self, entity): + l = entity.read(10) + for (sd, _) in l: + self._sub.put(sd) + + +## +# @if jp +# @brief モジュール登録関数 +# +# +# @else +# @brief +# +# +# @endif +# +def OpenSpliceInPortInit(): + factory = OpenRTM_aist.InPortProviderFactory.instance() + factory.addFactory("opensplice", + OpenSpliceInPort) diff --git a/OpenRTM_aist/ext/transport/OpenSplice/OpenSpliceMessageInfo.py b/OpenRTM_aist/ext/transport/OpenSplice/OpenSpliceMessageInfo.py new file mode 100644 index 00000000..19f5d2e7 --- /dev/null +++ b/OpenRTM_aist/ext/transport/OpenSplice/OpenSpliceMessageInfo.py @@ -0,0 +1,340 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- + +## +# @file OpenSpliceMessageInfo.py +# @brief OpenSplice Message Info class +# @date $Date$ +# @author Nobuhiko Miyamoto +# +# Copyright (C) 2019 +# Noriaki Ando +# Robot Innovation Research Center, +# National Institute of +# Advanced Industrial Science and Technology (AIST), Japan +# All rights reserved. +# +# $Id$ +# + +import OpenRTM_aist + +## +# @if jp +# @class OpenSpliceMessageInfoBase +# @brief OpenSpliceメッセージ情報格納オブジェクトの基底クラス +# OpenSpliceデータ型名、IDLファイルパスを登録する +# +# @else +# @class OpenSpliceOutPort +# @brief +# +# +# @endif + + +class OpenSpliceMessageInfoBase(object): + ## + # @if jp + # @brief コンストラクタ + # + # コンストラクタ + # + # @param self + # + # @else + # @brief Constructor + # + # @param self + # + # @endif + def __init__(self): + pass + ## + # @if jp + # @brief デストラクタ + # + # デストラクタ + # + # @param self + # + # @else + # @brief Destructor + # + # Destructor + # + # @param self + # + # @endif + # + + def __del__(self): + pass + + ## + # @if jp + # @brief データの型名を取得 + # + # @param self + # @return 型名 + # + # @else + # @brief + # + # + # @param self + # @return + # + # @endif + # + def datatype(self): + return "" + + ## + # @if jp + # @brief IDLファイルのパスを取得 + # + # @param self + # @return IDLファイルのパス + # + # @else + # @brief + # + # + # @param self + # @return + # + # @endif + # + def idlFile(self): + return "" + + +## +# @if jp +# @class OpenSpliceMessageInfo +# @brief メッセージの情報格納クラス +# +# +# @else +# @class OpenSpliceMessageInfo +# @brief +# +# +# @endif +class OpenSpliceMessageInfo(OpenSpliceMessageInfoBase): + """ + """ + ## + # @if jp + # @brief コンストラクタ + # + # コンストラクタ + # + # @param self + # + # @else + # @brief Constructor + # + # @param self + # + # @endif + + def __init__(self, datatype, idlfile): + super(OpenSpliceMessageInfo, self).__init__() + self._datatype = datatype + self._idlfile = idlfile + ## + # @if jp + # @brief デストラクタ + # + # + # @param self + # + # @else + # + # @brief self + # + # @endif + + def __del__(self): + pass + ## + # @if jp + # @brief メッセージの型名を取得 + # + # @param self + # @return 型名 + # + # @else + # @brief + # + # + # @param self + # @return + # + # @endif + # + + def datatype(self): + return self._datatype + ## + # @if jp + # @brief IDLファイルのパスを取得 + # + # @param self + # @return IDLファイルのパス + # + # @else + # @brief + # + # + # @param self + # @return + # + # @endif + # + + def idlFile(self): + return self._idlfile + + +opensplicemessageinfolist = None + + +## +# @if jp +# @class OpenSpliceMessageInfoList +# @brief OpenSpliceメッセージ情報を格納するリスト +# +# @else +# @class OpenSpliceMessageInfoList +# @brief +# +# +# @endif +class OpenSpliceMessageInfoList: + ## + # @if jp + # @brief コンストラクタ + # + # コンストラクタ + # + # @param self + # + # @else + # @brief Constructor + # + # @param self + # + # @endif + def __init__(self): + self._data = {} + + ## + # @if jp + # @brief デストラクタ + # + # デストラクタ + # + # @param self + # + # @else + # @brief Destructor + # + # Destructor + # + # @param self + # + # @endif + # + def __del__(self): + pass + + ## + # @if jp + # @brief インスタンス取得 + # + # + # @return インスタンス + # + # @else + # @brief + # + # + # @return + # + # @endif + # + def instance(): + global opensplicemessageinfolist + + if opensplicemessageinfolist is None: + opensplicemessageinfolist = OpenSpliceMessageInfoList() + + return opensplicemessageinfolist + + instance = staticmethod(instance) + + ## + # @if jp + # @brief ROS2MessageInfoの追加 + # + # @param self + # @param id 名前 + # @param info ROS2MessageInfo + # + # @else + # @brief + # + # @param self + # @param id + # @param info + # + # @endif + # + def addInfo(self, id, info): + self._data[id] = info + + ## + # @if jp + # @brief ROS2MessageInfoの削除 + # + # @param self + # @param id 名前 + # @return 削除に成功した場合はTrue + # + # @else + # @brief + # + # @param self + # @param id + # @return + # + # @endif + # + def removeInfo(self, id): + if id in self._data: + del self._data[id] + return True + return False + + ## + # @if jp + # @brief 指定名のROS2MessageInfoの取得 + # + # @param id 名前 + # @return ROS2MessageInfo + # + # @else + # @brief + # + # @param id + # @return + # + # @endif + # + def getInfo(self, id): + if id in self._data: + return self._data[id] + return None diff --git a/OpenRTM_aist/ext/transport/OpenSplice/OpenSpliceOutPort.py b/OpenRTM_aist/ext/transport/OpenSplice/OpenSpliceOutPort.py new file mode 100644 index 00000000..1a958f55 --- /dev/null +++ b/OpenRTM_aist/ext/transport/OpenSplice/OpenSpliceOutPort.py @@ -0,0 +1,270 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- + +## +# @file OpenSpliceOutPort.py +# @brief OpenSplice OutPort class +# @date $Date$ +# @author Nobuhiko Miyamoto +# +# Copyright (C) 2019 +# Noriaki Ando +# Robot Innovation Research Center, +# National Institute of +# Advanced Industrial Science and Technology (AIST), Japan +# All rights reserved. +# +# $Id$ +# + +import OpenRTM_aist +from OpenSpliceTopicManager import OpenSpliceTopicManager +import OpenSpliceMessageInfo +import RTC + + +## +# @if jp +# @class OpenSpliceOutPort +# @brief OpenSplice Publisherに対応するクラス +# InPortConsumerオブジェクトとして使用する +# +# @else +# @class OpenSpliceOutPort +# @brief +# +# +# @endif +class OpenSpliceOutPort(OpenRTM_aist.InPortConsumer): + """ + """ + + ## + # @if jp + # @brief コンストラクタ + # + # コンストラクタ + # + # @param self + # + # @else + # @brief Constructor + # + # @param self + # + # @endif + def __init__(self): + OpenRTM_aist.InPortConsumer.__init__(self) + self._rtcout = OpenRTM_aist.Manager.instance().getLogbuf("OpenSpliceOutPort") + self._properties = None + self._dataType = RTC.TimedLong._NP_RepositoryId + self._topic = "chatter" + self._writer = None + + ## + # @if jp + # @brief デストラクタ + # + # デストラクタ + # + # @param self + # + # @else + # @brief Destructor + # + # Destructor + # + # @param self + # + # @endif + # + + def __del__(self): + self._rtcout.RTC_PARANOID("~OpenSpliceOutPort()") + + ## + # @if jp + # @brief 設定初期化 + # + # InPortConsumerの各種設定を行う + # + # @param self + # @param prop 接続設定 + # marshaling_type シリアライザの種類 デフォルト:OpenSplice + # topic トピック名 デフォルト chatter + # + # @else + # @brief Initializing configuration + # + # This operation would be called to configure this consumer + # in initialization. + # + # @param self + # @param prop + # + # @endif + # + # virtual void init(coil::Properties& prop); + def init(self, prop): + self._rtcout.RTC_PARANOID("init()") + + if not prop.propertyNames(): + self._rtcout.RTC_DEBUG("Property is empty.") + return + + self._properties = prop + + qosxml = prop.getProperty("QOSXML") + qosprofile = prop.getProperty("QOSPrfile") + self._topicmgr = OpenSpliceTopicManager.instance(qosxml, qosprofile) + + self._dataType = prop.getProperty("data_type", self._dataType) + + self._topic = prop.getProperty("opensplice.topic", "chatter") + + topic = self._topicmgr.createTopic(self._dataType, self._topic) + + self._rtcout.RTC_VERBOSE("data type: %s", self._dataType) + self._rtcout.RTC_VERBOSE("topic name: %s", self._topic) + + self._writer = self._topicmgr.createWriter(topic) + + ## + # @if jp + # @brief 接続先へのデータ送信 + # + # 接続先のポートへデータを送信するための純粋仮想関数。 + # + # この関数は、以下のリターンコードを返す。 + # + # - PORT_OK: 正常終了。 + # - PORT_ERROR: データ送信の過程で何らかのエラーが発生した。 + # - SEND_FULL: データを送信したが、相手側バッファがフルだった。 + # - SEND_TIMEOUT: データを送信したが、相手側バッファがタイムアウトした。 + # - UNKNOWN_ERROR: 原因不明のエラー + # + # @param data 送信するデータ + # @return リターンコード + # + # @else + # @brief Send data to the destination port + # + # Pure virtual function to send data to the destination port. + # + # This function might the following return codes + # + # - PORT_OK: Normal return + # - PORT_ERROR: Error occurred in data transfer process + # - SEND_FULL: Buffer full although OutPort tried to send data + # - SEND_TIMEOUT: Timeout although OutPort tried to send data + # - UNKNOWN_ERROR: Unknown error + # + # @endif + # + # virtual ReturnCode put(const cdrMemoryStream& data); + def put(self, data): + self._rtcout.RTC_PARANOID("put()") + + if self._writer: + try: + self._writer.write(data) + return self.PORT_OK + except BaseException: + self._rtcout.RTC_ERROR("write error") + return self.CONNECTION_LOST + else: + return self.CONNECTION_LOST + + ## + # @if jp + # @brief InterfaceProfile情報を公開する + # + # InterfaceProfile情報を公開する。 + # 引数で指定するプロパティ情報内の NameValue オブジェクトの + # dataport.interface_type 値を調べ、当該ポートに設定されている + # インターフェースタイプと一致する場合のみ情報を取得する。 + # + # @param properties InterfaceProfile情報を受け取るプロパティ + # + # @else + # @brief Publish InterfaceProfile information + # + # Publish interfaceProfile information. + # Check the dataport.interface_type value of the NameValue object + # specified by an argument in property information and get information + # only when the interface type of the specified port is matched. + # + # @param properties Properties to get InterfaceProfile information + # + # @endif + # + # virtual void publishInterfaceProfile(SDOPackage::NVList& properties); + + def publishInterfaceProfile(self, properties): + pass + + ## + # @if jp + # @brief データ送信通知への登録 + # + # 指定されたプロパティに基づいて、データ送出通知の受け取りに登録する。 + # + # @param properties 登録情報 + # + # @return 登録処理結果(登録成功:true、登録失敗:false) + # + # @else + # @brief Subscribe to the data sending notification + # + # Subscribe to the data sending notification based on specified + # property information. + # + # @param properties Information for subscription + # + # @return Subscription result (Successful:true, Failed:false) + # + # @endif + # + # virtual bool subscribeInterface(const SDOPackage::NVList& properties); + def subscribeInterface(self, properties): + return True + + ## + # @if jp + # @brief データ送信通知からの登録解除 + # + # データ送出通知の受け取りから登録を解除する。 + # + # @param properties 登録解除情報 + # + # @else + # @brief Unsubscribe the data send notification + # + # Unsubscribe the data send notification. + # + # @param properties Information for unsubscription + # + # @endif + # + # virtual void unsubscribeInterface(const SDOPackage::NVList& properties); + def unsubscribeInterface(self, properties): + if self._writer: + self._writer.close() + self._rtcout.RTC_VERBOSE("remove writer") + + +## +# @if jp +# @brief モジュール登録関数 +# +# +# @else +# @brief +# +# +# @endif +# +def OpenSpliceOutPortInit(): + factory = OpenRTM_aist.InPortConsumerFactory.instance() + factory.addFactory("opensplice", + OpenSpliceOutPort) diff --git a/OpenRTM_aist/ext/transport/OpenSplice/OpenSpliceSerializer.py b/OpenRTM_aist/ext/transport/OpenSplice/OpenSpliceSerializer.py new file mode 100644 index 00000000..93bbf22c --- /dev/null +++ b/OpenRTM_aist/ext/transport/OpenSplice/OpenSpliceSerializer.py @@ -0,0 +1,365 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- + +## +# @file OpenSpliceSerializer.py +# @brief OpenSplice Serializer class +# @date $Date$ +# @author Nobuhiko Miyamoto +# +# Copyright (C) 2019 +# Noriaki Ando +# Robot Innovation Research Center, +# National Institute of +# Advanced Industrial Science and Technology (AIST), Japan +# All rights reserved. +# +# $Id$ +# + +import OpenRTM_aist +import omniORB + +import struct +import OpenSpliceMessageInfo +import RTC +import ddsutil +import os +import site +import sys + + +## +# @if jp +# @brief omniORBのデータからOpenSpliceのデータに変換 +# omniORBのデータ型の情報は_NP_RepositoryIdから取得し、 +# 定義された要素名に値を格納していく +# +# @param self +# @param data 変換前のデータ(omniORB) +# @param gen_info OpenSpliceのデータ型Infoオブジェクト +# @return 変換後のデータ(OpenSplice) +# +# +# @else +# @brief +# +# @param self +# @param data +# @param gen_info +# @return +# +# @endif +def OmniDataToDDSData(data, gen_info): + desc = omniORB.findType(data._NP_RepositoryId) + if desc[0] == omniORB.tcInternal.tv_struct: + arg = {} + for i in range(4, len(desc), 2): + attr = desc[i] + attr_type = desc[i + 1] + if isinstance(attr_type, int): + arg[attr] = data.__dict__[attr] + else: + cdata = data.__dict__[attr] + data_name = cdata._NP_RepositoryId + data_name = data_name.split(":")[1] + data_name = data_name.replace("/", "::") + datatype = gen_info.get_class(data_name) + cv = OmniDataToDDSData(cdata, gen_info) + arg[attr] = datatype(**cv) + return arg + + +if sys.version_info[0] == 3: + long = int + + +## +# @if jp +# @brief OpenSpliceのデータからomniORBのデータに変換 +# OpenSpliceのデータはxml.etree.ElementTreeで定義されており、 +# ElementTreeから要素名を取得して値を格納する +# +# @param self +# @param ddsdata 変換前のデータ(OpenSplice) +# @param omnidata 変更対象のデータ(omniORB) +# +# +# @else +# @brief +# +# @param self +# @param ddsdata +# @param omnidata +# +# @endif +def DDSDataToOmniData(ddsdata, omnidata): + for k in ddsdata._members.keys(): + v = ddsdata.__dict__[k] + if isinstance(v, int): + omnidata.__dict__[k] = v + elif isinstance(v, long): + omnidata.__dict__[k] = v + elif isinstance(v, float): + omnidata.__dict__[k] = v + elif isinstance(v, str): + omnidata.__dict__[k] = v + else: + DDSDataToOmniData(v, omnidata.__dict__[k]) + + +## +# @if jp +# @class OpenSpliceSerializer +# @brief OpenSplice用シリアライザ +# +# @else +# @class OpenSpliceSerializer +# @brief +# +# +# @endif +class OpenSpliceSerializer(OpenRTM_aist.ByteDataStreamBase): + """ + """ + + ## + # @if jp + # @brief コンストラクタ + # + # コンストラクタ + # + # @param self + # + # @else + # @brief Constructor + # + # @param self + # + # @endif + def __init__(self): + pass + + ## + # @if jp + # @brief デストラクタ + # + # + # @param self + # + # @else + # + # @brief self + # + # @endif + def __del__(self): + pass + + ## + # @if jp + # @brief 設定初期化 + # + # + # @param prop 設定情報 + # + # @else + # + # @brief Initializing configuration + # + # + # @param prop Configuration information + # + # @endif + # virtual ReturnCode init(coil::Properties& prop) = 0; + def init(self, prop): + pass + + ## + # @if jp + # @brief データの変換(omniORB->OpenSplice) + # + # + # @param data omniORB定義のデータ + # @return ret、value + # ret:SERIALIZE_OK:成功、SERIALIZE_ERROR:失敗、SERIALIZE_NOTFOUND:指定のシリアライザがない + # value:OpenSplice定義のデータ + # + # @else + # + # @brief + # + # + # @param data + # @return + # + # @endif + + def serialize(self, data): + info = OpenSpliceMessageInfo.OpenSpliceMessageInfoList.instance().getInfo( + data._NP_RepositoryId) + if info: + datatype = info.datatype() + idlFile = info.idlFile() + try: + gen_info = ddsutil.get_dds_classes_from_idl(idlFile, datatype) + osdata = gen_info.topic_data_class( + **OmniDataToDDSData(data, gen_info)) + if osdata: + return OpenRTM_aist.ByteDataStreamBase.SERIALIZE_OK, osdata + else: + return OpenRTM_aist.ByteDataStreamBase.SERIALIZE_ERROR, osdata + except BaseException: + return OpenRTM_aist.ByteDataStreamBase.SERIALIZE_ERROR, None + else: + return OpenRTM_aist.ByteDataStreamBase.SERIALIZE_NOTFOUND, None + + ## + # @if jp + # @brief データの変換(OpenSplice->omniORB) + # + # @param bdata OpenSplice定義のデータ + # @param data_type omniORB定義のデータ型 + # @return ret、value + # ret:SERIALIZE_OK:成功、SERIALIZE_ERROR:失敗、SERIALIZE_NOTFOUND:指定のシリアライザがない + # value:omniORB定義のデータ + # + # @else + # + # @brief + # + # @param bdata + # @param data_type + # @return + # + # @endif + def deserialize(self, bdata, data_type): + try: + DDSDataToOmniData(bdata, data_type) + return OpenRTM_aist.ByteDataStreamBase.SERIALIZE_OK, data_type + except BaseException: + return OpenRTM_aist.ByteDataStreamBase.SERIALIZE_ERROR, data_type + +## +# @if jp +# @brief OpenSpliceで使用するデータ型を追加する +# OpenSpliceとomniORBは同一のIDLファイルで定義したデータ型を使用するが、 +# omniORBのデータ型からどのIDLファイルで定義したデータ型なのかを取得することはできないため、 +# omniORBのデータ型名、OpenSpliceのデータ型名、IDLファイル名を関連付ける情報を登録する +# +# @param datatype omniORB定義のデータ型名 +# @param idlfile IDLファイルのパス +# +# @else +# +# @brief +# +# @param datatype +# @param idlfile +# +# @endif + + +def addDataType(datatype, idlfile): + name = datatype._NP_RepositoryId + data_name = name.split(":")[1] + data_name = data_name.replace("/", "::") + OpenSpliceMessageInfo.OpenSpliceMessageInfoList.instance().addInfo(name, + OpenSpliceMessageInfo.OpenSpliceMessageInfo( + data_name, idlfile)) + + +## +# @if jp +# @brief シリアライザ初期化、データ型情報登録 +# +# +# @else +# @brief +# +# +# @endif +# +def OpenSpliceSerializerInit(): + OpenRTM_aist.SerializerFactories.instance().addSerializerGlobal("opensplice", + OpenSpliceSerializer) + + OpenRTM_dir = OpenRTM_aist.__path__[0] + + idl_dir = os.path.join(OpenRTM_dir, "RTM_IDL") + basicdatatypefile = os.path.join(idl_dir, "BasicDataType.idl") + extendeddatatypes = os.path.join(idl_dir, "ExtendedDataTypes.idl") + interfacedataTypes = os.path.join(idl_dir, "InterfaceDataTypes.idl") + addDataType(RTC.TimedState, basicdatatypefile) + addDataType(RTC.TimedShort, basicdatatypefile) + addDataType(RTC.TimedLong, basicdatatypefile) + addDataType(RTC.TimedUShort, basicdatatypefile) + addDataType(RTC.TimedULong, basicdatatypefile) + addDataType(RTC.TimedFloat, basicdatatypefile) + addDataType(RTC.TimedDouble, basicdatatypefile) + addDataType(RTC.TimedChar, basicdatatypefile) + addDataType(RTC.TimedWChar, basicdatatypefile) + addDataType(RTC.TimedBoolean, basicdatatypefile) + addDataType(RTC.TimedOctet, basicdatatypefile) + addDataType(RTC.TimedString, basicdatatypefile) + addDataType(RTC.TimedWString, basicdatatypefile) + addDataType(RTC.TimedShortSeq, basicdatatypefile) + addDataType(RTC.TimedLongSeq, basicdatatypefile) + addDataType(RTC.TimedUShortSeq, basicdatatypefile) + addDataType(RTC.TimedULongSeq, basicdatatypefile) + addDataType(RTC.TimedFloatSeq, basicdatatypefile) + addDataType(RTC.TimedDoubleSeq, basicdatatypefile) + addDataType(RTC.TimedCharSeq, basicdatatypefile) + addDataType(RTC.TimedWCharSeq, basicdatatypefile) + addDataType(RTC.TimedBooleanSeq, basicdatatypefile) + addDataType(RTC.TimedOctetSeq, basicdatatypefile) + addDataType(RTC.TimedStringSeq, basicdatatypefile) + addDataType(RTC.TimedWStringSeq, basicdatatypefile) + addDataType(RTC.TimedRGBColour, extendeddatatypes) + addDataType(RTC.TimedPoint2D, extendeddatatypes) + addDataType(RTC.TimedVector2D, extendeddatatypes) + addDataType(RTC.TimedPose2D, extendeddatatypes) + addDataType(RTC.TimedVelocity2D, extendeddatatypes) + addDataType(RTC.TimedAcceleration2D, extendeddatatypes) + addDataType(RTC.TimedPoseVel2D, extendeddatatypes) + addDataType(RTC.TimedSize2D, extendeddatatypes) + addDataType(RTC.TimedGeometry2D, extendeddatatypes) + addDataType(RTC.TimedCovariance2D, extendeddatatypes) + addDataType(RTC.TimedPointCovariance2D, extendeddatatypes) + addDataType(RTC.TimedCarlike, extendeddatatypes) + addDataType(RTC.TimedSpeedHeading2D, extendeddatatypes) + addDataType(RTC.TimedPoint3D, extendeddatatypes) + addDataType(RTC.TimedVector3D, extendeddatatypes) + addDataType(RTC.TimedOrientation3D, extendeddatatypes) + addDataType(RTC.TimedPose3D, extendeddatatypes) + addDataType(RTC.TimedVelocity3D, extendeddatatypes) + addDataType(RTC.TimedAngularVelocity3D, extendeddatatypes) + addDataType(RTC.TimedAcceleration3D, extendeddatatypes) + addDataType(RTC.TimedAngularAcceleration3D, extendeddatatypes) + addDataType(RTC.TimedPoseVel3D, extendeddatatypes) + addDataType(RTC.TimedSize3D, extendeddatatypes) + addDataType(RTC.TimedGeometry3D, extendeddatatypes) + addDataType(RTC.TimedCovariance3D, extendeddatatypes) + addDataType(RTC.TimedSpeedHeading3D, extendeddatatypes) + addDataType(RTC.TimedOAP, extendeddatatypes) + addDataType(RTC.TimedQuaternion, extendeddatatypes) + addDataType(RTC.ActArrayActuatorPos, interfacedataTypes) + addDataType(RTC.ActArrayActuatorSpeed, interfacedataTypes) + addDataType(RTC.ActArrayActuatorCurrent, interfacedataTypes) + addDataType(RTC.ActArrayState, interfacedataTypes) + addDataType(RTC.CameraImage, interfacedataTypes) + addDataType(RTC.Fiducials, interfacedataTypes) + addDataType(RTC.GPSData, interfacedataTypes) + addDataType(RTC.GripperState, interfacedataTypes) + addDataType(RTC.INSData, interfacedataTypes) + addDataType(RTC.LimbState, interfacedataTypes) + addDataType(RTC.Hypotheses2D, interfacedataTypes) + addDataType(RTC.Hypotheses3D, interfacedataTypes) + addDataType(RTC.Features, interfacedataTypes) + addDataType(RTC.MultiCameraImages, interfacedataTypes) + addDataType(RTC.Path2D, interfacedataTypes) + addDataType(RTC.Path3D, interfacedataTypes) + addDataType(RTC.PointCloud, interfacedataTypes) + addDataType(RTC.PanTiltAngles, interfacedataTypes) + addDataType(RTC.PanTiltState, interfacedataTypes) + addDataType(RTC.RangeData, interfacedataTypes) + addDataType(RTC.IntensityData, interfacedataTypes) diff --git a/OpenRTM_aist/ext/transport/OpenSplice/OpenSpliceTopicManager.py b/OpenRTM_aist/ext/transport/OpenSplice/OpenSpliceTopicManager.py new file mode 100644 index 00000000..b92628c4 --- /dev/null +++ b/OpenRTM_aist/ext/transport/OpenSplice/OpenSpliceTopicManager.py @@ -0,0 +1,420 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- + +## +# @file OpenSpliceTopicManager.py +# @brief OpenSplice Topic Manager class +# @date $Date$ +# @author Nobuhiko Miyamoto +# +# Copyright (C) 2019 +# Noriaki Ando +# Robot Innovation Research Center, +# National Institute of +# Advanced Industrial Science and Technology (AIST), Japan +# All rights reserved. +# +# $Id$ +# + +import OpenRTM_aist +import OpenSpliceMessageInfo +import dds +import ddsutil +import threading + + +manager = None +mutex = threading.RLock() + +## +# @if jp +# @class OpenSpliceTopicManager +# @brief OpenSpliceトピックを管理するクラス +# +# +# @else +# @class OpenSpliceTopicManager +# @brief +# +# +# @endif + + +class OpenSpliceTopicManager(object): + """ + """ + + ## + # @if jp + # @brief コンストラクタ + # + # コンストラクタ + # + # @param self + # + # @else + # @brief Constructor + # + # @param self + # + # @endif + def __init__(self): + self._qosProfile = None + self._domainParticipant = None + self._topic = {} + self._info = {} + + #mgr = OpenRTM_aist.Manager.instance() + # mgr.addManagerActionListener(ManagerActionListener(self)) + #self._rtcout = mgr.getLogbuf("OpenSpliceTopicManager") + + ## + # @if jp + # @brief デストラクタ + # + # + # @param self + # + # @else + # + # @brief self + # + # @endif + + def __del__(self): + pass + + ## + # @if jp + # @brief ドメインパティシパント、パブリッシャー、サブスクライバー初期化 + # + # @param self + # @param qosxml QOS設定XMLファイル + # DDS_DefaultQoS_All.xml、DDS_VolatileQoS_All.xml等の設定ファイルを指定する + # 指定しない場合は以下のデフォルトのQOSに設定する + # DurabilityQosPolicy: TRANSIENT + # DeadlineQosPolicy: 500 + # LatencyBudgetQosPolicy 3000 + # LivelinessQosPolicy: MANUAL_BY_PARTICIPANT + # ReliabilityQosPolicy: RELIABLE, infinity + # DestinationOrderQosPolicy: BY_SOURCE_TIMESTAMP + # HistoryQosPolicy: KEEP_ALL + # ResourceLimitsQosPolicy: 10,10,10 + # TransportPriorityQosPolicy: 700 + # LifespanQosPolicy:10, 500 + # OwnershipQosPolicy: EXCLUSIVE + # OwnershipStrengthQosPolicy 100 + # WriterDataLifecycleQosPolicy: False + # ReaderDataLifecycleQosPolicy: 3,3 + # + # @else + # + # @brief + # + # @param self + # @param qosxml + # + # @endif + + def start(self, qosxml, qosprofile): + if qosxml and qosprofile: + self._qosProfile = dds.QosProvider(qosxml, qosprofile) + self._domainParticipant = dds.DomainParticipant( + qos=self._qosProfile.get_participant_qos()) + self._publisher = self._domainParticipant.create_publisher( + qos=self._qosProfile.get_publisher_qos()) + self._subscriber = self._domainParticipant.create_subscriber( + qos=self._qosProfile.get_subscriber_qos()) + else: + self._domainParticipant = dds.DomainParticipant() + self._publisher = self._domainParticipant.create_publisher() + self._subscriber = self._domainParticipant.create_subscriber() + + ## + # @if jp + # @brief 終了処理 + # + # @param self + # + # @else + # + # @brief + # + # @param self + # + # @endif + + def shutdown(self): + global manager + + manager = None + for _, v in self._topic.items(): + v.close() + if self._publisher: + self._publisher.close() + if self._subscriber: + self._subscriber.close() + if self._domainParticipant: + self._domainParticipant.close() + + self._qosProfile = None + self._domainParticipant = None + self._topic = {} + self._info = {} + + ## + # @if jp + # @brief 指定データ型のロード、Infoオブジェクト生成 + # + # @param self + # @param datatype データ型名 + # @return Infoオブジェクト + # + # @else + # + # @brief + # + # @param self + # @param datatype + # @return + # + # @endif + def genInfo(self, datatype): + global mutex + guard = OpenRTM_aist.ScopedLock(mutex) + if datatype in self._info: + return self._info[datatype] + datainfo = OpenSpliceMessageInfo.OpenSpliceMessageInfoList.instance().getInfo(datatype) + if datainfo: + datatype = datainfo.datatype() + idlfile = datainfo.idlFile() + self._info[datatype] = ddsutil.get_dds_classes_from_idl(idlfile, + datatype) + return self._info[datatype] + return None + + ## + # @if jp + # @brief Writerオブジェクト生成 + # + # @param self + # @param topic トピックオブジェクト + # @return Writerオブジェクト + # + # @else + # + # @brief + # + # @param self + # @param topic + # @return + # + # @endif + def createWriter(self, topic): + global mutex + guard = OpenRTM_aist.ScopedLock(mutex) + if self._qosProfile: + return self._publisher.create_datawriter( + topic, self._qosProfile.get_writer_qos()) + else: + writer_qos = dds.Qos([dds.DurabilityQosPolicy(dds.DDSDurabilityKind.TRANSIENT), + dds.DeadlineQosPolicy(dds.DDSDuration(500)), + dds.LatencyBudgetQosPolicy( + dds.DDSDuration(3000)), + dds.LivelinessQosPolicy( + dds.DDSLivelinessKind.MANUAL_BY_PARTICIPANT), + dds.ReliabilityQosPolicy( + dds.DDSReliabilityKind.RELIABLE, dds.DDSDuration.infinity()), + dds.DestinationOrderQosPolicy( + dds.DDSDestinationOrderKind.BY_SOURCE_TIMESTAMP), + dds.HistoryQosPolicy( + dds.DDSHistoryKind.KEEP_ALL), + dds.ResourceLimitsQosPolicy(10, 10, 10), + dds.TransportPriorityQosPolicy(700), + dds.LifespanQosPolicy( + dds.DDSDuration(10, 500)), + dds.OwnershipQosPolicy( + dds.DDSOwnershipKind.EXCLUSIVE), + dds.OwnershipStrengthQosPolicy(100), + dds.WriterDataLifecycleQosPolicy(False) + ]) + return self._publisher.create_datawriter(topic, writer_qos) + + ## + # @if jp + # @brief Readerオブジェクト生成 + # + # @param self + # @param topic トピックオブジェクト + # @return Readerオブジェクト + # + # @else + # + # @brief + # + # @param self + # @param topic + # @return + # + # @endif + def createReader(self, topic, listener): + global mutex + guard = OpenRTM_aist.ScopedLock(mutex) + if self._qosProfile: + return self._subscriber.create_datareader( + topic, self._qosProfile.get_reader_qos(), listener) + else: + reader_qos = dds.Qos([dds.DurabilityQosPolicy(dds.DDSDurabilityKind.TRANSIENT), + dds.DeadlineQosPolicy(dds.DDSDuration(500)), + dds.LatencyBudgetQosPolicy( + dds.DDSDuration(3000)), + dds.LivelinessQosPolicy( + dds.DDSLivelinessKind.MANUAL_BY_PARTICIPANT), + dds.ReliabilityQosPolicy( + dds.DDSReliabilityKind.RELIABLE, dds.DDSDuration.infinity()), + dds.DestinationOrderQosPolicy( + dds.DDSDestinationOrderKind.BY_SOURCE_TIMESTAMP), + dds.HistoryQosPolicy( + dds.DDSHistoryKind.KEEP_ALL), + dds.ResourceLimitsQosPolicy(10, 10, 10), + dds.OwnershipQosPolicy( + dds.DDSOwnershipKind.EXCLUSIVE), + dds.TimeBasedFilterQosPolicy( + dds.DDSDuration(2, 500)), + dds.ReaderDataLifecycleQosPolicy( + dds.DDSDuration(3), dds.DDSDuration(5)) + ]) + return self._subscriber.create_datareader( + topic, reader_qos, listener) + + ## + # @if jp + # @brief Topicオブジェクト生成 + # + # @param self + # @param datatype データ型名 + # @param topicname トピック名 + # @return Topicオブジェクト + # + # @else + # + # @brief + # + # @param self + # @param datatype + # @param topicname + # @return + # + # @endif + def createTopic(self, datatype, topicname): + global mutex + guard = OpenRTM_aist.ScopedLock(mutex) + if topicname in self._topic: + return self._topic[topicname] + else: + geninfo = self.genInfo(datatype) + if geninfo: + if self._qosProfile: + self._topic[topicname] = geninfo.register_topic( + self._domainParticipant, topicname, self._qosProfile.get_topic_qos()) + else: + topic_qos = dds.Qos([dds.DurabilityQosPolicy(dds.DDSDurabilityKind.TRANSIENT), + dds.DurabilityServiceQosPolicy(dds.DDSDuration( + 2, 500), dds.DDSHistoryKind.KEEP_ALL, 2, 100, 100, 100), + dds.DeadlineQosPolicy( + dds.DDSDuration(500)), + dds.LatencyBudgetQosPolicy( + dds.DDSDuration(3000)), + dds.LivelinessQosPolicy( + dds.DDSLivelinessKind.MANUAL_BY_PARTICIPANT), + dds.ReliabilityQosPolicy( + dds.DDSReliabilityKind.RELIABLE, dds.DDSDuration.infinity()), + dds.DestinationOrderQosPolicy( + dds.DDSDestinationOrderKind.BY_SOURCE_TIMESTAMP), + dds.HistoryQosPolicy( + dds.DDSHistoryKind.KEEP_ALL), + dds.ResourceLimitsQosPolicy( + 10, 10, 10), + dds.TransportPriorityQosPolicy(700), + dds.LifespanQosPolicy( + dds.DDSDuration(10, 500)), + dds.OwnershipQosPolicy( + dds.DDSOwnershipKind.EXCLUSIVE) + ]) + self._topic[topicname] = geninfo.register_topic( + self._domainParticipant, topicname, topic_qos) + return self._topic[topicname] + return None + + ## + # @if jp + # @brief Topicオブジェクト取得 + # + # @param self + # @param topicname トピック名 + # @return Topicオブジェクト + # + # @else + # + # @brief + # + # @param self + # @param topicname + # @return + # + # @endif + + def getTopic(self, topicname): + if topicname in self._topic: + return self._topic[topicname] + return None + + ## + # @if jp + # @brief インスタンス取得 + # + # @return インスタンス + # + # @else + # + # @brief + # + # @return + # + # @endif + def instance(qosxml="", qosprofile=""): + global manager + global mutex + + guard = OpenRTM_aist.ScopedLock(mutex) + if manager is None: + manager = OpenSpliceTopicManager() + manager.start(qosxml, qosprofile) + return manager + + instance = staticmethod(instance) + + ## + # @if jp + # @brief OpenSpliceTopicManagerを初期化している場合に終了処理を呼び出す + # + # + # @else + # + # @brief + # + # + # @endif + + def shutdown_global(): + global manager + global mutex + + guard = OpenRTM_aist.ScopedLock(mutex) + if manager is not None: + manager.shutdown() + + manager = None + + shutdown_global = staticmethod(shutdown_global) diff --git a/OpenRTM_aist/ext/transport/OpenSplice/OpenSpliceTransport.py b/OpenRTM_aist/ext/transport/OpenSplice/OpenSpliceTransport.py new file mode 100644 index 00000000..4aac25ba --- /dev/null +++ b/OpenRTM_aist/ext/transport/OpenSplice/OpenSpliceTransport.py @@ -0,0 +1,96 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- + +## +# @file OpenSpliceTransport.py +# @brief OpenSplice Transport class +# @date $Date$ +# @author Nobuhiko Miyamoto +# +# Copyright (C) 2019 +# Noriaki Ando +# Robot Innovation Research Center, +# National Institute of +# Advanced Industrial Science and Technology (AIST), Japan +# All rights reserved. +# +# $Id$ +# + +import OpenRTM_aist +import OpenSpliceInPort +import OpenSpliceOutPort +import OpenSpliceSerializer +from OpenSpliceTopicManager import OpenSpliceTopicManager + + +## +# @if jp +# @class ManagerActionListener +# @brief OpenSpliceTopicManagerの終了処理を行うマネージャアクションリスナ +# +# +# @else +# @class ManagerActionListener +# @brief +# +# +# @endif +class ManagerActionListener: + ## + # @if jp + # @brief コンストラクタ + # + # + # @param self + # + # @else + # + # @brief self + # + # @endif + def __init__(self): + pass + + def preShutdown(self): + pass + ## + # @if jp + # @brief RTMマネージャ終了後にOpenSpliceTopicManagerの終了処理を実行 + # + # + # @param self + # + # @else + # + # @brief self + # + # @endif + + def postShutdown(self): + OpenSpliceTopicManager.shutdown_global() + + def preReinit(self): + pass + + def postReinit(self): + pass + + +## +# @if jp +# @brief モジュール登録関数 +# +# +# @else +# @brief +# +# +# @endif +# +def OpenSpliceTransportInit(mgr): + OpenSpliceInPort.OpenSpliceInPortInit() + OpenSpliceOutPort.OpenSpliceOutPortInit() + OpenSpliceSerializer.OpenSpliceSerializerInit() + + mgr.addManagerActionListener(ManagerActionListener()) diff --git a/OpenRTM_aist/ext/transport/OpenSplice/__init__.py b/OpenRTM_aist/ext/transport/OpenSplice/__init__.py new file mode 100644 index 00000000..270be2a2 --- /dev/null +++ b/OpenRTM_aist/ext/transport/OpenSplice/__init__.py @@ -0,0 +1 @@ +# Empty file diff --git a/OpenRTM_aist/ext/transport/OpenSplice/rtc.conf b/OpenRTM_aist/ext/transport/OpenSplice/rtc.conf new file mode 100644 index 00000000..804c5a60 --- /dev/null +++ b/OpenRTM_aist/ext/transport/OpenSplice/rtc.conf @@ -0,0 +1,8 @@ +logger.enable: YES +logger.file_name: stdout +logger.log_level: ERROR + +manager.modules.load_path: . +manager.modules.preload: OpenSpliceTransport.py +manager.components.preconnect: ConsoleOut0.in?interface_type=opensplice&marshaling_type=opensplice, ConsoleIn0.out?interface_type=opensplice&marshaling_type=opensplice +manager.components.preactivation: ConsoleOut0, ConsoleIn0 \ No newline at end of file diff --git a/OpenRTM_aist/ext/transport/ROS2Transport/ROS2InPort.py b/OpenRTM_aist/ext/transport/ROS2Transport/ROS2InPort.py new file mode 100644 index 00000000..76b874c1 --- /dev/null +++ b/OpenRTM_aist/ext/transport/ROS2Transport/ROS2InPort.py @@ -0,0 +1,357 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- + +## +# @file ROS2InPort.py +# @brief ROS2 OutPort class +# @date $Date$ +# @author Nobuhiko Miyamoto +# +# Copyright (C) 2019 +# Noriaki Ando +# Robot Innovation Research Center, +# National Institute of +# Advanced Industrial Science and Technology (AIST), Japan +# All rights reserved. +# +# $Id$ +# + +import OpenRTM_aist +from ROS2TopicManager import ROS2TopicManager +import ROS2MessageInfo +import RTC +import threading + + +## +# @if jp +# @class ROS2InPort +# @brief ROS2 Subscriberに対応するクラス +# InPortProviderオブジェクトとして使用する +# +# @else +# @class ROS2InPort +# @brief +# +# +# @endif +class ROS2InPort(OpenRTM_aist.InPortProvider): + """ + """ + + ## + # @if jp + # @brief コンストラクタ + # + # コンストラクタ + # ポートプロパティに以下の項目を設定する。 + # - インターフェースタイプ : ROS2 + # - データフロータイプ : Push + # + # @param self + # + # @else + # @brief Constructor + # + # Constructor + # Set the following items to port properties + # - Interface type : CORBA_Any + # - Data flow type : Push, Pull + # + # @param self + # + # @endif + # + def __init__(self): + OpenRTM_aist.InPortProvider.__init__(self) + + # PortProfile setting + self.setInterfaceType("ros2") + + self._profile = None + self._listeners = None + + self._topic = "chatter" + self._messageType = None + self._subscriber = None + + self._mutex = threading.RLock() + + ## + # @if jp + # @brief デストラクタ + # + # デストラクタ + # + # @param self + # + # @else + # @brief Destructor + # + # Destructor + # + # @param self + # + # @endif + # + + def __del__(self): + return + + ## + # @if jp + # @brief 終了処理 + # + # @param self + # + # @else + # @brief + # + # @param self + # + # @endif + # + + def exit(self): + self._rtcout.RTC_PARANOID("exit()") + + ## + # @if jp + # @brief 初期化 + # + # @param self + # @param prop 接続設定 + # marshaling_type シリアライザの種類 デフォルト:ROS2 + # topic トピック名 デフォルト chatter + # + # @else + # @brief + # + # @param self + # @param prop + # + # @endif + # + # virtual void init(coil::Properties& prop); + + def init(self, prop): + self._rtcout.RTC_PARANOID("init()") + + if not prop.propertyNames(): + self._rtcout.RTC_DEBUG("Property is empty.") + return + + self._properties = prop + + args = [] + self._topicmgr = ROS2TopicManager.instance(args) + + self._messageType = prop.getProperty( + "marshaling_type", "ros2:std_msgs/Float32") + self._topic = prop.getProperty("ros2.topic", "chatter") + + self._rtcout.RTC_VERBOSE("message type: %s", self._messageType) + self._rtcout.RTC_VERBOSE("topic name: %s", self._topic) + + factory = ROS2MessageInfo.ROS2MessageInfoList.instance() + info = factory.getInfo(self._messageType) + + info_type = info.datatype() + + self._subscriber = self._topicmgr.createSubscriber( + info_type, self._topic, self.ros2_callback) + + # virtual void setBuffer(BufferBase* buffer); + + def setBuffer(self, buffer): + return + + ## + # @if jp + # @brief コネクタリスナの設定 + # + # @param info 接続情報 + # @param listeners リスナ + # + # @else + # @brief + # + # @param info + # @param listeners + # + # @endif + # + # void setListener(ConnectorInfo& info, + # ConnectorListeners* listeners); + def setListener(self, info, listeners): + self._profile = info + self._listeners = listeners + return + + ## + # @if jp + # @brief Subscriberメッセージ受信時のコールバック関数 + # + # @param self + # @param msg 受信メッセージ + # + # @else + # @brief + # + # @param self + # @param msg + # + # @endif + # + + def ros2_callback(self, msg): + self.put(msg) + + ## + # @if jp + # @brief バッファにデータを書き込む + # + # 設定されたバッファにデータを書き込む。 + # + # @param data 書込対象データ + # + # @else + # @brief Write data into the buffer + # + # Write data into the specified buffer. + # + # @param data The target data for writing + # + # @endif + # + + def put(self, data): + guard = OpenRTM_aist.Guard.ScopedLock(self._mutex) + try: + self._rtcout.RTC_PARANOID("ROS2InPort.put()") + if not self._connector: + self.onReceiverError(data) + return OpenRTM.PORT_ERROR + + data = self.onReceived(data) + + ret = self._connector.write(data) + + self.convertReturn(ret, data) + + except BaseException: + self._rtcout.RTC_TRACE(OpenRTM_aist.Logger.print_exception()) + + def convertReturn(self, status, data): + if status == OpenRTM_aist.BufferStatus.BUFFER_OK: + self.onBufferWrite(data) + return + + elif status == OpenRTM_aist.BufferStatus.BUFFER_ERROR: + self.onReceiverError(data) + return + + elif status == OpenRTM_aist.BufferStatus.BUFFER_FULL: + data = self.onBufferFull(data) + self.onReceiverFull(data) + return + + elif status == OpenRTM_aist.BufferStatus.BUFFER_EMPTY: + return + + elif status == OpenRTM_aist.BufferStatus.PRECONDITION_NOT_MET: + self.onReceiverError(data) + return + + elif status == OpenRTM_aist.BufferStatus.TIMEOUT: + data = self.onBufferWriteTimeout(data) + self.onReceiverTimeout(data) + return + + else: + self.onReceiverError(data) + return + + ## + # @brief Connector data listener functions + # + # inline void onBufferWrite(const cdrMemoryStream& data) + + def onBufferWrite(self, data): + if self._listeners is not None and self._profile is not None: + _, data = self._listeners.notifyData( + OpenRTM_aist.ConnectorDataListenerType.ON_BUFFER_WRITE, self._profile, data) + return data + + # inline void onBufferFull(const cdrMemoryStream& data) + + def onBufferFull(self, data): + if self._listeners is not None and self._profile is not None: + _, data = self._listeners.notifyData( + OpenRTM_aist.ConnectorDataListenerType.ON_BUFFER_FULL, self._profile, data) + return data + + # inline void onBufferWriteTimeout(const cdrMemoryStream& data) + + def onBufferWriteTimeout(self, data): + if self._listeners is not None and self._profile is not None: + _, data = self._listeners.notifyData( + OpenRTM_aist.ConnectorDataListenerType.ON_BUFFER_WRITE_TIMEOUT, self._profile, data) + return data + + # inline void onBufferWriteOverwrite(const cdrMemoryStream& data) + def onBufferWriteOverwrite(self, data): + if self._listeners is not None and self._profile is not None: + _, data = self._listeners.notifyData( + OpenRTM_aist.ConnectorDataListenerType.ON_BUFFER_OVERWRITE, self._profile, data) + return data + + # inline void onReceived(const cdrMemoryStream& data) + + def onReceived(self, data): + if self._listeners is not None and self._profile is not None: + _, data = self._listeners.notifyData( + OpenRTM_aist.ConnectorDataListenerType.ON_RECEIVED, self._profile, data) + return data + + # inline void onReceiverFull(const cdrMemoryStream& data) + + def onReceiverFull(self, data): + if self._listeners is not None and self._profile is not None: + _, data = self._listeners.notifyData( + OpenRTM_aist.ConnectorDataListenerType.ON_RECEIVER_FULL, self._profile, data) + return data + + # inline void onReceiverTimeout(const cdrMemoryStream& data) + + def onReceiverTimeout(self, data): + if self._listeners is not None and self._profile is not None: + _, data = self._listeners.notifyData( + OpenRTM_aist.ConnectorDataListenerType.ON_RECEIVER_TIMEOUT, self._profile, data) + return data + + # inline void onReceiverError(const cdrMemoryStream& data) + + def onReceiverError(self, data): + if self._listeners is not None and self._profile is not None: + _, data = self._listeners.notifyData( + OpenRTM_aist.ConnectorDataListenerType.ON_RECEIVER_ERROR, self._profile, data) + return data + + +## +# @if jp +# @brief モジュール登録関数 +# +# +# @else +# @brief +# +# +# @endif +# +def ROS2InPortInit(): + factory = OpenRTM_aist.InPortProviderFactory.instance() + factory.addFactory("ros2", + ROS2InPort) diff --git a/OpenRTM_aist/ext/transport/ROS2Transport/ROS2MessageInfo.py b/OpenRTM_aist/ext/transport/ROS2Transport/ROS2MessageInfo.py new file mode 100644 index 00000000..3f5d4155 --- /dev/null +++ b/OpenRTM_aist/ext/transport/ROS2Transport/ROS2MessageInfo.py @@ -0,0 +1,301 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- + +## +# @file ROS2MessageInfo.py +# @brief ROS2 Message Info class +# @date $Date$ +# @author Nobuhiko Miyamoto +# +# Copyright (C) 2019 +# Noriaki Ando +# Robot Innovation Research Center, +# National Institute of +# Advanced Industrial Science and Technology (AIST), Japan +# All rights reserved. +# +# $Id$ +# + +import OpenRTM_aist + +## +# @if jp +# @class ROS2MessageInfoBase +# @brief ROS2メッセージ情報格納オブジェクトの基底クラス +# ROS2データ型名、IDLファイルパスを登録する +# +# @else +# @class ROS2OutPort +# @brief +# +# +# @endif + + +class ROS2MessageInfoBase(object): + ## + # @if jp + # @brief コンストラクタ + # + # コンストラクタ + # + # @param self + # + # @else + # @brief Constructor + # + # @param self + # + # @endif + def __init__(self): + pass + ## + # @if jp + # @brief デストラクタ + # + # デストラクタ + # + # @param self + # + # @else + # @brief Destructor + # + # Destructor + # + # @param self + # + # @endif + # + + def __del__(self): + pass + + ## + # @if jp + # @brief データの型名を取得 + # + # @param self + # @return 型名 + # + # @else + # @brief + # + # + # @param self + # @return + # + # @endif + # + def datatype(self): + return None + + +## +# @if jp +# @class ROS2MessageInfo +# @brief メッセージの情報格納クラス +# +# +# @else +# @class ROS2MessageInfo +# @brief +# +# +# @endif +class ROS2MessageInfo(ROS2MessageInfoBase): + """ + """ + ## + # @if jp + # @brief コンストラクタ + # + # コンストラクタ + # + # @param self + # + # @else + # @brief Constructor + # + # @param self + # + # @endif + + def __init__(self, datatype): + super(ROS2MessageInfo, self).__init__() + self._datatype = datatype + ## + # @if jp + # @brief デストラクタ + # + # + # @param self + # + # @else + # + # @brief self + # + # @endif + + def __del__(self): + pass + ## + # @if jp + # @brief メッセージの型名を取得 + # + # @param self + # @return 型名 + # + # @else + # @brief + # + # + # @param self + # @return + # + # @endif + # + + def datatype(self): + return self._datatype + + +ros2messageinfolist = None + + +## +# @if jp +# @class ROS2MessageInfoList +# @brief ROS2メッセージ情報格納オブジェクト生成ファクトリ +# +# @else +# @class ROS2MessageInfoList +# @brief +# +# +# @endif +class ROS2MessageInfoList: + ## + # @if jp + # @brief コンストラクタ + # + # コンストラクタ + # + # @param self + # + # @else + # @brief Constructor + # + # @param self + # + # @endif + def __init__(self): + self._data = {} + + ## + # @if jp + # @brief デストラクタ + # + # デストラクタ + # + # @param self + # + # @else + # @brief Destructor + # + # Destructor + # + # @param self + # + # @endif + # + def __del__(self): + pass + + ## + # @if jp + # @brief インスタンス取得 + # + # + # @return インスタンス + # + # @else + # @brief + # + # + # @return + # + # @endif + # + def instance(): + global ros2messageinfolist + + if ros2messageinfolist is None: + ros2messageinfolist = ROS2MessageInfoList() + + return ros2messageinfolist + + instance = staticmethod(instance) + + ## + # @if jp + # @brief ROS2MessageInfoの追加 + # + # @param self + # @param id 名前 + # @param info ROS2MessageInfo + # + # @else + # @brief + # + # @param self + # @param id + # @param info + # + # @endif + # + def addInfo(self, id, info): + self._data[id] = info + + ## + # @if jp + # @brief ROS2MessageInfoの削除 + # + # @param self + # @param id 名前 + # @return 削除に成功した場合はTrue + # + # @else + # @brief + # + # @param self + # @param id + # @return + # + # @endif + # + def removeInfo(self, id): + if id in self._data: + del self._data[id] + return True + return False + + ## + # @if jp + # @brief 指定名のROS2MessageInfoの取得 + # + # @param id 名前 + # @return ROS2MessageInfo + # + # @else + # @brief + # + # @param id + # @return + # + # @endif + # + def getInfo(self, id): + if id in self._data: + return self._data[id] + return None diff --git a/OpenRTM_aist/ext/transport/ROS2Transport/ROS2OutPort.py b/OpenRTM_aist/ext/transport/ROS2Transport/ROS2OutPort.py new file mode 100644 index 00000000..ce2ffe32 --- /dev/null +++ b/OpenRTM_aist/ext/transport/ROS2Transport/ROS2OutPort.py @@ -0,0 +1,272 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- + +## +# @file ROS2OutPort.py +# @brief ROS2 OutPort class +# @date $Date$ +# @author Nobuhiko Miyamoto +# +# Copyright (C) 2019 +# Noriaki Ando +# Robot Innovation Research Center, +# National Institute of +# Advanced Industrial Science and Technology (AIST), Japan +# All rights reserved. +# +# $Id$ +# + +import OpenRTM_aist +from ROS2TopicManager import ROS2TopicManager +import ROS2MessageInfo +import RTC + + +## +# @if jp +# @class ROS2OutPort +# @brief ROS2 Publisherに対応するクラス +# InPortConsumerオブジェクトとして使用する +# +# @else +# @class ROS2OutPort +# @brief +# +# +# @endif +class ROS2OutPort(OpenRTM_aist.InPortConsumer): + """ + """ + + ## + # @if jp + # @brief コンストラクタ + # + # コンストラクタ + # + # @param self + # + # @else + # @brief Constructor + # + # @param self + # + # @endif + def __init__(self): + OpenRTM_aist.InPortConsumer.__init__(self) + self._rtcout = OpenRTM_aist.Manager.instance().getLogbuf("ROS2OutPort") + self._properties = None + self._messageType = "ROS2Float32" + self._topic = "chatter" + self._publisher = None + + ## + # @if jp + # @brief デストラクタ + # + # デストラクタ + # + # @param self + # + # @else + # @brief Destructor + # + # Destructor + # + # @param self + # + # @endif + # + + def __del__(self): + self._rtcout.RTC_PARANOID("~ROS2OutPort()") + + ## + # @if jp + # @brief 設定初期化 + # + # InPortConsumerの各種設定を行う + # + # @param self + # @param prop 接続設定 + # marshaling_type シリアライザの種類 デフォルト:ROS2 + # topic トピック名 デフォルト chatter + # + # @else + # @brief Initializing configuration + # + # This operation would be called to configure this consumer + # in initialization. + # + # @param self + # @param prop + # + # @endif + # + # virtual void init(coil::Properties& prop); + def init(self, prop): + self._rtcout.RTC_PARANOID("init()") + + if not prop.propertyNames(): + self._rtcout.RTC_DEBUG("Property is empty.") + return + + self._properties = prop + + args = [] + self._topicmgr = ROS2TopicManager.instance(args) + + self._messageType = prop.getProperty( + "marshaling_type", "ros2:std_msgs/Float32") + self._topic = prop.getProperty("ros2.topic", "chatter") + + self._rtcout.RTC_VERBOSE("message type: %s", self._messageType) + self._rtcout.RTC_VERBOSE("topic name: %s", self._topic) + + factory = ROS2MessageInfo.ROS2MessageInfoList.instance() + info = factory.getInfo(self._messageType) + + info_type = info.datatype() + + self._publisher = self._topicmgr.createPublisher( + info_type, self._topic) + + ## + # @if jp + # @brief 接続先へのデータ送信 + # + # 接続先のポートへデータを送信するための純粋仮想関数。 + # + # この関数は、以下のリターンコードを返す。 + # + # - PORT_OK: 正常終了。 + # - PORT_ERROR: データ送信の過程で何らかのエラーが発生した。 + # - SEND_FULL: データを送信したが、相手側バッファがフルだった。 + # - SEND_TIMEOUT: データを送信したが、相手側バッファがタイムアウトした。 + # - UNKNOWN_ERROR: 原因不明のエラー + # + # @param data 送信するデータ + # @return リターンコード + # + # @else + # @brief Send data to the destination port + # + # Pure virtual function to send data to the destination port. + # + # This function might the following return codes + # + # - PORT_OK: Normal return + # - PORT_ERROR: Error occurred in data transfer process + # - SEND_FULL: Buffer full although OutPort tried to send data + # - SEND_TIMEOUT: Timeout although OutPort tried to send data + # - UNKNOWN_ERROR: Unknown error + # + # @endif + # + # virtual ReturnCode put(const cdrMemoryStream& data); + + def put(self, data): + self._rtcout.RTC_PARANOID("put()") + + if self._publisher: + try: + self._publisher.publish(data) + return self.PORT_OK + except BaseException: + self._rtcout.RTC_ERROR("write error") + return self.CONNECTION_LOST + else: + return self.CONNECTION_LOST + + ## + # @if jp + # @brief InterfaceProfile情報を公開する + # + # InterfaceProfile情報を公開する。 + # 引数で指定するプロパティ情報内の NameValue オブジェクトの + # dataport.interface_type 値を調べ、当該ポートに設定されている + # インターフェースタイプと一致する場合のみ情報を取得する。 + # + # @param properties InterfaceProfile情報を受け取るプロパティ + # + # @else + # @brief Publish InterfaceProfile information + # + # Publish interfaceProfile information. + # Check the dataport.interface_type value of the NameValue object + # specified by an argument in property information and get information + # only when the interface type of the specified port is matched. + # + # @param properties Properties to get InterfaceProfile information + # + # @endif + # + # virtual void publishInterfaceProfile(SDOPackage::NVList& properties); + + def publishInterfaceProfile(self, properties): + pass + + ## + # @if jp + # @brief データ送信通知への登録 + # + # 指定されたプロパティに基づいて、データ送出通知の受け取りに登録する。 + # + # @param properties 登録情報 + # + # @return 登録処理結果(登録成功:true、登録失敗:false) + # + # @else + # @brief Subscribe to the data sending notification + # + # Subscribe to the data sending notification based on specified + # property information. + # + # @param properties Information for subscription + # + # @return Subscription result (Successful:true, Failed:false) + # + # @endif + # + # virtual bool subscribeInterface(const SDOPackage::NVList& properties); + def subscribeInterface(self, properties): + return True + + ## + # @if jp + # @brief データ送信通知からの登録解除 + # + # データ送出通知の受け取りから登録を解除する。 + # + # @param properties 登録解除情報 + # + # @else + # @brief Unsubscribe the data send notification + # + # Unsubscribe the data send notification. + # + # @param properties Information for unsubscription + # + # @endif + # + # virtual void unsubscribeInterface(const SDOPackage::NVList& properties); + def unsubscribeInterface(self, properties): + pass + + +## +# @if jp +# @brief モジュール登録関数 +# +# +# @else +# @brief +# +# +# @endif +# +def ROS2OutPortInit(): + factory = OpenRTM_aist.InPortConsumerFactory.instance() + factory.addFactory("ros2", + ROS2OutPort) diff --git a/OpenRTM_aist/ext/transport/ROS2Transport/ROS2Serializer.py b/OpenRTM_aist/ext/transport/ROS2Transport/ROS2Serializer.py new file mode 100644 index 00000000..c5d0a422 --- /dev/null +++ b/OpenRTM_aist/ext/transport/ROS2Transport/ROS2Serializer.py @@ -0,0 +1,895 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- + +## +# @file ROS2Serializer.py +# @brief ROS2 Serializer class +# @date $Date$ +# @author Nobuhiko Miyamoto +# +# Copyright (C) 2019 +# Noriaki Ando +# Robot Innovation Research Center, +# National Institute of +# Advanced Industrial Science and Technology (AIST), Japan +# All rights reserved. +# +# $Id$ +# + +import OpenRTM_aist +import omniORB + +import struct +import array +import ROS2MessageInfo +import RTC +import rclpy +from std_msgs.msg import Float32 +from std_msgs.msg import Float64 +from std_msgs.msg import Int8 +from std_msgs.msg import Int16 +from std_msgs.msg import Int32 +from std_msgs.msg import Int64 +from std_msgs.msg import UInt8 +from std_msgs.msg import UInt16 +from std_msgs.msg import UInt32 +from std_msgs.msg import UInt64 +from std_msgs.msg import Float32MultiArray +from std_msgs.msg import Float64MultiArray +from std_msgs.msg import Int8MultiArray +from std_msgs.msg import Int16MultiArray +from std_msgs.msg import Int32MultiArray +from std_msgs.msg import Int64MultiArray +from std_msgs.msg import UInt8MultiArray +from std_msgs.msg import UInt16MultiArray +from std_msgs.msg import UInt32MultiArray +from std_msgs.msg import UInt64MultiArray +from std_msgs.msg import String +from geometry_msgs.msg import PointStamped +from geometry_msgs.msg import QuaternionStamped +from geometry_msgs.msg import Vector3Stamped +from sensor_msgs.msg import Image + + +## +# @if jp +# @brief 単一データ、配列などの基本メッセージ型のROS2シリアライザの生成関数 +# +# @param message_type ROS2メッセージ型 +# +# @else +# @brief +# +# @param message_type +# +# @endif +# +def ros2_basic_data(message_type): + ## + # @if jp + # @class ROS2BasicData + # @brief 単一データ、配列などの基本メッセージ型 + # + # @else + # @class ROS2BasicData + # @brief + # + # + # @endif + class ROS2BasicData(OpenRTM_aist.ByteDataStreamBase): + """ + """ + + ## + # @if jp + # @brief コンストラクタ + # + # コンストラクタ + # + # @param self + # + # @else + # @brief Constructor + # + # @param self + # + # @endif + def __init__(self): + pass + + ## + # @if jp + # @brief デストラクタ + # + # + # @param self + # + # @else + # + # @brief self + # + # @endif + def __del__(self): + pass + + ## + # @if jp + # @brief 設定初期化 + # + # + # @param prop 設定情報 + # + # @else + # + # @brief Initializing configuration + # + # + # @param prop Configuration information + # + # @endif + # virtual ReturnCode init(coil::Properties& prop) = 0; + def init(self, prop): + pass + + ## + # @if jp + # @brief データの変換(omniORB->ROS2) + # + # + # @param data omniORBのデータ + # @return ret、value + # ret:SERIALIZE_OK:成功、SERIALIZE_ERROR:失敗、SERIALIZE_NOTFOUND:指定のシリアライザがない + # value:ROS2のデータ + # + # @else + # + # @brief + # + # + # @param data + # @return + # + # @endif + + def serialize(self, data): + msg = message_type() + field_type = msg.get_fields_and_field_types()["data"] + if field_type == "int" or field_type == "int8" or field_type == "int16" or field_type == "int32" or field_type == "int64": + msg.data = int(data.data) + elif field_type == "uint" or field_type == "uint8" or field_type == "uint16" or field_type == "uint32" or field_type == "uint64": + msg.data = int(data.data) + elif field_type == "float" or field_type == "double" or field_type == "float32" or field_type == "float64": + msg.data = float(data.data) + elif field_type == "sequence" or field_type == "sequence" or field_type == "sequence" or field_type == "sequence" or field_type == "int8[]" or field_type == "int16[]" or field_type == "int32[]" or field_type == "int64[]": + msg.data = list(map(int, data.data)) + elif field_type == "sequence" or field_type == "sequence" or field_type == "sequence" or field_type == "sequence" or field_type == "uint8[]" or field_type == "uint16[]" or field_type == "uint32[]" or field_type == "uint64[]": + msg.data = list(map(int, data.data)) + elif field_type == "sequence" or field_type == "sequence" or field_type == "float32[]" or field_type == "float64[]": + msg.data = list(map(float, data.data)) + elif field_type == "string": + msg.data = str(data.data) + else: + msg.data = data.data + + return OpenRTM_aist.ByteDataStreamBase.SERIALIZE_OK, msg + + ## + # @if jp + # @brief データの変換(ROS2->omniORB) + # + # @param self + # @param bdata ROS2のデータ + # @param data_type omniORBのデータ + # @return ret、value + # ret:SERIALIZE_OK:成功、SERIALIZE_ERROR:失敗、SERIALIZE_NOTFOUND:指定のシリアライザがない + # value:変換後のデータ + # + # @else + # + # @brief + # + # @param cdr + # @param data_type + # @return + # + # @endif + def deserialize(self, bdata, data_type): + try: + if isinstance(data_type.data, bytes): + if isinstance(bdata.data, array.array): + data_type.data = bdata.data.tobytes() + else: + data_type.data = bytes(bdata.data) + elif isinstance(data_type.data, str): + if isinstance(bdata.data, array.array): + data_type.data = bdata.data.tostring() + else: + data_type.data = str(bdata.data) + elif isinstance(data_type.data, list): + data_type.data = list(bdata.data) + elif isinstance(data_type.data, tuple): + data_type.data = tuple(bdata.data) + elif isinstance(data_type.data, int): + data_type.data = int(bdata.data) + elif isinstance(data_type.data, float): + data_type.data = float(bdata.data) + else: + data_type.data = bdata.data + return OpenRTM_aist.ByteDataStreamBase.SERIALIZE_OK, data_type + except BaseException: + return OpenRTM_aist.ByteDataStreamBase.SERIALIZE_NOT_SUPPORT_ENDIAN, data_type + return ROS2BasicData + +## +# @if jp +# @brief 単一データ、配列などの基本メッセージ型のシリアライザの初期化 +# +# @param message_type ROSメッセージ型 +# @param name シリアライザの名前 +# +# @else +# @brief +# +# @param message_type +# @param name +# +# +# @endif +# + + +def ROS2BasicDataInit(message_type, name): + datatypes = [RTC.TimedState, RTC.TimedShort, RTC.TimedLong, + RTC.TimedUShort, RTC.TimedULong, RTC.TimedFloat, + RTC.TimedDouble, RTC.TimedChar, RTC.TimedWChar, + RTC.TimedBoolean, RTC.TimedOctet, RTC.TimedString, + RTC.TimedWString, RTC.TimedShortSeq, RTC.TimedLongSeq, + RTC.TimedUShortSeq, RTC.TimedULongSeq, RTC.TimedFloatSeq, + RTC.TimedDoubleSeq, RTC.TimedCharSeq, RTC.TimedWCharSeq, + RTC.TimedBooleanSeq, RTC.TimedOctetSeq, RTC.TimedStringSeq, + RTC.TimedWStringSeq] + for datatype in datatypes: + OpenRTM_aist.SerializerFactories.instance().addSerializer(name, + ros2_basic_data( + message_type), datatype) + ROS2MessageInfo.ROS2MessageInfoList.instance().addInfo(name, + ROS2MessageInfo.ROS2MessageInfo( + message_type)) + + +## +# @if jp +# @class ROS2Point3DData +# @brief PointStamped型のシリアライザ初期化 +# +# @else +# @class ROS2Point3DData +# @brief +# +# +# @endif +class ROS2Point3DData(OpenRTM_aist.ByteDataStreamBase): + """ + """ + + ## + # @if jp + # @brief コンストラクタ + # + # コンストラクタ + # + # @param self + # + # @else + # @brief Constructor + # + # @param self + # + # @endif + def __init__(self): + pass + + ## + # @if jp + # @brief デストラクタ + # + # + # @param self + # + # @else + # + # @brief self + # + # @endif + def __del__(self): + pass + + ## + # @if jp + # @brief 設定初期化 + # + # + # @param prop 設定情報 + # + # @else + # + # @brief Initializing configuration + # + # + # @param prop Configuration information + # + # @endif + # virtual ReturnCode init(coil::Properties& prop) = 0; + def init(self, prop): + pass + + ## + # @if jp + # @brief データの変換(omniORB->ROS2) + # + # + # @param data omniORBのデータ + # @return ret、value + # ret:SERIALIZE_OK:成功、SERIALIZE_ERROR:失敗、SERIALIZE_NOTFOUND:指定のシリアライザがない + # value:ROS2のデータ + # + # @else + # + # @brief + # + # + # @param data + # @return + # + # @endif + + def serialize(self, data): + msg = PointStamped() + msg.header.stamp.sec = data.tm.sec + msg.header.stamp.nanosec = data.tm.nsec + msg.point.x = float(data.data.x) + msg.point.y = float(data.data.y) + msg.point.z = float(data.data.z) + + return OpenRTM_aist.ByteDataStreamBase.SERIALIZE_OK, msg + + ## + # @if jp + # @brief データの変換(ROS2->omniORB) + # + # @param self + # @param bdata ROS2のデータ + # @param data_type omniORBのデータ + # @return ret、value + # ret:SERIALIZE_OK:成功、SERIALIZE_ERROR:失敗、SERIALIZE_NOTFOUND:指定のシリアライザがない + # value:変換後のデータ + # + # @else + # + # @brief + # + # @param cdr + # @param data_type + # @return + # + # @endif + def deserialize(self, bdata, data_type): + try: + data_type.tm.sec = bdata.header.stamp.sec + data_type.tm.nsec = bdata.header.stamp.nanosec + data_type.data.x = bdata.point.x + data_type.data.y = bdata.point.y + data_type.data.z = bdata.point.z + return OpenRTM_aist.ByteDataStreamBase.SERIALIZE_OK, data_type + except BaseException: + return OpenRTM_aist.ByteDataStreamBase.SERIALIZE_NOT_SUPPORT_ENDIAN, data_type + + +## +# @if jp +# @brief PointStamped型のシリアライザの初期化 +# +# +# @else +# @brief +# +# +# @endif +# +def ROS2Point3DInit(): + OpenRTM_aist.SerializerFactories.instance().addSerializer("ros2:geometry_msgs/PointStamped", + ROS2Point3DData, RTC.TimedPoint3D) + ROS2MessageInfo.ROS2MessageInfoList.instance().addInfo("ros2:geometry_msgs/PointStamped", + ROS2MessageInfo.ROS2MessageInfo( + PointStamped)) + + +## +# @if jp +# @class ROS2QuaternionData +# @brief QuaternionStamped型のシリアライザ +# +# @else +# @class ROS2QuaternionData +# @brief +# +# +# @endif +class ROS2QuaternionData(OpenRTM_aist.ByteDataStreamBase): + """ + """ + + ## + # @if jp + # @brief コンストラクタ + # + # コンストラクタ + # + # @param self + # + # @else + # @brief Constructor + # + # @param self + # + # @endif + def __init__(self): + pass + + ## + # @if jp + # @brief デストラクタ + # + # + # @param self + # + # @else + # + # @brief self + # + # @endif + def __del__(self): + pass + + ## + # @if jp + # @brief 設定初期化 + # + # + # @param prop 設定情報 + # + # @else + # + # @brief Initializing configuration + # + # + # @param prop Configuration information + # + # @endif + # virtual ReturnCode init(coil::Properties& prop) = 0; + def init(self, prop): + pass + + ## + # @if jp + # @brief データの変換(omniORB->ROS2) + # + # + # @param data omniORBのデータ + # @return ret、value + # ret:SERIALIZE_OK:成功、SERIALIZE_ERROR:失敗、SERIALIZE_NOTFOUND:指定のシリアライザがない + # value:ROS2のデータ + # + # @else + # + # @brief + # + # + # @param data + # @return + # + # @endif + + def serialize(self, data): + msg = QuaternionStamped() + msg.header.stamp.sec = data.tm.sec + msg.header.stamp.nanosec = data.tm.nsec + msg.quaternion.x = float(data.data.x) + msg.quaternion.y = float(data.data.y) + msg.quaternion.z = float(data.data.z) + msg.quaternion.w = float(data.data.w) + + return OpenRTM_aist.ByteDataStreamBase.SERIALIZE_OK, msg + + ## + # @if jp + # @brief データの変換(ROS2->omniORB) + # + # @param self + # @param bdata ROS2のデータ + # @param data_type omniORBのデータ + # @return ret、value + # ret:SERIALIZE_OK:成功、SERIALIZE_ERROR:失敗、SERIALIZE_NOTFOUND:指定のシリアライザがない + # value:変換後のデータ + # + # @else + # + # @brief + # + # @param cdr + # @param data_type + # @return + # + # @endif + def deserialize(self, bdata, data_type): + try: + data_type.tm.sec = bdata.header.stamp.sec + data_type.tm.nsec = bdata.header.stamp.nanosec + data_type.data.x = bdata.quaternion.x + data_type.data.y = bdata.quaternion.y + data_type.data.z = bdata.quaternion.z + data_type.data.w = bdata.quaternion.w + return OpenRTM_aist.ByteDataStreamBase.SERIALIZE_OK, data_type + except BaseException: + return OpenRTM_aist.ByteDataStreamBase.SERIALIZE_NOT_SUPPORT_ENDIAN, data_type + + +## +# @if jp +# @brief QuaternionStamped型のシリアライザの初期化 +# +# +# @else +# @brief +# +# +# @endif +# +def ROS2QuaternionInit(): + OpenRTM_aist.SerializerFactories.instance().addSerializer("ros2:geometry_msgs/QuaternionStamped", + ROS2QuaternionData, RTC.TimedQuaternion) + ROS2MessageInfo.ROS2MessageInfoList.instance().addInfo("ros2:geometry_msgs/QuaternionStamped", + ROS2MessageInfo.ROS2MessageInfo( + QuaternionStamped)) + + +## +# @if jp +# @class ROS2Vector3DData +# @brief Vector3Stamped型のシリアライザ +# +# @else +# @class ROS2Vector3DData +# @brief +# +# +# @endif +class ROS2Vector3DData(OpenRTM_aist.ByteDataStreamBase): + """ + """ + + ## + # @if jp + # @brief コンストラクタ + # + # コンストラクタ + # + # @param self + # + # @else + # @brief Constructor + # + # @param self + # + # @endif + def __init__(self): + pass + + ## + # @if jp + # @brief デストラクタ + # + # + # @param self + # + # @else + # + # @brief self + # + # @endif + def __del__(self): + pass + + ## + # @if jp + # @brief 設定初期化 + # + # + # @param prop 設定情報 + # + # @else + # + # @brief Initializing configuration + # + # + # @param prop Configuration information + # + # @endif + # virtual ReturnCode init(coil::Properties& prop) = 0; + def init(self, prop): + pass + + ## + # @if jp + # @brief データの変換(omniORB->ROS2) + # + # + # @param data omniORBのデータ + # @return ret、value + # ret:SERIALIZE_OK:成功、SERIALIZE_ERROR:失敗、SERIALIZE_NOTFOUND:指定のシリアライザがない + # value:ROS2のデータ + # + # @else + # + # @brief + # + # + # @param data + # @return + # + # @endif + + def serialize(self, data): + msg = Vector3Stamped() + msg.header.stamp.sec = data.tm.sec + msg.header.stamp.nanosec = data.tm.nsec + msg.vector.x = float(data.data.x) + msg.vector.y = float(data.data.y) + msg.vector.z = float(data.data.z) + + return OpenRTM_aist.ByteDataStreamBase.SERIALIZE_OK, msg + + ## + # @if jp + # @brief データの変換(ROS2->omniORB) + # + # @param self + # @param bdata ROS2のデータ + # @param data_type omniORBのデータ + # @return ret、value + # ret:SERIALIZE_OK:成功、SERIALIZE_ERROR:失敗、SERIALIZE_NOTFOUND:指定のシリアライザがない + # value:変換後のデータ + # + # @else + # + # @brief + # + # @param cdr + # @param data_type + # @return + # + # @endif + def deserialize(self, bdata, data_type): + try: + data_type.tm.sec = bdata.header.stamp.sec + data_type.tm.nsec = bdata.header.stamp.nanosec + data_type.data.x = bdata.vector.x + data_type.data.y = bdata.vector.y + data_type.data.z = bdata.vector.z + return OpenRTM_aist.ByteDataStreamBase.SERIALIZE_OK, data_type + except BaseException: + return OpenRTM_aist.ByteDataStreamBase.SERIALIZE_NOT_SUPPORT_ENDIAN, data_type + + +## +# @if jp +# @brief Vector3Stamped型のシリアライザの初期化 +# +# +# @else +# @brief +# +# +# @endif +# +def ROS2Vector3DInit(): + OpenRTM_aist.SerializerFactories.instance().addSerializer("ros2:geometry_msgs/Vector3Stamped", + ROS2Vector3DData, RTC.TimedVector3D) + ROS2MessageInfo.ROS2MessageInfoList.instance().addInfo("ros2:geometry_msgs/Vector3Stamped", + ROS2MessageInfo.ROS2MessageInfo( + Vector3Stamped)) + + +## +# @if jp +# @class ROS2CameraImageData +# @brief Image型のシリアライザ +# +# @else +# @class ROS2CameraImageData +# @brief +# +# +# @endif +class ROS2CameraImageData(OpenRTM_aist.ByteDataStreamBase): + """ + """ + + ## + # @if jp + # @brief コンストラクタ + # + # コンストラクタ + # + # @param self + # + # @else + # @brief Constructor + # + # @param self + # + # @endif + def __init__(self): + pass + + ## + # @if jp + # @brief デストラクタ + # + # + # @param self + # + # @else + # + # @brief self + # + # @endif + def __del__(self): + pass + + ## + # @if jp + # @brief 設定初期化 + # + # + # @param prop 設定情報 + # + # @else + # + # @brief Initializing configuration + # + # + # @param prop Configuration information + # + # @endif + # virtual ReturnCode init(coil::Properties& prop) = 0; + def init(self, prop): + pass + + ## + # @if jp + # @brief データの変換(omniORB->ROS2) + # + # + # @param data omniORBのデータ + # @return ret、value + # ret:SERIALIZE_OK:成功、SERIALIZE_ERROR:失敗、SERIALIZE_NOTFOUND:指定のシリアライザがない + # value:ROS2のデータ + # + # @else + # + # @brief + # + # + # @param data + # @return + # + # @endif + + def serialize(self, data): + msg = Image() + msg.header.stamp.sec = data.tm.sec + msg.header.stamp.nanosec = data.tm.nsec + msg.height = data.height + msg.width = data.width + if not data.format: + msg.encoding = "rgb8" + else: + msg.encoding = data.format + msg.step = 1920 + msg.data = data.pixels + + return OpenRTM_aist.ByteDataStreamBase.SERIALIZE_OK, msg + + ## + # @if jp + # @brief データの変換(ROS2->omniORB) + # + # @param self + # @param bdata ROS2のデータ + # @param data_type omniORBのデータ + # @return ret、value + # ret:SERIALIZE_OK:成功、SERIALIZE_ERROR:失敗、SERIALIZE_NOTFOUND:指定のシリアライザがない + # value:変換後のデータ + # + # @else + # + # @brief + # + # @param cdr + # @param data_type + # @return + # + # @endif + def deserialize(self, bdata, data_type): + try: + data_type.tm.sec = bdata.header.stamp.sec + data_type.tm.nsec = bdata.header.stamp.nanosec + data_type.height = bdata.height + data_type.width = bdata.width + data_type.format = bdata.encoding + data_type.pixels = bdata.data.tobytes() + return OpenRTM_aist.ByteDataStreamBase.SERIALIZE_OK, data_type + except BaseException: + return OpenRTM_aist.ByteDataStreamBase.SERIALIZE_NOT_SUPPORT_ENDIAN, data_type + + +## +# @if jp +# @brief Image型のシリアライザの初期化 +# +# +# @else +# @brief +# +# +# @endif +# +def ROS2CameraImageInit(): + OpenRTM_aist.SerializerFactories.instance().addSerializer("ros2:sensor_msgs/Image", + ROS2CameraImageData, RTC.CameraImage) + ROS2MessageInfo.ROS2MessageInfoList.instance().addInfo("ros2:sensor_msgs/Image", + ROS2MessageInfo.ROS2MessageInfo( + Image)) + + +## +# @if jp +# @brief 各種シリアライザの初期化関数 +# +# +# @else +# @brief +# +# +# @endif +# +def ROS2SerializerInit(): + ROS2BasicDataInit(Float32, "ros2:std_msgs/Float32") + ROS2BasicDataInit(Float64, "ros2:std_msgs/Float64") + ROS2BasicDataInit(Int8, "ros2:std_msgs/Int8") + ROS2BasicDataInit(Int16, "ros2:std_msgs/Int16") + ROS2BasicDataInit(Int32, "ros2:std_msgs/Int32") + ROS2BasicDataInit(Int64, "ros2:std_msgs/Int64") + ROS2BasicDataInit(UInt8, "ros2:std_msgs/UInt8") + ROS2BasicDataInit(UInt16, "ros2:std_msgs/UInt16") + ROS2BasicDataInit(UInt32, "ros2:std_msgs/UInt32") + ROS2BasicDataInit(UInt64, "ros2:std_msgs/UInt64") + ROS2BasicDataInit(String, "ros2:std_msgs/String") + + ROS2BasicDataInit(Float32MultiArray, "ros2:std_msgs/Float32MultiArray") + ROS2BasicDataInit(Float64MultiArray, "ros2:std_msgs/Float64MultiArray") + ROS2BasicDataInit(Int8MultiArray, "ros2:std_msgs/Int8MultiArray") + ROS2BasicDataInit(Int16MultiArray, "ros2:std_msgs/Int16MultiArray") + ROS2BasicDataInit(Int32MultiArray, "ros2:std_msgs/Int32MultiArray") + ROS2BasicDataInit(Int64MultiArray, "ros2:std_msgs/Int64MultiArray") + ROS2BasicDataInit(UInt8MultiArray, "ros2:std_msgs/UInt8MultiArray") + ROS2BasicDataInit(UInt16MultiArray, "ros2:std_msgs/UInt16MultiArray") + ROS2BasicDataInit(UInt32MultiArray, "ros2:std_msgs/UInt32MultiArray") + ROS2BasicDataInit(UInt64MultiArray, "ros2:std_msgs/UInt64MultiArray") + + ROS2Point3DInit() + ROS2QuaternionInit() + ROS2Vector3DInit() + ROS2CameraImageInit() diff --git a/OpenRTM_aist/ext/transport/ROS2Transport/ROS2TopicManager.py b/OpenRTM_aist/ext/transport/ROS2Transport/ROS2TopicManager.py new file mode 100644 index 00000000..25230ed9 --- /dev/null +++ b/OpenRTM_aist/ext/transport/ROS2Transport/ROS2TopicManager.py @@ -0,0 +1,245 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- + +## +# @file ROS2TopicManager.py +# @brief ROS2 Topic Manager class +# @date $Date$ +# @author Nobuhiko Miyamoto +# +# Copyright (C) 2019 +# Noriaki Ando +# Robot Innovation Research Center, +# National Institute of +# Advanced Industrial Science and Technology (AIST), Japan +# All rights reserved. +# +# $Id$ +# + +import OpenRTM_aist +import ROS2MessageInfo +import rclpy +from rclpy.node import Node +import threading + + +manager = None +mutex = threading.RLock() + +## +# @if jp +# @class ROS2TopicManager +# @brief ROS2トピックを管理するクラス +# +# +# @else +# @class ROS2TopicManager +# @brief +# +# +# @endif + + +class ROS2TopicManager(object): + """ + """ + + ## + # @if jp + # @brief コンストラクタ + # + # コンストラクタ + # + # @param self + # + # @else + # @brief Constructor + # + # @param self + # + # @endif + def __init__(self): + self._thread = None + self._loop = True + + #mgr = OpenRTM_aist.Manager.instance() + # mgr.addManagerActionListener(ManagerActionListener(self)) + #self._rtcout = mgr.getLogbuf("ROS2TopicManager") + + ## + # @if jp + # @brief デストラクタ + # + # + # @param self + # + # @else + # + # @brief self + # + # @endif + + def __del__(self): + pass + + ## + # @if jp + # @brief ROS2初期化 + # + # @param self + # @param args rclpy.initの引数 + # + # @else + # + # @brief + # + # @param self + # @param args + # + # @endif + + def start(self, args=[]): + rclpy.init(args=args) + self._node = Node("openrtm") + + def spin(): + while self._loop: + rclpy.spin_once(self._node, timeout_sec=0.01) + self._thread = threading.Thread(target=spin) + self._thread.daemon = True + self._thread.start() + + ## + # @if jp + # @brief 終了処理 + # + # @param self + # + # @else + # + # @brief + # + # @param self + # + # @endif + + def shutdown(self): + if self._node: + self._loop = False + self._node.destroy_node() + # rclpy.try_shutdown() + # if self._thread: + # self._thread.join() + + ## + # @if jp + # @brief Publisherオブジェクト生成 + # + # @param self + # @param msgtype メッセージ型 + # @param topic トピック名 + # @return Publisherオブジェクト + # + # @else + # + # @brief + # + # @param self + # @param msgtype + # @param topic + # @return + # + # @endif + + def createPublisher(self, msgtype, topic): + global mutex + guard = OpenRTM_aist.ScopedLock(mutex) + if self._node: + return self._node.create_publisher(msgtype, topic) + return None + + ## + # @if jp + # @brief Subscriberオブジェクト生成 + # + # @param self + # @param msgtype メッセージ型 + # @param topic トピック名 + # @param listener コールバック関数 + # @return Subscriberオブジェクト + # + # @else + # + # @brief + # + # @param self + # @param msgtype + # @param topic + # @param listener + # @return + # + # @endif + def createSubscriber(self, msgtype, topic, listener): + global mutex + guard = OpenRTM_aist.ScopedLock(mutex) + if self._node: + return self._node.create_subscription(msgtype, topic, listener) + return None + + def deletePublisher(self, pub): + pass + + def deleteSubscriber(self, sub): + pass + + ## + # @if jp + # @brief インスタンス取得 + # + # @return インスタンス + # + # @else + # + # @brief + # + # @return インスタンス + # + # @endif + + def instance(args=[]): + global manager + global mutex + + guard = OpenRTM_aist.ScopedLock(mutex) + if manager is None: + manager = ROS2TopicManager() + manager.start(args) + + return manager + + instance = staticmethod(instance) + + ## + # @if jp + # @brief ROS2TopicManagerを初期化している場合に終了処理を呼び出す + # + # + # @else + # + # @brief + # + # + # @endif + + def shutdown_global(): + global manager + global mutex + + guard = OpenRTM_aist.ScopedLock(mutex) + if manager is not None: + manager.shutdown() + + manager = None + + shutdown_global = staticmethod(shutdown_global) diff --git a/OpenRTM_aist/ext/transport/ROS2Transport/ROS2Transport.py b/OpenRTM_aist/ext/transport/ROS2Transport/ROS2Transport.py new file mode 100644 index 00000000..f5019279 --- /dev/null +++ b/OpenRTM_aist/ext/transport/ROS2Transport/ROS2Transport.py @@ -0,0 +1,96 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- + +## +# @file ROS2Transport.py +# @brief ROS2 Transport class +# @date $Date$ +# @author Nobuhiko Miyamoto +# +# Copyright (C) 2019 +# Noriaki Ando +# Robot Innovation Research Center, +# National Institute of +# Advanced Industrial Science and Technology (AIST), Japan +# All rights reserved. +# +# $Id$ +# + +import OpenRTM_aist +import ROS2InPort +import ROS2OutPort +import ROS2Serializer +from ROS2TopicManager import ROS2TopicManager + + +## +# @if jp +# @class ManagerActionListener +# @brief ROS2TopicManagerの終了処理を行うマネージャアクションリスナ +# +# +# @else +# @class ManagerActionListener +# @brief +# +# +# @endif +class ManagerActionListener: + ## + # @if jp + # @brief コンストラクタ + # + # + # @param self + # + # @else + # + # @brief self + # + # @endif + def __init__(self): + pass + + def preShutdown(self): + pass + ## + # @if jp + # @brief RTMマネージャ終了後にROSTopicManagerの終了処理を実行 + # + # + # @param self + # + # @else + # + # @brief self + # + # @endif + + def postShutdown(self): + ROS2TopicManager.shutdown_global() + + def preReinit(self): + pass + + def postReinit(self): + pass + + +## +# @if jp +# @brief モジュール登録関数 +# +# +# @else +# @brief +# +# +# @endif +# +def ROS2TransportInit(mgr): + ROS2InPort.ROS2InPortInit() + ROS2OutPort.ROS2OutPortInit() + ROS2Serializer.ROS2SerializerInit() + + mgr.addManagerActionListener(ManagerActionListener()) diff --git a/OpenRTM_aist/ext/transport/ROS2Transport/__init__.py b/OpenRTM_aist/ext/transport/ROS2Transport/__init__.py new file mode 100644 index 00000000..270be2a2 --- /dev/null +++ b/OpenRTM_aist/ext/transport/ROS2Transport/__init__.py @@ -0,0 +1 @@ +# Empty file diff --git a/OpenRTM_aist/ext/transport/ROS2Transport/rtc.conf b/OpenRTM_aist/ext/transport/ROS2Transport/rtc.conf new file mode 100644 index 00000000..8d31c18c --- /dev/null +++ b/OpenRTM_aist/ext/transport/ROS2Transport/rtc.conf @@ -0,0 +1,10 @@ +logger.enable: YES +logger.file_name: stdout +logger.log_level: ERROR + +manager.modules.load_path: . +#manager.components.precreate: ConsoleOut +#manager.components.preconnect: ConsoleOut0.in?port=ConsoleIn0.out +manager.modules.preload: ROS2Transport.py +manager.components.preconnect: ConsoleOut0.in?interface_type=ros2&marshaling_type=ROS2Float32, ConsoleIn0.out?interface_type=ros2&marshaling_type=ROS2Float32 +manager.components.preactivation: ConsoleOut0, ConsoleIn0 diff --git a/OpenRTM_aist/ext/transport/ROSTransport/ROSInPort.py b/OpenRTM_aist/ext/transport/ROSTransport/ROSInPort.py new file mode 100644 index 00000000..11315783 --- /dev/null +++ b/OpenRTM_aist/ext/transport/ROSTransport/ROSInPort.py @@ -0,0 +1,736 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- + +## +# @file ROSInPort.py +# @brief ROS OutPort class +# @date $Date$ +# @author Nobuhiko Miyamoto +# +# Copyright (C) 2019 +# Noriaki Ando +# Robot Innovation Research Center, +# National Institute of +# Advanced Industrial Science and Technology (AIST), Japan +# All rights reserved. +# +# $Id$ +# + +import OpenRTM_aist +import rosgraph.xmlrpc +import socket +import threading +import select +try: + import xmlrpclib +except BaseException: + import xmlrpc.client as xmlrpclib + +from rosgraph.network import read_ros_handshake_header, write_ros_handshake_header +from ROSTopicManager import ROSTopicManager +import ROSMessageInfo +import struct +import sys + +try: + from cStringIO import StringIO +except ImportError: + from io import StringIO, BytesIO + + +## +# @if jp +# @class ROSInPort +# @brief ROS Subscriberに対応するクラス +# InPortProviderオブジェクトとして使用する +# +# @else +# @class ROSInPort +# @brief +# +# +# @endif +class ROSInPort(OpenRTM_aist.InPortProvider): + """ + """ + + ## + # @if jp + # @brief コンストラクタ + # + # コンストラクタ + # ポートプロパティに以下の項目を設定する。 + # - インターフェースタイプ : ros + # - データフロータイプ : Push + # + # @param self + # + # @else + # @brief Constructor + # + # Constructor + # Set the following items to port properties + # - Interface type : CORBA_Any + # - Data flow type : Push, Pull + # + # @param self + # + # @endif + # + def __init__(self): + OpenRTM_aist.InPortProvider.__init__(self) + + # PortProfile setting + self.setInterfaceType("ros") + + self._profile = None + self._listeners = None + + self._client = None + + self._topic = "chatter" + self._callerid = "" + self._messageType = "ros:std_msgs/Float32" + self._roscorehost = "localhost" + self._roscoreport = "11311" + + self._tcp_connecters = {} + self._pubnum = 0 + + self._mutex = threading.RLock() + + ## + # @if jp + # @brief デストラクタ + # + # デストラクタ + # + # @param self + # + # @else + # @brief Destructor + # + # Destructor + # + # @param self + # + # @endif + # + def __del__(self): + return + + ## + # @if jp + # @brief 終了処理 + # + # @param self + # + # @else + # @brief + # + # @param self + # + # @endif + # + + def exit(self): + self._rtcout.RTC_PARANOID("exit()") + if self._client is not None: + self._rtcout.RTC_PARANOID("unregister Subscriber()") + try: + ret, _, __ = self._client.unregisterSubscriber( + self._callerid, self._topic, self._topicmgr.getURI()) + if ret != 1: + self._rtcout.RTC_ERROR("unregister subscriber error") + except xmlrpclib.Fault as err: + self._rtcout.RTC_ERROR("XML-RPC Error:%s", err.faultString) + + if self._topicmgr is not None: + self._rtcout.RTC_VERBOSE("remove subscriber") + self._topicmgr.removeSubscriber(self) + + for k, connector in self._tcp_connecters.items(): + try: + self._rtcout.RTC_VERBOSE("connection close") + connector["socket"].shutdown(socket.SHUT_RDWR) + connector["socket"].close() + connector["listener"].shutdown() + connector["thread"].join() + except BaseException: + self._rtcout.RTC_ERROR("socket shutdown error") + + ## + # @if jp + # @brief 接続済みのソケットを終了させる + # + # @param self + # @param uri ソケットの接続先のURI + # + # @else + # @brief + # + # @param self + # @param uri + # + # @endif + # + def deleteSocket(self, uri): + if uri in self._tcp_connecters: + try: + self._rtcout.RTC_VERBOSE("close socket") + self._tcp_connecters[uri].shutdown(socket.SHUT_RDWR) + self._tcp_connecters[uri]["socket"].close() + self._tcp_connecters[uri]["listener"].shutdown() + self._tcp_connecters[uri]["thread"].join() + del self._tcp_connecters[uri] + except BaseException: + self._rtcout.RTC_ERROR("close socket error") + + ## + # @if jp + # @brief 初期化 + # + # @param self + # @param prop 接続設定 + # marshaling_type シリアライザの種類 デフォルト:ROSFloat32 + # topic トピック名 デフォルト chatter + # roscore_host roscoreのホスト名 デフォルト:localhost + # roscore_port roscoreのポート番号 デフォルト:11311 + # + # @else + # @brief + # + # @param self + # @param prop + # + # @endif + # + # virtual void init(coil::Properties& prop); + def init(self, prop): + self._rtcout.RTC_PARANOID("init()") + if not prop.propertyNames(): + self._rtcout.RTC_DEBUG("Property is empty.") + return + + self._topicmgr = ROSTopicManager.instance() + if self._topicmgr.existSubscriber(self): + self._rtcout.RTC_VERBOSE("Subscriber already exists.") + return + + self._messageType = prop.getProperty( + "marshaling_type", "ros:std_msgs/Float32") + self._topic = prop.getProperty("ros.topic", "chatter") + self._topic = "/" + self._topic + self._roscorehost = prop.getProperty("ros.roscore.host", "localhost") + self._roscoreport = prop.getProperty("ros.roscore.port", "11311") + + self._rtcout.RTC_VERBOSE("topic name: %s", self._topic) + self._rtcout.RTC_VERBOSE( + "roscore address: %s:%s", + (self._roscorehost, + self._roscoreport)) + + self._callerid = prop.getProperty("ros.node.name") + if not self._callerid: + self._callerid = str(OpenRTM_aist.uuid1()) + self._callerid = "/" + self._callerid + + factory = ROSMessageInfo.ROSMessageInfoList.instance() + info = factory.getInfo(self._messageType) + if info: + info_type = info.datatype() + else: + self._rtcout.RTC_ERROR("can not found %s", self._messageType) + return + + self._rtcout.RTC_VERBOSE("caller id: %s", self._callerid) + + self._topicmgr.addSubscriber(self) + + self._client = xmlrpclib.ServerProxy( + 'http://' + self._roscorehost + ":" + self._roscoreport) + + try: + _, __, val = self._client.registerSubscriber( + self._callerid, self._topic, info_type, self._topicmgr.getURI()) + except xmlrpclib.Fault as err: + self._rtcout.RTC_ERROR("XML-RPC ERROR: %s", err.faultString) + return + self.connect(self._callerid, self._topic, val) + + ## + # @if jp + # @brief publisherと接続 + # + # @param self + # @param caller_id 呼び出しID + # @param topic トピック名 + # @param publishers publisherのURIのリスト + # + # @else + # @brief + # + # @param self + # @param caller_id + # @param topic + # @param publishers + # + # @endif + # + def connect(self, caller_id, topic, publishers): + self._rtcout.RTC_VERBOSE("connect()") + if topic != self._topic: + self._rtcout.RTC_WARN( + "Topic name is not match(%s:%s)", (topic, self._topic)) + return + + for uri in publishers: + if uri in self._tcp_connecters: + continue + self._rtcout.RTC_PARANOID( + "connectTCP(%s, %s, %s)", (caller_id, topic, uri)) + try: + pub = xmlrpclib.ServerProxy(uri) + ret, message, result = pub.requestTopic( + self._callerid, topic, [['TCPROS']]) + except BaseException: + self._rtcout.RTC_ERROR("Failed connect %s", uri) + continue + + if ret == -1: + self._rtcout.RTC_WARN("requestTopic error: %s", message) + continue + elif ret == 0: + self._rtcout.RTC_WARN("requestTopic error: %s", message) + continue + else: + _, dest_addr, dest_port = result + sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) + sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1) + sock.setsockopt(socket.SOL_TCP, socket.TCP_KEEPCNT, 9) + sock.setsockopt(socket.SOL_TCP, socket.TCP_KEEPIDLE, 60) + sock.setsockopt(socket.SOL_TCP, socket.TCP_KEEPINTVL, 10) + sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1) + sock.settimeout(60.0) + sock.connect((dest_addr, dest_port)) + + fileno = sock.fileno() + if hasattr(select, 'poll'): + poller = select.poll() + poller.register(fileno, select.POLLOUT) + ready = False + + while not ready: + events = poller.poll() + for _, flag in events: + if flag & select.POLLOUT: + ready = True + else: + ready = None + while not ready: + try: + _, ready, _ = select.select([], [fileno], []) + except ValueError: + self._rtcout.RTC_ERROR("ValueError") + return + + factory = ROSMessageInfo.ROSMessageInfoList.instance() + info = factory.getInfo(self._messageType) + if(info): + info_type = info.datatype() + info_md5sum = info.md5sum() + info_message_definition = info.message_definition() + else: + self._rtcout.RTC_ERROR( + "Can not found %s", self._messageType) + + sock.setblocking(1) + fields = {'topic': topic, + 'message_definition': info_message_definition, + 'tcp_nodelay': '0', + 'md5sum': info_md5sum, + 'type': info_type, + 'callerid': self._callerid} + + try: + write_ros_handshake_header(sock, fields) + except rosgraph.network.ROSHandshakeException: + self._rtcout.RTC_ERROR("write ROS handshake header") + continue + if sys.version_info[0] == 3: + read_buff = BytesIO() + else: + read_buff = StringIO() + sock.setblocking(1) + + try: + read_ros_handshake_header(sock, read_buff, 65536) + except rosgraph.network.ROSHandshakeException: + self._rtcout.RTC_ERROR("read ROS handshake header") + continue + + listener = SubListener(self, sock, uri) + + self._rtcout.RTC_VERBOSE("Subscriber Listener thread start") + task = threading.Thread(target=listener.recieve, args=()) + task.start() + + self._tcp_connecters[uri] = { + "socket": sock, + "listener": listener, + "thread": task, + "id": self._pubnum} + self._pubnum += 1 + + # virtual void setBuffer(BufferBase* buffer); + + def setBuffer(self, buffer): + return + + ## + # @if jp + # @brief コネクタリスナの設定 + # + # @param info 接続情報 + # @param listeners リスナ + # + # @else + # @brief + # + # @param info + # @param listeners + # + # @endif + # + # void setListener(ConnectorInfo& info, + # ConnectorListeners* listeners); + def setListener(self, info, listeners): + self._profile = info + self._listeners = listeners + return + + ## + # @if jp + # @brief バッファにデータを書き込む + # + # 設定されたバッファにデータを書き込む。 + # + # @param data 書込対象データ + # + # @else + # @brief Write data into the buffer + # + # Write data into the specified buffer. + # + # @param data The target data for writing + # + # @endif + # + + def put(self, data): + guard = OpenRTM_aist.Guard.ScopedLock(self._mutex) + try: + self._rtcout.RTC_PARANOID("ROSInPort.put()") + if not self._connector: + self.onReceiverError(data) + return + + self._rtcout.RTC_PARANOID("received data size: %d", len(data)) + + data = self.onReceived(data) + + ret = self._connector.write(data) + + self.convertReturn(ret, data) + + except BaseException: + self._rtcout.RTC_TRACE(OpenRTM_aist.Logger.print_exception()) + + def convertReturn(self, status, data): + if status == OpenRTM_aist.BufferStatus.BUFFER_OK: + self.onBufferWrite(data) + return + + elif status == OpenRTM_aist.BufferStatus.BUFFER_ERROR: + self.onReceiverError(data) + return + + elif status == OpenRTM_aist.BufferStatus.BUFFER_FULL: + data = self.onBufferFull(data) + self.onReceiverFull(data) + return + + elif status == OpenRTM_aist.BufferStatus.BUFFER_EMPTY: + return + + elif status == OpenRTM_aist.BufferStatus.PRECONDITION_NOT_MET: + self.onReceiverError(data) + return + + elif status == OpenRTM_aist.BufferStatus.TIMEOUT: + data = self.onBufferWriteTimeout(data) + self.onReceiverTimeout(data) + return + + else: + self.onReceiverError(data) + return + + ## + # @brief Connector data listener functions + # + # inline void onBufferWrite(const cdrMemoryStream& data) + + def onBufferWrite(self, data): + if self._listeners is not None and self._profile is not None: + _, data = self._listeners.notifyData( + OpenRTM_aist.ConnectorDataListenerType.ON_BUFFER_WRITE, self._profile, data) + return data + + # inline void onBufferFull(const cdrMemoryStream& data) + + def onBufferFull(self, data): + if self._listeners is not None and self._profile is not None: + _, data = self._listeners.notifyData( + OpenRTM_aist.ConnectorDataListenerType.ON_BUFFER_FULL, self._profile, data) + return data + + # inline void onBufferWriteTimeout(const cdrMemoryStream& data) + + def onBufferWriteTimeout(self, data): + if self._listeners is not None and self._profile is not None: + _, data = self._listeners.notifyData( + OpenRTM_aist.ConnectorDataListenerType.ON_BUFFER_WRITE_TIMEOUT, self._profile, data) + return data + + # inline void onBufferWriteOverwrite(const cdrMemoryStream& data) + def onBufferWriteOverwrite(self, data): + if self._listeners is not None and self._profile is not None: + _, data = self._listeners.notifyData( + OpenRTM_aist.ConnectorDataListenerType.ON_BUFFER_OVERWRITE, self._profile, data) + return data + + # inline void onReceived(const cdrMemoryStream& data) + + def onReceived(self, data): + if self._listeners is not None and self._profile is not None: + _, data = self._listeners.notifyData( + OpenRTM_aist.ConnectorDataListenerType.ON_RECEIVED, self._profile, data) + return data + + # inline void onReceiverFull(const cdrMemoryStream& data) + + def onReceiverFull(self, data): + if self._listeners is not None and self._profile is not None: + _, data = self._listeners.notifyData( + OpenRTM_aist.ConnectorDataListenerType.ON_RECEIVER_FULL, self._profile, data) + return data + + # inline void onReceiverTimeout(const cdrMemoryStream& data) + + def onReceiverTimeout(self, data): + if self._listeners is not None and self._profile is not None: + _, data = self._listeners.notifyData( + OpenRTM_aist.ConnectorDataListenerType.ON_RECEIVER_TIMEOUT, self._profile, data) + return data + + # inline void onReceiverError(const cdrMemoryStream& data) + + def onReceiverError(self, data): + if self._listeners is not None and self._profile is not None: + _, data = self._listeners.notifyData( + OpenRTM_aist.ConnectorDataListenerType.ON_RECEIVER_ERROR, self._profile, data) + return data + + ## + # @if jp + # @brief ノード名の取得 + # + # @return ノード名 + # + # @else + # @brief + # + # @return + # + # @endif + # + def getName(self): + self._rtcout.RTC_VERBOSE("getName") + return self._callerid + + ## + # @if jp + # @brief メッセージ型の取得 + # + # @return メッセージ型 + # + # @else + # @brief + # + # @return + # + # @endif + # + def datatype(self): + self._rtcout.RTC_VERBOSE("datatype") + return self._messageType + + ## + # @if jp + # @brief コネクタの情報取得 + # + # @return コネクタの情報のリスト + # + # @else + # @brief + # + # @return + # + # @endif + # + def getInfo(self): + self._rtcout.RTC_VERBOSE("getInfo") + cons = [] + for k, connector in self._tcp_connecters.items(): + cons.append([connector["id"], k, "i", + "TCPROS", self._topic, True, ""]) + return cons + +## +# @if jp +# @class SubListener +# @brief ROS Subscriberのデータ受信時のリスナ +# +# +# @else +# @class SubListener +# @brief +# +# +# @endif + + +class SubListener: + ## + # @if jp + # @brief コンストラクタ + # + # @param self + # @param sub ROSInPort + # @param sock ソケット + # @param uri 接続先のURI + # + # @else + # @brief Constructor + # + # @param self + # @param sub + # @param sock + # @param uri + # + # @endif + # + def __init__(self, sub, sock, uri): + self._sub = sub + self._sock = sock + self._uri = uri + self._shutdown = False + ## + # @if jp + # @brief 終了処理開始 + # + # @param self + # + # @else + # @brief + # + # @param self + # + # @endif + # + + def shutdown(self): + self._shutdown = True + + ## + # @if jp + # @brief 受信処理 + # + # @param self + # + # @else + # @brief + # + # @param self + # + # @endif + # + def recieve(self): + buff_size = 65536 + start = 0 + size = -1 + if sys.version_info[0] == 3: + b = BytesIO() + else: + b = StringIO() + self._sock.setblocking(True) + while not self._shutdown: + try: + btell = b.tell() + pos = start + left = btell - pos + if left > 4: + b.seek(pos) + if size < 0 and btell >= 4: + (size,) = struct.unpack(' 0: + if left >= size: + start = 0 + b.seek(start) + data = b.read(size+4) + self._sub.put(data) + b.seek(start) + pos += size + size = -1 + if btell == pos: + b.seek(start) + b.truncate(start) + elif pos != start: + b.seek(pos) + leftovers = b.read(btell-pos) + b.truncate(start + len(leftovers)) + b.seek(start) + b.write(leftovers) + else: + b.seek(btell) + if b.tell() <= size+4: + d = self._sock.recv(buff_size) + if d: + b.write(d) + else: + raise BaseException + except BaseException: + self._sub.deleteSocket(self._uri) + return + + +## +# @if jp +# @brief モジュール登録関数 +# +# +# @else +# @brief +# +# +# @endif +# +def ROSInPortInit(): + factory = OpenRTM_aist.InPortProviderFactory.instance() + factory.addFactory("ros", + ROSInPort) diff --git a/OpenRTM_aist/ext/transport/ROSTransport/ROSMessageInfo.py b/OpenRTM_aist/ext/transport/ROSTransport/ROSMessageInfo.py new file mode 100644 index 00000000..af130507 --- /dev/null +++ b/OpenRTM_aist/ext/transport/ROSTransport/ROSMessageInfo.py @@ -0,0 +1,376 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- + +## +# @file ROSMessageInfo.py +# @brief ROS Message Info class +# @date $Date$ +# @author Nobuhiko Miyamoto +# +# Copyright (C) 2019 +# Noriaki Ando +# Robot Innovation Research Center, +# National Institute of +# Advanced Industrial Science and Technology (AIST), Japan +# All rights reserved. +# +# $Id$ +# + +import OpenRTM_aist + +## +# @if jp +# @class ROSMessageInfoBase +# @brief ROSメッセージ情報格納オブジェクトの基底クラス +# +# @else +# @class ROSOutPort +# @brief +# +# +# @endif + + +class ROSMessageInfoBase(object): + ## + # @if jp + # @brief コンストラクタ + # + # コンストラクタ + # + # @param self + # + # @else + # @brief Constructor + # + # @param self + # + # @endif + def __init__(self): + pass + ## + # @if jp + # @brief デストラクタ + # + # デストラクタ + # + # @param self + # + # @else + # @brief Destructor + # + # Destructor + # + # @param self + # + # @endif + # + + def __del__(self): + pass + + ## + # @if jp + # @brief メッセージの型名を取得 + # + # @param self + # @return 型名 + # + # @else + # @brief + # + # + # @param self + # @return + # + # @endif + # + def datatype(self): + return "" + + ## + # @if jp + # @brief メッセージのMD5チェックサムを取得 + # + # @param self + # @return MD5チェックサム + # + # @else + # @brief + # + # + # @param self + # @return + # + # @endif + # + def md5sum(self): + return "" + + ## + # @if jp + # @brief メッセージの詳細説明を取得 + # + # @param self + # @return 詳細説明 + # + # @else + # @brief + # + # + # @param self + # @return + # + # @endif + # + def message_definition(self): + return "" + + +## +# @if jp +# @class ROSMessageInfo +# @brief メッセージの情報格納クラス +# +# +# @else +# @class ROSMessageInfo +# @brief +# +# +# @endif +class ROSMessageInfo(ROSMessageInfoBase): + """ + """ + ## + # @if jp + # @brief コンストラクタ + # + # コンストラクタ + # + # @param self + # + # @else + # @brief Constructor + # + # @param self + # + # @endif + + def __init__(self, data_class): + super(ROSMessageInfo, self).__init__() + self._data_class = data_class + ## + # @if jp + # @brief デストラクタ + # + # + # @param self + # + # @else + # + # @brief self + # + # @endif + + def __del__(self): + pass + ## + # @if jp + # @brief メッセージの型名を取得 + # + # @param self + # @return 型名 + # + # @else + # @brief + # + # + # @param self + # @return + # + # @endif + # + + def datatype(self): + return self._data_class._type + ## + # @if jp + # @brief メッセージのMD5チェックサムを取得 + # + # @param self + # @return MD5チェックサム + # + # @else + # @brief + # + # + # @param self + # @return + # + # @endif + # + + def md5sum(self): + return self._data_class._md5sum + ## + # @if jp + # @brief メッセージのMD5チェックサムを取得 + # + # @param self + # @return MD5チェックサム + # + # @else + # @brief + # + # + # @param self + # @return + # + # @endif + # + + def message_definition(self): + return self._data_class._full_text + + +rosmessageinfolist = None + + +## +# @if jp +# @class ROSMessageInfoList +# @brief ROSメッセージ情報格納オブジェクト生成ファクトリ +# +# @else +# @class ROSMessageInfoList +# @brief +# +# +# @endif +class ROSMessageInfoList: + ## + # @if jp + # @brief コンストラクタ + # + # コンストラクタ + # + # @param self + # + # @else + # @brief Constructor + # + # @param self + # + # @endif + def __init__(self): + self._data = {} + + ## + # @if jp + # @brief デストラクタ + # + # デストラクタ + # + # @param self + # + # @else + # @brief Destructor + # + # Destructor + # + # @param self + # + # @endif + # + def __del__(self): + pass + + ## + # @if jp + # @brief インスタンス取得 + # + # + # @return インスタンス + # + # @else + # @brief + # + # + # @return + # + # @endif + # + def instance(): + global rosmessageinfolist + + if rosmessageinfolist is None: + rosmessageinfolist = ROSMessageInfoList() + + return rosmessageinfolist + + instance = staticmethod(instance) + + ## + # @if jp + # @brief ROSMessageInfoの追加 + # + # @param self + # @param id 名前 + # @param info ROSMessageInfo + # + # @else + # @brief + # + # @param self + # @param id + # @param info + # + # @endif + # + def addInfo(self, id, info): + self._data[id] = info + + ## + # @if jp + # @brief ROSMessageInfoの削除 + # + # @param self + # @param id 名前 + # @return 削除に成功した場合はTrue + # + # @else + # @brief + # + # @param self + # @param id + # @return + # + # @endif + # + def removeInfo(self, id): + if id in self._data: + del self._data[id] + return True + return False + + ## + # @if jp + # @brief 指定名のROSMessageInfoの取得 + # + # @param id 名前 + # @return ROSMessageInfo + # + # @else + # @brief + # + # @param id + # @return + # + # @endif + # + def getInfo(self, id): + if id in self._data: + return self._data[id] + return None diff --git a/OpenRTM_aist/ext/transport/ROSTransport/ROSOutPort.py b/OpenRTM_aist/ext/transport/ROSTransport/ROSOutPort.py new file mode 100644 index 00000000..486ba397 --- /dev/null +++ b/OpenRTM_aist/ext/transport/ROSTransport/ROSOutPort.py @@ -0,0 +1,511 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- + +## +# @file ROSOutPort.py +# @brief ROS OutPort class +# @date $Date$ +# @author Nobuhiko Miyamoto +# +# Copyright (C) 2019 +# Noriaki Ando +# Robot Innovation Research Center, +# National Institute of +# Advanced Industrial Science and Technology (AIST), Japan +# All rights reserved. +# +# $Id$ +# + +import OpenRTM_aist +from ROSTopicManager import ROSTopicManager +import ROSMessageInfo +try: + import xmlrpclib +except BaseException: + import xmlrpc.client as xmlrpclib +from rosgraph.network import read_ros_handshake_header, write_ros_handshake_header +import rosgraph.network +try: + from cStringIO import StringIO +except ImportError: + from io import StringIO, BytesIO +import socket +import select +import time +import sys + + +## +# @if jp +# @class ROSOutPort +# @brief ROS Publisherに対応するクラス +# InPortConsumerオブジェクトとして使用する +# +# @else +# @class ROSOutPort +# @brief +# +# +# @endif +class ROSOutPort(OpenRTM_aist.InPortConsumer): + """ + """ + + ## + # @if jp + # @brief コンストラクタ + # + # コンストラクタ + # + # @param self + # + # @else + # @brief Constructor + # + # @param self + # + # @endif + def __init__(self): + OpenRTM_aist.InPortConsumer.__init__(self) + self._rtcout = OpenRTM_aist.Manager.instance().getLogbuf("ROSOutPort") + self._properties = None + self._callerid = "" + self._messageType = "ros:std_msgs/Float32" + self._topic = "chatter" + self._roscorehost = "localhost" + self._roscoreport = "11311" + self._tcp_connecters = {} + self._subnum = 0 + + ## + # @if jp + # @brief デストラクタ + # + # デストラクタ + # + # @param self + # + # @else + # @brief Destructor + # + # Destructor + # + # @param self + # + # @endif + # + + def __del__(self): + self._rtcout.RTC_PARANOID("~ROSOutPort()") + + ## + # @if jp + # @brief 設定初期化 + # + # InPortConsumerの各種設定を行う + # + # @param self + # @param prop 接続設定 + # marshaling_type シリアライザの種類 デフォルト:ROSFloat32 + # topic トピック名 デフォルト chatter + # roscore_host roscoreのホスト名 デフォルト:localhost + # roscore_port roscoreのポート番号 デフォルト:11311 + # + # @else + # @brief Initializing configuration + # + # This operation would be called to configure this consumer + # in initialization. + # + # @param self + # @param prop + # + # @endif + # + # virtual void init(coil::Properties& prop); + def init(self, prop): + self._rtcout.RTC_PARANOID("init()") + + if not prop.propertyNames(): + self._rtcout.RTC_DEBUG("Property is empty.") + return + + self._topicmgr = ROSTopicManager.instance() + if self._topicmgr.existPublisher(self): + self._rtcout.RTC_VERBOSE("Publisher already exists.") + return + + self._properties = prop + + self._messageType = prop.getProperty( + "marshaling_type", "ros:std_msgs/Float32") + self._topic = prop.getProperty("ros.topic", "chatter") + self._topic = "/" + self._topic + self._roscorehost = prop.getProperty("ros.roscore.host", "localhost") + self._roscoreport = prop.getProperty("ros.roscore.port", "11311") + + self._rtcout.RTC_VERBOSE("topic name: %s", self._topic) + self._rtcout.RTC_VERBOSE( + "roscore address: %s:%s", + (self._roscorehost, + self._roscoreport)) + + self._callerid = prop.getProperty("ros.node.name") + if not self._callerid: + self._callerid = str(OpenRTM_aist.uuid1()) + self._callerid = "/" + self._callerid + + self._rtcout.RTC_VERBOSE("caller id: %s", self._callerid) + + self._topicmgr.addPublisher(self) + + self._client = xmlrpclib.ServerProxy( + 'http://' + self._roscorehost + ":" + self._roscoreport) + try: + self._client.registerPublisher( + self._callerid, + self._topic, + 'std_msgs/Float32', + self._topicmgr.getURI()) + except xmlrpclib.Fault as err: + self._rtcout.RTC_ERROR("XML-RPC ERROR: %s", err.faultString) + + ## + # @if jp + # @brief トピック名取得 + # + # + # @return トピック名 + # + # @else + # @brief get topic name + # + # @return topic name + # + # @endif + # + def getTopic(self): + self._rtcout.RTC_PARANOID("getTopic()") + return self._topic + + ## + # @if jp + # @brief Subscriberとの接続 + # + # + # @param self + # @param client_sock ソケット + # @param addr 接続先のURI + # + # @else + # @brief + # + # @param self + # @param client_sock + # @param addr + # + # @endif + # + def connect(self, client_sock, addr): + self._rtcout.RTC_PARANOID("connect()") + if addr in self._tcp_connecters: + self._rtcout.RTC_DEBUG("%s already exist", addr) + return + + try: + if sys.version_info[0] == 3: + header = read_ros_handshake_header( + client_sock, BytesIO(), 65536) + else: + header = read_ros_handshake_header( + client_sock, StringIO(), 65536) + except rosgraph.network.ROSHandshakeException: + self._rtcout.RTC_DEBUG("read ROS handshake exception") + return + except BaseException: + self._rtcout.RTC_ERROR(OpenRTM_aist.Logger.print_exception()) + + topic_name = header['topic'] + md5sum = header['md5sum'] + type_name = header['type'] + + self._rtcout.RTC_VERBOSE("Topic:%s", topic_name) + self._rtcout.RTC_VERBOSE("MD5sum:%s", md5sum) + self._rtcout.RTC_VERBOSE("Type:%s", type_name) + + factory = ROSMessageInfo.ROSMessageInfoList.instance() + info = factory.getInfo(self._messageType) + + if info: + info_type = info.datatype() + info_md5sum = info.md5sum() + info_message_definition = info.message_definition() + else: + self._rtcout.RTC_ERROR("can not found %s", self._messageType) + return + + if info_type != type_name: + self._rtcout.RTC_WARN( + "topic name in not match(%s:%s)", (info_type, type_name)) + return + if info_md5sum != md5sum: + self._rtcout.RTC_WARN( + "MD5sum in not match(%s:%s)", (info_md5sum, md5sum)) + return + + fileno = client_sock.fileno() + poller = None + if hasattr(select, 'poll'): + ready = False + poller = select.poll() + poller.register(fileno, select.POLLOUT) + while not ready: + events = poller.poll() + for _, flag in events: + if flag & select.POLLOUT: + ready = True + else: + ready = None + while not ready: + try: + _, ready, _ = select.select([], [fileno], []) + except ValueError: + self._rtcout.RTC_ERROR("ValueError") + return + client_sock.setblocking(1) + fields = {'topic': topic_name, + 'message_definition': info_message_definition, + 'tcp_nodelay': '0', + 'md5sum': info_md5sum, + 'type': info_type, + 'callerid': self._callerid} + + try: + write_ros_handshake_header(client_sock, fields) + except rosgraph.network.ROSHandshakeException: + self._rtcout.RTC_ERROR("write ROS handshake exception") + return + if poller: + poller.unregister(fileno) + + self._tcp_connecters[addr] = { + "socket": client_sock, + "id": self._subnum, + "node": header['callerid']} + self._subnum += 1 + + ## + # @if jp + # @brief 接続先へのデータ送信 + # + # 接続先のポートへデータを送信するための純粋仮想関数。 + # + # この関数は、以下のリターンコードを返す。 + # + # - PORT_OK: 正常終了。 + # - PORT_ERROR: データ送信の過程で何らかのエラーが発生した。 + # - SEND_FULL: データを送信したが、相手側バッファがフルだった。 + # - SEND_TIMEOUT: データを送信したが、相手側バッファがタイムアウトした。 + # - UNKNOWN_ERROR: 原因不明のエラー + # + # @param data 送信するデータ + # @return リターンコード + # + # @else + # @brief Send data to the destination port + # + # Pure virtual function to send data to the destination port. + # + # This function might the following return codes + # + # - PORT_OK: Normal return + # - PORT_ERROR: Error occurred in data transfer process + # - SEND_FULL: Buffer full although OutPort tried to send data + # - SEND_TIMEOUT: Timeout although OutPort tried to send data + # - UNKNOWN_ERROR: Unknown error + # + # @endif + # + # virtual ReturnCode put(const cdrMemoryStream& data); + + def put(self, data): + self._rtcout.RTC_PARANOID("put()") + + ret = self.PORT_OK + for k, connector in self._tcp_connecters.items(): + try: + connector["socket"].sendall(data) + except BaseException: + self._rtcout.RTC_ERROR("send error") + # connector.shutdown(socket.SHUT_RDWR) + connector["socket"].close() + ret = self.CONNECTION_LOST + del self._tcp_connecters[k] + return ret + + ## + # @if jp + # @brief InterfaceProfile情報を公開する + # + # InterfaceProfile情報を公開する。 + # 引数で指定するプロパティ情報内の NameValue オブジェクトの + # dataport.interface_type 値を調べ、当該ポートに設定されている + # インターフェースタイプと一致する場合のみ情報を取得する。 + # + # @param properties InterfaceProfile情報を受け取るプロパティ + # + # @else + # @brief Publish InterfaceProfile information + # + # Publish interfaceProfile information. + # Check the dataport.interface_type value of the NameValue object + # specified by an argument in property information and get information + # only when the interface type of the specified port is matched. + # + # @param properties Properties to get InterfaceProfile information + # + # @endif + # + # virtual void publishInterfaceProfile(SDOPackage::NVList& properties); + + def publishInterfaceProfile(self, properties): + pass + + ## + # @if jp + # @brief データ送信通知への登録 + # + # 指定されたプロパティに基づいて、データ送出通知の受け取りに登録する。 + # + # @param properties 登録情報 + # + # @return 登録処理結果(登録成功:true、登録失敗:false) + # + # @else + # @brief Subscribe to the data sending notification + # + # Subscribe to the data sending notification based on specified + # property information. + # + # @param properties Information for subscription + # + # @return Subscription result (Successful:true, Failed:false) + # + # @endif + # + # virtual bool subscribeInterface(const SDOPackage::NVList& properties); + def subscribeInterface(self, properties): + return True + + ## + # @if jp + # @brief データ送信通知からの登録解除 + # + # データ送出通知の受け取りから登録を解除する。 + # + # @param properties 登録解除情報 + # + # @else + # @brief Unsubscribe the data send notification + # + # Unsubscribe the data send notification. + # + # @param properties Information for unsubscription + # + # @endif + # + # virtual void unsubscribeInterface(const SDOPackage::NVList& properties); + def unsubscribeInterface(self, properties): + if self._client is not None: + try: + ret, _, __ = self._client.unregisterPublisher( + self._callerid, self._topic, self._topicmgr.getURI()) + if ret != 1: + self._rtcout.RTC_ERROR("unregister publisher error") + except xmlrpclib.Fault as err: + self._rtcout.RTC_ERROR("XML-RPC Error:%s", err.faultString) + if self._topicmgr is not None: + self._rtcout.RTC_VERBOSE("remove publisher") + self._topicmgr.removePublisher(self) + + for k, connector in self._tcp_connecters.items(): + try: + self._rtcout.RTC_VERBOSE("connection close") + connector["socket"].shutdown(socket.SHUT_RDWR) + connector["socket"].close() + except BaseException: + self._rtcout.RTC_ERROR("socket shutdown error") + + ## + # @if jp + # @brief ノード名の取得 + # + # @return ノード名 + # + # @else + # @brief + # + # @return + # + # @endif + # + def getName(self): + self._rtcout.RTC_VERBOSE("getName") + return self._callerid + + ## + # @if jp + # @brief メッセージ型の取得 + # + # @return メッセージ型 + # + # @else + # @brief + # + # @return + # + # @endif + # + def datatype(self): + self._rtcout.RTC_VERBOSE("datatype") + return self._messageType + + ## + # @if jp + # @brief コネクタの情報取得 + # + # @return コネクタの情報のリスト + # + # @else + # @brief + # + # @return + # + # @endif + # + def getInfo(self): + self._rtcout.RTC_VERBOSE("getInfo") + cons = [] + for k, connector in self._tcp_connecters.items(): + cons.append([connector["id"], connector["node"], + "i", "TCPROS", self._topic, True, ""]) + return cons + +## +# @if jp +# @brief モジュール登録関数 +# +# +# @else +# @brief +# +# +# @endif +# + + +def ROSOutPortInit(): + factory = OpenRTM_aist.InPortConsumerFactory.instance() + factory.addFactory("ros", + ROSOutPort) diff --git a/OpenRTM_aist/ext/transport/ROSTransport/ROSSerializer.py b/OpenRTM_aist/ext/transport/ROSTransport/ROSSerializer.py new file mode 100644 index 00000000..c8b8ef0a --- /dev/null +++ b/OpenRTM_aist/ext/transport/ROSTransport/ROSSerializer.py @@ -0,0 +1,967 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- + +## +# @file ROSSerializer.py +# @brief ROS Serializer class +# @date $Date$ +# @author Nobuhiko Miyamoto +# +# Copyright (C) 2019 +# Noriaki Ando +# Robot Innovation Research Center, +# National Institute of +# Advanced Industrial Science and Technology (AIST), Japan +# All rights reserved. +# +# $Id$ +# + +import OpenRTM_aist +import RTC + +try: + from cStringIO import StringIO +except ImportError: + from io import StringIO, BytesIO + +import sys +import struct +import ROSMessageInfo + +from std_msgs.msg import Float32 +from std_msgs.msg import Float64 +from std_msgs.msg import Int8 +from std_msgs.msg import Int16 +from std_msgs.msg import Int32 +from std_msgs.msg import Int64 +from std_msgs.msg import UInt8 +from std_msgs.msg import UInt16 +from std_msgs.msg import UInt32 +from std_msgs.msg import UInt64 +from std_msgs.msg import Float32MultiArray +from std_msgs.msg import Float64MultiArray +from std_msgs.msg import Int8MultiArray +from std_msgs.msg import Int16MultiArray +from std_msgs.msg import Int32MultiArray +from std_msgs.msg import Int64MultiArray +from std_msgs.msg import UInt8MultiArray +from std_msgs.msg import UInt16MultiArray +from std_msgs.msg import UInt32MultiArray +from std_msgs.msg import UInt64MultiArray +from std_msgs.msg import String +from geometry_msgs.msg import PointStamped +from geometry_msgs.msg import QuaternionStamped +from geometry_msgs.msg import Vector3Stamped +from sensor_msgs.msg import Image + + +## +# @if jp +# @brief ROSメッセージを符号化 +# +# @param msg ROSメッセージ +# @param buf バッファ +# @return 符号化のデータ +# +# @else +# @brief +# +# @param msg +# @param buf +# @return +# +# @endif +# +def ros_serialize(msg): + if sys.version_info[0] == 3: + buf = BytesIO() + else: + buf = StringIO() + + start = buf.tell() + buf.seek(start + 4) + msg.serialize(buf) + + end = buf.tell() + size = end - 4 - start + buf.seek(start) + buf.write(struct.pack(' +# +# Copyright (C) 2019 +# Noriaki Ando +# Robot Innovation Research Center, +# National Institute of +# Advanced Industrial Science and Technology (AIST), Japan +# All rights reserved. +# +# $Id$ +# +import OpenRTM_aist +import threading +import rosgraph.xmlrpc +import time +import socket + +try: + from cStringIO import StringIO +except ImportError: + from io import StringIO + + +manager = None +mutex = threading.RLock() + +## +# @if jp +# @class ROSTopicManager +# @brief ROSトピックを管理するクラス +# +# +# @else +# @class ROSTopicManager +# @brief +# +# +# @endif + + +class ROSTopicManager(rosgraph.xmlrpc.XmlRpcHandler): + """ + """ + + ## + # @if jp + # @brief コンストラクタ + # + # コンストラクタ + # + # @param self + # + # @else + # @brief Constructor + # + # @param self + # + # @endif + def __init__(self): + super(ROSTopicManager, self).__init__() + self._node = None + self._server_sock = None + self._publishers = [] + self._subscribers = [] + self._addr = "" + self._port = 0 + self._shutdownflag = False + self._thread = None + self._old_uris = [] + + ## + # @if jp + # @brief デストラクタ + # + # + # @param self + # + # @else + # + # @brief self + # + # @endif + def __del__(self): + pass + + ## + # @if jp + # @brief トピックマネージャ開始 + # + # @param self + # + # @else + # + # @brief + # + # @param self + # + # @endif + def start(self): + self._node = rosgraph.xmlrpc.XmlRpcNode(self._port, self) + self._node.start() + self._server_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + self._server_sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) + self._server_sock.bind( + (rosgraph.network.get_bind_address(), self._port)) + (self._addr, self._port) = self._server_sock.getsockname()[0:2] + self._server_sock.listen(5) + self._thread = threading.Thread(target=self.run, args=()) + self._thread.daemon = True + self._thread.start() + + ## + # @if jp + # @brief ROSOutPort登録 + # + # @param self + # @param publisher 登録対象のROSOutPort + # + # @else + # + # @brief + # + # @param self + # @param publisher + # + # @endif + def addPublisher(self, publisher): + if not self.existPublisher(publisher): + self._publishers.append(publisher) + + ## + # @if jp + # @brief ROSInPort登録 + # + # @param self + # @param subscriber 登録対象のROSInPort + # + # @else + # + # @brief + # + # @param self + # @param subscriber + # + # @endif + def addSubscriber(self, subscriber): + if not self.existSubscriber(subscriber): + self._subscribers.append(subscriber) + + ## + # @if jp + # @brief ROSOutPort削除 + # + # @param self + # @param publisher 削除対象のROSOutPort + # @return True:削除成功、False:削除対象が存在しない + # + # @else + # + # @brief + # + # @param self + # @param publisher + # @return + # + # @endif + + def removePublisher(self, publisher): + try: + self._publishers.remove(publisher) + return True + except ValueError: + return False + + ## + # @if jp + # @brief ROSInPort削除 + # + # @param self + # @param subscriber 削除対象のROSInPort + # @return True:削除成功、False:削除対象が存在しない + # + # @else + # + # @brief + # + # @param self + # @param subscriber + # @return + # + # @endif + def removeSubscriber(self, subscriber): + try: + self._subscribers.remove(subscriber) + return True + except ValueError: + return False + + ## + # @if jp + # @brief ROSOutPortが登録済みかの確認 + # + # @param self + # @param publisher ROSOutPort + # @return True:登録済み、False:未登録 + # + # @else + # + # @brief + # + # @param self + # @param publisher + # @return + # + # @endif + def existPublisher(self, publisher): + if self._publishers.count(publisher) > 0: + return True + else: + return False + + ## + # @if jp + # @brief ROSInPortが登録済みかの確認 + # + # @param self + # @param subscriber ROSInPort + # @return True:登録済み、False:未登録 + # + # @else + # + # @brief + # + # @param self + # @param subscriber + # @return + # + # @endif + def existSubscriber(self, subscriber): + if self._subscribers.count(subscriber) > 0: + return True + else: + return False + + ## + # @if jp + # @brief publisherUpdateコールバック関数 + # + # @param self + # @param caller_id 呼び出しID + # @param topic トピック名 + # @param publishers publisher一覧 + # @return ret, msg, value + # ret:リターンコード(1:問題なし) + # msg:メッセージ + # value:値 + # + # @else + # + # @brief + # + # @param self + # @param caller_id + # @param topic + # @param publishers + # @return + # + # @endif + def publisherUpdate(self, caller_id, topic, publishers): + lost_uris = [] + for uri in self._old_uris: + if not (uri in publishers): + lost_uris.append(uri) + + for subscriber in self._subscribers: + subscriber.connect(caller_id, topic, publishers) + for lost_uri in lost_uris: + subscriber.deleteSocket(lost_uri) + self._old_uris = publishers[:] + + return 1, "", 0 + + ## + # @if jp + # @brief TCPソケット受信時の処理関数 + # + # @param self + # + # @else + # + # @brief + # + # @param self + # + # @endif + def run(self): + while not self._shutdownflag: + try: + (client_sock, client_addr) = self._server_sock.accept() + addr = client_addr[0] + ":" + str(client_addr[1]) + for publisher in self._publishers: + publisher.connect(client_sock, addr) + except BaseException: + pass + + ## + # @if jp + # @brief ソケット、スレッド終了処理 + # + # @param self + # + # @else + # + # @brief + # + # @param self + # + # @endif + def shutdown(self): + self._shutdownflag = True + try: + self._server_sock.shutdown(socket.SHUT_WR) + except BaseException: + pass + self._server_sock.close() + self._thread.join() + self._node.shutdown(True) + + ## + # @if jp + # @brief requestTopicコールバック関数 + # + # @param self + # @param caller_id 呼び出しID + # @param topic トピック名 + # @param protocols プロトコル一覧 + # @return ret, msg, value + # ret:リターンコード(1:問題なし、-1:トピックに対応したPublisherが存在しない、0:それ以外のエラー) + # msg:メッセージ + # value:プロトコル、アドレス、ポート番号 + # + # @else + # + # @brief + # + # @param self + # @param caller_id + # @param topic + # @param protocols + # @return + # + # @endif + + def requestTopic(self, caller_id, topic, protocols): + if not self.hasPublisher(topic): + return -1, "Not a publisher of [%s]" % topic, [] + for protocol in protocols: + protocol_id = protocol[0] + if protocol_id == "TCPROS": + addr = rosgraph.network.get_host_name() + port = self._port + return 1, "ready on %s:%s" % (addr, port), [ + "TCPROS", addr, port] + return 0, "no supported protocol implementations", [] + + ## + # @if jp + # @brief getSubscriptionsコールバック関数 + # + # @param self + # @param caller_id 呼び出しID + # @return ret, msg, subs + # ret:リターンコード(1) + # msg:メッセージ + # subs:Subscriber一覧 + # + # @else + # + # @brief + # + # @param self + # @param caller_id + # @return ret, msg, subs + # + # @endif + def getSubscriptions(self, caller_id): + subs = [] + for subscriber in self._subscribers: + sub = [subscriber.getName(), subscriber.datatype()] + subs.append(sub) + + return 1, "subscriptions", subs + + ## + # @if jp + # @brief getPublicationsコールバック関数 + # + # @param self + # @param caller_id 呼び出しID + # @return ret, msg, pubs + # ret:リターンコード(1) + # msg:メッセージ + # pubs:Publisher一覧 + # + # @else + # + # @brief + # + # @param self + # @param caller_id + # @return ret, msg, pubs + # + # @endif + def getPublications(self, caller_id): + pubs = [] + for publisher in self._publishers: + pub = [publisher.getName(), publisher.datatype()] + pubs.append(pub) + + return 1, "subscriptions", pubs + + ## + # @if jp + # @brief getBusStatsコールバック関数 + # + # @param self + # @param caller_id 呼び出しID + # @return + # + # @else + # + # @brief + # + # @param self + # @param caller_id + # @return + # + # @endif + def getBusStats(self, caller_id): + return 1, "", [] + + ## + # @if jp + # @brief getBusInfoコールバック関数 + # + # @param self + # @param caller_id 呼び出しID + # @return ret, msg, info + # ret:リターンコード(1) + # msg:メッセージ + # pubs:コネクタの情報一覧 + # + # @else + # + # @brief + # + # @param self + # @param caller_id + # @return ret, msg, info + # + # @endif + def getBusInfo(self, caller_id): + info = [] + for subscriber in self._subscribers: + info.extend(subscriber.getInfo()) + for publisher in self._publishers: + info.extend(publisher.getInfo()) + + return 1, "bus info", info + + ## + # @if jp + # @brief getMainUriコールバック関数 + # + # @param self + # @param caller_id 呼び出しID + # @return + # + # @else + # + # @brief + # + # @param self + # @param caller_id + # @return + # + # @endif + # def getMainUri(self, caller_id): + # return 0, "main URI not set", "" + + ## + # @if jp + # @brief 指定トピック名のPublisherが登録されているかを確認 + # + # @param self + # @param topic トピック名 + # @return True:存在する、False:存在しない + # + # @else + # + # @brief + # + # @param self + # @param topic + # @return + # + # @endif + def hasPublisher(self, topic): + for publisher in self._publishers: + if publisher.getTopic() == topic: + return True + return False + + ## + # @if jp + # @brief TCPソケットのURIを取得 + # + # @param self + # @return URI + # + # @else + # + # @brief + # + # @param self + # @return + # + # @endif + def getURI(self): + for i in range(0, 10): + if self._node.uri: + return self._node.uri + time.sleep(1) + return None + + ## + # @if jp + # @brief インスタンス取得 + # + # @return インスタンス + # + # @else + # + # @brief + # + # @return インスタンス + # + # @endif + def instance(): + global manager + global mutex + + guard = OpenRTM_aist.ScopedLock(mutex) + if manager is None: + manager = ROSTopicManager() + manager.start() + + return manager + + instance = staticmethod(instance) + + ## + # @if jp + # @brief ROSTopicManagerを初期化している場合に終了処理を呼び出す + # + # + # @else + # + # @brief + # + # + # @endif + + def shutdown_global(): + global manager + global mutex + + guard = OpenRTM_aist.ScopedLock(mutex) + if manager is not None: + manager.shutdown() + + manager = None + + shutdown_global = staticmethod(shutdown_global) diff --git a/OpenRTM_aist/ext/transport/ROSTransport/ROSTransport.py b/OpenRTM_aist/ext/transport/ROSTransport/ROSTransport.py new file mode 100644 index 00000000..340a6093 --- /dev/null +++ b/OpenRTM_aist/ext/transport/ROSTransport/ROSTransport.py @@ -0,0 +1,96 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- + +## +# @file ROSTransport.py +# @brief ROS Transport class +# @date $Date$ +# @author Nobuhiko Miyamoto +# +# Copyright (C) 2019 +# Noriaki Ando +# Robot Innovation Research Center, +# National Institute of +# Advanced Industrial Science and Technology (AIST), Japan +# All rights reserved. +# +# $Id$ +# + +import OpenRTM_aist +import ROSInPort +import ROSOutPort +import ROSSerializer +from ROSTopicManager import ROSTopicManager + + +## +# @if jp +# @class ManagerActionListener +# @brief ROSTopicManagerの終了処理を行うマネージャアクションリスナ +# +# +# @else +# @class ManagerActionListener +# @brief +# +# +# @endif +class ManagerActionListener: + ## + # @if jp + # @brief コンストラクタ + # + # + # @param self + # + # @else + # + # @brief self + # + # @endif + def __init__(self): + pass + + def preShutdown(self): + pass + ## + # @if jp + # @brief RTMマネージャ終了後にROSTopicManagerの終了処理を実行 + # + # + # @param self + # + # @else + # + # @brief self + # + # @endif + + def postShutdown(self): + ROSTopicManager.shutdown_global() + + def preReinit(self): + pass + + def postReinit(self): + pass + + +## +# @if jp +# @brief モジュール登録関数 +# +# +# @else +# @brief +# +# +# @endif +# +def ROSTransportInit(mgr): + ROSInPort.ROSInPortInit() + ROSOutPort.ROSOutPortInit() + ROSSerializer.ROSSerializerInit() + + mgr.addManagerActionListener(ManagerActionListener()) diff --git a/OpenRTM_aist/ext/transport/ROSTransport/__init__.py b/OpenRTM_aist/ext/transport/ROSTransport/__init__.py new file mode 100644 index 00000000..b6098858 --- /dev/null +++ b/OpenRTM_aist/ext/transport/ROSTransport/__init__.py @@ -0,0 +1,5 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- + + +from ROSTransport import * diff --git a/OpenRTM_aist/ext/transport/ROSTransport/rtc.conf b/OpenRTM_aist/ext/transport/ROSTransport/rtc.conf new file mode 100644 index 00000000..550ac0bd --- /dev/null +++ b/OpenRTM_aist/ext/transport/ROSTransport/rtc.conf @@ -0,0 +1,8 @@ +logger.enable: YES +logger.file_name: stdout +logger.log_level: ERROR + +manager.modules.load_path: . +manager.modules.preload: ROSTransport.py +manager.components.preconnect: ConsoleOut0.in?interface_type=ros&marshaling_type=ROSFloat32, ConsoleIn0.out?interface_type=ros&marshaling_type=ROSFloat32 +manager.components.preactivation: ConsoleOut0, ConsoleIn0 \ No newline at end of file diff --git a/OpenRTM_aist/ext/transport/__init__.py b/OpenRTM_aist/ext/transport/__init__.py new file mode 100644 index 00000000..270be2a2 --- /dev/null +++ b/OpenRTM_aist/ext/transport/__init__.py @@ -0,0 +1 @@ +# Empty file diff --git a/OpenRTM_aist/test/BasicDataType.idl b/OpenRTM_aist/test/BasicDataType.idl deleted file mode 100644 index d089563d..00000000 --- a/OpenRTM_aist/test/BasicDataType.idl +++ /dev/null @@ -1,189 +0,0 @@ -// -*- IDL -*- -/*! - * @file DataType.idl - * @brief Basic Data Type definition - * @date $Date: 2007-01-09 15:36:29 $ - * @author Noriaki Ando - * - * Copyright (C) 2003-2006 - * Task-intelligence Research Group, - * Intelligent Systems Research Institute, - * National Institute of - * Advanced Industrial Science and Technology (AIST), Japan - * All rights reserved. - * - * $Id: BasicDataType.idl 1580 2009-12-07 08:54:10Z kurihara $ - * - */ - -#ifndef BasicDataType_idl -#define BasicDataType_idl - -module RTC { - //------------------------------------------------------------ - // Basic data type definition - //------------------------------------------------------------ - struct Time - { - unsigned long sec; // sec - unsigned long nsec; // nano sec - }; - - struct TimedState - { - Time tm; - short data; - }; - - struct TimedShort - { - Time tm; - short data; - }; - - struct TimedLong - { - Time tm; - long data; - }; - - struct TimedUShort - { - Time tm; - unsigned short data; - }; - - struct TimedULong - { - Time tm; - unsigned long data; - }; - - struct TimedFloat - { - Time tm; - float data; - }; - - struct TimedDouble - { - Time tm; - double data; - }; - - struct TimedChar - { - Time tm; - char data; - }; - - struct TimedWChar - { - Time tm; - wchar data; - }; - - struct TimedBoolean - { - Time tm; - boolean data; - }; - - struct TimedOctet - { - Time tm; - octet data; - }; - - struct TimedString - { - Time tm; - string data; - }; - - - struct TimedWString - { - Time tm; - wstring data; - }; - - - /*! - * Sequence data type - */ - struct TimedShortSeq - { - Time tm; - sequence data; - }; - - struct TimedLongSeq - { - Time tm; - sequence data; - }; - - struct TimedUShortSeq - { - Time tm; - sequence data; - }; - - struct TimedULongSeq - { - Time tm; - sequence data; - }; - - struct TimedFloatSeq - { - Time tm; - sequence data; - }; - - struct TimedDoubleSeq - { - Time tm; - sequence data; - }; - - struct TimedCharSeq - { - Time tm; - sequence data; - }; - - struct TimedWCharSeq - { - Time tm; - sequence data; - }; - - struct TimedBooleanSeq - { - Time tm; - sequence data; - }; - - struct TimedOctetSeq - { - Time tm; - sequence data; - }; - - struct TimedStringSeq - { - Time tm; - sequence data; - }; - - struct TimedWStringSeq - { - Time tm; - sequence data; - }; - -}; - -#endif // end of BasicDataType_idl diff --git a/OpenRTM_aist/test/ComponentActionListenerTestComp.py b/OpenRTM_aist/test/ComponentActionListenerTestComp.py deleted file mode 100644 index 6e197aa8..00000000 --- a/OpenRTM_aist/test/ComponentActionListenerTestComp.py +++ /dev/null @@ -1,369 +0,0 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- -# -*- Python -*- - -import sys - -import OpenRTM -import RTC -import OpenRTM_aist - -consolein_spec = ["implementation_id", "ConsoleIn", - "type_name", "ConsoleIn", - "description", "Console input component", - "version", "1.0", - "vendor", "Shinji Kurihara", - "category", "example", - "activity_type", "DataFlowComponent", - "max_instance", "10", - "language", "Python", - "lang_type", "script", - ""] - - -class DataListener(OpenRTM_aist.ConnectorDataListenerT): - def __init__(self, name): - self._name = name - - def __del__(self): - print "dtor of ", self._name - - def __call__(self, info, cdrdata): - data = OpenRTM_aist.ConnectorDataListenerT.__call__(self, info, cdrdata, RTC.TimedLong(RTC.Time(0,0),0)) - print "------------------------------" - print "Listener: ", self._name - print "Profile::name: ", info.name - print "Profile::id: ", info.id - print "Data: ", data.data - print "------------------------------" - -class ConnListener(OpenRTM_aist.ConnectorListener): - def __init__(self, name): - self._name = name - - def __del__(self): - print "dtor of ", self._name - - def __call__(self, info): - print "------------------------------" - print "Listener: ", self._name - print "Profile::name: ", info.name - print "Profile::id: ", info.id - print "------------------------------" - - -class ConsoleIn(OpenRTM_aist.DataFlowComponentBase): - def __init__(self, manager): - OpenRTM_aist.DataFlowComponentBase.__init__(self, manager) - self.addPreComponentActionListener(OpenRTM_aist.PreComponentActionListenerType.PRE_ON_INITIALIZE, - self.preOnInitializeFunc) - self.addExecutionContextActionListener(OpenRTM_aist.ExecutionContextActionListenerType.EC_ATTACHED, - self.onAttachExecutionContextFunc) - self.addExecutionContextActionListener(OpenRTM_aist.ExecutionContextActionListenerType.EC_DETACHED, - self.onDetachExecutionContextFunc) - - return - - def preOnInitializeFunc(self, ec_id): - print "preOnInitializeFunc" - return - - def preOnFinalizeFunc(self, ec_id): - print "preOnFinalizeFunc" - return - - def preOnStartupFunc(self, ec_id): - print "preOnStartupFunc" - return - - def preOnShutdownFunc(self, ec_id): - print "preOnShutdownFunc" - return - - def preOnActivatedFunc(self, ec_id): - print "preOnActivatedFunc" - return - - def preOnDeactivatedFunc(self, ec_id): - print "preOnDeactivatedFunc" - return - - def preOnAbortingFunc(self, ec_id): - print "preOnAbortingFunc" - return - - def preOnErrorFunc(self, ec_id): - print "preOnErrorFunc" - return - - def preOnResetFunc(self, ec_id): - print "preOnResetFunc" - return - - def preOnExecuteFunc(self, ec_id): - print "preOnExecuteFunc" - return - - def preOnStateUpdateFunc(self, ec_id): - print "preOnStateUpdateFunc" - return - - def preOnRateChangedFunc(self, ec_id): - print "preOnRateChangedFunc" - return - - def postOnInitializeFunc(self, ec_id, ret): - print "postOnInitializeFunc, ret: ", ret - return - - def postOnFinalizeFunc(self, ec_id, ret): - print "postOnFinalizeFunc, ret: ", ret - return - - def postOnStartupFunc(self, ec_id, ret): - print "postOnStartupFunc, ret: ", ret - return - - def postOnShutdownFunc(self, ec_id, ret): - print "postOnShutdownFunc, ret: ", ret - return - - def postOnActivatedFunc(self, ec_id, ret): - print "postOnActivatedFunc, ret: ", ret - return - - def postOnDeactivatedFunc(self, ec_id, ret): - print "postOnDeactivatedFunc, ret: ", ret - return - - def postOnAbortingFunc(self, ec_id, ret): - print "postOnAbortingFunc, ret: ", ret - return - - def postOnErrorFunc(self, ec_id, ret): - print "postOnErrorFunc, ret: ", ret - return - - def postOnResetFunc(self, ec_id, ret): - print "postOnResetFunc, ret: ", ret - return - - def postOnExecuteFunc(self, ec_id, ret): - print "postOnExecuteFunc, ret: ", ret - return - - def postOnStateUpdateFunc(self, ec_id, ret): - print "postOnStateUpdateFunc, ret: ", ret - return - - def postOnRateChangedFunc(self, ec_id, ret): - print "postOnRateChangedFunc, ret: ", ret - return - - def onAddPortFunc(self, pprof): - print "onAddPortFunc" - return - - def onRemovePortFunc(self, pprof): - print "onRemovePortFunc" - return - - def onAttachExecutionContextFunc(self, ec_id): - print "onAttachExecutionContextFunc" - return - - def onDetachExecutionContextFunc(self, ec_id): - print "onDetachExecutionContextFunc" - return - - - def onNotifyConnectFunc(self, pname, prof): - print "onNotifyConnectFunc pname: ",pname - return - - def onNotifyDisconnectFunc(self, pname, prof): - print "onNotifyDisconnectFunc pname: ",pname - return - - def onUnsubscribeInterfacesFunc(self, pname, profile): - print "onUnsubscribeInterfacesFunc pname: ", pname - return - - def onPublishInterfacesFunc(self, portname, profile, ret): - print "onPublishInterfacesFunc pname: ", portname, " ret: ", ret - return - - def onConnectNextportFunc(self, portname, profile, ret): - print "onConnectNextportFunc pname: ", portname, " ret: ", ret - return - - def onSubscribeInterfacesFunc(self, portname, profile, ret): - print "onSubscribeInterfacesFunc pname: ", portname, " ret: ", ret - return - - def onConnectedFunc(self, portname, profile, ret): - print "onConnectedFunc pname: ", portname, " ret: ", ret - return - - def onDisconnectNextportFunc(self, portname, profile, ret): - print "onDisconnectNextportFunc pname: ", portname, " ret: ", ret - return - - def onDisconnectedFunc(self, portname, profile, ret): - print "onDisconnectedFunc pname: ", portname, " ret: ", ret - return - - - def onInitialize(self): - self.addPreComponentActionListener(OpenRTM_aist.PreComponentActionListenerType.PRE_ON_FINALIZE, - self.preOnFinalizeFunc) - self.addPreComponentActionListener(OpenRTM_aist.PreComponentActionListenerType.PRE_ON_STARTUP, - self.preOnStartupFunc) - self.addPreComponentActionListener(OpenRTM_aist.PreComponentActionListenerType.PRE_ON_SHUTDOWN, - self.preOnShutdownFunc) - self.addPreComponentActionListener(OpenRTM_aist.PreComponentActionListenerType.PRE_ON_ACTIVATED, - self.preOnActivatedFunc) - self.addPreComponentActionListener(OpenRTM_aist.PreComponentActionListenerType.PRE_ON_DEACTIVATED, - self.preOnDeactivatedFunc) - self.addPreComponentActionListener(OpenRTM_aist.PreComponentActionListenerType.PRE_ON_ABORTING, - self.preOnAbortingFunc) - self.addPreComponentActionListener(OpenRTM_aist.PreComponentActionListenerType.PRE_ON_ERROR, - self.preOnErrorFunc) - self.addPreComponentActionListener(OpenRTM_aist.PreComponentActionListenerType.PRE_ON_RESET, - self.preOnResetFunc) - self.addPreComponentActionListener(OpenRTM_aist.PreComponentActionListenerType.PRE_ON_EXECUTE, - self.preOnExecuteFunc) - self.addPreComponentActionListener(OpenRTM_aist.PreComponentActionListenerType.PRE_ON_STATE_UPDATE, - self.preOnStateUpdateFunc) - self.addPreComponentActionListener(OpenRTM_aist.PreComponentActionListenerType.PRE_ON_RATE_CHANGED, - self.preOnRateChangedFunc) - - self.addPostComponentActionListener(OpenRTM_aist.PostComponentActionListenerType.POST_ON_INITIALIZE, - self.postOnInitializeFunc) - self.addPostComponentActionListener(OpenRTM_aist.PostComponentActionListenerType.POST_ON_FINALIZE, - self.postOnFinalizeFunc) - self.addPostComponentActionListener(OpenRTM_aist.PostComponentActionListenerType.POST_ON_STARTUP, - self.postOnStartupFunc) - self.addPostComponentActionListener(OpenRTM_aist.PostComponentActionListenerType.POST_ON_SHUTDOWN, - self.postOnShutdownFunc) - self.addPostComponentActionListener(OpenRTM_aist.PostComponentActionListenerType.POST_ON_ACTIVATED, - self.postOnActivatedFunc) - self.addPostComponentActionListener(OpenRTM_aist.PostComponentActionListenerType.POST_ON_DEACTIVATED, - self.postOnDeactivatedFunc) - self.addPostComponentActionListener(OpenRTM_aist.PostComponentActionListenerType.POST_ON_ABORTING, - self.postOnAbortingFunc) - self.addPostComponentActionListener(OpenRTM_aist.PostComponentActionListenerType.POST_ON_ERROR, - self.postOnErrorFunc) - self.addPostComponentActionListener(OpenRTM_aist.PostComponentActionListenerType.POST_ON_RESET, - self.postOnResetFunc) - self.addPostComponentActionListener(OpenRTM_aist.PostComponentActionListenerType.POST_ON_EXECUTE, - self.postOnExecuteFunc) - self.addPostComponentActionListener(OpenRTM_aist.PostComponentActionListenerType.POST_ON_STATE_UPDATE, - self.postOnStateUpdateFunc) - self.addPostComponentActionListener(OpenRTM_aist.PostComponentActionListenerType.POST_ON_RATE_CHANGED, - self.postOnRateChangedFunc) - - self.addPortActionListener(OpenRTM_aist.PortActionListenerType.ADD_PORT, - self.onAddPortFunc) - self.addPortActionListener(OpenRTM_aist.PortActionListenerType.REMOVE_PORT, - self.onRemovePortFunc) - - - self.addPortConnectListener(OpenRTM_aist.PortConnectListenerType.ON_NOTIFY_CONNECT, - self.onNotifyConnectFunc) - self.addPortConnectListener(OpenRTM_aist.PortConnectListenerType.ON_NOTIFY_DISCONNECT, - self.onNotifyDisconnectFunc) - self.addPortConnectListener(OpenRTM_aist.PortConnectListenerType.ON_UNSUBSCRIBE_INTERFACES, - self.onUnsubscribeInterfacesFunc) - - self.addPortConnectRetListener(OpenRTM_aist.PortConnectRetListenerType.ON_PUBLISH_INTERFACES, - self.onPublishInterfacesFunc) - self.addPortConnectRetListener(OpenRTM_aist.PortConnectRetListenerType.ON_CONNECT_NEXTPORT, - self.onConnectNextportFunc) - self.addPortConnectRetListener(OpenRTM_aist.PortConnectRetListenerType.ON_SUBSCRIBE_INTERFACES, - self.onSubscribeInterfacesFunc) - self.addPortConnectRetListener(OpenRTM_aist.PortConnectRetListenerType.ON_CONNECTED, - self.onConnectedFunc) - self.addPortConnectRetListener(OpenRTM_aist.PortConnectRetListenerType.ON_DISCONNECT_NEXT, - self.onDisconnectNextportFunc) - self.addPortConnectRetListener(OpenRTM_aist.PortConnectRetListenerType.ON_DISCONNECTED, - self.onDisconnectedFunc) - - - self._data = RTC.TimedLong(RTC.Time(0,0),0) - self._outport = OpenRTM_aist.OutPort("out", self._data) - # Set OutPort buffer - self.addOutPort("out", self._outport) - self._outport.addConnectorDataListener(OpenRTM_aist.ConnectorDataListenerType.ON_BUFFER_WRITE, - DataListener("ON_BUFFER_WRITE")) - self._outport.addConnectorDataListener(OpenRTM_aist.ConnectorDataListenerType.ON_BUFFER_FULL, - DataListener("ON_BUFFER_FULL")) - self._outport.addConnectorDataListener(OpenRTM_aist.ConnectorDataListenerType.ON_BUFFER_WRITE_TIMEOUT, - DataListener("ON_BUFFER_WRITE_TIMEOUT")) - self._outport.addConnectorDataListener(OpenRTM_aist.ConnectorDataListenerType.ON_BUFFER_OVERWRITE, - DataListener("ON_BUFFER_OVERWRITE")) - self._outport.addConnectorDataListener(OpenRTM_aist.ConnectorDataListenerType.ON_BUFFER_READ, - DataListener("ON_BUFFER_READ")) - self._outport.addConnectorDataListener(OpenRTM_aist.ConnectorDataListenerType.ON_SEND, - DataListener("ON_SEND")) - self._outport.addConnectorDataListener(OpenRTM_aist.ConnectorDataListenerType.ON_RECEIVED, - DataListener("ON_RECEIVED")) - self._outport.addConnectorDataListener(OpenRTM_aist.ConnectorDataListenerType.ON_RECEIVER_FULL, - DataListener("ON_RECEIVER_FULL")) - self._outport.addConnectorDataListener(OpenRTM_aist.ConnectorDataListenerType.ON_RECEIVER_TIMEOUT, - DataListener("ON_RECEIVER_TIMEOUT")) - self._outport.addConnectorDataListener(OpenRTM_aist.ConnectorDataListenerType.ON_RECEIVER_ERROR, - DataListener("ON_RECEIVER_ERROR")) - - self._outport.addConnectorListener(OpenRTM_aist.ConnectorListenerType.ON_CONNECT, - ConnListener("ON_CONNECT")) - self._outport.addConnectorListener(OpenRTM_aist.ConnectorListenerType.ON_DISCONNECT, - ConnListener("ON_DISCONNECT")) - - return RTC.RTC_OK - - - def onExecute(self, ec_id): - print "Please input number: ", - self._data.data = long(sys.stdin.readline()) - if self._data.data == 9: - return RTC.RTC_ERROR - OpenRTM_aist.setTimestamp(self._data) - print "Sending to subscriber: ", self._data.data - self._outport.write() - return RTC.RTC_OK - - -def ConsoleInInit(manager): - profile = OpenRTM_aist.Properties(defaults_str=consolein_spec) - manager.registerFactory(profile, - ConsoleIn, - OpenRTM_aist.Delete) - - -def MyModuleInit(manager): - ConsoleInInit(manager) - - # Create a component - comp = manager.createComponent("ConsoleIn") - -def main(): - # Initialize manager - mgr = OpenRTM_aist.Manager.init(sys.argv) - - # Set module initialization proceduer - # This procedure will be invoked in activateManager() function. - mgr.setModuleInitProc(MyModuleInit) - - # Activate manager and register to naming service - mgr.activateManager() - - # run the manager in blocking mode - # runManager(False) is the default - mgr.runManager() - - # If you want to run the manager in non-blocking mode, do like this - # mgr.runManager(True) - -if __name__ == "__main__": - main() diff --git a/OpenRTM_aist/test/ComponentObserver.idl b/OpenRTM_aist/test/ComponentObserver.idl deleted file mode 100644 index 3cba2694..00000000 --- a/OpenRTM_aist/test/ComponentObserver.idl +++ /dev/null @@ -1,512 +0,0 @@ -// -*- IDL -*- -/*! - * @file ComponentObserver.idl - * @brief Component observer SDO service - * @date $Date$ - * @author Noriaki Ando - * - * Copyright (C) 2011 - * Noriaki Ando - * Intelligent Systems Research Institute, - * National Institute of - * Advanced Industrial Science and Technology (AIST), Japan - * All rights reserved. - * - * $Id$ - * - */ - -#include "SDOPackage.idl" -#include "RTC.idl" - -/*! - * @if jp - * @brief ݡͥȾ֥֥Х󥿡ե - * - * ݡͥȤξ֤ƻ뤹뤿Υ֥Х󥿡ե - * Хѥ˽ġ뤬ݡͥȤ˥֥Х֥ - * Ȥ򥻥åȤݡͥȤϳƼѹˤ򥪥֥Х - * Ȥ򥳡뤷֥ФФѹΤ롣 - * - * @since 1.1 - * - * @else - * @brief Component state observer interface - * - * This interface defines observer interface for component states. - * According to the observer pattern, tools which want to observe - * component state set observer objects to the RT-Component, and weh - * RT-Component changes its status, the observer object is called and - * notice the changes to tools. - * - * - * @since 1.1 - * @endif - */ -module OpenRTM -{ - /*! - * @if jp - * - * @brief 줿֤μ - * - * åRTCǹ줿֤μʬह󷿡 - * - * @else - * - * @brief A kind of updated status - * - * This is a enumeration type to classify updated status in target RTC. - * - * @endif - */ - enum StatusKind - { - /*! - * @if jp - * - * @brief ݡͥȥץե - * - * ݡͥȥץե RTC::ComponentProfile 줿 - * Ȥ򼨤󷿡 - * - * RTC::ComponentProfile ΥСΤinstance_name, - * type_name, description, version, vendor, category RTCư - * ѹ뤳ȤϤʤ餬ѹ줿ˤϡ - * ComponentObserver::updatestatus() hint ˤϡ줾ΥС - * ̾ʸǻꤵ롣ޤparent ФѹΤʤ - * ˡproperties Фѹϡhint ", , - * ..." ηΤ롣 - * - * port_profiles ФѹϡҤ PORT_PROFILE ˤäΤ - * 뤿ᡢCOMPONENT_PROFILE ǤΤʤ - * - * @else - * - * @brief Component profile - * - * This is enumeration member to specify that the target - * component's RTC::componentProfile has been changed. - * - * In the member of RTC::ComponentProfile, instance_name, - * type_name, description, version, vendor, category are not - * modified during RTC running. If these members are changed, each - * member's name is specified in the - * ComponentObserver::updateStatus() 's hint argument. And, - * modification to parent is not notified. In the properties, the - * modification is notified as ", , ..." in the hint - * argument. - * - * The modification to port_profiles is not notified as - * COMPONENT_PROFILE becauase it is notified as PORT_PROFILE. - * - * @endif - */ - COMPONENT_PROFILE, - /*! - * @if jp - * - * @brief ݡͥȤξ - * - * ݡͥȤξ֤ѲȤ򼨤ҡ - * - * RTCˤECξ֤ȤơINACTIVE_STATE, ACTIVE_STATE, - * ERROR_STATE 뤬ξ֤ѲȤΤ뤿 - * ҡ - * - * ComponentObserver::updatestatus() hint ˤϡ֤ȡɤμ¹ - * ƥȤѲäΤ餻ʲʸ hint ˰ - * ȤͿ롣 - * - * hint: (INACTIVE, ACTIVE, ERROR): - * : - * ACTIVE:0 (ǥեȥƥȤRTCƥ֤ˤʤä) - * ERROR:1002 (¹ԥƥ1002RTC顼ˤʤä) - * - * @else - * - * @brief Component status - * - * This is INACTIVE_STATE, ACTIVE_STATE, - * ERROR_STATE status, and this enumerator specify a status of RTC changed. - * - * A status and ExecutionContext's id is specified in the argument of - * ComponentObserver::updateStatus() 's hint. - * - * hint: (INACTIVE, ACTIVE, ERROR): - * Example: - * ACTIVE:0 (RTC is activated in the default ExecuionContext) - * ERROR:1002 (RTC go to ERROR state in the EC of id 1002) - * - * @endif - */ - RTC_STATUS, - /*! - * @if jp - * - * @brief ExecutionContextξ - * - * ExecutionContextξ֤ѲȤ򼨤ҡ - * - * RTCEC attach/detach/rate_change/startup/shutdown 줿Ȥ - * ҡ - * - * ComponentObserver::updatestatus() hint ˤϡ - * attach/detach/rate_change/startup/shutdow Τ줬Ԥ줿ȡ - * оݤȤʤECidͿ롣 - * - * hint: (ATTACHED, DETACHED, RATE_CHANGED, STARTUP, - * SHUTDOWN): - * - * : - * ATTACHED:1002 (ECå졢ID1002) - * - * @else - * - * @brief The stauts of ExecutionContext - * - * This is enumerator notifies that ExecutionContext is - * attach/detach/rate_change/startup/shutdown. Attach or detach - * operation and target ExecutionContext's id is given in the - * argument of ComponentObserver::updateStatus() 's hint. - * - * hint: (ATTACHED, DETACHED, RATE_CHANGED, STARTUP, - * SHUTDOWN): - * - * Example: - * ATTACHED:1002 (EC is attached and its ID is 1002) - * - * @endif - */ - EC_STATUS, - /*! - * @if jp - * - * @brief Portξ - * - * Portξ֤ѲȤ򼨤ҡPortɲá³ - * ǤԤ줿Ȥ򼨤ComponentObserver::updatestatus() - * hint ˤϡ줫Υ󤬹Ԥ줿ȡоݤȤʤݡ - * ̾Ϳ롣 - * - * hint: (ADD, REMOVE, CONNECT, DISCONNECT): - * : - * CONNECT:velocity (velocity ݡȤ³Ω줿) - * - * @else - * - * @brief The stauts of ports - * - * This is enumerator which notifies that port is added, removed, - * connected and/or disconnected. Which action is performed and - * target port's name is given to the hint argument in - * ComponentObserver::updateStatus() operation. - * - * hint: (ADD, REMOVE, CONNECT, DISCONNECT): - * Example: - * CONNECT:velocity (A connection established in the velocity port) - * - * @endif - */ - PORT_PROFILE, - /*! - * @if jp - * - * @brief Configurationξ - * - * Configurationξ֤ѲȤ򼨤ҡConfiguration - * ơե졼ѥ᡼줿 - * (UPDATE_CONFIG_PARAM)ե졼󤬥å() - * 줿 (SET_CONFIG_SET)ե졼󥻥åȤɲä줿 - * (ADD_CONFIG_SET)ե졼󤬹줿 - * (UPDATE_CONFIG_SET)ե졼󥻥åȤ줿 - * (REMOVE_CONFIG_SET)ե졼󥻥åȤƥ֤ - * 줿 (ACTIVATE_CONFIG_SET) Ȥä󤬤äȤ - * Τ롣 - * - * - UPDATE_CONFIG_PARAM: . - * - SDOPackage::Configuration::set_configuration_parameter - * - SET_CONFIG_SET: - * - SDOPackage::Configuration::set_configuration_set_values - * - ADD_CONFIG_SET: - * - SDOPackage::Configuration::add_configuration_set - * - UPDATE_CONFIG_SET: - * - ΥեåȤºݤѿȿǤ - * - REMOVE_CONFIG_SET: - * - SDOPackage::Configuration::remove_configuration_set - * - ACTIVATE_CONFIG_SET: - * - SDOPackage::Configuration::activate_configuration_set - * - * @else - * - * @brief The stauts of ports - * - * This is enumerator which notifies that configuration is - * changed. To the configuration, a configuration parameter has - * been updated (UPDATE_CONFIG_PARAM), a configuration-set is set - * (SET_CONFIG_SET), a configuration set has been updated - * (UPDATE_CONFIG_SET), a configuration set has been added - * (ADD_CONFIG_SET) or removed (REMOVE_CONFIG_SET), the active - * configuration set has been changed (ACTIVATE_CONFIG_SET), these - * actions would be notified. - * - * - UPDATE_CONFIG_PARAM: . - * - SDOPackage::Configuration::set_configuration_parameter - * - SET_CONFIG_SET: - * - SDOPackage::Configuration::set_configuration_set_values - * - ADD_CONFIG_SET: - * - SDOPackage::Configuration::add_configuration_set - * - UPDATE_CONFIG_SET: - * - Apply configuration-set values into actual variables. - * - REMOVE_CONFIG_SET: - * - SDOPackage::Configuration::remove_configuration_set - * - ACTIVATE_CONFIG_SET: - * - SDOPackage::Configuration::activate_configuration_set - * - * @endif - */ - CONFIGURATION, - /*! - * @if jp - * - * @brief ϡȥӡȥ٥ - * - * RTC¸Ƥ뤳Ȥ򥪥֥С¦Τҡ - * - * ϡȥӡȤѤ뤫ɤӥϡȥӡȤμϡ - * ServiceProfile::properties ΰʲΥץѥƥˤäͿ롣 - * - * heartbeat.enable: YES/NO - * heartbeat.interval: x [s] - * - * @else - * - * @brief The stauts of ports - * - * This enumerator is heart beat notification. - * - * Whether if the heart-beat function is used is specified in the - * ServiceProfile::properties as the following properties. - * - * heartbeat.enable: YES/NO - * heartbeat.interval: x [s] - * - * @endif - */ - HEARTBEAT, - - STATUS_KIND_NUM - }; - - /*! - * @if jp - * - * @interface ComponentObserver - * - * RTCγƼ֤ιΤ餻뤿Υ֥С֥ȤΤ - * Υ󥿡եSDO Service ȤơоݤȤʤRTC/SDOФ - * å졢RTC/SDOξ֤ѹ줿ˡѹ줿֤ - * ȥҥȤƱΤ롣ġʤɤǡݡ󥰤ˤ餺RTC - * ξ֤ѲΤꤿʤɤѤ롣 - * - * ꤷƤˡϰʲΤȤǤ롣 - * - * -# SDO::get_configuration() ˤ Configuration ֥Ȥ - * -# Configuration::add_service_profile() ˤTool¦ - * ComponentObserver ServiceProfile ˤ RTC Ϳ롣 - * ServiceProfile ΥСϰʲΤ褦ꤹ뤳 - * - id: UUID ʤɰդIDꤹ롣ˤɬפˤʤΤǡTool - * ¦ǤIDݻƤʤФʤʤ - * - interface_type: ӥIFRIDʸȤƻꡣRTC¦ - * Ϥʸˤӥ֥Ȥ뤫ꤹ - * 뤿ɬܤȤʤ롣 - * - properties: RTC¦Υӥμ¦Τץѥƥ - * ꤹ롣ΥӥǤϡ heartbeat ϢΥץѥƥ - * ꤹ롣 - * - service: SDOService ֥ȤλȤꤹ롣 - * -# RTC¦Ǿ֤Ѳä update_status() ڥ졼 - * StatusKind hint ʸȤȤ˸ƤӽФ롣Tool¦ - * ǤϡStatusKind hint ˴Ť RTC Τʬξ֤Ѳ - * ȤΤꡢɬפʽԤ - * -# ǽŪComponentObserver֥Ȥפˤʤäˤϡ - * Configuration::remove_service_profile() id ȤȤ˸ƤӽФ - * RTC 롣 - * - *
    -   * 
    -   *   [RTC]    [Configuration]           [Observer]    [Tool]
    -   *     |            |                       |            |
    -   *     |            | get_configuration()   |            |
    -   *     |<------------------------------------------------|
    -   *     |            |                       |            |
    -   *     |            | add_service_profile(prof)          |
    -   *     |            |<-----------------------------------|
    -   *     |            |                       |            |
    -   *     |            | update_status(kind, hint)          |
    -   *     |----------------------------------->|            |
    -   *     |            | update_status(kind, hint)          |
    -   *     |----------------------------------->|            |
    -   *     |            |       :               |            |
    -   *     |            |                       |            |
    -   *     |            | remove_service_profile(id)         |
    -   *     |            |<-----------------------------------|
    -   *     |            |                       |            |
    -   *     |            |                       x            x
    -   *
    -   * 
    - * - * ʤServiceProfile::properties ˻ꤹץѥƥȤƤϡ - * - * - observed_status: ALL or kind of status - * - heartbeat.enable: YES/NO - * - heartbeat.interval: x [s] - * - * 롣 - * - * - observed_staus: ALL ޤϾ֤μ򥫥޶ڤǻ - * ƻ뤹֤ꤹ롣ǽʾ֤ɽʸϡ - * COMPONENT_PROFILE, RTC_STATUS, EC_STATUS, PORT_PROFILE, - * CONFIGURATION 5Ǥ롣ƻ뤷оݤ򥫥ޤǶڤʣ - * ꤹ뤳ȤǤ롣ޤ٤Ƥξ֤ƻ뤹硢ALL - * 뤳ȤǤ롣ʸʸʸʤ - * - * - heartbeat.interval: ñ̤ǿͤǻ - * ϡȥӡȤñ̤ǻꤹ롣ʤꤷÿ - * ǥϡȥӡȤɬݾڤϤʤäơRTC - * ɤǧˤϡheartbeat.interval ʬλ֤Ԥ - * ɬפ롣 - * - * - heartbeat.enable: YES ޤ NOǻ - * Tool¦Ǥϡ֤Ѳޤ RTC ¸Ƥ뤫ɤΤ - * ȤϤǤʤᡢRTCˤϡΤ뤳Ȥ - * ʤǡHEART_BEAT ٥ȤŪRTC¦餻뤳 - * ȤǤ롣ϡȥӡȤͭˤ뤫ݤ򤳤Υץǻ - * 롣 - * - * - * @else - * - * @interface ComponentObserver - * - * This is an interface to notify various status changed in RTC to - * others. This is attached into a target RTC/SDO as a SDO service, - * and if an RTC/SDO's status change, a kind of changed status and - * its hints are notified to observers. For example, it can be used - * to notify RTC's status changed without polling in certain tools. - * - * An assumed usage is as follows. - * - * -# SDO::get_configuration() is called to get a Configuration object - * - * -# Configuration::add_service_profile() is called by Tool. - * A ComponentObserver in a ServiceProfile is given to RTC. - * ServiceProfile members should be set as follows. - * - * - id: UUID and other unique ID should be specified. Since this ID - * is used when the service is removed, tools should remember - * this ID. - * - * - interface_type: IFR ID should be specified here. Since the RTC - * decides if the given SDO service object can be accepted by - * using the interface_type string, this member is mandatory. - * - * - properties: This member specifies properties to be notified to - * RTC side. In this service, the following heartbeat related - * properties should be specified. - * - * - service: SDOService object reference should be specified. - * - * -# If some changes happen in RTC, the update_status() operation - * is called with StatusKind and hint string. RTC's status change - * is notified to tool and some processes would be performed by - * the tool according to the StatusKind and hint. - * - * -# Finally, When the ComponentObserver object becomes - * unnecessary, Configuration::remove_service_profile() is called - * with id and it is removed from RTC. - * - *
    -   * 
    -   *   [RTC]    [Configuration]           [Observer]    [Tool]
    -   *     |            |                       |            |
    -   *     |            | get_configuration()   |            |
    -   *     |<------------------------------------------------|
    -   *     |            |                       |            |
    -   *     |            | add_service_profile(prof)          |
    -   *     |            |<-----------------------------------|
    -   *     |            |                       |            |
    -   *     |            | update_status(kind, hint)          |
    -   *     |----------------------------------->|            |
    -   *     |            | update_status(kind, hint)          |
    -   *     |----------------------------------->|            |
    -   *     |            |       :               |            |
    -   *     |            |                       |            |
    -   *     |            | remove_service_profile(id)         |
    -   *     |            |<-----------------------------------|
    -   *     |            |                       |            |
    -   *     |            |                       x            x
    -   *
    -   * 
    - * - * Properties which is specified in ServiceProfile::properties is as follows. - * - * - observed_status: ALL or kind of status - * - heartbeat.enable: YES/NO - * - heartbeat.interval: x [s] - * - * - * - observed_staus: ALL or comma separated status kinds This - * property specifies kind of status to be observed. Available - * kind of statuses are COMPONENT_PROFILE, RTC_STATUS, EC_STATUS, - * PORT_PROFILE, CONFIGURATION. You can specify comma-separated - * status list to be observed. And if you want to observe all the - * status, you just specify ALL instead of all the status kind - * list. Uppercase, lowercase and mixture are allowed in the - * specified status kind. - * - * - heartbeat.enable: YES or NO - * - * Since tools cannot know whether the RTC is alive or not until - * status change happens, if the RTC suddenly died, the tools - * cannot know it forever. To eliminate this problems, Observer - * object can send periodic heartbeat signals to observers. The - * heartbeat.enable option specifies whether the functionality is - * activated or not. - * - * - heartbeat.interval: Heartbeat interval should be specified in - * seconds. This specification does not guarantee that heartbeat - * signals precisely send back to observer. Therefore if you need - * to decide whether an RTC died or not, you have to wait for - * several heartbeat signals. - * - * @endif - */ - interface ComponentObserver - : SDOPackage::SDOService - { - /*! - * @if jp - * - * @brief ֤줿ȤΤ餻 - * - * ֤줿ȤΤ餻륪ڥ졼status_kind ˤ - * ƹ줿֤μࡢhint ˤäƤɤΤ褦ʾ֤ѹ줿 - * ˴ؤҥȤͿ롣 - * - * @param status_kind: StatusKind ξ֤μ - * @param hint; StatusKind ˷ޤѹ˴ؤҥ - * - * @else - * - * @brief Notifies the status updated - * - * This operation notifies the updated status. The status_kind - * notifies kind of updated status, and the hint give some hint - * about updated status. - * - * @endif - */ - oneway void update_status(in StatusKind status_kind, in string hint); - }; - -}; diff --git a/OpenRTM_aist/test/DataPort.idl b/OpenRTM_aist/test/DataPort.idl deleted file mode 100644 index d9881ea2..00000000 --- a/OpenRTM_aist/test/DataPort.idl +++ /dev/null @@ -1,48 +0,0 @@ -// -*- IDL -*- -/*! - * @file DataPort.idl - * @brief DataPort interface definition - * @date $Date: 2007-01-09 15:40:14 $ - * @author Noriaki Ando - * - * Copyright (C) 2006 - * Noriaki Ando - * Task-intelligence Research Group, - * Intelligent Systems Research Institute, - * National Institute of - * Advanced Industrial Science and Technology (AIST), Japan - * - * All rights reserved. - * - * $Id: DataPort.idl 1597 2009-12-22 02:26:17Z n-ando $ - * - */ - -#ifndef DataInPort_idl -#define DataInPort_idl - -module OpenRTM -{ - enum PortStatus - { - PORT_OK, - PORT_ERROR, - BUFFER_FULL, - BUFFER_EMPTY, - BUFFER_TIMEOUT, - UNKNOWN_ERROR - }; - - typedef sequence CdrData; - - interface InPortCdr - { - PortStatus put(in CdrData data); - }; - - interface OutPortCdr - { - PortStatus get(out CdrData data); - }; -}; -#endif diff --git a/OpenRTM_aist/test/MySdoServiceConsumer.py b/OpenRTM_aist/test/MySdoServiceConsumer.py deleted file mode 100644 index 771a4bb2..00000000 --- a/OpenRTM_aist/test/MySdoServiceConsumer.py +++ /dev/null @@ -1,54 +0,0 @@ -#!/usr/bin/env python -# -*- Python -*- - - -## \file MySdoServiceConsumer.py -## \brief test for SdoServiceConsumer class -## \date $Date: $ -## \author Shinji Kurihara -# -# Copyright (C) 2011 -# Task-intelligence Research Group, -# Intelligent Systems Research Institute, -# National Institute of -# Advanced Industrial Science and Technology (AIST), Japan -# All rights reserved. -# - -import sys -sys.path.insert(1,"../") -sys.path.insert(1,"../RTM_IDL") -import OpenRTM_aist -import OpenRTM - - -class MySdoServiceConsumer(OpenRTM_aist.SdoServiceConsumerBase): - def __init__(self): - self._profile = None - self._rtobj = None - return - - def __del__(self): - return - - def init(self, rtobj, profile): - self._rtobj = rtobj - self._profile = profile - return True - - def reinit(self, profile): - return - - def getProfile(self): - return self._profile - - def finalize(self): - return - - -def MySdoServiceConsumerInit(manager): - factory = OpenRTM_aist.SdoServiceConsumerFactory.instance() - factory.addFactory(OpenRTM_aist.toTypename(OpenRTM.ComponentObserver), - MySdoServiceConsumer, - OpenRTM_aist.Delete) - return diff --git a/OpenRTM_aist/test/MyService.idl b/OpenRTM_aist/test/MyService.idl deleted file mode 100755 index 6fad67b0..00000000 --- a/OpenRTM_aist/test/MyService.idl +++ /dev/null @@ -1,4 +0,0 @@ -interface MyService -{ - string echo(in string msg); -}; diff --git a/OpenRTM_aist/test/OpenRTM.idl b/OpenRTM_aist/test/OpenRTM.idl deleted file mode 100644 index ab4c3db4..00000000 --- a/OpenRTM_aist/test/OpenRTM.idl +++ /dev/null @@ -1,64 +0,0 @@ -// -*- IDL -*- -/*! - * @file OpenRTM.idl - * @brief OpenRTM interface definition - * @date $Date: 2007-09-21 09:19:33 $ - * @author Noriaki Ando - * - * Copyright (C) 2007 - * Task-intelligence Research Group, - * Intelligent Systems Research Institute, - * National Institute of - * Advanced Industrial Science and Technology (AIST), Japan - * All rights reserved. - * - * $Id: OpenRTM.idl 1338 2009-05-18 05:58:25Z n-ando $ - * - */ - -#include "RTC.idl" - -#pragma prefix "openrtm.aist.go.jp" - -module OpenRTM -{ - - interface DataFlowComponent - : RTC::RTObject, RTC::DataFlowComponent - { - }; - -// interface FiniteStateMachineComponent -// : RTC::RTObject, RTC::FsmParticipant -// { -// }; -// -// interface DataFlowFiniteStateMachineComponent -// : RTC::RTObject, RTC::DataFlowComponent, RTC::FsmParticipant -// { -// }; -// -// interface DataFlowMultiModeComponent -// : RTC::RTObject, RTC::DataFlowComponent, RTC::MultiModeObject -// { -// }; -// -// interface FiniteStateMachineMultiModeComponent -// : RTC::RTObject, RTC::FsmParticipant, RTC::MultiModeObject -// { -// }; -// -// interface DataFlowFiniteStateMachineMultiModeComponent -// : RTC::RTObject, RTC::DataFlowComponent, -// RTC::FsmParticipant, RTC::MultiModeObject -// { -// }; - - - interface ExtTrigExecutionContextService - : RTC::ExecutionContextService - { - void tick(); - }; - -}; diff --git a/OpenRTM_aist/test/RTC.idl b/OpenRTM_aist/test/RTC.idl deleted file mode 100644 index 6c16cc21..00000000 --- a/OpenRTM_aist/test/RTC.idl +++ /dev/null @@ -1,2649 +0,0 @@ -// RTC.idl - -#include "SDOPackage.idl" - -#pragma prefix "omg.org" - -#define EXECUTION_HANDLE_TYPE_NATIVE long - -module RTC -{ - /*! - * @if jp - * @brief - * @else - * @brief ExecutionContextHandle_t - * - * @section Description - * - * This data type represents the association between an RTC and an - * ExecutionContext in which it participates. - * - * @section Semantics - * - * This is an opaque DataType. It has no attributes or operations. - * - * @endif - */ - typedef EXECUTION_HANDLE_TYPE_NATIVE ExecutionContextHandle_t; - - typedef SDOPackage::UniqueIdentifier UniqueIdentifier; - typedef SDOPackage::NVList NVList; - - /*! - * @if jp - * @brief ReturnCode_t - * - * OMG RTC 1.0 ¿Υڥ졼ϡ饤ȤФƹͤ - * 륨顼֤𤹤ɬפ롣ϡReturnCode_tν - * ꥿󥳡ɤˤԤ롣 - * - * OMG RTC 1.0 PIM ˤơReturnCode_t֤ͤʤڥ졼 - * ͤη˰¸ơˡˤꥨ顼𤹤ΤȤ롣 - * -ڥ졼֤ͤ (OMG RTC 1.0 Section 5.2.2.6.4 - * get_rateΤ褦)֤ͤȤˤꥨ顼򼨤ΤȤ롣 - * - ڥ졼󤬥֥ȥե(RTObject::get_component_profile - * OMG RTC 1.0 5.4.2.2.1򻲾) ֤̾硢nilȤ֤Ȥˤ - * 顼򼨤ΤȤ롣 - * - * @else - * @brief ReturnCode_t - * - * A number of operations in this specification will need to report - * potential error conditions to their clients. This task shall be - * accomplished by means of operation "return codes" of type - * ReturnCode_t - * - * Operations in the PIM that do not return a value of type - * ReturnCode_t shall report errors in the following ways, depending - * on their return type: - * - If an operation normally returns a positive numerical value (such as - * get_rate, see [OMG RTC 1.0 Section 5.2.2.6.4]), it shall indicate - * failure by returning a negative value. - * - If an operation normally returns an object reference (such as - * RTObject::get_component_profile, see [OMG RTC 1.0 Section 5.4.2.2.1]), - * it shall indicate failure by returning a nil reference. - * - * @param RTC_OK The operation completed successfully. - * @param RTC_ERROR The operation failed with a generic, unspecified error. - * @param BAD_PARAMETER The operation failed because an illegal argument was - * passed to it. - * @param UNSUPPORTED The operation is unsupported by the implementation - * (e.g., it belongs to a compliance point that is not implemented). - * @param OUT_OF_RESOURCES The target of the operation ran out of the - * resources needed to complete the operation. - * @param PRECONDITION_NOT_MET A pre-condition for the operation was not met. - * - * @endif - */ - enum ReturnCode_t - { - RTC_OK, - RTC_ERROR, - BAD_PARAMETER, - UNSUPPORTED, - OUT_OF_RESOURCES, - PRECONDITION_NOT_MET - }; - - /*! - * @if jp - * @brief - * @else - * @brief LifeCycleState - * - * @section Description - * LifeCycleState is an enumeration of the states in the lifecycle above. - * - * @endif - */ - enum LifeCycleState - { - /*! - * @if jp - * @brief - * @else - * @brief CREATED - * - * @section Description - * - * The RTC object has been instantiated but not yet fully initialized. - * @endif - */ - CREATED_STATE, - - /*! - * @if jp - * @brief - * @else - * @brief INACTIVE - * - * @section Description - * - * The RTC is Alive but is not being invoked in any execution - * context (see Section 5.2.2.5), regardless of whether the context - * is Running or not. - * - * @section Semantics - * - * An instance of this state exists for each execution context in - * which the RTC participates. If the RTC does not participate in - * any execution context, a single instance of this state exists. - * - * @endif - */ - INACTIVE_STATE, - - /*! - * @if jp - * @brief - * @else - * @brief ACTIVE - * - * @section Description - * - * The RTC is Alive and will be invoked in the execution context - * if the context is Running. - * - * @section Semantics - * - * An instance of this state exists for each execution context in - * which the RTC participates. If the RTC does not participate in - * any execution context, this state shall never be observed. - * - * @endif - */ - ACTIVE_STATE, - - /*! - * @if jp - * @brief - * @else - * @brief ERROR - * - * @section Description - * - * The RTC has encountered a problem in a given execution context - * and cannot continue functioning in that context without being - * reset. - * - * @endif - */ - ERROR_STATE - }; - - interface ExecutionContext; - typedef sequence ExecutionContextList; - - /*! - * @if jp - * @brief - * @else - * @brief ComponentAction - * - * @section Description - * - * The ComponentAction interface provides callbacks corresponding to - * the execution of the lifecycle operations of LightweightRTObject - * (see Section 5.2.2.2) and ExecutionContext (see Section - * 5.2.2.5). An RTC developer may implement these callback - * operations in order to execute application-specific logic - * pointing response to those transitions. - * - * @section Semantics - * - * Clients of an RTC are not expected to invoke these operations - * directly; they are provided for the benefit of the RTC middleware - * implementation. - * - * @endif - */ - interface ComponentAction - { - /*! - * @if jp - * @brief - * @else - * @brief on_initialize - * - * @section Description - * - * The RTC has been initialized and entered the Alive state. - * - * @section Semantics - * - * Any RTC-specific initialization logic should be performed here. - * - * @endif - */ - ReturnCode_t on_initialize(); - - /*! - * @if jp - * @brief - * @else - * @brief on_finalize - * - * @section Description - * - * The RTC is being destroyed. - * - * @section Semantics - * - * Any final RTC-specific tear-down logic should be performed here. - * - * @endif - */ - ReturnCode_t on_finalize(); - - /*! - * @if jp - * @brief - * @else - * @brief on_startup - * - * @section Description - * - * The given execution context, in which the RTC is participating, - * has transitioned from Stopped to Running. - * - * @endif - */ - ReturnCode_t on_startup(in ExecutionContextHandle_t exec_handle); - - /*! - * @if jp - * @brief - * @else - * @brief on_shutdown - * - * @section Description - * - * The given execution context, in which the RTC is participating, - * has transitioned from Running to Stopped. - * - * @endif - */ - ReturnCode_t on_shutdown(in ExecutionContextHandle_t exec_handle); - - /*! - * @if jp - * @brief - * @else - * @brief on_activated - * - * @section Description - * - * The RTC has been activated in the given execution context. - * - * @endif - */ - ReturnCode_t on_activated(in ExecutionContextHandle_t exec_handle); - - /*! - * @if jp - * @brief - * @else - * @brief on_deactivated - * - * @section Description - * - * The RTC has been deactivated in the given execution context. - * - * @endif - */ - ReturnCode_t on_deactivated(in ExecutionContextHandle_t exec_handle); - - /*! - * @if jp - * @brief - * @else - * @brief on_aborting - * - * @section Description - * - * The RTC is transitioning from the Active state to the Error - * state in some execution context. - * - * @section Semantics - * - * This callback is invoked only a single time for time that the - * RTC transitions into the Error state from another state. This - * behavior is in contrast to that of on_error. - * - * @endif - */ - ReturnCode_t on_aborting(in ExecutionContextHandle_t exec_handle); - - /*! - * @if jp - * @brief - * @else - * @brief on_error - * - * @section Description - * - * The RTC remains in the Error state. - * - * @section Semantics - * - * If the RTC is in the Error state relative to some execution - * context when it would otherwise be invoked from that context - * (according to the contexts ExecutionKind), this callback - * shall be invoked instead. For example, - * - * - If the ExecutionKind is PERIODIC, this operation shall be - * invoked in sorted order at the rate of the context instead of - * DataFlowComponentAction::on_execute and on_state_update. - * - * - If the ExecutionKind is EVENT_DRIVEN, this operation shall be - * invoked whenever FsmParticipantAction::on_action would - * otherwise have been invoked. - * - * @endif - */ - ReturnCode_t on_error(in ExecutionContextHandle_t exec_handle); - - /*! - * @if jp - * @brief - * @else - * @brief on_reset - * - * @section Description - * - * The RTC is in the Error state. An attempt is being made to - * recover it such that it can return to the Inactive state. - * - * @section Semantics - * - * If the RTC was successfully recovered and can safely return to - * the Inactive state, this method shall complete with - * ReturnCode_t::OK. Any other result shall indicate that the RTC - * should remain in the Error state. - * - * @endif - */ - ReturnCode_t on_reset(in ExecutionContextHandle_t exec_handle); - }; - - /*! - * @if jp - * @brief - * @else - * @brief LightweightRTObject - * - * @section Description - * - * This interface is realized by all lightweight RTCs (as required - * by the lightweightRTComponent stereotype). It defines the states - * and transitions through which all RTCs will pass from the time - * they are created until the time they are destroyed. - * - * @section Semantics - * @subsection Initialization - * - * An RTC begins in the Created state; at this point, it has been - * instantiated but not yet fully initialized. Note that this state - * is highly implementation-dependent. For example, it may - * correspond to the invocation of a constructor in languages that - * support that concept, but not all languages do. Furthermore, how - * soon this state is entered before initialize is invoked is - * implementation-dependent. Therefore, it should be relied on by - * RTC implementers only to the minimum extent possible. An RTC - * that has completed its initialization and has not been finalized - * is said to be Alive. - * - * @subsection Execution Context - * - * An RTC in the Alive state may participate in any number of - * execution contexts (see Section 5.2.2.5 ). These contexts shall - * be represented to an RTC as distinct instances of the - * ExecutionContext class. The ExecutionContext manages the behavior - * of each RTC that participates in it. This relationship is defined - * by the following state machine, which is embedded within the - * ExecutionContext's own lifecycle (see Figure 5.5 ). Each - * participating RTC is represented as a separate parallel region. - * - * Relative to a given execution context, an RTC may either be - * Active, Inactive, or in Error. When the RTC is Active in a - * Running execution context, the ComponentAction callbacks (see - * Section 5.2.2.4) shall be invoked as appropriate for the context - * s ExecutionKind. The callbacks shall not be invoked relative to - * that context when either the RTC is Inactive in that context or - * the context is Stopped. (Note that starting and stopping an - * execution context shall not impact whether its participating RTCs - * are Active or Inactive.) It may be that a given RTC does not - * directly participate in any execution contexts. Such an RTC is - * referred to as passive. A passive RTC may provide services to - * other components upon request. At any other time, it shall not be - * required to perform any ongoing activity of its own; therefore, - * instances of such an RTC typically exist only as parts (directly - * or indirectly) of a containing active RTC. - * - * @subsection Error Handling - * - * If an operation fails while the RTC is Active in a given - * execution context, the RTC will transition to the Error state - * corresponding to that context. While the RTC is in Error, the - * ComponentAction::on_error callback will be invoked in place of - * those callbacks that would otherwise have been invoked according - * to the contexts ExecutionKind. For example, if the kind is - * PERIODIC, on_error shall be invoked instead of the pair of - * on_execute, and on_state_update. When an RTC is in Error, it may - * be reset. If resetting is successful, the RTC shall return to the - * Inactive state. If resetting is unsuccessful, it shall remain in - * the Error state. - * - * @endif - */ - interface LightweightRTObject - : ComponentAction - { - /*! - * @if jp - * @brief - * @else - * @brief initialize - * - * @section Description - * Initialize the RTC that realizes this interface. - * - * @section Semantics - * The invocation of this operation shall result in the invocation - * of the callback ComponentAction::on_initialize. - * - * @section Constraints - * - * - An RTC may be initialized only while it is in the Created - * state. Any attempt to invoke this operation while in another - * state shall fail with ReturnCode_t::PRECONDITION_NOT_MET. - * - Application developers are not expected to call this operation - * directly; it exists for use by the RTC infrastructure. - * - * @endif - */ - ReturnCode_t initialize(); - - /*! - * @if jp - * @brief - * @else - * @brief finalize - * - * @section Description - * - * Finalize the RTC that realizes this interface, preparing it for - * destruction. - * - * @section Semantics - * - * This invocation of this operation shall result in the - * invocation of the callback ComponentAction::on_finalize - * - * @section Constraints - * - * - An RTC may not be finalized while it is participating in any - * execution context. It must first be removed with - * ExecutionContextOperations::remove_component. Otherwise, this - * operation shall fail with - * ReturnCode_t::PRECONDITION_NOT_MET. See Figure 5.9. - * - * - An RTC may not be finalized while it is in the Created state. Any - * attempt to invoke this operation while in that state shall fail with - * ReturnCode_t::PRECONDITION_NOT_MET. - * - * - Application developers are not expected to call this operation - * directly; it exists for use by the RTC infrastructure. - * - * @endif - */ - ReturnCode_t finalize(); - - /*! - * @if jp - * @brief - * @else - * @brief is_alive - * - * @section Description - * - * A component is alive or not regardless of the execution context - * from which it is observed. However, whether or not it is - * Active, Inactive, or in Error is dependent on the execution - * context(s) (see Figure 5.7) in which it is running. That is, it - * may be Active in one context but Inactive in - * another. Therefore, this operation shall report whether this - * RTC is either Active, Inactive, or in Error; which of those - * states a component is in with respect to a particular context - * may be queried from the context itself. - * - * @endif - * - */ - boolean is_alive(in ExecutionContext exec_context); - - /*! - * @if jp - * @brief - * @else - * @brief exit - * - * @section Description - * - * Stop the RTCs execution context(s) and finalize it along with - * its contents. - * - * @section Semantics - * - * Any execution contexts for which the RTC is the owner shall be - * stopped. If the RTC participates in any execution contexts - * belonging to another RTC that contains it, directly or - * indirectly (i.e., the containing RTC is the owner of the - * ExecutionContext), it shall be deactivated in those contexts. - * After the RTC is no longer Active in any Running execution - * context, it and any RTCs contained transitively within it shall - * be finalized. - * - * @section Constraints - * - * An RTC cannot be exited if it has not yet been initialized. Any - * attempt to exit an RTC that is in the Created state shall fail - * with ReturnCode_t::PRECONDITION_NOT_MET. - * - * @endif - */ - ReturnCode_t exit(); - - /*! - * @if jp - * @brief - * @else - * @brief attach_context - * - * @section Description - * - * Inform this RTC that it is participating in the given execution - * context. Return a handle that represents the association of - * this RTC with the context. - * - * @section Semantics - * - * This operation is intended to be invoked by - * ExecutionContextOperations::add_component (see Section - * 5.2.2.6.6). It is not intended for use by other clients. - * - * @endif - */ - ExecutionContextHandle_t attach_context(in ExecutionContext exec_context); - - /*! - * @if jp - * @brief - * @else - * @brief detach_context - * @section Description - * - * Inform this RTC that it is no longer participating in the given - * execution context. - * - * @section Semantics - * - * This operation is intended to be invoked by - * ExecutionContextOperations::remove_component (see Section - * 5.2.2.6.7). It is not intended for use by other clients. - * - * @section Constraints - * - * - This operation may not be invoked if this RTC is not already - * participating in the execution context. Such a call shall fail - * with ReturnCode_t::PRECONDITION_NOT_MET. - * - * - This operation may not be invoked if this RTC is Active in - * the indicated execution context. Otherwise, it shall fail with - * ReturnCode_t::PRECONDITION_NOT_MET. - * - * @endif - */ - ReturnCode_t detach_context(in ExecutionContextHandle_t exec_handle); - - /*! - * @if jp - * @brief - * @else - * @brief get_context - * - * @section Description - * - * Obtain a reference to the execution context represented by the - * given handle. - * - * @section Semantics - * - * The mapping from handle to context is specific to a particular - * RTC instance. The given handle must have been obtained by a - * previous call to attach_context on this RTC. - * - * @endif - */ - ExecutionContext get_context(in ExecutionContextHandle_t exec_handle); - - /*! - * @if jp - * @brief get_owned_contexts - * - * @section Description - * - * RTC ͭ ExecutionContext ΥꥹȤ롣 - * - * @else - * @brief get_owned_contexts - * - * @section Description - * - * This operation returns a list of all execution contexts owned - * by this RTC. - * - * @endif - */ - ExecutionContextList get_owned_contexts(); - - /*! - * @if jp - * @brief get_participating_contexts - * - * @section Description - * - * RTC äƤ뤹٤Ƥ ExecutionContext ΥꥹȤ롣 - * - * @section Semantics - * - * ΥꥹȤ˴ޤޤ¹ԥƥȤϡattach_context Ƥӽ - * 뤴ȤˡꥹȤɲä졢detach_context ƤӽФ뤴 - * ȤˡꥹȤ롣 - * - * @else - * @brief* get_participating_contexts - * - * @section Description - * - * This operation returns a list of all execution contexts in - * which this RTC participates. - * - * @section Semantics - * - * Each call to attach_context causes the provided context to be - * added to this list. Each call to detach_context causes the - * provided context to be removed from this list. - * - * @endif - */ - ExecutionContextList get_participating_contexts(); - - /*! - * @if jp - * ### [] RTC.idl ˤϴޤޤƤʤPIMˤϴޤޤƤ롣 - * ### PIM - * - * @brief - * @else - * @brief get_context_handle - * - * @section Description - * - * This operation returns a handle that is associated with the given - * execution context. - * - * @endif - */ - ExecutionContextHandle_t get_context_handle(in ExecutionContext cxt); - }; - - /*! - * @if jp - * @brief - * @else - * @brief ExecutionKind - * - * @sectioni Description - * - * The ExecutionKind enumeration defines the execution semantics - * (see Section 5.3) of the RTCs that participate in an execution - * context. - * - * @endif - */ - enum ExecutionKind - { - /*! - * @if jp - * @brief - * - * @else - * @brief PERIODIC - * - * @section Description - * - * The participant RTCs are executing according to periodic - * sampled data semantics (see Section 5.3.1). - * - * @endif - */ - PERIODIC, - /*! - * @if jp - * @brief - * - * @else - * @brief EVENT_DRIVEN - * - * @section Description - * - * The participant RTCs are executing according to stimulus - * response semantics (see Section 5.3.2). - * - * @endif - */ - EVENT_DRIVEN, - /*! - * @if jp - * @brief - * - * @else - * @brief OTHER - * - * @section Description - * - * The participant RTCs are executing according to some semantics - * not defined by this specification. - * - * @endif - */ - OTHER - }; - - /*! - * @if jp - * @brief - * @else - * @brief ExecutionContext - * - * @section Description - * - * An ExecutionContext allows the business logic of an RTC to be - * decoupled from the thread of control in which it is executed. The - * context represents a logical thread of control and is provided to - * RTCs at runtime as an argument to various operations, allowing - * them to query and modify their own state, and that of other RTCs - * executing within the same context, in the lifecycle. This - * separation of concerns is important for two primary reasons: - * - * - Large number of components may collaborate tightly within a - * single node or process. If each component were to run within its - * own thread of control, the infrastructure may not be able to - * satisfy the timeliness and determinism requirements of real-time - * applications due to the large number of threads and the required - * synchronization between them. - * - * - A single application may carry out a number of independent - * tasks that require different execution rates. For example, it may - * need to sample a sensor periodically at a very high rate and update a - * user interface at a much lower rate. - * - * @section Semantics - * - * The state machine of an ExecutionContext has two parts. The - * behavior of the ExecutionContext itself is defined by the upper - * region in the above figure. The behavior of the RTCs that - * participate in the context is defined by the lower region. The - * contents of that region are displayed in more detail in Figure - * 5.5 in Section 5.2.2.2. Ownership and Participation Each - * execution context is owned by a single RTC and may be used to - * execute that RTC and the RTCs contained within it, directly or - * indirectly. An RTC that owns one or more execution contexts is - * known as an autonomous RTC. An autonomous RTC and some subset of - * the RTCs within it (to be defined by the application developer) - * shall be executed by the infrastructure according to the context - * s execution kind, which defines when each RTCs operations will - * be invoked when and in which order. These RTCs are said to - * participate in the context. The available execution kinds are - * described in Section 5.2.2.7. The relationship between RTCs and - * execution contexts may be many-to-many in the general case: - * multiple RTCs may be invoked from the same execution context, and - * a single RTC may be invoked from multiple contexts. In the case - * where multiple RTCs are invoked from the same context, starting - * or stopping the context shall result in the corresponding - * lifecycle transitions for all of those components. - * - * @section Logical and Physical Threads - * - * Although an execution context represents a logical thread of - * control, the choice of how it maps to a physical thread shall be - * left to the applications deployment - * environment. Implementations may elect to associate contexts with - * threads with a one-to-one mapping, to serve multiple contexts - * from a single thread, or by any other means. In the case where a - * given RTC may be invoked from multiple contexts, concurrency - * management is implementation-dependent. - * - * @endif - */ - interface ExecutionContext - { - - /*! - * @if jp - * @brief - * @else - * @brief is_running - * @section Description - * - * This operation shall return true if the context is in the - * Running state. - * - * @section Semantics - * - * While the context is Running, all Active RTCs participating in - * the context shall be executed according to the contexts - * execution kind. - * - * @endif - */ - boolean is_running(); - - /*! - * @if jp - * @brief - * @else - * - * @brief start - * - * @section Description - * - * Request that the context enter the Running state. Once the - * state transition occurs, the ComponentAction::on_startup - * operation (see Section 5.2.2.4.3) will be invoked. @section * - * - * @section Semantics - * - * An execution context may not be started - * until the RT components that participate in it have been - * initialized. An execution context may be started and stopped - * multiple times. - * - * @section Constraints - * - * - This operation shall fail with - * ReturnCode_t::PRECONDITION_NOT_MET if the context is not in the - * Stopped state. - * - * - This operation shall fail with - * ReturnCode_t::PRECONDITION_NOT_MET if any of the participating - * components are not in their Alive state. - * - * @endif - */ - ReturnCode_t start(); - - /*! - * @if jp - * @brief - * @else - * @brief stop - * - * @section Description - * - * Request that the context enter the Stopped state. Once the - * transition occurs, the ComponentAction::on_shutdown operation - * (see Section 5.2.2.4.4) will be invoked. - * - * @section Semantics - * - * An execution context must be stopped before the RT components - * that participate in it are finalized. - * - * An execution context may be started and stopped multiple times. - * - * @section Constraints - * - * - This operation shall fail with - * ReturnCode_t::PRECONDITION_NOT_MET if the context is not in the - * Running state. - * - * @endif - */ - ReturnCode_t stop(); - - /*! - * @if jp - * @brief - * @else - * @brief get_rate - * - * @section Description - * - * This operation shall return the rate (in hertz) at which its - * Active participating RTCs are being invoked. - * - * @section Semantics - * - * An implementation is permitted to perform some periodic or - * quasi-periodic processing within an execution context with an - * ExecutionKind other than PERIODIC. In such a case, the result - * of this operation is implementation-defined. If no periodic - * processing of any kind is taking place within the context, this - * operation shall fail as described in Section 5.2.1. - * - * @section Constraints - * - * - If the context has an ExecutionKind of PERIODIC, this - * operation shall return a rate greater than zero. - * - * @endif - */ - double get_rate(); - - /*! - * @if jp - * @brief - * @else - * @brief set_rate - * - * @section Description - * - * This operation shall set the rate (in hertz) at which this - * contexts Active participating RTCs are being called. - * - * @section Semantics - * - * If the execution kind of the context is PERIODIC, a rate change - * shall result in the invocation of on_rate_changed on any RTCs - * realizing DataFlowComponentAction that are registered with any - * RTCs participating in the context. An implementation is - * permitted to perform some periodic or quasi-periodic processing - * within an execution context with an ExecutionKind other than - * PERIODIC. If such is the case, and the implementation reports a - * rate from get_rate, this operation shall set that rate - * successfully provided that the given rate is valid. If no - * periodic processing of any kind is taking place within the - * context, this operation shall fail with - * ReturnCode_t::UNSUPPORTED. - * - * @section Constraints - * - * - The given rate must be greater than zero. Otherwise, this - * operation shall fail with ReturnCode_t::BAD_PARAMETER. - * - * @endif - */ - ReturnCode_t set_rate(in double rate); - - /*! - * @if jp - * @brief - * @else - * @brief add_component - * - * @section Description - * - * The operation causes the given RTC to begin participating in - * the execution context. - * - * @section Semantics - * - * The newly added RTC will receive a call to - * LightweightRTComponent::attach_context (see Section 5.2.2.2.5) - * and then enter the Inactive state. - * - * @section Constraints - * - * - If the ExecutionKind of this context is PERIODIC, the RTC - * must be a data flow component (see Section 5.3.1.1). - * Otherwise, this operation shall fail with - * ReturnCode_t::PRECONDITION_NOT_MET. - * - * - If the ExecutionKind of this context is EVENT_DRIVEN, the RTC - * must be an FSM participant (see Section 5.3.2.3). Otherwise, - * this operation shall fail with - * ReturnCode_t::PRECONDITION_NOT_MET. - * - * @endif - */ - ReturnCode_t add_component(in LightweightRTObject comp); - - /*! - * @if jp - * @brief - * @else - * @brief remove_component - * - * @section Description - * - * This operation causes a participant RTC to stop participating - * in the execution context. - * - * @section Semantics - * - * The removed RTC will receive a call to - * LightweightRTComponent::detach_context (see Section 5.2.2.2.6). - * - * @section Constraints - * - * - If the given RTC is not currently participating in the - * execution context, this operation shall fail with - * ReturnCode_t::BAD_PARAMETER. - * - * - An RTC must be deactivated before it can be removed from an - * execution context. If the given RTC is participating in the - * execution context but is still in the Active state, this - * operation shall fail with ReturnCode_t::PRECONDITION_NOT_MET. - * - * @endif - */ - ReturnCode_t remove_component(in LightweightRTObject comp); - - /*! - * @if jp - * @brief - * @else - * @brief activate_component - * - * @section Description - * - * The given participant RTC is Inactive and is therefore not - * being invoked according to the execution contexts execution - * kind. This operation shall cause the RTC to transition to the - * Active state such that it may subsequently be invoked in this - * execution context. - * - * @section Semantics - * - * The callback on_activate shall be called as a result of calling - * this operation. This operation shall not return until the - * callback has returned, and shall result in an error if the - * callback does. The following figure is a non-normative example - * sequence diagram for activate_component. - * - * @section Constraints - * - * - An execution context can only activate its participant - * components. If the given RTC is not participating in the - * execution context, this operation shall fail with - * ReturnCode_t::BAD_PARAMETER. - * - * - An RTC that is in the Error state cannot be activated until - * after it has been reset. If the given RTC is in the Error - * state, this operation shall fail with - * ReturnCode_t::PRECONDITION_NOT_MET. - * - * - This operation shall fail with ReturnCode_t::BAD_PARAMETER if - * the given component is not in its Alive state. - * - * @endif - */ - ReturnCode_t activate_component(in LightweightRTObject comp); - - /*! - * @if jp - * @brief - * @else - * @brief deactivate_component - * - * @section Description - * - * The given RTC is Active in the execution context. Cause it to - * transition to the Inactive state such that it will not be - * subsequently invoked from the context unless and until it is - * activated again. - * - * @section Semantics - * - * The callback on_deactivate shall be called as a result of - * calling this operation. This operation shall not return until - * the callback has returned, and shall result in an error if the - * callback does. The following figure is a non-normative example - * sequence diagram for deactivate_component. - * - * @section Constraints - * - * - An execution context can only deactivate its participant - * components. If the given RTC is not participating in the - * execution context, this operation shall fail with - * ReturnCode_t::BAD_PARAMETER. - * - * - This operation shall fail with ReturnCode_t::BAD_PARAMETER if - * the given component is not in its Alive state. - * - * @endif - */ - ReturnCode_t deactivate_component(in LightweightRTObject comp); - - /*! - * @if jp - * @brief - * @else - * @brief reset_component - * - * @section Description - * - * Attempt to recover the RTC when it is in Error. - * - * @section Semantics - * - * The ComponentAction::on_reset callback shall be invoked. This - * operation shall not return until the callback has returned, and - * shall result in an error if the callback does. If possible, the - * RTC developer should implement that callback such that the RTC - * may be returned to a valid state. * If this operation fails, - * the RTC will remain in Error. - * - * @section Constraints - * - * - An RTC may only be reset in an execution context in which it - * is in error. If the RTC is not in Error in the identified - * context, this operation shall fail with - * ReturnCode_t::PRECONDITION_NOT_MET. However, that failure shall - * not cause the RTC to enter the Error state. - * - * - An RTC may not be reset while in the Created state. Any - * attempt to invoke this operation while the RTC is in that state - * shall fail with ReturnCode_t::PRECONDITION_NOT_MET. However, - * that failure shall not cause the RTC to enter the Error state. - * - * @endif - */ - ReturnCode_t reset_component(in LightweightRTObject comp); - - /*! - * @if jp - * @brief - * @else - * @brief get_component_state - * - * @section Description - * - * This operation shall report the LifeCycleState of the given - * participant RTC. - * - * @section Constraints - * - * - The given RTC must be Alive. - * - * - The given RTC must be a participant in the target execution context. - * - * - The LifeCycleState returned by this operation shall be one of - * LifeCycleState::INACTIVE, ACTIVE, or ERROR. - * - * @endif - */ - LifeCycleState get_component_state(in LightweightRTObject comp); - - /*! - * @if jp - * @brief - * @else - * @brief get_kind - * - * @section Description - * - * This operation shall report the execution kind of the execution - * context. - * - * @endif - */ - ExecutionKind get_kind(); - }; - - - /*! - * @if jp - * @brief - * @else - * @brief DataFlowComponentAction - * - * @section Description - * - * DataFlowComponentAction is a companion to ComponentAction (see - * Section 5.2.2.4) that provides additional callbacks for - * intercepting the two execution passes defined in Section - * 5.3.1.1.2. - * - * @endif - */ - interface DataFlowComponentAction - { - /*! - * @if jp - * @brief - * @else - * @brief on_execute - * @section Description - * - * This operation will be invoked periodically at the rate of the - * given execution context as long as the following conditions - * hold: - * - * - The RTC is Active. - * - * - The given execution context is Running. - * - * @section Semantics - * - This callback occurs during the first execution pass. - * - * @section Constraints - * - * - The execution context of the given context shall be PERIODIC. - * - * @endif - */ - ReturnCode_t on_execute(in ExecutionContextHandle_t exec_handle); - /*! - * @if jp - * @brief - * @else - * @brief on_state_update - * - * @section Description - * - * This operation will be invoked periodically at the rate of the - * given execution context as long as the following conditions hold: - * - * - The RTC is Active. - * - * - The given execution context is Running. - * - * @section Semantics - * - * This callback occurs during the second execution pass. - * - * @section Constraints - * - * - The execution context of the given context shall be PERIODIC. - * - * - * @endif - */ - ReturnCode_t on_state_update(in ExecutionContextHandle_t exec_handle); - /*! - * @if jp - * @brief - * @else - * @brief on_rate_changed - * - * @section Description - * - * This operation is a notification that the rate of the indicated - * execution context (see Section 5.2.2.6.4) has changed. - * - * @section Constraints - * - * - The execution context of the given context shall be PERIODIC. - * - * - * @endif - */ - ReturnCode_t on_rate_changed(in ExecutionContextHandle_t exec_handle); - }; - - /*! - * @if jp - * @brief - * @else - * @brief dataFlowComponent - * - * @section Description - * - * The dataFlowComponent stereotype may be applied to a component - * type to indicate that its instances should be executed in sorted - * order by a periodic execution context. - * - * @section Constraints - * - * - An instance of a component extended by the dataFlowComponent - * stereotype must participate in at least one * execution context - * of kind PERIODIC, which shall also be used for the execution of - * any contained data flow components. - * - * - A component extended by dataFlowComponent must realize the - * interface DataFlowComponentAction. - * - * - * @endif - */ - interface DataFlowComponent - : LightweightRTObject, DataFlowComponentAction - { - }; - - /*! - * @if jp - * @brief - * @else - * @brief fsm - * - * @section Description - * - * Applying the fsm stereotype to a component implies the ability to - * define component-specific states and transitions. - * - * @section Semantics - * - * In creating a state machine such as is depicted in Figure 5.22, - * the RTC developer is implicitly defining the Active state to be a - * submachine state. * The BehaviorStateMachines package described - * in [UML] is considered the normative definition of a state - * machine. - * - * @endif - */ - interface Fsm - : LightweightRTObject - { - }; - - /*! - * @if jp - * @brief - * @else - * @brief FsmParticipantAction - * - * @section Description - * - * FsmParticipantAction is companion to ComponentAction (see Section - * 5.2.2.4) that is intended for use with FSM participant RTCs. It - * adds a callback for the interception of state transitions, state - * entries, and state exits. - * - * @endif - */ - interface FsmParticipantAction - { - - /*! - * @if jp - * @brief - * @else - * @brief on_action - * - * @section Description - * - * The indicated FSM participant RTC has been invoked as a result - * of a transition, state entry, or state exit in its containing - * FSM. - * - * @section Constraints - * - * - The given execution context shall be of kind EVENT_DRIVEN. - * - * @endif - */ - ReturnCode_t on_action(in ExecutionContextHandle_t exec_handle); - }; - - /*! - * @if jp - * @brief - * @else - * @brief - * @endif - */ - interface FsmParticipant - : LightweightRTObject, FsmParticipantAction - { - }; - - /*! - * @if jp - * @brief - * @else - * @brief Mode - * - * @section Description - * - * Each mode defined by a given RTC shall be represented by an - * instance of Mode. - * - * @endif - */ - interface Mode - { - }; - - /*! - * @if jp - * @brief - * @else - * @brief ModeCapable - * - * @section Description - * - * The ModeCapable interface provides access to an objects modes - * and a means to set the current mode. - * - * @section Semantics - * - * A given RTC may support multiple modes as well as multiple - * execution contexts. In such a case, a request for a mode change - * (e.g., from "cruise control on" to "cruise control off") may - * come asynchronously with respect to one or more of those - * execution contexts. The mode of an RTC may therefore be observed - * to be different from one execution context to another. - A mode - * is pending in a given execution context when a mode change has - * been requested but the new mode has not yet been observed by that - * context. - * - * - The new mode has been committed in a given execution context - * when the context finally observes the new mode. - * - * - The new mode has stabilized once it has been committed in all - * execution contexts in which the RTC participates. - * - * Figure 5.26 depicts a state machine that describes mode - * changes. Each parallel region in the composite state Mode Pending - * represents an execution context. The trigger "sample" within - * that state is considered to have occurred: - just before the - * next call to on_execute (see Section 5.3.1.2.1) in the case where - * immediate is false and the execution kind is PERIODIC, - * - * - just before the processing of the next stimulus in the case - * where immediate is false and the execution kind is - * EVENT_DRIVEN, or - immediately in all other cases. - * - * @endif - */ - interface ModeCapable - { - /*! - * @if jp - * @brief - * @else - * @brief get_default_mode - * - * @section Description - * - * This operation shall return the mode in which the RTC shall be - * when no other mode has been set. - * - * @section Constraints - * - * - This operation shall not return nil. - * - * @endif - */ - Mode get_default_mode(); - /*! - * @if jp - * @brief - * @else - * @brief get_current_mode - * - * @section Description - * - * This operation shall return the last mode to have - * stabilized. If no mode has been explicitly set, the current - * mode shall be the default mode. - * - * @section Constraints - * - * - This operation shall never return nil. - * - * @endif - */ - Mode get_current_mode(); - /*! - * @if jp - * @brief - * @else - * @brief get_current_mode_in_context - * - * @section Description - * - * This operation returns the current mode of the component as - * seen by the indicated execution context. - * - * @section Semantics - * - * The manner in which this property changes is described in Figure 5.26. - * - * @endif - */ - Mode get_current_mode_in_context(in ExecutionContext exec_context); - /*! - * @if jp - * @brief - * @else - * @brief get_pending_mode - * - * @section Description - * - * This operation shall return the last mode to have been passed - * to set_mode that has not yet stabilized. Once the RTCs mode - * has stabilized, this operation shall return nil. - * - * @endif - */ - Mode get_pending_mode(); - /*! - * @if jp - * @brief - * @else - * @brief get_pending_mode_in_context - * - * @section Description - * - * If the last mode to be requested by a call to set_mode is - * different than the current mode as seen by the indicated - * execution context (see get_current_mode_in_context), this - * operation returns the former. If the requested mode has already - * been seen in that context, it returns nil. - * - * @section Semantics - * - * See Figure 5.26 for a description of how the pending mode - * relates to the current mode within a given execution context. - * - * @endif - */ - Mode get_pending_mode_in_context(in ExecutionContext exec_context); - /*! - * @if jp - * @brief - * @else - * @brief set_mode - * - * @section Description - * - * This operation shall request that the RTC change to the indicated mode. - * - * @section Semantics - * - * Usually, the new mode will be pending in each execution context - * in which the component executes until the next sample period - * (if the execution kind is PERIODIC); at that point it will - * become the current mode in that context and there will no - * longer be a pending mode. However, in some cases it is - * important for a mode change to take place immediately; for - * example, a serious fault has occurred and the component must - * enter an emergency mode to ensure fail-safe behavior in a - * safety-critical system. In such a case, immediate should be - * true and the mode change will take place in all contexts - * without waiting for the next sample period. - * - * @endif - */ - ReturnCode_t set_mode(in Mode new_mode, - in boolean immediate); - }; - - /*! - * @if jp - * @brief - * @else - * @brief MultiModeComponentAction - * - * MultiModeComponentAction is a companion to ComponentAction that - is realized by RTCs that support multiple modes. - * - * @endif - */ - interface MultiModeComponentAction - { - /*! - * @if jp - * @brief - * @else - * @brief on_mode_changed - * - * @section Description - * - * This callback is invoked each time the observed mode of a - * component has changed with respect to a particular execution - * context. - * - * @section Semantics - * - * If the context is PERIODIC, this callback shall come before the - * next call to on_execute (see Section 5.3.1.2.1) within that - * context. The new mode can be retrieved with - * get_current_mode_in_context. If the result is the same as the - * result of get_current_mode, the mode has stabilized. - * - * @endif - */ - ReturnCode_t on_mode_changed(in ExecutionContextHandle_t exec_handle); - }; - - /*! - * @if jp - * @brief - * @else - * @brief - * @endif - */ - interface MultiModeObject - : LightweightRTObject, ModeCapable, MultiModeComponentAction - { - }; - - interface RTObject; - - /*! - * @if jp - * @brief - * @else - * @brief PortInterfacePolarity - * - * @section Description - * - * The PortInterfacePolarity enumeration identifies exposed - * interface instances as provided or required. @endif - */ - enum PortInterfacePolarity - { - /*! - * @if jp - * @brief - * @else - * @brief PROVIDED - * - * @section Description - * - * The target interface is provided as an output by the target - * port. - * - * @endif - */ - PROVIDED, - /*! - * @if jp - * @brief - * @else - * @brief REQUIRED - * - * @section Description - * - * The target interface is required as an input by the target port. - * - * @endif - */ - REQUIRED - }; - - /*! - * @if jp - * @brief - * @else - * @brief PortInterfaceProfile - * - * @section Description - * - * PortInterfaceProfile describes an instance of a particular - * interface as it is exposed by a particular port. These objects - * are referred to below as the "target interface" and "target - * port" respectively. - * - * @endif - */ - struct PortInterfaceProfile - { - /*! - * @if jp - * @brief - * @else - * @brief instance_name - * - * @section Description - * - * This attribute stores the name of the target interface instance. - * - * @endif - */ - string instance_name; - /*! - * @if jp - * @brief - * @else - * @brief type_name - * - * @section Description - * - * This attribute stores the name of the target interface type. - * - * @endif - */ - string type_name; - /*! - * @if jp - * @brief - * @else - * @brief polarity - * - * @section Description - * - * This attribute indicates whether the target interface instance - * is provided or required by the RTC. - * - * @endif - */ - PortInterfacePolarity polarity; - }; - - typedef sequence PortInterfaceProfileList; - - interface PortService; - typedef sequence PortServiceList; - typedef sequence RTCList; - - /*! - * @if jp - * @brief - * @else - * @brief ConnectorProfile - * - * @section Description - * - * The ConnectorProfile contains information about a connection - * between the ports of collaborating RTCs. - * - * @endif - */ - struct ConnectorProfile - { - /*! - * @if jp - * @brief - * @else - * @brief name - * - * @section Description - * - * This attribute contains the name of this connection. - * - * @endif - */ - string name; - /*! - * @if jp - * @brief - * @else - * @brief connector_id - * - * @section Description - * - * Each connector has a unique identifier that is assigned when - * connection is established. This attribute stores that - * identifier. - * - * @endif - */ - UniqueIdentifier connector_id; - /*! - * @if jp - * @brief - * @else - * @brief ports - * - * @section Description - * - * This field stores references to all ports connected by the - * target connector. - * - * @endif - */ - PortServiceList ports; - /*! - * @if jp - * @brief - * @else - * @brief properties - * - * @section Description - * - * This attribute contains additional properties of the connection. - * - * @section Semantics - * - * This attribute provides implementations the opportunity to - * describe additional characteristics of a particular connection - * that are outside of the scope of this specification. - * - * @endif - */ - NVList properties; - }; - - typedef sequence ConnectorProfileList; - - /*! - * @if jp - * @brief - * @else - * @brief PortProfile - * - * @section Description - * - * A PortProfile describes a port of an RTC (referred to as the - * "target" RTC). This port is referred to as the "target" port. - * From this profile, other components and tools can obtain Ports - * name, type, object reference, and so on. - * - * @endif - */ - struct PortProfile - { - /*! - * @if jp - * @brief - * @else - * @brief name - * - * @section Description - * - * This attribute contains the name of the target port. - * - * @section Semantics - * - * Ports owned by an RTC are distinguished by their - * names. Therefore, this name should be unique within the target - * RTC. - * - * @endif - */ - string name; - /*! - * @if jp - * @brief - * @else - * @brief interfaces - * - * @section Description - * - * This attribute contains the name and polarity of each interface - * exposed by the target port. - * - * @endif - */ - PortInterfaceProfileList interfaces; - /*! - * @if jp - * @brief - * @else - * @brief port_ref - * - * @section Description - * - * This attributes contains a reference to the target port. - * - * @endif - */ - PortService port_ref; - /*! - * @if jp - * @brief - * @else - * @brief connector_profiles - * - * @section Description - * - * This attribute contains a collection of profiles describing the - * connections to the target port. - * - * @endif - */ - ConnectorProfileList connector_profiles; - /*! - * @if jp - * @brief - * @else - * @brief owner - * - * @section Description - * - * This attribute contains a reference to the target RTC. - * - * @endif - */ - RTObject owner; - /*! - * @if jp - * @brief - * @else - * @brief properties - * - * @section Description - * - * This attribute contains additional properties of the port. - * - * @section Semantics - * - * This attribute provides implementations the opportunity to - * describe additional characteristics of a particular port that - * are otherwise outside of the scope of this specification. - * - * @endif - */ - NVList properties; - }; - - typedef sequence PortProfileList; - - /*! - * @if jp - * @brief - * @else - * @brief - * @endif - */ - struct ExecutionContextProfile - { - /*! - * @if jp - * @brief - * @else - * @brief kind - * - * @section Description - * - * This attribute stores the contexts ExecutionKind. - * - * @endif - */ - ExecutionKind kind; - /*! - * @if jp - * @brief - * @else - * @brief rate - * - * @section Description - * - * This attribute stores execution rate. - * - * @section Semantics - * - * If the execution kind is not PERIODIC, the value here may not - * be valid (and should be negative in that case). See - * ExecutionContext::get_rate (see Section 5.2.2.6.4) and set_rate - * (see Section 5.2.2.6.5) for more information. - * - * @endif - */ - double rate; - /*! - * @if jp - * @brief - * @else - * @brief owner - * - * @section Description - * - * This attribute stores a reference to the RTC that owns the context. - * - * @endif - */ - RTObject owner; - /*! - * @if jp - * @brief - * @else - * @brief participants - * - * @section Description - * - * This attribute stores references to the contexts participant RTCs. - * - * @endif - */ - RTCList participants; - /*! - * @if jp - * @brief - * @else - * @brief properties - * - * @section Description - * - * This attribute contains additional properties of the execution - * context. - * - * @section Semantics - * - * This attribute provides implementations the opportunity to - * describe additional characteristics of a particular execution - * context that are outside the scope of this specification. - * - * @endif - */ - NVList properties; - }; - - typedef sequence - ExecutionContextProfileList; - - /*! - * @if jp - * @brief - * @else - * @brief FsmObject - * - * @section Description - * - * The FsmObject interface allows programs to send stimuli to a - * finite state machine, possibly causing it to change states. - * - * @endif - */ - interface FsmObject - { - /*! - * @if jp - * @brief - * @else - * @brief send_stimulus - * - * @section Description - * - * Send a stimulus to an FSM that realizes this interface. - * - * @section Semantics - * - * If the stimulus corresponds to any outgoing transition of the - * current state, that transition shall be taken and the state - * shall change. Any FSM participants associated with the exit of - * the current state, the transition to the new state, or the - * entry to the new state shall be invoked. If the stimulus does - * not correspond to any such transition, this operation shall - * succeed but have no effect. - * - * If the given execution context is a non-nil reference to a - * context in which this FSM participates, the transition shall be - * executed in that context. If the argument is nil, the FSM shall - * choose an EVENT_DRIVEN context in which to execute the - * transition. If the argument is non-nil, but this FSM does not - * participate in the given context, this operation shall fail - * with * ReturnCode_t::BAD_PARAMETER. - * - * @section Constraints - * - * - The given execution context shall be of kind EVENT_DRIVEN. - * - * @endif - */ - ReturnCode_t send_stimulus(in string message, - in ExecutionContextHandle_t exec_handle); - }; - - /*! - * @if jp - * @brief - * @else - * @brief FsmBehaviorProfile - * - * @section Description - * - * FsmBehaviorProfile represents the association of an FSM - * participant with a transition, state entry, or state exit in an - * FSM. - * - * @section Semantics - * - * The assignment of identifiers to particular transitions, state - * entries, or state exits is implementation-dependent. - * - * @endif - */ - struct FsmBehaviorProfile - { - /*! - * @if jp - * @brief - * @else - * @brief action_component - * - * @section Description - * - * This attribute stores a reference to the FSM participant that - * is invoked when the containing Fsm receives a message - * distinguished by id. - * - * @endif - */ - FsmParticipantAction action_component; - /*! - * @if jp - * @brief - * @else - * @brief id - * - * @section Description - * - * This attribute stores the message identifier. - * - * @endif - */ - UniqueIdentifier id; - }; - - typedef sequence FsmBehaviorProfileList; - /*! - * @if jp - * @brief - * @else - * @brief FsmProfile - * - * @section Description - * - * The FsmProfile describes the correspondence between an FSM and - * its contained FSM participants. This Profile is necessary for - * Stimulus Response Processing. - * - * @endif - */ - struct FsmProfile - { - /*! - * @if jp - * @brief - * @else - * @brief behavior_profiles - * - * @section Description - * - * This attribute lists the correspondences between an FSM and its - * contained FSM participants. - * - * @endif - */ - FsmBehaviorProfileList behavior_profiles; - }; - - /*! - * @if jp - * @brief - * @else - * @brief FsmService - * - * @section Description - * - * The FsmService interface defines operations necessary for - * Stimulus Response Processing as an SDO service. - * - * @endif - */ - interface FsmService - : SDOPackage::SDOService - { - /*! - * @if jp - * @brief - * @else - * @brief get_fsm_profile - * - * @section Description - * - * Get the current state of the FSM. - * - * @section Semantics - * - * Modifications to the object returned by this operation will not - * be reflected in the FSM until and unless set_fsm_profile is - * called. - * - * @endif - */ - FsmProfile get_fsm_profile(); - /*! - * @if jp - * @brief - * @else - * @brief set_fsm_profile - * - * @section Description - * - * This operation will be used to modify the behavior of an FSM as - * described in Stimulus Response Processing. - * - * @endif - */ - ReturnCode_t set_fsm_profile(in FsmProfile fsm_profile); - }; - - /*! - * @if jp - * @brief - * @else - * @brief ComponentProfile - * - * @section Description - * - * ComponentProfile represents the static state of an RTC that is - * referred to here as the "target" RTC. - * - * @endif - */ - struct ComponentProfile - { - /*! - * @if jp - * @brief - * @else - * @brief instance_name - * - * @section Description - * - * This attribute shall contain the name of the target RTC instance. - * - * @section Semantics - * - * The instance_name should be unique among RTC instances - * contained within the same containing component. - * - * @endif - */ - string instance_name; - /*! - * @if jp - * @brief - * @else - * @brief type_name - * - * @section Description - * - * This attribute shall contain the name of the target RTC class. - * - * @section Semantics - * - * Each RTC class must have a name that is unique within an - * application. - * - * @endif - */ - string type_name; - /*! - * @if jp - * @brief - * @else - * @brief description - * - * @section Description - * - * This attribute shall briefly describe the target RTC for the - * benefit of a human operator. - * - * @endif - */ - string description; - /*! - * @if jp - * @brief - * @else - * @brief version - * - * @section Description - * - * This attribute shall contain the version number of the target - * RTC class. - * - * @section Semantics - * - * The format of the version number is outside of the scope of - * this specification. - * - * @endif - */ - string version; - /*! - * @if jp - * @brief - * @else - * @brief vendor - * - * @section Description - * - * The name of the individual or organization that produced the - * target RTC class. - * - * @endif - */ - string vendor; - /*! - * @if jp - * @brief - * @else - * @brief category - * - * @section Description - * - * This attribute contains the name of a "category" or group to - * which the target RTC belongs. - * - * - * @endif - */ - string category; - /*! - * @if jp - * @brief - * @else - * @brief port_profiles - * - * @section Description - * - * This attribute contains a list of PortProfiles that describe - * the ports of the target RTC. - * - * @section Semantics - * - * There shall be a one-to-one correspondence between the members - * of this list and the ports of the target RTC. - * - * - * @endif - */ - PortProfileList port_profiles; - /*! - * @if jp - * @brief - * @else - * @brief parent - * - * @section Description - * - * This attribute contains a reference to the RTC that contains - * the target RTC instance. If the target RTC instance is not - * owned by any other RTC, this field stores a nil reference. - * - * @endif - */ - RTObject parent; - /*! - * @if jp - * @brief - * @else - * @brief properties - * - * @section Description - * - * This attribute contains additional properties of the target RTC. - * - * @section Semantics - * - * This attribute provides implementations the opportunity to - * describe additional characteristics of a particular RTC that - * are otherwise outside of the scope of this specification. - * - * @endif - */ - NVList properties; - }; - - typedef sequence ComponentProfileList; - - /*! - * @if jp - * @brief - * @else - * @brief PortService - * - * @section Description - * - * An instance of the PortService interface represents a port (i.e., - * UML::Composite Structures::Ports::Port) of an RTC. It provides - * operations that allow it to be connected to and disconnected from - * other ports. - * - * @section Semantics - * - * A port service can support unidirectional or bidirectional - * communication. A port service may allow for a service-oriented - * connection, in which other connected ports, invoke methods on - * it. It may also allow for a data-centric connection, in which - * data values are streamed in or out. In either case, the - * connection is described by an instance of - * ConnectorProfile. However, the behavioral contracts of such - * connections are dependent on the interfaces exposed by the ports - * and are not described normatively by this specification. - * - * @endif - */ - interface PortService - : SDOPackage::SDOService - { - /*! - * @if jp - * @brief - * @else - * @brief get_port_profile - * - * @section Description - * - * This operation returns the PortProfile of the PortService. - * - * @endif - */ - PortProfile get_port_profile(); - /*! - * @if jp - * @brief - * @else - * @brief get_connector_profiles - * - * @section Description - * - * This operation returns a list of the ConnectorProfiles of the - * PortService. - * - * @endif - */ - ConnectorProfileList get_connector_profiles(); - /*! - * @if jp - * @brief - * @else - * @brief get_connector_profiles - * - * @section Description - * - * This operation returns a list of the ConnectorProfiles of the - * PortService. - * - * @endif - */ - ConnectorProfile get_connector_profile(in UniqueIdentifier connector_id); - /*! - * @if jp - * @brief - * @else - * @brief connect - * - * @section Description - * - * This operation establishes connection between this port and the - * peer ports according to given ConnectionProfile. - * - * @section Semantics - * - * A ConnectorProfile has a sequence of port references. This port - * invokes the notify_connect operation of one of the ports - * included in the sequence. It follows that the notification of - * connection is propagated by the notify_connect operation with - * ConnectorProfile. This operation returns ConnectorProfile - * return value and returns ReturnCode_t as return codes. - * - * @endif - */ - ReturnCode_t connect(inout ConnectorProfile connector_profile); - /*! - * @if jp - * @brief - * @else - * @brief disconnect - * - * @section Description - * - * This operation destroys the connection between this port and - * its peer ports using the ID that was given when the connection - * was established. - * - * @section Semantics - * - * This port invokes the notify_disconnect operation of one of the - * ports included in the sequence of the ConnectorProfile stored - * when the connection was established. The notification of - * disconnection is propagated by the notify_disconnect operation. - * - * @endif - */ - ReturnCode_t disconnect(in UniqueIdentifier connector_id); - /*! - * @if jp - * @brief - * @else - * @brief disconnect_all - * - * @section Description - * - * This operation destroys all connection channels owned by the - * PortService. - * - * @endif - */ - ReturnCode_t disconnect_all(); - /*! - * @if jp - * @brief - * @else - * @brief notify_connect - * - * @section Description - * - * This operation notifies this PortService of the connection - * between its corresponding port and the other ports and - * propagates the given ConnectionProfile. - * - * @section Semantics - * - * A ConnectorProfile has a sequence of port references. This - * PortService stores the ConnectorProfile and invokes the - * notify_connect operation of the next PortService in the - * sequence. As ports are added to the connector, PortService - * references are added to the ConnectorProfile and provided to - * the caller. In this way, notification of connection is - * propagated with the ConnectorProfile. - * - * @endif - */ - ReturnCode_t notify_connect(inout ConnectorProfile connector_profile); - /*! - * @if jp - * @brief - * @else - * @brief notify_disconnect - * - * @section Description - * - * This operation notifies a PortService of a disconnection - * between its corresponding port and the other ports. The - * disconnected connector is identified by the given ID, which was - * given when the connection was established. - * - * @section Semantics - * - * This port invokes the notify_disconnect operation of the next - * PortService in the sequence of the ConnectorProfile that was - * stored when the connection was established. As ports are - * disconnected, PortService references are removed from the - * ConnectorProfile. In this way, the notification of - * disconnection is propagated by the notify_disconnect operation. - * - * @endif - */ - ReturnCode_t notify_disconnect(in UniqueIdentifier connector_id); - }; - - /*! - * @if jp - * @brief - * @else - * @brief ExecutionContextService - * - * @section Description - * - * An ExecutionContextService exposes an ExecutionContext as an SDO - * service such that the context may be controlled remotely. - * - * @section Semantics - * - * Depending on the implementation, this interface may itself be an - * execution context (that is, it may be passed to the operations of - * ComponentAction) or it may represent a remote execution context - * that is not of type ExecutionContextService. @endif - */ - interface ExecutionContextService - : ExecutionContext, SDOPackage::SDOService - { - /*! - * @if jp - * @brief - * @else - * @brief get_profile - * - * @section Description - * - * This operation provides a profile "descriptor" for the - * execution context. - * - * @endif - */ - ExecutionContextProfile get_profile(); - }; - - typedef sequence - ExecutionContextServiceList; - - /*! - * @if jp - * @brief - * @else - * @brief RTObject - * - * @section Description - * - * The RTObject interface defines the operations that all SDO-based - * RTCs must provide. It is required by the rtComponent stereotype. - * - * @endif - */ - interface RTObject - : LightweightRTObject, SDOPackage::SDO - { - /*! - * @if jp - * @brief - * @else - * @brief get_component_profile - * - * @section Description - * - * This operation returns the ComponentProfile of the RTC. - * - * @endif - */ - ComponentProfile get_component_profile(); - /*! - * @if jp - * @brief - * @else - * @brief get_ports - * - * @section Description - * - * This operation returns a list of the RTCs ports. - * - * @endif - */ - PortServiceList get_ports(); - }; -}; - diff --git a/OpenRTM_aist/test/SDOPackage.idl b/OpenRTM_aist/test/SDOPackage.idl deleted file mode 100644 index 6bc18dad..00000000 --- a/OpenRTM_aist/test/SDOPackage.idl +++ /dev/null @@ -1,294 +0,0 @@ -//Platform Independent Model (PIM) and Platform Specific Model (PSM) -//for Super Distributed Objects (SDO) Specification, v1.1 - OMG IDL Summary File -//Object Management Group, Inc. -//Copyright (c) 2003, Fraunhofer FOKUS -//Copyright (c) 2003, Hitachi, Ltd. -//The companies listed above have granted to the Object Management Group, Inc. -//(OMG) a nonexclusive, royalty-free, paid up, worldwide license to copy and -//distribute this document and to modify this document and distribute copies of -//the modified version. Each of the copyright holders listed above has agreed -//that no person shall be deemed to have infringed the copyright in the included -//material of any such copyright holder by reason of having used the -//specification set forth herein or having conformed any computer software to -//the specification. -// -//This file contains OMG IDL from the Naming Service Specification, v1.2. -//OMG regularly publishes a summary file that contains all the "code" parts of -//an OMG formal document. Every formal document line that is IDL, PIDL, or -//language code is included in the summary file. The reason for such a listing -//is to give readers an electronic version of the "code" so that they can -//extract pieces of it. Readers might want to test an example, include it in -//their own code, or use it for documentation purposes. Having the code lines -//available electronically means there is less likelihood of a transcription -//error. -// -// ver 1.0 formal/2004-11-02 -// ver 1.1 (RTF report: dtc/2008-03-05) -// -//SDOPackage.idl - -#ifndef _SDO_PACKAGE_IDL_ -#define _SDO_PACKAGE_IDL_ - -#ifdef TAO_IDL -#include -#endif -#ifdef USE_MONITORING -#include -#endif -#ifndef ORBIT2_IDL -#define TypeCode CORBA::TypeCode -#endif -/** CORBA specific model for SDOs */ - -#pragma prefix "org.omg" -#define exception_body { string description; } - -module SDOPackage -{ - interface SDO; - interface SDOService; - interface SDOSystemElement; - interface Configuration; - interface Monitoring; - interface Organization; - - /** ------- Data Types -------*/ - typedef sequence StringList; - typedef sequence SDOList; - typedef sequence OrganizationList; - typedef string UniqueIdentifier; - - struct NameValue - { - string name; - any value; - }; - - typedef sequence NVList; - - enum NumericType - { - SHORT_TYPE, - LONG_TYPE, - FLOAT_TYPE, - DOUBLE_TYPE - }; - - union Numeric switch (NumericType) - { - case SHORT_TYPE: short short_value; - case LONG_TYPE: long long_value; - case FLOAT_TYPE: float float_value; - case DOUBLE_TYPE: double double_value; - }; - - struct EnumerationType - { - StringList enumerated_values; - }; - - struct RangeType - { - Numeric min; - Numeric max; - boolean min_inclusive; - boolean max_inclusive; - }; - - struct IntervalType - { - Numeric min; - Numeric max; - boolean min_inclusive; - boolean max_inclusive; - Numeric step; - }; - - enum ComplexDataType - { - ENUMERATION, RANGE, INTERVAL - }; - - union AllowedValues switch (ComplexDataType) - { - case ENUMERATION: EnumerationType allowed_enum; - case INTERVAL: IntervalType allowed_interval; - case RANGE: RangeType allowed_range; - }; - - struct Parameter - { - string name; - TypeCode type; - AllowedValues allowed_values; - }; - - typedef sequence ParameterList; - struct OrganizationProperty - { - NVList properties; - }; - enum DependencyType - { - OWN, - OWNED, - NO_DEPENDENCY - }; - - struct DeviceProfile - { - string device_type; - string manufacturer; - string model; - string version; - NVList properties; - }; - - struct ServiceProfile - { - string id; - string interface_type; - NVList properties; - SDOService service; - }; - - typedef sequence ServiceProfileList; - struct ConfigurationSet - { - string id; - string description; - NVList configuration_data; - }; - - typedef sequence ConfigurationSetList; - - - /** ------- Exceptions -------*/ - exception NotAvailable exception_body; - exception InterfaceNotImplemented exception_body; - exception InvalidParameter exception_body; - exception InternalError exception_body; - - /** ------- Interfaces -------*/ - interface SDOSystemElement - { - OrganizationList get_owned_organizations() - raises (NotAvailable,InternalError); - }; - interface SDO : SDOSystemElement - { - UniqueIdentifier get_sdo_id() - raises (NotAvailable, InternalError); - string get_sdo_type() - raises (NotAvailable, InternalError); - DeviceProfile get_device_profile () - raises (NotAvailable, InternalError); - ServiceProfileList get_service_profiles () - raises (NotAvailable, InternalError); - ServiceProfile get_service_profile (in UniqueIdentifier id) - raises (InvalidParameter, NotAvailable, InternalError); - SDOService get_sdo_service (in UniqueIdentifier id) - raises (InvalidParameter, NotAvailable, InternalError); - Configuration get_configuration () - raises (InterfaceNotImplemented, NotAvailable, InternalError); - Monitoring get_monitoring () - raises (InterfaceNotImplemented, NotAvailable, InternalError); - OrganizationList get_organizations () - raises (NotAvailable, InternalError); - NVList get_status_list () - raises (NotAvailable, InternalError); - any get_status (in string nme) - raises (InvalidParameter, NotAvailable, InternalError); - }; - - - interface Configuration - { - boolean set_device_profile (in DeviceProfile dProfile) - raises (InvalidParameter, NotAvailable, InternalError); - boolean add_service_profile (in ServiceProfile sProfile) - raises (InvalidParameter, NotAvailable, InternalError); - boolean add_organization (in Organization organization_object) - raises (InvalidParameter, NotAvailable, InternalError); - boolean remove_service_profile (in UniqueIdentifier id) - raises (InvalidParameter, NotAvailable, InternalError); - boolean remove_organization (in UniqueIdentifier organization_id) - raises (InvalidParameter, NotAvailable, InternalError); - ParameterList get_configuration_parameters () - raises (NotAvailable, InternalError); - NVList get_configuration_parameter_values () - raises (NotAvailable, InternalError); - any get_configuration_parameter_value (in string name) - raises (InvalidParameter, NotAvailable, InternalError); - boolean set_configuration_parameter (in string name, - in any value) - raises (InvalidParameter, NotAvailable, InternalError); - ConfigurationSetList get_configuration_sets () - raises (NotAvailable, InternalError); - ConfigurationSet get_configuration_set (in UniqueIdentifier config_id) - raises (NotAvailable, InternalError); - boolean set_configuration_set_values (in ConfigurationSet configuration_set) - raises (InvalidParameter, NotAvailable, InternalError); - ConfigurationSet get_active_configuration_set () - raises (NotAvailable, InternalError); - boolean add_configuration_set (in ConfigurationSet configuration_set) - raises (InvalidParameter, NotAvailable, InternalError); - boolean remove_configuration_set (in UniqueIdentifier config_id) - raises (InvalidParameter, NotAvailable, InternalError); - boolean activate_configuration_set (in UniqueIdentifier config_id) - raises (InvalidParameter, NotAvailable, InternalError); - }; - - -#ifdef USE_MONITORING - interface Monitoring : CosNotifyComm::StructuredPushConsumer, - CosNotifyComm::StructuredPushSupplier - { - any get_monitoring_parameter_value (in string name) - raises (InvalidParameter, NotAvailable, InternalError); - ParameterList get_monitoring_parameters () - raises (NotAvailable, InternalError); - NVList get_monitoring_parameter_values () - raises (NotAvailable, InternalError); - }; -#else - interface Monitoring {}; -#endif - - interface SDOService {}; - - interface Organization - { - UniqueIdentifier get_organization_id () - raises (InvalidParameter, NotAvailable, InternalError); - OrganizationProperty get_organization_property () - raises (NotAvailable, InternalError); - any get_organization_property_value (in string name) - raises (InvalidParameter, NotAvailable, InternalError); - boolean add_organization_property (in OrganizationProperty organization_property) - raises (InvalidParameter, NotAvailable, InternalError); - boolean set_organization_property_value (in string name, - in any value) - raises (InvalidParameter, NotAvailable, InternalError); - boolean remove_organization_property ( in string name ) - raises (InvalidParameter, NotAvailable, InternalError); - SDOSystemElement get_owner () - raises (NotAvailable, InternalError); - boolean set_owner (in SDOSystemElement sdo) - raises (InvalidParameter, NotAvailable, InternalError); - SDOList get_members () - raises (NotAvailable, InternalError); - boolean set_members (in SDOList sdos) - raises (InvalidParameter, NotAvailable, InternalError); - boolean add_members ( in SDOList sdo_list) - raises (InvalidParameter, NotAvailable, InternalError); - boolean remove_member (in UniqueIdentifier id) - raises (InvalidParameter, NotAvailable, InternalError); - DependencyType get_dependency() - raises (NotAvailable, InternalError); - boolean set_dependency (in DependencyType dependency) - raises (NotAvailable, InternalError); - }; -}; -#endif //_SDO_PACKAGE_IDL_ diff --git a/OpenRTM_aist/test/configsample.conf b/OpenRTM_aist/test/configsample.conf deleted file mode 100755 index a234252f..00000000 --- a/OpenRTM_aist/test/configsample.conf +++ /dev/null @@ -1,15 +0,0 @@ -conf.mode0.int_param0: 12345 -conf.mode0.int_param1: 98765 -conf.mode0.double_param0: 3.141592653589793238462643383279 -conf.mode0.double_param1: 2.718281828459045235360287471352 -conf.mode0.str_param0: bar -conf.mode0.str_param1: foo -conf.mode0.vector_param0: 0.0,0.1,0.2,0.3,0.4 - -conf.mode1.int_param0: -999 -conf.mode1.int_param1: 999 -conf.mode1.double_param0: 297992458 -conf.mode1.double_param1: 2.97992458e+8 -conf.mode1.str_param0: OpenRTM -conf.mode1.str_param1: AIST -conf.mode1.vector_param0: 1,2,3,4,5,6,7,8,9 diff --git a/OpenRTM_aist/test/hoge.py b/OpenRTM_aist/test/hoge.py deleted file mode 100755 index 01dff468..00000000 --- a/OpenRTM_aist/test/hoge.py +++ /dev/null @@ -1,41 +0,0 @@ -#!/usr/bin/env python -# -*- Python -*- - -hoge_spec = ["implementation_id", "hoge", - "type_name", "hoge", - "description", "hoge component", - "version", "1.0", - "vendor", "Shinji Kurihara", - "category", "example", - "activity_type", "DataFlowComponent", - "max_instance", "10", - "language", "Python", - "lang_type", "script", - ""] - -class HOGE: - def __init__(self): - pass - -def echo(*args): - print "hello HOGE" - - - -""" -import sys -argv = sys.argv[1:] -for x in argv: - try: - f = open(x) - print"---",x,"---" - for i in range(15): - print i+1,f.readline(), - print "---",x,"---\n" - f.close() - except IOError: - print "Can't find file:", x - -""" - - diff --git a/OpenRTM_aist/test/rtc.conf b/OpenRTM_aist/test/rtc.conf deleted file mode 100755 index 993cf7e8..00000000 --- a/OpenRTM_aist/test/rtc.conf +++ /dev/null @@ -1,6 +0,0 @@ -corba.nameservers: localhost -naming.formats: %n.rtc -logger.log_level: PARANOID -example.TestComp.config_file: configsample.conf -manager.modules.preload: ConfigSample -manager.shutdown_on_nortcs: NO \ No newline at end of file diff --git a/OpenRTM_aist/test/sample.py b/OpenRTM_aist/test/sample.py deleted file mode 100755 index ba77c47b..00000000 --- a/OpenRTM_aist/test/sample.py +++ /dev/null @@ -1,7 +0,0 @@ -#!/usr/bin/env python -# -*- Python -*- - -class test: - def __init__(self): - pass - diff --git a/OpenRTM_aist/test/test_All.py b/OpenRTM_aist/test/test_All.py deleted file mode 100755 index f99849f7..00000000 --- a/OpenRTM_aist/test/test_All.py +++ /dev/null @@ -1,104 +0,0 @@ -#!/usr/bin/env python -# -*- Python -*- - -import unittest -from test import test_support - -from test_BufferBase import * -from test_ConfigAdmin import * -from test_CORBA_SeqUtil import * -from test_CorbaConsumer import * -from test_CorbaNaming import * -from test_CorbaPort import * -from test_ECFactory import * -from test_ExtTrigExecutionContext import * -from test_Factory import * -from test_InPort import * -from test_InPortBase import * -from test_InPortProvider import * -from test_Listener import * -from test_Manager import * -from test_ManagerConfig import * -from test_ModuleManager import * -from test_NamingManager import * -from test_NumberingPolicy import * -from test_NVUtil import * -from test_ObjectManager import * -from test_OutPort import * -from test_OutPortBase import * -from test_OutPortProvider import * -from test_PeriodicExecutionContext import * -from test_PortAdmin import * -from test_PortBase import * -from test_Properties import * -from test_PublisherNew import * -from test_PublisherPeriodic import * -from test_RingBuffer import * -from test_RTCUtil import * -from test_RTObject import * -from test_SdoConfiguration import * -from test_SdoOrganization import * -from test_SdoService import * -from test_StateMachine import * -from test_StringUtil import * -from test_SystemLogger import * -from test_Timer import * -from test_TimeValue import * - - -# \file test_All.py -# -# Copyright (C) 2006 -# Noriaki Ando -# Task-intelligence Research Group, -# Intelligent Systems Research Institute, -# National Institute of -# Advanced Industrial Science and Technology (AIST), Japan -# All rights reserved. -# - -def test_main(): - test_support.run_unittest( - TestNullBuffer, - TestConfigAdmin, - TestCORBA_SeqUtil, - TestCorbaConsumer, - TestCorbaNaming, - TestCorbaPort, - TestECFactoryPython, - TestExtTrigExecutionContext, - TestFactoryPython, - TestInPort, - TestInPortBase, - TestInPortProvider, - TestListener, - TestManagerConfig, - TestModuleManager, - TestDefaultNumberingPolicy, - TestNVUtil, - TestObjectManager, - TestOutPort, - TestOutPortBase, - TestOutPortProvider, - TestPeriodicExecutionContext, - TestPortAdmin, - TestPortBase, - TestProperties, - TestPublisherNew, - TestPublisherPeriodic, - TestRingBuffer, - TestRTCUtil, - TestRTObject_impl, - TestConfiguration_impl, - TestOrganization_impl, - TestSDOServiceProfile, - TestStateMachine, - TestStringUtil, - TestLogger, - TestTimer, - TestTimeValue, - TestManager, - ) - -if __name__ == '__main__': - test_main() diff --git a/OpenRTM_aist/test/test_Async.py b/OpenRTM_aist/test/test_Async.py deleted file mode 100755 index 98533c45..00000000 --- a/OpenRTM_aist/test/test_Async.py +++ /dev/null @@ -1,117 +0,0 @@ -#!/usr/bin/env python -# -*- coding: euc-jp -*- - -# @file test_Async.py -# @brief test for Async class -# @date $Date: 2009/02/18$ -# @author Shinji Kurihara -# -# Copyright (C) 2009 -# Task-intelligence Research Group, -# Intelligent Systems Research Institute, -# National Institute of -# Advanced Industrial Science and Technology (AIST), Japan -# All rights reserved. -# - -import time -import sys -sys.path.insert(1,"../") - -import unittest -from Async import * - -class A: - def __init__(self): - self._hoge = False - self._munya = False - self._addone = False - return - - def hoge(self): - for i in range(5): - print ",", - time.sleep(1) - print - self._hoge = True - return - - def hoge_invoked(self): - return self._hoge - - def munya(self, msg): - print - for i in range(5): - print ",", - time.sleep(1) - self._munya = True - return - - def munya_invoked(self): - return self._munya - - def add_one(self, val): - for i in range(5): - print ",", - time.sleep(1) - self._addone = True - return val+1 - - def add_one_invoked(self): - return self._addone - - -class add_one_functor: - def __init__(self, val): - self._val = val - self._ret = None - - def __call__(self, obj): - self._ret = obj.add_one(self._val) - - def get_ret(self): - return self._ret - - - -class TestAsync(unittest.TestCase): - def setUp(self): - pass - - def test_memfun(self): - a = A() - invoker = Async_tInvoker(a,A.hoge) - invoker.invoke() - self.assertEqual(a.hoge_invoked(),False) - invoker.wait() - self.assertEqual(a.hoge_invoked(),True) - return - - - def test_memfun_with_args(self): - a = A() - invoker = Async_tInvoker(a,A.munya,"munyamunya") - invoker.invoke() - self.assertEqual(a.munya_invoked(),False) - invoker.wait() - self.assertEqual(a.munya_invoked(),True) - return - - - def test_functor(self): - a = A() - val = 100 - aof = add_one_functor(val) - invoker = Async_tInvoker(a,aof) - invoker.invoke() - self.assertEqual(a.add_one_invoked(),False) - invoker.wait() - self.assertEqual(a.add_one_invoked(),True) - self.assertEqual(aof.get_ret(),val+1) - return - - - -############### test ################# -if __name__ == '__main__': - unittest.main() diff --git a/OpenRTM_aist/test/test_BufferBase.py b/OpenRTM_aist/test/test_BufferBase.py deleted file mode 100755 index 04b706de..00000000 --- a/OpenRTM_aist/test/test_BufferBase.py +++ /dev/null @@ -1,77 +0,0 @@ -#!/usr/bin/env python -# -*- Python -*- - -# \file test_BufferBase.py -# \brief Buffer abstract class -# \date $Date: 2007/09/12 $ -# \author Shinji Kurihara -# -# Copyright (C) 2006 -# Noriaki Ando -# Task-intelligence Research Group, -# Intelligent Systems Research Institute, -# National Institute of -# Advanced Industrial Science and Technology (AIST), Japan -# All rights reserved. -# - -import sys -sys.path.insert(1,"../") - -import unittest -import OpenRTM_aist - -from BufferBase import * - -class TestNullBuffer(unittest.TestCase): - def setUp(self): - self.nb = NullBuffer() - self.nb.init(100) - - def tearDown(self): - OpenRTM_aist.Manager.instance().shutdownManager() - return - - def test_length(self): - self.assertEqual(self.nb.length(),1) - - - def test_write(self): - data=[0] - # test long - self.assertEqual(self.nb.write(10000), True) - self.nb.read(data) - self.assertEqual(data[0], 10000) - - # test float - self.assertEqual(self.nb.write(1.2345), True) - self.nb.read(data) - self.assertEqual(data[0], 1.2345) - - # test string - self.assertEqual(self.nb.write("test"), True) - self.nb.read(data) - self.assertEqual(data[0], "test") - - # test list - self.assertEqual(self.nb.write([1,2,3]), True) - self.nb.read(data) - self.assertEqual(data[0], [1,2,3]) - - - def test_isEmpty(self): - self.assertEqual(self.nb.isEmpty(),False) - - - def test_isNew(self): - data=[0] - self.assertEqual(self.nb.isNew(),False) - self.nb.read(data) - self.assertEqual(self.nb.isNew(),False) - self.assertEqual(self.nb.write(10000), True) - self.assertEqual(self.nb.isNew(),True) - - -############### test ################# -if __name__ == '__main__': - unittest.main() diff --git a/OpenRTM_aist/test/test_BufferStatus.py b/OpenRTM_aist/test/test_BufferStatus.py deleted file mode 100755 index 82091e18..00000000 --- a/OpenRTM_aist/test/test_BufferStatus.py +++ /dev/null @@ -1,47 +0,0 @@ -#!/usr/bin/env python -# -*- Python -*- - -# \file test_BufferStatus.py -# \brief test of BufferStatus class -# \date $Date: 2007/09/12 $ -# \author Shinji Kurihara -# -# Copyright (C) 2009 -# Noriaki Ando -# Task-intelligence Research Group, -# Intelligent Systems Research Institute, -# National Institute of -# Advanced Industrial Science and Technology (AIST), Japan -# All rights reserved. -# - -import sys -sys.path.insert(1,"../") - -import unittest - -from BufferStatus import * - -class MyBuffer(BufferStatus): - def __init__(self): - pass - -class TestBufferStatus(unittest.TestCase): - def setUp(self): - self.bf = MyBuffer() - - - def test_toString(self): - self.assertEqual(self.bf.toString(BufferStatus.BUFFER_OK),"BUFFER_OK") - self.assertEqual(self.bf.toString(BufferStatus.BUFFER_ERROR),"BUFFER_ERROR") - self.assertEqual(self.bf.toString(BufferStatus.BUFFER_FULL),"BUFFER_FULL") - self.assertEqual(self.bf.toString(BufferStatus.BUFFER_EMPTY),"BUFFER_EMPTY") - self.assertEqual(self.bf.toString(BufferStatus.NOT_SUPPORTED),"NOT_SUPPORTED") - self.assertEqual(self.bf.toString(BufferStatus.TIMEOUT),"TIMEOUT") - self.assertEqual(self.bf.toString(BufferStatus.PRECONDITION_NOT_MET),"PRECONDITION_NOT_MET") - - - -############### test ################# -if __name__ == '__main__': - unittest.main() diff --git a/OpenRTM_aist/test/test_CORBA_RTCUtil.py b/OpenRTM_aist/test/test_CORBA_RTCUtil.py deleted file mode 100644 index 145dd923..00000000 --- a/OpenRTM_aist/test/test_CORBA_RTCUtil.py +++ /dev/null @@ -1,371 +0,0 @@ -#!/usr/bin/env python -# -*- coding: euc-jp -*- - -# -# \file test_CORBA_RTCUtil.py -# \brief -# \date $Date: $ -# \author Nobuhiko Miyamoto -# - - -import sys -sys.path.insert(1,"../") - -try: - import unittest2 as unittest -except (ImportError): - import unittest - -import time - -#from Manager import * -import OpenRTM_aist -import RTC, RTC__POA -import OpenRTM, OpenRTM__POA - -testcomp1_spec = ["implementation_id", "TestComp1", - "type_name", "TestComp1", - "description", "Test example component", - "version", "1.0", - "vendor", "Nobuhiko Myiyamoto", - "category", "example", - "activity_type", "DataFlowComponent", - "max_instance", "10", - "language", "C++", - "lang_type", "compile", - "conf.default.test1", "0", - ""] - -testcomp2_spec = ["implementation_id", "TestComp2", - "type_name", "TestComp2", - "description", "Test example component", - "version", "1.0", - "vendor", "Nobuhiko Myiyamoto", - "category", "example", - "activity_type", "DataFlowComponent", - "max_instance", "10", - "language", "C++", - "lang_type", "compile", - ""] - -class Test_i(OpenRTM__POA.InPortCdr): - def __init__(self): - pass - def put(self, data): - return OpenRTM.PORT_OK - - -class TestComp1(OpenRTM_aist.DataFlowComponentBase): - def __init__(self, manager): - OpenRTM_aist.DataFlowComponentBase.__init__(self, manager) - self._d_out = RTC.TimedLong(RTC.Time(0,0),0) - self._outOut = OpenRTM_aist.OutPort("out", self._d_out) - self._d_in = RTC.TimedLong(RTC.Time(0,0),0) - self._inIn = OpenRTM_aist.InPort("in", self._d_in) - - self._servicePort_provided = OpenRTM_aist.CorbaPort("service") - self._testService_provided = Test_i() - - - self._test1 = [0] - - def onInitialize(self): - self.addOutPort("out",self._outOut) - self.addInPort("in",self._inIn) - - self._servicePort_provided.registerProvider("service", "TestService", self._testService_provided) - self.addPort(self._servicePort_provided) - - - - - self.bindParameter("test1", self._test1, "0") - - - return RTC.RTC_OK - - - -class TestComp2(OpenRTM_aist.DataFlowComponentBase): - def __init__(self, manager): - OpenRTM_aist.DataFlowComponentBase.__init__(self, manager) - self._d_out = RTC.TimedLong(RTC.Time(0,0),0) - self._outOut = OpenRTM_aist.OutPort("out", self._d_out) - self._d_in = RTC.TimedLong(RTC.Time(0,0),0) - self._inIn = OpenRTM_aist.InPort("in", self._d_in) - - - - - self._servicePort_required = OpenRTM_aist.CorbaPort("service") - self._testService_required = OpenRTM_aist.CorbaConsumer(interfaceType=OpenRTM.InPortCdr) - - - - return - - def onInitialize(self): - self.addInPort("in",self._inIn) - self.addOutPort("out",self._outOut) - - - - self._servicePort_required.registerConsumer("service", "TestService", self._testService_required) - self.addPort(self._servicePort_required) - - - return RTC.RTC_OK - - - - -def TestComp1Init(manager): - profile = OpenRTM_aist.Properties(defaults_str=testcomp1_spec) - manager.registerFactory(profile, - TestComp1, - OpenRTM_aist.Delete) - - - -def TestComp2Init(manager): - profile = OpenRTM_aist.Properties(defaults_str=testcomp2_spec) - manager.registerFactory(profile, - TestComp2, - OpenRTM_aist.Delete) - - -def MyModuleInit(manager): - TestComp1Init(manager) - TestComp2Init(manager) - com = manager.createComponent("TestComp1") - com = manager.createComponent("TestComp2") - - - - - -class Test_CORBA_RTCUtil(unittest.TestCase): - - def setUp(self): - sys.argv.extend(['-d']) - sys.argv.extend(['-o', 'exec_cxt.periodic.rate:1000']) - sys.argv.extend(['-o','naming.type:corba,manager']) - self.manager = OpenRTM_aist.Manager.init(sys.argv) - self.manager.setModuleInitProc(MyModuleInit) - self.manager.activateManager() - - - - self.comp1 = self.manager.getComponent("TestComp10").getObjRef() - self.comp2 = self.manager.getComponent("TestComp20").getObjRef() - - - def tearDown(self): - comps = self.manager.getComponents()[:] - for comp in comps: - self.manager.unregisterComponent(comp) - comp_id = comp.getProperties() - factory = self.manager._factory.find(comp_id) - factory.destroy(comp) - self.manager.shutdownNaming() - time.sleep(0.1) - - def test_Component(self): - compProf = OpenRTM_aist.get_component_profile(self.comp1) - self.assertEqual(compProf.getProperty("implementation_id"), "TestComp1") - ret = OpenRTM_aist.is_existing(self.comp1) - self.assertTrue(ret) - - def test_EC(self): - ec = OpenRTM_aist.get_actual_ec(self.comp1,0) - ec_id = OpenRTM_aist.get_ec_id(self.comp1, ec) - self.assertEqual(ec_id, 0) - - ret = OpenRTM_aist.add_rtc_to_default_ec(self.comp1, self.comp2) - self.assertEqual(ret, RTC.RTC_OK) - - - ret = OpenRTM_aist.is_alive_in_default_ec(self.comp1) - self.assertEqual(ret, True) - - ret = OpenRTM_aist.set_default_rate(self.comp1, 500) - self.assertEqual(ret, RTC.RTC_OK) - - rate = OpenRTM_aist.get_default_rate(self.comp1) - self.assertEqual(int(rate), 500) - - ret = OpenRTM_aist.set_current_rate(self.comp2,1000, 100) - self.assertEqual(ret, RTC.RTC_OK) - - rate = OpenRTM_aist.get_current_rate(self.comp2, 1000) - self.assertEqual(int(rate), 100) - - ret = OpenRTM_aist.activate(self.comp1,0) - self.assertEqual(ret, RTC.RTC_OK) - state = OpenRTM_aist.is_in_active(self.comp1, 0) - self.assertTrue(state) - - ret = OpenRTM_aist.deactivate(self.comp1,0) - self.assertEqual(ret, RTC.RTC_OK) - state = OpenRTM_aist.is_in_inactive(self.comp1, 0) - self.assertTrue(state) - - #state = OpenRTM_aist.is_in_error(self.comp1, 0) - #ret = OpenRTM_aist.reset(self.comp1,0) - #self.assertEqual(ret, RTC.RTC_OK) - - ret = [None] - ans = OpenRTM_aist.get_state(ret, self.comp1, 0) - self.assertEqual(ret[0], RTC.INACTIVE_STATE) - - ret = OpenRTM_aist.remove_rtc_to_default_ec(self.comp1, self.comp2) - self.assertEqual(ret, RTC.RTC_OK) - - - def test_Port(self): - port_names = OpenRTM_aist.get_port_names(self.comp1) - self.assertTrue("TestComp10.out" in port_names) - - inport_names = OpenRTM_aist.get_inport_names(self.comp2) - self.assertTrue("TestComp20.in" in inport_names) - - outport_names = OpenRTM_aist.get_outport_names(self.comp1) - self.assertTrue("TestComp10.out" in outport_names) - - svcport_names = OpenRTM_aist.get_svcport_names(self.comp1) - self.assertTrue("TestComp10.service" in svcport_names) - - rtc1_port_out = OpenRTM_aist.get_port_by_name(self.comp1,"TestComp10.out") - rtc2_port_out = OpenRTM_aist.get_port_by_name(self.comp2,"TestComp20.out") - rtc2_port_in = OpenRTM_aist.get_port_by_name(self.comp2,"TestComp20.in") - rtc1_port_in = OpenRTM_aist.get_port_by_name(self.comp1,"TestComp10.in") - - pp = rtc1_port_out.get_port_profile() - self.assertEqual(pp.name, "TestComp10.out") - - - prop = OpenRTM_aist.Properties() - connect_profile = OpenRTM_aist.create_connector("con1",prop,rtc1_port_out,rtc2_port_in) - ret = OpenRTM_aist.connect("con1",prop,rtc1_port_out,rtc2_port_in) - self.assertEqual(ret, RTC.RTC_OK) - - con_names = OpenRTM_aist.get_connector_names_by_portref(rtc1_port_out) - self.assertTrue("con1" in con_names) - con_names = OpenRTM_aist.get_connector_names(self.comp1,"TestComp10.out") - self.assertTrue("con1" in con_names) - con_ids = OpenRTM_aist.get_connector_ids_by_portref(rtc1_port_out) - con_ids = OpenRTM_aist.get_connector_ids(self.comp1,"TestComp10.out") - - - ret = OpenRTM_aist.already_connected(rtc1_port_out,rtc2_port_in) - self.assertTrue(ret) - - ret = OpenRTM_aist.disconnect(rtc1_port_out.get_connector_profiles()[0]) - self.assertEqual(ret, RTC.RTC_OK) - ret = OpenRTM_aist.already_connected(rtc1_port_out,rtc2_port_in) - self.assertFalse(ret) - - - - ret = OpenRTM_aist.connect_multi("con2",prop,rtc1_port_out,[rtc1_port_in,rtc2_port_in]) - self.assertEqual(ret, RTC.RTC_OK) - - ret = OpenRTM_aist.already_connected(rtc1_port_out,rtc1_port_in) - self.assertTrue(ret) - ret = OpenRTM_aist.already_connected(rtc1_port_out,rtc2_port_in) - self.assertTrue(ret) - - ret = OpenRTM_aist.disconnect_all_by_ref(rtc1_port_out) - self.assertEqual(ret, RTC.RTC_OK) - ret = OpenRTM_aist.already_connected(rtc1_port_out,rtc2_port_in) - self.assertFalse(ret) - - - - ret = OpenRTM_aist.connect_by_name("con3",prop,self.comp1,"TestComp10.out",self.comp2,"TestComp20.in") - self.assertEqual(ret, RTC.RTC_OK) - ret = OpenRTM_aist.already_connected(rtc1_port_out,rtc2_port_in) - self.assertTrue(ret) - - ret = OpenRTM_aist.disconnect_by_portref_connector_name(rtc1_port_out, "con3") - self.assertEqual(ret, RTC.RTC_OK) - ret = OpenRTM_aist.already_connected(rtc1_port_out,rtc2_port_in) - self.assertFalse(ret) - - ret = OpenRTM_aist.connect("con1",prop,rtc1_port_out,rtc2_port_in) - ret = OpenRTM_aist.disconnect_by_portref_connector_id(rtc1_port_out,rtc1_port_out.get_connector_profiles()[0].connector_id) - self.assertEqual(ret, RTC.RTC_OK) - ret = OpenRTM_aist.already_connected(rtc1_port_out,rtc2_port_in) - self.assertFalse(ret) - - ret = OpenRTM_aist.connect("con1",prop,rtc1_port_out,rtc2_port_in) - ret = OpenRTM_aist.disconnect_by_port_name(rtc1_port_out,"TestComp20.in") - self.assertEqual(ret, RTC.RTC_OK) - ret = OpenRTM_aist.already_connected(rtc1_port_out,rtc2_port_in) - self.assertFalse(ret) - - - ret = OpenRTM_aist.connect("con1",prop,rtc1_port_out,rtc2_port_in) - ret = OpenRTM_aist.disconnect_all_by_name("rtcloc://localhost:2810/example/TestComp20.in") - self.assertEqual(ret, RTC.RTC_OK) - ret = OpenRTM_aist.already_connected(rtc1_port_out,rtc2_port_in) - self.assertFalse(ret) - - ret = OpenRTM_aist.connect("con1",prop,rtc1_port_out,rtc2_port_in) - ret = OpenRTM_aist.disconnect_by_portname_connector_name("rtcloc://localhost:2810/example/TestComp20.in","con1") - self.assertEqual(ret, RTC.RTC_OK) - ret = OpenRTM_aist.already_connected(rtc1_port_out,rtc2_port_in) - self.assertFalse(ret) - - ret = OpenRTM_aist.connect("con1",prop,rtc1_port_out,rtc2_port_in) - ret = OpenRTM_aist.disconnect_by_portname_connector_id("rtcloc://localhost:2810/example/TestComp10.out",rtc1_port_out.get_connector_profiles()[0].connector_id) - self.assertEqual(ret, RTC.RTC_OK) - ret = OpenRTM_aist.already_connected(rtc1_port_out,rtc2_port_in) - self.assertFalse(ret) - - - - - def test_configuration(self): - conf = OpenRTM_aist.get_configuration(self.comp1, "default") - self.assertEqual(conf.getProperty("test1"),"0") - - ret = OpenRTM_aist.get_parameter_by_key(self.comp1,"default","test1") - self.assertEqual(ret,"0") - - conf = OpenRTM_aist.get_active_configuration(self.comp1) - self.assertEqual(conf.getProperty("test1"),"0") - - ret = OpenRTM_aist.set_configuration(self.comp1,"default","test1","1") - self.assertTrue(ret) - ret = OpenRTM_aist.get_parameter_by_key(self.comp1,"default","test1") - self.assertEqual(ret,"1") - - ret = OpenRTM_aist.set_active_configuration(self.comp1,"test1","2") - self.assertTrue(ret) - ret = OpenRTM_aist.get_parameter_by_key(self.comp1,"default","test1") - self.assertEqual(ret,"2") - - confsetname = OpenRTM_aist.get_active_configuration_name(self.comp1) - self.assertEqual(confsetname,"default") - - - #ec = self.comp1.get_owned_contexts()[0] - - #print OpenRTM_aist.get_participants_rtc(ec) - - #print ec.add_component(self.comp2) - #print ec.get_profile() - #prop = OpenRTM_aist.Properties() - #conf = self.comp1.get_configuration() - #print conf.get_configuration_sets() - #confsets = conf.get_configuration_sets() - #print confsets - #OpenRTM_aist.NVUtil.copyToProperties(prop,confsets) - #print prop - # self.comp1.get_status_list() - -############### test ################# -if __name__ == '__main__': - unittest.main() diff --git a/OpenRTM_aist/test/test_CORBA_SeqUtil.py b/OpenRTM_aist/test/test_CORBA_SeqUtil.py deleted file mode 100755 index c961011e..00000000 --- a/OpenRTM_aist/test/test_CORBA_SeqUtil.py +++ /dev/null @@ -1,133 +0,0 @@ -#!/usr/bin/env python -# -*- Python -*- - -# -# \file CORBA_SeqUtil.py -# \brief test for CORBA sequence utility template functions -# \date $Date: 2007/09/03$ -# \author Shinji Kurihara -# -# Copyright (C) 2006 -# Task-intelligence Research Group, -# Intelligent Systems Research Institute, -# National Institute of -# Advanced Industrial Science and Technology (AIST), Japan -# All rights reserved. -# - -import sys -sys.path.insert(1,"../") - -import unittest -import OpenRTM_aist - -import CORBA_SeqUtil - -class FunctorAdd: - def __init__(self, lists): - self._list = lists - - def __call__(self, obj): - self._list.append(obj) - -class Property: - def __init__(self,id_): - self.id =id_ - -class FunctorFind: - def __init__(self, id): - self._id = id - - def __call__(self, prof): - return self._id == prof.id - - - -class TestCORBA_SeqUtil(unittest.TestCase): - def setUp(self): - pass - - def tearDown(self): - OpenRTM_aist.Manager.instance().shutdownManager() - return - - def test_for_each(self): - list_ = [0,1,2] - func_ = FunctorAdd(list_) - add_ = [3,4,5,6,7] - CORBA_SeqUtil.for_each(add_,func_) - self.assertEqual(list_, [0,1,2,3,4,5,6,7]) - - - def test_find(self): - prof = [Property(100),Property(200),Property(300)] - index = CORBA_SeqUtil.find(prof,FunctorFind(300)) - self.assertEqual(index, 2) - - index = CORBA_SeqUtil.find(prof,FunctorFind(3000)) - self.assertEqual(index, -1) - - - def test_push_back(self): - list_ = [0,1,2,3] - CORBA_SeqUtil.push_back(list_,100) - self.assertEqual(list_, [0,1,2,3,100]) - - - def test_push_back_list(self): - list1 = [0,1,2] - list2 = [3,4,5,6,7] - CORBA_SeqUtil.push_back_list(list1,list2) - self.assertEqual(list1, [0,1,2,3,4,5,6,7]) - - - def test_insert(self): - list_ = [0,1,2] - CORBA_SeqUtil.insert(list_, "INS", 1) - self.assertEqual(list_, [0,"INS",1,2]) - - CORBA_SeqUtil.insert(list_, 10, 100) - self.assertEqual(list_, [0,"INS",1,2,10]) - - - def test_front(self): - list_ = [3,4,5,6] - self.assertEqual(CORBA_SeqUtil.front(list_),3) - - - def test_back(self): - list_ = [3,4,5,6] - self.assertEqual(CORBA_SeqUtil.back(list_),6) - - - def test_erase(self): - list_ = [9,8,7,6] - CORBA_SeqUtil.erase(list_, 10) - self.assertEqual(list_, [9,8,7,6]) - - CORBA_SeqUtil.erase(list_, 1) - self.assertEqual(list_, [9,7,6]) - - - def test_erase_if(self): - prof = [Property(100),Property(200),Property(300)] - CORBA_SeqUtil.erase_if(prof,FunctorFind(999)) - self.assertEqual(len(prof), 3) - - CORBA_SeqUtil.erase_if(prof,FunctorFind(200)) - self.assertEqual(len(prof), 2) - - - def test_clear(self): - list_ = [0,1,2,3,4,5] - CORBA_SeqUtil.clear(list_) - self.assertEqual(list_,[]) - - - def test_refToVstring(self): - pass - - -############### test ################# -if __name__ == '__main__': - unittest.main() diff --git a/OpenRTM_aist/test/test_CdrRingBuffer.py b/OpenRTM_aist/test/test_CdrRingBuffer.py deleted file mode 100755 index effc0648..00000000 --- a/OpenRTM_aist/test/test_CdrRingBuffer.py +++ /dev/null @@ -1,45 +0,0 @@ -#!/usr/bin/env python -# -*- Python -*- - -# \file test_CdrRingBuffer.py -# \brief test of CdrRingBuffer class -# \date $Date: 2007/09/12 $ -# \author Shinji Kurihara -# -# Copyright (C) 2006 -# Noriaki Ando -# Task-intelligence Research Group, -# Intelligent Systems Research Institute, -# National Institute of -# Advanced Industrial Science and Technology (AIST), Japan -# All rights reserved. -# - -import sys -sys.path.insert(1,"../") - -import unittest - -from CdrBufferBase import * -from CdrRingBuffer import * - -class TestCdrRingBuffer(unittest.TestCase): - def setUp(self): - CdrRingBufferInit() - self._buff = CdrBufferFactory.instance().createObject("ring_buffer") - - - def test_write(self): - self.assertEqual(self._buff.write(100),0) - - - def test_read(self): - data = [0] - self.assertEqual(self._buff.write(100),0) - self.assertEqual(self._buff.read(data), 0) - self.assertEqual(data[0], 100) - - -############### test ################# -if __name__ == '__main__': - unittest.main() diff --git a/OpenRTM_aist/test/test_ClockManager.py b/OpenRTM_aist/test/test_ClockManager.py deleted file mode 100644 index ed365cbf..00000000 --- a/OpenRTM_aist/test/test_ClockManager.py +++ /dev/null @@ -1,64 +0,0 @@ -#!/usr/bin/env python -# -*- coding: euc-jp -*- - -## -# @file test_ClockManager.py -# @brief test for ClockManager class -# @date $Date$ -# @author Noriaki Ando -# -# Copyright (C) 2012 -# Noriaki Ando -# Intelligent Systems Research Institute, -# National Institute of -# Advanced Industrial Science and Technology (AIST), Japan -# All rights reserved. -# -# $Id$ -# - -import time -import sys -import math -sys.path.insert(1,"../") - -import unittest -from ClockManager import * - - - -class TestClockManager(unittest.TestCase): - def setUp(self): - self._cm = ClockManager.instance() - return - - def test_LogicalClock(self): - tm = self._cm.getClock("logical").gettime() - self.assertEqual(0.0,tm.tv_sec) - self.assertEqual(0.0,tm.tv_usec) - stm = OpenRTM_aist.TimeValue(1,1) - tm = self._cm.getClock("logical").settime(stm) - tm = self._cm.getClock("logical").gettime() - self.assertEqual(1,tm.tv_sec) - self.assertEqual(1,tm.tv_usec) - tm = ClockManager.instance().getClock("logical").gettime() - self.assertEqual(1,tm.tv_sec) - self.assertEqual(1,tm.tv_usec) - return - - def test_AdjustedClock(self): - tm = self._cm.getClock("adjusted").gettime() - stm = OpenRTM_aist.TimeValue(1,1) - tm = self._cm.getClock("adjusted").settime(stm) - tm = self._cm.getClock("adjusted").gettime() - return - - def test_SystemClock(self): - tm = self._cm.getClock("system").gettime() - stm = OpenRTM_aist.TimeValue(1,1) - tm = self._cm.getClock("system").settime(stm) - return - -############### test ################# -if __name__ == '__main__': - unittest.main() diff --git a/OpenRTM_aist/test/test_ComponentActionListener.py b/OpenRTM_aist/test/test_ComponentActionListener.py deleted file mode 100644 index b5eee36f..00000000 --- a/OpenRTM_aist/test/test_ComponentActionListener.py +++ /dev/null @@ -1,248 +0,0 @@ -#!/usr/bin/env python -# -*- coding: euc-jp -*- - -# -# \file test_ComponentActionListener.py -# \brief -# \date $Date: $ -# \author Nobuhiko Miyamoto -# - - -import sys -sys.path.insert(1,"../") - -try: - import unittest2 as unittest -except (ImportError): - import unittest - -import time - -#from Manager import * -import OpenRTM_aist -import RTC, RTC__POA -import OpenRTM, OpenRTM__POA - -testcomp1_spec = ["implementation_id", "TestComp1", - "type_name", "TestComp1", - "description", "Test example component", - "version", "1.0", - "vendor", "Nobuhiko Myiyamoto", - "category", "example", - "activity_type", "DataFlowComponent", - "max_instance", "10", - "language", "C++", - "lang_type", "compile", - "conf.default.test1", "0", - ""] - -testcomp2_spec = ["implementation_id", "TestComp2", - "type_name", "TestComp2", - "description", "Test example component", - "version", "1.0", - "vendor", "Nobuhiko Myiyamoto", - "category", "example", - "activity_type", "DataFlowComponent", - "max_instance", "10", - "language", "C++", - "lang_type", "compile", - ""] - -class Test_i(OpenRTM__POA.InPortCdr): - def __init__(self): - pass - def put(self, data): - return OpenRTM.PORT_OK - - - -class TestPostListener(OpenRTM_aist.PostComponentActionListener): - def __init__(self, mes): - self.mes = mes - def __del__(self): - pass - def __call__(self, ec_id, ret): - print self.mes - - -class TestPreListener(OpenRTM_aist.PreComponentActionListener): - def __init__(self, mes): - self.mes = mes - def __del__(self): - pass - def __call__(self, ec_id): - print self.mes - - -class TestComp1(OpenRTM_aist.DataFlowComponentBase): - def __init__(self, manager): - OpenRTM_aist.DataFlowComponentBase.__init__(self, manager) - self._d_out = RTC.TimedLong(RTC.Time(0,0),0) - self._outOut = OpenRTM_aist.OutPort("out", self._d_out) - self._d_in = RTC.TimedLong(RTC.Time(0,0),0) - self._inIn = OpenRTM_aist.InPort("in", self._d_in) - - self._servicePort_provided = OpenRTM_aist.CorbaPort("service") - self._testService_provided = Test_i() - - self._test1 = [0] - - def onInitialize(self): - self.addOutPort("out",self._outOut) - self.addInPort("in",self._inIn) - - self._servicePort_provided.registerProvider("service", "TestService", self._testService_provided) - self.addPort(self._servicePort_provided) - - #self._servicePort_provided.activateInterfaces() - - self.bindParameter("test1", self._test1, "0") - - - self.addPreComponentActionListener(OpenRTM_aist.PreComponentActionListenerType.PRE_ON_INITIALIZE, TestPreListener("RTC2:PRE_ON_INITIALIZE")) - self.addPreComponentActionListener(OpenRTM_aist.PreComponentActionListenerType.PRE_ON_FINALIZE, TestPreListener("RTC1:PRE_ON_FINALIZE")) - self.addPreComponentActionListener(OpenRTM_aist.PreComponentActionListenerType.PRE_ON_STARTUP, TestPreListener("RTC1:PRE_ON_STARTUP")) - self.addPreComponentActionListener(OpenRTM_aist.PreComponentActionListenerType.PRE_ON_SHUTDOWN, TestPreListener("RTC1:PRE_ON_SHUTDOWN")) - self.addPreComponentActionListener(OpenRTM_aist.PreComponentActionListenerType.PRE_ON_ACTIVATED, TestPreListener("RTC1:PRE_ON_ACTIVATED")) - self.addPreComponentActionListener(OpenRTM_aist.PreComponentActionListenerType.PRE_ON_DEACTIVATED, TestPreListener("RTC1:PRE_ON_DEACTIVATED")) - self.addPreComponentActionListener(OpenRTM_aist.PreComponentActionListenerType.PRE_ON_ABORTING, TestPreListener("RTC1:PRE_ON_ABORTING")) - self.addPreComponentActionListener(OpenRTM_aist.PreComponentActionListenerType.PRE_ON_ERROR, TestPreListener("RTC1:PRE_ON_ERROR")) - self.addPreComponentActionListener(OpenRTM_aist.PreComponentActionListenerType.PRE_ON_RESET, TestPreListener("RTC1:PRE_ON_RESET")) - self.addPreComponentActionListener(OpenRTM_aist.PreComponentActionListenerType.PRE_ON_EXECUTE, TestPreListener("RTC1:PRE_ON_EXECUTE")) - self.addPreComponentActionListener(OpenRTM_aist.PreComponentActionListenerType.PRE_ON_STATE_UPDATE, TestPreListener("RTC1:PRE_ON_STATE_UPDATE")) - self.addPreComponentActionListener(OpenRTM_aist.PreComponentActionListenerType.PRE_ON_RATE_CHANGED, TestPreListener("RTC1:PRE_ON_RATE_CHANGED")) - - self.addPostComponentActionListener(OpenRTM_aist.PostComponentActionListenerType.POST_ON_INITIALIZE, TestPostListener("RTC1:POST_ON_INITIALIZE")) - self.addPostComponentActionListener(OpenRTM_aist.PostComponentActionListenerType.POST_ON_FINALIZE, TestPostListener("RTC1:POST_ON_FINALIZE")) - self.addPostComponentActionListener(OpenRTM_aist.PostComponentActionListenerType.POST_ON_STARTUP, TestPostListener("RTC1:POST_ON_STARTUP")) - self.addPostComponentActionListener(OpenRTM_aist.PostComponentActionListenerType.POST_ON_SHUTDOWN, TestPostListener("RTC1:POST_ON_SHUTDOWN")) - self.addPostComponentActionListener(OpenRTM_aist.PostComponentActionListenerType.POST_ON_ACTIVATED, TestPostListener("RTC1:POST_ON_ACTIVATED")) - self.addPostComponentActionListener(OpenRTM_aist.PostComponentActionListenerType.POST_ON_DEACTIVATED, TestPostListener("RTC1:POST_ON_DEACTIVATED")) - self.addPostComponentActionListener(OpenRTM_aist.PostComponentActionListenerType.POST_ON_ABORTING, TestPostListener("RTC1:POST_ON_ABORTING")) - self.addPostComponentActionListener(OpenRTM_aist.PostComponentActionListenerType.POST_ON_ERROR, TestPostListener("RTC1:POST_ON_ERROR")) - self.addPostComponentActionListener(OpenRTM_aist.PostComponentActionListenerType.POST_ON_RESET, TestPostListener("RTC1:POST_ON_RESET")) - self.addPostComponentActionListener(OpenRTM_aist.PostComponentActionListenerType.POST_ON_EXECUTE, TestPostListener("RTC1:POST_ON_EXECUTE")) - self.addPostComponentActionListener(OpenRTM_aist.PostComponentActionListenerType.POST_ON_STATE_UPDATE, TestPostListener("RTC1:POST_ON_STATE_UPDATE")) - self.addPostComponentActionListener(OpenRTM_aist.PostComponentActionListenerType.POST_ON_RATE_CHANGED, TestPostListener("RTC1:POST_ON_RATE_CHANGED")) - - - - - return RTC.RTC_OK - - - -class TestComp2(OpenRTM_aist.DataFlowComponentBase): - def __init__(self, manager): - OpenRTM_aist.DataFlowComponentBase.__init__(self, manager) - self._d_out = RTC.TimedLong(RTC.Time(0,0),0) - self._outOut = OpenRTM_aist.OutPort("out", self._d_out) - self._d_in = RTC.TimedLong(RTC.Time(0,0),0) - self._inIn = OpenRTM_aist.InPort("in", self._d_in) - - - - - self._servicePort_required = OpenRTM_aist.CorbaPort("service") - self._testService_required = OpenRTM_aist.CorbaConsumer(interfaceType=OpenRTM.InPortCdr) - - - - return - - def onInitialize(self): - self.addInPort("in",self._inIn) - self.addOutPort("out",self._outOut) - - - - self._servicePort_required.registerConsumer("service", "TestService", self._testService_required) - self.addPort(self._servicePort_required) - - - self.addPreComponentActionListener(OpenRTM_aist.PreComponentActionListenerType.PRE_ON_INITIALIZE, TestPreListener("RTC2:PRE_ON_INITIALIZE")) - self.addPreComponentActionListener(OpenRTM_aist.PreComponentActionListenerType.PRE_ON_FINALIZE, TestPreListener("RTC2:PRE_ON_FINALIZE")) - self.addPreComponentActionListener(OpenRTM_aist.PreComponentActionListenerType.PRE_ON_STARTUP, TestPreListener("RTC2:PRE_ON_STARTUP")) - self.addPreComponentActionListener(OpenRTM_aist.PreComponentActionListenerType.PRE_ON_SHUTDOWN, TestPreListener("RTC2:PRE_ON_SHUTDOWN")) - self.addPreComponentActionListener(OpenRTM_aist.PreComponentActionListenerType.PRE_ON_ACTIVATED, TestPreListener("RTC2:PRE_ON_ACTIVATED")) - self.addPreComponentActionListener(OpenRTM_aist.PreComponentActionListenerType.PRE_ON_DEACTIVATED, TestPreListener("RTC2:PRE_ON_DEACTIVATED")) - self.addPreComponentActionListener(OpenRTM_aist.PreComponentActionListenerType.PRE_ON_ABORTING, TestPreListener("RTC2:PRE_ON_ABORTING")) - self.addPreComponentActionListener(OpenRTM_aist.PreComponentActionListenerType.PRE_ON_ERROR, TestPreListener("RTC2:PRE_ON_ERROR")) - self.addPreComponentActionListener(OpenRTM_aist.PreComponentActionListenerType.PRE_ON_RESET, TestPreListener("RTC2:PRE_ON_RESET")) - self.addPreComponentActionListener(OpenRTM_aist.PreComponentActionListenerType.PRE_ON_EXECUTE, TestPreListener("RTC2:PRE_ON_EXECUTE")) - self.addPreComponentActionListener(OpenRTM_aist.PreComponentActionListenerType.PRE_ON_STATE_UPDATE, TestPreListener("RTC2:PRE_ON_STATE_UPDATE")) - self.addPreComponentActionListener(OpenRTM_aist.PreComponentActionListenerType.PRE_ON_RATE_CHANGED, TestPreListener("RTC2:PRE_ON_RATE_CHANGED")) - - self.addPostComponentActionListener(OpenRTM_aist.PostComponentActionListenerType.POST_ON_INITIALIZE, TestPostListener("RTC2:POST_ON_INITIALIZE")) - self.addPostComponentActionListener(OpenRTM_aist.PostComponentActionListenerType.POST_ON_FINALIZE, TestPostListener("RTC2:POST_ON_FINALIZE")) - self.addPostComponentActionListener(OpenRTM_aist.PostComponentActionListenerType.POST_ON_STARTUP, TestPostListener("RTC2:POST_ON_STARTUP")) - self.addPostComponentActionListener(OpenRTM_aist.PostComponentActionListenerType.POST_ON_SHUTDOWN, TestPostListener("RTC2:POST_ON_SHUTDOWN")) - self.addPostComponentActionListener(OpenRTM_aist.PostComponentActionListenerType.POST_ON_ACTIVATED, TestPostListener("RTC2:POST_ON_ACTIVATED")) - self.addPostComponentActionListener(OpenRTM_aist.PostComponentActionListenerType.POST_ON_DEACTIVATED, TestPostListener("RTC2:POST_ON_DEACTIVATED")) - self.addPostComponentActionListener(OpenRTM_aist.PostComponentActionListenerType.POST_ON_ABORTING, TestPostListener("RTC2:POST_ON_ABORTING")) - self.addPostComponentActionListener(OpenRTM_aist.PostComponentActionListenerType.POST_ON_ERROR, TestPostListener("RTC2:POST_ON_ERROR")) - self.addPostComponentActionListener(OpenRTM_aist.PostComponentActionListenerType.POST_ON_RESET, TestPostListener("RTC2:POST_ON_RESET")) - self.addPostComponentActionListener(OpenRTM_aist.PostComponentActionListenerType.POST_ON_EXECUTE, TestPostListener("RTC2:POST_ON_EXECUTE")) - self.addPostComponentActionListener(OpenRTM_aist.PostComponentActionListenerType.POST_ON_STATE_UPDATE, TestPostListener("RTC2:POST_ON_STATE_UPDATE")) - self.addPostComponentActionListener(OpenRTM_aist.PostComponentActionListenerType.POST_ON_RATE_CHANGED, TestPostListener("RTC2:POST_ON_RATE_CHANGED")) - - - return RTC.RTC_OK - - - - - -def TestComp1Init(manager): - profile = OpenRTM_aist.Properties(defaults_str=testcomp1_spec) - manager.registerFactory(profile, - TestComp1, - OpenRTM_aist.Delete) - - - -def TestComp2Init(manager): - profile = OpenRTM_aist.Properties(defaults_str=testcomp2_spec) - manager.registerFactory(profile, - TestComp2, - OpenRTM_aist.Delete) - - -def MyModuleInit(manager): - TestComp1Init(manager) - TestComp2Init(manager) - com = manager.createComponent("TestComp1") - com = manager.createComponent("TestComp2") - - - - - -class test_ComponentActionListener(unittest.TestCase): - - def setUp(self): - self.manager = OpenRTM_aist.Manager.init(sys.argv) - self.manager.setModuleInitProc(MyModuleInit) - self.manager.activateManager() - - self.comp1 = self.manager.getComponent("TestComp10").getObjRef() - self.comp2 = self.manager.getComponent("TestComp20").getObjRef() - - def tearDown(self): - comps = self.manager.getComponents()[:] - for comp in comps: - self.manager.unregisterComponent(comp) - comp_id = comp.getProperties() - factory = self.manager._factory.find(comp_id) - factory.destroy(comp) - self.manager.shutdownNaming() - time.sleep(0.1) - - def test_Component(self): - while(True): - time.sleep(10) - -############### test ################# -if __name__ == '__main__': - unittest.main() diff --git a/OpenRTM_aist/test/test_ConfigAdmin.py b/OpenRTM_aist/test/test_ConfigAdmin.py deleted file mode 100755 index a74542fd..00000000 --- a/OpenRTM_aist/test/test_ConfigAdmin.py +++ /dev/null @@ -1,327 +0,0 @@ -#!/usr/bin/env python -# -*- coding: euc-jp -*- - -# -# \file test_ConfigAdmin.py -# \brief test for Configuration Administration classes -# \date $Date: 2007/09/04$ -# \author Shinji Kurihara -# -# Copyright (C) 2007 -# Task-intelligence Research Group, -# Intelligent Systems Research Institute, -# National Institute of -# Advanced Industrial Science and Technology (AIST), Japan -# All rights reserved. - -import sys -sys.path.insert(1,"../") - -import unittest - -import OpenRTM_aist -from ConfigAdmin import * - -configsample_spec = ["implementation_id", "ConfigSample", - "type_name", "ConfigSample", - "description", "Configuration example component", - "version", "1.0", - "vendor", "Shinji Kurihara, AIST", - "category", "example", - "activity_type", "DataFlowComponent", - "max_instance", "10", - "language", "C++", - "lang_type", "compile", - # Configuration variables - "conf.default.int_param0", "0", - "conf.default.int_param1", "1", - "conf.default.double_param0", "0.11", - "conf.default.double_param1", "9.9", - "conf.default.str_param0", "hoge", - "conf.default.str_param1", "dara", - "conf.default.vector_param0", "0.0,1.0,2.0,3.0,4.0", - ""] - -configsample_mode_spec = ["conf.default.int_param0", "10", - "conf.default.int_param1", "11", - "conf.default.double_param0", "0.22", - "conf.default.double_param1", "9999.9", - "conf.default.str_param0", "hogehoge", - "conf.default.str_param1", "daradaradata", - "conf.default.vector_param0", "0.1,1.1,2.1,3.1,4.1", - ""] - -configsample_add_spec = ["conf.mode0.int_param0", "10", - "conf.mode0.int_param1", "11", - "conf.mode0.double_param0", "0.22", - "conf.mode0.double_param1", "9999.9", - "conf.mode0.str_param0", "hogehoge", - "conf.mode0.str_param1", "daradaradata", - "conf.mode0.vector_param0", "0.1,1.1,2.1,3.1,4.1", - ""] - -class TestConfigAdmin(unittest.TestCase): - def setUp(self): - prop = OpenRTM_aist.Properties(defaults_str=configsample_spec) - self._ca = ConfigAdmin(prop.getNode("conf")) - - def tearDown(self): - OpenRTM_aist.Manager.instance().shutdownManager() - return - - def CallBack(self,*args): - #print args - return - - def test_bindParameter(self): - self.int_param0 = [0] - self.int_param1 = [0] - self.double_param0 = [0.0] - self.double_param1 = [0.0] - self.str_param0 = [""] - self.str_param1 = [""] - self.vector_param0 = [[0.0,0.0,0.0,0.0,0.0]] - - self._ca.bindParameter("int_param0", self.int_param0, "0") - self._ca.bindParameter("int_param1", self.int_param1, "1") - self._ca.bindParameter("double_param0", self.double_param0, "0.11") - self._ca.bindParameter("double_param1", self.double_param1, "9.9") - self._ca.bindParameter("str_param0", self.str_param0, "hoge") - self._ca.bindParameter("str_param1", self.str_param1, "dara") - self._ca.bindParameter("vector_param0", self.vector_param0, "0.0,1.0,2.0,3.0,4.0") - print "Changed Parameters: ", self._ca.changedParameters() - self.assertEqual(True,self._ca.unbindParameter("int_param0")) - self.assertEqual(True,self._ca.unbindParameter("int_param1")) - self.assertEqual(True,self._ca.unbindParameter("double_param0")) - self.assertEqual(True,self._ca.unbindParameter("double_param1")) - self.assertEqual(True,self._ca.unbindParameter("str_param0")) - self.assertEqual(True,self._ca.unbindParameter("str_param1")) - self.assertEqual(True,self._ca.unbindParameter("vector_param0")) - return - - def test_update(self): - self._ca.update(config_set="default") - self._ca.update("default","int_param0") - self._ca.update() - return - - def test_isExist(self): - varName = "name" - prop = OpenRTM_aist.Properties() - ca = ConfigAdmin(prop) - - varName = "name" - var = [0.0] - default_value = "3.14159" - - self.assertEqual(True, ca.bindParameter(varName,var,default_value)) - self.assertEqual(3.14159,var[0]) - - # Хɤѿ̾ΤisExist()ƽФͤ뤫 - self.assertEqual(True, ca.isExist("name")) - - # ХɤƤʤ̾ΤisExist()ƽФͤ뤫 - self.assertEqual(False, ca.isExist("inexist name")) - - return - - def test_isChanged(self): - self.assertEqual(self._ca.isChanged(),False) - return - - - def test_getActiveId(self): - self.assertEqual(self._ca.getActiveId(),"default") - return - - - def test_haveConfig(self): - self.assertEqual(self._ca.haveConfig("default"),True) - # Failure pattern - # self.assertEqual(self._ca.haveConfig("int_param0"),True) - return - - - def test_isActive(self): - self.assertEqual(self._ca.isActive(),True) - return - - - def test_getConfigurationSets(self): - self.assertEqual(self._ca.getConfigurationSets()[0].name,"default") - return - - - def test_getConfigurationSet(self): - self.assertEqual(self._ca.getConfigurationSet("default").name, "default") - return - - def test_setConfigurationSetValues(self): - prop = OpenRTM_aist.Properties(defaults_str=configsample_mode_spec) - self.assertEqual(self._ca.setConfigurationSetValues(prop.getNode("conf.default")),True) - return - - def test_getActiveConfigurationSet(self): - self.assertEqual(self._ca.getActiveConfigurationSet().getName(),"default") - return - - def test_addConfigurationSet(self): - prop = OpenRTM_aist.Properties(defaults_str=configsample_add_spec) - self.assertEqual(self._ca.addConfigurationSet(prop.getNode("conf.mode0")),True) - return - - def test_removeConfigurationSet(self): - prop = OpenRTM_aist.Properties(defaults_str=configsample_add_spec) - self.assertEqual(self._ca.addConfigurationSet(prop.getNode("conf.mode0")),True) - self.assertEqual(self._ca.removeConfigurationSet("mode0"),True) - return - - - def test_activateConfigurationSet(self): - prop = OpenRTM_aist.Properties(defaults_str=configsample_add_spec) - self.assertEqual(self._ca.addConfigurationSet(prop.getNode("conf.mode0")),True) - self.assertEqual(self._ca.activateConfigurationSet("mode0"),True) - self.assertEqual(self._ca.activateConfigurationSet("default"),True) - self.assertEqual(self._ca.activateConfigurationSet("mode0"),True) - # Failure pattern - # self.assertEqual(self._ca.activateConfigurationSet("mode1"),True) - return - - def test_setOnUpdate(self): - self._ca.setOnUpdate(self.CallBack) - return - - def test_setOnUpdateParam(self): - self._ca.setOnUpdateParam(self.CallBack) - return - - def test_setOnSetConfigurationSet(self): - self._ca.setOnSetConfigurationSet(self.CallBack) - return - - def test_setOnAddConfigurationSet(self): - self._ca.setOnAddConfigurationSet(self.CallBack) - return - - - def test_setOnRemoveConfigurationSet(self): - self._ca.setOnRemoveConfigurationSet(self.CallBack) - return - - - def test_setOnActivateSet(self): - self._ca.setOnActivateSet(self.CallBack) - return - - - def test_onUpdate(self): - self._ca.setOnUpdate(self.CallBack) - self._ca.onUpdate("onUpdate") - return - - - def test_onUpdateParam(self): - self._ca.setOnUpdateParam(self.CallBack) - self._ca.onUpdateParam("onUpdateParam","Param") - return - - - def test_onSetConfigurationSet(self): - self._ca.setOnSetConfigurationSet(self.CallBack) - self._ca.onSetConfigurationSet("onSetConfigurationSet") - return - - - def test_onAddConfigurationSet(self): - self._ca.setOnAddConfigurationSet(self.CallBack) - self._ca.onAddConfigurationSet("onAddConfigurationSet") - return - - - def test_onRemoveConfigurationSet(self): - self._ca.setOnRemoveConfigurationSet(self.CallBack) - self._ca.onRemoveConfigurationSet("onRemoveConfigurationSet") - return - - - def test_onActivateSet(self): - self._ca.setOnActivateSet(self.CallBack) - self._ca.onActivateSet("ActivateSet") - return - - - def test_addremoveConfigurationParamListener(self): - listener = ConfigParamListenerCallback() - self._ca.addConfigurationParamListener(OpenRTM_aist.ConfigurationParamListenerType.ON_UPDATE_CONFIG_PARAM, - listener) - self._ca.onUpdateParam("","") - self._ca.removeConfigurationParamListener(OpenRTM_aist.ConfigurationParamListenerType.ON_UPDATE_CONFIG_PARAM, - listener) - return - - def test_addremoveConfigurationSetListener(self): - listener = ConfigSetListenerCallback() - self._ca.addConfigurationSetListener(OpenRTM_aist.ConfigurationSetListenerType.ON_SET_CONFIG_SET, - listener) - self._ca.onSetConfigurationSet(None) - self._ca.removeConfigurationSetListener(OpenRTM_aist.ConfigurationSetListenerType.ON_SET_CONFIG_SET, - listener) - self._ca.addConfigurationSetListener(OpenRTM_aist.ConfigurationSetListenerType.ON_ADD_CONFIG_SET, - listener) - self._ca.onSetConfigurationSet(None) - self._ca.removeConfigurationSetListener(OpenRTM_aist.ConfigurationSetListenerType.ON_ADD_CONFIG_SET, - listener) - return - - def test_addremoveConfigurationSetNameListener(self): - listener = ConfigSetNameListenerCallback() - self._ca.addConfigurationSetNameListener(OpenRTM_aist.ConfigurationSetNameListenerType.ON_UPDATE_CONFIG_SET, - listener) - self._ca.onUpdate("") - self._ca.removeConfigurationSetNameListener(OpenRTM_aist.ConfigurationSetNameListenerType.ON_UPDATE_CONFIG_SET, - listener) - - self._ca.addConfigurationSetNameListener(OpenRTM_aist.ConfigurationSetNameListenerType.ON_REMOVE_CONFIG_SET, - listener) - self._ca.onUpdate("") - self._ca.removeConfigurationSetNameListener(OpenRTM_aist.ConfigurationSetNameListenerType.ON_REMOVE_CONFIG_SET, - listener) - - self._ca.addConfigurationSetNameListener(OpenRTM_aist.ConfigurationSetNameListenerType.ON_ACTIVATE_CONFIG_SET, - listener) - self._ca.onUpdate("") - self._ca.removeConfigurationSetNameListener(OpenRTM_aist.ConfigurationSetNameListenerType.ON_ACTIVATE_CONFIG_SET, - listener) - return - -class ConfigParamListenerCallback(OpenRTM_aist.ConfigurationParamListener): - def __init__(self): - OpenRTM_aist.ConfigurationParamListener.__init__(self) - return - - def __call__(self, config_set_name, config_param_name): - print "ConfigParamListenerCallback called" - return - -class ConfigSetListenerCallback(OpenRTM_aist.ConfigurationSetListener): - def __init__(self): - OpenRTM_aist.ConfigurationSetListener.__init__(self) - return - - def __call__(self, config_set): - print "ConfigSetListenerCallback called" - return - -class ConfigSetNameListenerCallback(OpenRTM_aist.ConfigurationSetNameListener): - def __init__(self): - OpenRTM_aist.ConfigurationSetNameListener.__init__(self) - return - - def __call__(self, config_set_name): - print "ConfigSetNameListenerCallback called" - return - - -############### test ################# -if __name__ == '__main__': - unittest.main() diff --git a/OpenRTM_aist/test/test_ConfigurationListener.py b/OpenRTM_aist/test/test_ConfigurationListener.py deleted file mode 100644 index 2012f993..00000000 --- a/OpenRTM_aist/test/test_ConfigurationListener.py +++ /dev/null @@ -1,122 +0,0 @@ -#!/usr/bin/env python -# -*- coding: euc-jp -*- - -## -# @file test ConfigurationListener.py -# @brief test for ConfigurationListener class -# @date $Date$ -# @author Shinji Kurihara -# -# Copyright (C) 2011 -# Intelligent Systems Research Institute, -# National Institute of -# Advanced Industrial Science and Technology (AIST), Japan -# All rights reserved. - -import sys -sys.path.insert(1,"../") - -import unittest - -from ConfigurationListener import * -import OpenRTM_aist - -config_set = ["conf.default.int_param0", "0", - "conf.default.int_param1", "1", - "conf.default.double_param0", "0.11", - "conf.default.double_param1", "9.9", - "conf.default.str_param0", "hoge", - "conf.default.str_param1", "dara", - "conf.default.vector_param0", "0.0,1.0,2.0,3.0,4.0", - ""] - -class MockConfigurationParamListener(ConfigurationParamListener): - def __init__(self): - ConfigurationParamListener.__init__(self) - return - - def __call__(self, config_set_name, config_param_name): - return (config_set_name, config_param_name) - -class MockConfigurationSetListener(ConfigurationSetListener): - def __init__(self): - ConfigurationSetListener.__init__(self) - return - - def __call__(self, config_set): - return config_set - -class MockConfigurationSetNameListener(ConfigurationSetNameListener): - def __init__(self): - ConfigurationSetNameListener.__init__(self) - return - - def __call__(self, config_set_name): - return config_set_name - - -class TestListener(unittest.TestCase): - def setUp(self): - return - - def tearDown(self): - OpenRTM_aist.Manager.instance().shutdownManager() - return - - def test_ConfigurationParamListener_toString(self): - self.assertEqual("ON_UPDATE_CONFIG_PARAM", - ConfigurationParamListener.toString( - ConfigurationParamListenerType.ON_UPDATE_CONFIG_PARAM)) - return - - def test_ConfigurationSetListener_toString(self): - self.assertEqual("ON_SET_CONFIG_SET", - ConfigurationSetListener.toString( - ConfigurationSetListenerType.ON_SET_CONFIG_SET)) - self.assertEqual("ON_ADD_CONFIG_SET", - ConfigurationSetListener.toString( - ConfigurationSetListenerType.ON_ADD_CONFIG_SET)) - return - - def test_ConfigurationSetNameListener_toString(self): - self.assertEqual("ON_UPDATE_CONFIG_SET", - ConfigurationSetNameListener.toString( - ConfigurationSetNameListenerType.ON_UPDATE_CONFIG_SET)) - self.assertEqual("ON_REMOVE_CONFIG_SET", - ConfigurationSetNameListener.toString( - ConfigurationSetNameListenerType.ON_REMOVE_CONFIG_SET)) - self.assertEqual("ON_ACTIVATE_CONFIG_SET", - ConfigurationSetNameListener.toString( - ConfigurationSetNameListenerType.ON_ACTIVATE_CONFIG_SET)) - return - - def test_ConfigurationParamListenerHolder(self): - configparams = ConfigurationListeners() - listener = MockConfigurationParamListener() - configparams.configparam_[0].addListener(listener,True) - configparams.configparam_[0].notify("config_set_name","config_param_name") - configparams.configparam_[0].removeListener(listener) - return - - def test_ConfigurationSetListenerHolder(self): - configsetss = ConfigurationListeners() - listener = MockConfigurationSetListener() - configsets.configset_[0].addListener(listener,True) - prop = OpenRTM_aist.Properties(defaults_str=config_set) - configsets.configset_[0].notify(prop) - configsets.configset_[0].removeListener(listener) - return - - def test_ConfigurationSetNameListenerHolder(self): - configsetnames = ConfigurationListeners() - listener = MockConfigurationSetNameListener() - configsetnames.configsetname_[0].addListener(listener,True) - configsetnames.configsetname_[0].notify("config_set_name") - configsetnames.configsetname_[0].removeListener(listener) - return - - -############### test ################# -if __name__ == '__main__': - unittest.main() - diff --git a/OpenRTM_aist/test/test_ConnectorListener.py b/OpenRTM_aist/test/test_ConnectorListener.py deleted file mode 100755 index e8b593da..00000000 --- a/OpenRTM_aist/test/test_ConnectorListener.py +++ /dev/null @@ -1,211 +0,0 @@ -#!/usr/bin/env python -# -*- Python -*- - -## -# @file test_ConnectorListener.py -# @brief test for connector listener class -# @date $Date: 2010/01/06 $ -# @author Shinji Kurihara -# -# Copyright (C) 2010 -# Task-intelligence Research Group, -# Intelligent Systems Research Institute, -# National Institute of -# Advanced Industrial Science and Technology (AIST), Japan -# All rights reserved. -# - -import sys -sys.path.insert(1,"../") - -import unittest -import OpenRTM_aist -from ConnectorListener import * - -import RTC, RTC__POA -import OpenRTM - -from omniORB import * -from omniORB import any - -class DataListener(OpenRTM_aist.ConnectorDataListenerT): - def __init__(self, name): - self._name = name - self._data = None - return - - def __del__(self): - return - - def __call__(self, info, cdrdata): - data = OpenRTM_aist.ConnectorDataListenerT.__call__(self, info, cdrdata, RTC.TimedLong(RTC.Time(0,0),0)) - print "------------------------------" - print "Listener: ", self._name - print "------------------------------" - self._data = data - return - - def get_data(self): - tmp = self._data - self._data = None - return tmp - - - -class Listener(OpenRTM_aist.ConnectorListener): - def __init__(self, name): - self._name = name - return - - def __del__(self): - return - - def __call__(self, info): - print "------------------------------" - print "Listener: ", self._name - print "------------------------------" - return - - -def typeToStringDataListener(type): - if type == OpenRTM_aist.ConnectorDataListenerType.ON_BUFFER_WRITE: - return "ON_BUFFER_WRITE" - - elif type == OpenRTM_aist.ConnectorDataListenerType.ON_BUFFER_FULL: - return "ON_BUFFER_FULL" - - elif type == OpenRTM_aist.ConnectorDataListenerType.ON_BUFFER_WRITE_TIMEOUT: - return "ON_BUFFER_WRITE_TIMEOUT" - - elif type == OpenRTM_aist.ConnectorDataListenerType.ON_BUFFER_OVERWRITE: - return "ON_BUFFER_OVERWRITE" - - elif type == OpenRTM_aist.ConnectorDataListenerType.ON_BUFFER_READ: - return "ON_BUFFER_READ" - - elif type == OpenRTM_aist.ConnectorDataListenerType.ON_SEND: - return "ON_SEND" - - elif type == OpenRTM_aist.ConnectorDataListenerType.ON_RECEIVED: - return "ON_RECEIVED" - - elif type == OpenRTM_aist.ConnectorDataListenerType.ON_RECEIVER_FULL: - return "ON_RECEIVER_FULL" - - elif type == OpenRTM_aist.ConnectorDataListenerType.ON_RECEIVER_TIMEOUT: - return "ON_RECEIVER_TIMEOUT" - - elif type == OpenRTM_aist.ConnectorDataListenerType.ON_RECEIVER_ERROR: - return "ON_RECEIVER_ERROR" - - else: - return "UNKNOWN" - - -def typeToStringListener(type): - if type == OpenRTM_aist.ConnectorListenerType.ON_BUFFER_EMPTY: - return "ON_BUFFER_EMPTY" - - elif type == OpenRTM_aist.ConnectorListenerType.ON_BUFFER_READ_TIMEOUT: - return "ON_BUFFER_READ_TIMEOUT" - - elif type == OpenRTM_aist.ConnectorListenerType.ON_SENDER_EMPTY: - return "ON_SENDER_EMPTY" - - elif type == OpenRTM_aist.ConnectorListenerType.ON_SENDER_TIMEOUT: - return "ON_SENDER_TIMEOUT" - - elif type == OpenRTM_aist.ConnectorListenerType.ON_SENDER_ERROR: - return "ON_SENDER_ERROR" - - else: - return "UNKNOWN" - - -class TestConnectorListener(unittest.TestCase): - def setUp(self): - self._connectorListeners = ConnectorListeners() - self._info = OpenRTM_aist.ConnectorInfo("name", - "id", - [], - OpenRTM_aist.Properties()) - - self._datalisteners = [] - self._listeners = [] - - for i in range(OpenRTM_aist.ConnectorDataListenerType.CONNECTOR_DATA_LISTENER_NUM): - self._datalisteners.append(DataListener(typeToStringDataListener(i))) - - for i in range(OpenRTM_aist.ConnectorListenerType.CONNECTOR_LISTENER_NUM): - self._listeners.append(Listener(typeToStringListener(i))) - - return - - - def test_ConnectorDataListenerT(self): - # add DataListener. - for i in range(OpenRTM_aist.ConnectorDataListenerType.CONNECTOR_DATA_LISTENER_NUM): - self._connectorListeners.connectorData_[i].addListener(self._datalisteners[i],True) - - # test for ConnectorDataListenerT.__call__() with little endian data. - for i in range(OpenRTM_aist.ConnectorDataListenerType.CONNECTOR_DATA_LISTENER_NUM): - data = RTC.TimedLong(RTC.Time(0,0),i) - cdr_data = cdrMarshal(any.to_any(data).typecode(), data, True) # little endian - self._connectorListeners.connectorData_[i].notify(self._info, cdr_data) - self.assertEqual(self._datalisteners[i].get_data().data, i) - - - # test for ConnectorDataListenerT.__call__() with big endian data. - info = OpenRTM_aist.ConnectorInfo("name", - "id", - [], - OpenRTM_aist.Properties()) - info.properties.setProperty("serializer.cdr.endian","big") - - for i in range(OpenRTM_aist.ConnectorDataListenerType.CONNECTOR_DATA_LISTENER_NUM): - data = RTC.TimedLong(RTC.Time(0,0),i) - cdr_data = cdrMarshal(any.to_any(data).typecode(), data, False) # big endian - self._connectorListeners.connectorData_[i].notify(info, cdr_data) - self.assertEqual(self._datalisteners[i].get_data().data, i) - - - # remove DataListener. - for i in range(OpenRTM_aist.ConnectorDataListenerType.CONNECTOR_DATA_LISTENER_NUM): - self._connectorListeners.connectorData_[i].removeListener(self._datalisteners[i]) - - for i in range(OpenRTM_aist.ConnectorDataListenerType.CONNECTOR_DATA_LISTENER_NUM): - data = RTC.TimedLong(RTC.Time(0,0),i) - cdr_data = cdrMarshal(any.to_any(data).typecode(), data, True) - self._connectorListeners.connectorData_[i].notify(self._info, cdr_data) - # get_data() return None, because removeListener was called. - self.assertEqual(self._datalisteners[i].get_data(), None) - - return - - - def test_ConnectorListener(self): - # add Listener. - for i in range(OpenRTM_aist.ConnectorListenerType.CONNECTOR_LISTENER_NUM): - self._connectorListeners.connector_[i].addListener(self._listeners[i],True) - - # test for ConnectorListener.__call__() - for i in range(OpenRTM_aist.ConnectorListenerType.CONNECTOR_LISTENER_NUM): - self._connectorListeners.connector_[i].notify(self._info) - - # remove Listener. - for i in range(OpenRTM_aist.ConnectorListenerType.CONNECTOR_LISTENER_NUM): - self._connectorListeners.connector_[i].removeListener(self._listeners[i]) - - for i in range(OpenRTM_aist.ConnectorListenerType.CONNECTOR_LISTENER_NUM): - self._connectorListeners.connector_[i].notify(self._info) - - return - - - - - -############### test ################# -if __name__ == '__main__': - unittest.main() - diff --git a/OpenRTM_aist/test/test_CorbaConsumer.py b/OpenRTM_aist/test/test_CorbaConsumer.py deleted file mode 100755 index c2021c00..00000000 --- a/OpenRTM_aist/test/test_CorbaConsumer.py +++ /dev/null @@ -1,63 +0,0 @@ -#!/usr/bin/env python -# -*- Python -*- - -# -# \file test_CorbaConsumer.py -# \brief CORBA Consumer class -# \date $Date: 2007/09/20 $ -# \author Shinji Kurihara -# -# Copyright (C) 2006 -# Noriaki Ando -# Task-intelligence Research Group, -# Intelligent Systems Research Institute, -# National Institute of -# Advanced Industrial Science and Technology (AIST), Japan -# All rights reserved. - - -from omniORB import CORBA -from omniORB import any -from omniORB import * - -import sys -sys.path.insert(1,"../") -sys.path.insert(1,"../RTM_IDL") - -import unittest - -from CorbaConsumer import * - -import OpenRTM, OpenRTM__POA - -class InPortTest(OpenRTM__POA.InPortCdr): - def __init__(self): - self.orb = CORBA.ORB_init() - self.poa = self.orb.resolve_initial_references("RootPOA") - poaManager = self.poa._get_the_POAManager() - poaManager.activate() - - - def put(self, data): - #print "put data: ", data - return OpenRTM.PORT_OK - - -class TestCorbaConsumer(unittest.TestCase): - def setUp(self): - - self._cc = CorbaConsumer() - - def test_case(self): - self._cc.setObject(InPortTest()._this()) - obj = self._cc._ptr()._narrow(OpenRTM.InPortCdr) - cdr = cdrMarshal(any.to_any("hoge").typecode(), "hoge", 1) - self.assertEqual(OpenRTM.PORT_OK,obj.put(cdr)) - self._cc.releaseObject() - self.assertEqual(self._cc._ptr(), None) - - - -############### test ################# -if __name__ == '__main__': - unittest.main() diff --git a/OpenRTM_aist/test/test_CorbaNaming.py b/OpenRTM_aist/test/test_CorbaNaming.py deleted file mode 100755 index 8ba5110f..00000000 --- a/OpenRTM_aist/test/test_CorbaNaming.py +++ /dev/null @@ -1,182 +0,0 @@ -#!/usr/bin/env python -# -*- Python -*- - - -## \file test_CorbaNaming.py -## \brief test for CORBA naming service helper class -## \author Shinji Kurihara -# -# Copyright (C) 2006 -# Noriaki Ando -# Task-intelligence Research Group, -# Intelligent Systems Research Institute, -# National Institute of -# Advanced Industrial Science and Technology (AIST), Japan -# All rights reserved. -# - -import sys -sys.path.insert(1,"../") - -import unittest -import time - -from CorbaNaming import * -import OpenRTM_aist - -class TestCorbaNaming(unittest.TestCase): - - def setUp(self): - self.orb = OpenRTM_aist.Manager.instance().getORB() - self.naming = CorbaNaming(self.orb, "localhost:2809") - #self.naming.clearAll() - self.name_list = [] - self.name_list.append(CosNaming.NameComponent("Mon","mon_cxt")) - self.name_list.append(CosNaming.NameComponent("Tus","tus_cxt")) - self.name_list.append(CosNaming.NameComponent("Wed","wed_cxt")) - self.name_list.append(CosNaming.NameComponent("Thu","thu_cxt")) - self.name_list.append(CosNaming.NameComponent("Fri","fri_cxt")) - self.name_list.append(CosNaming.NameComponent("Sat","sat_cxt")) - self.name_list.append(CosNaming.NameComponent("Sun","sun_cxt")) - - return - - - def tearDown(self): - OpenRTM_aist.Manager.instance().shutdownManager() - del self - return - - def test_init(self): - try: - self.naming.init("localhost") - except: - print "Exeption at naming init." - - - def test_bind(self): - self.naming.clearAll() - self.bind_test_sequence(self.name_list) - - - def bind_test_sequence(self, sname): - obj = self.naming.newContext() - self.naming.bind(sname, obj) - - # resolve test - new_obj = self.naming.resolve(sname) - self.assertEqual(obj._is_equivalent(new_obj), True,"Resolve failed.") - return True - - - def test_bindByString(self): - name = "localhost.host_cxt\/Manager123456.mgr_cxt/MobileRobot.cat_cxt/Kani0.rtc" - - lname = [] - lname.append(CosNaming.NameComponent("localhost.host_cxt\/Manager123456","mgr_cxt")) - lname.append(CosNaming.NameComponent("MobileRobot","cat_cxt")) - lname.append(CosNaming.NameComponent("Kani0","rtc")) - - obj = self.naming.newContext() - self.naming.bindByString(name, obj) - new_obj = self.naming.resolve(name) - self.assertEqual(obj._is_equivalent(new_obj), True,"Resolve failed.") - new_obj = self.naming.resolve(lname) - self.assertEqual(obj._is_equivalent(new_obj), True,"Resolve failed.") - - - #def test_bindRecursive(self): - # pass - - def test_rebind(self): - obj = self.naming.newContext() - - self.naming.bind(self.name_list, obj) - new_obj = self.naming.resolve(self.name_list) - self.assertEqual(obj._is_equivalent(new_obj), True,"Resolve failed.") - - self.naming.rebind(self.name_list, obj) - new_obj = self.naming.resolve(self.name_list) - self.assertEqual(obj._is_equivalent(new_obj), True,"Resolve failed.") - - - #def test_rebindByString(self): - # pass - - - def test_rebindRecursive(self): - obj = self.naming.newContext() - - self.naming.bind(self.name_list, obj) - new_obj = self.naming.resolve(self.name_list) - self.assertEqual(obj._is_equivalent(new_obj), True,"Resolve failed.") - - self.naming.rebindRecursive(self.naming.getRootContext(), self.name_list, obj) - new_obj = self.naming.resolve(self.name_list) - self.assertEqual(obj._is_equivalent(new_obj), True,"Resolve failed.") - - - def test_bindContext(self): - obj = self.naming.newContext() - name = [] - name.append(CosNaming.NameComponent("bindcxt","bindcxt_cxt")) - - self.naming.bindContext("bindcxt.bindcxt_cxt", obj) - new_obj = self.naming.resolve(name) - self.assertEqual(obj._is_equivalent(new_obj), True,"Resolve failed.") - - - def test_unbind(self): - obj = self.naming.newContext() - - self.naming.bind(self.name_list, obj) - self.naming.unbind(self.name_list) - - - def test_bindNewContext(self): - name = [] - name.append(CosNaming.NameComponent("newContext","new_cxt")) - - self.naming.bindNewContext(name) - new_obj = self.naming.resolve(name) - - - def test_destroy(self): - obj = self.naming.newContext() - name = [] - name.append(CosNaming.NameComponent("destroy","destroy_cxt")) - - self.naming.bind(name, obj) - self.naming.destroy(obj) - - - def test_destroyRecursive(self): - obj = self.naming.newContext() - name = [] - name.append(CosNaming.NameComponent("desRec0","desRec0_cxt")) - name.append(CosNaming.NameComponent("desRec1","desRec1_cxt")) - name.append(CosNaming.NameComponent("desRec2","desRec2_cxt")) - - self.naming.bind(name, obj) - self.naming.destroyRecursive(obj) - - def test_list(self): - bl = [] - bi = [] - self.naming.list(self.naming.getRootContext(), 100, bl, bi) - print bl[0][0].binding_name[0].id - - - def test_toString(self): - name = [] - name.append(CosNaming.NameComponent("desRec0","desRec0_cxt")) - name.append(CosNaming.NameComponent("desRec1","desRec1_cxt")) - name.append(CosNaming.NameComponent("desRec2","desRec2_cxt")) - - string_name = self.naming.toString(name) - self.assertEqual(str("desRec0.desRec0_cxt/desRec1.desRec1_cxt/desRec2.desRec2_cxt/"),str(string_name)) - print ".",string_name,"." - -############### test ################# -if __name__ == '__main__': - unittest.main() diff --git a/OpenRTM_aist/test/test_CorbaObjectManager.py b/OpenRTM_aist/test/test_CorbaObjectManager.py deleted file mode 100755 index ccc6ce1d..00000000 --- a/OpenRTM_aist/test/test_CorbaObjectManager.py +++ /dev/null @@ -1,63 +0,0 @@ -#!/usr/bin/env python -# -*- Python -*- - -# -# \file test_CorbaObjManager.py -# \brief test for CORBA Object manager class -# \date $Date: 2007/08/27$ -# \author Shinji Kurihara -# -# Copyright (C) 2006 -# Noriaki Ando -# Task-intelligence Research Group, -# Intelligent Systems Research Institute, -# National Institute of -# Advanced Industrial Science and Technology (AIST), Japan -# All rights reserved. -# - -import sys -sys.path.insert(1,"../") - -import unittest - -import OpenRTM_aist - -from omniORB import CORBA, PortableServer -from CorbaObjectManager import * - - - -class test_comp(OpenRTM_aist.RTObject_impl): - def __init__(self): - pass - - def echo(self, msg): - print msg - return msg - - -class TestCorbaObjectManager(unittest.TestCase): - - def setUp(self): - self._orb = CORBA.ORB_init() - self._poa = self._orb.resolve_initial_references("RootPOA") - self._poa._get_the_POAManager().activate() - - self._com = CorbaObjectManager(self._orb, self._poa) - - self._obj = test_comp() - - def tearDown(self): - pass - - - def test_activate(self): - self._com.activate(self._obj) - - def test_deactivate(self): - self._com.deactivate(self._obj) - -############### test ################# -if __name__ == '__main__': - unittest.main() diff --git a/OpenRTM_aist/test/test_CorbaPort.py b/OpenRTM_aist/test/test_CorbaPort.py deleted file mode 100755 index f8bb759a..00000000 --- a/OpenRTM_aist/test/test_CorbaPort.py +++ /dev/null @@ -1,127 +0,0 @@ -#!/usr/bin/env python -# -*- Python -*- - -# -# \file test_CorbaPort.py -# \brief test for CorbaPort class -# \date $Date: 2007/09/27 $ -# \author Shinji Kurihara -# -# Copyright (C) 2006 -# Noriaki Ando -# Task-intelligence Research Group, -# Intelligent Systems Research Institute, -# National Institute of -# Advanced Industrial Science and Technology (AIST), Japan -# All rights reserved. - -from omniORB import any -import CORBA - -import OpenRTM_aist -import RTC, RTC__POA - -import sys -sys.path.insert(1,"../") - -import unittest - -from CorbaPort import * - -import _GlobalIDL, _GlobalIDL__POA - - -class MyService_impl(_GlobalIDL__POA.MyService): - def __init__(self): - pass - - def echo(self, msg): - print msg - return msg - - -class TestCorbaPort(unittest.TestCase): - def setUp(self): - orb = CORBA.ORB_init(sys.argv) - poa = orb.resolve_initial_references("RootPOA") - poa._get_the_POAManager().activate() - - self._mysvc = MyService_impl() - self._mycon = OpenRTM_aist.CorbaConsumer() - #self._mysvc._this() - - self._cpSvc = CorbaPort("MyService") - self._cpCon = CorbaPort("MyService") - - def tearDown(self): - OpenRTM_aist.Manager.instance().shutdownManager() - return - - def test_init(self): - prop = OpenRTM_aist.Properties() - prop.setProperty("connection_limit","3") - self._cpSvc.init(prop) - prop = OpenRTM_aist.Properties() - self._cpSvc.init(prop) - pass - - - def test_registerProvider(self): - self.assertEqual(self._cpSvc.registerProvider("myservice0", "MyService", self._mysvc),True) - self._cpSvc.activateInterfaces() - self._cpSvc.deactivateInterfaces() - - - def test_registerConsumer(self): - self.assertEqual(self._cpCon.registerConsumer("myservice0", "MyService", self._mycon),True) - - - def test_activateInterfaces(self): - self.assertEqual(self._cpSvc.registerProvider("myservice0", "MyService", self._mysvc),True) - self._cpSvc.activateInterfaces() - self._cpSvc.deactivateInterfaces() - self._cpSvc.activateInterfaces() - self._cpSvc.deactivateInterfaces() - - - def test_deactivateInterfaces(self): - self.assertEqual(self._cpSvc.registerProvider("myservice0", "MyService", self._mysvc),True) - self._cpSvc.activateInterfaces() - self._cpSvc.deactivateInterfaces() - - - def test_publishInterfaces(self): - prof = RTC.ConnectorProfile("","",[],[]) - self.assertEqual(self._cpSvc.publishInterfaces(prof),RTC.RTC_OK) - - - def test_subscribeInterfaces(self): - self.assertEqual(self._cpSvc.registerProvider("myservice0", "MyService", self._mysvc),True) - self.assertEqual(self._cpCon.registerConsumer("myservice0", "MyService", self._mycon),True) - prof = RTC.ConnectorProfile("","", - [self._cpSvc.getPortRef(),self._cpCon.getPortRef()], - []) - self.assertEqual(self._cpSvc.subscribeInterfaces(prof),RTC.RTC_OK) - - - def test_unsubscribeInterfaces(self): - prof = RTC.ConnectorProfile("","",[],[]) - self._cpSvc.unsubscribeInterfaces(prof) - - def test_findProvider(self): - self.assertEqual(self._cpSvc.registerProvider("myservice0", "MyService", self._mysvc),True) - consHolder = CorbaPort.CorbaConsumerHolder("myservice0","MyService",self._mycon,self._cpCon) - ior=[] - self.assertEqual(self._cpSvc.findProvider([],consHolder,ior),False) - - def test_findProviderOld(self): - self.assertEqual(self._cpSvc.registerProvider("myservice0", "MyService", self._mysvc),True) - consHolder = CorbaPort.CorbaConsumerHolder("myservice0","MyService",self._mycon,self._cpCon) - ior=[] - self.assertEqual(self._cpSvc.findProviderOld([],consHolder,ior),False) - - - -############### test ################# -if __name__ == '__main__': - unittest.main() diff --git a/OpenRTM_aist/test/test_CreateComponent_Slave.py b/OpenRTM_aist/test/test_CreateComponent_Slave.py deleted file mode 100644 index bb6b696d..00000000 --- a/OpenRTM_aist/test/test_CreateComponent_Slave.py +++ /dev/null @@ -1,211 +0,0 @@ -#!/usr/bin/env python -# -*- coding: euc-jp -*- - -# -# \file test_CreateComponent_Slave.py -# \brief -# \date $Date: $ -# \author Nobuhiko Miyamoto -# - - -import sys -sys.path.insert(1,"../") - -try: - import unittest2 as unittest -except (ImportError): - import unittest - -import time - -#from Manager import * -import OpenRTM_aist -import RTC, RTC__POA -import multiprocessing - -testcomp1_spec = ["implementation_id", "TestComp1", - "type_name", "TestComp1", - "description", "Test example component", - "version", "1.0", - "vendor", "Nobuhiko Myiyamoto", - "category", "example", - "activity_type", "DataFlowComponent", - "max_instance", "10", - "language", "C++", - "lang_type", "compile", - "conf.default.test1", "0", - ""] - -testcomp2_spec = ["implementation_id", "TestComp2", - "type_name", "TestComp2", - "description", "Test example component", - "version", "1.0", - "vendor", "Nobuhiko Myiyamoto", - "category", "example", - "activity_type", "DataFlowComponent", - "max_instance", "10", - "language", "C++", - "lang_type", "compile", - ""] - - - - -class TestComp1(OpenRTM_aist.DataFlowComponentBase): - def __init__(self, manager): - OpenRTM_aist.DataFlowComponentBase.__init__(self, manager) - - - def onInitialize(self): - - return RTC.RTC_OK - -class TestComp2(OpenRTM_aist.DataFlowComponentBase): - def __init__(self, manager): - OpenRTM_aist.DataFlowComponentBase.__init__(self, manager) - - - return - - def onInitialize(self): - - - return RTC.RTC_OK - - - - -def TestComp1Init(manager): - profile = OpenRTM_aist.Properties(defaults_str=testcomp1_spec) - manager.registerFactory(profile, - TestComp1, - OpenRTM_aist.Delete) - - - -def TestComp2Init(manager): - profile = OpenRTM_aist.Properties(defaults_str=testcomp2_spec) - manager.registerFactory(profile, - TestComp2, - OpenRTM_aist.Delete) - - -def TestComp1ModuleInit(manager): - TestComp1Init(manager) - #com = manager.createComponent("TestComp1") - -def TestComp2ModuleInit(manager): - TestComp2Init(manager) - #com = manager.createComponent("TestComp2") - - -def runTestComp2(q): - q.get() - argv = ["dummy"] - argv.extend(['-o','naming.type:corba,manager']) - argv.extend(['-o','naming.formats:test.host_cxt/%n.rtc']) - argv.extend(['-o','manager.instance_name:manager2']) - argv.extend(['-o','manager.shutdown_on_nortcs:NO']) - argv.extend(['-o','manager.shutdown_auto:NO']) - - manager = OpenRTM_aist.Manager.init(argv) - manager.setModuleInitProc(TestComp2ModuleInit) - manager.activateManager() - - - - - #print manager.getManagerServant().findManager_by_name("manager") - #rtc = manager.getManagerServant().create_component("testSHM_in&manager_name=manager3&language=Python") - #rtc = manager.getManagerServant().create_component("AbsFunction&manager_name=manager3&language=C++") - #$print rtc - #rtc = manager.getManagerServant().create_component("testSHM_in") - #print rtc - q.get() - - comps = manager.getComponents()[:] - for comp in comps: - manager.unregisterComponent(comp) - comp_id = comp.getProperties() - factory = manager._factory.find(comp_id) - factory.destroy(comp) - manager.shutdownNaming() - time.sleep(0.1) - - -class Test_CreateComponent_Slave(unittest.TestCase): - - def setUp(self): - - - sys.argv.extend(['-d']) - sys.argv.extend(['-o','naming.type:corba,manager']) - sys.argv.extend(['-o','naming.formats:test.host_cxt/%n.rtc']) - sys.argv.extend(['-o','manager.instance_name:manager']) - #sys.argv.extend(['-o','logger.log_level:DEBUG']) - self.manager = OpenRTM_aist.Manager.init(sys.argv) - self.manager.setModuleInitProc(TestComp1ModuleInit) - self.manager.activateManager() - - - - - - - - - def tearDown(self): - - - comps = self.manager.getComponents()[:] - for comp in comps: - self.manager.unregisterComponent(comp) - comp_id = comp.getProperties() - factory = self.manager._factory.find(comp_id) - factory.destroy(comp) - self.manager.shutdownNaming() - - time.sleep(0.1) - - - - - - def test_createComponent_slave(self): - self.queue = multiprocessing.Queue() - self.outport_process = multiprocessing.Process(target=runTestComp2, args=(self.queue,)) - self.outport_process.start() - self.queue.put("") - time.sleep(1) - test_module_name = ["comp&test=0"] - test_value = self.manager.getManagerServant().get_parameter_by_modulename("test",test_module_name) - self.assertEqual(test_value,"0") - self.assertEqual(test_module_name[0],"comp") - #rtc = self.manager.getManagerServant().create_component("TestComp1&manager_name=manager2") - #rtc = self.manager.getManagerServant().create_component("TestComp2&manager_address=localhost:2810") - rtc = self.manager.getManagerServant().create_component("TestComp2&manager_name=manager2") - slave = self.manager.getManagerServant().findManager_by_name("manager2") - self.assertTrue(slave is not None) - rtcs = slave.get_components_by_name("TestComp20") - name = rtcs[0].get_component_profile().instance_name - self.assertEqual(name,"TestComp20") - - self.queue.put("") - #rtc = self.manager.getManagerServant().create_component("TestComp2") - #print rtc - #comps = self.manager.getComponents() - #print comps - - def test_createComponent_newProcess(self): - rtc = self.manager.getManagerServant().create_component("TestComp3&manager_name=manager3&language=Python") - slave = self.manager.getManagerServant().findManager_by_name("manager3") - rtcs = slave.get_components_by_name("TestComp30") - name = rtcs[0].get_component_profile().instance_name - self.assertEqual(name,"TestComp30") - - - -############### test ################# -if __name__ == '__main__': - unittest.main() diff --git a/OpenRTM_aist/test/test_DataInPort.py b/OpenRTM_aist/test/test_DataInPort.py deleted file mode 100755 index 8a4e9787..00000000 --- a/OpenRTM_aist/test/test_DataInPort.py +++ /dev/null @@ -1,58 +0,0 @@ -#!/usr/bin/env python -# -*- Python -*- - -# -# \file test_DataInPort.py -# \brief RTC::Port implementation for Data InPort -# \date $Date: 2007/09/27 $ -# \author Shinji Kurihara -# -# Copyright (C) 2006 -# Noriaki Ando -# Task-intelligence Research Group, -# Intelligent Systems Research Institute, -# National Institute of -# Advanced Industrial Science and Technology (AIST), Japan -# All rights reserved. - -import OpenRTM_aist -import RTC, RTC__POA - -import CORBA -import sys -sys.path.insert(1,"../") - -import unittest - -from DataInPort import * - -class TestObj(OpenRTM_aist.RTObject_impl): - def __init__(self): - self._orb = CORBA.ORB_init() - self._poa = self._orb.resolve_initial_references("RootPOA") - OpenRTM_aist.RTObject_impl.__init__(self, orb=self._orb, poa=self._poa) - - -class TestDataInPort(unittest.TestCase): - def setUp(self): - self._orb = CORBA.ORB_init() - self._poa = self._orb.resolve_initial_references("RootPOA") - inport = OpenRTM_aist.InPort("in", RTC.TimedLong(RTC.Time(0,0),0), - OpenRTM_aist.RingBuffer(8)) - self._dip = DataInPort("in", inport, None) - - def test_case(self): - nvlist = [OpenRTM_aist.NVUtil.newNV("dataport.interface_type","CORBA_Any"), - OpenRTM_aist.NVUtil.newNV("dataport.dataflow_type","Push"), - OpenRTM_aist.NVUtil.newNV("dataport.subscription_type","Flush")] - - prof = RTC.ConnectorProfile("connector0","",[TestObj(),TestObj()],nvlist) - - self.assertEqual(self._dip.publishInterfaces(prof), RTC.RTC_OK) - self.assertEqual(self._dip.subscribeInterfaces(prof), RTC.RTC_OK) - self._dip.unsubscribeInterfaces(prof) - - -############### test ################# -if __name__ == '__main__': - unittest.main() diff --git a/OpenRTM_aist/test/test_DataOutPort.py b/OpenRTM_aist/test/test_DataOutPort.py deleted file mode 100755 index 0e99e878..00000000 --- a/OpenRTM_aist/test/test_DataOutPort.py +++ /dev/null @@ -1,60 +0,0 @@ -#!/usr/bin/env python -# -*- Python -*- - -# -# \file test_DataOutPort.py -# \brief test for Base class of OutPort -# \date $Date: 2007/09/27 $ -# \author Shinji Kurihara -# -# Copyright (C) 2006 -# Noriaki Ando -# Task-intelligence Research Group, -# Intelligent Systems Research Institute, -# National Institute of -# Advanced Industrial Science and Technology (AIST), Japan -# All rights reserved. - - -import OpenRTM_aist -import RTC, RTC__POA - -import CORBA -import sys -sys.path.insert(1,"../") - -import unittest - -from DataOutPort import * - -class TestObj(OpenRTM_aist.RTObject_impl): - def __init__(self): - self._orb = CORBA.ORB_init() - self._poa = self._orb.resolve_initial_references("RootPOA") - OpenRTM_aist.RTObject_impl.__init__(self, orb=self._orb, poa=self._poa) - -class TestDataOutPort(unittest.TestCase): - def setUp(self): - self._orb = CORBA.ORB_init() - self._poa = self._orb.resolve_initial_references("RootPOA") - outport = OpenRTM_aist.OutPort("out", RTC.TimedLong(RTC.Time(0,0),0), - OpenRTM_aist.RingBuffer(8)) - self._dop = DataOutPort("out", outport, None) - - - def test_case(self): - nvlist = [OpenRTM_aist.NVUtil.newNV("dataport.interface_type","CORBA_Any"), - OpenRTM_aist.NVUtil.newNV("dataport.dataflow_type","Push"), - OpenRTM_aist.NVUtil.newNV("dataport.subscription_type","Flush")] - - prof = RTC.ConnectorProfile("connector0","",[TestObj(),TestObj()],nvlist) - - self.assertEqual(self._dop.publishInterfaces(prof), RTC.RTC_OK) - self.assertEqual(self._dop.subscribeInterfaces(prof), RTC.RTC_OK) - self._dop.unsubscribeInterfaces(prof) - - - -############### test ################# -if __name__ == '__main__': - unittest.main() diff --git a/OpenRTM_aist/test/test_DataPortStatus.py b/OpenRTM_aist/test/test_DataPortStatus.py deleted file mode 100755 index 35c23702..00000000 --- a/OpenRTM_aist/test/test_DataPortStatus.py +++ /dev/null @@ -1,52 +0,0 @@ -#!/usr/bin/env python -# -*- Python -*- - -# -# \file test_DataPortStatus.py -# \brief test for CorbaPort class -# \date $Date: 2007/09/27 $ -# \author Shinji Kurihara -# -# Copyright (C) 2006 -# Noriaki Ando -# Task-intelligence Research Group, -# Intelligent Systems Research Institute, -# National Institute of -# Advanced Industrial Science and Technology (AIST), Japan -# All rights reserved. - -import OpenRTM_aist -import RTC, RTC__POA - -import sys -sys.path.insert(1,"../") - -import unittest - -from DataPortStatus import * - - -class TestDataPortStatus(unittest.TestCase): - def setUp(self): - self._dps = DataPortStatus() - - - def test_toString(self): - self.assertEqual(self._dps.toString(DataPortStatus.PORT_OK), "PORT_OK") - self.assertEqual(self._dps.toString(DataPortStatus.PORT_ERROR), "PORT_ERROR") - self.assertEqual(self._dps.toString(DataPortStatus.BUFFER_FULL), "BUFFER_FULL") - self.assertEqual(self._dps.toString(DataPortStatus.BUFFER_EMPTY), "BUFFER_EMPTY") - self.assertEqual(self._dps.toString(DataPortStatus.BUFFER_TIMEOUT), "BUFFER_TIMEOUT") - self.assertEqual(self._dps.toString(DataPortStatus.SEND_FULL), "SEND_FULL") - self.assertEqual(self._dps.toString(DataPortStatus.SEND_TIMEOUT), "SEND_TIMEOUT") - self.assertEqual(self._dps.toString(DataPortStatus.RECV_EMPTY), "RECV_EMPTY") - self.assertEqual(self._dps.toString(DataPortStatus.RECV_TIMEOUT), "RECV_TIMEOUT") - self.assertEqual(self._dps.toString(DataPortStatus.INVALID_ARGS), "INVALID_ARGS") - self.assertEqual(self._dps.toString(DataPortStatus.PRECONDITION_NOT_MET), "PRECONDITION_NOT_MET") - self.assertEqual(self._dps.toString(DataPortStatus.CONNECTION_LOST), "CONNECTION_LOST") - self.assertEqual(self._dps.toString(DataPortStatus.UNKNOWN_ERROR), "UNKNOWN_ERROR") - - -############### test ################# -if __name__ == '__main__': - unittest.main() diff --git a/OpenRTM_aist/test/test_DirectPort.py b/OpenRTM_aist/test/test_DirectPort.py deleted file mode 100644 index 2280ff19..00000000 --- a/OpenRTM_aist/test/test_DirectPort.py +++ /dev/null @@ -1,146 +0,0 @@ -#!/usr/bin/env python -# -*- coding: euc-jp -*- - -# -# \file test_DirectPort.py -# \brief -# \date $Date: $ -# \author Nobuhiko Miyamoto -# - - -import sys -sys.path.insert(1,"../") - -try: - import unittest2 as unittest -except (ImportError): - import unittest - -import time - -#from Manager import * -import OpenRTM_aist -import RTC - - - - -class DataListener(OpenRTM_aist.ConnectorDataListenerT): - def __init__(self, mes): - self.mes = mes - def __del__(self): - pass - def __call__(self, info, cdrdata): - print self.mes - -class ConnectorListener(OpenRTM_aist.ConnectorListener): - def __init__(self, mes): - self.mes = mes - def __del__(self): - pass - def __call__(self, info): - print self.mes - - - -class TestDirectPort(unittest.TestCase): - - def setUp(self): - self.manager = OpenRTM_aist.Manager.init(sys.argv) - self.manager.activateManager() - - self._d_in = RTC.TimedLong(RTC.Time(0,0),0) - self._inIn = OpenRTM_aist.InPort("in", self._d_in) - prop = OpenRTM_aist.Properties() - self._inIn.init(prop) - self.inport_obj = self._inIn.getPortRef() - - self._inIn.addConnectorDataListener(OpenRTM_aist.ConnectorDataListenerType.ON_BUFFER_WRITE,DataListener("InPort:ON_BUFFER_WRITE")) - self._inIn.addConnectorDataListener(OpenRTM_aist.ConnectorDataListenerType.ON_BUFFER_FULL,DataListener("InPort:ON_BUFFER_FULL")) - self._inIn.addConnectorDataListener(OpenRTM_aist.ConnectorDataListenerType.ON_BUFFER_WRITE_TIMEOUT,DataListener("InPort:ON_BUFFER_WRITE_TIMEOUT")) - self._inIn.addConnectorDataListener(OpenRTM_aist.ConnectorDataListenerType.ON_BUFFER_OVERWRITE,DataListener("InPort:ON_BUFFER_OVERWRITE")) - self._inIn.addConnectorDataListener(OpenRTM_aist.ConnectorDataListenerType.ON_BUFFER_READ,DataListener("InPort:ON_BUFFER_READ")) - self._inIn.addConnectorDataListener(OpenRTM_aist.ConnectorDataListenerType.ON_SEND,DataListener("InPort:ON_SEND")) - self._inIn.addConnectorDataListener(OpenRTM_aist.ConnectorDataListenerType.ON_RECEIVED,DataListener("InPort:ON_RECEIVED")) - self._inIn.addConnectorListener(OpenRTM_aist.ConnectorListenerType.ON_BUFFER_EMPTY,ConnectorListener("InPort:ON_BUFFER_EMPTY")) - self._inIn.addConnectorListener(OpenRTM_aist.ConnectorListenerType.ON_BUFFER_READ_TIMEOUT,ConnectorListener("InPort:ON_BUFFER_READ_TIMEOUT")) - self._inIn.addConnectorListener(OpenRTM_aist.ConnectorListenerType.ON_SENDER_EMPTY,ConnectorListener("InPort:ON_SENDER_EMPTY")) - self._inIn.addConnectorListener(OpenRTM_aist.ConnectorListenerType.ON_SENDER_TIMEOUT,ConnectorListener("InPort:ON_SENDER_TIMEOUT")) - self._inIn.addConnectorListener(OpenRTM_aist.ConnectorListenerType.ON_SENDER_ERROR,ConnectorListener("InPort:ON_SENDER_ERROR")) - self._inIn.addConnectorDataListener(OpenRTM_aist.ConnectorDataListenerType.ON_RECEIVER_FULL,DataListener("InPort:ON_RECEIVER_FULL")) - self._inIn.addConnectorDataListener(OpenRTM_aist.ConnectorDataListenerType.ON_RECEIVER_TIMEOUT,DataListener("InPort:ON_RECEIVER_TIMEOUT")) - self._inIn.addConnectorDataListener(OpenRTM_aist.ConnectorDataListenerType.ON_RECEIVER_ERROR,DataListener("InPort:ON_RECEIVER_ERROR")) - - - self._d_out = RTC.TimedLong(RTC.Time(0,0),0) - self._outOut = OpenRTM_aist.OutPort("out", self._d_out) - prop = OpenRTM_aist.Properties() - self._outOut.init(prop) - self.outport_obj = self._outOut.getPortRef() - - self._outOut.addConnectorDataListener(OpenRTM_aist.ConnectorDataListenerType.ON_BUFFER_WRITE,DataListener("OutPort:ON_BUFFER_WRITE")) - self._outOut.addConnectorDataListener(OpenRTM_aist.ConnectorDataListenerType.ON_BUFFER_FULL,DataListener("OutPort:ON_BUFFER_FULL")) - self._outOut.addConnectorDataListener(OpenRTM_aist.ConnectorDataListenerType.ON_BUFFER_WRITE_TIMEOUT,DataListener("OutPort:ON_BUFFER_WRITE_TIMEOUT")) - self._outOut.addConnectorDataListener(OpenRTM_aist.ConnectorDataListenerType.ON_BUFFER_OVERWRITE,DataListener("OutPort:ON_BUFFER_OVERWRITE")) - self._outOut.addConnectorDataListener(OpenRTM_aist.ConnectorDataListenerType.ON_BUFFER_READ,DataListener("OutPort:ON_BUFFER_READ")) - self._outOut.addConnectorDataListener(OpenRTM_aist.ConnectorDataListenerType.ON_SEND,DataListener("OutPort:ON_SEND")) - self._outOut.addConnectorDataListener(OpenRTM_aist.ConnectorDataListenerType.ON_RECEIVED,DataListener("OutPort:ON_RECEIVED")) - self._outOut.addConnectorListener(OpenRTM_aist.ConnectorListenerType.ON_BUFFER_EMPTY,ConnectorListener("OutPort:ON_BUFFER_EMPTY")) - self._outOut.addConnectorListener(OpenRTM_aist.ConnectorListenerType.ON_BUFFER_READ_TIMEOUT,ConnectorListener("OutPort:ON_BUFFER_READ_TIMEOUT")) - self._outOut.addConnectorListener(OpenRTM_aist.ConnectorListenerType.ON_SENDER_EMPTY,ConnectorListener("OutPort:ON_SENDER_EMPTY")) - self._outOut.addConnectorListener(OpenRTM_aist.ConnectorListenerType.ON_SENDER_TIMEOUT,ConnectorListener("OutPort:ON_SENDER_TIMEOUT")) - self._outOut.addConnectorListener(OpenRTM_aist.ConnectorListenerType.ON_SENDER_ERROR,ConnectorListener("OutPort:ON_SENDER_ERROR")) - self._outOut.addConnectorDataListener(OpenRTM_aist.ConnectorDataListenerType.ON_RECEIVER_FULL,DataListener("OutPort:ON_RECEIVER_FULL")) - self._outOut.addConnectorDataListener(OpenRTM_aist.ConnectorDataListenerType.ON_RECEIVER_TIMEOUT,DataListener("OutPort:ON_RECEIVER_TIMEOUT")) - self._outOut.addConnectorDataListener(OpenRTM_aist.ConnectorDataListenerType.ON_RECEIVER_ERROR,DataListener("OutPort:ON_RECEIVER_ERROR")) - - - def tearDown(self): - self.manager.shutdownManager() - - def test_Push(self): - print "Push" - prop = OpenRTM_aist.Properties() - prop.setProperty("dataport.interface_type","direct") - prop.setProperty("dataport.dataflow_type","push") - ret = OpenRTM_aist.connect("con1",prop,self.inport_obj,self.outport_obj) - - self._d_out.data = 100 - #for i in range(10): - #self._outOut.write() - self._outOut.write() - - ret = self._inIn.isNew() - self.assertTrue(ret) - - data = self._inIn.read() - self.assertEqual(data.data, 100) - self.assertTrue(data is self._d_out) - - self.outport_obj.disconnect_all() - - - - def test_Pull(self): - print "Pull" - prop = OpenRTM_aist.Properties() - prop.setProperty("dataport.interface_type","direct") - prop.setProperty("dataport.dataflow_type","pull") - ret = OpenRTM_aist.connect("con1",prop,self.inport_obj,self.outport_obj) - - self._d_out.data = 100 - self._outOut.write() - - #ret = self._inIn.isNew() - #self.assertTrue(ret) - - data = self._inIn.read() - self.assertEqual(data.data, 100) - self.assertTrue(data is self._d_out) - - self.outport_obj.disconnect_all() - -############### test ################# -if __name__ == '__main__': - unittest.main() diff --git a/OpenRTM_aist/test/test_DirectServicePort.py b/OpenRTM_aist/test/test_DirectServicePort.py deleted file mode 100644 index ef528a31..00000000 --- a/OpenRTM_aist/test/test_DirectServicePort.py +++ /dev/null @@ -1,86 +0,0 @@ -#!/usr/bin/env python -# -*- coding: euc-jp -*- - -# -# \file test_DirectServicePort.py -# \brief -# \date $Date: $ -# \author Nobuhiko Miyamoto -# - - -import sys -sys.path.insert(1,"../") - -try: - import unittest2 as unittest -except (ImportError): - import unittest - -import time - -#from Manager import * -import OpenRTM_aist -import RTC, RTC__POA -import OpenRTM, OpenRTM__POA - - - -class Test_i(OpenRTM__POA.InPortCdr): - def __init__(self): - pass - def put(self, data): - return OpenRTM.PORT_OK - - - - - - - -class TestDirectServicePort(unittest.TestCase): - - def setUp(self): - self.manager = OpenRTM_aist.Manager.init(sys.argv) - #self.manager.setModuleInitProc(MyModuleInit) - self.manager.activateManager() - self._servicePort_provided = OpenRTM_aist.CorbaPort("service") - self._testService_provided = Test_i() - - self._servicePort_required = OpenRTM_aist.CorbaPort("service") - self._testService_required = OpenRTM_aist.CorbaConsumer(interfaceType=OpenRTM.InPortCdr) - - - self._servicePort_provided.registerProvider("service", "TestService", self._testService_provided) - - - self._servicePort_required.registerConsumer("service", "TestService", self._testService_required) - - - self._servicePort_provided.activateInterfaces() - - def tearDown(self): - self.manager.shutdownManager() - time.sleep(0.1) - - - - def test_Service(self): - - - - - prop = OpenRTM_aist.Properties() - ret = OpenRTM_aist.connect("con1",prop,self._servicePort_provided.getPortRef(),self._servicePort_required.getPortRef()) - obj = self._testService_required._ptr() - - self.assertEqual(obj, self._testService_provided) - - - - - - -############### test ################# -if __name__ == '__main__': - unittest.main() diff --git a/OpenRTM_aist/test/test_ECFactory.py b/OpenRTM_aist/test/test_ECFactory.py deleted file mode 100755 index f614d782..00000000 --- a/OpenRTM_aist/test/test_ECFactory.py +++ /dev/null @@ -1,58 +0,0 @@ -#!/usr/bin/env python -# -*- Python -*- -# -# \file test_ECFactory.py -# \brief test for ExecutionContext Factory class -# \date $Date: $ -# \author Shinji Kurihara -# -# Copyright (C) 2007 -# Task-intelligence Research Group, -# Intelligent Systems Research Institute, -# National Institute of -# Advanced Industrial Science and Technology (AIST), Japan -# All rights reserved. -# - - -import sys -sys.path.insert(1,"../") - -import unittest - -from ECFactory import * -import OpenRTM_aist - - -class TestECFactoryPython(unittest.TestCase): - - def setUp(self): - self.ecfact = ECFactoryPython("test", self.create_func, self.del_func) - return - - def tearDown(self): - OpenRTM_aist.Manager.instance().shutdownManager() - del self - return - - def create_func(self): - print "create_func" - - def del_func(self, ec): - print "del_func" - - def test_name(self): - name = self.ecfact.name() - self.assertEqual(name,"test", "name is false.") - - def test_create(self): - self.ecfact.create() - - - def test_destroy(self): - self.ecfact.destroy("hoge") - -############### test ################# -if __name__ == '__main__': - unittest.main() - diff --git a/OpenRTM_aist/test/test_ExecutionContextBase.py b/OpenRTM_aist/test/test_ExecutionContextBase.py deleted file mode 100644 index b8eb301b..00000000 --- a/OpenRTM_aist/test/test_ExecutionContextBase.py +++ /dev/null @@ -1,321 +0,0 @@ -#!/usr/bin/env python -# -*- coding: euc-jp -*- - -## -# @file test_ExecutionContextBase.py -# @brief test for ExecutionContext base class -# @date $Date: 2007/08/31$ -# @author Shinji Kurihara -# -# Copyright (C) 2011 -# Task-intelligence Research Group, -# Intelligent Systems Research Institute, -# National Institute of -# Advanced Industrial Science and Technology (AIST), Japan -# All rights reserved. - -import sys -sys.path.insert(1,"../") -sys.path.insert(1,"../RTM_IDL") - -import time -import unittest - -from ExecutionContextBase import * -import OpenRTM__POA, RTC__POA, RTC -import OpenRTM_aist - -testcomp_spec = ["implementation_id", "TestComp", - "type_name", "TestComp", - "description", "Test example component", - "version", "1.0", - "vendor", "Shinji Kurihara, AIST", - "category", "example", - "activity_type", "DataFlowComponent", - "max_instance", "10", - "language", "Python", - "lang_type", "compile", - ""] - -class TestComp(OpenRTM_aist.DataFlowComponentBase): - def __init_(self, manager): - OpenRTM_aist.DataFlowComponentBase.__init__(self, manager) - - -def TestCompInit(manager): - global com - profile = OpenRTM_aist.Properties(defaults_str=configsample_spec) - manager.registerFactory(profile, - TestComp, - OpenRTM_aist.Delete) - - -class MyEC(OpenRTM__POA.ExtTrigExecutionContextService): - def __init__(self): - self._ref = self._this() - return - - -class MyEC2(ExecutionContextBase): - def __init__(self, name): - ExecutionContextBase.__init__(self, name) - return - - def onStarting(self): - return RTC.RTC_OK - - def onStarted(self): - return RTC.RTC_OK - - def onGetRate(self, rate): - return rate - - -class MyEC3(ExecutionContextBase, - RTC__POA.ExecutionContextService, - OpenRTM_aist.Task): - - def __init__(self, name): - ExecutionContextBase.__init__(self, name) - OpenRTM_aist.Task.__init__(self) - self.setObjRef(self._this()) - self._svc = False - return - - def __del__(self, Task=OpenRTM_aist.Task): - self._svc = False - return - - def start(self): - return ExecutionContextBase.start(self) - - def stop(self): - self._svc = False - return - - def open(self, *args): - self.activate() - return 0 - - def onStarting(self): - self._svc = True - self.open(0) - return RTC.RTC_OK - - - def svc(self): - while self._svc: - ExecutionContextBase.invokeWorkerPreDo(self) - ExecutionContextBase.invokeWorkerDo(self) - ExecutionContextBase.invokeWorkerPostDo(self) - - return 0 - - def onGetRate(self, rate): - return rate - - -class TestExecutioncontextBase(unittest.TestCase): - def setUp(self): - self.ecbase = ExecutionContextBase("test") - - def tearDown(self): - OpenRTM_aist.Manager.instance().shutdownManager() - return - - def test_init(self): - default_conf = ["sync_transition", "YES", - "sync_activation", "YES", - "sync_deactivation", "YES", - "sync_reset", "YES", - "transition_timeout", "0.5", - "activation_timeout", "0.5", - "deactivation_timeout", "0.5", - "reset_timeout", "0.5", - ""] - - prop_ = OpenRTM_aist.Properties(defaults_str=default_conf) - self.ecbase.init(prop_) - return - - def test_bindComponent(self): - mgr_ = OpenRTM_aist.Manager.instance() - mgr_.activateManager() - profile = OpenRTM_aist.Properties(defaults_str=testcomp_spec) - - mgr_.registerFactory(profile, - TestComp, - OpenRTM_aist.Delete) - - comp = mgr_.createComponent("TestComp") - ec_ = MyEC() - self.ecbase.setObjRef(ec_._ref) - self.assertEqual(RTC.RTC_OK, self.ecbase.bindComponent(comp)) - return - - def test_isRunning(self): - ecbase = MyEC2("test ec") - self.assertEqual(False, ecbase.isRunning()) - self.assertEqual(RTC.RTC_OK, ecbase.start()) - self.assertEqual(True, ecbase.isRunning()) - self.assertEqual(RTC.RTC_OK, ecbase.stop()) - self.assertEqual(False, ecbase.isRunning()) - return - - def test_getRate(self): - # default rate in DefaltConfig: 1000 - # default rate in ExecutionContextProfile.__init__ : 1000000.0 - self.assertEqual(1000000.0, self.ecbase.getRate()) - self.assertEqual(RTC.RTC_OK, self.ecbase.setRate(1000.0)) - self.assertEqual(1000.0, self.ecbase.getRate()) - self.assertEqual(0.001, self.ecbase.getPeriod().toDouble()) - return - - def test_addRemoveComponent(self): - mgr_ = OpenRTM_aist.Manager.instance() - mgr_.activateManager() - profile = OpenRTM_aist.Properties(defaults_str=testcomp_spec) - - mgr_.registerFactory(profile, - TestComp, - OpenRTM_aist.Delete) - - comp = mgr_.createComponent("TestComp") - ec_ = MyEC() - self.ecbase.setObjRef(ec_._ref) - self.assertEqual(ec_._ref, self.ecbase.getObjRef()) - ret = comp.getObjRef()._is_equivalent(comp.getObjRef()) - self.assertEqual(RTC.RTC_OK, self.ecbase.addComponent(comp.getObjRef())) - self.ecbase.invokeWorker() - self.assertEqual(RTC.BAD_PARAMETER, self.ecbase.removeComponent(None)) - self.assertEqual(RTC.RTC_OK, self.ecbase.removeComponent(comp.getObjRef())) - return - - def test_actDeactResetComponent(self): - mgr_ = OpenRTM_aist.Manager.instance() - mgr_.activateManager() - profile = OpenRTM_aist.Properties(defaults_str=testcomp_spec) - - mgr_.registerFactory(profile, - TestComp, - OpenRTM_aist.Delete) - - comp = mgr_.createComponent("TestComp") - ec_ = MyEC3("test") - self.assertEqual(RTC.RTC_OK, ec_.bindComponent(comp)) - ec_.start() - self.assertEqual(RTC.RTC_OK, ec_.activateComponent(comp.getObjRef())) - self.assertEqual(RTC.ACTIVE_STATE, ec_.getComponentState(comp.getObjRef())) - self.assertEqual(RTC.ACTIVE_STATE, ec_.getComponentState(comp.getObjRef())) - time.sleep(0.1) - self.assertEqual(RTC.RTC_OK, ec_.deactivateComponent(comp.getObjRef())) - self.assertEqual(RTC.INACTIVE_STATE, ec_.getComponentState(comp.getObjRef())) - rtobj_ = [None] - ec_._worker.activateComponent(comp.getObjRef(),rtobj_) - ec_.waitForActivated(rtobj_[0]) - rtobj_[0].goTo(RTC.ERROR_STATE) - time.sleep(0.1) - self.assertEqual(RTC.ERROR_STATE, ec_.getComponentState(comp.getObjRef())) - self.assertEqual(RTC.RTC_OK, ec_.resetComponent(comp.getObjRef())) - self.assertEqual(RTC.INACTIVE_STATE, ec_.getComponentState(comp.getObjRef())) - ec_.stop() - return - - def test_getStateString(self): - self.assertEqual("CREATED_STATE", self.ecbase.getStateString(RTC.CREATED_STATE)) - self.assertEqual("INACTIVE_STATE", self.ecbase.getStateString(RTC.INACTIVE_STATE)) - self.assertEqual("ACTIVE_STATE", self.ecbase.getStateString(RTC.ACTIVE_STATE)) - self.assertEqual("ERROR_STATE", self.ecbase.getStateString(RTC.ERROR_STATE)) - return - - def test_getKind(self): - self.assertEqual(RTC.PERIODIC, self.ecbase.getKind()) - self.assertEqual(RTC.RTC_OK, self.ecbase.setKind(RTC.PERIODIC)) - self.assertEqual(RTC.PERIODIC, self.ecbase.getKind()) - self.assertEqual(RTC.RTC_OK, self.ecbase.setKind(RTC.EVENT_DRIVEN)) - self.assertEqual(RTC.EVENT_DRIVEN, self.ecbase.getKind()) - self.assertEqual(RTC.RTC_OK, self.ecbase.setKind(RTC.OTHER)) - self.assertEqual(RTC.OTHER, self.ecbase.getKind()) - self.assertEqual("PERIODIC", self.ecbase.getKindString(RTC.PERIODIC)) - self.assertEqual("EVENT_DRIVEN", self.ecbase.getKindString(RTC.EVENT_DRIVEN)) - self.assertEqual("OTHER", self.ecbase.getKindString(RTC.OTHER)) - return - - def test_getSetProfile(self): - self.assertEqual(RTC.PERIODIC, self.ecbase.getProfile().kind) - self.assertEqual(1000000.0, self.ecbase.getProfile().rate) - self.assertEqual(RTC.RTC_OK, self.ecbase.setKind(RTC.EVENT_DRIVEN)) - self.assertEqual(RTC.RTC_OK, self.ecbase.setRate(1000)) - self.assertEqual(RTC.EVENT_DRIVEN, self.ecbase.getProfile().kind) - self.assertEqual(1000.0, self.ecbase.getProfile().rate) - return - - def test_setOwner(self): - mgr_ = OpenRTM_aist.Manager.instance() - mgr_.activateManager() - profile = OpenRTM_aist.Properties(defaults_str=testcomp_spec) - - mgr_.registerFactory(profile, - TestComp, - OpenRTM_aist.Delete) - - comp = mgr_.createComponent("TestComp") - self.ecbase.setOwner(comp.getObjRef()) - self.assertEqual(comp.getObjRef(), self.ecbase.getOwner()) - return - - def test_getComponentList(self): - mgr_ = OpenRTM_aist.Manager.instance() - mgr_.activateManager() - profile = OpenRTM_aist.Properties(defaults_str=testcomp_spec) - - mgr_.registerFactory(profile, - TestComp, - OpenRTM_aist.Delete) - - comp = mgr_.createComponent("TestComp") - ec_ = MyEC() - self.ecbase.setObjRef(ec_._ref) - self.assertEqual(ec_._ref, self.ecbase.getObjRef()) - ret = comp.getObjRef()._is_equivalent(comp.getObjRef()) - self.assertEqual(RTC.RTC_OK, self.ecbase.addComponent(comp.getObjRef())) - self.assertEqual(1, len(self.ecbase.getComponentList())) - return - - def test_setProperties(self): - prop_ = OpenRTM_aist.Properties() - prop_.setProperty("rate", 10) - prop_.setProperty("kind", RTC.PERIODIC) - self.ecbase.setProperties(prop_) - self.assertEqual("10", self.ecbase.getProperties().getProperty("rate")) - self.assertEqual("PERIODIC", self.ecbase.getProperties().getProperty("kind")) - return - - - def test_setExecutionRate(self): - prop_ = OpenRTM_aist.Properties() - prop_.setProperty("rate", 123) - self.assertEqual(True, self.ecbase.setExecutionRate(prop_)) - self.assertEqual(123.0, self.ecbase.getRate()) - return - - def test_setTransitionMode(self): - prop_ = OpenRTM_aist.Properties() - prop_.setProperty("sync_transition", "NO") - ret_ = [True] - self.assertEqual(True, self.ecbase.setTransitionMode(prop_, "sync_transition", ret_)) - self.assertEqual(False, ret_[0]) - return - - def test_setTimeout(self): - prop_ = OpenRTM_aist.Properties() - prop_.setProperty("transition_timeout", 321) - ret_ = [None] - self.assertEqual(True, self.ecbase.setTimeout(prop_, "transition_timeout", ret_)) - self.assertEqual(321.0, ret_[0].toDouble()) - return - - -############### test ################# -if __name__ == '__main__': - unittest.main() diff --git a/OpenRTM_aist/test/test_ExecutionContextProfile.py b/OpenRTM_aist/test/test_ExecutionContextProfile.py deleted file mode 100644 index fc5270f0..00000000 --- a/OpenRTM_aist/test/test_ExecutionContextProfile.py +++ /dev/null @@ -1,165 +0,0 @@ -#!/usr/bin/env python -# -*- coding: euc-jp -*- - -## -# @file test_ExecutionContextProfile.py -# @brief test for ExecutionContextProfile class -# @date $Date$ -# @author Shinji Kurihara -# -# Copyright (C) 2011 -# Noriaki Ando -# Intelligent Systems Research Institute, -# National Institute of -# Advanced Industrial Science and Technology (AIST), Japan -# All rights reserved. -# -# $Id$ -# - -import sys -sys.path.insert(1,"../") -sys.path.insert(1,"../RTM_IDL") - -import unittest - -from ExecutionContextProfile import * -import OpenRTM__POA, RTC -import OpenRTM_aist - - -testcomp_spec = ["implementation_id", "TestComp", - "type_name", "TestComp", - "description", "Test example component", - "version", "1.0", - "vendor", "Shinji Kurihara, AIST", - "category", "example", - "activity_type", "DataFlowComponent", - "max_instance", "10", - "language", "Python", - "lang_type", "compile", - ""] - -class TestComp(OpenRTM_aist.DataFlowComponentBase): - def __init_(self, manager): - OpenRTM_aist.DataFlowComponentBase.__init__(self, manager) - - -def TestCompInit(manager): - global com - profile = OpenRTM_aist.Properties(defaults_str=configsample_spec) - manager.registerFactory(profile, - TestComp, - OpenRTM_aist.Delete) - -class MyEC(OpenRTM__POA.ExtTrigExecutionContextService): - def __init__(self): - self._ref = self._this() - return - -class TestExecutionContextProfile(unittest.TestCase): - - def setUp(self): - self._ecprofile = ExecutionContextProfile() - return - - def tearDown(self): - OpenRTM_aist.Manager.instance().shutdownManager() - return - - def test_setGetObjRef(self): - ec_ = MyEC() - self._ecprofile.setObjRef(ec_._ref) - self.assertEqual(ec_._ref, self._ecprofile.getObjRef()) - return - - def test_setGetRate(self): - self._ecprofile.setRate(1000.0) - self.assertEqual(1000.0, self._ecprofile.getRate()) - return - - def test_setGetPeriod(self): - self.assertEqual(RTC.RTC_OK, self._ecprofile.setPeriod(0.1)) - self.assertEqual(RTC.BAD_PARAMETER, self._ecprofile.setPeriod(-0.1)) - self.assertEqual(0.1, self._ecprofile.getPeriod().toDouble()) - tv_ = OpenRTM_aist.TimeValue(-0.01) - self.assertEqual(RTC.BAD_PARAMETER, self._ecprofile.setPeriod(tv=tv_)) - tv_ = OpenRTM_aist.TimeValue(0.01) - self.assertEqual(RTC.RTC_OK, self._ecprofile.setPeriod(tv=tv_)) - self.assertEqual(0.01, self._ecprofile.getPeriod().toDouble()) - self.assertEqual(RTC.BAD_PARAMETER, self._ecprofile.setPeriod()) - return - - - def test_getKindString(self): - self.assertEqual("PERIODIC", self._ecprofile.getKindString(RTC.PERIODIC)) - self.assertEqual("EVENT_DRIVEN", self._ecprofile.getKindString(RTC.EVENT_DRIVEN)) - self.assertEqual("OTHER", self._ecprofile.getKindString(RTC.OTHER)) - self.assertEqual("", self._ecprofile.getKindString(RTC.UNSUPPORTED)) - return - - def test_setGetKind(self): - self.assertEqual(RTC.RTC_OK, self._ecprofile.setKind(RTC.PERIODIC)) - self.assertEqual(RTC.PERIODIC, self._ecprofile.getKind()) - self.assertEqual(RTC.RTC_OK, self._ecprofile.setKind(RTC.PERIODIC)) - self.assertEqual("EVENT_DRIVEN", self._ecprofile.getKindString(RTC.EVENT_DRIVEN)) - self.assertEqual("OTHER", self._ecprofile.getKindString(RTC.OTHER)) - self.assertEqual("", self._ecprofile.getKindString(RTC.UNSUPPORTED)) - return - - def test_setOwner(self): - mgr_ = OpenRTM_aist.Manager.instance() - mgr_.activateManager() - profile = OpenRTM_aist.Properties(defaults_str=testcomp_spec) - - mgr_.registerFactory(profile, - TestComp, - OpenRTM_aist.Delete) - - comp = mgr_.createComponent("TestComp") - self.assertEqual(RTC.RTC_OK, self._ecprofile.setOwner(comp.getObjRef())) - self.assertEqual(comp.getObjRef(), self._ecprofile.getOwner()) - return - - def test_addRemoveComponent(self): - mgr_ = OpenRTM_aist.Manager.instance() - mgr_.activateManager() - profile = OpenRTM_aist.Properties(defaults_str=testcomp_spec) - - mgr_.registerFactory(profile, - TestComp, - OpenRTM_aist.Delete) - - comp = mgr_.createComponent("TestComp") - self.assertEqual(0, len(self._ecprofile.getComponentList())) - self.assertEqual(RTC.RTC_OK, self._ecprofile.addComponent(comp.getObjRef())) - self.assertEqual(RTC.BAD_PARAMETER, self._ecprofile.addComponent(None)) - self.assertEqual(RTC.BAD_PARAMETER, self._ecprofile.removeComponent(None)) - self.assertEqual(RTC.RTC_OK, self._ecprofile.removeComponent(comp.getObjRef())) - self.assertEqual(0, len(self._ecprofile.getComponentList())) - self.assertEqual(RTC.RTC_OK, self._ecprofile.addComponent(comp.getObjRef())) - self.assertEqual(RTC.RTC_OK, self._ecprofile.addComponent(comp.getObjRef())) - self.assertEqual(2, len(self._ecprofile.getComponentList())) - return - - - def test_setGetProperties(self): - prop_ = OpenRTM_aist.Properties() - prop_.setProperty("test", "test value") - self._ecprofile.setProperties(prop_) - self.assertEqual("test value", self._ecprofile.getProperties().getProperty("test")) - prop_ = OpenRTM_aist.Properties() - val_ = OpenRTM_aist.NVUtil.copyToProperties(prop_, self._ecprofile.getProfile().properties) - self.assertEqual("test value", prop_.getProperty("test")) - return - - - def test_lock_unlock(self): - self._ecprofile.lock() - self._ecprofile.unlock() - return - - -############### test ################# -if __name__ == '__main__': - unittest.main() diff --git a/OpenRTM_aist/test/test_ExecutionContextWorker.py b/OpenRTM_aist/test/test_ExecutionContextWorker.py deleted file mode 100644 index 32a305a8..00000000 --- a/OpenRTM_aist/test/test_ExecutionContextWorker.py +++ /dev/null @@ -1,242 +0,0 @@ -#!/usr/bin/env python -# -*- coding: euc-jp -*- - -## -# @file test_ExecutionContextWorker.py -# @brief test for ExecutionContext's state machine worker class -# @date $Date$ -# @author Shinji Kurihara -# -# Copyright (C) 2011 -# Noriaki Ando -# Intelligent Systems Research Institute, -# National Institute of -# Advanced Industrial Science and Technology (AIST), Japan -# All rights reserved. -# -# $Id$ -# - -import sys -sys.path.insert(1,"../") -sys.path.insert(1,"../RTM_IDL") - -import time -import unittest - -from ExecutionContextWorker import * -import OpenRTM__POA, RTC__POA, RTC -import OpenRTM_aist - -testcomp_spec = ["implementation_id", "TestComp", - "type_name", "TestComp", - "description", "Test example component", - "version", "1.0", - "vendor", "Shinji Kurihara, AIST", - "category", "example", - "activity_type", "DataFlowComponent", - "max_instance", "10", - "language", "Python", - "lang_type", "compile", - ""] - -class TestComp(OpenRTM_aist.DataFlowComponentBase): - def __init_(self, manager): - OpenRTM_aist.DataFlowComponentBase.__init__(self, manager) - - -def TestCompInit(manager): - global com - profile = OpenRTM_aist.Properties(defaults_str=configsample_spec) - manager.registerFactory(profile, - TestComp, - OpenRTM_aist.Delete) - - -class MyEC(OpenRTM__POA.ExtTrigExecutionContextService): - def __init__(self): - self._ref = self._this() - return - -class MyEC3(OpenRTM_aist.ExecutionContextBase, - RTC__POA.ExecutionContextService, - OpenRTM_aist.Task): - - def __init__(self, name): - OpenRTM_aist.ExecutionContextBase.__init__(self, name) - OpenRTM_aist.Task.__init__(self) - self.setObjRef(self._this()) - self._svc = False - return - - def __del__(self, Task=OpenRTM_aist.Task): - self._svc = False - return - - def start(self): - return OpenRTM_aist.ExecutionContextBase.start(self) - - def stop(self): - self._svc = False - return - - def open(self, *args): - self.activate() - return 0 - - def onStarting(self): - self._svc = True - self.open(0) - return RTC.RTC_OK - - - def svc(self): - while self._svc: - OpenRTM_aist.ExecutionContextBase.invokeWorkerPreDo(self) - OpenRTM_aist.ExecutionContextBase.invokeWorkerDo(self) - OpenRTM_aist.ExecutionContextBase.invokeWorkerPostDo(self) - - return 0 - - def onGetRate(self, rate): - return rate - -class TestExecutionContextWorker(unittest.TestCase): - - def setUp(self): - self._ecworker = ExecutionContextWorker() - - def tearDown(self): - OpenRTM_aist.Manager.instance().shutdownManager() - return - - def test_setGetECRef(self): - ec_ = MyEC() - ref_ = ec_._ref - self._ecworker.setECRef(ref_) - self.assertEqual(ref_,self._ecworker.getECRef()) - - return - - - def test_startStopIsRunning(self): - self.assertEqual(RTC.RTC_OK, self._ecworker.start()) - self.assertEqual(RTC.PRECONDITION_NOT_MET, self._ecworker.start()) - self.assertEqual(True, self._ecworker.isRunning()) - self.assertEqual(RTC.RTC_OK, self._ecworker.stop()) - self.assertEqual(False, self._ecworker.isRunning()) - self.assertEqual(RTC.PRECONDITION_NOT_MET, self._ecworker.stop()) - return - - def test_actDeactResetState(self): - mgr_ = OpenRTM_aist.Manager.instance() - mgr_.activateManager() - profile = OpenRTM_aist.Properties(defaults_str=testcomp_spec) - mgr_.registerFactory(profile, - TestComp, - OpenRTM_aist.Delete) - comp = mgr_.createComponent("TestComp") - ec_ = MyEC3("test") - self._ecworker.setECRef(ec_._this()) - self.assertEqual(RTC.RTC_OK,self._ecworker.bindComponent(comp)) - self._ecworker.start() - rtobj_ = [None] - - # INACTIVE -> ACTIVE - self.assertEqual(RTC.RTC_OK, self._ecworker.activateComponent(comp.getObjRef(),rtobj_)) - self.assertEqual(False, self._ecworker.isAllCurrentState(RTC.ACTIVE_STATE)) - self.assertEqual(True, self._ecworker.isAllNextState(RTC.ACTIVE_STATE)) - self.assertEqual(False, self._ecworker.isOneOfCurrentState(RTC.ACTIVE_STATE)) - self._ecworker.invokeWorker() - self.assertEqual(RTC.ACTIVE_STATE, self._ecworker.getComponentState(comp.getObjRef())) - self.assertEqual(True, self._ecworker.isAllCurrentState(RTC.ACTIVE_STATE)) - self.assertEqual(True, self._ecworker.isOneOfCurrentState(RTC.ACTIVE_STATE)) - - # ACTIVE -> INACTIVE - self.assertEqual(RTC.RTC_OK, self._ecworker.deactivateComponent(comp.getObjRef(),rtobj_)) - self.assertEqual(False, self._ecworker.isAllCurrentState(RTC.INACTIVE_STATE)) - self.assertEqual(True, self._ecworker.isOneOfNextState(RTC.INACTIVE_STATE)) - self.assertEqual(True, self._ecworker.isAllNextState(RTC.INACTIVE_STATE)) - self._ecworker.invokeWorker() - self.assertEqual(RTC.INACTIVE_STATE, self._ecworker.getComponentState(comp.getObjRef())) - self.assertEqual(True, self._ecworker.isAllCurrentState(RTC.INACTIVE_STATE)) - - # INACTIVE -> ACTIVE -> ERROR - self.assertEqual(RTC.RTC_OK, self._ecworker.activateComponent(comp.getObjRef(),rtobj_)) - self._ecworker.invokeWorker() - rtobj_[0] = self._ecworker.findComponent(comp.getObjRef()) - rtobj_[0].goTo(RTC.ERROR_STATE) - self.assertEqual(True, self._ecworker.isOneOfNextState(RTC.ERROR_STATE)) - self._ecworker.invokeWorker() - self.assertEqual(RTC.ERROR_STATE, self._ecworker.getComponentState(comp.getObjRef())) - - # ERROR -> INACTIVE - self.assertEqual(RTC.RTC_OK, self._ecworker.resetComponent(comp.getObjRef(),rtobj_)) - self._ecworker.invokeWorker() - self.assertEqual(RTC.INACTIVE_STATE, self._ecworker.getComponentState(comp.getObjRef())) - self.assertEqual(True, self._ecworker.isAllCurrentState(RTC.INACTIVE_STATE)) - self._ecworker.stop() - return - - def waitActivateComplete(self): - # No implementation. - return - - def waitDeactivateComplete(self): - # No implementation. - return - - def waitResetComplete(self): - # No implementation. - return - - def test_getStateString(self): - self.assertEqual("CREATED_STATE", self._ecworker.getStateString(RTC.CREATED_STATE)) - self.assertEqual("INACTIVE_STATE", self._ecworker.getStateString(RTC.INACTIVE_STATE)) - self.assertEqual("ACTIVE_STATE", self._ecworker.getStateString(RTC.ACTIVE_STATE)) - self.assertEqual("ERROR_STATE", self._ecworker.getStateString(RTC.ERROR_STATE)) - return - - def test_addRemoveComponent(self): - mgr_ = OpenRTM_aist.Manager.instance() - mgr_.activateManager() - profile = OpenRTM_aist.Properties(defaults_str=testcomp_spec) - - mgr_.registerFactory(profile, - TestComp, - OpenRTM_aist.Delete) - - comp = mgr_.createComponent("TestComp") - ec_ = MyEC() - self._ecworker.setECRef(ec_._ref) - self.assertEqual(RTC.RTC_OK, self._ecworker.addComponent(comp.getObjRef())) - self._ecworker.invokeWorker() - self.assertEqual(RTC.BAD_PARAMETER, self._ecworker.removeComponent(None)) - self.assertEqual(RTC.RTC_OK, self._ecworker.removeComponent(comp.getObjRef())) - return - - def test_invokeWorker(self): - mgr_ = OpenRTM_aist.Manager.instance() - mgr_.activateManager() - profile = OpenRTM_aist.Properties(defaults_str=testcomp_spec) - - mgr_.registerFactory(profile, - TestComp, - OpenRTM_aist.Delete) - - comp = mgr_.createComponent("TestComp") - ec_ = MyEC() - self._ecworker.setECRef(ec_._ref) - self.assertEqual(RTC.RTC_OK, self._ecworker.addComponent(comp.getObjRef())) - self._ecworker.invokeWorkerPreDo() - self._ecworker.invokeWorkerDo() - self._ecworker.invokeWorkerPostDo() - self._ecworker.updateComponentList() - self.assertEqual(RTC.BAD_PARAMETER, self._ecworker.removeComponent(None)) - self.assertEqual(RTC.RTC_OK, self._ecworker.removeComponent(comp.getObjRef())) - return - - -############### test ################# -if __name__ == '__main__': - unittest.main() diff --git a/OpenRTM_aist/test/test_ExtTrigExecutionContext.py b/OpenRTM_aist/test/test_ExtTrigExecutionContext.py deleted file mode 100755 index e834714f..00000000 --- a/OpenRTM_aist/test/test_ExtTrigExecutionContext.py +++ /dev/null @@ -1,87 +0,0 @@ -#!/usr/bin/env python -# -*- Python -*- - -# -# \file test_ExtTrigExecutionContext.py -# \brief ExtTrigExecutionContext class -# \date $Date: 2007/09/06$ -# \author Shinji Kurihara -# -# Copyright (C) 2007 -# Task-intelligence Research Group, -# Intelligent Systems Research Institute, -# National Institute of -# Advanced Industrial Science and Technology (AIST), Japan -# All rights reserved. -# - -import sys -sys.path.insert(1,"../") -import threading - -import unittest -import OpenRTM_aist -import RTC, RTC__POA - -from ExtTrigExecutionContext import * - -from omniORB import CORBA, PortableServer - -class DFP(OpenRTM_aist.RTObject_impl): - def __init__(self): - self._orb = CORBA.ORB_init() - self._poa = self._orb.resolve_initial_references("RootPOA") - OpenRTM_aist.RTObject_impl.__init__(self, orb=self._orb, poa=self._poa) - self._error = False - self._ref = self._this() - self._eclist = [] - - def on_execute(self, ec_id): - return RTC.RTC_OK - -class TestExtTrigExecutionContext(unittest.TestCase): - def setUp(self): - self._dfp = DFP() - self._dfp._poa._get_the_POAManager().activate() - self.etec = ExtTrigExecutionContext() - #self.etec = ExtTrigExecutionContext(self._dfp._ref) - return - - def tearDown(self): - OpenRTM_aist.Manager.instance().shutdownManager() - return - - def test_tick(self): - pass - - def test_run(self): - self.assertEqual(self.etec.start(),RTC.RTC_OK) - self.assertEqual(self.etec.add_component(self._dfp._this()),RTC.RTC_OK) - self.etec.start() - self.etec.invokeWorker() - self.assertEqual(self.etec.activate_component(self._dfp._this()),RTC.RTC_OK) - import time - time.sleep(1) - self.etec.tick() - self.etec.tick() - time.sleep(1) - self.assertEqual(self.etec.deactivate_component(self._dfp._this()),RTC.RTC_OK) - time.sleep(1) - self.assertEqual(self.etec.remove_component(self._dfp._this()),RTC.RTC_OK) - th = threading.Thread(target=self.stop) - th.start() - self.etec.tick() - if th: - th.join() - self._dfp._poa.deactivate_object(self._dfp._poa.servant_to_id(self.etec)) - self._dfp._poa.deactivate_object(self._dfp._poa.servant_to_id(self._dfp)) - self.etec.stop() - return - - def stop(self): - self.etec.stop() - return - -############### test ################# -if __name__ == '__main__': - unittest.main() diff --git a/OpenRTM_aist/test/test_Factory.py b/OpenRTM_aist/test/test_Factory.py deleted file mode 100755 index 9d5c62f8..00000000 --- a/OpenRTM_aist/test/test_Factory.py +++ /dev/null @@ -1,56 +0,0 @@ -#!/usr/bin/env python -# -*- Python -*- - -# -# \file test_Factory.py -# \brief test for RTComponent factory class -# \date $Date: $ -# \author Shinji Kurihara -# -# Copyright (C) 2003-2005 -# Task-intelligence Research Group, -# Intelligent Systems Research Institute, -# National Institute of -# Advanced Industrial Science and Technology (AIST), Japan -# All rights reserved. -# - -import sys -sys.path.insert(1,"../") - -import OpenRTM_aist -import unittest - -from Factory import * - -class testClass: - def __init__(self,mgr): - self.test(mgr) - pass - - def test(self,mgr): - print "testClass: ", mgr - -class TestFactoryPython(unittest.TestCase): - - def setUp(self): - #profile = OpenRTM_aist.Properties() - profile = None - self.factory = FactoryPython(profile, testClass, OpenRTM_aist.Delete) - return - - def tearDown(self): - OpenRTM_aist.Manager.instance().shutdownManager() - del self - return - - def test_create(self): - self.factory.create(3) - self.assertEqual(self.factory.number(), 0) - - def destroy(self): - pass - -############### test ################# -if __name__ == '__main__': - unittest.main() diff --git a/OpenRTM_aist/test/test_FactoryInit.py b/OpenRTM_aist/test/test_FactoryInit.py deleted file mode 100755 index 6331f633..00000000 --- a/OpenRTM_aist/test/test_FactoryInit.py +++ /dev/null @@ -1,39 +0,0 @@ -#!/usr/bin/env python -# -*- Python -*- - -# -# \file test_FactoryInit.py -# \brief test for RTComponent factory class -# \date $Date: $ -# \author Shinji Kurihara -# -# Copyright (C) 2003-2005 -# Task-intelligence Research Group, -# Intelligent Systems Research Institute, -# National Institute of -# Advanced Industrial Science and Technology (AIST), Japan -# All rights reserved. -# - -import sys -sys.path.insert(1,"../") - -import unittest - -from FactoryInit import * - -class TestFactoryInit(unittest.TestCase): - - def setUp(self): - return - - def tearDown(self): - return - - def test_FactoryInit(self): - FactoryInit() - - -############### test ################# -if __name__ == '__main__': - unittest.main() diff --git a/OpenRTM_aist/test/test_GlobalFactory.py b/OpenRTM_aist/test/test_GlobalFactory.py deleted file mode 100755 index da39b375..00000000 --- a/OpenRTM_aist/test/test_GlobalFactory.py +++ /dev/null @@ -1,152 +0,0 @@ -#!/usr/bin/env python -# -*- coding: euc-jp -*- - -# -# \file test_GlobalFactory.py -# \brief test for RTComponent factory class -# \date $Date: $ -# \author Shinji Kurihara -# -# Copyright (C) 2003-2005 -# Task-intelligence Research Group, -# Intelligent Systems Research Institute, -# National Institute of -# Advanced Industrial Science and Technology (AIST), Japan -# All rights reserved. -# - -import sys -sys.path.insert(1,"../") - -import OpenRTM_aist -import unittest - -from GlobalFactory import * - -class Test: - def __init__(self): - pass - - def test(self): - return True - -class TestGlobalFactory(unittest.TestCase): - - def setUp(self): - self.factory = GlobalFactory.instance() - self.creator = Test - self.destructor = OpenRTM_aist.Delete - self.factory.addFactory("test",self.creator,self.destructor) - return - - def tearDown(self): - self.factory.removeFactory("test") - return - - def test_isinstance(self): - self.assertEqual(self.factory,GlobalFactory.instance()) - - def test_hasFactory(self): - # addFactoryˤϿեȥꥪ֥Ȥ䤤碌 - self.assertEqual(self.factory.hasFactory("test"),True) - # addFactoryˤϿƤʤեȥꥪ֥Ȥ䤤碌 - self.assertEqual(self.factory.hasFactory("testtest"),False) - # addFactoryˤϿƤʤեȥꥪ֥Ȥ䤤碌(ʸ) - self.assertEqual(self.factory.hasFactory(""),False) - return - - def test_getIdentifiers(self): - # եȥ꤬ϿѤߤξ䤤碌 - self.assertEqual(self.factory.getIdentifiers(),["test"]) - GlobalFactory.instance().addFactory("test2",Test,OpenRTM_aist.Delete) - self.assertEqual(self.factory.getIdentifiers(),["test","test2"]) - # եȥ꤬ϿƤʤ䤤碌 - self.factory.removeFactory("test") - self.factory.removeFactory("test2") - self.assertEqual(self.factory.getIdentifiers(),[]) - return - - def test_addFactory(self): - # creatorꤷʤ硢INVALID_ARG֤뤫? - self.assertEqual(GlobalFactory.instance().addFactory("test",None,OpenRTM_aist.Delete), - GlobalFactory.INVALID_ARG) - - # ϿѤߤIDˤaddFactory()򥳡뤷硢ALREADY_EXISTS֤뤫? - self.assertEqual(GlobalFactory.instance().addFactory("test",Test,OpenRTM_aist.Delete), - GlobalFactory.ALREADY_EXISTS) - - # idcreatorꤷaddFactory()򥳡뤷硢FACTORY_OK֤뤫? - self.assertEqual(GlobalFactory.instance().addFactory("test1",Test,OpenRTM_aist.Delete), - GlobalFactory.FACTORY_OK) - self.factory.removeFactory("test1") - - return - - def test_removeFactory(self): - # ϿƤʤIDǥ뤷硢NOT_FOUND֤뤫? - self.assertEqual(self.factory.removeFactory("testtest"), - GlobalFactory.NOT_FOUND) - - # ϿѤߤIDǥ뤷硢FACTORY_OK֤뤫? - self.assertEqual(self.factory.removeFactory("test"), - GlobalFactory.FACTORY_OK) - - # եȥ꤬줿? - self.assertEqual(self.factory.getIdentifiers(),[]) - return - - def test_createObject(self): - # ϿƤʤIDǥ뤷硢None֤뤫? - self.assertEqual(self.factory.createObject("testtest"), - None) - # ϿѤߤIDǥ뤷硢֥Ȥ֤뤫? - obj = self.factory.createObject("test") - self.assertEqual(obj.test(),True) - self.factory.deleteObject(obj) - return - - def test_deleteObject(self): - # ϿƤʤIDǥ뤷 - self.factory.deleteObject(self.factory.createObject("test"),"testtest") - # IDꤷʤǥ뤷 - self.factory.deleteObject(self.factory.createObject("test")) - return - - def test_createdObjects(self): - self.assertEqual(0, len(self.factory.createdObjects())) - obj = self.factory.createObject("test") - self.assertEqual(obj.test(),True) - self.assertEqual(1, len(self.factory.createdObjects())) - self.factory.deleteObject(obj) - return - - def test_isProducerOf(self): - obj = self.factory.createObject("test") - self.assertEqual(True, self.factory.isProducerOf(obj)) - self.factory.deleteObject(obj) - return - - def test_objectToIdentifier(self): - obj = self.factory.createObject("test") - id_ = [None] - self.assertEqual(Factory.FACTORY_OK, self.factory.objectToIdentifier(obj, id_)) - self.assertEqual("test",id_[0]) - self.factory.deleteObject(obj) - return - - def test_objectToCreator(self): - obj = self.factory.createObject("test") - self.assertEqual(self.creator, self.factory.objectToCreator(obj)) - self.factory.deleteObject(obj) - return - - def test_objectToDestructor(self): - obj = self.factory.createObject("test") - self.assertEqual(self.destructor, self.factory.objectToDestructor(obj)) - self.factory.deleteObject(obj) - return - - -############### test ################# -if __name__ == '__main__': - unittest.main() diff --git a/OpenRTM_aist/test/test_Guard.py b/OpenRTM_aist/test/test_Guard.py deleted file mode 100755 index 8eaf0792..00000000 --- a/OpenRTM_aist/test/test_Guard.py +++ /dev/null @@ -1,71 +0,0 @@ -#!/usr/bin/env python -# -*- Python -*- - -# -# \file test_Guard.py -# \brief test for Guard class -# \date $Date: 2007/09/18 $ -# \author Shinji Kurihara -# -# Copyright (C) 2006 -# Task-intelligence Research Group, -# Intelligent Systems Research Institute, -# National Institute of -# Advanced Industrial Science and Technology (AIST), Japan -# All rights reserved. -# - -import sys, time -sys.path.insert(1,"../") - -import unittest -import threading -from Guard import * -from Task import * - -ShareCount = 0 - -class TestGuardTask(Task): - def __init__(self): - global ShareCount - self.ShareCount = 1 - Task.__init__(self) - self.flag = False - self._mutex = threading.RLock() - - def svc(self): - global ShareCount - guard = ScopedLock(self._mutex) - for i in range(100): - ShareCount += 1 - time.sleep(0.1) - self.ShareCount = ShareCount - return - - def getShareCount(self): - return self.ShareCount - -class TestGuard(unittest.TestCase): - def setUp(self): - return - - def test_case0(self): - task1 = TestGuardTask() - task2 = TestGuardTask() - task1.activate() - task2.activate() - task1.wait() - task2.wait() - count = task1.getShareCount() - self.assertEqual(count, 200) - count = task2.getShareCount() - self.assertEqual(count, 200) - task2.finalize() - task1.finalize() - return - - - -############### test ################# -if __name__ == '__main__': - unittest.main() diff --git a/OpenRTM_aist/test/test_INSRTObject.py b/OpenRTM_aist/test/test_INSRTObject.py deleted file mode 100644 index 7dca44f7..00000000 --- a/OpenRTM_aist/test/test_INSRTObject.py +++ /dev/null @@ -1,99 +0,0 @@ -#!/usr/bin/env python -# -*- coding: euc-jp -*- - -# -# \file test_INSRTObject.py -# \brief -# \date $Date: $ -# \author Nobuhiko Miyamoto -# - - -import sys -sys.path.insert(1,"../") - -try: - import unittest2 as unittest -except (ImportError): - import unittest - -import time - -#from Manager import * -import OpenRTM_aist -import OpenRTM -import RTC, RTC__POA - -testcomp1_spec = ["implementation_id", "TestComp1", - "type_name", "TestComp1", - "description", "Test example component", - "version", "1.0", - "vendor", "Nobuhiko Myiyamoto", - "category", "example", - "activity_type", "DataFlowComponent", - "max_instance", "10", - "language", "C++", - "lang_type", "compile", - "conf.default.test1", "0", - ""] - - - - - - - - -def TestComp1Init(manager): - profile = OpenRTM_aist.Properties(defaults_str=testcomp1_spec) - manager.registerFactory(profile, - OpenRTM_aist.DataFlowComponentBase, - OpenRTM_aist.Delete) - - - - - - -def TestComp1ModuleInit(manager): - TestComp1Init(manager) - com = manager.createComponent("TestComp1") - - - - - - -class test_INSRTObject(unittest.TestCase): - - def setUp(self): - - sys.argv.extend(['-p','2810']) - self.manager = OpenRTM_aist.Manager.init(sys.argv) - self.manager.setModuleInitProc(TestComp1ModuleInit) - self.manager.activateManager() - - - def tearDown(self): - - comps = self.manager.getComponents()[:] - for comp in comps: - self.manager.unregisterComponent(comp) - comp_id = comp.getProperties() - factory = self.manager._factory.find(comp_id) - factory.destroy(comp) - self.manager.shutdownNaming() - time.sleep(0.1) - - def test_getComponent(self): - rtobj = self.manager.getORB().string_to_object("corbaloc:iiop:localhost:2810/example/TestComp10") - rtc = rtobj._narrow(OpenRTM.DataFlowComponent) - name = rtc.get_component_profile().instance_name - self.assertEqual(name, "TestComp10") - - - - -############### test ################# -if __name__ == '__main__': - unittest.main() diff --git a/OpenRTM_aist/test/test_InPort.py b/OpenRTM_aist/test/test_InPort.py deleted file mode 100755 index bbbbd4d1..00000000 --- a/OpenRTM_aist/test/test_InPort.py +++ /dev/null @@ -1,134 +0,0 @@ -#!/usr/bin/env python -# -*- Python -*- - - -# \file test_InPort.py -# \brief test for InPort template class -# \date $Date: 2007/09/20 $ -# \author Shinji Kurihara -# -# Copyright (C) 2003-2005 -# Task-intelligence Research Group, -# Intelligent Systems Research Institute, -# National Institute of -# Advanced Industrial Science and Technology (AIST), Japan -# All rights reserved. - - -import sys -sys.path.insert(1,"../") - -import unittest - -from InPort import * - -import RTC, RTC__POA -import OpenRTM_aist - -ShareCount = 0 - -class OnRWTest: - def __init__(self): - pass - - def echo(self, value=None): - print "OnRW Called" - - -class OnRWConvertTest: - def __init__(self): - pass - - def echo(self, value=None): - print "OnRWConvert Called" - return value - - -class BufferMock: - def __init__(self): - self._ShareCount = 0 - self._data = None - return - - def write(self, data): - global ShareCount - ShareCount += 1 - self._ShareCount = ShareCount - self._data = data - return OpenRTM_aist.BufferStatus.BUFFER_OK - - def read(self, value): - global ShareCount - ShareCount -= 1 - if ShareCount < 0: - ShareCount = 0 - self._ShareCount = ShareCount - if len(value) > 0: - value[0] = self._data - else: - value.append(self._data) - return OpenRTM_aist.BufferStatus.BUFFER_OK - - def readable(self): - return self._ShareCount - - -class ConnectorMock: - def __init__(self, buffer): - self._buffer = buffer - return - - def write(self, data): - self._buffer.write(data) - return OpenRTM_aist.BufferStatus.BUFFER_OK - - def read(self, data): - self._buffer.read(data) - return OpenRTM_aist.DataPortStatus.PORT_OK - - def getBuffer(self): - ret = self._buffer.readable() - return self._buffer - - -class TestInPort(unittest.TestCase): - def setUp(self): - OpenRTM_aist.Manager.instance() - self._buffer = BufferMock() - self._ipn = InPort("in", RTC.TimedLong(RTC.Time(0,0), 0), self._buffer) - self._connector = ConnectorMock(self._buffer) - self._ipn._connectors = [self._connector] - - def tearDown(self): - OpenRTM_aist.Manager.instance().shutdownManager() - return - - def test_name(self): - self.assertEqual(self._ipn.name(), "in") - - def test_read(self): - self.assertEqual(self._ipn.isEmpty(), True) - self.assertEqual(self._ipn.isNew(), False) - self._connector.write(RTC.TimedLong(RTC.Time(0,0), 123)) - self.assertEqual(self._ipn.isEmpty(), False) - self.assertEqual(self._ipn.isNew(), True) - read_data = self._ipn.read() - self.assertEqual(self._ipn.isEmpty(), True) - self.assertEqual(self._ipn.isNew(), False) - self.assertEqual(read_data.data, 123) - self._ipn.update() - return - - def test_OnRead(self): - self._connector.write(RTC.TimedLong(RTC.Time(0,0), 456)) - self._ipn.setOnRead(OnRWTest().echo) - self._ipn.setOnReadConvert(OnRWConvertTest().echo) - read_data = self._ipn.read() - self.assertEqual(read_data.data, 456) - return - - -############### test ################# -if __name__ == '__main__': - unittest.main() - diff --git a/OpenRTM_aist/test/test_InPortBase.py b/OpenRTM_aist/test/test_InPortBase.py deleted file mode 100755 index 89989917..00000000 --- a/OpenRTM_aist/test/test_InPortBase.py +++ /dev/null @@ -1,310 +0,0 @@ -#!/usr/bin/env python -# -*- coding: euc-jp -*- - - -# \file test_InPortBase.py -# \brief test for InPortBase class -# \date $Date: 2007/09/20 $ -# \author Shinji Kurihara -# -# Copyright (C) 2003-2005 -# Task-intelligence Research Group, -# Intelligent Systems Research Institute, -# National Institute of -# Advanced Industrial Science and Technology (AIST), Japan -# All rights reserved. - - -import sys -sys.path.insert(1,"../") - -from omniORB import CORBA, PortableServer -from omniORB import any - -import unittest - -from InPortBase import * - -import RTC, RTC__POA -import OpenRTM_aist - - -class InPortMock(InPortBase): - def __init__(self, name, data_type): - InPortBase.__init__(self, name, data_type) - return - - def getThebuffer(self): - return self._thebuffer - - def getProviderTypes(self): - return self._providerTypes - - def getConsumerTypes(self): - return self._consumerTypes - - def publishInterfaces_public(self, connector_profile): - return self.publishInterfaces(connector_profile) - - - -class TestInPortBase(unittest.TestCase): - def setUp(self): - #mgr=OpenRTM_aist.Manager.instance() - self._orb = CORBA.ORB_init(sys.argv) - self._poa = self._orb.resolve_initial_references("RootPOA") - self._poa._get_the_POAManager().activate() - - self._inport = InPortMock("in", OpenRTM_aist.toTypename(RTC.TimedLong(RTC.Time(0,0), 0))) - self._outport = OpenRTM_aist.OutPort("out",RTC.TimedLong(RTC.Time(0,0), 0)) - profile = self._outport.getPortProfile() - prop = OpenRTM_aist.NVUtil.toProperties(profile.properties) - self._outport.init(prop) - - self._nvlist = [OpenRTM_aist.NVUtil.newNV("dataport.interface_type","corba_cdr"), - OpenRTM_aist.NVUtil.newNV("dataport.dataflow_type","push"), - OpenRTM_aist.NVUtil.newNV("dataport.subscription_type","flush")] - - import time - time.sleep(0.05) - return - - - def tearDown(self): - OpenRTM_aist.Manager.instance().shutdownManager() - return - - def test_properties(self): - self.assertEqual(isinstance(self._inport.properties(),OpenRTM_aist.Properties),True) - return - - def test_init(self): - self.assertEqual(self._inport.getThebuffer(),None) - profile = self._inport.getPortProfile() - prop = OpenRTM_aist.NVUtil.toProperties(profile.properties) - - self.assertEqual(prop.getProperty("dataport.dataflow_type"),"") - self.assertEqual(prop.getProperty("dataport.interface_type"),"") - - pstr = self._inport.getProviderTypes() - self.assertEqual(len(pstr),0) - cstr = self._inport.getConsumerTypes() - self.assertEqual(len(cstr),0) - - self._inport.init(prop) - - # self._singlebufferTrueξself._thebuffer - self.assertNotEqual(self._inport.getThebuffer(),None) - profile = self._inport.getPortProfile() - prop = OpenRTM_aist.NVUtil.toProperties(profile.properties) - - # getPortProfileproperties˰ʲɲä - val = any.from_any(prop.getProperty("dataport.dataflow_type"),keep_structs=True) - self.assertEqual(val,"push, pull") - val = any.from_any(prop.getProperty("dataport.interface_type"),keep_structs=True) - self.assertEqual(val,"corba_cdr") - - # ProviderTypes,ConsumerTypes - pstr = self._inport.getProviderTypes() - self.assertEqual(pstr[0],"corba_cdr") - cstr = self._inport.getConsumerTypes() - self.assertEqual(cstr[0],"corba_cdr") - - return - - def test_activate_deactivateInterfaces(self): - profile = self._inport.getPortProfile() - prop = OpenRTM_aist.NVUtil.toProperties(profile.properties) - self._inport.init(prop) - prof = RTC.ConnectorProfile("InPortBaseTest0", - "id0", - [self._inport.get_port_profile().port_ref], - self._nvlist) - - self._inport.publishInterfaces_public(prof) - prof.connector_id = "id1" - prof.name = "InPortBaseTest1" - self._inport.publishInterfaces_public(prof) - - self._inport.activateInterfaces() - self._inport.deactivateInterfaces() - - - return - - def test_subscribe_unsubscribeInterfaces(self): - profile = self._inport.getPortProfile() - prop = OpenRTM_aist.NVUtil.toProperties(profile.properties) - self._inport.init(prop) - prof = RTC.ConnectorProfile("InPortBaseTest0", - "id0", - [self._inport.get_port_profile().port_ref,self._outport.get_port_profile().port_ref], - self._nvlist) - ret, con_prof = self._outport.connect(prof) - self.assertEqual(self._inport.subscribeInterfaces(prof),RTC.RTC_OK) - self._inport.unsubscribeInterfaces(prof) - ret = self._outport.disconnect(prof.connector_id) - return - - - def test_getConnectorProfiles(self): - profile = self._inport.getPortProfile() - prop = OpenRTM_aist.NVUtil.toProperties(profile.properties) - self._inport.init(prop) - - prof = RTC.ConnectorProfile("InPortBaseTest0", - "id0", - [self._inport.get_port_profile().port_ref,self._outport.get_port_profile().port_ref], - self._nvlist) - ret, con_prof = self._outport.connect(prof) - - cprofs = self._inport.getConnectorProfiles() - self.assertEqual(len(cprofs),1) - - self.assertEqual(cprofs[0].name,"InPortBaseTest0") - self.assertEqual(cprofs[0].id,"id0") - - ret = self._outport.disconnect(prof.connector_id) - return - - - def test_getConnectorIds(self): - profile = self._inport.getPortProfile() - prop = OpenRTM_aist.NVUtil.toProperties(profile.properties) - self._inport.init(prop) - - prof = RTC.ConnectorProfile("InPortBaseTest0", - "id0", - [self._inport.get_port_profile().port_ref,self._outport.get_port_profile().port_ref], - self._nvlist) - ret, con_prof = self._outport.connect(prof) - - cids = self._inport.getConnectorIds() - self.assertEqual(len(cids),1) - - self.assertEqual(cids[0],"id0") - - ret = self._outport.disconnect(prof.connector_id) - return - - - def test_getConnectorNames(self): - profile = self._inport.getPortProfile() - prop = OpenRTM_aist.NVUtil.toProperties(profile.properties) - self._inport.init(prop) - - prof = RTC.ConnectorProfile("InPortBaseTest0", - "id0", - [self._inport.get_port_profile().port_ref,self._outport.get_port_profile().port_ref], - self._nvlist) - ret, con_prof = self._outport.connect(prof) - - cnames = self._inport.getConnectorNames() - self.assertEqual(len(cnames),1) - - self.assertEqual(cnames[0],"InPortBaseTest0") - - ret = self._outport.disconnect(prof.connector_id) - return - - - def test_getConnectorById(self): - profile = self._inport.getPortProfile() - prop = OpenRTM_aist.NVUtil.toProperties(profile.properties) - self._inport.init(prop) - - prof = RTC.ConnectorProfile("InPortBaseTest0", - "id0", - [self._inport.get_port_profile().port_ref,self._outport.get_port_profile().port_ref], - self._nvlist) - ret, con_prof = self._outport.connect(prof) - - con = self._inport.getConnectorById("id") - self.assertEqual(con,None) - - con = self._inport.getConnectorById("id0") - self.assertEqual(con.profile().name,"InPortBaseTest0") - self.assertEqual(con.profile().id,"id0") - - ret = self._outport.disconnect(prof.connector_id) - return - - - def test_getConnectorByName(self): - profile = self._inport.getPortProfile() - prop = OpenRTM_aist.NVUtil.toProperties(profile.properties) - self._inport.init(prop) - - prof = RTC.ConnectorProfile("InPortBaseTest0", - "id0", - [self._inport.get_port_profile().port_ref,self._outport.get_port_profile().port_ref], - self._nvlist) - ret, con_prof = self._outport.connect(prof) - - con = self._inport.getConnectorByName("test") - self.assertEqual(con,None) - - con = self._inport.getConnectorByName("InPortBaseTest0") - - self.assertEqual(con.profile().name,"InPortBaseTest0") - self.assertEqual(con.profile().id,"id0") - - ret = self._outport.disconnect(prof.connector_id) - return - - - def test_getConnectorProfileById(self): - profile = self._inport.getPortProfile() - prop = OpenRTM_aist.NVUtil.toProperties(profile.properties) - self._inport.init(prop) - - prof = RTC.ConnectorProfile("InPortBaseTest0", - "id0", - [self._inport.get_port_profile().port_ref,self._outport.get_port_profile().port_ref], - self._nvlist) - ret, con_prof = self._outport.connect(prof) - - cprof = [None] - ret = self._inport.getConnectorProfileById("test", cprof) - self.assertEqual(ret,False) - - ret = self._inport.getConnectorProfileById("id0", cprof) - self.assertEqual(ret,True) - - self.assertEqual(cprof[0].name,"InPortBaseTest0") - self.assertEqual(cprof[0].id,"id0") - - ret = self._outport.disconnect(prof.connector_id) - return - - - def test_getConnectorProfileByName(self): - profile = self._inport.getPortProfile() - prop = OpenRTM_aist.NVUtil.toProperties(profile.properties) - self._inport.init(prop) - - prof = RTC.ConnectorProfile("InPortBaseTest0", - "id0", - [self._inport.get_port_profile().port_ref,self._outport.get_port_profile().port_ref], - self._nvlist) - ret, con_prof = self._outport.connect(prof) - - cprof = [None] - ret = self._inport.getConnectorProfileByName("test", cprof) - self.assertEqual(ret,False) - - ret = self._inport.getConnectorProfileByName("InPortBaseTest0", cprof) - self.assertEqual(ret,True) - - self.assertEqual(cprof[0].name,"InPortBaseTest0") - self.assertEqual(cprof[0].id,"id0") - - ret = self._outport.disconnect(prof.connector_id) - return - - - -############### test ################# -if __name__ == '__main__': - unittest.main() - diff --git a/OpenRTM_aist/test/test_InPortConnector.py b/OpenRTM_aist/test/test_InPortConnector.py deleted file mode 100755 index 7002931f..00000000 --- a/OpenRTM_aist/test/test_InPortConnector.py +++ /dev/null @@ -1,54 +0,0 @@ -#!/usr/bin/env python -# -*- Python -*- - - -# \file test_InPortConnector.py -# \brief test for InPortConnector class -# \date $Date: 2007/09/20 $ -# \author Shinji Kurihara -# -# Copyright (C) 2003-2005 -# Task-intelligence Research Group, -# Intelligent Systems Research Institute, -# National Institute of -# Advanced Industrial Science and Technology (AIST), Japan -# All rights reserved. - - -import sys -sys.path.insert(1,"../") - -import unittest - -from InPortConnector import * - -import RTC, RTC__POA -import OpenRTM_aist - - -class TestInPortConnector(unittest.TestCase): - def setUp(self): - self._prof = OpenRTM_aist.ConnectorBase.Profile("name","id",[],OpenRTM_aist.Properties()) - self._ic = InPortConnector(self._prof,None) - return - - def test_profile(self): - self.assertEqual(self._ic.profile(),self._prof) - return - - def test_id(self): - self.assertEqual(self._ic.id(),"id") - return - - def test_name(self): - self.assertEqual(self._ic.name(), "name") - - def test_getBuffer(self): - self.assertEqual(self._ic.getBuffer(),None) - - - -############### test ################# -if __name__ == '__main__': - unittest.main() - diff --git a/OpenRTM_aist/test/test_InPortConsumer.py b/OpenRTM_aist/test/test_InPortConsumer.py deleted file mode 100755 index 0e35b975..00000000 --- a/OpenRTM_aist/test/test_InPortConsumer.py +++ /dev/null @@ -1,58 +0,0 @@ -#!/usr/bin/env python -# -*- Python -*- - - -# \file test_InPortConsumer.py -# \brief test for InPort template class -# \date $Date: 2007/09/20 $ -# \author Shinji Kurihara -# -# Copyright (C) 2003-2005 -# Task-intelligence Research Group, -# Intelligent Systems Research Institute, -# National Institute of -# Advanced Industrial Science and Technology (AIST), Japan -# All rights reserved. - - -import sys -sys.path.insert(1,"../") - -import unittest - -from InPortConsumer import * - -import RTC, RTC__POA -import OpenRTM_aist - -class InPortConsumerMock: - def __init__(self): - pass - - def publishInterfaceProfile(self, prop): - return True - - def subscribeInterface(self, prop): - return True - - -class TestInPortConsumer(unittest.TestCase): - def setUp(self): - self._mock = InPortConsumerMock() - return - - def test_publishInterfaceProfileFunc(self): - pubFunc = InPortConsumerFactory.instance().publishInterfaceProfileFunc(None) - pubFunc(self._mock) - return - - def test_subscribeInterfaceFunc(self): - subFunc = InPortConsumerFactory.instance().subscribeInterfaceFunc(None) - self.assertEqual(subFunc(self._mock),True) - return - - -############### test ################# -if __name__ == '__main__': - unittest.main() - diff --git a/OpenRTM_aist/test/test_InPortCorbaCdrConsumer.py b/OpenRTM_aist/test/test_InPortCorbaCdrConsumer.py deleted file mode 100755 index 4c9d4f5f..00000000 --- a/OpenRTM_aist/test/test_InPortCorbaCdrConsumer.py +++ /dev/null @@ -1,92 +0,0 @@ -#!/usr/bin/env python -# -*- Python -*- - - -# \file test_InPortCorbaCdrConsumer.py -# \brief test for InPortCorbaCdrConsumer class -# \date $Date: 2007/09/20 $ -# \author Shinji Kurihara -# -# Copyright (C) 2003-2005 -# Task-intelligence Research Group, -# Intelligent Systems Research Institute, -# National Institute of -# Advanced Industrial Science and Technology (AIST), Japan -# All rights reserved. - - -import sys -sys.path.insert(1,"../") - -import unittest - -from InPortCorbaCdrConsumer import * - -import RTC, RTC__POA -import OpenRTM_aist - - -class TestInPortCorbaCdrConsumer(unittest.TestCase): - def setUp(self): - InPortCorbaCdrConsumerInit() - self._cons = OpenRTM_aist.InPortConsumerFactory.instance().createObject("corba_cdr") - self._inp = OpenRTM_aist.InPort("in",RTC.TimedLong(RTC.Time(0,0),0)) - self._orb = OpenRTM_aist.Manager.instance().getORB() - return - - def test_init(self): - self._cons.init(OpenRTM_aist.Properties()) - return - - def test_put(self): - self.assertEqual(self._cons.put(123),OpenRTM_aist.DataPortStatus.CONNECTION_LOST) - return - - def test_publishInterfaceProfile(self): - self._cons.publishInterfaceProfile(OpenRTM_aist.Properties()) - return - - def test_subscribeInterface(self): - ior = self._orb.object_to_string(self._inp.get_port_profile().port_ref) - self.assertEqual(self._cons.subscribeInterface([OpenRTM_aist.NVUtil.newNV("dataport.corba_cdr.inport_ior",ior)]),True) - self.assertEqual(self._cons.subscribeInterface([OpenRTM_aist.NVUtil.newNV("dataport.corba_cdr.inport_ref", - self._inp.get_port_profile().port_ref)]),True) - return - - def test_unsubscribeInterface(self): - ior = self._orb.object_to_string(self._inp.get_port_profile().port_ref) - self.assertEqual(self._cons.subscribeInterface([OpenRTM_aist.NVUtil.newNV("dataport.corba_cdr.inport_ior",ior)]),True) - self._cons.unsubscribeInterface([OpenRTM_aist.NVUtil.newNV("dataport.corba_cdr.inport_ior",ior)]) - self.assertEqual(self._cons.subscribeInterface([OpenRTM_aist.NVUtil.newNV("dataport.corba_cdr.inport_ref", - self._inp.get_port_profile().port_ref)]),True) - self._cons.unsubscribeInterface([OpenRTM_aist.NVUtil.newNV("dataport.corba_cdr.inport_ref", - self._inp.get_port_profile().port_ref)]) - return - - def test_subscribeFromIor(self): - ior = self._orb.object_to_string(self._inp.get_port_profile().port_ref) - self.assertEqual(self._cons.subscribeFromIor([OpenRTM_aist.NVUtil.newNV("dataport.corba_cdr.inport_ior",ior)]),True) - return - - def test_subscribeFromRef(self): - self.assertEqual(self._cons.subscribeFromRef([OpenRTM_aist.NVUtil.newNV("dataport.corba_cdr.inport_ref", - self._inp.get_port_profile().port_ref)]),True) - return - - def test_unsubscribeFromIor(self): - ior = self._orb.object_to_string(self._inp.get_port_profile().port_ref) - self.assertEqual(self._cons.subscribeFromIor([OpenRTM_aist.NVUtil.newNV("dataport.corba_cdr.inport_ior",ior)]),True) - self.assertEqual(self._cons.unsubscribeFromIor([OpenRTM_aist.NVUtil.newNV("dataport.corba_cdr.inport_ior",ior)]),True) - return - - def test_unsubscribeFromRef(self): - self.assertEqual(self._cons.subscribeFromRef([OpenRTM_aist.NVUtil.newNV("dataport.corba_cdr.inport_ref", - self._inp.get_port_profile().port_ref)]),True) - self.assertEqual(self._cons.unsubscribeFromRef([OpenRTM_aist.NVUtil.newNV("dataport.corba_cdr.inport_ref", - self._inp.get_port_profile().port_ref)]),True) - return - -############### test ################# -if __name__ == '__main__': - unittest.main() - diff --git a/OpenRTM_aist/test/test_InPortCorbaCdrProvider.py b/OpenRTM_aist/test/test_InPortCorbaCdrProvider.py deleted file mode 100755 index 15275a5e..00000000 --- a/OpenRTM_aist/test/test_InPortCorbaCdrProvider.py +++ /dev/null @@ -1,110 +0,0 @@ -#!/usr/bin/env python -# -*- Python -*- - - -# \file test_InPortCorbaCdrProvider.py -# \brief test for InPortCorbaCdrProvider class -# \date $Date: 2007/09/20 $ -# \author Shinji Kurihara -# -# Copyright (C) 2003-2005 -# Task-intelligence Research Group, -# Intelligent Systems Research Institute, -# National Institute of -# Advanced Industrial Science and Technology (AIST), Japan -# All rights reserved. - - -from omniORB import * -from omniORB import any - -import sys -sys.path.insert(1,"../") - -import unittest - -from InPortCorbaCdrProvider import * - -import RTC, RTC__POA -import OpenRTM -import OpenRTM_aist - - -class BufferMock: - def __init__(self): - self._data = None - return - - def write(self, data): - self._data = data - return OpenRTM_aist.BufferStatus.BUFFER_OK - - def read(self, value): - if len(value) > 0: - value[0] = self._data - else: - value.append(self._data) - return OpenRTM_aist.BufferStatus.BUFFER_OK - - def full(self): - return False - - -class ConnectorMock: - def __init__(self, buffer): - self._buffer = buffer - return - - def write(self, data): - self._buffer.write(data) - return OpenRTM_aist.BufferStatus.BUFFER_OK - - - -class TestInPortCorbaCdrProvider(unittest.TestCase): - def setUp(self): - InPortCorbaCdrProviderInit() - OpenRTM_aist.CdrRingBufferInit() - self._prov = OpenRTM_aist.InPortProviderFactory.instance().createObject("corba_cdr") - self._inp = OpenRTM_aist.InPort("in",RTC.TimedLong(RTC.Time(0,0),0)) - self._orb = OpenRTM_aist.Manager.instance().getORB() - self._buffer = BufferMock() - return - - def test_init(self): - self._prov.init(OpenRTM_aist.Properties()) - return - - def test_setBuffer(self): - self._prov.setBuffer(self._buffer) - return - - def test_put(self): - self._con = ConnectorMock(self._buffer) - self._prov._connector = self._con - self._prov.setBuffer(self._buffer) - data = RTC.TimedLong(RTC.Time(0,0),123) - cdr = cdrMarshal(any.to_any(data).typecode(), data, 1) - self.assertEqual(self._prov.put(cdr),OpenRTM.PORT_OK) - self.assertEqual(self._prov.put(cdr),OpenRTM.PORT_OK) - self.assertEqual(self._prov.put(cdr),OpenRTM.PORT_OK) - self.assertEqual(self._prov.put(cdr),OpenRTM.PORT_OK) - self.assertEqual(self._prov.put(cdr),OpenRTM.PORT_OK) - self.assertEqual(self._prov.put(cdr),OpenRTM.PORT_OK) - self.assertEqual(self._prov.put(cdr),OpenRTM.PORT_OK) - self.assertEqual(self._prov.put(cdr),OpenRTM.PORT_OK) - self.assertEqual(self._prov.put(cdr),OpenRTM.PORT_OK) - self.assertEqual(self._prov.put(cdr),OpenRTM.PORT_OK) - self.assertEqual(self._prov.put(cdr),OpenRTM.PORT_OK) - val = [] - self.assertEqual(self._buffer.read(val), OpenRTM_aist.BufferStatus.BUFFER_OK) - get_data = cdrUnmarshal(any.to_any(data).typecode(), val[0], 1) - self.assertEqual(get_data.data, 123) - return - - - -############### test ################# -if __name__ == '__main__': - unittest.main() - diff --git a/OpenRTM_aist/test/test_InPortCorbaConsumer.py b/OpenRTM_aist/test/test_InPortCorbaConsumer.py deleted file mode 100755 index 73e0bcd9..00000000 --- a/OpenRTM_aist/test/test_InPortCorbaConsumer.py +++ /dev/null @@ -1,93 +0,0 @@ -#!/usr/bin/env python -# -*- Python -*- - -# -# \file test_InPortCorbaConsumer.py -# \brief test for InPortCorbaConsumer class -# \date $Date: 2007/09/21 $ -# \author Shinji Kurihara -# -# Copyright (C) 2006 -# Noriaki Ando -# Task-intelligence Research Group, -# Intelligent Systems Research Institute, -# National Institute of -# Advanced Industrial Science and Technology (AIST), Japan -# All rights reserved. - - -import OpenRTM_aist - -import sys -sys.path.insert(1,"../") - -import unittest - -from InPortCorbaConsumer import * -from NVUtil import * - -from omniORB import CORBA -import RTC, RTC__POA -import SDOPackage,SDOPackage__POA -from omniORB import any - - -class InPortTest(RTC__POA.InPortAny): - def __init__(self): - self.orb = CORBA.ORB_init() - self.poa = self.orb.resolve_initial_references("RootPOA") - poaManager = self.poa._get_the_POAManager() - poaManager.activate() - - - def put(self, data): - print "put data: ", data - - -class test(OpenRTM_aist.RTObject_impl): - def __init__(self): - self.orb = CORBA.ORB_init() - self.poa = self.orb.resolve_initial_references("RootPOA") - OpenRTM_aist.RTObject_impl.__init__(self, orb=self.orb, poa=self.poa) - poaManager = self.poa._get_the_POAManager() - poaManager.activate() - - -class TestInPortCorbaConsumer(unittest.TestCase): - def setUp(self): - ringbuf = OpenRTM_aist.RingBuffer(8) - ringbuf.init(RTC.TimedLong(RTC.Time(0,0), 0)) - self._ipcc = InPortCorbaConsumer(OpenRTM_aist.OutPort("out", - RTC.TimedLong(RTC.Time(0,0), 0), - ringbuf)) - - def test_equal_operator(self): - self.assertEqual(self._ipcc.equal_operator(self._ipcc), self._ipcc) - - def test_put(self): - self._ipcc.setObject(InPortTest()._this()) - self._ipcc.put(RTC.TimedLong(RTC.Time(0,0), 123)) - - def test_push(self): - self._ipcc.setObject(InPortTest()._this()) - self._ipcc.push() - - def test_clone(self): - self._ipcc.clone() - - def test_subscribeInterface(self): - port = any.to_any(InPortTest()._this()) -# prop = [SDOPackage.NameValue("dataport.dataflow_type","Push"), -# SDOPackage.NameValue("dataport.corba_any.inport_ref",port)] - prop = [newNV("dataport.dataflow_type","Push"), - newNV("dataport.corba_any.inport_ref",port)] - self.assertEqual(self._ipcc.subscribeInterface(prop), True) - - - def unsubscribeInterface(self, properties): - pass - - -############### test ################# -if __name__ == '__main__': - unittest.main() diff --git a/OpenRTM_aist/test/test_InPortCorbaProvider.py b/OpenRTM_aist/test/test_InPortCorbaProvider.py deleted file mode 100755 index 79e63be6..00000000 --- a/OpenRTM_aist/test/test_InPortCorbaProvider.py +++ /dev/null @@ -1,59 +0,0 @@ -#!/usr/bin/env python -# -*- Python -*- - - -# -# \file InPortCorbaProvider.py -# \brief InPortCorbaProvider class -# \date $Date: 2007/09/25 $ -# \author Shinji Kurihara -# -# Copyright (C) 2006 -# Noriaki Ando -# Task-intelligence Research Group, -# Intelligent Systems Research Institute, -# National Institute of -# Advanced Industrial Science and Technology (AIST), Japan -# All rights reserved. - -import sys -sys.path.insert(1,"../") - -import unittest - -from InPortCorbaProvider import * - -from omniORB import CORBA -import RTC, RTC__POA -import SDOPackage,SDOPackage__POA -from omniORB import any - -import OpenRTM_aist - - -class TestInPortCorbaProvider(unittest.TestCase): - def setUp(self): - self.orb = CORBA.ORB_init() - self.poa = self.orb.resolve_initial_references("RootPOA") - poaManager = self.poa._get_the_POAManager() - poaManager.activate() - - ringbuf = OpenRTM_aist.RingBuffer(8) - ringbuf.init(RTC.TimedLong(RTC.Time(0,0), 0)) - self._ipcp = InPortCorbaProvider(OpenRTM_aist.InPort("in", - RTC.TimedLong(RTC.Time(0,0), 0), - ringbuf)) - - def test_publishInterface(self): - prop = [SDOPackage.NameValue("dataport.interface_type", "CORBA_Any")] - self._ipcp.publishInterface(prop) - - - def test_put(self): - data = any.to_any(RTC.TimedLong(RTC.Time(0,0),123)) - self._ipcp.put(data) - - -############### test ################# -if __name__ == '__main__': - unittest.main() diff --git a/OpenRTM_aist/test/test_InPortProvider.py b/OpenRTM_aist/test/test_InPortProvider.py deleted file mode 100755 index 92565514..00000000 --- a/OpenRTM_aist/test/test_InPortProvider.py +++ /dev/null @@ -1,51 +0,0 @@ -#!/usr/bin/env python -# -*- Python -*- - -# -# \file test_InPortProvider.py -# \brief test for InPortProvider class -# \date $Date: 2007/09/20 $ -# \author Shinji Kurihara -# -# Copyright (C) 2006 -# Noriaki Ando -# Task-intelligence Research Group, -# Intelligent Systems Research Institute, -# National Institute of -# Advanced Industrial Science and Technology (AIST), Japan -# All rights reserved. - - -import sys -sys.path.insert(1,"../") - -import unittest - -from InPortProvider import * -import OpenRTM_aist - - -class TestInPortProvider(unittest.TestCase): - def setUp(self): - return - - def tearDown(self): - OpenRTM_aist.Manager.instance().shutdownManager() - return - - def test_publishInterfaceProfile(self): - InPortProviderFactory.instance().setInterfaceType("corba_cdr") - InPortProviderFactory.instance().setDataFlowType("push,pull") - InPortProviderFactory.instance().setSubscriptionType("flush,new,periodic") - InPortProviderFactory.instance().publishInterfaceProfile([]) - - def test_publishInterface(self): - InPortProviderFactory.instance().setInterfaceType("corba_cdr") - InPortProviderFactory.instance().setDataFlowType("push,pull") - InPortProviderFactory.instance().setSubscriptionType("flush,new,periodic") - self.assertEqual(InPortProviderFactory.instance().publishInterface([OpenRTM_aist.NVUtil.newNV("dataport.interface_type","corba_cdr")]),True) - - -############### test ################# -if __name__ == '__main__': - unittest.main() diff --git a/OpenRTM_aist/test/test_InPortPullConnector.py b/OpenRTM_aist/test/test_InPortPullConnector.py deleted file mode 100755 index e1d26496..00000000 --- a/OpenRTM_aist/test/test_InPortPullConnector.py +++ /dev/null @@ -1,72 +0,0 @@ -#!/usr/bin/env python -# -*- Python -*- - - -# \file test_InPortPullConnector.py -# \brief test for InPortPullConnector class -# \date $Date: 2007/09/20 $ -# \author Shinji Kurihara -# -# Copyright (C) 2003-2005 -# Task-intelligence Research Group, -# Intelligent Systems Research Institute, -# National Institute of -# Advanced Industrial Science and Technology (AIST), Japan -# All rights reserved. - - -import sys -sys.path.insert(1,"../") - -import unittest - -from InPortPullConnector import * - -import RTC, RTC__POA -import OpenRTM_aist - -class InPortConsumerMock: - _buffer = None - - def setBuffer(self, buff): - self._buffer = buff - - def setListener(self, info, listener): - pass - - def get(self, data): - return OpenRTM_aist.DataPortStatus.PORT_OK - -class TestInPortPullConnector(unittest.TestCase): - def setUp(self): - OpenRTM_aist.Manager.instance() - self._con = InPortPullConnector(OpenRTM_aist.ConnectorInfo("name","id",[],OpenRTM_aist.Properties()),InPortConsumerMock(),OpenRTM_aist.ConnectorListeners()) - - def test_read(self): - data = [] - self.assertEqual(self._con.read(data),OpenRTM_aist.BufferStatus.PRECONDITION_NOT_MET) - return - - def test_disconnect(self): - self.assertEqual(self._con.disconnect(),OpenRTM_aist.DataPortStatus.PORT_OK) - return - - def test_activate(self): - self._con.activate() - return - - def test_deactivate(self): - self._con.deactivate() - return - - def test_createBuffer(self): - self._con.createBuffer(OpenRTM_aist.ConnectorInfo("name","id",[],OpenRTM_aist.Properties())) - return - - - - -############### test ################# -if __name__ == '__main__': - unittest.main() - diff --git a/OpenRTM_aist/test/test_InPortPushConnector.py b/OpenRTM_aist/test/test_InPortPushConnector.py deleted file mode 100755 index 4b82b95c..00000000 --- a/OpenRTM_aist/test/test_InPortPushConnector.py +++ /dev/null @@ -1,78 +0,0 @@ -#!/usr/bin/env python -# -*- Python -*- - - -# \file test_InPortPushConnector.py -# \brief test for InPortPushConnector class -# \date $Date: 2007/09/20 $ -# \author Shinji Kurihara -# -# Copyright (C) 2003-2005 -# Task-intelligence Research Group, -# Intelligent Systems Research Institute, -# National Institute of -# Advanced Industrial Science and Technology (AIST), Japan -# All rights reserved. - - -import sys -sys.path.insert(1,"../") - -import unittest - -from InPortPushConnector import * - -import RTC, RTC__POA -import OpenRTM_aist -from OpenRTM_aist import * - - -class InPortProviderMock: - _buffer = None - _prop = None - - def init(self, prop): - self._prop = prop - - def setBuffer(self, buff): - self._buffer = buff - - def setListener(self, info, listener): - pass - - -class TestInPortPushConnector(unittest.TestCase): - def setUp(self): - OpenRTM_aist.Manager.instance() - self._con = InPortPushConnector(OpenRTM_aist.ConnectorInfo("name","id",[],OpenRTM_aist.Properties()),InPortProviderMock(),OpenRTM_aist.ConnectorListeners()) - - def test_read(self): - data = [] - self.assertEqual(self._con.read(data),OpenRTM_aist.DataPortStatus.BUFFER_TIMEOUT) - data = 123 - self.assertEqual(self._con.read(data),OpenRTM_aist.DataPortStatus.BUFFER_TIMEOUT) - return - - def test_disconnect(self): - self.assertEqual(self._con.disconnect(),OpenRTM_aist.DataPortStatus.PORT_OK) - return - - def test_activate(self): - self._con.activate() - return - - def test_deactivate(self): - self._con.deactivate() - return - - def test_createBuffer(self): - self._con.createBuffer(OpenRTM_aist.ConnectorInfo("name","id",[],OpenRTM_aist.Properties())) - return - - - - -############### test ################# -if __name__ == '__main__': - unittest.main() - diff --git a/OpenRTM_aist/test/test_InPortSHMProvider.py b/OpenRTM_aist/test/test_InPortSHMProvider.py deleted file mode 100644 index 66f85e77..00000000 --- a/OpenRTM_aist/test/test_InPortSHMProvider.py +++ /dev/null @@ -1,108 +0,0 @@ -#!/usr/bin/env python -# -*- Python -*- - - -# \file test_InPortSHMProvider.py -# \brief test for InPortSHMProvider class -# \date $Date: 2007/09/20 $ -# \author Nobuhiko Miyamoto -# - - - -from omniORB import * -from omniORB import any - -import sys -sys.path.insert(1,"../") - -import unittest - -import RTC, RTC__POA -import OpenRTM -import OpenRTM_aist - - -class BufferMock: - def __init__(self): - self._data = None - return - - def write(self, data): - self._data = data - return OpenRTM_aist.BufferStatus.BUFFER_OK - - def read(self, value): - if len(value) > 0: - value[0] = self._data - else: - value.append(self._data) - return OpenRTM_aist.BufferStatus.BUFFER_OK - - def full(self): - return False - - -class ConnectorMock: - def __init__(self, buffer): - self._buffer = buffer - return - - def write(self, data): - self._buffer.write(data) - return OpenRTM_aist.BufferStatus.BUFFER_OK - - - -class TestInPortSHMProvider(unittest.TestCase): - def setUp(self): - OpenRTM_aist.InPortSHMProviderInit() - OpenRTM_aist.CdrRingBufferInit() - self._prov = OpenRTM_aist.InPortProviderFactory.instance().createObject("shared_memory") - self._inp = OpenRTM_aist.InPort("in",RTC.TimedLong(RTC.Time(0,0),0)) - self._orb = OpenRTM_aist.Manager.instance().getORB() - self._buffer = BufferMock() - #self._shm = OpenRTM_aist.SharedMemory() - - #self._shm.setInterface(self._prov._this()) - #self._shm.create_memory(1000,"test") - self._prov.create_memory(1000,"test") - return - - - - - - def test_put(self): - - self._con = ConnectorMock(self._buffer) - self._prov._connector = self._con - self._prov.setBuffer(self._buffer) - data = RTC.TimedLong(RTC.Time(0,0),123) - cdr = cdrMarshal(any.to_any(data).typecode(), data, 1) - - self._prov.write(cdr) - - self.assertEqual(self._prov.put(),OpenRTM.PORT_OK) - self.assertEqual(self._prov.put(),OpenRTM.PORT_OK) - self.assertEqual(self._prov.put(),OpenRTM.PORT_OK) - self.assertEqual(self._prov.put(),OpenRTM.PORT_OK) - self.assertEqual(self._prov.put(),OpenRTM.PORT_OK) - self.assertEqual(self._prov.put(),OpenRTM.PORT_OK) - self.assertEqual(self._prov.put(),OpenRTM.PORT_OK) - self.assertEqual(self._prov.put(),OpenRTM.PORT_OK) - self.assertEqual(self._prov.put(),OpenRTM.PORT_OK) - self.assertEqual(self._prov.put(),OpenRTM.PORT_OK) - self.assertEqual(self._prov.put(),OpenRTM.PORT_OK) - val = [] - self.assertEqual(self._buffer.read(val), OpenRTM_aist.BufferStatus.BUFFER_OK) - get_data = cdrUnmarshal(any.to_any(data).typecode(), val[0], 1) - self.assertEqual(get_data.data, 123) - return - - - -############### test ################# -if __name__ == '__main__': - unittest.main() - diff --git a/OpenRTM_aist/test/test_Listener.py b/OpenRTM_aist/test/test_Listener.py deleted file mode 100755 index b4e74e1a..00000000 --- a/OpenRTM_aist/test/test_Listener.py +++ /dev/null @@ -1,49 +0,0 @@ -#!/usr/bin/env python -# -*- Python -*- - -# -# \file test_Listener.py -# \brief test for Listener class -# \date $Date: 2007/08/23$ -# \author Shinji Kurihara -# -# Copyright (C) 2007 -# Task-intelligence Research Group, -# Intelligent Systems Research Institute, -# National Institute of -# Advanced Industrial Science and Technology (AIST), Japan -# All rights reserved. -# - -import sys -sys.path.insert(1,"../") - -import unittest - -from Listener import * -import OpenRTM_aist - -class test: - def func(self): - print "test func" - - -class TestListener(unittest.TestCase): - def setUp(self): - self.obj = ListenerObject(test(),test.func) - self.func = ListenerFunc(test().func) - - - def tearDown(self): - OpenRTM_aist.Manager.instance().shutdownManager() - return - - def test_invoke(self): - self.obj.invoke() - self.func.invoke() - - - -############### test ################# -if __name__ == '__main__': - unittest.main() diff --git a/OpenRTM_aist/test/test_ListenerHolder.py b/OpenRTM_aist/test/test_ListenerHolder.py deleted file mode 100644 index c4588e74..00000000 --- a/OpenRTM_aist/test/test_ListenerHolder.py +++ /dev/null @@ -1,51 +0,0 @@ -#!/usr/bin/env python -# -*- Python -*- - -# -# \file test_ListenerHolder.py -# \brief test for ListenerHolder class -# \date $Date: 2012/01/13$ -# \author Shinji Kurihara -# -# Copyright (C) 2012 -# Task-intelligence Research Group, -# Intelligent Systems Research Institute, -# National Institute of -# Advanced Industrial Science and Technology (AIST), Japan -# All rights reserved. -# - -import sys -sys.path.insert(1,"../") - -import unittest - -from ListenerHolder import * -import OpenRTM_aist - -class MyListener: - def func(self, *args): - print "MyListener func args: ", args - - -class TestListenerHolder(unittest.TestCase): - def setUp(self): - self.lholder = ListenerHolder() - self.listener = MyListener() - - - def tearDown(self): - OpenRTM_aist.Manager.instance().shutdownManager() - return - - def test_addRemoveListener(self): - self.lholder.addListener(self.listener,True) - self.lholder.LISTENERHOLDER_CALLBACK(MyListener.func,"test"," ListenerHolder") - self.lholder.removeListener(self.listener) - return - - - -############### test ################# -if __name__ == '__main__': - unittest.main() diff --git a/OpenRTM_aist/test/test_LocalServiceAdmin.py b/OpenRTM_aist/test/test_LocalServiceAdmin.py deleted file mode 100644 index a819d50c..00000000 --- a/OpenRTM_aist/test/test_LocalServiceAdmin.py +++ /dev/null @@ -1,87 +0,0 @@ -#!/usr/bin/env python -# -*- Python -*- - -# -# \file test_LocalServiceAdmin.py -# \brief test for LocalServiceAdmin class -# \date $Date: 2012/01/13$ -# \author Shinji Kurihara -# -# Copyright (C) 2012 -# Task-intelligence Research Group, -# Intelligent Systems Research Institute, -# National Institute of -# Advanced Industrial Science and Technology (AIST), Japan -# All rights reserved. -# - -import sys -sys.path.insert(1,"../") - -import unittest - -from LocalServiceAdmin import * -import OpenRTM_aist - -class MyLocalService: - def __init__(self): - return - - def init(self, props): - return - - def reinit(self, props): - return - - def getProfile(self): - prop = OpenRTM_aist.LocalServiceProfile() - prop.name = "MyLocalService" - prop.uuid = "1234" - p = OpenRTM_aist.Properties() - p.setProperty("id_", 4321) - prop.properties = p - prop.service = self - return prop - - def finalize(self): - return - -def MyLocalServiceInit(): - factory = OpenRTM_aist.LocalServiceFactory.instance() - factory.addFactory("MyLocalService", - MyLocalService, - OpenRTM_aist.Delete) - return - - - -class TestLocalServiceAdmin(unittest.TestCase): - def setUp(self): - self.ladmin = LocalServiceAdmin() - MyLocalServiceInit() - return - - def tearDown(self): - OpenRTM_aist.Manager.instance().shutdownManager() - return - - def test_init(self): - prop = OpenRTM_aist.Properties() - prop.setProperty("enabled_services","MyLocalService") - self.ladmin.init(prop) - self.ladmin.getServiceProfiles() - - get_prop = [OpenRTM_aist.Properties()] - prof = self.ladmin.getServiceProfile("MyLocalService", get_prop) - lsvc = self.ladmin.getService("MyLocalService") - self.assertNotEqual(None, lsvc) - self.assertEqual(True, self.ladmin.addLocalService(lsvc)) - self.assertEqual(True, self.ladmin.removeLocalService("MyLocalService")) - self.ladmin.finalize() - return - - - -############### test ################# -if __name__ == '__main__': - unittest.main() diff --git a/OpenRTM_aist/test/test_Manager.py b/OpenRTM_aist/test/test_Manager.py deleted file mode 100755 index 751d861c..00000000 --- a/OpenRTM_aist/test/test_Manager.py +++ /dev/null @@ -1,360 +0,0 @@ -#!/usr/bin/env python -# -*- coding: euc-jp -*- - -# -# \file test_Manager.py -# \brief test for RTComponent manager class -# \date $Date: $ -# \author Shinji Kurihara -# -# Copyright (C) 2006 -# Task-intelligence Research Group, -# Intelligent Systems Research Institute, -# National Institute of -# Advanced Industrial Science and Technology (AIST), Japan -# All rights reserved. -# - -import sys -sys.path.insert(1,"../") - -import unittest -import time - -#from Manager import * -import OpenRTM_aist -import RTC, RTC__POA - -testcomp_spec = ["implementation_id", "TestComp", - "type_name", "TestComp", - "description", "Test example component", - "version", "1.0", - "vendor", "Shinji Kurihara, AIST", - "category", "example", - "activity_type", "DataFlowComponent", - "max_instance", "10", - "language", "C++", - "lang_type", "compile", - # Configuration variables - "conf.default.int_param0", "0", - "conf.default.int_param1", "1", - "conf.default.double_param0", "0.11", - "conf.default.double_param1", "9.9", - "conf.default.str_param0", "hoge", - "conf.default.str_param1", "dara", - "conf.default.vector_param0", "0.0,1.0,2.0,3.0,4.0", - ""] - -class TestComp(OpenRTM_aist.DataFlowComponentBase): - def __init__(self, manager): - OpenRTM_aist.DataFlowComponentBase.__init__(self, manager) - return - - -def TestCompInit(manager): - profile = OpenRTM_aist.Properties(defaults_str=testcomp_spec) - manager.registerFactory(profile, - TestComp, - OpenRTM_aist.Delete) - -#def TestCompInit(manager): -def MyModuleInit(manager): - TestCompInit(manager) - com = manager.createComponent("TestComp") - -def TestEcInit(manager): - profile = OpenRTM_aist.Properties(defaults_str=testcomp_spec) - manager.registerECFactory("Art", - TestComp, - OpenRTM_aist.Delete) - manager.createComponent("TestEc") - - -class TestManager(unittest.TestCase): - - def setUp(self): - global manager - #manager = OpenRTM_aist.Manager.init(sys.argv) - #self.manager = manager - self.manager = OpenRTM_aist.Manager.init(sys.argv) - - def tearDown(self): - self.manager.shutdownManager() - time.sleep(0.1) - -### def COMMENTtest_terminate(self): -### self.manager.activateManager() -### self.manager.runManager(True) -### self.manager.terminate() -### return -### -### def COMMENTtest_shutdown(self): -### self.manager.activateManager() -### self.manager.runManager(True) -### time.sleep(0.1) -### self.manager.shutdown() -### #self.manager.runManager() -### -### - def test_init(self): - #self.assertEqual(self.manager,OpenRTM_aist.Manager.init(sys.argv)) - return - - def test_instance(self): - self.assertEqual(OpenRTM_aist.Manager.instance(), self.manager) - return - - - def test_load_unload(self): - self.manager.load("hoge", "echo") - self.manager.unload("hoge") - self.manager.unloadAll() - self.manager.load("hoge", "echo") - self.assertEqual(len(self.manager.getLoadedModules()), 1) - #self.assertEqual(len(self.manager.getLoadableModules()), 1) - return - - def test_getLoadedModules(self): - self.manager.activateManager() - self.assertEqual(self.manager.getLoadedModules(),[]) - return - - def test_getLoadableModules(self): - self.manager.activateManager() - # hoge.py is loadable module. - #self.assertNotEqual(self.manager.getLoadableModules(),[]) - return - - def test_registerFactory(self): - profile = OpenRTM_aist.Properties(defaults_str=testcomp_spec) - self.assertEqual(self.manager.registerFactory(profile, - TestComp, - OpenRTM_aist.Delete), - True) - return - - def test_getFactoryProfiles(self): - self.manager.getFactoryProfiles() - return - - def test_registerECFactory(self): - profile = OpenRTM_aist.Properties(defaults_str=testcomp_spec) - self.assertEqual(self.manager.registerECFactory("Art", - TestComp, - OpenRTM_aist.Delete), - True) - return - - def test_getModulesFactories(self): - self.assertEqual(self.manager.getModulesFactories()[0],'PeriodicECSharedComposite') - return - - def test_createComponent(self): - self.manager.activateManager() - profile = OpenRTM_aist.Properties(defaults_str=testcomp_spec) - self.manager.registerFactory(profile, - TestComp, - OpenRTM_aist.Delete) - com = self.manager.createComponent("TestComp") - self.assertNotEqual(com,None) - #self.assertEqual(self.manager.getComponent("TestComp0"),self.manager.getComponents()[0]) - #self.manager.deleteComponent("TestComp0") - self.manager.shutdownComponents() - time.sleep(0.1) - return - - def test_getORB(self): - self.manager.getORB() - return - - def test_getPOA(self): - self.manager.getPOA() - return - - def test_getPOAManager(self): - self.manager.getPOAManager() - return - - - def test_registerComponent(self): - self.manager.activateManager() - profile = OpenRTM_aist.Properties(defaults_str=testcomp_spec) - self.manager.registerFactory(profile, - TestComp, - OpenRTM_aist.Delete) - com = self.manager.createComponent("TestComp") - self.assertEqual(self.manager.registerComponent(com),True) - self.manager.shutdownComponents() - return -### -### def COMMENTtest_unregisterComponent(self): -### self.manager.activateManager() -### profile = OpenRTM_aist.Properties(defaults_str=testcomp_spec) -### self.manager.registerFactory(profile, -### TestComp, -### OpenRTM_aist.Delete) -### com = self.manager.createComponent("TestComp") -### self.assertEqual(self.manager.unregisterComponent(com),True) -### self.manager.shutdownComponents() -### return -### - def test_createContext(self): - ec_args = "PeriodicExecutionContext?rate=" - self.manager.activateManager() - ec = self.manager.createContext(ec_args) - self.assertNotEqual(ec,None) - ec.stop() - self.manager.getPOA().deactivate_object(self.manager.getPOA().servant_to_id(ec)) - del ec - return -### -### -### -### def test_shutdownManager(self): -### return -### -### def test_shutdownOnNoRtcs(self): -### return -### -### -### def test_createORBEndpoints(self): -### self.manager.activateManager() -### l=[] -### self.manager.createORBEndpoints(l) -### return -### - def test_createORBEndpointOption(self): - self.manager.activateManager() - self.manager.createORBEndpointOption("",[]) - return -### -### -### -### def test_shutdownORB(self): -### return -### -### def test_shutdownComponents(self): -### return -### -### -### - def test_cleanupComponent(self): - self.manager.activateManager() - profile = OpenRTM_aist.Properties(defaults_str=testcomp_spec) - self.manager.registerFactory(profile, - TestComp, - OpenRTM_aist.Delete) - com = self.manager.createComponent("TestComp") - self.assertEqual(self.manager.registerComponent(com),True) - self.manager.cleanupComponent(com) - com.exit() - self.manager.shutdownComponents() - return - - - def test_notifyFinalized(self): - self.manager.activateManager() - profile = OpenRTM_aist.Properties(defaults_str=testcomp_spec) - self.manager.registerFactory(profile, - TestComp, - OpenRTM_aist.Delete) - com = self.manager.createComponent("TestComp") - #self.manager.notifyFinalized(com) - #self.manager.cleanupComponents() - self.manager.shutdownComponents() - return - - - def test_initManager(self): - self.manager.initManager(sys.argv) - #self.manager.shutdownManager() - return - - def test_initLogger(self): - self.manager.initLogger() - #self.manager.shutdownLogger() - return - - def test_initORB(self): - #self.assertEqual(self.manager.initORB(),True) - #self.manager.shutdownORB() - return - - - def test_initNaming(self): - self.assertEqual(self.manager.initNaming(),True) - #self.manager.shutdownNaming() - return - - - def test_initExecContext(self): - self.assertEqual(self.manager.initExecContext(),True) - return - - def test_initComposite(self): - self.assertEqual(self.manager.initComposite(),True) - return - - - def test_initFactories(self): - self.assertEqual(self.manager.initFactories(),True) - return - - def test_initManagerServant(self): - self.assertEqual(self.manager.initManagerServant(), True) - return - - - def test_procComponentArgs(self): - comp_id = OpenRTM_aist.Properties() - comp_conf = OpenRTM_aist.Properties() - - self.assertEqual(self.manager.procComponentArgs("TestComp?instance_name=test&exported_ports=ConsoleIn0.out,ConsoleOut0.in",comp_id,comp_conf),True) - self.assertEqual(comp_id.getProperty("implementation_id"),"TestComp") - self.assertEqual(comp_conf.getProperty("instance_name"),"test") - self.assertEqual(comp_conf.getProperty("exported_ports"),"ConsoleIn0.out,ConsoleOut0.in") - return - - def test_procContextArgs(self): - ec_id = [""] - ec_conf = OpenRTM_aist.Properties() - self.assertEqual(self.manager.procContextArgs("PeriodicExecutionContext?rate=1000",ec_id,ec_conf),True) - self.assertEqual(ec_id[0],"PeriodicExecutionContext") - self.assertEqual(ec_conf.getProperty("rate"),"1000") - return - - def test_configureComponent(self): - self.manager.activateManager() - profile = OpenRTM_aist.Properties(defaults_str=testcomp_spec) - self.manager.registerFactory(profile, - TestComp, - OpenRTM_aist.Delete) - com = self.manager.createComponent("TestComp") - prop = OpenRTM_aist.Properties() - self.manager.configureComponent(com,prop) - self.manager.cleanupComponent(com) - com.exit() - self.manager.shutdownComponents() - return - - def test_formatString(self): - profile = OpenRTM_aist.Properties(defaults_str=testcomp_spec) - self.assertEqual(self.manager.formatString("rtc.log",profile),"rtc.log") - print self.manager.formatString("$(PWD)",profile) - print self.manager.formatString("%n.%t.%m.%v.%V.%c.%h.%M.%p",profile) - return - - def test_getLogbuf(self): - self.manager.getLogbuf() - return - - def test_getConfig(self): - self.manager.getConfig() - return - - - - -############### test ################# -if __name__ == '__main__': - unittest.main() diff --git a/OpenRTM_aist/test/test_ManagerActionListener.py b/OpenRTM_aist/test/test_ManagerActionListener.py deleted file mode 100644 index ccbaa596..00000000 --- a/OpenRTM_aist/test/test_ManagerActionListener.py +++ /dev/null @@ -1,210 +0,0 @@ -#!/usr/bin/env python -# -*- Python -*- - -# -# \file test_ManagerActionListener.py -# \brief test for ManagerActionListener class -# \date $Date: 2012/01/13$ -# \author Shinji Kurihara -# -# Copyright (C) 2012 -# Task-intelligence Research Group, -# Intelligent Systems Research Institute, -# National Institute of -# Advanced Industrial Science and Technology (AIST), Japan -# All rights reserved. -# - -import sys -sys.path.insert(1,"../") - -import unittest - -from ManagerActionListener import * -import OpenRTM_aist - -class MyManagerActionListener: - def __init__(self): - return - - def preShutdown(self): - print "MyManagerActionListener.preShutdown " - return - - def postShutdown(self): - print "MyManagerActionListener.postShutdown " - return - - def preReinit(self): - print "MyManagerActionListener.preReinit " - return - - def postReinit(self): - print "MyManagerActionListener.postReinit " - return - -class MyModuleActionListener: - def preLoad(self, modname, funcname): - print "MyModuleActionListener.preLoad " - return - - def postLoad(self, modname, funcname): - print "MyModuleActionListener.postLoad " - return - - def preUnload(self, modname): - print "MyModuleActionListener.preUnload " - return - - def postUnload(self, modname): - print "MyModuleActionListener.postUnload " - return - -class MyRtcLifecycleActionListener: - def preCreate(self, args): - print "MyRtcLifecycleActionListener.preCreate " - return - - def postCreate(self, args): - print "MyRtcLifecycleActionListener.postCreate " - return - - def preConfigure(self, prop): - print "MyRtcLifecycleActionListener.preConfigure " - return - - def postConfigure(self, prop): - print "MyRtcLifecycleActionListener.postConfigure " - return - - def preInitialize(self): - print "MyRtcLifecycleActionListener.preInitialize " - return - - def postInitialize(self): - print "MyRtcLifecycleActionListener.postInitialize " - return - -class MyNamingActionListener: - def preBind(self, rtobj, name): - print "MyNamingActionListener.preBind " - return - - def postBind(self, rtobj, name): - print "MyNamingActionListener.postBind " - return - - def preUnbind(self, rtobj, name): - print "MyNamingActionListener.preUnbind " - return - - def postUnbind(self, rtobj, name): - print "MyNamingActionListener.postUnbind " - return - -class MyLocalServiceActionListener: - def preServiceRegister(self, service_name): - print "MyLocalServiceActionListener.preServiceRegister " - return - - def postServiceRegister(self, service_name, service): - print "MyLocalServiceActionListener.postServiceRegister " - return - - def preServiceInit(self, prop, service): - print "MyLocalServiceActionListener.preServiceInit " - return - - def postServiceInit(self, prop, service): - print "MyLocalServiceActionListener.postServiceInit " - return - - def preServiceReinit(self, prop, service): - print "MyLocalServiceActionListener.preServiceReinit " - return - - def postServiceReinit(self, prop, service): - print "MyLocalServiceActionListener.postServiceReinit " - return - - def preServiceFinalize(self, service_name, service): - print "MyLocalServiceActionListener.preServiceFinalize " - return - - def postServiceFinalize(self, service_name, service): - print "MyLocalServiceActionListener.postServiceFinalize " - return - - - - -class TestManagerActionListener(unittest.TestCase): - def setUp(self): - self.ma_listeners = ManagerActionListeners() - return - - def tearDown(self): - OpenRTM_aist.Manager.instance().shutdownManager() - return - - def test_ManagerActionListenerHolder(self): - listener = MyManagerActionListener() - self.ma_listeners.manager_.addListener(listener, True) - self.ma_listeners.manager_.preShutdown() - self.ma_listeners.manager_.postShutdown() - self.ma_listeners.manager_.preReinit() - self.ma_listeners.manager_.postReinit() - self.ma_listeners.manager_.removeListener(listener) - return - - def test_ModuleActionListenerHolder(self): - listener = MyModuleActionListener() - self.ma_listeners.module_.addListener(listener, True) - self.ma_listeners.module_.preLoad("test_mod", "test_preLoad") - self.ma_listeners.module_.postLoad("test_mod", "test_postLoad") - self.ma_listeners.module_.preUnload("test_mod") - self.ma_listeners.module_.postUnload("test_mod") - self.ma_listeners.module_.removeListener(listener) - return - - def test_RtcLifecycleActionListenerHolder(self): - listener = MyRtcLifecycleActionListener() - self.ma_listeners.rtclifecycle_.addListener(listener, True) - self.ma_listeners.rtclifecycle_.preCreate("preCreate") - self.ma_listeners.rtclifecycle_.postCreate("preCreate") - self.ma_listeners.rtclifecycle_.preConfigure("preConf") - self.ma_listeners.rtclifecycle_.postConfigure("preConf") - self.ma_listeners.rtclifecycle_.preInitialize() - self.ma_listeners.rtclifecycle_.postInitialize() - self.ma_listeners.rtclifecycle_.removeListener(listener) - return - - def test_NamingActionListenerHolder(self): - listener = MyNamingActionListener() - self.ma_listeners.naming_.addListener(listener, True) - self.ma_listeners.naming_.preBind(None,"test_rtc") - self.ma_listeners.naming_.postBind(None,"test_rtc") - self.ma_listeners.naming_.preUnbind(None,"test_rtc") - self.ma_listeners.naming_.postUnbind(None,"test_rtc") - self.ma_listeners.naming_.removeListener(listener) - return - - def test_LocalServiceActionListenerHolder(self): - listener = MyLocalServiceActionListener() - self.ma_listeners.localservice_.addListener(listener, True) - self.ma_listeners.localservice_.preServiceRegister("servicename") - self.ma_listeners.localservice_.postServiceRegister("servicename",None) - self.ma_listeners.localservice_.preServiceInit(None, "servicename") - self.ma_listeners.localservice_.postServiceInit(None, "servicename") - self.ma_listeners.localservice_.preServiceReinit(None, "servicename") - self.ma_listeners.localservice_.postServiceReinit(None, "servicename") - self.ma_listeners.localservice_.preServiceFinalize(None, "servicename") - self.ma_listeners.localservice_.postServiceFinalize(None, "servicename") - self.ma_listeners.localservice_.removeListener(listener) - return - - - -############### test ################# -if __name__ == '__main__': - unittest.main() diff --git a/OpenRTM_aist/test/test_ManagerConfig.py b/OpenRTM_aist/test/test_ManagerConfig.py deleted file mode 100755 index 23c78531..00000000 --- a/OpenRTM_aist/test/test_ManagerConfig.py +++ /dev/null @@ -1,99 +0,0 @@ -#!/usr/bin/env python -# -*- Python -*- - -# -# \file test_ManagerConfig.py -# \brief test for RTC manager configuration -# \date $Date: $ -# \author Shinji Kurihara -# -# Copyright (C) 2003 -# Task-intelligence Research Group, -# Intelligent Systems Research Institute, -# National Institute of -# Advanced Industrial Science and Technology (AIST), Japan -# All rights reserved. -# - -import sys -sys.path.insert(1,"../") - -import unittest - -import OpenRTM_aist - -from ManagerConfig import * - -configsample_spec = ["implementation_id", "ConfigSample", - "type_name", "ConfigSample", - "description", "Configuration example component", - "version", "1.0", - "vendor", "Shinji Kurihara, AIST", - "category", "example", - "activity_type", "DataFlowComponent", - "max_instance", "10", - "language", "C++", - "lang_type", "compile", - # Configuration variables - "conf.default.int_param0", "0", - "conf.default.int_param1", "1", - "conf.default.double_param0", "0.11", - "conf.default.double_param1", "9.9", - "conf.default.str_param0", "hoge", - "conf.default.str_param1", "dara", - "conf.default.vector_param0", "0.0,1.0,2.0,3.0,4.0", - ""] - -class TestManagerConfig(unittest.TestCase) : - - def setUp(self): - argv = (sys.argv[0], "-f", "./rtc.conf") - self.mgrConf = ManagerConfig(argv) - - - def tearDown(self): - OpenRTM_aist.Manager.instance().shutdownManager() - return - - def test_configure(self): - prop = OpenRTM_aist.Properties(defaults_str=configsample_spec) - self.mgrConf.configure(prop) - self.assertEqual(prop.getProperty("type_name"),"ConfigSample","Result failed.") - - - def test_parseArgs(self): - argv = (sys.argv[0], "-f", "./rtc.conf") - self.mgrConf.parseArgs(argv) - - # Failed Pattern - # argv = (sys.argv[0], "-c", "./rtc.conf") - # self.mgrConf.parseArgs(3,argv) - - - def test_findConfigFile(self): - self.assertEqual(self.mgrConf.findConfigFile(),True,"Result failed.") - - - def test_setSystemInformation(self): - prop = OpenRTM_aist.Properties(defaults_str=configsample_spec) - # Failed Pattern - # self.assertEqual(prop.getProperty("manager.os.name"),"Linux","Result failed.") - - prop = self.mgrConf.setSystemInformation(prop) - self.assertEqual(prop.getProperty("manager.os.name"),"Linux","Result failed.") - #self.assertEqual(prop.getProperty("manager.os.name"),"Windows","Result failed.") - - - def test_fileExist(self): - self.assertEqual(self.mgrConf.fileExist("rtc.conf"),True,"Result failed.") - self.assertEqual(self.mgrConf.fileExist("./rtc.conf"),True,"Result failed.") - - # Failed Pattern - # self.assertEqual(self.mgrConf.fileExist("../rtc.conf"),True,"Result failed.") - - -############### test ################# -if __name__ == '__main__': - unittest.main() - - diff --git a/OpenRTM_aist/test/test_ManagerServant.py b/OpenRTM_aist/test/test_ManagerServant.py deleted file mode 100755 index 25b4889f..00000000 --- a/OpenRTM_aist/test/test_ManagerServant.py +++ /dev/null @@ -1,231 +0,0 @@ -#!/usr/bin/env python -# -*- coding: euc-jp -*- - -# -# \file test_ManagerServant.py -# \brief test for ManagerServant class -# \date $Date: $ -# \author Shinji Kurihara -# -# Copyright (C) 2006 -# Task-intelligence Research Group, -# Intelligent Systems Research Institute, -# National Institute of -# Advanced Industrial Science and Technology (AIST), Japan -# All rights reserved. -# - -import sys,time -sys.path.insert(1,"../RTM_IDL") -sys.path.insert(1,"../") - -import unittest -from omniORB import CORBA - -#from Manager import * -import OpenRTM_aist -import RTC, RTC__POA -import RTM, RTM__POA - -configsample_spec = ["implementation_id", "TestComp", - "type_name", "TestComp", - "description", "Test example component", - "version", "1.0", - "vendor", "Shinji Kurihara, AIST", - "category", "example", - "activity_type", "DataFlowComponent", - "max_instance", "10", - "language", "Python", - "lang_type", "compile", - # Configuration variables - "conf.default.int_param0", "0", - "conf.default.int_param1", "1", - "conf.default.double_param0", "0.11", - "conf.default.double_param1", "9.9", - "conf.default.str_param0", "hoge", - "conf.default.str_param1", "dara", - "conf.default.vector_param0", "0.0,1.0,2.0,3.0,4.0", - ""] - -com = None - -class TestComp(OpenRTM_aist.DataFlowComponentBase): - def __init_(self, manager): - OpenRTM_aist.DataFlowComponentBase.__init__(self, manager) - - -def TestCompInit(manager): - print "TestCompInit" - global com - profile = OpenRTM_aist.Properties(defaults_str=configsample_spec) - manager.registerFactory(profile, - TestComp, - OpenRTM_aist.Delete) - com = manager.createComponent("TestComp") - -def TestEcInit(manager): - profile = OpenRTM_aist.Properties(defaults_str=configsample_spec) - print manager.registerECFactory("Art", - TestComp, - OpenRTM_aist.Delete) - manager.createComponent("TestEc") - - -class TestManagerServant(unittest.TestCase): - - def setUp(self): - self.managerservant = OpenRTM_aist.ManagerServant() - - def tearDown(self): - self.managerservant.__del__() - del self.managerservant - #OpenRTM_aist.Manager.instance().shutdownManager() - OpenRTM_aist.Manager.instance().shutdown() - time.sleep(0.1) - return - - """ - def test_terminate(self): - self.managerservant.terminate() - - def test_shutdown(self): - self.managerservant.runManager(True) - import time - time.sleep(0.1) - self.managerservant.shutdown() - #self.managerservant.runManager() - """ - - def test_load_unload(self): - self.managerservant.load_module("hoge", "echo") - self.assertNotEqual(len(self.managerservant.get_loaded_modules()), 0) - self.assertNotEqual(len(self.managerservant.get_loadable_modules()), 0) - self.managerservant.unload_module("hoge") - return - - def test_get_loaded_modules(self): - self.assertEqual(self.managerservant.get_loaded_modules(),[]) - return - - def test_get_loadable_modules(self): - self.assertNotEqual(self.managerservant.get_loadable_modules(),[]) - return - - - def test_get_factory_profiles(self): - self.managerservant.get_factory_profiles() - return - - def test_create_component(self): - mgr=OpenRTM_aist.Manager.init(sys.argv) - mgr.activateManager() - self.managerservant.load_module("test_ManagerServant", "TestCompInit") - com = self.managerservant.create_component("TestComp") - self.managerservant.unload_module("test_ManagerServant") - self.assertNotEqual(com,None) - self.managerservant.delete_component("TestComp") - mgr.shutdownComponents() - return - - - def test_get_components(self): - self.assertEqual(self.managerservant.get_components(),[]) - return - - - def test_get_component_profiles(self): - self.assertEqual(self.managerservant.get_component_profiles(),[]) - return - - - def test_get_profile(self): - self.managerservant.get_profile() - return - - def test_get_configuration(self): - self.managerservant.get_configuration() - return - - def test_set_configuration(self): - self.assertEqual(self.managerservant.set_configuration("test_name", "test_value"),RTC.RTC_OK) - return - - - def test_get_service(self): - self.assertEqual(self.managerservant.get_service("test"),CORBA.Object._nil) - return - - - def test_getObjRef(self): - if not self.managerservant.createINSManager(): - poa=OpenRTM_aist.Manager.instance().getORB().resolve_initial_references("omniINSPOA") - poa.deactivate_object(OpenRTM_aist.Manager.instance().getConfig().getProperty("manager.name")) - self.assertEqual(self.managerservant.createINSManager(),True) - else: - self.assertEqual(self.managerservant.createINSManager(),False) - self.assertNotEqual(self.managerservant.getObjRef(),CORBA.Object._nil) - return - - def test_is_master(self): - self.assertEqual(self.managerservant.is_master(),False) - return - - def test_get_master_managers(self): - self.assertEqual(len(self.managerservant.get_master_managers()),0) - return - - def test_master_manager(self): - if not self.managerservant.createINSManager(): - poa=OpenRTM_aist.Manager.instance().getORB().resolve_initial_references("omniINSPOA") - poa.deactivate_object(OpenRTM_aist.Manager.instance().getConfig().getProperty("manager.name")) - self.assertEqual(self.managerservant.createINSManager(),True) - else: - self.assertEqual(self.managerservant.createINSManager(),False) - self.assertEqual(len(self.managerservant.get_master_managers()),0) - host_port = "localhost:2810" - owner = self.managerservant.findManager(host_port) - self.assertEqual(self.managerservant.add_master_manager(owner),RTC.RTC_OK) - self.assertEqual(len(self.managerservant.get_master_managers()),1) - self.assertEqual(self.managerservant.remove_master_manager(owner),RTC.RTC_OK) - self.assertEqual(len(self.managerservant.get_master_managers()),0) - - return - - - def test_slave_managers(self): - if not self.managerservant.createINSManager(): - poa=OpenRTM_aist.Manager.instance().getORB().resolve_initial_references("omniINSPOA") - poa.deactivate_object(OpenRTM_aist.Manager.instance().getConfig().getProperty("manager.name")) - self.assertEqual(self.managerservant.createINSManager(),True) - else: - self.assertEqual(self.managerservant.createINSManager(),False) - self.assertEqual(len(self.managerservant.get_slave_managers()),0) - host_port = "localhost:2810" - owner = self.managerservant.findManager(host_port) - self.assertEqual(self.managerservant.add_slave_manager(owner),RTC.RTC_OK) - self.assertEqual(len(self.managerservant.get_slave_managers()),1) - self.assertEqual(self.managerservant.remove_slave_manager(owner),RTC.RTC_OK) - self.assertEqual(len(self.managerservant.get_slave_managers()),0) - return - - -""" - def test_forck(self): - self.assertEqual(self.managerservant.fork(),RTC.RTC_OK) - return - - def test_shutdown(self): - #self.assertEqual(self.managerservant.shutdown(),RTC.RTC_OK) - return - - def test_restart(self): - self.assertEqual(self.managerservant.restart(),RTC.RTC_OK) - return - -""" - - - -############### test ################# -if __name__ == '__main__': - unittest.main() diff --git a/OpenRTM_aist/test/test_ModuleManager.py b/OpenRTM_aist/test/test_ModuleManager.py deleted file mode 100755 index 12bf2838..00000000 --- a/OpenRTM_aist/test/test_ModuleManager.py +++ /dev/null @@ -1,181 +0,0 @@ -#!/usr/bin/env python -# -*- Python -*- - -# -# \file test_ModulesManager.py -# \brief Loadable modules manager class -# \date $Date: $ -# \author Shinji Kurihara -# -# Copyright (C) 2006 -# Task-intelligence Research Group, -# Intelligent Systems Research Institute, -# National Institute of -# Advanced Industrial Science and Technology (AIST), Japan -# All rights reserved. -# - -import sys,os -sys.path.insert(1,"../") - -import unittest - -import OpenRTM_aist - -from ModuleManager import * - -configsample_spec = ["implementation_id", "ConfigSample", - "type_name", "ConfigSample", - "description", "Configuration example component", - "version", "1.0", - "vendor", "Shinji Kurihara, AIST", - "category", "example", - "activity_type", "DataFlowComponent", - "max_instance", "10", - "language", "Python", - "lang_type", "script", - # Configuration variables - "conf.default.int_param0", "0", - "conf.default.int_param1", "1", - "conf.default.double_param0", "0.11", - "conf.default.double_param1", "9.9", - "conf.default.str_param0", "hoge", - "conf.default.str_param1", "dara", - "conf.default.vector_param0", "0.0,1.0,2.0,3.0,4.0", - "manager.modules.abs_path_allowed", "YES", - ""] - - -class TestModuleManager(unittest.TestCase): - def setUp(self): - self.mm = ModuleManager(OpenRTM_aist.Properties(defaults_str=configsample_spec)) - - def tearDown(self): - del self.mm - OpenRTM_aist.Manager.instance().shutdownManager() - - - def test_load_unload(self): - try: - path = os.getcwd() - self.mm.load(path+"/hoge.py","echo") - self.mm.unload(path+"/hoge.py") - - self.mm.load("hoge","echo") - self.mm.unload("hoge") - - self.mm.load("hoge.py","echo") - self.mm.unload("hoge.py") - - self.mm.load("./hoge.py","echo") - self.mm.unload("./hoge.py") - - # Failure Pattern - #self.mm.load("sample") - except: - print "exception." - return - - - def test_unloadAll(self): - self.mm.unloadAll() - return - - - def test_symbol(self): - path = os.getcwd() - self.mm.load(path+"/hoge.py","echo") - self.mm.symbol(path+"/hoge.py","echo")() - self.mm.unload(path+"/hoge.py") - - self.mm.load("hoge","echo") - self.mm.symbol("hoge","echo")() - self.mm.unload("hoge") - - self.mm.load("hoge.py","echo") - self.mm.symbol("hoge.py","echo")() - self.mm.unload("hoge.py") - - - def test_setLoadpath(self): - self.mm.setLoadpath(["/usr/lib/python/site-packages","."]) - return - - def test_getLoadPath(self): - self.mm.setLoadpath(["/usr/lib/python/site-packages","."]) - self.assertEqual(self.mm.getLoadPath()[0],"/usr/lib/python/site-packages") - return - - - def test_addLoadpath(self): - self.mm.setLoadpath(["/usr/lib/python/site-packages","."]) - self.mm.addLoadpath(["/usr/local/lib/python/site-packages"]) - self.assertEqual(self.mm.getLoadPath()[0],"/usr/lib/python/site-packages") - self.assertEqual(self.mm.getLoadPath()[-1],"/usr/local/lib/python/site-packages") - return - - - def test_getLoadedModules(self): - self.mm.load("hoge","echo") - self.assertNotEqual(self.mm.getLoadedModules()[0],None) - return - - - def test_allowAbsolutePath(self): - self.mm.allowAbsolutePath() - return - - - def test_disallowAbsolutePath(self): - self.mm.disallowAbsolutePath() - return - - - def test_allowModuleDownload(self): - self.mm.allowModuleDownload() - return - - - def test_disallowModuleDownload(self): - self.mm.disallowModuleDownload() - return - - - def test_findFile(self): - self.assertEqual(self.mm.findFile("hoge",["."]),"hoge") - self.assertEqual(self.mm.findFile("hoge.py",["."]),"hoge.py") - self.assertEqual(self.mm.findFile("hogehoge",["."]),"") - return - - - def test_fileExist(self): - self.assertEqual(self.mm.fileExist("hoge.py"),True) - self.assertEqual(self.mm.fileExist("./hoge.py"),True) - self.assertEqual(self.mm.fileExist("hoge"),True) - self.assertEqual(self.mm.fileExist("./hoge"),True) - self.assertEqual(self.mm.fileExist("hogehoge"),False) - return - - - def test_getInitFuncName(self): - self.mm.getInitFuncName("hoge.py") - return - - - def test_getRtcProfile(self): - self.assertEqual(self.mm._ModuleManager__getRtcProfile("./ConfigSample.py"),None) - self.assertEqual(self.mm._ModuleManager__getRtcProfile("ConfigSample.py"),None) - self.assertEqual(self.mm._ModuleManager__getRtcProfile("ConfigSample"),None) - return - - - def test_getLoadableModules(self): - self.mm.setLoadpath([".","./","../"]) - self.assertNotEqual(self.mm.getLoadableModules(),[]) - return - - - -############### test ################# -if __name__ == '__main__': - unittest.main() diff --git a/OpenRTM_aist/test/test_NVUtil.py b/OpenRTM_aist/test/test_NVUtil.py deleted file mode 100755 index ead19ec8..00000000 --- a/OpenRTM_aist/test/test_NVUtil.py +++ /dev/null @@ -1,172 +0,0 @@ -#!/usr/bin/env python -# -*- Python -*- - -# \file test_NVUtil.py -# \brief test for NameValue and NVList utility functions -# \date $Date: 2007/09/11$ -# \author Shinji Kurihara -# -# Copyright (C) 2006 -# Noriaki Ando -# Task-intelligence Research Group, -# Intelligent Systems Research Institute, -# National Institute of -# Advanced Industrial Science and Technology (AIST), Japan -# All rights reserved. - -from omniORB import * -from omniORB import any -import sys -sys.path.insert(1,"../") - -import unittest -import OpenRTM_aist -import SDOPackage, SDOPackage__POA - -from NVUtil import * - -configsample_spec = ["implementation_id", "ConfigSample", - "type_name", "ConfigSample", - "description", "Configuration example component", - "version", "1.0", - "vendor", "Shinji Kurihara, AIST", - "category", "example", - "activity_type", "DataFlowComponent", - "max_instance", "10", - "language", "C++", - "lang_type", "compile", - # Configuration variables - "conf.default.int_param0", "0", - "conf.default.int_param1", "1", - "conf.default.double_param0", "0.11", - "conf.default.double_param1", "9.9", - "conf.default.str_param0", "hoge", - "conf.default.str_param1", "dara", - "conf.default.vector_param0", "0.0,1.0,2.0,3.0,4.0", - ""] - -class TestNVUtil(unittest.TestCase): - def setUp(self): - pass - - def tearDown(self): - OpenRTM_aist.Manager.instance().shutdownManager() - return - - def test_newNV(self): - self.assertEqual(newNV("long", 1).name, "long") - self.assertEqual(newNV("long", 1).value.value(), 1) - self.assertEqual(newNV("float", 1.2345).name, "float") - self.assertEqual(newNV("float", 1.2345).value.value(), 1.2345) - self.assertEqual(newNV("string", "test").name, "string") - self.assertEqual(newNV("string", "test").value.value(), "test") - - - def test_newNVBool(self): - self.assertEqual(newNV("bool", True).name, "bool") - self.assertEqual(newNV("bool", True).value.value(), True) - - - def test_newNVOctet(self): - self.assertEqual(newNV("oct", 0x01).name, "oct") - self.assertEqual(newNV("oct", 0x01).value.value(), 0x01) - - - def test_newNVAny(self): - import omniORB.any - self.assertEqual(omniORB.any.from_any(newNV("any",omniORB.any.to_any(12345)).value), 12345) - - - def test_copyFromProperties(self): - prop = OpenRTM_aist.Properties(defaults_str=configsample_spec) - nv = [] - copyFromProperties(nv, prop) - self.assertEqual(nv[0].name, "implementation_id") - self.assertEqual(nv[0].value.value(), "ConfigSample") - nv = [1,2,3] - copyFromProperties(nv, prop) - self.assertEqual(nv[0].name, "implementation_id") - self.assertEqual(nv[0].value.value(), "ConfigSample") - - - def test_copyToProperties(self): - nv = [newNV("id0",0),newNV("id1",1),newNV("id2",2),newNV("id3",3)] - prop = OpenRTM_aist.Properties(defaults_str=configsample_spec) - copyToProperties(prop, nv) - self.assertEqual(prop.getProperty("id0"), "0") - self.assertEqual(prop.getProperty("id1"), "1") - self.assertEqual(prop.getProperty("id2"), "2") - self.assertEqual(prop.getProperty("id3"), "3") - - - def test_toProperties(self): - nv = [newNV("id0",0),newNV("id1",1),newNV("id2",2),newNV("id3",3)] - prop = toProperties(nv) - self.assertEqual(prop.getProperty("id0").value(), 0) - self.assertEqual(prop.getProperty("id1").value(), 1) - self.assertEqual(prop.getProperty("id2").value(), 2) - self.assertEqual(prop.getProperty("id3").value(), 3) - - - def test_find(self): - nv = [newNV("id0",0),newNV("id1",1),newNV("id2",2),newNV("id3",3)] - self.assertEqual(find(nv,"id0").value(), 0) - self.assertEqual(find(nv,"id1").value(), 1) - self.assertEqual(find(nv,"id2").value(), 2) - self.assertEqual(find(nv,"id3").value(), 3) - - - def test_find_index(self): - nv = [newNV("id0",0),newNV("id1",1),newNV("id2",2),newNV("id3",3)] - self.assertEqual(find_index(nv,"id0"),0) - self.assertEqual(find_index(nv,"id1"),1) - self.assertEqual(find_index(nv,"id2"),2) - self.assertEqual(find_index(nv,"id3"),3) - - - def test_isString(self): - nv = [newNV("float",1.234),newNV("long",1234),newNV("string","test"),newNV("oct",0x01)] - self.assertEqual(isString(nv,"float"),False) - self.assertEqual(isString(nv,"long"),False) - self.assertEqual(isString(nv,"string"),True) - self.assertEqual(isString(nv,"oct"),False) - - - def test_isStringValue(self): - nv = [newNV("float",1.234),newNV("long",1234),newNV("string","test"),newNV("oct",0x01)] - self.assertEqual(isStringValue(nv,"float",1.234),False) - self.assertEqual(isStringValue(nv,"long",1234),False) - self.assertEqual(isStringValue(nv,"string","test"),True) - self.assertEqual(isStringValue(nv,"oct",0x01),False) - - - def test_toString(self): - nv = [newNV("float",1.234),newNV("long",1234),newNV("string","test"),newNV("oct",0x01)] - self.assertEqual(toString(nv,"float"),"") - self.assertEqual(toString(nv,"long"),"") - self.assertEqual(toString(nv,"string"),"test") - self.assertEqual(toString(nv,"oct"),"") - - - def test_appendStringValue(self): - nv = [newNV("string","test0, test1, test2")] - self.assertEqual(appendStringValue(nv,"string","test2"),True) - self.assertEqual(any.from_any(nv[0].value),"test0, test1, test2") - self.assertEqual(appendStringValue(nv,"string","test3"),True) - self.assertEqual(any.from_any(nv[0].value),"test0, test1, test2, test3") - - - def test_append(self): - list_ = [1,2,3] - append(list_,[4,5,6]) - self.assertEqual(list_,[1,2,3,4,5,6]) - - - def test_dump(self): - nv = [newNV("string","test0, test1, test2")] - dump(nv) - - -############### test ################# -if __name__ == '__main__': - unittest.main() diff --git a/OpenRTM_aist/test/test_NamingManager.py b/OpenRTM_aist/test/test_NamingManager.py deleted file mode 100755 index 17630275..00000000 --- a/OpenRTM_aist/test/test_NamingManager.py +++ /dev/null @@ -1,125 +0,0 @@ -#!/usr/bin/env python -# -*- Python -*- - -# -# \file test_NamingManager.py -# \brief test for naming Service helper class -# \date $Date: 2007/08/27$ -# \author Shinji Kurihara -# -# Copyright (C) 2006 -# Task-intelligence Research Group, -# Intelligent Systems Research Institute, -# National Institute of -# Advanced Industrial Science and Technology (AIST), Japan -# All rights reserved. -# - -import sys -sys.path.insert(1,"../") -from omniORB import CORBA - -import unittest - -import OpenRTM_aist - -from NamingManager import * - - -class test_comp(OpenRTM_aist.RTObject_impl): - def __init__(self): - pass - - def echo(self, msg): - print msg - return msg - -class TestNamingManager(unittest.TestCase): - - def setUp(self): - self._mgr = OpenRTM_aist.Manager.init(sys.argv) - self._nm = NamingManager(self._mgr) - self._obj = test_comp() - self._mgrservant = OpenRTM_aist.ManagerServant() - def __del__(self): - pass - - def test_bindObject(self): - self._noc.bindObject("test_comp",self._obj) - return - - def test_unbindObject(self): - self._noc.unbindObject("test_comp") - return - - - def test_registerNameServer(self): - self._nm.registerNameServer("test_comp","localhost") - return - - def test_bindObject(self): - self._nm.bindObject("test_comp",self._obj) - self._nm.registerNameServer("test_comp","localhost") - self._nm.bindObject("test_comp",self._obj) - return - - def test_bindManagerObject(self): - self._nm.bindManagerObject("test_mgr",self._mgrservant) - self._nm.registerNameServer("test_comp","localhost") - self._nm.bindManagerObject("test_mgr",self._mgrservant) - - def test_update(self): - self._nm.update() - self._nm.registerNameServer("test_comp","localhost") - self._nm.update() - return - - def test_unbindObject(self): - self._nm.unbindObject("test_comp") - self._nm.registerNameServer("test_comp","localhost") - self._nm.unbindObject("test_comp") - return - - def test_unbindAll(self): - self._nm.unbindAll() - self._nm.registerCompName("rest",self._obj) - self._nm.unbindAll() - self._nm.registerMgrName("rest",self._mgrservant) - self._nm.unbindAll() - return - - def test_getObjects(self): - self._nm.bindObject("test_comp",self._obj) - self.assertEqual(len(self._nm.getObjects()),1) - return - - def test_createNamingObj(self): - self._nm.createNamingObj("test", "localhost") - return - - def test_bindCompsTo(self): - self._nm.bindCompsTo(self._obj) - return - - def test_registerCompName(self): - self._nm.registerCompName("rest",self._obj) - return - - def test_registerMgrName(self): - self._nm.registerMgrName("rest",self._mgrservant) - return - - def test_unregisterCompName(self): - self._nm.registerCompName("rest",self._obj) - self._nm.unregisterCompName("rest") - return - - def test_unregisterMgrName(self): - self._nm.registerMgrName("rest",self._mgrservant) - self._nm.unregisterMgrName("rest") - return - - -############### test ################# -if __name__ == '__main__': - unittest.main() diff --git a/OpenRTM_aist/test/test_NumberingPolicy.py b/OpenRTM_aist/test/test_NumberingPolicy.py deleted file mode 100755 index 76e91588..00000000 --- a/OpenRTM_aist/test/test_NumberingPolicy.py +++ /dev/null @@ -1,57 +0,0 @@ -#!/usr/bin/env python -# -*- Python -*- - -# -# \file test_NumberingPolicy.py -# \brief Object numbering policy class -# \date $Date: 2007/08/23$ -# \author Shinji Kurihara -# -# Copyright (C) 2006 -# Task-intelligence Research Group, -# Intelligent Systems Research Institute, -# National Institute of -# Advanced Industrial Science and Technology (AIST), Japan -# All rights reserved. -# - -import sys -sys.path.insert(1,"../") - -import unittest - -from NumberingPolicy import * -import OpenRTM_aist - - -class TestDefaultNumberingPolicy(unittest.TestCase): - def setUp(self): - self.__dnp = DefaultNumberingPolicy() - - def tearDown(self): - OpenRTM_aist.Manager.instance().shutdownManager() - return - - def test_onCreate(self): - self.assertEqual(self.__dnp.onCreate("test0"),"0") - self.assertEqual(self.__dnp.onCreate("test1"),"1") - self.assertEqual(self.__dnp.onCreate("test1"),"2") - - - - def test_onDelete(self): - self.__dnp.onCreate("test") - self.__dnp.onCreate("test0") - self.__dnp.onDelete("test") - self.assertEqual(self.__dnp.onCreate("test1"),"0") - self.assertEqual(self.__dnp.onCreate("test"),"2") - - - - def test_find(self): - pass - - -############### test ################# -if __name__ == '__main__': - unittest.main() diff --git a/OpenRTM_aist/test/test_NumberingPolicy_node.py b/OpenRTM_aist/test/test_NumberingPolicy_node.py deleted file mode 100644 index afa19dcf..00000000 --- a/OpenRTM_aist/test/test_NumberingPolicy_node.py +++ /dev/null @@ -1,136 +0,0 @@ -#!/usr/bin/env python -# -*- coding: euc-jp -*- - -# -# \file test_NumberingPolicy_node.py -# \brief -# \date $Date: $ -# \author Nobuhiko Miyamoto -# - - -import sys -sys.path.insert(1,"../") - -try: - import unittest2 as unittest -except (ImportError): - import unittest - -import time - -#from Manager import * -import OpenRTM_aist -import RTC, RTC__POA -import multiprocessing - -testcomp1_spec = ["implementation_id", "TestComp1", - "type_name", "TestComp1", - "description", "Test example component", - "version", "1.0", - "vendor", "Nobuhiko Myiyamoto", - "category", "example", - "activity_type", "DataFlowComponent", - "max_instance", "10", - "language", "C++", - "lang_type", "compile", - "conf.default.test1", "0", - ""] - - - - - - - - -def TestComp1Init(manager): - profile = OpenRTM_aist.Properties(defaults_str=testcomp1_spec) - manager.registerFactory(profile, - OpenRTM_aist.DataFlowComponentBase, - OpenRTM_aist.Delete) - - - - - - -def TestComp1ModuleInit(manager): - TestComp1Init(manager) - com = manager.createComponent("TestComp1") - - - - -def runTestComp2(q): - - argv = [""] - argv.extend(['-d']) - argv.extend(['-o','manager.components.naming_policy:node_unique']) - argv.extend(['-o','naming.type:corba,manager']) - - - manager = OpenRTM_aist.Manager.init(argv) - manager.setModuleInitProc(TestComp1ModuleInit) - manager.activateManager() - - - q.get() - - comps = manager.getComponents()[:] - for comp in comps: - manager.unregisterComponent(comp) - comp_id = comp.getProperties() - factory = manager._factory.find(comp_id) - factory.destroy(comp) - manager.shutdownNaming() - time.sleep(0.1) - - -class Test_NumberingPolicy_node(unittest.TestCase): - - def setUp(self): - self.queue = multiprocessing.Queue() - self.outport_process = multiprocessing.Process(target=runTestComp2, args=(self.queue,)) - self.outport_process.start() - - time.sleep(1) - sys.argv.extend(['-o','manager.components.naming_policy:node_unique']) - sys.argv.extend(['-o','naming.type:corba,manager']) - #sys.argv.extend(['-o','manager.instance_name: manager2']) - self.manager = OpenRTM_aist.Manager.init(sys.argv) - self.manager.setModuleInitProc(TestComp1ModuleInit) - self.manager.activateManager() - - - def tearDown(self): - self.queue.put("") - comps = self.manager.getComponents()[:] - for comp in comps: - self.manager.unregisterComponent(comp) - comp_id = comp.getProperties() - factory = self.manager._factory.find(comp_id) - factory.destroy(comp) - self.manager.shutdownNaming() - time.sleep(0.1) - - def test_getComponent(self): - #prop = OpenRTM_aist.Properties() - #pp = self.manager.getManagerServant().get_profile().properties - #OpenRTM_aist.NVUtil.copyToProperties(prop, pp) - #print prop - comp = self.manager.getComponent("TestComp11") - self.assertTrue(comp is not None) - - self.__dnp = OpenRTM_aist.NodeNumberingPolicy() - num = self.__dnp.onCreate(comp) - self.assertEqual(num,"2") - - - - - - -############### test ################# -if __name__ == '__main__': - unittest.main() diff --git a/OpenRTM_aist/test/test_NumberingPolicy_ns.py b/OpenRTM_aist/test/test_NumberingPolicy_ns.py deleted file mode 100644 index 77a5c70c..00000000 --- a/OpenRTM_aist/test/test_NumberingPolicy_ns.py +++ /dev/null @@ -1,129 +0,0 @@ -#!/usr/bin/env python -# -*- coding: euc-jp -*- - -# -# \file test_NumberingPolicy_ns.py -# \brief -# \date $Date: $ -# \author Nobuhiko Miyamoto -# - - -import sys -sys.path.insert(1,"../") - -try: - import unittest2 as unittest -except (ImportError): - import unittest - -import time - -#from Manager import * -import OpenRTM_aist -import RTC, RTC__POA -import multiprocessing - -testcomp1_spec = ["implementation_id", "TestComp1", - "type_name", "TestComp1", - "description", "Test example component", - "version", "1.0", - "vendor", "Nobuhiko Myiyamoto", - "category", "example", - "activity_type", "DataFlowComponent", - "max_instance", "10", - "language", "C++", - "lang_type", "compile", - "conf.default.test1", "0", - ""] - - - - - - - - - - - - - -def TestComp1Init(manager): - profile = OpenRTM_aist.Properties(defaults_str=testcomp1_spec) - manager.registerFactory(profile, - OpenRTM_aist.DataFlowComponentBase, - OpenRTM_aist.Delete) - - - - - - -def TestComp1ModuleInit(manager): - TestComp1Init(manager) - com = manager.createComponent("TestComp1") - - - - -def runTestComp2(q): - - argv = [""] - argv.extend(['-d']) - argv.extend(['-o','manager.components.naming_policy:ns_unique']) - - - manager = OpenRTM_aist.Manager.init(argv) - manager.setModuleInitProc(TestComp1ModuleInit) - manager.activateManager() - - - q.get() - - comps = manager.getComponents()[:] - for comp in comps: - manager.unregisterComponent(comp) - comp_id = comp.getProperties() - factory = manager._factory.find(comp_id) - factory.destroy(comp) - manager.shutdownNaming() - time.sleep(0.1) - - -class Test_NumberingPolicy_ns(unittest.TestCase): - - def setUp(self): - self.queue = multiprocessing.Queue() - self.outport_process = multiprocessing.Process(target=runTestComp2, args=(self.queue,)) - self.outport_process.start() - - time.sleep(1) - sys.argv.extend(['-o','manager.components.naming_policy:ns_unique']) - self.manager = OpenRTM_aist.Manager.init(sys.argv) - self.manager.setModuleInitProc(TestComp1ModuleInit) - self.manager.activateManager() - - - def tearDown(self): - self.queue.put("") - comps = self.manager.getComponents()[:] - for comp in comps: - self.manager.unregisterComponent(comp) - comp_id = comp.getProperties() - factory = self.manager._factory.find(comp_id) - factory.destroy(comp) - self.manager.shutdownNaming() - time.sleep(0.1) - - def test_getComponent(self): - comp = self.manager.getComponent("TestComp11") - self.assertTrue(comp is not None) - - self.__dnp = OpenRTM_aist.NamingServiceNumberingPolicy() - num = self.__dnp.onCreate(comp) - self.assertEqual(num,"2") - -############### test ################# -if __name__ == '__main__': - unittest.main() diff --git a/OpenRTM_aist/test/test_ObjectManager.py b/OpenRTM_aist/test/test_ObjectManager.py deleted file mode 100755 index cbdd7113..00000000 --- a/OpenRTM_aist/test/test_ObjectManager.py +++ /dev/null @@ -1,117 +0,0 @@ -#!/usr/bin/env python -# -*- Python -*- - -# -# @file test_ObjectManager.py -# @brief test for Object management class -# @date $Date: $ -# @author Shinji Kurihara -# -# Copyright (C) 2003-2007 -# Task-intelligence Research Group, -# Intelligent Systems Research Institute, -# National Institute of -# Advanced Industrial Science and Technology (AIST), Japan -# All rights reserved. -# -# $Id: $ -# - -import sys -sys.path.insert(1,"../") - -import unittest - -from ObjectManager import * -import OpenRTM_aist - -class test_obj: - def __init__(self, name): - self.name = name - - def getInstanceName(self): - return self.name - - def getProperty(self,name): - return name - - -class TestObjectManager(unittest.TestCase): - - class InstanceName : - def __init__(self, name=None, factory=None): - if factory != None: - self._name = factory.getInstanceName() - elif name != None: - self._name = name - - #def func(self, factory): - def __call__(self, factory): - return self._name == factory.getInstanceName() - - - class ModuleFactories : - def __init__(self): - self._modlist = [] - - - #def func(self, f): - def __call__(self, f): - self._modlist.append(f.getProperty("implementation_id")) - - - def setUp(self): - self.obj = ObjectManager(self.InstanceName) - - - def tearDown(self): - OpenRTM_aist.Manager.instance().shutdownManager() - return - - def test_registerObject(self): - obj = test_obj("test") - self.assertEqual(self.obj.registerObject(obj),True,"Result failed.") - self.assertEqual(self.obj.registerObject(obj),False,"Result failed.") - - - def test_unregisterObject(self): - self.test_registerObject() - self.assertEqual(self.obj.unregisterObject("test").getInstanceName(),"test","Result failed.") - self.assertEqual(self.obj.unregisterObject("test"),None,"Result failed.") - # Failed Pattern - # self.assertEqual(self.obj.unregisterObject("test").getInstanceName(),"test","Result failed.") - - - def test_find(self): - self.test_registerObject() - self.assertEqual(self.obj.find("test").getInstanceName(),"test","Result failed.") - self.assertEqual(self.obj.find("testtest"),None,"Result failed.") - - - def test_getObjects(self): - obj = test_obj("test0") - self.obj.registerObject(obj) - obj = test_obj("test1") - self.obj.registerObject(obj) - obj = test_obj("test2") - self.obj.registerObject(obj) - self.assertEqual(len(self.obj.getObjects()),3,"Result failed.") - self.assertEqual(self.obj.getObjects()[0].getInstanceName(),"test0","Result failed.") - self.assertEqual(self.obj.getObjects()[1].getInstanceName(),"test1","Result failed.") - self.assertEqual(self.obj.getObjects()[2].getInstanceName(),"test2","Result failed.") - - - def test_for_each(self): - obj = test_obj("test0") - self.obj.registerObject(obj) - obj = test_obj("test1") - self.obj.registerObject(obj) - obj = test_obj("test2") - self.obj.registerObject(obj) - - self.assertEqual(len(self.obj.for_each(self.ModuleFactories)._modlist),3,"Result failed.") - - -############### test ################# -if __name__ == '__main__': - unittest.main() diff --git a/OpenRTM_aist/test/test_OutPort.py b/OpenRTM_aist/test/test_OutPort.py deleted file mode 100755 index 8f5a3cdb..00000000 --- a/OpenRTM_aist/test/test_OutPort.py +++ /dev/null @@ -1,93 +0,0 @@ -#!/usr/bin/env python -# -*- Python -*- - -# -# \file test_OutPort.py -# \brief test for OutPort class -# \date $Date: 2007/09/19$ -# \author Shinji Kurihara -# -# Copyright (C) 2006 -# Noriaki Ando -# Task-intelligence Research Group, -# Intelligent Systems Research Institute, -# National Institute of -# Advanced Industrial Science and Technology (AIST), Japan -# All rights reserved. -# - -import sys -sys.path.insert(1,"../") - -from omniORB import * -from omniORB import any - -import unittest -from OutPort import * - -import RTC, RTC__POA - -import OpenRTM_aist - -class OnRWTest: - def __init__(self): - pass - - def echo(self, value=None): - print "OnRW Called" - -class OnRWConvertTest: - def __init__(self): - pass - - def echo(self, value=None): - print "OnRWConvert Called" - return value - -class ConnectorMock: - def write(self, data): - self._data = data - return OpenRTM_aist.DataPortStatus.PORT_OK - - def read(self, data): - data[0] = self._data - return True - - -class TestOutPort(unittest.TestCase): - def setUp(self): - OpenRTM_aist.Manager.init(sys.argv) - self._op = OutPort("out", RTC.TimedLong(RTC.Time(0,0), 0)) - return - - def tearDown(self): - OpenRTM_aist.Manager.instance().shutdownManager() - return - - def test_write(self): - self.assertEqual(self._op.write(RTC.TimedLong(RTC.Time(0,0), 123)), True) - self._connector = ConnectorMock() - self._op._connectors = [self._connector] - self.assertEqual(self._op.write(RTC.TimedLong(RTC.Time(0,0), 123)), True) - read_data = [RTC.TimedLong(RTC.Time(0,0), 0)] - self._connector.read(read_data) - self.assertEqual(read_data[0].data,123) - return - - def test_OnWrite(self): - self._connector = ConnectorMock() - self._op._connectors = [self._connector] - self._op.setOnWrite(OnRWTest().echo) - self._op.setOnWriteConvert(OnRWConvertTest().echo) - self.assertEqual(self._op.write(RTC.TimedLong(RTC.Time(0,0), 123)), True) - return - - - def test_getPortDataType(self): - self.assertEqual(self._op.getPortDataType(),any.to_any(RTC.TimedLong(RTC.Time(0,0),0)).typecode().name()) - return - - -############### test ################# -if __name__ == '__main__': - unittest.main() diff --git a/OpenRTM_aist/test/test_OutPortBase.py b/OpenRTM_aist/test/test_OutPortBase.py deleted file mode 100755 index 042ae741..00000000 --- a/OpenRTM_aist/test/test_OutPortBase.py +++ /dev/null @@ -1,272 +0,0 @@ -#!/usr/bin/env python -# -*- Python -*- - -# -# \file test_OutPortBase.py -# \brief test for OutPortBase base class -# \date $Date: 2007/09/19 $ -# \author Shinji Kurihara -# -# Copyright (C) 2003-2006 -# Task-intelligence Research Group, -# Intelligent Systems Research Institute, -# National Institute of -# Advanced Industrial Science and Technology (AIST), Japan -# All rights reserved. - -import sys -sys.path.insert(1,"../") - -#from omniORB import any - -import unittest -from OutPortBase import * - -import OpenRTM_aist -import RTC - -counter = 0 - -class PublisherTest: - def __init__(self): - global counter - self.counter = counter - counter+=1 - - def update(self): - print "update",self.counter - -class ConnectorMock: - def __init__(self, name="name", id="id", ports=None, properties=None): - self._name = name - self._id = id - self._ports = ports - self._properties = properties - return - - def profile(self): - return OpenRTM_aist.ConnectorInfo(self._name,self._id,self._ports,self._properties) - - def id(self): - return self._id - - def name(self): - return self._name - - def activate(self): - pass - - def deactivate(self): - pass - - -class ConsumerMock: - def init(self,prop): - return - -class TestOutPortBase(unittest.TestCase): - def setUp(self): - OpenRTM_aist.Manager.init(sys.argv) - self._opb = OutPortBase("test","TimedLong") - self._opb.init(OpenRTM_aist.Properties()) - return - - def tearDown(self): - OpenRTM_aist.Manager.instance().shutdownManager() - return - - def test_getName(self): - self.assertEqual(self._opb.getName(),"unknown.test") - return - - def test_connectors(self): - self.assertEqual(self._opb.connectors(),[]) - return - - def test_getConnectorProfiles(self): - self.assertEqual(self._opb.getConnectorProfiles(),[]) - self._opb._connectors = [ConnectorMock()] - cprof = self._opb.getConnectorProfiles()[0] - self.assertEqual(cprof.name,"name") - return - - def test_getConnectorIds(self): - self.assertEqual(self._opb.getConnectorIds(),[]) - self._opb._connectors = [ConnectorMock()] - cprof = self._opb.getConnectorIds()[0] - self.assertEqual(cprof,"id") - return - - def test_getConnectorProfileById(self): - self.assertEqual(self._opb.getConnectorProfileById("id",[]),False) - self._opb._connectors = [ConnectorMock()] - prof = [None] - self.assertEqual(self._opb.getConnectorProfileById("id",prof),True) - self.assertEqual(prof[0].id,"id") - return - - def test_getConnectorProfileByName(self): - self.assertEqual(self._opb.getConnectorProfileByName("name",[]),False) - self._opb._connectors = [ConnectorMock()] - prof = [None] - self.assertEqual(self._opb.getConnectorProfileByName("name",prof),True) - self.assertEqual(prof[0].name,"name") - return - - def test_activateInterfaces(self): - self._opb._connectors = [ConnectorMock()] - self._opb.activateInterfaces() - self._opb.deactivateInterfaces() - return - - def test_publishInterfaces(self): - cprof = RTC.ConnectorProfile("","",[],[]) - self.assertEqual(self._opb.publishInterfaces(cprof),RTC.BAD_PARAMETER) - cprof = RTC.ConnectorProfile("connecto0","",[],[]) - OpenRTM_aist.CORBA_SeqUtil.push_back(cprof.properties, - OpenRTM_aist.NVUtil.newNV("dataport.interface_type", - "corba_cdr")) - - OpenRTM_aist.CORBA_SeqUtil.push_back(cprof.properties, - OpenRTM_aist.NVUtil.newNV("dataport.dataflow_type", - "push")) - - OpenRTM_aist.CORBA_SeqUtil.push_back(cprof.properties, - OpenRTM_aist.NVUtil.newNV("dataport.subscription_type", - "flush")) - - self.assertEqual(self._opb.publishInterfaces(cprof),RTC.RTC_OK) - return - - def test_subscribeInterfaces(self): - cprof = RTC.ConnectorProfile("","",[],[]) - self.assertEqual(self._opb.subscribeInterfaces(cprof),RTC.BAD_PARAMETER) - cprof = RTC.ConnectorProfile("connecto0","",[],[]) - OpenRTM_aist.CORBA_SeqUtil.push_back(cprof.properties, - OpenRTM_aist.NVUtil.newNV("dataport.interface_type", - "corba_cdr")) - - OpenRTM_aist.CORBA_SeqUtil.push_back(cprof.properties, - OpenRTM_aist.NVUtil.newNV("dataport.dataflow_type", - "push")) - - OpenRTM_aist.CORBA_SeqUtil.push_back(cprof.properties, - OpenRTM_aist.NVUtil.newNV("dataport.subscription_type", - "flush")) - - #self.assertEqual(self._opb.subscribeInterfaces(cprof),RTC.RTC_OK) - return - - - def test_unsubscribeInterfaces(self): - self._opb._connectors = [ConnectorMock()] - cprof = RTC.ConnectorProfile("connecto0","",[],[]) - OpenRTM_aist.CORBA_SeqUtil.push_back(cprof.properties, - OpenRTM_aist.NVUtil.newNV("dataport.interface_type", - "corba_cdr")) - - OpenRTM_aist.CORBA_SeqUtil.push_back(cprof.properties, - OpenRTM_aist.NVUtil.newNV("dataport.dataflow_type", - "push")) - - OpenRTM_aist.CORBA_SeqUtil.push_back(cprof.properties, - OpenRTM_aist.NVUtil.newNV("dataport.subscription_type", - "flush")) - self._opb.unsubscribeInterfaces(cprof) - return - - def test_initProviders(self): - self._opb.initProviders() - return - - def test_initConsumers(self): - self._opb.initConsumers() - return - - def test_createProvider(self): - self._opb._connectors = [ConnectorMock()] - cprof = RTC.ConnectorProfile("connecto0","",[],[]) - OpenRTM_aist.CORBA_SeqUtil.push_back(cprof.properties, - OpenRTM_aist.NVUtil.newNV("dataport.interface_type", - "corba_cdr")) - - OpenRTM_aist.CORBA_SeqUtil.push_back(cprof.properties, - OpenRTM_aist.NVUtil.newNV("dataport.dataflow_type", - "push")) - - OpenRTM_aist.CORBA_SeqUtil.push_back(cprof.properties, - OpenRTM_aist.NVUtil.newNV("dataport.subscription_type", - "flush")) - prop = OpenRTM_aist.Properties() - prop.setProperty("interface_type","corba_cdr") - prop.setProperty("dataflow_type","pull") - prop.setProperty("subscription_type","flush") - self.assertNotEqual(self._opb.createProvider(cprof,prop),0) - - return - - def test_createConsumer(self): - self._opb._connectors = [ConnectorMock()] - cprof = RTC.ConnectorProfile("connecto0","",[],[]) - OpenRTM_aist.CORBA_SeqUtil.push_back(cprof.properties, - OpenRTM_aist.NVUtil.newNV("dataport.interface_type", - "corba_cdr")) - - OpenRTM_aist.CORBA_SeqUtil.push_back(cprof.properties, - OpenRTM_aist.NVUtil.newNV("dataport.dataflow_type", - "push")) - - OpenRTM_aist.CORBA_SeqUtil.push_back(cprof.properties, - OpenRTM_aist.NVUtil.newNV("dataport.subscription_type", - "flush")) - prop = OpenRTM_aist.Properties() - prop.setProperty("interface_type","corba_cdr") - prop.setProperty("dataflow_type","push") - prop.setProperty("subscription_type","flush") - self.assertEqual(self._opb.createConsumer(cprof,prop),0) - - return - - def test_createConnector(self): - self._opb._connectors = [ConnectorMock()] - cprof = RTC.ConnectorProfile("connecto0","",[],[]) - OpenRTM_aist.CORBA_SeqUtil.push_back(cprof.properties, - OpenRTM_aist.NVUtil.newNV("dataport.interface_type", - "corba_cdr")) - - OpenRTM_aist.CORBA_SeqUtil.push_back(cprof.properties, - OpenRTM_aist.NVUtil.newNV("dataport.dataflow_type", - "push")) - - OpenRTM_aist.CORBA_SeqUtil.push_back(cprof.properties, - OpenRTM_aist.NVUtil.newNV("dataport.subscription_type", - "flush")) - prop = OpenRTM_aist.Properties() - prop.setProperty("interface_type","corba_cdr") - prop.setProperty("dataflow_type","push") - prop.setProperty("subscription_type","flush") - self.assertNotEqual(self._opb.createConnector(cprof,prop,consumer_=ConsumerMock()),0) - - return - - def test_getConnectorById(self): - self.assertEqual(self._opb.getConnectorById("test"),0) - self._opb._connectors = [ConnectorMock()] - prof = [None] - conn = self._opb.getConnectorById("id") - self.assertEqual(conn.id(),"id") - return - - - def test_getConnectorByName(self): - self.assertEqual(self._opb.getConnectorByName("test"),0) - self._opb._connectors = [ConnectorMock()] - prof = [None] - conn = self._opb.getConnectorByName("name") - self.assertEqual(conn.name(),"name") - return - - -############### test ################# -if __name__ == '__main__': - unittest.main() diff --git a/OpenRTM_aist/test/test_OutPortConnector.py b/OpenRTM_aist/test/test_OutPortConnector.py deleted file mode 100755 index 549633b9..00000000 --- a/OpenRTM_aist/test/test_OutPortConnector.py +++ /dev/null @@ -1,61 +0,0 @@ -#!/usr/bin/env python -# -*- Python -*- - -# -# \file test_OutPortConnector.py -# \brief test for OutPortConnector class -# \date $Date: 2007/09/19$ -# \author Shinji Kurihara -# -# Copyright (C) 2006 -# Noriaki Ando -# Task-intelligence Research Group, -# Intelligent Systems Research Institute, -# National Institute of -# Advanced Industrial Science and Technology (AIST), Japan -# All rights reserved. -# - -import sys -sys.path.insert(1,"../") - -from omniORB import * -from omniORB import any - -import unittest -from OutPortConnector import * - -import RTC, RTC__POA - -import OpenRTM_aist - - - -class TestOutPortConnector(unittest.TestCase): - def setUp(self): - self._profile = OpenRTM_aist.ConnectorBase.Profile("test", - "id", - ["in","out"], - OpenRTM_aist.Properties()) - - self._oc = OutPortConnector(self._profile) - return - - def test_profile(self): - self.assertEqual(self._oc.profile(), self._profile) - return - - - def test_id(self): - self.assertEqual(self._oc.id(), "id") - return - - - def test_name(self): - self.assertEqual(self._oc.name(),"test") - return - - -############### test ################# -if __name__ == '__main__': - unittest.main() diff --git a/OpenRTM_aist/test/test_OutPortConsumer.py b/OpenRTM_aist/test/test_OutPortConsumer.py deleted file mode 100755 index 37eb08c4..00000000 --- a/OpenRTM_aist/test/test_OutPortConsumer.py +++ /dev/null @@ -1,70 +0,0 @@ -#!/usr/bin/env python -# -*- Python -*- - -# -# \file test_OutPortConsumer.py -# \brief test for OutPortConsumer class -# \date $Date: 2007/09/19$ -# \author Shinji Kurihara -# -# Copyright (C) 2006 -# Noriaki Ando -# Task-intelligence Research Group, -# Intelligent Systems Research Institute, -# National Institute of -# Advanced Industrial Science and Technology (AIST), Japan -# All rights reserved. -# - -import sys -sys.path.insert(1,"../") - -from omniORB import * -from omniORB import any - -import unittest -from OutPortConsumer import * - -import RTC, RTC__POA - -import OpenRTM_aist - - -class ConsumerMock: - def subscribeInterface(self, prop): - print "subscribeInterface" - return - - def unsubscribeInterface(self, prop): - print "unsubscribeInterface" - return - - -class TestOutPortConsumer(unittest.TestCase): - def setUp(self): - self._oc = OutPortConsumerFactory.instance() - return - - def test_OutPortConsumerFactory(self): - _oc1 = OutPortConsumerFactory.instance() - self.assertEqual(self._oc, _oc1) - return - - def test_subscribe(self): - subs = self._oc.subscribe(None) - subs(ConsumerMock()) - subs(ConsumerMock()) - subs(ConsumerMock()) - return - - def test_unsubscribe(self): - subs = self._oc.unsubscribe(None) - subs(ConsumerMock()) - subs(ConsumerMock()) - subs(ConsumerMock()) - return - - -############### test ################# -if __name__ == '__main__': - unittest.main() diff --git a/OpenRTM_aist/test/test_OutPortCorbaCdrConsumer.py b/OpenRTM_aist/test/test_OutPortCorbaCdrConsumer.py deleted file mode 100755 index 2746a312..00000000 --- a/OpenRTM_aist/test/test_OutPortCorbaCdrConsumer.py +++ /dev/null @@ -1,72 +0,0 @@ -#!/usr/bin/env python -# -*- Python -*- - -# -# \file test_OutPortCorbaCdrConsumer.py -# \brief test for OutPortCorbaCdrConsumer class -# \date $Date: 2007/09/26 $ -# \author Shinji Kurihara -# -# Copyright (C) 2006 -# Noriaki Ando -# Task-intelligence Research Group, -# Intelligent Systems Research Institute, -# National Institute of -# Advanced Industrial Science and Technology (AIST), Japan -# All rights reserved. - -from omniORB import any -from omniORB import CORBA - -import OpenRTM_aist -import RTC, RTC__POA -import SDOPackage, SDOPackage__POA - -import sys -sys.path.insert(1,"../") - -import unittest - -from OutPortCorbaCdrConsumer import * - -class DummyBuffer: - def empty(): - return False - - def read(cdr): - cdr[0] = 123 - return 0 - -class TestOutPortCorbaCdrConsumer(unittest.TestCase): - - def setUp(self): - OpenRTM_aist.Manager.instance() - OpenRTM_aist.OutPortCorbaCdrProviderInit() - self._opp = OpenRTM_aist.OutPortCorbaCdrProvider() - self._opp.setBuffer(DummyBuffer()) - self._opcc = OutPortCorbaCdrConsumer() - return - - def test_setBuffer(self): - self._opcc.setBuffer(DummyBuffer()) - return - - def COMMENTtest_get(self): - data = [None] - self.assertEqual(self._opcc.subscribeInterface(self._opp._properties),True) - self.assertEqual(self._opcc.get(data),OpenRTM_aist.DataPortStatus.PORT_OK) - self.assertEqual(data[0],123) - return - - def test_subscribeInterface(self): - self.assertEqual(self._opcc.subscribeInterface(self._opp._properties),True) - return - - def test_unsubscribeInterface(self): - self._opcc.unsubscribeInterface(self._opp._properties) - return - - -############### test ################# -if __name__ == '__main__': - unittest.main() diff --git a/OpenRTM_aist/test/test_OutPortCorbaCdrProvider.py b/OpenRTM_aist/test/test_OutPortCorbaCdrProvider.py deleted file mode 100755 index 4a5480ed..00000000 --- a/OpenRTM_aist/test/test_OutPortCorbaCdrProvider.py +++ /dev/null @@ -1,85 +0,0 @@ -#!/usr/bin/env python -# -*- Python -*- - -# -# \file test_OutPortCorbaCdrProvider.py -# \brief test for OutPortCorbaCdrProvider class -# \date $Date: 2007/09/26 $ -# \author Shinji Kurihara -# -# Copyright (C) 2006 -# Noriaki Ando -# Task-intelligence Research Group, -# Intelligent Systems Research Institute, -# National Institute of -# Advanced Industrial Science and Technology (AIST), Japan -# All rights reserved. - -from omniORB import any -from omniORB import CORBA - -import OpenRTM_aist -import RTC, RTC__POA -import SDOPackage, SDOPackage__POA - -import sys -sys.path.insert(1,"../") - -import unittest - -from OutPortCorbaCdrProvider import * - -class DummyBuffer: - def __init__(self): - self._cdr = None - self._empty = True - - def empty(self): - return self._empty - - def write(self,d): - self._cdr = d - self._empty = False - return 0 - - def read(self,cdr): - cdr[0] = self._cdr - self._empty = True - return 0 - -class TestOutPortCorbaCdrProvider(unittest.TestCase): - - def setUp(self): - OpenRTM_aist.Manager.instance() - OpenRTM_aist.OutPortCorbaCdrProviderInit() - self._opp = OpenRTM_aist.OutPortCorbaCdrProvider() - return - - def test_setBuffer(self): - self._opp.setBuffer(DummyBuffer()) - return - - def test_get(self): - ret,data=self._opp.get() - self.assertEqual(ret,OpenRTM.UNKNOWN_ERROR) - - prop = OpenRTM_aist.Properties() - cinfo = OpenRTM_aist.ConnectorInfo("", - "", - [], - prop) - self._opp.setListener(cinfo,OpenRTM_aist.ConnectorListeners()) - buff = DummyBuffer() - self._opp.setBuffer(buff) - ret,data=self._opp.get() - self.assertEqual(ret,OpenRTM.BUFFER_EMPTY) - - buff.write(123) - ret,data=self._opp.get() - self.assertEqual(data,123) - return - - -############### test ################# -if __name__ == '__main__': - unittest.main() diff --git a/OpenRTM_aist/test/test_OutPortCorbaConsumer.py b/OpenRTM_aist/test/test_OutPortCorbaConsumer.py deleted file mode 100755 index 940b22e0..00000000 --- a/OpenRTM_aist/test/test_OutPortCorbaConsumer.py +++ /dev/null @@ -1,77 +0,0 @@ -#!/usr/bin/env python -# -*- Python -*- - -# -# \file test_OutPortCorbaConsumer.py -# \brief test for OutPortCorbaConsumer class -# \date $Date: 2007/09/26 $ -# \author Shinji Kurihara -# -# Copyright (C) 2006 -# Noriaki Ando -# Task-intelligence Research Group, -# Intelligent Systems Research Institute, -# National Institute of -# Advanced Industrial Science and Technology (AIST), Japan -# All rights reserved. - -from omniORB import any -from omniORB import CORBA - -import OpenRTM_aist -import RTC, RTC__POA -import SDOPackage, SDOPackage__POA - -import sys -sys.path.insert(1,"../") - -import unittest - -from OutPortCorbaConsumer import * - -class OutPortTest(RTC__POA.OutPortAny): - def __init__(self): - self.orb = CORBA.ORB_init() - self.poa = self.orb.resolve_initial_references("RootPOA") - poaManager = self.poa._get_the_POAManager() - poaManager.activate() - - - def get(self): - print "Called get operation." - return any.to_any(RTC.TimedLong(RTC.Time(0,0),123)) - - -class TestOutPortCorbaConsumer(unittest.TestCase): - - def setUp(self): - ringbuf = OpenRTM_aist.RingBuffer(8) - ringbuf.init(RTC.TimedLong(RTC.Time(0,0),0)) - self._opcc = OutPortCorbaConsumer(OpenRTM_aist.InPort("in", - RTC.TimedLong(RTC.Time(0,0),0), - ringbuf)) - - - - def test_get(self): - self._opcc.setObject(OutPortTest()._this()) - data=[None] - self.assertEqual(self._opcc.get(data),True) - self.assertEqual(data[0].data,123) - - - def test_pull(self): - self._opcc.pull() - - - def test_subscribeInterface(self): - port = any.to_any(OutPortTest()._this()) - prop = [SDOPackage.NameValue("dataport.dataflow_type","Push"), - SDOPackage.NameValue("dataport.corba_any.outport_ref",port)] - self.assertEqual(self._opcc.subscribeInterface(prop), True) - self._opcc.unsubscribeInterface(prop) - - -############### test ################# -if __name__ == '__main__': - unittest.main() diff --git a/OpenRTM_aist/test/test_OutPortCorbaProvider.py b/OpenRTM_aist/test/test_OutPortCorbaProvider.py deleted file mode 100755 index 66d4b9b3..00000000 --- a/OpenRTM_aist/test/test_OutPortCorbaProvider.py +++ /dev/null @@ -1,52 +0,0 @@ -#!/usr/bin/env python -# -*- Python -*- - -# -# \file test_OutPortCorbaProvider.py -# \brief test for OutPortCorbaProvider class -# \date $Date: 2007/09/26 $ -# \author Shinji Kurihara -# -# Copyright (C) 2006 -# Noriaki Ando -# Task-intelligence Research Group, -# Intelligent Systems Research Institute, -# National Institute of -# Advanced Industrial Science and Technology (AIST), Japan -# All rights reserved. - -import sys -sys.path.insert(1,"../") - -import unittest - -from OutPortCorbaProvider import * - -import OpenRTM_aist -import RTC, RTC__POA - -from omniORB import any -from omniORB import CORBA - -class TestOutPortCorbaProvider(unittest.TestCase): - def setUp(self): - self.orb = CORBA.ORB_init() - self.poa = self.orb.resolve_initial_references("RootPOA") - poaManager = self.poa._get_the_POAManager() - poaManager.activate() - - ringbuf = OpenRTM_aist.RingBuffer(8) - ringbuf.init(RTC.TimedLong(RTC.Time(0,0), 0)) - outport = OpenRTM_aist.OutPort("out", RTC.TimedLong(RTC.Time(0,0), 123), ringbuf) - self._opcp = OutPortCorbaProvider(outport) - outport.write(RTC.TimedLong(RTC.Time(0,0), 123)) - - - def test_get(self): - data = self._opcp.get() - self.assertEqual(any.from_any(data, keep_structs=True).data, 123) - - -############### test ################# -if __name__ == '__main__': - unittest.main() diff --git a/OpenRTM_aist/test/test_OutPortProvider.py b/OpenRTM_aist/test/test_OutPortProvider.py deleted file mode 100755 index 586119ab..00000000 --- a/OpenRTM_aist/test/test_OutPortProvider.py +++ /dev/null @@ -1,84 +0,0 @@ -#!/usr/bin/env python -# -*- Python -*- - -# -# \file test_OutPortProvider.py -# \brief test for OutPortProvider class -# \date $Date: 2007/09/05$ -# \author Shinji Kurihara -# -# Copyright (C) 2006 -# Noriaki Ando -# Task-intelligence Research Group, -# Intelligent Systems Research Institute, -# National Institute of -# Advanced Industrial Science and Technology (AIST), Japan -# All rights reserved. -# - -import sys -sys.path.insert(1,"../") - -import unittest - -from OutPortProvider import * -import OpenRTM_aist - - -class TestOutPortProvider(unittest.TestCase): - def setUp(self): - self._opp = OutPortProvider() - return - - def tearDown(self): - OpenRTM_aist.Manager.instance().shutdownManager() - return - - def test_publishInterfaceProfile(self): - properties = [] - self._opp.setInterfaceType("corba_cdr") - self._opp.publishInterfaceProfile(properties) - self.assertEqual("corba_cdr", - OpenRTM_aist.NVUtil.toString(properties,"dataport.interface_type")) - return - - def test_publishInterface(self): - properties = [] - self._opp.setInterfaceType("corba_cdr") - OpenRTM_aist.CORBA_SeqUtil.push_back(properties, - OpenRTM_aist.NVUtil.newNV("dataport.interface_type", - "corba_cdr")) - - OpenRTM_aist.CORBA_SeqUtil.push_back(properties, - OpenRTM_aist.NVUtil.newNV("dataport.dataflow_type", - "push")) - - OpenRTM_aist.CORBA_SeqUtil.push_back(properties, - OpenRTM_aist.NVUtil.newNV("dataport.subscription_type", - "flush")) - self.assertEqual(self._opp.publishInterface(properties),True) - return - - def test_setPortType(self): - self._opp.setPortType("out") - return - - def test_setDataType(self): - self._opp.setDataType("TimedLong") - return - - def test_setInterfaceType(self): - self._opp.setInterfaceType("corba_cdr") - return - - def test_setDataFlowType(self): - self._opp.setDataFlowType("flow") - return - - def test_setSubscriptionType(self): - self._opp.setSubscriptionType("flush") - - -############### test ################# -if __name__ == '__main__': - unittest.main() diff --git a/OpenRTM_aist/test/test_OutPortPullConnector.py b/OpenRTM_aist/test/test_OutPortPullConnector.py deleted file mode 100755 index eb834a5c..00000000 --- a/OpenRTM_aist/test/test_OutPortPullConnector.py +++ /dev/null @@ -1,93 +0,0 @@ -#!/usr/bin/env python -# -*- Python -*- - -# -# \file test_OutPortPullConnector.py -# \brief test for OutPortPullConnector class -# \date $Date: 2007/09/19$ -# \author Shinji Kurihara -# -# Copyright (C) 2006 -# Noriaki Ando -# Task-intelligence Research Group, -# Intelligent Systems Research Institute, -# National Institute of -# Advanced Industrial Science and Technology (AIST), Japan -# All rights reserved. -# - -import sys -sys.path.insert(1,"../") - -from omniORB import * -from omniORB import any - -import unittest -from OutPortPullConnector import * - -import RTC, RTC__POA - -import OpenRTM_aist - -class MyBuffer: - def __init__(self): - self._data = None - return - - def write(self, data): - self._data = data - return - - def read(self): - return self._data - - def init(self,info): - pass - -class OutPortProviderMock: - _buffer = None - _prop = None - - def init(self, prop): - self._prop = prop - - def setBuffer(self, buff): - self._buffer = buff - - def setListener(self, info, listener): - pass - - def setConnector(self, con): - pass - - -class TestOutPortPullConnector(unittest.TestCase): - def setUp(self): - self._buffer = MyBuffer() - self._profile = OpenRTM_aist.ConnectorInfo("test", - "id", - ["in","out"], - OpenRTM_aist.Properties()) - - self._oc = OutPortPullConnector(self._profile,OutPortProviderMock(),OpenRTM_aist.ConnectorListeners(), self._buffer) - return - - def test_write(self): - self._oc.write(123) - # self.assertEqual(self._buffer.read(), 123) - return - - - def test_disconnect(self): - self.assertEqual(self._oc.disconnect(), OpenRTM_aist.DataPortStatus.PORT_OK) - return - - - def test_getBuffer(self): - self.assertEqual(self._oc.getBuffer(),self._buffer) - return - - -############### test ################# -if __name__ == '__main__': - unittest.main() diff --git a/OpenRTM_aist/test/test_OutPortPushConnector.py b/OpenRTM_aist/test/test_OutPortPushConnector.py deleted file mode 100755 index 4c94b26e..00000000 --- a/OpenRTM_aist/test/test_OutPortPushConnector.py +++ /dev/null @@ -1,113 +0,0 @@ -#!/usr/bin/env python -# -*- Python -*- - -# -# \file test_OutPortPushConnector.py -# \brief test for OutPortPushConnector class -# \date $Date: 2007/09/19$ -# \author Shinji Kurihara -# -# Copyright (C) 2006 -# Noriaki Ando -# Task-intelligence Research Group, -# Intelligent Systems Research Institute, -# National Institute of -# Advanced Industrial Science and Technology (AIST), Japan -# All rights reserved. -# - -import sys -sys.path.insert(1,"../") - -from omniORB import * -from omniORB import any - -import unittest -from OutPortPushConnector import * - -import OpenRTM -import RTC -import OpenRTM_aist - -class MyBuffer: - def __init__(self): - self._data = None - return - - def write(self, data, sec=0, usec=0): - self._data = data - return - - def read(self): - return self._data - - def init(self,info): - return - -class ConsumerMock: - def __init__(self,buff): - self._data = None - self._buff = buff - return - - def init(self,prop): - return - - def write(self, data): - self._data = data - return OpenRTM.PORT_OK - - def put(self, data): - self._buff.write(data) - return OpenRTM.PORT_OK - -class TestOutPortPushConnector(unittest.TestCase): - def setUp(self): - self._buffer = MyBuffer() - self._consumer = ConsumerMock(self._buffer) - self._profile = OpenRTM_aist.ConnectorInfo("test", - "id", - ["in","out"], - OpenRTM_aist.Properties()) - - self._oc = OutPortPushConnector(self._profile,self._consumer,OpenRTM_aist.ConnectorListeners(),self._buffer) - return - - def test_write(self): - wdata = RTC.TimedLong(RTC.Time(0,0), 123) - self._oc.write(wdata) - val = self._buffer.read() - rdata = RTC.TimedLong(RTC.Time(0,0), 0) - get_data = cdrUnmarshal(any.to_any(rdata).typecode(),val,1) - self.assertEqual(get_data.data, 123) - return - - - def test_disconnect(self): - self.assertEqual(self._oc.disconnect(), OpenRTM_aist.DataPortStatus.PORT_OK) - return - - - def test_activate(self): - self._oc.activate() - return - - def test_deactivate(self): - self._oc.deactivate() - return - - def test_getBuffer(self): - self.assertEqual(self._oc.getBuffer(),self._buffer) - return - - def test_createPublisher(self): - self._oc.createPublisher(self._profile) - return - - def test_createBuffer(self): - self._oc.createBuffer(self._profile) - return - -############### test ################# -if __name__ == '__main__': - unittest.main() diff --git a/OpenRTM_aist/test/test_OutPortSHMProvider.py b/OpenRTM_aist/test/test_OutPortSHMProvider.py deleted file mode 100644 index 9acca65c..00000000 --- a/OpenRTM_aist/test/test_OutPortSHMProvider.py +++ /dev/null @@ -1,92 +0,0 @@ -#!/usr/bin/env python -# -*- Python -*- - -# -# \file test_OutPortSHMProvider.py -# \brief test for OutPortSHMProvider class -# \date $Date: 2016/03/26 $ -# \author Nobuhiko Miyamoto -# - - -from omniORB import any -from omniORB import CORBA - -import OpenRTM_aist -import RTC, RTC__POA -import SDOPackage, SDOPackage__POA -import OpenRTM - -import sys -sys.path.insert(1,"../") - -import unittest - - - -class DummyBuffer: - def __init__(self): - self._cdr = None - self._empty = True - - def empty(self): - return self._empty - - def write(self,d): - self._cdr = d - self._empty = False - return 0 - - def read(self,cdr): - cdr[0] = self._cdr - self._empty = True - return 0 - -class TestOutPortSHMProvider(unittest.TestCase): - - def setUp(self): - OpenRTM_aist.Manager.instance() - OpenRTM_aist.OutPortSHMProviderInit() - self._opp = OpenRTM_aist.OutPortSHMProvider() - - - #self._shm = OpenRTM_aist.SharedMemory() - #self._shm_var = self._sh._this() - return - - - - def test_get(self): - prop = OpenRTM_aist.Properties() - self._opp.init(prop) - - ret=self._opp.get() - self.assertEqual(ret,OpenRTM.UNKNOWN_ERROR) - - prop = OpenRTM_aist.Properties() - cinfo = OpenRTM_aist.ConnectorInfo("", - "", - [], - prop) - self._opp.setListener(cinfo,OpenRTM_aist.ConnectorListeners()) - buff = DummyBuffer() - self._opp.setBuffer(buff) - ret=self._opp.get() - self.assertEqual(ret,OpenRTM.BUFFER_EMPTY) - - - - #self._opp.setInterface(self._shm_var) - - - buff.write("abcde") - ret=self._opp.get() - self.assertEqual(ret,OpenRTM.PORT_OK) - data = self._opp.read() - self.assertEqual(data,"abcde") - return - - -############### test ################# -if __name__ == '__main__': - unittest.main() diff --git a/OpenRTM_aist/test/test_PeriodicECSharedComposite.py b/OpenRTM_aist/test/test_PeriodicECSharedComposite.py deleted file mode 100755 index b1ac98f7..00000000 --- a/OpenRTM_aist/test/test_PeriodicECSharedComposite.py +++ /dev/null @@ -1,157 +0,0 @@ -#!/usr/bin/env python -# -*- Python -*- - - -## \file test_PeriodicECSharedComposite.py -## \brief test for PeriodicECSharedComposite class -## \date $Date: $ -## \author Shinji Kurihara -# -# Copyright (C) 2006 -# Task-intelligence Research Group, -# Intelligent Systems Research Institute, -# National Institute of -# Advanced Industrial Science and Technology (AIST), Japan -# All rights reserved. -# - -import sys -sys.path.insert(1,"../") -sys.path.insert(1,"../RTM_IDL") - -import OpenRTM_aist -import RTC - -import unittest - - -configsample_spec = ["implementation_id", "TestComp", - "type_name", "TestComp", - "description", "Test example component", - "version", "1.0", - "vendor", "Shinji Kurihara, AIST", - "category", "example", - "activity_type", "DataFlowComponent", - "max_instance", "10", - "language", "Python", - "lang_type", "script", - # Configuration variables - "conf.default.int_param0", "0", - "conf.default.int_param1", "1", - "conf.default.double_param0", "0.11", - "conf.default.double_param1", "9.9", - "conf.default.str_param0", "hoge", - "conf.default.str_param1", "dara", - "conf.default.vector_param0", "0.0,1.0,2.0,3.0,4.0", - ""] - -com = None - - -class TestComp(OpenRTM_aist.DataFlowComponentBase): - - def __init__(self, manager): - OpenRTM_aist.DataFlowComponentBase.__init__(self, manager) - - def onInitialize(self): - print "onInitialize" - return RTC.RTC_OK - - def onFinalize(self): - print "onFinalize" - return RTC.RTC_OK - - def onStartup(self, ec_id): - print "onStartup" - return RTC.RTC_OK - - def onShutdown(self, ec_id): - print "onSutdown" - return RTC.RTC_OK - - def onActivated(self, ec_id): - print "onActivated" - return RTC.RTC_OK - - def onDeactivated(self, ec_id): - print "onDeactivated" - return RTC.RTC_OK - - def onExecute(self, ec_id): - print "onExecute" - return RTC.RTC_OK - - def onAborting(self, ec_id): - print "onAborting" - return RTC.RTC_OK - - def onReset(self, ec_id): - print "onReset" - return RTC.RTC_OK - - def onStateUpdate(self, ec_id): - print "onStateUpdate" - return RTC.RTC_OK - - def onRateChanged(self, ec_id): - print "onRateChanged" - return RTC.RTC_OK - - -def TestCompInit(manager): - global com - profile = OpenRTM_aist.Properties(defaults_str=configsample_spec) - manager.registerFactory(profile, - TestComp, - OpenRTM_aist.Delete) - com = manager.createComponent("TestComp") - - -class TestPeriodicECSharedComposite(unittest.TestCase): - - def setUp(self): - self.manager = OpenRTM_aist.Manager.init(sys.argv) - self.composite = OpenRTM_aist.PeriodicECSharedComposite(self.manager) - return - - def test_organization(self): - global com - self.manager.setModuleInitProc(TestCompInit) - self.manager.activateManager() - organization = OpenRTM_aist.PeriodicECOrganization(self.composite) - self.assertEqual(organization.set_members([com.getObjRef()]),True) - #self.assertEqual(organization.add_members([com.getObjRef()]),True) - self.assertEqual(organization.remove_member("TestComp0"),True) - self.assertEqual(organization.add_members([com.getObjRef()]),True) - organization.removeAllMembers() - return - - - def test_onInitialize(self): - self.assertEqual(self.composite.onInitialize(), RTC.RTC_OK) - return - - - def test_onActivated(self): - self.assertEqual(self.composite.onActivated(None), RTC.RTC_OK) - return - - - def test_onDeactivated(self): - self.assertEqual(self.composite.onDeactivated(None), RTC.RTC_OK) - return - - - def test_onReset(self): - self.assertEqual(self.composite.onReset(None), RTC.RTC_OK) - return - - - def test_delegatePort(self): - return - - - -############### test ################# -if __name__ == '__main__': - unittest.main() diff --git a/OpenRTM_aist/test/test_PeriodicExecutionContext.py b/OpenRTM_aist/test/test_PeriodicExecutionContext.py deleted file mode 100755 index 087efb25..00000000 --- a/OpenRTM_aist/test/test_PeriodicExecutionContext.py +++ /dev/null @@ -1,237 +0,0 @@ -#!/usr/bin/env python -# -*- Python -*- - -# -# \file test_PeriodicExecutionContext.py -# \brief test for PeriodicExecutionContext class -# \date $Date: 2007/08/28$ -# \author Shinji Kurihara -# -# Copyright (C) 2006 -# Task-intelligence Research Group, -# Intelligent Systems Research Institute, -# National Institute of -# Advanced Industrial Science and Technology (AIST), Japan -# All rights reserved. -# - -import sys -sys.path.insert(1,"../") - -import unittest -import OpenRTM_aist -from PeriodicExecutionContext import * - -import RTC -import RTC__POA -import SDOPackage -from omniORB import CORBA, PortableServer - - -#class DFP(RTC__POA.DataFlowComponent): -class DFP(OpenRTM_aist.RTObject_impl): - def __init__(self): - self._orb = CORBA.ORB_init() - self._poa = self._orb.resolve_initial_references("RootPOA") - OpenRTM_aist.RTObject_impl.__init__(self, orb=self._orb, poa=self._poa) - self._error = False - self._ref = self._this() - self._eclist = [] - - def getRef(self): - return self._ref - - def gotoError(self): - self._error = True - - def initialize(self): - return RTC.RTC_OK - - def finalize(self): - return RTC.RTC_OK - - def exit(self): - return RTC.RTC_OK - - def is_alive(self): - return True - - def get_contexts(self): - return self._eclist - - def set_execution_context_service(self, ec): - self._eclist.append(ec) - return len(self._eclist) -1 - - def get_component_profile(self): - return None - - def get_ports(self): - return None - - def get_execution_context_services(self): - return None - - def on_initialize(self): - print "on_initialize()" - return RTC.RTC_OK - - def on_finalize(self): - print "on_finalize()" - return RTC.RTC_OK - - def on_startup(self, id): - print "on_startup()" - return RTC.RTC_OK - - def on_shutdown(self, id): - print "shutdown()" - return RTC.RTC_OK - - def on_activated(self, id): - print "activated()" - return RTC.RTC_OK - - def on_deactivated(self, id): - print "deactivated()" - return RTC.RTC_OK - - def on_aborting(self, id): - print "on_aborting()" - return RTC.RTC_OK - - def on_error(self, id): - print "on_error()" - return RTC.RTC_OK - - def on_reset(self, id): - print "on_reset()" - return RTC.RTC_OK - - def on_execute(self, id): - print "on_execute()" - if self._error: - self._error = False - return RTC.RTC_ERROR - return RTC.RTC_OK - - def on_state_update(self, id): - print "on_state_update()" - return RTC.RTC_OK - - def on_rate_changed(self, id): - print "on_rate_changed()" - return RTC.RTC_OK - - def get_owned_organizations(self): - return None - - def get_sdo_id(self): - return None - - def get_sdo_type(self): - return None - - def get_device_profile(self): - return None - - def get_service_profiles(self): - return None - - def get_service_profile(self, id): - return None - - def get_sdo_service(self): - return SDOPackage.SDOService._nil() - - def get_configuration(self): - return SDOPackage.Configuration._nil() - - def get_monitoring(self): - return SDOPackage.Monitoring._nil() - - def get_organizations(self): - return None - - def get_status_list(self): - return None - - def get_status(self, name): - return None - - -class TestPeriodicExecutionContext(unittest.TestCase): - def setUp(self): - self._dfp = DFP() - self._dfp._poa._get_the_POAManager().activate() - - self._pec = PeriodicExecutionContext() - self._pec.add_component(self._dfp.getRef()) - self._pec.start() - - def tearDown(self): - self._pec.stop() - # import gc - self._pec.__del__() - self._pec = None - OpenRTM_aist.Manager.instance().shutdownManager() - - def getState(self, state): - if state == 0: - return "INACTIVE_STATE" - elif state == 1: - return "ACTIVE_STATE" - elif state == 2: - return "ERROR_STATE" - elif state == 3: - return "UNKNOWN_STATE" - - return "INVALID_STATE" - - - def test_case(self): - print "rate: ", self._pec.get_rate() - print "kind: ", self._pec.get_kind() - self._pec.activate_component(self._dfp.getRef()) - #for i in range(3): - # state = self._pec.get_component_state(self._dfp.getRef()) - # print self.getState(state) - #self._pec.stop() - #print "is_running : ", self._pec.is_running() - import time - time.sleep(1) - - - def test_set_rate(self): - self._pec.set_rate(1000) - print "get rate: ", self._pec.get_rate() - - - def test_activate_component(self): - #self._pec.activate_component(self._dfp.getRef()) - #self._pec.deactivate_component(self._dfp.getRef()) - pass - - - - def test_reset_component(self): - self._pec.reset_component(self._dfp.getRef()) - print "reset state: ", self._pec.get_component_state(self._dfp.getRef()) - self._pec.activate_component(self._dfp.getRef()) - print "activate state: ", self._pec.get_component_state(self._dfp.getRef()) - - - def test_remove(self): - self._pec.remove_component(self._dfp.getRef()) - self._pec.activate_component(self._dfp.getRef()) - print "activate state: ", self._pec.get_component_state(self._dfp.getRef()) - - - def test_get_profile(self): - print "get_profile.kind: ", self._pec.get_profile().kind - - - -############### test ################# -if __name__ == '__main__': - unittest.main() diff --git a/OpenRTM_aist/test/test_PeriodicTask.py b/OpenRTM_aist/test/test_PeriodicTask.py deleted file mode 100755 index 192c74e8..00000000 --- a/OpenRTM_aist/test/test_PeriodicTask.py +++ /dev/null @@ -1,297 +0,0 @@ -#!/usr/bin/env/python -# -*- Python -*- - -# -# \file PeriodicTask.py -# \brief PeriodicTask class -# \date $Date: $ -# \author Shinji Kurihara -# -# Copyright (C) 2007 -# Task-intelligence Research Group, -# Intelligent Systems Research Institute, -# National Institute of -# Advanced Industrial Science and Technology (AIST), Japan -# All rights reserved. -# - -import sys,time -sys.path.insert(1,"../") - -import OpenRTM_aist -import unittest - -from PeriodicTask import * -from TimeMeasure import * - -class LoggerMock: - def __init__(self): - self.m_log = [] - return - - def log(self, msg): - self.m_log.append(msg); - return - - def countLog(self, msg): - self.count = 0 - for i in range(len(self.m_log)): - if self.m_log[i] == msg: - self.count += 1 - return self.count - - def clearLog(self): - self.m_log = [] - return - -class MyMock: - def __init__(self): - return - - class mysvc2: - def __init__(self): - self.m_logger = None - return - - def __call__(self): - if self.m_logger is not None: - self.m_logger.log("mysvc2") - return 0 - - def setLogger(self, logger): - self.m_logger = logger - return - - class mysvc3: - def __init__(self): - self.m_logger = None - return - - def __call__(self): - if self.m_logger is not None: - self.m_logger.log("mysvc3") - return 0 - - def setLogger(self, logger): - self.m_logger = logger - return - -class TestPeriodicTask(unittest.TestCase): - def setUp(self): - return - - def test_setTask(self): - self._pt = PeriodicTask() - self._my = MyMock() - self._my.mysvc2 = MyMock().mysvc2() - self._logger = LoggerMock() - self._my.mysvc2.setLogger(self._logger) - - self.assert_(self._pt.setTask(self._my.mysvc2)) - self.assertEqual(0, self._logger.countLog("mysvc2")) - self._pt.activate() - time.sleep(0.005) - self._pt.finalize() - time.sleep(0.005) - self.assert_(1 < self._logger.countLog("mysvc2")) - return - - def test_setPeriodic(self): - self._pt = PeriodicTask() - self._my = MyMock() - self._my.mysvc2 = MyMock().mysvc2() - self._logger = LoggerMock() - self._my.mysvc2.setLogger(self._logger) - - self._pt.setTask(self._my.mysvc2) - self._pt.setPeriod(0.05) - self.assertEqual(0, self._logger.countLog("mysvc2")) - - self._pt.activate() - time.sleep(0.1) - self._pt.suspend() - time.sleep(0.05) - self.assert_(4 > self._logger.countLog("mysvc2")) - self.assert_(0 < self._logger.countLog("mysvc2")) - - self._logger.clearLog() - self._pt.setPeriod(0.01) - self.assertEqual(0, self._logger.countLog("mysvc2")) - - self._pt.resume() - time.sleep(0.1) - self._pt.suspend() - time.sleep(0.01) - self.assert_(12 > self._logger.countLog("mysvc2")) - self.assert_( 8 < self._logger.countLog("mysvc2")) - - self._logger.clearLog() - self._pt.setPeriod(0.05) - self.assertEqual(0, self._logger.countLog("mysvc2")) - - self._pt.resume() - time.sleep(0.1) - self._pt.finalize() - time.sleep(0.05) - self.assert_(4 > self._logger.countLog("mysvc2")) - self.assert_(0 < self._logger.countLog("mysvc2")) - return - - def test_signal(self): - self._pt = PeriodicTask() - self._my = MyMock() - self._my.mysvc2 = MyMock().mysvc2() - self._logger = LoggerMock() - self._my.mysvc2.setLogger(self._logger) - - self._pt.setTask(self._my.mysvc2) - self._pt.setPeriod(0.05) - self.assertEqual(0, self._logger.countLog("mysvc2")) - - self._pt.activate() - time.sleep(0.2) - self._pt.suspend() - count = self._logger.countLog("mysvc2") - - time.sleep(0.2) - self.assertEqual(count, self._logger.countLog("mysvc2")) - - self._pt.signal() - time.sleep(0.2) - self.assertEqual(count+1, self._logger.countLog("mysvc2")) - - self._pt.signal() - time.sleep(0.2) - self.assertEqual(count+2, self._logger.countLog("mysvc2")) - - self._logger.clearLog() - self._pt.resume() - time.sleep(0.2) - self._pt.suspend() - time.sleep(0.2) - self.assert_(6 > self._logger.countLog("mysvc2")) - self.assert_(2 < self._logger.countLog("mysvc2")) - - self._pt.finalize() - time.sleep(0.2) - return - - def test_executionMeasure(self): - self._pt = PeriodicTask() - self._my = MyMock() - self._my.mysvc3 = MyMock().mysvc3() - self._logger = LoggerMock() - self._my.mysvc3.setLogger(self._logger) - - wait = 0.03 # sec - self._pt.setTask(self._my.mysvc3) - self._pt.setPeriod(0.05) - self._pt.executionMeasure(True) - - # executionMeasureConut: 10 - self._pt.activate() - time.sleep(0.6) - self._pt.suspend() - time.sleep(0.05) - estat = self._pt.getExecStat() - ss = "" - ss = ss + "wait: " + str(wait) + "\n" - ss = ss + "estat max: " + str(estat._max_interval) + "\n" - ss = ss + "estat min: " + str(estat._min_interval) + "\n" - ss = ss + "estat mean: " + str(estat._mean_interval) + "\n" - ss = ss + "estat sdev: " + str(estat._std_deviation) + "\n" - self.assert_(estat._max_interval < (wait + 0.030), ss) - self.assert_(estat._min_interval > (wait - 0.03), ss) - self.assert_(abs(estat._mean_interval - wait) < 0.03, ss) - self.assert_(estat._std_deviation < (wait / 5.0), ss) - - # executionMeasureConut: 5 - self._pt.executionMeasureCount(5) - self._pt.resume() - time.sleep(0.3) - self._pt.suspend() - time.sleep(0.05) - estat = self._pt.getExecStat() - ss = "" - ss = ss + "wait: " + str(wait) + "\n" - ss = ss + "estat max: " + str(estat._max_interval) + "\n" - ss = ss + "estat min: " + str(estat._min_interval) + "\n" - ss = ss + "estat mean: " + str(estat._mean_interval) + "\n" - ss = ss + "estat sdev: " + str(estat._std_deviation) + "\n" - self.assert_(estat._max_interval < (wait + 0.030), ss) - self.assert_(estat._min_interval > (wait - 0.03), ss) - self.assert_(abs(estat._mean_interval - wait) < 0.03, ss) - self.assert_(estat._std_deviation < (wait / 5.0), ss) - - # executionMeasureConut: lessthan - self._pt.executionMeasureCount(10) - self._pt.resume() - time.sleep(0.3) - self._pt.suspend() - time.sleep(0.05) - self._pt.finalize() - estat2 = self._pt.getExecStat() - - # periodicMeasureConut: lessthan - self.assert_(estat._max_interval == estat2._max_interval) - self.assert_(estat._min_interval == estat2._min_interval) - self.assert_(estat._mean_interval == estat2._mean_interval) - self.assert_(estat._std_deviation == estat2._std_deviation) - return - - def test_periodicMeasure(self): - self._pt = PeriodicTask() - self._my = MyMock() - self._my.mysvc3 = MyMock().mysvc3() - self._logger = LoggerMock() - self._my.mysvc3.setLogger(self._logger) - - wait = 0.05 # sec - self._pt.setTask(self._my.mysvc3) - self._pt.setPeriod(0.05) - self._pt.periodicMeasure(True) - - # periodicMeasureConut: 10 - self._pt.activate() - time.sleep(0.6) - self._pt.suspend() - time.sleep(0.05) - pstat = self._pt.getPeriodStat() - self.assert_(pstat._max_interval < (wait + 0.030)) - self.assert_(pstat._min_interval > (wait - 0.050)) - self.assert_(abs(pstat._mean_interval - wait) < 0.03) - self.assert_(pstat._std_deviation < (wait / 1.0)) - - # periodicMeasureConut:5 - self._pt.periodicMeasureCount(5) - self._pt.resume() - time.sleep(0.3) - self._pt.suspend() - time.sleep(0.05) - pstat = self._pt.getPeriodStat() - self.assert_(pstat._max_interval < (wait + 0.030)) - self.assert_(pstat._min_interval > (wait - 0.010)) - self.assert_(abs(pstat._mean_interval - wait) < 0.03) - self.assert_(pstat._std_deviation < (wait / 5.0)) - - # periodicMeasureConut: lessthan - self._pt.periodicMeasureCount(10) - self._pt.resume() - time.sleep(0.3) - self._pt.suspend() - time.sleep(0.05) - self._pt.finalize() - pstat2 = self._pt.getPeriodStat() - - # periodicMeasureConut: lessthan - # Comment: Some errors may be observed. - #self.assert_(pstat._max_interval == pstat2._max_interval) - #self.assert_(pstat._min_interval == pstat2._min_interval) - #self.assert_(pstat._mean_interval == pstat2._mean_interval) - #self.assert_(pstat._std_deviation == pstat2._std_deviation) - return - - -############### test ################# -if __name__ == '__main__': - unittest.main() diff --git a/OpenRTM_aist/test/test_PortAdmin.py b/OpenRTM_aist/test/test_PortAdmin.py deleted file mode 100755 index acff17f1..00000000 --- a/OpenRTM_aist/test/test_PortAdmin.py +++ /dev/null @@ -1,157 +0,0 @@ -#!/usr/bin/env python -# -*- Python -*- - -# -# \file test_PortAdmin.py -# \brief test for RTC's Port administration class -# \date $Date: 2007/09/03 $ -# \author Shinji Kurihara -# -# Copyright (C) 2006 -# Task-intelligence Research Group, -# Intelligent Systems Research Institute, -# National Institute of -# Advanced Industrial Science and Technology (AIST), Japan -# All rights reserved. -# - -import sys -sys.path.insert(1,"../") - -import unittest -import OpenRTM_aist -from PortAdmin import * - -import RTC, RTC__POA -import OpenRTM - -from omniORB import CORBA - -class PortBase(OpenRTM_aist.PortBase): - def __init__(self): - OpenRTM_aist.PortBase.__init__(self) - - def publishInterfaces(self, prof): - return RTC.RTC_OK - - def subscribeInterfaces(self, prof): - return RTC.RTC_OK - - def unsubscribeInterfaces(self, prof): - return RTC.RTC_OK - - def activateInterfaces(self): - print "activateInterfaces" - - - def deactivateInterfaces(self): - print "deactivateInterfaces" - - -class TestPortAdmin(unittest.TestCase): - def setUp(self): - self._orb = CORBA.ORB_init(sys.argv) - self._poa = self._orb.resolve_initial_references("RootPOA") - self._poa._get_the_POAManager().activate() - - self._pa = PortAdmin(self._orb, self._poa) - - self._pb1 = PortBase() - self._pb2 = PortBase() - - self._pb1.setName("port0") - self._pb2.setName("port1") - - self._pa.registerPort(self._pb1) - self._pa.registerPort(self._pb2) - return - - def tearDown(self): - OpenRTM_aist.Manager.instance().shutdownManager() - - - def test_getPortServiceList(self): - plist = self._pa.getPortServiceList() - - prof0 = plist[0].get_port_profile() - self.assertEqual(prof0.name, "port0") - - prof1 = plist[1].get_port_profile() - self.assertEqual(prof1.name, "port1") - return - - - def test_getPortProfileList(self): - pprof = self._pa.getPortProfileList() - return - - - def CCCtest_getPortRef(self): - - getP = self._pa.getPortRef("") - self.assertEqual(CORBA.is_nil(getP), True) - - getP = self._pa.getPortRef("port1") - self.assertEqual(CORBA.is_nil(getP), False) - self.assertEqual(getP.get_port_profile().name, "port1") - - getP = self._pa.getPortRef("port0") - self.assertEqual(CORBA.is_nil(getP), False) - self.assertEqual(getP.get_port_profile().name, "port0") - return - - - def CCCtest_getPort(self): - pb = self._pa.getPort("port0") - prof = pb.get_port_profile() - self.assertEqual(prof.name, "port0") - - pb = self._pa.getPort("port1") - prof = pb.get_port_profile() - self.assertEqual(prof.name, "port1") - return - - - def CCCtest_deletePort(self): - self._pa.deletePort(self._pb1) - plist = self._pa.getPortServiceList() - self.assertEqual(len(plist), 1) - - prof = plist[0].get_port_profile() - self.assertEqual(prof.name, "port1") - return - - - def CCCtest_deletePortByName(self): - plist = self._pa.getPortServiceList() - self.assertEqual(len(plist), 2) - - self._pa.deletePortByName("port1") - - plist = self._pa.getPortServiceList() - self.assertEqual(len(plist), 1) - return - - - def CCCtest_activatePorts(self): - self._pa.activatePorts() - self._pa.deactivatePorts() - return - - - def CCCtest_finalizePorts(self): - plist = self._pa.getPortServiceList() - self.assertEqual(len(plist), 2) - - self._pa.finalizePorts() - - plist = self._pa.getPortServiceList() - self.assertEqual(len(plist), 0) - return - - - -############### test ################# -if __name__ == '__main__': - unittest.main() - diff --git a/OpenRTM_aist/test/test_PortBase.py b/OpenRTM_aist/test/test_PortBase.py deleted file mode 100755 index 232d6c21..00000000 --- a/OpenRTM_aist/test/test_PortBase.py +++ /dev/null @@ -1,183 +0,0 @@ -#!/usr/bin/env python -# -*- Python -*- - -# -# \file test_PortBase.py -# \brief test for RTC's Port base class -# \date $Date: 2007/09/18 $ -# \author Shinji Kurihara -# -# Copyright (C) 2006 -# Task-intelligence Research Group, -# Intelligent Systems Research Institute, -# National Institute of -# Advanced Industrial Science and Technology (AIST), Japan -# All rights reserved. -# - -import sys -sys.path.insert(1,"../") - -import unittest -from PortBase import * - -import CORBA -import OpenRTM_aist -import RTC, RTC__POA - - -class RTObjMock(OpenRTM_aist.DataFlowComponentBase): - def __init_(self, manager): - OpenRTM_aist.DataFlowComponentBase.__init__(self, manager) - -class OutPortObj(OpenRTM_aist.DataFlowComponentBase): - def __init__(self): - OpenRTM_aist.DataFlowComponentBase.__init__(self, OpenRTM_aist.Manager.instance()) - self.addOutPort("out",OpenRTM_aist.OutPort("out", RTC.TimedLong(RTC.Time(0,0),0))) - - -class InPortObj(OpenRTM_aist.DataFlowComponentBase): - def __init__(self): - OpenRTM_aist.DataFlowComponentBase.__init__(self, OpenRTM_aist.Manager.instance()) - self.addInPort("in",OpenRTM_aist.InPort("in", RTC.TimedLong(RTC.Time(0,0),0))) - - -class TestPortBase(unittest.TestCase): - def setUp(self): - OpenRTM_aist.Manager.init(sys.argv) - OpenRTM_aist.Manager.instance().activateManager() - self._pb = PortBase() - return - - def tearDown(self): - OpenRTM_aist.Manager.instance().shutdownManager() - return - - def test_get_port_profile(self): - self._pb.setName("test_connect") - prof = self._pb.get_port_profile() - self.assertEqual(prof.name,"test_connect") - return - - def test_getPortProfile(self): - self._pb.setName("test_connect") - prof = self._pb.getPortProfile() - self.assertEqual(prof.name,"test_connect") - - - def test_get_connector_profiles(self): - OpenRTM_aist.Manager.init(sys.argv) - nvlist = [OpenRTM_aist.NVUtil.newNV("dataport.interface_type","corba_cdr"), - OpenRTM_aist.NVUtil.newNV("dataport.dataflow_type","push"), - OpenRTM_aist.NVUtil.newNV("dataport.subscription_type","flush")] - - outp = OutPortObj() - outp = outp.get_ports() - - inp = InPortObj() - inp = inp.get_ports() - prof = RTC.ConnectorProfile("connector0", - "connectorid_0", - [outp[0]._narrow(RTC.PortService),inp[0]._narrow(RTC.PortService)], - nvlist) - ret, prof = self._pb.connect(prof) - cntlist = outp[0].get_connector_profiles() - self.assertEqual(cntlist[0].name,"connector0") - cntprofile = outp[0].get_connector_profile("connectorid_0") - self.assertEqual(cntprofile.connector_id,"connectorid_0") - #ret,prof = self._pb.notify_connect(prof) - return - - - - def test_connect_disconnect(self): - nvlist = [OpenRTM_aist.NVUtil.newNV("dataport.interface_type","corba_cdr"), - OpenRTM_aist.NVUtil.newNV("dataport.dataflow_type","push"), - OpenRTM_aist.NVUtil.newNV("dataport.subscription_type","flush")] - - outp = OutPortObj().get_ports() - inp = InPortObj().get_ports() - prof = RTC.ConnectorProfile("connector0","connector_id1",[inp[0],outp[0]],nvlist) - self._pb.connect(prof) - cntprofile = outp[0].get_connector_profile("connector_id1") - self.assertEqual(cntprofile.connector_id,"connector_id1") - outp[0].disconnect("connector_id1") - cntprofile = outp[0].get_connector_profile("connector_id1") - self.assertNotEqual(cntprofile.connector_id,"connector_id1") - self._pb.connect(prof) - outp[0].disconnect_all() - self.assertNotEqual(cntprofile.connector_id,"connector_id1") - return - - - - def test_getProfile(self): - outp = OutPortObj().get_ports() - self._pb.setName("test") - self._pb.setPortRef(outp[0]) - rtobj = RTObjMock(OpenRTM_aist.Manager.instance()) - self._pb.setOwner(rtobj) - prof = self._pb.getProfile() - self.assertEqual(prof.name,".test") - self.assertEqual(prof.port_ref,outp[0]) - self.assertEqual(prof.port_ref,outp[0]) - self.assertEqual(prof.port_ref,self._pb.getPortRef()) - return - - - def test_getUUID(self): - self._pb.getUUID() - return - - - def test_updateConnectorProfile(self): - nvlist = [OpenRTM_aist.NVUtil.newNV("dataport.interface_type","corba_cdr"), - OpenRTM_aist.NVUtil.newNV("dataport.dataflow_type","push"), - OpenRTM_aist.NVUtil.newNV("dataport.subscription_type","flush")] - - outp = OutPortObj().get_ports() - inp = InPortObj().get_ports() - prof = RTC.ConnectorProfile("connector0","connector_id1",[inp[0],outp[0]],nvlist) - self._pb.updateConnectorProfile(prof) - cntlist = self._pb.get_connector_profiles() - self.assertEqual(cntlist[0].name,"connector0") - return - - - - def test_eraseConnectorProfile(self): - nvlist = [OpenRTM_aist.NVUtil.newNV("dataport.interface_type","corba_cdr"), - OpenRTM_aist.NVUtil.newNV("dataport.dataflow_type","push"), - OpenRTM_aist.NVUtil.newNV("dataport.subscription_type","flush")] - - outp = OutPortObj().get_ports() - inp = InPortObj().get_ports() - prof = RTC.ConnectorProfile("connector0","connector_id1",[inp[0],outp[0]],nvlist) - self._pb.connect(prof) - #self.assertEqual(self._pb.eraseConnectorProfile("connector_id1"),True) - return - - - - def test_append_deleteInterface(self): - self.assertEqual(self._pb.appendInterface("name", "type", RTC.PROVIDED), True) - piprof = RTC.PortInterfaceProfile("name","type",RTC.PROVIDED) - self._pb._profile=RTC.PortProfile("name",[piprof],RTC.PortService._nil,[],RTC.RTObject._nil,[]) - self.assertEqual(self._pb.appendInterface("name", "type", RTC.PROVIDED), False) - self.assertEqual(self._pb.deleteInterface("name", RTC.PROVIDED), True) - self.assertEqual(self._pb.deleteInterface("name", RTC.PROVIDED), False) - return - - - def test_add_appendProperty(self): - self._pb.addProperty("name1","val1") - prof = self._pb.getPortProfile() - self.assertEqual(prof.properties[0].name, "name1") - self._pb.appendProperty("name2","val2") - prof = self._pb.getPortProfile() - self.assertEqual(prof.properties[1].name, "name2") - - -############### test ################# -if __name__ == '__main__': - unittest.main() diff --git a/OpenRTM_aist/test/test_PortConnectListener.py b/OpenRTM_aist/test/test_PortConnectListener.py deleted file mode 100644 index b1d3f97f..00000000 --- a/OpenRTM_aist/test/test_PortConnectListener.py +++ /dev/null @@ -1,119 +0,0 @@ -#!/usr/bin/env python -# -*- Python -*- - -## -# @file test_PortConnectListener.py -# @brief test for port connector listener class -# @date $Date: 2011/03/18 $ -# @author Shinji Kurihara -# -# Copyright (C) 2011 -# Intelligent Systems Research Institute, -# National Institute of -# Advanced Industrial Science and Technology (AIST), Japan -# All rights reserved. - - -import sys -sys.path.insert(1,"../") - -import unittest -import OpenRTM_aist -from PortConnectListener import * - -import RTC, RTC__POA -import OpenRTM - -from omniORB import * -from omniORB import any - -class MockPortConnectListener(PortConnectListener): - def __init__(self): - PortConnectListener.__init__(self) - return - - def __call__(self,portname,profile): - return - - -class MockPortConnectRetListener(PortConnectRetListener): - def __init__(self): - PortConnectRetListener.__init__(self) - return - - def __call__(self,portname,profile,ret): - return - - - -class TestListener(unittest.TestCase): - def setUp(self): - return - - def tearDown(self): - OpenRTM_aist.Manager.instance().shutdownManager() - return - - def test_PortConnectListener_toString(self): - self.assertEqual("ON_NOTIFY_CONNECT", - PortConnectListener.toString( - PortConnectListenerType.ON_NOTIFY_CONNECT)) - - self.assertEqual("ON_NOTIFY_DISCONNECT", - PortConnectListener.toString( - PortConnectListenerType.ON_NOTIFY_DISCONNECT)) - - self.assertEqual("ON_UNSUBSCRIBE_INTERFACES", - PortConnectListener.toString( - PortConnectListenerType.ON_UNSUBSCRIBE_INTERFACES)) - return - - - def test_PortConnectRetListener_toString(self): - self.assertEqual("ON_PUBLISH_INTERFACES", - PortConnectRetListener.toString( - PortConnectRetListenerType.ON_PUBLISH_INTERFACES)) - - self.assertEqual("ON_CONNECT_NEXTPORT", - PortConnectRetListener.toString( - PortConnectRetListenerType.ON_CONNECT_NEXTPORT)) - - self.assertEqual("ON_SUBSCRIBE_INTERFACES", - PortConnectRetListener.toString( - PortConnectRetListenerType.ON_SUBSCRIBE_INTERFACES)) - - self.assertEqual("ON_CONNECTED", - PortConnectRetListener.toString( - PortConnectRetListenerType.ON_CONNECTED)) - - self.assertEqual("ON_DISCONNECT_NEXT", - PortConnectRetListener.toString( - PortConnectRetListenerType.ON_DISCONNECT_NEXT)) - - self.assertEqual("ON_DISCONNECTED", - PortConnectRetListener.toString( - PortConnectRetListenerType.ON_DISCONNECTED)) - return - - - def test_PortConnectListenerHolder(self): - portconlisteners = PortConnectListeners() - listener = MockPortConnectListener() - portconlisteners.portconnect_[0].addListener(listener,True) - portconlisteners.portconnect_[0].notify("port_name",None) - portconlisteners.portconnect_[0].removeListener(listener) - return - - def test_PortConnectRetListenerHolder(self): - portconretlisteners = PortConnectRetListeners() - listener = MockPortConnectRetListener() - portconretlisteners.portconnret_[0].addListener(listener,True) - portconretlisteners.portconnret_[0].notify("port_name",None) - portconretlisteners.portconnret_[0].removeListener(listener) - return - - -############### test ################# -if __name__ == '__main__': - unittest.main() - diff --git a/OpenRTM_aist/test/test_PortProfileHelper.py b/OpenRTM_aist/test/test_PortProfileHelper.py deleted file mode 100755 index 87b4f41c..00000000 --- a/OpenRTM_aist/test/test_PortProfileHelper.py +++ /dev/null @@ -1,38 +0,0 @@ -#!/usr/bin/env python -# -*- Python -*- - -# -# \file test_PortProfileHelper.py -# \brief test for RTC's PortProfileHelper class -# \date $Date: 2007/09/18 $ -# \author Shinji Kurihara -# -# Copyright (C) 2006 -# Task-intelligence Research Group, -# Intelligent Systems Research Institute, -# National Institute of -# Advanced Industrial Science and Technology (AIST), Japan -# All rights reserved. -# - -import sys -sys.path.insert(1,"../") - -import unittest -from PortProfileHelper import * - -import CORBA -import OpenRTM_aist -import RTC, RTC__POA - - - -class TestPortProfileHelper(unittest.TestCase): - def setUp(self): - return - - - -############### test ################# -if __name__ == '__main__': - unittest.main() diff --git a/OpenRTM_aist/test/test_Preconfigured.py b/OpenRTM_aist/test/test_Preconfigured.py deleted file mode 100644 index 065cc392..00000000 --- a/OpenRTM_aist/test/test_Preconfigured.py +++ /dev/null @@ -1,211 +0,0 @@ -#!/usr/bin/env python -# -*- coding: euc-jp -*- - -# -# \file test_Preconfigured.py -# \brief -# \date $Date: $ -# \author Nobuhiko Miyamoto -# - - -import sys -sys.path.insert(1,"../") - -try: - import unittest2 as unittest -except (ImportError): - import unittest - -import time - -#from Manager import * -import OpenRTM_aist -import RTC, RTC__POA -import OpenRTM, OpenRTM__POA - -testcomp1_spec = ["implementation_id", "TestComp1", - "type_name", "TestComp1", - "description", "Test example component", - "version", "1.0", - "vendor", "Nobuhiko Myiyamoto", - "category", "example", - "activity_type", "DataFlowComponent", - "max_instance", "10", - "language", "C++", - "lang_type", "compile", - ""] - -testcomp2_spec = ["implementation_id", "TestComp2", - "type_name", "TestComp2", - "description", "Test example component", - "version", "1.0", - "vendor", "Nobuhiko Myiyamoto", - "category", "example", - "activity_type", "DataFlowComponent", - "max_instance", "10", - "language", "C++", - "lang_type", "compile", - ""] - -class Test_i(OpenRTM__POA.InPortCdr): - def __init__(self): - pass - def put(self, data): - return OpenRTM.PORT_OK - - -class TestComp1(OpenRTM_aist.DataFlowComponentBase): - def __init__(self, manager): - OpenRTM_aist.DataFlowComponentBase.__init__(self, manager) - self._d_out = RTC.TimedLong(RTC.Time(0,0),0) - self._outOut = OpenRTM_aist.OutPort("out", self._d_out) - - self._d_in = RTC.TimedLong(RTC.Time(0,0),0) - self._inIn = OpenRTM_aist.InPort("in", self._d_in) - - self._servicePort_provided = OpenRTM_aist.CorbaPort("service") - self._testService_provided = Test_i() - - - - def onInitialize(self): - self.addOutPort("out",self._outOut) - self.addInPort("in",self._inIn) - - self._servicePort_provided.registerProvider("service", "TestService", self._testService_provided) - self.addPort(self._servicePort_provided) - - #self._servicePort_provided.activateInterfaces() - - - - return RTC.RTC_OK - - - -class TestComp2(OpenRTM_aist.DataFlowComponentBase): - def __init__(self, manager): - OpenRTM_aist.DataFlowComponentBase.__init__(self, manager) - self._d_out = RTC.TimedLong(RTC.Time(0,0),0) - self._outOut = OpenRTM_aist.OutPort("out", self._d_out) - - self._d_in = RTC.TimedLong(RTC.Time(0,0),0) - self._inIn = OpenRTM_aist.InPort("in", self._d_in) - - - - - self._servicePort_required = OpenRTM_aist.CorbaPort("service") - self._testService_required = OpenRTM_aist.CorbaConsumer(interfaceType=OpenRTM.InPortCdr) - - - - return - - def onInitialize(self): - self.addOutPort("out",self._outOut) - self.addInPort("in",self._inIn) - - - - - self._servicePort_required.registerConsumer("service", "TestService", self._testService_required) - self.addPort(self._servicePort_required) - - return RTC.RTC_OK - - - - -def TestComp1Init(manager): - profile = OpenRTM_aist.Properties(defaults_str=testcomp1_spec) - manager.registerFactory(profile, - TestComp1, - OpenRTM_aist.Delete) - - - -def TestComp2Init(manager): - profile = OpenRTM_aist.Properties(defaults_str=testcomp2_spec) - manager.registerFactory(profile, - TestComp2, - OpenRTM_aist.Delete) - - -def MyModuleInit(manager): - TestComp1Init(manager) - TestComp2Init(manager) - com = manager.createComponent("TestComp1") - com = manager.createComponent("TestComp2") - - - - - -class Test_Preconfigured(unittest.TestCase): - - def setUp(self): - self.dataPortConnectorName = "TestComp20.in^TestComp10.out(interface_type=direct)" - self.servicePortConnectorName = "TestComp10.service^TestComp20.service()" - sys.argv.extend(['-o', 'manager.components.preconnect:'+self.dataPortConnectorName+","+self.servicePortConnectorName]) - sys.argv.extend(['-o', 'manager.components.preactivate:TestComp10']) - self.manager = OpenRTM_aist.Manager.init(sys.argv) - self.manager.setModuleInitProc(MyModuleInit) - self.manager.activateManager() - - self.comps = [] - self.comps.append(self.manager.getComponent("TestComp10")) - self.comps.append(self.manager.getComponent("TestComp20")) - self.comp1 = self.comps[0].getObjRef() - self.comp2 = self.comps[1].getObjRef() - - - - def tearDown(self): - for comp in self.comps: - self.manager.unregisterComponent(comp) - comp_id = comp.getProperties() - factory = self.manager._factory.find(comp_id) - factory.destroy(comp) - self.manager.shutdownNaming() - time.sleep(0.1) - - - - - - - def test_PreActivation(self): - - state = OpenRTM_aist.is_in_active(self.comp1) - self.assertTrue(state) - - - def test_PreConnection(self): - - inport = OpenRTM_aist.get_port_by_name(self.comp2, "TestComp20.in") - outport = OpenRTM_aist.get_port_by_name(self.comp1, "TestComp10.out") - ans = OpenRTM_aist.already_connected(inport, outport) - self.assertTrue(ans) - - #con = OpenRTM_aist.get_connector_names(inport)[0] - profile = inport.get_connector_profiles()[0] - prop = OpenRTM_aist.Properties() - OpenRTM_aist.NVUtil.copyToProperties(prop, profile.properties) - self.assertEqual(prop.getProperty("dataport.interface_type"),"direct") - - - provided = OpenRTM_aist.get_port_by_name(self.comp1, "TestComp10.service") - required = OpenRTM_aist.get_port_by_name(self.comp2, "TestComp20.service") - ans = OpenRTM_aist.already_connected(provided, required) - self.assertTrue(ans) - - - - - - -############### test ################# -if __name__ == '__main__': - unittest.main() diff --git a/OpenRTM_aist/test/test_Preconfigured_MultiProcess.py b/OpenRTM_aist/test/test_Preconfigured_MultiProcess.py deleted file mode 100644 index 00d50a59..00000000 --- a/OpenRTM_aist/test/test_Preconfigured_MultiProcess.py +++ /dev/null @@ -1,216 +0,0 @@ -#!/usr/bin/env python -# -*- coding: euc-jp -*- - -# -# \file test_Preconfigured_MultiProcess.py -# \brief -# \date $Date: $ -# \author Nobuhiko Miyamoto -# - - -import sys -sys.path.insert(1,"../") - -try: - import unittest2 as unittest -except (ImportError): - import unittest - -import time - -#from Manager import * -import OpenRTM_aist -import RTC, RTC__POA -import multiprocessing -import OpenRTM, OpenRTM__POA - -testcomp1_spec = ["implementation_id", "TestComp1", - "type_name", "TestComp1", - "description", "Test example component", - "version", "1.0", - "vendor", "Nobuhiko Myiyamoto", - "category", "example", - "activity_type", "DataFlowComponent", - "max_instance", "10", - "language", "C++", - "lang_type", "compile", - "conf.default.test1", "0", - ""] - -testcomp2_spec = ["implementation_id", "TestComp2", - "type_name", "TestComp2", - "description", "Test example component", - "version", "1.0", - "vendor", "Nobuhiko Myiyamoto", - "category", "example", - "activity_type", "DataFlowComponent", - "max_instance", "10", - "language", "C++", - "lang_type", "compile", - ""] - -class Test_i(OpenRTM__POA.InPortCdr): - def __init__(self): - pass - def put(self, data): - return OpenRTM.PORT_OK - - -class TestComp1(OpenRTM_aist.DataFlowComponentBase): - def __init__(self, manager): - OpenRTM_aist.DataFlowComponentBase.__init__(self, manager) - self._d_out = RTC.TimedLong(RTC.Time(0,0),0) - self._outOut = OpenRTM_aist.OutPort("out", self._d_out) - - self._d_in = RTC.TimedLong(RTC.Time(0,0),0) - self._inIn = OpenRTM_aist.InPort("in", self._d_in) - - self._servicePort_provided = OpenRTM_aist.CorbaPort("service") - self._testService_provided = Test_i() - - def onInitialize(self): - self.addOutPort("out",self._outOut) - self.addInPort("in",self._inIn) - - self._servicePort_provided.registerProvider("service", "TestService", self._testService_provided) - self.addPort(self._servicePort_provided) - - return RTC.RTC_OK - -class TestComp2(OpenRTM_aist.DataFlowComponentBase): - def __init__(self, manager): - OpenRTM_aist.DataFlowComponentBase.__init__(self, manager) - self._d_out = RTC.TimedLong(RTC.Time(0,0),0) - self._outOut = OpenRTM_aist.OutPort("out", self._d_out) - - self._d_in = RTC.TimedLong(RTC.Time(0,0),0) - self._inIn = OpenRTM_aist.InPort("in", self._d_in) - - self._servicePort_required = OpenRTM_aist.CorbaPort("service") - self._testService_required = OpenRTM_aist.CorbaConsumer(interfaceType=OpenRTM.InPortCdr) - - - - return - - def onInitialize(self): - self.addOutPort("out",self._outOut) - self.addInPort("in",self._inIn) - - - - - self._servicePort_required.registerConsumer("service", "TestService", self._testService_required) - self.addPort(self._servicePort_required) - - return RTC.RTC_OK - - - - -def TestComp1Init(manager): - profile = OpenRTM_aist.Properties(defaults_str=testcomp1_spec) - manager.registerFactory(profile, - TestComp1, - OpenRTM_aist.Delete) - - - -def TestComp2Init(manager): - profile = OpenRTM_aist.Properties(defaults_str=testcomp2_spec) - manager.registerFactory(profile, - TestComp2, - OpenRTM_aist.Delete) - - -def TestComp1ModuleInit(manager): - TestComp1Init(manager) - com = manager.createComponent("TestComp1") - -def TestComp2ModuleInit(manager): - TestComp2Init(manager) - com = manager.createComponent("TestComp2") - - -def runTestComp2(q): - - argv = [""] - argv.extend(['-d']) - argv.extend(['-o','naming.type:corba,manager']) - argv.extend(['-o','naming.formats:test.host_cxt/%n.rtc']) - - - manager = OpenRTM_aist.Manager.init(argv) - - manager.setModuleInitProc(TestComp2ModuleInit) - manager.activateManager() - - - q.get() - - comps = manager.getComponents()[:] - for comp in comps: - manager.unregisterComponent(comp) - comp_id = comp.getProperties() - factory = manager._factory.find(comp_id) - factory.destroy(comp) - manager.shutdownNaming() - time.sleep(0.1) - - -class Test_Preconfigured_MultiProcess(unittest.TestCase): - - def setUp(self): - self.queue = multiprocessing.Queue() - self.outport_process = multiprocessing.Process(target=runTestComp2, args=(self.queue,)) - self.outport_process.start() - - time.sleep(1) - sys.argv.extend(['-o','naming.type:corba,manager']) - sys.argv.extend(['-o','naming.formats:test.host_cxt/%n.rtc']) - - RTC2_URL = "rtcloc://localhost:2810/example/TestComp20" - self.dataPortConnectorName = RTC2_URL+".in"+"^TestComp10.out()" - self.servicePortConnectorName = "TestComp10.service^"+RTC2_URL+".service()" - sys.argv.extend(['-o', 'manager.components.preconnect:'+self.dataPortConnectorName+","+self.servicePortConnectorName]) - sys.argv.extend(['-o', 'manager.components.preactivate:'+RTC2_URL]) - #print 'manager.components.preactivate:'+RTC2_URL - self.manager = OpenRTM_aist.Manager.init(sys.argv) - self.manager.setModuleInitProc(TestComp1ModuleInit) - self.manager.activateManager() - - self.comp1 = self.manager.getComponent("TestComp10").getObjRef() - self.comp2 = self.manager._namingManager.string_to_component(RTC2_URL)[0] - - - def tearDown(self): - self.queue.put("") - comps = self.manager.getComponents()[:] - for comp in comps: - self.manager.unregisterComponent(comp) - comp_id = comp.getProperties() - factory = self.manager._factory.find(comp_id) - factory.destroy(comp) - self.manager.shutdownNaming() - time.sleep(0.1) - - def test_PreActivation(self): - state = OpenRTM_aist.is_in_active(self.comp2) - self.assertTrue(state) - - def test_PreConnection(self): - inport = OpenRTM_aist.get_port_by_name(self.comp2, "TestComp20.in") - outport = OpenRTM_aist.get_port_by_name(self.comp1, "TestComp10.out") - ans = OpenRTM_aist.already_connected(inport, outport) - self.assertTrue(ans) - - provided = OpenRTM_aist.get_port_by_name(self.comp1, "TestComp10.service") - required = OpenRTM_aist.get_port_by_name(self.comp2, "TestComp20.service") - ans = OpenRTM_aist.already_connected(provided, required) - self.assertTrue(ans) - - -############### test ################# -if __name__ == '__main__': - unittest.main() diff --git a/OpenRTM_aist/test/test_Properties.py b/OpenRTM_aist/test/test_Properties.py deleted file mode 100755 index 3c3e5484..00000000 --- a/OpenRTM_aist/test/test_Properties.py +++ /dev/null @@ -1,384 +0,0 @@ -#!/usr/bin/env python -# -*- Python -*- - -# -# @file test_Properties.py -# @brief test for Property list class (derived from Java Properties) -# @date $Date: $ -# @author Shinji Kurihara -# -# Copyright (C) 2006 -# Task-intelligence Research Group, -# Intelligent Systems Research Institute, -# National Institute of -# Advanced Industrial Science and Technology (AIST), Japan -# All rights reserved. -# - -import sys -sys.path.insert(1,"../") - -import unittest - -from Properties import * -import OpenRTM_aist - - -configsample_spec = ["implementation_id", "ConfigSample", - "type_name", "ConfigSample", - "description", "Configuration example component", - "version", "1.0", - "vendor", "Shinji Kurihara, AIST", - "category", "example", - "activity_type", "DataFlowComponent", - "max_instance", "10", - "language", "C++", - "lang_type", "compile", - # Configuration variables - "conf.default.int_param0", "0", - "conf.default.int_param1", "1", - "conf.default.double_param0", "0.11", - "conf.default.double_param1", "9.9", - "conf.default.str_param0", "hoge", - "conf.default.str_param1", "dara", - "conf.default.vector_param0", "0.0,1.0,2.0,3.0,4.0", - ""] - -class TestProperties(unittest.TestCase) : - - def setUp(self): - - self.prop = Properties(defaults_str=configsample_spec) - - def tearDown(self): - OpenRTM_aist.Manager.instance().shutdownManager() - return - - def test_getName(self): - self.assertEqual(self.prop.getName(), "", "Result failed.") - - - def test_getVlue(self): - self.assertEqual(self.prop.getValue(), "", "Result failed.") - - - def test_getDefaultValue(self): - self.assertEqual(self.prop.getDefaultValue(), "", "Result failed.") - - - - def test_getLeaf(self): - #print self.prop.getLeaf()[0].getName() - #print self.prop.getLeaf()[0].getValue() - - self.assertEqual(self.prop.getLeaf()[0].getName(), "implementation_id", "Result failed.") - self.assertEqual(self.prop.getLeaf()[1].getName(), "type_name", "Result failed.") - self.assertEqual(self.prop.getLeaf()[2].getName(), "description", "Result failed.") - self.assertEqual(self.prop.getLeaf()[3].getName(), "version", "Result failed.") - self.assertEqual(self.prop.getLeaf()[4].getName(), "vendor", "Result failed.") - self.assertEqual(self.prop.getLeaf()[5].getName(), "category", "Result failed.") - self.assertEqual(self.prop.getLeaf()[6].getName(), "activity_type", "Result failed.") - self.assertEqual(self.prop.getLeaf()[7].getName(), "max_instance", "Result failed.") - self.assertEqual(self.prop.getLeaf()[8].getName(), "language", "Result failed.") - self.assertEqual(self.prop.getLeaf()[9].getName(), "lang_type", "Result failed.") - self.assertEqual(self.prop.getLeaf()[10].getLeaf()[0].getLeaf()[0].getName(), "int_param0", "Result failed.") - self.assertEqual(self.prop.getLeaf()[10].getLeaf()[0].getLeaf()[1].getName(), "int_param1", "Result failed.") - self.assertEqual(self.prop.getLeaf()[10].getLeaf()[0].getLeaf()[2].getName(), "double_param0", "Result failed.") - self.assertEqual(self.prop.getLeaf()[10].getLeaf()[0].getLeaf()[3].getName(), "double_param1", "Result failed.") - self.assertEqual(self.prop.getLeaf()[10].getLeaf()[0].getLeaf()[4].getName(), "str_param0", "Result failed.") - self.assertEqual(self.prop.getLeaf()[10].getLeaf()[0].getLeaf()[5].getName(), "str_param1", "Result failed.") - self.assertEqual(self.prop.getLeaf()[10].getLeaf()[0].getLeaf()[6].getName(), "vector_param0", "Result failed.") - - # Failed Patern - # self.assertEqual(self.prop.getLeaf()[10].getName(), "conf.default.int_param0", "Result failed.") - - - def test_getRoot(self): - self.assertEqual(self.prop.getRoot(), None, "Result failed.") - self.assertEqual(self.prop.getLeaf()[10].getRoot().getRoot(), None, "Result failed.") - self.assertEqual(self.prop.getLeaf()[10].getLeaf()[0].getRoot().getName(), "conf", "Result failed.") - self.assertEqual(self.prop.getLeaf()[10].getLeaf()[0].getLeaf()[0].getRoot().getName(), "default", "Result failed.") - - - def test_getProperty(self): - self.assertEqual(self.prop.getProperty("implementation_id"), "ConfigSample", "Result failed.") - self.assertEqual(self.prop.getProperty("type_name"), "ConfigSample", "Result failed.") - self.assertEqual(self.prop.getProperty("description"), "Configuration example component","Result failed.") - self.assertEqual(self.prop.getProperty("version"), "1.0","Result failed.") - self.assertEqual(self.prop.getProperty("vendor"),"Shinji Kurihara, AIST", "Result failed.") - self.assertEqual(self.prop.getProperty("category"), "example","Result failed.") - self.assertEqual(self.prop.getProperty("activity_type"), "DataFlowComponent", "Result failed.") - self.assertEqual(self.prop.getProperty("max_instance"), "10", "Result failed.") - self.assertEqual(self.prop.getProperty("language"), "C++", "Result failed.") - self.assertEqual(self.prop.getProperty("lang_type"), "compile", "Result failed.") - self.assertEqual(self.prop.getProperty("conf.default.int_param0"), "0", "Result failed.") - self.assertEqual(self.prop.getProperty("conf.default.int_param1"), "1", "Result failed.") - self.assertEqual(self.prop.getProperty("conf.default.double_param0"), "0.11", "Result failed.") - self.assertEqual(self.prop.getProperty("conf.default.double_param1"), "9.9", "Result failed.") - self.assertEqual(self.prop.getProperty("conf.default.str_param0"), "hoge", "Result failed.") - self.assertEqual(self.prop.getProperty("conf.default.str_param1"), "dara", "Result failed.") - self.assertEqual(self.prop.getProperty("conf.default.vector_param0"), "0.0,1.0,2.0,3.0,4.0","Result failed.") - - # Failed Pattern - # self.assertEqual(self.prop.getProperty("int_param0"), "0", "Result failed.") - # self.assertEqual(self.prop.getProperty("int_param1"), "1", "Result failed.") - # self.assertEqual(self.prop.getProperty("double_param0"), "0.11", "Result failed.") - # self.assertEqual(self.prop.getProperty("double_param1"), "9.9", "Result failed.") - # self.assertEqual(self.prop.getProperty("str_param0"), "hoge", "Result failed.") - # self.assertEqual(self.prop.getProperty("str_param1"), "dara", "Result failed.") - # self.assertEqual(self.prop.getProperty("vector_param0"), "0.0,1.0,2.0,3.0,4.0","Result failed.") - - - def test_getDefault(self): - self.assertEqual(self.prop.getDefault("implementation_id"), "ConfigSample", "Result failed.") - self.assertEqual(self.prop.getDefault("type_name"), "ConfigSample", "Result failed.") - self.assertEqual(self.prop.getDefault("description"), "Configuration example component","Result failed.") - self.assertEqual(self.prop.getDefault("version"), "1.0","Result failed.") - self.assertEqual(self.prop.getDefault("vendor"),"Shinji Kurihara, AIST", "Result failed.") - self.assertEqual(self.prop.getDefault("category"), "example","Result failed.") - self.assertEqual(self.prop.getDefault("activity_type"), "DataFlowComponent", "Result failed.") - self.assertEqual(self.prop.getDefault("max_instance"), "10", "Result failed.") - self.assertEqual(self.prop.getDefault("language"), "C++", "Result failed.") - self.assertEqual(self.prop.getDefault("lang_type"), "compile", "Result failed.") - self.assertEqual(self.prop.getDefault("conf.default.int_param0"), "0", "Result failed.") - self.assertEqual(self.prop.getDefault("conf.default.int_param1"), "1", "Result failed.") - self.assertEqual(self.prop.getDefault("conf.default.double_param0"), "0.11", "Result failed.") - self.assertEqual(self.prop.getDefault("conf.default.double_param1"), "9.9", "Result failed.") - self.assertEqual(self.prop.getDefault("conf.default.str_param0"), "hoge", "Result failed.") - self.assertEqual(self.prop.getDefault("conf.default.str_param1"), "dara", "Result failed.") - self.assertEqual(self.prop.getDefault("conf.default.vector_param0"), "0.0,1.0,2.0,3.0,4.0","Result failed.") - - - def test_setProperty(self): - self.prop.setProperty("implementation_id", "ConfigSample_test") - self.prop.setProperty("type_name", "ConfigSample_test") - self.prop.setProperty("description", "Configuration example component test") - self.prop.setProperty("version", "2.0") - self.prop.setProperty("vendor","Shinji Kurihara") - self.prop.setProperty("category", "example_test") - self.prop.setProperty("activity_type", "DataFlowComponent") - self.prop.setProperty("max_instance", "1") - self.prop.setProperty("language", "C++") - self.prop.setProperty("lang_type", "compile") - self.prop.setProperty("conf.default.int_param0", "111") - self.prop.setProperty("conf.default.int_param1", "222") - self.prop.setProperty("conf.default.double_param0", "2.22") - self.prop.setProperty("conf.default.double_param1", "9.99") - self.prop.setProperty("conf.default.str_param0", "hogehoge") - self.prop.setProperty("conf.default.str_param1", "daradara") - self.prop.setProperty("conf.default.vector_param0", "0.0,1.1,2.2,3.3,4.4") - - self.assertEqual(self.prop.getProperty("implementation_id"), "ConfigSample_test", "Result failed.") - self.assertEqual(self.prop.getProperty("type_name"), "ConfigSample_test", "Result failed.") - self.assertEqual(self.prop.getProperty("description"), "Configuration example component test","Result failed.") - self.assertEqual(self.prop.getProperty("version"), "2.0","Result failed.") - self.assertEqual(self.prop.getProperty("vendor"),"Shinji Kurihara", "Result failed.") - self.assertEqual(self.prop.getProperty("category"), "example_test","Result failed.") - self.assertEqual(self.prop.getProperty("activity_type"), "DataFlowComponent", "Result failed.") - self.assertEqual(self.prop.getProperty("max_instance"), "1", "Result failed.") - self.assertEqual(self.prop.getProperty("language"), "C++", "Result failed.") - self.assertEqual(self.prop.getProperty("lang_type"), "compile", "Result failed.") - self.assertEqual(self.prop.getProperty("conf.default.int_param0"), "111", "Result failed.") - self.assertEqual(self.prop.getProperty("conf.default.int_param1"), "222", "Result failed.") - self.assertEqual(self.prop.getProperty("conf.default.double_param0"), "2.22", "Result failed.") - self.assertEqual(self.prop.getProperty("conf.default.double_param1"), "9.99", "Result failed.") - self.assertEqual(self.prop.getProperty("conf.default.str_param0"), "hogehoge", "Result failed.") - self.assertEqual(self.prop.getProperty("conf.default.str_param1"), "daradara", "Result failed.") - self.assertEqual(self.prop.getProperty("conf.default.vector_param0"), "0.0,1.1,2.2,3.3,4.4","Result failed.") - - - def test_setDefault(self): - self.prop.setDefault("implementation_id", "ConfigSample") - self.prop.setDefault("type_name", "ConfigSample") - self.prop.setDefault("description", "Configuration example component") - self.prop.setDefault("version", "1.0") - self.prop.setDefault("vendor","Shinji Kurihara") - self.prop.setDefault("category", "example") - self.prop.setDefault("activity_type", "DataFlowComponent") - self.prop.setDefault("max_instance", "10") - self.prop.setDefault("language", "C++") - self.prop.setDefault("lang_type", "compile") - self.prop.setDefault("conf.default.int_param0", "0") - self.prop.setDefault("conf.default.int_param1", "1") - self.prop.setDefault("conf.default.double_param0", "0.11") - self.prop.setDefault("conf.default.double_param1", "9.9") - self.prop.setDefault("conf.default.str_param0", "hoge") - self.prop.setDefault("conf.default.str_param1", "dara") - self.prop.setDefault("conf.default.vector_param0", "0.0,1.0,2.0,3.0,4.0") - - self.assertEqual(self.prop.getDefault("implementation_id"), "ConfigSample", "Result failed.") - self.assertEqual(self.prop.getDefault("type_name"), "ConfigSample", "Result failed.") - self.assertEqual(self.prop.getDefault("description"), "Configuration example component","Result failed.") - self.assertEqual(self.prop.getDefault("version"), "1.0","Result failed.") - self.assertEqual(self.prop.getDefault("vendor"),"Shinji Kurihara", "Result failed.") - self.assertEqual(self.prop.getDefault("category"), "example","Result failed.") - self.assertEqual(self.prop.getDefault("activity_type"), "DataFlowComponent", "Result failed.") - self.assertEqual(self.prop.getDefault("max_instance"), "10", "Result failed.") - self.assertEqual(self.prop.getDefault("language"), "C++", "Result failed.") - self.assertEqual(self.prop.getDefault("lang_type"), "compile", "Result failed.") - self.assertEqual(self.prop.getDefault("conf.default.int_param0"), "0", "Result failed.") - self.assertEqual(self.prop.getDefault("conf.default.int_param1"), "1", "Result failed.") - self.assertEqual(self.prop.getDefault("conf.default.double_param0"), "0.11", "Result failed.") - self.assertEqual(self.prop.getDefault("conf.default.double_param1"), "9.9", "Result failed.") - self.assertEqual(self.prop.getDefault("conf.default.str_param0"), "hoge", "Result failed.") - self.assertEqual(self.prop.getDefault("conf.default.str_param1"), "dara", "Result failed.") - self.assertEqual(self.prop.getDefault("conf.default.vector_param0"), "0.0,1.0,2.0,3.0,4.0","Result failed.") - - - def test_setDefaults(self): - self.prop.setDefaults(configsample_spec) - - self.assertEqual(self.prop.getDefault("implementation_id"), "ConfigSample", "Result failed.") - self.assertEqual(self.prop.getDefault("type_name"), "ConfigSample", "Result failed.") - self.assertEqual(self.prop.getDefault("description"), "Configuration example component","Result failed.") - self.assertEqual(self.prop.getDefault("version"), "1.0","Result failed.") - self.assertEqual(self.prop.getDefault("vendor"),"Shinji Kurihara, AIST", "Result failed.") - self.assertEqual(self.prop.getDefault("category"), "example","Result failed.") - self.assertEqual(self.prop.getDefault("activity_type"), "DataFlowComponent", "Result failed.") - self.assertEqual(self.prop.getDefault("max_instance"), "10", "Result failed.") - self.assertEqual(self.prop.getDefault("language"), "C++", "Result failed.") - self.assertEqual(self.prop.getDefault("lang_type"), "compile", "Result failed.") - self.assertEqual(self.prop.getDefault("conf.default.int_param0"), "0", "Result failed.") - self.assertEqual(self.prop.getDefault("conf.default.int_param1"), "1", "Result failed.") - self.assertEqual(self.prop.getDefault("conf.default.double_param0"), "0.11", "Result failed.") - self.assertEqual(self.prop.getDefault("conf.default.double_param1"), "9.9", "Result failed.") - self.assertEqual(self.prop.getDefault("conf.default.str_param0"), "hoge", "Result failed.") - self.assertEqual(self.prop.getDefault("conf.default.str_param1"), "dara", "Result failed.") - self.assertEqual(self.prop.getDefault("conf.default.vector_param0"), "0.0,1.0,2.0,3.0,4.0","Result failed.") - - - def test_list(self): - #self.prop.list(sys.stdout) - pass - - - def test_load(self): - fp = file("configsample.conf","r") - self.prop.load(fp) - self.assertEqual(self.prop.getProperty("conf.mode0.int_param0"), "12345", "Result failed.") - self.assertEqual(self.prop.getProperty("conf.mode0.int_param1"), "98765", "Result failed.") - self.assertEqual(self.prop.getProperty("conf.mode0.double_param0"), "3.141592653589793238462643383279") - self.assertEqual(self.prop.getProperty("conf.mode0.double_param1"), "2.718281828459045235360287471352", "Result failed.") - self.assertEqual(self.prop.getProperty("conf.mode0.str_param0"), "bar", "Result failed.") - self.assertEqual(self.prop.getProperty("conf.mode0.str_param1"), "foo", "Result failed.") - self.assertEqual(self.prop.getProperty("conf.mode0.vector_param0"), "0.0,0.1,0.2,0.3,0.4","Result failed.") - - - def test_save(self): - fp = file("test_save.data","w") - self.prop.save(fp,"test Properties") - - - def test_store(self): - fp = file("test_store.data","w") - self.prop.store(fp,"test Properties") - - - def test_propertyNames(self): - keys = self.prop.propertyNames() - self.assertEqual(keys[0],"implementation_id", "Result failed.") - self.assertEqual(keys[1],"type_name", "Result failed.") - self.assertEqual(keys[2],"description","Result failed.") - self.assertEqual(keys[3],"version","Result failed.") - self.assertEqual(keys[4],"vendor", "Result failed.") - self.assertEqual(keys[5],"category","Result failed.") - self.assertEqual(keys[6],"activity_type", "Result failed.") - self.assertEqual(keys[7],"max_instance", "Result failed.") - self.assertEqual(keys[8],"language", "Result failed.") - self.assertEqual(keys[9],"lang_type", "Result failed.") - self.assertEqual(keys[10],"conf.default.int_param0", "Result failed.") - self.assertEqual(keys[11],"conf.default.int_param1", "Result failed.") - self.assertEqual(keys[12],"conf.default.double_param0", "Result failed.") - self.assertEqual(keys[13],"conf.default.double_param1", "Result failed.") - self.assertEqual(keys[14],"conf.default.str_param0", "Result failed.") - self.assertEqual(keys[15],"conf.default.str_param1", "Result failed.") - self.assertEqual(keys[16],"conf.default.vector_param0","Result failed.") - - - def test_size(self): - self.assertEqual(self.prop.size(),17,"Result failed.") - - - def test_findNode(self): - self.assertEqual(self.prop.findNode("implementation_id").getDefaultValue(), "ConfigSample", "Result failed.") - - def test_getNode(self): - self.assertEqual(self.prop.getNode("implementation_id").getDefaultValue(), "ConfigSample", "Result failed.") - self.assertEqual(self.prop.getNode("type_name").getDefaultValue(), "ConfigSample", "Result failed.") - self.assertEqual(self.prop.getNode("description").getDefaultValue(), "Configuration example component","Result failed.") - self.assertEqual(self.prop.getNode("version").getDefaultValue(), "1.0","Result failed.") - self.assertEqual(self.prop.getNode("vendor").getDefaultValue(),"Shinji Kurihara, AIST", "Result failed.") - self.assertEqual(self.prop.getNode("category").getDefaultValue(), "example","Result failed.") - self.assertEqual(self.prop.getNode("activity_type").getDefaultValue(), "DataFlowComponent", "Result failed.") - self.assertEqual(self.prop.getNode("max_instance").getDefaultValue(), "10", "Result failed.") - self.assertEqual(self.prop.getNode("language").getDefaultValue(), "C++", "Result failed.") - self.assertEqual(self.prop.getNode("lang_type").getDefaultValue(), "compile", "Result failed.") - self.assertEqual(self.prop.getNode("conf.default.int_param0").getDefaultValue(), "0", "Result failed.") - self.assertEqual(self.prop.getNode("conf.default.int_param1").getDefaultValue(), "1", "Result failed.") - self.assertEqual(self.prop.getNode("conf.default.double_param0").getDefaultValue(), "0.11", "Result failed.") - self.assertEqual(self.prop.getNode("conf.default.double_param1").getDefaultValue(), "9.9", "Result failed.") - self.assertEqual(self.prop.getNode("conf.default.str_param0").getDefaultValue(), "hoge", "Result failed.") - self.assertEqual(self.prop.getNode("conf.default.str_param1").getDefaultValue(), "dara", "Result failed.") - self.assertEqual(self.prop.getNode("conf.default.vector_param0").getDefaultValue(), "0.0,1.0,2.0,3.0,4.0","Result failed.") - - - def test_createNode(self): - self.assertEqual(self.prop.createNode("conf.default.int_param.0"),True, "Result failed.") - self.assertEqual(self.prop.createNode("conf.add.int_param1"),True, "Result failed.") - self.assertEqual(len(self.prop.getNode("conf.default").leaf), 8, "Result failed.") - self.assertEqual(len(self.prop.getNode("conf.add").leaf), 1, "Result failed.") - - - def test_removeNode(self): - node = self.prop.getNode("conf.default") - node.removeNode("int_param0") - self.assertEqual( len(self.prop.getNode("conf.default").leaf),6, "Result failed.") - - node = self.prop.getNode("conf") - node.removeNode("default") - self.assertEqual( len(self.prop.getNode("conf").leaf),0, "Result failed.") - - - def test_hasKey(self): - node = self.prop.getNode("conf") - self.assertEqual(len(node.hasKey("default").leaf),7, "Result failed.") - - self.assertEqual(self.prop.hasKey("default"),None, "Result failed.") - - - def test_clear(self): - self.prop.clear() - self.assertEqual(self.prop.getProperty("implementation_id"), "", "Result failed.") - - # Failed Pattern - # self.assertEqual(self.prop.getProperty("implementation_id"), "ConfigSample", "Result failed.") - - - def test_splitKeyValue(self): - key=[] - val=[] - self.prop.splitKeyValue("key:value",key,val) - self.assertEqual(key[0],"key") - self.assertEqual(val[0],"value") - - - def test_split(self): - val=[] - self.prop.split("test.split,hoge",".",val) - - self.assertEqual(val, ["test","split,hoge"]) - - - def test_mergeProperties(self): - self.prop.mergeProperties(self.prop) - self.assertEqual(self.prop.getProperty("implementation_id"), "ConfigSample", "Result failed.") - - - def test_dump(self): - print self.prop - - - -############### test ################# -if __name__ == '__main__': - unittest.main() diff --git a/OpenRTM_aist/test/test_PublisherFlush.py b/OpenRTM_aist/test/test_PublisherFlush.py deleted file mode 100755 index e0404740..00000000 --- a/OpenRTM_aist/test/test_PublisherFlush.py +++ /dev/null @@ -1,76 +0,0 @@ -#!/usr/bin/env python -# -*- Python -*- - -# -# \file test_PublisherFlush.py -# \brief test for PublisherFlush class -# \date $Date: 2007/09/27 $ -# \author Shinji Kurihara -# -# Copyright (C) 2006 -# Noriaki Ando -# Task-intelligence Research Group, -# Intelligent Systems Research Institute, -# National Institute of -# Advanced Industrial Science and Technology (AIST), Japan -# All rights reserved. - -import sys -sys.path.insert(1,"../") - -import unittest - -from PublisherFlush import * -import OpenRTM_aist - -class Consumer: - def put(self,data): - return data - -class TestPublisherNew(unittest.TestCase): - - def setUp(self): - self._pf = PublisherFlush() - return - - def test_init(self): - self.assertEqual(self._pf.init(None),OpenRTM_aist.DataPortStatus.PORT_OK) - return - - def test_setConsumer(self): - self.assertEqual(self._pf.setConsumer(None),OpenRTM_aist.DataPortStatus.INVALID_ARGS) - self.assertEqual(self._pf.init(Consumer()),OpenRTM_aist.DataPortStatus.PORT_OK) - return - - def test_setBuffer(self): - self.assertEqual(self._pf.setBuffer(None),OpenRTM_aist.DataPortStatus.PORT_OK) - return - - def test_write(self): - prop = OpenRTM_aist.Properties() - cinfo = OpenRTM_aist.ConnectorInfo("", - "", - [], - prop) - self.assertEqual(self._pf.write(123,0,0),OpenRTM_aist.DataPortStatus.PRECONDITION_NOT_MET) - self.assertEqual(self._pf.setConsumer(OpenRTM_aist.InPortCorbaCdrConsumer()), - OpenRTM_aist.DataPortStatus.PORT_OK) - self.assertEqual(self._pf.setListener(cinfo,OpenRTM_aist.ConnectorListeners()), - OpenRTM_aist.DataPortStatus.PORT_OK) - self.assertEqual(self._pf.write(123,0,0),OpenRTM_aist.DataPortStatus.CONNECTION_LOST) - return - - def test_activate_deactivate_isActive(self): - self.assertEqual(self._pf.isActive(),False) - self.assertEqual(self._pf.activate(),OpenRTM_aist.DataPortStatus.PORT_OK) - self.assertEqual(self._pf.isActive(),True) - self.assertEqual(self._pf.activate(),OpenRTM_aist.DataPortStatus.PRECONDITION_NOT_MET) - self.assertEqual(self._pf.deactivate(),OpenRTM_aist.DataPortStatus.PORT_OK) - self.assertEqual(self._pf.isActive(),False) - self.assertEqual(self._pf.deactivate(),OpenRTM_aist.DataPortStatus.PRECONDITION_NOT_MET) - return - - -############### test ################# -if __name__ == '__main__': - unittest.main() diff --git a/OpenRTM_aist/test/test_PublisherNew.py b/OpenRTM_aist/test/test_PublisherNew.py deleted file mode 100755 index 7b8b7dcb..00000000 --- a/OpenRTM_aist/test/test_PublisherNew.py +++ /dev/null @@ -1,383 +0,0 @@ -#!/usr/bin/env python -# -*- coding: euc-jp -*- - -# -# \file test_PublisherNew.py -# \brief test for PublisherNew class -# \date $Date: 2007/09/27 $ -# \author Shinji Kurihara -# -# Copyright (C) 2006 -# Noriaki Ando -# Task-intelligence Research Group, -# Intelligent Systems Research Institute, -# National Institute of -# Advanced Industrial Science and Technology (AIST), Japan -# All rights reserved. - -import sys,time -sys.path.insert(1,"../") - -import unittest - -import OpenRTM_aist -from PublisherNew import * - -class ConsumerMock(OpenRTM_aist.InPortCorbaCdrConsumer): - def __init__(self): - buff = OpenRTM_aist.CdrRingBuffer() - prop = OpenRTM_aist.Properties() - prop.setProperty("write.full_policy","do_nothing") - buff.init(prop) - self._buffer = buff - - def __del__(self): - pass - - def convertReturnCode(self, ret): - if ret == OpenRTM_aist.BufferStatus.BUFFER_OK: - return self.PORT_OK - - elif ret == OpenRTM_aist.BufferStatus.BUFFER_ERROR: - return self.PORT_ERROR - - elif ret == OpenRTM_aist.BufferStatus.BUFFER_FULL: - return self.SEND_FULL - - elif ret == OpenRTM_aist.BufferStatus.TIMEOUT: - return self.SEND_TIMEOUT - - elif ret == OpenRTM_aist.BufferStatus.NOT_SUPPORTED: - return self.UNKNOWN_ERROR - - else: - return self.UNKNOWN_ERROR - - def put(self,data): - ret = self.convertReturnCode(self._buffer.write(data)) - return ret - """ - if self._buffer.full(): - return OpenRTM_aist.DataPortStatus.BUFFER_FULL - - ret = self._buffer.write(data) - if ret == OpenRTM_aist.BufferStatus.BUFFER_OK: - return OpenRTM_aist.DataPortStatus.PORT_OK - elif ret == OpenRTM_aist.BufferStatus.BUFFER_ERROR: - return OpenRTM_aist.DataPortStatus.PORT_ERROR - elif ret == OpenRTM_aist.BufferStatus.BUFFER_FULL: - return OpenRTM_aist.DataPortStatus.BUFFER_FULL - elif ret == OpenRTM_aist.BufferStatus.BUFFER_EMPTY: - return OpenRTM_aist.DataPortStatus.BUFFER_EMPTY - elif ret == OpenRTM_aist.BufferStatus.TIMEOUT: - return OpenRTM_aist.DataPortStatus.BUFFER_TIMEOUT - else: - return OpenRTM_aist.DataPortStatus.UNKNOWN_ERROR - """ - - def get_m_put_data(self): - cdr = [0] - self._buffer.read(cdr) - return cdr[0] - - def get_m_put_data_len(self): - ic = self._buffer.readable() - return ic - - - -class TestPublisherNew(unittest.TestCase): - - def setUp(self): - time.sleep(0.1) - return - - def tearDown(self): - OpenRTM_aist.Manager.instance().shutdownManager() - return - - def test_init(self): - _pn = PublisherNew() - prop = OpenRTM_aist.Properties() - # Propertiesξ֤Ǥư뤳Ȥǧ - ret = _pn.init(prop) - self.assertEqual(OpenRTM_aist.DataPortStatus.PORT_OK, ret) - _pn.__del__() - - _pn = PublisherNew() - prop.setProperty("publisher.push_policy","new") - prop.setProperty("thread_type","bar") - prop.setProperty("measurement.exec_time","default") - prop.setProperty("measurement.period_count","1") - - #thread_type ξ INVALID_ARGS ֤Ȥǧ롣 - ret = _pn.init(prop) - self.assertEqual(OpenRTM_aist.DataPortStatus.INVALID_ARGS, ret) - _pn.__del__() - - _pn = PublisherNew() - #ʲpropertiesư뤳Ȥǧ롣 - prop.setProperty("publisher.push_policy","all") - prop.setProperty("publisher.skip_count","0") - prop.setProperty("thread_type","default") - prop.setProperty("measurement.exec_time","enable") - prop.setProperty("measurement.exec_count","0") - prop.setProperty("measurement.period_time","enable") - prop.setProperty("measurement.period_count","0") - retcode = _pn.init(prop) - self.assertEqual(OpenRTM_aist.DataPortStatus.PORT_OK, retcode) - _pn.__del__() - - _pn = PublisherNew() - prop.setProperty("publisher.push_policy","fifo") - prop.setProperty("publisher.skip_count","1") - prop.setProperty("thread_type","default") - prop.setProperty("measurement.exec_time","disable") - prop.setProperty("measurement.exec_count","1") - prop.setProperty("measurement.period_time","disable") - prop.setProperty("measurement.period_count","0") - retcode = _pn.init(prop) - self.assertEqual(OpenRTM_aist.DataPortStatus.PORT_OK, retcode) - _pn.__del__() - - _pn = PublisherNew() - prop.setProperty("publisher.push_policy","fifo") - prop.setProperty("publisher.skip_count","1") - prop.setProperty("thread_type","default") - prop.setProperty("measurement.exec_time","disable") - prop.setProperty("measurement.exec_count","1") - prop.setProperty("measurement.period_time","disable") - prop.setProperty("measurement.period_count","1") - retcode = _pn.init(prop) - self.assertEqual(OpenRTM_aist.DataPortStatus.PORT_OK, retcode) - _pn.__del__() - - _pn = PublisherNew() - prop.setProperty("publisher.push_policy","skip") - prop.setProperty("publisher.skip_count","-1") - prop.setProperty("thread_type","default") - prop.setProperty("measurement.exec_time","bar") - prop.setProperty("measurement.exec_count","-1") - prop.setProperty("measurement.period_time","bar") - prop.setProperty("measurement.period_count","-1") - retcode = _pn.init(prop) - self.assertEqual(OpenRTM_aist.DataPortStatus.PORT_OK, retcode) - _pn.__del__() - - _pn = PublisherNew() - prop.setProperty("publisher.push_policy","new") - prop.setProperty("publisher.skip_count","1") - prop.setProperty("thread_type","default") - prop.setProperty("measurement.exec_time","enable") - prop.setProperty("measurement.exec_count","1") - prop.setProperty("measurement.period_time","enable") - prop.setProperty("measurement.period_count","1") - retcode = _pn.init(prop) - self.assertEqual(OpenRTM_aist.DataPortStatus.PORT_OK, retcode) - _pn.__del__() - - _pn = PublisherNew() - prop.setProperty("publisher.push_policy","bar") - prop.setProperty("publisher.skip_count","0") - prop.setProperty("thread_type","default") - prop.setProperty("measurement.exec_time","enable") - prop.setProperty("measurement.exec_count","0") - prop.setProperty("measurement.period_time","enable") - prop.setProperty("measurement.period_count","0") - retcode = _pn.init(prop) - self.assertEqual(OpenRTM_aist.DataPortStatus.PORT_OK, retcode) - _pn.__del__() - return - - def test_setConsumer(self): - _pn = PublisherNew() - self.assertEqual(_pn.setConsumer(None),OpenRTM_aist.DataPortStatus.INVALID_ARGS) - self.assertEqual(_pn.setConsumer(ConsumerMock()),OpenRTM_aist.DataPortStatus.PORT_OK) - _pn.__del__() - return - - def test_setBuffer(self): - _pn = PublisherNew() - self.assertEqual(_pn.setBuffer(None),OpenRTM_aist.DataPortStatus.INVALID_ARGS) - self.assertEqual(_pn.setBuffer(OpenRTM_aist.RingBuffer()),OpenRTM_aist.DataPortStatus.PORT_OK) - _pn.__del__() - return - - def test_write(self): - _pn = PublisherNew() - prop = OpenRTM_aist.Properties() - retcode = _pn.init(prop) - _pn.setBuffer(OpenRTM_aist.RingBuffer()) - #self.assertEqual(_pn.write(123,0,0),OpenRTM_aist.DataPortStatus.PORT_OK) - _pn.__del__() - return - - def test_activate_deactivate_isActive(self): - _pn = PublisherNew() - self.assertEqual(_pn.isActive(),False) - self.assertEqual(_pn.activate(),OpenRTM_aist.DataPortStatus.PORT_OK) - self.assertEqual(_pn.isActive(),True) - self.assertEqual(_pn.deactivate(),OpenRTM_aist.DataPortStatus.PORT_OK) - self.assertEqual(_pn.isActive(),False) - _pn.__del__() - return - - def test_pushAll(self): - _pn = PublisherNew() - prop = OpenRTM_aist.Properties() - cinfo = OpenRTM_aist.ConnectorInfo("", - "", - [], - prop) - self.assertEqual(_pn.setListener(cinfo,OpenRTM_aist.ConnectorListeners()), - OpenRTM_aist.DataPortStatus.PORT_OK) - prop = OpenRTM_aist.Properties() - prop.setProperty("publisher.push_policy","all") - prop.setProperty("publisher.skip_count","0") - prop.setProperty("thread_type","default") - prop.setProperty("measurement.exec_time","enable") - prop.setProperty("measurement.exec_count","0") - prop.setProperty("measurement.period_time","enable") - prop.setProperty("measurement.period_count","0") - retcode = _pn.init(prop) - cons = ConsumerMock() - self.assertEqual(_pn.setConsumer(cons),OpenRTM_aist.DataPortStatus.PORT_OK) - _pn.setBuffer(OpenRTM_aist.CdrRingBuffer()) - _pn.activate() - - self.assertEqual(_pn.write(123,0,0),OpenRTM_aist.DataPortStatus.PORT_OK) - self.assertEqual(_pn.write(123,0,0),OpenRTM_aist.DataPortStatus.PORT_OK) - self.assertEqual(_pn.write(123,0,0),OpenRTM_aist.DataPortStatus.PORT_OK) - self.assertEqual(_pn.write(123,0,0),OpenRTM_aist.DataPortStatus.PORT_OK) - self.assertEqual(_pn.write(123,0,0),OpenRTM_aist.DataPortStatus.PORT_OK) - self.assertEqual(_pn.write(123,0,0),OpenRTM_aist.DataPortStatus.PORT_OK) - self.assertEqual(_pn.write(123,0,0),OpenRTM_aist.DataPortStatus.PORT_OK) - self.assertEqual(_pn.write(123,0,0),OpenRTM_aist.DataPortStatus.PORT_OK) - _pn.deactivate() - _pn.__del__() - return - - def test_pushFifo(self): - _pn = PublisherNew() - prop = OpenRTM_aist.Properties() - cinfo = OpenRTM_aist.ConnectorInfo("", - "", - [], - prop) - self.assertEqual(_pn.setListener(cinfo,OpenRTM_aist.ConnectorListeners()), - OpenRTM_aist.DataPortStatus.PORT_OK) - prop = OpenRTM_aist.Properties() - prop.setProperty("publisher.push_policy","fifo") - prop.setProperty("publisher.skip_count","0") - prop.setProperty("thread_type","default") - prop.setProperty("measurement.exec_time","enable") - prop.setProperty("measurement.exec_count","0") - prop.setProperty("measurement.period_time","enable") - prop.setProperty("measurement.period_count","0") - retcode = _pn.init(prop) - cons = ConsumerMock() - self.assertEqual(_pn.setConsumer(cons),OpenRTM_aist.DataPortStatus.PORT_OK) - _pn.setBuffer(OpenRTM_aist.CdrRingBuffer()) - _pn.activate() - - self.assertEqual(_pn.write(123,0,0),OpenRTM_aist.DataPortStatus.PORT_OK) - self.assertEqual(_pn.write(123,0,0),OpenRTM_aist.DataPortStatus.PORT_OK) - self.assertEqual(_pn.write(123,0,0),OpenRTM_aist.DataPortStatus.PORT_OK) - self.assertEqual(_pn.write(123,0,0),OpenRTM_aist.DataPortStatus.PORT_OK) - self.assertEqual(_pn.write(123,0,0),OpenRTM_aist.DataPortStatus.PORT_OK) - self.assertEqual(_pn.write(123,0,0),OpenRTM_aist.DataPortStatus.PORT_OK) - self.assertEqual(_pn.write(123,0,0),OpenRTM_aist.DataPortStatus.PORT_OK) - self.assertEqual(_pn.write(123,0,0),OpenRTM_aist.DataPortStatus.PORT_OK) - _pn.deactivate() - _pn.__del__() - return - - - def test_pushSkip(self): - _pn = PublisherNew() - prop = OpenRTM_aist.Properties() - cinfo = OpenRTM_aist.ConnectorInfo("", - "", - [], - prop) - self.assertEqual(_pn.setListener(cinfo,OpenRTM_aist.ConnectorListeners()), - OpenRTM_aist.DataPortStatus.PORT_OK) - prop = OpenRTM_aist.Properties() - prop.setProperty("publisher.push_policy","skip") - prop.setProperty("publisher.skip_count","0") - prop.setProperty("thread_type","default") - prop.setProperty("measurement.exec_time","enable") - prop.setProperty("measurement.exec_count","0") - prop.setProperty("measurement.period_time","enable") - prop.setProperty("measurement.period_count","0") - retcode = _pn.init(prop) - cons = ConsumerMock() - self.assertEqual(_pn.setConsumer(cons),OpenRTM_aist.DataPortStatus.PORT_OK) - _pn.setBuffer(OpenRTM_aist.CdrRingBuffer()) - _pn.activate() - - self.assertEqual(_pn.write(123,0,0),OpenRTM_aist.DataPortStatus.PORT_OK) - self.assertEqual(_pn.write(123,0,0),OpenRTM_aist.DataPortStatus.PORT_OK) - self.assertEqual(_pn.write(123,0,0),OpenRTM_aist.DataPortStatus.PORT_OK) - self.assertEqual(_pn.write(123,0,0),OpenRTM_aist.DataPortStatus.PORT_OK) - self.assertEqual(_pn.write(123,0,0),OpenRTM_aist.DataPortStatus.PORT_OK) - self.assertEqual(_pn.write(123,0,0),OpenRTM_aist.DataPortStatus.PORT_OK) - self.assertEqual(_pn.write(123,0,0),OpenRTM_aist.DataPortStatus.PORT_OK) - self.assertEqual(_pn.write(123,0,0),OpenRTM_aist.DataPortStatus.PORT_OK) - _pn.deactivate() - _pn.__del__() - return - - def test_pushNew(self): - _pn = PublisherNew() - prop = OpenRTM_aist.Properties() - cinfo = OpenRTM_aist.ConnectorInfo("", - "", - [], - prop) - self.assertEqual(_pn.setListener(cinfo,OpenRTM_aist.ConnectorListeners()), - OpenRTM_aist.DataPortStatus.PORT_OK) - prop = OpenRTM_aist.Properties() - prop.setProperty("publisher.push_policy","new") - prop.setProperty("publisher.skip_count","0") - prop.setProperty("thread_type","default") - prop.setProperty("measurement.exec_time","enable") - prop.setProperty("measurement.exec_count","0") - prop.setProperty("measurement.period_time","enable") - prop.setProperty("measurement.period_count","0") - retcode = _pn.init(prop) - cons = ConsumerMock() - self.assertEqual(_pn.setConsumer(cons),OpenRTM_aist.DataPortStatus.PORT_OK) - _pn.setBuffer(OpenRTM_aist.CdrRingBuffer()) - _pn.activate() - - self.assertEqual(_pn.write(123,0,0),OpenRTM_aist.DataPortStatus.PORT_OK) - self.assertEqual(_pn.write(123,0,0),OpenRTM_aist.DataPortStatus.PORT_OK) - self.assertEqual(_pn.write(123,0,0),OpenRTM_aist.DataPortStatus.PORT_OK) - self.assertEqual(_pn.write(123,0,0),OpenRTM_aist.DataPortStatus.PORT_OK) - self.assertEqual(_pn.write(123,0,0),OpenRTM_aist.DataPortStatus.PORT_OK) - self.assertEqual(_pn.write(123,0,0),OpenRTM_aist.DataPortStatus.PORT_OK) - self.assertEqual(_pn.write(123,0,0),OpenRTM_aist.DataPortStatus.PORT_OK) - self.assertEqual(_pn.write(123,0,0),OpenRTM_aist.DataPortStatus.PORT_OK) - _pn.deactivate() - _pn.__del__() - return - - def test_convertReturn(self): - _pn = PublisherNew() - self.assertEqual(_pn.convertReturn(OpenRTM_aist.BufferStatus.BUFFER_OK,0), - OpenRTM_aist.DataPortStatus.PORT_OK) - self.assertEqual(_pn.convertReturn(OpenRTM_aist.BufferStatus.BUFFER_FULL,0), - OpenRTM_aist.DataPortStatus.BUFFER_FULL) - self.assertEqual(_pn.convertReturn(OpenRTM_aist.BufferStatus.TIMEOUT,0), - OpenRTM_aist.DataPortStatus.BUFFER_TIMEOUT) - self.assertEqual(_pn.convertReturn(OpenRTM_aist.BufferStatus.PRECONDITION_NOT_MET,0), - OpenRTM_aist.DataPortStatus.PRECONDITION_NOT_MET) - self.assertEqual(_pn.convertReturn(100,0), - OpenRTM_aist.DataPortStatus.PORT_ERROR) - _pn.__del__() - return - -############ test ################# -if __name__ == '__main__': - unittest.main() diff --git a/OpenRTM_aist/test/test_PublisherPeriodic.py b/OpenRTM_aist/test/test_PublisherPeriodic.py deleted file mode 100755 index d2219280..00000000 --- a/OpenRTM_aist/test/test_PublisherPeriodic.py +++ /dev/null @@ -1,401 +0,0 @@ -#!/usr/bin/env python -# -*- coding: euc-jp -*- - -# -# \file test_PublisherPeriodic.py -# \brief test for PublisherPeriodic class -# \date $Date: 2007/09/27 $ -# \author Shinji Kurihara -# -# Copyright (C) 2006 -# Noriaki Ando -# Task-intelligence Research Group, -# Intelligent Systems Research Institute, -# National Institute of -# Advanced Industrial Science and Technology (AIST), Japan -# All rights reserved. - -import sys,time -sys.path.insert(1,"../") - -import unittest - -import OpenRTM_aist -from PublisherPeriodic import * - -class ConsumerMock(OpenRTM_aist.InPortCorbaCdrConsumer): - def __init__(self): - buff = OpenRTM_aist.CdrRingBuffer() - prop = OpenRTM_aist.Properties() - prop.setProperty("write.full_policy","do_nothing") - buff.init(prop) - self._buffer = buff - - def __del__(self): - pass - - def convertReturnCode(self, ret): - if ret == OpenRTM_aist.BufferStatus.BUFFER_OK: - return self.PORT_OK - - elif ret == OpenRTM_aist.BufferStatus.BUFFER_ERROR: - return self.PORT_ERROR - - elif ret == OpenRTM_aist.BufferStatus.BUFFER_FULL: - return self.SEND_FULL - - elif ret == OpenRTM_aist.BufferStatus.TIMEOUT: - return self.SEND_TIMEOUT - - elif ret == OpenRTM_aist.BufferStatus.NOT_SUPPORTED: - return self.UNKNOWN_ERROR - - else: - return self.UNKNOWN_ERROR - - def put(self,data): - return self.convertReturnCode(self._buffer.write(data)) - - """ - if self._buffer.full(): - return OpenRTM_aist.DataPortStatus.BUFFER_FULL - - ret = self._buffer.write(data) - if ret == OpenRTM_aist.BufferStatus.BUFFER_OK: - return OpenRTM_aist.DataPortStatus.PORT_OK - elif ret == OpenRTM_aist.BufferStatus.BUFFER_ERROR: - return OpenRTM_aist.DataPortStatus.PORT_ERROR - elif ret == OpenRTM_aist.BufferStatus.BUFFER_FULL: - return OpenRTM_aist.DataPortStatus.BUFFER_FULL - elif ret == OpenRTM_aist.BufferStatus.BUFFER_EMPTY: - return OpenRTM_aist.DataPortStatus.BUFFER_EMPTY - elif ret == OpenRTM_aist.BufferStatus.TIMEOUT: - return OpenRTM_aist.DataPortStatus.BUFFER_TIMEOUT - else: - return OpenRTM_aist.DataPortStatus.UNKNOWN_ERROR - """ - - def get_m_put_data(self): - cdr = [0] - self._buffer.read(cdr) - return cdr[0] - - def get_m_put_data_len(self): - ic = self._buffer.readable() - return ic - - - -class TestPublisherPeriodic(unittest.TestCase): - - def setUp(self): - time.sleep(0.1) - return - - def tearDown(self): - time.sleep(0.1) - OpenRTM_aist.Manager.instance().shutdownManager() - return - - def test_init(self): - _pn = PublisherPeriodic() - prop = OpenRTM_aist.Properties() - # Propertiesξ֤Ǥư뤳Ȥǧ - ret = _pn.init(prop) - self.assertEqual(OpenRTM_aist.DataPortStatus.PORT_OK, ret) - time.sleep(0.1) - _pn.__del__() - - _pn = PublisherPeriodic() - prop.setProperty("publisher.push_policy","new") - prop.setProperty("thread_type","bar") - prop.setProperty("measurement.exec_time","default") - prop.setProperty("measurement.period_count","1") - - #thread_type ξ INVALID_ARGS ֤Ȥǧ롣 - ret = _pn.init(prop) - self.assertEqual(OpenRTM_aist.DataPortStatus.INVALID_ARGS, ret) - _pn.__del__() - - _pn = PublisherPeriodic() - #ʲpropertiesư뤳Ȥǧ롣 - prop.setProperty("publisher.push_policy","all") - prop.setProperty("publisher.skip_count","0") - prop.setProperty("thread_type","default") - prop.setProperty("measurement.exec_time","enable") - prop.setProperty("measurement.exec_count","0") - prop.setProperty("measurement.period_time","enable") - prop.setProperty("measurement.period_count","0") - retcode = _pn.init(prop) - self.assertEqual(OpenRTM_aist.DataPortStatus.PORT_OK, retcode) - _pn.__del__() - - _pn = PublisherPeriodic() - prop.setProperty("publisher.push_policy","fifo") - prop.setProperty("publisher.skip_count","1") - prop.setProperty("thread_type","default") - prop.setProperty("measurement.exec_time","disable") - prop.setProperty("measurement.exec_count","1") - prop.setProperty("measurement.period_time","disable") - prop.setProperty("measurement.period_count","0") - retcode = _pn.init(prop) - self.assertEqual(OpenRTM_aist.DataPortStatus.PORT_OK, retcode) - _pn.__del__() - - _pn = PublisherPeriodic() - prop.setProperty("publisher.push_policy","fifo") - prop.setProperty("publisher.skip_count","1") - prop.setProperty("thread_type","default") - prop.setProperty("measurement.exec_time","disable") - prop.setProperty("measurement.exec_count","1") - prop.setProperty("measurement.period_time","disable") - prop.setProperty("measurement.period_count","1") - retcode = _pn.init(prop) - self.assertEqual(OpenRTM_aist.DataPortStatus.PORT_OK, retcode) - _pn.__del__() - - _pn = PublisherPeriodic() - prop.setProperty("publisher.push_policy","skip") - prop.setProperty("publisher.skip_count","-1") - prop.setProperty("thread_type","default") - prop.setProperty("measurement.exec_time","bar") - prop.setProperty("measurement.exec_count","-1") - prop.setProperty("measurement.period_time","bar") - prop.setProperty("measurement.period_count","-1") - retcode = _pn.init(prop) - self.assertEqual(OpenRTM_aist.DataPortStatus.PORT_OK, retcode) - _pn.__del__() - - _pn = PublisherPeriodic() - prop.setProperty("publisher.push_policy","new") - prop.setProperty("publisher.skip_count","1") - prop.setProperty("thread_type","default") - prop.setProperty("measurement.exec_time","enable") - prop.setProperty("measurement.exec_count","1") - prop.setProperty("measurement.period_time","enable") - prop.setProperty("measurement.period_count","1") - retcode = _pn.init(prop) - self.assertEqual(OpenRTM_aist.DataPortStatus.PORT_OK, retcode) - _pn.__del__() - - _pn = PublisherPeriodic() - prop.setProperty("publisher.push_policy","bar") - prop.setProperty("publisher.skip_count","0") - prop.setProperty("thread_type","default") - prop.setProperty("measurement.exec_time","enable") - prop.setProperty("measurement.exec_count","0") - prop.setProperty("measurement.period_time","enable") - prop.setProperty("measurement.period_count","0") - retcode = _pn.init(prop) - self.assertEqual(OpenRTM_aist.DataPortStatus.PORT_OK, retcode) - _pn.__del__() - - return - - def test_setConsumer(self): - _pn = PublisherPeriodic() - self.assertEqual(_pn.setConsumer(None),OpenRTM_aist.DataPortStatus.INVALID_ARGS) - self.assertEqual(_pn.setConsumer(ConsumerMock()),OpenRTM_aist.DataPortStatus.PORT_OK) - _pn.__del__() - return - - def test_setBuffer(self): - _pn = PublisherPeriodic() - self.assertEqual(_pn.setBuffer(None),OpenRTM_aist.DataPortStatus.INVALID_ARGS) - self.assertEqual(_pn.setBuffer(OpenRTM_aist.RingBuffer()),OpenRTM_aist.DataPortStatus.PORT_OK) - _pn.__del__() - return - - def test_write(self): - _pn = PublisherPeriodic() - prop = OpenRTM_aist.Properties() - retcode = _pn.init(prop) - _pn.setBuffer(OpenRTM_aist.RingBuffer()) - _pn.__del__() - #self.assertEqual(_pn.write(123,0,0),OpenRTM_aist.DataPortStatus.PORT_OK) - return - - def test_activate_deactivate_isActive(self): - _pn = PublisherPeriodic() - prop = OpenRTM_aist.Properties() - retcode = _pn.init(prop) - self.assertEqual(_pn.isActive(),False) - cons = ConsumerMock() - self.assertEqual(_pn.setConsumer(cons),OpenRTM_aist.DataPortStatus.PORT_OK) - _pn.setBuffer(OpenRTM_aist.CdrRingBuffer()) - self.assertEqual(_pn.activate(),OpenRTM_aist.DataPortStatus.PORT_OK) - self.assertEqual(_pn.isActive(),True) - self.assertEqual(_pn.deactivate(),OpenRTM_aist.DataPortStatus.PORT_OK) - self.assertEqual(_pn.isActive(),False) - _pn.__del__() - return - - def test_pushAll(self): - _pn = PublisherPeriodic() - prop = OpenRTM_aist.Properties() - cinfo = OpenRTM_aist.ConnectorInfo("", - "", - [], - prop) - self.assertEqual(_pn.setListener(cinfo,OpenRTM_aist.ConnectorListeners()), - OpenRTM_aist.DataPortStatus.PORT_OK) - prop = OpenRTM_aist.Properties() - prop.setProperty("publisher.push_policy","all") - prop.setProperty("publisher.skip_count","0") - prop.setProperty("thread_type","default") - prop.setProperty("measurement.exec_time","enable") - prop.setProperty("measurement.exec_count","0") - prop.setProperty("measurement.period_time","enable") - prop.setProperty("measurement.period_count","0") - retcode = _pn.init(prop) - cons = ConsumerMock() - self.assertEqual(_pn.setConsumer(cons),OpenRTM_aist.DataPortStatus.PORT_OK) - _pn.setBuffer(OpenRTM_aist.CdrRingBuffer()) - _pn.activate() - - self.assertEqual(_pn.write(123,0,0),OpenRTM_aist.DataPortStatus.PORT_OK) - self.assertEqual(_pn.write(123,0,0),OpenRTM_aist.DataPortStatus.PORT_OK) - self.assertEqual(_pn.write(123,0,0),OpenRTM_aist.DataPortStatus.PORT_OK) - self.assertEqual(_pn.write(123,0,0),OpenRTM_aist.DataPortStatus.PORT_OK) - self.assertEqual(_pn.write(123,0,0),OpenRTM_aist.DataPortStatus.PORT_OK) - self.assertEqual(_pn.write(123,0,0),OpenRTM_aist.DataPortStatus.PORT_OK) - self.assertEqual(_pn.write(123,0,0),OpenRTM_aist.DataPortStatus.PORT_OK) - self.assertEqual(_pn.write(123,0,0),OpenRTM_aist.DataPortStatus.PORT_OK) - _pn.deactivate() - _pn.__del__() - return - - def test_pushFifo(self): - _pn = PublisherPeriodic() - prop = OpenRTM_aist.Properties() - cinfo = OpenRTM_aist.ConnectorInfo("", - "", - [], - prop) - self.assertEqual(_pn.setListener(cinfo,OpenRTM_aist.ConnectorListeners()), - OpenRTM_aist.DataPortStatus.PORT_OK) - prop = OpenRTM_aist.Properties() - prop.setProperty("publisher.push_policy","fifo") - prop.setProperty("publisher.skip_count","0") - prop.setProperty("thread_type","default") - prop.setProperty("measurement.exec_time","enable") - prop.setProperty("measurement.exec_count","0") - prop.setProperty("measurement.period_time","enable") - prop.setProperty("measurement.period_count","0") - retcode = _pn.init(prop) - cons = ConsumerMock() - self.assertEqual(_pn.setConsumer(cons),OpenRTM_aist.DataPortStatus.PORT_OK) - _pn.setBuffer(OpenRTM_aist.CdrRingBuffer()) - _pn.activate() - - self.assertEqual(_pn.write(123,0,0),OpenRTM_aist.DataPortStatus.PORT_OK) - time.sleep(0.01) - self.assertEqual(_pn.write(123,0,0),OpenRTM_aist.DataPortStatus.PORT_OK) - time.sleep(0.01) - self.assertEqual(_pn.write(123,0,0),OpenRTM_aist.DataPortStatus.PORT_OK) - time.sleep(0.01) - self.assertEqual(_pn.write(123,0,0),OpenRTM_aist.DataPortStatus.PORT_OK) - time.sleep(0.01) - self.assertEqual(_pn.write(123,0,0),OpenRTM_aist.DataPortStatus.PORT_OK) - time.sleep(0.01) - self.assertEqual(_pn.write(123,0,0),OpenRTM_aist.DataPortStatus.PORT_OK) - time.sleep(0.01) - self.assertEqual(_pn.write(123,0,0),OpenRTM_aist.DataPortStatus.PORT_OK) - time.sleep(0.01) - self.assertEqual(_pn.write(123,0,0),OpenRTM_aist.DataPortStatus.PORT_OK) - time.sleep(0.01) - _pn.deactivate() - _pn.__del__() - return - - - def test_pushSkip(self): - _pn = PublisherPeriodic() - prop = OpenRTM_aist.Properties() - cinfo = OpenRTM_aist.ConnectorInfo("", - "", - [], - prop) - self.assertEqual(_pn.setListener(cinfo,OpenRTM_aist.ConnectorListeners()), - OpenRTM_aist.DataPortStatus.PORT_OK) - prop = OpenRTM_aist.Properties() - prop.setProperty("publisher.push_policy","skip") - prop.setProperty("publisher.skip_count","0") - prop.setProperty("thread_type","default") - prop.setProperty("measurement.exec_time","enable") - prop.setProperty("measurement.exec_count","0") - prop.setProperty("measurement.period_time","enable") - prop.setProperty("measurement.period_count","0") - retcode = _pn.init(prop) - cons = ConsumerMock() - self.assertEqual(_pn.setConsumer(cons),OpenRTM_aist.DataPortStatus.PORT_OK) - _pn.setBuffer(OpenRTM_aist.CdrRingBuffer()) - _pn.activate() - - self.assertEqual(_pn.write(123,0,0),OpenRTM_aist.DataPortStatus.PORT_OK) - self.assertEqual(_pn.write(123,0,0),OpenRTM_aist.DataPortStatus.PORT_OK) - self.assertEqual(_pn.write(123,0,0),OpenRTM_aist.DataPortStatus.PORT_OK) - self.assertEqual(_pn.write(123,0,0),OpenRTM_aist.DataPortStatus.PORT_OK) - self.assertEqual(_pn.write(123,0,0),OpenRTM_aist.DataPortStatus.PORT_OK) - self.assertEqual(_pn.write(123,0,0),OpenRTM_aist.DataPortStatus.PORT_OK) - self.assertEqual(_pn.write(123,0,0),OpenRTM_aist.DataPortStatus.PORT_OK) - self.assertEqual(_pn.write(123,0,0),OpenRTM_aist.DataPortStatus.PORT_OK) - _pn.deactivate() - _pn.__del__() - return - - def test_pushNew(self): - _pn = PublisherPeriodic() - prop = OpenRTM_aist.Properties() - cinfo = OpenRTM_aist.ConnectorInfo("", - "", - [], - prop) - self.assertEqual(_pn.setListener(cinfo,OpenRTM_aist.ConnectorListeners()), - OpenRTM_aist.DataPortStatus.PORT_OK) - prop = OpenRTM_aist.Properties() - prop.setProperty("publisher.push_policy","new") - prop.setProperty("publisher.skip_count","0") - prop.setProperty("thread_type","default") - prop.setProperty("measurement.exec_time","enable") - prop.setProperty("measurement.exec_count","0") - prop.setProperty("measurement.period_time","enable") - prop.setProperty("measurement.period_count","0") - retcode = _pn.init(prop) - cons = ConsumerMock() - self.assertEqual(_pn.setConsumer(cons),OpenRTM_aist.DataPortStatus.PORT_OK) - _pn.setBuffer(OpenRTM_aist.CdrRingBuffer()) - _pn.activate() - - self.assertEqual(_pn.write(123,0,0),OpenRTM_aist.DataPortStatus.PORT_OK) - self.assertEqual(_pn.write(123,0,0),OpenRTM_aist.DataPortStatus.PORT_OK) - self.assertEqual(_pn.write(123,0,0),OpenRTM_aist.DataPortStatus.PORT_OK) - self.assertEqual(_pn.write(123,0,0),OpenRTM_aist.DataPortStatus.PORT_OK) - self.assertEqual(_pn.write(123,0,0),OpenRTM_aist.DataPortStatus.PORT_OK) - self.assertEqual(_pn.write(123,0,0),OpenRTM_aist.DataPortStatus.PORT_OK) - self.assertEqual(_pn.write(123,0,0),OpenRTM_aist.DataPortStatus.PORT_OK) - time.sleep(0.01) - self.assertEqual(_pn.write(123,0,0),OpenRTM_aist.DataPortStatus.PORT_OK) - _pn.deactivate() - time.sleep(0.01) - _pn.__del__() - return - - def test_convertReturn(self): - _pn = PublisherPeriodic() - self.assertEqual(_pn.convertReturn(OpenRTM_aist.BufferStatus.BUFFER_OK,0), - OpenRTM_aist.DataPortStatus.PORT_OK) - self.assertEqual(_pn.convertReturn(OpenRTM_aist.BufferStatus.BUFFER_EMPTY,0), - OpenRTM_aist.DataPortStatus.PORT_ERROR) - self.assertEqual(_pn.convertReturn(OpenRTM_aist.BufferStatus.TIMEOUT,0), - OpenRTM_aist.DataPortStatus.BUFFER_TIMEOUT) - self.assertEqual(_pn.convertReturn(OpenRTM_aist.BufferStatus.PRECONDITION_NOT_MET,0), - OpenRTM_aist.DataPortStatus.PRECONDITION_NOT_MET) - self.assertEqual(_pn.convertReturn(100,0), - OpenRTM_aist.DataPortStatus.PORT_ERROR) - _pn.__del__() - return - -############ test ################# -if __name__ == '__main__': - unittest.main() diff --git a/OpenRTM_aist/test/test_RTCUtil.py b/OpenRTM_aist/test/test_RTCUtil.py deleted file mode 100755 index d3e15103..00000000 --- a/OpenRTM_aist/test/test_RTCUtil.py +++ /dev/null @@ -1,72 +0,0 @@ -#!/usr/bin/env python -# -*- Python -*- - -# -# @file test_RTCUtil.py -# @brief test for RTComponent utils -# @date $Date: 2007/09/11 $ -# @author Shinji Kurihara -# -# Copyright (C) 2007 -# Task-intelligence Research Group, -# Intelligent Systems Research Institute, -# National Institute of -# Advanced Industrial Science and Technology (AIST), Japan -# All rights reserved. - - -import sys -sys.path.insert(1,"../") - -import unittest -import OpenRTM_aist -import RTC, RTC__POA - -from RTCUtil import * -from omniORB import CORBA - -#class test(RTC__POA.DataFlowParticipant): -class test(OpenRTM_aist.RTObject_impl): - def __init__(self): - self.orb = CORBA.ORB_init() - self.poa = self.orb.resolve_initial_references("RootPOA") - OpenRTM_aist.RTObject_impl.__init__(self, orb=self.orb, poa=self.poa) - poaManager = self.poa._get_the_POAManager() - poaManager.activate() - - -class TestRTCUtil(unittest.TestCase): - def setUp(self): - pass - - def tearDown(self): - OpenRTM_aist.Manager.instance().shutdownManager() - return - - def test_isDataFlowComponent(self): - dfp_i = test() - dfp = dfp_i._this() - print isDataFlowComponent(dfp) - - def test_isFsmParticipant(self): - dfp_i = test() - dfp = dfp_i._this() - print isFsmParticipant(dfp) - - - def test_isFsmObject(self): - dfp_i = test() - dfp = dfp_i._this() - print isFsmObject(dfp) - - - def test_isMultiModeObject(self): - dfp_i = test() - dfp = dfp_i._this() - print isMultiModeObject(dfp) - - - -############### test ################# -if __name__ == '__main__': - unittest.main() diff --git a/OpenRTM_aist/test/test_RTObject.py b/OpenRTM_aist/test/test_RTObject.py deleted file mode 100755 index b0ed4b27..00000000 --- a/OpenRTM_aist/test/test_RTObject.py +++ /dev/null @@ -1,747 +0,0 @@ -#!/usr/bin/env python -# -*- Python -*- - - -## \file test_RTObject.py -## \brief test for RT component base class -## \date $Date: $ -## \author Shinji Kurihara -# -# Copyright (C) 2006 -# Task-intelligence Research Group, -# Intelligent Systems Research Institute, -# National Institute of -# Advanced Industrial Science and Technology (AIST), Japan -# All rights reserved. -# - -import sys,time -sys.path.insert(1,"../") -sys.path.insert(1,"../RTM_IDL") - -import RTC -import OpenRTM -import SDOPackage -import OpenRTM_aist -from omniORB import CORBA, PortableServer -from omniORB import any -import unittest - -configsample_spec = ["implementation_id", "TestComp", - "type_name", "TestComp", - "description", "Test example component", - "version", "1.0", - "vendor", "Shinji Kurihara, AIST", - "category", "example", - "activity_type", "DataFlowComponent", - "max_instance", "10", - "language", "Python", - "lang_type", "script", - # Configuration variables - "conf.default.int_param0", "0", - "conf.default.int_param1", "1", - "conf.default.double_param0", "0.11", - "conf.default.double_param1", "9.9", - "conf.default.str_param0", "hoge", - "conf.default.str_param1", "dara", - "conf.default.vector_param0", "0.0,1.0,2.0,3.0,4.0", - ""] - -com = None - -class TestComp(OpenRTM_aist.RTObject_impl): - def __init__(self, orb_, poa_): - OpenRTM_aist.RTObject_impl.__init__(self, orb=orb_, poa=poa_) - - def onInitialize(self): - print "onInitialize" - return RTC.RTC_OK - - def onFinalize(self): - print "onFinalize" - return RTC.RTC_OK - - def onStartup(self, ec_id): - print "onStartup" - return RTC.RTC_OK - - def onShutdown(self, ec_id): - print "onSutdown" - return RTC.RTC_OK - - def onActivated(self, ec_id): - print "onActivated" - return RTC.RTC_OK - - def onDeactivated(self, ec_id): - print "onDeactivated" - return RTC.RTC_OK - - def onExecute(self, ec_id): - print "onExecute" - return RTC.RTC_OK - - def onAborting(self, ec_id): - print "onAborting" - return RTC.RTC_OK - - def onReset(self, ec_id): - print "onReset" - return RTC.RTC_OK - - def onStateUpdate(self, ec_id): - print "onStateUpdate" - return RTC.RTC_OK - - def onRateChanged(self, ec_id): - print "onRateChanged" - return RTC.RTC_OK - - -def TestCompInit(manager): - print "TestCompInit" - global com - profile = OpenRTM_aist.Properties(defaults_str=configsample_spec) - manager.registerFactory(profile, - TestComp, - OpenRTM_aist.Delete) - com = manager.createComponent("TestComp") - - -class MySdoServiceProviderBase(OpenRTM_aist.SdoServiceProviderBase): - def __init__(self): - self._profile = None - self._rtobj = None - return - - def __del__(self): - return - - def init(self, rtobj, profile): - self._rtobj = rtobj - self._profile = profile - return - - def reinit(self, profile): - return - - def getProfile(self): - return self._profile - - def finalize(self): - return - - -class TestRTObject_impl(unittest.TestCase): - def setUp(self): - self._orb = CORBA.ORB_init(sys.argv) - self._poa = self._orb.resolve_initial_references("RootPOA") - self._poa._get_the_POAManager().activate() - return - - def tearDown(self): - #global com - #self.rtobj.exit() - #self.manager.terminate() - time.sleep(0.1) - OpenRTM_aist.Manager.instance().shutdownManager() - #com = None - return - - def test_is_alive(self): - rtobj = TestComp(self._orb, self._poa) - ec = rtobj.getObjRef().get_context(0) - self.assertEqual(ec,None) - ec_args = "PeriodicExecutionContext" - ec=OpenRTM_aist.ExecutionContextFactory.instance().createObject(ec_args) - ec.bindComponent(rtobj) - self.assertNotEqual(rtobj.getObjRef().get_owned_contexts(),[]) - self.assertEqual(rtobj.is_alive(ec.getObjRef()),True) - ec.remove_component(rtobj.getObjRef()) - ec.stop() - del ec - - return - - def test_get_owned_contexts(self): - rtobj = TestComp(self._orb, self._poa) - self.assertEqual(rtobj.getObjRef().get_owned_contexts(),[]) - ec_args = "PeriodicExecutionContext" - ec=OpenRTM_aist.ExecutionContextFactory.instance().createObject(ec_args) - ec.bindComponent(rtobj) - self.assertNotEqual(rtobj.getObjRef().get_owned_contexts(),[]) - ec.remove_component(rtobj.getObjRef()) - ec.stop() - del ec - - return - - def test_get_participating_contexts(self): - rtobj = TestComp(self._orb, self._poa) - self.assertEqual(rtobj.getObjRef().get_participating_contexts(),[]) - return - - def test_get_context(self): - rtobj = TestComp(self._orb, self._poa) - print rtobj.getObjRef().get_context(0) - return - - def test_get_component_profile(self): - rtobj = TestComp(self._orb, self._poa) - rtobj.setInstanceName("TestComp0") - prof = rtobj.getObjRef().get_component_profile() - self.assertEqual(prof.instance_name, "TestComp0") - return - - def test_get_ports(self): - rtobj = TestComp(self._orb, self._poa) - self.assertEqual(rtobj.getObjRef().get_ports(), []) - return - - - def test_attach_context(self): - rtobj = TestComp(self._orb, self._poa) - ec = OpenRTM_aist.PeriodicExecutionContext() - id = rtobj.getObjRef().attach_context(ec.getObjRef()) - print "attach_context: ", id - print rtobj.getObjRef().detach_context(id) - poa = OpenRTM_aist.Manager.instance().getPOA() - poa.deactivate_object(poa.servant_to_id(ec)) - return - - def test_get_owned_organizations(self): - rtobj = TestComp(self._orb, self._poa) - self.assertEqual(rtobj.getObjRef().get_owned_organizations(),[]) - return - - def test_get_sdo_id(self): - rtobj = TestComp(self._orb, self._poa) - rtobj.setInstanceName("TestComp0") - self.assertEqual(rtobj.getObjRef().get_sdo_id(), "TestComp0") - return - - def test_get_sdo_type(self): - rtobj = TestComp(self._orb, self._poa) - prop = OpenRTM_aist.Properties(defaults_str=configsample_spec) - rtobj.setProperties(prop) - self.assertEqual(rtobj.getObjRef().get_sdo_type(), "Test example component") - return - - def test_get_device_profile(self): - rtobj = TestComp(self._orb, self._poa) - prof = rtobj.getObjRef().get_device_profile() - self.assertEqual(prof.device_type, "") - return - - def test_get_service_profiles(self): - rtobj = TestComp(self._orb, self._poa) - self.assertEqual(rtobj.getObjRef().get_service_profiles(),[]) - return - - - def test_get_service_profile(self): - #rtobj.getObjRef().get_service_profile("TestComp") - return - - - def test_get_sdo_service(self): - #rtobj.getObjRef().get_sdo_service(None) - return - - def test_get_configuration(self): - rtobj = TestComp(self._orb, self._poa) - print rtobj.getObjRef().get_configuration() - return - - def test_get_monitoring(self): - #rtobj.getObjRef().get_monitoring() - return - - def test_get_organizations(self): - rtobj = TestComp(self._orb, self._poa) - self.assertEqual(rtobj.getObjRef().get_organizations(), []) - return - - def test_get_status_list(self): - rtobj = TestComp(self._orb, self._poa) - self.assertEqual(rtobj.getObjRef().get_status_list(), []) - return - - def test_get_status(self): - #rtobj.getObjRef().get_status("status") - return - - def test_getPropTestCase(self): - rtobj = TestComp(self._orb, self._poa) - self.assertEqual(rtobj.getInstanceName(), "") - prop = OpenRTM_aist.Properties(defaults_str=configsample_spec) - rtobj.setInstanceName("TestComp0") - rtobj.setProperties(prop) - self.assertEqual(rtobj.getInstanceName(), "TestComp0") - self.assertEqual(rtobj.getTypeName(), "TestComp") - self.assertEqual(rtobj.getDescription(), "Test example component") - self.assertEqual(rtobj.getVersion(), "1.0") - self.assertEqual(rtobj.getVendor(), "Shinji Kurihara, AIST") - self.assertEqual(rtobj.getCategory(), "example") - self.assertNotEqual(rtobj.getNamingNames(),["TestComp0.rtc"]) - return - - def test_setObjRef(self): - rtobj = TestComp(self._orb, self._poa) - rtobj.setObjRef("test") - self.assertEqual(rtobj.getObjRef(),"test") - return - - def test_bindParameter(self): - rtobj = TestComp(self._orb, self._poa) - conf_ = [123] - self.assertEqual(rtobj.bindParameter("config", conf_, 0), True) - rtobj.updateParameters("") - return - - def test_PortTestCase(self): - rtobj = TestComp(self._orb, self._poa) - ringbuf = OpenRTM_aist.RingBuffer(8) - outp = OpenRTM_aist.OutPort("out", RTC.TimedLong(RTC.Time(0,0),0), ringbuf) - rtobj.registerOutPort("out",outp) - - ringbuf = OpenRTM_aist.RingBuffer(8) - inp = OpenRTM_aist.InPort("in", RTC.TimedLong(RTC.Time(0,0),0), ringbuf) - rtobj.registerInPort("in",inp) - - rtobj.deletePort(outp) - rtobj.deletePort(inp) - - rtobj.finalizePorts() - return - - # since 1.1.0 - def test_getExecutionContext(self): - rtobj = TestComp(self._orb, self._poa) - ec_args = "PeriodicExecutionContext" - ec=OpenRTM_aist.ExecutionContextFactory.instance().createObject(ec_args) - ec.bindComponent(rtobj) - self.assertNotEqual(rtobj.getExecutionContext(0),None) - return - - def test_getExecutionRate(self): - rtobj = TestComp(self._orb, self._poa) - ec_args = "PeriodicExecutionContext" - ec=OpenRTM_aist.ExecutionContextFactory.instance().createObject(ec_args) - ec.set_rate(1000) - ec.bindComponent(rtobj) - self.assertEqual(rtobj.getExecutionRate(0),1000.0) - return - - def test_setExecutionRate(self): - rtobj = TestComp(self._orb, self._poa) - ec_args = "PeriodicExecutionContext" - ec=OpenRTM_aist.ExecutionContextFactory.instance().createObject(ec_args) - ec.bindComponent(rtobj) - self.assertEqual(rtobj.setExecutionRate(0,10000),RTC.RTC_OK) - self.assertEqual(rtobj.getExecutionRate(0),10000.0) - return - - def test_isOwnExecutionContext(self): - rtobj = TestComp(self._orb, self._poa) - ec_args = "PeriodicExecutionContext" - ec=OpenRTM_aist.ExecutionContextFactory.instance().createObject(ec_args) - ec.bindComponent(rtobj) - self.assertEqual(rtobj.isOwnExecutionContext(0),True) - return - - def test_activate_deactivate(self): - rtobj = TestComp(self._orb, self._poa) - ec_args = "PeriodicExecutionContext" - ec=OpenRTM_aist.ExecutionContextFactory.instance().createObject(ec_args) - ec.set_rate(1000.0) - ec.bindComponent(rtobj) - ec.start() - self.assertEqual(rtobj.activate(0),RTC.RTC_OK) - time.sleep(0.1) - ret = rtobj.deactivate(0) - time.sleep(0.1) - self.assertEqual(ret,RTC.RTC_OK) - ec.stop() - return - - def test_reset(self): - rtobj = TestComp(self._orb, self._poa) - ec_args = "PeriodicExecutionContext" - ec=OpenRTM_aist.ExecutionContextFactory.instance().createObject(ec_args) - ec.bindComponent(rtobj) - ec.start() - self.assertEqual(rtobj.activate(0),RTC.RTC_OK) - ec._worker._comps[0]._sm.goTo(RTC.ERROR_STATE) - time.sleep(0.1) - self.assertEqual(rtobj.reset(0),RTC.RTC_OK) - ec.stop() - return - - def test_addRemoveSdoServiceProvider(self): - rtobj = TestComp(self._orb, self._poa) - prof = SDOPackage.ServiceProfile("id","interface_type", - OpenRTM_aist.NVUtil.newNV("test","any"), - SDOPackage.SDOService._nil) - prov = MySdoServiceProviderBase() - prov.init(rtobj,prof) - self.assertEqual(rtobj.addSdoServiceProvider(prof, prov),True) - self.assertEqual(rtobj.removeSdoServiceProvider("id"),True) - return - - def test_addRemoveSdoServiceConsumer(self): - import MySdoServiceConsumer - OpenRTM_aist.Manager.instance().load("MySdoServiceConsumer.py", - "MySdoServiceConsumerInit") - rtobj = TestComp(self._orb, self._poa) - prof = SDOPackage.ServiceProfile(OpenRTM_aist.toTypename(OpenRTM.ComponentObserver),OpenRTM_aist.toTypename(OpenRTM.ComponentObserver), - [OpenRTM_aist.NVUtil.newNV("test","any")], - SDOPackage.SDOService._nil) - self.assertEqual(rtobj.addSdoServiceConsumer(prof),True) - self.assertEqual(rtobj.removeSdoServiceConsumer(OpenRTM_aist.toTypename(OpenRTM.ComponentObserver)),True) - return - - def prelistenerFunc(self, id): - print "prelistenerFunc called !!!!" - return - - def test_addRemovePreComponentActionListener(self): - rtobj = TestComp(self._orb, self._poa) - - rtobj.addPreComponentActionListener(OpenRTM_aist.PreComponentActionListenerType.PRE_ON_INITIALIZE, - self.prelistenerFunc) - - rtobj.removePreComponentActionListener(OpenRTM_aist.PreComponentActionListenerType.PRE_ON_INITIALIZE, - self.prelistenerFunc) - - rtobj.addPreComponentActionListener(OpenRTM_aist.PreComponentActionListenerType.PRE_ON_FINALIZE, - self.prelistenerFunc) - - rtobj.removePreComponentActionListener(OpenRTM_aist.PreComponentActionListenerType.PRE_ON_FINALIZE, - self.prelistenerFunc) - return - - def postlistenerFunc(self, id, ret): - print "postlistenerFunc called !!!!" - return - - def test_addRemovePostComponentActionListener(self): - rtobj = TestComp(self._orb, self._poa) - - rtobj.addPostComponentActionListener(OpenRTM_aist.PostComponentActionListenerType.POST_ON_FINALIZE, - self.postlistenerFunc) - - rtobj.removePostComponentActionListener(OpenRTM_aist.PostComponentActionListenerType.POST_ON_FINALIZE, - self.postlistenerFunc) - return - - def test_addRemovePortActionListener(self): - rtobj = TestComp(self._orb, self._poa) - - rtobj.addPortActionListener(OpenRTM_aist.PortActionListenerType.ADD_PORT, - self.prelistenerFunc) - - rtobj.removePortActionListener(OpenRTM_aist.PortActionListenerType.ADD_PORT, - self.prelistenerFunc) - return - - def test_addRemoveExecutionContextActionListener(self): - rtobj = TestComp(self._orb, self._poa) - - rtobj.addExecutionContextActionListener(OpenRTM_aist.ExecutionContextActionListenerType.EC_ATTACHED, - self.prelistenerFunc) - - rtobj.removeExecutionContextActionListener(OpenRTM_aist.ExecutionContextActionListenerType.EC_ATTACHED, - self.prelistenerFunc) - return - - def test_addRemovePortConnectListener(self): - rtobj = TestComp(self._orb, self._poa) - - rtobj.addPortConnectListener(OpenRTM_aist.PortConnectListenerType.ON_NOTIFY_CONNECT, - self.postlistenerFunc) - - rtobj.removePortConnectListener(OpenRTM_aist.PortConnectListenerType.ON_NOTIFY_CONNECT, - self.postlistenerFunc) - return - - def portconretlistenerFunc(self, pname, cprof, ret): - print "portconretlistenerFunc called !!!!" - return - - def test_addRemovePortConnectRetListener(self): - rtobj = TestComp(self._orb, self._poa) - - rtobj.addPortConnectRetListener(OpenRTM_aist.PortConnectRetListenerType.ON_CONNECTED, - self.portconretlistenerFunc) - - rtobj.removePortConnectRetListener(OpenRTM_aist.PortConnectRetListenerType.ON_CONNECTED, - self.portconretlistenerFunc) - return - - def configparamlistenerFunc(self, pname, cprof, ret): - print "configparamlistenerFunc called !!!!" - return - - def test_addRemoveConfigurationParamListener(self): - rtobj = TestComp(self._orb, self._poa) - - rtobj.addConfigurationParamListener(OpenRTM_aist.ConfigurationParamListenerType.ON_UPDATE_CONFIG_PARAM, - self.configparamlistenerFunc) - - rtobj.removeConfigurationParamListener(OpenRTM_aist.ConfigurationParamListenerType.ON_UPDATE_CONFIG_PARAM, - self.configparamlistenerFunc) - return - - def test_addRemoveConfigurationSetListener(self): - rtobj = TestComp(self._orb, self._poa) - - rtobj.addConfigurationSetListener(OpenRTM_aist.ConfigurationSetListenerType.ON_SET_CONFIG_SET, - self.prelistenerFunc) - - rtobj.removeConfigurationSetListener(OpenRTM_aist.ConfigurationSetListenerType.ON_SET_CONFIG_SET, - self.prelistenerFunc) - return - - def test_addRemoveConfigurationSetNameListener(self): - rtobj = TestComp(self._orb, self._poa) - - rtobj.addConfigurationSetNameListener(OpenRTM_aist.ConfigurationSetNameListenerType.ON_UPDATE_CONFIG_SET, - self.prelistenerFunc) - - rtobj.removeConfigurationSetNameListener(OpenRTM_aist.ConfigurationSetNameListenerType.ON_UPDATE_CONFIG_SET, - self.prelistenerFunc) - return - - def test_shutdown(self): - return - - def test_preOnInitialize(self): - rtobj = TestComp(self._orb, self._poa) - ec_args = "PeriodicExecutionContext" - ec=OpenRTM_aist.ExecutionContextFactory.instance().createObject(ec_args) - ec.bindComponent(rtobj) - print "preOnInitialize()" - rtobj.preOnInitialize(0) - return - - def test_preOnFinalize(self): - rtobj = TestComp(self._orb, self._poa) - ec_args = "PeriodicExecutionContext" - ec=OpenRTM_aist.ExecutionContextFactory.instance().createObject(ec_args) - ec.bindComponent(rtobj) - rtobj.preOnFinalize(0) - return - - def test_preOnStartup(self): - rtobj = TestComp(self._orb, self._poa) - ec_args = "PeriodicExecutionContext" - ec=OpenRTM_aist.ExecutionContextFactory.instance().createObject(ec_args) - ec.bindComponent(rtobj) - rtobj.preOnStartup(0) - return - - def test_preOnShutdown(self): - rtobj = TestComp(self._orb, self._poa) - ec_args = "PeriodicExecutionContext" - ec=OpenRTM_aist.ExecutionContextFactory.instance().createObject(ec_args) - ec.bindComponent(rtobj) - rtobj.preOnShutdown(0) - return - - def test_preOnActivated(self): - rtobj = TestComp(self._orb, self._poa) - ec_args = "PeriodicExecutionContext" - ec=OpenRTM_aist.ExecutionContextFactory.instance().createObject(ec_args) - ec.bindComponent(rtobj) - rtobj.preOnActivated(0) - return - - def test_preOnDeactivated(self): - rtobj = TestComp(self._orb, self._poa) - ec_args = "PeriodicExecutionContext" - ec=OpenRTM_aist.ExecutionContextFactory.instance().createObject(ec_args) - ec.bindComponent(rtobj) - rtobj.preOnDeactivated(0) - return - - def test_preOnAborting(self): - rtobj = TestComp(self._orb, self._poa) - ec_args = "PeriodicExecutionContext" - ec=OpenRTM_aist.ExecutionContextFactory.instance().createObject(ec_args) - ec.bindComponent(rtobj) - rtobj.preOnAborting(0) - return - - def test_preOnError(self): - rtobj = TestComp(self._orb, self._poa) - ec_args = "PeriodicExecutionContext" - ec=OpenRTM_aist.ExecutionContextFactory.instance().createObject(ec_args) - ec.bindComponent(rtobj) - rtobj.preOnError(0) - return - - def test_preOnReset(self): - rtobj = TestComp(self._orb, self._poa) - ec_args = "PeriodicExecutionContext" - ec=OpenRTM_aist.ExecutionContextFactory.instance().createObject(ec_args) - ec.bindComponent(rtobj) - rtobj.preOnReset(0) - return - - def test_preOnExecute(self): - rtobj = TestComp(self._orb, self._poa) - ec_args = "PeriodicExecutionContext" - ec=OpenRTM_aist.ExecutionContextFactory.instance().createObject(ec_args) - ec.bindComponent(rtobj) - rtobj.preOnExecute(0) - return - - def test_preOnStateUpdate(self): - rtobj = TestComp(self._orb, self._poa) - ec_args = "PeriodicExecutionContext" - ec=OpenRTM_aist.ExecutionContextFactory.instance().createObject(ec_args) - ec.bindComponent(rtobj) - rtobj.preOnStateUpdate(0) - return - - def test_preOnRateChanged(self): - rtobj = TestComp(self._orb, self._poa) - ec_args = "PeriodicExecutionContext" - ec=OpenRTM_aist.ExecutionContextFactory.instance().createObject(ec_args) - ec.bindComponent(rtobj) - rtobj.preOnRateChanged(0) - return - - def test_postOnInitialize(self): - rtobj = TestComp(self._orb, self._poa) - ec_args = "PeriodicExecutionContext" - ec=OpenRTM_aist.ExecutionContextFactory.instance().createObject(ec_args) - ec.bindComponent(rtobj) - rtobj.postOnInitialize(0,True) - return - - def test_postOnFinalize(self): - rtobj = TestComp(self._orb, self._poa) - ec_args = "PeriodicExecutionContext" - ec=OpenRTM_aist.ExecutionContextFactory.instance().createObject(ec_args) - ec.bindComponent(rtobj) - rtobj.postOnFinalize(0,True) - return - - def test_postOnStartup(self): - rtobj = TestComp(self._orb, self._poa) - ec_args = "PeriodicExecutionContext" - ec=OpenRTM_aist.ExecutionContextFactory.instance().createObject(ec_args) - ec.bindComponent(rtobj) - rtobj.postOnStartup(0,True) - return - - def test_postOnShutdown(self): - rtobj = TestComp(self._orb, self._poa) - ec_args = "PeriodicExecutionContext" - ec=OpenRTM_aist.ExecutionContextFactory.instance().createObject(ec_args) - ec.bindComponent(rtobj) - rtobj.postOnShutdown(0,True) - return - - def test_postOnActivated(self): - rtobj = TestComp(self._orb, self._poa) - ec_args = "PeriodicExecutionContext" - ec=OpenRTM_aist.ExecutionContextFactory.instance().createObject(ec_args) - ec.bindComponent(rtobj) - rtobj.postOnActivated(0,True) - return - - def test_postOnDeactivated(self): - rtobj = TestComp(self._orb, self._poa) - ec_args = "PeriodicExecutionContext" - ec=OpenRTM_aist.ExecutionContextFactory.instance().createObject(ec_args) - ec.bindComponent(rtobj) - rtobj.postOnDeactivated(0,True) - return - - def test_postOnAborting(self): - rtobj = TestComp(self._orb, self._poa) - ec_args = "PeriodicExecutionContext" - ec=OpenRTM_aist.ExecutionContextFactory.instance().createObject(ec_args) - ec.bindComponent(rtobj) - rtobj.postOnAborting(0,True) - return - - def test_postOnError(self): - rtobj = TestComp(self._orb, self._poa) - ec_args = "PeriodicExecutionContext" - ec=OpenRTM_aist.ExecutionContextFactory.instance().createObject(ec_args) - ec.bindComponent(rtobj) - rtobj.postOnError(0,True) - return - - def test_postOnReset(self): - rtobj = TestComp(self._orb, self._poa) - ec_args = "PeriodicExecutionContext" - ec=OpenRTM_aist.ExecutionContextFactory.instance().createObject(ec_args) - ec.bindComponent(rtobj) - rtobj.postOnReset(0,True) - return - - def test_postOnExecute(self): - rtobj = TestComp(self._orb, self._poa) - ec_args = "PeriodicExecutionContext" - ec=OpenRTM_aist.ExecutionContextFactory.instance().createObject(ec_args) - ec.bindComponent(rtobj) - rtobj.postOnExecute(0,True) - return - - def test_postOnStateUpdate(self): - rtobj = TestComp(self._orb, self._poa) - ec_args = "PeriodicExecutionContext" - ec=OpenRTM_aist.ExecutionContextFactory.instance().createObject(ec_args) - ec.bindComponent(rtobj) - rtobj.postOnStateUpdate(0,True) - return - - def test_postOnRateChanged(self): - rtobj = TestComp(self._orb, self._poa) - ec_args = "PeriodicExecutionContext" - ec=OpenRTM_aist.ExecutionContextFactory.instance().createObject(ec_args) - ec.bindComponent(rtobj) - rtobj.postOnRateChanged(0,True) - return - - def test_onAddPort(self): - rtobj = TestComp(self._orb, self._poa) - ec_args = "PeriodicExecutionContext" - ec=OpenRTM_aist.ExecutionContextFactory.instance().createObject(ec_args) - ec.bindComponent(rtobj) - rtobj.onAddPort(0) - return - - def test_onRemovePort(self): - rtobj = TestComp(self._orb, self._poa) - ec_args = "PeriodicExecutionContext" - ec=OpenRTM_aist.ExecutionContextFactory.instance().createObject(ec_args) - ec.bindComponent(rtobj) - rtobj.onRemovePort(0) - return - - def test_onAttachExecutionContext(self): - rtobj = TestComp(self._orb, self._poa) - ec_args = "PeriodicExecutionContext" - ec=OpenRTM_aist.ExecutionContextFactory.instance().createObject(ec_args) - ec.bindComponent(rtobj) - rtobj.onAttachExecutionContext(0) - return - - def test_onDetachExecutionContext(self): - rtobj = TestComp(self._orb, self._poa) - ec_args = "PeriodicExecutionContext" - ec=OpenRTM_aist.ExecutionContextFactory.instance().createObject(ec_args) - ec.bindComponent(rtobj) - rtobj.onDetachExecutionContext(0) - return - - -############### test ################# -if __name__ == '__main__': - unittest.main() diff --git a/OpenRTM_aist/test/test_RTObjectStateMachine.py b/OpenRTM_aist/test/test_RTObjectStateMachine.py deleted file mode 100644 index 2976a798..00000000 --- a/OpenRTM_aist/test/test_RTObjectStateMachine.py +++ /dev/null @@ -1,127 +0,0 @@ -#!/usr/bin/env python -# -*- coding: euc-jp -*- - -## -# @file test_RTObjectStateMachine.py -# @brief test for ExecutionContext's state machine worker class -# @date $Date$ -# @author Shinji Kurihara -# -# Copyright (C) 2011 -# Noriaki Ando -# Intelligent Systems Research Institute, -# National Institute of -# Advanced Industrial Science and Technology (AIST), Japan -# All rights reserved. -# -# $Id$ -# - -import sys -sys.path.insert(1,"../") -sys.path.insert(1,"../RTM_IDL") - -import unittest - -from RTObjectStateMachine import * -import OpenRTM__POA, RTC -import OpenRTM_aist - - -testcomp_spec = ["implementation_id", "TestComp", - "type_name", "TestComp", - "description", "Test example component", - "version", "1.0", - "vendor", "Shinji Kurihara, AIST", - "category", "example", - "activity_type", "DataFlowComponent", - "max_instance", "10", - "language", "Python", - "lang_type", "compile", - ""] - -class TestComp(OpenRTM_aist.DataFlowComponentBase): - def __init_(self, manager): - OpenRTM_aist.DataFlowComponentBase.__init__(self, manager) - - -def TestCompInit(manager): - global com - profile = OpenRTM_aist.Properties(defaults_str=configsample_spec) - manager.registerFactory(profile, - TestComp, - OpenRTM_aist.Delete) - -class TestRTObjectStateMachine(unittest.TestCase): - """ - """ - - def setUp(self): - self._mgr = OpenRTM_aist.Manager.instance() - self._mgr.activateManager() - profile = OpenRTM_aist.Properties(defaults_str=testcomp_spec) - self._mgr.registerFactory(profile, - TestComp, - OpenRTM_aist.Delete) - self._comp = self._mgr.createComponent("TestComp") - self._rtsm = RTObjectStateMachine(0, self._comp.getObjRef()) - - def tearDown(self): - OpenRTM_aist.Manager.instance().shutdownManager() - return - - def test_getRTObject(self): - self.assertEqual(self._comp.getObjRef(), self._rtsm.getRTObject()) - return - - def test_isEquivalent(self): - self.assertEqual(True, self._rtsm.isEquivalent(self._comp.getObjRef())) - return - - def test_getExecutionContextHandle(self): - self.assertEqual(0, self._rtsm.getExecutionContextHandle()) - return - - def test_ComponentActionOperations(self): - self._rtsm.onStartup() - self._rtsm.onShutdown() - self._rtsm.onActivated(RTC.INACTIVE_STATE) - self._rtsm.onDeactivated(RTC.ACTIVE_STATE) - self._rtsm.onError(RTC.ACTIVE_STATE) - self._rtsm.onReset(RTC.ERROR_STATE) - self._rtsm.onExecute(RTC.ACTIVE_STATE) - self._rtsm.onStateUpdate(RTC.ACTIVE_STATE) - self._rtsm.onRateChanged() - self._rtsm.onAction(RTC.ACTIVE_STATE) - self._rtsm.onModeChanged(RTC.ACTIVE_STATE) - return - - def test_getState(self): - self.assertEqual(RTC.INACTIVE_STATE, self._rtsm.getState()) - self.assertEqual(RTC.INACTIVE_STATE, self._rtsm.getStates().curr) - self.assertEqual(True, self._rtsm.isCurrentState(RTC.INACTIVE_STATE)) - self.assertEqual(True, self._rtsm.isNextState(RTC.INACTIVE_STATE)) - self._rtsm.goTo(RTC.ACTIVE_STATE) - self.assertEqual(True, self._rtsm.isNextState(RTC.ACTIVE_STATE)) - return - - - def test_worker(self): - self._rtsm.workerPreDo() - self._rtsm.workerDo() - self._rtsm.workerPostDo() - return - - - def test_ComponentAction(self): - self._rtsm.setComponentAction(self._comp.getObjRef()) - self._rtsm.setDataFlowComponentAction(self._comp.getObjRef()) - self._rtsm.setFsmParticipantAction(self._comp.getObjRef()) - self._rtsm.setMultiModeComponentAction(self._comp.getObjRef()) - return - - - -############### test ################# -if __name__ == '__main__': - unittest.main() diff --git a/OpenRTM_aist/test/test_RingBuffer.py b/OpenRTM_aist/test/test_RingBuffer.py deleted file mode 100755 index 570c685e..00000000 --- a/OpenRTM_aist/test/test_RingBuffer.py +++ /dev/null @@ -1,186 +0,0 @@ -#!/usr/bin/env python -# -*- Python -*- - -# \file test_RingBuffer.py -# \brief test for Defautl Buffer class -# \date $Date: 2007/09/12 $ -# \author Shinji Kurihara -# -# Copyright (C) 2006 -# Noriaki Ando -# Task-intelligence Research Group, -# Intelligent Systems Research Institute, -# National Institute of -# Advanced Industrial Science and Technology (AIST), Japan -# All rights reserved. -# - - -import sys -sys.path.insert(1,"../") -sys.path.insert(1,"../RTM_IDL") - -import unittest - -from RingBuffer import * -import OpenRTM_aist - -class TestRingBuffer(unittest.TestCase): - - def setUp(self): - self._rb = RingBuffer() - - def tearDown(self): - OpenRTM_aist.Manager.instance().shutdownManager() - return - - def test_init(self): - prop = OpenRTM_aist.Properties() - prop.setProperty("length","5") - prop.setProperty("write.full_policy","overwrite") - #prop.setProperty("write.full_policy","do_nothing") - #prop.setProperty("write.full_policy","block") - prop.setProperty("write.timeout","5.0") - prop.setProperty("read.full_policy","overwrite") - #prop.setProperty("read.full_policy","do_nothing") - #prop.setProperty("read.full_policy","block") - prop.setProperty("read.timeout","5.0") - self._rb.init(prop) - self.assertEqual(self._rb.length(),5) - return - - def test_length(self): - self.assertEqual(self._rb.length(), 8) - self.assertEqual(self._rb.length(7), OpenRTM_aist.BufferStatus.BUFFER_OK) - self.assertEqual(self._rb.length(), 7) - self.assertEqual(self._rb.length(0), OpenRTM_aist.BufferStatus.NOT_SUPPORTED) - self.assertEqual(self._rb.length(-1), OpenRTM_aist.BufferStatus.NOT_SUPPORTED) - self.assertEqual(self._rb.length(1), OpenRTM_aist.BufferStatus.BUFFER_OK) - self.assertEqual(self._rb.length(), 1) - return - - - def test_reset(self): - prop = OpenRTM_aist.Properties() - prop.setProperty("length","5") - prop.setProperty("write.full_policy","overwrite") - #prop.setProperty("write.full_policy","do_nothing") - #prop.setProperty("write.full_policy","block") - prop.setProperty("write.timeout","5.0") - prop.setProperty("read.full_policy","overwrite") - #prop.setProperty("read.full_policy","do_nothing") - #prop.setProperty("read.full_policy","block") - prop.setProperty("read.timeout","5.0") - self._rb.init(prop) - self.assertEqual(self._rb.write(123), OpenRTM_aist.BufferStatus.BUFFER_OK) - value = [None] - self.assertEqual(self._rb.read(value),OpenRTM_aist.BufferStatus.BUFFER_OK) - self.assertEqual(value[0],123) - self._rb.reset() - self.assertEqual(self._rb.read(value),OpenRTM_aist.BufferStatus.BUFFER_EMPTY) - self.assertEqual(value[0],123) - - return - - def test_write(self): - data=[0] - self.assertEqual(self._rb.write(1),OpenRTM_aist.BufferStatus.BUFFER_OK) - self._rb.read(data) - self.assertEqual(data[0],1) - - self.assertEqual(self._rb.write(2),OpenRTM_aist.BufferStatus.BUFFER_OK) - self._rb.read(data) - self.assertEqual(data[0],2) - - self.assertEqual(self._rb.write(3),OpenRTM_aist.BufferStatus.BUFFER_OK) - self._rb.read(data) - self.assertEqual(data[0],3) - - self.assertEqual(self._rb.write(4),OpenRTM_aist.BufferStatus.BUFFER_OK) - self._rb.read(data) - self.assertEqual(data[0],4) - - self.assertEqual(self._rb.write(5),OpenRTM_aist.BufferStatus.BUFFER_OK) - self._rb.read(data) - self.assertEqual(data[0],5) - - self.assertEqual(self._rb.write(6),OpenRTM_aist.BufferStatus.BUFFER_OK) - self._rb.read(data) - self.assertEqual(data[0],6) - - self.assertEqual(self._rb.write("string"),OpenRTM_aist.BufferStatus.BUFFER_OK) - self._rb.read(data) - self.assertEqual(data[0],"string") - - self.assertEqual(self._rb.write([1,2,3]),OpenRTM_aist.BufferStatus.BUFFER_OK) - self._rb.read(data) - self.assertEqual(data[0],[1,2,3]) - - self.assertEqual(self._rb.write(0.12345),OpenRTM_aist.BufferStatus.BUFFER_OK) - self._rb.read(data) - self.assertEqual(data[0],0.12345) - - for i in range(8): - self.assertEqual(self._rb.write(0.12345,1,0),OpenRTM_aist.BufferStatus.BUFFER_OK) - self.assertEqual(self._rb.write(0.12345,1,0),OpenRTM_aist.BufferStatus.TIMEOUT) - - def test_read(self): - data=[0] - self.assertEqual(self._rb.read(data,1,0),OpenRTM_aist.BufferStatus.TIMEOUT) - self.assertEqual(self._rb.write("string"),OpenRTM_aist.BufferStatus.BUFFER_OK) - # Failure pattern (parameter must be List object.) - # data=0 - # self._rb.read(data) - self.assertEqual(self._rb.read(data),OpenRTM_aist.BufferStatus.BUFFER_OK) - self.assertEqual(data[0],"string") - self.assertEqual(self._rb.read(data,1,0),OpenRTM_aist.BufferStatus.TIMEOUT) - - def test_readable(self): - data=[0] - self.assertEqual(self._rb.readable(),0) - self.assertEqual(self._rb.write("string"),OpenRTM_aist.BufferStatus.BUFFER_OK) - self.assertEqual(self._rb.readable(),1) - self.assertEqual(self._rb.read(data),OpenRTM_aist.BufferStatus.BUFFER_OK) - self.assertEqual(self._rb.readable(),0) - self._rb.read(data) - self.assertEqual(self._rb.readable(),0) - - def test_empty(self): - data=[0] - self.assertEqual(self._rb.empty(),True) - self.assertEqual(self._rb.write("string"),OpenRTM_aist.BufferStatus.BUFFER_OK) - self.assertEqual(self._rb.empty(),False) - self.assertEqual(self._rb.read(data),OpenRTM_aist.BufferStatus.BUFFER_OK) - self.assertEqual(self._rb.empty(),True) - self._rb.read(data) - self.assertEqual(self._rb.empty(),True) - - def COMMENTtest_isFull(self): - self.assertEqual(self._rb.isFull(),False) - - - def COMMENTtest_isEmpty(self): - self.assertEqual(self._rb.isEmpty(),True) - self._rb.init(0) - self.assertEqual(self._rb.isEmpty(),False) - - - def COMMENTtest_isNew(self): - self.assertEqual(self._rb.isNew(),False) - self._rb.init(0) - self.assertEqual(self._rb.isNew(),True) - data=[0] - self._rb.read(data) - self.assertEqual(self._rb.isNew(),False) - - self.assertEqual(self._rb.write(0.12345),OpenRTM_aist.BufferStatus.BUFFER_OK) - self.assertEqual(self._rb.write(0.12345),OpenRTM_aist.BufferStatus.BUFFER_OK) - self.assertEqual(self._rb.write(0.12345),OpenRTM_aist.BufferStatus.BUFFER_OK) - self.assertEqual(self._rb.isNew(),True) - self.assertEqual(self._rb.isNew(),True) - self.assertEqual(self._rb.isNew(),True) - - -############### test ################# -if __name__ == '__main__': - unittest.main() diff --git a/OpenRTM_aist/test/test_SdoConfiguration.py b/OpenRTM_aist/test/test_SdoConfiguration.py deleted file mode 100755 index 774ff07b..00000000 --- a/OpenRTM_aist/test/test_SdoConfiguration.py +++ /dev/null @@ -1,203 +0,0 @@ -#!/usr/bin/env python -# -*- Python -*- - -# -# \file test_SdoConfiguration.py -# \brief test for RT component base class -# \date $Date: 2007/09/06$ -# \author Shinji Kurihara -# -# Copyright (C) 2006 -# Task-intelligence Research Group, -# Intelligent Systems Research Institute, -# National Institute of -# Advanced Industrial Science and Technology (AIST), Japan -# All rights reserved. -# - -import sys -sys.path.insert(1,"../") -sys.path.insert(1,"../RTM_IDL") - -import unittest -import OpenRTM_aist -import SDOPackage, SDOPackage__POA - -from SdoConfiguration import * - -import CORBA -from omniORB import CORBA, PortableServer - -class ServiceProf(SDOPackage__POA.SDOService): - def __init__(self): - pass - -class OrganizationTest(SDOPackage__POA.Organization): - def __init__(self): - pass - - -configsample_spec = ["implementation_id", "ConfigSample", - "type_name", "ConfigSample", - "description", "Configuration example component", - "version", "1.0", - "vendor", "Shinji Kurihara, AIST", - "category", "example", - "activity_type", "DataFlowComponent", - "max_instance", "10", - "language", "C++", - "lang_type", "compile", - # Configuration variables - "conf.default.int_param0", "0", - "conf.default.int_param1", "1", - "conf.default.double_param0", "0.11", - "conf.default.double_param1", "9.9", - "conf.default.str_param0", "hoge", - "conf.default.str_param1", "dara", - "conf.default.vector_param0", "0.0,1.0,2.0,3.0,4.0", - ""] - -configsample_mode_spec = ["conf.default.int_param0", "10", - "conf.default.int_param1", "11", - "conf.default.double_param0", "0.22", - "conf.default.double_param1", "9999.9", - "conf.default.str_param0", "hogehoge", - "conf.default.str_param1", "daradaradata", - "conf.default.vector_param0", "0.1,1.1,2.1,3.1,4.1", - ""] - - -class TestConfiguration_impl(unittest.TestCase): - def setUp(self): - self._orb = CORBA.ORB_init() - self._poa = self._orb.resolve_initial_references("RootPOA") - - prop = OpenRTM_aist.Properties(defaults_str=configsample_spec) - ca = OpenRTM_aist.ConfigAdmin(prop.getNode("conf")) - self._sdoconf = Configuration_impl(ca) - - def tearDown(self): - OpenRTM_aist.Manager.instance().shutdownManager() - return - - def test_set_device_profile(self): - dprof = SDOPackage.DeviceProfile("test","","","0.1.0",[]) - self._sdoconf.set_device_profile(dprof) - self.assertEqual(self._sdoconf.getDeviceProfile().device_type, "test") - self.assertEqual(self._sdoconf.getDeviceProfile().version, "0.1.0") - - self.assertRaises(SDOPackage.InvalidParameter, self._sdoconf.set_device_profile, None ) - - - def test_add_service_profile(self): - sprof = SDOPackage.ServiceProfile("test","MyService",[],ServiceProf()) - self._sdoconf.add_service_profile(sprof) - profiles = self._sdoconf.getServiceProfiles() - self.assertEqual(profiles[0].id, "test") - self.assertEqual(self._sdoconf.getServiceProfile("test").id, "test") - self._sdoconf.remove_service_profile("test") - self.assertEqual(self._sdoconf.getServiceProfile("test").id, "") - - self.assertRaises(SDOPackage.InvalidParameter, self._sdoconf.add_service_profile, None ) - self.assertRaises(SDOPackage.InvalidParameter, self._sdoconf.remove_service_profile, None ) - - # Failure pattern - #self.assertEqual(self._sdoconf.getServiceProfile("test").id, "test") - - def test_add_organization(self): - org = OrganizationTest() - self._sdoconf.add_organization(org) - self._sdoconf.add_organization(org) - self._sdoconf.add_organization(org) - self.assertEqual(len(self._sdoconf.getOrganizations()), 3) - - self.assertRaises(SDOPackage.InvalidParameter, self._sdoconf.add_organization, None ) - self.assertRaises(SDOPackage.InternalError, self._sdoconf.remove_organization, "aaa" ) - self.assertRaises(SDOPackage.InvalidParameter, self._sdoconf.remove_organization, None ) - - - def test_get_configuration_parameters(self): - self._sdoconf.get_configuration_parameters() - - - def test_get_configuration_parameter_values(self): - param_val = self._sdoconf.get_configuration_parameter_values() - self.assertEqual(param_val, []) - - def test_get_configuration_parameter_value(self): - param_val = self._sdoconf.get_configuration_parameter_value("aaa") - self.assertEqual(param_val, None) - - self.assertRaises(SDOPackage.InvalidParameter, self._sdoconf.get_configuration_parameter_value, None ) - - - def test_set_configuration_parameter(self): - self.assertEqual(self._sdoconf.set_configuration_parameter("name",123), True) - self.assertRaises(SDOPackage.InvalidParameter, self._sdoconf.set_configuration_parameter, None,None ) - self.assertRaises(SDOPackage.InvalidParameter, self._sdoconf.set_configuration_parameter, "name",None ) - self.assertRaises(SDOPackage.InvalidParameter, self._sdoconf.set_configuration_parameter, None,123 ) - - def test_get_configuration_sets(self): - conf_sets = self._sdoconf.get_configuration_sets() - self.assertEqual(len(conf_sets), 1) - - - def test_get_configuration_set(self): - conf_set = self._sdoconf.get_configuration_set("default") - self.assertEqual(conf_set.configuration_data[0].name, "int_param0") - self.assertEqual(conf_set.configuration_data[0].value.value(), "0") - - self.assertRaises(SDOPackage.InvalidParameter, self._sdoconf.get_configuration_set, None ) - - def test_set_configuration_set_values(self): - self._sdoconf.set_configuration_set_values(SDOPackage.ConfigurationSet("default2","",[])) - - self.assertRaises(SDOPackage.InvalidParameter, self._sdoconf.set_configuration_set_values, None ) - - def test_get_active_configuration_set(self): - self.assertEqual(self._sdoconf.get_active_configuration_set().id, "default") - - - def test_add_configuration_set(self): - self._sdoconf.add_configuration_set(SDOPackage.ConfigurationSet("default2","",[])) - - self.assertRaises(SDOPackage.InvalidParameter, self._sdoconf.add_configuration_set, None ) - - def test_remove_configuration_set(self): - self._sdoconf.add_configuration_set(SDOPackage.ConfigurationSet("default2","",[])) - self.assertEqual(self._sdoconf.remove_configuration_set("default2"),True) - - self.assertRaises(SDOPackage.InvalidParameter, self._sdoconf.remove_configuration_set, None ) - - def test_activate_configuration_set(self): - self._sdoconf.add_configuration_set(SDOPackage.ConfigurationSet("default2","",[])) - self.assertEqual(self._sdoconf.activate_configuration_set("default2"),True) - - self.assertRaises(SDOPackage.InvalidParameter, self._sdoconf.activate_configuration_set, None ) - - def test_getObjRef(self): - self._sdoconf.getObjRef() - - def test_getOrganizations(self): - self._sdoconf.getOrganizations() - - def test_getDeviceProfile(self): - self._sdoconf.getDeviceProfile() - - def test_getServiceProfiles(self): - self._sdoconf.getServiceProfiles() - - def test_getServiceProfile(self): - self._sdoconf.getServiceProfile("default") - - def test_getOrganizations(self): - self._sdoconf.getOrganizations() - - def test_getUUID(self): - print self._sdoconf.getUUID() - - - -############### test ################# -if __name__ == '__main__': - unittest.main() diff --git a/OpenRTM_aist/test/test_SdoOrganization.py b/OpenRTM_aist/test/test_SdoOrganization.py deleted file mode 100755 index 2379cbac..00000000 --- a/OpenRTM_aist/test/test_SdoOrganization.py +++ /dev/null @@ -1,160 +0,0 @@ -#!/usr/bin/env python -# -*- Python -*- - -# -# \file test_SdoOrganization.py -# \brief test for SDO Organization implementation class -# \date $Date: 2007/09/12 $ -# \author Shinji Kurihara -# -# Copyright (C) 2006 -# Task-intelligence Research Group, -# Intelligent Systems Research Institute, -# National Institute of -# Advanced Industrial Science and Technology (AIST), Japan -# All rights reserved. -# - -import omniORB.any -from omniORB import CORBA -import threading - -import sys -sys.path.insert(1,"../") -sys.path.insert(1,"../RTM_IDL") - -import unittest -import OpenRTM_aist -import SDOPackage, SDOPackage__POA - -from SdoOrganization import * - - -class TestComp(OpenRTM_aist.DataFlowComponentBase): - def __init__(self, manager): - OpenRTM_aist.DataFlowComponentBase.__init__(self, manager) - - def onInitialize(self): - print "onInitialize" - return RTC.RTC_OK - - def onFinalize(self): - print "onFinalize" - return RTC.RTC_OK - - def onStartup(self, ec_id): - print "onStartup" - return RTC.RTC_OK - - def onShutdown(self, ec_id): - print "onSutdown" - return RTC.RTC_OK - - def onActivated(self, ec_id): - print "onActivated" - return RTC.RTC_OK - - def onDeactivated(self, ec_id): - print "onDeactivated" - return RTC.RTC_OK - - def onExecute(self, ec_id): - print "onExecute" - return RTC.RTC_OK - - def onAborting(self, ec_id): - print "onAborting" - return RTC.RTC_OK - - def onReset(self, ec_id): - print "onReset" - return RTC.RTC_OK - - def onStateUpdate(self, ec_id): - print "onStateUpdate" - return RTC.RTC_OK - - def onRateChanged(self, ec_id): - print "onRateChanged" - return RTC.RTC_OK - - -class TestOrganization_impl(unittest.TestCase): - def setUp(self): - rtc = TestComp(OpenRTM_aist.Manager.instance()) - self.org = Organization_impl(rtc.getObjRef()) - - def tearDown(self): - OpenRTM_aist.Manager.instance().shutdownManager() - return - - def test_get_organization_id(self): - print self.org.get_organization_id() - - def test_get_organization_property(self): - nv_list = [SDOPackage.NameValue("test", 100)] - self.org.add_organization_property(SDOPackage.OrganizationProperty(nv_list)) - self.assertEqual(self.org.get_organization_property().properties[0].name, "test") - self.org.remove_organization_property("test") - ret_val = self.org.get_organization_property() - self.assertEqual(len(ret_val.properties), 0) - - self.assertRaises(SDOPackage.InvalidParameter, self.org.remove_organization_property, None ) - - def test_get_organization_property_value(self): - self.org.set_organization_property_value("test", 100) - self.assertRaises(SDOPackage.InvalidParameter, self.org.set_organization_property_value, None, None ) - - val = omniORB.any.from_any(self.org.get_organization_property_value("test")) - self.assertEqual(val, 100) - # Failure pattern - # because get_organization_property_value() returns value of CORBA.Any type. - # self.assertEqual(self.org.get_organization_property_value("test"), 100) - self.assertRaises(SDOPackage.InvalidParameter, self.org.get_organization_property_value, "aaa" ) - self.assertRaises(SDOPackage.InvalidParameter, self.org.get_organization_property_value, None ) - - self.assertRaises(SDOPackage.InvalidParameter, self.org.set_organization_property_value, None, "aaa" ) - - - def test_get_owner(self): - rtc = TestComp(OpenRTM_aist.Manager.instance()) - self.org.set_owner(rtc.getObjRef()) - self.assertNotEqual(self.org.get_owner(),None) - self.assertRaises(SDOPackage.InvalidParameter, self.org.set_owner, None ) - - class sdo_test(OpenRTM_aist.RTObject_impl): - def __init__(self): - self._orb = CORBA.ORB_init() - self._poa = self._orb.resolve_initial_references("RootPOA") - OpenRTM_aist.RTObject_impl.__init__(self, orb=self._orb, poa=self._poa) - - - def test_get_members(self): - # Failure pattern - #self.org.set_members([]) - self.assertEqual(self.org.get_members(),[]) - member = self.sdo_test() - member.setInstanceName("test0") - self.org.set_members([member]) - member = self.sdo_test() - member.setInstanceName("test1") - self.org.add_members([member]) - self.assertEqual(len(self.org.get_members()),2) - self.org.remove_member("test1") - self.assertEqual(len(self.org.get_members()),1) - - self.assertRaises(SDOPackage.InvalidParameter, self.org.set_members, None ) - self.assertRaises(SDOPackage.InvalidParameter, self.org.add_members, None ) - self.assertRaises(SDOPackage.InvalidParameter, self.org.remove_member, None ) - - - def test_get_dependency(self): - self.org.set_dependency(SDOPackage.OWN) - self.assertEqual(self.org.get_dependency(), SDOPackage.OWN) - - self.assertRaises(SDOPackage.InvalidParameter, self.org.set_dependency, None ) - - -############### test ################# -if __name__ == '__main__': - unittest.main() diff --git a/OpenRTM_aist/test/test_SdoService.py b/OpenRTM_aist/test/test_SdoService.py deleted file mode 100755 index b9347df8..00000000 --- a/OpenRTM_aist/test/test_SdoService.py +++ /dev/null @@ -1,70 +0,0 @@ -#!/usr/bin/env python -# -*- Python -*- - -# -# \file test_SdoService.py -# \brief test for SDO Service administration class -# \date $Date: 2007/09/12 $ -# \author Shinji Kurihara -# -# Copyright (C) 2006 -# Task-intelligence Research Group, -# Intelligent Systems Research Institute, -# National Institute of -# Advanced Industrial Science and Technology (AIST), Japan -# All rights reserved. -# - - -import sys -sys.path.insert(1,"../") -sys.path.insert(1,"../RTM_IDL") - -import unittest - -from SdoService import * -import OpenRTM_aist - - -class TestSDOServiceProfile(unittest.TestCase): - def setUp(self): - self.sdosp = SDOServiceProfile() - - def tearDown(self): - OpenRTM_aist.Manager.instance().shutdownManager() - return - - def test_getProfile(self): - sdosp = SDOServiceProfile("test", "test_type") - prof = sdosp.getProfile() - self.assertEqual(prof.id,"test") - self.assertEqual(prof.type,"test_type") - - def test_setName(self): - self.sdosp.setName("test") - self.assertEqual(self.sdosp.getName(),"test") - - - def test_setInterfaceType(self): - self.sdosp.setInterfaceType("test_type") - self.assertEqual(self.sdosp.getInterfaceType(),"test_type") - - - def test_setIdlDefinition(self): - self.sdosp.setIdlDefinition("test_idl") - self.assertEqual(self.sdosp.getIdlDefinition(),"test_idl") - - - def test_setProperties(self): - self.sdosp.setProperties(None) - self.assertEqual(self.sdosp.getProperties(),None) - - - def test_setServiceRef(self): - self.sdosp.setServiceRef(None) - self.assertEqual(self.sdosp.getServiceRef(),None) - - -############### test ################# -if __name__ == '__main__': - unittest.main() diff --git a/OpenRTM_aist/test/test_SdoServiceAdmin.py b/OpenRTM_aist/test/test_SdoServiceAdmin.py deleted file mode 100644 index a396f381..00000000 --- a/OpenRTM_aist/test/test_SdoServiceAdmin.py +++ /dev/null @@ -1,139 +0,0 @@ -#!/usr/bin/env python -# -*- coding: euc-jp -*- - -## -# @file test_SdoServiceAdmin.py -# @brief test for SdoServiceAdmin class -# @date $Date$ -# @author Shinji Kurihara -# -# Copyright (C) 2011 -# Intelligent Systems Research Institute, -# National Institute of -# Advanced Industrial Science and Technology (AIST), Japan -# All rights reserved. - -import sys -sys.path.insert(1, "../") - -import unittest -from SdoServiceAdmin import * -import OpenRTM_aist -import SDOPackage,SDOPackage__POA -from omniORB import CORBA, PortableServer -from omniORB import any - - -class MockRTC(OpenRTM_aist.RTObject_impl): - def __init__(self): - self._orb = CORBA.ORB_init() - self._poa = self._orb.resolve_initial_references("RootPOA") - OpenRTM_aist.RTObject_impl.__init__(self, orb=self._orb, poa=self._poa) - pass - - -class SDOServiceMock(SDOPackage__POA.SDOService): - def __init__(self): - pass - -class MockSdoServiceConsumer(OpenRTM_aist.SdoServiceConsumerBase): - """ - """ - - def __init__(self): - OpenRTM_aist.SdoServiceConsumerBase.__init__(self) - return - - def reinit(self, profile): - pass - - def getProfile(self): - any_val = any.to_any("3.14159") - nv = SDOPackage.NameValue("PROPERTIES NAME 0", any_val) - sprof = SDOPackage.ServiceProfile("test id","INTERFACE_TYPE",[nv],SDOServiceMock()) - return sprof - - -class TestListener(unittest.TestCase): - def setUp(self): - return - - - def tearDown(self): - OpenRTM_aist.Manager.instance().shutdownManager() - return - - - def test_addSdoServiceConsumerFactory(self): - sdoadmin = SdoServiceAdmin(MockRTC()) - self.assertEqual(sdoadmin.addSdoServiceConsumerFactory(),False) - return - - - def test_removeSdoServiceConsumerFactory(self): - sdoadmin = SdoServiceAdmin(MockRTC()) - self.assertEqual(sdoadmin.removeSdoServiceConsumerFactory(),False) - return - - - def test_addSdoServiceConsumer(self): - any_val = any.to_any("3.14159") - nv = SDOPackage.NameValue("PROPERTIES NAME 0", any_val) - sprof = SDOPackage.ServiceProfile("ID 0","INTERFACE_TYPE",[nv],SDOServiceMock()) - sdoadmin = SdoServiceAdmin(MockRTC()) - self.assertEqual(sdoadmin.addSdoServiceConsumer(sprof),False) - return - - - def test_removeSdoServiceConsumer(self): - any_val = any.to_any("3.14159") - nv = SDOPackage.NameValue("PROPERTIES NAME 0", any_val) - sprof = SDOPackage.ServiceProfile("test id","INTERFACE_TYPE",[nv],SDOServiceMock()) - sdoadmin = SdoServiceAdmin(MockRTC()) - self.assertEqual(sdoadmin.addSdoServiceConsumer(sprof),False) - sdoadmin._consumers.append(MockSdoServiceConsumer()) - self.assertEqual(sdoadmin.removeSdoServiceConsumer("test id"),True) - self.assertEqual(sdoadmin.addSdoServiceConsumer(sprof),False) - sdoadmin._consumers.append(MockSdoServiceConsumer()) - self.assertEqual(sdoadmin.removeSdoServiceConsumer("test id2"),False) - return - - - def test_isAllowedConsumerType(self): - sdoadmin = SdoServiceAdmin(MockRTC()) - any_val = any.to_any("3.14159") - nv = SDOPackage.NameValue("PROPERTIES NAME 0", any_val) - sprof = SDOPackage.ServiceProfile("test id","INTERFACE_TYPE",[nv],SDOServiceMock()) - self.assertEqual(sdoadmin.isAllowedConsumerType(sprof),True) - sdoadmin._allConsumerAllowed = False - self.assertEqual(sdoadmin.isAllowedConsumerType(sprof),False) - sdoadmin._consumerTypes = ["type0","type1","type2","INTERFACE_TYPE"] - self.assertEqual(sdoadmin.isAllowedConsumerType(sprof),True) - sdoadmin._consumerTypes = ["type0","type1","type2"] - self.assertEqual(sdoadmin.isAllowedConsumerType(sprof),False) - return - - - def test_isExistingConsumerType(self): - factory = OpenRTM_aist.SdoServiceConsumerFactory.instance() - factory.addFactory("test_factory",OpenRTM_aist.SdoServiceConsumerBase,OpenRTM_aist.Delete) - sdoadmin = SdoServiceAdmin(MockRTC()) - any_val = any.to_any("3.14159") - nv = SDOPackage.NameValue("PROPERTIES NAME 0", any_val) - sprof = SDOPackage.ServiceProfile("test id","INTERFACE_TYPE",[nv],SDOServiceMock()) - self.assertEqual(sdoadmin.isExistingConsumerType(sprof),False) - factory.addFactory("INTERFACE_TYPE",OpenRTM_aist.SdoServiceConsumerBase,OpenRTM_aist.Delete) - self.assertEqual(sdoadmin.isExistingConsumerType(sprof),True) - return - - - def test_getUUID(self): - sdoadmin = SdoServiceAdmin(MockRTC()) - self.assertNotEqual(sdoadmin.getUUID(),"") - self.assertNotEqual(sdoadmin.getUUID(),None) - return - - -############### test ################# -if __name__ == '__main__': - unittest.main() diff --git a/OpenRTM_aist/test/test_SharedMemory.py b/OpenRTM_aist/test/test_SharedMemory.py deleted file mode 100644 index afd2bfd4..00000000 --- a/OpenRTM_aist/test/test_SharedMemory.py +++ /dev/null @@ -1,212 +0,0 @@ -#!/usr/bin/env python -# -*- coding: euc-jp -*- - -# -# \file test_SharedMemory.py -# \brief -# \date $Date: $ -# \author Nobuhiko Miyamoto -# - - -import sys -sys.path.insert(1,"../") - -try: - import unittest2 as unittest -except (ImportError): - import unittest - -import time - -#from Manager import * -import OpenRTM_aist -import RTC, OpenRTM -from omniORB import cdrMarshal -from omniORB import cdrUnmarshal -import CORBA -import platform -import os - - - - - - - -class TestSharedMemory(unittest.TestCase): - - def setUp(self): - sys.argv.extend(['-o', 'port.outport.out.shem_default_size:1k']) - #sys.argv.extend(['-o', 'port.dataport.serializer.cdr.endian:1k']) - #sys.argv.extend(['-o', 'port.inport.in.shem_default_size:1k']) - self.manager = OpenRTM_aist.Manager.init(sys.argv) - self.manager.activateManager() - - self._d_in = RTC.TimedOctetSeq(RTC.Time(0,0),[]) - self._inIn = OpenRTM_aist.InPort("in", self._d_in) - - prop = self.manager.getConfig().getNode("port.inport.in") - self._inIn.init(prop) - self.inport_obj = self._inIn.getPortRef() - - - self._d_out = RTC.TimedOctetSeq(RTC.Time(0,0),[]) - self._outOut = OpenRTM_aist.OutPort("out", self._d_out) - prop = self.manager.getConfig().getNode("port.outport.out") - self._outOut.init(prop) - self.outport_obj = self._outOut.getPortRef() - - - - def tearDown(self): - self.manager.shutdownManager() - - def test_SharedMemory(self): - sh_read = OpenRTM_aist.SharedMemory() - sh_read_var = sh_read._this() - sh_write = OpenRTM_aist.SharedMemory() - sh_write_var = sh_write._this() - - sh_write.setInterface(sh_read_var) - - memsize = sh_write.string_to_MemorySize("1") - self.assertEqual(memsize, 1) - memsize = sh_write.string_to_MemorySize("1k") - self.assertEqual(memsize, 1024) - memsize = sh_write.string_to_MemorySize("1M") - self.assertEqual(memsize, 1024*1024) - - sh_write.create_memory(1000,"test") - sh_write.setEndian(True) - data_cdr = cdrMarshal(CORBA.TC_ulong, 100, True) - sh_write.write(data_cdr) - data_cdr = sh_read.read() - data = cdrUnmarshal(CORBA.TC_ulong, data_cdr, True) - self.assertEqual(data, 100) - if platform.system() == "Windows": - pass - else: - self.assertTrue(os.path.exists("/dev/shm/test")) - sh_write.close_memory(True) - if platform.system() == "Windows": - pass - else: - self.assertFalse(os.path.exists("/dev/shm/test")) - - - def test_Push(self): - - prop = OpenRTM_aist.Properties() - #prop.setProperty("dataport.shem_default_size","10k") - prop.setProperty("dataport.interface_type","shared_memory") - prop.setProperty("dataport.dataflow_type","push") - ret = OpenRTM_aist.connect("con1",prop,self.inport_obj,self.outport_obj) - - self._d_out.data = "a"*100 - self._outOut.write() - - ret = self._inIn.isNew() - self.assertTrue(ret) - - data = self._inIn.read() - self.assertEqual(data.data, self._d_out.data) - - - self._d_out.data = "a"*50000 - self._outOut.write() - - data = self._inIn.read() - self.assertEqual(data.data, self._d_out.data) - - - self.outport_obj.disconnect_all() - - - def test_Push_big_endian(self): - - prop = OpenRTM_aist.Properties() - #prop.setProperty("dataport.shem_default_size","10k") - prop.setProperty("dataport.interface_type","shared_memory") - prop.setProperty("dataport.dataflow_type","push") - prop.setProperty("dataport.serializer.cdr.endian","big") - ret = OpenRTM_aist.connect("con1",prop,self.inport_obj,self.outport_obj) - - self._d_out.data = "a"*100 - self._outOut.write() - - ret = self._inIn.isNew() - self.assertTrue(ret) - - data = self._inIn.read() - self.assertEqual(data.data, self._d_out.data) - - - self._d_out.data = "a"*50000 - self._outOut.write() - - data = self._inIn.read() - self.assertEqual(data.data, self._d_out.data) - - - self.outport_obj.disconnect_all() - - def test_Pull(self): - prop = OpenRTM_aist.Properties() - #prop.setProperty("dataport.shem_default_size","10k") - prop.setProperty("dataport.interface_type","shared_memory") - prop.setProperty("dataport.dataflow_type","pull") - ret = OpenRTM_aist.connect("con1",prop,self.inport_obj,self.outport_obj) - - self._d_out.data = "a"*100 - self._outOut.write() - - #ret = self._inIn.isNew() - #self.assertTrue(ret) - - data = self._inIn.read() - self.assertEqual(data.data, self._d_out.data) - - - self._d_out.data = "a"*50000 - self._outOut.write() - - - data = self._inIn.read() - self.assertEqual(data.data, self._d_out.data) - - - self.outport_obj.disconnect_all() - - - def test_Pull_big_endian(self): - prop = OpenRTM_aist.Properties() - #prop.setProperty("dataport.shem_default_size","10k") - prop.setProperty("dataport.interface_type","shared_memory") - prop.setProperty("dataport.dataflow_type","pull") - prop.setProperty("dataport.serializer.cdr.endian","big") - ret = OpenRTM_aist.connect("con1",prop,self.inport_obj,self.outport_obj) - - self._d_out.data = "a"*100 - self._outOut.write() - - #ret = self._inIn.isNew() - #self.assertTrue(ret) - - data = self._inIn.read() - self.assertEqual(data.data, self._d_out.data) - - - self._d_out.data = "a"*50000 - self._outOut.write() - - - data = self._inIn.read() - self.assertEqual(data.data, self._d_out.data) - - - self.outport_obj.disconnect_all() - -############### test ################# -if __name__ == '__main__': - unittest.main() diff --git a/OpenRTM_aist/test/test_Singleton.py b/OpenRTM_aist/test/test_Singleton.py deleted file mode 100755 index eee55cbd..00000000 --- a/OpenRTM_aist/test/test_Singleton.py +++ /dev/null @@ -1,77 +0,0 @@ -#!/usr/bin/env python -# -*- Python -*- - -# @file test_Singleton.py -# @brief test for Singleton class -# @date $Date$ -# @author Shinji Kurihara -# -# Copyright (C) 2003-2005 -# Task-intelligence Research Group, -# Intelligent Systems Research Institute, -# National Institute of -# Advanced Industrial Science and Technology (AIST), Japan -# All rights reserved. -# -# $Id$ -# - -# -# $Log$ -# -# - -import sys -sys.path.insert(1,"../") - -import unittest - -from Singleton import * - -class SingletonMock(Singleton): - _cnt = 0 - def __init__(self): - print "SingletonMock" - #self._cnt = 0 - pass - - def up(self): - self._cnt += 1 - - def get(self): - return self._cnt - - -class TestSingleton(unittest.TestCase): - def setUp(self): - return - - def tearDown(self): - return - - - def test_SingletonCase(self): - mock = SingletonMock() - print "Singleton 0" - mock0 = SingletonMock() - print "mock0 ", mock0 - print "Singleton 1" - mock1 = SingletonMock() - print "mock1 ", mock1 - self.assertEqual(mock0.get(), 0) - self.assertEqual(mock1.get(), 0) - mock0.up() - self.assertEqual(mock0.get(), 1) - self.assertEqual(mock1.get(), 1) - mock1.up() - self.assertEqual(mock0.get(), 2) - self.assertEqual(mock1.get(), 2) - mock2 = SingletonMock.instance() - print "mock2 ", mock2 - self.assertEqual(mock0.get(), 2) - self.assertEqual(mock1.get(), 2) - self.assertEqual(mock2.get(), 2) - return - -if __name__ == "__main__": - unittest.main() diff --git a/OpenRTM_aist/test/test_StateMachine.py b/OpenRTM_aist/test/test_StateMachine.py deleted file mode 100755 index 1cebc960..00000000 --- a/OpenRTM_aist/test/test_StateMachine.py +++ /dev/null @@ -1,134 +0,0 @@ -#!/usr/bin/env python -# -*- Python -*- - -# -# \file test_StateMachine.py -# \brief State machine template class -# \date $Date: 2007/08/30$ -# \author Shinji Kurihara -# -# Copyright (C) 2006 -# Task-intelligence Research Group, -# Intelligent Systems Research Institute, -# National Institute of -# Advanced Industrial Science and Technology (AIST), Japan -# All rights reserved. -# - -import sys -sys.path.insert(1,"../") - -import unittest - -from StateMachine import * -import OpenRTM_aist - - - -class TestStateMachine(unittest.TestCase): -# state = [0,1,2] - state = [RTC.INACTIVE_STATE, RTC.ACTIVE_STATE, RTC.ERROR_STATE] - - def setUp(self): - self._sm = StateMachine(3) - - self._sm.setNOP(self.nullAction) - - self._sm.setEntryAction(RTC.ACTIVE_STATE, self.on_activated) - self._sm.setEntryAction(RTC.ERROR_STATE,self.on_aborting) - self._sm.setPreDoAction(RTC.ACTIVE_STATE, self.on_reset) - self._sm.setDoAction(RTC.ACTIVE_STATE, self.on_execute) - self._sm.setPostDoAction(RTC.ACTIVE_STATE, self.on_state_update) - self._sm.setExitAction(RTC.ACTIVE_STATE, self.on_deactivated) - self._sm.setExitAction(RTC.ERROR_STATE, self.on_reset) - self._sm.setTransitionAction(self.transition) - - self._sm.setListener(self) - st = StateHolder() - st.prev = RTC.INACTIVE_STATE - st.curr = RTC.INACTIVE_STATE - st.next = RTC.INACTIVE_STATE - self._sm.setStartState(st) - self._sm.goTo(RTC.INACTIVE_STATE) - - def tearDown(self): - OpenRTM_aist.Manager.instance().shutdownManager() - return - - def nullAction(self, st): - print "nullAction." - return True - - def on_activated(self, st): - print "on_activated." - return True - - def on_deactivated(self, st): - print "on_deactivated." - return True - - def on_aborting(self, st): - print "on_aborting." - return True - - def on_error(self, st): - print "on_error." - return True - - def on_reset(self, st): - print "on_reset." - return True - - def on_execute(self, st): - print "on_execute." - return True - - def on_state_update(self, st): - print "on_state_update." - return True - - def transition(self, st): - print "transition." - return True - - - def test_setNOP(self): - self._sm.setNOP(self.nullAction) - - - def test_getStates(self): - self.assertEqual(self._sm.getStates().curr, RTC.INACTIVE_STATE) - self.assertEqual(self._sm.getStates().prev, RTC.INACTIVE_STATE) - self.assertEqual(self._sm.getStates().next, RTC.INACTIVE_STATE) - - st = StateHolder() - st.prev = RTC.ERROR_STATE - st.curr = RTC.ERROR_STATE - st.next = RTC.ERROR_STATE - self._sm.setStartState(st) - - self.assertEqual(self._sm.getStates().curr, RTC.ERROR_STATE) - self.assertEqual(self._sm.getStates().prev, RTC.ERROR_STATE) - self.assertEqual(self._sm.getStates().next, RTC.ERROR_STATE) - - def test_getState(self): - self.assertEqual(self._sm.getState(), RTC.INACTIVE_STATE) - - def test_isIn(self): - self.assertEqual(self._sm.isIn(RTC.INACTIVE_STATE), True) - - def test_goTo(self): - self._sm.goTo(RTC.INACTIVE_STATE) - -# def test_worker(self): -# self._sm.goTo(RTC.ACTIVE_STATE) -# self.assertEqual(self._sm.worker(), True) -# self.assertEqual(self._sm.worker(), True) -# self._sm.goTo(RTC.INACTIVE_STATE) -# self.assertEqual(self._sm.worker(), True) -# self.assertEqual(self._sm.worker(), True) - - -############### test ################# -if __name__ == '__main__': - unittest.main() diff --git a/OpenRTM_aist/test/test_StringUtil.py b/OpenRTM_aist/test/test_StringUtil.py deleted file mode 100755 index ccc25c4c..00000000 --- a/OpenRTM_aist/test/test_StringUtil.py +++ /dev/null @@ -1,285 +0,0 @@ -#!/usr/bin/env python -# -*- Python -*- - -# -# \file test_StringUtil.py -# \brief test for String operation utility -# \date $Date: $ -# \author Shinji Kurihara -# -# Copyright (C) 2003-2005 -# Task-intelligence Research Group, -# Intelligent Systems Research Institute, -# National Institute of -# Advanced Industrial Science and Technology (AIST), Japan -# All rights reserved. -# - -import sys -sys.path.insert(1,"../") - -import unittest - -from StringUtil import * -import OpenRTM_aist - -class TestStringUtil(unittest.TestCase): - - def setUp(self): - pass - - def tearDown(self): - OpenRTM_aist.Manager.instance().shutdownManager() - pass - - def test_isEscaped(self): - self.assertEqual(isEscaped("test\\\\test",5), True, "Result failed.") - - - def test_escape(self): - self.assertEqual(escape("test\ttest"), "test\\ttest", "Result failed.") - self.assertEqual(escape("test\ntest"), "test\\ntest", "Result failed.") - self.assertEqual(escape("test\ftest"), "test\\ftest", "Result failed.") - self.assertEqual(escape("test\rtest"), "test\\rtest", "Result failed.") - - - def test_unescape(self): - self.assertEqual(unescape("test\\ttest"), "test\ttest", "Result failed.") - self.assertEqual(unescape("test\\ntest"), "test\ntest", "Result failed.") - self.assertEqual(unescape("test\\ftest"), "test\ftest", "Result failed.") - self.assertEqual(unescape("test\\rtest"), "test\rtest", "Result failed.") - - - def test_eraseBlank(self): - _str=[" test"] - eraseBlank(_str) - self.assertEqual(_str[0], "test", "Result failed.") - - _str=[" test"] - eraseBlank(_str) - self.assertEqual(_str[0], "test", "Result failed.") - - _str=["\t\ttest"] - eraseBlank(_str) - self.assertEqual(_str[0], "test", "Result failed.") - - _str=[""] - eraseBlank(_str) - self.assertEqual(_str[0], "", "Result failed.") - - _str=["\t\n test"] - eraseBlank(_str) - self.assertEqual(_str[0], "\ntest") - - _str=["\t\\t test"] - eraseBlank(_str) - self.assertEqual(_str[0], "\\ttest", "Result failed.") - - def test_eraseHeadBlank(self): - _str=[" test"] - eraseHeadBlank(_str) - self.assertEqual(_str[0], "test", "Result failed.") - - _str=[" test"] - eraseHeadBlank(_str) - self.assertEqual(_str[0], "test", "Result failed.") - - _str=["\t\ttest"] - eraseHeadBlank(_str) - self.assertEqual(_str[0], "test", "Result failed.") - - _str=[""] - eraseHeadBlank(_str) - self.assertEqual(_str[0], "", "Result failed.") - - _str=["\t\n test"] - eraseHeadBlank(_str) - self.assertEqual(_str[0], "\n test", "Result failed.") - - _str=["\t\\t test"] - eraseHeadBlank(_str) - self.assertEqual(_str[0], "\\t test", "Result failed.") - - - # failed case - # _str=["\\t\\ttest"] - # eraseHeadBlank(_str) - # self.assertEqual(_str[0], "test", "Result failed.") - - - def test_eraseTailBlank(self): - _str=["test "] - eraseTailBlank(_str) - self.assertEqual(_str[0], "test", "Result failed.") - - _str=["test "] - eraseTailBlank(_str) - self.assertEqual(_str[0], "test", "Result failed.") - - _str=["test\t\t"] - eraseTailBlank(_str) - self.assertEqual(_str[0], "test", "Result failed.") - - _str=["test\t\n\t"] - eraseTailBlank(_str) - self.assertEqual(_str[0], "test\t\n", "Result failed.") - - _str=["test\\t"] - eraseTailBlank(_str) - self.assertEqual(_str[0], "test\\t", "Result failed.") - - # failed case - # _str=["test\\t\\t"] - # eraseTailBlank(_str) - # self.assertEqual(_str[0], "test", "Result failed.") - - def test_normalize(self): - _str = [" NORMALIZE "] - normalize(_str) - self.assertEqual(_str[0],"normalize") - - _str = [" \t \tNORmALIZE "] - normalize(_str) - self.assertEqual(_str[0],"normalize") - - _str = [" nORMALIZE\t \t\t\t"] - normalize(_str) - self.assertEqual(_str[0],"normalize") - - - def test_replaceString(self): - _str= ["replace"] - replaceString(_str,"l", "r") - self.assertEqual(_str[0], "reprace", "Result failed.") - - _str= ["replace"] - replaceString(_str,"re", "") - self.assertEqual(_str[0], "place", "Result failed.") - - _str= ["replace"] - replaceString(_str,"e", "a") - self.assertEqual(_str[0], "raplaca", "Result failed.") - - - def test_split(self): - _str = split("test0,test1,test2", ",") - self.assertEqual(_str[0], "test0", "Result failed.") - self.assertEqual(_str[1], "test1", "Result failed.") - self.assertEqual(_str[2], "test2", "Result failed.") - - _str = split("test0.test1.test2", ".") - self.assertEqual(_str[0], "test0", "Result failed.") - self.assertEqual(_str[1], "test1", "Result failed.") - self.assertEqual(_str[2], "test2", "Result failed.") - - _str = split("test0/test1/test2", "/") - self.assertEqual(_str[0], "test0", "Result failed.") - self.assertEqual(_str[1], "test1", "Result failed.") - self.assertEqual(_str[2], "test2", "Result failed.") - - _str = split("test0 test1 test2", " ") - self.assertEqual(_str[0], "test0", "Result failed.") - self.assertEqual(_str[1], "test1", "Result failed.") - self.assertEqual(_str[2], "test2", "Result failed.") - - - def test_toBool(self): - ret = toBool("yes", "yes", "no", True) - self.assertEqual(ret, True, "Result failed.") - - ret = toBool("no", "yes", "no", True) - self.assertEqual(ret, False, "Result failed.") - - ret = toBool("Yes", "YES", "NO", True) - self.assertEqual(ret, True, "Result failed.") - - ret = toBool("No", "YES", "NO", True) - self.assertEqual(ret, False, "Result failed.") - - def test_includes(self): - self.assertEqual(includes(["abc","abcde","ABC"],"abc"),True) - self.assertEqual(includes(["abc","abcde","ABC"],"a"),False) - self.assertEqual(includes(["abc","abcde","ABC"],"ABC"),True) - self.assertEqual(includes("abc,abcde,ABC","ABC"),True) - self.assertEqual(includes("abc,abcde,ABC","AbC",False),False) - self.assertEqual(includes(["abc","abcde","AbC"],"ABC"),True) - self.assertEqual(includes(["abc","abcde","AbC"],"ABC",False),False) - - - def test_isAbsolutePath(self): - self.assertEqual(isAbsolutePath("/usr/loca/bin"), True, "Result failed.") - self.assertEqual(isAbsolutePath("c:\\"), True, "Result failed.") - self.assertEqual(isAbsolutePath("\\\\localhost"), True, "Result failed.") - # failed case - # self.assertEqual(isAbsolutePath("\\localhost"), True, "Result failed.") - - - def test_isURL(self): - self.assertEqual(isURL("http://www.google.co.jp"), True, "Result failed.") - - # failed case - # self.assertEqual(isURL("www.google.co.jp"), True, "Result failed.") - # self.assertEqual(isURL("http:://www.google.co.jp"), True, "Result failed.") - - - def test_otos(self): - self.assertEqual(otos(123), "123", "Result failed.") - self.assertEqual(otos("123"), "123", "Result failed.") - self.assertEqual(otos(123456789123456789), "123456789123456789", "Result failed.") - self.assertEqual(otos(0.123), "0.123", "Result failed.") - - - def test_stringTo(self): - int_ = [0] - long_ = [0] - float_ = [0.0] - list_ = [[0.0,0.0,0.0,0.0]] - str_ = [""] - stringTo(int_,"123") - stringTo(long_,"123") - stringTo(float_,"0.123") - stringTo(list_,"0,1.1,2.2,3.3") - stringTo(str_,"hoge") - print list_[0] - self.assertEqual(int_[0], 123, "Result failed.") - self.assertEqual(long_[0], 123, "Result failed.") - self.assertEqual(float_[0], 0.123, "Result failed.") - self.assertEqual(list_[0], [0,1.1,2.2,3.3], "Result failed.") - self.assertEqual(str_[0], "hoge", "Result failed.") - - # failed case - # self.assertEqual(stringTo("int",0.123), 0.123, "Result failed.") - - - def test_unique_sv(self): - sv = ["test0","test1","test0","test2","test0"] - sv_ret = unique_sv(sv) - self.assertEqual(sv_ret[0], "test0", "Result failed.") - self.assertEqual(sv_ret[1], "test1", "Result failed.") - self.assertEqual(sv_ret[2], "test2", "Result failed.") - self.assertEqual(len(sv_ret), 3, "Result failed.") - - # failed case: len(sv_ret) is 4 - # - # sv = ["test0","test1","test0","test2","TEST0"] - # sv_ret = unique_sv(sv) - # self.assertEqual(len(sv_ret), 3, "Result failed.") - - - def test_flatten(self): - sv = ["test0","test1","test2"] - sv_ret = flatten(sv) - self.assertEqual(sv_ret, "test0, test1, test2","Result failed.") - - # failed case: Space is included. - # self.assertEqual(sv_ret, "test0,test1,test2","Result failed.") - - - def test_toArgv(self): - pass - - - -############### test ################# -if __name__ == '__main__': - unittest.main() diff --git a/OpenRTM_aist/test/test_SystemLogger.py b/OpenRTM_aist/test/test_SystemLogger.py deleted file mode 100755 index 4b12b85a..00000000 --- a/OpenRTM_aist/test/test_SystemLogger.py +++ /dev/null @@ -1,120 +0,0 @@ -#!/usr/bin/env python -# -*- Python -*- - -# @file test_SystemLogger.py -# @brief test for RT component logger class -# @date $Date$ -# @author Shinji Kurihara -# -# Copyright (C) 2003-2005 -# Task-intelligence Research Group, -# Intelligent Systems Research Institute, -# National Institute of -# Advanced Industrial Science and Technology (AIST), Japan -# All rights reserved. -# -# $Id$ -# - -# -# $Log$ -# -# - -import sys -sys.path.insert(1,"../") -import unittest - -from SystemLogger import * -import OpenRTM_aist - -i = 0 - -class TestLogger(unittest.TestCase): - def setUp(self): - - #import random - #val = random.uniform(0,100) - #self.filename = "log" + str(val) + ".log" - global i - i+=1 - self.filename = "log" + str(i) + ".log" - self.logstr = LogStream("test","FILE",self.filename) - - def tearDown(self): - self.logstr.__del__() - OpenRTM_aist.Manager.instance().shutdownManager() - pass - - def test_strToLogLevel(self): - self.logger = Logger.init("test","FILE","test.log") - self.assertEqual(self.logger.strToLogLevel("SILENT"), Logger.SILENT) - self.assertEqual(self.logger.strToLogLevel("ERROR"), Logger.ERROR) - self.assertEqual(self.logger.strToLogLevel("WARN"), Logger.WARN) - self.assertEqual(self.logger.strToLogLevel("INFO"), Logger.INFO) - self.assertEqual(self.logger.strToLogLevel("DEBUG"), Logger.DEBUG) - self.assertEqual(self.logger.strToLogLevel("TRACE"), Logger.TRACE) - self.assertEqual(self.logger.strToLogLevel("VERBOSE"), Logger.VERBOSE) - self.assertEqual(self.logger.strToLogLevel("PARANOID"), Logger.PARANOID) - self.assertEqual(self.logger.strToLogLevel("HOGE"), Logger.INFO) - - - def test_addHandler(self): - #self.logstr.addHandler("stdout") - self.logstr.setLogLevel("INFO") - self.logstr.RTC_INFO("addHandler test!!!!!") - - - def test_setLogLock(self): - self.logstr.setLogLock(True) - self.logstr.setLogLock(False) - - def test_enableLogLock(self): - self.logstr.enableLogLock() - - def test_disableLogLock(self): - self.logstr.disableLogLock() - - def test_acquire_release(self): - self.logstr.acquire() - self.logstr.release() - - def test_RTC_LOG(self): - import logging - self.logstr.RTC_LOG(logging.ERROR,"log %s, %s",("hoge","hogehoge")) - - - def test_RTC_ERROR(self): - self.logstr.RTC_ERROR("error!!!!!") - def test(): - raise MemorryError - try: - test() - except: - self.logstr.RTC_ERROR(sys.exc_info()) - - - def test_RTC_WARN(self): - self.logstr.RTC_WARN("warn!!!!!") - - - def test_RTC_INFO(self): - self.logstr.RTC_INFO("info!!!!!") - - - def test_RTC_DEBUG(self): - self.logstr.RTC_DEBUG("debug!!!!!") - - - def test_RTC_TRACE(self): - self.logstr.RTC_TRACE("trace!!!!") - - def test_RTC_VERBOSE(self): - self.logstr.RTC_VERBOSE("verbose!!!!") - - def test_RTC_PARANOID(self): - self.logstr.RTC_PARANOID("paranoid!!!!") - - -if __name__ == "__main__": - unittest.main() diff --git a/OpenRTM_aist/test/test_Task.py b/OpenRTM_aist/test/test_Task.py deleted file mode 100755 index ac6925cb..00000000 --- a/OpenRTM_aist/test/test_Task.py +++ /dev/null @@ -1,114 +0,0 @@ -#!/usr/bin/env/python -# -*- Python -*- - -# -# \file Task.py -# \brief Task class -# \date $Date: $ -# \author Shinji Kurihara -# -# Copyright (C) 2007 -# Task-intelligence Research Group, -# Intelligent Systems Research Institute, -# National Institute of -# Advanced Industrial Science and Technology (AIST), Japan -# All rights reserved. -# - -import sys,time -sys.path.insert(1,"../") - -import unittest - -from Task import * - -cnt = 0 - -class Mock(Task): - def __init__(self): - global cnt - cnt += 1 - self.cnt = cnt - Task.__init__(self) - self.flag = False - - def svc(self): - print "cnt: ", - while self.flag: - print self.cnt, " ", - time.sleep(0.1) - return - - def activate(self): - self.flag = True - Task.activate(self) - return - - def finalize(self): - self.flag = False - -class Mock2(Task): - def __init__(self,func): - global cnt - cnt += 1 - self.cnt = cnt - Task.__init__(self) - self.flag = False - self.func = func - - def svc(self): - time.sleep(1) - self.func() - return - - def activate(self): - self.flag = True - Task.activate(self) - return - - def finalize(self): - self.flag = False - - -class TestTask(unittest.TestCase): - def setUp(self): - self.mock = Mock() - return - - def test_activate(self): - self.mock.activate() - mock2= Mock() - mock2.activate() - time.sleep(2) - mock2.finalize() - self.mock.finalize() - return - - def test_wait(self): - self.mock.activate() - time.sleep(0.5) - mock2= Mock2(self.mock.finalize) - mock2.activate() - self.mock.wait() - mock2.finalize() - return - - - def test_reset(self): - self.mock.reset() - return - - - def test_finalize(self): - self.mock.finalize() - return - - - def test_svn_run(self): - self.mock.svc_run() - return - - -############### test ################# -if __name__ == '__main__': - unittest.main() diff --git a/OpenRTM_aist/test/test_TimeMeasure.py b/OpenRTM_aist/test/test_TimeMeasure.py deleted file mode 100755 index cc068d17..00000000 --- a/OpenRTM_aist/test/test_TimeMeasure.py +++ /dev/null @@ -1,188 +0,0 @@ -#!/usr/bin/env python -# -*- coding: euc-jp -*- - -# @file test_TimeMeasure.py -# @brief test for TimeMeasure class -# @date $Date: 2009/02/18$ -# @author Shinji Kurihara -# -# Copyright (C) 2009 -# Task-intelligence Research Group, -# Intelligent Systems Research Institute, -# National Institute of -# Advanced Industrial Science and Technology (AIST), Japan -# All rights reserved. -# - -import time -import sys -import math -sys.path.insert(1,"../") - -import unittest -from TimeMeasure import * - - - -class TestTimeMeasure(unittest.TestCase): - def setUp(self): - self._tm = TimeMeasure(10) - - def test_tick_tack(self): - for i in range(10): - self._tm.tick() - time.sleep(0.01) - self._tm.tack() - _max = [0] - _min = [0] - _mean = [0] - _stddev = [0] - print "count: ", self._tm.count() - print "result: ", self._tm.getStatistics(_max, _min, _mean, _stddev) - print "max: ", _max[0] - print "min: ", _min[0] - print "mean: ", _mean[0] - print "stddev: ", _stddev[0] - return - - def test_coutn(self): - tm_ = TimeMeasure() - self.assertEqual(0, tm_.count()) - - count0 = 10 - for i in range(10): - tm_.tick() - tm_.tack() - self.assertEqual(10, tm_.count()) - - tm_.reset() - self.assertEqual(0, tm_.count()) - - - count0 = 102 - for i in range(102): - tm_.tick() - tm_.tack() - self.assertNotEqual(102, tm_.count()) - return - - def test_stat(self): - tm_ = TimeMeasure() - maxi = [0.0] - mini = [0.0] - mean = [0.0] - stdev = [0.0] - - self.assertEqual(False, tm_.getStatistics(maxi, mini, mean, stdev)) - tm_.tick() - self.assertEqual(False, tm_.getStatistics(maxi, mini, mean, stdev)) - tm_.tack() - self.assertEqual(True, tm_.getStatistics(maxi, mini, mean, stdev)) - tm_.reset() - self.assertEqual(False, tm_.getStatistics(maxi, mini, mean, stdev)) - return - - def test_buflen(self): - tm_0 = TimeMeasure(1) - self.assertEqual(0, tm_0.count()) - tm_0.tick() - tm_0.tack() - self.assertEqual(1, tm_0.count()) - - count_ = 1024 - tm_1 = TimeMeasure(count_) - - for i in range(count_): - self.assertEqual(i, tm_1.count()) - tm_1.tick() - tm_1.tack() - - for i in range(count_): - tm_1.tick() - tm_1.tack() - self.assertEqual(count_ + 1, tm_1.count()) - return - - def test_30ms(self): - wait_ = 0.03 # [s] - tm_ = TimeMeasure() - for i in range(10): - tm_.tick() - time.sleep(wait_) - tm_.tack() - - maxi = [0.0] - mini = [0.0] - mean = [0.0] - stdev = [0.0] - tm_.getStatistics(maxi, mini, mean, stdev) - print "test_30ms" - print "max interval : ", maxi[0], " [sec]" - print "min interval : ", mini[0], " [sec]" - print "mean interval: ", mean[0], " [sec]" - print "stddev : ", stdev[0], " [sec]" - self.assert_(maxi[0] < (wait_ + 0.030)) - self.assert_(mini[0] > (wait_ - 0.010)) - self.assert_(math.fabs(mean[0] - wait_) < 0.03) - self.assert_(stdev[0] < (wait_ / 5.0)) - return - - def test_1s(self): - wait_ = 1.0 # [s] - tm_ = TimeMeasure() - for i in range(1): - tm_.tick() - time.sleep(wait_) - tm_.tack() - - maxi = [0.0] - mini = [0.0] - mean = [0.0] - stdev = [0.0] - tm_.getStatistics(maxi, mini, mean, stdev) - print "test_1ms" - print "max interval : ", maxi[0], " [sec]" - print "min interval : ", mini[0], " [sec]" - print "mean interval: ", mean[0], " [sec]" - print "stddev : ", stdev[0], " [sec]" - self.assert_(maxi[0] < (wait_ + 0.030)) - self.assert_(mini[0] > (wait_ - 0.010)) - self.assert_(math.fabs(mean[0] - wait_) < 0.03) - self.assert_(stdev[0] < (wait_ / 5.0)) - return - - def test_getsettimeofday(self): - """ - if sys.platform == "win32": - from ctypes import windll, Structure, c_ushort, byref, c_ulong, c_long - class SYSTEMTIME(Structure): - _fields_ = [('wYear', c_ushort), - ('wMonth', c_ushort), - ('wDayOfWeek', c_ushort), - ('wDay', c_ushort), - ('wHour', c_ushort), - ('wMinute', c_ushort), - ('wSecond', c_ushort), - ('wMilliseconds', c_ushort)] - - - class LARGE_INTEGER(Structure): - _fields_ = [('low', c_ulong), - ('high', c_long)] - - - st = SYSTEMTIME(0,0,0,0,0,0,0,0) - windll.kernel32.GetSystemTime(byref(st)) - ft = LARGE_INTEGER(0,0) - windll.kernel32.SystemTimeToFileTime(byref(st),byref(ft)) - ret = windll.kernel32.FileTimeToSystemTime(byref(ft), - byref(st)) - print "settime Yer:", st.wYear, " Month:", st.wMonth, \ - " DayOfWeek:", st.wDayOfWeek, " wDay:", st.wDay, \ - " Hour:", st.wHour, "Minute:", st.wMinute, \ - " Second:", st.wSecond, "Milliseconds:", st.wMilliseconds - """ - return -############### test ################# -if __name__ == '__main__': - unittest.main() diff --git a/OpenRTM_aist/test/test_TimeValue.py b/OpenRTM_aist/test/test_TimeValue.py deleted file mode 100755 index da891819..00000000 --- a/OpenRTM_aist/test/test_TimeValue.py +++ /dev/null @@ -1,73 +0,0 @@ -#!/usr/bin/env python -# -#- Python -#- -# -# \file test_TimeValue.py -# \brief test for TimeValue class -# \date $Date: $ -# \author Shinji Kurihara -# -# Copyright (C) 2007 -# Task-intelligence Research Group, -# Intelligent Systems Research Institute, -# National Institute of -# Advanced Industrial Science and Technology (AIST), Japan -# All rights reserved. -# - -import sys -sys.path.insert(1,"../") - -import unittest -import time - -from TimeValue import * -import OpenRTM_aist - -class TestTimeValue(unittest.TestCase): - - def setUp(self): - self.tm = TimeValue(usec=1000000) - - - def tearDown(self): - OpenRTM_aist.Manager.instance().shutdownManager() - pass - - - def test_set_time(self): - tm = time.time() - ret = self.tm.set_time(tm) - - - def test_toDouble(self): - self.test_set_time() - print self.tm.toDouble() - - def test_sec_usec(self): - tm = TimeValue(usec=1000000) - self.assertEqual(tm.sec(),1) - self.assertEqual(tm.usec(),0) - - def test_normalize(self): - tm = TimeValue(sec=0,usec=10000000) - tm.normalize() - self.assertEqual(tm.sec(),10) - self.assertEqual(tm.usec(),0) - - tm = TimeValue(sec=1,usec=1000000) - tm.normalize() - self.assertEqual(tm.sec(),2) - self.assertEqual(tm.usec(),0) - - tm = TimeValue(sec=1,usec=-100000) - tm.normalize() - self.assertEqual(tm.sec(),0) - self.assertEqual(tm.usec(),900000) - - def test__str__(self): - self.test_set_time() - print self.tm - -############### test ################# -if __name__ == '__main__': - unittest.main() diff --git a/OpenRTM_aist/test/test_Timer.py b/OpenRTM_aist/test/test_Timer.py deleted file mode 100755 index 10659453..00000000 --- a/OpenRTM_aist/test/test_Timer.py +++ /dev/null @@ -1,79 +0,0 @@ -#!/usr/bin/env/python -# -*- Python -*- - -# -# \file Timer.py -# \brief Timer class -# \date $Date: $ -# \author Noriaki Ando -# -# Copyright (C) 2007 -# Task-intelligence Research Group, -# Intelligent Systems Research Institute, -# National Institute of -# Advanced Industrial Science and Technology (AIST), Japan -# All rights reserved. -# - -import sys,time -sys.path.insert(1,"../") - -import unittest -import OpenRTM_aist - -from Timer import * - - -class test: - def func(self): - print "test.hello." - - def invoke(self): - print "test invoke" - -class TestTimer(unittest.TestCase): - def setUp(self): - self.tm = Timer(OpenRTM_aist.TimeValue()) - - def tearDown(self): - self.tm.__del__() - OpenRTM_aist.Manager.instance().shutdownManager() - time.sleep(0.1) - - def test_start_stop(self): - self.tm.start() - self.tm.stop() - - - def test_invoke(self): - self.tm.registerListenerFunc(test().func, OpenRTM_aist.TimeValue()) - self.tm.registerListenerFunc(test().func, OpenRTM_aist.TimeValue()) - self.tm.invoke() - - - def test_registerListener(self): - self.tm.registerListener(test(), OpenRTM_aist.TimeValue()) - self.tm.invoke() - pass - - - def test_registerListenerObj(self): - self.tm.registerListenerObj(test(), test.func, OpenRTM_aist.TimeValue()) - self.tm.invoke() - - - def test_registerListenerFunc(self): - self.tm.registerListenerFunc(test().func, OpenRTM_aist.TimeValue()) - self.tm.invoke() - - - def test_unregisterListener(self): - obj = OpenRTM_aist.ListenerObject(test(),test.func) - self.tm.registerListener(obj, OpenRTM_aist.TimeValue()) - self.assertEqual(self.tm.unregisterListener(obj),True) - self.assertEqual(self.tm.unregisterListener(obj),False) - - -############### test ################# -if __name__ == '__main__': - unittest.main() diff --git a/OpenRTM_aist/test/test_Topic.py b/OpenRTM_aist/test/test_Topic.py deleted file mode 100644 index bde2a599..00000000 --- a/OpenRTM_aist/test/test_Topic.py +++ /dev/null @@ -1,253 +0,0 @@ -#!/usr/bin/env python -# -*- coding: euc-jp -*- - -# -# \file test_Topic.py -# \brief -# \date $Date: $ -# \author Nobuhiko Miyamoto -# - - -import sys -sys.path.insert(1,"../") - -try: - import unittest2 as unittest -except (ImportError): - import unittest - -import time - -#from Manager import * -import OpenRTM_aist -import RTC, RTC__POA -import OpenRTM, OpenRTM__POA - -testcomp1_spec = ["implementation_id", "TestComp1", - "type_name", "TestComp1", - "description", "Test example component", - "version", "1.0", - "vendor", "Nobuhiko Myiyamoto", - "category", "example", - "activity_type", "DataFlowComponent", - "max_instance", "10", - "language", "C++", - "lang_type", "compile", - ""] - -testcomp2_spec = ["implementation_id", "TestComp2", - "type_name", "TestComp2", - "description", "Test example component", - "version", "1.0", - "vendor", "Nobuhiko Myiyamoto", - "category", "example", - "activity_type", "DataFlowComponent", - "max_instance", "10", - "language", "C++", - "lang_type", "compile", - ""] - -class Test_i(OpenRTM__POA.InPortCdr): - def __init__(self): - pass - def put(self, data): - return OpenRTM.PORT_OK - - -class TestComp1(OpenRTM_aist.DataFlowComponentBase): - def __init__(self, manager): - OpenRTM_aist.DataFlowComponentBase.__init__(self, manager) - self._d_out = RTC.TimedLong(RTC.Time(0,0),0) - self._outOut = OpenRTM_aist.OutPort("out", self._d_out) - - self._servicePort_provided = OpenRTM_aist.CorbaPort("service") - self._Service_provided = Test_i() - - - self._d_topic_out = RTC.TimedLong(RTC.Time(0,0),0) - self._topic_outOut = OpenRTM_aist.OutPort("topic_out", self._d_topic_out) - - self._topic_servicePort_provided = OpenRTM_aist.CorbaPort("topic_service") - self._topic_Service_provided = Test_i() - - def onInitialize(self): - self.addOutPort("out",self._outOut) - self._servicePort_provided.registerProvider("service", "TestService", self._Service_provided) - self.addPort(self._servicePort_provided) - - self.addOutPort("topic_out",self._topic_outOut) - self._topic_outOut.appendProperty("publish_topic","test") - - self._topic_servicePort_provided.registerProvider("topic_service", "TestService", self._topic_Service_provided) - self.addPort(self._topic_servicePort_provided) - self._topic_servicePort_provided.appendProperty("publish_topic","test") - - - return RTC.RTC_OK - - - -class TestComp2(OpenRTM_aist.DataFlowComponentBase): - def __init__(self, manager): - OpenRTM_aist.DataFlowComponentBase.__init__(self, manager) - self._d_in = RTC.TimedLong(RTC.Time(0,0),0) - self._inIn = OpenRTM_aist.InPort("in", self._d_in) - - self._servicePort_required = OpenRTM_aist.CorbaPort("service") - self._Service_required = OpenRTM_aist.CorbaConsumer(interfaceType=OpenRTM.InPortCdr) - - - self._d_topic_in = RTC.TimedLong(RTC.Time(0,0),0) - self._topic_inIn = OpenRTM_aist.InPort("topic_in", self._d_topic_in) - - - - self._topic_servicePort_required = OpenRTM_aist.CorbaPort("topic_service") - self._topic_Service_required = OpenRTM_aist.CorbaConsumer(interfaceType=OpenRTM.InPortCdr) - - return - - def onInitialize(self): - self.addInPort("in",self._inIn) - - self._servicePort_required.registerConsumer("service", "TestService", self._Service_required) - self.addPort(self._servicePort_required) - - - self.addInPort("topic_in",self._topic_inIn) - self._topic_inIn.appendProperty("publish_topic","test") - - - self._topic_servicePort_required.registerConsumer("topic_service", "TestService", self._topic_Service_required) - self.addPort(self._topic_servicePort_required) - self._topic_servicePort_required.appendProperty("publish_topic","test") - - return RTC.RTC_OK - - - - -def TestComp1Init(manager): - profile = OpenRTM_aist.Properties(defaults_str=testcomp1_spec) - manager.registerFactory(profile, - TestComp1, - OpenRTM_aist.Delete) - - - -def TestComp2Init(manager): - profile = OpenRTM_aist.Properties(defaults_str=testcomp2_spec) - manager.registerFactory(profile, - TestComp2, - OpenRTM_aist.Delete) - - -def MyModuleInit(manager): - TestComp1Init(manager) - TestComp2Init(manager) - com = manager.createComponent("TestComp1") - com = manager.createComponent("TestComp2") - - - - - -class test_Topic(unittest.TestCase): - - def setUp(self): - #sys.argv.extend(['-o','port.outport.topic_out.publish_topic:test2']) - #sys.argv.extend(['-o','port.inport.topic_in.publish_topic:test2']) - #sys.argv.extend(['-o','port.corbaport.topic_service.publish_topic:test2']) - self.manager = OpenRTM_aist.Manager.init(sys.argv) - - self.manager.setModuleInitProc(MyModuleInit) - self.manager.activateManager() - - self.comps = [] - self.comps.append(self.manager.getComponent("TestComp10")) - self.comps.append(self.manager.getComponent("TestComp20")) - self.comp1 = self.comps[0].getObjRef() - self.comp2 = self.comps[1].getObjRef() - - - - def tearDown(self): - for comp in self.comps: - self.manager.unregisterComponent(comp) - comp_id = comp.getProperties() - factory = self.manager._factory.find(comp_id) - factory.destroy(comp) - self.manager.shutdownNaming() - time.sleep(0.1) - - def test_port(self): - inport = OpenRTM_aist.get_port_by_name(self.comp2, "TestComp20.in") - outport = OpenRTM_aist.get_port_by_name(self.comp1, "TestComp10.out") - - self.manager.connectDataPorts(inport, [outport]) - ans = OpenRTM_aist.already_connected(inport, outport) - self.assertTrue(ans) - - - service_required = OpenRTM_aist.get_port_by_name(self.comp2, "TestComp20.service") - service_provided = OpenRTM_aist.get_port_by_name(self.comp1, "TestComp10.service") - self.manager.connectServicePorts(service_required, [service_provided]) - ans = OpenRTM_aist.already_connected(service_required, service_provided) - self.assertTrue(ans) - - ports = self.manager.getPortsOnNameServers("dataports.port_cxt/test.topic_cxt","inport") - name = ports[0].get_port_profile().name - self.assertEqual(name, "TestComp20.topic_in") - - orb = self.manager.getORB() - names = "localhost" - cns = OpenRTM_aist.CorbaNaming(orb,names) - bl = cns.listByKind("dataports.port_cxt/test.topic_cxt","inport") - name = bl[0].binding_name[0].id - self.assertEqual(name, "TestComp20.topic_in") - - - self._d_out = RTC.TimedOctetSeq(RTC.Time(0,0),[]) - self._outOut = OpenRTM_aist.OutPort("out", self._d_out) - prop = OpenRTM_aist.Properties() - self._outOut.init(prop) - - naming = self.manager.getNaming() - naming.bindPortObject("test.port",self._outOut) - - port = cns.resolveStr("test.port") - self.assertTrue(port is not None) - - naming = OpenRTM_aist.NamingOnCorba(orb, "localhost") - naming.bindPortObject("test2.port",self._outOut) - - port = cns.resolveStr("test2.port") - self.assertTrue(port is not None) - - def test_Topic(self): - - inport = OpenRTM_aist.get_port_by_name(self.comp2, "TestComp20.topic_in") - outport = OpenRTM_aist.get_port_by_name(self.comp1, "TestComp10.topic_out") - ans = OpenRTM_aist.already_connected(inport, outport) - self.assertTrue(ans) - - - - - provided = OpenRTM_aist.get_port_by_name(self.comp1, "TestComp10.topic_service") - required = OpenRTM_aist.get_port_by_name(self.comp2, "TestComp20.topic_service") - ans = OpenRTM_aist.already_connected(provided, required) - self.assertTrue(ans) - - - - - - - - - -############### test ################# -if __name__ == '__main__': - unittest.main() diff --git a/OpenRTM_aist/test/test_string_to_component.py b/OpenRTM_aist/test/test_string_to_component.py deleted file mode 100644 index bd5d471e..00000000 --- a/OpenRTM_aist/test/test_string_to_component.py +++ /dev/null @@ -1,161 +0,0 @@ -#!/usr/bin/env python -# -*- coding: euc-jp -*- - -# -# \file test_string_to_component.py -# \brief -# \date $Date: $ -# \author Nobuhiko Miyamoto -# - - -import sys -sys.path.insert(1,"../") - -try: - import unittest2 as unittest -except (ImportError): - import unittest - -import time - -#from Manager import * -import OpenRTM_aist -import RTC, RTC__POA -import multiprocessing - -testcomp1_spec = ["implementation_id", "TestComp1", - "type_name", "TestComp1", - "description", "Test example component", - "version", "1.0", - "vendor", "Nobuhiko Myiyamoto", - "category", "example", - "activity_type", "DataFlowComponent", - "max_instance", "10", - "language", "C++", - "lang_type", "compile", - "conf.default.test1", "0", - ""] - -testcomp2_spec = ["implementation_id", "TestComp2", - "type_name", "TestComp2", - "description", "Test example component", - "version", "1.0", - "vendor", "Nobuhiko Myiyamoto", - "category", "example", - "activity_type", "DataFlowComponent", - "max_instance", "10", - "language", "C++", - "lang_type", "compile", - ""] - - - - - - - - -def TestComp1Init(manager): - profile = OpenRTM_aist.Properties(defaults_str=testcomp1_spec) - manager.registerFactory(profile, - OpenRTM_aist.DataFlowComponentBase, - OpenRTM_aist.Delete) - - - -def TestComp2Init(manager): - profile = OpenRTM_aist.Properties(defaults_str=testcomp2_spec) - manager.registerFactory(profile, - OpenRTM_aist.DataFlowComponentBase, - OpenRTM_aist.Delete) - - -def TestComp1ModuleInit(manager): - TestComp1Init(manager) - com = manager.createComponent("TestComp1") - -def TestComp2ModuleInit(manager): - TestComp2Init(manager) - com = manager.createComponent("TestComp2") - - -def runTestComp2(q): - - argv = [""] - argv.extend(['-d']) - argv.extend(['-o','naming.type:corba,manager']) - argv.extend(['-o','naming.formats:test.host_cxt/%n.rtc']) - - - manager = OpenRTM_aist.Manager.init(argv) - manager.setModuleInitProc(TestComp2ModuleInit) - manager.activateManager() - - - q.get() - - comps = manager.getComponents()[:] - for comp in comps: - manager.unregisterComponent(comp) - comp_id = comp.getProperties() - factory = manager._factory.find(comp_id) - factory.destroy(comp) - manager.shutdownNaming() - time.sleep(0.1) - - -class Test_string_to_component(unittest.TestCase): - - def setUp(self): - self.queue = multiprocessing.Queue() - self.outport_process = multiprocessing.Process(target=runTestComp2, args=(self.queue,)) - self.outport_process.start() - - time.sleep(1) - sys.argv.extend(['-o','naming.type:corba,manager']) - sys.argv.extend(['-o','naming.formats:test.host_cxt/%n.rtc']) - self.manager = OpenRTM_aist.Manager.init(sys.argv) - self.manager.setModuleInitProc(TestComp1ModuleInit) - self.manager.activateManager() - - - def tearDown(self): - - self.queue.put("") - comps = self.manager.getComponents()[:] - for comp in comps: - self.manager.unregisterComponent(comp) - comp_id = comp.getProperties() - factory = self.manager._factory.find(comp_id) - factory.destroy(comp) - self.manager.shutdownNaming() - time.sleep(0.1) - - def test_getComponent(self): - #mgr_sev = self.manager._mgrservant.getObjRef() - #print mgr_sev.get_components_by_name("example/TestComp10") - rtcs = self.manager.getNaming().string_to_component("rtcloc://localhost:2810/example/TestComp20") - name = rtcs[0].get_component_profile().instance_name - self.assertEqual(name,"TestComp20") - rtcs = self.manager.getNaming().string_to_component("rtcloc://*/example/TestComp20") - name = rtcs[0].get_component_profile().instance_name - self.assertEqual(name,"TestComp20") - rtcs = self.manager.getNaming().string_to_component("rtcloc://*/*/TestComp20") - name = rtcs[0].get_component_profile().instance_name - self.assertEqual(name,"TestComp20") - #print rtcs - rtcs = self.manager.getNaming().string_to_component("rtcname://localhost/test.host_cxt/TestComp20") - name = rtcs[0].get_component_profile().instance_name - self.assertEqual(name,"TestComp20") - rtcs = self.manager.getNaming().string_to_component("rtcname://*/test.host_cxt/TestComp20") - name = rtcs[0].get_component_profile().instance_name - self.assertEqual(name,"TestComp20") - rtcs = self.manager.getNaming().string_to_component("rtcname://*/*/TestComp20") - name = rtcs[0].get_component_profile().instance_name - self.assertEqual(name,"TestComp20") - - -############### test ################# -if __name__ == '__main__': - unittest.main() diff --git a/OpenRTM_aist/test/uuid.py b/OpenRTM_aist/test/uuid.py deleted file mode 100755 index 15582b64..00000000 --- a/OpenRTM_aist/test/uuid.py +++ /dev/null @@ -1,475 +0,0 @@ -r"""UUID objects (universally unique identifiers) according to RFC 4122. - -This module provides immutable UUID objects (class UUID) and the functions -uuid1(), uuid3(), uuid4(), uuid5() for generating version 1, 3, 4, and 5 -UUIDs as specified in RFC 4122. - -If all you want is a unique ID, you should probably call uuid1() or uuid4(). -Note that uuid1() may compromise privacy since it creates a UUID containing -the computer's network address. uuid4() creates a random UUID. - -Typical usage: - - >>> import uuid - - # make a UUID based on the host ID and current time - >>> uuid.uuid1() - UUID('a8098c1a-f86e-11da-bd1a-00112444be1e') - - # make a UUID using an MD5 hash of a namespace UUID and a name - >>> uuid.uuid3(uuid.NAMESPACE_DNS, 'python.org') - UUID('6fa459ea-ee8a-3ca4-894e-db77e160355e') - - # make a random UUID - >>> uuid.uuid4() - UUID('16fd2706-8baf-433b-82eb-8c7fada847da') - - # make a UUID using a SHA-1 hash of a namespace UUID and a name - >>> uuid.uuid5(uuid.NAMESPACE_DNS, 'python.org') - UUID('886313e1-3b8a-5372-9b90-0c9aee199e5d') - - # make a UUID from a string of hex digits (braces and hyphens ignored) - >>> x = uuid.UUID('{00010203-0405-0607-0809-0a0b0c0d0e0f}') - - # convert a UUID to a string of hex digits in standard form - >>> str(x) - '00010203-0405-0607-0809-0a0b0c0d0e0f' - - # get the raw 16 bytes of the UUID - >>> x.bytes - '\x00\x01\x02\x03\x04\x05\x06\x07\x08\t\n\x0b\x0c\r\x0e\x0f' - - # make a UUID from a 16-byte string - >>> uuid.UUID(bytes=x.bytes) - UUID('00010203-0405-0607-0809-0a0b0c0d0e0f') - -This module works with Python 2.3 or higher.""" - -__author__ = 'Ka-Ping Yee ' -__date__ = '$Date: 2006/06/12 23:15:40 $'.split()[1].replace('/', '-') -__version__ = '$Revision: 1.30 $'.split()[1] - -RESERVED_NCS, RFC_4122, RESERVED_MICROSOFT, RESERVED_FUTURE = [ - 'reserved for NCS compatibility', 'specified in RFC 4122', - 'reserved for Microsoft compatibility', 'reserved for future definition'] - -class UUID(object): - """Instances of the UUID class represent UUIDs as specified in RFC 4122. - UUID objects are immutable, hashable, and usable as dictionary keys. - Converting a UUID to a string with str() yields something in the form - '12345678-1234-1234-1234-123456789abc'. The UUID constructor accepts - four possible forms: a similar string of hexadecimal digits, or a - string of 16 raw bytes as an argument named 'bytes', or a tuple of - six integer fields (with 32-bit, 16-bit, 16-bit, 8-bit, 8-bit, and - 48-bit values respectively) as an argument named 'fields', or a single - 128-bit integer as an argument named 'int'. - - UUIDs have these read-only attributes: - - bytes the UUID as a 16-byte string - - fields a tuple of the six integer fields of the UUID, - which are also available as six individual attributes - and two derived attributes: - - time_low the first 32 bits of the UUID - time_mid the next 16 bits of the UUID - time_hi_version the next 16 bits of the UUID - clock_seq_hi_variant the next 8 bits of the UUID - clock_seq_low the next 8 bits of the UUID - node the last 48 bits of the UUID - - time the 60-bit timestamp - clock_seq the 14-bit sequence number - - hex the UUID as a 32-character hexadecimal string - - int the UUID as a 128-bit integer - - urn the UUID as a URN as specified in RFC 4122 - - variant the UUID variant (one of the constants RESERVED_NCS, - RFC_4122, RESERVED_MICROSOFT, or RESERVED_FUTURE) - - version the UUID version number (1 through 5, meaningful only - when the variant is RFC_4122) - """ - - def __init__(self, hex=None, bytes=None, fields=None, int=None, - version=None): - r"""Create a UUID from either a string of 32 hexadecimal digits, - a string of 16 bytes as the 'bytes' argument, a tuple of six - integers (32-bit time_low, 16-bit time_mid, 16-bit time_hi_version, - 8-bit clock_seq_hi_variant, 8-bit clock_seq_low, 48-bit node) as - the 'fields' argument, or a single 128-bit integer as the 'int' - argument. When a string of hex digits is given, curly braces, - hyphens, and a URN prefix are all optional. For example, these - expressions all yield the same UUID: - - UUID('{12345678-1234-5678-1234-567812345678}') - UUID('12345678123456781234567812345678') - UUID('urn:uuid:12345678-1234-5678-1234-567812345678') - UUID(bytes='\x12\x34\x56\x78'*4) - UUID(fields=(0x12345678, 0x1234, 0x5678, 0x12, 0x34, 0x567812345678)) - UUID(int=0x12345678123456781234567812345678) - - Exactly one of 'hex', 'bytes', 'fields', or 'int' must be given. - The 'version' argument is optional; if given, the resulting UUID - will have its variant and version number set according to RFC 4122, - overriding bits in the given 'hex', 'bytes', 'fields', or 'int'. - """ - - if [hex, bytes, fields, int].count(None) != 3: - raise TypeError('need just one of hex, bytes, fields, or int') - if hex is not None: - hex = hex.replace('urn:', '').replace('uuid:', '') - hex = hex.strip('{}').replace('-', '') - if len(hex) != 32: - raise ValueError('badly formed hexadecimal UUID string') - int = long(hex, 16) - if bytes is not None: - if len(bytes) != 16: - raise ValueError('bytes is not a 16-char string') - int = long(('%02x'*16) % tuple(map(ord, bytes)), 16) - if fields is not None: - if len(fields) != 6: - raise ValueError('fields is not a 6-tuple') - (time_low, time_mid, time_hi_version, - clock_seq_hi_variant, clock_seq_low, node) = fields - if not 0 <= time_low < 1<<32L: - raise ValueError('field 1 out of range (need a 32-bit value)') - if not 0 <= time_mid < 1<<16L: - raise ValueError('field 2 out of range (need a 16-bit value)') - if not 0 <= time_hi_version < 1<<16L: - raise ValueError('field 3 out of range (need a 16-bit value)') - if not 0 <= clock_seq_hi_variant < 1<<8L: - raise ValueError('field 4 out of range (need an 8-bit value)') - if not 0 <= clock_seq_low < 1<<8L: - raise ValueError('field 5 out of range (need an 8-bit value)') - if not 0 <= node < 1<<48L: - raise ValueError('field 6 out of range (need a 48-bit value)') - clock_seq = (clock_seq_hi_variant << 8L) | clock_seq_low - int = ((time_low << 96L) | (time_mid << 80L) | - (time_hi_version << 64L) | (clock_seq << 48L) | node) - if int is not None: - if not 0 <= int < 1<<128L: - raise ValueError('int is out of range (need a 128-bit value)') - if version is not None: - if not 1 <= version <= 5: - raise ValueError('illegal version number') - # Set the variant to RFC 4122. - int &= ~(0xc000 << 48L) - int |= 0x8000 << 48L - # Set the version number. - int &= ~(0xf000 << 64L) - int |= version << 76L - self.__dict__['int'] = int - - def __cmp__(self, other): - if isinstance(other, UUID): - return cmp(self.int, other.int) - return NotImplemented - - def __hash__(self): - return hash(self.int) - - def __int__(self): - return self.int - - def __repr__(self): - return 'UUID(%r)' % str(self) - - def __setattr__(self, name, value): - raise TypeError('UUID objects are immutable') - - def __str__(self): - hex = '%032x' % self.int - return '%s-%s-%s-%s-%s' % ( - hex[:8], hex[8:12], hex[12:16], hex[16:20], hex[20:]) - - def get_bytes(self): - bytes = '' - for shift in range(0, 128, 8): - bytes = chr((self.int >> shift) & 0xff) + bytes - return bytes - - bytes = property(get_bytes) - - def get_fields(self): - return (self.time_low, self.time_mid, self.time_hi_version, - self.clock_seq_hi_variant, self.clock_seq_low, self.node) - - fields = property(get_fields) - - def get_time_low(self): - return self.int >> 96L - - time_low = property(get_time_low) - - def get_time_mid(self): - return (self.int >> 80L) & 0xffff - - time_mid = property(get_time_mid) - - def get_time_hi_version(self): - return (self.int >> 64L) & 0xffff - - time_hi_version = property(get_time_hi_version) - - def get_clock_seq_hi_variant(self): - return (self.int >> 56L) & 0xff - - clock_seq_hi_variant = property(get_clock_seq_hi_variant) - - def get_clock_seq_low(self): - return (self.int >> 48L) & 0xff - - clock_seq_low = property(get_clock_seq_low) - - def get_time(self): - return (((self.time_hi_version & 0x0fffL) << 48L) | - (self.time_mid << 32L) | self.time_low) - - time = property(get_time) - - def get_clock_seq(self): - return (((self.clock_seq_hi_variant & 0x3fL) << 8L) | - self.clock_seq_low) - - clock_seq = property(get_clock_seq) - - def get_node(self): - return self.int & 0xffffffffffff - - node = property(get_node) - - def get_hex(self): - return '%032x' % self.int - - hex = property(get_hex) - - def get_urn(self): - return 'urn:uuid:' + str(self) - - urn = property(get_urn) - - def get_variant(self): - if not self.int & (0x8000 << 48L): - return RESERVED_NCS - elif not self.int & (0x4000 << 48L): - return RFC_4122 - elif not self.int & (0x2000 << 48L): - return RESERVED_MICROSOFT - else: - return RESERVED_FUTURE - - variant = property(get_variant) - - def get_version(self): - # The version bits are only meaningful for RFC 4122 UUIDs. - if self.variant == RFC_4122: - return int((self.int >> 76L) & 0xf) - - version = property(get_version) - -def _ifconfig_getnode(): - """Get the hardware address on Unix by running ifconfig.""" - import os - dir = '/sbin/' - pipe = os.popen(os.path.join(dir, 'ifconfig')) - - for line in pipe: - words = line.lower().split() - for i in range(len(words)): - if words[i] in ['hwaddr', 'ether']: - return int(words[i + 1].replace(':', ''), 16) - -def _ipconfig_getnode(): - """Get the hardware address on Windows by running ipconfig.exe.""" - import os, re - dirs = ['', r'c:\windows\system32', r'c:\winnt\system32'] - try: - import ctypes - buffer = ctypes.create_string_buffer(300) - ctypes.windll.kernel32.GetSystemDirectoryA(buffer, 300) - dirs.insert(0, buffer.value.decode('mbcs')) - except: - pass - for dir in dirs: - try: - pipe = os.popen(os.path.join(dir, 'ipconfig') + ' /all') - except IOError: - continue - for line in pipe: - value = line.split(':')[-1].strip().lower() - if re.match('([0-9a-f][0-9a-f]-){5}[0-9a-f][0-9a-f]', value): - return int(value.replace('-', ''), 16) - -def _netbios_getnode(): - """Get the hardware address on Windows using NetBIOS calls. - See http://support.microsoft.com/kb/118623 for details.""" - import win32wnet, netbios - ncb = netbios.NCB() - ncb.Command = netbios.NCBENUM - ncb.Buffer = adapters = netbios.LANA_ENUM() - adapters._pack() - if win32wnet.Netbios(ncb) != 0: - return - adapters._unpack() - for i in range(adapters.length): - ncb.Reset() - ncb.Command = netbios.NCBRESET - ncb.Lana_num = ord(adapters.lana[i]) - if win32wnet.Netbios(ncb) != 0: - continue - ncb.Reset() - ncb.Command = netbios.NCBASTAT - ncb.Lana_num = ord(adapters.lana[i]) - ncb.Callname = '*'.ljust(16) - ncb.Buffer = status = netbios.ADAPTER_STATUS() - if win32wnet.Netbios(ncb) != 0: - continue - status._unpack() - bytes = map(ord, status.adapter_address) - return ((bytes[0]<<40L) + (bytes[1]<<32L) + (bytes[2]<<24L) + - (bytes[3]<<16L) + (bytes[4]<<8L) + bytes[5]) - -# Thanks to Thomas Heller for ctypes and for his help with its use here. - -# If ctypes is available, use it to find system routines for UUID generation. -_uuid_generate_random = _uuid_generate_time = _UuidCreate = None -try: - import ctypes, ctypes.util - _buffer = ctypes.create_string_buffer(16) - - # The uuid_generate_* routines are provided by libuuid on at least - # Linux and FreeBSD, and provided by libc on Mac OS X. - for libname in ['uuid', 'c']: - try: - lib = ctypes.CDLL(ctypes.util.find_library(libname)) - except: - continue - if hasattr(lib, 'uuid_generate_random'): - _uuid_generate_random = lib.uuid_generate_random - if hasattr(lib, 'uuid_generate_time'): - _uuid_generate_time = lib.uuid_generate_time - - # On Windows prior to 2000, UuidCreate gives a UUID containing the - # hardware address. On Windows 2000 and later, UuidCreate makes a - # random UUID and UuidCreateSequential gives a UUID containing the - # hardware address. These routines are provided by the RPC runtime. - try: - lib = ctypes.windll.rpcrt4 - except: - lib = None - _UuidCreate = getattr(lib, 'UuidCreateSequential', - getattr(lib, 'UuidCreate', None)) -except: - pass - -def _unixdll_getnode(): - """Get the hardware address on Unix using ctypes.""" - _uuid_generate_time(_buffer) - return UUID(bytes=_buffer.raw).node - -def _windll_getnode(): - """Get the hardware address on Windows using ctypes.""" - if _UuidCreate(_buffer) == 0: - return UUID(bytes=_buffer.raw).node - -def _random_getnode(): - """Get a random node ID, with eighth bit set as suggested by RFC 4122.""" - import random - return random.randrange(0, 1<<48L) | 0x010000000000L - -_node = None - -def getnode(): - """Get the hardware address as a 48-bit integer. The first time this - runs, it may launch a separate program, which could be quite slow. If - all attempts to obtain the hardware address fail, we choose a random - 48-bit number with its eighth bit set to 1 as recommended in RFC 4122.""" - - global _node - if _node is not None: - return _node - - import sys - if sys.platform == 'win32': - getters = [_windll_getnode, _netbios_getnode, _ipconfig_getnode] - else: - getters = [_unixdll_getnode, _ifconfig_getnode] - - for getter in getters + [_random_getnode]: - try: - _node = getter() - except: - continue - if _node is not None: - return _node - -def uuid1(node=None, clock_seq=None): - """Generate a UUID from a host ID, sequence number, and the current time. - If 'node' is not given, getnode() is used to obtain the hardware - address. If 'clock_seq' is given, it is used as the sequence number; - otherwise a random 14-bit sequence number is chosen.""" - - # When the system provides a version-1 UUID generator, use it (but don't - # use UuidCreate here because its UUIDs don't conform to RFC 4122). - if _uuid_generate_time and node is clock_seq is None: - _uuid_generate_time(_buffer) - return UUID(bytes=_buffer.raw) - - import time - nanoseconds = int(time.time() * 1e9) - # 0x01b21dd213814000 is the number of 100-ns intervals between the - # UUID epoch 1582-10-15 00:00:00 and the Unix epoch 1970-01-01 00:00:00. - timestamp = int(nanoseconds/100) + 0x01b21dd213814000L - if clock_seq is None: - import random - clock_seq = random.randrange(1<<14L) # instead of stable storage - time_low = timestamp & 0xffffffffL - time_mid = (timestamp >> 32L) & 0xffffL - time_hi_version = (timestamp >> 48L) & 0x0fffL - clock_seq_low = clock_seq & 0xffL - clock_seq_hi_variant = (clock_seq >> 8L) & 0x3fL - if node is None: - node = getnode() - return UUID(fields=(time_low, time_mid, time_hi_version, - clock_seq_hi_variant, clock_seq_low, node), version=1) - -def uuid3(namespace, name): - """Generate a UUID from the MD5 hash of a namespace UUID and a name.""" - import md5 - hash = md5.md5(namespace.bytes + name).digest() - return UUID(bytes=hash[:16], version=3) - -def uuid4(): - """Generate a random UUID.""" - - # When the system provides a version-4 UUID generator, use it. - if _uuid_generate_random: - _uuid_generate_random(_buffer) - return UUID(bytes=_buffer.raw) - - # Otherwise, get randomness from urandom or the 'random' module. - try: - import os - return UUID(bytes=os.urandom(16), version=4) - except: - import random - bytes = [chr(random.randrange(256)) for i in range(16)] - return UUID(bytes=bytes, version=4) - -def uuid5(namespace, name): - """Generate a UUID from the SHA-1 hash of a namespace UUID and a name.""" - import sha - hash = sha.sha(namespace.bytes + name).digest() - return UUID(bytes=hash[:16], version=5) - -# The following standard UUIDs are for use with uuid3() or uuid5(). - -NAMESPACE_DNS = UUID('6ba7b810-9dad-11d1-80b4-00c04fd430c8') -NAMESPACE_URL = UUID('6ba7b811-9dad-11d1-80b4-00c04fd430c8') -NAMESPACE_OID = UUID('6ba7b812-9dad-11d1-80b4-00c04fd430c8') -NAMESPACE_X500 = UUID('6ba7b814-9dad-11d1-80b4-00c04fd430c8') diff --git a/OpenRTM_aist/utils/__init__.py b/OpenRTM_aist/utils/__init__.py index 932b7982..270be2a2 100644 --- a/OpenRTM_aist/utils/__init__.py +++ b/OpenRTM_aist/utils/__init__.py @@ -1 +1 @@ -# Empty file +# Empty file diff --git a/OpenRTM_aist/utils/rtc-template/README_gen.py b/OpenRTM_aist/utils/rtc-template/README_gen.py index d9b97be5..66f2067c 100644 --- a/OpenRTM_aist/utils/rtc-template/README_gen.py +++ b/OpenRTM_aist/utils/rtc-template/README_gen.py @@ -1,18 +1,18 @@ -#!/usr/bin/env python +#!/usr/bin/env python # -*- python -*- # # @file README_src.py # @brief rtc-template RTComponent's README file generator class # @date $Date: 2007/01/11 07:47:03 $ # @author Noriaki Ando -# +# # Copyright (C) 2004-2005 # Task-intelligence Research Group, # Intelligent Systems Research Institute, # National Institute of # Advanced Industrial Science and Technology (AIST), Japan # All rights reserved. -# +# # $Id: README_gen.py 775 2008-07-28 16:14:45Z n-ando $ # @@ -25,7 +25,7 @@ # # OpenRTM-aist-[version] # -# Date: [date] +# Date: [date] # # This file is generated by rtc-template with the following argments. # @@ -59,12 +59,12 @@ # Service definition #====================================================================== # -# +#
    #====================================================================== # Configuration definition #====================================================================== # -# +#
    """ module = """Basic Information: @@ -82,8 +82,8 @@ MAX Inst.: [basicInfo.maxInstances] - Lang: - Lang Type: + Lang: + Lang Type: """ inport = """InPorts: @@ -105,7 +105,7 @@ SubscriptionType: [inport.subscriptionType] - MaxOut: + MaxOut: [endif] [endfor] @@ -130,7 +130,7 @@ SubscriptionType: [outport.subscriptionType] - MaxOut: + MaxOut: [endif] [endfor] @@ -160,7 +160,7 @@ IDLfile: [svcif.idlFile] FilePath: [svcif.path] - + [endfor] [endfor] @@ -186,60 +186,59 @@ [endfor]""" + class README_gen(gen_base.gen_base): - def __init__(self, data): - self.data = data.copy() - self.data['fname'] = "README." + self.data['basicInfo']['name'] - self.data['version'] = os.popen("rtm-config --version", "r").read() - self.data['date'] = time.asctime() - - self.tags = {} - self.tags["module"] = module - self.tags["actions"] = self.CreateActions() - self.tags["inport"] = inport - self.tags["outport"] = outport - self.tags["service"] = service - self.tags["configuration"] = configuration - self.gen_tags(self.tags) - return - - def CreateActions(self): - actnames = [ - "onInitialize", - "onFinalize", - "onActivated", - "onDeactivated", - "onAborting", - "onError", - "onReset", - "onExecute", - "onStateUpdate", - "onShutdown", - "onStartup", - "onRateChanged", - ] - acttext = """ %s: + def __init__(self, data): + self.data = data.copy() + self.data['fname'] = "README." + self.data['basicInfo']['name'] + self.data['version'] = os.popen("rtm-config --version", "r").read() + self.data['date'] = time.asctime() + + self.tags = {} + self.tags["module"] = module + self.tags["actions"] = self.CreateActions() + self.tags["inport"] = inport + self.tags["outport"] = outport + self.tags["service"] = service + self.tags["configuration"] = configuration + self.gen_tags(self.tags) + return + + def CreateActions(self): + actnames = [ + "onInitialize", + "onFinalize", + "onActivated", + "onDeactivated", + "onAborting", + "onError", + "onReset", + "onExecute", + "onStateUpdate", + "onShutdown", + "onStartup", + "onRateChanged", + ] + acttext = """ %s: Description: [actions.%s.rtcDoc::doc.description] - + PreCondition: [actions.%s.rtcDoc::doc.preCondition] - + PostCondition: [actions.%s.rtcDoc::doc.postCondition] """ - actions = """Actions: + actions = """Actions: """ - for a in actnames: - actions += acttext % (a,a,a,a) - return actions - - def print_readme(self): - self.gen(self.data["fname"], readme, self.data, self.tags) - - def print_all(self): - self.print_readme() + for a in actnames: + actions += acttext % (a, a, a, a) + return actions + def print_readme(self): + self.gen(self.data["fname"], readme, self.data, self.tags) + def print_all(self): + self.print_readme() diff --git a/OpenRTM_aist/utils/rtc-template/__init__.py b/OpenRTM_aist/utils/rtc-template/__init__.py index 932b7982..270be2a2 100644 --- a/OpenRTM_aist/utils/rtc-template/__init__.py +++ b/OpenRTM_aist/utils/rtc-template/__init__.py @@ -1 +1 @@ -# Empty file +# Empty file diff --git a/OpenRTM_aist/utils/rtc-template/gen_base.py b/OpenRTM_aist/utils/rtc-template/gen_base.py index 873c7530..ac3dccea 100644 --- a/OpenRTM_aist/utils/rtc-template/gen_base.py +++ b/OpenRTM_aist/utils/rtc-template/gen_base.py @@ -1,4 +1,4 @@ -#!/usr/bin/env python +#!/usr/bin/env python # -*- python -*- # -*- condig shift_jis -*- # @@ -6,97 +6,98 @@ # @brief rtc-template source code generator base class # @date $Date: 2007/01/11 07:43:16 $ # @author Noriaki Ando -# +# # Copyright (C) 2005 # Task-intelligence Research Group, # Intelligent Systems Research Institute, # National Institute of # Advanced Industrial Science and Technology (AIST), Japan # All rights reserved. -# +# # $Id: gen_base.py 775 2008-07-28 16:14:45Z n-ando $ -# +# import os import re import time import yat import StringIO + + class gen_base: - - def check_overwrite(self, fname, wmode="w"): - """ - Check file exist or not. - """ - msg = " already exists. Overwrite or merge? (y/n/m)" - if (os.access(fname, os.F_OK)): - ans = raw_input("\"" + fname + "\"" + msg) - if (ans == "y" or ans == "Y"): - return file(fname, wmode), None - elif (ans == "m" or ans == "M"): - f = file(fname, "r") - lines = [] - for l in f.readlines(): - lines.append(l.rstrip()) - f.close() - oldfname = fname + ".old." + time.strftime("%y%m%d%H%M%S") - os.rename(fname, oldfname) - return file(fname, wmode), lines - else: - return None, None - else: - return file(fname, wmode), None - return - - def replace_tags(self, lines, data): - in_tag = False - tag_name = "" - ret_lines = "" - - for l in lines: - m = re.search("", l) - if m: - in_tag = True - tag_name = m.group(1) - ret_lines += l + "\n" - continue - m = re.search("", l) - if m: - in_tag = False - if tag_name in data: - ret_lines += data[tag_name] + "\n" - ret_lines += l + "\n" - tag_name = "" - continue + def check_overwrite(self, fname, wmode="w"): + """ + Check file exist or not. + """ + msg = " already exists. Overwrite or merge? (y/n/m)" + if (os.access(fname, os.F_OK)): + ans = raw_input("\"" + fname + "\"" + msg) + if (ans == "y" or ans == "Y"): + return file(fname, wmode), None + elif (ans == "m" or ans == "M"): + f = file(fname, "r") + lines = [] + for l in f.readlines(): + lines.append(l.rstrip()) + f.close() + oldfname = fname + ".old." + time.strftime("%y%m%d%H%M%S") + os.rename(fname, oldfname) + return file(fname, wmode), lines + else: + return None, None + else: + return file(fname, wmode), None + return + + def replace_tags(self, lines, data): + in_tag = False + tag_name = "" + ret_lines = "" + + for l in lines: + m = re.search("", l) + if m: + in_tag = True + tag_name = m.group(1) + ret_lines += l + "\n" + continue - if in_tag != True: - ret_lines += l + "\n" + m = re.search("", l) + if m: + in_tag = False + if tag_name in data: + ret_lines += data[tag_name] + "\n" + ret_lines += l + "\n" + tag_name = "" + continue - return ret_lines + if in_tag != True: + ret_lines += l + "\n" + return ret_lines - def gen_tags(self, tags): - for key in tags.keys(): - t = yat.Template(tags[key]) - text=t.generate(self.data) - tags[key] = text - return + def gen_tags(self, tags): + for key in tags.keys(): + t = yat.Template(tags[key]) + text = t.generate(self.data) + tags[key] = text + return - def gen(self, fname, temp_txt, data, tags): - f, lines = self.check_overwrite(fname) - if not f: # overwrite: No - return + def gen(self, fname, temp_txt, data, tags): + f, lines = self.check_overwrite(fname) + if not f: # overwrite: No + return - if not lines: # overwrite: Yes - t = yat.Template(temp_txt) - taged_txt = t.generate(self.data) - else: # overwrite: Merge mode - taged_txt = lines + if not lines: # overwrite: Yes + t = yat.Template(temp_txt) + taged_txt = t.generate(self.data) + else: # overwrite: Merge mode + taged_txt = lines - # replace tags - gen_txt = self.replace_tags(taged_txt.split("\n"), tags) - f.write(gen_txt) - f.close() - print(" File \"" + fname + "\"" " was generated.") - return + # replace tags + gen_txt = self.replace_tags(taged_txt.split("\n"), tags) + f.write(gen_txt) + f.close() + print(" File \"" + fname + "\"" " was generated.") + return diff --git a/OpenRTM_aist/utils/rtc-template/profile_gen.py b/OpenRTM_aist/utils/rtc-template/profile_gen.py index 0fb53243..3a1e8b7d 100644 --- a/OpenRTM_aist/utils/rtc-template/profile_gen.py +++ b/OpenRTM_aist/utils/rtc-template/profile_gen.py @@ -1,24 +1,24 @@ -#!/usr/bin/env python +#!/usr/bin/env python # -*- python -*- # # @file profile_gen.py # @brief RTC profile generator # @date $Date$ # @author Noriaki Ando -# +# # Copyright (C) 2008 # Task-intelligence Research Group, # Intelligent Systems Research Institute, # National Institute of # Advanced Industrial Science and Technology (AIST), Japan # All rights reserved. -# +# # $Id$ # import gen_base -profile_yaml = """rtcProfile: +profile_yaml = """rtcProfile: version: "1.0" id: [id] @@ -86,19 +86,19 @@ reference: [basicInfo.rtcDoc::doc.reference] - "rtcExt::versionUpLog": + "rtcExt::versionUpLog": [for log in basicInfo.rtcExt::versionUpLog] - [log] [endfor] - language: + language: [if-any language.java] - java: - library: + java: + library: [for javalib in language.java.library] - [javalib] [endfor] [endif] - actions: + actions: onInitialize: implemented: [actions.onInitialize.implemented] @@ -219,7 +219,7 @@ preCondition: [actions.onStateUpdate.rtcDoc::doc.preCondition] - dataPorts: + dataPorts: [for dport in dataPorts] - portType: [dport.portType] @@ -256,7 +256,7 @@ "rtcExt::varname": [dport.rtcExt::varname] [endfor] - servicePorts: + servicePorts: [for sport in servicePorts] - name: [sport.name] @@ -268,7 +268,7 @@ "rtcExt::position": [sport.rtcExt::position] - serviceInterface: + serviceInterface: [for sif in sport.serviceInterface] - direction: [sif.direction] @@ -300,10 +300,10 @@ [endfor] [endfor] - configurationSet: - configuration: + configurationSet: + configuration: [for conf in configurationSet.configuration] - - + - name: [conf.name] type: [conf.type] @@ -326,7 +326,7 @@ unit: [conf.rtcDoc::doc.unit] [endfor] - parameters: + parameters: [if-any parameters] [for param in parameters] - diff --git a/OpenRTM_aist/utils/rtc-template/python_gen.py b/OpenRTM_aist/utils/rtc-template/python_gen.py index da2e4e4a..5810ac99 100644 --- a/OpenRTM_aist/utils/rtc-template/python_gen.py +++ b/OpenRTM_aist/utils/rtc-template/python_gen.py @@ -1,20 +1,20 @@ -#!/usr/bin/env python +#!/usr/bin/env python # -*- Python -*- # # @file Py_src.py # @brief rtc-template Python soruce code generator class # @date $Date: 2005/08/26 12:02:37 $ # @author Noriaki Ando -# +# # Copyright (C) 2004-2008 # Task-intelligence Research Group, # Intelligent Systems Research Institute, # National Institute of # Advanced Industrial Science and Technology (AIST), Japan # All rights reserved. -# +# # $Id: python_gen.py 775 2008-07-28 16:14:45Z n-ando $ -# +# import re import os @@ -22,14 +22,16 @@ import string import sys + def description(): - return "Python component code generator" + return "Python component code generator" + def usage(): - """ - Python generator specific usage - """ - return """ + """ + Python generator specific usage + """ + return """ ---------------------------------- Help for Python code generator ---------------------------------- @@ -41,8 +43,10 @@ def usage(): """ + def get_opt_fmt(): - return [] + return [] + service_impl = """\ [for sidl in service_idl] @@ -55,15 +59,15 @@ def get_opt_fmt(): no_global_idl = "" module_spec = """\ -[l_name]_spec = ["implementation_id", "[basicInfo.name]", - "type_name", "[basicInfo.name]", - "description", "[basicInfo.description]", - "version", "[basicInfo.version]", - "vendor", "[basicInfo.vendor]", - "category", "[basicInfo.category]", - "activity_type", "[basicInfo.componentType]", - "max_instance", "[basicInfo.maxInstances]", - "language", "Python", +[l_name]_spec = ["implementation_id", "[basicInfo.name]", + "type_name", "[basicInfo.name]", + "description", "[basicInfo.description]", + "version", "[basicInfo.version]", + "vendor", "[basicInfo.vendor]", + "category", "[basicInfo.category]", + "activity_type", "[basicInfo.componentType]", + "max_instance", "[basicInfo.maxInstances]", + "language", "Python", "lang_type", "SCRIPT", [if-any configurationSet.configuration] [for config in configurationSet.configuration] @@ -117,9 +121,9 @@ def get_opt_fmt(): [endfor]""" -#------------------------------------------------------------ +# ------------------------------------------------------------ # Python component source code template -#------------------------------------------------------------ +# ------------------------------------------------------------ py_source = """#!/usr/bin/env python # -*- Python -*- @@ -201,196 +205,195 @@ def main(): """ - - class python_gen(gen_base.gen_base): - """ - Python component source code generation class - """ - def __init__(self, data, opts): - self.data = data - self.data['fname'] = self.data['basicInfo']['name'] - self.data['fname_py'] = self.data['fname'] + ".py" - self.data["u_name"] = self.data["fname"].upper() - self.data["l_name"] = self.data["fname"].lower() - - self.CreateActivityFuncs(self.data) - self.CreateDataPorts(self.data) - self.CreateService(self.data) - self.CreateConfiguration(self.data) - self.tags = {} - self.tags["service_impl"] = service_impl - if len(self.data["service_idl"]) > 0 or \ - len(self.data["consumer_idl"]) > 0: - self.tags["global_idl"] = global_idl - else: - self.tags["global_idl"] = no_global_idl - self.tags["module_spec"] = module_spec - self.tags["data_ports"] = data_ports - self.tags["service_ports"] = service_ports - self.tags["configurations"] = configurations - self.tags["bind_config"] = bind_config - self.gen_tags(self.tags) - return - - - def CreateActivityFuncs(self, dict): - acts = (("onFinalize", None), \ - ("onStartup", "ec_id"), \ - ("onShutdown", "ec_id"), \ - ("onActivated", "ec_id"), \ - ("onDeactivated", "ec_id"), \ - ("onExecute", "ec_id"), \ - ("onAborting", "ec_id"), \ - ("onError", "ec_id"), \ - ("onReset", "ec_id"), \ - ("onStateUpdate", "ec_id"), \ - ("onRateChanged", "ec_id")) - actlist = [] - for name, args in acts: - a = {} - a["name"] = name - a["args"] = args - actlist.append(a) - - dict["activity"] = actlist - return - - def CreateService(self, dict): - if dict["service_idl"]: - for svc in dict["service_idl"]: - svc["impl_py"] = svc["idl_basename"] + \ - "_idl_example.py" - - if dict["consumer_idl"]: - for cons in dict["consumer_idl"]: - try: - cons["modulename"] = "_GlobalIDL" - f = open(cons["idl_fname"], 'a+') - while 1: - _str = f.readline() - if not _str: - break - mod_idx = _str.find("module", 0) - if mod_idx < 0: - break; - _str = _str[mod_idx + 6:] - idx = _str.find("{", 0) - if idx < 0: - break - _str = _str[:idx] - cons["modulename"] = \ - string.strip(_str) - break - f.close() - except IOError: - print("Can't find file:", file) - return - - def CreateDataPorts(self, dict): - if dict["dataPorts"] == None: - return - for dport in dict["dataPorts"]: - if self.check_data_type(dport["type"]) == "sequence": - dport["data_type_args"] = "RTC.Time(0,0),[]" - else: - dport["data_type_args"] = "RTC.Time(0,0),0" - return - - def CreateConfiguration(self, dict): - config = dict["configurationSet"]["configuration"] - if config: - for i, conf in enumerate(config): - split_data = conf["defaultValue"].split(",") - if len(split_data) > 1: - _data = [] - _type = self.get_type(conf["type"]) - for d in split_data: - _data.append(_type(d)) - conf["defaultData"] = str([_data]) - else: - _type = self.get_type(conf["type"]) - conf["defaultData"] = \ - str([_type(conf["defaultValue"])]) - return - - def check_data_type(self, _type): - if str(_type) in ["TimedShortSeq", "TimedLongSeq", - "TimedUShortSeq", "TimedULongSeq", - "TimedFloatSeq", "TimedDoubleSeq", - "TimedCharSeq","TimedBooleanSeq", - "TimedOctetSeq", "TimedStringSeq"]: - return "sequence" - else: - return None - return None - - def get_type(self, _type): - if str(_type) == "int": - return int - elif str(_type) == "long": - return long - elif str(_type) == "float": - return float - elif str(_type) == "double": - return float - elif str(_type) == "string": - return str - else: - return str - - return str - - def print_impl(self): - for sidl in self.data["service_idl"]: - if not os.access(sidl["idl_fname"], os.F_OK): - sys.stderr.write("Error: IDL file \"" \ - + sidl["idl_fname"] \ - + "\" not found.\n") - sys.exit(1) - - try: - cmd = "omniidl -bpython -Wbexample " + \ - sidl["idl_fname"] - os.system(cmd) - except: - sys.stderr.write("Generate error: " \ - + sidl["impl_py"] + "\n") - - print(" File \"" \ - + sidl["impl_py"] \ - + "\" was generated.") - - for cons in self.data["consumer_idl"]: - dup = False - for svc in self.data["service_idl"]: - if cons["idl_fname"] == svc["idl_fname"]: - dup = True - - if not dup: - if not os.access(cons["idl_fname"], os.F_OK): - sys.stderr.write("Error: IDL file \"" \ - + cons["idl_fname"] \ - + "\" not found.\n") - sys.exit(1) - - try: - cmd = "omniidl -bpython " + \ - cons["idl_fname"] - os.system(cmd) - except: - sys.stderr.write("Generate error: omniidl -bpython " + cons["idl_fname"]) - return - - def print_pysrc(self): """ - Generate component class script + Python component source code generation class """ - self.gen(self.data["fname_py"], py_source, self.data, self.tags) - return - - def print_all(self): - self.print_impl() - self.print_pysrc() - return + def __init__(self, data, opts): + self.data = data + self.data['fname'] = self.data['basicInfo']['name'] + self.data['fname_py'] = self.data['fname'] + ".py" + self.data["u_name"] = self.data["fname"].upper() + self.data["l_name"] = self.data["fname"].lower() + + self.CreateActivityFuncs(self.data) + self.CreateDataPorts(self.data) + self.CreateService(self.data) + self.CreateConfiguration(self.data) + self.tags = {} + self.tags["service_impl"] = service_impl + if len(self.data["service_idl"]) > 0 or \ + len(self.data["consumer_idl"]) > 0: + self.tags["global_idl"] = global_idl + else: + self.tags["global_idl"] = no_global_idl + self.tags["module_spec"] = module_spec + self.tags["data_ports"] = data_ports + self.tags["service_ports"] = service_ports + self.tags["configurations"] = configurations + self.tags["bind_config"] = bind_config + self.gen_tags(self.tags) + return + + def CreateActivityFuncs(self, dict): + acts = (("onFinalize", None), + ("onStartup", "ec_id"), + ("onShutdown", "ec_id"), + ("onActivated", "ec_id"), + ("onDeactivated", "ec_id"), + ("onExecute", "ec_id"), + ("onAborting", "ec_id"), + ("onError", "ec_id"), + ("onReset", "ec_id"), + ("onStateUpdate", "ec_id"), + ("onRateChanged", "ec_id")) + actlist = [] + for name, args in acts: + a = {} + a["name"] = name + a["args"] = args + actlist.append(a) + + dict["activity"] = actlist + return + + def CreateService(self, dict): + if dict["service_idl"]: + for svc in dict["service_idl"]: + svc["impl_py"] = svc["idl_basename"] + \ + "_idl_example.py" + + if dict["consumer_idl"]: + for cons in dict["consumer_idl"]: + try: + cons["modulename"] = "_GlobalIDL" + f = open(cons["idl_fname"], 'a+') + while True: + _str = f.readline() + if not _str: + break + mod_idx = _str.find("module", 0) + if mod_idx < 0: + break + _str = _str[mod_idx + 6:] + idx = _str.find("{", 0) + if idx < 0: + break + _str = _str[:idx] + cons["modulename"] = \ + string.strip(_str) + break + f.close() + except IOError: + print("Can't find file:", file) + return + + def CreateDataPorts(self, dict): + if dict["dataPorts"] is None: + return + for dport in dict["dataPorts"]: + if self.check_data_type(dport["type"]) == "sequence": + dport["data_type_args"] = "RTC.Time(0,0),[]" + else: + dport["data_type_args"] = "RTC.Time(0,0),0" + return + + def CreateConfiguration(self, dict): + config = dict["configurationSet"]["configuration"] + if config: + for i, conf in enumerate(config): + split_data = conf["defaultValue"].split(",") + if len(split_data) > 1: + _data = [] + _type = self.get_type(conf["type"]) + for d in split_data: + _data.append(_type(d)) + conf["defaultData"] = str([_data]) + else: + _type = self.get_type(conf["type"]) + conf["defaultData"] = \ + str([_type(conf["defaultValue"])]) + return + + def check_data_type(self, _type): + if str(_type) in ["TimedShortSeq", "TimedLongSeq", + "TimedUShortSeq", "TimedULongSeq", + "TimedFloatSeq", "TimedDoubleSeq", + "TimedCharSeq", "TimedBooleanSeq", + "TimedOctetSeq", "TimedStringSeq"]: + return "sequence" + else: + return None + return None + + def get_type(self, _type): + if str(_type) == "int": + return int + elif str(_type) == "long": + return long + elif str(_type) == "float": + return float + elif str(_type) == "double": + return float + elif str(_type) == "string": + return str + else: + return str + + return str + + def print_impl(self): + for sidl in self.data["service_idl"]: + if not os.access(sidl["idl_fname"], os.F_OK): + sys.stderr.write("Error: IDL file \"" + + sidl["idl_fname"] + + "\" not found.\n") + sys.exit(1) + + try: + cmd = "omniidl -bpython -Wbexample " + \ + sidl["idl_fname"] + os.system(cmd) + except BaseException: + sys.stderr.write("Generate error: " + + sidl["impl_py"] + "\n") + + print(" File \"" + + sidl["impl_py"] + + "\" was generated.") + + for cons in self.data["consumer_idl"]: + dup = False + for svc in self.data["service_idl"]: + if cons["idl_fname"] == svc["idl_fname"]: + dup = True + + if not dup: + if not os.access(cons["idl_fname"], os.F_OK): + sys.stderr.write("Error: IDL file \"" + + cons["idl_fname"] + + "\" not found.\n") + sys.exit(1) + + try: + cmd = "omniidl -bpython " + \ + cons["idl_fname"] + os.system(cmd) + except BaseException: + sys.stderr.write( + "Generate error: omniidl -bpython " + + cons["idl_fname"]) + return + + def print_pysrc(self): + """ + Generate component class script + """ + self.gen(self.data["fname_py"], py_source, self.data, self.tags) + return + + def print_all(self): + self.print_impl() + self.print_pysrc() + return diff --git a/OpenRTM_aist/utils/rtc-template/rtc-template.py b/OpenRTM_aist/utils/rtc-template/rtc-template.py index 2cbc8f4d..8ac3192a 100644 --- a/OpenRTM_aist/utils/rtc-template/rtc-template.py +++ b/OpenRTM_aist/utils/rtc-template/rtc-template.py @@ -1,22 +1,23 @@ -#!/usr/bin/env python +#!/usr/bin/env python # -*- Python -*- # # @file rtc-template # @brief rtc-template RTComponent source code generator tool # @date $Date: 2007-10-09 07:19:15 $ # @author Noriaki Ando -# +# # Copyright (C) 2004-2008 # Task-intelligence Research Group, # Intelligent Systems Research Institute, # National Institute of # Advanced Industrial Science and Technology (AIST), Japan # All rights reserved. -# +# # $Id: rtc-template 1815 2010-01-27 20:26:57Z n-ando $ # -import getopt, sys +import getopt +import sys import time import re import os @@ -25,8 +26,8 @@ from distutils.sysconfig import get_python_lib -default_profile=""" -rtcProfile: +default_profile = """ +rtcProfile: version: "1.0" id: # RTC:SampleVendor.SampleCategory.SampleComponent:1.0.0 basicInfo: @@ -63,14 +64,14 @@ inout: "" license: "" reference: "" - "rtcExt::versionUpLog": + "rtcExt::versionUpLog": - "2008/04/18 14:00:00:Ver1.0" - "2008/04/18 17:00:00:Ver1.1" - language: - java: - library: + language: + java: + library: - library1 - actions: + actions: onAborting: "rtcDoc::doc": description: on_aborting description @@ -135,7 +136,7 @@ description: on_state_update description postCondition: on_state_update Post_condition preCondition: on_state_update Pre_condition - dataPorts: + dataPorts: - name: inport1 portType: DataInPort @@ -154,14 +155,14 @@ unit: In1Unit "rtcExt::position": LEFT "rtcExt::varname": In1Var - servicePorts: + servicePorts: - name: SrvPort1 "rtcDoc::doc": description: ServicePort1 description ifdescription: ServicePort1 I/F description "rtcExt::position": LEFT - serviceInterface: + serviceInterface: - direction: Provided "rtcDoc::doc": @@ -177,9 +178,9 @@ path: IF1SearchPath type: IF1Type varname: IF1VarName - configurationSet: - configuration: - - + configurationSet: + configuration: + - name: config1 type: int varname: var1 @@ -191,7 +192,7 @@ description: config_Desc1 range: config_range1 unit: config_unit1 - parameters: + parameters: - defaultValue: param_def1 name: param1 @@ -203,15 +204,16 @@ class Struct: - def __init__(self): - return + def __init__(self): + return + plib = get_python_lib() if sys.platform == "win32": - pyhelper_path = os.path.join(plib,"OpenRTM_aist\\rtc-template") + pyhelper_path = os.path.join(plib, "OpenRTM_aist\\rtc-template") else: - pyhelper_path = os.path.join(plib,"/OpenRTM_aist/utils/rtc-template") + pyhelper_path = os.path.join(plib, "/OpenRTM_aist/utils/rtc-template") sys.path.append(pyhelper_path) @@ -239,10 +241,10 @@ def __init__(self): def usage_short(): - """ - Help message - """ - print(""" + """ + Help message + """ + print(""" Usage: rtc-template [OPTIONS] Options: @@ -270,11 +272,12 @@ def usage_short(): """) + def usage_long(): - """ - Help message - """ - print(""" + """ + Help message + """ + print(""" --output[=output_file]: Specify base name of output file. If 'XXX' is specified, Python source codes XXX.py is generated. @@ -328,12 +331,12 @@ class name is also names as this RTC_MODULE_NAME. 'Type' is OutPort's variable type. The acceptable types are, Timed[ Short | Long | UShort | ULong | Float | Double | Char | Boolean | Octet | String ] and its sequence types. - + --service=[PortName:Name:Type]: Specify service name, type and port name. PortName: The name of Port to which the interface belongs. This name is used as CorbaPort's name. - Name: The name of the service interface. This name is used as + Name: The name of the service interface. This name is used as the name of the interface, instance name and variable name. Type: The type of the serivce interface. This name is used as type name of the service. @@ -342,12 +345,12 @@ class name is also names as this RTC_MODULE_NAME. Specify IDL file of service interface. For simplicity, please define one interface in one IDL file, although this IDL file can include two or more interface definition, - + --consumer=[PortName:Name:Type]: Specify consumer name, type and port name. PortName: The name of Port to which the consumer belongs. This name is used as CorbaPort's name. - Name: The name of the consumer. This name is used as + Name: The name of the consumer. This name is used as the name of the consumer, instance name and variable name. Type: The serivce interface type that is required by the consumer. This name is used as type name of the consumer. @@ -356,7 +359,7 @@ class name is also names as this RTC_MODULE_NAME. Specify IDL file of service consumer. For simplicity, please define one interface in one IDL file, although this IDL file can include two or more interface definition, - + Example: rtc-template -bpython \\ @@ -375,557 +378,563 @@ class name is also names as this RTC_MODULE_NAME. --service-idl=MyService.idl --consumer-idl=YourService.idl """) - return + return + def usage(): - usage_short() - usage_long() - return - + usage_short() + usage_long() + return + def CreateBasicInfo(opts): - """ - MakeModuleProfile - - Create ModuleProfile list from command options - """ - mapping = { - 'name': 'name', - 'desc': 'description', - 'version': 'version', - 'vendor': 'vendor', - 'category': 'category', - 'comp-type': 'componentType', - 'act-type': 'activityType', - 'type': 'componentKind', - 'max-inst': 'maxInstances' + """ + MakeModuleProfile + + Create ModuleProfile list from command options + """ + mapping = { + 'name': 'name', + 'desc': 'description', + 'version': 'version', + 'vendor': 'vendor', + 'category': 'category', + 'comp-type': 'componentType', + 'act-type': 'activityType', + 'type': 'componentKind', + 'max-inst': 'maxInstances' } - # default "basicInfo" - prof = { - "name": "", - "description": "", - "version": "1.0.0", - "vendor": "", - "category": "", - "componentType": "STATIC", - "activityType": "PERIODIC", - "componentKind": "DataFlowComponent", - "maxInstances": "1", - "abstract": "", - "executionRate": "1000.0", - "executionType": "PeriodicExecutionContext", - "creationDate": - { - "day": "", - "hour": "", - "minute": "", - "month": "", - "second": "", - "year": "" - }, - "updateDate": - { - "year": "", - "month": "", - "day": "", - "hour": "", - "minute": "", - "second": "", - }, - "rtcDoc::doc": - { - "algorithm": "", - "creator": "", - "description": "", - "inout": "", - "license": "", - "reference": "" - }, - "rtcExt::versionUpLog": [] + # default "basicInfo" + prof = { + "name": "", + "description": "", + "version": "1.0.0", + "vendor": "", + "category": "", + "componentType": "STATIC", + "activityType": "PERIODIC", + "componentKind": "DataFlowComponent", + "maxInstances": "1", + "abstract": "", + "executionRate": "1000.0", + "executionType": "PeriodicExecutionContext", + "creationDate": + { + "day": "", + "hour": "", + "minute": "", + "month": "", + "second": "", + "year": "" + }, + "updateDate": + { + "year": "", + "month": "", + "day": "", + "hour": "", + "minute": "", + "second": "", + }, + "rtcDoc::doc": + { + "algorithm": "", + "creator": "", + "description": "", + "inout": "", + "license": "", + "reference": "" + }, + "rtcExt::versionUpLog": [] } - # obtain --module-xxx options' values - for opt, arg in opts: - if opt.find("--module-") == 0: - var = opt.replace("--module-","") - if mapping[var] in prof: - prof[mapping[var]] = arg - # set creationDate - cDate = time.localtime() - i = 0 - cDateKey = ['year', 'month', 'day', 'hour', 'minute', 'second'] - for key in cDateKey: - prof["creationDate"][key] = cDate[i] - i += 1 - # check empty values - empty = [] - for key in prof.keys(): - if prof[key] == "": - empty.append(key) - - return prof + # obtain --module-xxx options' values + for opt, arg in opts: + if opt.find("--module-") == 0: + var = opt.replace("--module-", "") + if mapping[var] in prof: + prof[mapping[var]] = arg + # set creationDate + cDate = time.localtime() + i = 0 + cDateKey = ['year', 'month', 'day', 'hour', 'minute', 'second'] + for key in cDateKey: + prof["creationDate"][key] = cDate[i] + i += 1 + # check empty values + empty = [] + for key in prof.keys(): + if prof[key] == "": + empty.append(key) + + return prof + def CreateActions(opts): - actnames = [ - "onInitialize", - "onFinalize", - "onActivated", - "onDeactivated", - "onAborting", - "onError", - "onReset", - "onExecute", - "onStateUpdate", - "onShutdown", - "onStartup", - "onRateChanged", + actnames = [ + "onInitialize", + "onFinalize", + "onActivated", + "onDeactivated", + "onAborting", + "onError", + "onReset", + "onExecute", + "onStateUpdate", + "onShutdown", + "onStartup", + "onRateChanged", ] - actions = {} - for a in actnames: - actions[a] = { - "rtcDoc::doc": { - "description": a + " description", - "postCondition": a + " Post_condition", - "preCondition": a + " Pre_condition" - }, - "implemented": True - } - return actions + actions = {} + for a in actnames: + actions[a] = { + "rtcDoc::doc": { + "description": a + " description", + "postCondition": a + " Post_condition", + "preCondition": a + " Pre_condition" + }, + "implemented": True + } + return actions + def CreateConfigurationSet(opts): - """ - MakeConfigurationParameters - - Create Configuration list from command options - """ - prof_list = [] - prof = { - "name": "", - "type": "", - "varname": "", - "defaultValue": "", - "rtcDoc::doc": - { - "type": "type", # type - "constraint": "constraint", - "dataname": "dataname", - "defaultValue": "default", - "description": "description", - "range": "range", - "unit": "unit" - } + """ + MakeConfigurationParameters + + Create Configuration list from command options + """ + prof_list = [] + prof = { + "name": "", + "type": "", + "varname": "", + "defaultValue": "", + "rtcDoc::doc": + { + "type": "type", # type + "constraint": "constraint", + "dataname": "dataname", + "defaultValue": "default", + "description": "description", + "range": "range", + "unit": "unit" + } } - for opt, arg in opts: - if opt == ("--config"): - try: - # For C++ scope resolution operator - arg = re.sub("::", "@@", arg) - name, type, default = arg.split(":") - name = re.sub("@@", "::", name) - type = re.sub("@@", "::", type) - default = re.sub("@@", "::", default) - except: - sys.stderr.write("Invalid option: " \ - + opt \ - + "=" \ - + arg) - tmp = copy.deepcopy(prof) - tmp["name"] = name - tmp["varname"] = name - tmp["l_name"] = name.lower() - tmp["u_name"] = name.upper() - tmp["type"] = type - tmp["defaultValue"] = default - tmp["rtcDoc::doc"]["defaultValue"] = default - prof_list.append(tmp) - return {'configuration': prof_list} + for opt, arg in opts: + if opt == ("--config"): + try: + # For C++ scope resolution operator + arg = re.sub("::", "@@", arg) + name, type, default = arg.split(":") + name = re.sub("@@", "::", name) + type = re.sub("@@", "::", type) + default = re.sub("@@", "::", default) + except BaseException: + sys.stderr.write("Invalid option: " + + opt + + "=" + + arg) + tmp = copy.deepcopy(prof) + tmp["name"] = name + tmp["varname"] = name + tmp["l_name"] = name.lower() + tmp["u_name"] = name.upper() + tmp["type"] = type + tmp["defaultValue"] = default + tmp["rtcDoc::doc"]["defaultValue"] = default + prof_list.append(tmp) + return {'configuration': prof_list} def CreateDataPorts(opts): - """ - MakePortProfile - - Create PortProfile list from command options - """ - prof_list = [] - prof = { - "name": "", - "portType": "", - "type": "", - "interfaceType": "CorbaPort", - "dataflowType": "Push,Pull", - "subscriptionType": "Periodic,New,Flush", - "idlFile": "", - "rtcDoc::doc": - { - "type": "", - "description": "", - "number": "", - "occerrence": "", - "operation": "", - "semantics": "", - "unit": "" - }, - "rtcExt::position": "", - "rtcExt::varname": "" + """ + MakePortProfile + + Create PortProfile list from command options + """ + prof_list = [] + prof = { + "name": "", + "portType": "", + "type": "", + "interfaceType": "CorbaPort", + "dataflowType": "Push,Pull", + "subscriptionType": "Periodic,New,Flush", + "idlFile": "", + "rtcDoc::doc": + { + "type": "", + "description": "", + "number": "", + "occerrence": "", + "operation": "", + "semantics": "", + "unit": "" + }, + "rtcExt::position": "", + "rtcExt::varname": "" } - cnt = 0 - portType = {"--inport": "DataInPort", "--outport": "DataOutPort"} - position = {"--inport": "LEFT", "--outport": "RIGHT"} - for opt, arg in opts: - if opt == "--inport" or opt == "--outport": - try: - arg = re.sub("::", "@@", arg) - name, type = arg.split(":") - name = re.sub("@@", "::", name) - type = re.sub("@@", "::", type) - except: - sys.stderr.write("Invalid option: " \ - + opt \ - + "=" \ - + arg) - tmp = copy.deepcopy(prof) - tmp["name"] = name - tmp["portType"] = portType[opt] - tmp["type"] = type - tmp["num"] = cnt - tmp["rtcDoc::doc"]["type"] = type - tmp["rtcDoc::doc"]["number"] = cnt - tmp["rtcExt::varname"] = name - tmp["rtcExt::position"] = position[opt] - prof_list.append(tmp) - cnt += 1 - - return prof_list + cnt = 0 + portType = {"--inport": "DataInPort", "--outport": "DataOutPort"} + position = {"--inport": "LEFT", "--outport": "RIGHT"} + for opt, arg in opts: + if opt == "--inport" or opt == "--outport": + try: + arg = re.sub("::", "@@", arg) + name, type = arg.split(":") + name = re.sub("@@", "::", name) + type = re.sub("@@", "::", type) + except BaseException: + sys.stderr.write("Invalid option: " + + opt + + "=" + + arg) + tmp = copy.deepcopy(prof) + tmp["name"] = name + tmp["portType"] = portType[opt] + tmp["type"] = type + tmp["num"] = cnt + tmp["rtcDoc::doc"]["type"] = type + tmp["rtcDoc::doc"]["number"] = cnt + tmp["rtcExt::varname"] = name + tmp["rtcExt::position"] = position[opt] + prof_list.append(tmp) + cnt += 1 + + return prof_list def CreateServicePorts(opts): - """ - MakePortInterface - - Create Port interface profile list from command options - """ - prof_list = [] - - prof = { - "name": "", - "rtcDoc::doc": - { - "description": "", - "ifdescription": "", - }, - "rtcExt::position": "LEFT", - "serviceInterface": [] + """ + MakePortInterface + + Create Port interface profile list from command options + """ + prof_list = [] + + prof = { + "name": "", + "rtcDoc::doc": + { + "description": "", + "ifdescription": "", + }, + "rtcExt::position": "LEFT", + "serviceInterface": [] } - ifprof = { - "name": "", - "type": "", - "direction": "", - "varname": "", - "instanceName": "", - "idlFile": "", - "path": "", - "rtcDoc::doc": - { - "description": "", - "docArgument": "", - "docException": "", - "docPostCondition": "", - "docPreCondition": "", - "docReturn": "" - } + ifprof = { + "name": "", + "type": "", + "direction": "", + "varname": "", + "instanceName": "", + "idlFile": "", + "path": "", + "rtcDoc::doc": + { + "description": "", + "docArgument": "", + "docException": "", + "docPostCondition": "", + "docPreCondition": "", + "docReturn": "" + } } - def findport(prof_list, port_name): - for p in prof_list: - if p["name"] == port_name: - return p - return None - def lr(port): - cnt = {"Provided": 0, "Required": 0} - for ifprof in port["serviceInterface"]: - cnt[ifprof["direction"]] += 1 - if cnt["Provided"] < cnt["Required"]: - return "LEFT" - else: - return "RIGHT" - - cnt = 0 - ifType = {"--service": "Provided", "--consumer": "Required"} - for opt, arg in opts: - if opt == "--service" or opt == "--consumer": - try: - arg = re.sub("::", "@@", arg) - portname, name, type = arg.split(":") - portname = re.sub("@@", "::", portname) - name = re.sub("@@", "::", name) - type = re.sub("@@", "::", type) - except: - sys.stderr.write("Invalid option: " \ - + opt \ - + "=" \ - + arg) - port = findport(prof_list, portname) - if port == None: - port = copy.deepcopy(prof) - port["name"] = portname - prof_list.append(port) - - tmp = copy.deepcopy(ifprof) - tmp["name"] = name - tmp["type"] = type - tmp["direction"] = ifType[opt] - tmp["varname"] = name - tmp["instanceName"] = name - idlfname = FindIdlFile(opts, type) - if idlfname == None: - print("Error:") - print("IDL file not found for a interface: ", type) - sys.exit(1) - tmp["idlFile"] = idlfname - port["serviceInterface"].append(tmp) - port["rtcExt::position"] = lr(port) - cnt += 1 - return prof_list + def findport(prof_list, port_name): + for p in prof_list: + if p["name"] == port_name: + return p + return None + + def lr(port): + cnt = {"Provided": 0, "Required": 0} + for ifprof in port["serviceInterface"]: + cnt[ifprof["direction"]] += 1 + if cnt["Provided"] < cnt["Required"]: + return "LEFT" + else: + return "RIGHT" + + cnt = 0 + ifType = {"--service": "Provided", "--consumer": "Required"} + for opt, arg in opts: + if opt == "--service" or opt == "--consumer": + try: + arg = re.sub("::", "@@", arg) + portname, name, type = arg.split(":") + portname = re.sub("@@", "::", portname) + name = re.sub("@@", "::", name) + type = re.sub("@@", "::", type) + except BaseException: + sys.stderr.write("Invalid option: " + + opt + + "=" + + arg) + port = findport(prof_list, portname) + if port is None: + port = copy.deepcopy(prof) + port["name"] = portname + prof_list.append(port) + + tmp = copy.deepcopy(ifprof) + tmp["name"] = name + tmp["type"] = type + tmp["direction"] = ifType[opt] + tmp["varname"] = name + tmp["instanceName"] = name + idlfname = FindIdlFile(opts, type) + if idlfname is None: + print("Error:") + print("IDL file not found for a interface: ", type) + sys.exit(1) + tmp["idlFile"] = idlfname + port["serviceInterface"].append(tmp) + port["rtcExt::position"] = lr(port) + cnt += 1 + return prof_list def FindIdlFile(opts, ifname): - _re_text = "interface\s+" + ifname - for opt, arg in opts: - if opt == "--service-idl" or opt == "--consumer-idl": - fname = arg - fd = open(fname, "r") - if fd == None: - print("IDL file not found: ", arg) - sys.exit(1) - t = fd.read() - if None != re.compile(_re_text).search(t): - fd.close() - return fname - fd.close() - return None + _re_text = r"interface\s+" + ifname + for opt, arg in opts: + if opt == "--service-idl" or opt == "--consumer-idl": + fname = arg + fd = open(fname, "r") + if fd is None: + print("IDL file not found: ", arg) + sys.exit(1) + t = fd.read() + if None != re.compile(_re_text).search(t): + fd.close() + return fname + fd.close() + return None + def PickupIDLFiles(dict): - svcidls = {} - cnsidls = {} - for svc in dict["servicePorts"]: - for sif in svc["serviceInterface"]: - if sif["direction"] == "Provided": - svcidls[sif["idlFile"]] = "" - elif sif["direction"] == "Required": - if not sif["idlFile"] in svcidls: - cnsidls[sif["idlFile"]] = "" - dict["service_idl"] = [] - dict["consumer_idl"] = [] - for f in svcidls.keys(): - idl = {} - idl["idl_fname"] = f - idl["idl_basename"] = f.split(".")[0] - dict["service_idl"].append(idl) - for f in cnsidls.keys(): - idl = {} - idl["idl_fname"] = f - idl["idl_basename"] = f.split(".")[0] - dict["consumer_idl"].append(idl) - return + svcidls = {} + cnsidls = {} + for svc in dict["servicePorts"]: + for sif in svc["serviceInterface"]: + if sif["direction"] == "Provided": + svcidls[sif["idlFile"]] = "" + elif sif["direction"] == "Required": + if not sif["idlFile"] in svcidls: + cnsidls[sif["idlFile"]] = "" + dict["service_idl"] = [] + dict["consumer_idl"] = [] + for f in svcidls.keys(): + idl = {} + idl["idl_fname"] = f + idl["idl_basename"] = f.split(".")[0] + dict["service_idl"].append(idl) + for f in cnsidls.keys(): + idl = {} + idl["idl_fname"] = f + idl["idl_basename"] = f.split(".")[0] + dict["consumer_idl"].append(idl) + return + def CreateId(dict): - dict["id"] = "RTC:" + \ - dict["basicInfo"]["vendor"] + "." + \ - dict["basicInfo"]["category"] + "." + \ - dict["basicInfo"]["name"] + ":" + \ - dict["basicInfo"]["version"] + dict["id"] = "RTC:" + \ + dict["basicInfo"]["vendor"] + "." + \ + dict["basicInfo"]["category"] + "." + \ + dict["basicInfo"]["name"] + ":" + \ + dict["basicInfo"]["version"] + def find_opt(opts, value, default): - for opt, arg in opts: - if opt.find(value) == 0: - return arg + for opt, arg in opts: + if opt.find(value) == 0: + return arg + + return default - return default def find_opt_list(opts, value, default): - list = [] - if len(default) > 0: - list += default - for opt, arg in opts: - if opt == ("--" + value): - list.append(arg) - return list + list = [] + if len(default) > 0: + list += default + for opt, arg in opts: + if opt == ("--" + value): + list.append(arg) + return list class Backend: - def __init__(self, mod_name, mod): - self.mod = mod - self.obj = getattr(mod, mod_name) - self.mod_name = mod_name + def __init__(self, mod_name, mod): + self.mod = mod + self.obj = getattr(mod, mod_name) + self.mod_name = mod_name class BackendLoader: - def __init__(self): - self.backends = {} - self.opts = [] - self.available() - return - - def available(self): - path_list = [pyhelper_path, "."] - for path in path_list: - for f in os.listdir(path): - if re.compile("_gen.py$").search(f): - mod_name = f.replace(".py", "") - opt_name = f.replace("_gen.py", "") - mod = __import__(mod_name, globals(), locals(), []) - try: - mod.usage() - be = Backend(mod_name, mod) - self.backends[opt_name] = be - except: - pass - - return self.backends - - def check_args(self, args): - for opt in args: - if opt.find('-b') == 0: - backend_name = opt.replace("-b", "") - if backend_name in self.backends: - self.opts.append(backend_name) - else: - print("No such backend: ", backend_name) - sys.exit(-1) - elif opt.find('--backend=') == 0: - backend_name = opt.replace("--backend=", "") - if backend_name in self.backends: - self.opts.append(backend_name) - else: - print("No such backend: ", backend_name) - sys.exit(-1) - return self.opts - - def get_opt_fmts(self): - fmts = [] - for be in self.opts: - fmts += self.backends[be].mod.get_opt_fmt() - return fmts - - - def usage_available(self): - print("The following backends are available.") - space = 10 - for key in self.backends: - desc = self.backends[key].mod.description() - print(" -b" + key + ("." * (space - len(key))) + desc) - print(""" + def __init__(self): + self.backends = {} + self.opts = [] + self.available() + return + + def available(self): + path_list = [pyhelper_path, "."] + for path in path_list: + for f in os.listdir(path): + if re.compile("_gen.py$").search(f): + mod_name = f.replace(".py", "") + opt_name = f.replace("_gen.py", "") + mod = __import__(mod_name, globals(), locals(), []) + try: + mod.usage() + be = Backend(mod_name, mod) + self.backends[opt_name] = be + except BaseException: + pass + + return self.backends + + def check_args(self, args): + for opt in args: + if opt.find('-b') == 0: + backend_name = opt.replace("-b", "") + if backend_name in self.backends: + self.opts.append(backend_name) + else: + print("No such backend: ", backend_name) + sys.exit(-1) + elif opt.find('--backend=') == 0: + backend_name = opt.replace("--backend=", "") + if backend_name in self.backends: + self.opts.append(backend_name) + else: + print("No such backend: ", backend_name) + sys.exit(-1) + return self.opts + + def get_opt_fmts(self): + fmts = [] + for be in self.opts: + fmts += self.backends[be].mod.get_opt_fmt() + return fmts + + def usage_available(self): + print("The following backends are available.") + space = 10 + for key in self.backends: + desc = self.backends[key].mod.description() + print(" -b" + key + ("." * (space - len(key))) + desc) + print(""" Backend [xxx] specific help can be available by the following options. -bxxx --help|-h or --backend=xxx --help|-h """) - return + return - def usage(self): - for be in self.opts: - print(self.backends[be].mod.usage()) - print("") - return + def usage(self): + for be in self.opts: + print(self.backends[be].mod.usage()) + print("") + return - def usage_short(self): - for be in self.opts: - print(self.backends[be].mod.usage_short()) - print("") - return + def usage_short(self): + for be in self.opts: + print(self.backends[be].mod.usage_short()) + print("") + return - def generate_code(self, data, opts): - for be in self.opts: - self.backends[be].obj(data, opts).print_all() - return - + def generate_code(self, data, opts): + for be in self.opts: + self.backends[be].obj(data, opts).print_all() + return -def fmtd_args(width, args): - arg_fmt = [""] - w = 0 - line = 0 - for a in args: - w += len(a) + 1 - if w > width: - w = len(a) + 1 - line += 1 - arg_fmt.append("") - arg_fmt[line] += a + " " - return arg_fmt +def fmtd_args(width, args): + arg_fmt = [""] + w = 0 + line = 0 + for a in args: + w += len(a) + 1 + if w > width: + w = len(a) + 1 + line += 1 + arg_fmt.append("") + arg_fmt[line] += a + " " + return arg_fmt def main(): - global opt_args_fmt - - backends = BackendLoader() - backends.check_args(sys.argv[1:]) - opt_args_fmt += backends.get_opt_fmts() - - try: - opts, args = getopt.getopt(sys.argv[1:], "b:ho:v", opt_args_fmt) - except getopt.GetoptError: - print("Error: Invalid option.", getopt.GetoptError) - usage_short() - backends.usage_available() - sys.exit(-1) + global opt_args_fmt + + backends = BackendLoader() + backends.check_args(sys.argv[1:]) + opt_args_fmt += backends.get_opt_fmts() + + try: + opts, args = getopt.getopt(sys.argv[1:], "b:ho:v", opt_args_fmt) + except getopt.GetoptError: + print("Error: Invalid option.", getopt.GetoptError) + usage_short() + backends.usage_available() + sys.exit(-1) + + if not opts: + usage_short() + backends.usage_available() + sys.exit(-1) + + output = None + verbose = False + + for o, a in opts: + if o == "-v": + verbose = True + if o in ("-h"): + usage_short() + backends.usage_available() + backends.usage_short() + sys.exit(0) + if o in ("--help"): + usage() + backends.usage_available() + backends.usage() + sys.exit(0) + if o in ("-o", "--output"): + output = a + # ... + + idl_dir = os.path.join(get_python_lib(), "OpenRTM_aist\\RTM_IDL") + idl_inc = [] + idl_inc.append(idl_dir) + idl_inc.append(".") + + # Create dictionary for ezt + data = {'basicInfo': CreateBasicInfo(opts), + 'actions': CreateActions(opts), + 'configurationSet': CreateConfigurationSet(opts), + 'dataPorts': CreateDataPorts(opts), + 'servicePorts': CreateServicePorts(opts), + 'args': sys.argv, + 'fmtd_args': fmtd_args(70, sys.argv), + 'idl_include': idl_inc + } + CreateId(data) + PickupIDLFiles(data) + + if not 'fname' in data: + data['fname'] = data['basicInfo']['name'] + backends.generate_code(data, opts) + + import README_gen + readme = README_gen.README_gen(data) + readme.print_all() + import profile_gen + profile = profile_gen.profile_gen(data) + profile.print_all() + return - if not opts: - usage_short() - backends.usage_available() - sys.exit(-1) - - output = None - verbose = False - - for o, a in opts: - if o == "-v": - verbose = True - if o in ("-h"): - usage_short() - backends.usage_available() - backends.usage_short() - sys.exit(0) - if o in ("--help"): - usage() - backends.usage_available() - backends.usage() - sys.exit(0) - if o in ("-o", "--output"): - output = a - # ... - - idl_dir = os.path.join(get_python_lib(),"OpenRTM_aist\\RTM_IDL") - idl_inc = [] - idl_inc.append(idl_dir) - idl_inc.append(".") - - # Create dictionary for ezt - data = {'basicInfo': CreateBasicInfo(opts), - 'actions': CreateActions(opts), - 'configurationSet': CreateConfigurationSet(opts), - 'dataPorts': CreateDataPorts(opts), - 'servicePorts': CreateServicePorts(opts), - 'args': sys.argv, - 'fmtd_args': fmtd_args(70, sys.argv), - 'idl_include': idl_inc - } - CreateId(data) - PickupIDLFiles(data) - - if not 'fname' in data: - data['fname'] = data['basicInfo']['name'] - backends.generate_code(data, opts) - - import README_gen - readme = README_gen.README_gen(data) - readme.print_all() - import profile_gen - profile = profile_gen.profile_gen(data) - profile.print_all() - return - if __name__ == "__main__": - main() + main() diff --git a/OpenRTM_aist/utils/rtc-template/uuid.py b/OpenRTM_aist/utils/rtc-template/uuid.py index 0e29c156..99dfdf2f 100644 --- a/OpenRTM_aist/utils/rtc-template/uuid.py +++ b/OpenRTM_aist/utils/rtc-template/uuid.py @@ -1,9 +1,9 @@ -#!/usr/bin/env python -# -*- coding: euc-jp -*- +#!/usr/bin/env python +# -*- coding: utf-8 -*- ## # @file uuid.py -# @brief +# @brief # @date $Date: 2006/06/12 $ # @author Ka-Ping Yee # @@ -25,13 +25,12 @@ long = int - ## # @if jp # @class UUID -# @brief UUIDݻ饹 -# -# UUID ξݻ뤿Υ饹 +# @brief UUID保持クラス +# +# 生成した UUID の情報を保持するためのクラス。 # # @since 0.4.0 # @@ -41,7 +40,7 @@ class UUID(object): def __init__(self, hex=None, bytes=None, fields=None, int_value=None, - version=None): + version=None): r"""Create a UUID from either a string of 32 hexadecimal digits, a string of 16 bytes as the 'bytes' argument, a tuple of six integers (32-bit time_low, 16-bit time_mid, 16-bit time_hi_version, @@ -64,7 +63,6 @@ def __init__(self, hex=None, bytes=None, fields=None, int_value=None, overriding bits in the given 'hex', 'bytes', 'fields', or 'int'. """ - if [hex, bytes, fields, int_value].count(None) != 3: raise TypeError('need just one of hex, bytes, fields, or int') if hex: @@ -76,29 +74,29 @@ def __init__(self, hex=None, bytes=None, fields=None, int_value=None, if bytes: if len(bytes) != 16: raise ValueError('bytes is not a 16-char string') - int_value = long(('%02x'*16) % tuple(map(ord, bytes)), 16) + int_value = long(('%02x' * 16) % tuple(map(ord, bytes)), 16) if fields: if len(fields) != 6: raise ValueError('fields is not a 6-tuple') (time_low, time_mid, time_hi_version, clock_seq_hi_variant, clock_seq_low, node) = fields - if not 0 <= time_low < 1<<32: + if not 0 <= time_low < 1 << 32: raise ValueError('field 1 out of range (need a 32-bit value)') - if not 0 <= time_mid < 1<<16: + if not 0 <= time_mid < 1 << 16: raise ValueError('field 2 out of range (need a 16-bit value)') - if not 0 <= time_hi_version < 1<<16: + if not 0 <= time_hi_version < 1 << 16: raise ValueError('field 3 out of range (need a 16-bit value)') - if not 0 <= clock_seq_hi_variant < 1<<8: + if not 0 <= clock_seq_hi_variant < 1 << 8: raise ValueError('field 4 out of range (need an 8-bit value)') - if not 0 <= clock_seq_low < 1<<8: + if not 0 <= clock_seq_low < 1 << 8: raise ValueError('field 5 out of range (need an 8-bit value)') - if not 0 <= node < 1<<48: + if not 0 <= node < 1 << 48: raise ValueError('field 6 out of range (need a 48-bit value)') clock_seq = (clock_seq_hi_variant << 8) | clock_seq_low int_value = ((time_low << 96) | (time_mid << 80) | - (time_hi_version << 64) | (clock_seq << 48) | node) + (time_hi_version << 64) | (clock_seq << 48) | node) if int_value: - if not 0 <= int_value < 1<<128: + if not 0 <= int_value < 1 << 128: raise ValueError('int is out of range (need a 128-bit value)') if version: if not 1 <= version <= 5: @@ -149,7 +147,7 @@ def get_fields(self): def get_time_low(self): return self.int_value >> 96 - + time_low = property(get_time_low) def get_time_mid(self): @@ -159,14 +157,14 @@ def get_time_mid(self): def get_time_hi_version(self): return (self.int_value >> 64) & 0xffff - + time_hi_version = property(get_time_hi_version) def get_clock_seq_hi_variant(self): return (self.int_value >> 56) & 0xff clock_seq_hi_variant = property(get_clock_seq_hi_variant) - + def get_clock_seq_low(self): return (self.int_value >> 48) & 0xff @@ -183,7 +181,7 @@ def get_clock_seq(self): self.clock_seq_low) clock_seq = property(get_clock_seq) - + def get_node(self): return self.int_value & 0xffffffffffff @@ -218,6 +216,7 @@ def get_version(self): version = property(get_version) + def _ifconfig_getnode(): """Get the hardware address on Unix by running ifconfig.""" import os @@ -225,21 +224,23 @@ def _ifconfig_getnode(): pipe = os.popen(os.path.join(dir, 'ifconfig')) for line in pipe: - words = line.lower().split() - for i in range(len(words)): - if words[i] in ['hwaddr', 'ether']: - return int(words[i + 1].replace(':', ''), 16) + words = line.lower().split() + for i in range(len(words)): + if words[i] in ['hwaddr', 'ether']: + return int(words[i + 1].replace(':', ''), 16) + def _ipconfig_getnode(): """Get the hardware address on Windows by running ipconfig.exe.""" - import os, re + import os + import re dirs = ['', r'c:\windows\system32', r'c:\winnt\system32'] try: import ctypes buffer = ctypes.create_string_buffer(300) ctypes.windll.kernel32.GetSystemDirectoryA(buffer, 300) dirs.insert(0, buffer.value.decode('mbcs')) - except: + except BaseException: pass for dir in dirs: try: @@ -251,10 +252,12 @@ def _ipconfig_getnode(): if re.match('([0-9a-f][0-9a-f]-){5}[0-9a-f][0-9a-f]', value): return int(value.replace('-', ''), 16) + def _netbios_getnode(): """Get the hardware address on Windows using NetBIOS calls. See http://support.microsoft.com/kb/118623 for details.""" - import win32wnet, netbios + import win32wnet + import netbios ncb = netbios.NCB() ncb.Command = netbios.NCBENUM ncb.Buffer = adapters = netbios.LANA_ENUM() @@ -277,15 +280,17 @@ def _netbios_getnode(): continue status._unpack() bytes = map(ord, status.adapter_address) - return ((bytes[0]<<40) + (bytes[1]<<32) + (bytes[2]<<24) + - (bytes[3]<<16) + (bytes[4]<<8) + bytes[5]) + return ((bytes[0] << 40) + (bytes[1] << 32) + (bytes[2] << 24) + + (bytes[3] << 16) + (bytes[4] << 8) + bytes[5]) # Thanks to Thomas Heller for ctypes and for his help with its use here. + # If ctypes is available, use it to find system routines for UUID generation. _uuid_generate_random = _uuid_generate_time = _UuidCreate = None try: - import ctypes, ctypes.util + import ctypes + import ctypes.util _buffer = ctypes.create_string_buffer(16) # The uuid_generate_* routines are provided by libuuid on at least @@ -293,7 +298,7 @@ def _netbios_getnode(): for libname in ['uuid', 'c']: try: lib = ctypes.CDLL(ctypes.util.find_library(libname)) - except: + except BaseException: continue if hasattr(lib, 'uuid_generate_random'): _uuid_generate_random = lib.uuid_generate_random @@ -306,30 +311,35 @@ def _netbios_getnode(): # hardware address. These routines are provided by the RPC runtime. try: lib = ctypes.windll.rpcrt4 - except: + except BaseException: lib = None _UuidCreate = getattr(lib, 'UuidCreateSequential', getattr(lib, 'UuidCreate', None)) -except: +except BaseException: pass + def _unixdll_getnode(): """Get the hardware address on Unix using ctypes.""" _uuid_generate_time(_buffer) return UUID(bytes=_buffer.raw).node + def _windll_getnode(): """Get the hardware address on Windows using ctypes.""" if _UuidCreate(_buffer) == 0: return UUID(bytes=_buffer.raw).node + def _random_getnode(): """Get a random node ID, with eighth bit set as suggested by RFC 4122.""" import random - return random.randrange(0, 1<<48) | 0x010000000000 + return random.randrange(0, 1 << 48) | 0x010000000000 + _node = None + def getnode(): """Get the hardware address as a 48-bit integer. The first time this runs, it may launch a separate program, which could be quite slow. If @@ -349,11 +359,12 @@ def getnode(): for getter in getters + [_random_getnode]: try: _node = getter() - except: + except BaseException: continue if _node: return _node + def uuid1(node=None, clock_seq=None): """Generate a UUID from a host ID, sequence number, and the current time. If 'node' is not given, getnode() is used to obtain the hardware @@ -370,10 +381,10 @@ def uuid1(node=None, clock_seq=None): nanoseconds = int(time.time() * 1e9) # 0x01b21dd213814000 is the number of 100-ns intervals between the # UUID epoch 1582-10-15 00:00:00 and the Unix epoch 1970-01-01 00:00:00. - timestamp = int(nanoseconds/100) + 0x01b21dd213814000 + timestamp = int(nanoseconds / 100) + 0x01b21dd213814000 if clock_seq is None: import random - clock_seq = random.randrange(1<<14) # instead of stable storage + clock_seq = random.randrange(1 << 14) # instead of stable storage time_low = timestamp & 0xffffffff time_mid = (timestamp >> 32) & 0xffff time_hi_version = (timestamp >> 48) & 0x0fff @@ -384,12 +395,14 @@ def uuid1(node=None, clock_seq=None): return UUID(fields=(time_low, time_mid, time_hi_version, clock_seq_hi_variant, clock_seq_low, node), version=1) + def uuid3(namespace, name): """Generate a UUID from the MD5 hash of a namespace UUID and a name.""" import md5 hash = md5.md5(namespace.bytes + name).digest() return UUID(bytes=hash[:16], version=3) + def uuid4(): """Generate a random UUID.""" @@ -402,11 +415,12 @@ def uuid4(): try: import os return UUID(bytes=os.urandom(16), version=4) - except: + except BaseException: import random bytes = [chr(random.randrange(256)) for i in range(16)] return UUID(bytes=bytes, version=4) + def uuid5(namespace, name): """Generate a UUID from the SHA-1 hash of a namespace UUID and a name.""" import sha @@ -415,6 +429,7 @@ def uuid5(namespace, name): # The following standard UUIDs are for use with uuid3() or uuid5(). + NAMESPACE_DNS = UUID('6ba7b810-9dad-11d1-80b4-00c04fd430c8') NAMESPACE_URL = UUID('6ba7b811-9dad-11d1-80b4-00c04fd430c8') NAMESPACE_OID = UUID('6ba7b812-9dad-11d1-80b4-00c04fd430c8') diff --git a/OpenRTM_aist/utils/rtc-template/yat.py b/OpenRTM_aist/utils/rtc-template/yat.py index 2fd23b14..64b1dfa2 100644 --- a/OpenRTM_aist/utils/rtc-template/yat.py +++ b/OpenRTM_aist/utils/rtc-template/yat.py @@ -1,4 +1,4 @@ -#!/usr/bin/env python +#!/usr/bin/env python # # @brief YAT: YAml Template text processor # @date $Date: 2008-02-09 20:04:27 $ @@ -11,14 +11,14 @@ # # Usage: -#------------------------------------------------------------ +# ------------------------------------------------------------ # import yaml # import yat # # dict = yaml.load(open(filename, "r").read()) # t = yat.Template(template, "\[", "\]") # result = t.generate(dict) -#------------------------------------------------------------ +# ------------------------------------------------------------ # # 1. Simple directive: # [dictionary_key] @@ -60,11 +60,11 @@ # # template: # [for lst in list] -# [lst], +# [lst], # [endfor] # [for lst in listed_dict] # [lst.name]: [lst.value] -# +# # [endfor] # # result: @@ -171,6 +171,7 @@ from types import StringType, IntType, FloatType, DictType, ListType, ClassType import sys + class Template: """ usage: @@ -180,8 +181,8 @@ class Template: generated_text = t.generate(dictionary) """ - - def __init__(self, template, begin_mark="\[", end_mark="\]"): + + def __init__(self, template, begin_mark=r"\[", end_mark=r"\]"): self.__procs = [self.__proc_text, self.__proc_cmd, self.__proc_bracket] @@ -203,37 +204,37 @@ def __init__(self, template, begin_mark="\[", end_mark="\]"): # NAME : (alphanum | '_' | '-' | '.')+ # (2) BEGIN_MARK_ESCAPE : '[[]' # (3) COMMENT : '[#' not-rbracket - # + # # re_item = r'(?:"(?:[^\\"]|\\.)*"|[-\w.]+)' # re_command = r'\[(%s(?: +%s)*)\]' % (re_item, re_item) # re_beginmark = r'\[\[\]' # re_comment = r'\[#[^\]]*\]' - # re_parse = re.compile(r'%s|(%s)|%s' + # re_parse = re.compile(r'%s|(%s)|%s' # % (re_command, re_beginmark, re_comment)) # re_args = re.compile(r'"(?:[^\\"]|\\.)*"|[-\w.]+') # # - re_item = r'(?:"(?:[^\\"]|\\.)*"|[-\w.:]+)' - re_command = r'%s(%s(?: +%s)*)%s' % \ + re_item = r'(?:"(?:[^\\"]|\\.)*"|[-\w.:]+)' + re_command = r'%s(%s(?: +%s)*)%s' % \ (begin_mark, re_item, re_item, end_mark) - re_bracket = r'%s%s%s' % \ + re_bracket = r'%s%s%s' % \ (begin_mark, begin_mark, end_mark) - re_comment = r'%s#[^%s]*%s' % \ + re_comment = r'%s#[^%s]*%s' % \ (begin_mark, end_mark, end_mark) - self.begin_mark = begin_mark.replace("\\","") - self.re_parse = re.compile(r'%s|(%s)|%s' % \ - (re_command, re_bracket, re_comment)) - self.re_args = re.compile(r'"(?:[^\\"]|\\.)*"|[-\w.:]+') + self.begin_mark = begin_mark.replace("\\", "") + self.re_parse = re.compile(r'%s|(%s)|%s' % + (re_command, re_bracket, re_comment)) + self.re_args = re.compile(r'"(?:[^\\"]|\\.)*"|[-\w.:]+') self.re_number = re.compile(r'[0-9]+') # tokenize input text self.token = self.re_parse.split(self.template) - self.token_len = len(self.token) - + self.token_len = len(self.token) + # initialize variables self.script = program self.indent = 4 - self.script_level = 2 + self.script_level = 2 self.level = 0 self.index = 0 self.cmd_cxt = [] @@ -261,13 +262,13 @@ def __pop_level(self): self.level -= 1 def __write_cmd(self, cmd): - tmp_cmd = self.__indent() + tmp_cmd = self.__indent() tmp_cmd += "self.set_index(%s)\n" % (self.index) self.script += tmp_cmd self.__write_cmd_noindex(cmd) def __write_cmd_noindex(self, cmd): - tmp_cmd = self.__indent() + tmp_cmd = self.__indent() tmp_cmd += cmd + "\n" self.script += tmp_cmd @@ -289,24 +290,24 @@ def __parse(self): self.index += 1 def __proc_text(self): - if self.token[self.index] == None: + if self.token[self.index] is None: return cmd_text = "self.write_token(%s)" % (self.index) self.__write_cmd(cmd_text) return True - + def __proc_bracket(self): - if self.token[self.index] == None: + if self.token[self.index] is None: return cmd_text = "self.write(\"" + self.begin_mark + "\")" self.__write_cmd(cmd_text) return True - + def __proc_cmd(self): cmd = self.token[self.index] try: args = self.re_args.findall(cmd) - except: + except BaseException: return self.del_nl_after_cmd() argc = len(args) @@ -315,7 +316,7 @@ def __proc_cmd(self): # simple directive if argc == 1: - if args[0] == "endfor": + if args[0] == "endfor": self.__endfor_cmd(args) return elif args[0] == "else": @@ -334,7 +335,7 @@ def __proc_cmd(self): if args[0] == "if-any": self.__if_any_cmd(args) return - elif argc == 4: # [for key in value] + elif argc == 4: # [for key in value] if args[0] == "for" and args[2] == "in": self.__for_cmd(args) return True @@ -356,12 +357,12 @@ def __cmd(self, args): cmd_text = "self.write_dict(\"%s\")" % (args[0]) self.__write_cmd(cmd_text) - #------------------------------------------------------------ + # ------------------------------------------------------------ # [for] commands # - for # - last # - endfor - #------------------------------------------------------------ + # ------------------------------------------------------------ def __for_cmd(self, args): """ The following [for] directive @@ -396,20 +397,20 @@ def __endfor_cmd(self, args): raise UnmatchedBlock(self.lineno(), "endfor") self.__write_cmd("self.pop_dict()") self.__pop_level() - except: + except BaseException: print(args, self.lineno()) raise UnmatchedBlock(self.lineno(), "endfor") return # end of [for] commands - #------------------------------------------------------------ + # ------------------------------------------------------------ - #------------------------------------------------------------ + # ------------------------------------------------------------ # [if] commands # - if # - if-index # - if-any - #------------------------------------------------------------ + # ------------------------------------------------------------ def __if_cmd(self, args): """ The following [if] directive @@ -443,16 +444,16 @@ def __if_index_cmd(self, args): # [if-index KEY is [first|even|odd|last|NUMBER]] # ~~~0~~~ ~1~ 2 ~~~~~~~~~~~~~~3~~~~~~~~~~~~ cmdlist = {"first": "if %s_index == 0:", - "even" : "if (%s_index %% 2) == 0:", - "odd" : "if (%s_index %% 2) != 0:", - "last" : "if %s_index == %s_len - 1:"} + "even": "if (%s_index %% 2) == 0:", + "odd": "if (%s_index %% 2) != 0:", + "last": "if %s_index == %s_len - 1:"} key = args[1] cmd = args[3] if len(self.re_number.findall(cmd)) == 1: cmd_text = "if %s_index == %s:" % (key, cmd) elif cmd in cmdlist: if cmd == "last": - cmd_text = cmdlist[cmd] % (key,key) + cmd_text = cmdlist[cmd] % (key, key) else: cmd_text = cmdlist[cmd] % (key) else: @@ -467,16 +468,16 @@ def __elif_index_cmd(self, args): # [elif-index KEY is [first|even|odd|last|NUMBER]] # ~~~0~~~ ~1~ 2 ~~~~~~~~~~~~~~3~~~~~~~~~~~~ cmdlist = {"first": "elif %s_index == 0:", - "even" : "elif (%s_index %% 2) == 0:", - "odd" : "elif (%s_index %% 2) != 0:", - "last" : "elif %s_index == %s_len - 1:"} + "even": "elif (%s_index %% 2) == 0:", + "odd": "elif (%s_index %% 2) != 0:", + "last": "elif %s_index == %s_len - 1:"} key = args[1] cmd = args[3] if len(self.re_number.findall(cmd)) == 1: cmd_text = "elif %s_index == %s:" % (key, cmd) elif cmd in cmdlist: if cmd == "last": - cmd_text = cmdlist[cmd] % (key,key) + cmd_text = cmdlist[cmd] % (key, key) else: cmd_text = cmdlist[cmd] % (key) else: @@ -522,7 +523,7 @@ def __endif_cmd(self, args): self.__pop_level() return # end of [if] commands - #------------------------------------------------------------ + # ------------------------------------------------------------ def __print_error(self, e): print("Parse Error: line", e.lineno, "in input data") @@ -530,20 +531,22 @@ def __print_error(self, e): lines = self.template.split("\n") length = len(lines) print("------------------------------------------------------------") - for i in range(1,10): + for i in range(1, 10): l = e.lineno - 6 + i if l > 0 and l < length: print(lines[l]) if i == 5: - uline = '~'*len(lines[l]) + uline = '~' * len(lines[l]) print(uline) print("------------------------------------------------------------") - + def del_nl_after_cmd(self): # next text index after command next = self.index + 2 - if next > self.token_len: return - if self.token[next] == None: return + if next > self.token_len: + return + if self.token[next] is None: + return text = self.token[next] tlen = len(text) if tlen > 0 and text[0] == '\n': @@ -565,9 +568,9 @@ def lineno(self): return l -#------------------------------------------------------------ +# ------------------------------------------------------------ # Generator and GeneratorBase classes -#------------------------------------------------------------ +# ------------------------------------------------------------ program = """ class Generator(GeneratorBase): def __init__(self, token, dict): @@ -583,6 +586,7 @@ def generate(self): def process(self): """ + class GeneratorBase: def __init__(self, token, dict): self.token = token @@ -595,7 +599,7 @@ def print_error(self, e): print(" " + ''.join(nesteditem(e.value))) temp = "" for i, s in enumerate(self.token): - if s != None: + if s is not None: if i % 3 == 1: temp += "[" + s + "]\n" else: @@ -603,15 +607,15 @@ def print_error(self, e): lines = temp.split("\n") length = len(lines) print("------------------------------------------------------------") - for i in range(1,10): + for i in range(1, 10): l = e.lineno - 6 + i if l > 0 and l < length: print(lines[l]) if i == 5: - uline = '~'*len(lines[l]) + uline = '~' * len(lines[l]) print(uline) print("------------------------------------------------------------") - + def set_index(self, index): self.index = index @@ -635,22 +639,22 @@ def write_token(self, index): def lineno(self): cnt = 1 for i in range(0, self.index, 3): - if self.token[i] != None: + if self.token[i] is not None: cnt += self.token[i].count('\n') # count deleted '\n' after commands for i in range(1, self.index, 3): - if self.token[i] != None: + if self.token[i] is not None: cnt += 1 return cnt - + def get_text(self, keytext): val = self.get_value(keytext) if isinstance(val, StringType): return val if isinstance(val, IntType) or isinstance(val, FloatType): return str(val) - raise UnexpectedData(self.lineno(), "\"" + keytext + \ - "\" should have string, int or float value.") + raise UnexpectedData(self.lineno(), "\"" + keytext + + "\" should have string, int or float value.") def get_list(self, keytext): val = self.get_value(keytext) @@ -670,9 +674,9 @@ def get_value(self, keytext): keys = keytext.split('.') for i in range(len(self.dicts) - 1, -1, -1): dict_value = self.get_dict_value(keys, self.dicts[i]) - if dict_value != None: + if dict_value is not None: return dict_value - raise NotFound(self.lineno(), keytext) + raise NotFound(self.lineno(), keytext) def get_dict_value(self, keys, dict): length = len(keys) @@ -685,66 +689,74 @@ def get_dict_value(self, keys, dict): return d -#------------------------------------------------------------ -# Exceptions -#------------------------------------------------------------ +# ------------------------------------------------------------ +# Exceptions +# ------------------------------------------------------------ class YATException(Exception): pass + class UnknownError(YATException): def __init__(self, lineno): self.lineno = lineno self.value = "Unknown error." + class UnmatchedBlock(YATException): def __init__(self, lineno, msg): self.lineno = lineno self.value = "Unmatched block error: " + msg + class UnexpectedData(YATException): def __init__(self, lineno, msg): self.lineno = lineno self.value = msg + class NotFinalElement(YATException): def __init__(self, dictkey, dictvalue): self.value = "Specified key is not final element: ",\ dictkey, "=>", dictvalue + class InvalidDirective(YATException): def __init__(self, lineno, directive): self.lineno = lineno self.value = "Invalid directive: \"[" + directive + "]\"" + class UnmatchedData(YATException): def __init__(self, lineno, description): self.lineno = lineno self.value = "Unmatched data and input: ", description + class NotFound(YATException): def __init__(self, lineno, description): self.lineno = lineno self.value = "Value not found for: \"" + description + "\"" -#------------------------------------------------------------ +# ------------------------------------------------------------ # other functions -#------------------------------------------------------------ +# ------------------------------------------------------------ + + def nesteditem(aList): for anItem in aList: - if type(anItem)==list: + if isinstance(anItem, list): for subitem in nesteditem(anItem): yield subitem else: yield anItem - if __name__ == "__main__": dict = [] template = [] - #------------------------------------------------------------ + # ------------------------------------------------------------ # Example 0 - #------------------------------------------------------------ + # ------------------------------------------------------------ dict.append({"a": "This is a", "b": {"1": "This is b.1", "2": "This is b.2"} @@ -755,26 +767,26 @@ def nesteditem(aList): [b.2]""") - #------------------------------------------------------------ + # ------------------------------------------------------------ # Example 1 - #------------------------------------------------------------ + # ------------------------------------------------------------ dict.append({"list": [0, 1, 2], "listed_dict": [ {"name": "x", "value": "1.0"}, {"name": "y", "value": "0.2"}, {"name": "z", "value": "0.1"}]}) template.append("""[for lst in list] -[lst], +[lst], [endfor] [for lst in listed_dict] [lst.name]: [lst.value] [endfor]""") - #------------------------------------------------------------ + # ------------------------------------------------------------ # Example 2 - #------------------------------------------------------------ - dict.append({"list": [0,1,2,3,4,5,6,7,8,9,10]}) + # ------------------------------------------------------------ + dict.append({"list": [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]}) template.append("""[for key in list] [if-index key is 3] [key] is hoge!! [elif-index key is 6] [key] is foo!! @@ -786,9 +798,9 @@ def nesteditem(aList): [endif] [endfor]""") - #------------------------------------------------------------ + # ------------------------------------------------------------ # Example 3 - #------------------------------------------------------------ + # ------------------------------------------------------------ dict.append({"key1": "a", "key2": "b"}) template.append("""[if key1 is a] The key1 is "a". @@ -796,9 +808,9 @@ def nesteditem(aList): This key1 is not "a". [endif]""") - #------------------------------------------------------------ + # ------------------------------------------------------------ # Example 4 - #------------------------------------------------------------ + # ------------------------------------------------------------ dict.append({"key1": "a", "key2": "b"}) template.append("""[if-any key1] key1 exists. @@ -816,7 +828,7 @@ def nesteditem(aList): import yaml if len(dict) == len(template): - for i in range(len(dict)-1,len(dict)): + for i in range(len(dict) - 1, len(dict)): t = Template(template[i]) print("-" * 60) print("Example:", i) diff --git a/OpenRTM_aist/utils/rtcd/__init__.py b/OpenRTM_aist/utils/rtcd/__init__.py index a7e6c177..5f282702 100644 --- a/OpenRTM_aist/utils/rtcd/__init__.py +++ b/OpenRTM_aist/utils/rtcd/__init__.py @@ -1 +1 @@ -from rtcd import * + \ No newline at end of file diff --git a/OpenRTM_aist/utils/rtcd/py2exe/setup.py b/OpenRTM_aist/utils/rtcd/py2exe/setup.py index 6cfe1184..090a22d7 100644 --- a/OpenRTM_aist/utils/rtcd/py2exe/setup.py +++ b/OpenRTM_aist/utils/rtcd/py2exe/setup.py @@ -1,16 +1,16 @@ -from distutils.core import setup +from distutils.core import setup import py2exe option = { - "compressed" : 1, - "optimize" : 2, - } + "compressed": 1, + "optimize": 2, +} setup( - options = { "py2exe" : option - }, - console = [ - {"script" : "rtcd_python.py" } - ], - zipfile = "rtcd-lib/rtcd.zip" + options={"py2exe" : option + }, + console=[ + {"script" : "rtcd_python.py"} + ], + zipfile="rtcd-lib/rtcd.zip" ) diff --git a/OpenRTM_aist/utils/rtcd/rtcd_python b/OpenRTM_aist/utils/rtcd/rtcd_python index e6b314b6..43eef909 100755 --- a/OpenRTM_aist/utils/rtcd/rtcd_python +++ b/OpenRTM_aist/utils/rtcd/rtcd_python @@ -15,10 +15,10 @@ # All rights reserved. import sys -import rtcd +import rtcd.rtcd_python def main(): - rtcd.main() + rtcd.rtcd_python.main() return if __name__ == "__main__": diff --git a/OpenRTM_aist/utils/rtcd/rtcd_python.bat b/OpenRTM_aist/utils/rtcd/rtcd_python.bat index 70117f5b..f78d1f64 100755 --- a/OpenRTM_aist/utils/rtcd/rtcd_python.bat +++ b/OpenRTM_aist/utils/rtcd/rtcd_python.bat @@ -6,4 +6,4 @@ rem Intelligent Systems Research Institute, rem National Institute of rem Advanced Industrial Science and Technology (AIST), Japan rem All rights reserved. -%~dp0\python.exe %~dp0\rtcd.py %* +%~dp0\python.exe %~dp0\rtcd_python.py %* diff --git a/OpenRTM_aist/utils/rtcd/rtcd_python.py b/OpenRTM_aist/utils/rtcd/rtcd_python.py index 8668086c..91b05ace 100755 --- a/OpenRTM_aist/utils/rtcd/rtcd_python.py +++ b/OpenRTM_aist/utils/rtcd/rtcd_python.py @@ -1,4 +1,4 @@ -#!/usr/bin/env python +#!/usr/bin/env python # -*- Python -*- ## @@ -16,18 +16,21 @@ # # $Id: $ -import sys,os +import sys +import os import OpenRTM_aist + def main(): - manager = OpenRTM_aist.Manager.init(sys.argv) + manager = OpenRTM_aist.Manager.init(sys.argv) + + manager.activateManager() - manager.activateManager() + manager.runManager() - manager.runManager() + return - return if __name__ == "__main__": - main() + main() diff --git a/OpenRTM_aist/utils/rtcd/rtcd.py b/OpenRTM_aist/utils/rtcd/rtcd_python3 similarity index 54% rename from OpenRTM_aist/utils/rtcd/rtcd.py rename to OpenRTM_aist/utils/rtcd/rtcd_python3 index 8668086c..2b884c70 100644 --- a/OpenRTM_aist/utils/rtcd/rtcd.py +++ b/OpenRTM_aist/utils/rtcd/rtcd_python3 @@ -1,32 +1,24 @@ -#!/usr/bin/env python +#!/usr/bin/env python3 # -*- Python -*- +# -*- coding: euc-jp -*- ## -# @file rtcd.py +# @file rtcd_python # @brief RT component server daemon -# @date $Date: 2005-05-12 09:06:19 $ +# @date $Date: $ # @author Noriaki Ando and Shinji Kurihara # -# Copyright (C) 2003-2008 -# Task-intelligence Research Group, +# Copyright (C) 2010 # Intelligent Systems Research Institute, # National Institute of # Advanced Industrial Science and Technology (AIST), Japan # All rights reserved. -# -# $Id: $ - -import sys,os -import OpenRTM_aist +import sys +import rtcd.rtcd_python def main(): - manager = OpenRTM_aist.Manager.init(sys.argv) - - manager.activateManager() - - manager.runManager() - + rtcd.rtcd_python.main() return if __name__ == "__main__": diff --git a/OpenRTM_aist/utils/rtcprof/__init__.py b/OpenRTM_aist/utils/rtcprof/__init__.py index 6ca05542..5f282702 100644 --- a/OpenRTM_aist/utils/rtcprof/__init__.py +++ b/OpenRTM_aist/utils/rtcprof/__init__.py @@ -1 +1 @@ -from rtcprof import * + \ No newline at end of file diff --git a/OpenRTM_aist/utils/rtcprof/rtcprof.py b/OpenRTM_aist/utils/rtcprof/rtcprof.py deleted file mode 100644 index e1a403bb..00000000 --- a/OpenRTM_aist/utils/rtcprof/rtcprof.py +++ /dev/null @@ -1,112 +0,0 @@ -#!/usr/bin/env python -# -*- Python -*- - -## -# @file rtcprof.py -# @brief RT-Component profile dump command -# @date $Date$ -# @author Noriaki Ando and Shinji Kurihara -# -# Copyright (C) 2010 -# Intelligent Systems Research Institute, -# National Institute of -# Advanced Industrial Science and Technology (AIST), Japan -# All rights reserved. -# -# $Id$ - -import sys -import os - -import OpenRTM_aist - -def main(): - - if len(sys.argv) != 2: - print("usage: ") - print(sys.argv[0], " *.py ") - return - - # file name with full path - fullname = sys.argv[1] - # directory name - dirname = os.path.dirname(sys.argv[1]) - tmp_path = sys.path - sys.path.append(dirname) - - # basename - basename = os.path.basename(sys.argv[1]) - # classname - classname = basename.split(".")[0].lower() - - opts =[] - opts.append("dummy") - opts.append("-o") - opts.append("manager.modules.load_path: " + dirname) - opts.append("-o") - opts.append("logger.enable:NO") - opts.append("-o") - opts.append("manager.corba_servant:NO") - opts.append("-o") - opts.append("timer.enable:NO") - - # Manager initialization - OpenRTM_aist.Manager.init(opts) - mgr = OpenRTM_aist.Manager.instance() - - # loaded profile = old profiles - new profiles - # for old - oldp = mgr.getFactoryProfiles() - - # for new - comp_spec_name = classname+"_spec" - - with open(str(fullname)) as f: - if f.read().find(comp_spec_name) == -1: - return - try: - imp_file = __import__(basename.split(".")[0]) - except: - sys.path = tmp_path - return - - comp_spec = getattr(imp_file,comp_spec_name,None) - if not comp_spec: - sys.path = tmp_path - return - - newp = OpenRTM_aist.Properties(defaults_str=comp_spec) - - profs = [] - - exists = False - for i in range(len(oldp)): - if oldp[i].getProperty("implementation_id") == newp.getProperty("implementation_id") and \ - oldp[i].getProperty("type_name") == newp.getProperty("type_name") and \ - oldp[i].getProperty("description") == newp.getProperty("description") and \ - oldp[i].getProperty("version") == newp.getProperty("version"): - exists = True - if not exists: - profs.append(newp) - - - # loaded component profile have to be one - if len(profs) == 0: - print("Load failed. file name: ", fname) - sys.path = tmp_path - return OpenRTM_aist.Properties() - - if len(profs) > 1: - print("One or more modules loaded.") - sys.path = tmp_path - return OpenRTM_aist.Properties() - - keys = profs[0].propertyNames() - for key in keys: - print("%s:%s"%(key,profs[0].getProperty(key))) - - sys.path = tmp_path - return - -if __name__ == "__main__": - main() diff --git a/OpenRTM_aist/utils/rtcprof/rtcprof_python b/OpenRTM_aist/utils/rtcprof/rtcprof_python index 7a55300f..b72a6c73 100755 --- a/OpenRTM_aist/utils/rtcprof/rtcprof_python +++ b/OpenRTM_aist/utils/rtcprof/rtcprof_python @@ -15,10 +15,10 @@ # All rights reserved. import sys -import rtcprof +import rtcprof.rtcprof_python def main(): - rtcprof.main() + rtcprof.rtcprof_python.main() return if __name__ == "__main__": diff --git a/OpenRTM_aist/utils/rtcprof/rtcprof_python.bat b/OpenRTM_aist/utils/rtcprof/rtcprof_python.bat index 3e1bda4c..bb91543a 100755 --- a/OpenRTM_aist/utils/rtcprof/rtcprof_python.bat +++ b/OpenRTM_aist/utils/rtcprof/rtcprof_python.bat @@ -5,4 +5,4 @@ rem Intelligent Systems Research Institute, rem National Institute of rem Advanced Industrial Science and Technology (AIST), Japan rem All rights reserved. -%~dp0\python.exe %~dp0\rtcprof.py %* +%~dp0\python.exe %~dp0\rtcprof_python.py %* diff --git a/OpenRTM_aist/utils/rtcprof/rtcprof_python.py b/OpenRTM_aist/utils/rtcprof/rtcprof_python.py new file mode 100644 index 00000000..1ac721a0 --- /dev/null +++ b/OpenRTM_aist/utils/rtcprof/rtcprof_python.py @@ -0,0 +1,122 @@ +#!/usr/bin/env python +# -*- Python -*- +# -*- coding: utf-8 -*- + +## +# @file rtcprof.py +# @brief RT-Component profile dump command +# @date $Date$ +# @author Noriaki Ando and Shinji Kurihara +# +# Copyright (C) 2010 +# Intelligent Systems Research Institute, +# National Institute of +# Advanced Industrial Science and Technology (AIST), Japan +# All rights reserved. +# +# $Id$ + +import sys +import os + +import OpenRTM_aist + + +def main(): + + if len(sys.argv) != 2: + print("usage: ") + print(sys.argv[0], " *.py ") + return + + # file name with full path + fullname = sys.argv[1] + # directory name + dirname = os.path.dirname(sys.argv[1]) + tmp_path = sys.path + sys.path.append(dirname) + + # basename + basename = os.path.basename(sys.argv[1]) + # classname + classname = basename.split(".")[0].lower() + + opts = [] + opts.append("dummy") + opts.append("-o") + opts.append("manager.modules.load_path: " + dirname) + opts.append("-o") + opts.append("logger.enable:NO") + opts.append("-o") + opts.append("manager.corba_servant:NO") + opts.append("-o") + opts.append("timer.enable:NO") + + # Manager initialization + OpenRTM_aist.Manager.init(opts) + mgr = OpenRTM_aist.Manager.instance() + + # loaded profile = old profiles - new profiles + # for old + oldp = mgr.getFactoryProfiles() + + # for new + comp_spec_name = classname + "_spec" + + try: + code = "UTF-8-SIG" + import chardet + import codecs + with open(str(fullname), mode='rb') as f: + code = chardet.detect(f.read())["encoding"] + with codecs.open(str(fullname), "r", encoding=code) as f: + if f.read().find(comp_spec_name) == -1: + return + except BaseException: + pass + try: + imp_file = __import__(basename.split(".")[0]) + except BaseException: + sys.path = tmp_path + return + + comp_spec = getattr(imp_file, comp_spec_name, None) + if not comp_spec: + sys.path = tmp_path + return + + newp = OpenRTM_aist.Properties(defaults_str=comp_spec) + + profs = [] + + exists = False + for o in oldp: + if o.getProperty("implementation_id") == newp.getProperty("implementation_id") and \ + o.getProperty("type_name") == newp.getProperty("type_name") and \ + o.getProperty("description") == newp.getProperty("description") and \ + o.getProperty("version") == newp.getProperty("version"): + exists = True + if not exists: + profs.append(newp) + + # loaded component profile have to be one + if not profs: + print("Load failed. file name: ", fname) + sys.path = tmp_path + return OpenRTM_aist.Properties() + + if len(profs) > 1: + print("One or more modules loaded.") + sys.path = tmp_path + return OpenRTM_aist.Properties() + + keys = profs[0].propertyNames() + for key in keys: + print("%s:%s" % (key, profs[0].getProperty(key))) + + sys.path = tmp_path + return + + +if __name__ == "__main__": + main() diff --git a/OpenRTM_aist/utils/rtcprof/rtcprof_python3 b/OpenRTM_aist/utils/rtcprof/rtcprof_python3 new file mode 100644 index 00000000..21db141d --- /dev/null +++ b/OpenRTM_aist/utils/rtcprof/rtcprof_python3 @@ -0,0 +1,25 @@ +#!/usr/bin/env python3 +# -*- Python -*- +# -*- coding: euc-jp -*- + +## +# @file rtcprof_python +# @brief RT-Component profile dump command +# @date $Date: $ +# @author Noriaki Ando and Shinji Kurihara +# +# Copyright (C) 2010 +# Intelligent Systems Research Institute, +# National Institute of +# Advanced Industrial Science and Technology (AIST), Japan +# All rights reserved. + +import sys +import rtcprof.rtcprof_python + +def main(): + rtcprof.rtcprof_python.main() + return + +if __name__ == "__main__": + main() diff --git a/OpenRTM_aist/utils/rtm-naming/__init__.py b/OpenRTM_aist/utils/rtm-naming/__init__.py index 932b7982..270be2a2 100644 --- a/OpenRTM_aist/utils/rtm-naming/__init__.py +++ b/OpenRTM_aist/utils/rtm-naming/__init__.py @@ -1 +1 @@ -# Empty file +# Empty file diff --git a/OpenRTM_aist/utils/rtm-naming/rtm-naming.py b/OpenRTM_aist/utils/rtm-naming/rtm-naming.py index bbe0c2ae..0742227f 100644 --- a/OpenRTM_aist/utils/rtm-naming/rtm-naming.py +++ b/OpenRTM_aist/utils/rtm-naming/rtm-naming.py @@ -1,29 +1,29 @@ -#!/usr/bin/env python +#!/usr/bin/env python # -*- Python -*- # # @file rtm-naming.py # @brief OpenRTM-aist name server launcher # @date $Date: 2007/10/25 $ # @author Noriaki Ando and Shinji Kurihara -# +# # Copyright (C) 2003-2009 # Task-intelligence Research Group, # Intelligent Systems Research Institute, # National Institute of # Advanced Industrial Science and Technology (AIST), Japan # All rights reserved. -# - -default_orb="omniORB" -orb=default_orb -default_port="2809" - +# -import sys,os,platform +import platform +import os +import sys +default_orb = "omniORB" +orb = default_orb +default_port = "2809" def get_hostname(): - sysinfo = platform.uname() + sysinfo = platform.uname() hostname = sysinfo[1] return str(hostname) @@ -40,11 +40,11 @@ def get_tempdir(): return os.getcwd() -def find_nscmd(ns_cmd, ns_env = ""): +def find_nscmd(ns_cmd, ns_env=""): if sys.platform == "win32": - ns_path = os.path.join(sys.exec_prefix,ns_cmd) + ns_path = os.path.join(sys.exec_prefix, ns_cmd) else: - ns_path = os.path.join(sys.exec_prefix,'bin',ns_cmd) + ns_path = os.path.join(sys.exec_prefix, 'bin', ns_cmd) if os.path.exists(ns_path): return ns_path @@ -75,7 +75,7 @@ def usage(): print("Usage: python rtm-naming.py port_number") -def omninames(port = "", endpoint = ""): +def omninames(port="", endpoint=""): hostname = get_hostname() log_path = get_tempdir() @@ -111,7 +111,7 @@ def omninames(port = "", endpoint = ""): print("Not found omniNames.") sys.exit() - cmd = omniNames + cmd = omniNames cmd += " -start " + str(port) cmd += " -logdir \"" + str(log_path) + "\"" print(cmd) @@ -125,9 +125,9 @@ def omninames(port = "", endpoint = ""): if sys.argv[1] == "-u" or sys.argv[1] == "-h" or sys.argv[1] == "--help": usage() - except: + except BaseException: usage() sys.exit(1) - + if orb == "omniORB": omninames() diff --git a/OpenRTM_aist/uuid.py b/OpenRTM_aist/uuid.py index 681c8d6f..2866191b 100644 --- a/OpenRTM_aist/uuid.py +++ b/OpenRTM_aist/uuid.py @@ -1,9 +1,9 @@ #!/usr/bin/env python -# -*- coding: euc-jp -*- +# -*- coding: utf-8 -*- ## # @file uuid.py -# @brief +# @brief # @date $Date: 2006/06/12 $ # @author Ka-Ping Yee # @@ -25,15 +25,12 @@ long = int - - - ## # @if jp # @class UUID -# @brief UUIDݻ饹 -# -# UUID ξݻ뤿Υ饹 +# @brief UUID保持クラス +# +# 生成した UUID の情報を保持するためのクラス。 # # @since 0.4.0 # @@ -43,7 +40,7 @@ class UUID(object): def __init__(self, hex=None, bytes=None, fields=None, int_value=None, - version=None): + version=None): r"""Create a UUID from either a string of 32 hexadecimal digits, a string of 16 bytes as the 'bytes' argument, a tuple of six integers (32-bit time_low, 16-bit time_mid, 16-bit time_hi_version, @@ -66,7 +63,6 @@ def __init__(self, hex=None, bytes=None, fields=None, int_value=None, overriding bits in the given 'hex', 'bytes', 'fields', or 'int'. """ - if [hex, bytes, fields, int_value].count(None) != 3: raise TypeError('need just one of hex, bytes, fields, or int') if hex: @@ -78,34 +74,35 @@ def __init__(self, hex=None, bytes=None, fields=None, int_value=None, if bytes: if len(bytes) != 16: raise ValueError('bytes is not a 16-char string') + def ord_func(v): if sys.version_info[0] == 3: return ord(chr(v)) else: return ord(v) - int_value = long(('%02x'*16) % tuple(map(ord_func, bytes)), 16) + int_value = long(('%02x' * 16) % tuple(map(ord_func, bytes)), 16) if fields: if len(fields) != 6: raise ValueError('fields is not a 6-tuple') (time_low, time_mid, time_hi_version, clock_seq_hi_variant, clock_seq_low, node) = fields - if not 0 <= time_low < 1<<32: + if not 0 <= time_low < 1 << 32: raise ValueError('field 1 out of range (need a 32-bit value)') - if not 0 <= time_mid < 1<<16: + if not 0 <= time_mid < 1 << 16: raise ValueError('field 2 out of range (need a 16-bit value)') - if not 0 <= time_hi_version < 1<<16: + if not 0 <= time_hi_version < 1 << 16: raise ValueError('field 3 out of range (need a 16-bit value)') - if not 0 <= clock_seq_hi_variant < 1<<8: + if not 0 <= clock_seq_hi_variant < 1 << 8: raise ValueError('field 4 out of range (need an 8-bit value)') - if not 0 <= clock_seq_low < 1<<8: + if not 0 <= clock_seq_low < 1 << 8: raise ValueError('field 5 out of range (need an 8-bit value)') - if not 0 <= node < 1<<48: + if not 0 <= node < 1 << 48: raise ValueError('field 6 out of range (need a 48-bit value)') clock_seq = (clock_seq_hi_variant << 8) | clock_seq_low int_value = ((time_low << 96) | (time_mid << 80) | - (time_hi_version << 64) | (clock_seq << 48) | node) + (time_hi_version << 64) | (clock_seq << 48) | node) if int_value: - if not 0 <= int_value < 1<<128: + if not 0 <= int_value < 1 << 128: raise ValueError('int is out of range (need a 128-bit value)') if version: if not 1 <= version <= 5: @@ -156,7 +153,7 @@ def get_fields(self): def get_time_low(self): return self.int_value >> 96 - + time_low = property(get_time_low) def get_time_mid(self): @@ -166,14 +163,14 @@ def get_time_mid(self): def get_time_hi_version(self): return (self.int_value >> 64) & 0xffff - + time_hi_version = property(get_time_hi_version) def get_clock_seq_hi_variant(self): return (self.int_value >> 56) & 0xff clock_seq_hi_variant = property(get_clock_seq_hi_variant) - + def get_clock_seq_low(self): return (self.int_value >> 48) & 0xff @@ -190,7 +187,7 @@ def get_clock_seq(self): self.clock_seq_low) clock_seq = property(get_clock_seq) - + def get_node(self): return self.int_value & 0xffffffffffff @@ -225,6 +222,7 @@ def get_version(self): version = property(get_version) + def _ifconfig_getnode(): """Get the hardware address on Unix by running ifconfig.""" import os @@ -232,21 +230,23 @@ def _ifconfig_getnode(): pipe = os.popen(os.path.join(dir, 'ifconfig')) for line in pipe: - words = line.lower().split() - for i in range(len(words)): - if words[i] in ['hwaddr', 'ether']: - return int(words[i + 1].replace(':', ''), 16) + words = line.lower().split() + for i in range(len(words)): + if words[i] in ['hwaddr', 'ether']: + return int(words[i + 1].replace(':', ''), 16) + def _ipconfig_getnode(): """Get the hardware address on Windows by running ipconfig.exe.""" - import os, re + import os + import re dirs = ['', r'c:\windows\system32', r'c:\winnt\system32'] try: import ctypes buffer = ctypes.create_string_buffer(300) ctypes.windll.kernel32.GetSystemDirectoryA(buffer, 300) dirs.insert(0, buffer.value.decode('mbcs')) - except: + except BaseException: pass for dir in dirs: try: @@ -258,10 +258,12 @@ def _ipconfig_getnode(): if re.match('([0-9a-f][0-9a-f]-){5}[0-9a-f][0-9a-f]', value): return int(value.replace('-', ''), 16) + def _netbios_getnode(): """Get the hardware address on Windows using NetBIOS calls. See http://support.microsoft.com/kb/118623 for details.""" - import win32wnet, netbios + import win32wnet + import netbios ncb = netbios.NCB() ncb.Command = netbios.NCBENUM ncb.Buffer = adapters = netbios.LANA_ENUM() @@ -284,15 +286,17 @@ def _netbios_getnode(): continue status._unpack() bytes = map(ord, status.adapter_address) - return ((bytes[0]<<40) + (bytes[1]<<32) + (bytes[2]<<24) + - (bytes[3]<<16) + (bytes[4]<<8) + bytes[5]) + return ((bytes[0] << 40) + (bytes[1] << 32) + (bytes[2] << 24) + + (bytes[3] << 16) + (bytes[4] << 8) + bytes[5]) # Thanks to Thomas Heller for ctypes and for his help with its use here. + # If ctypes is available, use it to find system routines for UUID generation. _uuid_generate_random = _uuid_generate_time = _UuidCreate = None try: - import ctypes, ctypes.util + import ctypes + import ctypes.util _buffer = ctypes.create_string_buffer(16) # The uuid_generate_* routines are provided by libuuid on at least @@ -300,7 +304,7 @@ def _netbios_getnode(): for libname in ['uuid', 'c']: try: lib = ctypes.CDLL(ctypes.util.find_library(libname)) - except: + except BaseException: continue if hasattr(lib, 'uuid_generate_random'): _uuid_generate_random = lib.uuid_generate_random @@ -313,30 +317,35 @@ def _netbios_getnode(): # hardware address. These routines are provided by the RPC runtime. try: lib = ctypes.windll.rpcrt4 - except: + except BaseException: lib = None _UuidCreate = getattr(lib, 'UuidCreateSequential', getattr(lib, 'UuidCreate', None)) -except: +except BaseException: pass + def _unixdll_getnode(): """Get the hardware address on Unix using ctypes.""" _uuid_generate_time(_buffer) return UUID(bytes=_buffer.raw).node + def _windll_getnode(): """Get the hardware address on Windows using ctypes.""" if _UuidCreate(_buffer) == 0: return UUID(bytes=_buffer.raw).node + def _random_getnode(): """Get a random node ID, with eighth bit set as suggested by RFC 4122.""" import random - return random.randrange(0, 1<<48) | 0x010000000000 + return random.randrange(0, 1 << 48) | 0x010000000000 + _node = None + def getnode(): """Get the hardware address as a 48-bit integer. The first time this runs, it may launch a separate program, which could be quite slow. If @@ -356,11 +365,12 @@ def getnode(): for getter in getters + [_random_getnode]: try: _node = getter() - except: + except BaseException: continue if _node: return _node + def uuid1(node=None, clock_seq=None): """Generate a UUID from a host ID, sequence number, and the current time. If 'node' is not given, getnode() is used to obtain the hardware @@ -377,10 +387,10 @@ def uuid1(node=None, clock_seq=None): nanoseconds = int(time.time() * 1e9) # 0x01b21dd213814000 is the number of 100-ns intervals between the # UUID epoch 1582-10-15 00:00:00 and the Unix epoch 1970-01-01 00:00:00. - timestamp = int(nanoseconds/100) + 0x01b21dd213814000 + timestamp = int(nanoseconds / 100) + 0x01b21dd213814000 if clock_seq is None: import random - clock_seq = random.randrange(1<<14) # instead of stable storage + clock_seq = random.randrange(1 << 14) # instead of stable storage time_low = timestamp & 0xffffffff time_mid = (timestamp >> 32) & 0xffff time_hi_version = (timestamp >> 48) & 0x0fff @@ -391,12 +401,14 @@ def uuid1(node=None, clock_seq=None): return UUID(fields=(time_low, time_mid, time_hi_version, clock_seq_hi_variant, clock_seq_low, node), version=1) + def uuid3(namespace, name): """Generate a UUID from the MD5 hash of a namespace UUID and a name.""" import md5 hash = md5.md5(namespace.bytes + name).digest() return UUID(bytes=hash[:16], version=3) + def uuid4(): """Generate a random UUID.""" @@ -409,11 +421,12 @@ def uuid4(): try: import os return UUID(bytes=os.urandom(16), version=4) - except: + except BaseException: import random bytes = [chr(random.randrange(256)) for i in range(16)] return UUID(bytes=bytes, version=4) + def uuid5(namespace, name): """Generate a UUID from the SHA-1 hash of a namespace UUID and a name.""" import sha @@ -422,6 +435,7 @@ def uuid5(namespace, name): # The following standard UUIDs are for use with uuid3() or uuid5(). + NAMESPACE_DNS = UUID('6ba7b810-9dad-11d1-80b4-00c04fd430c8') NAMESPACE_URL = UUID('6ba7b811-9dad-11d1-80b4-00c04fd430c8') NAMESPACE_OID = UUID('6ba7b812-9dad-11d1-80b4-00c04fd430c8') diff --git a/OpenRTM_aist/version.py b/OpenRTM_aist/version.py index dcb17272..9f2379cc 100644 --- a/OpenRTM_aist/version.py +++ b/OpenRTM_aist/version.py @@ -1,6 +1,6 @@ #!/usr/bin/env python -# -*- coding: euc-jp -*- +# -*- coding: utf-8 -*- -openrtm_name = "OpenRTM-aist-1.2.0" -openrtm_version = "1.2.0" -corba_name = "omniORB" +openrtm_name = "OpenRTM-aist-2.0.0" +openrtm_version = "2.0.0" +corba_name = "omniORB" diff --git a/README b/README deleted file mode 100644 index 4232a33f..00000000 --- a/README +++ /dev/null @@ -1,96 +0,0 @@ ------------------------------ - OpenRTM-aist-1.0 Python ------------------------------ - (2010ǯ0331) - - -ǧѤưĶ ---------------- - OS : - - Vine Linux 4.0, 4.1, 4.2 - - Fedora 10, 11 - - Ubuntu 8.04, 8.10, 9.04, 9.10 - - Debian 4.0, 5.0 - - Windows XP Professional, Windows Vista, Windows7 - - -ɬפʤ ----------- - -Python(version: 2.4ʾ) - -omniORBpy(version: 2.7ʾ) - - -ĶѿPYTHONPATH --------------- - (Vine Linux) - cshξ : setenv PYTHONPATH /usr/lib/python2.4/site-packages - bashξ : export PYTHONPATH=/usr/lib/python2.4/site-packages - /usr/lib/python2.3βսϡ󥹥ȡ뤷Ķˤ碌Ʋ - - (WindowsXP) - [ȥѥͥ] -> [ƥ(ƥΥץѥƥ)] -> [ܺ - ] -> [Ķѿ(N)] -> [(N)] - - ѿ̾(N) : PYTHONPATH - ѿ(V) : C:\Python24\Lib\site-packages - - -󥹥ȡˡ ----------------- -ܥѥå Distutils (Python Distribution Utilities) -Ƥޤ - - 󥹥ȡ˴ĶѿPYTHONPATHꤵƤǧƤ - - - (Vine Linux) - $ printenv PYTHONPATH - - -[Vine Linuxξ] - - 1. ֤β - $ tar xvzf OpenRTM-aist-Python-1.0.0.tar.gz - - 2. ӥ - $ cd OpenRTM-aist-Python-1.0.0 - $ python setup.py build - - 3. 󥹥ȡ - $ su - # python setup.py install - - -[Windows XPξ] - - 1. ֤β - OpenRTM-aist-Python-1.0.0.zipॽեȤˤƲषƲ - - 2. ӥ - > cd <֤Ÿե> - > python setup.py build - - 3. 󥹥ȡ - > python setup.py install - - - 1. 󥹥ȡ顼ưؼˤäƥ󥹥ȡԤäƲ - - - omniORBpy󥹥ȡ뤵Ƥʤ硢ʲμǥ󥹥ȡ - ԤäƲ - - (1) ѥåΥ - ʲΥڡ"omniORBpy-2.7-win32-python2.4.zip" - ɤƲ - - URL: http://omniorb.sourceforge.net/download.html - - (2) ֤β - ॽեȤˤzipեβԤäƲ - - (3) եΥԡ - omniORBpy-2.7\bin\x86_win32\*.dll C:\Python24\Lib\site-packages إԡ - omniORBpy-2.7\lib\x86_win32\*.pyd C:\Python24\Lib\site-packages إԡ - omniORBpy-2.7\lib\python\* C:\Python24\Lib\site-packages إԡ - diff --git a/README.jp.md b/README.jp.md new file mode 100644 index 00000000..bc6a369c --- /dev/null +++ b/README.jp.md @@ -0,0 +1,28 @@ +これは OpenRTM-aist-Python のリリースバージョン 2.0.0 です。 +OpenRTM-aist-Python はデュアルライセンスのオープンソースのRTミドルウエアです。 + +OpenRTM の設定、ビルド、インストールおよび RTコンポーネントの作成を行う前に、 +以下の文書をよくお読みください。 + +files: +README - このファイルの英語版 +README.jp - このファイル +COPYRIGHT - 著作権表示およびライセンスについて +COPYING.LIB - LGPL (GNU劣等一般公衆利用許諾契約書) +INSTALL - インストール手順(英語版) +INSTALL.jp - インストール手順 + +このプロジェクトは、[コントリビュータ行動規範](.github/CODE_OF_CONDUCT.md)を遵守します。 +受け入れられない振る舞いがあれば n-ando@aist.go.jp まで報告してください。 + +# ドキュメントとIssueトラック +- [Official Site](http://openrtm.org) +- [Issue Tracking](https://github.com/OpenRTM/OpenRTM-aist-Python/issues) + +# 貢献方法 +[the contlibute guideline](https://github.com/OpenRTM/OpenRTM-aist-Python/wiki/How-to-Contribute)をお読みください. + +- [バグ報告](https://github.com/OpenRTM/OpenRTM-aist-Python/wiki/How-to-Contribute#バグ報告) +- [機能追加の提案](https://github.com/OpenRTM/OpenRTM-aist-Python/wiki/How-to-Contribute#機能追加の提案) +- [問い合わせ](https://github.com/OpenRTM/OpenRTM-aist-Python/wiki/How-to-Contribute#問い合わせ) +- [Pull Request](https://github.com/OpenRTM/OpenRTM-aist-Python/wiki/How-to-Contribute#pull-request) diff --git a/README.md b/README.md new file mode 100644 index 00000000..d028b085 --- /dev/null +++ b/README.md @@ -0,0 +1,27 @@ +This is a release of OpenRTM-aist-Python-2.0.0, dual-license open source RT-Middleware. + +Carefully read the following files before you configure, build, install +OpenRTM and develop RT-Components. + +files: +README - This file +README.jp - Japanese Version of This file +COPYRIGHT - Copyright Notice and License Information +COPYING.LIB - LGPL Terms and Conditions +INSTALL - Installation Instructions +INSTALL.jp - Installation Instructions (Japanese) + +This project adheres to the Contributor Covenant [code of conduct](.github/CODE_OF_CONDUCT.md). +Please report unacceptable behavior to n-ando@aist.go.jp . + +# Resources +- [Official Site](http://openrtm.org) +- [Issue Tracking](https://github.com/OpenRTM/OpenRTM-aist-Python/issues) + +# How To Contribute +Please read [the contlibute guideline](https://github.com/OpenRTM/OpenRTM-aist-Python/wiki/How-to-Contribute). + +- [Bug Report](https://github.com/OpenRTM/OpenRTM-aist-Python/wiki/How-to-Contribute#バグ報告) +- [Feature Request](https://github.com/OpenRTM/OpenRTM-aist-Python/wiki/How-to-Contribute#機能追加の提案) +- [Inquiry](https://github.com/OpenRTM/OpenRTM-aist-Python/wiki/How-to-Contribute#問い合わせ) +- [Pull Request](https://github.com/OpenRTM/OpenRTM-aist-Python/wiki/How-to-Contribute#pull-request) diff --git a/packages/rpm/openrtm-aist_py3.spec.in b/packages/rpm/openrtm-aist_py3.spec.in new file mode 100755 index 00000000..a30a5009 --- /dev/null +++ b/packages/rpm/openrtm-aist_py3.spec.in @@ -0,0 +1,127 @@ +#------------------------------------------------------------ +# +# @file RPM spec file for OpenRTM-aist-Python +# @author Noriaki Ando +# +# $Id$ +# + +%define pkgname OpenRTM-aist-Python +%define version __VERSION__ +%define short_version __SHORT_VERSION__ +%define distname __DISTNAME__ +%define builddir %{_topdir}/BUILD/%{distname} +%define pkgver 0 +%define _unpackaged_files_terminate_build 0 +%global debug_package %{nil} + +#------------------------------------------------------------ +# Package information +Name: OpenRTM-aist-Python +Version: %{version} +Release: %{pkgver}.%{distname} +Summary: Python modules for OpenRTM-aist +Group: Applications/System +License: LGPL +URL: http://openrtm.org +Source0: %{pkgname}-%{version}.tar.gz +Vendor: AIST + +Prefix: %{_prefix} +Buildroot: %{_tmppath}/%{pkgname}-%{version}-%{release}-root + +Requires: python3 +Requires: omniORBpy-devel + +BuildRequires: python3-devel + +%description +OpenRTM-aist is a reference implementation of RTC (Robotic Technology +Component Version 1.1, formal/12-09-01) specification which is OMG +standard (http://www.omg.org/spec/RTC/). OpenRTM-aist includes +RT-Middleware runtime environment and RTC framework. The OMG standard +defines a component model and certain important infrastructure +services applicable to the domain of robotics software +development. OpenRTM-aist is being developed and distributed by +National Institute of Advanced Industrial Science and Technology +(AIST), Japan. Please see http://www.openrtm.org/ for more detail. + +#------------------------------------------------------------ +# doc package +%package doc +Summary: Documentation +Group: Development/Libraries +%description doc +Class reference manual of OpenRTM-aist. + +#------------------------------------------------------------ +# example package +%package example +Summary: Example +Group: Development/Libraries +Requires: OpenRTM-aist-Python +%description example +Example components and sources of OpenRTM-aist. + +#------------------------------------------------------------ +# prep section +%prep +%{__rm} -rf %{buildroot} +%setup + +#------------------------------------------------------------ +# build section +%build +%{__python3} setup.py build_core +%{__python3} setup.py build_example + +#------------------------------------------------------------ +# install section +%install +%{__python3} setup.py install --root=%{buildroot} --record=INSTALLED_FILES + +#------------------------------------------------------------ +# clean section +%clean +#rm -rf %{buildroot} + +#------------------------------------------------------------ +# core files section +%files +%defattr(-,root,root) +%{python3_sitelib}/OpenRTM-aist.pth +%{python3_sitelib}/OpenRTM_aist_Python-%{version}-py%{python_version}.egg-info +%{python3_sitelib}/OpenRTM_aist +%attr(755,root,root) %{_bindir}/* + +#------------------------------------------------------------ +# doc package file list +%files doc +%defattr(-,root,root,-) +%{_datadir}/openrtm-%{short_version}/doc/python/ + + +#------------------------------------------------------------ +# example package file list +%files example +%defattr(755,root,root,-) +%{_datadir}/openrtm-%{short_version}/components/python/ + + +#------------------------------------------------------------ +# changelog section +%changelog +* Wed Nov 16 2016 1.2.0-0._distname +- 1.2.0-RELEASE + +* Tue Feb 23 2016 1.1.2 +- 1.1.2-RELEASE + +* Wed Oct 21 2015 1.1.1 +- 1.1.1-RELEASE + +* Wed May 01 2013 1.1.0 +- 1.1.0-RELEASE + +* Thu Sep 27 2007 Noriaki Ando - 0.4.1-1._distname +- The second public release version of OpenRTM-aist-0.4.1. diff --git a/packages/rpm/rpm_build.sh b/packages/rpm/rpm_build.sh index 87b4f877..81f1c057 100755 --- a/packages/rpm/rpm_build.sh +++ b/packages/rpm/rpm_build.sh @@ -41,7 +41,7 @@ check_distribution() # Check the Fedora version if test "x$dist_name" = "x" && test -f /etc/fedora-release ; then dist_name=`cat /etc/fedora-release`-`uname -m` - dist_key=`sed -e 's/.[^0-9]*\([0-9]\+\).*/fc\1/' /etc/fedora-release` + dist_key=`sed -e 's/.[^0-9]*\([0-9]\+\).*/\1/' /etc/fedora-release` FEDORA_VER=$dist_key fi #Check the Debian version @@ -91,6 +91,15 @@ create_rpmbuilddir() export BUILD_DIR=`pwd` } +rewrite_chebang_to_python3() +{ + if [ $FEDORA_VER -ge 29 ] ; then + find ../../OpenRTM_aist -name "*.py" | xargs -I {} sh -c "sed -i -e '1 s/env python/python3/g' {}" + find ../../OpenRTM_aist/utils/rtcd -name "rtcd_python" | xargs -I {} sh -c "sed -i -e '1 s/env python/python3/g' {}" + find ../../OpenRTM_aist/utils/rtcprof -name "rtcprof_python" | xargs -I {} sh -c "sed -i -e '1 s/env python/python3/g' {}" + fi +} + create_source_package() { cd ../../ @@ -106,10 +115,10 @@ copy_source_package() create_spec_file() { - if test "x$FEDORA_VER" = "xfc19" ; then - sed "s/__DISTNAME__/$DIST_KEY/g" openrtm-aist_fc19.spec.in > openrtm-aist.spec.1 - else + if [ $FEDORA_VER -lt 29 ] ; then sed "s/__DISTNAME__/$DIST_KEY/g" openrtm-aist.spec.in > openrtm-aist.spec.1 + else + sed "s/__DISTNAME__/$DIST_KEY/g" openrtm-aist_py3.spec.in > openrtm-aist.spec.1 fi sed "s/__VERSION__/$VERSION/g" openrtm-aist.spec.1 > openrtm-aist.spec.2 sed "s/__SHORT_VERSION__/$SHORT_VERSION/g" openrtm-aist.spec.2 > openrtm-aist.spec.3 @@ -144,6 +153,7 @@ check_distribution get_version_info create_rpmbuilddir +rewrite_chebang_to_python3 create_source_package copy_source_package create_spec_file diff --git a/setup.py b/setup.py index 5c553cca..e4f7f2b8 100755 --- a/setup.py +++ b/setup.py @@ -1,4 +1,5 @@ #!/usr/bin/env python +# -*- coding: utf-8 -*- # # @file setup.py # @author Noriaki Ando @@ -9,7 +10,7 @@ # Advanced Industrial Science and Technology (AIST), Japan All # rights reserved. # -#------------------------------------------------------------ +# ------------------------------------------------------------ # How to update this script: # # 1. Change version number for "pkg_*_version" @@ -44,7 +45,7 @@ # This script installs python module files and others according to the # following rules # -# install: installing all files. +# install: installing all files. # install_core: installing core libraries. # core modules: -> /lib/pythonX.Y/dist-pacakges/OpenRTM_aist/ # OpenRTM-aist.pth @@ -73,26 +74,52 @@ # sdist_tgz: create tgz type source distribution packages # sdist_zip: create zip type source distribution packages # -#------------------------------------------------------------ +# ------------------------------------------------------------ -#============================== +# ============================== # Package version definition -#============================== -pkg_major_version = "1" -pkg_minor_version = "2" -pkg_revision_num = "0" +# ============================== +from distutils.command.install_egg_info import install_egg_info as _install_egg_info +from distutils.command.install_scripts import install_scripts as _install_scripts +from distutils.command.install_lib import install_lib as _install_lib +from distutils.command.build_py import build_py as _build_py +import os.path +import os +from distutils.dist import Distribution +from distutils.filelist import FileList +from distutils.command.install_data import install_data +from distutils.command.install_lib import install_lib +from distutils.command.install import install +from distutils.command.sdist import sdist +from distutils.command.clean import clean +from distutils.command.build import build +from distutils import version +from distutils import errors +from distutils import dir_util +from distutils import util +from distutils import log +from distutils import cmd +from distutils.core import Command +from distutils import core +import shutil +import glob +import string +import sys +pkg_major_version = "2" +pkg_minor_version = "0" +pkg_revision_num = "0" -#============================================================ +# ============================================================ # MODIFICATION IS ALLOWED IF IT IS NEED TO MODIFY. -#============================================================ -pkg_name = "OpenRTM-aist-Python" -pkg_shortver = pkg_major_version + "." + pkg_minor_version -pkg_version = pkg_shortver + "." + pkg_revision_num -pkg_desc = "Python modules for OpenRTM-aist-" + pkg_shortver -pkg_author = "Shinji Kurihara and Noriaki Ando" -pkg_email = "n-ando@aist.go.jp" -pkg_url = "http://openrtm.org/" -pkg_license = "LGPL" +# ============================================================ +pkg_name = "OpenRTM-aist-Python" +pkg_shortver = pkg_major_version + "." + pkg_minor_version +pkg_version = pkg_shortver + "." + pkg_revision_num +pkg_desc = "Python modules for OpenRTM-aist-" + pkg_shortver +pkg_author = "Shinji Kurihara and Noriaki Ando" +pkg_email = "n-ando@aist.go.jp" +pkg_url = "http://openrtm.org/" +pkg_license = "LGPL" pkg_long_desc = """\ OpenRTM-aist is a reference implementation of RT-Middleware and RT-Component framework. RT-Component (RTC) is a component model @@ -102,7 +129,7 @@ distributed by Intelligent Systems Research Institute, National Institute of Advanced Industrial Science and Technology (AIST), Japan. Please see http://openrtm.org/ for more details.""" -pkg_usage = """\ +pkg_usage = """\ Common commands: (see '--help-commands' for more) setup.py build will compile IDL files and documentation @@ -122,157 +149,163 @@ setup.py sdist_zip will create zip source package """ -#============================================================ +# ============================================================ # importing modules -#============================================================ -import os,os.path -import sys -import string +# ============================================================ if sys.version_info[0] == 2: - import commands + import commands else: - import subprocess as commands -import glob -import shutil -from distutils import core -from distutils.core import Command -from distutils import cmd -from distutils import log -from distutils import util -from distutils import dir_util -from distutils import errors -from distutils import version -from distutils.command.build import build -from distutils.command.clean import clean -from distutils.command.sdist import sdist -from distutils.command.install import install -from distutils.command.install_lib import install_lib -from distutils.command.install_data import install_data + import subprocess -#------------------------------------------------------------ +# ------------------------------------------------------------ # Getting OS type -#------------------------------------------------------------ +# ------------------------------------------------------------ + + def os_is(): - if os.sep == '/': - return "unix" - elif os.sep == ':': - return None - elif os.sep == '\\': - return "win32" - else: - return None - -#============================================================ + if os.sep == '/': + return "unix" + elif os.sep == ':': + return None + elif os.sep == '\\': + return "win32" + else: + return None + + +# ============================================================ # Directory settings for file list -#============================================================ -current_dir = os.getcwd() +# ============================================================ +current_dir = os.getcwd() # # core settings # module_dir = "OpenRTM_aist" openrtm_core_packages = [ - "OpenRTM_aist", - "OpenRTM_aist.RTM_IDL", - "OpenRTM_aist.RTM_IDL.OpenRTM", - "OpenRTM_aist.RTM_IDL.OpenRTM__POA", - "OpenRTM_aist.RTM_IDL.RTC", - "OpenRTM_aist.RTM_IDL.RTC__POA", - "OpenRTM_aist.RTM_IDL.RTM", - "OpenRTM_aist.RTM_IDL.RTM__POA", - "OpenRTM_aist.RTM_IDL.SDOPackage", - "OpenRTM_aist.RTM_IDL.SDOPackage__POA", - "OpenRTM_aist.RTM_IDL.device_interfaces", - "OpenRTM_aist.RTM_IDL._GlobalIDL", - "OpenRTM_aist.RTM_IDL._GlobalIDL__POA", - ] + "OpenRTM_aist", + "OpenRTM_aist.RTM_IDL", + "OpenRTM_aist.RTM_IDL.OpenRTM", + "OpenRTM_aist.RTM_IDL.OpenRTM__POA", + "OpenRTM_aist.RTM_IDL.RTC", + "OpenRTM_aist.RTM_IDL.RTC__POA", + "OpenRTM_aist.RTM_IDL.RTM", + "OpenRTM_aist.RTM_IDL.RTM__POA", + "OpenRTM_aist.RTM_IDL.SDOPackage", + "OpenRTM_aist.RTM_IDL.SDOPackage__POA", + "OpenRTM_aist.RTM_IDL.device_interfaces", + "OpenRTM_aist.RTM_IDL._GlobalIDL", + "OpenRTM_aist.RTM_IDL._GlobalIDL__POA", + "OpenRTM_aist.RTM_IDL.CSP", + "OpenRTM_aist.RTM_IDL.CSP__POA", + "OpenRTM_aist.RTM_IDL.Img", + "OpenRTM_aist.RTM_IDL.Img__POA", + "OpenRTM_aist.RTM_IDL.JARA_ARM", + "OpenRTM_aist.RTM_IDL.JARA_ARM__POA", +] openrtm_ext_packages = [ - "OpenRTM_aist.ext", - "OpenRTM_aist.ext.sdo", - "OpenRTM_aist.ext.sdo.observer", - "OpenRTM_aist.ext.ssl", - ] + "OpenRTM_aist.ext", + "OpenRTM_aist.ext.sdo", + "OpenRTM_aist.ext.sdo.observer", + "OpenRTM_aist.ext.ssl", + "OpenRTM_aist.ext.logger", + "OpenRTM_aist.ext.logger.fluentbit_stream", + "OpenRTM_aist.ext.transport", + "OpenRTM_aist.ext.transport.ROSTransport", + "OpenRTM_aist.ext.transport.ROS2Transport", + "OpenRTM_aist.ext.transport.OpenSplice", + "OpenRTM_aist.ext.local_service", + "OpenRTM_aist.ext.local_service.nameservice_file", + "OpenRTM_aist.ext.extended_fsm", + "OpenRTM_aist.ext.fsm4rtc_observer", +] openrtm_utils_packages = [ - "OpenRTM_aist.utils", - "OpenRTM_aist.utils.rtcd", - "OpenRTM_aist.utils.rtcprof", - "OpenRTM_aist.utils.rtc-template", - "OpenRTM_aist.utils.rtm-naming", - ] + "OpenRTM_aist.utils", + "OpenRTM_aist.utils.rtcd", + "OpenRTM_aist.utils.rtcprof", + "OpenRTM_aist.utils.rtc-template", + "OpenRTM_aist.utils.rtm-naming", +] # # IDL settings # -baseidl_dir = "OpenRTM_aist/RTM_IDL" +baseidl_dir = "OpenRTM_aist/RTM_IDL" baseidl_files = [ - "BasicDataType.idl", - "DataPort.idl", - "ExtendedDataTypes.idl", - "InterfaceDataTypes.idl", - "Manager.idl", - "OpenRTM.idl", - "RTC.idl", - "SDOPackage.idl", - "SharedMemory.idl", - "IORProfile.idl", - "../ext/sdo/observer/ComponentObserver.idl", - "ExtendedFsmService.idl", - "DataPort_OpenRTM.idl" - ] -baseidl_mods = ["RTM", "RTC", "SDOPackage", "OpenRTM"] -baseidl_path = os.path.normpath(current_dir + "/" + baseidl_dir) + "BasicDataType.idl", + "DataPort.idl", + "ExtendedDataTypes.idl", + "InterfaceDataTypes.idl", + "Manager.idl", + "OpenRTM.idl", + "RTC.idl", + "SDOPackage.idl", + "SharedMemory.idl", + "IORProfile.idl", + "../ext/sdo/observer/ComponentObserver_OpenRTM.idl", + "ExtendedFsmService.idl", + "DataPort_OpenRTM.idl", + "CSPPort.idl", + "../ext/fsm4rtc_observer/ComponentObserver.idl", + "ext/rtmCamera/CameraCommonInterface.idl", + "ext/rtmManipulator/ManipulatorCommonInterface_Common.idl", + "ext/rtmManipulator/ManipulatorCommonInterface_DataTypes.idl", + "ext/rtmManipulator/ManipulatorCommonInterface_Middle.idl" +] +baseidl_mods = ["RTM", "RTC", "SDOPackage", "OpenRTM"] +baseidl_path = os.path.normpath(current_dir + "/" + baseidl_dir) # # scripts settings # -pkg_scripts_unix = ['OpenRTM_aist/utils/rtcd/rtcd_python', - 'OpenRTM_aist/utils/rtcprof/rtcprof_python'] -pkg_scripts_win32 = ['OpenRTM_aist/utils/rtcd/rtcd.py', -# 'OpenRTM_aist/utils/rtcd/rtcd_python.exe', +pkg_scripts_unix = ['OpenRTM_aist/utils/rtcd/rtcd_python', + 'OpenRTM_aist/utils/rtcprof/rtcprof_python'] +pkg_scripts_win32 = ['OpenRTM_aist/utils/rtcd/rtcd_python.py', + # 'OpenRTM_aist/utils/rtcd/rtcd_python.exe', 'OpenRTM_aist/utils/rtcd/rtcd_python.bat', 'OpenRTM_aist/utils/rtcprof/rtcprof_python.py', 'OpenRTM_aist/utils/rtcprof/rtcprof_python.bat'] -pkg_data_files_unix = [] +pkg_data_files_unix = [] rtcd_python = 'OpenRTM_aist/utils/rtcd/rtcd_python.exe' if os.path.exists(rtcd_python): - pkg_data_files_win32 = [("Scripts", [rtcd_python])] + pkg_data_files_win32 = [("Scripts", [rtcd_python])] else: - pkg_data_files_win32 = [("Scripts", [])] + pkg_data_files_win32 = [("Scripts", [])] # # ext modules # -ext_dir = "OpenRTM_aist/ext" -target_ext_dir = "lib/openrtm-" + pkg_shortver + "/python" -ext_match_regex_unix = ".*\.(py|conf|sh|xml|idl)$" -ext_match_regex_win32 = ".*\.(py|conf|bat|xml|idl)$" +ext_dir = "OpenRTM_aist/ext" +target_ext_dir = "lib/openrtm-" + pkg_shortver + "/python" +ext_match_regex_unix = r".*\.(py|conf|sh|xml|idl)$" +ext_match_regex_win32 = r".*\.(py|conf|bat|xml|idl)$" # # examples # -example_dir = "OpenRTM_aist/examples" -target_example_dir = "share/openrtm-" + pkg_shortver + "/components/python" -example_match_regex = ".*\.(py|conf|sh|xml|idl)$" -example_path = os.path.normpath(current_dir + "/" + example_dir) +example_dir = "OpenRTM_aist/examples" +target_example_dir = "share/openrtm-" + pkg_shortver + "/components/python" +example_match_regex = r".*\.(py|conf|sh|xml|idl)$" +example_path = os.path.normpath(current_dir + "/" + example_dir) # # documents # -document_dir = "OpenRTM_aist/docs" -target_doc_dir = "share/openrtm-" + pkg_shortver + "/doc/python" -document_match_regex = ".*\.(css|gif|png|html||hhc|hhk|hhp)$" -document_path = os.path.normpath(current_dir + "/" + document_dir) +document_dir = "OpenRTM_aist/docs" +target_doc_dir = "share/openrtm-" + pkg_shortver + "/doc/python" +document_match_regex = r".*\.(css|gif|png|html||hhc|hhk|hhp|js)$" +document_path = os.path.normpath(current_dir + "/" + document_dir) -################################################################################ +########################################################################## # DO NOT CHANGE FROM HERE !!! -################################################################################ +########################################################################## -#============================================================ +# ============================================================ # utility functions -#============================================================ -#------------------------------------------------------------ +# ============================================================ +# ------------------------------------------------------------ # Creating file list to be passed to distutils.core.setup # # This function creates the following file list. @@ -292,40 +325,42 @@ def os_is(): # Now we assume that the following arguments are set to create_filelist() # start_path = OpenRTM_aist/examples/ # subs_path = OpenRTM_aist/examples/ -# target_path = share/openrtm-1.2/components/python/ +# target_path = share/openrtm-2.0/components/python/ # regex_match = .*\.py$ # # A file matched: OpenRTM_aist/examples/SimpleIO/ConsoleIn.py # "OpenRTM_aist/examples" (subs_path) is removed from the # path. obtained file path: SimpleIO/ConsoleIn.py is merged # target_path, and then we get final target path -# /share/openrtm-1.2/components/python/SimpleIO/ConsoleIn.py +# /share/openrtm-2.0/components/python/SimpleIO/ConsoleIn.py # -#------------------------------------------------------------ -def create_filelist(start_path, subs_path, target_path, regex_match, -not_included_modules=[]): - filelist = [] - temp_hash = {} - if start_path[-1] != "/": start_path += "/" - if subs_path[-1] != "/": subs_path += "/" - import re - for root, dirs, files in os.walk(start_path): - if root.replace("\\","/") in not_included_modules: - continue - for filename in files: - if re.match(regex_match, filename): - subdir = re.sub(subs_path, "", root) - dir_name = os.path.join(target_path, subdir) - file_path = os.path.join(root, filename) - if not dir_name in temp_hash: - temp_hash[dir_name] = [] - temp_hash[dir_name].append(file_path) - - for k in temp_hash.keys(): - filelist.append((k, temp_hash[k])) - return filelist - -#------------------------------------------------------------ +# ------------------------------------------------------------ +def create_filelist(start_path, subs_path, target_path, regex_match, + not_included_modules=[]): + filelist = [] + temp_hash = {} + if start_path[-1] != "/": + start_path += "/" + if subs_path[-1] != "/": + subs_path += "/" + import re + for root, dirs, files in os.walk(start_path): + if root.replace("\\", "/") in not_included_modules: + continue + for filename in files: + if re.match(regex_match, filename): + subdir = re.sub(subs_path, "", root) + dir_name = os.path.join(target_path, subdir) + file_path = os.path.join(root, filename) + if not dir_name in temp_hash: + temp_hash[dir_name] = [] + temp_hash[dir_name].append(file_path) + + for k in temp_hash.keys(): + filelist.append((k, temp_hash[k])) + return filelist + +# ------------------------------------------------------------ # convert_file_code() # # converting file encoding and CR-LF code @@ -340,134 +375,172 @@ def create_filelist(start_path, subs_path, target_path, regex_match, # -- converting to UNIX/Mac OS X code (EUC/LF) -- # convert_file_code("hoge.txt", "euc_jp", "\n") # -#------------------------------------------------------------ +# ------------------------------------------------------------ + + def convert_file_code(file_name, char_code, crlf_code, hint=None): - import codecs - import os - def conv_encoding(data, to_enc="utf_8"): - default_lookup = ('utf_8', - 'euc_jp', 'euc_jis_2004', 'euc_jisx0213', - 'shift_jis', 'shift_jis_2004','shift_jisx0213', - 'iso2022jp', 'iso2022_jp_1', 'iso2022_jp_2', - 'iso2022_jp_3', 'iso2022_jp_ext', - 'latin_1', 'ascii') - if hint: - lookup = (hint, 'ascii', 'shift_jis', 'euc_jp') - else: - lookup = default_lookup - for encoding in lookup: - try: - data = data.decode(encoding) - break - except: - pass - if isinstance(data, unicode): - return data.encode(to_enc) - else: - return data - # end of conv_encoding() - temp_fname = file_name + ".tmp" - outfd = open(temp_fname, "w") - def coding_name(coding): - conv = {"euc_jp": "euc-jp", - "shift_jis": "cp932"} - if coding in conv: - return conv[coding] - return coding - sub_str = "coding: " + coding_name(char_code) - import re - infd = open(file_name, "r") - for line in infd: - try: - outdata = conv_encoding(line.rstrip('\r\n'), char_code) - outdata = re.sub("coding: [^ ]*", sub_str, outdata) - outdata = re.sub("encoding: [^ ]*", sub_str, outdata) - except Exception as e: - print("Exception cought in " + file_name + ": " + line) - print(e) - infd.close() - outfd.close() - os.remove(temp_fname) - sys.exit(1) - outfd.write(outdata + crlf_code) - infd.close() - os.remove(file_name) - outfd.close() - os.rename(temp_fname, file_name) - -#------------------------------------------------------------ + import codecs + import os + + def conv_encoding(data, to_enc="utf_8"): + default_lookup = ('utf_8', + 'euc_jp', 'euc_jis_2004', 'euc_jisx0213', + 'shift_jis', 'shift_jis_2004', 'shift_jisx0213', + 'iso2022jp', 'iso2022_jp_1', 'iso2022_jp_2', + 'iso2022_jp_3', 'iso2022_jp_ext', + 'latin_1', 'ascii') + if hint: + lookup = (hint, 'ascii', 'shift_jis', 'euc_jp') + else: + lookup = default_lookup + for encoding in lookup: + try: + data = data.decode(encoding) + break + except BaseException: + pass + if isinstance(data, unicode): + return data.encode(to_enc) + else: + return data + # end of conv_encoding() + temp_fname = file_name + ".tmp" + outfd = open(temp_fname, "w") + + def coding_name(coding): + conv = {"euc_jp": "euc-jp", + "shift_jis": "cp932"} + if coding in conv: + return conv[coding] + return coding + sub_str = "coding: " + coding_name(char_code) + import re + infd = open(file_name, "r") + for line in infd: + try: + outdata = conv_encoding(line.rstrip('\r\n'), char_code) + outdata = re.sub("coding: [^ ]*", sub_str, outdata) + outdata = re.sub("encoding: [^ ]*", sub_str, outdata) + except Exception as e: + print("Exception cought in " + file_name + ": " + line) + print(e) + infd.close() + outfd.close() + os.remove(temp_fname) + sys.exit(1) + outfd.write(outdata + crlf_code) + infd.close() + os.remove(file_name) + outfd.close() + os.rename(temp_fname, file_name) + +# ------------------------------------------------------------ # compiling IDL files -#------------------------------------------------------------ +# ------------------------------------------------------------ + + def compile_idl(idl_compiler, include_dirs, current_dir, files): - """ - compile_idl - - idl_compiler: [string] path to omniidl executable - - include_dirs: [list] path list for include directories - - current_dir : [string] directory where stubs are generated - - files : [list] IDL file list - """ - # create command and option list - cmd = [idl_compiler, "-bpython"] - if include_dirs: cmd += ["-I" + inc for inc in include_dirs] - if current_dir : cmd += ["-C" + current_dir] - cmd += files - # function to be given dist.util.execute - def exec_idl_compile(cmd_str): - #cmdline = string.join(cmd_str) - cmdline = " ".join(cmd_str) - if os_is() == "win32": - os.system(cmdline) - return - log.info(cmdline) - status, output = commands.getstatusoutput(cmdline) - log.info(output) - if status != 0: - raise errors.DistutilsExecError("Return status of %s is %d" % - (cmd, status)) - return - # compile IDL by using dist.util.execute - util.execute(exec_idl_compile, [cmd], - "Generating python stubs from IDL files") - -#------------------------------------------------------------ + """ + compile_idl + - idl_compiler: [string] path to omniidl executable + - include_dirs: [list] path list for include directories + - current_dir : [string] directory where stubs are generated + - files : [list] IDL file list + """ + # create command and option list + cmd = [idl_compiler, "-bpython"] + if include_dirs: + cmd += ["-I" + inc for inc in include_dirs] + if current_dir: + cmd += ["-C" + current_dir] + cmd += files + # function to be given dist.util.execute + + def exec_idl_compile(cmd_str): + #cmdline = string.join(cmd_str) + cmdline = " ".join(cmd_str) + if os_is() == "win32": + os.system(cmdline) + return + log.info(cmdline) + if sys.version_info[0] == 2: + status, output = commands.getstatusoutput(cmdline) + log.info(output) + else: + try: + proc = subprocess.run( + cmdline, + shell=True, + check=True, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE) + status = 0 + log.info(proc.stdout.decode("UTF-8")) + except BaseException: + status = 1 + if status != 0: + raise errors.DistutilsExecError("Return status of %s is %d" % + (cmd, status)) + return + # compile IDL by using dist.util.execute + util.execute(exec_idl_compile, [cmd], + "Generating python stubs from IDL files") + +# ------------------------------------------------------------ # compiling doxygen -#------------------------------------------------------------ +# ------------------------------------------------------------ + + def create_doc(doxygen_conf, target_dir): - """ - create_doc - - doxygen_conf: [string] path to Doxygen's conf file - - target_dir : [string] directory to where doxygen generates documentation - """ - def exec_doxygen(cmd): - # remove target dir - if os.path.exists(target_dir + "/html/index.html"): - return - if os.path.exists(target_dir): - shutil.rmtree(target_dir) - - #cmdline = string.join(cmd) - cmdline = " ".join(cmd) - if os_is() == "win32": - os.system(cmdline) - return - log.info(cmdline) - status, output = commands.getstatusoutput(cmdline) - log.info(output) - if status != 0: - raise errors.DistutilsExecError("Return status of %s is %d" % - (cmd, status)) - return - # compile IDL by using dist.util.execute - docdir = os.path.dirname(doxygen_conf) - tmp = os.getcwd() - os.chdir(docdir) - cmd = ["doxygen", doxygen_conf] - util.execute(exec_doxygen, [cmd], - "Generating documentation") - os.chdir(tmp) - - -#============================================================ + """ + create_doc + - doxygen_conf: [string] path to Doxygen's conf file + - target_dir : [string] directory to where doxygen generates documentation + """ + def exec_doxygen(cmd): + # remove target dir + if os.path.exists(target_dir + "/html/index.html"): + return + if os.path.exists(target_dir): + shutil.rmtree(target_dir) + + #cmdline = string.join(cmd) + cmdline = " ".join(cmd) + if os_is() == "win32": + os.system(cmdline) + return + log.info(cmdline) + if sys.version_info[0] == 2: + status, output = commands.getstatusoutput(cmdline) + log.info(output) + else: + try: + proc = subprocess.run( + cmdline, + shell=True, + check=True, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE) + status = 0 + log.info(proc.stdout.decode("UTF-8")) + except BaseException: + status = 1 + + if status != 0: + raise errors.DistutilsExecError("Return status of %s is %d" % + (cmd, status)) + return + # compile IDL by using dist.util.execute + docdir = os.path.dirname(doxygen_conf) + tmp = os.getcwd() + os.chdir(docdir) + cmd = ["doxygen", doxygen_conf] + util.execute(exec_doxygen, [cmd], + "Generating documentation") + os.chdir(tmp) + + +# ============================================================ # command classes # # build @@ -487,381 +560,403 @@ def exec_doxygen(cmd): # install_core # install_example # install_doc -#============================================================ +# ============================================================ -#============================================================ +# ============================================================ # build command family -#============================================================ -#------------------------------------------------------------ +# ============================================================ +# ------------------------------------------------------------ # "build" command -#------------------------------------------------------------ +# ------------------------------------------------------------ class build_all(build): - """ - This class is a parent command of build to compile IDL into CORBA - stubs and to make documentation. - """ - description = "Generate python CORBA stubs from IDL files and documentation" - user_options = build.user_options + [ - ("omniidl=", "i", - "omniidl program used to build stubs"), - ("idldir=", "i", - "directory where IDL files reside"), - ("doxygen=", "d", - "path to doxygen executable") + """ + This class is a parent command of build to compile IDL into CORBA + stubs and to make documentation. + """ + description = "Generate python CORBA stubs from IDL files and documentation" + user_options = build.user_options + [ + ("omniidl=", "i", + "omniidl program used to build stubs"), + ("idldir=", "i", + "directory where IDL files reside"), + ("doxygen=", "d", + "path to doxygen executable") ] - def initialize_options(self): - self.omniidl = None - self.idldir = None - self.doxygen = None - build.initialize_options(self) - return - - def finalize_options(self): - build.finalize_options(self) - if not self.omniidl: - self.omniidl = "omniidl" - - if not self.idldir: - self.idldir = baseidl_path - - if not self.doxygen: - self.doxygen = "doxygen" - # Transferring options to sub-commands - self.distribution.omniidl = self.omniidl - self.distribution.idldir = self.idldir - self.distribution.doxygen = self.doxygen - - def run(self): - return build.run(self) - - # sub_command member attribute - sub_commands = [ - ('build_core', None), - ('build_doc', None), - ('build_example', None) + def initialize_options(self): + self.omniidl = None + self.idldir = None + self.doxygen = None + build.initialize_options(self) + return + + def finalize_options(self): + build.finalize_options(self) + if not self.omniidl: + self.omniidl = "omniidl" + + if not self.idldir: + self.idldir = baseidl_path + + if not self.doxygen: + self.doxygen = "doxygen" + # Transferring options to sub-commands + self.distribution.omniidl = self.omniidl + self.distribution.idldir = self.idldir + self.distribution.doxygen = self.doxygen + + def run(self): + return build.run(self) + + # sub_command member attribute + sub_commands = [ + ('build_core', None), + ('build_doc', None), + ('build_example', None) ] -#------------------------------------------------------------ +# ------------------------------------------------------------ # "build_sub" base class -#------------------------------------------------------------ +# ------------------------------------------------------------ + + class build_sub(build): - """ - This class is a subcommand base class for compiling IDL and - generating stubs. - """ - description = "Generate python CORBA stubs for core from IDL files" - user_options = build.user_options + [ - ("omniidl=", "i", - "omniidl program used to build stubs"), - ("idldir=", "d", - "directory where IDL files reside") + """ + This class is a subcommand base class for compiling IDL and + generating stubs. + """ + description = "Generate python CORBA stubs for core from IDL files" + user_options = build.user_options + [ + ("omniidl=", "i", + "omniidl program used to build stubs"), + ("idldir=", "d", + "directory where IDL files reside") ] - def initialize_options(self): - self.idldir = None - self.omniidl = None - build.initialize_options(self) - - def finalize_options(self): - build.finalize_options(self) - if not self.omniidl: - if hasattr(self.distribution, "omniidl"): - self.omniidl = self.distribution.omniidl - else: - self.omniidl = "omniidl" - - if not self.idldir: - if hasattr(self.distribution, "idldir"): - self.idldir = self.distribution.idldir - else: + def initialize_options(self): self.idldir = None - return - -#------------------------------------------------------------ + self.omniidl = None + build.initialize_options(self) + + def finalize_options(self): + build.finalize_options(self) + if not self.omniidl: + if hasattr(self.distribution, "omniidl"): + self.omniidl = self.distribution.omniidl + else: + self.omniidl = "omniidl" + + if not self.idldir: + if hasattr(self.distribution, "idldir"): + self.idldir = self.distribution.idldir + else: + self.idldir = None + return + +# ------------------------------------------------------------ # "build_core" sub command -#------------------------------------------------------------ +# ------------------------------------------------------------ + + class build_core(build_sub): - """ - This class is a subcommand of build command. The command compiles - IDL files and generates CORBA stubs for core packages. - """ - description = "Generate python CORBA stubs for core packages." - def run(self): - idldir = baseidl_path - include_dirs = [baseidl_path] - current_dir = baseidl_path - idl_files = [os.path.join(baseidl_path, f) for f in baseidl_files] - compile_idl(self.omniidl, include_dirs, current_dir, idl_files) - self.run_command("build_py") + """ + This class is a subcommand of build command. The command compiles + IDL files and generates CORBA stubs for core packages. + """ + description = "Generate python CORBA stubs for core packages." + + def run(self): + idldir = baseidl_path + include_dirs = [baseidl_path] + current_dir = baseidl_path + idl_files = [os.path.join(baseidl_path, f) for f in baseidl_files] + compile_idl(self.omniidl, include_dirs, current_dir, idl_files) + self.run_command("build_py") + -from distutils.command.build_py import build_py as _build_py class build_py(_build_py): - """ - This class is a subcommand of build_core command. The command copies - modules into build directory. - # This class was created for only copying OpenRTM-aist.pth file - """ - description = "Copying pure python modules into build directory." - def run(self): - # Preparering rtcprof_python.py for Windows - if os_is() == "win32": - rtcprof_dir = os.path.join("OpenRTM_aist", "utils", "rtcprof/") - self.copy_file(os.path.join(rtcprof_dir, "rtcprof.py"), - os.path.join(rtcprof_dir, "rtcprof_python.py")) - _build_py.run(self) - # copying OpenRTM-aist.pth file - self.copy_file(os.path.join(".", "OpenRTM-aist.pth"), self.build_lib, - preserve_mode=False) - -#------------------------------------------------------------ + """ + This class is a subcommand of build_core command. The command copies + modules into build directory. + # This class was created for only copying OpenRTM-aist.pth file + """ + description = "Copying pure python modules into build directory." + + def run(self): + _build_py.run(self) + # copying OpenRTM-aist.pth file + self.copy_file(os.path.join(".", "OpenRTM-aist.pth"), self.build_lib, + preserve_mode=False) + +# ------------------------------------------------------------ # "build_example" sub command -#------------------------------------------------------------ +# ------------------------------------------------------------ + + class build_example(build_sub): - """ - This class is a subcommand of build command. The command compiles - IDL files and generates CORBA stubs for example packages. - """ - description = "Generate python CORBA stubs for example packages." - def run(self): - # SimpleService - current_dir = os.path.join(example_dir, "SimpleService") - include_dirs = [baseidl_path, current_dir] - idl_files = [os.path.join(current_dir, "MyService.idl")] - compile_idl(self.omniidl, include_dirs, current_dir, idl_files) - - # AutoTest - current_dir = os.path.join(example_dir, "AutoTest") - include_dirs = [baseidl_path, current_dir] - idl_files = [os.path.join(current_dir, "AutoTestService.idl")] - compile_idl(self.omniidl, include_dirs, current_dir, idl_files) - - -#------------------------------------------------------------ + """ + This class is a subcommand of build command. The command compiles + IDL files and generates CORBA stubs for example packages. + """ + description = "Generate python CORBA stubs for example packages." + + def run(self): + # SimpleService + current_dir = os.path.join(example_dir, "SimpleService") + include_dirs = [baseidl_path, current_dir] + idl_files = [os.path.join(current_dir, "MyService.idl")] + compile_idl(self.omniidl, include_dirs, current_dir, idl_files) + + # AutoTest + current_dir = os.path.join(example_dir, "AutoTest") + include_dirs = [baseidl_path, current_dir] + idl_files = [os.path.join(current_dir, "AutoTestService.idl")] + compile_idl(self.omniidl, include_dirs, current_dir, idl_files) + + +# ------------------------------------------------------------ # "build_doc" sub command -#------------------------------------------------------------ +# ------------------------------------------------------------ class build_doc(build): - """ - This class is a subcommand of build command. The command generates - documentation from source code. - """ - description = "Generate documentation from source code." - user_options = build.user_options + [ - ("doxygen=", "d", - "path to doxygen executable") + """ + This class is a subcommand of build command. The command generates + documentation from source code. + """ + description = "Generate documentation from source code." + user_options = build.user_options + [ + ("doxygen=", "d", + "path to doxygen executable") ] - def initialize_options(self): - self.doxygen = None - build.initialize_options(self) - - def finalize_options(self): - build.finalize_options(self) - if not self.doxygen: - if hasattr(self.distribution, "doxygen"): - self.doxygen = self.distribution.doxygen - else: - self.doxygen = "doxygen" - - def build_doc_common(self, infile, outfile): - f_input = open(infile, 'r') - src = f_input.read() - f_input.close() - dst = src.replace("__VERSION__", pkg_version) - f_output = open(outfile, 'w') - f_output.write(dst) - f_output.close() - - def run(self): - conf_in_file = os.path.normpath(document_path + "/Doxyfile_en.in") - conf_file = os.path.normpath(document_path + "/Doxyfile_en") - self.build_doc_common(conf_in_file, conf_file) - target_dir = os.path.normpath(document_path + "/ClassReference-en") - create_doc(conf_file, target_dir) - - conf_in_file = os.path.normpath(document_path + "/Doxyfile_jp.in") - conf_file = os.path.normpath(document_path + "/Doxyfile_jp") - self.build_doc_common(conf_in_file, conf_file) - target_dir = os.path.normpath(document_path + "/ClassReference-jp") - create_doc(conf_file, target_dir) - - -#============================================================ + def initialize_options(self): + self.doxygen = None + build.initialize_options(self) + + def finalize_options(self): + build.finalize_options(self) + if not self.doxygen: + if hasattr(self.distribution, "doxygen"): + self.doxygen = self.distribution.doxygen + else: + self.doxygen = "doxygen" + + def build_doc_common(self, infile, outfile): + f_input = open(infile, 'r') + src = f_input.read() + f_input.close() + dst = src.replace("__VERSION__", pkg_version) + f_output = open(outfile, 'w') + f_output.write(dst) + f_output.close() + + def run(self): + conf_in_file = os.path.normpath(document_path + "/Doxyfile_en.in") + conf_file = os.path.normpath(document_path + "/Doxyfile_en") + self.build_doc_common(conf_in_file, conf_file) + target_dir = os.path.normpath(document_path + "/ClassReference-en") + create_doc(conf_file, target_dir) + + conf_in_file = os.path.normpath(document_path + "/Doxyfile_jp.in") + conf_file = os.path.normpath(document_path + "/Doxyfile_jp") + self.build_doc_common(conf_in_file, conf_file) + target_dir = os.path.normpath(document_path + "/ClassReference-jp") + create_doc(conf_file, target_dir) + + +# ============================================================ # clean command classes -#============================================================ +# ============================================================ def remove_stubs(target_dir, idl_files, module_names): - files = [f.replace(".idl", "_idl.py") for f in idl_files] - for f in files: - file_path = os.path.normpath(target_dir + "/" + f) - if os.path.exists(file_path): - os.remove(file_path) - # removing dirs and dirs and MyDistribution.example_files # -pkg_example_files = create_filelist(example_dir, - example_dir, - target_example_dir, - example_match_regex, - ["OpenRTM_aist/examples/NXTRTC"]) +pkg_example_files = create_filelist(example_dir, + example_dir, + target_example_dir, + example_match_regex, + ["OpenRTM_aist/examples/NXTRTC"]) # @@ -1029,43 +1134,43 @@ def __init__(self, attrs=None): document_match_regex) pkg_document_files = pkg_document_files_en + pkg_document_files_jp -#============================== +# ============================== # main -#============================== -core.setup(name = pkg_name, - version = pkg_version, - description = pkg_desc, - author = pkg_author, - author_email = pkg_email, - url = pkg_url, - long_description = pkg_long_desc, - license = pkg_license, - distclass = MyDistribution, - cmdclass = { "build": build_all, - "build_core": build_core, - "build_py": build_py, - "build_example": build_example, - "build_doc": build_doc, - "clean": clean_all, - "clean_core": clean_core, - "clean_example": clean_example, - "clean_doc": clean_doc, - "install": install_all, - "install_core_lib": install_core_lib, - "install_core_scripts": install_core_scripts, - "install_core_egg_info": install_core_egg_info, - "install_core": install_core, - "install_example": install_example, - "install_doc": install_doc, - "sdist": sdist_all, - "sdist_tgz": sdist_tgz, - "sdist_zip": sdist_zip, - }, - packages = pkg_packages, - package_dir = {module_dir: module_dir}, - package_data = pkg_package_data_files, - scripts = pkg_scripts, - data_files = pkg_data_files, - example_files = pkg_example_files, - document_files = pkg_document_files, +# ============================== +core.setup(name=pkg_name, + version=pkg_version, + description=pkg_desc, + author=pkg_author, + author_email=pkg_email, + url=pkg_url, + long_description=pkg_long_desc, + license=pkg_license, + distclass=MyDistribution, + cmdclass={"build": build_all, + "build_core": build_core, + "build_py": build_py, + "build_example": build_example, + "build_doc": build_doc, + "clean": clean_all, + "clean_core": clean_core, + "clean_example": clean_example, + "clean_doc": clean_doc, + "install": install_all, + "install_core_lib": install_core_lib, + "install_core_scripts": install_core_scripts, + "install_core_egg_info": install_core_egg_info, + "install_core": install_core, + "install_example": install_example, + "install_doc": install_doc, + "sdist": sdist_all, + "sdist_tgz": sdist_tgz, + "sdist_zip": sdist_zip, + }, + packages=pkg_packages, + package_dir={module_dir: module_dir}, + package_data=pkg_package_data_files, + scripts=pkg_scripts, + data_files=pkg_data_files, + example_files=pkg_example_files, + document_files=pkg_document_files, )