[zb4osgi-changeset] [scm] ZigBee 4 OSGi repository change: r229 - in /projects/zb4osgi/sandbox/miguel.llorente/zibgee.tsb.driver: ./ src/ src/main/ src/main/java/ src/main/java/it/ src/main/java/it/cnr/ src/main/java/it/cnr/isti/ src/main/java/it/cnr/isti/zigbee/ src/main/java/it/cnr/isti/zigbee/dongle/ src/main/java/it/cnr/isti/zigbee/dongle/tsb/ src/main/java/it/cnr/isti/zigbee/dongle/tsb/impl/ src/main/resources/ src/test/ src/test/java/ src/test/resources/
scm-notify at zb4osgi.aaloa.org
scm-notify at zb4osgi.aaloa.org
Fri May 20 11:42:59 CEST 2011
Author: miguel.llorente
Date: Fri May 20 11:42:58 2011
New Revision: 229
Log:
initial import.
Added:
projects/zb4osgi/sandbox/miguel.llorente/zibgee.tsb.driver/
projects/zb4osgi/sandbox/miguel.llorente/zibgee.tsb.driver/LICENSE
projects/zb4osgi/sandbox/miguel.llorente/zibgee.tsb.driver/LICENSE.RxTx
projects/zb4osgi/sandbox/miguel.llorente/zibgee.tsb.driver/LICENSE.ZigBee
projects/zb4osgi/sandbox/miguel.llorente/zibgee.tsb.driver/NOTICE
projects/zb4osgi/sandbox/miguel.llorente/zibgee.tsb.driver/pom.xml
projects/zb4osgi/sandbox/miguel.llorente/zibgee.tsb.driver/src/
projects/zb4osgi/sandbox/miguel.llorente/zibgee.tsb.driver/src/main/
projects/zb4osgi/sandbox/miguel.llorente/zibgee.tsb.driver/src/main/java/
projects/zb4osgi/sandbox/miguel.llorente/zibgee.tsb.driver/src/main/java/it/
projects/zb4osgi/sandbox/miguel.llorente/zibgee.tsb.driver/src/main/java/it/cnr/
projects/zb4osgi/sandbox/miguel.llorente/zibgee.tsb.driver/src/main/java/it/cnr/isti/
projects/zb4osgi/sandbox/miguel.llorente/zibgee.tsb.driver/src/main/java/it/cnr/isti/zigbee/
projects/zb4osgi/sandbox/miguel.llorente/zibgee.tsb.driver/src/main/java/it/cnr/isti/zigbee/dongle/
projects/zb4osgi/sandbox/miguel.llorente/zibgee.tsb.driver/src/main/java/it/cnr/isti/zigbee/dongle/tsb/
projects/zb4osgi/sandbox/miguel.llorente/zibgee.tsb.driver/src/main/java/it/cnr/isti/zigbee/dongle/tsb/Activator.java (with props)
projects/zb4osgi/sandbox/miguel.llorente/zibgee.tsb.driver/src/main/java/it/cnr/isti/zigbee/dongle/tsb/impl/
projects/zb4osgi/sandbox/miguel.llorente/zibgee.tsb.driver/src/main/java/it/cnr/isti/zigbee/dongle/tsb/impl/DriverTSB.java (with props)
projects/zb4osgi/sandbox/miguel.llorente/zibgee.tsb.driver/src/main/java/it/cnr/isti/zigbee/dongle/tsb/impl/DriverTSBi.java (with props)
projects/zb4osgi/sandbox/miguel.llorente/zibgee.tsb.driver/src/main/java/it/cnr/isti/zigbee/dongle/tsb/impl/DriverTSBm.java (with props)
projects/zb4osgi/sandbox/miguel.llorente/zibgee.tsb.driver/src/main/java/it/cnr/isti/zigbee/dongle/tsb/impl/DriverTSBn.java (with props)
projects/zb4osgi/sandbox/miguel.llorente/zibgee.tsb.driver/src/main/java/it/cnr/isti/zigbee/dongle/tsb/impl/MasterResetGUI.java (with props)
projects/zb4osgi/sandbox/miguel.llorente/zibgee.tsb.driver/src/main/resources/
projects/zb4osgi/sandbox/miguel.llorente/zibgee.tsb.driver/src/test/
projects/zb4osgi/sandbox/miguel.llorente/zibgee.tsb.driver/src/test/java/
projects/zb4osgi/sandbox/miguel.llorente/zibgee.tsb.driver/src/test/resources/
Added: projects/zb4osgi/sandbox/miguel.llorente/zibgee.tsb.driver/LICENSE
==============================================================================
--- projects/zb4osgi/sandbox/miguel.llorente/zibgee.tsb.driver/LICENSE (added)
+++ projects/zb4osgi/sandbox/miguel.llorente/zibgee.tsb.driver/LICENSE Fri May 20 11:42:58 2011
@@ -1,0 +1,202 @@
+
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "[]"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+ Copyright [yyyy] [name of copyright owner]
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
Added: projects/zb4osgi/sandbox/miguel.llorente/zibgee.tsb.driver/LICENSE.RxTx
==============================================================================
--- projects/zb4osgi/sandbox/miguel.llorente/zibgee.tsb.driver/LICENSE.RxTx (added)
+++ projects/zb4osgi/sandbox/miguel.llorente/zibgee.tsb.driver/LICENSE.RxTx Fri May 20 11:42:58 2011
@@ -1,0 +1,563 @@
+/*-------------------------------------------------------------------------
+| RXTX License v 2.1 - LGPL v 2.1 + Linking Over Controlled Interface.
+| RXTX is a native interface to serial ports in java.
+| Copyright 1997-2007 by Trent Jarvi tjarvi at qbang.org and others who
+| actually wrote it. See individual source files for more information.
+|
+| A copy of the LGPL v 2.1 may be found at
+| http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html on November 21st 2007
+| A copy is here for your convenience.
+|
+| This library is free software; you can redistribute it and/or
+| modify it under the terms of the GNU Lesser General Public
+| License as published by the Free Software Foundation; either
+| version 2.1 of the License, or (at your option) any later version.
+|
+| This library is distributed in the hope that it will be useful,
+| but WITHOUT ANY WARRANTY; without even the implied warranty of
+| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+| Lesser General Public License for more details.
+|
+| An executable that contains no derivative of any portion of RXTX, but
+| is designed to work with RXTX by being dynamically linked with it,
+| is considered a "work that uses the Library" subject to the terms and
+| conditions of the GNU Lesser General Public License.
+|
+| The following has been added to the RXTX License to remove
+| any confusion about linking to RXTX. We want to allow in part what
+| section 5, paragraph 2 of the LGPL does not permit in the special
+| case of linking over a controlled interface. The intent is to add a
+| Java Specification Request or standards body defined interface in the
+| future as another exception but one is not currently available.
+|
+| http://www.fsf.org/licenses/gpl-faq.html#LinkingOverControlledInterface
+|
+| As a special exception, the copyright holders of RXTX give you
+| permission to link RXTX with independent modules that communicate with
+| RXTX solely through the Sun Microsytems CommAPI interface version 2,
+| regardless of the license terms of these independent modules, and to copy
+| and distribute the resulting combined work under terms of your choice,
+| provided that every copy of the combined work is accompanied by a complete
+| copy of the source code of RXTX (the version of RXTX used to produce the
+| combined work), being distributed under the terms of the GNU Lesser General
+| Public License plus this exception. An independent module is a
+| module which is not derived from or based on RXTX.
+|
+| Note that people who make modified versions of RXTX are not obligated
+| to grant this special exception for their modified versions; it is
+| their choice whether to do so. The GNU Lesser General Public License
+| gives permission to release a modified version without this exception; this
+| exception also makes it possible to release a modified version which
+| carries forward this exception.
+|
+| You should have received a copy of the GNU Lesser General Public
+| License along with this library; if not, write to the Free
+| Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+| All trademarks belong to their respective owners.
+--------------------------------------------------------------------------*/
+
+The original GNU Lesser General Public License Follows.
+
+
+ GNU LESSER GENERAL PUBLIC LICENSE
+ Version 2.1, February 1999
+
+ Copyright (C) 1991, 1999 Free Software Foundation, Inc.
+ 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+[This is the first released version of the Lesser GPL. It also counts
+ as the successor of the GNU Library Public License, version 2, hence
+ the version number 2.1.]
+
+ Preamble
+
+ The licenses for most software are designed to take away your
+freedom to share and change it. By contrast, the GNU General Public
+Licenses are intended to guarantee your freedom to share and change
+free software--to make sure the software is free for all its users.
+
+ This license, the Lesser General Public License, applies to some
+specially designated software packages--typically libraries--of the
+Free Software Foundation and other authors who decide to use it. You
+can use it too, but we suggest you first think carefully about whether
+this license or the ordinary General Public License is the better
+strategy to use in any particular case, based on the explanations below.
+
+ When we speak of free software, we are referring to freedom of use,
+not price. Our General Public Licenses are designed to make sure that
+you have the freedom to distribute copies of free software (and charge
+for this service if you wish); that you receive source code or can get
+it if you want it; that you can change the software and use pieces of
+it in new free programs; and that you are informed that you can do
+these things.
+
+ To protect your rights, we need to make restrictions that forbid
+distributors to deny you these rights or to ask you to surrender these
+rights. These restrictions translate to certain responsibilities for
+you if you distribute copies of the library or if you modify it.
+
+ For example, if you distribute copies of the library, whether gratis
+or for a fee, you must give the recipients all the rights that we gave
+you. You must make sure that they, too, receive or can get the source
+code. If you link other code with the library, you must provide
+complete object files to the recipients, so that they can relink them
+with the library after making changes to the library and recompiling
+it. And you must show them these terms so they know their rights.
+
+ We protect your rights with a two-step method: (1) we copyright the
+library, and (2) we offer you this license, which gives you legal
+permission to copy, distribute and/or modify the library.
+
+ To protect each distributor, we want to make it very clear that
+there is no warranty for the free library. Also, if the library is
+modified by someone else and passed on, the recipients should know
+that what they have is not the original version, so that the original
+author's reputation will not be affected by problems that might be
+introduced by others.
+
+ Finally, software patents pose a constant threat to the existence of
+any free program. We wish to make sure that a company cannot
+effectively restrict the users of a free program by obtaining a
+restrictive license from a patent holder. Therefore, we insist that
+any patent license obtained for a version of the library must be
+consistent with the full freedom of use specified in this license.
+
+ Most GNU software, including some libraries, is covered by the
+ordinary GNU General Public License. This license, the GNU Lesser
+General Public License, applies to certain designated libraries, and
+is quite different from the ordinary General Public License. We use
+this license for certain libraries in order to permit linking those
+libraries into non-free programs.
+
+ When a program is linked with a library, whether statically or using
+a shared library, the combination of the two is legally speaking a
+combined work, a derivative of the original library. The ordinary
+General Public License therefore permits such linking only if the
+entire combination fits its criteria of freedom. The Lesser General
+Public License permits more lax criteria for linking other code with
+the library.
+
+ We call this license the "Lesser" General Public License because it
+does Less to protect the user's freedom than the ordinary General
+Public License. It also provides other free software developers Less
+of an advantage over competing non-free programs. These disadvantages
+are the reason we use the ordinary General Public License for many
+libraries. However, the Lesser license provides advantages in certain
+special circumstances.
+
+ For example, on rare occasions, there may be a special need to
+encourage the widest possible use of a certain library, so that it becomes
+a de-facto standard. To achieve this, non-free programs must be
+allowed to use the library. A more frequent case is that a free
+library does the same job as widely used non-free libraries. In this
+case, there is little to gain by limiting the free library to free
+software only, so we use the Lesser General Public License.
+
+ In other cases, permission to use a particular library in non-free
+programs enables a greater number of people to use a large body of
+free software. For example, permission to use the GNU C Library in
+non-free programs enables many more people to use the whole GNU
+operating system, as well as its variant, the GNU/Linux operating
+system.
+
+ Although the Lesser General Public License is Less protective of the
+users' freedom, it does ensure that the user of a program that is
+linked with the Library has the freedom and the wherewithal to run
+that program using a modified version of the Library.
+
+ The precise terms and conditions for copying, distribution and
+modification follow. Pay close attention to the difference between a
+"work based on the library" and a "work that uses the library". The
+former contains code derived from the library, whereas the latter must
+be combined with the library in order to run.
+
+ GNU LESSER GENERAL PUBLIC LICENSE
+ TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
+
+ 0. This License Agreement applies to any software library or other
+program which contains a notice placed by the copyright holder or
+other authorized party saying it may be distributed under the terms of
+this Lesser General Public License (also called "this License").
+Each licensee is addressed as "you".
+
+ A "library" means a collection of software functions and/or data
+prepared so as to be conveniently linked with application programs
+(which use some of those functions and data) to form executables.
+
+ The "Library", below, refers to any such software library or work
+which has been distributed under these terms. A "work based on the
+Library" means either the Library or any derivative work under
+copyright law: that is to say, a work containing the Library or a
+portion of it, either verbatim or with modifications and/or translated
+straightforwardly into another language. (Hereinafter, translation is
+included without limitation in the term "modification".)
+
+ "Source code" for a work means the preferred form of the work for
+making modifications to it. For a library, complete source code means
+all the source code for all modules it contains, plus any associated
+interface definition files, plus the scripts used to control compilation
+and installation of the library.
+
+ Activities other than copying, distribution and modification are not
+covered by this License; they are outside its scope. The act of
+running a program using the Library is not restricted, and output from
+such a program is covered only if its contents constitute a work based
+on the Library (independent of the use of the Library in a tool for
+writing it). Whether that is true depends on what the Library does
+and what the program that uses the Library does.
+
+ 1. You may copy and distribute verbatim copies of the Library's
+complete source code as you receive it, in any medium, provided that
+you conspicuously and appropriately publish on each copy an
+appropriate copyright notice and disclaimer of warranty; keep intact
+all the notices that refer to this License and to the absence of any
+warranty; and distribute a copy of this License along with the
+Library.
+
+ You may charge a fee for the physical act of transferring a copy,
+and you may at your option offer warranty protection in exchange for a
+fee.
+
+ 2. You may modify your copy or copies of the Library or any portion
+of it, thus forming a work based on the Library, and copy and
+distribute such modifications or work under the terms of Section 1
+above, provided that you also meet all of these conditions:
+
+ a) The modified work must itself be a software library.
+
+ b) You must cause the files modified to carry prominent notices
+ stating that you changed the files and the date of any change.
+
+ c) You must cause the whole of the work to be licensed at no
+ charge to all third parties under the terms of this License.
+
+ d) If a facility in the modified Library refers to a function or a
+ table of data to be supplied by an application program that uses
+ the facility, other than as an argument passed when the facility
+ is invoked, then you must make a good faith effort to ensure that,
+ in the event an application does not supply such function or
+ table, the facility still operates, and performs whatever part of
+ its purpose remains meaningful.
+
+ (For example, a function in a library to compute square roots has
+ a purpose that is entirely well-defined independent of the
+ application. Therefore, Subsection 2d requires that any
+ application-supplied function or table used by this function must
+ be optional: if the application does not supply it, the square
+ root function must still compute square roots.)
+
+These requirements apply to the modified work as a whole. If
+identifiable sections of that work are not derived from the Library,
+and can be reasonably considered independent and separate works in
+themselves, then this License, and its terms, do not apply to those
+sections when you distribute them as separate works. But when you
+distribute the same sections as part of a whole which is a work based
+on the Library, the distribution of the whole must be on the terms of
+this License, whose permissions for other licensees extend to the
+entire whole, and thus to each and every part regardless of who wrote
+it.
+
+Thus, it is not the intent of this section to claim rights or contest
+your rights to work written entirely by you; rather, the intent is to
+exercise the right to control the distribution of derivative or
+collective works based on the Library.
+
+In addition, mere aggregation of another work not based on the Library
+with the Library (or with a work based on the Library) on a volume of
+a storage or distribution medium does not bring the other work under
+the scope of this License.
+
+ 3. You may opt to apply the terms of the ordinary GNU General Public
+License instead of this License to a given copy of the Library. To do
+this, you must alter all the notices that refer to this License, so
+that they refer to the ordinary GNU General Public License, version 2,
+instead of to this License. (If a newer version than version 2 of the
+ordinary GNU General Public License has appeared, then you can specify
+that version instead if you wish.) Do not make any other change in
+these notices.
+
+ Once this change is made in a given copy, it is irreversible for
+that copy, so the ordinary GNU General Public License applies to all
+subsequent copies and derivative works made from that copy.
+
+ This option is useful when you wish to copy part of the code of
+the Library into a program that is not a library.
+
+ 4. You may copy and distribute the Library (or a portion or
+derivative of it, under Section 2) in object code or executable form
+under the terms of Sections 1 and 2 above provided that you accompany
+it with the complete corresponding machine-readable source code, which
+must be distributed under the terms of Sections 1 and 2 above on a
+medium customarily used for software interchange.
+
+ If distribution of object code is made by offering access to copy
+from a designated place, then offering equivalent access to copy the
+source code from the same place satisfies the requirement to
+distribute the source code, even though third parties are not
+compelled to copy the source along with the object code.
+
+ 5. A program that contains no derivative of any portion of the
+Library, but is designed to work with the Library by being compiled or
+linked with it, is called a "work that uses the Library". Such a
+work, in isolation, is not a derivative work of the Library, and
+therefore falls outside the scope of this License.
+
+ However, linking a "work that uses the Library" with the Library
+creates an executable that is a derivative of the Library (because it
+contains portions of the Library), rather than a "work that uses the
+library". The executable is therefore covered by this License.
+Section 6 states terms for distribution of such executables.
+
+ When a "work that uses the Library" uses material from a header file
+that is part of the Library, the object code for the work may be a
+derivative work of the Library even though the source code is not.
+Whether this is true is especially significant if the work can be
+linked without the Library, or if the work is itself a library. The
+threshold for this to be true is not precisely defined by law.
+
+ If such an object file uses only numerical parameters, data
+structure layouts and accessors, and small macros and small inline
+functions (ten lines or less in length), then the use of the object
+file is unrestricted, regardless of whether it is legally a derivative
+work. (Executables containing this object code plus portions of the
+Library will still fall under Section 6.)
+
+ Otherwise, if the work is a derivative of the Library, you may
+distribute the object code for the work under the terms of Section 6.
+Any executables containing that work also fall under Section 6,
+whether or not they are linked directly with the Library itself.
+
+ 6. As an exception to the Sections above, you may also combine or
+link a "work that uses the Library" with the Library to produce a
+work containing portions of the Library, and distribute that work
+under terms of your choice, provided that the terms permit
+modification of the work for the customer's own use and reverse
+engineering for debugging such modifications.
+
+ You must give prominent notice with each copy of the work that the
+Library is used in it and that the Library and its use are covered by
+this License. You must supply a copy of this License. If the work
+during execution displays copyright notices, you must include the
+copyright notice for the Library among them, as well as a reference
+directing the user to the copy of this License. Also, you must do one
+of these things:
+
+ a) Accompany the work with the complete corresponding
+ machine-readable source code for the Library including whatever
+ changes were used in the work (which must be distributed under
+ Sections 1 and 2 above); and, if the work is an executable linked
+ with the Library, with the complete machine-readable "work that
+ uses the Library", as object code and/or source code, so that the
+ user can modify the Library and then relink to produce a modified
+ executable containing the modified Library. (It is understood
+ that the user who changes the contents of definitions files in the
+ Library will not necessarily be able to recompile the application
+ to use the modified definitions.)
+
+ b) Use a suitable shared library mechanism for linking with the
+ Library. A suitable mechanism is one that (1) uses at run time a
+ copy of the library already present on the user's computer system,
+ rather than copying library functions into the executable, and (2)
+ will operate properly with a modified version of the library, if
+ the user installs one, as long as the modified version is
+ interface-compatible with the version that the work was made with.
+
+ c) Accompany the work with a written offer, valid for at
+ least three years, to give the same user the materials
+ specified in Subsection 6a, above, for a charge no more
+ than the cost of performing this distribution.
+
+ d) If distribution of the work is made by offering access to copy
+ from a designated place, offer equivalent access to copy the above
+ specified materials from the same place.
+
+ e) Verify that the user has already received a copy of these
+ materials or that you have already sent this user a copy.
+
+ For an executable, the required form of the "work that uses the
+Library" must include any data and utility programs needed for
+reproducing the executable from it. However, as a special exception,
+the materials to be distributed need not include anything that is
+normally distributed (in either source or binary form) with the major
+components (compiler, kernel, and so on) of the operating system on
+which the executable runs, unless that component itself accompanies
+the executable.
+
+ It may happen that this requirement contradicts the license
+restrictions of other proprietary libraries that do not normally
+accompany the operating system. Such a contradiction means you cannot
+use both them and the Library together in an executable that you
+distribute.
+
+ 7. You may place library facilities that are a work based on the
+Library side-by-side in a single library together with other library
+facilities not covered by this License, and distribute such a combined
+library, provided that the separate distribution of the work based on
+the Library and of the other library facilities is otherwise
+permitted, and provided that you do these two things:
+
+ a) Accompany the combined library with a copy of the same work
+ based on the Library, uncombined with any other library
+ facilities. This must be distributed under the terms of the
+ Sections above.
+
+ b) Give prominent notice with the combined library of the fact
+ that part of it is a work based on the Library, and explaining
+ where to find the accompanying uncombined form of the same work.
+
+ 8. You may not copy, modify, sublicense, link with, or distribute
+the Library except as expressly provided under this License. Any
+attempt otherwise to copy, modify, sublicense, link with, or
+distribute the Library is void, and will automatically terminate your
+rights under this License. However, parties who have received copies,
+or rights, from you under this License will not have their licenses
+terminated so long as such parties remain in full compliance.
+
+ 9. You are not required to accept this License, since you have not
+signed it. However, nothing else grants you permission to modify or
+distribute the Library or its derivative works. These actions are
+prohibited by law if you do not accept this License. Therefore, by
+modifying or distributing the Library (or any work based on the
+Library), you indicate your acceptance of this License to do so, and
+all its terms and conditions for copying, distributing or modifying
+the Library or works based on it.
+
+ 10. Each time you redistribute the Library (or any work based on the
+Library), the recipient automatically receives a license from the
+original licensor to copy, distribute, link with or modify the Library
+subject to these terms and conditions. You may not impose any further
+restrictions on the recipients' exercise of the rights granted herein.
+You are not responsible for enforcing compliance by third parties with
+this License.
+
+ 11. If, as a consequence of a court judgment or allegation of patent
+infringement or for any other reason (not limited to patent issues),
+conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License. If you cannot
+distribute so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you
+may not distribute the Library at all. For example, if a patent
+license would not permit royalty-free redistribution of the Library by
+all those who receive copies directly or indirectly through you, then
+the only way you could satisfy both it and this License would be to
+refrain entirely from distribution of the Library.
+
+If any portion of this section is held invalid or unenforceable under any
+particular circumstance, the balance of the section is intended to apply,
+and the section as a whole is intended to apply in other circumstances.
+
+It is not the purpose of this section to induce you to infringe any
+patents or other property right claims or to contest validity of any
+such claims; this section has the sole purpose of protecting the
+integrity of the free software distribution system which is
+implemented by public license practices. Many people have made
+generous contributions to the wide range of software distributed
+through that system in reliance on consistent application of that
+system; it is up to the author/donor to decide if he or she is willing
+to distribute software through any other system and a licensee cannot
+impose that choice.
+
+This section is intended to make thoroughly clear what is believed to
+be a consequence of the rest of this License.
+
+ 12. If the distribution and/or use of the Library is restricted in
+certain countries either by patents or by copyrighted interfaces, the
+original copyright holder who places the Library under this License may add
+an explicit geographical distribution limitation excluding those countries,
+so that distribution is permitted only in or among countries not thus
+excluded. In such case, this License incorporates the limitation as if
+written in the body of this License.
+
+ 13. The Free Software Foundation may publish revised and/or new
+versions of the Lesser General Public License from time to time.
+Such new versions will be similar in spirit to the present version,
+but may differ in detail to address new problems or concerns.
+
+Each version is given a distinguishing version number. If the Library
+specifies a version number of this License which applies to it and
+"any later version", you have the option of following the terms and
+conditions either of that version or of any later version published by
+the Free Software Foundation. If the Library does not specify a
+license version number, you may choose any version ever published by
+the Free Software Foundation.
+
+ 14. If you wish to incorporate parts of the Library into other free
+programs whose distribution conditions are incompatible with these,
+write to the author to ask for permission. For software which is
+copyrighted by the Free Software Foundation, write to the Free
+Software Foundation; we sometimes make exceptions for this. Our
+decision will be guided by the two goals of preserving the free status
+of all derivatives of our free software and of promoting the sharing
+and reuse of software generally.
+
+ NO WARRANTY
+
+ 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO
+WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW.
+EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR
+OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY
+KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE
+IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE
+LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME
+THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
+
+ 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN
+WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY
+AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU
+FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR
+CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE
+LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING
+RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A
+FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF
+SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
+DAMAGES.
+
+ END OF TERMS AND CONDITIONS
+
+ How to Apply These Terms to Your New Libraries
+
+ If you develop a new library, and you want it to be of the greatest
+possible use to the public, we recommend making it free software that
+everyone can redistribute and change. You can do so by permitting
+redistribution under these terms (or, alternatively, under the terms of the
+ordinary General Public License).
+
+ To apply these terms, attach the following notices to the library. It is
+safest to attach them to the start of each source file to most effectively
+convey the exclusion of warranty; and each file should have at least the
+"copyright" line and a pointer to where the full notice is found.
+
+
+ Copyright (C)
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Lesser General Public
+ License as published by the Free Software Foundation; either
+ version 2.1 of the License, or (at your option) any later version.
+
+ This library is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public
+ License along with this library; if not, write to the Free Software
+ Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+
+Also add information on how to contact you by electronic and paper mail.
+
+You should also get your employer (if you work as a programmer) or your
+school, if any, to sign a "copyright disclaimer" for the library, if
+necessary. Here is a sample; alter the names:
+
+ Yoyodyne, Inc., hereby disclaims all copyright interest in the
+ library `Frob' (a library for tweaking knobs) written by James Random Hacker.
+
+ , 1 April 1990
+ Ty Coon, President of Vice
+
+That's all there is to it!
Added: projects/zb4osgi/sandbox/miguel.llorente/zibgee.tsb.driver/LICENSE.ZigBee
==============================================================================
--- projects/zb4osgi/sandbox/miguel.llorente/zibgee.tsb.driver/LICENSE.ZigBee (added)
+++ projects/zb4osgi/sandbox/miguel.llorente/zibgee.tsb.driver/LICENSE.ZigBee Fri May 20 11:42:58 2011
@@ -1,0 +1,37 @@
+The ZigBee Specification is available to individuals, companies and institutions free of
+charge for all non-commercial purposes (including university research, technical
+evaluation, and development of non-commercial software, tools, or documentation). No
+part of this specification may be used in development of a product for sale without
+becoming a member of ZigBee Alliance.
+
+Copyright © ZigBee Alliance, Inc. (2007). All Rights Reserved. The information within this
+document is the property of the ZigBee Alliance and its use and disclosure are restricted.
+
+Elements of ZigBee Alliance specifications may be subject to third party intellectual
+property rights, including without limitation, patent, copyright or trademark rights (such a
+third party may or may not be a member of ZigBee). ZigBee is not responsible and shall not
+be held responsible in any manner for identifying or failing to identify any or all such third
+party intellectual property rights.
+
+This document and the information contained herein are provided on an ?AS IS? basis and
+ZigBee DISCLAIMS ALL WARRANTIES EXPRESS OR IMPLIED, INCLUDING BUT NOT
+LIMITED TO (A) ANY WARRANTY THAT THE USE OF THE INFORMATION HEREIN
+WILL NOT INFRINGE ANY RIGHTS OF THIRD PARTIES (INCLUDING WITHOUT
+LIMITATION ANY INTELLECTUAL PROPERTY RIGHTS INCLUDING PATENT,
+COPYRIGHT OR TRADEMARK RIGHTS) OR (B) ANY IMPLIED WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, TITLE OR NONINFRINGEMENT.
+IN NO EVENT WILL ZIGBEE BE LIABLE FOR ANY LOSS OF
+PROFITS, LOSS OF BUSINESS, LOSS OF USE OF DATA, INTERRUPTION OF
+BUSINESS, OR FOR ANY OTHER DIRECT, INDIRECT, SPECIAL OR EXEMPLARY,
+INCIDENTIAL, PUNITIVE OR CONSEQUENTIAL DAMAGES OF ANY KIND, IN
+CONTRACT OR IN TORT, IN CONNECTION WITH THIS DOCUMENT OR THE
+INFORMATION CONTAINED HEREIN, EVEN IF ADVISED OF THE POSSIBILITY OF
+SUCH LOSS OR DAMAGE. All Company, brand and product names may be trademarks
+that are the sole property of their respective owners.
+
+The above notice and this paragraph must be included on all copies of this document that
+are made.
+
+ZigBee Alliance, Inc.
+2400 Camino Ramon, Suite 375
+San Ramon, CA 94583
Added: projects/zb4osgi/sandbox/miguel.llorente/zibgee.tsb.driver/NOTICE
==============================================================================
--- projects/zb4osgi/sandbox/miguel.llorente/zibgee.tsb.driver/NOTICE (added)
+++ projects/zb4osgi/sandbox/miguel.llorente/zibgee.tsb.driver/NOTICE Fri May 20 11:42:58 2011
@@ -1,0 +1,51 @@
+ZIC for TSB dongle
+
+Copyright 2008-2010 CNR-ISTI, http://isti.cnr.it
+Institute of Information Science and Technologies of the
+Italian National Research Council
+
+Copyright 2008-2010 ITACA-TSB, http://www.tsb.upv.es/
+Instituto Tecnologico de Aplicaciones de Comunicacion
+Avanzadas - Grupo Tecnologias para la Salud y el
+Bienestar (TSB)
+
+I. Included Software
+
+This does not include any software developed by 3rd parties
+
+
+II. Used Software
+
+This product uses software developed at
+The Codehaus (http://www.codehaus.org)
+Licensed under the Apache License 2.0.
+
+This product uses software developed at
+The OPS4J (http://www.ops4j.org)
+Licensed under the Apache License 2.0.
+
+This product uses software developed at
+The RXTX (http://users.frii.com/jarvi/rxtx)
+RXTX License v 2.1 - LGPL v 2.1 + Linking Over
+Controlled Interface (see LICENSE.RxTx file ).
+
+This product uses software developed at
+The OSGi Alliance (http://www.osgi.org/).
+Copyright 2006-2008 The OSGi Alliance.
+Licensed under the Apache License 2.0.
+
+
+III. Specification used
+
+Part of this software is based on the specification
+provided by The ZigBee Alliance (http://www.zigbee.org)
+Licensed under ZigBee specific license for non-member
+of the ZigBee Allinace (see LICENSE.ZigBee file )
+
+
+IV. License Summary
+
+- Apache License 2.0
+- Common Public License Version 1.0
+- ZigBee Non-Member License
+- RXTX License v 2.1 - LGPL v 2.1 + Linking Over Controlled Interface
Added: projects/zb4osgi/sandbox/miguel.llorente/zibgee.tsb.driver/pom.xml
==============================================================================
--- projects/zb4osgi/sandbox/miguel.llorente/zibgee.tsb.driver/pom.xml (added)
+++ projects/zb4osgi/sandbox/miguel.llorente/zibgee.tsb.driver/pom.xml Fri May 20 11:42:58 2011
@@ -1,0 +1,186 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
+ <modelVersion>4.0.0</modelVersion>
+
+ <parent>
+ <artifactId>sail.pom</artifactId>
+ <groupId>org.aal-persona.sail</groupId>
+ <version>8-SNAPSHOT</version>
+ <relativePath>../pom/pom.xml</relativePath>
+ </parent>
+
+ <groupId>org.aal-persona.sail</groupId>
+ <artifactId>org.aal-persona.zigbee.tsb.driver</artifactId>
+ <version>0.7.0-SNAPSHOT</version>
+ <packaging>bundle</packaging>
+
+ <name>ZIC for TSB dongle</name>
+ <url>http://gforge.aal-persona.org/projects/persona-sail/</url>
+ <description><![CDATA[
+ Implementation of the ZigBee Controller Interface API for a custom usb device
+ designed by TSB which is composed by CC2520 and MSP430 chips. The firmware
+ is based on the Z-Stack 2.x and the serial port communication protocol has been
+ adapted to be complaint with the "CC2480 Serial Interface"
+ ]]></description>
+
+ <inceptionYear>2008</inceptionYear>
+ <organization>
+ <name><![CDATA[
+ ISTI-CNR, Institute of Information Science and Technologies of the Italian National Research Council
+ Instituto Tecnologico de Aplicaciones de Comunicacion Avanzadas - Grupo Tecnologias para la Salud y el Bienestar (TSB)
+ ]]></name>
+ <url><![CDATA[
+ http://isti.cnr.it/
+ http://www.itaca.upv.es/
+ ]]></url>
+ </organization>
+
+ <licenses>
+ <license>
+ <name>The Apache Software License, Version 2.0</name>
+ <url>http://www.apache.org/licenses/LICENSE-2.0.txt</url>
+ <distribution>repo</distribution>
+ </license>
+ </licenses>
+
+ <developers>
+ <developer>
+ <id>slenzi</id>
+ <name>Stefano "Kismet" Lenzi</name>
+ <email>stefano.lenzi at isti.cnr.it</email>
+ <organization>Institute of Information Science and Technologies of the Italian National Research Council</organization>
+ <organizationUrl>http://www.isti.cnr.it/</organizationUrl>
+ <timezone>+1</timezone>
+ </developer>
+ <developer>
+ <id>alfiva</id>
+ <name>Ãlvaro Fides Valero</name>
+ <email>alfiva at aaa.upv.es</email>
+ <organization>Instituto Tecnologico de Aplicaciones de Comunicacion Avanzadas - Grupo Tecnologias para la Salud y el Bienestar (TSB)</organization>
+ <organizationUrl>http://www.itaca.upv.es//</organizationUrl>
+ <timezone>+1</timezone>
+ </developer>
+ </developers>
+
+
+ <scm>
+ <connection>scm:svn:http://gforge.aal-persona.org/svn/persona-sail/trunk/Java/zigbee.tsb.driver</connection>
+ <developerConnection>scm:svn:http://gforge.aal-persona.org/svn/persona-sail/trunk/Java/zigbee.tsb.driver</developerConnection>
+ <url>http://gforge.aal-persona.org/scm/viewvc.php/trunk/Java/?root=persona-sail/trunk/Java/zigbee.tsb.driver</url>
+ </scm>
+
+ <dependencies>
+<!-- <dependency>-->
+<!-- <groupId>org.aal-persona.bundle</groupId>-->
+<!-- <artifactId>org.aal-persona.bundle.rxtx</artifactId>-->
+<!-- </dependency>-->
+ <dependency>
+ <groupId>org.aaloa.zb4osgi</groupId>
+ <artifactId>org.aaloa.zb4osgi.zigbee.dongle.api</artifactId>
+ <version>0.7.0</version>
+ </dependency>
+ <dependency>
+ <groupId>org.aaloa.zb4osgi</groupId>
+ <artifactId>org.aaloa.zb4osgi.zigbee.common</artifactId>
+ <version>0.5.0</version>
+ </dependency>
+ <dependency>
+ <groupId>org.aaloa.zb4osgi</groupId>
+ <artifactId>org.aaloa.zb4osgi.zigbee.cc2480.datalink</artifactId>
+ <version>0.7.0</version>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.felix</groupId>
+ <artifactId>org.osgi.core</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>org.ops4j.pax.logging</groupId>
+ <artifactId>pax-logging-api</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>org.ops4j.pax.logging</groupId>
+ <artifactId>pax-logging-service</artifactId>
+ </dependency>
+ </dependencies>
+
+ <build>
+ <plugins>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-javadoc-plugin</artifactId>
+ <configuration>
+ <bottom><![CDATA[
+ Copyright 2008-2010 <a href="http://isti.cnr.it">CNR-ISTI,
+ Institute of Information Science and Technologies
+ of the Italian National Research Council</a>
+<br>
+ Copyright 2008-2010 <a href="http://www.itaca.upv.es/">
+ Instituto Tecnologico de Aplicaciones de Comunicacion Avanzadas - Grupo Tecnologias para la Salud y el Bienestar (TSB)</a>
+ ]]></bottom>
+ </configuration>
+ </plugin>
+ <plugin>
+ <groupId>org.ops4j</groupId>
+ <artifactId>maven-pax-plugin</artifactId>
+ <configuration>
+ <runner>0.13.0</runner>
+ <!-- args>file:src/test/resources/pax.args</args -->
+ <!-- provision>
+ <provision>mvn:org.apache.felix/org.apache.felix.upnp.basedriver/0.8.0 at nostart</provision>
+ <provision>mvn:org.apache.felix/org.apache.felix.upnp.tester</provision>
+ <provision>mvn:org.apache.felix/org.apache.felix.upnp.extra</provision>
+ </provision -->
+ </configuration>
+ </plugin>
+
+ <plugin>
+ <groupId>org.apache.felix</groupId>
+ <artifactId>maven-bundle-plugin</artifactId>
+ <extensions>true</extensions>
+ <configuration>
+ <instructions>
+ <Bundle-Author><![CDATA[
+ Stefano "Kismet" Lenzi <stefano.lenzi at isti.cnr.it>,
+ Ãlvaro Fides Valero <alfiva at aaa.upv.es>
+ ]]></Bundle-Author>
+ <Bundle-Name>${pom.name}</Bundle-Name>
+ <Bundle-SymbolicName>${pom.artifactId}</Bundle-SymbolicName>
+ <Bundle-Activator>it.cnr.isti.zigbee.dongle.tsb.Activator</Bundle-Activator>
+ <Private-Package>
+ it.cnr.isti.zigbee.dongle.tsb.*
+ </Private-Package>
+ <Import-Package>
+ org.osgi.*,
+ javax.comm,
+ com.itaca.ztool.*,
+ it.cnr.isti.zigbee.dongle.api*,
+ it.cnr.isti.cc2480.*, javax.swing,
+ it.cnr.isti.primitvetypes.util, it.cnr.isti.osgi.util,
+ org.slf4j.*; provider=paxlogging
+ </Import-Package>
+ <Export-Package>
+ </Export-Package>
+ </instructions>
+ </configuration>
+ </plugin>
+ </plugins>
+ </build>
+
+ <reporting>
+ <plugins>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-changelog-plugin</artifactId>
+ <configuration>
+ <type>date</type>
+ <dates>
+ <date implementation="java.lang.String">2009-09-25</date>
+ <date implementation="java.lang.String">2010-10-23</date>
+ </dates>
+ <dateFormat>yyyy-MM-dd</dateFormat>
+ </configuration>
+ </plugin>
+ </plugins>
+ </reporting>
+
+</project>
Added: projects/zb4osgi/sandbox/miguel.llorente/zibgee.tsb.driver/src/main/java/it/cnr/isti/zigbee/dongle/tsb/Activator.java
==============================================================================
--- projects/zb4osgi/sandbox/miguel.llorente/zibgee.tsb.driver/src/main/java/it/cnr/isti/zigbee/dongle/tsb/Activator.java (added)
+++ projects/zb4osgi/sandbox/miguel.llorente/zibgee.tsb.driver/src/main/java/it/cnr/isti/zigbee/dongle/tsb/Activator.java Fri May 20 11:42:58 2011
@@ -1,0 +1,74 @@
+/*
+ Copyright 2008-2010 CNR-ISTI, http://isti.cnr.it
+ Institute of Information Science and Technologies
+ of the Italian National Research Council
+
+
+ See the NOTICE file distributed with this work for additional
+ information regarding copyright ownership
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+*/
+package it.cnr.isti.zigbee.dongle.tsb;
+
+import it.cnr.isti.osgi.util.OSGiProperties;
+import it.cnr.isti.zigbee.dongle.api.ConfigurationProperties;
+import it.cnr.isti.zigbee.dongle.api.DriverStatus;
+import it.cnr.isti.zigbee.dongle.api.NetworkMode;
+import it.cnr.isti.zigbee.dongle.api.SimpleDriver;
+//import it.cnr.isti.zigbee.dongle.tsb.impl.DriverTSB;
+//import it.cnr.isti.zigbee.dongle.tsb.impl.DriverTSBi;
+import it.cnr.isti.zigbee.dongle.tsb.impl.DriverTSBn;
+
+import java.util.Properties;
+
+import org.osgi.framework.BundleActivator;
+import org.osgi.framework.BundleContext;
+import org.osgi.framework.ServiceRegistration;
+
+/**
+ *
+ * @author <a href="mailto:stefano.lenzi at isti.cnr.it">Stefano "Kismet" Lenzi - ISTI-CNR
+ * @version $LastChangedRevision$ ($LastChangedDate$)
+ * @since 0.1.0
+ *
+ */
+public class Activator implements BundleActivator {
+
+ private DriverTSBn driver;
+ private ServiceRegistration service;
+
+ public void start(BundleContext bc) throws Exception {
+ driver = new DriverTSBn(
+ OSGiProperties.getString(bc, ConfigurationProperties.COM_NAME_KEY, ConfigurationProperties.COM_NAME),
+ OSGiProperties.getInt(bc, ConfigurationProperties.COM_BOUDRATE_KEY, 115200),
+ NetworkMode.valueOf(OSGiProperties.getString(
+ bc, ConfigurationProperties.NETWORK_MODE_KEY, ConfigurationProperties.NETWORK_MODE
+ )),
+ OSGiProperties.getInt(bc, ConfigurationProperties.PAN_ID_KEY, ConfigurationProperties.PAN_ID),
+ OSGiProperties.getInt(bc, ConfigurationProperties.CHANNEL_ID_KEY, ConfigurationProperties.CHANNEL_ID),
+ OSGiProperties.getBoolean(bc, ConfigurationProperties.NETWORK_FLUSH_KEY, ConfigurationProperties.NETWORK_FLUSH)
+ );
+ Properties properties = new Properties();
+ properties.put("zigbee.driver.id", DriverTSBn.class.getName());
+ properties.put("zigbee.supported.devices", new String[]{"tsb"});
+ properties.put("zigbee.driver.type", "hardware");
+ properties.put("zigbee.driver.mode", "real");
+ service = bc.registerService(SimpleDriver.class.getName(), driver, properties); }
+
+ public void stop(BundleContext bc) throws Exception {
+ service.unregister();
+ driver.close();
+ }
+
+}
Propchange: projects/zb4osgi/sandbox/miguel.llorente/zibgee.tsb.driver/src/main/java/it/cnr/isti/zigbee/dongle/tsb/Activator.java
------------------------------------------------------------------------------
svn-mine-type = text/plain
Propchange: projects/zb4osgi/sandbox/miguel.llorente/zibgee.tsb.driver/src/main/java/it/cnr/isti/zigbee/dongle/tsb/Activator.java
------------------------------------------------------------------------------
svn:eol-style = native
Propchange: projects/zb4osgi/sandbox/miguel.llorente/zibgee.tsb.driver/src/main/java/it/cnr/isti/zigbee/dongle/tsb/Activator.java
------------------------------------------------------------------------------
svn:keywords = Id Author Date Revision
Added: projects/zb4osgi/sandbox/miguel.llorente/zibgee.tsb.driver/src/main/java/it/cnr/isti/zigbee/dongle/tsb/impl/DriverTSB.java
==============================================================================
--- projects/zb4osgi/sandbox/miguel.llorente/zibgee.tsb.driver/src/main/java/it/cnr/isti/zigbee/dongle/tsb/impl/DriverTSB.java (added)
+++ projects/zb4osgi/sandbox/miguel.llorente/zibgee.tsb.driver/src/main/java/it/cnr/isti/zigbee/dongle/tsb/impl/DriverTSB.java Fri May 20 11:42:58 2011
@@ -1,0 +1,1199 @@
+/*
+ Copyright 2008-2010 CNR-ISTI, http://isti.cnr.it
+ Institute of Information Science and Technologies
+ of the Italian National Research Council
+
+
+ See the NOTICE file distributed with this work for additional
+ information regarding copyright ownership
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+*/
+package it.cnr.isti.zigbee.dongle.tsb.impl;
+
+import javax.comm.CommPortIdentifier;
+import it.cnr.isti.cc2480.high.AsynchrounsCommandListener;
+import it.cnr.isti.cc2480.high.HWHighLevelDriver;
+import it.cnr.isti.cc2480.high.SynchrounsCommandListner;
+import it.cnr.isti.cc2480.low.HWLowLevelDriver;
+import it.cnr.isti.cc2480.low.PacketListener;
+import it.cnr.isti.primitvetypes.util.Integers;
+import it.cnr.isti.zigbee.dongle.api.AFMessageListner;
+import it.cnr.isti.zigbee.dongle.api.AnnunceListner;
+import it.cnr.isti.zigbee.dongle.api.DriverStatus;
+import it.cnr.isti.zigbee.dongle.api.NetworkMode;
+import it.cnr.isti.zigbee.dongle.api.SimpleDriver;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Enumeration;
+import java.util.HashSet;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import com.itaca.ztool.api.ZToolCMD;
+import com.itaca.ztool.api.ZToolException;
+import com.itaca.ztool.api.ZToolPacket;
+import com.itaca.ztool.api.af.AF_DATA_CONFIRM;
+import com.itaca.ztool.api.af.AF_DATA_REQUEST;
+import com.itaca.ztool.api.af.AF_DATA_SRSP;
+import com.itaca.ztool.api.af.AF_INCOMING_MSG;
+import com.itaca.ztool.api.af.AF_REGISTER;
+import com.itaca.ztool.api.af.AF_REGISTER_SRSP;
+import com.itaca.ztool.api.simple.ZB_GET_DEVICE_INFO;
+import com.itaca.ztool.api.simple.ZB_GET_DEVICE_INFO_RSP;
+import com.itaca.ztool.api.system.SYS_RESET;
+import com.itaca.ztool.api.system.SYS_RESET_RESPONSE;
+import com.itaca.ztool.api.system.SYS_VERSION;
+import com.itaca.ztool.api.util.UTIL_SET_CHANNELS;
+import com.itaca.ztool.api.util.UTIL_SET_CHANNELS_RESPONSE;
+import com.itaca.ztool.api.util.UTIL_SET_PANID;
+import com.itaca.ztool.api.util.UTIL_SET_PANID_RESPONSE;
+import com.itaca.ztool.api.zdo.ZDO_ACTIVE_EP_REQ;
+import com.itaca.ztool.api.zdo.ZDO_ACTIVE_EP_REQ_SRSP;
+import com.itaca.ztool.api.zdo.ZDO_ACTIVE_EP_RSP;
+import com.itaca.ztool.api.zdo.ZDO_BIND_REQ;
+import com.itaca.ztool.api.zdo.ZDO_BIND_REQ_SRSP;
+import com.itaca.ztool.api.zdo.ZDO_BIND_RSP;
+import com.itaca.ztool.api.zdo.ZDO_END_DEVICE_ANNCE_IND;
+import com.itaca.ztool.api.zdo.ZDO_IEEE_ADDR_REQ;
+import com.itaca.ztool.api.zdo.ZDO_IEEE_ADDR_REQ_SRSP;
+import com.itaca.ztool.api.zdo.ZDO_IEEE_ADDR_RSP;
+import com.itaca.ztool.api.zdo.ZDO_NODE_DESC_REQ;
+import com.itaca.ztool.api.zdo.ZDO_NODE_DESC_REQ_SRSP;
+import com.itaca.ztool.api.zdo.ZDO_NODE_DESC_RSP;
+import com.itaca.ztool.api.zdo.ZDO_SIMPLE_DESC_REQ;
+import com.itaca.ztool.api.zdo.ZDO_SIMPLE_DESC_REQ_SRSP;
+import com.itaca.ztool.api.zdo.ZDO_SIMPLE_DESC_RSP;
+import com.itaca.ztool.api.zdo.ZDO_STARTUP_FROM_APP;
+import com.itaca.ztool.api.zdo.ZDO_STARTUP_FROM_APP_SRSP;
+import com.itaca.ztool.api.zdo.ZDO_UNBIND_REQ;
+import com.itaca.ztool.api.zdo.ZDO_UNBIND_REQ_SRSP;
+import com.itaca.ztool.api.zdo.ZDO_UNBIND_RSP;
+
+/**
+ *
+ * @author <a href="mailto:stefano.lenzi at isti.cnr.it">Stefano "Kismet" Lenzi</a>
+ * @author <a href="mailto:alfiva at upvnet.upv.es">Álvaro Fides Valero</a>
+ * @version $LastChangedRevision$ ($LastChangedDate$)
+ * @since 0.1.0
+ *
+ */
+public class DriverTSB implements SimpleDriver, Runnable{
+
+ private final static Logger logger = LoggerFactory.getLogger(SimpleDriver.class);
+ private final static Logger logger4Waiter = LoggerFactory.getLogger(WaitForCommand.class);
+
+
+ private Thread driver;
+
+ private HWHighLevelDriver high;
+ private HWLowLevelDriver low;
+ private String port;
+ private int rate;
+ private DriverStatus state;
+ private NetworkMode mode;
+ private short pan;
+ private byte channel;
+ private boolean cleanStatus;
+
+ private long TIMEOUT = 5000;//Activator.getCurrentConfiguration().getZigBeeTimeout();
+
+ private final HashSet<AnnunceListner> annunceListners = new HashSet<AnnunceListner>();
+ private final AnnunceListerFilter annunceListner = new AnnunceListerFilter(annunceListners);
+
+ private final ArrayList<AFMessageListner> afMessageListners = new ArrayList<AFMessageListner>();
+ private final AFMessageListnerFilter afListner = new AFMessageListnerFilter(afMessageListners);
+
+ private long ieeeAddress = -1;
+
+ private class AnnunceListerFilter implements AsynchrounsCommandListener{
+
+ private final Collection<AnnunceListner> listners;
+
+ private AnnunceListerFilter(Collection<AnnunceListner> list){
+ listners = list;
+ }
+
+ public void receivedAsynchrounsCommand(ZToolPacket packet) {
+ if(packet.isError()) return;
+ if(packet.getCMD().get16BitValue() == ZToolCMD.ZDO_END_DEVICE_ANNCE_IND){
+ ZDO_END_DEVICE_ANNCE_IND annunce = (ZDO_END_DEVICE_ANNCE_IND) packet;
+ for (AnnunceListner l : listners) {
+ l.notify(annunce.SrcAddr, annunce.IEEEAddr, annunce.NwkAddr, annunce.Capabilities);
+ }
+ }
+ }
+
+ }
+
+ private class AFMessageListnerFilter implements AsynchrounsCommandListener{
+
+ private final Collection<AFMessageListner> listners;
+
+ private AFMessageListnerFilter(Collection<AFMessageListner> list){
+ listners = list;
+ }
+
+ public void receivedAsynchrounsCommand(ZToolPacket packet) {
+ if(packet.isError()) return;
+ if(packet.getCMD().get16BitValue() == ZToolCMD.AF_INCOMING_MSG){
+ AF_INCOMING_MSG msg = (AF_INCOMING_MSG) packet;
+ if( listners.isEmpty() ){
+ logger.debug("Recieved AF_INCOMING_MSG but no listeners. Message was: {} ", msg);
+ } else {
+ logger.debug("Recieved AF_INCOMING_MSG notifying {} listeners of {}", listners.size(), msg);
+ }
+ ArrayList<AFMessageListner> localCopy = null;
+ synchronized (listners) {
+ localCopy = new ArrayList<AFMessageListner>(listners);
+ }
+ for ( AFMessageListner l : localCopy){
+// if( l.match(
+// msg.getClusterId(), msg.getSrcAddr(),
+// msg.getSrcEndpoint(), msg.getDstEndpoint(),
+// msg.getTransId()
+// ) ) {
+ l.notify(msg);
+// }
+ }
+ }
+ }
+
+ }
+
+ public DriverTSB(String serialPort, int bitrate) throws ZToolException {
+ this(serialPort,bitrate,NetworkMode.Coordinator,0,19, false);
+ }
+
+ public DriverTSB(
+ String serialPort, int bitrate, NetworkMode mode,
+ int pan, int channel
+ ) throws ZToolException {
+ this(serialPort, bitrate, mode, pan, channel, false);
+ }
+
+ public DriverTSB(
+ String serialPort, int bitRate, NetworkMode mode,
+ int pan, int channel, boolean cleanNetworkStatus
+ ) throws ZToolException {
+ state = DriverStatus.CLOSED;
+ this.cleanStatus = cleanNetworkStatus;
+ setSerialPort(serialPort, bitRate);
+ setZigBeeNetwork((byte)channel, (short)pan);
+ setZigBeeNodeMode(mode);
+ }
+
+ private String buildDriverThreadName(String serialPort, int bitrate) {
+ return "SimpleDriver["+serialPort+","+bitrate+"]";
+ }
+
+ public void setZigBeeNodeMode(NetworkMode m) {
+ if ( state != DriverStatus.CLOSED ) {
+ throw new IllegalStateException("Network mode can be changed only " +
+ "if driver is CLOSED while it is:"+state);
+ }
+ cleanStatus = mode != m;
+ mode = m;
+ }
+
+ public void setZigBeeNetwork(byte ch, short panId) {
+ if ( state != DriverStatus.CLOSED ) {
+ throw new IllegalStateException("Network mode can be changed only " +
+ "if driver is CLOSED while it is:"+state);
+ }
+ cleanStatus = ch != channel || panId != pan;
+ channel = ch;
+ pan = panId;
+ }
+
+ public void setSerialPort(String serialName,int bitRate) {
+ if ( state != DriverStatus.CLOSED ) {
+ throw new IllegalStateException("Serial port can be changed only " +
+ "if driver is CLOSED while it is:"+state);
+ }
+ port = serialName;
+ rate = bitRate;
+ }
+
+ public void open(boolean cleanCache){
+ cleanStatus = cleanCache;
+ open();
+ }
+
+ public void open(){
+ if ( state == DriverStatus.CLOSED ) {
+ state = DriverStatus.CREATED;
+ driver = new Thread(this);
+ driver.setName(buildDriverThreadName(port,rate));
+ driver.start();
+ }else{
+ throw new IllegalStateException("Driver already opened, current statu is:"+state);
+ }
+ }
+
+ public void close(){
+ if(state == DriverStatus.CLOSED){
+ logger.debug("Already CLOSED");
+ return;
+ }
+ logger.info("Closing");
+ if( Thread.currentThread() != driver ){
+ logger.debug("Waiting for intialization operation to complete before closing");
+ try {
+ driver.join();
+ } catch (InterruptedException ignored) {
+ }
+ }else{
+ logger.debug("Self closing");
+ }
+ if(state == DriverStatus.NETWORK_READY){
+ logger.debug("Closing NETWORK");
+ setState(DriverStatus.HARDWARE_READY);
+ }
+ if(state == DriverStatus.HARDWARE_READY){
+ logger.debug("Closing HARDWARE");
+ high.close();
+ logger.debug("Closing LOW HARDWARE");
+ low.close();
+ setState(DriverStatus.CREATED);
+ }
+ if(state == DriverStatus.CREATED){
+ setState(DriverStatus.CLOSED);
+ }
+ logger.info("Closed");
+ }
+
+ public ZDO_IEEE_ADDR_RSP sendZDOIEEEAddressRequest(ZDO_IEEE_ADDR_REQ request){
+ if( waitForNetwork() == false ) return null;
+
+ final WaitForCommand waiter = new WaitForCommand(ZToolCMD.ZDO_IEEE_ADDR_RSP, high);
+
+ logger.debug("Sending ZDO_IEEE_ADDR_REQ {}", request);
+ ZDO_IEEE_ADDR_REQ_SRSP response = (ZDO_IEEE_ADDR_REQ_SRSP) sendSynchrouns(high, request);
+ if ( response == null || response.Status != 0 ) {
+ logger.debug("ZDO_IEEE_ADDR_REQ failed, recieved {}", response);
+ waiter.cleanup();
+ return null;
+ } else {
+ return (ZDO_IEEE_ADDR_RSP) waiter.getCommand(TIMEOUT);
+ }
+ }
+
+ public ZDO_NODE_DESC_RSP sendZDONodeDescriptionRequest(ZDO_NODE_DESC_REQ request) {
+ if( waitForNetwork() == false ) return null;
+
+ final WaitForCommand waiter = new WaitForCommand(ZToolCMD.ZDO_NODE_DESC_RSP, high);
+
+ ZDO_NODE_DESC_REQ_SRSP response = (ZDO_NODE_DESC_REQ_SRSP) sendSynchrouns(high, request);
+ if ( response == null || response.Status != 0 ) {
+ waiter.cleanup();
+ return null;
+ } else {
+ return (ZDO_NODE_DESC_RSP) waiter.getCommand(TIMEOUT);
+ }
+ }
+
+ public ZDO_ACTIVE_EP_RSP sendZDOActiveEndPointRequest(ZDO_ACTIVE_EP_REQ request) {
+ if( waitForNetwork() == false ) return null;
+
+ final WaitForCommand waiter = new WaitForCommand(ZToolCMD.ZDO_ACTIVE_EP_RSP, high);
+
+ logger.debug("Sending ZDO_ACTIVE_EP_REQ {}", request);
+ ZDO_ACTIVE_EP_REQ_SRSP response = (ZDO_ACTIVE_EP_REQ_SRSP) sendSynchrouns(high, request);
+ if ( response == null || response.Status != 0 ) {
+ logger.debug("ZDO_ACTIVE_EP_REQ failed, recieved {}", response);
+ waiter.cleanup();
+ return null;
+ } else {
+ return (ZDO_ACTIVE_EP_RSP) waiter.getCommand(TIMEOUT);
+ }
+ }
+
+ public ZDO_SIMPLE_DESC_RSP sendZDOSimpleDescriptionRequest(ZDO_SIMPLE_DESC_REQ request) {
+ if( waitForNetwork() == false ) return null;
+
+ final WaitForCommand waiter = new WaitForCommand(ZToolCMD.ZDO_SIMPLE_DESC_RSP, high);
+
+ ZDO_SIMPLE_DESC_REQ_SRSP response = (ZDO_SIMPLE_DESC_REQ_SRSP) sendSynchrouns(high, request);
+ if ( response == null || response.Status != 0 ) {
+ waiter.cleanup();
+ return null;
+ } else {
+ return (ZDO_SIMPLE_DESC_RSP) waiter.getCommand(TIMEOUT);
+ }
+ }
+
+ public void run() {
+ logger.info("Intializing");
+ setState(DriverStatus.HARDWARE_INITIALIZING);
+ if(initializeHardware() == true){
+ setState(DriverStatus.HARDWARE_READY);
+ }else{
+ close();
+ logger.error("Could not initialize hardware");
+ return;
+ }
+
+ setState(DriverStatus.NETWORK_INITIALIZING);
+ if(initializeZigBeeNetwork() == true){
+ setState(DriverStatus.NETWORK_READY);
+ }else{
+ close();
+ logger.error("Could not initialize network");
+ return;
+ }
+ }
+
+
+ @SuppressWarnings("unchecked")
+ private boolean initializeHardware() {
+ String portToOpen = null;
+ if("auto".equalsIgnoreCase(port)){
+ Enumeration<CommPortIdentifier> ports = CommPortIdentifier.getPortIdentifiers();
+ while(ports.hasMoreElements()){
+ CommPortIdentifier com = ports.nextElement();
+ if(DriverTSB.initializeHardware(com.getName(), rate)){
+ portToOpen=com.getName();
+ Thread.currentThread().setName(buildDriverThreadName(portToOpen, rate));
+ break;
+ }
+ }
+ }else{
+ if( DriverTSB.initializeHardware(port, rate) == true ){
+ portToOpen = port;
+ }
+ }
+ if( portToOpen == null ){
+ return false;
+ } else {
+ low = new HWLowLevelDriver();
+ try {
+ low.open(portToOpen, rate);
+ } catch (ZToolException e) {
+ logger.error("The port was already open in advance but we can't open it now",e);
+ return false;
+ }
+ high = new HWHighLevelDriver(low);
+ return true;
+ }
+ }
+
+ private void setState(DriverStatus value) {
+ logger.info("State changed from {} to {}", this.state, value);
+ synchronized (this) {
+ state = value;
+ notifyAll();
+ }
+ if(state == DriverStatus.HARDWARE_READY){
+ postHardwareEnabled();
+ }
+ }
+
+ private void postHardwareEnabled() {
+ if( ! afMessageListners.isEmpty() ){
+ high.addAsynchrounsCommandListener(afListner);
+ }
+ if( ! annunceListners.isEmpty() ){
+ high.addAsynchrounsCommandListener(annunceListner);
+ }
+ }
+
+ static boolean initializeHardware(String portName, int boudRate) {
+ boolean result = false;
+ final int recieved[] = new int[1];
+ final HWLowLevelDriver probingDriver = new HWLowLevelDriver();
+ final PacketListener monitor = new PacketListener(){
+ public void packetRecieved(ZToolPacket packet) {
+ if(packet.getCommandId() == ZToolCMD.SYS_VERSION_RESPONSE){
+ logger.debug("Initializing Hardware: Received correctly SYS_VERSION_RESPONSE");
+ synchronized (recieved) {
+ recieved[0] = 3;
+ }
+ } else if(packet.isError()){
+ logger.debug("Initializing Hardware: Received erroneous packet: {}",packet.getErrorMsg());
+ synchronized (recieved) {
+ recieved[0] += 1;
+ }
+ } else {
+ logger.debug("Initializing Hardware: Received {}",packet.getClass().getName());
+ synchronized (recieved) {
+ recieved[0] += 1;
+ }
+ }
+ }
+
+ };
+ probingDriver.addPacketListener(monitor);
+ try {
+ probingDriver.open(portName,boudRate);
+ probingDriver.sendPacket(new SYS_VERSION());
+ final long ready = System.currentTimeMillis() + 5000;
+ while(ready > System.currentTimeMillis()){
+ synchronized (recieved) {
+ if( recieved[0] == 3 ){
+ break;
+ }
+ }
+
+ try {
+ Thread.sleep(500);
+ } catch (InterruptedException ignored) {
+ }
+ }
+ synchronized (recieved) {
+ if( recieved[0] == 3 ){
+ result = true;
+ }
+ }
+ } catch (ZToolException e) {
+ logger.info("Unable to open serial port: {}", portName);
+ logger.error("Unable to open serial port, due to:", e);
+ }catch (IOException e) {
+ logger.error("Hardware initialization failed", e);
+ }
+ probingDriver.close();
+ probingDriver.removePacketListener(monitor);
+ return result;
+ }
+
+ private boolean waitForHardware() {
+ synchronized (this) {
+ while (state == DriverStatus.CREATED || state == DriverStatus.CLOSED ){
+ logger.debug("Waiting for HARDWARE to become ready");
+ try {
+ wait();
+ } catch (InterruptedException ignored) {
+ }
+ }
+ return isHardwareReady();
+ }
+ }
+
+ private boolean waitForNetwork() {
+ synchronized (this) {
+ while (state != DriverStatus.NETWORK_READY && state != DriverStatus.CLOSED ){
+ logger.debug("Waiting for NETWORK to become ready");
+ try {
+ wait();
+ } catch (InterruptedException ignored) {
+ }
+ }
+ return isNetworkReady();
+ }
+ }
+
+ private class WaitForCommand implements AsynchrounsCommandListener{
+
+ final ZToolPacket[] result = new ZToolPacket[]{null};
+ final int waitFor;
+ final HWHighLevelDriver driver;
+
+ public WaitForCommand(int waitFor, HWHighLevelDriver driver) {
+ this.waitFor = waitFor;
+ this.driver = driver;
+ driver.addAsynchrounsCommandListener(this);
+ }
+
+
+
+ public void receivedAsynchrounsCommand(ZToolPacket packet) {
+ logger4Waiter.info("Recieved a packet {} and waiting for {}", packet.getCMD(), waitFor);
+ logger4Waiter.debug("Recieved {} {}", packet.getClass(), packet.toString());
+ if( packet.isError() ) return;
+ if( packet.getCMD().get16BitValue() != waitFor) return;
+ synchronized (result) {
+ result[0]=packet;
+ logger4Waiter.info("Recieved packet that we were waiting for");
+ cleanup();
+ }
+ }
+
+ public ZToolPacket getCommand(final long timeout){
+ synchronized (result) {
+ final long wakeUpTime = System.currentTimeMillis() + timeout;
+ while(result[0] == null && wakeUpTime > System.currentTimeMillis()){
+ try {
+ result.wait(wakeUpTime-System.currentTimeMillis());
+ } catch (InterruptedException ignored) {
+ }
+
+ }
+ }
+ if( result[0] == null ){
+ logger4Waiter.warn("Timeout {} expired and not packet with {} recieved", timeout, waitFor);
+ }
+ cleanup();
+ return result[0];
+ }
+
+ public void cleanup(){
+ synchronized (result) {
+ driver.removeAsynchrounsCommandListener(this);
+ result.notify();
+ }
+ }
+ }
+
+ private class WaitForAList implements PacketListener{
+
+ final int[] waitingList;
+ final ZToolPacket[] packetHistory;
+ final HWLowLevelDriver hwDriver;
+ int idx = 0;
+
+ /**
+ * This constructor uses the {@link WaitForAList#WaitForAList(int[], ZToolPacket[], HWLowLevelDriver) constructor<br>
+ * with the following parameters <code>WaitForAList(list,null,null)</code>
+ *
+ * @see WaitForAList#WaitForAList(int[], ZToolPacket[], HWLowLevelDriver)
+ * @param list
+ */
+ public WaitForAList(final int[] list){
+ this(list, null, null);
+ }
+
+ /**
+ * Create a {@link WaitForAList} that wait for a specified list<br>
+ * of packet to be received. Furthermore, the {@link WaitForAList}<br>
+ * while record all the matching packet received, and it will handle<br>
+ * by itself the registration and unregistration as {@link PacketListener}<br>
+ * to the specified {@link HWLowLevelDriver}.<br>
+ * <br>
+ * <b>NOTE:</b>If the {@link ZToolPacket} array is null no packet will be recorded<br>
+ * <b>NOTE:</b>If the {@link HWLowLevelDriver} array is null registration and unregistration as<br>
+ * {@link PacketListener} must be handled by the invoker<br>
+ *
+ * @param list the array of <code>int</code> to listen to
+ * @param packets {@link ZToolPacket} the array of the same size as <code>list</code> to record the received packet
+ * @param lowDriver {@link HWLowLevelDriver} to register to, if <code>null</code> to handle registration/unregistration manually
+ */
+ public WaitForAList(
+ final int[] list,
+ final ZToolPacket[] packets,
+ final HWLowLevelDriver lowDriver){
+ this.waitingList = list;
+ this.packetHistory = packets;
+ this.hwDriver = lowDriver;
+ if ( hwDriver != null) {
+ hwDriver.addPacketListener(this);
+ }
+ }
+
+ public void waitForAll(long timeout){
+ long wakeUpTime = System.currentTimeMillis() + timeout;
+ synchronized (waitingList) {
+ while( idx < waitingList.length && wakeUpTime > System.currentTimeMillis()){
+ try {
+ waitingList.wait(wakeUpTime - System.currentTimeMillis());
+ } catch (InterruptedException ignored) {
+ }
+ }
+ }
+ }
+
+ public void packetRecieved(ZToolPacket packet) {
+ if(packet.isError()) return;
+ if((packet.getCommandId() & 0xFFFF) == waitingList[idx]){
+ logger.info("Recieved packet that was waiting for incresing waitingList");
+ synchronized (waitingList) {
+ if ( packetHistory != null ) {
+ packetHistory[idx] = packet;
+ }
+ idx = idx + 1;
+ if ( idx == waitingList.length ){
+ if ( low != null) {
+ low.removePacketListener(this);
+ }
+ waitingList.notifyAll();
+ return;
+ }
+ }
+ }
+ }
+
+ }
+
+
+ private boolean dongleReset(){
+ if( waitForHardware() == false ) return false;
+
+ final WaitForCommand waiter = new WaitForCommand(
+ ZToolCMD.SYS_RESET_RESPONSE,
+ high
+ );
+
+// WaitForAList waiting = new WaitForAList(new int[]{
+// ZToolCMD.SYS_RESET_RESPONSE,
+// });
+//
+// low.addPacketListener(waiting);
+
+ try {
+ high.sendAsynchrounsCommand(new SYS_RESET(SYS_RESET.RESET_TYPE.TARGET_DEVICE));
+ } catch (IOException e) {
+ logger.error("DongleReset failed", e);
+ return false;
+ }
+
+ SYS_RESET_RESPONSE response =
+ (SYS_RESET_RESPONSE) waiter.getCommand(TIMEOUT);
+
+// waiting.waitForAll(TIMEOUT*2);
+// low.removePacketListener(waiting);
+ return response != null;
+// return true;
+ }
+
+ static final int[] buildChannelMask(int channel){
+ int channelMask = 1 << channel;
+ int[] mask = new int[4];
+ for (int i = 0; i < mask.length; i++) {
+ mask[i] = Integers.getByteAsInteger(channelMask, i);
+ }
+ return mask;
+ }
+
+ private boolean dongleSetChannel(int[] channelMask) {
+
+ logger.info(
+ "Setting the channel to {}{}{}{}", new Object[]{
+ Integer.toHexString(channelMask[0]),
+ Integer.toHexString(channelMask[1]),
+ Integer.toHexString(channelMask[2]),
+ Integer.toHexString(channelMask[3])
+ }
+ );
+
+ UTIL_SET_CHANNELS_RESPONSE response =
+ (UTIL_SET_CHANNELS_RESPONSE) sendSynchrouns(
+ high,
+ new UTIL_SET_CHANNELS(
+ channelMask
+ )
+ );
+
+ return response != null && response.Status == 0;
+ }
+
+ private boolean dongleSetChannel(int ch){
+ int[] channelMask = buildChannelMask(ch);
+
+ return dongleSetChannel(channelMask);
+ }
+
+ private boolean dongleSetChannel(){
+ int[] channelMask = buildChannelMask(channel);
+
+ return dongleSetChannel(channelMask);
+ }
+
+
+ private boolean dongleSetPanId(){
+ UTIL_SET_PANID_RESPONSE response =
+ (UTIL_SET_PANID_RESPONSE) sendSynchrouns(
+ high,
+ new UTIL_SET_PANID(
+ new int[]{
+ Integers.getByteAsInteger(pan, 0),
+ Integers.getByteAsInteger(pan, 1)
+ }
+ )
+ );
+
+ return response != null && response.Status == 0;
+ }
+
+
+ private boolean createZigBeeNetwork(boolean reset){
+ /*
+ * NOTE:The dongle has to be reset all the time to avoid that the endpoints
+ * register on the dongle itself break the code at upper level
+ *
+ */
+ if( reset && dongleReset() ) {
+ logger.debug("Reset the dongle before Creating ZigBee Network");
+ } else if (reset) {
+ logger.debug("FAILED to reset the dongle before Creating ZigBee Network");
+ } else {
+ logger.debug("Dongle has already been reset so no endpoint registered");
+ }
+ switch (mode) {
+ case Coordinator:
+ return doCreateNetwork();
+ case Router:
+ //TODO Implements start up as Router
+ return doCreateNetwork();
+ case EndDevice:
+ return doCreateNetwork();
+ }
+
+ /*
+ * This code is unreachable but compiler can't find this out yet.
+ * It may introduce a compilation issue of future compilers
+ */
+ return false;
+ }
+
+ private boolean doCreateNetwork() {
+ logger.debug("Creating network");
+
+// final WaitForAList completeWait = new WaitForAList(
+// new int[]{
+// ZToolCMD.ZB_START_CONFIRM,
+// ZToolCMD.ZB_GET_DEVICE_INFO_RSP,
+// ZToolCMD.ZB_GET_DEVICE_INFO_RSP
+// },
+// new ZToolPacket[3],
+// low
+// );
+//
+// final WaitForCommand waiter = new WaitForCommand(ZToolCMD.ZB_START_CONFIRM,high);
+//
+// ZB_START_CONFIRM result = null;
+ ZDO_STARTUP_FROM_APP_SRSP response = (ZDO_STARTUP_FROM_APP_SRSP) sendSynchrouns(
+ high, new ZDO_STARTUP_FROM_APP(ZDO_STARTUP_FROM_APP.RESET_TYPE.TARGET_DEVICE)
+ );
+// if ( response == null ) {
+// waiter.cleanup();
+// return false;
+// } else {
+// result = (ZB_START_CONFIRM) waiter.getCommand(TIMEOUT);
+// }
+//
+// completeWait.waitForAll(TIMEOUT * 2);
+//
+// return result != null && result.Status == ZB_START_CONFIRM.AF_STATUS.SUCCESS;
+ return (response != null) ;
+ }
+
+
+ /*
+ //TODO We should check if the current setting differs from the setting stored on the dongle
+ * and later define whetever to clean or not the cache
+ private boolean mustCleanStatus(){
+ if( cleanStatus ) {
+ return true;
+ }
+
+ createZigBeeNetwork();
+
+ int[] value;
+
+ value = getDeviceInfo(ZB_GET_DEVICE_INFO.DEV_INFO_TYPE.CHANNEL);
+ if ( value == null){
+ logger.error("Method getDeviceInfo(ZB_GET_DEVICE_INFO.DEV_INFO_TYPE.CHANNEL) returned null");
+ return true;
+ } else if ( value[0] != this.channel ) {
+ logger.debug("Dongle network state must be reset because channel is changed. " +
+ "Old was = {} while new is {}", value[0], this.channel);
+ return true;
+ }
+
+ value = getDeviceInfo(ZB_GET_DEVICE_INFO.DEV_INFO_TYPE.PAN_ID);
+ if ( value == null){
+ logger.error("Method getDeviceInfo(ZB_GET_DEVICE_INFO.DEV_INFO_TYPE.PAN_ID) returned null");
+ return true;
+ } else if ( Integers.shortFromInts(value, 1, 0) != this.pan) {
+ logger.debug("Dongle network state must be reset because PanId is changed. " +
+ "Old was = {} while new is {}", Integers.shortFromInts(value, 1, 0), this.pan);
+ return true;
+ }
+
+ dongleReset();
+
+ return false;
+ }
+ */
+
+ private boolean initializeZigBeeNetwork() {
+
+ /*
+ //TODO Fix this peace of code because it is not working
+ The right configuration procedure is:
+ - Set the clear the state
+ - Reboot
+ - Check the status from getDeviceInfo
+ - Set the configuration of: Mode, Channel, PanId, etc.
+
+ boolean cleanNetworkState = mustCleanStatus(); */
+
+ boolean cleanNetworkState = cleanStatus;
+
+// if( cleanNetworkState ) {
+// if( ! dongleReset()/*dongleClearState() */){
+// return false;
+// }
+// if( ! dongleSetChannel() ){
+// return false;
+// }
+// if( ! dongleSetPanId() ){
+// return false;
+// }
+//
+// return createZigBeeNetwork(false);
+// } else {
+// return createZigBeeNetwork(true);
+// }
+ if( cleanNetworkState ) {
+ int tries=0;
+ boolean worked=false;
+
+ while (!worked&&(tries<3)){
+ tries++;
+ worked=dongleReset();
+ }
+ if(!worked)return false;
+ worked=false;tries=0;
+
+ while (!worked&&(tries<3)){
+ tries++;
+ worked=dongleSetChannel();
+ }
+ if(!worked)return false;
+ worked=false;tries=0;
+
+ while (!worked&&(tries<3)){
+ tries++;
+ worked=dongleSetPanId();
+ }
+ if(!worked)return false;
+ worked=false;tries=0;
+
+ while (!worked&&(tries<3)){
+ tries++;
+ worked=createZigBeeNetwork(false);
+ }
+ return worked;
+
+ } else {
+ int tries=0;
+ boolean worked=false;
+ while (!worked&&(tries<3)){
+ tries++;
+ worked=createZigBeeNetwork(true);
+ }
+ return worked;
+ }
+ }
+
+ private ZToolPacket sendSynchrouns(final HWHighLevelDriver hwDriver, final ZToolPacket request) {
+ final ZToolPacket[] response = new ZToolPacket[]{null};
+ final int TIMEOUT = 1000, MAX_SEND = 3;
+ int sending = 1;
+
+ logger.info("Sending Synchrouns {}", request.getClass().getName());
+
+ SynchrounsCommandListner listener = new SynchrounsCommandListner() {
+
+ public void receivedCommandResponse(ZToolPacket packet) {
+ logger.info("Recieved Synchrouns Response {}", packet.getClass().getName());
+ synchronized (response) {
+ response[0] = packet;
+ response.notify();
+ }
+ }
+
+ };
+
+ while( sending <= MAX_SEND ){
+ try {
+ hwDriver.sendSynchrounsCommand(request, listener, TIMEOUT);
+ logger.info("Sent {} during the {}-th tenative", request.getClass().getName(),sending);
+ synchronized (response) {
+ long wakeUpTime = System.currentTimeMillis() + TIMEOUT;
+ while(response[0] == null && wakeUpTime > System.currentTimeMillis()){
+ final long sleeping = wakeUpTime - System.currentTimeMillis();
+ logger.debug("Waiting Synchrouns for up to {}ms till {} Unixtime", sleeping, wakeUpTime);
+ if ( sleeping <= 0 ) {
+ break;
+ }
+ try {
+ response.wait(sleeping);
+ } catch (InterruptedException ignored) {
+ }
+ }
+ }
+ if ( response[0] != null ) {
+ logger.debug("Recieved synchrouns command {} before timout", response[0]);
+ } else {
+ logger.debug("Timeout fired and not synchrouns command recieved", response[0]);
+ }
+ break;
+ }catch(IOException ignored){
+ logger.info("Failed to send {} during the {}-th tenative", request.getClass().getName(),sending);
+ logger.debug("Sending operation failed due to ", ignored);
+ sending++;
+ }
+ }
+
+ return response[0];
+ }
+
+ public boolean addAnnunceListener(AnnunceListner listner){
+ if(annunceListners.isEmpty() && isHardwareReady() ){
+ high.addAsynchrounsCommandListener(annunceListner);
+ }
+ return annunceListners.add(listner);
+ }
+
+ public boolean removeAnnunceListener(AnnunceListner listner){
+ boolean result = annunceListners.remove(listner);
+ if(annunceListners.isEmpty() && isHardwareReady() ){
+ high.removeAsynchrounsCommandListener(annunceListner);
+ }
+ return result;
+ }
+
+ public AF_REGISTER_SRSP sendAFRegister(AF_REGISTER request) {
+ if( waitForNetwork() == false ) return null;
+
+ AF_REGISTER_SRSP response = (AF_REGISTER_SRSP) sendSynchrouns(high, request);
+ return response;
+ }
+
+ public AF_DATA_CONFIRM sendAFDataRequest(AF_DATA_REQUEST request) {
+ if( waitForNetwork() == false ) return null;
+
+ final WaitForCommand waiter = new WaitForCommand(ZToolCMD.AF_DATA_CONFIRM, high);
+
+ AF_DATA_SRSP response = (AF_DATA_SRSP) sendSynchrouns(high, request);
+ if ( response == null || response.Status != 0 ) {
+ waiter.cleanup();
+ return null;
+ } else {
+ return (AF_DATA_CONFIRM) waiter.getCommand(TIMEOUT);
+ }
+ }
+
+ public ZDO_BIND_RSP sendZDOBind(ZDO_BIND_REQ request) {
+ if( waitForNetwork() == false ) return null;
+
+ final WaitForCommand waiter = new WaitForCommand(ZToolCMD.ZDO_BIND_RSP, high);
+
+ ZDO_BIND_REQ_SRSP response = (ZDO_BIND_REQ_SRSP) sendSynchrouns(high, request);
+ if ( response == null || response.Status != 0 ) {
+ waiter.cleanup();
+ return null;
+ } else {
+ return (ZDO_BIND_RSP) waiter.getCommand(TIMEOUT);
+ }
+ }
+
+ public ZDO_UNBIND_RSP sendZDOUnbind(ZDO_UNBIND_REQ request) {
+ if( waitForNetwork() == false ) return null;
+
+ final WaitForCommand waiter = new WaitForCommand(ZToolCMD.ZDO_UNBIND_RSP, high);
+
+ ZDO_UNBIND_REQ_SRSP response = (ZDO_UNBIND_REQ_SRSP) sendSynchrouns(high, request);
+ if ( response == null || response.Status != 0 ) {
+ waiter.cleanup();
+ return null;
+ } else {
+ return (ZDO_UNBIND_RSP) waiter.getCommand(TIMEOUT);
+ }
+ }
+
+ public boolean removeAFMessageListener(AFMessageListner listner){
+ boolean result = false;
+ synchronized (afMessageListners) {
+ result = afMessageListners.remove(listner);
+ }
+
+ if(afMessageListners.isEmpty() && isHardwareReady() ){
+ if ( high.removeAsynchrounsCommandListener(afListner) ) {
+ logger.debug("Removed AsynchrounsCommandListener {} to HWHighLevelDriver", afListner.getClass().getName());
+ } else {
+ logger.debug("Could not remove AsynchrounsCommandListener {} to HWHighLevelDriver", afListner.getClass().getName());
+ }
+ }
+ if ( result ) {
+ logger.debug("Removed AFMessageListner {}:{}", listner, listner.getClass().getName());
+ return true;
+ } else {
+ logger.debug("Could not remove AFMessageListner {}:{}", listner, listner.getClass().getName());
+ return false;
+ }
+ }
+
+ public boolean addAFMessageListner(AFMessageListner listner) {
+ if(afMessageListners.isEmpty() && isHardwareReady() ){
+ if ( high.addAsynchrounsCommandListener(afListner) ) {
+ logger.debug("Added AsynchrounsCommandListener {} to HWHighLevelDriver", afListner.getClass().getName());
+ } else {
+ logger.debug("Could not add AsynchrounsCommandListener {} to HWHighLevelDriver", afListner.getClass().getName());
+ }
+ }
+ boolean result = false;
+ synchronized (afMessageListners) {
+ result = afMessageListners.add(listner);
+ }
+
+ if ( result ) {
+ logger.debug("Added AFMessageListner {}:{}", listner, listner.getClass().getName());
+ return true;
+ } else {
+ logger.debug("Could not add AFMessageListner {}:{}", listner, listner.getClass().getName());
+ return false;
+ }
+ }
+
+ private boolean isNetworkReady() {
+ synchronized (this) {
+ return state.ordinal() >= DriverStatus.NETWORK_READY.ordinal()
+ && state.ordinal() < DriverStatus.CLOSED.ordinal();
+ }
+ }
+
+ private boolean isHardwareReady() {
+ synchronized (this) {
+ return state.ordinal() >= DriverStatus.HARDWARE_READY.ordinal()
+ && state.ordinal() < DriverStatus.CLOSED.ordinal();
+ }
+ }
+
+ /**
+ *
+ * @return
+ * @since 0.2.0
+ */
+ public long getExtendedPanId() {
+ if( waitForNetwork() == false ) {
+ logger.info("Failed to reach the {} level: getExtendedPanId() failed", DriverStatus.NETWORK_READY);
+ return -1;
+ }
+
+ int[] result = getDeviceInfo(ZB_GET_DEVICE_INFO.DEV_INFO_TYPE.EXT_PAN_ID);
+
+ if( result == null ){
+ return -1;
+ } else {
+ return Integers.shortFromInts(result, 7, 0);
+ } }
+
+ /**
+ *
+ * @return
+ * @since 0.2.0
+ */
+ public long getIEEEAddress() {
+
+ if( ieeeAddress != -1 ){
+ return ieeeAddress;
+ }
+
+ if( waitForNetwork() == false ) {
+ logger.info("Failed to reach the {} level: getIEEEAddress() failed", DriverStatus.NETWORK_READY);
+ return -1;
+ }
+
+ int[] result = getDeviceInfo(ZB_GET_DEVICE_INFO.DEV_INFO_TYPE.IEEE_ADDR);
+
+ if( result == null ){
+ return -1;
+ } else {
+ ieeeAddress = Integers.longFromInts(result, 7, 0);
+ return ieeeAddress;
+ }
+ }
+
+ /**
+ *
+ * @return
+ * @since 0.2.0
+ */
+ public int getCurrentPanId(){
+ if( waitForNetwork() == false ) {
+ logger.info("Failed to reach the {} level: getCurrentPanId() failed", DriverStatus.NETWORK_READY);
+ return -1;
+ }
+
+ int[] result = getDeviceInfo(ZB_GET_DEVICE_INFO.DEV_INFO_TYPE.PAN_ID);
+
+ if( result == null ){
+ return -1;
+ } else {
+ return Integers.shortFromInts(result, 1, 0);
+ }
+ }
+
+ /**
+ *
+ * @return
+ * @since 0.2.0
+ */
+ public int getCurrentChannel(){
+ if( waitForNetwork() == false ) {
+ logger.info("Failed to reach the {} level: getCurrentChannel() failed", DriverStatus.NETWORK_READY);
+ return -1;
+ }
+
+ int[] result = getDeviceInfo(ZB_GET_DEVICE_INFO.DEV_INFO_TYPE.CHANNEL);
+
+ if( result == null ){
+ return -1;
+ } else {
+ return result[0];
+ }
+ }
+
+ /**
+ *
+ * @return
+ * @since 0.2.0
+ */
+ public int getCurrentState(){
+ if( waitForNetwork() == false ) {
+ logger.info("Failed to reach the {} level: getCurrentChannel() failed", DriverStatus.NETWORK_READY);
+ return -1;
+ }
+
+ int[] result = getDeviceInfo(ZB_GET_DEVICE_INFO.DEV_INFO_TYPE.STATE);
+
+ if( result == null ){
+ return -1;
+ } else {
+ return result[0];
+ }
+ }
+
+
+ private int[] getDeviceInfo(int type){
+ ZB_GET_DEVICE_INFO_RSP response = (ZB_GET_DEVICE_INFO_RSP) sendSynchrouns(
+ high, new ZB_GET_DEVICE_INFO(type)
+ );
+
+ if ( response == null ){
+ logger.debug("Failed getDeviceInfo for {} due to null value", type);
+ return null;
+ } else if ( response.Param != type ) {
+ logger.debug("Failed getDeviceInfo for {} non matching response returned {}", type, response.Param);
+ return null;
+ } else {
+ logger.debug("Successed getDeviceInfo for {}", type);
+ return response.Value;
+ }
+ }
+
+ public DriverStatus getDriverStatus() {
+ return state;
+ }
+
+ public int getZigBeeNodeMode() {
+ // TODO Auto-generated method stub
+ return -1;
+ }
+}
+
Propchange: projects/zb4osgi/sandbox/miguel.llorente/zibgee.tsb.driver/src/main/java/it/cnr/isti/zigbee/dongle/tsb/impl/DriverTSB.java
------------------------------------------------------------------------------
svn-mine-type = text/plain
Propchange: projects/zb4osgi/sandbox/miguel.llorente/zibgee.tsb.driver/src/main/java/it/cnr/isti/zigbee/dongle/tsb/impl/DriverTSB.java
------------------------------------------------------------------------------
svn:eol-style = native
Propchange: projects/zb4osgi/sandbox/miguel.llorente/zibgee.tsb.driver/src/main/java/it/cnr/isti/zigbee/dongle/tsb/impl/DriverTSB.java
------------------------------------------------------------------------------
svn:keywords = Id Author Date Revision
Added: projects/zb4osgi/sandbox/miguel.llorente/zibgee.tsb.driver/src/main/java/it/cnr/isti/zigbee/dongle/tsb/impl/DriverTSBi.java
==============================================================================
--- projects/zb4osgi/sandbox/miguel.llorente/zibgee.tsb.driver/src/main/java/it/cnr/isti/zigbee/dongle/tsb/impl/DriverTSBi.java (added)
+++ projects/zb4osgi/sandbox/miguel.llorente/zibgee.tsb.driver/src/main/java/it/cnr/isti/zigbee/dongle/tsb/impl/DriverTSBi.java Fri May 20 11:42:58 2011
@@ -1,0 +1,1380 @@
+package it.cnr.isti.zigbee.dongle.tsb.impl;
+
+import javax.comm.CommPortIdentifier;
+import it.cnr.isti.cc2480.high.AsynchrounsCommandListener;
+import it.cnr.isti.cc2480.high.HWHighLevelDriver;
+import it.cnr.isti.cc2480.high.SynchrounsCommandListner;
+import it.cnr.isti.cc2480.low.HWLowLevelDriver;
+import it.cnr.isti.cc2480.low.PacketListener;
+import it.cnr.isti.primitvetypes.util.Integers;
+import it.cnr.isti.zigbee.dongle.api.AFMessageListner;
+import it.cnr.isti.zigbee.dongle.api.AnnunceListner;
+import it.cnr.isti.zigbee.dongle.api.DriverStatus;
+import it.cnr.isti.zigbee.dongle.api.NetworkMode;
+import it.cnr.isti.zigbee.dongle.api.SimpleDriver;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Enumeration;
+import java.util.HashSet;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import com.itaca.ztool.api.ZToolAddress16;
+import com.itaca.ztool.api.ZToolAddress64;
+import com.itaca.ztool.api.ZToolCMD;
+import com.itaca.ztool.api.ZToolException;
+import com.itaca.ztool.api.ZToolPacket;
+import com.itaca.ztool.api.af.AF_DATA_CONFIRM;
+import com.itaca.ztool.api.af.AF_DATA_REQUEST;
+import com.itaca.ztool.api.af.AF_DATA_SRSP;
+import com.itaca.ztool.api.af.AF_INCOMING_MSG;
+import com.itaca.ztool.api.af.AF_REGISTER;
+import com.itaca.ztool.api.af.AF_REGISTER_SRSP;
+import com.itaca.ztool.api.simple.ZB_GET_DEVICE_INFO;
+import com.itaca.ztool.api.simple.ZB_GET_DEVICE_INFO_RSP;
+import com.itaca.ztool.api.simple.ZB_READ_CONFIGURATION;
+import com.itaca.ztool.api.simple.ZB_READ_CONFIGURATION_RSP;
+import com.itaca.ztool.api.simple.ZB_WRITE_CONFIGURATION;
+import com.itaca.ztool.api.simple.ZB_WRITE_CONFIGURATION_RSP;
+import com.itaca.ztool.api.system.SYS_RESET;
+import com.itaca.ztool.api.system.SYS_RESET_RESPONSE;
+import com.itaca.ztool.api.system.SYS_VERSION;
+import com.itaca.ztool.api.util.UTIL_GET_DEVICE_INFO;
+import com.itaca.ztool.api.util.UTIL_GET_DEVICE_INFO_RESPONSE;
+import com.itaca.ztool.api.zdo.ZDO_ACTIVE_EP_REQ;
+import com.itaca.ztool.api.zdo.ZDO_ACTIVE_EP_REQ_SRSP;
+import com.itaca.ztool.api.zdo.ZDO_ACTIVE_EP_RSP;
+import com.itaca.ztool.api.zdo.ZDO_BIND_REQ;
+import com.itaca.ztool.api.zdo.ZDO_BIND_REQ_SRSP;
+import com.itaca.ztool.api.zdo.ZDO_BIND_RSP;
+import com.itaca.ztool.api.zdo.ZDO_END_DEVICE_ANNCE_IND;
+import com.itaca.ztool.api.zdo.ZDO_IEEE_ADDR_REQ;
+import com.itaca.ztool.api.zdo.ZDO_IEEE_ADDR_REQ_SRSP;
+import com.itaca.ztool.api.zdo.ZDO_IEEE_ADDR_RSP;
+import com.itaca.ztool.api.zdo.ZDO_MGMT_LEAVE_REQ;
+import com.itaca.ztool.api.zdo.ZDO_MGMT_LEAVE_REQ_SRSP;
+import com.itaca.ztool.api.zdo.ZDO_MGMT_LEAVE_RSP;
+import com.itaca.ztool.api.zdo.ZDO_NODE_DESC_REQ;
+import com.itaca.ztool.api.zdo.ZDO_NODE_DESC_REQ_SRSP;
+import com.itaca.ztool.api.zdo.ZDO_NODE_DESC_RSP;
+import com.itaca.ztool.api.zdo.ZDO_SIMPLE_DESC_REQ;
+import com.itaca.ztool.api.zdo.ZDO_SIMPLE_DESC_REQ_SRSP;
+import com.itaca.ztool.api.zdo.ZDO_SIMPLE_DESC_RSP;
+import com.itaca.ztool.api.zdo.ZDO_STARTUP_FROM_APP;
+import com.itaca.ztool.api.zdo.ZDO_STARTUP_FROM_APP_SRSP;
+import com.itaca.ztool.api.zdo.ZDO_UNBIND_REQ;
+import com.itaca.ztool.api.zdo.ZDO_UNBIND_REQ_SRSP;
+import com.itaca.ztool.api.zdo.ZDO_UNBIND_RSP;
+
+/**
+ *
+ * @author <a href="mailto:stefano.lenzi at isti.cnr.it">Stefano "Kismet" Lenzi</a>
+ * @version $LastChangedRevision$ ($LastChangedDate$)
+ * @since 0.1.0
+ *
+ */
+public class DriverTSBi implements Runnable, SimpleDriver{
+
+ private final static Logger logger = LoggerFactory.getLogger(DriverTSBi.class);
+ private final static Logger logger4Waiter = LoggerFactory.getLogger(WaitForCommand.class);
+
+ private Thread driver;
+
+ private HWHighLevelDriver high;
+ private HWLowLevelDriver low;
+ private String port;
+ private int rate;
+ private DriverStatus state;
+ private NetworkMode mode;
+ private short pan;
+ private byte channel;
+ private boolean cleanStatus;
+
+ private long TIMEOUT = 5000;//Activator.getCurrentConfiguration().getZigBeeTimeout();
+
+ private final HashSet<AnnunceListner> annunceListners = new HashSet<AnnunceListner>();
+ private final AnnunceListerFilter annunceListner = new AnnunceListerFilter(annunceListners);
+
+ private final ArrayList<AFMessageListner> afMessageListners = new ArrayList<AFMessageListner>();
+ private final AFMessageListnerFilter afListner = new AFMessageListnerFilter(afMessageListners);
+
+ private long ieeeAddress = -1;
+
+ private class AnnunceListerFilter implements AsynchrounsCommandListener{
+
+ private final Collection<AnnunceListner> listners;
+
+ private AnnunceListerFilter(Collection<AnnunceListner> list){
+ listners = list;
+ }
+
+ public void receivedAsynchrounsCommand(ZToolPacket packet) {
+ if(packet.isError()) return;
+ if(packet.getCMD().get16BitValue() == ZToolCMD.ZDO_END_DEVICE_ANNCE_IND){
+ ZDO_END_DEVICE_ANNCE_IND annunce = (ZDO_END_DEVICE_ANNCE_IND) packet;
+ for (AnnunceListner l : listners) {
+ l.notify(annunce.SrcAddr, annunce.IEEEAddr, annunce.NwkAddr, annunce.Capabilities);
+ }
+ }
+ }
+
+ }
+
+ private class AFMessageListnerFilter implements AsynchrounsCommandListener{
+
+ private final Collection<AFMessageListner> listners;
+
+ private AFMessageListnerFilter(Collection<AFMessageListner> list){
+ listners = list;
+ }
+
+ public void receivedAsynchrounsCommand(ZToolPacket packet) {
+ if(packet.isError()) return;
+ if(packet.getCMD().get16BitValue() == ZToolCMD.AF_INCOMING_MSG){
+ AF_INCOMING_MSG msg = (AF_INCOMING_MSG) packet;
+ if( listners.isEmpty() ){
+ logger.debug("Recieved AF_INCOMING_MSG but no listeners. Message was: {} ", msg);
+ } else {
+ logger.debug("Recieved AF_INCOMING_MSG notifying {} listeners of {}", listners.size(), msg);
+ }
+ ArrayList<AFMessageListner> localCopy = null;
+ synchronized (listners) {
+ localCopy = new ArrayList<AFMessageListner>(listners);
+ }
+ for ( AFMessageListner l : localCopy){
+// if( l.match(
+// msg.getClusterId(), msg.getSrcAddr(),
+// msg.getSrcEndpoint(), msg.getDstEndpoint(),
+// msg.getTransId()
+// ) ) {
+ l.notify(msg);
+// }
+ }
+ }
+ }
+
+ }
+
+ public DriverTSBi(String serialPort, int bitrate) throws ZToolException {
+ this(serialPort,bitrate,NetworkMode.Coordinator,0,19, false);
+ }
+
+ public DriverTSBi(
+ String serialPort, int bitrate, NetworkMode mode, int pan, int channel
+ ) throws ZToolException {
+
+ this(serialPort, bitrate, mode, pan, channel, false);
+ }
+
+ public DriverTSBi(
+ String serialPort, int bitRate, NetworkMode mode, int pan, int channel, boolean cleanNetworkStatus
+ ) throws ZToolException {
+
+ state = DriverStatus.CLOSED;
+ this.cleanStatus = cleanNetworkStatus;
+ setSerialPort(serialPort, bitRate);
+ setZigBeeNetwork((byte)channel, (short)pan);
+ setZigBeeNodeMode(mode);
+
+ }
+
+ private String buildDriverThreadName(String serialPort, int bitrate) {
+ return "SimpleDriver["+serialPort+","+bitrate+"]";
+ }
+
+ public void setZigBeeNodeMode(NetworkMode m) {
+ if ( state != DriverStatus.CLOSED ) {
+ throw new IllegalStateException("Network mode can be changed only " +
+ "if driver is CLOSED while it is:"+state);
+ }
+ cleanStatus = mode != m;
+ mode = m;
+ }
+
+ public void setZigBeeNetwork(byte ch, short panId) {
+ if ( state != DriverStatus.CLOSED ) {
+ throw new IllegalStateException("Network mode can be changed only " +
+ "if driver is CLOSED while it is:"+state);
+ }
+ cleanStatus = ch != channel || panId != pan;
+ channel = ch;
+ pan = panId;
+ }
+
+ public void setSerialPort(String serialName,int bitRate) {
+ if ( state != DriverStatus.CLOSED ) {
+ throw new IllegalStateException("Serial port can be changed only " +
+ "if driver is CLOSED while it is:"+state);
+ }
+ port = serialName;
+ rate = bitRate;
+ }
+
+ public void open(boolean cleanCache){
+ cleanStatus = cleanCache;
+ open();
+ }
+
+ public void open(){
+ if ( state == DriverStatus.CLOSED ) {
+ state = DriverStatus.CREATED;
+ driver = new Thread(this);
+ driver.setName(buildDriverThreadName(port,rate));
+ driver.start();
+ }else{
+ throw new IllegalStateException("Driver already opened, current status is:"+state);
+ }
+ }
+
+ public void close(){
+ if(state == DriverStatus.CLOSED){
+ logger.debug("Already CLOSED");
+ return;
+ }
+ logger.info("Closing");
+ if( Thread.currentThread() != driver ){
+ logger.debug("Waiting for intialization operation to complete before closing");
+ try {
+ driver.join();
+ } catch (InterruptedException ignored) {
+ }
+ }else{
+ logger.debug("Self closing");
+ }
+ if(state == DriverStatus.NETWORK_READY){
+ logger.debug("Closing NETWORK");
+ setState(DriverStatus.HARDWARE_READY);
+ }
+ if(state == DriverStatus.HARDWARE_READY){
+ logger.debug("Closing HARDWARE");
+ high.close();
+ logger.debug("Closing LOW HARDWARE");
+ low.close();
+ setState(DriverStatus.CREATED);
+ }
+ if(state == DriverStatus.CREATED){
+ setState(DriverStatus.CLOSED);
+ }
+ logger.info("Closed");
+ }
+
+ public ZDO_IEEE_ADDR_RSP sendZDOIEEEAddressRequest(ZDO_IEEE_ADDR_REQ request){
+ if( waitForNetwork() == false ) return null;
+
+ final WaitForCommand waiter = new WaitForCommand(ZToolCMD.ZDO_IEEE_ADDR_RSP, high);
+
+ logger.debug("Sending ZDO_IEEE_ADDR_REQ {}", request);
+ ZDO_IEEE_ADDR_REQ_SRSP response = (ZDO_IEEE_ADDR_REQ_SRSP) sendSynchrouns(high, request);
+ if ( response == null || response.Status != 0 ) {
+ logger.debug("ZDO_IEEE_ADDR_REQ failed, recieved {}", response);
+ waiter.cleanup();
+ return null;
+ } else {
+ return (ZDO_IEEE_ADDR_RSP) waiter.getCommand(TIMEOUT);
+ }
+ }
+
+ public ZDO_NODE_DESC_RSP sendZDONodeDescriptionRequest(ZDO_NODE_DESC_REQ request) {
+ if( waitForNetwork() == false ) return null;
+
+ final WaitForCommand waiter = new WaitForCommand(ZToolCMD.ZDO_NODE_DESC_RSP, high);
+
+ ZDO_NODE_DESC_REQ_SRSP response = (ZDO_NODE_DESC_REQ_SRSP) sendSynchrouns(high, request);
+ if ( response == null || response.Status != 0 ) {
+ waiter.cleanup();
+ return null;
+ } else {
+ return (ZDO_NODE_DESC_RSP) waiter.getCommand(TIMEOUT);
+ }
+ }
+
+ public ZDO_ACTIVE_EP_RSP sendZDOActiveEndPointRequest(ZDO_ACTIVE_EP_REQ request) {
+ if( waitForNetwork() == false ) return null;
+
+ final WaitForCommand waiter = new WaitForCommand(ZToolCMD.ZDO_ACTIVE_EP_RSP, high);
+
+ logger.debug("Sending ZDO_ACTIVE_EP_REQ {}", request);
+ ZDO_ACTIVE_EP_REQ_SRSP response = (ZDO_ACTIVE_EP_REQ_SRSP) sendSynchrouns(high, request);
+ if ( response == null || response.Status != 0 ) {
+ logger.debug("ZDO_ACTIVE_EP_REQ failed, recieved {}", response);
+ waiter.cleanup();
+ return null;
+ } else {
+ return (ZDO_ACTIVE_EP_RSP) waiter.getCommand(TIMEOUT);
+ }
+ }
+
+ public ZDO_SIMPLE_DESC_RSP sendZDOSimpleDescriptionRequest(ZDO_SIMPLE_DESC_REQ request) {
+ if( waitForNetwork() == false ) return null;
+
+ final WaitForCommand waiter = new WaitForCommand(ZToolCMD.ZDO_SIMPLE_DESC_RSP, high);
+
+ ZDO_SIMPLE_DESC_REQ_SRSP response = (ZDO_SIMPLE_DESC_REQ_SRSP) sendSynchrouns(high, request);
+ if ( response == null || response.Status != 0 ) {
+ waiter.cleanup();
+ return null;
+ } else {
+ return (ZDO_SIMPLE_DESC_RSP) waiter.getCommand(TIMEOUT);
+ }
+ }
+
+ public void run() {
+ logger.info("Intializing");
+ setState(DriverStatus.HARDWARE_INITIALIZING);
+ if(initializeHardware() == true){
+ setState(DriverStatus.HARDWARE_READY);
+ }else{
+ close();
+ return;
+ }
+
+ setState(DriverStatus.NETWORK_INITIALIZING);
+ if(initializeZigBeeNetwork() == true){
+ setState(DriverStatus.NETWORK_READY);
+ }else{
+ close();
+ return;
+ }
+ }
+
+
+ @SuppressWarnings("unchecked")
+ private boolean initializeHardware() {
+ String portToOpen = null;
+ if("auto".equalsIgnoreCase(port)){
+ logger.info("Automatic discovery the dongle port by inspecting all the serail ports");
+ Enumeration<CommPortIdentifier> ports = CommPortIdentifier.getPortIdentifiers();
+ while(ports.hasMoreElements()){
+ CommPortIdentifier com = ports.nextElement();
+ if(DriverTSBi.initializeHardware(com.getName(), rate)){
+ portToOpen=com.getName();
+ Thread.currentThread().setName(buildDriverThreadName(portToOpen, rate));
+ break;
+ }
+ }
+ if ( portToOpen == null ) {
+ logger.error("Automatic discovery FAILED the dongle couldn't be find on any port: it may be frozen");
+ return false;
+ }
+ }else{
+ if( DriverTSBi.initializeHardware(port, rate) == true ){
+ portToOpen = port;
+ } else {
+ logger.error("Failed to intialize the dongle on port {} at rate {}", port, rate);
+ return false;
+ }
+ }
+
+ low = new HWLowLevelDriver();
+ try {
+ low.open(portToOpen, rate);
+ } catch (ZToolException e) {
+ logger.error("The port was already open in advance but we can't open it now",e);
+ return false;
+ }
+ high = new HWHighLevelDriver(low);
+ return true;
+ }
+
+ private void setState(DriverStatus value) {
+ logger.info("State changed from {} to {}", this.state, value);
+ synchronized (this) {
+ state = value;
+ notifyAll();
+ }
+ if(state == DriverStatus.HARDWARE_READY){
+ postHardwareEnabled();
+ }
+ }
+
+ private void postHardwareEnabled() {
+ if( ! afMessageListners.isEmpty() ){
+ high.addAsynchrounsCommandListener(afListner);
+ }
+ if( ! annunceListners.isEmpty() ){
+ high.addAsynchrounsCommandListener(annunceListner);
+ }
+ }
+
+ static boolean initializeHardware(String portName, int boudRate) {
+ boolean result = false;
+ final int recieved[] = new int[1];
+ final HWLowLevelDriver probingDriver = new HWLowLevelDriver();
+ final PacketListener monitor = new PacketListener(){
+ public void packetRecieved(ZToolPacket packet) {
+ if(packet.getCommandId() == ZToolCMD.SYS_VERSION_RESPONSE){
+ logger.debug("Initializing Hardware: Received correctly SYS_VERSION_RESPONSE");
+ synchronized (recieved) {
+ recieved[0] = 3;
+ }
+ } else if(packet.isError()){
+ logger.debug("Initializing Hardware: Received erroneous packet: {}",packet.getErrorMsg());
+ synchronized (recieved) {
+ recieved[0] += 1;
+ }
+ } else {
+ logger.debug("Initializing Hardware: Received {}",packet.getClass().getName());
+ synchronized (recieved) {
+ recieved[0] += 1;
+ }
+ }
+ }
+
+ };
+ probingDriver.addPacketListener(monitor);
+ try {
+ probingDriver.open(portName,boudRate);
+ probingDriver.sendPacket(new SYS_VERSION());
+ final long ready = System.currentTimeMillis() + 5000;
+ while(ready > System.currentTimeMillis()){
+ synchronized (recieved) {
+ if( recieved[0] == 3 ){
+ break;
+ }
+ }
+
+ try {
+ Thread.sleep(500);
+ } catch (InterruptedException ignored) {
+ }
+ }
+ synchronized (recieved) {
+ if( recieved[0] == 3 ){
+ result = true;
+ }
+ }
+ } catch (ZToolException e) {
+ logger.info("Unable to open serial port: {}", portName);
+ logger.error("Unable to open serial port, due to:", e);
+ }catch (IOException e) {
+ logger.error("Hardware initialization failed", e);
+ }
+ probingDriver.close();
+ probingDriver.removePacketListener(monitor);
+ return result;
+ }
+
+ private boolean waitForHardware() {
+ synchronized (this) {
+ while (state == DriverStatus.CREATED || state == DriverStatus.CLOSED ){
+ logger.debug("Waiting for HARDWARE to become ready");
+ try {
+ wait();
+ } catch (InterruptedException ignored) {
+ }
+ }
+ return isHardwareReady();
+ }
+ }
+
+ private boolean waitForNetwork() {
+ synchronized (this) {
+ while (state != DriverStatus.NETWORK_READY && state != DriverStatus.CLOSED ){
+ logger.debug("Waiting for NETWORK to become ready");
+ try {
+ wait();
+ } catch (InterruptedException ignored) {
+ }
+ }
+ return isNetworkReady();
+ }
+ }
+
+ private class WaitForCommand implements AsynchrounsCommandListener{
+
+ final ZToolPacket[] result = new ZToolPacket[]{null};
+ final int waitFor;
+ final HWHighLevelDriver driver;
+
+ public WaitForCommand(int waitFor, HWHighLevelDriver driver) {
+ this.waitFor = waitFor;
+ this.driver = driver;
+ driver.addAsynchrounsCommandListener(this);
+ }
+
+
+
+ public void receivedAsynchrounsCommand(ZToolPacket packet) {
+ logger4Waiter.info("Recieved a packet {} and waiting for {}", packet.getCMD(), waitFor);
+ logger4Waiter.debug("Recieved {} {}", packet.getClass(), packet.toString());
+ if( packet.isError() ) return;
+ if( packet.getCMD().get16BitValue() != waitFor) return;
+ synchronized (result) {
+ result[0]=packet;
+ logger4Waiter.info("Recieved packet that we were waiting for");
+ cleanup();
+ }
+ }
+
+ public ZToolPacket getCommand(final long timeout){
+ synchronized (result) {
+ final long wakeUpTime = System.currentTimeMillis() + timeout;
+ while(result[0] == null && wakeUpTime > System.currentTimeMillis()){
+ try {
+ result.wait(wakeUpTime-System.currentTimeMillis());
+ } catch (InterruptedException ignored) {
+ }
+
+ }
+ }
+ if( result[0] == null ){
+ logger4Waiter.warn("Timeout {} expired and not packet with {} recieved", timeout, waitFor);
+ }
+ cleanup();
+ return result[0];
+ }
+
+ public void cleanup(){
+ synchronized (result) {
+ driver.removeAsynchrounsCommandListener(this);
+ result.notify();
+ }
+ }
+ }
+
+// private class WaitForAList implements PacketListener{
+//
+// final int[] waitingList;
+// final ZToolPacket[] packetHistory;
+// final HWLowLevelDriver hwDriver;
+// int idx = 0;
+//
+// /**
+// * This constructor uses the {@link WaitForAList#WaitForAList(int[], ZToolPacket[], HWLowLevelDriver) constructor<br>
+// * with the following parameters <code>WaitForAList(list,null,null)</code>
+// *
+// * @see WaitForAList#WaitForAList(int[], ZToolPacket[], HWLowLevelDriver)
+// * @param list
+// */
+// public WaitForAList(final int[] list){
+// this(list, null, null);
+// }
+//
+// /**
+// * Create a {@link WaitForAList} that wait for a specified list<br>
+// * of packet to be received. Furthermore, the {@link WaitForAList}<br>
+// * while record all the matching packet received, and it will handle<br>
+// * by itself the registration and unregistration as {@link PacketListener}<br>
+// * to the specified {@link HWLowLevelDriver}.<br>
+// * <br>
+// * <b>NOTE:</b>If the {@link ZToolPacket} array is null no packet will be recorded<br>
+// * <b>NOTE:</b>If the {@link HWLowLevelDriver} array is null registration and unregistration as<br>
+// * {@link PacketListener} must be handled by the invoker<br>
+// *
+// * @param list the array of <code>int</code> to listen to
+// * @param packets {@link ZToolPacket} the array of the same size as <code>list</code> to record the received packet
+// * @param lowDriver {@link HWLowLevelDriver} to register to, if <code>null</code> to handle registration/unregistration manually
+// */
+// public WaitForAList(
+// final int[] list,
+// final ZToolPacket[] packets,
+// final HWLowLevelDriver lowDriver){
+// this.waitingList = list;
+// this.packetHistory = packets;
+// this.hwDriver = lowDriver;
+// if ( hwDriver != null) {
+// hwDriver.addPacketListener(this);
+// }
+// }
+//
+// public void waitForAll(long timeout){
+// long wakeUpTime = System.currentTimeMillis() + timeout;
+// synchronized (waitingList) {
+// while( idx < waitingList.length && wakeUpTime > System.currentTimeMillis()){
+// try {
+// waitingList.wait(wakeUpTime - System.currentTimeMillis());
+// } catch (InterruptedException ignored) {
+// }
+// }
+// }
+// }
+//
+// public void packetRecieved(ZToolPacket packet) {
+// if(packet.isError()) return;
+// if((packet.getCommandId() & 0xFFFF) == waitingList[idx]){
+// logger.info("Recieved packet that was waiting for incresing waitingList");
+// synchronized (waitingList) {
+// if ( packetHistory != null ) {
+// packetHistory[idx] = packet;
+// }
+// idx = idx + 1;
+// if ( idx == waitingList.length ){
+// if ( low != null) {
+// low.removePacketListener(this);
+// }
+// waitingList.notifyAll();
+// return;
+// }
+// }
+// }
+// }
+//
+// }
+
+
+ private boolean dongleReset(){
+ if( waitForHardware() == false ) return false;
+
+ final WaitForCommand waiter = new WaitForCommand(
+ ZToolCMD.SYS_RESET_RESPONSE,
+ high
+ );
+
+// WaitForAList waiting = new WaitForAList(new int[]{
+// ZToolCMD.SYS_RESET_RESPONSE,
+// ZToolCMD.ZB_APP_REGISTER_RSP,
+// ZToolCMD.ZB_WRITE_CONFIGURATION_RSP,
+// ZToolCMD.ZB_WRITE_CONFIGURATION_RSP
+// });
+
+// low.addPacketListener(waiting);
+
+ try {
+ high.sendAsynchrounsCommand(new SYS_RESET(SYS_RESET.RESET_TYPE.TARGET_DEVICE));
+ } catch (IOException e) {
+ logger.error("DongleReset failed", e);
+ return false;
+ }
+
+ SYS_RESET_RESPONSE response =
+ (SYS_RESET_RESPONSE) waiter.getCommand(TIMEOUT);
+
+// waiting.waitForAll(TIMEOUT*2);
+// low.removePacketListener(waiting);
+ return response != null;
+ }
+
+// private boolean dongleClearState(){
+// ZB_WRITE_CONFIGURATION_RSP response;
+// response = (ZB_WRITE_CONFIGURATION_RSP) sendSynchrouns(
+// high,
+// new ZB_WRITE_CONFIGURATION(
+// ZB_WRITE_CONFIGURATION.CONFIG_ID.ZCD_NV_STARTUP_OPTION,
+// new int[]{0x00000002}
+// )
+// );
+//
+// if( response == null || response.Status != 0) {
+// logger.info("Couldn't set ZCD_NV_STARTUP_OPTION to CLEAN_STATE");
+// return false;
+// }else{
+// logger.info("Set ZCD_NV_STARTUP_OPTION to CLEAN_STATE");
+// }
+//
+// boolean result = dongleReset();
+//
+// response = (ZB_WRITE_CONFIGURATION_RSP) sendSynchrouns(
+// high,
+// new ZB_WRITE_CONFIGURATION(
+// ZB_WRITE_CONFIGURATION.CONFIG_ID.ZCD_NV_STARTUP_OPTION,
+// new int[]{0x00000000}
+// )
+// );
+//
+// if( response == null || response.Status != 0) {
+// logger.info("Couldn't set ZCD_NV_STARTUP_OPTION back to DO_NOTHING");
+// }
+//
+// return result;
+// }
+
+ static final int[] buildChannelMask(int channel){
+ int channelMask = 1 << channel;
+ int[] mask = new int[4];
+ for (int i = 0; i < mask.length; i++) {
+ mask[i] = Integers.getByteAsInteger(channelMask, i);
+ }
+ return mask;
+ }
+
+// private boolean dongleSetChannel(int[] channelMask) {
+//
+// logger.info(
+// "Setting the channel to {}{}{}{}", new Object[]{
+// Integer.toHexString(channelMask[0]),
+// Integer.toHexString(channelMask[1]),
+// Integer.toHexString(channelMask[2]),
+// Integer.toHexString(channelMask[3])
+// }
+// );
+//
+// ZB_WRITE_CONFIGURATION_RSP response =
+// (ZB_WRITE_CONFIGURATION_RSP) sendSynchrouns(
+// high,
+// new ZB_WRITE_CONFIGURATION(
+// ZB_WRITE_CONFIGURATION.CONFIG_ID.ZCD_NV_CHANLIST,
+// channelMask
+// )
+// );
+//
+// return response != null && response.Status == 0;
+// }
+
+// private boolean dongleSetChannel(int ch){
+// int[] channelMask = buildChannelMask(ch);
+//
+// return dongleSetChannel(channelMask);
+// }
+//
+// private boolean dongleSetChannel(){
+// int[] channelMask = buildChannelMask(channel);
+//
+// return dongleSetChannel(channelMask);
+// }
+//
+// private boolean dongleSetNetworkMode(){
+// logger.info("Changing the Network Mode to {}", mode);
+//
+// ZB_WRITE_CONFIGURATION_RSP response =
+// (ZB_WRITE_CONFIGURATION_RSP) sendSynchrouns(
+// high,
+// new ZB_WRITE_CONFIGURATION(
+// ZB_WRITE_CONFIGURATION.CONFIG_ID.ZCD_NV_LOGICAL_TYPE,
+// new int[]{ mode.ordinal() }
+// )
+// );
+//
+// return response != null && response.Status == 0;
+// }
+//
+// private boolean dongleSetPanId(){
+// ZB_WRITE_CONFIGURATION_RSP response =
+// (ZB_WRITE_CONFIGURATION_RSP) sendSynchrouns(
+// high,
+// new ZB_WRITE_CONFIGURATION(
+// ZB_WRITE_CONFIGURATION.CONFIG_ID.ZCD_NV_PANID,
+// new int[]{
+// Integers.getByteAsInteger(pan, 0),
+// Integers.getByteAsInteger(pan, 1)
+// }
+// )
+// );
+//
+// return response != null && response.Status == 0;
+// }
+
+
+ private boolean createZigBeeNetwork(boolean reset){
+ /*
+ * NOTE:The dongle has to be reset all the time to avoid that the endpoints
+ * register on the dongle itself break the code at upper level
+ *
+ */
+ if( reset && dongleReset() ) {
+ logger.debug("Reset the dongle before Creating ZigBee Network");
+ } else if (reset) {
+ logger.debug("FAILED to reset the dongle before Creating ZigBee Network");
+ } else {
+ logger.debug("Dongle has already been reset so no endpoint registered");
+ }
+ switch (mode) {
+ case Coordinator:
+ return doCoordinatorCreateNetwork();
+ case Router:
+ //TODO Implements start up as Router
+ return false;
+ case EndDevice:
+ return false;
+// return doEndDeviceCreateNetwok();
+ }
+
+ /*
+ * This code is unreachable but compiler can't find this out yet.
+ * It may introduce a compilation issue of future compilers
+ */
+ return false;
+ }
+
+// private boolean doEndDeviceCreateNetwok() {
+// logger.debug("Creating network as EndDevice");
+//
+// final WaitForAList completeWait = new WaitForAList(
+// new int[]{
+// ZToolCMD.ZB_START_CONFIRM,
+// ZToolCMD.ZB_GET_DEVICE_INFO_RSP,
+// ZToolCMD.ZB_GET_DEVICE_INFO_RSP
+// },
+// new ZToolPacket[3],
+// low
+// );
+//
+// final WaitForCommand waiter = new WaitForCommand(ZToolCMD.ZB_START_CONFIRM,high);
+//
+// ZB_START_CONFIRM result = null;
+// ZB_START_REQUEST_RSP response = (ZB_START_REQUEST_RSP) sendSynchrouns(
+// high, new ZB_START_REQUEST()
+// );
+// if ( response == null ) {
+// waiter.cleanup();
+// return false;
+// } else {
+// result = (ZB_START_CONFIRM) waiter.getCommand(TIMEOUT);
+// }
+//
+// completeWait.waitForAll(TIMEOUT * 2);
+//
+// return result != null && result.Status == ZB_START_CONFIRM.AF_STATUS.SUCCESS;
+// }
+
+ private boolean doCoordinatorCreateNetwork() {
+ logger.info("Creating network as Coordintator");
+
+ if(cleanStatus){
+ //---------START FROM APP
+ ZDO_STARTUP_FROM_APP_SRSP responseA1 = (ZDO_STARTUP_FROM_APP_SRSP) sendSynchrouns(
+ high, new ZDO_STARTUP_FROM_APP(ZDO_STARTUP_FROM_APP.RESET_TYPE.TARGET_DEVICE)
+ );
+ if (responseA1==null)return false;
+ //---------ZB WRITE CONF
+ ZB_WRITE_CONFIGURATION_RSP responseA2 = (ZB_WRITE_CONFIGURATION_RSP) sendSynchrouns(
+ high, new ZB_WRITE_CONFIGURATION(3,new int[]{2})
+ );
+ if (responseA2==null)return false;
+ //---------GET DEVICE INFO
+ final WaitForCommand waiter1 = new WaitForCommand(
+ ZToolCMD.UTIL_GET_DEVICE_INFO_RESPONSE,
+ high
+ );
+ try{
+ high.sendAsynchrounsCommand(new UTIL_GET_DEVICE_INFO());
+ } catch (IOException e) {
+ logger.error("GetDeviceInfo of Master Reset failed", e);
+ return false;
+ }
+ UTIL_GET_DEVICE_INFO_RESPONSE responseA3 = (UTIL_GET_DEVICE_INFO_RESPONSE) waiter1.getCommand(TIMEOUT);
+ if (responseA3==null)return false;
+ ZToolAddress16[] addresses = new ZToolAddress16[responseA3.AssocDevicesList.length];
+ for(int k=0;k<responseA3.AssocDevicesList.length;k++){
+ addresses[k]=new ZToolAddress16(responseA3.AssocDevicesList[k].getMsb(),responseA3.AssocDevicesList[k].getLsb());
+ }
+ //---------ZDO GET IEEE ADDR
+ ZToolAddress64[] longAddresses = new ZToolAddress64[addresses.length];
+ for(int k=0;k<addresses.length;k++){
+ ZDO_IEEE_ADDR_RSP responseA4 = sendZDOIEEEAddressRequest(new ZDO_IEEE_ADDR_REQ(addresses[k],ZDO_IEEE_ADDR_REQ.REQ_TYPE.EXTENDED.getValue(),0));
+ if (responseA4!=null){
+ longAddresses[k]=responseA4.getIEEEAddress();
+ }else{
+ longAddresses[k]=null;
+ }
+ }
+ //---------ZDO MGMT LEAVE
+ long start=System.currentTimeMillis();
+ for (int k = 0; k < longAddresses.length; k++) {
+ if (longAddresses[k] != null) {
+ WaitForCommand waiter3 = new WaitForCommand(ZToolCMD.ZDO_MGMT_LEAVE_RSP, high);
+
+ ZDO_MGMT_LEAVE_REQ_SRSP response = (ZDO_MGMT_LEAVE_REQ_SRSP) sendSynchrouns(high, new ZDO_MGMT_LEAVE_REQ(addresses[k], longAddresses[k], 3));
+ if ((System.currentTimeMillis() - start) > 5000)return false;
+ if ( response == null || response.Status != 0 ) {
+ waiter3.cleanup();
+ return false;
+ } else {
+ if ((System.currentTimeMillis() - start) > 5000)return false;
+ ZDO_MGMT_LEAVE_RSP responseA5 = (ZDO_MGMT_LEAVE_RSP) waiter3.getCommand(TIMEOUT);
+ if ((System.currentTimeMillis() - start) > 5000)return false;
+ if(responseA5==null || responseA5.Status!=ZDO_MGMT_LEAVE_RSP.ZDO_STATUS.ZDP_SUCCESS)return false;
+ }
+ }
+ if ((System.currentTimeMillis() - start) > 5000)return false;
+ }
+
+ //---------SYS RESET
+ if (!dongleReset())return false;
+ //---------START FROM APP
+
+ ZDO_STARTUP_FROM_APP_SRSP responseA7 = (ZDO_STARTUP_FROM_APP_SRSP) sendSynchrouns(
+ high, new ZDO_STARTUP_FROM_APP(ZDO_STARTUP_FROM_APP.RESET_TYPE.TARGET_DEVICE)
+ );
+ if (responseA7==null)return false;
+
+ }else{
+ //--------READ CONFIG
+ ZB_READ_CONFIGURATION_RSP responseB1 = (ZB_READ_CONFIGURATION_RSP) sendSynchrouns(
+ high, new ZB_READ_CONFIGURATION(3)
+ );
+ //--------WRITE CONFIG and/or STARTUP FROM APP
+ if(responseB1!=null){
+ ZB_WRITE_CONFIGURATION_RSP responseB2=null;
+ if(responseB1.Len==1){
+ if(responseB1.Value[0]!=0){
+ responseB2 = (ZB_WRITE_CONFIGURATION_RSP) sendSynchrouns(
+ high, new ZB_WRITE_CONFIGURATION(3,new int[]{0})
+ );
+ }
+ }else{
+ responseB2 = (ZB_WRITE_CONFIGURATION_RSP) sendSynchrouns(
+ high, new ZB_WRITE_CONFIGURATION(3,new int[]{0})
+ );
+ }
+ if(responseB2!=null){
+ ZDO_STARTUP_FROM_APP_SRSP responseB3 = (ZDO_STARTUP_FROM_APP_SRSP) sendSynchrouns(
+ high, new ZDO_STARTUP_FROM_APP(ZDO_STARTUP_FROM_APP.RESET_TYPE.TARGET_DEVICE)
+ );
+ return responseB3!=null;
+ }else{
+ return false;
+ }
+ }else{
+ return false;
+ }
+ }
+ return true;
+ }
+
+ /*
+ //TODO We should check if the current setting differs from the setting stored on the dongle
+ * and later define whetever to clean or not the cache
+ private boolean mustCleanStatus(){
+ if( cleanStatus ) {
+ return true;
+ }
+
+ createZigBeeNetwork();
+
+ int[] value;
+
+ value = getDeviceInfo(ZB_GET_DEVICE_INFO.DEV_INFO_TYPE.CHANNEL);
+ if ( value == null){
+ logger.error("Method getDeviceInfo(ZB_GET_DEVICE_INFO.DEV_INFO_TYPE.CHANNEL) returned null");
+ return true;
+ } else if ( value[0] != this.channel ) {
+ logger.debug("Dongle network state must be reset because channel is changed. " +
+ "Old was = {} while new is {}", value[0], this.channel);
+ return true;
+ }
+
+ value = getDeviceInfo(ZB_GET_DEVICE_INFO.DEV_INFO_TYPE.PAN_ID);
+ if ( value == null){
+ logger.error("Method getDeviceInfo(ZB_GET_DEVICE_INFO.DEV_INFO_TYPE.PAN_ID) returned null");
+ return true;
+ } else if ( Integers.shortFromInts(value, 1, 0) != this.pan) {
+ logger.debug("Dongle network state must be reset because PanId is changed. " +
+ "Old was = {} while new is {}", Integers.shortFromInts(value, 1, 0), this.pan);
+ return true;
+ }
+
+ dongleReset();
+
+ return false;
+ }
+ */
+
+ private boolean initializeZigBeeNetwork() {
+
+ /*
+ //TODO Fix this peace of code because it is not working
+ The right configuration procedure is:
+ - Set the clear the state
+ - Reboot
+ - Check the status from getDeviceInfo
+ - Set the configuration of: Mode, Channel, PanId, etc.
+
+ boolean cleanNetworkState = mustCleanStatus(); */
+
+ boolean cleanNetworkState = cleanStatus;
+ if( cleanNetworkState ) {
+// if ( doCleanAndSetConfiguration() == false ) {
+// return false;
+// }
+ return createZigBeeNetwork(false);
+ } else {
+ synchronized (this) {
+ boolean creation = createZigBeeNetwork(true);
+ if ( creation == false ){
+ return false;
+ }
+ state = DriverStatus.NETWORK_READY;
+// if ( doesCurrentConfigurationMatchZStackConfiguration() ) {
+// return creation;
+// }
+// if ( doCleanAndSetConfiguration() == false ) {
+// return false;
+// }
+ return createZigBeeNetwork(false);
+ }
+ }
+ }
+
+// private boolean doesCurrentConfigurationMatchZStackConfiguration() {
+// int value = -1;
+// boolean mismatch = false;
+// if ( ( value = getCurrentChannel() ) != channel ) {
+// logger.warn(
+// "The channel configuration differ from the channel configuration in use: " +
+// "in use {}, while the configured is {}.\n" +
+// "The ZigBee Stack shold be should, try to set "+ConfigurationProperties.NETWORK_FLUSH+" to TRUE",
+// value, channel
+// );
+// mismatch = true;
+// }
+// if ( ( value = getCurrentPanId() ) != pan ) {
+// logger.warn(
+// "The PanId configuration differ from the channel configuration in use: " +
+// "in use {}, while the configured is {}.\n" +
+// "The ZigBee Stack shold be should, try to set "+ConfigurationProperties.NETWORK_FLUSH+" to TRUE",
+// value, pan
+// );
+// mismatch = true;
+// }
+// if ( ( value = getZigBeeNodeMode() ) != mode.ordinal() ) {
+// logger.warn(
+// "The NetworkMode configuration differ from the channel configuration in use: " +
+// "in use {}, while the configured is {}.\n" +
+// "The ZigBee Stack shold be should, try to set "+ConfigurationProperties.NETWORK_FLUSH+" to TRUE",
+// value, mode.ordinal()
+// );
+// mismatch = true;
+// }
+//
+// return mismatch;
+// }
+//
+// private boolean doCleanAndSetConfiguration() {
+// logger.debug("Cleaning dongle networks stack status");
+// if( ! dongleClearState() ){
+// logger.error("Unable to CLEAN the ZigBee network stack staus");
+// return false;
+// } else {
+// logger.info("ZigBee network stack status CLEANED");
+// }
+// if( ! dongleSetChannel() ){
+// logger.error("Unable to set CHANNEL for ZigBee Network");
+// return false;
+// } else {
+// logger.info("CHANNEL set");
+// }
+// if( ! dongleSetPanId() ){
+// logger.error("Unable to set PANID for ZigBee Network");
+// return false;
+// } else {
+// logger.info("PANID set");
+// }
+//
+// if ( dongleSetNetworkMode() == false ) {
+// logger.error("Unable to set NETWORK_MODE for ZigBee Network");
+// return false;
+// } else {
+// logger.info("NETWORK_MODE set");
+// }
+// return true;
+// }
+
+ private ZToolPacket sendSynchrouns(final HWHighLevelDriver hwDriver, final ZToolPacket request) {
+ final ZToolPacket[] response = new ZToolPacket[]{null};
+ final int TIMEOUT = 1000, MAX_SEND = 3;
+ int sending = 1;
+
+ logger.info("Sending Synchrouns {}", request.getClass().getName());
+
+ SynchrounsCommandListner listener = new SynchrounsCommandListner() {
+
+ public void receivedCommandResponse(ZToolPacket packet) {
+ logger.info("Recieved Synchrouns Response {}", packet.getClass().getName());
+ synchronized (response) {
+ response[0] = packet;
+ response.notify();
+ }
+ }
+
+ };
+
+ while( sending <= MAX_SEND ){
+ try {
+ hwDriver.sendSynchrounsCommand(request, listener, TIMEOUT);
+ logger.info("Sent {} during the {}-th tenative", request.getClass().getName(),sending);
+ synchronized (response) {
+ long wakeUpTime = System.currentTimeMillis() + TIMEOUT;
+ while(response[0] == null && wakeUpTime > System.currentTimeMillis()){
+ final long sleeping = wakeUpTime - System.currentTimeMillis();
+ logger.debug("Waiting Synchrouns for up to {}ms till {} Unixtime", sleeping, wakeUpTime);
+ if ( sleeping <= 0 ) {
+ break;
+ }
+ try {
+ response.wait(sleeping);
+ } catch (InterruptedException ignored) {
+ }
+ }
+ }
+ if ( response[0] != null ) {
+ logger.debug("Recieved synchrouns command {} before timout", response[0]);
+ } else {
+ logger.debug("Timeout fired and not synchrouns command recieved", response[0]);
+ }
+ break;
+ }catch(IOException ignored){
+ logger.info("Failed to send {} during the {}-th tenative", request.getClass().getName(),sending);
+ logger.debug("Sending operation failed due to ", ignored);
+ sending++;
+ }
+ }
+
+ return response[0];
+ }
+
+ public boolean addAnnunceListener(AnnunceListner listner){
+ if(annunceListners.isEmpty() && isHardwareReady() ){
+ high.addAsynchrounsCommandListener(annunceListner);
+ }
+ return annunceListners.add(listner);
+ }
+
+ public boolean removeAnnunceListener(AnnunceListner listner){
+ boolean result = annunceListners.remove(listner);
+ if(annunceListners.isEmpty() && isHardwareReady() ){
+ high.removeAsynchrounsCommandListener(annunceListner);
+ }
+ return result;
+ }
+
+ public AF_REGISTER_SRSP sendAFRegister(AF_REGISTER request) {
+ if( waitForNetwork() == false ) return null;
+
+ AF_REGISTER_SRSP response = (AF_REGISTER_SRSP) sendSynchrouns(high, request);
+ return response;
+ }
+
+ public AF_DATA_CONFIRM sendAFDataRequest(AF_DATA_REQUEST request) {
+ if( waitForNetwork() == false ) return null;
+
+ final WaitForCommand waiter = new WaitForCommand(ZToolCMD.AF_DATA_CONFIRM, high);
+
+ AF_DATA_SRSP response = (AF_DATA_SRSP) sendSynchrouns(high, request);
+ if ( response == null || response.Status != 0 ) {
+ waiter.cleanup();
+ return null;
+ } else {
+ return (AF_DATA_CONFIRM) waiter.getCommand(TIMEOUT);
+ }
+ }
+
+ public ZDO_BIND_RSP sendZDOBind(ZDO_BIND_REQ request) {
+ if( waitForNetwork() == false ) return null;
+
+ final WaitForCommand waiter = new WaitForCommand(ZToolCMD.ZDO_BIND_RSP, high);
+
+ ZDO_BIND_REQ_SRSP response = (ZDO_BIND_REQ_SRSP) sendSynchrouns(high, request);
+ if ( response == null || response.Status != 0 ) {
+ waiter.cleanup();
+ return null;
+ } else {
+ return (ZDO_BIND_RSP) waiter.getCommand(TIMEOUT);
+ }
+ }
+
+ public ZDO_UNBIND_RSP sendZDOUnbind(ZDO_UNBIND_REQ request) {
+ if( waitForNetwork() == false ) return null;
+
+ final WaitForCommand waiter = new WaitForCommand(ZToolCMD.ZDO_UNBIND_RSP, high);
+
+ ZDO_UNBIND_REQ_SRSP response = (ZDO_UNBIND_REQ_SRSP) sendSynchrouns(high, request);
+ if ( response == null || response.Status != 0 ) {
+ waiter.cleanup();
+ return null;
+ } else {
+ return (ZDO_UNBIND_RSP) waiter.getCommand(TIMEOUT);
+ }
+ }
+
+ public boolean removeAFMessageListener(AFMessageListner listner){
+ boolean result = false;
+ synchronized (afMessageListners) {
+ result = afMessageListners.remove(listner);
+ }
+
+ if(afMessageListners.isEmpty() && isHardwareReady() ){
+ if ( high.removeAsynchrounsCommandListener(afListner) ) {
+ logger.debug("Removed AsynchrounsCommandListener {} to HWHighLevelDriver", afListner.getClass().getName());
+ } else {
+ logger.debug("Could not remove AsynchrounsCommandListener {} to HWHighLevelDriver", afListner.getClass().getName());
+ }
+ }
+ if ( result ) {
+ logger.debug("Removed AFMessageListner {}:{}", listner, listner.getClass().getName());
+ return true;
+ } else {
+ logger.debug("Could not remove AFMessageListner {}:{}", listner, listner.getClass().getName());
+ return false;
+ }
+ }
+
+ public boolean addAFMessageListner(AFMessageListner listner) {
+ if(afMessageListners.isEmpty() && isHardwareReady() ){
+ if ( high.addAsynchrounsCommandListener(afListner) ) {
+ logger.debug("Added AsynchrounsCommandListener {} to HWHighLevelDriver", afListner.getClass().getName());
+ } else {
+ logger.debug("Could not add AsynchrounsCommandListener {} to HWHighLevelDriver", afListner.getClass().getName());
+ }
+ }
+ boolean result = false;
+ synchronized (afMessageListners) {
+ result = afMessageListners.add(listner);
+ }
+
+ if ( result ) {
+ logger.debug("Added AFMessageListner {}:{}", listner, listner.getClass().getName());
+ return true;
+ } else {
+ logger.debug("Could not add AFMessageListner {}:{}", listner, listner.getClass().getName());
+ return false;
+ }
+ }
+
+ private boolean isNetworkReady() {
+ synchronized (this) {
+ return state.ordinal() >= DriverStatus.NETWORK_READY.ordinal()
+ && state.ordinal() < DriverStatus.CLOSED.ordinal();
+ }
+ }
+
+ private boolean isHardwareReady() {
+ synchronized (this) {
+ return state.ordinal() >= DriverStatus.HARDWARE_READY.ordinal()
+ && state.ordinal() < DriverStatus.CLOSED.ordinal();
+ }
+ }
+
+ /**
+ *
+ * @return
+ * @since 0.2.0
+ */
+ public long getExtendedPanId() {
+ if( waitForNetwork() == false ) {
+ logger.info("Failed to reach the {} level: getExtendedPanId() failed", DriverStatus.NETWORK_READY);
+ return -1;
+ }
+
+ int[] result = getDeviceInfo(ZB_GET_DEVICE_INFO.DEV_INFO_TYPE.EXT_PAN_ID);
+
+ if( result == null ){
+ return -1;
+ } else {
+ return Integers.shortFromInts(result, 7, 0);
+ } }
+
+ /**
+ *
+ * @return
+ * @since 0.2.0
+ */
+ public long getIEEEAddress() {
+
+ if( ieeeAddress != -1 ){
+ return ieeeAddress;
+ }
+
+ if( waitForNetwork() == false ) {
+ logger.info("Failed to reach the {} level: getIEEEAddress() failed", DriverStatus.NETWORK_READY);
+ return -1;
+ }
+
+ int[] result = getDeviceInfo(ZB_GET_DEVICE_INFO.DEV_INFO_TYPE.IEEE_ADDR);
+
+ if( result == null ){
+ return -1;
+ } else {
+ ieeeAddress = Integers.longFromInts(result, 7, 0);
+ return ieeeAddress;
+ }
+ }
+
+ /**
+ *
+ * @return
+ * @since 0.2.0
+ */
+ public int getCurrentPanId(){
+ if( waitForNetwork() == false ) {
+ logger.info("Failed to reach the {} level: getCurrentPanId() failed", DriverStatus.NETWORK_READY);
+ return -1;
+ }
+
+ int[] result = getDeviceInfo(ZB_GET_DEVICE_INFO.DEV_INFO_TYPE.PAN_ID);
+
+ if( result == null ){
+ return -1;
+ } else {
+ return Integers.shortFromInts(result, 1, 0);
+ }
+ }
+
+ /**
+ *
+ * @return
+ * @since 0.2.0
+ */
+ public int getCurrentChannel(){
+ if( waitForNetwork() == false ) {
+ logger.info("Failed to reach the {} level: getCurrentChannel() failed", DriverStatus.NETWORK_READY);
+ return -1;
+ }
+
+ int[] result = getDeviceInfo(ZB_GET_DEVICE_INFO.DEV_INFO_TYPE.CHANNEL);
+
+ if( result == null ){
+ return -1;
+ } else {
+ return result[0];
+ }
+ }
+
+ /**
+ *
+ * @return
+ * @since 0.2.0
+ */
+ public int getCurrentState(){
+ if( waitForNetwork() == false ) {
+ logger.info("Failed to reach the {} level: getCurrentChannel() failed", DriverStatus.NETWORK_READY);
+ return -1;
+ }
+
+ int[] result = getDeviceInfo(ZB_GET_DEVICE_INFO.DEV_INFO_TYPE.STATE);
+
+ if( result == null ){
+ return -1;
+ } else {
+ return result[0];
+ }
+ }
+
+
+ private int[] getDeviceInfo(int type){
+ ZB_GET_DEVICE_INFO_RSP response = (ZB_GET_DEVICE_INFO_RSP) sendSynchrouns(
+ high, new ZB_GET_DEVICE_INFO(type)
+ );
+
+ if ( response == null ){
+ logger.debug("Failed getDeviceInfo for {} due to null value", type);
+ return null;
+ } else if ( response.Param != type ) {
+ logger.debug("Failed getDeviceInfo for {} non matching response returned {}", type, response.Param);
+ return null;
+ } else {
+ logger.debug("Successed getDeviceInfo for {}", type);
+ return response.Value;
+ }
+ }
+
+ public int getZigBeeNodeMode(){
+ ZB_READ_CONFIGURATION_RSP response =
+ (ZB_READ_CONFIGURATION_RSP) sendSynchrouns(
+ high,
+ new ZB_READ_CONFIGURATION( ZB_WRITE_CONFIGURATION.CONFIG_ID.ZCD_NV_LOGICAL_TYPE )
+ );
+ if ( response != null && response.Status == 0 ) {
+ return response.Value[0];
+ } else {
+ return -1;
+ }
+ }
+
+ public DriverStatus getDriverStatus() {
+ return state;
+ }
+
+}
Propchange: projects/zb4osgi/sandbox/miguel.llorente/zibgee.tsb.driver/src/main/java/it/cnr/isti/zigbee/dongle/tsb/impl/DriverTSBi.java
------------------------------------------------------------------------------
svn-mine-type = text/plain
Propchange: projects/zb4osgi/sandbox/miguel.llorente/zibgee.tsb.driver/src/main/java/it/cnr/isti/zigbee/dongle/tsb/impl/DriverTSBi.java
------------------------------------------------------------------------------
svn:eol-style = native
Propchange: projects/zb4osgi/sandbox/miguel.llorente/zibgee.tsb.driver/src/main/java/it/cnr/isti/zigbee/dongle/tsb/impl/DriverTSBi.java
------------------------------------------------------------------------------
svn:keywords = Id Author Date Revision
Added: projects/zb4osgi/sandbox/miguel.llorente/zibgee.tsb.driver/src/main/java/it/cnr/isti/zigbee/dongle/tsb/impl/DriverTSBm.java
==============================================================================
--- projects/zb4osgi/sandbox/miguel.llorente/zibgee.tsb.driver/src/main/java/it/cnr/isti/zigbee/dongle/tsb/impl/DriverTSBm.java (added)
+++ projects/zb4osgi/sandbox/miguel.llorente/zibgee.tsb.driver/src/main/java/it/cnr/isti/zigbee/dongle/tsb/impl/DriverTSBm.java Fri May 20 11:42:58 2011
@@ -1,0 +1,1517 @@
+package it.cnr.isti.zigbee.dongle.tsb.impl;
+
+import javax.comm.CommPortIdentifier;
+import it.cnr.isti.cc2480.high.AsynchrounsCommandListener;
+import it.cnr.isti.cc2480.high.HWHighLevelDriver;
+import it.cnr.isti.cc2480.high.SynchrounsCommandListner;
+import it.cnr.isti.cc2480.low.HWLowLevelDriver;
+import it.cnr.isti.cc2480.low.PacketListener;
+import it.cnr.isti.primitvetypes.util.Integers;
+import it.cnr.isti.zigbee.dongle.api.AFMessageListner;
+import it.cnr.isti.zigbee.dongle.api.AnnunceListner;
+import it.cnr.isti.zigbee.dongle.api.ConfigurationProperties;
+import it.cnr.isti.zigbee.dongle.api.DriverStatus;
+import it.cnr.isti.zigbee.dongle.api.NetworkMode;
+import it.cnr.isti.zigbee.dongle.api.SimpleDriver;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Enumeration;
+import java.util.HashMap;
+import java.util.HashSet;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import com.itaca.ztool.api.ZToolAddress16;
+import com.itaca.ztool.api.ZToolAddress64;
+import com.itaca.ztool.api.ZToolCMD;
+import com.itaca.ztool.api.ZToolException;
+import com.itaca.ztool.api.ZToolPacket;
+import com.itaca.ztool.api.af.AF_DATA_CONFIRM;
+import com.itaca.ztool.api.af.AF_DATA_REQUEST;
+import com.itaca.ztool.api.af.AF_DATA_SRSP;
+import com.itaca.ztool.api.af.AF_INCOMING_MSG;
+import com.itaca.ztool.api.af.AF_REGISTER;
+import com.itaca.ztool.api.af.AF_REGISTER_SRSP;
+import com.itaca.ztool.api.simple.ZB_GET_DEVICE_INFO;
+import com.itaca.ztool.api.simple.ZB_GET_DEVICE_INFO_RSP;
+import com.itaca.ztool.api.simple.ZB_READ_CONFIGURATION;
+import com.itaca.ztool.api.simple.ZB_READ_CONFIGURATION_RSP;
+import com.itaca.ztool.api.simple.ZB_WRITE_CONFIGURATION;
+import com.itaca.ztool.api.simple.ZB_WRITE_CONFIGURATION_RSP;
+import com.itaca.ztool.api.system.SYS_RESET;
+import com.itaca.ztool.api.system.SYS_RESET_RESPONSE;
+import com.itaca.ztool.api.system.SYS_VERSION;
+import com.itaca.ztool.api.util.UTIL_GET_DEVICE_INFO;
+import com.itaca.ztool.api.util.UTIL_GET_DEVICE_INFO_RESPONSE;
+import com.itaca.ztool.api.zdo.ZDO_ACTIVE_EP_REQ;
+import com.itaca.ztool.api.zdo.ZDO_ACTIVE_EP_REQ_SRSP;
+import com.itaca.ztool.api.zdo.ZDO_ACTIVE_EP_RSP;
+import com.itaca.ztool.api.zdo.ZDO_BIND_REQ;
+import com.itaca.ztool.api.zdo.ZDO_BIND_REQ_SRSP;
+import com.itaca.ztool.api.zdo.ZDO_BIND_RSP;
+import com.itaca.ztool.api.zdo.ZDO_END_DEVICE_ANNCE_IND;
+import com.itaca.ztool.api.zdo.ZDO_IEEE_ADDR_REQ;
+import com.itaca.ztool.api.zdo.ZDO_IEEE_ADDR_REQ_SRSP;
+import com.itaca.ztool.api.zdo.ZDO_IEEE_ADDR_RSP;
+import com.itaca.ztool.api.zdo.ZDO_MGMT_LEAVE_REQ;
+import com.itaca.ztool.api.zdo.ZDO_MGMT_LEAVE_REQ_SRSP;
+import com.itaca.ztool.api.zdo.ZDO_MGMT_LEAVE_RSP;
+import com.itaca.ztool.api.zdo.ZDO_NODE_DESC_REQ;
+import com.itaca.ztool.api.zdo.ZDO_NODE_DESC_REQ_SRSP;
+import com.itaca.ztool.api.zdo.ZDO_NODE_DESC_RSP;
+import com.itaca.ztool.api.zdo.ZDO_SIMPLE_DESC_REQ;
+import com.itaca.ztool.api.zdo.ZDO_SIMPLE_DESC_REQ_SRSP;
+import com.itaca.ztool.api.zdo.ZDO_SIMPLE_DESC_RSP;
+import com.itaca.ztool.api.zdo.ZDO_STARTUP_FROM_APP;
+import com.itaca.ztool.api.zdo.ZDO_STARTUP_FROM_APP_SRSP;
+import com.itaca.ztool.api.zdo.ZDO_UNBIND_REQ;
+import com.itaca.ztool.api.zdo.ZDO_UNBIND_REQ_SRSP;
+import com.itaca.ztool.api.zdo.ZDO_UNBIND_RSP;
+
+/**
+ *
+ * @author <a href="mailto:stefano.lenzi at isti.cnr.it">Stefano "Kismet" Lenzi</a>
+ * @version $LastChangedRevision$ ($LastChangedDate$)
+ * @since 0.1.0
+ *
+ */
+public class DriverTSBm implements Runnable, SimpleDriver{
+
+ private final static Logger logger = LoggerFactory.getLogger(DriverTSBm.class);
+ private final static Logger logger4Waiter = LoggerFactory.getLogger(WaitForCommand.class);
+
+ public static final int RESEND_TIMEOUT_DEFAULT = 1000;
+ public static final String RESEND_TIMEOUT_KEY = "zigbee.driver.tsb.resend.timout";
+
+ public static final int RESEND_MAX_RESEND_DEFAULT = 3;
+ public static final String RESEND_MAX_RESEND_KEY = "zigbee.driver.tsb.resend.max";
+
+ public static final boolean RESEND_ONLY_EXCEPTION_DEFAULT = true;
+ public static final String RESEND_ONLY_EXCEPTION_KEY = "zigbee.driver.tsb.resend.exceptiononly";
+
+ private Thread driver;
+
+ private HWHighLevelDriver high;
+ private HWLowLevelDriver low;
+ private String port;
+ private int rate;
+ private DriverStatus state;
+ private NetworkMode mode;
+ private short pan;
+ private byte channel;
+ private boolean cleanStatus;
+
+ private long TIMEOUT = 5000;//Activator.getCurrentConfiguration().getZigBeeTimeout();
+ private final int RESEND_TIMEOUT;
+ private final int RESEND_MAX_RETRY;
+ private final boolean RESEND_ONLY_EXCEPTION;
+
+ private final HashSet<AnnunceListner> annunceListners = new HashSet<AnnunceListner>();
+ private final AnnunceListerFilter annunceListner = new AnnunceListerFilter(annunceListners);
+
+ private final ArrayList<AFMessageListner> afMessageListners = new ArrayList<AFMessageListner>();
+ private final AFMessageListnerFilter afListner = new AFMessageListnerFilter(afMessageListners);
+
+ private long ieeeAddress = -1;
+ private final HashMap<Class<?>, Thread> conversation3Way = new HashMap<Class<?>, Thread>();
+
+ private class AnnunceListerFilter implements AsynchrounsCommandListener{
+
+ private final Collection<AnnunceListner> listners;
+
+ private AnnunceListerFilter(Collection<AnnunceListner> list){
+ listners = list;
+ }
+
+ public void receivedAsynchrounsCommand(ZToolPacket packet) {
+ if(packet.isError()) return;
+ if(packet.getCMD().get16BitValue() == ZToolCMD.ZDO_END_DEVICE_ANNCE_IND){
+ ZDO_END_DEVICE_ANNCE_IND annunce = (ZDO_END_DEVICE_ANNCE_IND) packet;
+ for (AnnunceListner l : listners) {
+ l.notify(annunce.SrcAddr, annunce.IEEEAddr, annunce.NwkAddr, annunce.Capabilities);
+ }
+ }
+ }
+
+ }
+
+ private class AFMessageListnerFilter implements AsynchrounsCommandListener{
+
+ private final Collection<AFMessageListner> listners;
+
+ private AFMessageListnerFilter(Collection<AFMessageListner> list){
+ listners = list;
+ }
+
+ public void receivedAsynchrounsCommand(ZToolPacket packet) {
+ if(packet.isError()) return;
+ if(packet.getCMD().get16BitValue() == ZToolCMD.AF_INCOMING_MSG){
+ AF_INCOMING_MSG msg = (AF_INCOMING_MSG) packet;
+ if( listners.isEmpty() ){
+ logger.debug("Recieved AF_INCOMING_MSG but no listeners. Message was: {} ", msg);
+ } else {
+ logger.debug("Recieved AF_INCOMING_MSG notifying {} listeners of {}", listners.size(), msg);
+ }
+ ArrayList<AFMessageListner> localCopy = null;
+ synchronized (listners) {
+ localCopy = new ArrayList<AFMessageListner>(listners);
+ }
+ for ( AFMessageListner l : localCopy){
+// if( l.match(
+// msg.getClusterId(), msg.getSrcAddr(),
+// msg.getSrcEndpoint(), msg.getDstEndpoint(),
+// msg.getTransId()
+// ) ) {
+ l.notify(msg);
+// }
+ }
+ }
+ }
+
+ }
+
+ public DriverTSBm(String serialPort, int bitrate) throws ZToolException {
+ this(serialPort,bitrate,NetworkMode.Coordinator,0,19, false);
+ }
+
+ public DriverTSBm(
+ String serialPort, int bitrate, NetworkMode mode, int pan, int channel
+ ) throws ZToolException {
+
+ this(serialPort, bitrate, mode, pan, channel, false);
+ }
+
+ public DriverTSBm(
+ String serialPort, int bitRate, NetworkMode mode, int pan, int channel, boolean cleanNetworkStatus
+ ) throws ZToolException {
+
+ int aux = RESEND_TIMEOUT_DEFAULT;
+ try{
+ aux = Integer.parseInt(System.getProperty(RESEND_TIMEOUT_KEY));
+ logger.debug("Using {} set from enviroment {}", RESEND_TIMEOUT_KEY, aux);
+ }catch(NumberFormatException ex){
+ logger.debug("Using {} set as DEFAULT {}", RESEND_TIMEOUT_KEY, aux);
+ }
+ RESEND_TIMEOUT = aux;
+
+ aux = RESEND_MAX_RESEND_DEFAULT;
+ try{
+ aux = Integer.parseInt(System.getProperty(RESEND_MAX_RESEND_KEY));
+ logger.debug("Using {} set from enviroment {}", RESEND_MAX_RESEND_KEY, aux);
+ }catch(NumberFormatException ex){
+ logger.debug("Using {} set as DEFAULT {}", RESEND_MAX_RESEND_KEY, aux);
+ }
+ RESEND_MAX_RETRY = aux;
+
+ boolean b = RESEND_ONLY_EXCEPTION_DEFAULT;
+ try{
+ b = Boolean.parseBoolean(System.getProperty(RESEND_ONLY_EXCEPTION_KEY));
+ logger.debug("Using {} set from enviroment {}", RESEND_ONLY_EXCEPTION_KEY, b);
+ }catch(NumberFormatException ex){
+ logger.debug("Using {} set as DEFAULT {}", RESEND_ONLY_EXCEPTION_KEY, b);
+ }
+ RESEND_ONLY_EXCEPTION = b;
+
+
+ state = DriverStatus.CLOSED;
+ this.cleanStatus = cleanNetworkStatus;
+ setSerialPort(serialPort, bitRate);
+ setZigBeeNetwork((byte)channel, (short)pan);
+ setZigBeeNodeMode(mode);
+
+ }
+
+ private String buildDriverThreadName(String serialPort, int bitrate) {
+ return "SimpleDriver["+serialPort+","+bitrate+"]";
+ }
+
+ public void setZigBeeNodeMode(NetworkMode m) {
+ if ( state != DriverStatus.CLOSED ) {
+ throw new IllegalStateException("Network mode can be changed only " +
+ "if driver is CLOSED while it is:"+state);
+ }
+ cleanStatus = mode != m;
+ mode = m;
+ }
+
+ public void setZigBeeNetwork(byte ch, short panId) {
+ if ( state != DriverStatus.CLOSED ) {
+ throw new IllegalStateException("Network mode can be changed only " +
+ "if driver is CLOSED while it is:"+state);
+ }
+ cleanStatus = ch != channel || panId != pan;
+ channel = ch;
+ pan = panId;
+ }
+
+ public void setSerialPort(String serialName,int bitRate) {
+ if ( state != DriverStatus.CLOSED ) {
+ throw new IllegalStateException("Serial port can be changed only " +
+ "if driver is CLOSED while it is:"+state);
+ }
+ port = serialName;
+ rate = bitRate;
+ }
+
+ public void open(boolean cleanCache){
+ cleanStatus = cleanCache;
+ open();
+ }
+
+ public void open(){
+ if ( state == DriverStatus.CLOSED ) {
+ state = DriverStatus.CREATED;
+ driver = new Thread(this);
+ driver.setName(buildDriverThreadName(port,rate));
+ driver.start();
+ }else{
+ throw new IllegalStateException("Driver already opened, current status is:"+state);
+ }
+ }
+
+ public void close(){
+ if(state == DriverStatus.CLOSED){
+ logger.debug("Already CLOSED");
+ return;
+ }
+ logger.info("Closing");
+ if( Thread.currentThread() != driver ){
+ logger.debug("Waiting for intialization operation to complete before closing");
+ try {
+ driver.join();
+ } catch (InterruptedException ignored) {
+ }
+ }else{
+ logger.debug("Self closing");
+ }
+ if(state == DriverStatus.NETWORK_READY){
+ logger.debug("Closing NETWORK");
+ setState(DriverStatus.HARDWARE_READY);
+ }
+ if(state == DriverStatus.HARDWARE_READY){
+ logger.debug("Closing HARDWARE");
+ high.close();
+ logger.debug("Closing LOW HARDWARE");
+ low.close();
+ setState(DriverStatus.CREATED);
+ }
+ if(state == DriverStatus.CREATED){
+ setState(DriverStatus.CLOSED);
+ }
+ logger.info("Closed");
+ }
+
+ public ZDO_IEEE_ADDR_RSP sendZDOIEEEAddressRequest(ZDO_IEEE_ADDR_REQ request){
+ if( waitForNetwork() == false ) return null;
+ ZDO_IEEE_ADDR_RSP result = null;
+
+ waitAndLock3WayConversation(request);
+ final WaitForCommand waiter = new WaitForCommand(ZToolCMD.ZDO_IEEE_ADDR_RSP, high);
+
+ logger.debug("Sending ZDO_IEEE_ADDR_REQ {}", request);
+ ZDO_IEEE_ADDR_REQ_SRSP response = (ZDO_IEEE_ADDR_REQ_SRSP) sendSynchrouns(high, request);
+ if ( response == null || response.Status != 0 ) {
+ logger.debug("ZDO_IEEE_ADDR_REQ failed, recieved {}", response);
+ waiter.cleanup();
+ } else {
+ result = (ZDO_IEEE_ADDR_RSP) waiter.getCommand(TIMEOUT);
+ }
+ unLock3WayConversation(request);
+ return result;
+ }
+
+ public ZDO_NODE_DESC_RSP sendZDONodeDescriptionRequest(ZDO_NODE_DESC_REQ request) {
+ if( waitForNetwork() == false ) return null;
+ ZDO_NODE_DESC_RSP result = null;
+
+ waitAndLock3WayConversation(request);
+ final WaitForCommand waiter = new WaitForCommand(ZToolCMD.ZDO_NODE_DESC_RSP, high);
+
+ ZDO_NODE_DESC_REQ_SRSP response = (ZDO_NODE_DESC_REQ_SRSP) sendSynchrouns(high, request);
+ if ( response == null || response.Status != 0 ) {
+ waiter.cleanup();
+ } else {
+ result = (ZDO_NODE_DESC_RSP) waiter.getCommand(TIMEOUT);
+ }
+
+ unLock3WayConversation(request);
+ return result;
+ }
+
+ public ZDO_ACTIVE_EP_RSP sendZDOActiveEndPointRequest(ZDO_ACTIVE_EP_REQ request) {
+ if( waitForNetwork() == false ) return null;
+ ZDO_ACTIVE_EP_RSP result = null;
+
+ waitAndLock3WayConversation(request);
+ final WaitForCommand waiter = new WaitForCommand(ZToolCMD.ZDO_ACTIVE_EP_RSP, high);
+
+ logger.debug("Sending ZDO_ACTIVE_EP_REQ {}", request);
+ ZDO_ACTIVE_EP_REQ_SRSP response = (ZDO_ACTIVE_EP_REQ_SRSP) sendSynchrouns(high, request);
+ if ( response == null || response.Status != 0 ) {
+ logger.debug("ZDO_ACTIVE_EP_REQ failed, recieved {}", response);
+ waiter.cleanup();
+ } else {
+ result = (ZDO_ACTIVE_EP_RSP) waiter.getCommand(TIMEOUT);
+ }
+ unLock3WayConversation(request);
+ return result;
+ }
+
+ /**
+ * @param request
+ */
+ private void waitAndLock3WayConversation(ZToolPacket request) {
+ synchronized (conversation3Way) {
+ Class<?> clz = request.getClass();
+ Thread requestor = null;
+ while( (requestor = conversation3Way.get(clz) ) != null ){
+ logger.debug("Waiting for {} issued by {} to complete", clz, requestor);
+ try{
+ conversation3Way.wait();
+ }catch(InterruptedException ex){
+ }
+ }
+ conversation3Way.put(clz, Thread.currentThread());
+ }
+ }
+
+ /**
+ * Release the lock held for the 3-way communication
+ *
+ * @param request
+ */
+ private void unLock3WayConversation(ZToolPacket request) {
+ Class<?> clz = request.getClass();
+ Thread requestor = null;
+ synchronized ( conversation3Way ) {
+ requestor = conversation3Way.get( clz );
+ conversation3Way.put( clz, null );
+ }
+ if( requestor == null ){
+ logger.error("LOCKING BROKEN SOMEONE RELEASE LOCK WITHOU LOCKING IN ADVANCE for {}", clz);
+ } else if( requestor != Thread.currentThread() ) {
+ logger.error(
+ "Thread {} stolen the answer of {} waited by {}",
+ new Object[]{ Thread.currentThread(), clz, requestor }
+ );
+ }
+ }
+
+ public ZDO_SIMPLE_DESC_RSP sendZDOSimpleDescriptionRequest(ZDO_SIMPLE_DESC_REQ request) {
+ if( waitForNetwork() == false ) return null;
+ ZDO_SIMPLE_DESC_RSP result = null;
+ waitAndLock3WayConversation(request);
+ final WaitForCommand waiter = new WaitForCommand(ZToolCMD.ZDO_SIMPLE_DESC_RSP, high);
+
+ ZDO_SIMPLE_DESC_REQ_SRSP response = (ZDO_SIMPLE_DESC_REQ_SRSP) sendSynchrouns(high, request);
+ if ( response == null || response.Status != 0 ) {
+ waiter.cleanup();
+ } else {
+ result = (ZDO_SIMPLE_DESC_RSP) waiter.getCommand(TIMEOUT);
+ }
+
+ unLock3WayConversation(request);
+ return result;
+ }
+
+ public void run() {
+ logger.info("Intializing");
+ setState(DriverStatus.HARDWARE_INITIALIZING);
+ if(initializeHardware() == true){
+ setState(DriverStatus.HARDWARE_READY);
+ }else{
+ close();
+ return;
+ }
+
+ setState(DriverStatus.NETWORK_INITIALIZING);
+ if(initializeZigBeeNetwork() == true){
+ setState(DriverStatus.NETWORK_READY);
+ }else{
+ close();
+ return;
+ }
+ }
+
+
+ @SuppressWarnings("unchecked")
+ private boolean initializeHardware() {
+ String portToOpen = null;
+ if("auto".equalsIgnoreCase(port)){
+ logger.info("Automatic discovery the dongle port by inspecting all the serail ports");
+ Enumeration<CommPortIdentifier> ports = CommPortIdentifier.getPortIdentifiers();
+ while(ports.hasMoreElements()){
+ CommPortIdentifier com = ports.nextElement();
+ if(DriverTSBm.initializeHardware(com.getName(), rate)){
+ portToOpen=com.getName();
+ Thread.currentThread().setName(buildDriverThreadName(portToOpen, rate));
+ break;
+ }
+ }
+ if ( portToOpen == null ) {
+ logger.error("Automatic discovery FAILED the dongle couldn't be find on any port: it may be frozen");
+ return false;
+ }
+ }else{
+ if( DriverTSBm.initializeHardware(port, rate) == true ){
+ portToOpen = port;
+ } else {
+ logger.error("Failed to intialize the dongle on port {} at rate {}", port, rate);
+ return false;
+ }
+ }
+
+ low = new HWLowLevelDriver();
+ try {
+ low.open(portToOpen, rate);
+ } catch (ZToolException e) {
+ logger.error("The port was already open in advance but we can't open it now",e);
+ return false;
+ }
+ high = new HWHighLevelDriver(low);
+ return true;
+ }
+
+ private void setState(DriverStatus value) {
+ logger.info("State changed from {} to {}", this.state, value);
+ synchronized (this) {
+ state = value;
+ notifyAll();
+ }
+ if(state == DriverStatus.HARDWARE_READY){
+ postHardwareEnabled();
+ }
+ }
+
+ private void postHardwareEnabled() {
+ if( ! afMessageListners.isEmpty() ){
+ high.addAsynchrounsCommandListener(afListner);
+ }
+ if( ! annunceListners.isEmpty() ){
+ high.addAsynchrounsCommandListener(annunceListner);
+ }
+ }
+
+ static boolean initializeHardware(String portName, int boudRate) {
+ boolean result = false;
+ final int recieved[] = new int[1];
+ final HWLowLevelDriver probingDriver = new HWLowLevelDriver();
+ final PacketListener monitor = new PacketListener(){
+ public void packetRecieved(ZToolPacket packet) {
+ logger.debug("Received initializing SYS VERSION candidate");
+ if(packet.getCommandId() == ZToolCMD.SYS_VERSION_RESPONSE){
+ logger.debug("Initializing Hardware: Received correctly SYS_VERSION_RESPONSE");
+ synchronized (recieved) {
+ recieved[0] = 3;
+ }
+ } else if(packet.isError()){
+ logger.debug("Initializing Hardware: Received erroneous packet: {}",packet.getErrorMsg());
+ synchronized (recieved) {
+ recieved[0] += 1;
+ }
+ } else {
+ logger.debug("Initializing Hardware: Received {}",packet.getClass().getName());
+ synchronized (recieved) {
+ recieved[0] += 1;
+ }
+ }
+ }
+
+ };
+ probingDriver.addPacketListener(monitor);
+ try {
+ probingDriver.open(portName,boudRate);
+ probingDriver.sendPacket(new SYS_VERSION());
+ final long ready = System.currentTimeMillis() + 5000;
+ while(ready > System.currentTimeMillis()){
+ synchronized (recieved) {
+ if( recieved[0] == 3 ){
+ logger.debug("Received initializing SYS VERSION");
+ break;
+ }
+ }
+
+ try {
+ Thread.sleep(500);
+ } catch (InterruptedException ignored) {
+ logger.debug("Exception SYS VERSION");
+ }
+ }
+ logger.debug("End of waiting for SYS VERSION");
+ synchronized (recieved) {
+ if( recieved[0] == 3 ){
+ logger.debug("Succeeded initializing SYS VERSION");
+ result = true;
+ }
+ }
+ } catch (ZToolException e) {
+ logger.info("Unable to open serial port: {}", portName);
+ logger.error("Unable to open serial port, due to:", e);
+ }catch (IOException e) {
+ logger.error("Hardware initialization failed", e);
+ }
+ probingDriver.close();
+ probingDriver.removePacketListener(monitor);
+ return result;
+ }
+
+ private boolean waitForHardware() {
+ synchronized (this) {
+ while (state == DriverStatus.CREATED || state == DriverStatus.CLOSED ){
+ logger.debug("Waiting for HARDWARE to become ready");
+ try {
+ wait();
+ } catch (InterruptedException ignored) {
+ }
+ }
+ return isHardwareReady();
+ }
+ }
+
+ private boolean waitForNetwork() {
+ synchronized (this) {
+ while (state != DriverStatus.NETWORK_READY && state != DriverStatus.CLOSED ){
+ logger.debug("Waiting for NETWORK to become ready");
+ try {
+ wait();
+ } catch (InterruptedException ignored) {
+ }
+ }
+ return isNetworkReady();
+ }
+ }
+
+ private class WaitForCommand implements AsynchrounsCommandListener{
+
+ final ZToolPacket[] result = new ZToolPacket[]{null};
+ final int waitFor;
+ final HWHighLevelDriver driver;
+
+ public WaitForCommand(int waitFor, HWHighLevelDriver driver) {
+ this.waitFor = waitFor;
+ this.driver = driver;
+ driver.addAsynchrounsCommandListener(this);
+ }
+
+
+
+ public void receivedAsynchrounsCommand(ZToolPacket packet) {
+ logger4Waiter.info("Recieved a packet {} and waiting for {}", packet.getCMD(), waitFor);
+ logger4Waiter.debug("Recieved {} {}", packet.getClass(), packet.toString());
+ if( packet.isError() ) return;
+ if( packet.getCMD().get16BitValue() != waitFor) return;
+ synchronized (result) {
+ result[0]=packet;
+ logger4Waiter.info("Recieved packet that we were waiting for");
+ cleanup();
+ }
+ }
+
+ public ZToolPacket getCommand(final long timeout){
+ synchronized (result) {
+ final long wakeUpTime = System.currentTimeMillis() + timeout;
+ while(result[0] == null && wakeUpTime > System.currentTimeMillis()){
+ try {
+ result.wait(wakeUpTime-System.currentTimeMillis());
+ } catch (InterruptedException ignored) {
+ }
+
+ }
+ }
+ if( result[0] == null ){
+ logger4Waiter.warn("Timeout {} expired and not packet with {} recieved", timeout, waitFor);
+ }
+ cleanup();
+ return result[0];
+ }
+
+ public void cleanup(){
+ synchronized (result) {
+ driver.removeAsynchrounsCommandListener(this);
+ result.notify();
+ }
+ }
+ }
+
+ private class WaitForAList implements PacketListener{
+
+ final int[] waitingList;
+ final ZToolPacket[] packetHistory;
+ final HWLowLevelDriver hwDriver;
+ int idx = 0;
+
+ /**
+ * This constructor uses the {@link WaitForAList#WaitForAList(int[], ZToolPacket[], HWLowLevelDriver) constructor<br>
+ * with the following parameters <code>WaitForAList(list,null,null)</code>
+ *
+ * @see WaitForAList#WaitForAList(int[], ZToolPacket[], HWLowLevelDriver)
+ * @param list
+ */
+ public WaitForAList(final int[] list){
+ this(list, null, null);
+ }
+
+ /**
+ * Create a {@link WaitForAList} that wait for a specified list<br>
+ * of packet to be received. Furthermore, the {@link WaitForAList}<br>
+ * while record all the matching packet received, and it will handle<br>
+ * by itself the registration and unregistration as {@link PacketListener}<br>
+ * to the specified {@link HWLowLevelDriver}.<br>
+ * <br>
+ * <b>NOTE:</b>If the {@link ZToolPacket} array is null no packet will be recorded<br>
+ * <b>NOTE:</b>If the {@link HWLowLevelDriver} array is null registration and unregistration as<br>
+ * {@link PacketListener} must be handled by the invoker<br>
+ *
+ * @param list the array of <code>int</code> to listen to
+ * @param packets {@link ZToolPacket} the array of the same size as <code>list</code> to record the received packet
+ * @param lowDriver {@link HWLowLevelDriver} to register to, if <code>null</code> to handle registration/unregistration manually
+ */
+ public WaitForAList(
+ final int[] list,
+ final ZToolPacket[] packets,
+ final HWLowLevelDriver lowDriver){
+ this.waitingList = list;
+ this.packetHistory = packets;
+ this.hwDriver = lowDriver;
+ if ( hwDriver != null) {
+ hwDriver.addPacketListener(this);
+ }
+ }
+
+ public void waitForAll(long timeout){
+ long wakeUpTime = System.currentTimeMillis() + timeout;
+ synchronized (waitingList) {
+ while( idx < waitingList.length && wakeUpTime > System.currentTimeMillis()){
+ try {
+ waitingList.wait(wakeUpTime - System.currentTimeMillis());
+ } catch (InterruptedException ignored) {
+ }
+ }
+ }
+ }
+
+ public void packetRecieved(ZToolPacket packet) {
+ if(packet.isError()) return;
+ if((packet.getCommandId() & 0xFFFF) == waitingList[idx]){
+ logger.info("Recieved packet that was waiting for incresing waitingList");
+ synchronized (waitingList) {
+ if ( packetHistory != null ) {
+ packetHistory[idx] = packet;
+ }
+ idx = idx + 1;
+ if ( idx == waitingList.length ){
+ if ( low != null) {
+ low.removePacketListener(this);
+ }
+ waitingList.notifyAll();
+ return;
+ }
+ }
+ }
+ }
+
+ }
+
+
+ private boolean dongleReset(){
+ if( waitForHardware() == false ) return false;
+
+ final WaitForCommand waiter = new WaitForCommand(
+ ZToolCMD.SYS_RESET_RESPONSE,
+ high
+ );
+
+ WaitForAList waiting = new WaitForAList(new int[]{
+ ZToolCMD.SYS_RESET_RESPONSE,
+ ZToolCMD.ZB_APP_REGISTER_RSP,
+ ZToolCMD.ZB_WRITE_CONFIGURATION_RSP,
+ ZToolCMD.ZB_WRITE_CONFIGURATION_RSP
+ });
+
+ low.addPacketListener(waiting);
+
+ try {
+ high.sendAsynchrounsCommand(new SYS_RESET(SYS_RESET.RESET_TYPE.SERIAL_BOOTLOADER));
+ } catch (IOException e) {
+ logger.error("DongleReset failed", e);
+ return false;
+ }
+
+ SYS_RESET_RESPONSE response =
+ (SYS_RESET_RESPONSE) waiter.getCommand(TIMEOUT);
+
+ waiting.waitForAll(TIMEOUT*2);
+ low.removePacketListener(waiting);
+ return response != null;
+ }
+
+ private boolean dongleClearState(){
+ dongleSetCleanState(true);
+
+ boolean result = dongleReset();
+
+ dongleSetCleanState(false);
+
+ return result;
+ }
+
+ private boolean dongleSetCleanState(boolean clean){
+ ZB_WRITE_CONFIGURATION_RSP response;
+ if(clean){
+ response = (ZB_WRITE_CONFIGURATION_RSP) sendSynchrouns(
+ high,
+ new ZB_WRITE_CONFIGURATION(
+ ZB_WRITE_CONFIGURATION.CONFIG_ID.ZCD_NV_STARTUP_OPTION,
+ new int[]{0x00000002}
+ )
+ );
+
+ if( response == null || response.Status != 0) {
+ logger.info("Couldn't set ZCD_NV_STARTUP_OPTION to CLEAN_STATE");
+ return false;
+ }else{
+ logger.info("Set ZCD_NV_STARTUP_OPTION to CLEAN_STATE");
+ }
+ }else{
+ response = (ZB_WRITE_CONFIGURATION_RSP) sendSynchrouns(
+ high,
+ new ZB_WRITE_CONFIGURATION(
+ ZB_WRITE_CONFIGURATION.CONFIG_ID.ZCD_NV_STARTUP_OPTION,
+ new int[]{0x00000000}
+ )
+ );
+
+ if( response == null || response.Status != 0) {
+ logger.info("Couldn't set ZCD_NV_STARTUP_OPTION back to DO_NOTHING");
+ return false;
+ }
+ }
+ return true;
+ }
+
+ static final int[] buildChannelMask(int channel){
+ int channelMask = 1 << channel;
+ int[] mask = new int[4];
+ for (int i = 0; i < mask.length; i++) {
+ mask[i] = Integers.getByteAsInteger(channelMask, i);
+ }
+ return mask;
+ }
+
+ private boolean dongleSetChannel(int[] channelMask) {
+
+ logger.info(
+ "Setting the channel to {}{}{}{}", new Object[]{
+ Integer.toHexString(channelMask[0]),
+ Integer.toHexString(channelMask[1]),
+ Integer.toHexString(channelMask[2]),
+ Integer.toHexString(channelMask[3])
+ }
+ );
+
+ ZB_WRITE_CONFIGURATION_RSP response =
+ (ZB_WRITE_CONFIGURATION_RSP) sendSynchrouns(
+ high,
+ new ZB_WRITE_CONFIGURATION(
+ ZB_WRITE_CONFIGURATION.CONFIG_ID.ZCD_NV_CHANLIST,
+ channelMask
+ )
+ );
+
+ return response != null && response.Status == 0;
+ }
+
+ private boolean dongleSetChannel(int ch){
+ int[] channelMask = buildChannelMask(ch);
+
+ return dongleSetChannel(channelMask);
+ }
+
+ private boolean dongleSetChannel(){
+ int[] channelMask = buildChannelMask(channel);
+
+ return dongleSetChannel(channelMask);
+ }
+
+ private boolean dongleSetNetworkMode(){
+ logger.info("Changing the Network Mode to {}", mode);
+
+ ZB_WRITE_CONFIGURATION_RSP response =
+ (ZB_WRITE_CONFIGURATION_RSP) sendSynchrouns(
+ high,
+ new ZB_WRITE_CONFIGURATION(
+ ZB_WRITE_CONFIGURATION.CONFIG_ID.ZCD_NV_LOGICAL_TYPE,
+ new int[]{ mode.ordinal() }
+ )
+ );
+
+ return response != null && response.Status == 0;
+ }
+
+ private boolean dongleSetPanId(){
+ ZB_WRITE_CONFIGURATION_RSP response =
+ (ZB_WRITE_CONFIGURATION_RSP) sendSynchrouns(
+ high,
+ new ZB_WRITE_CONFIGURATION(
+ ZB_WRITE_CONFIGURATION.CONFIG_ID.ZCD_NV_PANID,
+ new int[]{
+ Integers.getByteAsInteger(pan, 0),
+ Integers.getByteAsInteger(pan, 1)
+ }
+ )
+ );
+
+ return response != null && response.Status == 0;
+ }
+
+
+ private boolean createZigBeeNetwork(boolean reset){
+ /*
+ * NOTE:The dongle has to be reset all the time to avoid that the endpoints
+ * register on the dongle itself break the code at upper level
+ *
+ */
+ if( reset && dongleReset() ) {
+ logger.debug("Reset the dongle before Creating ZigBee Network");
+ } else if (reset) {
+ logger.debug("FAILED to reset the dongle before Creating ZigBee Network");
+ } else {
+ logger.debug("Dongle has already been reset so no endpoint registered");
+ }
+ switch (mode) {
+ case Coordinator:
+ return doCoordinatorCreateNetwork();
+ case Router:
+ //TODO Implements start up as Router
+ return false;
+ case EndDevice:
+ return doEndDeviceCreateNetwok();
+ }
+
+ /*
+ * This code is unreachable but compiler can't find this out yet.
+ * It may introduce a compilation issue of future compilers
+ */
+ return false;
+ }
+
+ private boolean doEndDeviceCreateNetwok() {
+ logger.debug("Creating network as EndDevice");
+
+ ZDO_STARTUP_FROM_APP_SRSP response = (ZDO_STARTUP_FROM_APP_SRSP) sendSynchrouns(
+ high, new ZDO_STARTUP_FROM_APP(ZDO_STARTUP_FROM_APP.RESET_TYPE.TARGET_DEVICE)
+ );
+ if ( response == null ) {
+ return false;
+ } else {
+ return true;//TODO: response.Status == ZDO_STARTUP_FROM_APP_SRSP.AF_STATUS.SUCCESS;
+ }
+ }
+
+ private boolean doCoordinatorCreateNetwork() {
+ logger.info("Creating network as Coordintator");
+
+ ZDO_STARTUP_FROM_APP_SRSP response = (ZDO_STARTUP_FROM_APP_SRSP) sendSynchrouns(
+ high, new ZDO_STARTUP_FROM_APP(ZDO_STARTUP_FROM_APP.RESET_TYPE.TARGET_DEVICE)
+ );
+ if ( response == null ) {
+ return false;
+ } else {
+ return true;//TODO response.Status == ZDO_STARTUP_FROM_APP_SRSP.AF_STATUS.SUCCESS;
+ }
+ }
+
+ /*
+ //TODO We should check if the current setting differs from the setting stored on the dongle
+ * and later define whetever to clean or not the cache
+ private boolean mustCleanStatus(){
+ if( cleanStatus ) {
+ return true;
+ }
+
+ createZigBeeNetwork();
+
+ int[] value;
+
+ value = getDeviceInfo(ZB_GET_DEVICE_INFO.DEV_INFO_TYPE.CHANNEL);
+ if ( value == null){
+ logger.error("Method getDeviceInfo(ZB_GET_DEVICE_INFO.DEV_INFO_TYPE.CHANNEL) returned null");
+ return true;
+ } else if ( value[0] != this.channel ) {
+ logger.debug("Dongle network state must be reset because channel is changed. " +
+ "Old was = {} while new is {}", value[0], this.channel);
+ return true;
+ }
+
+ value = getDeviceInfo(ZB_GET_DEVICE_INFO.DEV_INFO_TYPE.PAN_ID);
+ if ( value == null){
+ logger.error("Method getDeviceInfo(ZB_GET_DEVICE_INFO.DEV_INFO_TYPE.PAN_ID) returned null");
+ return true;
+ } else if ( Integers.shortFromInts(value, 1, 0) != this.pan) {
+ logger.debug("Dongle network state must be reset because PanId is changed. " +
+ "Old was = {} while new is {}", Integers.shortFromInts(value, 1, 0), this.pan);
+ return true;
+ }
+
+ dongleReset();
+
+ return false;
+ }
+ */
+
+ private boolean initializeZigBeeNetwork() {
+
+ /*
+ //TODO Fix this peace of code because it is not working
+ The right configuration procedure is:
+ - Set the clear the state
+ - Reboot
+ - Check the status from getDeviceInfo
+ - Set the configuration of: Mode, Channel, PanId, etc.
+
+ boolean cleanNetworkState = mustCleanStatus(); */
+
+ boolean cleanNetworkState = cleanStatus;
+// if( cleanNetworkState ) {
+// if ( doCleanAndSetConfiguration() == false ) {
+// return false;
+// }
+// return createZigBeeNetwork(false);
+// } else {
+// synchronized (this) {
+// boolean creation = createZigBeeNetwork(true);
+// if ( creation == false ){
+// return false;
+// }
+// state = DriverStatus.NETWORK_READY;
+// if ( doesCurrentConfigurationMatchZStackConfiguration() ) {
+// return creation;
+// }
+// if ( doCleanAndSetConfiguration() == false ) {
+// return false;
+// }
+// return createZigBeeNetwork(false);
+// }
+// }
+ if(cleanNetworkState){
+ if ( doCleanAndSetConfiguration() == false ) {
+ return false;
+ }
+ }
+ boolean creation = createZigBeeNetwork(true);
+ if ( creation == false ){
+ return false;
+ }
+ state = DriverStatus.NETWORK_READY;
+ if ( doesCurrentConfigurationMatchZStackConfiguration() ) {
+ logger.error("Dongle configuration does not match specified configuration");
+ }
+ return creation;
+
+ }
+
+ private boolean doesCurrentConfigurationMatchZStackConfiguration() {
+ int value = -1;
+ boolean mismatch = false;
+ if ( ( value = getCurrentChannel() ) != channel ) {
+ logger.warn(
+ "The channel configuration differ from the channel configuration in use: " +
+ "in use {}, while the configured is {}.\n" +
+ "The ZigBee Stack shuold be flushed, try to set "+ConfigurationProperties.NETWORK_FLUSH+" to TRUE",
+ value, channel
+ );
+ mismatch = true;
+ }
+ if ( ( value = getCurrentPanId() ) != pan ) {
+ logger.warn(
+ "The PanId configuration differ from the channel configuration in use: " +
+ "in use {}, while the configured is {}.\n" +
+ "The ZigBee Stack shuold be flushed, try to set "+ConfigurationProperties.NETWORK_FLUSH+" to TRUE",
+ value, pan
+ );
+ mismatch = true;
+ }
+ if ( ( value = getZigBeeNodeMode() ) != mode.ordinal() ) {
+ logger.warn(
+ "The NetworkMode configuration differ from the channel configuration in use: " +
+ "in use {}, while the configured is {}.\n" +
+ "The ZigBee Stack should be flushed, try to set "+ConfigurationProperties.NETWORK_FLUSH+" to TRUE",
+ value, mode.ordinal()
+ );
+ mismatch = true;
+ }
+
+ return mismatch;
+ }
+
+ private boolean doCleanAndSetConfiguration() {
+ logger.debug("Cleaning dongle networks stack status");
+// if( ! dongleClearState() ){
+// logger.error("Unable to CLEAN the ZigBee network stack staus");
+// return false;
+// } else {
+// logger.info("ZigBee network stack status CLEANED");
+// }
+ if( ! dongleSetCleanState(true) ){
+ logger.error("Unable to set clean state for dongle");
+ return false;
+ }
+ if( ! dongleSetChannel() ){
+ logger.error("Unable to set CHANNEL for ZigBee Network");
+ return false;
+ } else {
+ logger.info("CHANNEL set");
+ }
+ if( ! dongleSetPanId() ){
+ logger.error("Unable to set PANID for ZigBee Network");
+ return false;
+ } else {
+ logger.info("PANID set");
+ }
+ if ( dongleSetNetworkMode() == false ) {
+ logger.error("Unable to set NETWORK_MODE for ZigBee Network");
+ return false;
+ } else {
+ logger.info("NETWORK_MODE set");
+ }
+ if( ! dongleReset() ){
+ logger.error("Unable to reset dongle");
+ return false;
+ }
+ if( ! dongleSetCleanState(false) ){
+ logger.error("Unable to unset clean state for dongle");
+ return false;
+ }
+ if ( dongleMasterReset() == false ) {
+ logger.error("Unable to send the master reset for ZigBee Network");
+ return false;
+ } else {
+ logger.info("master reset sent");
+ }
+ return true;
+ }
+
+ private boolean dongleMasterReset() {
+ //---------START FROM APP
+ logger.debug("Reset seq: Trying STARTFROMAPP");
+ ZDO_STARTUP_FROM_APP_SRSP responseA1 = (ZDO_STARTUP_FROM_APP_SRSP) sendSynchrouns(
+ high, new ZDO_STARTUP_FROM_APP(ZDO_STARTUP_FROM_APP.RESET_TYPE.TARGET_DEVICE)
+ );
+ if (responseA1==null){logger.error("Reset seq: Failed STARTFROMAPP");return false;}
+ //---------ZB WRITE CONF
+ logger.debug("Reset seq: Trying WRITECONF");
+ ZB_WRITE_CONFIGURATION_RSP responseA2 = (ZB_WRITE_CONFIGURATION_RSP) sendSynchrouns(
+ high, new ZB_WRITE_CONFIGURATION(3,new int[]{2})
+ );
+ if (responseA2==null){logger.error("Reset seq: Failed WRITECONF");return false;}
+ //---------GET DEVICE INFO
+ logger.debug("Reset seq: Trying GETDEVICEINFO");
+// final WaitForCommand waiter1 = new WaitForCommand(
+// ZToolCMD.UTIL_GET_DEVICE_INFO_RESPONSE,
+// high
+// );
+// try{
+// high.sendAsynchrounsCommand(new UTIL_GET_DEVICE_INFO());
+// } catch (IOException e) {
+// logger.error("GetDeviceInfo of Master Reset failed", e);
+// return false;
+// }
+// UTIL_GET_DEVICE_INFO_RESPONSE responseA3 = (UTIL_GET_DEVICE_INFO_RESPONSE) waiter1.getCommand(TIMEOUT);
+ UTIL_GET_DEVICE_INFO_RESPONSE responseA3 = (UTIL_GET_DEVICE_INFO_RESPONSE) sendSynchrouns(high,new UTIL_GET_DEVICE_INFO());
+ if (responseA3==null){logger.error("Reset seq: Failed GETDEVICEINFO");return false;}
+ ZToolAddress16[] addresses = new ZToolAddress16[responseA3.AssocDevicesList.length];
+ for(int k=0;k<responseA3.AssocDevicesList.length;k++){
+ addresses[k]=new ZToolAddress16(responseA3.AssocDevicesList[k].getMsb(),responseA3.AssocDevicesList[k].getLsb());
+ }
+ //---------ZDO GET IEEE ADDR
+ logger.debug("Reset seq: Trying GETIEEEADDR");
+ ZToolAddress64[] longAddresses = new ZToolAddress64[addresses.length];
+ for(int k=0;k<addresses.length;k++){
+// ZDO_IEEE_ADDR_RSP responseA4 = sendZDOIEEEAddressRequest(new ZDO_IEEE_ADDR_REQ(addresses[k],ZDO_IEEE_ADDR_REQ.REQ_TYPE.EXTENDED.getValue(),0));
+
+ ZDO_IEEE_ADDR_RSP responseA4 = null;
+ WaitForCommand waiter = new WaitForCommand(ZToolCMD.ZDO_IEEE_ADDR_RSP, high);
+ logger.debug("Sending ZDO_IEEE_ADDR_REQ");
+ ZDO_IEEE_ADDR_REQ_SRSP response = (ZDO_IEEE_ADDR_REQ_SRSP) sendSynchrouns(high, new ZDO_IEEE_ADDR_REQ(addresses[k],ZDO_IEEE_ADDR_REQ.REQ_TYPE.EXTENDED.getValue(),0));
+ if ( response == null || response.Status != 0 ) {
+ logger.debug("ZDO_IEEE_ADDR_REQ failed, recieved {}", response);
+ waiter.cleanup();
+ } else {
+ responseA4 = (ZDO_IEEE_ADDR_RSP) waiter.getCommand(TIMEOUT);
+ }
+
+ if (responseA4!=null){
+ longAddresses[k]=responseA4.getIEEEAddress();
+ }else{
+ longAddresses[k]=null;
+ }
+ }
+ //---------ZDO MGMT LEAVE
+ logger.debug("Reset seq: Trying LEAVE");
+ long start=System.currentTimeMillis();
+ for (int k = 0; k < longAddresses.length; k++) {
+ if (longAddresses[k] != null) {
+ WaitForCommand waiter3 = new WaitForCommand(ZToolCMD.ZDO_MGMT_LEAVE_RSP, high);
+
+ ZDO_MGMT_LEAVE_REQ_SRSP response = (ZDO_MGMT_LEAVE_REQ_SRSP) sendSynchrouns(high, new ZDO_MGMT_LEAVE_REQ(addresses[k], longAddresses[k], 3));
+ if ((System.currentTimeMillis() - start) > 5000){logger.error("Reset seq: Failed LEAVE");return false;}
+ if ( response == null || response.Status != 0 ) {
+ waiter3.cleanup();
+ logger.error("Reset seq: Failed LEAVE");
+ return false;
+ } else {
+ if ((System.currentTimeMillis() - start) > 5000){logger.error("Reset seq: Failed LEAVE");return false;}
+ ZDO_MGMT_LEAVE_RSP responseA5 = (ZDO_MGMT_LEAVE_RSP) waiter3.getCommand(TIMEOUT);
+ if ((System.currentTimeMillis() - start) > 5000){logger.error("Reset seq: Failed LEAVE");return false;}
+ if(responseA5==null || responseA5.Status!=ZDO_MGMT_LEAVE_RSP.ZDO_STATUS.ZDP_SUCCESS){logger.error("Reset seq: Failed LEAVE");return false;}
+ }
+ }
+ if ((System.currentTimeMillis() - start) > 5000){logger.error("Reset seq: Failed LEAVE");return false;}
+ }
+
+ //---------SYS RESET
+ logger.debug("Reset seq: Trying SYSRESET");
+ if (!dongleReset()){logger.error("Reset seq: Failed SYSRESET");return false;}
+ //---------START FROM APP
+// //already in initializeZigBeeNetwork
+// ZDO_STARTUP_FROM_APP_SRSP responseA7 = (ZDO_STARTUP_FROM_APP_SRSP) sendSynchrouns(
+// high, new ZDO_STARTUP_FROM_APP(ZDO_STARTUP_FROM_APP.RESET_TYPE.TARGET_DEVICE)
+// );
+// if (responseA7==null)return false;
+ return true;
+ }
+
+ private ZToolPacket sendSynchrouns(final HWHighLevelDriver hwDriver, final ZToolPacket request) {
+ final ZToolPacket[] response = new ZToolPacket[]{null};
+ int sending = 1;
+
+ logger.info("Sending Synchrouns {}", request.getClass().getName());
+
+ SynchrounsCommandListner listener = new SynchrounsCommandListner() {
+
+ public void receivedCommandResponse(ZToolPacket packet) {
+ logger.info("Recieved Synchrouns Response {}", packet.getClass().getName());
+ synchronized (response) {
+ response[0] = packet;
+ response.notify();
+ }
+ }
+
+ };
+
+ while( sending <= RESEND_MAX_RETRY ){
+ try {
+ hwDriver.sendSynchrounsCommand(request, listener, RESEND_TIMEOUT);
+ logger.info("Sent {} during the {}-th tenative", request.getClass().getName(),sending);
+ synchronized (response) {
+ long wakeUpTime = System.currentTimeMillis() + RESEND_TIMEOUT;
+ while(response[0] == null && wakeUpTime > System.currentTimeMillis()){
+ final long sleeping = wakeUpTime - System.currentTimeMillis();
+ logger.debug("Waiting Synchrouns for up to {}ms till {} Unixtime", sleeping, wakeUpTime);
+ if ( sleeping <= 0 ) {
+ break;
+ }
+ try {
+ response.wait(sleeping);
+ } catch (InterruptedException ignored) {
+ }
+ }
+ }
+ if ( response[0] != null ) {
+ logger.debug("Recieved synchrouns command {} before timout", response[0]);
+ } else {
+ logger.debug("Timeout fired and not synchrouns command recieved", response[0]);
+ }
+ if ( RESEND_ONLY_EXCEPTION ) {
+ break;
+ }else{
+ logger.info("Failed to send {} during the {}-th tenative", request.getClass().getName(),sending);
+ sending++;
+ }
+ }catch(IOException ignored){
+ logger.info("Failed to send {} during the {}-th tenative", request.getClass().getName(),sending);
+ logger.debug("Sending operation failed due to ", ignored);
+ sending++;
+ }
+ }
+
+ return response[0];
+ }
+
+ public boolean addAnnunceListener(AnnunceListner listner){
+ if(annunceListners.isEmpty() && isHardwareReady() ){
+ high.addAsynchrounsCommandListener(annunceListner);
+ }
+ return annunceListners.add(listner);
+ }
+
+ public boolean removeAnnunceListener(AnnunceListner listner){
+ boolean result = annunceListners.remove(listner);
+ if(annunceListners.isEmpty() && isHardwareReady() ){
+ high.removeAsynchrounsCommandListener(annunceListner);
+ }
+ return result;
+ }
+
+ public AF_REGISTER_SRSP sendAFRegister(AF_REGISTER request) {
+ if( waitForNetwork() == false ) return null;
+
+ AF_REGISTER_SRSP response = (AF_REGISTER_SRSP) sendSynchrouns(high, request);
+ return response;
+ }
+
+ public AF_DATA_CONFIRM sendAFDataRequest(AF_DATA_REQUEST request) {
+ if( waitForNetwork() == false ) return null;
+ AF_DATA_CONFIRM result = null;
+
+ waitAndLock3WayConversation(request);
+ final WaitForCommand waiter = new WaitForCommand(ZToolCMD.AF_DATA_CONFIRM, high);
+
+ AF_DATA_SRSP response = (AF_DATA_SRSP) sendSynchrouns(high, request);
+ if ( response == null || response.Status != 0 ) {
+ waiter.cleanup();
+ } else {
+ result = (AF_DATA_CONFIRM) waiter.getCommand(TIMEOUT);
+ }
+ unLock3WayConversation(request);
+ return result;
+ }
+
+ public ZDO_BIND_RSP sendZDOBind(ZDO_BIND_REQ request) {
+ if( waitForNetwork() == false ) return null;
+ ZDO_BIND_RSP result = null;
+
+ waitAndLock3WayConversation(request);
+ final WaitForCommand waiter = new WaitForCommand(ZToolCMD.ZDO_BIND_RSP, high);
+
+ ZDO_BIND_REQ_SRSP response = (ZDO_BIND_REQ_SRSP) sendSynchrouns(high, request);
+ if ( response == null || response.Status != 0 ) {
+ waiter.cleanup();
+ } else {
+ result = (ZDO_BIND_RSP) waiter.getCommand(TIMEOUT);
+ }
+ unLock3WayConversation(request);
+ return result;
+ }
+
+ public ZDO_UNBIND_RSP sendZDOUnbind(ZDO_UNBIND_REQ request) {
+ if( waitForNetwork() == false ) return null;
+ ZDO_UNBIND_RSP result = null;
+
+ waitAndLock3WayConversation(request);
+ final WaitForCommand waiter = new WaitForCommand(ZToolCMD.ZDO_UNBIND_RSP, high);
+
+ ZDO_UNBIND_REQ_SRSP response = (ZDO_UNBIND_REQ_SRSP) sendSynchrouns(high, request);
+ if ( response == null || response.Status != 0 ) {
+ waiter.cleanup();
+ } else {
+ result = (ZDO_UNBIND_RSP) waiter.getCommand(TIMEOUT);
+ }
+
+ unLock3WayConversation(request);
+ return result;
+ }
+
+ public boolean removeAFMessageListener(AFMessageListner listner){
+ boolean result = false;
+ synchronized (afMessageListners) {
+ result = afMessageListners.remove(listner);
+ }
+
+ if(afMessageListners.isEmpty() && isHardwareReady() ){
+ if ( high.removeAsynchrounsCommandListener(afListner) ) {
+ logger.debug("Removed AsynchrounsCommandListener {} to HWHighLevelDriver", afListner.getClass().getName());
+ } else {
+ logger.debug("Could not remove AsynchrounsCommandListener {} to HWHighLevelDriver", afListner.getClass().getName());
+ }
+ }
+ if ( result ) {
+ logger.debug("Removed AFMessageListner {}:{}", listner, listner.getClass().getName());
+ return true;
+ } else {
+ logger.debug("Could not remove AFMessageListner {}:{}", listner, listner.getClass().getName());
+ return false;
+ }
+ }
+
+ public boolean addAFMessageListner(AFMessageListner listner) {
+ if(afMessageListners.isEmpty() && isHardwareReady() ){
+ if ( high.addAsynchrounsCommandListener(afListner) ) {
+ logger.debug("Added AsynchrounsCommandListener {} to HWHighLevelDriver", afListner.getClass().getName());
+ } else {
+ logger.debug("Could not add AsynchrounsCommandListener {} to HWHighLevelDriver", afListner.getClass().getName());
+ }
+ }
+ boolean result = false;
+ synchronized (afMessageListners) {
+ result = afMessageListners.add(listner);
+ }
+
+ if ( result ) {
+ logger.debug("Added AFMessageListner {}:{}", listner, listner.getClass().getName());
+ return true;
+ } else {
+ logger.debug("Could not add AFMessageListner {}:{}", listner, listner.getClass().getName());
+ return false;
+ }
+ }
+
+ private boolean isNetworkReady() {
+ synchronized (this) {
+ return state.ordinal() >= DriverStatus.NETWORK_READY.ordinal()
+ && state.ordinal() < DriverStatus.CLOSED.ordinal();
+ }
+ }
+
+ private boolean isHardwareReady() {
+ synchronized (this) {
+ return state.ordinal() >= DriverStatus.HARDWARE_READY.ordinal()
+ && state.ordinal() < DriverStatus.CLOSED.ordinal();
+ }
+ }
+
+ /**
+ *
+ * @return
+ * @since 0.2.0
+ */
+ public long getExtendedPanId() {
+ if( waitForNetwork() == false ) {
+ logger.info("Failed to reach the {} level: getExtendedPanId() failed", DriverStatus.NETWORK_READY);
+ return -1;
+ }
+
+ int[] result = getDeviceInfo(ZB_GET_DEVICE_INFO.DEV_INFO_TYPE.EXT_PAN_ID);
+
+ if( result == null ){
+ return -1;
+ } else {
+ return Integers.shortFromInts(result, 7, 0);
+ } }
+
+ /**
+ *
+ * @return
+ * @since 0.2.0
+ */
+ public long getIEEEAddress() {
+
+ if( ieeeAddress != -1 ){
+ return ieeeAddress;
+ }
+
+ if( waitForNetwork() == false ) {
+ logger.info("Failed to reach the {} level: getIEEEAddress() failed", DriverStatus.NETWORK_READY);
+ return -1;
+ }
+
+ int[] result = getDeviceInfo(ZB_GET_DEVICE_INFO.DEV_INFO_TYPE.IEEE_ADDR);
+
+ if( result == null ){
+ return -1;
+ } else {
+ ieeeAddress = Integers.longFromInts(result, 7, 0);
+ return ieeeAddress;
+ }
+ }
+
+ /**
+ *
+ * @return
+ * @since 0.2.0
+ */
+ public int getCurrentPanId(){
+ if( waitForNetwork() == false ) {
+ logger.info("Failed to reach the {} level: getCurrentPanId() failed", DriverStatus.NETWORK_READY);
+ return -1;
+ }
+
+ int[] result = getDeviceInfo(ZB_GET_DEVICE_INFO.DEV_INFO_TYPE.PAN_ID);
+
+ if( result == null ){
+ return -1;
+ } else {
+ return Integers.shortFromInts(result, 1, 0);
+ }
+ }
+
+ /**
+ *
+ * @return
+ * @since 0.2.0
+ */
+ public int getCurrentChannel(){
+ if( waitForNetwork() == false ) {
+ logger.info("Failed to reach the {} level: getCurrentChannel() failed", DriverStatus.NETWORK_READY);
+ return -1;
+ }
+
+ int[] result = getDeviceInfo(ZB_GET_DEVICE_INFO.DEV_INFO_TYPE.CHANNEL);
+
+ if( result == null ){
+ return -1;
+ } else {
+ return result[0];
+ }
+ }
+
+ /**
+ *
+ * @return
+ * @since 0.2.0
+ */
+ public int getCurrentState(){
+ if( waitForNetwork() == false ) {
+ logger.info("Failed to reach the {} level: getCurrentChannel() failed", DriverStatus.NETWORK_READY);
+ return -1;
+ }
+
+ int[] result = getDeviceInfo(ZB_GET_DEVICE_INFO.DEV_INFO_TYPE.STATE);
+
+ if( result == null ){
+ return -1;
+ } else {
+ return result[0];
+ }
+ }
+
+
+ private int[] getDeviceInfo(int type){
+ ZB_GET_DEVICE_INFO_RSP response = (ZB_GET_DEVICE_INFO_RSP) sendSynchrouns(
+ high, new ZB_GET_DEVICE_INFO(type)
+ );
+
+ if ( response == null ){
+ logger.debug("Failed getDeviceInfo for {} due to null value", type);
+ return null;
+ } else if ( response.Param != type ) {
+ logger.debug("Failed getDeviceInfo for {} non matching response returned {}", type, response.Param);
+ return null;
+ } else {
+ logger.debug("Successed getDeviceInfo for {}", type);
+ return response.Value;
+ }
+ }
+
+ public int getZigBeeNodeMode(){
+ ZB_READ_CONFIGURATION_RSP response =
+ (ZB_READ_CONFIGURATION_RSP) sendSynchrouns(
+ high,
+ new ZB_READ_CONFIGURATION( ZB_WRITE_CONFIGURATION.CONFIG_ID.ZCD_NV_LOGICAL_TYPE )
+ );
+ if ( response != null && response.Status == 0 ) {
+ return response.Value[0];
+ } else {
+ return -1;
+ }
+ }
+
+ public DriverStatus getDriverStatus() {
+ return state;
+ }
+
+}
+
Propchange: projects/zb4osgi/sandbox/miguel.llorente/zibgee.tsb.driver/src/main/java/it/cnr/isti/zigbee/dongle/tsb/impl/DriverTSBm.java
------------------------------------------------------------------------------
svn-mine-type = text/plain
Propchange: projects/zb4osgi/sandbox/miguel.llorente/zibgee.tsb.driver/src/main/java/it/cnr/isti/zigbee/dongle/tsb/impl/DriverTSBm.java
------------------------------------------------------------------------------
svn:eol-style = native
Propchange: projects/zb4osgi/sandbox/miguel.llorente/zibgee.tsb.driver/src/main/java/it/cnr/isti/zigbee/dongle/tsb/impl/DriverTSBm.java
------------------------------------------------------------------------------
svn:keywords = Id Author Date Revision
Added: projects/zb4osgi/sandbox/miguel.llorente/zibgee.tsb.driver/src/main/java/it/cnr/isti/zigbee/dongle/tsb/impl/DriverTSBn.java
==============================================================================
--- projects/zb4osgi/sandbox/miguel.llorente/zibgee.tsb.driver/src/main/java/it/cnr/isti/zigbee/dongle/tsb/impl/DriverTSBn.java (added)
+++ projects/zb4osgi/sandbox/miguel.llorente/zibgee.tsb.driver/src/main/java/it/cnr/isti/zigbee/dongle/tsb/impl/DriverTSBn.java Fri May 20 11:42:58 2011
@@ -1,0 +1,1499 @@
+package it.cnr.isti.zigbee.dongle.tsb.impl;
+
+import javax.comm.CommPortIdentifier;
+import it.cnr.isti.cc2480.high.AsynchrounsCommandListener;
+import it.cnr.isti.cc2480.high.HWHighLevelDriver;
+import it.cnr.isti.cc2480.high.SynchrounsCommandListner;
+import it.cnr.isti.cc2480.low.HWLowLevelDriver;
+import it.cnr.isti.cc2480.low.PacketListener;
+import it.cnr.isti.primitvetypes.util.Integers;
+import it.cnr.isti.zigbee.dongle.api.AFMessageListner;
+import it.cnr.isti.zigbee.dongle.api.AnnunceListner;
+import it.cnr.isti.zigbee.dongle.api.ConfigurationProperties;
+import it.cnr.isti.zigbee.dongle.api.DriverStatus;
+import it.cnr.isti.zigbee.dongle.api.NetworkMode;
+import it.cnr.isti.zigbee.dongle.api.SimpleDriver;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Enumeration;
+import java.util.HashMap;
+import java.util.HashSet;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import com.itaca.ztool.api.ZToolAddress16;
+import com.itaca.ztool.api.ZToolAddress64;
+import com.itaca.ztool.api.ZToolCMD;
+import com.itaca.ztool.api.ZToolException;
+import com.itaca.ztool.api.ZToolPacket;
+import com.itaca.ztool.api.af.AF_DATA_CONFIRM;
+import com.itaca.ztool.api.af.AF_DATA_REQUEST;
+import com.itaca.ztool.api.af.AF_DATA_SRSP;
+import com.itaca.ztool.api.af.AF_INCOMING_MSG;
+import com.itaca.ztool.api.af.AF_REGISTER;
+import com.itaca.ztool.api.af.AF_REGISTER_SRSP;
+import com.itaca.ztool.api.simple.ZB_GET_DEVICE_INFO;
+import com.itaca.ztool.api.simple.ZB_GET_DEVICE_INFO_RSP;
+import com.itaca.ztool.api.simple.ZB_READ_CONFIGURATION;
+import com.itaca.ztool.api.simple.ZB_READ_CONFIGURATION_RSP;
+import com.itaca.ztool.api.simple.ZB_WRITE_CONFIGURATION;
+import com.itaca.ztool.api.simple.ZB_WRITE_CONFIGURATION_RSP;
+import com.itaca.ztool.api.system.SYS_RESET;
+import com.itaca.ztool.api.system.SYS_RESET_RESPONSE;
+import com.itaca.ztool.api.system.SYS_VERSION;
+import com.itaca.ztool.api.util.UTIL_GET_DEVICE_INFO;
+import com.itaca.ztool.api.util.UTIL_GET_DEVICE_INFO_RESPONSE;
+import com.itaca.ztool.api.zdo.ZDO_ACTIVE_EP_REQ;
+import com.itaca.ztool.api.zdo.ZDO_ACTIVE_EP_REQ_SRSP;
+import com.itaca.ztool.api.zdo.ZDO_ACTIVE_EP_RSP;
+import com.itaca.ztool.api.zdo.ZDO_BIND_REQ;
+import com.itaca.ztool.api.zdo.ZDO_BIND_REQ_SRSP;
+import com.itaca.ztool.api.zdo.ZDO_BIND_RSP;
+import com.itaca.ztool.api.zdo.ZDO_END_DEVICE_ANNCE_IND;
+import com.itaca.ztool.api.zdo.ZDO_IEEE_ADDR_REQ;
+import com.itaca.ztool.api.zdo.ZDO_IEEE_ADDR_REQ_SRSP;
+import com.itaca.ztool.api.zdo.ZDO_IEEE_ADDR_RSP;
+import com.itaca.ztool.api.zdo.ZDO_MGMT_LEAVE_REQ;
+import com.itaca.ztool.api.zdo.ZDO_MGMT_LEAVE_REQ_SRSP;
+import com.itaca.ztool.api.zdo.ZDO_MGMT_LEAVE_RSP;
+import com.itaca.ztool.api.zdo.ZDO_NODE_DESC_REQ;
+import com.itaca.ztool.api.zdo.ZDO_NODE_DESC_REQ_SRSP;
+import com.itaca.ztool.api.zdo.ZDO_NODE_DESC_RSP;
+import com.itaca.ztool.api.zdo.ZDO_SIMPLE_DESC_REQ;
+import com.itaca.ztool.api.zdo.ZDO_SIMPLE_DESC_REQ_SRSP;
+import com.itaca.ztool.api.zdo.ZDO_SIMPLE_DESC_RSP;
+import com.itaca.ztool.api.zdo.ZDO_STARTUP_FROM_APP;
+import com.itaca.ztool.api.zdo.ZDO_STARTUP_FROM_APP_SRSP;
+import com.itaca.ztool.api.zdo.ZDO_UNBIND_REQ;
+import com.itaca.ztool.api.zdo.ZDO_UNBIND_REQ_SRSP;
+import com.itaca.ztool.api.zdo.ZDO_UNBIND_RSP;
+
+/**
+ *
+ * @author <a href="mailto:stefano.lenzi at isti.cnr.it">Stefano "Kismet" Lenzi</a>
+ * @version $LastChangedRevision$ ($LastChangedDate$)
+ * @since 0.1.0
+ *
+ */
+public class DriverTSBn implements Runnable, SimpleDriver{
+ private MasterResetGUI resetGUI;
+ private final static Logger logger = LoggerFactory.getLogger(DriverTSBn.class);
+ private final static Logger logger4Waiter = LoggerFactory.getLogger(WaitForCommand.class);
+
+ public static final int RESEND_TIMEOUT_DEFAULT = 1000;
+ public static final String RESEND_TIMEOUT_KEY = "zigbee.driver.tsb.resend.timout";
+
+ public static final int RESEND_MAX_RESEND_DEFAULT = 3;
+ public static final String RESEND_MAX_RESEND_KEY = "zigbee.driver.tsb.resend.max";
+
+ public static final boolean RESEND_ONLY_EXCEPTION_DEFAULT = true;
+ public static final String RESEND_ONLY_EXCEPTION_KEY = "zigbee.driver.tsb.resend.exceptiononly";
+
+
+ private Thread driver;
+
+ private HWHighLevelDriver high;
+ private HWLowLevelDriver low;
+ private String port;
+ private int rate;
+ private DriverStatus state;
+ private NetworkMode mode;
+ private short pan;
+ private byte channel;
+ private boolean cleanStatus;
+
+ private long TIMEOUT = 5000;//Activator.getCurrentConfiguration().getZigBeeTimeout();
+ private final int RESEND_TIMEOUT;
+ private final int RESEND_MAX_RETRY;
+ private final boolean RESEND_ONLY_EXCEPTION;
+
+ private final HashSet<AnnunceListner> annunceListners = new HashSet<AnnunceListner>();
+ private final AnnunceListerFilter annunceListner = new AnnunceListerFilter(annunceListners);
+
+ private final ArrayList<AFMessageListner> afMessageListners = new ArrayList<AFMessageListner>();
+ private final AFMessageListnerFilter afListner = new AFMessageListnerFilter(afMessageListners);
+
+ private long ieeeAddress = -1;
+ private final HashMap<Class<?>, Thread> conversation3Way = new HashMap<Class<?>, Thread>();
+
+ private class AnnunceListerFilter implements AsynchrounsCommandListener{
+
+ private final Collection<AnnunceListner> listners;
+
+ private AnnunceListerFilter(Collection<AnnunceListner> list){
+ listners = list;
+ }
+
+ public void receivedAsynchrounsCommand(ZToolPacket packet) {
+ if(packet.isError()) return;
+ if(packet.getCMD().get16BitValue() == ZToolCMD.ZDO_END_DEVICE_ANNCE_IND){
+ ZDO_END_DEVICE_ANNCE_IND annunce = (ZDO_END_DEVICE_ANNCE_IND) packet;
+ for (AnnunceListner l : listners) {
+ l.notify(annunce.SrcAddr, annunce.IEEEAddr, annunce.NwkAddr, annunce.Capabilities);
+ }
+ }
+ }
+
+ }
+
+ private class AFMessageListnerFilter implements AsynchrounsCommandListener{
+
+ private final Collection<AFMessageListner> listners;
+
+ private AFMessageListnerFilter(Collection<AFMessageListner> list){
+ listners = list;
+ }
+
+ public void receivedAsynchrounsCommand(ZToolPacket packet) {
+ if(packet.isError()) return;
+ if(packet.getCMD().get16BitValue() == ZToolCMD.AF_INCOMING_MSG){
+ AF_INCOMING_MSG msg = (AF_INCOMING_MSG) packet;
+ if( listners.isEmpty() ){
+ logger.debug("Recieved AF_INCOMING_MSG but no listeners. Message was: {} ", msg);
+ } else {
+ logger.debug("Recieved AF_INCOMING_MSG notifying {} listeners of {}", listners.size(), msg);
+ }
+ ArrayList<AFMessageListner> localCopy = null;
+ synchronized (listners) {
+ localCopy = new ArrayList<AFMessageListner>(listners);
+ }
+ for ( AFMessageListner l : localCopy){
+// if( l.match(
+// msg.getClusterId(), msg.getSrcAddr(),
+// msg.getSrcEndpoint(), msg.getDstEndpoint(),
+// msg.getTransId()
+// ) ) {
+ l.notify(msg);
+// }
+ }
+ }
+ }
+
+ }
+
+ public DriverTSBn(String serialPort, int bitrate) throws ZToolException {
+ this(serialPort,bitrate,NetworkMode.Coordinator,0,19, false);
+ }
+
+ public DriverTSBn(
+ String serialPort, int bitrate, NetworkMode mode, int pan, int channel
+ ) throws ZToolException {
+
+ this(serialPort, bitrate, mode, pan, channel, false);
+ }
+
+ public DriverTSBn(
+ String serialPort, int bitRate, NetworkMode mode, int pan, int channel, boolean cleanNetworkStatus
+ ) throws ZToolException {
+ int aux = RESEND_TIMEOUT_DEFAULT;
+ try{
+ aux = Integer.parseInt(System.getProperty(RESEND_TIMEOUT_KEY));
+ logger.debug("Using RESEND_TIMEOUT set from enviroment {}", aux);
+ }catch(NumberFormatException ex){
+ logger.debug("Using RESEND_TIMEOUT set as DEFAULT {}", aux);
+ }
+ RESEND_TIMEOUT = aux;
+
+ aux = RESEND_MAX_RESEND_DEFAULT;
+ try{
+ aux = Integer.parseInt(System.getProperty(RESEND_MAX_RESEND_KEY));
+ logger.debug("Using RESEND_MAX_RETRY set from enviroment {}", aux);
+ }catch(NumberFormatException ex){
+ logger.debug("Using RESEND_MAX_RETRY set as DEFAULT {}", aux);
+ }
+ RESEND_MAX_RETRY = aux;
+
+ boolean b = RESEND_ONLY_EXCEPTION_DEFAULT;
+ try{
+ aux = Integer.parseInt(System.getProperty(RESEND_ONLY_EXCEPTION_KEY));
+ logger.debug("Using RESEND_MAX_RETRY set from enviroment {}", aux);
+ }catch(NumberFormatException ex){
+ logger.debug("Using RESEND_MAX_RETRY set as DEFAULT {}", aux);
+ }
+ RESEND_ONLY_EXCEPTION = b;
+ state = DriverStatus.CLOSED;
+ this.cleanStatus = cleanNetworkStatus;
+ setSerialPort(serialPort, bitRate);
+ setZigBeeNetwork((byte)channel, (short)pan);
+ setZigBeeNodeMode(mode);
+ resetGUI=new MasterResetGUI(this);
+ resetGUI.setVisible(true);
+ }
+
+ private String buildDriverThreadName(String serialPort, int bitrate) {
+ return "SimpleDriver["+serialPort+","+bitrate+"]";
+ }
+
+ public void setZigBeeNodeMode(NetworkMode m) {
+ if ( state != DriverStatus.CLOSED ) {
+ throw new IllegalStateException("Network mode can be changed only " +
+ "if driver is CLOSED while it is:"+state);
+ }
+ cleanStatus = mode != m;
+ mode = m;
+ }
+
+ public void setZigBeeNetwork(byte ch, short panId) {
+ if ( state != DriverStatus.CLOSED ) {
+ throw new IllegalStateException("Network mode can be changed only " +
+ "if driver is CLOSED while it is:"+state);
+ }
+ cleanStatus = ch != channel || panId != pan;
+ channel = ch;
+ pan = panId;
+ }
+
+ public void setSerialPort(String serialName,int bitRate) {
+ if ( state != DriverStatus.CLOSED ) {
+ throw new IllegalStateException("Serial port can be changed only " +
+ "if driver is CLOSED while it is:"+state);
+ }
+ port = serialName;
+ rate = bitRate;
+ }
+
+ public void open(boolean cleanCache){
+ cleanStatus = cleanCache;
+ open();
+ }
+
+ public void open(){
+ if ( state == DriverStatus.CLOSED ) {
+ state = DriverStatus.CREATED;
+ driver = new Thread(this);
+ driver.setName(buildDriverThreadName(port,rate));
+ driver.start();
+ }else{
+ throw new IllegalStateException("Driver already opened, current status is:"+state);
+ }
+ }
+
+ public void close(){
+ if(state == DriverStatus.CLOSED){
+ logger.debug("Already CLOSED");
+ return;
+ }
+ logger.info("Closing");
+ if( Thread.currentThread() != driver ){
+ logger.debug("Waiting for intialization operation to complete before closing");
+ try {
+ driver.join();
+ } catch (InterruptedException ignored) {
+ }
+ }else{
+ logger.debug("Self closing");
+ }
+ if(state == DriverStatus.NETWORK_READY){
+ logger.debug("Closing NETWORK");
+ setState(DriverStatus.HARDWARE_READY);
+ }
+ if(state == DriverStatus.HARDWARE_READY){
+ logger.debug("Closing HARDWARE");
+ high.close();
+ logger.debug("Closing LOW HARDWARE");
+ low.close();
+ setState(DriverStatus.CREATED);
+ }
+ if(state == DriverStatus.CREATED){
+ setState(DriverStatus.CLOSED);
+ }
+ logger.info("Closed");
+ }
+
+ public ZDO_IEEE_ADDR_RSP sendZDOIEEEAddressRequest(ZDO_IEEE_ADDR_REQ request){
+ if( waitForNetwork() == false ) return null;
+ ZDO_IEEE_ADDR_RSP result = null;
+
+ waitAndLock3WayConversation(request);
+ final WaitForCommand waiter = new WaitForCommand(ZToolCMD.ZDO_IEEE_ADDR_RSP, high);
+
+ logger.debug("Sending ZDO_IEEE_ADDR_REQ {}", request);
+ ZDO_IEEE_ADDR_REQ_SRSP response = (ZDO_IEEE_ADDR_REQ_SRSP) sendSynchrouns(high, request);
+ if ( response == null || response.Status != 0 ) {
+ logger.debug("ZDO_IEEE_ADDR_REQ failed, recieved {}", response);
+ waiter.cleanup();
+ } else {
+ result = (ZDO_IEEE_ADDR_RSP) waiter.getCommand(TIMEOUT);
+ }
+ unLock3WayConversation(request);
+ return result;
+ }
+
+ public ZDO_NODE_DESC_RSP sendZDONodeDescriptionRequest(ZDO_NODE_DESC_REQ request) {
+ if( waitForNetwork() == false ) return null;
+ ZDO_NODE_DESC_RSP result = null;
+
+ waitAndLock3WayConversation(request);
+ final WaitForCommand waiter = new WaitForCommand(ZToolCMD.ZDO_NODE_DESC_RSP, high);
+
+ ZDO_NODE_DESC_REQ_SRSP response = (ZDO_NODE_DESC_REQ_SRSP) sendSynchrouns(high, request);
+ if ( response == null || response.Status != 0 ) {
+ waiter.cleanup();
+ } else {
+ result = (ZDO_NODE_DESC_RSP) waiter.getCommand(TIMEOUT);
+ }
+
+ unLock3WayConversation(request);
+ return result;
+ }
+
+ public ZDO_ACTIVE_EP_RSP sendZDOActiveEndPointRequest(ZDO_ACTIVE_EP_REQ request) {
+ if( waitForNetwork() == false ) return null;
+ ZDO_ACTIVE_EP_RSP result = null;
+
+ waitAndLock3WayConversation(request);
+ final WaitForCommand waiter = new WaitForCommand(ZToolCMD.ZDO_ACTIVE_EP_RSP, high);
+
+ logger.debug("Sending ZDO_ACTIVE_EP_REQ {}", request);
+ ZDO_ACTIVE_EP_REQ_SRSP response = (ZDO_ACTIVE_EP_REQ_SRSP) sendSynchrouns(high, request);
+ if ( response == null || response.Status != 0 ) {
+ logger.debug("ZDO_ACTIVE_EP_REQ failed, recieved {}", response);
+ waiter.cleanup();
+ } else {
+ result = (ZDO_ACTIVE_EP_RSP) waiter.getCommand(TIMEOUT);
+ }
+ unLock3WayConversation(request);
+ return result;
+ }
+
+ /**
+ * @param request
+ */
+ private void waitAndLock3WayConversation(ZToolPacket request) {
+ synchronized (conversation3Way) {
+ Class<?> clz = request.getClass();
+ Thread requestor = null;
+ while( (requestor = conversation3Way.get(clz) ) != null ){
+ logger.debug("Waiting for {} issued by {} to complete", clz, requestor);
+ try{
+ conversation3Way.wait();
+ }catch(InterruptedException ex){
+ }
+ }
+ conversation3Way.put(clz, Thread.currentThread());
+ }
+ }
+
+ /**
+ * Release the lock held for the 3-way communication
+ *
+ * @param request
+ */
+ private void unLock3WayConversation(ZToolPacket request) {
+ Class<?> clz = request.getClass();
+ Thread requestor = null;
+ synchronized ( conversation3Way ) {
+ requestor = conversation3Way.get( clz );
+ conversation3Way.put( clz, null );
+ }
+ if( requestor == null ){
+ logger.error("LOCKING BROKEN SOMEONE RELEASE LOCK WITHOU LOCKING IN ADVANCE for {}", clz);
+ } else if( requestor != Thread.currentThread() ) {
+ logger.error(
+ "Thread {} stolen the answer of {} waited by {}",
+ new Object[]{ Thread.currentThread(), clz, requestor }
+ );
+ }
+ }
+
+ public ZDO_SIMPLE_DESC_RSP sendZDOSimpleDescriptionRequest(ZDO_SIMPLE_DESC_REQ request) {
+ if( waitForNetwork() == false ) return null;
+ ZDO_SIMPLE_DESC_RSP result = null;
+ waitAndLock3WayConversation(request);
+ final WaitForCommand waiter = new WaitForCommand(ZToolCMD.ZDO_SIMPLE_DESC_RSP, high);
+
+ ZDO_SIMPLE_DESC_REQ_SRSP response = (ZDO_SIMPLE_DESC_REQ_SRSP) sendSynchrouns(high, request);
+ if ( response == null || response.Status != 0 ) {
+ waiter.cleanup();
+ } else {
+ result = (ZDO_SIMPLE_DESC_RSP) waiter.getCommand(TIMEOUT);
+ }
+
+ unLock3WayConversation(request);
+ return result;
+ }
+
+ public void run() {
+ logger.info("Intializing");
+ setState(DriverStatus.HARDWARE_INITIALIZING);
+ if(initializeHardware() == true){
+ setState(DriverStatus.HARDWARE_READY);
+ }else{
+ close();
+ return;
+ }
+
+ setState(DriverStatus.NETWORK_INITIALIZING);
+ if(initializeZigBeeNetwork() == true){
+ setState(DriverStatus.NETWORK_READY);
+ }else{
+ close();
+ return;
+ }
+ }
+
+
+ @SuppressWarnings("unchecked")
+ private boolean initializeHardware() {
+ String portToOpen = null;
+ if("auto".equalsIgnoreCase(port)){
+ logger.info("Automatic discovery the dongle port by inspecting all the serail ports");
+ Enumeration<CommPortIdentifier> ports = CommPortIdentifier.getPortIdentifiers();
+ while(ports.hasMoreElements()){
+ CommPortIdentifier com = ports.nextElement();
+ if(DriverTSBn.initializeHardware(com.getName(), rate)){
+ portToOpen=com.getName();
+ Thread.currentThread().setName(buildDriverThreadName(portToOpen, rate));
+ break;
+ }
+ }
+ if ( portToOpen == null ) {
+ logger.error("Automatic discovery FAILED the dongle couldn't be find on any port: it may be frozen");
+ return false;
+ }
+ }else{
+ if( DriverTSBn.initializeHardware(port, rate) == true ){
+ portToOpen = port;
+ } else {
+ logger.error("Failed to intialize the dongle on port {} at rate {}", port, rate);
+ return false;
+ }
+ }
+
+ low = new HWLowLevelDriver();
+ try {
+ low.open(portToOpen, rate);
+ } catch (ZToolException e) {
+ logger.error("The port was already open in advance but we can't open it now",e);
+ return false;
+ }
+ high = new HWHighLevelDriver(low);
+ return true;
+ }
+
+ private void setState(DriverStatus value) {
+ logger.info("State changed from {} to {}", this.state, value);
+ synchronized (this) {
+ state = value;
+ notifyAll();
+ }
+ if(state == DriverStatus.HARDWARE_READY){
+ postHardwareEnabled();
+ }
+ }
+
+ private void postHardwareEnabled() {
+ if( ! afMessageListners.isEmpty() ){
+ high.addAsynchrounsCommandListener(afListner);
+ }
+ if( ! annunceListners.isEmpty() ){
+ high.addAsynchrounsCommandListener(annunceListner);
+ }
+ }
+
+ static boolean initializeHardware(String portName, int boudRate) {
+ boolean result = false;
+ final int recieved[] = new int[1];
+ final HWLowLevelDriver probingDriver = new HWLowLevelDriver();
+ final PacketListener monitor = new PacketListener(){
+ public void packetRecieved(ZToolPacket packet) {
+ logger.debug("Received initializing SYS VERSION candidate");
+ if(packet.getCommandId() == ZToolCMD.SYS_VERSION_RESPONSE){
+ logger.debug("Initializing Hardware: Received correctly SYS_VERSION_RESPONSE");
+ synchronized (recieved) {
+ recieved[0] = 3;
+ }
+ } else if(packet.isError()){
+ logger.debug("Initializing Hardware: Received erroneous packet: {}",packet.getErrorMsg());
+ synchronized (recieved) {
+ recieved[0] += 1;
+ }
+ } else {
+ logger.debug("Initializing Hardware: Received {}",packet.getClass().getName());
+ synchronized (recieved) {
+ recieved[0] += 1;
+ }
+ }
+ }
+
+ };
+ probingDriver.addPacketListener(monitor);
+ try {
+ probingDriver.open(portName,boudRate);
+ probingDriver.sendPacket(new SYS_VERSION());
+ final long ready = System.currentTimeMillis() + 5000;
+ while(ready > System.currentTimeMillis()){
+ synchronized (recieved) {
+ if( recieved[0] == 3 ){
+ logger.debug("Received initializing SYS VERSION");
+ break;
+ }
+ }
+
+ try {
+ Thread.sleep(500);
+ } catch (InterruptedException ignored) {
+ logger.debug("Exception SYS VERSION");
+ }
+ }
+ logger.debug("End of waiting for SYS VERSION");
+ synchronized (recieved) {
+ if( recieved[0] == 3 ){
+ logger.debug("Succeeded initializing SYS VERSION");
+ result = true;
+ }
+ }
+ } catch (ZToolException e) {
+ logger.info("Unable to open serial port: {}", portName);
+ logger.error("Unable to open serial port, due to:", e);
+ }catch (IOException e) {
+ logger.error("Hardware initialization failed", e);
+ }
+ probingDriver.close();
+ probingDriver.removePacketListener(monitor);
+ return result;
+ }
+
+ private boolean waitForHardware() {
+ synchronized (this) {
+ while (state == DriverStatus.CREATED || state == DriverStatus.CLOSED ){
+ logger.debug("Waiting for HARDWARE to become ready");
+ try {
+ wait();
+ } catch (InterruptedException ignored) {
+ }
+ }
+ return isHardwareReady();
+ }
+ }
+
+ private boolean waitForNetwork() {
+ synchronized (this) {
+ while (state != DriverStatus.NETWORK_READY && state != DriverStatus.CLOSED ){
+ logger.debug("Waiting for NETWORK to become ready");
+ try {
+ wait();
+ } catch (InterruptedException ignored) {
+ }
+ }
+ return isNetworkReady();
+ }
+ }
+
+ private class WaitForCommand implements AsynchrounsCommandListener{
+
+ final ZToolPacket[] result = new ZToolPacket[]{null};
+ final int waitFor;
+ final HWHighLevelDriver driver;
+
+ public WaitForCommand(int waitFor, HWHighLevelDriver driver) {
+ this.waitFor = waitFor;
+ this.driver = driver;
+ driver.addAsynchrounsCommandListener(this);
+ }
+
+
+
+ public void receivedAsynchrounsCommand(ZToolPacket packet) {
+ logger4Waiter.info("Recieved a packet {} and waiting for {}", packet.getCMD(), waitFor);
+ logger4Waiter.debug("Recieved {} {}", packet.getClass(), packet.toString());
+ if( packet.isError() ) return;
+ if( packet.getCMD().get16BitValue() != waitFor) return;
+ synchronized (result) {
+ result[0]=packet;
+ logger4Waiter.info("Recieved packet that we were waiting for");
+ cleanup();
+ }
+ }
+
+ public ZToolPacket getCommand(final long timeout){
+ synchronized (result) {
+ final long wakeUpTime = System.currentTimeMillis() + timeout;
+ while(result[0] == null && wakeUpTime > System.currentTimeMillis()){
+ try {
+ result.wait(wakeUpTime-System.currentTimeMillis());
+ } catch (InterruptedException ignored) {
+ }
+
+ }
+ }
+ if( result[0] == null ){
+ logger4Waiter.warn("Timeout {} expired and not packet with {} recieved", timeout, waitFor);
+ }
+ cleanup();
+ return result[0];
+ }
+
+ public void cleanup(){
+ synchronized (result) {
+ driver.removeAsynchrounsCommandListener(this);
+ result.notify();
+ }
+ }
+ }
+
+ private class WaitForAList implements PacketListener{
+
+ final int[] waitingList;
+ final ZToolPacket[] packetHistory;
+ final HWLowLevelDriver hwDriver;
+ int idx = 0;
+
+ /**
+ * This constructor uses the {@link WaitForAList#WaitForAList(int[], ZToolPacket[], HWLowLevelDriver) constructor<br>
+ * with the following parameters <code>WaitForAList(list,null,null)</code>
+ *
+ * @see WaitForAList#WaitForAList(int[], ZToolPacket[], HWLowLevelDriver)
+ * @param list
+ */
+ public WaitForAList(final int[] list){
+ this(list, null, null);
+ }
+
+ /**
+ * Create a {@link WaitForAList} that wait for a specified list<br>
+ * of packet to be received. Furthermore, the {@link WaitForAList}<br>
+ * while record all the matching packet received, and it will handle<br>
+ * by itself the registration and unregistration as {@link PacketListener}<br>
+ * to the specified {@link HWLowLevelDriver}.<br>
+ * <br>
+ * <b>NOTE:</b>If the {@link ZToolPacket} array is null no packet will be recorded<br>
+ * <b>NOTE:</b>If the {@link HWLowLevelDriver} array is null registration and unregistration as<br>
+ * {@link PacketListener} must be handled by the invoker<br>
+ *
+ * @param list the array of <code>int</code> to listen to
+ * @param packets {@link ZToolPacket} the array of the same size as <code>list</code> to record the received packet
+ * @param lowDriver {@link HWLowLevelDriver} to register to, if <code>null</code> to handle registration/unregistration manually
+ */
+ public WaitForAList(
+ final int[] list,
+ final ZToolPacket[] packets,
+ final HWLowLevelDriver lowDriver){
+ this.waitingList = list;
+ this.packetHistory = packets;
+ this.hwDriver = lowDriver;
+ if ( hwDriver != null) {
+ hwDriver.addPacketListener(this);
+ }
+ }
+
+ public void waitForAll(long timeout){
+ long wakeUpTime = System.currentTimeMillis() + timeout;
+ synchronized (waitingList) {
+ while( idx < waitingList.length && wakeUpTime > System.currentTimeMillis()){
+ try {
+ waitingList.wait(wakeUpTime - System.currentTimeMillis());
+ } catch (InterruptedException ignored) {
+ }
+ }
+ }
+ }
+
+ public void packetRecieved(ZToolPacket packet) {
+ if(packet.isError()) return;
+ if((packet.getCommandId() & 0xFFFF) == waitingList[idx]){
+ logger.info("Recieved packet that was waiting for incresing waitingList");
+ synchronized (waitingList) {
+ if ( packetHistory != null ) {
+ packetHistory[idx] = packet;
+ }
+ idx = idx + 1;
+ if ( idx == waitingList.length ){
+ if ( low != null) {
+ low.removePacketListener(this);
+ }
+ waitingList.notifyAll();
+ return;
+ }
+ }
+ }
+ }
+
+ }
+
+
+ private boolean dongleReset(){
+ if( waitForHardware() == false ) return false;
+
+ final WaitForCommand waiter = new WaitForCommand(
+ ZToolCMD.SYS_RESET_RESPONSE,
+ high
+ );
+
+// WaitForAList waiting = new WaitForAList(new int[]{
+// ZToolCMD.SYS_RESET_RESPONSE,
+// ZToolCMD.ZB_APP_REGISTER_RSP,
+// ZToolCMD.ZB_WRITE_CONFIGURATION_RSP,
+// ZToolCMD.ZB_WRITE_CONFIGURATION_RSP
+// });
+
+// low.addPacketListener(waiting);
+
+ try {
+ high.sendAsynchrounsCommand(new SYS_RESET(SYS_RESET.RESET_TYPE.SERIAL_BOOTLOADER));
+ } catch (IOException e) {
+ logger.error("DongleReset failed", e);
+ return false;
+ }
+
+ SYS_RESET_RESPONSE response =
+ (SYS_RESET_RESPONSE) waiter.getCommand(TIMEOUT);
+
+// waiting.waitForAll(TIMEOUT*2);
+// low.removePacketListener(waiting);
+ return response != null;
+ }
+
+ private boolean dongleClearState(){
+ dongleSetCleanState(true);
+
+ boolean result = dongleReset();
+
+ dongleSetCleanState(false);
+
+ return result;
+ }
+
+ private boolean dongleSetCleanState(boolean clean){
+ ZB_WRITE_CONFIGURATION_RSP response;
+ if(clean){
+ response = (ZB_WRITE_CONFIGURATION_RSP) sendSynchrouns(
+ high,
+ new ZB_WRITE_CONFIGURATION(
+ ZB_WRITE_CONFIGURATION.CONFIG_ID.ZCD_NV_STARTUP_OPTION,
+ new int[]{0x00000002}
+ )
+ );
+
+ if( response == null || response.Status != 0) {
+ logger.info("Couldn't set ZCD_NV_STARTUP_OPTION to CLEAN_STATE");
+ return false;
+ }else{
+ logger.info("Set ZCD_NV_STARTUP_OPTION to CLEAN_STATE");
+ }
+ }else{
+ response = (ZB_WRITE_CONFIGURATION_RSP) sendSynchrouns(
+ high,
+ new ZB_WRITE_CONFIGURATION(
+ ZB_WRITE_CONFIGURATION.CONFIG_ID.ZCD_NV_STARTUP_OPTION,
+ new int[]{0x00000000}
+ )
+ );
+
+ if( response == null || response.Status != 0) {
+ logger.info("Couldn't set ZCD_NV_STARTUP_OPTION back to DO_NOTHING");
+ return false;
+ }
+ }
+ return true;
+ }
+
+ static final int[] buildChannelMask(int channel){
+ int channelMask = 1 << channel;
+ int[] mask = new int[4];
+ for (int i = 0; i < mask.length; i++) {
+ mask[i] = Integers.getByteAsInteger(channelMask, i);
+ }
+ return mask;
+ }
+
+ private boolean dongleSetChannel(int[] channelMask) {
+
+ logger.info(
+ "Setting the channel to {}{}{}{}", new Object[]{
+ Integer.toHexString(channelMask[0]),
+ Integer.toHexString(channelMask[1]),
+ Integer.toHexString(channelMask[2]),
+ Integer.toHexString(channelMask[3])
+ }
+ );
+
+ ZB_WRITE_CONFIGURATION_RSP response =
+ (ZB_WRITE_CONFIGURATION_RSP) sendSynchrouns(
+ high,
+ new ZB_WRITE_CONFIGURATION(
+ ZB_WRITE_CONFIGURATION.CONFIG_ID.ZCD_NV_CHANLIST,
+ channelMask
+ )
+ );
+
+ return response != null && response.Status == 0;
+ }
+
+ private boolean dongleSetChannel(int ch){
+ int[] channelMask = buildChannelMask(ch);
+
+ return dongleSetChannel(channelMask);
+ }
+
+ private boolean dongleSetChannel(){
+ int[] channelMask = buildChannelMask(channel);
+
+ return dongleSetChannel(channelMask);
+ }
+
+ private boolean dongleSetNetworkMode(){
+ logger.info("Changing the Network Mode to {}", mode);
+
+ ZB_WRITE_CONFIGURATION_RSP response =
+ (ZB_WRITE_CONFIGURATION_RSP) sendSynchrouns(
+ high,
+ new ZB_WRITE_CONFIGURATION(
+ ZB_WRITE_CONFIGURATION.CONFIG_ID.ZCD_NV_LOGICAL_TYPE,
+ new int[]{ mode.ordinal() }
+ )
+ );
+
+ return response != null && response.Status == 0;
+ }
+
+ private boolean dongleSetPanId(){
+ ZB_WRITE_CONFIGURATION_RSP response =
+ (ZB_WRITE_CONFIGURATION_RSP) sendSynchrouns(
+ high,
+ new ZB_WRITE_CONFIGURATION(
+ ZB_WRITE_CONFIGURATION.CONFIG_ID.ZCD_NV_PANID,
+ new int[]{
+ Integers.getByteAsInteger(pan, 0),
+ Integers.getByteAsInteger(pan, 1)
+ }
+ )
+ );
+
+ return response != null && response.Status == 0;
+ }
+
+
+ private boolean createZigBeeNetwork(){
+ /*
+ * NOTE:The dongle has to be reset all the time to avoid that the endpoints
+ * register on the dongle itself break the code at upper level
+ *
+ */
+// if( reset && dongleReset() ) {
+// logger.debug("Reset the dongle before Creating ZigBee Network");
+// } else if (reset) {
+// logger.debug("FAILED to reset the dongle before Creating ZigBee Network");
+// } else {
+// logger.debug("Dongle has already been reset so no endpoint registered");
+// }
+ switch (mode) {
+ case Coordinator:
+ return doCoordinatorCreateNetwork();
+ case Router:
+ //TODO Implements start up as Router
+ return false;
+ case EndDevice:
+ return doEndDeviceCreateNetwok();
+ }
+
+ /*
+ * This code is unreachable but compiler can't find this out yet.
+ * It may introduce a compilation issue of future compilers
+ */
+ return false;
+ }
+
+ private boolean doEndDeviceCreateNetwok() {
+ logger.debug("Creating network as EndDevice");
+
+ ZDO_STARTUP_FROM_APP_SRSP response = (ZDO_STARTUP_FROM_APP_SRSP) sendSynchrouns(
+ high, new ZDO_STARTUP_FROM_APP(ZDO_STARTUP_FROM_APP.RESET_TYPE.TARGET_DEVICE)
+ );
+ if ( response == null ) {
+ return false;
+ } else {
+ return true;//TODO: response.Status == ZDO_STARTUP_FROM_APP_SRSP.AF_STATUS.SUCCESS;
+ }
+ }
+
+ private boolean doCoordinatorCreateNetwork() {
+ logger.info("Creating network as Coordintator");
+
+ ZB_READ_CONFIGURATION_RSP response = (ZB_READ_CONFIGURATION_RSP) sendSynchrouns(
+ high, new ZB_READ_CONFIGURATION(3));
+
+ if(response!=null && response.Status==0){
+ if(response.Len==1 && response.Value[0]==0){
+ dongleSetCleanState(false);
+ }
+ }else{
+ logger.error("Couldn´t get dongle status for startup");
+ return false;
+ }
+
+ ZDO_STARTUP_FROM_APP_SRSP response2 = (ZDO_STARTUP_FROM_APP_SRSP) sendSynchrouns(
+ high, new ZDO_STARTUP_FROM_APP(ZDO_STARTUP_FROM_APP.RESET_TYPE.TARGET_DEVICE)
+ );
+ if ( response2 == null ) {
+ return false;
+ } else {
+ return true;//TODO response.Status == ZDO_STARTUP_FROM_APP_SRSP.AF_STATUS.SUCCESS;
+ }
+ }
+
+ /*
+ //TODO We should check if the current setting differs from the setting stored on the dongle
+ * and later define whetever to clean or not the cache
+ private boolean mustCleanStatus(){
+ if( cleanStatus ) {
+ return true;
+ }
+
+ createZigBeeNetwork();
+
+ int[] value;
+
+ value = getDeviceInfo(ZB_GET_DEVICE_INFO.DEV_INFO_TYPE.CHANNEL);
+ if ( value == null){
+ logger.error("Method getDeviceInfo(ZB_GET_DEVICE_INFO.DEV_INFO_TYPE.CHANNEL) returned null");
+ return true;
+ } else if ( value[0] != this.channel ) {
+ logger.debug("Dongle network state must be reset because channel is changed. " +
+ "Old was = {} while new is {}", value[0], this.channel);
+ return true;
+ }
+
+ value = getDeviceInfo(ZB_GET_DEVICE_INFO.DEV_INFO_TYPE.PAN_ID);
+ if ( value == null){
+ logger.error("Method getDeviceInfo(ZB_GET_DEVICE_INFO.DEV_INFO_TYPE.PAN_ID) returned null");
+ return true;
+ } else if ( Integers.shortFromInts(value, 1, 0) != this.pan) {
+ logger.debug("Dongle network state must be reset because PanId is changed. " +
+ "Old was = {} while new is {}", Integers.shortFromInts(value, 1, 0), this.pan);
+ return true;
+ }
+
+ dongleReset();
+
+ return false;
+ }
+ */
+
+ private boolean initializeZigBeeNetwork() {
+
+ boolean cleanNetworkState = cleanStatus;
+
+ if(cleanNetworkState){
+ if ( doCleanAndSetConfiguration() == false ) {
+ return false;
+ }
+ }
+ boolean creation = createZigBeeNetwork();
+ if ( creation == false ){
+ return false;
+ }
+ state = DriverStatus.NETWORK_READY;
+ if ( doesCurrentConfigurationMatchZStackConfiguration() ) {
+ logger.error("Dongle configuration does not match specified configuration");
+ }
+ return creation;
+
+ }
+
+ private boolean doesCurrentConfigurationMatchZStackConfiguration() {
+ int value = -1;
+ boolean mismatch = false;
+ if ( ( value = getCurrentChannel() ) != channel ) {
+ logger.warn(
+ "The channel configuration differ from the channel configuration in use: " +
+ "in use {}, while the configured is {}.\n" +
+ "The ZigBee Stack shuold be flushed, try to set "+ConfigurationProperties.NETWORK_FLUSH+" to TRUE",
+ value, channel
+ );
+ mismatch = true;
+ }
+ if ( ( value = getCurrentPanId() ) != pan ) {
+ logger.warn(
+ "The PanId configuration differ from the channel configuration in use: " +
+ "in use {}, while the configured is {}.\n" +
+ "The ZigBee Stack shuold be flushed, try to set "+ConfigurationProperties.NETWORK_FLUSH+" to TRUE",
+ value, pan
+ );
+ mismatch = true;
+ }
+ if ( ( value = getZigBeeNodeMode() ) != mode.ordinal() ) {
+ logger.warn(
+ "The NetworkMode configuration differ from the channel configuration in use: " +
+ "in use {}, while the configured is {}.\n" +
+ "The ZigBee Stack should be flushed, try to set "+ConfigurationProperties.NETWORK_FLUSH+" to TRUE",
+ value, mode.ordinal()
+ );
+ mismatch = true;
+ }
+
+ return mismatch;
+ }
+
+ private boolean doCleanAndSetConfiguration() {
+ logger.debug("Cleaning dongle networks stack status");
+// if( ! dongleClearState() ){
+// logger.error("Unable to CLEAN the ZigBee network stack staus");
+// return false;
+// } else {
+// logger.info("ZigBee network stack status CLEANED");
+// }
+ if( ! dongleSetCleanState(true) ){
+ logger.error("Unable to set clean state for dongle");
+ return false;
+ }
+ if( ! dongleSetChannel() ){
+ logger.error("Unable to set CHANNEL for ZigBee Network");
+ return false;
+ } else {
+ logger.info("CHANNEL set");
+ }
+ if( ! dongleSetPanId() ){
+ logger.error("Unable to set PANID for ZigBee Network");
+ return false;
+ } else {
+ logger.info("PANID set");
+ }
+ if ( dongleSetNetworkMode() == false ) {
+ logger.error("Unable to set NETWORK_MODE for ZigBee Network");
+ return false;
+ } else {
+ logger.info("NETWORK_MODE set");
+ }
+ if( ! dongleReset() ){
+ logger.error("Unable to reset dongle");
+ return false;
+ }
+ if( ! dongleSetCleanState(false) ){
+ logger.error("Unable to unset clean state for dongle");
+ return false;
+ }
+// if ( dongleMasterReset() == false ) {
+// logger.error("Unable to send the master reset for ZigBee Network");
+// return false;
+// } else {
+// logger.info("master reset sent");
+// }
+ return true;
+ }
+
+ protected boolean dongleMasterReset() {
+ //---------START FROM APP
+ logger.debug("Reset seq: Trying STARTFROMAPP");
+ ZDO_STARTUP_FROM_APP_SRSP responseA1 = (ZDO_STARTUP_FROM_APP_SRSP) sendSynchrouns(
+ high, new ZDO_STARTUP_FROM_APP(ZDO_STARTUP_FROM_APP.RESET_TYPE.TARGET_DEVICE)
+ );
+ if (responseA1==null){logger.error("Reset seq: Failed STARTFROMAPP");return false;}
+ //---------ZB WRITE CONF
+ logger.debug("Reset seq: Trying WRITECONF");
+ ZB_WRITE_CONFIGURATION_RSP responseA2 = (ZB_WRITE_CONFIGURATION_RSP) sendSynchrouns(
+ high, new ZB_WRITE_CONFIGURATION(3,new int[]{2})
+ );
+ if (responseA2==null){logger.error("Reset seq: Failed WRITECONF");return false;}
+ //---------GET DEVICE INFO
+ logger.debug("Reset seq: Trying GETDEVICEINFO");
+// final WaitForCommand waiter1 = new WaitForCommand(
+// ZToolCMD.UTIL_GET_DEVICE_INFO_RESPONSE,
+// high
+// );
+// try{
+// high.sendAsynchrounsCommand(new UTIL_GET_DEVICE_INFO());
+// } catch (IOException e) {
+// logger.error("GetDeviceInfo of Master Reset failed", e);
+// return false;
+// }
+// UTIL_GET_DEVICE_INFO_RESPONSE responseA3 = (UTIL_GET_DEVICE_INFO_RESPONSE) waiter1.getCommand(TIMEOUT);
+ UTIL_GET_DEVICE_INFO_RESPONSE responseA3 = (UTIL_GET_DEVICE_INFO_RESPONSE) sendSynchrouns(high,new UTIL_GET_DEVICE_INFO());
+ if (responseA3==null){logger.error("Reset seq: Failed GETDEVICEINFO");return false;}
+ ZToolAddress16[] addresses = new ZToolAddress16[responseA3.AssocDevicesList.length];
+ for(int k=0;k<responseA3.AssocDevicesList.length;k++){
+ addresses[k]=new ZToolAddress16(responseA3.AssocDevicesList[k].getMsb(),responseA3.AssocDevicesList[k].getLsb());
+ }
+ //---------ZDO GET IEEE ADDR
+ logger.debug("Reset seq: Trying GETIEEEADDR");
+ ZToolAddress64[] longAddresses = new ZToolAddress64[addresses.length];
+ for(int k=0;k<addresses.length;k++){
+// ZDO_IEEE_ADDR_RSP responseA4 = sendZDOIEEEAddressRequest(new ZDO_IEEE_ADDR_REQ(addresses[k],ZDO_IEEE_ADDR_REQ.REQ_TYPE.EXTENDED.getValue(),0));
+
+ ZDO_IEEE_ADDR_RSP responseA4 = null;
+ WaitForCommand waiter = new WaitForCommand(ZToolCMD.ZDO_IEEE_ADDR_RSP, high);
+ logger.debug("Sending ZDO_IEEE_ADDR_REQ");
+ ZDO_IEEE_ADDR_REQ_SRSP response = (ZDO_IEEE_ADDR_REQ_SRSP) sendSynchrouns(high, new ZDO_IEEE_ADDR_REQ(addresses[k],ZDO_IEEE_ADDR_REQ.REQ_TYPE.EXTENDED.getValue(),0));
+ if ( response == null || response.Status != 0 ) {
+ logger.debug("ZDO_IEEE_ADDR_REQ failed, recieved {}", response);
+ waiter.cleanup();
+ } else {
+ responseA4 = (ZDO_IEEE_ADDR_RSP) waiter.getCommand(TIMEOUT);
+ }
+
+ if (responseA4!=null){
+ longAddresses[k]=responseA4.getIEEEAddress();
+ }else{
+ longAddresses[k]=null;
+ }
+ }
+ //---------ZDO MGMT LEAVE
+ logger.debug("Reset seq: Trying LEAVE");
+ long start=System.currentTimeMillis();
+ for (int k = 0; k < longAddresses.length; k++) {
+ if (longAddresses[k] != null) {
+ WaitForCommand waiter3 = new WaitForCommand(ZToolCMD.ZDO_MGMT_LEAVE_RSP, high);
+
+ ZDO_MGMT_LEAVE_REQ_SRSP response = (ZDO_MGMT_LEAVE_REQ_SRSP) sendSynchrouns(high, new ZDO_MGMT_LEAVE_REQ(addresses[k], longAddresses[k], 3));
+ if ((System.currentTimeMillis() - start) > 5000){logger.error("Reset seq: Failed LEAVE");return false;}
+ if ( response == null || response.Status != 0 ) {
+ waiter3.cleanup();
+ logger.error("Reset seq: Failed LEAVE");
+ return false;
+ } else {
+ if ((System.currentTimeMillis() - start) > 5000){logger.error("Reset seq: Failed LEAVE");return false;}
+ ZDO_MGMT_LEAVE_RSP responseA5 = (ZDO_MGMT_LEAVE_RSP) waiter3.getCommand(TIMEOUT);
+ if ((System.currentTimeMillis() - start) > 5000){logger.error("Reset seq: Failed LEAVE");return false;}
+ if(responseA5==null || responseA5.Status!=ZDO_MGMT_LEAVE_RSP.ZDO_STATUS.ZDP_SUCCESS){logger.error("Reset seq: Failed LEAVE");return false;}
+ }
+ }
+ if ((System.currentTimeMillis() - start) > 5000){logger.error("Reset seq: Failed LEAVE");return false;}
+ }
+
+ //---------SYS RESET
+ logger.debug("Reset seq: Trying SYSRESET");
+ if (!dongleReset()){logger.error("Reset seq: Failed SYSRESET");return false;}
+ //---------START FROM APP
+// //already in initializeZigBeeNetwork
+// ZDO_STARTUP_FROM_APP_SRSP responseA7 = (ZDO_STARTUP_FROM_APP_SRSP) sendSynchrouns(
+// high, new ZDO_STARTUP_FROM_APP(ZDO_STARTUP_FROM_APP.RESET_TYPE.TARGET_DEVICE)
+// );
+// if (responseA7==null)return false;
+ return true;
+ }
+
+ private ZToolPacket sendSynchrouns(final HWHighLevelDriver hwDriver, final ZToolPacket request) {
+ final ZToolPacket[] response = new ZToolPacket[]{null};
+// final int TIMEOUT = 1000, MAX_SEND = 3;
+ int sending = 1;
+
+ logger.info("Sending Synchrouns {}", request.getClass().getName());
+
+ SynchrounsCommandListner listener = new SynchrounsCommandListner() {
+
+ public void receivedCommandResponse(ZToolPacket packet) {
+ logger.info("Recieved Synchrouns Response {}", packet.getClass().getName());
+ synchronized (response) {
+ response[0] = packet;
+ response.notify();
+ }
+ }
+
+ };
+
+ while( sending <= RESEND_MAX_RETRY ){
+ try {
+ hwDriver.sendSynchrounsCommand(request, listener, RESEND_TIMEOUT);
+ logger.info("Sent {} during the {}-th tenative", request.getClass().getName(),sending);
+ synchronized (response) {
+ long wakeUpTime = System.currentTimeMillis() + RESEND_TIMEOUT;
+ while(response[0] == null && wakeUpTime > System.currentTimeMillis()){
+ final long sleeping = wakeUpTime - System.currentTimeMillis();
+ logger.debug("Waiting Synchrouns for up to {}ms till {} Unixtime", sleeping, wakeUpTime);
+ if ( sleeping <= 0 ) {
+ break;
+ }
+ try {
+ response.wait(sleeping);
+ } catch (InterruptedException ignored) {
+ }
+ }
+ }
+ if ( response[0] != null ) {
+ logger.debug("Recieved synchrouns command {} before timout", response[0]);
+ } else {
+ logger.debug("Timeout fired and not synchrouns command recieved", response[0]);
+ }
+ if ( RESEND_ONLY_EXCEPTION ) {
+ break;
+ }else{
+ logger.info("Failed to send {} during the {}-th tenative", request.getClass().getName(),sending);
+ sending++;
+ }
+ }catch(IOException ignored){
+ logger.info("Failed to send {} during the {}-th tenative", request.getClass().getName(),sending);
+ logger.debug("Sending operation failed due to ", ignored);
+ sending++;
+ }
+ }
+
+ return response[0];
+ }
+
+ public boolean addAnnunceListener(AnnunceListner listner){
+ if(annunceListners.isEmpty() && isHardwareReady() ){
+ high.addAsynchrounsCommandListener(annunceListner);
+ }
+ return annunceListners.add(listner);
+ }
+
+ public boolean removeAnnunceListener(AnnunceListner listner){
+ boolean result = annunceListners.remove(listner);
+ if(annunceListners.isEmpty() && isHardwareReady() ){
+ high.removeAsynchrounsCommandListener(annunceListner);
+ }
+ return result;
+ }
+
+ public AF_REGISTER_SRSP sendAFRegister(AF_REGISTER request) {
+ if( waitForNetwork() == false ) return null;
+
+ AF_REGISTER_SRSP response = (AF_REGISTER_SRSP) sendSynchrouns(high, request);
+ return response;
+ }
+
+ public AF_DATA_CONFIRM sendAFDataRequest(AF_DATA_REQUEST request) {
+ if( waitForNetwork() == false ) return null;
+ AF_DATA_CONFIRM result = null;
+
+ waitAndLock3WayConversation(request);
+ final WaitForCommand waiter = new WaitForCommand(ZToolCMD.AF_DATA_CONFIRM, high);
+
+ AF_DATA_SRSP response = (AF_DATA_SRSP) sendSynchrouns(high, request);
+ if ( response == null || response.Status != 0 ) {
+ waiter.cleanup();
+ } else {
+ result = (AF_DATA_CONFIRM) waiter.getCommand(TIMEOUT);
+ }
+ unLock3WayConversation(request);
+ return result;
+ }
+
+ public ZDO_BIND_RSP sendZDOBind(ZDO_BIND_REQ request) {
+ if( waitForNetwork() == false ) return null;
+ ZDO_BIND_RSP result = null;
+
+ waitAndLock3WayConversation(request);
+ final WaitForCommand waiter = new WaitForCommand(ZToolCMD.ZDO_BIND_RSP, high);
+
+ ZDO_BIND_REQ_SRSP response = (ZDO_BIND_REQ_SRSP) sendSynchrouns(high, request);
+ if ( response == null || response.Status != 0 ) {
+ waiter.cleanup();
+ } else {
+ result = (ZDO_BIND_RSP) waiter.getCommand(TIMEOUT);
+ }
+ unLock3WayConversation(request);
+ return result;
+ }
+
+ public ZDO_UNBIND_RSP sendZDOUnbind(ZDO_UNBIND_REQ request) {
+ if( waitForNetwork() == false ) return null;
+ ZDO_UNBIND_RSP result = null;
+
+ waitAndLock3WayConversation(request);
+ final WaitForCommand waiter = new WaitForCommand(ZToolCMD.ZDO_UNBIND_RSP, high);
+
+ ZDO_UNBIND_REQ_SRSP response = (ZDO_UNBIND_REQ_SRSP) sendSynchrouns(high, request);
+ if ( response == null || response.Status != 0 ) {
+ waiter.cleanup();
+ } else {
+ result = (ZDO_UNBIND_RSP) waiter.getCommand(TIMEOUT);
+ }
+
+ unLock3WayConversation(request);
+ return result;
+ }
+
+ public boolean removeAFMessageListener(AFMessageListner listner){
+ boolean result = false;
+ synchronized (afMessageListners) {
+ result = afMessageListners.remove(listner);
+ }
+
+ if(afMessageListners.isEmpty() && isHardwareReady() ){
+ if ( high.removeAsynchrounsCommandListener(afListner) ) {
+ logger.debug("Removed AsynchrounsCommandListener {} to HWHighLevelDriver", afListner.getClass().getName());
+ } else {
+ logger.debug("Could not remove AsynchrounsCommandListener {} to HWHighLevelDriver", afListner.getClass().getName());
+ }
+ }
+ if ( result ) {
+ logger.debug("Removed AFMessageListner {}:{}", listner, listner.getClass().getName());
+ return true;
+ } else {
+ logger.debug("Could not remove AFMessageListner {}:{}", listner, listner.getClass().getName());
+ return false;
+ }
+ }
+
+ public boolean addAFMessageListner(AFMessageListner listner) {
+ if(afMessageListners.isEmpty() && isHardwareReady() ){
+ if ( high.addAsynchrounsCommandListener(afListner) ) {
+ logger.debug("Added AsynchrounsCommandListener {} to HWHighLevelDriver", afListner.getClass().getName());
+ } else {
+ logger.debug("Could not add AsynchrounsCommandListener {} to HWHighLevelDriver", afListner.getClass().getName());
+ }
+ }
+ boolean result = false;
+ synchronized (afMessageListners) {
+ result = afMessageListners.add(listner);
+ }
+
+ if ( result ) {
+ logger.debug("Added AFMessageListner {}:{}", listner, listner.getClass().getName());
+ return true;
+ } else {
+ logger.debug("Could not add AFMessageListner {}:{}", listner, listner.getClass().getName());
+ return false;
+ }
+ }
+
+ private boolean isNetworkReady() {
+ synchronized (this) {
+ return state.ordinal() >= DriverStatus.NETWORK_READY.ordinal()
+ && state.ordinal() < DriverStatus.CLOSED.ordinal();
+ }
+ }
+
+ private boolean isHardwareReady() {
+ synchronized (this) {
+ return state.ordinal() >= DriverStatus.HARDWARE_READY.ordinal()
+ && state.ordinal() < DriverStatus.CLOSED.ordinal();
+ }
+ }
+
+ /**
+ *
+ * @return
+ * @since 0.2.0
+ */
+ public long getExtendedPanId() {
+ if( waitForNetwork() == false ) {
+ logger.info("Failed to reach the {} level: getExtendedPanId() failed", DriverStatus.NETWORK_READY);
+ return -1;
+ }
+
+ int[] result = getDeviceInfo(ZB_GET_DEVICE_INFO.DEV_INFO_TYPE.EXT_PAN_ID);
+
+ if( result == null ){
+ return -1;
+ } else {
+ return Integers.shortFromInts(result, 7, 0);
+ } }
+
+ /**
+ *
+ * @return
+ * @since 0.2.0
+ */
+ public long getIEEEAddress() {
+
+ if( ieeeAddress != -1 ){
+ return ieeeAddress;
+ }
+
+ if( waitForNetwork() == false ) {
+ logger.info("Failed to reach the {} level: getIEEEAddress() failed", DriverStatus.NETWORK_READY);
+ return -1;
+ }
+
+ int[] result = getDeviceInfo(ZB_GET_DEVICE_INFO.DEV_INFO_TYPE.IEEE_ADDR);
+
+ if( result == null ){
+ return -1;
+ } else {
+ ieeeAddress = Integers.longFromInts(result, 7, 0);
+ return ieeeAddress;
+ }
+ }
+
+ /**
+ *
+ * @return
+ * @since 0.2.0
+ */
+ public int getCurrentPanId(){
+ if( waitForNetwork() == false ) {
+ logger.info("Failed to reach the {} level: getCurrentPanId() failed", DriverStatus.NETWORK_READY);
+ return -1;
+ }
+
+ int[] result = getDeviceInfo(ZB_GET_DEVICE_INFO.DEV_INFO_TYPE.PAN_ID);
+
+ if( result == null ){
+ return -1;
+ } else {
+ return Integers.shortFromInts(result, 1, 0);
+ }
+ }
+
+ /**
+ *
+ * @return
+ * @since 0.2.0
+ */
+ public int getCurrentChannel(){
+ if( waitForNetwork() == false ) {
+ logger.info("Failed to reach the {} level: getCurrentChannel() failed", DriverStatus.NETWORK_READY);
+ return -1;
+ }
+
+ int[] result = getDeviceInfo(ZB_GET_DEVICE_INFO.DEV_INFO_TYPE.CHANNEL);
+
+ if( result == null ){
+ return -1;
+ } else {
+ return result[0];
+ }
+ }
+
+ /**
+ *
+ * @return
+ * @since 0.2.0
+ */
+ public int getCurrentState(){
+ if( waitForNetwork() == false ) {
+ logger.info("Failed to reach the {} level: getCurrentChannel() failed", DriverStatus.NETWORK_READY);
+ return -1;
+ }
+
+ int[] result = getDeviceInfo(ZB_GET_DEVICE_INFO.DEV_INFO_TYPE.STATE);
+
+ if( result == null ){
+ return -1;
+ } else {
+ return result[0];
+ }
+ }
+
+
+ private int[] getDeviceInfo(int type){
+ ZB_GET_DEVICE_INFO_RSP response = (ZB_GET_DEVICE_INFO_RSP) sendSynchrouns(
+ high, new ZB_GET_DEVICE_INFO(type)
+ );
+
+ if ( response == null ){
+ logger.debug("Failed getDeviceInfo for {} due to null value", type);
+ return null;
+ } else if ( response.Param != type ) {
+ logger.debug("Failed getDeviceInfo for {} non matching response returned {}", type, response.Param);
+ return null;
+ } else {
+ logger.debug("Successed getDeviceInfo for {}", type);
+ return response.Value;
+ }
+ }
+
+ public int getZigBeeNodeMode(){
+ ZB_READ_CONFIGURATION_RSP response =
+ (ZB_READ_CONFIGURATION_RSP) sendSynchrouns(
+ high,
+ new ZB_READ_CONFIGURATION( ZB_WRITE_CONFIGURATION.CONFIG_ID.ZCD_NV_LOGICAL_TYPE )
+ );
+ if ( response != null && response.Status == 0 ) {
+ return response.Value[0];
+ } else {
+ return -1;
+ }
+ }
+
+ public DriverStatus getDriverStatus() {
+ return state;
+ }
+
+}
+
Propchange: projects/zb4osgi/sandbox/miguel.llorente/zibgee.tsb.driver/src/main/java/it/cnr/isti/zigbee/dongle/tsb/impl/DriverTSBn.java
------------------------------------------------------------------------------
svn-mine-type = text/plain
Propchange: projects/zb4osgi/sandbox/miguel.llorente/zibgee.tsb.driver/src/main/java/it/cnr/isti/zigbee/dongle/tsb/impl/DriverTSBn.java
------------------------------------------------------------------------------
svn:eol-style = native
Propchange: projects/zb4osgi/sandbox/miguel.llorente/zibgee.tsb.driver/src/main/java/it/cnr/isti/zigbee/dongle/tsb/impl/DriverTSBn.java
------------------------------------------------------------------------------
svn:keywords = Id Author Date Revision
Added: projects/zb4osgi/sandbox/miguel.llorente/zibgee.tsb.driver/src/main/java/it/cnr/isti/zigbee/dongle/tsb/impl/MasterResetGUI.java
==============================================================================
--- projects/zb4osgi/sandbox/miguel.llorente/zibgee.tsb.driver/src/main/java/it/cnr/isti/zigbee/dongle/tsb/impl/MasterResetGUI.java (added)
+++ projects/zb4osgi/sandbox/miguel.llorente/zibgee.tsb.driver/src/main/java/it/cnr/isti/zigbee/dongle/tsb/impl/MasterResetGUI.java Fri May 20 11:42:58 2011
@@ -1,0 +1,97 @@
+package it.cnr.isti.zigbee.dongle.tsb.impl;
+
+import java.awt.Dimension;
+
+import javax.swing.UIManager;
+
+public class MasterResetGUI extends javax.swing.JFrame {
+ DriverTSBn parentDriver;
+ public MasterResetGUI(DriverTSBn parent) {
+ parentDriver=parent;
+ try {
+ UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
+ } catch (Exception e) {
+ System.err.println("Windows Look&Feel Not Found !");
+ }
+ initComponents();
+ }
+
+ /** This method is called from within the constructor to
+ * initialize the form.
+ * WARNING: Do NOT modify this code. The content of this method is
+ * always regenerated by the Form Editor.
+ */
+ // <editor-fold defaultstate="collapsed" desc="Generated Code">
+ private void initComponents() {
+
+ contextTabbedPane = new javax.swing.JTabbedPane();
+ contextPanel1 = new javax.swing.JPanel();
+ contextPanel1chkBox1 = new javax.swing.JCheckBox();
+ contextPanel1sendButton = new javax.swing.JButton();
+ jLabel1 = new javax.swing.JLabel();
+ txtBoxSequence = new javax.swing.JTextField();
+
+ //WINDOW
+ setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
+ this.setBounds(800, 660, 420, 330);
+ this.setMaximumSize(new Dimension(320, 230));
+ this.setMinimumSize(new Dimension(320, 230));
+ this.setPreferredSize(new Dimension(320, 230));
+ setResizable(true);
+ getContentPane().setLayout(null);
+
+ //TAB 1
+ contextPanel1.setLayout(null);
+
+ txtBoxSequence.setText("Sequence");
+ contextPanel1.add(txtBoxSequence);
+ txtBoxSequence.setBounds(20, 20, 210, 23);
+
+ contextPanel1chkBox1.setText("ARMED");
+ contextPanel1.add(contextPanel1chkBox1);
+ contextPanel1chkBox1.setBounds(20, 50, 190, 23);
+
+ contextPanel1sendButton.setText("RESET");
+ contextPanel1sendButton.addActionListener(new java.awt.event.ActionListener() {
+ public void actionPerformed(java.awt.event.ActionEvent evt) {
+ sendButton1ActionPerformed(evt);
+ }
+ });
+ contextPanel1.add(contextPanel1sendButton);
+ contextPanel1sendButton.setBounds(20, 80, 75, 29);
+
+ contextTabbedPane.addTab("Master Reset", contextPanel1);
+
+ //MAIN
+ getContentPane().add(contextTabbedPane);
+ contextTabbedPane.setBounds(10, 40, 300, 160);
+
+ jLabel1.setFont(new java.awt.Font("Verdana", 1, 14));
+ jLabel1.setText("Master Reset");
+ getContentPane().add(jLabel1);
+ jLabel1.setBounds(10, 10, 300, 18);
+
+ pack();
+ }// </editor-fold>
+
+ private void sendButton1ActionPerformed(java.awt.event.ActionEvent evt) {
+ if(this.txtBoxSequence.getText().equals("1a2b3c4d")){
+ if(this.contextPanel1chkBox1.isSelected()){
+ //MASTER RESET!!
+ parentDriver.dongleMasterReset();
+ }
+ }else{
+ this.txtBoxSequence.setText("Invalid");
+ }
+ }
+
+ // Variables declaration - do not modify
+ private javax.swing.JTabbedPane contextTabbedPane;
+ private javax.swing.JLabel jLabel1;
+ private javax.swing.JButton contextPanel1sendButton;
+ private javax.swing.JCheckBox contextPanel1chkBox1;
+ private javax.swing.JPanel contextPanel1;
+ private javax.swing.JTextField txtBoxSequence;
+ // End of variables declaration
+
+}
Propchange: projects/zb4osgi/sandbox/miguel.llorente/zibgee.tsb.driver/src/main/java/it/cnr/isti/zigbee/dongle/tsb/impl/MasterResetGUI.java
------------------------------------------------------------------------------
svn-mine-type = text/plain
Propchange: projects/zb4osgi/sandbox/miguel.llorente/zibgee.tsb.driver/src/main/java/it/cnr/isti/zigbee/dongle/tsb/impl/MasterResetGUI.java
------------------------------------------------------------------------------
svn:eol-style = native
Propchange: projects/zb4osgi/sandbox/miguel.llorente/zibgee.tsb.driver/src/main/java/it/cnr/isti/zigbee/dongle/tsb/impl/MasterResetGUI.java
------------------------------------------------------------------------------
svn:keywords = Id Author Date Revision
More information about the Commit
mailing list