package org.reprap.comms.port; import java.io.PipedInputStream; import java.io.PipedOutputStream; import java.util.HashMap; import org.reprap.comms.port.testhandlers.TestDevice; import org.reprap.comms.snap.SNAPAddress; import org.reprap.comms.snap.SNAPPacket; public class TestPortHandler { /// A map of address to TestDevice HashMap deviceMap = new HashMap(); PipedInputStream in; PipedOutputStream out; boolean dropNextIncomingPacketFlag = false; public TestPortHandler(PipedInputStream in, PipedOutputStream out) { this.in = in; this.out = out; } /** * Register a device to receive messages. This should *only* be called * prior to sending the first messages because the HashMap is not * thread safe. * @param address * @param device */ public void registerDevice(SNAPAddress address, TestDevice device) { deviceMap.put(address, device); } public void watch() { SNAPPacket packet = new SNAPPacket(); for(;;) { try { int data = in.read(); if (packet.receiveByte((byte)data)) { // Process a packet and prepare for a new one if (!dropNextIncomingPacketFlag) processPacket(packet); packet = new SNAPPacket(); dropNextIncomingPacketFlag = false; } } catch(Exception ex) { System.out.println("PIC side simulator exception: " + ex); } } } private void processPacket(SNAPPacket packet) throws Exception { SNAPAddress dest = packet.getDestinationAddress(); if (!deviceMap.containsKey(dest)) throw new Exception("Packet sent to non-existent device " + dest.getAddress()); TestDevice device = (TestDevice)deviceMap.get(dest); System.out.println("Packet to " + packet.getDestinationAddress() + " type " + (int)packet.getPayload()[0]); // Send an ACK back first SNAPPacket ack = packet.generateACK(); out.write(ack.getRawData()); out.flush(); // Pass on to device device.receivePacket(out, packet); } public void dropNextIncomingPacket() { dropNextIncomingPacketFlag = true; } }