fusion_bridge.pyβ’3.38 kB
"""
Fusion 360 Bridge - Enables code execution from web UI
This script runs inside Fusion 360 and monitors for execution requests
"""
import adsk.core
import adsk.fusion
import traceback
import json
import os
import time
import threading
# Shared execution queue path
QUEUE_PATH = os.path.expanduser('~/fusion_mcp_queue.json')
RESULT_PATH = os.path.expanduser('~/fusion_mcp_result.json')
class FusionBridge:
"""Bridge between web UI and Fusion 360"""
def __init__(self):
self.app = adsk.core.Application.get()
self.ui = self.app.userInterface
self.running = False
self.thread = None
def start(self):
"""Start monitoring for execution requests"""
self.running = True
self.thread = threading.Thread(target=self._monitor_queue)
self.thread.daemon = True
self.thread.start()
self.ui.messageBox('Fusion MCP Bridge started!\nWeb UI can now execute code in Fusion 360.')
def stop(self):
"""Stop monitoring"""
self.running = False
if self.thread:
self.thread.join(timeout=2)
def _monitor_queue(self):
"""Monitor queue file for execution requests"""
while self.running:
try:
if os.path.exists(QUEUE_PATH):
# Read and process queue
with open(QUEUE_PATH, 'r') as f:
request = json.load(f)
# Remove queue file immediately
os.remove(QUEUE_PATH)
# Execute code
result = self._execute_code(request.get('code', ''))
# Write result
with open(RESULT_PATH, 'w') as f:
json.dump({
'success': result['success'],
'message': result['message'],
'timestamp': time.time()
}, f)
except Exception as e:
print(f"Bridge error: {e}")
time.sleep(0.5) # Check every 500ms
def _execute_code(self, code):
"""Execute Python code in Fusion context"""
try:
# Create execution environment
exec_globals = {
'adsk': adsk,
'app': self.app,
'ui': self.ui,
'__name__': '__main__'
}
# Execute code
exec(code, exec_globals)
return {
'success': True,
'message': 'Code executed successfully in Fusion 360'
}
except Exception as e:
error_msg = traceback.format_exc()
return {
'success': False,
'message': f'Execution error: {str(e)}\n{error_msg}'
}
# Global bridge instance
_bridge = None
def run(context):
"""Main entry point"""
global _bridge
try:
if _bridge is None:
_bridge = FusionBridge()
_bridge.start()
else:
_bridge.ui.messageBox('Bridge is already running!')
except:
ui = adsk.core.Application.get().userInterface
ui.messageBox('Failed:\n{}'.format(traceback.format_exc()))
def stop(context):
"""Stop the bridge"""
global _bridge
if _bridge:
_bridge.stop()
_bridge = None