001package jmri.jmris.simpleserver;
002
003import java.io.DataInputStream;
004import java.io.DataOutputStream;
005import java.io.IOException;
006
007import jmri.InstanceManager;
008import jmri.JmriException;
009import jmri.SignalHead;
010import jmri.jmris.AbstractSignalHeadServer;
011import jmri.jmris.JmriConnection;
012
013/**
014 * Simple Server interface between the JMRI Sensor manager and a network
015 * connection
016 *
017 * @author Paul Bender Copyright (C) 2010
018 */
019public class SimpleSignalHeadServer extends AbstractSignalHeadServer {
020
021    private DataOutputStream output;
022    private JmriConnection connection;
023
024    public SimpleSignalHeadServer(JmriConnection connection) {
025        super();
026        this.connection = connection;
027    }
028
029    public SimpleSignalHeadServer(DataInputStream inStream, DataOutputStream outStream){
030        super();
031        output = outStream;
032    }
033
034    /*
035     * Protocol Specific Abstract Functions
036     */
037    @Override
038    public void sendStatus(String signalHeadName, int Status) throws IOException {
039        this.addSignalHeadToList(signalHeadName);
040        this.sendMessage("SIGNALHEAD " + signalHeadName + " " + this.nameForAppearance(Status) + "\n");
041    }
042
043    @Override
044    public void sendErrorStatus(String signalHeadName) throws IOException {
045        this.sendMessage("SIGNALHEAD ERROR\n");
046    }
047
048    @Override
049    public void parseStatus(String statusString) throws JmriException, IOException {
050        String[] status = statusString.split("\\s+");
051        if (status.length == 3) {
052            this.setSignalHeadAppearance(status[1], status[2]);
053        } else {
054            SignalHead signalHead = InstanceManager.getDefault(jmri.SignalHeadManager.class).getSignalHead(status[1]);
055            if(signalHead != null) {
056               this.sendStatus(signalHead.getSystemName(), signalHead.getAppearance());
057            } else {
058               sendErrorStatus(status[1]);
059            }
060        }
061    }
062
063    private void sendMessage(String message) throws IOException {
064        if (this.output != null) {
065            this.output.writeBytes(message);
066        } else {
067            this.connection.sendMessage(message);
068        }
069    }
070}