001package jmri.jmris.simpleserver;
002
003import java.io.DataInputStream;
004import java.io.DataOutputStream;
005import java.io.IOException;
006import jmri.PowerManager;
007import jmri.jmris.AbstractPowerServer;
008import jmri.jmris.JmriConnection;
009import jmri.jmris.simpleserver.parser.JmriServerParser;
010import jmri.jmris.simpleserver.parser.ParseException;
011import jmri.jmris.simpleserver.parser.SimpleNode;
012import jmri.jmris.simpleserver.parser.SimpleVisitor;
013import jmri.jmris.simpleserver.parser.TokenMgrError;
014
015/**
016 * Simple Server interface between the JMRI power manager and a network
017 * connection
018 *
019 * @author Paul Bender Copyright (C) 2010
020 */
021public class SimplePowerServer extends AbstractPowerServer {
022
023    private DataOutputStream output;
024    private JmriConnection connection;
025    public SimplePowerServer(DataInputStream inStream, DataOutputStream outStream) {
026        output = outStream;
027        mgrOK();
028    }
029
030    public SimplePowerServer(JmriConnection cnctn) {
031        this.connection = cnctn;
032        mgrOK();
033    }
034
035    /*
036     * Protocol Specific Abstract Functions
037     */
038    @Override
039    public void sendStatus(int Status) throws IOException {
040        switch (Status) {
041            case PowerManager.ON:
042                this.sendStatus("POWER ON\n");
043                break;
044            case PowerManager.OFF:
045                this.sendStatus("POWER OFF\n");
046                break;
047            default:
048                this.sendStatus("POWER UNKNOWN\n");
049                break;
050        }
051    }
052
053    @Override
054    public void sendErrorStatus() throws IOException {
055        this.sendStatus("POWER ERROR\n");
056    }
057
058    @Override
059    public void parseStatus(String statusString) throws jmri.JmriException {
060        JmriServerParser p = new JmriServerParser(new java.io.StringReader(statusString));
061        try{
062           try{
063              SimpleNode e=p.powercmd();
064              SimpleVisitor v = new SimpleVisitor();
065              e.jjtAccept(v,this);
066              if(v.getOutputString() != null ){
067                 sendStatus(v.getOutputString());
068              } 
069           } catch(ParseException | TokenMgrError pe){
070              sendErrorStatus();
071           }
072        } catch(IOException ioe) {
073          // we should check to see if there is an  
074        }
075    }
076
077    public void sendStatus(String status) throws IOException {
078        if (this.output != null) {
079            this.output.writeBytes(status);
080        } else {
081            this.connection.sendMessage(status);
082        }
083    }
084}