001package jmri.jmrix.ecos;
002
003import jmri.JmriException;
004import jmri.managers.AbstractPowerManager;
005
006import org.slf4j.Logger;
007import org.slf4j.LoggerFactory;
008
009/**
010 * PowerManager implementation for controlling ECoS layout power.
011 *
012 * @author Bob Jacobsen Copyright (C) 2001, 2008
013 */
014public class EcosPowerManager extends AbstractPowerManager<EcosSystemConnectionMemo> implements EcosListener {
015
016    EcosTrafficController tc;
017
018    public EcosPowerManager(EcosTrafficController etc) {
019        super(etc.adaptermemo);
020        // connect to the TrafficManager
021        tc = etc;
022        tc.addEcosListener(this);
023
024        // ask to be notified
025        EcosMessage m = new EcosMessage("request(1, view)");
026        tc.sendEcosMessage(m, this);
027
028        // get initial state
029        m = new EcosMessage("get(1, status)");
030        tc.sendEcosMessage(m, this);
031
032    }
033
034    @Override
035    public void setPower(int v) throws JmriException {
036        int old = power;
037        power = UNKNOWN; // while waiting for reply
038        checkTC();
039        if (v == ON) {
040            // send message to turn on
041            EcosMessage l = new EcosMessage("set(1, go)");
042            tc.sendEcosMessage(l, this);
043        } else if (v == OFF) {
044            // send message to turn off
045            EcosMessage l = new EcosMessage("set(1, stop)");
046            tc.sendEcosMessage(l, this);
047        }
048        firePowerPropertyChange(old, power);
049    }
050
051    // to free resources when no longer used
052    @Override
053    public void dispose() throws JmriException {
054        tc.removeEcosListener(this);
055        tc = null;
056    }
057
058    private void checkTC() throws JmriException {
059        if (tc == null) {
060            throw new JmriException("attempt to use EcosPowerManager after dispose");
061        }
062    }
063
064    // to listen for status changes from Ecos system
065    @Override
066    public void reply(EcosReply m) {
067        // power message?
068        String msg = m.toString();
069        if (msg.contains("<EVENT 1>") || msg.contains("REPLY get(1,") || msg.contains("REPLY set(1,")) {
070            int old = power;
071            if (msg.contains("status[GO]") || msg.contains("et(1, go)")) {
072                log.debug("POWER ON DETECTED");
073                power = ON;
074            } else if (msg.contains("status[STOP]") || msg.contains("et(1, stop)")) {
075                log.debug("POWER OFF DETECTED");
076                power = OFF;
077            }
078            firePowerPropertyChange(old, power);
079        }
080    }
081
082    @Override
083    public void message(EcosMessage m) {
084        // messages are ignored
085    }
086
087    private final static Logger log = LoggerFactory.getLogger(EcosPowerManager.class);
088
089}