12 Commits

Author SHA1 Message Date
N07070
c9a42a7b8b Fixed buggy connection to printer 2021-01-02 17:21:41 +01:00
N07070
4ed11cb078 Added files for api and web classes 2020-12-27 21:33:12 +01:00
N07070
55b763dfe8 Moved old files to archive folder 2020-12-27 21:32:51 +01:00
N07070
e6a046d4e6 Now using configuration files 2020-12-27 21:32:29 +01:00
N07070
8153bfd9ca Fixed typo 2020-12-27 21:32:08 +01:00
N07070
5ab316e9da Added configuration files 2020-12-27 21:31:02 +01:00
N07070
3fde3fd8ae Added documentation for the EPSON printer and the CUPS driver's archive, just in case someone needs it and the link dies 2020-12-27 21:29:29 +01:00
N07070
c38faa940f Updated readme, add cover and completed instructions 2020-12-27 21:10:19 +01:00
N07070
af267a20f7 Updated the .gitignore 2020-12-26 23:35:55 +01:00
N07070
b58748e671 Removed old code, added new files in src/ using classes for each moving part. 2020-12-26 23:34:22 +01:00
N07070
fbc6a09e60 Updated requirements. Use most recent version 2020-12-26 18:57:40 +01:00
N07070
e7a1e8a61f Added the virtualenv files 2020-12-26 18:55:59 +01:00
16 changed files with 245 additions and 22 deletions

3
.gitignore vendored
View File

@@ -24,6 +24,9 @@ wheels/
.installed.cfg
*.egg
MANIFEST
bin/
share/
pyvenv.cfg
# PyInstaller
# Usually these files are written by a python script from a template

View File

@@ -3,6 +3,9 @@
> Print out shit from the cloud.
![Ditherd image of a Adafruit Thermal Printer](dither_it_cover.png)
[CC-BY oomlout](https://commons.wikimedia.org/wiki/File:TPRI-01_(14335248671).jpg)
## About
This project started when I got a Thermal Printer from a friend. I don't really know if you can do anything more, but I guess it's fun.
@@ -11,39 +14,54 @@ This project started when I got a Thermal Printer from a friend. I don't really
## Requirements
To make this project work, you will need :
- [A Thermal Printer](https://www.adafruit.com/product/597)
- A Raspberry Pi
- A Thermal Printer :
- I used Adafruit's thermal printer at first, but it broke down. You can get it [here](https://www.adafruit.com/product/597).
- I then used a EPSON TM-T2OIII. It's expensive, but it's also high quality, and has better CUPS and specific library support.
- A Raspberry Pi or any computer with USB or Serial.
- Some electric wires.
- Some knowledge of the command line
- 3h of your time
- Some knowledge of the command line,
- Some knowledge of Python.
- 3h of your time, 5h if things need debugging.
- `git`, `virtualenv`,`pip` and `python` >= 3.8.6.
## Installation
Start by following the guide [here](https://learn.adafruit.com/networked-thermal-printer-using-cups-and-raspberry-pi) to install the CUPS software needed to print images. If you want, you can install it via the command line, [following this guide](https://help.ubuntu.com/lts/serverguide/cups.html).
For the EPSON TM-T20III, you can get the CUPS driver from [here](https://download.epson-biz.com/modules/pos/index.php?page=soft&scat=32). It's not specific to the printer I've been using, so you can try with other printers.
With that, you can try out your printer and print normal text, images or pdf documents for example. LittlePrynter itself does not require any other software than the ones installed with it, i.e the ones listed in the `requirements.txt` file.
For the Adafruit printer, start by following the guide [here](https://learn.adafruit.com/networked-thermal-printer-using-cups-and-raspberry-pi) to install the CUPS software needed to print images. If you want, you can install it via the command line, [following this guide](https://help.ubuntu.com/lts/serverguide/cups.html).
You can also get some information from [here](https://learn.adafruit.com/mini-thermal-receipt-printer) and [here](https://learn.adafruit.com/instant-camera-using-raspberry-pi-and-thermal-printer) if you're stuck.
Then, setup the project :
```
git clone https://git.n07070.xyz/n07070/LittlePrynter
virtualenv LittlePrynter
cd LittlePrynter
pip install -r requirements.txt
```
Now, edit `the users.json` and add a user. **Don't forget to remove the test user.**
You should see a folder named `configuration`. Enter it, and duplicate the file named `config.toml.sample`, and rename the copy to `config.toml`. Now, edit this file by following the comments in the file itself.
You can now start the web server with
```
export FLASK_APP=littleprynter.py
export FLASK_APP=main.py
flask run
```
This command should start a web server with which you can test your configuration. If you plan on exposing your printer to the Internet, and give it an IP / URL, _please, please, please_, don't run it this way. Look at Flask's documentation and read about running a production server. It's a little more work, but it will prevent your computer/server being hacked in too easily.
Voilà !
## More
If you liked this project, feel free to support my work !
[https://n07070.xyz/post/about-me/about-me/](Donations welcome :-])
[Donations welcome ! :)](https://n07070.xyz/about-me)
## Links
@@ -51,7 +69,6 @@ If you liked this project, feel free to support my work !
- [Github repo with CUPS drivers for the Adafruit Thermal Printer ( zj-58 )](https://github.com/klirichek/zj-58)
- [A link to buy one in Europe](https://rlx.sk/sk/various-boards/1829-mini-thermal-receipt-printer-adafruit-597.html)
- [Another link to buy one, direct from factory](https://www.cashinotech.com/csn-a2-58mm-mini-panel-thermal-receipt-printer_p11.html)
-
## Licence

14
configuration/config.toml Normal file
View File

@@ -0,0 +1,14 @@
# Configuration file the LittlePrynter
# Printer settings
[printer]
vendor_id = 0x04b8
device_id = 0x0e28
# Users = Password
[users]
admin = "admin"
# Secrets for flask
[secrets]
flask_secret_key = "ChÕÓhÑLa)Ù<î=F;ÑÊÝ5fV÷}º35+FâXg£Ì;Ñ58ëȤ^ìãtzº<$úÌ¢ü>A¡ÿ:--_Uc²æmÇ)ëÛòöéZ¥÷Z¯¦`,ç¶B°>Å:Zÿ¼Á@ªu-º´¬XäwYÃ`c>YÜYÏJ${_f{MJ[ÙkNzg_WZv"

View File

@@ -0,0 +1,15 @@
# Configuration file the LittlePrynter
# Printer settings
[printer]
vendor_id = "0x04b8"
device_id = "0x0e28"
# Users = Password
[users]
admin = "admin"
# Secrets for flask
# See "How to generate good secret keys" in https://flask.palletsprojects.com/en/1.1.x/quickstart/
[secrets]
flask_secret_key = "random string to do things"

Binary file not shown.

After

Width:  |  Height:  |  Size: 62 KiB

BIN
dither_it_cover.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 20 KiB

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

View File

@@ -1,13 +1,13 @@
Adafruit-Thermal==1.1.0
Click==7.0
Flask==1.0.2
Flask-Limiter==1.0.1
itsdangerous==0.24
Jinja2==2.10
limits==1.3
MarkupSafe==1.0
Pillow==5.3.0
pyserial==3.4
six==1.11.0
Unidecode==1.0.22
Werkzeug==0.14.1
Adafruit-Thermal>=1.1.0
Click>=7.0
Flask>=1.0.2
Flask-Limiter>=1.0.1
itsdangerous>=0.24
Jinja2>=2.10
limits>=1.3
MarkupSafe>=1.0
Pillow>=5.3.0
pyserial>=3.4
six>=1.11.0
Unidecode>=1.0.22
Werkzeug>=0.14.1

64
src/main.py Normal file
View File

@@ -0,0 +1,64 @@
# Welcome to the LittlePrynter's source code.
# This program expose a web interface, with user authentification, that makes it possible to print messages from the web.
# It also exposes a API, making it possible to print and interface with much of the printer's abilities.
# We first define the connection to the printer itself,
# Then we build the API around Flask,
# Then we build the web interface, using the simple Jinja2 templating.
# Following are the librairies we import,
from flask import Flask # Used for the web framework
from printer import Printer # The wrapper for the printer class
import toml # Used for the config file parsing
import pprint
# Load the configuration file
try:
configuration_file = toml.load("configuration/config.toml")
except TypeError :
print("Unable to load the config file: invalid type or is a list containing invalid types")
exit(-1)
except toml.TomlDecodeError:
print("An error occured while decoding the file")
exit(-1)
except Exception as e:
print("Error while loading file : " + str(e))
pprint.pprint(configuration_file)
# We define the app module used by Flask
app = Flask(__name__)
app.secret_key = configuration_file["secrets"]["flask_secret_key"]
# Printer connection
# Uses the class defined in the printer.py file
# Define the USB connections here.
vendor_id = configuration_file["printer"]["vendor_id"]
device_id = configuration_file["printer"]["device_id"]
printer = Printer(app)
if not printer.init_printer(vendor_id, device_id):
app.logger.error('Could not init printer, aborting.')
exit(-1)
# API routes
# The api has the following methods
# api/print/{sms,img,letter,qr,barcode}
# api/auth/{login,logout}
# api/status/{paper,ping,stats}
# If you just call the api route, you get a help back.
@app.route('/api')
def api_help():
return "Welcome to the API's help page"
@app.route('/api/print')
def index():
return "Printing..."
@app.route('/api/print/sms')
def api_print_sms():
return "Printing short message."

98
src/printer.py Normal file
View File

@@ -0,0 +1,98 @@
# Importing the module to mage the connection to the printer.
from escpos.printer import Usb, USBNotFoundError
from time import sleep, gmtime, strftime
import os.path
class Printer(object):
"""
# The connection is based on the ESC/POS library
## Connection to the USB printer
## Making sure the printer is alive
## Making sure it has paper
## Define default print settings
## Print starting message, log time of first print, cut.
## Annonce readyness : return a positive pong message.
"""
# Is the printer ready to accept a new print ?
ready = False
def __init__(self, app):
super(Printer, self).__init__()
self.app = app
self.ready = False
self.printer = None
def init_printer(self, device_id,vendor_id):
try:
p = Usb(0x04b8, 0x0e28, 0)
except USBNotFoundError as e:
self.app.logger.error("The USB device is not plugged in, aborting..." + str(e))
return False
waiting_elapsed = 10
# p.open()
# Is the printer online ? Is the communication with the printer successfull ?
while not p.is_online():
self.app.logger.debug('Waiting for printer to get online...')
sleep(1)
waiting_elapsed -= 1
if waiting_elapsed < 1:
self.app.logger.error('Printer took more than 10 seconds to get online, aborting...')
return False
# Let's check paper status.
ps = p.paper_status()
if ps == 0:
self.app.logger.error('Printer has no more paper, aborting...')
return False
elif ps == 1:
self.app.logger.warning('Printer needs paper to be changed very soon ! ')
sleep(5)
elif ps == 0:
self.app.logger.debug('Printer has paper, good to go')
# We're going to print a little text to let know that we're good, as a final check.
# p.textln("Hello world ! \nStarting up at " + strftime("%Y-%m-%d %H:%M:%S", gmtime()))
# p.set(align='center', font='a', bold=False, underline=0, width=1, height=1, density=9, invert=False, smooth=False, flip=False, double_width=False, double_height=False, custom_size=False)
# p.textln("------------------")
# p.qr("Hello World ! :)",size=1)
p.image("configuration/hello_world.png",center=True,impl='bitImageColumn')
# p.cut()
self.printer = p;
self.ready = True;
return True
def print_sms(self, msg):
clean_msg = str(msg)
if len(clean_msg) > 256 or len(clean_msg) < 10 :
self.app.logger.warning("Could not print message of this length :" + len(clean_msg))
return False
else :
self.printer.textln(strftime("%Y-%m-%d %H:%M:%S", gmtime()))
self.printer.textln(clean_msg)
def print_img(self, path):
if os.path.isfile(str(path)):
pass
else:
self.app.logger.warning("File does not exist : " + str(path))
try:
self.printer.image(path)
except Exception as e:
return e
else:
self.app.logging.debug("Printed an image : " + str(path))

12
src/web.py Normal file
View File

@@ -0,0 +1,12 @@
class web(object):
"""docstring for web."""
def __init__(self, arg):
super(web, self).__init__()
self.arg = arg
def login_page():
return "login page"
def logout_page():
return "logout"