pax_global_header00006660000000000000000000000064134165024620014515gustar00rootroot0000000000000052 comment=1cfc7e7302bb3c6ac5632cc478d4c028d7c67a92 pklaus-brother_ql-3380c8c/000077500000000000000000000000001341650246200155105ustar00rootroot00000000000000pklaus-brother_ql-3380c8c/.gitignore000066400000000000000000000012761341650246200175060ustar00rootroot00000000000000# Byte-compiled / optimized / DLL files __pycache__/ *.py[cod] # C extensions *.so # Distribution / packaging .Python env/ build/ develop-eggs/ dist/ downloads/ eggs/ .eggs/ lib/ lib64/ parts/ sdist/ var/ *.egg-info/ .installed.cfg *.egg # PyInstaller # Usually these files are written by a python script from a template # before PyInstaller builds the exe, so as to inject date/other infos into it. *.manifest *.spec # Installer logs pip-log.txt pip-delete-this-directory.txt # Unit test / coverage reports htmlcov/ .tox/ .coverage .coverage.* .cache nosetests.xml coverage.xml *,cover # Translations *.mo *.pot # Django stuff: *.log # Sphinx documentation docs/_build/ # PyBuilder target/ pklaus-brother_ql-3380c8c/LEGACY.md000066400000000000000000000200451341650246200167770ustar00rootroot00000000000000## Legacy User Interfaces The following user interfaces of this package are still around but their use is now deprecated and they will be removed in a future release of the package. This documentation still lists the old UI and how it was used. ### Create The command line tool `brother_ql_create` is possibly the most important piece of software in this package. It allows you to create a new instruction file in the label printers' raster language: brother_ql_create --model QL-500 ./720x300_monochrome.png > 720x300_monochrome.bin If you want to find out about its options, just call the tool with `--help`: brother_ql_create --help giving: usage: brother_ql_create [-h] [--model MODEL] [--label-size LABEL_SIZE] [--rotate {0,90,180,270}] [--threshold THRESHOLD] [--dither] [--compress] [--red] [--600dpi] [--no-cut] [--loglevel LOGLEVEL] image [outfile] positional arguments: image The image file to create a label from. outfile The file to write the instructions to. Defaults to stdout. optional arguments: -h, --help show this help message and exit --model MODEL, -m MODEL The printer model to use. Check available ones with `brother_ql_info list-models`. --label-size LABEL_SIZE, -s LABEL_SIZE The label size (and kind) to use. Check available ones with `brother_ql_info list-label-sizes`. --rotate {0,90,180,270}, -r {0,90,180,270} Rotate the image (counterclock-wise) by this amount of degrees. --threshold THRESHOLD, -t THRESHOLD The threshold value (in percent) to discriminate between black and white pixels. --dither, -d Enable dithering when converting the image to b/w. If set, --threshold is meaningless. --compress, -c Enable compression (if available with the model). Takes more time but results in smaller file size. --red Create a label to be printed on black/red/white tape (only with QL-8xx series on DK-22251 labels). You must use this option when printing on black/red tape, even when not printing red. --600dpi Print with 600x300 dpi available on some models. Provide your image as 600x600 dpi; perpendicular to the feeding the image will be resized to 300dpi. --no-cut Don't cut the tape after printing the label. --loglevel LOGLEVEL Set to DEBUG for verbose debugging output to stderr. The image argument should be a PNG/GIF/JPEG image file. ### Print Once you have a Brother QL instruction file, you can send it to the printer like this: cat my_label.bin > /dev/usb/lp1 Be sure to have permission to write to the device (usually adding yourself to the *lp* group is sufficient. Or via network (if you have a LAN/WLAN enabled Brother QL): nc 192.168.0.23 9100 < my_label.bin You can also use the tool `brother_ql_print` (Py3 only) to send the instructions to your printer: brother_ql_print 720x151_monochrome.bin /dev/usb/lp0 # or brother_ql_print --backend network 720x151_monochrome.bin tcp://192.168.0.23:9100 # or (requires PyUSB: `pip install pyusb`) brother_ql_print 720x151_monochrome.bin usb://0x04f9:0x2015 # or if you have multiple ones connected: brother_ql_print 720x151_monochrome.bin usb://0x04f9:0x2015/000M6Z401370 # where 000M6Z401370 is the serial number (see lsusb output). If your printer has problems printing the instructions file, it may blink its LED (green or red) depending on the model. This can have many reasons, eg.: * The selected label doesn't match (make sure `--red` has been passed to `brother_ql_create` if you're using black/red labels). * End of paper. * Unsupported opcode (wrong `--model` when using `brother_ql_create`?) ### DEBUG In case of trouble printing an instruction file, there are some ways to help debugging. One way is to look into the binary raster instruction file, see the *Analyse* section. The other way is to send those instructions to the printer one by one and check how it reacts, see the *Debug* section. #### Analyse To analyse a binary file containing Brother QL Raster instructions: brother_ql_analyse 720x300_monochrome.bin --loglevel DEBUG The tool will dissect your file and print the opcodes to stdout. In addition, it creates PNG images of what the printer's output would look like. They are saved to page0001.png etc. (yes, one .bin file can contain more than one "page"). This tool also has the `--help` option. (This specific tool doesn't work on Python 2.) #### Debug If your printer has problems printing the instructions file, it may blink its LED (green or red) depending on the model. This can have many reasons, eg.: * The selected label doesn't match. * End of paper. * Unsupported opcode (some printers require a mode switching opcode, others fail if such an instruction is sent; some do support data compression, others don't) To debug this situation and find out which command could be the culprit, connect your printer via USB. (You don't get any status information via network). You can use the supplied tool `brother_ql_debug` to send your problematic instructions file to the printer. It will be split into single instructions sent one after the other. After every instruction, the printer will be given a chance to send a status response containing error information. Here is an example: philipp@lion ~> brother_ql_debug ./720x151_monochrome.bin /dev/usb/lp0 INFO: CMD preamble FOUND. Instruction: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 [...] 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 INFO: CMD init FOUND. Instruction: 1B 40 INFO: CMD status request FOUND. Instruction: 1B 69 53 INFO: Response from the device: 80 20 42 30 4F 30 00 00 00 00 3E 0A 00 00 15 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 INFO: Interpretation of the response: 'Reply to status request' (phase: Waiting to receive), 'Continuous length tape' 62x0 mm^2, errors: [] INFO: CMD media/quality FOUND. Instruction: 1B 69 7A CE 0A 3E 00 97 00 00 00 01 00 INFO: CMD margins FOUND. Instruction: 1B 69 64 23 00 INFO: CMD raster FOUND. Instruction: 67 00 5A 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 01 FF FF FF 1F FF FF FF FF FF F0 00 00 00 00 00 0F FF FF 03 FF FF FF FF E0 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 [...] 00 07 FF FF 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 INFO: Response from the device: 80 20 42 30 4F 30 00 00 00 00 3E 0A 00 00 15 00 00 00 06 01 00 00 00 00 00 00 00 00 00 00 00 00 INFO: Interpretation of the response: 'Phase change' (phase: Printing state), 'Continuous length tape' 62x0 mm^2, errors: [] INFO: CMD print FOUND. Instruction: 1A TIME 1.60 INFO: Interpretation of the response: 'Printing completed' (phase: Printing state), 'Continuous length tape' 62x0 mm^2, errors: [] TIME 1.60 INFO: Interpretation of the response: 'Phase change' (phase: Waiting to receive), 'Continuous length tape' 62x0 mm^2, errors: [] Here, a command file was successfully printed. The last response should state the *Waiting to receive* phase. If you want to confirm the sending of every single command individually, you can add the `--interactive` argument to the command line call. If you're seeing any error there, open a new issue on Github containing the debugging output to get your device supported. pklaus-brother_ql-3380c8c/LICENSE000066400000000000000000001045061341650246200165230ustar00rootroot00000000000000 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. {one line to give the program's name and a brief idea of what it does.} Copyright (C) {year} {name of author} 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: {project} Copyright (C) {year} {fullname} 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 . pklaus-brother_ql-3380c8c/README.md000066400000000000000000000277401341650246200170010ustar00rootroot00000000000000## brother\_ql A Python package to control Brother QL label printers. It implements the raster language of those printers and allows you to send instruction files to your printer. In more details, the following is possible with this package: * Create raster language files for the Brother label printers. They can be created from image files or programmatically in your own Python script. * Print raster instruction files with your Brother label printer via different backends: * pyusb (works cross-platform) * network (works cross-platform for WiFi/Ethernet-enabled printers) * linux\_kernel (works on Linux only; uses the /dev/usb/lp0 device handles) The following printers are claimed to be supported (✓ means verified by the author or by contributors): * QL-500 (✓), QL-550 (✓), QL-560 (✓), QL-570 (✓), QL-580N, QL-650TD, QL-700 (✓), QL-710W (✓), QL-720NW (✓), QL-800 (✓), QL-810W (✓), QL-820NWB (✓), QL-1050 (✓), and QL-1060N (✓). The new QL-800 series can print labels with two colors (black and red) on DK-22251 labels. Note: If your printer has an 'Editor Lite' mode, you need to disable it if you want to print via USB. Make sure that the corresponding LED is not lit by holding the button down until it turns off. If you're interested in printing labels using a web interface, check out [brother\_ql\_web][], which builds upon this package. ## Why The special feature of this package is that no printer driver is required for it to work. This software bypasses the whole printing system including printer drivers and directly talks to your label printer instead. This means that even though Brother doesn't offer a driver for the Raspberry Pi (running Linux on ARM) you can print nicely using this software. And even if there are drivers for your operating system, many programs have difficulties to set the page sizes and margins for the labels correctly. If you want to print with high precision (which is important for barcodes for example), you rather want to have control about every single pixel to be printed. This is where brother\_ql comes into the game. ## Installation brother\_ql is [available on the Python Package Index][PyPI] to be installed with pip: pip install --upgrade brother_ql The upgrade flag makes sure, you get the latest version of brother\_ql but also of its dependencies. Alternatively, you can install the latest version from Github using: pip install --upgrade https://github.com/pklaus/brother_ql/archive/master.zip This package was mainly created for use with Python 3. The essential functionality, however, will also work with Python 2: the creation of label files. In order to run the `brother_ql` command line utility, the directory it resides in needs to be in the PATH envirnoment variable. On some systems, the `pip install` command defaults to the `--user` flag resulting in the utility being put in the `~/.local/bin` directory. On those systems, extending the path variable via `export PATH="${PATH}:~/.local/bin"` is needed. ## Usage The main user interface of this package is the command line tool `brother_ql`. Usage: brother_ql [OPTIONS] COMMAND [ARGS]... Command line interface for the brother_ql Python package. Options: -b, --backend [pyusb|network|linux_kernel] -m, --model [QL-500|QL-550|QL-560|QL-570|QL-580N|QL-650TD|QL-700|QL-710W|QL-720NW|QL-800|QL-810W|QL-820NWB|QL-1050|QL-1060N] -p, --printer PRINTER_IDENTIFIER The identifier for the printer. This could be a string like tcp://192.168.1.21:9100 for a networked printer or usb://0x04f9:0x2015/000M6Z401370 for a printer connected via USB. --debug --version Show the version and exit. --help Show this message and exit. Commands: analyze interpret a binary file containing raster... discover find connected label printers info list available labels, models etc. print Print a label send send an instruction file to the printer There are some global options available such as --model and --printer. They can also be provided by environment variables (`BROTHER_QL_MODEL` and `BROTHER_QL_PRINTER`). The global options are followed by a command such as `info` or `print`. The most important command is the `print` command and here is its CLI signature: Usage: brother_ql print [OPTIONS] IMAGE [IMAGE] ... Print a label of the provided IMAGE. Options: -l, --label [12|29|38|50|54|62|102|17x54|17x87|23x23|29x42|29x90|39x90|39x48|52x29|62x29|62x100|102x51|102x152|d12|d24|d58] The label (size, type - die-cut or endless). Run `brother_ql info labels` for a full list including ideal pixel dimensions. -r, --rotate [auto|0|90|180|270] Rotate the image (counterclock-wise) by this amount of degrees. -t, --threshold FLOAT The threshold value (in percent) to discriminate between black and white pixels. -d, --dither Enable dithering when converting the image to b/w. If set, --threshold is meaningless. -c, --compress Enable compression (if available with the model). Label creation can take slightly longer but the resulting instruction size is normally considerably smaller. --red Create a label to be printed on black/red/white tape (only with QL-8xx series on DK-22251 labels). You must use this option when printing on black/red tape, even when not printing red. --600dpi Print with 600x300 dpi available on some models. Provide your image as 600x600 dpi; perpendicular to the feeding the image will be resized to 300dpi. --lq Print with low quality (faster). Default is high quality. --no-cut Don't cut the tape after printing the label. --help Show this message and exit. So, printing an image file onto 62mm endless tape on a QL-710W label printer can be as easy as: export BROTHER_QL_PRINTER=tcp://192.168.1.21 export BROTHER_QL_MODEL=QL-710W brother_ql print -l 62 my_image.png The available label names can be listed with `brother_ql info labels`: Name Printable px Description 12 106 12mm endless 29 306 29mm endless 38 413 38mm endless 50 554 50mm endless 54 590 54mm endless 62 696 62mm endless 102 1164 102mm endless 17x54 165 x 566 17mm x 54mm die-cut 17x87 165 x 956 17mm x 87mm die-cut 23x23 202 x 202 23mm x 23mm die-cut 29x42 306 x 425 29mm x 42mm die-cut 29x90 306 x 991 29mm x 90mm die-cut 39x90 413 x 991 38mm x 90mm die-cut 39x48 425 x 495 39mm x 48mm die-cut 52x29 578 x 271 52mm x 29mm die-cut 62x29 696 x 271 62mm x 29mm die-cut 62x100 696 x 1109 62mm x 100mm die-cut 102x51 1164 x 526 102mm x 51mm die-cut 102x152 1164 x 1660 102mm x 153mm die-cut d12 94 x 94 12mm round die-cut d24 236 x 236 24mm round die-cut d58 618 x 618 58mm round die-cut **Pro Tip™**: For the best results, use image files with the matching pixel dimensions. Die-cut labels have to be in the exact pixel dimensions stated above. For endless label rolls, you can provide image files with a pixel width as stated above. If you provide a file with different dimensions when creating an endless label file, it will be scaled to fit the width. ### Backends There are multiple backends for connecting to the printer available (✔: supported, ✘: not supported): Backend | Kind | Linux | Mac OS | Windows -------|-------|---------|---------|-------- network (1) | TCP | ✔ | ✔ | ✔ linux\_kernel | USB | ✔ (2) | ✘ | ✘ pyusb (3) | USB | ✔ (3.1) | ✔ (3.2) | ✔ (3.3) Notes: 1. The network backend doesn't support reading back the printer state, currently. Failure such as *wrong label type* or *end of label roll reached* won't be detected by this software. 2. The label printer should show up automatically as `/dev/usb/lp0` when connected. Please check the ownership (user, group) of this file to be able to print as a regular user. Consider setting up a udev .rules file. 3. PyUSB is a Python wrapper allowing to implement USB communication in userspace. 1. On Linux: install libusb1 as offered by your distribution: `sudo apt-get install libusb-1.0-0` (Ubuntu, Debian), `sudo zyppe in libusb-1_0-0` (OpenSUSE), `sudo pacman -S libusb` (Arch). 2. On Mac OS: Install [Homebrew](https://brew.sh/) and then install libusb1 using: `brew install libusb`. 3. On Windows: download [libusb-win32-devel-filter-1.2.6.0.exe](https://sourceforge.net/projects/libusb-win32/files/libusb-win32-releases/1.2.6.0/) from sourceforge and install it. After installing, you have to use the "Filter Wizard" to setup a "device filter" for the label printer. ### Legacy command line tools For a long time, this project provided multiple command line tools, such as `brother_ql_create`, `brother_ql_print`, `brother_ql_analyze`, and more. The overview of those tools can still be found in the [LEGACY][] documentation. The use of these tools is now considered deprecated and they will be removed in a future release. ## Author This software package was written by Philipp Klaus based on Brother's documentation of its raster language and based on additinal reverse engineering efforts. * Philipp Klaus Many more have contributed by raising issues, helping to solve them, improving the code and helping out financially. ## Contributing There are many ways to support the development of brother\_ql: * **File an issue** on Github, if you encounter problems, have a proposal, etc. * **Send an email with ideas** to the author. * **Submit a pull request** on Github if you improved the code and know how to use git. * **Finance a label printer** from the [author's wishlist][] to allow him to extend the device coverage and testing. * **Donate** an arbitrary amount of money for the development of brother\_ql [via Paypal][donation]. Thanks to everyone helping to improve brother\_ql. ## Links * The source code and issue tracker of this package is to be found on **Github**: [pklaus/brother\_ql][]. * The package is also to be found on the Python Package Index **PyPI**: [brother\_ql][PyPI]. * A curated list of related and unrelated software can be found [in this document][related-unrelated]. [author's wishlist]: https://www.amazon.de/registry/wishlist/3GSVLPF08AFIR [donation]: https://www.paypal.com/cgi-bin/webscr?cmd=_donations&business=philipp.klaus@gmail.com&lc=US&item_name=Donation+to+brother_ql+Development&no_note=0&cn=¤cy_code=USD&bn=PP-DonationsBF:btn_donateCC_LG.gif:NonHosted [brother\_ql\_web]: https://github.com/pklaus/brother_ql_web [LEGACY]: https://github.com/pklaus/brother_ql/blob/master/LEGACY.md [pklaus/brother\_ql]: https://github.com/pklaus/brother_ql [PyPI]: https://pypi.python.org/pypi/brother_ql [related-unrelated]: https://gist.github.com/pklaus/aeb55e18d36690df6a84a3eab49e9fd7 pklaus-brother_ql-3380c8c/brother_ql/000077500000000000000000000000001341650246200176515ustar00rootroot00000000000000pklaus-brother_ql-3380c8c/brother_ql/__init__.py000066400000000000000000000001561341650246200217640ustar00rootroot00000000000000 from .exceptions import * from .raster import BrotherQLRaster from .brother_ql_create import create_label pklaus-brother_ql-3380c8c/brother_ql/backends/000077500000000000000000000000001341650246200214235ustar00rootroot00000000000000pklaus-brother_ql-3380c8c/brother_ql/backends/__init__.py000066400000000000000000000030371341650246200235370ustar00rootroot00000000000000 from .generic import BrotherQLBackendGeneric available_backends = [ 'pyusb', 'network', 'linux_kernel', ] def guess_backend(identifier): """ guess the backend from a given identifier string for the device """ if identifier.startswith('usb://') or identifier.startswith('0x'): return 'pyusb' elif identifier.startswith('file://') or identifier.startswith('/dev/usb/') or identifier.startswith('lp'): return 'linux_kernel' elif identifier.startswith('tcp://'): return 'network' else: raise ValueError('Cannot guess backend for given identifier: %s' % identifier) def backend_factory(backend_name): if backend_name == 'pyusb': from . import pyusb as pyusb_backend list_available_devices = pyusb_backend.list_available_devices backend_class = pyusb_backend.BrotherQLBackendPyUSB elif backend_name == 'linux_kernel': from . import linux_kernel as linux_kernel_backend list_available_devices = linux_kernel_backend.list_available_devices backend_class = linux_kernel_backend.BrotherQLBackendLinuxKernel elif backend_name == 'network': from . import network as network_backend list_available_devices = network_backend.list_available_devices backend_class = network_backend.BrotherQLBackendNetwork else: raise NotImplementedError('Backend %s not implemented.' % backend_name) return {'list_available_devices': list_available_devices, 'backend_class': backend_class} pklaus-brother_ql-3380c8c/brother_ql/backends/generic.py000066400000000000000000000025751341650246200234220ustar00rootroot00000000000000 import logging logger = logging.getLogger(__name__) def list_available_devices(): """ List all available devices for the respective backend """ # returns a list of dictionaries with the keys 'identifier' and 'instance': # [ {'identifier': '/dev/usb/lp0', 'instance': os.open('/dev/usb/lp0', os.O_RDWR)}, ] raise NotImplementedError() class BrotherQLBackendGeneric(object): def __init__(self, device_specifier): """ device_specifier can be either a string or an instance of the required class type. """ self.write_dev = None self.read_dev = None raise NotImplementedError() def _write(self, data): self.write_dev.write(data) def _read(self, length=32): return bytes(self.read_dev.read(length)) def write(self, data): logger.debug('Writing %d bytes.', len(data)) self._write(data) def read(self, length=32): try: ret_bytes = self._read(length) if ret_bytes: logger.debug('Read %d bytes.', len(ret_bytes)) return ret_bytes except Exception as e: logger.debug('Error reading... %s', e) raise def dispose(self): try: self._dispose() except: pass def _dispose(self): raise NotImplementedError() def __del__(self): self.dispose() pklaus-brother_ql-3380c8c/brother_ql/backends/helpers.py000077500000000000000000000100221341650246200234350ustar00rootroot00000000000000#!/usr/bin/env python """ Helpers for the subpackage brother_ql.backends * device discovery * printing """ import logging, time from brother_ql.backends import backend_factory, guess_backend from brother_ql.reader import interpret_response logger = logging.getLogger(__name__) def discover(backend_identifier='linux_kernel'): be = backend_factory(backend_identifier) list_available_devices = be['list_available_devices'] BrotherQLBackend = be['backend_class'] available_devices = list_available_devices() return available_devices def send(instructions, printer_identifier=None, backend_identifier=None, blocking=True): """ Send instruction bytes to a printer. :param bytes instructions: The instructions to be sent to the printer. :param str printer_identifier: Identifier for the printer. :param str backend_identifier: Can enforce the use of a specific backend. :param bool blocking: Indicates whether the function call should block while waiting for the completion of the printing. """ status = { 'instructions_sent': True, # The instructions were sent to the printer. 'outcome': 'unknown', # String description of the outcome of the sending operation like: 'unknown', 'sent', 'printed', 'error' 'printer_state': None, # If the selected backend supports reading back the printer state, this key will contain it. 'did_print': False, # If True, a print was produced. It defaults to False if the outcome is uncertain (due to a backend without read-back capability). 'ready_for_next_job': False, # If True, the printer is ready to receive the next instructions. It defaults to False if the state is unknown. } selected_backend = None if backend_identifier: selected_backend = backend_identifier else: try: selected_backend = guess_backend(printer_identifier) except: logger.info("No backend stated. Selecting the default linux_kernel backend.") selected_backend = 'linux_kernel' be = backend_factory(selected_backend) list_available_devices = be['list_available_devices'] BrotherQLBackend = be['backend_class'] printer = BrotherQLBackend(printer_identifier) start = time.time() logger.info('Sending instructions to the printer. Total: %d bytes.', len(instructions)) printer.write(instructions) status['outcome'] = 'sent' if not blocking: return status if selected_backend == 'network': """ No need to wait for completion. The network backend doesn't support readback. """ return status while time.time() - start < 10: data = printer.read() if not data: time.sleep(0.005) continue try: result = interpret_response(data) except ValueError: logger.error("TIME %.3f - Couln't understand response: %s", time.time()-start, data) continue status['printer_state'] = result logger.debug('TIME %.3f - result: %s', time.time()-start, result) if result['errors']: logger.error('Errors occured: %s', result['errors']) status['outcome'] = 'error' break if result['status_type'] == 'Printing completed': status['did_print'] = True status['outcome'] = 'printed' if result['status_type'] == 'Phase change' and result['phase_type'] == 'Waiting to receive': status['ready_for_next_job'] = True if status['did_print'] and status['ready_for_next_job']: break if not status['did_print']: logger.warning("'printing completed' status not received.") if not status['ready_for_next_job']: logger.warning("'waiting to receive' status not received.") if (not status['did_print']) or (not status['ready_for_next_job']): logger.warning('Printing potentially not successful?') if status['did_print'] and status['ready_for_next_job']: logger.info("Printing was successful. Waiting for the next job.") return status pklaus-brother_ql-3380c8c/brother_ql/backends/linux_kernel.py000077500000000000000000000054271341650246200245070ustar00rootroot00000000000000#!/usr/bin/env python """ Backend to support Brother QL-series printers via the linux kernel USB printer interface. Works on Linux. """ from __future__ import unicode_literals from builtins import str import glob, os, time, select from .generic import BrotherQLBackendGeneric def list_available_devices(): """ List all available devices for the linux kernel backend returns: devices: a list of dictionaries with the keys 'identifier' and 'instance': \ [ {'identifier': 'file:///dev/usb/lp0', 'instance': None}, ] \ Instance is set to None because we don't want to open (and thus potentially block) the device here. """ paths = glob.glob('/dev/usb/lp*') return [{'identifier': 'file://' + path, 'instance': None} for path in paths] class BrotherQLBackendLinuxKernel(BrotherQLBackendGeneric): """ BrotherQL backend using the Linux Kernel USB Printer Device Handles """ def __init__(self, device_specifier): """ device_specifier: string or os.open(): identifier in the \ format file:///dev/usb/lp0 or os.open() raw device handle. """ self.read_timeout = 0.01 # strategy : try_twice or select self.strategy = 'select' if isinstance(device_specifier, str): if device_specifier.startswith('file://'): device_specifier = device_specifier[7:] self.dev = os.open(device_specifier, os.O_RDWR) elif isinstance(device_specifier, int): self.dev = device_specifier else: raise NotImplementedError('Currently the printer can be specified either via an appropriate string or via an os.open() handle.') self.write_dev = self.dev self.read_dev = self.dev def _write(self, data): os.write(self.write_dev, data) def _read(self, length=32): if self.strategy == 'try_twice': data = os.read(self.read_dev, length) if data: return data else: time.sleep(self.read_timeout) return os.read(self.read_dev, length) elif self.strategy == 'select': data = b'' start = time.time() while (not data) and (time.time() - start < self.read_timeout): result, _, _ = select.select([self.read_dev], [], [], 0) if self.read_dev in result: data += os.read(self.read_dev, length) if data: break time.sleep(0.001) if not data: # one last try if still no data: return os.read(self.read_dev, length) else: return data else: raise NotImplementedError('Unknown strategy') def _dispose(self): os.close(self.dev) pklaus-brother_ql-3380c8c/brother_ql/backends/network.py000077500000000000000000000067531341650246200235040ustar00rootroot00000000000000#!/usr/bin/env python """ Backend to support Brother QL-series printers via network. Works cross-platform. """ from __future__ import unicode_literals from builtins import str import socket, os, time, select from .generic import BrotherQLBackendGeneric def list_available_devices(): """ List all available devices for the network backend returns: devices: a list of dictionaries with the keys 'identifier' and 'instance': \ [ {'identifier': 'tcp://hostname[:port]', 'instance': None}, ] \ Instance is set to None because we don't want to connect to the device here yet. """ # We need some snmp request sent to 255.255.255.255 here raise NotImplementedError() return [{'identifier': 'tcp://' + path, 'instance': None} for path in paths] class BrotherQLBackendNetwork(BrotherQLBackendGeneric): """ BrotherQL backend using the Linux Kernel USB Printer Device Handles """ def __init__(self, device_specifier): """ device_specifier: string or os.open(): identifier in the \ format file:///dev/usb/lp0 or os.open() raw device handle. """ self.read_timeout = 0.01 # strategy : try_twice, select or socket_timeout self.strategy = 'socket_timeout' if isinstance(device_specifier, str): if device_specifier.startswith('tcp://'): device_specifier = device_specifier[6:] host, _, port = device_specifier.partition(':') if port: port = int(port) else: port = 9100 #try: self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.s.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1) self.s.connect((host, port)) #except OSError as e: # raise ValueError('Could not connect to the device.') if self.strategy == 'socket_timeout': self.s.settimeout(self.read_timeout) elif self.strategy == 'try_twice': self.s.settimeout(self.read_timeout) else: self.s.settimeout(0) elif isinstance(device_specifier, int): self.dev = device_specifier else: raise NotImplementedError('Currently the printer can be specified either via an appropriate string or via an os.open() handle.') def _write(self, data): self.s.settimeout(10) self.s.sendall(data) self.s.settimeout(self.read_timeout) def _read(self, length=32): if self.strategy in ('socket_timeout', 'try_twice'): if self.strategy == 'socket_timeout': tries = 1 if self.strategy == 'try_twice': tries = 2 for i in range(tries): try: data = self.s.recv(length) return data except socket.timeout: pass return b'' elif self.strategy == 'select': data = b'' start = time.time() while (not data) and (time.time() - start < self.read_timeout): result, _, _ = select.select([self.s], [], [], 0) if self.s in result: data += self.s.recv(length) if data: break time.sleep(0.001) return data else: raise NotImplementedError('Unknown strategy') def _dispose(self): self.s.shutdown(socket.SHUT_RDWR) self.s.close() pklaus-brother_ql-3380c8c/brother_ql/backends/pyusb.py000077500000000000000000000133671341650246200231540ustar00rootroot00000000000000#!/usr/bin/env python """ Backend to support Brother QL-series printers via PyUSB. Works on Mac OS X and Linux. Requires PyUSB: https://github.com/walac/pyusb/ Install via `pip install pyusb` """ from __future__ import unicode_literals from builtins import str import time import usb.core import usb.util from .generic import BrotherQLBackendGeneric def list_available_devices(): """ List all available devices for the respective backend returns: devices: a list of dictionaries with the keys 'identifier' and 'instance': \ [ {'identifier': 'usb://0x04f9:0x2015/C5Z315686', 'instance': pyusb.core.Device()}, ] The 'identifier' is of the format idVendor:idProduct_iSerialNumber. """ class find_class(object): def __init__(self, class_): self._class = class_ def __call__(self, device): # first, let's check the device if device.bDeviceClass == self._class: return True # ok, transverse all devices to find an interface that matches our class for cfg in device: # find_descriptor: what's it? intf = usb.util.find_descriptor(cfg, bInterfaceClass=self._class) if intf is not None: return True return False # only Brother printers printers = usb.core.find(find_all=1, custom_match=find_class(7), idVendor=0x04f9) def identifier(dev): try: serial = usb.util.get_string(dev, 256, dev.iSerialNumber) return 'usb://0x{:04x}:0x{:04x}_{}'.format(dev.idVendor, dev.idProduct, serial) except: return 'usb://0x{:04x}:0x{:04x}'.format(dev.idVendor, dev.idProduct) return [{'identifier': identifier(printer), 'instance': printer} for printer in printers] class BrotherQLBackendPyUSB(BrotherQLBackendGeneric): """ BrotherQL backend using PyUSB """ def __init__(self, device_specifier): """ device_specifier: string or pyusb.core.Device: identifier of the \ format usb://idVendor:idProduct/iSerialNumber or pyusb.core.Device instance. """ self.dev = None self.read_timeout = 10. # ms self.write_timeout = 15000. # ms # strategy : try_twice or select self.strategy = 'try_twice' if isinstance(device_specifier, str): if device_specifier.startswith('usb://'): device_specifier = device_specifier[6:] vendor_product, _, serial = device_specifier.partition('/') vendor, _, product = vendor_product.partition(':') vendor, product = int(vendor, 16), int(product, 16) for result in list_available_devices(): printer = result['instance'] if printer.idVendor == vendor and printer.idProduct == product or (serial and printer.iSerialNumber == serial): self.dev = printer break if self.dev is None: raise ValueError('Device not found') elif isinstance(device_specifier, usb.core.Device): self.dev = device_specifier else: raise NotImplementedError('Currently the printer can be specified either via an appropriate string or via a usb.core.Device instance.') # Now we are sure to have self.dev around, start using it: try: assert self.dev.is_kernel_driver_active(0) self.dev.detach_kernel_driver(0) self.was_kernel_driver_active = True except (NotImplementedError, AssertionError): self.was_kernel_driver_active = False # set the active configuration. With no arguments, the first configuration will be the active one self.dev.set_configuration() cfg = self.dev.get_active_configuration() intf = usb.util.find_descriptor(cfg, bInterfaceClass=7) assert intf is not None ep_match_in = lambda e: usb.util.endpoint_direction(e.bEndpointAddress) == usb.util.ENDPOINT_IN ep_match_out = lambda e: usb.util.endpoint_direction(e.bEndpointAddress) == usb.util.ENDPOINT_OUT ep_in = usb.util.find_descriptor(intf, custom_match=ep_match_in) ep_out = usb.util.find_descriptor(intf, custom_match=ep_match_out) assert ep_in is not None assert ep_out is not None self.write_dev = ep_out self.read_dev = ep_in def _raw_read(self, length): # pyusb Device.read() operations return array() type - let's convert it to bytes() return bytes(self.read_dev.read(length)) def _read(self, length=32): if self.strategy == 'try_twice': data = self._raw_read(length) if data: return bytes(data) else: time.sleep(self.read_timeout/1000.) return self._raw_read(length) elif self.strategy == 'select': data = b'' start = time.time() while (not data) and (time.time() - start < self.read_timeout/1000.): result, _, _ = select.select([self.read_dev], [], [], 0) if self.read_dev in result: data += self._raw_read(length) if data: break time.sleep(0.001) if not data: # one last try if still no data: return self._raw_read(length) else: return data else: raise NotImplementedError('Unknown strategy') def _write(self, data): self.write_dev.write(data, int(self.write_timeout)) def _dispose(self): usb.util.dispose_resources(self.dev) del self.write_dev, self.read_dev if self.was_kernel_driver_active: self.dev.attach_kernel_driver(0) del self.dev pklaus-brother_ql-3380c8c/brother_ql/brother_ql_analyse.py000077500000000000000000000012551341650246200241060ustar00rootroot00000000000000#!/usr/bin/env python import sys, argparse, logging from brother_ql.reader import BrotherQLReader def main(): parser = argparse.ArgumentParser() parser.add_argument('file', help='The file to analyze', type=argparse.FileType('rb')) parser.add_argument('--loglevel', type=lambda x: getattr(logging, x), default=logging.WARNING, help='The loglevel to apply') args = parser.parse_args() logging.basicConfig(stream=sys.stdout, format='%(levelname)s: %(message)s', level=args.loglevel) try: args.file = args.file.buffer except AttributeError: pass br = BrotherQLReader(args.file) br.analyse() if __name__ == '__main__': main() pklaus-brother_ql-3380c8c/brother_ql/brother_ql_create.py000077500000000000000000000066651341650246200237270ustar00rootroot00000000000000#!/usr/bin/env python import sys, argparse, logging from brother_ql.raster import BrotherQLRaster from brother_ql.conversion import convert from brother_ql.devicedependent import label_type_specs try: stdout = sys.stdout.buffer except: stdout = sys.stdout logger = logging.getLogger(__name__) def main(): parser = argparse.ArgumentParser() parser.add_argument('image', help='The image file to create a label from.') parser.add_argument('outfile', nargs='?', type=argparse.FileType('wb'), default=stdout, help='The file to write the instructions to. Defaults to stdout.') parser.add_argument('--model', '-m', default='QL-500', help='The printer model to use. Check available ones with `brother_ql_info list-models`.') parser.add_argument('--label-size', '-s', default='62', help='The label size (and kind) to use. Check available ones with `brother_ql_info list-label-sizes`.') parser.add_argument('--rotate', '-r', choices=('0', '90', '180', '270'), default='auto', help='Rotate the image (counterclock-wise) by this amount of degrees.') parser.add_argument('--threshold', '-t', type=float, default=70.0, help='The threshold value (in percent) to discriminate between black and white pixels.') parser.add_argument('--dither', '-d', action='store_true', help='Enable dithering when converting the image to b/w. If set, --threshold is meaningless.') parser.add_argument('--compress', '-c', action='store_true', help='Enable compression (if available with the model). Takes more time but results in smaller file size.') parser.add_argument('--red', action='store_true', help='Create a label to be printed on black/red/white tape (only with QL-8xx series on DK-22251 labels). You must use this option when printing on black/red tape, even when not printing red.') parser.add_argument('--600dpi', action='store_true', dest='dpi_600', help='Print with 600x300 dpi available on some models. Provide your image as 600x600 dpi; perpendicular to the feeding the image will be resized to 300dpi.') parser.add_argument('--lq', action='store_false', dest='hq', help='Print with low quality (faster). Default is high quality.') parser.add_argument('--no-cut', dest='cut', action='store_false', help="Don't cut the tape after printing the label.") parser.add_argument('--loglevel', type=lambda x: getattr(logging, x), default=logging.WARNING, help='Set to DEBUG for verbose debugging output to stderr.') args = parser.parse_args() logging.basicConfig(level=args.loglevel) args.model = args.model.upper() try: qlr = BrotherQLRaster(args.model) except BrotherQLUnknownModel: sys.exit("Unknown model. Use the command brother_ql_info list-models to show available models.") try: label_type_specs[args.label_size] except ValueError: sys.exit("Unknown label_size. Check available sizes with the command brother_ql_info list-label-sizes") qlr.exception_on_warning = True create_label(qlr, args.image, args.label_size, threshold=args.threshold, cut=args.cut, rotate=args.rotate, dither=args.dither, compress=args.compress, red=args.red, dpi_600=args.dpi_600, hq=args.hq) args.outfile.write(qlr.data) def create_label(qlr, image, label_size, threshold=70, cut=True, dither=False, compress=False, red=False, **kwargs): convert(qlr, [image], label_size, threshold=threshold, cut=cut, dither=dither, compress=compress, red=red, **kwargs) if __name__ == "__main__": main() pklaus-brother_ql-3380c8c/brother_ql/brother_ql_debug.py000077500000000000000000000117721341650246200235450ustar00rootroot00000000000000#!/usr/bin/env python import sys, argparse, logging, struct, io, logging, sys, os, time from pprint import pprint, pformat from brother_ql.reader import OPCODES, chunker, merge_specific_instructions, interpret_response, match_opcode, hex_format from brother_ql.backends import backend_factory, guess_backend logger = logging.getLogger(__name__) class BrotherQL_USBdebug(object): def __init__(self, dev, instructions_data, backend='linux_kernel'): be_cls = backend_factory(backend)['backend_class'] self.be = be_cls(dev) self.sleep_time = 0.0 self.sleep_before_read = 0.0 self.continue_reading_for = 3.0 self.start = time.time() self.interactive = False self.merge_specific_instructions = True if type(instructions_data) in (str,): with open(instructions_data, 'rb') as f: self.instructions_data = f.read() elif type(instructions_data) in (bytes,): self.instructions_data = instructions_data else: raise NotImplementedError('Only filename or bytes supported for instructions_data argument') response = self.be.read() if response: logger.warning('Received response before sending instructions: {}'.format(hex_format(response))) def continue_reading(self, seconds=3.0): start = time.time() while time.time() - start < seconds: data = self.be.read() if data != b'': global_time = time.time() - self.start print('TIME %.2f' % global_time) self.log_interp_response(data) time.sleep(0.001) def log_interp_response(self, data): try: interp_result = interpret_response(data) logger.info("Interpretation of the response: '{status_type}' (phase: {phase_type}), '{media_type}' {media_width}x{media_length} mm^2, errors: {errors}".format(**interp_result)) except: logger.error("Couln't interpret response: %s", hex_format(data)) def print_and_debug(self): self.continue_reading(0.2) instructions = chunker(self.instructions_data) instructions = merge_specific_instructions(instructions, join_preamble=True, join_raster=self.merge_specific_instructions) for instruction in instructions: opcode = match_opcode(instruction) opcode_def = OPCODES[opcode] cmd_name = opcode_def[0] hex_instruction = hex_format(instruction).split() if len(hex_instruction) > 100: hex_instruction = ' '.join(hex_instruction[0:70] + ['[...]'] + hex_instruction[-30:]) else: hex_instruction = ' '.join(hex_instruction) logger.info("CMD {} FOUND. Instruction: {} ".format(cmd_name, hex_instruction)) if self.interactive: input('Continue?') # WRITE self.be.write(instruction) # SLEEP BEFORE READ time.sleep(self.sleep_before_read) # READ response = self.be.read() #response += self.be.read() if response != b'': logger.info("Response from the device: {}".format(hex_format(response))) self.log_interp_response(response) # SLEEP BETWEEN INSTRUCTIONS time.sleep(self.sleep_time) self.continue_reading(self.continue_reading_for) def main(): parser = argparse.ArgumentParser() parser.add_argument('file', help='The file to analyze') parser.add_argument('dev', help='The device to use. Can be usb://0x04f9:0x2015 or /dev/usb/lp0 for example') parser.add_argument('--sleep-time', type=float, help='time in seconds to sleep between instructions') parser.add_argument('--sleep-before-read', type=float, help='time in seconds to sleep before reading response') parser.add_argument('--continue-reading-for', type=float, help='continue reading after sending the last commands (time in seconds)') parser.add_argument('--interactive', action='store_true', help='interactive mode') parser.add_argument('--split-raster', action='store_true', help='even split preamble and raster instructions into single write operations') parser.add_argument('--debug', action='store_true', help='enable debug mode') args = parser.parse_args() # SETUP loglevel = logging.DEBUG if args.debug else logging.INFO logging.basicConfig(level=loglevel, format='%(levelname)s: %(message)s') try: backend = guess_backend(args.dev) except ValueError as e: parser.error(e.msg) br = BrotherQL_USBdebug(args.dev, args.file, backend=backend) if args.interactive: br.interactive = True if args.sleep_time: br.sleep_time = args.sleep_time if args.sleep_before_read: br.sleep_before_read = args.sleep_before_read if args.split_raster: br.merge_specific_instructions = False if args.continue_reading_for: br.continue_reading_for = args.continue_reading_for # GO br.print_and_debug() if __name__ == '__main__': main() pklaus-brother_ql-3380c8c/brother_ql/brother_ql_info.py000077500000000000000000000032661341650246200234110ustar00rootroot00000000000000#!/usr/bin/env python import argparse from brother_ql.devicedependent import models, label_sizes, label_type_specs, DIE_CUT_LABEL, ENDLESS_LABEL, ROUND_DIE_CUT_LABEL def main(): parser = argparse.ArgumentParser() subparser = parser.add_subparsers(dest='action') subparser.add_parser('list-label-sizes', help='List available label sizes') subparser.add_parser('list-models', help='List available models') args = parser.parse_args() if not args.action: parser.error('Please choose an action') elif args.action == 'list-models': print('Supported models:') for model in models: print(" " + model) elif args.action == 'list-label-sizes': print('Supported label sizes:') fmt = " {label_size:9s} {dots_printable:14s} {label_descr:26s}" print(fmt.format(label_size="Name", label_descr="Description", dots_printable="Printable px")) for label_size in label_sizes: s = label_type_specs[label_size] if s['kind'] == DIE_CUT_LABEL: label_descr = "(%d x %d mm^2)" % s['tape_size'] dots_printable = "{0:4d} x {1:4d}".format(*s['dots_printable']) if s['kind'] == ENDLESS_LABEL: label_descr = "(%d mm endless)" % s['tape_size'][0] dots_printable = "{0:4d}".format(*s['dots_printable']) if s['kind'] == ROUND_DIE_CUT_LABEL: label_descr = "(%d mm diameter, round)" % s['tape_size'][0] dots_printable = "{0:4d} x {1:4d}".format(*s['dots_printable']) print(fmt.format(label_size=label_size, label_descr=label_descr, dots_printable=dots_printable)) if __name__ == "__main__": main() pklaus-brother_ql-3380c8c/brother_ql/brother_ql_print.py000077500000000000000000000070701341650246200236070ustar00rootroot00000000000000#!/usr/bin/env python """ Testing the packaged version of the Linux Kernel backend """ import argparse, logging, sys from brother_ql.backends import backend_factory, guess_backend, available_backends from brother_ql.backends.helpers import discover, send from brother_ql.output_helpers import log_discovered_devices, textual_description_discovered_devices logger = logging.getLogger(__name__) def main(): # Command line parsing... parser = argparse.ArgumentParser() parser.add_argument('--backend', choices=available_backends, help='Forces the use of a specific backend') parser.add_argument('--list-printers', action='store_true', help='List the devices available with the selected --backend') parser.add_argument('--debug', action='store_true', help='Enable debugging output') parser.add_argument('instruction_file', nargs='?', help='file containing the instructions to be sent to the printer') parser.add_argument('printer', metavar='PRINTER_IDENTIFIER', nargs='?', help='Identifier string specifying the printer. If not specified, selects the first detected device.') args = parser.parse_args() if args.list_printers and not args.backend: parser.error('Please specify the backend in order to list available devices.') if not args.list_printers and not args.instruction_file: parser.error("the following arguments are required: instruction_file") # Reading the instruction input file into content variable if args.instruction_file == '-': try: content = sys.stdin.buffer.read() except AttributeError: content = sys.stdin.read() else: with open(args.instruction_file, 'rb') as f: content = f.read() # Setting up the requested level of logging. level = logging.DEBUG if args.debug else logging.INFO logging.basicConfig(level=level) # State any shortcomings of this software early on. if args.backend == 'network': logger.warning("The network backend doesn't supply any 'readback' functionality. No status reports will be received.") # Select the backend based: Either explicitly stated or derived from identifier. Otherwise: Default. selected_backend = None if args.backend: selected_backend = args.backend else: try: selected_backend = guess_backend(args.printer) except: logger.info("No backend stated. Selecting the default linux_kernel backend.") selected_backend = 'linux_kernel' # List any printers found, if explicitly asked to do so or if no identifier has been provided. if args.list_printers or not args.printer: available_devices = discover(backend_identifier=selected_backend) log_discovered_devices(available_devices) if args.list_printers: print(textual_description_discovered_devices(available_devices)) sys.exit(0) # Determine the identifier. Either selecting the explicitly stated one or using the first found device. identifier = None if not args.printer: "We need to search for available devices and select the first." if not available_devices: sys.exit("No printer found") identifier = available_devices[0]['identifier'] print("Selecting first device %s" % identifier) else: "A string identifier for the device was given, let's use it." identifier = args.printer # Finally, do the actual printing. send(instructions=content, printer_identifier=identifier, backend_identifier=selected_backend, blocking=True) if __name__ == "__main__": main() pklaus-brother_ql-3380c8c/brother_ql/cli.py000077500000000000000000000171441341650246200210040ustar00rootroot00000000000000#!/usr/bin/env python # Python standard library from __future__ import print_function import logging # external dependencies import click # imports from this very package from brother_ql.devicedependent import models, label_sizes, label_type_specs, DIE_CUT_LABEL, ENDLESS_LABEL, ROUND_DIE_CUT_LABEL from brother_ql.backends import available_backends, backend_factory logger = logging.getLogger('brother_ql') printer_help = "The identifier for the printer. This could be a string like tcp://192.168.1.21:9100 for a networked printer or usb://0x04f9:0x2015/000M6Z401370 for a printer connected via USB." @click.group() @click.option('-b', '--backend', type=click.Choice(available_backends), envvar='BROTHER_QL_BACKEND') @click.option('-m', '--model', type=click.Choice(models), envvar='BROTHER_QL_MODEL') @click.option('-p', '--printer', metavar='PRINTER_IDENTIFIER', envvar='BROTHER_QL_PRINTER', help=printer_help) @click.option('--debug', is_flag=True) @click.version_option() @click.pass_context def cli(ctx, *args, **kwargs): """ Command line interface for the brother_ql Python package. """ backend = kwargs.get('backend', None) model = kwargs.get('model', None) printer = kwargs.get('printer', None) debug = kwargs.get('debug') # Store the general CLI options in the context meta dictionary. # The name corresponds to the second half of the respective envvar: ctx.meta['MODEL'] = model ctx.meta['BACKEND'] = backend ctx.meta['PRINTER'] = printer logging.basicConfig(level='DEBUG' if debug else 'INFO') @cli.command() @click.pass_context def discover(ctx): """ find connected label printers """ backend = ctx.meta.get('BACKEND', 'pyusb') discover_and_list_available_devices(backend) def discover_and_list_available_devices(backend): from brother_ql.backends.helpers import discover available_devices = discover(backend_identifier=backend) from brother_ql.output_helpers import log_discovered_devices, textual_description_discovered_devices log_discovered_devices(available_devices) print(textual_description_discovered_devices(available_devices)) @cli.group() @click.pass_context def info(ctx, *args, **kwargs): """ list available labels, models etc. """ @info.command(name='models') @click.pass_context def models_cmd(ctx, *args, **kwargs): """ List the choices for --model """ print('Supported models:') for model in models: print(" " + model) @info.command() @click.pass_context def labels(ctx, *args, **kwargs): """ List the choices for --label """ from brother_ql.output_helpers import textual_label_description print(textual_label_description(label_sizes)) @info.command() @click.pass_context def env(ctx, *args, **kwargs): """ print debug info about running environment """ import sys, platform, os, shutil from pkg_resources import get_distribution, working_set print("\n##################\n") print("Information about the running environment of brother_ql.") print("(Please provide this information when reporting any issue.)\n") # computer print("About the computer:") for attr in ('platform', 'processor', 'release', 'system', 'machine', 'architecture'): print(' * '+attr.title()+':', getattr(platform, attr)()) # Python print("About the installed Python version:") py_version = str(sys.version).replace('\n', ' ') print(" *", py_version) # brother_ql print("About the brother_ql package:") pkg = get_distribution('brother_ql') print(" * package location:", pkg.location) print(" * package version: ", pkg.version) try: cli_loc = shutil.which('brother_ql') except: cli_loc = 'unknown' print(" * brother_ql CLI path:", cli_loc) # brother_ql's requirements print("About the requirements of brother_ql:") fmt = " {req:14s} | {spec:10s} | {ins_vers:17s}" print(fmt.format(req='requirement', spec='requested', ins_vers='installed version')) print(fmt.format(req='-' * 14, spec='-'*10, ins_vers='-'*17)) requirements = list(pkg.requires()) requirements.sort(key=lambda x: x.project_name) for req in requirements: proj = req.project_name req_pkg = get_distribution(proj) spec = ' '.join(req.specs[0]) if req.specs else 'any' print(fmt.format(req=proj, spec=spec, ins_vers=req_pkg.version)) print("\n##################\n") @cli.command('print', short_help='Print a label') @click.argument('images', nargs=-1, type=click.File('rb'), metavar='IMAGE [IMAGE] ...') @click.option('-l', '--label', type=click.Choice(label_sizes), envvar='BROTHER_QL_LABEL', help='The label (size, type - die-cut or endless). Run `brother_ql info labels` for a full list including ideal pixel dimensions.') @click.option('-r', '--rotate', type=click.Choice(('auto', '0', '90', '180', '270')), default='auto', help='Rotate the image (counterclock-wise) by this amount of degrees.') @click.option('-t', '--threshold', type=float, default=70.0, help='The threshold value (in percent) to discriminate between black and white pixels.') @click.option('-d', '--dither', is_flag=True, help='Enable dithering when converting the image to b/w. If set, --threshold is meaningless.') @click.option('-c', '--compress', is_flag=True, help='Enable compression (if available with the model). Label creation can take slightly longer but the resulting instruction size is normally considerably smaller.') @click.option('--red', is_flag=True, help='Create a label to be printed on black/red/white tape (only with QL-8xx series on DK-22251 labels). You must use this option when printing on black/red tape, even when not printing red.') @click.option('--600dpi', 'dpi_600', is_flag=True, help='Print with 600x300 dpi available on some models. Provide your image as 600x600 dpi; perpendicular to the feeding the image will be resized to 300dpi.') @click.option('--lq', is_flag=True, help='Print with low quality (faster). Default is high quality.') @click.option('--no-cut', is_flag=True, help="Don't cut the tape after printing the label.") @click.pass_context def print_cmd(ctx, *args, **kwargs): """ Print a label of the provided IMAGE. """ backend = ctx.meta.get('BACKEND', 'pyusb') model = ctx.meta.get('MODEL') printer = ctx.meta.get('PRINTER') from brother_ql.conversion import convert from brother_ql.backends.helpers import send from brother_ql.raster import BrotherQLRaster qlr = BrotherQLRaster(model) qlr.exception_on_warning = True kwargs['cut'] = not kwargs['no_cut'] del kwargs['no_cut'] instructions = convert(qlr=qlr, **kwargs) send(instructions=instructions, printer_identifier=printer, backend_identifier=backend, blocking=True) @cli.command(name='analyze', help='interpret a binary file containing raster instructions for the Brother QL-Series printers') @click.argument('instructions', type=click.File('rb')) @click.option('-f', '--filename-format', help="Filename format string. Default is: label{counter:04d}.png.") @click.pass_context def analyze_cmd(ctx, *args, **kwargs): from brother_ql.reader import BrotherQLReader br = BrotherQLReader(kwargs.get('instructions')) if kwargs.get('filename_format'): br.filename_fmt = kwargs.get('filename_format') br.analyse() @cli.command(name='send', short_help='send an instruction file to the printer') @click.argument('instructions', type=click.File('rb')) @click.pass_context def send_cmd(ctx, *args, **kwargs): from brother_ql.backends.helpers import send send(instructions=kwargs['instructions'].read(), printer_identifier=ctx.meta.get('PRINTER'), backend_identifier=ctx.meta.get('BACKEND'), blocking=True) if __name__ == '__main__': cli() pklaus-brother_ql-3380c8c/brother_ql/conversion.py000077500000000000000000000163311341650246200224170ustar00rootroot00000000000000#!/usr/bin/env python from __future__ import division, unicode_literals from builtins import str import logging from PIL import Image import PIL.ImageOps, PIL.ImageChops from brother_ql.raster import BrotherQLRaster from brother_ql.devicedependent import label_type_specs, ENDLESS_LABEL, DIE_CUT_LABEL, ROUND_DIE_CUT_LABEL, right_margin_addition from brother_ql import BrotherQLUnsupportedCmd from brother_ql.image_trafos import filtered_hsv logger = logging.getLogger(__name__) logging.getLogger("PIL.PngImagePlugin").setLevel(logging.WARNING) def convert(qlr, images, label, **kwargs): r"""Converts one or more images to a raster instruction file. :param qlr: An instance of the BrotherQLRaster class :type qlr: :py:class:`brother_ql.raster.BrotherQLRaster` :param images: The images to be converted. They can be filenames or instances of Pillow's Image. :type images: list(PIL.Image.Image) or list(str) images :param str label: Type of label the printout should be on. :param \**kwargs: See below :Keyword Arguments: * **cut** (``bool``) -- Enable cutting after printing the labels. * **dither** (``bool``) -- Instead of applying a threshold to the pixel values, approximate grey tones with dithering. * **compress** * **red** * **rotate** * **dpi_600** * **hq** * **threshold** """ label_specs = label_type_specs[label] dots_printable = label_specs['dots_printable'] right_margin_dots = label_specs['right_margin_dots'] right_margin_dots += right_margin_addition.get(qlr.model, 0) device_pixel_width = qlr.get_pixel_width() cut = kwargs.get('cut', True) dither = kwargs.get('dither', False) compress = kwargs.get('compress', False) red = kwargs.get('red', False) rotate = kwargs.get('rotate', 'auto') if rotate != 'auto': rotate = int(rotate) dpi_600 = kwargs.get('dpi_600', False) hq = kwargs.get('hq', True) threshold = kwargs.get('threshold', 70) threshold = 100.0 - threshold threshold = min(255, max(0, int(threshold/100.0 * 255))) if red and not qlr.two_color_support: raise BrotherQLUnsupportedCmd('Printing in red is not supported with the selected model.') try: qlr.add_switch_mode() except BrotherQLUnsupportedCmd: pass qlr.add_invalidate() qlr.add_initialize() try: qlr.add_switch_mode() except BrotherQLUnsupportedCmd: pass for image in images: if isinstance(image, Image.Image): im = image else: try: im = Image.open(image) except: raise NotImplementedError("The image argument needs to be an Image() instance, the filename to an image, or a file handle.") if im.mode.endswith('A'): # place in front of white background and get red of transparency bg = Image.new("RGB", im.size, (255,255,255)) bg.paste(im, im.split()[-1]) im = bg elif im.mode == "P": # Convert GIF ("P") to RGB im = im.convert("RGB" if red else "L") elif im.mode == "L" and red: # Convert greyscale to RGB if printing on black/red tape im = im.convert("RGB") if dpi_600: dots_expected = [el*2 for el in dots_printable] else: dots_expected = dots_printable if label_specs['kind'] == ENDLESS_LABEL: if rotate not in ('auto', 0): im = im.rotate(rotate, expand=True) if dpi_600: im = im.resize((im.size[0]//2, im.size[1])) if im.size[0] != dots_printable[0]: hsize = int((dots_printable[0] / im.size[0]) * im.size[1]) im = im.resize((dots_printable[0], hsize), Image.ANTIALIAS) logger.warning('Need to resize the image...') if im.size[0] < device_pixel_width: new_im = Image.new(im.mode, (device_pixel_width, im.size[1]), (255,)*len(im.mode)) new_im.paste(im, (device_pixel_width-im.size[0]-right_margin_dots, 0)) im = new_im elif label_specs['kind'] in (DIE_CUT_LABEL, ROUND_DIE_CUT_LABEL): if rotate == 'auto': if im.size[0] == dots_expected[1] and im.size[1] == dots_expected[0]: im = im.rotate(90, expand=True) elif rotate != 0: im = im.rotate(rotate, expand=True) if im.size[0] != dots_expected[0] or im.size[1] != dots_expected[1]: raise ValueError("Bad image dimensions: %s. Expecting: %s." % (im.size, dots_expected)) if dpi_600: im = im.resize((im.size[0]//2, im.size[1])) new_im = Image.new(im.mode, (device_pixel_width, dots_expected[1]), (255,)*len(im.mode)) new_im.paste(im, (device_pixel_width-im.size[0]-right_margin_dots, 0)) im = new_im if red: filter_h = lambda h: 255 if (h < 40 or h > 210) else 0 filter_s = lambda s: 255 if s > 100 else 0 filter_v = lambda v: 255 if v > 80 else 0 red_im = filtered_hsv(im, filter_h, filter_s, filter_v) red_im = red_im.convert("L") red_im = PIL.ImageOps.invert(red_im) red_im = red_im.point(lambda x: 0 if x < threshold else 255, mode="1") filter_h = lambda h: 255 filter_s = lambda s: 255 filter_v = lambda v: 255 if v < 80 else 0 black_im = filtered_hsv(im, filter_h, filter_s, filter_v) black_im = black_im.convert("L") black_im = PIL.ImageOps.invert(black_im) black_im = black_im.point(lambda x: 0 if x < threshold else 255, mode="1") black_im = PIL.ImageChops.subtract(black_im, red_im) else: im = im.convert("L") im = PIL.ImageOps.invert(im) if dither: im = im.convert("1", dither=Image.FLOYDSTEINBERG) else: im = im.point(lambda x: 0 if x < threshold else 255, mode="1") qlr.add_status_information() tape_size = label_specs['tape_size'] if label_specs['kind'] in (DIE_CUT_LABEL, ROUND_DIE_CUT_LABEL): qlr.mtype = 0x0B qlr.mwidth = tape_size[0] qlr.mlength = tape_size[1] else: qlr.mtype = 0x0A qlr.mwidth = tape_size[0] qlr.mlength = 0 qlr.pquality = int(hq) qlr.add_media_and_quality(im.size[1]) try: if cut: qlr.add_autocut(True) qlr.add_cut_every(1) except BrotherQLUnsupportedCmd: pass try: qlr.dpi_600 = dpi_600 qlr.cut_at_end = cut qlr.two_color_printing = True if red else False qlr.add_expanded_mode() except BrotherQLUnsupportedCmd: pass qlr.add_margins(label_specs['feed_margin']) try: if compress: qlr.add_compression(True) except BrotherQLUnsupportedCmd: pass if red: qlr.add_raster_data(black_im, red_im) else: qlr.add_raster_data(im) qlr.add_print() return qlr.data pklaus-brother_ql-3380c8c/brother_ql/devicedependent.py000066400000000000000000000063511341650246200233560ustar00rootroot00000000000000""" Deprecated Module brother_ql.devicedependent This module held constants and settings that were specific to different QL-series printer models and to different label types. The content is now split into two modules: * brother_ql.models * brother_ql.labels Please import directly from them as this module will be removed in a future version. """ import logging logger = logging.getLogger(__name__) logger.warn("deprecation warning: brother_ql.devicedependent is deprecated and will be removed in a future release") ## These module level variables were available here before. # Concerning labels DIE_CUT_LABEL = None ENDLESS_LABEL = None ROUND_DIE_CUT_LABEL = None label_type_specs = {} label_sizes = [] # And concerning printer models models = [] min_max_length_dots = {} min_max_feed = {} number_bytes_per_row = {} right_margin_addition = {} modesetting = [] cuttingsupport = [] expandedmode = [] compressionsupport = [] two_color_support = [] ## Let's recreate them using the improved data structures ## in brother_ql.models and brother_ql.labels def _populate_model_legacy_structures(): from brother_ql.models import ModelsManager global models global min_max_length_dots, min_max_feed, number_bytes_per_row, right_margin_addition global modesetting, cuttingsupport, expandedmode, compressionsupport, two_color_support for model in ModelsManager().iter_elements(): models.append(model.identifier) min_max_length_dots[model.identifier] = model.min_max_length_dots min_max_feed[model.identifier] = model.min_max_feed number_bytes_per_row[model.identifier] = model.number_bytes_per_row right_margin_addition[model.identifier] = model.additional_offset_r if model.mode_setting: modesetting.append(model.identifier) if model.cutting: cuttingsupport.append(model.identifier) if model.expanded_mode: expandedmode.append(model.identifier) if model.compression: compressionsupport.append(model.identifier) if model.two_color: two_color_support.append(model.identifier) def _populate_label_legacy_structures(): """ We contain this code inside a function so that the imports we do in here are not visible at the module level. """ global DIE_CUT_LABEL, ENDLESS_LABEL, ROUND_DIE_CUT_LABEL global label_sizes, label_type_specs from brother_ql.labels import FormFactor DIE_CUT_LABEL = FormFactor.DIE_CUT ENDLESS_LABEL = FormFactor.ENDLESS ROUND_DIE_CUT_LABEL = FormFactor.ROUND_DIE_CUT from brother_ql.labels import LabelsManager lm = LabelsManager() label_sizes = list(lm.iter_identifiers()) for label in lm.iter_elements(): l = {} l['name'] = label.name l['kind'] = label.form_factor l['color'] = label.color l['tape_size'] = label.tape_size l['dots_total'] = label.dots_total l['dots_printable'] = label.dots_printable l['right_margin_dots'] = label.offset_r l['feed_margin'] = label.feed_margin l['restrict_printers'] = label.restricted_to_models label_type_specs[label.identifier] = l def _populate_all_legacy_structures(): _populate_label_legacy_structures() _populate_model_legacy_structures() _populate_all_legacy_structures() pklaus-brother_ql-3380c8c/brother_ql/exceptions.py000066400000000000000000000003211341650246200224000ustar00rootroot00000000000000 class BrotherQLError(Exception): pass class BrotherQLUnsupportedCmd(BrotherQLError): pass class BrotherQLUnknownModel(BrotherQLError): pass class BrotherQLRasterError(BrotherQLError): pass pklaus-brother_ql-3380c8c/brother_ql/helpers.py000066400000000000000000000023651341650246200216730ustar00rootroot00000000000000 import logging logger = logging.getLogger(__name__) class ElementsManager(object): """ A class managing a collection of 'elements'. Those elements are expected to be objects that * can be compared for equality against each other * have the attribute .identifier """ DEFAULT_ELEMENTS = [] ELEMENT_NAME = "element" def __init__(self, elements=None): if elements: self._elements = elements else: self._elements = self.DEFAULT_ELEMENTS def register(self, element, pos=-1): if element not in self._elements: if pos == -1: pos = len(self._labels) self._labels.insert(len(self._labels), label) else: logger.warn("Won't register %s as it's already present: %s", self.ELEMENT_NAME, element) def deregister(self, element): if element in self._elements: self._elements.remove(element) else: logger.warn("Trying to deregister a %s that's not registered currently: %s", self.ELEMENT_NAME, label) def iter_identifiers(self): for element in self._elements: yield element.identifier def iter_elements(self): for element in self._elements: yield element pklaus-brother_ql-3380c8c/brother_ql/image_trafos.py000066400000000000000000000012401341650246200226600ustar00rootroot00000000000000from PIL import Image import colorsys def filtered_hsv(im, filter_h, filter_s, filter_v, default_col=(255,255,255)): """ https://stackoverflow.com/a/22237709/183995 """ hsv_im = im.convert('HSV') H, S, V = 0, 1, 2 hsv = hsv_im.split() mask_h = hsv[H].point(filter_h) mask_s = hsv[S].point(filter_s) mask_v = hsv[V].point(filter_v) Mdat = [] for h, s, v in zip(mask_h.getdata(), mask_s.getdata(), mask_v.getdata()): Mdat.append(255 if (h and s and v) else 0) mask = mask_h mask.putdata(Mdat) filtered_im = Image.new("RGB", im.size, color=default_col) filtered_im.paste(im, None, mask) return filtered_im pklaus-brother_ql-3380c8c/brother_ql/labels.py000066400000000000000000000130321341650246200214640ustar00rootroot00000000000000 from attr import attrs, attrib from typing import List, Tuple from enum import Enum import copy from brother_ql.helpers import ElementsManager class FormFactor(Enum): """ Enumeration representing the form factor of a label. The labels for the Brother QL series are supplied either as die-cut (pre-sized), or for more flexibility the continuous label tapes offer the ability to vary the label length. """ #: rectangular die-cut labels DIE_CUT = 1 #: endless (continouse) labels ENDLESS = 2 #: round die-cut labels ROUND_DIE_CUT = 3 class Color(Enum): """ Enumeration representing the colors to be printed on a label. Most labels only support printing black on white. Some newer ones can also print in black and red on white. """ #: The label can be printed in black & white. BLACK_WHITE = 0 #: The label can be printed in black, white & red. BLACK_RED_WHITE = 1 @attrs class Label(object): """ This class represents a label. All specifics of a certain label and what the rasterizer needs to take care of depending on the label choosen, should be contained in this class. """ #: A string identifier given to each label that can be selected. Eg. '29'. identifier = attrib(type=str) #: The tape size of a single label (width, lenght) in mm. For endless labels, the length is 0 by definition. tape_size = attrib(type=Tuple[int, int]) #: The type of label form_factor = attrib(type=FormFactor) #: The total area (width, length) of the label in dots (@300dpi). dots_total = attrib(type=Tuple[int, int]) #: The printable area (width, length) of the label in dots (@300dpi). dots_printable = attrib(type=Tuple[int, int]) #: The required offset from the right side of the label in dots to obtain a centered printout. offset_r = attrib(type=int) #: An additional amount of feeding when printing the label. #: This is non-zero for some smaller label sizes and for endless labels. feed_margin = attrib(type=int, default=0) #: If a label can only be printed with certain label printers, this member variable lists the allowed ones. #: Otherwise it's an empty list. restricted_to_models = attrib(type=List[str], factory=list) #: Some labels allow printing in red, most don't. color = attrib(type=Color, default=Color.BLACK_WHITE) def works_with_model(self, model): # type: bool """ Method to determine if certain label can be printed by the specified printer model. """ if self.restricted_to_models and model not in models: return False else: return True @property def name(self): # type: str out = "" if 'x' in self.identifier: out = '{0}mm x {1}mm die-cut'.format(*self.tape_size) elif self.identifier.startswith('d'): out = '{0}mm round die-cut'.format(self.tape_size[0]) else: out = '{0}mm endless'.format(self.tape_size[0]) if self.color == Color.BLACK_RED_WHITE: out += ' (black/red/white)' return out ALL_LABELS = ( Label("12", ( 12, 0), FormFactor.ENDLESS, ( 142, 0), ( 106, 0), 29 , feed_margin=35), Label("29", ( 29, 0), FormFactor.ENDLESS, ( 342, 0), ( 306, 0), 6 , feed_margin=35), Label("38", ( 38, 0), FormFactor.ENDLESS, ( 449, 0), ( 413, 0), 12 , feed_margin=35), Label("50", ( 50, 0), FormFactor.ENDLESS, ( 590, 0), ( 554, 0), 12 , feed_margin=35), Label("54", ( 54, 0), FormFactor.ENDLESS, ( 636, 0), ( 590, 0), 0 , feed_margin=35), Label("62", ( 62, 0), FormFactor.ENDLESS, ( 732, 0), ( 696, 0), 12 , feed_margin=35), Label("62red", ( 62, 0), FormFactor.ENDLESS, ( 732, 0), ( 696, 0), 12 , feed_margin=35, color=Color.BLACK_RED_WHITE), Label("102", (102, 0), FormFactor.ENDLESS, (1200, 0), (1164, 0), 12 , feed_margin=35, restricted_to_models=['QL-1050', 'QL-1060N']), Label("17x54", ( 17, 54), FormFactor.DIE_CUT, ( 201, 636), ( 165, 566), 0 ), Label("17x87", ( 17, 87), FormFactor.DIE_CUT, ( 201, 1026), ( 165, 956), 0 ), Label("23x23", ( 23, 23), FormFactor.DIE_CUT, ( 272, 272), ( 202, 202), 42 ), Label("29x42", ( 29, 42), FormFactor.DIE_CUT, ( 342, 495), ( 306, 425), 6 ), Label("29x90", ( 29, 90), FormFactor.DIE_CUT, ( 342, 1061), ( 306, 991), 6 ), Label("39x90", ( 38, 90), FormFactor.DIE_CUT, ( 449, 1061), ( 413, 991), 12 ), Label("39x48", ( 39, 48), FormFactor.DIE_CUT, ( 461, 565), ( 425, 495), 6 ), Label("52x29", ( 52, 29), FormFactor.DIE_CUT, ( 614, 341), ( 578, 271), 0 ), Label("62x29", ( 62, 29), FormFactor.DIE_CUT, ( 732, 341), ( 696, 271), 12 ), Label("62x100", ( 62, 100), FormFactor.DIE_CUT, ( 732, 1179), ( 696, 1109), 12 ), Label("102x51", (102, 51), FormFactor.DIE_CUT, (1200, 596), (1164, 526), 12 , restricted_to_models=['QL-1050', 'QL-1060N']), Label("102x152",(102, 153), FormFactor.DIE_CUT, (1200, 1804), (1164, 1660), 12 , restricted_to_models=['QL-1050', 'QL-1060N']), Label("d12", ( 12, 12), FormFactor.ROUND_DIE_CUT, ( 142, 142), ( 94, 94), 113 , feed_margin=35), Label("d24", ( 24, 24), FormFactor.ROUND_DIE_CUT, ( 284, 284), ( 236, 236), 42 ), Label("d58", ( 58, 58), FormFactor.ROUND_DIE_CUT, ( 688, 688), ( 618, 618), 51 ), ) class LabelsManager(ElementsManager): DEFAULT_ELEMENTS = copy.copy(ALL_LABELS) ELEMENT_NAME = "label" pklaus-brother_ql-3380c8c/brother_ql/models.py000066400000000000000000000052621341650246200215130ustar00rootroot00000000000000from attr import attrs, attrib from typing import Tuple import copy from brother_ql.helpers import ElementsManager @attrs class Model(object): """ This class represents a printer model. All specifics of a certain model and the opcodes it supports should be contained in this class. """ #: A string identifier given to each model implemented. Eg. 'QL-500'. identifier = attrib(type=str) #: Minimum and maximum number of rows or 'dots' that can be printed. #: Together with the dpi this gives the minimum and maximum length #: for continuous tape printing. min_max_length_dots = attrib(type=Tuple[int, int]) #: The minimum and maximum amount of feeding a label min_max_feed = attrib(type=Tuple[int, int], default=(35, 1500)) number_bytes_per_row = attrib(type=int, default=90) #: The required additional offset from the right side additional_offset_r = attrib(type=int, default=0) #: Support for the 'mode setting' opcode mode_setting = attrib(type=bool, default=True) #: Model has a cutting blade to automatically cut labels cutting = attrib(type=bool, default=True) #: Model has support for the 'expanded mode' opcode. #: (So far, all models that have cutting support do). expanded_mode = attrib(type=bool, default=True) #: Model has support for compressing the transmitted raster data. #: Some models with only USB connectivity don't support compression. compression = attrib(type=bool, default=True) #: Support for two color printing (black/red/white) #: available only on some newer models. two_color = attrib(type=bool, default=False) @property def name(self): return self.identifier ALL_MODELS = [ Model('QL-500', (295, 11811), compression=False, mode_setting=False, expanded_mode=False, cutting=False), Model('QL-550', (295, 11811), compression=False, mode_setting=False), Model('QL-560', (295, 11811), compression=False, mode_setting=False), Model('QL-570', (150, 11811), compression=False, mode_setting=False), Model('QL-580N', (150, 11811)), Model('QL-650TD', (295, 11811)), Model('QL-700', (150, 11811), compression=False, mode_setting=False), Model('QL-710W', (150, 11811)), Model('QL-720NW', (150, 11811)), Model('QL-800', (150, 11811), two_color=True, compression=False), Model('QL-810W', (150, 11811), two_color=True), Model('QL-820NWB',(150, 11811), two_color=True), Model('QL-1050', (295, 35433), number_bytes_per_row=162, additional_offset_r=44), Model('QL-1060N', (295, 35433), number_bytes_per_row=162, additional_offset_r=44), ] class ModelsManager(ElementsManager): DEFAULT_ELEMENTS = copy.copy(ALL_MODELS) ELEMENTS_NAME = 'model' pklaus-brother_ql-3380c8c/brother_ql/output_helpers.py000066400000000000000000000027651341650246200233170ustar00rootroot00000000000000import logging from brother_ql.devicedependent import label_type_specs from brother_ql.devicedependent import DIE_CUT_LABEL, ENDLESS_LABEL, ROUND_DIE_CUT_LABEL logger = logging.getLogger(__name__) def textual_label_description(labels_to_include): output = "Supported label sizes:\n" output = "" fmt = " {label_size:9s} {dots_printable:14s} {label_descr:26s}\n" output += fmt.format(label_size="Name", dots_printable="Printable px", label_descr="Description") #output += fmt.format(label_size="", dots_printable="width x height", label_descr="") for label_size in labels_to_include: s = label_type_specs[label_size] if s['kind'] in (DIE_CUT_LABEL, ROUND_DIE_CUT_LABEL): dp_fmt = "{0:4d} x {1:4d}" elif s['kind'] == ENDLESS_LABEL: dp_fmt = "{0:4d}" else: dp_fmt = " - unknown - " dots_printable = dp_fmt.format(*s['dots_printable']) label_descr = s['name'] output += fmt.format(label_size=label_size, dots_printable=dots_printable, label_descr=label_descr) return output def log_discovered_devices(available_devices, level=logging.INFO): for ad in available_devices: result = {'model': 'unknown'} result.update(ad) logger.log(level, " Found a label printer: {identifier} (model: {model})".format(**result)) def textual_description_discovered_devices(available_devices): output = "" for ad in available_devices: output += ad['identifier'] return output pklaus-brother_ql-3380c8c/brother_ql/raster.py000066400000000000000000000173361341650246200215350ustar00rootroot00000000000000 from builtins import bytes import struct import logging import packbits from PIL import Image import io from .devicedependent import models, \ min_max_feed, \ min_max_length_dots, \ number_bytes_per_row, \ right_margin_addition, \ compressionsupport, \ cuttingsupport, \ expandedmode, \ two_color_support, \ modesetting from . import BrotherQLError, BrotherQLUnsupportedCmd, BrotherQLUnknownModel, BrotherQLRasterError try: from io import BytesIO except: # Py2 from cStringIO import StringIO as BytesIO logger = logging.getLogger(__name__) class BrotherQLRaster(object): def __init__(self, model='QL-500'): if model not in models: raise BrotherQLUnknownModel() self.model = model self.data = b'' self._pquality = True self.page_number = 0 self.cut_at_end = True self.dpi_600 = False self.two_color_printing = False self._compression = False self.exception_on_warning = False def _warn(self, problem, kind=BrotherQLRasterError): """ Logs the warning message `problem` or raises a `BrotherQLRasterError` exception (changeable via `kind`) if `self.exception_on_warning` is set to True. :raises BrotherQLRasterError: Or other exception \ set via the `kind` keyword argument. """ if self.exception_on_warning: raise kind(problem) else: logger.warning(problem) def unsupported(self, problem): """ Raises BrotherQLUnsupportedCmd if exception_on_warning is set to True. Issues a logger warning otherwise. :raises BrotherQLUnsupportedCmd: """ self._warn(problem, kind=BrotherQLUnsupportedCmd) @property def two_color_support(self): return self.model in two_color_support def add_initialize(self): self.page_number = 0 self.data += b'\x1B\x40' # ESC @ def add_status_information(self): """ Status Information Request """ self.data += b'\x1B\x69\x53' # ESC i S def add_switch_mode(self): """ Switch dynamic command mode Switch to the raster mode on the printers that support the mode change (others are in raster mode already). """ if self.model not in modesetting: self.unsupported("Trying to switch the operating mode on a printer that doesn't support the command.") return self.data += b'\x1B\x69\x61\x01' # ESC i a def add_invalidate(self): """ clear command buffer """ self.data += b'\x00' * 200 @property def mtype(self): return self._mtype @property def mwidth(self): return self._mwidth @property def mlength(self): return self._mlength @property def pquality(self): return self._pquality @mtype.setter def mtype(self, value): self._mtype = bytes([value & 0xFF]) @mwidth.setter def mwidth(self, value): self._mwidth = bytes([value & 0xFF]) @mlength.setter def mlength(self, value): self._mlength = bytes([value & 0xFF]) @pquality.setter def pquality(self, value): self._pquality = bool(value) def add_media_and_quality(self, rnumber): self.data += b'\x1B\x69\x7A' # ESC i z valid_flags = 0x80 valid_flags |= (self._mtype is not None) << 1 valid_flags |= (self._mwidth is not None) << 2 valid_flags |= (self._mlength is not None) << 3 valid_flags |= self._pquality << 6 self.data += bytes([valid_flags]) vals = [self._mtype, self._mwidth, self._mlength] self.data += b''.join(b'\x00' if val is None else val for val in vals) self.data += struct.pack(' found! (payload: 8E 0A 3E 00 D2 00 00 00 00 00) def add_autocut(self, autocut = False): if self.model not in cuttingsupport: self.unsupported("Trying to call add_autocut with a printer that doesn't support it") return self.data += b'\x1B\x69\x4D' # ESC i M self.data += bytes([autocut << 6]) def add_cut_every(self, n=1): if self.model not in cuttingsupport: self.unsupported("Trying to call add_cut_every with a printer that doesn't support it") return self.data += b'\x1B\x69\x41' # ESC i A self.data += bytes([n & 0xFF]) def add_expanded_mode(self): if self.model not in expandedmode: self.unsupported("Trying to set expanded mode (dpi/cutting at end) on a printer that doesn't support it") return if self.two_color_printing and not self.two_color_support: self.unsupported("Trying to set two_color_printing in expanded mode on a printer that doesn't support it.") return self.data += b'\x1B\x69\x4B' # ESC i K flags = 0x00 flags |= self.cut_at_end << 3 flags |= self.dpi_600 << 6 flags |= self.two_color_printing << 0 self.data += bytes([flags]) def add_margins(self, dots=0x23): self.data += b'\x1B\x69\x64' # ESC i d self.data += struct.pack(' 0: num_bytes += opcode_def[1] if 'raster' in opcode_def[0]: num_bytes += data[2] + 2 #payload = data[len(opcode):num_bytes] instructions.append(data[:num_bytes]) data = data[num_bytes:] return instructions def match_opcode(data): matching_opcodes = [opcode for opcode in OPCODES.keys() if data.startswith(opcode)] assert len(matching_opcodes) == 1 return matching_opcodes[0] def interpret_response(data): data = bytes(data) if len(data) < 32: raise NameError('Insufficient amount of data received', hex_format(data)) if not data.startswith(b'\x80\x20\x42'): raise NameError("Printer response doesn't start with the usual header (80:20:42)", hex_format(data)) for i, byte_name in enumerate(RESP_BYTE_NAMES): logger.debug('Byte %2d %24s %02X', i, byte_name+':', data[i]) errors = [] error_info_1 = data[8] error_info_2 = data[9] for error_bit in RESP_ERROR_INFORMATION_1_DEF: if error_info_1 & (1 << error_bit): logger.error('Error: ' + RESP_ERROR_INFORMATION_1_DEF[error_bit]) errors.append(RESP_ERROR_INFORMATION_1_DEF[error_bit]) for error_bit in RESP_ERROR_INFORMATION_2_DEF: if error_info_2 & (1 << error_bit): logger.error('Error: ' + RESP_ERROR_INFORMATION_2_DEF[error_bit]) errors.append(RESP_ERROR_INFORMATION_2_DEF[error_bit]) media_width = data[10] media_length = data[17] media_type = data[11] if media_type in RESP_MEDIA_TYPES: media_type = RESP_MEDIA_TYPES[media_type] logger.debug("Media type: %s", media_type) else: logger.error("Unknown media type %02X", media_type) status_type = data[18] if status_type in RESP_STATUS_TYPES: status_type = RESP_STATUS_TYPES[status_type] logger.debug("Status type: %s", status_type) else: logger.error("Unknown status type %02X", status_type) phase_type = data[19] if phase_type in RESP_PHASE_TYPES: phase_type = RESP_PHASE_TYPES[phase_type] logger.debug("Phase type: %s", phase_type) else: logger.error("Unknown phase type %02X", phase_type) response = { 'status_type': status_type, 'phase_type': phase_type, 'media_type': media_type, 'media_width': media_width, 'media_length': media_length, 'errors': errors, } return response def merge_specific_instructions(chunks, join_preamble=True, join_raster=True): """ Process a list of instructions by merging subsequent instuctions with identical opcodes into "large instructions". """ new_instructions = [] last_opcode = None instruction_buffer = b'' for instruction in chunks: opcode = match_opcode(instruction) if join_preamble and OPCODES[opcode][0] == 'preamble' and last_opcode == 'preamble': instruction_buffer += instruction elif join_raster and 'raster' in OPCODES[opcode][0] and 'raster' in last_opcode: instruction_buffer += instruction else: if instruction_buffer: new_instructions.append(instruction_buffer) instruction_buffer = instruction last_opcode = OPCODES[opcode][0] if instruction_buffer: new_instructions.append(instruction_buffer) return new_instructions class BrotherQLReader(object): DEFAULT_FILENAME_FMT = 'label{counter:04d}.png' def __init__(self, brother_file): if type(brother_file) in (str,): brother_file = io.open(brother_file, 'rb') self.brother_file = brother_file self.mwidth, self.mheight = None, None self.raster_no = None self.black_rows = [] self.red_rows = [] self.compression = False self.page_counter = 1 self.two_color_printing = False self.cut_at_end = False self.high_resolution_printing = False self.filename_fmt = self.DEFAULT_FILENAME_FMT def analyse(self): instructions = self.brother_file.read() for instruction in chunker(instructions): for opcode in OPCODES.keys(): if instruction.startswith(opcode): opcode_def = OPCODES[opcode] if opcode_def[0] == 'init': self.mwidth, self.mheight = None, None self.raster_no = None self.black_rows = [] self.red_rows = [] payload = instruction[len(opcode):] logger.info(" {} ({}) --> found! (payload: {})".format(opcode_def[0], hex_format(opcode), hex_format(payload))) if opcode_def[0] == 'compression': self.compression = payload[0] == 0x02 if 'raster' in opcode_def[0]: rpl = bytes(payload[2:]) # raster payload if self.compression: row = bytes() index = 0 while True: num = rpl[index] if num & 0x80: num = num - 0x100 if num < 0: num = -num + 1 row += bytes([rpl[index+1]] * num) index += 2 else: num = num + 1 row += rpl[index+1:index+1+num] index += 1 + num if index >= len(rpl): break else: row = rpl if opcode_def[0] == 'raster': self.black_rows.append(row) else: # 2-color if payload[0] == 0x01: self.black_rows.append(row) elif payload[0] == 0x02: self.red_rows.append(row) else: raise NotImplementedError("color: 0x%x" % payload[0]) if opcode_def[0] == 'expanded': self.two_color_printing = bool(payload[0] & (1 << 0)) self.cut_at_end = bool(payload[0] & (1 << 3)) self.high_resolution_printing = bool(payload[0] & (1 << 6)) if opcode_def[0] == 'media/quality': self.raster_no = struct.unpack('=3.3.0", "pyusb", 'attrs', 'typing;python_version<"3.5"', 'enum34;python_version<"3.4"', ], extras_require = { #'brother_ql_analyse': ["matplotlib",], #'brother_ql_create' : ["matplotlib",], }, keywords = 'Brother QL-500 QL-550 QL-560 QL-570 QL-700 QL-710W QL-720NW QL-800 QL-810W QL-820NWB QL-1050 QL-1060N', classifiers = [ 'Development Status :: 4 - Beta', 'Operating System :: OS Independent', 'License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+)', 'Programming Language :: Python', 'Programming Language :: Python :: 3', 'Topic :: Scientific/Engineering :: Visualization', 'Topic :: System :: Hardware :: Hardware Drivers', ] )