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