413 lines
18 KiB
Python
413 lines
18 KiB
Python
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} • 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)
|
|
|