import socket
import sys
import time

# The XML content to send (using <parameters> as in your provided XML)
xml = '''<?xml version="1.0" encoding="utf-8"?>
<package>
  <header>
    <name>LockerELSNETInfo</name>
    <version>1.0</version>
  </header>
  <parameters>
    <item>W001</item>
  </parameters>
  <userdata>xyz</userdata>
</package>'''

# Server details
host = '192.168.16.100'
port = 6771  # Default TCP port for Metra XML interface

# Frame the XML with STX (0x02) and ETX (0x03)
frame = chr(2) + xml + chr(3)

# Create socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)  # Enable TCP keep-alive
sock.settimeout(3)  # Increased timeout to 30 seconds

print(f"[{time.strftime('%Y-%m-%d %H:%M:%S')}] Attempting to connect to {host}:{port}")
try:
    # Connect to server
    sock.connect((host, port))
    print(f"[{time.strftime('%Y-%m-%d %H:%M:%S')}] Connected successfully")
except Exception as e:
    print(f"[{time.strftime('%Y-%m-%d %H:%M:%S')}] Connection error: {e}")
    sys.exit(1)

try:
    # Send the framed XML
    print(f"[{time.strftime('%Y-%m-%d %H:%M:%S')}] Sending XML:\n{frame}")
    sock.sendall(frame.encode('utf-8'))
except Exception as e:
    print(f"[{time.strftime('%Y-%m-%d %H:%M:%S')}] Send error: {e}")
    sock.close()
    sys.exit(1)

# Read the response
response = b''
try:
    print(f"[{time.strftime('%Y-%m-%d %H:%M:%S')}] Waiting for response...")
    while True:
        data = sock.recv(2048)
        if not data:
            print(f"[{time.strftime('%Y-%m-%d %H:%M:%S')}] No more data received (connection closed by server).")
            break
        response += data
        print(f"[{time.strftime('%Y-%m-%d %H:%M:%S')}] Received chunk: {data.decode('utf-8', errors='ignore')}")
    if not response:
        print(f"[{time.strftime('%Y-%m-%d %H:%M:%S')}] No response received from the server.")
except Exception as e:
    print(f"[{time.strftime('%Y-%m-%d %H:%M:%S')}] Receive error: {e}")
    sock.close()
    sys.exit(1)

# Close the socket
sock.close()

try:
    # Decode response to string
    response = response.decode('utf-8', errors='ignore')
except Exception as e:
    print(f"[{time.strftime('%Y-%m-%d %H:%M:%S')}] Decode error: {e}")
    sys.exit(1)

# Remove STX and ETX from response if present
if response.startswith(chr(2)):
    response = response[1:]
if response.endswith(chr(3)):
    response = response[:-1]

# Output the server's response
print(f"[{time.strftime('%Y-%m-%d %H:%M:%S')}] Server response:\n{response}")
