test_ae_connection.pyā¢5.78 kB
import socket
import json
import time
import logging
import os
from pathlib import Path
# Set up logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s'
)
# Configuration
AE_HOST = "127.0.0.1"
AE_PORT = 8250
TEMP_DIR = "C:/ae_temp"
COMMAND_FILE = os.path.join(TEMP_DIR, "command.json")
RESULT_FILE = os.path.join(TEMP_DIR, "result.json")
def test_tcp_connection():
"""Test TCP connection to After Effects"""
try:
logging.info("Attempting TCP connection to After Effects...")
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(2)
sock.connect((AE_HOST, AE_PORT))
# Send test command
test_command = {
"action": "get_project_info",
"params": {},
"confirmation_message": "Testing connection..."
}
sock.send(json.dumps(test_command).encode())
response = sock.recv(4096).decode()
result = json.loads(response)
if result.get("status") == "success":
logging.info("TCP connection successful!")
return True
else:
logging.error(f"TCP command failed: {result.get('message')}")
return False
except ConnectionRefusedError:
logging.error("TCP connection refused. After Effects might not be running or the MCP Bridge script is not active.")
return False
except socket.timeout:
logging.error("TCP connection timed out.")
return False
except Exception as e:
logging.error(f"TCP connection error: {str(e)}")
return False
finally:
sock.close()
def test_file_connection():
"""Test file-based connection to After Effects"""
try:
logging.info("Attempting file-based connection to After Effects...")
# Create temp directory if it doesn't exist
Path(TEMP_DIR).mkdir(parents=True, exist_ok=True)
# Write test command
test_command = {
"action": "get_project_info",
"params": {},
"confirmation_message": "Testing file-based connection..."
}
with open(COMMAND_FILE, 'w') as f:
json.dump(test_command, f)
# Wait for result
max_wait = 10 # seconds
start_time = time.time()
while time.time() - start_time < max_wait:
if os.path.exists(RESULT_FILE):
with open(RESULT_FILE, 'r') as f:
result = json.load(f)
# Clean up files
os.remove(COMMAND_FILE)
os.remove(RESULT_FILE)
if result.get("status") == "success":
logging.info("File-based connection successful!")
return True
else:
logging.error(f"File-based command failed: {result.get('message')}")
return False
time.sleep(0.5)
logging.error("File-based connection timed out waiting for response.")
return False
except Exception as e:
logging.error(f"File-based connection error: {str(e)}")
return False
def check_ae_installation():
"""Check if After Effects is installed and running"""
logging.info("Checking After Effects installation...")
# Check if After Effects is running
try:
import win32gui
import win32process
import psutil
def callback(hwnd, pid):
if win32process.GetWindowThreadProcessId(hwnd)[1] == pid:
window_text = win32gui.GetWindowText(hwnd)
if "After Effects" in window_text:
return True
return False
for proc in psutil.process_iter(['pid', 'name']):
if "After Effects" in proc.info['name']:
logging.info("After Effects is running!")
return True
logging.error("After Effects is not running. Please start After Effects first.")
return False
except ImportError:
logging.warning("Could not check if After Effects is running. Please make sure it's running.")
return True
def check_mcp_bridge():
"""Check if MCP Bridge script is installed"""
logging.info("Checking MCP Bridge script...")
script_path = os.path.join(os.path.dirname(os.path.dirname(__file__)), "after_effects_script", "mcp_bridge.jsx")
if not os.path.exists(script_path):
logging.error(f"MCP Bridge script not found at: {script_path}")
return False
logging.info("MCP Bridge script found!")
return True
def main():
"""Run all connection tests"""
logging.info("Starting After Effects connection tests...")
# Check installation
if not check_ae_installation():
logging.error("After Effects is not running. Please start After Effects first.")
return
# Check MCP Bridge
if not check_mcp_bridge():
logging.error("MCP Bridge script not found. Please install it first.")
return
# Test TCP connection
if test_tcp_connection():
logging.info("All tests passed! After Effects is properly connected.")
return
# If TCP fails, try file-based
logging.info("TCP connection failed, trying file-based connection...")
if test_file_connection():
logging.info("File-based connection successful! After Effects is connected.")
return
logging.error("All connection tests failed. Please check After Effects and the MCP Bridge script.")
if __name__ == "__main__":
main()