From 5b5271e98c6d7f0ffea9d6b3fbf2cec43d283d64 Mon Sep 17 00:00:00 2001 From: Tat-Chee Wan (USM) Date: Tue, 1 Mar 2011 09:10:13 +0800 Subject: Imported nxt-python baseline (v2.1.0) --- nxt-python-2.1.0.tar.gz | Bin 0 -> 49769 bytes nxt-python-fantom/LICENSE | 674 +++++++++++++++++++++++ nxt-python-fantom/MANIFEST.in | 4 + nxt-python-fantom/PKG-INFO | 168 ++++++ nxt-python-fantom/README | 169 ++++++ nxt-python-fantom/examples/alpharex.py | 151 ++++++ nxt-python-fantom/examples/cnc.py | 53 ++ nxt-python-fantom/examples/latency.py | 23 + nxt-python-fantom/examples/mary.py | 45 ++ nxt-python-fantom/examples/message_test.py | 15 + nxt-python-fantom/examples/spin.py | 14 + nxt-python-fantom/examples/test_sensors.py | 11 + nxt-python-fantom/install.bat | 11 + nxt-python-fantom/nxt/__init__.py | 17 + nxt-python-fantom/nxt/bluesock.py | 78 +++ nxt-python-fantom/nxt/brick.py | 225 ++++++++ nxt-python-fantom/nxt/direct.py | 216 ++++++++ nxt-python-fantom/nxt/error.py | 87 +++ nxt-python-fantom/nxt/lightblueglue.py | 53 ++ nxt-python-fantom/nxt/locator.py | 57 ++ nxt-python-fantom/nxt/motor.py | 431 +++++++++++++++ nxt-python-fantom/nxt/sensor/__init__.py | 50 ++ nxt-python-fantom/nxt/sensor/analog.py | 41 ++ nxt-python-fantom/nxt/sensor/common.py | 67 +++ nxt-python-fantom/nxt/sensor/digital.py | 227 ++++++++ nxt-python-fantom/nxt/sensor/generic.py | 154 ++++++ nxt-python-fantom/nxt/sensor/hitechnic.py | 611 +++++++++++++++++++++ nxt-python-fantom/nxt/sensor/mindsensors.py | 815 ++++++++++++++++++++++++++++ nxt-python-fantom/nxt/system.py | 297 ++++++++++ nxt-python-fantom/nxt/telegram.py | 118 ++++ nxt-python-fantom/nxt/usbsock.py | 82 +++ nxt-python-fantom/nxt/utils.py | 33 ++ nxt-python-fantom/scripts/nxt_filer | 142 +++++ nxt-python-fantom/scripts/nxt_push | 47 ++ nxt-python-fantom/scripts/nxt_test | 33 ++ nxt-python-fantom/setup.py | 23 + 36 files changed, 5242 insertions(+) create mode 100644 nxt-python-2.1.0.tar.gz create mode 100644 nxt-python-fantom/LICENSE create mode 100644 nxt-python-fantom/MANIFEST.in create mode 100644 nxt-python-fantom/PKG-INFO create mode 100644 nxt-python-fantom/README create mode 100644 nxt-python-fantom/examples/alpharex.py create mode 100644 nxt-python-fantom/examples/cnc.py create mode 100644 nxt-python-fantom/examples/latency.py create mode 100644 nxt-python-fantom/examples/mary.py create mode 100644 nxt-python-fantom/examples/message_test.py create mode 100644 nxt-python-fantom/examples/spin.py create mode 100644 nxt-python-fantom/examples/test_sensors.py create mode 100644 nxt-python-fantom/install.bat create mode 100644 nxt-python-fantom/nxt/__init__.py create mode 100644 nxt-python-fantom/nxt/bluesock.py create mode 100644 nxt-python-fantom/nxt/brick.py create mode 100644 nxt-python-fantom/nxt/direct.py create mode 100644 nxt-python-fantom/nxt/error.py create mode 100644 nxt-python-fantom/nxt/lightblueglue.py create mode 100644 nxt-python-fantom/nxt/locator.py create mode 100644 nxt-python-fantom/nxt/motor.py create mode 100644 nxt-python-fantom/nxt/sensor/__init__.py create mode 100644 nxt-python-fantom/nxt/sensor/analog.py create mode 100644 nxt-python-fantom/nxt/sensor/common.py create mode 100644 nxt-python-fantom/nxt/sensor/digital.py create mode 100644 nxt-python-fantom/nxt/sensor/generic.py create mode 100644 nxt-python-fantom/nxt/sensor/hitechnic.py create mode 100644 nxt-python-fantom/nxt/sensor/mindsensors.py create mode 100644 nxt-python-fantom/nxt/system.py create mode 100644 nxt-python-fantom/nxt/telegram.py create mode 100644 nxt-python-fantom/nxt/usbsock.py create mode 100644 nxt-python-fantom/nxt/utils.py create mode 100644 nxt-python-fantom/scripts/nxt_filer create mode 100644 nxt-python-fantom/scripts/nxt_push create mode 100644 nxt-python-fantom/scripts/nxt_test create mode 100644 nxt-python-fantom/setup.py diff --git a/nxt-python-2.1.0.tar.gz b/nxt-python-2.1.0.tar.gz new file mode 100644 index 0000000..014132b Binary files /dev/null and b/nxt-python-2.1.0.tar.gz differ diff --git a/nxt-python-fantom/LICENSE b/nxt-python-fantom/LICENSE new file mode 100644 index 0000000..818433e --- /dev/null +++ b/nxt-python-fantom/LICENSE @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, 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 +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If 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 convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU 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 +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "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 PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM 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 PROGRAM (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 PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state 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 program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program 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 General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/nxt-python-fantom/MANIFEST.in b/nxt-python-fantom/MANIFEST.in new file mode 100644 index 0000000..9dd36e1 --- /dev/null +++ b/nxt-python-fantom/MANIFEST.in @@ -0,0 +1,4 @@ +include docs/*.html *.url *.css *.txt +include README LICENSE install.bat MANIFEST.in +include examples/*.py +exclude arduino/* diff --git a/nxt-python-fantom/PKG-INFO b/nxt-python-fantom/PKG-INFO new file mode 100644 index 0000000..1e0e361 --- /dev/null +++ b/nxt-python-fantom/PKG-INFO @@ -0,0 +1,168 @@ +Metadata-Version: 1.0 +Name: nxt-python +Version: 2.1.0 +Summary: LEGO Mindstorms NXT Control Package +Home-page: http://code.google.com/p/nxt-python/ +Author: Marcus Wanner +Author-email: marcusw@cox.net +License: Gnu GPL v3 +Description: NXT-Python is a package for controlling a LEGO NXT robot using the Python + programming language. It can communicate using either USB or Bluetooth. It is + available under the Gnu GPL license. It is based on NXT_Python, where releases + halted in May 2007. + + Requirements: + + * Python 2.6 (http://www.python.org) + And at least one comm library: + * Bluetooth communications: + Linux/Windows: PyBluez (http://code.google.com/p/pybluez/) + (package python-bluez in deb-based linuxes) + Mac: LightBlue (http://lightblue.sourceforge.net/) + * USB communications: + PyUSB (http://sourceforge.net/projects/pyusb/) + + Installation (if using source package): + + * Untar/unzip source package + * In package directory, run "python setup.py install" (as root), or if + under windows, double-click install.bat. + * To use USB on Linux as non-superuser, at a root terminal type: + groupadd lego + usermod -a -G lego [username] + echo 'BUS=="usb", SYSFS{idVendor}=="0694", GROUP="lego", MODE="0660"' \ + > /etc/udev/rules.d/70-lego.rules + + Getting Started: + + Take a look at the examples directory. Feel free to copy that code into your + scripts and don't be afraid to experiment! If you are having trouble with + something, you may find the solution in the docstrings (for example, + help('nxt.sensor.Ultrasonic')) or even in the source code (especially for + digital sensors). + + Notes/FAQ: + (I have tried to put the most important stuff first, but it would be a good + idea to read the whole section. In any case, read it all the way through + before asking for help. Thanks!) + + -=-=-About v2-=-=- + This version is part of the 2.x series of releases. Programs designed for + NXT_Python or for the 1.x series of nxt-python will not work with this version. + If you are trying to get an old program to work, it most likely needs a 1.x + series release, which can be downloaded from the nxt-python downloads page at + googlecode. New projects should use a 2.x series release (hint: this is one!) + due to the new features and API improvements. Converting old projects is + somewhat difficult and not officially supported, though as always you're + welcome to ask for help. + -=-=-Problems and Their Solutions-=-=- + Support for a number of sensors has not been tested at all, due to lack of + hardware. I have started a project to test this code, but the going is slow + and I have decided to go ahead and release rather than waiting several more + months. If you have a problem with a digital sensor, see the troubleshooting + guide below and don't forget to report your trouble! + The Synchronized Motor support has not been extensively tested for accuracy. + It seems to mostly work well but the accuracy of the braking function and the + closeness of the two motors to each other have not been assesed. + NXT-Python has not been tested and may not work with custom nxt firmware + versions (if you don't know what that means, you don't need to worry about it). + However, if the firmware uses the standard USB/BT communications protocol, + everything should more or less work. NXT-Python has been tested with bricks + using LEGO firmware version up to 1.29 and is compatible with protocol version + 1.124 (used by most if not all of the official firmwares). It has also been + reported working with LeJOS. + -=-=-If you co'd the SVN...-=-=- + The Arduino directory of an svn checkout (not included with release + packages) contains a digital sensor unit test system called nxtduemu. It is + intended for developers and advanced users who are looking to experiment with + sensors and the digital sensor framework and classes. See Arduino/README for + more info and usage instructions. + + Specific Stability Status: + nxt.brick, nxt.telegram, nxt.direct, and nxt.system: + Hardly changed since NXT_Python; very, very stable. + USB Communication System (nxt.usbsock) + On Linux: Very stable and extensively tested. + On Windows: Somewhat tested; seems to work pretty well. + On Mac: Should be working, though I have not heard either way. + BlueTooth Communication System (nxt.bluesock, nxt.lightblueglue) + On Linux: Stable; well tested. + On Windows: Stable; working last I checked. + On Mac: Reported working. + nxt.locator: + Stable, somewhat tested. One developer reported problems. + nxt.motor: + Stable except for Synchronized Motor support, which is experimental at + this stage and has not been extensively tested. + nxt.sensor: + Code not specific to a particular sensor is well tested and working + great. More than half of the sensor classes were last reported working; + the rest have not to my knowlege been tested and were written blindly + from the manuacturers' specifications. + nxt.error: + If there's a problem with this one, I'm gonna cry. + + Contact: + + NXT-Python's Head Developer: + Marcus Wanner (marcusw@cox.net) + The support and development mailing list: + http://groups.google.com/group/nxt-python + Report bugs and suggest new features at: + http://code.google.com/p/nxt-python/issues/list + + Thanks to: + + Doug Lau for writing NXT_Python, our starting point. + rhn for creating what would become v2, making lots of smaller changes, and + reviewing tons of code. + mindsensors.com (esp. Ryan Kneip) for helping out with the code for a lot of + their sensors and expanding the sensors covered by the type checking + database. + HiTechnic for providing identification information for their sensors. I note + that they have now included this information in their website. ;) + Linus Atorf, Samuel Leeman-Munk, melducky, Simon Levy, Steve Castellotti, + Paulo Vieira, zonedabone, migpics, and anyone else I forgot for various + fixes and additions. + All our users for their interest and support! + + + + Troubleshooting Digital Sensors (don't read unless you have problems): + If you are getting errors, strange behavor, or incorrect values from a digital + sensor, chances are that there is a bug in our code. Follow these instructions + to try and find out what's wrong: + 1. Test the sensor with a different access library to make sure it's working + right. + 2. Check your code again. There are some weird "features" in the interfaces + of some of the sensors; make sure you are doing things right. + 3. Locate the sensor class's source code in nxt-python. It should be + somewhere in nxt/sensor/.py, under the heading "class SensorName( + BaseDigitalSensor):". Read any comments for instructions on certain things. + + If you get to here and are still having a problem, you can either go ahead and + report it now or continue to try and find and fix the problem and then report + it (or not report it at all, but that wouldn't be very nice...). + Python experience required beyond this point. + + 4. Get the sensor's specifications from the manufacturer's website. Make + sure it includes a table of I2C registers and instructions for using them. + 5. Pick one of the following depending on what the problem is: + ####Errors: + Cause: We screwed up. + Solution: Check the line mentioned in the error for incorrect syntax or + other problem. A bit of python experience and maybe some googling is needed + here. + ####Strange Behavior (in sensors with modes/commands): + Cause: nxt-python's command enumerations are incorrect. + Solution: Verify them using the sensor's specs, and correct any problems. + See "Incorrect Values" for more. + ####Incorrect Values: + Cause: nxt-python is processing the value wrong. + Solution: Check what goes on in the sampling method against what the spec + says should be done. If there is an inconsistency, try to fix it. + Cause: nxt-python has an incorrect register number or type in I2C_ADDRESS. + Solution: Verify the address (the number) and the string (the struct format + string). To verify the address, use the spec. To verify the struct format, you + wil +Platform: UNKNOWN diff --git a/nxt-python-fantom/README b/nxt-python-fantom/README new file mode 100644 index 0000000..5d9a214 --- /dev/null +++ b/nxt-python-fantom/README @@ -0,0 +1,169 @@ +NXT-Python is a package for controlling a LEGO NXT robot using the Python +programming language. It can communicate using either USB or Bluetooth. It is +available under the Gnu GPL license. It is based on NXT_Python, where releases +halted in May 2007. + +Requirements: + + * Python 2.6 (http://www.python.org) + And at least one comm library: + * Bluetooth communications: + Linux/Windows: PyBluez (http://code.google.com/p/pybluez/) + (package python-bluez in deb-based linuxes) + Mac: LightBlue (http://lightblue.sourceforge.net/) + * USB communications: + PyUSB (http://sourceforge.net/projects/pyusb/) + +Installation (if using source package): + + * Untar/unzip source package + * In package directory, run "python setup.py install" (as root), or if + under windows, double-click install.bat. + * To use USB on Linux as non-superuser, at a root terminal type: + groupadd lego + usermod -a -G lego [username] + echo 'BUS=="usb", SYSFS{idVendor}=="0694", GROUP="lego", MODE="0660"' \ + > /etc/udev/rules.d/70-lego.rules + +Getting Started: + + Take a look at the examples directory. Feel free to copy that code into your +scripts and don't be afraid to experiment! If you are having trouble with +something, you may find the solution in the docstrings (for example, +help('nxt.sensor.Ultrasonic')) or even in the source code (especially for +digital sensors). + +Notes/FAQ: + (I have tried to put the most important stuff first, but it would be a good + idea to read the whole section. In any case, read it all the way through + before asking for help. Thanks!) + + -=-=-About v2-=-=- + This version is part of the 2.x series of releases. Programs designed for +NXT_Python or for the 1.x series of nxt-python will not work with this version. +If you are trying to get an old program to work, it most likely needs a 1.x +series release, which can be downloaded from the nxt-python downloads page at +googlecode. New projects should use a 2.x series release (hint: this is one!) +due to the new features and API improvements. Converting old projects is +somewhat difficult and not officially supported, though as always you're +welcome to ask for help. + -=-=-Problems and Their Solutions-=-=- + Support for a number of sensors has not been tested at all, due to lack of +hardware. I have started a project to test this code, but the going is slow +and I have decided to go ahead and release rather than waiting several more +months. If you have a problem with a digital sensor, see the troubleshooting +guide below and don't forget to report your trouble! + The Synchronized Motor support has not been extensively tested for accuracy. +It seems to mostly work well but the accuracy of the braking function and the +closeness of the two motors to each other have not been assesed. + NXT-Python has not been tested and may not work with custom nxt firmware +versions (if you don't know what that means, you don't need to worry about it). +However, if the firmware uses the standard USB/BT communications protocol, +everything should more or less work. NXT-Python has been tested with bricks +using LEGO firmware version up to 1.29 and is compatible with protocol version +1.124 (used by most if not all of the official firmwares). It has also been +reported working with LeJOS. + -=-=-If you co'd the SVN...-=-=- + The Arduino directory of an svn checkout (not included with release +packages) contains a digital sensor unit test system called nxtduemu. It is +intended for developers and advanced users who are looking to experiment with +sensors and the digital sensor framework and classes. See Arduino/README for +more info and usage instructions. + +Specific Stability Status: + nxt.brick, nxt.telegram, nxt.direct, and nxt.system: + Hardly changed since NXT_Python; very, very stable. + USB Communication System (nxt.usbsock) + On Linux: Very stable and extensively tested. + On Windows: Somewhat tested; seems to work pretty well. + On Mac: Should be working, though I have not heard either way. + BlueTooth Communication System (nxt.bluesock, nxt.lightblueglue) + On Linux: Stable; well tested. + On Windows: Stable; working last I checked. + On Mac: Reported working. + nxt.locator: + Stable, somewhat tested. One developer reported problems. + nxt.motor: + Stable except for Synchronized Motor support, which is experimental at + this stage and has not been extensively tested. + nxt.sensor: + Code not specific to a particular sensor is well tested and working + great. More than half of the sensor classes were last reported working; + the rest have not to my knowlege been tested and were written blindly + from the manuacturers' specifications. + nxt.error: + If there's a problem with this one, I'm gonna cry. + +Contact: + + NXT-Python's Head Developer: + Marcus Wanner (marcusw@cox.net) + The support and development mailing list: + http://groups.google.com/group/nxt-python + Report bugs and suggest new features at: + http://code.google.com/p/nxt-python/issues/list + +Thanks to: + + Doug Lau for writing NXT_Python, our starting point. + rhn for creating what would become v2, making lots of smaller changes, and + reviewing tons of code. + mindsensors.com (esp. Ryan Kneip) for helping out with the code for a lot of + their sensors and expanding the sensors covered by the type checking + database. + HiTechnic for providing identification information for their sensors. I note + that they have now included this information in their website. ;) + Linus Atorf, Samuel Leeman-Munk, melducky, Simon Levy, Steve Castellotti, + Paulo Vieira, zonedabone, migpics, and anyone else I forgot for various + fixes and additions. + All our users for their interest and support! + + + +Troubleshooting Digital Sensors (don't read unless you have problems): +If you are getting errors, strange behavor, or incorrect values from a digital +sensor, chances are that there is a bug in our code. Follow these instructions +to try and find out what's wrong: + 1. Test the sensor with a different access library to make sure it's working +right. + 2. Check your code again. There are some weird "features" in the interfaces +of some of the sensors; make sure you are doing things right. + 3. Locate the sensor class's source code in nxt-python. It should be +somewhere in nxt/sensor/.py, under the heading "class SensorName( +BaseDigitalSensor):". Read any comments for instructions on certain things. + +If you get to here and are still having a problem, you can either go ahead and +report it now or continue to try and find and fix the problem and then report +it (or not report it at all, but that wouldn't be very nice...). +Python experience required beyond this point. + + 4. Get the sensor's specifications from the manufacturer's website. Make +sure it includes a table of I2C registers and instructions for using them. + 5. Pick one of the following depending on what the problem is: +####Errors: + Cause: We screwed up. + Solution: Check the line mentioned in the error for incorrect syntax or +other problem. A bit of python experience and maybe some googling is needed +here. +####Strange Behavior (in sensors with modes/commands): + Cause: nxt-python's command enumerations are incorrect. + Solution: Verify them using the sensor's specs, and correct any problems. + See "Incorrect Values" for more. +####Incorrect Values: + Cause: nxt-python is processing the value wrong. + Solution: Check what goes on in the sampling method against what the spec +says should be done. If there is an inconsistency, try to fix it. + Cause: nxt-python has an incorrect register number or type in I2C_ADDRESS. + Solution: Verify the address (the number) and the string (the struct format +string). To verify the address, use the spec. To verify the struct format, you +will need to read this: or have experience with struct. +Read the spec for the sensor to determine how the given value should be read, +then start at the sample method and read through it, checking for problems as +you go. If it seems right, go back to the I2C_ADDRESS chunk (near the top of the +class) and make sure that the correct struct format string is being used. The +most common problem here is values that are off by plus or minus 128 or 32768 +because of an incorrect signed/unsigned setting. This can be fixed by switching +the case (as in upper or lower) of the letter in the string. Other problems +could include the wrong size (B, H, or L) being used, or, in the two latter +ones, the wrong byte order (< or >). As always, common sense required. diff --git a/nxt-python-fantom/examples/alpharex.py b/nxt-python-fantom/examples/alpharex.py new file mode 100644 index 0000000..13c5979 --- /dev/null +++ b/nxt-python-fantom/examples/alpharex.py @@ -0,0 +1,151 @@ +r'''Alpha Rex API + + A high-level, object-oriented programming interface to Lego MINDSTORMS + NXT's "Alpha Rex" model (see [1] for assembling instructions), along with a + small collection of functions demonstrating obvious usage scenarios. + + 1. http://www.active-robots.com/products/mindstorms4schools/building-instructions.shtml +''' + +from time import sleep + +from nxt.brick import Brick +from nxt.locator import find_one_brick +from nxt.motor import Motor, PORT_A, PORT_B, PORT_C +from nxt.sensor import Light, Sound, Touch, Ultrasonic +from nxt.sensor import PORT_1, PORT_2, PORT_3, PORT_4 + + +FORTH = 100 +BACK = -100 + + +class AlphaRex(object): + r'''A high-level controller for the Alpha Rex model. + + This class implements methods for the most obvious actions performable + by Alpha Rex, such as walk, wave its arms, and retrieve sensor samples. + Additionally, it also allows direct access to the robot's components + through public attributes. + ''' + def __init__(self, brick='NXT'): + r'''Creates a new Alpha Rex controller. + + brick + Either an nxt.brick.Brick object, or an NXT brick's name as a + string. If omitted, a Brick named 'NXT' is looked up. + ''' + if isinstance(brick, basestring): + brick = find_one_brick(name=brick) + + self.brick = brick + self.arms = Motor(brick, PORT_A) + self.legs = [Motor(brick, PORT_B), Motor(brick, PORT_C)] + + self.touch = Touch(brick, PORT_1) + self.sound = Sound(brick, PORT_2) + self.light = Light(brick, PORT_3) + self.ultrasonic = Ultrasonic(brick, PORT_4) + + def echolocate(self): + r'''Reads the Ultrasonic sensor's output. + ''' + return self.ultrasonic.get_sample() + + def feel(self): + r'''Reads the Touch sensor's output. + ''' + return self.touch.get_sample() + + def hear(self): + r'''Reads the Sound sensor's output. + ''' + return self.sound.get_sample() + + def say(self, line, times=1): + r'''Plays a sound file named (line + '.rso'), which is expected to be + stored in the brick. The file is played (times) times. + + line + The name of a sound file stored in the brick. + + times + How many times the sound file will be played before this method + returns. + ''' + for i in range(0, times): + self.brick.play_sound_file(False, line + '.rso') + sleep(1) + + def see(self): + r'''Reads the Light sensor's output. + ''' + return self.light.get_sample() + + def walk(self, secs, power=FORTH): + r'''Simultaneously activates the leg motors, causing Alpha Rex to walk. + + secs + How long the motors will rotate. + + power + The strength effected by the motors. Positive values will cause + Alpha Rex to walk forward, while negative values will cause it + to walk backwards. If you are unsure about how much force to + apply, the special values FORTH and BACK provide reasonable + defaults. If omitted, FORTH is used. + ''' + for motor in self.legs: + motor.run(power=power) + + sleep(secs) + + for motor in self.legs: + motor.idle() + + def wave(self, secs, power=100): + r'''Make Alpha Rex move its arms. + + secs + How long the arms' motor will rotate. + + power + The strength effected by the motor. If omitted, (100) is used. + ''' + self.arms.run(power=power) + sleep(secs) + self.arms.idle() + + +def wave_and_talk(): + r'''Connects to a nearby Alpha Rex, then commands it to wave its arms and + play the sound file 'Object.rso'. + ''' + robot = AlphaRex() + robot.wave(1) + robot.say('Object') + + +def walk_forth_and_back(): + r'''Connects to a nearby Alpha Rex, then commands it to walk forward and + then backwards. + ''' + robot = AlphaRex() + robot.walk(10, FORTH) + robot.walk(10, BACK) + + +def walk_to_object(): + r'''Connects to a nearby Alpha Rex, then commands it to walk until it + approaches an obstacle, then stop and say 'Object' three times. + ''' + robot = AlphaRex() + while robot.echolocate() > 10: + robot.walk(1, FORTH) + + robot.say('Object', 3) + + +if __name__ == '__main__': + walk_to_object() + diff --git a/nxt-python-fantom/examples/cnc.py b/nxt-python-fantom/examples/cnc.py new file mode 100644 index 0000000..456cf92 --- /dev/null +++ b/nxt-python-fantom/examples/cnc.py @@ -0,0 +1,53 @@ +#Script to control a NXT 2-axis CNC "Pancake maker" +#Illustrates controlling more than one motor at the same time without trying to +#sync them. Uses the thread module. +#Written 2/3/11 by Marcus Wanner +# +#For more info and warnings see: +#http://groups.google.com/group/nxt-python/browse_thread/thread/f6ef0865ae768ef + +import nxt, thread, time +b = nxt.find_one_brick(name = 'MyNXT') +mx = nxt.Motor(b, nxt.PORT_A) +my = nxt.Motor(b, nxt.PORT_B) +motors = [mx, my] + +def turnmotor(m, power, degrees): + m.turn(power, degrees) + +#here are the instructions... +#the first value is the time to start the instruction +#the second is the axis (0 for x, 1 for y) +#the third is the power +#the fourth is the degrees +#it's probably not a good idea to run simultaneous turn +#functions on a single motor, so be careful with this +instructions = ( + [0, 0, 80, 180], + [0, 1, -40, 1080], + [1, 0, -80, 180], + [2, 0, 80, 180], + [3, 1, 100, 360], + [3, 0, -100, 360], +) +#how long from start until the last instruction is ended +length = 5 + +def runinstruction(i): + motorid, speed, degrees = i + #THIS IS THE IMPORTANT PART! + thread.start_new_thread( + turnmotor, + (motors[motorid], speed, degrees)) + +#main loop +seconds = 0 +while 1: + print "Tick %d" % seconds + for i in instructions: + if i[0] == seconds: + runinstruction(i[1:]) + seconds = seconds + 1 + if seconds >= length: + break + time.sleep(1) diff --git a/nxt-python-fantom/examples/latency.py b/nxt-python-fantom/examples/latency.py new file mode 100644 index 0000000..b4b1f26 --- /dev/null +++ b/nxt-python-fantom/examples/latency.py @@ -0,0 +1,23 @@ +#!/usr/bin/env python + +import time +import nxt.locator +from nxt.sensor import * + +b = nxt.locator.find_one_brick() + +#Touch sensor latency test +touch = Touch(b, PORT_1) +start = time.time() +for i in range(100): + touch.get_sample() +stop = time.time() +print 'touch latency: %s ms' % (1000 * (stop - start) / 100.0) + +#Ultrasonic sensor latency test +ultrasonic = Ultrasonic(b, PORT_4) +start = time.time() +for i in range(100): + ultrasonic.get_sample() +stop = time.time() +print 'ultrasonic latency: %s ms' % (1000 * (stop - start) / 100.0) diff --git a/nxt-python-fantom/examples/mary.py b/nxt-python-fantom/examples/mary.py new file mode 100644 index 0000000..907cc23 --- /dev/null +++ b/nxt-python-fantom/examples/mary.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python +# +# Converted from mary.rb found in ruby_nxt package +# Plays "Mary Had A Little Lamb" +# Author: Christopher Continanza + +from time import sleep +import nxt.locator + +FREQ_C = 523 +FREQ_D = 587 +FREQ_E = 659 +FREQ_G = 784 + +b = nxt.locator.find_one_brick() + +b.play_tone_and_wait(FREQ_E, 500) +b.play_tone_and_wait(FREQ_D, 500) +b.play_tone_and_wait(FREQ_C, 500) +b.play_tone_and_wait(FREQ_D, 500) +b.play_tone_and_wait(FREQ_E, 500) +b.play_tone_and_wait(FREQ_E, 500) +b.play_tone_and_wait(FREQ_E, 500) +sleep(0.5) +b.play_tone_and_wait(FREQ_D, 500) +b.play_tone_and_wait(FREQ_D, 500) +b.play_tone_and_wait(FREQ_D, 500) +sleep(0.5) +b.play_tone_and_wait(FREQ_E, 500) +b.play_tone_and_wait(FREQ_G, 500) +b.play_tone_and_wait(FREQ_G, 500) +sleep(0.5) +b.play_tone_and_wait(FREQ_E, 500) +b.play_tone_and_wait(FREQ_D, 500) +b.play_tone_and_wait(FREQ_C, 500) +b.play_tone_and_wait(FREQ_D, 500) +b.play_tone_and_wait(FREQ_E, 500) +b.play_tone_and_wait(FREQ_E, 500) +b.play_tone_and_wait(FREQ_E, 500) +b.play_tone_and_wait(FREQ_E, 500) +b.play_tone_and_wait(FREQ_D, 500) +b.play_tone_and_wait(FREQ_D, 500) +b.play_tone_and_wait(FREQ_E, 500) +b.play_tone_and_wait(FREQ_D, 500) +b.play_tone_and_wait(FREQ_C, 750) diff --git a/nxt-python-fantom/examples/message_test.py b/nxt-python-fantom/examples/message_test.py new file mode 100644 index 0000000..c2fbda7 --- /dev/null +++ b/nxt-python-fantom/examples/message_test.py @@ -0,0 +1,15 @@ +#!/usr/bin/env python + +#During this test you need to run any program on the brick +#which doesn't use the messaging system. Most programs fit +#this requirement. + +import nxt.locator + +b = nxt.locator.find_one_brick() +for box in range(10): + b.message_write(box, 'message test %d' % box) +for box in range(10): + local_box, message = b.message_read(box, box, True) + print local_box, message +print 'Test succeeded!' diff --git a/nxt-python-fantom/examples/spin.py b/nxt-python-fantom/examples/spin.py new file mode 100644 index 0000000..fc7cb2c --- /dev/null +++ b/nxt-python-fantom/examples/spin.py @@ -0,0 +1,14 @@ +#!/usr/bin/env python + +import nxt.locator +from nxt.motor import * + +def spin_around(b): + m_left = Motor(b, PORT_B) + m_left.turn(100, 360) + m_right = Motor(b, PORT_C) + m_right.turn(-100, 360) + +b = nxt.locator.find_one_brick() +spin_around(b) + diff --git a/nxt-python-fantom/examples/test_sensors.py b/nxt-python-fantom/examples/test_sensors.py new file mode 100644 index 0000000..4c8d249 --- /dev/null +++ b/nxt-python-fantom/examples/test_sensors.py @@ -0,0 +1,11 @@ +#!/usr/bin/env python + +import nxt.locator +from nxt.sensor import * + +b = nxt.locator.find_one_brick() + +print 'Touch:', Touch(b, PORT_1).get_sample() +print 'Sound:', Sound(b, PORT_2).get_sample() +print 'Light:', Light(b, PORT_3).get_sample() +print 'Ultrasonic:', Ultrasonic(b, PORT_4).get_sample() diff --git a/nxt-python-fantom/install.bat b/nxt-python-fantom/install.bat new file mode 100644 index 0000000..afa7bfc --- /dev/null +++ b/nxt-python-fantom/install.bat @@ -0,0 +1,11 @@ +@echo off +@call setup.py install +if errorlevel 1 goto error +goto end +:error +echo -=-=-=-=-=-=-=-=-=-=- +echo There was an error during the installation. +echo Please check the above text for more information. +pause +:end +@echo on diff --git a/nxt-python-fantom/nxt/__init__.py b/nxt-python-fantom/nxt/__init__.py new file mode 100644 index 0000000..01be052 --- /dev/null +++ b/nxt-python-fantom/nxt/__init__.py @@ -0,0 +1,17 @@ +# nxt.__init__ module -- LEGO Mindstorms NXT python package +# Copyright (C) 2006 Douglas P Lau +# Copyright (C) 2009 Marcus Wanner +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This program 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 General Public License for more details. + +from .locator import find_one_brick +from .motor import * +from .sensor import * diff --git a/nxt-python-fantom/nxt/bluesock.py b/nxt-python-fantom/nxt/bluesock.py new file mode 100644 index 0000000..c57894d --- /dev/null +++ b/nxt-python-fantom/nxt/bluesock.py @@ -0,0 +1,78 @@ +# nxt.bluesock module -- Bluetooth socket communication with LEGO Minstorms NXT +# Copyright (C) 2006, 2007 Douglas P Lau +# Copyright (C) 2009 Marcus Wanner +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This program 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 General Public License for more details. + +try: + import bluetooth +except ImportError: + import lightblueglue as bluetooth +import os +from .brick import Brick + +class BlueSock(object): + + bsize = 118 # Bluetooth socket block size + PORT = 1 # Standard NXT rfcomm port + + def __init__(self, host): + self.host = host + self.sock = None + self.debug = False + + def __str__(self): + return 'Bluetooth (%s)' % self.host + + def connect(self): + if self.debug: + print 'Connecting via Bluetooth...' + sock = bluetooth.BluetoothSocket(bluetooth.RFCOMM) + sock.connect((self.host, BlueSock.PORT)) + self.sock = sock + if self.debug: + print 'Connected.' + return Brick(self) + + def close(self): + if self.debug: + print 'Closing Bluetooth connection...' + self.sock.close() + if self.debug: + print 'Bluetooth connection closed.' + + def send(self, data): + if self.debug: + print 'Send:', + print ':'.join('%02x' % ord(c) for c in data) + l0 = len(data) & 0xFF + l1 = (len(data) >> 8) & 0xFF + d = chr(l0) + chr(l1) + data + self.sock.send(d) + + def recv(self): + data = self.sock.recv(2) + l0 = ord(data[0]) + l1 = ord(data[1]) + plen = l0 + (l1 << 8) + data = self.sock.recv(plen) + if self.debug: + print 'Recv:', + print ':'.join('%02x' % ord(c) for c in data) + return data + +def _check_brick(arg, value): + return arg is None or arg == value + +def find_bricks(host=None, name=None): + for h, n in bluetooth.discover_devices(lookup_names=True): + if _check_brick(host, h) and _check_brick(name, n): + yield BlueSock(h) diff --git a/nxt-python-fantom/nxt/brick.py b/nxt-python-fantom/nxt/brick.py new file mode 100644 index 0000000..740ccbd --- /dev/null +++ b/nxt-python-fantom/nxt/brick.py @@ -0,0 +1,225 @@ +# nxt.brick module -- Classes to represent LEGO Mindstorms NXT bricks +# Copyright (C) 2006 Douglas P Lau +# Copyright (C) 2009 Marcus Wanner, rhn +# Copyright (C) 2010 rhn, Marcus Wanner, zonedabone +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This program 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 General Public License for more details. + +from time import sleep +from threading import Lock +from .error import FileNotFound, ModuleNotFound +from .telegram import OPCODES, Telegram +from .sensor import get_sensor + +def _make_poller(opcode, poll_func, parse_func): + def poll(self, *args, **kwargs): + ogram = poll_func(opcode, *args, **kwargs) + with self.lock: + self.sock.send(str(ogram)) + igram = Telegram(opcode=opcode, pkt=self.sock.recv()) + return parse_func(igram) + return poll + +class _Meta(type): + 'Metaclass which adds one method for each telegram opcode' + + def __init__(cls, name, bases, dict): + super(_Meta, cls).__init__(name, bases, dict) + for opcode in OPCODES: + poll_func, parse_func = OPCODES[opcode] + m = _make_poller(opcode, poll_func, parse_func) + setattr(cls, poll_func.__name__, m) + + +class FileFinder(object): + 'A generator to find files on a NXT brick.' + + def __init__(self, brick, pattern): + self.brick = brick + self.pattern = pattern + self.handle = None + + def _close(self): + if self.handle is not None: + self.brick.close(self.handle) + self.handle = None + + def __del__(self): + self._close() + + def __iter__(self): + results = [] + self.handle, fname, size = self.brick.find_first(self.pattern) + results.append((fname, size)) + while True: + try: + handle, fname, size = self.brick.find_next(self.handle) + results.append((fname, size)) + except FileNotFound: + self._close() + break + for result in results: + yield result + + +def File(brick, name, mode='r', size=None): + """Opens a file for reading/writing. Mode is 'r' or 'w'. If mode is 'w', + size must be provided. + """ + if mode == 'w': + if size is not None: + return FileWriter(brick, name, size) + else: + return ValueError('Size not specified') + elif mode == 'r': + return FileReader(brick, name) + else: + return ValueError('Mode ' + str(mode) + ' not supported') + + +class FileReader(object): + """Context manager to read a file on a NXT brick. Do use the iterator or + the read() method, but not both at the same time! + The iterator returns strings of an arbitrary (short) length. + """ + + def __init__(self, brick, fname): + self.brick = brick + self.handle, self.size = brick.open_read(fname) + + def read(self, bytes=None): + if bytes is not None: + remaining = bytes + else: + remaining = self.size + bsize = self.brick.sock.bsize + data = [] + while remaining > 0: + handle, bsize, buffer_ = self.brick.read(self.handle, + min(bsize, remaining)) + remaining -= len(buffer_) + data.append(buffer_) + return ''.join(data) + + def close(self): + if self.handle is not None: + self.brick.close(self.handle) + self.handle = None + + def __del__(self): + self.close() + + def __enter__(self): + return self + + def __exit__(self, etp, value, tb): + self.close() + + def __iter__(self): + rem = self.size + bsize = self.brick.sock.bsize + while rem > 0: + handle, bsize, data = self.brick.read(self.handle, + min(bsize, rem)) + yield data + rem -= len(data) + + +class FileWriter(object): + "Object to write to a file on a NXT brick" + + def __init__(self, brick, fname, size): + self.brick = brick + self.handle = self.brick.open_write(fname, size) + self._position = 0 + self.size = size + + def __del__(self): + self.close() + + def close(self): + if self.handle is not None: + self.brick.close(self.handle) + self.handle = None + + def tell(self): + return self._position + + def write(self, data): + remaining = len(data) + if remaining > self.size - self._position: + raise ValueError('Data will not fit into remaining space') + bsize = self.brick.sock.bsize + data_position = 0 + + while remaining > 0: + batch_size = min(bsize, remaining) + next_data_position = data_position + batch_size + buffer_ = data[data_position:next_data_position] + + handle, size = self.brick.write(self.handle, buffer_) + + self._position += batch_size + data_position = next_data_position + remaining -= batch_size + + +class ModuleFinder(object): + 'Iterator to lookup modules on a NXT brick' + + def __init__(self, brick, pattern): + self.brick = brick + self.pattern = pattern + self.handle = None + + def _close(self): + if self.handle: + self.brick.close(self.handle) + self.handle = None + + def __del__(self): + self._close() + + def __iter__(self): + self.handle, mname, mid, msize, miomap_size = \ + self.brick.request_first_module(self.pattern) + yield (mname, mid, msize, miomap_size) + while True: + try: + handle, mname, mid, msize, miomap_size = \ + self.brick.request_next_module( + self.handle) + yield (mname, mid, msize, miomap_size) + except ModuleNotFound: + self._close() + break + + +class Brick(object): #TODO: this begs to have explicit methods + 'Main object for NXT Control' + + __metaclass__ = _Meta + + def __init__(self, sock): + self.sock = sock + self.lock = Lock() + + def play_tone_and_wait(self, frequency, duration): + self.play_tone(frequency, duration) + sleep(duration / 1000.0) + + def __del__(self): + self.sock.close() + + find_files = FileFinder + find_modules = ModuleFinder + open_file = File + get_sensor = get_sensor diff --git a/nxt-python-fantom/nxt/direct.py b/nxt-python-fantom/nxt/direct.py new file mode 100644 index 0000000..50b7f2a --- /dev/null +++ b/nxt-python-fantom/nxt/direct.py @@ -0,0 +1,216 @@ +# nxt.direct module -- LEGO Mindstorms NXT direct telegrams +# Copyright (C) 2006, 2007 Douglas P Lau +# Copyright (C) 2009 Marcus Wanner +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This program 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 General Public License for more details. + +'Use for direct communication with the NXT ***EXTREMELY ADVANCED USERS ONLY***' + +def _create(opcode): + 'Create a simple direct telegram' + from telegram import Telegram + return Telegram(True, opcode) + +def start_program(opcode, fname): + tgram = _create(opcode) + tgram.add_filename(fname) + return tgram + +def _parse_simple(tgram): + tgram.check_status() + +def stop_program(opcode): + return _create(opcode) + +def play_sound_file(opcode, loop, fname): + tgram = _create(opcode) + tgram.add_u8(loop) + tgram.add_filename(fname) + return tgram + +def play_tone(opcode, frequency, duration): + 'Play a tone at frequency (Hz) for duration (ms)' + tgram = _create(opcode) + tgram.add_u16(frequency) + tgram.add_u16(duration) + return tgram + +def set_output_state(opcode, port, power, mode, regulation, turn_ratio, + run_state, tacho_limit): + tgram = _create(opcode) + tgram.add_u8(port) + tgram.add_s8(power) + tgram.add_u8(mode) + tgram.add_u8(regulation) + tgram.add_s8(turn_ratio) + tgram.add_u8(run_state) + tgram.add_u32(tacho_limit) + return tgram + +def set_input_mode(opcode, port, sensor_type, sensor_mode): + tgram = _create(opcode) + tgram.add_u8(port) + tgram.add_u8(sensor_type) + tgram.add_u8(sensor_mode) + return tgram + +def get_output_state(opcode, port): + tgram = _create(opcode) + tgram.add_u8(port) + return tgram + +def _parse_get_output_state(tgram): + tgram.check_status() + port = tgram.parse_u8() + power = tgram.parse_s8() + mode = tgram.parse_u8() + regulation = tgram.parse_u8() + turn_ratio = tgram.parse_s8() + run_state = tgram.parse_u8() + tacho_limit = tgram.parse_u32() + tacho_count = tgram.parse_s32() + block_tacho_count = tgram.parse_s32() + rotation_count = tgram.parse_s32() + return (port, power, mode, regulation, turn_ratio, run_state, + tacho_limit, tacho_count, block_tacho_count, rotation_count) + +def get_input_values(opcode, port): + tgram = _create(opcode) + tgram.add_u8(port) + return tgram + +def _parse_get_input_values(tgram): + tgram.check_status() + port = tgram.parse_u8() + valid = tgram.parse_u8() + calibrated = tgram.parse_u8() + sensor_type = tgram.parse_u8() + sensor_mode = tgram.parse_u8() + raw_ad_value = tgram.parse_u16() + normalized_ad_value = tgram.parse_u16() + scaled_value = tgram.parse_s16() + calibrated_value = tgram.parse_s16() + return (port, valid, calibrated, sensor_type, sensor_mode, raw_ad_value, + normalized_ad_value, scaled_value, calibrated_value) + +def reset_input_scaled_value(opcode, port): + tgram = _create(opcode) + tgram.add_u8(port) + return tgram + +def message_write(opcode, inbox, message): + tgram = _create(opcode) + tgram.add_u8(inbox) + tgram.add_u8(len(message) + 1) + tgram.add_string(len(message), message) + tgram.add_u8(0) + return tgram + +def reset_motor_position(opcode, port, relative): + tgram = _create(opcode) + tgram.add_u8(port) + tgram.add_u8(relative) + return tgram + +def get_battery_level(opcode): + return _create(opcode) + +def _parse_get_battery_level(tgram): + tgram.check_status() + millivolts = tgram.parse_u16() + return millivolts + +def stop_sound_playback(opcode): + return _create(opcode) + +def keep_alive(opcode): + return _create(opcode) + +def _parse_keep_alive(tgram): + tgram.check_status() + sleep_time = tgram.parse_u32() + return sleep_time + +def ls_get_status(opcode, port): + 'Get status of low-speed sensor (ultrasonic)' + tgram = _create(opcode) + tgram.add_u8(port) + return tgram + +def _parse_ls_get_status(tgram): + tgram.check_status() + n_bytes = tgram.parse_u8() + return n_bytes + +def ls_write(opcode, port, tx_data, rx_bytes): + 'Write a low-speed command to a sensor (ultrasonic)' + tgram = _create(opcode) + tgram.add_u8(port) + tgram.add_u8(len(tx_data)) + tgram.add_u8(rx_bytes) + tgram.add_string(len(tx_data), tx_data) + return tgram + +def ls_read(opcode, port): + 'Read a low-speed sensor value (ultrasonic)' + tgram = _create(opcode) + tgram.add_u8(port) + return tgram + +def _parse_ls_read(tgram): + tgram.check_status() + n_bytes = tgram.parse_u8() + contents = tgram.parse_string() + return contents[:n_bytes] + +def get_current_program_name(opcode): + return _create(opcode) + +def _parse_get_current_program_name(tgram): + tgram.check_status() + fname = tgram.parse_string() + return fname + +def message_read(opcode, remote_inbox, local_inbox, remove): + tgram = _create(opcode) + tgram.add_u8(remote_inbox) + tgram.add_u8(local_inbox) + tgram.add_u8(remove) + return tgram + +def _parse_message_read(tgram): + tgram.check_status() + local_inbox = tgram.parse_u8() + n_bytes = tgram.parse_u8() + message = tgram.parse_string() + return (local_inbox, message[:n_bytes]) + +OPCODES = { + 0x00: (start_program, _parse_simple), + 0x01: (stop_program, _parse_simple), + 0x02: (play_sound_file, _parse_simple), + 0x03: (play_tone, _parse_simple), + 0x04: (set_output_state, _parse_simple), + 0x05: (set_input_mode, _parse_simple), + 0x06: (get_output_state, _parse_get_output_state), + 0x07: (get_input_values, _parse_get_input_values), + 0x08: (reset_input_scaled_value, _parse_simple), + 0x09: (message_write, _parse_simple), + 0x0A: (reset_motor_position, _parse_simple), + 0x0B: (get_battery_level, _parse_get_battery_level), + 0x0C: (stop_sound_playback, _parse_simple), + 0x0D: (keep_alive, _parse_keep_alive), + 0x0E: (ls_get_status, _parse_ls_get_status), + 0x0F: (ls_write, _parse_simple), + 0x10: (ls_read, _parse_ls_read), + 0x11: (get_current_program_name, _parse_get_current_program_name), + 0x13: (message_read, _parse_message_read), +} diff --git a/nxt-python-fantom/nxt/error.py b/nxt-python-fantom/nxt/error.py new file mode 100644 index 0000000..3d14497 --- /dev/null +++ b/nxt-python-fantom/nxt/error.py @@ -0,0 +1,87 @@ +# nxt.error module -- LEGO Mindstorms NXT error handling +# Copyright (C) 2006, 2007 Douglas P Lau +# Copyright (C) 2009 Marcus Wanner +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This program 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 General Public License for more details. + +'Declarations for the errors' + +class ProtocolError(Exception): + pass + +class SysProtError(ProtocolError): + pass + +class FileExistsError(SysProtError): + pass + +class FileNotFound(SysProtError): + pass + +class ModuleNotFound(SysProtError): + pass + +class DirProtError(ProtocolError): + pass + +class I2CError(DirProtError): + pass + +class I2CPendingError(I2CError): + pass + +CODES = { + 0x00: None, + 0x20: I2CPendingError('Pending communication transaction in progress'), + 0x40: DirProtError('Specified mailbox queue is empty'), + 0x81: SysProtError('No more handles'), + 0x82: SysProtError('No space'), + 0x83: SysProtError('No more files'), + 0x84: SysProtError('End of file expected'), + 0x85: SysProtError('End of file'), + 0x86: SysProtError('Not a linear file'), + 0x87: FileNotFound('File not found'), + 0x88: SysProtError('Handle already closed'), + 0x89: SysProtError('No linear space'), + 0x8A: SysProtError('Undefined error'), + 0x8B: SysProtError('File is busy'), + 0x8C: SysProtError('No write buffers'), + 0x8D: SysProtError('Append not possible'), + 0x8E: SysProtError('File is full'), + 0x8F: FileExistsError('File exists'), + 0x90: ModuleNotFound('Module not found'), + 0x91: SysProtError('Out of bounds'), + 0x92: SysProtError('Illegal file name'), + 0x93: SysProtError('Illegal handle'), + 0xBD: DirProtError('Request failed (i.e. specified file not found)'), + 0xBE: DirProtError('Unknown command opcode'), + 0xBF: DirProtError('Insane packet'), + 0xC0: DirProtError('Data contains out-of-range values'), + 0xDD: DirProtError('Communication bus error'), + 0xDE: DirProtError('No free memory in communication buffer'), + 0xDF: DirProtError('Specified channel/connection is not valid'), + 0xE0: I2CError('Specified channel/connection not configured or busy'), + 0xEC: DirProtError('No active program'), + 0xED: DirProtError('Illegal size specified'), + 0xEE: DirProtError('Illegal mailbox queue ID specified'), + 0xEF: DirProtError('Attempted to access invalid field of a structure'), + 0xF0: DirProtError('Bad input or output specified'), + 0xFB: DirProtError('Insufficient memory available'), + 0xFF: DirProtError('Bad arguments'), +} + +def check_status(status): + if status: + ex = CODES.get(status) + if ex: + raise ex + else: + raise ProtocolError, status diff --git a/nxt-python-fantom/nxt/lightblueglue.py b/nxt-python-fantom/nxt/lightblueglue.py new file mode 100644 index 0000000..f2ab92f --- /dev/null +++ b/nxt-python-fantom/nxt/lightblueglue.py @@ -0,0 +1,53 @@ +# bluetooth.py module -- Glue code from NXT_Python to Lightblue, allowing +# NXT_Python to run on Mac without modification. Supports subset of +# PyBluez/bluetooth.py used by NXT_Python. +# +# Copyright (C) 2007 Simon D. Levy +# +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 3 of the License, or +# (at your option) any later version. +# +# This program 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 General Public License for more details. + +import lightblue + +RFCOMM=11 + +def discover_devices(lookup_names=False): # parameter is ignored + pairs = [] + d = lightblue.finddevices() + for p in d: + h = p[0] + n = p[1] + pairs.append((h, n)) + return pairs + +class BluetoothSocket: + + def __init__(self, proto = RFCOMM, _sock=None): + if _sock is None: + _sock = lightblue.socket(proto) + self._sock = _sock + self._proto = proto + + def connect(self, addrport): + addr, port = addrport + self._sock.connect( (addr, port )) + + def send(self, data): + return self._sock.send( data ) + + def recv(self, numbytes): + return self._sock.recv( numbytes ) + + def close(self): + return self._sock.close() + +class BluetoothError(IOError): + pass + diff --git a/nxt-python-fantom/nxt/locator.py b/nxt-python-fantom/nxt/locator.py new file mode 100644 index 0000000..4adc680 --- /dev/null +++ b/nxt-python-fantom/nxt/locator.py @@ -0,0 +1,57 @@ +# nxt.locator module -- Locate LEGO Minstorms NXT bricks via USB or Bluetooth +# Copyright (C) 2006, 2007 Douglas P Lau +# Copyright (C) 2009 Marcus Wanner +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This program 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 General Public License for more details. + +class BrickNotFoundError(Exception): + pass + +class NoBackendError(Exception): + pass + +def find_bricks(host=None, name=None, silent=False): + """Used by find_one_brick to look for bricks ***ADVANCED USERS ONLY***""" + + try: + import usbsock + usb_available = True + socks = usbsock.find_bricks(host, name) + for s in socks: + yield s + except ImportError: + usb_available = False + import sys + if not silent: print >>sys.stderr, "USB module unavailable, not searching there" + + try: + import bluesock + try: + socks = bluesock.find_bricks(host, name) + for s in socks: + yield s + except (bluesock.bluetooth.BluetoothError, IOError): #for cases such as no adapter, bluetooth throws IOError, not BluetoothError + pass + except ImportError: + import sys + if not silent: print >>sys.stderr, "Bluetooth module unavailable, not searching there" + if not usb_available: + raise NoBackendError("Neither USB nor Bluetooth could be used! Did you install PyUSB or PyBluez?") + + +def find_one_brick(host=None, name=None, silent=False): + """Use to find one brick. After it returns a usbsock object or a bluesock +object, it automatically connects to it. The host and name args limit +the search to a given MAC or brick name. Set silent to True to stop +nxt-python from printing anything during the search.""" + for s in find_bricks(host, name, silent): + return s.connect() + raise BrickNotFoundError diff --git a/nxt-python-fantom/nxt/motor.py b/nxt-python-fantom/nxt/motor.py new file mode 100644 index 0000000..f29a5a5 --- /dev/null +++ b/nxt-python-fantom/nxt/motor.py @@ -0,0 +1,431 @@ +# nxt.motor module -- Class to control LEGO Mindstorms NXT motors +# Copyright (C) 2006 Douglas P Lau +# Copyright (C) 2009 Marcus Wanner, rhn +# Copyright (C) 2010 rhn +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This program 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 General Public License for more details. + +"""Use for motor control""" + +import time +import warnings + +PORT_A = 0x00 +PORT_B = 0x01 +PORT_C = 0x02 +PORT_ALL = 0xFF + +MODE_IDLE = 0x00 +MODE_MOTOR_ON = 0x01 +MODE_BRAKE = 0x02 +MODE_REGULATED = 0x04 + +REGULATION_IDLE = 0x00 +REGULATION_MOTOR_SPEED = 0x01 +REGULATION_MOTOR_SYNC = 0x02 + +RUN_STATE_IDLE = 0x00 +RUN_STATE_RAMP_UP = 0x10 +RUN_STATE_RUNNING = 0x20 +RUN_STATE_RAMP_DOWN = 0x40 + +LIMIT_RUN_FOREVER = 0 + +class BlockedException(Exception): + pass + +class OutputState(object): + """An object holding the internal state of a motor, not including rotation + counters. + """ + def __init__(self, values): + (self.power, self.mode, self.regulation, + self.turn_ratio, self.run_state, self.tacho_limit) = values + + def to_list(self): + """Returns a list of properties that can be used with set_output_state. + """ + return [self.power, self.mode, self.regulation, + self.turn_ratio, self.run_state, self.tacho_limit] + + def __str__(self): + modes = [] + if self.mode & MODE_MOTOR_ON: + modes.append('on') + if self.mode & MODE_BRAKE: + modes.append('brake') + if self.mode & MODE_REGULATED: + modes.append('regulated') + if not modes: + modes.append('idle') + mode = '&'.join(modes) + regulation = 'regulation: ' + \ + ['idle', 'speed', 'sync'][self.regulation] + run_state = 'run state: ' + {0: 'idle', 0x10: 'ramp_up', + 0x20: 'running', 0x40: 'ramp_down'}[self.run_state] + return ', '.join([mode, regulation, str(self.turn_ratio), run_state] + [str(self.tacho_limit)]) + + +class TachoInfo: + """An object containing the information about the rotation of a motor""" + def __init__(self, values): + self.tacho_count, self.block_tacho_count, self.rotation_count = values + + def get_target(self, tacho_limit, direction): + """Returns a TachoInfo object which corresponds to tacho state after + moving for tacho_limit ticks. Direction can be 1 (add) or -1 (subtract) + """ + # TODO: adjust other fields + if abs(direction) != 1: + raise ValueError('Invalid direction') + new_tacho = self.tacho_count + direction * tacho_limit + return TachoInfo([new_tacho, None, None]) + + def is_greater(self, target, direction): + return direction * (self.tacho_count - target.tacho_count) > 0 + + def is_near(self, target, threshold): + difference = abs(target.tacho_count - self.tacho_count) + return difference < threshold + + def __str__(self): + return str((self.tacho_count, self.block_tacho_count, + self.rotation_count)) + + +class SynchronizedTacho(object): + def __init__(self, leader_tacho, follower_tacho): + self.leader_tacho = leader_tacho + self.follower_tacho = follower_tacho + + def get_target(self, tacho_limit, direction): + """This method will leave follower's target as None""" + leader_tacho = self.leader_tacho.get_target(tacho_limit, direction) + return SynchronizedTacho(leader_tacho, None) + + def is_greater(self, other, direction): + return self.leader_tacho.is_greater(other.leader_tacho, direction) + + def is_near(self, other, threshold): + return self.leader_tacho.is_near(other.leader_tacho, threshold) + + def __str__(self): + if self.follower_tacho is not None: + t2 = str(self.follower_tacho.tacho_count) + else: + t2 = 'None' + t1 = str(self.leader_tacho.tacho_count) + return 'tacho: ' + t1 + ' ' + t2 + + +def get_tacho_and_state(values): + """A convenience function. values is the list of values from + get_output_state. Returns both OutputState and TachoInfo. + """ + return OutputState(values[1:7]), TachoInfo(values[7:]) + + +class BaseMotor(object): + """Base class for motors""" + debug = 0 + def _debug_out(self, message): + if self.debug: + print message + + def turn(self, power, tacho_units, brake=True, timeout=1, emulate=True): + """Use this to turn a motor. The motor will not stop until it turns the + desired distance. Accuracy is much better over a USB connection than + with bluetooth... + power is a value between -127 and 128 (an absolute value greater than + 64 is recommended) + tacho_units is the number of degrees to turn the motor. values smaller + than 50 are not recommended and may have strange results. + brake is whether or not to hold the motor after the function exits + (either by reaching the distance or throwing an exception). + timeout is the number of seconds after which a BlockedException is + raised if the motor doesn't turn + emulate is a boolean value. If set to False, the motor is aware of the + tacho limit. If True, a run() function equivalent is used. + Warning: motors remember their positions and not using emulate + may lead to strange behavior, especially with synced motors + """ + + tacho_limit = tacho_units + + if tacho_limit < 0: + raise ValueError, "tacho_units must be greater than 0!" + + if self.method == 'bluetooth': + threshold = 70 + elif self.method == 'usb': + threshold = 5 + else: + threshold = 30 #compromise + + tacho = self.get_tacho() + state = self._get_new_state() + + # Update modifiers even if they aren't used, might have been changed + state.power = power + if not emulate: + state.tacho_limit = tacho_limit + + self._debug_out('Updating motor information...') + self._set_state(state) + + direction = 1 if power > 0 else -1 + self._debug_out('tachocount: ' + str(tacho)) + current_time = time.time() + tacho_target = tacho.get_target(tacho_limit, direction) + + blocked = False + try: + while True: + time.sleep(self._eta(tacho, tacho_target, power) / 2) + + if not blocked: # if still blocked, don't reset the counter + last_tacho = tacho + last_time = current_time + + tacho = self.get_tacho() + current_time = time.time() + blocked = self._is_blocked(tacho, last_tacho, direction) + if blocked: + self._debug_out(('not advancing', last_tacho, tacho)) + # the motor can be up to 80+ degrees in either direction from target when using bluetooth + if current_time - last_time > timeout: + if tacho.is_near(tacho_target, threshold): + break + else: + raise BlockedException("Blocked!") + else: + self._debug_out(('advancing', last_tacho, tacho)) + if tacho.is_near(tacho_target, threshold) or tacho.is_greater(tacho_target, direction): + break + finally: + if brake: + self.brake() + else: + self.idle() + + +class Motor(BaseMotor): + def __init__(self, brick, port): + self.brick = brick + self.port = port + self._read_state() + self.sync = 0 + self.turn_ratio = 0 + if str(type(self.brick.sock)) == "": + self.method = 'bluetooth' + elif str(type(self.brick.sock)) == "": + self.method = 'usb' + else: + print "Warning: Socket object does not of a known type." + print "The name is: " + str(type(self.brick.sock)) + print "Please report this problem to the developers!" + print "For now, turn() accuracy will not be optimal." + print "Continuing happily..." + self.method = None + + def _set_state(self, state): + self._debug_out('Setting brick output state...') + list_state = [self.port] + state.to_list() + self.brick.set_output_state(*list_state) + self._debug_out(state) + self._state = state + self._debug_out('State set.') + + def _read_state(self): + self._debug_out('Getting brick output state...') + values = self.brick.get_output_state(self.port) + self._debug_out('State got.') + self._state, tacho = get_tacho_and_state(values) + return self._state, tacho + + #def get_tacho_and_state here would allow tacho manipulation + + def _get_state(self): + """Returns a copy of the current motor state for manipulation.""" + return OutputState(self._state.to_list()) + + def _get_new_state(self): + state = self._get_state() + if self.sync: + state.mode = MODE_MOTOR_ON | MODE_REGULATED + state.regulation = REGULATION_MOTOR_SYNC + state.turn_ratio = self.turn_ratio + else: + state.mode = MODE_MOTOR_ON | MODE_REGULATED + state.regulation = REGULATION_MOTOR_SPEED + state.run_state = RUN_STATE_RUNNING + state.tacho_limit = LIMIT_RUN_FOREVER + return state + + def get_tacho(self): + return self._read_state()[1] + + def reset_position(self, relative): + """Resets the counters. Relative can be True or False""" + self.brick.reset_motor_position(self.port, relative) + + def run(self, power=100, regulated=False): + '''Tells the motor to run continuously. If regulated is True, then the + synchronization starts working. + ''' + state = self._get_new_state() + state.power = power + if not regulated: + state.mode = MODE_MOTOR_ON + self._set_state(state) + + def brake(self): + """Holds the motor in place""" + state = self._get_new_state() + state.power = 0 + state.mode = MODE_MOTOR_ON | MODE_BRAKE | MODE_REGULATED + self._set_state(state) + + def idle(self): + '''Tells the motor to stop whatever it's doing. It also desyncs it''' + state = self._get_new_state() + state.power = 0 + state.mode = MODE_IDLE + state.regulation = REGULATION_IDLE + state.run_state = RUN_STATE_IDLE + self._set_state(state) + + def weak_turn(self, power, tacho_units): + """Tries to turn a motor for the specified distance. This function + returns immediately, and it's not guaranteed that the motor turns that + distance. This is an interface to use tacho_limit without + REGULATION_MODE_SPEED + """ + tacho_limit = tacho_units + tacho = self.get_tacho() + state = self._get_new_state() + + # Update modifiers even if they aren't used, might have been changed + state.mode = MODE_MOTOR_ON + state.regulation = REGULATION_IDLE + state.power = power + state.tacho_limit = tacho_limit + + self._debug_out('Updating motor information...') + self._set_state(state) + + def _eta(self, current, target, power): + """Returns time in seconds. Do not trust it too much""" + tacho = abs(current.tacho_count - target.tacho_count) + return (float(tacho) / abs(power)) / 5 + + def _is_blocked(self, tacho, last_tacho, direction): + """Returns if any of the engines is blocked""" + return direction * (last_tacho.tacho_count - tacho.tacho_count) >= 0 + + +class SynchronizedMotors(BaseMotor): + """The object used to make two motors run in sync. Many objects may be + present at the same time but they can't be used at the same time. + Warning! Movement methods reset tacho counter. + THIS CODE IS EXPERIMENTAL!!! + """ + def __init__(self, leader, follower, turn_ratio): + """Turn ratio can be >= 0 only! If you want to have it reversed, + change motor order. + """ + if follower.brick != leader.brick: + raise ValueError('motors belong to different bricks') + self.leader = leader + self.follower = follower + self.method = self.leader.method #being from the same brick, they both have the same com method. + + if turn_ratio < 0: + raise ValueError('Turn ratio <0. Change motor order instead!') + + if self.leader.port == self.follower.port: + raise ValueError("The same motor passed twice") + elif self.leader.port > self.follower.port: + self.turn_ratio = turn_ratio + else: + self._debug_out('reversed') + self.turn_ratio = -turn_ratio + + def _get_new_state(self): + return self.leader._get_new_state() + + def _set_state(self, state): + self.leader._set_state(state) + self.follower._set_state(state) + + def get_tacho(self): + leadertacho = self.leader.get_tacho() + followertacho = self.follower.get_tacho() + return SynchronizedTacho(leadertacho, followertacho) + + def reset_position(self, relative): + """Resets the counters. Relative can be True or False""" + self.leader.reset_position(relative) + self.follower.reset_position(relative) + + def _enable(self): # This works as expected. I'm not sure why. + #self._disable() + self.reset_position(True) + self.leader.sync = True + self.follower.sync = True + self.leader.turn_ratio = self.turn_ratio + self.follower.turn_ratio = self.turn_ratio + + def _disable(self): # This works as expected. (tacho is reset ok) + self.leader.sync = False + self.follower.sync = False + #self.reset_position(True) + self.leader.idle() + self.follower.idle() + #self.reset_position(True) + + def run(self, power=100): + """Warning! After calling this method, make sure to call idle. The + motors are reported to behave wildly otherwise. + """ + self._enable() + self.leader.run(power, True) + self.follower.run(power, True) + + def brake(self): + self._disable() # reset the counters + self._enable() + self.leader.brake() # brake both motors at the same time + self.follower.brake() + self._disable() # now brake as usual + self.leader.brake() + self.follower.brake() + + def idle(self): + self._disable() + + def turn(self, power, tacho_units, brake=True, timeout=1): + self._enable() + # non-emulation is a nightmare, tacho is being counted differently + try: + if power < 0: + self.leader, self.follower = self.follower, self.leader + BaseMotor.turn(self, power, tacho_units, brake, timeout, emulate=True) + finally: + if power < 0: + self.leader, self.follower = self.follower, self.leader + + def _eta(self, tacho, target, power): + return self.leader._eta(tacho.leader_tacho, target.leader_tacho, power) + + def _is_blocked(self, tacho, last_tacho, direction): + # no need to check both, they're synced + return self.leader._is_blocked(tacho.leader_tacho, last_tacho.leader_tacho, direction) diff --git a/nxt-python-fantom/nxt/sensor/__init__.py b/nxt-python-fantom/nxt/sensor/__init__.py new file mode 100644 index 0000000..8f2a337 --- /dev/null +++ b/nxt-python-fantom/nxt/sensor/__init__.py @@ -0,0 +1,50 @@ +# nxt.sensor module -- Classes to read LEGO Mindstorms NXT sensors +# Copyright (C) 2006,2007 Douglas P Lau +# Copyright (C) 2009 Marcus Wanner, Paulo Vieira, rhn +# Copyright (C) 2010 Marcus Wanner +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This program 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 General Public License for more details. + +from .common import * +from .analog import BaseAnalogSensor +from .digital import BaseDigitalSensor, find_class +from .generic import Touch, Light, Sound, Ultrasonic, Color20 +import mindsensors +MSSumoEyes = mindsensors.SumoEyes +MSCompassv2 = mindsensors.Compassv2 +MSDIST = mindsensors.DIST +MSRTC = mindsensors.RTC +MSACCL = mindsensors.ACCL +MSServo = mindsensors.Servo +MSMTRMUX = mindsensors.MTRMUX +MSLineLeader = mindsensors.LineLeader +MSMMX = mindsensors.MMX +MSPS2 = mindsensors.PS2 +MSHID = mindsensors.HID +import hitechnic +HTCompass = hitechnic.Compass +HTAccelerometer = hitechnic.Accelerometer +HTGyro = hitechnic.Gyro +HTColorv2 = hitechnic.Colorv2 +HTEOPD = hitechnic.EOPD +HTIRReceiver = hitechnic.IRReceiver +HTIRSeekerv2 = hitechnic.IRSeekerv2 +HTPrototype = hitechnic.Prototype + + +def get_sensor(brick, port): + """Tries to detect the sensor type and return the correct sensor +object. Does not work for sensors with no identification information (such as +all analog sensors or the MindSensors RTC. + """ + base_sensor = BaseDigitalSensor(brick, port, False) + info = base_sensor.get_sensor_info() + return find_class(info)(brick, port, check_compatible=False) diff --git a/nxt-python-fantom/nxt/sensor/analog.py b/nxt-python-fantom/nxt/sensor/analog.py new file mode 100644 index 0000000..e8d9b7b --- /dev/null +++ b/nxt-python-fantom/nxt/sensor/analog.py @@ -0,0 +1,41 @@ +# nxt.sensor.analog module -- submodule for use with analog sensors +# Copyright (C) 2006,2007 Douglas P Lau +# Copyright (C) 2009 Marcus Wanner, Paulo Vieira, rhn +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This program 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 General Public License for more details. + +from common import * + + +class RawReading: # can be converted to the old version + """A pseudo-structure holding the raw sensor values as returned by the NXT + brick. + """ + def __init__(self, values): + (self.port, self.valid, self.calibrated, self.sensor_type, self.mode, + self.raw_ad_value, self.normalized_ad_value, self.scaled_value, + self.calibrated_value) = values + + def __repr__(self): + return str((self.port, self.valid, self.calibrated, self.sensor_type, self.mode, + self.raw_ad_value, self.normalized_ad_value, self.scaled_value, + self.calibrated_value)) + + +class BaseAnalogSensor(Sensor): + """Object for analog sensors.""" + def get_input_values(self): + """Returns the raw sensor values as returned by the NXT brick.""" + return RawReading(self.brick.get_input_values(self.port)) + + def reset_input_scaled_value(self): + self.brick.reset_input_scaled_value() + diff --git a/nxt-python-fantom/nxt/sensor/common.py b/nxt-python-fantom/nxt/sensor/common.py new file mode 100644 index 0000000..5afd6c8 --- /dev/null +++ b/nxt-python-fantom/nxt/sensor/common.py @@ -0,0 +1,67 @@ +# nxt.sensor.common module -- submodule with stuff useful in all sensors +# Copyright (C) 2006,2007 Douglas P Lau +# Copyright (C) 2009 Marcus Wanner, Paulo Vieira, rhn +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This program 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 General Public License for more details. + +PORT_1 = 0x00 +PORT_2 = 0x01 +PORT_3 = 0x02 +PORT_4 = 0x03 + +class Type(object): + 'Namespace for enumeration of the type of sensor' + # NOTE: just a namespace (enumeration) + NO_SENSOR = 0x00 + SWITCH = 0x01 # Touch sensor + TEMPERATURE = 0x02 + REFLECTION = 0x03 + ANGLE = 0x04 + LIGHT_ACTIVE = 0x05 # Light sensor (illuminated) + LIGHT_INACTIVE = 0x06 # Light sensor (ambient) + SOUND_DB = 0x07 # Sound sensor (unadjusted) + SOUND_DBA = 0x08 # Sound sensor (adjusted) + CUSTOM = 0x09 + LOW_SPEED = 0x0A + LOW_SPEED_9V = 0x0B # Low-speed I2C (Ultrasonic sensor) + HIGH_SPEED = 0x0C #Possibly other mode for I2C; may be used by future sensors. + COLORFULL = 0x0D #NXT 2.0 color sensor in full color mode (color sensor mode) + COLORRED = 0x0E #NXT 2.0 color sensor with red light on (light sensor mode) + COLORGREEN = 0x0F #NXT 2.0 color sensor with green light on (light sensor mode) + COLORBLUE = 0x10 #NXT 2.0 color sensor in with blue light on (light sensor mode) + COLORNONE = 0x11 #NXT 2.0 color sensor in with light off (light sensor mode) + COLOREXIT = 0x12 #NXT 2.0 color sensor internal state (not sure what this is for yet) + + +class Mode(object): + 'Namespace for enumeration of the mode of sensor' + # NOTE: just a namespace (enumeration) + RAW = 0x00 + BOOLEAN = 0x20 + TRANSITION_CNT = 0x40 + PERIOD_COUNTER = 0x60 + PCT_FULL_SCALE = 0x80 + CELSIUS = 0xA0 + FAHRENHEIT = 0xC0 + ANGLE_STEPS = 0xE0 + MASK = 0xE0 + MASK_SLOPE = 0x1F # Why isn't this slope thing documented? + + +class Sensor(object): + 'Main sensor object' + + def __init__(self, brick, port): + self.brick = brick + self.port = port + + def set_input_mode(self, type_, mode): + self.brick.set_input_mode(self.port, type_, mode) diff --git a/nxt-python-fantom/nxt/sensor/digital.py b/nxt-python-fantom/nxt/sensor/digital.py new file mode 100644 index 0000000..dbc730f --- /dev/null +++ b/nxt-python-fantom/nxt/sensor/digital.py @@ -0,0 +1,227 @@ +# nxt.sensor module -- Classes to read LEGO Mindstorms NXT sensors +# Copyright (C) 2006,2007 Douglas P Lau +# Copyright (C) 2009 Marcus Wanner, Paulo Vieira, rhn +# Copyright (C) 2010,2011 Marcus Wanner +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This program 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 General Public License for more details. + +from nxt.error import I2CError, I2CPendingError, DirProtError + +from common import * +from time import sleep, time +import struct + + +class SensorInfo: + def __init__(self, version, product_id, sensor_type): + self.version = version + self.product_id = product_id + self.sensor_type = sensor_type + + def clarifybinary(self, instr, label): + outstr = '' + outstr += (label + ': `' + instr + '`\n') + for char in instr: + outstr += (hex(ord(char))+', ') + outstr += ('\n') + return outstr + + def __str__(self): + outstr = '' + outstr += (self.clarifybinary(str(self.version), 'Version')) + outstr += (self.clarifybinary(str(self.product_id), 'Product ID')) + outstr += (self.clarifybinary(str(self.sensor_type), 'Type')) + return outstr + +class BaseDigitalSensor(Sensor): + """Object for digital sensors. I2C_ADDRESS is the dictionary storing name + to i2c address mappings. It should be updated in every subclass. When + subclassing this class, make sure to call add_compatible_sensor to add + compatible sensor data. + """ + I2C_DEV = 0x02 + I2C_ADDRESS = {'version': (0x00, '8s'), + 'product_id': (0x08, '8s'), + 'sensor_type': (0x10, '8s'), +# 'factory_zero': (0x11, 1), # is this really correct? + 'factory_scale_factor': (0x12, 'B'), + 'factory_scale_divisor': (0x13, 'B'), + } + + def __init__(self, brick, port, check_compatible=True): + """Creates a BaseDigitalSensor. If check_compatible is True, queries + the sensor for its name, and if a wrong sensor class was used, prints + a warning. + """ + super(BaseDigitalSensor, self).__init__(brick, port) + self.set_input_mode(Type.LOW_SPEED_9V, Mode.RAW) + self.last_poll = time() + self.poll_delay = 0.01 + sleep(0.1) # Give I2C time to initialize + #Don't do type checking if this class has no compatible sensors listed. + try: self.compatible_sensors + except AttributeError: check_compatible = False + if check_compatible: + sensor = self.get_sensor_info() + if not sensor in self.compatible_sensors: + print ('WARNING: Wrong sensor class chosen for sensor ' + + str(sensor.product_id) + ' on port ' + str(port) + '. ' + """ +You may be using the wrong type of sensor or may have connected the cable +incorrectly. If you are sure you're using the correct sensor class for the +sensor, this message is likely in error and you should disregard it and file a +bug report, including the output of get_sensor_info(). This message can be +suppressed by passing "check_compatible=False" when creating the sensor object.""") + + def _ls_get_status(self, n_bytes): + for n in range(10): + try: + b = self.brick.ls_get_status(self.port) + if b >= n_bytes: + return b + except I2CPendingError: + pass + raise I2CError, 'ls_get_status timeout' + + def _i2c_command(self, address, value, format): + """Writes an i2c value to the given address. value must be a string. value is + a tuple of values corresponding to the given format. + """ + value = struct.pack(format, *value) + msg = chr(self.I2C_DEV) + chr(address) + value + if self.last_poll+self.poll_delay > time(): + diff = time() - self.last_poll + sleep(self.poll_delay - diff) + self.last_poll = time() + self.brick.ls_write(self.port, msg, 0) + + def _i2c_query(self, address, format): + """Reads an i2c value from given address, and returns a value unpacked + according to the given format. Format is the same as in the struct + module. See http://docs.python.org/library/struct.html#format-strings + """ + n_bytes = struct.calcsize(format) + msg = chr(self.I2C_DEV) + chr(address) + if self.last_poll+self.poll_delay > time(): + diff = time() - self.last_poll + sleep(self.poll_delay - diff) + self.last_poll = time() + self.brick.ls_write(self.port, msg, n_bytes) + try: + self._ls_get_status(n_bytes) + finally: + #we should clear the buffer no matter what happens + data = self.brick.ls_read(self.port) + if len(data) < n_bytes: + raise I2CError, 'Read failure: Not enough bytes' + data = struct.unpack(format, data[-n_bytes:]) + return data + + def read_value(self, name): + """Reads a value from the sensor. Name must be a string found in + self.I2C_ADDRESS dictionary. Entries in self.I2C_ADDRESS are in the + name: (address, format) form, with format as in the struct module. + Be careful on unpacking single variables - struct module puts them in + tuples containing only one element. + """ + address, fmt = self.I2C_ADDRESS[name] + for n in range(3): + try: + return self._i2c_query(address, fmt) + except DirProtError: + pass + raise I2CError, "read_value timeout" + + def write_value(self, name, value): + """Writes value to the sensor. Name must be a string found in + self.I2C_ADDRESS dictionary. Entries in self.I2C_ADDRESS are in the + name: (address, format) form, with format as in the struct module. + value is a tuple of values corresponding to the format from + self.I2C_ADDRESS dictionary. + """ + address, fmt = self.I2C_ADDRESS[name] + self._i2c_command(address, value, fmt) + + def get_sensor_info(self): + version = self.read_value('version')[0].split('\0')[0] + product_id = self.read_value('product_id')[0].split('\0')[0] + sensor_type = self.read_value('sensor_type')[0].split('\0')[0] + return SensorInfo(version, product_id, sensor_type) + + @classmethod + def add_compatible_sensor(cls, version, product_id, sensor_type): + """Adds an entry in the compatibility table for the sensor. If version + is None, then it's the default class for this model. If product_id is + None, then this is the default class for this vendor. + """ + try: + cls.compatible_sensors + except AttributeError: + cls.compatible_sensors = [] + finally: + cls.compatible_sensors.append(SCompatibility(version, product_id, + sensor_type)) + add_mapping(cls, version, product_id, sensor_type) + + +class SCompatibility(SensorInfo): + """An object that helps manage the sensor mappings""" + def __eq__(self, other): + if self.product_id is None: + return self.product_id == other.product_id + elif self.version is None: + return (self.product_id == other.product_id and + self.sensor_type == other.sensor_type) + else: + return (self.version == other.version and + self.product_id == other.product_id and + self.sensor_type == other.sensor_type) + +sensor_mappings = {} + + +def add_mapping(cls, version, product_id, sensor_type): + "None means any other value" + if product_id not in sensor_mappings: + sensor_mappings[product_id] = {} + models = sensor_mappings[product_id] + + if sensor_type is None: + if sensor_type in models: + raise ValueError('Already registered!') + models[sensor_type] = cls + return + + if sensor_type not in models: + models[sensor_type] = {} + versions = models[sensor_type] + + if version in versions: + raise ValueError('Already registered!') + else: + versions[version] = cls + + +class SearchError(Exception): + pass + + +def find_class(info): + """Returns an appropriate class for the given SensorInfo""" + dic = sensor_mappings + for val, msg in zip((info.product_id, info.sensor_type, info.version), + ('Vendor', 'Model', 'Version')): + if val in dic: + dic = dic[val] + elif None in dic: + dic = dic[None] + else: + raise SearchError(msg + ' not found') + return dic[info.sensor_type][None] diff --git a/nxt-python-fantom/nxt/sensor/generic.py b/nxt-python-fantom/nxt/sensor/generic.py new file mode 100644 index 0000000..b3d792f --- /dev/null +++ b/nxt-python-fantom/nxt/sensor/generic.py @@ -0,0 +1,154 @@ +# nxt.sensor.generic module -- Classes to read LEGO Mindstorms NXT sensors +# Copyright (C) 2006,2007 Douglas P Lau +# Copyright (C) 2009 Marcus Wanner, Paulo Vieira, rhn +# Copyright (C) 2010 melducky, Marcus Wanner +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This program 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 General Public License for more details. + +from .common import * +from .digital import BaseDigitalSensor +from .analog import BaseAnalogSensor + + +class Touch(BaseAnalogSensor): + """The LEGO touch sensor""" + + def __init__(self, brick, port): + super(Touch, self).__init__(brick, port) + self.set_input_mode(Type.SWITCH, Mode.BOOLEAN) + + def is_pressed(self): + return bool(self.get_input_values().scaled_value) + + get_sample = is_pressed + + +class Light(BaseAnalogSensor): + """Object for light sensors. It automatically turns off light when it's not + used. + """ + def __init__(self, brick, port, illuminated=True): + super(Light, self).__init__(brick, port) + + def set_illuminated(self, active): + if active: + type_ = Type.LIGHT_ACTIVE + else: + type_ = Type.LIGHT_INACTIVE + self.set_input_mode(type_, Mode.RAW) + + def get_lightness(self): + return self.get_input_values().scaled_value + + get_sample = get_lightness + + +class Sound(BaseAnalogSensor): + 'Object for sound sensors' + + def __init__(self, brick, port, adjusted=True): + super(Sound, self).__init__(brick, port) + self.set_adjusted(adjusted) + + def set_adjusted(self, active): + if active: + type_ = Type.SOUND_DBA + else: + type_ = Type.SOUND_DB + self.set_input_mode(type_, Mode.RAW) + + def get_loudness(self): + return self.get_input_values().scaled_value + + get_sample = get_loudness + + +class Ultrasonic(BaseDigitalSensor): + """Object for ultrasonic sensors""" + I2C_ADDRESS = BaseDigitalSensor.I2C_ADDRESS.copy() + I2C_ADDRESS.update({'measurement_units': (0x14, '7s'), + 'continuous_measurement_interval': (0x40, 'B'), + 'command': (0x41, 'B'), + 'measurement_byte_0': (0x42, 'B'), + 'measurements': (0x42, '8B'), + 'actual_scale_factor': (0x51, 'B'), + 'actual_scale_divisor': (0x52, 'B'), + }) + + class Commands: + 'These are for passing to command()' + OFF = 0x00 + SINGLE_SHOT = 0x01 + CONTINUOUS_MEASUREMENT = 0x02 + EVENT_CAPTURE = 0x03 #Optimize results when other Ultrasonic sensors running + REQUEST_WARM_RESET = 0x04 + + def __init__(self, brick, port, check_compatible=True): + super(Ultrasonic, self).__init__(brick, port, check_compatible) + self.set_input_mode(Type.LOW_SPEED_9V, Mode.RAW) + + def get_distance(self): + 'Function to get data from the ultrasonic sensor' + return self.read_value('measurement_byte_0')[0] + + get_sample = get_distance + + def get_measurement_units(self): + return self.read_value('measurement_units')[0].split('\0')[0] + + def get_all_measurements(self): + "Returns all the past readings in measurement_byte_0 through 7" + return self.read_value('measurements') + + def get_measurement_no(self, number): + "Returns measurement_byte_number" + if not 0 <= number < 8: + raise ValueError('Measurements are numbered 0 to 7, not ' + str(number)) + base_address, format = self.I2C_ADDRESS['measurement_byte_0'] + return self._i2c_query(base_address + number, format)[0] + + def command(self, command): + self.write_value('command', (command, )) + + def get_interval(self): + 'Get the sample interval for continuous measurement mode -- Unknown units' + return self.read_value('continuous_measurement_interval') + + def set_interval(self, interval): + """Set the sample interval for continuous measurement mode. +Unknown units; default is 1""" + self.write_value('continuous_measurement_interval', interval) + +Ultrasonic.add_compatible_sensor(None, 'LEGO', 'Sonar') #Tested with version 'V1.0' + + +class Color20(BaseAnalogSensor): + def __init__(self, brick, port): + super(Color20, self).__init__(brick, port) + self.set_light_color(Type.COLORFULL) + + def set_light_color(self, color): + """color should be one of the COLOR* Type namespace values, e.g. Type.COLORBLUE""" + self.set_input_mode(color, Mode.RAW) + + def get_light_color(self): + """Returns one of the COLOR* Type namespace values, e.g. Type.COLORRED""" + return self.get_input_values().sensor_type + + def get_reflected_light(self, color): + self.set_light_color(color) + return self.get_input_values().scaled_value + + def get_color(self): + self.get_reflected_light(Type.COLORFULL) + return self.get_input_values().scaled_value + + get_sample = get_color diff --git a/nxt-python-fantom/nxt/sensor/hitechnic.py b/nxt-python-fantom/nxt/sensor/hitechnic.py new file mode 100644 index 0000000..d2bd8ec --- /dev/null +++ b/nxt-python-fantom/nxt/sensor/hitechnic.py @@ -0,0 +1,611 @@ +# nxt.sensor.hitechnic module -- Classes to read HiTechnic sensors +# Copyright (C) 2006,2007 Douglas P Lau +# Copyright (C) 2009 Marcus Wanner, Paulo Vieira, rhn +# Copyright (C) 2010 rhn, Marcus Wanner, melducky, Samuel Leeman-Munk +# Copyright (C) 2011 jerradgenson, Marcus Wanner +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This program 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 General Public License for more details. + +from .common import * +from .digital import BaseDigitalSensor +from .analog import BaseAnalogSensor + + +class Compass(BaseDigitalSensor): + """Hitechnic compass sensor.""" + I2C_ADDRESS = BaseDigitalSensor.I2C_ADDRESS.copy() + I2C_ADDRESS.update({'mode': (0x41, 'B'), + 'heading': (0x42, 'B'), + 'adder' : (0x43, 'B'), + }) + + class Modes: + MEASUREMENT = 0x00 + CALIBRATION = 0x43 + CALIBRATION_FAILED = 0x02 + + def get_heading(self): + """Returns heading from North in degrees.""" + + two_degree_heading = self.read_value('heading')[0] + adder = self.read_value('adder')[0] + heading = two_degree_heading * 2 + adder + + return heading + + get_sample = get_heading + + def get_relative_heading(self,target=0): + rheading = self.get_sample()-target + if rheading > 180: + rheading -= 360 + elif rheading < -180: + rheading += 360 + return rheading + + def is_in_range(self,minval,maxval): + """This deserves a little explanation: +if max > min, it's straightforward, but +if min > max, it switches the values of max and min +and returns true if heading is NOT between the new max and min + """ + if minval > maxval: + (maxval,minval) = (minval,maxval) + inverted = True + else: + inverted = False + heading = self.get_sample() + in_range = (heading > minval) and (heading < maxval) + #an xor handles the reversal + #a faster, more compact way of saying + #if !reversed return in_range + #if reversed return !in_range + return bool(inverted) ^ bool(in_range) + + def get_mode(self): + return self.read_value('mode')[0] + + def set_mode(self, mode): + if mode != self.Modes.MEASUREMENT and \ + mode != self.Modes.CALIBRATION: + raise ValueError('Invalid mode specified: ' + str(mode)) + self.write_value('mode', (mode, )) + +Compass.add_compatible_sensor(None, 'HiTechnc', 'Compass ') #Tested with version '\xfdV1.23 ' +Compass.add_compatible_sensor(None, 'HITECHNC', 'Compass ') #Tested with version '\xfdV2.1 ' + + +class Accelerometer(BaseDigitalSensor): + 'Object for Accelerometer sensors. Thanks to Paulo Vieira.' + I2C_ADDRESS = BaseDigitalSensor.I2C_ADDRESS.copy() + I2C_ADDRESS.update({'x_axis_high': (0x42, 'b'), + 'y_axis_high': (0x43, 'b'), + 'z_axis_high': (0x44, 'b'), + 'xyz_short': (0x42, '3b'), + 'all_data': (0x42, '3b3B') + }) + + class Acceleration: + def __init__(self, x, y, z): + self.x, self.y, self.z = x, y, z + + def __init__(self, brick, port, check_compatible=True): + super(Accelerometer, self).__init__(brick, port, check_compatible) + + def get_acceleration(self): + """Returns the acceleration along x, y, z axes. Units are unknown to me. + """ + xh, yh, zh, xl, yl, zl = self.read_value('all_data') + x = xh << 2 + xl + y = yh << 2 + yl + z = zh << 2 + yl + return self.Acceleration(x, y, z) + + get_sample = get_acceleration + +Accelerometer.add_compatible_sensor(None, 'HiTechnc', 'Accel. ') +Accelerometer.add_compatible_sensor(None, 'HITECHNC', 'Accel. ') #Tested with version '\xfdV1.1 ' + + +class IRReceiver(BaseDigitalSensor): + """Object for HiTechnic IRReceiver sensors for use with LEGO Power Functions IR +Remotes. Coded to HiTechnic's specs for the sensor but not tested. Please report +whether this worked for you or not! + """ + I2C_ADDRESS = BaseDigitalSensor.I2C_ADDRESS.copy() + I2C_ADDRESS.update({ + 'm1A': (0x42, 'b'), + 'm1B': (0x43, 'b'), + 'm2A': (0x44, 'b'), + 'm2B': (0x45, 'b'), + 'm3A': (0x46, 'b'), + 'm3B': (0x47, 'b'), + 'm4A': (0x48, 'b'), + 'm4B': (0x49, 'b'), + 'all_data': (0x42, '8b') + }) + + class SpeedReading: + def __init__(self, m1A, m1B, m2A, m2B, m3A, m3B, m4A, m4B): + self.m1A, self.m1B, self.m2A, self.m2B, self.m3A, self.m3B, self.m4A, self.m4B = m1A, m1B, m2A, m2B, m3A, m3B, m4A, m4B + self.channel_1 = (m1A, m1B) + self.channel_2 = (m2A, m2B) + self.channel_3 = (m3A, m3B) + self.channel_4 = (m4A, m4B) + + def __init__(self, brick, port, check_compatible=True): + super(IRReceiver, self).__init__(brick, port, check_compatible) + + def get_speeds(self): + """Returns the motor speeds for motors A and B on channels 1-4. +Values are -128, -100, -86, -72, -58, -44, -30, -16, 0, 16, 30, 44, 58, 72, 86 +and 100. -128 specifies motor brake mode. Note that no motors are actually +being controlled here! + """ + m1A, m1B, m2A, m2B, m3A, m3B, m4A, m4B = self.read_value('all_data') + return self.SpeedReading(m1A, m1B, m2A, m2B, m3A, m3B, m4A, m4B) + + get_sample = get_speeds + +IRReceiver.add_compatible_sensor(None, 'HiTechnc', 'IRRecv ') +IRReceiver.add_compatible_sensor(None, 'HITECHNC', 'IRRecv ') + + +class IRSeekerv2(BaseDigitalSensor): + """Object for HiTechnic IRSeeker sensors. Coded to HiTechnic's specs for the sensor +but not tested. Please report whether this worked for you or not! + """ + I2C_ADDRESS = BaseDigitalSensor.I2C_ADDRESS.copy() + I2C_ADDRESS.update({ + 'dspmode': (0x41, 'B'), + 'DC_direction': (0x42, 'B'), + 'DC_sensor_1': (0x43, 'B'), + 'DC_sensor_2': (0x44, 'B'), + 'DC_sensor_3': (0x45, 'B'), + 'DC_sensor_4': (0x46, 'B'), + 'DC_sensor_5': (0x47, 'B'), + 'DC_sensor_mean': (0x48, 'B'), + 'all_DC': (0x42, '7B'), + 'AC_direction': (0x49, 'B'), + 'AC_sensor_1': (0x4A, 'B'), + 'AC_sensor_2': (0x4B, 'B'), + 'AC_sensor_3': (0x4C, 'B'), + 'AC_sensor_4': (0x4D, 'B'), + 'AC_sensor_5': (0x4E, 'B'), + 'all_AC': (0x49, '6B') + }) + I2C_DEV = 0x10 #different from standard 0x02 + + class DSPModes: + #Modes for modulated (AC) data. + AC_DSP_1200Hz = 0x00 + AC_DSP_600Hz = 0x01 + + class _data: + def get_dir_brightness(self, direction): + "Gets the brightness of a given direction (1-9)." + if direction%2 == 1: #if it's an odd number + exec("val = self.sensor_%d" % ((direction-1)/2+1)) + else: + exec("val = (self.sensor_%d+self.sensor_%d)/2" % (direction/2, (direction/2)+1)) + return val + + class DCData(_data): + def __init__(self, direction, sensor_1, sensor_2, sensor_3, sensor_4, sensor_5, sensor_mean): + self.direction, self.sensor_1, self.sensor_2, self.sensor_3, self.sensor_4, self.sensor_5, self.sensor_mean = direction, sensor_1, sensor_2, sensor_3, sensor_4, sensor_5, sensor_mean + + class ACData(_data): + def __init__(self, direction, sensor_1, sensor_2, sensor_3, sensor_4, sensor_5): + self.direction, self.sensor_1, self.sensor_2, self.sensor_3, self.sensor_4, self.sensor_5 = direction, sensor_1, sensor_2, sensor_3, sensor_4, sensor_5 + + + def __init__(self, brick, port, check_compatible=True): + super(IRSeekerv2, self).__init__(brick, port, check_compatible) + + def get_dc_values(self): + """Returns the unmodulated (DC) values. + """ + direction, sensor_1, sensor_2, sensor_3, sensor_4, sensor_5, sensor_mean = self.read_value('all_DC') + return self.DCData(direction, sensor_1, sensor_2, sensor_3, sensor_4, sensor_5, sensor_mean) + + def get_ac_values(self): + """Returns the modulated (AC) values. 600Hz and 1200Hz modes can be selected +between by using the set_dsp_mode() function. + """ + direction, sensor_1, sensor_2, sensor_3, sensor_4, sensor_5 = self.read_value('all_AC') + return self.ACData(direction, sensor_1, sensor_2, sensor_3, sensor_4, sensor_5) + + def get_dsp_mode(self): + return self.read_value('dspmode')[0] + + def set_dsp_mode(self, mode): + self.write_value('dspmode', (mode, )) + + get_sample = get_ac_values + +IRSeekerv2.add_compatible_sensor(None, 'HiTechnc', 'NewIRDir') +IRSeekerv2.add_compatible_sensor(None, 'HITECHNC', 'NewIRDir') + + +class EOPD(BaseAnalogSensor): + """Object for HiTechnic Electro-Optical Proximity Detection sensors. + """ + + # To be divided by processed value. + _SCALE_CONSTANT = 250 + + # Maximum distance the sensor can detect. + _MAX_DISTANCE = 1023 + + def __init__(self, brick, port): + super(EOPD, self).__init__(brick, port) + from math import sqrt + self.sqrt = sqrt + + def set_range_long(self): + ''' Choose this mode to increase the sensitivity + of the EOPD sensor by approximately 4x. May + cause sensor overload. + ''' + + self.set_input_mode(Type.LIGHT_ACTIVE, Mode.RAW) + + def set_range_short(self): + ''' Choose this mode to prevent the EOPD sensor from + being overloaded by white objects. + ''' + + self.set_input_mode(Type.LIGHT_INACTIVE, Mode.RAW) + + def get_raw_value(self): + '''Unscaled value read from sensor.''' + + return self._MAX_DISTANCE - self.get_input_values().raw_ad_value + + def get_processed_value(self): + '''Derived from the square root of the raw value.''' + + return self.sqrt(self.get_raw_value()) + + def get_scaled_value(self): + ''' Returns a value that will scale linearly as distance + from target changes. This is the method that should + generally be called to get EOPD sensor data. + ''' + + try: + result = self._SCALE_CONSTANT / self.get_processed_value() + return result + + except ZeroDivisionError: + return self._SCALE_CONSTANT + + get_sample = get_scaled_value + + +class Colorv2(BaseDigitalSensor): + """Object for HiTechnic Color v2 Sensors. Coded to HiTechnic's specs for the sensor +but not tested. Please report whether this worked for you or not!""" + I2C_ADDRESS = BaseDigitalSensor.I2C_ADDRESS.copy() + I2C_ADDRESS.update({ + 'mode': (0x41, 'B'), + 'number': (0x42, 'B'), + 'red': (0x43, 'B'), + 'green': (0x44, 'B'), + 'blue': (0x45, 'B'), + 'white': (0x46, 'B'), + 'index': (0x47, 'B'), + 'normred': (0x48, 'B'), + 'normgreen': (0x49, 'B'), + 'normblue': (0x4A, 'B'), + 'all_data': (0x42, '9B'), + 'rawred': (0x42, 'l'), + 'm1mode': (0x44, 'B'), + 'm1power': (0x45, 'b'), + 'm2power': (0x46, 'b'), + 'm2mode': (0x47, 'B'), + 'm2enctarget': (0x48, '>l'), + 'm1enccurrent': (0x4c, '>l'), + 'm2enccurrent': (0x50, '>l'), + 'batteryvoltage': (0x54, '2B'), + 'm1gearratio': (0x56, 'b'), + 'm1pid': (0x57, '3B'), + 'm2gearratio': (0x5a, 'b'), + 'm2pid': (0x5b, '3B'), + }) + + class PID_Data(): + def __init__(self, p, i, d): + self.p, self.i, self.d = p, i, d + + def __init__(self, brick, port, check_compatible=True): + super(MotorCon, self).__init__(brick, port, check_compatible) + + def set_enc_target(self, mot, val): + """Set the encoder target (-2147483648-2147483647) for a motor + """ + self.write_value('m%denctarget'%mot, (val, )) + + def get_enc_target(self, mot): + """Get the encoder target for a motor + """ + return self.read_value('m%denctarget'%mot)[0] + + def get_enc_current(self, mot): + """Get the current encoder value for a motor + """ + return self.read_value('m%denccurrent'%mot)[0] + + def set_mode(self, mot, mode): + """Set the mode for a motor. This value is a bit mask and you can +find details about it in the sensor's documentation. + """ + self.write_value('m%dmode'%mot, (mode, )) + + def get_mode(self, mot): + """Get the mode for a motor. This value is a bit mask and you can +find details about it in the sensor's documentation. + """ + return self.read_value('m%dmode'%mot)[0] + + def set_power(self, mot, power): + """Set the power (-100-100) for a motor + """ + self.write_value('m%dpower'%mot, (power, )) + + def get_power(self, mot): + """Get the power for a motor + """ + return self.read_value('m%dpower'%mot)[0] + + def set_gear_ratio(self, mot, ratio): + """Set the gear ratio for a motor + """ + self.write_value('m%dgearratio'%mot, (ratio, )) + + def get_gear_ratio(self, mot): + """Get the gear ratio for a motor + """ + return self.read_value('m%dgearratio'%mot)[0] + + def set_pid(self, mot, piddata): + """Set the PID coefficients for a motor. Takes data in +MotorCon.PID_Data(p, i, d) format. + """ + self.write_value('m%dpid'%mot, (piddata.p, piddata.i, piddata.d)) + + def get_pid(self, mot): + """Get the PID coefficients for a motor. Returns a PID_Data() object. + """ + p, i, d = self.read_value('m%dpid'%mot) + return self.PID_Data(p, i, d) + + def get_battery_voltage(self): + """Gets the battery voltage (in millivolts/20) + """ + high, low = self.read_value('bateryvoltage')[0] + return high << 2 + low + +MotorCon.add_compatible_sensor(None, 'HiTechnc', 'MotorCon') diff --git a/nxt-python-fantom/nxt/sensor/mindsensors.py b/nxt-python-fantom/nxt/sensor/mindsensors.py new file mode 100644 index 0000000..de6c7ee --- /dev/null +++ b/nxt-python-fantom/nxt/sensor/mindsensors.py @@ -0,0 +1,815 @@ +# nxt.sensor.mindsensors module -- Classes implementing Mindsensors sensors +# Copyright (C) 2006,2007 Douglas P Lau +# Copyright (C) 2009 Marcus Wanner, Paulo Vieira, rhn +# Copyright (C) 2010 Marcus Wanner, MindSensors +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This program 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 General Public License for more details. + + +from .common import * +from .digital import BaseDigitalSensor, SensorInfo +from .analog import BaseAnalogSensor + + +class SumoEyes(BaseAnalogSensor): + """The class to control Mindsensors Sumo sensor. Warning: long range not + working for my sensor. + """ + #range: 5-10cm + class Reading: + """Contains the reading of SumoEyes sensor. left and right can be True or + False. If True, then there is something there, if False, then it's empty + there. + """ + def __init__(self, raw_reading): + self.raw = raw_reading + val = raw_reading.normalized_ad_value # FIXME: make it rely on raw_ad_value + right = 600 < val < 700 + both = 700 <= val < 900 + left = 300 < val < 400 + self.left = left or both + self.right = right or both + + def __str__(self): + return '(left: ' + str(self.left) + ', right: ' + str(self.right) + ')' + + def __init__(self, brick, port, long_range=False): + super(SumoEyes, self).__init__(brick, port) + self.set_long_range(long_range) + + def set_long_range(self, val): + """Sets if the sensor should operate in long range mode (12 inches) or + the short range mode (6 in). val should be True or False. + """ + if val: + type_ = Type.LIGHT_INACTIVE + else: + type_ = Type.LIGHT_ACTIVE + self.set_input_mode(type_, Mode.RAW) + + def get_sample(self): + """Returns the processed meaningful values of the sensor""" + return self.Reading(self.get_input_values()) + + +class Compassv2(BaseDigitalSensor): + """Class for the now-discontinued CMPS-Nx sensor. Also works with v1.1 sensors. +Note that when using a v1.x sensor, some of the commands are not supported! +To determine your sensor's version, use get_sensor_info().version""" + I2C_ADDRESS = BaseDigitalSensor.I2C_ADDRESS.copy() + I2C_ADDRESS.update({'command': (0x41, '> 4 + return str(gs3) + str(gs2) + + def get_minutes(self): + gm = self.read_value('minutes')[0] + gm2 = gm & 0xf + gm3 = gm & 0x70 + gm3 = gm3 >> 4 + return str(gm3) + str(gm2) + + def get_hours(self): + gh = self.read_value('hours')[0] + gh2 = gh & 0xf + gh3 = gh & 0x30 + gh3 = gh3 >> 4 + return str(gh3) + str(gh2) + + def get_day(self): + gwd = self.read_value('day')[0] + gwd = gwd & 0x07 + return gwd + + def get_month(self): + gmo = self.read_value('month')[0] + gmo2 = gmo & 0xf + gmo3 = gmo & 0x10 + gmo3 = gmo3 >> 4 + return str(gmo3) + str(gmo2) + + def get_year(self): + """Last two digits (10 for 2010)""" + gy = self.read_value('year')[0] + gy2 = gy & 0xf + gy3 = gy & 0xF0 + gy3 = gy3 >> 4 + return str(gy3) + str(gy2) + + def get_date(self): + gd = self.read_value('date')[0] + gd2 = gd & 0xf + gd3 = gd & 0x60 + gd3 = gd3 >> 4 + return str(gd3) + str(gd2) + + def hour_mode(self, mode): + """Writes mode bit and re-enters hours, which is required""" + if mode == 12 or 24: + hm = self.read_value('hours')[0] + hm2 = hm & 0x40 + hm2 = hm2 >> 6 + if mode == 12 and hm2 == 0: #12_HOUR = 1 + hm3 = hm + 64 + self.write_value('hours', (hm3, )) + elif mode == 24 and hm2 == 1: #24_HOUR = 0 + hm3 = hm - 64 + self.write_value('hours', (hm3, )) + else: + print 'That mode is already selected!' + else: + raise ValueError('Must be 12 or 24!') + + def get_mer(self): + mer = self.read_value('hours')[0] + mer2 = mer & 0x40 + mer2 = mer2 >> 6 + if mer2 == 1: + mer3 = mer & 0x20 + mer3 = mer3 >> 0x10 + return mer3 + else: + print 'Cannot get mer! In 24-hour mode!' + + def get_sample(self): + """Returns a struct_time() tuple which can be processed by the time module.""" + import time + return time.struct_time(( + int(self.get_year())+2000, + int(self.get_month()), + int(self.get_date()), + int(self.get_hours()), + int(self.get_minutes()), + int(self.get_seconds()), + int(self.get_day()), + 0, #Should be the Julian Day, but computing that is hard. + 0 #No daylight savings time to worry about here. + )) + + +class ACCL(BaseDigitalSensor): + """Class for Accelerometer sensor""" + I2C_ADDRESS = BaseDigitalSensor.I2C_ADDRESS.copy() + I2C_ADDRESS.update({'sensitivity': (0x19, 'B'), + 'command': (0x41, 'B'), + 'x_tilt': (0x42, 'b'), + 'y_tilt': (0x43, 'b'), + 'z_tilt': (0x44, 'b'), + 'all_tilt': (0x42, '3b'), + + 'x_accel': (0x45, '> bit_num + return value + + def get_tasks(self, motor_number): + addressname = 'tasks_running_m' + str(motor_number) + return self.read_value(addressname)[0] + + def set_pid(self, pid, target, value): + addressname = str(pid) + '_' + str(target) + self.write_value(addressname, (value, )) + + def set_pass_count(self, value): + self.write_value('pass_count', (value, )) + + def set_tolerance(self, value): + self.write_value('tolerance', (value, )) + +MMX.add_compatible_sensor(None, 'mndsnsrs', 'NxTMMX') #Tested with version 'V1.01' + + +class HID(BaseDigitalSensor): + """Class for Human Interface Device sensors. +These are connected to a computer and look like a keyboard to it.""" + I2C_ADDRESS = BaseDigitalSensor.I2C_ADDRESS.copy() + I2C_ADDRESS.update({'command' : (0x41, ' 15: + print "Warning! Brick name %s will be truncated to %s!" % (bname, bname[0:15]) + bname = bname[0:15] + elif len(bname) < 15: + bname += '\x00' * (15-len(bname)) #fill the extra chars with nulls + tgram.add_string(len(bname), bname) + return tgram + +def _parse_set_brick_name(tgram): + tgram.check_status() + +def get_device_info(opcode): + return _create(opcode) + +def _parse_get_device_info(tgram): + tgram.check_status() + name = tgram.parse_string(15) + a0 = tgram.parse_u8() + a1 = tgram.parse_u8() + a2 = tgram.parse_u8() + a3 = tgram.parse_u8() + a4 = tgram.parse_u8() + a5 = tgram.parse_u8() + a6 = tgram.parse_u8() + # FIXME: what is a6 for? + address = '%02X:%02X:%02X:%02X:%02X:%02X' % (a0, a1, a2, a3, a4, a5) + signal_strength = tgram.parse_u32() + user_flash = tgram.parse_u32() + return (name, address, signal_strength, user_flash) + +def delete_user_flash(opcode): + return _create(opcode) + +def _parse_delete_user_flash(tgram): + tgram.check_status() + +def poll_command_length(opcode, buf_num): + tgram = _create(opcode) + tgram.add_u8(buf_num) + return tgram + +def _parse_poll_command_length(tgram): + buf_num = tgram.parse_u8() + tgram.check_status() + n_bytes = tgram.parse_u8() + return (buf_num, n_bytes) + +def poll_command(opcode, buf_num, n_bytes): + tgram = _create(opcode) + tgram.add_u8(buf_num) + tgram.add_u8(n_bytes) + return tgram + +def _parse_poll_command(tgram): + buf_num = tgram.parse_u8() + tgram.check_status() + n_bytes = tgram.parse_u8() + command = tgram.parse_string() + return (buf_num, n_bytes, command) + +def bluetooth_factory_reset(opcode): + # Note: this command is USB only (no Bluetooth) + return _create(opcode) + +def _parse_bluetooth_factory_reset(tgram): + tgram.check_status() + +OPCODES = { + 0x80: (open_read, _parse_open_read), + 0x81: (open_write, _parse_open_write), + 0x82: (read, _parse_read), + 0x83: (write, _parse_write), + 0x84: (close, _parse_close), + 0x85: (delete, _parse_delete), + 0x86: (find_first, _parse_find), + 0x87: (find_next, _parse_find), + 0x88: (get_firmware_version, _parse_get_firmware_version), + 0x89: (open_write_linear, _parse_open_write), + 0x8A: (open_read_linear, _parse_open_read_linear), + 0x8B: (open_write_data, _parse_open_write), + 0x8C: (open_append_data, _parse_open_append_data), + 0x90: (request_first_module, _parse_request_module), + 0x91: (request_next_module, _parse_request_module), + 0x92: (close_module_handle, _parse_close), + 0x94: (read_io_map, _parse_read_io_map), + 0x95: (write_io_map, _parse_write_io_map), + 0x97: (boot, _parse_boot), + 0x98: (set_brick_name, _parse_set_brick_name), + 0x9B: (get_device_info, _parse_get_device_info), + 0xA0: (delete_user_flash, _parse_delete_user_flash), + 0xA1: (poll_command_length, _parse_poll_command_length), + 0xA2: (poll_command, _parse_poll_command), + 0xA4: (bluetooth_factory_reset, _parse_bluetooth_factory_reset), +} diff --git a/nxt-python-fantom/nxt/telegram.py b/nxt-python-fantom/nxt/telegram.py new file mode 100644 index 0000000..1fc5b3e --- /dev/null +++ b/nxt-python-fantom/nxt/telegram.py @@ -0,0 +1,118 @@ +# nxt.telegram module -- LEGO Mindstorms NXT telegram formatting and parsing +# Copyright (C) 2006 Douglas P Lau +# Copyright (C) 2009 Marcus Wanner +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This program 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 General Public License for more details. + +'Used by nxt.system for sending telegrams to the NXT' + +from cStringIO import StringIO +from struct import pack, unpack +import nxt.error + +class InvalidReplyError(Exception): + pass + +class InvalidOpcodeError(Exception): + pass + +class Telegram(object): + + TYPE = 0 # type byte offset + CODE = 1 # code byte offset + DATA = 2 # data byte offset + + TYPE_NOT_DIRECT = 0x01 # system vs. direct type + TYPE_REPLY = 0x02 # reply type (from NXT brick) + TYPE_REPLY_NOT_REQUIRED = 0x80 # reply not required flag + + def __init__(self, direct=False, opcode=0, reply_req=True, pkt=None): + if pkt: + self.pkt = StringIO(pkt) + self.typ = self.parse_u8() + self.opcode = self.parse_u8() + if not self.is_reply(): + raise InvalidReplyError + if self.opcode != opcode: + raise InvalidOpcodeError, self.opcode + else: + self.pkt = StringIO() + typ = 0 + if not direct: + typ |= Telegram.TYPE_NOT_DIRECT + if not reply_req: + typ |= Telegram.TYPE_REPLY_NOT_REQUIRED + self.add_u8(typ) + self.add_u8(opcode) + + def __str__(self): + return self.pkt.getvalue() + + def is_reply(self): + return self.typ == Telegram.TYPE_REPLY + + def add_string(self, n_bytes, v): + self.pkt.write(pack('%ds' % n_bytes, v)) + + def add_filename(self, fname): + self.pkt.write(pack('20s', fname)) + + def add_s8(self, v): + self.pkt.write(pack(' + + nxt-python-fantom + + + + + + + + diff --git a/nxt-python-fantom/nxt/fantomglue.py b/nxt-python-fantom/nxt/fantomglue.py new file mode 100644 index 0000000..a987a7e --- /dev/null +++ b/nxt-python-fantom/nxt/fantomglue.py @@ -0,0 +1,55 @@ +# fantom.py module -- Glue code from NXT_Python to Fantom, allowing +# NXT_Python to run on Mac without modification. Supports subset of +# PyBluez/bluetooth.py used by NXT_Python. +# +# Copyright (C) 2011 Tat-Chee Wan +# +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 3 of the License, or +# (at your option) any later version. +# +# This program 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 General Public License for more details. + +import fantom + +FANTOM_BT='BT' +FANTOM_USB='USB' + + +def discover_devices(lookup_names=False): # parameter is ignored + pairs = [] + d = fantom.finddevices(proto = FANTOM_BT) + for p in d: + h = p[0] + n = p[1] + pairs.append((h, n)) + return pairs + +class BluetoothSocket: + + def __init__(self, proto = FANTOM_BT, _sock=None): + if _sock is None: + _sock = fantom.socket(proto) + self._sock = _sock + self._proto = proto + + def connect(self, addrport): + addr, port = addrport + self._sock.connect( (addr, port )) + + def send(self, data): + return self._sock.send( data ) + + def recv(self, numbytes): + return self._sock.recv( numbytes ) + + def close(self): + return self._sock.close() + +class BluetoothError(IOError): + pass + -- cgit v1.2.3 From 2cbe251e1b726c2fc5347dffd25cd4f9102012ed Mon Sep 17 00:00:00 2001 From: Tat-Chee Wan (USM) Date: Tue, 1 Mar 2011 12:12:49 +0800 Subject: added fantom module for python --- FantomModule/FantomModule.cp | 133 ++++ FantomModule/FantomModule.h | 49 ++ .../FantomModule.xcodeproj/project.pbxproj | 293 +++++++++ FantomModule/FantomModulePriv.h | 19 + FantomModule/FantomModuleProj.xcconfig | 6 + FantomModule/FantomModuleTarget.xcconfig | 11 + FantomModule/FantomModule_Prefix.pch | 6 + FantomModule/fantom/iFile.h | 280 +++++++++ FantomModule/fantom/iFileIterator.h | 133 ++++ FantomModule/fantom/iModule.h | 154 +++++ FantomModule/fantom/iModuleIterator.h | 123 ++++ FantomModule/fantom/iNXT.h | 666 +++++++++++++++++++++ FantomModule/fantom/iNXTIterator.h | 120 ++++ FantomModule/fantom/platform.h | 94 +++ FantomModule/fantom/tStatus.h | 458 ++++++++++++++ .../include/labview/macosx/advanceFileIterator.vi | Bin 0 -> 52507 bytes .../labview/macosx/advanceModuleIterator.vi | Bin 0 -> 49641 bytes .../include/labview/macosx/advanceNXTIterator.vi | Bin 0 -> 49658 bytes .../labview/macosx/bluetoothFactoryReset.vi | Bin 0 -> 44169 bytes FantomModule/include/labview/macosx/bootSamba.vi | Bin 0 -> 30013 bytes FantomModule/include/labview/macosx/closeFile.vi | Bin 0 -> 42973 bytes FantomModule/include/labview/macosx/createFile.vi | Bin 0 -> 53398 bytes .../include/labview/macosx/createFileIterator.vi | Bin 0 -> 59566 bytes .../include/labview/macosx/createModule.vi | Bin 0 -> 60580 bytes .../include/labview/macosx/createModuleIterator.vi | Bin 0 -> 59588 bytes FantomModule/include/labview/macosx/createNXT.vi | Bin 0 -> 77937 bytes .../include/labview/macosx/createNXTIterator.vi | Bin 0 -> 61697 bytes FantomModule/include/labview/macosx/destroyFile.vi | Bin 0 -> 44491 bytes .../include/labview/macosx/destroyFileIterator.vi | Bin 0 -> 44715 bytes .../include/labview/macosx/destroyModule.vi | Bin 0 -> 44733 bytes .../labview/macosx/destroyModuleIterator.vi | Bin 0 -> 44657 bytes FantomModule/include/labview/macosx/destroyNXT.vi | Bin 0 -> 54226 bytes .../include/labview/macosx/destroyNXTIterator.vi | Bin 0 -> 44090 bytes .../include/labview/macosx/downloadFirmware.vi | Bin 0 -> 51788 bytes .../include/labview/macosx/eraseUserFlash.vi | Bin 0 -> 53218 bytes .../macosx/findDeviceInFirmwareDownloadMode.vi | Bin 0 -> 33424 bytes FantomModule/include/labview/macosx/findNXT.vi | Bin 0 -> 57487 bytes .../include/labview/macosx/getAvailableSize.vi | Bin 0 -> 46052 bytes .../include/labview/macosx/getDeviceInfo.vi | Bin 0 -> 77397 bytes FantomModule/include/labview/macosx/getFile.vi | Bin 0 -> 46879 bytes FantomModule/include/labview/macosx/getFileName.vi | Bin 0 -> 57503 bytes FantomModule/include/labview/macosx/getFileSize.vi | Bin 0 -> 49827 bytes .../labview/macosx/getFileSizeFromIterator.vi | Bin 0 -> 46119 bytes .../labview/macosx/getFilenameFromIterator.vi | Bin 0 -> 50359 bytes .../include/labview/macosx/getFirmwareVersion.vi | Bin 0 -> 54438 bytes .../include/labview/macosx/getIOMapSize.vi | Bin 0 -> 47320 bytes FantomModule/include/labview/macosx/getModule.vi | Bin 0 -> 45677 bytes FantomModule/include/labview/macosx/getModuleID.vi | Bin 0 -> 47455 bytes .../include/labview/macosx/getModuleName.vi | Bin 0 -> 51125 bytes .../labview/macosx/getModuleNameFromIterator.vi | Bin 0 -> 50373 bytes .../include/labview/macosx/getModuleSize.vi | Bin 0 -> 47365 bytes .../include/labview/macosx/getNXTFromIterator.vi | Bin 0 -> 45554 bytes .../include/labview/macosx/getResourceString.vi | Bin 0 -> 50629 bytes .../labview/macosx/getStringFromNXTIterator.vi | Bin 0 -> 50832 bytes FantomModule/include/labview/macosx/isPaired.vi | Bin 0 -> 33180 bytes FantomModule/include/labview/macosx/nakedRead.vi | Bin 0 -> 56833 bytes FantomModule/include/labview/macosx/nakedWrite.vi | Bin 0 -> 53942 bytes FantomModule/include/labview/macosx/nxt.ctl | Bin 0 -> 12924 bytes FantomModule/include/labview/macosx/openForRead.vi | Bin 0 -> 46847 bytes .../include/labview/macosx/openForWrite.vi | Bin 0 -> 61344 bytes .../include/labview/macosx/pairBluetooth.vi | Bin 0 -> 37997 bytes .../include/labview/macosx/pollAvailableLength.vi | Bin 0 -> 48927 bytes FantomModule/include/labview/macosx/read.vi | Bin 0 -> 57324 bytes .../include/labview/macosx/readBufferData.vi | Bin 0 -> 60250 bytes FantomModule/include/labview/macosx/readIOMap.vi | Bin 0 -> 56653 bytes FantomModule/include/labview/macosx/remove.vi | Bin 0 -> 46762 bytes .../include/labview/macosx/sendDirectCommand.vi | Bin 0 -> 62289 bytes FantomModule/include/labview/macosx/setNXTName.vi | Bin 0 -> 46126 bytes .../include/labview/macosx/unpairBluetooth.vi | Bin 0 -> 28927 bytes FantomModule/include/labview/macosx/write.vi | Bin 0 -> 53525 bytes FantomModule/include/labview/macosx/writeIOMap.vi | Bin 0 -> 54282 bytes .../include/labview/win32/advanceFileIterator.vi | Bin 0 -> 50807 bytes .../include/labview/win32/advanceModuleIterator.vi | Bin 0 -> 47697 bytes .../include/labview/win32/advanceNXTIterator.vi | Bin 0 -> 47430 bytes .../include/labview/win32/bluetoothFactoryReset.vi | Bin 0 -> 42289 bytes FantomModule/include/labview/win32/bootSamba.vi | Bin 0 -> 28245 bytes FantomModule/include/labview/win32/closeFile.vi | Bin 0 -> 41293 bytes FantomModule/include/labview/win32/createFile.vi | Bin 0 -> 51566 bytes .../include/labview/win32/createFileIterator.vi | Bin 0 -> 57766 bytes FantomModule/include/labview/win32/createModule.vi | Bin 0 -> 58556 bytes .../include/labview/win32/createModuleIterator.vi | Bin 0 -> 57524 bytes FantomModule/include/labview/win32/createNXT.vi | Bin 0 -> 75773 bytes .../include/labview/win32/createNXTIterator.vi | Bin 0 -> 59605 bytes FantomModule/include/labview/win32/destroyFile.vi | Bin 0 -> 42775 bytes .../include/labview/win32/destroyFileIterator.vi | Bin 0 -> 43063 bytes .../include/labview/win32/destroyModule.vi | Bin 0 -> 43017 bytes .../include/labview/win32/destroyModuleIterator.vi | Bin 0 -> 42989 bytes FantomModule/include/labview/win32/destroyNXT.vi | Bin 0 -> 52394 bytes .../include/labview/win32/destroyNXTIterator.vi | Bin 0 -> 42110 bytes .../include/labview/win32/downloadFirmware.vi | Bin 0 -> 49704 bytes .../include/labview/win32/eraseUserFlash.vi | Bin 0 -> 50750 bytes .../win32/findDeviceInFirmwareDownloadMode.vi | Bin 0 -> 31524 bytes FantomModule/include/labview/win32/findNXT.vi | Bin 0 -> 55779 bytes .../include/labview/win32/getAvailableSize.vi | Bin 0 -> 43996 bytes .../include/labview/win32/getDeviceInfo.vi | Bin 0 -> 73869 bytes FantomModule/include/labview/win32/getFile.vi | Bin 0 -> 45059 bytes FantomModule/include/labview/win32/getFileName.vi | Bin 0 -> 55387 bytes FantomModule/include/labview/win32/getFileSize.vi | Bin 0 -> 47899 bytes .../labview/win32/getFileSizeFromIterator.vi | Bin 0 -> 44047 bytes .../labview/win32/getFilenameFromIterator.vi | Bin 0 -> 48447 bytes .../include/labview/win32/getFirmwareVersion.vi | Bin 0 -> 52298 bytes FantomModule/include/labview/win32/getIOMapSize.vi | Bin 0 -> 45256 bytes FantomModule/include/labview/win32/getModule.vi | Bin 0 -> 43873 bytes FantomModule/include/labview/win32/getModuleID.vi | Bin 0 -> 45675 bytes .../include/labview/win32/getModuleName.vi | Bin 0 -> 49113 bytes .../labview/win32/getModuleNameFromIterator.vi | Bin 0 -> 48477 bytes .../include/labview/win32/getModuleSize.vi | Bin 0 -> 45533 bytes .../include/labview/win32/getNXTFromIterator.vi | Bin 0 -> 43762 bytes .../include/labview/win32/getResourceString.vi | Bin 0 -> 48689 bytes .../labview/win32/getStringFromNXTIterator.vi | Bin 0 -> 48664 bytes FantomModule/include/labview/win32/isPaired.vi | Bin 0 -> 31428 bytes FantomModule/include/labview/win32/nakedRead.vi | Bin 0 -> 55097 bytes FantomModule/include/labview/win32/nakedWrite.vi | Bin 0 -> 51866 bytes FantomModule/include/labview/win32/nxt.ctl | Bin 0 -> 12692 bytes FantomModule/include/labview/win32/openForRead.vi | Bin 0 -> 44755 bytes FantomModule/include/labview/win32/openForWrite.vi | Bin 0 -> 58108 bytes .../include/labview/win32/pairBluetooth.vi | Bin 0 -> 35997 bytes .../include/labview/win32/pollAvailableLength.vi | Bin 0 -> 46951 bytes FantomModule/include/labview/win32/read.vi | Bin 0 -> 55444 bytes .../include/labview/win32/readBufferData.vi | Bin 0 -> 58354 bytes FantomModule/include/labview/win32/readIOMap.vi | Bin 0 -> 54409 bytes FantomModule/include/labview/win32/remove.vi | Bin 0 -> 45010 bytes .../include/labview/win32/sendDirectCommand.vi | Bin 0 -> 60249 bytes FantomModule/include/labview/win32/setNXTName.vi | Bin 0 -> 44182 bytes .../include/labview/win32/unpairBluetooth.vi | Bin 0 -> 27139 bytes FantomModule/include/labview/win32/write.vi | Bin 0 -> 51589 bytes FantomModule/include/labview/win32/writeIOMap.vi | Bin 0 -> 52014 bytes FantomModule/visatype.h | 155 +++++ 128 files changed, 2700 insertions(+) create mode 100644 FantomModule/FantomModule.cp create mode 100644 FantomModule/FantomModule.h create mode 100644 FantomModule/FantomModule.xcodeproj/project.pbxproj create mode 100644 FantomModule/FantomModulePriv.h create mode 100644 FantomModule/FantomModuleProj.xcconfig create mode 100644 FantomModule/FantomModuleTarget.xcconfig create mode 100644 FantomModule/FantomModule_Prefix.pch create mode 100644 FantomModule/fantom/iFile.h create mode 100644 FantomModule/fantom/iFileIterator.h create mode 100644 FantomModule/fantom/iModule.h create mode 100644 FantomModule/fantom/iModuleIterator.h create mode 100644 FantomModule/fantom/iNXT.h create mode 100644 FantomModule/fantom/iNXTIterator.h create mode 100644 FantomModule/fantom/platform.h create mode 100644 FantomModule/fantom/tStatus.h create mode 100644 FantomModule/include/labview/macosx/advanceFileIterator.vi create mode 100644 FantomModule/include/labview/macosx/advanceModuleIterator.vi create mode 100644 FantomModule/include/labview/macosx/advanceNXTIterator.vi create mode 100644 FantomModule/include/labview/macosx/bluetoothFactoryReset.vi create mode 100644 FantomModule/include/labview/macosx/bootSamba.vi create mode 100644 FantomModule/include/labview/macosx/closeFile.vi create mode 100644 FantomModule/include/labview/macosx/createFile.vi create mode 100644 FantomModule/include/labview/macosx/createFileIterator.vi create mode 100644 FantomModule/include/labview/macosx/createModule.vi create mode 100644 FantomModule/include/labview/macosx/createModuleIterator.vi create mode 100644 FantomModule/include/labview/macosx/createNXT.vi create mode 100644 FantomModule/include/labview/macosx/createNXTIterator.vi create mode 100644 FantomModule/include/labview/macosx/destroyFile.vi create mode 100644 FantomModule/include/labview/macosx/destroyFileIterator.vi create mode 100644 FantomModule/include/labview/macosx/destroyModule.vi create mode 100644 FantomModule/include/labview/macosx/destroyModuleIterator.vi create mode 100644 FantomModule/include/labview/macosx/destroyNXT.vi create mode 100644 FantomModule/include/labview/macosx/destroyNXTIterator.vi create mode 100644 FantomModule/include/labview/macosx/downloadFirmware.vi create mode 100644 FantomModule/include/labview/macosx/eraseUserFlash.vi create mode 100644 FantomModule/include/labview/macosx/findDeviceInFirmwareDownloadMode.vi create mode 100644 FantomModule/include/labview/macosx/findNXT.vi create mode 100644 FantomModule/include/labview/macosx/getAvailableSize.vi create mode 100644 FantomModule/include/labview/macosx/getDeviceInfo.vi create mode 100644 FantomModule/include/labview/macosx/getFile.vi create mode 100644 FantomModule/include/labview/macosx/getFileName.vi create mode 100644 FantomModule/include/labview/macosx/getFileSize.vi create mode 100644 FantomModule/include/labview/macosx/getFileSizeFromIterator.vi create mode 100644 FantomModule/include/labview/macosx/getFilenameFromIterator.vi create mode 100644 FantomModule/include/labview/macosx/getFirmwareVersion.vi create mode 100644 FantomModule/include/labview/macosx/getIOMapSize.vi create mode 100644 FantomModule/include/labview/macosx/getModule.vi create mode 100644 FantomModule/include/labview/macosx/getModuleID.vi create mode 100644 FantomModule/include/labview/macosx/getModuleName.vi create mode 100644 FantomModule/include/labview/macosx/getModuleNameFromIterator.vi create mode 100644 FantomModule/include/labview/macosx/getModuleSize.vi create mode 100644 FantomModule/include/labview/macosx/getNXTFromIterator.vi create mode 100644 FantomModule/include/labview/macosx/getResourceString.vi create mode 100644 FantomModule/include/labview/macosx/getStringFromNXTIterator.vi create mode 100644 FantomModule/include/labview/macosx/isPaired.vi create mode 100644 FantomModule/include/labview/macosx/nakedRead.vi create mode 100644 FantomModule/include/labview/macosx/nakedWrite.vi create mode 100644 FantomModule/include/labview/macosx/nxt.ctl create mode 100644 FantomModule/include/labview/macosx/openForRead.vi create mode 100644 FantomModule/include/labview/macosx/openForWrite.vi create mode 100644 FantomModule/include/labview/macosx/pairBluetooth.vi create mode 100644 FantomModule/include/labview/macosx/pollAvailableLength.vi create mode 100644 FantomModule/include/labview/macosx/read.vi create mode 100644 FantomModule/include/labview/macosx/readBufferData.vi create mode 100644 FantomModule/include/labview/macosx/readIOMap.vi create mode 100644 FantomModule/include/labview/macosx/remove.vi create mode 100644 FantomModule/include/labview/macosx/sendDirectCommand.vi create mode 100644 FantomModule/include/labview/macosx/setNXTName.vi create mode 100644 FantomModule/include/labview/macosx/unpairBluetooth.vi create mode 100644 FantomModule/include/labview/macosx/write.vi create mode 100644 FantomModule/include/labview/macosx/writeIOMap.vi create mode 100644 FantomModule/include/labview/win32/advanceFileIterator.vi create mode 100644 FantomModule/include/labview/win32/advanceModuleIterator.vi create mode 100644 FantomModule/include/labview/win32/advanceNXTIterator.vi create mode 100644 FantomModule/include/labview/win32/bluetoothFactoryReset.vi create mode 100644 FantomModule/include/labview/win32/bootSamba.vi create mode 100644 FantomModule/include/labview/win32/closeFile.vi create mode 100644 FantomModule/include/labview/win32/createFile.vi create mode 100644 FantomModule/include/labview/win32/createFileIterator.vi create mode 100644 FantomModule/include/labview/win32/createModule.vi create mode 100644 FantomModule/include/labview/win32/createModuleIterator.vi create mode 100644 FantomModule/include/labview/win32/createNXT.vi create mode 100644 FantomModule/include/labview/win32/createNXTIterator.vi create mode 100644 FantomModule/include/labview/win32/destroyFile.vi create mode 100644 FantomModule/include/labview/win32/destroyFileIterator.vi create mode 100644 FantomModule/include/labview/win32/destroyModule.vi create mode 100644 FantomModule/include/labview/win32/destroyModuleIterator.vi create mode 100644 FantomModule/include/labview/win32/destroyNXT.vi create mode 100644 FantomModule/include/labview/win32/destroyNXTIterator.vi create mode 100644 FantomModule/include/labview/win32/downloadFirmware.vi create mode 100644 FantomModule/include/labview/win32/eraseUserFlash.vi create mode 100644 FantomModule/include/labview/win32/findDeviceInFirmwareDownloadMode.vi create mode 100644 FantomModule/include/labview/win32/findNXT.vi create mode 100644 FantomModule/include/labview/win32/getAvailableSize.vi create mode 100644 FantomModule/include/labview/win32/getDeviceInfo.vi create mode 100644 FantomModule/include/labview/win32/getFile.vi create mode 100644 FantomModule/include/labview/win32/getFileName.vi create mode 100644 FantomModule/include/labview/win32/getFileSize.vi create mode 100644 FantomModule/include/labview/win32/getFileSizeFromIterator.vi create mode 100644 FantomModule/include/labview/win32/getFilenameFromIterator.vi create mode 100644 FantomModule/include/labview/win32/getFirmwareVersion.vi create mode 100644 FantomModule/include/labview/win32/getIOMapSize.vi create mode 100644 FantomModule/include/labview/win32/getModule.vi create mode 100644 FantomModule/include/labview/win32/getModuleID.vi create mode 100644 FantomModule/include/labview/win32/getModuleName.vi create mode 100644 FantomModule/include/labview/win32/getModuleNameFromIterator.vi create mode 100644 FantomModule/include/labview/win32/getModuleSize.vi create mode 100644 FantomModule/include/labview/win32/getNXTFromIterator.vi create mode 100644 FantomModule/include/labview/win32/getResourceString.vi create mode 100644 FantomModule/include/labview/win32/getStringFromNXTIterator.vi create mode 100644 FantomModule/include/labview/win32/isPaired.vi create mode 100644 FantomModule/include/labview/win32/nakedRead.vi create mode 100644 FantomModule/include/labview/win32/nakedWrite.vi create mode 100644 FantomModule/include/labview/win32/nxt.ctl create mode 100644 FantomModule/include/labview/win32/openForRead.vi create mode 100644 FantomModule/include/labview/win32/openForWrite.vi create mode 100644 FantomModule/include/labview/win32/pairBluetooth.vi create mode 100644 FantomModule/include/labview/win32/pollAvailableLength.vi create mode 100644 FantomModule/include/labview/win32/read.vi create mode 100644 FantomModule/include/labview/win32/readBufferData.vi create mode 100644 FantomModule/include/labview/win32/readIOMap.vi create mode 100644 FantomModule/include/labview/win32/remove.vi create mode 100644 FantomModule/include/labview/win32/sendDirectCommand.vi create mode 100644 FantomModule/include/labview/win32/setNXTName.vi create mode 100644 FantomModule/include/labview/win32/unpairBluetooth.vi create mode 100644 FantomModule/include/labview/win32/write.vi create mode 100644 FantomModule/include/labview/win32/writeIOMap.vi create mode 100644 FantomModule/visatype.h diff --git a/FantomModule/FantomModule.cp b/FantomModule/FantomModule.cp new file mode 100644 index 0000000..60bbe80 --- /dev/null +++ b/FantomModule/FantomModule.cp @@ -0,0 +1,133 @@ +/* + * FantomModule.cp + * FantomModule + * + * Created by tcmac on 01/03/2011. + * Copyright 2011 TC Wan. All rights reserved. + * + * Based on code from Fantom Driver 1.0.2f0 Example + * © Copyright 2006, + * National Instruments Corporation. + * All rights reserved. + * + * Originated: 10 March 2006 + * + */ + +#include +#include +#include "FantomModule.h" +#include "FantomModulePriv.h" + +static PyMethodDef FantomMethods[] = { + {"finddevices", fantom_finddevices, METH_VARARGS, + "Find a NXT Device"}, + {"socket", fantom_socket, METH_VARARGS, + "Create a Socket for a NXT Brick"}, + {"connect", fantom_connect, METH_VARARGS, + "Connect the Socket to a NXT Brick"}, + {"send", fantom_send, METH_VARARGS, + "Send Data via the Socket to a NXT Brick"}, + {"recv", fantom_recv, METH_VARARGS, + "Receive Data via the Socket from a NXT Brick"}, + {"close", fantom_close, METH_VARARGS, + "Close the Socket to a NXT Brick"}, + {NULL, NULL, 0, NULL} /* Sentinel */ +}; + +extern "C" PyMODINIT_FUNC +initspam(void) +{ + (void) Py_InitModule("fantom", FantomMethods); +} + +extern "C" PyObject *fantom_finddevices(PyObject *py_self, PyObject *py_args) +{ + FantomModule *fantomObject; + fantomObject = new FantomModule; + + PyObject *list = fantomObject->finddevices(py_self,py_args); + delete fantomObject; + + return list; +} +extern "C" PyObject *fantom_socket(PyObject *py_self, PyObject *py_args) +{ +} + +extern "C" PyObject *fantom_connect(PyObject *py_self, PyObject *py_args) +{ +} + +extern "C" PyObject *fantom_send(PyObject *py_self, PyObject *py_args) +{ +} + +extern "C" PyObject *fantom_recv(PyObject *py_self, PyObject *py_args) +{ +} + +extern "C" PyObject *fantom_close(PyObject *py_self, PyObject *py_args) +{ +} + +PyObject *FantomModule::finddevices(PyObject *py_self, PyObject *py_args) +{ + const char *proto; + if (!PyArg_ParseTuple(py_args, "s", &proto)) + return NULL; + + ViBoolean useBT; + useBT = strcmp(proto, FANTOM_BT) ? true : false; + +/* + const char *command; + int sts; + + if (!PyArg_ParseTuple(py_args, "s", &command)) + return NULL; + sts = system(command); + return Py_BuildValue("i", sts); +*/ + + // Create an NXT iterator object which is used to find all accessible NXT devices. + nxtIteratorPtr = nFANTOM100::iNXT::createNXTIterator(useBT, FANTOM_BT_TIMEOUTSEC, status); + + // Creating the NXT iterator object could fail, better check status before dereferencing a + // potentially NULL pointer. + if( status.isNotFatal()) + { + ViChar nxtName[FANTOM_NXTNAME_LEN]; + nxtIteratorPtr->getName(nxtName, status); + if( status.isNotFatal()) + { + // FIXME: Append to Python list + } + nxtIteratorPtr->advance(status); + + } + // Destroy the NXT iterator object which we no longer need + nFANTOM100::iNXT::destroyNXTIterator( nxtIteratorPtr ); + +} + +PyObject *FantomModule::socket(PyObject *py_self, PyObject *py_args) +{ + // Create an NXT object for the first NXT that was found. Note that if a NXT is found + // over BT, the computer and the NXT must be paired before an NXT object can be + // created. This can be done programatically using the iNXT::pairBluetooth method. + // nxtPtr = nxtIteratorPtr->getNXT( status ); +} + +void FantomModule::HelloWorld(const char * s) +{ + FantomModulePriv *theObj = new FantomModulePriv; + theObj->HelloWorldPriv(s); + delete theObj; +}; + +void FantomModulePriv::HelloWorldPriv(const char * s) +{ + std::cout << s << std::endl; +}; + diff --git a/FantomModule/FantomModule.h b/FantomModule/FantomModule.h new file mode 100644 index 0000000..91e7575 --- /dev/null +++ b/FantomModule/FantomModule.h @@ -0,0 +1,49 @@ +/* + * FantomModule.h + * FantomModule + * + * Created by tcmac on 01/03/2011. + * Copyright 2011 __MyCompanyName__. All rights reserved. + * + */ + +#ifndef FantomModule_ +#define FantomModule_ + +#include +#include "fantom/iNXT.h" +#include "fantom/iNXTIterator.h" +#include "fantom/tStatus.h" + +#define FANTOM_BT "BT" +#define FANTOM_USB "USB" +#define FANTOM_BT_TIMEOUTSEC 2 +#define FANTOM_NXTNAME_LEN 256 + +/* The classes below are exported */ +#pragma GCC visibility push(default) + +extern "C" PyMODINIT_FUNC initspam(void); + +extern "C" PyObject *fantom_finddevices(PyObject *py_self, PyObject *py_args); +extern "C" PyObject *fantom_socket(PyObject *py_self, PyObject *py_args); +extern "C" PyObject *fantom_connect(PyObject *py_self, PyObject *py_args); +extern "C" PyObject *fantom_send(PyObject *py_self, PyObject *py_args); +extern "C" PyObject *fantom_recv(PyObject *py_self, PyObject *py_args); +extern "C" PyObject *fantom_close(PyObject *py_self, PyObject *py_args); + +class FantomModule +{ + nFANTOM100::tStatus status; + nFANTOM100::iNXTIterator* nxtIteratorPtr; + nFANTOM100::iNXT* nxtPtr; + + public: + PyObject *finddevices(PyObject *py_self, PyObject *py_args); + PyObject *socket(PyObject *py_self, PyObject *py_args); + + void HelloWorld(const char *); +}; + +#pragma GCC visibility pop +#endif diff --git a/FantomModule/FantomModule.xcodeproj/project.pbxproj b/FantomModule/FantomModule.xcodeproj/project.pbxproj new file mode 100644 index 0000000..c85a049 --- /dev/null +++ b/FantomModule/FantomModule.xcodeproj/project.pbxproj @@ -0,0 +1,293 @@ +// !$*UTF8*$! +{ + archiveVersion = 1; + classes = { + }; + objectVersion = 45; + objects = { + +/* Begin PBXBuildFile section */ + 43B531D2131C92690016BF14 /* Python in Frameworks */ = {isa = PBXBuildFile; fileRef = 43B531D1131C92690016BF14 /* Python */; }; + 43B531F2131C962E0016BF14 /* iFile.h in Headers */ = {isa = PBXBuildFile; fileRef = 43B531EA131C962E0016BF14 /* iFile.h */; }; + 43B531F3131C962E0016BF14 /* iFileIterator.h in Headers */ = {isa = PBXBuildFile; fileRef = 43B531EB131C962E0016BF14 /* iFileIterator.h */; }; + 43B531F4131C962E0016BF14 /* iModule.h in Headers */ = {isa = PBXBuildFile; fileRef = 43B531EC131C962E0016BF14 /* iModule.h */; }; + 43B531F5131C962E0016BF14 /* iModuleIterator.h in Headers */ = {isa = PBXBuildFile; fileRef = 43B531ED131C962E0016BF14 /* iModuleIterator.h */; }; + 43B531F6131C962E0016BF14 /* iNXT.h in Headers */ = {isa = PBXBuildFile; fileRef = 43B531EE131C962E0016BF14 /* iNXT.h */; }; + 43B531F7131C962E0016BF14 /* iNXTIterator.h in Headers */ = {isa = PBXBuildFile; fileRef = 43B531EF131C962E0016BF14 /* iNXTIterator.h */; }; + 43B531F8131C962E0016BF14 /* platform.h in Headers */ = {isa = PBXBuildFile; fileRef = 43B531F0131C962E0016BF14 /* platform.h */; }; + 43B531F9131C962E0016BF14 /* tStatus.h in Headers */ = {isa = PBXBuildFile; fileRef = 43B531F1131C962E0016BF14 /* tStatus.h */; }; + 43B531FB131C963A0016BF14 /* visatype.h in Headers */ = {isa = PBXBuildFile; fileRef = 43B531FA131C963A0016BF14 /* visatype.h */; }; + 43B5320A131C975B0016BF14 /* Fantom in Frameworks */ = {isa = PBXBuildFile; fileRef = 43B53209131C975B0016BF14 /* Fantom */; }; + 50149BDA09E781A5002DEE6A /* FantomModule.h in Headers */ = {isa = PBXBuildFile; fileRef = 50149BD909E781A5002DEE6A /* FantomModule.h */; }; + 5073E0CB09E734E500EC74B6 /* FantomModule.cp in Sources */ = {isa = PBXBuildFile; fileRef = 5073E0C409E734A800EC74B6 /* FantomModule.cp */; }; +/* End PBXBuildFile section */ + +/* Begin PBXFileReference section */ + 32BAE0B70371A74B00C91783 /* FantomModule_Prefix.pch */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = FantomModule_Prefix.pch; sourceTree = ""; }; + 43B531D1131C92690016BF14 /* Python */ = {isa = PBXFileReference; lastKnownFileType = "compiled.mach-o.dylib"; name = Python; path = /System/Library/Frameworks/Python.framework/Python; sourceTree = ""; }; + 43B531EA131C962E0016BF14 /* iFile.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = iFile.h; sourceTree = ""; }; + 43B531EB131C962E0016BF14 /* iFileIterator.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = iFileIterator.h; sourceTree = ""; }; + 43B531EC131C962E0016BF14 /* iModule.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = iModule.h; sourceTree = ""; }; + 43B531ED131C962E0016BF14 /* iModuleIterator.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = iModuleIterator.h; sourceTree = ""; }; + 43B531EE131C962E0016BF14 /* iNXT.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = iNXT.h; sourceTree = ""; }; + 43B531EF131C962E0016BF14 /* iNXTIterator.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = iNXTIterator.h; sourceTree = ""; }; + 43B531F0131C962E0016BF14 /* platform.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = platform.h; sourceTree = ""; }; + 43B531F1131C962E0016BF14 /* tStatus.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = tStatus.h; sourceTree = ""; }; + 43B531FA131C963A0016BF14 /* visatype.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = visatype.h; sourceTree = ""; }; + 43B53209131C975B0016BF14 /* Fantom */ = {isa = PBXFileReference; lastKnownFileType = "compiled.mach-o.dylib"; name = Fantom; path = /Library/Frameworks/Fantom.framework/Fantom; sourceTree = ""; }; + 50149BD909E781A5002DEE6A /* FantomModule.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = FantomModule.h; sourceTree = ""; }; + 5073E0C409E734A800EC74B6 /* FantomModule.cp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = FantomModule.cp; sourceTree = ""; }; + 5073E0C609E734A800EC74B6 /* FantomModuleProj.xcconfig */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = text.xcconfig; path = FantomModuleProj.xcconfig; sourceTree = ""; }; + 5073E0C709E734A800EC74B6 /* FantomModuleTarget.xcconfig */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = text.xcconfig; path = FantomModuleTarget.xcconfig; sourceTree = ""; }; + 50B2938909F016FC00694E55 /* FantomModulePriv.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = FantomModulePriv.h; sourceTree = ""; }; + D2AAC09D05546B4700DB518D /* libFantomModule.dylib */ = {isa = PBXFileReference; explicitFileType = "compiled.mach-o.dylib"; includeInIndex = 0; path = libFantomModule.dylib; sourceTree = BUILT_PRODUCTS_DIR; }; +/* End PBXFileReference section */ + +/* Begin PBXFrameworksBuildPhase section */ + D2AAC09B05546B4700DB518D /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + 43B531D2131C92690016BF14 /* Python in Frameworks */, + 43B5320A131C975B0016BF14 /* Fantom in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXFrameworksBuildPhase section */ + +/* Begin PBXGroup section */ + 034768DDFF38A45A11DB9C8B /* Products */ = { + isa = PBXGroup; + children = ( + D2AAC09D05546B4700DB518D /* libFantomModule.dylib */, + ); + name = Products; + sourceTree = ""; + }; + 0867D691FE84028FC02AAC07 /* FantomModule */ = { + isa = PBXGroup; + children = ( + 43B531FA131C963A0016BF14 /* visatype.h */, + 43B531E9131C962E0016BF14 /* fantom */, + 5073E0CA09E734BC00EC74B6 /* Configuration Files */, + 08FB77ACFE841707C02AAC07 /* Source */, + 0867D69AFE84028FC02AAC07 /* External Frameworks and Libraries */, + 034768DDFF38A45A11DB9C8B /* Products */, + ); + name = FantomModule; + sourceTree = ""; + }; + 0867D69AFE84028FC02AAC07 /* External Frameworks and Libraries */ = { + isa = PBXGroup; + children = ( + 43B53209131C975B0016BF14 /* Fantom */, + 43B531D1131C92690016BF14 /* Python */, + ); + name = "External Frameworks and Libraries"; + sourceTree = ""; + }; + 08FB77ACFE841707C02AAC07 /* Source */ = { + isa = PBXGroup; + children = ( + 32BAE0B70371A74B00C91783 /* FantomModule_Prefix.pch */, + 50149BD909E781A5002DEE6A /* FantomModule.h */, + 50B2938909F016FC00694E55 /* FantomModulePriv.h */, + 5073E0C409E734A800EC74B6 /* FantomModule.cp */, + ); + name = Source; + sourceTree = ""; + }; + 43B531E9131C962E0016BF14 /* fantom */ = { + isa = PBXGroup; + children = ( + 43B531EA131C962E0016BF14 /* iFile.h */, + 43B531EB131C962E0016BF14 /* iFileIterator.h */, + 43B531EC131C962E0016BF14 /* iModule.h */, + 43B531ED131C962E0016BF14 /* iModuleIterator.h */, + 43B531EE131C962E0016BF14 /* iNXT.h */, + 43B531EF131C962E0016BF14 /* iNXTIterator.h */, + 43B531F0131C962E0016BF14 /* platform.h */, + 43B531F1131C962E0016BF14 /* tStatus.h */, + ); + path = fantom; + sourceTree = ""; + }; + 5073E0CA09E734BC00EC74B6 /* Configuration Files */ = { + isa = PBXGroup; + children = ( + 5073E0C609E734A800EC74B6 /* FantomModuleProj.xcconfig */, + 5073E0C709E734A800EC74B6 /* FantomModuleTarget.xcconfig */, + ); + name = "Configuration Files"; + sourceTree = ""; + }; +/* End PBXGroup section */ + +/* Begin PBXHeadersBuildPhase section */ + D2AAC09905546B4700DB518D /* Headers */ = { + isa = PBXHeadersBuildPhase; + buildActionMask = 2147483647; + files = ( + 50149BDA09E781A5002DEE6A /* FantomModule.h in Headers */, + 43B531F2131C962E0016BF14 /* iFile.h in Headers */, + 43B531F3131C962E0016BF14 /* iFileIterator.h in Headers */, + 43B531F4131C962E0016BF14 /* iModule.h in Headers */, + 43B531F5131C962E0016BF14 /* iModuleIterator.h in Headers */, + 43B531F6131C962E0016BF14 /* iNXT.h in Headers */, + 43B531F7131C962E0016BF14 /* iNXTIterator.h in Headers */, + 43B531F8131C962E0016BF14 /* platform.h in Headers */, + 43B531F9131C962E0016BF14 /* tStatus.h in Headers */, + 43B531FB131C963A0016BF14 /* visatype.h in Headers */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXHeadersBuildPhase section */ + +/* Begin PBXNativeTarget section */ + D2AAC09C05546B4700DB518D /* FantomModule */ = { + isa = PBXNativeTarget; + buildConfigurationList = 1DEB916008733D950010E9CD /* Build configuration list for PBXNativeTarget "FantomModule" */; + buildPhases = ( + D2AAC09905546B4700DB518D /* Headers */, + D2AAC09B05546B4700DB518D /* Frameworks */, + D2AAC09A05546B4700DB518D /* Sources */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = FantomModule; + productName = libFantomModule; + productReference = D2AAC09D05546B4700DB518D /* libFantomModule.dylib */; + productType = "com.apple.product-type.library.dynamic"; + }; +/* End PBXNativeTarget section */ + +/* Begin PBXProject section */ + 0867D690FE84028FC02AAC07 /* Project object */ = { + isa = PBXProject; + buildConfigurationList = 1DEB916408733D950010E9CD /* Build configuration list for PBXProject "FantomModule" */; + compatibilityVersion = "Xcode 3.1"; + developmentRegion = English; + hasScannedForEncodings = 1; + knownRegions = ( + English, + Japanese, + French, + German, + ); + mainGroup = 0867D691FE84028FC02AAC07 /* FantomModule */; + productRefGroup = 034768DDFF38A45A11DB9C8B /* Products */; + projectDirPath = ""; + projectRoot = ""; + targets = ( + D2AAC09C05546B4700DB518D /* FantomModule */, + ); + }; +/* End PBXProject section */ + +/* Begin PBXSourcesBuildPhase section */ + D2AAC09A05546B4700DB518D /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 5073E0CB09E734E500EC74B6 /* FantomModule.cp in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXSourcesBuildPhase section */ + +/* Begin XCBuildConfiguration section */ + 1DEB916108733D950010E9CD /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 5073E0C709E734A800EC74B6 /* FantomModuleTarget.xcconfig */; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + COPY_PHASE_STRIP = NO; + GCC_DYNAMIC_NO_PIC = NO; + GCC_ENABLE_FIX_AND_CONTINUE = YES; + GCC_MODEL_TUNING = G5; + GCC_OPTIMIZATION_LEVEL = 0; + GCC_PRECOMPILE_PREFIX_HEADER = YES; + GCC_PREFIX_HEADER = FantomModule_Prefix.pch; + LIBRARY_SEARCH_PATHS = ( + "$(inherited)", + "\"$(SYSTEM_LIBRARY_DIR)/Frameworks/Python.framework\"", + "\"$(LOCAL_LIBRARY_DIR)/Frameworks/Fantom.framework\"", + ); + }; + name = Debug; + }; + 1DEB916208733D950010E9CD /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 5073E0C709E734A800EC74B6 /* FantomModuleTarget.xcconfig */; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + GCC_MODEL_TUNING = G5; + GCC_PRECOMPILE_PREFIX_HEADER = YES; + GCC_PREFIX_HEADER = FantomModule_Prefix.pch; + LIBRARY_SEARCH_PATHS = ( + "$(inherited)", + "\"$(SYSTEM_LIBRARY_DIR)/Frameworks/Python.framework\"", + "\"$(LOCAL_LIBRARY_DIR)/Frameworks/Fantom.framework\"", + ); + STRIP_INSTALLED_PRODUCT = YES; + STRIP_STYLE = "non-global"; + }; + name = Release; + }; + 1DEB916508733D950010E9CD /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 5073E0C609E734A800EC74B6 /* FantomModuleProj.xcconfig */; + buildSettings = { + ARCHS = "$(ARCHS_STANDARD_32_64_BIT)"; + GCC_C_LANGUAGE_STANDARD = gnu99; + GCC_OPTIMIZATION_LEVEL = 0; + GCC_WARN_ABOUT_RETURN_TYPE = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + HEADER_SEARCH_PATHS = /usr/include/python2.6/; + ONLY_ACTIVE_ARCH = YES; + PREBINDING = NO; + SDKROOT = macosx10.6; + }; + name = Debug; + }; + 1DEB916608733D950010E9CD /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 5073E0C609E734A800EC74B6 /* FantomModuleProj.xcconfig */; + buildSettings = { + ARCHS = "$(ARCHS_STANDARD_32_64_BIT)"; + GCC_C_LANGUAGE_STANDARD = gnu99; + GCC_WARN_ABOUT_RETURN_TYPE = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + PREBINDING = NO; + SDKROOT = macosx10.6; + }; + name = Release; + }; +/* End XCBuildConfiguration section */ + +/* Begin XCConfigurationList section */ + 1DEB916008733D950010E9CD /* Build configuration list for PBXNativeTarget "FantomModule" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 1DEB916108733D950010E9CD /* Debug */, + 1DEB916208733D950010E9CD /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 1DEB916408733D950010E9CD /* Build configuration list for PBXProject "FantomModule" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 1DEB916508733D950010E9CD /* Debug */, + 1DEB916608733D950010E9CD /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; +/* End XCConfigurationList section */ + }; + rootObject = 0867D690FE84028FC02AAC07 /* Project object */; +} diff --git a/FantomModule/FantomModulePriv.h b/FantomModule/FantomModulePriv.h new file mode 100644 index 0000000..54e0775 --- /dev/null +++ b/FantomModule/FantomModulePriv.h @@ -0,0 +1,19 @@ +/* + * FantomModulePriv.h + * FantomModule + * + * Created by tcmac on 01/03/2011. + * Copyright 2011 __MyCompanyName__. All rights reserved. + * + */ + +/* The classes below are not exported */ +#pragma GCC visibility push(hidden) + +class FantomModulePriv +{ + public: + void HelloWorldPriv(const char *); +}; + +#pragma GCC visibility pop diff --git a/FantomModule/FantomModuleProj.xcconfig b/FantomModule/FantomModuleProj.xcconfig new file mode 100644 index 0000000..363b2d1 --- /dev/null +++ b/FantomModule/FantomModuleProj.xcconfig @@ -0,0 +1,6 @@ + PREBINDING = NO; + GCC_WARN_ABOUT_RETURN_TYPE = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + GCC_MODEL_TUNING = G5; + GCC_INCREASE_PRECOMPILED_HEADER_SHARING = YES; + GCC_GENERATE_DEBUGGING_SYMBOLS = YES; diff --git a/FantomModule/FantomModuleTarget.xcconfig b/FantomModule/FantomModuleTarget.xcconfig new file mode 100644 index 0000000..63f1a7e --- /dev/null +++ b/FantomModule/FantomModuleTarget.xcconfig @@ -0,0 +1,11 @@ + PRODUCT_NAME = libFantomModule; + INSTALL_PATH = /usr/local/lib; + MACH_O_TYPE = mh_dylib; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + GCC_PRECOMPILE_PREFIX_HEADER = YES; + GCC_PREFIX_HEADER = FantomModule_Prefix.pch; + GCC_ENABLE_CPP_EXCEPTIONS = YES; + GCC_ENABLE_CPP_RTTI = YES; + STANDARD_C_PLUS_PLUS_LIBRARY_TYPE = Dynamic; + GCC_SYMBOLS_PRIVATE_EXTERN = YES; diff --git a/FantomModule/FantomModule_Prefix.pch b/FantomModule/FantomModule_Prefix.pch new file mode 100644 index 0000000..031204e --- /dev/null +++ b/FantomModule/FantomModule_Prefix.pch @@ -0,0 +1,6 @@ +// +// Prefix header for all source files of the 'FantomModule' target in the 'FantomModule' project. +// + + +#include diff --git a/FantomModule/fantom/iFile.h b/FantomModule/fantom/iFile.h new file mode 100644 index 0000000..d9884f9 --- /dev/null +++ b/FantomModule/fantom/iFile.h @@ -0,0 +1,280 @@ +/*! + \file iFile.h + \brief Interface for a file on a LEGO MINDSTORMS NXT. +*/ +/* + © Copyright 2005-2006, + National Instruments Corporation. + All rights reserved. + + File: iFile.h + Originated: 12 May 2005 +*/ + +#ifndef ___fantom_iFile_h___ +#define ___fantom_iFile_h___ + +// includes... + +#ifndef ___fantom_platform_h___ + #include "platform.h" +#endif + +#ifndef ___fantom_tStatus_h___ + #include "tStatus.h" +#endif + + +// defines... + + +namespace nFANTOM100 +{ + // forward declarations... + + // typedefs... + + // classes... + + /*! + \class iFile + \brief Interface to a file on a LEGO MINDSTORMS NXT. + */ + class iFile + { + friend class tNXT; + + // methods + protected: + + //! Destructor + virtual ~iFile() = 0; + + public: + + //! Retrieves the name of this file. + /*! + \param fileName Populated with the name of this file. The file name character array + must be able to accomodate a NULL-terminated, 15.3 formatted module name. That + is, it must have a capacity of 20 bytes. + */ + virtual void getName( ViChar fileName[] ) const = 0; + + //! Retrieves the total size of this file in bytes. + /*! + The returned size is undefined if the specified status is fatal. + + \param status Status chaining object. + \return The total size of this file in bytes. + */ + virtual ViUInt32 getSize( tStatus& status ) = 0; + + //! Retrieves the remaining available size, in bytes, in this file. + /*! + This number is only helpful for data logging files, which can contain variable + amounts of data. + The returned size is undefined if the specified status is fatal. + + \param status Status chaining object. + \return The remaining available size, in bytes, in this file. + */ + virtual ViUInt32 getAvailableSize( tStatus& status ) = 0; + + + //! Opens this file for reading. + /*! + Opens, for reading, the file that corresponds to this object on the associated NXT. + The file is not opened if the specified status is fatal. + + \param status Status chaining object. + */ + virtual void openForRead( tStatus& status ) = 0; + + + //! Open this file for writing. + /*! + Opens, for writing, the file that corresponds to this object on the associated NXT. + If this file doesn't exist on the NXT, it is created. If this file does exist on + the NXT, an error is generated. + The file is not opened if the specified status is fatal. + + \param sizeInBytes Size of the data, in bytes, that will be written to this file. + \param status Status chaining object. + */ + virtual void openForWrite( ViUInt32 sizeInBytes, tStatus& status ) = 0; + + + //! Open this file for linear (contiguous) writing. + /*! + Opens, for linear (contiguous) writing, the file that corresponds to this object on + the associated NXT. If this file doesn't exist on the NXT, it is created. If this + file does exist on the NXT, an error is generated. + The file is not opened if the specified status is fatal. + + \param sizeInBytes Size of the data, in bytes, that will be written to the file. + \param status Status chaining object. + */ + virtual void openForLinearWrite( ViUInt32 sizeInBytes, tStatus& status ) = 0; + + + //! Open this data file for writing. + /*! + Opens, for writing, the data file that corresponds to this object on the associated + NXT. This data file differs from normal files in that a data file can be closed + before the entire file has been written. If this file doesn't exist on the NXT, + it is created. If this file does exist on the NXT, an error is generated. + The file is not opened if the specified status is fatal. + + \param sizeInBytes Size of the data, in bytes, that may be written to the file. + \param status Status chaining object. + */ + virtual void openForDataWrite( ViUInt32 sizeInBytes, tStatus& status ) = 0; + + + //! Open this data file for appending additional data. + /*! + Opens, for appending additional data, the data file that corresponds to this object + on the associated NXT. If this file doesn't exist on the NXT, the behavior is + undefined. If this file does exist on the NXT, the data that is written is + appended to the end of the exiting data. + The file is not opened if the specified status is fatal. + + \param status Status chaining object. + */ + virtual void openForDataAppend( tStatus& status ) = 0; + + + //! Closes this file. + /*! + Closes the file that corresponds to this object on the associated NXT. + The file is not closed if the specified status is fatal. + + \param status Status chaining object. + */ + virtual void close( tStatus& status ) = 0; + + + //! Reads from this file + /*! + Reads the specified number of bytes from this file into the specified buffer. No data + is read if the specified status is fatal. The ownership of the buffer is not + transferred to this file object. + + \param bufferPtr A pointer to the buffer that will be populated with the data that is + read. The capacity of the specified buffer must be at least the specified number + of bytes. + \param numberOfBytes Number of bytes to read. + \param status Status chaining object. + \return The number of bytes actually read from this file. + + \pre This file must have been opened for reading with the iFile::openForRead method. + \post The specified buffer may be deallocated. + */ + virtual ViUInt32 read( ViPBuf bufferPtr, ViUInt32 numberOfBytes, tStatus& status ) = 0; + + + //! Writes to this file + /*! + Writes the specified number of bytes from the specified buffer to this file. No data + is written if the specified status is fatal. The ownership of the buffer is not + transferred to this file object. + + \param bufferPtr A pointer to the buffer that contains the data that will be written. + The capacity of the specified buffer must be at least the specified number of + bytes. + \param numberOfBytes Number of bytes to write to this file. + \param status Status chaining object. + \return The number of bytes actually written to this file. + + \pre This file must have previously been opened for writing. + \post The specified buffer may be deallocated. + */ + virtual ViUInt32 write( const ViByte bufferPtr[], ViUInt32 numberOfBytes, + tStatus& status ) = 0; + + + //! Removes this file + /*! + Removes the file that corresponds to this object on the associated NXT. + The file is not removed if the specified status is fatal. + + \param status Status chaining object. + */ + virtual void remove( tStatus& status ) = 0; + + }; + + + // constants... + const ViUInt8 kProtocolFilenameLength = 19; // 15 basename + 1 dot + 3 extension = 19 + +} // namespace nFANTOM100 + + + // declarations for globally-scoped globals... + + // typedefs... + typedef ViObject nFANTOM100_iFile; + + // prototypes... + extern "C" + { + nFANTOM100_kExport void _VI_FUNCC nFANTOM100_iFile_getName( + nFANTOM100_iFile filePtr, + ViChar fileName[], + ViStatus* status ); + + nFANTOM100_kExport ViUInt32 _VI_FUNCC nFANTOM100_iFile_getSize( + nFANTOM100_iFile filePtr, + ViStatus* status ); + + nFANTOM100_kExport ViUInt32 _VI_FUNCC nFANTOM100_iFile_getAvailableSize( + nFANTOM100_iFile filePtr, + ViStatus* status ); + + nFANTOM100_kExport void _VI_FUNCC nFANTOM100_iFile_openForRead( + nFANTOM100_iFile filePtr, + ViStatus* status ); + + nFANTOM100_kExport void _VI_FUNCC nFANTOM100_iFile_openForWrite( + nFANTOM100_iFile filePtr, + ViUInt32 sizeInBytes, + ViStatus* status ); + + nFANTOM100_kExport void _VI_FUNCC nFANTOM100_iFile_openForLinearWrite( + nFANTOM100_iFile filePtr, + ViUInt32 sizeInBytes, + ViStatus* status ); + + nFANTOM100_kExport void _VI_FUNCC nFANTOM100_iFile_openForDataWrite( + nFANTOM100_iFile filePtr, + ViUInt32 sizeInBytes, + ViStatus* status ); + + nFANTOM100_kExport void _VI_FUNCC nFANTOM100_iFile_openForDataAppend( + nFANTOM100_iFile filePtr, + ViStatus* status ); + + nFANTOM100_kExport void _VI_FUNCC nFANTOM100_iFile_close( + nFANTOM100_iFile filePtr, + ViStatus* status ); + + nFANTOM100_kExport void _VI_FUNCC nFANTOM100_iFile_read( + nFANTOM100_iFile filePtr, + ViPBuf bufferPtr, + ViUInt32 numberOfBytes, + ViStatus* status ); + + nFANTOM100_kExport void _VI_FUNCC nFANTOM100_iFile_write( + nFANTOM100_iFile filePtr, + const ViByte bufferPtr[], + ViUInt32 numberOfBytes, + ViStatus* status ); + + nFANTOM100_kExport void _VI_FUNCC nFANTOM100_iFile_remove( + nFANTOM100_iFile filePtr, + ViStatus* status ); + + } + +#endif // ___fantom_iFile_h___ diff --git a/FantomModule/fantom/iFileIterator.h b/FantomModule/fantom/iFileIterator.h new file mode 100644 index 0000000..5803be8 --- /dev/null +++ b/FantomModule/fantom/iFileIterator.h @@ -0,0 +1,133 @@ +/*! + \file iFileIterator.h + \brief Interface for an iterator for files on a LEGO MINDSTORMS NXT. +*/ +/* + © Copyright 2005-2006, + National Instruments Corporation. + All rights reserved. + + File: iFileIterator.h + Originated: 12 May 2005 +*/ + +#ifndef ___fantom_iFileIterator_h___ +#define ___fantom_iFileIterator_h___ + + +// includes... + +#ifndef ___fantom_platform_h___ + #include "platform.h" +#endif + +#ifndef ___fantom_iFile_h___ + #include "iFile.h" +#endif + +#ifndef ___fantom_tStatus_h___ + #include "tStatus.h" +#endif + + +// defines... + + +namespace nFANTOM100 +{ + // forward declarations... + + // typedefs... + + // classes... + + /*! + \class iFileIterator + \brief Interface to an iterator for files on a LEGO MINDSTORMS NXT. + */ + class iFileIterator + { + friend class tNXT; + + // methods + protected: + + //! Destructor + virtual ~iFileIterator() = 0; + + public: + + //! Creates a file object for the file referenced by this iterator. + /*! + Creates file object for the file referenced by this iterator. An object is not + created if the specified status is fatal or if this iterator refers to the end of + the list. The returned file object should be destroyed using the + iNXT::destroyFile method. + + \param status Status chaining object. + \return A pointer to the iFile object that was created. + */ + virtual iFile* getFile( tStatus& status ) = 0; + + //! Advances this iterator. + /*! + Advances this iterator to the next file that matches the previously specified file + name pattern. If no more files match, this iterator is advanced to the end of the + list. + The iterator is not advanced if the specified status is fatal. + If this iterator is already at the end of the list, a fatal status will be generated. + + \param status Status chaining object. + */ + virtual void advance( tStatus& status ) = 0; + + //! Retrieves the name of the file to which this iterator refers. + /*! + \param fileName Populated with the name of the file to which this iterator refers. + The file name character array must be able to accomodate a NULL-terminated, 15.3 + formatted file name. This is, it must have a capacity of 20 bytes. + \param status Status chaining object. + */ + virtual void getName( ViChar fileName[], tStatus& status ) = 0; + + //! Retrieves the total size, in bytes, of the file to which this iterator refers. + /*! + \param status Status chaining object. + \return The total size of the file in bytes. + */ + virtual ViUInt32 getSize( tStatus& status ) = 0; + + }; + + + // constants... + +} // namespace nFANTOM100 + + + // declarations for globally-scoped globals... + + // typedefs + typedef ViObject nFANTOM100_iFileIterator; + + extern "C" + { + nFANTOM100_kExport nFANTOM100_iFile _VI_FUNCC nFANTOM100_iFileIterator_getFile( + nFANTOM100_iFileIterator iteratorPtr, + ViStatus* status ); + + nFANTOM100_kExport void _VI_FUNCC nFANTOM100_iFileIterator_advance( + nFANTOM100_iFileIterator iteratorPtr, + ViStatus* status ); + + nFANTOM100_kExport void _VI_FUNCC nFANTOM100_iFileIterator_getName( + nFANTOM100_iFileIterator iteratorPtr, + ViChar filename[], + ViStatus* status ); + + nFANTOM100_kExport ViUInt32 _VI_FUNCC nFANTOM100_iFileIterator_getSize( + nFANTOM100_iFileIterator iteratorPtr, + ViStatus* status ); + } + +#endif // ___fantom_iFileIterator_h___ diff --git a/FantomModule/fantom/iModule.h b/FantomModule/fantom/iModule.h new file mode 100644 index 0000000..1f03849 --- /dev/null +++ b/FantomModule/fantom/iModule.h @@ -0,0 +1,154 @@ +/*! + \file iModule.h + \brief Interface for a firmware module on a LEGO MINDSTORMS NXT. +*/ +/* + © Copyright 2005-2006, + National Instruments Corporation. + All rights reserved. + + File: iModule.h + Originated: 8 Aug 2005 +*/ + +#ifndef ___fantom_iModule_h___ +#define ___fantom_iModule_h___ + +#ifndef ___fantom_platform_h___ + #include "platform.h" +#endif + +#ifndef ___fantom_tStatus_h___ + #include "tStatus.h" +#endif + + +// defines... + + +namespace nFANTOM100 +{ + + /*! + \class iModule + \brief Interface to a firmware module on a LEGO MINDSTORMS NXT. + */ + class iModule + { + friend class tNXT; + + // methods + protected: + + //! Destructor + virtual ~iModule() = 0; + + public: + + //! Retrieves the name of this module. + /*! + \param moduleName Populated with the name of this module. The module name character + array must be able to accomodate a NULL-terminated, 15.3 formatted module name. + That is, it must have a capacity of 20 bytes. + */ + virtual void getName( ViChar moduleName[] ) const = 0; + + //! Retrieves the internal module ID of this module. + /*! + \return The internal module ID of this module. + */ + virtual ViUInt32 getModuleID( void ) const = 0; + + //! Retrieves the size in bytes of this module. + /*! + \return The size in bytes of this module. + */ + virtual ViUInt32 getModuleSize( void ) const = 0; + + //! Retrieves the size in bytes of the I/O map associated with this module. + /*! + \return The size in bytes of the I/O map associated with this module. + */ + virtual ViUInt32 getModuleIOMapSize( void ) const = 0; + + //! Reads a portion of this module's I/O map. + /*! + Reads the data located at [I/O map address] + [specified offset in bytes] into the + specified data buffer. The read will attempt to copy the specified number of + bytes. No read occurs if the specified status is fatal. The ownership of data + buffer is not transferred to this module object. + + \param offsetInBytes The index of the byte in the I/O map at which to start the read. + \param numberOfBytes The number of bytes that should be read from the I/O map. + \param dataBufferPtr A pointer to the data buffer that will be populated with the + data that is read. The capacity of the specified data buffer must be at least the + specified number of bytes. + \param status Status chaining object. + \return The number of bytes actually read from the I/O map. + + \post The specified data buffer may be deallocated. + */ + virtual ViUInt32 readIOMap( ViUInt32 offsetInBytes, ViUInt32 numberOfBytes, + ViPBuf dataBufferPtr, tStatus& status ) = 0; + + //! Writes a portion of this module's I/O map. + /*! + Writes the specified data into this module's I/O map. The write starts at [I/O map + address] + [specified offset in bytes] and stops after the specified number of + bytes have been written. No write occurs if the specified status is fatal. The + ownership of data buffer is not transferred to this module object. + + \param offsetInBytes The index of the byte in the I/O map at which to start the write. + \param numberOfBytes The number of bytes to write into the I/O map. + \param dataBufferPtr A pointer to the data buffer that contains the data that will be + written. The capacity of the specified data buffer must be at least the specified + number of bytes. + \param status Status chaining object. + \return The number of bytes actually written into the I/O map. + + \post The specified data buffer may be deallocated. + */ + virtual ViUInt32 writeIOMap( ViUInt32 offsetInBytes, ViUInt32 numberOfBytes, + const ViByte dataBufferPtr[], tStatus& status ) = 0; + + }; + +}; // nFANTOM100 + +typedef ViObject nFANTOM100_iModule; + +extern "C" +{ + nFANTOM100_kExport void _VI_FUNCC nFANTOM100_iModule_getName( + nFANTOM100_iModule modulePtr, + ViChar moduleName[], + ViStatus* status ); + + nFANTOM100_kExport ViUInt32 _VI_FUNCC nFANTOM100_iModule_getModuleID( + nFANTOM100_iModule modulePtr, + ViStatus* status ); + + nFANTOM100_kExport ViUInt32 _VI_FUNCC nFANTOM100_iModule_getModuleSize( + nFANTOM100_iModule modulePtr, + ViStatus* status ); + + nFANTOM100_kExport ViUInt32 _VI_FUNCC nFANTOM100_iModule_getIOMapSize( + nFANTOM100_iModule modulePtr, + ViStatus* status ); + + nFANTOM100_kExport ViUInt32 _VI_FUNCC nFANTOM100_iModule_readIOMap( + nFANTOM100_iModule modulePtr, + ViUInt32 offset, + ViUInt32 numberBytesToRead, + ViPBuf dataBuffer, + ViStatus* status ); + + nFANTOM100_kExport ViUInt32 _VI_FUNCC nFANTOM100_iModule_writeIOMap( + nFANTOM100_iModule modulePtr, + ViUInt32 offset, + ViUInt32 numberBytesToWrite, + const ViByte dataBuffer[], + ViStatus* status ); +} + +#endif // ___fantom_iModule_h___ diff --git a/FantomModule/fantom/iModuleIterator.h b/FantomModule/fantom/iModuleIterator.h new file mode 100644 index 0000000..402bf1a --- /dev/null +++ b/FantomModule/fantom/iModuleIterator.h @@ -0,0 +1,123 @@ +/*! + \file iModuleIterator.h + \brief Interface for an iterator for firmware modules on a LEGO MINDSTORMS NXT. +*/ +/* + © Copyright 2005-2006, + National Instruments Corporation. + All rights reserved. + + File: iModuleIterator.h + Originated: 8 Aug 2005 +*/ + +#ifndef ___fantom_iModuleIterator_h___ +#define ___fantom_iModuleIterator_h___ + + +// includes... + +#ifndef ___fantom_platform_h___ + #include "platform.h" +#endif + +#ifndef ___fantom_iModule_h___ + #include "iModule.h" +#endif + +#ifndef ___fantom_tStatus_h___ + #include "tStatus.h" +#endif + + +// defines... + + +namespace nFANTOM100 +{ + // forward declarations... + + // typedefs... + + // classes... + + /*! + \class iModuleIterator + \brief Interface to an iterator for firmware modules on a LEGO MINDSTORMS NXT. + */ + class iModuleIterator + { + friend class tNXT; + + // methods + protected: + + //! Destructor + virtual ~iModuleIterator() = 0; + + public: + + //! Creates a module object for the module referenced by this iterator. + /*! + Creates a module object for the module referenced by this iterator. An object is not + created if the specified status is fatal or if this iterator refers to the end of + the list. The returned module object should be destroyed using the + iNXT::destroyModule method. + + \param status Status chaining object. + \return A pointer to the iModule object that was created. + */ + virtual iModule* getModule( tStatus& status ) = 0; + + //! Advances this iterator. + /*! + Advances this iterator to the next module that matches the previously specified + module name pattern. If no more modules match, this iterator is advanced to the + end of the list. + The iterator is not advanced if the specified status is fatal. + If this iterator is already at the end of the list, a fatal status will be generated. + + \param status Status chaining object. + */ + virtual void advance( tStatus& status ) = 0; + + //! Retrieves the name of the module to which this iterator refers. + /*! + \param moduleName Populated with the name of the module to which this iterator + refers. The module name character array must be able to accomodate a + NULL-terminated, 15.3 formatted module name. This is, it must have a capacity of + 20 bytes. + \param status Status chaining object. + */ + virtual void getName( ViChar moduleName[], tStatus& status ) = 0; + + }; + + + // constants... + +} // namespace nFANTOM100 + + + // declarations for globally-scoped globals... + + // typedefs + typedef ViObject nFANTOM100_iModuleIterator; + + extern "C" + { + nFANTOM100_kExport nFANTOM100_iModule _VI_FUNCC nFANTOM100_iModuleIterator_getModule( + nFANTOM100_iModuleIterator iteratorPtr, + ViStatus* status ); + + nFANTOM100_kExport void _VI_FUNCC nFANTOM100_iModuleIterator_advance( + nFANTOM100_iModuleIterator iteratorPtr, + ViStatus* status ); + + nFANTOM100_kExport void _VI_FUNCC nFANTOM100_iModuleIterator_getName( + nFANTOM100_iModuleIterator iteratorPtr, + ViChar moduleName[], + ViStatus* status ); + } + +#endif // ___fantom_iModuleIterator_h___ diff --git a/FantomModule/fantom/iNXT.h b/FantomModule/fantom/iNXT.h new file mode 100644 index 0000000..ba61db8 --- /dev/null +++ b/FantomModule/fantom/iNXT.h @@ -0,0 +1,666 @@ +/*! + \file iNXT.h + \brief Interface for a LEGO MINDSTORMS NXT and declaration of its factory. +*/ +/* + © Copyright 2005-2006, + National Instruments Corporation. + All rights reserved. + + File: iNXT.h + Originated: 12 May 2005 +*/ + +#ifndef ___fantom_iNXT_h___ +#define ___fantom_iNXT_h___ + + +// includes... + +#ifndef ___fantom_platform_h___ + #include "platform.h" +#endif + +#ifndef ___fantom_iFile_h___ + #include "iFile.h" +#endif + +#ifndef ___fantom_iFileIterator_h___ + #include "iFileIterator.h" +#endif + +#ifndef ___fantom_iModule_h___ + #include "iModule.h" +#endif + +#ifndef ___fantom_iModuleIterator_h___ + #include "iModuleIterator.h" +#endif + +#ifndef ___fantom_iNXTIterator_h___ + #include "iNXTIterator.h" +#endif + +#ifndef ___fantom_tStatus_h___ + #include "tStatus.h" +#endif + +// defines... + + +namespace nFANTOM100 +{ + // forward declarations... + + // typedefs... + + // classes... + + /*! + \class iNXT + \brief Interface to a LEGO MINDSTORMS NXT. + */ + class iNXT + { + // methods + protected: + + //! Destructor + virtual ~iNXT() = 0; + + public: + + //! Enumeration of buffer types on the NXT + enum tBuffer + { + // The buffer associated with the standard port. + kBufferStandard, + + // The buffer associated with the high-speed port. + kBufferHighSpeed + }; + + //! Creates a file object for the file with the specified name on this NXT. + /*! + Invoking this method does not actually create a file on the NXT. Rather, this method + creates a file object which may be used to open a file on this NXT, for reading or + writing, or may be used to delete a file on the NXT. + A file is not created if the specified status is fatal. + The returned file object should be destroyed using the iNXT::destroyFile method. + + \param fileName Name of the file. The file name must conform to the 15.3 naming + convention and be NULL-terminated. + \param status Status chaining object. + \return A pointer to the iFile object that was created. + */ + virtual iFile* createFile( ViConstString fileName, tStatus& status ) = 0; + + + //! Destroys the specified file object. + /*! + Invoking this method does not actually delete a file on the NXT. Rather, this method + destroys a file object which may have been used to open a file on this NXT for + reading or writing, or may have been used to delete a file on the NXT. + + \param filePtr Pointer to the file object to destroy. + */ + virtual void destroyFile( iFile* filePtr ) = 0; + + + //! Creates an iterator to the files on this NXT. + /*! + The iterator traverses those files on this NXT that match the specified file name + pattern. + The iterator is not created if the specified status is fatal. + The returned file iterator object should be destroyed using the + iNXT::destroyFileIterator method. + + \param fileNamePattern The file name pattern against which to match when iterating + over the files on this NXT. The file name pattern may contain wildcards. The + wildcards may be used in the following manner: *.* (all files on this NXT); + fileBaseName.* (all files on this NXT with the specified base name regardless of + extension); *.fileExtension (all files on this NXT with the specified extension, + regardless of basename); fileBaseName.fileExtension (the file on this NXT with the + specified base name and extension). + \param status Status chaining object. + \return A pointer to the iFileIterator object that was created. + */ + virtual iFileIterator* createFileIterator( ViConstString fileNamePattern, + tStatus& status ) = 0; + + + //! Destroys the specified file iterator. + /*! + \param fileIteratorPtr A pointer to the file iterator to destroy. + */ + virtual void destroyFileIterator( iFileIterator* fileIteratorPtr ) = 0; + + //! Creates a module object for the module with the specified name on this NXT. + /*! + Invoking this method does not actually create a module on the NXT. Rather, this + method creates a module object which may be used to access an I/O map on this NXT. + A module is not created if the specified status is fatal. + The returned module object should be destroyed using the iNXT::destroyModule method. + + \param moduleName The name of the module. The module name must conform to the 15.3 + naming convention and be NULL-terminated. + \param moduleID The NXT-internal ID of the module. + \param moduleSizeInBytes The number of bytes the module occupies. + \param ioMapSizeInBytes The number of bytes the module's I/O map occupies. + \param status Status chaining object. + \return A pointer to the iModule object that was created. + */ + virtual iModule* createModule( ViConstString moduleName, ViUInt32 moduleID, + ViUInt32 moduleSizeInBytes, ViUInt32 ioMapSizeInBytes, tStatus& status ) = 0; + + //! Destroys the specified module object. + /*! + Invoking this method does not actually delete a module on this NXT. Rather, this + method destroys a module object which may have been used to access an I/O map on + this NXT. + + \param modulePtr Pointer to the module object to destroy. + */ + virtual void destroyModule( iModule* modulePtr ) = 0; + + + //! Creates an iterator to the modules on this NXT. + /*! + The iterator traverses those modules on this NXT that match the specified module name + pattern. + The iterator is not created if the specified status is fatal. + The returned module iterator object should be destroyed using the + iNXT::destroyModuleIterator method. + + \param moduleNamePattern The module name pattern against which to match. The module + name pattern may contain wildcards. Since extensions are implicit in the case of + modules, a wildcard may only be used for the module name, as in "*.mod". + \param status Status chaining object. + \return A pointer to an iModuleIterator object that was created. + */ + virtual iModuleIterator* createModuleIterator( ViConstString moduleNamePattern, + tStatus& status ) = 0; + + + //! Destroys the specified module iterator. + /*! + \param moduleIteratorPtr A pointer to the module iterator object to destroy. + */ + virtual void destroyModuleIterator( iModuleIterator* moduleIteratorPtr ) = 0; + + //! Retrieves the firmware version of this NXT. + /*! + Returns the protocol and firmware versions installed on this NXT. + The current version of this driver supports a protocol major version number of 1 and a + firmware major version number of 1. If either of these major version numbers is a + value other than 1, the driver will not attempt to communicate to the NXT. + The returned versions are undefined if the specified status is fatal. + + \param protocolVersionMajorRef Reference to parameter that will be populated with the + major protocol version. + \param protocolVersionMinorRef Reference to parameter that will be populated with the + minor protocol version. + \param firmwareVersionMajorRef Reference to parameter that will be populated with the + major firmware verison. + \param firmwareVersionMinorRef Reference to parameter that will be populated with the + minor firmware verison. + \param status Status chaining object. + */ + virtual void getFirmwareVersion( ViUInt8& protocolVersionMajorRef, + ViUInt8& protocolVersionMinorRef, ViUInt8& firmwareVersionMajorRef, + ViUInt8& firmwareVersionMinorRef, tStatus& status ) = 0; + + + //! Sends the specified direct command to this NXT. + /*! + For more information on direct commands, refer to the LEGO MINDSTORMS NXT Direct + commands document. + The command is not sent if the specified status is fatal. + The command buffer must be non-NULL and the command buffer size in bytes must be + non-zero. + If require response is set to true, the response buffer must be non-NULL and the + response buffer size in bytes must be non-zero. + If require response is set to false, the response buffer must be NULL and the + response buffer size in bytes must be zero. + Both of the buffer size parameters must be small enough to fit in one packet for + whichever bus the NXT is connected over (USB or Bluetooth). This means the + maximum length for a direct command over USB is 63 bytes; over Bluetooth, 65,533 + bytes. + If any of these requirements are violated, VI_ERROR_USER_BUF will be returned. + + \param requireResponse Boolean flag indicating if a response is required. + \param commandBufferPtr Buffer containing the direct command to send to the NXT. + \param commandBufferSizeInBytes Number of bytes in the command buffer. + \param responseBufferPtr Buffer that will be populated with the response to the direct + command. + \param responseBufferSizeInBytes Capacity of the response buffer in bytes. + \param status Status chaining object. + \return Number of bytes written to the response buffer. + */ + virtual ViUInt32 sendDirectCommand( ViBoolean requireResponse, const ViByte commandBufferPtr[], + ViUInt32 commandBufferSizeInBytes, ViPBuf responseBufferPtr, + ViUInt32 responseBufferSizeInBytes, tStatus& status ) = 0; + + //! Downloads firmware to this NXT. + /*! + The NXT must already be in firmware-download mode. + + \param firmwareBufferPtr The buffer containing the new firmware binary image. + \param firmwareBufferSizeInBytes The number of bytes in the new firmware image. + \param status Status chaining object. + */ + virtual void downloadFirmware( const ViByte firmwareBufferPtr[], + ViUInt32 firmwareBufferSizeInBytes, tStatus& status ) = 0; + + + //! Writes, in a generic fashion, to this NXT. + /*! + Writes a command directly to this NXT. In general, this method isn't used and, + instead, the sendDirectCommand and other more specific methods are invoked when + communication to the NXT. + The write doesn not occur if the specified status is fatal. + + \param bufferPtr A pointer to the buffer that contains the command that will be + written. + \param numberOfBytes Size of the buffer. + \param status Status chaining object. + \return The number of bytes actually written to the NXT. + */ + virtual ViUInt32 write( const ViByte bufferPtr[], ViUInt32 numberOfBytes, + tStatus& status ) = 0; + + //! Reads, in a generic fashion, from this NXT. + /*! + Reads a response directly from this NXT. In general, this method isn't used and, + instead, the sendDirectCommand and other more specific methods are invoked when + communication to the NXT. + The command is not sent if the specified status is fatal. + + \param bufferPtr A pointer to the buffer that will be populated with the response. + \param numberOfBytes Number of bytes expected to be read from this NXT. + \param status Status chaining object. + \return The number of bytes actually read from this NXT. + */ + virtual ViUInt32 read ( ViPBuf bufferPtr, ViUInt32 numberOfBytes, tStatus& status ) = 0; + + //! Reboots this NXT into firmware-download mode. + /*! + This is required before invoking the downloadFirmware method. + The reboot does not occur is the specified status is fatal. + + \param status Status chaining object. + */ + virtual void bootIntoFirmwareDownloadMode( tStatus& status ) = 0; + + //! Sets the name of this NXT. + /*! + The specified name will be displayed on the NXT, show up during Bluetooth scans, and + returned when the getDeviceInfo method is called. + + \param newName The name for the NXT. The name can be at most 15 characters. However, + the NXT can only display 8 characters. The string must be NULL terminated. + \param status Status chaining object. + */ + virtual void setName( ViConstString newName, tStatus& status ) = 0; + + //! Retrieves basic information about this NXT. + /*! + Retrieves the name of this NXT, its Bluetooth address, the Bluetooth signal strength, + and the number of bytes available. + Information retrieval is not done if specified status is fatal. + + \param name Populated with the name of this NXT. The name character array must be + able to accomodate a NULL-terminated 15 character name. That is, it must have a + capacity of 16 bytes. + \param bluetoothAddress Populated with this NXT's Bluetooth address. The bluetooth + address array must have a capacity of six bytes. + \param signalStrength Populated with strength of the signal for this NXT's four + Bluetooth conenctions. The signal strength array must have a capacity of four + bytes. + \param availableFlash Populated with the amount of memory in bytes that is not + occupied by firmware or user files. + \param status Status chaining object. + */ + virtual void getDeviceInfo( ViChar name[], ViByte bluetoothAddress[], + ViUInt8 signalStrength[], ViUInt32 &availableFlash, tStatus& status ) = 0; + + //! Erases all files from this NXT, leaving only the firmware. + /*! + All programs, sounds, and data logs are erased. + The erasure does not occur if specified status is fatal. + + \param status Status chaining object. + */ + virtual void eraseUserFlash( tStatus& status ) = 0; + + //! Polls the data buffer on this NXT for the number of bytes available to be read. + /* + The data buffer is not polled if the specified status is fatal. + + \param bufferSelector The buffer from which to read. + \param status Status chaining object. + \return The number of bytes in the buffer available to be read. + */ + virtual ViUInt32 pollAvailableLength( tBuffer bufferSelector, tStatus& status ) = 0; + + //! Reads data from the data buffer on this NXT. + /*! + Data is not read if the specified status is fatal. + + \param dataBuffer Populated with the data that is read from the specified buffer. + \param bufferSelector The buffer from which to read. + \param numberOfBytesToRead The number of bytes to read from the data buffer. + \param status Status chaining object. + \return The number of bytes actually read from the data buffer. + */ + virtual ViUInt32 readBufferData( ViPBuf dataBuffer, tBuffer bufferSelector, + ViUInt32 numberOfBytesToRead, tStatus& status ) = 0; + + //! Retrieves the resource string for this NXT's session. + /* + An example resource string could look like the one of the following: + BTH::LEGOBrick::00:16:53:04:05:06::5 + BTH::LEGOBrick::00:16:53:04:05:06::1 + BTH::Brick2::00:16:53:44:FF:66 + USB0::0x0694::0x0002::0016535127BA::RAW + + \param resourceString Populated with the resource string. The resource string must + have a capacity of 256 bytes. + \param status Status chaining object. + */ + virtual void getResourceString( ViChar resourceString[], tStatus& status ) = 0; + + //! Resets the Bluetooth module on this NXT to its factory settings. + /* + \param status Status chaining object. + */ + virtual void bluetoothFactoryReset( tStatus& status ) = 0; + + //! Creates an NXT object + /*! + Creates an NXT object representing the specified NXT. + The NXT object is not created if the specified status is fatal. + The returned NXT object should be destroyed using the iNXT::destroyNXT method. + + \param resourceString A string identifying which resource should be opened. A list + of possible strings can be obtained using an iNXTIterator (refer to the + createNXTIterator method). + \param status Status chaining object. + \param checkFirmwareVersion A boolean flag that specifies whether version validation + should occur (defaults to true). + \return A pointer to the iNXT object that was created. + */ + nFANTOM100_kExport static iNXT* _VI_FUNCC createNXT( ViConstString resourceString, + tStatus& status, ViBoolean checkFirmwareVersion = true ); + + //! Destroys an NXT object + /*! + \param nxtPtr A pointer to the NXT object to destroy; may be NULL + */ + nFANTOM100_kExport static void _VI_FUNCC destroyNXT( iNXT* nxtPtr ); + + //! Creates an NXT iterator. + /*! + The NXT iterator can be used to find all NXTs that are connected (USB) or in range + (Bluetooth). + The NXT iterator is not created if the specified status is fatal. + The returned NXT iterator object should be destroyed using the + iNXT::destroyNXTIterator method. + + \param searchBluetooth A boolean flag that specifies if the iterator should traverse + NXTs via Bluetooth. + \param bluetoothSearchTimeoutInSeconds The minimum number of seconds that should be + spent waiting for Bluetooth devices to respond. + \param status Status chaining object. + \return A pointer to the iNXTIterator object that was created. + */ + nFANTOM100_kExport static iNXTIterator* _VI_FUNCC createNXTIterator( + ViBoolean searchBluetooth, ViUInt32 bluetoothSearchTimeoutInSeconds, + tStatus& status ); + + //! Destroys an NXT iterator object. + /* + \param iterPtr A pointer to the iNXTIterator object to destroy. + */ + nFANTOM100_kExport static void _VI_FUNCC destroyNXTIterator( iNXTIterator* iterPtr ); + + //! Pairs with an NXT via Bluetooth. + /*! + Programmatically pairs the specified NXT to this computer and, on Windows, creates a + virtual serial port to use for communication with that NXT. However, clients + should not depend on the creation of this virtual serial port. + The pairing is not done if the specified status is fatal. + + \param resourceName The resource string that specifies the NXT with which to pair. + \param passkey A string containing the passkey the computer should exchange with the + device. The passkey cannot be longer than 15 characters and must be + NULL-terminated. + \param pairedResourceName A Bluetooth resource string representing the paired device. + On Windows, the specified resourceName is suffixed with the COM port; On Mac OS X, + the RFCOMM channel identifier. The resource string must have a capacity of 256 + bytes. + \param status Status chaining object. + */ + nFANTOM100_kExport static void _VI_FUNCC pairBluetooth( ViConstString resourceName, + ViConstString passkey, ViChar pairedResourceName[], tStatus& status ); + + //! Unpairs with an NXT via Bluetooth. + /*! + Programmatically destroys the Bluetooth pairing that was previously established + between this computer and the specified NXT. On Mac OS X, this method has no + effect and doesn't generate a fatal status. + The unpairing is not done if the specified status is fatal. + + \param resourceName The resource string that specifies the NXT with which to unpair. + \param status Status chaining object. + */ + nFANTOM100_kExport static void _VI_FUNCC unpairBluetooth( ViConstString resourceName, + tStatus& status ); + + //! Determines if the NXT associated with the specified resource string is paired. + /*! + The determination is not done if the specified status is fatal. + + \param resourceName A resource string that specifies the NXT for which to check its + pairing status. + \param status Status chaining object. + \return VI_TRUE if the NXT is paired with this computer (or if it is connected via + USB); VI_FALSE otherwise. + */ + nFANTOM100_kExport static ViBoolean _VI_FUNCC isPaired( ViConstString resourceName, + tStatus& status ); + + //! Finds the NXT that is currently in firmware-download mode. + /*! + Note that only a single NXT may be in firmware-download mode at a time. + + \param resourceName Populated with the resource string. The resource string must + have a capacity of 256 bytes. + \param status Status chaining object. + */ + nFANTOM100_kExport static void findDeviceInFirmwareDownloadMode( ViChar resourceName[], + tStatus& status ); + + + private: + + }; + + // constants... + +} // namespace nFANTOM100 + + + // declarations for globally-scoped globals... + + // typedefs... + typedef ViObject nFANTOM100_iNXT; + + // prototypes... + extern "C" + { + + nFANTOM100_kExport nFANTOM100_iNXTIterator _VI_FUNCC nFANTOM100_createNXTIterator( + ViBoolean searchBluetooth, + ViUInt32 bluetoothSearchTimeoutInSeconds, + ViStatus* status ); + + nFANTOM100_kExport void _VI_FUNCC nFANTOM100_destroyNXTIterator( + nFANTOM100_iNXTIterator iterPtr, + ViStatus* status ); + + nFANTOM100_kExport void _VI_FUNCC nFANTOM100_pairBluetooth( + ViConstString resourceName, + ViConstString passkey, + ViChar pairedResourceName[], + ViStatus* status ); + + nFANTOM100_kExport void _VI_FUNCC nFANTOM100_unpairBluetooth( + ViConstString resourceName, + ViStatus* status ); + + nFANTOM100_kExport ViBoolean _VI_FUNCC nFANTOM100_isPaired( + ViConstString resourceName, + ViStatus* status ); + + nFANTOM100_kExport nFANTOM100_iNXT _VI_FUNCC nFANTOM100_createNXT( + ViConstString resourceString, + ViStatus* status, + ViBoolean checkFirmwareVersion ); + + nFANTOM100_kExport void _VI_FUNCC nFANTOM100_destroyNXT( + nFANTOM100_iNXT nxtPtr, + ViStatus* status ); + + nFANTOM100_kExport nFANTOM100_iFile _VI_FUNCC nFANTOM100_iNXT_createFile( + nFANTOM100_iNXT nxtPtr, + ViConstString fileName, + ViStatus* status ); + + nFANTOM100_kExport void _VI_FUNCC nFANTOM100_iNXT_destroyFile( + nFANTOM100_iNXT nxtPtr, + nFANTOM100_iFile filePtr, + ViStatus* status ); + + nFANTOM100_kExport nFANTOM100_iFileIterator _VI_FUNCC nFANTOM100_iNXT_createFileIterator( + nFANTOM100_iNXT nxtPtr, + ViConstString fileNamePattern, + ViStatus* status ); + + nFANTOM100_kExport void _VI_FUNCC nFANTOM100_iNXT_destroyFileIterator( + nFANTOM100_iNXT nxtPtr, + nFANTOM100_iFileIterator fileIteratorPtr, + ViStatus* status ); + + nFANTOM100_kExport nFANTOM100_iModule _VI_FUNCC nFANTOM100_iNXT_createModule( + nFANTOM100_iNXT nxtPtr, + ViConstString moduleName, + ViUInt32 moduleID, + ViUInt32 moduleSize, + ViUInt32 ioMapSizeInBytes, + ViStatus* status ); + + nFANTOM100_kExport void _VI_FUNCC nFANTOM100_iNXT_destroyModule( + nFANTOM100_iNXT nxtPtr, + nFANTOM100_iModule modulePtr, + ViStatus* status ); + + nFANTOM100_kExport nFANTOM100_iModuleIterator _VI_FUNCC nFANTOM100_iNXT_createModuleIterator( + nFANTOM100_iNXT nxtPtr, + ViConstString moduleNamePattern, + ViStatus* status ); + + nFANTOM100_kExport void _VI_FUNCC nFANTOM100_iNXT_destroyModuleIterator( + nFANTOM100_iNXT nxtPtr, + nFANTOM100_iModuleIterator moduleIteratorPtr, + ViStatus* status ); + + nFANTOM100_kExport void _VI_FUNCC nFANTOM100_iNXT_getFirmwareVersion( + nFANTOM100_iNXT nxtPtr, + ViUInt8* protocolVersionMajorPtr, + ViUInt8* protocolVersionMinorPtr, + ViUInt8* firmwareVersionMajorPtr, + ViUInt8* firmwareVersionMinorPtr, + ViStatus* status ); + + nFANTOM100_kExport ViUInt32 _VI_FUNCC nFANTOM100_iNXT_sendDirectCommand( + nFANTOM100_iNXT nxtPtr, + ViBoolean requireResponse, + const ViByte commandBufferPtr[], + ViUInt32 commandBufferSizeInBytes, + ViPBuf responseBufferPtr, + ViUInt32 responseBufferSizeInBytes, + ViStatus* status ); + + nFANTOM100_kExport void _VI_FUNCC nFANTOM100_iNXT_findDeviceInFirmwareDownloadMode( + ViChar resourceString[], + ViStatus* status ); + + nFANTOM100_kExport void _VI_FUNCC nFANTOM100_iNXT_downloadFirmware( + nFANTOM100_iNXT nxtPtr, + const ViByte firmwareBufferPtr[], + ViUInt32 firmwareBufferSize, + ViStatus* status ); + + nFANTOM100_kExport ViUInt32 _VI_FUNCC nFANTOM100_iNXT_write( + nFANTOM100_iNXT nxtPtr, + const ViByte bufferPtr[], + ViUInt32 numberOfBytes, + ViStatus* status ); + + nFANTOM100_kExport ViUInt32 _VI_FUNCC nFANTOM100_iNXT_read( + nFANTOM100_iNXT nxtPtr, + ViPBuf bufferPtr, + ViUInt32 numberOfBytes, + ViStatus* status ); + + nFANTOM100_kExport void _VI_FUNCC nFANTOM100_iNXT_bootIntoFirmwareDownloadMode( + ViConstString resouceName, + ViStatus* status ); + + nFANTOM100_kExport void _VI_FUNCC nFANTOM100_iNXT_setName( + nFANTOM100_iNXT nxtPtr, + ViConstString newName, + ViStatus* status ); + + nFANTOM100_kExport void _VI_FUNCC nFANTOM100_iNXT_getDeviceInfo( + nFANTOM100_iNXT nxtPtr, + ViChar name[], + ViByte bluetoothAddress[], + ViUInt8 signalStrength[], + ViUInt32* availableFlash, + ViStatus* status ); + + nFANTOM100_kExport void _VI_FUNCC nFANTOM100_iNXT_eraseUserFlash( + nFANTOM100_iNXT nxtPtr, + ViStatus* status ); + + nFANTOM100_kExport ViUInt32 _VI_FUNCC nFANTOM100_iNXT_pollAvailableLength( + nFANTOM100_iNXT nxtPtr, + ViUInt32 bufferIndex, + ViStatus* status ); + + nFANTOM100_kExport ViUInt32 _VI_FUNCC nFANTOM100_iNXT_readBufferData( + nFANTOM100_iNXT nxtPtr, + ViPBuf dataBuffer, + ViUInt32 bufferIndex, + ViUInt32 numberOfBytesToRead, + ViStatus* status ); + + nFANTOM100_kExport void _VI_FUNCC nFANTOM100_iNXT_getResourceString( + nFANTOM100_iNXT nxtPtr, + ViChar resourceString[], + ViStatus* status ); + + nFANTOM100_kExport void _VI_FUNCC nFANTOM100_iNXT_bluetoothFactoryReset( + nFANTOM100_iNXT nxtPtr, + ViStatus* status ); + + + } // extern "C" + + +// inline functions and function macros... + + +#endif // ___fantom_iNXT_h___ diff --git a/FantomModule/fantom/iNXTIterator.h b/FantomModule/fantom/iNXTIterator.h new file mode 100644 index 0000000..6f43537 --- /dev/null +++ b/FantomModule/fantom/iNXTIterator.h @@ -0,0 +1,120 @@ +/*! + \file iNXTIterator.h + \brief Interface used for searching for LEGO MINDSTORMS NXTs. +*/ +/* + © Copyright 2005-2006, + National Instruments Corporation. + All rights reserved. + + File: iNXTIterator.h + Originated: 17 Oct 2005 +*/ + +#ifndef ___fantom_iNXTIterator_h___ +#define ___fantom_iNXTIterator_h___ + + +// includes... + +#ifndef ___fantom_platform_h___ + #include "platform.h" +#endif + +#ifndef ___fantom_tStatus_h___ + #include "tStatus.h" +#endif + + +// defines... + + +namespace nFANTOM100 +{ + // forward declarations... + class iNXT; + + // typedefs... + + // classes... + + /*! + \class iNXTIterator + \brief Interface to an iterator for LEGO MINDSTORMS NXTs. + */ + class iNXTIterator + { + friend class iNXT; + + // methods + protected: + + //! Destructor + virtual ~iNXTIterator() = 0; + + public: + + //! Retrieves the name of the NXT to which this iterator refers. + /* + \param resourceName Populated with the name of the NXT to which this iterator + currently refers. The resource name character array must have a capacity of 256 + bytes. + \param status Status chaining object. + */ + virtual void getName( ViChar resourceName[], tStatus& status ) const = 0; + + //! Advances this iterator. + /*! + Advances this iterator to the next NXT that was found. If no more NXTs are found, + this iterator is advanced to the end of the list. + The iterator is not advanced if the specified status is fatal. + If this iterator is already at the end of the list, a fatal status will be generated. + + \param status Status chaining object. + */ + virtual void advance( tStatus& status ) = 0; + + //! Creates an NXT object for the NXT referenced by this iterator. + /* + Creates an NXT object for the NXT referenced by this iterator. An object is not + created if the specified status is fatal or if this iterator refers to the end of + the list. The returned iNXT object should be destroyed using the iNXT::destroyNXT + method. + + \param status Status chaining object. + \return A pointer to the iNXT object that was created. + */ + virtual iNXT* getNXT( tStatus& status ) = 0; + }; + + + // constants... + +} // namespace nFANTOM100 + + + // declarations for globally-scoped globals... + + // typedefs + typedef ViObject nFANTOM100_iNXTIterator; + + // we must duplicate this typedef for the getNXT C wrapper + typedef ViObject nFANTOM100_iNXT; + + extern "C" + { + nFANTOM100_kExport void _VI_FUNCC nFANTOM100_iNXTIterator_getName( + nFANTOM100_iNXTIterator iteratorPtr, + ViChar resourceName[], + ViStatus* status ); + + nFANTOM100_kExport void _VI_FUNCC nFANTOM100_iNXTIterator_advance( + nFANTOM100_iNXTIterator iteratorPtr, + ViStatus* status ); + + nFANTOM100_kExport nFANTOM100_iNXT _VI_FUNCC nFANTOM100_iNXTIterator_getNXT( + nFANTOM100_iNXTIterator iteratorPtr, + ViStatus* status ); + } + +#endif // ___fantom_iNXTIterator_h___ diff --git a/FantomModule/fantom/platform.h b/FantomModule/fantom/platform.h new file mode 100644 index 0000000..7455796 --- /dev/null +++ b/FantomModule/fantom/platform.h @@ -0,0 +1,94 @@ +/*! + \file platform.h + \brief This file contains platform-related defines. +*/ +/* + © Copyright 2005, + National Instruments Corporation. + All rights reserved. + + File: platform.h + Originated: 23 June 2005 +*/ + + +#ifndef ___fantom_platform_h___ +#define ___fantom_platform_h___ + +#ifndef __VISATYPE_HEADER__ + #include "visatype.h" +#endif + + +#define nFANTOM100_kOSMacOSX 0 +#define nFANTOM100_kOSWin32 0 + +#define nFANTOM100_kProcessorI386 0 +#define nFANTOM100_kProcessorPPC 0 + +#define nFANTOM100_kCompilerMSVC 0 +#define nFANTOM100_kCompilerApple 0 + + +#if (( defined( __GNUG__ ) || defined( __GNUC__ )) && defined( __APPLE__ )) + + #undef nFANTOM100_kOSMacOSX + #define nFANTOM100_kOSMacOSX 1 + + #undef nFANTOM100_kCompilerApple + #define nFANTOM100_kCompilerApple ( __GNUC__ * 10000 \ + + __GNUC_MINOR__ * 100 \ + + __GNUC_PATCHLEVEL__ ) + + #if ( defined( __ppc__ )) + #undef nFANTOM100_kProcessorPPC + #define nFANTOM100_kProcessorPPC 1 + + #define nFANTOM100_kBigEndian 1 + #define nFANTOM100_kLittleEndian 0 + #elif ( defined( __i386__ )) + #undef nFANTOM100_kProcessorI386 + #define nFANTOM100_kProcessorI386 1 + + #define nFANTOM100_kBigEndian 0 + #define nFANTOM100_kLittleEndian 1 + #else + #error Unknown processor. + #endif + + #ifdef nFANTOM100_kExportSymbols + #define nFANTOM100_kExport __attribute__ ((section ("__TEXT,__export"))) + #else + #define nFANTOM100_kExport + #endif + + +#elif ( defined( _MSC_VER ) && ( defined( _M_IX86 ) || defined( _M_I86 ))) + + #undef nFANTOM100_kOSWin32 + #define nFANTOM100_kOSWin32 1 + + #undef nFANTOM100_kCompilerMSVC + #define nFANTOM100_kCompilerMSVC _MSC_VER + + #undef nFANTOM100_kProcessorI386 + #define nFANTOM100_kProcessorI386 1 + + #ifdef nFANTOM100_kExportSymbols + #define nFANTOM100_kExport __declspec(dllexport) + #else + #define nFANTOM100_kExport __declspec(dllimport) + #endif + + #define nFANTOM100_kBigEndian 0 + #define nFANTOM100_kLittleEndian 1 + +#else + + #error Unknown platform. + +#endif + + +#endif // ___fantom_platform_h___ + diff --git a/FantomModule/fantom/tStatus.h b/FantomModule/fantom/tStatus.h new file mode 100644 index 0000000..7622c63 --- /dev/null +++ b/FantomModule/fantom/tStatus.h @@ -0,0 +1,458 @@ +/*! + \file tStatus.h + \brief Status code class +*/ +/* + © Copyright 2005-2006, + National Instruments Corporation. + All rights reserved. + + File: tStatus.h + Originated: 10 March 2005 +*/ + +#ifndef ___fantom_tStatus_h___ +#define ___fantom_tStatus_h___ + +// includes ... + +#ifndef ___fantom_platform_h___ + #include "platform.h" +#endif + +#include + + +// defines... + +#define nFANTOM_mLocation __FILE__, __LINE__ + +#define nFANTOM_ForceToWarning(s) (((s) >= 0 ) ? (s) : -(s)) +#define nFANTOM_ForceToFatal(s) (((s) <= 0 ) ? (s) : -(s)) + +/*! + \brief The namespace for Fantom 1.0. +*/ +namespace nFANTOM100 +{ + // forward declarations... + + // typedefs... + + // classes... + const ViInt32 kStatusOffset = -142000; // 0xFFFDD550 + const ViStatus kStatusSuccess = VI_SUCCESS; + + /*! + \brief Enumeration of Fantom-specific status codes. NI-VISA status codes may also be + returned. These are documented in the NI-VISA Programmer Reference Manual which is + available from . + */ + enum tFANTOMStatus + { + kStatusFirst = (kStatusOffset + 0), + + //! Error: Bluetooth pairing operation failed. + //! Warning: You have already paired with that Bluetooth device. + kStatusPairingFailed = (kStatusOffset + -5), // 0x54B + + //! Error: Bluetooth search failed. + kStatusBluetoothSearchFailed = (kStatusOffset + -6), // 0x54A + + //! Error: System library not found. + kStatusSystemLibraryNotFound = (kStatusOffset + -7), // 0x549 + + //! Error: Bluetooth unpairing operation failed. + kStatusUnpairingFailed = (kStatusOffset + -8), // 0x548 + + //! Error: Invalid filename specified. + kStatusInvalidFilename = (kStatusOffset + -9), // 0x547 + + //! Error: Invalid iterator dereference. (No object to get.) + kStatusInvalidIteratorDereference = (kStatusOffset + -10), // 0x546 + + //! Error: Resource locking operation failed. + kStatusLockOperationFailed = (kStatusOffset + -11), // 0x545 + + //! Error: Could not determine the requested size. + kStatusSizeUnknown = (kStatusOffset + -12), // 0x544 + + //! Error: Cannot open two objects at once. + kStatusDuplicateOpen = (kStatusOffset + -13), // 0x543 + + //! Error: File is empty. + //! Warning: The requested file is empty. + kStatusEmptyFile = (kStatusOffset + -14), // 0x542 + + //! Error: Firmware download failed. + kStatusFirmwareDownloadFailed = (kStatusOffset + -15), // 0x541 + + //! Error: Could not locate virtual serial port. + kStatusPortNotFound = (kStatusOffset + -16), // 0x540 + + //! Error: No more items found. + kStatusNoMoreItemsFound = (kStatusOffset + -17), // 0x53F + + //! Error: Too many unconfigured devices. + kStatusTooManyUnconfiguredDevices = (kStatusOffset + -18), // 0x53E + + //! Error: Command mismatch in firmware response. + kStatusCommandMismatch = (kStatusOffset + -19), // 0x53D + + //! Error: Illegal operation. + kStatusIllegalOperation = (kStatusOffset + -20), // 0x53C + + //! Error: Could not update local Bluetooth cache with new name. + //! Warning: Could not update local Bluetooth cache with new name. + kStatusBluetoothCacheUpdateFailed = (kStatusOffset + -21), // 0x53B + + //! Error: Selected device is not an NXT. + kStatusNonNXTDeviceSelected = (kStatusOffset + -22), // 0x53A + + //! Error: Communication error. Retry the operation. + kStatusRetryConnection = (kStatusOffset + -23), // 0x539 + + //! Error: Could not connect to NXT. Turn the NXT off and then back on before continuing. + kStatusPowerCycleNXT = (kStatusOffset + -24), // 0x538 + + //! Error: This feature is not yet implemented. + kStatusFeatureNotImplemented = (kStatusOffset + -99), // 0x4ED + + //! Error: Firmware reported an illegal handle. + kStatusFWIllegalHandle = (kStatusOffset + -189), // 0x493 + + //! Error: Firmware reported an illegal file name. + kStatusFWIllegalFileName = (kStatusOffset + -190), // 0x492 + + //! Error: Firmware reported an out of bounds reference. + kStatusFWOutOfBounds = (kStatusOffset + -191), // 0x491 + + //! Error: Firmware could not find module. + kStatusFWModuleNotFound = (kStatusOffset + -192), // 0x490 + + //! Error: Firmware reported that the file already exists. + kStatusFWFileExists = (kStatusOffset + -193), // 0x48F + + //! Error: Firmware reported that the file is full. + kStatusFWFileIsFull = (kStatusOffset + -194), // 0x48E + + //! Error: Firmware reported the append operation is not possible. + kStatusFWAppendNotPossible = (kStatusOffset + -195), // 0x48D + + //! Error: Firmware has no write buffers available. + kStatusFWNoWriteBuffers = (kStatusOffset + -196), // 0x48C + + //! Error: Firmware reported that file is busy. + kStatusFWFileIsBusy = (kStatusOffset + -197), // 0x48B + + //! Error: Firmware reported the undefined error. + kStatusFWUndefinedError = (kStatusOffset + -198), // 0x48A + + //! Error: Firmware reported that no linear space is available. + kStatusFWNoLinearSpace = (kStatusOffset + -199), // 0x489 + + //! Error: Firmware reported that handle has already been closed. + kStatusFWHandleAlreadyClosed = (kStatusOffset + -200), // 0x488 + + //! Error: Firmware could not find file. + kStatusFWFileNotFound = (kStatusOffset + -201), // 0x487 + + //! Error: Firmware reported that the requested file is not linear. + kStatusFWNotLinearFile = (kStatusOffset + -202), // 0x486 + + //! Error: Firmware reached the end of the file. + kStatusFWEndOfFile = (kStatusOffset + -203), // 0x485 + + //! Error: Firmware expected an end of file. + kStatusFWEndOfFileExpected = (kStatusOffset + -204), // 0x484 + + //! Error: Firmware cannot handle more files. + kStatusFWNoMoreFiles = (kStatusOffset + -205), // 0x483 + + //! Error: Firmware reported the NXT is out of space. + kStatusFWNoSpace = (kStatusOffset + -206), // 0x482 + + //! Error: Firmware could not create a handle. + kStatusFWNoMoreHandles = (kStatusOffset + -207), // 0x481 + + //! Error: Firmware reported an unknown error code. + kStatusFWUnknownErrorCode = (kStatusOffset + -208), // 0x480 + + kStatusLast = (kStatusOffset + -999) + }; + + /*! + \brief Class that contains a status code and the file name and line number where that + status code was generated. + */ + class tStatus + { + public: + + // methods + + //! constructor + /*! + Creates a tStatus object intialized to success. + + \post The status code is set to VI_SUCCESS. + */ + inline tStatus( void ) : + _code( VI_SUCCESS ), + _lineNumber( 0 ) + { + _fileName[0] = '\0'; + } + + + //! copy constructor + /*! + Copies the code, line number, and file name from the specified tStatus object. + + \param status The status object to copy. + */ + inline tStatus( const tStatus& status ) : + _code( status._code ), + _lineNumber( status._lineNumber ) + { + ::strcpy( _fileName, "" ); + ::strncat( _fileName, status._fileName, kMaxFileNameLength - 1 ); + } + + + //! constructor with code, filename, and line number + /*! + Creates a tStatus object initialized to the specified code, file name, and line number. + Note that the nFANTOM_mLocation macro can be used to pass the fileName and lineNumber + parameters. + + \param code A status code. + \param fileName The name of the file in which the status code was generated. + \param lineNumber The line number in the file at which the status code was generated. + */ + inline tStatus( ViStatus code, const char* fileName, ViUInt32 lineNumber ) : + _code( code ), + _lineNumber( lineNumber ) + { + ::strcpy( _fileName, "" ); + ::strncat( _fileName, reinterpret_cast( fileName ), kMaxFileNameLength - 1 ); + } + + + //! destructor + inline ~tStatus() + { + } + + + //! Returns the status code for this status object. + /*! + \return The status code for this status object. + */ + inline ViStatus getCode( void ) const + { + return _code; + } + + + //! Returns the file name in which the status code, for this status object, was generated. + /*! + \return The file name in which the status code, for this status object, was generated. + */ + inline const char* getFileName( void ) const + { + return _fileName; + } + + + //! Returns the line number at which the status code, for this status object, was + // generated. + /*! + \return The line number at which the status code, for this status object, was + generated. + */ + inline ViUInt32 getLineNumber( void ) const + { + return _lineNumber; + } + + + //! Sets the status code, file name, and line number for this status object, if + // appropriate. + /*! + Stores the specified status code, file name, and line number in this status object if + this status object contains a successful status code or if this status object + contains a warning status code and the specified status code is fatal. A fatal + status code is denoted by a negative value. A successful status code is denoted + by VI_SUCCESS. + + \param code A status code. + \param fileName The name of the file in which the status code was generated. + \param lineNumber The line number in the file at which the status code was generated. + */ + inline void setCode( ViStatus code, const char* fileName, ViUInt32 lineNumber ) + { + if(( isSuccess() && code != VI_SUCCESS ) || ( isNotFatal() && code < VI_SUCCESS )) + { + _code = code; + _lineNumber = lineNumber; + ::strcpy( _fileName, "" ); + ::strncat( _fileName, fileName, kMaxFileNameLength - 1 ); + } + } + + + //! Assigns the specified status object to this status object, if appropriate. + /*! + Stores the status code, file name, and line number of the specified status object in + this status object if this status object contains a successful status code or if + this status object contains a warning status code and the status code of the + speciied status object is fatal. A fatal status code is denoted by a negative + value. A successful status code is denoted by VI_SUCCESS. + + \param status The status object to assign. + */ + inline void assign( const tStatus& status ) + { + setCode( status.getCode(), status.getFileName(), status.getLineNumber()); + } + + + //! Clears the status code for this status object. + /*! + \post status The code is set to VI_SUCCESS. + */ + inline void clear( void ) + { + _code = VI_SUCCESS; + _lineNumber = 0; + _fileName[0] = '\0'; + } + + + //! Returns true if this status object contains a status code that is fatal. + /*! + A status code with a negative value is considered fatal. + + \return true if this status object contains a status code that is + fatal; false otherwise. + */ + inline bool isFatal( void ) const + { + return ( _code < VI_SUCCESS ); + } + + //! Returns true if this status object contains a status code that is not fatal. + /*! + Any status code with a non-negative (including zero) value is considered non-fatal. + + \return true if this status object contains a non-fatal status code; + false otherwise. + */ + inline bool isNotFatal( void ) const + { + return !isFatal(); + } + + + //! Returns true if this status object contains a status code that is a warning. + /*! + A status code with a non-zero, positive value is considered a warning. + + \return true if this status object contains a status code that is a warning; false + otherwise. + */ + inline bool isWarning( void ) const + { + return ( _code > VI_SUCCESS ); + } + + + //! Returns true if this status object contains the status code for success. + /*! + A value of VI_SUCCESS represents success. + + \return true if this status object contains the status code for success; false + otherwise. + */ + inline bool isSuccess( void ) const + { + return ( _code == VI_SUCCESS ); + } + + private: + + // declared private to prevent assignment + tStatus& operator=(const tStatus& rhs); + + enum + { + kMaxFileNameLength = 101 + }; + + ViStatus _code; + ViChar _fileName[ kMaxFileNameLength ]; + ViUInt32 _lineNumber; + }; + + + // declarations for globally-scoped globals... + inline ViStatus convertStatus( ViUInt8 firmwareStatus ) + { + ViStatus status; + switch (firmwareStatus) + { + // each of these cases corresponds to a unique status code returned by the firmware + case 0x00 : status = kStatusSuccess; + break; + case 0x81 : status = kStatusFWNoMoreHandles; // No more available handles + break; + case 0x82 : status = kStatusFWNoSpace; // No space + break; + case 0x83 : status = kStatusFWNoMoreFiles; // No more files + break; + case 0x84 : status = kStatusFWEndOfFileExpected; // End of file expected + break; + case 0x85 : status = kStatusFWEndOfFile; // End of file reached + break; + case 0x86 : status = kStatusFWNotLinearFile; // Not a linear file + break; + case 0x87 : status = kStatusFWFileNotFound; // File not found + break; + case 0x88 : status = kStatusFWHandleAlreadyClosed; // Handle is already closed + break; + case 0x89 : status = kStatusFWNoLinearSpace; // No linear space available + break; + case 0x8A : status = kStatusFWUndefinedError; // Undefined error + break; + case 0x8B : status = kStatusFWFileIsBusy; // File is busy + break; + case 0x8C : status = kStatusFWNoWriteBuffers; // No write buffers available + break; + case 0x8D : status = kStatusFWAppendNotPossible; // Append not possible + break; + case 0x8E : status = kStatusFWFileIsFull; // File is full + break; + case 0x8F : status = kStatusFWFileExists; // File already exists + break; + case 0x90 : status = kStatusFWModuleNotFound; // Module not found + break; + case 0x91 : status = kStatusFWOutOfBounds; // Out of module I/O map boundary + break; + case 0x92 : status = kStatusFWIllegalFileName; // Illegal file name + break; + case 0x93 : status = kStatusFWIllegalHandle; // Illegal handle + break; + default : + status = kStatusFWUnknownErrorCode; + } + return status; + } + + // prototypes... + +} // namespace nFANTOM100 + +// inline functions and function macros... + +#endif // ___fantom_tStatus_h___ diff --git a/FantomModule/include/labview/macosx/advanceFileIterator.vi b/FantomModule/include/labview/macosx/advanceFileIterator.vi new file mode 100644 index 0000000..427df5b Binary files /dev/null and b/FantomModule/include/labview/macosx/advanceFileIterator.vi differ diff --git a/FantomModule/include/labview/macosx/advanceModuleIterator.vi b/FantomModule/include/labview/macosx/advanceModuleIterator.vi new file mode 100644 index 0000000..46617f5 Binary files /dev/null and b/FantomModule/include/labview/macosx/advanceModuleIterator.vi differ diff --git a/FantomModule/include/labview/macosx/advanceNXTIterator.vi b/FantomModule/include/labview/macosx/advanceNXTIterator.vi new file mode 100644 index 0000000..e223afd Binary files /dev/null and b/FantomModule/include/labview/macosx/advanceNXTIterator.vi differ diff --git a/FantomModule/include/labview/macosx/bluetoothFactoryReset.vi b/FantomModule/include/labview/macosx/bluetoothFactoryReset.vi new file mode 100644 index 0000000..d821675 Binary files /dev/null and b/FantomModule/include/labview/macosx/bluetoothFactoryReset.vi differ diff --git a/FantomModule/include/labview/macosx/bootSamba.vi b/FantomModule/include/labview/macosx/bootSamba.vi new file mode 100644 index 0000000..a1bf225 Binary files /dev/null and b/FantomModule/include/labview/macosx/bootSamba.vi differ diff --git a/FantomModule/include/labview/macosx/closeFile.vi b/FantomModule/include/labview/macosx/closeFile.vi new file mode 100644 index 0000000..f5b1e12 Binary files /dev/null and b/FantomModule/include/labview/macosx/closeFile.vi differ diff --git a/FantomModule/include/labview/macosx/createFile.vi b/FantomModule/include/labview/macosx/createFile.vi new file mode 100644 index 0000000..b3442ac Binary files /dev/null and b/FantomModule/include/labview/macosx/createFile.vi differ diff --git a/FantomModule/include/labview/macosx/createFileIterator.vi b/FantomModule/include/labview/macosx/createFileIterator.vi new file mode 100644 index 0000000..4ad1d34 Binary files /dev/null and b/FantomModule/include/labview/macosx/createFileIterator.vi differ diff --git a/FantomModule/include/labview/macosx/createModule.vi b/FantomModule/include/labview/macosx/createModule.vi new file mode 100644 index 0000000..bd1f3e8 Binary files /dev/null and b/FantomModule/include/labview/macosx/createModule.vi differ diff --git a/FantomModule/include/labview/macosx/createModuleIterator.vi b/FantomModule/include/labview/macosx/createModuleIterator.vi new file mode 100644 index 0000000..051e858 Binary files /dev/null and b/FantomModule/include/labview/macosx/createModuleIterator.vi differ diff --git a/FantomModule/include/labview/macosx/createNXT.vi b/FantomModule/include/labview/macosx/createNXT.vi new file mode 100644 index 0000000..bb38bb8 Binary files /dev/null and b/FantomModule/include/labview/macosx/createNXT.vi differ diff --git a/FantomModule/include/labview/macosx/createNXTIterator.vi b/FantomModule/include/labview/macosx/createNXTIterator.vi new file mode 100644 index 0000000..2827435 Binary files /dev/null and b/FantomModule/include/labview/macosx/createNXTIterator.vi differ diff --git a/FantomModule/include/labview/macosx/destroyFile.vi b/FantomModule/include/labview/macosx/destroyFile.vi new file mode 100644 index 0000000..a57aea3 Binary files /dev/null and b/FantomModule/include/labview/macosx/destroyFile.vi differ diff --git a/FantomModule/include/labview/macosx/destroyFileIterator.vi b/FantomModule/include/labview/macosx/destroyFileIterator.vi new file mode 100644 index 0000000..0010789 Binary files /dev/null and b/FantomModule/include/labview/macosx/destroyFileIterator.vi differ diff --git a/FantomModule/include/labview/macosx/destroyModule.vi b/FantomModule/include/labview/macosx/destroyModule.vi new file mode 100644 index 0000000..66af71f Binary files /dev/null and b/FantomModule/include/labview/macosx/destroyModule.vi differ diff --git a/FantomModule/include/labview/macosx/destroyModuleIterator.vi b/FantomModule/include/labview/macosx/destroyModuleIterator.vi new file mode 100644 index 0000000..c0a4b9a Binary files /dev/null and b/FantomModule/include/labview/macosx/destroyModuleIterator.vi differ diff --git a/FantomModule/include/labview/macosx/destroyNXT.vi b/FantomModule/include/labview/macosx/destroyNXT.vi new file mode 100644 index 0000000..3065055 Binary files /dev/null and b/FantomModule/include/labview/macosx/destroyNXT.vi differ diff --git a/FantomModule/include/labview/macosx/destroyNXTIterator.vi b/FantomModule/include/labview/macosx/destroyNXTIterator.vi new file mode 100644 index 0000000..f763b9a Binary files /dev/null and b/FantomModule/include/labview/macosx/destroyNXTIterator.vi differ diff --git a/FantomModule/include/labview/macosx/downloadFirmware.vi b/FantomModule/include/labview/macosx/downloadFirmware.vi new file mode 100644 index 0000000..d0c082b Binary files /dev/null and b/FantomModule/include/labview/macosx/downloadFirmware.vi differ diff --git a/FantomModule/include/labview/macosx/eraseUserFlash.vi b/FantomModule/include/labview/macosx/eraseUserFlash.vi new file mode 100644 index 0000000..4961a39 Binary files /dev/null and b/FantomModule/include/labview/macosx/eraseUserFlash.vi differ diff --git a/FantomModule/include/labview/macosx/findDeviceInFirmwareDownloadMode.vi b/FantomModule/include/labview/macosx/findDeviceInFirmwareDownloadMode.vi new file mode 100644 index 0000000..44bfc91 Binary files /dev/null and b/FantomModule/include/labview/macosx/findDeviceInFirmwareDownloadMode.vi differ diff --git a/FantomModule/include/labview/macosx/findNXT.vi b/FantomModule/include/labview/macosx/findNXT.vi new file mode 100644 index 0000000..78b9034 Binary files /dev/null and b/FantomModule/include/labview/macosx/findNXT.vi differ diff --git a/FantomModule/include/labview/macosx/getAvailableSize.vi b/FantomModule/include/labview/macosx/getAvailableSize.vi new file mode 100644 index 0000000..c6f2be6 Binary files /dev/null and b/FantomModule/include/labview/macosx/getAvailableSize.vi differ diff --git a/FantomModule/include/labview/macosx/getDeviceInfo.vi b/FantomModule/include/labview/macosx/getDeviceInfo.vi new file mode 100644 index 0000000..1fbc025 Binary files /dev/null and b/FantomModule/include/labview/macosx/getDeviceInfo.vi differ diff --git a/FantomModule/include/labview/macosx/getFile.vi b/FantomModule/include/labview/macosx/getFile.vi new file mode 100644 index 0000000..6a31965 Binary files /dev/null and b/FantomModule/include/labview/macosx/getFile.vi differ diff --git a/FantomModule/include/labview/macosx/getFileName.vi b/FantomModule/include/labview/macosx/getFileName.vi new file mode 100644 index 0000000..b5d7724 Binary files /dev/null and b/FantomModule/include/labview/macosx/getFileName.vi differ diff --git a/FantomModule/include/labview/macosx/getFileSize.vi b/FantomModule/include/labview/macosx/getFileSize.vi new file mode 100644 index 0000000..d0d18dc Binary files /dev/null and b/FantomModule/include/labview/macosx/getFileSize.vi differ diff --git a/FantomModule/include/labview/macosx/getFileSizeFromIterator.vi b/FantomModule/include/labview/macosx/getFileSizeFromIterator.vi new file mode 100644 index 0000000..b9ee459 Binary files /dev/null and b/FantomModule/include/labview/macosx/getFileSizeFromIterator.vi differ diff --git a/FantomModule/include/labview/macosx/getFilenameFromIterator.vi b/FantomModule/include/labview/macosx/getFilenameFromIterator.vi new file mode 100644 index 0000000..f389374 Binary files /dev/null and b/FantomModule/include/labview/macosx/getFilenameFromIterator.vi differ diff --git a/FantomModule/include/labview/macosx/getFirmwareVersion.vi b/FantomModule/include/labview/macosx/getFirmwareVersion.vi new file mode 100644 index 0000000..d31e7b1 Binary files /dev/null and b/FantomModule/include/labview/macosx/getFirmwareVersion.vi differ diff --git a/FantomModule/include/labview/macosx/getIOMapSize.vi b/FantomModule/include/labview/macosx/getIOMapSize.vi new file mode 100644 index 0000000..b85503e Binary files /dev/null and b/FantomModule/include/labview/macosx/getIOMapSize.vi differ diff --git a/FantomModule/include/labview/macosx/getModule.vi b/FantomModule/include/labview/macosx/getModule.vi new file mode 100644 index 0000000..c7aa164 Binary files /dev/null and b/FantomModule/include/labview/macosx/getModule.vi differ diff --git a/FantomModule/include/labview/macosx/getModuleID.vi b/FantomModule/include/labview/macosx/getModuleID.vi new file mode 100644 index 0000000..c361683 Binary files /dev/null and b/FantomModule/include/labview/macosx/getModuleID.vi differ diff --git a/FantomModule/include/labview/macosx/getModuleName.vi b/FantomModule/include/labview/macosx/getModuleName.vi new file mode 100644 index 0000000..1e677ac Binary files /dev/null and b/FantomModule/include/labview/macosx/getModuleName.vi differ diff --git a/FantomModule/include/labview/macosx/getModuleNameFromIterator.vi b/FantomModule/include/labview/macosx/getModuleNameFromIterator.vi new file mode 100644 index 0000000..f398170 Binary files /dev/null and b/FantomModule/include/labview/macosx/getModuleNameFromIterator.vi differ diff --git a/FantomModule/include/labview/macosx/getModuleSize.vi b/FantomModule/include/labview/macosx/getModuleSize.vi new file mode 100644 index 0000000..504956b Binary files /dev/null and b/FantomModule/include/labview/macosx/getModuleSize.vi differ diff --git a/FantomModule/include/labview/macosx/getNXTFromIterator.vi b/FantomModule/include/labview/macosx/getNXTFromIterator.vi new file mode 100644 index 0000000..8301df2 Binary files /dev/null and b/FantomModule/include/labview/macosx/getNXTFromIterator.vi differ diff --git a/FantomModule/include/labview/macosx/getResourceString.vi b/FantomModule/include/labview/macosx/getResourceString.vi new file mode 100644 index 0000000..55f8fe7 Binary files /dev/null and b/FantomModule/include/labview/macosx/getResourceString.vi differ diff --git a/FantomModule/include/labview/macosx/getStringFromNXTIterator.vi b/FantomModule/include/labview/macosx/getStringFromNXTIterator.vi new file mode 100644 index 0000000..9f97c2a Binary files /dev/null and b/FantomModule/include/labview/macosx/getStringFromNXTIterator.vi differ diff --git a/FantomModule/include/labview/macosx/isPaired.vi b/FantomModule/include/labview/macosx/isPaired.vi new file mode 100644 index 0000000..a2f9602 Binary files /dev/null and b/FantomModule/include/labview/macosx/isPaired.vi differ diff --git a/FantomModule/include/labview/macosx/nakedRead.vi b/FantomModule/include/labview/macosx/nakedRead.vi new file mode 100644 index 0000000..00a43de Binary files /dev/null and b/FantomModule/include/labview/macosx/nakedRead.vi differ diff --git a/FantomModule/include/labview/macosx/nakedWrite.vi b/FantomModule/include/labview/macosx/nakedWrite.vi new file mode 100644 index 0000000..01bd8e1 Binary files /dev/null and b/FantomModule/include/labview/macosx/nakedWrite.vi differ diff --git a/FantomModule/include/labview/macosx/nxt.ctl b/FantomModule/include/labview/macosx/nxt.ctl new file mode 100644 index 0000000..2f06605 Binary files /dev/null and b/FantomModule/include/labview/macosx/nxt.ctl differ diff --git a/FantomModule/include/labview/macosx/openForRead.vi b/FantomModule/include/labview/macosx/openForRead.vi new file mode 100644 index 0000000..74dd60b Binary files /dev/null and b/FantomModule/include/labview/macosx/openForRead.vi differ diff --git a/FantomModule/include/labview/macosx/openForWrite.vi b/FantomModule/include/labview/macosx/openForWrite.vi new file mode 100644 index 0000000..180bd70 Binary files /dev/null and b/FantomModule/include/labview/macosx/openForWrite.vi differ diff --git a/FantomModule/include/labview/macosx/pairBluetooth.vi b/FantomModule/include/labview/macosx/pairBluetooth.vi new file mode 100644 index 0000000..1845031 Binary files /dev/null and b/FantomModule/include/labview/macosx/pairBluetooth.vi differ diff --git a/FantomModule/include/labview/macosx/pollAvailableLength.vi b/FantomModule/include/labview/macosx/pollAvailableLength.vi new file mode 100644 index 0000000..0b74f5d Binary files /dev/null and b/FantomModule/include/labview/macosx/pollAvailableLength.vi differ diff --git a/FantomModule/include/labview/macosx/read.vi b/FantomModule/include/labview/macosx/read.vi new file mode 100644 index 0000000..9cf87a4 Binary files /dev/null and b/FantomModule/include/labview/macosx/read.vi differ diff --git a/FantomModule/include/labview/macosx/readBufferData.vi b/FantomModule/include/labview/macosx/readBufferData.vi new file mode 100644 index 0000000..1ebef92 Binary files /dev/null and b/FantomModule/include/labview/macosx/readBufferData.vi differ diff --git a/FantomModule/include/labview/macosx/readIOMap.vi b/FantomModule/include/labview/macosx/readIOMap.vi new file mode 100644 index 0000000..be244b0 Binary files /dev/null and b/FantomModule/include/labview/macosx/readIOMap.vi differ diff --git a/FantomModule/include/labview/macosx/remove.vi b/FantomModule/include/labview/macosx/remove.vi new file mode 100644 index 0000000..4216b11 Binary files /dev/null and b/FantomModule/include/labview/macosx/remove.vi differ diff --git a/FantomModule/include/labview/macosx/sendDirectCommand.vi b/FantomModule/include/labview/macosx/sendDirectCommand.vi new file mode 100644 index 0000000..c7694ca Binary files /dev/null and b/FantomModule/include/labview/macosx/sendDirectCommand.vi differ diff --git a/FantomModule/include/labview/macosx/setNXTName.vi b/FantomModule/include/labview/macosx/setNXTName.vi new file mode 100644 index 0000000..19339d2 Binary files /dev/null and b/FantomModule/include/labview/macosx/setNXTName.vi differ diff --git a/FantomModule/include/labview/macosx/unpairBluetooth.vi b/FantomModule/include/labview/macosx/unpairBluetooth.vi new file mode 100644 index 0000000..c2e3b7c Binary files /dev/null and b/FantomModule/include/labview/macosx/unpairBluetooth.vi differ diff --git a/FantomModule/include/labview/macosx/write.vi b/FantomModule/include/labview/macosx/write.vi new file mode 100644 index 0000000..9f556a0 Binary files /dev/null and b/FantomModule/include/labview/macosx/write.vi differ diff --git a/FantomModule/include/labview/macosx/writeIOMap.vi b/FantomModule/include/labview/macosx/writeIOMap.vi new file mode 100644 index 0000000..dda451b Binary files /dev/null and b/FantomModule/include/labview/macosx/writeIOMap.vi differ diff --git a/FantomModule/include/labview/win32/advanceFileIterator.vi b/FantomModule/include/labview/win32/advanceFileIterator.vi new file mode 100644 index 0000000..19fc124 Binary files /dev/null and b/FantomModule/include/labview/win32/advanceFileIterator.vi differ diff --git a/FantomModule/include/labview/win32/advanceModuleIterator.vi b/FantomModule/include/labview/win32/advanceModuleIterator.vi new file mode 100644 index 0000000..b9879c7 Binary files /dev/null and b/FantomModule/include/labview/win32/advanceModuleIterator.vi differ diff --git a/FantomModule/include/labview/win32/advanceNXTIterator.vi b/FantomModule/include/labview/win32/advanceNXTIterator.vi new file mode 100644 index 0000000..a0fe1f1 Binary files /dev/null and b/FantomModule/include/labview/win32/advanceNXTIterator.vi differ diff --git a/FantomModule/include/labview/win32/bluetoothFactoryReset.vi b/FantomModule/include/labview/win32/bluetoothFactoryReset.vi new file mode 100644 index 0000000..0f9c6a8 Binary files /dev/null and b/FantomModule/include/labview/win32/bluetoothFactoryReset.vi differ diff --git a/FantomModule/include/labview/win32/bootSamba.vi b/FantomModule/include/labview/win32/bootSamba.vi new file mode 100644 index 0000000..397a119 Binary files /dev/null and b/FantomModule/include/labview/win32/bootSamba.vi differ diff --git a/FantomModule/include/labview/win32/closeFile.vi b/FantomModule/include/labview/win32/closeFile.vi new file mode 100644 index 0000000..3e893e7 Binary files /dev/null and b/FantomModule/include/labview/win32/closeFile.vi differ diff --git a/FantomModule/include/labview/win32/createFile.vi b/FantomModule/include/labview/win32/createFile.vi new file mode 100644 index 0000000..1445f12 Binary files /dev/null and b/FantomModule/include/labview/win32/createFile.vi differ diff --git a/FantomModule/include/labview/win32/createFileIterator.vi b/FantomModule/include/labview/win32/createFileIterator.vi new file mode 100644 index 0000000..5554f4b Binary files /dev/null and b/FantomModule/include/labview/win32/createFileIterator.vi differ diff --git a/FantomModule/include/labview/win32/createModule.vi b/FantomModule/include/labview/win32/createModule.vi new file mode 100644 index 0000000..b640ae7 Binary files /dev/null and b/FantomModule/include/labview/win32/createModule.vi differ diff --git a/FantomModule/include/labview/win32/createModuleIterator.vi b/FantomModule/include/labview/win32/createModuleIterator.vi new file mode 100644 index 0000000..fd79dba Binary files /dev/null and b/FantomModule/include/labview/win32/createModuleIterator.vi differ diff --git a/FantomModule/include/labview/win32/createNXT.vi b/FantomModule/include/labview/win32/createNXT.vi new file mode 100644 index 0000000..47b3243 Binary files /dev/null and b/FantomModule/include/labview/win32/createNXT.vi differ diff --git a/FantomModule/include/labview/win32/createNXTIterator.vi b/FantomModule/include/labview/win32/createNXTIterator.vi new file mode 100644 index 0000000..c6f8f24 Binary files /dev/null and b/FantomModule/include/labview/win32/createNXTIterator.vi differ diff --git a/FantomModule/include/labview/win32/destroyFile.vi b/FantomModule/include/labview/win32/destroyFile.vi new file mode 100644 index 0000000..c71a99a Binary files /dev/null and b/FantomModule/include/labview/win32/destroyFile.vi differ diff --git a/FantomModule/include/labview/win32/destroyFileIterator.vi b/FantomModule/include/labview/win32/destroyFileIterator.vi new file mode 100644 index 0000000..783c4f4 Binary files /dev/null and b/FantomModule/include/labview/win32/destroyFileIterator.vi differ diff --git a/FantomModule/include/labview/win32/destroyModule.vi b/FantomModule/include/labview/win32/destroyModule.vi new file mode 100644 index 0000000..0cf7fb7 Binary files /dev/null and b/FantomModule/include/labview/win32/destroyModule.vi differ diff --git a/FantomModule/include/labview/win32/destroyModuleIterator.vi b/FantomModule/include/labview/win32/destroyModuleIterator.vi new file mode 100644 index 0000000..5e40e7e Binary files /dev/null and b/FantomModule/include/labview/win32/destroyModuleIterator.vi differ diff --git a/FantomModule/include/labview/win32/destroyNXT.vi b/FantomModule/include/labview/win32/destroyNXT.vi new file mode 100644 index 0000000..42409c3 Binary files /dev/null and b/FantomModule/include/labview/win32/destroyNXT.vi differ diff --git a/FantomModule/include/labview/win32/destroyNXTIterator.vi b/FantomModule/include/labview/win32/destroyNXTIterator.vi new file mode 100644 index 0000000..b9a9113 Binary files /dev/null and b/FantomModule/include/labview/win32/destroyNXTIterator.vi differ diff --git a/FantomModule/include/labview/win32/downloadFirmware.vi b/FantomModule/include/labview/win32/downloadFirmware.vi new file mode 100644 index 0000000..cf95da4 Binary files /dev/null and b/FantomModule/include/labview/win32/downloadFirmware.vi differ diff --git a/FantomModule/include/labview/win32/eraseUserFlash.vi b/FantomModule/include/labview/win32/eraseUserFlash.vi new file mode 100644 index 0000000..d3c9154 Binary files /dev/null and b/FantomModule/include/labview/win32/eraseUserFlash.vi differ diff --git a/FantomModule/include/labview/win32/findDeviceInFirmwareDownloadMode.vi b/FantomModule/include/labview/win32/findDeviceInFirmwareDownloadMode.vi new file mode 100644 index 0000000..4a0b7c6 Binary files /dev/null and b/FantomModule/include/labview/win32/findDeviceInFirmwareDownloadMode.vi differ diff --git a/FantomModule/include/labview/win32/findNXT.vi b/FantomModule/include/labview/win32/findNXT.vi new file mode 100644 index 0000000..747c8cd Binary files /dev/null and b/FantomModule/include/labview/win32/findNXT.vi differ diff --git a/FantomModule/include/labview/win32/getAvailableSize.vi b/FantomModule/include/labview/win32/getAvailableSize.vi new file mode 100644 index 0000000..b511b2d Binary files /dev/null and b/FantomModule/include/labview/win32/getAvailableSize.vi differ diff --git a/FantomModule/include/labview/win32/getDeviceInfo.vi b/FantomModule/include/labview/win32/getDeviceInfo.vi new file mode 100644 index 0000000..835046a Binary files /dev/null and b/FantomModule/include/labview/win32/getDeviceInfo.vi differ diff --git a/FantomModule/include/labview/win32/getFile.vi b/FantomModule/include/labview/win32/getFile.vi new file mode 100644 index 0000000..2931da1 Binary files /dev/null and b/FantomModule/include/labview/win32/getFile.vi differ diff --git a/FantomModule/include/labview/win32/getFileName.vi b/FantomModule/include/labview/win32/getFileName.vi new file mode 100644 index 0000000..40ec334 Binary files /dev/null and b/FantomModule/include/labview/win32/getFileName.vi differ diff --git a/FantomModule/include/labview/win32/getFileSize.vi b/FantomModule/include/labview/win32/getFileSize.vi new file mode 100644 index 0000000..3ba069e Binary files /dev/null and b/FantomModule/include/labview/win32/getFileSize.vi differ diff --git a/FantomModule/include/labview/win32/getFileSizeFromIterator.vi b/FantomModule/include/labview/win32/getFileSizeFromIterator.vi new file mode 100644 index 0000000..9228800 Binary files /dev/null and b/FantomModule/include/labview/win32/getFileSizeFromIterator.vi differ diff --git a/FantomModule/include/labview/win32/getFilenameFromIterator.vi b/FantomModule/include/labview/win32/getFilenameFromIterator.vi new file mode 100644 index 0000000..bbbf882 Binary files /dev/null and b/FantomModule/include/labview/win32/getFilenameFromIterator.vi differ diff --git a/FantomModule/include/labview/win32/getFirmwareVersion.vi b/FantomModule/include/labview/win32/getFirmwareVersion.vi new file mode 100644 index 0000000..38760ac Binary files /dev/null and b/FantomModule/include/labview/win32/getFirmwareVersion.vi differ diff --git a/FantomModule/include/labview/win32/getIOMapSize.vi b/FantomModule/include/labview/win32/getIOMapSize.vi new file mode 100644 index 0000000..adf1396 Binary files /dev/null and b/FantomModule/include/labview/win32/getIOMapSize.vi differ diff --git a/FantomModule/include/labview/win32/getModule.vi b/FantomModule/include/labview/win32/getModule.vi new file mode 100644 index 0000000..eeff3c8 Binary files /dev/null and b/FantomModule/include/labview/win32/getModule.vi differ diff --git a/FantomModule/include/labview/win32/getModuleID.vi b/FantomModule/include/labview/win32/getModuleID.vi new file mode 100644 index 0000000..2250164 Binary files /dev/null and b/FantomModule/include/labview/win32/getModuleID.vi differ diff --git a/FantomModule/include/labview/win32/getModuleName.vi b/FantomModule/include/labview/win32/getModuleName.vi new file mode 100644 index 0000000..b0620c8 Binary files /dev/null and b/FantomModule/include/labview/win32/getModuleName.vi differ diff --git a/FantomModule/include/labview/win32/getModuleNameFromIterator.vi b/FantomModule/include/labview/win32/getModuleNameFromIterator.vi new file mode 100644 index 0000000..f0e31ce Binary files /dev/null and b/FantomModule/include/labview/win32/getModuleNameFromIterator.vi differ diff --git a/FantomModule/include/labview/win32/getModuleSize.vi b/FantomModule/include/labview/win32/getModuleSize.vi new file mode 100644 index 0000000..1b2a5f6 Binary files /dev/null and b/FantomModule/include/labview/win32/getModuleSize.vi differ diff --git a/FantomModule/include/labview/win32/getNXTFromIterator.vi b/FantomModule/include/labview/win32/getNXTFromIterator.vi new file mode 100644 index 0000000..8acd597 Binary files /dev/null and b/FantomModule/include/labview/win32/getNXTFromIterator.vi differ diff --git a/FantomModule/include/labview/win32/getResourceString.vi b/FantomModule/include/labview/win32/getResourceString.vi new file mode 100644 index 0000000..c0d019a Binary files /dev/null and b/FantomModule/include/labview/win32/getResourceString.vi differ diff --git a/FantomModule/include/labview/win32/getStringFromNXTIterator.vi b/FantomModule/include/labview/win32/getStringFromNXTIterator.vi new file mode 100644 index 0000000..8dee827 Binary files /dev/null and b/FantomModule/include/labview/win32/getStringFromNXTIterator.vi differ diff --git a/FantomModule/include/labview/win32/isPaired.vi b/FantomModule/include/labview/win32/isPaired.vi new file mode 100644 index 0000000..1c73992 Binary files /dev/null and b/FantomModule/include/labview/win32/isPaired.vi differ diff --git a/FantomModule/include/labview/win32/nakedRead.vi b/FantomModule/include/labview/win32/nakedRead.vi new file mode 100644 index 0000000..9c40980 Binary files /dev/null and b/FantomModule/include/labview/win32/nakedRead.vi differ diff --git a/FantomModule/include/labview/win32/nakedWrite.vi b/FantomModule/include/labview/win32/nakedWrite.vi new file mode 100644 index 0000000..f2f875a Binary files /dev/null and b/FantomModule/include/labview/win32/nakedWrite.vi differ diff --git a/FantomModule/include/labview/win32/nxt.ctl b/FantomModule/include/labview/win32/nxt.ctl new file mode 100644 index 0000000..6016dd1 Binary files /dev/null and b/FantomModule/include/labview/win32/nxt.ctl differ diff --git a/FantomModule/include/labview/win32/openForRead.vi b/FantomModule/include/labview/win32/openForRead.vi new file mode 100644 index 0000000..48d08e5 Binary files /dev/null and b/FantomModule/include/labview/win32/openForRead.vi differ diff --git a/FantomModule/include/labview/win32/openForWrite.vi b/FantomModule/include/labview/win32/openForWrite.vi new file mode 100644 index 0000000..e5d83c8 Binary files /dev/null and b/FantomModule/include/labview/win32/openForWrite.vi differ diff --git a/FantomModule/include/labview/win32/pairBluetooth.vi b/FantomModule/include/labview/win32/pairBluetooth.vi new file mode 100644 index 0000000..52fb06a Binary files /dev/null and b/FantomModule/include/labview/win32/pairBluetooth.vi differ diff --git a/FantomModule/include/labview/win32/pollAvailableLength.vi b/FantomModule/include/labview/win32/pollAvailableLength.vi new file mode 100644 index 0000000..6d05f67 Binary files /dev/null and b/FantomModule/include/labview/win32/pollAvailableLength.vi differ diff --git a/FantomModule/include/labview/win32/read.vi b/FantomModule/include/labview/win32/read.vi new file mode 100644 index 0000000..c20cab9 Binary files /dev/null and b/FantomModule/include/labview/win32/read.vi differ diff --git a/FantomModule/include/labview/win32/readBufferData.vi b/FantomModule/include/labview/win32/readBufferData.vi new file mode 100644 index 0000000..6b621d8 Binary files /dev/null and b/FantomModule/include/labview/win32/readBufferData.vi differ diff --git a/FantomModule/include/labview/win32/readIOMap.vi b/FantomModule/include/labview/win32/readIOMap.vi new file mode 100644 index 0000000..9d89134 Binary files /dev/null and b/FantomModule/include/labview/win32/readIOMap.vi differ diff --git a/FantomModule/include/labview/win32/remove.vi b/FantomModule/include/labview/win32/remove.vi new file mode 100644 index 0000000..9870267 Binary files /dev/null and b/FantomModule/include/labview/win32/remove.vi differ diff --git a/FantomModule/include/labview/win32/sendDirectCommand.vi b/FantomModule/include/labview/win32/sendDirectCommand.vi new file mode 100644 index 0000000..dba13c6 Binary files /dev/null and b/FantomModule/include/labview/win32/sendDirectCommand.vi differ diff --git a/FantomModule/include/labview/win32/setNXTName.vi b/FantomModule/include/labview/win32/setNXTName.vi new file mode 100644 index 0000000..65aa4ac Binary files /dev/null and b/FantomModule/include/labview/win32/setNXTName.vi differ diff --git a/FantomModule/include/labview/win32/unpairBluetooth.vi b/FantomModule/include/labview/win32/unpairBluetooth.vi new file mode 100644 index 0000000..9389c36 Binary files /dev/null and b/FantomModule/include/labview/win32/unpairBluetooth.vi differ diff --git a/FantomModule/include/labview/win32/write.vi b/FantomModule/include/labview/win32/write.vi new file mode 100644 index 0000000..d6f95d9 Binary files /dev/null and b/FantomModule/include/labview/win32/write.vi differ diff --git a/FantomModule/include/labview/win32/writeIOMap.vi b/FantomModule/include/labview/win32/writeIOMap.vi new file mode 100644 index 0000000..621546c Binary files /dev/null and b/FantomModule/include/labview/win32/writeIOMap.vi differ diff --git a/FantomModule/visatype.h b/FantomModule/visatype.h new file mode 100644 index 0000000..a667ff1 --- /dev/null +++ b/FantomModule/visatype.h @@ -0,0 +1,155 @@ +/*---------------------------------------------------------------------------*/ +/* Distributed by VXIplug&play Systems Alliance */ +/* */ +/* Do not modify the contents of this file. */ +/*---------------------------------------------------------------------------*/ +/* */ +/* Title : VISATYPE.H */ +/* Date : 08-01-98 */ +/* Purpose : Fundamental VISA data types and macro definitions */ +/* */ +/*---------------------------------------------------------------------------*/ + +#ifndef __VISATYPE_HEADER__ +#define __VISATYPE_HEADER__ + +#if (defined(WIN32) || defined(_WIN32) || defined(__WIN32__) || defined(__NT__)) && !defined(_NI_mswin16_) +#define _VI_FAR +#define _VI_FUNC __stdcall +#define _VI_FUNCC __cdecl +#define _VI_FUNCH __stdcall +#define _VI_SIGNED signed +#elif defined(_CVI_) && defined(_NI_i386_) +#define _VI_FAR +#define _VI_FUNC _pascal +#define _VI_FUNCC +#define _VI_FUNCH _pascal +#define _VI_SIGNED signed +#elif (defined(_WINDOWS) || defined(_Windows)) && !defined(_NI_mswin16_) +#define _VI_FAR _far +#define _VI_FUNC _far _pascal _export +#define _VI_FUNCC _far _cdecl _export +#define _VI_FUNCH _far _pascal +#define _VI_SIGNED signed +#elif (defined(hpux) || defined(__hpux)) && (defined(__cplusplus) || defined(__cplusplus__)) +#define _VI_FAR +#define _VI_FUNC +#define _VI_FUNCC +#define _VI_FUNCH +#define _VI_SIGNED +#else +#define _VI_FAR +#define _VI_FUNC +#define _VI_FUNCC +#define _VI_FUNCH +#define _VI_SIGNED signed +#endif + +#define _VI_ERROR (-2147483647L-1) /* 0x80000000 */ +#define _VI_PTR _VI_FAR * + +/*- VISA Types --------------------------------------------------------------*/ + +typedef unsigned long ViUInt32; +typedef ViUInt32 _VI_PTR ViPUInt32; +typedef ViUInt32 _VI_PTR ViAUInt32; + +typedef _VI_SIGNED long ViInt32; +typedef ViInt32 _VI_PTR ViPInt32; +typedef ViInt32 _VI_PTR ViAInt32; + +typedef unsigned short ViUInt16; +typedef ViUInt16 _VI_PTR ViPUInt16; +typedef ViUInt16 _VI_PTR ViAUInt16; + +typedef _VI_SIGNED short ViInt16; +typedef ViInt16 _VI_PTR ViPInt16; +typedef ViInt16 _VI_PTR ViAInt16; + +typedef unsigned char ViUInt8; +typedef ViUInt8 _VI_PTR ViPUInt8; +typedef ViUInt8 _VI_PTR ViAUInt8; + +typedef _VI_SIGNED char ViInt8; +typedef ViInt8 _VI_PTR ViPInt8; +typedef ViInt8 _VI_PTR ViAInt8; + +typedef char ViChar; +typedef ViChar _VI_PTR ViPChar; +typedef ViChar _VI_PTR ViAChar; + +typedef unsigned char ViByte; +typedef ViByte _VI_PTR ViPByte; +typedef ViByte _VI_PTR ViAByte; + +typedef void _VI_PTR ViAddr; +typedef ViAddr _VI_PTR ViPAddr; +typedef ViAddr _VI_PTR ViAAddr; + +typedef float ViReal32; +typedef ViReal32 _VI_PTR ViPReal32; +typedef ViReal32 _VI_PTR ViAReal32; + +typedef double ViReal64; +typedef ViReal64 _VI_PTR ViPReal64; +typedef ViReal64 _VI_PTR ViAReal64; + +typedef ViPByte ViBuf; +typedef ViPByte ViPBuf; +typedef ViPByte _VI_PTR ViABuf; + +typedef ViPChar ViString; +typedef ViPChar ViPString; +typedef ViPChar _VI_PTR ViAString; + +typedef ViString ViRsrc; +typedef ViString ViPRsrc; +typedef ViString _VI_PTR ViARsrc; + +typedef ViUInt16 ViBoolean; +typedef ViBoolean _VI_PTR ViPBoolean; +typedef ViBoolean _VI_PTR ViABoolean; + +typedef ViInt32 ViStatus; +typedef ViStatus _VI_PTR ViPStatus; +typedef ViStatus _VI_PTR ViAStatus; + +typedef ViUInt32 ViVersion; +typedef ViVersion _VI_PTR ViPVersion; +typedef ViVersion _VI_PTR ViAVersion; + +typedef ViUInt32 ViObject; +typedef ViObject _VI_PTR ViPObject; +typedef ViObject _VI_PTR ViAObject; + +typedef ViObject ViSession; +typedef ViSession _VI_PTR ViPSession; +typedef ViSession _VI_PTR ViASession; + +typedef ViUInt32 ViAttr; + +#ifndef _VI_CONST_STRING_DEFINED +typedef const ViChar * ViConstString; +#define _VI_CONST_STRING_DEFINED +#endif + +/*- Completion and Error Codes ----------------------------------------------*/ + +#define VI_SUCCESS (0L) + +/*- Other VISA Definitions --------------------------------------------------*/ + +#define VI_NULL (0) + +#define VI_TRUE (1) +#define VI_FALSE (0) + +/*- Backward Compatibility Macros -------------------------------------------*/ + +#define VISAFN _VI_FUNC +#define ViPtr _VI_PTR + +#endif + +/*- The End -----------------------------------------------------------------*/ + -- cgit v1.2.3 From a9c9b62a94e0398e5be0f3eb5f1ef666548617ca Mon Sep 17 00:00:00 2001 From: Tat-Chee Wan (USM) Date: Tue, 1 Mar 2011 12:13:26 +0800 Subject: updated ignore list for xcode build stuff --- .gitignore | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/.gitignore b/.gitignore index 1435c9c..8579431 100644 --- a/.gitignore +++ b/.gitignore @@ -21,6 +21,10 @@ MASTER-REPO_DO-NOT-DELETE # Python distutils creates this when building. pynxt/build/ +# XCode build stuff +FantomModule/build/ +*mode1v3 +*pbxuser # SCons cruft .sconsign.dblite -- cgit v1.2.3 From edf4a348de0ddaf3bd0429d3cbb7dacc3b748954 Mon Sep 17 00:00:00 2001 From: Tat-Chee Wan (USM) Date: Tue, 1 Mar 2011 15:49:21 +0800 Subject: added pyfantom python module, renamed .cp to .cpp, add setup.py --- FantomModule/FantomModule.cp | 133 --------------------- FantomModule/FantomModule.cpp | 133 +++++++++++++++++++++ FantomModule/FantomModule.h | 4 +- .../FantomModule.xcodeproj/project.pbxproj | 10 +- FantomModule/pyfantom/__init__.py | 0 FantomModule/setup.py | 35 ++++++ 6 files changed, 176 insertions(+), 139 deletions(-) delete mode 100644 FantomModule/FantomModule.cp create mode 100644 FantomModule/FantomModule.cpp create mode 100644 FantomModule/pyfantom/__init__.py create mode 100644 FantomModule/setup.py diff --git a/FantomModule/FantomModule.cp b/FantomModule/FantomModule.cp deleted file mode 100644 index 60bbe80..0000000 --- a/FantomModule/FantomModule.cp +++ /dev/null @@ -1,133 +0,0 @@ -/* - * FantomModule.cp - * FantomModule - * - * Created by tcmac on 01/03/2011. - * Copyright 2011 TC Wan. All rights reserved. - * - * Based on code from Fantom Driver 1.0.2f0 Example - * © Copyright 2006, - * National Instruments Corporation. - * All rights reserved. - * - * Originated: 10 March 2006 - * - */ - -#include -#include -#include "FantomModule.h" -#include "FantomModulePriv.h" - -static PyMethodDef FantomMethods[] = { - {"finddevices", fantom_finddevices, METH_VARARGS, - "Find a NXT Device"}, - {"socket", fantom_socket, METH_VARARGS, - "Create a Socket for a NXT Brick"}, - {"connect", fantom_connect, METH_VARARGS, - "Connect the Socket to a NXT Brick"}, - {"send", fantom_send, METH_VARARGS, - "Send Data via the Socket to a NXT Brick"}, - {"recv", fantom_recv, METH_VARARGS, - "Receive Data via the Socket from a NXT Brick"}, - {"close", fantom_close, METH_VARARGS, - "Close the Socket to a NXT Brick"}, - {NULL, NULL, 0, NULL} /* Sentinel */ -}; - -extern "C" PyMODINIT_FUNC -initspam(void) -{ - (void) Py_InitModule("fantom", FantomMethods); -} - -extern "C" PyObject *fantom_finddevices(PyObject *py_self, PyObject *py_args) -{ - FantomModule *fantomObject; - fantomObject = new FantomModule; - - PyObject *list = fantomObject->finddevices(py_self,py_args); - delete fantomObject; - - return list; -} -extern "C" PyObject *fantom_socket(PyObject *py_self, PyObject *py_args) -{ -} - -extern "C" PyObject *fantom_connect(PyObject *py_self, PyObject *py_args) -{ -} - -extern "C" PyObject *fantom_send(PyObject *py_self, PyObject *py_args) -{ -} - -extern "C" PyObject *fantom_recv(PyObject *py_self, PyObject *py_args) -{ -} - -extern "C" PyObject *fantom_close(PyObject *py_self, PyObject *py_args) -{ -} - -PyObject *FantomModule::finddevices(PyObject *py_self, PyObject *py_args) -{ - const char *proto; - if (!PyArg_ParseTuple(py_args, "s", &proto)) - return NULL; - - ViBoolean useBT; - useBT = strcmp(proto, FANTOM_BT) ? true : false; - -/* - const char *command; - int sts; - - if (!PyArg_ParseTuple(py_args, "s", &command)) - return NULL; - sts = system(command); - return Py_BuildValue("i", sts); -*/ - - // Create an NXT iterator object which is used to find all accessible NXT devices. - nxtIteratorPtr = nFANTOM100::iNXT::createNXTIterator(useBT, FANTOM_BT_TIMEOUTSEC, status); - - // Creating the NXT iterator object could fail, better check status before dereferencing a - // potentially NULL pointer. - if( status.isNotFatal()) - { - ViChar nxtName[FANTOM_NXTNAME_LEN]; - nxtIteratorPtr->getName(nxtName, status); - if( status.isNotFatal()) - { - // FIXME: Append to Python list - } - nxtIteratorPtr->advance(status); - - } - // Destroy the NXT iterator object which we no longer need - nFANTOM100::iNXT::destroyNXTIterator( nxtIteratorPtr ); - -} - -PyObject *FantomModule::socket(PyObject *py_self, PyObject *py_args) -{ - // Create an NXT object for the first NXT that was found. Note that if a NXT is found - // over BT, the computer and the NXT must be paired before an NXT object can be - // created. This can be done programatically using the iNXT::pairBluetooth method. - // nxtPtr = nxtIteratorPtr->getNXT( status ); -} - -void FantomModule::HelloWorld(const char * s) -{ - FantomModulePriv *theObj = new FantomModulePriv; - theObj->HelloWorldPriv(s); - delete theObj; -}; - -void FantomModulePriv::HelloWorldPriv(const char * s) -{ - std::cout << s << std::endl; -}; - diff --git a/FantomModule/FantomModule.cpp b/FantomModule/FantomModule.cpp new file mode 100644 index 0000000..ff2c6cd --- /dev/null +++ b/FantomModule/FantomModule.cpp @@ -0,0 +1,133 @@ +/* + * FantomModule.cp + * FantomModule + * + * Created by tcmac on 01/03/2011. + * Copyright 2011 TC Wan. All rights reserved. + * + * Based on code from Fantom Driver 1.0.2f0 Example + * © Copyright 2006, + * National Instruments Corporation. + * All rights reserved. + * + * Originated: 10 March 2006 + * + */ + +#include +#include +#include "FantomModule.h" +#include "FantomModulePriv.h" + +static PyMethodDef FantomMethods[] = { + {"finddevices", fantom_finddevices, METH_VARARGS, + "Find a NXT Device"}, + {"socket", fantom_socket, METH_VARARGS, + "Create a Socket for a NXT Brick"}, + {"connect", fantom_connect, METH_VARARGS, + "Connect the Socket to a NXT Brick"}, + {"send", fantom_send, METH_VARARGS, + "Send Data via the Socket to a NXT Brick"}, + {"recv", fantom_recv, METH_VARARGS, + "Receive Data via the Socket from a NXT Brick"}, + {"close", fantom_close, METH_VARARGS, + "Close the Socket to a NXT Brick"}, + {NULL, NULL, 0, NULL} /* Sentinel */ +}; + +extern "C" PyMODINIT_FUNC +initfantom(void) +{ + (void) Py_InitModule("fantom", FantomMethods); +} + +extern "C" PyObject *fantom_finddevices(PyObject *py_self, PyObject *py_args) +{ + FantomModule *fantomObject; + fantomObject = new FantomModule; + + PyObject *list = fantomObject->finddevices(py_self,py_args); + delete fantomObject; + + return list; +} +extern "C" PyObject *fantom_socket(PyObject *py_self, PyObject *py_args) +{ +} + +extern "C" PyObject *fantom_connect(PyObject *py_self, PyObject *py_args) +{ +} + +extern "C" PyObject *fantom_send(PyObject *py_self, PyObject *py_args) +{ +} + +extern "C" PyObject *fantom_recv(PyObject *py_self, PyObject *py_args) +{ +} + +extern "C" PyObject *fantom_close(PyObject *py_self, PyObject *py_args) +{ +} + +PyObject *FantomModule::finddevices(PyObject *py_self, PyObject *py_args) +{ + const char *proto; + if (!PyArg_ParseTuple(py_args, "s", &proto)) + return NULL; + + ViBoolean useBT; + useBT = strcmp(proto, FANTOM_BT) ? true : false; + +/* + const char *command; + int sts; + + if (!PyArg_ParseTuple(py_args, "s", &command)) + return NULL; + sts = system(command); + return Py_BuildValue("i", sts); +*/ + + // Create an NXT iterator object which is used to find all accessible NXT devices. + nxtIteratorPtr = nFANTOM100::iNXT::createNXTIterator(useBT, FANTOM_BT_TIMEOUTSEC, status); + + // Creating the NXT iterator object could fail, better check status before dereferencing a + // potentially NULL pointer. + if( status.isNotFatal()) + { + ViChar nxtName[FANTOM_NXTNAME_LEN]; + nxtIteratorPtr->getName(nxtName, status); + if( status.isNotFatal()) + { + // FIXME: Append to Python list + } + nxtIteratorPtr->advance(status); + + } + // Destroy the NXT iterator object which we no longer need + nFANTOM100::iNXT::destroyNXTIterator( nxtIteratorPtr ); + +} + +PyObject *FantomModule::socket(PyObject *py_self, PyObject *py_args) +{ + // Create an NXT object for the first NXT that was found. Note that if a NXT is found + // over BT, the computer and the NXT must be paired before an NXT object can be + // created. This can be done programatically using the iNXT::pairBluetooth method. + // nxtPtr = nxtIteratorPtr->getNXT( status ); +} + +void FantomModule::HelloWorld(const char * s) +{ + FantomModulePriv *theObj = new FantomModulePriv; + theObj->HelloWorldPriv(s); + delete theObj; +}; + +void FantomModulePriv::HelloWorldPriv(const char * s) +{ + std::cout << s << std::endl; +}; + diff --git a/FantomModule/FantomModule.h b/FantomModule/FantomModule.h index 91e7575..4266d04 100644 --- a/FantomModule/FantomModule.h +++ b/FantomModule/FantomModule.h @@ -10,7 +10,7 @@ #ifndef FantomModule_ #define FantomModule_ -#include +#include "Python.h" #include "fantom/iNXT.h" #include "fantom/iNXTIterator.h" #include "fantom/tStatus.h" @@ -23,7 +23,7 @@ /* The classes below are exported */ #pragma GCC visibility push(default) -extern "C" PyMODINIT_FUNC initspam(void); +extern "C" PyMODINIT_FUNC initfantom(void); extern "C" PyObject *fantom_finddevices(PyObject *py_self, PyObject *py_args); extern "C" PyObject *fantom_socket(PyObject *py_self, PyObject *py_args); diff --git a/FantomModule/FantomModule.xcodeproj/project.pbxproj b/FantomModule/FantomModule.xcodeproj/project.pbxproj index c85a049..f4a5ec8 100644 --- a/FantomModule/FantomModule.xcodeproj/project.pbxproj +++ b/FantomModule/FantomModule.xcodeproj/project.pbxproj @@ -19,7 +19,7 @@ 43B531FB131C963A0016BF14 /* visatype.h in Headers */ = {isa = PBXBuildFile; fileRef = 43B531FA131C963A0016BF14 /* visatype.h */; }; 43B5320A131C975B0016BF14 /* Fantom in Frameworks */ = {isa = PBXBuildFile; fileRef = 43B53209131C975B0016BF14 /* Fantom */; }; 50149BDA09E781A5002DEE6A /* FantomModule.h in Headers */ = {isa = PBXBuildFile; fileRef = 50149BD909E781A5002DEE6A /* FantomModule.h */; }; - 5073E0CB09E734E500EC74B6 /* FantomModule.cp in Sources */ = {isa = PBXBuildFile; fileRef = 5073E0C409E734A800EC74B6 /* FantomModule.cp */; }; + 5073E0CB09E734E500EC74B6 /* FantomModule.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 5073E0C409E734A800EC74B6 /* FantomModule.cpp */; }; /* End PBXBuildFile section */ /* Begin PBXFileReference section */ @@ -35,8 +35,9 @@ 43B531F1131C962E0016BF14 /* tStatus.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = tStatus.h; sourceTree = ""; }; 43B531FA131C963A0016BF14 /* visatype.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = visatype.h; sourceTree = ""; }; 43B53209131C975B0016BF14 /* Fantom */ = {isa = PBXFileReference; lastKnownFileType = "compiled.mach-o.dylib"; name = Fantom; path = /Library/Frameworks/Fantom.framework/Fantom; sourceTree = ""; }; + 43DB2163131CBF18001443AF /* setup.py */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.script.python; path = setup.py; sourceTree = ""; }; 50149BD909E781A5002DEE6A /* FantomModule.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = FantomModule.h; sourceTree = ""; }; - 5073E0C409E734A800EC74B6 /* FantomModule.cp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = FantomModule.cp; sourceTree = ""; }; + 5073E0C409E734A800EC74B6 /* FantomModule.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = FantomModule.cpp; sourceTree = ""; }; 5073E0C609E734A800EC74B6 /* FantomModuleProj.xcconfig */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = text.xcconfig; path = FantomModuleProj.xcconfig; sourceTree = ""; }; 5073E0C709E734A800EC74B6 /* FantomModuleTarget.xcconfig */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = text.xcconfig; path = FantomModuleTarget.xcconfig; sourceTree = ""; }; 50B2938909F016FC00694E55 /* FantomModulePriv.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = FantomModulePriv.h; sourceTree = ""; }; @@ -73,6 +74,7 @@ 08FB77ACFE841707C02AAC07 /* Source */, 0867D69AFE84028FC02AAC07 /* External Frameworks and Libraries */, 034768DDFF38A45A11DB9C8B /* Products */, + 43DB2163131CBF18001443AF /* setup.py */, ); name = FantomModule; sourceTree = ""; @@ -92,7 +94,7 @@ 32BAE0B70371A74B00C91783 /* FantomModule_Prefix.pch */, 50149BD909E781A5002DEE6A /* FantomModule.h */, 50B2938909F016FC00694E55 /* FantomModulePriv.h */, - 5073E0C409E734A800EC74B6 /* FantomModule.cp */, + 5073E0C409E734A800EC74B6 /* FantomModule.cpp */, ); name = Source; sourceTree = ""; @@ -191,7 +193,7 @@ isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = ( - 5073E0CB09E734E500EC74B6 /* FantomModule.cp in Sources */, + 5073E0CB09E734E500EC74B6 /* FantomModule.cpp in Sources */, ); runOnlyForDeploymentPostprocessing = 0; }; diff --git a/FantomModule/pyfantom/__init__.py b/FantomModule/pyfantom/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/FantomModule/setup.py b/FantomModule/setup.py new file mode 100644 index 0000000..25dd152 --- /dev/null +++ b/FantomModule/setup.py @@ -0,0 +1,35 @@ +from distutils.core import setup, Extension +import sys + +def getextensions(): + mac_ext = Extension("FantomModule", + define_macros=[('PYFANTOM_DEBUG', '0')], # set to '1' to print debug messges + include_dirs=['.'], + extra_compile_args=['-arch i386'], + libraries=["Fantom"], + sources=["FantomModule.cpp"] + ) + return [mac_ext] + +# install the main library +setup(name="pyfantom", + version="0.1", + author="Tat-Chee Wan", + author_email="tcwan@cs.usm.my", + url="", + description="Python Extension to call Fantom Driver", + long_description="Python Wrapper for Fantom Driver on Mac OS X.", + license="GPL", + packages=["pyfantom"], + ext_modules=getextensions(), + classifiers = [ "Development Status :: 3 - Alpha", + "Intended Audience :: Developers", + # Need to confirm Fantom / NI-VISA license compatibility + # "License :: OSI Approved :: GNU General Public License (GPL)", + # "License :: OSI Approved :: GNU General Public License v2", + "Programming Language :: C++", + "Topic :: Software Development :: Libraries", + "Topic :: System :: Networking", + "Topic :: Communications", + "Operating System :: MacOS :: MacOS X" ] + ) -- cgit v1.2.3 From 4ca74ae715848ddc6cb3272a8b2c655240d70180 Mon Sep 17 00:00:00 2001 From: Tat-Chee Wan (USM) Date: Tue, 1 Mar 2011 15:51:11 +0800 Subject: modified module name to pyfantom --- nxt-python-fantom/nxt/fantomglue.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/nxt-python-fantom/nxt/fantomglue.py b/nxt-python-fantom/nxt/fantomglue.py index a987a7e..4a2497a 100644 --- a/nxt-python-fantom/nxt/fantomglue.py +++ b/nxt-python-fantom/nxt/fantomglue.py @@ -14,7 +14,7 @@ # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. -import fantom +import pyfantom FANTOM_BT='BT' FANTOM_USB='USB' @@ -22,7 +22,7 @@ FANTOM_USB='USB' def discover_devices(lookup_names=False): # parameter is ignored pairs = [] - d = fantom.finddevices(proto = FANTOM_BT) + d = pyfantom.finddevices(proto = FANTOM_BT) for p in d: h = p[0] n = p[1] @@ -33,7 +33,7 @@ class BluetoothSocket: def __init__(self, proto = FANTOM_BT, _sock=None): if _sock is None: - _sock = fantom.socket(proto) + _sock = pyfantom.socket(proto) self._sock = _sock self._proto = proto -- cgit v1.2.3 From 2234d3c1cae095a3a450e7c5bbf0c7b89bb6c346 Mon Sep 17 00:00:00 2001 From: Tat-Chee Wan (USM) Date: Tue, 1 Mar 2011 16:59:50 +0800 Subject: updated to handle fantom i386 only lib issue, framework linking --- FantomModule/setup.py | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/FantomModule/setup.py b/FantomModule/setup.py index 25dd152..e713d2f 100644 --- a/FantomModule/setup.py +++ b/FantomModule/setup.py @@ -1,16 +1,21 @@ from distutils.core import setup, Extension import sys +import os def getextensions(): mac_ext = Extension("FantomModule", define_macros=[('PYFANTOM_DEBUG', '0')], # set to '1' to print debug messges include_dirs=['.'], - extra_compile_args=['-arch i386'], - libraries=["Fantom"], + extra_compile_args=["-Wno-strict-prototypes"], + extra_link_args=["-framework Fantom"], sources=["FantomModule.cpp"] ) return [mac_ext] +# Must specify i386 arch via environment variable since Fantom libraries are i386 only +# Order of gcc flags is important, it can't be specified via Extension() module +os.environ['ARCHFLAGS'] = '-arch i386' + # install the main library setup(name="pyfantom", version="0.1", -- cgit v1.2.3