View Javadoc
1   package org.opentrafficsim.core.perception;
2   
3   import org.djunits.value.vdouble.scalar.Time;
4   import org.opentrafficsim.core.perception.AbstractHistorical.EventValue;
5   
6   import nl.tudelft.simulation.language.Throw;
7   
8   /**
9    * Single-valued historical state.
10   * <p>
11   * Copyright (c) 2013-2018 Delft University of Technology, PO Box 5, 2600 AA, Delft, the Netherlands. All rights reserved. <br>
12   * BSD-style license. See <a href="http://opentrafficsim.org/node/13">OpenTrafficSim License</a>.
13   * <p>
14   * @version $Revision$, $LastChangedDate$, by $Author$, initial version 1 jan. 2018 <br>
15   * @author <a href="http://www.tbm.tudelft.nl/averbraeck">Alexander Verbraeck</a>
16   * @author <a href="http://www.tudelft.nl/pknoppers">Peter Knoppers</a>
17   * @author <a href="http://www.transport.citg.tudelft.nl">Wouter Schakel</a>
18   * @param <T> value type
19   */
20  public class HistoricalValue<T> extends AbstractHistorical<T, EventValue<T>> implements Historical<T>
21  {
22  
23      /** Store last value for quick access. */
24      private T lastValue;
25  
26      /** Store last time for quick access. */
27      private double lastTime;
28  
29      /**
30       * Constructor.
31       * @param historyManager HistoryManager; history manager
32       */
33      public HistoricalValue(final HistoryManager historyManager)
34      {
35          super(historyManager);
36      }
37  
38      /**
39       * Constructor.
40       * @param historyManager HistoryManager; history manager
41       * @param initialValue T; initial value
42       */
43      public HistoricalValue(final HistoryManager historyManager, final T initialValue)
44      {
45          super(historyManager);
46          set(initialValue);
47      }
48  
49      /** {@inheritDoc} */
50      @Override
51      public final void set(final T value)
52      {
53          this.lastValue = value;
54          this.lastTime = now().si;
55          EventValue<T> event = getLastEvent();
56          if (event != null && event.getTime() == this.lastTime)
57          {
58              removeEvent(event);
59          }
60          addEvent(new EventValue<>(this.lastTime, value));
61      }
62  
63      /** {@inheritDoc} */
64      @Override
65      public final T get()
66      {
67          return this.lastValue;
68      }
69  
70      /** {@inheritDoc} */
71      @Override
72      public final T get(final Time time)
73      {
74          Throw.whenNull(time, "Time may not be null.");
75          if (time.si >= this.lastTime)
76          {
77              return this.lastValue;
78          }
79          EventValue<T> event = getEvent(time);
80          return event == null ? null : event.getValue();
81      }
82  
83      /** {@inheritDoc} */
84      @Override
85      public String toString()
86      {
87          return "HistoricalValue [current=" + get() + "]";
88      }
89  
90  }