001package jmri.jmrix.xpa;
002
003import jmri.JmriException;
004import jmri.PowerManager;
005import jmri.managers.AbstractPowerManager;
006
007/**
008 * PowerManager implementation for controlling layout power from an XPA+modem
009 * connected to an XpressNet based system.
010 *
011 * @author Paul Bender Copyright (C) 2004
012  *
013 */
014public class XpaPowerManager extends AbstractPowerManager<XpaSystemConnectionMemo> implements XpaListener {
015
016    XpaTrafficController tc;
017    boolean waiting = false;
018    int onReply = UNKNOWN;
019
020    public XpaPowerManager(XpaSystemConnectionMemo memo) {
021        super(memo);
022        // connect to the TrafficManager
023        tc = memo.getXpaTrafficController();
024        tc.addXpaListener(this);
025    }
026
027    @Override
028    public void setPower(int v) throws JmriException {
029        int old = power;
030        power = UNKNOWN; // while waiting for reply
031        checkTC();
032        if (v == ON) {
033            // configure to wait for reply
034            waiting = true;
035            onReply = PowerManager.ON;
036        } else if (v == OFF) {
037            // configure to wait for reply
038            waiting = true;
039            onReply = PowerManager.OFF;
040        }
041        // send "Emergency Off/Emergency Stop"
042        XpaMessage l = XpaMessage.getEStopMsg();
043        tc.sendXpaMessage(l, this);
044        firePowerPropertyChange(old, power);
045    }
046
047    // to free resources when no longer used
048    @Override
049    public void dispose() {
050        tc.removeXpaListener(this);
051        tc = null;
052    }
053
054    private void checkTC() throws JmriException {
055        if (tc == null) {
056            throw new JmriException("attempt to use XpaPowerManager after dispose");
057        }
058    }
059
060    // to listen for status changes from Xpa system
061    @Override
062    public void reply(XpaMessage m) {
063        if (waiting) {
064            int old = power;
065            power = onReply;
066            firePowerPropertyChange(old, power);
067        }
068        waiting = false;
069    }
070
071    @Override
072    public void message(XpaMessage m) {
073    }
074
075}