1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889 |
- package classes.holonControlUnit;
- import classes.Holon;
- import classes.holonControlUnit.messages.Message;
- import classes.holonControlUnit.messages.NeighborhoodMsg;
- import classes.holonControlUnit.messages.StateMsg;
- import classes.holonControlUnit.messages.StateRequestMsg;
- import java.util.ArrayList;
- import java.util.HashSet;
- import java.util.Set;
- import com.google.gson.Gson;
- /**
- * this class is responsable for communication between holons
- * @author Jonas
- *
- */
- public class CommunicationModule {
-
- private HolonControlUnit hcu;
- private Gson gson;
-
- public CommunicationModule(HolonControlUnit owner) {
- this.hcu = owner;
- this.gson = new Gson();
- }
- public void sendMsg(String receiver, Message.Type type, String body) {
- //send msg to holon receiver
- Message msg = new Message(this.hcu.getHolon().getUniqueID(), receiver, type, body);
- //get receiver through his uniqueID
- Holon h = this.hcu.getHolon().model.getHolonsByID().get(receiver);
- if(h == null) {
- System.err.println("Could not find Holon: "+receiver+"\t in holons: "+this.hcu.getHolon().model.getHolonsByID());
- return;
- }
- h.holonControlUnit.getCommunicator().receiveMsg(gson.toJson(msg));
- }
-
- public void receiveMsg(String message) {
- Message msg = this.gson.fromJson(message, Message.class);
-
- if(!msg.getReceiver().equals(this.hcu.getHolon().getUniqueID()))
- throw new RuntimeException("Missleaded message:\n"+message);
-
- switch (msg.getType()) {
- case ORDER:
-
- break;
- case NEIGHBORHOOD:
- receiveNeighborhoodMsg(msg);
- break;
- case STATE_REQUEST:
- this.hcu.getStateEstimator().receiveStateRequest(msg.getSender(), this.gson.fromJson(msg.getBody(), StateRequestMsg.class));
- break;
- case STATE:
- this.hcu.getStateEstimator().receiveState(msg.getSender(), this.gson.fromJson(msg.getBody(), StateMsg.class));
- break;
- default:
- throw new RuntimeException("Unknown message type:\n"+message);
- }
- }
-
- private void receiveNeighborhoodMsg(Message msg) {
- NeighborhoodMsg nMsg = this.gson.fromJson(msg.getBody(), NeighborhoodMsg.class);
- ArrayList<String> neighbors = nMsg.getNeighbors();
- switch(nMsg.getType()) {
- case NEW_VIRTUAL_NEIGHBOR:
- this.hcu.getHierarchyController().addVirtualNeighbors(neighbors);
- break;
- case REMOVE_VIRTUAL_NEIGHBOR:
- this.hcu.getHierarchyController().removeVirtualNeighbors(neighbors);
- break;
- case NEW_PHYSICAL_NEIGHBOR:
- break;
- case REMOVE_PHYSICAL_NEIGHBOR:
- break;
- default:
- throw new RuntimeException("Unknown neighborhood type:\n"+msg);
- }
- }
-
- public Gson getGson() {
- return this.gson;
- }
-
- }
|