├── .gitignore ├── LICENSE ├── README.md ├── dist ├── peripage-1.2.tar.gz ├── ppa6-0.1.tar.gz ├── ppa6-0.2.tar.gz ├── ppa6-0.3.tar.gz └── ppa6-0.4.tar.gz ├── honk.png ├── notebooks ├── Test-notebook.ipynb └── ppa6-tutorial.ipynb ├── peripage.py ├── peripage ├── __init__.py └── __main__.py ├── print-server ├── README.md ├── __main__.py ├── print_service.py └── scripts │ ├── print_ascii_clipboard.bat │ ├── print_ascii_clipboard.py │ ├── print_image_clipboard.bat │ ├── print_image_clipboard.py │ ├── print_image_drag_and_drop.bat │ └── print_image_drag_and_drop.py ├── print_service.py ├── requirements.txt ├── setup.cfg └── setup.py /.gitignore: -------------------------------------------------------------------------------- 1 | *__pycache__* -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # peripage-python 2 | ### Python module for printing on Peripage printers 3 | 4 | **This project is a continued development of the [original project](https://github.com/eliasweingaertner/peripage-A6-bluetooth) made by [Elias Weingärtner](https://github.com/eliasweingaertner). This module combined all results of reverse engineering of the Peripage A6/A6+ protocol in a python utility providing interface and CLI tool for printing on this thermal printer.** 5 | 6 | ## [The original introduction](https://github.com/eliasweingaertner/peripage-A6-bluetooth#introduction) 7 | 8 | The Peripage A6 F622 is an inexpensive portable thermal printer. It provides both Bluetooth and USB connectivity. Unlike most other thermo printers it **does not** seem to support ESC/POS or any other standardized printer control language. 9 | 10 | So far, the Peripage A6 F622 can be only controlled using a proprietary app (iOS / Anndroid). There is also a driver for Windows with many limitations, most notably the need of defining a page size before printing; this is a huge limitation, as the Peripage prints on continuous form paper. 11 | 12 | The script provided here was built based on an analysis of captured Bluetooth traffic between the printer and an Android device. The Peripage A6 uses the serial profile (BTSPP) and RFCOMM. 13 | 14 | Essentially, the script takes an input images, scales it to the printers native X resolution of 384 pixels, and then sends it to the printer. 15 | 16 | ## Deprecation Warning 17 | 18 | **The latest version ot `ppa6-python` module is deprecated due the major update with new models support and better module naming** 19 | 20 | ## Denial of responsibility 21 | 22 | The author and people associated with him are not responsible for the inoperability, breakdown, disruption and failure of software and hardware, as well as loss and damage to physical and software property as a result of the use of this software and related projects. Everything you do is at your own risk and responsibility. 23 | 24 | ## Features 25 | 26 | * Printing text of any length encoded in ASCII 27 | * Printing Images using PIL library 28 | * Printing Images row-by row using binary row representation 29 | * Printing page breaks using paper feed 30 | * Printing using generator/iterator that return bytes for each row, chunks of bytes for each row, images 31 | * Requesting printer details (Serial Number, Name, Battery Level, Hardware Info and an option the meaning of which i don't know) 32 | * Configuring print concentration (temperature) 33 | * Changing printer serial number 34 | * Configuring printer poweroff timeout 35 | * Supported printers: 36 | * Peripage A6 37 | * Peripage A6+ 38 | * Peripage A40 39 | * Peripage A40+ 40 | 41 | ## Prerequisites 42 | 43 | * Peripage A6/A6+/A40/A40+/e.t.c printer 44 | * Python 3 45 | 46 | ## Installation 47 | 48 | **Install from git clone** 49 | 50 | ``` 51 | pip install -r requirements.txt 52 | pip install . --user 53 | ``` 54 | 55 | **Install from pypi using pip** 56 | 57 | ``` 58 | pip install peripage 59 | ``` 60 | 61 | ## Dependencies 62 | 63 | * `PyBluez>=0.30` 64 | * `Pillow>=8.1.2` 65 | * `argparse>=1.1` 66 | 67 | Install dependencies with 68 | `pip install -r requirements.txt` 69 | 70 | ## Identify printer Bluetooth MAC address 71 | 72 | **On linux:** 73 | 74 | ``` 75 | user@name:~$ hcitool scan 76 | Scanning .. 77 | 00:15:83:15:bc:5f PeriPage+BC5F 78 | ``` 79 | 80 | **On windows:** 81 | 82 | You may use [BluetoothCL](https://www.nirsoft.net/utils/bluetoothcl.html) 83 | 84 | ``` 85 | PS E:\E\E> .\BluetoothCL.exe 86 | BluetoothCL v1.07 87 | Copyright (c) 2009 - 2014 Nir Sofer 88 | Web Site: http://www.nirsoft.net 89 | 90 | syntax: 91 | BluetoothCL -timeout [seconds] 92 | 93 | -timeout is optional parameter. The default value is 15 seconds. 94 | 95 | 96 | Scanning bluetooth devices... please wait. 97 | 98 | 00:15:83:15:bc:5f Imaging PeriPage+BC5F 99 | ``` 100 | 101 | ## Troubleshooting 102 | 103 | > Windows installation requires installing PyBluez from master branch as pypi module is not updated 104 | 105 | ``` 106 | pip install git+https://github.com/pybluez/pybluez@master#egg=pybluez --user 107 | ``` 108 | 109 | > Raspberry PI installation requires additional libraries 110 | 111 | ``` 112 | sudo apt install libbluetooth-dev libopenjp2-7 libtiff5 113 | ``` 114 | 115 | > Some cases may require restarting bluetooth adapter 116 | 117 | ``` 118 | sudo systemctl restart bluetooth 119 | sudo hciconfig hci0 reset 120 | ``` 121 | 122 | ## CLI usage 123 | 124 | **On linux** 125 | 126 | Install module and run 127 | `peripage ` 128 | 129 | **On windows** 130 | 131 | Install module and run 132 | `python -m peripage ` 133 | 134 | ### Options 135 | 136 | ``` 137 | $ python -m peripage -h 138 | usage: __main__.py [-h] -m MAC [-c [0-2]] [-b [0-255]] -p {A6,A6p,A40,A40p} (-t TEXT | -s | -i IMAGE | -q QR | -e) 139 | 140 | Print on a Peripage printer via bluetooth 141 | 142 | optional arguments: 143 | -h, --help show this help message and exit 144 | -m MAC, --mac MAC Bluetooth MAC address of the printer 145 | -c [0-2], --concentration [0-2] 146 | Concentration value for printing (temperature) 147 | -b [0-255], --break [0-255] 148 | Size of the break inserted after printed image or text 149 | -p {A6,A6p,A40,A40p}, --printer {A6,A6p,A40,A40p} 150 | Printer model selection 151 | -t TEXT, --text TEXT ASCII text to print. Text must be ASCII-safe and will be filtered for invalid characters 152 | -s, --stream Print text received from STDIN, line by line. Text must be ASCII-safe and will be filtered for invalid characters 153 | -i IMAGE, --image IMAGE 154 | Path to the image for printing 155 | -q QR, --qr QR String to convert into a QR code for printing 156 | -e, --introduce Ask the printer to introduce itself 157 | ``` 158 | 159 | ### Print image example 160 | 161 | **Print image from [file](https://github.com/bitrate16/peripage-python/blob/main/honk.png) with following break for 100px and concentration set to 2 (HIGH) on A6+** 162 | ``` 163 | peripage -m 00:15:83:15:bc:5f -p A6p -b 100 -c 2 -i honk.png 164 | ``` 165 | 166 | ### Print text example 167 | 168 | **Print some random text followed by newline and break for 100px on A6+** 169 | ``` 170 | peripage -m 00:15:83:15:bc:5f -p A6p -b 100 -t "HONK" -n 171 | ``` 172 | Newline is required to fush the internal printer buffer and force it to print all text without cutting 173 | 174 | ## Print Service 175 | 176 | **Print 50 text tasks on A6+** 177 | ```python 178 | import peripage 179 | import print_service 180 | 181 | # Ping battery every 60 seconds 182 | # Send task every 5 seconds 183 | # Try to reconnect after waiting 5 seconds 184 | # Wait 1 second before send after connecting/reconnecting to printer 185 | # Print only after pinging printer and waiting for 1 second 186 | service = print_service.PrintService(60, 5, 5, 1, 1) 187 | service.start('00:15:83:15:bc:5f', peripage.PrinterType.A6p) 188 | for i in range(50): 189 | service.add_print_ascii(f'number {i}', flush=True) 190 | ``` 191 | Newline is required to fush the internal printer buffer and force it to print all text without cutting 192 | 193 | ## Recommendations 194 | 195 | * Don't forget about concentration, this can make print brighter and better visible. 196 | * Split long images into multiple print requests with cooldown time for printer (printer may overheat during a long print and will stop printing for a while. This will result in partial print loss because the internal buffer is about 250px height). For example, when you print [looooooooooooooooooooooooooooooongcat.jpg](http://lurkmore.so/images/9/91/Loooooooooooooooooooooooooooooooooooooooooongcat.JPG), split it into at least 20 pieces with 1-2 minutes delay because you will definetly loose something without cooling. Printer gets hot very fast. Yes, it was the first that i've printed. 197 | * Be carefull when printing lots of black or using max concentration, as i said, printer heats up very fast. 198 | * The picture printed at maximum concentration has the longest shelf life. 199 | * Turn printer off then long press the power button till it becomes orange. Release the button and look at the another useless feature. 200 | * Be aware of cats, they have paws 🐾 201 | 202 | ## Code example 203 | 204 | View this [python notebook](https://github.com/bitrate16/peripage-python/blob/main/notebooks/peripage-tutorial.ipynb) for tutorial 205 | 206 | View this [python notebook](https://github.com/bitrate16/peripage-python/blob/main/notebooks/Test-notebook.ipynb) for test 207 | 208 | ## Printer disassembly 209 | 210 | [Disassembly for A6+](https://imgur.com/a/6LLwuaD) 211 | 212 | ## TODO 213 | 214 | * Fix page sometimes get cutted off for some rows 215 | * Fix delays 216 | * ~~Python 2.7 support~~ (Don't need) 217 | * Implement overheat protection 218 | * Implement cover open handler 219 | * Tweak wait timings to precisely match printing speed 220 | * Implement printer renaming 221 | * Implement printing stop operation 222 | * Reverse-engineer USB driver and add support for it 223 | * Print randomly gets cropped (some images getting cropped) 224 | * 1 type conversion is low quality 225 | 226 | ## Contribution 227 | 228 | > Q: How to contribute? 229 | > 230 | > A: Implement some features and make a pull request in this repo. For example, you could add info about USB communication, write a any-font printing using PIL text drawing, make an additional research in protocol and other cool things. 231 | 232 | > Q: How to get my printer supported? 233 | > 234 | > A: If you own a peripage printer that is currently unsupported, you can reverse-engineer the bluetooth packets captured from the oficial printing app and find out the specs of your printer (the main and the only spec is bytes per row). Another way is to find how many letters can fit in a row when using `printASCII()`. 235 | > 236 | > If you would like to participate, please make an issue and I will guide you on how to obtain required parameters. 237 | 238 | ## Credits 239 | 240 | * [Elias Weingärtner](https://github.com/eliasweingaertner) for initial work in reverse-engineering bluetooth protocol 241 | * [bitrate16](https://github.com/bitrate16) for additional research and python module 242 | * [henryleonard](https://github.com/henryleonard) for specs of A40 printer 243 | * [anthony-foulfoin](https://github.com/anthony-foulfoin) for specs of A40+ printer 244 | 245 | ## License 246 | 247 | [GPLv3 License](https://github.com/bitrate16/peripage-python/blob/main/LICENSE) 248 | -------------------------------------------------------------------------------- /dist/peripage-1.2.tar.gz: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bitrate16/peripage-python/8d255ea3cc85b9cb94394a556ef5875fadbd329c/dist/peripage-1.2.tar.gz -------------------------------------------------------------------------------- /dist/ppa6-0.1.tar.gz: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bitrate16/peripage-python/8d255ea3cc85b9cb94394a556ef5875fadbd329c/dist/ppa6-0.1.tar.gz -------------------------------------------------------------------------------- /dist/ppa6-0.2.tar.gz: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bitrate16/peripage-python/8d255ea3cc85b9cb94394a556ef5875fadbd329c/dist/ppa6-0.2.tar.gz -------------------------------------------------------------------------------- /dist/ppa6-0.3.tar.gz: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bitrate16/peripage-python/8d255ea3cc85b9cb94394a556ef5875fadbd329c/dist/ppa6-0.3.tar.gz -------------------------------------------------------------------------------- /dist/ppa6-0.4.tar.gz: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bitrate16/peripage-python/8d255ea3cc85b9cb94394a556ef5875fadbd329c/dist/ppa6-0.4.tar.gz -------------------------------------------------------------------------------- /honk.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bitrate16/peripage-python/8d255ea3cc85b9cb94394a556ef5875fadbd329c/honk.png -------------------------------------------------------------------------------- /notebooks/Test-notebook.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "code", 5 | "execution_count": 1, 6 | "metadata": {}, 7 | "outputs": [], 8 | "source": [ 9 | "import peripage\n", 10 | "\n", 11 | "printer = peripage.Printer(\n", 12 | " mac='00:15:83:15:BC:5F',\n", 13 | " printer_type=peripage.PrinterType.A6p\n", 14 | ")\n", 15 | "printer.connect()\n" 16 | ] 17 | }, 18 | { 19 | "cell_type": "code", 20 | "execution_count": 2, 21 | "metadata": {}, 22 | "outputs": [], 23 | "source": [ 24 | "printer.disconnect()\n" 25 | ] 26 | }, 27 | { 28 | "cell_type": "code", 29 | "execution_count": 3, 30 | "metadata": {}, 31 | "outputs": [], 32 | "source": [ 33 | "printer.reconnect()\n" 34 | ] 35 | }, 36 | { 37 | "cell_type": "code", 38 | "execution_count": 4, 39 | "metadata": {}, 40 | "outputs": [], 41 | "source": [ 42 | "printer.reset()\n" 43 | ] 44 | }, 45 | { 46 | "cell_type": "code", 47 | "execution_count": 5, 48 | "metadata": {}, 49 | "outputs": [ 50 | { 51 | "name": "stdout", 52 | "output_type": "stream", 53 | "text": [ 54 | "b'IP-300'\n", 55 | "b'PeriPage+BC5F'\n", 56 | "b'A6491571121'\n", 57 | "b'V2.11_304dpi'\n", 58 | "93\n", 59 | "b'BR2141e-s(A02)_B9_20190815_r3460'\n", 60 | "b'\\x00\\x15\\x83\\x15\\xbc_\\xc0\\x15\\x83\\x15\\xbc_'\n", 61 | "b'PeriPage+BC5F|00:15:83:15:BC:5F|C0:15:83:15:BC:5F|V2.11_304dpi|A6491571121|93'\n" 62 | ] 63 | } 64 | ], 65 | "source": [ 66 | "print(printer.getDeviceIP())\n", 67 | "print(printer.getDeviceName())\n", 68 | "print(printer.getDeviceSerialNumber())\n", 69 | "print(printer.getDeviceFirmware())\n", 70 | "print(printer.getDeviceBattery())\n", 71 | "print(printer.getDeviceHardware())\n", 72 | "print(printer.getDeviceMAC())\n", 73 | "print(printer.getDeviceFull())\n" 74 | ] 75 | }, 76 | { 77 | "cell_type": "code", 78 | "execution_count": 6, 79 | "metadata": {}, 80 | "outputs": [ 81 | { 82 | "name": "stdout", 83 | "output_type": "stream", 84 | "text": [ 85 | "b'A6491571121'\n", 86 | "b'abobus'\n", 87 | "b'A6491571121'\n" 88 | ] 89 | } 90 | ], 91 | "source": [ 92 | "print(printer.getDeviceSerialNumber())\n", 93 | "printer.reset()\n", 94 | "printer.setDeviceSerialNumber('abobus')\n", 95 | "print(printer.getDeviceSerialNumber())\n", 96 | "printer.reset()\n", 97 | "printer.setDeviceSerialNumber('A6491571121')\n", 98 | "print(printer.getDeviceSerialNumber())\n" 99 | ] 100 | }, 101 | { 102 | "cell_type": "code", 103 | "execution_count": 7, 104 | "metadata": {}, 105 | "outputs": [ 106 | { 107 | "data": { 108 | "text/plain": [ 109 | "b'OK'" 110 | ] 111 | }, 112 | "execution_count": 7, 113 | "metadata": {}, 114 | "output_type": "execute_result" 115 | } 116 | ], 117 | "source": [ 118 | "printer.setPowerTimeout(1)\n", 119 | "# Will power off in one minute\n" 120 | ] 121 | }, 122 | { 123 | "cell_type": "code", 124 | "execution_count": 10, 125 | "metadata": {}, 126 | "outputs": [ 127 | { 128 | "data": { 129 | "text/plain": [ 130 | "b'OK'" 131 | ] 132 | }, 133 | "execution_count": 10, 134 | "metadata": {}, 135 | "output_type": "execute_result" 136 | } 137 | ], 138 | "source": [ 139 | "printer.setPowerTimeout(60)\n" 140 | ] 141 | }, 142 | { 143 | "cell_type": "code", 144 | "execution_count": 11, 145 | "metadata": {}, 146 | "outputs": [], 147 | "source": [ 148 | "printer.printBreak(100)\n", 149 | "# Should output a break of 100px\n" 150 | ] 151 | }, 152 | { 153 | "cell_type": "code", 154 | "execution_count": 13, 155 | "metadata": {}, 156 | "outputs": [ 157 | { 158 | "data": { 159 | "text/plain": [ 160 | "''" 161 | ] 162 | }, 163 | "execution_count": 13, 164 | "metadata": {}, 165 | "output_type": "execute_result" 166 | } 167 | ], 168 | "source": [ 169 | "printer.print_buffer = ''\n", 170 | "printer.printASCII('a' * printer.getRowCharacters())\n", 171 | "printer.print_buffer\n", 172 | "# Shoud print out a full line\n" 173 | ] 174 | }, 175 | { 176 | "cell_type": "code", 177 | "execution_count": 14, 178 | "metadata": {}, 179 | "outputs": [ 180 | { 181 | "data": { 182 | "text/plain": [ 183 | "'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'" 184 | ] 185 | }, 186 | "execution_count": 14, 187 | "metadata": {}, 188 | "output_type": "execute_result" 189 | } 190 | ], 191 | "source": [ 192 | "printer.printASCII('a' * (printer.getRowCharacters() - 1))\n", 193 | "printer.print_buffer\n", 194 | "# Shoud not print\n" 195 | ] 196 | }, 197 | { 198 | "cell_type": "code", 199 | "execution_count": 12, 200 | "metadata": {}, 201 | "outputs": [ 202 | { 203 | "data": { 204 | "text/plain": [ 205 | "''" 206 | ] 207 | }, 208 | "execution_count": 12, 209 | "metadata": {}, 210 | "output_type": "execute_result" 211 | } 212 | ], 213 | "source": [ 214 | "printer.print_buffer = 'a' * (printer.getRowCharacters() - 1)\n", 215 | "printer.printASCII('\\n')\n", 216 | "printer.print_buffer\n", 217 | "# Shoud flush the above data\n" 218 | ] 219 | }, 220 | { 221 | "cell_type": "code", 222 | "execution_count": 14, 223 | "metadata": {}, 224 | "outputs": [ 225 | { 226 | "data": { 227 | "text/plain": [ 228 | "''" 229 | ] 230 | }, 231 | "execution_count": 14, 232 | "metadata": {}, 233 | "output_type": "execute_result" 234 | } 235 | ], 236 | "source": [ 237 | "printer.print_buffer = ''\n", 238 | "printer.printASCII(('a' * printer.getRowCharacters()) + ('a' * (printer.getRowCharacters() - 1)) + '\\n')\n", 239 | "printer.print_buffer\n", 240 | "# Shoud print two lines (one incomplete)\n" 241 | ] 242 | }, 243 | { 244 | "cell_type": "code", 245 | "execution_count": 18, 246 | "metadata": {}, 247 | "outputs": [ 248 | { 249 | "data": { 250 | "text/plain": [ 251 | "'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'" 252 | ] 253 | }, 254 | "execution_count": 18, 255 | "metadata": {}, 256 | "output_type": "execute_result" 257 | } 258 | ], 259 | "source": [ 260 | "printer.print_buffer = ''\n", 261 | "printer.printASCII(('a' * printer.getRowCharacters()) + ('a' * (printer.getRowCharacters() - 1)))\n", 262 | "printer.print_buffer\n", 263 | "# Shoud print one line\n" 264 | ] 265 | }, 266 | { 267 | "cell_type": "code", 268 | "execution_count": 19, 269 | "metadata": {}, 270 | "outputs": [ 271 | { 272 | "data": { 273 | "text/plain": [ 274 | "''" 275 | ] 276 | }, 277 | "execution_count": 19, 278 | "metadata": {}, 279 | "output_type": "execute_result" 280 | } 281 | ], 282 | "source": [ 283 | "printer.print_buffer = ''\n", 284 | "printer.printASCII('\\n\\n')\n", 285 | "printer.print_buffer\n", 286 | "# Shoud print two newlines\n" 287 | ] 288 | }, 289 | { 290 | "cell_type": "code", 291 | "execution_count": 31, 292 | "metadata": {}, 293 | "outputs": [], 294 | "source": [ 295 | "for i in range(10):\n", 296 | " printer.printRow(bytes.fromhex('55' * printer.getRowBytes()))\n", 297 | "# Shoud write a single black-white row with pattern 01010101\n", 298 | "\n", 299 | "for i in range(10):\n", 300 | " printer.printRow(bytes.fromhex('aa' * printer.getRowBytes()))\n", 301 | "# Shoud write a single black-white row with pattern 10101010 (inverse)\n" 302 | ] 303 | }, 304 | { 305 | "cell_type": "code", 306 | "execution_count": 33, 307 | "metadata": {}, 308 | "outputs": [], 309 | "source": [ 310 | "chunk = [ bytes.fromhex('55' * printer.getRowBytes()), bytes.fromhex('aa' * printer.getRowBytes()) ] * 20\n", 311 | "printer.printRowBytesIterator(chunk)\n", 312 | "# Should write grid using iterator (very slow)\n" 313 | ] 314 | }, 315 | { 316 | "cell_type": "code", 317 | "execution_count": 34, 318 | "metadata": {}, 319 | "outputs": [], 320 | "source": [ 321 | "half_0 = '00' * (printer.getRowBytes() // 2)\n", 322 | "half_1 = 'ff' * (printer.getRowBytes() // 2)\n", 323 | "\n", 324 | "half_left = bytes.fromhex(half_1 + half_0)\n", 325 | "half_right = bytes.fromhex(half_0 + half_1)\n", 326 | "\n", 327 | "chunk = [ half_left ] * 20 + [ half_right ] * 20\n", 328 | "chunk += chunk\n", 329 | "\n", 330 | "printer.printRowBytesIterator(chunk)\n", 331 | "# Should output a half-black followed by inverse half black using iterator (very slow)\n" 332 | ] 333 | }, 334 | { 335 | "cell_type": "code", 336 | "execution_count": 5, 337 | "metadata": {}, 338 | "outputs": [], 339 | "source": [ 340 | "chunk = [ bytes.fromhex('55' * printer.getRowBytes()), bytes.fromhex('aa' * printer.getRowBytes()) ] * 20\n", 341 | "printer.printRowBytesList(chunk)\n", 342 | "# Should write grid using list\n" 343 | ] 344 | }, 345 | { 346 | "cell_type": "code", 347 | "execution_count": 7, 348 | "metadata": {}, 349 | "outputs": [], 350 | "source": [ 351 | "half_0 = '00' * (printer.getRowBytes() // 2)\n", 352 | "half_1 = 'ff' * (printer.getRowBytes() // 2)\n", 353 | "\n", 354 | "half_left = bytes.fromhex(half_1 + half_0)\n", 355 | "half_right = bytes.fromhex(half_0 + half_1)\n", 356 | "\n", 357 | "chunk = [ half_left ] * 20 + [ half_right ] * 20\n", 358 | "chunk += chunk\n", 359 | "\n", 360 | "printer.printRowBytesList(chunk)\n", 361 | "# Should output a half-black followed by inverse half black using list\n" 362 | ] 363 | }, 364 | { 365 | "cell_type": "code", 366 | "execution_count": 8, 367 | "metadata": {}, 368 | "outputs": [], 369 | "source": [ 370 | "half_0 = '00' * (printer.getRowBytes() // 2)\n", 371 | "half_1 = 'ff' * (printer.getRowBytes() // 2)\n", 372 | "\n", 373 | "half_left = bytes.fromhex(half_1 + half_0)\n", 374 | "half_right = bytes.fromhex(half_0 + half_1)\n", 375 | "\n", 376 | "chunk = [ half_left ] * 20 + [ half_right ] * 20\n", 377 | "\n", 378 | "printer.printRowChunksIterator([ chunk, chunk ])\n", 379 | "# Should output a half-black followed by inverse half black using chunk iterator\n" 380 | ] 381 | }, 382 | { 383 | "cell_type": "code", 384 | "execution_count": 9, 385 | "metadata": {}, 386 | "outputs": [], 387 | "source": [ 388 | "import PIL.Image\n", 389 | "\n", 390 | "honk = PIL.Image.open('honk.png')\n", 391 | "\n", 392 | "printer.printImage(honk)\n", 393 | "# Should print a honk\n" 394 | ] 395 | }, 396 | { 397 | "cell_type": "code", 398 | "execution_count": 11, 399 | "metadata": {}, 400 | "outputs": [], 401 | "source": [ 402 | "import PIL.Image\n", 403 | "\n", 404 | "honk = PIL.Image.open('honk.png')\n", 405 | "\n", 406 | "pieces = [\n", 407 | " honk.crop((0, 0, honk.size[0], honk.size[1] // 2)),\n", 408 | " honk.crop((0, honk.size[1] // 2, honk.size[0], honk.size[1])),\n", 409 | "]\n", 410 | "\n", 411 | "printer.printImageIterator(reversed(pieces))\n", 412 | "# Should print a honk from two pieces using iterator, image is reversed for text\n" 413 | ] 414 | }, 415 | { 416 | "cell_type": "code", 417 | "execution_count": 12, 418 | "metadata": {}, 419 | "outputs": [], 420 | "source": [ 421 | "import PIL.Image\n", 422 | "\n", 423 | "honk = PIL.Image.open('honk.png')\n", 424 | "\n", 425 | "printer.setConcentration(0)\n", 426 | "printer.printImage(honk)\n", 427 | "\n", 428 | "printer.setConcentration(1)\n", 429 | "printer.printImage(honk)\n", 430 | "\n", 431 | "printer.setConcentration(2)\n", 432 | "printer.printImage(honk)\n", 433 | "# Should print a honk 3 times with different concentration\n" 434 | ] 435 | }, 436 | { 437 | "cell_type": "code", 438 | "execution_count": 13, 439 | "metadata": {}, 440 | "outputs": [], 441 | "source": [ 442 | "printer.printQR('https://www.youtube.com/watch?v=dQw4w9WgXcQ')\n", 443 | "# Never gonna give you up\n" 444 | ] 445 | } 446 | ], 447 | "metadata": { 448 | "kernelspec": { 449 | "display_name": "Python 3", 450 | "language": "python", 451 | "name": "python3" 452 | }, 453 | "language_info": { 454 | "codemirror_mode": { 455 | "name": "ipython", 456 | "version": 3 457 | }, 458 | "file_extension": ".py", 459 | "mimetype": "text/x-python", 460 | "name": "python", 461 | "nbconvert_exporter": "python", 462 | "pygments_lexer": "ipython3", 463 | "version": "3.9.13" 464 | }, 465 | "orig_nbformat": 4 466 | }, 467 | "nbformat": 4, 468 | "nbformat_minor": 2 469 | } 470 | -------------------------------------------------------------------------------- /notebooks/ppa6-tutorial.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "attachments": {}, 5 | "cell_type": "markdown", 6 | "metadata": {}, 7 | "source": [ 8 | "# Connect to the printer" 9 | ] 10 | }, 11 | { 12 | "cell_type": "code", 13 | "execution_count": 1, 14 | "metadata": {}, 15 | "outputs": [], 16 | "source": [ 17 | "import peripage\n", 18 | "\n", 19 | "printer = peripage.Printer('00:15:83:15:bc:5f', peripage.PrinterType.A6p)\n", 20 | "printer.connect()\n", 21 | "printer.reset()" 22 | ] 23 | }, 24 | { 25 | "attachments": {}, 26 | "cell_type": "markdown", 27 | "metadata": {}, 28 | "source": [ 29 | "# Get information about printer" 30 | ] 31 | }, 32 | { 33 | "cell_type": "code", 34 | "execution_count": 2, 35 | "metadata": {}, 36 | "outputs": [ 37 | { 38 | "name": "stdout", 39 | "output_type": "stream", 40 | "text": [ 41 | "Name: b'PeriPage+BC5F'\n", 42 | "S/N: b'A6431928321'\n", 43 | "F/W: b'V2.11_304dpi'\n", 44 | "Battery: 38%\n", 45 | "H/W: b'BR2141e-s(A02)_B9_20190815_r3460'\n", 46 | "MAC: b'\\x00\\x15\\x83\\x15\\xbc_\\xc0\\x15\\x83\\x15\\xbc_'\n", 47 | "Full: b'PeriPage+BC5F|00:15:83:15:BC:5F|C0:15:83:15:BC:5F|V2.11_304dpi|A6431928321|38'\n" 48 | ] 49 | } 50 | ], 51 | "source": [ 52 | "print(f'Name: {printer.getDeviceName()}')\n", 53 | "print(f'S/N: {printer.getDeviceSerialNumber()}')\n", 54 | "print(f'F/W: {printer.getDeviceFirmware()}')\n", 55 | "print(f'Battery: {printer.getDeviceBattery()}%')\n", 56 | "print(f'H/W: {printer.getDeviceHardware()}')\n", 57 | "print(f'MAC: {printer.getDeviceMAC()}')\n", 58 | "print(f'Full: {printer.getDeviceFull()}')" 59 | ] 60 | }, 61 | { 62 | "attachments": {}, 63 | "cell_type": "markdown", 64 | "metadata": {}, 65 | "source": [ 66 | "# Sample print" 67 | ] 68 | }, 69 | { 70 | "cell_type": "code", 71 | "execution_count": null, 72 | "metadata": {}, 73 | "outputs": [], 74 | "source": [ 75 | "printer.writeASCII('Hello World?\\n')\n", 76 | "printer.printBreak(100)" 77 | ] 78 | }, 79 | { 80 | "attachments": {}, 81 | "cell_type": "markdown", 82 | "metadata": {}, 83 | "source": [ 84 | "# Print random image" 85 | ] 86 | }, 87 | { 88 | "cell_type": "code", 89 | "execution_count": null, 90 | "metadata": {}, 91 | "outputs": [], 92 | "source": [ 93 | "imarray = numpy.random.rand(printer.getRowWidth(),printer.getRowWidth(), 3) * 255\n", 94 | "im = Image.fromarray(imarray.astype('uint8')).convert('L')\n", 95 | "\n", 96 | "# Set print concentration\n", 97 | "printer.setConcentration(1)\n", 98 | "\n", 99 | "# Print image & break\n", 100 | "printer.printImage(im)\n", 101 | "printer.printBreak(100)" 102 | ] 103 | }, 104 | { 105 | "attachments": {}, 106 | "cell_type": "markdown", 107 | "metadata": {}, 108 | "source": [ 109 | "# Infinite print using generator" 110 | ] 111 | }, 112 | { 113 | "cell_type": "code", 114 | "execution_count": null, 115 | "metadata": {}, 116 | "outputs": [], 117 | "source": [ 118 | "# Ping-pong slider\n", 119 | "def slider():\n", 120 | " direct = True\n", 121 | " pos = 0\n", 122 | " while True:\n", 123 | " s = '00' * pos + 'ff' + '00' * (printer.getRowBytes() - pos - 1)\n", 124 | " if direct:\n", 125 | " pos = pos + 1\n", 126 | " if pos == printer.getRowBytes() - 1:\n", 127 | " direct = False\n", 128 | " else:\n", 129 | " pos = pos - 1\n", 130 | " if pos == 0:\n", 131 | " direct = True\n", 132 | " yield bytes.fromhex(s)\n", 133 | "\n", 134 | "# Infinite printing, slow\n", 135 | "printer.printRowBytesIterator(slider(), 0.25)" 136 | ] 137 | }, 138 | { 139 | "attachments": {}, 140 | "cell_type": "markdown", 141 | "metadata": {}, 142 | "source": [ 143 | "# Print using generator in limited page length" 144 | ] 145 | }, 146 | { 147 | "cell_type": "code", 148 | "execution_count": null, 149 | "metadata": {}, 150 | "outputs": [], 151 | "source": [ 152 | "# Ping-pong slider\n", 153 | "def slider():\n", 154 | " direct = True\n", 155 | " pos = 0\n", 156 | " while True:\n", 157 | " s = '00' * pos + 'ff' + '00' * (printer.getRowBytes() - pos - 1)\n", 158 | " if direct:\n", 159 | " pos = pos + 1\n", 160 | " if pos == printer.getRowBytes() - 1:\n", 161 | " direct = False\n", 162 | " else:\n", 163 | " pos = pos - 1\n", 164 | " if pos == 0:\n", 165 | " direct = True\n", 166 | " yield bytes.fromhex(s)\n", 167 | "\n", 168 | "# Print on page 200 px length\n", 169 | "printer.printRowBytesIteratorOfSize(slider(), 200, 0.01)\n", 170 | "printer.printBreak(100)" 171 | ] 172 | }, 173 | { 174 | "cell_type": "code", 175 | "execution_count": null, 176 | "metadata": {}, 177 | "outputs": [], 178 | "source": [ 179 | "import random\n", 180 | "\n", 181 | "# Random byte rows\n", 182 | "def rand():\n", 183 | " while True:\n", 184 | " s = ''.join([random.choice('0123456789abcdef') for n in range(printer.getRowWidth())])\n", 185 | " yield s\n", 186 | "\n", 187 | "# Print on page 200 px length\n", 188 | "printer.printRowBytesIteratorOfSize(rand(), 200, 0.01)\n", 189 | "printer.printBreak(100)" 190 | ] 191 | } 192 | ], 193 | "metadata": { 194 | "kernelspec": { 195 | "display_name": "Python 3", 196 | "language": "python", 197 | "name": "python3" 198 | }, 199 | "language_info": { 200 | "codemirror_mode": { 201 | "name": "ipython", 202 | "version": 3 203 | }, 204 | "file_extension": ".py", 205 | "mimetype": "text/x-python", 206 | "name": "python", 207 | "nbconvert_exporter": "python", 208 | "pygments_lexer": "ipython3", 209 | "version": "3.7.9" 210 | } 211 | }, 212 | "nbformat": 4, 213 | "nbformat_minor": 4 214 | } 215 | -------------------------------------------------------------------------------- /peripage.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | # MIT License 4 | # 5 | # Copyright (c) 2021 bitrate16 6 | 7 | from peripage.__main__ import main 8 | 9 | if __name__ == '__main__': 10 | main() 11 | -------------------------------------------------------------------------------- /peripage/__init__.py: -------------------------------------------------------------------------------- 1 | # peripage-python - python library for peripage thermal printers 2 | # Copyright (C) 2020-2023 bitrate16 (pegasko) 3 | # 4 | # This program is free software: you can redistribute it and/or modify 5 | # it under the terms of the GNU General Public License as published by 6 | # the Free Software Foundation, either version 3 of the License, or 7 | # (at your option) any later version. 8 | # 9 | # This program is distributed in the hope that it will be useful, 10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | # GNU General Public License for more details. 13 | # 14 | # You should have received a copy of the GNU General Public License 15 | # along with this program. If not, see . 16 | 17 | 18 | __title__ = 'Peripage buetooth printing utility' 19 | __version__ = '1.2' 20 | __author__ = 'bitrate16' 21 | __license__ = 'GPLv3' 22 | __copyright__ = 'Copyright (c) GPLv3 2021-2023 bitrate16 (pegasko)' 23 | 24 | 25 | import time 26 | import qrcode 27 | import typing 28 | import enum 29 | import bluetooth 30 | 31 | import PIL.Image 32 | import PIL.ImageOps 33 | 34 | 35 | class PrinterTypeSpecs: 36 | """ 37 | Specification parameters for each printer model. required for unifying the 38 | printing interface and easy adding new printe models. 39 | 40 | Defines: 41 | * `row_bytes` - bytes per row encoding 42 | * `row_width` - width of single row in pixels 43 | * `row_characters` - width of row in ASCII-mode characters 44 | """ 45 | 46 | def __init__(self, row_bytes: int, row_width: int, row_characters: int): 47 | self.row_bytes = row_bytes 48 | self.row_width = row_width 49 | self.row_characters = row_characters 50 | 51 | class PrinterType(enum.Enum): 52 | """ 53 | Defines names for supported printer types. 54 | Currently supported printers are: Peripage A6, A6+, A40, A40+ 55 | """ 56 | 57 | A6 = PrinterTypeSpecs( 58 | row_bytes=48, 59 | row_width=384, 60 | row_characters=32 61 | ) 62 | 63 | A6p = PrinterTypeSpecs( 64 | row_bytes=72, 65 | row_width=576, 66 | row_characters=48 67 | ) 68 | 69 | A40 = PrinterTypeSpecs( 70 | row_bytes=216, 71 | row_width=1728, 72 | row_characters=144 73 | ) 74 | 75 | A40p = PrinterTypeSpecs( 76 | row_bytes=231, 77 | row_width=1848, 78 | row_characters=154 79 | ) 80 | 81 | @classmethod 82 | def names(cls) -> typing.List[str]: 83 | """List available keys from Enum""" 84 | return [ e.name for e in cls ] 85 | 86 | def __new__(cls, *args, **kwds): 87 | value = len(cls.__members__) + 1 88 | obj = object.__new__(cls) 89 | obj._value_ = value 90 | return obj 91 | 92 | def __init__(self, spec: PrinterTypeSpecs): 93 | self.spec = spec 94 | 95 | class Printer: 96 | """ 97 | This class defines the Peripage interface utility. 98 | It contains methods wrapping requests with special control opcodes. 99 | By default instance of this class is constructed with timeout set 100 | to 1s and printer type A6. 101 | Currently there is no thermal overheat protection opcodes found, so 102 | use printing carefully and avoid overheating of the printer which 103 | may result in hardware break. 104 | Currently there is no stop codes found, so you can not stop printing. 105 | 106 | It is required to perform reset() after connection to the printer. 107 | """ 108 | 109 | @staticmethod 110 | def filter_ascii(text: str) -> str: 111 | """ 112 | Remove non-safe-ascii letters from the string so it can be safety used 113 | in most internal calls. 114 | """ 115 | 116 | return ''.join([ i for i in text if (31 < ord(i) or ord(i) == 10) and ord(i) < 127 ]) 117 | 118 | @staticmethod 119 | def is_safe_ascii(text: str) -> bool: 120 | """ 121 | Check is string does not contain non-safe-ascii letters (like `>0x7f` or `\\0`). 122 | """ 123 | 124 | for i in text: 125 | if (31 < ord(i) or ord(i) == 10) and ord(i) < 127: 126 | return False 127 | return True 128 | 129 | def __init__(self, mac: str, printer_type: PrinterType, timeout: float=1.0): 130 | """ 131 | Create instance of peripage connector. `mac` and `printer_type` are 132 | required for bluetooth connection and printer-specific printing 133 | parameters. 134 | 135 | In order to make printer operate normally, it is required to call 136 | `reset()` after connecting. 137 | 138 | Arguments: 139 | * `mac` - mac address of the printer 140 | * `printer_type` - printer type enum with specification 141 | * `timeout` - socket connection timeout in seconds 142 | """ 143 | 144 | self.mac = mac 145 | self.timeout = timeout 146 | self.printer_type = printer_type 147 | 148 | # buffer used for continuous printing with line wrapping 149 | self.print_buffer = '' 150 | 151 | def isConnected(self) -> bool: 152 | """ 153 | Check if printer is connected (socket alive) 154 | """ 155 | 156 | try: 157 | self.sock.getpeername() 158 | return True 159 | except: 160 | return False 161 | 162 | def connect(self) -> None: 163 | """ 164 | Open a new connection to the printer without checking for existing 165 | connection. In case of malfunction and/or twice connecting to the same 166 | printer, socket descriptor becomes unoperateable. 167 | 168 | In order to make printer operate normally, it is required to call 169 | `reset()` after connecting. 170 | """ 171 | 172 | self.sock = bluetooth.BluetoothSocket(bluetooth.RFCOMM) 173 | self.sock.connect((self.mac, 1)) 174 | self.sock.settimeout(self.timeout) 175 | 176 | def reconnect(self) -> None: 177 | """ 178 | Reconnect to the printer with existing connection check. 179 | 180 | In order to make printer operate normally, it is required to call 181 | `reset()` after connecting. 182 | """ 183 | 184 | if self.isConnected(): 185 | # self.sock.shutdown(socket.SHUT_RDWR) 186 | self.sock.close() 187 | del self.sock 188 | 189 | self.sock = bluetooth.BluetoothSocket(bluetooth.RFCOMM) 190 | self.sock.connect((self.mac, 1)) 191 | self.sock.settimeout(self.timeout) 192 | 193 | def disconnect(self) -> None: 194 | """ 195 | Disconnect from the printer. 196 | """ 197 | 198 | if self.isConnected(): 199 | # self.sock.shutdown(socket.SHUT_RDWR) 200 | self.sock.close() 201 | del self.sock 202 | 203 | def setTimeout(self, timeout) -> None: 204 | """ 205 | Set the bluetooth socket connection recv / send timeout. 206 | """ 207 | 208 | self.timeout = timeout 209 | if self.isConnected(): 210 | self.sock.settimeout(timeout) 211 | 212 | def tellPrinter(self, byteseq: bytes) -> None: 213 | """ 214 | Send `bytes` to the printer without response. 215 | 216 | Arguments: 217 | * `byteseq` - `bytes` data 218 | """ 219 | 220 | self.sock.send(byteseq) 221 | 222 | def askPrinter(self, byteseq: bytes, recv_size: int=1024) -> bytes: 223 | """ 224 | Send `bytes` to the printer with response. 225 | 226 | Arguments: 227 | * `recv_size` - max size of received chunk 228 | * `byteseq` - `bytes` data 229 | """ 230 | 231 | self.sock.send(byteseq) 232 | return self.sock.recv(recv_size) 233 | 234 | def listenPrinter(self, recv_size: int=1024) -> bytes: 235 | """ 236 | Receive data from printer. 237 | 238 | Arguments: 239 | * `recv_size` - max size of received chunk 240 | """ 241 | 242 | return self.sock.recv(recv_size) 243 | 244 | def tellPrinterSeq(self, byteseq: typing.Iterable[bytes]) -> None: 245 | """ 246 | Send list of `bytes` to the printer without response. 247 | 248 | Arguments: 249 | * `byteseq` - `list` of `bytes` 250 | """ 251 | 252 | for s in byteseq: 253 | self.sock.send(s) 254 | 255 | def askPrinterSeq(self, byteseq: typing.Iterable[bytes], recv_size: int=1024) -> bytes: 256 | """ 257 | Send list of `bytes` to the printer with response. 258 | 259 | Arguments: 260 | * `recv_size` - max size of received chunk 261 | * `byteseq` - `list` of `bytes` 262 | """ 263 | 264 | for s in byteseq: 265 | self.sock.send(s) 266 | return self.sock.recv(recv_size) 267 | 268 | def getDeviceIP(self) -> bytes: 269 | """ 270 | Query Unknown Property. 271 | 272 | Request: `10ff20f0`. 273 | 274 | Response: `bytes` with unknown property. 275 | 276 | Example: Peripage A6+ returns `IP-300`. 277 | """ 278 | 279 | return self.askPrinter(bytes.fromhex('10ff20f0')) 280 | 281 | def getDeviceName(self) -> bytes: 282 | """ 283 | Query device name. 284 | 285 | Request: `10ff3011`. 286 | 287 | Response: `bytes` with `device_name+two_bytes_of_mac` 288 | 289 | Example: Peripage A6+ returns `PeriPage+DF7A`. 290 | """ 291 | 292 | return self.askPrinter(bytes.fromhex('10ff3011')) 293 | 294 | def getDeviceSerialNumber(self) -> bytes: 295 | """ 296 | Query serial number. 297 | 298 | Request: `10ff20f2`. 299 | 300 | Response: `bytes` with serial number 301 | 302 | Example: Peripage A6+ returns `A6491571121`. 303 | """ 304 | 305 | return self.askPrinter(bytes.fromhex('10ff20f2')) 306 | 307 | def getDeviceFirmware(self) -> bytes: 308 | """ 309 | Query device firmware version. 310 | 311 | Request: `10ff20f1`. 312 | 313 | Response: `bytes` with firmware version 314 | 315 | Example: Peripage A6+ returns `V2.11_304dpi`. 316 | """ 317 | 318 | return self.askPrinter(bytes.fromhex('10ff20f1')) 319 | 320 | def getDeviceBattery(self) -> int: 321 | """ 322 | Query device battery percentage. 323 | 324 | Request: `10ff50f1`. 325 | 326 | Response: `bytes[2]` with percentage. `bytes[2] = { 0, percentage }` 327 | 328 | Example: Peripage A6+ returns `\\x00@` (equals to `bytes[2] = { 0, 64 }`). 329 | """ 330 | return int(self.askPrinter(bytes.fromhex('10ff50f1'))[1]) 331 | 332 | def getDeviceHardware(self) -> bytes: 333 | """ 334 | Query device hardware info. 335 | 336 | Request: `10ff3010`. 337 | 338 | Response: `bytes` with hw info. 339 | 340 | Example: Peripage A6+ returns `BR2141e-s(A02)_B9_20190815_r3460`. 341 | `BR2141e-s` chip with a pile of ascii letters. 342 | """ 343 | 344 | return self.askPrinter(bytes.fromhex('10ff3010')) 345 | 346 | def getDeviceMAC(self) -> bytes: 347 | """ 348 | Query device mac from device itself. 349 | 350 | Request: `10ff3012`. 351 | 352 | Response: `bytes` with mac address. 353 | 354 | Example: Peripage A6+ returns `\\x00\\xF5\\x73\\x25\\xAC\\x9F_\\x00\\xF5\\x73\\x25\\xAC\\x9F_` 355 | (equals to `00:F5:73:25:AC:9F`). 356 | """ 357 | 358 | return self.askPrinter(bytes.fromhex('10ff3012')) 359 | 360 | def getDeviceFull(self) -> bytes: 361 | """ 362 | Query full device info. 363 | 364 | Request: `10ff70f100`. 365 | 366 | Response: `bytes` with fill info. 367 | 368 | Example: Peripage A6+ returns `PeriPage+DF7A|00:F5:73:25:AC:9F|C5:12:81:19:2C:51|V2.11_304dpi|A6491571121|84` 369 | (`name+mac_slice|device_mac|client_mac|firmware|serial_number|battery_percentage`). 370 | 371 | WARNING: 372 | 373 | This command has a side-effect causing the printed images getting 374 | corrupted by shifting horisontally and adding a █ character to the 375 | in-printer ASCII buffer. 376 | """ 377 | 378 | return self.askPrinter(bytes.fromhex('10ff70f100')) 379 | 380 | def getRowBytes(self) -> int: 381 | """ 382 | Get row_bytes spec for current printer. 383 | 384 | Images are encoded as 1-pixel-per-1-bit, which means that 1 byte can 385 | encode 8 black-white pixels in a line. This property defines the bytes 386 | limit per image row, the overflow is truncated. 387 | """ 388 | 389 | return self.printer_type.spec.row_bytes 390 | 391 | def getRowWidth(self) -> int: 392 | """ 393 | Get row_width spec for current printer. 394 | 395 | Images are encoded as 1-pixel-per-1-bit, which means that 1 byte can 396 | encode 8 black-white pixels in a line. This property defines the pixel 397 | limit per image row, the overflow is truncated. 398 | """ 399 | 400 | return self.printer_type.spec.row_width 401 | 402 | def getRowCharacters(self) -> int: 403 | """ 404 | Get row_characters spec for current printer. 405 | 406 | Internal ASCII printing mode allows printer to output the raw ASCII 407 | letters up to `0x7f` and below to `0x10`. This property defunes the 408 | amount of letters that can fit in a single row. in case of wrapped 409 | printing, the overflow is wrapped using in-class buffer and synchronized 410 | with the in-printer buffer. 411 | """ 412 | 413 | return self.printer_type.spec.row_characters 414 | 415 | def getHeightLimit(self) -> int: 416 | """ 417 | Get the limit of single-image printing chunk. 418 | 419 | Printer protocol allows only 16-bit number as the definition for the 420 | image printing procedire, that requires used to vertically split the 421 | image into multiple chunks. 422 | """ 423 | 424 | return 0xffff 425 | 426 | def setDeviceSerialNumber(self, serial_number: str, wait: bool=True) -> None: 427 | """ 428 | Set device serial number. 429 | 430 | Set a new device serial number explicitly. `serial_number` defines the 431 | new serial number for the device. This serial number must be 432 | ascii-encodable string that match the requirements of 433 | `Printer.is_safe_ascii()` filter in order to work. Serial number string 434 | is additionally filtered with `Printer.filter_ascii` if you haven't read 435 | the previous sentence. 436 | 437 | Request: `10ff20f4+ascii_str+00`. 438 | 439 | Arguments: 440 | * `serial_number` - serial number string that passes the 441 | `Printer.is_safe_ascii()` check. 442 | """ 443 | 444 | request = bytes.fromhex('10ff20f4') + Printer.filter_ascii(serial_number).encode('ascii') + b'\0' 445 | 446 | if wait: 447 | return self.askPrinter(request) 448 | else: 449 | self.tellPrinter(request) 450 | 451 | def setPowerTimeout(self, timeout: int, wait: bool=True) -> None: 452 | """ 453 | Set device poweroff timeout. 454 | 455 | Device standby mode is triggered by any action made with the device. It 456 | can be either a print task, battery lever query and anything else that 457 | envolves ask-answer communication. Power timeout defines the internal 458 | auto poweroff timeout of the device in minutes, up to `0xffff` minutes. 459 | 460 | Request: `10ff12+bytes[2]:big_endian`. 461 | 462 | Arguments: 463 | * `timeout` - new timeout value between `0` and `0xffff`, minutes 464 | """ 465 | 466 | timeout = max(min(0xfff0, timeout), 0x0001) 467 | request = bytes.fromhex('10ff12') + int.to_bytes(timeout, 2, 'big') 468 | 469 | if wait: 470 | return self.askPrinter(request) 471 | else: 472 | self.tellPrinter(request) 473 | 474 | def setConcentration(self, concentration: int, wait: bool=False) -> None: 475 | """ 476 | Set printing concentration level. 477 | 478 | Printer supports multiple temperature concentration modes that allow to 479 | print darker or lighter images with the price of overheating. The more 480 | concentration - the longer lasting image will be. 481 | 482 | Request: `10ff1000+bytes[1]:big_endian`. 483 | 484 | Arguments: 485 | * `concentration` - concentration value from range `(0, 1, 2)` 486 | """ 487 | 488 | if concentration <= 0: 489 | request = bytes.fromhex('10ff100000') 490 | elif concentration == 1: 491 | request = bytes.fromhex('10ff100001') 492 | elif concentration >= 2: 493 | request = bytes.fromhex('10ff100002') 494 | 495 | if wait: 496 | return self.askPrinter(request) 497 | else: 498 | self.tellPrinter(request) 499 | 500 | def reset(self) -> None: 501 | """ 502 | Send reset request, required for initial printer initialization after 503 | connect/reconnect. Without this operation, printer will not print nor 504 | return any data. 505 | 506 | Request: `10fffe01+000000000000000000000000`. 507 | """ 508 | 509 | self.tellPrinter(bytes.fromhex('10fffe01000000000000000000000000')) 510 | 511 | def printBreak(self, size: int=0x40) -> None: 512 | """ 513 | Ask printer to print out a break of fixed size. 514 | 515 | Printer allows user to feed out some paper to wipe away tears of this 516 | module developer. 517 | 518 | Request: `1b4a+bytes[1]:big_endian`. 519 | 520 | Arguments: 521 | * `size` - break size in range `(0, 0xff)` 522 | """ 523 | 524 | size = min(0xff, max(0x01, size)) 525 | request = bytes.fromhex('1b4a') + int.to_bytes(size, 1, 'big') 526 | 527 | self.tellPrinter(request) 528 | 529 | def writeASCII(self, text: str='\n', wait=False) -> None: 530 | """ 531 | WARNING: THIS API IS UNSAFE 532 | 533 | Write text into printer without internal safety-checks and filtering. If 534 | you want to print text with internal checks for non-ascii or 535 | unsafe-ascii characters, use `Printer.printASCII()`. If you need to use 536 | this function, check you text with `Printer.is_safe_ascii` or filter 537 | with `Printer.filter_ascii` and do not leave more than one sequential 538 | `\\n` character. 539 | 540 | Request: `ascii_str`. 541 | 542 | Arguments: 543 | * `text` - text to be printed, should be checked by user before print or 544 | may malfunction and/or damage the printer. String must not contain 545 | repeating `\\n` characters or printer will freeze. 546 | """ 547 | 548 | request = text.encode('ascii') 549 | 550 | if wait: 551 | return self.askPrinter(request) 552 | else: 553 | self.tellPrinter(request) 554 | 555 | def printlnASCII(self, text: str='', delay: float=0.25) -> None: 556 | """ 557 | Safe to use printing method that relies on in-class buffer for wrapping 558 | text. The input is filtered with `Printer.filter_ascii` in order to 559 | exclude all non-safe-ascii characters and later splitted into multiple 560 | chunks over `\\n` in order to prevent freeze caused by twice-newline in 561 | printer buffer. This function is equal to normal `println` in C and 562 | semi-equal to `print(text + '\\n')`. This method relies on in-class 563 | buffer to track printed data and keeping sync with in-printer buffer. 564 | 565 | Request: `impl:Printer.printASCII()`. 566 | 567 | Arguments: 568 | * `text` - text to be printed, automatically filtered with 569 | `Printer.filter_ascii()` and splitted into newline-chunked data. 570 | * `delay` - delay between lines submission, seconds 571 | """ 572 | 573 | self.printASCII(text=text + '\n', delay=delay) 574 | 575 | def printASCII(self, text: str='\n', delay: float=0.25) -> None: 576 | """ 577 | Safe to use printing method that relies on in-class buffer for wrapping 578 | text. The input is filtered with `Printer.filter_ascii` in order to 579 | exclude all non-safe-ascii characters and later splitted into multiple 580 | chunks over `\\n` in order to prevent freeze caused by twice-newline in 581 | printer buffer. This function is equal to normal `print` in C. This 582 | method relies on in-class buffer to track printed data and keeping sync 583 | with in-printer buffer. 584 | 585 | In case when the input text contains two sequential `\\n`, they are 586 | replaced with `Printer.printBreak(30)`. 587 | 588 | Request: `impl:Printer.writeASCII()`. 589 | 590 | Arguments: 591 | * `text` - text to be printed, automatically filtered with 592 | `Printer.filter_ascii()` and splitted into newline-chunked data. 593 | * `delay` - delay between lines submission, seconds 594 | """ 595 | 596 | text = Printer.filter_ascii(text) 597 | 598 | # Check for empty and print out newline 599 | text = self.print_buffer + text 600 | self.print_buffer = '' 601 | if len(text) == 0: 602 | return 603 | 604 | # Special case: \n only, causes duplicating newlines (white-only string) 605 | if len(text.strip()) == 0: 606 | for s in text: 607 | if s == '\n': 608 | self.printBreak(30) 609 | time.sleep(delay) 610 | return 611 | 612 | # Iterlines 613 | lines = text.split('\n') 614 | for l in lines: 615 | 616 | # Flush previuos incomplete line 617 | if len(self.print_buffer) != 0: 618 | self.tellPrinter(self.print_buffer.encode('ascii')) 619 | self.tellPrinter(b'\n') 620 | self.print_buffer = '' 621 | time.sleep(delay) 622 | 623 | # Flush if white-empty, because it is newline 624 | elif len(l.strip()) == 0: 625 | 626 | # Flush in-printer buffer if not empty 627 | if len(self.print_buffer) != 0: 628 | self.tellPrinter(self.print_buffer.encode('ascii')) 629 | self.tellPrinter(b'\n') 630 | self.print_buffer = '' 631 | time.sleep(delay) 632 | 633 | # Trail 634 | else: 635 | self.printBreak(30) 636 | time.sleep(delay) 637 | 638 | # Process normal lines 639 | else: 640 | # Wrap line 641 | parts = [ l[i:i+self.getRowCharacters()] for i in range(0, len(l), self.getRowCharacters()) ] 642 | 643 | for p in parts: 644 | 645 | # Print full line 646 | if len(p) == self.getRowCharacters(): 647 | self.tellPrinter(p.encode('ascii')) 648 | self.tellPrinter(b'\n') 649 | time.sleep(delay) 650 | 651 | # Partial, write to buffer 652 | else: 653 | self.print_buffer = p 654 | 655 | def flushASCII(self, delay: float=0.25) -> None: 656 | """ 657 | Force=print out buffer if it is not empty. Not equal to 658 | `Printer.println()` because does not output empty newline if buffer is 659 | empty. 660 | 661 | Request: `impl:Printer.printASCII()`. 662 | 663 | Arguments: 664 | * `delay` - delay between lines submission, seconds 665 | """ 666 | 667 | if len(self.print_buffer) != 0: 668 | self.tellPrinter(self.print_buffer.encode('ascii')) 669 | self.tellPrinter(b'\n') 670 | self.print_buffer = '' 671 | time.sleep(delay) 672 | 673 | def printRow(self, rowbytes: bytes, delay: float=0.01) -> None: 674 | """ 675 | Send bytes representing a single image row in binary black/white mode. 676 | If amount of bydes exceedes the `Printer.getRowBytes()` constant, input 677 | is truncated. If size of input is under the `Printer.getRowBytes()`, it 678 | will be padded with zeros. 679 | 680 | Request: `1d763000+bytes[2]:big_endian+0100+bytes[Printer.getRowBytes()*1]`. 681 | 682 | Note: In case of A6+, preamble is `1d76300048000100` that can be viewed 683 | as `[ 1d7630, 0030, 0001 ]`, where `1d7630` is printing operation 684 | request, `0030` is big endian bytes per row, `0001` is big endian input 685 | height. 686 | 687 | Arguments: 688 | * `rowbytes` - bytes representing image pixels, 8 pixels per byte, 689 | truncated/padded to fit `Printer.getRowBytes()`. 690 | * `delay` - delay between printing each row of the image. 691 | """ 692 | 693 | expectedLen = self.getRowBytes() 694 | if len(rowbytes) < expectedLen: 695 | rowbytes = rowbytes.ljust(expectedLen, b'\0') 696 | elif len(rowbytes) > expectedLen: 697 | rowbytes = rowbytes[:expectedLen] 698 | 699 | self.reset() 700 | 701 | # Notify printer about incomming $expectedLen bytes row 702 | request = bytes.fromhex('1d763000') + int.to_bytes(self.getRowBytes(), 1, 'big') + bytes.fromhex('000100') + rowbytes 703 | self.tellPrinter(request) 704 | time.sleep(delay) 705 | 706 | # We're done here 707 | 708 | def printRowBytesList(self, rowbytes: typing.Iterable[bytes], delay: float=0.01) -> None: 709 | """ 710 | Send an array of bytes representing a multiple image rows in binary 711 | black/white mode. If amount of bydes per row exceedes the 712 | `Printer.getRowBytes()` constant, input is truncated. If size of input 713 | is under the `Printer.getRowBytes()`, it will be padded with zeros. 714 | 715 | This printer supports pages up to `0xffff` rows, but current 716 | implementation relies on chunked data with height limit of `0xff` and 717 | automatically slices the input into chunks. 718 | 719 | Note: In case of A6+, preamble is `1d76300048000100` that can be viewed 720 | as `[ 1d7630, 0030, 0001 ]`, where `1d7630` is printing operation 721 | request, `0030` is big endian bytes per row, `0001` is big endian input 722 | height. 723 | 724 | Request: chunked `1d763000+bytes[1]:big_endian+00+bytes[1]:big_endian+00+bytes[Printer.getRowBytes()*chunk_height]`. 725 | 726 | Arguments: 727 | * `rowbytes` - list of bytes defining each row of the image. If row 728 | length does not match the `Printer.getRowBytes()`, data is 729 | truncated/padded to match the size. 730 | * `delay` - delay between printing each row of the image. 731 | """ 732 | 733 | if len(rowbytes) == 0: 734 | return 735 | 736 | expectedLen = self.getRowBytes() 737 | chunks = [ rowbytes[i:i+0xff] for i in range(0, len(rowbytes), 0xff) ] 738 | 739 | for chunk in chunks: 740 | 741 | # Reset state before print 742 | self.reset() 743 | 744 | # 1d763000 30 00 01 00 745 | # Send preamble: `1d763000` + row_bytes:bytes[1] + `00` + chunk_size:bytes[1] + `00` 746 | request = bytes.fromhex('1d763000') + int.to_bytes(self.getRowBytes(), 1, 'big') + bytes.fromhex('00') + int.to_bytes(len(chunk), 1, 'big') + bytes.fromhex('00') 747 | 748 | # Flush preamble 749 | self.tellPrinter(request) 750 | 751 | # Flush rows dith delay 752 | for row in chunk: 753 | # trunc/pad 754 | if len(row) < expectedLen: 755 | row = row.ljust(expectedLen, b'\0') 756 | elif len(row) > expectedLen: 757 | row = row[:expectedLen] 758 | 759 | self.tellPrinter(row) 760 | 761 | time.sleep(delay) 762 | 763 | def printRowBytesIterator(self, rowiterator: typing.Iterable[bytes], delay: float=0.01) -> None: 764 | """ 765 | Iterate over the given iterator and print out all produced rows. This 766 | method is very slow as it required printer to oftenly switch on/off 767 | printing mode and pass a large overhead to set up the printing mode. 768 | 769 | This method uses the `Printer.printRow()` call. 770 | 771 | Arguments: 772 | * `rowiterator` - iterator that returns bytes. 773 | * `delay` - delay between printing each row of the image. 774 | """ 775 | 776 | for r in rowiterator: 777 | self.printRow(r, delay=delay) 778 | 779 | def printRowChunksIterator(self, rowiterator: typing.Iterable[typing.List[bytes]], delay: float=0.01) -> None: 780 | """ 781 | Iterate over the given iterator and print out all produced chunks of 782 | rows. One chunk of rows is a list of bytes where each bytes define the 783 | specific line of the image. This method is better than the use of 784 | `Printer.printRowBytesIterator()` as it passes each chunk of image data 785 | directly into the `Printer.printImageRowBytesList()`. 786 | 787 | Arguments: 788 | * `rowiterator` - iterator that returns list[bytes]. 789 | * `delay` - delay between printing each row of the image. 790 | """ 791 | 792 | for chunk in rowiterator: 793 | self.printRowBytesList(chunk, delay=delay) 794 | 795 | def printImageBytes(self, imagebytes: bytes, delay: float=0.01) -> None: 796 | """ 797 | Send an bytes representing single-line encoded image. For example, 798 | `[0xff000000, 0x00ff0000, 0x0000ff00, 0x000000ff]` is encoded as 799 | `0xff00000000ff00000000ff00000000ff`. 800 | 801 | Image must be valid aligned and sequence size must divide by 802 | `Printer.getRowBytes()`. In case of partial data, the rest of partial 803 | data is padded with zeros. Number of lines is calcualted as 804 | `nlines = ceil(len(imagebytes) / Printer.getRowBytes())`. 805 | 806 | Arguments: 807 | * `imagebytes` - bytes defining concatenated rows of the image. Each 808 | row must be aligned to `Printer.getRowBytes()` in order to display 809 | properly. If length of the last row dows not match 810 | `Printer.getRowBytes()`, data is truncated/padded to match the size. 811 | * `delay` - delay between printing each row of the image. 812 | """ 813 | 814 | if len(imagebytes) == 0: 815 | return 816 | 817 | # Delegate to impl 818 | self.printRowBytesList([ imagebytes[i:i+self.getRowBytes()] for i in range(0, len(imagebytes), self.getRowBytes()) ], delay=delay) 819 | 820 | def printImage(self, img: PIL.Image.Image, delay=0.01, resample=PIL.Image.Resampling.NEAREST) -> None: 821 | """ 822 | Print PIL Image on this printer with automatic internal to-blackwhite 823 | conversion. 824 | 825 | WARNING: In order to prevent the overhead of the printer (and possibly 826 | loose some data but to limitations of the in-printer buffer) it is 827 | suggested to split image into many vertical pieces and wait a 828 | reasonable amount of time to let the printer to cooldown. 829 | 830 | Arguments: 831 | * `img` - your pretty PIL Image. 832 | * `delay` - delay between printing each row of the image. 833 | * `resample` - resampling mode of the image, used to automatically 834 | rescale image to fit the printer width of `Printer.getRowWidth()`. 835 | """ 836 | 837 | img = img.convert('L') 838 | img = PIL.ImageOps.invert(img) 839 | img = img.resize((self.getRowWidth(), int(self.getRowWidth() / img.size[0] * img.size[1])), resample) 840 | img = img.convert('1') 841 | 842 | imgbytes = img.tobytes() 843 | self.printImageBytes(imgbytes, delay=delay) 844 | 845 | def printImageIterator(self, imgiterator: typing.Iterable[PIL.Image.Image], delay: float=0.01): 846 | """ 847 | Iterate over iterator and print out each PIL Image that it returns. 848 | 849 | Arguments: 850 | * `rowiterator` - iterator that returns list[bytes]. 851 | * `delay` - delay between printing each row of the image. 852 | """ 853 | 854 | for img in imgiterator: 855 | self.printImage(img, delay=delay) 856 | 857 | def printQR(self, text: str, delay: float=0.01, resample=PIL.Image.Resampling.NEAREST) -> None: 858 | """ 859 | Generate a QR code from specified string and print it. 860 | 861 | Arguments: 862 | * `text` - your pretty text. 863 | * `delay` - delay between printing each row of the image. 864 | * `resample` - resampling mode of the image, used to automatically 865 | rescale image to fit the printer width of `Printer.getRowWidth()`. 866 | """ 867 | 868 | self.printImage(qrcode.make(text, border=0), delay=delay, resample=resample) 869 | -------------------------------------------------------------------------------- /peripage/__main__.py: -------------------------------------------------------------------------------- 1 | # peripage-python - python library for peripage thermal printers 2 | # Copyright (C) 2020-2023 bitrate16 (pegasko) 3 | # 4 | # This program is free software: you can redistribute it and/or modify 5 | # it under the terms of the GNU General Public License as published by 6 | # the Free Software Foundation, either version 3 of the License, or 7 | # (at your option) any later version. 8 | # 9 | # This program is distributed in the hope that it will be useful, 10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | # GNU General Public License for more details. 13 | # 14 | # You should have received a copy of the GNU General Public License 15 | # along with this program. If not, see . 16 | 17 | 18 | def main(): 19 | import argparse 20 | import sys 21 | import peripage 22 | import PIL.Image 23 | 24 | parser = argparse.ArgumentParser(description='Print on a Peripage printer via bluetooth') 25 | parser.add_argument( 26 | '-m', '--mac', 27 | help='Bluetooth MAC address of the printer', 28 | required=True, 29 | type=str 30 | ) 31 | parser.add_argument( 32 | '-c', '--concentration', 33 | help='Concentration value for printing (temperature)', 34 | choices=[0, 1, 2], 35 | metavar='[0-2]', 36 | type=int, 37 | default=0 38 | ) 39 | parser.add_argument( 40 | '-b', '--break', 41 | dest='break_size', 42 | help='Size of the break inserted after printed image or text', 43 | choices=range(256), 44 | metavar='[0-255]', 45 | type=int, 46 | default=0 47 | ) 48 | parser.add_argument( 49 | '-p', '--printer', 50 | help='Printer model selection', 51 | choices=peripage.PrinterType.names(), 52 | type=str, 53 | required=True 54 | ) 55 | 56 | group = parser.add_mutually_exclusive_group(required=True) 57 | group.add_argument( 58 | '-t', '--text', 59 | help='ASCII text to print. Text must be ASCII-safe and will be filtered for invalid characters', 60 | type=str 61 | ) 62 | group.add_argument( 63 | '-s', '--stream', 64 | help='Print text received from STDIN, line by line. Text must be ASCII-safe and will be filtered for invalid characters', 65 | action='store_true' 66 | ) 67 | group.add_argument( 68 | '-i', '--image', 69 | help='Path to the image for printing', 70 | type=str 71 | ) 72 | group.add_argument( 73 | '-q', '--qr', 74 | help='String to convert into a QR code for printing', 75 | type=str 76 | ) 77 | group.add_argument( 78 | '-e', '--introduce', 79 | help='Ask the printer to introduce itself', 80 | action='store_true' 81 | ) 82 | 83 | args = parser.parse_args() 84 | 85 | # Open connection 86 | printer = peripage.Printer(args.mac, peripage.PrinterType[args.printer]) 87 | printer.connect() 88 | printer.reset() 89 | 90 | # Act based on args 91 | if 'introduce' in args and args.introduce: 92 | 93 | # print('Hello, my name is Harold..') 94 | print(printer.getDeviceFull().decode('ascii')) 95 | printer.disconnect() 96 | sys.exit(0) 97 | 98 | elif 'stream' in args and args.stream: 99 | 100 | printer.setConcentration(args.concentration) 101 | 102 | while True: 103 | try: 104 | line = input().rstrip() 105 | 106 | printer.printlnASCII(line) 107 | 108 | except EOFError: 109 | # Input closed ^d^d 110 | break 111 | 112 | if args.break_size > 0: 113 | printer.printBreak(args.break_size) 114 | 115 | printer.disconnect() 116 | 117 | sys.exit(0) 118 | 119 | elif 'text' in args and args.text is not None: 120 | 121 | printer.setConcentration(args.concentration) 122 | 123 | text = args.text.rstrip() 124 | 125 | if len(text) > 0: 126 | printer.printASCII(text) 127 | printer.flushASCII() 128 | 129 | if args.break_size > 0: 130 | printer.printBreak(args.break_size) 131 | 132 | printer.disconnect() 133 | 134 | sys.exit(0) 135 | 136 | elif 'image' in args and args.image is not None: 137 | 138 | printer.setConcentration(args.concentration) 139 | 140 | try: 141 | img = PIL.Image.open(args.image) 142 | except: 143 | print(f'Failed to open image { args.image }') 144 | 145 | printer.printImage(img) 146 | 147 | if args.break_size > 0: 148 | printer.printBreak(args.break_size) 149 | 150 | printer.disconnect() 151 | 152 | sys.exit(0) 153 | 154 | elif 'qr' in args and args.qr is not None: 155 | 156 | printer.setConcentration(args.concentration) 157 | 158 | printer.printQR(args.qr) 159 | 160 | if args.break_size > 0: 161 | printer.printBreak(args.break_size) 162 | 163 | printer.disconnect() 164 | 165 | sys.exit(0) 166 | 167 | else: 168 | 169 | print('How did you get there?') 170 | 171 | if __name__ == '__main__': 172 | main() 173 | -------------------------------------------------------------------------------- /print-server/README.md: -------------------------------------------------------------------------------- 1 | # print-server 2 | 3 | Simple utility for creating standalone print server for peripage A6/A6+ thermal printer 4 | 5 | # Configure 6 | 7 | Edit config in `__main__.py` 8 | ```python 9 | # Config 10 | PRINTER_MODEL = peripage.PrinterType.A6p 11 | PRINTER_MAC = '00:15:83:15:bc:5f' 12 | SERVER_PORT = 11001 13 | BREAK_SIZE = 100 14 | TIMEZONE = 'Europe/Moscow' 15 | SECRET_KEY = '1234567890' 16 | RECEIVE_DIRECTORY = 'received' 17 | ``` 18 | 19 | Edit server properties in `scripts/print_ascii_clipboard.py` 20 | ```python 21 | SERVER_ADDR = '192.168.1.101:11001' 22 | BREAK = 1 # Enable/disable 23 | CONCENTRATION = 2 # Value (0-2) 24 | SECRET_KEY = '1234567890' 25 | ``` 26 | 27 | Edit server properties in `scripts/print_image_drag_and_drop.py` 28 | ```python 29 | SERVER_ADDR = '192.168.1.101:11001' 30 | BREAK = 1 # Enable/disable 31 | CONCENTRATION = 2 # Value (0-2) 32 | SECRET_KEY = '1234567890' 33 | ``` 34 | 35 | Edit server properties in `scripts/print_image_clipboard.py` 36 | ```python 37 | SERVER_ADDR = '192.168.1.101:11001' 38 | BREAK = 1 # Enable/disable 39 | CONCENTRATION = 2 # Value (0-2) 40 | SECRET_KEY = '1234567890' 41 | ``` 42 | 43 | # Requirements 44 | 45 | Libraries: 46 | ```bash 47 | $ sudo apt install bluetooth bluez libbluetooth-dev libopenjp2-7 48 | ``` 49 | 50 | Packages: 51 | ``` 52 | $ pip3 install Pillow aiohttp aiohttp_middlewares peripage python-dateutil 53 | ``` 54 | 55 | # Usage 56 | 57 | ### ASCII text print 58 | 59 | Tabs automatically converted to 4 spaces 60 | 61 | 1. Copy text to clipboard 62 | 2. Run `print_ascii_clipboard.py` or `print_ascii_clipboard.bat` 63 | 64 | Endpoint: 65 | ``` 66 | Set print_date to 1 to enable print leading date 67 | Set print_break to 1 to enable print trailing break 68 | Set request body to ASCII text to print 69 | 70 | POST /print_ascii?print_date=1&print_break=1 71 | body: "Hello World!" 72 | ``` 73 | 74 | ### Image print 75 | 76 | Supported: jpeg, png 77 | 78 | 1. Drag and drop image file on `print_image_drag_and_drop.bat.py` or `print_image_drag_and_drop.bat` 79 | 80 | Endpoint: 81 | ``` 82 | Set print_date to 1 to enable print leading date 83 | Set print_break to 1 to enable print trailing break 84 | Set request body to image file, supported png and jpg 85 | 86 | POST /print_image?print_break=1 87 | body: { image: binary image file } 88 | ``` 89 | 90 | ### Image print from clipboard 91 | 92 | Supported: jpeg, png 93 | 94 | 1. Copy image from browser/editor/etc and run `print_image_clipboard.py` or `print_image_clipboard.bat` 95 | Endpoint: Same as above 96 | 97 | # Run 98 | 99 | Run with: 100 | ``` 101 | python3 -m print-server 102 | ``` 103 | -------------------------------------------------------------------------------- /print-server/__main__.py: -------------------------------------------------------------------------------- 1 | # MIT (C) bitrate16 2022 2 | 3 | # Requirements: 4 | # $ sudo apt install bluetooth bluez libbluetooth-dev libopenjp2-7 5 | # $ pip3 install Pillow aiohttp aiohttp_middlewares peripage python-dateutil 6 | 7 | # Run with 8 | # $ python3 -m print-server 9 | 10 | 11 | import aiohttp 12 | import io 13 | import os 14 | import aiohttp.web 15 | import aiohttp_middlewares 16 | import peripage 17 | import atexit 18 | import PIL 19 | import sys 20 | 21 | from dateutil import tz 22 | from datetime import datetime 23 | 24 | from . import print_service 25 | 26 | # Config 27 | PRINTER_MODEL = peripage.PrinterType.A6p 28 | PRINTER_MAC = '00:15:83:15:bc:5f' 29 | SERVER_PORT = 11001 30 | BREAK_SIZE = 100 31 | TIMEZONE = 'Europe/Moscow' 32 | SECRET_KEY = '1234567890' 33 | RECEIVE_DIRECTORY = 'received' 34 | MAX_FILE_SIZE = 10 * 1024 * 1024 35 | 36 | 37 | # Globals 38 | service: print_service.PrintService = None 39 | app: aiohttp.web.Application = None 40 | file = None 41 | 42 | 43 | # Utils 44 | def log(*args): 45 | print(*args) 46 | for a in args: 47 | file.write(str(a)) 48 | file.write(' ') 49 | file.write('\n') 50 | file.flush() 51 | 52 | def print_break(timestamp, date, ip, proxy_ip): 53 | """ 54 | Simple page break of given size 55 | """ 56 | 57 | def wrap_print_break(p: peripage.Printer): 58 | p.printBreak(BREAK_SIZE) 59 | log(ip, '/', proxy_ip, '#', date, timestamp, 'done', 'BREAK') 60 | 61 | service.add_print_handler(wrap_print_break) 62 | 63 | 64 | # Handlers 65 | 66 | async def post_print_ascii(request: aiohttp.web.Request): 67 | 68 | if request.query.get('secret', None) != SECRET_KEY: 69 | return aiohttp.web.json_response({ 70 | 'status': 'error', 71 | 'message': 'missing secret key' 72 | }) 73 | 74 | # Get request payload 75 | if not request.body_exists: 76 | return aiohttp.web.json_response({ 77 | 'status': 'error', 78 | 'message': 'missing request body' 79 | }) 80 | 81 | # Clear, post and return length 82 | text = await request.text() 83 | 84 | # Additinally process string 85 | text.replace('\t', ' ') 86 | ascii_text = ''.join([i for i in text if (31 < ord(i) or ord(i) == 10) and ord(i) < 127]).strip() 87 | 88 | if len(ascii_text) == 0: 89 | return aiohttp.web.json_response({ 90 | 'status': 'error', 91 | 'message': 'empty ascii string' 92 | }) 93 | 94 | date = datetime.now(tz.gettz(TIMEZONE)) 95 | timestamp = round(date.timestamp() * 1000) 96 | date = date.strftime("%d.%m.%Y %H:%M:%S.%f") 97 | 98 | # Log 99 | log(request.remote, '/', request.headers.get('X-Forwarded-For', 'None'), '#', date, timestamp, '--->', 'ASCII') 100 | 101 | # Save data 102 | if RECEIVE_DIRECTORY is not None: 103 | with open(f'{RECEIVE_DIRECTORY}/{timestamp}_ascii.txt', 'w') as f: 104 | f.write(ascii_text) 105 | 106 | # Decorate string 107 | print_text = ascii_text 108 | if (request.query.get('print_date', None) == 'true') or (request.query.get('print_date', None) == '1'): 109 | print_text = f'{date}\n{print_text}' 110 | 111 | # Get concentration 112 | try: 113 | concenttration = min(2, max(0, int(request.query.get('print_concentration', 0)))) 114 | except: 115 | concenttration = 0 116 | 117 | # Submit image printing task 118 | def wrap_print_ascii(p: peripage.Printer): 119 | p.setConcentration(concenttration) 120 | p.printASCII(ascii_text) 121 | p.flushASCII() 122 | log(request.remote, '/', request.headers.get('X-Forwarded-For', 'None'), '#', date, timestamp, 'done', 'ASCII') 123 | 124 | service.add_print_handler(wrap_print_ascii) 125 | 126 | if (request.query.get('print_break', None) == 'true') or (request.query.get('print_break', None) == '1'): 127 | print_break(timestamp, date, request.remote, request.headers.get('X-Forwarded-For', 'None')) 128 | 129 | return aiohttp.web.json_response({ 130 | 'status': 'result', 131 | 'length': len(ascii_text) 132 | }) 133 | 134 | async def post_print_image(request: aiohttp.web.Request): 135 | 136 | if request.query.get('secret', None) != SECRET_KEY: 137 | return aiohttp.web.json_response({ 138 | 'status': 'error', 139 | 'message': 'missing secret key' 140 | }) 141 | 142 | # Get request payload 143 | if not request.body_exists: 144 | return aiohttp.web.json_response({ 145 | 'status': 'error', 146 | 'message': 'missing request body' 147 | }) 148 | 149 | post = post = await request.post() 150 | image = post.get('image') 151 | 152 | if not image: 153 | return aiohttp.web.json_response({ 154 | 'status': 'error', 155 | 'message': 'missing request image' 156 | }) 157 | 158 | try: 159 | img_content = image.file.read() 160 | buf = io.BytesIO(img_content) 161 | img = PIL.Image.open(buf) 162 | 163 | date = datetime.now(tz.gettz(TIMEZONE)) 164 | timestamp = round(date.timestamp() * 1000) 165 | date = date.strftime("%d.%m.%Y %H:%M:%S.%f") 166 | 167 | if not img: 168 | return aiohttp.web.json_response({ 169 | 'status': 'error', 170 | 'message': 'invalid request image' 171 | }) 172 | 173 | # Log 174 | log(request.remote, '/', request.headers.get('X-Forwarded-For', 'None'), '#', date, timestamp, '--->', 'Image') 175 | 176 | # Save data 177 | if RECEIVE_DIRECTORY is not None: 178 | img.save(f'{RECEIVE_DIRECTORY}/{timestamp}_image.png', 'PNG') 179 | 180 | # Get concentration 181 | try: 182 | concenttration = min(2, max(0, int(request.query.get('print_concentration', 0)))) 183 | except: 184 | concenttration = 0 185 | 186 | # Submit image printing task 187 | def wrap_print_image(p: peripage.Printer): 188 | p.setConcentration(concenttration) 189 | p.printImage(img) 190 | log(request.remote, '/', request.headers.get('X-Forwarded-For', 'None'), '#', date, timestamp, 'done', 'Image') 191 | 192 | service.add_print_handler(wrap_print_image) 193 | 194 | # Add page break 195 | if (request.query.get('print_break', None) == 'true') or (request.query.get('print_break', None) == '1'): 196 | print_break(timestamp, date, request.remote, request.headers.get('X-Forwarded-For', 'None')) 197 | 198 | # Return size of payload 199 | return aiohttp.web.json_response({ 200 | 'status': 'result', 201 | 'length': len(img_content) 202 | }) 203 | 204 | except: 205 | type, value, _ = sys.exc_info() 206 | return aiohttp.web.json_response({ 207 | 'status': 'error', 208 | 'message': str(value), 209 | 'type': str(type) 210 | }) 211 | 212 | 213 | def main(): 214 | 215 | # Create output directory 216 | if RECEIVE_DIRECTORY is not None: 217 | os.makedirs(RECEIVE_DIRECTORY, exist_ok=True) 218 | 219 | global file 220 | file = open(f'print-server.log', 'a', encoding='utf-8') 221 | 222 | # Init app 223 | global app 224 | app = aiohttp.web.Application(middlewares=[ 225 | aiohttp_middlewares.cors_middleware(allow_all=True), 226 | ], client_max_size=MAX_FILE_SIZE) 227 | 228 | # Init printing service 229 | global service 230 | service = print_service.PrintService(60, 1, 5) 231 | service.start(PRINTER_MAC, PRINTER_MODEL) 232 | 233 | # Attach routes 234 | app.router.add_post('/print_ascii', post_print_ascii) 235 | app.router.add_post('/print_image', post_print_image) 236 | 237 | # Register exit handler 238 | atexit.register(dispose) 239 | 240 | # Run 241 | aiohttp.web.run_app(app, port=SERVER_PORT) 242 | 243 | def dispose(): 244 | service.stop() 245 | 246 | if __name__ == '__main__': 247 | main() 248 | -------------------------------------------------------------------------------- /print-server/print_service.py: -------------------------------------------------------------------------------- 1 | # Utility for tracking printing tasks 2 | # 3 | # MIT License 4 | # 5 | # Copyright (c) 2022 bitrate16 6 | 7 | import time 8 | import threading 9 | import PIL 10 | 11 | import peripage 12 | 13 | 14 | class Repeat(): 15 | """ 16 | Interval-based code execution 17 | """ 18 | 19 | def __init__(self, interval: float, handler): 20 | self.interval = interval 21 | self.running = False 22 | self.should_stop = True 23 | self.thread = None 24 | self.handler = handler 25 | 26 | def start(self): 27 | if self.running: 28 | return False 29 | else: 30 | def handler(): 31 | self.running = True 32 | 33 | while not self.should_stop: 34 | try: 35 | self.handler() 36 | except: 37 | # XXX: Important: we are ignoring this exception 38 | pass 39 | time.sleep(self.interval) 40 | 41 | self.running = False 42 | 43 | self.should_stop = False 44 | self.thread = threading.Thread(target=handler).start() 45 | return True 46 | 47 | def stop(self): 48 | if not self.running: 49 | return False 50 | else: 51 | self.should_stop = True 52 | 53 | def set_handler(self, handler): 54 | self.handler = handler 55 | 56 | def is_running(self): 57 | return self.running 58 | 59 | 60 | class PrintService: 61 | """ 62 | This printer task autimatically handler print tasks from internal queue and 63 | maintains printer connected state. 64 | 65 | Printer processes events in another thread by proocessing single event per 66 | event_interval. 67 | 68 | If printer disconnects, this service will automatically reconnect it after 69 | event_interval and print in the same time slot. If reconnect attempts fail, 70 | it will wait given offline_interval until next connection attempt. 71 | 72 | If ping interval is over, printer will be pinged to return battery level and 73 | keep connection alive (prevent sleep). 74 | """ 75 | 76 | def __init__(self, ping_interval: float = 60, event_interval: float = 1, offline_interval: float = 1, startup_interval: float = 1, guard_ping_interval: float = 1): 77 | # Printer keep-alive check interval, seconds 78 | self.ping_interval = ping_interval 79 | 80 | # Printer event check interval, seconds 81 | self.event_interval = event_interval 82 | 83 | # Last printer ping timestamp, seconds 84 | self.last_ping_timestamp = 0 85 | 86 | # Interval to wait after printer cconnection established 87 | self.startup_interval = startup_interval 88 | 89 | # Time between reconnect attempts 90 | self.offline_interval = offline_interval 91 | 92 | # interval between ping and data sending 93 | self.guard_ping_interval = guard_ping_interval 94 | 95 | # Serive task loop 96 | self.service: Repeat = None 97 | 98 | # Instance of printer 99 | self.printer: peripage.Printer = None 100 | 101 | # Event queue 102 | self.events = [] 103 | 104 | # Indicate service failture 105 | self.service_failture = True 106 | 107 | def start(self, printer_mac: str, printer_type: peripage.PrinterType, timeout: float = 1.0, concentration: int = 1): 108 | """ 109 | Perform startup oof the service without check for previous instance running. 110 | """ 111 | 112 | def service_handler(): 113 | """ 114 | Internal event processing handler. 115 | """ 116 | 117 | initial_failture = True 118 | while self.service.is_running(): 119 | try: 120 | if not self.printer.isConnected(): 121 | raise RuntimeError('not connected') 122 | 123 | # Windows workaround 124 | try: 125 | self.printer.sock.listen() 126 | except: 127 | pass 128 | 129 | if not self.printer.isConnected(): 130 | raise RuntimeError('not connected') 131 | 132 | # If time is over, perform keep-alive procedure 133 | if time.time() > (self.last_ping_timestamp + self.ping_interval): 134 | str(self.printer.getDeviceBattery()) 135 | self.last_ping_timestamp = time.time() 136 | 137 | # Execute task handler 138 | # Task will be deleted only after correct execution without exceptions 139 | if len(self.events): 140 | 141 | if self.guard_ping_interval is not None: 142 | str(self.printer.getDeviceBattery()) 143 | self.last_ping_timestamp = time.time() 144 | 145 | time.sleep(self.guard_ping_interval) 146 | 147 | self.events[0](self.printer) 148 | self.events.pop(0) 149 | 150 | # Return on success 151 | return 152 | 153 | except: 154 | # Connection error, reinitialize connection 155 | self.service_failture = True 156 | 157 | # Wait for offline_interval before reconnects 158 | if not initial_failture: 159 | time.sleep(self.offline_interval) 160 | initial_failture = False 161 | 162 | # Disconnect 163 | try: 164 | if self.printer.isConnected(): 165 | self.printer.disconnect() 166 | except: 167 | pass 168 | 169 | # Connect 170 | try: 171 | self.printer.connect() 172 | self.printer.reset() 173 | self.printer.setConcentration(self.concentration) 174 | 175 | time.sleep(self.startup_interval) 176 | 177 | self.last_ping_timestamp = time.time() 178 | self.service_failture = False 179 | except: 180 | pass 181 | 182 | self.concentration = concentration 183 | self.printer = peripage.Printer(printer_mac, printer_type, timeout) 184 | self.last_ping_timestamp = time.time() 185 | self.events = [] 186 | self.service = Repeat(self.event_interval, service_handler) 187 | self.service.start() 188 | 189 | def stop(self): 190 | try: 191 | self.service.stop() 192 | self.printer.disconnect() 193 | except: 194 | pass 195 | 196 | def is_service_failture(self): 197 | return self.service_failture 198 | 199 | def add_print_handler(self, print_handler): 200 | """ 201 | Adds event handler to the queue. THis handler will be executed with single 202 | arguemnt - printer instance. 203 | 204 | Example: 205 | ``` 206 | printer_task.add_print_handler(lambda printer: printer.printASCII('hello')) 207 | ``` 208 | """ 209 | 210 | try: 211 | self.events.append(print_handler) 212 | return True 213 | except: 214 | return False 215 | 216 | def add_print_ascii(self, ascii_text: str, concentration: int=None, break_size: int=0, /, flush: bool = False): 217 | """ 218 | Adds simple print ASCII event to queue, additionally flushes output 219 | buffer. 220 | 221 | `ascii_text` defines the input text to be printed. 222 | 223 | `concentration` defines the concentration value from range [0, 1, 2]. 224 | Set to None to ignore. 225 | 226 | `break_size` defines the break size to print after the text. Refers to 227 | `peripage.Printer.printBreak()` for value limitations. Set to None or 0 to 228 | ignore. 229 | 230 | `flush` allows force flushing ASCII buffer. Refers to 231 | `peripage.Printer.flushASCII()`. 232 | 233 | 234 | Example: 235 | ``` 236 | printer_task.add_print_ascii('hello', concentration=2, break_size=100, flush=True) 237 | ``` 238 | """ 239 | 240 | def wrap_print(printer: peripage.Printer): 241 | if concentration is not None: 242 | printer.setConcentration(concentration) 243 | 244 | printer.printASCII(ascii_text) 245 | 246 | if flush: 247 | printer.flushASCII() 248 | 249 | if break_size is not None and break_size > 0: 250 | printer.printBreak(break_size) 251 | 252 | try: 253 | self.events.append(wrap_print) 254 | return True 255 | except: 256 | return False 257 | 258 | def add_print_image(self, image: PIL.Image, concentration: int=None, break_size: int=0): 259 | """ 260 | Adds simple print Image event to queue. 261 | 262 | `image` defines the input image to be printed. 263 | 264 | `concentration` defines the concentration value from range [0, 1, 2]. 265 | Set to None to ignore. 266 | 267 | `break_size` defines the break size to print after the image. Refers to 268 | `peripage.Printer.printBreak()` for value limitations. Set to None or 0 to 269 | ignore. 270 | 271 | 272 | Example: 273 | ``` 274 | printer_task.add_print_iamge(PIL.open('image.png'), concentration=2, break_size=100, flush=True) 275 | ``` 276 | """ 277 | 278 | def wrap_print(printer: peripage.Printer): 279 | if concentration is not None: 280 | printer.setConcentration(concentration) 281 | 282 | printer.printImage(image) 283 | 284 | if break_size is not None and break_size > 0: 285 | printer.printBreak(break_size) 286 | 287 | try: 288 | self.events.append(wrap_print) 289 | return True 290 | except: 291 | return False 292 | 293 | def add_print_break(self, break_size: int=0): 294 | """ 295 | Adds simple print break event to queue. 296 | 297 | `break_size` defines the break size to print after the image. Refers to 298 | `peripage.Printer.printBreak()` for value limitations. Set to None or 0 to 299 | ignore. 300 | 301 | 302 | Example: 303 | ``` 304 | printer_task.add_print_break(200) 305 | ``` 306 | """ 307 | 308 | if break_size is not None and break_size > 0: 309 | try: 310 | self.events.append(lambda p: p.printBreak(break_size)) 311 | return True 312 | except: 313 | return False 314 | return False 315 | 316 | def add_print_flush_ascii(self): 317 | """ 318 | Adds simple flush ASCII buffer event to queue. 319 | 320 | 321 | Example: 322 | ``` 323 | printer_task.add_print_flush_ascii(200) 324 | ``` 325 | """ 326 | 327 | try: 328 | self.events.append(lambda p: p.flushASCII()) 329 | return True 330 | except: 331 | return False 332 | 333 | def add_print_concentration(self, concentration: int=None): 334 | """ 335 | Adds concentration change event to queue. 336 | 337 | `concentration` defines the concentration value from range [0, 1, 2]. 338 | Set to None to ignore. 339 | 340 | 341 | Example: 342 | ``` 343 | printer_task.add_print_concentration(1) 344 | ``` 345 | """ 346 | 347 | if concentration is not None: 348 | try: 349 | self.events.append(lambda p: p.setConcentration(concentration)) 350 | return True 351 | except: 352 | return False 353 | return False 354 | 355 | def clear_tasks(self): 356 | """ 357 | Remove all tasks from queue 358 | """ 359 | 360 | if self.events: 361 | self.events.clear() 362 | 363 | def get_task_count(self): 364 | """ 365 | Returns rest task count 366 | """ 367 | 368 | return len(self.events) if self.events else 0 369 | -------------------------------------------------------------------------------- /print-server/scripts/print_ascii_clipboard.bat: -------------------------------------------------------------------------------- 1 | python print_ascii_clipboard.py 2 | -------------------------------------------------------------------------------- /print-server/scripts/print_ascii_clipboard.py: -------------------------------------------------------------------------------- 1 | import pyperclip 2 | import requests 3 | import sys 4 | 5 | SERVER_ADDR = 'http://127.0.0.1:11001' 6 | BREAK = 1 # Enable/disable 7 | CONCENTRATION = 2 # Value (0-2) 8 | SECRET_KEY = '1234567890' 9 | 10 | s = pyperclip.paste().strip().replace('\t', ' ') 11 | s = ''.join([i for i in s if (31 < ord(i) or ord(i) == 10) and ord(i) < 127]) 12 | print(s) 13 | 14 | r = requests.post( 15 | url=f'{SERVER_ADDR}/print_ascii?print_break={BREAK}&print_concentration={CONCENTRATION}&secret={SECRET_KEY}', 16 | data=s 17 | ) 18 | 19 | print(r.status_code, r.text) 20 | -------------------------------------------------------------------------------- /print-server/scripts/print_image_clipboard.bat: -------------------------------------------------------------------------------- 1 | python "%~p0print_image_clipboard.py" 2 | -------------------------------------------------------------------------------- /print-server/scripts/print_image_clipboard.py: -------------------------------------------------------------------------------- 1 | import secrets 2 | import requests 3 | import sys 4 | import PIL.ImageGrab 5 | import secrets 6 | import traceback 7 | import os 8 | 9 | SERVER_ADDR = 'http://127.0.0.1:11001' 10 | BREAK = 1 # Enable/disable 11 | CONCENTRATION = 2 # Value (0-2) 12 | SECRET_KEY = '1234567890' 13 | 14 | # Detect type: list[str] or image 15 | 16 | im = PIL.ImageGrab.grabclipboard() 17 | 18 | if isinstance(im, list): 19 | im = im[0] 20 | 21 | if not (im.endswith('.png') or im.endswith('.jpg') or im.endswith('.jpeg')): 22 | raise RuntimeError('Invalid file type') 23 | 24 | try: 25 | r = requests.post( 26 | url=f'{SERVER_ADDR}/print_image?print_break={BREAK}&print_concentration={CONCENTRATION}&secret={SECRET_KEY}', 27 | files={ 28 | 'image': open(im, 'rb') 29 | } 30 | ) 31 | 32 | print(r.status_code, r.text) 33 | except: 34 | traceback.print_exc() 35 | 36 | else: 37 | temp_name = f'{secrets.token_bytes(16).hex()}-temp.png' 38 | im.save(temp_name, 'PNG') 39 | 40 | try: 41 | r = requests.post( 42 | url=f'{SERVER_ADDR}/print_image?print_break={BREAK}&print_concentration={CONCENTRATION}&secret={SECRET_KEY}', 43 | files={ 44 | 'image': open(temp_name, 'rb') 45 | } 46 | ) 47 | 48 | print(r.status_code, r.text) 49 | except: 50 | traceback.print_exc() 51 | 52 | os.remove(temp_name) 53 | 54 | -------------------------------------------------------------------------------- /print-server/scripts/print_image_drag_and_drop.bat: -------------------------------------------------------------------------------- 1 | python "%~p0print_image_drag_and_drop.py" "%~1" 2 | -------------------------------------------------------------------------------- /print-server/scripts/print_image_drag_and_drop.py: -------------------------------------------------------------------------------- 1 | import requests 2 | import sys 3 | 4 | SERVER_ADDR = 'http://127.0.0.1:11001' 5 | BREAK = 1 # Enable/disable 6 | CONCENTRATION = 2 # Value (0-2) 7 | SECRET_KEY = '1234567890' 8 | 9 | r = requests.post( 10 | url=f'{SERVER_ADDR}/print_image?print_break={BREAK}&print_concentration={CONCENTRATION}&secret={SECRET_KEY}', 11 | files={ 12 | 'image': open(sys.argv[1], 'rb') 13 | } 14 | ) 15 | 16 | print(r.status_code, r.text) 17 | -------------------------------------------------------------------------------- /print_service.py: -------------------------------------------------------------------------------- 1 | # Utility for tracking printing tasks 2 | # 3 | # MIT License 4 | # 5 | # Copyright (c) 2022 bitrate16 6 | 7 | import time 8 | import threading 9 | import PIL 10 | 11 | import peripage 12 | 13 | 14 | class Repeat(): 15 | """ 16 | Interval-based code execution 17 | """ 18 | 19 | def __init__(self, interval: float, handler): 20 | self.interval = interval 21 | self.running = False 22 | self.should_stop = True 23 | self.thread = None 24 | self.handler = handler 25 | 26 | def start(self): 27 | if self.running: 28 | return False 29 | else: 30 | def handler(): 31 | self.running = True 32 | 33 | while not self.should_stop: 34 | try: 35 | self.handler() 36 | except: 37 | # XXX: Important: we are ignoring this exception 38 | pass 39 | time.sleep(self.interval) 40 | 41 | self.running = False 42 | 43 | self.should_stop = False 44 | self.thread = threading.Thread(target=handler).start() 45 | return True 46 | 47 | def stop(self): 48 | if not self.running: 49 | return False 50 | else: 51 | self.should_stop = True 52 | 53 | def set_handler(self, handler): 54 | self.handler = handler 55 | 56 | def is_running(self): 57 | return self.running 58 | 59 | 60 | class PrintService: 61 | """ 62 | This printer task autimatically handler print tasks from internal queue and 63 | maintains printer connected state. 64 | 65 | Printer processes events in another thread by proocessing single event per 66 | event_interval. 67 | 68 | If printer disconnects, this service will automatically reconnect it after 69 | event_interval and print in the same time slot. If reconnect attempts fail, 70 | it will wait given offline_interval until next connection attempt. 71 | 72 | If ping interval is over, printer will be pinged to return battery level and 73 | keep connection alive (prevent sleep). 74 | """ 75 | 76 | def __init__(self, ping_interval: float = 60, event_interval: float = 1, offline_interval: float = 1, startup_interval: float = 1, guard_ping_interval: float = 1): 77 | # Printer keep-alive check interval, seconds 78 | self.ping_interval = ping_interval 79 | 80 | # Printer event check interval, seconds 81 | self.event_interval = event_interval 82 | 83 | # Last printer ping timestamp, seconds 84 | self.last_ping_timestamp = 0 85 | 86 | # Interval to wait after printer cconnection established 87 | self.startup_interval = startup_interval 88 | 89 | # Time between reconnect attempts 90 | self.offline_interval = offline_interval 91 | 92 | # interval between ping and data sending 93 | self.guard_ping_interval = guard_ping_interval 94 | 95 | # Serive task loop 96 | self.service: Repeat = None 97 | 98 | # Instance of printer 99 | self.printer: peripage.Printer = None 100 | 101 | # Event queue 102 | self.events = [] 103 | 104 | # Indicate service failture 105 | self.service_failture = True 106 | 107 | def start(self, printer_mac: str, printer_type: peripage.PrinterType, timeout: float = 1.0, concentration: int = 1): 108 | """ 109 | Perform startup oof the service without check for previous instance running. 110 | """ 111 | 112 | def service_handler(): 113 | """ 114 | Internal event processing handler. 115 | """ 116 | 117 | initial_failture = True 118 | while self.service.is_running(): 119 | try: 120 | if not self.printer.isConnected(): 121 | raise RuntimeError('not connected') 122 | 123 | # Windows workaround 124 | try: 125 | self.printer.sock.listen() 126 | except: 127 | pass 128 | 129 | if not self.printer.isConnected(): 130 | raise RuntimeError('not connected') 131 | 132 | # If time is over, perform keep-alive procedure 133 | if time.time() > (self.last_ping_timestamp + self.ping_interval): 134 | str(self.printer.getDeviceBattery()) 135 | self.last_ping_timestamp = time.time() 136 | 137 | # Execute task handler 138 | # Task will be deleted only after correct execution without exceptions 139 | if len(self.events): 140 | 141 | if self.guard_ping_interval is not None: 142 | str(self.printer.getDeviceBattery()) 143 | self.last_ping_timestamp = time.time() 144 | 145 | time.sleep(self.guard_ping_interval) 146 | 147 | self.events[0](self.printer) 148 | self.events.pop(0) 149 | 150 | # Return on success 151 | return 152 | 153 | except: 154 | # Connection error, reinitialize connection 155 | self.service_failture = True 156 | 157 | # Wait for offline_interval before reconnects 158 | if not initial_failture: 159 | time.sleep(self.offline_interval) 160 | initial_failture = False 161 | 162 | # Disconnect 163 | try: 164 | if self.printer.isConnected(): 165 | self.printer.disconnect() 166 | except: 167 | pass 168 | 169 | # Connect 170 | try: 171 | self.printer.connect() 172 | self.printer.reset() 173 | self.printer.setConcentration(self.concentration) 174 | 175 | time.sleep(self.startup_interval) 176 | 177 | self.last_ping_timestamp = time.time() 178 | self.service_failture = False 179 | except: 180 | pass 181 | 182 | self.concentration = concentration 183 | self.printer = peripage.Printer(printer_mac, printer_type, timeout) 184 | self.last_ping_timestamp = time.time() 185 | self.events = [] 186 | self.service = Repeat(self.event_interval, service_handler) 187 | self.service.start() 188 | 189 | def stop(self): 190 | try: 191 | self.service.stop() 192 | self.printer.disconnect() 193 | except: 194 | pass 195 | 196 | def is_service_failture(self): 197 | return self.service_failture 198 | 199 | def add_print_handler(self, print_handler): 200 | """ 201 | Adds event handler to the queue. THis handler will be executed with single 202 | arguemnt - printer instance. 203 | 204 | Example: 205 | ``` 206 | printer_task.add_print_handler(lambda printer: printer.printASCII('hello')) 207 | ``` 208 | """ 209 | 210 | try: 211 | self.events.append(print_handler) 212 | return True 213 | except: 214 | return False 215 | 216 | def add_print_ascii(self, ascii_text: str, concentration: int=None, break_size: int=0, /, flush: bool = False): 217 | """ 218 | Adds simple print ASCII event to queue, additionally flushes output 219 | buffer. 220 | 221 | `ascii_text` defines the input text to be printed. 222 | 223 | `concentration` defines the concentration value from range [0, 1, 2]. 224 | Set to None to ignore. 225 | 226 | `break_size` defines the break size to print after the text. Refers to 227 | `peripage.Printer.printBreak()` for value limitations. Set to None or 0 to 228 | ignore. 229 | 230 | `flush` allows force flushing ASCII buffer. Refers to 231 | `peripage.Printer.flushASCII()`. 232 | 233 | 234 | Example: 235 | ``` 236 | printer_task.add_print_ascii('hello', concentration=2, break_size=100, flush=True) 237 | ``` 238 | """ 239 | 240 | def wrap_print(printer: peripage.Printer): 241 | if concentration is not None: 242 | printer.setConcentration(concentration) 243 | 244 | printer.printASCII(ascii_text) 245 | 246 | if flush: 247 | printer.flushASCII() 248 | 249 | if break_size is not None and break_size > 0: 250 | printer.printBreak(break_size) 251 | 252 | try: 253 | self.events.append(wrap_print) 254 | return True 255 | except: 256 | return False 257 | 258 | def add_print_image(self, image: PIL.Image, concentration: int=None, break_size: int=0): 259 | """ 260 | Adds simple print Image event to queue. 261 | 262 | `image` defines the input image to be printed. 263 | 264 | `concentration` defines the concentration value from range [0, 1, 2]. 265 | Set to None to ignore. 266 | 267 | `break_size` defines the break size to print after the image. Refers to 268 | `peripage.Printer.printBreak()` for value limitations. Set to None or 0 to 269 | ignore. 270 | 271 | 272 | Example: 273 | ``` 274 | printer_task.add_print_iamge(PIL.open('image.png'), concentration=2, break_size=100, flush=True) 275 | ``` 276 | """ 277 | 278 | def wrap_print(printer: peripage.Printer): 279 | if concentration is not None: 280 | printer.setConcentration(concentration) 281 | 282 | printer.printImage(image) 283 | 284 | if break_size is not None and break_size > 0: 285 | printer.printBreak(break_size) 286 | 287 | try: 288 | self.events.append(wrap_print) 289 | return True 290 | except: 291 | return False 292 | 293 | def add_print_break(self, break_size: int=0): 294 | """ 295 | Adds simple print break event to queue. 296 | 297 | `break_size` defines the break size to print after the image. Refers to 298 | `peripage.Printer.printBreak()` for value limitations. Set to None or 0 to 299 | ignore. 300 | 301 | 302 | Example: 303 | ``` 304 | printer_task.add_print_break(200) 305 | ``` 306 | """ 307 | 308 | if break_size is not None and break_size > 0: 309 | try: 310 | self.events.append(lambda p: p.printBreak(break_size)) 311 | return True 312 | except: 313 | return False 314 | return False 315 | 316 | def add_print_flush_ascii(self): 317 | """ 318 | Adds simple flush ASCII buffer event to queue. 319 | 320 | 321 | Example: 322 | ``` 323 | printer_task.add_print_flush_ascii(200) 324 | ``` 325 | """ 326 | 327 | try: 328 | self.events.append(lambda p: p.flushASCII()) 329 | return True 330 | except: 331 | return False 332 | 333 | def add_print_concentration(self, concentration: int=None): 334 | """ 335 | Adds concentration change event to queue. 336 | 337 | `concentration` defines the concentration value from range [0, 1, 2]. 338 | Set to None to ignore. 339 | 340 | 341 | Example: 342 | ``` 343 | printer_task.add_print_concentration(1) 344 | ``` 345 | """ 346 | 347 | if concentration is not None: 348 | try: 349 | self.events.append(lambda p: p.setConcentration(concentration)) 350 | return True 351 | except: 352 | return False 353 | return False 354 | 355 | def clear_tasks(self): 356 | """ 357 | Remove all tasks from queue 358 | """ 359 | 360 | if self.events: 361 | self.events.clear() 362 | 363 | def get_task_count(self): 364 | """ 365 | Returns rest task count 366 | """ 367 | 368 | return len(self.events) if self.events else 0 369 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | Pillow>=8.2.0 2 | argparse>=1.1 3 | PyBluez @ git+https://github.com/pybluez/pybluez@master#egg=pybluez 4 | qrcode>=6.1 5 | -------------------------------------------------------------------------------- /setup.cfg: -------------------------------------------------------------------------------- 1 | # Inside of setup.cfg 2 | [metadata] 3 | description_file = README.md 4 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | from setuptools import setup 2 | 3 | setup( 4 | name = 'peripage', 5 | packages = ['peripage'], 6 | version = '1.2', 7 | license='MIT', 8 | description = 'Utility for printing on Peripage printers via bluetooth', 9 | author = 'bitrate16', 10 | author_email = 'bitrate16@gmail.com', 11 | url = 'https://github.com/bitrate16/peripage-python', 12 | keywords = ['PERIPAGE', 'BLUETOOTH', 'THERMAL PRINTER', 'PRINTER'], 13 | install_requires=[ 14 | 'PyBluez>=0.23', 15 | 'Pillow>=8.2.0', 16 | 'argparse>=1.1', 17 | 'qrcode>=6.1', 18 | ], 19 | classifiers=[ 20 | 'Development Status :: 5 - Production/Stable', # Chose either "3 - Alpha", "4 - Beta" or "5 - Production/Stable" as the current state of your package 21 | 'Intended Audience :: Developers', 22 | 'Topic :: Software Development :: Libraries :: Python Modules', 23 | 'License :: OSI Approved :: MIT License', 24 | 'Programming Language :: Python :: 3', 25 | 'Programming Language :: Python :: 3.6', 26 | 'Programming Language :: Python :: 3.7', 27 | 'Programming Language :: Python :: 3.8', 28 | 'Programming Language :: Python :: 3.9', 29 | 'Programming Language :: Python :: 3.10', 30 | 'Programming Language :: Python :: 3.11', 31 | ], 32 | entry_points={ 33 | 'console_scripts': [ 34 | 'peripage = peripage.__main__:main' 35 | ] 36 | } 37 | ) 38 | --------------------------------------------------------------------------------