001package jmri.jmrit.operations.automation.actions; 002 003import java.beans.PropertyChangeEvent; 004import java.beans.PropertyChangeListener; 005import jmri.jmrit.operations.routes.RouteLocation; 006import jmri.jmrit.operations.setup.Control; 007import jmri.jmrit.operations.trains.Train; 008import org.slf4j.Logger; 009import org.slf4j.LoggerFactory; 010 011public class WaitTrainAction extends Action implements PropertyChangeListener { 012 013 private static final int _code = ActionCodes.WAIT_FOR_TRAIN; 014 015 @Override 016 public int getCode() { 017 return _code; 018 } 019 020 @Override 021 public String getName() { 022 return Bundle.getMessage("WaitForTrain"); 023 } 024 025 @Override 026 public boolean isConcurrentAction() { 027 return true; 028 } 029 030 @Override 031 public void doAction() { 032 if (getAutomationItem() != null) { 033 Train train = getAutomationItem().getTrain(); 034 if (train != null && train.getRoute() != null) { 035 setRunning(true); 036 train.addPropertyChangeListener(this); 037 } else { 038 finishAction(false); 039 } 040 } 041 } 042 043 /** 044 * Wait for train to build and no location, or train to arrive at location, 045 * or train build to be deselected. 046 * 047 */ 048 private void trainUpdate(PropertyChangeEvent evt) { 049 if (getAutomationItem() != null) { 050 if (evt.getPropertyName().equals(Train.TRAIN_MOVE_COMPLETE_CHANGED_PROPERTY) || 051 (evt.getPropertyName().equals(Train.BUILT_CHANGED_PROPERTY) 052 && (boolean) evt.getNewValue() == true)) { 053 Train train = getAutomationItem().getTrain(); 054 RouteLocation rl = getAutomationItem().getRouteLocation(); 055 if (rl != null && rl != train.getCurrentRouteLocation()) { 056 return; // haven't reached this location continue waiting 057 } 058 train.removePropertyChangeListener(this); 059 finishAction(true); 060 } else if (evt.getPropertyName().equals(Train.BUILD_CHANGED_PROPERTY) 061 && (boolean) evt.getNewValue() == false) { 062 Train train = getAutomationItem().getTrain(); 063 train.removePropertyChangeListener(this); 064 finishAction(true); 065 } 066 } 067 } 068 069 @Override 070 public void cancelAction() { 071 if (getAutomationItem() != null) { 072 setRunning(false); 073 Train train = getAutomationItem().getTrain(); 074 if (train != null) { 075 train.removePropertyChangeListener(this); 076 } 077 } 078 } 079 080 @Override 081 public void propertyChange(PropertyChangeEvent evt) { 082 if (Control.SHOW_PROPERTY) 083 log.debug("Property change AutomationItem {}: ({}) old: ({}) new: ({})", getAutomationItem().getId(), 084 evt.getPropertyName(), evt.getOldValue(), evt.getNewValue()); 085 trainUpdate(evt); 086 } 087 088 private final static Logger log = LoggerFactory.getLogger(WaitTrainAction.class); 089 090}