Inizializzazione progetto Barcode Reader PC (Server Python + App Flutter per com.catellisrl)
This commit is contained in:
commit
b2cf67fdca
150 files changed
+7904
No files matched your search
Executable
+38
@@ -0,0 +1,38 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Script per creare un eseguibile standalone (Windows .exe, Linux binary, macOS binary)
|
||||
con PyInstaller in un singolo file.
|
||||
"""
|
||||
|
||||
import os
|
||||
import platform
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
|
||||
def build():
|
||||
print(f"[+] Compilazione eseguibile per {platform.system()}...")
|
||||
try:
|
||||
import PyInstaller
|
||||
except ImportError:
|
||||
print("[!] PyInstaller non installato. Installazione in corso...")
|
||||
subprocess.check_call([sys.executable, "-m", "pip", "install", "pyinstaller"])
|
||||
|
||||
cmd = [
|
||||
sys.executable,
|
||||
"-m",
|
||||
"PyInstaller",
|
||||
"--name=barcode_server",
|
||||
"--onefile",
|
||||
"--clean",
|
||||
"main.py",
|
||||
]
|
||||
|
||||
print(f"[+] Comando: {' '.join(cmd)}")
|
||||
subprocess.check_call(cmd)
|
||||
print("\n[✔] Compilazione completata con successo!")
|
||||
print(f"[✔] L'eseguibile si trova nella cartella: {os.path.abspath('dist')}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
build()
|
||||
@@ -0,0 +1,38 @@
|
||||
import json
|
||||
import os
|
||||
import secrets
|
||||
from pathlib import Path
|
||||
|
||||
CONFIG_FILE = Path(__file__).parent / "config.json"
|
||||
|
||||
DEFAULT_CONFIG = {
|
||||
"host": "0.0.0.0",
|
||||
"port": 8765,
|
||||
"udp_discovery_port": 8766,
|
||||
"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"
|
||||
"log_history": True,
|
||||
}
|
||||
|
||||
|
||||
def load_config() -> dict:
|
||||
if CONFIG_FILE.exists():
|
||||
try:
|
||||
with open(CONFIG_FILE, "r", encoding="utf-8") as f:
|
||||
data = json.load(f)
|
||||
config = {**DEFAULT_CONFIG, **data}
|
||||
return config
|
||||
except Exception as e:
|
||||
print(f"Avviso: Errore nella lettura di {CONFIG_FILE}: {e}. Uso configurazione predefinita.")
|
||||
return DEFAULT_CONFIG.copy()
|
||||
|
||||
|
||||
def save_config(config: dict) -> None:
|
||||
try:
|
||||
with open(CONFIG_FILE, "w", encoding="utf-8") as f:
|
||||
json.dump(config, f, indent=4)
|
||||
except Exception as e:
|
||||
print(f"Errore nel salvataggio della configurazione: {e}")
|
||||
@@ -0,0 +1,65 @@
|
||||
import asyncio
|
||||
import json
|
||||
import socket
|
||||
from typing import Dict, Any
|
||||
|
||||
|
||||
class DiscoveryServer:
|
||||
def __init__(self, local_ip: str, port: int, hostname: str, pin_required: bool, udp_port: int = 8766):
|
||||
self.local_ip = local_ip
|
||||
self.port = port
|
||||
self.hostname = hostname
|
||||
self.pin_required = pin_required
|
||||
self.udp_port = udp_port
|
||||
self.transport = None
|
||||
self._running = False
|
||||
|
||||
class _Protocol(asyncio.DatagramProtocol):
|
||||
def __init__(self, parent: "DiscoveryServer"):
|
||||
self.parent = parent
|
||||
|
||||
def datagram_received(self, data: bytes, addr: tuple[str, int]) -> None:
|
||||
try:
|
||||
message = data.decode("utf-8").strip()
|
||||
if "DISCOVER" in message.upper():
|
||||
response = json.dumps({
|
||||
"type": "discover_response",
|
||||
"server_name": self.parent.hostname,
|
||||
"ip": self.parent.local_ip,
|
||||
"port": self.parent.port,
|
||||
"ws_url": f"ws://{self.parent.local_ip}:{self.parent.port}/ws",
|
||||
"http_url": f"http://{self.parent.local_ip}:{self.parent.port}",
|
||||
"pin_required": self.parent.pin_required,
|
||||
}).encode("utf-8")
|
||||
self.transport.sendto(response, addr)
|
||||
except Exception as e:
|
||||
pass
|
||||
|
||||
def connection_made(self, transport: asyncio.DatagramTransport) -> None:
|
||||
self.transport = transport
|
||||
|
||||
async def start(self) -> None:
|
||||
loop = asyncio.get_running_loop()
|
||||
try:
|
||||
# Set up UDP socket with SO_REUSEADDR and SO_BROADCAST
|
||||
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
|
||||
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
|
||||
try:
|
||||
sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
|
||||
except Exception:
|
||||
pass
|
||||
sock.bind(("0.0.0.0", self.udp_port))
|
||||
sock.setblocking(False)
|
||||
|
||||
self.transport, _ = await loop.create_datagram_endpoint(
|
||||
lambda: self._Protocol(self),
|
||||
sock=sock
|
||||
)
|
||||
self._running = True
|
||||
except Exception as e:
|
||||
print(f"Avviso: Impossibile avviare il servizio UDP discovery sulla porta {self.udp_port}: {e}")
|
||||
|
||||
def stop(self) -> None:
|
||||
if self.transport:
|
||||
self.transport.close()
|
||||
self._running = False
|
||||
@@ -0,0 +1,84 @@
|
||||
import asyncio
|
||||
import sys
|
||||
import time
|
||||
from typing import Optional
|
||||
|
||||
try:
|
||||
from pynput.keyboard import Controller, Key
|
||||
_controller = Controller()
|
||||
except Exception as e:
|
||||
_controller = None
|
||||
print(f"Avviso: Impossibile inizializzare il controller pynput: {e}")
|
||||
|
||||
try:
|
||||
import pyperclip
|
||||
except ImportError:
|
||||
pyperclip = None
|
||||
|
||||
_lock = asyncio.Lock()
|
||||
|
||||
|
||||
class KeyboardSimulator:
|
||||
def __init__(self, default_suffix: str = "enter", typing_delay: float = 0.005, mode: str = "type", prefix: str = ""):
|
||||
self.default_suffix = default_suffix
|
||||
self.typing_delay = typing_delay
|
||||
self.mode = mode
|
||||
self.prefix = prefix
|
||||
self.controller = _controller
|
||||
self.is_mac = sys.platform == "darwin"
|
||||
|
||||
async def type_text(self, text: str, suffix: Optional[str] = None, mode: Optional[str] = None, prefix: Optional[str] = None) -> bool:
|
||||
"""
|
||||
Scrive il testo simulando la tastiera.
|
||||
Supporta modalità 'type' (digitazione carattere per carattere) e 'paste' (appunti + Ctrl+V / Cmd+V).
|
||||
"""
|
||||
async with _lock:
|
||||
active_prefix = prefix if prefix is not None else self.prefix
|
||||
active_suffix = suffix if suffix is not None else self.default_suffix
|
||||
active_mode = mode if mode is not None else self.mode
|
||||
|
||||
full_text = f"{active_prefix}{text}"
|
||||
|
||||
loop = asyncio.get_running_loop()
|
||||
return await loop.run_in_executor(None, self._sync_type, full_text, active_suffix, active_mode)
|
||||
|
||||
def _sync_type(self, full_text: str, suffix: str, mode: str) -> bool:
|
||||
if not self.controller:
|
||||
print("Errore: controller tastiera non disponibile!")
|
||||
return False
|
||||
|
||||
try:
|
||||
if mode == "paste" and pyperclip:
|
||||
# Modalità Incolla: copia negli appunti e invia Ctrl+V (o Cmd+V su Mac)
|
||||
pyperclip.copy(full_text)
|
||||
time.sleep(0.02)
|
||||
modifier = Key.cmd if self.is_mac else Key.ctrl
|
||||
with self.controller.pressed(modifier):
|
||||
self.controller.tap("v")
|
||||
time.sleep(0.02)
|
||||
else:
|
||||
# Modalità Digitazione Tastiera: digita carattere per carattere
|
||||
for char in full_text:
|
||||
self.controller.type(char)
|
||||
if self.typing_delay > 0:
|
||||
time.sleep(self.typing_delay)
|
||||
|
||||
# Gestione suffisso (es. Invio o Tab, tipici dei lettori barcode)
|
||||
suffix_lower = suffix.lower() if suffix else "none"
|
||||
if suffix_lower == "enter" or suffix_lower == "\\n":
|
||||
time.sleep(0.02)
|
||||
self.controller.tap(Key.enter)
|
||||
elif suffix_lower == "tab" or suffix_lower == "\\t":
|
||||
time.sleep(0.02)
|
||||
self.controller.tap(Key.tab)
|
||||
elif suffix_lower not in ("none", ""):
|
||||
# Suffisso personalizzato come stringa
|
||||
for char in suffix:
|
||||
self.controller.type(char)
|
||||
if self.typing_delay > 0:
|
||||
time.sleep(self.typing_delay)
|
||||
|
||||
return True
|
||||
except Exception as e:
|
||||
print(f"Errore durante l'emulazione della tastiera: {e}")
|
||||
return False
|
||||
Executable
+436
@@ -0,0 +1,436 @@
|
||||
#!/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.
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
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
|
||||
|
||||
|
||||
def print_ascii_qr(payload: str) -> None:
|
||||
"""Stampa un codice QR leggibile direttamente nel terminale."""
|
||||
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 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(),
|
||||
})
|
||||
|
||||
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()}")
|
||||
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(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(" Premi CTRL+C per arrestare il server.")
|
||||
print("=" * 64 + "\n")
|
||||
|
||||
try:
|
||||
while True:
|
||||
await asyncio.sleep(3600)
|
||||
except (asyncio.CancelledError, KeyboardInterrupt):
|
||||
pass
|
||||
finally:
|
||||
discovery.stop()
|
||||
await runner.cleanup()
|
||||
|
||||
|
||||
def main():
|
||||
try:
|
||||
asyncio.run(run_server())
|
||||
except KeyboardInterrupt:
|
||||
print("\nServer arrestato con successo.")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,4 @@
|
||||
aiohttp>=3.9.0
|
||||
pynput>=1.7.6
|
||||
pyperclip>=1.8.2
|
||||
qrcode>=7.4.2
|
||||
@@ -0,0 +1,16 @@
|
||||
@echo off
|
||||
REM Script di avvio per Windows
|
||||
cd /d "%~dp0"
|
||||
|
||||
if not exist "venv" (
|
||||
echo [+] Creazione ambiente virtuale Python...
|
||||
python -m venv venv
|
||||
call venv\Scripts\activate.bat
|
||||
echo [+] Installazione dipendenze...
|
||||
pip install -r requirements.txt
|
||||
) else (
|
||||
call venv\Scripts\activate.bat
|
||||
)
|
||||
|
||||
python main.py
|
||||
pause
|
||||
Executable
+16
@@ -0,0 +1,16 @@
|
||||
#!/usr/bin/env bash
|
||||
# Script di avvio per Linux e macOS
|
||||
set -e
|
||||
cd "$(dirname "$0")"
|
||||
|
||||
if [ ! -d "venv" ]; then
|
||||
echo "[+] Creazione ambiente virtuale Python..."
|
||||
python3 -m venv venv
|
||||
source venv/bin/activate
|
||||
echo "[+] Installazione dipendenze..."
|
||||
pip install -r requirements.txt
|
||||
else
|
||||
source venv/bin/activate
|
||||
fi
|
||||
|
||||
python3 main.py
|
||||
Reference in new issue
Block a user