Files
quality_recticel/py_app/test_print_connection.py

161 lines
5.9 KiB
Python
Raw Blame History

This file contains invisible Unicode characters
This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/usr/bin/env python3
"""
Windows Print Service Connection Tester
Tests connectivity between Flask server and Windows Print Service
"""
import sys
import os
sys.path.append(os.path.join(os.path.dirname(__file__), 'app'))
import requests
import time
from app.print_config import WINDOWS_PRINT_SERVICE_URL, PRINT_SERVICE_TIMEOUT
def test_print_service_connection():
"""Test connection to Windows Print Service"""
print("=== Windows Print Service Connection Test ===\n")
print(f"🔍 Testing connection to: {WINDOWS_PRINT_SERVICE_URL}")
print(f"⏱️ Timeout: {PRINT_SERVICE_TIMEOUT} seconds")
print(f"🌐 From: Flask server (Linux)")
print(f"🎯 To: Windows Print Service")
print()
# Test 1: Health check
print("1⃣ Testing /health endpoint...")
try:
start_time = time.time()
response = requests.get(
f"{WINDOWS_PRINT_SERVICE_URL}/health",
timeout=PRINT_SERVICE_TIMEOUT
)
elapsed = time.time() - start_time
if response.status_code == 200:
data = response.json()
print(f" ✅ SUCCESS (Status: {response.status_code}, Time: {elapsed:.2f}s)")
print(f" 📋 Service: {data.get('service', 'Unknown')}")
print(f" 🖥️ Platform: {data.get('platform', 'Unknown')}")
print(f" 📅 Timestamp: {data.get('timestamp', 'Unknown')}")
health_ok = True
else:
print(f" ❌ FAILED (Status: {response.status_code})")
print(f" 📝 Response: {response.text}")
health_ok = False
except requests.exceptions.ConnectionError as e:
print(f" ❌ CONNECTION REFUSED")
print(f" 🔧 Error: {str(e)}")
print(f" 💡 This usually means:")
print(f" • Windows service is not running")
print(f" • Wrong IP address in configuration")
print(f" • Firewall blocking connection")
print(f" • Network routing issue")
health_ok = False
except Exception as e:
print(f" ❌ ERROR: {str(e)}")
health_ok = False
print()
# Test 2: Printers endpoint (only if health check passed)
if health_ok:
print("2⃣ Testing /printers endpoint...")
try:
response = requests.get(
f"{WINDOWS_PRINT_SERVICE_URL}/printers",
timeout=PRINT_SERVICE_TIMEOUT
)
if response.status_code == 200:
data = response.json()
printers = data.get('printers', [])
print(f" ✅ SUCCESS - Found {len(printers)} printer(s)")
for i, printer in enumerate(printers[:3]): # Show first 3
name = printer.get('name', 'Unknown') if isinstance(printer, dict) else printer
print(f" 🖨️ {i+1}. {name}")
if len(printers) > 3:
print(f" ... and {len(printers)-3} more")
else:
print(f" ❌ FAILED (Status: {response.status_code})")
except Exception as e:
print(f" ❌ ERROR: {str(e)}")
print()
# Test 3: Network diagnostics
print("3⃣ Network Diagnostics...")
# Parse URL to get host and port
try:
from urllib.parse import urlparse
parsed = urlparse(WINDOWS_PRINT_SERVICE_URL)
host = parsed.hostname
port = parsed.port or 8765
print(f" 🌐 Target Host: {host}")
print(f" 🔌 Target Port: {port}")
# Test DNS resolution
try:
import socket
ip = socket.gethostbyname(host)
print(f" 🔍 DNS Resolution: {host}{ip}")
dns_ok = True
except Exception as e:
print(f" ❌ DNS Resolution failed: {e}")
dns_ok = False
# Test raw TCP connection
if dns_ok:
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(5)
result = sock.connect_ex((host, port))
sock.close()
if result == 0:
print(f" ✅ TCP Connection: Port {port} is open")
else:
print(f" ❌ TCP Connection: Port {port} is closed or filtered")
print(f" 💡 Check Windows Firewall and service status")
except Exception as e:
print(f" ❌ TCP Test error: {e}")
except Exception as e:
print(f" ❌ URL parsing error: {e}")
print()
# Final recommendations
print("🔧 TROUBLESHOOTING RECOMMENDATIONS:")
print()
if not health_ok:
print("❌ CONNECTION FAILED - Try these steps:")
print("1. Verify Windows Print Service is running:")
print(" • Windows: sc query QualityLabelPrinting")
print(" • Or: Get-Service QualityLabelPrinting")
print()
print("2. Check Windows machine IP address:")
print(" • Windows: ipconfig | findstr IPv4")
print(" • Update WINDOWS_PRINT_SERVICE_URL in print_config.py")
print()
print("3. Test firewall:")
print(" • Windows: Allow port 8765 in Windows Firewall")
print(" • Test: telnet [WINDOWS_IP] 8765")
print()
print("4. If same machine, verify service binding:")
print(" • Service should bind to 0.0.0.0:8765 (not 127.0.0.1)")
else:
print("✅ CONNECTION SUCCESS - Print service should work!")
print("• Service is reachable and responding")
print("• Ready for label printing")
print("• Try printing labels from the web interface")
print(f"\n📝 Current Configuration:")
print(f" Service URL: {WINDOWS_PRINT_SERVICE_URL}")
print(f" Timeout: {PRINT_SERVICE_TIMEOUT}s")
return health_ok
if __name__ == "__main__":
test_print_service_connection()