distributed_automated/multi_agent_system/src/com/mas/main/ControllerAgent.java
<reponame>haiderali27/master_assignmentspackage com.mas.main;


import jade.core.AID;
import jade.core.Agent;
import jade.core.behaviours.CyclicBehaviour;
import jade.lang.acl.ACLMessage;
import jade.lang.acl.MessageTemplate;
import jade.wrapper.AgentController;
import jade.wrapper.StaleProxyException;

public class ControllerAgent extends Agent{
	private static Graph conveyor = new Graph();
	
	public static Graph getGraph() {
		return conveyor;
	}

	protected void setup() {
		try {
			for(int i=1; i<15;i++) {
				AgentController agent = getContainerController().createNewAgent("ConveyorAgent"+i, "com.mas.main.ConveyorAgent", new Object[] {Integer.toString(i), ENUMS.STATES.IDLE});
				conveyor.addVertex(Integer.toString(i), "IDLE");
				// register the agent with the JADE runtime environment
				agent.start();
			}
			//ConfigureHere
			conveyor.addEdge("1", "2", 1);
			conveyor.addEdge("2", "3", 1);
			conveyor.addEdge("3", "4", 1);
			conveyor.addEdge("3", "13", 1);
			conveyor.addEdge("4", "5", 1);
			conveyor.addEdge("5", "6", 1);
			conveyor.addEdge("6", "7", 1);
			conveyor.addEdge("7", "8", 1);
			conveyor.addEdge("8", "14", 1);
			conveyor.addEdge("8", "9", 1);
			conveyor.addEdge("9", "10", 1);
			conveyor.addEdge("10", "11", 1);
			conveyor.addEdge("11", "12", 1);
			conveyor.addEdge("12", "1", 1);
			conveyor.addEdge("13", "14", 1);
			conveyor.addEdge("14", "12",  1);
			addBehaviour(new ControllerBehaviour());


		} catch (StaleProxyException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	private class ControllerBehaviour extends CyclicBehaviour {

		@Override
		public void action() {
			MessageTemplate mt = MessageTemplate.MatchPerformative(ACLMessage.REQUEST);
			ACLMessage msg = receive(mt);
			if (msg != null) {
				String content = msg.getContent();
				System.out.println("msg: "+content);

				//CHANGE_STATE:1:IDLE example message to change state of conveyor
				if(content!=null&&msg.getContent().contains("CHANGE_STATE")) {
					String[] contentParts = content.split(":");
					String conveyorNumber = contentParts[1].trim();
					String newState = contentParts[2];
					if(!(newState.contentEquals("IDLE")||newState.contentEquals("DOWN")||newState.contentEquals("BUSY"))) {
						System.out.println("Wrong State");
						return;
					}
					
					ACLMessage sendMsg = new ACLMessage(ACLMessage.REQUEST);
					sendMsg.setContent("CHANGE_STATE:"+newState);
					sendMsg.addReceiver(new AID("ConveyorAgent"+conveyorNumber, AID.ISLOCALNAME));
					send(sendMsg);
					ACLMessage response = blockingReceive(); // Wait for a response
					if (response != null) {
						// Process the response
						String responseContent = response.getContent();
						System.out.println("Received response: " + responseContent);
					} else {
						System.out.println("Did not receive a response.");
					}
					return;
				}



			}

		

		}

	}
}
