diff --git a/.coveragerc b/.coveragerc new file mode 100644 index 0000000..398ff08 --- /dev/null +++ b/.coveragerc @@ -0,0 +1,2 @@ +[run] +branch = True diff --git a/.gitignore b/.gitignore index 944dcb3..932ff9b 100644 --- a/.gitignore +++ b/.gitignore @@ -5,6 +5,7 @@ $~ .idea/ .directory +.cache/ # temporary data temp diff --git a/.gitmodules b/.gitmodules new file mode 100644 index 0000000..8c16a8a --- /dev/null +++ b/.gitmodules @@ -0,0 +1,3 @@ +[submodule "capabilities-data"] + path = capabilities-data + url = https://github.com/receipt-print-hq/escpos-printer-db.git diff --git a/.travis.yml b/.travis.yml index cce6180..3966d74 100644 --- a/.travis.yml +++ b/.travis.yml @@ -15,22 +15,28 @@ matrix: env: TOXENV=py34 - python: 3.5 env: TOXENV=py35 - - python: 3.5-dev - env: TOXENV=py35 - - python: nightly + - python: 3.6 env: TOXENV=py36 + - python: 3.6-dev + env: TOXENV=py36 + - python: nightly + env: TOXENV=py37 - python: pypy env: TOXENV=pypy - python: pypy3 env: TOXENV=pypy3 - python: 2.7 env: TOXENV=docs + - python: 2.7 + env: TOXENV=flake8 + - python: 3.5 + env: TOXENV=flake8 allow_failures: - - python: 3.5-dev + - python: 3.6-dev - python: nightly - python: pypy3 before_install: - - pip install tox codecov + - pip install tox codecov 'sphinx>=1.5.1' script: - tox - codecov diff --git a/CHANGELOG.rst b/CHANGELOG.rst index 0ff3ed2..d5a23a3 100644 --- a/CHANGELOG.rst +++ b/CHANGELOG.rst @@ -1,6 +1,37 @@ ********* Changelog ********* + +2017-01-31 - Version 3.0a - "Grey Area" +--------------------------------------- +This release is the first alpha release of the new version 3.0. Please +be aware that the API will still change until v3.0 is released. + +changes +^^^^^^^ +- change the project's license to MIT in accordance with the contributors (see python-escpos/python-escpos#171) +- feature: add "capabilities" which are shared with escpos-php, capabilities are stored in + `escpos-printer-db `_ +- feature: the driver tries now to guess the appropriate codepage and sets it automatically (called "magic encode") +- as an alternative you can force the codepage with the old API +- updated and improved documentation +- changed constructor of main class due to introduction of capablities +- changed interface of method `blocktext`, changed behavior of multiple methods, for details refer to the documentation + on `python-escpos.readthedocs.io `_ +- add support for custom cash drawer sequence +- enforce flake8 on the src-files, test py36 and py37 on travis + +contributors +^^^^^^^^^^^^ +- Michael Billington +- Michael Elsdörfer +- Patrick Kanzler (with code by Frédéric Van der Essen) +- Asuki Kono +- Benito López +- Curtis // mashedkeyboard +- Thijs Triemstra +- ysuolmai + 2016-08-26 - Version 2.2.0 - "Fate Amenable To Change" ------------------------------------------------------ diff --git a/CONTRIBUTING.rst b/CONTRIBUTING.rst index e68360f..9d5de8b 100644 --- a/CONTRIBUTING.rst +++ b/CONTRIBUTING.rst @@ -29,7 +29,7 @@ of every file of code: from __future__ import division from __future__ import print_function from __future__ import unicode_literals - + Furthermore please be aware of the differences between Python 2 and 3. For example `this guide `_ is helpful. Special care has to be taken when dealing with strings and byte-strings. Please note @@ -45,8 +45,7 @@ The checks by Landscape and QuantifiedCode that run on every PR will provide you GIT ^^^ The master-branch contains code that has been released to PyPi. A release is marked with a tag -corresponding to the version. Issues are closed when they have been resolved in a released version -of the package. +corresponding to the version. Issues are closed when they have been resolved in the development-branch. When you have a change to make, begin by creating a new branch from the HEAD of `python-escpos/development`. Name your branch to indicate what you are trying to achieve. Good branch names might diff --git a/COPYING b/COPYING deleted file mode 100644 index 94a9ed0..0000000 --- a/COPYING +++ /dev/null @@ -1,674 +0,0 @@ - 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/LICENSE b/LICENSE new file mode 100644 index 0000000..3b78da5 --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2012-2017 python-escpos and Manuel F Martinez + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/MANIFEST.in b/MANIFEST.in index 997ee7b..3b066a0 100644 --- a/MANIFEST.in +++ b/MANIFEST.in @@ -1,8 +1,10 @@ include *.rst include *.txt include COPYING +include LICENSE include INSTALL include tox.ini +include capabilities-data/dist/capabilities.json recursive-include doc *.bat recursive-include doc *.ico recursive-include doc *.py diff --git a/README.rst b/README.rst index e79b279..1a10540 100644 --- a/README.rst +++ b/README.rst @@ -37,6 +37,11 @@ Text can be aligned/justified and fonts can be changed by size, type and weight. Also, this module handles some hardware functionalities like cutting paper, control characters, printer reset and similar functions. +Since supported commands differ from printer to printer the software tries to automatically apply the right +settings for the printer that you set. These settings are handled by +`escpos-printer-db `_ which is also used in +`escpos-php `_. + Dependencies ------------ @@ -56,11 +61,11 @@ The basic usage is: from escpos.printer import Usb - """ Seiko Epson Corp. Receipt Printer M129 Definitions (EPSON TM-T88IV) """ - p = Usb(0x04b8,0x0202,0) + """ Seiko Epson Corp. Receipt Printer (EPSON TM-T88III) """ + p = Usb(0x04b8, 0x0202, 0, profile="TM-T88III") p.text("Hello World\n") p.image("logo.gif") - p.barcode('1324354657687','EAN13',64,2,'','') + p.barcode('1324354657687', 'EAN13', 64, 2, '', '') p.cut() The full project-documentation is available on `Read the Docs `_. diff --git a/capabilities-data b/capabilities-data new file mode 160000 index 0000000..31d2269 --- /dev/null +++ b/capabilities-data @@ -0,0 +1 @@ +Subproject commit 31d2269651d4d10ca51f59799ee4d05b4c4a1625 diff --git a/doc/api/capabilities.rst b/doc/api/capabilities.rst new file mode 100644 index 0000000..f88b0e1 --- /dev/null +++ b/doc/api/capabilities.rst @@ -0,0 +1,10 @@ +Capabilities +------------ +Module :py:mod:`escpos.capabilities` + +.. automodule:: escpos.capabilities + :members: + :inherited-members: + :undoc-members: + :show-inheritance: + :member-order: bysource \ No newline at end of file diff --git a/doc/api/cli.rst b/doc/api/cli.rst new file mode 100644 index 0000000..dabbc10 --- /dev/null +++ b/doc/api/cli.rst @@ -0,0 +1,10 @@ +CLI +--- +Module :py:mod:`escpos.cli` + +.. automodule:: escpos.cli + :members: + :inherited-members: + :undoc-members: + :show-inheritance: + :member-order: bysource \ No newline at end of file diff --git a/doc/api/codepages.rst b/doc/api/codepages.rst new file mode 100644 index 0000000..c4e9183 --- /dev/null +++ b/doc/api/codepages.rst @@ -0,0 +1,10 @@ +Codepages +--------- +Module :py:mod:`escpos.codepages` + +.. automodule:: escpos.codepages + :members: + :inherited-members: + :undoc-members: + :show-inheritance: + :member-order: bysource \ No newline at end of file diff --git a/doc/api/katakana.rst b/doc/api/katakana.rst new file mode 100644 index 0000000..899b080 --- /dev/null +++ b/doc/api/katakana.rst @@ -0,0 +1,10 @@ +Katakana +-------- +Module :py:mod:`escpos.katakana` + +.. automodule:: escpos.katakana + :members: + :inherited-members: + :undoc-members: + :show-inheritance: + :member-order: bysource \ No newline at end of file diff --git a/doc/api/magicencode.rst b/doc/api/magicencode.rst new file mode 100644 index 0000000..715c218 --- /dev/null +++ b/doc/api/magicencode.rst @@ -0,0 +1,10 @@ +Magic Encode +------------ +Module :py:mod:`escpos.magicencode` + +.. automodule:: escpos.magicencode + :members: + :inherited-members: + :undoc-members: + :show-inheritance: + :member-order: bysource \ No newline at end of file diff --git a/doc/index.rst b/doc/index.rst index 060fc7f..4b5eea7 100644 --- a/doc/index.rst +++ b/doc/index.rst @@ -35,8 +35,13 @@ Content api/printer api/constants api/exceptions + api/capabilities api/config api/image + api/cli + api/magicencode + api/codepages + api/katakana Indices and tables ================== diff --git a/doc/requirements.txt b/doc/requirements.txt index acd8cd8..682316c 100644 --- a/doc/requirements.txt +++ b/doc/requirements.txt @@ -4,3 +4,4 @@ qrcode>=4.0 pyserial sphinx-rtd-theme setuptools-scm +docutils>=0.12 diff --git a/doc/user/methods.rst b/doc/user/methods.rst index 12a076c..5a150ad 100644 --- a/doc/user/methods.rst +++ b/doc/user/methods.rst @@ -1,144 +1,17 @@ ******* Methods ******* - -.. note:: **TODO** Merge this page with the API-description. (Make the API-description more pretty and then - replace this with the API-description.) +:Last Reviewed: 2017-01-25 Escpos class ------------ -Escpos inherits its methods to the printers. the following methods are -defined: +The core part of this libraries API is the Escpos class. +You use it by instantiating a :doc:`printer ` which is a child of Escpos. +The following methods are available: -image("image\_name.ext") -^^^^^^^^^^^^^^^^^^^^^^^^ +.. autoclass:: escpos.escpos.Escpos + :members: + :member-order: bysource + :noindex: -Prints an image. Its adjust the size in order to print it. - -* ``image_name.ext`` is the complete file name and location of any image type (jpg, gif, png, bmp) - -Raises ``ImageSizeError`` exception. - -qr("text") -^^^^^^^^^^ - -Prints a QR code. The size has been adjusted to Version 4, so it can be -enough small to be printed but also enough big to be read by a smart -phone. - -* ``text`` Any text that needs to be QR encoded. It could be a slogan, - salutation, url, etc. - -barcode("code", "barcode\_type", width, height, "position", "font") -^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - -Prints a barcode. - -* ``code`` is an alphanumeric code to be printed as bar code -* ``barcode_type`` must be one of the following type of codes for function type A: - - * UPC-A - * UPC-E - * EAN13 - * EAN8 - * CODE39 - * ITF - * NW7 - - And for function type B: - - * Any type above - * CODE93 - * CODE128 - * GS1-128 - * GS1 DataBar Omnidirectional - * GS1 DataBar Truncated - * GS1 DataBar Limited - * GS1 DataBar Expanded - - -* ``width`` is a numeric value in the range between (1,255) *Default:* 64 -* ``height`` is a numeric value in the range between (2,6) *Default:* 3 -* ``position`` is where to place the code around the bars, could be one of the following values: - - * ABOVE - * BELOW - * BOTH - * OFF > *Default:* BELOW - -* ``font`` is one of the 2 type of fonts, values could be: - - * A - * B > *Default:* A - -* ``fuction_type`` chooses between ESCPOS function type A or B. A is default, B has more barcode options. Choose which one based upon your printer support and require barcode. - - * A - * B > *Default* A - -* Raises ``BarcodeTypeError``, ``BarcodeSizeError``, ``BarcodeCodeError`` exceptions. - -text("text") -^^^^^^^^^^^^ - -Prints raw text. Raises ``TextError`` exception. - -set("align", "font", "type", width, height, invert, smooth, flip) -^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - -Set text properties. - -* ``align`` set horizontal position for text, the possible values are: - - * CENTER - * LEFT - * RIGHT > > *Default:* left - -* ``font`` type could be ``A`` or ``B``. *Default:* A -* ``type`` type could be ``B`` (Bold), ``U`` (Underline) or ``normal``. *Default:* normal -* ``width`` is a numeric value, 1 is for regular size, and 2 is twice the standard size. *Default*: 1 -* ``height`` is a numeric value, 1 is for regular size and 2 is twice the standard size. *Default*: 1 -* ``invert`` is a boolean value, True enables white on black printing. *Default*: False -* ``smooth`` is a boolean value, True enables text smoothing. *Default*: False -* ``flip`` is a boolean value, True enables upside-down text. *Default*: False - -cut("mode") -^^^^^^^^^^^ - -Cut paper. - -* ``mode`` set a full or partial cut. *Default:* full - -**Partial cut is not implemented in all printers.** - -cashdraw(pin) -^^^^^^^^^^^^^ - -Sends a pulse to the cash drawer in the specified pin. - -* ``pin`` is a numeric value which defines the pin to be used to send the pulse, it could be 2 or 5. Raises ``CashDrawerError()`` - -hw("operation") -^^^^^^^^^^^^^^^ - -Hardware operations. - -* ``operation`` is any of the following options: - - * INIT - * SELECT - * RESET - -control("align") -^^^^^^^^^^^^^^^^ - -Carrier feed and tabs. - -* ``align`` is a string which takes any of the following values: - - * LF *for Line Feed* - * FF *for Form Feed* - * CR *for Carriage Return* - * HT *for Horizontal Tab* - * VT *for Vertical Tab* diff --git a/doc/user/printers.rst b/doc/user/printers.rst index 073aef3..1e3484b 100644 --- a/doc/user/printers.rst +++ b/doc/user/printers.rst @@ -1,56 +1,77 @@ ******** Printers ******** +:Last Reviewed: 2017-01-25 -.. note:: **TODO** Merge this page into the API-description. +As of now there are 5 different type of printer implementations. -There 3 different type of printers: +USB +--- +The USB-class uses pyusb and libusb to communicate with USB-based +printers. Note that this driver is not suited for USB-to-Serial-adapters +and similiar devices, but only for those implementing native USB. -USB(idVendor, idProduct, interface, in\_ep, out\_ep) -^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +.. autoclass:: escpos.printer.Usb + :members: + :special-members: + :member-order: bysource + :noindex: -Based on pyusb and libusb-1.0 +Serial +------ +This driver uses pyserial in order to communicate with serial devices. +If you are using an USB-based adapter to connect to the serial port, +then you should also use this driver. +The configuration is often based on DIP-switches that you can set on your +printer. For the hardware-configuration please refer to your printer's manual. -* ``idVendor`` is the Vendor ID -* ``idProduct`` is the Product ID -* ``interface`` is the USB device interface (default = 0) -* ``in_ep`` is the input end point (default = 0x82) -* ``out_ep`` is the output end point (default = 0x01) +.. autoclass:: escpos.printer.Serial + :members: + :special-members: + :member-order: bysource + :noindex: -Serial("devfile", baudrate, bytesize, timeout) -^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +Network +------- -Based on pyserial, default values are based on the defaults set by -DIP\_SWITCH\_1 on the documentation(hardware side). +This driver is based on the socket class. -* ``devfile`` is an alphanumeric device file name under /dev filesystem (default = /ev/ttyS0) -* ``baudrate`` is the Baud rate for serial transmission (default = 9600) -* ``bytesize`` sets the serial buffer size (default = 8) -* ``timeout`` defines Read/Write timeout (default = 1) +.. autoclass:: escpos.printer.Network + :members: + :special-members: + :member-order: bysource + :noindex: -Network("host", port) -^^^^^^^^^^^^^^^^^^^^^ - -Based on socket - -* ``host`` is an alphanumeric host name, could be either DNS host name or IP address. -* ``port`` to write to (default = 9100) - -Troubleshooting: +Troubleshooting +^^^^^^^^^^^^^^^ Problems with a network-attached printer can have numerous causes. Make sure that your device has a proper IP address. Often you can check the IP address by triggering the self-test of the device. As a next step try to send text manually to the device. You could use for example: -.. :: + :: - echo "OK\n" | nc IPADDRESS 9100 - # the port number is often 9100 + echo "OK\n" | nc IPADDRESS 9100 + # the port number is often 9100 As a last resort try to reset the interface of the printer. This should be described in its manual. -File("file\_name") -^^^^^^^^^^^^^^^^^^ +File +---- +This printer "prints" just into a file-handle. Especially on \*nix-systems this comes very handy. -Printcap printers +.. autoclass:: escpos.printer.File + :members: + :special-members: + :member-order: bysource + :noindex: + +Dummy +----- +The Dummy-printer is mainly for testing- and debugging-purposes. It stores +all of the "output" as raw ESC/POS in a string and returns that. + +.. autoclass:: escpos.printer.Dummy + :members: + :member-order: bysource + :noindex: -* ``file_name`` is the full path to the device file name diff --git a/doc/user/raspi.rst b/doc/user/raspi.rst index 387c648..bb05f5e 100644 --- a/doc/user/raspi.rst +++ b/doc/user/raspi.rst @@ -2,10 +2,9 @@ Raspberry Pi ************ -This instructions were tested on Raspbian. +:Last Reviewed: 2017-01-05 -Unless you have done any distro with libusb-1.0 on the Raspberry Pi, the -following instructions should works fine on your raspberry distro. +This instructions were tested on Raspbian Jessie. .. warning:: You should **never** directly connect an printer with RS232-interface (serial port) directly to a Raspberry PI or similar interface (e.g. those simple USB-sticks without encasing). Those interfaces are @@ -14,60 +13,30 @@ following instructions should works fine on your raspberry distro. Dependencies ------------ - First, install the packages available on Raspbian. :: - # apt-get install python-imaging python-serial python-setuptools - -PyUSB -^^^^^ - -PyUSB 1.0 is not available on Ubuntu, so you have to download and -install it manually - -1. Download the latest tarball from - `Sourceforge `__ -2. Decompress the zip file -3. Install the library - - :: - - # wget ... - # unzip pyusb*.zip - # cd pyusb* - # python setup.py build - # sudo python setup.py install - -python-qrcode -^^^^^^^^^^^^^ - -1. Checkout the code from github -2. Install the library - - :: - - # git clone https://github.com/lincolnloop/python-qrcode - # cd python-qrcode - # python setup.py build - # sudo python setup.py install + sudo apt-get install python3 python3-setuptools python3-pip libjpeg8-dev Installation ------------ - -If you have installed pyusb for libusb-1.0 then you need to: - -1. Download the latest file -2. Decompress the file -3. Install the library +You can install by using pip3. :: - # git clone https://github.com/manpaz/python-escpos.git - # cd python-escpos - # python setup.py build - # sudo python setup.py install + sudo pip3 install --upgrade pip + sudo pip3 install python-escpos -Now you can attach your printer and and test it with the example code in -the project's `home `__ +Run +--- +You need sudo and python3 to run your program. + +:: + + sudo python3 your-program.py + +Now you can attach your printer and and test it with the example code in the project's set of examples. +You can find that in the `project-repository `__. + +For more details on this check the :doc:`installation-manual `. diff --git a/doc/user/usage.rst b/doc/user/usage.rst index 91629cd..4ef0439 100644 --- a/doc/user/usage.rst +++ b/doc/user/usage.rst @@ -8,12 +8,11 @@ Define your printer USB printer ^^^^^^^^^^^ -Before start creating your Python ESC/POS printer instance, you must see -at your system for the printer parameters. This is done with the 'lsusb' -command. +Before creating your Python ESC/POS printer instance, consult the system to obtain +the printer parameters. This is done with the 'lsusb' command. -First run the command to look for the "Vendor ID" and "Product ID", then -write down the values, these values are displayed just before the name +Run the command and look for the "Vendor ID" and "Product ID" and write +down the values. These values are displayed just before the name of the device with the following format: :: @@ -37,7 +36,7 @@ so you can get the "Interface" number and "End Point" # lsusb -vvv -d xxxx:xxxx | grep bEndpointAddress | grep OUT bEndpointAddress 0x01 EP 1 OUT -The first command will yields the "Interface" number that must be handy +The first command will yield the "Interface" number that must be handy to have and the second yields the "Output Endpoint" address. **USB Printer initialization** @@ -47,9 +46,9 @@ to have and the second yields the "Output Endpoint" address. Epson = printer.Usb(0x04b8,0x0202) By default the "Interface" number is "0" and the "Output Endpoint" -address is "0x01", if you have other values then you can define with +address is "0x01". If you have other values then you can define them on your instance. So, assuming that we have another printer where in\_ep is -on 0x81 and out\_ep=0x02, then the printer definition should looks like: +on 0x81 and out\_ep=0x02, then the printer definition should look like: **Generic USB Printer initialization** @@ -72,10 +71,10 @@ IP by DHCP or you set it manually. Serial printer ^^^^^^^^^^^^^^ -Must of the default values set by the DIP switches for the serial +Most of the default values set by the DIP switches for the serial printers, have been set as default on the serial printer class, so the -only thing you need to know is which serial port the printer is hooked -up. +only thing you need to know is which serial port the printer is connected +to. **Serial printer initialization** @@ -86,9 +85,9 @@ up. Other printers ^^^^^^^^^^^^^^ -Some printers under /dev can't be used or initialized with any of the +Some printers under `/dev` can't be used or initialized with any of the methods described above. Usually, those are printers used by printcap, -however, if you know the device name, you could try the initialize +however, if you know the device name, you could try to initialize by passing the device node name. :: @@ -101,8 +100,8 @@ node, then you don't necessary need to pass the node name. Define your instance -------------------- -The following example demonstrate how to initialize the Epson TM-TI88IV -on USB interface +The following example demonstrates how to initialize the Epson TM-TI88IV +on a USB interface. :: @@ -125,9 +124,9 @@ Configuration File You can create a configuration file for python-escpos. This will allow you to use the CLI, and skip some setup when using the library -programically. +programmatically. -The default configuration file is named ``config.yaml``. It's in the YAML +The default configuration file is named ``config.yaml`` and uses the YAML format. For windows it is probably at:: %appdata%/python-escpos/config.yaml @@ -143,11 +142,10 @@ If you aren't sure, run:: c.load() If it can't find the configuration file in the default location, it will tell -you where it's looking. You can always pass a path or a list of paths to -search to the ``load()`` method. +you where it's looking. You can always pass a path, or a list of paths, to +the ``load()`` method. - -To load the configured pritner, run:: +To load the configured printer, run:: from escpos import config c = config.Config() @@ -177,6 +175,20 @@ And for a network printer:: host: 127.0.0.1 port: 9000 +Printing text right +------------------- +Python-escpos is designed to accept unicode. So make sure that you use ``u'strings'`` or import ``unicode_literals`` +from ``__future__`` if you are on Python 2. On Python 3 you should be fine. + +For normal usage you can simply pass your text to the printers ``text()``-function. It will automatically guess +the right codepage and then send the encoded data to the printer. If this feature does not work, please try to +isolate the error and then create an issue on the Github project page. + +If you want or need to you can manually set the codepage. For this please use the ``charcode()``-function. You can set +any key-value that is in ``CHARCODE``. If something is wrong, an ``CharCodeError`` will be raised. +After you have manually set the codepage the printer won't change it anymore. You can revert to normal behaviour +by setting charcode to ``AUTO``. + Advanced Usage: Print from binary blob -------------------------------------- @@ -230,24 +242,8 @@ This is probably best explained by an example: # send code to printer p._raw(d.output) -This way you could also store the code in a file and print later. +This way you could also store the code in a file and print it later. You could then for example print the code from another process than your main-program and thus reduce the waiting time. (Of course this will not make the printer print faster.) -How to update your code for USB printers ----------------------------------------- - -Old code - -:: - - Epson = escpos.Escpos(0x04b8,0x0202,0) - -New code - -:: - - Epson = printer.Usb(0x04b8,0x0202) - -Nothe that "0" which is the interface number is no longer needed. diff --git a/examples/codepage_tables.py b/examples/codepage_tables.py new file mode 100644 index 0000000..7966036 --- /dev/null +++ b/examples/codepage_tables.py @@ -0,0 +1,63 @@ +"""Prints code page tables. +""" + +from __future__ import print_function + +import six +import sys + +from escpos import printer +from escpos.constants import CODEPAGE_CHANGE, ESC, CTL_LF, CTL_FF, CTL_CR, CTL_HT, CTL_VT + + +def main(): + dummy = printer.Dummy() + + dummy.hw('init') + + for codepage in sys.argv[1:] or ['USA']: + dummy.set(height=2, width=2) + dummy._raw(codepage + "\n\n\n") + print_codepage(dummy, codepage) + dummy._raw("\n\n") + + dummy.cut() + + print(dummy.output) + + +def print_codepage(printer, codepage): + if codepage.isdigit(): + codepage = int(codepage) + printer._raw(CODEPAGE_CHANGE + six.int2byte(codepage)) + printer._raw("after") + else: + printer.charcode(codepage) + + sep = "" + + # Table header + printer.set(text_type='B') + printer._raw(" {}\n".format(sep.join(map(lambda s: hex(s)[2:], range(0, 16))))) + printer.set() + + # The table + for x in range(0, 16): + # First column + printer.set(text_type='B') + printer._raw("{} ".format(hex(x)[2:])) + printer.set() + + for y in range(0, 16): + byte = six.int2byte(x * 16 + y) + + if byte in (ESC, CTL_LF, CTL_FF, CTL_CR, CTL_HT, CTL_VT): + byte = ' ' + + printer._raw(byte) + printer._raw(sep) + printer._raw('\n') + + +if __name__ == '__main__': + main() diff --git a/setup.cfg b/setup.cfg index 654c47d..ea43f22 100644 --- a/setup.cfg +++ b/setup.cfg @@ -5,3 +5,8 @@ with-doctest=1 [bdist_wheel] # This flag says that the code is written to work on both Python 2 and Python 3. universal=1 + +[flake8] +exclude = .git,.tox,.github,.eggs,__pycache__,doc/conf.py,build,dist,capabilities-data,test,src/escpos/constants.py +max-line-length = 120 +# future-imports = absolute_import, division, print_function, unicode_literals # we are not there yet diff --git a/setup.py b/setup.py index 02d479a..c5d77f6 100755 --- a/setup.py +++ b/setup.py @@ -50,10 +50,12 @@ setuptools_scm_template = """\ # coding: utf-8 # file generated by setuptools_scm # don't change, don't track in version control +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function from __future__ import unicode_literals version = '{version}' - """ @@ -67,12 +69,12 @@ setup( download_url='https://github.com/python-escpos/python-escpos/archive/master.zip', description='Python library to manipulate ESC/POS Printers', bugtrack_url='https://github.com/python-escpos/python-escpos/issues', - license='GNU GPL v3', + license='MIT', long_description=read('README.rst'), author='Manuel F Martinez and others', author_email='manpaz@bashlinux.com', maintainer='Patrick Kanzler', - maintainer_email='patrick.kanzler@fablab.fau.de', + maintainer_email='dev@pkanzler.de', keywords=[ 'ESC/POS', 'thermoprinter', @@ -83,12 +85,13 @@ setup( platforms='any', package_dir={"": "src"}, packages=find_packages(where="src", exclude=["tests", "tests.*"]), - package_data={'': ['COPYING']}, + package_data={'': ['COPYING', 'src/escpos/capabilities.json']}, + include_package_data=True, classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Console', 'Intended Audience :: Developers', - 'License :: OSI Approved :: GNU General Public License v3 (GPLv3)', + 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2', @@ -112,11 +115,23 @@ setup( 'pyyaml', 'argparse', 'argcomplete', + 'future' ], setup_requires=[ 'setuptools_scm', ], - tests_require=['tox', 'nose', 'scripttest', 'mock', 'hypothesis'], + tests_require=[ + 'jaconv', + 'tox', + 'pytest', + 'pytest-cov', + 'pytest-mock', + 'nose', + 'scripttest', + 'mock', + 'hypothesis', + 'flake8' + ], cmdclass={'test': Tox}, entry_points={ 'console_scripts': [ diff --git a/src/escpos/capabilities.json b/src/escpos/capabilities.json new file mode 120000 index 0000000..fd2b9f4 --- /dev/null +++ b/src/escpos/capabilities.json @@ -0,0 +1 @@ +../../capabilities-data/dist/capabilities.json \ No newline at end of file diff --git a/src/escpos/capabilities.py b/src/escpos/capabilities.py new file mode 100644 index 0000000..e4f1a18 --- /dev/null +++ b/src/escpos/capabilities.py @@ -0,0 +1,114 @@ +import re +import six +from os import path +import yaml + +# Load external printer database +with open(path.join(path.dirname(__file__), 'capabilities.json')) as f: + CAPABILITIES = yaml.load(f) + +PROFILES = CAPABILITIES['profiles'] + + +class NotSupported(Exception): + """Raised if a requested feature is not suppored by the + printer profile. + """ + pass + + +BARCODE_B = 'barcodeB' + + +class BaseProfile(object): + """This respresents a printer profile. + + A printer profile knows about the number of columns, supported + features, colors and more. + """ + + profile_data = {} + + def __getattr__(self, name): + return self.profile_data[name] + + def get_font(self, font): + """Return the escpos index for `font`. Makes sure that + the requested `font` is valid. + """ + font = {'a': 0, 'b': 1}.get(font, font) + if not six.text_type(font) in self.fonts: + raise NotSupported( + '"{}" is not a valid font in the current profile'.format(font)) + return font + + def get_columns(self, font): + """ Return the number of columns for the given font. + """ + font = self.get_font(font) + return self.fonts[six.text_type(font)]['columns'] + + def supports(self, feature): + """Return true/false for the given feature. + """ + return self.features.get(feature) + + def get_code_pages(self): + """Return the support code pages as a {name: index} dict. + """ + return {v: k for k, v in self.codePages.items()} + + +def get_profile(name=None, **kwargs): + """Get the profile by name; if no name is given, return the + default profile. + """ + if isinstance(name, Profile): + return name + + clazz = get_profile_class(name or 'default') + return clazz(**kwargs) + + +CLASS_CACHE = {} + + +def get_profile_class(name): + """For the given profile name, load the data from the external + database, then generate dynamically a class. + """ + if name not in CLASS_CACHE: + profile_data = PROFILES[name] + profile_name = clean(name) + class_name = '{}{}Profile'.format( + profile_name[0].upper(), profile_name[1:]) + new_class = type(class_name, (BaseProfile,), {'profile_data': profile_data}) + CLASS_CACHE[name] = new_class + + return CLASS_CACHE[name] + + +def clean(s): + # Remove invalid characters + s = re.sub('[^0-9a-zA-Z_]', '', s) + # Remove leading characters until we find a letter or underscore + s = re.sub('^[^a-zA-Z_]+', '', s) + return str(s) + + +class Profile(get_profile_class('default')): + """ + For users, who want to provide their profile + """ + + def __init__(self, columns=None, features=None): + super(Profile, self).__init__() + + self.columns = columns + self.features = features or {} + + def get_columns(self, font): + if self.columns is not None: + return self.columns + + return super(Profile, self).get_columns(font) diff --git a/src/escpos/cli.py b/src/escpos/cli.py index 3e3311d..dad2dfb 100644 --- a/src/escpos/cli.py +++ b/src/escpos/cli.py @@ -33,9 +33,11 @@ def str_to_bool(string): """ return string.lower() in ('y', 'yes', '1', 'true') + # A list of functions that work better with a newline to be sent after them. REQUIRES_NEWLINE = ('qr', 'barcode', 'text', 'block_text') + # Used in demo method # Key: The name of escpos function and the argument passed on the CLI. Some # manual translation is done in the case of barcodes_a -> barcode. @@ -244,13 +246,13 @@ ESCPOS_COMMANDS = [ 'option_strings': ('--high_density_horizontal',), 'help': 'Image density (horizontal)', 'type': str_to_bool, - }, + }, { 'option_strings': ('--high_density_vertical',), 'help': 'Image density (vertical)', 'type': str_to_bool, - }, - + }, + ], }, { @@ -568,5 +570,6 @@ def demo(printer, **kwargs): command(**params) printer.cut() + if __name__ == '__main__': main() diff --git a/src/escpos/codepages.py b/src/escpos/codepages.py new file mode 100644 index 0000000..ca63ef3 --- /dev/null +++ b/src/escpos/codepages.py @@ -0,0 +1,24 @@ +from .capabilities import CAPABILITIES + + +class CodePageManager: + """Holds information about all the code pages (as defined + in escpos-printer-db). + """ + + def __init__(self, data): + self.data = data + + def get_all(self): + return self.data.values() + + @staticmethod + def get_encoding_name(encoding): + # TODO resolve the encoding alias + return encoding.upper() + + def get_encoding(self, encoding): + return self.data[encoding] + + +CodePages = CodePageManager(CAPABILITIES['encodings']) diff --git a/src/escpos/constants.py b/src/escpos/constants.py index e4dd944..e3225f8 100644 --- a/src/escpos/constants.py +++ b/src/escpos/constants.py @@ -7,8 +7,8 @@ moved to `capabilities` as in `escpos-php by @mike42 `_ and others :organization: Bashlinux and `python-escpos `_ -:copyright: Copyright (c) 2012 Bashlinux -:license: GNU GPL v3 +:copyright: Copyright (c) 2012-2017 Bashlinux and python-escpos +:license: MIT """ from __future__ import absolute_import @@ -47,6 +47,7 @@ HW_RESET = ESC + b'\x3f\x0a\x00' # Reset printer hardware # Cash Drawer (ESC p ) _CASH_DRAWER = lambda m, t1='', t2='': ESC + b'p' + m + six.int2byte(t1) + six.int2byte(t2) +CD_KICK_DEC_SEQUENCE = lambda esc, p, m, t1=50, t2=50: six.int2byte(esc) + six.int2byte(p) + six.int2byte(m) + six.int2byte(t1) + six.int2byte(t2) CD_KICK_2 = _CASH_DRAWER(b'\x00', 50, 50) # Sends a pulse to pin 2 [] CD_KICK_5 = _CASH_DRAWER(b'\x01', 50, 50) # Sends a pulse to pin 5 [] @@ -100,14 +101,17 @@ TXT_UNDERL_ON = ESC + b'\x2d\x01' # Underline font 1-dot ON TXT_UNDERL2_ON = ESC + b'\x2d\x02' # Underline font 2-dot ON TXT_BOLD_OFF = ESC + b'\x45\x00' # Bold font OFF TXT_BOLD_ON = ESC + b'\x45\x01' # Bold font ON -TXT_FONT_A = ESC + b'\x4d\x00' # Font type A -TXT_FONT_B = ESC + b'\x4d\x01' # Font type B TXT_ALIGN_LT = ESC + b'\x61\x00' # Left justification TXT_ALIGN_CT = ESC + b'\x61\x01' # Centering TXT_ALIGN_RT = ESC + b'\x61\x02' # Right justification TXT_INVERT_ON = GS + b'\x42\x01' # Inverse Printing ON TXT_INVERT_OFF = GS + b'\x42\x00' # Inverse Printing OFF +# Fonts +SET_FONT = lambda n: ESC + b'\x4d' + n +TXT_FONT_A = SET_FONT(b'\x00') # Font type A +TXT_FONT_B = SET_FONT(b'\x01') # Font type B + # Text colors TXT_COLOR_BLACK = ESC + b'\x72\x00' # Default Color TXT_COLOR_RED = ESC + b'\x72\x01' # Alternative Color (Usually Red) @@ -120,27 +124,9 @@ LINESPACING_FUNCS = { 180: ESC + b'3', # line_spacing/180 of an inch, 0 <= line_spacing <= 255 } -# Char code table -CHARCODE_PC437 = ESC + b'\x74\x00' # USA: Standard Europe -CHARCODE_JIS = ESC + b'\x74\x01' # Japanese Katakana -CHARCODE_PC850 = ESC + b'\x74\x02' # Multilingual -CHARCODE_PC860 = ESC + b'\x74\x03' # Portuguese -CHARCODE_PC863 = ESC + b'\x74\x04' # Canadian-French -CHARCODE_PC865 = ESC + b'\x74\x05' # Nordic -CHARCODE_WEU = ESC + b'\x74\x06' # Simplified Kanji, Hirakana -CHARCODE_GREEK = ESC + b'\x74\x07' # Simplified Kanji -CHARCODE_HEBREW = ESC + b'\x74\x08' # Simplified Kanji -CHARCODE_PC1252 = ESC + b'\x74\x11' # Western European Windows Code Set -CHARCODE_PC866 = ESC + b'\x74\x12' # Cirillic #2 -CHARCODE_PC852 = ESC + b'\x74\x13' # Latin 2 -CHARCODE_PC858 = ESC + b'\x74\x14' # Euro -CHARCODE_THAI42 = ESC + b'\x74\x15' # Thai character code 42 -CHARCODE_THAI11 = ESC + b'\x74\x16' # Thai character code 11 -CHARCODE_THAI13 = ESC + b'\x74\x17' # Thai character code 13 -CHARCODE_THAI14 = ESC + b'\x74\x18' # Thai character code 14 -CHARCODE_THAI16 = ESC + b'\x74\x19' # Thai character code 16 -CHARCODE_THAI17 = ESC + b'\x74\x1a' # Thai character code 17 -CHARCODE_THAI18 = ESC + b'\x74\x1b' # Thai character code 18 +# Prefix to change the codepage. You need to attach a byte to indicate +# the codepage to use. We use escpos-printer-db as the data source. +CODEPAGE_CHANGE = ESC + b'\x74' # Barcode format _SET_BARCODE_TXT_POS = lambda n: GS + b'H' + n diff --git a/src/escpos/escpos.py b/src/escpos/escpos.py index c102e2c..3e07fc0 100644 --- a/src/escpos/escpos.py +++ b/src/escpos/escpos.py @@ -6,8 +6,8 @@ This module contains the abstract base class :py:class:`Escpos`. :author: `Manuel F Martinez `_ and others :organization: Bashlinux and `python-escpos `_ -:copyright: Copyright (c) 2012 Bashlinux -:license: GNU GPL v3 +:copyright: Copyright (c) 2012-2017 Bashlinux and python-escpos +:license: MIT """ from __future__ import absolute_import @@ -17,12 +17,29 @@ from __future__ import unicode_literals import qrcode import textwrap +import six -from .constants import * -from .exceptions import * +from .constants import ESC, GS, NUL, QR_ECLEVEL_L, QR_ECLEVEL_M, QR_ECLEVEL_H, QR_ECLEVEL_Q +from .constants import QR_MODEL_1, QR_MODEL_2, QR_MICRO, BARCODE_TYPES, BARCODE_HEIGHT, BARCODE_WIDTH +from .constants import TXT_ALIGN_CT, TXT_ALIGN_LT, TXT_ALIGN_RT, BARCODE_FONT_A, BARCODE_FONT_B +from .constants import BARCODE_TXT_OFF, BARCODE_TXT_BTH, BARCODE_TXT_ABV, BARCODE_TXT_BLW +from .constants import TXT_HEIGHT, TXT_WIDTH, TXT_SIZE, TXT_NORMAL, TXT_SMOOTH_OFF, TXT_SMOOTH_ON +from .constants import TXT_FLIP_OFF, TXT_FLIP_ON, TXT_2WIDTH, TXT_2HEIGHT, TXT_4SQUARE +from .constants import TXT_UNDERL_OFF, TXT_UNDERL_ON, TXT_BOLD_OFF, TXT_BOLD_ON, SET_FONT, TXT_UNDERL2_ON +from .constants import TXT_INVERT_OFF, TXT_INVERT_ON, LINESPACING_FUNCS, LINESPACING_RESET +from .constants import PD_0, PD_N12, PD_N25, PD_N37, PD_N50, PD_P50, PD_P37, PD_P25, PD_P12 +from .constants import CD_KICK_DEC_SEQUENCE, CD_KICK_5, CD_KICK_2, PAPER_FULL_CUT, PAPER_PART_CUT +from .constants import HW_RESET, HW_SELECT, HW_INIT +from .constants import CTL_VT, CTL_HT, CTL_CR, CTL_FF, CTL_LF, CTL_SET_HT, PANEL_BUTTON_OFF, PANEL_BUTTON_ON + +from .exceptions import BarcodeTypeError, BarcodeSizeError, TabPosError +from .exceptions import CashDrawerError, SetVariableError, BarcodeCodeError + +from .magicencode import MagicEncode from abc import ABCMeta, abstractmethod # abstract base class support from escpos.image import EscposImage +from escpos.capabilities import get_profile, BARCODE_B @six.add_metaclass(ABCMeta) @@ -33,13 +50,13 @@ class Escpos(object): class. """ device = None - codepage = None - def __init__(self, columns=32): + def __init__(self, profile=None, magic_encode_args=None, **kwargs): """ Initialize ESCPOS Printer - :param columns: Text columns used by the printer. Defaults to 32.""" - self.columns = columns + :param profile: Printer profile""" + self.profile = get_profile(profile) + self.magic = MagicEncode(self, **(magic_encode_args or {})) def __del__(self): """ call self.close upon deletion """ @@ -57,7 +74,7 @@ class Escpos(object): pass def image(self, img_source, high_density_vertical=True, high_density_horizontal=True, impl="bitImageRaster", - fragment_height=1024): + fragment_height=960): """ Print an image You can select whether the printer should print in high density or not. The default value is high density. @@ -77,9 +94,9 @@ class Escpos(object): :param high_density_vertical: print in high density in vertical direction *default:* True :param high_density_horizontal: print in high density in horizontal direction *default:* True :param impl: choose image printing mode between `bitImageRaster`, `graphics` or `bitImageColumn` - :param fragment_height: Images larger than this will be split into multiple fragments *default:* 1024 + :param fragment_height: Images larger than this will be split into multiple fragments *default:* 960 - """ + """ im = EscposImage(img_source) if im.height > fragment_height: @@ -91,13 +108,14 @@ class Escpos(object): impl=impl, fragment_height=fragment_height) return - + if impl == "bitImageRaster": # GS v 0, raster format bit image density_byte = (0 if high_density_horizontal else 1) + (0 if high_density_vertical else 2) - header = GS + b"v0" + six.int2byte(density_byte) + self._int_low_high(im.width_bytes, 2) + self._int_low_high(im.height, 2) + header = GS + b"v0" + six.int2byte(density_byte) + self._int_low_high(im.width_bytes, 2) +\ + self._int_low_high(im.height, 2) self._raw(header + im.to_raster_format()) - + if impl == "graphics": # GS ( L raster format graphics img_header = self._int_low_high(im.width, 2) + self._int_low_high(im.height, 2) @@ -109,7 +127,7 @@ class Escpos(object): raster_data = im.to_raster_format() self._image_send_graphics_data(b'0', b'p', header + raster_data) self._image_send_graphics_data(b'0', b'2', b'') - + if impl == "bitImageColumn": # ESC *, column format bit image density_byte = (1 if high_density_horizontal else 0) + (32 if high_density_vertical else 0) @@ -123,7 +141,7 @@ class Escpos(object): def _image_send_graphics_data(self, m, fn, data): """ Wrapper for GS ( L, to calculate and send correct data length. - + :param m: Modifier//variant for function. Usually '0' :param fn: Function number to use, as byte :param data: Data to send @@ -196,11 +214,11 @@ class Escpos(object): raise ValueError("cn and fn must be one byte each.") header = self._int_low_high(len(data) + len(m) + 2, 2) self._raw(GS + b'(k' + header + cn + fn + m + data) - + @staticmethod def _int_low_high(inp_number, out_bytes): """ Generate multiple bytes for a number: In lower and higher parts, or more parts as needed. - + :param inp_number: Input number :param out_bytes: The number of bytes to output (1 - 4). """ @@ -215,84 +233,23 @@ class Escpos(object): inp_number //= 256 return outp - def charcode(self, code): + def charcode(self, code="AUTO"): """ Set Character Code Table - Sends the control sequence from :py:mod:`escpos.constants` to the printer - with :py:meth:`escpos.printer.'implementation'._raw()`. + Sets the control sequence from ``CHARCODE`` in :py:mod:`escpos.constants` as active. It will be sent with + the next text sequence. If you set the variable code to ``AUTO`` it will try to automatically guess the + right codepage. (This is the standard behaviour.) :param code: Name of CharCode :raises: :py:exc:`~escpos.exceptions.CharCodeError` """ - # TODO improve this (rather unhandy code) - # TODO check the codepages - if code.upper() == "USA": - self._raw(CHARCODE_PC437) - self.codepage = 'cp437' - elif code.upper() == "JIS": - self._raw(CHARCODE_JIS) - self.codepage = 'cp932' - elif code.upper() == "MULTILINGUAL": - self._raw(CHARCODE_PC850) - self.codepage = 'cp850' - elif code.upper() == "PORTUGUESE": - self._raw(CHARCODE_PC860) - self.codepage = 'cp860' - elif code.upper() == "CA_FRENCH": - self._raw(CHARCODE_PC863) - self.codepage = 'cp863' - elif code.upper() == "NORDIC": - self._raw(CHARCODE_PC865) - self.codepage = 'cp865' - elif code.upper() == "WEST_EUROPE": - self._raw(CHARCODE_WEU) - self.codepage = 'latin_1' - elif code.upper() == "GREEK": - self._raw(CHARCODE_GREEK) - self.codepage = 'cp737' - elif code.upper() == "HEBREW": - self._raw(CHARCODE_HEBREW) - self.codepage = 'cp862' - # elif code.upper() == "LATVIAN": # this is not listed in the constants - # self._raw(CHARCODE_PC755) - # self.codepage = 'cp' - elif code.upper() == "WPC1252": - self._raw(CHARCODE_PC1252) - self.codepage = 'cp1252' - elif code.upper() == "CIRILLIC2": - self._raw(CHARCODE_PC866) - self.codepage = 'cp866' - elif code.upper() == "LATIN2": - self._raw(CHARCODE_PC852) - self.codepage = 'cp852' - elif code.upper() == "EURO": - self._raw(CHARCODE_PC858) - self.codepage = 'cp858' - elif code.upper() == "THAI42": - self._raw(CHARCODE_THAI42) - self.codepage = 'cp874' - elif code.upper() == "THAI11": - self._raw(CHARCODE_THAI11) - self.codepage = 'cp874' - elif code.upper() == "THAI13": - self._raw(CHARCODE_THAI13) - self.codepage = 'cp874' - elif code.upper() == "THAI14": - self._raw(CHARCODE_THAI14) - self.codepage = 'cp874' - elif code.upper() == "THAI16": - self._raw(CHARCODE_THAI16) - self.codepage = 'cp874' - elif code.upper() == "THAI17": - self._raw(CHARCODE_THAI17) - self.codepage = 'cp874' - elif code.upper() == "THAI18": - self._raw(CHARCODE_THAI18) - self.codepage = 'cp874' + if code.upper() == "AUTO": + self.magic.force_encoding(False) else: - raise CharCodeError() + self.magic.force_encoding(code) - def barcode(self, code, bc, height=64, width=3, pos="BELOW", font="A", align_ct=True, function_type="A"): + def barcode(self, code, bc, height=64, width=3, pos="BELOW", font="A", + align_ct=True, function_type=None): """ Print Barcode This method allows to print barcodes. The rendering of the barcode is done by the printer and therefore has to @@ -317,7 +274,7 @@ class Escpos(object): .. todo:: If further barcode-types are needed they could be rendered transparently as an image. (This could also be of help if the printer does not support types that others do.) - + :param code: alphanumeric data to be printed as bar code :param bc: barcode format, possible values are for type A are: @@ -363,14 +320,40 @@ class Escpos(object): issued. :type align_ct: bool - :param function_type: Choose between ESCPOS function type A or B, depending on printer support and desired - barcode. + :param function_type: Choose between ESCPOS function type A or B, + depending on printer support and desired barcode. If not given, + the printer will attempt to automatically choose the correct + function based on the current profile. *default*: A :raises: :py:exc:`~escpos.exceptions.BarcodeSizeError`, :py:exc:`~escpos.exceptions.BarcodeTypeError`, :py:exc:`~escpos.exceptions.BarcodeCodeError` """ + if function_type is None: + # Choose the function type automatically. + if bc in BARCODE_TYPES['A']: + function_type = 'A' + else: + if bc in BARCODE_TYPES['B']: + if not self.profile.supports(BARCODE_B): + raise BarcodeTypeError(( + "Barcode type '{bc} not supported for " + "the current printer profile").format(bc=bc)) + function_type = 'B' + else: + raise BarcodeTypeError(( + "Barcode type '{bc} is not valid").format(bc=bc)) + + bc_types = BARCODE_TYPES[function_type.upper()] + if bc.upper() not in bc_types.keys(): + raise BarcodeTypeError(( + "Barcode type '{bc}' not valid for barcode function type " + "{function_type}").format( + bc=bc, + function_type=function_type, + )) + # Align Bar Code() if align_ct: self._raw(TXT_ALIGN_CT) @@ -399,14 +382,6 @@ class Escpos(object): else: # DEFAULT POSITION: BELOW self._raw(BARCODE_TXT_BLW) - bc_types = BARCODE_TYPES[function_type.upper()] - if bc.upper() not in bc_types.keys(): - # TODO: Raise a better error, or fix the message of this error type - raise BarcodeTypeError("Barcode type {bc} not valid for barcode function type {function_type}".format( - bc=bc, - function_type=function_type, - )) - self._raw(bc_types[bc.upper()]) if function_type.upper() == "B": @@ -430,29 +405,24 @@ class Escpos(object): :param txt: text to be printed :raises: :py:exc:`~escpos.exceptions.TextError` """ - if txt: - if self.codepage: - self._raw(txt.encode(self.codepage)) - else: - self._raw(txt.encode()) - else: - # TODO: why is it problematic to print an empty string? - raise TextError() + txt = six.text_type(txt) + self.magic.write(txt) - def block_text(self, txt, columns=None): + def block_text(self, txt, font=None, columns=None): """ Text is printed wrapped to specified columns Text has to be encoded in unicode. :param txt: text to be printed + :param font: font to be used, can be :code:`a` or :code`b` :param columns: amount of columns :return: None """ - col_count = self.columns if columns is None else columns + col_count = self.profile.get_columns(font) if columns is None else columns self.text(textwrap.fill(txt, col_count)) - def set(self, align='left', font='a', text_type='normal', width=1, height=1, density=9, invert=False, smooth=False, - flip=False): + def set(self, align='left', font='a', text_type='normal', width=1, + height=1, density=9, invert=False, smooth=False, flip=False): """ Set text properties by sending them to the printer :param align: horizontal position for text, possible values are: @@ -462,7 +432,9 @@ class Escpos(object): * RIGHT *default*: LEFT - :param font: font type, possible values are A or B, *default*: A + + :param font: font given as an index, a name, or one of the + special values 'a' or 'b', refering to fonts 0 and 1. :param text_type: text type, possible values are: * B for bold @@ -527,10 +499,8 @@ class Escpos(object): self._raw(TXT_BOLD_OFF) self._raw(TXT_UNDERL_OFF) # Font - if font.upper() == "B": - self._raw(TXT_FONT_B) - else: # DEFAULT FONT: A - self._raw(TXT_FONT_A) + self._raw(SET_FONT(six.int2byte(self.profile.get_font(font)))) + # Align if align.upper() == "CENTER": self._raw(TXT_ALIGN_CT) @@ -586,7 +556,7 @@ class Escpos(object): if divisor not in LINESPACING_FUNCS: raise ValueError("divisor must be either 360, 180 or 60") - if (divisor in [360, 180] \ + if (divisor in [360, 180] and (not(0 <= spacing <= 255))): raise ValueError("spacing must be a int between 0 and 255 when divisor is 360 or 180") if divisor == 60 and (not(0 <= spacing <= 85)): @@ -600,7 +570,7 @@ class Escpos(object): Without any arguments the paper will be cut completely. With 'mode=PART' a partial cut will be attempted. Note however, that not all models can do a partial cut. See the documentation of your printer for details. - + .. todo:: Check this function on TM-T88II. :param mode: set to 'PART' for a partial cut @@ -616,9 +586,10 @@ class Escpos(object): def cashdraw(self, pin): """ Send pulse to kick the cash drawer - Kick cash drawer on pin 2 or pin 5 according to parameter. + Kick cash drawer on pin 2 or pin 5 according to default parameter. + For non default parameter send a decimal sequence i.e. [27,112,48] or [27,112,0,25,255] - :param pin: pin number, 2 or 5 + :param pin: pin number, 2 or 5 or list of decimals :raises: :py:exc:`~escpos.exceptions.CashDrawerError` """ if pin == 2: @@ -626,7 +597,10 @@ class Escpos(object): elif pin == 5: self._raw(CD_KICK_5) else: - raise CashDrawerError() + try: + self._raw(CD_KICK_DEC_SEQUENCE(*pin)) + except: + raise CashDrawerError() def hw(self, hw): """ Hardware operations diff --git a/src/escpos/exceptions.py b/src/escpos/exceptions.py index d0e2bd6..8c574ff 100644 --- a/src/escpos/exceptions.py +++ b/src/escpos/exceptions.py @@ -20,8 +20,8 @@ Result/Exit codes: :author: `Manuel F Martinez `_ and others :organization: Bashlinux and `python-escpos `_ -:copyright: Copyright (c) 2012 Bashlinux -:license: GNU GPL v3 +:copyright: Copyright (c) 2012-2017 Bashlinux and python-escpos +:license: MIT """ from __future__ import absolute_import @@ -87,7 +87,7 @@ class BarcodeCodeError(Error): self.resultcode = 30 def __str__(self): - return "No Barcode code was supplied" + return "No Barcode code was supplied ({msg})".format(msg=self.msg) class ImageSizeError(Error): @@ -101,7 +101,7 @@ class ImageSizeError(Error): self.resultcode = 40 def __str__(self): - return "Image height is longer than 255px and can't be printed" + return "Image height is longer than 255px and can't be printed ({msg})".format(msg=self.msg) class TextError(Error): @@ -116,7 +116,7 @@ class TextError(Error): self.resultcode = 50 def __str__(self): - return "Text string must be supplied to the text() method" + return "Text string must be supplied to the text() method ({msg})".format(msg=self.msg) class CashDrawerError(Error): @@ -131,7 +131,7 @@ class CashDrawerError(Error): self.resultcode = 60 def __str__(self): - return "Valid pin must be set to send pulse" + return "Valid pin must be set to send pulse ({msg})".format(msg=self.msg) class TabPosError(Error): @@ -146,7 +146,7 @@ class TabPosError(Error): self.resultcode = 70 def __str__(self): - return "Valid tab positions must be in the range 0 to 16" + return "Valid tab positions must be in the range 0 to 16 ({msg})".format(msg=self.msg) class CharCodeError(Error): @@ -161,7 +161,7 @@ class CharCodeError(Error): self.resultcode = 80 def __str__(self): - return "Valid char code must be set" + return "Valid char code must be set ({msg})".format(msg=self.msg) class USBNotFoundError(Error): @@ -176,7 +176,7 @@ class USBNotFoundError(Error): self.resultcode = 90 def __str__(self): - return "USB device not found" + return "USB device not found ({msg})".format(msg=self.msg) class SetVariableError(Error): @@ -191,7 +191,7 @@ class SetVariableError(Error): self.resultcode = 100 def __str__(self): - return "Set variable out of range" + return "Set variable out of range ({msg})".format(msg=self.msg) # Configuration errors diff --git a/src/escpos/image.py b/src/escpos/image.py index abf2e22..a5b15ab 100644 --- a/src/escpos/image.py +++ b/src/escpos/image.py @@ -5,7 +5,7 @@ This module contains the image format handler :py:class:`EscposImage`. :author: `Michael Billington `_ :organization: `python-escpos `_ :copyright: Copyright (c) 2016 Michael Billington -:license: GNU GPL v3 +:license: MIT """ from __future__ import absolute_import @@ -28,7 +28,7 @@ class EscposImage(object): def __init__(self, img_source): """ Load in an image - + :param img_source: PIL.Image, or filename to load one from. """ if isinstance(img_source, Image.Image): @@ -45,12 +45,12 @@ class EscposImage(object): im = Image.new("RGB", img_original.size, (255, 255, 255)) im.paste(img_original, mask=img_original.split()[3]) # Convert down to greyscale - im = im.convert("L") + im = im.convert("L") # Invert: Only works on 'L' images im = ImageOps.invert(im) # Pure black and white self._im = im.convert("1") - + @property def width(self): """ diff --git a/src/escpos/katakana.py b/src/escpos/katakana.py new file mode 100644 index 0000000..927a59b --- /dev/null +++ b/src/escpos/katakana.py @@ -0,0 +1,107 @@ +# -*- coding: utf-8 -*- +"""Helpers to encode Japanese characters. + +I doubt that this currently works correctly. +""" + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function +from __future__ import unicode_literals + + +try: + import jaconv +except ImportError: + jaconv = None + + +def encode_katakana(text): + """I don't think this quite works yet.""" + encoded = [] + for char in text: + if jaconv: + # try to convert japanese text to half-katakanas + char = jaconv.z2h(jaconv.hira2kata(char)) + # TODO: "the conversion may result in multiple characters" + # If that really can happen (I am not really shure), than the string would have to be split and every single + # character has to passed through the following lines. + + if char in TXT_ENC_KATAKANA_MAP: + encoded.append(TXT_ENC_KATAKANA_MAP[char]) + else: + # TODO doesn't this discard all that is not in the map? Can we be sure that the input does contain only + # encodable characters? We could at least throw an exception if encoding is not possible. + pass + return b"".join(encoded) + + +TXT_ENC_KATAKANA_MAP = { + # Maps UTF-8 Katakana symbols to KATAKANA Page Codes + # TODO: has this really to be hardcoded? + + # Half-Width Katakanas + '。': b'\xa1', + '「': b'\xa2', + '」': b'\xa3', + '、': b'\xa4', + '・': b'\xa5', + 'ヲ': b'\xa6', + 'ァ': b'\xa7', + 'ィ': b'\xa8', + 'ゥ': b'\xa9', + 'ェ': b'\xaa', + 'ォ': b'\xab', + 'ャ': b'\xac', + 'ュ': b'\xad', + 'ョ': b'\xae', + 'ッ': b'\xaf', + 'ー': b'\xb0', + 'ア': b'\xb1', + 'イ': b'\xb2', + 'ウ': b'\xb3', + 'エ': b'\xb4', + 'オ': b'\xb5', + 'カ': b'\xb6', + 'キ': b'\xb7', + 'ク': b'\xb8', + 'ケ': b'\xb9', + 'コ': b'\xba', + 'サ': b'\xbb', + 'シ': b'\xbc', + 'ス': b'\xbd', + 'セ': b'\xbe', + 'ソ': b'\xbf', + 'タ': b'\xc0', + 'チ': b'\xc1', + 'ツ': b'\xc2', + 'テ': b'\xc3', + 'ト': b'\xc4', + 'ナ': b'\xc5', + 'ニ': b'\xc6', + 'ヌ': b'\xc7', + 'ネ': b'\xc8', + 'ノ': b'\xc9', + 'ハ': b'\xca', + 'ヒ': b'\xcb', + 'フ': b'\xcc', + 'ヘ': b'\xcd', + 'ホ': b'\xce', + 'マ': b'\xcf', + 'ミ': b'\xd0', + 'ム': b'\xd1', + 'メ': b'\xd2', + 'モ': b'\xd3', + 'ヤ': b'\xd4', + 'ユ': b'\xd5', + 'ヨ': b'\xd6', + 'ラ': b'\xd7', + 'リ': b'\xd8', + 'ル': b'\xd9', + 'レ': b'\xda', + 'ロ': b'\xdb', + 'ワ': b'\xdc', + 'ン': b'\xdd', + '゙': b'\xde', + '゚': b'\xdf', +} diff --git a/src/escpos/magicencode.py b/src/escpos/magicencode.py new file mode 100644 index 0000000..c87b20c --- /dev/null +++ b/src/escpos/magicencode.py @@ -0,0 +1,296 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- +""" Magic Encode + +This module tries to convert an UTF-8 string to an encoded string for the printer. +It uses trial and error in order to guess the right codepage. +The code is based on the encoding-code in py-xml-escpos by @fvdsn. + +:author: `Patrick Kanzler `_ +:organization: `python-escpos `_ +:copyright: Copyright (c) 2016 Patrick Kanzler and Frédéric van der Essen +:license: MIT +""" + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function +from __future__ import unicode_literals + +from builtins import bytes +from .constants import CODEPAGE_CHANGE +from .exceptions import Error +from .codepages import CodePages +import six + + +class Encoder(object): + """Takes a list of available code spaces. Picks the right one for a + given character. + + Note: To determine the code page, it needs to do the conversion, and + thus already knows what the final byte in the target encoding would + be. Nevertheless, the API of this class doesn't return the byte. + + The caller use to do the character conversion itself. + + $ python -m timeit -s "{u'ö':'a'}.get(u'ö')" + 100000000 loops, best of 3: 0.0133 usec per loop + + $ python -m timeit -s "u'ö'.encode('latin1')" + 100000000 loops, best of 3: 0.0141 usec per loop + """ + + def __init__(self, codepage_map): + self.codepages = codepage_map + self.available_encodings = set(codepage_map.keys()) + self.available_characters = {} + self.used_encodings = set() + + def get_sequence(self, encoding): + return int(self.codepages[encoding]) + + def get_encoding_name(self, encoding): + """Given an encoding provided by the user, will return a + canonical encoding name; and also validate that the encoding + is supported. + + TODO: Support encoding aliases: pc437 instead of cp437. + """ + encoding = CodePages.get_encoding_name(encoding) + if encoding not in self.codepages: + raise ValueError(( + 'Encoding "{}" cannot be used for the current profile. ' + 'Valid encodings are: {}' + ).format(encoding, ','.join(self.codepages.keys()))) + return encoding + + @staticmethod + def _get_codepage_char_list(encoding): + """Get codepage character list + + Gets characters 128-255 for a given code page, as an array. + + :param encoding: The name of the encoding. This must appear in the CodePage list + """ + codepage = CodePages.get_encoding(encoding) + if 'data' in codepage: + encodable_chars = list("".join(codepage['data'])) + assert(len(encodable_chars) == 128) + return encodable_chars + elif 'python_encode' in codepage: + encodable_chars = [u" "] * 128 + for i in range(0, 128): + codepoint = i + 128 + try: + encodable_chars[i] = bytes([codepoint]).decode(codepage['python_encode']) + except UnicodeDecodeError: + # Non-encodable character, just skip it + pass + return encodable_chars + raise LookupError("Can't find a known encoding for {}".format(encoding)) + + def _get_codepage_char_map(self, encoding): + """ Get codepage character map + + Process an encoding and return a map of UTF-characters to code points + in this encoding. + + This is generated once only, and returned from a cache. + + :param encoding: The name of the encoding. + """ + # Skip things that were loaded previously + if encoding in self.available_characters: + return self.available_characters[encoding] + codepage_char_list = self._get_codepage_char_list(encoding) + codepage_char_map = dict((utf8, i + 128) for (i, utf8) in enumerate(codepage_char_list)) + self.available_characters[encoding] = codepage_char_map + return codepage_char_map + + def can_encode(self, encoding, char): + """Determine if a character is encodeable in the given code page. + + :param encoding: The name of the encoding. + :param char: The character to attempt to encode. + """ + available_map = {} + try: + available_map = self._get_codepage_char_map(encoding) + except LookupError: + return False + + # Decide whether this character is encodeable in this code page + is_ascii = ord(char) < 128 + is_encodable = char in available_map + return is_ascii or is_encodable + + @staticmethod + def _encode_char(char, charmap, defaultchar): + """ Encode a single character with the given encoding map + + :param char: char to encode + :param charmap: dictionary for mapping characters in this code page + """ + if ord(char) < 128: + return ord(char) + if char in charmap: + return charmap[char] + return ord(defaultchar) + + def encode(self, text, encoding, defaultchar='?'): + """ Encode text under the given encoding + + :param text: Text to encode + :param encoding: Encoding name to use (must be defined in capabilities) + :param defaultchar: Fallback for non-encodable characters + """ + codepage_char_map = self._get_codepage_char_map(encoding) + output_bytes = bytes([self._encode_char(char, codepage_char_map, defaultchar) for char in text]) + return output_bytes + + def __encoding_sort_func(self, item): + key, index = item + return ( + key in self.used_encodings, + index + ) + + def find_suitable_encoding(self, char): + """The order of our search is a specific one: + + 1. code pages that we already tried before; there is a good + chance they might work again, reducing the search space, + and by re-using already used encodings we might also + reduce the number of codepage change instructiosn we have + to send. Still, any performance gains will presumably be + fairly minor. + + 2. code pages in lower ESCPOS slots first. Presumably, they + are more likely to be supported, so if a printer profile + is missing or incomplete, we might increase our change + that the code page we pick for this character is actually + supported. + """ + sorted_encodings = sorted( + self.codepages.items(), + key=self.__encoding_sort_func) + + for encoding, _ in sorted_encodings: + if self.can_encode(encoding, char): + # This encoding worked; at it to the set of used ones. + self.used_encodings.add(encoding) + return encoding + + +def split_writable_text(encoder, text, encoding): + """Splits off as many characters from the begnning of text as + are writable with "encoding". Returns a 2-tuple (writable, rest). + """ + if not encoding: + return None, text + + for idx, char in enumerate(text): + if encoder.can_encode(encoding, char): + continue + return text[:idx], text[idx:] + + return text, None + + +class MagicEncode(object): + """A helper that helps us to automatically switch to the right + code page to encode any given Unicode character. + + This will consider the printers supported codepages, according + to the printer profile, and if a character cannot be encoded + with the current profile, it will attempt to find a suitable one. + + If the printer does not support a suitable code page, it can + insert an error character. + """ + def __init__(self, driver, encoding=None, disabled=False, + defaultsymbol='?', encoder=None): + """ + + :param driver: + :param encoding: If you know the current encoding of the printer + when initializing this class, set it here. If the current + encoding is unknown, the first character emitted will be a + codepage switch. + :param disabled: + :param defaultsymbol: + :param encoder: + """ + if disabled and not encoding: + raise Error('If you disable magic encode, you need to define an encoding!') + + self.driver = driver + self.encoder = encoder or Encoder(driver.profile.get_code_pages()) + + self.encoding = self.encoder.get_encoding_name(encoding) if encoding else None + self.defaultsymbol = defaultsymbol + self.disabled = disabled + + def force_encoding(self, encoding): + """Sets a fixed encoding. The change is emitted right away. + + From now one, this buffer will switch the code page anymore. + However, it will still keep track of the current code page. + """ + if not encoding: + self.disabled = False + else: + self.write_with_encoding(encoding, None) + self.disabled = True + + def write(self, text): + """Write the text, automatically switching encodings. + """ + + if self.disabled: + self.write_with_encoding(self.encoding, text) + return + + # See how far we can go into the text with the current encoding + to_write, text = split_writable_text(self.encoder, text, self.encoding) + if to_write: + self.write_with_encoding(self.encoding, to_write) + + while text: + # See if any of the code pages that the printer profile + # supports can encode this character. + encoding = self.encoder.find_suitable_encoding(text[0]) + if not encoding: + self._handle_character_failed(text[0]) + text = text[1:] + continue + + # Write as much text as possible with the encoding found. + to_write, text = split_writable_text(self.encoder, text, encoding) + if to_write: + self.write_with_encoding(encoding, to_write) + + def _handle_character_failed(self, char): + """Called when no codepage was found to render a character. + """ + # Writing the default symbol via write() allows us to avoid + # unnecesary codepage switches. + self.write(self.defaultsymbol) + + def write_with_encoding(self, encoding, text): + if text is not None and type(text) is not six.text_type: + raise Error("The supplied text has to be unicode, but is of type {type}.".format( + type=type(text) + )) + + # We always know the current code page; if the new codepage + # is different, emit a change command. + if encoding != self.encoding: + self.encoding = encoding + self.driver._raw( + CODEPAGE_CHANGE + + six.int2byte(self.encoder.get_sequence(encoding))) + + if text: + self.driver._raw(self.encoder.encode(text, encoding)) diff --git a/src/escpos/printer.py b/src/escpos/printer.py index ec936b5..d14b93d 100644 --- a/src/escpos/printer.py +++ b/src/escpos/printer.py @@ -4,8 +4,8 @@ :author: `Manuel F Martinez `_ and others :organization: Bashlinux and `python-escpos `_ -:copyright: Copyright (c) 2012 Bashlinux -:license: GNU GPL v3 +:copyright: Copyright (c) 2012-2017 Bashlinux and python-escpos +:license: MIT """ from __future__ import absolute_import @@ -34,7 +34,7 @@ class Usb(Escpos): """ - def __init__(self, idVendor, idProduct, timeout=0, in_ep=0x82, out_ep=0x01, *args, **kwargs): + def __init__(self, idVendor, idProduct, timeout=0, in_ep=0x82, out_ep=0x01, *args, **kwargs): # noqa: N803 """ :param idVendor: Vendor ID :param idProduct: Product ID @@ -182,9 +182,9 @@ class Network(Escpos): def __init__(self, host, port=9100, timeout=60, *args, **kwargs): """ - :param host : Printer's hostname or IP address - :param port : Port to write to - :param timeout : timeout in seconds for the socket-library + :param host: Printer's hostname or IP address + :param port: Port to write to + :param timeout: timeout in seconds for the socket-library """ Escpos.__init__(self, *args, **kwargs) self.host = host @@ -211,8 +211,9 @@ class Network(Escpos): def close(self): """ Close TCP connection """ - self.device.shutdown(socket.SHUT_RDWR) - self.device.close() + if self.device is not None: + self.device.shutdown(socket.SHUT_RDWR) + self.device.close() class File(Escpos): @@ -263,8 +264,9 @@ class File(Escpos): def close(self): """ Close system file """ - self.device.flush() - self.device.close() + if self.device is not None: + self.device.flush() + self.device.close() class Dummy(Escpos): diff --git a/test/Dies ist ein Test.LF.txt b/test/Dies ist ein Test.LF.txt deleted file mode 100644 index d7e5cff..0000000 --- a/test/Dies ist ein Test.LF.txt +++ /dev/null @@ -1 +0,0 @@ -Dies ist ein Test. diff --git a/test/conftest.py b/test/conftest.py new file mode 100644 index 0000000..2dad088 --- /dev/null +++ b/test/conftest.py @@ -0,0 +1,7 @@ +import pytest +from escpos.printer import Dummy + + +@pytest.fixture +def driver(): + return Dummy() diff --git a/test/test_abstract_base_class.py b/test/test_abstract_base_class.py index f5ec61f..9450e1b 100644 --- a/test/test_abstract_base_class.py +++ b/test/test_abstract_base_class.py @@ -4,7 +4,7 @@ :author: `Patrick Kanzler `_ :organization: `python-escpos `_ :copyright: Copyright (c) 2016 Patrick Kanzler -:license: GNU GPL v3 +:license: MIT """ from __future__ import absolute_import diff --git a/test/test_cli.py b/test/test_cli.py index b9aebc3..6b45036 100644 --- a/test/test_cli.py +++ b/test/test_cli.py @@ -10,7 +10,7 @@ from __future__ import unicode_literals import os import sys from scripttest import TestFileEnvironment -from nose.tools import assert_equals +from nose.tools import assert_equals, nottest import escpos TEST_DIR = os.path.abspath('test/test-cli-output') @@ -30,31 +30,26 @@ printer: ) -class TestCLI(): +class TestCLI: """ Contains setups, teardowns, and tests for CLI """ - def __init__(self): - """ Initalize the tests. - Just define some vars here since most of them get set during - setup_class and teardown_class - """ - self.env = None - self.default_args = None - - @staticmethod - def setup_class(): + @classmethod + def setup_class(cls): """ Create a config file to read from """ with open(CONFIGFILE, 'w') as config: config.write(CONFIG_YAML) - @staticmethod - def teardown_class(): + @classmethod + def teardown_class(cls): """ Remove config file """ os.remove(CONFIGFILE) def setup(self): """ Create a file to print to and set up env""" + self.env = None + self.default_args = None + self.env = TestFileEnvironment( base_path=TEST_DIR, cwd=os.getcwd(), @@ -89,6 +84,7 @@ class TestCLI(): assert not result.stderr assert_equals(escpos.__version__, result.stdout.strip()) + @nottest # disable this test as it is not that easy anymore to predict the outcome of this call def test_cli_text(self): """ Make sure text returns what we sent it """ test_text = 'this is some text' diff --git a/test/test_function_barcode.py b/test/test_function_barcode.py new file mode 100644 index 0000000..710e5cd --- /dev/null +++ b/test/test_function_barcode.py @@ -0,0 +1,38 @@ +#!/usr/bin/python +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function +from __future__ import unicode_literals + +import escpos.printer as printer +from escpos.constants import BARCODE_TYPE_A, BARCODE_TYPE_B +from escpos.capabilities import Profile, BARCODE_B +from escpos.exceptions import BarcodeTypeError +import pytest + + +@pytest.mark.parametrize("bctype,data,expected", [ + ('EAN13', '4006381333931', + b'\x1ba\x01\x1dh@\x1dw\x03\x1df\x00\x1dH\x02\x1dk\x024006381333931\x00') +]) +def test_barcode(bctype, data, expected): + """should generate different barcode types correctly. + """ + instance = printer.Dummy() + instance.barcode(data, bctype) + assert instance.output == expected + + +@pytest.mark.parametrize("bctype,supports_b", [ + ('invalid', True), + ('CODE128', False), +]) +def test_lacks_support(bctype, supports_b): + """should raise an error if the barcode type is not supported. + """ + profile = Profile(features={BARCODE_B: supports_b}) + instance = printer.Dummy(profile=profile) + with pytest.raises(BarcodeTypeError): + instance.barcode('test', bctype) + + assert instance.output == b'' diff --git a/test/test_function_image.py b/test/test_function_image.py index b1762f6..27b4fd7 100644 --- a/test/test_function_image.py +++ b/test/test_function_image.py @@ -4,7 +4,7 @@ :author: `Michael Billington `_ :organization: `python-escpos `_ :copyright: Copyright (c) 2016 `Michael Billington `_ -:license: GNU GPL v3 +:license: MIT """ from __future__ import absolute_import diff --git a/test/test_function_panel_button.py b/test/test_function_panel_button.py index 403bc75..1006e5b 100644 --- a/test/test_function_panel_button.py +++ b/test/test_function_panel_button.py @@ -4,7 +4,7 @@ :author: `Patrick Kanzler `_ :organization: `python-escpos `_ :copyright: Copyright (c) 2016 `python-escpos `_ -:license: GNU GPL v3 +:license: MIT """ from __future__ import absolute_import diff --git a/test/test_function_qr_native.py b/test/test_function_qr_native.py index a3355ca..2fbaa64 100644 --- a/test/test_function_qr_native.py +++ b/test/test_function_qr_native.py @@ -4,7 +4,7 @@ :author: `Michael Billington `_ :organization: `python-escpos `_ :copyright: Copyright (c) 2016 `Michael Billington `_ -:license: GNU GPL v3 +:license: MIT """ from __future__ import absolute_import diff --git a/test/test_function_qr_non-native.py b/test/test_function_qr_non-native.py index 5c0566a..bba47fd 100644 --- a/test/test_function_qr_non-native.py +++ b/test/test_function_qr_non-native.py @@ -5,7 +5,7 @@ :author: `Patrick Kanzler `_ :organization: `python-escpos `_ :copyright: Copyright (c) 2016 `python-escpos `_ -:license: GNU GPL v3 +:license: MIT """ from __future__ import absolute_import diff --git a/test/test_function_text.py b/test/test_function_text.py index b0b1ca1..04222a1 100644 --- a/test/test_function_text.py +++ b/test/test_function_text.py @@ -4,7 +4,7 @@ :author: `Patrick Kanzler `_ :organization: `python-escpos `_ :copyright: Copyright (c) 2016 `python-escpos `_ -:license: GNU GPL v3 +:license: MIT """ from __future__ import absolute_import @@ -12,34 +12,30 @@ from __future__ import division from __future__ import print_function from __future__ import unicode_literals -from nose.tools import with_setup - -import escpos.printer as printer -import os - -import filecmp - -devfile = 'testfile' +import pytest +import mock +from hypothesis import given, assume +import hypothesis.strategies as st +from escpos.printer import Dummy -def setup_testfile(): - """create a testfile as devfile""" - fhandle = open(devfile, 'a') - try: - os.utime(devfile, None) - finally: - fhandle.close() +def get_printer(): + return Dummy(magic_encode_args={'disabled': True, 'encoding': 'CP437'}) -def teardown_testfile(): - """destroy testfile again""" - os.remove(devfile) +@given(text=st.text()) +def test_text(text): + """Test that text() calls the MagicEncode object. + """ + instance = get_printer() + instance.magic.write = mock.Mock() + instance.text(text) + instance.magic.write.assert_called_with(text) -@with_setup(setup_testfile, teardown_testfile) -def test_function_text_dies_ist_ein_test_lf(): - """test the text printing function with simple string and compare output""" - instance = printer.File(devfile=devfile) - instance.text('Dies ist ein Test.\n') - instance.flush() - assert(filecmp.cmp('test/Dies ist ein Test.LF.txt', devfile)) +def test_block_text(): + printer = get_printer() + printer.block_text( + "All the presidents men were eating falafel for breakfast.", font='a') + assert printer.output == \ + b'All the presidents men were eating falafel\nfor breakfast.' diff --git a/test/test_functions.py b/test/test_functions.py index 22ee737..96b923a 100644 --- a/test/test_functions.py +++ b/test/test_functions.py @@ -17,10 +17,10 @@ def test_line_spacing_rest(): def test_line_spacing_error_handling(): printer = Dummy() with assert_raises(ValueError): - printer.line_spacing(99, divisor=44) + printer.line_spacing(99, divisor=44) with assert_raises(ValueError): - printer.line_spacing(divisor=80, spacing=86) + printer.line_spacing(divisor=80, spacing=86) with assert_raises(ValueError): - printer.line_spacing(divisor=360, spacing=256) + printer.line_spacing(divisor=360, spacing=256) with assert_raises(ValueError): - printer.line_spacing(divisor=180, spacing=256) \ No newline at end of file + printer.line_spacing(divisor=180, spacing=256) diff --git a/test/test_image.py b/test/test_image.py index 6fda6dd..4a9e8b0 100644 --- a/test/test_image.py +++ b/test/test_image.py @@ -5,7 +5,7 @@ converted to ESC/POS column & raster formats. :author: `Michael Billington `_ :organization: `python-escpos `_ :copyright: Copyright (c) 2016 `Michael Billington `_ -:license: GNU GPL v3 +:license: MIT """ from escpos.image import EscposImage diff --git a/test/test_load_module.py b/test/test_load_module.py index daf94b4..aeffc5b 100644 --- a/test/test_load_module.py +++ b/test/test_load_module.py @@ -4,7 +4,7 @@ :author: `Patrick Kanzler `_ :organization: `python-escpos `_ :copyright: Copyright (c) 2016 `python-escpos `_ -:license: GNU GPL v3 +:license: MIT """ from __future__ import absolute_import diff --git a/test/test_magicencode.py b/test/test_magicencode.py new file mode 100644 index 0000000..bb2dcde --- /dev/null +++ b/test/test_magicencode.py @@ -0,0 +1,127 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- +"""tests for the magic encode module + +:author: `Patrick Kanzler `_ +:organization: `python-escpos `_ +:copyright: Copyright (c) 2016 `python-escpos `_ +:license: MIT +""" + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function +from __future__ import unicode_literals + +import pytest +from nose.tools import raises, assert_raises +from hypothesis import given, example +import hypothesis.strategies as st +from escpos.magicencode import MagicEncode, Encoder +from escpos.katakana import encode_katakana +from escpos.exceptions import CharCodeError, Error + + +class TestEncoder: + """ + Tests the single encoders. + """ + + def test_can_encode(self): + assert not Encoder({'CP437': 1}).can_encode('CP437', u'€') + assert Encoder({'CP437': 1}).can_encode('CP437', u'á') + assert not Encoder({'foobar': 1}).can_encode('foobar', 'a') + + def test_find_suitable_encoding(self): + assert not Encoder({'CP437': 1}).find_suitable_encoding(u'€') + assert Encoder({'CP858': 1}).find_suitable_encoding(u'€') == 'CP858' + + @raises(ValueError) + def test_get_encoding(self): + Encoder({}).get_encoding_name('latin1') + + +class TestMagicEncode: + """ + Tests the magic encode functionality. + """ + + class TestInit: + """ + Test initialization. + """ + + def test_disabled_requires_encoding(self, driver): + """ + Test that disabled without encoder raises an error. + + :param driver: + """ + with pytest.raises(Error): + MagicEncode(driver, disabled=True) + + class TestWriteWithEncoding: + + def test_init_from_none(self, driver): + encode = MagicEncode(driver, encoding=None) + encode.write_with_encoding('CP858', '€ ist teuro.') + assert driver.output == b'\x1bt\x13\xd5 ist teuro.' + + def test_change_from_another(self, driver): + encode = MagicEncode(driver, encoding='CP437') + encode.write_with_encoding('CP858', '€ ist teuro.') + assert driver.output == b'\x1bt\x13\xd5 ist teuro.' + + def test_no_change(self, driver): + encode = MagicEncode(driver, encoding='CP858') + encode.write_with_encoding('CP858', '€ ist teuro.') + assert driver.output == b'\xd5 ist teuro.' + + class TestWrite: + + def test_write(self, driver): + encode = MagicEncode(driver) + encode.write('€ ist teuro.') + assert driver.output == b'\x1bt\x0f\xa4 ist teuro.' + + def test_write_disabled(self, driver): + encode = MagicEncode(driver, encoding='CP437', disabled=True) + encode.write('€ ist teuro.') + assert driver.output == b'? ist teuro.' + + def test_write_no_codepage(self, driver): + encode = MagicEncode( + driver, defaultsymbol="_", encoder=Encoder({'CP437': 1}), + encoding='CP437') + encode.write(u'€ ist teuro.') + assert driver.output == b'_ ist teuro.' + + class TestForceEncoding: + + def test(self, driver): + encode = MagicEncode(driver) + encode.force_encoding('CP437') + assert driver.output == b'\x1bt\x00' + + encode.write('€ ist teuro.') + assert driver.output == b'\x1bt\x00? ist teuro.' + + +try: + import jaconv +except ImportError: + jaconv = None + + +@pytest.mark.skipif(not jaconv, reason="jaconv not installed") +class TestKatakana: + @given(st.text()) + @example("カタカナ") + @example("あいうえお") + @example("ハンカクカタカナ") + def test_accept(self, text): + encode_katakana(text) + + def test_result(self): + assert encode_katakana('カタカナ') == b'\xb6\xc0\xb6\xc5' + assert encode_katakana("あいうえお") == b'\xb1\xb2\xb3\xb4\xb5' diff --git a/test/test_printer_file.py b/test/test_printer_file.py index bce9a0e..48b7606 100644 --- a/test/test_printer_file.py +++ b/test/test_printer_file.py @@ -5,7 +5,7 @@ :author: `Patrick Kanzler `_ :organization: `python-escpos `_ :copyright: Copyright (c) 2016 `python-escpos `_ -:license: GNU GPL v3 +:license: MIT """ from __future__ import absolute_import @@ -15,7 +15,7 @@ from __future__ import unicode_literals import six -import mock +import pytest from hypothesis import given from hypothesis.strategies import text @@ -26,22 +26,24 @@ if six.PY3: else: mock_open_call = '__builtin__.open' + @given(path=text()) -@mock.patch(mock_open_call) -@mock.patch('escpos.escpos.Escpos.__init__') -def test_load_file_printer(mock_escpos, mock_open, path): +def test_load_file_printer(mocker, path): """test the loading of the file-printer""" + mock_escpos = mocker.patch('escpos.escpos.Escpos.__init__') + mock_open = mocker.patch(mock_open_call) printer.File(devfile=path) assert mock_escpos.called mock_open.assert_called_with(path, "wb") @given(txt=text()) -@mock.patch.object(printer.File, 'device') -@mock.patch(mock_open_call) -@mock.patch('escpos.escpos.Escpos.__init__') -def test_auto_flush(mock_escpos, mock_open, mock_device, txt): +def test_auto_flush(mocker, txt): """test auto_flush in file-printer""" + mock_escpos = mocker.patch('escpos.escpos.Escpos.__init__') + mock_open = mocker.patch(mock_open_call) + mock_device = mocker.patch.object(printer.File, 'device') + p = printer.File(auto_flush=False) # inject the mocked device-object p.device = mock_device @@ -56,10 +58,11 @@ def test_auto_flush(mock_escpos, mock_open, mock_device, txt): @given(txt=text()) -@mock.patch.object(printer.File, 'device') -@mock.patch(mock_open_call) -def test_flush_on_close(mock_open, mock_device, txt): +def test_flush_on_close(mocker, txt): """test flush on close in file-printer""" + mock_open = mocker.patch(mock_open_call) + mock_device = mocker.patch.object(printer.File, 'device') + p = printer.File(auto_flush=False) # inject the mocked device-object p.device = mock_device diff --git a/test/test_profile.py b/test/test_profile.py new file mode 100644 index 0000000..5f4fa4b --- /dev/null +++ b/test/test_profile.py @@ -0,0 +1,38 @@ +import pytest +from escpos.capabilities import get_profile, NotSupported, BARCODE_B, Profile + + +@pytest.fixture +def profile(): + return get_profile('default') + + +class TestBaseProfile: + """Test the `BaseProfile` class. + """ + + def test_get_font(self, profile): + with pytest.raises(NotSupported): + assert profile.get_font('3') + assert profile.get_font(1) == 1 + assert profile.get_font('a') == 0 + + def test_supports(self, profile): + assert not profile.supports('asdf asdf') + assert profile.supports(BARCODE_B) + + def test_get_columns(self, profile): + assert profile.get_columns('a') > 5 + with pytest.raises(NotSupported): + assert profile.get_columns('asdfasdf') + + +class TestCustomProfile: + """Test custom profile options with the `Profile` class. + """ + + def test_columns(self): + assert Profile(columns=10).get_columns('sdfasdf') == 10 + + def test_features(self): + assert Profile(features={'foo': True}).supports('foo') diff --git a/test/test_with_statement.py b/test/test_with_statement.py index 71efc24..4abb283 100644 --- a/test/test_with_statement.py +++ b/test/test_with_statement.py @@ -4,7 +4,7 @@ :author: `Patrick Kanzler `_ :organization: `python-escpos `_ :copyright: Copyright (c) 2016 `python-escpos `_ -:license: GNU GPL v3 +:license: MIT """ from __future__ import absolute_import diff --git a/tox.ini b/tox.ini index 0968270..d51853c 100644 --- a/tox.ini +++ b/tox.ini @@ -1,17 +1,28 @@ [tox] -envlist = py27, py34, py35, docs +envlist = py27, py34, py35, docs, flake8 [testenv] deps = nose + jaconv coverage scripttest mock + pytest + pytest-cov + pytest-mock hypothesis -commands = nosetests --with-coverage --cover-erase --cover-branches +commands = py.test --cov escpos [testenv:docs] basepython = python changedir = doc -deps = sphinx +deps = sphinx>=1.5.1 setuptools_scm commands = sphinx-build -W -b html -d {envtmpdir}/doctrees . {envtmpdir}/html + +[testenv:flake8] +basepython = python +# TODO add flake8-future +# TODO add flake8-docstrings +deps = flake8 +commands = flake8