001package jmri.jmrix.easydcc;
002
003import jmri.JmriException;
004import jmri.PowerManager;
005import jmri.managers.AbstractPowerManager;
006
007/**
008 * PowerManager implementation for controlling layout power
009 *
010 * @author Bob Jacobsen Copyright (C) 2001
011 */
012public class EasyDccPowerManager extends AbstractPowerManager<EasyDccSystemConnectionMemo> implements EasyDccListener {
013
014    private EasyDccTrafficController trafficController = null;
015    boolean waiting = false;
016    int onReply = UNKNOWN;
017
018    public EasyDccPowerManager(EasyDccSystemConnectionMemo memo) {
019        super(memo);
020        // connect to the TrafficManager
021        trafficController = memo.getTrafficController();
022        trafficController.addEasyDccListener(this);
023    }
024
025    @Override
026    public void setPower(int v) throws JmriException {
027        int old = power;
028        power = UNKNOWN; // while waiting for reply
029        checkTC();
030        if (v == ON) {
031            // configure to wait for reply
032            waiting = true;
033            onReply = PowerManager.ON;
034            // send "Enable main track"
035            EasyDccMessage l = EasyDccMessage.getEnableMain();
036            trafficController.sendEasyDccMessage(l, this);
037        } else if (v == OFF) {
038            // configure to wait for reply
039            waiting = true;
040            onReply = PowerManager.OFF;
041            // send "Kill main track"
042            EasyDccMessage l = EasyDccMessage.getKillMain();
043            trafficController.sendEasyDccMessage(l, this);
044        }
045        firePowerPropertyChange(old, power);
046    }
047
048    // to free resources when no longer used
049    @Override
050    public void dispose() throws JmriException {
051        trafficController.removeEasyDccListener(this);
052        trafficController = null;
053    }
054
055    private void checkTC() throws JmriException {
056        if (trafficController == null) {
057            throw new JmriException("attempt to use EasyDccPowerManager after dispose");
058        }
059    }
060
061    // to listen for status changes from EasyDcc system
062    @Override
063    public void reply(EasyDccReply m) {
064        int old = power;
065        if (waiting) {
066            power = onReply;
067            firePowerPropertyChange(old, power); // NOI18N
068        }
069        waiting = false;
070    }
071
072    @Override
073    public void message(EasyDccMessage m) {
074        if (m.isKillMain()) {
075            // configure to wait for reply
076            waiting = true;
077            onReply = PowerManager.OFF;
078        } else if (m.isEnableMain()) {
079            // configure to wait for reply
080            waiting = true;
081            onReply = PowerManager.ON;
082        }
083    }
084
085}