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