001package jmri.jmrix.marklin;
002
003import jmri.JmriException;
004import jmri.managers.AbstractPowerManager;
005
006/**
007 * PowerManager implementation for controlling layout power.
008 *
009 * @author Kevin Dickerson (C) 2012
010 */
011public class MarklinPowerManager extends AbstractPowerManager<MarklinSystemConnectionMemo> implements MarklinListener {
012
013    private MarklinTrafficController tc;
014
015    public MarklinPowerManager(MarklinTrafficController etc) {
016        super(etc.adaptermemo);
017        // connect to the TrafficManager
018        tc = etc;
019        tc.addMarklinListener(MarklinPowerManager.this);
020
021    }
022
023    @Override
024    public void setPower(int v) throws JmriException {
025        int old = power;
026        power = UNKNOWN; // while waiting for reply
027        checkTC();
028        if (v == ON) {
029            // send message to turn on
030            MarklinMessage l = MarklinMessage.getEnableMain();
031            tc.sendMarklinMessage(l, this);
032        } else if (v == OFF) {
033            // send message to turn off
034            MarklinMessage l = MarklinMessage.getKillMain();
035            tc.sendMarklinMessage(l, this);
036        }
037        firePowerPropertyChange(old, power);
038    }
039
040    // to free resources when no longer used
041    @Override
042    public void dispose() throws JmriException {
043        tc.removeMarklinListener(this);
044        tc = null;
045    }
046
047    private void checkTC() throws JmriException {
048        if (tc == null) {
049            throw new JmriException("attempt to use MarklinPowerManager after dispose");
050        }
051    }
052
053    // to listen for status changes from Marklin system
054    @Override
055    public void reply(MarklinReply m) {
056        int old = power;
057        // power message?
058        if (m.getPriority() == MarklinConstants.PRIO_1
059            && m.getCommand() == MarklinConstants.SYSCOMMANDSTART && m.getAddress() == 0x0000) {
060            switch (m.getElement(9)) {
061                case MarklinConstants.CMDGOSYS:
062                    power = ON;
063                    break;
064                case MarklinConstants.CMDSTOPSYS:
065                case MarklinConstants.CMDHALTSYS:
066                    power = OFF;
067                    break;
068                default:
069                    log.warn("Unknown sub command {}", m.getElement(9));
070            }
071            firePowerPropertyChange(old, power);
072        }
073    }
074
075    @Override
076    public void message(MarklinMessage m) {
077        // messages are ignored
078    }
079
080    private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(MarklinPowerManager.class);
081
082}