feat(server): aggiunge GUI desktop, icona tray, switch ascolto e autostart al boot

This commit is contained in:
brontomark committed 2026-11-10 09:56:14 +01:00
1 parent 118311147d
commit 6018eaf0dd
10 files changed
+1321 -391

No files matched your search

+139
View File
@@ -0,0 +1,139 @@
import os
import sys
from pathlib import Path
APP_NAME = "BarcodeReaderServer"
PLIST_LABEL = "com.catellisrl.barcodereader"
def get_launch_command() -> list[str]:
"""Ottiene il comando eseguibile appropriato per l'avvio automatico."""
if getattr(sys, "frozen", False):
# Se compilato con PyInstaller
return [sys.executable, "--minimized"]
else:
# Se eseguito come script Python
python_exe = sys.executable
script_path = str(Path(__file__).parent / "main.py")
return [python_exe, script_path, "--minimized"]
def is_autostart_enabled() -> bool:
"""Verifica se l'avvio automatico è abilitato per il sistema operativo corrente."""
if sys.platform == "win32":
try:
import winreg
key = winreg.OpenKey(
winreg.HKEY_CURRENT_USER,
r"Software\Microsoft\Windows\CurrentVersion\Run",
0,
winreg.KEY_READ,
)
try:
winreg.QueryValueEx(key, APP_NAME)
winreg.CloseKey(key)
return True
except FileNotFoundError:
winreg.CloseKey(key)
return False
except Exception:
return False
elif sys.platform == "darwin":
plist_path = Path.home() / "Library" / "LaunchAgents" / f"{PLIST_LABEL}.plist"
return plist_path.exists()
elif sys.platform.startswith("linux"):
desktop_path = Path.home() / ".config" / "autostart" / f"{APP_NAME}.desktop"
return desktop_path.exists()
return False
def set_autostart(enabled: bool) -> bool:
"""Abilita o disabilita l'avvio automatico al boot del sistema operativo."""
cmd = get_launch_command()
try:
if sys.platform == "win32":
import winreg
key = winreg.OpenKey(
winreg.HKEY_CURRENT_USER,
r"Software\Microsoft\Windows\CurrentVersion\Run",
0,
winreg.KEY_SET_VALUE,
)
if enabled:
cmd_str = f'"{cmd[0]}"'
if len(cmd) > 1:
cmd_str += " " + " ".join(f'"{arg}"' for arg in cmd[1:])
winreg.SetValueEx(key, APP_NAME, 0, winreg.REG_SZ, cmd_str)
else:
try:
winreg.DeleteValue(key, APP_NAME)
except FileNotFoundError:
pass
winreg.CloseKey(key)
return True
elif sys.platform == "darwin":
launch_agents_dir = Path.home() / "Library" / "LaunchAgents"
plist_path = launch_agents_dir / f"{PLIST_LABEL}.plist"
if enabled:
launch_agents_dir.mkdir(parents=True, exist_ok=True)
args_xml = "\n".join(f" <string>{arg}</string>" for arg in cmd)
plist_content = f"""<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>Label</key>
<string>{PLIST_LABEL}</string>
<key>ProgramArguments</key>
<array>
{args_xml}
</array>
<key>RunAtLoad</key>
<true/>
<key>KeepAlive</key>
<false/>
<key>StandardOutPath</key>
<string>/tmp/barcode_server.log</string>
<key>StandardErrorPath</key>
<string>/tmp/barcode_server_error.log</string>
</dict>
</plist>
"""
plist_path.write_text(plist_content, encoding="utf-8")
else:
if plist_path.exists():
plist_path.unlink()
return True
elif sys.platform.startswith("linux"):
autostart_dir = Path.home() / ".config" / "autostart"
desktop_path = autostart_dir / f"{APP_NAME}.desktop"
if enabled:
autostart_dir.mkdir(parents=True, exist_ok=True)
cmd_str = " ".join(f'"{arg}"' for arg in cmd)
content = f"""[Desktop Entry]
Type=Application
Exec={cmd_str}
Hidden=false
NoDisplay=false
X-GNOME-Autostart-enabled=true
Name=Barcode Reader Server
Comment=Server emulatore tastiera per codici a barre
"""
desktop_path.write_text(content, encoding="utf-8")
else:
if desktop_path.exists():
desktop_path.unlink()
return True
except Exception as e:
print(f"Errore nella configurazione dell'autostart: {e}")
return False
return False
+6 -1
View File
@@ -1,6 +1,6 @@
import json
import os
import secrets
import socket
from pathlib import Path
CONFIG_FILE = Path(__file__).parent / "config.json"
@@ -9,11 +9,14 @@ DEFAULT_CONFIG = {
"host": "0.0.0.0",
"port": 8765,
"udp_discovery_port": 8766,
"server_name": socket.gethostname(),
"pin": "", # Empty means no PIN required; or 4-digit code
"suffix": "enter", # "enter", "tab", "none" or custom string
"prefix": "",
"typing_delay": 0.005, # Delay between keystrokes in seconds
"mode": "type", # "type" or "paste"
"listening": True, # Whether the server actively processes and types barcodes
"minimize_to_tray": True, # Close/minimize button hides to system tray
"log_history": True,
}
@@ -24,6 +27,8 @@ def load_config() -> dict:
with open(CONFIG_FILE, "r", encoding="utf-8") as f:
data = json.load(f)
config = {**DEFAULT_CONFIG, **data}
if not config.get("server_name"):
config["server_name"] = socket.gethostname()
return config
except Exception as e:
print(f"Avviso: Errore nella lettura di {CONFIG_FILE}: {e}. Uso configurazione predefinita.")
+570
View File
@@ -0,0 +1,570 @@
import io
import json
import os
import socket
import sys
import tkinter as tk
from tkinter import ttk, messagebox
import webbrowser
from datetime import datetime
from typing import Optional
from PIL import Image, ImageTk
from autostart import is_autostart_enabled, set_autostart
from config import load_config, save_config
from server_core import BarcodeServerCore, generate_qr_image
from tray import ServerTrayIcon
class ServerAppGUI:
def __init__(self, root: tk.Tk, server: BarcodeServerCore, start_minimized: bool = False):
self.root = root
self.server = server
self.config = server.config
self.root.title("Barcode Reader PC Server - Catelli Srl")
self.root.geometry("820x680")
self.root.minsize(760, 600)
self.root.configure(bg="#0F172A")
self.qr_photo: Optional[ImageTk.PhotoImage] = None
# Setup stili moderni scuri
self._setup_styles()
# Inizializza Tray Icon
self.tray = ServerTrayIcon(
on_show_window=self.show_window,
on_toggle_listening=self.toggle_listening,
on_open_web=self.open_web_dashboard,
on_quit=self.quit_app,
is_listening=self.server.is_listening,
)
self.tray.start()
# Intercetta evento chiusura finestra (X)
self.root.protocol("WM_DELETE_WINDOW", self.on_close_clicked)
# Costruisci l'interfaccia grafica
self._build_ui()
# Collega callback del server
self.server.on_scan = self._threadsafe_on_scan
self.server.on_devices_change = self._threadsafe_on_devices_change
self.server.on_status_change = self._threadsafe_on_status_change
# Avvia il server core in background
self.server.start_background()
# Se richiesto l'avvio minimizzato (es. autostart all'avvio del PC)
if start_minimized or self.config.get("start_minimized", False):
self.root.withdraw()
else:
self.root.deiconify()
def _setup_styles(self):
style = ttk.Style()
try:
style.theme_use("clam")
except Exception:
pass
# Colori Palette
bg_dark = "#0F172A"
card_bg = "#1E293B"
border_color = "#334155"
primary_color = "#0284C7"
text_primary = "#F8FAFC"
text_secondary = "#94A3B8"
style.configure(".", background=bg_dark, foreground=text_primary, font=("Segoe UI", 10))
style.configure("TNotebook", background=bg_dark, borderwidth=0)
style.configure(
"TNotebook.Tab",
background=card_bg,
foreground=text_secondary,
padding=[18, 8],
font=("Segoe UI", 10, "bold"),
borderwidth=0,
)
style.map(
"TNotebook.Tab",
background=[("selected", primary_color)],
foreground=[("selected", "#FFFFFF")],
)
style.configure("Card.TFrame", background=card_bg, relief="solid", borderwidth=1)
style.configure("Inner.TFrame", background=card_bg)
style.configure(
"Primary.TButton",
background=primary_color,
foreground="#FFFFFF",
font=("Segoe UI", 10, "bold"),
borderwidth=0,
padding=[14, 8],
)
style.map(
"Primary.TButton",
background=[("active", "#0369A1"), ("disabled", "#475569")],
)
style.configure(
"Secondary.TButton",
background=card_bg,
foreground=text_primary,
font=("Segoe UI", 10),
borderwidth=1,
padding=[12, 6],
)
style.map(
"Secondary.TButton",
background=[("active", "#334155")],
)
style.configure(
"Treeview",
background=card_bg,
foreground=text_primary,
fieldbackground=card_bg,
rowheight=26,
font=("Segoe UI", 9),
)
style.configure(
"Treeview.Heading",
background="#0F172A",
foreground="#38BDF8",
font=("Segoe UI", 9, "bold"),
)
def _build_ui(self):
# 1. Header superiore
header = tk.Frame(self.root, bg="#1E293B", height=70, bd=1, relief="solid", highlightbackground="#334155")
header.pack(fill="x", side="top", padx=16, pady=12)
# Titolo e sottotitolo
title_box = tk.Frame(header, bg="#1E293B")
title_box.pack(side="left", padx=16, pady=10)
title_lbl = tk.Label(
title_box,
text="Barcode Reader PC Server",
font=("Segoe UI", 16, "bold"),
fg="#38BDF8",
bg="#1E293B",
)
title_lbl.pack(anchor="w")
sub_lbl = tk.Label(
title_box,
text="Catelli Srl • Ricezione e digitazione automatica codici a barre",
font=("Segoe UI", 9),
fg="#94A3B8",
bg="#1E293B",
)
sub_lbl.pack(anchor="w")
# Controlli di stato a destra
status_box = tk.Frame(header, bg="#1E293B")
status_box.pack(side="right", padx=16, pady=10)
self.status_badge = tk.Label(
status_box,
text="● IN ASCOLTO",
font=("Segoe UI", 11, "bold"),
fg="#10B981",
bg="#064E3B",
padx=12,
pady=4,
)
self.status_badge.pack(side="left", padx=(0, 10))
self.btn_toggle = tk.Button(
status_box,
text="Metti in Pausa",
font=("Segoe UI", 9, "bold"),
bg="#334155",
fg="white",
activebackground="#475569",
activeforeground="white",
relief="flat",
padx=12,
pady=4,
command=self.toggle_listening,
cursor="hand2",
)
self.btn_toggle.pack(side="left")
# 2. Notebook a schede
self.notebook = ttk.Notebook(self.root)
self.notebook.pack(fill="both", expand=True, padx=16, pady=(0, 12))
# Scheda 1: Dashboard
self.tab_dashboard = tk.Frame(self.notebook, bg="#0F172A")
self.notebook.add(self.tab_dashboard, text=" Dashboard & Dispositivi ")
self._build_dashboard_tab(self.tab_dashboard)
# Scheda 2: Impostazioni
self.tab_settings = tk.Frame(self.notebook, bg="#0F172A")
self.notebook.add(self.tab_settings, text=" Impostazioni Server ")
self._build_settings_tab(self.tab_settings)
def _build_dashboard_tab(self, parent: tk.Frame):
# Frame superiore a due colonne
top_frame = tk.Frame(parent, bg="#0F172A")
top_frame.pack(fill="x", pady=12)
# Colonna Sinistra: QR Code per Pairing rapido
qr_card = tk.Frame(top_frame, bg="#1E293B", bd=1, relief="solid", highlightbackground="#334155")
qr_card.pack(side="left", fill="both", expand=True, padx=(0, 8))
qr_title = tk.Label(qr_card, text="PAIRING RAPIDO CON APP", font=("Segoe UI", 10, "bold"), fg="#38BDF8", bg="#1E293B")
qr_title.pack(anchor="w", padx=14, pady=(12, 6))
self.qr_label = tk.Label(qr_card, bg="#FFFFFF", padx=8, pady=8)
self.qr_label.pack(pady=6)
self._refresh_qr_display()
qr_help = tk.Label(
qr_card,
text="Inquadra il QR con l'app per collegarti istantaneamente",
font=("Segoe UI", 9),
fg="#94A3B8",
bg="#1E293B",
)
qr_help.pack(pady=(0, 10))
# Colonna Destra: Informazioni di Rete & Dispositivi
info_card = tk.Frame(top_frame, bg="#1E293B", bd=1, relief="solid", highlightbackground="#334155")
info_card.pack(side="right", fill="both", expand=True, padx=(8, 0))
info_title = tk.Label(info_card, text="STATO SERVER & RETE", font=("Segoe UI", 10, "bold"), fg="#38BDF8", bg="#1E293B")
info_title.pack(anchor="w", padx=14, pady=(12, 10))
grid_box = tk.Frame(info_card, bg="#1E293B")
grid_box.pack(fill="x", padx=14)
self.lbl_ip = self._create_info_row(grid_box, 0, "Indirizzo IP PC:", self.server.local_ip)
self.lbl_port = self._create_info_row(grid_box, 1, "Porta Server:", str(self.server.port))
self.lbl_name = self._create_info_row(grid_box, 2, "Nome Server:", self.server.server_name)
pin_val = self.config.get("pin") or "Nessuno (Libero)"
self.lbl_pin = self._create_info_row(grid_box, 3, "PIN Sicurezza:", pin_val)
# Azioni rapide
btn_box = tk.Frame(info_card, bg="#1E293B")
btn_box.pack(fill="x", padx=14, pady=16)
btn_copy_ip = tk.Button(
btn_box,
text="Copia IP",
bg="#334155",
fg="white",
relief="flat",
padx=10,
pady=4,
command=self._copy_ip_to_clipboard,
cursor="hand2",
)
btn_copy_ip.pack(side="left", padx=(0, 8))
btn_web = tk.Button(
btn_box,
text="Apri Dashboard Web",
bg="#0284C7",
fg="white",
font=("Segoe UI", 9, "bold"),
relief="flat",
padx=10,
pady=4,
command=self.open_web_dashboard,
cursor="hand2",
)
btn_web.pack(side="left")
# Dispositivi connessi
dev_lbl = tk.Label(info_card, text="DISPOSITIVI CONNESSI AL MOMENTO:", font=("Segoe UI", 9, "bold"), fg="#94A3B8", bg="#1E293B")
dev_lbl.pack(anchor="w", padx=14, pady=(6, 4))
self.lbl_devices = tk.Label(
info_card,
text="Nessun dispositivo mobile collegato.",
font=("Segoe UI", 9),
fg="#64748B",
bg="#1E293B",
)
self.lbl_devices.pack(anchor="w", padx=14, pady=(0, 12))
# Sezione Inferiore: Registro Scansioni Live
log_card = tk.Frame(parent, bg="#1E293B", bd=1, relief="solid", highlightbackground="#334155")
log_card.pack(fill="both", expand=True, pady=(4, 0))
log_header = tk.Frame(log_card, bg="#1E293B")
log_header.pack(fill="x", padx=14, pady=8)
log_title = tk.Label(log_header, text="REGISTRO SCANSIONI DIGITATE IN TEMPO REALE", font=("Segoe UI", 10, "bold"), fg="#38BDF8", bg="#1E293B")
log_title.pack(side="left")
btn_clear_log = tk.Button(
log_header,
text="Pulisci Elenco",
bg="#334155",
fg="#94A3B8",
relief="flat",
padx=8,
pady=2,
command=self._clear_scan_log,
cursor="hand2",
)
btn_clear_log.pack(side="right")
# Tabella Treeview
columns = ("time", "source", "code", "status")
self.tree = ttk.Treeview(log_card, columns=columns, show="headings", height=7)
self.tree.heading("time", text="Orario")
self.tree.heading("source", text="Dispositivo")
self.tree.heading("code", text="Codice Barcode")
self.tree.heading("status", text="Stato")
self.tree.column("time", width=80, anchor="center")
self.tree.column("source", width=140, anchor="w")
self.tree.column("code", width=360, anchor="w")
self.tree.column("status", width=100, anchor="center")
scroll = ttk.Scrollbar(log_card, orient="vertical", command=self.tree.yview)
self.tree.configure(yscrollcommand=scroll.set)
self.tree.pack(side="left", fill="both", expand=True, padx=(14, 0), pady=(0, 10))
scroll.pack(side="right", fill="y", padx=(0, 14), pady=(0, 10))
def _create_info_row(self, parent: tk.Frame, row: int, label: str, value: str) -> tk.Label:
lbl = tk.Label(parent, text=label, font=("Segoe UI", 9), fg="#94A3B8", bg="#1E293B")
lbl.grid(row=row, column=0, sticky="w", pady=2)
val_lbl = tk.Label(parent, text=value, font=("Segoe UI", 9, "bold"), fg="#F8FAFC", bg="#1E293B")
val_lbl.grid(row=row, column=1, sticky="w", padx=10, pady=2)
return val_lbl
def _build_settings_tab(self, parent: tk.Frame):
container = tk.Frame(parent, bg="#1E293B", bd=1, relief="solid", highlightbackground="#334155")
container.pack(fill="both", expand=True, padx=8, pady=12)
# Variabili Tkinter
self.var_name = tk.StringVar(value=self.config.get("server_name", socket.gethostname()))
self.var_pin = tk.StringVar(value=self.config.get("pin", ""))
self.var_port = tk.StringVar(value=str(self.config.get("port", 8765)))
self.var_suffix = tk.StringVar(value=self.config.get("suffix", "enter"))
self.var_mode = tk.StringVar(value=self.config.get("mode", "type"))
self.var_autostart = tk.BooleanVar(value=is_autostart_enabled())
self.var_tray = tk.BooleanVar(value=self.config.get("minimize_to_tray", True))
pad_x = 24
pad_y = 6
# Sezione Identità Server
lbl_sec1 = tk.Label(container, text="IDENTITÀ E SICUREZZA", font=("Segoe UI", 11, "bold"), fg="#38BDF8", bg="#1E293B")
lbl_sec1.pack(anchor="w", padx=pad_x, pady=(16, 8))
f_name = tk.Frame(container, bg="#1E293B")
f_name.pack(fill="x", padx=pad_x, pady=pad_y)
tk.Label(f_name, text="Nome Computer (visibile sull'app mobile):", width=36, anchor="w", fg="#F8FAFC", bg="#1E293B").pack(side="left")
entry_name = tk.Entry(f_name, textvariable=self.var_name, font=("Segoe UI", 10), bg="#0F172A", fg="white", insertbackground="white", relief="solid", bd=1)
entry_name.pack(side="left", fill="x", expand=True)
f_pin = tk.Frame(container, bg="#1E293B")
f_pin.pack(fill="x", padx=pad_x, pady=pad_y)
tk.Label(f_pin, text="Codice PIN di sicurezza (lascia vuoto per disattivare):", width=36, anchor="w", fg="#F8FAFC", bg="#1E293B").pack(side="left")
entry_pin = tk.Entry(f_pin, textvariable=self.var_pin, font=("Segoe UI", 10), bg="#0F172A", fg="white", insertbackground="white", relief="solid", bd=1)
entry_pin.pack(side="left", fill="x", expand=True)
f_port = tk.Frame(container, bg="#1E293B")
f_port.pack(fill="x", padx=pad_x, pady=pad_y)
tk.Label(f_port, text="Porta di ascolto (default 8765):", width=36, anchor="w", fg="#F8FAFC", bg="#1E293B").pack(side="left")
entry_port = tk.Entry(f_port, textvariable=self.var_port, font=("Segoe UI", 10), bg="#0F172A", fg="white", insertbackground="white", relief="solid", bd=1)
entry_port.pack(side="left", width=120)
# Sezione Emulazione Tastiera
lbl_sec2 = tk.Label(container, text="COMPORTAMENTO EMULAZIONE TASTIERA", font=("Segoe UI", 11, "bold"), fg="#38BDF8", bg="#1E293B")
lbl_sec2.pack(anchor="w", padx=pad_x, pady=(16, 8))
f_suffix = tk.Frame(container, bg="#1E293B")
f_suffix.pack(fill="x", padx=pad_x, pady=pad_y)
tk.Label(f_suffix, text="Tasto finale dopo ogni scansione:", width=36, anchor="w", fg="#F8FAFC", bg="#1E293B").pack(side="left")
r1 = tk.Radiobutton(f_suffix, text="Tasto Invio (Enter)", variable=self.var_suffix, value="enter", bg="#1E293B", fg="#F8FAFC", selectcolor="#0F172A", activebackground="#1E293B")
r2 = tk.Radiobutton(f_suffix, text="Tasto Tabulatore (Tab)", variable=self.var_suffix, value="tab", bg="#1E293B", fg="#F8FAFC", selectcolor="#0F172A", activebackground="#1E293B")
r3 = tk.Radiobutton(f_suffix, text="Nessun tasto", variable=self.var_suffix, value="none", bg="#1E293B", fg="#F8FAFC", selectcolor="#0F172A", activebackground="#1E293B")
r1.pack(side="left", padx=4)
r2.pack(side="left", padx=4)
r3.pack(side="left", padx=4)
f_mode = tk.Frame(container, bg="#1E293B")
f_mode.pack(fill="x", padx=pad_x, pady=pad_y)
tk.Label(f_mode, text="Modalità di scrittura:", width=36, anchor="w", fg="#F8FAFC", bg="#1E293B").pack(side="left")
m1 = tk.Radiobutton(f_mode, text="Digitazione tastiera reale (Consigliato)", variable=self.var_mode, value="type", bg="#1E293B", fg="#F8FAFC", selectcolor="#0F172A", activebackground="#1E293B")
m2 = tk.Radiobutton(f_mode, text="Incolla veloce da appunti (Ctrl+V / Cmd+V)", variable=self.var_mode, value="paste", bg="#1E293B", fg="#F8FAFC", selectcolor="#0F172A", activebackground="#1E293B")
m1.pack(side="left", padx=4)
m2.pack(side="left", padx=4)
# Sezione Sistema & Tray
lbl_sec3 = tk.Label(container, text="AVVIO AUTOMATICO E TRAY", font=("Segoe UI", 11, "bold"), fg="#38BDF8", bg="#1E293B")
lbl_sec3.pack(anchor="w", padx=pad_x, pady=(16, 8))
chk_autostart = tk.Checkbutton(
container,
text="Avvia automaticamente all'avvio del sistema operativo (Login / Boot)",
variable=self.var_autostart,
bg="#1E293B",
fg="#F8FAFC",
selectcolor="#0F172A",
activebackground="#1E293B",
font=("Segoe UI", 10),
)
chk_autostart.pack(anchor="w", padx=pad_x, pady=3)
chk_tray = tk.Checkbutton(
container,
text="Alla chiusura (X) riduci nel vassoio di sistema (System Tray Icon) invece di terminare",
variable=self.var_tray,
bg="#1E293B",
fg="#F8FAFC",
selectcolor="#0F172A",
activebackground="#1E293B",
font=("Segoe UI", 10),
)
chk_tray.pack(anchor="w", padx=pad_x, pady=3)
# Pulsante Salva
btn_save = tk.Button(
container,
text="Salva ed Applica Impostazioni",
font=("Segoe UI", 11, "bold"),
bg="#0284C7",
fg="white",
relief="flat",
padx=20,
pady=10,
command=self._save_settings_action,
cursor="hand2",
)
btn_save.pack(anchor="w", padx=pad_x, pady=(24, 16))
def _refresh_qr_display(self):
try:
buffer = generate_qr_image(self.server.pairing_payload)
pil_img = Image.open(buffer).resize((180, 180), Image.Resampling.LANCZOS)
self.qr_photo = ImageTk.PhotoImage(pil_img)
self.qr_label.configure(image=self.qr_photo)
except Exception as e:
print(f"Errore generazione QR per interfaccia: {e}")
def _copy_ip_to_clipboard(self):
self.root.clipboard_clear()
self.root.clipboard_append(self.server.local_ip)
messagebox.showinfo("Copia", f"Indirizzo IP ({self.server.local_ip}) copiato negli appunti!")
def _clear_scan_log(self):
for item in self.tree.get_children():
self.tree.delete(item)
def _save_settings_action(self):
try:
port = int(self.var_port.get().strip())
except ValueError:
messagebox.showerror("Errore", "La porta deve essere un numero valido (es. 8765)")
return
new_config = {
"server_name": self.var_name.get().strip() or socket.gethostname(),
"pin": self.var_pin.get().strip(),
"port": port,
"suffix": self.var_suffix.get(),
"mode": self.var_mode.get(),
"minimize_to_tray": self.var_tray.get(),
}
# Gestione Autostart
autostart_desired = self.var_autostart.get()
if autostart_desired != is_autostart_enabled():
set_autostart(autostart_desired)
# Applica modifiche al server
self.server.update_settings(new_config)
# Aggiorna label interfaccia
self.lbl_name.configure(text=self.server.server_name)
pin_text = new_config["pin"] if new_config["pin"] else "Nessuno (Libero)"
self.lbl_pin.configure(text=pin_text)
self.lbl_port.configure(text=str(port))
self._refresh_qr_display()
messagebox.showinfo("Impostazioni", "Impostazioni salvate ed applicate con successo!")
def toggle_listening(self):
new_state = not self.server.is_listening
self.server.set_listening(new_state)
self.tray.update_status(new_state)
self._update_status_ui(new_state)
def _update_status_ui(self, is_listening: bool):
if is_listening:
self.status_badge.configure(text="● IN ASCOLTO", fg="#10B981", bg="#064E3B")
self.btn_toggle.configure(text="Metti in Pausa")
else:
self.status_badge.configure(text="○ IN PAUSA", fg="#F59E0B", bg="#451A03")
self.btn_toggle.configure(text="Riprendi Ricezione")
def _threadsafe_on_status_change(self, is_listening: bool):
self.root.after(0, lambda: self._update_status_ui(is_listening))
self.root.after(0, lambda: self.tray.update_status(is_listening))
def _threadsafe_on_scan(self, code: str, source: str, success: bool):
def _add():
timestamp = datetime.now().strftime("%H:%M:%S")
status_str = "Digitato ✓" if success else "Fallito ✗"
self.tree.insert("", 0, values=(timestamp, source, code, status_str))
# Mantieni massimo 100 righe
children = self.tree.get_children()
if len(children) > 100:
self.tree.delete(children[-1])
self.root.after(0, _add)
def _threadsafe_on_devices_change(self, devices: list[str]):
def _update():
if not devices:
self.lbl_devices.configure(text="Nessun dispositivo mobile collegato.", fg="#64748B")
else:
text = f"{len(devices)} collegati: " + ", ".join(devices)
self.lbl_devices.configure(text=text, fg="#10B981")
self.root.after(0, _update)
def open_web_dashboard(self):
webbrowser.open(self.server.web_url)
def show_window(self):
self.root.after(0, self._deiconify)
def _deiconify(self):
self.root.deiconify()
self.root.lift()
self.root.focus_force()
def on_close_clicked(self):
"""Gestisce il click sul pulsante di chiusura (X)."""
if self.config.get("minimize_to_tray", True):
self.root.withdraw()
else:
self.quit_app()
def quit_app(self):
"""Arresta completamente server, tray ed esce."""
try:
self.tray.stop()
except Exception:
pass
try:
self.server.stop()
except Exception:
pass
self.root.after(100, self.root.destroy)
self.root.after(200, sys.exit)
+71 -382
View File
@@ -3,8 +3,10 @@
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
@@ -13,34 +15,14 @@ import platform
import socket
import sys
from datetime import datetime
from typing import Set
from aiohttp import web
import qrcode
from config import load_config, save_config
from discovery import DiscoveryServer
from keyboard_controller import KeyboardSimulator
connected_websockets: Set[web.WebSocketResponse] = set()
scan_history = []
def get_local_ip() -> str:
"""Trova l'indirizzo IP locale principale del PC nella rete locale."""
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
try:
s.connect(("10.255.255.255", 1))
ip = s.getsockname()[0]
except Exception:
ip = "127.0.0.1"
finally:
s.close()
return ip
from config import load_config
from server_core import BarcodeServerCore
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)
@@ -50,386 +32,93 @@ def print_ascii_qr(payload: str) -> None:
print(f.read())
def create_app(config: dict, kb: KeyboardSimulator) -> web.Application:
app = web.Application()
async def handle_index(request: web.Request) -> web.Response:
"""Dashboard web per visualizzare lo stato e testare la digitazione."""
local_ip = request.app["local_ip"]
port = request.app["port"]
pin = config.get("pin", "")
ws_url = f"ws://{local_ip}:{port}/ws"
pairing_data = json.dumps({"url": ws_url, "ip": local_ip, "port": port, "pin": pin})
html = f"""<!DOCTYPE html>
<html lang="it">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Barcode Reader PC Server</title>
<style>
* {{ box-sizing: border-box; font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif; }}
body {{ background: #0f172a; color: #f8fafc; margin: 0; padding: 24px; display: flex; flex-direction: column; align-items: center; min-height: 100vh; }}
.card {{ background: #1e293b; border-radius: 16px; padding: 28px; max-width: 640px; width: 100%; box-shadow: 0 10px 25px -5px rgba(0,0,0,0.5); margin-bottom: 24px; border: 1px solid #334155; }}
h1 {{ margin-top: 0; color: #38bdf8; font-size: 24px; display: flex; align-items: center; gap: 10px; }}
.badge {{ background: #10b981; color: #022c22; font-size: 12px; font-weight: bold; padding: 4px 10px; border-radius: 9999px; text-transform: uppercase; }}
.info-grid {{ display: grid; grid-template-columns: 1fr 1fr; gap: 16px; margin: 20px 0; }}
.info-box {{ background: #0f172a; padding: 14px; border-radius: 10px; border: 1px solid #334155; }}
.label {{ font-size: 12px; color: #94a3b8; text-transform: uppercase; margin-bottom: 4px; }}
.value {{ font-size: 16px; font-weight: 600; color: #f1f5f9; word-break: break-all; }}
.test-form {{ margin-top: 20px; display: flex; gap: 8px; }}
input[type="text"] {{ flex: 1; padding: 12px 16px; border-radius: 8px; border: 1px solid #475569; background: #0f172a; color: white; font-size: 15px; }}
button {{ background: #0284c7; color: white; border: none; padding: 12px 20px; border-radius: 8px; font-weight: 600; cursor: pointer; transition: background 0.2s; }}
button:hover {{ background: #0369a1; }}
.history {{ margin-top: 20px; max-height: 220px; overflow-y: auto; background: #0f172a; border-radius: 8px; padding: 12px; border: 1px solid #334155; }}
.history-item {{ font-family: monospace; padding: 6px 0; border-bottom: 1px solid #1e293b; display: flex; justify-content: space-between; font-size: 14px; }}
.history-item:last-child {{ border-bottom: none; }}
.time {{ color: #64748b; font-size: 12px; }}
.qr-section {{ text-align: center; margin-top: 10px; padding: 16px; background: #ffffff; border-radius: 12px; display: inline-block; }}
</style>
</head>
<body>
<div class="card">
<h1>
<span>Barcode Reader Server</span>
<span class="badge">Attivo</span>
</h1>
<p style="color: #94a3b8; font-size: 14px; margin-top: -6px;">Catelli Srl - Server di emulazione tastiera per codici a barre</p>
<div class="info-grid">
<div class="info-box">
<div class="label">Indirizzo IP PC</div>
<div class="value">{local_ip}</div>
</div>
<div class="info-box">
<div class="label">Porta</div>
<div class="value">{port}</div>
</div>
<div class="info-box">
<div class="label">Suffisso Automatico</div>
<div class="value">{config.get("suffix", "enter").upper()}</div>
</div>
<div class="info-box">
<div class="label">Modalità Digitazione</div>
<div class="value">{config.get("mode", "type").upper()}</div>
</div>
</div>
<div style="text-align: center; margin: 16px 0;">
<div class="label" style="margin-bottom: 8px;">Inquadra dall'App Mobile per Connetterti</div>
<div class="qr-section">
<img src="/api/qr" alt="QR Code Connessione" style="width: 180px; height: 180px; display: block;" />
</div>
</div>
<h3>Test di Digitazione</h3>
<p style="color: #94a3b8; font-size: 13px;">Inserisci una stringa qui sotto. Verrà digitata immediatamente emulando la tastiera.</p>
<form class="test-form" onsubmit="event.preventDefault(); sendTest();">
<input type="text" id="testInput" placeholder="Inserisci codice da digitare..." autofocus />
<button type="submit">Digita</button>
</form>
<h3 style="margin-top: 24px;">Ultime Scansioni Ricevute</h3>
<div class="history" id="historyBox">
<div style="color: #64748b; font-size: 13px; text-align: center; padding: 12px;">In attesa di scansioni da mobile...</div>
</div>
</div>
<script>
async function sendTest() {{
const input = document.getElementById('testInput');
const val = input.value;
if (!val) return;
await fetch('/api/type', {{
method: 'POST',
headers: {{ 'Content-Type': 'application/json' }},
body: JSON.stringify({{ code: val, source: 'Web Dashboard' }})
}});
input.value = '';
loadHistory();
}}
async function loadHistory() {{
try {{
const res = await fetch('/api/history');
const data = await res.json();
const box = document.getElementById('historyBox');
if (data.length === 0) {{
box.innerHTML = '<div style="color: #64748b; font-size: 13px; text-align: center; padding: 12px;">Nessuna scansione registrata</div>';
return;
}}
box.innerHTML = data.slice(-10).reverse().map(item => `
<div class="history-item">
<span><strong>${{item.code}}</strong> <span style="color:#64748b;">(${{item.source || 'Mobile'}})</span></span>
<span class="time">${{item.time}}</span>
</div>
`).join('');
}} catch(e) {{}}
}}
setInterval(loadHistory, 2000);
loadHistory();
</script>
</body>
</html>"""
return web.Response(text=html, content_type="text/html")
async def handle_qr_image(request: web.Request) -> web.Response:
"""Restituisce l'immagine PNG del codice QR di pairing."""
local_ip = request.app["local_ip"]
port = request.app["port"]
pin = config.get("pin", "")
payload = json.dumps({
"type": "barcode_server_pairing",
"url": f"ws://{local_ip}:{port}/ws",
"ip": local_ip,
"port": port,
"pin": pin,
"name": socket.gethostname(),
})
qr = qrcode.QRCode(box_size=6, border=2)
qr.add_data(payload)
qr.make(fit=True)
img = qr.make_image(fill_color="black", back_color="white")
buf = io.BytesIO()
img.save(buf, format="PNG")
buf.seek(0)
return web.Response(body=buf.read(), content_type="image/png")
async def handle_type_post(request: web.Request) -> web.Response:
"""Endpoint HTTP REST per ricevere e digitare codici."""
try:
data = await request.json()
except Exception:
return web.json_response({"error": "Payload JSON non valido"}, status=400)
code = str(data.get("code", ""))
if not code:
return web.json_response({"error": "Parametro 'code' mancante o vuoto"}, status=400)
pin = data.get("pin", "")
expected_pin = config.get("pin", "")
if expected_pin and pin != expected_pin:
return web.json_response({"error": "PIN non corretto"}, status=401)
suffix = data.get("suffix", config.get("suffix", "enter"))
mode = data.get("mode", config.get("mode", "type"))
prefix = data.get("prefix", config.get("prefix", ""))
source = data.get("source", "HTTP API")
success = await kb.type_text(code, suffix=suffix, mode=mode, prefix=prefix)
timestamp = datetime.now().strftime("%H:%M:%S")
entry = {"code": code, "time": timestamp, "source": source, "success": success}
scan_history.append(entry)
if len(scan_history) > 100:
scan_history.pop(0)
print(f"[{timestamp}] Scritto ({source}): '{code}' (Suffisso: {suffix}) -> Successo: {success}")
# Broadcast via WebSocket a tutti i client connessi per sincronizzare la cronologia
for ws in list(connected_websockets):
if not ws.closed:
try:
await ws.send_json({"type": "history_update", "item": entry})
except Exception:
pass
return web.json_response({"success": success, "code": code, "time": timestamp})
async def handle_history(request: web.Request) -> web.Response:
"""Restituisce le ultime scansioni registrate."""
return web.json_response(scan_history)
async def handle_status(request: web.Request) -> web.Response:
"""Restituisce lo stato del server."""
return web.json_response({
"status": "online",
"server_name": socket.gethostname(),
"os": platform.system(),
"local_ip": request.app["local_ip"],
"port": request.app["port"],
"suffix": config.get("suffix", "enter"),
"mode": config.get("mode", "type"),
"connected_clients": len(connected_websockets),
"pin_required": bool(config.get("pin", "")),
})
async def handle_websocket(request: web.Request) -> web.WebSocketResponse:
"""Endpoint WebSocket per streaming istantaneo bidirezionale."""
ws = web.WebSocketResponse()
await ws.prepare(request)
connected_websockets.add(ws)
client_device = "App Mobile"
print(f"\n[+] Nuovo dispositivo mobile connesso via WebSocket.")
try:
# Invia messaggio di benvenuto con info del server
await ws.send_json({
"type": "welcome",
"server_name": socket.gethostname(),
"os": platform.system(),
"suffix": config.get("suffix", "enter"),
"pin_required": bool(config.get("pin", "")),
})
async for msg in ws:
if msg.type == web.WSMsgType.TEXT:
try:
data = json.loads(msg.data)
msg_type = data.get("type", "scan")
if msg_type == "handshake":
client_device = data.get("device_name", client_device)
pin = data.get("pin", "")
expected_pin = config.get("pin", "")
if expected_pin and pin != expected_pin:
await ws.send_json({"type": "auth_error", "message": "PIN errato"})
await ws.close()
break
await ws.send_json({"type": "authenticated", "device": client_device})
print(f"[i] Dispositivo autenticato: {client_device}")
elif msg_type == "scan":
code = str(data.get("code", ""))
suffix = data.get("suffix", config.get("suffix", "enter"))
mode = data.get("mode", config.get("mode", "type"))
prefix = data.get("prefix", config.get("prefix", ""))
if code:
success = await kb.type_text(code, suffix=suffix, mode=mode, prefix=prefix)
timestamp = datetime.now().strftime("%H:%M:%S")
entry = {"code": code, "time": timestamp, "source": client_device, "success": success}
scan_history.append(entry)
if len(scan_history) > 100:
scan_history.pop(0)
print(f"[{timestamp}] 📦 Codice Ricevuto da {client_device}: '{code}' -> Digitato con successo")
# Invia ACK al dispositivo mobile
await ws.send_json({
"type": "ack",
"code": code,
"success": success,
"time": timestamp,
})
elif msg_type == "ping":
await ws.send_json({"type": "pong"})
except json.JSONDecodeError:
# Se è arrivata una stringa semplice, la gestiamo direttamente come codice
code = msg.data.strip()
if code:
success = await kb.type_text(code, suffix=config.get("suffix", "enter"))
timestamp = datetime.now().strftime("%H:%M:%S")
print(f"[{timestamp}] 📦 Codice Ricevuto: '{code}'")
await ws.send_json({"type": "ack", "code": code, "success": success})
elif msg.type == web.WSMsgType.ERROR:
print(f"[-] Errore WebSocket da {client_device}: {ws.exception()}")
finally:
connected_websockets.discard(ws)
print(f"[-] Dispositivo disconnesso: {client_device}")
return ws
app.router.add_get("/", handle_index)
app.router.add_get("/ws", handle_websocket)
app.router.add_get("/api/qr", handle_qr_image)
app.router.add_get("/api/status", handle_status)
app.router.add_get("/api/history", handle_history)
app.router.add_post("/api/type", handle_type_post)
return app
async def run_server():
config = load_config()
local_ip = get_local_ip()
port = int(config.get("port", 8765))
udp_port = int(config.get("udp_discovery_port", 8766))
pin = config.get("pin", "")
kb = KeyboardSimulator(
default_suffix=config.get("suffix", "enter"),
typing_delay=float(config.get("typing_delay", 0.005)),
mode=config.get("mode", "type"),
prefix=config.get("prefix", ""),
)
# Avvia Discovery UDP in background
discovery = DiscoveryServer(
local_ip=local_ip,
port=port,
hostname=socket.gethostname(),
pin_required=bool(pin),
udp_port=udp_port,
)
await discovery.start()
app = create_app(config, kb)
app["local_ip"] = local_ip
app["port"] = port
runner = web.AppRunner(app)
await runner.setup()
site = web.TCPSite(runner, host=config.get("host", "0.0.0.0"), port=port)
await site.start()
ws_url = f"ws://{local_ip}:{port}/ws"
http_url = f"http://{local_ip}:{port}"
pairing_payload = json.dumps({
"type": "barcode_server_pairing",
"url": ws_url,
"ip": local_ip,
"port": port,
"pin": pin,
"name": socket.gethostname(),
})
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" Indirizzo Server: {http_url}")
print(f" WebSocket Endpoint: {ws_url}")
print(f" Discovery UDP: Porta {udp_port} (Attiva)")
print(f" Suffisso tasto: {config.get('suffix', 'enter').upper()}")
print(f" Modalità digitazione: {config.get('mode', 'type').upper()}")
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}")
print(f" PIN di protezione: {pin}")
else:
print(" PIN di protezione: Nessuno (Accesso libero sulla LAN)")
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(pairing_payload)
print_ascii_qr(server.pairing_payload)
except Exception as e:
print(f" (QR non stampabile nel terminale: {e})")
print("-" * 64)
print(" In ascolto... Porta il cursore sul campo in cui desideri scrivere.")
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:
await asyncio.sleep(3600)
except (asyncio.CancelledError, KeyboardInterrupt):
pass
finally:
discovery.stop()
await runner.cleanup()
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():
try:
asyncio.run(run_server())
except KeyboardInterrupt:
print("\nServer arrestato con successo.")
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:
print(f"Avviso: Impossibile avviare interfaccia grafica ({e}). Fallback su modalità terminale.")
run_cli_mode(server)
if __name__ == "__main__":
+2
View File
@@ -2,3 +2,5 @@ aiohttp>=3.9.0
pynput>=1.7.6
pyperclip>=1.8.2
qrcode>=7.4.2
pystray>=0.19.5
pillow>=10.0.0
+1 -1
View File
@@ -12,5 +12,5 @@ if not exist "venv" (
call venv\Scripts\activate.bat
)
python main.py
python main.py %*
pause
+1 -1
View File
@@ -13,4 +13,4 @@ else
source venv/bin/activate
fi
python3 main.py
python3 main.py "$@"
+411
View File
@@ -0,0 +1,411 @@
import asyncio
import io
import json
import os
import platform
import socket
import sys
import threading
from datetime import datetime
from typing import Callable, Dict, List, Optional, Set
from aiohttp import web
import qrcode
from config import load_config, save_config
from discovery import DiscoveryServer
from keyboard_controller import KeyboardSimulator
def get_local_ip() -> str:
"""Rileva l'indirizzo IP locale principale del PC."""
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
try:
s.connect(("10.255.255.255", 1))
ip = s.getsockname()[0]
except Exception:
ip = "127.0.0.1"
finally:
s.close()
return ip
def generate_qr_image(payload: str) -> io.BytesIO:
"""Genera un'immagine PNG del codice QR in memoria."""
qr = qrcode.QRCode(
version=1,
error_correction=qrcode.constants.ERROR_CORRECT_M,
box_size=8,
border=2,
)
qr.add_data(payload)
qr.make(fit=True)
img = qr.make_image(fill_color="black", back_color="white")
buffer = io.BytesIO()
img.save(buffer, format="PNG")
buffer.seek(0)
return buffer
class BarcodeServerCore:
def __init__(
self,
config: Optional[dict] = None,
on_scan_callback: Optional[Callable[[str, str, bool], None]] = None,
on_devices_change_callback: Optional[Callable[[List[str]], None]] = None,
on_status_change_callback: Optional[Callable[[bool], None]] = None,
):
self.config = config or load_config()
self.on_scan = on_scan_callback
self.on_devices_change = on_devices_change_callback
self.on_status_change = on_status_change_callback
self.local_ip = get_local_ip()
self.port = int(self.config.get("port", 8765))
self.udp_port = int(self.config.get("udp_discovery_port", 8766))
self.server_name = self.config.get("server_name", socket.gethostname())
self.is_listening = bool(self.config.get("listening", True))
self.kb = KeyboardSimulator(
default_suffix=self.config.get("suffix", "enter"),
typing_delay=float(self.config.get("typing_delay", 0.005)),
mode=self.config.get("mode", "type"),
prefix=self.config.get("prefix", ""),
)
self.connected_websockets: Dict[web.WebSocketResponse, str] = {}
self.scan_history: List[dict] = []
self._loop: Optional[asyncio.AbstractEventLoop] = None
self._runner: Optional[web.AppRunner] = None
self._discovery: Optional[DiscoveryServer] = None
self._thread: Optional[threading.Thread] = None
self._running = False
@property
def pairing_payload(self) -> str:
ws_url = f"ws://{self.local_ip}:{self.port}/ws"
return json.dumps({
"type": "barcode_server_pairing",
"url": ws_url,
"ip": self.local_ip,
"port": self.port,
"pin": self.config.get("pin", ""),
"name": self.server_name,
})
@property
def web_url(self) -> str:
return f"http://{self.local_ip}:{self.port}"
def set_listening(self, listening: bool):
"""Attiva o sospende la ricezione e digitazione dei codici."""
self.is_listening = listening
self.config["listening"] = listening
save_config(self.config)
if self.on_status_change:
self.on_status_change(listening)
def update_settings(self, new_config: dict):
"""Aggiorna le impostazioni del server."""
self.config.update(new_config)
save_config(self.config)
self.server_name = self.config.get("server_name", socket.gethostname())
self.is_listening = bool(self.config.get("listening", True))
self.kb.default_suffix = self.config.get("suffix", "enter")
self.kb.mode = self.config.get("mode", "type")
self.kb.prefix = self.config.get("prefix", "")
if self._discovery:
self._discovery.hostname = self.server_name
self._discovery.pin_required = bool(self.config.get("pin", ""))
if self.on_status_change:
self.on_status_change(self.is_listening)
def _create_app(self) -> web.Application:
app = web.Application()
async def handle_index(request: web.Request) -> web.Response:
html = f"""<!DOCTYPE html>
<html lang="it">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Barcode Reader PC Server</title>
<style>
* {{ box-sizing: border-box; font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif; }}
body {{ background: #0f172a; color: #f8fafc; margin: 0; padding: 24px; display: flex; flex-direction: column; align-items: center; min-height: 100vh; }}
.card {{ background: #1e293b; border-radius: 16px; padding: 28px; max-width: 640px; width: 100%; box-shadow: 0 10px 25px -5px rgba(0,0,0,0.5); margin-bottom: 24px; border: 1px solid #334155; }}
h1 {{ margin-top: 0; color: #38bdf8; font-size: 24px; display: flex; align-items: center; justify-content: space-between; }}
.badge {{ font-size: 12px; font-weight: bold; padding: 4px 10px; border-radius: 9999px; text-transform: uppercase; }}
.badge-active {{ background: #10b981; color: #022c22; }}
.badge-paused {{ background: #f59e0b; color: #451a03; }}
.info-grid {{ display: grid; grid-template-columns: 1fr 1fr; gap: 16px; margin: 20px 0; }}
.info-box {{ background: #0f172a; padding: 14px; border-radius: 10px; border: 1px solid #334155; }}
.label {{ font-size: 12px; color: #94a3b8; text-transform: uppercase; margin-bottom: 4px; }}
.value {{ font-size: 16px; font-weight: 600; color: #f1f5f9; word-break: break-all; }}
.qr-section {{ text-align: center; margin: 16px 0; padding: 16px; background: #ffffff; border-radius: 12px; display: inline-block; }}
input[type="text"] {{ flex: 1; padding: 12px 16px; border-radius: 8px; border: 1px solid #475569; background: #0f172a; color: white; font-size: 15px; }}
button {{ background: #0284c7; color: white; border: none; padding: 12px 20px; border-radius: 8px; font-weight: 600; cursor: pointer; }}
button:hover {{ background: #0369a1; }}
.history {{ margin-top: 20px; max-height: 220px; overflow-y: auto; background: #0f172a; border-radius: 8px; padding: 12px; border: 1px solid #334155; }}
.history-item {{ font-family: monospace; padding: 6px 0; border-bottom: 1px solid #1e293b; display: flex; justify-content: space-between; font-size: 14px; }}
</style>
</head>
<body>
<div class="card">
<h1>
<span>Barcode Reader Server</span>
<span class="badge {'badge-active' if self.is_listening else 'badge-paused'}">
{'IN ASCOLTO' if self.is_listening else 'IN PAUSA'}
</span>
</h1>
<p style="color: #94a3b8; font-size: 14px; margin-top: -6px;">{self.server_name} &bull; Catelli Srl</p>
<div class="info-grid">
<div class="info-box"><div class="label">Indirizzo IP</div><div class="value">{self.local_ip}</div></div>
<div class="info-box"><div class="label">Porta</div><div class="value">{self.port}</div></div>
<div class="info-box"><div class="label">Dispositivi Connessi</div><div class="value">{len(self.connected_websockets)}</div></div>
<div class="info-box"><div class="label">Suffisso</div><div class="value">{self.config.get('suffix', 'enter').upper()}</div></div>
</div>
<div style="text-align: center;">
<div class="qr-section">
<img src="/api/qr" alt="QR Code di Pairing" style="width: 200px; height: 200px; display: block;" />
</div>
<p style="color: #94a3b8; font-size: 13px;">Inquadra questo codice con l'app mobile per connetterti</p>
</div>
<form style="display: flex; gap: 8px; margin-top: 16px;" onsubmit="testType(event)">
<input type="text" id="testInput" placeholder="Digita codice di test..." />
<button type="submit">Digita sul PC</button>
</form>
<div class="history">
<div style="font-size: 12px; color: #94a3b8; margin-bottom: 8px; font-weight: bold;">ULTIMI CODICI RICEVUTI:</div>
<div id="historyList">
{''.join(f'<div class="history-item"><span>{item["code"]}</span><span style="color: #64748b;">{item["time"]} ({item["source"]})</span></div>' for item in reversed(self.scan_history[-10:])) or '<div style="color: #64748b; font-size: 13px;">Nessuna scansione recente.</div>'}
</div>
</div>
</div>
<script>
async function testType(e) {{
e.preventDefault();
const input = document.getElementById('testInput');
const code = input.value.trim();
if (!code) return;
await fetch('/api/type', {{
method: 'POST',
headers: {{'Content-Type': 'application/json'}},
body: JSON.stringify({{ code: code, source: 'Web Dashboard' }})
}});
input.value = '';
setTimeout(() => location.reload(), 300);
}}
</script>
</body>
</html>"""
return web.Response(text=html, content_type="text/html")
async def handle_qr(request: web.Request) -> web.Response:
buffer = generate_qr_image(self.pairing_payload)
return web.Response(body=buffer.getvalue(), content_type="image/png")
async def handle_status(request: web.Request) -> web.Response:
return web.json_response({
"server_name": self.server_name,
"listening": self.is_listening,
"ip": self.local_ip,
"port": self.port,
"connected_devices": list(self.connected_websockets.values()),
"pin_required": bool(self.config.get("pin")),
"suffix": self.config.get("suffix", "enter"),
"mode": self.config.get("mode", "type"),
})
async def handle_history(request: web.Request) -> web.Response:
return web.json_response(self.scan_history[-50:])
async def handle_type_post(request: web.Request) -> web.Response:
if not self.is_listening:
return web.json_response({"status": "paused", "message": "Server in pausa"}, status=503)
try:
data = await request.json()
code = str(data.get("code", "")).strip()
pin = str(data.get("pin", "")).strip()
source = str(data.get("source", "HTTP REST"))
required_pin = str(self.config.get("pin", "")).strip()
if required_pin and pin != required_pin:
return web.json_response({"status": "error", "message": "PIN errato"}, status=401)
if not code:
return web.json_response({"status": "error", "message": "Nessun codice fornito"}, status=400)
suffix = data.get("suffix") or self.config.get("suffix", "enter")
success = await self.kb.type_text(code, suffix=suffix)
timestamp = datetime.now().strftime("%H:%M:%S")
entry = {"code": code, "time": timestamp, "source": source, "success": success}
self.scan_history.append(entry)
if len(self.scan_history) > 150:
self.scan_history.pop(0)
if self.on_scan:
self.on_scan(code, source, success)
return web.json_response({"status": "ok", "typed": code, "success": success})
except Exception as e:
return web.json_response({"status": "error", "message": str(e)}, status=500)
async def handle_websocket(request: web.Request) -> web.WebSocketResponse:
ws = web.WebSocketResponse(heartbeat=25.0)
await ws.prepare(request)
client_name = "Dispositivo Sconosciuto"
authenticated = not bool(self.config.get("pin"))
try:
async for msg in ws:
if msg.type == web.WSMsgType.TEXT:
try:
payload = json.loads(msg.data)
msg_type = payload.get("type")
if msg_type == "handshake":
client_name = payload.get("device_name", client_name)
provided_pin = str(payload.get("pin", "")).strip()
required_pin = str(self.config.get("pin", "")).strip()
if required_pin and provided_pin != required_pin:
await ws.send_json({
"type": "auth_error",
"message": "PIN non valido",
})
await ws.close()
return ws
authenticated = True
self.connected_websockets[ws] = client_name
if self.on_devices_change:
self.on_devices_change(list(self.connected_websockets.values()))
await ws.send_json({
"type": "welcome",
"server_name": self.server_name,
"suffix": self.config.get("suffix", "enter"),
"listening": self.is_listening,
})
elif msg_type == "scan":
if not authenticated:
await ws.send_json({"type": "auth_error", "message": "Autenticazione richiesta"})
continue
if not self.is_listening:
await ws.send_json({"type": "paused", "message": "Server in pausa"})
continue
code = str(payload.get("code", "")).strip()
if code:
suffix = payload.get("suffix") or self.config.get("suffix", "enter")
success = await self.kb.type_text(code, suffix=suffix)
timestamp = datetime.now().strftime("%H:%M:%S")
entry = {"code": code, "time": timestamp, "source": client_name, "success": success}
self.scan_history.append(entry)
if len(self.scan_history) > 150:
self.scan_history.pop(0)
if self.on_scan:
self.on_scan(code, client_name, success)
await ws.send_json({
"type": "ack",
"code": code,
"success": success,
"time": timestamp,
})
elif msg_type == "ping":
await ws.send_json({"type": "pong"})
except json.JSONDecodeError:
if self.is_listening and authenticated:
code = msg.data.strip()
if code:
success = await self.kb.type_text(code, suffix=self.config.get("suffix", "enter"))
timestamp = datetime.now().strftime("%H:%M:%S")
if self.on_scan:
self.on_scan(code, client_name, success)
await ws.send_json({"type": "ack", "code": code, "success": success})
finally:
self.connected_websockets.pop(ws, None)
if self.on_devices_change:
self.on_devices_change(list(self.connected_websockets.values()))
return ws
app.router.add_get("/", handle_index)
app.router.add_get("/ws", handle_websocket)
app.router.add_get("/api/qr", handle_qr)
app.router.add_get("/api/status", handle_status)
app.router.add_get("/api/history", handle_history)
app.router.add_post("/api/type", handle_type_post)
return app
async def _async_start(self):
self._loop = asyncio.get_running_loop()
# Avvio Discovery UDP
self._discovery = DiscoveryServer(
local_ip=self.local_ip,
port=self.port,
hostname=self.server_name,
pin_required=bool(self.config.get("pin")),
udp_port=self.udp_port,
)
await self._discovery.start()
# Avvio server web/ws
app = self._create_app()
self._runner = web.AppRunner(app)
await self._runner.setup()
site = web.TCPSite(self._runner, host=self.config.get("host", "0.0.0.0"), port=self.port)
await site.start()
self._running = True
while self._running:
await asyncio.sleep(1)
def start_background(self):
"""Avvia il server in un thread separato in background."""
if self._thread and self._thread.is_alive():
return
def runner():
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
try:
loop.run_until_complete(self._async_start())
except Exception as e:
print(f"Errore server core: {e}")
finally:
loop.close()
self._thread = threading.Thread(target=runner, daemon=True)
self._thread.start()
def stop(self):
"""Arresta il server e libera le porte."""
self._running = False
if self._discovery:
self._discovery.stop()
if self._runner and self._loop:
asyncio.run_coroutine_threadsafe(self._runner.cleanup(), self._loop)
+108
View File
@@ -0,0 +1,108 @@
import threading
import webbrowser
from typing import Callable, Optional
from PIL import Image, ImageDraw
import pystray
from pystray import MenuItem as item, Menu
def create_tray_image(listening: bool = True) -> Image.Image:
"""Genera l'icona per la System Tray (64x64) con stato dinamico."""
img = Image.new("RGBA", (64, 64), (0, 0, 0, 0))
draw = ImageDraw.Draw(img)
# Base scura arrotondata
draw.rounded_rectangle((4, 4, 60, 60), radius=12, fill="#0F172A", outline="#334155", width=2)
# Barre del codice a barre stilizzato in azzurro
bar_color = "#38BDF8"
bars = [(14, 2), (19, 4), (26, 2), (31, 5), (39, 2), (44, 4)]
for x, w in bars:
draw.rectangle((x, 18, x + w - 1, 46), fill=bar_color)
# Badge circolare di stato (Verde per In Ascolto, Ambra per In Pausa)
dot_color = "#10B981" if listening else "#F59E0B"
draw.ellipse((42, 42, 58, 58), fill=dot_color, outline="#0F172A", width=2)
return img
class ServerTrayIcon:
def __init__(
self,
on_show_window: Callable[[], None],
on_toggle_listening: Callable[[], None],
on_open_web: Callable[[], None],
on_quit: Callable[[], None],
is_listening: bool = True,
):
self.on_show_window = on_show_window
self.on_toggle_listening = on_toggle_listening
self.on_open_web = on_open_web
self.on_quit = on_quit
self.is_listening = is_listening
self.icon: Optional[pystray.Icon] = None
self._thread: Optional[threading.Thread] = None
def _build_menu(self) -> Menu:
status_label = "● Stato: IN ASCOLTO" if self.is_listening else "○ Stato: IN PAUSA"
toggle_label = "Metti in Pausa Ricezione" if self.is_listening else "Riprendi Ricezione Codici"
return Menu(
item("Mostra Server Barcode", self._on_show, default=True),
Menu.SEPARATOR,
item(status_label, lambda icon, item: None, enabled=False),
item(toggle_label, self._on_toggle),
item("Apri Dashboard Web", self._on_web),
Menu.SEPARATOR,
item("Esci Definitivamente", self._on_exit),
)
def _on_show(self, icon, item):
if self.on_show_window:
self.on_show_window()
def _on_toggle(self, icon, item):
if self.on_toggle_listening:
self.on_toggle_listening()
def _on_web(self, icon, item):
if self.on_open_web:
self.on_open_web()
def _on_exit(self, icon, item):
if self.on_quit:
self.on_quit()
def update_status(self, is_listening: bool):
"""Aggiorna l'icona e il menu della tray dinamicamente."""
self.is_listening = is_listening
if self.icon:
self.icon.icon = create_tray_image(is_listening)
self.icon.menu = self._build_menu()
self.icon.title = f"Barcode Reader Server ({'In ascolto' if is_listening else 'In pausa'})"
def start(self):
"""Avvia l'icona di notifica nella tray in un thread in background."""
image = create_tray_image(self.is_listening)
self.icon = pystray.Icon(
name="barcode_reader_server",
icon=image,
title="Barcode Reader Server",
menu=self._build_menu(),
)
def run_tray():
try:
self.icon.run()
except Exception as e:
print(f"Avviso Tray: {e}")
self._thread = threading.Thread(target=run_tray, daemon=True)
self._thread.start()
def stop(self):
"""Rimuove l'icona dalla tray."""
if self.icon:
self.icon.stop()