001package jmri.jmris.simpleserver;
002
003import java.io.DataInputStream;
004import java.io.DataOutputStream;
005import java.io.IOException;
006import jmri.JmriException;
007import jmri.Light;
008import jmri.jmris.AbstractLightServer;
009import jmri.jmris.JmriConnection;
010
011/**
012 * Simple Server interface between the JMRI light manager and a network
013 * connection
014 *
015 * @author Paul Bender Copyright (C) 2010
016 */
017public class SimpleLightServer extends AbstractLightServer {
018
019    private static final String LIGHT = "LIGHT";
020    private DataOutputStream output = null;
021    private JmriConnection connection = null;
022
023    public SimpleLightServer(JmriConnection connection) {
024        this.connection = connection;
025    }
026
027    public SimpleLightServer(DataInputStream inStream, DataOutputStream outStream) {
028
029        output = outStream;
030    }
031
032
033    /*
034     * Protocol Specific Abstract Functions
035     */
036    @Override
037    public void sendStatus(String lightName, int Status) throws IOException {
038        switch (Status) {
039            case Light.ON:
040                this.sendMessage(LIGHT + " " + lightName + " ON\n");
041                break;
042            case Light.OFF:
043                this.sendMessage(LIGHT + " " + lightName + " OFF\n");
044                break;
045            default: //  unknown state
046                this.sendMessage(LIGHT + " " + lightName + " UNKNOWN\n");
047                break;
048        }
049    }
050
051    @Override
052    public void sendErrorStatus(String lightName) throws IOException {
053        this.sendMessage(LIGHT + " ERROR\n");
054    }
055
056    @Override
057    public void parseStatus(String statusString) throws JmriException, IOException {
058        int index;
059        index = statusString.indexOf(' ') + 1;
060        if (statusString.contains("ON")) {
061            log.debug("Setting Light ON");
062            initLight(statusString.substring(index, statusString.indexOf(' ', index + 1)));
063            lightOn(statusString.substring(index, statusString.indexOf(' ', index + 1)));
064        } else if (statusString.contains("OFF")) {
065            log.debug("Setting Light OFF");
066            initLight(statusString.substring(index, statusString.indexOf(' ', index + 1)));
067            lightOff(statusString.substring(index, statusString.indexOf(' ', index + 1)));
068        }
069    }
070
071    private void sendMessage(String message) throws IOException {
072        if (this.output != null) {
073            this.output.writeBytes(message);
074        } else {
075            this.connection.sendMessage(message);
076        }
077    }
078
079    private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(SimpleLightServer.class);
080}