diff --git a/LICENSE b/LICENSE
new file mode 100644
index 0000000..f288702
--- /dev/null
+++ b/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/README.md b/README.md
index 4c0eba2..cd061ae 100644
--- a/README.md
+++ b/README.md
@@ -1,22 +1,41 @@
# PiCar
+
Module to Support ESE205 PiCar Platform
The PiCar comes equipped with a variety of sensors. In order to facilitate off-car development, this module provides a wrapper around the code to interact with several key car components. This way, you can test your code with your own hardware before attempting to test it on the car. The following table describes how you should interact with the available sensors:
-| Sensor | Method |
-|---|---|
-| Camera | Use as Normal UNLESS threaded=True, in which case use PiCar.get_image() |
-| DC Motor | Use PiCar.set_motor(DutyCycle) |
-| Servo(s) | Use PiCar.set_[servo_name]_servo(value) |
-| ADC | Use functions as normal, but use the PiCar.adc variable instead of your own mcp variable |
-| Ultrasonic | Use PiCar.read_distance() |
+| Sensor | Method |
+| ---------- | ---------------------------------------------------------------------------------------- |
+| Camera | Use as Normal UNLESS threaded=True, in which case use PiCar.get_image() |
+| DC Motor | Use PiCar.set_motor(DutyCycle) |
+| Servo(s) | Use PiCar.set\_[servo_name]\_servo(value) |
+| ADC | Use functions as normal, but use the PiCar.adc variable instead of your own mcp variable |
+| Ultrasonic | Use PiCar.read_distance() |
For examples of PiCar.[function_name] interaction, see [Usage](#Usage)
-PiCar assumes specific wiring of your components for use in simulated hardware mode. See [Hardware Connection](#Hardware_Connection) for the default configuration (reccomended), or see [Configuration](#Configuration) to see how to specify your own hardware setup.
+PiCar assumes specific wiring of your components for use in simulated hardware mode. See [Hardware Connection](#Hardware_Connection) for the default configuration (reccomended), or see [Configuration](#Configuration) to see how to specify your own hardware setup.
# Installation
-The following will install the package and all dependencies:
+
+You will first need to install redis with the following command:
+
+```bash
+
+sudo apt install redis -y
+
+```
+
+Verify redis is installed and running with:
+
+```bash
+
+service redis status
+
+```
+
+The following will install the package and all python dependencies:
+
```bash
pip3 install git+https://github.com/ESE205/PiCar
```
@@ -52,6 +71,7 @@ configure.configure_car(car)
```
Quick rundown of helpful commands:
+
```python
# import PiCar class
@@ -66,8 +86,12 @@ car = PiCar(mock_car=True, pins=None, config_name=None)
# i.e. provide servo configuration for car 3
car = PiCar(mock_car=False, pins=None, config_name="PICAR_CONFIG_CAR3.txt")
+# A method which passes the image through the thread to the PiCar main class
+def send_image(img):
+ return img
+
# initialize PiCar in threaded mode
-car = PiCar(mock_car=False, threaded=True)
+car = PiCar(mock_car=False, threaded=True, cam_task=send_image)
# turn on the DC motor- duty_cycle ranges 0-100, forward is optional but is either True (forward) or False (backward)
car.set_motor(100)
@@ -85,7 +109,7 @@ car.configure_swivel_servo_positions(2, 7, 12)
car.configure_steer_servo_positions(4, 9, 12)
# set the servo positions
-# range for servo functions is -10 (down/left) to 10 (up/right) with 0 being center
+# range for servo functions is -10 (down/left) to 10 (up/right) with 0 being center
car.set_nod_servo(-10)
car.set_swivel_servo(0)
car.set_steer_servo(10)
@@ -108,6 +132,7 @@ print(car)
```
# PiCar.configure
+
The configure module is set up to help handle servo inconsistency across hardware. Running `configure.configure_car` will give you the opportunity to generate a configuraton file with the left, middle, and right servo positions for your specific hardware, which will then be used on initialization of the PiCar module.
```python
@@ -144,17 +169,40 @@ To remove the need for complicated timing considerations, the PiCar supports thr
> NOTE: If using threaded mode, the PiCamera module cannot be instantiated in any user code. To get images from the camera, only the PiCar.get_image() method should be used.
+When the PiCar is running in threaded mode, it must have a `cam_task` parameter. This is a python function which will be performed upon the images in the same thread as the taking of the pictures, and will return a result, which will be returned upon a call to `PiCar.get_image()`. This method takes a single parameter, an image taken with the PiCamera, and can return whatever you like. This approach allows you to offload image processing to a different thread, and reduce the amount of data being passed between processes, which will improve timing consistency. There are several examples below.
+
```python
# import PiCar class
from picar import PiCar
+# A method which passes the image through the thread to the PiCar main class
+# This would achieve the same result as the current PiCar get_image() implementation
+def send_image(img):
+ return img
+
# initialize PiCar in threaded mode
-car = PiCar(mock_car=False, threaded=True)
+car = PiCar(mock_car=False, threaded=True, cam_task=send_image)
+
+img = car.get_image() # returns an image if one is available, or None
+
+# A method which performs some processing on the image, and returns an angle
+def get_angle(img):
+ hsv = cv2Color(img, cv2.COLOR_BGR2HSV)
+ mask = cv2.inRange(hsv, (100, 100, 200), (150, 150, 250))
+ moments = cv2.moments(mask)
+ # ... other code
+ # compute the angle
+ return angle
+
+# initialize PiCar in threaded mode
+car = PiCar(mock_car=False, threaded=True, cam_task=get_angle)
+
+img = car.get_image() # returns an angle if one is available, or none
```
-Threaded mode spawns two threads- one for ultrasonic readings, and one for the PiCamera. Each sets a target sample rate. When a reading from either is requested, *only the most recent reading will be returned*. All other readings will be discarded.
+Threaded mode spawns two threads- one for ultrasonic readings, and one for the PiCamera. Each sets a target sample rate. When a reading from either is requested, _only the most recent reading will be returned_. All other readings will be discarded.
```python
@@ -175,62 +223,62 @@ dist = car.read_distance()
While the ADC can be used the same way as you would normally interface with an ADC, we have set up the ADC for the PiCar to have specific chanels tied to different functionality.
-| ADC Channel | Function |
-|---|---|
-| 0 | Photo Resistor |
-| 1 | - |
-| 2 | - |
-| 3 | - |
-| 4 | - |
-| 5 | - |
-| 6 | - |
-| 7 | On/Off Switch |
+| ADC Channel | Function |
+| ----------- | -------------- |
+| 0 | Photo Resistor |
+| 1 | - |
+| 2 | - |
+| 3 | - |
+| 4 | - |
+| 5 | - |
+| 6 | - |
+| 7 | On/Off Switch |
# Hardware Connecton for Simulated Hardware
## DC Motor
| Motor Driver Pin Label | Motor Driver Pin Number | Pi Pin Label | Pi Pin Number |
-|---|---|---|---|
-| ENA | - | GPIO06 | 31 |
-| IN1 | - | GPIO13 | 33 |
-| IN2 | - | GPIO26 | 35 |
+| ---------------------- | ----------------------- | ------------ | ------------- |
+| ENA | - | GPIO06 | 31 |
+| IN1 | - | GPIO13 | 33 |
+| IN2 | - | GPIO26 | 35 |
## Servos
-| Servo Pin Label | Servo Pin Number | Pi Pin Label | Pi Pin Number |
-|---|---|---|---|
-| Nod Servo Signal | - | GPIO17 | 11 |
-| Swivel Servo Signal | - | GPIO27 | 13 |
-| Steer Servo Signal | - | GPIO22 | 15 |
+| Servo Pin Label | Servo Pin Number | Pi Pin Label | Pi Pin Number |
+| ------------------- | ---------------- | ------------ | ------------- |
+| Nod Servo Signal | - | GPIO17 | 11 |
+| Swivel Servo Signal | - | GPIO27 | 13 |
+| Steer Servo Signal | - | GPIO22 | 15 |
## ADC
**NOTE**: See [ADC Channels](#ADC_Channels) for which channel should be tied to which physical component
| ADC Pin Label | ADC Pin Number | Pi Pin Label | Pi Pin Number |
-|---|---|---|---|
-| VDD | 16 | 3v3 | 1 |
-| VREF | 15 | 3v3 | 1 |
-| AGND | 14 | GND | 6 |
-| CLK | 13 | SCLK | 40 |
-| DOUT | 12 | MISO | 21 |
-| DIN | 11 | MOSI | 19 |
-| CS | 10 | CE1 | 26 |
-| DGND | 9 | GND | 6 |
+| ------------- | -------------- | ------------ | ------------- |
+| VDD | 16 | 3v3 | 1 |
+| VREF | 15 | 3v3 | 1 |
+| AGND | 14 | GND | 6 |
+| CLK | 13 | SCLK | 40 |
+| DOUT | 12 | MISO | 21 |
+| DIN | 11 | MOSI | 19 |
+| CS | 10 | CE1 | 26 |
+| DGND | 9 | GND | 6 |
## Ultrasonic
**WARNING**: Remember that the Ultrasonic Echo uses 5V logic, so it needs to be stepped down via a 1K and 2K resistor
| Ultrasonic Pin Label | Ultrasonic Pin Number | Pi Pin Label | Pi Pin Number |
-|---|---|---|---|
-| Trigger | - | GPIO23 | 16 |
-| Echo | - | GPIO24 | 18 |
+| -------------------- | --------------------- | ------------ | ------------- |
+| Trigger | - | GPIO23 | 16 |
+| Echo | - | GPIO24 | 18 |
# Configuration
-There are two main options for configuration of the PiCar module.
+There are four main options for configuration of the PiCar module.
## Servo Range
@@ -255,7 +303,7 @@ When initializing the PiCar class, you can pass a `pins` argument which will ove
```python
# for the following variables, provide your own pin numbers
-motor_enable = 10
+motor_enable = 10
motor_pin_1 = 11
motor_pin_2 = 12
servo_nod = 13
@@ -270,11 +318,32 @@ car = PiCar(mock_car=True, pins=pins)
```
+## Camera Resolution and Framerate
+
+It is possible to configure the framerate and resolution of the PiCar class when operating in threaded mode.
+
+These default to `(640, 368)` for your resolution, and `15fps` for your framerate. Trying to set these too large or too high could lead to a performance bottleneck, so modify this value cautiously. Additionally, the framerate is only a target value, not a gauranteed value.
+
+```py
+picar = PiCar(threaded=True, camera_target_rate=15, camera_resolution=(640,368))
+```
+
+## Ultrasonic Target Rate
+
+It is possible to configure the target rate for ultrasonic distance sample collection when operating in threaded mode.
+
+The PiCar class defaults to `10` samples per second. This is only a target value, setting it significantly higher will not guarentee the specified target rate, and could lead to performance impacts on your code.
+
+```py
+picar = PiCar(threaded=True, ultrasonic_target_rate=10)
+```
+
# Module Function Documentation
## State Variables
You have access to state variables for the following:
+
- nod_servo_state
- swivel_servo_state
- steer_servo_state
@@ -291,14 +360,14 @@ car.steer_servo_state
Initialize the PiCar Module
-*Arguments*:
+_Arguments_:
**mock_car (bool) (Optional) (Default=True)**: True for simulated hardware, False to run on actual PiCar
**pins (tuple) (Optional) (Default=None)**: List of Custom pins to be used in simulated hardware, in following order:
(motor_enable, motor_pin_1, motor_pin_2, servo_nod, servo_swivel, servo_steer, ultrasonic_trigger, ultrasonic_echo)
-*Examples:*
+_Examples:_
```python
# init car with mock hardware
@@ -310,18 +379,20 @@ car = PiCar(False)
# init car with mock hardware and custom pins
car = PiCar(True, pins=pins)
```
+
---
+
## set_motor
Sets the Duty Cycle and Direction of the DC Motor
-*Arguments*:
+_Arguments_:
**duty_cycle (int)**: Duty Cycle for DC Motor between 0 and 100
**forward (bool) (Optional) (Default=True)**: True for forward direction, False for reverse direction
-*Examples:*
+_Examples:_
```python
# set duty cycle to half
@@ -330,12 +401,14 @@ car.set_motor(50)
# set duty cycle to half in reverse direction
car.set_motor(50, forward=False)
```
+
---
+
## stop
Stop the hardware - will kill PWM instance for all motors and servos
-*Examples:*
+_Examples:_
```python
# kill car
@@ -346,82 +419,94 @@ car.stop()
car = PiCar()
# do something with the car
```
+
---
+
## configure_nod_servo_positions
Allows user to provide alternate servo positions for nod servo in mock hardware.
PiCar assumes a default of 5 for left, 7.5 for middle, and 10 for right.
-*Arguments*:
+_Arguments_:
**left (int)**: servo duty cycle for left position
**middle (int)**: servo duty cycle for middle position
**right (int)**: servo duty cycle for right position
-*Examples:*
+_Examples:_
```python
# for a servo with a range 0-14
car.configure_nod_servo_positons(0, 7, 14)
```
+
---
+
## set_nod_servo
Sets the nod servo to the specified relative Duty Cycle.
-`set_nod_servo` uses internal left, middle, and right positions and maps the `value` argument to them via linear interpolation. For example, with `left=0, middle=5, right=10` and `value=5`, set_nod_servo will set the nod servo duty cycle to `7.5`, whereas a `value=-5` would yield a duty cycle of `2.5`.
+`set_nod_servo` uses internal left, middle, and right positions and maps the `value` argument to them via linear interpolation. For example, with `left=0, middle=5, right=10` and `value=5`, set_nod_servo will set the nod servo duty cycle to `7.5`, whereas a `value=-5` would yield a duty cycle of `2.5`.
The left, middle, and right values can be configured via `configure_nod_servo_positons`.
-*Arguments:*
+_Arguments:_
**value (int)**: Between -10 and 10, -10 being max down/left, 0 being middle/center, and 10 being max up/right
-*Examples:*
+_Examples:_
```python
# set nod servo to point max up/right
car.set_nod_servo(10)
```
+
---
+
## configure_swivel_servo_positions
See `configure_nod_servo_positons`
---
+
## set_swivel_servo
See `set_nod_servo`
---
+
## configure_steer_servo_positions
See `configure_nod_servo_positons`
---
+
## set_steer_servo
See `set_nod_servo`
---
+
## read_distance
Reads the ultrasonic sensor and returns calculated distance.
**Return Value (float)**: distance in cm from object as detected by ultrasonic sensor
-*Examples:*
+_Examples:_
```python
# get distance as calculated via the ultrasonic sensor
distance = car.read_distance()
```
+
---
+
## adc
The MCP3008 ADC can be accessed via the PiCar `adc` class variable exactly how you would normally interface with an ADC.
-*Examples:*
+_Examples:_
```python
# read the adc 0 channel
@@ -430,4 +515,4 @@ car.adc.read_adc(0)
# Contributing
-When contributing, make sure to increment the **version** field in **setup.py**, otherwise the package will not overwrite the currently installed package on user systems.
\ No newline at end of file
+When contributing, make sure to increment the **version** field in **setup.py**, otherwise the package will not overwrite the currently installed package on user systems.
diff --git a/VERSION b/VERSION
index 1f77169..27efe3e 100644
--- a/VERSION
+++ b/VERSION
@@ -1 +1 @@
-0.4.13
+0.6.0-alpha
\ No newline at end of file
diff --git a/picar/CarProcesses.py b/picar/CarProcesses.py
deleted file mode 100644
index 18ea8e1..0000000
--- a/picar/CarProcesses.py
+++ /dev/null
@@ -1,63 +0,0 @@
-from time import time, sleep
-import RPi.GPIO as GPIO
-from picamera.array import PiRGBArray
-from picamera import PiCamera
-
-
-def ps_image_stream(queue, resolution=(1280, 720), framerate=30):
- """
- The process function to take photos from the camera
- queue: multiprocessing.Manager.Queue = queue to store image data in
- resolution: (width: Int, height: Int) = resolution of images to take
- framerate: Int = target FPS
- """
- try:
- camera = PiCamera()
- camera.resolution = resolution
- camera.framerate = framerate
- rawCapture = PiRGBArray(camera, size=resolution)
- for frame in camera.capture_continuous(
- rawCapture, format="bgr", use_video_port=True
- ):
- queue.put((frame.array, time()))
- rawCapture.truncate(0)
- except KeyboardInterrupt:
- pass
-
-
-def ps_ultrasonic_dist(queue, ECHO_PIN, TRIG_PIN, target_sample_rate=10):
- """
- The process function to read ultrasonic values
- queue: multiprocessing.Manager.Queue = queue to store ultrasonic data in
- ECHO_PIN: GPIO.BOARD Pin = attached to ultrasonic echo pin
- TRIG_PIN: GPIO.BOARD Pin = attached to ultrasonic trigger pin
- target_sample_rate: Int = target sample rate
- """
- TRIG_TIME = 0.00001
-
- start_time, end_time = (0, 0)
-
- nextTime = time()
- try:
- while True:
-
- if time() > nextTime:
- # trigger a reading
- GPIO.output(TRIG_PIN, True)
- sleep(TRIG_TIME)
- GPIO.output(TRIG_PIN, False)
-
- # find the start and end of the ultrasonic pulse
- while GPIO.input(ECHO_PIN) == 0:
- start_time = time()
- while GPIO.input(ECHO_PIN) == 1:
- end_time = time()
-
- # Speed of sound 34300 cm/sec
- dist = (end_time - start_time) * 34300 / 2
-
- queue.put((dist, time()))
-
- nextTime += 1 / target_sample_rate
- except KeyboardInterrupt:
- pass
diff --git a/picar/ParallelTask.py b/picar/ParallelTask.py
index 28589df..4bdb4ba 100644
--- a/picar/ParallelTask.py
+++ b/picar/ParallelTask.py
@@ -1,45 +1,128 @@
-from multiprocessing import Process, Manager, Queue
+from multiprocessing import Process, Event
+import redis
+import RPi.GPIO as GPIO
+from time import time, sleep
+from picamera.array import PiRGBArray
+from picamera import PiCamera
-class ParallelTask:
+from typing import Tuple
- _process = None
- _queue = None
+class UltrasonicProcess(Process):
+ """
+ The process function to read ultrasonic values
+ queue: multiprocessing.Manager.Queue = queue to store ultrasonic data in
+ ECHO_PIN: GPIO.BOARD Pin = attached to ultrasonic echo pin
+ TRIG_PIN: GPIO.BOARD Pin = attached to ultrasonic trigger pin
+ target_sample_rate: Int = target sample rate
+ """
- @staticmethod
- def get_from_queue(queue):
- """
- The method to flush the queues and return the most recent result
- Args:
- queue: multiprocessing.Manager.Queue
- return: (data value, time read, datapoints in queue when called)
- """
- v = (None, None)
- tossed_readings = 0
- while not queue.empty():
- tossed_readings += 1
- # don't block if the queue is busy
- v = queue.get_nowait()
- # expand the queue 2-tuple (reading, time read) into a flat 3-tuple
- return (*v, tossed_readings)
+ _db = redis.Redis(host="localhost", port=6379, db=0)
- def __init__(self, funct, funct_args):
+ TRIG_TIME = 0.00001
- manager = Manager()
+ sample_rate: int = 10
+ trig_pin: int = None
+ echo_pin: int = None
- self._queue = manager.Queue()
+ def __init__(
+ self,
+ echo_pin: int,
+ trig_pin: int,
+ target_sample_rate: int = 10,
+ ):
+ Process.__init__(self)
- self._process = Process(target=funct, args=(self._queue, *funct_args))
+ self.sample_rate = target_sample_rate
+ self.trig_pin = trig_pin
+ self.echo_pin = echo_pin
- self._process.start()
+ self.kill = Event()
- def get_result(self):
- """
- Method to return process result
- data takes the format (reading, time read, values in queue when read)
- """
- # note that get_from_queue empties the queue
- data = ParallelTask.get_from_queue(self._queue)
+ def run(self):
- return data
+ start_time, end_time = (0, 0)
+
+ nextTime = time()
+
+ while not self.kill.is_set():
+ if time() > nextTime:
+ # trigger a reading
+ GPIO.output(self.trig_pin, True)
+ sleep(self.TRIG_TIME)
+ GPIO.output(self.trig_pin, False)
+
+ # find the start and end of the ultrasonic pulse
+ while GPIO.input(self.echo_pin) == 0:
+ start_time = time()
+ while GPIO.input(self.echo_pin) == 1:
+ end_time = time()
+
+ # Speed of sound 34300 cm/sec
+ dist = (end_time - start_time) * 34300 / 2
+ dist_time = time()
+ self._db.set("dist_ps_result", dist, time())
+ self._db.set("dist_update_time", dist_time)
+
+ nextTime += 1 / self.sample_rate
+
+ def stop(self):
+ self.kill.set()
+
+
+class CameraProcess(Process):
+ """
+ The process function to read ultrasonic values
+ queue: multiprocessing.Manager.Queue = queue to store ultrasonic data in
+ ECHO_PIN: GPIO.BOARD Pin = attached to ultrasonic echo pin
+ TRIG_PIN: GPIO.BOARD Pin = attached to ultrasonic trigger pin
+ target_sample_rate: Int = target sample rate
+ """
+
+ _db = redis.Redis(host="localhost", port=6379, db=0)
+
+ resolution: Tuple[int, int] = None
+ framerate: int = None
+ task = None
+
+ def __init__(
+ self,
+ cam_task=None,
+ resolution: Tuple[int, int] = (1280, 720),
+ framerate: int = 30,
+ ):
+ Process.__init__(self)
+
+ self.resolution = resolution
+ self.framerate = framerate
+
+ self.task = cam_task
+
+ self.kill = Event()
+
+ def run(self):
+
+ camera = PiCamera()
+ camera.resolution = self.resolution
+ camera.framerate = self.framerate
+ rawCapture = PiRGBArray(camera, size=self.resolution)
+ for frame in camera.capture_continuous(
+ rawCapture, format="bgr", use_video_port=True
+ ):
+
+ # TODO test this to make sure it sends fine
+ res = frame.array
+ if self.task is not None:
+ res = self.task(frame.array)
+ else:
+ res = bytes(res)
+ cam_time = time()
+ self._db.set("cam_ps_result", res)
+ self._db.set("cam_update_time", cam_time)
+ rawCapture.truncate(0)
+ if self.kill.is_set():
+ break
+
+ def stop(self):
+ self.kill.set()
\ No newline at end of file
diff --git a/picar/PiCar.py b/picar/PiCar.py
index ef79623..757b048 100644
--- a/picar/PiCar.py
+++ b/picar/PiCar.py
@@ -1,15 +1,17 @@
import RPi.GPIO as GPIO
import time
+from typing import Tuple
import Adafruit_PCA9685 as PWM_HAT
from Adafruit_GPIO.GPIO import RPiGPIOAdapter as Adafruit_GPIO_Adapter
import Adafruit_MCP3008
-from picar.CarProcesses import ps_image_stream, ps_ultrasonic_dist
-from picar.ParallelTask import ParallelTask
+from picar.ParallelTask import CameraProcess, UltrasonicProcess
+from picar.Servo import Servo
-import pkg_resources
import os.path
+import redis
+import struct
class PiCar:
@@ -18,47 +20,48 @@ class PiCar:
"""
# Global Variables
- PICAR_CONFIG_FILE_NAME = "PICAR_CONFIG.txt"
+ PICAR_CONFIG_FILE_NAME: str = "PICAR_CONFIG.txt"
- MOCK_CAR_CONFIG_FILE_NAME = "MOCK_CAR_CONFIG.txt"
+ MOCK_CAR_CONFIG_FILE_NAME: str = "MOCK_CAR_CONFIG.txt"
- SERVO_NOD = 0
- SERVO_SWIVEL = 1
- SERVO_STEER = 2
+ SERVO_NOD: int = 0
+ SERVO_SWIVEL: int = 1
+ SERVO_STEER: int = 2
# Class Variables
_simulated_hardware = None
_motor_enable, _motor_pin_1, _motor_pin_2, _motor_pwm = (None, None, None, None)
- motor_state = 0
+ motor_state: int = 0
_servo_global_pwm = None
- _servo_nod_pin, _servo_nod_pwm = (None, None)
- _servo_nod_left, _servo_nod_middle, _servo_nod_right = (295, 425, 662)
-
- nod_servo_state = 0
-
- _servo_swivel_pin, _servo_swivel_pwm = (None, None)
- _servo_swivel_left, _servo_swivel_middle, _servo_swivel_right = (140, 310, 476)
-
- swivel_servo_state = 0
-
- _servo_steer_pin, _servo_steer_pwm = (None, None)
- _servo_steer_left, _servo_steer_middle, _servo_steer_right = (280, 370, 500)
-
- steer_servo_state = 0
+ steer_servo: Servo = None
+ swivel_servo: Servo = None
+ nod_servo: Servo = None
_ultrasonic_trigger, _ultrasonic_echo = (None, None)
- _threaded = None
+ _threaded: bool = None
_camera_process, _ultrasonic_process = (None, None)
+ _redis = None
+
adc = None
- def __init__(self, mock_car=True, pins=None, config_name=None, threaded=False):
+ def __init__(
+ self,
+ mock_car: bool = True,
+ pins: Tuple[int, int, int, int, int, int, int, int] = None,
+ config_name: str = None,
+ threaded: bool = False,
+ ultrasonic_target_rate: int = None,
+ camera_target_rate: int = None,
+ camera_resolution: Tuple[int, int] = None,
+ cam_task=None,
+ ):
"""
Initialize the PiCar Module
---------------------------
@@ -80,6 +83,8 @@ def __init__(self, mock_car=True, pins=None, config_name=None, threaded=False):
self._simulated_hardware = mock_car
+ GPIO.setwarnings(False)
+
GPIO.setmode(GPIO.BOARD)
print("configuring pins...")
@@ -97,7 +102,16 @@ def __init__(self, mock_car=True, pins=None, config_name=None, threaded=False):
# specify default pins for real hardware
if pins is not None:
print("Custom pins overridden - not allowed when mock_car is False")
- pins = (11, 13, 12, 0, 1, 2, 23, 24)
+ pins = (
+ 11,
+ 13,
+ 12,
+ self.SERVO_NOD,
+ self.SERVO_SWIVEL,
+ self.SERVO_STEER,
+ 23,
+ 24,
+ )
self._init_pins(pins)
if self._simulated_hardware:
@@ -109,26 +123,60 @@ def __init__(self, mock_car=True, pins=None, config_name=None, threaded=False):
if self._threaded:
print("Program is running in THREADED MODE")
+
+ self._redis = redis.Redis(host="localhost", port=6379, db=0)
+
print(
"NOTE: All use of the PiCamera module should be through PiCar.get_image"
)
print(
"Any attempt to use the PiCamera module in another context will crash your program"
)
- self._camera_process = ParallelTask(ps_image_stream, ((640, 360), 15))
- self._ultrasonic_process = ParallelTask(
- ps_ultrasonic_dist, (self._ultrasonic_echo, self._ultrasonic_trigger)
+ camera_resolution = (
+ (640, 368) if camera_resolution is None else camera_resolution
+ )
+ camera_target_rate = (
+ 15 if camera_target_rate is None else camera_target_rate
)
+
+ # self._camera_process = ParallelTask(
+ # ps_image_stream, (camera_resolution, camera_target_rate)
+ # )
+ if cam_task is None:
+ raise SystemExit(
+ "FATAL: you must provide a cam_task to the PiCar while in threaded mode"
+ )
+ self._camera_process = CameraProcess(
+ cam_task, camera_resolution, camera_target_rate
+ )
+ self._camera_process.start()
+
+ ultrasonic_target_rate = (
+ 10 if ultrasonic_target_rate is None else ultrasonic_target_rate
+ )
+
+ # self._ultrasonic_process = ParallelTask(
+ # ps_ultrasonic_dist,
+ # (
+ # self._ultrasonic_echo,
+ # self._ultrasonic_trigger,
+ # ultrasonic_target_rate,
+ # ),
+ # )
+ self._ultrasonic_process = UltrasonicProcess(
+ self._ultrasonic_echo, self._ultrasonic_trigger, ultrasonic_target_rate
+ )
+ self._ultrasonic_process.start()
# give the camera a bit to wake up
time.sleep(1)
print("initializing software SPI")
# initialize software SPI
gpio_adapter = Adafruit_GPIO_Adapter(GPIO, mode=GPIO.BOARD)
- clk_pin = 40
- miso_pin = 21
- mosi_pin = 19
- cs_pin = 26
+ clk_pin: int = 40
+ miso_pin: int = 21
+ mosi_pin: int = 19
+ cs_pin: int = 26
self.adc = Adafruit_MCP3008.MCP3008(
clk=clk_pin, cs=cs_pin, miso=miso_pin, mosi=mosi_pin, gpio=gpio_adapter
@@ -145,6 +193,11 @@ def __init__(self, mock_car=True, pins=None, config_name=None, threaded=False):
f"looking for config file: ./{self.MOCK_CAR_CONFIG_FILE_NAME if mock_car else self.PICAR_CONFIG_FILE_NAME}"
)
+ # low middle high
+ nod_servo_config = (280, 370, 500)
+ swivel_servo_config = (280, 370, 500)
+ steer_servo_config = (280, 370, 500)
+
if os.path.exists(
self.MOCK_CAR_CONFIG_FILE_NAME if mock_car else self.PICAR_CONFIG_FILE_NAME
):
@@ -162,17 +215,19 @@ def __init__(self, mock_car=True, pins=None, config_name=None, threaded=False):
f"Invalid configuration file, expected 9 elements, found {len(configuration)}"
)
else:
- self.configure_nod_servo_positions(
+ nod_servo_config = (
int(configuration[1]),
int(configuration[0]),
int(configuration[2]),
)
- self.configure_swivel_servo_positions(
+
+ swivel_servo_config = (
int(configuration[4]),
int(configuration[3]),
int(configuration[5]),
)
- self.configure_steer_servo_positions(
+
+ steer_servo_config = (
int(configuration[7]),
int(configuration[6]),
int(configuration[8]),
@@ -180,6 +235,10 @@ def __init__(self, mock_car=True, pins=None, config_name=None, threaded=False):
else:
print("servo configuration not found, using default values")
+ self.nod_servo = Servo(pins[3], self._servo_global_pwm, *nod_servo_config)
+ self.swivel_servo = Servo(pins[4], self._servo_global_pwm, *swivel_servo_config)
+ self.steer_servo = Servo(pins[5], self._servo_global_pwm, *steer_servo_config)
+
print("PiCar configured successfully")
print(self)
@@ -189,23 +248,19 @@ def __init__(self, mock_car=True, pins=None, config_name=None, threaded=False):
# set initial component states
self.set_motor(0)
- self.set_nod_servo(0)
- self.set_swivel_servo(0)
- self.set_steer_servo(0)
-
def _init_pins(self, pins):
"""
pins: List of pins to be configured for hardware, in following order:
- (motor_pin_1, motor_pin_2, motor_enable, servo_nod, servo_swivel, servo_steer)
+ (motor_enable, motor_pin_1, motor_pin_2, servo_nod, servo_swivel, servo_steer)
"""
(
self._motor_enable,
self._motor_pin_1,
self._motor_pin_2,
- self._servo_nod_pin,
- self._servo_swivel_pin,
- self._servo_steer_pin,
+ _,
+ _,
+ _,
self._ultrasonic_trigger,
self._ultrasonic_echo,
) = pins
@@ -215,38 +270,20 @@ def _init_pins(self, pins):
GPIO.setup(self._motor_pin_1, GPIO.OUT, initial=GPIO.LOW)
GPIO.setup(self._motor_pin_2, GPIO.OUT, initial=GPIO.LOW)
- # setup servo pins
- if self._simulated_hardware:
- GPIO.setup(self._servo_nod_pin, GPIO.OUT)
- GPIO.setup(self._servo_swivel_pin, GPIO.OUT)
- GPIO.setup(self._servo_steer_pin, GPIO.OUT)
-
# setup ultrasonic pins
GPIO.setup(self._ultrasonic_trigger, GPIO.OUT, initial=GPIO.LOW)
GPIO.setup(self._ultrasonic_echo, GPIO.IN)
- def _init_mock_car(self):
+ def _init_mock_car(self) -> None:
"""
Initialize car variables for use with RPi Treated as Mock Car
"""
- self._servo_nod_pwm = GPIO.PWM(self._servo_nod_pin, 50)
- self._servo_swivel_pwm = GPIO.PWM(self._servo_swivel_pin, 50)
- self._servo_steer_pwm = GPIO.PWM(self._servo_steer_pin, 50)
-
- self.configure_nod_servo_positions(5, 7.5, 10)
- self.configure_swivel_servo_positions(5, 7.5, 10)
- self.configure_steer_servo_positions(5, 7.5, 10)
-
- self._servo_nod_pwm.start(self._servo_nod_middle)
- self._servo_swivel_pwm.start(self._servo_swivel_middle)
- self._servo_steer_pwm.start(self._servo_steer_middle)
-
self._motor_pwm = GPIO.PWM(self._motor_enable, 1000)
self._motor_pwm.start(0)
pass
- def _init_car(self):
+ def _init_car(self) -> None:
"""
Initialize car variables for use with the actual Adeept Car
"""
@@ -255,10 +292,9 @@ def _init_car(self):
self._motor_pwm = GPIO.PWM(self._motor_enable, 1000)
self._motor_pwm.start(0)
-
pass
- def set_motor(self, duty_cycle, forward=True):
+ def set_motor(self, duty_cycle: int, forward: bool = True) -> None:
"""
forward (bool):direction of motor spin
duty_cycle (int): 0->100
@@ -270,7 +306,7 @@ def set_motor(self, duty_cycle, forward=True):
self._motor_pwm.ChangeDutyCycle(duty_cycle)
self.motor_state = duty_cycle
- def reset(self):
+ def reset(self) -> None:
"""
Reset the hardware - will set all motors and servos to neutral positions
"""
@@ -280,218 +316,54 @@ def reset(self):
self.set_steer_servo(0)
self.set_swivel_servo(0)
- def stop(self):
+ def stop(self) -> None:
"""
Stop the hardware - will kill PWM instance for all motors and servos, and cleanup GPIO
"""
self._motor_pwm.stop()
- if self._simulated_hardware:
- self._servo_nod_pwm.stop()
- self._servo_swivel_pwm.stop()
- self._servo_steer_pwm.stop()
-
+ self.nod_servo.stop()
+ self.swivel_servo.stop()
+ self.steer_servo.stop()
+ if self._threaded:
+ self._camera_process.stop()
+ time.sleep(0.1)
+ self._camera_process.terminate()
+ self._camera_process.join()
+ self._ultrasonic_process.stop()
+ time.sleep(0.1)
+ self._ultrasonic_process.terminate()
+ self._ultrasonic_process.join()
GPIO.cleanup()
- def _calc_servo_duty_cycle(self, left, middle, right, amount, is_left):
- return (
- middle - (middle - left) * amount / 10
- if is_left
- else (right - middle) * amount / 10 + middle
- )
-
- def _set_servo(self, servo, value=None, raw=False):
- """
- Generic set servo code
- Wrapped by specific set servo commands so as to not change the API for students
- TODO: change API to use this for simplicity
- """
- if servo not in [PiCar.SERVO_NOD, PiCar.SERVO_SWIVEL, PiCar.SERVO_STEER]:
- raise SystemExit(
- f"Invalid servo specified to set_servo. Expected one of PiCar.SERVO_NOD, PiCar.SERVO_SWIVEL, PiCar.SERVO_STEER"
- )
- # handle special input cases
- if raw:
- if servo == PiCar.SERVO_NOD:
- self._servo_global_pwm.set_pwm(self._servo_nod_pin, 0, raw)
- self.nod_servo_state = raw
- elif servo == PiCar.SERVO_SWIVEL:
- self._servo_global_pwm.set_pwm(self._servo_swivel_pin, 0, raw)
- self.nod_swivel_state = raw
- elif servo == PiCar.SERVO_STEER:
- self._servo_global_pwm.set_pwm(self._servo_steer_pin, 0, raw)
- self.nod_steer_state = raw
- return
- if not (isinstance(value, int) or isinstance(value, float)):
- raise SystemExit(
- f"value argument must be numeric between -10 and 10. Expected int or float, found {type(value)}"
- )
-
- # cast value to correct range
- safe_value = max(min(10, value), -10)
- if safe_value != value:
- print(
- f"WARNING: value passed to set_[nod|swivel|steer]_servo exceeds expected range. Expected -10 <= value <= 10, found {value}"
- )
- print(f"Casting value to {safe_value}")
- value = safe_value
-
- is_left, amount = (value < 0, abs(value))
- duty_cycle = None
- if servo == PiCar.SERVO_NOD:
- duty_cycle = self._calc_servo_duty_cycle(
- self._servo_nod_left,
- self._servo_nod_middle,
- self._servo_nod_right,
- amount,
- is_left,
- )
- elif servo == PiCar.SERVO_SWIVEL:
- duty_cycle = self._calc_servo_duty_cycle(
- self._servo_swivel_left,
- self._servo_swivel_middle,
- self._servo_swivel_right,
- amount,
- is_left,
- )
- elif servo == PiCar.SERVO_STEER:
- duty_cycle = self._calc_servo_duty_cycle(
- self._servo_steer_left,
- self._servo_steer_middle,
- self._servo_steer_right,
- amount,
- is_left,
- )
-
- if self._simulated_hardware:
- if servo == PiCar.SERVO_NOD:
- self._servo_nod_pwm.ChangeDutyCycle(duty_cycle)
- elif servo == PiCar.SERVO_SWIVEL:
- self._servo_swivel_pwm.ChangeDutyCycle(duty_cycle)
- elif servo == PiCar.SERVO_STEER:
- self._servo_steer_pwm.ChangeDutyCycle(duty_cycle)
- else:
- if servo == PiCar.SERVO_NOD:
- self._servo_global_pwm.set_pwm(self._servo_nod_pin, 0, int(duty_cycle))
- elif servo == PiCar.SERVO_SWIVEL:
- self._servo_global_pwm.set_pwm(
- self._servo_swivel_pin, 0, int(duty_cycle)
- )
- elif servo == PiCar.SERVO_STEER:
- self._servo_global_pwm.set_pwm(
- self._servo_steer_pin, 0, int(duty_cycle)
- )
- if servo == PiCar.SERVO_NOD:
- self.nod_servo_state = value
- elif servo == PiCar.SERVO_SWIVEL:
- self.swivel_servo_state = value
- elif servo == PiCar.SERVO_STEER:
- self.steer_servo_state = value
-
- def configure_nod_servo_positions(self, left=None, middle=None, right=None):
- """
- Provide alternate nod servo positions
- Note: when setting servo positon, values between left and middle or left and right are linearly interpolated
- left (int): servo duty cycle for left position
- middle (int): servo duty cycle for middle position
- right (int): servo duty cycle for right position
- """
- if left is None:
- left = self._servo_nod_left
- if middle is None:
- middle = self._servo_nod_middle
- if right is None:
- right = self._servo_nod_right
- if False in [
- isinstance(x, int) or isinstance(x, float) for x in (left, middle, right)
- ]:
- raise SystemExit(
- f"All args must be integer values, expected int, int, int, found: {type(left)}, {type(middle)}, {type(right)}"
- )
- print(f"nod : {left} , {middle} , {right}")
- self._servo_nod_left = left
- self._servo_nod_middle = middle
- self._servo_nod_right = right
-
def set_nod_servo(self, value, raw=False):
"""
value (int): between -10 and 10, -10 being max down, 0 being center, and 10 being max up
raw (int): only to be used for TA debugging
"""
- self._set_servo(PiCar.SERVO_NOD, value, raw)
-
- def configure_swivel_servo_positions(self, left=None, middle=None, right=None):
- """
- Provide alternate swivel servo positions
- Note: when setting servo positon, values between left and middle or left and right are linearly interpolated
- left (int): servo duty cycle for left position
- middle (int): servo duty cycle for middle position
- right (int): servo duty cycle for right position
- """
- if left is None:
- left = self._servo_swivel_left
- if middle is None:
- middle = self._servo_swivel_middle
- if right is None:
- right = self._servo_swivel_right
- if False in [
- isinstance(x, int) or isinstance(x, float) for x in (left, middle, right)
- ]:
- raise SystemExit(
- f"All args must be integer values, expected int, int, int, found: {type(left)}, {type(middle)}, {type(right)}"
- )
- print(f"swivel : {left} , {middle} , {right}")
- self._servo_swivel_left = left
- self._servo_swivel_middle = middle
- self._servo_swivel_right = right
+ self.nod_servo.set_position(value, raw)
def set_swivel_servo(self, value, raw=False):
"""
value (int): between -10 and 10, -10 being max left, 0 being center, and 10 being max right
raw (int): only to be used for TA debugging
"""
- self._set_servo(PiCar.SERVO_SWIVEL, value, raw)
-
- def configure_steer_servo_positions(self, left=None, middle=None, right=None):
- """
- Provide alternate steer servo positions
- Note: when setting servo positon, values between left and middle or left and right are linearly interpolated
- left (int): servo duty cycle for left position
- middle (int): servo duty cycle for middle position
- right (int): servo duty cycle for right position
- """
- if left is None:
- left = self._servo_steer_left
- if middle is None:
- middle = self._servo_steer_middle
- if right is None:
- right = self._servo_steer_right
- if False in [
- isinstance(x, int) or isinstance(x, float) for x in (left, middle, right)
- ]:
- raise SystemExit(
- f"All args must be integer values, expected int, int, int, found: {type(left)}, {type(middle)}, {type(right)}"
- )
-
- print(f"steer : {left} , {middle} , {right}")
- self._servo_steer_left = left
- self._servo_steer_middle = middle
- self._servo_steer_right = right
+ self.swivel_servo.set_position(value, raw)
def set_steer_servo(self, value, raw=False):
"""
- Set the steer servo
+ Set the steer servo
value (int): between -10 and 10, -10 being max left, 0 being center, and 10 being max right
- raw (int): only to be used for TA debugging
+ raw (int): only to be used for TA debugging
"""
- self._set_servo(PiCar.SERVO_STEER, value, raw)
+ self.steer_servo.set_position(value, raw)
- def read_distance(self):
+ def read_distance(self) -> float:
"""
Read ultrasonic sensor
return (double): distance in cm from object as detected by ultrasonic sensor
"""
if self._threaded:
- return self._ultrasonic_process.get_result()[0]
+ return self._redis.get("dist_ps_result")
else:
# activate trigger
GPIO.output(self._ultrasonic_trigger, GPIO.HIGH)
@@ -508,66 +380,92 @@ def read_distance(self):
# compute one way distance in cm from a two way time in seconds
return (echo_end - echo_start) * 340 * 100 / 2
+ def get_distance_time(self):
+ """
+ returns the last time distance was updated in redis
+ NOTE: only valid if the program is threaded
+ """
+ if not self._threaded:
+ raise SystemExit(
+ "FATAL: get_image can only be called when PiCar is run in threaded mode"
+ )
+ return self._redis.get("dist_update_time")
+
def get_image(self):
"""
- returns an image object
+ If a cam_task is specified by the user, then returns the
+ result of that function.
+ Otherwise returns an image object which can be processed by OpenCV
NOTE: only valid if the program is threaded
"""
if not self._threaded:
raise SystemExit(
"FATAL: get_image can only be called when PiCar is run in threaded mode"
)
+ if self.cam_task is None:
+ # TODO unpack image from bytes
+ return self._redis.get("cam_ps_result")
+ else:
+ return self._redis.get("cam_ps_result")
- return self._camera_process.get_result()[0]
+ def get_image_time(self):
+ """
+ returns the last time image was updated in redis
+ NOTE: only valid if the program is threaded
+ """
+ if not self._threaded:
+ raise SystemExit(
+ "FATAL: get_image can only be called when PiCar is run in threaded mode"
+ )
+ return self._redis.get("cam_update_time")
def __repr__(self):
"""
Format PiCar for print representation
print(PiCar) will show currently configured pins
TODO: Add additional variables (i.e. simulated or not, whether all PWMs are configured, etc)
- TODO fix version
TODO: Add config filename
- with open("./VERSION", "r") as ver:
- version = ver.read().strip()
- print("ok")
"""
+ with open(os.path.join(os.path.dirname(__file__), "VERSION"), "r") as ver:
+ version = ver.read().strip()
+
entries = [
["State"],
["Motor", self.motor_state],
- ["Nod Servo", self.nod_servo_state],
- ["Swivel Servo", self.swivel_servo_state],
- ["Steer Servo", self.steer_servo_state],
+ ["Nod Servo", self.nod_servo.state],
+ ["Swivel Servo", self.swivel_servo.state],
+ ["Steer Servo", self.steer_servo.state],
["Configuration"],
[
"Nod Servo (l, m, r)",
- self._servo_nod_left,
- self._servo_nod_middle,
- self._servo_nod_right,
+ self.nod_servo.low,
+ self.nod_servo.middle,
+ self.nod_servo.high,
],
[
"Swivel Servo (l, m, r)",
- self._servo_swivel_left,
- self._servo_swivel_middle,
- self._servo_swivel_right,
+ self.swivel_servo.low,
+ self.swivel_servo.middle,
+ self.swivel_servo.high,
],
[
"Steer Servo (l, m, r)",
- self._servo_steer_left,
- self._servo_steer_middle,
- self._servo_steer_right,
+ self.steer_servo.low,
+ self.steer_servo.middle,
+ self.steer_servo.high,
],
["Pins"],
["Motor Enable", self._motor_enable],
["Motor 1", self._motor_pin_1],
["Motor 2", self._motor_pin_2],
- ["Nod Servo", self._servo_nod_pin],
- ["Swivel Servo", self._servo_swivel_pin],
- ["Steer Servo", self._servo_steer_pin],
+ ["Nod Servo", self.nod_servo._pin],
+ ["Swivel Servo", self.swivel_servo._pin],
+ ["Steer Servo", self.steer_servo._pin],
["Trigger", self._ultrasonic_trigger],
["Echo", self._ultrasonic_echo],
]
- rep = f"PiCar Version 0.3.x:\n"
+ rep = f"PiCar Version {version}:\n"
col_sizes = compute_column_lengths(entries)
diff --git a/picar/Servo.py b/picar/Servo.py
new file mode 100644
index 0000000..aee11b4
--- /dev/null
+++ b/picar/Servo.py
@@ -0,0 +1,144 @@
+import RPi.GPIO as GPIO
+
+
+class Servo:
+ """
+ Class to interface with a Servo
+ """
+
+ # Class Variables
+ _simulated_hardware: bool = None
+
+ _pin: int = None
+
+ # either a handle to GPIO pwm instance in the case of mock car
+ # or a handle to the global HAT servo interface in case of real car
+ _pwm = None
+
+ low: int = 0
+ middle: int = 0
+ high: int = 0
+
+ state: int = 0
+
+ def __init__(
+ self,
+ pin: int,
+ global_pwm_instance=None,
+ low: int = 300,
+ middle: int = 350,
+ high: int = 450,
+ ):
+ self._simulated_hardware = True
+ if global_pwm_instance is not None:
+ self._simulated_hardware = False
+ self._pwm = global_pwm_instance
+
+ self._init_pins(pin)
+
+ if self._simulated_hardware:
+ self._init_servo_hardware()
+
+ self.configure_positions(
+ low,
+ middle,
+ high,
+ )
+
+ self.set_position(0)
+
+ def _init_pins(self, pin: int) -> None:
+ """
+ pin: the pin to be used to control the servo, or the number for the hat device
+ """
+
+ self._pin = pin
+
+ if self._simulated_hardware:
+ GPIO.setup(self._pin, GPIO.OUT)
+
+ def _init_servo_hardware(self) -> None:
+ """
+ Initialize car variables for use with RPi Treated as Mock Car
+ """
+ self._pwm = GPIO.PWM(self._pin, 50)
+ self.configure_positions(5, 7.5, 10)
+ self._pwm.start(self.middle)
+
+ def stop(self) -> None:
+ """
+ Stop the hardware - will kill PWM instance for all motors and servos, and cleanup GPIO
+ """
+ if self._simulated_hardware:
+ self._pwm.stop()
+
+ def _calc_duty_cycle(self, amount: int, is_left: bool) -> float:
+ return (
+ self.middle - (self.middle - self.low) * amount / 10
+ if is_left
+ else (self.high - self.middle) * amount / 10 + self.middle
+ )
+
+ def set_position(self, value: int = None, raw: int = None) -> None:
+ """
+ Sets the servo to a specific position
+ """
+ # handle special input cases
+ if raw is not None:
+ # we will only be able to use raw values for off-the-shelf servos
+ # this should rarely be used
+ self._pwm.set_pwm(self._pin, 0, raw)
+ self.state = raw
+ return
+ if not (isinstance(value, int) or isinstance(value, float)):
+ raise SystemExit(
+ f"value argument must be numeric between -10 and 10. Expected int or float, found {type(value)}"
+ )
+
+ # cast value to correct range
+ safe_value = max(min(10, value), -10)
+ if safe_value != value:
+ print(
+ f"WARNING: value passed to Servo.set_position exceeds expected range. Expected -10 <= value <= 10, found {value}"
+ )
+ print(f"Casting value to {safe_value}")
+ value = safe_value
+
+ is_left, amount = (value < 0, abs(value))
+ duty_cycle = self._calc_duty_cycle(
+ amount,
+ is_left,
+ )
+
+ if self._simulated_hardware:
+ self._pwm.ChangeDutyCycle(duty_cycle)
+ else:
+ self._pwm.set_pwm(self._pin, 0, int(duty_cycle))
+
+ self.state = value
+
+ def configure_positions(
+ self, low: int = None, middle: int = None, high: int = None
+ ) -> None:
+ """
+ Provide alternate nod servo positions
+ Note: when setting servo positon, values between low and middle or low and high are linearly interpolated
+ low (int): servo duty cycle for low position
+ middle (int): servo duty cycle for middle position
+ high (int): servo duty cycle for high position
+ """
+ if low is None:
+ low = self._low
+ if middle is None:
+ middle = self._middle
+ if high is None:
+ high = self._high
+ if False in [
+ isinstance(x, int) or isinstance(x, float) for x in (low, middle, high)
+ ]:
+ raise SystemExit(
+ f"All args must be integer values, expected int, int, int, found: {type(low)}, {type(middle)}, {type(high)}"
+ )
+ self.low = low
+ self.middle = middle
+ self.high = high
\ No newline at end of file
diff --git a/picar/configure.py b/picar/configure.py
index ddc3c9e..b258f60 100644
--- a/picar/configure.py
+++ b/picar/configure.py
@@ -1,8 +1,7 @@
from picar import PiCar
-from time import sleep as wait
-def configure_car(pi_car_instance: PiCar):
+def configure_car(pi_car_instance: PiCar) -> None:
print("beginning configuration...")
@@ -31,47 +30,47 @@ def configure_car(pi_car_instance: PiCar):
for description, position, function in [
(
"middle for nod servo",
- pi_car_instance._servo_nod_middle,
+ pi_car_instance.nod_servo.middle,
pi_car_instance.set_nod_servo,
),
(
"low end for nod servo",
- pi_car_instance._servo_nod_left,
+ pi_car_instance.nod_servo.low,
pi_car_instance.set_nod_servo,
),
(
"high end for nod servo",
- pi_car_instance._servo_nod_right,
+ pi_car_instance.nod_servo.high,
pi_car_instance.set_nod_servo,
),
(
"middle for swivel servo",
- pi_car_instance._servo_swivel_middle,
+ pi_car_instance.swivel_servo.middle,
pi_car_instance.set_swivel_servo,
),
(
"low end for swivel servo",
- pi_car_instance._servo_swivel_left,
+ pi_car_instance.swivel_servo.low,
pi_car_instance.set_swivel_servo,
),
(
"high end for swivel servo",
- pi_car_instance._servo_swivel_right,
+ pi_car_instance.swivel_servo.high,
pi_car_instance.set_swivel_servo,
),
(
"middle for steer servo",
- pi_car_instance._servo_steer_middle,
+ pi_car_instance.steer_servo.middle,
pi_car_instance.set_steer_servo,
),
(
"low end for steer servo",
- pi_car_instance._servo_steer_left,
+ pi_car_instance.steer_servo.low,
pi_car_instance.set_steer_servo,
),
(
"high end for steer servo",
- pi_car_instance._servo_steer_middle,
+ pi_car_instance.steer_servo.high,
pi_car_instance.set_steer_servo,
),
]:
@@ -85,3 +84,5 @@ def configure_car(pi_car_instance: PiCar):
)
config.write(f"{int(final_position)}\n")
+
+ print("Config written to file")
diff --git a/picar/test.py b/picar/test.py
index 8c4dba0..2f9f43f 100644
--- a/picar/test.py
+++ b/picar/test.py
@@ -2,7 +2,7 @@
from time import sleep as wait
-def execute_test(pi_car_instance: PiCar):
+def execute_test(pi_car_instance: PiCar) -> None:
print("test motor range: off -> 50% -> 100% -> off")
pi_car_instance.set_motor(0)
wait(0.5)
@@ -42,4 +42,4 @@ def execute_test(pi_car_instance: PiCar):
print(pi_car_instance.adc.read_adc(7))
print("testing ultrasonic, ensure distance is reasonable")
- print(pi_car_instance.read_distance())
+ print(pi_car_instance.read_distance())
\ No newline at end of file
diff --git a/requirements.txt b/requirements.txt
index 6e31770..6d129db 100644
--- a/requirements.txt
+++ b/requirements.txt
@@ -1,3 +1,4 @@
Adafruit_PCA9685
Adafruit_MCP3008
-Adafruit_GPIO
\ No newline at end of file
+Adafruit_GPIO
+redis
\ No newline at end of file