001package jmri.jmrix.nce; 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 NcePowerManager extends AbstractPowerManager<NceSystemConnectionMemo> implements NceListener { 013 014 public NcePowerManager(NceSystemConnectionMemo memo) { 015 this(memo.getNceTrafficController(), memo.getSystemPrefix());// connect to the TrafficManager 016 } 017 018 public NcePowerManager(NceTrafficController tc, String p) { 019 super(tc.getAdapterMemo()); 020 // connect to the TrafficManager 021 this.tc = tc; 022 tc.addNceListener(this); 023 } 024 025 boolean waiting = false; 026 int onReply = UNKNOWN; 027 028 @Override 029 public void setPower(int v) throws JmriException { 030 int old = power; 031 power = UNKNOWN; // while waiting for reply 032 checkTC(); 033 if (v == ON) { 034 // configure to wait for reply 035 waiting = true; 036 onReply = PowerManager.ON; 037 // send "Enable main track" 038 NceMessage l = NceMessage.getEnableMain(tc); 039 tc.sendNceMessage(l, this); 040 } else if (v == OFF) { 041 // configure to wait for reply 042 waiting = true; 043 onReply = PowerManager.OFF; 044 firePowerPropertyChange(old, power); 045 // send "Kill main track" 046 NceMessage l = NceMessage.getKillMain(tc); 047 tc.sendNceMessage(l, this); 048 } 049 firePowerPropertyChange(old, power); 050 } 051 052 // to free resources when no longer used 053 @Override 054 public void dispose() throws JmriException { 055 tc.removeNceListener(this); 056 tc = null; 057 } 058 059 private void checkTC() throws JmriException { 060 if (tc == null) { 061 throw new JmriException("attempt to use NcePowerManager after dispose"); 062 } 063 } 064 065 NceTrafficController tc = null; 066 067 // to listen for status changes from NCE system 068 @Override 069 public void reply(NceReply m) { 070 if (waiting) { 071 int old = power; 072 power = onReply; 073 firePowerPropertyChange(old, power); 074 } 075 waiting = false; 076 } 077 078 @Override 079 public void message(NceMessage m) { 080 if (m.isKillMain()) { 081 // configure to wait for reply 082 waiting = true; 083 onReply = PowerManager.OFF; 084 } else if (m.isEnableMain()) { 085 // configure to wait for reply 086 waiting = true; 087 onReply = PowerManager.ON; 088 } 089 } 090 091} 092 093 094