001package jmri.jmrit.withrottle;
002
003import jmri.LocoAddress;
004import jmri.DccLocoAddress;
005import jmri.DccThrottle;
006import jmri.ThrottleListener;
007import jmri.jmrit.roster.RosterEntry;
008import org.slf4j.Logger;
009import org.slf4j.LoggerFactory;
010
011/**
012 *
013 * @author Brett Hoffman Copyright (C) 2010, 2011
014 */
015public class ConsistFunctionController implements ThrottleListener {
016
017    private DccThrottle throttle;
018    private RosterEntry rosterLoco = null;
019    private ThrottleController throttleController;
020
021    public ConsistFunctionController(ThrottleController tc) {
022        throttleController = tc;
023    }
024
025    public ConsistFunctionController(ThrottleController tc, RosterEntry re) {
026        throttleController = tc;
027        rosterLoco = re;
028    }
029
030    @Override
031    public void notifyThrottleFound(DccThrottle t) {
032        if (log.isDebugEnabled()) {
033            log.debug("Lead Loco throttle found: {}, for consist: {}", t, throttleController.getCurrentAddressString());
034        }
035        throttle = t;
036
037        if (rosterLoco == null) {
038            rosterLoco = throttleController.findRosterEntry(throttle);
039        }
040
041        throttleController.syncThrottleFunctions(throttle, rosterLoco);
042        throttleController.setFunctionThrottle(t);
043        throttleController.sendFunctionLabels(rosterLoco);
044        throttleController.sendAllFunctionStates(throttle);
045    }
046
047    @Override
048    public void notifyFailedThrottleRequest(LocoAddress address, String reason) {
049        log.error("Throttle request failed for {} because {}", address, reason);
050    }
051
052    /**
053     * No steal or share decisions made locally
054     */
055    @Override
056    public void notifyDecisionRequired(jmri.LocoAddress address, DecisionType question) {
057    }
058
059    public void dispose() {
060        jmri.InstanceManager.throttleManagerInstance().releaseThrottle(throttle, this);
061    }
062
063    public DccThrottle getThrottle() {
064        return throttle;
065    }
066
067    boolean requestThrottle(DccLocoAddress loco) {
068        return jmri.InstanceManager.throttleManagerInstance().requestThrottle(loco, this, true);
069    }
070
071    private final static Logger log = LoggerFactory.getLogger(ConsistFunctionController.class);
072
073}