summaryrefslogtreecommitdiff
path: root/branches/sm-unittesting/src/org/reprap/comms/port/TestPortHandler.java
blob: 71d7d46aa665a33abc22093c36c3b2d82b5c3f8c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
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;
	}
}