CommunicationModule.java 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. package classes.holonControlUnit;
  2. import classes.Holon;
  3. import classes.holonControlUnit.messages.Message;
  4. import classes.holonControlUnit.messages.NeighborhoodMsg;
  5. import java.util.ArrayList;
  6. import java.util.HashSet;
  7. import java.util.Set;
  8. import com.google.gson.Gson;
  9. /**
  10. * this class is responsable for communication between holons
  11. * @author Jonas
  12. *
  13. */
  14. public class CommunicationModule {
  15. private HolonControlUnit hcu;
  16. private Gson gson;
  17. public enum MessageType {
  18. ORDER, NEIGHBORHOOD
  19. }
  20. public CommunicationModule(HolonControlUnit owner) {
  21. this.hcu = owner;
  22. this.gson = new Gson();
  23. }
  24. public void sendMsg(String receiver, MessageType type, String body) {
  25. //send msg to holon receiver
  26. Message msg = new Message(this.hcu.getHolon().getUniqueID(), receiver, type, body);
  27. // System.out.println("Holon "+hcu.getHolon().getUniqueID()+" send message: "+msg);
  28. //get receiver through his uniqueID
  29. Holon h = this.hcu.getHolon().model.getHolonsByID().get(receiver);
  30. if(h == null) {
  31. System.err.println("Could not find Holon: "+receiver+"\t in holons: "+this.hcu.getHolon().model.getHolonsByID());
  32. return;
  33. }
  34. h.holonControlUnit.getCommunicator().receiveMsg(gson.toJson(msg));
  35. }
  36. public void receiveMsg(String message) {
  37. Message msg = this.gson.fromJson(message, Message.class);
  38. // System.out.println("Holon "+hcu.getHolon().getUniqueID()+" received message: "+message);
  39. if(!msg.getReceiver().equals(this.hcu.getHolon().getUniqueID()))
  40. throw new RuntimeException("Missleaded message:\n"+message);
  41. switch (msg.getType()) {
  42. case ORDER:
  43. break;
  44. case NEIGHBORHOOD:
  45. receiveNewVNeighbor(msg);
  46. break;
  47. default:
  48. throw new RuntimeException("Unknown message type:\n"+message);
  49. }
  50. }
  51. private void receiveNewVNeighbor(Message msg) {
  52. NeighborhoodMsg nMsg = this.gson.fromJson(msg.getBody(), NeighborhoodMsg.class);
  53. ArrayList<String> neighbors = nMsg.getNeighbors();
  54. switch(nMsg.getType()) {
  55. case NEW_VIRTUAL_NEIGHBOR:
  56. this.hcu.getHierarchyController().addVirtualNeighbors(neighbors);
  57. break;
  58. case REMOVE_VIRTUAL_NEIGHBOR:
  59. this.hcu.getHierarchyController().removeVirtualNeighbors(neighbors);
  60. break;
  61. case NEW_PHYSICAL_NEIGHBOR:
  62. break;
  63. case REMOVE_PHYSICAL_NEIGHBOR:
  64. break;
  65. default:
  66. throw new RuntimeException("Unknown neighborhood type:\n"+msg);
  67. }
  68. // System.out.println("Holon "+hcu.getHolon().name+" received new v neighbor "+v.getNewVirtualNeighbor());
  69. }
  70. public Gson getGson() {
  71. return this.gson;
  72. }
  73. }