001package jmri.jmris.srcp;
002
003import java.io.IOException;
004import java.io.OutputStream;
005
006import jmri.PowerManager;
007import jmri.jmris.AbstractPowerServer;
008import org.slf4j.Logger;
009import org.slf4j.LoggerFactory;
010
011/**
012 * SRCP interface between the JMRI power manager and a network connection
013 *
014 * @author Paul Bender Copyright (C) 2010
015 */
016public class JmriSRCPPowerServer extends AbstractPowerServer {
017
018    private OutputStream output;
019
020    public JmriSRCPPowerServer(OutputStream outStream) {
021        super();
022        output = outStream;
023        mgrOK();
024    }
025
026
027    /*
028     * Protocol Specific Abstract Functions
029     */
030    @Override
031    public void sendStatus(int Status) throws IOException {
032        if (Status == PowerManager.ON) {
033            output.write("100 INFO 0 POWER ON\n\r".getBytes());
034        } else if (Status == PowerManager.OFF) {
035            output.write("100 INFO 0 POWER OFF\n\r".getBytes());
036        } else {
037            // power unknown
038            output.write("411 ERROR unknown value\n\r".getBytes());
039        }
040    }
041
042    @Override
043    public void sendErrorStatus() throws IOException {
044        output.write("499 ERROR unspecified error\n\r".getBytes());
045    }
046
047    @Override
048    public void parseStatus(String statusString) throws jmri.JmriException {
049        if (statusString.contains("ON")) {
050            if (log.isDebugEnabled()) {
051                log.debug("Setting Power ON");
052            }
053            setOnStatus();
054        } else if (statusString.contains("OFF")) {
055            if (log.isDebugEnabled()) {
056                log.debug("Setting Power OFF");
057            }
058            setOffStatus();
059        }
060    }
061
062    @Override
063    public void propertyChange(java.beans.PropertyChangeEvent ev) {
064        try {
065            // send updates, but only if the status is ON or OFF.
066            if (p.getPower() == PowerManager.ON || p.getPower() == PowerManager.OFF) {
067                sendStatus(p.getPower());
068            }
069        } catch (IOException ie2) {
070            // silently ignore
071        }
072    }
073    private static final Logger log = LoggerFactory.getLogger(JmriSRCPPowerServer.class);
074
075}