001package jmri.jmrix.openlcb.swing;
002
003import java.util.TimerTask;
004import javax.swing.JLabel;
005
006import jmri.jmrix.can.CanListener;
007import jmri.jmrix.can.CanMessage;
008import jmri.jmrix.can.CanReply;
009import jmri.jmrix.can.CanSystemConnectionMemo;
010import jmri.util.TimerUtil;
011
012/**
013 * A JLabel that displays whether a LCC/OpenLCB connection
014 * is currently active or not by making the word "Active"
015 * dark (enabled) or light (disabled).
016 *
017 * @author Bob Jacobsen
018 */
019public class TrafficStatusLabel extends JLabel implements CanListener {
020    
021    private static final int INTERVAL = 200;
022    final CanSystemConnectionMemo memo;
023    
024    TimerTask timertask;
025
026    boolean active;
027    
028    public TrafficStatusLabel(CanSystemConnectionMemo memo) {
029        super("Active");
030        this.setEnabled(false);
031        this.memo = memo;
032        
033        // set up traffic listener
034        memo.getTrafficController().addCanConsoleListener(this);
035        
036        // start the process
037        this.active = false;
038        setEnabled(false);
039    }
040    
041    TimerTask getNewTimerTask() {
042        return new TimerTask() {
043            @Override
044            public void run() {
045                active = false;
046                displayActive(); 
047            }
048        };
049    }
050    
051    void traffic() {
052        if (timertask != null) {
053            timertask.cancel();
054            timertask = null;
055        }
056        active = true;
057        displayActive();
058        if (active) {
059            timertask = TimerUtil.scheduleOnGUIThread(getNewTimerTask(), INTERVAL); // return value kept for cancel
060        }
061        
062    }
063
064    void displayActive() {
065        if (active != isEnabled()) {
066            setEnabled(active); // `if` reduces redisplays 
067        }
068    }
069    
070    @Override
071    public synchronized void message(CanMessage l) {
072        traffic();
073    }
074
075    @Override
076    public synchronized void reply(CanReply l) { 
077        traffic();
078    }
079    
080    //private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(TrafficStatusLabel.class);
081}