Commit 9111f4a5 authored by MarkG's avatar MarkG Committed by TIGERs GitLab
Browse files

Resolve "More robust ongoing pass detection with external simulator"

Closes #1634

See merge request main/Sumatra!1378

sumatra-commit: 751c2818f700677f57d54e8d056df4b8c8cc1a6c
parent abab79dd
Pipeline #16700 passed with stage
in 5 minutes and 38 seconds
/*
* Copyright (c) 2009 - 2021, DHBW Mannheim - TIGERs Mannheim
*/
package edu.tigers.sumatra.data;
import lombok.Setter;
import lombok.Value;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
/**
* A time-based buffer that removes the oldest elements based on duration and size.
*
* @param <T> the type of the buffered value.
*/
public class TimeLimitedBuffer<T>
{
private final List<Entry<T>> data = new ArrayList<>();
@Setter
private int maxElements;
@Setter
private double maxDuration;
/**
* Add a new entry and reduce the buffer, if required.
*
* @param timestamp
* @param value
*/
public void add(long timestamp, T value)
{
data.add(new Entry<>(timestamp, value));
Collections.sort(data);
reduceBySize();
reduceByDuration();
}
/**
* @return the current list of stored elements.
*/
public List<T> getElements()
{
return data.stream().map(Entry::getValue).collect(Collectors.toUnmodifiableList());
}
public Optional<T> getLatest()
{
return data.stream().skip(data.size() - 1L).map(Entry::getValue).findAny();
}
public Optional<T> getOldest()
{
return data.stream().map(Entry::getValue).findFirst();
}
private void reduceBySize()
{
if (maxElements <= 0)
{
// No size limit
return;
}
while (data.size() > maxElements)
{
data.remove(0);
}
}
private void reduceByDuration()
{
if (maxDuration <= 0 || data.isEmpty())
{
// no duration limit
return;
}
long maxTimestamp = data.get(data.size() - 1).timestamp;
long minTimestamp = maxTimestamp - (long) (maxDuration * 1e9);
while (!data.isEmpty() && data.get(0).timestamp < minTimestamp)
{
data.remove(0);
}
}
@Value
private static class Entry<T> implements Comparable<Entry<T>>
{
long timestamp;
T value;
@Override
public int compareTo(Entry<T> o)
{
return Long.compare(timestamp, o.timestamp);
}
}
}
/*
* Copyright (c) 2009 - 2018, DHBW Mannheim - TIGERs Mannheim
* Copyright (c) 2009 - 2021, DHBW Mannheim - TIGERs Mannheim
*/
package edu.tigers.sumatra.data;
......@@ -68,11 +68,7 @@ public class TimestampBasedBuffer<T extends ITimestampBased>
public Optional<T> getOldest()
{
if (buffer.isEmpty())
{
return Optional.empty();
}
return Optional.of(buffer.get(0));
return buffer.stream().findFirst();
}
......@@ -82,6 +78,6 @@ public class TimestampBasedBuffer<T extends ITimestampBased>
{
return Optional.empty();
}
return Optional.of(buffer.get(buffer.size()));
return Optional.of(buffer.get(buffer.size() - 1));
}
}
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment