2 次代码提交 afb26abaed ... cfaa05246c

作者 SHA1 备注 提交日期
  Andreas T. Meyer-Berg cfaa05246c Fixes FalsePositive Bugs, adds new scenarios 3 年之前
  Andreas T. Meyer-Berg a445a49a95 Adds PacketType Attribute 3 年之前

+ 7 - 1
src/main/java/de/tu_darmstadt/tk/SmartHomeNetworkSim/Main.java

@@ -3,6 +3,9 @@ package de.tu_darmstadt.tk.SmartHomeNetworkSim;
 import de.tu_darmstadt.tk.SmartHomeNetworkSim.control.Controller;
 import de.tu_darmstadt.tk.SmartHomeNetworkSim.core.Model;
 import de.tu_darmstadt.tk.SmartHomeNetworkSim.view.MainFrame;
+import de.tu_darmstadt.tk.SmartHomeNetworkSim.view.menuBar.HeaterScenario;
+import de.tu_darmstadt.tk.SmartHomeNetworkSim.view.menuBar.HeaterScenarioFakeData;
+import de.tu_darmstadt.tk.SmartHomeNetworkSim.view.menuBar.LightScenario;
 
 /**
  * Main class which initializes and connects the different parts and starts the program
@@ -33,7 +36,10 @@ public class Main {
 		model = new Model();
 		controller = new Controller(model);
 	    view = new MainFrame(controller);
-	    view.menu.mnExamples.createSWCExample(true);
+	    //view.menu.mnExamples.createSWCExample(true);
+	    //new HeaterScenario(controller, controller.getNetworkController()).createSWCExample(true);
+	    //new LightScenario(controller).createSWCExample(true);
+	    new HeaterScenarioFakeData(controller, controller.getNetworkController()).createSWCExample(true);
 	    System.exit(0);
 	}
 }

+ 8 - 0
src/main/java/de/tu_darmstadt/tk/SmartHomeNetworkSim/core/Packet.java

@@ -116,4 +116,12 @@ public abstract class Packet {
 	public void setLabel(short label) {
 		this.label = label;
 	}
+	
+	/**
+	 * Returns more specific Package type, or default if not implemented
+	 * @return PackageType
+	 */
+	public String getPackageType() {
+		return "default";
+	}
 }

+ 263 - 210
src/main/java/de/tu_darmstadt/tk/SmartHomeNetworkSim/core/protocols/packets/MQTT_packet.java

@@ -1,210 +1,263 @@
-package de.tu_darmstadt.tk.SmartHomeNetworkSim.core.protocols.packets;
-
-import de.tu_darmstadt.tk.SmartHomeNetworkSim.core.Packet;
-import de.tu_darmstadt.tk.SmartHomeNetworkSim.core.Port;
-
-/**
- * Packet generated by the MQTT Protocol
- * 
- *
- * @author Andreas T. Meyer-Berg
- */
-public class MQTT_packet extends Packet {
-
-	/*
-	 * List of the different MQTT packet types, which are the bits 7 to 4 of the
-	 * first byte of the packet as specified in MQTT Specification 2.2.1 (MQTT
-	 * Control Packet type)<br> The first 4 bits contain the values 0 to F.
-	 */
-	/*
-	 * The second part of the first byte are the Flag Bits. In most control
-	 * packets they are 0. The Publish Packet contains DUP, QoS, QoS, RETAIN
-	 * bits. PUBREL, SUBSCRIBE and UNSUBSCRIBE contain 0x2 as lower nibble. See
-	 * MQTT Section 2.2.2 for further infos.
-	 */
-
-	/**
-	 * Reserved (forbidden)
-	 */
-	public static final byte RESERVED = (byte) 0x00;
-	/**
-	 * Client request to connect to Server (Client-{@literal >}Server)
-	 */
-	public static final byte CONNECT = (byte) 0x10;
-	/**
-	 * Connect acknowledgement (Client{@literal <}-Server)
-	 */
-	public static final byte CONNACK = (byte) 0x20;
-	/**
-	 * Publish message (Client{@literal <}-{@literal >}Server)
-	 */
-	public static final byte PUBLISH = (byte) 0x30;
-	/**
-	 * Publish acknowledgement (Client{@literal <}-{@literal >}Server)
-	 */
-	public static final byte PUBACK = (byte) 0x40;
-	/**
-	 * Publish received (assured delivery part 1) (Client{@literal <}-{@literal >}Server)
-	 */
-	public static final byte PUBREC = (byte) 0x50;
-	/**
-	 * Publish received (assured delivery part 2) (Client{@literal <}-{@literal >}Server)
-	 */
-	public static final byte PUBREL = (byte) 0x62;
-	/**
-	 * Publish received (assured delivery part 3) (Client{@literal <}-{@literal >}Server)
-	 */
-	public static final byte PUBCOMP = (byte) 0x70;
-	/**
-	 * Client subscribe request (Client-{@literal >}Server)
-	 */
-	public static final byte SUBSCRIBE = (byte) 0x82;
-	/**
-	 * Subscribe acknowledgement (Client{@literal <}-Server)
-	 */
-	public static final byte SUBACK = (byte) 0x90;
-	/**
-	 * Unsubscribe request (Client-{@literal >}Server)
-	 */
-	public static final byte UNSUBSCRIBE = (byte) 0xA2;
-	/**
-	 * Unsubscribe acknowledgement (Client{@literal <}-Server)
-	 */
-	public static final byte UNSUBACK = (byte) 0xB0;
-	/**
-	 * PING request (Client-{@literal >}Server)
-	 */
-	public static final byte PINGREQ = (byte) 0xC0;
-	/**
-	 * PING response (Client{@literal <}-Server)
-	 */
-	public static final byte PINGRESP = (byte) 0xD0;
-	/**
-	 * Client is disconnecting (Client-{@literal >}Server)
-	 */
-	public static final byte DISCONNECT = (byte) 0xE0;
-	/**
-	 * Reserved - forbidden
-	 */
-	public static final byte RESERVED2 = (byte) 0xF0;
-
-	/*
-	 * Packet Content
-	 */
-	/**
-	 * First byte of the MQTT:Packet
-	 */
-	protected byte controlByte;
-
-	/**
-	 * Payload message
-	 */
-	protected String message = "";
-
-	/**
-	 * Creates a new MQTT Packet
-	 * 
-	 * @param controlType
-	 *            specifies the packetType. one of CONNECT, CONNACK, ...
-	 * @param timestamp
-	 *            time the packet was sent
-	 * @param source
-	 *            source port of the package
-	 * @param destination
-	 *            destination port of the packet
-	 */
-	public MQTT_packet(byte controlType, long timestamp, Port source, Port destination) {
-		super(timestamp, source, destination);
-		controlByte = controlType;
-	}
-	
-	/**
-	 * Creates a new MQTT Packet
-	 * 
-	 * @param controlType
-	 *            specifies the packetType. one of CONNECT, CONNACK, ...
-	 * @param timestamp
-	 *            time the packet was sent
-	 * @param source
-	 *            source port of the package
-	 * @param destination
-	 *            destination port of the packet
-	 * @param msg Message of the packet
-	 */
-	public MQTT_packet(byte controlType, long timestamp, Port source, Port destination, String msg) {
-		super(timestamp, source, destination);
-		controlByte = controlType;
-		message = msg;
-	}
-
-	@Override
-	public byte[] dumpBytes() {
-		return "not implemented".getBytes();
-	}
-
-	@Override
-	public String getTextualRepresentation() {
-		/**
-		 * Control type of the MQTT Packet as String
-		 */
-		String packetType;
-		switch (controlByte) {
-		case CONNECT:
-			packetType="CONNECT";
-			break;
-		case CONNACK:
-			packetType="CONNACK";
-			break;
-		case PUBLISH:
-			packetType="PUBLISH";
-			break;
-		case PUBACK:
-			packetType="PUBACK";
-			break;
-		case PUBREC:
-			packetType="PUBREC";
-			break;
-		case PUBREL:
-			packetType="PUBREL";
-			break;
-		case PUBCOMP:
-			packetType="PUBCOMP";
-			break;
-		case SUBSCRIBE:
-			packetType="SUBSCRIBE";
-			break;
-		case SUBACK:
-			packetType="SUBACK";
-			break;
-		case UNSUBSCRIBE:
-			packetType="UNSUBSCRIBE";
-			break;
-		case UNSUBACK:
-			packetType="UNSUBACK";
-			break;
-		case PINGREQ:
-			packetType="PINGREQ";
-			break;
-		case PINGRESP:
-			packetType="PINGRESP";
-			break;
-		case DISCONNECT:
-			packetType="DISCONNECT";
-			break;
-		default:
-			packetType="RESERVED";
-			break;
-		}
-		return "[MQTT: "+packetType+"; time:"+timestamp+"; source:"+source.getOwner().getName()+":"+source.getPortNumber()+"; destination:"+destination.getOwner().getName()+":"+destination.getPortNumber()+(message==""?"":"; "+message)+"]";
-	}
-
-	@Override
-	public String getPayload() {
-		return "null";
-	}
-
-	@Override
-	public String getProtocolName() {
-		return "MQTT";
-	}
-}
+package de.tu_darmstadt.tk.SmartHomeNetworkSim.core.protocols.packets;
+
+import de.tu_darmstadt.tk.SmartHomeNetworkSim.core.Packet;
+import de.tu_darmstadt.tk.SmartHomeNetworkSim.core.Port;
+
+/**
+ * Packet generated by the MQTT Protocol
+ * 
+ *
+ * @author Andreas T. Meyer-Berg
+ */
+public class MQTT_packet extends Packet {
+
+	/*
+	 * List of the different MQTT packet types, which are the bits 7 to 4 of the
+	 * first byte of the packet as specified in MQTT Specification 2.2.1 (MQTT
+	 * Control Packet type)<br> The first 4 bits contain the values 0 to F.
+	 */
+	/*
+	 * The second part of the first byte are the Flag Bits. In most control
+	 * packets they are 0. The Publish Packet contains DUP, QoS, QoS, RETAIN
+	 * bits. PUBREL, SUBSCRIBE and UNSUBSCRIBE contain 0x2 as lower nibble. See
+	 * MQTT Section 2.2.2 for further infos.
+	 */
+
+	/**
+	 * Reserved (forbidden)
+	 */
+	public static final byte RESERVED = (byte) 0x00;
+	/**
+	 * Client request to connect to Server (Client-{@literal >}Server)
+	 */
+	public static final byte CONNECT = (byte) 0x10;
+	/**
+	 * Connect acknowledgement (Client{@literal <}-Server)
+	 */
+	public static final byte CONNACK = (byte) 0x20;
+	/**
+	 * Publish message (Client{@literal <}-{@literal >}Server)
+	 */
+	public static final byte PUBLISH = (byte) 0x30;
+	/**
+	 * Publish acknowledgement (Client{@literal <}-{@literal >}Server)
+	 */
+	public static final byte PUBACK = (byte) 0x40;
+	/**
+	 * Publish received (assured delivery part 1) (Client{@literal <}-{@literal >}Server)
+	 */
+	public static final byte PUBREC = (byte) 0x50;
+	/**
+	 * Publish received (assured delivery part 2) (Client{@literal <}-{@literal >}Server)
+	 */
+	public static final byte PUBREL = (byte) 0x62;
+	/**
+	 * Publish received (assured delivery part 3) (Client{@literal <}-{@literal >}Server)
+	 */
+	public static final byte PUBCOMP = (byte) 0x70;
+	/**
+	 * Client subscribe request (Client-{@literal >}Server)
+	 */
+	public static final byte SUBSCRIBE = (byte) 0x82;
+	/**
+	 * Subscribe acknowledgement (Client{@literal <}-Server)
+	 */
+	public static final byte SUBACK = (byte) 0x90;
+	/**
+	 * Unsubscribe request (Client-{@literal >}Server)
+	 */
+	public static final byte UNSUBSCRIBE = (byte) 0xA2;
+	/**
+	 * Unsubscribe acknowledgement (Client{@literal <}-Server)
+	 */
+	public static final byte UNSUBACK = (byte) 0xB0;
+	/**
+	 * PING request (Client-{@literal >}Server)
+	 */
+	public static final byte PINGREQ = (byte) 0xC0;
+	/**
+	 * PING response (Client{@literal <}-Server)
+	 */
+	public static final byte PINGRESP = (byte) 0xD0;
+	/**
+	 * Client is disconnecting (Client-{@literal >}Server)
+	 */
+	public static final byte DISCONNECT = (byte) 0xE0;
+	/**
+	 * Reserved - forbidden
+	 */
+	public static final byte RESERVED2 = (byte) 0xF0;
+
+	/*
+	 * Packet Content
+	 */
+	/**
+	 * First byte of the MQTT:Packet
+	 */
+	protected byte controlByte;
+
+	/**
+	 * Payload message
+	 */
+	protected String message = "";
+
+	/**
+	 * Creates a new MQTT Packet
+	 * 
+	 * @param controlType
+	 *            specifies the packetType. one of CONNECT, CONNACK, ...
+	 * @param timestamp
+	 *            time the packet was sent
+	 * @param source
+	 *            source port of the package
+	 * @param destination
+	 *            destination port of the packet
+	 */
+	public MQTT_packet(byte controlType, long timestamp, Port source, Port destination) {
+		super(timestamp, source, destination);
+		controlByte = controlType;
+	}
+	
+	/**
+	 * Creates a new MQTT Packet
+	 * 
+	 * @param controlType
+	 *            specifies the packetType. one of CONNECT, CONNACK, ...
+	 * @param timestamp
+	 *            time the packet was sent
+	 * @param source
+	 *            source port of the package
+	 * @param destination
+	 *            destination port of the packet
+	 * @param msg Message of the packet
+	 */
+	public MQTT_packet(byte controlType, long timestamp, Port source, Port destination, String msg) {
+		super(timestamp, source, destination);
+		controlByte = controlType;
+		message = msg;
+	}
+
+	@Override
+	public byte[] dumpBytes() {
+		return "not implemented".getBytes();
+	}
+
+	@Override
+	public String getTextualRepresentation() {
+		/**
+		 * Control type of the MQTT Packet as String
+		 */
+		String packetType;
+		switch (controlByte) {
+		case CONNECT:
+			packetType="CONNECT";
+			break;
+		case CONNACK:
+			packetType="CONNACK";
+			break;
+		case PUBLISH:
+			packetType="PUBLISH";
+			break;
+		case PUBACK:
+			packetType="PUBACK";
+			break;
+		case PUBREC:
+			packetType="PUBREC";
+			break;
+		case PUBREL:
+			packetType="PUBREL";
+			break;
+		case PUBCOMP:
+			packetType="PUBCOMP";
+			break;
+		case SUBSCRIBE:
+			packetType="SUBSCRIBE";
+			break;
+		case SUBACK:
+			packetType="SUBACK";
+			break;
+		case UNSUBSCRIBE:
+			packetType="UNSUBSCRIBE";
+			break;
+		case UNSUBACK:
+			packetType="UNSUBACK";
+			break;
+		case PINGREQ:
+			packetType="PINGREQ";
+			break;
+		case PINGRESP:
+			packetType="PINGRESP";
+			break;
+		case DISCONNECT:
+			packetType="DISCONNECT";
+			break;
+		default:
+			packetType="RESERVED";
+			break;
+		}
+		return "[MQTT: "+packetType+"; time:"+timestamp+"; source:"+source.getOwner().getName()+":"+source.getPortNumber()+"; destination:"+destination.getOwner().getName()+":"+destination.getPortNumber()+(message==""?"":"; "+message)+"]";
+	}
+
+	@Override
+	public String getPayload() {
+		return "null";
+	}
+
+	@Override
+	public String getProtocolName() {
+		return "MQTT";
+	}
+	
+	@Override
+	public String getPackageType() {
+		String packetType;
+		switch (controlByte) {
+		case CONNECT:
+			packetType="CONNECT";
+			break;
+		case CONNACK:
+			packetType="CONNACK";
+			break;
+		case PUBLISH:
+			packetType="PUBLISH";
+			break;
+		case PUBACK:
+			packetType="PUBACK";
+			break;
+		case PUBREC:
+			packetType="PUBREC";
+			break;
+		case PUBREL:
+			packetType="PUBREL";
+			break;
+		case PUBCOMP:
+			packetType="PUBCOMP";
+			break;
+		case SUBSCRIBE:
+			packetType="SUBSCRIBE";
+			break;
+		case SUBACK:
+			packetType="SUBACK";
+			break;
+		case UNSUBSCRIBE:
+			packetType="UNSUBSCRIBE";
+			break;
+		case UNSUBACK:
+			packetType="UNSUBACK";
+			break;
+		case PINGREQ:
+			packetType="PINGREQ";
+			break;
+		case PINGRESP:
+			packetType="PINGRESP";
+			break;
+		case DISCONNECT:
+			packetType="DISCONNECT";
+			break;
+		default:
+			packetType="RESERVED";
+			break;
+		}
+		return packetType;
+	}
+}

+ 24 - 9
src/main/java/de/tu_darmstadt/tk/SmartHomeNetworkSim/evaluation/BasicPacketClassifier.java

@@ -9,6 +9,7 @@ import java.util.HashSet;
 import java.util.Iterator;
 import java.util.LinkedList;
 import java.util.Map.Entry;
+import java.util.Set;
 
 import de.tu_darmstadt.tk.SmartHomeNetworkSim.core.Link;
 import de.tu_darmstadt.tk.SmartHomeNetworkSim.core.Packet;
@@ -70,6 +71,11 @@ public abstract class BasicPacketClassifier implements PacketSniffer {
 	 * Map for the protocol names
 	 */
 	protected HashSet<String> protocol_mappings = new HashSet<String>();
+	
+	/**
+	 * Map for the protocol names
+	 */
+	protected HashSet<String> package_mappings = new HashSet<String>();
 
 	/**
 	 * Number of packets which are used to calculate the current transmission speed
@@ -87,6 +93,7 @@ public abstract class BasicPacketClassifier implements PacketSniffer {
 		link_mappings.add("unknown");
 		destination_mappings.add("unknown");
 		protocol_mappings.add("unknown");
+		package_mappings.add("unknown");
 	}
 	
 	@Override
@@ -154,7 +161,7 @@ public abstract class BasicPacketClassifier implements PacketSniffer {
 		 */
 		DenseInstance instance = new DenseInstance(dataset.numAttributes());
 		instance.setDataset(dataset);
-		
+		/*
 		// link
 		instance.setValue(0, stringToNominal(link_mappings, link.getName()));
 		
@@ -189,24 +196,25 @@ public abstract class BasicPacketClassifier implements PacketSniffer {
 		
 		// Packets per second
 		//instance.setValue(6, getEstimatedPacketsPerSecond(link, packet));
-		// MQTT Value
+		// MQTT Value*/
 		if(packet instanceof MQTTpublishPacket) {
 			MQTTpublishPacket mqttPack = (MQTTpublishPacket)packet;
 			if(mqttPack.isBoolean()) {
 				//System.out.println("MQTT PACK: " + mqttPack.getValue());
 				if(mqttPack.getValue() == 0) {
 					//System.out.println("False");
-					instance.setValue(6,0);
+					instance.setValue(0,Settings.FALSE_VALUE);
 				} else {
 					//System.out.println("True");
-					instance.setValue(6, 1);
+					instance.setValue(0, Settings.TRUE_VALUE);
 				}
 			}else {				
-				instance.setValue(6, ((MQTTpublishPacket)packet).getValue());
+				instance.setValue(0, ((MQTTpublishPacket)packet).getValue());
 			}
 		} else {
-			instance.setValue(6, -100);
+			instance.setValue(0, Settings.NO_VALUE);
 		}
+		instance.setValue(1, stringToNominal(destination_mappings, packet.getPackageType()));
 		return instance;
 	}
 	
@@ -248,11 +256,14 @@ public abstract class BasicPacketClassifier implements PacketSniffer {
 			for(Packet pac: e.getValue()) {
 				if(pac == null || pac.getSource()==null ||pac.getDestination() == null || pac.getSource().getOwner() == null || pac.getDestination().getOwner() == null)
 					continue;
+				if(!(pac instanceof MQTTpublishPacket))
+					continue;
 				insertNominalIntoMap(destination_mappings, pac.getSource().getOwner().getName());
 				insertNominalIntoMap(destination_mappings, pac.getDestination().getOwner().getName());
 				insertNominalIntoMap(source_mappings, pac.getSource().getOwner().getName());
 				insertNominalIntoMap(source_mappings, pac.getDestination().getOwner().getName());
 				insertNominalIntoMap(protocol_mappings, pac.getProtocolName());
+				insertNominalIntoMap(package_mappings, pac.getPackageType());
 			}
 			//TODO: Add packet/Link/Names etc. to mappings
 		}
@@ -269,7 +280,7 @@ public abstract class BasicPacketClassifier implements PacketSniffer {
 		printHashSet("Source-Device", source_mappings);
 		printHashSet("Destination-Port", destination_mappings);
 		printHashSet("Protocol-name", protocol_mappings);
-		*/
+		*//*
 		atts.add(new Attribute("Link-Name", new LinkedList<String>(link_mappings)));//TODO:??
 		atts.add(new Attribute("Source-Device", new LinkedList<String>(source_mappings)));
 		atts.add(new Attribute("Source-Port-number", false));
@@ -280,8 +291,9 @@ public abstract class BasicPacketClassifier implements PacketSniffer {
 		atts.add(pn);
 		//Attribute pps = new Attribute("Packets-per-second", false);
 		//pps.setWeight(20);
-		//atts.add(pps);
+		//atts.add(pps);*/
 		atts.add(new Attribute("PacketValue", false));
+		atts.add(new Attribute("PacketType", new LinkedList<String>(protocol_mappings)));
 		//atts.add(new Attribute("Anomaly", false));
 		
 		// TODO: Sensor Attribute, given as side channel information
@@ -366,6 +378,8 @@ public abstract class BasicPacketClassifier implements PacketSniffer {
 				 * Packet which should be checked
 				 */
 				Packet packet = (Packet) itPacket.next();
+				if(!(packet instanceof MQTTpublishPacket))
+					continue;
 
 				start = Math.min(start, packet.getTimestamp());
 				end = Math.max(end, packet.getTimestamp());
@@ -390,7 +404,7 @@ public abstract class BasicPacketClassifier implements PacketSniffer {
 				
 				try {
 					double dist = classifyInstance(packet_instance, packet);	
-					if(dist<=Settings.DECISION_THRESHOLD) {
+					if(dist<=Settings.SECOND_THRESHOLD) {
 						if(packet.getLabel()==0)
 							tn++;
 						else {
@@ -408,6 +422,7 @@ public abstract class BasicPacketClassifier implements PacketSniffer {
 						}
 					}
 				} catch (Exception e) {
+					e.printStackTrace();
 					if(packet.getLabel()==0) {
 						fp++;
 						try {

+ 28 - 13
src/main/java/de/tu_darmstadt/tk/SmartHomeNetworkSim/evaluation/BasicPacketClassifierWitLabels.java

@@ -9,6 +9,7 @@ import java.util.HashSet;
 import java.util.Iterator;
 import java.util.LinkedList;
 import java.util.Map.Entry;
+import java.util.Set;
 
 import de.tu_darmstadt.tk.SmartHomeNetworkSim.core.Link;
 import de.tu_darmstadt.tk.SmartHomeNetworkSim.core.Packet;
@@ -71,6 +72,11 @@ public abstract class BasicPacketClassifierWitLabels implements PacketSniffer {
 	 */
 	protected HashSet<String> protocol_mappings = new HashSet<String>();
 
+	/**
+	 * Map for the protocol names
+	 */
+	protected HashSet<String> packet_mappings = new HashSet<String>();
+	
 	/**
 	 * Number of packets which are used to calculate the current transmission speed
 	 */
@@ -87,6 +93,7 @@ public abstract class BasicPacketClassifierWitLabels implements PacketSniffer {
 		link_mappings.add("unknown");
 		destination_mappings.add("unknown");
 		protocol_mappings.add("unknown");
+		packet_mappings.add("unknown");
 	}
 	
 	@Override
@@ -155,6 +162,7 @@ public abstract class BasicPacketClassifierWitLabels implements PacketSniffer {
 		DenseInstance instance = new DenseInstance(dataset.numAttributes());
 		instance.setDataset(dataset);
 		
+		/**
 		// link
 		instance.setValue(0, stringToNominal(link_mappings, link.getName()));
 		
@@ -189,34 +197,35 @@ public abstract class BasicPacketClassifierWitLabels implements PacketSniffer {
 		
 		// Packets per second
 		//instance.setValue(6, getEstimatedPacketsPerSecond(link, packet));
-		// MQTT Value
+		// MQTT Value*/
 		if(packet instanceof MQTTpublishPacket) {
 			MQTTpublishPacket mqttPack = (MQTTpublishPacket)packet;
 			if(mqttPack.isBoolean()) {
 				//System.out.println("MQTT PACK: " + mqttPack.getValue() + "," +mqttPack.getSensorValue());
 				if(mqttPack.getValue() == 0) {
-					instance.setValue(6,0);
+					instance.setValue(0, Settings.FALSE_VALUE);
 					//System.out.println("False");
 				}
 				else {
-					instance.setValue(6, 1);
+					instance.setValue(0, Settings.TRUE_VALUE);
 					//System.out.println("True");
 				}
 				if(mqttPack.getSensorValue() == 0) {
-					instance.setValue(7,0);
+					instance.setValue(1, Settings.FALSE_VALUE);
 					//System.out.println("False");
 				} else {
-					instance.setValue(7, 1);	
+					instance.setValue(1, Settings.TRUE_VALUE);	
 					//System.out.println("True");				
 				}
 			}else {				
-				instance.setValue(6, ((MQTTpublishPacket)packet).getValue());
-				instance.setValue(7, ((MQTTpublishPacket)packet).getSensorValue());
+				instance.setValue(0, ((MQTTpublishPacket)packet).getValue());
+				instance.setValue(1, ((MQTTpublishPacket)packet).getSensorValue());
 			}
 		} else {
-			instance.setValue(6, -100);
-			instance.setValue(7, -100);
+			instance.setValue(0, Settings.NO_VALUE);
+			instance.setValue(1, Settings.NO_VALUE);
 		}
+		instance.setValue(2, stringToNominal(packet_mappings, packet.getPackageType()));
 		return instance;
 	}
 	
@@ -258,11 +267,14 @@ public abstract class BasicPacketClassifierWitLabels implements PacketSniffer {
 			for(Packet pac: e.getValue()) {
 				if(pac == null || pac.getSource()==null ||pac.getDestination() == null || pac.getSource().getOwner() == null || pac.getDestination().getOwner() == null)
 					continue;
+				if(!(pac instanceof MQTTpublishPacket))
+					continue;
 				insertNominalIntoMap(destination_mappings, pac.getSource().getOwner().getName());
 				insertNominalIntoMap(destination_mappings, pac.getDestination().getOwner().getName());
 				insertNominalIntoMap(source_mappings, pac.getSource().getOwner().getName());
 				insertNominalIntoMap(source_mappings, pac.getDestination().getOwner().getName());
 				insertNominalIntoMap(protocol_mappings, pac.getProtocolName());
+				insertNominalIntoMap(packet_mappings, pac.getPackageType());
 			}
 			//TODO: Add packet/Link/Names etc. to mappings
 		}
@@ -280,6 +292,7 @@ public abstract class BasicPacketClassifierWitLabels implements PacketSniffer {
 		printHashSet("Destination-Port", destination_mappings);
 		printHashSet("Protocol-name", protocol_mappings);
 		*/
+		/*
 		atts.add(new Attribute("Link-Name", new LinkedList<String>(link_mappings)));//TODO:??
 		atts.add(new Attribute("Source-Device", new LinkedList<String>(source_mappings)));
 		atts.add(new Attribute("Source-Port-number", false));
@@ -290,13 +303,13 @@ public abstract class BasicPacketClassifierWitLabels implements PacketSniffer {
 		atts.add(pn);
 		//Attribute pps = new Attribute("Packets-per-second", false);
 		//pps.setWeight(20);
-		//atts.add(pps);
+		//atts.add(pps);*/
 		atts.add(new Attribute("PacketValue", false));
 		//atts.add(new Attribute("Anomaly", false));
 		
 		// TODO: Sensor Attribute, given as side channel information
 		atts.add(new Attribute("SensorValue", false));
-
+		atts.add(new Attribute("PackageType",new LinkedList<String>(packet_mappings)));
 		/*
 		atts = new ArrayList<Attribute>();
 		atts.add(new Attribute("LN", new LinkedList<String>(link_mappings)));//TODO:??
@@ -376,7 +389,8 @@ public abstract class BasicPacketClassifierWitLabels implements PacketSniffer {
 				 * Packet which should be checked
 				 */
 				Packet packet = (Packet) itPacket.next();
-
+				if(!(packet instanceof MQTTpublishPacket))
+					continue;
 				start = Math.min(start, packet.getTimestamp());
 				end = Math.max(end, packet.getTimestamp());
 				/**
@@ -401,7 +415,7 @@ public abstract class BasicPacketClassifierWitLabels implements PacketSniffer {
 				try {
 					double dist = classifyInstance(packet_instance, packet);
 					//System.out.println(packet.getTextualRepresentation()+": "+packet.getLabel() +":"+sensorLabel);	
-					if(dist<=Settings.DECISION_THRESHOLD) {
+					if(dist<=Settings.SECOND_THRESHOLD) {
 						if(packet.getLabel()==0) {
 							tn++;
 							writer.write(packet.getTextualRepresentation()+",TN"+sensorLabel+"\n");
@@ -422,6 +436,7 @@ public abstract class BasicPacketClassifierWitLabels implements PacketSniffer {
 					}
 				} catch (Exception e) {
 					System.out.println(e);
+					e.printStackTrace();
 					if(packet.getLabel()==0) {
 						fp++;
 						try {

+ 10 - 8
src/main/java/de/tu_darmstadt/tk/SmartHomeNetworkSim/evaluation/SWCKMeansClustering.java

@@ -33,7 +33,7 @@ public class SWCKMeansClustering extends BasicPacketClassifier {
 		clusterer = new SimpleKMeans();
 		clusterer.setSeed(42);
 		//clusterer.setDisplayStdDevs(true);
-		clusterer.setInitializationMethod(new SelectedTag(SimpleKMeans.RANDOM,SimpleKMeans.TAGS_SELECTION));
+		clusterer.setInitializationMethod(new SelectedTag(Settings.KMEANS_INIT,SimpleKMeans.TAGS_SELECTION));
 		//clusterer.setCanopyPeriodicPruningRate(100);
 		//clusterer.setCanopyT1(0.001);
 		//clusterer.setCanopyT2(0.1);
@@ -89,24 +89,26 @@ public class SWCKMeansClustering extends BasicPacketClassifier {
 		Instance center = clusterer.getClusterCentroids().get(x);
 		
 		double dist = clusterer.getDistanceFunction().distance(center, instance);
-		if(test && dist<stdv[x] && origin.getLabel()!=0) {
-			test = false;
-			System.out.println("Analysis of: "+origin.getTextualRepresentation());
+		if(test) {// && dist<stdv[x] && origin.getLabel()!=0) {
+			//test = false;
+			System.out.println("Analysis of: "+origin.getTextualRepresentation() + " Label: " + origin.getLabel());
 			System.out.println("Classified as: "+x+" Dist: "+dist+" Stdv: "+stdv[x]);
-			for(int i=0; i<NUMBER_OF_CLUSTERS; i++) {
+			for(int i=0; i<clusterer.getNumClusters(); i++) {
 				Instance centroid = clusterer.getClusterCentroids().get(i);
 				if(centroid == null)continue;
 				double d = clusterer.getDistanceFunction().distance(centroid, instance);
 				
 				System.out.println("Cluster: "+i+" Dist: "+d+" Stdv: "+stdv[i]);
 			}
-			test = false;
+			//test = false;
 			System.out.println("");
 		}
-		if(dist < stdv[x] * Settings.ANOMALY_THRESHOLD)
+		if(dist < stdv[x]*Settings.ANOMALY_THRESHOLD + Settings.PRECISION_ERROR) {
 			return 0;
-		else
+		}
+		else {
 			return Double.MAX_VALUE;
+		}
 		
 	}
 

+ 13 - 9
src/main/java/de/tu_darmstadt/tk/SmartHomeNetworkSim/evaluation/SWCKMeansClusteringWithLabels.java

@@ -1,5 +1,7 @@
 package de.tu_darmstadt.tk.SmartHomeNetworkSim.evaluation;
 
+import java.util.Set;
+
 import de.tu_darmstadt.tk.SmartHomeNetworkSim.core.Packet;
 import weka.clusterers.SimpleKMeans;
 import weka.core.Instance;
@@ -33,7 +35,7 @@ public class SWCKMeansClusteringWithLabels extends BasicPacketClassifierWitLabel
 		clusterer = new SimpleKMeans();
 		clusterer.setSeed(42);
 		//clusterer.setDisplayStdDevs(true);
-		clusterer.setInitializationMethod(new SelectedTag(SimpleKMeans.RANDOM,SimpleKMeans.TAGS_SELECTION));
+		clusterer.setInitializationMethod(new SelectedTag(Settings.KMEANS_INIT,SimpleKMeans.TAGS_SELECTION));
 		//clusterer.setCanopyPeriodicPruningRate(100);
 		//clusterer.setCanopyT1(0.001);
 		//clusterer.setCanopyT2(0.1);
@@ -75,7 +77,7 @@ public class SWCKMeansClusteringWithLabels extends BasicPacketClassifierWitLabel
 			e.printStackTrace();
 		}
 	}
-	private boolean test = false;
+	private boolean test = Settings.TEST;
 	
 	@Override
 	public double classifyInstance(Instance instance, Packet origin) throws Exception {
@@ -89,24 +91,26 @@ public class SWCKMeansClusteringWithLabels extends BasicPacketClassifierWitLabel
 		Instance center = clusterer.getClusterCentroids().get(x);
 		
 		double dist = clusterer.getDistanceFunction().distance(center, instance);
-		if(test && dist<stdv[x] && origin.getLabel()!=0) {
-			test = false;
-			System.out.println("Analysis of: "+origin.getTextualRepresentation());
+		if(test) { //&& dist<stdv[x] && origin.getLabel()!=0) {
+			//test = false;
+			System.out.println("Analysis of: "+origin.getTextualRepresentation() + " Label: " + origin.getLabel());
 			System.out.println("Classified as: "+x+" Dist: "+dist+" Stdv: "+stdv[x]);
-			for(int i=0; i<NUMBER_OF_CLUSTERS; i++) {
+			for(int i=0; i<clusterer.getNumClusters(); i++) {
 				Instance centroid = clusterer.getClusterCentroids().get(i);
 				if(centroid == null)continue;
 				double d = clusterer.getDistanceFunction().distance(centroid, instance);
 				
 				System.out.println("Cluster: "+i+" Dist: "+d+" Stdv: "+stdv[i]);
 			}
-			test = false;
+			//test = false;
 			System.out.println("");
 		}
-		if(dist < stdv[x]*Settings.ANOMALY_THRESHOLD)
+		if(dist < stdv[x]*Settings.ANOMALY_THRESHOLD + Settings.PRECISION_ERROR) {
 			return 0;
-		else
+		}
+		else {
 			return Double.MAX_VALUE;
+		}
 		
 	}
 

+ 10 - 2
src/main/java/de/tu_darmstadt/tk/SmartHomeNetworkSim/evaluation/Settings.java

@@ -1,10 +1,18 @@
 package de.tu_darmstadt.tk.SmartHomeNetworkSim.evaluation;
 
+import weka.clusterers.SimpleKMeans;
+
 public class Settings {
 
-	public static int NUM_CLUSTERS = 20;
+	public static int NUM_CLUSTERS = 4;
 	public static double ANOMALY_THRESHOLD = 1;
-	public static double DECISION_THRESHOLD = 1;
+	public static double PRECISION_ERROR = 0.01;
+	public static double SECOND_THRESHOLD = 1;
+	public static double FALSE_VALUE = -1000;
+	public static double TRUE_VALUE = 1000;
+	public static double NO_VALUE = 0;
+	public static int KMEANS_INIT =  SimpleKMeans.FARTHEST_FIRST;
+	public static boolean TEST = false;
 	
 	public Settings() {
 		// TODO Auto-generated constructor stub

+ 287 - 0
src/main/java/de/tu_darmstadt/tk/SmartHomeNetworkSim/view/menuBar/HeaterScenario.java

@@ -0,0 +1,287 @@
+package de.tu_darmstadt.tk.SmartHomeNetworkSim.view.menuBar;
+
+import org.apache.commons.math3.distribution.NormalDistribution;
+
+import de.tu_darmstadt.tk.SmartHomeNetworkSim.control.Controller;
+import de.tu_darmstadt.tk.SmartHomeNetworkSim.control.NetworkController;
+import de.tu_darmstadt.tk.SmartHomeNetworkSim.control.PacketCaptureController;
+import de.tu_darmstadt.tk.SmartHomeNetworkSim.control.SimulationController;
+import de.tu_darmstadt.tk.SmartHomeNetworkSim.core.Connection;
+import de.tu_darmstadt.tk.SmartHomeNetworkSim.core.ConnectionPrecision;
+import de.tu_darmstadt.tk.SmartHomeNetworkSim.core.Link;
+import de.tu_darmstadt.tk.SmartHomeNetworkSim.core.PacketCollector;
+import de.tu_darmstadt.tk.SmartHomeNetworkSim.core.Port;
+import de.tu_darmstadt.tk.SmartHomeNetworkSim.core.PrecisionLink;
+import de.tu_darmstadt.tk.SmartHomeNetworkSim.core.RoomStatus;
+import de.tu_darmstadt.tk.SmartHomeNetworkSim.core.SimulationManager;
+import de.tu_darmstadt.tk.SmartHomeNetworkSim.core.SmartDevice;
+import de.tu_darmstadt.tk.SmartHomeNetworkSim.core.devices.SmartLight;
+import de.tu_darmstadt.tk.SmartHomeNetworkSim.core.devices.SmartLightSensor;
+import de.tu_darmstadt.tk.SmartHomeNetworkSim.core.devices.SmartTemperatureProducer;
+import de.tu_darmstadt.tk.SmartHomeNetworkSim.core.devices.SmartTemperatureSensor;
+import de.tu_darmstadt.tk.SmartHomeNetworkSim.core.distributionHandler.NormalDistributionHandler;
+import de.tu_darmstadt.tk.SmartHomeNetworkSim.core.protocols.MQTT_protocol;
+import de.tu_darmstadt.tk.SmartHomeNetworkSim.core.scheduler.AbstractEvent;
+import de.tu_darmstadt.tk.SmartHomeNetworkSim.evaluation.SWCKMeansClustering;
+import de.tu_darmstadt.tk.SmartHomeNetworkSim.evaluation.SWCKMeansClusteringWithLabels;
+
+public class HeaterScenario {
+
+	Controller controller;
+	NetworkController networkController;
+	public HeaterScenario(Controller controller, NetworkController networkController) {
+		this.controller=controller;
+		this.networkController=networkController;
+	}
+	
+	/**
+	 * Creates the paper toy example, also simulates it, if run = true
+	 * @param run
+	 */
+	@SuppressWarnings("unchecked")
+	public void createSWCExample(boolean run){
+		/**
+		 * Reset network, etc.
+		 */
+
+		long hour = 60 * 60 * 1000;
+		long endTime = 24 * hour;
+		long noAnomEnd = endTime + 1 * hour;
+		long heaterEnd = noAnomEnd + 1 * hour;
+		long stepLength=hour;
+		long currentSimTime=0;
+		
+		SimulationController sim = controller.getSimulationController();
+		if(run) {
+			controller.getSimulationController().resetSimulation();
+			controller.getNetworkController().deleteNetworkModel();
+			/*
+			 * Simulate 24 hours
+			 */
+			sim.setStartTime(0);
+			sim.resetSimulation();
+			sim.setStepDuration(hour);
+			sim.setPrintPackets(false);
+			sim.setEndTime(endTime);
+		}
+		/*
+		 * Main networking devices 
+		 */
+		SmartDevice smartHub = networkController.createSmartDevice("SmartHub", 400, 400, 50);
+		
+		/*
+		 * Links/Networks
+		 */
+		Link zigbee = new PrecisionLink("ZigBee");
+		networkController.addLink(zigbee);
+		
+		/*
+		 * Connect Devices to Links
+		 */
+		networkController.addLinkToDevice(zigbee, smartHub);
+		
+		
+		/*
+		 * Create MQTT Connection
+		 */
+		Connection mqtt = new ConnectionPrecision();
+		mqtt.setName("HomeAutomation (MQTT)");
+		networkController.addConnectionToLink(mqtt, zigbee);
+		mqtt.setProtocol(new MQTT_protocol());
+		Port pBroker = new Port(smartHub, (short)1883);
+		pBroker.setStatus(Port.OPEN);
+		pBroker.setResponseTime((short)2);
+		networkController.addDeviceToConnectionAndProtocol(pBroker, mqtt, 0);
+		networkController.addConnection(mqtt);
+		mqtt.setLabel((short) 0);
+		
+		/**
+		 * Room
+		 */
+		String roomName = "Bedroom";
+		RoomStatus room = new RoomStatus();
+		room.setTemperature(19f);
+		/*
+		 * Add some MQTT Devices
+		 */
+		
+		/**
+		 * Room Thermostat
+		 */
+		SmartTemperatureSensor heatSensor = new SmartTemperatureSensor(roomName + " Thermostat", room);
+		heatSensor.setFSinfoName("home/" + roomName + "/sensorTemp");
+		networkController.addLinkToDevice(zigbee, heatSensor);
+		networkController.moveSmartDevice(heatSensor, 300, 300, 50);
+		heatSensor.setFSmin(19.0f);
+		heatSensor.setFSmax(21.0f);
+		heatSensor.setFSval(19.0f);
+		networkController.addSmartDevice(heatSensor);
+		Port pFloatSensor = new Port(heatSensor, (short)1883, 15000);
+		pFloatSensor.setTriggerHandler(new NormalDistributionHandler(15000, 500));
+		pFloatSensor.setStatus(Port.SENDING);
+		pFloatSensor.setLastTrigger(-357L);
+		networkController.addDeviceToConnectionAndProtocol(pFloatSensor, mqtt,1);
+		heatSensor.setLabel((short) 0);
+		/*
+		 * Add Heater (every second update)
+		 */
+		SmartTemperatureProducer heaterDevice = new SmartTemperatureProducer(roomName + " Heater", room, 500, heatSensor);
+		heaterDevice.setFSinfoName("home/" + roomName + "/heaterTemp");
+		networkController.addLinkToDevice(zigbee, heaterDevice);
+		networkController.moveSmartDevice(heaterDevice, 300, 500, 50);
+		heaterDevice.setFSmin(19.0f);
+		heaterDevice.setFSmax(21.0f);
+		heaterDevice.setFSval(19.0f);
+		networkController.addSmartDevice(heaterDevice);
+		Port pHeaterDevice = new Port(heaterDevice, (short)1883, 15000);
+		pHeaterDevice.setStatus(Port.SENDING);
+		pHeaterDevice.setTriggerHandler(new NormalDistributionHandler(15000, 500));
+		pHeaterDevice.setLastTrigger(-1231L);
+		networkController.addDeviceToConnectionAndProtocol(pHeaterDevice, mqtt,1);
+		heaterDevice.setLabel((short) 0);
+		
+		/* 
+		 * Update visualization 
+		 */
+		controller.notifyObservers();
+		
+		/**
+		 * Run only if run == true
+		 */
+		if(!run)return;
+		try {
+			System.out.println("Check 1");//TODO
+			/**
+			 * Instances of the packet Sniffers
+			 */
+			SWCKMeansClusteringWithLabels snifferKNNwithLabels = new SWCKMeansClusteringWithLabels();
+			SWCKMeansClustering snifferKNNnoLabels = new SWCKMeansClustering();
+
+
+			PacketCollector collectorKNNwithLabels = new PacketCollector(snifferKNNwithLabels);
+			PacketCollector collectorKNNnoLabels = new PacketCollector(snifferKNNnoLabels);
+			//PacketCollector collectorEM = new PacketCollector(snifferEM);
+			//PacketCollector collectorHC = new PacketCollector(snifferHC);
+			
+			/*
+			 * Capture both links on all collectors
+			 */
+			PacketCaptureController captureController = controller.getSimulationController().getPacketCaptureController();
+			//captureController.addLinkToCollector(collectorEM, zigbee);
+			//captureController.addLinkToCollector(collectorKNN, zigbee);
+			captureController.addDeviceToCollector(collectorKNNwithLabels, heaterDevice);
+			captureController.addPacketCollector(collectorKNNwithLabels);
+			captureController.addDeviceToCollector(collectorKNNnoLabels, heaterDevice);
+			captureController.addPacketCollector(collectorKNNnoLabels);
+			//captureController.addPacketCollector(collectorEM);
+			//captureController.addPacketCollector(collectorHC);
+
+			System.out.println("Check 3: created Controller");//TODO
+			
+			long currentTime = System.currentTimeMillis();
+			
+
+
+			/**
+			 * Training events
+			 */
+			System.out.println("Create training events");
+			/**
+			 * Heater Events (random switch every 2h +- 30min
+			 */
+			NormalDistribution tempDist = new NormalDistribution(2*hour, hour/2);
+			long eventTime = 0;
+			boolean low = true;
+			while(eventTime < noAnomEnd) {
+				/**
+				 * At least 1 second between events
+				 */
+				final float newTemp;
+				if(low)
+					newTemp = heaterDevice.getFSmax();
+				else
+					newTemp = heaterDevice.getFSmin();
+				low = !low;
+				SimulationManager.scheduleEvent(new AbstractEvent(eventTime) {
+					
+					@Override
+					public void simulateEvent(long time) {
+						heaterDevice.setFSval(newTemp);
+						heaterDevice.setTrueTemperature(newTemp);
+					}
+				});
+				eventTime+=Math.max(1000, Math.round(tempDist.sample()));
+				
+			}
+			
+			System.out.println("Training:");//TODO
+			while(currentSimTime<endTime) {
+				sim.getSimulationManager().simulateTimeIntervall(currentSimTime, stepLength);
+				currentSimTime+=stepLength;
+			}
+			
+			long new_time = System.currentTimeMillis();
+			long elapsed_time = new_time-currentTime;
+			System.out.println("Training data generation took: "+elapsed_time+"ms");
+			currentTime = new_time;
+			
+			/*
+			 * Start Classifying 
+			 */
+			collectorKNNwithLabels.setMode(true);
+			collectorKNNnoLabels.setMode(true);
+			//collectorEM.setMode(true);
+			//collectorHC.setMode(true);
+			new_time = System.currentTimeMillis();
+			elapsed_time = new_time-currentTime;
+			System.out.println("Training of algorithm took: "+elapsed_time+"ms");
+			currentTime = new_time;
+			
+			
+			
+			/*
+			 * Simulate/Test 2 hour without anomalies
+			 */
+			snifferKNNwithLabels.setCurrentScenario("NoAnomalies");
+			snifferKNNnoLabels.setCurrentScenario("NoAnomalies");
+			System.out.println("Test w/0 anomalies:");//TODO
+			sim.getSimulationManager().simulateTimeIntervall(currentSimTime, noAnomEnd-currentSimTime);
+			currentSimTime=noAnomEnd;
+			
+			
+			new_time = System.currentTimeMillis();
+			elapsed_time = new_time-currentTime;
+			System.out.println("Test witout anomalies took: "+elapsed_time+"ms");
+			currentTime = new_time;
+			
+			
+			
+			/**
+			 * Temperature Anomaly 1h
+			 */
+			snifferKNNwithLabels.setCurrentScenario("TemperatureAnomalies");
+			snifferKNNnoLabels.setCurrentScenario("TemperatureAnomalies");
+			System.out.println("Temperature Anomaly:");
+			heaterDevice.setFSval(21f);
+			heaterDevice.setTrueTemperature(34f);
+			heaterDevice.setLabel((short)-1);//-1 Value anomaly			
+			
+			sim.getSimulationManager().simulateTimeIntervall(currentSimTime, heaterEnd-currentSimTime);
+			currentSimTime=heaterEnd;
+			
+			heaterDevice.setFSval(21f);
+			heaterDevice.setTrueTemperature(21f);
+			heaterDevice.setLabel((short)0);
+			
+			new_time = System.currentTimeMillis();
+			elapsed_time = new_time-currentTime;
+			System.out.println("Anomaly generation & classification: "+elapsed_time+"ms");
+			currentTime = new_time;
+			
+			System.out.println("Testing completed");
+		} catch(Exception e) {
+			System.out.println("WARNING: Testing failed: ");
+			e.printStackTrace();
+		}
+	}
+}

+ 287 - 0
src/main/java/de/tu_darmstadt/tk/SmartHomeNetworkSim/view/menuBar/HeaterScenarioFakeData.java

@@ -0,0 +1,287 @@
+package de.tu_darmstadt.tk.SmartHomeNetworkSim.view.menuBar;
+
+import org.apache.commons.math3.distribution.NormalDistribution;
+
+import de.tu_darmstadt.tk.SmartHomeNetworkSim.control.Controller;
+import de.tu_darmstadt.tk.SmartHomeNetworkSim.control.NetworkController;
+import de.tu_darmstadt.tk.SmartHomeNetworkSim.control.PacketCaptureController;
+import de.tu_darmstadt.tk.SmartHomeNetworkSim.control.SimulationController;
+import de.tu_darmstadt.tk.SmartHomeNetworkSim.core.Connection;
+import de.tu_darmstadt.tk.SmartHomeNetworkSim.core.ConnectionPrecision;
+import de.tu_darmstadt.tk.SmartHomeNetworkSim.core.Link;
+import de.tu_darmstadt.tk.SmartHomeNetworkSim.core.PacketCollector;
+import de.tu_darmstadt.tk.SmartHomeNetworkSim.core.Port;
+import de.tu_darmstadt.tk.SmartHomeNetworkSim.core.PrecisionLink;
+import de.tu_darmstadt.tk.SmartHomeNetworkSim.core.RoomStatus;
+import de.tu_darmstadt.tk.SmartHomeNetworkSim.core.SimulationManager;
+import de.tu_darmstadt.tk.SmartHomeNetworkSim.core.SmartDevice;
+import de.tu_darmstadt.tk.SmartHomeNetworkSim.core.devices.SmartLight;
+import de.tu_darmstadt.tk.SmartHomeNetworkSim.core.devices.SmartLightSensor;
+import de.tu_darmstadt.tk.SmartHomeNetworkSim.core.devices.SmartTemperatureProducer;
+import de.tu_darmstadt.tk.SmartHomeNetworkSim.core.devices.SmartTemperatureSensor;
+import de.tu_darmstadt.tk.SmartHomeNetworkSim.core.distributionHandler.NormalDistributionHandler;
+import de.tu_darmstadt.tk.SmartHomeNetworkSim.core.protocols.MQTT_protocol;
+import de.tu_darmstadt.tk.SmartHomeNetworkSim.core.scheduler.AbstractEvent;
+import de.tu_darmstadt.tk.SmartHomeNetworkSim.evaluation.SWCKMeansClustering;
+import de.tu_darmstadt.tk.SmartHomeNetworkSim.evaluation.SWCKMeansClusteringWithLabels;
+
+public class HeaterScenarioFakeData {
+
+	Controller controller;
+	NetworkController networkController;
+	public HeaterScenarioFakeData(Controller controller, NetworkController networkController) {
+		this.controller=controller;
+		this.networkController=networkController;
+	}
+	
+	/**
+	 * Creates the paper toy example, also simulates it, if run = true
+	 * @param run
+	 */
+	@SuppressWarnings("unchecked")
+	public void createSWCExample(boolean run){
+		/**
+		 * Reset network, etc.
+		 */
+
+		long hour = 60 * 60 * 1000;
+		long endTime = 24 * hour;
+		long noAnomEnd = endTime + 1 * hour;
+		long heaterEnd = noAnomEnd + 1 * hour;
+		long stepLength=hour;
+		long currentSimTime=0;
+		
+		SimulationController sim = controller.getSimulationController();
+		if(run) {
+			controller.getSimulationController().resetSimulation();
+			controller.getNetworkController().deleteNetworkModel();
+			/*
+			 * Simulate 24 hours
+			 */
+			sim.setStartTime(0);
+			sim.resetSimulation();
+			sim.setStepDuration(hour);
+			sim.setPrintPackets(false);
+			sim.setEndTime(endTime);
+		}
+		/*
+		 * Main networking devices 
+		 */
+		SmartDevice smartHub = networkController.createSmartDevice("SmartHub", 400, 400, 50);
+		
+		/*
+		 * Links/Networks
+		 */
+		Link zigbee = new PrecisionLink("ZigBee");
+		networkController.addLink(zigbee);
+		
+		/*
+		 * Connect Devices to Links
+		 */
+		networkController.addLinkToDevice(zigbee, smartHub);
+		
+		
+		/*
+		 * Create MQTT Connection
+		 */
+		Connection mqtt = new ConnectionPrecision();
+		mqtt.setName("HomeAutomation (MQTT)");
+		networkController.addConnectionToLink(mqtt, zigbee);
+		mqtt.setProtocol(new MQTT_protocol());
+		Port pBroker = new Port(smartHub, (short)1883);
+		pBroker.setStatus(Port.OPEN);
+		pBroker.setResponseTime((short)2);
+		networkController.addDeviceToConnectionAndProtocol(pBroker, mqtt, 0);
+		networkController.addConnection(mqtt);
+		mqtt.setLabel((short) 0);
+		
+		/**
+		 * Room
+		 */
+		String roomName = "Bedroom";
+		RoomStatus room = new RoomStatus();
+		room.setTemperature(19f);
+		/*
+		 * Add some MQTT Devices
+		 */
+		
+		/**
+		 * Room Thermostat
+		 */
+		SmartTemperatureSensor heatSensor = new SmartTemperatureSensor(roomName + " Thermostat", room);
+		heatSensor.setFSinfoName("home/" + roomName + "/sensorTemp");
+		networkController.addLinkToDevice(zigbee, heatSensor);
+		networkController.moveSmartDevice(heatSensor, 300, 300, 50);
+		heatSensor.setFSmin(19.0f);
+		heatSensor.setFSmax(21.0f);
+		heatSensor.setFSval(19.0f);
+		networkController.addSmartDevice(heatSensor);
+		Port pFloatSensor = new Port(heatSensor, (short)1883, 15000);
+		pFloatSensor.setTriggerHandler(new NormalDistributionHandler(15000, 500));
+		pFloatSensor.setStatus(Port.SENDING);
+		pFloatSensor.setLastTrigger(-357L);
+		networkController.addDeviceToConnectionAndProtocol(pFloatSensor, mqtt,1);
+		heatSensor.setLabel((short) 0);
+		/*
+		 * Add Heater (every second update)
+		 */
+		SmartTemperatureProducer heaterDevice = new SmartTemperatureProducer(roomName + " Heater", room, 500, heatSensor);
+		heaterDevice.setFSinfoName("home/" + roomName + "/heaterTemp");
+		networkController.addLinkToDevice(zigbee, heaterDevice);
+		networkController.moveSmartDevice(heaterDevice, 300, 500, 50);
+		heaterDevice.setFSmin(19.0f);
+		heaterDevice.setFSmax(21.0f);
+		heaterDevice.setFSval(19.0f);
+		networkController.addSmartDevice(heaterDevice);
+		Port pHeaterDevice = new Port(heaterDevice, (short)1883, 15000);
+		pHeaterDevice.setStatus(Port.SENDING);
+		pHeaterDevice.setTriggerHandler(new NormalDistributionHandler(15000, 500));
+		pHeaterDevice.setLastTrigger(-1231L);
+		networkController.addDeviceToConnectionAndProtocol(pHeaterDevice, mqtt,1);
+		heaterDevice.setLabel((short) 0);
+		
+		/* 
+		 * Update visualization 
+		 */
+		controller.notifyObservers();
+		
+		/**
+		 * Run only if run == true
+		 */
+		if(!run)return;
+		try {
+			System.out.println("Check 1");//TODO
+			/**
+			 * Instances of the packet Sniffers
+			 */
+			SWCKMeansClusteringWithLabels snifferKNNwithLabels = new SWCKMeansClusteringWithLabels();
+			SWCKMeansClustering snifferKNNnoLabels = new SWCKMeansClustering();
+
+
+			PacketCollector collectorKNNwithLabels = new PacketCollector(snifferKNNwithLabels);
+			PacketCollector collectorKNNnoLabels = new PacketCollector(snifferKNNnoLabels);
+			//PacketCollector collectorEM = new PacketCollector(snifferEM);
+			//PacketCollector collectorHC = new PacketCollector(snifferHC);
+			
+			/*
+			 * Capture both links on all collectors
+			 */
+			PacketCaptureController captureController = controller.getSimulationController().getPacketCaptureController();
+			//captureController.addLinkToCollector(collectorEM, zigbee);
+			//captureController.addLinkToCollector(collectorKNN, zigbee);
+			captureController.addDeviceToCollector(collectorKNNwithLabels, heaterDevice);
+			captureController.addPacketCollector(collectorKNNwithLabels);
+			captureController.addDeviceToCollector(collectorKNNnoLabels, heaterDevice);
+			captureController.addPacketCollector(collectorKNNnoLabels);
+			//captureController.addPacketCollector(collectorEM);
+			//captureController.addPacketCollector(collectorHC);
+
+			System.out.println("Check 3: created Controller");//TODO
+			
+			long currentTime = System.currentTimeMillis();
+			
+
+
+			/**
+			 * Training events
+			 */
+			System.out.println("Create training events");
+			/**
+			 * Heater Events (random switch every 2h +- 30min
+			 */
+			NormalDistribution tempDist = new NormalDistribution(2*hour, hour/2);
+			long eventTime = 0;
+			boolean low = true;
+			while(eventTime < noAnomEnd) {
+				/**
+				 * At least 1 second between events
+				 */
+				final float newTemp;
+				if(low)
+					newTemp = heaterDevice.getFSmax();
+				else
+					newTemp = heaterDevice.getFSmin();
+				low = !low;
+				SimulationManager.scheduleEvent(new AbstractEvent(eventTime) {
+					
+					@Override
+					public void simulateEvent(long time) {
+						heaterDevice.setFSval(newTemp);
+						heaterDevice.setTrueTemperature(newTemp);
+					}
+				});
+				eventTime+=Math.max(1000, Math.round(tempDist.sample()));
+				
+			}
+			
+			System.out.println("Training:");//TODO
+			while(currentSimTime<endTime) {
+				sim.getSimulationManager().simulateTimeIntervall(currentSimTime, stepLength);
+				currentSimTime+=stepLength;
+			}
+			
+			long new_time = System.currentTimeMillis();
+			long elapsed_time = new_time-currentTime;
+			System.out.println("Training data generation took: "+elapsed_time+"ms");
+			currentTime = new_time;
+			
+			/*
+			 * Start Classifying 
+			 */
+			collectorKNNwithLabels.setMode(true);
+			collectorKNNnoLabels.setMode(true);
+			//collectorEM.setMode(true);
+			//collectorHC.setMode(true);
+			new_time = System.currentTimeMillis();
+			elapsed_time = new_time-currentTime;
+			System.out.println("Training of algorithm took: "+elapsed_time+"ms");
+			currentTime = new_time;
+			
+			
+			
+			/*
+			 * Simulate/Test 2 hour without anomalies
+			 */
+			snifferKNNwithLabels.setCurrentScenario("NoAnomalies");
+			snifferKNNnoLabels.setCurrentScenario("NoAnomalies");
+			System.out.println("Test w/0 anomalies:");//TODO
+			sim.getSimulationManager().simulateTimeIntervall(currentSimTime, noAnomEnd-currentSimTime);
+			currentSimTime=noAnomEnd;
+			
+			
+			new_time = System.currentTimeMillis();
+			elapsed_time = new_time-currentTime;
+			System.out.println("Test witout anomalies took: "+elapsed_time+"ms");
+			currentTime = new_time;
+			
+			
+			
+			/**
+			 * Temperature Anomaly 1h
+			 */
+			snifferKNNwithLabels.setCurrentScenario("TemperatureAnomalies");
+			snifferKNNnoLabels.setCurrentScenario("TemperatureAnomalies");
+			System.out.println("Temperature Anomaly:");
+			heaterDevice.setFSval(34f);
+			heaterDevice.setTrueTemperature(21f);
+			heaterDevice.setLabel((short)-1);//-1 Value anomaly			
+			
+			sim.getSimulationManager().simulateTimeIntervall(currentSimTime, heaterEnd-currentSimTime);
+			currentSimTime=heaterEnd;
+			
+			heaterDevice.setFSval(21f);
+			heaterDevice.setTrueTemperature(21f);
+			heaterDevice.setLabel((short)0);
+			
+			new_time = System.currentTimeMillis();
+			elapsed_time = new_time-currentTime;
+			System.out.println("Anomaly generation & classification: "+elapsed_time+"ms");
+			currentTime = new_time;
+			
+			System.out.println("Testing completed");
+		} catch(Exception e) {
+			System.out.println("WARNING: Testing failed: ");
+			e.printStackTrace();
+		}
+	}
+}

+ 296 - 0
src/main/java/de/tu_darmstadt/tk/SmartHomeNetworkSim/view/menuBar/LightScenario.java

@@ -0,0 +1,296 @@
+package de.tu_darmstadt.tk.SmartHomeNetworkSim.view.menuBar;
+
+import org.apache.commons.math3.distribution.NormalDistribution;
+
+import de.tu_darmstadt.tk.SmartHomeNetworkSim.control.Controller;
+import de.tu_darmstadt.tk.SmartHomeNetworkSim.control.NetworkController;
+import de.tu_darmstadt.tk.SmartHomeNetworkSim.control.PacketCaptureController;
+import de.tu_darmstadt.tk.SmartHomeNetworkSim.control.SimulationController;
+import de.tu_darmstadt.tk.SmartHomeNetworkSim.core.Connection;
+import de.tu_darmstadt.tk.SmartHomeNetworkSim.core.ConnectionPrecision;
+import de.tu_darmstadt.tk.SmartHomeNetworkSim.core.Link;
+import de.tu_darmstadt.tk.SmartHomeNetworkSim.core.PacketCollector;
+import de.tu_darmstadt.tk.SmartHomeNetworkSim.core.Port;
+import de.tu_darmstadt.tk.SmartHomeNetworkSim.core.PrecisionLink;
+import de.tu_darmstadt.tk.SmartHomeNetworkSim.core.RoomStatus;
+import de.tu_darmstadt.tk.SmartHomeNetworkSim.core.SimulationManager;
+import de.tu_darmstadt.tk.SmartHomeNetworkSim.core.SmartDevice;
+import de.tu_darmstadt.tk.SmartHomeNetworkSim.core.devices.SmartLight;
+import de.tu_darmstadt.tk.SmartHomeNetworkSim.core.devices.SmartLightSensor;
+import de.tu_darmstadt.tk.SmartHomeNetworkSim.core.devices.SmartTemperatureProducer;
+import de.tu_darmstadt.tk.SmartHomeNetworkSim.core.devices.SmartTemperatureSensor;
+import de.tu_darmstadt.tk.SmartHomeNetworkSim.core.distributionHandler.NormalDistributionHandler;
+import de.tu_darmstadt.tk.SmartHomeNetworkSim.core.protocols.MQTT_protocol;
+import de.tu_darmstadt.tk.SmartHomeNetworkSim.core.scheduler.AbstractEvent;
+import de.tu_darmstadt.tk.SmartHomeNetworkSim.evaluation.SWCKMeansClustering;
+import de.tu_darmstadt.tk.SmartHomeNetworkSim.evaluation.SWCKMeansClusteringWithLabels;
+
+public class LightScenario {
+
+	Controller controller;
+	NetworkController networkController;
+	public LightScenario(Controller controller) {
+		this.controller=controller;
+		this.networkController=controller.getNetworkController();
+	}
+	
+	/**
+	 * Creates the paper toy example, also simulates it, if run = true
+	 * @param run
+	 */
+	@SuppressWarnings("unchecked")
+	public void createSWCExample(boolean run){
+		/**
+		 * Reset network, etc.
+		 */
+
+		long hour = 60 * 60 * 1000;
+		long endTime = 24 * hour;
+		long noAnomEnd = endTime + 1 * hour;
+		long lightEnd = noAnomEnd + 1 * hour;
+		long stepLength = hour;
+		long currentSimTime=0;
+		
+		SimulationController sim = controller.getSimulationController();
+		if(run) {
+			controller.getSimulationController().resetSimulation();
+			controller.getNetworkController().deleteNetworkModel();
+			/*
+			 * Simulate 24 hours
+			 */
+			sim.setStartTime(0);
+			sim.resetSimulation();
+			sim.setStepDuration(hour);
+			sim.setPrintPackets(false);
+			sim.setEndTime(endTime);
+		}
+		/*
+		 * Main networking devices 
+		 */
+		SmartDevice smartHub = networkController.createSmartDevice("SmartHub", 400, 400, 50);
+		
+		/*
+		 * Links/Networks
+		 */
+		Link zigbee = new PrecisionLink("ZigBee");
+		networkController.addLink(zigbee);
+		
+		/*
+		 * Connect Devices to Links
+		 */
+		networkController.addLinkToDevice(zigbee, smartHub);
+		
+		
+		/*
+		 * Create MQTT Connection
+		 */
+		Connection mqtt = new ConnectionPrecision();
+		mqtt.setName("HomeAutomation (MQTT)");
+		networkController.addConnectionToLink(mqtt, zigbee);
+		mqtt.setProtocol(new MQTT_protocol());
+		Port pBroker = new Port(smartHub, (short)1883);
+		pBroker.setStatus(Port.OPEN);
+		pBroker.setResponseTime((short)2);
+		networkController.addDeviceToConnectionAndProtocol(pBroker, mqtt, 0);
+		networkController.addConnection(mqtt);
+		mqtt.setLabel((short) 0);
+		
+		/**
+		 * Room
+		 */
+		String roomName = "Bedroom";
+		RoomStatus room = new RoomStatus();
+		room.setTemperature(19f);
+		/*
+		 * Add some MQTT Devices
+		 */
+		
+		/*
+		 * Add light Sensor
+		 */
+		SmartLightSensor lightSensor = new SmartLightSensor(roomName + " LightSensor", room, 1000);
+		lightSensor.setBSinfoName("home/" + roomName + "/light");
+		networkController.addLinkToDevice(zigbee, lightSensor);
+		networkController.moveSmartDevice(lightSensor, 500, 300, 50);
+		networkController.addSmartDevice(lightSensor);
+		Port pLightSensor = new Port(lightSensor, (short)1883, 15000);
+		pLightSensor.setTriggerHandler(new NormalDistributionHandler(15000, 500));
+		pLightSensor.setStatus(Port.SENDING);
+		pLightSensor.setLastTrigger(-1337L);
+		networkController.addDeviceToConnectionAndProtocol(pLightSensor, mqtt,1);
+		lightSensor.setLabel((short) 0);
+		
+		/*
+		 * Add a light
+		 */
+		SmartLight smartLight = new SmartLight(roomName + " Light", room, lightSensor);
+		smartLight.setBSinfoName("home/" + roomName + "/light");
+		networkController.addLinkToDevice(zigbee, smartLight);
+		networkController.moveSmartDevice(smartLight, 500, 500, 50);
+		networkController.addSmartDevice(smartLight);
+		Port pSmartLight = new Port(smartLight, (short)1883, 15000);
+		pSmartLight.setTriggerHandler(new NormalDistributionHandler(15000, 500));
+		pSmartLight.setStatus(Port.SENDING);
+		pSmartLight.setLastTrigger(-1207L);
+		networkController.addDeviceToConnectionAndProtocol(pSmartLight, mqtt,1);
+		smartLight.setLabel((short) 0);
+		
+		/* 
+		 * Update visualization 
+		 */
+		controller.notifyObservers();
+		
+		/**
+		 * Run only if run == true
+		 */
+		if(!run)return;
+		try {
+			System.out.println("Check 1");//TODO
+			/**
+			 * Instances of the packet Sniffers
+			 */
+			SWCKMeansClusteringWithLabels snifferKNNwithLabels = new SWCKMeansClusteringWithLabels();
+			SWCKMeansClustering snifferKNNnoLabels = new SWCKMeansClustering();
+
+
+			PacketCollector collectorKNNwithLabels = new PacketCollector(snifferKNNwithLabels);
+			PacketCollector collectorKNNnoLabels = new PacketCollector(snifferKNNnoLabels);
+			//PacketCollector collectorEM = new PacketCollector(snifferEM);
+			//PacketCollector collectorHC = new PacketCollector(snifferHC);
+			
+			/*
+			 * Capture both links on all collectors
+			 */
+			PacketCaptureController captureController = controller.getSimulationController().getPacketCaptureController();
+			//captureController.addLinkToCollector(collectorEM, zigbee);
+			//captureController.addLinkToCollector(collectorKNN, zigbee);
+			captureController.addDeviceToCollector(collectorKNNwithLabels, smartLight);
+			captureController.addPacketCollector(collectorKNNwithLabels);
+			captureController.addDeviceToCollector(collectorKNNnoLabels, smartLight);
+			captureController.addPacketCollector(collectorKNNnoLabels);
+			//captureController.addPacketCollector(collectorEM);
+			//captureController.addPacketCollector(collectorHC);
+
+			System.out.println("Check 3: created Controller");//TODO
+			
+			long currentTime = System.currentTimeMillis();
+			
+
+
+			/**
+			 * Training events
+			 */
+			System.out.println("Create training events");
+			/**
+			 * Light Events (random switch every 30min+-15min
+			 */
+			NormalDistribution lightDist = new NormalDistribution(hour/10, hour/20);
+			long eventTime = 0;
+			boolean on = true;
+			while(eventTime < noAnomEnd) {
+				/**
+				 * At least 1 second between events
+				 */
+				
+				final boolean newVal = on;
+				SimulationManager.scheduleEvent(new AbstractEvent(eventTime) {
+					
+					@Override
+					public void simulateEvent(long time) {
+						smartLight.setTrueStatus(newVal);
+						smartLight.setBSval(newVal);
+					}
+				});
+				on = !on;
+				eventTime+=Math.max(1000, Math.round(lightDist.sample()));
+				
+			}
+			
+			System.out.println("Training:");//TODO
+			while(currentSimTime<endTime) {
+				sim.getSimulationManager().simulateTimeIntervall(currentSimTime, stepLength);
+				currentSimTime+=stepLength;
+			}
+			
+			long new_time = System.currentTimeMillis();
+			long elapsed_time = new_time-currentTime;
+			System.out.println("Training data generation took: "+elapsed_time+"ms");
+			currentTime = new_time;
+			
+			/*
+			 * Start Classifying 
+			 */
+			collectorKNNwithLabels.setMode(true);
+			collectorKNNnoLabels.setMode(true);
+			//collectorEM.setMode(true);
+			//collectorHC.setMode(true);
+			new_time = System.currentTimeMillis();
+			elapsed_time = new_time-currentTime;
+			System.out.println("Training of algorithm took: "+elapsed_time+"ms");
+			currentTime = new_time;
+			
+			
+			
+			/*
+			 * Simulate/Test 2 hour without anomalies
+			 */
+			snifferKNNwithLabels.setCurrentScenario("NoAnomalies");
+			snifferKNNnoLabels.setCurrentScenario("NoAnomalies");
+			System.out.println("Test w/0 anomalies:");//TODO
+			sim.getSimulationManager().simulateTimeIntervall(currentSimTime, noAnomEnd-currentSimTime);
+			currentSimTime=noAnomEnd;
+			
+			
+			new_time = System.currentTimeMillis();
+			elapsed_time = new_time-currentTime;
+			System.out.println("Test witout anomalies took: "+elapsed_time+"ms");
+			currentTime = new_time;
+			
+			/**
+			 * Light Anomaly 1h
+			 * Light != Sensor
+			 */
+			snifferKNNwithLabels.setCurrentScenario("LightAnomalies");
+			snifferKNNnoLabels.setCurrentScenario("LightAnomalies");
+			System.out.println("Light Anomaly:");
+			eventTime = noAnomEnd;
+			on = true;
+			smartLight.setTrueStatus(false);
+			smartLight.setBSval(true);
+			while(eventTime < lightEnd) {
+				/**
+				 * At least 1 second between events
+				 */
+				
+				final boolean newVal = on;
+				SimulationManager.scheduleEvent(new AbstractEvent(eventTime) {
+					
+					@Override
+					public void simulateEvent(long time) {
+						smartLight.setTrueStatus(newVal);
+						smartLight.setBSval(!newVal);
+					}
+				});
+				on = !on;
+				eventTime+=Math.max(1000, Math.round(lightDist.sample()));
+				
+			}
+			smartLight.setLabel((short)-1);
+			sim.getSimulationManager().simulateTimeIntervall(currentSimTime, lightEnd-currentSimTime);
+			currentSimTime=lightEnd;
+
+			smartLight.setBSval(smartLight.isTrueStatus());
+			smartLight.setLabel((short)0);
+			
+			new_time = System.currentTimeMillis();
+			elapsed_time = new_time-currentTime;
+			System.out.println("Anomaly generation & classification: "+elapsed_time+"ms");
+			currentTime = new_time;
+			
+			System.out.println("Testing completed");
+		} catch(Exception e) {
+			System.out.println("WARNING: Testing failed: ");
+			e.printStackTrace();
+		}
+	}
+}

+ 2 - 2
src/main/java/de/tu_darmstadt/tk/SmartHomeNetworkSim/view/menuBar/MenuBarNetworkExamples.java

@@ -802,8 +802,8 @@ public class MenuBarNetworkExamples extends JMenu{
 		 */
 
 		long hour = 60 * 60 * 1000;
-		long endTime = 72*hour;
-		long noAnomEnd = endTime + 2 * hour;
+		long endTime = 24 * hour;
+		long noAnomEnd = endTime + 1 * hour;
 		long lightEnd = noAnomEnd + 1 * hour;
 		long tempEnd = lightEnd + 1 * hour;
 		long stepLength=hour;