204 lines
6.8 KiB
Python
Executable File
204 lines
6.8 KiB
Python
Executable File
#!/usr/bin/env python3
|
|
"""
|
|
Barcode Reader PC Server
|
|
Catelli Srl - https://catellisrl.com
|
|
Riceve codici a barre/stringhe da app mobile e li scrive emulando la tastiera.
|
|
Include interfaccia grafica Desktop (GUI), icona di sistema (System Tray) e supporto all'avvio automatico.
|
|
"""
|
|
|
|
import argparse
|
|
import asyncio
|
|
import io
|
|
import json
|
|
import os
|
|
import platform
|
|
import socket
|
|
import sys
|
|
from datetime import datetime
|
|
|
|
from config import load_config
|
|
from server_core import BarcodeServerCore
|
|
|
|
|
|
def _configure_stdio() -> bool:
|
|
"""
|
|
Configura UTF-8 su console o reindirizza stdout/stderr su barcode_server.log
|
|
quando l'app e' avviata senza console (pythonw.exe o eseguibile --windowed).
|
|
Restituisce True se avviata in modalita' windowless (senza stdout/stderr nativi).
|
|
"""
|
|
is_windowless = sys.stdout is None or sys.stderr is None
|
|
if is_windowless:
|
|
log_handle = None
|
|
try:
|
|
from config import CONFIG_FILE
|
|
|
|
log_path = CONFIG_FILE.parent / "barcode_server.log"
|
|
log_path.parent.mkdir(parents=True, exist_ok=True)
|
|
if log_path.exists() and log_path.stat().st_size > 1_048_576:
|
|
log_path.write_text("", encoding="utf-8")
|
|
log_handle = open(log_path, "a", encoding="utf-8", errors="replace", buffering=1)
|
|
except Exception:
|
|
try:
|
|
log_handle = open(os.devnull, "w", encoding="utf-8")
|
|
except Exception:
|
|
log_handle = None
|
|
|
|
if sys.stdout is None and log_handle is not None:
|
|
sys.stdout = log_handle
|
|
if sys.stderr is None and log_handle is not None:
|
|
sys.stderr = log_handle
|
|
|
|
for stream in (sys.stdout, sys.stderr):
|
|
reconfigure = getattr(stream, "reconfigure", None)
|
|
if callable(reconfigure):
|
|
try:
|
|
reconfigure(encoding="utf-8", errors="replace")
|
|
except Exception:
|
|
pass
|
|
|
|
return is_windowless
|
|
|
|
|
|
def _show_fatal_gui_error(message: str) -> None:
|
|
"""Mostra un avviso grafico se l'avvio windowless fallisce senza terminale visibile."""
|
|
try:
|
|
import tkinter as tk
|
|
from tkinter import messagebox
|
|
|
|
root = tk.Tk()
|
|
root.withdraw()
|
|
messagebox.showerror("Barcode Reader PC Server", message)
|
|
root.destroy()
|
|
return
|
|
except Exception:
|
|
pass
|
|
|
|
if sys.platform == "win32":
|
|
try:
|
|
import ctypes
|
|
|
|
ctypes.windll.user32.MessageBoxW(0, message, "Barcode Reader PC Server", 0x10)
|
|
except Exception:
|
|
pass
|
|
|
|
|
|
def print_ascii_qr(payload: str) -> None:
|
|
"""Stampa un codice QR leggibile direttamente nel terminale."""
|
|
import qrcode
|
|
qr = qrcode.QRCode(border=1)
|
|
qr.add_data(payload)
|
|
qr.make(fit=True)
|
|
f = io.StringIO()
|
|
qr.print_ascii(out=f, invert=True)
|
|
f.seek(0)
|
|
print(f.read())
|
|
|
|
|
|
def run_cli_mode(server: BarcodeServerCore):
|
|
"""Esecuzione classica a riga di comando (Headless)."""
|
|
server.start_background()
|
|
|
|
print("=" * 64)
|
|
print(" BARCODE READER PC SERVER - CATELLI SRL")
|
|
print("=" * 64)
|
|
print(f" Piattaforma: {platform.system()} ({platform.release()})")
|
|
print(f" Nome Server: {server.server_name}")
|
|
print(f" Indirizzo Web: {server.web_url}")
|
|
print(f" Suffisso tasto: {server.config.get('suffix', 'enter').upper()}")
|
|
print(f" Modalità digitazione: {server.config.get('mode', 'type').upper()}")
|
|
pin = server.config.get("pin", "")
|
|
if pin:
|
|
print(f" PIN di protezione: {pin}")
|
|
else:
|
|
print(" PIN di protezione: Nessuno (Accesso libero sulla LAN)")
|
|
print("-" * 64)
|
|
print(" INQUADRA QUESTO QR CODE CON L'APP MOBILE PER CONNETTERTI:")
|
|
print("-" * 64)
|
|
try:
|
|
print_ascii_qr(server.pairing_payload)
|
|
except Exception as e:
|
|
print(f" (QR non stampabile nel terminale: {e})")
|
|
print("-" * 64)
|
|
print(" Server in ascolto... Porta il cursore dove desideri scrivere.")
|
|
print(" Premi CTRL+C per arrestare il server.")
|
|
print("=" * 64 + "\n")
|
|
|
|
def on_scan_cli(code, source, success):
|
|
t = datetime.now().strftime("%H:%M:%S")
|
|
status = "Digitato ✓" if success else "Fallito ✗"
|
|
print(f"[{t}] 📦 Ricevuto da {source}: '{code}' -> {status}")
|
|
|
|
server.on_scan = on_scan_cli
|
|
|
|
try:
|
|
import time
|
|
while True:
|
|
time.sleep(1)
|
|
except KeyboardInterrupt:
|
|
print("\nArresto server in corso...")
|
|
server.stop()
|
|
print("Server arrestato.")
|
|
|
|
|
|
def run_gui_mode(server: BarcodeServerCore, start_minimized: bool):
|
|
"""Avvio con interfaccia grafica moderna e System Tray."""
|
|
import tkinter as tk
|
|
from gui import ServerAppGUI
|
|
|
|
root = tk.Tk()
|
|
app = ServerAppGUI(root=root, server=server, start_minimized=start_minimized)
|
|
root.mainloop()
|
|
|
|
|
|
def main():
|
|
is_windowless = _configure_stdio()
|
|
parser = argparse.ArgumentParser(description="Barcode Reader PC Server - Catelli Srl")
|
|
parser.add_argument(
|
|
"--cli", "--headless", "--no-gui",
|
|
action="store_true",
|
|
dest="cli",
|
|
help="Avvia in modalità testuale da terminale (senza interfaccia grafica)",
|
|
)
|
|
parser.add_argument(
|
|
"--minimized",
|
|
action="store_true",
|
|
dest="minimized",
|
|
help="Avvia l'applicazione direttamente ridotta a icona nella System Tray",
|
|
)
|
|
|
|
args = parser.parse_args()
|
|
|
|
config = load_config()
|
|
server = BarcodeServerCore(config=config)
|
|
|
|
# Se esplicitamente richiesta modalità CLI o se non è presente un display (es. server Linux puro)
|
|
is_headless_env = sys.platform.startswith("linux") and not os.environ.get("DISPLAY") and not os.environ.get("WAYLAND_DISPLAY")
|
|
|
|
if args.cli or is_headless_env:
|
|
run_cli_mode(server)
|
|
else:
|
|
try:
|
|
run_gui_mode(server, start_minimized=args.minimized)
|
|
except Exception as e:
|
|
import traceback
|
|
traceback.print_exc()
|
|
if is_windowless:
|
|
_show_fatal_gui_error(
|
|
f"Impossibile avviare l'interfaccia grafica del server:\n{e}\n\n"
|
|
"Controlla il file barcode_server.log per i dettagli."
|
|
)
|
|
sys.exit(1)
|
|
|
|
print(f"\n[!] Avviso: Impossibile avviare interfaccia grafica ({e}). Fallback su modalità terminale.")
|
|
if "tkinter" in str(e).lower() or "libtk" in str(e).lower() or isinstance(e, ImportError):
|
|
print("\n[i] NOTA PER LINUX:")
|
|
print(" Per abilitare l'interfaccia grafica (GUI), installa Tkinter per la tua distribuzione:")
|
|
print(" • Arch / CachyOS / Manjaro: sudo pacman -S tk")
|
|
print(" • Ubuntu / Debian / Mint: sudo apt install python3-tk")
|
|
print(" • Fedora: sudo dnf install python3-tkinter\n")
|
|
run_cli_mode(server)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|