001package jmri.jmrix.roco.z21;
002
003/**
004 * Z21 specific class to send heartbeat messages to
005 * the Z21.  Heartbeat messages are only required if
006 * no other messages are sent for a specific period
007 * of time, so any outgoing message should restart
008 * the timer.
009 *
010 * @author Paul Bender Copyright (C) 2019 
011 */
012public class Z21HeartBeat implements Z21Listener {
013
014    private javax.swing.Timer keepAliveTimer; // Timer used to periodically
015    // send a message to both
016    // ports to keep the ports
017    // open
018    private static final int keepAliveTimeoutValue = 30000; // Interval
019    // to send a message
020    // Must be < 60s.
021    private Z21TrafficController tc;
022
023    public Z21HeartBeat(Z21SystemConnectionMemo memo) {
024        tc = memo.getTrafficController();
025        tc.addz21Listener(this);
026        keepAliveTimer();
027    }
028
029    /*
030     * Set up the keepAliveTimer, and start it.
031     */
032    private void keepAliveTimer() {
033        if (keepAliveTimer == null) {
034            keepAliveTimer = new javax.swing.Timer(keepAliveTimeoutValue, e -> {
035                // If the timer times out, send a request for status
036                tc.sendz21Message(
037                   Z21Message.getSerialNumberRequestMessage(),
038                   null);
039            });
040        }
041        keepAliveTimer.stop();
042        keepAliveTimer.setInitialDelay(keepAliveTimeoutValue);
043        keepAliveTimer.setRepeats(true);
044        keepAliveTimer.start();
045    }
046
047    public void dispose(){
048       if (keepAliveTimer != null) {
049           keepAliveTimer.stop();
050       }
051       keepAliveTimer = null;
052    }
053
054    // Z21Listener methods.
055
056    /**
057     * {@inheritDoc}
058     */
059    @Override
060    public void reply(Z21Reply msg){
061        // this class doesn't care about incoming messages.
062    }
063
064    /**
065     * {@inheritDoc}
066     */
067    @Override
068    public void message(Z21Message msg){
069       if(keepAliveTimer!=null) { 
070          // if we see any outgoing message, restart the timer
071          keepAliveTimer.restart();
072       }
073    }
074
075}