001 package toolbus;
002
003 import toolbus.adapter.ToolBridge;
004 import toolbus.communication.DirectIOHandler;
005 import toolbus.exceptions.ToolBusError;
006 import toolbus.logging.ILogger;
007 import toolbus.logging.IToolBusLoggerConstants;
008 import toolbus.logging.LoggerFactory;
009 import toolbus.tool.ToolDefinition;
010 import toolbus.tool.ToolInstance;
011 import aterm.AFun;
012 import aterm.ATerm;
013
014 public class DirectConnectionHandler{
015 private final ToolBus toolbus;
016
017 public DirectConnectionHandler(ToolBus toolbus){
018 super();
019
020 this.toolbus = toolbus;
021 }
022
023 public void dock(ToolBridge toolBridge) throws ToolBusError{
024 String toolName = toolBridge.getToolName();
025
026 ToolDefinition toolDef = toolbus.getToolDefinition(toolName);
027 if(toolDef == null){
028 String error = "No tool definition found for tool with name: " + toolName;
029 LoggerFactory.log(error, ILogger.WARNING, IToolBusLoggerConstants.COMMUNICATION);
030 throw new RuntimeException(error);
031 }
032
033 if(!toolBridge.checkSignature(toolDef.getSignature())){
034 String error = "The tool, with name: "+toolName+", did not provide the expected interface.";
035 LoggerFactory.log(error, ILogger.WARNING, IToolBusLoggerConstants.COMMUNICATION);
036 throw new RuntimeException(error);
037 }
038
039 ToolInstanceManager toolInstanceManager = toolbus.getToolInstanceManager();
040
041 TBTermFactory tbfactory = toolbus.getTBTermFactory();
042 AFun afun = tbfactory.makeAFun(toolDef.getName(), 1, false);
043 ATerm toolKey = tbfactory.makeAppl(afun, tbfactory.makeInt(toolBridge.getToolID()));
044
045 ToolInstance toolInstance = toolInstanceManager.getPendingTool(toolKey);
046
047 // If we didn't request the tool with the given id to execute, it's connecting on it's own
048 // initiative.
049 if(toolInstance == null){
050 toolInstance = new ToolInstance(toolDef, toolbus);
051 toolInstanceManager.addDynamiclyConnectedTool(toolInstance);
052
053 LoggerFactory.log("Tool: " + toolInstance.getToolKey() + ", connected at its own initiative.", ILogger.INFO, IToolBusLoggerConstants.COMMUNICATION);
054 }
055
056 // Connect the tool bridge with the tool instance.
057 DirectIOHandler toolDirectIOHandler = new DirectIOHandler(toolBridge);
058 toolBridge.setIOHandler(toolDirectIOHandler);
059
060 DirectIOHandler toolBusDirectIOHandler = new DirectIOHandler(toolInstance);
061 toolInstance.setIOHandler(toolBusDirectIOHandler);
062
063 toolDirectIOHandler.setDirectIOHandler(toolBusDirectIOHandler);
064 toolBusDirectIOHandler.setDirectIOHandler(toolDirectIOHandler);
065 }
066 }