Update little printer requirements

This commit is contained in:
nono
2025-06-23 23:08:32 +02:00
committed by n07070
parent d4a9a059bf
commit 1a1c4e2fb3
8 changed files with 311 additions and 127 deletions

View File

@@ -6,11 +6,17 @@
# Then we build the API around Flask,
# Then we build the web interface, using the simple Jinja2 templating.
# We support two modes :
# The first is a simple mode, where a computer, connected to a thermal printer, runs this program and exposes a web interface that makes use of the client's camera
# The seconde is booth mode, where a Raspberry Pi is connected to a thermal printer, a button and a flash. The web interface exists but may not be used, as the press of the button with take a picture and activate the flash while simply informing the web page.
# Following are the librairies we import,
from flask import Flask, request, render_template, flash, abort, redirect, url_for, make_response, jsonify # Used for the web framework
from flask_socketio import SocketIO
from flask_limiter import Limiter
from flask_limiter.util import get_remote_address
from printer import Printer # The wrapper for the printer class
from raspberry import Raspberry # The Raspberry pi control Class
from web import Web # Wrapper for the web routes and API
import toml # Used for the config file parsing
import pprint # To pretty print JSON
@@ -19,6 +25,7 @@ import os # For VARS from the shell.
# Variables
app = Flask(__name__)
socketio = SocketIO(app)
ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg', 'gif'}
# Load the configuration file
@@ -36,6 +43,7 @@ except Exception as e:
exit(-1)
app.logger.debug("Config file loaded !")
# Define the USB connections here.
vendor_id = configuration_file["printer"]["vendor_id"]
device_id = configuration_file["printer"]["device_id"]
@@ -68,18 +76,28 @@ app.config['TEMPLATES_AUTO_RELOAD'] = True
printer = Printer(app,0x04b8, 0x0e28)
printer.init_printer()
# Web routes
# Find out if we are running on a Raspberry Pi
rpi = Raspberry(printer, app, socketio, configuration_file['rpi']['button_gpio_port_number'], configuration_file['rpi']['indicator_gpio_port_number'], configuration_file['rpi']['flash'] )
RASPBERRY_PI_CONNECTED = rpi.is_raspberry_pi()
if RASPBERRY_PI_CONNECTED:
rpi.initialise_gpio()
#############################################################
# Web & API routes
#############################################################
web = Web(app, printer)
if __name__ == "__main__":
app.run(ssl_context='adhoc')
limiter = Limiter(
app,
key_func=get_remote_address,
get_remote_address,
app=app,
default_limits=["1500 per day", "500 per hour"]
)
)
@app.route('/')
@limiter.limit("1/second", override_defaults=False)
@@ -116,16 +134,12 @@ def api_print_sms():
txt = request.form["txt"]
sign = request.form["signature"]
except Exception as e:
app.logger.error(str(e) + " - Whoops, no forms submitted or missing signature.")
return jsonify({'message': 'Error getting the information from the form :' + e}), 500
app.logger.error("Whoops, no forms submitted or missing signature :" + str(e))
flash("Whoops, no forms submitted or missing signature : " + str(e))
return redirect(url_for("index"))
try:
web.print_sms(txt,sign)
except Exception as e:
return jsonify({'message': 'Error printing the SMS:' + e}), 500
return jsonify({'message': 'Message printed'}), 200
web.print_sms(txt,sign)
return redirect(url_for("index"))
@app.route('/api/print/img', methods=['POST'])
@limiter.limit("6/minute", override_defaults=False)
@@ -135,40 +149,61 @@ def api_print_image():
try:
sign = request.form["signature"]
except Exception as e:
app.logger.error(str(e) + " - Whoops, no forms submitted or missing signature.")
return jsonify({'message': 'Error getting the information from the form :' + e}), 500
app.logger.error("Whoops, no forms submitted or missing signature :" + str(e))
flash("Whoops, no forms submitted or missing signature : " + str(e))
return redirect(url_for("index"))
if request.method == 'POST':
# check if the post request has the file part
try:
if 'img' not in request.files:
app.logger.error("No file found. Did you use the good form ?")
return jsonify({'message': 'No file found. Did you use the good form ?'}), 500
app.logger.error("Whoops, no images submitted :" + str(e))
flash("Whoops, no images submitted : " + str(e))
else:
file = request.files['img']
except Exception as e:
app.logger.error('Error getting the files :' + e)
return jsonify({'message': 'Error getting the files :' + e}), 500
app.logger.error('Error getting the files :' + str(e))
flash('Error getting the files :' + str(e))
return redirect(url_for("index"))
# If the user does not select a file, the browser submits an
# empty file without a filename.
if file.filename == '':
app.logger.error("Submitted file has no filename !")
return jsonify({'message': "Submitted file has no filename !" + e}), 500
flash("Submitted file has no filename !")
return redirect(url_for("index"))
try:
app.logger.debug("Sending the image to the printer.")
web.print_image(file, sign)
except Exception as e:
app.logger.error("The image could not be printed : " + e )
return jsonify({'message': "The image could not be printed :" + e}), 500
app.logger.error("The image could not be printed because : " + str(e) )
flash("The image could not be printed because : " + str(e))
return redirect(url_for("index"))
else:
return jsonify({'message': "Method Not Allowed, please POST"}), 403
app.logger.debug('Bad access type to this API, please POST')
app.logger.error("Method not allowed")
flash("Method not allowed")
return redirect(url_for("index"))
flash('Picture printed ! '),
return redirect(url_for("index"))
@app.route('/api/camera/picture')
def camera_picture():
# Returns a picture taken by the camera
if RASPBERRY_PI_CONNECTED:
try:
return rpi.camera_picture()
except Exception as e:
return jsonify({'message': 'Error getting the stream : ' + e}), 500
else:
return jsonify({'message': 'No camera present'}), 500
return jsonify({'message': 'Message printed'}), 200
@app.route('/login')
@@ -195,3 +230,16 @@ def ping():
flash("🏓 Pong !",'info')
app.logger.debug('🏓 Pong !')
return redirect(url_for("index"))
@socketio.on('ping')
def handle_message(data):
app.logger.debug('Received : ' + str(data))
socketio.emit('pong',"Pong !")
@socketio.on('get_camera_status')
def camera_status():
app.logger.debug('Client asked if we had a camera')
if RASPBERRY_PI_CONNECTED:
socketio.emit("camera_status", True)
else:
socketio.emit("camera_status", False)